]> asedeno.scripts.mit.edu Git - linux.git/blob - tools/perf/util/hist.c
0441a92b855fea5f14db6ed1018e75954929fad2
[linux.git] / tools / perf / util / hist.c
1 // SPDX-License-Identifier: GPL-2.0
2 #include "util.h"
3 #include "build-id.h"
4 #include "hist.h"
5 #include "map.h"
6 #include "session.h"
7 #include "namespaces.h"
8 #include "sort.h"
9 #include "units.h"
10 #include "evlist.h"
11 #include "evsel.h"
12 #include "annotate.h"
13 #include "srcline.h"
14 #include "thread.h"
15 #include "ui/progress.h"
16 #include <errno.h>
17 #include <math.h>
18 #include <inttypes.h>
19 #include <sys/param.h>
20
21 static bool hists__filter_entry_by_dso(struct hists *hists,
22                                        struct hist_entry *he);
23 static bool hists__filter_entry_by_thread(struct hists *hists,
24                                           struct hist_entry *he);
25 static bool hists__filter_entry_by_symbol(struct hists *hists,
26                                           struct hist_entry *he);
27 static bool hists__filter_entry_by_socket(struct hists *hists,
28                                           struct hist_entry *he);
29
30 u16 hists__col_len(struct hists *hists, enum hist_column col)
31 {
32         return hists->col_len[col];
33 }
34
35 void hists__set_col_len(struct hists *hists, enum hist_column col, u16 len)
36 {
37         hists->col_len[col] = len;
38 }
39
40 bool hists__new_col_len(struct hists *hists, enum hist_column col, u16 len)
41 {
42         if (len > hists__col_len(hists, col)) {
43                 hists__set_col_len(hists, col, len);
44                 return true;
45         }
46         return false;
47 }
48
49 void hists__reset_col_len(struct hists *hists)
50 {
51         enum hist_column col;
52
53         for (col = 0; col < HISTC_NR_COLS; ++col)
54                 hists__set_col_len(hists, col, 0);
55 }
56
57 static void hists__set_unres_dso_col_len(struct hists *hists, int dso)
58 {
59         const unsigned int unresolved_col_width = BITS_PER_LONG / 4;
60
61         if (hists__col_len(hists, dso) < unresolved_col_width &&
62             !symbol_conf.col_width_list_str && !symbol_conf.field_sep &&
63             !symbol_conf.dso_list)
64                 hists__set_col_len(hists, dso, unresolved_col_width);
65 }
66
67 void hists__calc_col_len(struct hists *hists, struct hist_entry *h)
68 {
69         const unsigned int unresolved_col_width = BITS_PER_LONG / 4;
70         int symlen;
71         u16 len;
72
73         /*
74          * +4 accounts for '[x] ' priv level info
75          * +2 accounts for 0x prefix on raw addresses
76          * +3 accounts for ' y ' symtab origin info
77          */
78         if (h->ms.sym) {
79                 symlen = h->ms.sym->namelen + 4;
80                 if (verbose > 0)
81                         symlen += BITS_PER_LONG / 4 + 2 + 3;
82                 hists__new_col_len(hists, HISTC_SYMBOL, symlen);
83         } else {
84                 symlen = unresolved_col_width + 4 + 2;
85                 hists__new_col_len(hists, HISTC_SYMBOL, symlen);
86                 hists__set_unres_dso_col_len(hists, HISTC_DSO);
87         }
88
89         len = thread__comm_len(h->thread);
90         if (hists__new_col_len(hists, HISTC_COMM, len))
91                 hists__set_col_len(hists, HISTC_THREAD, len + 8);
92
93         if (h->ms.map) {
94                 len = dso__name_len(h->ms.map->dso);
95                 hists__new_col_len(hists, HISTC_DSO, len);
96         }
97
98         if (h->parent)
99                 hists__new_col_len(hists, HISTC_PARENT, h->parent->namelen);
100
101         if (h->branch_info) {
102                 if (h->branch_info->from.sym) {
103                         symlen = (int)h->branch_info->from.sym->namelen + 4;
104                         if (verbose > 0)
105                                 symlen += BITS_PER_LONG / 4 + 2 + 3;
106                         hists__new_col_len(hists, HISTC_SYMBOL_FROM, symlen);
107
108                         symlen = dso__name_len(h->branch_info->from.map->dso);
109                         hists__new_col_len(hists, HISTC_DSO_FROM, symlen);
110                 } else {
111                         symlen = unresolved_col_width + 4 + 2;
112                         hists__new_col_len(hists, HISTC_SYMBOL_FROM, symlen);
113                         hists__set_unres_dso_col_len(hists, HISTC_DSO_FROM);
114                 }
115
116                 if (h->branch_info->to.sym) {
117                         symlen = (int)h->branch_info->to.sym->namelen + 4;
118                         if (verbose > 0)
119                                 symlen += BITS_PER_LONG / 4 + 2 + 3;
120                         hists__new_col_len(hists, HISTC_SYMBOL_TO, symlen);
121
122                         symlen = dso__name_len(h->branch_info->to.map->dso);
123                         hists__new_col_len(hists, HISTC_DSO_TO, symlen);
124                 } else {
125                         symlen = unresolved_col_width + 4 + 2;
126                         hists__new_col_len(hists, HISTC_SYMBOL_TO, symlen);
127                         hists__set_unres_dso_col_len(hists, HISTC_DSO_TO);
128                 }
129
130                 if (h->branch_info->srcline_from)
131                         hists__new_col_len(hists, HISTC_SRCLINE_FROM,
132                                         strlen(h->branch_info->srcline_from));
133                 if (h->branch_info->srcline_to)
134                         hists__new_col_len(hists, HISTC_SRCLINE_TO,
135                                         strlen(h->branch_info->srcline_to));
136         }
137
138         if (h->mem_info) {
139                 if (h->mem_info->daddr.sym) {
140                         symlen = (int)h->mem_info->daddr.sym->namelen + 4
141                                + unresolved_col_width + 2;
142                         hists__new_col_len(hists, HISTC_MEM_DADDR_SYMBOL,
143                                            symlen);
144                         hists__new_col_len(hists, HISTC_MEM_DCACHELINE,
145                                            symlen + 1);
146                 } else {
147                         symlen = unresolved_col_width + 4 + 2;
148                         hists__new_col_len(hists, HISTC_MEM_DADDR_SYMBOL,
149                                            symlen);
150                         hists__new_col_len(hists, HISTC_MEM_DCACHELINE,
151                                            symlen);
152                 }
153
154                 if (h->mem_info->iaddr.sym) {
155                         symlen = (int)h->mem_info->iaddr.sym->namelen + 4
156                                + unresolved_col_width + 2;
157                         hists__new_col_len(hists, HISTC_MEM_IADDR_SYMBOL,
158                                            symlen);
159                 } else {
160                         symlen = unresolved_col_width + 4 + 2;
161                         hists__new_col_len(hists, HISTC_MEM_IADDR_SYMBOL,
162                                            symlen);
163                 }
164
165                 if (h->mem_info->daddr.map) {
166                         symlen = dso__name_len(h->mem_info->daddr.map->dso);
167                         hists__new_col_len(hists, HISTC_MEM_DADDR_DSO,
168                                            symlen);
169                 } else {
170                         symlen = unresolved_col_width + 4 + 2;
171                         hists__set_unres_dso_col_len(hists, HISTC_MEM_DADDR_DSO);
172                 }
173
174                 hists__new_col_len(hists, HISTC_MEM_PHYS_DADDR,
175                                    unresolved_col_width + 4 + 2);
176
177         } else {
178                 symlen = unresolved_col_width + 4 + 2;
179                 hists__new_col_len(hists, HISTC_MEM_DADDR_SYMBOL, symlen);
180                 hists__new_col_len(hists, HISTC_MEM_IADDR_SYMBOL, symlen);
181                 hists__set_unres_dso_col_len(hists, HISTC_MEM_DADDR_DSO);
182         }
183
184         hists__new_col_len(hists, HISTC_CGROUP_ID, 20);
185         hists__new_col_len(hists, HISTC_CPU, 3);
186         hists__new_col_len(hists, HISTC_SOCKET, 6);
187         hists__new_col_len(hists, HISTC_MEM_LOCKED, 6);
188         hists__new_col_len(hists, HISTC_MEM_TLB, 22);
189         hists__new_col_len(hists, HISTC_MEM_SNOOP, 12);
190         hists__new_col_len(hists, HISTC_MEM_LVL, 21 + 3);
191         hists__new_col_len(hists, HISTC_LOCAL_WEIGHT, 12);
192         hists__new_col_len(hists, HISTC_GLOBAL_WEIGHT, 12);
193
194         if (h->srcline) {
195                 len = MAX(strlen(h->srcline), strlen(sort_srcline.se_header));
196                 hists__new_col_len(hists, HISTC_SRCLINE, len);
197         }
198
199         if (h->srcfile)
200                 hists__new_col_len(hists, HISTC_SRCFILE, strlen(h->srcfile));
201
202         if (h->transaction)
203                 hists__new_col_len(hists, HISTC_TRANSACTION,
204                                    hist_entry__transaction_len());
205
206         if (h->trace_output)
207                 hists__new_col_len(hists, HISTC_TRACE, strlen(h->trace_output));
208 }
209
210 void hists__output_recalc_col_len(struct hists *hists, int max_rows)
211 {
212         struct rb_node *next = rb_first(&hists->entries);
213         struct hist_entry *n;
214         int row = 0;
215
216         hists__reset_col_len(hists);
217
218         while (next && row++ < max_rows) {
219                 n = rb_entry(next, struct hist_entry, rb_node);
220                 if (!n->filtered)
221                         hists__calc_col_len(hists, n);
222                 next = rb_next(&n->rb_node);
223         }
224 }
225
226 static void he_stat__add_cpumode_period(struct he_stat *he_stat,
227                                         unsigned int cpumode, u64 period)
228 {
229         switch (cpumode) {
230         case PERF_RECORD_MISC_KERNEL:
231                 he_stat->period_sys += period;
232                 break;
233         case PERF_RECORD_MISC_USER:
234                 he_stat->period_us += period;
235                 break;
236         case PERF_RECORD_MISC_GUEST_KERNEL:
237                 he_stat->period_guest_sys += period;
238                 break;
239         case PERF_RECORD_MISC_GUEST_USER:
240                 he_stat->period_guest_us += period;
241                 break;
242         default:
243                 break;
244         }
245 }
246
247 static void he_stat__add_period(struct he_stat *he_stat, u64 period,
248                                 u64 weight)
249 {
250
251         he_stat->period         += period;
252         he_stat->weight         += weight;
253         he_stat->nr_events      += 1;
254 }
255
256 static void he_stat__add_stat(struct he_stat *dest, struct he_stat *src)
257 {
258         dest->period            += src->period;
259         dest->period_sys        += src->period_sys;
260         dest->period_us         += src->period_us;
261         dest->period_guest_sys  += src->period_guest_sys;
262         dest->period_guest_us   += src->period_guest_us;
263         dest->nr_events         += src->nr_events;
264         dest->weight            += src->weight;
265 }
266
267 static void he_stat__decay(struct he_stat *he_stat)
268 {
269         he_stat->period = (he_stat->period * 7) / 8;
270         he_stat->nr_events = (he_stat->nr_events * 7) / 8;
271         /* XXX need decay for weight too? */
272 }
273
274 static void hists__delete_entry(struct hists *hists, struct hist_entry *he);
275
276 static bool hists__decay_entry(struct hists *hists, struct hist_entry *he)
277 {
278         u64 prev_period = he->stat.period;
279         u64 diff;
280
281         if (prev_period == 0)
282                 return true;
283
284         he_stat__decay(&he->stat);
285         if (symbol_conf.cumulate_callchain)
286                 he_stat__decay(he->stat_acc);
287         decay_callchain(he->callchain);
288
289         diff = prev_period - he->stat.period;
290
291         if (!he->depth) {
292                 hists->stats.total_period -= diff;
293                 if (!he->filtered)
294                         hists->stats.total_non_filtered_period -= diff;
295         }
296
297         if (!he->leaf) {
298                 struct hist_entry *child;
299                 struct rb_node *node = rb_first(&he->hroot_out);
300                 while (node) {
301                         child = rb_entry(node, struct hist_entry, rb_node);
302                         node = rb_next(node);
303
304                         if (hists__decay_entry(hists, child))
305                                 hists__delete_entry(hists, child);
306                 }
307         }
308
309         return he->stat.period == 0;
310 }
311
312 static void hists__delete_entry(struct hists *hists, struct hist_entry *he)
313 {
314         struct rb_root *root_in;
315         struct rb_root *root_out;
316
317         if (he->parent_he) {
318                 root_in  = &he->parent_he->hroot_in;
319                 root_out = &he->parent_he->hroot_out;
320         } else {
321                 if (hists__has(hists, need_collapse))
322                         root_in = &hists->entries_collapsed;
323                 else
324                         root_in = hists->entries_in;
325                 root_out = &hists->entries;
326         }
327
328         rb_erase(&he->rb_node_in, root_in);
329         rb_erase(&he->rb_node, root_out);
330
331         --hists->nr_entries;
332         if (!he->filtered)
333                 --hists->nr_non_filtered_entries;
334
335         hist_entry__delete(he);
336 }
337
338 void hists__decay_entries(struct hists *hists, bool zap_user, bool zap_kernel)
339 {
340         struct rb_node *next = rb_first(&hists->entries);
341         struct hist_entry *n;
342
343         while (next) {
344                 n = rb_entry(next, struct hist_entry, rb_node);
345                 next = rb_next(&n->rb_node);
346                 if (((zap_user && n->level == '.') ||
347                      (zap_kernel && n->level != '.') ||
348                      hists__decay_entry(hists, n))) {
349                         hists__delete_entry(hists, n);
350                 }
351         }
352 }
353
354 void hists__delete_entries(struct hists *hists)
355 {
356         struct rb_node *next = rb_first(&hists->entries);
357         struct hist_entry *n;
358
359         while (next) {
360                 n = rb_entry(next, struct hist_entry, rb_node);
361                 next = rb_next(&n->rb_node);
362
363                 hists__delete_entry(hists, n);
364         }
365 }
366
367 /*
368  * histogram, sorted on item, collects periods
369  */
370
371 static int hist_entry__init(struct hist_entry *he,
372                             struct hist_entry *template,
373                             bool sample_self,
374                             size_t callchain_size)
375 {
376         *he = *template;
377         he->callchain_size = callchain_size;
378
379         if (symbol_conf.cumulate_callchain) {
380                 he->stat_acc = malloc(sizeof(he->stat));
381                 if (he->stat_acc == NULL)
382                         return -ENOMEM;
383                 memcpy(he->stat_acc, &he->stat, sizeof(he->stat));
384                 if (!sample_self)
385                         memset(&he->stat, 0, sizeof(he->stat));
386         }
387
388         map__get(he->ms.map);
389
390         if (he->branch_info) {
391                 /*
392                  * This branch info is (a part of) allocated from
393                  * sample__resolve_bstack() and will be freed after
394                  * adding new entries.  So we need to save a copy.
395                  */
396                 he->branch_info = malloc(sizeof(*he->branch_info));
397                 if (he->branch_info == NULL) {
398                         map__zput(he->ms.map);
399                         free(he->stat_acc);
400                         return -ENOMEM;
401                 }
402
403                 memcpy(he->branch_info, template->branch_info,
404                        sizeof(*he->branch_info));
405
406                 map__get(he->branch_info->from.map);
407                 map__get(he->branch_info->to.map);
408         }
409
410         if (he->mem_info) {
411                 map__get(he->mem_info->iaddr.map);
412                 map__get(he->mem_info->daddr.map);
413         }
414
415         if (hist_entry__has_callchains(he) && symbol_conf.use_callchain)
416                 callchain_init(he->callchain);
417
418         if (he->raw_data) {
419                 he->raw_data = memdup(he->raw_data, he->raw_size);
420
421                 if (he->raw_data == NULL) {
422                         map__put(he->ms.map);
423                         if (he->branch_info) {
424                                 map__put(he->branch_info->from.map);
425                                 map__put(he->branch_info->to.map);
426                                 free(he->branch_info);
427                         }
428                         if (he->mem_info) {
429                                 map__put(he->mem_info->iaddr.map);
430                                 map__put(he->mem_info->daddr.map);
431                         }
432                         free(he->stat_acc);
433                         return -ENOMEM;
434                 }
435         }
436         INIT_LIST_HEAD(&he->pairs.node);
437         thread__get(he->thread);
438         he->hroot_in  = RB_ROOT;
439         he->hroot_out = RB_ROOT;
440
441         if (!symbol_conf.report_hierarchy)
442                 he->leaf = true;
443
444         return 0;
445 }
446
447 static void *hist_entry__zalloc(size_t size)
448 {
449         return zalloc(size + sizeof(struct hist_entry));
450 }
451
452 static void hist_entry__free(void *ptr)
453 {
454         free(ptr);
455 }
456
457 static struct hist_entry_ops default_ops = {
458         .new    = hist_entry__zalloc,
459         .free   = hist_entry__free,
460 };
461
462 static struct hist_entry *hist_entry__new(struct hist_entry *template,
463                                           bool sample_self)
464 {
465         struct hist_entry_ops *ops = template->ops;
466         size_t callchain_size = 0;
467         struct hist_entry *he;
468         int err = 0;
469
470         if (!ops)
471                 ops = template->ops = &default_ops;
472
473         if (symbol_conf.use_callchain)
474                 callchain_size = sizeof(struct callchain_root);
475
476         he = ops->new(callchain_size);
477         if (he) {
478                 err = hist_entry__init(he, template, sample_self, callchain_size);
479                 if (err) {
480                         ops->free(he);
481                         he = NULL;
482                 }
483         }
484
485         return he;
486 }
487
488 static u8 symbol__parent_filter(const struct symbol *parent)
489 {
490         if (symbol_conf.exclude_other && parent == NULL)
491                 return 1 << HIST_FILTER__PARENT;
492         return 0;
493 }
494
495 static void hist_entry__add_callchain_period(struct hist_entry *he, u64 period)
496 {
497         if (!hist_entry__has_callchains(he) || !symbol_conf.use_callchain)
498                 return;
499
500         he->hists->callchain_period += period;
501         if (!he->filtered)
502                 he->hists->callchain_non_filtered_period += period;
503 }
504
505 static struct hist_entry *hists__findnew_entry(struct hists *hists,
506                                                struct hist_entry *entry,
507                                                struct addr_location *al,
508                                                bool sample_self)
509 {
510         struct rb_node **p;
511         struct rb_node *parent = NULL;
512         struct hist_entry *he;
513         int64_t cmp;
514         u64 period = entry->stat.period;
515         u64 weight = entry->stat.weight;
516
517         p = &hists->entries_in->rb_node;
518
519         while (*p != NULL) {
520                 parent = *p;
521                 he = rb_entry(parent, struct hist_entry, rb_node_in);
522
523                 /*
524                  * Make sure that it receives arguments in a same order as
525                  * hist_entry__collapse() so that we can use an appropriate
526                  * function when searching an entry regardless which sort
527                  * keys were used.
528                  */
529                 cmp = hist_entry__cmp(he, entry);
530
531                 if (!cmp) {
532                         if (sample_self) {
533                                 he_stat__add_period(&he->stat, period, weight);
534                                 hist_entry__add_callchain_period(he, period);
535                         }
536                         if (symbol_conf.cumulate_callchain)
537                                 he_stat__add_period(he->stat_acc, period, weight);
538
539                         /*
540                          * This mem info was allocated from sample__resolve_mem
541                          * and will not be used anymore.
542                          */
543                         mem_info__zput(entry->mem_info);
544
545                         /* If the map of an existing hist_entry has
546                          * become out-of-date due to an exec() or
547                          * similar, update it.  Otherwise we will
548                          * mis-adjust symbol addresses when computing
549                          * the history counter to increment.
550                          */
551                         if (he->ms.map != entry->ms.map) {
552                                 map__put(he->ms.map);
553                                 he->ms.map = map__get(entry->ms.map);
554                         }
555                         goto out;
556                 }
557
558                 if (cmp < 0)
559                         p = &(*p)->rb_left;
560                 else
561                         p = &(*p)->rb_right;
562         }
563
564         he = hist_entry__new(entry, sample_self);
565         if (!he)
566                 return NULL;
567
568         if (sample_self)
569                 hist_entry__add_callchain_period(he, period);
570         hists->nr_entries++;
571
572         rb_link_node(&he->rb_node_in, parent, p);
573         rb_insert_color(&he->rb_node_in, hists->entries_in);
574 out:
575         if (sample_self)
576                 he_stat__add_cpumode_period(&he->stat, al->cpumode, period);
577         if (symbol_conf.cumulate_callchain)
578                 he_stat__add_cpumode_period(he->stat_acc, al->cpumode, period);
579         return he;
580 }
581
582 static struct hist_entry*
583 __hists__add_entry(struct hists *hists,
584                    struct addr_location *al,
585                    struct symbol *sym_parent,
586                    struct branch_info *bi,
587                    struct mem_info *mi,
588                    struct perf_sample *sample,
589                    bool sample_self,
590                    struct hist_entry_ops *ops)
591 {
592         struct namespaces *ns = thread__namespaces(al->thread);
593         struct hist_entry entry = {
594                 .thread = al->thread,
595                 .comm = thread__comm(al->thread),
596                 .cgroup_id = {
597                         .dev = ns ? ns->link_info[CGROUP_NS_INDEX].dev : 0,
598                         .ino = ns ? ns->link_info[CGROUP_NS_INDEX].ino : 0,
599                 },
600                 .ms = {
601                         .map    = al->map,
602                         .sym    = al->sym,
603                 },
604                 .srcline = al->srcline ? strdup(al->srcline) : NULL,
605                 .socket  = al->socket,
606                 .cpu     = al->cpu,
607                 .cpumode = al->cpumode,
608                 .ip      = al->addr,
609                 .level   = al->level,
610                 .stat = {
611                         .nr_events = 1,
612                         .period = sample->period,
613                         .weight = sample->weight,
614                 },
615                 .parent = sym_parent,
616                 .filtered = symbol__parent_filter(sym_parent) | al->filtered,
617                 .hists  = hists,
618                 .branch_info = bi,
619                 .mem_info = mi,
620                 .transaction = sample->transaction,
621                 .raw_data = sample->raw_data,
622                 .raw_size = sample->raw_size,
623                 .ops = ops,
624         };
625
626         return hists__findnew_entry(hists, &entry, al, sample_self);
627 }
628
629 struct hist_entry *hists__add_entry(struct hists *hists,
630                                     struct addr_location *al,
631                                     struct symbol *sym_parent,
632                                     struct branch_info *bi,
633                                     struct mem_info *mi,
634                                     struct perf_sample *sample,
635                                     bool sample_self)
636 {
637         return __hists__add_entry(hists, al, sym_parent, bi, mi,
638                                   sample, sample_self, NULL);
639 }
640
641 struct hist_entry *hists__add_entry_ops(struct hists *hists,
642                                         struct hist_entry_ops *ops,
643                                         struct addr_location *al,
644                                         struct symbol *sym_parent,
645                                         struct branch_info *bi,
646                                         struct mem_info *mi,
647                                         struct perf_sample *sample,
648                                         bool sample_self)
649 {
650         return __hists__add_entry(hists, al, sym_parent, bi, mi,
651                                   sample, sample_self, ops);
652 }
653
654 static int
655 iter_next_nop_entry(struct hist_entry_iter *iter __maybe_unused,
656                     struct addr_location *al __maybe_unused)
657 {
658         return 0;
659 }
660
661 static int
662 iter_add_next_nop_entry(struct hist_entry_iter *iter __maybe_unused,
663                         struct addr_location *al __maybe_unused)
664 {
665         return 0;
666 }
667
668 static int
669 iter_prepare_mem_entry(struct hist_entry_iter *iter, struct addr_location *al)
670 {
671         struct perf_sample *sample = iter->sample;
672         struct mem_info *mi;
673
674         mi = sample__resolve_mem(sample, al);
675         if (mi == NULL)
676                 return -ENOMEM;
677
678         iter->priv = mi;
679         return 0;
680 }
681
682 static int
683 iter_add_single_mem_entry(struct hist_entry_iter *iter, struct addr_location *al)
684 {
685         u64 cost;
686         struct mem_info *mi = iter->priv;
687         struct hists *hists = evsel__hists(iter->evsel);
688         struct perf_sample *sample = iter->sample;
689         struct hist_entry *he;
690
691         if (mi == NULL)
692                 return -EINVAL;
693
694         cost = sample->weight;
695         if (!cost)
696                 cost = 1;
697
698         /*
699          * must pass period=weight in order to get the correct
700          * sorting from hists__collapse_resort() which is solely
701          * based on periods. We want sorting be done on nr_events * weight
702          * and this is indirectly achieved by passing period=weight here
703          * and the he_stat__add_period() function.
704          */
705         sample->period = cost;
706
707         he = hists__add_entry(hists, al, iter->parent, NULL, mi,
708                               sample, true);
709         if (!he)
710                 return -ENOMEM;
711
712         iter->he = he;
713         return 0;
714 }
715
716 static int
717 iter_finish_mem_entry(struct hist_entry_iter *iter,
718                       struct addr_location *al __maybe_unused)
719 {
720         struct perf_evsel *evsel = iter->evsel;
721         struct hists *hists = evsel__hists(evsel);
722         struct hist_entry *he = iter->he;
723         int err = -EINVAL;
724
725         if (he == NULL)
726                 goto out;
727
728         hists__inc_nr_samples(hists, he->filtered);
729
730         err = hist_entry__append_callchain(he, iter->sample);
731
732 out:
733         /*
734          * We don't need to free iter->priv (mem_info) here since the mem info
735          * was either already freed in hists__findnew_entry() or passed to a
736          * new hist entry by hist_entry__new().
737          */
738         iter->priv = NULL;
739
740         iter->he = NULL;
741         return err;
742 }
743
744 static int
745 iter_prepare_branch_entry(struct hist_entry_iter *iter, struct addr_location *al)
746 {
747         struct branch_info *bi;
748         struct perf_sample *sample = iter->sample;
749
750         bi = sample__resolve_bstack(sample, al);
751         if (!bi)
752                 return -ENOMEM;
753
754         iter->curr = 0;
755         iter->total = sample->branch_stack->nr;
756
757         iter->priv = bi;
758         return 0;
759 }
760
761 static int
762 iter_add_single_branch_entry(struct hist_entry_iter *iter __maybe_unused,
763                              struct addr_location *al __maybe_unused)
764 {
765         return 0;
766 }
767
768 static int
769 iter_next_branch_entry(struct hist_entry_iter *iter, struct addr_location *al)
770 {
771         struct branch_info *bi = iter->priv;
772         int i = iter->curr;
773
774         if (bi == NULL)
775                 return 0;
776
777         if (iter->curr >= iter->total)
778                 return 0;
779
780         al->map = bi[i].to.map;
781         al->sym = bi[i].to.sym;
782         al->addr = bi[i].to.addr;
783         return 1;
784 }
785
786 static int
787 iter_add_next_branch_entry(struct hist_entry_iter *iter, struct addr_location *al)
788 {
789         struct branch_info *bi;
790         struct perf_evsel *evsel = iter->evsel;
791         struct hists *hists = evsel__hists(evsel);
792         struct perf_sample *sample = iter->sample;
793         struct hist_entry *he = NULL;
794         int i = iter->curr;
795         int err = 0;
796
797         bi = iter->priv;
798
799         if (iter->hide_unresolved && !(bi[i].from.sym && bi[i].to.sym))
800                 goto out;
801
802         /*
803          * The report shows the percentage of total branches captured
804          * and not events sampled. Thus we use a pseudo period of 1.
805          */
806         sample->period = 1;
807         sample->weight = bi->flags.cycles ? bi->flags.cycles : 1;
808
809         he = hists__add_entry(hists, al, iter->parent, &bi[i], NULL,
810                               sample, true);
811         if (he == NULL)
812                 return -ENOMEM;
813
814         hists__inc_nr_samples(hists, he->filtered);
815
816 out:
817         iter->he = he;
818         iter->curr++;
819         return err;
820 }
821
822 static int
823 iter_finish_branch_entry(struct hist_entry_iter *iter,
824                          struct addr_location *al __maybe_unused)
825 {
826         zfree(&iter->priv);
827         iter->he = NULL;
828
829         return iter->curr >= iter->total ? 0 : -1;
830 }
831
832 static int
833 iter_prepare_normal_entry(struct hist_entry_iter *iter __maybe_unused,
834                           struct addr_location *al __maybe_unused)
835 {
836         return 0;
837 }
838
839 static int
840 iter_add_single_normal_entry(struct hist_entry_iter *iter, struct addr_location *al)
841 {
842         struct perf_evsel *evsel = iter->evsel;
843         struct perf_sample *sample = iter->sample;
844         struct hist_entry *he;
845
846         he = hists__add_entry(evsel__hists(evsel), al, iter->parent, NULL, NULL,
847                               sample, true);
848         if (he == NULL)
849                 return -ENOMEM;
850
851         iter->he = he;
852         return 0;
853 }
854
855 static int
856 iter_finish_normal_entry(struct hist_entry_iter *iter,
857                          struct addr_location *al __maybe_unused)
858 {
859         struct hist_entry *he = iter->he;
860         struct perf_evsel *evsel = iter->evsel;
861         struct perf_sample *sample = iter->sample;
862
863         if (he == NULL)
864                 return 0;
865
866         iter->he = NULL;
867
868         hists__inc_nr_samples(evsel__hists(evsel), he->filtered);
869
870         return hist_entry__append_callchain(he, sample);
871 }
872
873 static int
874 iter_prepare_cumulative_entry(struct hist_entry_iter *iter,
875                               struct addr_location *al __maybe_unused)
876 {
877         struct hist_entry **he_cache;
878
879         callchain_cursor_commit(&callchain_cursor);
880
881         /*
882          * This is for detecting cycles or recursions so that they're
883          * cumulated only one time to prevent entries more than 100%
884          * overhead.
885          */
886         he_cache = malloc(sizeof(*he_cache) * (callchain_cursor.nr + 1));
887         if (he_cache == NULL)
888                 return -ENOMEM;
889
890         iter->priv = he_cache;
891         iter->curr = 0;
892
893         return 0;
894 }
895
896 static int
897 iter_add_single_cumulative_entry(struct hist_entry_iter *iter,
898                                  struct addr_location *al)
899 {
900         struct perf_evsel *evsel = iter->evsel;
901         struct hists *hists = evsel__hists(evsel);
902         struct perf_sample *sample = iter->sample;
903         struct hist_entry **he_cache = iter->priv;
904         struct hist_entry *he;
905         int err = 0;
906
907         he = hists__add_entry(hists, al, iter->parent, NULL, NULL,
908                               sample, true);
909         if (he == NULL)
910                 return -ENOMEM;
911
912         iter->he = he;
913         he_cache[iter->curr++] = he;
914
915         hist_entry__append_callchain(he, sample);
916
917         /*
918          * We need to re-initialize the cursor since callchain_append()
919          * advanced the cursor to the end.
920          */
921         callchain_cursor_commit(&callchain_cursor);
922
923         hists__inc_nr_samples(hists, he->filtered);
924
925         return err;
926 }
927
928 static int
929 iter_next_cumulative_entry(struct hist_entry_iter *iter,
930                            struct addr_location *al)
931 {
932         struct callchain_cursor_node *node;
933
934         node = callchain_cursor_current(&callchain_cursor);
935         if (node == NULL)
936                 return 0;
937
938         return fill_callchain_info(al, node, iter->hide_unresolved);
939 }
940
941 static int
942 iter_add_next_cumulative_entry(struct hist_entry_iter *iter,
943                                struct addr_location *al)
944 {
945         struct perf_evsel *evsel = iter->evsel;
946         struct perf_sample *sample = iter->sample;
947         struct hist_entry **he_cache = iter->priv;
948         struct hist_entry *he;
949         struct hist_entry he_tmp = {
950                 .hists = evsel__hists(evsel),
951                 .cpu = al->cpu,
952                 .thread = al->thread,
953                 .comm = thread__comm(al->thread),
954                 .ip = al->addr,
955                 .ms = {
956                         .map = al->map,
957                         .sym = al->sym,
958                 },
959                 .srcline = al->srcline ? strdup(al->srcline) : NULL,
960                 .parent = iter->parent,
961                 .raw_data = sample->raw_data,
962                 .raw_size = sample->raw_size,
963         };
964         int i;
965         struct callchain_cursor cursor;
966
967         callchain_cursor_snapshot(&cursor, &callchain_cursor);
968
969         callchain_cursor_advance(&callchain_cursor);
970
971         /*
972          * Check if there's duplicate entries in the callchain.
973          * It's possible that it has cycles or recursive calls.
974          */
975         for (i = 0; i < iter->curr; i++) {
976                 if (hist_entry__cmp(he_cache[i], &he_tmp) == 0) {
977                         /* to avoid calling callback function */
978                         iter->he = NULL;
979                         return 0;
980                 }
981         }
982
983         he = hists__add_entry(evsel__hists(evsel), al, iter->parent, NULL, NULL,
984                               sample, false);
985         if (he == NULL)
986                 return -ENOMEM;
987
988         iter->he = he;
989         he_cache[iter->curr++] = he;
990
991         if (hist_entry__has_callchains(he) && symbol_conf.use_callchain)
992                 callchain_append(he->callchain, &cursor, sample->period);
993         return 0;
994 }
995
996 static int
997 iter_finish_cumulative_entry(struct hist_entry_iter *iter,
998                              struct addr_location *al __maybe_unused)
999 {
1000         zfree(&iter->priv);
1001         iter->he = NULL;
1002
1003         return 0;
1004 }
1005
1006 const struct hist_iter_ops hist_iter_mem = {
1007         .prepare_entry          = iter_prepare_mem_entry,
1008         .add_single_entry       = iter_add_single_mem_entry,
1009         .next_entry             = iter_next_nop_entry,
1010         .add_next_entry         = iter_add_next_nop_entry,
1011         .finish_entry           = iter_finish_mem_entry,
1012 };
1013
1014 const struct hist_iter_ops hist_iter_branch = {
1015         .prepare_entry          = iter_prepare_branch_entry,
1016         .add_single_entry       = iter_add_single_branch_entry,
1017         .next_entry             = iter_next_branch_entry,
1018         .add_next_entry         = iter_add_next_branch_entry,
1019         .finish_entry           = iter_finish_branch_entry,
1020 };
1021
1022 const struct hist_iter_ops hist_iter_normal = {
1023         .prepare_entry          = iter_prepare_normal_entry,
1024         .add_single_entry       = iter_add_single_normal_entry,
1025         .next_entry             = iter_next_nop_entry,
1026         .add_next_entry         = iter_add_next_nop_entry,
1027         .finish_entry           = iter_finish_normal_entry,
1028 };
1029
1030 const struct hist_iter_ops hist_iter_cumulative = {
1031         .prepare_entry          = iter_prepare_cumulative_entry,
1032         .add_single_entry       = iter_add_single_cumulative_entry,
1033         .next_entry             = iter_next_cumulative_entry,
1034         .add_next_entry         = iter_add_next_cumulative_entry,
1035         .finish_entry           = iter_finish_cumulative_entry,
1036 };
1037
1038 int hist_entry_iter__add(struct hist_entry_iter *iter, struct addr_location *al,
1039                          int max_stack_depth, void *arg)
1040 {
1041         int err, err2;
1042         struct map *alm = NULL;
1043
1044         if (al)
1045                 alm = map__get(al->map);
1046
1047         err = sample__resolve_callchain(iter->sample, &callchain_cursor, &iter->parent,
1048                                         iter->evsel, al, max_stack_depth);
1049         if (err)
1050                 return err;
1051
1052         err = iter->ops->prepare_entry(iter, al);
1053         if (err)
1054                 goto out;
1055
1056         err = iter->ops->add_single_entry(iter, al);
1057         if (err)
1058                 goto out;
1059
1060         if (iter->he && iter->add_entry_cb) {
1061                 err = iter->add_entry_cb(iter, al, true, arg);
1062                 if (err)
1063                         goto out;
1064         }
1065
1066         while (iter->ops->next_entry(iter, al)) {
1067                 err = iter->ops->add_next_entry(iter, al);
1068                 if (err)
1069                         break;
1070
1071                 if (iter->he && iter->add_entry_cb) {
1072                         err = iter->add_entry_cb(iter, al, false, arg);
1073                         if (err)
1074                                 goto out;
1075                 }
1076         }
1077
1078 out:
1079         err2 = iter->ops->finish_entry(iter, al);
1080         if (!err)
1081                 err = err2;
1082
1083         map__put(alm);
1084
1085         return err;
1086 }
1087
1088 int64_t
1089 hist_entry__cmp(struct hist_entry *left, struct hist_entry *right)
1090 {
1091         struct hists *hists = left->hists;
1092         struct perf_hpp_fmt *fmt;
1093         int64_t cmp = 0;
1094
1095         hists__for_each_sort_list(hists, fmt) {
1096                 if (perf_hpp__is_dynamic_entry(fmt) &&
1097                     !perf_hpp__defined_dynamic_entry(fmt, hists))
1098                         continue;
1099
1100                 cmp = fmt->cmp(fmt, left, right);
1101                 if (cmp)
1102                         break;
1103         }
1104
1105         return cmp;
1106 }
1107
1108 int64_t
1109 hist_entry__collapse(struct hist_entry *left, struct hist_entry *right)
1110 {
1111         struct hists *hists = left->hists;
1112         struct perf_hpp_fmt *fmt;
1113         int64_t cmp = 0;
1114
1115         hists__for_each_sort_list(hists, fmt) {
1116                 if (perf_hpp__is_dynamic_entry(fmt) &&
1117                     !perf_hpp__defined_dynamic_entry(fmt, hists))
1118                         continue;
1119
1120                 cmp = fmt->collapse(fmt, left, right);
1121                 if (cmp)
1122                         break;
1123         }
1124
1125         return cmp;
1126 }
1127
1128 void hist_entry__delete(struct hist_entry *he)
1129 {
1130         struct hist_entry_ops *ops = he->ops;
1131
1132         thread__zput(he->thread);
1133         map__zput(he->ms.map);
1134
1135         if (he->branch_info) {
1136                 map__zput(he->branch_info->from.map);
1137                 map__zput(he->branch_info->to.map);
1138                 free_srcline(he->branch_info->srcline_from);
1139                 free_srcline(he->branch_info->srcline_to);
1140                 zfree(&he->branch_info);
1141         }
1142
1143         if (he->mem_info) {
1144                 map__zput(he->mem_info->iaddr.map);
1145                 map__zput(he->mem_info->daddr.map);
1146                 mem_info__zput(he->mem_info);
1147         }
1148
1149         zfree(&he->stat_acc);
1150         free_srcline(he->srcline);
1151         if (he->srcfile && he->srcfile[0])
1152                 free(he->srcfile);
1153         free_callchain(he->callchain);
1154         free(he->trace_output);
1155         free(he->raw_data);
1156         ops->free(he);
1157 }
1158
1159 /*
1160  * If this is not the last column, then we need to pad it according to the
1161  * pre-calculated max lenght for this column, otherwise don't bother adding
1162  * spaces because that would break viewing this with, for instance, 'less',
1163  * that would show tons of trailing spaces when a long C++ demangled method
1164  * names is sampled.
1165 */
1166 int hist_entry__snprintf_alignment(struct hist_entry *he, struct perf_hpp *hpp,
1167                                    struct perf_hpp_fmt *fmt, int printed)
1168 {
1169         if (!list_is_last(&fmt->list, &he->hists->hpp_list->fields)) {
1170                 const int width = fmt->width(fmt, hpp, he->hists);
1171                 if (printed < width) {
1172                         advance_hpp(hpp, printed);
1173                         printed = scnprintf(hpp->buf, hpp->size, "%-*s", width - printed, " ");
1174                 }
1175         }
1176
1177         return printed;
1178 }
1179
1180 /*
1181  * collapse the histogram
1182  */
1183
1184 static void hists__apply_filters(struct hists *hists, struct hist_entry *he);
1185 static void hists__remove_entry_filter(struct hists *hists, struct hist_entry *he,
1186                                        enum hist_filter type);
1187
1188 typedef bool (*fmt_chk_fn)(struct perf_hpp_fmt *fmt);
1189
1190 static bool check_thread_entry(struct perf_hpp_fmt *fmt)
1191 {
1192         return perf_hpp__is_thread_entry(fmt) || perf_hpp__is_comm_entry(fmt);
1193 }
1194
1195 static void hist_entry__check_and_remove_filter(struct hist_entry *he,
1196                                                 enum hist_filter type,
1197                                                 fmt_chk_fn check)
1198 {
1199         struct perf_hpp_fmt *fmt;
1200         bool type_match = false;
1201         struct hist_entry *parent = he->parent_he;
1202
1203         switch (type) {
1204         case HIST_FILTER__THREAD:
1205                 if (symbol_conf.comm_list == NULL &&
1206                     symbol_conf.pid_list == NULL &&
1207                     symbol_conf.tid_list == NULL)
1208                         return;
1209                 break;
1210         case HIST_FILTER__DSO:
1211                 if (symbol_conf.dso_list == NULL)
1212                         return;
1213                 break;
1214         case HIST_FILTER__SYMBOL:
1215                 if (symbol_conf.sym_list == NULL)
1216                         return;
1217                 break;
1218         case HIST_FILTER__PARENT:
1219         case HIST_FILTER__GUEST:
1220         case HIST_FILTER__HOST:
1221         case HIST_FILTER__SOCKET:
1222         case HIST_FILTER__C2C:
1223         default:
1224                 return;
1225         }
1226
1227         /* if it's filtered by own fmt, it has to have filter bits */
1228         perf_hpp_list__for_each_format(he->hpp_list, fmt) {
1229                 if (check(fmt)) {
1230                         type_match = true;
1231                         break;
1232                 }
1233         }
1234
1235         if (type_match) {
1236                 /*
1237                  * If the filter is for current level entry, propagate
1238                  * filter marker to parents.  The marker bit was
1239                  * already set by default so it only needs to clear
1240                  * non-filtered entries.
1241                  */
1242                 if (!(he->filtered & (1 << type))) {
1243                         while (parent) {
1244                                 parent->filtered &= ~(1 << type);
1245                                 parent = parent->parent_he;
1246                         }
1247                 }
1248         } else {
1249                 /*
1250                  * If current entry doesn't have matching formats, set
1251                  * filter marker for upper level entries.  it will be
1252                  * cleared if its lower level entries is not filtered.
1253                  *
1254                  * For lower-level entries, it inherits parent's
1255                  * filter bit so that lower level entries of a
1256                  * non-filtered entry won't set the filter marker.
1257                  */
1258                 if (parent == NULL)
1259                         he->filtered |= (1 << type);
1260                 else
1261                         he->filtered |= (parent->filtered & (1 << type));
1262         }
1263 }
1264
1265 static void hist_entry__apply_hierarchy_filters(struct hist_entry *he)
1266 {
1267         hist_entry__check_and_remove_filter(he, HIST_FILTER__THREAD,
1268                                             check_thread_entry);
1269
1270         hist_entry__check_and_remove_filter(he, HIST_FILTER__DSO,
1271                                             perf_hpp__is_dso_entry);
1272
1273         hist_entry__check_and_remove_filter(he, HIST_FILTER__SYMBOL,
1274                                             perf_hpp__is_sym_entry);
1275
1276         hists__apply_filters(he->hists, he);
1277 }
1278
1279 static struct hist_entry *hierarchy_insert_entry(struct hists *hists,
1280                                                  struct rb_root *root,
1281                                                  struct hist_entry *he,
1282                                                  struct hist_entry *parent_he,
1283                                                  struct perf_hpp_list *hpp_list)
1284 {
1285         struct rb_node **p = &root->rb_node;
1286         struct rb_node *parent = NULL;
1287         struct hist_entry *iter, *new;
1288         struct perf_hpp_fmt *fmt;
1289         int64_t cmp;
1290
1291         while (*p != NULL) {
1292                 parent = *p;
1293                 iter = rb_entry(parent, struct hist_entry, rb_node_in);
1294
1295                 cmp = 0;
1296                 perf_hpp_list__for_each_sort_list(hpp_list, fmt) {
1297                         cmp = fmt->collapse(fmt, iter, he);
1298                         if (cmp)
1299                                 break;
1300                 }
1301
1302                 if (!cmp) {
1303                         he_stat__add_stat(&iter->stat, &he->stat);
1304                         return iter;
1305                 }
1306
1307                 if (cmp < 0)
1308                         p = &parent->rb_left;
1309                 else
1310                         p = &parent->rb_right;
1311         }
1312
1313         new = hist_entry__new(he, true);
1314         if (new == NULL)
1315                 return NULL;
1316
1317         hists->nr_entries++;
1318
1319         /* save related format list for output */
1320         new->hpp_list = hpp_list;
1321         new->parent_he = parent_he;
1322
1323         hist_entry__apply_hierarchy_filters(new);
1324
1325         /* some fields are now passed to 'new' */
1326         perf_hpp_list__for_each_sort_list(hpp_list, fmt) {
1327                 if (perf_hpp__is_trace_entry(fmt) || perf_hpp__is_dynamic_entry(fmt))
1328                         he->trace_output = NULL;
1329                 else
1330                         new->trace_output = NULL;
1331
1332                 if (perf_hpp__is_srcline_entry(fmt))
1333                         he->srcline = NULL;
1334                 else
1335                         new->srcline = NULL;
1336
1337                 if (perf_hpp__is_srcfile_entry(fmt))
1338                         he->srcfile = NULL;
1339                 else
1340                         new->srcfile = NULL;
1341         }
1342
1343         rb_link_node(&new->rb_node_in, parent, p);
1344         rb_insert_color(&new->rb_node_in, root);
1345         return new;
1346 }
1347
1348 static int hists__hierarchy_insert_entry(struct hists *hists,
1349                                          struct rb_root *root,
1350                                          struct hist_entry *he)
1351 {
1352         struct perf_hpp_list_node *node;
1353         struct hist_entry *new_he = NULL;
1354         struct hist_entry *parent = NULL;
1355         int depth = 0;
1356         int ret = 0;
1357
1358         list_for_each_entry(node, &hists->hpp_formats, list) {
1359                 /* skip period (overhead) and elided columns */
1360                 if (node->level == 0 || node->skip)
1361                         continue;
1362
1363                 /* insert copy of 'he' for each fmt into the hierarchy */
1364                 new_he = hierarchy_insert_entry(hists, root, he, parent, &node->hpp);
1365                 if (new_he == NULL) {
1366                         ret = -1;
1367                         break;
1368                 }
1369
1370                 root = &new_he->hroot_in;
1371                 new_he->depth = depth++;
1372                 parent = new_he;
1373         }
1374
1375         if (new_he) {
1376                 new_he->leaf = true;
1377
1378                 if (hist_entry__has_callchains(new_he) &&
1379                     symbol_conf.use_callchain) {
1380                         callchain_cursor_reset(&callchain_cursor);
1381                         if (callchain_merge(&callchain_cursor,
1382                                             new_he->callchain,
1383                                             he->callchain) < 0)
1384                                 ret = -1;
1385                 }
1386         }
1387
1388         /* 'he' is no longer used */
1389         hist_entry__delete(he);
1390
1391         /* return 0 (or -1) since it already applied filters */
1392         return ret;
1393 }
1394
1395 static int hists__collapse_insert_entry(struct hists *hists,
1396                                         struct rb_root *root,
1397                                         struct hist_entry *he)
1398 {
1399         struct rb_node **p = &root->rb_node;
1400         struct rb_node *parent = NULL;
1401         struct hist_entry *iter;
1402         int64_t cmp;
1403
1404         if (symbol_conf.report_hierarchy)
1405                 return hists__hierarchy_insert_entry(hists, root, he);
1406
1407         while (*p != NULL) {
1408                 parent = *p;
1409                 iter = rb_entry(parent, struct hist_entry, rb_node_in);
1410
1411                 cmp = hist_entry__collapse(iter, he);
1412
1413                 if (!cmp) {
1414                         int ret = 0;
1415
1416                         he_stat__add_stat(&iter->stat, &he->stat);
1417                         if (symbol_conf.cumulate_callchain)
1418                                 he_stat__add_stat(iter->stat_acc, he->stat_acc);
1419
1420                         if (hist_entry__has_callchains(he) && symbol_conf.use_callchain) {
1421                                 callchain_cursor_reset(&callchain_cursor);
1422                                 if (callchain_merge(&callchain_cursor,
1423                                                     iter->callchain,
1424                                                     he->callchain) < 0)
1425                                         ret = -1;
1426                         }
1427                         hist_entry__delete(he);
1428                         return ret;
1429                 }
1430
1431                 if (cmp < 0)
1432                         p = &(*p)->rb_left;
1433                 else
1434                         p = &(*p)->rb_right;
1435         }
1436         hists->nr_entries++;
1437
1438         rb_link_node(&he->rb_node_in, parent, p);
1439         rb_insert_color(&he->rb_node_in, root);
1440         return 1;
1441 }
1442
1443 struct rb_root *hists__get_rotate_entries_in(struct hists *hists)
1444 {
1445         struct rb_root *root;
1446
1447         pthread_mutex_lock(&hists->lock);
1448
1449         root = hists->entries_in;
1450         if (++hists->entries_in > &hists->entries_in_array[1])
1451                 hists->entries_in = &hists->entries_in_array[0];
1452
1453         pthread_mutex_unlock(&hists->lock);
1454
1455         return root;
1456 }
1457
1458 static void hists__apply_filters(struct hists *hists, struct hist_entry *he)
1459 {
1460         hists__filter_entry_by_dso(hists, he);
1461         hists__filter_entry_by_thread(hists, he);
1462         hists__filter_entry_by_symbol(hists, he);
1463         hists__filter_entry_by_socket(hists, he);
1464 }
1465
1466 int hists__collapse_resort(struct hists *hists, struct ui_progress *prog)
1467 {
1468         struct rb_root *root;
1469         struct rb_node *next;
1470         struct hist_entry *n;
1471         int ret;
1472
1473         if (!hists__has(hists, need_collapse))
1474                 return 0;
1475
1476         hists->nr_entries = 0;
1477
1478         root = hists__get_rotate_entries_in(hists);
1479
1480         next = rb_first(root);
1481
1482         while (next) {
1483                 if (session_done())
1484                         break;
1485                 n = rb_entry(next, struct hist_entry, rb_node_in);
1486                 next = rb_next(&n->rb_node_in);
1487
1488                 rb_erase(&n->rb_node_in, root);
1489                 ret = hists__collapse_insert_entry(hists, &hists->entries_collapsed, n);
1490                 if (ret < 0)
1491                         return -1;
1492
1493                 if (ret) {
1494                         /*
1495                          * If it wasn't combined with one of the entries already
1496                          * collapsed, we need to apply the filters that may have
1497                          * been set by, say, the hist_browser.
1498                          */
1499                         hists__apply_filters(hists, n);
1500                 }
1501                 if (prog)
1502                         ui_progress__update(prog, 1);
1503         }
1504         return 0;
1505 }
1506
1507 static int hist_entry__sort(struct hist_entry *a, struct hist_entry *b)
1508 {
1509         struct hists *hists = a->hists;
1510         struct perf_hpp_fmt *fmt;
1511         int64_t cmp = 0;
1512
1513         hists__for_each_sort_list(hists, fmt) {
1514                 if (perf_hpp__should_skip(fmt, a->hists))
1515                         continue;
1516
1517                 cmp = fmt->sort(fmt, a, b);
1518                 if (cmp)
1519                         break;
1520         }
1521
1522         return cmp;
1523 }
1524
1525 static void hists__reset_filter_stats(struct hists *hists)
1526 {
1527         hists->nr_non_filtered_entries = 0;
1528         hists->stats.total_non_filtered_period = 0;
1529 }
1530
1531 void hists__reset_stats(struct hists *hists)
1532 {
1533         hists->nr_entries = 0;
1534         hists->stats.total_period = 0;
1535
1536         hists__reset_filter_stats(hists);
1537 }
1538
1539 static void hists__inc_filter_stats(struct hists *hists, struct hist_entry *h)
1540 {
1541         hists->nr_non_filtered_entries++;
1542         hists->stats.total_non_filtered_period += h->stat.period;
1543 }
1544
1545 void hists__inc_stats(struct hists *hists, struct hist_entry *h)
1546 {
1547         if (!h->filtered)
1548                 hists__inc_filter_stats(hists, h);
1549
1550         hists->nr_entries++;
1551         hists->stats.total_period += h->stat.period;
1552 }
1553
1554 static void hierarchy_recalc_total_periods(struct hists *hists)
1555 {
1556         struct rb_node *node;
1557         struct hist_entry *he;
1558
1559         node = rb_first(&hists->entries);
1560
1561         hists->stats.total_period = 0;
1562         hists->stats.total_non_filtered_period = 0;
1563
1564         /*
1565          * recalculate total period using top-level entries only
1566          * since lower level entries only see non-filtered entries
1567          * but upper level entries have sum of both entries.
1568          */
1569         while (node) {
1570                 he = rb_entry(node, struct hist_entry, rb_node);
1571                 node = rb_next(node);
1572
1573                 hists->stats.total_period += he->stat.period;
1574                 if (!he->filtered)
1575                         hists->stats.total_non_filtered_period += he->stat.period;
1576         }
1577 }
1578
1579 static void hierarchy_insert_output_entry(struct rb_root *root,
1580                                           struct hist_entry *he)
1581 {
1582         struct rb_node **p = &root->rb_node;
1583         struct rb_node *parent = NULL;
1584         struct hist_entry *iter;
1585         struct perf_hpp_fmt *fmt;
1586
1587         while (*p != NULL) {
1588                 parent = *p;
1589                 iter = rb_entry(parent, struct hist_entry, rb_node);
1590
1591                 if (hist_entry__sort(he, iter) > 0)
1592                         p = &parent->rb_left;
1593                 else
1594                         p = &parent->rb_right;
1595         }
1596
1597         rb_link_node(&he->rb_node, parent, p);
1598         rb_insert_color(&he->rb_node, root);
1599
1600         /* update column width of dynamic entry */
1601         perf_hpp_list__for_each_sort_list(he->hpp_list, fmt) {
1602                 if (perf_hpp__is_dynamic_entry(fmt))
1603                         fmt->sort(fmt, he, NULL);
1604         }
1605 }
1606
1607 static void hists__hierarchy_output_resort(struct hists *hists,
1608                                            struct ui_progress *prog,
1609                                            struct rb_root *root_in,
1610                                            struct rb_root *root_out,
1611                                            u64 min_callchain_hits,
1612                                            bool use_callchain)
1613 {
1614         struct rb_node *node;
1615         struct hist_entry *he;
1616
1617         *root_out = RB_ROOT;
1618         node = rb_first(root_in);
1619
1620         while (node) {
1621                 he = rb_entry(node, struct hist_entry, rb_node_in);
1622                 node = rb_next(node);
1623
1624                 hierarchy_insert_output_entry(root_out, he);
1625
1626                 if (prog)
1627                         ui_progress__update(prog, 1);
1628
1629                 hists->nr_entries++;
1630                 if (!he->filtered) {
1631                         hists->nr_non_filtered_entries++;
1632                         hists__calc_col_len(hists, he);
1633                 }
1634
1635                 if (!he->leaf) {
1636                         hists__hierarchy_output_resort(hists, prog,
1637                                                        &he->hroot_in,
1638                                                        &he->hroot_out,
1639                                                        min_callchain_hits,
1640                                                        use_callchain);
1641                         continue;
1642                 }
1643
1644                 if (!use_callchain)
1645                         continue;
1646
1647                 if (callchain_param.mode == CHAIN_GRAPH_REL) {
1648                         u64 total = he->stat.period;
1649
1650                         if (symbol_conf.cumulate_callchain)
1651                                 total = he->stat_acc->period;
1652
1653                         min_callchain_hits = total * (callchain_param.min_percent / 100);
1654                 }
1655
1656                 callchain_param.sort(&he->sorted_chain, he->callchain,
1657                                      min_callchain_hits, &callchain_param);
1658         }
1659 }
1660
1661 static void __hists__insert_output_entry(struct rb_root *entries,
1662                                          struct hist_entry *he,
1663                                          u64 min_callchain_hits,
1664                                          bool use_callchain)
1665 {
1666         struct rb_node **p = &entries->rb_node;
1667         struct rb_node *parent = NULL;
1668         struct hist_entry *iter;
1669         struct perf_hpp_fmt *fmt;
1670
1671         if (use_callchain) {
1672                 if (callchain_param.mode == CHAIN_GRAPH_REL) {
1673                         u64 total = he->stat.period;
1674
1675                         if (symbol_conf.cumulate_callchain)
1676                                 total = he->stat_acc->period;
1677
1678                         min_callchain_hits = total * (callchain_param.min_percent / 100);
1679                 }
1680                 callchain_param.sort(&he->sorted_chain, he->callchain,
1681                                       min_callchain_hits, &callchain_param);
1682         }
1683
1684         while (*p != NULL) {
1685                 parent = *p;
1686                 iter = rb_entry(parent, struct hist_entry, rb_node);
1687
1688                 if (hist_entry__sort(he, iter) > 0)
1689                         p = &(*p)->rb_left;
1690                 else
1691                         p = &(*p)->rb_right;
1692         }
1693
1694         rb_link_node(&he->rb_node, parent, p);
1695         rb_insert_color(&he->rb_node, entries);
1696
1697         perf_hpp_list__for_each_sort_list(&perf_hpp_list, fmt) {
1698                 if (perf_hpp__is_dynamic_entry(fmt) &&
1699                     perf_hpp__defined_dynamic_entry(fmt, he->hists))
1700                         fmt->sort(fmt, he, NULL);  /* update column width */
1701         }
1702 }
1703
1704 static void output_resort(struct hists *hists, struct ui_progress *prog,
1705                           bool use_callchain, hists__resort_cb_t cb)
1706 {
1707         struct rb_root *root;
1708         struct rb_node *next;
1709         struct hist_entry *n;
1710         u64 callchain_total;
1711         u64 min_callchain_hits;
1712
1713         callchain_total = hists->callchain_period;
1714         if (symbol_conf.filter_relative)
1715                 callchain_total = hists->callchain_non_filtered_period;
1716
1717         min_callchain_hits = callchain_total * (callchain_param.min_percent / 100);
1718
1719         hists__reset_stats(hists);
1720         hists__reset_col_len(hists);
1721
1722         if (symbol_conf.report_hierarchy) {
1723                 hists__hierarchy_output_resort(hists, prog,
1724                                                &hists->entries_collapsed,
1725                                                &hists->entries,
1726                                                min_callchain_hits,
1727                                                use_callchain);
1728                 hierarchy_recalc_total_periods(hists);
1729                 return;
1730         }
1731
1732         if (hists__has(hists, need_collapse))
1733                 root = &hists->entries_collapsed;
1734         else
1735                 root = hists->entries_in;
1736
1737         next = rb_first(root);
1738         hists->entries = RB_ROOT;
1739
1740         while (next) {
1741                 n = rb_entry(next, struct hist_entry, rb_node_in);
1742                 next = rb_next(&n->rb_node_in);
1743
1744                 if (cb && cb(n))
1745                         continue;
1746
1747                 __hists__insert_output_entry(&hists->entries, n, min_callchain_hits, use_callchain);
1748                 hists__inc_stats(hists, n);
1749
1750                 if (!n->filtered)
1751                         hists__calc_col_len(hists, n);
1752
1753                 if (prog)
1754                         ui_progress__update(prog, 1);
1755         }
1756 }
1757
1758 void perf_evsel__output_resort(struct perf_evsel *evsel, struct ui_progress *prog)
1759 {
1760         bool use_callchain;
1761
1762         if (evsel && symbol_conf.use_callchain && !symbol_conf.show_ref_callgraph)
1763                 use_callchain = evsel__has_callchain(evsel);
1764         else
1765                 use_callchain = symbol_conf.use_callchain;
1766
1767         use_callchain |= symbol_conf.show_branchflag_count;
1768
1769         output_resort(evsel__hists(evsel), prog, use_callchain, NULL);
1770 }
1771
1772 void hists__output_resort(struct hists *hists, struct ui_progress *prog)
1773 {
1774         output_resort(hists, prog, symbol_conf.use_callchain, NULL);
1775 }
1776
1777 void hists__output_resort_cb(struct hists *hists, struct ui_progress *prog,
1778                              hists__resort_cb_t cb)
1779 {
1780         output_resort(hists, prog, symbol_conf.use_callchain, cb);
1781 }
1782
1783 static bool can_goto_child(struct hist_entry *he, enum hierarchy_move_dir hmd)
1784 {
1785         if (he->leaf || hmd == HMD_FORCE_SIBLING)
1786                 return false;
1787
1788         if (he->unfolded || hmd == HMD_FORCE_CHILD)
1789                 return true;
1790
1791         return false;
1792 }
1793
1794 struct rb_node *rb_hierarchy_last(struct rb_node *node)
1795 {
1796         struct hist_entry *he = rb_entry(node, struct hist_entry, rb_node);
1797
1798         while (can_goto_child(he, HMD_NORMAL)) {
1799                 node = rb_last(&he->hroot_out);
1800                 he = rb_entry(node, struct hist_entry, rb_node);
1801         }
1802         return node;
1803 }
1804
1805 struct rb_node *__rb_hierarchy_next(struct rb_node *node, enum hierarchy_move_dir hmd)
1806 {
1807         struct hist_entry *he = rb_entry(node, struct hist_entry, rb_node);
1808
1809         if (can_goto_child(he, hmd))
1810                 node = rb_first(&he->hroot_out);
1811         else
1812                 node = rb_next(node);
1813
1814         while (node == NULL) {
1815                 he = he->parent_he;
1816                 if (he == NULL)
1817                         break;
1818
1819                 node = rb_next(&he->rb_node);
1820         }
1821         return node;
1822 }
1823
1824 struct rb_node *rb_hierarchy_prev(struct rb_node *node)
1825 {
1826         struct hist_entry *he = rb_entry(node, struct hist_entry, rb_node);
1827
1828         node = rb_prev(node);
1829         if (node)
1830                 return rb_hierarchy_last(node);
1831
1832         he = he->parent_he;
1833         if (he == NULL)
1834                 return NULL;
1835
1836         return &he->rb_node;
1837 }
1838
1839 bool hist_entry__has_hierarchy_children(struct hist_entry *he, float limit)
1840 {
1841         struct rb_node *node;
1842         struct hist_entry *child;
1843         float percent;
1844
1845         if (he->leaf)
1846                 return false;
1847
1848         node = rb_first(&he->hroot_out);
1849         child = rb_entry(node, struct hist_entry, rb_node);
1850
1851         while (node && child->filtered) {
1852                 node = rb_next(node);
1853                 child = rb_entry(node, struct hist_entry, rb_node);
1854         }
1855
1856         if (node)
1857                 percent = hist_entry__get_percent_limit(child);
1858         else
1859                 percent = 0;
1860
1861         return node && percent >= limit;
1862 }
1863
1864 static void hists__remove_entry_filter(struct hists *hists, struct hist_entry *h,
1865                                        enum hist_filter filter)
1866 {
1867         h->filtered &= ~(1 << filter);
1868
1869         if (symbol_conf.report_hierarchy) {
1870                 struct hist_entry *parent = h->parent_he;
1871
1872                 while (parent) {
1873                         he_stat__add_stat(&parent->stat, &h->stat);
1874
1875                         parent->filtered &= ~(1 << filter);
1876
1877                         if (parent->filtered)
1878                                 goto next;
1879
1880                         /* force fold unfiltered entry for simplicity */
1881                         parent->unfolded = false;
1882                         parent->has_no_entry = false;
1883                         parent->row_offset = 0;
1884                         parent->nr_rows = 0;
1885 next:
1886                         parent = parent->parent_he;
1887                 }
1888         }
1889
1890         if (h->filtered)
1891                 return;
1892
1893         /* force fold unfiltered entry for simplicity */
1894         h->unfolded = false;
1895         h->has_no_entry = false;
1896         h->row_offset = 0;
1897         h->nr_rows = 0;
1898
1899         hists->stats.nr_non_filtered_samples += h->stat.nr_events;
1900
1901         hists__inc_filter_stats(hists, h);
1902         hists__calc_col_len(hists, h);
1903 }
1904
1905
1906 static bool hists__filter_entry_by_dso(struct hists *hists,
1907                                        struct hist_entry *he)
1908 {
1909         if (hists->dso_filter != NULL &&
1910             (he->ms.map == NULL || he->ms.map->dso != hists->dso_filter)) {
1911                 he->filtered |= (1 << HIST_FILTER__DSO);
1912                 return true;
1913         }
1914
1915         return false;
1916 }
1917
1918 static bool hists__filter_entry_by_thread(struct hists *hists,
1919                                           struct hist_entry *he)
1920 {
1921         if (hists->thread_filter != NULL &&
1922             he->thread != hists->thread_filter) {
1923                 he->filtered |= (1 << HIST_FILTER__THREAD);
1924                 return true;
1925         }
1926
1927         return false;
1928 }
1929
1930 static bool hists__filter_entry_by_symbol(struct hists *hists,
1931                                           struct hist_entry *he)
1932 {
1933         if (hists->symbol_filter_str != NULL &&
1934             (!he->ms.sym || strstr(he->ms.sym->name,
1935                                    hists->symbol_filter_str) == NULL)) {
1936                 he->filtered |= (1 << HIST_FILTER__SYMBOL);
1937                 return true;
1938         }
1939
1940         return false;
1941 }
1942
1943 static bool hists__filter_entry_by_socket(struct hists *hists,
1944                                           struct hist_entry *he)
1945 {
1946         if ((hists->socket_filter > -1) &&
1947             (he->socket != hists->socket_filter)) {
1948                 he->filtered |= (1 << HIST_FILTER__SOCKET);
1949                 return true;
1950         }
1951
1952         return false;
1953 }
1954
1955 typedef bool (*filter_fn_t)(struct hists *hists, struct hist_entry *he);
1956
1957 static void hists__filter_by_type(struct hists *hists, int type, filter_fn_t filter)
1958 {
1959         struct rb_node *nd;
1960
1961         hists->stats.nr_non_filtered_samples = 0;
1962
1963         hists__reset_filter_stats(hists);
1964         hists__reset_col_len(hists);
1965
1966         for (nd = rb_first(&hists->entries); nd; nd = rb_next(nd)) {
1967                 struct hist_entry *h = rb_entry(nd, struct hist_entry, rb_node);
1968
1969                 if (filter(hists, h))
1970                         continue;
1971
1972                 hists__remove_entry_filter(hists, h, type);
1973         }
1974 }
1975
1976 static void resort_filtered_entry(struct rb_root *root, struct hist_entry *he)
1977 {
1978         struct rb_node **p = &root->rb_node;
1979         struct rb_node *parent = NULL;
1980         struct hist_entry *iter;
1981         struct rb_root new_root = RB_ROOT;
1982         struct rb_node *nd;
1983
1984         while (*p != NULL) {
1985                 parent = *p;
1986                 iter = rb_entry(parent, struct hist_entry, rb_node);
1987
1988                 if (hist_entry__sort(he, iter) > 0)
1989                         p = &(*p)->rb_left;
1990                 else
1991                         p = &(*p)->rb_right;
1992         }
1993
1994         rb_link_node(&he->rb_node, parent, p);
1995         rb_insert_color(&he->rb_node, root);
1996
1997         if (he->leaf || he->filtered)
1998                 return;
1999
2000         nd = rb_first(&he->hroot_out);
2001         while (nd) {
2002                 struct hist_entry *h = rb_entry(nd, struct hist_entry, rb_node);
2003
2004                 nd = rb_next(nd);
2005                 rb_erase(&h->rb_node, &he->hroot_out);
2006
2007                 resort_filtered_entry(&new_root, h);
2008         }
2009
2010         he->hroot_out = new_root;
2011 }
2012
2013 static void hists__filter_hierarchy(struct hists *hists, int type, const void *arg)
2014 {
2015         struct rb_node *nd;
2016         struct rb_root new_root = RB_ROOT;
2017
2018         hists->stats.nr_non_filtered_samples = 0;
2019
2020         hists__reset_filter_stats(hists);
2021         hists__reset_col_len(hists);
2022
2023         nd = rb_first(&hists->entries);
2024         while (nd) {
2025                 struct hist_entry *h = rb_entry(nd, struct hist_entry, rb_node);
2026                 int ret;
2027
2028                 ret = hist_entry__filter(h, type, arg);
2029
2030                 /*
2031                  * case 1. non-matching type
2032                  * zero out the period, set filter marker and move to child
2033                  */
2034                 if (ret < 0) {
2035                         memset(&h->stat, 0, sizeof(h->stat));
2036                         h->filtered |= (1 << type);
2037
2038                         nd = __rb_hierarchy_next(&h->rb_node, HMD_FORCE_CHILD);
2039                 }
2040                 /*
2041                  * case 2. matched type (filter out)
2042                  * set filter marker and move to next
2043                  */
2044                 else if (ret == 1) {
2045                         h->filtered |= (1 << type);
2046
2047                         nd = __rb_hierarchy_next(&h->rb_node, HMD_FORCE_SIBLING);
2048                 }
2049                 /*
2050                  * case 3. ok (not filtered)
2051                  * add period to hists and parents, erase the filter marker
2052                  * and move to next sibling
2053                  */
2054                 else {
2055                         hists__remove_entry_filter(hists, h, type);
2056
2057                         nd = __rb_hierarchy_next(&h->rb_node, HMD_FORCE_SIBLING);
2058                 }
2059         }
2060
2061         hierarchy_recalc_total_periods(hists);
2062
2063         /*
2064          * resort output after applying a new filter since filter in a lower
2065          * hierarchy can change periods in a upper hierarchy.
2066          */
2067         nd = rb_first(&hists->entries);
2068         while (nd) {
2069                 struct hist_entry *h = rb_entry(nd, struct hist_entry, rb_node);
2070
2071                 nd = rb_next(nd);
2072                 rb_erase(&h->rb_node, &hists->entries);
2073
2074                 resort_filtered_entry(&new_root, h);
2075         }
2076
2077         hists->entries = new_root;
2078 }
2079
2080 void hists__filter_by_thread(struct hists *hists)
2081 {
2082         if (symbol_conf.report_hierarchy)
2083                 hists__filter_hierarchy(hists, HIST_FILTER__THREAD,
2084                                         hists->thread_filter);
2085         else
2086                 hists__filter_by_type(hists, HIST_FILTER__THREAD,
2087                                       hists__filter_entry_by_thread);
2088 }
2089
2090 void hists__filter_by_dso(struct hists *hists)
2091 {
2092         if (symbol_conf.report_hierarchy)
2093                 hists__filter_hierarchy(hists, HIST_FILTER__DSO,
2094                                         hists->dso_filter);
2095         else
2096                 hists__filter_by_type(hists, HIST_FILTER__DSO,
2097                                       hists__filter_entry_by_dso);
2098 }
2099
2100 void hists__filter_by_symbol(struct hists *hists)
2101 {
2102         if (symbol_conf.report_hierarchy)
2103                 hists__filter_hierarchy(hists, HIST_FILTER__SYMBOL,
2104                                         hists->symbol_filter_str);
2105         else
2106                 hists__filter_by_type(hists, HIST_FILTER__SYMBOL,
2107                                       hists__filter_entry_by_symbol);
2108 }
2109
2110 void hists__filter_by_socket(struct hists *hists)
2111 {
2112         if (symbol_conf.report_hierarchy)
2113                 hists__filter_hierarchy(hists, HIST_FILTER__SOCKET,
2114                                         &hists->socket_filter);
2115         else
2116                 hists__filter_by_type(hists, HIST_FILTER__SOCKET,
2117                                       hists__filter_entry_by_socket);
2118 }
2119
2120 void events_stats__inc(struct events_stats *stats, u32 type)
2121 {
2122         ++stats->nr_events[0];
2123         ++stats->nr_events[type];
2124 }
2125
2126 void hists__inc_nr_events(struct hists *hists, u32 type)
2127 {
2128         events_stats__inc(&hists->stats, type);
2129 }
2130
2131 void hists__inc_nr_samples(struct hists *hists, bool filtered)
2132 {
2133         events_stats__inc(&hists->stats, PERF_RECORD_SAMPLE);
2134         if (!filtered)
2135                 hists->stats.nr_non_filtered_samples++;
2136 }
2137
2138 static struct hist_entry *hists__add_dummy_entry(struct hists *hists,
2139                                                  struct hist_entry *pair)
2140 {
2141         struct rb_root *root;
2142         struct rb_node **p;
2143         struct rb_node *parent = NULL;
2144         struct hist_entry *he;
2145         int64_t cmp;
2146
2147         if (hists__has(hists, need_collapse))
2148                 root = &hists->entries_collapsed;
2149         else
2150                 root = hists->entries_in;
2151
2152         p = &root->rb_node;
2153
2154         while (*p != NULL) {
2155                 parent = *p;
2156                 he = rb_entry(parent, struct hist_entry, rb_node_in);
2157
2158                 cmp = hist_entry__collapse(he, pair);
2159
2160                 if (!cmp)
2161                         goto out;
2162
2163                 if (cmp < 0)
2164                         p = &(*p)->rb_left;
2165                 else
2166                         p = &(*p)->rb_right;
2167         }
2168
2169         he = hist_entry__new(pair, true);
2170         if (he) {
2171                 memset(&he->stat, 0, sizeof(he->stat));
2172                 he->hists = hists;
2173                 if (symbol_conf.cumulate_callchain)
2174                         memset(he->stat_acc, 0, sizeof(he->stat));
2175                 rb_link_node(&he->rb_node_in, parent, p);
2176                 rb_insert_color(&he->rb_node_in, root);
2177                 hists__inc_stats(hists, he);
2178                 he->dummy = true;
2179         }
2180 out:
2181         return he;
2182 }
2183
2184 static struct hist_entry *add_dummy_hierarchy_entry(struct hists *hists,
2185                                                     struct rb_root *root,
2186                                                     struct hist_entry *pair)
2187 {
2188         struct rb_node **p;
2189         struct rb_node *parent = NULL;
2190         struct hist_entry *he;
2191         struct perf_hpp_fmt *fmt;
2192
2193         p = &root->rb_node;
2194         while (*p != NULL) {
2195                 int64_t cmp = 0;
2196
2197                 parent = *p;
2198                 he = rb_entry(parent, struct hist_entry, rb_node_in);
2199
2200                 perf_hpp_list__for_each_sort_list(he->hpp_list, fmt) {
2201                         cmp = fmt->collapse(fmt, he, pair);
2202                         if (cmp)
2203                                 break;
2204                 }
2205                 if (!cmp)
2206                         goto out;
2207
2208                 if (cmp < 0)
2209                         p = &parent->rb_left;
2210                 else
2211                         p = &parent->rb_right;
2212         }
2213
2214         he = hist_entry__new(pair, true);
2215         if (he) {
2216                 rb_link_node(&he->rb_node_in, parent, p);
2217                 rb_insert_color(&he->rb_node_in, root);
2218
2219                 he->dummy = true;
2220                 he->hists = hists;
2221                 memset(&he->stat, 0, sizeof(he->stat));
2222                 hists__inc_stats(hists, he);
2223         }
2224 out:
2225         return he;
2226 }
2227
2228 static struct hist_entry *hists__find_entry(struct hists *hists,
2229                                             struct hist_entry *he)
2230 {
2231         struct rb_node *n;
2232
2233         if (hists__has(hists, need_collapse))
2234                 n = hists->entries_collapsed.rb_node;
2235         else
2236                 n = hists->entries_in->rb_node;
2237
2238         while (n) {
2239                 struct hist_entry *iter = rb_entry(n, struct hist_entry, rb_node_in);
2240                 int64_t cmp = hist_entry__collapse(iter, he);
2241
2242                 if (cmp < 0)
2243                         n = n->rb_left;
2244                 else if (cmp > 0)
2245                         n = n->rb_right;
2246                 else
2247                         return iter;
2248         }
2249
2250         return NULL;
2251 }
2252
2253 static struct hist_entry *hists__find_hierarchy_entry(struct rb_root *root,
2254                                                       struct hist_entry *he)
2255 {
2256         struct rb_node *n = root->rb_node;
2257
2258         while (n) {
2259                 struct hist_entry *iter;
2260                 struct perf_hpp_fmt *fmt;
2261                 int64_t cmp = 0;
2262
2263                 iter = rb_entry(n, struct hist_entry, rb_node_in);
2264                 perf_hpp_list__for_each_sort_list(he->hpp_list, fmt) {
2265                         cmp = fmt->collapse(fmt, iter, he);
2266                         if (cmp)
2267                                 break;
2268                 }
2269
2270                 if (cmp < 0)
2271                         n = n->rb_left;
2272                 else if (cmp > 0)
2273                         n = n->rb_right;
2274                 else
2275                         return iter;
2276         }
2277
2278         return NULL;
2279 }
2280
2281 static void hists__match_hierarchy(struct rb_root *leader_root,
2282                                    struct rb_root *other_root)
2283 {
2284         struct rb_node *nd;
2285         struct hist_entry *pos, *pair;
2286
2287         for (nd = rb_first(leader_root); nd; nd = rb_next(nd)) {
2288                 pos  = rb_entry(nd, struct hist_entry, rb_node_in);
2289                 pair = hists__find_hierarchy_entry(other_root, pos);
2290
2291                 if (pair) {
2292                         hist_entry__add_pair(pair, pos);
2293                         hists__match_hierarchy(&pos->hroot_in, &pair->hroot_in);
2294                 }
2295         }
2296 }
2297
2298 /*
2299  * Look for pairs to link to the leader buckets (hist_entries):
2300  */
2301 void hists__match(struct hists *leader, struct hists *other)
2302 {
2303         struct rb_root *root;
2304         struct rb_node *nd;
2305         struct hist_entry *pos, *pair;
2306
2307         if (symbol_conf.report_hierarchy) {
2308                 /* hierarchy report always collapses entries */
2309                 return hists__match_hierarchy(&leader->entries_collapsed,
2310                                               &other->entries_collapsed);
2311         }
2312
2313         if (hists__has(leader, need_collapse))
2314                 root = &leader->entries_collapsed;
2315         else
2316                 root = leader->entries_in;
2317
2318         for (nd = rb_first(root); nd; nd = rb_next(nd)) {
2319                 pos  = rb_entry(nd, struct hist_entry, rb_node_in);
2320                 pair = hists__find_entry(other, pos);
2321
2322                 if (pair)
2323                         hist_entry__add_pair(pair, pos);
2324         }
2325 }
2326
2327 static int hists__link_hierarchy(struct hists *leader_hists,
2328                                  struct hist_entry *parent,
2329                                  struct rb_root *leader_root,
2330                                  struct rb_root *other_root)
2331 {
2332         struct rb_node *nd;
2333         struct hist_entry *pos, *leader;
2334
2335         for (nd = rb_first(other_root); nd; nd = rb_next(nd)) {
2336                 pos = rb_entry(nd, struct hist_entry, rb_node_in);
2337
2338                 if (hist_entry__has_pairs(pos)) {
2339                         bool found = false;
2340
2341                         list_for_each_entry(leader, &pos->pairs.head, pairs.node) {
2342                                 if (leader->hists == leader_hists) {
2343                                         found = true;
2344                                         break;
2345                                 }
2346                         }
2347                         if (!found)
2348                                 return -1;
2349                 } else {
2350                         leader = add_dummy_hierarchy_entry(leader_hists,
2351                                                            leader_root, pos);
2352                         if (leader == NULL)
2353                                 return -1;
2354
2355                         /* do not point parent in the pos */
2356                         leader->parent_he = parent;
2357
2358                         hist_entry__add_pair(pos, leader);
2359                 }
2360
2361                 if (!pos->leaf) {
2362                         if (hists__link_hierarchy(leader_hists, leader,
2363                                                   &leader->hroot_in,
2364                                                   &pos->hroot_in) < 0)
2365                                 return -1;
2366                 }
2367         }
2368         return 0;
2369 }
2370
2371 /*
2372  * Look for entries in the other hists that are not present in the leader, if
2373  * we find them, just add a dummy entry on the leader hists, with period=0,
2374  * nr_events=0, to serve as the list header.
2375  */
2376 int hists__link(struct hists *leader, struct hists *other)
2377 {
2378         struct rb_root *root;
2379         struct rb_node *nd;
2380         struct hist_entry *pos, *pair;
2381
2382         if (symbol_conf.report_hierarchy) {
2383                 /* hierarchy report always collapses entries */
2384                 return hists__link_hierarchy(leader, NULL,
2385                                              &leader->entries_collapsed,
2386                                              &other->entries_collapsed);
2387         }
2388
2389         if (hists__has(other, need_collapse))
2390                 root = &other->entries_collapsed;
2391         else
2392                 root = other->entries_in;
2393
2394         for (nd = rb_first(root); nd; nd = rb_next(nd)) {
2395                 pos = rb_entry(nd, struct hist_entry, rb_node_in);
2396
2397                 if (!hist_entry__has_pairs(pos)) {
2398                         pair = hists__add_dummy_entry(leader, pos);
2399                         if (pair == NULL)
2400                                 return -1;
2401                         hist_entry__add_pair(pos, pair);
2402                 }
2403         }
2404
2405         return 0;
2406 }
2407
2408 void hist__account_cycles(struct branch_stack *bs, struct addr_location *al,
2409                           struct perf_sample *sample, bool nonany_branch_mode)
2410 {
2411         struct branch_info *bi;
2412
2413         /* If we have branch cycles always annotate them. */
2414         if (bs && bs->nr && bs->entries[0].flags.cycles) {
2415                 int i;
2416
2417                 bi = sample__resolve_bstack(sample, al);
2418                 if (bi) {
2419                         struct addr_map_symbol *prev = NULL;
2420
2421                         /*
2422                          * Ignore errors, still want to process the
2423                          * other entries.
2424                          *
2425                          * For non standard branch modes always
2426                          * force no IPC (prev == NULL)
2427                          *
2428                          * Note that perf stores branches reversed from
2429                          * program order!
2430                          */
2431                         for (i = bs->nr - 1; i >= 0; i--) {
2432                                 addr_map_symbol__account_cycles(&bi[i].from,
2433                                         nonany_branch_mode ? NULL : prev,
2434                                         bi[i].flags.cycles);
2435                                 prev = &bi[i].to;
2436                         }
2437                         free(bi);
2438                 }
2439         }
2440 }
2441
2442 size_t perf_evlist__fprintf_nr_events(struct perf_evlist *evlist, FILE *fp)
2443 {
2444         struct perf_evsel *pos;
2445         size_t ret = 0;
2446
2447         evlist__for_each_entry(evlist, pos) {
2448                 ret += fprintf(fp, "%s stats:\n", perf_evsel__name(pos));
2449                 ret += events_stats__fprintf(&evsel__hists(pos)->stats, fp);
2450         }
2451
2452         return ret;
2453 }
2454
2455
2456 u64 hists__total_period(struct hists *hists)
2457 {
2458         return symbol_conf.filter_relative ? hists->stats.total_non_filtered_period :
2459                 hists->stats.total_period;
2460 }
2461
2462 int __hists__scnprintf_title(struct hists *hists, char *bf, size_t size, bool show_freq)
2463 {
2464         char unit;
2465         int printed;
2466         const struct dso *dso = hists->dso_filter;
2467         const struct thread *thread = hists->thread_filter;
2468         int socket_id = hists->socket_filter;
2469         unsigned long nr_samples = hists->stats.nr_events[PERF_RECORD_SAMPLE];
2470         u64 nr_events = hists->stats.total_period;
2471         struct perf_evsel *evsel = hists_to_evsel(hists);
2472         const char *ev_name = perf_evsel__name(evsel);
2473         char buf[512], sample_freq_str[64] = "";
2474         size_t buflen = sizeof(buf);
2475         char ref[30] = " show reference callgraph, ";
2476         bool enable_ref = false;
2477
2478         if (symbol_conf.filter_relative) {
2479                 nr_samples = hists->stats.nr_non_filtered_samples;
2480                 nr_events = hists->stats.total_non_filtered_period;
2481         }
2482
2483         if (perf_evsel__is_group_event(evsel)) {
2484                 struct perf_evsel *pos;
2485
2486                 perf_evsel__group_desc(evsel, buf, buflen);
2487                 ev_name = buf;
2488
2489                 for_each_group_member(pos, evsel) {
2490                         struct hists *pos_hists = evsel__hists(pos);
2491
2492                         if (symbol_conf.filter_relative) {
2493                                 nr_samples += pos_hists->stats.nr_non_filtered_samples;
2494                                 nr_events += pos_hists->stats.total_non_filtered_period;
2495                         } else {
2496                                 nr_samples += pos_hists->stats.nr_events[PERF_RECORD_SAMPLE];
2497                                 nr_events += pos_hists->stats.total_period;
2498                         }
2499                 }
2500         }
2501
2502         if (symbol_conf.show_ref_callgraph &&
2503             strstr(ev_name, "call-graph=no"))
2504                 enable_ref = true;
2505
2506         if (show_freq)
2507                 scnprintf(sample_freq_str, sizeof(sample_freq_str), " %d Hz,", evsel->attr.sample_freq);
2508
2509         nr_samples = convert_unit(nr_samples, &unit);
2510         printed = scnprintf(bf, size,
2511                            "Samples: %lu%c of event%s '%s',%s%sEvent count (approx.): %" PRIu64,
2512                            nr_samples, unit, evsel->nr_members > 1 ? "s" : "",
2513                            ev_name, sample_freq_str, enable_ref ? ref : " ", nr_events);
2514
2515
2516         if (hists->uid_filter_str)
2517                 printed += snprintf(bf + printed, size - printed,
2518                                     ", UID: %s", hists->uid_filter_str);
2519         if (thread) {
2520                 if (hists__has(hists, thread)) {
2521                         printed += scnprintf(bf + printed, size - printed,
2522                                     ", Thread: %s(%d)",
2523                                      (thread->comm_set ? thread__comm_str(thread) : ""),
2524                                     thread->tid);
2525                 } else {
2526                         printed += scnprintf(bf + printed, size - printed,
2527                                     ", Thread: %s",
2528                                      (thread->comm_set ? thread__comm_str(thread) : ""));
2529                 }
2530         }
2531         if (dso)
2532                 printed += scnprintf(bf + printed, size - printed,
2533                                     ", DSO: %s", dso->short_name);
2534         if (socket_id > -1)
2535                 printed += scnprintf(bf + printed, size - printed,
2536                                     ", Processor Socket: %d", socket_id);
2537
2538         return printed;
2539 }
2540
2541 int parse_filter_percentage(const struct option *opt __maybe_unused,
2542                             const char *arg, int unset __maybe_unused)
2543 {
2544         if (!strcmp(arg, "relative"))
2545                 symbol_conf.filter_relative = true;
2546         else if (!strcmp(arg, "absolute"))
2547                 symbol_conf.filter_relative = false;
2548         else {
2549                 pr_debug("Invalid percentage: %s\n", arg);
2550                 return -1;
2551         }
2552
2553         return 0;
2554 }
2555
2556 int perf_hist_config(const char *var, const char *value)
2557 {
2558         if (!strcmp(var, "hist.percentage"))
2559                 return parse_filter_percentage(NULL, value, 0);
2560
2561         return 0;
2562 }
2563
2564 int __hists__init(struct hists *hists, struct perf_hpp_list *hpp_list)
2565 {
2566         memset(hists, 0, sizeof(*hists));
2567         hists->entries_in_array[0] = hists->entries_in_array[1] = RB_ROOT;
2568         hists->entries_in = &hists->entries_in_array[0];
2569         hists->entries_collapsed = RB_ROOT;
2570         hists->entries = RB_ROOT;
2571         pthread_mutex_init(&hists->lock, NULL);
2572         hists->socket_filter = -1;
2573         hists->hpp_list = hpp_list;
2574         INIT_LIST_HEAD(&hists->hpp_formats);
2575         return 0;
2576 }
2577
2578 static void hists__delete_remaining_entries(struct rb_root *root)
2579 {
2580         struct rb_node *node;
2581         struct hist_entry *he;
2582
2583         while (!RB_EMPTY_ROOT(root)) {
2584                 node = rb_first(root);
2585                 rb_erase(node, root);
2586
2587                 he = rb_entry(node, struct hist_entry, rb_node_in);
2588                 hist_entry__delete(he);
2589         }
2590 }
2591
2592 static void hists__delete_all_entries(struct hists *hists)
2593 {
2594         hists__delete_entries(hists);
2595         hists__delete_remaining_entries(&hists->entries_in_array[0]);
2596         hists__delete_remaining_entries(&hists->entries_in_array[1]);
2597         hists__delete_remaining_entries(&hists->entries_collapsed);
2598 }
2599
2600 static void hists_evsel__exit(struct perf_evsel *evsel)
2601 {
2602         struct hists *hists = evsel__hists(evsel);
2603         struct perf_hpp_fmt *fmt, *pos;
2604         struct perf_hpp_list_node *node, *tmp;
2605
2606         hists__delete_all_entries(hists);
2607
2608         list_for_each_entry_safe(node, tmp, &hists->hpp_formats, list) {
2609                 perf_hpp_list__for_each_format_safe(&node->hpp, fmt, pos) {
2610                         list_del(&fmt->list);
2611                         free(fmt);
2612                 }
2613                 list_del(&node->list);
2614                 free(node);
2615         }
2616 }
2617
2618 static int hists_evsel__init(struct perf_evsel *evsel)
2619 {
2620         struct hists *hists = evsel__hists(evsel);
2621
2622         __hists__init(hists, &perf_hpp_list);
2623         return 0;
2624 }
2625
2626 /*
2627  * XXX We probably need a hists_evsel__exit() to free the hist_entries
2628  * stored in the rbtree...
2629  */
2630
2631 int hists__init(void)
2632 {
2633         int err = perf_evsel__object_config(sizeof(struct hists_evsel),
2634                                             hists_evsel__init,
2635                                             hists_evsel__exit);
2636         if (err)
2637                 fputs("FATAL ERROR: Couldn't setup hists class\n", stderr);
2638
2639         return err;
2640 }
2641
2642 void perf_hpp_list__init(struct perf_hpp_list *list)
2643 {
2644         INIT_LIST_HEAD(&list->fields);
2645         INIT_LIST_HEAD(&list->sorts);
2646 }