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