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