xref: /openbmc/linux/tools/perf/util/pmu.c (revision 9ac17575)
1 // SPDX-License-Identifier: GPL-2.0
2 #include <linux/list.h>
3 #include <linux/compiler.h>
4 #include <linux/string.h>
5 #include <linux/zalloc.h>
6 #include <subcmd/pager.h>
7 #include <sys/types.h>
8 #include <errno.h>
9 #include <fcntl.h>
10 #include <sys/stat.h>
11 #include <unistd.h>
12 #include <stdio.h>
13 #include <stdbool.h>
14 #include <stdarg.h>
15 #include <dirent.h>
16 #include <api/fs/fs.h>
17 #include <locale.h>
18 #include <regex.h>
19 #include <perf/cpumap.h>
20 #include "debug.h"
21 #include "evsel.h"
22 #include "pmu.h"
23 #include "parse-events.h"
24 #include "header.h"
25 #include "string2.h"
26 #include "strbuf.h"
27 #include "fncache.h"
28 
29 struct perf_pmu_format {
30 	char *name;
31 	int value;
32 	DECLARE_BITMAP(bits, PERF_PMU_FORMAT_BITS);
33 	struct list_head list;
34 };
35 
36 int perf_pmu_parse(struct list_head *list, char *name);
37 extern FILE *perf_pmu_in;
38 
39 static LIST_HEAD(pmus);
40 
41 /*
42  * Parse & process all the sysfs attributes located under
43  * the directory specified in 'dir' parameter.
44  */
45 int perf_pmu__format_parse(char *dir, struct list_head *head)
46 {
47 	struct dirent *evt_ent;
48 	DIR *format_dir;
49 	int ret = 0;
50 
51 	format_dir = opendir(dir);
52 	if (!format_dir)
53 		return -EINVAL;
54 
55 	while (!ret && (evt_ent = readdir(format_dir))) {
56 		char path[PATH_MAX];
57 		char *name = evt_ent->d_name;
58 		FILE *file;
59 
60 		if (!strcmp(name, ".") || !strcmp(name, ".."))
61 			continue;
62 
63 		snprintf(path, PATH_MAX, "%s/%s", dir, name);
64 
65 		ret = -EINVAL;
66 		file = fopen(path, "r");
67 		if (!file)
68 			break;
69 
70 		perf_pmu_in = file;
71 		ret = perf_pmu_parse(head, name);
72 		fclose(file);
73 	}
74 
75 	closedir(format_dir);
76 	return ret;
77 }
78 
79 /*
80  * Reading/parsing the default pmu format definition, which should be
81  * located at:
82  * /sys/bus/event_source/devices/<dev>/format as sysfs group attributes.
83  */
84 static int pmu_format(const char *name, struct list_head *format)
85 {
86 	char path[PATH_MAX];
87 	const char *sysfs = sysfs__mountpoint();
88 
89 	if (!sysfs)
90 		return -1;
91 
92 	snprintf(path, PATH_MAX,
93 		 "%s" EVENT_SOURCE_DEVICE_PATH "%s/format", sysfs, name);
94 
95 	if (!file_available(path))
96 		return 0;
97 
98 	if (perf_pmu__format_parse(path, format))
99 		return -1;
100 
101 	return 0;
102 }
103 
104 int perf_pmu__convert_scale(const char *scale, char **end, double *sval)
105 {
106 	char *lc;
107 	int ret = 0;
108 
109 	/*
110 	 * save current locale
111 	 */
112 	lc = setlocale(LC_NUMERIC, NULL);
113 
114 	/*
115 	 * The lc string may be allocated in static storage,
116 	 * so get a dynamic copy to make it survive setlocale
117 	 * call below.
118 	 */
119 	lc = strdup(lc);
120 	if (!lc) {
121 		ret = -ENOMEM;
122 		goto out;
123 	}
124 
125 	/*
126 	 * force to C locale to ensure kernel
127 	 * scale string is converted correctly.
128 	 * kernel uses default C locale.
129 	 */
130 	setlocale(LC_NUMERIC, "C");
131 
132 	*sval = strtod(scale, end);
133 
134 out:
135 	/* restore locale */
136 	setlocale(LC_NUMERIC, lc);
137 	free(lc);
138 	return ret;
139 }
140 
141 static int perf_pmu__parse_scale(struct perf_pmu_alias *alias, char *dir, char *name)
142 {
143 	struct stat st;
144 	ssize_t sret;
145 	char scale[128];
146 	int fd, ret = -1;
147 	char path[PATH_MAX];
148 
149 	scnprintf(path, PATH_MAX, "%s/%s.scale", dir, name);
150 
151 	fd = open(path, O_RDONLY);
152 	if (fd == -1)
153 		return -1;
154 
155 	if (fstat(fd, &st) < 0)
156 		goto error;
157 
158 	sret = read(fd, scale, sizeof(scale)-1);
159 	if (sret < 0)
160 		goto error;
161 
162 	if (scale[sret - 1] == '\n')
163 		scale[sret - 1] = '\0';
164 	else
165 		scale[sret] = '\0';
166 
167 	ret = perf_pmu__convert_scale(scale, NULL, &alias->scale);
168 error:
169 	close(fd);
170 	return ret;
171 }
172 
173 static int perf_pmu__parse_unit(struct perf_pmu_alias *alias, char *dir, char *name)
174 {
175 	char path[PATH_MAX];
176 	ssize_t sret;
177 	int fd;
178 
179 	scnprintf(path, PATH_MAX, "%s/%s.unit", dir, name);
180 
181 	fd = open(path, O_RDONLY);
182 	if (fd == -1)
183 		return -1;
184 
185 	sret = read(fd, alias->unit, UNIT_MAX_LEN);
186 	if (sret < 0)
187 		goto error;
188 
189 	close(fd);
190 
191 	if (alias->unit[sret - 1] == '\n')
192 		alias->unit[sret - 1] = '\0';
193 	else
194 		alias->unit[sret] = '\0';
195 
196 	return 0;
197 error:
198 	close(fd);
199 	alias->unit[0] = '\0';
200 	return -1;
201 }
202 
203 static int
204 perf_pmu__parse_per_pkg(struct perf_pmu_alias *alias, char *dir, char *name)
205 {
206 	char path[PATH_MAX];
207 	int fd;
208 
209 	scnprintf(path, PATH_MAX, "%s/%s.per-pkg", dir, name);
210 
211 	fd = open(path, O_RDONLY);
212 	if (fd == -1)
213 		return -1;
214 
215 	close(fd);
216 
217 	alias->per_pkg = true;
218 	return 0;
219 }
220 
221 static int perf_pmu__parse_snapshot(struct perf_pmu_alias *alias,
222 				    char *dir, char *name)
223 {
224 	char path[PATH_MAX];
225 	int fd;
226 
227 	scnprintf(path, PATH_MAX, "%s/%s.snapshot", dir, name);
228 
229 	fd = open(path, O_RDONLY);
230 	if (fd == -1)
231 		return -1;
232 
233 	alias->snapshot = true;
234 	close(fd);
235 	return 0;
236 }
237 
238 static void perf_pmu_assign_str(char *name, const char *field, char **old_str,
239 				char **new_str)
240 {
241 	if (!*old_str)
242 		goto set_new;
243 
244 	if (*new_str) {	/* Have new string, check with old */
245 		if (strcasecmp(*old_str, *new_str))
246 			pr_debug("alias %s differs in field '%s'\n",
247 				 name, field);
248 		zfree(old_str);
249 	} else		/* Nothing new --> keep old string */
250 		return;
251 set_new:
252 	*old_str = *new_str;
253 	*new_str = NULL;
254 }
255 
256 static void perf_pmu_update_alias(struct perf_pmu_alias *old,
257 				  struct perf_pmu_alias *newalias)
258 {
259 	perf_pmu_assign_str(old->name, "desc", &old->desc, &newalias->desc);
260 	perf_pmu_assign_str(old->name, "long_desc", &old->long_desc,
261 			    &newalias->long_desc);
262 	perf_pmu_assign_str(old->name, "topic", &old->topic, &newalias->topic);
263 	perf_pmu_assign_str(old->name, "metric_expr", &old->metric_expr,
264 			    &newalias->metric_expr);
265 	perf_pmu_assign_str(old->name, "metric_name", &old->metric_name,
266 			    &newalias->metric_name);
267 	perf_pmu_assign_str(old->name, "value", &old->str, &newalias->str);
268 	old->scale = newalias->scale;
269 	old->per_pkg = newalias->per_pkg;
270 	old->snapshot = newalias->snapshot;
271 	memcpy(old->unit, newalias->unit, sizeof(old->unit));
272 }
273 
274 /* Delete an alias entry. */
275 static void perf_pmu_free_alias(struct perf_pmu_alias *newalias)
276 {
277 	zfree(&newalias->name);
278 	zfree(&newalias->desc);
279 	zfree(&newalias->long_desc);
280 	zfree(&newalias->topic);
281 	zfree(&newalias->str);
282 	zfree(&newalias->metric_expr);
283 	zfree(&newalias->metric_name);
284 	parse_events_terms__purge(&newalias->terms);
285 	free(newalias);
286 }
287 
288 /* Merge an alias, search in alias list. If this name is already
289  * present merge both of them to combine all information.
290  */
291 static bool perf_pmu_merge_alias(struct perf_pmu_alias *newalias,
292 				 struct list_head *alist)
293 {
294 	struct perf_pmu_alias *a;
295 
296 	list_for_each_entry(a, alist, list) {
297 		if (!strcasecmp(newalias->name, a->name)) {
298 			perf_pmu_update_alias(a, newalias);
299 			perf_pmu_free_alias(newalias);
300 			return true;
301 		}
302 	}
303 	return false;
304 }
305 
306 static int __perf_pmu__new_alias(struct list_head *list, char *dir, char *name,
307 				 char *desc, char *val,
308 				 char *long_desc, char *topic,
309 				 char *unit, char *perpkg,
310 				 char *metric_expr,
311 				 char *metric_name,
312 				 char *deprecated)
313 {
314 	struct parse_events_term *term;
315 	struct perf_pmu_alias *alias;
316 	int ret;
317 	int num;
318 	char newval[256];
319 
320 	alias = malloc(sizeof(*alias));
321 	if (!alias)
322 		return -ENOMEM;
323 
324 	INIT_LIST_HEAD(&alias->terms);
325 	alias->scale = 1.0;
326 	alias->unit[0] = '\0';
327 	alias->per_pkg = false;
328 	alias->snapshot = false;
329 	alias->deprecated = false;
330 
331 	ret = parse_events_terms(&alias->terms, val);
332 	if (ret) {
333 		pr_err("Cannot parse alias %s: %d\n", val, ret);
334 		free(alias);
335 		return ret;
336 	}
337 
338 	/* Scan event and remove leading zeroes, spaces, newlines, some
339 	 * platforms have terms specified as
340 	 * event=0x0091 (read from files ../<PMU>/events/<FILE>
341 	 * and terms specified as event=0x91 (read from JSON files).
342 	 *
343 	 * Rebuild string to make alias->str member comparable.
344 	 */
345 	memset(newval, 0, sizeof(newval));
346 	ret = 0;
347 	list_for_each_entry(term, &alias->terms, list) {
348 		if (ret)
349 			ret += scnprintf(newval + ret, sizeof(newval) - ret,
350 					 ",");
351 		if (term->type_val == PARSE_EVENTS__TERM_TYPE_NUM)
352 			ret += scnprintf(newval + ret, sizeof(newval) - ret,
353 					 "%s=%#x", term->config, term->val.num);
354 		else if (term->type_val == PARSE_EVENTS__TERM_TYPE_STR)
355 			ret += scnprintf(newval + ret, sizeof(newval) - ret,
356 					 "%s=%s", term->config, term->val.str);
357 	}
358 
359 	alias->name = strdup(name);
360 	if (dir) {
361 		/*
362 		 * load unit name and scale if available
363 		 */
364 		perf_pmu__parse_unit(alias, dir, name);
365 		perf_pmu__parse_scale(alias, dir, name);
366 		perf_pmu__parse_per_pkg(alias, dir, name);
367 		perf_pmu__parse_snapshot(alias, dir, name);
368 	}
369 
370 	alias->metric_expr = metric_expr ? strdup(metric_expr) : NULL;
371 	alias->metric_name = metric_name ? strdup(metric_name): NULL;
372 	alias->desc = desc ? strdup(desc) : NULL;
373 	alias->long_desc = long_desc ? strdup(long_desc) :
374 				desc ? strdup(desc) : NULL;
375 	alias->topic = topic ? strdup(topic) : NULL;
376 	if (unit) {
377 		if (perf_pmu__convert_scale(unit, &unit, &alias->scale) < 0)
378 			return -1;
379 		snprintf(alias->unit, sizeof(alias->unit), "%s", unit);
380 	}
381 	alias->per_pkg = perpkg && sscanf(perpkg, "%d", &num) == 1 && num == 1;
382 	alias->str = strdup(newval);
383 
384 	if (deprecated)
385 		alias->deprecated = true;
386 
387 	if (!perf_pmu_merge_alias(alias, list))
388 		list_add_tail(&alias->list, list);
389 
390 	return 0;
391 }
392 
393 static int perf_pmu__new_alias(struct list_head *list, char *dir, char *name, FILE *file)
394 {
395 	char buf[256];
396 	int ret;
397 
398 	ret = fread(buf, 1, sizeof(buf), file);
399 	if (ret == 0)
400 		return -EINVAL;
401 
402 	buf[ret] = 0;
403 
404 	/* Remove trailing newline from sysfs file */
405 	strim(buf);
406 
407 	return __perf_pmu__new_alias(list, dir, name, NULL, buf, NULL, NULL, NULL,
408 				     NULL, NULL, NULL, NULL);
409 }
410 
411 static inline bool pmu_alias_info_file(char *name)
412 {
413 	size_t len;
414 
415 	len = strlen(name);
416 	if (len > 5 && !strcmp(name + len - 5, ".unit"))
417 		return true;
418 	if (len > 6 && !strcmp(name + len - 6, ".scale"))
419 		return true;
420 	if (len > 8 && !strcmp(name + len - 8, ".per-pkg"))
421 		return true;
422 	if (len > 9 && !strcmp(name + len - 9, ".snapshot"))
423 		return true;
424 
425 	return false;
426 }
427 
428 /*
429  * Process all the sysfs attributes located under the directory
430  * specified in 'dir' parameter.
431  */
432 static int pmu_aliases_parse(char *dir, struct list_head *head)
433 {
434 	struct dirent *evt_ent;
435 	DIR *event_dir;
436 
437 	event_dir = opendir(dir);
438 	if (!event_dir)
439 		return -EINVAL;
440 
441 	while ((evt_ent = readdir(event_dir))) {
442 		char path[PATH_MAX];
443 		char *name = evt_ent->d_name;
444 		FILE *file;
445 
446 		if (!strcmp(name, ".") || !strcmp(name, ".."))
447 			continue;
448 
449 		/*
450 		 * skip info files parsed in perf_pmu__new_alias()
451 		 */
452 		if (pmu_alias_info_file(name))
453 			continue;
454 
455 		scnprintf(path, PATH_MAX, "%s/%s", dir, name);
456 
457 		file = fopen(path, "r");
458 		if (!file) {
459 			pr_debug("Cannot open %s\n", path);
460 			continue;
461 		}
462 
463 		if (perf_pmu__new_alias(head, dir, name, file) < 0)
464 			pr_debug("Cannot set up %s\n", name);
465 		fclose(file);
466 	}
467 
468 	closedir(event_dir);
469 	return 0;
470 }
471 
472 /*
473  * Reading the pmu event aliases definition, which should be located at:
474  * /sys/bus/event_source/devices/<dev>/events as sysfs group attributes.
475  */
476 static int pmu_aliases(const char *name, struct list_head *head)
477 {
478 	char path[PATH_MAX];
479 	const char *sysfs = sysfs__mountpoint();
480 
481 	if (!sysfs)
482 		return -1;
483 
484 	snprintf(path, PATH_MAX,
485 		 "%s/bus/event_source/devices/%s/events", sysfs, name);
486 
487 	if (!file_available(path))
488 		return 0;
489 
490 	if (pmu_aliases_parse(path, head))
491 		return -1;
492 
493 	return 0;
494 }
495 
496 static int pmu_alias_terms(struct perf_pmu_alias *alias,
497 			   struct list_head *terms)
498 {
499 	struct parse_events_term *term, *cloned;
500 	LIST_HEAD(list);
501 	int ret;
502 
503 	list_for_each_entry(term, &alias->terms, list) {
504 		ret = parse_events_term__clone(&cloned, term);
505 		if (ret) {
506 			parse_events_terms__purge(&list);
507 			return ret;
508 		}
509 		/*
510 		 * Weak terms don't override command line options,
511 		 * which we don't want for implicit terms in aliases.
512 		 */
513 		cloned->weak = true;
514 		list_add_tail(&cloned->list, &list);
515 	}
516 	list_splice(&list, terms);
517 	return 0;
518 }
519 
520 /*
521  * Reading/parsing the default pmu type value, which should be
522  * located at:
523  * /sys/bus/event_source/devices/<dev>/type as sysfs attribute.
524  */
525 static int pmu_type(const char *name, __u32 *type)
526 {
527 	char path[PATH_MAX];
528 	FILE *file;
529 	int ret = 0;
530 	const char *sysfs = sysfs__mountpoint();
531 
532 	if (!sysfs)
533 		return -1;
534 
535 	snprintf(path, PATH_MAX,
536 		 "%s" EVENT_SOURCE_DEVICE_PATH "%s/type", sysfs, name);
537 
538 	if (access(path, R_OK) < 0)
539 		return -1;
540 
541 	file = fopen(path, "r");
542 	if (!file)
543 		return -EINVAL;
544 
545 	if (1 != fscanf(file, "%u", type))
546 		ret = -1;
547 
548 	fclose(file);
549 	return ret;
550 }
551 
552 /* Add all pmus in sysfs to pmu list: */
553 static void pmu_read_sysfs(void)
554 {
555 	char path[PATH_MAX];
556 	DIR *dir;
557 	struct dirent *dent;
558 	const char *sysfs = sysfs__mountpoint();
559 
560 	if (!sysfs)
561 		return;
562 
563 	snprintf(path, PATH_MAX,
564 		 "%s" EVENT_SOURCE_DEVICE_PATH, sysfs);
565 
566 	dir = opendir(path);
567 	if (!dir)
568 		return;
569 
570 	while ((dent = readdir(dir))) {
571 		if (!strcmp(dent->d_name, ".") || !strcmp(dent->d_name, ".."))
572 			continue;
573 		/* add to static LIST_HEAD(pmus): */
574 		perf_pmu__find(dent->d_name);
575 	}
576 
577 	closedir(dir);
578 }
579 
580 static struct perf_cpu_map *__pmu_cpumask(const char *path)
581 {
582 	FILE *file;
583 	struct perf_cpu_map *cpus;
584 
585 	file = fopen(path, "r");
586 	if (!file)
587 		return NULL;
588 
589 	cpus = perf_cpu_map__read(file);
590 	fclose(file);
591 	return cpus;
592 }
593 
594 /*
595  * Uncore PMUs have a "cpumask" file under sysfs. CPU PMUs (e.g. on arm/arm64)
596  * may have a "cpus" file.
597  */
598 #define CPUS_TEMPLATE_UNCORE	"%s/bus/event_source/devices/%s/cpumask"
599 #define CPUS_TEMPLATE_CPU	"%s/bus/event_source/devices/%s/cpus"
600 
601 static struct perf_cpu_map *pmu_cpumask(const char *name)
602 {
603 	char path[PATH_MAX];
604 	struct perf_cpu_map *cpus;
605 	const char *sysfs = sysfs__mountpoint();
606 	const char *templates[] = {
607 		CPUS_TEMPLATE_UNCORE,
608 		CPUS_TEMPLATE_CPU,
609 		NULL
610 	};
611 	const char **template;
612 
613 	if (!sysfs)
614 		return NULL;
615 
616 	for (template = templates; *template; template++) {
617 		snprintf(path, PATH_MAX, *template, sysfs, name);
618 		cpus = __pmu_cpumask(path);
619 		if (cpus)
620 			return cpus;
621 	}
622 
623 	return NULL;
624 }
625 
626 static bool pmu_is_uncore(const char *name)
627 {
628 	char path[PATH_MAX];
629 	const char *sysfs;
630 
631 	sysfs = sysfs__mountpoint();
632 	snprintf(path, PATH_MAX, CPUS_TEMPLATE_UNCORE, sysfs, name);
633 	return file_available(path);
634 }
635 
636 /*
637  *  PMU CORE devices have different name other than cpu in sysfs on some
638  *  platforms.
639  *  Looking for possible sysfs files to identify the arm core device.
640  */
641 static int is_arm_pmu_core(const char *name)
642 {
643 	char path[PATH_MAX];
644 	const char *sysfs = sysfs__mountpoint();
645 
646 	if (!sysfs)
647 		return 0;
648 
649 	/* Look for cpu sysfs (specific to arm) */
650 	scnprintf(path, PATH_MAX, "%s/bus/event_source/devices/%s/cpus",
651 				sysfs, name);
652 	return file_available(path);
653 }
654 
655 static char *perf_pmu__getcpuid(struct perf_pmu *pmu)
656 {
657 	char *cpuid;
658 	static bool printed;
659 
660 	cpuid = getenv("PERF_CPUID");
661 	if (cpuid)
662 		cpuid = strdup(cpuid);
663 	if (!cpuid)
664 		cpuid = get_cpuid_str(pmu);
665 	if (!cpuid)
666 		return NULL;
667 
668 	if (!printed) {
669 		pr_debug("Using CPUID %s\n", cpuid);
670 		printed = true;
671 	}
672 	return cpuid;
673 }
674 
675 struct pmu_events_map *perf_pmu__find_map(struct perf_pmu *pmu)
676 {
677 	struct pmu_events_map *map;
678 	char *cpuid = perf_pmu__getcpuid(pmu);
679 	int i;
680 
681 	/* on some platforms which uses cpus map, cpuid can be NULL for
682 	 * PMUs other than CORE PMUs.
683 	 */
684 	if (!cpuid)
685 		return NULL;
686 
687 	i = 0;
688 	for (;;) {
689 		map = &pmu_events_map[i++];
690 		if (!map->table) {
691 			map = NULL;
692 			break;
693 		}
694 
695 		if (!strcmp_cpuid_str(map->cpuid, cpuid))
696 			break;
697 	}
698 	free(cpuid);
699 	return map;
700 }
701 
702 bool pmu_uncore_alias_match(const char *pmu_name, const char *name)
703 {
704 	char *tmp = NULL, *tok, *str;
705 	bool res;
706 
707 	str = strdup(pmu_name);
708 	if (!str)
709 		return false;
710 
711 	/*
712 	 * uncore alias may be from different PMU with common prefix
713 	 */
714 	tok = strtok_r(str, ",", &tmp);
715 	if (strncmp(pmu_name, tok, strlen(tok))) {
716 		res = false;
717 		goto out;
718 	}
719 
720 	/*
721 	 * Match more complex aliases where the alias name is a comma-delimited
722 	 * list of tokens, orderly contained in the matching PMU name.
723 	 *
724 	 * Example: For alias "socket,pmuname" and PMU "socketX_pmunameY", we
725 	 *	    match "socket" in "socketX_pmunameY" and then "pmuname" in
726 	 *	    "pmunameY".
727 	 */
728 	for (; tok; name += strlen(tok), tok = strtok_r(NULL, ",", &tmp)) {
729 		name = strstr(name, tok);
730 		if (!name) {
731 			res = false;
732 			goto out;
733 		}
734 	}
735 
736 	res = true;
737 out:
738 	free(str);
739 	return res;
740 }
741 
742 /*
743  * From the pmu_events_map, find the table of PMU events that corresponds
744  * to the current running CPU. Then, add all PMU events from that table
745  * as aliases.
746  */
747 void pmu_add_cpu_aliases_map(struct list_head *head, struct perf_pmu *pmu,
748 			     struct pmu_events_map *map)
749 {
750 	int i;
751 	const char *name = pmu->name;
752 	/*
753 	 * Found a matching PMU events table. Create aliases
754 	 */
755 	i = 0;
756 	while (1) {
757 		const char *cpu_name = is_arm_pmu_core(name) ? name : "cpu";
758 		struct pmu_event *pe = &map->table[i++];
759 		const char *pname = pe->pmu ? pe->pmu : cpu_name;
760 
761 		if (!pe->name) {
762 			if (pe->metric_group || pe->metric_name)
763 				continue;
764 			break;
765 		}
766 
767 		if (pmu_is_uncore(name) &&
768 		    pmu_uncore_alias_match(pname, name))
769 			goto new_alias;
770 
771 		if (strcmp(pname, name))
772 			continue;
773 
774 new_alias:
775 		/* need type casts to override 'const' */
776 		__perf_pmu__new_alias(head, NULL, (char *)pe->name,
777 				(char *)pe->desc, (char *)pe->event,
778 				(char *)pe->long_desc, (char *)pe->topic,
779 				(char *)pe->unit, (char *)pe->perpkg,
780 				(char *)pe->metric_expr,
781 				(char *)pe->metric_name,
782 				(char *)pe->deprecated);
783 	}
784 }
785 
786 static void pmu_add_cpu_aliases(struct list_head *head, struct perf_pmu *pmu)
787 {
788 	struct pmu_events_map *map;
789 
790 	map = perf_pmu__find_map(pmu);
791 	if (!map)
792 		return;
793 
794 	pmu_add_cpu_aliases_map(head, pmu, map);
795 }
796 
797 struct perf_event_attr * __weak
798 perf_pmu__get_default_config(struct perf_pmu *pmu __maybe_unused)
799 {
800 	return NULL;
801 }
802 
803 static int pmu_max_precise(const char *name)
804 {
805 	char path[PATH_MAX];
806 	int max_precise = -1;
807 
808 	scnprintf(path, PATH_MAX,
809 		 "bus/event_source/devices/%s/caps/max_precise",
810 		 name);
811 
812 	sysfs__read_int(path, &max_precise);
813 	return max_precise;
814 }
815 
816 static struct perf_pmu *pmu_lookup(const char *name)
817 {
818 	struct perf_pmu *pmu;
819 	LIST_HEAD(format);
820 	LIST_HEAD(aliases);
821 	__u32 type;
822 
823 	/*
824 	 * The pmu data we store & need consists of the pmu
825 	 * type value and format definitions. Load both right
826 	 * now.
827 	 */
828 	if (pmu_format(name, &format))
829 		return NULL;
830 
831 	/*
832 	 * Check the type first to avoid unnecessary work.
833 	 */
834 	if (pmu_type(name, &type))
835 		return NULL;
836 
837 	if (pmu_aliases(name, &aliases))
838 		return NULL;
839 
840 	pmu = zalloc(sizeof(*pmu));
841 	if (!pmu)
842 		return NULL;
843 
844 	pmu->cpus = pmu_cpumask(name);
845 	pmu->name = strdup(name);
846 	pmu->type = type;
847 	pmu->is_uncore = pmu_is_uncore(name);
848 	pmu->max_precise = pmu_max_precise(name);
849 	pmu_add_cpu_aliases(&aliases, pmu);
850 
851 	INIT_LIST_HEAD(&pmu->format);
852 	INIT_LIST_HEAD(&pmu->aliases);
853 	INIT_LIST_HEAD(&pmu->caps);
854 	list_splice(&format, &pmu->format);
855 	list_splice(&aliases, &pmu->aliases);
856 	list_add_tail(&pmu->list, &pmus);
857 
858 	pmu->default_config = perf_pmu__get_default_config(pmu);
859 
860 	return pmu;
861 }
862 
863 static struct perf_pmu *pmu_find(const char *name)
864 {
865 	struct perf_pmu *pmu;
866 
867 	list_for_each_entry(pmu, &pmus, list)
868 		if (!strcmp(pmu->name, name))
869 			return pmu;
870 
871 	return NULL;
872 }
873 
874 struct perf_pmu *perf_pmu__find_by_type(unsigned int type)
875 {
876 	struct perf_pmu *pmu;
877 
878 	list_for_each_entry(pmu, &pmus, list)
879 		if (pmu->type == type)
880 			return pmu;
881 
882 	return NULL;
883 }
884 
885 struct perf_pmu *perf_pmu__scan(struct perf_pmu *pmu)
886 {
887 	/*
888 	 * pmu iterator: If pmu is NULL, we start at the begin,
889 	 * otherwise return the next pmu. Returns NULL on end.
890 	 */
891 	if (!pmu) {
892 		pmu_read_sysfs();
893 		pmu = list_prepare_entry(pmu, &pmus, list);
894 	}
895 	list_for_each_entry_continue(pmu, &pmus, list)
896 		return pmu;
897 	return NULL;
898 }
899 
900 struct perf_pmu *evsel__find_pmu(struct evsel *evsel)
901 {
902 	struct perf_pmu *pmu = NULL;
903 
904 	while ((pmu = perf_pmu__scan(pmu)) != NULL) {
905 		if (pmu->type == evsel->core.attr.type)
906 			break;
907 	}
908 
909 	return pmu;
910 }
911 
912 bool evsel__is_aux_event(struct evsel *evsel)
913 {
914 	struct perf_pmu *pmu = evsel__find_pmu(evsel);
915 
916 	return pmu && pmu->auxtrace;
917 }
918 
919 struct perf_pmu *perf_pmu__find(const char *name)
920 {
921 	struct perf_pmu *pmu;
922 
923 	/*
924 	 * Once PMU is loaded it stays in the list,
925 	 * so we keep us from multiple reading/parsing
926 	 * the pmu format definitions.
927 	 */
928 	pmu = pmu_find(name);
929 	if (pmu)
930 		return pmu;
931 
932 	return pmu_lookup(name);
933 }
934 
935 static struct perf_pmu_format *
936 pmu_find_format(struct list_head *formats, const char *name)
937 {
938 	struct perf_pmu_format *format;
939 
940 	list_for_each_entry(format, formats, list)
941 		if (!strcmp(format->name, name))
942 			return format;
943 
944 	return NULL;
945 }
946 
947 __u64 perf_pmu__format_bits(struct list_head *formats, const char *name)
948 {
949 	struct perf_pmu_format *format = pmu_find_format(formats, name);
950 	__u64 bits = 0;
951 	int fbit;
952 
953 	if (!format)
954 		return 0;
955 
956 	for_each_set_bit(fbit, format->bits, PERF_PMU_FORMAT_BITS)
957 		bits |= 1ULL << fbit;
958 
959 	return bits;
960 }
961 
962 int perf_pmu__format_type(struct list_head *formats, const char *name)
963 {
964 	struct perf_pmu_format *format = pmu_find_format(formats, name);
965 
966 	if (!format)
967 		return -1;
968 
969 	return format->value;
970 }
971 
972 /*
973  * Sets value based on the format definition (format parameter)
974  * and unformated value (value parameter).
975  */
976 static void pmu_format_value(unsigned long *format, __u64 value, __u64 *v,
977 			     bool zero)
978 {
979 	unsigned long fbit, vbit;
980 
981 	for (fbit = 0, vbit = 0; fbit < PERF_PMU_FORMAT_BITS; fbit++) {
982 
983 		if (!test_bit(fbit, format))
984 			continue;
985 
986 		if (value & (1llu << vbit++))
987 			*v |= (1llu << fbit);
988 		else if (zero)
989 			*v &= ~(1llu << fbit);
990 	}
991 }
992 
993 static __u64 pmu_format_max_value(const unsigned long *format)
994 {
995 	int w;
996 
997 	w = bitmap_weight(format, PERF_PMU_FORMAT_BITS);
998 	if (!w)
999 		return 0;
1000 	if (w < 64)
1001 		return (1ULL << w) - 1;
1002 	return -1;
1003 }
1004 
1005 /*
1006  * Term is a string term, and might be a param-term. Try to look up it's value
1007  * in the remaining terms.
1008  * - We have a term like "base-or-format-term=param-term",
1009  * - We need to find the value supplied for "param-term" (with param-term named
1010  *   in a config string) later on in the term list.
1011  */
1012 static int pmu_resolve_param_term(struct parse_events_term *term,
1013 				  struct list_head *head_terms,
1014 				  __u64 *value)
1015 {
1016 	struct parse_events_term *t;
1017 
1018 	list_for_each_entry(t, head_terms, list) {
1019 		if (t->type_val == PARSE_EVENTS__TERM_TYPE_NUM &&
1020 		    t->config && !strcmp(t->config, term->config)) {
1021 			t->used = true;
1022 			*value = t->val.num;
1023 			return 0;
1024 		}
1025 	}
1026 
1027 	if (verbose > 0)
1028 		printf("Required parameter '%s' not specified\n", term->config);
1029 
1030 	return -1;
1031 }
1032 
1033 static char *pmu_formats_string(struct list_head *formats)
1034 {
1035 	struct perf_pmu_format *format;
1036 	char *str = NULL;
1037 	struct strbuf buf = STRBUF_INIT;
1038 	unsigned i = 0;
1039 
1040 	if (!formats)
1041 		return NULL;
1042 
1043 	/* sysfs exported terms */
1044 	list_for_each_entry(format, formats, list)
1045 		if (strbuf_addf(&buf, i++ ? ",%s" : "%s", format->name) < 0)
1046 			goto error;
1047 
1048 	str = strbuf_detach(&buf, NULL);
1049 error:
1050 	strbuf_release(&buf);
1051 
1052 	return str;
1053 }
1054 
1055 /*
1056  * Setup one of config[12] attr members based on the
1057  * user input data - term parameter.
1058  */
1059 static int pmu_config_term(struct list_head *formats,
1060 			   struct perf_event_attr *attr,
1061 			   struct parse_events_term *term,
1062 			   struct list_head *head_terms,
1063 			   bool zero, struct parse_events_error *err)
1064 {
1065 	struct perf_pmu_format *format;
1066 	__u64 *vp;
1067 	__u64 val, max_val;
1068 
1069 	/*
1070 	 * If this is a parameter we've already used for parameterized-eval,
1071 	 * skip it in normal eval.
1072 	 */
1073 	if (term->used)
1074 		return 0;
1075 
1076 	/*
1077 	 * Hardcoded terms should be already in, so nothing
1078 	 * to be done for them.
1079 	 */
1080 	if (parse_events__is_hardcoded_term(term))
1081 		return 0;
1082 
1083 	format = pmu_find_format(formats, term->config);
1084 	if (!format) {
1085 		if (verbose > 0)
1086 			printf("Invalid event/parameter '%s'\n", term->config);
1087 		if (err) {
1088 			char *pmu_term = pmu_formats_string(formats);
1089 
1090 			parse_events__handle_error(err, term->err_term,
1091 				strdup("unknown term"),
1092 				parse_events_formats_error_string(pmu_term));
1093 			free(pmu_term);
1094 		}
1095 		return -EINVAL;
1096 	}
1097 
1098 	switch (format->value) {
1099 	case PERF_PMU_FORMAT_VALUE_CONFIG:
1100 		vp = &attr->config;
1101 		break;
1102 	case PERF_PMU_FORMAT_VALUE_CONFIG1:
1103 		vp = &attr->config1;
1104 		break;
1105 	case PERF_PMU_FORMAT_VALUE_CONFIG2:
1106 		vp = &attr->config2;
1107 		break;
1108 	default:
1109 		return -EINVAL;
1110 	}
1111 
1112 	/*
1113 	 * Either directly use a numeric term, or try to translate string terms
1114 	 * using event parameters.
1115 	 */
1116 	if (term->type_val == PARSE_EVENTS__TERM_TYPE_NUM) {
1117 		if (term->no_value &&
1118 		    bitmap_weight(format->bits, PERF_PMU_FORMAT_BITS) > 1) {
1119 			if (err) {
1120 				parse_events__handle_error(err, term->err_val,
1121 					   strdup("no value assigned for term"),
1122 					   NULL);
1123 			}
1124 			return -EINVAL;
1125 		}
1126 
1127 		val = term->val.num;
1128 	} else if (term->type_val == PARSE_EVENTS__TERM_TYPE_STR) {
1129 		if (strcmp(term->val.str, "?")) {
1130 			if (verbose > 0) {
1131 				pr_info("Invalid sysfs entry %s=%s\n",
1132 						term->config, term->val.str);
1133 			}
1134 			if (err) {
1135 				parse_events__handle_error(err, term->err_val,
1136 					strdup("expected numeric value"),
1137 					NULL);
1138 			}
1139 			return -EINVAL;
1140 		}
1141 
1142 		if (pmu_resolve_param_term(term, head_terms, &val))
1143 			return -EINVAL;
1144 	} else
1145 		return -EINVAL;
1146 
1147 	max_val = pmu_format_max_value(format->bits);
1148 	if (val > max_val) {
1149 		if (err) {
1150 			char *err_str;
1151 
1152 			parse_events__handle_error(err, term->err_val,
1153 				asprintf(&err_str,
1154 				    "value too big for format, maximum is %llu",
1155 				    (unsigned long long)max_val) < 0
1156 				    ? strdup("value too big for format")
1157 				    : err_str,
1158 				    NULL);
1159 			return -EINVAL;
1160 		}
1161 		/*
1162 		 * Assume we don't care if !err, in which case the value will be
1163 		 * silently truncated.
1164 		 */
1165 	}
1166 
1167 	pmu_format_value(format->bits, val, vp, zero);
1168 	return 0;
1169 }
1170 
1171 int perf_pmu__config_terms(struct list_head *formats,
1172 			   struct perf_event_attr *attr,
1173 			   struct list_head *head_terms,
1174 			   bool zero, struct parse_events_error *err)
1175 {
1176 	struct parse_events_term *term;
1177 
1178 	list_for_each_entry(term, head_terms, list) {
1179 		if (pmu_config_term(formats, attr, term, head_terms,
1180 				    zero, err))
1181 			return -EINVAL;
1182 	}
1183 
1184 	return 0;
1185 }
1186 
1187 /*
1188  * Configures event's 'attr' parameter based on the:
1189  * 1) users input - specified in terms parameter
1190  * 2) pmu format definitions - specified by pmu parameter
1191  */
1192 int perf_pmu__config(struct perf_pmu *pmu, struct perf_event_attr *attr,
1193 		     struct list_head *head_terms,
1194 		     struct parse_events_error *err)
1195 {
1196 	bool zero = !!pmu->default_config;
1197 
1198 	attr->type = pmu->type;
1199 	return perf_pmu__config_terms(&pmu->format, attr, head_terms,
1200 				      zero, err);
1201 }
1202 
1203 static struct perf_pmu_alias *pmu_find_alias(struct perf_pmu *pmu,
1204 					     struct parse_events_term *term)
1205 {
1206 	struct perf_pmu_alias *alias;
1207 	char *name;
1208 
1209 	if (parse_events__is_hardcoded_term(term))
1210 		return NULL;
1211 
1212 	if (term->type_val == PARSE_EVENTS__TERM_TYPE_NUM) {
1213 		if (term->val.num != 1)
1214 			return NULL;
1215 		if (pmu_find_format(&pmu->format, term->config))
1216 			return NULL;
1217 		name = term->config;
1218 	} else if (term->type_val == PARSE_EVENTS__TERM_TYPE_STR) {
1219 		if (strcasecmp(term->config, "event"))
1220 			return NULL;
1221 		name = term->val.str;
1222 	} else {
1223 		return NULL;
1224 	}
1225 
1226 	list_for_each_entry(alias, &pmu->aliases, list) {
1227 		if (!strcasecmp(alias->name, name))
1228 			return alias;
1229 	}
1230 	return NULL;
1231 }
1232 
1233 
1234 static int check_info_data(struct perf_pmu_alias *alias,
1235 			   struct perf_pmu_info *info)
1236 {
1237 	/*
1238 	 * Only one term in event definition can
1239 	 * define unit, scale and snapshot, fail
1240 	 * if there's more than one.
1241 	 */
1242 	if ((info->unit && alias->unit[0]) ||
1243 	    (info->scale && alias->scale) ||
1244 	    (info->snapshot && alias->snapshot))
1245 		return -EINVAL;
1246 
1247 	if (alias->unit[0])
1248 		info->unit = alias->unit;
1249 
1250 	if (alias->scale)
1251 		info->scale = alias->scale;
1252 
1253 	if (alias->snapshot)
1254 		info->snapshot = alias->snapshot;
1255 
1256 	return 0;
1257 }
1258 
1259 /*
1260  * Find alias in the terms list and replace it with the terms
1261  * defined for the alias
1262  */
1263 int perf_pmu__check_alias(struct perf_pmu *pmu, struct list_head *head_terms,
1264 			  struct perf_pmu_info *info)
1265 {
1266 	struct parse_events_term *term, *h;
1267 	struct perf_pmu_alias *alias;
1268 	int ret;
1269 
1270 	info->per_pkg = false;
1271 
1272 	/*
1273 	 * Mark unit and scale as not set
1274 	 * (different from default values, see below)
1275 	 */
1276 	info->unit     = NULL;
1277 	info->scale    = 0.0;
1278 	info->snapshot = false;
1279 	info->metric_expr = NULL;
1280 	info->metric_name = NULL;
1281 
1282 	list_for_each_entry_safe(term, h, head_terms, list) {
1283 		alias = pmu_find_alias(pmu, term);
1284 		if (!alias)
1285 			continue;
1286 		ret = pmu_alias_terms(alias, &term->list);
1287 		if (ret)
1288 			return ret;
1289 
1290 		ret = check_info_data(alias, info);
1291 		if (ret)
1292 			return ret;
1293 
1294 		if (alias->per_pkg)
1295 			info->per_pkg = true;
1296 		info->metric_expr = alias->metric_expr;
1297 		info->metric_name = alias->metric_name;
1298 
1299 		list_del_init(&term->list);
1300 		parse_events_term__delete(term);
1301 	}
1302 
1303 	/*
1304 	 * if no unit or scale foundin aliases, then
1305 	 * set defaults as for evsel
1306 	 * unit cannot left to NULL
1307 	 */
1308 	if (info->unit == NULL)
1309 		info->unit   = "";
1310 
1311 	if (info->scale == 0.0)
1312 		info->scale  = 1.0;
1313 
1314 	return 0;
1315 }
1316 
1317 int perf_pmu__new_format(struct list_head *list, char *name,
1318 			 int config, unsigned long *bits)
1319 {
1320 	struct perf_pmu_format *format;
1321 
1322 	format = zalloc(sizeof(*format));
1323 	if (!format)
1324 		return -ENOMEM;
1325 
1326 	format->name = strdup(name);
1327 	format->value = config;
1328 	memcpy(format->bits, bits, sizeof(format->bits));
1329 
1330 	list_add_tail(&format->list, list);
1331 	return 0;
1332 }
1333 
1334 void perf_pmu__set_format(unsigned long *bits, long from, long to)
1335 {
1336 	long b;
1337 
1338 	if (!to)
1339 		to = from;
1340 
1341 	memset(bits, 0, BITS_TO_BYTES(PERF_PMU_FORMAT_BITS));
1342 	for (b = from; b <= to; b++)
1343 		set_bit(b, bits);
1344 }
1345 
1346 static int sub_non_neg(int a, int b)
1347 {
1348 	if (b > a)
1349 		return 0;
1350 	return a - b;
1351 }
1352 
1353 static char *format_alias(char *buf, int len, struct perf_pmu *pmu,
1354 			  struct perf_pmu_alias *alias)
1355 {
1356 	struct parse_events_term *term;
1357 	int used = snprintf(buf, len, "%s/%s", pmu->name, alias->name);
1358 
1359 	list_for_each_entry(term, &alias->terms, list) {
1360 		if (term->type_val == PARSE_EVENTS__TERM_TYPE_STR)
1361 			used += snprintf(buf + used, sub_non_neg(len, used),
1362 					",%s=%s", term->config,
1363 					term->val.str);
1364 	}
1365 
1366 	if (sub_non_neg(len, used) > 0) {
1367 		buf[used] = '/';
1368 		used++;
1369 	}
1370 	if (sub_non_neg(len, used) > 0) {
1371 		buf[used] = '\0';
1372 		used++;
1373 	} else
1374 		buf[len - 1] = '\0';
1375 
1376 	return buf;
1377 }
1378 
1379 static char *format_alias_or(char *buf, int len, struct perf_pmu *pmu,
1380 			     struct perf_pmu_alias *alias)
1381 {
1382 	snprintf(buf, len, "%s OR %s/%s/", alias->name, pmu->name, alias->name);
1383 	return buf;
1384 }
1385 
1386 struct sevent {
1387 	char *name;
1388 	char *desc;
1389 	char *topic;
1390 	char *str;
1391 	char *pmu;
1392 	char *metric_expr;
1393 	char *metric_name;
1394 };
1395 
1396 static int cmp_sevent(const void *a, const void *b)
1397 {
1398 	const struct sevent *as = a;
1399 	const struct sevent *bs = b;
1400 
1401 	/* Put extra events last */
1402 	if (!!as->desc != !!bs->desc)
1403 		return !!as->desc - !!bs->desc;
1404 	if (as->topic && bs->topic) {
1405 		int n = strcmp(as->topic, bs->topic);
1406 
1407 		if (n)
1408 			return n;
1409 	}
1410 	return strcmp(as->name, bs->name);
1411 }
1412 
1413 static void wordwrap(char *s, int start, int max, int corr)
1414 {
1415 	int column = start;
1416 	int n;
1417 
1418 	while (*s) {
1419 		int wlen = strcspn(s, " \t");
1420 
1421 		if (column + wlen >= max && column > start) {
1422 			printf("\n%*s", start, "");
1423 			column = start + corr;
1424 		}
1425 		n = printf("%s%.*s", column > start ? " " : "", wlen, s);
1426 		if (n <= 0)
1427 			break;
1428 		s += wlen;
1429 		column += n;
1430 		s = skip_spaces(s);
1431 	}
1432 }
1433 
1434 bool is_pmu_core(const char *name)
1435 {
1436 	return !strcmp(name, "cpu") || is_arm_pmu_core(name);
1437 }
1438 
1439 void print_pmu_events(const char *event_glob, bool name_only, bool quiet_flag,
1440 			bool long_desc, bool details_flag, bool deprecated)
1441 {
1442 	struct perf_pmu *pmu;
1443 	struct perf_pmu_alias *alias;
1444 	char buf[1024];
1445 	int printed = 0;
1446 	int len, j;
1447 	struct sevent *aliases;
1448 	int numdesc = 0;
1449 	int columns = pager_get_columns();
1450 	char *topic = NULL;
1451 
1452 	pmu = NULL;
1453 	len = 0;
1454 	while ((pmu = perf_pmu__scan(pmu)) != NULL) {
1455 		list_for_each_entry(alias, &pmu->aliases, list)
1456 			len++;
1457 		if (pmu->selectable)
1458 			len++;
1459 	}
1460 	aliases = zalloc(sizeof(struct sevent) * len);
1461 	if (!aliases)
1462 		goto out_enomem;
1463 	pmu = NULL;
1464 	j = 0;
1465 	while ((pmu = perf_pmu__scan(pmu)) != NULL) {
1466 		list_for_each_entry(alias, &pmu->aliases, list) {
1467 			char *name = alias->desc ? alias->name :
1468 				format_alias(buf, sizeof(buf), pmu, alias);
1469 			bool is_cpu = !strcmp(pmu->name, "cpu");
1470 
1471 			if (alias->deprecated && !deprecated)
1472 				continue;
1473 
1474 			if (event_glob != NULL &&
1475 			    !(strglobmatch_nocase(name, event_glob) ||
1476 			      (!is_cpu && strglobmatch_nocase(alias->name,
1477 						       event_glob)) ||
1478 			      (alias->topic &&
1479 			       strglobmatch_nocase(alias->topic, event_glob))))
1480 				continue;
1481 
1482 			if (is_cpu && !name_only && !alias->desc)
1483 				name = format_alias_or(buf, sizeof(buf), pmu, alias);
1484 
1485 			aliases[j].name = name;
1486 			if (is_cpu && !name_only && !alias->desc)
1487 				aliases[j].name = format_alias_or(buf,
1488 								  sizeof(buf),
1489 								  pmu, alias);
1490 			aliases[j].name = strdup(aliases[j].name);
1491 			if (!aliases[j].name)
1492 				goto out_enomem;
1493 
1494 			aliases[j].desc = long_desc ? alias->long_desc :
1495 						alias->desc;
1496 			aliases[j].topic = alias->topic;
1497 			aliases[j].str = alias->str;
1498 			aliases[j].pmu = pmu->name;
1499 			aliases[j].metric_expr = alias->metric_expr;
1500 			aliases[j].metric_name = alias->metric_name;
1501 			j++;
1502 		}
1503 		if (pmu->selectable &&
1504 		    (event_glob == NULL || strglobmatch(pmu->name, event_glob))) {
1505 			char *s;
1506 			if (asprintf(&s, "%s//", pmu->name) < 0)
1507 				goto out_enomem;
1508 			aliases[j].name = s;
1509 			j++;
1510 		}
1511 	}
1512 	len = j;
1513 	qsort(aliases, len, sizeof(struct sevent), cmp_sevent);
1514 	for (j = 0; j < len; j++) {
1515 		/* Skip duplicates */
1516 		if (j > 0 && !strcmp(aliases[j].name, aliases[j - 1].name))
1517 			continue;
1518 		if (name_only) {
1519 			printf("%s ", aliases[j].name);
1520 			continue;
1521 		}
1522 		if (aliases[j].desc && !quiet_flag) {
1523 			if (numdesc++ == 0)
1524 				printf("\n");
1525 			if (aliases[j].topic && (!topic ||
1526 					strcmp(topic, aliases[j].topic))) {
1527 				printf("%s%s:\n", topic ? "\n" : "",
1528 						aliases[j].topic);
1529 				topic = aliases[j].topic;
1530 			}
1531 			printf("  %-50s\n", aliases[j].name);
1532 			printf("%*s", 8, "[");
1533 			wordwrap(aliases[j].desc, 8, columns, 0);
1534 			printf("]\n");
1535 			if (details_flag) {
1536 				printf("%*s%s/%s/ ", 8, "", aliases[j].pmu, aliases[j].str);
1537 				if (aliases[j].metric_name)
1538 					printf(" MetricName: %s", aliases[j].metric_name);
1539 				if (aliases[j].metric_expr)
1540 					printf(" MetricExpr: %s", aliases[j].metric_expr);
1541 				putchar('\n');
1542 			}
1543 		} else
1544 			printf("  %-50s [Kernel PMU event]\n", aliases[j].name);
1545 		printed++;
1546 	}
1547 	if (printed && pager_in_use())
1548 		printf("\n");
1549 out_free:
1550 	for (j = 0; j < len; j++)
1551 		zfree(&aliases[j].name);
1552 	zfree(&aliases);
1553 	return;
1554 
1555 out_enomem:
1556 	printf("FATAL: not enough memory to print PMU events\n");
1557 	if (aliases)
1558 		goto out_free;
1559 }
1560 
1561 bool pmu_have_event(const char *pname, const char *name)
1562 {
1563 	struct perf_pmu *pmu;
1564 	struct perf_pmu_alias *alias;
1565 
1566 	pmu = NULL;
1567 	while ((pmu = perf_pmu__scan(pmu)) != NULL) {
1568 		if (strcmp(pname, pmu->name))
1569 			continue;
1570 		list_for_each_entry(alias, &pmu->aliases, list)
1571 			if (!strcmp(alias->name, name))
1572 				return true;
1573 	}
1574 	return false;
1575 }
1576 
1577 static FILE *perf_pmu__open_file(struct perf_pmu *pmu, const char *name)
1578 {
1579 	char path[PATH_MAX];
1580 	const char *sysfs;
1581 
1582 	sysfs = sysfs__mountpoint();
1583 	if (!sysfs)
1584 		return NULL;
1585 
1586 	snprintf(path, PATH_MAX,
1587 		 "%s" EVENT_SOURCE_DEVICE_PATH "%s/%s", sysfs, pmu->name, name);
1588 	if (!file_available(path))
1589 		return NULL;
1590 	return fopen(path, "r");
1591 }
1592 
1593 int perf_pmu__scan_file(struct perf_pmu *pmu, const char *name, const char *fmt,
1594 			...)
1595 {
1596 	va_list args;
1597 	FILE *file;
1598 	int ret = EOF;
1599 
1600 	va_start(args, fmt);
1601 	file = perf_pmu__open_file(pmu, name);
1602 	if (file) {
1603 		ret = vfscanf(file, fmt, args);
1604 		fclose(file);
1605 	}
1606 	va_end(args);
1607 	return ret;
1608 }
1609 
1610 static int perf_pmu__new_caps(struct list_head *list, char *name, char *value)
1611 {
1612 	struct perf_pmu_caps *caps = zalloc(sizeof(*caps));
1613 
1614 	if (!caps)
1615 		return -ENOMEM;
1616 
1617 	caps->name = strdup(name);
1618 	if (!caps->name)
1619 		goto free_caps;
1620 	caps->value = strndup(value, strlen(value) - 1);
1621 	if (!caps->value)
1622 		goto free_name;
1623 	list_add_tail(&caps->list, list);
1624 	return 0;
1625 
1626 free_name:
1627 	zfree(caps->name);
1628 free_caps:
1629 	free(caps);
1630 
1631 	return -ENOMEM;
1632 }
1633 
1634 /*
1635  * Reading/parsing the given pmu capabilities, which should be located at:
1636  * /sys/bus/event_source/devices/<dev>/caps as sysfs group attributes.
1637  * Return the number of capabilities
1638  */
1639 int perf_pmu__caps_parse(struct perf_pmu *pmu)
1640 {
1641 	struct stat st;
1642 	char caps_path[PATH_MAX];
1643 	const char *sysfs = sysfs__mountpoint();
1644 	DIR *caps_dir;
1645 	struct dirent *evt_ent;
1646 	int nr_caps = 0;
1647 
1648 	if (!sysfs)
1649 		return -1;
1650 
1651 	snprintf(caps_path, PATH_MAX,
1652 		 "%s" EVENT_SOURCE_DEVICE_PATH "%s/caps", sysfs, pmu->name);
1653 
1654 	if (stat(caps_path, &st) < 0)
1655 		return 0;	/* no error if caps does not exist */
1656 
1657 	caps_dir = opendir(caps_path);
1658 	if (!caps_dir)
1659 		return -EINVAL;
1660 
1661 	while ((evt_ent = readdir(caps_dir)) != NULL) {
1662 		char path[PATH_MAX + NAME_MAX + 1];
1663 		char *name = evt_ent->d_name;
1664 		char value[128];
1665 		FILE *file;
1666 
1667 		if (!strcmp(name, ".") || !strcmp(name, ".."))
1668 			continue;
1669 
1670 		snprintf(path, sizeof(path), "%s/%s", caps_path, name);
1671 
1672 		file = fopen(path, "r");
1673 		if (!file)
1674 			continue;
1675 
1676 		if (!fgets(value, sizeof(value), file) ||
1677 		    (perf_pmu__new_caps(&pmu->caps, name, value) < 0)) {
1678 			fclose(file);
1679 			continue;
1680 		}
1681 
1682 		nr_caps++;
1683 		fclose(file);
1684 	}
1685 
1686 	closedir(caps_dir);
1687 
1688 	return nr_caps;
1689 }
1690