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