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