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