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