perf report: Tidy up reporting of symbols not found
[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         ret += repsep_fprintf(fp, "[%c] ", self->level);
709         if (self->sym) {
710                 ret += repsep_fprintf(fp, "%s", self->sym->name);
711
712                 if (self->sym->module)
713                         ret += repsep_fprintf(fp, "\t[%s]",
714                                              self->sym->module->name);
715         } else {
716                 ret += repsep_fprintf(fp, "%#016llx", (u64)self->ip);
717         }
718
719         return ret;
720 }
721
722 static struct sort_entry sort_sym = {
723         .header = "Symbol",
724         .cmp    = sort__sym_cmp,
725         .print  = sort__sym_print,
726 };
727
728 /* --sort parent */
729
730 static int64_t
731 sort__parent_cmp(struct hist_entry *left, struct hist_entry *right)
732 {
733         struct symbol *sym_l = left->parent;
734         struct symbol *sym_r = right->parent;
735
736         if (!sym_l || !sym_r)
737                 return cmp_null(sym_l, sym_r);
738
739         return strcmp(sym_l->name, sym_r->name);
740 }
741
742 static size_t
743 sort__parent_print(FILE *fp, struct hist_entry *self, unsigned int width)
744 {
745         return repsep_fprintf(fp, "%-*s", width,
746                               self->parent ? self->parent->name : "[other]");
747 }
748
749 static unsigned int parent_symbol__col_width;
750
751 static struct sort_entry sort_parent = {
752         .header = "Parent symbol",
753         .cmp    = sort__parent_cmp,
754         .print  = sort__parent_print,
755         .width  = &parent_symbol__col_width,
756 };
757
758 static int sort__need_collapse = 0;
759 static int sort__has_parent = 0;
760
761 struct sort_dimension {
762         char                    *name;
763         struct sort_entry       *entry;
764         int                     taken;
765 };
766
767 static struct sort_dimension sort_dimensions[] = {
768         { .name = "pid",        .entry = &sort_thread,  },
769         { .name = "comm",       .entry = &sort_comm,    },
770         { .name = "dso",        .entry = &sort_dso,     },
771         { .name = "symbol",     .entry = &sort_sym,     },
772         { .name = "parent",     .entry = &sort_parent,  },
773 };
774
775 static LIST_HEAD(hist_entry__sort_list);
776
777 static int sort_dimension__add(char *tok)
778 {
779         unsigned int i;
780
781         for (i = 0; i < ARRAY_SIZE(sort_dimensions); i++) {
782                 struct sort_dimension *sd = &sort_dimensions[i];
783
784                 if (sd->taken)
785                         continue;
786
787                 if (strncasecmp(tok, sd->name, strlen(tok)))
788                         continue;
789
790                 if (sd->entry->collapse)
791                         sort__need_collapse = 1;
792
793                 if (sd->entry == &sort_parent) {
794                         int ret = regcomp(&parent_regex, parent_pattern, REG_EXTENDED);
795                         if (ret) {
796                                 char err[BUFSIZ];
797
798                                 regerror(ret, &parent_regex, err, sizeof(err));
799                                 fprintf(stderr, "Invalid regex: %s\n%s",
800                                         parent_pattern, err);
801                                 exit(-1);
802                         }
803                         sort__has_parent = 1;
804                 }
805
806                 list_add_tail(&sd->entry->list, &hist_entry__sort_list);
807                 sd->taken = 1;
808
809                 return 0;
810         }
811
812         return -ESRCH;
813 }
814
815 static int64_t
816 hist_entry__cmp(struct hist_entry *left, struct hist_entry *right)
817 {
818         struct sort_entry *se;
819         int64_t cmp = 0;
820
821         list_for_each_entry(se, &hist_entry__sort_list, list) {
822                 cmp = se->cmp(left, right);
823                 if (cmp)
824                         break;
825         }
826
827         return cmp;
828 }
829
830 static int64_t
831 hist_entry__collapse(struct hist_entry *left, struct hist_entry *right)
832 {
833         struct sort_entry *se;
834         int64_t cmp = 0;
835
836         list_for_each_entry(se, &hist_entry__sort_list, list) {
837                 int64_t (*f)(struct hist_entry *, struct hist_entry *);
838
839                 f = se->collapse ?: se->cmp;
840
841                 cmp = f(left, right);
842                 if (cmp)
843                         break;
844         }
845
846         return cmp;
847 }
848
849 static size_t ipchain__fprintf_graph_line(FILE *fp, int depth, int depth_mask)
850 {
851         int i;
852         size_t ret = 0;
853
854         ret += fprintf(fp, "%s", "                ");
855
856         for (i = 0; i < depth; i++)
857                 if (depth_mask & (1 << i))
858                         ret += fprintf(fp, "|          ");
859                 else
860                         ret += fprintf(fp, "           ");
861
862         ret += fprintf(fp, "\n");
863
864         return ret;
865 }
866 static size_t
867 ipchain__fprintf_graph(FILE *fp, struct callchain_list *chain, int depth,
868                        int depth_mask, int count, u64 total_samples,
869                        int hits)
870 {
871         int i;
872         size_t ret = 0;
873
874         ret += fprintf(fp, "%s", "                ");
875         for (i = 0; i < depth; i++) {
876                 if (depth_mask & (1 << i))
877                         ret += fprintf(fp, "|");
878                 else
879                         ret += fprintf(fp, " ");
880                 if (!count && i == depth - 1) {
881                         double percent;
882
883                         percent = hits * 100.0 / total_samples;
884                         ret += percent_color_fprintf(fp, "--%2.2f%%-- ", percent);
885                 } else
886                         ret += fprintf(fp, "%s", "          ");
887         }
888         if (chain->sym)
889                 ret += fprintf(fp, "%s\n", chain->sym->name);
890         else
891                 ret += fprintf(fp, "%p\n", (void *)(long)chain->ip);
892
893         return ret;
894 }
895
896 static size_t
897 callchain__fprintf_graph(FILE *fp, struct callchain_node *self,
898                         u64 total_samples, int depth, int depth_mask)
899 {
900         struct rb_node *node, *next;
901         struct callchain_node *child;
902         struct callchain_list *chain;
903         int new_depth_mask = depth_mask;
904         u64 new_total;
905         size_t ret = 0;
906         int i;
907
908         if (callchain_param.mode == CHAIN_GRAPH_REL)
909                 new_total = self->cumul_hit;
910         else
911                 new_total = total_samples;
912
913         node = rb_first(&self->rb_root);
914         while (node) {
915                 child = rb_entry(node, struct callchain_node, rb_node);
916
917                 /*
918                  * The depth mask manages the output of pipes that show
919                  * the depth. We don't want to keep the pipes of the current
920                  * level for the last child of this depth
921                  */
922                 next = rb_next(node);
923                 if (!next)
924                         new_depth_mask &= ~(1 << (depth - 1));
925
926                 /*
927                  * But we keep the older depth mask for the line seperator
928                  * to keep the level link until we reach the last child
929                  */
930                 ret += ipchain__fprintf_graph_line(fp, depth, depth_mask);
931                 i = 0;
932                 list_for_each_entry(chain, &child->val, list) {
933                         if (chain->ip >= PERF_CONTEXT_MAX)
934                                 continue;
935                         ret += ipchain__fprintf_graph(fp, chain, depth,
936                                                       new_depth_mask, i++,
937                                                       new_total,
938                                                       child->cumul_hit);
939                 }
940                 ret += callchain__fprintf_graph(fp, child, new_total,
941                                                 depth + 1,
942                                                 new_depth_mask | (1 << depth));
943                 node = next;
944         }
945
946         return ret;
947 }
948
949 static size_t
950 callchain__fprintf_flat(FILE *fp, struct callchain_node *self,
951                         u64 total_samples)
952 {
953         struct callchain_list *chain;
954         size_t ret = 0;
955
956         if (!self)
957                 return 0;
958
959         ret += callchain__fprintf_flat(fp, self->parent, total_samples);
960
961
962         list_for_each_entry(chain, &self->val, list) {
963                 if (chain->ip >= PERF_CONTEXT_MAX)
964                         continue;
965                 if (chain->sym)
966                         ret += fprintf(fp, "                %s\n", chain->sym->name);
967                 else
968                         ret += fprintf(fp, "                %p\n",
969                                         (void *)(long)chain->ip);
970         }
971
972         return ret;
973 }
974
975 static size_t
976 hist_entry_callchain__fprintf(FILE *fp, struct hist_entry *self,
977                               u64 total_samples)
978 {
979         struct rb_node *rb_node;
980         struct callchain_node *chain;
981         size_t ret = 0;
982
983         rb_node = rb_first(&self->sorted_chain);
984         while (rb_node) {
985                 double percent;
986
987                 chain = rb_entry(rb_node, struct callchain_node, rb_node);
988                 percent = chain->hit * 100.0 / total_samples;
989                 switch (callchain_param.mode) {
990                 case CHAIN_FLAT:
991                         ret += percent_color_fprintf(fp, "           %6.2f%%\n",
992                                                      percent);
993                         ret += callchain__fprintf_flat(fp, chain, total_samples);
994                         break;
995                 case CHAIN_GRAPH_ABS: /* Falldown */
996                 case CHAIN_GRAPH_REL:
997                         ret += callchain__fprintf_graph(fp, chain,
998                                                         total_samples, 1, 1);
999                 default:
1000                         break;
1001                 }
1002                 ret += fprintf(fp, "\n");
1003                 rb_node = rb_next(rb_node);
1004         }
1005
1006         return ret;
1007 }
1008
1009
1010 static size_t
1011 hist_entry__fprintf(FILE *fp, struct hist_entry *self, u64 total_samples)
1012 {
1013         struct sort_entry *se;
1014         size_t ret;
1015
1016         if (exclude_other && !self->parent)
1017                 return 0;
1018
1019         if (total_samples)
1020                 ret = percent_color_fprintf(fp,
1021                                             field_sep ? "%.2f" : "   %6.2f%%",
1022                                         (self->count * 100.0) / total_samples);
1023         else
1024                 ret = fprintf(fp, field_sep ? "%lld" : "%12lld ", self->count);
1025
1026         list_for_each_entry(se, &hist_entry__sort_list, list) {
1027                 if (exclude_other && (se == &sort_parent))
1028                         continue;
1029
1030                 fprintf(fp, "%s", field_sep ?: "  ");
1031                 ret += se->print(fp, self, se->width ? *se->width : 0);
1032         }
1033
1034         ret += fprintf(fp, "\n");
1035
1036         if (callchain)
1037                 hist_entry_callchain__fprintf(fp, self, total_samples);
1038
1039         return ret;
1040 }
1041
1042 /*
1043  *
1044  */
1045
1046 static void dso__calc_col_width(struct dso *self)
1047 {
1048         if (!col_width_list_str && !field_sep &&
1049             (!dso_list || strlist__has_entry(dso_list, self->name))) {
1050                 unsigned int slen = strlen(self->name);
1051                 if (slen > dsos__col_width)
1052                         dsos__col_width = slen;
1053         }
1054
1055         self->slen_calculated = 1;
1056 }
1057
1058 static struct symbol *
1059 resolve_symbol(struct thread *thread, struct map **mapp,
1060                struct dso **dsop, u64 *ipp)
1061 {
1062         struct dso *dso = dsop ? *dsop : NULL;
1063         struct map *map = mapp ? *mapp : NULL;
1064         u64 ip = *ipp;
1065
1066         if (!thread)
1067                 return NULL;
1068
1069         if (dso)
1070                 goto got_dso;
1071
1072         if (map)
1073                 goto got_map;
1074
1075         map = thread__find_map(thread, ip);
1076         if (map != NULL) {
1077                 /*
1078                  * We have to do this here as we may have a dso
1079                  * with no symbol hit that has a name longer than
1080                  * the ones with symbols sampled.
1081                  */
1082                 if (!map->dso->slen_calculated)
1083                         dso__calc_col_width(map->dso);
1084
1085                 if (mapp)
1086                         *mapp = map;
1087 got_map:
1088                 ip = map->map_ip(map, ip);
1089
1090                 dso = map->dso;
1091         } else {
1092                 /*
1093                  * If this is outside of all known maps,
1094                  * and is a negative address, try to look it
1095                  * up in the kernel dso, as it might be a
1096                  * vsyscall (which executes in user-mode):
1097                  */
1098                 if ((long long)ip < 0)
1099                 dso = kernel_dso;
1100         }
1101         dprintf(" ...... dso: %s\n", dso ? dso->name : "<not found>");
1102         dprintf(" ...... map: %Lx -> %Lx\n", *ipp, ip);
1103         *ipp  = ip;
1104
1105         if (dsop)
1106                 *dsop = dso;
1107
1108         if (!dso)
1109                 return NULL;
1110 got_dso:
1111         return dso->find_symbol(dso, ip);
1112 }
1113
1114 static int call__match(struct symbol *sym)
1115 {
1116         if (sym->name && !regexec(&parent_regex, sym->name, 0, NULL, 0))
1117                 return 1;
1118
1119         return 0;
1120 }
1121
1122 static struct symbol **
1123 resolve_callchain(struct thread *thread, struct map *map __used,
1124                     struct ip_callchain *chain, struct hist_entry *entry)
1125 {
1126         u64 context = PERF_CONTEXT_MAX;
1127         struct symbol **syms = NULL;
1128         unsigned int i;
1129
1130         if (callchain) {
1131                 syms = calloc(chain->nr, sizeof(*syms));
1132                 if (!syms) {
1133                         fprintf(stderr, "Can't allocate memory for symbols\n");
1134                         exit(-1);
1135                 }
1136         }
1137
1138         for (i = 0; i < chain->nr; i++) {
1139                 u64 ip = chain->ips[i];
1140                 struct dso *dso = NULL;
1141                 struct symbol *sym;
1142
1143                 if (ip >= PERF_CONTEXT_MAX) {
1144                         context = ip;
1145                         continue;
1146                 }
1147
1148                 switch (context) {
1149                 case PERF_CONTEXT_HV:
1150                         dso = hypervisor_dso;
1151                         break;
1152                 case PERF_CONTEXT_KERNEL:
1153                         dso = kernel_dso;
1154                         break;
1155                 default:
1156                         break;
1157                 }
1158
1159                 sym = resolve_symbol(thread, NULL, &dso, &ip);
1160
1161                 if (sym) {
1162                         if (sort__has_parent && call__match(sym) &&
1163                             !entry->parent)
1164                                 entry->parent = sym;
1165                         if (!callchain)
1166                                 break;
1167                         syms[i] = sym;
1168                 }
1169         }
1170
1171         return syms;
1172 }
1173
1174 /*
1175  * collect histogram counts
1176  */
1177
1178 static int
1179 hist_entry__add(struct thread *thread, struct map *map, struct dso *dso,
1180                 struct symbol *sym, u64 ip, struct ip_callchain *chain,
1181                 char level, u64 count)
1182 {
1183         struct rb_node **p = &hist.rb_node;
1184         struct rb_node *parent = NULL;
1185         struct hist_entry *he;
1186         struct symbol **syms = NULL;
1187         struct hist_entry entry = {
1188                 .thread = thread,
1189                 .map    = map,
1190                 .dso    = dso,
1191                 .sym    = sym,
1192                 .ip     = ip,
1193                 .level  = level,
1194                 .count  = count,
1195                 .parent = NULL,
1196                 .sorted_chain = RB_ROOT
1197         };
1198         int cmp;
1199
1200         if ((sort__has_parent || callchain) && chain)
1201                 syms = resolve_callchain(thread, map, chain, &entry);
1202
1203         while (*p != NULL) {
1204                 parent = *p;
1205                 he = rb_entry(parent, struct hist_entry, rb_node);
1206
1207                 cmp = hist_entry__cmp(&entry, he);
1208
1209                 if (!cmp) {
1210                         he->count += count;
1211                         if (callchain) {
1212                                 append_chain(&he->callchain, chain, syms);
1213                                 free(syms);
1214                         }
1215                         return 0;
1216                 }
1217
1218                 if (cmp < 0)
1219                         p = &(*p)->rb_left;
1220                 else
1221                         p = &(*p)->rb_right;
1222         }
1223
1224         he = malloc(sizeof(*he));
1225         if (!he)
1226                 return -ENOMEM;
1227         *he = entry;
1228         if (callchain) {
1229                 callchain_init(&he->callchain);
1230                 append_chain(&he->callchain, chain, syms);
1231                 free(syms);
1232         }
1233         rb_link_node(&he->rb_node, parent, p);
1234         rb_insert_color(&he->rb_node, &hist);
1235
1236         return 0;
1237 }
1238
1239 static void hist_entry__free(struct hist_entry *he)
1240 {
1241         free(he);
1242 }
1243
1244 /*
1245  * collapse the histogram
1246  */
1247
1248 static struct rb_root collapse_hists;
1249
1250 static void collapse__insert_entry(struct hist_entry *he)
1251 {
1252         struct rb_node **p = &collapse_hists.rb_node;
1253         struct rb_node *parent = NULL;
1254         struct hist_entry *iter;
1255         int64_t cmp;
1256
1257         while (*p != NULL) {
1258                 parent = *p;
1259                 iter = rb_entry(parent, struct hist_entry, rb_node);
1260
1261                 cmp = hist_entry__collapse(iter, he);
1262
1263                 if (!cmp) {
1264                         iter->count += he->count;
1265                         hist_entry__free(he);
1266                         return;
1267                 }
1268
1269                 if (cmp < 0)
1270                         p = &(*p)->rb_left;
1271                 else
1272                         p = &(*p)->rb_right;
1273         }
1274
1275         rb_link_node(&he->rb_node, parent, p);
1276         rb_insert_color(&he->rb_node, &collapse_hists);
1277 }
1278
1279 static void collapse__resort(void)
1280 {
1281         struct rb_node *next;
1282         struct hist_entry *n;
1283
1284         if (!sort__need_collapse)
1285                 return;
1286
1287         next = rb_first(&hist);
1288         while (next) {
1289                 n = rb_entry(next, struct hist_entry, rb_node);
1290                 next = rb_next(&n->rb_node);
1291
1292                 rb_erase(&n->rb_node, &hist);
1293                 collapse__insert_entry(n);
1294         }
1295 }
1296
1297 /*
1298  * reverse the map, sort on count.
1299  */
1300
1301 static struct rb_root output_hists;
1302
1303 static void output__insert_entry(struct hist_entry *he, u64 min_callchain_hits)
1304 {
1305         struct rb_node **p = &output_hists.rb_node;
1306         struct rb_node *parent = NULL;
1307         struct hist_entry *iter;
1308
1309         if (callchain)
1310                 callchain_param.sort(&he->sorted_chain, &he->callchain,
1311                                       min_callchain_hits, &callchain_param);
1312
1313         while (*p != NULL) {
1314                 parent = *p;
1315                 iter = rb_entry(parent, struct hist_entry, rb_node);
1316
1317                 if (he->count > iter->count)
1318                         p = &(*p)->rb_left;
1319                 else
1320                         p = &(*p)->rb_right;
1321         }
1322
1323         rb_link_node(&he->rb_node, parent, p);
1324         rb_insert_color(&he->rb_node, &output_hists);
1325 }
1326
1327 static void output__resort(u64 total_samples)
1328 {
1329         struct rb_node *next;
1330         struct hist_entry *n;
1331         struct rb_root *tree = &hist;
1332         u64 min_callchain_hits;
1333
1334         min_callchain_hits = total_samples * (callchain_param.min_percent / 100);
1335
1336         if (sort__need_collapse)
1337                 tree = &collapse_hists;
1338
1339         next = rb_first(tree);
1340
1341         while (next) {
1342                 n = rb_entry(next, struct hist_entry, rb_node);
1343                 next = rb_next(&n->rb_node);
1344
1345                 rb_erase(&n->rb_node, tree);
1346                 output__insert_entry(n, min_callchain_hits);
1347         }
1348 }
1349
1350 static size_t output__fprintf(FILE *fp, u64 total_samples)
1351 {
1352         struct hist_entry *pos;
1353         struct sort_entry *se;
1354         struct rb_node *nd;
1355         size_t ret = 0;
1356         unsigned int width;
1357         char *col_width = col_width_list_str;
1358
1359         fprintf(fp, "\n");
1360         fprintf(fp, "#\n");
1361         fprintf(fp, "# (%Ld samples)\n", (u64)total_samples);
1362         fprintf(fp, "#\n");
1363
1364         fprintf(fp, "# Overhead");
1365         list_for_each_entry(se, &hist_entry__sort_list, list) {
1366                 if (exclude_other && (se == &sort_parent))
1367                         continue;
1368                 if (field_sep) {
1369                         fprintf(fp, "%c%s", *field_sep, se->header);
1370                         continue;
1371                 }
1372                 width = strlen(se->header);
1373                 if (se->width) {
1374                         if (col_width_list_str) {
1375                                 if (col_width) {
1376                                         *se->width = atoi(col_width);
1377                                         col_width = strchr(col_width, ',');
1378                                         if (col_width)
1379                                                 ++col_width;
1380                                 }
1381                         }
1382                         width = *se->width = max(*se->width, width);
1383                 }
1384                 fprintf(fp, "  %*s", width, se->header);
1385         }
1386         fprintf(fp, "\n");
1387
1388         if (field_sep)
1389                 goto print_entries;
1390
1391         fprintf(fp, "# ........");
1392         list_for_each_entry(se, &hist_entry__sort_list, list) {
1393                 unsigned int i;
1394
1395                 if (exclude_other && (se == &sort_parent))
1396                         continue;
1397
1398                 fprintf(fp, "  ");
1399                 if (se->width)
1400                         width = *se->width;
1401                 else
1402                         width = strlen(se->header);
1403                 for (i = 0; i < width; i++)
1404                         fprintf(fp, ".");
1405         }
1406         fprintf(fp, "\n");
1407
1408         fprintf(fp, "#\n");
1409
1410 print_entries:
1411         for (nd = rb_first(&output_hists); nd; nd = rb_next(nd)) {
1412                 pos = rb_entry(nd, struct hist_entry, rb_node);
1413                 ret += hist_entry__fprintf(fp, pos, total_samples);
1414         }
1415
1416         if (sort_order == default_sort_order &&
1417                         parent_pattern == default_parent_pattern) {
1418                 fprintf(fp, "#\n");
1419                 fprintf(fp, "# (For more details, try: perf report --sort comm,dso,symbol)\n");
1420                 fprintf(fp, "#\n");
1421         }
1422         fprintf(fp, "\n");
1423
1424         return ret;
1425 }
1426
1427 static void register_idle_thread(void)
1428 {
1429         struct thread *thread = threads__findnew(0);
1430
1431         if (thread == NULL ||
1432                         thread__set_comm(thread, "[idle]")) {
1433                 fprintf(stderr, "problem inserting idle task.\n");
1434                 exit(-1);
1435         }
1436 }
1437
1438 static unsigned long total = 0,
1439                      total_mmap = 0,
1440                      total_comm = 0,
1441                      total_fork = 0,
1442                      total_unknown = 0,
1443                      total_lost = 0;
1444
1445 static int validate_chain(struct ip_callchain *chain, event_t *event)
1446 {
1447         unsigned int chain_size;
1448
1449         chain_size = event->header.size;
1450         chain_size -= (unsigned long)&event->ip.__more_data - (unsigned long)event;
1451
1452         if (chain->nr*sizeof(u64) > chain_size)
1453                 return -1;
1454
1455         return 0;
1456 }
1457
1458 static int
1459 process_sample_event(event_t *event, unsigned long offset, unsigned long head)
1460 {
1461         char level;
1462         int show = 0;
1463         struct dso *dso = NULL;
1464         struct thread *thread = threads__findnew(event->ip.pid);
1465         u64 ip = event->ip.ip;
1466         u64 period = 1;
1467         struct map *map = NULL;
1468         void *more_data = event->ip.__more_data;
1469         struct ip_callchain *chain = NULL;
1470         int cpumode;
1471
1472         if (sample_type & PERF_SAMPLE_PERIOD) {
1473                 period = *(u64 *)more_data;
1474                 more_data += sizeof(u64);
1475         }
1476
1477         dprintf("%p [%p]: PERF_EVENT_SAMPLE (IP, %d): %d: %p period: %Ld\n",
1478                 (void *)(offset + head),
1479                 (void *)(long)(event->header.size),
1480                 event->header.misc,
1481                 event->ip.pid,
1482                 (void *)(long)ip,
1483                 (long long)period);
1484
1485         if (sample_type & PERF_SAMPLE_CALLCHAIN) {
1486                 unsigned int i;
1487
1488                 chain = (void *)more_data;
1489
1490                 dprintf("... chain: nr:%Lu\n", chain->nr);
1491
1492                 if (validate_chain(chain, event) < 0) {
1493                         eprintf("call-chain problem with event, skipping it.\n");
1494                         return 0;
1495                 }
1496
1497                 if (dump_trace) {
1498                         for (i = 0; i < chain->nr; i++)
1499                                 dprintf("..... %2d: %016Lx\n", i, chain->ips[i]);
1500                 }
1501         }
1502
1503         dprintf(" ... thread: %s:%d\n", thread->comm, thread->pid);
1504
1505         if (thread == NULL) {
1506                 eprintf("problem processing %d event, skipping it.\n",
1507                         event->header.type);
1508                 return -1;
1509         }
1510
1511         if (comm_list && !strlist__has_entry(comm_list, thread->comm))
1512                 return 0;
1513
1514         cpumode = event->header.misc & PERF_EVENT_MISC_CPUMODE_MASK;
1515
1516         if (cpumode == PERF_EVENT_MISC_KERNEL) {
1517                 show = SHOW_KERNEL;
1518                 level = 'k';
1519
1520                 dso = kernel_dso;
1521
1522                 dprintf(" ...... dso: %s\n", dso->name);
1523
1524         } else if (cpumode == PERF_EVENT_MISC_USER) {
1525
1526                 show = SHOW_USER;
1527                 level = '.';
1528
1529         } else {
1530                 show = SHOW_HV;
1531                 level = 'H';
1532
1533                 dso = hypervisor_dso;
1534
1535                 dprintf(" ...... dso: [hypervisor]\n");
1536         }
1537
1538         if (show & show_mask) {
1539                 struct symbol *sym = resolve_symbol(thread, &map, &dso, &ip);
1540
1541                 if (dso_list && dso && dso->name && !strlist__has_entry(dso_list, dso->name))
1542                         return 0;
1543
1544                 if (sym_list && sym && !strlist__has_entry(sym_list, sym->name))
1545                         return 0;
1546
1547                 if (hist_entry__add(thread, map, dso, sym, ip, chain, level, period)) {
1548                         eprintf("problem incrementing symbol count, skipping event\n");
1549                         return -1;
1550                 }
1551         }
1552         total += period;
1553
1554         return 0;
1555 }
1556
1557 static int
1558 process_mmap_event(event_t *event, unsigned long offset, unsigned long head)
1559 {
1560         struct thread *thread = threads__findnew(event->mmap.pid);
1561         struct map *map = map__new(&event->mmap);
1562
1563         dprintf("%p [%p]: PERF_EVENT_MMAP %d: [%p(%p) @ %p]: %s\n",
1564                 (void *)(offset + head),
1565                 (void *)(long)(event->header.size),
1566                 event->mmap.pid,
1567                 (void *)(long)event->mmap.start,
1568                 (void *)(long)event->mmap.len,
1569                 (void *)(long)event->mmap.pgoff,
1570                 event->mmap.filename);
1571
1572         if (thread == NULL || map == NULL) {
1573                 dprintf("problem processing PERF_EVENT_MMAP, skipping event.\n");
1574                 return 0;
1575         }
1576
1577         thread__insert_map(thread, map);
1578         total_mmap++;
1579
1580         return 0;
1581 }
1582
1583 static int
1584 process_comm_event(event_t *event, unsigned long offset, unsigned long head)
1585 {
1586         struct thread *thread = threads__findnew(event->comm.pid);
1587
1588         dprintf("%p [%p]: PERF_EVENT_COMM: %s:%d\n",
1589                 (void *)(offset + head),
1590                 (void *)(long)(event->header.size),
1591                 event->comm.comm, event->comm.pid);
1592
1593         if (thread == NULL ||
1594             thread__set_comm(thread, event->comm.comm)) {
1595                 dprintf("problem processing PERF_EVENT_COMM, skipping event.\n");
1596                 return -1;
1597         }
1598         total_comm++;
1599
1600         return 0;
1601 }
1602
1603 static int
1604 process_fork_event(event_t *event, unsigned long offset, unsigned long head)
1605 {
1606         struct thread *thread = threads__findnew(event->fork.pid);
1607         struct thread *parent = threads__findnew(event->fork.ppid);
1608
1609         dprintf("%p [%p]: PERF_EVENT_FORK: %d:%d\n",
1610                 (void *)(offset + head),
1611                 (void *)(long)(event->header.size),
1612                 event->fork.pid, event->fork.ppid);
1613
1614         if (!thread || !parent || thread__fork(thread, parent)) {
1615                 dprintf("problem processing PERF_EVENT_FORK, skipping event.\n");
1616                 return -1;
1617         }
1618         total_fork++;
1619
1620         return 0;
1621 }
1622
1623 static int
1624 process_period_event(event_t *event, unsigned long offset, unsigned long head)
1625 {
1626         dprintf("%p [%p]: PERF_EVENT_PERIOD: time:%Ld, id:%Ld: period:%Ld\n",
1627                 (void *)(offset + head),
1628                 (void *)(long)(event->header.size),
1629                 event->period.time,
1630                 event->period.id,
1631                 event->period.sample_period);
1632
1633         return 0;
1634 }
1635
1636 static int
1637 process_lost_event(event_t *event, unsigned long offset, unsigned long head)
1638 {
1639         dprintf("%p [%p]: PERF_EVENT_LOST: id:%Ld: lost:%Ld\n",
1640                 (void *)(offset + head),
1641                 (void *)(long)(event->header.size),
1642                 event->lost.id,
1643                 event->lost.lost);
1644
1645         total_lost += event->lost.lost;
1646
1647         return 0;
1648 }
1649
1650 static void trace_event(event_t *event)
1651 {
1652         unsigned char *raw_event = (void *)event;
1653         char *color = PERF_COLOR_BLUE;
1654         int i, j;
1655
1656         if (!dump_trace)
1657                 return;
1658
1659         dprintf(".");
1660         cdprintf("\n. ... raw event: size %d bytes\n", event->header.size);
1661
1662         for (i = 0; i < event->header.size; i++) {
1663                 if ((i & 15) == 0) {
1664                         dprintf(".");
1665                         cdprintf("  %04x: ", i);
1666                 }
1667
1668                 cdprintf(" %02x", raw_event[i]);
1669
1670                 if (((i & 15) == 15) || i == event->header.size-1) {
1671                         cdprintf("  ");
1672                         for (j = 0; j < 15-(i & 15); j++)
1673                                 cdprintf("   ");
1674                         for (j = 0; j < (i & 15); j++) {
1675                                 if (isprint(raw_event[i-15+j]))
1676                                         cdprintf("%c", raw_event[i-15+j]);
1677                                 else
1678                                         cdprintf(".");
1679                         }
1680                         cdprintf("\n");
1681                 }
1682         }
1683         dprintf(".\n");
1684 }
1685
1686 static int
1687 process_read_event(event_t *event, unsigned long offset, unsigned long head)
1688 {
1689         dprintf("%p [%p]: PERF_EVENT_READ: %d %d %Lu\n",
1690                         (void *)(offset + head),
1691                         (void *)(long)(event->header.size),
1692                         event->read.pid,
1693                         event->read.tid,
1694                         event->read.value);
1695
1696         return 0;
1697 }
1698
1699 static int
1700 process_event(event_t *event, unsigned long offset, unsigned long head)
1701 {
1702         trace_event(event);
1703
1704         switch (event->header.type) {
1705         case PERF_EVENT_SAMPLE:
1706                 return process_sample_event(event, offset, head);
1707
1708         case PERF_EVENT_MMAP:
1709                 return process_mmap_event(event, offset, head);
1710
1711         case PERF_EVENT_COMM:
1712                 return process_comm_event(event, offset, head);
1713
1714         case PERF_EVENT_FORK:
1715                 return process_fork_event(event, offset, head);
1716
1717         case PERF_EVENT_PERIOD:
1718                 return process_period_event(event, offset, head);
1719
1720         case PERF_EVENT_LOST:
1721                 return process_lost_event(event, offset, head);
1722
1723         case PERF_EVENT_READ:
1724                 return process_read_event(event, offset, head);
1725
1726         /*
1727          * We dont process them right now but they are fine:
1728          */
1729
1730         case PERF_EVENT_THROTTLE:
1731         case PERF_EVENT_UNTHROTTLE:
1732                 return 0;
1733
1734         default:
1735                 return -1;
1736         }
1737
1738         return 0;
1739 }
1740
1741 static struct perf_header       *header;
1742
1743 static u64 perf_header__sample_type(void)
1744 {
1745         u64 sample_type = 0;
1746         int i;
1747
1748         for (i = 0; i < header->attrs; i++) {
1749                 struct perf_header_attr *attr = header->attr[i];
1750
1751                 if (!sample_type)
1752                         sample_type = attr->attr.sample_type;
1753                 else if (sample_type != attr->attr.sample_type)
1754                         die("non matching sample_type");
1755         }
1756
1757         return sample_type;
1758 }
1759
1760 static int __cmd_report(void)
1761 {
1762         int ret, rc = EXIT_FAILURE;
1763         unsigned long offset = 0;
1764         unsigned long head, shift;
1765         struct stat stat;
1766         event_t *event;
1767         uint32_t size;
1768         char *buf;
1769
1770         register_idle_thread();
1771
1772         input = open(input_name, O_RDONLY);
1773         if (input < 0) {
1774                 fprintf(stderr, " failed to open file: %s", input_name);
1775                 if (!strcmp(input_name, "perf.data"))
1776                         fprintf(stderr, "  (try 'perf record' first)");
1777                 fprintf(stderr, "\n");
1778                 exit(-1);
1779         }
1780
1781         ret = fstat(input, &stat);
1782         if (ret < 0) {
1783                 perror("failed to stat file");
1784                 exit(-1);
1785         }
1786
1787         if (!stat.st_size) {
1788                 fprintf(stderr, "zero-sized file, nothing to do!\n");
1789                 exit(0);
1790         }
1791
1792         header = perf_header__read(input);
1793         head = header->data_offset;
1794
1795         sample_type = perf_header__sample_type();
1796
1797         if (!(sample_type & PERF_SAMPLE_CALLCHAIN)) {
1798                 if (sort__has_parent) {
1799                         fprintf(stderr, "selected --sort parent, but no"
1800                                         " callchain data. Did you call"
1801                                         " perf record without -g?\n");
1802                         exit(-1);
1803                 }
1804                 if (callchain) {
1805                         fprintf(stderr, "selected -c but no callchain data."
1806                                         " Did you call perf record without"
1807                                         " -g?\n");
1808                         exit(-1);
1809                 }
1810         }
1811
1812         if (load_kernel() < 0) {
1813                 perror("failed to load kernel symbols");
1814                 return EXIT_FAILURE;
1815         }
1816
1817         if (!full_paths) {
1818                 if (getcwd(__cwd, sizeof(__cwd)) == NULL) {
1819                         perror("failed to get the current directory");
1820                         return EXIT_FAILURE;
1821                 }
1822                 cwdlen = strlen(cwd);
1823         } else {
1824                 cwd = NULL;
1825                 cwdlen = 0;
1826         }
1827
1828         shift = page_size * (head / page_size);
1829         offset += shift;
1830         head -= shift;
1831
1832 remap:
1833         buf = (char *)mmap(NULL, page_size * mmap_window, PROT_READ,
1834                            MAP_SHARED, input, offset);
1835         if (buf == MAP_FAILED) {
1836                 perror("failed to mmap file");
1837                 exit(-1);
1838         }
1839
1840 more:
1841         event = (event_t *)(buf + head);
1842
1843         size = event->header.size;
1844         if (!size)
1845                 size = 8;
1846
1847         if (head + event->header.size >= page_size * mmap_window) {
1848                 int ret;
1849
1850                 shift = page_size * (head / page_size);
1851
1852                 ret = munmap(buf, page_size * mmap_window);
1853                 assert(ret == 0);
1854
1855                 offset += shift;
1856                 head -= shift;
1857                 goto remap;
1858         }
1859
1860         size = event->header.size;
1861
1862         dprintf("\n%p [%p]: event: %d\n",
1863                         (void *)(offset + head),
1864                         (void *)(long)event->header.size,
1865                         event->header.type);
1866
1867         if (!size || process_event(event, offset, head) < 0) {
1868
1869                 dprintf("%p [%p]: skipping unknown header type: %d\n",
1870                         (void *)(offset + head),
1871                         (void *)(long)(event->header.size),
1872                         event->header.type);
1873
1874                 total_unknown++;
1875
1876                 /*
1877                  * assume we lost track of the stream, check alignment, and
1878                  * increment a single u64 in the hope to catch on again 'soon'.
1879                  */
1880
1881                 if (unlikely(head & 7))
1882                         head &= ~7ULL;
1883
1884                 size = 8;
1885         }
1886
1887         head += size;
1888
1889         if (offset + head >= header->data_offset + header->data_size)
1890                 goto done;
1891
1892         if (offset + head < (unsigned long)stat.st_size)
1893                 goto more;
1894
1895 done:
1896         rc = EXIT_SUCCESS;
1897         close(input);
1898
1899         dprintf("      IP events: %10ld\n", total);
1900         dprintf("    mmap events: %10ld\n", total_mmap);
1901         dprintf("    comm events: %10ld\n", total_comm);
1902         dprintf("    fork events: %10ld\n", total_fork);
1903         dprintf("    lost events: %10ld\n", total_lost);
1904         dprintf(" unknown events: %10ld\n", total_unknown);
1905
1906         if (dump_trace)
1907                 return 0;
1908
1909         if (verbose >= 3)
1910                 threads__fprintf(stdout);
1911
1912         if (verbose >= 2)
1913                 dsos__fprintf(stdout);
1914
1915         collapse__resort();
1916         output__resort(total);
1917         output__fprintf(stdout, total);
1918
1919         return rc;
1920 }
1921
1922 static int
1923 parse_callchain_opt(const struct option *opt __used, const char *arg,
1924                     int unset __used)
1925 {
1926         char *tok;
1927         char *endptr;
1928
1929         callchain = 1;
1930
1931         if (!arg)
1932                 return 0;
1933
1934         tok = strtok((char *)arg, ",");
1935         if (!tok)
1936                 return -1;
1937
1938         /* get the output mode */
1939         if (!strncmp(tok, "graph", strlen(arg)))
1940                 callchain_param.mode = CHAIN_GRAPH_ABS;
1941
1942         else if (!strncmp(tok, "flat", strlen(arg)))
1943                 callchain_param.mode = CHAIN_FLAT;
1944
1945         else if (!strncmp(tok, "fractal", strlen(arg)))
1946                 callchain_param.mode = CHAIN_GRAPH_REL;
1947
1948         else
1949                 return -1;
1950
1951         /* get the min percentage */
1952         tok = strtok(NULL, ",");
1953         if (!tok)
1954                 goto setup;
1955
1956         callchain_param.min_percent = strtod(tok, &endptr);
1957         if (tok == endptr)
1958                 return -1;
1959
1960 setup:
1961         if (register_callchain_param(&callchain_param) < 0) {
1962                 fprintf(stderr, "Can't register callchain params\n");
1963                 return -1;
1964         }
1965         return 0;
1966 }
1967
1968 static const char * const report_usage[] = {
1969         "perf report [<options>] <command>",
1970         NULL
1971 };
1972
1973 static const struct option options[] = {
1974         OPT_STRING('i', "input", &input_name, "file",
1975                     "input file name"),
1976         OPT_BOOLEAN('v', "verbose", &verbose,
1977                     "be more verbose (show symbol address, etc)"),
1978         OPT_BOOLEAN('D', "dump-raw-trace", &dump_trace,
1979                     "dump raw trace in ASCII"),
1980         OPT_STRING('k', "vmlinux", &vmlinux, "file", "vmlinux pathname"),
1981         OPT_BOOLEAN('m', "modules", &modules,
1982                     "load module symbols - WARNING: use only with -k and LIVE kernel"),
1983         OPT_STRING('s', "sort", &sort_order, "key[,key2...]",
1984                    "sort by key(s): pid, comm, dso, symbol, parent"),
1985         OPT_BOOLEAN('P', "full-paths", &full_paths,
1986                     "Don't shorten the pathnames taking into account the cwd"),
1987         OPT_STRING('p', "parent", &parent_pattern, "regex",
1988                    "regex filter to identify parent, see: '--sort parent'"),
1989         OPT_BOOLEAN('x', "exclude-other", &exclude_other,
1990                     "Only display entries with parent-match"),
1991         OPT_CALLBACK_DEFAULT('c', "callchain", NULL, "output_type,min_percent",
1992                      "Display callchains using output_type and min percent threshold. "
1993                      "Default: flat,0", &parse_callchain_opt, callchain_default_opt),
1994         OPT_STRING('d', "dsos", &dso_list_str, "dso[,dso...]",
1995                    "only consider symbols in these dsos"),
1996         OPT_STRING('C', "comms", &comm_list_str, "comm[,comm...]",
1997                    "only consider symbols in these comms"),
1998         OPT_STRING('S', "symbols", &sym_list_str, "symbol[,symbol...]",
1999                    "only consider these symbols"),
2000         OPT_STRING('w', "column-widths", &col_width_list_str,
2001                    "width[,width...]",
2002                    "don't try to adjust column width, use these fixed values"),
2003         OPT_STRING('t', "field-separator", &field_sep, "separator",
2004                    "separator for columns, no spaces will be added between "
2005                    "columns '.' is reserved."),
2006         OPT_END()
2007 };
2008
2009 static void setup_sorting(void)
2010 {
2011         char *tmp, *tok, *str = strdup(sort_order);
2012
2013         for (tok = strtok_r(str, ", ", &tmp);
2014                         tok; tok = strtok_r(NULL, ", ", &tmp)) {
2015                 if (sort_dimension__add(tok) < 0) {
2016                         error("Unknown --sort key: `%s'", tok);
2017                         usage_with_options(report_usage, options);
2018                 }
2019         }
2020
2021         free(str);
2022 }
2023
2024 static void setup_list(struct strlist **list, const char *list_str,
2025                        const char *list_name)
2026 {
2027         if (list_str) {
2028                 *list = strlist__new(true, list_str);
2029                 if (!*list) {
2030                         fprintf(stderr, "problems parsing %s list\n",
2031                                 list_name);
2032                         exit(129);
2033                 }
2034         }
2035 }
2036
2037 int cmd_report(int argc, const char **argv, const char *prefix __used)
2038 {
2039         symbol__init();
2040
2041         page_size = getpagesize();
2042
2043         argc = parse_options(argc, argv, options, report_usage, 0);
2044
2045         setup_sorting();
2046
2047         if (parent_pattern != default_parent_pattern)
2048                 sort_dimension__add("parent");
2049         else
2050                 exclude_other = 0;
2051
2052         /*
2053          * Any (unrecognized) arguments left?
2054          */
2055         if (argc)
2056                 usage_with_options(report_usage, options);
2057
2058         setup_list(&dso_list, dso_list_str, "dso");
2059         setup_list(&comm_list, comm_list_str, "comm");
2060         setup_list(&sym_list, sym_list_str, "symbol");
2061
2062         if (field_sep && *field_sep == '.') {
2063                 fputs("'.' is the only non valid --field-separator argument\n",
2064                       stderr);
2065                 exit(129);
2066         }
2067
2068         setup_pager();
2069
2070         return __cmd_report();
2071 }