xref: /linux/tools/perf/util/pmu.c (revision 40ccd6aa3e2e05be93394e3cd560c718dedfcc77)
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  * perf_pmu__match_ignoring_suffix - Does the pmu_name match tok ignoring any
852  *                                   trailing suffix? The Suffix must be in form
853  *                                   tok_{digits}, or tok{digits}.
854  * @pmu_name: The pmu_name with possible suffix.
855  * @tok: The possible match to pmu_name without suffix.
856  */
857 static bool perf_pmu__match_ignoring_suffix(const char *pmu_name, const char *tok)
858 {
859 	const char *p, *suffix;
860 	bool has_hex = false;
861 
862 	if (strncmp(pmu_name, tok, strlen(tok)))
863 		return false;
864 
865 	suffix = p = pmu_name + strlen(tok);
866 	if (*p == 0)
867 		return true;
868 
869 	if (*p == '_') {
870 		++p;
871 		++suffix;
872 	}
873 
874 	/* Ensure we end in a number */
875 	while (1) {
876 		if (!isxdigit(*p))
877 			return false;
878 		if (!has_hex)
879 			has_hex = !isdigit(*p);
880 		if (*(++p) == 0)
881 			break;
882 	}
883 
884 	if (has_hex)
885 		return (p - suffix) > 2;
886 
887 	return true;
888 }
889 
890 /**
891  * pmu_uncore_alias_match - does name match the PMU name?
892  * @pmu_name: the json struct pmu_event name. This may lack a suffix (which
893  *            matches) or be of the form "socket,pmuname" which will match
894  *            "socketX_pmunameY".
895  * @name: a real full PMU name as from sysfs.
896  */
897 static bool pmu_uncore_alias_match(const char *pmu_name, const char *name)
898 {
899 	char *tmp = NULL, *tok, *str;
900 	bool res;
901 
902 	if (strchr(pmu_name, ',') == NULL)
903 		return perf_pmu__match_ignoring_suffix(name, pmu_name);
904 
905 	str = strdup(pmu_name);
906 	if (!str)
907 		return false;
908 
909 	/*
910 	 * uncore alias may be from different PMU with common prefix
911 	 */
912 	tok = strtok_r(str, ",", &tmp);
913 	if (strncmp(pmu_name, tok, strlen(tok))) {
914 		res = false;
915 		goto out;
916 	}
917 
918 	/*
919 	 * Match more complex aliases where the alias name is a comma-delimited
920 	 * list of tokens, orderly contained in the matching PMU name.
921 	 *
922 	 * Example: For alias "socket,pmuname" and PMU "socketX_pmunameY", we
923 	 *	    match "socket" in "socketX_pmunameY" and then "pmuname" in
924 	 *	    "pmunameY".
925 	 */
926 	while (1) {
927 		char *next_tok = strtok_r(NULL, ",", &tmp);
928 
929 		name = strstr(name, tok);
930 		if (!name ||
931 		    (!next_tok && !perf_pmu__match_ignoring_suffix(name, tok))) {
932 			res = false;
933 			goto out;
934 		}
935 		if (!next_tok)
936 			break;
937 		tok = next_tok;
938 		name += strlen(tok);
939 	}
940 
941 	res = true;
942 out:
943 	free(str);
944 	return res;
945 }
946 
947 bool pmu_uncore_identifier_match(const char *compat, const char *id)
948 {
949 	regex_t re;
950 	regmatch_t pmatch[1];
951 	int match;
952 
953 	if (regcomp(&re, compat, REG_EXTENDED) != 0) {
954 		/* Warn unable to generate match particular string. */
955 		pr_info("Invalid regular expression %s\n", compat);
956 		return false;
957 	}
958 
959 	match = !regexec(&re, id, 1, pmatch, 0);
960 	if (match) {
961 		/* Ensure a full match. */
962 		match = pmatch[0].rm_so == 0 && (size_t)pmatch[0].rm_eo == strlen(id);
963 	}
964 	regfree(&re);
965 
966 	return match;
967 }
968 
969 static int pmu_add_cpu_aliases_map_callback(const struct pmu_event *pe,
970 					const struct pmu_events_table *table __maybe_unused,
971 					void *vdata)
972 {
973 	struct perf_pmu *pmu = vdata;
974 
975 	perf_pmu__new_alias(pmu, pe->name, pe->desc, pe->event, /*val_fd=*/ NULL,
976 			    pe, EVENT_SRC_CPU_JSON);
977 	return 0;
978 }
979 
980 /*
981  * From the pmu_events_table, find the events that correspond to the given
982  * PMU and add them to the list 'head'.
983  */
984 void pmu_add_cpu_aliases_table(struct perf_pmu *pmu, const struct pmu_events_table *table)
985 {
986 	pmu_events_table__for_each_event(table, pmu, pmu_add_cpu_aliases_map_callback, pmu);
987 }
988 
989 static void pmu_add_cpu_aliases(struct perf_pmu *pmu)
990 {
991 	if (!pmu->events_table)
992 		return;
993 
994 	if (pmu->cpu_aliases_added)
995 		return;
996 
997 	pmu_add_cpu_aliases_table(pmu, pmu->events_table);
998 	pmu->cpu_aliases_added = true;
999 }
1000 
1001 static int pmu_add_sys_aliases_iter_fn(const struct pmu_event *pe,
1002 				       const struct pmu_events_table *table __maybe_unused,
1003 				       void *vdata)
1004 {
1005 	struct perf_pmu *pmu = vdata;
1006 
1007 	if (!pe->compat || !pe->pmu)
1008 		return 0;
1009 
1010 	if (pmu_uncore_alias_match(pe->pmu, pmu->name) &&
1011 	    pmu_uncore_identifier_match(pe->compat, pmu->id)) {
1012 		perf_pmu__new_alias(pmu,
1013 				pe->name,
1014 				pe->desc,
1015 				pe->event,
1016 				/*val_fd=*/ NULL,
1017 				pe,
1018 				EVENT_SRC_SYS_JSON);
1019 	}
1020 
1021 	return 0;
1022 }
1023 
1024 void pmu_add_sys_aliases(struct perf_pmu *pmu)
1025 {
1026 	if (!pmu->id)
1027 		return;
1028 
1029 	pmu_for_each_sys_event(pmu_add_sys_aliases_iter_fn, pmu);
1030 }
1031 
1032 static char *pmu_find_alias_name(struct perf_pmu *pmu, int dirfd)
1033 {
1034 	FILE *file = perf_pmu__open_file_at(pmu, dirfd, "alias");
1035 	char *line = NULL;
1036 	size_t line_len = 0;
1037 	ssize_t ret;
1038 
1039 	if (!file)
1040 		return NULL;
1041 
1042 	ret = getline(&line, &line_len, file);
1043 	if (ret < 0) {
1044 		fclose(file);
1045 		return NULL;
1046 	}
1047 	/* Remove trailing newline. */
1048 	if (ret > 0 && line[ret - 1] == '\n')
1049 		line[--ret] = '\0';
1050 
1051 	fclose(file);
1052 	return line;
1053 }
1054 
1055 static int pmu_max_precise(int dirfd, struct perf_pmu *pmu)
1056 {
1057 	int max_precise = -1;
1058 
1059 	perf_pmu__scan_file_at(pmu, dirfd, "caps/max_precise", "%d", &max_precise);
1060 	return max_precise;
1061 }
1062 
1063 void __weak
1064 perf_pmu__arch_init(struct perf_pmu *pmu)
1065 {
1066 	if (pmu->is_core)
1067 		pmu->mem_events = perf_mem_events;
1068 }
1069 
1070 struct perf_pmu *perf_pmu__lookup(struct list_head *pmus, int dirfd, const char *name,
1071 				  bool eager_load)
1072 {
1073 	struct perf_pmu *pmu;
1074 	__u32 type;
1075 
1076 	pmu = zalloc(sizeof(*pmu));
1077 	if (!pmu)
1078 		return NULL;
1079 
1080 	pmu->name = strdup(name);
1081 	if (!pmu->name)
1082 		goto err;
1083 
1084 	/*
1085 	 * Read type early to fail fast if a lookup name isn't a PMU. Ensure
1086 	 * that type value is successfully assigned (return 1).
1087 	 */
1088 	if (perf_pmu__scan_file_at(pmu, dirfd, "type", "%u", &type) != 1)
1089 		goto err;
1090 
1091 	INIT_LIST_HEAD(&pmu->format);
1092 	INIT_LIST_HEAD(&pmu->aliases);
1093 	INIT_LIST_HEAD(&pmu->caps);
1094 
1095 	/*
1096 	 * The pmu data we store & need consists of the pmu
1097 	 * type value and format definitions. Load both right
1098 	 * now.
1099 	 */
1100 	if (pmu_format(pmu, dirfd, name, eager_load))
1101 		goto err;
1102 
1103 	pmu->is_core = is_pmu_core(name);
1104 	pmu->cpus = pmu_cpumask(dirfd, name, pmu->is_core);
1105 
1106 	pmu->type = type;
1107 	pmu->is_uncore = pmu_is_uncore(dirfd, name);
1108 	if (pmu->is_uncore)
1109 		pmu->id = pmu_id(name);
1110 	pmu->max_precise = pmu_max_precise(dirfd, pmu);
1111 	pmu->alias_name = pmu_find_alias_name(pmu, dirfd);
1112 	pmu->events_table = perf_pmu__find_events_table(pmu);
1113 	/*
1114 	 * Load the sys json events/aliases when loading the PMU as each event
1115 	 * may have a different compat regular expression. We therefore can't
1116 	 * know the number of sys json events/aliases without computing the
1117 	 * regular expressions for them all.
1118 	 */
1119 	pmu_add_sys_aliases(pmu);
1120 	list_add_tail(&pmu->list, pmus);
1121 
1122 	perf_pmu__arch_init(pmu);
1123 
1124 	if (eager_load)
1125 		pmu_aliases_parse_eager(pmu, dirfd);
1126 
1127 	return pmu;
1128 err:
1129 	zfree(&pmu->name);
1130 	free(pmu);
1131 	return NULL;
1132 }
1133 
1134 /* Creates the PMU when sysfs scanning fails. */
1135 struct perf_pmu *perf_pmu__create_placeholder_core_pmu(struct list_head *core_pmus)
1136 {
1137 	struct perf_pmu *pmu = zalloc(sizeof(*pmu));
1138 
1139 	if (!pmu)
1140 		return NULL;
1141 
1142 	pmu->name = strdup("cpu");
1143 	if (!pmu->name) {
1144 		free(pmu);
1145 		return NULL;
1146 	}
1147 
1148 	pmu->is_core = true;
1149 	pmu->type = PERF_TYPE_RAW;
1150 	pmu->cpus = cpu_map__online();
1151 
1152 	INIT_LIST_HEAD(&pmu->format);
1153 	INIT_LIST_HEAD(&pmu->aliases);
1154 	INIT_LIST_HEAD(&pmu->caps);
1155 	list_add_tail(&pmu->list, core_pmus);
1156 	return pmu;
1157 }
1158 
1159 void perf_pmu__warn_invalid_formats(struct perf_pmu *pmu)
1160 {
1161 	struct perf_pmu_format *format;
1162 
1163 	if (pmu->formats_checked)
1164 		return;
1165 
1166 	pmu->formats_checked = true;
1167 
1168 	/* fake pmu doesn't have format list */
1169 	if (pmu == &perf_pmu__fake)
1170 		return;
1171 
1172 	list_for_each_entry(format, &pmu->format, list) {
1173 		perf_pmu_format__load(pmu, format);
1174 		if (format->value >= PERF_PMU_FORMAT_VALUE_CONFIG_END) {
1175 			pr_warning("WARNING: '%s' format '%s' requires 'perf_event_attr::config%d'"
1176 				   "which is not supported by this version of perf!\n",
1177 				   pmu->name, format->name, format->value);
1178 			return;
1179 		}
1180 	}
1181 }
1182 
1183 bool evsel__is_aux_event(const struct evsel *evsel)
1184 {
1185 	struct perf_pmu *pmu = evsel__find_pmu(evsel);
1186 
1187 	return pmu && pmu->auxtrace;
1188 }
1189 
1190 /*
1191  * Set @config_name to @val as long as the user hasn't already set or cleared it
1192  * by passing a config term on the command line.
1193  *
1194  * @val is the value to put into the bits specified by @config_name rather than
1195  * the bit pattern. It is shifted into position by this function, so to set
1196  * something to true, pass 1 for val rather than a pre shifted value.
1197  */
1198 #define field_prep(_mask, _val) (((_val) << (ffsll(_mask) - 1)) & (_mask))
1199 void evsel__set_config_if_unset(struct perf_pmu *pmu, struct evsel *evsel,
1200 				const char *config_name, u64 val)
1201 {
1202 	u64 user_bits = 0, bits;
1203 	struct evsel_config_term *term = evsel__get_config_term(evsel, CFG_CHG);
1204 
1205 	if (term)
1206 		user_bits = term->val.cfg_chg;
1207 
1208 	bits = perf_pmu__format_bits(pmu, config_name);
1209 
1210 	/* Do nothing if the user changed the value */
1211 	if (bits & user_bits)
1212 		return;
1213 
1214 	/* Otherwise replace it */
1215 	evsel->core.attr.config &= ~bits;
1216 	evsel->core.attr.config |= field_prep(bits, val);
1217 }
1218 
1219 static struct perf_pmu_format *
1220 pmu_find_format(const struct list_head *formats, const char *name)
1221 {
1222 	struct perf_pmu_format *format;
1223 
1224 	list_for_each_entry(format, formats, list)
1225 		if (!strcmp(format->name, name))
1226 			return format;
1227 
1228 	return NULL;
1229 }
1230 
1231 __u64 perf_pmu__format_bits(struct perf_pmu *pmu, const char *name)
1232 {
1233 	struct perf_pmu_format *format = pmu_find_format(&pmu->format, name);
1234 	__u64 bits = 0;
1235 	int fbit;
1236 
1237 	if (!format)
1238 		return 0;
1239 
1240 	for_each_set_bit(fbit, format->bits, PERF_PMU_FORMAT_BITS)
1241 		bits |= 1ULL << fbit;
1242 
1243 	return bits;
1244 }
1245 
1246 int perf_pmu__format_type(struct perf_pmu *pmu, const char *name)
1247 {
1248 	struct perf_pmu_format *format = pmu_find_format(&pmu->format, name);
1249 
1250 	if (!format)
1251 		return -1;
1252 
1253 	perf_pmu_format__load(pmu, format);
1254 	return format->value;
1255 }
1256 
1257 /*
1258  * Sets value based on the format definition (format parameter)
1259  * and unformatted value (value parameter).
1260  */
1261 static void pmu_format_value(unsigned long *format, __u64 value, __u64 *v,
1262 			     bool zero)
1263 {
1264 	unsigned long fbit, vbit;
1265 
1266 	for (fbit = 0, vbit = 0; fbit < PERF_PMU_FORMAT_BITS; fbit++) {
1267 
1268 		if (!test_bit(fbit, format))
1269 			continue;
1270 
1271 		if (value & (1llu << vbit++))
1272 			*v |= (1llu << fbit);
1273 		else if (zero)
1274 			*v &= ~(1llu << fbit);
1275 	}
1276 }
1277 
1278 static __u64 pmu_format_max_value(const unsigned long *format)
1279 {
1280 	int w;
1281 
1282 	w = bitmap_weight(format, PERF_PMU_FORMAT_BITS);
1283 	if (!w)
1284 		return 0;
1285 	if (w < 64)
1286 		return (1ULL << w) - 1;
1287 	return -1;
1288 }
1289 
1290 /*
1291  * Term is a string term, and might be a param-term. Try to look up it's value
1292  * in the remaining terms.
1293  * - We have a term like "base-or-format-term=param-term",
1294  * - We need to find the value supplied for "param-term" (with param-term named
1295  *   in a config string) later on in the term list.
1296  */
1297 static int pmu_resolve_param_term(struct parse_events_term *term,
1298 				  struct parse_events_terms *head_terms,
1299 				  __u64 *value)
1300 {
1301 	struct parse_events_term *t;
1302 
1303 	list_for_each_entry(t, &head_terms->terms, list) {
1304 		if (t->type_val == PARSE_EVENTS__TERM_TYPE_NUM &&
1305 		    t->config && !strcmp(t->config, term->config)) {
1306 			t->used = true;
1307 			*value = t->val.num;
1308 			return 0;
1309 		}
1310 	}
1311 
1312 	if (verbose > 0)
1313 		printf("Required parameter '%s' not specified\n", term->config);
1314 
1315 	return -1;
1316 }
1317 
1318 static char *pmu_formats_string(const struct list_head *formats)
1319 {
1320 	struct perf_pmu_format *format;
1321 	char *str = NULL;
1322 	struct strbuf buf = STRBUF_INIT;
1323 	unsigned int i = 0;
1324 
1325 	if (!formats)
1326 		return NULL;
1327 
1328 	/* sysfs exported terms */
1329 	list_for_each_entry(format, formats, list)
1330 		if (strbuf_addf(&buf, i++ ? ",%s" : "%s", format->name) < 0)
1331 			goto error;
1332 
1333 	str = strbuf_detach(&buf, NULL);
1334 error:
1335 	strbuf_release(&buf);
1336 
1337 	return str;
1338 }
1339 
1340 /*
1341  * Setup one of config[12] attr members based on the
1342  * user input data - term parameter.
1343  */
1344 static int pmu_config_term(const struct perf_pmu *pmu,
1345 			   struct perf_event_attr *attr,
1346 			   struct parse_events_term *term,
1347 			   struct parse_events_terms *head_terms,
1348 			   bool zero, struct parse_events_error *err)
1349 {
1350 	struct perf_pmu_format *format;
1351 	__u64 *vp;
1352 	__u64 val, max_val;
1353 
1354 	/*
1355 	 * If this is a parameter we've already used for parameterized-eval,
1356 	 * skip it in normal eval.
1357 	 */
1358 	if (term->used)
1359 		return 0;
1360 
1361 	/*
1362 	 * Hardcoded terms should be already in, so nothing
1363 	 * to be done for them.
1364 	 */
1365 	if (parse_events__is_hardcoded_term(term))
1366 		return 0;
1367 
1368 	format = pmu_find_format(&pmu->format, term->config);
1369 	if (!format) {
1370 		char *pmu_term = pmu_formats_string(&pmu->format);
1371 		char *unknown_term;
1372 		char *help_msg;
1373 
1374 		if (asprintf(&unknown_term,
1375 				"unknown term '%s' for pmu '%s'",
1376 				term->config, pmu->name) < 0)
1377 			unknown_term = NULL;
1378 		help_msg = parse_events_formats_error_string(pmu_term);
1379 		if (err) {
1380 			parse_events_error__handle(err, term->err_term,
1381 						   unknown_term,
1382 						   help_msg);
1383 		} else {
1384 			pr_debug("%s (%s)\n", unknown_term, help_msg);
1385 			free(unknown_term);
1386 		}
1387 		free(pmu_term);
1388 		return -EINVAL;
1389 	}
1390 	perf_pmu_format__load(pmu, format);
1391 	switch (format->value) {
1392 	case PERF_PMU_FORMAT_VALUE_CONFIG:
1393 		vp = &attr->config;
1394 		break;
1395 	case PERF_PMU_FORMAT_VALUE_CONFIG1:
1396 		vp = &attr->config1;
1397 		break;
1398 	case PERF_PMU_FORMAT_VALUE_CONFIG2:
1399 		vp = &attr->config2;
1400 		break;
1401 	case PERF_PMU_FORMAT_VALUE_CONFIG3:
1402 		vp = &attr->config3;
1403 		break;
1404 	default:
1405 		return -EINVAL;
1406 	}
1407 
1408 	/*
1409 	 * Either directly use a numeric term, or try to translate string terms
1410 	 * using event parameters.
1411 	 */
1412 	if (term->type_val == PARSE_EVENTS__TERM_TYPE_NUM) {
1413 		if (term->no_value &&
1414 		    bitmap_weight(format->bits, PERF_PMU_FORMAT_BITS) > 1) {
1415 			if (err) {
1416 				parse_events_error__handle(err, term->err_val,
1417 					   strdup("no value assigned for term"),
1418 					   NULL);
1419 			}
1420 			return -EINVAL;
1421 		}
1422 
1423 		val = term->val.num;
1424 	} else if (term->type_val == PARSE_EVENTS__TERM_TYPE_STR) {
1425 		if (strcmp(term->val.str, "?")) {
1426 			if (verbose > 0) {
1427 				pr_info("Invalid sysfs entry %s=%s\n",
1428 						term->config, term->val.str);
1429 			}
1430 			if (err) {
1431 				parse_events_error__handle(err, term->err_val,
1432 					strdup("expected numeric value"),
1433 					NULL);
1434 			}
1435 			return -EINVAL;
1436 		}
1437 
1438 		if (pmu_resolve_param_term(term, head_terms, &val))
1439 			return -EINVAL;
1440 	} else
1441 		return -EINVAL;
1442 
1443 	max_val = pmu_format_max_value(format->bits);
1444 	if (val > max_val) {
1445 		if (err) {
1446 			char *err_str;
1447 
1448 			parse_events_error__handle(err, term->err_val,
1449 				asprintf(&err_str,
1450 				    "value too big for format (%s), maximum is %llu",
1451 				    format->name, (unsigned long long)max_val) < 0
1452 				    ? strdup("value too big for format")
1453 				    : err_str,
1454 				    NULL);
1455 			return -EINVAL;
1456 		}
1457 		/*
1458 		 * Assume we don't care if !err, in which case the value will be
1459 		 * silently truncated.
1460 		 */
1461 	}
1462 
1463 	pmu_format_value(format->bits, val, vp, zero);
1464 	return 0;
1465 }
1466 
1467 int perf_pmu__config_terms(const struct perf_pmu *pmu,
1468 			   struct perf_event_attr *attr,
1469 			   struct parse_events_terms *terms,
1470 			   bool zero, struct parse_events_error *err)
1471 {
1472 	struct parse_events_term *term;
1473 
1474 	list_for_each_entry(term, &terms->terms, list) {
1475 		if (pmu_config_term(pmu, attr, term, terms, zero, err))
1476 			return -EINVAL;
1477 	}
1478 
1479 	return 0;
1480 }
1481 
1482 /*
1483  * Configures event's 'attr' parameter based on the:
1484  * 1) users input - specified in terms parameter
1485  * 2) pmu format definitions - specified by pmu parameter
1486  */
1487 int perf_pmu__config(struct perf_pmu *pmu, struct perf_event_attr *attr,
1488 		     struct parse_events_terms *head_terms,
1489 		     struct parse_events_error *err)
1490 {
1491 	bool zero = !!pmu->perf_event_attr_init_default;
1492 
1493 	return perf_pmu__config_terms(pmu, attr, head_terms, zero, err);
1494 }
1495 
1496 static struct perf_pmu_alias *pmu_find_alias(struct perf_pmu *pmu,
1497 					     struct parse_events_term *term)
1498 {
1499 	struct perf_pmu_alias *alias;
1500 	const char *name;
1501 
1502 	if (parse_events__is_hardcoded_term(term))
1503 		return NULL;
1504 
1505 	if (term->type_val == PARSE_EVENTS__TERM_TYPE_NUM) {
1506 		if (!term->no_value)
1507 			return NULL;
1508 		if (pmu_find_format(&pmu->format, term->config))
1509 			return NULL;
1510 		name = term->config;
1511 
1512 	} else if (term->type_val == PARSE_EVENTS__TERM_TYPE_STR) {
1513 		if (strcasecmp(term->config, "event"))
1514 			return NULL;
1515 		name = term->val.str;
1516 	} else {
1517 		return NULL;
1518 	}
1519 
1520 	alias = perf_pmu__find_alias(pmu, name, /*load=*/ true);
1521 	if (alias || pmu->cpu_aliases_added)
1522 		return alias;
1523 
1524 	/* Alias doesn't exist, try to get it from the json events. */
1525 	if (pmu->events_table &&
1526 	    pmu_events_table__find_event(pmu->events_table, pmu, name,
1527 				         pmu_add_cpu_aliases_map_callback,
1528 				         pmu) == 0) {
1529 		alias = perf_pmu__find_alias(pmu, name, /*load=*/ false);
1530 	}
1531 	return alias;
1532 }
1533 
1534 
1535 static int check_info_data(struct perf_pmu *pmu,
1536 			   struct perf_pmu_alias *alias,
1537 			   struct perf_pmu_info *info,
1538 			   struct parse_events_error *err,
1539 			   int column)
1540 {
1541 	read_alias_info(pmu, alias);
1542 	/*
1543 	 * Only one term in event definition can
1544 	 * define unit, scale and snapshot, fail
1545 	 * if there's more than one.
1546 	 */
1547 	if (info->unit && alias->unit[0]) {
1548 		parse_events_error__handle(err, column,
1549 					strdup("Attempt to set event's unit twice"),
1550 					NULL);
1551 		return -EINVAL;
1552 	}
1553 	if (info->scale && alias->scale) {
1554 		parse_events_error__handle(err, column,
1555 					strdup("Attempt to set event's scale twice"),
1556 					NULL);
1557 		return -EINVAL;
1558 	}
1559 	if (info->snapshot && alias->snapshot) {
1560 		parse_events_error__handle(err, column,
1561 					strdup("Attempt to set event snapshot twice"),
1562 					NULL);
1563 		return -EINVAL;
1564 	}
1565 
1566 	if (alias->unit[0])
1567 		info->unit = alias->unit;
1568 
1569 	if (alias->scale)
1570 		info->scale = alias->scale;
1571 
1572 	if (alias->snapshot)
1573 		info->snapshot = alias->snapshot;
1574 
1575 	return 0;
1576 }
1577 
1578 /*
1579  * Find alias in the terms list and replace it with the terms
1580  * defined for the alias
1581  */
1582 int perf_pmu__check_alias(struct perf_pmu *pmu, struct parse_events_terms *head_terms,
1583 			  struct perf_pmu_info *info, bool *rewrote_terms,
1584 			  struct parse_events_error *err)
1585 {
1586 	struct parse_events_term *term, *h;
1587 	struct perf_pmu_alias *alias;
1588 	int ret;
1589 
1590 	*rewrote_terms = false;
1591 	info->per_pkg = false;
1592 
1593 	/*
1594 	 * Mark unit and scale as not set
1595 	 * (different from default values, see below)
1596 	 */
1597 	info->unit     = NULL;
1598 	info->scale    = 0.0;
1599 	info->snapshot = false;
1600 
1601 	list_for_each_entry_safe(term, h, &head_terms->terms, list) {
1602 		alias = pmu_find_alias(pmu, term);
1603 		if (!alias)
1604 			continue;
1605 		ret = pmu_alias_terms(alias, term->err_term, &term->list);
1606 		if (ret) {
1607 			parse_events_error__handle(err, term->err_term,
1608 						strdup("Failure to duplicate terms"),
1609 						NULL);
1610 			return ret;
1611 		}
1612 		*rewrote_terms = true;
1613 		ret = check_info_data(pmu, alias, info, err, term->err_term);
1614 		if (ret)
1615 			return ret;
1616 
1617 		if (alias->per_pkg)
1618 			info->per_pkg = true;
1619 
1620 		list_del_init(&term->list);
1621 		parse_events_term__delete(term);
1622 	}
1623 
1624 	/*
1625 	 * if no unit or scale found in aliases, then
1626 	 * set defaults as for evsel
1627 	 * unit cannot left to NULL
1628 	 */
1629 	if (info->unit == NULL)
1630 		info->unit   = "";
1631 
1632 	if (info->scale == 0.0)
1633 		info->scale  = 1.0;
1634 
1635 	return 0;
1636 }
1637 
1638 struct find_event_args {
1639 	const char *event;
1640 	void *state;
1641 	pmu_event_callback cb;
1642 };
1643 
1644 static int find_event_callback(void *state, struct pmu_event_info *info)
1645 {
1646 	struct find_event_args *args = state;
1647 
1648 	if (!strcmp(args->event, info->name))
1649 		return args->cb(args->state, info);
1650 
1651 	return 0;
1652 }
1653 
1654 int perf_pmu__find_event(struct perf_pmu *pmu, const char *event, void *state, pmu_event_callback cb)
1655 {
1656 	struct find_event_args args = {
1657 		.event = event,
1658 		.state = state,
1659 		.cb = cb,
1660 	};
1661 
1662 	/* Sub-optimal, but function is only used by tests. */
1663 	return perf_pmu__for_each_event(pmu, /*skip_duplicate_pmus=*/ false,
1664 					&args, find_event_callback);
1665 }
1666 
1667 static void perf_pmu__del_formats(struct list_head *formats)
1668 {
1669 	struct perf_pmu_format *fmt, *tmp;
1670 
1671 	list_for_each_entry_safe(fmt, tmp, formats, list) {
1672 		list_del(&fmt->list);
1673 		zfree(&fmt->name);
1674 		free(fmt);
1675 	}
1676 }
1677 
1678 bool perf_pmu__has_format(const struct perf_pmu *pmu, const char *name)
1679 {
1680 	struct perf_pmu_format *format;
1681 
1682 	list_for_each_entry(format, &pmu->format, list) {
1683 		if (!strcmp(format->name, name))
1684 			return true;
1685 	}
1686 	return false;
1687 }
1688 
1689 int perf_pmu__for_each_format(struct perf_pmu *pmu, void *state, pmu_format_callback cb)
1690 {
1691 	static const char *const terms[] = {
1692 		"config=0..0xffffffffffffffff",
1693 		"config1=0..0xffffffffffffffff",
1694 		"config2=0..0xffffffffffffffff",
1695 		"config3=0..0xffffffffffffffff",
1696 		"name=string",
1697 		"period=number",
1698 		"freq=number",
1699 		"branch_type=(u|k|hv|any|...)",
1700 		"time",
1701 		"call-graph=(fp|dwarf|lbr)",
1702 		"stack-size=number",
1703 		"max-stack=number",
1704 		"nr=number",
1705 		"inherit",
1706 		"no-inherit",
1707 		"overwrite",
1708 		"no-overwrite",
1709 		"percore",
1710 		"aux-output",
1711 		"aux-sample-size=number",
1712 	};
1713 	struct perf_pmu_format *format;
1714 	int ret;
1715 
1716 	/*
1717 	 * max-events and driver-config are missing above as are the internal
1718 	 * types user, metric-id, raw, legacy cache and hardware. Assert against
1719 	 * the enum parse_events__term_type so they are kept in sync.
1720 	 */
1721 	_Static_assert(ARRAY_SIZE(terms) == __PARSE_EVENTS__TERM_TYPE_NR - 6,
1722 		       "perf_pmu__for_each_format()'s terms must be kept in sync with enum parse_events__term_type");
1723 	list_for_each_entry(format, &pmu->format, list) {
1724 		perf_pmu_format__load(pmu, format);
1725 		ret = cb(state, format->name, (int)format->value, format->bits);
1726 		if (ret)
1727 			return ret;
1728 	}
1729 	if (!pmu->is_core)
1730 		return 0;
1731 
1732 	for (size_t i = 0; i < ARRAY_SIZE(terms); i++) {
1733 		int config = PERF_PMU_FORMAT_VALUE_CONFIG;
1734 
1735 		if (i < PERF_PMU_FORMAT_VALUE_CONFIG_END)
1736 			config = i;
1737 
1738 		ret = cb(state, terms[i], config, /*bits=*/NULL);
1739 		if (ret)
1740 			return ret;
1741 	}
1742 	return 0;
1743 }
1744 
1745 bool is_pmu_core(const char *name)
1746 {
1747 	return !strcmp(name, "cpu") || !strcmp(name, "cpum_cf") || is_sysfs_pmu_core(name);
1748 }
1749 
1750 bool perf_pmu__supports_legacy_cache(const struct perf_pmu *pmu)
1751 {
1752 	return pmu->is_core;
1753 }
1754 
1755 bool perf_pmu__auto_merge_stats(const struct perf_pmu *pmu)
1756 {
1757 	return !pmu->is_core || perf_pmus__num_core_pmus() == 1;
1758 }
1759 
1760 bool perf_pmu__have_event(struct perf_pmu *pmu, const char *name)
1761 {
1762 	if (!name)
1763 		return false;
1764 	if (perf_pmu__find_alias(pmu, name, /*load=*/ true) != NULL)
1765 		return true;
1766 	if (pmu->cpu_aliases_added || !pmu->events_table)
1767 		return false;
1768 	return pmu_events_table__find_event(pmu->events_table, pmu, name, NULL, NULL) == 0;
1769 }
1770 
1771 size_t perf_pmu__num_events(struct perf_pmu *pmu)
1772 {
1773 	size_t nr;
1774 
1775 	pmu_aliases_parse(pmu);
1776 	nr = pmu->sysfs_aliases + pmu->sys_json_aliases;;
1777 
1778 	if (pmu->cpu_aliases_added)
1779 		 nr += pmu->cpu_json_aliases;
1780 	else if (pmu->events_table)
1781 		nr += pmu_events_table__num_events(pmu->events_table, pmu) - pmu->cpu_json_aliases;
1782 	else
1783 		assert(pmu->cpu_json_aliases == 0);
1784 
1785 	return pmu->selectable ? nr + 1 : nr;
1786 }
1787 
1788 static int sub_non_neg(int a, int b)
1789 {
1790 	if (b > a)
1791 		return 0;
1792 	return a - b;
1793 }
1794 
1795 static char *format_alias(char *buf, int len, const struct perf_pmu *pmu,
1796 			  const struct perf_pmu_alias *alias, bool skip_duplicate_pmus)
1797 {
1798 	struct parse_events_term *term;
1799 	size_t pmu_name_len = skip_duplicate_pmus
1800 		? pmu_name_len_no_suffix(pmu->name)
1801 		: strlen(pmu->name);
1802 	int used = snprintf(buf, len, "%.*s/%s", (int)pmu_name_len, pmu->name, alias->name);
1803 
1804 	list_for_each_entry(term, &alias->terms.terms, list) {
1805 		if (term->type_val == PARSE_EVENTS__TERM_TYPE_STR)
1806 			used += snprintf(buf + used, sub_non_neg(len, used),
1807 					",%s=%s", term->config,
1808 					term->val.str);
1809 	}
1810 
1811 	if (sub_non_neg(len, used) > 0) {
1812 		buf[used] = '/';
1813 		used++;
1814 	}
1815 	if (sub_non_neg(len, used) > 0) {
1816 		buf[used] = '\0';
1817 		used++;
1818 	} else
1819 		buf[len - 1] = '\0';
1820 
1821 	return buf;
1822 }
1823 
1824 int perf_pmu__for_each_event(struct perf_pmu *pmu, bool skip_duplicate_pmus,
1825 			     void *state, pmu_event_callback cb)
1826 {
1827 	char buf[1024];
1828 	struct perf_pmu_alias *event;
1829 	struct pmu_event_info info = {
1830 		.pmu = pmu,
1831 	};
1832 	int ret = 0;
1833 	struct strbuf sb;
1834 
1835 	strbuf_init(&sb, /*hint=*/ 0);
1836 	pmu_aliases_parse(pmu);
1837 	pmu_add_cpu_aliases(pmu);
1838 	list_for_each_entry(event, &pmu->aliases, list) {
1839 		size_t buf_used, pmu_name_len;
1840 
1841 		info.pmu_name = event->pmu_name ?: pmu->name;
1842 		pmu_name_len = skip_duplicate_pmus
1843 			? pmu_name_len_no_suffix(info.pmu_name)
1844 			: strlen(info.pmu_name);
1845 		info.alias = NULL;
1846 		if (event->desc) {
1847 			info.name = event->name;
1848 			buf_used = 0;
1849 		} else {
1850 			info.name = format_alias(buf, sizeof(buf), pmu, event,
1851 						 skip_duplicate_pmus);
1852 			if (pmu->is_core) {
1853 				info.alias = info.name;
1854 				info.name = event->name;
1855 			}
1856 			buf_used = strlen(buf) + 1;
1857 		}
1858 		info.scale_unit = NULL;
1859 		if (strlen(event->unit) || event->scale != 1.0) {
1860 			info.scale_unit = buf + buf_used;
1861 			buf_used += snprintf(buf + buf_used, sizeof(buf) - buf_used,
1862 					"%G%s", event->scale, event->unit) + 1;
1863 		}
1864 		info.desc = event->desc;
1865 		info.long_desc = event->long_desc;
1866 		info.encoding_desc = buf + buf_used;
1867 		parse_events_terms__to_strbuf(&event->terms, &sb);
1868 		buf_used += snprintf(buf + buf_used, sizeof(buf) - buf_used,
1869 				"%.*s/%s/", (int)pmu_name_len, info.pmu_name, sb.buf) + 1;
1870 		info.topic = event->topic;
1871 		info.str = sb.buf;
1872 		info.deprecated = event->deprecated;
1873 		ret = cb(state, &info);
1874 		if (ret)
1875 			goto out;
1876 		strbuf_setlen(&sb, /*len=*/ 0);
1877 	}
1878 	if (pmu->selectable) {
1879 		info.name = buf;
1880 		snprintf(buf, sizeof(buf), "%s//", pmu->name);
1881 		info.alias = NULL;
1882 		info.scale_unit = NULL;
1883 		info.desc = NULL;
1884 		info.long_desc = NULL;
1885 		info.encoding_desc = NULL;
1886 		info.topic = NULL;
1887 		info.pmu_name = pmu->name;
1888 		info.deprecated = false;
1889 		ret = cb(state, &info);
1890 	}
1891 out:
1892 	strbuf_release(&sb);
1893 	return ret;
1894 }
1895 
1896 bool pmu__name_match(const struct perf_pmu *pmu, const char *pmu_name)
1897 {
1898 	return !strcmp(pmu->name, pmu_name) ||
1899 		(pmu->is_uncore && pmu_uncore_alias_match(pmu_name, pmu->name)) ||
1900 		/*
1901 		 * jevents and tests use default_core as a marker for any core
1902 		 * PMU as the PMU name varies across architectures.
1903 		 */
1904 	        (pmu->is_core && !strcmp(pmu_name, "default_core"));
1905 }
1906 
1907 bool perf_pmu__is_software(const struct perf_pmu *pmu)
1908 {
1909 	const char *known_sw_pmus[] = {
1910 		"kprobe",
1911 		"msr",
1912 		"uprobe",
1913 	};
1914 
1915 	if (pmu->is_core || pmu->is_uncore || pmu->auxtrace)
1916 		return false;
1917 	switch (pmu->type) {
1918 	case PERF_TYPE_HARDWARE:	return false;
1919 	case PERF_TYPE_SOFTWARE:	return true;
1920 	case PERF_TYPE_TRACEPOINT:	return true;
1921 	case PERF_TYPE_HW_CACHE:	return false;
1922 	case PERF_TYPE_RAW:		return false;
1923 	case PERF_TYPE_BREAKPOINT:	return true;
1924 	default: break;
1925 	}
1926 	for (size_t i = 0; i < ARRAY_SIZE(known_sw_pmus); i++) {
1927 		if (!strcmp(pmu->name, known_sw_pmus[i]))
1928 			return true;
1929 	}
1930 	return false;
1931 }
1932 
1933 FILE *perf_pmu__open_file(const struct perf_pmu *pmu, const char *name)
1934 {
1935 	char path[PATH_MAX];
1936 
1937 	if (!perf_pmu__pathname_scnprintf(path, sizeof(path), pmu->name, name) ||
1938 	    !file_available(path))
1939 		return NULL;
1940 
1941 	return fopen(path, "r");
1942 }
1943 
1944 FILE *perf_pmu__open_file_at(const struct perf_pmu *pmu, int dirfd, const char *name)
1945 {
1946 	int fd;
1947 
1948 	fd = perf_pmu__pathname_fd(dirfd, pmu->name, name, O_RDONLY);
1949 	if (fd < 0)
1950 		return NULL;
1951 
1952 	return fdopen(fd, "r");
1953 }
1954 
1955 int perf_pmu__scan_file(const struct perf_pmu *pmu, const char *name, const char *fmt,
1956 			...)
1957 {
1958 	va_list args;
1959 	FILE *file;
1960 	int ret = EOF;
1961 
1962 	va_start(args, fmt);
1963 	file = perf_pmu__open_file(pmu, name);
1964 	if (file) {
1965 		ret = vfscanf(file, fmt, args);
1966 		fclose(file);
1967 	}
1968 	va_end(args);
1969 	return ret;
1970 }
1971 
1972 int perf_pmu__scan_file_at(const struct perf_pmu *pmu, int dirfd, const char *name,
1973 			   const char *fmt, ...)
1974 {
1975 	va_list args;
1976 	FILE *file;
1977 	int ret = EOF;
1978 
1979 	va_start(args, fmt);
1980 	file = perf_pmu__open_file_at(pmu, dirfd, name);
1981 	if (file) {
1982 		ret = vfscanf(file, fmt, args);
1983 		fclose(file);
1984 	}
1985 	va_end(args);
1986 	return ret;
1987 }
1988 
1989 bool perf_pmu__file_exists(const struct perf_pmu *pmu, const char *name)
1990 {
1991 	char path[PATH_MAX];
1992 
1993 	if (!perf_pmu__pathname_scnprintf(path, sizeof(path), pmu->name, name))
1994 		return false;
1995 
1996 	return file_available(path);
1997 }
1998 
1999 static int perf_pmu__new_caps(struct list_head *list, char *name, char *value)
2000 {
2001 	struct perf_pmu_caps *caps = zalloc(sizeof(*caps));
2002 
2003 	if (!caps)
2004 		return -ENOMEM;
2005 
2006 	caps->name = strdup(name);
2007 	if (!caps->name)
2008 		goto free_caps;
2009 	caps->value = strndup(value, strlen(value) - 1);
2010 	if (!caps->value)
2011 		goto free_name;
2012 	list_add_tail(&caps->list, list);
2013 	return 0;
2014 
2015 free_name:
2016 	zfree(&caps->name);
2017 free_caps:
2018 	free(caps);
2019 
2020 	return -ENOMEM;
2021 }
2022 
2023 static void perf_pmu__del_caps(struct perf_pmu *pmu)
2024 {
2025 	struct perf_pmu_caps *caps, *tmp;
2026 
2027 	list_for_each_entry_safe(caps, tmp, &pmu->caps, list) {
2028 		list_del(&caps->list);
2029 		zfree(&caps->name);
2030 		zfree(&caps->value);
2031 		free(caps);
2032 	}
2033 }
2034 
2035 /*
2036  * Reading/parsing the given pmu capabilities, which should be located at:
2037  * /sys/bus/event_source/devices/<dev>/caps as sysfs group attributes.
2038  * Return the number of capabilities
2039  */
2040 int perf_pmu__caps_parse(struct perf_pmu *pmu)
2041 {
2042 	struct stat st;
2043 	char caps_path[PATH_MAX];
2044 	DIR *caps_dir;
2045 	struct dirent *evt_ent;
2046 	int caps_fd;
2047 
2048 	if (pmu->caps_initialized)
2049 		return pmu->nr_caps;
2050 
2051 	pmu->nr_caps = 0;
2052 
2053 	if (!perf_pmu__pathname_scnprintf(caps_path, sizeof(caps_path), pmu->name, "caps"))
2054 		return -1;
2055 
2056 	if (stat(caps_path, &st) < 0) {
2057 		pmu->caps_initialized = true;
2058 		return 0;	/* no error if caps does not exist */
2059 	}
2060 
2061 	caps_dir = opendir(caps_path);
2062 	if (!caps_dir)
2063 		return -EINVAL;
2064 
2065 	caps_fd = dirfd(caps_dir);
2066 
2067 	while ((evt_ent = readdir(caps_dir)) != NULL) {
2068 		char *name = evt_ent->d_name;
2069 		char value[128];
2070 		FILE *file;
2071 		int fd;
2072 
2073 		if (!strcmp(name, ".") || !strcmp(name, ".."))
2074 			continue;
2075 
2076 		fd = openat(caps_fd, name, O_RDONLY);
2077 		if (fd == -1)
2078 			continue;
2079 		file = fdopen(fd, "r");
2080 		if (!file) {
2081 			close(fd);
2082 			continue;
2083 		}
2084 
2085 		if (!fgets(value, sizeof(value), file) ||
2086 		    (perf_pmu__new_caps(&pmu->caps, name, value) < 0)) {
2087 			fclose(file);
2088 			continue;
2089 		}
2090 
2091 		pmu->nr_caps++;
2092 		fclose(file);
2093 	}
2094 
2095 	closedir(caps_dir);
2096 
2097 	pmu->caps_initialized = true;
2098 	return pmu->nr_caps;
2099 }
2100 
2101 static void perf_pmu__compute_config_masks(struct perf_pmu *pmu)
2102 {
2103 	struct perf_pmu_format *format;
2104 
2105 	if (pmu->config_masks_computed)
2106 		return;
2107 
2108 	list_for_each_entry(format, &pmu->format, list)	{
2109 		unsigned int i;
2110 		__u64 *mask;
2111 
2112 		if (format->value >= PERF_PMU_FORMAT_VALUE_CONFIG_END)
2113 			continue;
2114 
2115 		pmu->config_masks_present = true;
2116 		mask = &pmu->config_masks[format->value];
2117 
2118 		for_each_set_bit(i, format->bits, PERF_PMU_FORMAT_BITS)
2119 			*mask |= 1ULL << i;
2120 	}
2121 	pmu->config_masks_computed = true;
2122 }
2123 
2124 void perf_pmu__warn_invalid_config(struct perf_pmu *pmu, __u64 config,
2125 				   const char *name, int config_num,
2126 				   const char *config_name)
2127 {
2128 	__u64 bits;
2129 	char buf[100];
2130 
2131 	perf_pmu__compute_config_masks(pmu);
2132 
2133 	/*
2134 	 * Kernel doesn't export any valid format bits.
2135 	 */
2136 	if (!pmu->config_masks_present)
2137 		return;
2138 
2139 	bits = config & ~pmu->config_masks[config_num];
2140 	if (bits == 0)
2141 		return;
2142 
2143 	bitmap_scnprintf((unsigned long *)&bits, sizeof(bits) * 8, buf, sizeof(buf));
2144 
2145 	pr_warning("WARNING: event '%s' not valid (bits %s of %s "
2146 		   "'%llx' not supported by kernel)!\n",
2147 		   name ?: "N/A", buf, config_name, config);
2148 }
2149 
2150 bool perf_pmu__match(const struct perf_pmu *pmu, const char *tok)
2151 {
2152 	const char *name = pmu->name;
2153 	bool need_fnmatch = strchr(tok, '*') != NULL;
2154 
2155 	if (!strncmp(tok, "uncore_", 7))
2156 		tok += 7;
2157 	if (!strncmp(name, "uncore_", 7))
2158 		name += 7;
2159 
2160 	if (perf_pmu__match_ignoring_suffix(name, tok) ||
2161 	    (need_fnmatch && !fnmatch(tok, name, 0)))
2162 		return true;
2163 
2164 	name = pmu->alias_name;
2165 	if (!name)
2166 		return false;
2167 
2168 	if (!strncmp(name, "uncore_", 7))
2169 		name += 7;
2170 
2171 	return perf_pmu__match_ignoring_suffix(name, tok) ||
2172 		(need_fnmatch && !fnmatch(tok, name, 0));
2173 }
2174 
2175 double __weak perf_pmu__cpu_slots_per_cycle(void)
2176 {
2177 	return NAN;
2178 }
2179 
2180 int perf_pmu__event_source_devices_scnprintf(char *pathname, size_t size)
2181 {
2182 	const char *sysfs = sysfs__mountpoint();
2183 
2184 	if (!sysfs)
2185 		return 0;
2186 	return scnprintf(pathname, size, "%s/bus/event_source/devices/", sysfs);
2187 }
2188 
2189 int perf_pmu__event_source_devices_fd(void)
2190 {
2191 	char path[PATH_MAX];
2192 	const char *sysfs = sysfs__mountpoint();
2193 
2194 	if (!sysfs)
2195 		return -1;
2196 
2197 	scnprintf(path, sizeof(path), "%s/bus/event_source/devices/", sysfs);
2198 	return open(path, O_DIRECTORY);
2199 }
2200 
2201 /*
2202  * Fill 'buf' with the path to a file or folder in 'pmu_name' in
2203  * sysfs. For example if pmu_name = "cs_etm" and 'filename' = "format"
2204  * then pathname will be filled with
2205  * "/sys/bus/event_source/devices/cs_etm/format"
2206  *
2207  * Return 0 if the sysfs mountpoint couldn't be found, if no characters were
2208  * written or if the buffer size is exceeded.
2209  */
2210 int perf_pmu__pathname_scnprintf(char *buf, size_t size,
2211 				 const char *pmu_name, const char *filename)
2212 {
2213 	size_t len;
2214 
2215 	len = perf_pmu__event_source_devices_scnprintf(buf, size);
2216 	if (!len || (len + strlen(pmu_name) + strlen(filename) + 1)  >= size)
2217 		return 0;
2218 
2219 	return scnprintf(buf + len, size - len, "%s/%s", pmu_name, filename);
2220 }
2221 
2222 int perf_pmu__pathname_fd(int dirfd, const char *pmu_name, const char *filename, int flags)
2223 {
2224 	char path[PATH_MAX];
2225 
2226 	scnprintf(path, sizeof(path), "%s/%s", pmu_name, filename);
2227 	return openat(dirfd, path, flags);
2228 }
2229 
2230 void perf_pmu__delete(struct perf_pmu *pmu)
2231 {
2232 	perf_pmu__del_formats(&pmu->format);
2233 	perf_pmu__del_aliases(pmu);
2234 	perf_pmu__del_caps(pmu);
2235 
2236 	perf_cpu_map__put(pmu->cpus);
2237 
2238 	zfree(&pmu->name);
2239 	zfree(&pmu->alias_name);
2240 	zfree(&pmu->id);
2241 	free(pmu);
2242 }
2243 
2244 const char *perf_pmu__name_from_config(struct perf_pmu *pmu, u64 config)
2245 {
2246 	struct perf_pmu_alias *event;
2247 
2248 	if (!pmu)
2249 		return NULL;
2250 
2251 	pmu_aliases_parse(pmu);
2252 	pmu_add_cpu_aliases(pmu);
2253 	list_for_each_entry(event, &pmu->aliases, list) {
2254 		struct perf_event_attr attr = {.config = 0,};
2255 		int ret = perf_pmu__config(pmu, &attr, &event->terms, NULL);
2256 
2257 		if (ret == 0 && config == attr.config)
2258 			return event->name;
2259 	}
2260 	return NULL;
2261 }
2262