perf report: Adjust column width to the values sampled
[linux-2.6] / tools / perf / builtin-report.c
1 /*
2  * builtin-report.c
3  *
4  * Builtin report command: Analyze the perf.data input file,
5  * look up and read DSOs and symbol information and display
6  * a histogram of results, along various sorting keys.
7  */
8 #include "builtin.h"
9
10 #include "util/util.h"
11
12 #include "util/color.h"
13 #include <linux/list.h>
14 #include "util/cache.h"
15 #include <linux/rbtree.h>
16 #include "util/symbol.h"
17 #include "util/string.h"
18 #include "util/callchain.h"
19 #include "util/strlist.h"
20
21 #include "perf.h"
22 #include "util/header.h"
23
24 #include "util/parse-options.h"
25 #include "util/parse-events.h"
26
27 #define SHOW_KERNEL     1
28 #define SHOW_USER       2
29 #define SHOW_HV         4
30
31 static char             const *input_name = "perf.data";
32 static char             *vmlinux = NULL;
33
34 static char             default_sort_order[] = "comm,dso";
35 static char             *sort_order = default_sort_order;
36 static char             *dso_list_str, *comm_list_str, *sym_list_str,
37                         *col_width_list_str;
38 static struct strlist   *dso_list, *comm_list, *sym_list;
39 static char             *field_sep;
40
41 static int              input;
42 static int              show_mask = SHOW_KERNEL | SHOW_USER | SHOW_HV;
43
44 static int              dump_trace = 0;
45 #define dprintf(x...)   do { if (dump_trace) printf(x); } while (0)
46 #define cdprintf(x...)  do { if (dump_trace) color_fprintf(stdout, color, x); } while (0)
47
48 static int              verbose;
49 #define eprintf(x...)   do { if (verbose) fprintf(stderr, x); } while (0)
50
51 static int              modules;
52
53 static int              full_paths;
54
55 static unsigned long    page_size;
56 static unsigned long    mmap_window = 32;
57
58 static char             default_parent_pattern[] = "^sys_|^do_page_fault";
59 static char             *parent_pattern = default_parent_pattern;
60 static regex_t          parent_regex;
61
62 static int              exclude_other = 1;
63
64 static char             callchain_default_opt[] = "fractal,0.5";
65
66 static int              callchain;
67
68 static
69 struct callchain_param  callchain_param = {
70         .mode   = CHAIN_GRAPH_ABS,
71         .min_percent = 0.5
72 };
73
74 static u64              sample_type;
75
76 struct ip_event {
77         struct perf_event_header header;
78         u64 ip;
79         u32 pid, tid;
80         unsigned char __more_data[];
81 };
82
83 struct mmap_event {
84         struct perf_event_header header;
85         u32 pid, tid;
86         u64 start;
87         u64 len;
88         u64 pgoff;
89         char filename[PATH_MAX];
90 };
91
92 struct comm_event {
93         struct perf_event_header header;
94         u32 pid, tid;
95         char comm[16];
96 };
97
98 struct fork_event {
99         struct perf_event_header header;
100         u32 pid, ppid;
101 };
102
103 struct period_event {
104         struct perf_event_header header;
105         u64 time;
106         u64 id;
107         u64 sample_period;
108 };
109
110 struct lost_event {
111         struct perf_event_header header;
112         u64 id;
113         u64 lost;
114 };
115
116 struct read_event {
117         struct perf_event_header header;
118         u32 pid,tid;
119         u64 value;
120         u64 format[3];
121 };
122
123 typedef union event_union {
124         struct perf_event_header        header;
125         struct ip_event                 ip;
126         struct mmap_event               mmap;
127         struct comm_event               comm;
128         struct fork_event               fork;
129         struct period_event             period;
130         struct lost_event               lost;
131         struct read_event               read;
132 } event_t;
133
134 static int repsep_fprintf(FILE *fp, const char *fmt, ...)
135 {
136         int n;
137         va_list ap;
138
139         va_start(ap, fmt);
140         if (!field_sep)
141                 n = vfprintf(fp, fmt, ap);
142         else {
143                 char *bf = NULL;
144                 n = vasprintf(&bf, fmt, ap);
145                 if (n > 0) {
146                         char *sep = bf;
147                         while (1) {
148                                 sep = strchr(sep, *field_sep);
149                                 if (sep == NULL)
150                                         break;
151                                 *sep = '.';
152                         }
153                 }
154                 fputs(bf, fp);
155                 free(bf);
156         }
157         va_end(ap);
158         return n;
159 }
160
161 static LIST_HEAD(dsos);
162 static struct dso *kernel_dso;
163 static struct dso *vdso;
164 static struct dso *hypervisor_dso;
165
166 static void dsos__add(struct dso *dso)
167 {
168         list_add_tail(&dso->node, &dsos);
169 }
170
171 static struct dso *dsos__find(const char *name)
172 {
173         struct dso *pos;
174
175         list_for_each_entry(pos, &dsos, node)
176                 if (strcmp(pos->name, name) == 0)
177                         return pos;
178         return NULL;
179 }
180
181 static struct dso *dsos__findnew(const char *name)
182 {
183         struct dso *dso = dsos__find(name);
184         int nr;
185
186         if (dso)
187                 return dso;
188
189         dso = dso__new(name, 0);
190         if (!dso)
191                 goto out_delete_dso;
192
193         nr = dso__load(dso, NULL, verbose);
194         if (nr < 0) {
195                 eprintf("Failed to open: %s\n", name);
196                 goto out_delete_dso;
197         }
198         if (!nr)
199                 eprintf("No symbols found in: %s, maybe install a debug package?\n", name);
200
201         dsos__add(dso);
202
203         return dso;
204
205 out_delete_dso:
206         dso__delete(dso);
207         return NULL;
208 }
209
210 static void dsos__fprintf(FILE *fp)
211 {
212         struct dso *pos;
213
214         list_for_each_entry(pos, &dsos, node)
215                 dso__fprintf(pos, fp);
216 }
217
218 static struct symbol *vdso__find_symbol(struct dso *dso, u64 ip)
219 {
220         return dso__find_symbol(dso, ip);
221 }
222
223 static int load_kernel(void)
224 {
225         int err;
226
227         kernel_dso = dso__new("[kernel]", 0);
228         if (!kernel_dso)
229                 return -1;
230
231         err = dso__load_kernel(kernel_dso, vmlinux, NULL, verbose, modules);
232         if (err <= 0) {
233                 dso__delete(kernel_dso);
234                 kernel_dso = NULL;
235         } else
236                 dsos__add(kernel_dso);
237
238         vdso = dso__new("[vdso]", 0);
239         if (!vdso)
240                 return -1;
241
242         vdso->find_symbol = vdso__find_symbol;
243
244         dsos__add(vdso);
245
246         hypervisor_dso = dso__new("[hypervisor]", 0);
247         if (!hypervisor_dso)
248                 return -1;
249         dsos__add(hypervisor_dso);
250
251         return err;
252 }
253
254 static char __cwd[PATH_MAX];
255 static char *cwd = __cwd;
256 static int cwdlen;
257
258 static int strcommon(const char *pathname)
259 {
260         int n = 0;
261
262         while (pathname[n] == cwd[n] && n < cwdlen)
263                 ++n;
264
265         return n;
266 }
267
268 struct map {
269         struct list_head node;
270         u64      start;
271         u64      end;
272         u64      pgoff;
273         u64      (*map_ip)(struct map *, u64);
274         struct dso       *dso;
275 };
276
277 static u64 map__map_ip(struct map *map, u64 ip)
278 {
279         return ip - map->start + map->pgoff;
280 }
281
282 static u64 vdso__map_ip(struct map *map __used, u64 ip)
283 {
284         return ip;
285 }
286
287 static inline int is_anon_memory(const char *filename)
288 {
289         return strcmp(filename, "//anon") == 0;
290 }
291
292 static struct map *map__new(struct mmap_event *event)
293 {
294         struct map *self = malloc(sizeof(*self));
295
296         if (self != NULL) {
297                 const char *filename = event->filename;
298                 char newfilename[PATH_MAX];
299                 int anon;
300
301                 if (cwd) {
302                         int n = strcommon(filename);
303
304                         if (n == cwdlen) {
305                                 snprintf(newfilename, sizeof(newfilename),
306                                          ".%s", filename + n);
307                                 filename = newfilename;
308                         }
309                 }
310
311                 anon = is_anon_memory(filename);
312
313                 if (anon) {
314                         snprintf(newfilename, sizeof(newfilename), "/tmp/perf-%d.map", event->pid);
315                         filename = newfilename;
316                 }
317
318                 self->start = event->start;
319                 self->end   = event->start + event->len;
320                 self->pgoff = event->pgoff;
321
322                 self->dso = dsos__findnew(filename);
323                 if (self->dso == NULL)
324                         goto out_delete;
325
326                 if (self->dso == vdso || anon)
327                         self->map_ip = vdso__map_ip;
328                 else
329                         self->map_ip = map__map_ip;
330         }
331         return self;
332 out_delete:
333         free(self);
334         return NULL;
335 }
336
337 static struct map *map__clone(struct map *self)
338 {
339         struct map *map = malloc(sizeof(*self));
340
341         if (!map)
342                 return NULL;
343
344         memcpy(map, self, sizeof(*self));
345
346         return map;
347 }
348
349 static int map__overlap(struct map *l, struct map *r)
350 {
351         if (l->start > r->start) {
352                 struct map *t = l;
353                 l = r;
354                 r = t;
355         }
356
357         if (l->end > r->start)
358                 return 1;
359
360         return 0;
361 }
362
363 static size_t map__fprintf(struct map *self, FILE *fp)
364 {
365         return fprintf(fp, " %Lx-%Lx %Lx %s\n",
366                        self->start, self->end, self->pgoff, self->dso->name);
367 }
368
369
370 struct thread {
371         struct rb_node   rb_node;
372         struct list_head maps;
373         pid_t            pid;
374         char             *comm;
375 };
376
377 static struct thread *thread__new(pid_t pid)
378 {
379         struct thread *self = malloc(sizeof(*self));
380
381         if (self != NULL) {
382                 self->pid = pid;
383                 self->comm = malloc(32);
384                 if (self->comm)
385                         snprintf(self->comm, 32, ":%d", self->pid);
386                 INIT_LIST_HEAD(&self->maps);
387         }
388
389         return self;
390 }
391
392 static unsigned int dsos__col_width,
393                     comms__col_width,
394                     threads__col_width;
395
396 static int thread__set_comm(struct thread *self, const char *comm)
397 {
398         if (self->comm)
399                 free(self->comm);
400         self->comm = strdup(comm);
401         if (!self->comm)
402                 return -ENOMEM;
403
404         if (!col_width_list_str && !field_sep &&
405             (!comm_list || strlist__has_entry(comm_list, comm))) {
406                 unsigned int slen = strlen(comm);
407                 if (slen > comms__col_width) {
408                         comms__col_width = slen;
409                         threads__col_width = slen + 6;
410                 }
411         }
412
413         return 0;
414 }
415
416 static size_t thread__fprintf(struct thread *self, FILE *fp)
417 {
418         struct map *pos;
419         size_t ret = fprintf(fp, "Thread %d %s\n", self->pid, self->comm);
420
421         list_for_each_entry(pos, &self->maps, node)
422                 ret += map__fprintf(pos, fp);
423
424         return ret;
425 }
426
427
428 static struct rb_root threads;
429 static struct thread *last_match;
430
431 static struct thread *threads__findnew(pid_t pid)
432 {
433         struct rb_node **p = &threads.rb_node;
434         struct rb_node *parent = NULL;
435         struct thread *th;
436
437         /*
438          * Font-end cache - PID lookups come in blocks,
439          * so most of the time we dont have to look up
440          * the full rbtree:
441          */
442         if (last_match && last_match->pid == pid)
443                 return last_match;
444
445         while (*p != NULL) {
446                 parent = *p;
447                 th = rb_entry(parent, struct thread, rb_node);
448
449                 if (th->pid == pid) {
450                         last_match = th;
451                         return th;
452                 }
453
454                 if (pid < th->pid)
455                         p = &(*p)->rb_left;
456                 else
457                         p = &(*p)->rb_right;
458         }
459
460         th = thread__new(pid);
461         if (th != NULL) {
462                 rb_link_node(&th->rb_node, parent, p);
463                 rb_insert_color(&th->rb_node, &threads);
464                 last_match = th;
465         }
466
467         return th;
468 }
469
470 static void thread__insert_map(struct thread *self, struct map *map)
471 {
472         struct map *pos, *tmp;
473
474         list_for_each_entry_safe(pos, tmp, &self->maps, node) {
475                 if (map__overlap(pos, map)) {
476                         if (verbose >= 2) {
477                                 printf("overlapping maps:\n");
478                                 map__fprintf(map, stdout);
479                                 map__fprintf(pos, stdout);
480                         }
481
482                         if (map->start <= pos->start && map->end > pos->start)
483                                 pos->start = map->end;
484
485                         if (map->end >= pos->end && map->start < pos->end)
486                                 pos->end = map->start;
487
488                         if (verbose >= 2) {
489                                 printf("after collision:\n");
490                                 map__fprintf(pos, stdout);
491                         }
492
493                         if (pos->start >= pos->end) {
494                                 list_del_init(&pos->node);
495                                 free(pos);
496                         }
497                 }
498         }
499
500         list_add_tail(&map->node, &self->maps);
501 }
502
503 static int thread__fork(struct thread *self, struct thread *parent)
504 {
505         struct map *map;
506
507         if (self->comm)
508                 free(self->comm);
509         self->comm = strdup(parent->comm);
510         if (!self->comm)
511                 return -ENOMEM;
512
513         list_for_each_entry(map, &parent->maps, node) {
514                 struct map *new = map__clone(map);
515                 if (!new)
516                         return -ENOMEM;
517                 thread__insert_map(self, new);
518         }
519
520         return 0;
521 }
522
523 static struct map *thread__find_map(struct thread *self, u64 ip)
524 {
525         struct map *pos;
526
527         if (self == NULL)
528                 return NULL;
529
530         list_for_each_entry(pos, &self->maps, node)
531                 if (ip >= pos->start && ip <= pos->end)
532                         return pos;
533
534         return NULL;
535 }
536
537 static size_t threads__fprintf(FILE *fp)
538 {
539         size_t ret = 0;
540         struct rb_node *nd;
541
542         for (nd = rb_first(&threads); nd; nd = rb_next(nd)) {
543                 struct thread *pos = rb_entry(nd, struct thread, rb_node);
544
545                 ret += thread__fprintf(pos, fp);
546         }
547
548         return ret;
549 }
550
551 /*
552  * histogram, sorted on item, collects counts
553  */
554
555 static struct rb_root hist;
556
557 struct hist_entry {
558         struct rb_node          rb_node;
559
560         struct thread           *thread;
561         struct map              *map;
562         struct dso              *dso;
563         struct symbol           *sym;
564         struct symbol           *parent;
565         u64                     ip;
566         char                    level;
567         struct callchain_node   callchain;
568         struct rb_root          sorted_chain;
569
570         u64                     count;
571 };
572
573 /*
574  * configurable sorting bits
575  */
576
577 struct sort_entry {
578         struct list_head list;
579
580         char *header;
581
582         int64_t (*cmp)(struct hist_entry *, struct hist_entry *);
583         int64_t (*collapse)(struct hist_entry *, struct hist_entry *);
584         size_t  (*print)(FILE *fp, struct hist_entry *, unsigned int width);
585         unsigned int *width;
586 };
587
588 static int64_t cmp_null(void *l, void *r)
589 {
590         if (!l && !r)
591                 return 0;
592         else if (!l)
593                 return -1;
594         else
595                 return 1;
596 }
597
598 /* --sort pid */
599
600 static int64_t
601 sort__thread_cmp(struct hist_entry *left, struct hist_entry *right)
602 {
603         return right->thread->pid - left->thread->pid;
604 }
605
606 static size_t
607 sort__thread_print(FILE *fp, struct hist_entry *self, unsigned int width)
608 {
609         return repsep_fprintf(fp, "%*s:%5d", width - 6,
610                               self->thread->comm ?: "", self->thread->pid);
611 }
612
613 static struct sort_entry sort_thread = {
614         .header = "Command:  Pid",
615         .cmp    = sort__thread_cmp,
616         .print  = sort__thread_print,
617         .width  = &threads__col_width,
618 };
619
620 /* --sort comm */
621
622 static int64_t
623 sort__comm_cmp(struct hist_entry *left, struct hist_entry *right)
624 {
625         return right->thread->pid - left->thread->pid;
626 }
627
628 static int64_t
629 sort__comm_collapse(struct hist_entry *left, struct hist_entry *right)
630 {
631         char *comm_l = left->thread->comm;
632         char *comm_r = right->thread->comm;
633
634         if (!comm_l || !comm_r)
635                 return cmp_null(comm_l, comm_r);
636
637         return strcmp(comm_l, comm_r);
638 }
639
640 static size_t
641 sort__comm_print(FILE *fp, struct hist_entry *self, unsigned int width)
642 {
643         return repsep_fprintf(fp, "%*s", width, self->thread->comm);
644 }
645
646 static struct sort_entry sort_comm = {
647         .header         = "Command",
648         .cmp            = sort__comm_cmp,
649         .collapse       = sort__comm_collapse,
650         .print          = sort__comm_print,
651         .width          = &comms__col_width,
652 };
653
654 /* --sort dso */
655
656 static int64_t
657 sort__dso_cmp(struct hist_entry *left, struct hist_entry *right)
658 {
659         struct dso *dso_l = left->dso;
660         struct dso *dso_r = right->dso;
661
662         if (!dso_l || !dso_r)
663                 return cmp_null(dso_l, dso_r);
664
665         return strcmp(dso_l->name, dso_r->name);
666 }
667
668 static size_t
669 sort__dso_print(FILE *fp, struct hist_entry *self, unsigned int width)
670 {
671         if (self->dso)
672                 return repsep_fprintf(fp, "%-*s", width, self->dso->name);
673
674         return repsep_fprintf(fp, "%*llx", width, (u64)self->ip);
675 }
676
677 static struct sort_entry sort_dso = {
678         .header = "Shared Object",
679         .cmp    = sort__dso_cmp,
680         .print  = sort__dso_print,
681         .width  = &dsos__col_width,
682 };
683
684 /* --sort symbol */
685
686 static int64_t
687 sort__sym_cmp(struct hist_entry *left, struct hist_entry *right)
688 {
689         u64 ip_l, ip_r;
690
691         if (left->sym == right->sym)
692                 return 0;
693
694         ip_l = left->sym ? left->sym->start : left->ip;
695         ip_r = right->sym ? right->sym->start : right->ip;
696
697         return (int64_t)(ip_r - ip_l);
698 }
699
700 static size_t
701 sort__sym_print(FILE *fp, struct hist_entry *self, unsigned int width __used)
702 {
703         size_t ret = 0;
704
705         if (verbose)
706                 ret += repsep_fprintf(fp, "%#018llx  ", (u64)self->ip);
707
708         if (self->sym) {
709                 ret += repsep_fprintf(fp, "[%c] %s",
710                         self->dso == kernel_dso ? 'k' :
711                         self->dso == hypervisor_dso ? 'h' : '.', self->sym->name);
712
713                 if (self->sym->module)
714                         ret += repsep_fprintf(fp, "\t[%s]",
715                                              self->sym->module->name);
716         } else {
717                 ret += repsep_fprintf(fp, "%#016llx", (u64)self->ip);
718         }
719
720         return ret;
721 }
722
723 static struct sort_entry sort_sym = {
724         .header = "Symbol",
725         .cmp    = sort__sym_cmp,
726         .print  = sort__sym_print,
727 };
728
729 /* --sort parent */
730
731 static int64_t
732 sort__parent_cmp(struct hist_entry *left, struct hist_entry *right)
733 {
734         struct symbol *sym_l = left->parent;
735         struct symbol *sym_r = right->parent;
736
737         if (!sym_l || !sym_r)
738                 return cmp_null(sym_l, sym_r);
739
740         return strcmp(sym_l->name, sym_r->name);
741 }
742
743 static size_t
744 sort__parent_print(FILE *fp, struct hist_entry *self, unsigned int width)
745 {
746         return repsep_fprintf(fp, "%-*s", width,
747                               self->parent ? self->parent->name : "[other]");
748 }
749
750 static unsigned int parent_symbol__col_width;
751
752 static struct sort_entry sort_parent = {
753         .header = "Parent symbol",
754         .cmp    = sort__parent_cmp,
755         .print  = sort__parent_print,
756         .width  = &parent_symbol__col_width,
757 };
758
759 static int sort__need_collapse = 0;
760 static int sort__has_parent = 0;
761
762 struct sort_dimension {
763         char                    *name;
764         struct sort_entry       *entry;
765         int                     taken;
766 };
767
768 static struct sort_dimension sort_dimensions[] = {
769         { .name = "pid",        .entry = &sort_thread,  },
770         { .name = "comm",       .entry = &sort_comm,    },
771         { .name = "dso",        .entry = &sort_dso,     },
772         { .name = "symbol",     .entry = &sort_sym,     },
773         { .name = "parent",     .entry = &sort_parent,  },
774 };
775
776 static LIST_HEAD(hist_entry__sort_list);
777
778 static int sort_dimension__add(char *tok)
779 {
780         unsigned int i;
781
782         for (i = 0; i < ARRAY_SIZE(sort_dimensions); i++) {
783                 struct sort_dimension *sd = &sort_dimensions[i];
784
785                 if (sd->taken)
786                         continue;
787
788                 if (strncasecmp(tok, sd->name, strlen(tok)))
789                         continue;
790
791                 if (sd->entry->collapse)
792                         sort__need_collapse = 1;
793
794                 if (sd->entry == &sort_parent) {
795                         int ret = regcomp(&parent_regex, parent_pattern, REG_EXTENDED);
796                         if (ret) {
797                                 char err[BUFSIZ];
798
799                                 regerror(ret, &parent_regex, err, sizeof(err));
800                                 fprintf(stderr, "Invalid regex: %s\n%s",
801                                         parent_pattern, err);
802                                 exit(-1);
803                         }
804                         sort__has_parent = 1;
805                 }
806
807                 list_add_tail(&sd->entry->list, &hist_entry__sort_list);
808                 sd->taken = 1;
809
810                 return 0;
811         }
812
813         return -ESRCH;
814 }
815
816 static int64_t
817 hist_entry__cmp(struct hist_entry *left, struct hist_entry *right)
818 {
819         struct sort_entry *se;
820         int64_t cmp = 0;
821
822         list_for_each_entry(se, &hist_entry__sort_list, list) {
823                 cmp = se->cmp(left, right);
824                 if (cmp)
825                         break;
826         }
827
828         return cmp;
829 }
830
831 static int64_t
832 hist_entry__collapse(struct hist_entry *left, struct hist_entry *right)
833 {
834         struct sort_entry *se;
835         int64_t cmp = 0;
836
837         list_for_each_entry(se, &hist_entry__sort_list, list) {
838                 int64_t (*f)(struct hist_entry *, struct hist_entry *);
839
840                 f = se->collapse ?: se->cmp;
841
842                 cmp = f(left, right);
843                 if (cmp)
844                         break;
845         }
846
847         return cmp;
848 }
849
850 static size_t ipchain__fprintf_graph_line(FILE *fp, int depth, int depth_mask)
851 {
852         int i;
853         size_t ret = 0;
854
855         ret += fprintf(fp, "%s", "                ");
856
857         for (i = 0; i < depth; i++)
858                 if (depth_mask & (1 << i))
859                         ret += fprintf(fp, "|          ");
860                 else
861                         ret += fprintf(fp, "           ");
862
863         ret += fprintf(fp, "\n");
864
865         return ret;
866 }
867 static size_t
868 ipchain__fprintf_graph(FILE *fp, struct callchain_list *chain, int depth,
869                        int depth_mask, int count, u64 total_samples,
870                        int hits)
871 {
872         int i;
873         size_t ret = 0;
874
875         ret += fprintf(fp, "%s", "                ");
876         for (i = 0; i < depth; i++) {
877                 if (depth_mask & (1 << i))
878                         ret += fprintf(fp, "|");
879                 else
880                         ret += fprintf(fp, " ");
881                 if (!count && i == depth - 1) {
882                         double percent;
883
884                         percent = hits * 100.0 / total_samples;
885                         ret += percent_color_fprintf(fp, "--%2.2f%%-- ", percent);
886                 } else
887                         ret += fprintf(fp, "%s", "          ");
888         }
889         if (chain->sym)
890                 ret += fprintf(fp, "%s\n", chain->sym->name);
891         else
892                 ret += fprintf(fp, "%p\n", (void *)(long)chain->ip);
893
894         return ret;
895 }
896
897 static size_t
898 callchain__fprintf_graph(FILE *fp, struct callchain_node *self,
899                         u64 total_samples, int depth, int depth_mask)
900 {
901         struct rb_node *node, *next;
902         struct callchain_node *child;
903         struct callchain_list *chain;
904         int new_depth_mask = depth_mask;
905         u64 new_total;
906         size_t ret = 0;
907         int i;
908
909         if (callchain_param.mode == CHAIN_GRAPH_REL)
910                 new_total = self->cumul_hit;
911         else
912                 new_total = total_samples;
913
914         node = rb_first(&self->rb_root);
915         while (node) {
916                 child = rb_entry(node, struct callchain_node, rb_node);
917
918                 /*
919                  * The depth mask manages the output of pipes that show
920                  * the depth. We don't want to keep the pipes of the current
921                  * level for the last child of this depth
922                  */
923                 next = rb_next(node);
924                 if (!next)
925                         new_depth_mask &= ~(1 << (depth - 1));
926
927                 /*
928                  * But we keep the older depth mask for the line seperator
929                  * to keep the level link until we reach the last child
930                  */
931                 ret += ipchain__fprintf_graph_line(fp, depth, depth_mask);
932                 i = 0;
933                 list_for_each_entry(chain, &child->val, list) {
934                         if (chain->ip >= PERF_CONTEXT_MAX)
935                                 continue;
936                         ret += ipchain__fprintf_graph(fp, chain, depth,
937                                                       new_depth_mask, i++,
938                                                       new_total,
939                                                       child->cumul_hit);
940                 }
941                 ret += callchain__fprintf_graph(fp, child, new_total,
942                                                 depth + 1,
943                                                 new_depth_mask | (1 << depth));
944                 node = next;
945         }
946
947         return ret;
948 }
949
950 static size_t
951 callchain__fprintf_flat(FILE *fp, struct callchain_node *self,
952                         u64 total_samples)
953 {
954         struct callchain_list *chain;
955         size_t ret = 0;
956
957         if (!self)
958                 return 0;
959
960         ret += callchain__fprintf_flat(fp, self->parent, total_samples);
961
962
963         list_for_each_entry(chain, &self->val, list) {
964                 if (chain->ip >= PERF_CONTEXT_MAX)
965                         continue;
966                 if (chain->sym)
967                         ret += fprintf(fp, "                %s\n", chain->sym->name);
968                 else
969                         ret += fprintf(fp, "                %p\n",
970                                         (void *)(long)chain->ip);
971         }
972
973         return ret;
974 }
975
976 static size_t
977 hist_entry_callchain__fprintf(FILE *fp, struct hist_entry *self,
978                               u64 total_samples)
979 {
980         struct rb_node *rb_node;
981         struct callchain_node *chain;
982         size_t ret = 0;
983
984         rb_node = rb_first(&self->sorted_chain);
985         while (rb_node) {
986                 double percent;
987
988                 chain = rb_entry(rb_node, struct callchain_node, rb_node);
989                 percent = chain->hit * 100.0 / total_samples;
990                 switch (callchain_param.mode) {
991                 case CHAIN_FLAT:
992                         ret += percent_color_fprintf(fp, "           %6.2f%%\n",
993                                                      percent);
994                         ret += callchain__fprintf_flat(fp, chain, total_samples);
995                         break;
996                 case CHAIN_GRAPH_ABS: /* Falldown */
997                 case CHAIN_GRAPH_REL:
998                         ret += callchain__fprintf_graph(fp, chain,
999                                                         total_samples, 1, 1);
1000                 default:
1001                         break;
1002                 }
1003                 ret += fprintf(fp, "\n");
1004                 rb_node = rb_next(rb_node);
1005         }
1006
1007         return ret;
1008 }
1009
1010
1011 static size_t
1012 hist_entry__fprintf(FILE *fp, struct hist_entry *self, u64 total_samples)
1013 {
1014         struct sort_entry *se;
1015         size_t ret;
1016
1017         if (exclude_other && !self->parent)
1018                 return 0;
1019
1020         if (total_samples)
1021                 ret = percent_color_fprintf(fp,
1022                                             field_sep ? "%.2f" : "   %6.2f%%",
1023                                         (self->count * 100.0) / total_samples);
1024         else
1025                 ret = fprintf(fp, field_sep ? "%lld" : "%12lld ", self->count);
1026
1027         list_for_each_entry(se, &hist_entry__sort_list, list) {
1028                 if (exclude_other && (se == &sort_parent))
1029                         continue;
1030
1031                 fprintf(fp, "%s", field_sep ?: "  ");
1032                 ret += se->print(fp, self, se->width ? *se->width : 0);
1033         }
1034
1035         ret += fprintf(fp, "\n");
1036
1037         if (callchain)
1038                 hist_entry_callchain__fprintf(fp, self, total_samples);
1039
1040         return ret;
1041 }
1042
1043 /*
1044  *
1045  */
1046
1047 static void dso__calc_col_width(struct dso *self)
1048 {
1049         if (!col_width_list_str && !field_sep &&
1050             (!dso_list || strlist__has_entry(dso_list, self->name))) {
1051                 unsigned int slen = strlen(self->name);
1052                 if (slen > dsos__col_width)
1053                         dsos__col_width = slen;
1054         }
1055
1056         self->slen_calculated = 1;
1057 }
1058
1059 static struct symbol *
1060 resolve_symbol(struct thread *thread, struct map **mapp,
1061                struct dso **dsop, u64 *ipp)
1062 {
1063         struct dso *dso = dsop ? *dsop : NULL;
1064         struct map *map = mapp ? *mapp : NULL;
1065         u64 ip = *ipp;
1066
1067         if (!thread)
1068                 return NULL;
1069
1070         if (dso)
1071                 goto got_dso;
1072
1073         if (map)
1074                 goto got_map;
1075
1076         map = thread__find_map(thread, ip);
1077         if (map != NULL) {
1078                 /*
1079                  * We have to do this here as we may have a dso
1080                  * with no symbol hit that has a name longer than
1081                  * the ones with symbols sampled.
1082                  */
1083                 if (!map->dso->slen_calculated)
1084                         dso__calc_col_width(map->dso);
1085
1086                 if (mapp)
1087                         *mapp = map;
1088 got_map:
1089                 ip = map->map_ip(map, ip);
1090
1091                 dso = map->dso;
1092         } else {
1093                 /*
1094                  * If this is outside of all known maps,
1095                  * and is a negative address, try to look it
1096                  * up in the kernel dso, as it might be a
1097                  * vsyscall (which executes in user-mode):
1098                  */
1099                 if ((long long)ip < 0)
1100                 dso = kernel_dso;
1101         }
1102         dprintf(" ...... dso: %s\n", dso ? dso->name : "<not found>");
1103         dprintf(" ...... map: %Lx -> %Lx\n", *ipp, ip);
1104         *ipp  = ip;
1105
1106         if (dsop)
1107                 *dsop = dso;
1108
1109         if (!dso)
1110                 return NULL;
1111 got_dso:
1112         return dso->find_symbol(dso, ip);
1113 }
1114
1115 static int call__match(struct symbol *sym)
1116 {
1117         if (sym->name && !regexec(&parent_regex, sym->name, 0, NULL, 0))
1118                 return 1;
1119
1120         return 0;
1121 }
1122
1123 static struct symbol **
1124 resolve_callchain(struct thread *thread, struct map *map __used,
1125                     struct ip_callchain *chain, struct hist_entry *entry)
1126 {
1127         u64 context = PERF_CONTEXT_MAX;
1128         struct symbol **syms = NULL;
1129         unsigned int i;
1130
1131         if (callchain) {
1132                 syms = calloc(chain->nr, sizeof(*syms));
1133                 if (!syms) {
1134                         fprintf(stderr, "Can't allocate memory for symbols\n");
1135                         exit(-1);
1136                 }
1137         }
1138
1139         for (i = 0; i < chain->nr; i++) {
1140                 u64 ip = chain->ips[i];
1141                 struct dso *dso = NULL;
1142                 struct symbol *sym;
1143
1144                 if (ip >= PERF_CONTEXT_MAX) {
1145                         context = ip;
1146                         continue;
1147                 }
1148
1149                 switch (context) {
1150                 case PERF_CONTEXT_HV:
1151                         dso = hypervisor_dso;
1152                         break;
1153                 case PERF_CONTEXT_KERNEL:
1154                         dso = kernel_dso;
1155                         break;
1156                 default:
1157                         break;
1158                 }
1159
1160                 sym = resolve_symbol(thread, NULL, &dso, &ip);
1161
1162                 if (sym) {
1163                         if (sort__has_parent && call__match(sym) &&
1164                             !entry->parent)
1165                                 entry->parent = sym;
1166                         if (!callchain)
1167                                 break;
1168                         syms[i] = sym;
1169                 }
1170         }
1171
1172         return syms;
1173 }
1174
1175 /*
1176  * collect histogram counts
1177  */
1178
1179 static int
1180 hist_entry__add(struct thread *thread, struct map *map, struct dso *dso,
1181                 struct symbol *sym, u64 ip, struct ip_callchain *chain,
1182                 char level, u64 count)
1183 {
1184         struct rb_node **p = &hist.rb_node;
1185         struct rb_node *parent = NULL;
1186         struct hist_entry *he;
1187         struct symbol **syms = NULL;
1188         struct hist_entry entry = {
1189                 .thread = thread,
1190                 .map    = map,
1191                 .dso    = dso,
1192                 .sym    = sym,
1193                 .ip     = ip,
1194                 .level  = level,
1195                 .count  = count,
1196                 .parent = NULL,
1197                 .sorted_chain = RB_ROOT
1198         };
1199         int cmp;
1200
1201         if ((sort__has_parent || callchain) && chain)
1202                 syms = resolve_callchain(thread, map, chain, &entry);
1203
1204         while (*p != NULL) {
1205                 parent = *p;
1206                 he = rb_entry(parent, struct hist_entry, rb_node);
1207
1208                 cmp = hist_entry__cmp(&entry, he);
1209
1210                 if (!cmp) {
1211                         he->count += count;
1212                         if (callchain) {
1213                                 append_chain(&he->callchain, chain, syms);
1214                                 free(syms);
1215                         }
1216                         return 0;
1217                 }
1218
1219                 if (cmp < 0)
1220                         p = &(*p)->rb_left;
1221                 else
1222                         p = &(*p)->rb_right;
1223         }
1224
1225         he = malloc(sizeof(*he));
1226         if (!he)
1227                 return -ENOMEM;
1228         *he = entry;
1229         if (callchain) {
1230                 callchain_init(&he->callchain);
1231                 append_chain(&he->callchain, chain, syms);
1232                 free(syms);
1233         }
1234         rb_link_node(&he->rb_node, parent, p);
1235         rb_insert_color(&he->rb_node, &hist);
1236
1237         return 0;
1238 }
1239
1240 static void hist_entry__free(struct hist_entry *he)
1241 {
1242         free(he);
1243 }
1244
1245 /*
1246  * collapse the histogram
1247  */
1248
1249 static struct rb_root collapse_hists;
1250
1251 static void collapse__insert_entry(struct hist_entry *he)
1252 {
1253         struct rb_node **p = &collapse_hists.rb_node;
1254         struct rb_node *parent = NULL;
1255         struct hist_entry *iter;
1256         int64_t cmp;
1257
1258         while (*p != NULL) {
1259                 parent = *p;
1260                 iter = rb_entry(parent, struct hist_entry, rb_node);
1261
1262                 cmp = hist_entry__collapse(iter, he);
1263
1264                 if (!cmp) {
1265                         iter->count += he->count;
1266                         hist_entry__free(he);
1267                         return;
1268                 }
1269
1270                 if (cmp < 0)
1271                         p = &(*p)->rb_left;
1272                 else
1273                         p = &(*p)->rb_right;
1274         }
1275
1276         rb_link_node(&he->rb_node, parent, p);
1277         rb_insert_color(&he->rb_node, &collapse_hists);
1278 }
1279
1280 static void collapse__resort(void)
1281 {
1282         struct rb_node *next;
1283         struct hist_entry *n;
1284
1285         if (!sort__need_collapse)
1286                 return;
1287
1288         next = rb_first(&hist);
1289         while (next) {
1290                 n = rb_entry(next, struct hist_entry, rb_node);
1291                 next = rb_next(&n->rb_node);
1292
1293                 rb_erase(&n->rb_node, &hist);
1294                 collapse__insert_entry(n);
1295         }
1296 }
1297
1298 /*
1299  * reverse the map, sort on count.
1300  */
1301
1302 static struct rb_root output_hists;
1303
1304 static void output__insert_entry(struct hist_entry *he, u64 min_callchain_hits)
1305 {
1306         struct rb_node **p = &output_hists.rb_node;
1307         struct rb_node *parent = NULL;
1308         struct hist_entry *iter;
1309
1310         if (callchain)
1311                 callchain_param.sort(&he->sorted_chain, &he->callchain,
1312                                       min_callchain_hits, &callchain_param);
1313
1314         while (*p != NULL) {
1315                 parent = *p;
1316                 iter = rb_entry(parent, struct hist_entry, rb_node);
1317
1318                 if (he->count > iter->count)
1319                         p = &(*p)->rb_left;
1320                 else
1321                         p = &(*p)->rb_right;
1322         }
1323
1324         rb_link_node(&he->rb_node, parent, p);
1325         rb_insert_color(&he->rb_node, &output_hists);
1326 }
1327
1328 static void output__resort(u64 total_samples)
1329 {
1330         struct rb_node *next;
1331         struct hist_entry *n;
1332         struct rb_root *tree = &hist;
1333         u64 min_callchain_hits;
1334
1335         min_callchain_hits = total_samples * (callchain_param.min_percent / 100);
1336
1337         if (sort__need_collapse)
1338                 tree = &collapse_hists;
1339
1340         next = rb_first(tree);
1341
1342         while (next) {
1343                 n = rb_entry(next, struct hist_entry, rb_node);
1344                 next = rb_next(&n->rb_node);
1345
1346                 rb_erase(&n->rb_node, tree);
1347                 output__insert_entry(n, min_callchain_hits);
1348         }
1349 }
1350
1351 static size_t output__fprintf(FILE *fp, u64 total_samples)
1352 {
1353         struct hist_entry *pos;
1354         struct sort_entry *se;
1355         struct rb_node *nd;
1356         size_t ret = 0;
1357         unsigned int width;
1358         char *col_width = col_width_list_str;
1359
1360         fprintf(fp, "\n");
1361         fprintf(fp, "#\n");
1362         fprintf(fp, "# (%Ld samples)\n", (u64)total_samples);
1363         fprintf(fp, "#\n");
1364
1365         fprintf(fp, "# Overhead");
1366         list_for_each_entry(se, &hist_entry__sort_list, list) {
1367                 if (exclude_other && (se == &sort_parent))
1368                         continue;
1369                 if (field_sep) {
1370                         fprintf(fp, "%c%s", *field_sep, se->header);
1371                         continue;
1372                 }
1373                 width = strlen(se->header);
1374                 if (se->width) {
1375                         if (col_width_list_str) {
1376                                 if (col_width) {
1377                                         *se->width = atoi(col_width);
1378                                         col_width = strchr(col_width, ',');
1379                                         if (col_width)
1380                                                 ++col_width;
1381                                 }
1382                         }
1383                         width = *se->width = max(*se->width, width);
1384                 }
1385                 fprintf(fp, "  %*s", width, se->header);
1386         }
1387         fprintf(fp, "\n");
1388
1389         if (field_sep)
1390                 goto print_entries;
1391
1392         fprintf(fp, "# ........");
1393         list_for_each_entry(se, &hist_entry__sort_list, list) {
1394                 unsigned int i;
1395
1396                 if (exclude_other && (se == &sort_parent))
1397                         continue;
1398
1399                 fprintf(fp, "  ");
1400                 if (se->width)
1401                         width = *se->width;
1402                 else
1403                         width = strlen(se->header);
1404                 for (i = 0; i < width; i++)
1405                         fprintf(fp, ".");
1406         }
1407         fprintf(fp, "\n");
1408
1409         fprintf(fp, "#\n");
1410
1411 print_entries:
1412         for (nd = rb_first(&output_hists); nd; nd = rb_next(nd)) {
1413                 pos = rb_entry(nd, struct hist_entry, rb_node);
1414                 ret += hist_entry__fprintf(fp, pos, total_samples);
1415         }
1416
1417         if (sort_order == default_sort_order &&
1418                         parent_pattern == default_parent_pattern) {
1419                 fprintf(fp, "#\n");
1420                 fprintf(fp, "# (For more details, try: perf report --sort comm,dso,symbol)\n");
1421                 fprintf(fp, "#\n");
1422         }
1423         fprintf(fp, "\n");
1424
1425         return ret;
1426 }
1427
1428 static void register_idle_thread(void)
1429 {
1430         struct thread *thread = threads__findnew(0);
1431
1432         if (thread == NULL ||
1433                         thread__set_comm(thread, "[idle]")) {
1434                 fprintf(stderr, "problem inserting idle task.\n");
1435                 exit(-1);
1436         }
1437 }
1438
1439 static unsigned long total = 0,
1440                      total_mmap = 0,
1441                      total_comm = 0,
1442                      total_fork = 0,
1443                      total_unknown = 0,
1444                      total_lost = 0;
1445
1446 static int validate_chain(struct ip_callchain *chain, event_t *event)
1447 {
1448         unsigned int chain_size;
1449
1450         chain_size = event->header.size;
1451         chain_size -= (unsigned long)&event->ip.__more_data - (unsigned long)event;
1452
1453         if (chain->nr*sizeof(u64) > chain_size)
1454                 return -1;
1455
1456         return 0;
1457 }
1458
1459 static int
1460 process_sample_event(event_t *event, unsigned long offset, unsigned long head)
1461 {
1462         char level;
1463         int show = 0;
1464         struct dso *dso = NULL;
1465         struct thread *thread = threads__findnew(event->ip.pid);
1466         u64 ip = event->ip.ip;
1467         u64 period = 1;
1468         struct map *map = NULL;
1469         void *more_data = event->ip.__more_data;
1470         struct ip_callchain *chain = NULL;
1471         int cpumode;
1472
1473         if (sample_type & PERF_SAMPLE_PERIOD) {
1474                 period = *(u64 *)more_data;
1475                 more_data += sizeof(u64);
1476         }
1477
1478         dprintf("%p [%p]: PERF_EVENT_SAMPLE (IP, %d): %d: %p period: %Ld\n",
1479                 (void *)(offset + head),
1480                 (void *)(long)(event->header.size),
1481                 event->header.misc,
1482                 event->ip.pid,
1483                 (void *)(long)ip,
1484                 (long long)period);
1485
1486         if (sample_type & PERF_SAMPLE_CALLCHAIN) {
1487                 unsigned int i;
1488
1489                 chain = (void *)more_data;
1490
1491                 dprintf("... chain: nr:%Lu\n", chain->nr);
1492
1493                 if (validate_chain(chain, event) < 0) {
1494                         eprintf("call-chain problem with event, skipping it.\n");
1495                         return 0;
1496                 }
1497
1498                 if (dump_trace) {
1499                         for (i = 0; i < chain->nr; i++)
1500                                 dprintf("..... %2d: %016Lx\n", i, chain->ips[i]);
1501                 }
1502         }
1503
1504         dprintf(" ... thread: %s:%d\n", thread->comm, thread->pid);
1505
1506         if (thread == NULL) {
1507                 eprintf("problem processing %d event, skipping it.\n",
1508                         event->header.type);
1509                 return -1;
1510         }
1511
1512         if (comm_list && !strlist__has_entry(comm_list, thread->comm))
1513                 return 0;
1514
1515         cpumode = event->header.misc & PERF_EVENT_MISC_CPUMODE_MASK;
1516
1517         if (cpumode == PERF_EVENT_MISC_KERNEL) {
1518                 show = SHOW_KERNEL;
1519                 level = 'k';
1520
1521                 dso = kernel_dso;
1522
1523                 dprintf(" ...... dso: %s\n", dso->name);
1524
1525         } else if (cpumode == PERF_EVENT_MISC_USER) {
1526
1527                 show = SHOW_USER;
1528                 level = '.';
1529
1530         } else {
1531                 show = SHOW_HV;
1532                 level = 'H';
1533
1534                 dso = hypervisor_dso;
1535
1536                 dprintf(" ...... dso: [hypervisor]\n");
1537         }
1538
1539         if (show & show_mask) {
1540                 struct symbol *sym = resolve_symbol(thread, &map, &dso, &ip);
1541
1542                 if (dso_list && dso && dso->name && !strlist__has_entry(dso_list, dso->name))
1543                         return 0;
1544
1545                 if (sym_list && sym && !strlist__has_entry(sym_list, sym->name))
1546                         return 0;
1547
1548                 if (hist_entry__add(thread, map, dso, sym, ip, chain, level, period)) {
1549                         eprintf("problem incrementing symbol count, skipping event\n");
1550                         return -1;
1551                 }
1552         }
1553         total += period;
1554
1555         return 0;
1556 }
1557
1558 static int
1559 process_mmap_event(event_t *event, unsigned long offset, unsigned long head)
1560 {
1561         struct thread *thread = threads__findnew(event->mmap.pid);
1562         struct map *map = map__new(&event->mmap);
1563
1564         dprintf("%p [%p]: PERF_EVENT_MMAP %d: [%p(%p) @ %p]: %s\n",
1565                 (void *)(offset + head),
1566                 (void *)(long)(event->header.size),
1567                 event->mmap.pid,
1568                 (void *)(long)event->mmap.start,
1569                 (void *)(long)event->mmap.len,
1570                 (void *)(long)event->mmap.pgoff,
1571                 event->mmap.filename);
1572
1573         if (thread == NULL || map == NULL) {
1574                 dprintf("problem processing PERF_EVENT_MMAP, skipping event.\n");
1575                 return 0;
1576         }
1577
1578         thread__insert_map(thread, map);
1579         total_mmap++;
1580
1581         return 0;
1582 }
1583
1584 static int
1585 process_comm_event(event_t *event, unsigned long offset, unsigned long head)
1586 {
1587         struct thread *thread = threads__findnew(event->comm.pid);
1588
1589         dprintf("%p [%p]: PERF_EVENT_COMM: %s:%d\n",
1590                 (void *)(offset + head),
1591                 (void *)(long)(event->header.size),
1592                 event->comm.comm, event->comm.pid);
1593
1594         if (thread == NULL ||
1595             thread__set_comm(thread, event->comm.comm)) {
1596                 dprintf("problem processing PERF_EVENT_COMM, skipping event.\n");
1597                 return -1;
1598         }
1599         total_comm++;
1600
1601         return 0;
1602 }
1603
1604 static int
1605 process_fork_event(event_t *event, unsigned long offset, unsigned long head)
1606 {
1607         struct thread *thread = threads__findnew(event->fork.pid);
1608         struct thread *parent = threads__findnew(event->fork.ppid);
1609
1610         dprintf("%p [%p]: PERF_EVENT_FORK: %d:%d\n",
1611                 (void *)(offset + head),
1612                 (void *)(long)(event->header.size),
1613                 event->fork.pid, event->fork.ppid);
1614
1615         if (!thread || !parent || thread__fork(thread, parent)) {
1616                 dprintf("problem processing PERF_EVENT_FORK, skipping event.\n");
1617                 return -1;
1618         }
1619         total_fork++;
1620
1621         return 0;
1622 }
1623
1624 static int
1625 process_period_event(event_t *event, unsigned long offset, unsigned long head)
1626 {
1627         dprintf("%p [%p]: PERF_EVENT_PERIOD: time:%Ld, id:%Ld: period:%Ld\n",
1628                 (void *)(offset + head),
1629                 (void *)(long)(event->header.size),
1630                 event->period.time,
1631                 event->period.id,
1632                 event->period.sample_period);
1633
1634         return 0;
1635 }
1636
1637 static int
1638 process_lost_event(event_t *event, unsigned long offset, unsigned long head)
1639 {
1640         dprintf("%p [%p]: PERF_EVENT_LOST: id:%Ld: lost:%Ld\n",
1641                 (void *)(offset + head),
1642                 (void *)(long)(event->header.size),
1643                 event->lost.id,
1644                 event->lost.lost);
1645
1646         total_lost += event->lost.lost;
1647
1648         return 0;
1649 }
1650
1651 static void trace_event(event_t *event)
1652 {
1653         unsigned char *raw_event = (void *)event;
1654         char *color = PERF_COLOR_BLUE;
1655         int i, j;
1656
1657         if (!dump_trace)
1658                 return;
1659
1660         dprintf(".");
1661         cdprintf("\n. ... raw event: size %d bytes\n", event->header.size);
1662
1663         for (i = 0; i < event->header.size; i++) {
1664                 if ((i & 15) == 0) {
1665                         dprintf(".");
1666                         cdprintf("  %04x: ", i);
1667                 }
1668
1669                 cdprintf(" %02x", raw_event[i]);
1670
1671                 if (((i & 15) == 15) || i == event->header.size-1) {
1672                         cdprintf("  ");
1673                         for (j = 0; j < 15-(i & 15); j++)
1674                                 cdprintf("   ");
1675                         for (j = 0; j < (i & 15); j++) {
1676                                 if (isprint(raw_event[i-15+j]))
1677                                         cdprintf("%c", raw_event[i-15+j]);
1678                                 else
1679                                         cdprintf(".");
1680                         }
1681                         cdprintf("\n");
1682                 }
1683         }
1684         dprintf(".\n");
1685 }
1686
1687 static int
1688 process_read_event(event_t *event, unsigned long offset, unsigned long head)
1689 {
1690         dprintf("%p [%p]: PERF_EVENT_READ: %d %d %Lu\n",
1691                         (void *)(offset + head),
1692                         (void *)(long)(event->header.size),
1693                         event->read.pid,
1694                         event->read.tid,
1695                         event->read.value);
1696
1697         return 0;
1698 }
1699
1700 static int
1701 process_event(event_t *event, unsigned long offset, unsigned long head)
1702 {
1703         trace_event(event);
1704
1705         switch (event->header.type) {
1706         case PERF_EVENT_SAMPLE:
1707                 return process_sample_event(event, offset, head);
1708
1709         case PERF_EVENT_MMAP:
1710                 return process_mmap_event(event, offset, head);
1711
1712         case PERF_EVENT_COMM:
1713                 return process_comm_event(event, offset, head);
1714
1715         case PERF_EVENT_FORK:
1716                 return process_fork_event(event, offset, head);
1717
1718         case PERF_EVENT_PERIOD:
1719                 return process_period_event(event, offset, head);
1720
1721         case PERF_EVENT_LOST:
1722                 return process_lost_event(event, offset, head);
1723
1724         case PERF_EVENT_READ:
1725                 return process_read_event(event, offset, head);
1726
1727         /*
1728          * We dont process them right now but they are fine:
1729          */
1730
1731         case PERF_EVENT_THROTTLE:
1732         case PERF_EVENT_UNTHROTTLE:
1733                 return 0;
1734
1735         default:
1736                 return -1;
1737         }
1738
1739         return 0;
1740 }
1741
1742 static struct perf_header       *header;
1743
1744 static u64 perf_header__sample_type(void)
1745 {
1746         u64 sample_type = 0;
1747         int i;
1748
1749         for (i = 0; i < header->attrs; i++) {
1750                 struct perf_header_attr *attr = header->attr[i];
1751
1752                 if (!sample_type)
1753                         sample_type = attr->attr.sample_type;
1754                 else if (sample_type != attr->attr.sample_type)
1755                         die("non matching sample_type");
1756         }
1757
1758         return sample_type;
1759 }
1760
1761 static int __cmd_report(void)
1762 {
1763         int ret, rc = EXIT_FAILURE;
1764         unsigned long offset = 0;
1765         unsigned long head, shift;
1766         struct stat stat;
1767         event_t *event;
1768         uint32_t size;
1769         char *buf;
1770
1771         register_idle_thread();
1772
1773         input = open(input_name, O_RDONLY);
1774         if (input < 0) {
1775                 fprintf(stderr, " failed to open file: %s", input_name);
1776                 if (!strcmp(input_name, "perf.data"))
1777                         fprintf(stderr, "  (try 'perf record' first)");
1778                 fprintf(stderr, "\n");
1779                 exit(-1);
1780         }
1781
1782         ret = fstat(input, &stat);
1783         if (ret < 0) {
1784                 perror("failed to stat file");
1785                 exit(-1);
1786         }
1787
1788         if (!stat.st_size) {
1789                 fprintf(stderr, "zero-sized file, nothing to do!\n");
1790                 exit(0);
1791         }
1792
1793         header = perf_header__read(input);
1794         head = header->data_offset;
1795
1796         sample_type = perf_header__sample_type();
1797
1798         if (!(sample_type & PERF_SAMPLE_CALLCHAIN)) {
1799                 if (sort__has_parent) {
1800                         fprintf(stderr, "selected --sort parent, but no"
1801                                         " callchain data. Did you call"
1802                                         " perf record without -g?\n");
1803                         exit(-1);
1804                 }
1805                 if (callchain) {
1806                         fprintf(stderr, "selected -c but no callchain data."
1807                                         " Did you call perf record without"
1808                                         " -g?\n");
1809                         exit(-1);
1810                 }
1811         }
1812
1813         if (load_kernel() < 0) {
1814                 perror("failed to load kernel symbols");
1815                 return EXIT_FAILURE;
1816         }
1817
1818         if (!full_paths) {
1819                 if (getcwd(__cwd, sizeof(__cwd)) == NULL) {
1820                         perror("failed to get the current directory");
1821                         return EXIT_FAILURE;
1822                 }
1823                 cwdlen = strlen(cwd);
1824         } else {
1825                 cwd = NULL;
1826                 cwdlen = 0;
1827         }
1828
1829         shift = page_size * (head / page_size);
1830         offset += shift;
1831         head -= shift;
1832
1833 remap:
1834         buf = (char *)mmap(NULL, page_size * mmap_window, PROT_READ,
1835                            MAP_SHARED, input, offset);
1836         if (buf == MAP_FAILED) {
1837                 perror("failed to mmap file");
1838                 exit(-1);
1839         }
1840
1841 more:
1842         event = (event_t *)(buf + head);
1843
1844         size = event->header.size;
1845         if (!size)
1846                 size = 8;
1847
1848         if (head + event->header.size >= page_size * mmap_window) {
1849                 int ret;
1850
1851                 shift = page_size * (head / page_size);
1852
1853                 ret = munmap(buf, page_size * mmap_window);
1854                 assert(ret == 0);
1855
1856                 offset += shift;
1857                 head -= shift;
1858                 goto remap;
1859         }
1860
1861         size = event->header.size;
1862
1863         dprintf("\n%p [%p]: event: %d\n",
1864                         (void *)(offset + head),
1865                         (void *)(long)event->header.size,
1866                         event->header.type);
1867
1868         if (!size || process_event(event, offset, head) < 0) {
1869
1870                 dprintf("%p [%p]: skipping unknown header type: %d\n",
1871                         (void *)(offset + head),
1872                         (void *)(long)(event->header.size),
1873                         event->header.type);
1874
1875                 total_unknown++;
1876
1877                 /*
1878                  * assume we lost track of the stream, check alignment, and
1879                  * increment a single u64 in the hope to catch on again 'soon'.
1880                  */
1881
1882                 if (unlikely(head & 7))
1883                         head &= ~7ULL;
1884
1885                 size = 8;
1886         }
1887
1888         head += size;
1889
1890         if (offset + head >= header->data_offset + header->data_size)
1891                 goto done;
1892
1893         if (offset + head < (unsigned long)stat.st_size)
1894                 goto more;
1895
1896 done:
1897         rc = EXIT_SUCCESS;
1898         close(input);
1899
1900         dprintf("      IP events: %10ld\n", total);
1901         dprintf("    mmap events: %10ld\n", total_mmap);
1902         dprintf("    comm events: %10ld\n", total_comm);
1903         dprintf("    fork events: %10ld\n", total_fork);
1904         dprintf("    lost events: %10ld\n", total_lost);
1905         dprintf(" unknown events: %10ld\n", total_unknown);
1906
1907         if (dump_trace)
1908                 return 0;
1909
1910         if (verbose >= 3)
1911                 threads__fprintf(stdout);
1912
1913         if (verbose >= 2)
1914                 dsos__fprintf(stdout);
1915
1916         collapse__resort();
1917         output__resort(total);
1918         output__fprintf(stdout, total);
1919
1920         return rc;
1921 }
1922
1923 static int
1924 parse_callchain_opt(const struct option *opt __used, const char *arg,
1925                     int unset __used)
1926 {
1927         char *tok;
1928         char *endptr;
1929
1930         callchain = 1;
1931
1932         if (!arg)
1933                 return 0;
1934
1935         tok = strtok((char *)arg, ",");
1936         if (!tok)
1937                 return -1;
1938
1939         /* get the output mode */
1940         if (!strncmp(tok, "graph", strlen(arg)))
1941                 callchain_param.mode = CHAIN_GRAPH_ABS;
1942
1943         else if (!strncmp(tok, "flat", strlen(arg)))
1944                 callchain_param.mode = CHAIN_FLAT;
1945
1946         else if (!strncmp(tok, "fractal", strlen(arg)))
1947                 callchain_param.mode = CHAIN_GRAPH_REL;
1948
1949         else
1950                 return -1;
1951
1952         /* get the min percentage */
1953         tok = strtok(NULL, ",");
1954         if (!tok)
1955                 goto setup;
1956
1957         callchain_param.min_percent = strtod(tok, &endptr);
1958         if (tok == endptr)
1959                 return -1;
1960
1961 setup:
1962         if (register_callchain_param(&callchain_param) < 0) {
1963                 fprintf(stderr, "Can't register callchain params\n");
1964                 return -1;
1965         }
1966         return 0;
1967 }
1968
1969 static const char * const report_usage[] = {
1970         "perf report [<options>] <command>",
1971         NULL
1972 };
1973
1974 static const struct option options[] = {
1975         OPT_STRING('i', "input", &input_name, "file",
1976                     "input file name"),
1977         OPT_BOOLEAN('v', "verbose", &verbose,
1978                     "be more verbose (show symbol address, etc)"),
1979         OPT_BOOLEAN('D', "dump-raw-trace", &dump_trace,
1980                     "dump raw trace in ASCII"),
1981         OPT_STRING('k', "vmlinux", &vmlinux, "file", "vmlinux pathname"),
1982         OPT_BOOLEAN('m', "modules", &modules,
1983                     "load module symbols - WARNING: use only with -k and LIVE kernel"),
1984         OPT_STRING('s', "sort", &sort_order, "key[,key2...]",
1985                    "sort by key(s): pid, comm, dso, symbol, parent"),
1986         OPT_BOOLEAN('P', "full-paths", &full_paths,
1987                     "Don't shorten the pathnames taking into account the cwd"),
1988         OPT_STRING('p', "parent", &parent_pattern, "regex",
1989                    "regex filter to identify parent, see: '--sort parent'"),
1990         OPT_BOOLEAN('x', "exclude-other", &exclude_other,
1991                     "Only display entries with parent-match"),
1992         OPT_CALLBACK_DEFAULT('c', "callchain", NULL, "output_type,min_percent",
1993                      "Display callchains using output_type and min percent threshold. "
1994                      "Default: flat,0", &parse_callchain_opt, callchain_default_opt),
1995         OPT_STRING('d', "dsos", &dso_list_str, "dso[,dso...]",
1996                    "only consider symbols in these dsos"),
1997         OPT_STRING('C', "comms", &comm_list_str, "comm[,comm...]",
1998                    "only consider symbols in these comms"),
1999         OPT_STRING('S', "symbols", &sym_list_str, "symbol[,symbol...]",
2000                    "only consider these symbols"),
2001         OPT_STRING('w', "column-widths", &col_width_list_str,
2002                    "width[,width...]",
2003                    "don't try to adjust column width, use these fixed values"),
2004         OPT_STRING('t', "field-separator", &field_sep, "separator",
2005                    "separator for columns, no spaces will be added between "
2006                    "columns '.' is reserved."),
2007         OPT_END()
2008 };
2009
2010 static void setup_sorting(void)
2011 {
2012         char *tmp, *tok, *str = strdup(sort_order);
2013
2014         for (tok = strtok_r(str, ", ", &tmp);
2015                         tok; tok = strtok_r(NULL, ", ", &tmp)) {
2016                 if (sort_dimension__add(tok) < 0) {
2017                         error("Unknown --sort key: `%s'", tok);
2018                         usage_with_options(report_usage, options);
2019                 }
2020         }
2021
2022         free(str);
2023 }
2024
2025 static void setup_list(struct strlist **list, const char *list_str,
2026                        const char *list_name)
2027 {
2028         if (list_str) {
2029                 *list = strlist__new(true, list_str);
2030                 if (!*list) {
2031                         fprintf(stderr, "problems parsing %s list\n",
2032                                 list_name);
2033                         exit(129);
2034                 }
2035         }
2036 }
2037
2038 int cmd_report(int argc, const char **argv, const char *prefix __used)
2039 {
2040         symbol__init();
2041
2042         page_size = getpagesize();
2043
2044         argc = parse_options(argc, argv, options, report_usage, 0);
2045
2046         setup_sorting();
2047
2048         if (parent_pattern != default_parent_pattern)
2049                 sort_dimension__add("parent");
2050         else
2051                 exclude_other = 0;
2052
2053         /*
2054          * Any (unrecognized) arguments left?
2055          */
2056         if (argc)
2057                 usage_with_options(report_usage, options);
2058
2059         setup_list(&dso_list, dso_list_str, "dso");
2060         setup_list(&comm_list, comm_list_str, "comm");
2061         setup_list(&sym_list, sym_list_str, "symbol");
2062
2063         if (field_sep && *field_sep == '.') {
2064                 fputs("'.' is the only non valid --field-separator argument\n",
2065                       stderr);
2066                 exit(129);
2067         }
2068
2069         setup_pager();
2070
2071         return __cmd_report();
2072 }