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