trace: Support output of a flamegraph
[platform/kernel/u-boot.git] / tools / proftool.c
1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3  * Copyright 2023 Google LLC
4  * Written by Simon Glass <sjg@chromium.org>
5  */
6
7 /*
8  * Decode and dump U-Boot trace information into formats that can be used
9  * by trace-cmd, kernelshark or flamegraph.pl
10  *
11  * See doc/develop/trace.rst for more information
12  */
13
14 #include <assert.h>
15 #include <ctype.h>
16 #include <limits.h>
17 #include <regex.h>
18 #include <stdarg.h>
19 #include <stdio.h>
20 #include <stdlib.h>
21 #include <string.h>
22 #include <unistd.h>
23 #include <sys/param.h>
24 #include <sys/types.h>
25
26 #include <compiler.h>
27 #include <trace.h>
28 #include <abuf.h>
29
30 #include <linux/list.h>
31
32 /* Set to 1 to emit version 7 file (currently this doesn't work) */
33 #define VERSION7        0
34
35 /* enable some debug features */
36 #define _DEBUG  0
37
38 /* from linux/kernel.h */
39 #define __ALIGN_MASK(x, mask)   (((x) + (mask)) & ~(mask))
40 #define ALIGN(x, a)             __ALIGN_MASK((x), (typeof(x))(a) - 1)
41
42 /**
43  * container_of - cast a member of a structure out to the containing structure
44  * @ptr:        the pointer to the member.
45  * @type:       the type of the container struct this is embedded in.
46  * @member:     the name of the member within the struct.
47  *
48  * (this is needed by list.h)
49  */
50 #define container_of(ptr, type, member) ({                      \
51         const typeof( ((type *)0)->member ) *__mptr = (ptr);    \
52         (type *)( (char *)__mptr - offsetof(type,member) );})
53
54 enum {
55         FUNCF_TRACE     = 1 << 0,       /* Include this function in trace */
56         TRACE_PAGE_SIZE = 4096,         /* Assumed page size for trace */
57         TRACE_PID       = 1,            /* PID to use for U-Boot */
58         LEN_STACK_SIZE  = 4,            /* number of nested length fix-ups */
59         TRACE_PAGE_MASK = TRACE_PAGE_SIZE - 1,
60         MAX_STACK_DEPTH = 50,           /* Max nested function calls */
61         MAX_LINE_LEN    = 500,          /* Max characters per line */
62 };
63
64 /**
65  * enum out_format_t - supported output formats
66  *
67  * @OUT_FMT_DEFAULT: Use the default for the output file
68  * @OUT_FMT_FUNCTION: Write ftrace 'function' records
69  * @OUT_FMT_FUNCGRAPH: Write ftrace funcgraph_entry and funcgraph_exit records
70  */
71 enum out_format_t {
72         OUT_FMT_DEFAULT,
73         OUT_FMT_FUNCTION,
74         OUT_FMT_FUNCGRAPH,
75 };
76
77 /* Section types for v7 format (trace-cmd format) */
78 enum {
79         SECTION_OPTIONS,
80 };
81
82 /* Option types (trace-cmd format) */
83 enum {
84         OPTION_DONE,
85         OPTION_DATE,
86         OPTION_CPUSTAT,
87         OPTION_BUFFER,
88         OPTION_TRACECLOCK,
89         OPTION_UNAME,
90         OPTION_HOOK,
91         OPTION_OFFSET,
92         OPTION_CPUCOUNT,
93         OPTION_VERSION,
94         OPTION_PROCMAPS,
95         OPTION_TRACEID,
96         OPTION_TIME_SHIFT,
97         OPTION_GUEST,
98         OPTION_TSC2NSEC,
99 };
100
101 /* types of trace records (trace-cmd format) */
102 enum trace_type {
103         __TRACE_FIRST_TYPE = 0,
104
105         TRACE_FN,
106         TRACE_CTX,
107         TRACE_WAKE,
108         TRACE_STACK,
109         TRACE_PRINT,
110         TRACE_BPRINT,
111         TRACE_MMIO_RW,
112         TRACE_MMIO_MAP,
113         TRACE_BRANCH,
114         TRACE_GRAPH_RET,
115         TRACE_GRAPH_ENT,
116 };
117
118 /**
119  * struct flame_node - a node in the call-stack tree
120  *
121  * Each stack frame detected in the trace is given a node corresponding to a
122  * function call in the call stack. Functions can appear multiple times when
123  * they are called by a different set of parent functions.
124  *
125  * @parent: Parent node (the call stack for the function that called this one)
126  * @child_head: List of children of this node (functions called from here)
127  * @sibling: Next node in the list of children
128  * @func: Function this node refers to (NULL for root node)
129  * @count: Number of times this call-stack occurred
130  */
131 struct flame_node {
132         struct flame_node *parent;
133         struct list_head child_head;
134         struct list_head sibling_node;
135         struct func_info *func;
136         int count;
137 };
138
139 /**
140  * struct flame_state - state information for building the flame graph
141  *
142  * @node: Current node being processed (corresponds to a function call)
143  * @nodes: Number of nodes created (running count)
144  */
145 struct flame_state {
146         struct flame_node *node;
147         int nodes;
148 };
149
150 /**
151  * struct func_info - information recorded for each function
152  *
153  * @offset: Function offset in the image, measured from the text_base
154  * @name: Function name
155  * @code_size: Total code size of the function
156  * @flags: Either 0 or FUNCF_TRACE
157  */
158 struct func_info {
159         unsigned long offset;
160         const char *name;
161         unsigned long code_size;
162         unsigned flags;
163 };
164
165 /**
166  * enum trace_line_type - whether to include or exclude a function
167  *
168  * @TRACE_LINE_INCLUDE: Include the function
169  * @TRACE_LINE_EXCLUDE: Exclude the function
170  */
171 enum trace_line_type {
172         TRACE_LINE_INCLUDE,
173         TRACE_LINE_EXCLUDE,
174 };
175
176 /**
177  * struct trace_configline_info - information about a config-file line
178  *
179  * @next: Next line
180  * @type: Line type
181  * @name: identifier name / wildcard
182  * @regex: Regex to use if name starts with '/'
183  */
184 struct trace_configline_info {
185         struct trace_configline_info *next;
186         enum trace_line_type type;
187         const char *name;
188         regex_t regex;
189 };
190
191 /**
192  * struct tw_len - holds information about a length value that need fix-ups
193  *
194  * This is used to record a placeholder for a u32 or u64 length which is written
195  * to the output file but needs to be updated once the length is actually known
196  *
197  * This allows us to write tw->ptr - @len_base to position @ptr in the file
198  *
199  * @ptr: Position of the length value in the file
200  * @base: Base position for the calculation
201  * @size: Size of the length value, in bytes (4 or 8)
202  */
203 struct tw_len {
204         int ptr;
205         int base;
206         int size;
207 };
208
209 /**
210  * struct twriter - Writer for trace records
211  *
212  * Maintains state used when writing the output file in trace-cmd format
213  *
214  * @ptr: Current file position
215  * @len_stack: Stack of length values that need fixing up
216  * @len: Number of items on @len_stack
217  * @str_buf: Buffer of strings (for v7 format)
218  * @str_ptr: Current write-position in the buffer for strings
219  * @fout: Output file
220  */
221 struct twriter {
222         int ptr;
223         struct tw_len len_stack[LEN_STACK_SIZE];
224         int len_count;
225         struct abuf str_buf;
226         int str_ptr;
227         FILE *fout;
228 };
229
230 /* The contents of the trace config file */
231 struct trace_configline_info *trace_config_head;
232
233 /* list of all functions in System.map file, sorted by offset in the image */
234 struct func_info *func_list;
235
236 int func_count;                 /* number of functions */
237 struct trace_call *call_list;   /* list of all calls in the input trace file */
238 int call_count;                 /* number of calls */
239 int verbose;    /* Verbosity level 0=none, 1=warn, 2=notice, 3=info, 4=debug */
240 ulong text_offset;              /* text address of first function */
241 ulong text_base;                /* CONFIG_TEXT_BASE from trace file */
242
243 /* debugging helpers */
244 static void outf(int level, const char *fmt, ...)
245                 __attribute__ ((format (__printf__, 2, 3)));
246 #define error(fmt, b...) outf(0, fmt, ##b)
247 #define warn(fmt, b...) outf(1, fmt, ##b)
248 #define notice(fmt, b...) outf(2, fmt, ##b)
249 #define info(fmt, b...) outf(3, fmt, ##b)
250 #define debug(fmt, b...) outf(4, fmt, ##b)
251
252 static void outf(int level, const char *fmt, ...)
253 {
254         if (verbose >= level) {
255                 va_list args;
256
257                 va_start(args, fmt);
258                 vfprintf(stderr, fmt, args);
259                 va_end(args);
260         }
261 }
262
263 static void usage(void)
264 {
265         fprintf(stderr,
266                 "Usage: proftool [-cmtv] <cmd> <profdata>\n"
267                 "\n"
268                 "Commands\n"
269                 "   dump-ftrace\t\tDump out records in ftrace format for use by trace-cmd\n"
270                 "   dump-flamegraph\tWrite a file for use with flamegraph.pl\n"
271                 "\n"
272                 "Options:\n"
273                 "   -c <cfg>\tSpecify config file\n"
274                 "   -f <subtype>\tSpecify output subtype\n"
275                 "   -m <map>\tSpecify Systen.map file\n"
276                 "   -o <fname>\tSpecify output file\n"
277                 "   -t <fname>\tSpecify trace data file (from U-Boot 'trace calls')\n"
278                 "   -v <0-4>\tSpecify verbosity\n"
279                 "\n"
280                 "Subtypes for dump-ftrace:\n"
281                 "   function - write function-call records (caller/callee)\n"
282                 "   funcgraph - write function entry/exit records (graph)\n");
283         exit(EXIT_FAILURE);
284 }
285
286 /**
287  * h_cmp_offset - bsearch() function to compare two functions bny their offset
288  *
289  * @v1: Pointer to first function (struct func_info)
290  * @v2: Pointer to second function (struct func_info)
291  * Returns: < 0 if v1 offset < v2 offset, 0 if equal, > 0 otherwise
292  */
293 static int h_cmp_offset(const void *v1, const void *v2)
294 {
295         const struct func_info *f1 = v1, *f2 = v2;
296
297         return (f1->offset / FUNC_SITE_SIZE) - (f2->offset / FUNC_SITE_SIZE);
298 }
299
300 /**
301  * read_system_map() - read the System.map file to create a list of functions
302  *
303  * This also reads the text_offset value, since we assume that the first text
304  * symbol is at that address
305  *
306  * @fin: File to read
307  * Returns: 0 if OK, non-zero on error
308  */
309 static int read_system_map(FILE *fin)
310 {
311         unsigned long offset, start = 0;
312         struct func_info *func;
313         char buff[MAX_LINE_LEN];
314         char symtype;
315         char symname[MAX_LINE_LEN + 1];
316         int linenum;
317         int alloced;
318
319         for (linenum = 1, alloced = func_count = 0;; linenum++) {
320                 int fields = 0;
321
322                 if (fgets(buff, sizeof(buff), fin))
323                         fields = sscanf(buff, "%lx %c %100s\n", &offset,
324                                 &symtype, symname);
325                 if (fields == 2) {
326                         continue;
327                 } else if (feof(fin)) {
328                         break;
329                 } else if (fields < 2) {
330                         error("Map file line %d: invalid format\n", linenum);
331                         return 1;
332                 }
333
334                 /* Must be a text symbol */
335                 symtype = tolower(symtype);
336                 if (symtype != 't' && symtype != 'w')
337                         continue;
338
339                 if (func_count == alloced) {
340                         alloced += 256;
341                         func_list = realloc(func_list,
342                                         sizeof(struct func_info) * alloced);
343                         assert(func_list);
344                 }
345                 if (!func_count)
346                         start = offset;
347
348                 func = &func_list[func_count++];
349                 memset(func, '\0', sizeof(*func));
350                 func->offset = offset - start;
351                 func->name = strdup(symname);
352                 func->flags = FUNCF_TRACE;      /* trace by default */
353
354                 /* Update previous function's code size */
355                 if (func_count > 1)
356                         func[-1].code_size = func->offset - func[-1].offset;
357         }
358         notice("%d functions found in map file, start addr %lx\n", func_count,
359                start);
360         text_offset = start;
361
362         return 0;
363 }
364
365 static int read_data(FILE *fin, void *buff, int size)
366 {
367         int err;
368
369         err = fread(buff, 1, size, fin);
370         if (!err)
371                 return 1;
372         if (err != size) {
373                 error("Cannot read trace file at pos %lx\n", ftell(fin));
374                 return -1;
375         }
376         return 0;
377 }
378
379 /**
380  * find_func_by_offset() - Look up a function by its offset
381  *
382  * @offset: Offset to search for, from text_base
383  * Returns: function, if found, else NULL
384  *
385  * This does a fast search for a function given its offset from text_base
386  *
387  */
388 static struct func_info *find_func_by_offset(uint offset)
389 {
390         struct func_info key, *found;
391
392         key.offset = offset;
393         found = bsearch(&key, func_list, func_count, sizeof(struct func_info),
394                         h_cmp_offset);
395
396         return found;
397 }
398
399 /**
400  * find_caller_by_offset() - finds the function which contains the given offset
401  *
402  * @offset: Offset to search for, from text_base
403  * Returns: function, if found, else NULL
404  *
405  * If the offset falls between two functions, then it is assumed to belong to
406  * the first function (with the lowest offset). This is a way of figuring out
407  * which function owns code at a particular offset
408  */
409 static struct func_info *find_caller_by_offset(uint offset)
410 {
411         int low;        /* least function that could be a match */
412         int high;       /* greated function that could be a match */
413         struct func_info key;
414
415         low = 0;
416         high = func_count - 1;
417         key.offset = offset;
418         while (high > low + 1) {
419                 int mid = (low + high) / 2;
420                 int result;
421
422                 result = h_cmp_offset(&key, &func_list[mid]);
423                 if (result > 0)
424                         low = mid;
425                 else if (result < 0)
426                         high = mid;
427                 else
428                         return &func_list[mid];
429         }
430
431         return low >= 0 ? &func_list[low] : NULL;
432 }
433
434 /**
435  * read_calls() - Read the list of calls from the trace data
436  *
437  * The calls are stored consecutively in the trace output produced by U-Boot
438  *
439  * @fin: File to read from
440  * @count: Number of calls to read
441  * Returns: 0 if OK, -1 on error
442  */
443 static int read_calls(FILE *fin, size_t count)
444 {
445         struct trace_call *call_data;
446         int i;
447
448         notice("call count: %zu\n", count);
449         call_list = (struct trace_call *)calloc(count, sizeof(*call_data));
450         if (!call_list) {
451                 error("Cannot allocate call_list\n");
452                 return -1;
453         }
454         call_count = count;
455
456         call_data = call_list;
457         for (i = 0; i < count; i++, call_data++) {
458                 if (read_data(fin, call_data, sizeof(*call_data)))
459                         return -1;
460         }
461         return 0;
462 }
463
464 /**
465  * read_trace() - Read the U-Boot trace file
466  *
467  * Read in the calls from the trace file. The function list is ignored at
468  * present
469  *
470  * @fin: File to read
471  * Returns 0 if OK, non-zero on error
472  */
473 static int read_trace(FILE *fin)
474 {
475         struct trace_output_hdr hdr;
476
477         while (!feof(fin)) {
478                 int err;
479
480                 err = read_data(fin, &hdr, sizeof(hdr));
481                 if (err == 1)
482                         break; /* EOF */
483                 else if (err)
484                         return 1;
485                 text_base = hdr.text_base;
486
487                 switch (hdr.type) {
488                 case TRACE_CHUNK_FUNCS:
489                         /* Ignored at present */
490                         break;
491
492                 case TRACE_CHUNK_CALLS:
493                         if (read_calls(fin, hdr.rec_count))
494                                 return 1;
495                         break;
496                 }
497         }
498         return 0;
499 }
500
501 /**
502  * read_map_file() - Read the System.map file
503  *
504  * This reads the file into the func_list array
505  *
506  * @fname: Filename to read
507  * Returns 0 if OK, non-zero on error
508  */
509 static int read_map_file(const char *fname)
510 {
511         FILE *fmap;
512         int err = 0;
513
514         fmap = fopen(fname, "r");
515         if (!fmap) {
516                 error("Cannot open map file '%s'\n", fname);
517                 return 1;
518         }
519         if (fmap) {
520                 err = read_system_map(fmap);
521                 fclose(fmap);
522         }
523         return err;
524 }
525
526 /**
527  * read_trace_file() - Open and read the U-Boot trace file
528  *
529  * Read in the calls from the trace file. The function list is ignored at
530  * present
531  *
532  * @fin: File to read
533  * Returns 0 if OK, non-zero on error
534  */
535 static int read_trace_file(const char *fname)
536 {
537         FILE *fprof;
538         int err;
539
540         fprof = fopen(fname, "rb");
541         if (!fprof) {
542                 error("Cannot open trace data file '%s'\n",
543                       fname);
544                 return 1;
545         } else {
546                 err = read_trace(fprof);
547                 fclose(fprof);
548                 if (err)
549                         return err;
550         }
551         return 0;
552 }
553
554 static int regex_report_error(regex_t *regex, int err, const char *op,
555                               const char *name)
556 {
557         char buf[200];
558
559         regerror(err, regex, buf, sizeof(buf));
560         error("Regex error '%s' in %s '%s'\n", buf, op, name);
561         return -1;
562 }
563
564 static void check_trace_config_line(struct trace_configline_info *item)
565 {
566         struct func_info *func, *end;
567         int err;
568
569         debug("Checking trace config line '%s'\n", item->name);
570         for (func = func_list, end = func + func_count; func < end; func++) {
571                 err = regexec(&item->regex, func->name, 0, NULL, 0);
572                 debug("   - regex '%s', string '%s': %d\n", item->name,
573                       func->name, err);
574                 if (err == REG_NOMATCH)
575                         continue;
576
577                 if (err) {
578                         regex_report_error(&item->regex, err, "match",
579                                            item->name);
580                         break;
581                 }
582
583                 /* It matches, so perform the action */
584                 switch (item->type) {
585                 case TRACE_LINE_INCLUDE:
586                         info("      include %s at %lx\n", func->name,
587                              text_offset + func->offset);
588                         func->flags |= FUNCF_TRACE;
589                         break;
590
591                 case TRACE_LINE_EXCLUDE:
592                         info("      exclude %s at %lx\n", func->name,
593                              text_offset + func->offset);
594                         func->flags &= ~FUNCF_TRACE;
595                         break;
596                 }
597         }
598 }
599
600 /** check_trace_config() - Check trace-config file, reporting any problems */
601 static void check_trace_config(void)
602 {
603         struct trace_configline_info *line;
604
605         for (line = trace_config_head; line; line = line->next)
606                 check_trace_config_line(line);
607 }
608
609 /**
610  * read_trace_config() - read the trace-config file
611  *
612  * This file consists of lines like:
613  *
614  * include-func <regex>
615  * exclude-func <regex>
616  *
617  * where <regex> is a regular expression matched against function names. It
618  * allows some functions to be dropped from the trace when producing ftrace
619  * records
620  *
621  * @fin: File to process
622  * Returns: 0 if OK, -1 on error
623  */
624 static int read_trace_config(FILE *fin)
625 {
626         char buff[200];
627         int linenum = 0;
628         struct trace_configline_info **tailp = &trace_config_head;
629
630         while (fgets(buff, sizeof(buff), fin)) {
631                 int len = strlen(buff);
632                 struct trace_configline_info *line;
633                 char *saveptr;
634                 char *s, *tok;
635                 int err;
636
637                 linenum++;
638                 if (len && buff[len - 1] == '\n')
639                         buff[len - 1] = '\0';
640
641                 /* skip blank lines and comments */
642                 for (s = buff; *s == ' ' || *s == '\t'; s++)
643                         ;
644                 if (!*s || *s == '#')
645                         continue;
646
647                 line = (struct trace_configline_info *)calloc(1, sizeof(*line));
648                 if (!line) {
649                         error("Cannot allocate config line\n");
650                         return -1;
651                 }
652
653                 tok = strtok_r(s, " \t", &saveptr);
654                 if (!tok) {
655                         error("Invalid trace config data on line %d\n",
656                               linenum);
657                         return -1;
658                 }
659                 if (0 == strcmp(tok, "include-func")) {
660                         line->type = TRACE_LINE_INCLUDE;
661                 } else if (0 == strcmp(tok, "exclude-func")) {
662                         line->type = TRACE_LINE_EXCLUDE;
663                 } else {
664                         error("Unknown command in trace config data line %d\n",
665                               linenum);
666                         return -1;
667                 }
668
669                 tok = strtok_r(NULL, " \t", &saveptr);
670                 if (!tok) {
671                         error("Missing pattern in trace config data line %d\n",
672                               linenum);
673                         return -1;
674                 }
675
676                 err = regcomp(&line->regex, tok, REG_NOSUB);
677                 if (err) {
678                         int r = regex_report_error(&line->regex, err,
679                                                    "compile", tok);
680                         free(line);
681                         return r;
682                 }
683
684                 /* link this new one to the end of the list */
685                 line->name = strdup(tok);
686                 line->next = NULL;
687                 *tailp = line;
688                 tailp = &line->next;
689         }
690
691         if (!feof(fin)) {
692                 error("Cannot read from trace config file at position %ld\n",
693                       ftell(fin));
694                 return -1;
695         }
696         return 0;
697 }
698
699 static int read_trace_config_file(const char *fname)
700 {
701         FILE *fin;
702         int err;
703
704         fin = fopen(fname, "r");
705         if (!fin) {
706                 error("Cannot open trace_config file '%s'\n", fname);
707                 return -1;
708         }
709         err = read_trace_config(fin);
710         fclose(fin);
711         return err;
712 }
713
714 /**
715  * tputh() - Write a 16-bit little-endian value to a file
716  *
717  * @fout: File to write to
718  * @val: Value to write
719  * Returns: number of bytes written (2)
720  */
721 static int tputh(FILE *fout, unsigned int val)
722 {
723         fputc(val, fout);
724         fputc(val >> 8, fout);
725
726         return 2;
727 }
728
729 /**
730  * tputl() - Write a 32-bit little-endian value to a file
731  *
732  * @fout: File to write to
733  * @val: Value to write
734  * Returns: number of bytes written (4)
735  */
736 static int tputl(FILE *fout, ulong val)
737 {
738         fputc(val, fout);
739         fputc(val >> 8, fout);
740         fputc(val >> 16, fout);
741         fputc(val >> 24, fout);
742
743         return 4;
744 }
745
746 /**
747  * tputh() - Write a 64-bit little-endian value to a file
748  *
749  * @fout: File to write to
750  * @val: Value to write
751  * Returns: number of bytes written (8)
752  */
753 static int tputq(FILE *fout, unsigned long long val)
754 {
755         tputl(fout, val);
756         tputl(fout, val >> 32U);
757
758         return 8;
759 }
760
761 /**
762  * tputh() - Write a string to a file
763  *
764  * The string is written without its terminator
765  *
766  * @fout: File to write to
767  * @val: Value to write
768  * Returns: number of bytes written
769  */
770 static int tputs(FILE *fout, const char *str)
771 {
772         fputs(str, fout);
773
774         return strlen(str);
775 }
776
777 /**
778  * add_str() - add a name string to the string table
779  *
780  * This is used by the v7 format
781  *
782  * @tw: Writer context
783  * @name: String to write
784  * Returns: Updated value of string pointer, or -1 if out of memory
785  */
786 static int add_str(struct twriter *tw, const char *name)
787 {
788         int str_ptr;
789         int len;
790
791         len = strlen(name) + 1;
792         str_ptr = tw->str_ptr;
793         tw->str_ptr += len;
794
795         if (tw->str_ptr > abuf_size(&tw->str_buf)) {
796                 int new_size;
797
798                 new_size = ALIGN(tw->str_ptr, 4096);
799                 if (!abuf_realloc(&tw->str_buf, new_size))
800                         return -1;
801         }
802
803         return str_ptr;
804 }
805
806 /**
807  * push_len() - Push a new length request onto the stack
808  *
809  * @tw: Writer context
810  * @base: Base position of the length calculation
811  * @msg: Indicates the type of caller, for debugging
812  * @size: Size of the length value, either 4 bytes or 8
813  * Returns number of bytes written to the file (=@size on success), -ve on error
814  *
815  * This marks a place where a length must be written, covering data that is
816  * about to be written. It writes a placeholder value.
817  *
818  * Once the data is written, calling pop_len() will update the placeholder with
819  * the correct length based on how many bytes have been written
820  */
821 static int push_len(struct twriter *tw, int base, const char *msg, int size)
822 {
823         struct tw_len *lp;
824
825         if (tw->len_count >= LEN_STACK_SIZE) {
826                 fprintf(stderr, "Length-stack overflow: %s\n", msg);
827                 return -1;
828         }
829         if (size != 4 && size != 8) {
830                 fprintf(stderr, "Length-stack invalid size %d: %s\n", size,
831                         msg);
832                 return -1;
833         }
834
835         lp = &tw->len_stack[tw->len_count++];
836         lp->base = base;
837         lp->ptr = tw->ptr;
838         lp->size = size;
839
840         return size == 8 ? tputq(tw->fout, 0) : tputl(tw->fout, 0);
841 }
842
843 /**
844  * pop_len() - Update a length value once the length is known
845  *
846  * Pops a value of the length stack and updates the file at that position with
847  * the number of bytes written between now and then. Once done, the file is
848  * seeked to the current (tw->ptr) position again, so writing can continue as
849  * normal.
850  *
851  * @tw: Writer context
852  * @msg: Indicates the type of caller, for debugging
853  * Returns 0 if OK, -1 on error
854  */
855 static int pop_len(struct twriter *tw, const char *msg)
856 {
857         struct tw_len *lp;
858         int len, ret;
859
860         if (!tw->len_count) {
861                 fprintf(stderr, "Length-stack underflow: %s\n", msg);
862                 return -1;
863         }
864
865         lp = &tw->len_stack[--tw->len_count];
866         if (fseek(tw->fout, lp->ptr, SEEK_SET))
867                 return -1;
868         len = tw->ptr - lp->base;
869         ret = lp->size == 8 ? tputq(tw->fout, len) : tputl(tw->fout, len);
870         if (ret < 0)
871                 return -1;
872         if (fseek(tw->fout, tw->ptr, SEEK_SET))
873                 return -1;
874
875         return 0;
876 }
877
878 /**
879  * start_header() - Start a v7 section
880  *
881  * Writes a header in v7 format
882  *
883  * @tw: Writer context
884  * @id: ID of header to write (SECTION_...)
885  * @flags: Flags value to write
886  * @name: Name of section
887  * Returns: number of bytes written
888  */
889 static int start_header(struct twriter *tw, int id, uint flags,
890                         const char *name)
891 {
892         int str_id;
893         int lptr;
894         int base;
895         int ret;
896
897         base = tw->ptr + 16;
898         lptr = 0;
899         lptr += tputh(tw->fout, id);
900         lptr += tputh(tw->fout, flags);
901         str_id = add_str(tw, name);
902         if (str_id < 0)
903                 return -1;
904         lptr += tputl(tw->fout, str_id);
905
906         /* placeholder for size */
907         ret = push_len(tw, base, "v7 header", 8);
908         if (ret < 0)
909                 return -1;
910         lptr += ret;
911
912         return lptr;
913 }
914
915 /**
916  * start_page() - Start a new page of output data
917  *
918  * The output is arranged in 4KB pages with a base timestamp at the start of
919  * each. This starts a new page, making sure it is aligned to 4KB in the output
920  * file.
921  *
922  * @tw: Writer context
923  * @timestamp: Base timestamp for the page
924  */
925 static int start_page(struct twriter *tw, ulong timestamp)
926 {
927         int start;
928         int ret;
929
930         /* move to start of next page */
931         start = ALIGN(tw->ptr, TRACE_PAGE_SIZE);
932         ret = fseek(tw->fout, start, SEEK_SET);
933         if (ret < 0) {
934                 fprintf(stderr, "Cannot seek to page start\n");
935                 return -1;
936         }
937         tw->ptr = start;
938
939         /* page header */
940         tw->ptr += tputq(tw->fout, timestamp);
941         ret = push_len(tw, start + 16, "page", 8);
942         if (ret < 0)
943                 return ret;
944         tw->ptr += ret;
945
946         return 0;
947 }
948
949 /**
950  * finish_page() - finish a page
951  *
952  * Sets the lengths correctly and moves to the start of the next page
953  *
954  * @tw: Writer context
955  * Returns: 0 on success, -1 on error
956  */
957 static int finish_page(struct twriter *tw)
958 {
959         int ret, end;
960
961         ret = pop_len(tw, "page");
962         if (ret < 0)
963                 return ret;
964         end = ALIGN(tw->ptr, TRACE_PAGE_SIZE);
965
966         /*
967          * Write a byte so that the data actually makes to the file, in the case
968          * that we never write any more pages
969          */
970         if (tw->ptr != end) {
971                 if (fseek(tw->fout, end - 1, SEEK_SET)) {
972                         fprintf(stderr, "cannot seek to start of next page\n");
973                         return -1;
974                 }
975                 fputc(0, tw->fout);
976                 tw->ptr = end;
977         }
978
979         return 0;
980 }
981
982 /**
983  * output_headers() - Output v6 headers to the file
984  *
985  * Writes out the various formats so that trace-cmd and kernelshark can make
986  * sense of the data
987  *
988  * This updates tw->ptr as it goes
989  *
990  * @tw: Writer context
991  * Returns: 0 on success, -ve on error
992  */
993 static int output_headers(struct twriter *tw)
994 {
995         FILE *fout = tw->fout;
996         char str[800];
997         int len, ret;
998
999         tw->ptr += fprintf(fout, "%c%c%ctracing6%c%c%c", 0x17, 0x08, 0x44,
1000                            0 /* terminator */, 0 /* little endian */,
1001                            4 /* 32-bit long values */);
1002
1003         /* host-machine page size 4KB */
1004         tw->ptr += tputl(fout, 4 << 10);
1005
1006         tw->ptr += fprintf(fout, "header_page%c", 0);
1007
1008         snprintf(str, sizeof(str),
1009                  "\tfield: u64 timestamp;\toffset:0;\tsize:8;\tsigned:0;\n"
1010                  "\tfield: local_t commit;\toffset:8;\tsize:8;\tsigned:1;\n"
1011                  "\tfield: int overwrite;\toffset:8;\tsize:1;\tsigned:1;\n"
1012                  "\tfield: char data;\toffset:16;\tsize:4080;\tsigned:1;\n");
1013         len = strlen(str);
1014         tw->ptr += tputq(fout, len);
1015         tw->ptr += tputs(fout, str);
1016
1017         if (VERSION7) {
1018                 /* no compression */
1019                 tw->ptr += fprintf(fout, "none%cversion%c\n", 0, 0);
1020
1021                 ret = start_header(tw, SECTION_OPTIONS, 0, "options");
1022                 if (ret < 0) {
1023                         fprintf(stderr, "Cannot start option header\n");
1024                         return -1;
1025                 }
1026                 tw->ptr += ret;
1027                 tw->ptr += tputh(fout, OPTION_DONE);
1028                 tw->ptr += tputl(fout, 8);
1029                 tw->ptr += tputl(fout, 0);
1030                 ret = pop_len(tw, "t7 header");
1031                 if (ret < 0) {
1032                         fprintf(stderr, "Cannot finish option header\n");
1033                         return -1;
1034                 }
1035         }
1036
1037         tw->ptr += fprintf(fout, "header_event%c", 0);
1038         snprintf(str, sizeof(str),
1039                  "# compressed entry header\n"
1040                  "\ttype_len    :    5 bits\n"
1041                  "\ttime_delta  :   27 bits\n"
1042                  "\tarray       :   32 bits\n"
1043                  "\n"
1044                  "\tpadding     : type == 29\n"
1045                  "\ttime_extend : type == 30\n"
1046                  "\ttime_stamp : type == 31\n"
1047                  "\tdata max type_len  == 28\n");
1048         len = strlen(str);
1049         tw->ptr += tputq(fout, len);
1050         tw->ptr += tputs(fout, str);
1051
1052         /* number of ftrace-event-format files */
1053         tw->ptr += tputl(fout, 3);
1054
1055         snprintf(str, sizeof(str),
1056                  "name: function\n"
1057                  "ID: 1\n"
1058                  "format:\n"
1059                  "\tfield:unsigned short common_type;\toffset:0;\tsize:2;\tsigned:0;\n"
1060                  "\tfield:unsigned char common_flags;\toffset:2;\tsize:1;\tsigned:0;\n"
1061                  "\tfield:unsigned char common_preempt_count;\toffset:3;\tsize:1;signed:0;\n"
1062                  "\tfield:int common_pid;\toffset:4;\tsize:4;\tsigned:1;\n"
1063                  "\n"
1064                  "\tfield:unsigned long ip;\toffset:8;\tsize:8;\tsigned:0;\n"
1065                  "\tfield:unsigned long parent_ip;\toffset:16;\tsize:8;\tsigned:0;\n"
1066                  "\n"
1067                  "print fmt: \" %%ps <-- %%ps\", (void *)REC->ip, (void *)REC->parent_ip\n");
1068         len = strlen(str);
1069         tw->ptr += tputq(fout, len);
1070         tw->ptr += tputs(fout, str);
1071
1072         snprintf(str, sizeof(str),
1073                  "name: funcgraph_entry\n"
1074                  "ID: 11\n"
1075                  "format:\n"
1076                  "\tfield:unsigned short common_type;\toffset:0;\tsize:2;\tsigned:0;\n"
1077                  "\tfield:unsigned char common_flags;\toffset:2;\tsize:1;\tsigned:0;\n"
1078                  "\tfield:unsigned char common_preempt_count;\toffset:3;\tsize:1;signed:0;\n"
1079                  "\tfield:int common_pid;\toffset:4;\tsize:4;\tsigned:1;\n"
1080                  "\n"
1081                  "\tfield:unsigned long func;\toffset:8;\tsize:8;\tsigned:0;\n"
1082                  "\tfield:int depth;\toffset:16;\tsize:4;\tsigned:1;\n"
1083                 "\n"
1084                  "print fmt: \"--> %%ps (%%d)\", (void *)REC->func, REC->depth\n");
1085         len = strlen(str);
1086         tw->ptr += tputq(fout, len);
1087         tw->ptr += tputs(fout, str);
1088
1089         snprintf(str, sizeof(str),
1090                  "name: funcgraph_exit\n"
1091                  "ID: 10\n"
1092                  "format:\n"
1093                  "\tfield:unsigned short common_type;\toffset:0;\tsize:2;\tsigned:0;\n"
1094                  "\tfield:unsigned char common_flags;\toffset:2;\tsize:1;\tsigned:0;\n"
1095                  "\tfield:unsigned char common_preempt_count;\toffset:3;\tsize:1;signed:0;\n"
1096                  "\tfield:int common_pid;\toffset:4;\tsize:4;\tsigned:1;\n"
1097                  "\n"
1098                  "\tfield:unsigned long func;\toffset:8;\tsize:8;\tsigned:0;\n"
1099                  "\tfield:int depth;\toffset:16;\tsize:4;\tsigned:1;\n"
1100                  "\tfield:unsigned int overrun;\toffset:20;\tsize:4;\tsigned:0;\n"
1101                  "\tfield:unsigned long long calltime;\toffset:24;\tsize:8;\tsigned:0;\n"
1102                  "\tfield:unsigned long long rettime;\toffset:32;\tsize:8;\tsigned:0;\n"
1103                  "\n"
1104                  "print fmt: \"<-- %%ps (%%d) (start: %%llx  end: %%llx) over: %%d\", (void *)REC->func, REC->depth, REC->calltime, REC->rettime, REC->depth\n");
1105         len = strlen(str);
1106         tw->ptr += tputq(fout, len);
1107         tw->ptr += tputs(fout, str);
1108
1109         return 0;
1110 }
1111
1112 /**
1113  * write_symbols() - Write the symbols out
1114  *
1115  * Writes the symbol information in the following format to mimic the Linux
1116  * /proc/kallsyms file:
1117  *
1118  * <address> T <name>
1119  *
1120  * This updates tw->ptr as it goes
1121  *
1122  * @tw: Writer context
1123  * Returns: 0 on success, -ve on error
1124  */
1125 static int write_symbols(struct twriter *tw)
1126 {
1127         char str[200];
1128         int ret, i;
1129
1130         /* write symbols */
1131         ret = push_len(tw, tw->ptr + 4, "syms", 4);
1132         if (ret < 0)
1133                 return -1;
1134         tw->ptr += ret;
1135         for (i = 0; i < func_count; i++) {
1136                 struct func_info *func = &func_list[i];
1137
1138                 snprintf(str, sizeof(str), "%016lx T %s\n",
1139                          text_offset + func->offset, func->name);
1140                 tw->ptr += tputs(tw->fout, str);
1141         }
1142         ret = pop_len(tw, "syms");
1143         if (ret < 0)
1144                 return -1;
1145         tw->ptr += ret;
1146
1147         return 0;
1148 }
1149
1150 /**
1151  * write_options() - Write the options out
1152  *
1153  * Writes various options which are needed or useful. We use OPTION_TSC2NSEC
1154  * to indicates that values in the output need to be multiplied by 1000 since
1155  * U-Boot's trace values are in microseconds.
1156  *
1157  * This updates tw->ptr as it goes
1158  *
1159  * @tw: Writer context
1160  * Returns: 0 on success, -ve on error
1161  */
1162 static int write_options(struct twriter *tw)
1163 {
1164         FILE *fout = tw->fout;
1165         char str[200];
1166         int len;
1167
1168         /* trace_printk, 0 for now */
1169         tw->ptr += tputl(fout, 0);
1170
1171         /* processes */
1172         snprintf(str, sizeof(str), "%d u-boot\n", TRACE_PID);
1173         len = strlen(str);
1174         tw->ptr += tputq(fout, len);
1175         tw->ptr += tputs(fout, str);
1176
1177         /* number of CPUs */
1178         tw->ptr += tputl(fout, 1);
1179
1180         tw->ptr += fprintf(fout, "options  %c", 0);
1181
1182         /* traceclock */
1183         tw->ptr += tputh(fout, OPTION_TRACECLOCK);
1184         tw->ptr += tputl(fout, 0);
1185
1186         /* uname */
1187         tw->ptr += tputh(fout, OPTION_UNAME);
1188         snprintf(str, sizeof(str), "U-Boot");
1189         len = strlen(str);
1190         tw->ptr += tputl(fout, len);
1191         tw->ptr += tputs(fout, str);
1192
1193         /* version */
1194         tw->ptr += tputh(fout, OPTION_VERSION);
1195         snprintf(str, sizeof(str), "unknown");
1196         len = strlen(str);
1197         tw->ptr += tputl(fout, len);
1198         tw->ptr += tputs(fout, str);
1199
1200         /* trace ID */
1201         tw->ptr += tputh(fout, OPTION_TRACEID);
1202         tw->ptr += tputl(fout, 8);
1203         tw->ptr += tputq(fout, 0x123456780abcdef0);
1204
1205         /* time conversion */
1206         tw->ptr += tputh(fout, OPTION_TSC2NSEC);
1207         tw->ptr += tputl(fout, 16);
1208         tw->ptr += tputl(fout, 1000);   /* multiplier */
1209         tw->ptr += tputl(fout, 0);      /* shift */
1210         tw->ptr += tputq(fout, 0);      /* offset */
1211
1212         /* cpustat - bogus data for now, but at least it mentions the CPU */
1213         tw->ptr += tputh(fout, OPTION_CPUSTAT);
1214         snprintf(str, sizeof(str),
1215                  "CPU: 0\n"
1216                  "entries: 100\n"
1217                  "overrun: 43565\n"
1218                  "commit overrun: 0\n"
1219                  "bytes: 3360\n"
1220                  "oldest event ts: 963732.447752\n"
1221                  "now ts: 963832.146824\n"
1222                  "dropped events: 0\n"
1223                  "read events: 42379\n");
1224         len = strlen(str);
1225         tw->ptr += tputl(fout, len);
1226         tw->ptr += tputs(fout, str);
1227
1228         tw->ptr += tputh(fout, OPTION_DONE);
1229
1230         return 0;
1231 }
1232
1233 /**
1234  * calc_min_depth() - Calculate the minimum call depth from the call list
1235  *
1236  * Starting with a depth of 0, this works through the call list, adding 1 for
1237  * each function call and subtracting 1 for each function return. Most likely
1238  * the value ends up being negative, since the trace does not start at the
1239  * very top of the call stack, e.g. main(), but some function called by that.
1240  *
1241  * This value can be used to calculate the depth value for the first call,
1242  * such that it never goes negative for subsequent returns.
1243  *
1244  * Returns: minimum call depth (e.g. -2)
1245  */
1246 static int calc_min_depth(void)
1247 {
1248         struct trace_call *call;
1249         int depth, min_depth, i;
1250
1251         /* Calculate minimum depth */
1252         depth = 0;
1253         min_depth = 0;
1254         for (i = 0, call = call_list; i < call_count; i++, call++) {
1255                 switch (TRACE_CALL_TYPE(call)) {
1256                 case FUNCF_ENTRY:
1257                         depth++;
1258                         break;
1259                 case FUNCF_EXIT:
1260                         depth--;
1261                         if (depth < min_depth)
1262                                 min_depth = depth;
1263                         break;
1264                 }
1265         }
1266
1267         return min_depth;
1268 }
1269
1270 /**
1271  * write_pages() - Write the pages of trace data
1272  *
1273  * This works through all the calls, writing out as many pages of data as are
1274  * needed.
1275  *
1276  * @tw: Writer context
1277  * @out_format: Output format to use
1278  * @missing_countp: Returns number of missing functions (not found in function
1279  * list)
1280  * @skip_countp: Returns number of skipped functions (excluded from trace)
1281  *
1282  * Returns: 0 on success, -ve on error
1283  */
1284 static int write_pages(struct twriter *tw, enum out_format_t out_format,
1285                        int *missing_countp, int *skip_countp)
1286 {
1287         ulong func_stack[MAX_STACK_DEPTH];
1288         int stack_ptr;  /* next free position in stack */
1289         int upto, depth, page_upto, i;
1290         int missing_count = 0, skip_count = 0;
1291         struct trace_call *call;
1292         ulong last_timestamp;
1293         FILE *fout = tw->fout;
1294         int last_delta = 0;
1295         int err_count;
1296         bool in_page;
1297
1298         in_page = false;
1299         last_timestamp = 0;
1300         upto = 0;
1301         page_upto = 0;
1302         err_count = 0;
1303
1304         /* maintain a stack of start times for calling functions */
1305         stack_ptr = 0;
1306
1307         /*
1308          * The first thing in the trace may not be the top-level function, so
1309          * set the initial depth so that no function goes below depth 0
1310          */
1311         depth = -calc_min_depth();
1312         for (i = 0, call = call_list; i < call_count; i++, call++) {
1313                 bool entry = TRACE_CALL_TYPE(call) == FUNCF_ENTRY;
1314                 struct func_info *func;
1315                 ulong timestamp;
1316                 uint rec_words;
1317                 int delta;
1318
1319                 func = find_func_by_offset(call->func);
1320                 if (!func) {
1321                         warn("Cannot find function at %lx\n",
1322                              text_offset + call->func);
1323                         missing_count++;
1324                         if (missing_count > 20) {
1325                                 /* perhaps trace does not match System.map */
1326                                 fprintf(stderr, "Too many missing functions\n");
1327                                 return -1;
1328                         }
1329                         continue;
1330                 }
1331
1332                 if (!(func->flags & FUNCF_TRACE)) {
1333                         debug("Funcion '%s' is excluded from trace\n",
1334                               func->name);
1335                         skip_count++;
1336                         continue;
1337                 }
1338
1339                 if (out_format == OUT_FMT_FUNCTION)
1340                         rec_words = 6;
1341                 else /* 2 header words and then 3 or 8 others */
1342                         rec_words = 2 + (entry ? 3 : 8);
1343
1344                 /* convert timestamp from us to ns */
1345                 timestamp = call->flags & FUNCF_TIMESTAMP_MASK;
1346                 if (in_page) {
1347                         if (page_upto + rec_words * 4 > TRACE_PAGE_SIZE) {
1348                                 if (finish_page(tw))
1349                                         return -1;
1350                                 in_page = false;
1351                         }
1352                 }
1353                 if (!in_page) {
1354                         if (start_page(tw, timestamp))
1355                                 return -1;
1356                         in_page = true;
1357                         last_timestamp = timestamp;
1358                         last_delta = 0;
1359                         page_upto = tw->ptr & TRACE_PAGE_MASK;
1360                         if (_DEBUG) {
1361                                 fprintf(stderr,
1362                                         "new page, last_timestamp=%ld, upto=%d\n",
1363                                         last_timestamp, upto);
1364                         }
1365                 }
1366
1367                 delta = timestamp - last_timestamp;
1368                 if (delta < 0) {
1369                         fprintf(stderr, "Time went backwards\n");
1370                         err_count++;
1371                 }
1372
1373                 if (err_count > 20) {
1374                         fprintf(stderr, "Too many errors, giving up\n");
1375                         return -1;
1376                 }
1377
1378                 if (delta > 0x07fffff) {
1379                         /*
1380                          * hard to imagine how this could happen since it means
1381                          * that no function calls were made for a long time
1382                          */
1383                         fprintf(stderr, "cannot represent time delta %x\n",
1384                                 delta);
1385                         return -1;
1386                 }
1387
1388                 if (out_format == OUT_FMT_FUNCTION) {
1389                         struct func_info *caller_func;
1390
1391                         if (_DEBUG) {
1392                                 fprintf(stderr, "%d: delta=%d, stamp=%ld\n",
1393                                         upto, delta, timestamp);
1394                                 fprintf(stderr,
1395                                         "   last_delta %x to %x: last_timestamp=%lx, "
1396                                         "timestamp=%lx, call->flags=%x, upto=%d\n",
1397                                         last_delta, delta, last_timestamp,
1398                                         timestamp, call->flags, upto);
1399                         }
1400
1401                         /* type_len is 6, meaning 4 * 6 = 24 bytes */
1402                         tw->ptr += tputl(fout, rec_words | (uint)delta << 5);
1403                         tw->ptr += tputh(fout, TRACE_FN);
1404                         tw->ptr += tputh(fout, 0);      /* flags */
1405                         tw->ptr += tputl(fout, TRACE_PID);      /* PID */
1406                         /* function */
1407                         tw->ptr += tputq(fout, text_offset + func->offset);
1408                         caller_func = find_caller_by_offset(call->caller);
1409                         /* caller */
1410                         tw->ptr += tputq(fout,
1411                                          text_offset + caller_func->offset);
1412                 } else {
1413                         tw->ptr += tputl(fout, rec_words | delta << 5);
1414                         tw->ptr += tputh(fout, entry ? TRACE_GRAPH_ENT
1415                                                 : TRACE_GRAPH_RET);
1416                         tw->ptr += tputh(fout, 0);      /* flags */
1417                         tw->ptr += tputl(fout, TRACE_PID); /* PID */
1418                         /* function */
1419                         tw->ptr += tputq(fout, text_offset + func->offset);
1420                         tw->ptr += tputl(fout, depth); /* depth */
1421                         if (entry) {
1422                                 depth++;
1423                                 if (stack_ptr < MAX_STACK_DEPTH)
1424                                         func_stack[stack_ptr] = timestamp;
1425                                 stack_ptr++;
1426                         } else {
1427                                 ulong func_duration = 0;
1428
1429                                 depth--;
1430                                 if (stack_ptr && stack_ptr <= MAX_STACK_DEPTH) {
1431                                         ulong start = func_stack[--stack_ptr];
1432
1433                                         func_duration = timestamp - start;
1434                                 }
1435                                 tw->ptr += tputl(fout, 0);      /* overrun */
1436                                 tw->ptr += tputq(fout, 0);      /* calltime */
1437                                 /* rettime */
1438                                 tw->ptr += tputq(fout, func_duration);
1439                         }
1440                 }
1441
1442                 last_delta = delta;
1443                 last_timestamp = timestamp;
1444                 page_upto += 4 + rec_words * 4;
1445                 upto++;
1446                 if (stack_ptr == MAX_STACK_DEPTH)
1447                         break;
1448         }
1449         if (in_page && finish_page(tw))
1450                 return -1;
1451         *missing_countp = missing_count;
1452         *skip_countp = skip_count;
1453
1454         return 0;
1455 }
1456
1457 /**
1458  * write_flyrecord() - Write the flyrecord information
1459  *
1460  * Writes the header and pages of data for the "flyrecord" section. It also
1461  * writes out the counter-type info, selecting "[local]"
1462  *
1463  * @tw: Writer context
1464  * @out_format: Output format to use
1465  * @missing_countp: Returns number of missing functions (not found in function
1466  * list)
1467  * @skip_countp: Returns number of skipped functions (excluded from trace)
1468  *
1469  * Returns: 0 on success, -ve on error
1470  */
1471 static int write_flyrecord(struct twriter *tw, enum out_format_t out_format,
1472                            int *missing_countp, int *skip_countp)
1473 {
1474         int start, ret, len;
1475         FILE *fout = tw->fout;
1476         char str[200];
1477
1478         tw->ptr += fprintf(fout, "flyrecord%c", 0);
1479
1480         /* trace data */
1481         start = ALIGN(tw->ptr + 16, TRACE_PAGE_SIZE);
1482         tw->ptr += tputq(fout, start);
1483
1484         /* use a placeholder for the size */
1485         ret = push_len(tw, start, "flyrecord", 8);
1486         if (ret < 0)
1487                 return -1;
1488         tw->ptr += ret;
1489
1490         snprintf(str, sizeof(str),
1491                  "[local] global counter uptime perf mono mono_raw boot x86-tsc\n");
1492         len = strlen(str);
1493         tw->ptr += tputq(fout, len);
1494         tw->ptr += tputs(fout, str);
1495
1496         debug("trace text base %lx, map file %lx\n", text_base, text_offset);
1497
1498         ret = write_pages(tw, out_format, missing_countp, skip_countp);
1499         if (ret < 0) {
1500                 fprintf(stderr, "Cannot output pages\n");
1501                 return -1;
1502         }
1503
1504         ret = pop_len(tw, "flyrecord");
1505         if (ret < 0) {
1506                 fprintf(stderr, "Cannot finish flyrecord header\n");
1507                 return -1;
1508         }
1509
1510         return 0;
1511 }
1512
1513 /**
1514  * make_ftrace() - Write out an ftrace file
1515  *
1516  * See here for format:
1517  *
1518  * https://github.com/rostedt/trace-cmd/blob/master/Documentation/trace-cmd/trace-cmd.dat.v7.5.txt
1519  *
1520  * @fout: Output file
1521  * @out_format: Output format to use
1522  * Returns: 0 on success, -ve on error
1523  */
1524 static int make_ftrace(FILE *fout, enum out_format_t out_format)
1525 {
1526         int missing_count, skip_count;
1527         struct twriter tws, *tw = &tws;
1528         int ret;
1529
1530         memset(tw, '\0', sizeof(*tw));
1531         abuf_init(&tw->str_buf);
1532         tw->fout = fout;
1533
1534         tw->ptr = 0;
1535         ret = output_headers(tw);
1536         if (ret < 0) {
1537                 fprintf(stderr, "Cannot output headers\n");
1538                 return -1;
1539         }
1540         /* number of event systems files */
1541         tw->ptr += tputl(fout, 0);
1542
1543         ret = write_symbols(tw);
1544         if (ret < 0) {
1545                 fprintf(stderr, "Cannot write symbols\n");
1546                 return -1;
1547         }
1548
1549         ret = write_options(tw);
1550         if (ret < 0) {
1551                 fprintf(stderr, "Cannot write options\n");
1552                 return -1;
1553         }
1554
1555         ret = write_flyrecord(tw, out_format, &missing_count, &skip_count);
1556         if (ret < 0) {
1557                 fprintf(stderr, "Cannot write flyrecord\n");
1558                 return -1;
1559         }
1560
1561         info("ftrace: %d functions not found, %d excluded\n", missing_count,
1562              skip_count);
1563
1564         return 0;
1565 }
1566
1567 /**
1568  * create_node() - Create a new node in the flamegraph tree
1569  *
1570  * @msg: Message to use for debugging if something goes wrong
1571  * Returns: Pointer to newly created node, or NULL on error
1572  */
1573 static struct flame_node *create_node(const char *msg)
1574 {
1575         struct flame_node *node;
1576
1577         node = calloc(1, sizeof(*node));
1578         if (!node) {
1579                 fprintf(stderr, "Out of memory for %s\n", msg);
1580                 return NULL;
1581         }
1582         INIT_LIST_HEAD(&node->child_head);
1583
1584         return node;
1585 }
1586
1587 /**
1588  * process_call(): Add a call to the flamegraph info
1589  *
1590  * For function calls, if this call stack has been seen before, this increments
1591  * the call count, creating a new node if needed.
1592  *
1593  * For function returns, it adds up the time spent in this call stack,
1594  * subtracting the time spent by child functions.
1595  *
1596  * @state: Current flamegraph state
1597  * @entry: true if this is a function entry, false if a function exit
1598  * @timestamp: Timestamp from the trace file (in microseconds)
1599  * @func: Function that was called/returned from
1600  *
1601  * Returns: 0 on success, -ve on error
1602  */
1603 static int process_call(struct flame_state *state, bool entry, ulong timestamp,
1604                         struct func_info *func)
1605 {
1606         struct flame_node *node = state->node;
1607
1608         if (entry) {
1609                 struct flame_node *child, *chd;
1610
1611                 /* see if we have this as a child node already */
1612                 child = NULL;
1613                 list_for_each_entry(chd, &node->child_head, sibling_node) {
1614                         if (chd->func == func) {
1615                                 child = chd;
1616                                 break;
1617                         }
1618                 }
1619                 if (!child) {
1620                         /* create a new node */
1621                         child = create_node("child");
1622                         if (!child)
1623                                 return -1;
1624                         list_add_tail(&child->sibling_node, &node->child_head);
1625                         child->func = func;
1626                         child->parent = node;
1627                         state->nodes++;
1628                 }
1629                 debug("entry %s: move from %s to %s\n", func->name,
1630                       node->func ? node->func->name : "(root)",
1631                       child->func->name);
1632                 child->count++;
1633                 node = child;
1634         } else if (node->parent) {
1635                 debug("exit  %s: move from %s to %s\n", func->name,
1636                       node->func->name, node->parent->func ?
1637                       node->parent->func->name : "(root)");
1638                 node = node->parent;
1639         }
1640
1641         state->node = node;
1642
1643         return 0;
1644 }
1645
1646 /**
1647  * make_flame_tree() - Create a tree of stack traces
1648  *
1649  * Set up a tree, with the root node having the top-level functions as children
1650  * and the leaf nodes being leaf functions. Each node has a count of how many
1651  * times this function appears in the trace
1652  *
1653  * @treep: Returns the resulting flamegraph tree
1654  * Returns: 0 on success, -ve on error
1655  */
1656 static int make_flame_tree(struct flame_node **treep)
1657 {
1658         struct flame_state state;
1659         struct flame_node *tree;
1660         struct trace_call *call;
1661         int missing_count = 0;
1662         int i, depth;
1663
1664         /*
1665          * The first thing in the trace may not be the top-level function, so
1666          * set the initial depth so that no function goes below depth 0
1667          */
1668         depth = -calc_min_depth();
1669
1670         tree = create_node("tree");
1671         if (!tree)
1672                 return -1;
1673         state.node = tree;
1674         state.nodes = 0;
1675
1676         for (i = 0, call = call_list; i < call_count; i++, call++) {
1677                 bool entry = TRACE_CALL_TYPE(call) == FUNCF_ENTRY;
1678                 ulong timestamp = call->flags & FUNCF_TIMESTAMP_MASK;
1679                 struct func_info *func;
1680
1681                 if (entry)
1682                         depth++;
1683                 else
1684                         depth--;
1685
1686                 func = find_func_by_offset(call->func);
1687                 if (!func) {
1688                         warn("Cannot find function at %lx\n",
1689                              text_offset + call->func);
1690                         missing_count++;
1691                         continue;
1692                 }
1693
1694                 if (process_call(&state, entry, timestamp, func))
1695                         return -1;
1696         }
1697         fprintf(stderr, "%d nodes\n", state.nodes);
1698         *treep = tree;
1699
1700         return 0;
1701 }
1702
1703 /**
1704  * output_tree() - Output a flamegraph tree
1705  *
1706  * Writes the tree out to a file in a format suitable for flamegraph.pl
1707  *
1708  * This works by maintaining a string shared across all recursive calls. The
1709  * function name for this node is added to the existing string, to make up the
1710  * full call-stack description. For example, on entry, @str might contain:
1711  *
1712  *    "initf_bootstage;bootstage_mark_name"
1713  *                                        ^ @base
1714  *
1715  * with @base pointing to the \0 at the end of the string. This function adds
1716  * a ';' following by the name of the current function, e.g. "timer_get_boot_us"
1717  * as well as the output value, to get the full line:
1718  *
1719  * initf_bootstage;bootstage_mark_name;timer_get_boot_us 123
1720  *
1721  * @fout: Output file
1722  * @node: Node to output (pass the whole tree at first)
1723  * @str: String to use to build the output line (e.g. 500 charas long)
1724  * @maxlen: Maximum length of string
1725  * @base: Current base position in the string
1726  * @treep: Returns the resulting flamegraph tree
1727  * Returns 0 if OK, -1 on error
1728  */
1729 static int output_tree(FILE *fout, const struct flame_node *node,
1730                        char *str, int maxlen, int base)
1731 {
1732         const struct flame_node *child;
1733         int pos;
1734
1735         if (node->count)
1736                 fprintf(fout, "%s %d\n", str, node->count);
1737
1738         pos = base;
1739         if (pos)
1740                 str[pos++] = ';';
1741         list_for_each_entry(child, &node->child_head, sibling_node) {
1742                 int len;
1743
1744                 len = strlen(child->func->name);
1745                 if (pos + len + 1 >= maxlen) {
1746                         fprintf(stderr, "String too short (%d chars)\n",
1747                                 maxlen);
1748                         return -1;
1749                 }
1750                 strcpy(str + pos, child->func->name);
1751                 if (output_tree(fout, child, str, maxlen, pos + len))
1752                         return -1;
1753         }
1754
1755         return 0;
1756 }
1757
1758 /**
1759  * make_flamegraph() - Write out a flame graph
1760  *
1761  * @fout: Output file
1762  * Returns 0 if OK, -1 on error
1763  */
1764 static int make_flamegraph(FILE *fout)
1765 {
1766         struct flame_node *tree;
1767         char str[500];
1768
1769         if (make_flame_tree(&tree))
1770                 return -1;
1771
1772         *str = '\0';
1773         if (output_tree(fout, tree, str, sizeof(str), 0))
1774                 return -1;
1775
1776         return 0;
1777 }
1778
1779 /**
1780  * prof_tool() - Performs requested action
1781  *
1782  * @argc: Number of arguments (used to obtain the command
1783  * @argv: List of arguments
1784  * @trace_fname: Filename of input file (trace data from U-Boot)
1785  * @map_fname: Filename of map file (System.map from U-Boot)
1786  * @trace_config_fname: Trace-configuration file, or NULL if none
1787  * @out_fname: Output filename
1788  */
1789 static int prof_tool(int argc, char *const argv[],
1790                      const char *trace_fname, const char *map_fname,
1791                      const char *trace_config_fname, const char *out_fname,
1792                      enum out_format_t out_format)
1793 {
1794         int err = 0;
1795
1796         if (read_map_file(map_fname))
1797                 return -1;
1798         if (trace_fname && read_trace_file(trace_fname))
1799                 return -1;
1800         if (trace_config_fname && read_trace_config_file(trace_config_fname))
1801                 return -1;
1802
1803         check_trace_config();
1804
1805         for (; argc; argc--, argv++) {
1806                 const char *cmd = *argv;
1807
1808                 if (!strcmp(cmd, "dump-ftrace")) {
1809                         FILE *fout;
1810
1811                         if (out_format != OUT_FMT_FUNCTION &&
1812                             out_format != OUT_FMT_FUNCGRAPH)
1813                                 out_format = OUT_FMT_FUNCTION;
1814                         fout = fopen(out_fname, "w");
1815                         if (!fout) {
1816                                 fprintf(stderr, "Cannot write file '%s'\n",
1817                                         out_fname);
1818                                 return -1;
1819                         }
1820                         err = make_ftrace(fout, out_format);
1821                         fclose(fout);
1822                 } else if (!strcmp(cmd, "dump-flamegraph")) {
1823                         FILE *fout;
1824
1825                         fout = fopen(out_fname, "w");
1826                         if (!fout) {
1827                                 fprintf(stderr, "Cannot write file '%s'\n",
1828                                         out_fname);
1829                                 return -1;
1830                         }
1831                         err = make_flamegraph(fout);
1832                         fclose(fout);
1833                 } else {
1834                         warn("Unknown command '%s'\n", cmd);
1835                 }
1836         }
1837
1838         return err;
1839 }
1840
1841 int main(int argc, char *argv[])
1842 {
1843         enum out_format_t out_format = OUT_FMT_DEFAULT;
1844         const char *map_fname = "System.map";
1845         const char *trace_fname = NULL;
1846         const char *config_fname = NULL;
1847         const char *out_fname = NULL;
1848         int opt;
1849
1850         verbose = 2;
1851         while ((opt = getopt(argc, argv, "c:f:m:o:t:v:")) != -1) {
1852                 switch (opt) {
1853                 case 'c':
1854                         config_fname = optarg;
1855                         break;
1856                 case 'f':
1857                         if (!strcmp("function", optarg)) {
1858                                 out_format = OUT_FMT_FUNCTION;
1859                         } else if (!strcmp("funcgraph", optarg)) {
1860                                 out_format = OUT_FMT_FUNCGRAPH;
1861                         } else {
1862                                 fprintf(stderr,
1863                                         "Invalid format: use function, funcgraph, calls, timing\n");
1864                                 exit(1);
1865                         }
1866                         break;
1867                 case 'm':
1868                         map_fname = optarg;
1869                         break;
1870                 case 'o':
1871                         out_fname = optarg;
1872                         break;
1873                 case 't':
1874                         trace_fname = optarg;
1875                         break;
1876                 case 'v':
1877                         verbose = atoi(optarg);
1878                         break;
1879                 default:
1880                         usage();
1881                 }
1882         }
1883         argc -= optind; argv += optind;
1884         if (argc < 1)
1885                 usage();
1886
1887         if (!out_fname || !map_fname || !trace_fname) {
1888                 fprintf(stderr,
1889                         "Must provide trace data, System.map file and output file\n");
1890                 usage();
1891         }
1892
1893         debug("Debug enabled\n");
1894         return prof_tool(argc, argv, trace_fname, map_fname, config_fname,
1895                          out_fname, out_format);
1896 }