xref: /openbmc/linux/tools/perf/util/pmu.c (revision 89df62c3)
1 // SPDX-License-Identifier: GPL-2.0
2 #include <linux/list.h>
3 #include <linux/compiler.h>
4 #include <linux/string.h>
5 #include <linux/zalloc.h>
6 #include <linux/ctype.h>
7 #include <sys/types.h>
8 #include <fcntl.h>
9 #include <sys/stat.h>
10 #include <unistd.h>
11 #include <stdio.h>
12 #include <stdbool.h>
13 #include <dirent.h>
14 #include <api/fs/fs.h>
15 #include <locale.h>
16 #include <fnmatch.h>
17 #include <math.h>
18 #include "debug.h"
19 #include "evsel.h"
20 #include "pmu.h"
21 #include "pmus.h"
22 #include "pmu-bison.h"
23 #include "pmu-flex.h"
24 #include "parse-events.h"
25 #include "print-events.h"
26 #include "header.h"
27 #include "string2.h"
28 #include "strbuf.h"
29 #include "fncache.h"
30 #include "util/evsel_config.h"
31 
32 struct perf_pmu perf_pmu__fake;
33 
34 /**
35  * struct perf_pmu_format - Values from a format file read from
36  * <sysfs>/devices/cpu/format/ held in struct perf_pmu.
37  *
38  * For example, the contents of <sysfs>/devices/cpu/format/event may be
39  * "config:0-7" and will be represented here as name="event",
40  * value=PERF_PMU_FORMAT_VALUE_CONFIG and bits 0 to 7 will be set.
41  */
42 struct perf_pmu_format {
43 	/** @name: The modifier/file name. */
44 	char *name;
45 	/**
46 	 * @value : Which config value the format relates to. Supported values
47 	 * are from PERF_PMU_FORMAT_VALUE_CONFIG to
48 	 * PERF_PMU_FORMAT_VALUE_CONFIG_END.
49 	 */
50 	int value;
51 	/** @bits: Which config bits are set by this format value. */
52 	DECLARE_BITMAP(bits, PERF_PMU_FORMAT_BITS);
53 	/** @list: Element on list within struct perf_pmu. */
54 	struct list_head list;
55 };
56 
57 /*
58  * Parse & process all the sysfs attributes located under
59  * the directory specified in 'dir' parameter.
60  */
61 int perf_pmu__format_parse(int dirfd, struct list_head *head)
62 {
63 	struct dirent *evt_ent;
64 	DIR *format_dir;
65 	int ret = 0;
66 
67 	format_dir = fdopendir(dirfd);
68 	if (!format_dir)
69 		return -EINVAL;
70 
71 	while (!ret && (evt_ent = readdir(format_dir))) {
72 		char *name = evt_ent->d_name;
73 		int fd;
74 		void *scanner;
75 		FILE *file;
76 
77 		if (!strcmp(name, ".") || !strcmp(name, ".."))
78 			continue;
79 
80 
81 		ret = -EINVAL;
82 		fd = openat(dirfd, name, O_RDONLY);
83 		if (fd < 0)
84 			break;
85 
86 		file = fdopen(fd, "r");
87 		if (!file) {
88 			close(fd);
89 			break;
90 		}
91 
92 		ret = perf_pmu_lex_init(&scanner);
93 		if (ret) {
94 			fclose(file);
95 			break;
96 		}
97 
98 		perf_pmu_set_in(file, scanner);
99 		ret = perf_pmu_parse(head, name, scanner);
100 		perf_pmu_lex_destroy(scanner);
101 		fclose(file);
102 	}
103 
104 	closedir(format_dir);
105 	return ret;
106 }
107 
108 /*
109  * Reading/parsing the default pmu format definition, which should be
110  * located at:
111  * /sys/bus/event_source/devices/<dev>/format as sysfs group attributes.
112  */
113 static int pmu_format(int dirfd, const char *name, struct list_head *format)
114 {
115 	int fd;
116 
117 	fd = perf_pmu__pathname_fd(dirfd, name, "format", O_DIRECTORY);
118 	if (fd < 0)
119 		return 0;
120 
121 	/* it'll close the fd */
122 	if (perf_pmu__format_parse(fd, format))
123 		return -1;
124 
125 	return 0;
126 }
127 
128 int perf_pmu__convert_scale(const char *scale, char **end, double *sval)
129 {
130 	char *lc;
131 	int ret = 0;
132 
133 	/*
134 	 * save current locale
135 	 */
136 	lc = setlocale(LC_NUMERIC, NULL);
137 
138 	/*
139 	 * The lc string may be allocated in static storage,
140 	 * so get a dynamic copy to make it survive setlocale
141 	 * call below.
142 	 */
143 	lc = strdup(lc);
144 	if (!lc) {
145 		ret = -ENOMEM;
146 		goto out;
147 	}
148 
149 	/*
150 	 * force to C locale to ensure kernel
151 	 * scale string is converted correctly.
152 	 * kernel uses default C locale.
153 	 */
154 	setlocale(LC_NUMERIC, "C");
155 
156 	*sval = strtod(scale, end);
157 
158 out:
159 	/* restore locale */
160 	setlocale(LC_NUMERIC, lc);
161 	free(lc);
162 	return ret;
163 }
164 
165 static int perf_pmu__parse_scale(struct perf_pmu_alias *alias, int dirfd, char *name)
166 {
167 	struct stat st;
168 	ssize_t sret;
169 	char scale[128];
170 	int fd, ret = -1;
171 	char path[PATH_MAX];
172 
173 	scnprintf(path, PATH_MAX, "%s.scale", name);
174 
175 	fd = openat(dirfd, path, O_RDONLY);
176 	if (fd == -1)
177 		return -1;
178 
179 	if (fstat(fd, &st) < 0)
180 		goto error;
181 
182 	sret = read(fd, scale, sizeof(scale)-1);
183 	if (sret < 0)
184 		goto error;
185 
186 	if (scale[sret - 1] == '\n')
187 		scale[sret - 1] = '\0';
188 	else
189 		scale[sret] = '\0';
190 
191 	ret = perf_pmu__convert_scale(scale, NULL, &alias->scale);
192 error:
193 	close(fd);
194 	return ret;
195 }
196 
197 static int perf_pmu__parse_unit(struct perf_pmu_alias *alias, int dirfd, char *name)
198 {
199 	char path[PATH_MAX];
200 	ssize_t sret;
201 	int fd;
202 
203 	scnprintf(path, PATH_MAX, "%s.unit", name);
204 
205 	fd = openat(dirfd, path, O_RDONLY);
206 	if (fd == -1)
207 		return -1;
208 
209 	sret = read(fd, alias->unit, UNIT_MAX_LEN);
210 	if (sret < 0)
211 		goto error;
212 
213 	close(fd);
214 
215 	if (alias->unit[sret - 1] == '\n')
216 		alias->unit[sret - 1] = '\0';
217 	else
218 		alias->unit[sret] = '\0';
219 
220 	return 0;
221 error:
222 	close(fd);
223 	alias->unit[0] = '\0';
224 	return -1;
225 }
226 
227 static int
228 perf_pmu__parse_per_pkg(struct perf_pmu_alias *alias, int dirfd, char *name)
229 {
230 	char path[PATH_MAX];
231 	int fd;
232 
233 	scnprintf(path, PATH_MAX, "%s.per-pkg", name);
234 
235 	fd = openat(dirfd, path, O_RDONLY);
236 	if (fd == -1)
237 		return -1;
238 
239 	close(fd);
240 
241 	alias->per_pkg = true;
242 	return 0;
243 }
244 
245 static int perf_pmu__parse_snapshot(struct perf_pmu_alias *alias,
246 				    int dirfd, char *name)
247 {
248 	char path[PATH_MAX];
249 	int fd;
250 
251 	scnprintf(path, PATH_MAX, "%s.snapshot", name);
252 
253 	fd = openat(dirfd, path, O_RDONLY);
254 	if (fd == -1)
255 		return -1;
256 
257 	alias->snapshot = true;
258 	close(fd);
259 	return 0;
260 }
261 
262 static void perf_pmu_assign_str(char *name, const char *field, char **old_str,
263 				char **new_str)
264 {
265 	if (!*old_str)
266 		goto set_new;
267 
268 	if (*new_str) {	/* Have new string, check with old */
269 		if (strcasecmp(*old_str, *new_str))
270 			pr_debug("alias %s differs in field '%s'\n",
271 				 name, field);
272 		zfree(old_str);
273 	} else		/* Nothing new --> keep old string */
274 		return;
275 set_new:
276 	*old_str = *new_str;
277 	*new_str = NULL;
278 }
279 
280 static void perf_pmu_update_alias(struct perf_pmu_alias *old,
281 				  struct perf_pmu_alias *newalias)
282 {
283 	perf_pmu_assign_str(old->name, "desc", &old->desc, &newalias->desc);
284 	perf_pmu_assign_str(old->name, "long_desc", &old->long_desc,
285 			    &newalias->long_desc);
286 	perf_pmu_assign_str(old->name, "topic", &old->topic, &newalias->topic);
287 	perf_pmu_assign_str(old->name, "value", &old->str, &newalias->str);
288 	old->scale = newalias->scale;
289 	old->per_pkg = newalias->per_pkg;
290 	old->snapshot = newalias->snapshot;
291 	memcpy(old->unit, newalias->unit, sizeof(old->unit));
292 }
293 
294 /* Delete an alias entry. */
295 void perf_pmu_free_alias(struct perf_pmu_alias *newalias)
296 {
297 	zfree(&newalias->name);
298 	zfree(&newalias->desc);
299 	zfree(&newalias->long_desc);
300 	zfree(&newalias->topic);
301 	zfree(&newalias->str);
302 	zfree(&newalias->pmu_name);
303 	parse_events_terms__purge(&newalias->terms);
304 	free(newalias);
305 }
306 
307 static void perf_pmu__del_aliases(struct perf_pmu *pmu)
308 {
309 	struct perf_pmu_alias *alias, *tmp;
310 
311 	list_for_each_entry_safe(alias, tmp, &pmu->aliases, list) {
312 		list_del(&alias->list);
313 		perf_pmu_free_alias(alias);
314 	}
315 }
316 
317 /* Merge an alias, search in alias list. If this name is already
318  * present merge both of them to combine all information.
319  */
320 static bool perf_pmu_merge_alias(struct perf_pmu_alias *newalias,
321 				 struct list_head *alist)
322 {
323 	struct perf_pmu_alias *a;
324 
325 	list_for_each_entry(a, alist, list) {
326 		if (!strcasecmp(newalias->name, a->name)) {
327 			if (newalias->pmu_name && a->pmu_name &&
328 			    !strcasecmp(newalias->pmu_name, a->pmu_name)) {
329 				continue;
330 			}
331 			perf_pmu_update_alias(a, newalias);
332 			perf_pmu_free_alias(newalias);
333 			return true;
334 		}
335 	}
336 	return false;
337 }
338 
339 static int __perf_pmu__new_alias(struct list_head *list, int dirfd, char *name,
340 				 char *desc, char *val, const struct pmu_event *pe)
341 {
342 	struct parse_events_term *term;
343 	struct perf_pmu_alias *alias;
344 	int ret;
345 	char newval[256];
346 	const char *long_desc = NULL, *topic = NULL, *unit = NULL, *pmu_name = NULL;
347 	bool deprecated = false, perpkg = false;
348 
349 	if (pe) {
350 		long_desc = pe->long_desc;
351 		topic = pe->topic;
352 		unit = pe->unit;
353 		perpkg = pe->perpkg;
354 		deprecated = pe->deprecated;
355 		pmu_name = pe->pmu;
356 	}
357 
358 	alias = malloc(sizeof(*alias));
359 	if (!alias)
360 		return -ENOMEM;
361 
362 	INIT_LIST_HEAD(&alias->terms);
363 	alias->scale = 1.0;
364 	alias->unit[0] = '\0';
365 	alias->per_pkg = perpkg;
366 	alias->snapshot = false;
367 	alias->deprecated = deprecated;
368 
369 	ret = parse_events_terms(&alias->terms, val);
370 	if (ret) {
371 		pr_err("Cannot parse alias %s: %d\n", val, ret);
372 		free(alias);
373 		return ret;
374 	}
375 
376 	/* Scan event and remove leading zeroes, spaces, newlines, some
377 	 * platforms have terms specified as
378 	 * event=0x0091 (read from files ../<PMU>/events/<FILE>
379 	 * and terms specified as event=0x91 (read from JSON files).
380 	 *
381 	 * Rebuild string to make alias->str member comparable.
382 	 */
383 	memset(newval, 0, sizeof(newval));
384 	ret = 0;
385 	list_for_each_entry(term, &alias->terms, list) {
386 		if (ret)
387 			ret += scnprintf(newval + ret, sizeof(newval) - ret,
388 					 ",");
389 		if (term->type_val == PARSE_EVENTS__TERM_TYPE_NUM)
390 			ret += scnprintf(newval + ret, sizeof(newval) - ret,
391 					 "%s=%#x", term->config, term->val.num);
392 		else if (term->type_val == PARSE_EVENTS__TERM_TYPE_STR)
393 			ret += scnprintf(newval + ret, sizeof(newval) - ret,
394 					 "%s=%s", term->config, term->val.str);
395 	}
396 
397 	alias->name = strdup(name);
398 	if (dirfd >= 0) {
399 		/*
400 		 * load unit name and scale if available
401 		 */
402 		perf_pmu__parse_unit(alias, dirfd, name);
403 		perf_pmu__parse_scale(alias, dirfd, name);
404 		perf_pmu__parse_per_pkg(alias, dirfd, name);
405 		perf_pmu__parse_snapshot(alias, dirfd, name);
406 	}
407 
408 	alias->desc = desc ? strdup(desc) : NULL;
409 	alias->long_desc = long_desc ? strdup(long_desc) :
410 				desc ? strdup(desc) : NULL;
411 	alias->topic = topic ? strdup(topic) : NULL;
412 	if (unit) {
413 		if (perf_pmu__convert_scale(unit, (char **)&unit, &alias->scale) < 0)
414 			return -1;
415 		snprintf(alias->unit, sizeof(alias->unit), "%s", unit);
416 	}
417 	alias->str = strdup(newval);
418 	alias->pmu_name = pmu_name ? strdup(pmu_name) : NULL;
419 
420 	if (!perf_pmu_merge_alias(alias, list))
421 		list_add_tail(&alias->list, list);
422 
423 	return 0;
424 }
425 
426 static int perf_pmu__new_alias(struct list_head *list, int dirfd, char *name, FILE *file)
427 {
428 	char buf[256];
429 	int ret;
430 
431 	ret = fread(buf, 1, sizeof(buf), file);
432 	if (ret == 0)
433 		return -EINVAL;
434 
435 	buf[ret] = 0;
436 
437 	/* Remove trailing newline from sysfs file */
438 	strim(buf);
439 
440 	return __perf_pmu__new_alias(list, dirfd, name, NULL, buf, NULL);
441 }
442 
443 static inline bool pmu_alias_info_file(char *name)
444 {
445 	size_t len;
446 
447 	len = strlen(name);
448 	if (len > 5 && !strcmp(name + len - 5, ".unit"))
449 		return true;
450 	if (len > 6 && !strcmp(name + len - 6, ".scale"))
451 		return true;
452 	if (len > 8 && !strcmp(name + len - 8, ".per-pkg"))
453 		return true;
454 	if (len > 9 && !strcmp(name + len - 9, ".snapshot"))
455 		return true;
456 
457 	return false;
458 }
459 
460 /*
461  * Process all the sysfs attributes located under the directory
462  * specified in 'dir' parameter.
463  */
464 static int pmu_aliases_parse(int dirfd, struct list_head *head)
465 {
466 	struct dirent *evt_ent;
467 	DIR *event_dir;
468 	int fd;
469 
470 	event_dir = fdopendir(dirfd);
471 	if (!event_dir)
472 		return -EINVAL;
473 
474 	while ((evt_ent = readdir(event_dir))) {
475 		char *name = evt_ent->d_name;
476 		FILE *file;
477 
478 		if (!strcmp(name, ".") || !strcmp(name, ".."))
479 			continue;
480 
481 		/*
482 		 * skip info files parsed in perf_pmu__new_alias()
483 		 */
484 		if (pmu_alias_info_file(name))
485 			continue;
486 
487 		fd = openat(dirfd, name, O_RDONLY);
488 		if (fd == -1) {
489 			pr_debug("Cannot open %s\n", name);
490 			continue;
491 		}
492 		file = fdopen(fd, "r");
493 		if (!file) {
494 			close(fd);
495 			continue;
496 		}
497 
498 		if (perf_pmu__new_alias(head, dirfd, name, file) < 0)
499 			pr_debug("Cannot set up %s\n", name);
500 		fclose(file);
501 	}
502 
503 	closedir(event_dir);
504 	return 0;
505 }
506 
507 /*
508  * Reading the pmu event aliases definition, which should be located at:
509  * /sys/bus/event_source/devices/<dev>/events as sysfs group attributes.
510  */
511 static int pmu_aliases(int dirfd, const char *name, struct list_head *head)
512 {
513 	int fd;
514 
515 	fd = perf_pmu__pathname_fd(dirfd, name, "events", O_DIRECTORY);
516 	if (fd < 0)
517 		return 0;
518 
519 	/* it'll close the fd */
520 	if (pmu_aliases_parse(fd, head))
521 		return -1;
522 
523 	return 0;
524 }
525 
526 static int pmu_alias_terms(struct perf_pmu_alias *alias,
527 			   struct list_head *terms)
528 {
529 	struct parse_events_term *term, *cloned;
530 	LIST_HEAD(list);
531 	int ret;
532 
533 	list_for_each_entry(term, &alias->terms, list) {
534 		ret = parse_events_term__clone(&cloned, term);
535 		if (ret) {
536 			parse_events_terms__purge(&list);
537 			return ret;
538 		}
539 		/*
540 		 * Weak terms don't override command line options,
541 		 * which we don't want for implicit terms in aliases.
542 		 */
543 		cloned->weak = true;
544 		list_add_tail(&cloned->list, &list);
545 	}
546 	list_splice(&list, terms);
547 	return 0;
548 }
549 
550 /*
551  * Uncore PMUs have a "cpumask" file under sysfs. CPU PMUs (e.g. on arm/arm64)
552  * may have a "cpus" file.
553  */
554 static struct perf_cpu_map *pmu_cpumask(int dirfd, const char *name)
555 {
556 	struct perf_cpu_map *cpus;
557 	const char *templates[] = {
558 		"cpumask",
559 		"cpus",
560 		NULL
561 	};
562 	const char **template;
563 	char pmu_name[PATH_MAX];
564 	struct perf_pmu pmu = {.name = pmu_name};
565 	FILE *file;
566 
567 	strlcpy(pmu_name, name, sizeof(pmu_name));
568 	for (template = templates; *template; template++) {
569 		file = perf_pmu__open_file_at(&pmu, dirfd, *template);
570 		if (!file)
571 			continue;
572 		cpus = perf_cpu_map__read(file);
573 		fclose(file);
574 		if (cpus)
575 			return cpus;
576 	}
577 
578 	return !strcmp(name, "cpu") ? perf_cpu_map__get(cpu_map__online()) : NULL;
579 }
580 
581 static bool pmu_is_uncore(int dirfd, const char *name)
582 {
583 	int fd;
584 
585 	fd = perf_pmu__pathname_fd(dirfd, name, "cpumask", O_PATH);
586 	if (fd < 0)
587 		return false;
588 
589 	close(fd);
590 	return true;
591 }
592 
593 static char *pmu_id(const char *name)
594 {
595 	char path[PATH_MAX], *str;
596 	size_t len;
597 
598 	perf_pmu__pathname_scnprintf(path, sizeof(path), name, "identifier");
599 
600 	if (filename__read_str(path, &str, &len) < 0)
601 		return NULL;
602 
603 	str[len - 1] = 0; /* remove line feed */
604 
605 	return str;
606 }
607 
608 /**
609  * is_sysfs_pmu_core() - PMU CORE devices have different name other than cpu in
610  *         sysfs on some platforms like ARM or Intel hybrid. Looking for
611  *         possible the cpus file in sysfs files to identify whether this is a
612  *         core device.
613  * @name: The PMU name such as "cpu_atom".
614  */
615 static int is_sysfs_pmu_core(const char *name)
616 {
617 	char path[PATH_MAX];
618 
619 	if (!perf_pmu__pathname_scnprintf(path, sizeof(path), name, "cpus"))
620 		return 0;
621 	return file_available(path);
622 }
623 
624 char *perf_pmu__getcpuid(struct perf_pmu *pmu)
625 {
626 	char *cpuid;
627 	static bool printed;
628 
629 	cpuid = getenv("PERF_CPUID");
630 	if (cpuid)
631 		cpuid = strdup(cpuid);
632 	if (!cpuid)
633 		cpuid = get_cpuid_str(pmu);
634 	if (!cpuid)
635 		return NULL;
636 
637 	if (!printed) {
638 		pr_debug("Using CPUID %s\n", cpuid);
639 		printed = true;
640 	}
641 	return cpuid;
642 }
643 
644 __weak const struct pmu_events_table *pmu_events_table__find(void)
645 {
646 	return perf_pmu__find_events_table(NULL);
647 }
648 
649 __weak const struct pmu_metrics_table *pmu_metrics_table__find(void)
650 {
651 	return perf_pmu__find_metrics_table(NULL);
652 }
653 
654 /**
655  * perf_pmu__match_ignoring_suffix - Does the pmu_name match tok ignoring any
656  *                                   trailing suffix? The Suffix must be in form
657  *                                   tok_{digits}, or tok{digits}.
658  * @pmu_name: The pmu_name with possible suffix.
659  * @tok: The possible match to pmu_name without suffix.
660  */
661 static bool perf_pmu__match_ignoring_suffix(const char *pmu_name, const char *tok)
662 {
663 	const char *p;
664 
665 	if (strncmp(pmu_name, tok, strlen(tok)))
666 		return false;
667 
668 	p = pmu_name + strlen(tok);
669 	if (*p == 0)
670 		return true;
671 
672 	if (*p == '_')
673 		++p;
674 
675 	/* Ensure we end in a number */
676 	while (1) {
677 		if (!isdigit(*p))
678 			return false;
679 		if (*(++p) == 0)
680 			break;
681 	}
682 
683 	return true;
684 }
685 
686 /**
687  * pmu_uncore_alias_match - does name match the PMU name?
688  * @pmu_name: the json struct pmu_event name. This may lack a suffix (which
689  *            matches) or be of the form "socket,pmuname" which will match
690  *            "socketX_pmunameY".
691  * @name: a real full PMU name as from sysfs.
692  */
693 static bool pmu_uncore_alias_match(const char *pmu_name, const char *name)
694 {
695 	char *tmp = NULL, *tok, *str;
696 	bool res;
697 
698 	if (strchr(pmu_name, ',') == NULL)
699 		return perf_pmu__match_ignoring_suffix(name, pmu_name);
700 
701 	str = strdup(pmu_name);
702 	if (!str)
703 		return false;
704 
705 	/*
706 	 * uncore alias may be from different PMU with common prefix
707 	 */
708 	tok = strtok_r(str, ",", &tmp);
709 	if (strncmp(pmu_name, tok, strlen(tok))) {
710 		res = false;
711 		goto out;
712 	}
713 
714 	/*
715 	 * Match more complex aliases where the alias name is a comma-delimited
716 	 * list of tokens, orderly contained in the matching PMU name.
717 	 *
718 	 * Example: For alias "socket,pmuname" and PMU "socketX_pmunameY", we
719 	 *	    match "socket" in "socketX_pmunameY" and then "pmuname" in
720 	 *	    "pmunameY".
721 	 */
722 	while (1) {
723 		char *next_tok = strtok_r(NULL, ",", &tmp);
724 
725 		name = strstr(name, tok);
726 		if (!name ||
727 		    (!next_tok && !perf_pmu__match_ignoring_suffix(name, tok))) {
728 			res = false;
729 			goto out;
730 		}
731 		if (!next_tok)
732 			break;
733 		tok = next_tok;
734 		name += strlen(tok);
735 	}
736 
737 	res = true;
738 out:
739 	free(str);
740 	return res;
741 }
742 
743 struct pmu_add_cpu_aliases_map_data {
744 	struct list_head *head;
745 	const char *name;
746 	const char *cpu_name;
747 	struct perf_pmu *pmu;
748 };
749 
750 static int pmu_add_cpu_aliases_map_callback(const struct pmu_event *pe,
751 					const struct pmu_events_table *table __maybe_unused,
752 					void *vdata)
753 {
754 	struct pmu_add_cpu_aliases_map_data *data = vdata;
755 	const char *pname = pe->pmu ? pe->pmu : data->cpu_name;
756 
757 	if (data->pmu->is_uncore && pmu_uncore_alias_match(pname, data->name))
758 		goto new_alias;
759 
760 	if (strcmp(pname, data->name))
761 		return 0;
762 
763 new_alias:
764 	/* need type casts to override 'const' */
765 	__perf_pmu__new_alias(data->head, -1, (char *)pe->name, (char *)pe->desc,
766 			      (char *)pe->event, pe);
767 	return 0;
768 }
769 
770 /*
771  * From the pmu_events_map, find the table of PMU events that corresponds
772  * to the current running CPU. Then, add all PMU events from that table
773  * as aliases.
774  */
775 void pmu_add_cpu_aliases_table(struct list_head *head, struct perf_pmu *pmu,
776 			       const struct pmu_events_table *table)
777 {
778 	struct pmu_add_cpu_aliases_map_data data = {
779 		.head = head,
780 		.name = pmu->name,
781 		.cpu_name = is_sysfs_pmu_core(pmu->name) ? pmu->name : "cpu",
782 		.pmu = pmu,
783 	};
784 
785 	pmu_events_table_for_each_event(table, pmu_add_cpu_aliases_map_callback, &data);
786 }
787 
788 static void pmu_add_cpu_aliases(struct list_head *head, struct perf_pmu *pmu)
789 {
790 	const struct pmu_events_table *table;
791 
792 	table = perf_pmu__find_events_table(pmu);
793 	if (!table)
794 		return;
795 
796 	pmu_add_cpu_aliases_table(head, pmu, table);
797 }
798 
799 struct pmu_sys_event_iter_data {
800 	struct list_head *head;
801 	struct perf_pmu *pmu;
802 };
803 
804 static int pmu_add_sys_aliases_iter_fn(const struct pmu_event *pe,
805 				       const struct pmu_events_table *table __maybe_unused,
806 				       void *data)
807 {
808 	struct pmu_sys_event_iter_data *idata = data;
809 	struct perf_pmu *pmu = idata->pmu;
810 
811 	if (!pe->compat || !pe->pmu)
812 		return 0;
813 
814 	if (!strcmp(pmu->id, pe->compat) &&
815 	    pmu_uncore_alias_match(pe->pmu, pmu->name)) {
816 		__perf_pmu__new_alias(idata->head, -1,
817 				      (char *)pe->name,
818 				      (char *)pe->desc,
819 				      (char *)pe->event,
820 				      pe);
821 	}
822 
823 	return 0;
824 }
825 
826 void pmu_add_sys_aliases(struct list_head *head, struct perf_pmu *pmu)
827 {
828 	struct pmu_sys_event_iter_data idata = {
829 		.head = head,
830 		.pmu = pmu,
831 	};
832 
833 	if (!pmu->id)
834 		return;
835 
836 	pmu_for_each_sys_event(pmu_add_sys_aliases_iter_fn, &idata);
837 }
838 
839 struct perf_event_attr * __weak
840 perf_pmu__get_default_config(struct perf_pmu *pmu __maybe_unused)
841 {
842 	return NULL;
843 }
844 
845 char * __weak
846 pmu_find_real_name(const char *name)
847 {
848 	return (char *)name;
849 }
850 
851 char * __weak
852 pmu_find_alias_name(const char *name __maybe_unused)
853 {
854 	return NULL;
855 }
856 
857 static int pmu_max_precise(int dirfd, struct perf_pmu *pmu)
858 {
859 	int max_precise = -1;
860 
861 	perf_pmu__scan_file_at(pmu, dirfd, "caps/max_precise", "%d", &max_precise);
862 	return max_precise;
863 }
864 
865 struct perf_pmu *perf_pmu__lookup(struct list_head *pmus, int dirfd, const char *lookup_name)
866 {
867 	struct perf_pmu *pmu;
868 	LIST_HEAD(format);
869 	LIST_HEAD(aliases);
870 	__u32 type;
871 	char *name = pmu_find_real_name(lookup_name);
872 	char *alias_name;
873 
874 	/*
875 	 * The pmu data we store & need consists of the pmu
876 	 * type value and format definitions. Load both right
877 	 * now.
878 	 */
879 	if (pmu_format(dirfd, name, &format))
880 		return NULL;
881 
882 	/*
883 	 * Check the aliases first to avoid unnecessary work.
884 	 */
885 	if (pmu_aliases(dirfd, name, &aliases))
886 		return NULL;
887 
888 	pmu = zalloc(sizeof(*pmu));
889 	if (!pmu)
890 		return NULL;
891 
892 	pmu->cpus = pmu_cpumask(dirfd, name);
893 	pmu->name = strdup(name);
894 	if (!pmu->name)
895 		goto err;
896 
897 	/* Read type, and ensure that type value is successfully assigned (return 1) */
898 	if (perf_pmu__scan_file_at(pmu, dirfd, "type", "%u", &type) != 1)
899 		goto err;
900 
901 	alias_name = pmu_find_alias_name(name);
902 	if (alias_name) {
903 		pmu->alias_name = strdup(alias_name);
904 		if (!pmu->alias_name)
905 			goto err;
906 	}
907 
908 	pmu->type = type;
909 	pmu->is_core = is_pmu_core(name);
910 	pmu->is_uncore = pmu_is_uncore(dirfd, name);
911 	if (pmu->is_uncore)
912 		pmu->id = pmu_id(name);
913 	pmu->max_precise = pmu_max_precise(dirfd, pmu);
914 	pmu_add_cpu_aliases(&aliases, pmu);
915 	pmu_add_sys_aliases(&aliases, pmu);
916 
917 	INIT_LIST_HEAD(&pmu->format);
918 	INIT_LIST_HEAD(&pmu->aliases);
919 	INIT_LIST_HEAD(&pmu->caps);
920 	list_splice(&format, &pmu->format);
921 	list_splice(&aliases, &pmu->aliases);
922 	list_add_tail(&pmu->list, pmus);
923 
924 	pmu->default_config = perf_pmu__get_default_config(pmu);
925 
926 	return pmu;
927 err:
928 	zfree(&pmu->name);
929 	free(pmu);
930 	return NULL;
931 }
932 
933 void perf_pmu__warn_invalid_formats(struct perf_pmu *pmu)
934 {
935 	struct perf_pmu_format *format;
936 
937 	/* fake pmu doesn't have format list */
938 	if (pmu == &perf_pmu__fake)
939 		return;
940 
941 	list_for_each_entry(format, &pmu->format, list)
942 		if (format->value >= PERF_PMU_FORMAT_VALUE_CONFIG_END) {
943 			pr_warning("WARNING: '%s' format '%s' requires 'perf_event_attr::config%d'"
944 				   "which is not supported by this version of perf!\n",
945 				   pmu->name, format->name, format->value);
946 			return;
947 		}
948 }
949 
950 bool evsel__is_aux_event(const struct evsel *evsel)
951 {
952 	struct perf_pmu *pmu = evsel__find_pmu(evsel);
953 
954 	return pmu && pmu->auxtrace;
955 }
956 
957 /*
958  * Set @config_name to @val as long as the user hasn't already set or cleared it
959  * by passing a config term on the command line.
960  *
961  * @val is the value to put into the bits specified by @config_name rather than
962  * the bit pattern. It is shifted into position by this function, so to set
963  * something to true, pass 1 for val rather than a pre shifted value.
964  */
965 #define field_prep(_mask, _val) (((_val) << (ffsll(_mask) - 1)) & (_mask))
966 void evsel__set_config_if_unset(struct perf_pmu *pmu, struct evsel *evsel,
967 				const char *config_name, u64 val)
968 {
969 	u64 user_bits = 0, bits;
970 	struct evsel_config_term *term = evsel__get_config_term(evsel, CFG_CHG);
971 
972 	if (term)
973 		user_bits = term->val.cfg_chg;
974 
975 	bits = perf_pmu__format_bits(&pmu->format, config_name);
976 
977 	/* Do nothing if the user changed the value */
978 	if (bits & user_bits)
979 		return;
980 
981 	/* Otherwise replace it */
982 	evsel->core.attr.config &= ~bits;
983 	evsel->core.attr.config |= field_prep(bits, val);
984 }
985 
986 static struct perf_pmu_format *
987 pmu_find_format(struct list_head *formats, const char *name)
988 {
989 	struct perf_pmu_format *format;
990 
991 	list_for_each_entry(format, formats, list)
992 		if (!strcmp(format->name, name))
993 			return format;
994 
995 	return NULL;
996 }
997 
998 __u64 perf_pmu__format_bits(struct list_head *formats, const char *name)
999 {
1000 	struct perf_pmu_format *format = pmu_find_format(formats, name);
1001 	__u64 bits = 0;
1002 	int fbit;
1003 
1004 	if (!format)
1005 		return 0;
1006 
1007 	for_each_set_bit(fbit, format->bits, PERF_PMU_FORMAT_BITS)
1008 		bits |= 1ULL << fbit;
1009 
1010 	return bits;
1011 }
1012 
1013 int perf_pmu__format_type(struct list_head *formats, const char *name)
1014 {
1015 	struct perf_pmu_format *format = pmu_find_format(formats, name);
1016 
1017 	if (!format)
1018 		return -1;
1019 
1020 	return format->value;
1021 }
1022 
1023 /*
1024  * Sets value based on the format definition (format parameter)
1025  * and unformatted value (value parameter).
1026  */
1027 static void pmu_format_value(unsigned long *format, __u64 value, __u64 *v,
1028 			     bool zero)
1029 {
1030 	unsigned long fbit, vbit;
1031 
1032 	for (fbit = 0, vbit = 0; fbit < PERF_PMU_FORMAT_BITS; fbit++) {
1033 
1034 		if (!test_bit(fbit, format))
1035 			continue;
1036 
1037 		if (value & (1llu << vbit++))
1038 			*v |= (1llu << fbit);
1039 		else if (zero)
1040 			*v &= ~(1llu << fbit);
1041 	}
1042 }
1043 
1044 static __u64 pmu_format_max_value(const unsigned long *format)
1045 {
1046 	int w;
1047 
1048 	w = bitmap_weight(format, PERF_PMU_FORMAT_BITS);
1049 	if (!w)
1050 		return 0;
1051 	if (w < 64)
1052 		return (1ULL << w) - 1;
1053 	return -1;
1054 }
1055 
1056 /*
1057  * Term is a string term, and might be a param-term. Try to look up it's value
1058  * in the remaining terms.
1059  * - We have a term like "base-or-format-term=param-term",
1060  * - We need to find the value supplied for "param-term" (with param-term named
1061  *   in a config string) later on in the term list.
1062  */
1063 static int pmu_resolve_param_term(struct parse_events_term *term,
1064 				  struct list_head *head_terms,
1065 				  __u64 *value)
1066 {
1067 	struct parse_events_term *t;
1068 
1069 	list_for_each_entry(t, head_terms, list) {
1070 		if (t->type_val == PARSE_EVENTS__TERM_TYPE_NUM &&
1071 		    t->config && !strcmp(t->config, term->config)) {
1072 			t->used = true;
1073 			*value = t->val.num;
1074 			return 0;
1075 		}
1076 	}
1077 
1078 	if (verbose > 0)
1079 		printf("Required parameter '%s' not specified\n", term->config);
1080 
1081 	return -1;
1082 }
1083 
1084 static char *pmu_formats_string(struct list_head *formats)
1085 {
1086 	struct perf_pmu_format *format;
1087 	char *str = NULL;
1088 	struct strbuf buf = STRBUF_INIT;
1089 	unsigned int i = 0;
1090 
1091 	if (!formats)
1092 		return NULL;
1093 
1094 	/* sysfs exported terms */
1095 	list_for_each_entry(format, formats, list)
1096 		if (strbuf_addf(&buf, i++ ? ",%s" : "%s", format->name) < 0)
1097 			goto error;
1098 
1099 	str = strbuf_detach(&buf, NULL);
1100 error:
1101 	strbuf_release(&buf);
1102 
1103 	return str;
1104 }
1105 
1106 /*
1107  * Setup one of config[12] attr members based on the
1108  * user input data - term parameter.
1109  */
1110 static int pmu_config_term(const char *pmu_name,
1111 			   struct list_head *formats,
1112 			   struct perf_event_attr *attr,
1113 			   struct parse_events_term *term,
1114 			   struct list_head *head_terms,
1115 			   bool zero, struct parse_events_error *err)
1116 {
1117 	struct perf_pmu_format *format;
1118 	__u64 *vp;
1119 	__u64 val, max_val;
1120 
1121 	/*
1122 	 * If this is a parameter we've already used for parameterized-eval,
1123 	 * skip it in normal eval.
1124 	 */
1125 	if (term->used)
1126 		return 0;
1127 
1128 	/*
1129 	 * Hardcoded terms should be already in, so nothing
1130 	 * to be done for them.
1131 	 */
1132 	if (parse_events__is_hardcoded_term(term))
1133 		return 0;
1134 
1135 	format = pmu_find_format(formats, term->config);
1136 	if (!format) {
1137 		char *pmu_term = pmu_formats_string(formats);
1138 		char *unknown_term;
1139 		char *help_msg;
1140 
1141 		if (asprintf(&unknown_term,
1142 				"unknown term '%s' for pmu '%s'",
1143 				term->config, pmu_name) < 0)
1144 			unknown_term = NULL;
1145 		help_msg = parse_events_formats_error_string(pmu_term);
1146 		if (err) {
1147 			parse_events_error__handle(err, term->err_term,
1148 						   unknown_term,
1149 						   help_msg);
1150 		} else {
1151 			pr_debug("%s (%s)\n", unknown_term, help_msg);
1152 			free(unknown_term);
1153 		}
1154 		free(pmu_term);
1155 		return -EINVAL;
1156 	}
1157 
1158 	switch (format->value) {
1159 	case PERF_PMU_FORMAT_VALUE_CONFIG:
1160 		vp = &attr->config;
1161 		break;
1162 	case PERF_PMU_FORMAT_VALUE_CONFIG1:
1163 		vp = &attr->config1;
1164 		break;
1165 	case PERF_PMU_FORMAT_VALUE_CONFIG2:
1166 		vp = &attr->config2;
1167 		break;
1168 	case PERF_PMU_FORMAT_VALUE_CONFIG3:
1169 		vp = &attr->config3;
1170 		break;
1171 	default:
1172 		return -EINVAL;
1173 	}
1174 
1175 	/*
1176 	 * Either directly use a numeric term, or try to translate string terms
1177 	 * using event parameters.
1178 	 */
1179 	if (term->type_val == PARSE_EVENTS__TERM_TYPE_NUM) {
1180 		if (term->no_value &&
1181 		    bitmap_weight(format->bits, PERF_PMU_FORMAT_BITS) > 1) {
1182 			if (err) {
1183 				parse_events_error__handle(err, term->err_val,
1184 					   strdup("no value assigned for term"),
1185 					   NULL);
1186 			}
1187 			return -EINVAL;
1188 		}
1189 
1190 		val = term->val.num;
1191 	} else if (term->type_val == PARSE_EVENTS__TERM_TYPE_STR) {
1192 		if (strcmp(term->val.str, "?")) {
1193 			if (verbose > 0) {
1194 				pr_info("Invalid sysfs entry %s=%s\n",
1195 						term->config, term->val.str);
1196 			}
1197 			if (err) {
1198 				parse_events_error__handle(err, term->err_val,
1199 					strdup("expected numeric value"),
1200 					NULL);
1201 			}
1202 			return -EINVAL;
1203 		}
1204 
1205 		if (pmu_resolve_param_term(term, head_terms, &val))
1206 			return -EINVAL;
1207 	} else
1208 		return -EINVAL;
1209 
1210 	max_val = pmu_format_max_value(format->bits);
1211 	if (val > max_val) {
1212 		if (err) {
1213 			char *err_str;
1214 
1215 			parse_events_error__handle(err, term->err_val,
1216 				asprintf(&err_str,
1217 				    "value too big for format, maximum is %llu",
1218 				    (unsigned long long)max_val) < 0
1219 				    ? strdup("value too big for format")
1220 				    : err_str,
1221 				    NULL);
1222 			return -EINVAL;
1223 		}
1224 		/*
1225 		 * Assume we don't care if !err, in which case the value will be
1226 		 * silently truncated.
1227 		 */
1228 	}
1229 
1230 	pmu_format_value(format->bits, val, vp, zero);
1231 	return 0;
1232 }
1233 
1234 int perf_pmu__config_terms(const char *pmu_name, struct list_head *formats,
1235 			   struct perf_event_attr *attr,
1236 			   struct list_head *head_terms,
1237 			   bool zero, struct parse_events_error *err)
1238 {
1239 	struct parse_events_term *term;
1240 
1241 	list_for_each_entry(term, head_terms, list) {
1242 		if (pmu_config_term(pmu_name, formats, attr, term, head_terms,
1243 				    zero, err))
1244 			return -EINVAL;
1245 	}
1246 
1247 	return 0;
1248 }
1249 
1250 /*
1251  * Configures event's 'attr' parameter based on the:
1252  * 1) users input - specified in terms parameter
1253  * 2) pmu format definitions - specified by pmu parameter
1254  */
1255 int perf_pmu__config(struct perf_pmu *pmu, struct perf_event_attr *attr,
1256 		     struct list_head *head_terms,
1257 		     struct parse_events_error *err)
1258 {
1259 	bool zero = !!pmu->default_config;
1260 
1261 	return perf_pmu__config_terms(pmu->name, &pmu->format, attr,
1262 				      head_terms, zero, err);
1263 }
1264 
1265 static struct perf_pmu_alias *pmu_find_alias(struct perf_pmu *pmu,
1266 					     struct parse_events_term *term)
1267 {
1268 	struct perf_pmu_alias *alias;
1269 	char *name;
1270 
1271 	if (parse_events__is_hardcoded_term(term))
1272 		return NULL;
1273 
1274 	if (term->type_val == PARSE_EVENTS__TERM_TYPE_NUM) {
1275 		if (term->val.num != 1)
1276 			return NULL;
1277 		if (pmu_find_format(&pmu->format, term->config))
1278 			return NULL;
1279 		name = term->config;
1280 	} else if (term->type_val == PARSE_EVENTS__TERM_TYPE_STR) {
1281 		if (strcasecmp(term->config, "event"))
1282 			return NULL;
1283 		name = term->val.str;
1284 	} else {
1285 		return NULL;
1286 	}
1287 
1288 	list_for_each_entry(alias, &pmu->aliases, list) {
1289 		if (!strcasecmp(alias->name, name))
1290 			return alias;
1291 	}
1292 	return NULL;
1293 }
1294 
1295 
1296 static int check_info_data(struct perf_pmu_alias *alias,
1297 			   struct perf_pmu_info *info)
1298 {
1299 	/*
1300 	 * Only one term in event definition can
1301 	 * define unit, scale and snapshot, fail
1302 	 * if there's more than one.
1303 	 */
1304 	if ((info->unit && alias->unit[0]) ||
1305 	    (info->scale && alias->scale) ||
1306 	    (info->snapshot && alias->snapshot))
1307 		return -EINVAL;
1308 
1309 	if (alias->unit[0])
1310 		info->unit = alias->unit;
1311 
1312 	if (alias->scale)
1313 		info->scale = alias->scale;
1314 
1315 	if (alias->snapshot)
1316 		info->snapshot = alias->snapshot;
1317 
1318 	return 0;
1319 }
1320 
1321 /*
1322  * Find alias in the terms list and replace it with the terms
1323  * defined for the alias
1324  */
1325 int perf_pmu__check_alias(struct perf_pmu *pmu, struct list_head *head_terms,
1326 			  struct perf_pmu_info *info)
1327 {
1328 	struct parse_events_term *term, *h;
1329 	struct perf_pmu_alias *alias;
1330 	int ret;
1331 
1332 	info->per_pkg = false;
1333 
1334 	/*
1335 	 * Mark unit and scale as not set
1336 	 * (different from default values, see below)
1337 	 */
1338 	info->unit     = NULL;
1339 	info->scale    = 0.0;
1340 	info->snapshot = false;
1341 
1342 	list_for_each_entry_safe(term, h, head_terms, list) {
1343 		alias = pmu_find_alias(pmu, term);
1344 		if (!alias)
1345 			continue;
1346 		ret = pmu_alias_terms(alias, &term->list);
1347 		if (ret)
1348 			return ret;
1349 
1350 		ret = check_info_data(alias, info);
1351 		if (ret)
1352 			return ret;
1353 
1354 		if (alias->per_pkg)
1355 			info->per_pkg = true;
1356 
1357 		list_del_init(&term->list);
1358 		parse_events_term__delete(term);
1359 	}
1360 
1361 	/*
1362 	 * if no unit or scale found in aliases, then
1363 	 * set defaults as for evsel
1364 	 * unit cannot left to NULL
1365 	 */
1366 	if (info->unit == NULL)
1367 		info->unit   = "";
1368 
1369 	if (info->scale == 0.0)
1370 		info->scale  = 1.0;
1371 
1372 	return 0;
1373 }
1374 
1375 int perf_pmu__new_format(struct list_head *list, char *name,
1376 			 int config, unsigned long *bits)
1377 {
1378 	struct perf_pmu_format *format;
1379 
1380 	format = zalloc(sizeof(*format));
1381 	if (!format)
1382 		return -ENOMEM;
1383 
1384 	format->name = strdup(name);
1385 	format->value = config;
1386 	memcpy(format->bits, bits, sizeof(format->bits));
1387 
1388 	list_add_tail(&format->list, list);
1389 	return 0;
1390 }
1391 
1392 void perf_pmu__set_format(unsigned long *bits, long from, long to)
1393 {
1394 	long b;
1395 
1396 	if (!to)
1397 		to = from;
1398 
1399 	memset(bits, 0, BITS_TO_BYTES(PERF_PMU_FORMAT_BITS));
1400 	for (b = from; b <= to; b++)
1401 		__set_bit(b, bits);
1402 }
1403 
1404 void perf_pmu__del_formats(struct list_head *formats)
1405 {
1406 	struct perf_pmu_format *fmt, *tmp;
1407 
1408 	list_for_each_entry_safe(fmt, tmp, formats, list) {
1409 		list_del(&fmt->list);
1410 		zfree(&fmt->name);
1411 		free(fmt);
1412 	}
1413 }
1414 
1415 bool is_pmu_core(const char *name)
1416 {
1417 	return !strcmp(name, "cpu") || is_sysfs_pmu_core(name);
1418 }
1419 
1420 bool perf_pmu__supports_legacy_cache(const struct perf_pmu *pmu)
1421 {
1422 	return pmu->is_core;
1423 }
1424 
1425 bool perf_pmu__auto_merge_stats(const struct perf_pmu *pmu)
1426 {
1427 	return pmu->is_core && perf_pmus__num_core_pmus() > 1;
1428 }
1429 
1430 bool perf_pmu__have_event(const struct perf_pmu *pmu, const char *name)
1431 {
1432 	struct perf_pmu_alias *alias;
1433 
1434 	list_for_each_entry(alias, &pmu->aliases, list) {
1435 		if (!strcmp(alias->name, name))
1436 			return true;
1437 	}
1438 	return false;
1439 }
1440 
1441 FILE *perf_pmu__open_file(struct perf_pmu *pmu, const char *name)
1442 {
1443 	char path[PATH_MAX];
1444 
1445 	if (!perf_pmu__pathname_scnprintf(path, sizeof(path), pmu->name, name) ||
1446 	    !file_available(path))
1447 		return NULL;
1448 
1449 	return fopen(path, "r");
1450 }
1451 
1452 FILE *perf_pmu__open_file_at(struct perf_pmu *pmu, int dirfd, const char *name)
1453 {
1454 	int fd;
1455 
1456 	fd = perf_pmu__pathname_fd(dirfd, pmu->name, name, O_RDONLY);
1457 	if (fd < 0)
1458 		return NULL;
1459 
1460 	return fdopen(fd, "r");
1461 }
1462 
1463 int perf_pmu__scan_file(struct perf_pmu *pmu, const char *name, const char *fmt,
1464 			...)
1465 {
1466 	va_list args;
1467 	FILE *file;
1468 	int ret = EOF;
1469 
1470 	va_start(args, fmt);
1471 	file = perf_pmu__open_file(pmu, name);
1472 	if (file) {
1473 		ret = vfscanf(file, fmt, args);
1474 		fclose(file);
1475 	}
1476 	va_end(args);
1477 	return ret;
1478 }
1479 
1480 int perf_pmu__scan_file_at(struct perf_pmu *pmu, int dirfd, const char *name,
1481 			   const char *fmt, ...)
1482 {
1483 	va_list args;
1484 	FILE *file;
1485 	int ret = EOF;
1486 
1487 	va_start(args, fmt);
1488 	file = perf_pmu__open_file_at(pmu, dirfd, name);
1489 	if (file) {
1490 		ret = vfscanf(file, fmt, args);
1491 		fclose(file);
1492 	}
1493 	va_end(args);
1494 	return ret;
1495 }
1496 
1497 bool perf_pmu__file_exists(struct perf_pmu *pmu, const char *name)
1498 {
1499 	char path[PATH_MAX];
1500 
1501 	if (!perf_pmu__pathname_scnprintf(path, sizeof(path), pmu->name, name))
1502 		return false;
1503 
1504 	return file_available(path);
1505 }
1506 
1507 static int perf_pmu__new_caps(struct list_head *list, char *name, char *value)
1508 {
1509 	struct perf_pmu_caps *caps = zalloc(sizeof(*caps));
1510 
1511 	if (!caps)
1512 		return -ENOMEM;
1513 
1514 	caps->name = strdup(name);
1515 	if (!caps->name)
1516 		goto free_caps;
1517 	caps->value = strndup(value, strlen(value) - 1);
1518 	if (!caps->value)
1519 		goto free_name;
1520 	list_add_tail(&caps->list, list);
1521 	return 0;
1522 
1523 free_name:
1524 	zfree(&caps->name);
1525 free_caps:
1526 	free(caps);
1527 
1528 	return -ENOMEM;
1529 }
1530 
1531 static void perf_pmu__del_caps(struct perf_pmu *pmu)
1532 {
1533 	struct perf_pmu_caps *caps, *tmp;
1534 
1535 	list_for_each_entry_safe(caps, tmp, &pmu->caps, list) {
1536 		list_del(&caps->list);
1537 		zfree(&caps->name);
1538 		zfree(&caps->value);
1539 		free(caps);
1540 	}
1541 }
1542 
1543 /*
1544  * Reading/parsing the given pmu capabilities, which should be located at:
1545  * /sys/bus/event_source/devices/<dev>/caps as sysfs group attributes.
1546  * Return the number of capabilities
1547  */
1548 int perf_pmu__caps_parse(struct perf_pmu *pmu)
1549 {
1550 	struct stat st;
1551 	char caps_path[PATH_MAX];
1552 	DIR *caps_dir;
1553 	struct dirent *evt_ent;
1554 	int caps_fd;
1555 
1556 	if (pmu->caps_initialized)
1557 		return pmu->nr_caps;
1558 
1559 	pmu->nr_caps = 0;
1560 
1561 	if (!perf_pmu__pathname_scnprintf(caps_path, sizeof(caps_path), pmu->name, "caps"))
1562 		return -1;
1563 
1564 	if (stat(caps_path, &st) < 0) {
1565 		pmu->caps_initialized = true;
1566 		return 0;	/* no error if caps does not exist */
1567 	}
1568 
1569 	caps_dir = opendir(caps_path);
1570 	if (!caps_dir)
1571 		return -EINVAL;
1572 
1573 	caps_fd = dirfd(caps_dir);
1574 
1575 	while ((evt_ent = readdir(caps_dir)) != NULL) {
1576 		char *name = evt_ent->d_name;
1577 		char value[128];
1578 		FILE *file;
1579 		int fd;
1580 
1581 		if (!strcmp(name, ".") || !strcmp(name, ".."))
1582 			continue;
1583 
1584 		fd = openat(caps_fd, name, O_RDONLY);
1585 		if (fd == -1)
1586 			continue;
1587 		file = fdopen(fd, "r");
1588 		if (!file) {
1589 			close(fd);
1590 			continue;
1591 		}
1592 
1593 		if (!fgets(value, sizeof(value), file) ||
1594 		    (perf_pmu__new_caps(&pmu->caps, name, value) < 0)) {
1595 			fclose(file);
1596 			continue;
1597 		}
1598 
1599 		pmu->nr_caps++;
1600 		fclose(file);
1601 	}
1602 
1603 	closedir(caps_dir);
1604 
1605 	pmu->caps_initialized = true;
1606 	return pmu->nr_caps;
1607 }
1608 
1609 void perf_pmu__warn_invalid_config(struct perf_pmu *pmu, __u64 config,
1610 				   const char *name)
1611 {
1612 	struct perf_pmu_format *format;
1613 	__u64 masks = 0, bits;
1614 	char buf[100];
1615 	unsigned int i;
1616 
1617 	list_for_each_entry(format, &pmu->format, list)	{
1618 		if (format->value != PERF_PMU_FORMAT_VALUE_CONFIG)
1619 			continue;
1620 
1621 		for_each_set_bit(i, format->bits, PERF_PMU_FORMAT_BITS)
1622 			masks |= 1ULL << i;
1623 	}
1624 
1625 	/*
1626 	 * Kernel doesn't export any valid format bits.
1627 	 */
1628 	if (masks == 0)
1629 		return;
1630 
1631 	bits = config & ~masks;
1632 	if (bits == 0)
1633 		return;
1634 
1635 	bitmap_scnprintf((unsigned long *)&bits, sizeof(bits) * 8, buf, sizeof(buf));
1636 
1637 	pr_warning("WARNING: event '%s' not valid (bits %s of config "
1638 		   "'%llx' not supported by kernel)!\n",
1639 		   name ?: "N/A", buf, config);
1640 }
1641 
1642 int perf_pmu__match(char *pattern, char *name, char *tok)
1643 {
1644 	if (!name)
1645 		return -1;
1646 
1647 	if (fnmatch(pattern, name, 0))
1648 		return -1;
1649 
1650 	if (tok && !perf_pmu__match_ignoring_suffix(name, tok))
1651 		return -1;
1652 
1653 	return 0;
1654 }
1655 
1656 double __weak perf_pmu__cpu_slots_per_cycle(void)
1657 {
1658 	return NAN;
1659 }
1660 
1661 int perf_pmu__event_source_devices_scnprintf(char *pathname, size_t size)
1662 {
1663 	const char *sysfs = sysfs__mountpoint();
1664 
1665 	if (!sysfs)
1666 		return 0;
1667 	return scnprintf(pathname, size, "%s/bus/event_source/devices/", sysfs);
1668 }
1669 
1670 int perf_pmu__event_source_devices_fd(void)
1671 {
1672 	char path[PATH_MAX];
1673 	const char *sysfs = sysfs__mountpoint();
1674 
1675 	if (!sysfs)
1676 		return -1;
1677 
1678 	scnprintf(path, sizeof(path), "%s/bus/event_source/devices/", sysfs);
1679 	return open(path, O_DIRECTORY);
1680 }
1681 
1682 /*
1683  * Fill 'buf' with the path to a file or folder in 'pmu_name' in
1684  * sysfs. For example if pmu_name = "cs_etm" and 'filename' = "format"
1685  * then pathname will be filled with
1686  * "/sys/bus/event_source/devices/cs_etm/format"
1687  *
1688  * Return 0 if the sysfs mountpoint couldn't be found or if no
1689  * characters were written.
1690  */
1691 int perf_pmu__pathname_scnprintf(char *buf, size_t size,
1692 				 const char *pmu_name, const char *filename)
1693 {
1694 	char base_path[PATH_MAX];
1695 
1696 	if (!perf_pmu__event_source_devices_scnprintf(base_path, sizeof(base_path)))
1697 		return 0;
1698 	return scnprintf(buf, size, "%s%s/%s", base_path, pmu_name, filename);
1699 }
1700 
1701 int perf_pmu__pathname_fd(int dirfd, const char *pmu_name, const char *filename, int flags)
1702 {
1703 	char path[PATH_MAX];
1704 
1705 	scnprintf(path, sizeof(path), "%s/%s", pmu_name, filename);
1706 	return openat(dirfd, path, flags);
1707 }
1708 
1709 void perf_pmu__delete(struct perf_pmu *pmu)
1710 {
1711 	perf_pmu__del_formats(&pmu->format);
1712 	perf_pmu__del_aliases(pmu);
1713 	perf_pmu__del_caps(pmu);
1714 
1715 	perf_cpu_map__put(pmu->cpus);
1716 
1717 	zfree(&pmu->default_config);
1718 	zfree(&pmu->name);
1719 	zfree(&pmu->alias_name);
1720 	free(pmu);
1721 }
1722