• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 <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  */
perf_pmu__format_parse(char * dir,struct list_head * head)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  */
pmu_format(const char * name,struct list_head * format)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 
convert_scale(const char * scale,char ** end,double * sval)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 
perf_pmu__parse_scale(struct perf_pmu_alias * alias,char * dir,char * name)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 	scnprintf(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 
perf_pmu__parse_unit(struct perf_pmu_alias * alias,char * dir,char * name)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 	scnprintf(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
perf_pmu__parse_per_pkg(struct perf_pmu_alias * alias,char * dir,char * name)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 	scnprintf(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 
perf_pmu__parse_snapshot(struct perf_pmu_alias * alias,char * dir,char * name)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 	scnprintf(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 
__perf_pmu__new_alias(struct list_head * list,char * dir,char * name,char * desc,char * val,char * long_desc,char * topic,char * unit,char * perpkg,char * metric_expr,char * metric_name)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 
perf_pmu__new_alias(struct list_head * list,char * dir,char * name,FILE * file)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 
pmu_alias_info_file(char * name)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  */
pmu_aliases_parse(char * dir,struct list_head * head)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 		scnprintf(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  */
pmu_aliases(const char * name,struct list_head * head)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 
pmu_alias_terms(struct perf_pmu_alias * alias,struct list_head * terms)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 		/*
408 		 * Weak terms don't override command line options,
409 		 * which we don't want for implicit terms in aliases.
410 		 */
411 		cloned->weak = true;
412 		list_add_tail(&cloned->list, &list);
413 	}
414 	list_splice(&list, terms);
415 	return 0;
416 }
417 
418 /*
419  * Reading/parsing the default pmu type value, which should be
420  * located at:
421  * /sys/bus/event_source/devices/<dev>/type as sysfs attribute.
422  */
pmu_type(const char * name,__u32 * type)423 static int pmu_type(const char *name, __u32 *type)
424 {
425 	struct stat st;
426 	char path[PATH_MAX];
427 	FILE *file;
428 	int ret = 0;
429 	const char *sysfs = sysfs__mountpoint();
430 
431 	if (!sysfs)
432 		return -1;
433 
434 	snprintf(path, PATH_MAX,
435 		 "%s" EVENT_SOURCE_DEVICE_PATH "%s/type", sysfs, name);
436 
437 	if (stat(path, &st) < 0)
438 		return -1;
439 
440 	file = fopen(path, "r");
441 	if (!file)
442 		return -EINVAL;
443 
444 	if (1 != fscanf(file, "%u", type))
445 		ret = -1;
446 
447 	fclose(file);
448 	return ret;
449 }
450 
451 /* Add all pmus in sysfs to pmu list: */
pmu_read_sysfs(void)452 static void pmu_read_sysfs(void)
453 {
454 	char path[PATH_MAX];
455 	DIR *dir;
456 	struct dirent *dent;
457 	const char *sysfs = sysfs__mountpoint();
458 
459 	if (!sysfs)
460 		return;
461 
462 	snprintf(path, PATH_MAX,
463 		 "%s" EVENT_SOURCE_DEVICE_PATH, sysfs);
464 
465 	dir = opendir(path);
466 	if (!dir)
467 		return;
468 
469 	while ((dent = readdir(dir))) {
470 		if (!strcmp(dent->d_name, ".") || !strcmp(dent->d_name, ".."))
471 			continue;
472 		/* add to static LIST_HEAD(pmus): */
473 		perf_pmu__find(dent->d_name);
474 	}
475 
476 	closedir(dir);
477 }
478 
__pmu_cpumask(const char * path)479 static struct cpu_map *__pmu_cpumask(const char *path)
480 {
481 	FILE *file;
482 	struct cpu_map *cpus;
483 
484 	file = fopen(path, "r");
485 	if (!file)
486 		return NULL;
487 
488 	cpus = cpu_map__read(file);
489 	fclose(file);
490 	return cpus;
491 }
492 
493 /*
494  * Uncore PMUs have a "cpumask" file under sysfs. CPU PMUs (e.g. on arm/arm64)
495  * may have a "cpus" file.
496  */
497 #define CPUS_TEMPLATE_UNCORE	"%s/bus/event_source/devices/%s/cpumask"
498 #define CPUS_TEMPLATE_CPU	"%s/bus/event_source/devices/%s/cpus"
499 
pmu_cpumask(const char * name)500 static struct cpu_map *pmu_cpumask(const char *name)
501 {
502 	char path[PATH_MAX];
503 	struct cpu_map *cpus;
504 	const char *sysfs = sysfs__mountpoint();
505 	const char *templates[] = {
506 		CPUS_TEMPLATE_UNCORE,
507 		CPUS_TEMPLATE_CPU,
508 		NULL
509 	};
510 	const char **template;
511 
512 	if (!sysfs)
513 		return NULL;
514 
515 	for (template = templates; *template; template++) {
516 		snprintf(path, PATH_MAX, *template, sysfs, name);
517 		cpus = __pmu_cpumask(path);
518 		if (cpus)
519 			return cpus;
520 	}
521 
522 	return NULL;
523 }
524 
pmu_is_uncore(const char * name)525 static bool pmu_is_uncore(const char *name)
526 {
527 	char path[PATH_MAX];
528 	struct cpu_map *cpus;
529 	const char *sysfs = sysfs__mountpoint();
530 
531 	snprintf(path, PATH_MAX, CPUS_TEMPLATE_UNCORE, sysfs, name);
532 	cpus = __pmu_cpumask(path);
533 	cpu_map__put(cpus);
534 
535 	return !!cpus;
536 }
537 
538 /*
539  * Return the CPU id as a raw string.
540  *
541  * Each architecture should provide a more precise id string that
542  * can be use to match the architecture's "mapfile".
543  */
get_cpuid_str(void)544 char * __weak get_cpuid_str(void)
545 {
546 	return NULL;
547 }
548 
549 /*
550  * From the pmu_events_map, find the table of PMU events that corresponds
551  * to the current running CPU. Then, add all PMU events from that table
552  * as aliases.
553  */
pmu_add_cpu_aliases(struct list_head * head,const char * name)554 static void pmu_add_cpu_aliases(struct list_head *head, const char *name)
555 {
556 	int i;
557 	struct pmu_events_map *map;
558 	struct pmu_event *pe;
559 	char *cpuid;
560 	static bool printed;
561 
562 	cpuid = getenv("PERF_CPUID");
563 	if (cpuid)
564 		cpuid = strdup(cpuid);
565 	if (!cpuid)
566 		cpuid = get_cpuid_str();
567 	if (!cpuid)
568 		return;
569 
570 	if (!printed) {
571 		pr_debug("Using CPUID %s\n", cpuid);
572 		printed = true;
573 	}
574 
575 	i = 0;
576 	while (1) {
577 		map = &pmu_events_map[i++];
578 		if (!map->table)
579 			goto out;
580 
581 		if (!strcmp(map->cpuid, cpuid))
582 			break;
583 	}
584 
585 	/*
586 	 * Found a matching PMU events table. Create aliases
587 	 */
588 	i = 0;
589 	while (1) {
590 		const char *pname;
591 
592 		pe = &map->table[i++];
593 		if (!pe->name)
594 			break;
595 
596 		pname = pe->pmu ? pe->pmu : "cpu";
597 		if (strncmp(pname, name, strlen(pname)))
598 			continue;
599 
600 		/* need type casts to override 'const' */
601 		__perf_pmu__new_alias(head, NULL, (char *)pe->name,
602 				(char *)pe->desc, (char *)pe->event,
603 				(char *)pe->long_desc, (char *)pe->topic,
604 				(char *)pe->unit, (char *)pe->perpkg,
605 				(char *)pe->metric_expr,
606 				(char *)pe->metric_name);
607 	}
608 
609 out:
610 	free(cpuid);
611 }
612 
613 struct perf_event_attr * __weak
perf_pmu__get_default_config(struct perf_pmu * pmu __maybe_unused)614 perf_pmu__get_default_config(struct perf_pmu *pmu __maybe_unused)
615 {
616 	return NULL;
617 }
618 
pmu_lookup(const char * name)619 static struct perf_pmu *pmu_lookup(const char *name)
620 {
621 	struct perf_pmu *pmu;
622 	LIST_HEAD(format);
623 	LIST_HEAD(aliases);
624 	__u32 type;
625 
626 	/*
627 	 * The pmu data we store & need consists of the pmu
628 	 * type value and format definitions. Load both right
629 	 * now.
630 	 */
631 	if (pmu_format(name, &format))
632 		return NULL;
633 
634 	/*
635 	 * Check the type first to avoid unnecessary work.
636 	 */
637 	if (pmu_type(name, &type))
638 		return NULL;
639 
640 	if (pmu_aliases(name, &aliases))
641 		return NULL;
642 
643 	pmu_add_cpu_aliases(&aliases, name);
644 	pmu = zalloc(sizeof(*pmu));
645 	if (!pmu)
646 		return NULL;
647 
648 	pmu->cpus = pmu_cpumask(name);
649 
650 	pmu->is_uncore = pmu_is_uncore(name);
651 
652 	INIT_LIST_HEAD(&pmu->format);
653 	INIT_LIST_HEAD(&pmu->aliases);
654 	list_splice(&format, &pmu->format);
655 	list_splice(&aliases, &pmu->aliases);
656 	pmu->name = strdup(name);
657 	pmu->type = type;
658 	list_add_tail(&pmu->list, &pmus);
659 
660 	pmu->default_config = perf_pmu__get_default_config(pmu);
661 
662 	return pmu;
663 }
664 
pmu_find(const char * name)665 static struct perf_pmu *pmu_find(const char *name)
666 {
667 	struct perf_pmu *pmu;
668 
669 	list_for_each_entry(pmu, &pmus, list)
670 		if (!strcmp(pmu->name, name))
671 			return pmu;
672 
673 	return NULL;
674 }
675 
perf_pmu__scan(struct perf_pmu * pmu)676 struct perf_pmu *perf_pmu__scan(struct perf_pmu *pmu)
677 {
678 	/*
679 	 * pmu iterator: If pmu is NULL, we start at the begin,
680 	 * otherwise return the next pmu. Returns NULL on end.
681 	 */
682 	if (!pmu) {
683 		pmu_read_sysfs();
684 		pmu = list_prepare_entry(pmu, &pmus, list);
685 	}
686 	list_for_each_entry_continue(pmu, &pmus, list)
687 		return pmu;
688 	return NULL;
689 }
690 
perf_pmu__find(const char * name)691 struct perf_pmu *perf_pmu__find(const char *name)
692 {
693 	struct perf_pmu *pmu;
694 
695 	/*
696 	 * Once PMU is loaded it stays in the list,
697 	 * so we keep us from multiple reading/parsing
698 	 * the pmu format definitions.
699 	 */
700 	pmu = pmu_find(name);
701 	if (pmu)
702 		return pmu;
703 
704 	return pmu_lookup(name);
705 }
706 
707 static struct perf_pmu_format *
pmu_find_format(struct list_head * formats,const char * name)708 pmu_find_format(struct list_head *formats, const char *name)
709 {
710 	struct perf_pmu_format *format;
711 
712 	list_for_each_entry(format, formats, list)
713 		if (!strcmp(format->name, name))
714 			return format;
715 
716 	return NULL;
717 }
718 
perf_pmu__format_bits(struct list_head * formats,const char * name)719 __u64 perf_pmu__format_bits(struct list_head *formats, const char *name)
720 {
721 	struct perf_pmu_format *format = pmu_find_format(formats, name);
722 	__u64 bits = 0;
723 	int fbit;
724 
725 	if (!format)
726 		return 0;
727 
728 	for_each_set_bit(fbit, format->bits, PERF_PMU_FORMAT_BITS)
729 		bits |= 1ULL << fbit;
730 
731 	return bits;
732 }
733 
734 /*
735  * Sets value based on the format definition (format parameter)
736  * and unformated value (value parameter).
737  */
pmu_format_value(unsigned long * format,__u64 value,__u64 * v,bool zero)738 static void pmu_format_value(unsigned long *format, __u64 value, __u64 *v,
739 			     bool zero)
740 {
741 	unsigned long fbit, vbit;
742 
743 	for (fbit = 0, vbit = 0; fbit < PERF_PMU_FORMAT_BITS; fbit++) {
744 
745 		if (!test_bit(fbit, format))
746 			continue;
747 
748 		if (value & (1llu << vbit++))
749 			*v |= (1llu << fbit);
750 		else if (zero)
751 			*v &= ~(1llu << fbit);
752 	}
753 }
754 
pmu_format_max_value(const unsigned long * format)755 static __u64 pmu_format_max_value(const unsigned long *format)
756 {
757 	int w;
758 
759 	w = bitmap_weight(format, PERF_PMU_FORMAT_BITS);
760 	if (!w)
761 		return 0;
762 	if (w < 64)
763 		return (1ULL << w) - 1;
764 	return -1;
765 }
766 
767 /*
768  * Term is a string term, and might be a param-term. Try to look up it's value
769  * in the remaining terms.
770  * - We have a term like "base-or-format-term=param-term",
771  * - We need to find the value supplied for "param-term" (with param-term named
772  *   in a config string) later on in the term list.
773  */
pmu_resolve_param_term(struct parse_events_term * term,struct list_head * head_terms,__u64 * value)774 static int pmu_resolve_param_term(struct parse_events_term *term,
775 				  struct list_head *head_terms,
776 				  __u64 *value)
777 {
778 	struct parse_events_term *t;
779 
780 	list_for_each_entry(t, head_terms, list) {
781 		if (t->type_val == PARSE_EVENTS__TERM_TYPE_NUM) {
782 			if (!strcmp(t->config, term->config)) {
783 				t->used = true;
784 				*value = t->val.num;
785 				return 0;
786 			}
787 		}
788 	}
789 
790 	if (verbose > 0)
791 		printf("Required parameter '%s' not specified\n", term->config);
792 
793 	return -1;
794 }
795 
pmu_formats_string(struct list_head * formats)796 static char *pmu_formats_string(struct list_head *formats)
797 {
798 	struct perf_pmu_format *format;
799 	char *str = NULL;
800 	struct strbuf buf = STRBUF_INIT;
801 	unsigned i = 0;
802 
803 	if (!formats)
804 		return NULL;
805 
806 	/* sysfs exported terms */
807 	list_for_each_entry(format, formats, list)
808 		if (strbuf_addf(&buf, i++ ? ",%s" : "%s", format->name) < 0)
809 			goto error;
810 
811 	str = strbuf_detach(&buf, NULL);
812 error:
813 	strbuf_release(&buf);
814 
815 	return str;
816 }
817 
818 /*
819  * Setup one of config[12] attr members based on the
820  * user input data - term parameter.
821  */
pmu_config_term(struct list_head * formats,struct perf_event_attr * attr,struct parse_events_term * term,struct list_head * head_terms,bool zero,struct parse_events_error * err)822 static int pmu_config_term(struct list_head *formats,
823 			   struct perf_event_attr *attr,
824 			   struct parse_events_term *term,
825 			   struct list_head *head_terms,
826 			   bool zero, struct parse_events_error *err)
827 {
828 	struct perf_pmu_format *format;
829 	__u64 *vp;
830 	__u64 val, max_val;
831 
832 	/*
833 	 * If this is a parameter we've already used for parameterized-eval,
834 	 * skip it in normal eval.
835 	 */
836 	if (term->used)
837 		return 0;
838 
839 	/*
840 	 * Hardcoded terms should be already in, so nothing
841 	 * to be done for them.
842 	 */
843 	if (parse_events__is_hardcoded_term(term))
844 		return 0;
845 
846 	format = pmu_find_format(formats, term->config);
847 	if (!format) {
848 		if (verbose > 0)
849 			printf("Invalid event/parameter '%s'\n", term->config);
850 		if (err) {
851 			char *pmu_term = pmu_formats_string(formats);
852 
853 			err->idx  = term->err_term;
854 			err->str  = strdup("unknown term");
855 			err->help = parse_events_formats_error_string(pmu_term);
856 			free(pmu_term);
857 		}
858 		return -EINVAL;
859 	}
860 
861 	switch (format->value) {
862 	case PERF_PMU_FORMAT_VALUE_CONFIG:
863 		vp = &attr->config;
864 		break;
865 	case PERF_PMU_FORMAT_VALUE_CONFIG1:
866 		vp = &attr->config1;
867 		break;
868 	case PERF_PMU_FORMAT_VALUE_CONFIG2:
869 		vp = &attr->config2;
870 		break;
871 	default:
872 		return -EINVAL;
873 	}
874 
875 	/*
876 	 * Either directly use a numeric term, or try to translate string terms
877 	 * using event parameters.
878 	 */
879 	if (term->type_val == PARSE_EVENTS__TERM_TYPE_NUM) {
880 		if (term->no_value &&
881 		    bitmap_weight(format->bits, PERF_PMU_FORMAT_BITS) > 1) {
882 			if (err) {
883 				err->idx = term->err_val;
884 				err->str = strdup("no value assigned for term");
885 			}
886 			return -EINVAL;
887 		}
888 
889 		val = term->val.num;
890 	} else if (term->type_val == PARSE_EVENTS__TERM_TYPE_STR) {
891 		if (strcmp(term->val.str, "?")) {
892 			if (verbose > 0) {
893 				pr_info("Invalid sysfs entry %s=%s\n",
894 						term->config, term->val.str);
895 			}
896 			if (err) {
897 				err->idx = term->err_val;
898 				err->str = strdup("expected numeric value");
899 			}
900 			return -EINVAL;
901 		}
902 
903 		if (pmu_resolve_param_term(term, head_terms, &val))
904 			return -EINVAL;
905 	} else
906 		return -EINVAL;
907 
908 	max_val = pmu_format_max_value(format->bits);
909 	if (val > max_val) {
910 		if (err) {
911 			err->idx = term->err_val;
912 			if (asprintf(&err->str,
913 				     "value too big for format, maximum is %llu",
914 				     (unsigned long long)max_val) < 0)
915 				err->str = strdup("value too big for format");
916 			return -EINVAL;
917 		}
918 		/*
919 		 * Assume we don't care if !err, in which case the value will be
920 		 * silently truncated.
921 		 */
922 	}
923 
924 	pmu_format_value(format->bits, val, vp, zero);
925 	return 0;
926 }
927 
perf_pmu__config_terms(struct list_head * formats,struct perf_event_attr * attr,struct list_head * head_terms,bool zero,struct parse_events_error * err)928 int perf_pmu__config_terms(struct list_head *formats,
929 			   struct perf_event_attr *attr,
930 			   struct list_head *head_terms,
931 			   bool zero, struct parse_events_error *err)
932 {
933 	struct parse_events_term *term;
934 
935 	list_for_each_entry(term, head_terms, list) {
936 		if (pmu_config_term(formats, attr, term, head_terms,
937 				    zero, err))
938 			return -EINVAL;
939 	}
940 
941 	return 0;
942 }
943 
944 /*
945  * Configures event's 'attr' parameter based on the:
946  * 1) users input - specified in terms parameter
947  * 2) pmu format definitions - specified by pmu parameter
948  */
perf_pmu__config(struct perf_pmu * pmu,struct perf_event_attr * attr,struct list_head * head_terms,struct parse_events_error * err)949 int perf_pmu__config(struct perf_pmu *pmu, struct perf_event_attr *attr,
950 		     struct list_head *head_terms,
951 		     struct parse_events_error *err)
952 {
953 	bool zero = !!pmu->default_config;
954 
955 	attr->type = pmu->type;
956 	return perf_pmu__config_terms(&pmu->format, attr, head_terms,
957 				      zero, err);
958 }
959 
pmu_find_alias(struct perf_pmu * pmu,struct parse_events_term * term)960 static struct perf_pmu_alias *pmu_find_alias(struct perf_pmu *pmu,
961 					     struct parse_events_term *term)
962 {
963 	struct perf_pmu_alias *alias;
964 	char *name;
965 
966 	if (parse_events__is_hardcoded_term(term))
967 		return NULL;
968 
969 	if (term->type_val == PARSE_EVENTS__TERM_TYPE_NUM) {
970 		if (term->val.num != 1)
971 			return NULL;
972 		if (pmu_find_format(&pmu->format, term->config))
973 			return NULL;
974 		name = term->config;
975 	} else if (term->type_val == PARSE_EVENTS__TERM_TYPE_STR) {
976 		if (strcasecmp(term->config, "event"))
977 			return NULL;
978 		name = term->val.str;
979 	} else {
980 		return NULL;
981 	}
982 
983 	list_for_each_entry(alias, &pmu->aliases, list) {
984 		if (!strcasecmp(alias->name, name))
985 			return alias;
986 	}
987 	return NULL;
988 }
989 
990 
check_info_data(struct perf_pmu_alias * alias,struct perf_pmu_info * info)991 static int check_info_data(struct perf_pmu_alias *alias,
992 			   struct perf_pmu_info *info)
993 {
994 	/*
995 	 * Only one term in event definition can
996 	 * define unit, scale and snapshot, fail
997 	 * if there's more than one.
998 	 */
999 	if ((info->unit && alias->unit[0]) ||
1000 	    (info->scale && alias->scale) ||
1001 	    (info->snapshot && alias->snapshot))
1002 		return -EINVAL;
1003 
1004 	if (alias->unit[0])
1005 		info->unit = alias->unit;
1006 
1007 	if (alias->scale)
1008 		info->scale = alias->scale;
1009 
1010 	if (alias->snapshot)
1011 		info->snapshot = alias->snapshot;
1012 
1013 	return 0;
1014 }
1015 
1016 /*
1017  * Find alias in the terms list and replace it with the terms
1018  * defined for the alias
1019  */
perf_pmu__check_alias(struct perf_pmu * pmu,struct list_head * head_terms,struct perf_pmu_info * info)1020 int perf_pmu__check_alias(struct perf_pmu *pmu, struct list_head *head_terms,
1021 			  struct perf_pmu_info *info)
1022 {
1023 	struct parse_events_term *term, *h;
1024 	struct perf_pmu_alias *alias;
1025 	int ret;
1026 
1027 	info->per_pkg = false;
1028 
1029 	/*
1030 	 * Mark unit and scale as not set
1031 	 * (different from default values, see below)
1032 	 */
1033 	info->unit     = NULL;
1034 	info->scale    = 0.0;
1035 	info->snapshot = false;
1036 	info->metric_expr = NULL;
1037 	info->metric_name = NULL;
1038 
1039 	list_for_each_entry_safe(term, h, head_terms, list) {
1040 		alias = pmu_find_alias(pmu, term);
1041 		if (!alias)
1042 			continue;
1043 		ret = pmu_alias_terms(alias, &term->list);
1044 		if (ret)
1045 			return ret;
1046 
1047 		ret = check_info_data(alias, info);
1048 		if (ret)
1049 			return ret;
1050 
1051 		if (alias->per_pkg)
1052 			info->per_pkg = true;
1053 		info->metric_expr = alias->metric_expr;
1054 		info->metric_name = alias->metric_name;
1055 
1056 		list_del(&term->list);
1057 		free(term);
1058 	}
1059 
1060 	/*
1061 	 * if no unit or scale foundin aliases, then
1062 	 * set defaults as for evsel
1063 	 * unit cannot left to NULL
1064 	 */
1065 	if (info->unit == NULL)
1066 		info->unit   = "";
1067 
1068 	if (info->scale == 0.0)
1069 		info->scale  = 1.0;
1070 
1071 	return 0;
1072 }
1073 
perf_pmu__new_format(struct list_head * list,char * name,int config,unsigned long * bits)1074 int perf_pmu__new_format(struct list_head *list, char *name,
1075 			 int config, unsigned long *bits)
1076 {
1077 	struct perf_pmu_format *format;
1078 
1079 	format = zalloc(sizeof(*format));
1080 	if (!format)
1081 		return -ENOMEM;
1082 
1083 	format->name = strdup(name);
1084 	format->value = config;
1085 	memcpy(format->bits, bits, sizeof(format->bits));
1086 
1087 	list_add_tail(&format->list, list);
1088 	return 0;
1089 }
1090 
perf_pmu__set_format(unsigned long * bits,long from,long to)1091 void perf_pmu__set_format(unsigned long *bits, long from, long to)
1092 {
1093 	long b;
1094 
1095 	if (!to)
1096 		to = from;
1097 
1098 	memset(bits, 0, BITS_TO_BYTES(PERF_PMU_FORMAT_BITS));
1099 	for (b = from; b <= to; b++)
1100 		set_bit(b, bits);
1101 }
1102 
sub_non_neg(int a,int b)1103 static int sub_non_neg(int a, int b)
1104 {
1105 	if (b > a)
1106 		return 0;
1107 	return a - b;
1108 }
1109 
format_alias(char * buf,int len,struct perf_pmu * pmu,struct perf_pmu_alias * alias)1110 static char *format_alias(char *buf, int len, struct perf_pmu *pmu,
1111 			  struct perf_pmu_alias *alias)
1112 {
1113 	struct parse_events_term *term;
1114 	int used = snprintf(buf, len, "%s/%s", pmu->name, alias->name);
1115 
1116 	list_for_each_entry(term, &alias->terms, list) {
1117 		if (term->type_val == PARSE_EVENTS__TERM_TYPE_STR)
1118 			used += snprintf(buf + used, sub_non_neg(len, used),
1119 					",%s=%s", term->config,
1120 					term->val.str);
1121 	}
1122 
1123 	if (sub_non_neg(len, used) > 0) {
1124 		buf[used] = '/';
1125 		used++;
1126 	}
1127 	if (sub_non_neg(len, used) > 0) {
1128 		buf[used] = '\0';
1129 		used++;
1130 	} else
1131 		buf[len - 1] = '\0';
1132 
1133 	return buf;
1134 }
1135 
format_alias_or(char * buf,int len,struct perf_pmu * pmu,struct perf_pmu_alias * alias)1136 static char *format_alias_or(char *buf, int len, struct perf_pmu *pmu,
1137 			     struct perf_pmu_alias *alias)
1138 {
1139 	snprintf(buf, len, "%s OR %s/%s/", alias->name, pmu->name, alias->name);
1140 	return buf;
1141 }
1142 
1143 struct sevent {
1144 	char *name;
1145 	char *desc;
1146 	char *topic;
1147 	char *str;
1148 	char *pmu;
1149 	char *metric_expr;
1150 	char *metric_name;
1151 };
1152 
cmp_sevent(const void * a,const void * b)1153 static int cmp_sevent(const void *a, const void *b)
1154 {
1155 	const struct sevent *as = a;
1156 	const struct sevent *bs = b;
1157 
1158 	/* Put extra events last */
1159 	if (!!as->desc != !!bs->desc)
1160 		return !!as->desc - !!bs->desc;
1161 	if (as->topic && bs->topic) {
1162 		int n = strcmp(as->topic, bs->topic);
1163 
1164 		if (n)
1165 			return n;
1166 	}
1167 	return strcmp(as->name, bs->name);
1168 }
1169 
wordwrap(char * s,int start,int max,int corr)1170 static void wordwrap(char *s, int start, int max, int corr)
1171 {
1172 	int column = start;
1173 	int n;
1174 
1175 	while (*s) {
1176 		int wlen = strcspn(s, " \t");
1177 
1178 		if (column + wlen >= max && column > start) {
1179 			printf("\n%*s", start, "");
1180 			column = start + corr;
1181 		}
1182 		n = printf("%s%.*s", column > start ? " " : "", wlen, s);
1183 		if (n <= 0)
1184 			break;
1185 		s += wlen;
1186 		column += n;
1187 		s = ltrim(s);
1188 	}
1189 }
1190 
print_pmu_events(const char * event_glob,bool name_only,bool quiet_flag,bool long_desc,bool details_flag)1191 void print_pmu_events(const char *event_glob, bool name_only, bool quiet_flag,
1192 			bool long_desc, bool details_flag)
1193 {
1194 	struct perf_pmu *pmu;
1195 	struct perf_pmu_alias *alias;
1196 	char buf[1024];
1197 	int printed = 0;
1198 	int len, j;
1199 	struct sevent *aliases;
1200 	int numdesc = 0;
1201 	int columns = pager_get_columns();
1202 	char *topic = NULL;
1203 
1204 	pmu = NULL;
1205 	len = 0;
1206 	while ((pmu = perf_pmu__scan(pmu)) != NULL) {
1207 		list_for_each_entry(alias, &pmu->aliases, list)
1208 			len++;
1209 		if (pmu->selectable)
1210 			len++;
1211 	}
1212 	aliases = zalloc(sizeof(struct sevent) * len);
1213 	if (!aliases)
1214 		goto out_enomem;
1215 	pmu = NULL;
1216 	j = 0;
1217 	while ((pmu = perf_pmu__scan(pmu)) != NULL) {
1218 		list_for_each_entry(alias, &pmu->aliases, list) {
1219 			char *name = alias->desc ? alias->name :
1220 				format_alias(buf, sizeof(buf), pmu, alias);
1221 			bool is_cpu = !strcmp(pmu->name, "cpu");
1222 
1223 			if (event_glob != NULL &&
1224 			    !(strglobmatch_nocase(name, event_glob) ||
1225 			      (!is_cpu && strglobmatch_nocase(alias->name,
1226 						       event_glob)) ||
1227 			      (alias->topic &&
1228 			       strglobmatch_nocase(alias->topic, event_glob))))
1229 				continue;
1230 
1231 			if (is_cpu && !name_only && !alias->desc)
1232 				name = format_alias_or(buf, sizeof(buf), pmu, alias);
1233 
1234 			aliases[j].name = name;
1235 			if (is_cpu && !name_only && !alias->desc)
1236 				aliases[j].name = format_alias_or(buf,
1237 								  sizeof(buf),
1238 								  pmu, alias);
1239 			aliases[j].name = strdup(aliases[j].name);
1240 			if (!aliases[j].name)
1241 				goto out_enomem;
1242 
1243 			aliases[j].desc = long_desc ? alias->long_desc :
1244 						alias->desc;
1245 			aliases[j].topic = alias->topic;
1246 			aliases[j].str = alias->str;
1247 			aliases[j].pmu = pmu->name;
1248 			aliases[j].metric_expr = alias->metric_expr;
1249 			aliases[j].metric_name = alias->metric_name;
1250 			j++;
1251 		}
1252 		if (pmu->selectable &&
1253 		    (event_glob == NULL || strglobmatch(pmu->name, event_glob))) {
1254 			char *s;
1255 			if (asprintf(&s, "%s//", pmu->name) < 0)
1256 				goto out_enomem;
1257 			aliases[j].name = s;
1258 			j++;
1259 		}
1260 	}
1261 	len = j;
1262 	qsort(aliases, len, sizeof(struct sevent), cmp_sevent);
1263 	for (j = 0; j < len; j++) {
1264 		/* Skip duplicates */
1265 		if (j > 0 && !strcmp(aliases[j].name, aliases[j - 1].name))
1266 			continue;
1267 		if (name_only) {
1268 			printf("%s ", aliases[j].name);
1269 			continue;
1270 		}
1271 		if (aliases[j].desc && !quiet_flag) {
1272 			if (numdesc++ == 0)
1273 				printf("\n");
1274 			if (aliases[j].topic && (!topic ||
1275 					strcmp(topic, aliases[j].topic))) {
1276 				printf("%s%s:\n", topic ? "\n" : "",
1277 						aliases[j].topic);
1278 				topic = aliases[j].topic;
1279 			}
1280 			printf("  %-50s\n", aliases[j].name);
1281 			printf("%*s", 8, "[");
1282 			wordwrap(aliases[j].desc, 8, columns, 0);
1283 			printf("]\n");
1284 			if (details_flag) {
1285 				printf("%*s%s/%s/ ", 8, "", aliases[j].pmu, aliases[j].str);
1286 				if (aliases[j].metric_name)
1287 					printf(" MetricName: %s", aliases[j].metric_name);
1288 				if (aliases[j].metric_expr)
1289 					printf(" MetricExpr: %s", aliases[j].metric_expr);
1290 				putchar('\n');
1291 			}
1292 		} else
1293 			printf("  %-50s [Kernel PMU event]\n", aliases[j].name);
1294 		printed++;
1295 	}
1296 	if (printed && pager_in_use())
1297 		printf("\n");
1298 out_free:
1299 	for (j = 0; j < len; j++)
1300 		zfree(&aliases[j].name);
1301 	zfree(&aliases);
1302 	return;
1303 
1304 out_enomem:
1305 	printf("FATAL: not enough memory to print PMU events\n");
1306 	if (aliases)
1307 		goto out_free;
1308 }
1309 
pmu_have_event(const char * pname,const char * name)1310 bool pmu_have_event(const char *pname, const char *name)
1311 {
1312 	struct perf_pmu *pmu;
1313 	struct perf_pmu_alias *alias;
1314 
1315 	pmu = NULL;
1316 	while ((pmu = perf_pmu__scan(pmu)) != NULL) {
1317 		if (strcmp(pname, pmu->name))
1318 			continue;
1319 		list_for_each_entry(alias, &pmu->aliases, list)
1320 			if (!strcmp(alias->name, name))
1321 				return true;
1322 	}
1323 	return false;
1324 }
1325 
perf_pmu__open_file(struct perf_pmu * pmu,const char * name)1326 static FILE *perf_pmu__open_file(struct perf_pmu *pmu, const char *name)
1327 {
1328 	struct stat st;
1329 	char path[PATH_MAX];
1330 	const char *sysfs;
1331 
1332 	sysfs = sysfs__mountpoint();
1333 	if (!sysfs)
1334 		return NULL;
1335 
1336 	snprintf(path, PATH_MAX,
1337 		 "%s" EVENT_SOURCE_DEVICE_PATH "%s/%s", sysfs, pmu->name, name);
1338 
1339 	if (stat(path, &st) < 0)
1340 		return NULL;
1341 
1342 	return fopen(path, "r");
1343 }
1344 
perf_pmu__scan_file(struct perf_pmu * pmu,const char * name,const char * fmt,...)1345 int perf_pmu__scan_file(struct perf_pmu *pmu, const char *name, const char *fmt,
1346 			...)
1347 {
1348 	va_list args;
1349 	FILE *file;
1350 	int ret = EOF;
1351 
1352 	va_start(args, fmt);
1353 	file = perf_pmu__open_file(pmu, name);
1354 	if (file) {
1355 		ret = vfscanf(file, fmt, args);
1356 		fclose(file);
1357 	}
1358 	va_end(args);
1359 	return ret;
1360 }
1361