1/*
2 * builtin-report.c
3 *
4 * Builtin report command: Analyze the perf.data input file,
5 * look up and read DSOs and symbol information and display
6 * a histogram of results, along various sorting keys.
7 */
8#include "builtin.h"
9
10#include "util/util.h"
11
12#include "util/annotate.h"
13#include "util/color.h"
14/* ANDROID_CHANGE_BEGIN */
15#if 0
16#include <linux/list.h>
17#include "util/cache.h"
18#include <linux/rbtree.h>
19#else
20#include "util/include/linux/list.h"
21#include "util/cache.h"
22#include "util/include/linux/rbtree.h"
23#endif
24/* ANDROID_CHANGE_END */
25#include "util/symbol.h"
26#include "util/callchain.h"
27#include "util/strlist.h"
28#include "util/values.h"
29
30#include "perf.h"
31#include "util/debug.h"
32#include "util/evlist.h"
33#include "util/evsel.h"
34#include "util/header.h"
35#include "util/session.h"
36
37#include "util/parse-options.h"
38#include "util/parse-events.h"
39
40#include "util/thread.h"
41#include "util/sort.h"
42#include "util/hist.h"
43
44static char		const *input_name = "perf.data";
45
46static bool		force, use_tui, use_stdio;
47static bool		hide_unresolved;
48static bool		dont_use_callchains;
49
50static bool		show_threads;
51static struct perf_read_values	show_threads_values;
52
53static const char	default_pretty_printing_style[] = "normal";
54static const char	*pretty_printing_style = default_pretty_printing_style;
55
56static char		callchain_default_opt[] = "fractal,0.5";
57static symbol_filter_t	annotate_init;
58
59static int perf_session__add_hist_entry(struct perf_session *session,
60					struct addr_location *al,
61					struct perf_sample *sample,
62					struct perf_evsel *evsel)
63{
64	struct symbol *parent = NULL;
65	int err = 0;
66	struct hist_entry *he;
67
68	if ((sort__has_parent || symbol_conf.use_callchain) && sample->callchain) {
69		err = perf_session__resolve_callchain(session, al->thread,
70						      sample->callchain, &parent);
71		if (err)
72			return err;
73	}
74
75	he = __hists__add_entry(&evsel->hists, al, parent, sample->period);
76	if (he == NULL)
77		return -ENOMEM;
78
79	if (symbol_conf.use_callchain) {
80		err = callchain_append(he->callchain, &session->callchain_cursor,
81				       sample->period);
82		if (err)
83			return err;
84	}
85	/*
86	 * Only in the newt browser we are doing integrated annotation,
87	 * so we don't allocated the extra space needed because the stdio
88	 * code will not use it.
89	 */
90	if (al->sym != NULL && use_browser > 0) {
91		struct annotation *notes = symbol__annotation(he->ms.sym);
92
93		assert(evsel != NULL);
94
95		err = -ENOMEM;
96		if (notes->src == NULL &&
97		    symbol__alloc_hist(he->ms.sym, session->evlist->nr_entries) < 0)
98			goto out;
99
100		err = hist_entry__inc_addr_samples(he, evsel->idx, al->addr);
101	}
102
103	evsel->hists.stats.total_period += sample->period;
104	hists__inc_nr_events(&evsel->hists, PERF_RECORD_SAMPLE);
105out:
106	return err;
107}
108
109
110static int process_sample_event(union perf_event *event,
111				struct perf_sample *sample,
112				struct perf_evsel *evsel,
113				struct perf_session *session)
114{
115	struct addr_location al;
116
117	if (perf_event__preprocess_sample(event, session, &al, sample,
118					  annotate_init) < 0) {
119		fprintf(stderr, "problem processing %d event, skipping it.\n",
120			event->header.type);
121		return -1;
122	}
123
124	if (al.filtered || (hide_unresolved && al.sym == NULL))
125		return 0;
126
127	if (al.map != NULL)
128		al.map->dso->hit = 1;
129
130	if (perf_session__add_hist_entry(session, &al, sample, evsel)) {
131		pr_debug("problem incrementing symbol period, skipping event\n");
132		return -1;
133	}
134
135	return 0;
136}
137
138static int process_read_event(union perf_event *event,
139			      struct perf_sample *sample __used,
140			      struct perf_session *session)
141{
142	struct perf_evsel *evsel = perf_evlist__id2evsel(session->evlist,
143							 event->read.id);
144	if (show_threads) {
145		const char *name = evsel ? event_name(evsel) : "unknown";
146		perf_read_values_add_value(&show_threads_values,
147					   event->read.pid, event->read.tid,
148					   event->read.id,
149					   name,
150					   event->read.value);
151	}
152
153	dump_printf(": %d %d %s %" PRIu64 "\n", event->read.pid, event->read.tid,
154		    evsel ? event_name(evsel) : "FAIL",
155		    event->read.value);
156
157	return 0;
158}
159
160static int perf_session__setup_sample_type(struct perf_session *self)
161{
162	if (!(self->sample_type & PERF_SAMPLE_CALLCHAIN)) {
163		if (sort__has_parent) {
164			fprintf(stderr, "selected --sort parent, but no"
165					" callchain data. Did you call"
166					" perf record without -g?\n");
167			return -EINVAL;
168		}
169		if (symbol_conf.use_callchain) {
170			fprintf(stderr, "selected -g but no callchain data."
171					" Did you call perf record without"
172					" -g?\n");
173			return -1;
174		}
175	} else if (!dont_use_callchains && callchain_param.mode != CHAIN_NONE &&
176		   !symbol_conf.use_callchain) {
177			symbol_conf.use_callchain = true;
178			if (callchain_register_param(&callchain_param) < 0) {
179				fprintf(stderr, "Can't register callchain"
180						" params\n");
181				return -EINVAL;
182			}
183	}
184
185	return 0;
186}
187
188static struct perf_event_ops event_ops = {
189	.sample		 = process_sample_event,
190	.mmap		 = perf_event__process_mmap,
191	.comm		 = perf_event__process_comm,
192	.exit		 = perf_event__process_task,
193	.fork		 = perf_event__process_task,
194	.lost		 = perf_event__process_lost,
195	.read		 = process_read_event,
196	.attr		 = perf_event__process_attr,
197	.event_type	 = perf_event__process_event_type,
198	.tracing_data	 = perf_event__process_tracing_data,
199	.build_id	 = perf_event__process_build_id,
200	.ordered_samples = true,
201	.ordering_requires_timestamps = true,
202};
203
204extern volatile int session_done;
205
206static void sig_handler(int sig __used)
207{
208	session_done = 1;
209}
210
211static size_t hists__fprintf_nr_sample_events(struct hists *self,
212					      const char *evname, FILE *fp)
213{
214	size_t ret;
215	char unit;
216	unsigned long nr_events = self->stats.nr_events[PERF_RECORD_SAMPLE];
217
218	nr_events = convert_unit(nr_events, &unit);
219	ret = fprintf(fp, "# Events: %lu%c", nr_events, unit);
220	if (evname != NULL)
221		ret += fprintf(fp, " %s", evname);
222	return ret + fprintf(fp, "\n#\n");
223}
224
225static int perf_evlist__tty_browse_hists(struct perf_evlist *evlist,
226					 const char *help)
227{
228	struct perf_evsel *pos;
229
230	list_for_each_entry(pos, &evlist->entries, node) {
231		struct hists *hists = &pos->hists;
232		const char *evname = NULL;
233
234		if (rb_first(&hists->entries) != rb_last(&hists->entries))
235			evname = event_name(pos);
236
237		hists__fprintf_nr_sample_events(hists, evname, stdout);
238		hists__fprintf(hists, NULL, false, stdout);
239		fprintf(stdout, "\n\n");
240	}
241
242	if (sort_order == default_sort_order &&
243	    parent_pattern == default_parent_pattern) {
244		fprintf(stdout, "#\n# (%s)\n#\n", help);
245
246		if (show_threads) {
247			bool style = !strcmp(pretty_printing_style, "raw");
248			perf_read_values_display(stdout, &show_threads_values,
249						 style);
250			perf_read_values_destroy(&show_threads_values);
251		}
252	}
253
254	return 0;
255}
256
257static int __cmd_report(void)
258{
259	int ret = -EINVAL;
260	u64 nr_samples;
261	struct perf_session *session;
262	struct perf_evsel *pos;
263	struct map *kernel_map;
264	struct kmap *kernel_kmap;
265	const char *help = "For a higher level overview, try: perf report --sort comm,dso";
266
267	signal(SIGINT, sig_handler);
268
269	session = perf_session__new(input_name, O_RDONLY, force, false, &event_ops);
270	if (session == NULL)
271		return -ENOMEM;
272
273	if (show_threads)
274		perf_read_values_init(&show_threads_values);
275
276	ret = perf_session__setup_sample_type(session);
277	if (ret)
278		goto out_delete;
279
280	ret = perf_session__process_events(session, &event_ops);
281	if (ret)
282		goto out_delete;
283
284	kernel_map = session->host_machine.vmlinux_maps[MAP__FUNCTION];
285	kernel_kmap = map__kmap(kernel_map);
286	if (kernel_map == NULL ||
287	    (kernel_map->dso->hit &&
288	     (kernel_kmap->ref_reloc_sym == NULL ||
289	      kernel_kmap->ref_reloc_sym->addr == 0))) {
290		const struct dso *kdso = kernel_map->dso;
291
292		ui__warning(
293"Kernel address maps (/proc/{kallsyms,modules}) were restricted.\n\n"
294"Check /proc/sys/kernel/kptr_restrict before running 'perf record'.\n\n%s\n\n"
295"Samples in kernel modules can't be resolved as well.\n\n",
296			    RB_EMPTY_ROOT(&kdso->symbols[MAP__FUNCTION]) ?
297"As no suitable kallsyms nor vmlinux was found, kernel samples\n"
298"can't be resolved." :
299"If some relocation was applied (e.g. kexec) symbols may be misresolved.");
300	}
301
302	if (dump_trace) {
303		perf_session__fprintf_nr_events(session, stdout);
304		goto out_delete;
305	}
306
307	if (verbose > 3)
308		perf_session__fprintf(session, stdout);
309
310	if (verbose > 2)
311		perf_session__fprintf_dsos(session, stdout);
312
313	nr_samples = 0;
314	list_for_each_entry(pos, &session->evlist->entries, node) {
315		struct hists *hists = &pos->hists;
316
317		hists__collapse_resort(hists);
318		hists__output_resort(hists);
319		nr_samples += hists->stats.nr_events[PERF_RECORD_SAMPLE];
320	}
321
322	if (nr_samples == 0) {
323		ui__warning("The %s file has no samples!\n", input_name);
324		goto out_delete;
325	}
326
327	if (use_browser > 0)
328		perf_evlist__tui_browse_hists(session->evlist, help);
329	else
330		perf_evlist__tty_browse_hists(session->evlist, help);
331
332out_delete:
333	/*
334	 * Speed up the exit process, for large files this can
335	 * take quite a while.
336	 *
337	 * XXX Enable this when using valgrind or if we ever
338	 * librarize this command.
339	 *
340	 * Also experiment with obstacks to see how much speed
341	 * up we'll get here.
342	 *
343 	 * perf_session__delete(session);
344 	 */
345	return ret;
346}
347
348static int
349parse_callchain_opt(const struct option *opt __used, const char *arg,
350		    int unset)
351{
352	char *tok, *tok2;
353	char *endptr;
354
355	/*
356	 * --no-call-graph
357	 */
358	if (unset) {
359		dont_use_callchains = true;
360		return 0;
361	}
362
363	symbol_conf.use_callchain = true;
364
365	if (!arg)
366		return 0;
367
368	tok = strtok((char *)arg, ",");
369	if (!tok)
370		return -1;
371
372	/* get the output mode */
373	if (!strncmp(tok, "graph", strlen(arg)))
374		callchain_param.mode = CHAIN_GRAPH_ABS;
375
376	else if (!strncmp(tok, "flat", strlen(arg)))
377		callchain_param.mode = CHAIN_FLAT;
378
379	else if (!strncmp(tok, "fractal", strlen(arg)))
380		callchain_param.mode = CHAIN_GRAPH_REL;
381
382	else if (!strncmp(tok, "none", strlen(arg))) {
383		callchain_param.mode = CHAIN_NONE;
384		symbol_conf.use_callchain = false;
385
386		return 0;
387	}
388
389	else
390		return -1;
391
392	/* get the min percentage */
393	tok = strtok(NULL, ",");
394	if (!tok)
395		goto setup;
396
397	tok2 = strtok(NULL, ",");
398	callchain_param.min_percent = strtod(tok, &endptr);
399	if (tok == endptr)
400		return -1;
401
402	if (tok2)
403		callchain_param.print_limit = strtod(tok2, &endptr);
404setup:
405	if (callchain_register_param(&callchain_param) < 0) {
406		fprintf(stderr, "Can't register callchain params\n");
407		return -1;
408	}
409	return 0;
410}
411
412static const char * const report_usage[] = {
413	"perf report [<options>] <command>",
414	NULL
415};
416
417static const struct option options[] = {
418	OPT_STRING('i', "input", &input_name, "file",
419		    "input file name"),
420	OPT_INCR('v', "verbose", &verbose,
421		    "be more verbose (show symbol address, etc)"),
422	OPT_BOOLEAN('D', "dump-raw-trace", &dump_trace,
423		    "dump raw trace in ASCII"),
424	OPT_STRING('k', "vmlinux", &symbol_conf.vmlinux_name,
425		   "file", "vmlinux pathname"),
426	OPT_STRING(0, "kallsyms", &symbol_conf.kallsyms_name,
427		   "file", "kallsyms pathname"),
428	OPT_BOOLEAN('f', "force", &force, "don't complain, do it"),
429	OPT_BOOLEAN('m', "modules", &symbol_conf.use_modules,
430		    "load module symbols - WARNING: use only with -k and LIVE kernel"),
431	OPT_BOOLEAN('n', "show-nr-samples", &symbol_conf.show_nr_samples,
432		    "Show a column with the number of samples"),
433	OPT_BOOLEAN('T', "threads", &show_threads,
434		    "Show per-thread event counters"),
435	OPT_STRING(0, "pretty", &pretty_printing_style, "key",
436		   "pretty printing style key: normal raw"),
437	OPT_BOOLEAN(0, "tui", &use_tui, "Use the TUI interface"),
438	OPT_BOOLEAN(0, "stdio", &use_stdio, "Use the stdio interface"),
439	OPT_STRING('s', "sort", &sort_order, "key[,key2...]",
440		   "sort by key(s): pid, comm, dso, symbol, parent"),
441	OPT_BOOLEAN(0, "showcpuutilization", &symbol_conf.show_cpu_utilization,
442		    "Show sample percentage for different cpu modes"),
443	OPT_STRING('p', "parent", &parent_pattern, "regex",
444		   "regex filter to identify parent, see: '--sort parent'"),
445	OPT_BOOLEAN('x', "exclude-other", &symbol_conf.exclude_other,
446		    "Only display entries with parent-match"),
447	OPT_CALLBACK_DEFAULT('g', "call-graph", NULL, "output_type,min_percent",
448		     "Display callchains using output_type (graph, flat, fractal, or none) and min percent threshold. "
449		     "Default: fractal,0.5", &parse_callchain_opt, callchain_default_opt),
450	OPT_STRING('d', "dsos", &symbol_conf.dso_list_str, "dso[,dso...]",
451		   "only consider symbols in these dsos"),
452	OPT_STRING('C', "comms", &symbol_conf.comm_list_str, "comm[,comm...]",
453		   "only consider symbols in these comms"),
454	OPT_STRING('S', "symbols", &symbol_conf.sym_list_str, "symbol[,symbol...]",
455		   "only consider these symbols"),
456	OPT_STRING('w', "column-widths", &symbol_conf.col_width_list_str,
457		   "width[,width...]",
458		   "don't try to adjust column width, use these fixed values"),
459	OPT_STRING('t', "field-separator", &symbol_conf.field_sep, "separator",
460		   "separator for columns, no spaces will be added between "
461		   "columns '.' is reserved."),
462	OPT_BOOLEAN('U', "hide-unresolved", &hide_unresolved,
463		    "Only display entries resolved to a symbol"),
464	OPT_STRING(0, "symfs", &symbol_conf.symfs, "directory",
465		    "Look for files with symbols relative to this directory"),
466	OPT_END()
467};
468
469int cmd_report(int argc, const char **argv, const char *prefix __used)
470{
471	argc = parse_options(argc, argv, options, report_usage, 0);
472
473	if (use_stdio)
474		use_browser = 0;
475	else if (use_tui)
476		use_browser = 1;
477
478	if (strcmp(input_name, "-") != 0)
479		setup_browser(true);
480	else
481		use_browser = 0;
482	/*
483	 * Only in the newt browser we are doing integrated annotation,
484	 * so don't allocate extra space that won't be used in the stdio
485	 * implementation.
486	 */
487	if (use_browser > 0) {
488		symbol_conf.priv_size = sizeof(struct annotation);
489		annotate_init	      = symbol__annotate_init;
490		/*
491 		 * For searching by name on the "Browse map details".
492 		 * providing it only in verbose mode not to bloat too
493 		 * much struct symbol.
494 		 */
495		if (verbose) {
496			/*
497			 * XXX: Need to provide a less kludgy way to ask for
498			 * more space per symbol, the u32 is for the index on
499			 * the ui browser.
500			 * See symbol__browser_index.
501			 */
502			symbol_conf.priv_size += sizeof(u32);
503			symbol_conf.sort_by_name = true;
504		}
505	}
506
507	if (symbol__init() < 0)
508		return -1;
509
510	setup_sorting(report_usage, options);
511
512	if (parent_pattern != default_parent_pattern) {
513		if (sort_dimension__add("parent") < 0)
514			return -1;
515		sort_parent.elide = 1;
516	} else
517		symbol_conf.exclude_other = false;
518
519	/*
520	 * Any (unrecognized) arguments left?
521	 */
522	if (argc)
523		usage_with_options(report_usage, options);
524
525	sort_entry__setup_elide(&sort_dso, symbol_conf.dso_list, "dso", stdout);
526	sort_entry__setup_elide(&sort_comm, symbol_conf.comm_list, "comm", stdout);
527	sort_entry__setup_elide(&sort_sym, symbol_conf.sym_list, "symbol", stdout);
528
529	return __cmd_report();
530}
531