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