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