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