xref: /openbmc/linux/tools/perf/util/pmu.c (revision fca3aa16)
1 // SPDX-License-Identifier: GPL-2.0
2 #include <linux/list.h>
3 #include <linux/compiler.h>
4 #include <sys/types.h>
5 #include <errno.h>
6 #include <fcntl.h>
7 #include <sys/stat.h>
8 #include <unistd.h>
9 #include <stdio.h>
10 #include <stdbool.h>
11 #include <stdarg.h>
12 #include <dirent.h>
13 #include <api/fs/fs.h>
14 #include <locale.h>
15 #include <regex.h>
16 #include "util.h"
17 #include "pmu.h"
18 #include "parse-events.h"
19 #include "cpumap.h"
20 #include "header.h"
21 #include "pmu-events/pmu-events.h"
22 #include "cache.h"
23 #include "string2.h"
24 
25 struct perf_pmu_format {
26 	char *name;
27 	int value;
28 	DECLARE_BITMAP(bits, PERF_PMU_FORMAT_BITS);
29 	struct list_head list;
30 };
31 
32 #define EVENT_SOURCE_DEVICE_PATH "/bus/event_source/devices/"
33 
34 int perf_pmu_parse(struct list_head *list, char *name);
35 extern FILE *perf_pmu_in;
36 
37 static LIST_HEAD(pmus);
38 
39 /*
40  * Parse & process all the sysfs attributes located under
41  * the directory specified in 'dir' parameter.
42  */
43 int perf_pmu__format_parse(char *dir, struct list_head *head)
44 {
45 	struct dirent *evt_ent;
46 	DIR *format_dir;
47 	int ret = 0;
48 
49 	format_dir = opendir(dir);
50 	if (!format_dir)
51 		return -EINVAL;
52 
53 	while (!ret && (evt_ent = readdir(format_dir))) {
54 		char path[PATH_MAX];
55 		char *name = evt_ent->d_name;
56 		FILE *file;
57 
58 		if (!strcmp(name, ".") || !strcmp(name, ".."))
59 			continue;
60 
61 		snprintf(path, PATH_MAX, "%s/%s", dir, name);
62 
63 		ret = -EINVAL;
64 		file = fopen(path, "r");
65 		if (!file)
66 			break;
67 
68 		perf_pmu_in = file;
69 		ret = perf_pmu_parse(head, name);
70 		fclose(file);
71 	}
72 
73 	closedir(format_dir);
74 	return ret;
75 }
76 
77 /*
78  * Reading/parsing the default pmu format definition, which should be
79  * located at:
80  * /sys/bus/event_source/devices/<dev>/format as sysfs group attributes.
81  */
82 static int pmu_format(const char *name, struct list_head *format)
83 {
84 	struct stat st;
85 	char path[PATH_MAX];
86 	const char *sysfs = sysfs__mountpoint();
87 
88 	if (!sysfs)
89 		return -1;
90 
91 	snprintf(path, PATH_MAX,
92 		 "%s" EVENT_SOURCE_DEVICE_PATH "%s/format", sysfs, name);
93 
94 	if (stat(path, &st) < 0)
95 		return 0;	/* no error if format does not exist */
96 
97 	if (perf_pmu__format_parse(path, format))
98 		return -1;
99 
100 	return 0;
101 }
102 
103 static int convert_scale(const char *scale, char **end, double *sval)
104 {
105 	char *lc;
106 	int ret = 0;
107 
108 	/*
109 	 * save current locale
110 	 */
111 	lc = setlocale(LC_NUMERIC, NULL);
112 
113 	/*
114 	 * The lc string may be allocated in static storage,
115 	 * so get a dynamic copy to make it survive setlocale
116 	 * call below.
117 	 */
118 	lc = strdup(lc);
119 	if (!lc) {
120 		ret = -ENOMEM;
121 		goto out;
122 	}
123 
124 	/*
125 	 * force to C locale to ensure kernel
126 	 * scale string is converted correctly.
127 	 * kernel uses default C locale.
128 	 */
129 	setlocale(LC_NUMERIC, "C");
130 
131 	*sval = strtod(scale, end);
132 
133 out:
134 	/* restore locale */
135 	setlocale(LC_NUMERIC, lc);
136 	free(lc);
137 	return ret;
138 }
139 
140 static int perf_pmu__parse_scale(struct perf_pmu_alias *alias, char *dir, char *name)
141 {
142 	struct stat st;
143 	ssize_t sret;
144 	char scale[128];
145 	int fd, ret = -1;
146 	char path[PATH_MAX];
147 
148 	snprintf(path, PATH_MAX, "%s/%s.scale", dir, name);
149 
150 	fd = open(path, O_RDONLY);
151 	if (fd == -1)
152 		return -1;
153 
154 	if (fstat(fd, &st) < 0)
155 		goto error;
156 
157 	sret = read(fd, scale, sizeof(scale)-1);
158 	if (sret < 0)
159 		goto error;
160 
161 	if (scale[sret - 1] == '\n')
162 		scale[sret - 1] = '\0';
163 	else
164 		scale[sret] = '\0';
165 
166 	ret = convert_scale(scale, NULL, &alias->scale);
167 error:
168 	close(fd);
169 	return ret;
170 }
171 
172 static int perf_pmu__parse_unit(struct perf_pmu_alias *alias, char *dir, char *name)
173 {
174 	char path[PATH_MAX];
175 	ssize_t sret;
176 	int fd;
177 
178 	snprintf(path, PATH_MAX, "%s/%s.unit", dir, name);
179 
180 	fd = open(path, O_RDONLY);
181 	if (fd == -1)
182 		return -1;
183 
184 	sret = read(fd, alias->unit, UNIT_MAX_LEN);
185 	if (sret < 0)
186 		goto error;
187 
188 	close(fd);
189 
190 	if (alias->unit[sret - 1] == '\n')
191 		alias->unit[sret - 1] = '\0';
192 	else
193 		alias->unit[sret] = '\0';
194 
195 	return 0;
196 error:
197 	close(fd);
198 	alias->unit[0] = '\0';
199 	return -1;
200 }
201 
202 static int
203 perf_pmu__parse_per_pkg(struct perf_pmu_alias *alias, char *dir, char *name)
204 {
205 	char path[PATH_MAX];
206 	int fd;
207 
208 	snprintf(path, PATH_MAX, "%s/%s.per-pkg", dir, name);
209 
210 	fd = open(path, O_RDONLY);
211 	if (fd == -1)
212 		return -1;
213 
214 	close(fd);
215 
216 	alias->per_pkg = true;
217 	return 0;
218 }
219 
220 static int perf_pmu__parse_snapshot(struct perf_pmu_alias *alias,
221 				    char *dir, char *name)
222 {
223 	char path[PATH_MAX];
224 	int fd;
225 
226 	snprintf(path, PATH_MAX, "%s/%s.snapshot", dir, name);
227 
228 	fd = open(path, O_RDONLY);
229 	if (fd == -1)
230 		return -1;
231 
232 	alias->snapshot = true;
233 	close(fd);
234 	return 0;
235 }
236 
237 static int __perf_pmu__new_alias(struct list_head *list, char *dir, char *name,
238 				 char *desc, char *val,
239 				 char *long_desc, char *topic,
240 				 char *unit, char *perpkg,
241 				 char *metric_expr,
242 				 char *metric_name)
243 {
244 	struct perf_pmu_alias *alias;
245 	int ret;
246 	int num;
247 
248 	alias = malloc(sizeof(*alias));
249 	if (!alias)
250 		return -ENOMEM;
251 
252 	INIT_LIST_HEAD(&alias->terms);
253 	alias->scale = 1.0;
254 	alias->unit[0] = '\0';
255 	alias->per_pkg = false;
256 	alias->snapshot = false;
257 
258 	ret = parse_events_terms(&alias->terms, val);
259 	if (ret) {
260 		pr_err("Cannot parse alias %s: %d\n", val, ret);
261 		free(alias);
262 		return ret;
263 	}
264 
265 	alias->name = strdup(name);
266 	if (dir) {
267 		/*
268 		 * load unit name and scale if available
269 		 */
270 		perf_pmu__parse_unit(alias, dir, name);
271 		perf_pmu__parse_scale(alias, dir, name);
272 		perf_pmu__parse_per_pkg(alias, dir, name);
273 		perf_pmu__parse_snapshot(alias, dir, name);
274 	}
275 
276 	alias->metric_expr = metric_expr ? strdup(metric_expr) : NULL;
277 	alias->metric_name = metric_name ? strdup(metric_name): NULL;
278 	alias->desc = desc ? strdup(desc) : NULL;
279 	alias->long_desc = long_desc ? strdup(long_desc) :
280 				desc ? strdup(desc) : NULL;
281 	alias->topic = topic ? strdup(topic) : NULL;
282 	if (unit) {
283 		if (convert_scale(unit, &unit, &alias->scale) < 0)
284 			return -1;
285 		snprintf(alias->unit, sizeof(alias->unit), "%s", unit);
286 	}
287 	alias->per_pkg = perpkg && sscanf(perpkg, "%d", &num) == 1 && num == 1;
288 	alias->str = strdup(val);
289 
290 	list_add_tail(&alias->list, list);
291 
292 	return 0;
293 }
294 
295 static int perf_pmu__new_alias(struct list_head *list, char *dir, char *name, FILE *file)
296 {
297 	char buf[256];
298 	int ret;
299 
300 	ret = fread(buf, 1, sizeof(buf), file);
301 	if (ret == 0)
302 		return -EINVAL;
303 
304 	buf[ret] = 0;
305 
306 	return __perf_pmu__new_alias(list, dir, name, NULL, buf, NULL, NULL, NULL,
307 				     NULL, NULL, NULL);
308 }
309 
310 static inline bool pmu_alias_info_file(char *name)
311 {
312 	size_t len;
313 
314 	len = strlen(name);
315 	if (len > 5 && !strcmp(name + len - 5, ".unit"))
316 		return true;
317 	if (len > 6 && !strcmp(name + len - 6, ".scale"))
318 		return true;
319 	if (len > 8 && !strcmp(name + len - 8, ".per-pkg"))
320 		return true;
321 	if (len > 9 && !strcmp(name + len - 9, ".snapshot"))
322 		return true;
323 
324 	return false;
325 }
326 
327 /*
328  * Process all the sysfs attributes located under the directory
329  * specified in 'dir' parameter.
330  */
331 static int pmu_aliases_parse(char *dir, struct list_head *head)
332 {
333 	struct dirent *evt_ent;
334 	DIR *event_dir;
335 
336 	event_dir = opendir(dir);
337 	if (!event_dir)
338 		return -EINVAL;
339 
340 	while ((evt_ent = readdir(event_dir))) {
341 		char path[PATH_MAX];
342 		char *name = evt_ent->d_name;
343 		FILE *file;
344 
345 		if (!strcmp(name, ".") || !strcmp(name, ".."))
346 			continue;
347 
348 		/*
349 		 * skip info files parsed in perf_pmu__new_alias()
350 		 */
351 		if (pmu_alias_info_file(name))
352 			continue;
353 
354 		scnprintf(path, PATH_MAX, "%s/%s", dir, name);
355 
356 		file = fopen(path, "r");
357 		if (!file) {
358 			pr_debug("Cannot open %s\n", path);
359 			continue;
360 		}
361 
362 		if (perf_pmu__new_alias(head, dir, name, file) < 0)
363 			pr_debug("Cannot set up %s\n", name);
364 		fclose(file);
365 	}
366 
367 	closedir(event_dir);
368 	return 0;
369 }
370 
371 /*
372  * Reading the pmu event aliases definition, which should be located at:
373  * /sys/bus/event_source/devices/<dev>/events as sysfs group attributes.
374  */
375 static int pmu_aliases(const char *name, struct list_head *head)
376 {
377 	struct stat st;
378 	char path[PATH_MAX];
379 	const char *sysfs = sysfs__mountpoint();
380 
381 	if (!sysfs)
382 		return -1;
383 
384 	snprintf(path, PATH_MAX,
385 		 "%s/bus/event_source/devices/%s/events", sysfs, name);
386 
387 	if (stat(path, &st) < 0)
388 		return 0;	 /* no error if 'events' does not exist */
389 
390 	if (pmu_aliases_parse(path, head))
391 		return -1;
392 
393 	return 0;
394 }
395 
396 static int pmu_alias_terms(struct perf_pmu_alias *alias,
397 			   struct list_head *terms)
398 {
399 	struct parse_events_term *term, *cloned;
400 	LIST_HEAD(list);
401 	int ret;
402 
403 	list_for_each_entry(term, &alias->terms, list) {
404 		ret = parse_events_term__clone(&cloned, term);
405 		if (ret) {
406 			parse_events_terms__purge(&list);
407 			return ret;
408 		}
409 		/*
410 		 * Weak terms don't override command line options,
411 		 * which we don't want for implicit terms in aliases.
412 		 */
413 		cloned->weak = true;
414 		list_add_tail(&cloned->list, &list);
415 	}
416 	list_splice(&list, terms);
417 	return 0;
418 }
419 
420 /*
421  * Reading/parsing the default pmu type value, which should be
422  * located at:
423  * /sys/bus/event_source/devices/<dev>/type as sysfs attribute.
424  */
425 static int pmu_type(const char *name, __u32 *type)
426 {
427 	struct stat st;
428 	char path[PATH_MAX];
429 	FILE *file;
430 	int ret = 0;
431 	const char *sysfs = sysfs__mountpoint();
432 
433 	if (!sysfs)
434 		return -1;
435 
436 	snprintf(path, PATH_MAX,
437 		 "%s" EVENT_SOURCE_DEVICE_PATH "%s/type", sysfs, name);
438 
439 	if (stat(path, &st) < 0)
440 		return -1;
441 
442 	file = fopen(path, "r");
443 	if (!file)
444 		return -EINVAL;
445 
446 	if (1 != fscanf(file, "%u", type))
447 		ret = -1;
448 
449 	fclose(file);
450 	return ret;
451 }
452 
453 /* Add all pmus in sysfs to pmu list: */
454 static void pmu_read_sysfs(void)
455 {
456 	char path[PATH_MAX];
457 	DIR *dir;
458 	struct dirent *dent;
459 	const char *sysfs = sysfs__mountpoint();
460 
461 	if (!sysfs)
462 		return;
463 
464 	snprintf(path, PATH_MAX,
465 		 "%s" EVENT_SOURCE_DEVICE_PATH, sysfs);
466 
467 	dir = opendir(path);
468 	if (!dir)
469 		return;
470 
471 	while ((dent = readdir(dir))) {
472 		if (!strcmp(dent->d_name, ".") || !strcmp(dent->d_name, ".."))
473 			continue;
474 		/* add to static LIST_HEAD(pmus): */
475 		perf_pmu__find(dent->d_name);
476 	}
477 
478 	closedir(dir);
479 }
480 
481 static struct cpu_map *__pmu_cpumask(const char *path)
482 {
483 	FILE *file;
484 	struct cpu_map *cpus;
485 
486 	file = fopen(path, "r");
487 	if (!file)
488 		return NULL;
489 
490 	cpus = cpu_map__read(file);
491 	fclose(file);
492 	return cpus;
493 }
494 
495 /*
496  * Uncore PMUs have a "cpumask" file under sysfs. CPU PMUs (e.g. on arm/arm64)
497  * may have a "cpus" file.
498  */
499 #define CPUS_TEMPLATE_UNCORE	"%s/bus/event_source/devices/%s/cpumask"
500 #define CPUS_TEMPLATE_CPU	"%s/bus/event_source/devices/%s/cpus"
501 
502 static struct cpu_map *pmu_cpumask(const char *name)
503 {
504 	char path[PATH_MAX];
505 	struct cpu_map *cpus;
506 	const char *sysfs = sysfs__mountpoint();
507 	const char *templates[] = {
508 		CPUS_TEMPLATE_UNCORE,
509 		CPUS_TEMPLATE_CPU,
510 		NULL
511 	};
512 	const char **template;
513 
514 	if (!sysfs)
515 		return NULL;
516 
517 	for (template = templates; *template; template++) {
518 		snprintf(path, PATH_MAX, *template, sysfs, name);
519 		cpus = __pmu_cpumask(path);
520 		if (cpus)
521 			return cpus;
522 	}
523 
524 	return NULL;
525 }
526 
527 static bool pmu_is_uncore(const char *name)
528 {
529 	char path[PATH_MAX];
530 	struct cpu_map *cpus;
531 	const char *sysfs = sysfs__mountpoint();
532 
533 	snprintf(path, PATH_MAX, CPUS_TEMPLATE_UNCORE, sysfs, name);
534 	cpus = __pmu_cpumask(path);
535 	cpu_map__put(cpus);
536 
537 	return !!cpus;
538 }
539 
540 /*
541  *  PMU CORE devices have different name other than cpu in sysfs on some
542  *  platforms. looking for possible sysfs files to identify as core device.
543  */
544 static int is_pmu_core(const char *name)
545 {
546 	struct stat st;
547 	char path[PATH_MAX];
548 	const char *sysfs = sysfs__mountpoint();
549 
550 	if (!sysfs)
551 		return 0;
552 
553 	/* Look for cpu sysfs (x86 and others) */
554 	scnprintf(path, PATH_MAX, "%s/bus/event_source/devices/cpu", sysfs);
555 	if ((stat(path, &st) == 0) &&
556 			(strncmp(name, "cpu", strlen("cpu")) == 0))
557 		return 1;
558 
559 	/* Look for cpu sysfs (specific to arm) */
560 	scnprintf(path, PATH_MAX, "%s/bus/event_source/devices/%s/cpus",
561 				sysfs, name);
562 	if (stat(path, &st) == 0)
563 		return 1;
564 
565 	/* Look for cpu sysfs (specific to s390) */
566 	scnprintf(path, PATH_MAX, "%s/bus/event_source/devices/%s",
567 		  sysfs, name);
568 	if (stat(path, &st) == 0 && !strncmp(name, "cpum_", 5))
569 		return 1;
570 
571 	return 0;
572 }
573 
574 /*
575  * Return the CPU id as a raw string.
576  *
577  * Each architecture should provide a more precise id string that
578  * can be use to match the architecture's "mapfile".
579  */
580 char * __weak get_cpuid_str(struct perf_pmu *pmu __maybe_unused)
581 {
582 	return NULL;
583 }
584 
585 /* Return zero when the cpuid from the mapfile.csv matches the
586  * cpuid string generated on this platform.
587  * Otherwise return non-zero.
588  */
589 int __weak strcmp_cpuid_str(const char *mapcpuid, const char *cpuid)
590 {
591 	regex_t re;
592 	regmatch_t pmatch[1];
593 	int match;
594 
595 	if (regcomp(&re, mapcpuid, REG_EXTENDED) != 0) {
596 		/* Warn unable to generate match particular string. */
597 		pr_info("Invalid regular expression %s\n", mapcpuid);
598 		return 1;
599 	}
600 
601 	match = !regexec(&re, cpuid, 1, pmatch, 0);
602 	regfree(&re);
603 	if (match) {
604 		size_t match_len = (pmatch[0].rm_eo - pmatch[0].rm_so);
605 
606 		/* Verify the entire string matched. */
607 		if (match_len == strlen(cpuid))
608 			return 0;
609 	}
610 	return 1;
611 }
612 
613 static char *perf_pmu__getcpuid(struct perf_pmu *pmu)
614 {
615 	char *cpuid;
616 	static bool printed;
617 
618 	cpuid = getenv("PERF_CPUID");
619 	if (cpuid)
620 		cpuid = strdup(cpuid);
621 	if (!cpuid)
622 		cpuid = get_cpuid_str(pmu);
623 	if (!cpuid)
624 		return NULL;
625 
626 	if (!printed) {
627 		pr_debug("Using CPUID %s\n", cpuid);
628 		printed = true;
629 	}
630 	return cpuid;
631 }
632 
633 struct pmu_events_map *perf_pmu__find_map(struct perf_pmu *pmu)
634 {
635 	struct pmu_events_map *map;
636 	char *cpuid = perf_pmu__getcpuid(pmu);
637 	int i;
638 
639 	/* on some platforms which uses cpus map, cpuid can be NULL for
640 	 * PMUs other than CORE PMUs.
641 	 */
642 	if (!cpuid)
643 		return NULL;
644 
645 	i = 0;
646 	for (;;) {
647 		map = &pmu_events_map[i++];
648 		if (!map->table) {
649 			map = NULL;
650 			break;
651 		}
652 
653 		if (!strcmp_cpuid_str(map->cpuid, cpuid))
654 			break;
655 	}
656 	free(cpuid);
657 	return map;
658 }
659 
660 /*
661  * From the pmu_events_map, find the table of PMU events that corresponds
662  * to the current running CPU. Then, add all PMU events from that table
663  * as aliases.
664  */
665 static void pmu_add_cpu_aliases(struct list_head *head, struct perf_pmu *pmu)
666 {
667 	int i;
668 	struct pmu_events_map *map;
669 	struct pmu_event *pe;
670 	const char *name = pmu->name;
671 
672 	map = perf_pmu__find_map(pmu);
673 	if (!map)
674 		return;
675 
676 	/*
677 	 * Found a matching PMU events table. Create aliases
678 	 */
679 	i = 0;
680 	while (1) {
681 
682 		pe = &map->table[i++];
683 		if (!pe->name) {
684 			if (pe->metric_group || pe->metric_name)
685 				continue;
686 			break;
687 		}
688 
689 		if (!is_pmu_core(name)) {
690 			/* check for uncore devices */
691 			if (pe->pmu == NULL)
692 				continue;
693 			if (strncmp(pe->pmu, name, strlen(pe->pmu)))
694 				continue;
695 		}
696 
697 		/* need type casts to override 'const' */
698 		__perf_pmu__new_alias(head, NULL, (char *)pe->name,
699 				(char *)pe->desc, (char *)pe->event,
700 				(char *)pe->long_desc, (char *)pe->topic,
701 				(char *)pe->unit, (char *)pe->perpkg,
702 				(char *)pe->metric_expr,
703 				(char *)pe->metric_name);
704 	}
705 }
706 
707 struct perf_event_attr * __weak
708 perf_pmu__get_default_config(struct perf_pmu *pmu __maybe_unused)
709 {
710 	return NULL;
711 }
712 
713 static struct perf_pmu *pmu_lookup(const char *name)
714 {
715 	struct perf_pmu *pmu;
716 	LIST_HEAD(format);
717 	LIST_HEAD(aliases);
718 	__u32 type;
719 
720 	/*
721 	 * The pmu data we store & need consists of the pmu
722 	 * type value and format definitions. Load both right
723 	 * now.
724 	 */
725 	if (pmu_format(name, &format))
726 		return NULL;
727 
728 	/*
729 	 * Check the type first to avoid unnecessary work.
730 	 */
731 	if (pmu_type(name, &type))
732 		return NULL;
733 
734 	if (pmu_aliases(name, &aliases))
735 		return NULL;
736 
737 	pmu = zalloc(sizeof(*pmu));
738 	if (!pmu)
739 		return NULL;
740 
741 	pmu->cpus = pmu_cpumask(name);
742 	pmu->name = strdup(name);
743 	pmu->type = type;
744 	pmu->is_uncore = pmu_is_uncore(name);
745 	pmu_add_cpu_aliases(&aliases, pmu);
746 
747 	INIT_LIST_HEAD(&pmu->format);
748 	INIT_LIST_HEAD(&pmu->aliases);
749 	list_splice(&format, &pmu->format);
750 	list_splice(&aliases, &pmu->aliases);
751 	list_add_tail(&pmu->list, &pmus);
752 
753 	pmu->default_config = perf_pmu__get_default_config(pmu);
754 
755 	return pmu;
756 }
757 
758 static struct perf_pmu *pmu_find(const char *name)
759 {
760 	struct perf_pmu *pmu;
761 
762 	list_for_each_entry(pmu, &pmus, list)
763 		if (!strcmp(pmu->name, name))
764 			return pmu;
765 
766 	return NULL;
767 }
768 
769 struct perf_pmu *perf_pmu__scan(struct perf_pmu *pmu)
770 {
771 	/*
772 	 * pmu iterator: If pmu is NULL, we start at the begin,
773 	 * otherwise return the next pmu. Returns NULL on end.
774 	 */
775 	if (!pmu) {
776 		pmu_read_sysfs();
777 		pmu = list_prepare_entry(pmu, &pmus, list);
778 	}
779 	list_for_each_entry_continue(pmu, &pmus, list)
780 		return pmu;
781 	return NULL;
782 }
783 
784 struct perf_pmu *perf_pmu__find(const char *name)
785 {
786 	struct perf_pmu *pmu;
787 
788 	/*
789 	 * Once PMU is loaded it stays in the list,
790 	 * so we keep us from multiple reading/parsing
791 	 * the pmu format definitions.
792 	 */
793 	pmu = pmu_find(name);
794 	if (pmu)
795 		return pmu;
796 
797 	return pmu_lookup(name);
798 }
799 
800 static struct perf_pmu_format *
801 pmu_find_format(struct list_head *formats, const char *name)
802 {
803 	struct perf_pmu_format *format;
804 
805 	list_for_each_entry(format, formats, list)
806 		if (!strcmp(format->name, name))
807 			return format;
808 
809 	return NULL;
810 }
811 
812 __u64 perf_pmu__format_bits(struct list_head *formats, const char *name)
813 {
814 	struct perf_pmu_format *format = pmu_find_format(formats, name);
815 	__u64 bits = 0;
816 	int fbit;
817 
818 	if (!format)
819 		return 0;
820 
821 	for_each_set_bit(fbit, format->bits, PERF_PMU_FORMAT_BITS)
822 		bits |= 1ULL << fbit;
823 
824 	return bits;
825 }
826 
827 /*
828  * Sets value based on the format definition (format parameter)
829  * and unformated value (value parameter).
830  */
831 static void pmu_format_value(unsigned long *format, __u64 value, __u64 *v,
832 			     bool zero)
833 {
834 	unsigned long fbit, vbit;
835 
836 	for (fbit = 0, vbit = 0; fbit < PERF_PMU_FORMAT_BITS; fbit++) {
837 
838 		if (!test_bit(fbit, format))
839 			continue;
840 
841 		if (value & (1llu << vbit++))
842 			*v |= (1llu << fbit);
843 		else if (zero)
844 			*v &= ~(1llu << fbit);
845 	}
846 }
847 
848 static __u64 pmu_format_max_value(const unsigned long *format)
849 {
850 	__u64 w = 0;
851 	int fbit;
852 
853 	for_each_set_bit(fbit, format, PERF_PMU_FORMAT_BITS)
854 		w |= (1ULL << fbit);
855 
856 	return w;
857 }
858 
859 /*
860  * Term is a string term, and might be a param-term. Try to look up it's value
861  * in the remaining terms.
862  * - We have a term like "base-or-format-term=param-term",
863  * - We need to find the value supplied for "param-term" (with param-term named
864  *   in a config string) later on in the term list.
865  */
866 static int pmu_resolve_param_term(struct parse_events_term *term,
867 				  struct list_head *head_terms,
868 				  __u64 *value)
869 {
870 	struct parse_events_term *t;
871 
872 	list_for_each_entry(t, head_terms, list) {
873 		if (t->type_val == PARSE_EVENTS__TERM_TYPE_NUM) {
874 			if (!strcmp(t->config, term->config)) {
875 				t->used = true;
876 				*value = t->val.num;
877 				return 0;
878 			}
879 		}
880 	}
881 
882 	if (verbose > 0)
883 		printf("Required parameter '%s' not specified\n", term->config);
884 
885 	return -1;
886 }
887 
888 static char *pmu_formats_string(struct list_head *formats)
889 {
890 	struct perf_pmu_format *format;
891 	char *str = NULL;
892 	struct strbuf buf = STRBUF_INIT;
893 	unsigned i = 0;
894 
895 	if (!formats)
896 		return NULL;
897 
898 	/* sysfs exported terms */
899 	list_for_each_entry(format, formats, list)
900 		if (strbuf_addf(&buf, i++ ? ",%s" : "%s", format->name) < 0)
901 			goto error;
902 
903 	str = strbuf_detach(&buf, NULL);
904 error:
905 	strbuf_release(&buf);
906 
907 	return str;
908 }
909 
910 /*
911  * Setup one of config[12] attr members based on the
912  * user input data - term parameter.
913  */
914 static int pmu_config_term(struct list_head *formats,
915 			   struct perf_event_attr *attr,
916 			   struct parse_events_term *term,
917 			   struct list_head *head_terms,
918 			   bool zero, struct parse_events_error *err)
919 {
920 	struct perf_pmu_format *format;
921 	__u64 *vp;
922 	__u64 val, max_val;
923 
924 	/*
925 	 * If this is a parameter we've already used for parameterized-eval,
926 	 * skip it in normal eval.
927 	 */
928 	if (term->used)
929 		return 0;
930 
931 	/*
932 	 * Hardcoded terms should be already in, so nothing
933 	 * to be done for them.
934 	 */
935 	if (parse_events__is_hardcoded_term(term))
936 		return 0;
937 
938 	format = pmu_find_format(formats, term->config);
939 	if (!format) {
940 		if (verbose > 0)
941 			printf("Invalid event/parameter '%s'\n", term->config);
942 		if (err) {
943 			char *pmu_term = pmu_formats_string(formats);
944 
945 			err->idx  = term->err_term;
946 			err->str  = strdup("unknown term");
947 			err->help = parse_events_formats_error_string(pmu_term);
948 			free(pmu_term);
949 		}
950 		return -EINVAL;
951 	}
952 
953 	switch (format->value) {
954 	case PERF_PMU_FORMAT_VALUE_CONFIG:
955 		vp = &attr->config;
956 		break;
957 	case PERF_PMU_FORMAT_VALUE_CONFIG1:
958 		vp = &attr->config1;
959 		break;
960 	case PERF_PMU_FORMAT_VALUE_CONFIG2:
961 		vp = &attr->config2;
962 		break;
963 	default:
964 		return -EINVAL;
965 	}
966 
967 	/*
968 	 * Either directly use a numeric term, or try to translate string terms
969 	 * using event parameters.
970 	 */
971 	if (term->type_val == PARSE_EVENTS__TERM_TYPE_NUM) {
972 		if (term->no_value &&
973 		    bitmap_weight(format->bits, PERF_PMU_FORMAT_BITS) > 1) {
974 			if (err) {
975 				err->idx = term->err_val;
976 				err->str = strdup("no value assigned for term");
977 			}
978 			return -EINVAL;
979 		}
980 
981 		val = term->val.num;
982 	} else if (term->type_val == PARSE_EVENTS__TERM_TYPE_STR) {
983 		if (strcmp(term->val.str, "?")) {
984 			if (verbose > 0) {
985 				pr_info("Invalid sysfs entry %s=%s\n",
986 						term->config, term->val.str);
987 			}
988 			if (err) {
989 				err->idx = term->err_val;
990 				err->str = strdup("expected numeric value");
991 			}
992 			return -EINVAL;
993 		}
994 
995 		if (pmu_resolve_param_term(term, head_terms, &val))
996 			return -EINVAL;
997 	} else
998 		return -EINVAL;
999 
1000 	max_val = pmu_format_max_value(format->bits);
1001 	if (val > max_val) {
1002 		if (err) {
1003 			err->idx = term->err_val;
1004 			if (asprintf(&err->str,
1005 				     "value too big for format, maximum is %llu",
1006 				     (unsigned long long)max_val) < 0)
1007 				err->str = strdup("value too big for format");
1008 			return -EINVAL;
1009 		}
1010 		/*
1011 		 * Assume we don't care if !err, in which case the value will be
1012 		 * silently truncated.
1013 		 */
1014 	}
1015 
1016 	pmu_format_value(format->bits, val, vp, zero);
1017 	return 0;
1018 }
1019 
1020 int perf_pmu__config_terms(struct list_head *formats,
1021 			   struct perf_event_attr *attr,
1022 			   struct list_head *head_terms,
1023 			   bool zero, struct parse_events_error *err)
1024 {
1025 	struct parse_events_term *term;
1026 
1027 	list_for_each_entry(term, head_terms, list) {
1028 		if (pmu_config_term(formats, attr, term, head_terms,
1029 				    zero, err))
1030 			return -EINVAL;
1031 	}
1032 
1033 	return 0;
1034 }
1035 
1036 /*
1037  * Configures event's 'attr' parameter based on the:
1038  * 1) users input - specified in terms parameter
1039  * 2) pmu format definitions - specified by pmu parameter
1040  */
1041 int perf_pmu__config(struct perf_pmu *pmu, struct perf_event_attr *attr,
1042 		     struct list_head *head_terms,
1043 		     struct parse_events_error *err)
1044 {
1045 	bool zero = !!pmu->default_config;
1046 
1047 	attr->type = pmu->type;
1048 	return perf_pmu__config_terms(&pmu->format, attr, head_terms,
1049 				      zero, err);
1050 }
1051 
1052 static struct perf_pmu_alias *pmu_find_alias(struct perf_pmu *pmu,
1053 					     struct parse_events_term *term)
1054 {
1055 	struct perf_pmu_alias *alias;
1056 	char *name;
1057 
1058 	if (parse_events__is_hardcoded_term(term))
1059 		return NULL;
1060 
1061 	if (term->type_val == PARSE_EVENTS__TERM_TYPE_NUM) {
1062 		if (term->val.num != 1)
1063 			return NULL;
1064 		if (pmu_find_format(&pmu->format, term->config))
1065 			return NULL;
1066 		name = term->config;
1067 	} else if (term->type_val == PARSE_EVENTS__TERM_TYPE_STR) {
1068 		if (strcasecmp(term->config, "event"))
1069 			return NULL;
1070 		name = term->val.str;
1071 	} else {
1072 		return NULL;
1073 	}
1074 
1075 	list_for_each_entry(alias, &pmu->aliases, list) {
1076 		if (!strcasecmp(alias->name, name))
1077 			return alias;
1078 	}
1079 	return NULL;
1080 }
1081 
1082 
1083 static int check_info_data(struct perf_pmu_alias *alias,
1084 			   struct perf_pmu_info *info)
1085 {
1086 	/*
1087 	 * Only one term in event definition can
1088 	 * define unit, scale and snapshot, fail
1089 	 * if there's more than one.
1090 	 */
1091 	if ((info->unit && alias->unit[0]) ||
1092 	    (info->scale && alias->scale) ||
1093 	    (info->snapshot && alias->snapshot))
1094 		return -EINVAL;
1095 
1096 	if (alias->unit[0])
1097 		info->unit = alias->unit;
1098 
1099 	if (alias->scale)
1100 		info->scale = alias->scale;
1101 
1102 	if (alias->snapshot)
1103 		info->snapshot = alias->snapshot;
1104 
1105 	return 0;
1106 }
1107 
1108 /*
1109  * Find alias in the terms list and replace it with the terms
1110  * defined for the alias
1111  */
1112 int perf_pmu__check_alias(struct perf_pmu *pmu, struct list_head *head_terms,
1113 			  struct perf_pmu_info *info)
1114 {
1115 	struct parse_events_term *term, *h;
1116 	struct perf_pmu_alias *alias;
1117 	int ret;
1118 
1119 	info->per_pkg = false;
1120 
1121 	/*
1122 	 * Mark unit and scale as not set
1123 	 * (different from default values, see below)
1124 	 */
1125 	info->unit     = NULL;
1126 	info->scale    = 0.0;
1127 	info->snapshot = false;
1128 	info->metric_expr = NULL;
1129 	info->metric_name = NULL;
1130 
1131 	list_for_each_entry_safe(term, h, head_terms, list) {
1132 		alias = pmu_find_alias(pmu, term);
1133 		if (!alias)
1134 			continue;
1135 		ret = pmu_alias_terms(alias, &term->list);
1136 		if (ret)
1137 			return ret;
1138 
1139 		ret = check_info_data(alias, info);
1140 		if (ret)
1141 			return ret;
1142 
1143 		if (alias->per_pkg)
1144 			info->per_pkg = true;
1145 		info->metric_expr = alias->metric_expr;
1146 		info->metric_name = alias->metric_name;
1147 
1148 		list_del(&term->list);
1149 		free(term);
1150 	}
1151 
1152 	/*
1153 	 * if no unit or scale foundin aliases, then
1154 	 * set defaults as for evsel
1155 	 * unit cannot left to NULL
1156 	 */
1157 	if (info->unit == NULL)
1158 		info->unit   = "";
1159 
1160 	if (info->scale == 0.0)
1161 		info->scale  = 1.0;
1162 
1163 	return 0;
1164 }
1165 
1166 int perf_pmu__new_format(struct list_head *list, char *name,
1167 			 int config, unsigned long *bits)
1168 {
1169 	struct perf_pmu_format *format;
1170 
1171 	format = zalloc(sizeof(*format));
1172 	if (!format)
1173 		return -ENOMEM;
1174 
1175 	format->name = strdup(name);
1176 	format->value = config;
1177 	memcpy(format->bits, bits, sizeof(format->bits));
1178 
1179 	list_add_tail(&format->list, list);
1180 	return 0;
1181 }
1182 
1183 void perf_pmu__set_format(unsigned long *bits, long from, long to)
1184 {
1185 	long b;
1186 
1187 	if (!to)
1188 		to = from;
1189 
1190 	memset(bits, 0, BITS_TO_BYTES(PERF_PMU_FORMAT_BITS));
1191 	for (b = from; b <= to; b++)
1192 		set_bit(b, bits);
1193 }
1194 
1195 static int sub_non_neg(int a, int b)
1196 {
1197 	if (b > a)
1198 		return 0;
1199 	return a - b;
1200 }
1201 
1202 static char *format_alias(char *buf, int len, struct perf_pmu *pmu,
1203 			  struct perf_pmu_alias *alias)
1204 {
1205 	struct parse_events_term *term;
1206 	int used = snprintf(buf, len, "%s/%s", pmu->name, alias->name);
1207 
1208 	list_for_each_entry(term, &alias->terms, list) {
1209 		if (term->type_val == PARSE_EVENTS__TERM_TYPE_STR)
1210 			used += snprintf(buf + used, sub_non_neg(len, used),
1211 					",%s=%s", term->config,
1212 					term->val.str);
1213 	}
1214 
1215 	if (sub_non_neg(len, used) > 0) {
1216 		buf[used] = '/';
1217 		used++;
1218 	}
1219 	if (sub_non_neg(len, used) > 0) {
1220 		buf[used] = '\0';
1221 		used++;
1222 	} else
1223 		buf[len - 1] = '\0';
1224 
1225 	return buf;
1226 }
1227 
1228 static char *format_alias_or(char *buf, int len, struct perf_pmu *pmu,
1229 			     struct perf_pmu_alias *alias)
1230 {
1231 	snprintf(buf, len, "%s OR %s/%s/", alias->name, pmu->name, alias->name);
1232 	return buf;
1233 }
1234 
1235 struct sevent {
1236 	char *name;
1237 	char *desc;
1238 	char *topic;
1239 	char *str;
1240 	char *pmu;
1241 	char *metric_expr;
1242 	char *metric_name;
1243 };
1244 
1245 static int cmp_sevent(const void *a, const void *b)
1246 {
1247 	const struct sevent *as = a;
1248 	const struct sevent *bs = b;
1249 
1250 	/* Put extra events last */
1251 	if (!!as->desc != !!bs->desc)
1252 		return !!as->desc - !!bs->desc;
1253 	if (as->topic && bs->topic) {
1254 		int n = strcmp(as->topic, bs->topic);
1255 
1256 		if (n)
1257 			return n;
1258 	}
1259 	return strcmp(as->name, bs->name);
1260 }
1261 
1262 static void wordwrap(char *s, int start, int max, int corr)
1263 {
1264 	int column = start;
1265 	int n;
1266 
1267 	while (*s) {
1268 		int wlen = strcspn(s, " \t");
1269 
1270 		if (column + wlen >= max && column > start) {
1271 			printf("\n%*s", start, "");
1272 			column = start + corr;
1273 		}
1274 		n = printf("%s%.*s", column > start ? " " : "", wlen, s);
1275 		if (n <= 0)
1276 			break;
1277 		s += wlen;
1278 		column += n;
1279 		s = ltrim(s);
1280 	}
1281 }
1282 
1283 void print_pmu_events(const char *event_glob, bool name_only, bool quiet_flag,
1284 			bool long_desc, bool details_flag)
1285 {
1286 	struct perf_pmu *pmu;
1287 	struct perf_pmu_alias *alias;
1288 	char buf[1024];
1289 	int printed = 0;
1290 	int len, j;
1291 	struct sevent *aliases;
1292 	int numdesc = 0;
1293 	int columns = pager_get_columns();
1294 	char *topic = NULL;
1295 
1296 	pmu = NULL;
1297 	len = 0;
1298 	while ((pmu = perf_pmu__scan(pmu)) != NULL) {
1299 		list_for_each_entry(alias, &pmu->aliases, list)
1300 			len++;
1301 		if (pmu->selectable)
1302 			len++;
1303 	}
1304 	aliases = zalloc(sizeof(struct sevent) * len);
1305 	if (!aliases)
1306 		goto out_enomem;
1307 	pmu = NULL;
1308 	j = 0;
1309 	while ((pmu = perf_pmu__scan(pmu)) != NULL) {
1310 		list_for_each_entry(alias, &pmu->aliases, list) {
1311 			char *name = alias->desc ? alias->name :
1312 				format_alias(buf, sizeof(buf), pmu, alias);
1313 			bool is_cpu = !strcmp(pmu->name, "cpu");
1314 
1315 			if (event_glob != NULL &&
1316 			    !(strglobmatch_nocase(name, event_glob) ||
1317 			      (!is_cpu && strglobmatch_nocase(alias->name,
1318 						       event_glob)) ||
1319 			      (alias->topic &&
1320 			       strglobmatch_nocase(alias->topic, event_glob))))
1321 				continue;
1322 
1323 			if (is_cpu && !name_only && !alias->desc)
1324 				name = format_alias_or(buf, sizeof(buf), pmu, alias);
1325 
1326 			aliases[j].name = name;
1327 			if (is_cpu && !name_only && !alias->desc)
1328 				aliases[j].name = format_alias_or(buf,
1329 								  sizeof(buf),
1330 								  pmu, alias);
1331 			aliases[j].name = strdup(aliases[j].name);
1332 			if (!aliases[j].name)
1333 				goto out_enomem;
1334 
1335 			aliases[j].desc = long_desc ? alias->long_desc :
1336 						alias->desc;
1337 			aliases[j].topic = alias->topic;
1338 			aliases[j].str = alias->str;
1339 			aliases[j].pmu = pmu->name;
1340 			aliases[j].metric_expr = alias->metric_expr;
1341 			aliases[j].metric_name = alias->metric_name;
1342 			j++;
1343 		}
1344 		if (pmu->selectable &&
1345 		    (event_glob == NULL || strglobmatch(pmu->name, event_glob))) {
1346 			char *s;
1347 			if (asprintf(&s, "%s//", pmu->name) < 0)
1348 				goto out_enomem;
1349 			aliases[j].name = s;
1350 			j++;
1351 		}
1352 	}
1353 	len = j;
1354 	qsort(aliases, len, sizeof(struct sevent), cmp_sevent);
1355 	for (j = 0; j < len; j++) {
1356 		/* Skip duplicates */
1357 		if (j > 0 && !strcmp(aliases[j].name, aliases[j - 1].name))
1358 			continue;
1359 		if (name_only) {
1360 			printf("%s ", aliases[j].name);
1361 			continue;
1362 		}
1363 		if (aliases[j].desc && !quiet_flag) {
1364 			if (numdesc++ == 0)
1365 				printf("\n");
1366 			if (aliases[j].topic && (!topic ||
1367 					strcmp(topic, aliases[j].topic))) {
1368 				printf("%s%s:\n", topic ? "\n" : "",
1369 						aliases[j].topic);
1370 				topic = aliases[j].topic;
1371 			}
1372 			printf("  %-50s\n", aliases[j].name);
1373 			printf("%*s", 8, "[");
1374 			wordwrap(aliases[j].desc, 8, columns, 0);
1375 			printf("]\n");
1376 			if (details_flag) {
1377 				printf("%*s%s/%s/ ", 8, "", aliases[j].pmu, aliases[j].str);
1378 				if (aliases[j].metric_name)
1379 					printf(" MetricName: %s", aliases[j].metric_name);
1380 				if (aliases[j].metric_expr)
1381 					printf(" MetricExpr: %s", aliases[j].metric_expr);
1382 				putchar('\n');
1383 			}
1384 		} else
1385 			printf("  %-50s [Kernel PMU event]\n", aliases[j].name);
1386 		printed++;
1387 	}
1388 	if (printed && pager_in_use())
1389 		printf("\n");
1390 out_free:
1391 	for (j = 0; j < len; j++)
1392 		zfree(&aliases[j].name);
1393 	zfree(&aliases);
1394 	return;
1395 
1396 out_enomem:
1397 	printf("FATAL: not enough memory to print PMU events\n");
1398 	if (aliases)
1399 		goto out_free;
1400 }
1401 
1402 bool pmu_have_event(const char *pname, const char *name)
1403 {
1404 	struct perf_pmu *pmu;
1405 	struct perf_pmu_alias *alias;
1406 
1407 	pmu = NULL;
1408 	while ((pmu = perf_pmu__scan(pmu)) != NULL) {
1409 		if (strcmp(pname, pmu->name))
1410 			continue;
1411 		list_for_each_entry(alias, &pmu->aliases, list)
1412 			if (!strcmp(alias->name, name))
1413 				return true;
1414 	}
1415 	return false;
1416 }
1417 
1418 static FILE *perf_pmu__open_file(struct perf_pmu *pmu, const char *name)
1419 {
1420 	struct stat st;
1421 	char path[PATH_MAX];
1422 	const char *sysfs;
1423 
1424 	sysfs = sysfs__mountpoint();
1425 	if (!sysfs)
1426 		return NULL;
1427 
1428 	snprintf(path, PATH_MAX,
1429 		 "%s" EVENT_SOURCE_DEVICE_PATH "%s/%s", sysfs, pmu->name, name);
1430 
1431 	if (stat(path, &st) < 0)
1432 		return NULL;
1433 
1434 	return fopen(path, "r");
1435 }
1436 
1437 int perf_pmu__scan_file(struct perf_pmu *pmu, const char *name, const char *fmt,
1438 			...)
1439 {
1440 	va_list args;
1441 	FILE *file;
1442 	int ret = EOF;
1443 
1444 	va_start(args, fmt);
1445 	file = perf_pmu__open_file(pmu, name);
1446 	if (file) {
1447 		ret = vfscanf(file, fmt, args);
1448 		fclose(file);
1449 	}
1450 	va_end(args);
1451 	return ret;
1452 }
1453