xref: /openbmc/linux/tools/perf/builtin-list.c (revision a325f174)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * builtin-list.c
4  *
5  * Builtin list command: list all event types
6  *
7  * Copyright (C) 2009, Thomas Gleixner <tglx@linutronix.de>
8  * Copyright (C) 2008-2009, Red Hat Inc, Ingo Molnar <mingo@redhat.com>
9  * Copyright (C) 2011, Red Hat Inc, Arnaldo Carvalho de Melo <acme@redhat.com>
10  */
11 #include "builtin.h"
12 
13 #include "util/print-events.h"
14 #include "util/pmus.h"
15 #include "util/pmu.h"
16 #include "util/debug.h"
17 #include "util/metricgroup.h"
18 #include "util/pfm.h"
19 #include "util/string2.h"
20 #include "util/strlist.h"
21 #include "util/strbuf.h"
22 #include <subcmd/pager.h>
23 #include <subcmd/parse-options.h>
24 #include <linux/zalloc.h>
25 #include <stdarg.h>
26 #include <stdio.h>
27 
28 /**
29  * struct print_state - State and configuration passed to the default_print
30  * functions.
31  */
32 struct print_state {
33 	/**
34 	 * @pmu_glob: Optionally restrict PMU and metric matching to PMU or
35 	 * debugfs subsystem name.
36 	 */
37 	char *pmu_glob;
38 	/** @event_glob: Optional pattern matching glob. */
39 	char *event_glob;
40 	/** @name_only: Print event or metric names only. */
41 	bool name_only;
42 	/** @desc: Print the event or metric description. */
43 	bool desc;
44 	/** @long_desc: Print longer event or metric description. */
45 	bool long_desc;
46 	/** @deprecated: Print deprecated events or metrics. */
47 	bool deprecated;
48 	/**
49 	 * @detailed: Print extra information on the perf event such as names
50 	 * and expressions used internally by events.
51 	 */
52 	bool detailed;
53 	/** @metrics: Controls printing of metric and metric groups. */
54 	bool metrics;
55 	/** @metricgroups: Controls printing of metric and metric groups. */
56 	bool metricgroups;
57 	/** @last_topic: The last printed event topic. */
58 	char *last_topic;
59 	/** @last_metricgroups: The last printed metric group. */
60 	char *last_metricgroups;
61 	/** @visited_metrics: Metrics that are printed to avoid duplicates. */
62 	struct strlist *visited_metrics;
63 };
64 
65 static void default_print_start(void *ps)
66 {
67 	struct print_state *print_state = ps;
68 
69 	if (!print_state->name_only && pager_in_use())
70 		printf("\nList of pre-defined events (to be used in -e or -M):\n\n");
71 }
72 
73 static void default_print_end(void *print_state __maybe_unused) {}
74 
75 static void wordwrap(const char *s, int start, int max, int corr)
76 {
77 	int column = start;
78 	int n;
79 	bool saw_newline = false;
80 
81 	while (*s) {
82 		int wlen = strcspn(s, " \t\n");
83 
84 		if ((column + wlen >= max && column > start) || saw_newline) {
85 			printf("\n%*s", start, "");
86 			column = start + corr;
87 		}
88 		n = printf("%s%.*s", column > start ? " " : "", wlen, s);
89 		if (n <= 0)
90 			break;
91 		saw_newline = s[wlen] == '\n';
92 		s += wlen;
93 		column += n;
94 		s = skip_spaces(s);
95 	}
96 }
97 
98 static void default_print_event(void *ps, const char *pmu_name, const char *topic,
99 				const char *event_name, const char *event_alias,
100 				const char *scale_unit __maybe_unused,
101 				bool deprecated, const char *event_type_desc,
102 				const char *desc, const char *long_desc,
103 				const char *encoding_desc)
104 {
105 	struct print_state *print_state = ps;
106 	int pos;
107 
108 	if (deprecated && !print_state->deprecated)
109 		return;
110 
111 	if (print_state->pmu_glob && pmu_name && !strglobmatch(pmu_name, print_state->pmu_glob))
112 		return;
113 
114 	if (print_state->event_glob &&
115 	    (!event_name || !strglobmatch(event_name, print_state->event_glob)) &&
116 	    (!event_alias || !strglobmatch(event_alias, print_state->event_glob)) &&
117 	    (!topic || !strglobmatch_nocase(topic, print_state->event_glob)))
118 		return;
119 
120 	if (print_state->name_only) {
121 		if (event_alias && strlen(event_alias))
122 			printf("%s ", event_alias);
123 		else
124 			printf("%s ", event_name);
125 		return;
126 	}
127 
128 	if (strcmp(print_state->last_topic, topic ?: "")) {
129 		if (topic)
130 			printf("\n%s:\n", topic);
131 		zfree(&print_state->last_topic);
132 		print_state->last_topic = strdup(topic ?: "");
133 	}
134 
135 	if (event_alias && strlen(event_alias))
136 		pos = printf("  %s OR %s", event_name, event_alias);
137 	else
138 		pos = printf("  %s", event_name);
139 
140 	if (!topic && event_type_desc) {
141 		for (; pos < 53; pos++)
142 			putchar(' ');
143 		printf("[%s]\n", event_type_desc);
144 	} else
145 		putchar('\n');
146 
147 	if (desc && print_state->desc) {
148 		char *desc_with_unit = NULL;
149 		int desc_len = -1;
150 
151 		if (pmu_name && strcmp(pmu_name, "default_core")) {
152 			desc_len = strlen(desc);
153 			desc_len = asprintf(&desc_with_unit,
154 					    desc[desc_len - 1] != '.'
155 					      ? "%s. Unit: %s" : "%s Unit: %s",
156 					    desc, pmu_name);
157 		}
158 		printf("%*s", 8, "[");
159 		wordwrap(desc_len > 0 ? desc_with_unit : desc, 8, pager_get_columns(), 0);
160 		printf("]\n");
161 		free(desc_with_unit);
162 	}
163 	long_desc = long_desc ?: desc;
164 	if (long_desc && print_state->long_desc) {
165 		printf("%*s", 8, "[");
166 		wordwrap(long_desc, 8, pager_get_columns(), 0);
167 		printf("]\n");
168 	}
169 
170 	if (print_state->detailed && encoding_desc) {
171 		printf("%*s", 8, "");
172 		wordwrap(encoding_desc, 8, pager_get_columns(), 0);
173 		putchar('\n');
174 	}
175 }
176 
177 static void default_print_metric(void *ps,
178 				const char *group,
179 				const char *name,
180 				const char *desc,
181 				const char *long_desc,
182 				const char *expr,
183 				const char *threshold,
184 				const char *unit __maybe_unused)
185 {
186 	struct print_state *print_state = ps;
187 
188 	if (print_state->event_glob &&
189 	    (!print_state->metrics || !name || !strglobmatch(name, print_state->event_glob)) &&
190 	    (!print_state->metricgroups || !group || !strglobmatch(group, print_state->event_glob)))
191 		return;
192 
193 	if (!print_state->name_only && !print_state->last_metricgroups) {
194 		if (print_state->metricgroups) {
195 			printf("\nMetric Groups:\n");
196 			if (!print_state->metrics)
197 				putchar('\n');
198 		} else {
199 			printf("\nMetrics:\n\n");
200 		}
201 	}
202 	if (!print_state->last_metricgroups ||
203 	    strcmp(print_state->last_metricgroups, group ?: "")) {
204 		if (group && print_state->metricgroups) {
205 			if (print_state->name_only)
206 				printf("%s ", group);
207 			else if (print_state->metrics) {
208 				const char *gdesc = describe_metricgroup(group);
209 
210 				if (gdesc)
211 					printf("\n%s: [%s]\n", group, gdesc);
212 				else
213 					printf("\n%s:\n", group);
214 			} else
215 				printf("%s\n", group);
216 		}
217 		zfree(&print_state->last_metricgroups);
218 		print_state->last_metricgroups = strdup(group ?: "");
219 	}
220 	if (!print_state->metrics)
221 		return;
222 
223 	if (print_state->name_only) {
224 		if (print_state->metrics &&
225 		    !strlist__has_entry(print_state->visited_metrics, name)) {
226 			printf("%s ", name);
227 			strlist__add(print_state->visited_metrics, name);
228 		}
229 		return;
230 	}
231 	printf("  %s\n", name);
232 
233 	if (desc && print_state->desc) {
234 		printf("%*s", 8, "[");
235 		wordwrap(desc, 8, pager_get_columns(), 0);
236 		printf("]\n");
237 	}
238 	if (long_desc && print_state->long_desc) {
239 		printf("%*s", 8, "[");
240 		wordwrap(long_desc, 8, pager_get_columns(), 0);
241 		printf("]\n");
242 	}
243 	if (expr && print_state->detailed) {
244 		printf("%*s", 8, "[");
245 		wordwrap(expr, 8, pager_get_columns(), 0);
246 		printf("]\n");
247 	}
248 	if (threshold && print_state->detailed) {
249 		printf("%*s", 8, "[");
250 		wordwrap(threshold, 8, pager_get_columns(), 0);
251 		printf("]\n");
252 	}
253 }
254 
255 struct json_print_state {
256 	/** Should a separator be printed prior to the next item? */
257 	bool need_sep;
258 };
259 
260 static void json_print_start(void *print_state __maybe_unused)
261 {
262 	printf("[\n");
263 }
264 
265 static void json_print_end(void *ps)
266 {
267 	struct json_print_state *print_state = ps;
268 
269 	printf("%s]\n", print_state->need_sep ? "\n" : "");
270 }
271 
272 static void fix_escape_printf(struct strbuf *buf, const char *fmt, ...)
273 {
274 	va_list args;
275 
276 	va_start(args, fmt);
277 	strbuf_setlen(buf, 0);
278 	for (size_t fmt_pos = 0; fmt_pos < strlen(fmt); fmt_pos++) {
279 		switch (fmt[fmt_pos]) {
280 		case '%':
281 			fmt_pos++;
282 			switch (fmt[fmt_pos]) {
283 			case 's': {
284 				const char *s = va_arg(args, const char*);
285 
286 				strbuf_addstr(buf, s);
287 				break;
288 			}
289 			case 'S': {
290 				const char *s = va_arg(args, const char*);
291 
292 				for (size_t s_pos = 0; s_pos < strlen(s); s_pos++) {
293 					switch (s[s_pos]) {
294 					case '\n':
295 						strbuf_addstr(buf, "\\n");
296 						break;
297 					case '\\':
298 						fallthrough;
299 					case '\"':
300 						strbuf_addch(buf, '\\');
301 						fallthrough;
302 					default:
303 						strbuf_addch(buf, s[s_pos]);
304 						break;
305 					}
306 				}
307 				break;
308 			}
309 			default:
310 				pr_err("Unexpected format character '%c'\n", fmt[fmt_pos]);
311 				strbuf_addch(buf, '%');
312 				strbuf_addch(buf, fmt[fmt_pos]);
313 			}
314 			break;
315 		default:
316 			strbuf_addch(buf, fmt[fmt_pos]);
317 			break;
318 		}
319 	}
320 	va_end(args);
321 	fputs(buf->buf, stdout);
322 }
323 
324 static void json_print_event(void *ps, const char *pmu_name, const char *topic,
325 			     const char *event_name, const char *event_alias,
326 			     const char *scale_unit,
327 			     bool deprecated, const char *event_type_desc,
328 			     const char *desc, const char *long_desc,
329 			     const char *encoding_desc)
330 {
331 	struct json_print_state *print_state = ps;
332 	bool need_sep = false;
333 	struct strbuf buf;
334 
335 	strbuf_init(&buf, 0);
336 	printf("%s{\n", print_state->need_sep ? ",\n" : "");
337 	print_state->need_sep = true;
338 	if (pmu_name) {
339 		fix_escape_printf(&buf, "\t\"Unit\": \"%S\"", pmu_name);
340 		need_sep = true;
341 	}
342 	if (topic) {
343 		fix_escape_printf(&buf, "%s\t\"Topic\": \"%S\"", need_sep ? ",\n" : "", topic);
344 		need_sep = true;
345 	}
346 	if (event_name) {
347 		fix_escape_printf(&buf, "%s\t\"EventName\": \"%S\"", need_sep ? ",\n" : "",
348 				  event_name);
349 		need_sep = true;
350 	}
351 	if (event_alias && strlen(event_alias)) {
352 		fix_escape_printf(&buf, "%s\t\"EventAlias\": \"%S\"", need_sep ? ",\n" : "",
353 				  event_alias);
354 		need_sep = true;
355 	}
356 	if (scale_unit && strlen(scale_unit)) {
357 		fix_escape_printf(&buf, "%s\t\"ScaleUnit\": \"%S\"", need_sep ? ",\n" : "",
358 				  scale_unit);
359 		need_sep = true;
360 	}
361 	if (event_type_desc) {
362 		fix_escape_printf(&buf, "%s\t\"EventType\": \"%S\"", need_sep ? ",\n" : "",
363 				  event_type_desc);
364 		need_sep = true;
365 	}
366 	if (deprecated) {
367 		fix_escape_printf(&buf, "%s\t\"Deprecated\": \"%S\"", need_sep ? ",\n" : "",
368 				  deprecated ? "1" : "0");
369 		need_sep = true;
370 	}
371 	if (desc) {
372 		fix_escape_printf(&buf, "%s\t\"BriefDescription\": \"%S\"", need_sep ? ",\n" : "",
373 				  desc);
374 		need_sep = true;
375 	}
376 	if (long_desc) {
377 		fix_escape_printf(&buf, "%s\t\"PublicDescription\": \"%S\"", need_sep ? ",\n" : "",
378 				  long_desc);
379 		need_sep = true;
380 	}
381 	if (encoding_desc) {
382 		fix_escape_printf(&buf, "%s\t\"Encoding\": \"%S\"", need_sep ? ",\n" : "",
383 				  encoding_desc);
384 		need_sep = true;
385 	}
386 	printf("%s}", need_sep ? "\n" : "");
387 	strbuf_release(&buf);
388 }
389 
390 static void json_print_metric(void *ps __maybe_unused, const char *group,
391 			      const char *name, const char *desc,
392 			      const char *long_desc, const char *expr,
393 			      const char *threshold, const char *unit)
394 {
395 	struct json_print_state *print_state = ps;
396 	bool need_sep = false;
397 	struct strbuf buf;
398 
399 	strbuf_init(&buf, 0);
400 	printf("%s{\n", print_state->need_sep ? ",\n" : "");
401 	print_state->need_sep = true;
402 	if (group) {
403 		fix_escape_printf(&buf, "\t\"MetricGroup\": \"%S\"", group);
404 		need_sep = true;
405 	}
406 	if (name) {
407 		fix_escape_printf(&buf, "%s\t\"MetricName\": \"%S\"", need_sep ? ",\n" : "", name);
408 		need_sep = true;
409 	}
410 	if (expr) {
411 		fix_escape_printf(&buf, "%s\t\"MetricExpr\": \"%S\"", need_sep ? ",\n" : "", expr);
412 		need_sep = true;
413 	}
414 	if (threshold) {
415 		fix_escape_printf(&buf, "%s\t\"MetricThreshold\": \"%S\"", need_sep ? ",\n" : "",
416 				  threshold);
417 		need_sep = true;
418 	}
419 	if (unit) {
420 		fix_escape_printf(&buf, "%s\t\"ScaleUnit\": \"%S\"", need_sep ? ",\n" : "", unit);
421 		need_sep = true;
422 	}
423 	if (desc) {
424 		fix_escape_printf(&buf, "%s\t\"BriefDescription\": \"%S\"", need_sep ? ",\n" : "",
425 				  desc);
426 		need_sep = true;
427 	}
428 	if (long_desc) {
429 		fix_escape_printf(&buf, "%s\t\"PublicDescription\": \"%S\"", need_sep ? ",\n" : "",
430 				  long_desc);
431 		need_sep = true;
432 	}
433 	printf("%s}", need_sep ? "\n" : "");
434 	strbuf_release(&buf);
435 }
436 
437 static bool default_skip_duplicate_pmus(void *ps)
438 {
439 	struct print_state *print_state = ps;
440 
441 	return !print_state->long_desc;
442 }
443 
444 int cmd_list(int argc, const char **argv)
445 {
446 	int i, ret = 0;
447 	struct print_state default_ps = {};
448 	struct print_state json_ps = {};
449 	void *ps = &default_ps;
450 	struct print_callbacks print_cb = {
451 		.print_start = default_print_start,
452 		.print_end = default_print_end,
453 		.print_event = default_print_event,
454 		.print_metric = default_print_metric,
455 		.skip_duplicate_pmus = default_skip_duplicate_pmus,
456 	};
457 	const char *cputype = NULL;
458 	const char *unit_name = NULL;
459 	bool json = false;
460 	struct option list_options[] = {
461 		OPT_BOOLEAN(0, "raw-dump", &default_ps.name_only, "Dump raw events"),
462 		OPT_BOOLEAN('j', "json", &json, "JSON encode events and metrics"),
463 		OPT_BOOLEAN('d', "desc", &default_ps.desc,
464 			    "Print extra event descriptions. --no-desc to not print."),
465 		OPT_BOOLEAN('v', "long-desc", &default_ps.long_desc,
466 			    "Print longer event descriptions."),
467 		OPT_BOOLEAN(0, "details", &default_ps.detailed,
468 			    "Print information on the perf event names and expressions used internally by events."),
469 		OPT_BOOLEAN(0, "deprecated", &default_ps.deprecated,
470 			    "Print deprecated events."),
471 		OPT_STRING(0, "cputype", &cputype, "cpu type",
472 			   "Limit PMU or metric printing to the given PMU (e.g. cpu, core or atom)."),
473 		OPT_STRING(0, "unit", &unit_name, "PMU name",
474 			   "Limit PMU or metric printing to the specified PMU."),
475 		OPT_INCR(0, "debug", &verbose,
476 			     "Enable debugging output"),
477 		OPT_END()
478 	};
479 	const char * const list_usage[] = {
480 #ifdef HAVE_LIBPFM
481 		"perf list [<options>] [hw|sw|cache|tracepoint|pmu|sdt|metric|metricgroup|event_glob|pfm]",
482 #else
483 		"perf list [<options>] [hw|sw|cache|tracepoint|pmu|sdt|metric|metricgroup|event_glob]",
484 #endif
485 		NULL
486 	};
487 
488 	set_option_flag(list_options, 0, "raw-dump", PARSE_OPT_HIDDEN);
489 	/* Hide hybrid flag for the more generic 'unit' flag. */
490 	set_option_flag(list_options, 0, "cputype", PARSE_OPT_HIDDEN);
491 
492 	argc = parse_options(argc, argv, list_options, list_usage,
493 			     PARSE_OPT_STOP_AT_NON_OPTION);
494 
495 	setup_pager();
496 
497 	if (!default_ps.name_only)
498 		setup_pager();
499 
500 	if (json) {
501 		print_cb = (struct print_callbacks){
502 			.print_start = json_print_start,
503 			.print_end = json_print_end,
504 			.print_event = json_print_event,
505 			.print_metric = json_print_metric,
506 		};
507 		ps = &json_ps;
508 	} else {
509 		default_ps.desc = !default_ps.long_desc;
510 		default_ps.last_topic = strdup("");
511 		assert(default_ps.last_topic);
512 		default_ps.visited_metrics = strlist__new(NULL, NULL);
513 		assert(default_ps.visited_metrics);
514 		if (unit_name)
515 			default_ps.pmu_glob = strdup(unit_name);
516 		else if (cputype) {
517 			const struct perf_pmu *pmu = perf_pmus__pmu_for_pmu_filter(cputype);
518 
519 			if (!pmu) {
520 				pr_err("ERROR: cputype is not supported!\n");
521 				ret = -1;
522 				goto out;
523 			}
524 			default_ps.pmu_glob = strdup(pmu->name);
525 		}
526 	}
527 	print_cb.print_start(ps);
528 
529 	if (argc == 0) {
530 		default_ps.metrics = true;
531 		default_ps.metricgroups = true;
532 		print_events(&print_cb, ps);
533 		goto out;
534 	}
535 
536 	for (i = 0; i < argc; ++i) {
537 		char *sep, *s;
538 
539 		if (strcmp(argv[i], "tracepoint") == 0)
540 			print_tracepoint_events(&print_cb, ps);
541 		else if (strcmp(argv[i], "hw") == 0 ||
542 			 strcmp(argv[i], "hardware") == 0)
543 			print_symbol_events(&print_cb, ps, PERF_TYPE_HARDWARE,
544 					event_symbols_hw, PERF_COUNT_HW_MAX);
545 		else if (strcmp(argv[i], "sw") == 0 ||
546 			 strcmp(argv[i], "software") == 0) {
547 			print_symbol_events(&print_cb, ps, PERF_TYPE_SOFTWARE,
548 					event_symbols_sw, PERF_COUNT_SW_MAX);
549 			print_tool_events(&print_cb, ps);
550 		} else if (strcmp(argv[i], "cache") == 0 ||
551 			 strcmp(argv[i], "hwcache") == 0)
552 			print_hwcache_events(&print_cb, ps);
553 		else if (strcmp(argv[i], "pmu") == 0)
554 			perf_pmus__print_pmu_events(&print_cb, ps);
555 		else if (strcmp(argv[i], "sdt") == 0)
556 			print_sdt_events(&print_cb, ps);
557 		else if (strcmp(argv[i], "metric") == 0 || strcmp(argv[i], "metrics") == 0) {
558 			default_ps.metricgroups = false;
559 			default_ps.metrics = true;
560 			metricgroup__print(&print_cb, ps);
561 		} else if (strcmp(argv[i], "metricgroup") == 0 ||
562 			   strcmp(argv[i], "metricgroups") == 0) {
563 			default_ps.metricgroups = true;
564 			default_ps.metrics = false;
565 			metricgroup__print(&print_cb, ps);
566 		}
567 #ifdef HAVE_LIBPFM
568 		else if (strcmp(argv[i], "pfm") == 0)
569 			print_libpfm_events(&print_cb, ps);
570 #endif
571 		else if ((sep = strchr(argv[i], ':')) != NULL) {
572 			char *old_pmu_glob = default_ps.pmu_glob;
573 
574 			default_ps.event_glob = strdup(argv[i]);
575 			if (!default_ps.event_glob) {
576 				ret = -1;
577 				goto out;
578 			}
579 
580 			print_tracepoint_events(&print_cb, ps);
581 			print_sdt_events(&print_cb, ps);
582 			default_ps.metrics = true;
583 			default_ps.metricgroups = true;
584 			metricgroup__print(&print_cb, ps);
585 			zfree(&default_ps.event_glob);
586 			default_ps.pmu_glob = old_pmu_glob;
587 		} else {
588 			if (asprintf(&s, "*%s*", argv[i]) < 0) {
589 				printf("Critical: Not enough memory! Trying to continue...\n");
590 				continue;
591 			}
592 			default_ps.event_glob = s;
593 			print_symbol_events(&print_cb, ps, PERF_TYPE_HARDWARE,
594 					event_symbols_hw, PERF_COUNT_HW_MAX);
595 			print_symbol_events(&print_cb, ps, PERF_TYPE_SOFTWARE,
596 					event_symbols_sw, PERF_COUNT_SW_MAX);
597 			print_tool_events(&print_cb, ps);
598 			print_hwcache_events(&print_cb, ps);
599 			perf_pmus__print_pmu_events(&print_cb, ps);
600 			print_tracepoint_events(&print_cb, ps);
601 			print_sdt_events(&print_cb, ps);
602 			default_ps.metrics = true;
603 			default_ps.metricgroups = true;
604 			metricgroup__print(&print_cb, ps);
605 			free(s);
606 		}
607 	}
608 
609 out:
610 	print_cb.print_end(ps);
611 	free(default_ps.pmu_glob);
612 	free(default_ps.last_topic);
613 	free(default_ps.last_metricgroups);
614 	strlist__delete(default_ps.visited_metrics);
615 	return ret;
616 }
617