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