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 
report__config(const char * var,const char * value,void * cb)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 
hist_iter__report_callback(struct hist_entry_iter * iter,struct addr_location * al,bool single,void * arg)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 
hist_iter__branch_callback(struct hist_entry_iter * iter,struct addr_location * al __maybe_unused,bool single __maybe_unused,void * arg)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 
setup_forced_leader(struct report * report,struct evlist * evlist)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 
process_feature_event(struct perf_session * session,union perf_event * event)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 
process_sample_event(struct perf_tool * tool,union perf_event * event,struct perf_sample * sample,struct evsel * evsel,struct machine * machine)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 
process_read_event(struct perf_tool * tool,union perf_event * event,struct perf_sample * sample __maybe_unused,struct evsel * evsel,struct machine * machine __maybe_unused)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 */
report__setup_sample_type(struct report * rep)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 
sig_handler(int sig __maybe_unused)455 static void sig_handler(int sig __maybe_unused)
456 {
457 	session_done = 1;
458 }
459 
hists__fprintf_nr_sample_events(struct hists * hists,struct report * rep,const char * evname,FILE * fp)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 
evlist__tui_block_hists_browse(struct evlist * evlist,struct report * rep)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 
evlist__tty_browse_hists(struct evlist * evlist,struct report * rep,const char * help)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 
report__warn_kptr_restrict(const struct report * rep)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 
report__gtk_browse_hists(struct report * rep,const char * help)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 
report__browse_hists(struct report * rep)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 
report__collapse_hists(struct report * rep)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 
hists__resort_cb(struct hist_entry * he,void * arg)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 
report__output_resort(struct report * rep)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 
count_sample_event(struct perf_tool * tool __maybe_unused,union perf_event * event __maybe_unused,struct perf_sample * sample __maybe_unused,struct evsel * evsel,struct machine * machine __maybe_unused)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 
count_lost_samples_event(struct perf_tool * tool,union perf_event * event,struct perf_sample * sample,struct machine * machine __maybe_unused)755 static int count_lost_samples_event(struct perf_tool *tool,
756 				    union perf_event *event,
757 				    struct perf_sample *sample,
758 				    struct machine *machine __maybe_unused)
759 {
760 	struct report *rep = container_of(tool, struct report, tool);
761 	struct evsel *evsel;
762 
763 	evsel = evlist__id2evsel(rep->session->evlist, sample->id);
764 	if (evsel) {
765 		hists__inc_nr_lost_samples(evsel__hists(evsel),
766 					   event->lost_samples.lost);
767 	}
768 	return 0;
769 }
770 
771 static int process_attr(struct perf_tool *tool __maybe_unused,
772 			union perf_event *event,
773 			struct evlist **pevlist);
774 
stats_setup(struct report * rep)775 static void stats_setup(struct report *rep)
776 {
777 	memset(&rep->tool, 0, sizeof(rep->tool));
778 	rep->tool.attr = process_attr;
779 	rep->tool.sample = count_sample_event;
780 	rep->tool.lost_samples = count_lost_samples_event;
781 	rep->tool.no_warn = true;
782 }
783 
stats_print(struct report * rep)784 static int stats_print(struct report *rep)
785 {
786 	struct perf_session *session = rep->session;
787 
788 	perf_session__fprintf_nr_events(session, stdout, rep->skip_empty);
789 	evlist__fprintf_nr_events(session->evlist, stdout, rep->skip_empty);
790 	return 0;
791 }
792 
tasks_setup(struct report * rep)793 static void tasks_setup(struct report *rep)
794 {
795 	memset(&rep->tool, 0, sizeof(rep->tool));
796 	rep->tool.ordered_events = true;
797 	if (rep->mmaps_mode) {
798 		rep->tool.mmap = perf_event__process_mmap;
799 		rep->tool.mmap2 = perf_event__process_mmap2;
800 	}
801 	rep->tool.attr = process_attr;
802 	rep->tool.comm = perf_event__process_comm;
803 	rep->tool.exit = perf_event__process_exit;
804 	rep->tool.fork = perf_event__process_fork;
805 	rep->tool.no_warn = true;
806 }
807 
808 struct task {
809 	struct thread		*thread;
810 	struct list_head	 list;
811 	struct list_head	 children;
812 };
813 
tasks_list(struct task * task,struct machine * machine)814 static struct task *tasks_list(struct task *task, struct machine *machine)
815 {
816 	struct thread *parent_thread, *thread = task->thread;
817 	struct task   *parent_task;
818 
819 	/* Already listed. */
820 	if (!list_empty(&task->list))
821 		return NULL;
822 
823 	/* Last one in the chain. */
824 	if (thread->ppid == -1)
825 		return task;
826 
827 	parent_thread = machine__find_thread(machine, -1, thread->ppid);
828 	if (!parent_thread)
829 		return ERR_PTR(-ENOENT);
830 
831 	parent_task = thread__priv(parent_thread);
832 	list_add_tail(&task->list, &parent_task->children);
833 	return tasks_list(parent_task, machine);
834 }
835 
maps__fprintf_task(struct maps * maps,int indent,FILE * fp)836 static size_t maps__fprintf_task(struct maps *maps, int indent, FILE *fp)
837 {
838 	size_t printed = 0;
839 	struct map *map;
840 
841 	maps__for_each_entry(maps, map) {
842 		printed += fprintf(fp, "%*s  %" PRIx64 "-%" PRIx64 " %c%c%c%c %08" PRIx64 " %" PRIu64 " %s\n",
843 				   indent, "", map->start, map->end,
844 				   map->prot & PROT_READ ? 'r' : '-',
845 				   map->prot & PROT_WRITE ? 'w' : '-',
846 				   map->prot & PROT_EXEC ? 'x' : '-',
847 				   map->flags & MAP_SHARED ? 's' : 'p',
848 				   map->pgoff,
849 				   map->dso->id.ino, map->dso->name);
850 	}
851 
852 	return printed;
853 }
854 
task__print_level(struct task * task,FILE * fp,int level)855 static void task__print_level(struct task *task, FILE *fp, int level)
856 {
857 	struct thread *thread = task->thread;
858 	struct task *child;
859 	int comm_indent = fprintf(fp, "  %8d %8d %8d |%*s",
860 				  thread->pid_, thread->tid, thread->ppid,
861 				  level, "");
862 
863 	fprintf(fp, "%s\n", thread__comm_str(thread));
864 
865 	maps__fprintf_task(thread->maps, comm_indent, fp);
866 
867 	if (!list_empty(&task->children)) {
868 		list_for_each_entry(child, &task->children, list)
869 			task__print_level(child, fp, level + 1);
870 	}
871 }
872 
tasks_print(struct report * rep,FILE * fp)873 static int tasks_print(struct report *rep, FILE *fp)
874 {
875 	struct perf_session *session = rep->session;
876 	struct machine      *machine = &session->machines.host;
877 	struct task *tasks, *task;
878 	unsigned int nr = 0, itask = 0, i;
879 	struct rb_node *nd;
880 	LIST_HEAD(list);
881 
882 	/*
883 	 * No locking needed while accessing machine->threads,
884 	 * because --tasks is single threaded command.
885 	 */
886 
887 	/* Count all the threads. */
888 	for (i = 0; i < THREADS__TABLE_SIZE; i++)
889 		nr += machine->threads[i].nr;
890 
891 	tasks = malloc(sizeof(*tasks) * nr);
892 	if (!tasks)
893 		return -ENOMEM;
894 
895 	for (i = 0; i < THREADS__TABLE_SIZE; i++) {
896 		struct threads *threads = &machine->threads[i];
897 
898 		for (nd = rb_first_cached(&threads->entries); nd;
899 		     nd = rb_next(nd)) {
900 			task = tasks + itask++;
901 
902 			task->thread = rb_entry(nd, struct thread, rb_node);
903 			INIT_LIST_HEAD(&task->children);
904 			INIT_LIST_HEAD(&task->list);
905 			thread__set_priv(task->thread, task);
906 		}
907 	}
908 
909 	/*
910 	 * Iterate every task down to the unprocessed parent
911 	 * and link all in task children list. Task with no
912 	 * parent is added into 'list'.
913 	 */
914 	for (itask = 0; itask < nr; itask++) {
915 		task = tasks + itask;
916 
917 		if (!list_empty(&task->list))
918 			continue;
919 
920 		task = tasks_list(task, machine);
921 		if (IS_ERR(task)) {
922 			pr_err("Error: failed to process tasks\n");
923 			free(tasks);
924 			return PTR_ERR(task);
925 		}
926 
927 		if (task)
928 			list_add_tail(&task->list, &list);
929 	}
930 
931 	fprintf(fp, "# %8s %8s %8s  %s\n", "pid", "tid", "ppid", "comm");
932 
933 	list_for_each_entry(task, &list, list)
934 		task__print_level(task, fp, 0);
935 
936 	free(tasks);
937 	return 0;
938 }
939 
__cmd_report(struct report * rep)940 static int __cmd_report(struct report *rep)
941 {
942 	int ret;
943 	struct perf_session *session = rep->session;
944 	struct evsel *pos;
945 	struct perf_data *data = session->data;
946 
947 	signal(SIGINT, sig_handler);
948 
949 	if (rep->cpu_list) {
950 		ret = perf_session__cpu_bitmap(session, rep->cpu_list,
951 					       rep->cpu_bitmap);
952 		if (ret) {
953 			ui__error("failed to set cpu bitmap\n");
954 			return ret;
955 		}
956 		session->itrace_synth_opts->cpu_bitmap = rep->cpu_bitmap;
957 	}
958 
959 	if (rep->show_threads) {
960 		ret = perf_read_values_init(&rep->show_threads_values);
961 		if (ret)
962 			return ret;
963 	}
964 
965 	ret = report__setup_sample_type(rep);
966 	if (ret) {
967 		/* report__setup_sample_type() already showed error message */
968 		return ret;
969 	}
970 
971 	if (rep->stats_mode)
972 		stats_setup(rep);
973 
974 	if (rep->tasks_mode)
975 		tasks_setup(rep);
976 
977 	ret = perf_session__process_events(session);
978 	if (ret) {
979 		ui__error("failed to process sample\n");
980 		return ret;
981 	}
982 
983 	evlist__check_mem_load_aux(session->evlist);
984 
985 	if (rep->stats_mode)
986 		return stats_print(rep);
987 
988 	if (rep->tasks_mode)
989 		return tasks_print(rep, stdout);
990 
991 	report__warn_kptr_restrict(rep);
992 
993 	evlist__for_each_entry(session->evlist, pos)
994 		rep->nr_entries += evsel__hists(pos)->nr_entries;
995 
996 	if (use_browser == 0) {
997 		if (verbose > 3)
998 			perf_session__fprintf(session, stdout);
999 
1000 		if (verbose > 2)
1001 			perf_session__fprintf_dsos(session, stdout);
1002 
1003 		if (dump_trace) {
1004 			perf_session__fprintf_nr_events(session, stdout,
1005 							rep->skip_empty);
1006 			evlist__fprintf_nr_events(session->evlist, stdout,
1007 						  rep->skip_empty);
1008 			return 0;
1009 		}
1010 	}
1011 
1012 	ret = report__collapse_hists(rep);
1013 	if (ret) {
1014 		ui__error("failed to process hist entry\n");
1015 		return ret;
1016 	}
1017 
1018 	if (session_done())
1019 		return 0;
1020 
1021 	/*
1022 	 * recalculate number of entries after collapsing since it
1023 	 * might be changed during the collapse phase.
1024 	 */
1025 	rep->nr_entries = 0;
1026 	evlist__for_each_entry(session->evlist, pos)
1027 		rep->nr_entries += evsel__hists(pos)->nr_entries;
1028 
1029 	if (rep->nr_entries == 0) {
1030 		ui__error("The %s data has no samples!\n", data->path);
1031 		return 0;
1032 	}
1033 
1034 	report__output_resort(rep);
1035 
1036 	if (rep->total_cycles_mode) {
1037 		int block_hpps[6] = {
1038 			PERF_HPP_REPORT__BLOCK_TOTAL_CYCLES_PCT,
1039 			PERF_HPP_REPORT__BLOCK_LBR_CYCLES,
1040 			PERF_HPP_REPORT__BLOCK_CYCLES_PCT,
1041 			PERF_HPP_REPORT__BLOCK_AVG_CYCLES,
1042 			PERF_HPP_REPORT__BLOCK_RANGE,
1043 			PERF_HPP_REPORT__BLOCK_DSO,
1044 		};
1045 
1046 		rep->block_reports = block_info__create_report(session->evlist,
1047 							       rep->total_cycles,
1048 							       block_hpps, 6,
1049 							       &rep->nr_block_reports);
1050 		if (!rep->block_reports)
1051 			return -1;
1052 	}
1053 
1054 	return report__browse_hists(rep);
1055 }
1056 
1057 static int
report_parse_callchain_opt(const struct option * opt,const char * arg,int unset)1058 report_parse_callchain_opt(const struct option *opt, const char *arg, int unset)
1059 {
1060 	struct callchain_param *callchain = opt->value;
1061 
1062 	callchain->enabled = !unset;
1063 	/*
1064 	 * --no-call-graph
1065 	 */
1066 	if (unset) {
1067 		symbol_conf.use_callchain = false;
1068 		callchain->mode = CHAIN_NONE;
1069 		return 0;
1070 	}
1071 
1072 	return parse_callchain_report_opt(arg);
1073 }
1074 
1075 static int
parse_time_quantum(const struct option * opt,const char * arg,int unset __maybe_unused)1076 parse_time_quantum(const struct option *opt, const char *arg,
1077 		   int unset __maybe_unused)
1078 {
1079 	unsigned long *time_q = opt->value;
1080 	char *end;
1081 
1082 	*time_q = strtoul(arg, &end, 0);
1083 	if (end == arg)
1084 		goto parse_err;
1085 	if (*time_q == 0) {
1086 		pr_err("time quantum cannot be 0");
1087 		return -1;
1088 	}
1089 	end = skip_spaces(end);
1090 	if (*end == 0)
1091 		return 0;
1092 	if (!strcmp(end, "s")) {
1093 		*time_q *= NSEC_PER_SEC;
1094 		return 0;
1095 	}
1096 	if (!strcmp(end, "ms")) {
1097 		*time_q *= NSEC_PER_MSEC;
1098 		return 0;
1099 	}
1100 	if (!strcmp(end, "us")) {
1101 		*time_q *= NSEC_PER_USEC;
1102 		return 0;
1103 	}
1104 	if (!strcmp(end, "ns"))
1105 		return 0;
1106 parse_err:
1107 	pr_err("Cannot parse time quantum `%s'\n", arg);
1108 	return -1;
1109 }
1110 
1111 int
report_parse_ignore_callees_opt(const struct option * opt __maybe_unused,const char * arg,int unset __maybe_unused)1112 report_parse_ignore_callees_opt(const struct option *opt __maybe_unused,
1113 				const char *arg, int unset __maybe_unused)
1114 {
1115 	if (arg) {
1116 		int err = regcomp(&ignore_callees_regex, arg, REG_EXTENDED);
1117 		if (err) {
1118 			char buf[BUFSIZ];
1119 			regerror(err, &ignore_callees_regex, buf, sizeof(buf));
1120 			pr_err("Invalid --ignore-callees regex: %s\n%s", arg, buf);
1121 			return -1;
1122 		}
1123 		have_ignore_callees = 1;
1124 	}
1125 
1126 	return 0;
1127 }
1128 
1129 static int
parse_branch_mode(const struct option * opt,const char * str __maybe_unused,int unset)1130 parse_branch_mode(const struct option *opt,
1131 		  const char *str __maybe_unused, int unset)
1132 {
1133 	int *branch_mode = opt->value;
1134 
1135 	*branch_mode = !unset;
1136 	return 0;
1137 }
1138 
1139 static int
parse_percent_limit(const struct option * opt,const char * str,int unset __maybe_unused)1140 parse_percent_limit(const struct option *opt, const char *str,
1141 		    int unset __maybe_unused)
1142 {
1143 	struct report *rep = opt->value;
1144 	double pcnt = strtof(str, NULL);
1145 
1146 	rep->min_percent = pcnt;
1147 	callchain_param.min_percent = pcnt;
1148 	return 0;
1149 }
1150 
process_attr(struct perf_tool * tool __maybe_unused,union perf_event * event,struct evlist ** pevlist)1151 static int process_attr(struct perf_tool *tool __maybe_unused,
1152 			union perf_event *event,
1153 			struct evlist **pevlist)
1154 {
1155 	u64 sample_type;
1156 	int err;
1157 
1158 	err = perf_event__process_attr(tool, event, pevlist);
1159 	if (err)
1160 		return err;
1161 
1162 	/*
1163 	 * Check if we need to enable callchains based
1164 	 * on events sample_type.
1165 	 */
1166 	sample_type = evlist__combined_sample_type(*pevlist);
1167 	callchain_param_setup(sample_type, perf_env__arch((*pevlist)->env));
1168 	return 0;
1169 }
1170 
cmd_report(int argc,const char ** argv)1171 int cmd_report(int argc, const char **argv)
1172 {
1173 	struct perf_session *session;
1174 	struct itrace_synth_opts itrace_synth_opts = { .set = 0, };
1175 	struct stat st;
1176 	bool has_br_stack = false;
1177 	int branch_mode = -1;
1178 	int last_key = 0;
1179 	bool branch_call_mode = false;
1180 #define CALLCHAIN_DEFAULT_OPT  "graph,0.5,caller,function,percent"
1181 	static const char report_callchain_help[] = "Display call graph (stack chain/backtrace):\n\n"
1182 						    CALLCHAIN_REPORT_HELP
1183 						    "\n\t\t\t\tDefault: " CALLCHAIN_DEFAULT_OPT;
1184 	char callchain_default_opt[] = CALLCHAIN_DEFAULT_OPT;
1185 	const char * const report_usage[] = {
1186 		"perf report [<options>]",
1187 		NULL
1188 	};
1189 	struct report report = {
1190 		.tool = {
1191 			.sample		 = process_sample_event,
1192 			.mmap		 = perf_event__process_mmap,
1193 			.mmap2		 = perf_event__process_mmap2,
1194 			.comm		 = perf_event__process_comm,
1195 			.namespaces	 = perf_event__process_namespaces,
1196 			.cgroup		 = perf_event__process_cgroup,
1197 			.exit		 = perf_event__process_exit,
1198 			.fork		 = perf_event__process_fork,
1199 			.lost		 = perf_event__process_lost,
1200 			.read		 = process_read_event,
1201 			.attr		 = process_attr,
1202 			.tracing_data	 = perf_event__process_tracing_data,
1203 			.build_id	 = perf_event__process_build_id,
1204 			.id_index	 = perf_event__process_id_index,
1205 			.auxtrace_info	 = perf_event__process_auxtrace_info,
1206 			.auxtrace	 = perf_event__process_auxtrace,
1207 			.event_update	 = perf_event__process_event_update,
1208 			.feature	 = process_feature_event,
1209 			.ordered_events	 = true,
1210 			.ordering_requires_timestamps = true,
1211 		},
1212 		.max_stack		 = PERF_MAX_STACK_DEPTH,
1213 		.pretty_printing_style	 = "normal",
1214 		.socket_filter		 = -1,
1215 		.annotation_opts	 = annotation__default_options,
1216 		.skip_empty		 = true,
1217 	};
1218 	char *sort_order_help = sort_help("sort by key(s):");
1219 	char *field_order_help = sort_help("output field(s): overhead period sample ");
1220 	const struct option options[] = {
1221 	OPT_STRING('i', "input", &input_name, "file",
1222 		    "input file name"),
1223 	OPT_INCR('v', "verbose", &verbose,
1224 		    "be more verbose (show symbol address, etc)"),
1225 	OPT_BOOLEAN('q', "quiet", &quiet, "Do not show any warnings or messages"),
1226 	OPT_BOOLEAN('D', "dump-raw-trace", &dump_trace,
1227 		    "dump raw trace in ASCII"),
1228 	OPT_BOOLEAN(0, "stats", &report.stats_mode, "Display event stats"),
1229 	OPT_BOOLEAN(0, "tasks", &report.tasks_mode, "Display recorded tasks"),
1230 	OPT_BOOLEAN(0, "mmaps", &report.mmaps_mode, "Display recorded tasks memory maps"),
1231 	OPT_STRING('k', "vmlinux", &symbol_conf.vmlinux_name,
1232 		   "file", "vmlinux pathname"),
1233 	OPT_BOOLEAN(0, "ignore-vmlinux", &symbol_conf.ignore_vmlinux,
1234                     "don't load vmlinux even if found"),
1235 	OPT_STRING(0, "kallsyms", &symbol_conf.kallsyms_name,
1236 		   "file", "kallsyms pathname"),
1237 	OPT_BOOLEAN('f', "force", &symbol_conf.force, "don't complain, do it"),
1238 	OPT_BOOLEAN('m', "modules", &symbol_conf.use_modules,
1239 		    "load module symbols - WARNING: use only with -k and LIVE kernel"),
1240 	OPT_BOOLEAN('n', "show-nr-samples", &symbol_conf.show_nr_samples,
1241 		    "Show a column with the number of samples"),
1242 	OPT_BOOLEAN('T', "threads", &report.show_threads,
1243 		    "Show per-thread event counters"),
1244 	OPT_STRING(0, "pretty", &report.pretty_printing_style, "key",
1245 		   "pretty printing style key: normal raw"),
1246 #ifdef HAVE_SLANG_SUPPORT
1247 	OPT_BOOLEAN(0, "tui", &report.use_tui, "Use the TUI interface"),
1248 #endif
1249 #ifdef HAVE_GTK2_SUPPORT
1250 	OPT_BOOLEAN(0, "gtk", &report.use_gtk, "Use the GTK2 interface"),
1251 #endif
1252 	OPT_BOOLEAN(0, "stdio", &report.use_stdio,
1253 		    "Use the stdio interface"),
1254 	OPT_BOOLEAN(0, "header", &report.header, "Show data header."),
1255 	OPT_BOOLEAN(0, "header-only", &report.header_only,
1256 		    "Show only data header."),
1257 	OPT_STRING('s', "sort", &sort_order, "key[,key2...]",
1258 		   sort_order_help),
1259 	OPT_STRING('F', "fields", &field_order, "key[,keys...]",
1260 		   field_order_help),
1261 	OPT_BOOLEAN(0, "show-cpu-utilization", &symbol_conf.show_cpu_utilization,
1262 		    "Show sample percentage for different cpu modes"),
1263 	OPT_BOOLEAN_FLAG(0, "showcpuutilization", &symbol_conf.show_cpu_utilization,
1264 		    "Show sample percentage for different cpu modes", PARSE_OPT_HIDDEN),
1265 	OPT_STRING('p', "parent", &parent_pattern, "regex",
1266 		   "regex filter to identify parent, see: '--sort parent'"),
1267 	OPT_BOOLEAN('x', "exclude-other", &symbol_conf.exclude_other,
1268 		    "Only display entries with parent-match"),
1269 	OPT_CALLBACK_DEFAULT('g', "call-graph", &callchain_param,
1270 			     "print_type,threshold[,print_limit],order,sort_key[,branch],value",
1271 			     report_callchain_help, &report_parse_callchain_opt,
1272 			     callchain_default_opt),
1273 	OPT_BOOLEAN(0, "children", &symbol_conf.cumulate_callchain,
1274 		    "Accumulate callchains of children and show total overhead as well. "
1275 		    "Enabled by default, use --no-children to disable."),
1276 	OPT_INTEGER(0, "max-stack", &report.max_stack,
1277 		    "Set the maximum stack depth when parsing the callchain, "
1278 		    "anything beyond the specified depth will be ignored. "
1279 		    "Default: kernel.perf_event_max_stack or " __stringify(PERF_MAX_STACK_DEPTH)),
1280 	OPT_BOOLEAN('G', "inverted", &report.inverted_callchain,
1281 		    "alias for inverted call graph"),
1282 	OPT_CALLBACK(0, "ignore-callees", NULL, "regex",
1283 		   "ignore callees of these functions in call graphs",
1284 		   report_parse_ignore_callees_opt),
1285 	OPT_STRING('d', "dsos", &symbol_conf.dso_list_str, "dso[,dso...]",
1286 		   "only consider symbols in these dsos"),
1287 	OPT_STRING('c', "comms", &symbol_conf.comm_list_str, "comm[,comm...]",
1288 		   "only consider symbols in these comms"),
1289 	OPT_STRING(0, "pid", &symbol_conf.pid_list_str, "pid[,pid...]",
1290 		   "only consider symbols in these pids"),
1291 	OPT_STRING(0, "tid", &symbol_conf.tid_list_str, "tid[,tid...]",
1292 		   "only consider symbols in these tids"),
1293 	OPT_STRING('S', "symbols", &symbol_conf.sym_list_str, "symbol[,symbol...]",
1294 		   "only consider these symbols"),
1295 	OPT_STRING(0, "symbol-filter", &report.symbol_filter_str, "filter",
1296 		   "only show symbols that (partially) match with this filter"),
1297 	OPT_STRING('w', "column-widths", &symbol_conf.col_width_list_str,
1298 		   "width[,width...]",
1299 		   "don't try to adjust column width, use these fixed values"),
1300 	OPT_STRING_NOEMPTY('t', "field-separator", &symbol_conf.field_sep, "separator",
1301 		   "separator for columns, no spaces will be added between "
1302 		   "columns '.' is reserved."),
1303 	OPT_BOOLEAN('U', "hide-unresolved", &symbol_conf.hide_unresolved,
1304 		    "Only display entries resolved to a symbol"),
1305 	OPT_CALLBACK(0, "symfs", NULL, "directory",
1306 		     "Look for files with symbols relative to this directory",
1307 		     symbol__config_symfs),
1308 	OPT_STRING('C', "cpu", &report.cpu_list, "cpu",
1309 		   "list of cpus to profile"),
1310 	OPT_BOOLEAN('I', "show-info", &report.show_full_info,
1311 		    "Display extended information about perf.data file"),
1312 	OPT_BOOLEAN(0, "source", &report.annotation_opts.annotate_src,
1313 		    "Interleave source code with assembly code (default)"),
1314 	OPT_BOOLEAN(0, "asm-raw", &report.annotation_opts.show_asm_raw,
1315 		    "Display raw encoding of assembly instructions (default)"),
1316 	OPT_STRING('M', "disassembler-style", &report.annotation_opts.disassembler_style, "disassembler style",
1317 		   "Specify disassembler style (e.g. -M intel for intel syntax)"),
1318 	OPT_STRING(0, "prefix", &report.annotation_opts.prefix, "prefix",
1319 		    "Add prefix to source file path names in programs (with --prefix-strip)"),
1320 	OPT_STRING(0, "prefix-strip", &report.annotation_opts.prefix_strip, "N",
1321 		    "Strip first N entries of source file path name in programs (with --prefix)"),
1322 	OPT_BOOLEAN(0, "show-total-period", &symbol_conf.show_total_period,
1323 		    "Show a column with the sum of periods"),
1324 	OPT_BOOLEAN_SET(0, "group", &symbol_conf.event_group, &report.group_set,
1325 		    "Show event group information together"),
1326 	OPT_INTEGER(0, "group-sort-idx", &symbol_conf.group_sort_idx,
1327 		    "Sort the output by the event at the index n in group. "
1328 		    "If n is invalid, sort by the first event. "
1329 		    "WARNING: should be used on grouped events."),
1330 	OPT_CALLBACK_NOOPT('b', "branch-stack", &branch_mode, "",
1331 		    "use branch records for per branch histogram filling",
1332 		    parse_branch_mode),
1333 	OPT_BOOLEAN(0, "branch-history", &branch_call_mode,
1334 		    "add last branch records to call history"),
1335 	OPT_STRING(0, "objdump", &report.annotation_opts.objdump_path, "path",
1336 		   "objdump binary to use for disassembly and annotations"),
1337 	OPT_BOOLEAN(0, "demangle", &symbol_conf.demangle,
1338 		    "Disable symbol demangling"),
1339 	OPT_BOOLEAN(0, "demangle-kernel", &symbol_conf.demangle_kernel,
1340 		    "Enable kernel symbol demangling"),
1341 	OPT_BOOLEAN(0, "mem-mode", &report.mem_mode, "mem access profile"),
1342 	OPT_INTEGER(0, "samples", &symbol_conf.res_sample,
1343 		    "Number of samples to save per histogram entry for individual browsing"),
1344 	OPT_CALLBACK(0, "percent-limit", &report, "percent",
1345 		     "Don't show entries under that percent", parse_percent_limit),
1346 	OPT_CALLBACK(0, "percentage", NULL, "relative|absolute",
1347 		     "how to display percentage of filtered entries", parse_filter_percentage),
1348 	OPT_CALLBACK_OPTARG(0, "itrace", &itrace_synth_opts, NULL, "opts",
1349 			    "Instruction Tracing options\n" ITRACE_HELP,
1350 			    itrace_parse_synth_opts),
1351 	OPT_BOOLEAN(0, "full-source-path", &srcline_full_filename,
1352 			"Show full source file name path for source lines"),
1353 	OPT_BOOLEAN(0, "show-ref-call-graph", &symbol_conf.show_ref_callgraph,
1354 		    "Show callgraph from reference event"),
1355 	OPT_BOOLEAN(0, "stitch-lbr", &report.stitch_lbr,
1356 		    "Enable LBR callgraph stitching approach"),
1357 	OPT_INTEGER(0, "socket-filter", &report.socket_filter,
1358 		    "only show processor socket that match with this filter"),
1359 	OPT_BOOLEAN(0, "raw-trace", &symbol_conf.raw_trace,
1360 		    "Show raw trace event output (do not use print fmt or plugins)"),
1361 	OPT_BOOLEAN(0, "hierarchy", &symbol_conf.report_hierarchy,
1362 		    "Show entries in a hierarchy"),
1363 	OPT_CALLBACK_DEFAULT(0, "stdio-color", NULL, "mode",
1364 			     "'always' (default), 'never' or 'auto' only applicable to --stdio mode",
1365 			     stdio__config_color, "always"),
1366 	OPT_STRING(0, "time", &report.time_str, "str",
1367 		   "Time span of interest (start,stop)"),
1368 	OPT_BOOLEAN(0, "inline", &symbol_conf.inline_name,
1369 		    "Show inline function"),
1370 	OPT_CALLBACK(0, "percent-type", &report.annotation_opts, "local-period",
1371 		     "Set percent type local/global-period/hits",
1372 		     annotate_parse_percent_type),
1373 	OPT_BOOLEAN(0, "ns", &symbol_conf.nanosecs, "Show times in nanosecs"),
1374 	OPT_CALLBACK(0, "time-quantum", &symbol_conf.time_quantum, "time (ms|us|ns|s)",
1375 		     "Set time quantum for time sort key (default 100ms)",
1376 		     parse_time_quantum),
1377 	OPTS_EVSWITCH(&report.evswitch),
1378 	OPT_BOOLEAN(0, "total-cycles", &report.total_cycles_mode,
1379 		    "Sort all blocks by 'Sampled Cycles%'"),
1380 	OPT_BOOLEAN(0, "disable-order", &report.disable_order,
1381 		    "Disable raw trace ordering"),
1382 	OPT_BOOLEAN(0, "skip-empty", &report.skip_empty,
1383 		    "Do not display empty (or dummy) events in the output"),
1384 	OPT_END()
1385 	};
1386 	struct perf_data data = {
1387 		.mode  = PERF_DATA_MODE_READ,
1388 	};
1389 	int ret = hists__init();
1390 	char sort_tmp[128];
1391 
1392 	if (ret < 0)
1393 		goto exit;
1394 
1395 	ret = perf_config(report__config, &report);
1396 	if (ret)
1397 		goto exit;
1398 
1399 	argc = parse_options(argc, argv, options, report_usage, 0);
1400 	if (argc) {
1401 		/*
1402 		 * Special case: if there's an argument left then assume that
1403 		 * it's a symbol filter:
1404 		 */
1405 		if (argc > 1)
1406 			usage_with_options(report_usage, options);
1407 
1408 		report.symbol_filter_str = argv[0];
1409 	}
1410 
1411 	if (annotate_check_args(&report.annotation_opts) < 0) {
1412 		ret = -EINVAL;
1413 		goto exit;
1414 	}
1415 
1416 	if (report.mmaps_mode)
1417 		report.tasks_mode = true;
1418 
1419 	if (dump_trace && report.disable_order)
1420 		report.tool.ordered_events = false;
1421 
1422 	if (quiet)
1423 		perf_quiet_option();
1424 
1425 	ret = symbol__validate_sym_arguments();
1426 	if (ret)
1427 		goto exit;
1428 
1429 	if (report.inverted_callchain)
1430 		callchain_param.order = ORDER_CALLER;
1431 	if (symbol_conf.cumulate_callchain && !callchain_param.order_set)
1432 		callchain_param.order = ORDER_CALLER;
1433 
1434 	if ((itrace_synth_opts.callchain || itrace_synth_opts.add_callchain) &&
1435 	    (int)itrace_synth_opts.callchain_sz > report.max_stack)
1436 		report.max_stack = itrace_synth_opts.callchain_sz;
1437 
1438 	if (!input_name || !strlen(input_name)) {
1439 		if (!fstat(STDIN_FILENO, &st) && S_ISFIFO(st.st_mode))
1440 			input_name = "-";
1441 		else
1442 			input_name = "perf.data";
1443 	}
1444 
1445 	data.path  = input_name;
1446 	data.force = symbol_conf.force;
1447 
1448 repeat:
1449 	session = perf_session__new(&data, &report.tool);
1450 	if (IS_ERR(session)) {
1451 		ret = PTR_ERR(session);
1452 		goto exit;
1453 	}
1454 
1455 	ret = evswitch__init(&report.evswitch, session->evlist, stderr);
1456 	if (ret)
1457 		goto exit;
1458 
1459 	if (zstd_init(&(session->zstd_data), 0) < 0)
1460 		pr_warning("Decompression initialization failed. Reported data may be incomplete.\n");
1461 
1462 	if (report.queue_size) {
1463 		ordered_events__set_alloc_size(&session->ordered_events,
1464 					       report.queue_size);
1465 	}
1466 
1467 	session->itrace_synth_opts = &itrace_synth_opts;
1468 
1469 	report.session = session;
1470 
1471 	has_br_stack = perf_header__has_feat(&session->header,
1472 					     HEADER_BRANCH_STACK);
1473 	if (evlist__combined_sample_type(session->evlist) & PERF_SAMPLE_STACK_USER)
1474 		has_br_stack = false;
1475 
1476 	setup_forced_leader(&report, session->evlist);
1477 
1478 	if (symbol_conf.group_sort_idx && !session->evlist->core.nr_groups) {
1479 		parse_options_usage(NULL, options, "group-sort-idx", 0);
1480 		ret = -EINVAL;
1481 		goto error;
1482 	}
1483 
1484 	if (itrace_synth_opts.last_branch || itrace_synth_opts.add_last_branch)
1485 		has_br_stack = true;
1486 
1487 	if (has_br_stack && branch_call_mode)
1488 		symbol_conf.show_branchflag_count = true;
1489 
1490 	memset(&report.brtype_stat, 0, sizeof(struct branch_type_stat));
1491 
1492 	/*
1493 	 * Branch mode is a tristate:
1494 	 * -1 means default, so decide based on the file having branch data.
1495 	 * 0/1 means the user chose a mode.
1496 	 */
1497 	if (((branch_mode == -1 && has_br_stack) || branch_mode == 1) &&
1498 	    !branch_call_mode) {
1499 		sort__mode = SORT_MODE__BRANCH;
1500 		symbol_conf.cumulate_callchain = false;
1501 	}
1502 	if (branch_call_mode) {
1503 		callchain_param.key = CCKEY_ADDRESS;
1504 		callchain_param.branch_callstack = true;
1505 		symbol_conf.use_callchain = true;
1506 		callchain_register_param(&callchain_param);
1507 		if (sort_order == NULL)
1508 			sort_order = "srcline,symbol,dso";
1509 	}
1510 
1511 	if (report.mem_mode) {
1512 		if (sort__mode == SORT_MODE__BRANCH) {
1513 			pr_err("branch and mem mode incompatible\n");
1514 			goto error;
1515 		}
1516 		sort__mode = SORT_MODE__MEMORY;
1517 		symbol_conf.cumulate_callchain = false;
1518 	}
1519 
1520 	if (symbol_conf.report_hierarchy) {
1521 		/* disable incompatible options */
1522 		symbol_conf.cumulate_callchain = false;
1523 
1524 		if (field_order) {
1525 			pr_err("Error: --hierarchy and --fields options cannot be used together\n");
1526 			parse_options_usage(report_usage, options, "F", 1);
1527 			parse_options_usage(NULL, options, "hierarchy", 0);
1528 			goto error;
1529 		}
1530 
1531 		perf_hpp_list.need_collapse = true;
1532 	}
1533 
1534 	if (report.use_stdio)
1535 		use_browser = 0;
1536 #ifdef HAVE_SLANG_SUPPORT
1537 	else if (report.use_tui)
1538 		use_browser = 1;
1539 #endif
1540 #ifdef HAVE_GTK2_SUPPORT
1541 	else if (report.use_gtk)
1542 		use_browser = 2;
1543 #endif
1544 
1545 	/* Force tty output for header output and per-thread stat. */
1546 	if (report.header || report.header_only || report.show_threads)
1547 		use_browser = 0;
1548 	if (report.header || report.header_only)
1549 		report.tool.show_feat_hdr = SHOW_FEAT_HEADER;
1550 	if (report.show_full_info)
1551 		report.tool.show_feat_hdr = SHOW_FEAT_HEADER_FULL_INFO;
1552 	if (report.stats_mode || report.tasks_mode)
1553 		use_browser = 0;
1554 	if (report.stats_mode && report.tasks_mode) {
1555 		pr_err("Error: --tasks and --mmaps can't be used together with --stats\n");
1556 		goto error;
1557 	}
1558 
1559 	if (report.total_cycles_mode) {
1560 		if (sort__mode != SORT_MODE__BRANCH)
1561 			report.total_cycles_mode = false;
1562 		else
1563 			sort_order = NULL;
1564 	}
1565 
1566 	if (strcmp(input_name, "-") != 0)
1567 		setup_browser(true);
1568 	else
1569 		use_browser = 0;
1570 
1571 	if (sort_order && strstr(sort_order, "ipc")) {
1572 		parse_options_usage(report_usage, options, "s", 1);
1573 		goto error;
1574 	}
1575 
1576 	if (sort_order && strstr(sort_order, "symbol")) {
1577 		if (sort__mode == SORT_MODE__BRANCH) {
1578 			snprintf(sort_tmp, sizeof(sort_tmp), "%s,%s",
1579 				 sort_order, "ipc_lbr");
1580 			report.symbol_ipc = true;
1581 		} else {
1582 			snprintf(sort_tmp, sizeof(sort_tmp), "%s,%s",
1583 				 sort_order, "ipc_null");
1584 		}
1585 
1586 		sort_order = sort_tmp;
1587 	}
1588 
1589 	if ((last_key != K_SWITCH_INPUT_DATA && last_key != K_RELOAD) &&
1590 	    (setup_sorting(session->evlist) < 0)) {
1591 		if (sort_order)
1592 			parse_options_usage(report_usage, options, "s", 1);
1593 		if (field_order)
1594 			parse_options_usage(sort_order ? NULL : report_usage,
1595 					    options, "F", 1);
1596 		goto error;
1597 	}
1598 
1599 	if ((report.header || report.header_only) && !quiet) {
1600 		perf_session__fprintf_info(session, stdout,
1601 					   report.show_full_info);
1602 		if (report.header_only) {
1603 			if (data.is_pipe) {
1604 				/*
1605 				 * we need to process first few records
1606 				 * which contains PERF_RECORD_HEADER_FEATURE.
1607 				 */
1608 				perf_session__process_events(session);
1609 			}
1610 			ret = 0;
1611 			goto error;
1612 		}
1613 	} else if (use_browser == 0 && !quiet &&
1614 		   !report.stats_mode && !report.tasks_mode) {
1615 		fputs("# To display the perf.data header info, please use --header/--header-only options.\n#\n",
1616 		      stdout);
1617 	}
1618 
1619 	/*
1620 	 * Only in the TUI browser we are doing integrated annotation,
1621 	 * so don't allocate extra space that won't be used in the stdio
1622 	 * implementation.
1623 	 */
1624 	if (ui__has_annotation() || report.symbol_ipc ||
1625 	    report.total_cycles_mode) {
1626 		ret = symbol__annotation_init();
1627 		if (ret < 0)
1628 			goto error;
1629 		/*
1630  		 * For searching by name on the "Browse map details".
1631  		 * providing it only in verbose mode not to bloat too
1632  		 * much struct symbol.
1633  		 */
1634 		if (verbose > 0) {
1635 			/*
1636 			 * XXX: Need to provide a less kludgy way to ask for
1637 			 * more space per symbol, the u32 is for the index on
1638 			 * the ui browser.
1639 			 * See symbol__browser_index.
1640 			 */
1641 			symbol_conf.priv_size += sizeof(u32);
1642 			symbol_conf.sort_by_name = true;
1643 		}
1644 		annotation_config__init(&report.annotation_opts);
1645 	}
1646 
1647 	if (symbol__init(&session->header.env) < 0)
1648 		goto error;
1649 
1650 	if (report.time_str) {
1651 		ret = perf_time__parse_for_ranges(report.time_str, session,
1652 						  &report.ptime_range,
1653 						  &report.range_size,
1654 						  &report.range_num);
1655 		if (ret < 0)
1656 			goto error;
1657 
1658 		itrace_synth_opts__set_time_range(&itrace_synth_opts,
1659 						  report.ptime_range,
1660 						  report.range_num);
1661 	}
1662 
1663 	if (session->tevent.pevent &&
1664 	    tep_set_function_resolver(session->tevent.pevent,
1665 				      machine__resolve_kernel_addr,
1666 				      &session->machines.host) < 0) {
1667 		pr_err("%s: failed to set libtraceevent function resolver\n",
1668 		       __func__);
1669 		return -1;
1670 	}
1671 
1672 	sort__setup_elide(stdout);
1673 
1674 	ret = __cmd_report(&report);
1675 	if (ret == K_SWITCH_INPUT_DATA || ret == K_RELOAD) {
1676 		perf_session__delete(session);
1677 		last_key = K_SWITCH_INPUT_DATA;
1678 		goto repeat;
1679 	} else
1680 		ret = 0;
1681 
1682 error:
1683 	if (report.ptime_range) {
1684 		itrace_synth_opts__clear_time_range(&itrace_synth_opts);
1685 		zfree(&report.ptime_range);
1686 	}
1687 
1688 	if (report.block_reports) {
1689 		block_info__free_report(report.block_reports,
1690 					report.nr_block_reports);
1691 		report.block_reports = NULL;
1692 	}
1693 
1694 	zstd_fini(&(session->zstd_data));
1695 	perf_session__delete(session);
1696 exit:
1697 	free(sort_order_help);
1698 	free(field_order_help);
1699 	return ret;
1700 }
1701