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