xref: /linux/tools/perf/ui/browsers/hists.c (revision 59eca524949b5e4b9f3e0691e041996508d37589)
1 // SPDX-License-Identifier: GPL-2.0
2 #include <dirent.h>
3 #include <errno.h>
4 #include <inttypes.h>
5 #include <limits.h>
6 #include <stdio.h>
7 #include <stdlib.h>
8 #include <string.h>
9 #include <linux/rbtree.h>
10 #include <linux/string.h>
11 #include <sys/ttydefaults.h>
12 #include <linux/time64.h>
13 #include <linux/zalloc.h>
14 
15 #include "../../util/debug.h"
16 #include "../../util/dso.h"
17 #include "../../util/callchain.h"
18 #include "../../util/evsel.h"
19 #include "../../util/evlist.h"
20 #include "../../util/header.h"
21 #include "../../util/hist.h"
22 #include "../../util/machine.h"
23 #include "../../util/map.h"
24 #include "../../util/maps.h"
25 #include "../../util/symbol.h"
26 #include "../../util/map_symbol.h"
27 #include "../../util/branch.h"
28 #include "../../util/pstack.h"
29 #include "../../util/sort.h"
30 #include "../../util/top.h"
31 #include "../../util/thread.h"
32 #include "../../util/block-info.h"
33 #include "../../util/util.h"
34 #include "../../arch/common.h"
35 
36 #include "../browsers/hists.h"
37 #include "../helpline.h"
38 #include "../keysyms.h"
39 #include "../util.h"
40 #include "../ui.h"
41 #include "map.h"
42 #include "annotate.h"
43 #include "annotate-data.h"
44 #include "srcline.h"
45 #include "string2.h"
46 #include "units.h"
47 #include "time-utils.h"
48 
49 #include <linux/ctype.h>
50 
51 extern void hist_browser__init_hpp(void);
52 
53 static int hists_browser__scnprintf_title(struct hist_browser *browser, char *bf, size_t size);
54 static void hist_browser__update_nr_entries(struct hist_browser *hb);
55 
56 static struct rb_node *hists__filter_entries(struct rb_node *nd,
57 					     float min_pcnt);
58 
59 static bool hist_browser__has_filter(struct hist_browser *hb)
60 {
61 	return hists__has_filter(hb->hists) || hb->min_pcnt || symbol_conf.has_filter || hb->c2c_filter;
62 }
63 
64 static int hist_browser__get_folding(struct hist_browser *browser)
65 {
66 	struct rb_node *nd;
67 	struct hists *hists = browser->hists;
68 	int unfolded_rows = 0;
69 
70 	for (nd = rb_first_cached(&hists->entries);
71 	     (nd = hists__filter_entries(nd, browser->min_pcnt)) != NULL;
72 	     nd = rb_hierarchy_next(nd)) {
73 		struct hist_entry *he =
74 			rb_entry(nd, struct hist_entry, rb_node);
75 
76 		if (he->leaf && he->unfolded)
77 			unfolded_rows += he->nr_rows;
78 	}
79 	return unfolded_rows;
80 }
81 
82 static void hist_browser__set_title_space(struct hist_browser *hb)
83 {
84 	struct ui_browser *browser = &hb->b;
85 	struct hists *hists = hb->hists;
86 	struct perf_hpp_list *hpp_list = hists->hpp_list;
87 
88 	browser->extra_title_lines = hb->show_headers ? hpp_list->nr_header_lines : 0;
89 }
90 
91 static u32 hist_browser__nr_entries(struct hist_browser *hb)
92 {
93 	u32 nr_entries;
94 
95 	if (symbol_conf.report_hierarchy)
96 		nr_entries = hb->nr_hierarchy_entries;
97 	else if (hist_browser__has_filter(hb))
98 		nr_entries = hb->nr_non_filtered_entries;
99 	else
100 		nr_entries = hb->hists->nr_entries;
101 
102 	hb->nr_callchain_rows = hist_browser__get_folding(hb);
103 	return nr_entries + hb->nr_callchain_rows;
104 }
105 
106 static void hist_browser__update_rows(struct hist_browser *hb)
107 {
108 	struct ui_browser *browser = &hb->b;
109 	struct hists *hists = hb->hists;
110 	struct perf_hpp_list *hpp_list = hists->hpp_list;
111 	u16 index_row;
112 
113 	if (!hb->show_headers) {
114 		browser->rows += browser->extra_title_lines;
115 		browser->extra_title_lines = 0;
116 		return;
117 	}
118 
119 	browser->extra_title_lines = hpp_list->nr_header_lines;
120 	browser->rows -= browser->extra_title_lines;
121 	/*
122 	 * Verify if we were at the last line and that line isn't
123 	 * visible because we now show the header line(s).
124 	 */
125 	index_row = browser->index - browser->top_idx;
126 	if (index_row >= browser->rows)
127 		browser->index -= index_row - browser->rows + 1;
128 }
129 
130 static void hist_browser__refresh_dimensions(struct ui_browser *browser)
131 {
132 	struct hist_browser *hb = container_of(browser, struct hist_browser, b);
133 
134 	/* 3 == +/- toggle symbol before actual hist_entry rendering */
135 	browser->width = 3 + (hists__sort_list_width(hb->hists) + sizeof("[k]"));
136 	/*
137  	 * FIXME: Just keeping existing behaviour, but this really should be
138  	 *	  before updating browser->width, as it will invalidate the
139  	 *	  calculation above. Fix this and the fallout in another
140  	 *	  changeset.
141  	 */
142 	ui_browser__refresh_dimensions(browser);
143 }
144 
145 static void hist_browser__reset(struct hist_browser *browser)
146 {
147 	/*
148 	 * The hists__remove_entry_filter() already folds non-filtered
149 	 * entries so we can assume it has 0 callchain rows.
150 	 */
151 	browser->nr_callchain_rows = 0;
152 
153 	hist_browser__update_nr_entries(browser);
154 	browser->b.nr_entries = hist_browser__nr_entries(browser);
155 	hist_browser__refresh_dimensions(&browser->b);
156 	ui_browser__reset_index(&browser->b);
157 }
158 
159 static char tree__folded_sign(bool unfolded)
160 {
161 	return unfolded ? '-' : '+';
162 }
163 
164 static char hist_entry__folded(const struct hist_entry *he)
165 {
166 	return he->has_children ? tree__folded_sign(he->unfolded) : ' ';
167 }
168 
169 static char callchain_list__folded(const struct callchain_list *cl)
170 {
171 	return cl->has_children ? tree__folded_sign(cl->unfolded) : ' ';
172 }
173 
174 static void callchain_list__set_folding(struct callchain_list *cl, bool unfold)
175 {
176 	cl->unfolded = unfold ? cl->has_children : false;
177 }
178 
179 static int callchain_node__count_rows_rb_tree(struct callchain_node *node)
180 {
181 	int n = 0;
182 	struct rb_node *nd;
183 
184 	for (nd = rb_first(&node->rb_root); nd; nd = rb_next(nd)) {
185 		struct callchain_node *child = rb_entry(nd, struct callchain_node, rb_node);
186 		struct callchain_list *chain;
187 		char folded_sign = ' '; /* No children */
188 
189 		list_for_each_entry(chain, &child->val, list) {
190 			++n;
191 
192 			/* We need this because we may not have children */
193 			folded_sign = callchain_list__folded(chain);
194 			if (folded_sign == '+')
195 				break;
196 		}
197 
198 		if (folded_sign == '-') /* Have children and they're unfolded */
199 			n += callchain_node__count_rows_rb_tree(child);
200 	}
201 
202 	return n;
203 }
204 
205 static int callchain_node__count_flat_rows(struct callchain_node *node)
206 {
207 	struct callchain_list *chain;
208 	char folded_sign = 0;
209 	int n = 0;
210 
211 	list_for_each_entry(chain, &node->parent_val, list) {
212 		if (!folded_sign) {
213 			/* only check first chain list entry */
214 			folded_sign = callchain_list__folded(chain);
215 			if (folded_sign == '+')
216 				return 1;
217 		}
218 		n++;
219 	}
220 
221 	list_for_each_entry(chain, &node->val, list) {
222 		if (!folded_sign) {
223 			/* node->parent_val list might be empty */
224 			folded_sign = callchain_list__folded(chain);
225 			if (folded_sign == '+')
226 				return 1;
227 		}
228 		n++;
229 	}
230 
231 	return n;
232 }
233 
234 static int callchain_node__count_folded_rows(struct callchain_node *node __maybe_unused)
235 {
236 	return 1;
237 }
238 
239 static int callchain_node__count_rows(struct callchain_node *node)
240 {
241 	struct callchain_list *chain;
242 	bool unfolded = false;
243 	int n = 0;
244 
245 	if (callchain_param.mode == CHAIN_FLAT)
246 		return callchain_node__count_flat_rows(node);
247 	else if (callchain_param.mode == CHAIN_FOLDED)
248 		return callchain_node__count_folded_rows(node);
249 
250 	list_for_each_entry(chain, &node->val, list) {
251 		++n;
252 
253 		unfolded = chain->unfolded;
254 	}
255 
256 	if (unfolded)
257 		n += callchain_node__count_rows_rb_tree(node);
258 
259 	return n;
260 }
261 
262 static int callchain__count_rows(struct rb_root *chain)
263 {
264 	struct rb_node *nd;
265 	int n = 0;
266 
267 	for (nd = rb_first(chain); nd; nd = rb_next(nd)) {
268 		struct callchain_node *node = rb_entry(nd, struct callchain_node, rb_node);
269 		n += callchain_node__count_rows(node);
270 	}
271 
272 	return n;
273 }
274 
275 static int hierarchy_count_rows(struct hist_browser *hb, struct hist_entry *he,
276 				bool include_children)
277 {
278 	int count = 0;
279 	struct rb_node *node;
280 	struct hist_entry *child;
281 
282 	if (he->leaf)
283 		return callchain__count_rows(&he->sorted_chain);
284 
285 	if (he->has_no_entry)
286 		return 1;
287 
288 	node = rb_first_cached(&he->hroot_out);
289 	while (node) {
290 		float percent;
291 
292 		child = rb_entry(node, struct hist_entry, rb_node);
293 		percent = hist_entry__get_percent_limit(child);
294 
295 		if (!child->filtered && percent >= hb->min_pcnt) {
296 			count++;
297 
298 			if (include_children && child->unfolded)
299 				count += hierarchy_count_rows(hb, child, true);
300 		}
301 
302 		node = rb_next(node);
303 	}
304 	return count;
305 }
306 
307 static bool hist_entry__toggle_fold(struct hist_entry *he)
308 {
309 	if (!he)
310 		return false;
311 
312 	if (!he->has_children)
313 		return false;
314 
315 	he->unfolded = !he->unfolded;
316 	return true;
317 }
318 
319 static bool callchain_list__toggle_fold(struct callchain_list *cl)
320 {
321 	if (!cl)
322 		return false;
323 
324 	if (!cl->has_children)
325 		return false;
326 
327 	cl->unfolded = !cl->unfolded;
328 	return true;
329 }
330 
331 static void callchain_node__init_have_children_rb_tree(struct callchain_node *node)
332 {
333 	struct rb_node *nd = rb_first(&node->rb_root);
334 
335 	for (nd = rb_first(&node->rb_root); nd; nd = rb_next(nd)) {
336 		struct callchain_node *child = rb_entry(nd, struct callchain_node, rb_node);
337 		struct callchain_list *chain;
338 		bool first = true;
339 
340 		list_for_each_entry(chain, &child->val, list) {
341 			if (first) {
342 				first = false;
343 				chain->has_children = chain->list.next != &child->val ||
344 							 !RB_EMPTY_ROOT(&child->rb_root);
345 			} else
346 				chain->has_children = chain->list.next == &child->val &&
347 							 !RB_EMPTY_ROOT(&child->rb_root);
348 		}
349 
350 		callchain_node__init_have_children_rb_tree(child);
351 	}
352 }
353 
354 static void callchain_node__init_have_children(struct callchain_node *node,
355 					       bool has_sibling)
356 {
357 	struct callchain_list *chain;
358 
359 	chain = list_entry(node->val.next, struct callchain_list, list);
360 	chain->has_children = has_sibling;
361 
362 	if (!list_empty(&node->val)) {
363 		chain = list_entry(node->val.prev, struct callchain_list, list);
364 		chain->has_children = !RB_EMPTY_ROOT(&node->rb_root);
365 	}
366 
367 	callchain_node__init_have_children_rb_tree(node);
368 }
369 
370 static void callchain__init_have_children(struct rb_root *root)
371 {
372 	struct rb_node *nd = rb_first(root);
373 	bool has_sibling = nd && rb_next(nd);
374 
375 	for (nd = rb_first(root); nd; nd = rb_next(nd)) {
376 		struct callchain_node *node = rb_entry(nd, struct callchain_node, rb_node);
377 		callchain_node__init_have_children(node, has_sibling);
378 		if (callchain_param.mode == CHAIN_FLAT ||
379 		    callchain_param.mode == CHAIN_FOLDED)
380 			callchain_node__make_parent_list(node);
381 	}
382 }
383 
384 static void hist_entry__init_have_children(struct hist_entry *he)
385 {
386 	if (he->init_have_children)
387 		return;
388 
389 	if (he->leaf) {
390 		he->has_children = !RB_EMPTY_ROOT(&he->sorted_chain);
391 		callchain__init_have_children(&he->sorted_chain);
392 	} else {
393 		he->has_children = !RB_EMPTY_ROOT(&he->hroot_out.rb_root);
394 	}
395 
396 	he->init_have_children = true;
397 }
398 
399 static bool hist_browser__selection_has_children(struct hist_browser *browser)
400 {
401 	struct hist_entry *he = browser->he_selection;
402 	struct map_symbol *ms = browser->selection;
403 
404 	if (!he || !ms)
405 		return false;
406 
407 	if (ms == &he->ms)
408 	       return he->has_children;
409 
410 	return container_of(ms, struct callchain_list, ms)->has_children;
411 }
412 
413 static bool hist_browser__selection_unfolded(struct hist_browser *browser)
414 {
415 	struct hist_entry *he = browser->he_selection;
416 	struct map_symbol *ms = browser->selection;
417 
418 	if (!he || !ms)
419 		return false;
420 
421 	if (ms == &he->ms)
422 	       return he->unfolded;
423 
424 	return container_of(ms, struct callchain_list, ms)->unfolded;
425 }
426 
427 static char *hist_browser__selection_sym_name(struct hist_browser *browser, char *bf, size_t size)
428 {
429 	struct hist_entry *he = browser->he_selection;
430 	struct map_symbol *ms = browser->selection;
431 	struct callchain_list *callchain_entry;
432 
433 	if (!he || !ms)
434 		return NULL;
435 
436 	if (ms == &he->ms) {
437 	       hist_entry__sym_snprintf(he, bf, size, 0);
438 	       return bf + 4; // skip the level, e.g. '[k] '
439 	}
440 
441 	callchain_entry = container_of(ms, struct callchain_list, ms);
442 	return callchain_list__sym_name(callchain_entry, bf, size, browser->show_dso);
443 }
444 
445 static bool hist_browser__toggle_fold(struct hist_browser *browser)
446 {
447 	struct hist_entry *he = browser->he_selection;
448 	struct map_symbol *ms = browser->selection;
449 	struct callchain_list *cl = container_of(ms, struct callchain_list, ms);
450 	bool has_children;
451 
452 	if (!he || !ms)
453 		return false;
454 
455 	if (ms == &he->ms)
456 		has_children = hist_entry__toggle_fold(he);
457 	else
458 		has_children = callchain_list__toggle_fold(cl);
459 
460 	if (has_children) {
461 		int child_rows = 0;
462 
463 		hist_entry__init_have_children(he);
464 		browser->b.nr_entries -= he->nr_rows;
465 
466 		if (he->leaf)
467 			browser->nr_callchain_rows -= he->nr_rows;
468 		else
469 			browser->nr_hierarchy_entries -= he->nr_rows;
470 
471 		if (symbol_conf.report_hierarchy)
472 			child_rows = hierarchy_count_rows(browser, he, true);
473 
474 		if (he->unfolded) {
475 			if (he->leaf)
476 				he->nr_rows = callchain__count_rows(
477 						&he->sorted_chain);
478 			else
479 				he->nr_rows = hierarchy_count_rows(browser, he, false);
480 
481 			/* account grand children */
482 			if (symbol_conf.report_hierarchy)
483 				browser->b.nr_entries += child_rows - he->nr_rows;
484 
485 			if (!he->leaf && he->nr_rows == 0) {
486 				he->has_no_entry = true;
487 				he->nr_rows = 1;
488 			}
489 		} else {
490 			if (symbol_conf.report_hierarchy)
491 				browser->b.nr_entries -= child_rows - he->nr_rows;
492 
493 			if (he->has_no_entry)
494 				he->has_no_entry = false;
495 
496 			he->nr_rows = 0;
497 		}
498 
499 		browser->b.nr_entries += he->nr_rows;
500 
501 		if (he->leaf)
502 			browser->nr_callchain_rows += he->nr_rows;
503 		else
504 			browser->nr_hierarchy_entries += he->nr_rows;
505 
506 		return true;
507 	}
508 
509 	/* If it doesn't have children, no toggling performed */
510 	return false;
511 }
512 
513 static int callchain_node__set_folding_rb_tree(struct callchain_node *node, bool unfold)
514 {
515 	int n = 0;
516 	struct rb_node *nd;
517 
518 	for (nd = rb_first(&node->rb_root); nd; nd = rb_next(nd)) {
519 		struct callchain_node *child = rb_entry(nd, struct callchain_node, rb_node);
520 		struct callchain_list *chain;
521 		bool has_children = false;
522 
523 		list_for_each_entry(chain, &child->val, list) {
524 			++n;
525 			callchain_list__set_folding(chain, unfold);
526 			has_children = chain->has_children;
527 		}
528 
529 		if (has_children)
530 			n += callchain_node__set_folding_rb_tree(child, unfold);
531 	}
532 
533 	return n;
534 }
535 
536 static int callchain_node__set_folding(struct callchain_node *node, bool unfold)
537 {
538 	struct callchain_list *chain;
539 	bool has_children = false;
540 	int n = 0;
541 
542 	list_for_each_entry(chain, &node->val, list) {
543 		++n;
544 		callchain_list__set_folding(chain, unfold);
545 		has_children = chain->has_children;
546 	}
547 
548 	if (has_children)
549 		n += callchain_node__set_folding_rb_tree(node, unfold);
550 
551 	return n;
552 }
553 
554 static int callchain__set_folding(struct rb_root *chain, bool unfold)
555 {
556 	struct rb_node *nd;
557 	int n = 0;
558 
559 	for (nd = rb_first(chain); nd; nd = rb_next(nd)) {
560 		struct callchain_node *node = rb_entry(nd, struct callchain_node, rb_node);
561 		n += callchain_node__set_folding(node, unfold);
562 	}
563 
564 	return n;
565 }
566 
567 static int hierarchy_set_folding(struct hist_browser *hb, struct hist_entry *he,
568 				 bool unfold __maybe_unused)
569 {
570 	float percent;
571 	struct rb_node *nd;
572 	struct hist_entry *child;
573 	int n = 0;
574 
575 	for (nd = rb_first_cached(&he->hroot_out); nd; nd = rb_next(nd)) {
576 		child = rb_entry(nd, struct hist_entry, rb_node);
577 		percent = hist_entry__get_percent_limit(child);
578 		if (!child->filtered && percent >= hb->min_pcnt)
579 			n++;
580 	}
581 
582 	return n;
583 }
584 
585 static void hist_entry__set_folding(struct hist_entry *he,
586 				    struct hist_browser *hb, bool unfold)
587 {
588 	hist_entry__init_have_children(he);
589 	he->unfolded = unfold ? he->has_children : false;
590 
591 	if (he->has_children) {
592 		int n;
593 
594 		if (he->leaf)
595 			n = callchain__set_folding(&he->sorted_chain, unfold);
596 		else
597 			n = hierarchy_set_folding(hb, he, unfold);
598 
599 		he->nr_rows = unfold ? n : 0;
600 	} else
601 		he->nr_rows = 0;
602 }
603 
604 static void
605 __hist_browser__set_folding(struct hist_browser *browser, bool unfold)
606 {
607 	struct rb_node *nd;
608 	struct hist_entry *he;
609 	double percent;
610 
611 	nd = rb_first_cached(&browser->hists->entries);
612 	while (nd) {
613 		he = rb_entry(nd, struct hist_entry, rb_node);
614 
615 		/* set folding state even if it's currently folded */
616 		nd = __rb_hierarchy_next(nd, HMD_FORCE_CHILD);
617 
618 		hist_entry__set_folding(he, browser, unfold);
619 
620 		percent = hist_entry__get_percent_limit(he);
621 		if (he->filtered || percent < browser->min_pcnt)
622 			continue;
623 
624 		if (!he->depth || unfold)
625 			browser->nr_hierarchy_entries++;
626 		if (he->leaf)
627 			browser->nr_callchain_rows += he->nr_rows;
628 		else if (unfold && !hist_entry__has_hierarchy_children(he, browser->min_pcnt)) {
629 			browser->nr_hierarchy_entries++;
630 			he->has_no_entry = true;
631 			he->nr_rows = 1;
632 		} else
633 			he->has_no_entry = false;
634 	}
635 }
636 
637 static void hist_browser__set_folding(struct hist_browser *browser, bool unfold)
638 {
639 	browser->nr_hierarchy_entries = 0;
640 	browser->nr_callchain_rows = 0;
641 	__hist_browser__set_folding(browser, unfold);
642 
643 	browser->b.nr_entries = hist_browser__nr_entries(browser);
644 	/* Go to the start, we may be way after valid entries after a collapse */
645 	ui_browser__reset_index(&browser->b);
646 }
647 
648 static void hist_browser__set_folding_selected(struct hist_browser *browser, bool unfold)
649 {
650 	if (!browser->he_selection)
651 		return;
652 
653 	if (unfold == browser->he_selection->unfolded)
654 		return;
655 
656 	hist_browser__toggle_fold(browser);
657 }
658 
659 static void ui_browser__warn_lost_events(struct ui_browser *browser)
660 {
661 	ui_browser__warning(browser, 4,
662 		"Events are being lost, check IO/CPU overload!\n\n"
663 		"You may want to run 'perf' using a RT scheduler policy:\n\n"
664 		" perf top -r 80\n\n"
665 		"Or reduce the sampling frequency.");
666 }
667 
668 static int hist_browser__title(struct hist_browser *browser, char *bf, size_t size)
669 {
670 	return browser->title ? browser->title(browser, bf, size) : 0;
671 }
672 
673 static int hist_browser__handle_hotkey(struct hist_browser *browser, bool warn_lost_event, char *title, size_t size, int key)
674 {
675 	switch (key) {
676 	case K_TIMER: {
677 		struct hist_browser_timer *hbt = browser->hbt;
678 		struct evsel *evsel = hists_to_evsel(browser->hists);
679 		u64 nr_entries;
680 
681 		WARN_ON_ONCE(!hbt);
682 
683 		if (hbt)
684 			hbt->timer(hbt->arg);
685 
686 		if (hist_browser__has_filter(browser) || symbol_conf.report_hierarchy)
687 			hist_browser__update_nr_entries(browser);
688 
689 		nr_entries = hist_browser__nr_entries(browser);
690 		ui_browser__update_nr_entries(&browser->b, nr_entries);
691 
692 		if (warn_lost_event &&
693 		    (evlist__stats(evsel->evlist)->nr_lost_warned !=
694 		     evlist__stats(evsel->evlist)->nr_events[PERF_RECORD_LOST])) {
695 			evlist__stats(evsel->evlist)->nr_lost_warned =
696 				evlist__stats(evsel->evlist)->nr_events[PERF_RECORD_LOST];
697 			ui_browser__warn_lost_events(&browser->b);
698 		}
699 
700 		hist_browser__title(browser, title, size);
701 		ui_browser__show_title(&browser->b, title);
702 		break;
703 	}
704 	case 'D': { /* Debug */
705 		struct hist_entry *h = rb_entry(browser->b.top, struct hist_entry, rb_node);
706 		static int seq;
707 
708 		ui_helpline__pop();
709 		ui_helpline__fpush("%d: nr_ent=(%d,%d), etl: %d, rows=%d, idx=%d, fve: idx=%d, row_off=%d, nrows=%d",
710 				   seq++, browser->b.nr_entries, browser->hists->nr_entries,
711 				   browser->b.extra_title_lines, browser->b.rows,
712 				   browser->b.index, browser->b.top_idx, h->row_offset, h->nr_rows);
713 	}
714 		break;
715 	case 'C':
716 		/* Collapse the whole world. */
717 		hist_browser__set_folding(browser, false);
718 		break;
719 	case 'c':
720 		/* Collapse the selected entry. */
721 		hist_browser__set_folding_selected(browser, false);
722 		break;
723 	case 'E':
724 		/* Expand the whole world. */
725 		hist_browser__set_folding(browser, true);
726 		break;
727 	case 'e':
728 		/* Toggle expand/collapse the selected entry. */
729 		hist_browser__toggle_fold(browser);
730 		break;
731 	case 'H':
732 		browser->show_headers = !browser->show_headers;
733 		hist_browser__update_rows(browser);
734 		break;
735 	case '+':
736 		if (hist_browser__toggle_fold(browser))
737 			break;
738 		/* fall thru */
739 	default:
740 		return -1;
741 	}
742 
743 	return 0;
744 }
745 
746 int hist_browser__run(struct hist_browser *browser, const char *help,
747 		      bool warn_lost_event, int key)
748 {
749 	char title[160];
750 	struct hist_browser_timer *hbt = browser->hbt;
751 	int delay_secs = hbt ? hbt->refresh : 0;
752 
753 	browser->b.entries = &browser->hists->entries;
754 	browser->b.nr_entries = hist_browser__nr_entries(browser);
755 
756 	hist_browser__title(browser, title, sizeof(title));
757 
758 	if (ui_browser__show(&browser->b, title, "%s", help) < 0)
759 		return -1;
760 
761 	if (key && hist_browser__handle_hotkey(browser, warn_lost_event, title, sizeof(title), key))
762 		goto out;
763 
764 	while (1) {
765 		key = ui_browser__run(&browser->b, delay_secs);
766 
767 		if (hist_browser__handle_hotkey(browser, warn_lost_event, title, sizeof(title), key))
768 			break;
769 	}
770 out:
771 	ui_browser__hide(&browser->b);
772 	return key;
773 }
774 
775 struct callchain_print_arg {
776 	/* for hists browser */
777 	off_t	row_offset;
778 	bool	is_current_entry;
779 
780 	/* for file dump */
781 	FILE	*fp;
782 	int	printed;
783 };
784 
785 typedef void (*print_callchain_entry_fn)(struct hist_browser *browser,
786 					 struct callchain_list *chain,
787 					 const char *str, int offset,
788 					 unsigned short row,
789 					 struct callchain_print_arg *arg);
790 
791 static void hist_browser__show_callchain_entry(struct hist_browser *browser,
792 					       struct callchain_list *chain,
793 					       const char *str, int offset,
794 					       unsigned short row,
795 					       struct callchain_print_arg *arg)
796 {
797 	int color, width;
798 	char folded_sign = callchain_list__folded(chain);
799 	bool show_annotated = browser->show_dso && chain->ms.sym && symbol__annotation(chain->ms.sym)->src;
800 
801 	color = HE_COLORSET_NORMAL;
802 	width = browser->b.width - (offset + 2);
803 	if (ui_browser__is_current_entry(&browser->b, row)) {
804 		browser->selection = &chain->ms;
805 		color = HE_COLORSET_SELECTED;
806 		arg->is_current_entry = true;
807 	}
808 
809 	ui_browser__set_color(&browser->b, color);
810 	ui_browser__gotorc(&browser->b, row, 0);
811 	ui_browser__write_nstring(&browser->b, " ", offset);
812 	ui_browser__printf(&browser->b, "%c", folded_sign);
813 	ui_browser__write_graph(&browser->b, show_annotated ? SLSMG_RARROW_CHAR : ' ');
814 	ui_browser__write_nstring(&browser->b, str, width);
815 }
816 
817 static void hist_browser__fprintf_callchain_entry(struct hist_browser *b __maybe_unused,
818 						  struct callchain_list *chain,
819 						  const char *str, int offset,
820 						  unsigned short row __maybe_unused,
821 						  struct callchain_print_arg *arg)
822 {
823 	char folded_sign = callchain_list__folded(chain);
824 
825 	arg->printed += fprintf(arg->fp, "%*s%c %s\n", offset, " ",
826 				folded_sign, str);
827 }
828 
829 typedef bool (*check_output_full_fn)(struct hist_browser *browser,
830 				     unsigned short row);
831 
832 static bool hist_browser__check_output_full(struct hist_browser *browser,
833 					    unsigned short row)
834 {
835 	return browser->b.rows == row;
836 }
837 
838 static bool hist_browser__check_dump_full(struct hist_browser *browser __maybe_unused,
839 					  unsigned short row __maybe_unused)
840 {
841 	return false;
842 }
843 
844 #define LEVEL_OFFSET_STEP 3
845 
846 static int hist_browser__show_callchain_list(struct hist_browser *browser,
847 					     struct callchain_node *node,
848 					     struct callchain_list *chain,
849 					     unsigned short row, u64 total,
850 					     bool need_percent, int offset,
851 					     print_callchain_entry_fn print,
852 					     struct callchain_print_arg *arg)
853 {
854 	char bf[1024], *alloc_str;
855 	char buf[64], *alloc_str2;
856 	const char *str;
857 	int ret = 1;
858 
859 	if (arg->row_offset != 0) {
860 		arg->row_offset--;
861 		return 0;
862 	}
863 
864 	alloc_str = NULL;
865 	alloc_str2 = NULL;
866 
867 	str = callchain_list__sym_name(chain, bf, sizeof(bf),
868 				       browser->show_dso);
869 
870 	if (symbol_conf.show_branchflag_count) {
871 		callchain_list_counts__printf_value(chain, NULL,
872 						    buf, sizeof(buf));
873 
874 		if (asprintf(&alloc_str2, "%s%s", str, buf) < 0)
875 			str = "Not enough memory!";
876 		else
877 			str = alloc_str2;
878 	}
879 
880 	if (need_percent) {
881 		callchain_node__scnprintf_value(node, buf, sizeof(buf),
882 						total);
883 
884 		if (asprintf(&alloc_str, "%s %s", buf, str) < 0)
885 			str = "Not enough memory!";
886 		else
887 			str = alloc_str;
888 	}
889 
890 	print(browser, chain, str, offset, row, arg);
891 	free(alloc_str);
892 	free(alloc_str2);
893 
894 	return ret;
895 }
896 
897 static bool check_percent_display(struct rb_node *node, u64 parent_total)
898 {
899 	struct callchain_node *child;
900 
901 	if (node == NULL)
902 		return false;
903 
904 	if (rb_next(node))
905 		return true;
906 
907 	child = rb_entry(node, struct callchain_node, rb_node);
908 	return callchain_cumul_hits(child) != parent_total;
909 }
910 
911 static int hist_browser__show_callchain_flat(struct hist_browser *browser,
912 					     struct rb_root *root,
913 					     unsigned short row, u64 total,
914 					     u64 parent_total,
915 					     print_callchain_entry_fn print,
916 					     struct callchain_print_arg *arg,
917 					     check_output_full_fn is_output_full)
918 {
919 	struct rb_node *node;
920 	int first_row = row, offset = LEVEL_OFFSET_STEP;
921 	bool need_percent;
922 
923 	node = rb_first(root);
924 	need_percent = check_percent_display(node, parent_total);
925 
926 	while (node) {
927 		struct callchain_node *child = rb_entry(node, struct callchain_node, rb_node);
928 		struct rb_node *next = rb_next(node);
929 		struct callchain_list *chain;
930 		char folded_sign = ' ';
931 		int first = true;
932 		int extra_offset = 0;
933 
934 		list_for_each_entry(chain, &child->parent_val, list) {
935 			bool was_first = first;
936 
937 			if (first)
938 				first = false;
939 			else if (need_percent)
940 				extra_offset = LEVEL_OFFSET_STEP;
941 
942 			folded_sign = callchain_list__folded(chain);
943 
944 			row += hist_browser__show_callchain_list(browser, child,
945 							chain, row, total,
946 							was_first && need_percent,
947 							offset + extra_offset,
948 							print, arg);
949 
950 			if (is_output_full(browser, row))
951 				goto out;
952 
953 			if (folded_sign == '+')
954 				goto next;
955 		}
956 
957 		list_for_each_entry(chain, &child->val, list) {
958 			bool was_first = first;
959 
960 			if (first)
961 				first = false;
962 			else if (need_percent)
963 				extra_offset = LEVEL_OFFSET_STEP;
964 
965 			folded_sign = callchain_list__folded(chain);
966 
967 			row += hist_browser__show_callchain_list(browser, child,
968 							chain, row, total,
969 							was_first && need_percent,
970 							offset + extra_offset,
971 							print, arg);
972 
973 			if (is_output_full(browser, row))
974 				goto out;
975 
976 			if (folded_sign == '+')
977 				break;
978 		}
979 
980 next:
981 		if (is_output_full(browser, row))
982 			break;
983 		node = next;
984 	}
985 out:
986 	return row - first_row;
987 }
988 
989 static char *hist_browser__folded_callchain_str(struct hist_browser *browser,
990 						struct callchain_list *chain,
991 						char *value_str, char *old_str)
992 {
993 	char bf[1024];
994 	const char *str;
995 	char *new;
996 
997 	str = callchain_list__sym_name(chain, bf, sizeof(bf),
998 				       browser->show_dso);
999 	if (old_str) {
1000 		if (asprintf(&new, "%s%s%s", old_str,
1001 			     symbol_conf.field_sep ?: ";", str) < 0)
1002 			new = NULL;
1003 	} else {
1004 		if (value_str) {
1005 			if (asprintf(&new, "%s %s", value_str, str) < 0)
1006 				new = NULL;
1007 		} else {
1008 			if (asprintf(&new, "%s", str) < 0)
1009 				new = NULL;
1010 		}
1011 	}
1012 	return new;
1013 }
1014 
1015 static int hist_browser__show_callchain_folded(struct hist_browser *browser,
1016 					       struct rb_root *root,
1017 					       unsigned short row, u64 total,
1018 					       u64 parent_total,
1019 					       print_callchain_entry_fn print,
1020 					       struct callchain_print_arg *arg,
1021 					       check_output_full_fn is_output_full)
1022 {
1023 	struct rb_node *node;
1024 	int first_row = row, offset = LEVEL_OFFSET_STEP;
1025 	bool need_percent;
1026 
1027 	node = rb_first(root);
1028 	need_percent = check_percent_display(node, parent_total);
1029 
1030 	while (node) {
1031 		struct callchain_node *child = rb_entry(node, struct callchain_node, rb_node);
1032 		struct rb_node *next = rb_next(node);
1033 		struct callchain_list *chain, *first_chain = NULL;
1034 		int first = true;
1035 		char *value_str = NULL, *value_str_alloc = NULL;
1036 		char *chain_str = NULL, *chain_str_alloc = NULL;
1037 
1038 		if (arg->row_offset != 0) {
1039 			arg->row_offset--;
1040 			goto next;
1041 		}
1042 
1043 		if (need_percent) {
1044 			char buf[64];
1045 
1046 			callchain_node__scnprintf_value(child, buf, sizeof(buf), total);
1047 			if (asprintf(&value_str, "%s", buf) < 0) {
1048 				value_str = (char *)"<...>";
1049 				goto do_print;
1050 			}
1051 			value_str_alloc = value_str;
1052 		}
1053 
1054 		list_for_each_entry(chain, &child->parent_val, list) {
1055 			chain_str = hist_browser__folded_callchain_str(browser,
1056 						chain, value_str, chain_str);
1057 			if (first) {
1058 				first = false;
1059 				first_chain = chain;
1060 			}
1061 
1062 			if (chain_str == NULL) {
1063 				chain_str = (char *)"Not enough memory!";
1064 				goto do_print;
1065 			}
1066 
1067 			chain_str_alloc = chain_str;
1068 		}
1069 
1070 		list_for_each_entry(chain, &child->val, list) {
1071 			chain_str = hist_browser__folded_callchain_str(browser,
1072 						chain, value_str, chain_str);
1073 			if (first) {
1074 				first = false;
1075 				first_chain = chain;
1076 			}
1077 
1078 			if (chain_str == NULL) {
1079 				chain_str = (char *)"Not enough memory!";
1080 				goto do_print;
1081 			}
1082 
1083 			chain_str_alloc = chain_str;
1084 		}
1085 
1086 do_print:
1087 		print(browser, first_chain, chain_str, offset, row++, arg);
1088 		free(value_str_alloc);
1089 		free(chain_str_alloc);
1090 
1091 next:
1092 		if (is_output_full(browser, row))
1093 			break;
1094 		node = next;
1095 	}
1096 
1097 	return row - first_row;
1098 }
1099 
1100 static int hist_browser__show_callchain_graph(struct hist_browser *browser,
1101 					struct rb_root *root, int level,
1102 					unsigned short row, u64 total,
1103 					u64 parent_total,
1104 					print_callchain_entry_fn print,
1105 					struct callchain_print_arg *arg,
1106 					check_output_full_fn is_output_full)
1107 {
1108 	struct rb_node *node;
1109 	int first_row = row, offset = level * LEVEL_OFFSET_STEP;
1110 	bool need_percent;
1111 	u64 percent_total = total;
1112 
1113 	if (callchain_param.mode == CHAIN_GRAPH_REL)
1114 		percent_total = parent_total;
1115 
1116 	node = rb_first(root);
1117 	need_percent = check_percent_display(node, parent_total);
1118 
1119 	while (node) {
1120 		struct callchain_node *child = rb_entry(node, struct callchain_node, rb_node);
1121 		struct rb_node *next = rb_next(node);
1122 		struct callchain_list *chain;
1123 		char folded_sign = ' ';
1124 		int first = true;
1125 		int extra_offset = 0;
1126 
1127 		list_for_each_entry(chain, &child->val, list) {
1128 			bool was_first = first;
1129 
1130 			if (first)
1131 				first = false;
1132 			else if (need_percent)
1133 				extra_offset = LEVEL_OFFSET_STEP;
1134 
1135 			folded_sign = callchain_list__folded(chain);
1136 
1137 			row += hist_browser__show_callchain_list(browser, child,
1138 							chain, row, percent_total,
1139 							was_first && need_percent,
1140 							offset + extra_offset,
1141 							print, arg);
1142 
1143 			if (is_output_full(browser, row))
1144 				goto out;
1145 
1146 			if (folded_sign == '+')
1147 				break;
1148 		}
1149 
1150 		if (folded_sign == '-') {
1151 			const int new_level = level + (extra_offset ? 2 : 1);
1152 
1153 			row += hist_browser__show_callchain_graph(browser, &child->rb_root,
1154 							    new_level, row, total,
1155 							    child->children_hit,
1156 							    print, arg, is_output_full);
1157 		}
1158 		if (is_output_full(browser, row))
1159 			break;
1160 		node = next;
1161 	}
1162 out:
1163 	return row - first_row;
1164 }
1165 
1166 static int hist_browser__show_callchain(struct hist_browser *browser,
1167 					struct hist_entry *entry, int level,
1168 					unsigned short row,
1169 					print_callchain_entry_fn print,
1170 					struct callchain_print_arg *arg,
1171 					check_output_full_fn is_output_full)
1172 {
1173 	u64 total = hists__total_period(entry->hists);
1174 	u64 parent_total;
1175 	int printed;
1176 
1177 	if (symbol_conf.cumulate_callchain)
1178 		parent_total = entry->stat_acc->period;
1179 	else
1180 		parent_total = entry->stat.period;
1181 
1182 	if (callchain_param.mode == CHAIN_FLAT) {
1183 		printed = hist_browser__show_callchain_flat(browser,
1184 						&entry->sorted_chain, row,
1185 						total, parent_total, print, arg,
1186 						is_output_full);
1187 	} else if (callchain_param.mode == CHAIN_FOLDED) {
1188 		printed = hist_browser__show_callchain_folded(browser,
1189 						&entry->sorted_chain, row,
1190 						total, parent_total, print, arg,
1191 						is_output_full);
1192 	} else {
1193 		printed = hist_browser__show_callchain_graph(browser,
1194 						&entry->sorted_chain, level, row,
1195 						total, parent_total, print, arg,
1196 						is_output_full);
1197 	}
1198 
1199 	if (arg->is_current_entry)
1200 		browser->he_selection = entry;
1201 
1202 	return printed;
1203 }
1204 
1205 struct hpp_arg {
1206 	struct ui_browser *b;
1207 	char folded_sign;
1208 	bool current_entry;
1209 };
1210 
1211 int __hpp__slsmg_color_printf(struct perf_hpp *hpp, const char *fmt, ...)
1212 {
1213 	struct hpp_arg *arg = hpp->ptr;
1214 	int ret, len;
1215 	va_list args;
1216 	double percent;
1217 
1218 	va_start(args, fmt);
1219 	len = va_arg(args, int);
1220 	percent = va_arg(args, double);
1221 	va_end(args);
1222 
1223 	ui_browser__set_percent_color(arg->b, percent, arg->current_entry);
1224 
1225 	ret = scnprintf(hpp->buf, hpp->size, fmt, len, percent);
1226 	ui_browser__printf(arg->b, "%s", hpp->buf);
1227 
1228 	return ret;
1229 }
1230 
1231 #define __HPP_COLOR_PERCENT_FN(_type, _field, _fmttype)			\
1232 static u64 __hpp_get_##_field(struct hist_entry *he)			\
1233 {									\
1234 	return he->stat._field;						\
1235 }									\
1236 									\
1237 static int								\
1238 hist_browser__hpp_color_##_type(struct perf_hpp_fmt *fmt,		\
1239 				struct perf_hpp *hpp,			\
1240 				struct hist_entry *he)			\
1241 {									\
1242 	return hpp__fmt(fmt, hpp, he, __hpp_get_##_field, " %*.2f%%",	\
1243 			__hpp__slsmg_color_printf, _fmttype);		\
1244 }
1245 
1246 #define __HPP_COLOR_ACC_PERCENT_FN(_type, _field, _fmttype)		\
1247 static u64 __hpp_get_acc_##_field(struct hist_entry *he)		\
1248 {									\
1249 	return he->stat_acc->_field;					\
1250 }									\
1251 									\
1252 static int								\
1253 hist_browser__hpp_color_##_type(struct perf_hpp_fmt *fmt,		\
1254 				struct perf_hpp *hpp,			\
1255 				struct hist_entry *he)			\
1256 {									\
1257 	if (!symbol_conf.cumulate_callchain) {				\
1258 		struct hpp_arg *arg = hpp->ptr;				\
1259 		int len = fmt->user_len ?: fmt->len;			\
1260 		int ret = scnprintf(hpp->buf, hpp->size,		\
1261 				    "%*s", len, "N/A");			\
1262 		ui_browser__printf(arg->b, "%s", hpp->buf);		\
1263 									\
1264 		return ret;						\
1265 	}								\
1266 	return hpp__fmt(fmt, hpp, he, __hpp_get_acc_##_field,		\
1267 			" %*.2f%%", __hpp__slsmg_color_printf,		\
1268 			_fmttype);					\
1269 }
1270 
1271 #define __HPP_COLOR_MEM_STAT_FN(_name, _type)				\
1272 static int								\
1273 hist_browser__hpp_color_mem_stat_##_name(struct perf_hpp_fmt *fmt,	\
1274 					 struct perf_hpp *hpp,		\
1275 					 struct hist_entry *he)		\
1276 {									\
1277 	return hpp__fmt_mem_stat(fmt, hpp, he, PERF_MEM_STAT_##_type,	\
1278 				 " %5.1f%%", __hpp__slsmg_color_printf);\
1279 }
1280 
1281 __HPP_COLOR_PERCENT_FN(overhead, period, PERF_HPP_FMT_TYPE__PERCENT)
1282 __HPP_COLOR_PERCENT_FN(latency, latency, PERF_HPP_FMT_TYPE__LATENCY)
1283 __HPP_COLOR_PERCENT_FN(overhead_sys, period_sys, PERF_HPP_FMT_TYPE__PERCENT)
1284 __HPP_COLOR_PERCENT_FN(overhead_us, period_us, PERF_HPP_FMT_TYPE__PERCENT)
1285 __HPP_COLOR_PERCENT_FN(overhead_guest_sys, period_guest_sys, PERF_HPP_FMT_TYPE__PERCENT)
1286 __HPP_COLOR_PERCENT_FN(overhead_guest_us, period_guest_us, PERF_HPP_FMT_TYPE__PERCENT)
1287 __HPP_COLOR_ACC_PERCENT_FN(overhead_acc, period, PERF_HPP_FMT_TYPE__PERCENT)
1288 __HPP_COLOR_ACC_PERCENT_FN(latency_acc, latency, PERF_HPP_FMT_TYPE__LATENCY)
1289 __HPP_COLOR_MEM_STAT_FN(op, OP)
1290 __HPP_COLOR_MEM_STAT_FN(cache, CACHE)
1291 __HPP_COLOR_MEM_STAT_FN(memory, MEMORY)
1292 __HPP_COLOR_MEM_STAT_FN(snoop, SNOOP)
1293 __HPP_COLOR_MEM_STAT_FN(dtlb, DTLB)
1294 
1295 #undef __HPP_COLOR_PERCENT_FN
1296 #undef __HPP_COLOR_ACC_PERCENT_FN
1297 #undef __HPP_COLOR_MEM_STAT_FN
1298 
1299 void hist_browser__init_hpp(void)
1300 {
1301 	perf_hpp__format[PERF_HPP__OVERHEAD].color =
1302 				hist_browser__hpp_color_overhead;
1303 	perf_hpp__format[PERF_HPP__LATENCY].color =
1304 				hist_browser__hpp_color_latency;
1305 	perf_hpp__format[PERF_HPP__OVERHEAD_SYS].color =
1306 				hist_browser__hpp_color_overhead_sys;
1307 	perf_hpp__format[PERF_HPP__OVERHEAD_US].color =
1308 				hist_browser__hpp_color_overhead_us;
1309 	perf_hpp__format[PERF_HPP__OVERHEAD_GUEST_SYS].color =
1310 				hist_browser__hpp_color_overhead_guest_sys;
1311 	perf_hpp__format[PERF_HPP__OVERHEAD_GUEST_US].color =
1312 				hist_browser__hpp_color_overhead_guest_us;
1313 	perf_hpp__format[PERF_HPP__OVERHEAD_ACC].color =
1314 				hist_browser__hpp_color_overhead_acc;
1315 	perf_hpp__format[PERF_HPP__LATENCY_ACC].color =
1316 				hist_browser__hpp_color_latency_acc;
1317 	perf_hpp__format[PERF_HPP__MEM_STAT_OP].color =
1318 				hist_browser__hpp_color_mem_stat_op;
1319 	perf_hpp__format[PERF_HPP__MEM_STAT_CACHE].color =
1320 				hist_browser__hpp_color_mem_stat_cache;
1321 	perf_hpp__format[PERF_HPP__MEM_STAT_MEMORY].color =
1322 				hist_browser__hpp_color_mem_stat_memory;
1323 	perf_hpp__format[PERF_HPP__MEM_STAT_SNOOP].color =
1324 				hist_browser__hpp_color_mem_stat_snoop;
1325 	perf_hpp__format[PERF_HPP__MEM_STAT_DTLB].color =
1326 				hist_browser__hpp_color_mem_stat_dtlb;
1327 
1328 	res_sample_init();
1329 }
1330 
1331 static int hist_browser__show_entry(struct hist_browser *browser,
1332 				    struct hist_entry *entry,
1333 				    unsigned short row)
1334 {
1335 	int printed = 0;
1336 	int width = browser->b.width;
1337 	char folded_sign = ' ';
1338 	bool current_entry = ui_browser__is_current_entry(&browser->b, row);
1339 	bool use_callchain = hist_entry__has_callchains(entry) && symbol_conf.use_callchain;
1340 	off_t row_offset = entry->row_offset;
1341 	bool first = true;
1342 	struct perf_hpp_fmt *fmt;
1343 
1344 	if (current_entry) {
1345 		browser->he_selection = entry;
1346 		browser->selection = &entry->ms;
1347 	}
1348 
1349 	if (use_callchain) {
1350 		hist_entry__init_have_children(entry);
1351 		folded_sign = hist_entry__folded(entry);
1352 	}
1353 
1354 	if (row_offset == 0) {
1355 		struct hpp_arg arg = {
1356 			.b		= &browser->b,
1357 			.folded_sign	= folded_sign,
1358 			.current_entry	= current_entry,
1359 		};
1360 		int column = 0;
1361 
1362 		ui_browser__gotorc(&browser->b, row, 0);
1363 
1364 		hists__for_each_format(browser->hists, fmt) {
1365 			char s[2048];
1366 			struct perf_hpp hpp = {
1367 				.buf	= s,
1368 				.size	= sizeof(s),
1369 				.ptr	= &arg,
1370 			};
1371 
1372 			if (perf_hpp__should_skip(fmt, entry->hists) ||
1373 			    column++ < browser->b.horiz_scroll)
1374 				continue;
1375 
1376 			if (current_entry && browser->b.navkeypressed) {
1377 				ui_browser__set_color(&browser->b,
1378 						      HE_COLORSET_SELECTED);
1379 			} else {
1380 				ui_browser__set_color(&browser->b,
1381 						      HE_COLORSET_NORMAL);
1382 			}
1383 
1384 			if (first) {
1385 				if (use_callchain) {
1386 					ui_browser__printf(&browser->b, "%c ", folded_sign);
1387 					width -= 2;
1388 				}
1389 				first = false;
1390 			} else {
1391 				ui_browser__printf(&browser->b, "  ");
1392 				width -= 2;
1393 			}
1394 
1395 			if (fmt->color) {
1396 				int ret = fmt->color(fmt, &hpp, entry);
1397 				hist_entry__snprintf_alignment(entry, &hpp, fmt, ret);
1398 				/*
1399 				 * fmt->color() already used ui_browser to
1400 				 * print the non alignment bits, skip it (+ret):
1401 				 */
1402 				ui_browser__printf(&browser->b, "%s", s + ret);
1403 			} else {
1404 				hist_entry__snprintf_alignment(entry, &hpp, fmt, fmt->entry(fmt, &hpp, entry));
1405 				ui_browser__printf(&browser->b, "%s", s);
1406 			}
1407 			width -= hpp.buf - s;
1408 		}
1409 
1410 		/* The scroll bar isn't being used */
1411 		if (!browser->b.navkeypressed)
1412 			width += 1;
1413 
1414 		ui_browser__write_nstring(&browser->b, "", width);
1415 
1416 		++row;
1417 		++printed;
1418 	} else
1419 		--row_offset;
1420 
1421 	if (folded_sign == '-' && row != browser->b.rows) {
1422 		struct callchain_print_arg arg = {
1423 			.row_offset = row_offset,
1424 			.is_current_entry = current_entry,
1425 		};
1426 
1427 		printed += hist_browser__show_callchain(browser,
1428 				entry, 1, row,
1429 				hist_browser__show_callchain_entry,
1430 				&arg,
1431 				hist_browser__check_output_full);
1432 	}
1433 
1434 	return printed;
1435 }
1436 
1437 static int hist_browser__show_hierarchy_entry(struct hist_browser *browser,
1438 					      struct hist_entry *entry,
1439 					      unsigned short row,
1440 					      int level)
1441 {
1442 	int printed = 0;
1443 	int width = browser->b.width;
1444 	char folded_sign = ' ';
1445 	bool current_entry = ui_browser__is_current_entry(&browser->b, row);
1446 	off_t row_offset = entry->row_offset;
1447 	bool first = true;
1448 	struct perf_hpp_fmt *fmt;
1449 	struct perf_hpp_list_node *fmt_node;
1450 	struct hpp_arg arg = {
1451 		.b		= &browser->b,
1452 		.current_entry	= current_entry,
1453 	};
1454 	int column = 0;
1455 	int hierarchy_indent = (entry->hists->nr_hpp_node - 2) * HIERARCHY_INDENT;
1456 
1457 	if (current_entry) {
1458 		browser->he_selection = entry;
1459 		browser->selection = &entry->ms;
1460 	}
1461 
1462 	hist_entry__init_have_children(entry);
1463 	folded_sign = hist_entry__folded(entry);
1464 	arg.folded_sign = folded_sign;
1465 
1466 	if (entry->leaf && row_offset) {
1467 		row_offset--;
1468 		goto show_callchain;
1469 	}
1470 
1471 	ui_browser__gotorc(&browser->b, row, 0);
1472 
1473 	if (current_entry && browser->b.navkeypressed)
1474 		ui_browser__set_color(&browser->b, HE_COLORSET_SELECTED);
1475 	else
1476 		ui_browser__set_color(&browser->b, HE_COLORSET_NORMAL);
1477 
1478 	ui_browser__write_nstring(&browser->b, "", level * HIERARCHY_INDENT);
1479 	width -= level * HIERARCHY_INDENT;
1480 
1481 	/* the first hpp_list_node is for overhead columns */
1482 	fmt_node = list_first_entry(&entry->hists->hpp_formats,
1483 				    struct perf_hpp_list_node, list);
1484 	perf_hpp_list__for_each_format(&fmt_node->hpp, fmt) {
1485 		char s[2048];
1486 		struct perf_hpp hpp = {
1487 			.buf		= s,
1488 			.size		= sizeof(s),
1489 			.ptr		= &arg,
1490 		};
1491 
1492 		if (perf_hpp__should_skip(fmt, entry->hists) ||
1493 		    column++ < browser->b.horiz_scroll)
1494 			continue;
1495 
1496 		if (current_entry && browser->b.navkeypressed) {
1497 			ui_browser__set_color(&browser->b,
1498 					      HE_COLORSET_SELECTED);
1499 		} else {
1500 			ui_browser__set_color(&browser->b,
1501 					      HE_COLORSET_NORMAL);
1502 		}
1503 
1504 		if (first) {
1505 			ui_browser__printf(&browser->b, "%c ", folded_sign);
1506 			width -= 2;
1507 			first = false;
1508 		} else {
1509 			ui_browser__printf(&browser->b, "  ");
1510 			width -= 2;
1511 		}
1512 
1513 		if (fmt->color) {
1514 			int ret = fmt->color(fmt, &hpp, entry);
1515 			hist_entry__snprintf_alignment(entry, &hpp, fmt, ret);
1516 			/*
1517 			 * fmt->color() already used ui_browser to
1518 			 * print the non alignment bits, skip it (+ret):
1519 			 */
1520 			ui_browser__printf(&browser->b, "%s", s + ret);
1521 		} else {
1522 			int ret = fmt->entry(fmt, &hpp, entry);
1523 			hist_entry__snprintf_alignment(entry, &hpp, fmt, ret);
1524 			ui_browser__printf(&browser->b, "%s", s);
1525 		}
1526 		width -= hpp.buf - s;
1527 	}
1528 
1529 	if (!first) {
1530 		ui_browser__write_nstring(&browser->b, "", hierarchy_indent);
1531 		width -= hierarchy_indent;
1532 	}
1533 
1534 	if (column >= browser->b.horiz_scroll) {
1535 		char s[2048];
1536 		struct perf_hpp hpp = {
1537 			.buf		= s,
1538 			.size		= sizeof(s),
1539 			.ptr		= &arg,
1540 		};
1541 
1542 		if (current_entry && browser->b.navkeypressed) {
1543 			ui_browser__set_color(&browser->b,
1544 					      HE_COLORSET_SELECTED);
1545 		} else {
1546 			ui_browser__set_color(&browser->b,
1547 					      HE_COLORSET_NORMAL);
1548 		}
1549 
1550 		perf_hpp_list__for_each_format(entry->hpp_list, fmt) {
1551 			if (first) {
1552 				ui_browser__printf(&browser->b, "%c ", folded_sign);
1553 				first = false;
1554 			} else {
1555 				ui_browser__write_nstring(&browser->b, "", 2);
1556 			}
1557 
1558 			width -= 2;
1559 
1560 			/*
1561 			 * No need to call hist_entry__snprintf_alignment()
1562 			 * since this fmt is always the last column in the
1563 			 * hierarchy mode.
1564 			 */
1565 			if (fmt->color) {
1566 				width -= fmt->color(fmt, &hpp, entry);
1567 			} else {
1568 				int i = 0;
1569 
1570 				width -= fmt->entry(fmt, &hpp, entry);
1571 				ui_browser__printf(&browser->b, "%s", skip_spaces(s));
1572 
1573 				while (isspace(s[i++]))
1574 					width++;
1575 			}
1576 		}
1577 	}
1578 
1579 	/* The scroll bar isn't being used */
1580 	if (!browser->b.navkeypressed)
1581 		width += 1;
1582 
1583 	ui_browser__write_nstring(&browser->b, "", width);
1584 
1585 	++row;
1586 	++printed;
1587 
1588 show_callchain:
1589 	if (entry->leaf && folded_sign == '-' && row != browser->b.rows) {
1590 		struct callchain_print_arg carg = {
1591 			.row_offset = row_offset,
1592 		};
1593 
1594 		printed += hist_browser__show_callchain(browser, entry,
1595 					level + 1, row,
1596 					hist_browser__show_callchain_entry, &carg,
1597 					hist_browser__check_output_full);
1598 	}
1599 
1600 	return printed;
1601 }
1602 
1603 static int hist_browser__show_no_entry(struct hist_browser *browser,
1604 				       unsigned short row, int level)
1605 {
1606 	int width = browser->b.width;
1607 	bool current_entry = ui_browser__is_current_entry(&browser->b, row);
1608 	bool first = true;
1609 	int column = 0;
1610 	int ret;
1611 	struct perf_hpp_fmt *fmt;
1612 	struct perf_hpp_list_node *fmt_node;
1613 	int indent = browser->hists->nr_hpp_node - 2;
1614 
1615 	if (current_entry) {
1616 		browser->he_selection = NULL;
1617 		browser->selection = NULL;
1618 	}
1619 
1620 	ui_browser__gotorc(&browser->b, row, 0);
1621 
1622 	if (current_entry && browser->b.navkeypressed)
1623 		ui_browser__set_color(&browser->b, HE_COLORSET_SELECTED);
1624 	else
1625 		ui_browser__set_color(&browser->b, HE_COLORSET_NORMAL);
1626 
1627 	ui_browser__write_nstring(&browser->b, "", level * HIERARCHY_INDENT);
1628 	width -= level * HIERARCHY_INDENT;
1629 
1630 	/* the first hpp_list_node is for overhead columns */
1631 	fmt_node = list_first_entry(&browser->hists->hpp_formats,
1632 				    struct perf_hpp_list_node, list);
1633 	perf_hpp_list__for_each_format(&fmt_node->hpp, fmt) {
1634 		if (perf_hpp__should_skip(fmt, browser->hists) ||
1635 		    column++ < browser->b.horiz_scroll)
1636 			continue;
1637 
1638 		ret = fmt->width(fmt, NULL, browser->hists);
1639 
1640 		if (first) {
1641 			/* for folded sign */
1642 			first = false;
1643 			ret++;
1644 		} else {
1645 			/* space between columns */
1646 			ret += 2;
1647 		}
1648 
1649 		ui_browser__write_nstring(&browser->b, "", ret);
1650 		width -= ret;
1651 	}
1652 
1653 	ui_browser__write_nstring(&browser->b, "", indent * HIERARCHY_INDENT);
1654 	width -= indent * HIERARCHY_INDENT;
1655 
1656 	if (column >= browser->b.horiz_scroll) {
1657 		char buf[32];
1658 
1659 		ret = snprintf(buf, sizeof(buf), "no entry >= %.2f%%", browser->min_pcnt);
1660 		ui_browser__printf(&browser->b, "  %s", buf);
1661 		width -= ret + 2;
1662 	}
1663 
1664 	/* The scroll bar isn't being used */
1665 	if (!browser->b.navkeypressed)
1666 		width += 1;
1667 
1668 	ui_browser__write_nstring(&browser->b, "", width);
1669 	return 1;
1670 }
1671 
1672 static int advance_hpp_check(struct perf_hpp *hpp, int inc)
1673 {
1674 	advance_hpp(hpp, inc);
1675 	return hpp->size <= 0;
1676 }
1677 
1678 static int
1679 hists_browser__scnprintf_headers(struct hist_browser *browser, char *buf,
1680 				 size_t size, int line)
1681 {
1682 	struct hists *hists = browser->hists;
1683 	struct perf_hpp dummy_hpp = {
1684 		.buf    = buf,
1685 		.size   = size,
1686 	};
1687 	struct perf_hpp_fmt *fmt;
1688 	size_t ret = 0;
1689 	int column = 0;
1690 	int span = 0;
1691 
1692 	if (hists__has_callchains(hists) && symbol_conf.use_callchain) {
1693 		ret = scnprintf(buf, size, "  ");
1694 		if (advance_hpp_check(&dummy_hpp, ret))
1695 			return ret;
1696 	}
1697 
1698 	hists__for_each_format(browser->hists, fmt) {
1699 		if (perf_hpp__should_skip(fmt, hists)  || column++ < browser->b.horiz_scroll)
1700 			continue;
1701 
1702 		ret = fmt->header(fmt, &dummy_hpp, hists, line, &span);
1703 		if (advance_hpp_check(&dummy_hpp, ret))
1704 			break;
1705 
1706 		if (span)
1707 			continue;
1708 
1709 		ret = scnprintf(dummy_hpp.buf, dummy_hpp.size, "  ");
1710 		if (advance_hpp_check(&dummy_hpp, ret))
1711 			break;
1712 	}
1713 
1714 	return ret;
1715 }
1716 
1717 static int hists_browser__scnprintf_hierarchy_headers(struct hist_browser *browser,
1718 						      char *buf, size_t size, int line)
1719 {
1720 	struct hists *hists = browser->hists;
1721 	struct perf_hpp dummy_hpp = {
1722 		.buf    = buf,
1723 		.size   = size,
1724 	};
1725 	struct perf_hpp_fmt *fmt;
1726 	struct perf_hpp_list_node *fmt_node;
1727 	size_t ret = 0;
1728 	int column = 0;
1729 	int indent = hists->nr_hpp_node - 2;
1730 	bool first_node, first_col;
1731 
1732 	ret = scnprintf(buf, size, "  ");
1733 	if (advance_hpp_check(&dummy_hpp, ret))
1734 		return ret;
1735 
1736 	first_node = true;
1737 	/* the first hpp_list_node is for overhead columns */
1738 	fmt_node = list_first_entry(&hists->hpp_formats,
1739 				    struct perf_hpp_list_node, list);
1740 	perf_hpp_list__for_each_format(&fmt_node->hpp, fmt) {
1741 		if (column++ < browser->b.horiz_scroll)
1742 			continue;
1743 
1744 		ret = fmt->header(fmt, &dummy_hpp, hists, line, NULL);
1745 		if (advance_hpp_check(&dummy_hpp, ret))
1746 			break;
1747 
1748 		ret = scnprintf(dummy_hpp.buf, dummy_hpp.size, "  ");
1749 		if (advance_hpp_check(&dummy_hpp, ret))
1750 			break;
1751 
1752 		first_node = false;
1753 	}
1754 
1755 	if (line < hists->hpp_list->nr_header_lines - 1)
1756 		return ret;
1757 
1758 	if (!first_node) {
1759 		ret = scnprintf(dummy_hpp.buf, dummy_hpp.size, "%*s",
1760 				indent * HIERARCHY_INDENT, "");
1761 		if (advance_hpp_check(&dummy_hpp, ret))
1762 			return ret;
1763 	}
1764 
1765 	first_node = true;
1766 	list_for_each_entry_continue(fmt_node, &hists->hpp_formats, list) {
1767 		if (!first_node) {
1768 			ret = scnprintf(dummy_hpp.buf, dummy_hpp.size, " / ");
1769 			if (advance_hpp_check(&dummy_hpp, ret))
1770 				break;
1771 		}
1772 		first_node = false;
1773 
1774 		first_col = true;
1775 		perf_hpp_list__for_each_format(&fmt_node->hpp, fmt) {
1776 			char *start;
1777 
1778 			if (perf_hpp__should_skip(fmt, hists))
1779 				continue;
1780 
1781 			if (!first_col) {
1782 				ret = scnprintf(dummy_hpp.buf, dummy_hpp.size, "+");
1783 				if (advance_hpp_check(&dummy_hpp, ret))
1784 					break;
1785 			}
1786 			first_col = false;
1787 
1788 			ret = fmt->header(fmt, &dummy_hpp, hists, line, NULL);
1789 			dummy_hpp.buf[ret] = '\0';
1790 
1791 			start = strim(dummy_hpp.buf);
1792 			ret = strlen(start);
1793 
1794 			if (start != dummy_hpp.buf)
1795 				memmove(dummy_hpp.buf, start, ret + 1);
1796 
1797 			if (advance_hpp_check(&dummy_hpp, ret))
1798 				break;
1799 		}
1800 	}
1801 
1802 	return ret;
1803 }
1804 
1805 static void hists_browser__hierarchy_headers(struct hist_browser *browser)
1806 {
1807 	struct perf_hpp_list *hpp_list = browser->hists->hpp_list;
1808 	char headers[1024];
1809 	int line;
1810 
1811 	for (line = 0; line < hpp_list->nr_header_lines; line++) {
1812 		hists_browser__scnprintf_hierarchy_headers(browser, headers,
1813 							   sizeof(headers), line);
1814 
1815 		ui_browser__gotorc_title(&browser->b, line, 0);
1816 		ui_browser__set_color(&browser->b, HE_COLORSET_ROOT);
1817 		ui_browser__write_nstring(&browser->b, headers, browser->b.width + 1);
1818 	}
1819 }
1820 
1821 static void hists_browser__headers(struct hist_browser *browser)
1822 {
1823 	struct hists *hists = browser->hists;
1824 	struct perf_hpp_list *hpp_list = hists->hpp_list;
1825 
1826 	int line;
1827 
1828 	for (line = 0; line < hpp_list->nr_header_lines; line++) {
1829 		char headers[1024];
1830 
1831 		hists_browser__scnprintf_headers(browser, headers,
1832 						 sizeof(headers), line);
1833 
1834 		ui_browser__gotorc_title(&browser->b, line, 0);
1835 		ui_browser__set_color(&browser->b, HE_COLORSET_ROOT);
1836 		ui_browser__write_nstring(&browser->b, headers, browser->b.width + 1);
1837 	}
1838 }
1839 
1840 static void hist_browser__show_headers(struct hist_browser *browser)
1841 {
1842 	if (symbol_conf.report_hierarchy)
1843 		hists_browser__hierarchy_headers(browser);
1844 	else
1845 		hists_browser__headers(browser);
1846 }
1847 
1848 static void ui_browser__hists_init_top(struct ui_browser *browser)
1849 {
1850 	if (browser->top == NULL) {
1851 		struct hist_browser *hb;
1852 
1853 		hb = container_of(browser, struct hist_browser, b);
1854 		browser->top = rb_first_cached(&hb->hists->entries);
1855 	}
1856 }
1857 
1858 static unsigned int hist_browser__refresh(struct ui_browser *browser)
1859 {
1860 	unsigned row = 0;
1861 	struct rb_node *nd;
1862 	struct hist_browser *hb = container_of(browser, struct hist_browser, b);
1863 
1864 	if (hb->show_headers)
1865 		hist_browser__show_headers(hb);
1866 
1867 	ui_browser__hists_init_top(browser);
1868 	hb->he_selection = NULL;
1869 	hb->selection = NULL;
1870 
1871 	for (nd = browser->top; nd; nd = rb_hierarchy_next(nd)) {
1872 		struct hist_entry *h = rb_entry(nd, struct hist_entry, rb_node);
1873 		float percent;
1874 
1875 		if (h->filtered) {
1876 			/* let it move to sibling */
1877 			h->unfolded = false;
1878 			continue;
1879 		}
1880 
1881 		if (symbol_conf.report_individual_block)
1882 			percent = block_info__total_cycles_percent(h);
1883 		else
1884 			percent = hist_entry__get_percent_limit(h);
1885 
1886 		if (percent < hb->min_pcnt)
1887 			continue;
1888 
1889 		if (symbol_conf.report_hierarchy) {
1890 			row += hist_browser__show_hierarchy_entry(hb, h, row,
1891 								  h->depth);
1892 			if (row == browser->rows)
1893 				break;
1894 
1895 			if (h->has_no_entry) {
1896 				hist_browser__show_no_entry(hb, row, h->depth + 1);
1897 				row++;
1898 			}
1899 		} else {
1900 			row += hist_browser__show_entry(hb, h, row);
1901 		}
1902 
1903 		if (row == browser->rows)
1904 			break;
1905 	}
1906 
1907 	return row;
1908 }
1909 
1910 static struct rb_node *hists__filter_entries(struct rb_node *nd,
1911 					     float min_pcnt)
1912 {
1913 	while (nd != NULL) {
1914 		struct hist_entry *h = rb_entry(nd, struct hist_entry, rb_node);
1915 		float percent = hist_entry__get_percent_limit(h);
1916 
1917 		if (!h->filtered && percent >= min_pcnt)
1918 			return nd;
1919 
1920 		/*
1921 		 * If it's filtered, its all children also were filtered.
1922 		 * So move to sibling node.
1923 		 */
1924 		if (rb_next(nd))
1925 			nd = rb_next(nd);
1926 		else
1927 			nd = rb_hierarchy_next(nd);
1928 	}
1929 
1930 	return NULL;
1931 }
1932 
1933 static struct rb_node *hists__filter_prev_entries(struct rb_node *nd,
1934 						  float min_pcnt)
1935 {
1936 	while (nd != NULL) {
1937 		struct hist_entry *h = rb_entry(nd, struct hist_entry, rb_node);
1938 		float percent = hist_entry__get_percent_limit(h);
1939 
1940 		if (!h->filtered && percent >= min_pcnt)
1941 			return nd;
1942 
1943 		nd = rb_hierarchy_prev(nd);
1944 	}
1945 
1946 	return NULL;
1947 }
1948 
1949 static void ui_browser__hists_seek(struct ui_browser *browser,
1950 				   off_t offset, int whence)
1951 {
1952 	struct hist_entry *h;
1953 	struct rb_node *nd;
1954 	bool first = true;
1955 	struct hist_browser *hb;
1956 
1957 	hb = container_of(browser, struct hist_browser, b);
1958 
1959 	if (browser->nr_entries == 0)
1960 		return;
1961 
1962 	ui_browser__hists_init_top(browser);
1963 
1964 	switch (whence) {
1965 	case SEEK_SET:
1966 		nd = hists__filter_entries(rb_first(browser->entries),
1967 					   hb->min_pcnt);
1968 		break;
1969 	case SEEK_CUR:
1970 		nd = browser->top;
1971 		goto do_offset;
1972 	case SEEK_END:
1973 		nd = rb_hierarchy_last(rb_last(browser->entries));
1974 		nd = hists__filter_prev_entries(nd, hb->min_pcnt);
1975 		first = false;
1976 		break;
1977 	default:
1978 		return;
1979 	}
1980 
1981 	/*
1982 	 * Moves not relative to the first visible entry invalidates its
1983 	 * row_offset:
1984 	 */
1985 	h = rb_entry(browser->top, struct hist_entry, rb_node);
1986 	h->row_offset = 0;
1987 
1988 	/*
1989 	 * Here we have to check if nd is expanded (+), if it is we can't go
1990 	 * the next top level hist_entry, instead we must compute an offset of
1991 	 * what _not_ to show and not change the first visible entry.
1992 	 *
1993 	 * This offset increments when we are going from top to bottom and
1994 	 * decreases when we're going from bottom to top.
1995 	 *
1996 	 * As we don't have backpointers to the top level in the callchains
1997 	 * structure, we need to always print the whole hist_entry callchain,
1998 	 * skipping the first ones that are before the first visible entry
1999 	 * and stop when we printed enough lines to fill the screen.
2000 	 */
2001 do_offset:
2002 	if (!nd)
2003 		return;
2004 
2005 	if (offset > 0) {
2006 		do {
2007 			h = rb_entry(nd, struct hist_entry, rb_node);
2008 			if (h->unfolded && h->leaf) {
2009 				u16 remaining = h->nr_rows - h->row_offset;
2010 				if (offset > remaining) {
2011 					offset -= remaining;
2012 					h->row_offset = 0;
2013 				} else {
2014 					h->row_offset += offset;
2015 					offset = 0;
2016 					browser->top = nd;
2017 					break;
2018 				}
2019 			}
2020 			nd = hists__filter_entries(rb_hierarchy_next(nd),
2021 						   hb->min_pcnt);
2022 			if (nd == NULL)
2023 				break;
2024 			--offset;
2025 			browser->top = nd;
2026 		} while (offset != 0);
2027 	} else if (offset < 0) {
2028 		while (1) {
2029 			h = rb_entry(nd, struct hist_entry, rb_node);
2030 			if (h->unfolded && h->leaf) {
2031 				if (first) {
2032 					if (-offset > h->row_offset) {
2033 						offset += h->row_offset;
2034 						h->row_offset = 0;
2035 					} else {
2036 						h->row_offset += offset;
2037 						offset = 0;
2038 						browser->top = nd;
2039 						break;
2040 					}
2041 				} else {
2042 					if (-offset > h->nr_rows) {
2043 						offset += h->nr_rows;
2044 						h->row_offset = 0;
2045 					} else {
2046 						h->row_offset = h->nr_rows + offset;
2047 						offset = 0;
2048 						browser->top = nd;
2049 						break;
2050 					}
2051 				}
2052 			}
2053 
2054 			nd = hists__filter_prev_entries(rb_hierarchy_prev(nd),
2055 							hb->min_pcnt);
2056 			if (nd == NULL)
2057 				break;
2058 			++offset;
2059 			browser->top = nd;
2060 			if (offset == 0) {
2061 				/*
2062 				 * Last unfiltered hist_entry, check if it is
2063 				 * unfolded, if it is then we should have
2064 				 * row_offset at its last entry.
2065 				 */
2066 				h = rb_entry(nd, struct hist_entry, rb_node);
2067 				if (h->unfolded && h->leaf)
2068 					h->row_offset = h->nr_rows;
2069 				break;
2070 			}
2071 			first = false;
2072 		}
2073 	} else {
2074 		browser->top = nd;
2075 		h = rb_entry(nd, struct hist_entry, rb_node);
2076 		h->row_offset = 0;
2077 	}
2078 }
2079 
2080 static int hist_browser__fprintf_callchain(struct hist_browser *browser,
2081 					   struct hist_entry *he, FILE *fp,
2082 					   int level)
2083 {
2084 	struct callchain_print_arg arg  = {
2085 		.fp = fp,
2086 	};
2087 
2088 	hist_browser__show_callchain(browser, he, level, 0,
2089 				     hist_browser__fprintf_callchain_entry, &arg,
2090 				     hist_browser__check_dump_full);
2091 	return arg.printed;
2092 }
2093 
2094 static int hist_browser__fprintf_entry(struct hist_browser *browser,
2095 				       struct hist_entry *he, FILE *fp)
2096 {
2097 	char s[8192];
2098 	int printed = 0;
2099 	char folded_sign = ' ';
2100 	struct perf_hpp hpp = {
2101 		.buf = s,
2102 		.size = sizeof(s),
2103 	};
2104 	struct perf_hpp_fmt *fmt;
2105 	bool first = true;
2106 	int ret;
2107 
2108 	if (hist_entry__has_callchains(he) && symbol_conf.use_callchain) {
2109 		folded_sign = hist_entry__folded(he);
2110 		printed += fprintf(fp, "%c ", folded_sign);
2111 	}
2112 
2113 	hists__for_each_format(browser->hists, fmt) {
2114 		if (perf_hpp__should_skip(fmt, he->hists))
2115 			continue;
2116 
2117 		if (!first) {
2118 			ret = scnprintf(hpp.buf, hpp.size, "  ");
2119 			advance_hpp(&hpp, ret);
2120 		} else
2121 			first = false;
2122 
2123 		ret = fmt->entry(fmt, &hpp, he);
2124 		ret = hist_entry__snprintf_alignment(he, &hpp, fmt, ret);
2125 		advance_hpp(&hpp, ret);
2126 	}
2127 	printed += fprintf(fp, "%s\n", s);
2128 
2129 	if (folded_sign == '-')
2130 		printed += hist_browser__fprintf_callchain(browser, he, fp, 1);
2131 
2132 	return printed;
2133 }
2134 
2135 
2136 static int hist_browser__fprintf_hierarchy_entry(struct hist_browser *browser,
2137 						 struct hist_entry *he,
2138 						 FILE *fp, int level)
2139 {
2140 	char s[8192];
2141 	int printed = 0;
2142 	char folded_sign = ' ';
2143 	struct perf_hpp hpp = {
2144 		.buf = s,
2145 		.size = sizeof(s),
2146 	};
2147 	struct perf_hpp_fmt *fmt;
2148 	struct perf_hpp_list_node *fmt_node;
2149 	bool first = true;
2150 	int ret;
2151 	int hierarchy_indent = (he->hists->nr_hpp_node - 2) * HIERARCHY_INDENT;
2152 
2153 	printed = fprintf(fp, "%*s", level * HIERARCHY_INDENT, "");
2154 
2155 	folded_sign = hist_entry__folded(he);
2156 	printed += fprintf(fp, "%c", folded_sign);
2157 
2158 	/* the first hpp_list_node is for overhead columns */
2159 	fmt_node = list_first_entry(&he->hists->hpp_formats,
2160 				    struct perf_hpp_list_node, list);
2161 	perf_hpp_list__for_each_format(&fmt_node->hpp, fmt) {
2162 		if (!first) {
2163 			ret = scnprintf(hpp.buf, hpp.size, "  ");
2164 			advance_hpp(&hpp, ret);
2165 		} else
2166 			first = false;
2167 
2168 		ret = fmt->entry(fmt, &hpp, he);
2169 		advance_hpp(&hpp, ret);
2170 	}
2171 
2172 	ret = scnprintf(hpp.buf, hpp.size, "%*s", hierarchy_indent, "");
2173 	advance_hpp(&hpp, ret);
2174 
2175 	perf_hpp_list__for_each_format(he->hpp_list, fmt) {
2176 		ret = scnprintf(hpp.buf, hpp.size, "  ");
2177 		advance_hpp(&hpp, ret);
2178 
2179 		ret = fmt->entry(fmt, &hpp, he);
2180 		advance_hpp(&hpp, ret);
2181 	}
2182 
2183 	strim(s);
2184 	printed += fprintf(fp, "%s\n", s);
2185 
2186 	if (he->leaf && folded_sign == '-') {
2187 		printed += hist_browser__fprintf_callchain(browser, he, fp,
2188 							   he->depth + 1);
2189 	}
2190 
2191 	return printed;
2192 }
2193 
2194 static int hist_browser__fprintf(struct hist_browser *browser, FILE *fp)
2195 {
2196 	struct rb_node *nd = hists__filter_entries(rb_first(browser->b.entries),
2197 						   browser->min_pcnt);
2198 	int printed = 0;
2199 
2200 	while (nd) {
2201 		struct hist_entry *h = rb_entry(nd, struct hist_entry, rb_node);
2202 
2203 		if (symbol_conf.report_hierarchy) {
2204 			printed += hist_browser__fprintf_hierarchy_entry(browser,
2205 									 h, fp,
2206 									 h->depth);
2207 		} else {
2208 			printed += hist_browser__fprintf_entry(browser, h, fp);
2209 		}
2210 
2211 		nd = hists__filter_entries(rb_hierarchy_next(nd),
2212 					   browser->min_pcnt);
2213 	}
2214 
2215 	return printed;
2216 }
2217 
2218 static int hist_browser__dump(struct hist_browser *browser)
2219 {
2220 	char filename[64];
2221 	FILE *fp;
2222 
2223 	while (1) {
2224 		scnprintf(filename, sizeof(filename), "perf.hist.%d", browser->print_seq);
2225 		if (access(filename, F_OK))
2226 			break;
2227 		/*
2228  		 * XXX: Just an arbitrary lazy upper limit
2229  		 */
2230 		if (++browser->print_seq == 8192) {
2231 			ui_helpline__fpush("Too many perf.hist.N files, nothing written!");
2232 			return -1;
2233 		}
2234 	}
2235 
2236 	fp = fopen(filename, "w");
2237 	if (fp == NULL) {
2238 		char bf[64];
2239 		const char *err = str_error_r(errno, bf, sizeof(bf));
2240 		ui_helpline__fpush("Couldn't write to %s: %s", filename, err);
2241 		return -1;
2242 	}
2243 
2244 	++browser->print_seq;
2245 	hist_browser__fprintf(browser, fp);
2246 	fclose(fp);
2247 	ui_helpline__fpush("%s written!", filename);
2248 
2249 	return 0;
2250 }
2251 
2252 void hist_browser__init(struct hist_browser *browser,
2253 			struct hists *hists)
2254 {
2255 	struct perf_hpp_fmt *fmt;
2256 
2257 	browser->hists			= hists;
2258 	browser->b.refresh		= hist_browser__refresh;
2259 	browser->b.refresh_dimensions	= hist_browser__refresh_dimensions;
2260 	browser->b.seek			= ui_browser__hists_seek;
2261 	browser->b.use_navkeypressed	= true;
2262 	browser->show_headers		= symbol_conf.show_hist_headers;
2263 	hist_browser__set_title_space(browser);
2264 
2265 	if (symbol_conf.report_hierarchy) {
2266 		struct perf_hpp_list_node *fmt_node;
2267 
2268 		/* count overhead columns (in the first node) */
2269 		fmt_node = list_first_entry(&hists->hpp_formats,
2270 					    struct perf_hpp_list_node, list);
2271 		perf_hpp_list__for_each_format(&fmt_node->hpp, fmt)
2272 			++browser->b.columns;
2273 
2274 		/* add a single column for whole hierarchy sort keys*/
2275 		++browser->b.columns;
2276 	} else {
2277 		hists__for_each_format(hists, fmt)
2278 			++browser->b.columns;
2279 	}
2280 
2281 	hists__reset_column_width(hists);
2282 }
2283 
2284 struct hist_browser *hist_browser__new(struct hists *hists)
2285 {
2286 	struct hist_browser *browser = zalloc(sizeof(*browser));
2287 
2288 	if (browser)
2289 		hist_browser__init(browser, hists);
2290 
2291 	return browser;
2292 }
2293 
2294 static struct hist_browser *
2295 perf_evsel_browser__new(struct evsel *evsel,
2296 			struct hist_browser_timer *hbt,
2297 			struct perf_env *env)
2298 {
2299 	struct hist_browser *browser = hist_browser__new(evsel__hists(evsel));
2300 
2301 	if (browser) {
2302 		browser->hbt   = hbt;
2303 		browser->env   = env;
2304 		browser->title = hists_browser__scnprintf_title;
2305 	}
2306 	return browser;
2307 }
2308 
2309 void hist_browser__delete(struct hist_browser *browser)
2310 {
2311 	free(browser);
2312 }
2313 
2314 static struct hist_entry *hist_browser__selected_entry(struct hist_browser *browser)
2315 {
2316 	return browser->he_selection;
2317 }
2318 
2319 static struct thread *hist_browser__selected_thread(struct hist_browser *browser)
2320 {
2321 	return browser->he_selection->thread;
2322 }
2323 
2324 static struct res_sample *hist_browser__selected_res_sample(struct hist_browser *browser)
2325 {
2326 	return browser->he_selection ? browser->he_selection->res_samples : NULL;
2327 }
2328 
2329 /* Check whether the browser is for 'top' or 'report' */
2330 static inline bool is_report_browser(void *timer)
2331 {
2332 	return timer == NULL;
2333 }
2334 
2335 static int hists_browser__scnprintf_title(struct hist_browser *browser, char *bf, size_t size)
2336 {
2337 	struct hist_browser_timer *hbt = browser->hbt;
2338 	int printed = __hists__scnprintf_title(browser->hists, bf, size, !is_report_browser(hbt));
2339 
2340 	if (!is_report_browser(hbt)) {
2341 		struct perf_top *top = hbt->arg;
2342 
2343 		printed += scnprintf(bf + printed, size - printed,
2344 				     " lost: %" PRIu64 "/%" PRIu64,
2345 				     top->lost, top->lost_total);
2346 
2347 		printed += scnprintf(bf + printed, size - printed,
2348 				     " drop: %" PRIu64 "/%" PRIu64,
2349 				     top->drop, top->drop_total);
2350 
2351 		if (top->zero)
2352 			printed += scnprintf(bf + printed, size - printed, " [z]");
2353 
2354 		perf_top__reset_sample_counters(top);
2355 	}
2356 
2357 
2358 	return printed;
2359 }
2360 
2361 struct popup_action {
2362 	unsigned long		time;
2363 	int (*fn)(struct hist_browser *browser, struct popup_action *act);
2364 	struct map_symbol	ms;
2365 	int			socket;
2366 	enum rstype		rstype;
2367 
2368 };
2369 
2370 static inline void free_popup_options(char **options, int n)
2371 {
2372 	int i;
2373 
2374 	for (i = 0; i < n; ++i)
2375 		zfree(&options[i]);
2376 }
2377 
2378 static inline void free_popup_actions(struct popup_action *actions, int n)
2379 {
2380 	int i;
2381 
2382 	for (i = 0; i < n; ++i) {
2383 		map_symbol__exit(&actions[i].ms);
2384 		memset(&actions[i], 0, sizeof(struct popup_action));
2385 	}
2386 }
2387 
2388 /*
2389  * Only runtime switching of perf data file will make "input_name" point
2390  * to a malloced buffer. So add "is_input_name_malloced" flag to decide
2391  * whether we need to call free() for current "input_name" during the switch.
2392  */
2393 static bool is_input_name_malloced = false;
2394 
2395 static int switch_data_file(void)
2396 {
2397 	char *pwd, *options[32], *abs_path[32], *tmp;
2398 	DIR *pwd_dir;
2399 	int nr_options = 0, choice = -1, ret = -1;
2400 	struct dirent *dent;
2401 
2402 	pwd = getenv("PWD");
2403 	if (!pwd)
2404 		return ret;
2405 
2406 	pwd_dir = opendir(pwd);
2407 	if (!pwd_dir)
2408 		return ret;
2409 
2410 	memset(options, 0, sizeof(options));
2411 	memset(abs_path, 0, sizeof(abs_path));
2412 
2413 	while ((dent = readdir(pwd_dir))) {
2414 		char path[PATH_MAX];
2415 		u64 magic;
2416 		char *name = dent->d_name;
2417 		FILE *file;
2418 
2419 		if (!(dent->d_type == DT_REG))
2420 			continue;
2421 
2422 		snprintf(path, sizeof(path), "%s/%s", pwd, name);
2423 
2424 		file = fopen(path, "r");
2425 		if (!file)
2426 			continue;
2427 
2428 		if (fread(&magic, 1, 8, file) < 8)
2429 			goto close_file_and_continue;
2430 
2431 		if (is_perf_magic(magic)) {
2432 			options[nr_options] = strdup(name);
2433 			if (!options[nr_options])
2434 				goto close_file_and_continue;
2435 
2436 			abs_path[nr_options] = strdup(path);
2437 			if (!abs_path[nr_options]) {
2438 				zfree(&options[nr_options]);
2439 				ui__warning("Can't search all data files due to memory shortage.\n");
2440 				fclose(file);
2441 				break;
2442 			}
2443 
2444 			nr_options++;
2445 		}
2446 
2447 close_file_and_continue:
2448 		fclose(file);
2449 		if (nr_options >= 32) {
2450 			ui__warning("Too many perf data files in PWD!\n"
2451 				    "Only the first 32 files will be listed.\n");
2452 			break;
2453 		}
2454 	}
2455 	closedir(pwd_dir);
2456 
2457 	if (nr_options) {
2458 		choice = ui__popup_menu(nr_options, options, NULL);
2459 		if (choice < nr_options && choice >= 0) {
2460 			tmp = strdup(abs_path[choice]);
2461 			if (tmp) {
2462 				if (is_input_name_malloced)
2463 					free((void *)input_name);
2464 				input_name = tmp;
2465 				is_input_name_malloced = true;
2466 				ret = 0;
2467 			} else
2468 				ui__warning("Data switch failed due to memory shortage!\n");
2469 		}
2470 	}
2471 
2472 	free_popup_options(options, nr_options);
2473 	free_popup_options(abs_path, nr_options);
2474 	return ret;
2475 }
2476 
2477 static int
2478 do_annotate(struct hist_browser *browser, struct popup_action *act)
2479 {
2480 	struct evsel *evsel;
2481 	struct annotation *notes;
2482 	struct hist_entry *he;
2483 	int err;
2484 
2485 	if (!annotate_opts.objdump_path &&
2486 	    perf_env__lookup_objdump(browser->env, &annotate_opts.objdump_path))
2487 		return 0;
2488 
2489 	notes = symbol__annotation(act->ms.sym);
2490 	if (!notes->src)
2491 		return 0;
2492 
2493 	if (browser->block_evsel)
2494 		evsel = browser->block_evsel;
2495 	else
2496 		evsel = hists_to_evsel(browser->hists);
2497 
2498 	he = hist_browser__selected_entry(browser);
2499 	err = __hist_entry__tui_annotate(he, &act->ms, evsel, browser->hbt, NO_ADDR);
2500 	/*
2501 	 * offer option to annotate the other branch source or target
2502 	 * (if they exists) when returning from annotate
2503 	 */
2504 	if ((err == 'q' || err == CTRL('c')) && he->branch_info)
2505 		return 1;
2506 
2507 	ui_browser__update_nr_entries(&browser->b, browser->hists->nr_entries);
2508 	if (err)
2509 		ui_browser__handle_resize(&browser->b);
2510 	return 0;
2511 }
2512 
2513 static struct symbol *symbol__new_unresolved(u64 addr, struct map *map)
2514 {
2515 	struct annotated_source *src;
2516 	struct symbol *sym;
2517 	char name[64];
2518 
2519 	snprintf(name, sizeof(name), "%.*" PRIx64, BITS_PER_LONG / 4, addr);
2520 
2521 	sym = symbol__new(addr, ANNOTATION_DUMMY_LEN, 0, 0, name);
2522 	if (sym) {
2523 		src = symbol__hists(sym, 1);
2524 		if (!src) {
2525 			symbol__delete(sym);
2526 			return NULL;
2527 		}
2528 
2529 		dso__insert_symbol(map__dso(map), sym);
2530 	}
2531 
2532 	return sym;
2533 }
2534 
2535 static int
2536 add_annotate_opt(struct popup_action *act, char **optstr,
2537 		 struct map_symbol *ms,
2538 		 u64 addr)
2539 {
2540 	struct dso *dso;
2541 
2542 	if (!ms->map || (dso = map__dso(ms->map)) == NULL || dso__annotate_warned(dso))
2543 		return 0;
2544 
2545 	if (!ms->sym)
2546 		ms->sym = symbol__new_unresolved(addr, ms->map);
2547 
2548 	if (ms->sym == NULL || symbol__annotation(ms->sym)->src == NULL)
2549 		return 0;
2550 
2551 	if (asprintf(optstr, "Annotate %s", ms->sym->name) < 0)
2552 		return 0;
2553 
2554 	map_symbol__copy(&act->ms, ms);
2555 	act->fn = do_annotate;
2556 	return 1;
2557 }
2558 
2559 static int
2560 do_annotate_type(struct hist_browser *browser, struct popup_action *act __maybe_unused)
2561 {
2562 	struct hist_entry *he = browser->he_selection;
2563 
2564 	hist_entry__annotate_data_tui(he, hists_to_evsel(browser->hists), browser->hbt);
2565 	ui_browser__handle_resize(&browser->b);
2566 	return 0;
2567 }
2568 
2569 static int
2570 add_annotate_type_opt(struct popup_action *act, char **optstr,
2571 		      struct hist_entry *he)
2572 {
2573 	if (he == NULL || he->mem_type == NULL || he->mem_type->histograms == NULL)
2574 		return 0;
2575 
2576 	if (asprintf(optstr, "Annotate type %s", he->mem_type->self.type_name) < 0)
2577 		return 0;
2578 
2579 	act->fn = do_annotate_type;
2580 	return 1;
2581 }
2582 
2583 static int
2584 do_zoom_thread(struct hist_browser *browser, struct popup_action *act)
2585 {
2586 	struct thread *thread = act->ms.thread;
2587 
2588 	if ((!hists__has(browser->hists, thread) &&
2589 	     !hists__has(browser->hists, comm)) || thread == NULL)
2590 		return 0;
2591 
2592 	if (browser->hists->thread_filter) {
2593 		pstack__remove(browser->pstack, &browser->hists->thread_filter);
2594 		perf_hpp__set_elide(HISTC_THREAD, false);
2595 		thread__zput(browser->hists->thread_filter);
2596 		ui_helpline__pop();
2597 	} else {
2598 		const char *comm_set_str =
2599 			thread__comm_set(thread) ? thread__comm_str(thread) : "";
2600 
2601 		if (hists__has(browser->hists, thread)) {
2602 			ui_helpline__fpush("To zoom out press ESC or ENTER + \"Zoom out of %s(%d) thread\"",
2603 					   comm_set_str, thread__tid(thread));
2604 		} else {
2605 			ui_helpline__fpush("To zoom out press ESC or ENTER + \"Zoom out of %s thread\"",
2606 					   comm_set_str);
2607 		}
2608 
2609 		browser->hists->thread_filter = thread__get(thread);
2610 		perf_hpp__set_elide(HISTC_THREAD, false);
2611 		pstack__push(browser->pstack, &browser->hists->thread_filter);
2612 	}
2613 
2614 	hists__filter_by_thread(browser->hists);
2615 	hist_browser__reset(browser);
2616 	return 0;
2617 }
2618 
2619 static int
2620 add_thread_opt(struct hist_browser *browser, struct popup_action *act,
2621 	       char **optstr, struct thread *thread)
2622 {
2623 	int ret;
2624 	const char *comm_set_str, *in_out;
2625 
2626 	if ((!hists__has(browser->hists, thread) &&
2627 	     !hists__has(browser->hists, comm)) || thread == NULL)
2628 		return 0;
2629 
2630 	in_out = browser->hists->thread_filter ? "out of" : "into";
2631 	comm_set_str = thread__comm_set(thread) ? thread__comm_str(thread) : "";
2632 	if (hists__has(browser->hists, thread)) {
2633 		ret = asprintf(optstr, "Zoom %s %s(%d) thread",
2634 			       in_out, comm_set_str, thread__tid(thread));
2635 	} else {
2636 		ret = asprintf(optstr, "Zoom %s %s thread", in_out, comm_set_str);
2637 	}
2638 	if (ret < 0)
2639 		return 0;
2640 
2641 	act->ms.thread = thread__get(thread);
2642 	act->fn = do_zoom_thread;
2643 	return 1;
2644 }
2645 
2646 static int hists_browser__zoom_map(struct hist_browser *browser, struct map *map)
2647 {
2648 	if (!hists__has(browser->hists, dso) || map == NULL)
2649 		return 0;
2650 
2651 	if (browser->hists->dso_filter) {
2652 		pstack__remove(browser->pstack, &browser->hists->dso_filter);
2653 		perf_hpp__set_elide(HISTC_DSO, false);
2654 		dso__put((struct dso *)browser->hists->dso_filter);
2655 		browser->hists->dso_filter = NULL;
2656 		ui_helpline__pop();
2657 	} else {
2658 		struct dso *dso = map__dso(map);
2659 		ui_helpline__fpush("To zoom out press ESC or ENTER + \"Zoom out of %s DSO\"",
2660 				   __map__is_kernel(map) ? "the Kernel" : dso__short_name(dso));
2661 		browser->hists->dso_filter = dso__get(dso);
2662 		perf_hpp__set_elide(HISTC_DSO, true);
2663 		pstack__push(browser->pstack, &browser->hists->dso_filter);
2664 	}
2665 
2666 	hists__filter_by_dso(browser->hists);
2667 	hist_browser__reset(browser);
2668 	return 0;
2669 }
2670 
2671 static int
2672 do_zoom_dso(struct hist_browser *browser, struct popup_action *act)
2673 {
2674 	return hists_browser__zoom_map(browser, act->ms.map);
2675 }
2676 
2677 static int
2678 add_dso_opt(struct hist_browser *browser, struct popup_action *act,
2679 	    char **optstr, struct map *map)
2680 {
2681 	if (!hists__has(browser->hists, dso) || map == NULL)
2682 		return 0;
2683 
2684 	if (asprintf(optstr, "Zoom %s %s DSO (use the 'k' hotkey to zoom directly into the kernel)",
2685 		     browser->hists->dso_filter ? "out of" : "into",
2686 		     __map__is_kernel(map) ? "the Kernel" : dso__short_name(map__dso(map))) < 0)
2687 		return 0;
2688 
2689 	act->ms.map = map__get(map);
2690 	act->fn = do_zoom_dso;
2691 	return 1;
2692 }
2693 
2694 static int do_toggle_callchain(struct hist_browser *browser, struct popup_action *act __maybe_unused)
2695 {
2696 	hist_browser__toggle_fold(browser);
2697 	return 0;
2698 }
2699 
2700 static int add_callchain_toggle_opt(struct hist_browser *browser, struct popup_action *act, char **optstr)
2701 {
2702 	char sym_name[512];
2703 
2704         if (!hist_browser__selection_has_children(browser))
2705                 return 0;
2706 
2707 	if (asprintf(optstr, "%s [%s] callchain (one level, same as '+' hotkey, use 'e'/'c' for the whole main level entry)",
2708 		     hist_browser__selection_unfolded(browser) ? "Collapse" : "Expand",
2709 		     hist_browser__selection_sym_name(browser, sym_name, sizeof(sym_name))) < 0)
2710 		return 0;
2711 
2712 	act->fn = do_toggle_callchain;
2713 	return 1;
2714 }
2715 
2716 static int
2717 do_browse_map(struct hist_browser *browser __maybe_unused,
2718 	      struct popup_action *act)
2719 {
2720 	map__browse(act->ms.map);
2721 	return 0;
2722 }
2723 
2724 static int
2725 add_map_opt(struct hist_browser *browser,
2726 	    struct popup_action *act, char **optstr, struct map *map)
2727 {
2728 	if (!hists__has(browser->hists, dso) || map == NULL)
2729 		return 0;
2730 
2731 	if (asprintf(optstr, "Browse map details") < 0)
2732 		return 0;
2733 
2734 	act->ms.map = map__get(map);
2735 	act->fn = do_browse_map;
2736 	return 1;
2737 }
2738 
2739 static int
2740 do_run_script(struct hist_browser *browser,
2741 	      struct popup_action *act)
2742 {
2743 	char *script_opt;
2744 	int len;
2745 	int n = 0;
2746 
2747 	len = 100;
2748 	if (act->ms.thread)
2749 		len += strlen(thread__comm_str(act->ms.thread));
2750 	else if (act->ms.sym)
2751 		len += strlen(act->ms.sym->name);
2752 	script_opt = malloc(len);
2753 	if (!script_opt)
2754 		return -1;
2755 
2756 	script_opt[0] = 0;
2757 	if (act->ms.thread) {
2758 		n = scnprintf(script_opt, len, " -c %s ",
2759 			  thread__comm_str(act->ms.thread));
2760 	} else if (act->ms.sym) {
2761 		n = scnprintf(script_opt, len, " -S %s ",
2762 			  act->ms.sym->name);
2763 	}
2764 
2765 	if (act->time) {
2766 		char start[32], end[32];
2767 		unsigned long starttime = act->time;
2768 		unsigned long endtime = act->time + symbol_conf.time_quantum;
2769 
2770 		if (starttime == endtime) { /* Display 1ms as fallback */
2771 			starttime -= 1*NSEC_PER_MSEC;
2772 			endtime += 1*NSEC_PER_MSEC;
2773 		}
2774 		timestamp__scnprintf_usec(starttime, start, sizeof start);
2775 		timestamp__scnprintf_usec(endtime, end, sizeof end);
2776 		n += snprintf(script_opt + n, len - n, " --time %s,%s", start, end);
2777 	}
2778 
2779 	script_browse(script_opt, hists_to_evsel(browser->hists));
2780 	free(script_opt);
2781 	return 0;
2782 }
2783 
2784 static int
2785 do_res_sample_script(struct hist_browser *browser,
2786 		     struct popup_action *act)
2787 {
2788 	struct hist_entry *he;
2789 
2790 	he = hist_browser__selected_entry(browser);
2791 	res_sample_browse(he->res_samples, he->num_res, hists_to_evsel(browser->hists), act->rstype);
2792 	return 0;
2793 }
2794 
2795 static int
2796 add_script_opt_2(struct popup_action *act, char **optstr,
2797 	       struct thread *thread, struct symbol *sym,
2798 	       const char *tstr)
2799 {
2800 
2801 	if (thread) {
2802 		if (asprintf(optstr, "Run scripts for samples of thread [%s]%s",
2803 			     thread__comm_str(thread), tstr) < 0)
2804 			return 0;
2805 	} else if (sym) {
2806 		if (asprintf(optstr, "Run scripts for samples of symbol [%s]%s",
2807 			     sym->name, tstr) < 0)
2808 			return 0;
2809 	} else {
2810 		if (asprintf(optstr, "Run scripts for all samples%s", tstr) < 0)
2811 			return 0;
2812 	}
2813 
2814 	act->ms.thread = thread__get(thread);
2815 	act->ms.sym = sym;
2816 	act->fn = do_run_script;
2817 	return 1;
2818 }
2819 
2820 static int
2821 add_script_opt(struct hist_browser *browser,
2822 	       struct popup_action *act, char **optstr,
2823 	       struct thread *thread, struct symbol *sym)
2824 {
2825 	int n, j, ret;
2826 	struct hist_entry *he;
2827 
2828 	n = add_script_opt_2(act, optstr, thread, sym, "");
2829 
2830 	he = hist_browser__selected_entry(browser);
2831 	if (sort_order && strstr(sort_order, "time")) {
2832 		char tstr[128];
2833 		struct popup_action *time_act = act;
2834 		char **time_optstr = optstr;
2835 
2836 		if (n > 0) {
2837 			time_optstr++;
2838 			time_act++;
2839 		}
2840 		if (he == NULL)
2841 			return n;
2842 		j = sprintf(tstr, " in ");
2843 		j += timestamp__scnprintf_usec(he->time, tstr + j,
2844 					       sizeof tstr - j);
2845 		j += sprintf(tstr + j, "-");
2846 		timestamp__scnprintf_usec(he->time + symbol_conf.time_quantum,
2847 				          tstr + j, sizeof tstr - j);
2848 		ret = add_script_opt_2(time_act, time_optstr, thread, sym, tstr);
2849 		if (ret > 0) {
2850 			time_act->time = he->time;
2851 			n += ret;
2852 		}
2853 	}
2854 	return n;
2855 }
2856 
2857 static int
2858 add_res_sample_opt(struct hist_browser *browser __maybe_unused,
2859 		   struct popup_action *act, char **optstr,
2860 		   struct res_sample *res_sample,
2861 		   enum rstype type)
2862 {
2863 	if (!res_sample)
2864 		return 0;
2865 
2866 	if (asprintf(optstr, "Show context for individual samples %s",
2867 		type == A_ASM ? "with assembler" :
2868 		type == A_SOURCE ? "with source" : "") < 0)
2869 		return 0;
2870 
2871 	act->fn = do_res_sample_script;
2872 	act->rstype = type;
2873 	return 1;
2874 }
2875 
2876 static int
2877 do_switch_data(struct hist_browser *browser __maybe_unused,
2878 	       struct popup_action *act __maybe_unused)
2879 {
2880 	if (switch_data_file()) {
2881 		ui__warning("Won't switch the data files due to\n"
2882 			    "no valid data file get selected!\n");
2883 		return 0;
2884 	}
2885 
2886 	return K_SWITCH_INPUT_DATA;
2887 }
2888 
2889 static int
2890 add_switch_opt(struct hist_browser *browser,
2891 	       struct popup_action *act, char **optstr)
2892 {
2893 	if (!is_report_browser(browser->hbt))
2894 		return 0;
2895 
2896 	if (asprintf(optstr, "Switch to another data file in PWD") < 0)
2897 		return 0;
2898 
2899 	act->fn = do_switch_data;
2900 	return 1;
2901 }
2902 
2903 static int
2904 do_exit_browser(struct hist_browser *browser __maybe_unused,
2905 		struct popup_action *act __maybe_unused)
2906 {
2907 	return 0;
2908 }
2909 
2910 static int
2911 add_exit_opt(struct hist_browser *browser __maybe_unused,
2912 	     struct popup_action *act, char **optstr)
2913 {
2914 	if (asprintf(optstr, "Exit") < 0)
2915 		return 0;
2916 
2917 	act->fn = do_exit_browser;
2918 	return 1;
2919 }
2920 
2921 static int
2922 do_zoom_socket(struct hist_browser *browser, struct popup_action *act)
2923 {
2924 	if (!hists__has(browser->hists, socket) || act->socket < 0)
2925 		return 0;
2926 
2927 	if (browser->hists->socket_filter > -1) {
2928 		pstack__remove(browser->pstack, &browser->hists->socket_filter);
2929 		browser->hists->socket_filter = -1;
2930 		perf_hpp__set_elide(HISTC_SOCKET, false);
2931 	} else {
2932 		browser->hists->socket_filter = act->socket;
2933 		perf_hpp__set_elide(HISTC_SOCKET, true);
2934 		pstack__push(browser->pstack, &browser->hists->socket_filter);
2935 	}
2936 
2937 	hists__filter_by_socket(browser->hists);
2938 	hist_browser__reset(browser);
2939 	return 0;
2940 }
2941 
2942 static int
2943 add_socket_opt(struct hist_browser *browser, struct popup_action *act,
2944 	       char **optstr, int socket_id)
2945 {
2946 	if (!hists__has(browser->hists, socket) || socket_id < 0)
2947 		return 0;
2948 
2949 	if (asprintf(optstr, "Zoom %s Processor Socket %d",
2950 		     (browser->hists->socket_filter > -1) ? "out of" : "into",
2951 		     socket_id) < 0)
2952 		return 0;
2953 
2954 	act->socket = socket_id;
2955 	act->fn = do_zoom_socket;
2956 	return 1;
2957 }
2958 
2959 static void hist_browser__update_nr_entries(struct hist_browser *hb)
2960 {
2961 	u64 nr_entries = 0;
2962 	struct rb_node *nd = rb_first_cached(&hb->hists->entries);
2963 
2964 	if (hb->min_pcnt == 0 && !symbol_conf.report_hierarchy) {
2965 		hb->nr_non_filtered_entries = hb->hists->nr_non_filtered_entries;
2966 		return;
2967 	}
2968 
2969 	while ((nd = hists__filter_entries(nd, hb->min_pcnt)) != NULL) {
2970 		nr_entries++;
2971 		nd = rb_hierarchy_next(nd);
2972 	}
2973 
2974 	hb->nr_non_filtered_entries = nr_entries;
2975 	hb->nr_hierarchy_entries = nr_entries;
2976 }
2977 
2978 static void hist_browser__update_percent_limit(struct hist_browser *hb,
2979 					       double percent)
2980 {
2981 	struct hist_entry *he;
2982 	struct rb_node *nd = rb_first_cached(&hb->hists->entries);
2983 	u64 total = hists__total_period(hb->hists);
2984 	u64 min_callchain_hits = total * (percent / 100);
2985 
2986 	hb->min_pcnt = callchain_param.min_percent = percent;
2987 
2988 	while ((nd = hists__filter_entries(nd, hb->min_pcnt)) != NULL) {
2989 		he = rb_entry(nd, struct hist_entry, rb_node);
2990 
2991 		if (he->has_no_entry) {
2992 			he->has_no_entry = false;
2993 			he->nr_rows = 0;
2994 		}
2995 
2996 		if (!he->leaf || !hist_entry__has_callchains(he) || !symbol_conf.use_callchain)
2997 			goto next;
2998 
2999 		if (callchain_param.mode == CHAIN_GRAPH_REL) {
3000 			total = he->stat.period;
3001 
3002 			if (symbol_conf.cumulate_callchain)
3003 				total = he->stat_acc->period;
3004 
3005 			min_callchain_hits = total * (percent / 100);
3006 		}
3007 
3008 		callchain_param.sort(&he->sorted_chain, he->callchain,
3009 				     min_callchain_hits, &callchain_param);
3010 
3011 next:
3012 		nd = __rb_hierarchy_next(nd, HMD_FORCE_CHILD);
3013 
3014 		/* force to re-evaluate folding state of callchains */
3015 		he->init_have_children = false;
3016 		hist_entry__set_folding(he, hb, false);
3017 	}
3018 }
3019 
3020 static int evsel__hists_browse(struct evsel *evsel, int nr_events, const char *helpline,
3021 			       bool left_exits, struct hist_browser_timer *hbt, float min_pcnt,
3022 			       struct perf_env *env, bool warn_lost_event)
3023 {
3024 	struct hists *hists = evsel__hists(evsel);
3025 	struct hist_browser *browser = perf_evsel_browser__new(evsel, hbt, env);
3026 	struct branch_info *bi = NULL;
3027 #define MAX_OPTIONS  32
3028 	char *options[MAX_OPTIONS];
3029 	struct popup_action actions[MAX_OPTIONS], hotkey_act;
3030 	int nr_options = 0;
3031 	int key = -1;
3032 	char buf[128];
3033 	int delay_secs = hbt ? hbt->refresh : 0;
3034 
3035 #define HIST_BROWSER_HELP_COMMON					\
3036 	"h/?/F1        Show this window\n"				\
3037 	"UP/DOWN/PGUP\n"						\
3038 	"PGDN/SPACE    Navigate\n"					\
3039 	"q/ESC/CTRL+C  Exit browser or go back to previous screen\n\n"	\
3040 	"For multiple event sessions:\n\n"				\
3041 	"TAB/UNTAB     Switch events\n\n"				\
3042 	"For symbolic views (--sort has sym):\n\n"			\
3043 	"ENTER         Zoom into DSO/Threads & Annotate current symbol\n" \
3044 	"ESC           Zoom out\n"					\
3045 	"+             Expand/Collapse one callchain level\n"		\
3046 	"a             Annotate current symbol\n"			\
3047 	"C             Collapse all callchains\n"			\
3048 	"d             Zoom into current DSO\n"				\
3049 	"e             Expand/Collapse main entry callchains\n"	\
3050 	"E             Expand all callchains\n"				\
3051 	"F             Toggle percentage of filtered entries\n"		\
3052 	"H             Display column headers\n"			\
3053 	"k             Zoom into the kernel map\n"			\
3054 	"L             Change percent limit\n"				\
3055 	"m             Display context menu\n"				\
3056 	"S             Zoom into current Processor Socket\n"		\
3057 
3058 	/* help messages are sorted by lexical order of the hotkey */
3059 	static const char report_help[] = HIST_BROWSER_HELP_COMMON
3060 	"i             Show header information\n"
3061 	"P             Print histograms to perf.hist.N\n"
3062 	"r             Run available scripts\n"
3063 	"s             Switch to another data file in PWD\n"
3064 	"t             Zoom into current Thread\n"
3065 	"V             Verbose (DSO names in callchains, etc)\n"
3066 	"/             Filter symbol by name\n"
3067 	"0-9           Sort by event n in group";
3068 	static const char top_help[] = HIST_BROWSER_HELP_COMMON
3069 	"P             Print histograms to perf.hist.N\n"
3070 	"t             Zoom into current Thread\n"
3071 	"V             Verbose (DSO names in callchains, etc)\n"
3072 	"z             Toggle zeroing of samples\n"
3073 	"f             Enable/Disable events\n"
3074 	"/             Filter symbol by name";
3075 
3076 	if (browser == NULL)
3077 		return -1;
3078 
3079 	/* reset abort key so that it can get Ctrl-C as a key */
3080 	SLang_reset_tty();
3081 	SLang_init_tty(0, 0, 0);
3082 	SLtty_set_suspend_state(true);
3083 
3084 	if (min_pcnt)
3085 		browser->min_pcnt = min_pcnt;
3086 	hist_browser__update_nr_entries(browser);
3087 
3088 	memset(options, 0, sizeof(options));
3089 	memset(actions, 0, sizeof(actions));
3090 
3091 	browser->pstack = pstack__new(3);
3092 	if (browser->pstack == NULL)
3093 		goto out;
3094 
3095 	ui_helpline__push(helpline);
3096 
3097 	if (symbol_conf.col_width_list_str)
3098 		perf_hpp__set_user_width(symbol_conf.col_width_list_str);
3099 
3100 	if (!is_report_browser(hbt))
3101 		browser->b.no_samples_msg = "Collecting samples...";
3102 
3103 	while (1) {
3104 		struct thread *thread = NULL;
3105 		struct map *map = NULL;
3106 		int choice;
3107 		int socked_id = -1;
3108 
3109 		key = 0; // reset key
3110 do_hotkey:		 // key came straight from options ui__popup_menu()
3111 		free_popup_options(options, MAX_OPTIONS);
3112 		free_popup_actions(actions, MAX_OPTIONS);
3113 		choice = nr_options = 0;
3114 		key = hist_browser__run(browser, helpline, warn_lost_event, key);
3115 
3116 		if (browser->he_selection != NULL) {
3117 			thread = hist_browser__selected_thread(browser);
3118 			map = browser->selection->map;
3119 			socked_id = browser->he_selection->socket;
3120 		}
3121 		switch (key) {
3122 		case K_TAB:
3123 		case K_UNTAB:
3124 			if (nr_events == 1)
3125 				continue;
3126 			/*
3127 			 * Exit the browser, let hists__browser_tree
3128 			 * go to the next or previous
3129 			 */
3130 			goto out_free_stack;
3131 		case '0' ... '9':
3132 			if (!symbol_conf.event_group ||
3133 			    evsel->core.nr_members < 2) {
3134 				snprintf(buf, sizeof(buf),
3135 					 "Sort by index only available with group events!");
3136 				helpline = buf;
3137 				continue;
3138 			}
3139 
3140 			if (key - '0' == symbol_conf.group_sort_idx)
3141 				continue;
3142 
3143 			symbol_conf.group_sort_idx = key - '0';
3144 
3145 			if (symbol_conf.group_sort_idx >= evsel->core.nr_members) {
3146 				snprintf(buf, sizeof(buf),
3147 					 "Max event group index to sort is %d (index from 0 to %d)",
3148 					 evsel->core.nr_members - 1,
3149 					 evsel->core.nr_members - 1);
3150 				helpline = buf;
3151 				continue;
3152 			}
3153 
3154 			key = K_RELOAD;
3155 			goto out_free_stack;
3156 		case 'a':
3157 			if (!hists__has(hists, sym)) {
3158 				ui_browser__warning(&browser->b, delay_secs * 2,
3159 			"Annotation is only available for symbolic views, "
3160 			"include \"sym*\" in --sort to use it.");
3161 				continue;
3162 			}
3163 
3164 			if (!browser->selection ||
3165 			    !browser->selection->map ||
3166 			    !map__dso(browser->selection->map) ||
3167 			    dso__annotate_warned(map__dso(browser->selection->map))) {
3168 				continue;
3169 			}
3170 
3171 			if (!browser->selection->sym) {
3172 				struct map_symbol source_ms;
3173 
3174 				if (!browser->he_selection)
3175 					continue;
3176 
3177 				memset(&source_ms, 0, sizeof(source_ms));
3178 
3179 				if (sort__mode == SORT_MODE__BRANCH) {
3180 					bi = browser->he_selection->branch_info;
3181 					if (!bi || !bi->to.ms.map)
3182 						continue;
3183 
3184 					source_ms.sym =
3185 						symbol__new_unresolved(
3186 							bi->to.al_addr,
3187 							bi->to.ms.map);
3188 					source_ms.thread = bi->to.ms.thread;
3189 					source_ms.map = bi->to.ms.map;
3190 				} else {
3191 					source_ms.sym =
3192 						symbol__new_unresolved(
3193 							browser->he_selection->ip,
3194 							browser->selection->map);
3195 					source_ms.thread = browser->selection->thread;
3196 					source_ms.map = browser->selection->map;
3197 				}
3198 
3199 				if (!source_ms.sym)
3200 					continue;
3201 
3202 				memset(&hotkey_act, 0, sizeof(hotkey_act));
3203 				map_symbol__copy(&hotkey_act.ms, &source_ms);
3204 				do_annotate(browser, &hotkey_act);
3205 				map_symbol__exit(&hotkey_act.ms);
3206 			} else {
3207 				if (symbol__annotation(browser->selection->sym)->src == NULL) {
3208 					ui_browser__warning(&browser->b, delay_secs * 2,
3209 						"No samples for the \"%s\" symbol.\n\n"
3210 						"Probably appeared just in a callchain",
3211 						browser->selection->sym->name);
3212 					continue;
3213 				}
3214 
3215 				memset(&hotkey_act, 0, sizeof(hotkey_act));
3216 				map_symbol__copy(&hotkey_act.ms, browser->selection);
3217 				do_annotate(browser, &hotkey_act);
3218 				map_symbol__exit(&hotkey_act.ms);
3219 			}
3220 			continue;
3221 		case 'P':
3222 			hist_browser__dump(browser);
3223 			continue;
3224 		case 'd':
3225 			memset(&hotkey_act, 0, sizeof(hotkey_act));
3226 			hotkey_act.ms.map = map__get(map);
3227 			do_zoom_dso(browser, &hotkey_act);
3228 			map_symbol__exit(&hotkey_act.ms);
3229 			continue;
3230 		case 'k':
3231 			if (browser->selection != NULL)
3232 				hists_browser__zoom_map(browser,
3233 					maps__machine(thread__maps(browser->selection->thread)
3234 						     )->vmlinux_map);
3235 			continue;
3236 		case 'V':
3237 			verbose = (verbose + 1) % 4;
3238 			browser->show_dso = verbose > 0;
3239 			ui_helpline__fpush("Verbosity level set to %d\n",
3240 					   verbose);
3241 			continue;
3242 		case 't':
3243 			memset(&hotkey_act, 0, sizeof(hotkey_act));
3244 			hotkey_act.ms.thread = thread__get(thread);
3245 			do_zoom_thread(browser, &hotkey_act);
3246 			map_symbol__exit(&hotkey_act.ms);
3247 			continue;
3248 		case 'S':
3249 			memset(&hotkey_act, 0, sizeof(hotkey_act));
3250 			hotkey_act.socket = socked_id;
3251 			do_zoom_socket(browser, &hotkey_act);
3252 			map_symbol__exit(&hotkey_act.ms);
3253 			continue;
3254 		case '/':
3255 			if (ui_browser__input_window("Symbol to show",
3256 					"Please enter the name of symbol you want to see.\n"
3257 					"To remove the filter later, press / + ENTER.",
3258 					buf, "ENTER: OK, ESC: Cancel",
3259 					delay_secs * 2) == K_ENTER) {
3260 				char *new_filter = *buf ? strdup(buf) : NULL;
3261 
3262 				zfree(&hists->symbol_filter_str);
3263 				hists->symbol_filter_str = new_filter;
3264 				hists__filter_by_symbol(hists);
3265 				hist_browser__reset(browser);
3266 			}
3267 			continue;
3268 		case 'r':
3269 			if (is_report_browser(hbt)) {
3270 				memset(&hotkey_act, 0, sizeof(hotkey_act));
3271 				hotkey_act.ms.thread = NULL;
3272 				hotkey_act.ms.sym = NULL;
3273 				do_run_script(browser, &hotkey_act);
3274 				map_symbol__exit(&hotkey_act.ms);
3275 			}
3276 			continue;
3277 		case 's':
3278 			if (is_report_browser(hbt)) {
3279 				key = do_switch_data(browser, actions);
3280 				if (key == K_SWITCH_INPUT_DATA)
3281 					goto out_free_stack;
3282 			}
3283 			continue;
3284 		case 'i':
3285 			/* env->arch is NULL for live-mode (i.e. perf top) */
3286 			if (env->arch)
3287 				tui__header_window(evsel__session(evsel));
3288 			continue;
3289 		case 'F':
3290 			symbol_conf.filter_relative ^= 1;
3291 			continue;
3292 		case 'z':
3293 			if (!is_report_browser(hbt)) {
3294 				struct perf_top *top = hbt->arg;
3295 
3296 				top->zero = !top->zero;
3297 			}
3298 			continue;
3299 		case 'L':
3300 			if (ui_browser__input_window("Percent Limit",
3301 					"Please enter the value you want to hide entries under that percent.",
3302 					buf, "ENTER: OK, ESC: Cancel",
3303 					delay_secs * 2) == K_ENTER) {
3304 				char *end;
3305 				double new_percent = strtod(buf, &end);
3306 
3307 				if (new_percent < 0 || new_percent > 100) {
3308 					ui_browser__warning(&browser->b, delay_secs * 2,
3309 						"Invalid percent: %.2f", new_percent);
3310 					continue;
3311 				}
3312 
3313 				hist_browser__update_percent_limit(browser, new_percent);
3314 				hist_browser__reset(browser);
3315 			}
3316 			continue;
3317 		case K_F1:
3318 		case 'h':
3319 		case '?':
3320 			ui_browser__help_window(&browser->b,
3321 				is_report_browser(hbt) ? report_help : top_help);
3322 			continue;
3323 		case K_ENTER:
3324 		case K_RIGHT:
3325 		case 'm':
3326 			/* menu */
3327 			break;
3328 		case K_ESC:
3329 		case K_LEFT: {
3330 			const void *top;
3331 
3332 			if (pstack__empty(browser->pstack)) {
3333 				/*
3334 				 * Go back to the perf_evsel_menu__run or other user
3335 				 */
3336 				if (left_exits)
3337 					goto out_free_stack;
3338 
3339 				if (key == K_ESC &&
3340 				    ui_browser__dialog_yesno(&browser->b,
3341 							     "Do you really want to exit?"))
3342 					goto out_free_stack;
3343 
3344 				continue;
3345 			}
3346 			memset(&hotkey_act, 0, sizeof(hotkey_act));
3347 			top = pstack__peek(browser->pstack);
3348 			if (top == &browser->hists->dso_filter) {
3349 				hotkey_act.ms.map = map__get(map);
3350 				do_zoom_dso(browser, &hotkey_act);
3351 			} else if (top == &browser->hists->thread_filter) {
3352 				hotkey_act.ms.thread = thread__get(thread);
3353 				do_zoom_thread(browser, &hotkey_act);
3354 			} else if (top == &browser->hists->socket_filter) {
3355 				hotkey_act.socket = socked_id;
3356 				do_zoom_socket(browser, &hotkey_act);
3357 			}
3358 			map_symbol__exit(&hotkey_act.ms);
3359 			continue;
3360 		}
3361 		case 'q':
3362 		case CTRL('c'):
3363 			goto out_free_stack;
3364 		case 'f':
3365 			if (!is_report_browser(hbt)) {
3366 				struct perf_top *top = hbt->arg;
3367 
3368 				evlist__toggle_enable(top->evlist);
3369 				/*
3370 				 * No need to refresh, resort/decay histogram
3371 				 * entries if we are not collecting samples:
3372 				 */
3373 				if (evlist__enabled(top->evlist)) {
3374 					helpline = "Press 'f' to disable the events or 'h' to see other hotkeys";
3375 					hbt->refresh = delay_secs;
3376 				} else {
3377 					helpline = "Press 'f' again to re-enable the events";
3378 					hbt->refresh = 0;
3379 				}
3380 				continue;
3381 			}
3382 			/* Fall thru */
3383 		default:
3384 			helpline = "Press '?' for help on key bindings";
3385 			ui_browser__warn_unhandled_hotkey(&browser->b, key, delay_secs,
3386 							  ", use 'h'/'?'/F1 to see actions");
3387 			continue;
3388 		}
3389 
3390 		if (!hists__has(hists, sym) || browser->selection == NULL)
3391 			goto skip_annotation;
3392 
3393 		if (sort__mode == SORT_MODE__BRANCH) {
3394 
3395 			if (browser->he_selection)
3396 				bi = browser->he_selection->branch_info;
3397 
3398 			if (bi == NULL)
3399 				goto skip_annotation;
3400 
3401 			nr_options += add_annotate_opt(&actions[nr_options],
3402 						       &options[nr_options],
3403 						       &bi->from.ms,
3404 						       bi->from.al_addr);
3405 			if (bi->to.ms.sym != bi->from.ms.sym)
3406 				nr_options += add_annotate_opt(&actions[nr_options],
3407 							&options[nr_options],
3408 							&bi->to.ms,
3409 							bi->to.al_addr);
3410 		} else if (browser->he_selection) {
3411 			nr_options += add_annotate_opt(&actions[nr_options],
3412 						       &options[nr_options],
3413 						       browser->selection,
3414 						       browser->he_selection->ip);
3415 		}
3416 skip_annotation:
3417 		nr_options += add_annotate_type_opt(&actions[nr_options],
3418 						    &options[nr_options],
3419 						    browser->he_selection);
3420 		nr_options += add_thread_opt(browser, &actions[nr_options],
3421 					     &options[nr_options], thread);
3422 		nr_options += add_dso_opt(browser, &actions[nr_options],
3423 					  &options[nr_options], map);
3424 		nr_options += add_callchain_toggle_opt(browser, &actions[nr_options], &options[nr_options]);
3425 		nr_options += add_map_opt(browser, &actions[nr_options],
3426 					  &options[nr_options],
3427 					  browser->selection ?
3428 						browser->selection->map : NULL);
3429 		nr_options += add_socket_opt(browser, &actions[nr_options],
3430 					     &options[nr_options],
3431 					     socked_id);
3432 		/* perf script support */
3433 		if (!is_report_browser(hbt))
3434 			goto skip_scripting;
3435 
3436 		if (browser->he_selection) {
3437 			if (hists__has(hists, thread) && thread) {
3438 				nr_options += add_script_opt(browser,
3439 							     &actions[nr_options],
3440 							     &options[nr_options],
3441 							     thread, NULL);
3442 			}
3443 			/*
3444 			 * Note that browser->selection != NULL
3445 			 * when browser->he_selection is not NULL,
3446 			 * so we don't need to check browser->selection
3447 			 * before fetching browser->selection->sym like what
3448 			 * we do before fetching browser->selection->map.
3449 			 *
3450 			 * See hist_browser__show_entry.
3451 			 */
3452 			if (hists__has(hists, sym) && browser->selection->sym) {
3453 				nr_options += add_script_opt(browser,
3454 							     &actions[nr_options],
3455 							     &options[nr_options],
3456 							     NULL, browser->selection->sym);
3457 			}
3458 		}
3459 		nr_options += add_script_opt(browser, &actions[nr_options],
3460 					     &options[nr_options], NULL, NULL);
3461 		nr_options += add_res_sample_opt(browser, &actions[nr_options],
3462 						 &options[nr_options],
3463 						 hist_browser__selected_res_sample(browser),
3464 						 A_NORMAL);
3465 		nr_options += add_res_sample_opt(browser, &actions[nr_options],
3466 						 &options[nr_options],
3467 						 hist_browser__selected_res_sample(browser),
3468 						 A_ASM);
3469 		nr_options += add_res_sample_opt(browser, &actions[nr_options],
3470 						 &options[nr_options],
3471 						 hist_browser__selected_res_sample(browser),
3472 						 A_SOURCE);
3473 		nr_options += add_switch_opt(browser, &actions[nr_options],
3474 					     &options[nr_options]);
3475 skip_scripting:
3476 		nr_options += add_exit_opt(browser, &actions[nr_options],
3477 					   &options[nr_options]);
3478 
3479 		do {
3480 			struct popup_action *act;
3481 
3482 			choice = ui__popup_menu(nr_options, options, &key);
3483 			if (choice == -1)
3484 				break;
3485 
3486 			if (choice == nr_options)
3487 				goto do_hotkey;
3488 
3489 			act = &actions[choice];
3490 			key = act->fn(browser, act);
3491 		} while (key == 1);
3492 
3493 		if (key == K_SWITCH_INPUT_DATA)
3494 			break;
3495 
3496 		free_popup_options(options, MAX_OPTIONS);
3497 		free_popup_actions(actions, MAX_OPTIONS);
3498 	}
3499 out_free_stack:
3500 	pstack__delete(browser->pstack);
3501 	free_popup_actions(actions, MAX_OPTIONS);
3502 	thread__zput(hists->thread_filter);
3503 	dso__put((struct dso *)hists->dso_filter);
3504 	hists->dso_filter = NULL;
3505 	perf_hpp__set_elide(HISTC_DSO, false);
3506 	perf_hpp__set_elide(HISTC_THREAD, false);
3507 	hists__filter_by_dso(hists);
3508 	hists__filter_by_thread(hists);
3509 out:
3510 	hist_browser__delete(browser);
3511 	free_popup_options(options, MAX_OPTIONS);
3512 	return key;
3513 }
3514 
3515 struct evsel_menu {
3516 	struct ui_browser b;
3517 	struct evsel *selection;
3518 	bool lost_events, lost_events_warned;
3519 	float min_pcnt;
3520 	struct perf_env *env;
3521 };
3522 
3523 static void perf_evsel_menu__write(struct ui_browser *browser,
3524 				   void *entry, int row)
3525 {
3526 	struct evsel_menu *menu = container_of(browser,
3527 						    struct evsel_menu, b);
3528 	struct evsel *evsel = list_entry(entry, struct evsel, core.node);
3529 	struct hists *hists = evsel__hists(evsel);
3530 	bool current_entry = ui_browser__is_current_entry(browser, row);
3531 	unsigned long nr_events = hists->stats.nr_samples;
3532 	const char *ev_name = evsel__name(evsel);
3533 	char bf[256], unit;
3534 	const char *warn = " ";
3535 	size_t printed;
3536 
3537 	ui_browser__set_color(browser, current_entry ? HE_COLORSET_SELECTED :
3538 						       HE_COLORSET_NORMAL);
3539 
3540 	if (evsel__is_group_event(evsel)) {
3541 		struct evsel *pos;
3542 
3543 		ev_name = evsel__group_name(evsel);
3544 
3545 		for_each_group_member(pos, evsel) {
3546 			struct hists *pos_hists = evsel__hists(pos);
3547 			nr_events += pos_hists->stats.nr_samples;
3548 		}
3549 	}
3550 
3551 	nr_events = convert_unit(nr_events, &unit);
3552 	printed = scnprintf(bf, sizeof(bf), "%lu%c%s%s", nr_events,
3553 			   unit, unit == ' ' ? "" : " ", ev_name);
3554 	ui_browser__printf(browser, "%s", bf);
3555 
3556 	nr_events = evlist__stats(evsel->evlist)->nr_events[PERF_RECORD_LOST];
3557 	if (nr_events != 0) {
3558 		menu->lost_events = true;
3559 		if (!current_entry)
3560 			ui_browser__set_color(browser, HE_COLORSET_TOP);
3561 		nr_events = convert_unit(nr_events, &unit);
3562 		printed += scnprintf(bf, sizeof(bf), ": %ld%c%schunks LOST!",
3563 				     nr_events, unit, unit == ' ' ? "" : " ");
3564 		warn = bf;
3565 	}
3566 
3567 	ui_browser__write_nstring(browser, warn, browser->width - printed);
3568 
3569 	if (current_entry)
3570 		menu->selection = evsel;
3571 }
3572 
3573 static int perf_evsel_menu__run(struct evsel_menu *menu,
3574 				int nr_events, const char *help,
3575 				struct hist_browser_timer *hbt,
3576 				bool warn_lost_event)
3577 {
3578 	struct evlist *evlist = menu->b.priv;
3579 	struct evsel *pos;
3580 	const char *title = "Available samples";
3581 	int delay_secs = hbt ? hbt->refresh : 0;
3582 	int key;
3583 	const char *help_text = "ESC: exit, ENTER|->: Browse histograms";
3584 
3585 	if (!symbol_conf.hybrid_merge && evlist__can_merge_hybrid(evlist, menu->env))
3586 		help_text = "ESC: exit, ENTER|->: Browse. Try --hybrid-merge to combine events.";
3587 
3588 	if (ui_browser__show(&menu->b, title, help_text) < 0)
3589 		return -1;
3590 
3591 	while (1) {
3592 		key = ui_browser__run(&menu->b, delay_secs);
3593 
3594 		switch (key) {
3595 		case K_TIMER:
3596 			if (hbt)
3597 				hbt->timer(hbt->arg);
3598 
3599 			if (!menu->lost_events_warned &&
3600 			    menu->lost_events &&
3601 			    warn_lost_event) {
3602 				ui_browser__warn_lost_events(&menu->b);
3603 				menu->lost_events_warned = true;
3604 			}
3605 			continue;
3606 		case K_RIGHT:
3607 		case K_ENTER:
3608 			if (!menu->selection)
3609 				continue;
3610 			pos = menu->selection;
3611 browse_hists:
3612 			evlist__set_selected(evlist, pos);
3613 			/*
3614 			 * Give the calling tool a chance to populate the non
3615 			 * default evsel resorted hists tree.
3616 			 */
3617 			if (hbt)
3618 				hbt->timer(hbt->arg);
3619 			key = evsel__hists_browse(pos, nr_events, help, true, hbt,
3620 						  menu->min_pcnt, menu->env,
3621 						  warn_lost_event);
3622 			ui_browser__show_title(&menu->b, title);
3623 			switch (key) {
3624 			case K_TAB:
3625 				if (pos->core.node.next == &evlist__core(evlist)->entries)
3626 					pos = evlist__first(evlist);
3627 				else
3628 					pos = evsel__next(pos);
3629 				goto browse_hists;
3630 			case K_UNTAB:
3631 				if (pos->core.node.prev == &evlist__core(evlist)->entries)
3632 					pos = evlist__last(evlist);
3633 				else
3634 					pos = evsel__prev(pos);
3635 				goto browse_hists;
3636 			case K_SWITCH_INPUT_DATA:
3637 			case K_RELOAD:
3638 			case 'q':
3639 			case CTRL('c'):
3640 				goto out;
3641 			case K_ESC:
3642 			default:
3643 				continue;
3644 			}
3645 		case K_LEFT:
3646 			continue;
3647 		case K_ESC:
3648 			if (!ui_browser__dialog_yesno(&menu->b,
3649 					       "Do you really want to exit?"))
3650 				continue;
3651 			/* Fall thru */
3652 		case 'q':
3653 		case CTRL('c'):
3654 			goto out;
3655 		default:
3656 			ui_browser__warn_unhandled_hotkey(&menu->b, key, delay_secs, NULL);
3657 			continue;
3658 		}
3659 	}
3660 
3661 out:
3662 	ui_browser__hide(&menu->b);
3663 	return key;
3664 }
3665 
3666 static bool filter_group_entries(struct ui_browser *browser __maybe_unused,
3667 				 void *entry)
3668 {
3669 	struct evsel *evsel = list_entry(entry, struct evsel, core.node);
3670 
3671 	if (symbol_conf.event_group && !evsel__is_group_leader(evsel))
3672 		return true;
3673 
3674 	return false;
3675 }
3676 
3677 static int __evlist__tui_browse_hists(struct evlist *evlist, int nr_entries, const char *help,
3678 				      struct hist_browser_timer *hbt, float min_pcnt, struct perf_env *env,
3679 				      bool warn_lost_event)
3680 {
3681 	struct evsel *pos;
3682 	struct evsel_menu menu = {
3683 		.b = {
3684 			.entries    = &evlist__core(evlist)->entries,
3685 			.refresh    = ui_browser__list_head_refresh,
3686 			.seek	    = ui_browser__list_head_seek,
3687 			.write	    = perf_evsel_menu__write,
3688 			.filter	    = filter_group_entries,
3689 			.nr_entries = nr_entries,
3690 			.priv	    = evlist,
3691 		},
3692 		.min_pcnt = min_pcnt,
3693 		.env = env,
3694 	};
3695 
3696 	ui_helpline__push("Press ESC to exit");
3697 
3698 	evlist__for_each_entry(evlist, pos) {
3699 		const char *ev_name = evsel__name(pos);
3700 		size_t line_len = strlen(ev_name) + 7;
3701 
3702 		if (menu.b.width < line_len)
3703 			menu.b.width = line_len;
3704 	}
3705 
3706 	return perf_evsel_menu__run(&menu, nr_entries, help,
3707 				    hbt, warn_lost_event);
3708 }
3709 
3710 static bool evlist__single_entry(struct evlist *evlist)
3711 {
3712 	int nr_entries = evlist__nr_entries(evlist);
3713 
3714 	if (nr_entries == 1)
3715 	       return true;
3716 
3717 	if (nr_entries == 2) {
3718 		struct evsel *last = evlist__last(evlist);
3719 
3720 		if (evsel__is_dummy_event(last))
3721 			return true;
3722 	}
3723 
3724 	return false;
3725 }
3726 
3727 int evlist__tui_browse_hists(struct evlist *evlist, const char *help, struct hist_browser_timer *hbt,
3728 			     float min_pcnt, struct perf_env *env, bool warn_lost_event)
3729 {
3730 	int nr_entries = evlist__nr_entries(evlist);
3731 
3732 	if (evlist__single_entry(evlist)) {
3733 single_entry: {
3734 		struct evsel *first = evlist__first(evlist);
3735 
3736 		return evsel__hists_browse(first, nr_entries, help, false, hbt, min_pcnt,
3737 					   env, warn_lost_event);
3738 	}
3739 	}
3740 
3741 	if (symbol_conf.event_group) {
3742 		struct evsel *pos;
3743 
3744 		nr_entries = 0;
3745 		evlist__for_each_entry(evlist, pos) {
3746 			if (evsel__is_group_leader(pos))
3747 				nr_entries++;
3748 		}
3749 
3750 		if (nr_entries == 1)
3751 			goto single_entry;
3752 	}
3753 
3754 	return __evlist__tui_browse_hists(evlist, nr_entries, help, hbt, min_pcnt, env,
3755 					  warn_lost_event);
3756 }
3757 
3758 static int block_hists_browser__title(struct hist_browser *browser, char *bf,
3759 				      size_t size)
3760 {
3761 	struct hists *hists = evsel__hists(browser->block_evsel);
3762 	const char *evname = evsel__name(browser->block_evsel);
3763 	unsigned long nr_samples = hists->stats.nr_samples;
3764 	int ret;
3765 
3766 	ret = scnprintf(bf, size, "# Samples: %lu", nr_samples);
3767 	if (evname)
3768 		scnprintf(bf + ret, size -  ret, " of event '%s'", evname);
3769 
3770 	return 0;
3771 }
3772 
3773 int block_hists_tui_browse(struct block_hist *bh, struct evsel *evsel,
3774 			   float min_percent, struct perf_env *env)
3775 {
3776 	struct hists *hists = &bh->block_hists;
3777 	struct hist_browser *browser;
3778 	int key = -1;
3779 	struct popup_action action;
3780 	char *br_cntr_text = NULL;
3781 	static const char help[] =
3782 	" q/ESC         Quit \n"
3783 	" B             Branch counter abbr list (Optional)\n";
3784 
3785 	browser = hist_browser__new(hists);
3786 	if (!browser)
3787 		return -1;
3788 
3789 	browser->block_evsel = evsel;
3790 	browser->title = block_hists_browser__title;
3791 	browser->min_pcnt = min_percent;
3792 	browser->env = env;
3793 
3794 	/* reset abort key so that it can get Ctrl-C as a key */
3795 	SLang_reset_tty();
3796 	SLang_init_tty(0, 0, 0);
3797 	SLtty_set_suspend_state(true);
3798 
3799 	memset(&action, 0, sizeof(action));
3800 
3801 	if (!annotation_br_cntr_abbr_list(&br_cntr_text, evsel, false))
3802 		annotate_opts.show_br_cntr = true;
3803 
3804 	while (1) {
3805 		key = hist_browser__run(browser, "? - help", true, 0);
3806 
3807 		switch (key) {
3808 		case 'q':
3809 		case K_ESC:
3810 			goto out;
3811 		case '?':
3812 			ui_browser__help_window(&browser->b, help);
3813 			break;
3814 		case 'a':
3815 		case K_ENTER:
3816 			if (!browser->selection ||
3817 			    !browser->selection->sym) {
3818 				continue;
3819 			}
3820 
3821 			action.ms.map = browser->selection->map;
3822 			action.ms.sym = browser->selection->sym;
3823 			do_annotate(browser, &action);
3824 			continue;
3825 		case 'B':
3826 			if (br_cntr_text) {
3827 				ui__question_window("Branch counter abbr list",
3828 						    br_cntr_text, "Press any key...", 0);
3829 			} else {
3830 				ui__question_window("Branch counter abbr list",
3831 						    "\n The branch counter is not available.\n",
3832 						    "Press any key...", 0);
3833 			}
3834 			continue;
3835 		default:
3836 			ui_browser__warn_unhandled_hotkey(&browser->b, key, 0,
3837 							  ", use '?' to see actions");
3838 			continue;
3839 		}
3840 	}
3841 
3842 out:
3843 	hist_browser__delete(browser);
3844 	free(br_cntr_text);
3845 	return 0;
3846 }
3847