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