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