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