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