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