xref: /openbmc/linux/tools/perf/builtin-report.c (revision 0e6774ec)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * builtin-report.c
4  *
5  * Builtin report command: Analyze the perf.data input file,
6  * look up and read DSOs and symbol information and display
7  * a histogram of results, along various sorting keys.
8  */
9 #include "builtin.h"
10 
11 #include "util/config.h"
12 
13 #include "util/annotate.h"
14 #include "util/color.h"
15 #include "util/dso.h"
16 #include <linux/list.h>
17 #include <linux/rbtree.h>
18 #include <linux/err.h>
19 #include <linux/zalloc.h>
20 #include "util/map.h"
21 #include "util/symbol.h"
22 #include "util/map_symbol.h"
23 #include "util/mem-events.h"
24 #include "util/branch.h"
25 #include "util/callchain.h"
26 #include "util/values.h"
27 
28 #include "perf.h"
29 #include "util/debug.h"
30 #include "util/evlist.h"
31 #include "util/evsel.h"
32 #include "util/evswitch.h"
33 #include "util/header.h"
34 #include "util/session.h"
35 #include "util/srcline.h"
36 #include "util/tool.h"
37 
38 #include <subcmd/parse-options.h>
39 #include <subcmd/exec-cmd.h>
40 #include "util/parse-events.h"
41 
42 #include "util/thread.h"
43 #include "util/sort.h"
44 #include "util/hist.h"
45 #include "util/data.h"
46 #include "arch/common.h"
47 #include "util/time-utils.h"
48 #include "util/auxtrace.h"
49 #include "util/units.h"
50 #include "util/util.h" // perf_tip()
51 #include "ui/ui.h"
52 #include "ui/progress.h"
53 #include "util/block-info.h"
54 
55 #include <dlfcn.h>
56 #include <errno.h>
57 #include <inttypes.h>
58 #include <regex.h>
59 #include <linux/ctype.h>
60 #include <signal.h>
61 #include <linux/bitmap.h>
62 #include <linux/string.h>
63 #include <linux/stringify.h>
64 #include <linux/time64.h>
65 #include <sys/types.h>
66 #include <sys/stat.h>
67 #include <unistd.h>
68 #include <linux/mman.h>
69 
70 #ifdef HAVE_LIBTRACEEVENT
71 #include <traceevent/event-parse.h>
72 #endif
73 
74 struct report {
75 	struct perf_tool	tool;
76 	struct perf_session	*session;
77 	struct evswitch		evswitch;
78 #ifdef HAVE_SLANG_SUPPORT
79 	bool			use_tui;
80 #endif
81 #ifdef HAVE_GTK2_SUPPORT
82 	bool			use_gtk;
83 #endif
84 	bool			use_stdio;
85 	bool			show_full_info;
86 	bool			show_threads;
87 	bool			inverted_callchain;
88 	bool			mem_mode;
89 	bool			stats_mode;
90 	bool			tasks_mode;
91 	bool			mmaps_mode;
92 	bool			header;
93 	bool			header_only;
94 	bool			nonany_branch_mode;
95 	bool			group_set;
96 	bool			stitch_lbr;
97 	bool			disable_order;
98 	bool			skip_empty;
99 	int			max_stack;
100 	struct perf_read_values	show_threads_values;
101 	const char		*pretty_printing_style;
102 	const char		*cpu_list;
103 	const char		*symbol_filter_str;
104 	const char		*time_str;
105 	struct perf_time_interval *ptime_range;
106 	int			range_size;
107 	int			range_num;
108 	float			min_percent;
109 	u64			nr_entries;
110 	u64			queue_size;
111 	u64			total_cycles;
112 	int			socket_filter;
113 	DECLARE_BITMAP(cpu_bitmap, MAX_NR_CPUS);
114 	struct branch_type_stat	brtype_stat;
115 	bool			symbol_ipc;
116 	bool			total_cycles_mode;
117 	struct block_report	*block_reports;
118 	int			nr_block_reports;
119 };
120 
121 static int report__config(const char *var, const char *value, void *cb)
122 {
123 	struct report *rep = cb;
124 
125 	if (!strcmp(var, "report.group")) {
126 		symbol_conf.event_group = perf_config_bool(var, value);
127 		return 0;
128 	}
129 	if (!strcmp(var, "report.percent-limit")) {
130 		double pcnt = strtof(value, NULL);
131 
132 		rep->min_percent = pcnt;
133 		callchain_param.min_percent = pcnt;
134 		return 0;
135 	}
136 	if (!strcmp(var, "report.children")) {
137 		symbol_conf.cumulate_callchain = perf_config_bool(var, value);
138 		return 0;
139 	}
140 	if (!strcmp(var, "report.queue-size"))
141 		return perf_config_u64(&rep->queue_size, var, value);
142 
143 	if (!strcmp(var, "report.sort_order")) {
144 		default_sort_order = strdup(value);
145 		if (!default_sort_order) {
146 			pr_err("Not enough memory for report.sort_order\n");
147 			return -1;
148 		}
149 		return 0;
150 	}
151 
152 	if (!strcmp(var, "report.skip-empty")) {
153 		rep->skip_empty = perf_config_bool(var, value);
154 		return 0;
155 	}
156 
157 	pr_debug("%s variable unknown, ignoring...", var);
158 	return 0;
159 }
160 
161 static int hist_iter__report_callback(struct hist_entry_iter *iter,
162 				      struct addr_location *al, bool single,
163 				      void *arg)
164 {
165 	int err = 0;
166 	struct report *rep = arg;
167 	struct hist_entry *he = iter->he;
168 	struct evsel *evsel = iter->evsel;
169 	struct perf_sample *sample = iter->sample;
170 	struct mem_info *mi;
171 	struct branch_info *bi;
172 
173 	if (!ui__has_annotation() && !rep->symbol_ipc)
174 		return 0;
175 
176 	if (sort__mode == SORT_MODE__BRANCH) {
177 		bi = he->branch_info;
178 		err = addr_map_symbol__inc_samples(&bi->from, sample, evsel);
179 		if (err)
180 			goto out;
181 
182 		err = addr_map_symbol__inc_samples(&bi->to, sample, evsel);
183 
184 	} else if (rep->mem_mode) {
185 		mi = he->mem_info;
186 		err = addr_map_symbol__inc_samples(&mi->daddr, sample, evsel);
187 		if (err)
188 			goto out;
189 
190 		err = hist_entry__inc_addr_samples(he, sample, evsel, al->addr);
191 
192 	} else if (symbol_conf.cumulate_callchain) {
193 		if (single)
194 			err = hist_entry__inc_addr_samples(he, sample, evsel, al->addr);
195 	} else {
196 		err = hist_entry__inc_addr_samples(he, sample, evsel, al->addr);
197 	}
198 
199 out:
200 	return err;
201 }
202 
203 static int hist_iter__branch_callback(struct hist_entry_iter *iter,
204 				      struct addr_location *al __maybe_unused,
205 				      bool single __maybe_unused,
206 				      void *arg)
207 {
208 	struct hist_entry *he = iter->he;
209 	struct report *rep = arg;
210 	struct branch_info *bi = he->branch_info;
211 	struct perf_sample *sample = iter->sample;
212 	struct evsel *evsel = iter->evsel;
213 	int err;
214 
215 	branch_type_count(&rep->brtype_stat, &bi->flags,
216 			  bi->from.addr, bi->to.addr);
217 
218 	if (!ui__has_annotation() && !rep->symbol_ipc)
219 		return 0;
220 
221 	err = addr_map_symbol__inc_samples(&bi->from, sample, evsel);
222 	if (err)
223 		goto out;
224 
225 	err = addr_map_symbol__inc_samples(&bi->to, sample, evsel);
226 
227 out:
228 	return err;
229 }
230 
231 static void setup_forced_leader(struct report *report,
232 				struct evlist *evlist)
233 {
234 	if (report->group_set)
235 		evlist__force_leader(evlist);
236 }
237 
238 static int process_feature_event(struct perf_session *session,
239 				 union perf_event *event)
240 {
241 	struct report *rep = container_of(session->tool, struct report, tool);
242 
243 	if (event->feat.feat_id < HEADER_LAST_FEATURE)
244 		return perf_event__process_feature(session, event);
245 
246 	if (event->feat.feat_id != HEADER_LAST_FEATURE) {
247 		pr_err("failed: wrong feature ID: %" PRI_lu64 "\n",
248 		       event->feat.feat_id);
249 		return -1;
250 	} else if (rep->header_only) {
251 		session_done = 1;
252 	}
253 
254 	/*
255 	 * (feat_id = HEADER_LAST_FEATURE) is the end marker which
256 	 * means all features are received, now we can force the
257 	 * group if needed.
258 	 */
259 	setup_forced_leader(rep, session->evlist);
260 	return 0;
261 }
262 
263 static int process_sample_event(struct perf_tool *tool,
264 				union perf_event *event,
265 				struct perf_sample *sample,
266 				struct evsel *evsel,
267 				struct machine *machine)
268 {
269 	struct report *rep = container_of(tool, struct report, tool);
270 	struct addr_location al;
271 	struct hist_entry_iter iter = {
272 		.evsel 			= evsel,
273 		.sample 		= sample,
274 		.hide_unresolved 	= symbol_conf.hide_unresolved,
275 		.add_entry_cb 		= hist_iter__report_callback,
276 	};
277 	int ret = 0;
278 
279 	if (perf_time__ranges_skip_sample(rep->ptime_range, rep->range_num,
280 					  sample->time)) {
281 		return 0;
282 	}
283 
284 	if (evswitch__discard(&rep->evswitch, evsel))
285 		return 0;
286 
287 	addr_location__init(&al);
288 	if (machine__resolve(machine, &al, sample) < 0) {
289 		pr_debug("problem processing %d event, skipping it.\n",
290 			 event->header.type);
291 		ret = -1;
292 		goto out_put;
293 	}
294 
295 	if (rep->stitch_lbr)
296 		thread__set_lbr_stitch_enable(al.thread, true);
297 
298 	if (symbol_conf.hide_unresolved && al.sym == NULL)
299 		goto out_put;
300 
301 	if (rep->cpu_list && !test_bit(sample->cpu, rep->cpu_bitmap))
302 		goto out_put;
303 
304 	if (sort__mode == SORT_MODE__BRANCH) {
305 		/*
306 		 * A non-synthesized event might not have a branch stack if
307 		 * branch stacks have been synthesized (using itrace options).
308 		 */
309 		if (!sample->branch_stack)
310 			goto out_put;
311 
312 		iter.add_entry_cb = hist_iter__branch_callback;
313 		iter.ops = &hist_iter_branch;
314 	} else if (rep->mem_mode) {
315 		iter.ops = &hist_iter_mem;
316 	} else if (symbol_conf.cumulate_callchain) {
317 		iter.ops = &hist_iter_cumulative;
318 	} else {
319 		iter.ops = &hist_iter_normal;
320 	}
321 
322 	if (al.map != NULL)
323 		map__dso(al.map)->hit = 1;
324 
325 	if (ui__has_annotation() || rep->symbol_ipc || rep->total_cycles_mode) {
326 		hist__account_cycles(sample->branch_stack, &al, sample,
327 				     rep->nonany_branch_mode,
328 				     &rep->total_cycles);
329 	}
330 
331 	ret = hist_entry_iter__add(&iter, &al, rep->max_stack, rep);
332 	if (ret < 0)
333 		pr_debug("problem adding hist entry, skipping event\n");
334 out_put:
335 	addr_location__exit(&al);
336 	return ret;
337 }
338 
339 static int process_read_event(struct perf_tool *tool,
340 			      union perf_event *event,
341 			      struct perf_sample *sample __maybe_unused,
342 			      struct evsel *evsel,
343 			      struct machine *machine __maybe_unused)
344 {
345 	struct report *rep = container_of(tool, struct report, tool);
346 
347 	if (rep->show_threads) {
348 		const char *name = evsel__name(evsel);
349 		int err = perf_read_values_add_value(&rep->show_threads_values,
350 					   event->read.pid, event->read.tid,
351 					   evsel->core.idx,
352 					   name,
353 					   event->read.value);
354 
355 		if (err)
356 			return err;
357 	}
358 
359 	return 0;
360 }
361 
362 /* For pipe mode, sample_type is not currently set */
363 static int report__setup_sample_type(struct report *rep)
364 {
365 	struct perf_session *session = rep->session;
366 	u64 sample_type = evlist__combined_sample_type(session->evlist);
367 	bool is_pipe = perf_data__is_pipe(session->data);
368 	struct evsel *evsel;
369 
370 	if (session->itrace_synth_opts->callchain ||
371 	    session->itrace_synth_opts->add_callchain ||
372 	    (!is_pipe &&
373 	     perf_header__has_feat(&session->header, HEADER_AUXTRACE) &&
374 	     !session->itrace_synth_opts->set))
375 		sample_type |= PERF_SAMPLE_CALLCHAIN;
376 
377 	if (session->itrace_synth_opts->last_branch ||
378 	    session->itrace_synth_opts->add_last_branch)
379 		sample_type |= PERF_SAMPLE_BRANCH_STACK;
380 
381 	if (!is_pipe && !(sample_type & PERF_SAMPLE_CALLCHAIN)) {
382 		if (perf_hpp_list.parent) {
383 			ui__error("Selected --sort parent, but no "
384 				    "callchain data. Did you call "
385 				    "'perf record' without -g?\n");
386 			return -EINVAL;
387 		}
388 		if (symbol_conf.use_callchain &&
389 			!symbol_conf.show_branchflag_count) {
390 			ui__error("Selected -g or --branch-history.\n"
391 				  "But no callchain or branch data.\n"
392 				  "Did you call 'perf record' without -g or -b?\n");
393 			return -1;
394 		}
395 	} else if (!callchain_param.enabled &&
396 		   callchain_param.mode != CHAIN_NONE &&
397 		   !symbol_conf.use_callchain) {
398 			symbol_conf.use_callchain = true;
399 			if (callchain_register_param(&callchain_param) < 0) {
400 				ui__error("Can't register callchain params.\n");
401 				return -EINVAL;
402 			}
403 	}
404 
405 	if (symbol_conf.cumulate_callchain) {
406 		/* Silently ignore if callchain is missing */
407 		if (!(sample_type & PERF_SAMPLE_CALLCHAIN)) {
408 			symbol_conf.cumulate_callchain = false;
409 			perf_hpp__cancel_cumulate();
410 		}
411 	}
412 
413 	if (sort__mode == SORT_MODE__BRANCH) {
414 		if (!is_pipe &&
415 		    !(sample_type & PERF_SAMPLE_BRANCH_STACK)) {
416 			ui__error("Selected -b but no branch data. "
417 				  "Did you call perf record without -b?\n");
418 			return -1;
419 		}
420 	}
421 
422 	if (sort__mode == SORT_MODE__MEMORY) {
423 		/*
424 		 * FIXUP: prior to kernel 5.18, Arm SPE missed to set
425 		 * PERF_SAMPLE_DATA_SRC bit in sample type.  For backward
426 		 * compatibility, set the bit if it's an old perf data file.
427 		 */
428 		evlist__for_each_entry(session->evlist, evsel) {
429 			if (strstr(evsel__name(evsel), "arm_spe") &&
430 				!(sample_type & PERF_SAMPLE_DATA_SRC)) {
431 				evsel->core.attr.sample_type |= PERF_SAMPLE_DATA_SRC;
432 				sample_type |= PERF_SAMPLE_DATA_SRC;
433 			}
434 		}
435 
436 		if (!is_pipe && !(sample_type & PERF_SAMPLE_DATA_SRC)) {
437 			ui__error("Selected --mem-mode but no mem data. "
438 				  "Did you call perf record without -d?\n");
439 			return -1;
440 		}
441 	}
442 
443 	callchain_param_setup(sample_type, perf_env__arch(&rep->session->header.env));
444 
445 	if (rep->stitch_lbr && (callchain_param.record_mode != CALLCHAIN_LBR)) {
446 		ui__warning("Can't find LBR callchain. Switch off --stitch-lbr.\n"
447 			    "Please apply --call-graph lbr when recording.\n");
448 		rep->stitch_lbr = false;
449 	}
450 
451 	/* ??? handle more cases than just ANY? */
452 	if (!(evlist__combined_branch_type(session->evlist) & PERF_SAMPLE_BRANCH_ANY))
453 		rep->nonany_branch_mode = true;
454 
455 #if !defined(HAVE_LIBUNWIND_SUPPORT) && !defined(HAVE_DWARF_SUPPORT)
456 	if (dwarf_callchain_users) {
457 		ui__warning("Please install libunwind or libdw "
458 			    "development packages during the perf build.\n");
459 	}
460 #endif
461 
462 	return 0;
463 }
464 
465 static void sig_handler(int sig __maybe_unused)
466 {
467 	session_done = 1;
468 }
469 
470 static size_t hists__fprintf_nr_sample_events(struct hists *hists, struct report *rep,
471 					      const char *evname, FILE *fp)
472 {
473 	size_t ret;
474 	char unit;
475 	unsigned long nr_samples = hists->stats.nr_samples;
476 	u64 nr_events = hists->stats.total_period;
477 	struct evsel *evsel = hists_to_evsel(hists);
478 	char buf[512];
479 	size_t size = sizeof(buf);
480 	int socked_id = hists->socket_filter;
481 
482 	if (quiet)
483 		return 0;
484 
485 	if (symbol_conf.filter_relative) {
486 		nr_samples = hists->stats.nr_non_filtered_samples;
487 		nr_events = hists->stats.total_non_filtered_period;
488 	}
489 
490 	if (evsel__is_group_event(evsel)) {
491 		struct evsel *pos;
492 
493 		evsel__group_desc(evsel, buf, size);
494 		evname = buf;
495 
496 		for_each_group_member(pos, evsel) {
497 			const struct hists *pos_hists = evsel__hists(pos);
498 
499 			if (symbol_conf.filter_relative) {
500 				nr_samples += pos_hists->stats.nr_non_filtered_samples;
501 				nr_events += pos_hists->stats.total_non_filtered_period;
502 			} else {
503 				nr_samples += pos_hists->stats.nr_samples;
504 				nr_events += pos_hists->stats.total_period;
505 			}
506 		}
507 	}
508 
509 	nr_samples = convert_unit(nr_samples, &unit);
510 	ret = fprintf(fp, "# Samples: %lu%c", nr_samples, unit);
511 	if (evname != NULL) {
512 		ret += fprintf(fp, " of event%s '%s'",
513 			       evsel->core.nr_members > 1 ? "s" : "", evname);
514 	}
515 
516 	if (rep->time_str)
517 		ret += fprintf(fp, " (time slices: %s)", rep->time_str);
518 
519 	if (symbol_conf.show_ref_callgraph && evname && strstr(evname, "call-graph=no")) {
520 		ret += fprintf(fp, ", show reference callgraph");
521 	}
522 
523 	if (rep->mem_mode) {
524 		ret += fprintf(fp, "\n# Total weight : %" PRIu64, nr_events);
525 		ret += fprintf(fp, "\n# Sort order   : %s", sort_order ? : default_mem_sort_order);
526 	} else
527 		ret += fprintf(fp, "\n# Event count (approx.): %" PRIu64, nr_events);
528 
529 	if (socked_id > -1)
530 		ret += fprintf(fp, "\n# Processor Socket: %d", socked_id);
531 
532 	return ret + fprintf(fp, "\n#\n");
533 }
534 
535 static int evlist__tui_block_hists_browse(struct evlist *evlist, struct report *rep)
536 {
537 	struct evsel *pos;
538 	int i = 0, ret;
539 
540 	evlist__for_each_entry(evlist, pos) {
541 		ret = report__browse_block_hists(&rep->block_reports[i++].hist,
542 						 rep->min_percent, pos,
543 						 &rep->session->header.env);
544 		if (ret != 0)
545 			return ret;
546 	}
547 
548 	return 0;
549 }
550 
551 static int evlist__tty_browse_hists(struct evlist *evlist, struct report *rep, const char *help)
552 {
553 	struct evsel *pos;
554 	int i = 0;
555 
556 	if (!quiet) {
557 		fprintf(stdout, "#\n# Total Lost Samples: %" PRIu64 "\n#\n",
558 			evlist->stats.total_lost_samples);
559 	}
560 
561 	evlist__for_each_entry(evlist, pos) {
562 		struct hists *hists = evsel__hists(pos);
563 		const char *evname = evsel__name(pos);
564 
565 		i++;
566 		if (symbol_conf.event_group && !evsel__is_group_leader(pos))
567 			continue;
568 
569 		if (rep->skip_empty && !hists->stats.nr_samples)
570 			continue;
571 
572 		hists__fprintf_nr_sample_events(hists, rep, evname, stdout);
573 
574 		if (rep->total_cycles_mode) {
575 			report__browse_block_hists(&rep->block_reports[i - 1].hist,
576 						   rep->min_percent, pos, NULL);
577 			continue;
578 		}
579 
580 		hists__fprintf(hists, !quiet, 0, 0, rep->min_percent, stdout,
581 			       !(symbol_conf.use_callchain ||
582 			         symbol_conf.show_branchflag_count));
583 		fprintf(stdout, "\n\n");
584 	}
585 
586 	if (!quiet)
587 		fprintf(stdout, "#\n# (%s)\n#\n", help);
588 
589 	if (rep->show_threads) {
590 		bool style = !strcmp(rep->pretty_printing_style, "raw");
591 		perf_read_values_display(stdout, &rep->show_threads_values,
592 					 style);
593 		perf_read_values_destroy(&rep->show_threads_values);
594 	}
595 
596 	if (sort__mode == SORT_MODE__BRANCH)
597 		branch_type_stat_display(stdout, &rep->brtype_stat);
598 
599 	return 0;
600 }
601 
602 static void report__warn_kptr_restrict(const struct report *rep)
603 {
604 	struct map *kernel_map = machine__kernel_map(&rep->session->machines.host);
605 	struct kmap *kernel_kmap = kernel_map ? map__kmap(kernel_map) : NULL;
606 
607 	if (evlist__exclude_kernel(rep->session->evlist))
608 		return;
609 
610 	if (kernel_map == NULL ||
611 	     (map__dso(kernel_map)->hit &&
612 	     (kernel_kmap->ref_reloc_sym == NULL ||
613 	      kernel_kmap->ref_reloc_sym->addr == 0))) {
614 		const char *desc =
615 		    "As no suitable kallsyms nor vmlinux was found, kernel samples\n"
616 		    "can't be resolved.";
617 
618 		if (kernel_map && map__has_symbols(kernel_map)) {
619 			desc = "If some relocation was applied (e.g. "
620 			       "kexec) symbols may be misresolved.";
621 		}
622 
623 		ui__warning(
624 "Kernel address maps (/proc/{kallsyms,modules}) were restricted.\n\n"
625 "Check /proc/sys/kernel/kptr_restrict before running 'perf record'.\n\n%s\n\n"
626 "Samples in kernel modules can't be resolved as well.\n\n",
627 		desc);
628 	}
629 }
630 
631 static int report__gtk_browse_hists(struct report *rep, const char *help)
632 {
633 	int (*hist_browser)(struct evlist *evlist, const char *help,
634 			    struct hist_browser_timer *timer, float min_pcnt);
635 
636 	hist_browser = dlsym(perf_gtk_handle, "evlist__gtk_browse_hists");
637 
638 	if (hist_browser == NULL) {
639 		ui__error("GTK browser not found!\n");
640 		return -1;
641 	}
642 
643 	return hist_browser(rep->session->evlist, help, NULL, rep->min_percent);
644 }
645 
646 static int report__browse_hists(struct report *rep)
647 {
648 	int ret;
649 	struct perf_session *session = rep->session;
650 	struct evlist *evlist = session->evlist;
651 	char *help = NULL, *path = NULL;
652 
653 	path = system_path(TIPDIR);
654 	if (perf_tip(&help, path) || help == NULL) {
655 		/* fallback for people who don't install perf ;-) */
656 		free(path);
657 		path = system_path(DOCDIR);
658 		if (perf_tip(&help, path) || help == NULL)
659 			help = strdup("Cannot load tips.txt file, please install perf!");
660 	}
661 	free(path);
662 
663 	switch (use_browser) {
664 	case 1:
665 		if (rep->total_cycles_mode) {
666 			ret = evlist__tui_block_hists_browse(evlist, rep);
667 			break;
668 		}
669 
670 		ret = evlist__tui_browse_hists(evlist, help, NULL, rep->min_percent,
671 					       &session->header.env, true);
672 		/*
673 		 * Usually "ret" is the last pressed key, and we only
674 		 * care if the key notifies us to switch data file.
675 		 */
676 		if (ret != K_SWITCH_INPUT_DATA && ret != K_RELOAD)
677 			ret = 0;
678 		break;
679 	case 2:
680 		ret = report__gtk_browse_hists(rep, help);
681 		break;
682 	default:
683 		ret = evlist__tty_browse_hists(evlist, rep, help);
684 		break;
685 	}
686 	free(help);
687 	return ret;
688 }
689 
690 static int report__collapse_hists(struct report *rep)
691 {
692 	struct ui_progress prog;
693 	struct evsel *pos;
694 	int ret = 0;
695 
696 	ui_progress__init(&prog, rep->nr_entries, "Merging related events...");
697 
698 	evlist__for_each_entry(rep->session->evlist, pos) {
699 		struct hists *hists = evsel__hists(pos);
700 
701 		if (pos->core.idx == 0)
702 			hists->symbol_filter_str = rep->symbol_filter_str;
703 
704 		hists->socket_filter = rep->socket_filter;
705 
706 		ret = hists__collapse_resort(hists, &prog);
707 		if (ret < 0)
708 			break;
709 
710 		/* Non-group events are considered as leader */
711 		if (symbol_conf.event_group && !evsel__is_group_leader(pos)) {
712 			struct hists *leader_hists = evsel__hists(evsel__leader(pos));
713 
714 			hists__match(leader_hists, hists);
715 			hists__link(leader_hists, hists);
716 		}
717 	}
718 
719 	ui_progress__finish();
720 	return ret;
721 }
722 
723 static int hists__resort_cb(struct hist_entry *he, void *arg)
724 {
725 	struct report *rep = arg;
726 	struct symbol *sym = he->ms.sym;
727 
728 	if (rep->symbol_ipc && sym && !sym->annotate2) {
729 		struct evsel *evsel = hists_to_evsel(he->hists);
730 
731 		symbol__annotate2(&he->ms, evsel, NULL);
732 	}
733 
734 	return 0;
735 }
736 
737 static void report__output_resort(struct report *rep)
738 {
739 	struct ui_progress prog;
740 	struct evsel *pos;
741 
742 	ui_progress__init(&prog, rep->nr_entries, "Sorting events for output...");
743 
744 	evlist__for_each_entry(rep->session->evlist, pos) {
745 		evsel__output_resort_cb(pos, &prog, hists__resort_cb, rep);
746 	}
747 
748 	ui_progress__finish();
749 }
750 
751 static int count_sample_event(struct perf_tool *tool __maybe_unused,
752 			      union perf_event *event __maybe_unused,
753 			      struct perf_sample *sample __maybe_unused,
754 			      struct evsel *evsel,
755 			      struct machine *machine __maybe_unused)
756 {
757 	struct hists *hists = evsel__hists(evsel);
758 
759 	hists__inc_nr_events(hists);
760 	return 0;
761 }
762 
763 static int count_lost_samples_event(struct perf_tool *tool,
764 				    union perf_event *event,
765 				    struct perf_sample *sample,
766 				    struct machine *machine __maybe_unused)
767 {
768 	struct report *rep = container_of(tool, struct report, tool);
769 	struct evsel *evsel;
770 
771 	evsel = evlist__id2evsel(rep->session->evlist, sample->id);
772 	if (evsel) {
773 		hists__inc_nr_lost_samples(evsel__hists(evsel),
774 					   event->lost_samples.lost);
775 	}
776 	return 0;
777 }
778 
779 static int process_attr(struct perf_tool *tool __maybe_unused,
780 			union perf_event *event,
781 			struct evlist **pevlist);
782 
783 static void stats_setup(struct report *rep)
784 {
785 	memset(&rep->tool, 0, sizeof(rep->tool));
786 	rep->tool.attr = process_attr;
787 	rep->tool.sample = count_sample_event;
788 	rep->tool.lost_samples = count_lost_samples_event;
789 	rep->tool.no_warn = true;
790 }
791 
792 static int stats_print(struct report *rep)
793 {
794 	struct perf_session *session = rep->session;
795 
796 	perf_session__fprintf_nr_events(session, stdout, rep->skip_empty);
797 	evlist__fprintf_nr_events(session->evlist, stdout, rep->skip_empty);
798 	return 0;
799 }
800 
801 static void tasks_setup(struct report *rep)
802 {
803 	memset(&rep->tool, 0, sizeof(rep->tool));
804 	rep->tool.ordered_events = true;
805 	if (rep->mmaps_mode) {
806 		rep->tool.mmap = perf_event__process_mmap;
807 		rep->tool.mmap2 = perf_event__process_mmap2;
808 	}
809 	rep->tool.attr = process_attr;
810 	rep->tool.comm = perf_event__process_comm;
811 	rep->tool.exit = perf_event__process_exit;
812 	rep->tool.fork = perf_event__process_fork;
813 	rep->tool.no_warn = true;
814 }
815 
816 struct task {
817 	struct thread		*thread;
818 	struct list_head	 list;
819 	struct list_head	 children;
820 };
821 
822 static struct task *tasks_list(struct task *task, struct machine *machine)
823 {
824 	struct thread *parent_thread, *thread = task->thread;
825 	struct task   *parent_task;
826 
827 	/* Already listed. */
828 	if (!list_empty(&task->list))
829 		return NULL;
830 
831 	/* Last one in the chain. */
832 	if (thread__ppid(thread) == -1)
833 		return task;
834 
835 	parent_thread = machine__find_thread(machine, -1, thread__ppid(thread));
836 	if (!parent_thread)
837 		return ERR_PTR(-ENOENT);
838 
839 	parent_task = thread__priv(parent_thread);
840 	thread__put(parent_thread);
841 	list_add_tail(&task->list, &parent_task->children);
842 	return tasks_list(parent_task, machine);
843 }
844 
845 static size_t maps__fprintf_task(struct maps *maps, int indent, FILE *fp)
846 {
847 	size_t printed = 0;
848 	struct map_rb_node *rb_node;
849 
850 	maps__for_each_entry(maps, rb_node) {
851 		struct map *map = rb_node->map;
852 		const struct dso *dso = map__dso(map);
853 		u32 prot = map__prot(map);
854 
855 		printed += fprintf(fp, "%*s  %" PRIx64 "-%" PRIx64 " %c%c%c%c %08" PRIx64 " %" PRIu64 " %s\n",
856 				   indent, "", map__start(map), map__end(map),
857 				   prot & PROT_READ ? 'r' : '-',
858 				   prot & PROT_WRITE ? 'w' : '-',
859 				   prot & PROT_EXEC ? 'x' : '-',
860 				   map__flags(map) ? 's' : 'p',
861 				   map__pgoff(map),
862 				   dso->id.ino, dso->name);
863 	}
864 
865 	return printed;
866 }
867 
868 static void task__print_level(struct task *task, FILE *fp, int level)
869 {
870 	struct thread *thread = task->thread;
871 	struct task *child;
872 	int comm_indent = fprintf(fp, "  %8d %8d %8d |%*s",
873 				  thread__pid(thread), thread__tid(thread),
874 				  thread__ppid(thread), level, "");
875 
876 	fprintf(fp, "%s\n", thread__comm_str(thread));
877 
878 	maps__fprintf_task(thread__maps(thread), comm_indent, fp);
879 
880 	if (!list_empty(&task->children)) {
881 		list_for_each_entry(child, &task->children, list)
882 			task__print_level(child, fp, level + 1);
883 	}
884 }
885 
886 static int tasks_print(struct report *rep, FILE *fp)
887 {
888 	struct perf_session *session = rep->session;
889 	struct machine      *machine = &session->machines.host;
890 	struct task *tasks, *task;
891 	unsigned int nr = 0, itask = 0, i;
892 	struct rb_node *nd;
893 	LIST_HEAD(list);
894 
895 	/*
896 	 * No locking needed while accessing machine->threads,
897 	 * because --tasks is single threaded command.
898 	 */
899 
900 	/* Count all the threads. */
901 	for (i = 0; i < THREADS__TABLE_SIZE; i++)
902 		nr += machine->threads[i].nr;
903 
904 	tasks = malloc(sizeof(*tasks) * nr);
905 	if (!tasks)
906 		return -ENOMEM;
907 
908 	for (i = 0; i < THREADS__TABLE_SIZE; i++) {
909 		struct threads *threads = &machine->threads[i];
910 
911 		for (nd = rb_first_cached(&threads->entries); nd;
912 		     nd = rb_next(nd)) {
913 			task = tasks + itask++;
914 
915 			task->thread = rb_entry(nd, struct thread_rb_node, rb_node)->thread;
916 			INIT_LIST_HEAD(&task->children);
917 			INIT_LIST_HEAD(&task->list);
918 			thread__set_priv(task->thread, task);
919 		}
920 	}
921 
922 	/*
923 	 * Iterate every task down to the unprocessed parent
924 	 * and link all in task children list. Task with no
925 	 * parent is added into 'list'.
926 	 */
927 	for (itask = 0; itask < nr; itask++) {
928 		task = tasks + itask;
929 
930 		if (!list_empty(&task->list))
931 			continue;
932 
933 		task = tasks_list(task, machine);
934 		if (IS_ERR(task)) {
935 			pr_err("Error: failed to process tasks\n");
936 			free(tasks);
937 			return PTR_ERR(task);
938 		}
939 
940 		if (task)
941 			list_add_tail(&task->list, &list);
942 	}
943 
944 	fprintf(fp, "# %8s %8s %8s  %s\n", "pid", "tid", "ppid", "comm");
945 
946 	list_for_each_entry(task, &list, list)
947 		task__print_level(task, fp, 0);
948 
949 	free(tasks);
950 	return 0;
951 }
952 
953 static int __cmd_report(struct report *rep)
954 {
955 	int ret;
956 	struct perf_session *session = rep->session;
957 	struct evsel *pos;
958 	struct perf_data *data = session->data;
959 
960 	signal(SIGINT, sig_handler);
961 
962 	if (rep->cpu_list) {
963 		ret = perf_session__cpu_bitmap(session, rep->cpu_list,
964 					       rep->cpu_bitmap);
965 		if (ret) {
966 			ui__error("failed to set cpu bitmap\n");
967 			return ret;
968 		}
969 		session->itrace_synth_opts->cpu_bitmap = rep->cpu_bitmap;
970 	}
971 
972 	if (rep->show_threads) {
973 		ret = perf_read_values_init(&rep->show_threads_values);
974 		if (ret)
975 			return ret;
976 	}
977 
978 	ret = report__setup_sample_type(rep);
979 	if (ret) {
980 		/* report__setup_sample_type() already showed error message */
981 		return ret;
982 	}
983 
984 	if (rep->stats_mode)
985 		stats_setup(rep);
986 
987 	if (rep->tasks_mode)
988 		tasks_setup(rep);
989 
990 	ret = perf_session__process_events(session);
991 	if (ret) {
992 		ui__error("failed to process sample\n");
993 		return ret;
994 	}
995 
996 	evlist__check_mem_load_aux(session->evlist);
997 
998 	if (rep->stats_mode)
999 		return stats_print(rep);
1000 
1001 	if (rep->tasks_mode)
1002 		return tasks_print(rep, stdout);
1003 
1004 	report__warn_kptr_restrict(rep);
1005 
1006 	evlist__for_each_entry(session->evlist, pos)
1007 		rep->nr_entries += evsel__hists(pos)->nr_entries;
1008 
1009 	if (use_browser == 0) {
1010 		if (verbose > 3)
1011 			perf_session__fprintf(session, stdout);
1012 
1013 		if (verbose > 2)
1014 			perf_session__fprintf_dsos(session, stdout);
1015 
1016 		if (dump_trace) {
1017 			perf_session__fprintf_nr_events(session, stdout,
1018 							rep->skip_empty);
1019 			evlist__fprintf_nr_events(session->evlist, stdout,
1020 						  rep->skip_empty);
1021 			return 0;
1022 		}
1023 	}
1024 
1025 	ret = report__collapse_hists(rep);
1026 	if (ret) {
1027 		ui__error("failed to process hist entry\n");
1028 		return ret;
1029 	}
1030 
1031 	if (session_done())
1032 		return 0;
1033 
1034 	/*
1035 	 * recalculate number of entries after collapsing since it
1036 	 * might be changed during the collapse phase.
1037 	 */
1038 	rep->nr_entries = 0;
1039 	evlist__for_each_entry(session->evlist, pos)
1040 		rep->nr_entries += evsel__hists(pos)->nr_entries;
1041 
1042 	if (rep->nr_entries == 0) {
1043 		ui__error("The %s data has no samples!\n", data->path);
1044 		return 0;
1045 	}
1046 
1047 	report__output_resort(rep);
1048 
1049 	if (rep->total_cycles_mode) {
1050 		int block_hpps[6] = {
1051 			PERF_HPP_REPORT__BLOCK_TOTAL_CYCLES_PCT,
1052 			PERF_HPP_REPORT__BLOCK_LBR_CYCLES,
1053 			PERF_HPP_REPORT__BLOCK_CYCLES_PCT,
1054 			PERF_HPP_REPORT__BLOCK_AVG_CYCLES,
1055 			PERF_HPP_REPORT__BLOCK_RANGE,
1056 			PERF_HPP_REPORT__BLOCK_DSO,
1057 		};
1058 
1059 		rep->block_reports = block_info__create_report(session->evlist,
1060 							       rep->total_cycles,
1061 							       block_hpps, 6,
1062 							       &rep->nr_block_reports);
1063 		if (!rep->block_reports)
1064 			return -1;
1065 	}
1066 
1067 	return report__browse_hists(rep);
1068 }
1069 
1070 static int
1071 report_parse_callchain_opt(const struct option *opt, const char *arg, int unset)
1072 {
1073 	struct callchain_param *callchain = opt->value;
1074 
1075 	callchain->enabled = !unset;
1076 	/*
1077 	 * --no-call-graph
1078 	 */
1079 	if (unset) {
1080 		symbol_conf.use_callchain = false;
1081 		callchain->mode = CHAIN_NONE;
1082 		return 0;
1083 	}
1084 
1085 	return parse_callchain_report_opt(arg);
1086 }
1087 
1088 static int
1089 parse_time_quantum(const struct option *opt, const char *arg,
1090 		   int unset __maybe_unused)
1091 {
1092 	unsigned long *time_q = opt->value;
1093 	char *end;
1094 
1095 	*time_q = strtoul(arg, &end, 0);
1096 	if (end == arg)
1097 		goto parse_err;
1098 	if (*time_q == 0) {
1099 		pr_err("time quantum cannot be 0");
1100 		return -1;
1101 	}
1102 	end = skip_spaces(end);
1103 	if (*end == 0)
1104 		return 0;
1105 	if (!strcmp(end, "s")) {
1106 		*time_q *= NSEC_PER_SEC;
1107 		return 0;
1108 	}
1109 	if (!strcmp(end, "ms")) {
1110 		*time_q *= NSEC_PER_MSEC;
1111 		return 0;
1112 	}
1113 	if (!strcmp(end, "us")) {
1114 		*time_q *= NSEC_PER_USEC;
1115 		return 0;
1116 	}
1117 	if (!strcmp(end, "ns"))
1118 		return 0;
1119 parse_err:
1120 	pr_err("Cannot parse time quantum `%s'\n", arg);
1121 	return -1;
1122 }
1123 
1124 int
1125 report_parse_ignore_callees_opt(const struct option *opt __maybe_unused,
1126 				const char *arg, int unset __maybe_unused)
1127 {
1128 	if (arg) {
1129 		int err = regcomp(&ignore_callees_regex, arg, REG_EXTENDED);
1130 		if (err) {
1131 			char buf[BUFSIZ];
1132 			regerror(err, &ignore_callees_regex, buf, sizeof(buf));
1133 			pr_err("Invalid --ignore-callees regex: %s\n%s", arg, buf);
1134 			return -1;
1135 		}
1136 		have_ignore_callees = 1;
1137 	}
1138 
1139 	return 0;
1140 }
1141 
1142 static int
1143 parse_branch_mode(const struct option *opt,
1144 		  const char *str __maybe_unused, int unset)
1145 {
1146 	int *branch_mode = opt->value;
1147 
1148 	*branch_mode = !unset;
1149 	return 0;
1150 }
1151 
1152 static int
1153 parse_percent_limit(const struct option *opt, const char *str,
1154 		    int unset __maybe_unused)
1155 {
1156 	struct report *rep = opt->value;
1157 	double pcnt = strtof(str, NULL);
1158 
1159 	rep->min_percent = pcnt;
1160 	callchain_param.min_percent = pcnt;
1161 	return 0;
1162 }
1163 
1164 static int process_attr(struct perf_tool *tool __maybe_unused,
1165 			union perf_event *event,
1166 			struct evlist **pevlist)
1167 {
1168 	u64 sample_type;
1169 	int err;
1170 
1171 	err = perf_event__process_attr(tool, event, pevlist);
1172 	if (err)
1173 		return err;
1174 
1175 	/*
1176 	 * Check if we need to enable callchains based
1177 	 * on events sample_type.
1178 	 */
1179 	sample_type = evlist__combined_sample_type(*pevlist);
1180 	callchain_param_setup(sample_type, perf_env__arch((*pevlist)->env));
1181 	return 0;
1182 }
1183 
1184 int cmd_report(int argc, const char **argv)
1185 {
1186 	struct perf_session *session;
1187 	struct itrace_synth_opts itrace_synth_opts = { .set = 0, };
1188 	struct stat st;
1189 	bool has_br_stack = false;
1190 	int branch_mode = -1;
1191 	int last_key = 0;
1192 	bool branch_call_mode = false;
1193 #define CALLCHAIN_DEFAULT_OPT  "graph,0.5,caller,function,percent"
1194 	static const char report_callchain_help[] = "Display call graph (stack chain/backtrace):\n\n"
1195 						    CALLCHAIN_REPORT_HELP
1196 						    "\n\t\t\t\tDefault: " CALLCHAIN_DEFAULT_OPT;
1197 	char callchain_default_opt[] = CALLCHAIN_DEFAULT_OPT;
1198 	const char * const report_usage[] = {
1199 		"perf report [<options>]",
1200 		NULL
1201 	};
1202 	struct report report = {
1203 		.tool = {
1204 			.sample		 = process_sample_event,
1205 			.mmap		 = perf_event__process_mmap,
1206 			.mmap2		 = perf_event__process_mmap2,
1207 			.comm		 = perf_event__process_comm,
1208 			.namespaces	 = perf_event__process_namespaces,
1209 			.cgroup		 = perf_event__process_cgroup,
1210 			.exit		 = perf_event__process_exit,
1211 			.fork		 = perf_event__process_fork,
1212 			.lost		 = perf_event__process_lost,
1213 			.read		 = process_read_event,
1214 			.attr		 = process_attr,
1215 #ifdef HAVE_LIBTRACEEVENT
1216 			.tracing_data	 = perf_event__process_tracing_data,
1217 #endif
1218 			.build_id	 = perf_event__process_build_id,
1219 			.id_index	 = perf_event__process_id_index,
1220 			.auxtrace_info	 = perf_event__process_auxtrace_info,
1221 			.auxtrace	 = perf_event__process_auxtrace,
1222 			.event_update	 = perf_event__process_event_update,
1223 			.feature	 = process_feature_event,
1224 			.ordered_events	 = true,
1225 			.ordering_requires_timestamps = true,
1226 		},
1227 		.max_stack		 = PERF_MAX_STACK_DEPTH,
1228 		.pretty_printing_style	 = "normal",
1229 		.socket_filter		 = -1,
1230 		.skip_empty		 = true,
1231 	};
1232 	char *sort_order_help = sort_help("sort by key(s):");
1233 	char *field_order_help = sort_help("output field(s): overhead period sample ");
1234 	const char *disassembler_style = NULL, *objdump_path = NULL, *addr2line_path = NULL;
1235 	const struct option options[] = {
1236 	OPT_STRING('i', "input", &input_name, "file",
1237 		    "input file name"),
1238 	OPT_INCR('v', "verbose", &verbose,
1239 		    "be more verbose (show symbol address, etc)"),
1240 	OPT_BOOLEAN('q', "quiet", &quiet, "Do not show any warnings or messages"),
1241 	OPT_BOOLEAN('D', "dump-raw-trace", &dump_trace,
1242 		    "dump raw trace in ASCII"),
1243 	OPT_BOOLEAN(0, "stats", &report.stats_mode, "Display event stats"),
1244 	OPT_BOOLEAN(0, "tasks", &report.tasks_mode, "Display recorded tasks"),
1245 	OPT_BOOLEAN(0, "mmaps", &report.mmaps_mode, "Display recorded tasks memory maps"),
1246 	OPT_STRING('k', "vmlinux", &symbol_conf.vmlinux_name,
1247 		   "file", "vmlinux pathname"),
1248 	OPT_BOOLEAN(0, "ignore-vmlinux", &symbol_conf.ignore_vmlinux,
1249                     "don't load vmlinux even if found"),
1250 	OPT_STRING(0, "kallsyms", &symbol_conf.kallsyms_name,
1251 		   "file", "kallsyms pathname"),
1252 	OPT_BOOLEAN('f', "force", &symbol_conf.force, "don't complain, do it"),
1253 	OPT_BOOLEAN('m', "modules", &symbol_conf.use_modules,
1254 		    "load module symbols - WARNING: use only with -k and LIVE kernel"),
1255 	OPT_BOOLEAN('n', "show-nr-samples", &symbol_conf.show_nr_samples,
1256 		    "Show a column with the number of samples"),
1257 	OPT_BOOLEAN('T', "threads", &report.show_threads,
1258 		    "Show per-thread event counters"),
1259 	OPT_STRING(0, "pretty", &report.pretty_printing_style, "key",
1260 		   "pretty printing style key: normal raw"),
1261 #ifdef HAVE_SLANG_SUPPORT
1262 	OPT_BOOLEAN(0, "tui", &report.use_tui, "Use the TUI interface"),
1263 #endif
1264 #ifdef HAVE_GTK2_SUPPORT
1265 	OPT_BOOLEAN(0, "gtk", &report.use_gtk, "Use the GTK2 interface"),
1266 #endif
1267 	OPT_BOOLEAN(0, "stdio", &report.use_stdio,
1268 		    "Use the stdio interface"),
1269 	OPT_BOOLEAN(0, "header", &report.header, "Show data header."),
1270 	OPT_BOOLEAN(0, "header-only", &report.header_only,
1271 		    "Show only data header."),
1272 	OPT_STRING('s', "sort", &sort_order, "key[,key2...]",
1273 		   sort_order_help),
1274 	OPT_STRING('F', "fields", &field_order, "key[,keys...]",
1275 		   field_order_help),
1276 	OPT_BOOLEAN(0, "show-cpu-utilization", &symbol_conf.show_cpu_utilization,
1277 		    "Show sample percentage for different cpu modes"),
1278 	OPT_BOOLEAN_FLAG(0, "showcpuutilization", &symbol_conf.show_cpu_utilization,
1279 		    "Show sample percentage for different cpu modes", PARSE_OPT_HIDDEN),
1280 	OPT_STRING('p', "parent", &parent_pattern, "regex",
1281 		   "regex filter to identify parent, see: '--sort parent'"),
1282 	OPT_BOOLEAN('x', "exclude-other", &symbol_conf.exclude_other,
1283 		    "Only display entries with parent-match"),
1284 	OPT_CALLBACK_DEFAULT('g', "call-graph", &callchain_param,
1285 			     "print_type,threshold[,print_limit],order,sort_key[,branch],value",
1286 			     report_callchain_help, &report_parse_callchain_opt,
1287 			     callchain_default_opt),
1288 	OPT_BOOLEAN(0, "children", &symbol_conf.cumulate_callchain,
1289 		    "Accumulate callchains of children and show total overhead as well. "
1290 		    "Enabled by default, use --no-children to disable."),
1291 	OPT_INTEGER(0, "max-stack", &report.max_stack,
1292 		    "Set the maximum stack depth when parsing the callchain, "
1293 		    "anything beyond the specified depth will be ignored. "
1294 		    "Default: kernel.perf_event_max_stack or " __stringify(PERF_MAX_STACK_DEPTH)),
1295 	OPT_BOOLEAN('G', "inverted", &report.inverted_callchain,
1296 		    "alias for inverted call graph"),
1297 	OPT_CALLBACK(0, "ignore-callees", NULL, "regex",
1298 		   "ignore callees of these functions in call graphs",
1299 		   report_parse_ignore_callees_opt),
1300 	OPT_STRING('d', "dsos", &symbol_conf.dso_list_str, "dso[,dso...]",
1301 		   "only consider symbols in these dsos"),
1302 	OPT_STRING('c', "comms", &symbol_conf.comm_list_str, "comm[,comm...]",
1303 		   "only consider symbols in these comms"),
1304 	OPT_STRING(0, "pid", &symbol_conf.pid_list_str, "pid[,pid...]",
1305 		   "only consider symbols in these pids"),
1306 	OPT_STRING(0, "tid", &symbol_conf.tid_list_str, "tid[,tid...]",
1307 		   "only consider symbols in these tids"),
1308 	OPT_STRING('S', "symbols", &symbol_conf.sym_list_str, "symbol[,symbol...]",
1309 		   "only consider these symbols"),
1310 	OPT_STRING(0, "symbol-filter", &report.symbol_filter_str, "filter",
1311 		   "only show symbols that (partially) match with this filter"),
1312 	OPT_STRING('w', "column-widths", &symbol_conf.col_width_list_str,
1313 		   "width[,width...]",
1314 		   "don't try to adjust column width, use these fixed values"),
1315 	OPT_STRING_NOEMPTY('t', "field-separator", &symbol_conf.field_sep, "separator",
1316 		   "separator for columns, no spaces will be added between "
1317 		   "columns '.' is reserved."),
1318 	OPT_BOOLEAN('U', "hide-unresolved", &symbol_conf.hide_unresolved,
1319 		    "Only display entries resolved to a symbol"),
1320 	OPT_CALLBACK(0, "symfs", NULL, "directory",
1321 		     "Look for files with symbols relative to this directory",
1322 		     symbol__config_symfs),
1323 	OPT_STRING('C', "cpu", &report.cpu_list, "cpu",
1324 		   "list of cpus to profile"),
1325 	OPT_BOOLEAN('I', "show-info", &report.show_full_info,
1326 		    "Display extended information about perf.data file"),
1327 	OPT_BOOLEAN(0, "source", &annotate_opts.annotate_src,
1328 		    "Interleave source code with assembly code (default)"),
1329 	OPT_BOOLEAN(0, "asm-raw", &annotate_opts.show_asm_raw,
1330 		    "Display raw encoding of assembly instructions (default)"),
1331 	OPT_STRING('M', "disassembler-style", &disassembler_style, "disassembler style",
1332 		   "Specify disassembler style (e.g. -M intel for intel syntax)"),
1333 	OPT_STRING(0, "prefix", &annotate_opts.prefix, "prefix",
1334 		    "Add prefix to source file path names in programs (with --prefix-strip)"),
1335 	OPT_STRING(0, "prefix-strip", &annotate_opts.prefix_strip, "N",
1336 		    "Strip first N entries of source file path name in programs (with --prefix)"),
1337 	OPT_BOOLEAN(0, "show-total-period", &symbol_conf.show_total_period,
1338 		    "Show a column with the sum of periods"),
1339 	OPT_BOOLEAN_SET(0, "group", &symbol_conf.event_group, &report.group_set,
1340 		    "Show event group information together"),
1341 	OPT_INTEGER(0, "group-sort-idx", &symbol_conf.group_sort_idx,
1342 		    "Sort the output by the event at the index n in group. "
1343 		    "If n is invalid, sort by the first event. "
1344 		    "WARNING: should be used on grouped events."),
1345 	OPT_CALLBACK_NOOPT('b', "branch-stack", &branch_mode, "",
1346 		    "use branch records for per branch histogram filling",
1347 		    parse_branch_mode),
1348 	OPT_BOOLEAN(0, "branch-history", &branch_call_mode,
1349 		    "add last branch records to call history"),
1350 	OPT_STRING(0, "objdump", &objdump_path, "path",
1351 		   "objdump binary to use for disassembly and annotations"),
1352 	OPT_STRING(0, "addr2line", &addr2line_path, "path",
1353 		   "addr2line binary to use for line numbers"),
1354 	OPT_BOOLEAN(0, "demangle", &symbol_conf.demangle,
1355 		    "Disable symbol demangling"),
1356 	OPT_BOOLEAN(0, "demangle-kernel", &symbol_conf.demangle_kernel,
1357 		    "Enable kernel symbol demangling"),
1358 	OPT_BOOLEAN(0, "mem-mode", &report.mem_mode, "mem access profile"),
1359 	OPT_INTEGER(0, "samples", &symbol_conf.res_sample,
1360 		    "Number of samples to save per histogram entry for individual browsing"),
1361 	OPT_CALLBACK(0, "percent-limit", &report, "percent",
1362 		     "Don't show entries under that percent", parse_percent_limit),
1363 	OPT_CALLBACK(0, "percentage", NULL, "relative|absolute",
1364 		     "how to display percentage of filtered entries", parse_filter_percentage),
1365 	OPT_CALLBACK_OPTARG(0, "itrace", &itrace_synth_opts, NULL, "opts",
1366 			    "Instruction Tracing options\n" ITRACE_HELP,
1367 			    itrace_parse_synth_opts),
1368 	OPT_BOOLEAN(0, "full-source-path", &srcline_full_filename,
1369 			"Show full source file name path for source lines"),
1370 	OPT_BOOLEAN(0, "show-ref-call-graph", &symbol_conf.show_ref_callgraph,
1371 		    "Show callgraph from reference event"),
1372 	OPT_BOOLEAN(0, "stitch-lbr", &report.stitch_lbr,
1373 		    "Enable LBR callgraph stitching approach"),
1374 	OPT_INTEGER(0, "socket-filter", &report.socket_filter,
1375 		    "only show processor socket that match with this filter"),
1376 	OPT_BOOLEAN(0, "raw-trace", &symbol_conf.raw_trace,
1377 		    "Show raw trace event output (do not use print fmt or plugins)"),
1378 	OPT_BOOLEAN(0, "hierarchy", &symbol_conf.report_hierarchy,
1379 		    "Show entries in a hierarchy"),
1380 	OPT_CALLBACK_DEFAULT(0, "stdio-color", NULL, "mode",
1381 			     "'always' (default), 'never' or 'auto' only applicable to --stdio mode",
1382 			     stdio__config_color, "always"),
1383 	OPT_STRING(0, "time", &report.time_str, "str",
1384 		   "Time span of interest (start,stop)"),
1385 	OPT_BOOLEAN(0, "inline", &symbol_conf.inline_name,
1386 		    "Show inline function"),
1387 	OPT_CALLBACK(0, "percent-type", &annotate_opts, "local-period",
1388 		     "Set percent type local/global-period/hits",
1389 		     annotate_parse_percent_type),
1390 	OPT_BOOLEAN(0, "ns", &symbol_conf.nanosecs, "Show times in nanosecs"),
1391 	OPT_CALLBACK(0, "time-quantum", &symbol_conf.time_quantum, "time (ms|us|ns|s)",
1392 		     "Set time quantum for time sort key (default 100ms)",
1393 		     parse_time_quantum),
1394 	OPTS_EVSWITCH(&report.evswitch),
1395 	OPT_BOOLEAN(0, "total-cycles", &report.total_cycles_mode,
1396 		    "Sort all blocks by 'Sampled Cycles%'"),
1397 	OPT_BOOLEAN(0, "disable-order", &report.disable_order,
1398 		    "Disable raw trace ordering"),
1399 	OPT_BOOLEAN(0, "skip-empty", &report.skip_empty,
1400 		    "Do not display empty (or dummy) events in the output"),
1401 	OPT_END()
1402 	};
1403 	struct perf_data data = {
1404 		.mode  = PERF_DATA_MODE_READ,
1405 	};
1406 	int ret = hists__init();
1407 	char sort_tmp[128];
1408 
1409 	if (ret < 0)
1410 		goto exit;
1411 
1412 	/*
1413 	 * tasks_mode require access to exited threads to list those that are in
1414 	 * the data file. Off-cpu events are synthesized after other events and
1415 	 * reference exited threads.
1416 	 */
1417 	symbol_conf.keep_exited_threads = true;
1418 
1419 	annotation_options__init(&annotate_opts);
1420 
1421 	ret = perf_config(report__config, &report);
1422 	if (ret)
1423 		goto exit;
1424 
1425 	argc = parse_options(argc, argv, options, report_usage, 0);
1426 	if (argc) {
1427 		/*
1428 		 * Special case: if there's an argument left then assume that
1429 		 * it's a symbol filter:
1430 		 */
1431 		if (argc > 1)
1432 			usage_with_options(report_usage, options);
1433 
1434 		report.symbol_filter_str = argv[0];
1435 	}
1436 
1437 	if (disassembler_style) {
1438 		annotate_opts.disassembler_style = strdup(disassembler_style);
1439 		if (!annotate_opts.disassembler_style)
1440 			return -ENOMEM;
1441 	}
1442 	if (objdump_path) {
1443 		annotate_opts.objdump_path = strdup(objdump_path);
1444 		if (!annotate_opts.objdump_path)
1445 			return -ENOMEM;
1446 	}
1447 	if (addr2line_path) {
1448 		symbol_conf.addr2line_path = strdup(addr2line_path);
1449 		if (!symbol_conf.addr2line_path)
1450 			return -ENOMEM;
1451 	}
1452 
1453 	if (annotate_check_args(&annotate_opts) < 0) {
1454 		ret = -EINVAL;
1455 		goto exit;
1456 	}
1457 
1458 	if (report.mmaps_mode)
1459 		report.tasks_mode = true;
1460 
1461 	if (dump_trace && report.disable_order)
1462 		report.tool.ordered_events = false;
1463 
1464 	if (quiet)
1465 		perf_quiet_option();
1466 
1467 	ret = symbol__validate_sym_arguments();
1468 	if (ret)
1469 		goto exit;
1470 
1471 	if (report.inverted_callchain)
1472 		callchain_param.order = ORDER_CALLER;
1473 	if (symbol_conf.cumulate_callchain && !callchain_param.order_set)
1474 		callchain_param.order = ORDER_CALLER;
1475 
1476 	if ((itrace_synth_opts.callchain || itrace_synth_opts.add_callchain) &&
1477 	    (int)itrace_synth_opts.callchain_sz > report.max_stack)
1478 		report.max_stack = itrace_synth_opts.callchain_sz;
1479 
1480 	if (!input_name || !strlen(input_name)) {
1481 		if (!fstat(STDIN_FILENO, &st) && S_ISFIFO(st.st_mode))
1482 			input_name = "-";
1483 		else
1484 			input_name = "perf.data";
1485 	}
1486 
1487 	data.path  = input_name;
1488 	data.force = symbol_conf.force;
1489 
1490 repeat:
1491 	session = perf_session__new(&data, &report.tool);
1492 	if (IS_ERR(session)) {
1493 		ret = PTR_ERR(session);
1494 		goto exit;
1495 	}
1496 
1497 	ret = evswitch__init(&report.evswitch, session->evlist, stderr);
1498 	if (ret)
1499 		goto exit;
1500 
1501 	if (zstd_init(&(session->zstd_data), 0) < 0)
1502 		pr_warning("Decompression initialization failed. Reported data may be incomplete.\n");
1503 
1504 	if (report.queue_size) {
1505 		ordered_events__set_alloc_size(&session->ordered_events,
1506 					       report.queue_size);
1507 	}
1508 
1509 	session->itrace_synth_opts = &itrace_synth_opts;
1510 
1511 	report.session = session;
1512 
1513 	has_br_stack = perf_header__has_feat(&session->header,
1514 					     HEADER_BRANCH_STACK);
1515 	if (evlist__combined_sample_type(session->evlist) & PERF_SAMPLE_STACK_USER)
1516 		has_br_stack = false;
1517 
1518 	setup_forced_leader(&report, session->evlist);
1519 
1520 	if (symbol_conf.group_sort_idx && evlist__nr_groups(session->evlist) == 0) {
1521 		parse_options_usage(NULL, options, "group-sort-idx", 0);
1522 		ret = -EINVAL;
1523 		goto error;
1524 	}
1525 
1526 	if (itrace_synth_opts.last_branch || itrace_synth_opts.add_last_branch)
1527 		has_br_stack = true;
1528 
1529 	if (has_br_stack && branch_call_mode)
1530 		symbol_conf.show_branchflag_count = true;
1531 
1532 	memset(&report.brtype_stat, 0, sizeof(struct branch_type_stat));
1533 
1534 	/*
1535 	 * Branch mode is a tristate:
1536 	 * -1 means default, so decide based on the file having branch data.
1537 	 * 0/1 means the user chose a mode.
1538 	 */
1539 	if (((branch_mode == -1 && has_br_stack) || branch_mode == 1) &&
1540 	    !branch_call_mode) {
1541 		sort__mode = SORT_MODE__BRANCH;
1542 		symbol_conf.cumulate_callchain = false;
1543 	}
1544 	if (branch_call_mode) {
1545 		callchain_param.key = CCKEY_ADDRESS;
1546 		callchain_param.branch_callstack = true;
1547 		symbol_conf.use_callchain = true;
1548 		callchain_register_param(&callchain_param);
1549 		if (sort_order == NULL)
1550 			sort_order = "srcline,symbol,dso";
1551 	}
1552 
1553 	if (report.mem_mode) {
1554 		if (sort__mode == SORT_MODE__BRANCH) {
1555 			pr_err("branch and mem mode incompatible\n");
1556 			goto error;
1557 		}
1558 		sort__mode = SORT_MODE__MEMORY;
1559 		symbol_conf.cumulate_callchain = false;
1560 	}
1561 
1562 	if (symbol_conf.report_hierarchy) {
1563 		/* disable incompatible options */
1564 		symbol_conf.cumulate_callchain = false;
1565 
1566 		if (field_order) {
1567 			pr_err("Error: --hierarchy and --fields options cannot be used together\n");
1568 			parse_options_usage(report_usage, options, "F", 1);
1569 			parse_options_usage(NULL, options, "hierarchy", 0);
1570 			goto error;
1571 		}
1572 
1573 		perf_hpp_list.need_collapse = true;
1574 	}
1575 
1576 	if (report.use_stdio)
1577 		use_browser = 0;
1578 #ifdef HAVE_SLANG_SUPPORT
1579 	else if (report.use_tui)
1580 		use_browser = 1;
1581 #endif
1582 #ifdef HAVE_GTK2_SUPPORT
1583 	else if (report.use_gtk)
1584 		use_browser = 2;
1585 #endif
1586 
1587 	/* Force tty output for header output and per-thread stat. */
1588 	if (report.header || report.header_only || report.show_threads)
1589 		use_browser = 0;
1590 	if (report.header || report.header_only)
1591 		report.tool.show_feat_hdr = SHOW_FEAT_HEADER;
1592 	if (report.show_full_info)
1593 		report.tool.show_feat_hdr = SHOW_FEAT_HEADER_FULL_INFO;
1594 	if (report.stats_mode || report.tasks_mode)
1595 		use_browser = 0;
1596 	if (report.stats_mode && report.tasks_mode) {
1597 		pr_err("Error: --tasks and --mmaps can't be used together with --stats\n");
1598 		goto error;
1599 	}
1600 
1601 	if (report.total_cycles_mode) {
1602 		if (sort__mode != SORT_MODE__BRANCH)
1603 			report.total_cycles_mode = false;
1604 		else
1605 			sort_order = NULL;
1606 	}
1607 
1608 	if (strcmp(input_name, "-") != 0)
1609 		setup_browser(true);
1610 	else
1611 		use_browser = 0;
1612 
1613 	if (sort_order && strstr(sort_order, "ipc")) {
1614 		parse_options_usage(report_usage, options, "s", 1);
1615 		goto error;
1616 	}
1617 
1618 	if (sort_order && strstr(sort_order, "symbol")) {
1619 		if (sort__mode == SORT_MODE__BRANCH) {
1620 			snprintf(sort_tmp, sizeof(sort_tmp), "%s,%s",
1621 				 sort_order, "ipc_lbr");
1622 			report.symbol_ipc = true;
1623 		} else {
1624 			snprintf(sort_tmp, sizeof(sort_tmp), "%s,%s",
1625 				 sort_order, "ipc_null");
1626 		}
1627 
1628 		sort_order = sort_tmp;
1629 	}
1630 
1631 	if ((last_key != K_SWITCH_INPUT_DATA && last_key != K_RELOAD) &&
1632 	    (setup_sorting(session->evlist) < 0)) {
1633 		if (sort_order)
1634 			parse_options_usage(report_usage, options, "s", 1);
1635 		if (field_order)
1636 			parse_options_usage(sort_order ? NULL : report_usage,
1637 					    options, "F", 1);
1638 		goto error;
1639 	}
1640 
1641 	if ((report.header || report.header_only) && !quiet) {
1642 		perf_session__fprintf_info(session, stdout,
1643 					   report.show_full_info);
1644 		if (report.header_only) {
1645 			if (data.is_pipe) {
1646 				/*
1647 				 * we need to process first few records
1648 				 * which contains PERF_RECORD_HEADER_FEATURE.
1649 				 */
1650 				perf_session__process_events(session);
1651 			}
1652 			ret = 0;
1653 			goto error;
1654 		}
1655 	} else if (use_browser == 0 && !quiet &&
1656 		   !report.stats_mode && !report.tasks_mode) {
1657 		fputs("# To display the perf.data header info, please use --header/--header-only options.\n#\n",
1658 		      stdout);
1659 	}
1660 
1661 	/*
1662 	 * Only in the TUI browser we are doing integrated annotation,
1663 	 * so don't allocate extra space that won't be used in the stdio
1664 	 * implementation.
1665 	 */
1666 	if (ui__has_annotation() || report.symbol_ipc ||
1667 	    report.total_cycles_mode) {
1668 		ret = symbol__annotation_init();
1669 		if (ret < 0)
1670 			goto error;
1671 		/*
1672  		 * For searching by name on the "Browse map details".
1673  		 * providing it only in verbose mode not to bloat too
1674  		 * much struct symbol.
1675  		 */
1676 		if (verbose > 0) {
1677 			/*
1678 			 * XXX: Need to provide a less kludgy way to ask for
1679 			 * more space per symbol, the u32 is for the index on
1680 			 * the ui browser.
1681 			 * See symbol__browser_index.
1682 			 */
1683 			symbol_conf.priv_size += sizeof(u32);
1684 		}
1685 		annotation_config__init(&annotate_opts);
1686 	}
1687 
1688 	if (symbol__init(&session->header.env) < 0)
1689 		goto error;
1690 
1691 	if (report.time_str) {
1692 		ret = perf_time__parse_for_ranges(report.time_str, session,
1693 						  &report.ptime_range,
1694 						  &report.range_size,
1695 						  &report.range_num);
1696 		if (ret < 0)
1697 			goto error;
1698 
1699 		itrace_synth_opts__set_time_range(&itrace_synth_opts,
1700 						  report.ptime_range,
1701 						  report.range_num);
1702 	}
1703 
1704 #ifdef HAVE_LIBTRACEEVENT
1705 	if (session->tevent.pevent &&
1706 	    tep_set_function_resolver(session->tevent.pevent,
1707 				      machine__resolve_kernel_addr,
1708 				      &session->machines.host) < 0) {
1709 		pr_err("%s: failed to set libtraceevent function resolver\n",
1710 		       __func__);
1711 		return -1;
1712 	}
1713 #endif
1714 	sort__setup_elide(stdout);
1715 
1716 	ret = __cmd_report(&report);
1717 	if (ret == K_SWITCH_INPUT_DATA || ret == K_RELOAD) {
1718 		perf_session__delete(session);
1719 		last_key = K_SWITCH_INPUT_DATA;
1720 		goto repeat;
1721 	} else
1722 		ret = 0;
1723 
1724 error:
1725 	if (report.ptime_range) {
1726 		itrace_synth_opts__clear_time_range(&itrace_synth_opts);
1727 		zfree(&report.ptime_range);
1728 	}
1729 
1730 	if (report.block_reports) {
1731 		block_info__free_report(report.block_reports,
1732 					report.nr_block_reports);
1733 		report.block_reports = NULL;
1734 	}
1735 
1736 	zstd_fini(&(session->zstd_data));
1737 	perf_session__delete(session);
1738 exit:
1739 	annotation_options__exit(&annotate_opts);
1740 	free(sort_order_help);
1741 	free(field_order_help);
1742 	return ret;
1743 }
1744