1 // SPDX-License-Identifier: GPL-2.0
2 #include <linux/list.h>
3 #include <linux/compiler.h>
4 #include <linux/string.h>
5 #include <linux/zalloc.h>
6 #include <linux/ctype.h>
7 #include <sys/types.h>
8 #include <fcntl.h>
9 #include <sys/stat.h>
10 #include <unistd.h>
11 #include <stdio.h>
12 #include <stdbool.h>
13 #include <dirent.h>
14 #include <api/fs/fs.h>
15 #include <api/io.h>
16 #include <api/io_dir.h>
17 #include <locale.h>
18 #include <fnmatch.h>
19 #include <math.h>
20 #include "debug.h"
21 #include "evsel.h"
22 #include "pmu.h"
23 #include "hwmon_pmu.h"
24 #include "pmus.h"
25 #include "tool_pmu.h"
26 #include <util/pmu-bison.h>
27 #include <util/pmu-flex.h>
28 #include "parse-events.h"
29 #include "print-events.h"
30 #include "header.h"
31 #include "string2.h"
32 #include "strbuf.h"
33 #include "fncache.h"
34 #include "util/evsel_config.h"
35 #include <regex.h>
36 
37 #define UNIT_MAX_LEN	31 /* max length for event unit name */
38 
39 enum event_source {
40 	/* An event loaded from /sys/bus/event_source/devices/<pmu>/events. */
41 	EVENT_SRC_SYSFS,
42 	/* An event loaded from a CPUID matched json file. */
43 	EVENT_SRC_CPU_JSON,
44 	/*
45 	 * An event loaded from a /sys/bus/event_source/devices/<pmu>/identifier matched json
46 	 * file.
47 	 */
48 	EVENT_SRC_SYS_JSON,
49 };
50 
51 /**
52  * struct perf_pmu_alias - An event either read from sysfs or builtin in
53  * pmu-events.c, created by parsing the pmu-events json files.
54  */
55 struct perf_pmu_alias {
56 	/** @name: Name of the event like "mem-loads". */
57 	char *name;
58 	/** @desc: Optional short description of the event. */
59 	char *desc;
60 	/** @long_desc: Optional long description. */
61 	char *long_desc;
62 	/**
63 	 * @topic: Optional topic such as cache or pipeline, particularly for
64 	 * json events.
65 	 */
66 	char *topic;
67 	/** @terms: Owned list of the original parsed parameters. */
68 	struct parse_events_terms terms;
69 	/** @list: List element of struct perf_pmu aliases. */
70 	struct list_head list;
71 	/**
72 	 * @pmu_name: The name copied from the json struct pmu_event. This can
73 	 * differ from the PMU name as it won't have suffixes.
74 	 */
75 	char *pmu_name;
76 	/** @unit: Units for the event, such as bytes or cache lines. */
77 	char unit[UNIT_MAX_LEN+1];
78 	/** @scale: Value to scale read counter values by. */
79 	double scale;
80 	/**
81 	 * @per_pkg: Does the file
82 	 * <sysfs>/bus/event_source/devices/<pmu_name>/events/<name>.per-pkg or
83 	 * equivalent json value exist and have the value 1.
84 	 */
85 	bool per_pkg;
86 	/**
87 	 * @snapshot: Does the file
88 	 * <sysfs>/bus/event_source/devices/<pmu_name>/events/<name>.snapshot
89 	 * exist and have the value 1.
90 	 */
91 	bool snapshot;
92 	/**
93 	 * @deprecated: Is the event hidden and so not shown in perf list by
94 	 * default.
95 	 */
96 	bool deprecated;
97 	/** @from_sysfs: Was the alias from sysfs or a json event? */
98 	bool from_sysfs;
99 	/** @info_loaded: Have the scale, unit and other values been read from disk? */
100 	bool info_loaded;
101 };
102 
103 /**
104  * struct perf_pmu_format - Values from a format file read from
105  * <sysfs>/devices/cpu/format/ held in struct perf_pmu.
106  *
107  * For example, the contents of <sysfs>/devices/cpu/format/event may be
108  * "config:0-7" and will be represented here as name="event",
109  * value=PERF_PMU_FORMAT_VALUE_CONFIG and bits 0 to 7 will be set.
110  */
111 struct perf_pmu_format {
112 	/** @list: Element on list within struct perf_pmu. */
113 	struct list_head list;
114 	/** @bits: Which config bits are set by this format value. */
115 	DECLARE_BITMAP(bits, PERF_PMU_FORMAT_BITS);
116 	/** @name: The modifier/file name. */
117 	char *name;
118 	/**
119 	 * @value : Which config value the format relates to. Supported values
120 	 * are from PERF_PMU_FORMAT_VALUE_CONFIG to
121 	 * PERF_PMU_FORMAT_VALUE_CONFIG_END.
122 	 */
123 	u16 value;
124 	/** @loaded: Has the contents been loaded/parsed. */
125 	bool loaded;
126 };
127 
128 static int pmu_aliases_parse(struct perf_pmu *pmu);
129 
perf_pmu__new_format(struct list_head * list,char * name)130 static struct perf_pmu_format *perf_pmu__new_format(struct list_head *list, char *name)
131 {
132 	struct perf_pmu_format *format;
133 
134 	format = zalloc(sizeof(*format));
135 	if (!format)
136 		return NULL;
137 
138 	format->name = strdup(name);
139 	if (!format->name) {
140 		free(format);
141 		return NULL;
142 	}
143 	list_add_tail(&format->list, list);
144 	return format;
145 }
146 
147 /* Called at the end of parsing a format. */
perf_pmu_format__set_value(void * vformat,int config,unsigned long * bits)148 void perf_pmu_format__set_value(void *vformat, int config, unsigned long *bits)
149 {
150 	struct perf_pmu_format *format = vformat;
151 
152 	format->value = config;
153 	memcpy(format->bits, bits, sizeof(format->bits));
154 }
155 
__perf_pmu_format__load(struct perf_pmu_format * format,FILE * file)156 static void __perf_pmu_format__load(struct perf_pmu_format *format, FILE *file)
157 {
158 	void *scanner;
159 	int ret;
160 
161 	ret = perf_pmu_lex_init(&scanner);
162 	if (ret)
163 		return;
164 
165 	perf_pmu_set_in(file, scanner);
166 	ret = perf_pmu_parse(format, scanner);
167 	perf_pmu_lex_destroy(scanner);
168 	format->loaded = true;
169 }
170 
perf_pmu_format__load(const struct perf_pmu * pmu,struct perf_pmu_format * format)171 static void perf_pmu_format__load(const struct perf_pmu *pmu, struct perf_pmu_format *format)
172 {
173 	char path[PATH_MAX];
174 	FILE *file = NULL;
175 
176 	if (format->loaded)
177 		return;
178 
179 	if (!perf_pmu__pathname_scnprintf(path, sizeof(path), pmu->name, "format"))
180 		return;
181 
182 	assert(strlen(path) + strlen(format->name) + 2 < sizeof(path));
183 	strcat(path, "/");
184 	strcat(path, format->name);
185 
186 	file = fopen(path, "r");
187 	if (!file)
188 		return;
189 	__perf_pmu_format__load(format, file);
190 	fclose(file);
191 }
192 
193 /*
194  * Parse & process all the sysfs attributes located under
195  * the directory specified in 'dir' parameter.
196  */
perf_pmu__format_parse(struct perf_pmu * pmu,int dirfd,bool eager_load)197 static int perf_pmu__format_parse(struct perf_pmu *pmu, int dirfd, bool eager_load)
198 {
199 	struct io_dirent64 *evt_ent;
200 	struct io_dir format_dir;
201 	int ret = 0;
202 
203 	io_dir__init(&format_dir, dirfd);
204 
205 	while ((evt_ent = io_dir__readdir(&format_dir)) != NULL) {
206 		struct perf_pmu_format *format;
207 		char *name = evt_ent->d_name;
208 
209 		if (io_dir__is_dir(&format_dir, evt_ent))
210 			continue;
211 
212 		format = perf_pmu__new_format(&pmu->format, name);
213 		if (!format) {
214 			ret = -ENOMEM;
215 			break;
216 		}
217 
218 		if (eager_load) {
219 			FILE *file;
220 			int fd = openat(dirfd, name, O_RDONLY);
221 
222 			if (fd < 0) {
223 				ret = -errno;
224 				break;
225 			}
226 			file = fdopen(fd, "r");
227 			if (!file) {
228 				close(fd);
229 				break;
230 			}
231 			__perf_pmu_format__load(format, file);
232 			fclose(file);
233 		}
234 	}
235 
236 	close(format_dir.dirfd);
237 	return ret;
238 }
239 
240 /*
241  * Reading/parsing the default pmu format definition, which should be
242  * located at:
243  * /sys/bus/event_source/devices/<dev>/format as sysfs group attributes.
244  */
pmu_format(struct perf_pmu * pmu,int dirfd,const char * name,bool eager_load)245 static int pmu_format(struct perf_pmu *pmu, int dirfd, const char *name, bool eager_load)
246 {
247 	int fd;
248 
249 	fd = perf_pmu__pathname_fd(dirfd, name, "format", O_DIRECTORY);
250 	if (fd < 0)
251 		return 0;
252 
253 	/* it'll close the fd */
254 	if (perf_pmu__format_parse(pmu, fd, eager_load))
255 		return -1;
256 
257 	return 0;
258 }
259 
perf_pmu__convert_scale(const char * scale,char ** end,double * sval)260 int perf_pmu__convert_scale(const char *scale, char **end, double *sval)
261 {
262 	char *lc;
263 	int ret = 0;
264 
265 	/*
266 	 * save current locale
267 	 */
268 	lc = setlocale(LC_NUMERIC, NULL);
269 
270 	/*
271 	 * The lc string may be allocated in static storage,
272 	 * so get a dynamic copy to make it survive setlocale
273 	 * call below.
274 	 */
275 	lc = strdup(lc);
276 	if (!lc) {
277 		ret = -ENOMEM;
278 		goto out;
279 	}
280 
281 	/*
282 	 * force to C locale to ensure kernel
283 	 * scale string is converted correctly.
284 	 * kernel uses default C locale.
285 	 */
286 	setlocale(LC_NUMERIC, "C");
287 
288 	*sval = strtod(scale, end);
289 
290 out:
291 	/* restore locale */
292 	setlocale(LC_NUMERIC, lc);
293 	free(lc);
294 	return ret;
295 }
296 
perf_pmu__parse_scale(struct perf_pmu * pmu,struct perf_pmu_alias * alias)297 static int perf_pmu__parse_scale(struct perf_pmu *pmu, struct perf_pmu_alias *alias)
298 {
299 	struct stat st;
300 	ssize_t sret;
301 	size_t len;
302 	char scale[128];
303 	int fd, ret = -1;
304 	char path[PATH_MAX];
305 
306 	len = perf_pmu__event_source_devices_scnprintf(path, sizeof(path));
307 	if (!len)
308 		return 0;
309 	scnprintf(path + len, sizeof(path) - len, "%s/events/%s.scale", pmu->name, alias->name);
310 
311 	fd = open(path, O_RDONLY);
312 	if (fd == -1)
313 		return -1;
314 
315 	if (fstat(fd, &st) < 0)
316 		goto error;
317 
318 	sret = read(fd, scale, sizeof(scale)-1);
319 	if (sret < 0)
320 		goto error;
321 
322 	if (scale[sret - 1] == '\n')
323 		scale[sret - 1] = '\0';
324 	else
325 		scale[sret] = '\0';
326 
327 	ret = perf_pmu__convert_scale(scale, NULL, &alias->scale);
328 error:
329 	close(fd);
330 	return ret;
331 }
332 
perf_pmu__parse_unit(struct perf_pmu * pmu,struct perf_pmu_alias * alias)333 static int perf_pmu__parse_unit(struct perf_pmu *pmu, struct perf_pmu_alias *alias)
334 {
335 	char path[PATH_MAX];
336 	size_t len;
337 	ssize_t sret;
338 	int fd;
339 
340 
341 	len = perf_pmu__event_source_devices_scnprintf(path, sizeof(path));
342 	if (!len)
343 		return 0;
344 	scnprintf(path + len, sizeof(path) - len, "%s/events/%s.unit", pmu->name, alias->name);
345 
346 	fd = open(path, O_RDONLY);
347 	if (fd == -1)
348 		return -1;
349 
350 	sret = read(fd, alias->unit, UNIT_MAX_LEN);
351 	if (sret < 0)
352 		goto error;
353 
354 	close(fd);
355 
356 	if (alias->unit[sret - 1] == '\n')
357 		alias->unit[sret - 1] = '\0';
358 	else
359 		alias->unit[sret] = '\0';
360 
361 	return 0;
362 error:
363 	close(fd);
364 	alias->unit[0] = '\0';
365 	return -1;
366 }
367 
perf_pmu__parse_event_source_bool(const char * pmu_name,const char * event_name,const char * suffix)368 static bool perf_pmu__parse_event_source_bool(const char *pmu_name, const char *event_name,
369 					      const char *suffix)
370 {
371 	char path[PATH_MAX];
372 	size_t len;
373 	int fd;
374 
375 	len = perf_pmu__event_source_devices_scnprintf(path, sizeof(path));
376 	if (!len)
377 		return false;
378 
379 	scnprintf(path + len, sizeof(path) - len, "%s/events/%s.%s", pmu_name, event_name, suffix);
380 
381 	fd = open(path, O_RDONLY);
382 	if (fd == -1)
383 		return false;
384 
385 #ifndef NDEBUG
386 	{
387 		char buf[8];
388 
389 		len = read(fd, buf, sizeof(buf));
390 		assert(len == 1 || len == 2);
391 		assert(buf[0] == '1');
392 	}
393 #endif
394 
395 	close(fd);
396 	return true;
397 }
398 
perf_pmu__parse_per_pkg(struct perf_pmu * pmu,struct perf_pmu_alias * alias)399 static void perf_pmu__parse_per_pkg(struct perf_pmu *pmu, struct perf_pmu_alias *alias)
400 {
401 	alias->per_pkg = perf_pmu__parse_event_source_bool(pmu->name, alias->name, "per-pkg");
402 }
403 
perf_pmu__parse_snapshot(struct perf_pmu * pmu,struct perf_pmu_alias * alias)404 static void perf_pmu__parse_snapshot(struct perf_pmu *pmu, struct perf_pmu_alias *alias)
405 {
406 	alias->snapshot = perf_pmu__parse_event_source_bool(pmu->name, alias->name, "snapshot");
407 }
408 
409 /* Delete an alias entry. */
perf_pmu_free_alias(struct perf_pmu_alias * newalias)410 static void perf_pmu_free_alias(struct perf_pmu_alias *newalias)
411 {
412 	zfree(&newalias->name);
413 	zfree(&newalias->desc);
414 	zfree(&newalias->long_desc);
415 	zfree(&newalias->topic);
416 	zfree(&newalias->pmu_name);
417 	parse_events_terms__exit(&newalias->terms);
418 	free(newalias);
419 }
420 
perf_pmu__del_aliases(struct perf_pmu * pmu)421 static void perf_pmu__del_aliases(struct perf_pmu *pmu)
422 {
423 	struct perf_pmu_alias *alias, *tmp;
424 
425 	list_for_each_entry_safe(alias, tmp, &pmu->aliases, list) {
426 		list_del(&alias->list);
427 		perf_pmu_free_alias(alias);
428 	}
429 }
430 
perf_pmu__find_alias(struct perf_pmu * pmu,const char * name,bool load)431 static struct perf_pmu_alias *perf_pmu__find_alias(struct perf_pmu *pmu,
432 						   const char *name,
433 						   bool load)
434 {
435 	struct perf_pmu_alias *alias;
436 
437 	if (load && !pmu->sysfs_aliases_loaded) {
438 		bool has_sysfs_event;
439 		char event_file_name[FILENAME_MAX + 8];
440 
441 		/*
442 		 * Test if alias/event 'name' exists in the PMU's sysfs/events
443 		 * directory. If not skip parsing the sysfs aliases. Sysfs event
444 		 * name must be all lower or all upper case.
445 		 */
446 		scnprintf(event_file_name, sizeof(event_file_name), "events/%s", name);
447 		for (size_t i = 7, n = 7 + strlen(name); i < n; i++)
448 			event_file_name[i] = tolower(event_file_name[i]);
449 
450 		has_sysfs_event = perf_pmu__file_exists(pmu, event_file_name);
451 		if (!has_sysfs_event) {
452 			for (size_t i = 7, n = 7 + strlen(name); i < n; i++)
453 				event_file_name[i] = toupper(event_file_name[i]);
454 
455 			has_sysfs_event = perf_pmu__file_exists(pmu, event_file_name);
456 		}
457 		if (has_sysfs_event)
458 			pmu_aliases_parse(pmu);
459 
460 	}
461 	list_for_each_entry(alias, &pmu->aliases, list) {
462 		if (!strcasecmp(alias->name, name))
463 			return alias;
464 	}
465 	return NULL;
466 }
467 
assign_str(const char * name,const char * field,char ** old_str,const char * new_str)468 static bool assign_str(const char *name, const char *field, char **old_str,
469 				const char *new_str)
470 {
471 	if (!*old_str && new_str) {
472 		*old_str = strdup(new_str);
473 		return true;
474 	}
475 
476 	if (!new_str || !strcasecmp(*old_str, new_str))
477 		return false; /* Nothing to update. */
478 
479 	pr_debug("alias %s differs in field '%s' ('%s' != '%s')\n",
480 		name, field, *old_str, new_str);
481 	zfree(old_str);
482 	*old_str = strdup(new_str);
483 	return true;
484 }
485 
read_alias_info(struct perf_pmu * pmu,struct perf_pmu_alias * alias)486 static void read_alias_info(struct perf_pmu *pmu, struct perf_pmu_alias *alias)
487 {
488 	if (!alias->from_sysfs || alias->info_loaded)
489 		return;
490 
491 	/*
492 	 * load unit name and scale if available
493 	 */
494 	perf_pmu__parse_unit(pmu, alias);
495 	perf_pmu__parse_scale(pmu, alias);
496 	perf_pmu__parse_per_pkg(pmu, alias);
497 	perf_pmu__parse_snapshot(pmu, alias);
498 }
499 
500 struct update_alias_data {
501 	struct perf_pmu *pmu;
502 	struct perf_pmu_alias *alias;
503 };
504 
update_alias(const struct pmu_event * pe,const struct pmu_events_table * table __maybe_unused,void * vdata)505 static int update_alias(const struct pmu_event *pe,
506 			const struct pmu_events_table *table __maybe_unused,
507 			void *vdata)
508 {
509 	struct update_alias_data *data = vdata;
510 	int ret = 0;
511 
512 	read_alias_info(data->pmu, data->alias);
513 	assign_str(pe->name, "desc", &data->alias->desc, pe->desc);
514 	assign_str(pe->name, "long_desc", &data->alias->long_desc, pe->long_desc);
515 	assign_str(pe->name, "topic", &data->alias->topic, pe->topic);
516 	data->alias->per_pkg = pe->perpkg;
517 	if (pe->event) {
518 		parse_events_terms__exit(&data->alias->terms);
519 		ret = parse_events_terms(&data->alias->terms, pe->event, /*input=*/NULL);
520 	}
521 	if (!ret && pe->unit) {
522 		char *unit;
523 
524 		ret = perf_pmu__convert_scale(pe->unit, &unit, &data->alias->scale);
525 		if (!ret)
526 			snprintf(data->alias->unit, sizeof(data->alias->unit), "%s", unit);
527 	}
528 	return ret;
529 }
530 
perf_pmu__new_alias(struct perf_pmu * pmu,const char * name,const char * desc,const char * val,FILE * val_fd,const struct pmu_event * pe,enum event_source src)531 static int perf_pmu__new_alias(struct perf_pmu *pmu, const char *name,
532 				const char *desc, const char *val, FILE *val_fd,
533 			        const struct pmu_event *pe, enum event_source src)
534 {
535 	struct perf_pmu_alias *alias;
536 	int ret;
537 	const char *long_desc = NULL, *topic = NULL, *unit = NULL, *pmu_name = NULL;
538 	bool deprecated = false, perpkg = false;
539 
540 	if (perf_pmu__find_alias(pmu, name, /*load=*/ false)) {
541 		/* Alias was already created/loaded. */
542 		return 0;
543 	}
544 
545 	if (pe) {
546 		long_desc = pe->long_desc;
547 		topic = pe->topic;
548 		unit = pe->unit;
549 		perpkg = pe->perpkg;
550 		deprecated = pe->deprecated;
551 		if (pe->pmu && strcmp(pe->pmu, "default_core"))
552 			pmu_name = pe->pmu;
553 	}
554 
555 	alias = zalloc(sizeof(*alias));
556 	if (!alias)
557 		return -ENOMEM;
558 
559 	parse_events_terms__init(&alias->terms);
560 	alias->scale = 1.0;
561 	alias->unit[0] = '\0';
562 	alias->per_pkg = perpkg;
563 	alias->snapshot = false;
564 	alias->deprecated = deprecated;
565 
566 	ret = parse_events_terms(&alias->terms, val, val_fd);
567 	if (ret) {
568 		pr_err("Cannot parse alias %s: %d\n", val, ret);
569 		free(alias);
570 		return ret;
571 	}
572 
573 	alias->name = strdup(name);
574 	alias->desc = desc ? strdup(desc) : NULL;
575 	alias->long_desc = long_desc ? strdup(long_desc) :
576 				desc ? strdup(desc) : NULL;
577 	alias->topic = topic ? strdup(topic) : NULL;
578 	alias->pmu_name = pmu_name ? strdup(pmu_name) : NULL;
579 	if (unit) {
580 		if (perf_pmu__convert_scale(unit, (char **)&unit, &alias->scale) < 0) {
581 			perf_pmu_free_alias(alias);
582 			return -1;
583 		}
584 		snprintf(alias->unit, sizeof(alias->unit), "%s", unit);
585 	}
586 	switch (src) {
587 	default:
588 	case EVENT_SRC_SYSFS:
589 		alias->from_sysfs = true;
590 		if (pmu->events_table) {
591 			/* Update an event from sysfs with json data. */
592 			struct update_alias_data data = {
593 				.pmu = pmu,
594 				.alias = alias,
595 			};
596 			if (pmu_events_table__find_event(pmu->events_table, pmu, name,
597 							 update_alias, &data) == 0)
598 				pmu->cpu_common_json_aliases++;
599 		}
600 		pmu->sysfs_aliases++;
601 		break;
602 	case  EVENT_SRC_CPU_JSON:
603 		pmu->cpu_json_aliases++;
604 		break;
605 	case  EVENT_SRC_SYS_JSON:
606 		pmu->sys_json_aliases++;
607 		break;
608 
609 	}
610 	list_add_tail(&alias->list, &pmu->aliases);
611 	return 0;
612 }
613 
pmu_alias_info_file(const char * name)614 static inline bool pmu_alias_info_file(const char *name)
615 {
616 	size_t len;
617 
618 	len = strlen(name);
619 	if (len > 5 && !strcmp(name + len - 5, ".unit"))
620 		return true;
621 	if (len > 6 && !strcmp(name + len - 6, ".scale"))
622 		return true;
623 	if (len > 8 && !strcmp(name + len - 8, ".per-pkg"))
624 		return true;
625 	if (len > 9 && !strcmp(name + len - 9, ".snapshot"))
626 		return true;
627 
628 	return false;
629 }
630 
631 /*
632  * Reading the pmu event aliases definition, which should be located at:
633  * /sys/bus/event_source/devices/<dev>/events as sysfs group attributes.
634  */
__pmu_aliases_parse(struct perf_pmu * pmu,int events_dir_fd)635 static int __pmu_aliases_parse(struct perf_pmu *pmu, int events_dir_fd)
636 {
637 	struct io_dirent64 *evt_ent;
638 	struct io_dir event_dir;
639 
640 	io_dir__init(&event_dir, events_dir_fd);
641 
642 	while ((evt_ent = io_dir__readdir(&event_dir))) {
643 		char *name = evt_ent->d_name;
644 		int fd;
645 		FILE *file;
646 
647 		if (!strcmp(name, ".") || !strcmp(name, ".."))
648 			continue;
649 
650 		/*
651 		 * skip info files parsed in perf_pmu__new_alias()
652 		 */
653 		if (pmu_alias_info_file(name))
654 			continue;
655 
656 		fd = openat(events_dir_fd, name, O_RDONLY);
657 		if (fd == -1) {
658 			pr_debug("Cannot open %s\n", name);
659 			continue;
660 		}
661 		file = fdopen(fd, "r");
662 		if (!file) {
663 			close(fd);
664 			continue;
665 		}
666 
667 		if (perf_pmu__new_alias(pmu, name, /*desc=*/ NULL,
668 					/*val=*/ NULL, file, /*pe=*/ NULL,
669 					EVENT_SRC_SYSFS) < 0)
670 			pr_debug("Cannot set up %s\n", name);
671 		fclose(file);
672 	}
673 
674 	pmu->sysfs_aliases_loaded = true;
675 	return 0;
676 }
677 
pmu_aliases_parse(struct perf_pmu * pmu)678 static int pmu_aliases_parse(struct perf_pmu *pmu)
679 {
680 	char path[PATH_MAX];
681 	size_t len;
682 	int events_dir_fd, ret;
683 
684 	if (pmu->sysfs_aliases_loaded)
685 		return 0;
686 
687 	len = perf_pmu__event_source_devices_scnprintf(path, sizeof(path));
688 	if (!len)
689 		return 0;
690 	scnprintf(path + len, sizeof(path) - len, "%s/events", pmu->name);
691 
692 	events_dir_fd = open(path, O_DIRECTORY);
693 	if (events_dir_fd == -1) {
694 		pmu->sysfs_aliases_loaded = true;
695 		return 0;
696 	}
697 	ret = __pmu_aliases_parse(pmu, events_dir_fd);
698 	close(events_dir_fd);
699 	return ret;
700 }
701 
pmu_aliases_parse_eager(struct perf_pmu * pmu,int sysfs_fd)702 static int pmu_aliases_parse_eager(struct perf_pmu *pmu, int sysfs_fd)
703 {
704 	char path[FILENAME_MAX + 7];
705 	int ret, events_dir_fd;
706 
707 	scnprintf(path, sizeof(path), "%s/events", pmu->name);
708 	events_dir_fd = openat(sysfs_fd, path, O_DIRECTORY, 0);
709 	if (events_dir_fd == -1) {
710 		pmu->sysfs_aliases_loaded = true;
711 		return 0;
712 	}
713 	ret = __pmu_aliases_parse(pmu, events_dir_fd);
714 	close(events_dir_fd);
715 	return ret;
716 }
717 
pmu_alias_terms(struct perf_pmu_alias * alias,int err_loc,struct list_head * terms)718 static int pmu_alias_terms(struct perf_pmu_alias *alias, int err_loc, struct list_head *terms)
719 {
720 	struct parse_events_term *term, *cloned;
721 	struct parse_events_terms clone_terms;
722 
723 	parse_events_terms__init(&clone_terms);
724 	list_for_each_entry(term, &alias->terms.terms, list) {
725 		int ret = parse_events_term__clone(&cloned, term);
726 
727 		if (ret) {
728 			parse_events_terms__exit(&clone_terms);
729 			return ret;
730 		}
731 		/*
732 		 * Weak terms don't override command line options,
733 		 * which we don't want for implicit terms in aliases.
734 		 */
735 		cloned->weak = true;
736 		cloned->err_term = cloned->err_val = err_loc;
737 		list_add_tail(&cloned->list, &clone_terms.terms);
738 	}
739 	list_splice_init(&clone_terms.terms, terms);
740 	parse_events_terms__exit(&clone_terms);
741 	return 0;
742 }
743 
744 /*
745  * Uncore PMUs have a "cpumask" file under sysfs. CPU PMUs (e.g. on arm/arm64)
746  * may have a "cpus" file.
747  */
pmu_cpumask(int dirfd,const char * pmu_name,bool is_core)748 static struct perf_cpu_map *pmu_cpumask(int dirfd, const char *pmu_name, bool is_core)
749 {
750 	const char *templates[] = {
751 		"cpumask",
752 		"cpus",
753 		NULL
754 	};
755 	const char **template;
756 
757 	for (template = templates; *template; template++) {
758 		struct io io;
759 		char buf[128];
760 		char *cpumask = NULL;
761 		size_t cpumask_len;
762 		ssize_t ret;
763 		struct perf_cpu_map *cpus;
764 
765 		io.fd = perf_pmu__pathname_fd(dirfd, pmu_name, *template, O_RDONLY);
766 		if (io.fd < 0)
767 			continue;
768 
769 		io__init(&io, io.fd, buf, sizeof(buf));
770 		ret = io__getline(&io, &cpumask, &cpumask_len);
771 		close(io.fd);
772 		if (ret < 0)
773 			continue;
774 
775 		cpus = perf_cpu_map__new(cpumask);
776 		free(cpumask);
777 		if (cpus)
778 			return cpus;
779 	}
780 
781 	/* Nothing found, for core PMUs assume this means all CPUs. */
782 	return is_core ? cpu_map__online() : NULL;
783 }
784 
pmu_is_uncore(int dirfd,const char * name)785 static bool pmu_is_uncore(int dirfd, const char *name)
786 {
787 	int fd;
788 
789 	fd = perf_pmu__pathname_fd(dirfd, name, "cpumask", O_PATH);
790 	if (fd < 0)
791 		return false;
792 
793 	close(fd);
794 	return true;
795 }
796 
pmu_id(const char * name)797 static char *pmu_id(const char *name)
798 {
799 	char path[PATH_MAX], *str;
800 	size_t len;
801 
802 	perf_pmu__pathname_scnprintf(path, sizeof(path), name, "identifier");
803 
804 	if (filename__read_str(path, &str, &len) < 0)
805 		return NULL;
806 
807 	str[len - 1] = 0; /* remove line feed */
808 
809 	return str;
810 }
811 
812 /**
813  * is_sysfs_pmu_core() - PMU CORE devices have different name other than cpu in
814  *         sysfs on some platforms like ARM or Intel hybrid. Looking for
815  *         possible the cpus file in sysfs files to identify whether this is a
816  *         core device.
817  * @name: The PMU name such as "cpu_atom".
818  */
is_sysfs_pmu_core(const char * name)819 static int is_sysfs_pmu_core(const char *name)
820 {
821 	char path[PATH_MAX];
822 
823 	if (!perf_pmu__pathname_scnprintf(path, sizeof(path), name, "cpus"))
824 		return 0;
825 	return file_available(path);
826 }
827 
828 /**
829  * Return the length of the PMU name not including the suffix for uncore PMUs.
830  *
831  * We want to deduplicate many similar uncore PMUs by stripping their suffixes,
832  * but there are never going to be too many core PMUs and the suffixes might be
833  * interesting. "arm_cortex_a53" vs "arm_cortex_a57" or "cpum_cf" for example.
834  *
835  * @skip_duplicate_pmus: False in verbose mode so all uncore PMUs are visible
836  */
pmu_deduped_name_len(const struct perf_pmu * pmu,const char * name,bool skip_duplicate_pmus)837 static size_t pmu_deduped_name_len(const struct perf_pmu *pmu, const char *name,
838 				   bool skip_duplicate_pmus)
839 {
840 	return skip_duplicate_pmus && !pmu->is_core
841 		? pmu_name_len_no_suffix(name)
842 		: strlen(name);
843 }
844 
845 /**
846  * perf_pmu__match_wildcard - Does the pmu_name start with tok and is then only
847  *                            followed by nothing or a suffix? tok may contain
848  *                            part of a suffix.
849  * @pmu_name: The pmu_name with possible suffix.
850  * @tok: The wildcard argument to match.
851  */
perf_pmu__match_wildcard(const char * pmu_name,const char * tok)852 static bool perf_pmu__match_wildcard(const char *pmu_name, const char *tok)
853 {
854 	const char *p, *suffix;
855 	bool has_hex = false;
856 	size_t tok_len = strlen(tok);
857 
858 	/* Check start of pmu_name for equality. */
859 	if (strncmp(pmu_name, tok, tok_len))
860 		return false;
861 
862 	suffix = p = pmu_name + tok_len;
863 	if (*p == 0)
864 		return true;
865 
866 	if (*p == '_') {
867 		++p;
868 		++suffix;
869 	}
870 
871 	/* Ensure we end in a number */
872 	while (1) {
873 		if (!isxdigit(*p))
874 			return false;
875 		if (!has_hex)
876 			has_hex = !isdigit(*p);
877 		if (*(++p) == 0)
878 			break;
879 	}
880 
881 	if (has_hex)
882 		return (p - suffix) > 2;
883 
884 	return true;
885 }
886 
887 /**
888  * perf_pmu__match_ignoring_suffix_uncore - Does the pmu_name match tok ignoring
889  *                                          any trailing suffix on pmu_name and
890  *                                          tok?  The Suffix must be in form
891  *                                          tok_{digits}, or tok{digits}.
892  * @pmu_name: The pmu_name with possible suffix.
893  * @tok: The possible match to pmu_name.
894  */
perf_pmu__match_ignoring_suffix_uncore(const char * pmu_name,const char * tok)895 static bool perf_pmu__match_ignoring_suffix_uncore(const char *pmu_name, const char *tok)
896 {
897 	size_t pmu_name_len, tok_len;
898 
899 	/* For robustness, check for NULL. */
900 	if (pmu_name == NULL)
901 		return tok == NULL;
902 
903 	/* uncore_ prefixes are ignored. */
904 	if (!strncmp(pmu_name, "uncore_", 7))
905 		pmu_name += 7;
906 	if (!strncmp(tok, "uncore_", 7))
907 		tok += 7;
908 
909 	pmu_name_len = pmu_name_len_no_suffix(pmu_name);
910 	tok_len = pmu_name_len_no_suffix(tok);
911 	if (pmu_name_len != tok_len)
912 		return false;
913 
914 	return strncmp(pmu_name, tok, pmu_name_len) == 0;
915 }
916 
917 
918 /**
919  * perf_pmu__match_wildcard_uncore - does to_match match the PMU's name?
920  * @pmu_name: The pmu->name or pmu->alias to match against.
921  * @to_match: the json struct pmu_event name. This may lack a suffix (which
922  *            matches) or be of the form "socket,pmuname" which will match
923  *            "socketX_pmunameY".
924  */
perf_pmu__match_wildcard_uncore(const char * pmu_name,const char * to_match)925 static bool perf_pmu__match_wildcard_uncore(const char *pmu_name, const char *to_match)
926 {
927 	char *mutable_to_match, *tok, *tmp;
928 
929 	if (!pmu_name)
930 		return false;
931 
932 	/* uncore_ prefixes are ignored. */
933 	if (!strncmp(pmu_name, "uncore_", 7))
934 		pmu_name += 7;
935 	if (!strncmp(to_match, "uncore_", 7))
936 		to_match += 7;
937 
938 	if (strchr(to_match, ',') == NULL)
939 		return perf_pmu__match_wildcard(pmu_name, to_match);
940 
941 	/* Process comma separated list of PMU name components. */
942 	mutable_to_match = strdup(to_match);
943 	if (!mutable_to_match)
944 		return false;
945 
946 	tok = strtok_r(mutable_to_match, ",", &tmp);
947 	while (tok) {
948 		size_t tok_len = strlen(tok);
949 
950 		if (strncmp(pmu_name, tok, tok_len)) {
951 			/* Mismatch between part of pmu_name and tok. */
952 			free(mutable_to_match);
953 			return false;
954 		}
955 		/* Move pmu_name forward over tok and suffix. */
956 		pmu_name += tok_len;
957 		while (*pmu_name != '\0' && isdigit(*pmu_name))
958 			pmu_name++;
959 		if (*pmu_name == '_')
960 			pmu_name++;
961 
962 		tok = strtok_r(NULL, ",", &tmp);
963 	}
964 	free(mutable_to_match);
965 	return *pmu_name == '\0';
966 }
967 
pmu_uncore_identifier_match(const char * compat,const char * id)968 bool pmu_uncore_identifier_match(const char *compat, const char *id)
969 {
970 	regex_t re;
971 	regmatch_t pmatch[1];
972 	int match;
973 
974 	if (regcomp(&re, compat, REG_EXTENDED) != 0) {
975 		/* Warn unable to generate match particular string. */
976 		pr_info("Invalid regular expression %s\n", compat);
977 		return false;
978 	}
979 
980 	match = !regexec(&re, id, 1, pmatch, 0);
981 	if (match) {
982 		/* Ensure a full match. */
983 		match = pmatch[0].rm_so == 0 && (size_t)pmatch[0].rm_eo == strlen(id);
984 	}
985 	regfree(&re);
986 
987 	return match;
988 }
989 
pmu_add_cpu_aliases_map_callback(const struct pmu_event * pe,const struct pmu_events_table * table __maybe_unused,void * vdata)990 static int pmu_add_cpu_aliases_map_callback(const struct pmu_event *pe,
991 					const struct pmu_events_table *table __maybe_unused,
992 					void *vdata)
993 {
994 	struct perf_pmu *pmu = vdata;
995 
996 	perf_pmu__new_alias(pmu, pe->name, pe->desc, pe->event, /*val_fd=*/ NULL,
997 			    pe, EVENT_SRC_CPU_JSON);
998 	return 0;
999 }
1000 
1001 /*
1002  * From the pmu_events_table, find the events that correspond to the given
1003  * PMU and add them to the list 'head'.
1004  */
pmu_add_cpu_aliases_table(struct perf_pmu * pmu,const struct pmu_events_table * table)1005 void pmu_add_cpu_aliases_table(struct perf_pmu *pmu, const struct pmu_events_table *table)
1006 {
1007 	pmu_events_table__for_each_event(table, pmu, pmu_add_cpu_aliases_map_callback, pmu);
1008 }
1009 
pmu_add_cpu_aliases(struct perf_pmu * pmu)1010 static void pmu_add_cpu_aliases(struct perf_pmu *pmu)
1011 {
1012 	if (!pmu->events_table)
1013 		return;
1014 
1015 	if (pmu->cpu_aliases_added)
1016 		return;
1017 
1018 	pmu_add_cpu_aliases_table(pmu, pmu->events_table);
1019 	pmu->cpu_aliases_added = true;
1020 }
1021 
pmu_add_sys_aliases_iter_fn(const struct pmu_event * pe,const struct pmu_events_table * table __maybe_unused,void * vdata)1022 static int pmu_add_sys_aliases_iter_fn(const struct pmu_event *pe,
1023 				       const struct pmu_events_table *table __maybe_unused,
1024 				       void *vdata)
1025 {
1026 	struct perf_pmu *pmu = vdata;
1027 
1028 	if (!pe->compat || !pe->pmu) {
1029 		/* No data to match. */
1030 		return 0;
1031 	}
1032 
1033 	if (!perf_pmu__match_wildcard_uncore(pmu->name, pe->pmu) &&
1034 	    !perf_pmu__match_wildcard_uncore(pmu->alias_name, pe->pmu)) {
1035 		/* PMU name/alias_name don't match. */
1036 		return 0;
1037 	}
1038 
1039 	if (pmu_uncore_identifier_match(pe->compat, pmu->id)) {
1040 		/* Id matched. */
1041 		perf_pmu__new_alias(pmu,
1042 				pe->name,
1043 				pe->desc,
1044 				pe->event,
1045 				/*val_fd=*/ NULL,
1046 				pe,
1047 				EVENT_SRC_SYS_JSON);
1048 	}
1049 	return 0;
1050 }
1051 
pmu_add_sys_aliases(struct perf_pmu * pmu)1052 void pmu_add_sys_aliases(struct perf_pmu *pmu)
1053 {
1054 	if (!pmu->id)
1055 		return;
1056 
1057 	pmu_for_each_sys_event(pmu_add_sys_aliases_iter_fn, pmu);
1058 }
1059 
pmu_find_alias_name(struct perf_pmu * pmu,int dirfd)1060 static char *pmu_find_alias_name(struct perf_pmu *pmu, int dirfd)
1061 {
1062 	FILE *file = perf_pmu__open_file_at(pmu, dirfd, "alias");
1063 	char *line = NULL;
1064 	size_t line_len = 0;
1065 	ssize_t ret;
1066 
1067 	if (!file)
1068 		return NULL;
1069 
1070 	ret = getline(&line, &line_len, file);
1071 	if (ret < 0) {
1072 		fclose(file);
1073 		return NULL;
1074 	}
1075 	/* Remove trailing newline. */
1076 	if (ret > 0 && line[ret - 1] == '\n')
1077 		line[--ret] = '\0';
1078 
1079 	fclose(file);
1080 	return line;
1081 }
1082 
pmu_max_precise(int dirfd,struct perf_pmu * pmu)1083 static int pmu_max_precise(int dirfd, struct perf_pmu *pmu)
1084 {
1085 	int max_precise = -1;
1086 
1087 	perf_pmu__scan_file_at(pmu, dirfd, "caps/max_precise", "%d", &max_precise);
1088 	return max_precise;
1089 }
1090 
1091 void __weak
perf_pmu__arch_init(struct perf_pmu * pmu)1092 perf_pmu__arch_init(struct perf_pmu *pmu)
1093 {
1094 	if (pmu->is_core)
1095 		pmu->mem_events = perf_mem_events;
1096 }
1097 
perf_pmu__lookup(struct list_head * pmus,int dirfd,const char * name,bool eager_load)1098 struct perf_pmu *perf_pmu__lookup(struct list_head *pmus, int dirfd, const char *name,
1099 				  bool eager_load)
1100 {
1101 	struct perf_pmu *pmu;
1102 	__u32 type;
1103 
1104 	pmu = zalloc(sizeof(*pmu));
1105 	if (!pmu)
1106 		return NULL;
1107 
1108 	pmu->name = strdup(name);
1109 	if (!pmu->name)
1110 		goto err;
1111 
1112 	/*
1113 	 * Read type early to fail fast if a lookup name isn't a PMU. Ensure
1114 	 * that type value is successfully assigned (return 1).
1115 	 */
1116 	if (perf_pmu__scan_file_at(pmu, dirfd, "type", "%u", &type) != 1)
1117 		goto err;
1118 
1119 	INIT_LIST_HEAD(&pmu->format);
1120 	INIT_LIST_HEAD(&pmu->aliases);
1121 	INIT_LIST_HEAD(&pmu->caps);
1122 
1123 	/*
1124 	 * The pmu data we store & need consists of the pmu
1125 	 * type value and format definitions. Load both right
1126 	 * now.
1127 	 */
1128 	if (pmu_format(pmu, dirfd, name, eager_load))
1129 		goto err;
1130 
1131 	pmu->is_core = is_pmu_core(name);
1132 	pmu->cpus = pmu_cpumask(dirfd, name, pmu->is_core);
1133 
1134 	pmu->type = type;
1135 	pmu->is_uncore = pmu_is_uncore(dirfd, name);
1136 	if (pmu->is_uncore)
1137 		pmu->id = pmu_id(name);
1138 	pmu->max_precise = pmu_max_precise(dirfd, pmu);
1139 	pmu->alias_name = pmu_find_alias_name(pmu, dirfd);
1140 	pmu->events_table = perf_pmu__find_events_table(pmu);
1141 	/*
1142 	 * Load the sys json events/aliases when loading the PMU as each event
1143 	 * may have a different compat regular expression. We therefore can't
1144 	 * know the number of sys json events/aliases without computing the
1145 	 * regular expressions for them all.
1146 	 */
1147 	pmu_add_sys_aliases(pmu);
1148 	list_add_tail(&pmu->list, pmus);
1149 
1150 	perf_pmu__arch_init(pmu);
1151 
1152 	if (eager_load)
1153 		pmu_aliases_parse_eager(pmu, dirfd);
1154 
1155 	return pmu;
1156 err:
1157 	zfree(&pmu->name);
1158 	free(pmu);
1159 	return NULL;
1160 }
1161 
1162 /* Creates the PMU when sysfs scanning fails. */
perf_pmu__create_placeholder_core_pmu(struct list_head * core_pmus)1163 struct perf_pmu *perf_pmu__create_placeholder_core_pmu(struct list_head *core_pmus)
1164 {
1165 	struct perf_pmu *pmu = zalloc(sizeof(*pmu));
1166 
1167 	if (!pmu)
1168 		return NULL;
1169 
1170 	pmu->name = strdup("cpu");
1171 	if (!pmu->name) {
1172 		free(pmu);
1173 		return NULL;
1174 	}
1175 
1176 	pmu->is_core = true;
1177 	pmu->type = PERF_TYPE_RAW;
1178 	pmu->cpus = cpu_map__online();
1179 
1180 	INIT_LIST_HEAD(&pmu->format);
1181 	INIT_LIST_HEAD(&pmu->aliases);
1182 	INIT_LIST_HEAD(&pmu->caps);
1183 	list_add_tail(&pmu->list, core_pmus);
1184 	return pmu;
1185 }
1186 
perf_pmu__is_fake(const struct perf_pmu * pmu)1187 bool perf_pmu__is_fake(const struct perf_pmu *pmu)
1188 {
1189 	return pmu->type == PERF_PMU_TYPE_FAKE;
1190 }
1191 
perf_pmu__warn_invalid_formats(struct perf_pmu * pmu)1192 void perf_pmu__warn_invalid_formats(struct perf_pmu *pmu)
1193 {
1194 	struct perf_pmu_format *format;
1195 
1196 	if (pmu->formats_checked)
1197 		return;
1198 
1199 	pmu->formats_checked = true;
1200 
1201 	/* fake pmu doesn't have format list */
1202 	if (perf_pmu__is_fake(pmu))
1203 		return;
1204 
1205 	list_for_each_entry(format, &pmu->format, list) {
1206 		perf_pmu_format__load(pmu, format);
1207 		if (format->value >= PERF_PMU_FORMAT_VALUE_CONFIG_END) {
1208 			pr_warning("WARNING: '%s' format '%s' requires 'perf_event_attr::config%d'"
1209 				   "which is not supported by this version of perf!\n",
1210 				   pmu->name, format->name, format->value);
1211 			return;
1212 		}
1213 	}
1214 }
1215 
evsel__is_aux_event(const struct evsel * evsel)1216 bool evsel__is_aux_event(const struct evsel *evsel)
1217 {
1218 	struct perf_pmu *pmu;
1219 
1220 	if (evsel->needs_auxtrace_mmap)
1221 		return true;
1222 
1223 	pmu = evsel__find_pmu(evsel);
1224 	return pmu && pmu->auxtrace;
1225 }
1226 
1227 /*
1228  * Set @config_name to @val as long as the user hasn't already set or cleared it
1229  * by passing a config term on the command line.
1230  *
1231  * @val is the value to put into the bits specified by @config_name rather than
1232  * the bit pattern. It is shifted into position by this function, so to set
1233  * something to true, pass 1 for val rather than a pre shifted value.
1234  */
1235 #define field_prep(_mask, _val) (((_val) << (ffsll(_mask) - 1)) & (_mask))
evsel__set_config_if_unset(struct perf_pmu * pmu,struct evsel * evsel,const char * config_name,u64 val)1236 void evsel__set_config_if_unset(struct perf_pmu *pmu, struct evsel *evsel,
1237 				const char *config_name, u64 val)
1238 {
1239 	u64 user_bits = 0, bits;
1240 	struct evsel_config_term *term = evsel__get_config_term(evsel, CFG_CHG);
1241 
1242 	if (term)
1243 		user_bits = term->val.cfg_chg;
1244 
1245 	bits = perf_pmu__format_bits(pmu, config_name);
1246 
1247 	/* Do nothing if the user changed the value */
1248 	if (bits & user_bits)
1249 		return;
1250 
1251 	/* Otherwise replace it */
1252 	evsel->core.attr.config &= ~bits;
1253 	evsel->core.attr.config |= field_prep(bits, val);
1254 }
1255 
1256 static struct perf_pmu_format *
pmu_find_format(const struct list_head * formats,const char * name)1257 pmu_find_format(const struct list_head *formats, const char *name)
1258 {
1259 	struct perf_pmu_format *format;
1260 
1261 	list_for_each_entry(format, formats, list)
1262 		if (!strcmp(format->name, name))
1263 			return format;
1264 
1265 	return NULL;
1266 }
1267 
perf_pmu__format_bits(struct perf_pmu * pmu,const char * name)1268 __u64 perf_pmu__format_bits(struct perf_pmu *pmu, const char *name)
1269 {
1270 	struct perf_pmu_format *format = pmu_find_format(&pmu->format, name);
1271 	__u64 bits = 0;
1272 	int fbit;
1273 
1274 	if (!format)
1275 		return 0;
1276 
1277 	for_each_set_bit(fbit, format->bits, PERF_PMU_FORMAT_BITS)
1278 		bits |= 1ULL << fbit;
1279 
1280 	return bits;
1281 }
1282 
perf_pmu__format_type(struct perf_pmu * pmu,const char * name)1283 int perf_pmu__format_type(struct perf_pmu *pmu, const char *name)
1284 {
1285 	struct perf_pmu_format *format = pmu_find_format(&pmu->format, name);
1286 
1287 	if (!format)
1288 		return -1;
1289 
1290 	perf_pmu_format__load(pmu, format);
1291 	return format->value;
1292 }
1293 
1294 /*
1295  * Sets value based on the format definition (format parameter)
1296  * and unformatted value (value parameter).
1297  */
pmu_format_value(unsigned long * format,__u64 value,__u64 * v,bool zero)1298 static void pmu_format_value(unsigned long *format, __u64 value, __u64 *v,
1299 			     bool zero)
1300 {
1301 	unsigned long fbit, vbit;
1302 
1303 	for (fbit = 0, vbit = 0; fbit < PERF_PMU_FORMAT_BITS; fbit++) {
1304 
1305 		if (!test_bit(fbit, format))
1306 			continue;
1307 
1308 		if (value & (1llu << vbit++))
1309 			*v |= (1llu << fbit);
1310 		else if (zero)
1311 			*v &= ~(1llu << fbit);
1312 	}
1313 }
1314 
pmu_format_max_value(const unsigned long * format)1315 static __u64 pmu_format_max_value(const unsigned long *format)
1316 {
1317 	int w;
1318 
1319 	w = bitmap_weight(format, PERF_PMU_FORMAT_BITS);
1320 	if (!w)
1321 		return 0;
1322 	if (w < 64)
1323 		return (1ULL << w) - 1;
1324 	return -1;
1325 }
1326 
1327 /*
1328  * Term is a string term, and might be a param-term. Try to look up it's value
1329  * in the remaining terms.
1330  * - We have a term like "base-or-format-term=param-term",
1331  * - We need to find the value supplied for "param-term" (with param-term named
1332  *   in a config string) later on in the term list.
1333  */
pmu_resolve_param_term(struct parse_events_term * term,struct parse_events_terms * head_terms,__u64 * value)1334 static int pmu_resolve_param_term(struct parse_events_term *term,
1335 				  struct parse_events_terms *head_terms,
1336 				  __u64 *value)
1337 {
1338 	struct parse_events_term *t;
1339 
1340 	list_for_each_entry(t, &head_terms->terms, list) {
1341 		if (t->type_val == PARSE_EVENTS__TERM_TYPE_NUM &&
1342 		    t->config && !strcmp(t->config, term->config)) {
1343 			t->used = true;
1344 			*value = t->val.num;
1345 			return 0;
1346 		}
1347 	}
1348 
1349 	if (verbose > 0)
1350 		printf("Required parameter '%s' not specified\n", term->config);
1351 
1352 	return -1;
1353 }
1354 
pmu_formats_string(const struct list_head * formats)1355 static char *pmu_formats_string(const struct list_head *formats)
1356 {
1357 	struct perf_pmu_format *format;
1358 	char *str = NULL;
1359 	struct strbuf buf = STRBUF_INIT;
1360 	unsigned int i = 0;
1361 
1362 	if (!formats)
1363 		return NULL;
1364 
1365 	/* sysfs exported terms */
1366 	list_for_each_entry(format, formats, list)
1367 		if (strbuf_addf(&buf, i++ ? ",%s" : "%s", format->name) < 0)
1368 			goto error;
1369 
1370 	str = strbuf_detach(&buf, NULL);
1371 error:
1372 	strbuf_release(&buf);
1373 
1374 	return str;
1375 }
1376 
1377 /*
1378  * Setup one of config[12] attr members based on the
1379  * user input data - term parameter.
1380  */
pmu_config_term(const struct perf_pmu * pmu,struct perf_event_attr * attr,struct parse_events_term * term,struct parse_events_terms * head_terms,bool zero,bool apply_hardcoded,struct parse_events_error * err)1381 static int pmu_config_term(const struct perf_pmu *pmu,
1382 			   struct perf_event_attr *attr,
1383 			   struct parse_events_term *term,
1384 			   struct parse_events_terms *head_terms,
1385 			   bool zero, bool apply_hardcoded,
1386 			   struct parse_events_error *err)
1387 {
1388 	struct perf_pmu_format *format;
1389 	__u64 *vp;
1390 	__u64 val, max_val;
1391 
1392 	/*
1393 	 * If this is a parameter we've already used for parameterized-eval,
1394 	 * skip it in normal eval.
1395 	 */
1396 	if (term->used)
1397 		return 0;
1398 
1399 	/*
1400 	 * Hardcoded terms are generally handled in event parsing, which
1401 	 * traditionally have had to handle not having a PMU. An alias may
1402 	 * have hard coded config values, optionally apply them below.
1403 	 */
1404 	if (parse_events__is_hardcoded_term(term)) {
1405 		/* Config terms set all bits in the config. */
1406 		DECLARE_BITMAP(bits, PERF_PMU_FORMAT_BITS);
1407 
1408 		if (!apply_hardcoded)
1409 			return 0;
1410 
1411 		bitmap_fill(bits, PERF_PMU_FORMAT_BITS);
1412 
1413 		switch (term->type_term) {
1414 		case PARSE_EVENTS__TERM_TYPE_CONFIG:
1415 			assert(term->type_val == PARSE_EVENTS__TERM_TYPE_NUM);
1416 			pmu_format_value(bits, term->val.num, &attr->config, zero);
1417 			break;
1418 		case PARSE_EVENTS__TERM_TYPE_CONFIG1:
1419 			assert(term->type_val == PARSE_EVENTS__TERM_TYPE_NUM);
1420 			pmu_format_value(bits, term->val.num, &attr->config1, zero);
1421 			break;
1422 		case PARSE_EVENTS__TERM_TYPE_CONFIG2:
1423 			assert(term->type_val == PARSE_EVENTS__TERM_TYPE_NUM);
1424 			pmu_format_value(bits, term->val.num, &attr->config2, zero);
1425 			break;
1426 		case PARSE_EVENTS__TERM_TYPE_CONFIG3:
1427 			assert(term->type_val == PARSE_EVENTS__TERM_TYPE_NUM);
1428 			pmu_format_value(bits, term->val.num, &attr->config3, zero);
1429 			break;
1430 		case PARSE_EVENTS__TERM_TYPE_USER: /* Not hardcoded. */
1431 			return -EINVAL;
1432 		case PARSE_EVENTS__TERM_TYPE_NAME ... PARSE_EVENTS__TERM_TYPE_HARDWARE:
1433 			/* Skip non-config terms. */
1434 			break;
1435 		default:
1436 			break;
1437 		}
1438 		return 0;
1439 	}
1440 
1441 	format = pmu_find_format(&pmu->format, term->config);
1442 	if (!format) {
1443 		char *pmu_term = pmu_formats_string(&pmu->format);
1444 		char *unknown_term;
1445 		char *help_msg;
1446 
1447 		if (asprintf(&unknown_term,
1448 				"unknown term '%s' for pmu '%s'",
1449 				term->config, pmu->name) < 0)
1450 			unknown_term = NULL;
1451 		help_msg = parse_events_formats_error_string(pmu_term);
1452 		if (err) {
1453 			parse_events_error__handle(err, term->err_term,
1454 						   unknown_term,
1455 						   help_msg);
1456 		} else {
1457 			pr_debug("%s (%s)\n", unknown_term, help_msg);
1458 			free(unknown_term);
1459 		}
1460 		free(pmu_term);
1461 		return -EINVAL;
1462 	}
1463 	perf_pmu_format__load(pmu, format);
1464 	switch (format->value) {
1465 	case PERF_PMU_FORMAT_VALUE_CONFIG:
1466 		vp = &attr->config;
1467 		break;
1468 	case PERF_PMU_FORMAT_VALUE_CONFIG1:
1469 		vp = &attr->config1;
1470 		break;
1471 	case PERF_PMU_FORMAT_VALUE_CONFIG2:
1472 		vp = &attr->config2;
1473 		break;
1474 	case PERF_PMU_FORMAT_VALUE_CONFIG3:
1475 		vp = &attr->config3;
1476 		break;
1477 	default:
1478 		return -EINVAL;
1479 	}
1480 
1481 	/*
1482 	 * Either directly use a numeric term, or try to translate string terms
1483 	 * using event parameters.
1484 	 */
1485 	if (term->type_val == PARSE_EVENTS__TERM_TYPE_NUM) {
1486 		if (term->no_value &&
1487 		    bitmap_weight(format->bits, PERF_PMU_FORMAT_BITS) > 1) {
1488 			if (err) {
1489 				parse_events_error__handle(err, term->err_val,
1490 					   strdup("no value assigned for term"),
1491 					   NULL);
1492 			}
1493 			return -EINVAL;
1494 		}
1495 
1496 		val = term->val.num;
1497 	} else if (term->type_val == PARSE_EVENTS__TERM_TYPE_STR) {
1498 		if (strcmp(term->val.str, "?")) {
1499 			if (verbose > 0) {
1500 				pr_info("Invalid sysfs entry %s=%s\n",
1501 						term->config, term->val.str);
1502 			}
1503 			if (err) {
1504 				parse_events_error__handle(err, term->err_val,
1505 					strdup("expected numeric value"),
1506 					NULL);
1507 			}
1508 			return -EINVAL;
1509 		}
1510 
1511 		if (pmu_resolve_param_term(term, head_terms, &val))
1512 			return -EINVAL;
1513 	} else
1514 		return -EINVAL;
1515 
1516 	max_val = pmu_format_max_value(format->bits);
1517 	if (val > max_val) {
1518 		if (err) {
1519 			char *err_str;
1520 
1521 			if (asprintf(&err_str,
1522 				     "value too big for format (%s), maximum is %llu",
1523 				     format->name, (unsigned long long)max_val) < 0) {
1524 				err_str = strdup("value too big for format");
1525 			}
1526 			parse_events_error__handle(err, term->err_val, err_str, /*help=*/NULL);
1527 			return -EINVAL;
1528 		}
1529 		/*
1530 		 * Assume we don't care if !err, in which case the value will be
1531 		 * silently truncated.
1532 		 */
1533 	}
1534 
1535 	pmu_format_value(format->bits, val, vp, zero);
1536 	return 0;
1537 }
1538 
perf_pmu__config_terms(const struct perf_pmu * pmu,struct perf_event_attr * attr,struct parse_events_terms * terms,bool zero,bool apply_hardcoded,struct parse_events_error * err)1539 int perf_pmu__config_terms(const struct perf_pmu *pmu,
1540 			   struct perf_event_attr *attr,
1541 			   struct parse_events_terms *terms,
1542 			   bool zero, bool apply_hardcoded,
1543 			   struct parse_events_error *err)
1544 {
1545 	struct parse_events_term *term;
1546 
1547 	if (perf_pmu__is_hwmon(pmu))
1548 		return hwmon_pmu__config_terms(pmu, attr, terms, err);
1549 
1550 	list_for_each_entry(term, &terms->terms, list) {
1551 		if (pmu_config_term(pmu, attr, term, terms, zero, apply_hardcoded, err))
1552 			return -EINVAL;
1553 	}
1554 
1555 	return 0;
1556 }
1557 
1558 /*
1559  * Configures event's 'attr' parameter based on the:
1560  * 1) users input - specified in terms parameter
1561  * 2) pmu format definitions - specified by pmu parameter
1562  */
perf_pmu__config(struct perf_pmu * pmu,struct perf_event_attr * attr,struct parse_events_terms * head_terms,bool apply_hardcoded,struct parse_events_error * err)1563 int perf_pmu__config(struct perf_pmu *pmu, struct perf_event_attr *attr,
1564 		     struct parse_events_terms *head_terms,
1565 		     bool apply_hardcoded,
1566 		     struct parse_events_error *err)
1567 {
1568 	bool zero = !!pmu->perf_event_attr_init_default;
1569 
1570 	/* Fake PMU doesn't have proper terms so nothing to configure in attr. */
1571 	if (perf_pmu__is_fake(pmu))
1572 		return 0;
1573 
1574 	return perf_pmu__config_terms(pmu, attr, head_terms, zero, apply_hardcoded, err);
1575 }
1576 
pmu_find_alias(struct perf_pmu * pmu,struct parse_events_term * term)1577 static struct perf_pmu_alias *pmu_find_alias(struct perf_pmu *pmu,
1578 					     struct parse_events_term *term)
1579 {
1580 	struct perf_pmu_alias *alias;
1581 	const char *name;
1582 
1583 	if (parse_events__is_hardcoded_term(term))
1584 		return NULL;
1585 
1586 	if (term->type_val == PARSE_EVENTS__TERM_TYPE_NUM) {
1587 		if (!term->no_value)
1588 			return NULL;
1589 		if (pmu_find_format(&pmu->format, term->config))
1590 			return NULL;
1591 		name = term->config;
1592 
1593 	} else if (term->type_val == PARSE_EVENTS__TERM_TYPE_STR) {
1594 		if (strcasecmp(term->config, "event"))
1595 			return NULL;
1596 		name = term->val.str;
1597 	} else {
1598 		return NULL;
1599 	}
1600 
1601 	alias = perf_pmu__find_alias(pmu, name, /*load=*/ true);
1602 	if (alias || pmu->cpu_aliases_added)
1603 		return alias;
1604 
1605 	/* Alias doesn't exist, try to get it from the json events. */
1606 	if (pmu->events_table &&
1607 	    pmu_events_table__find_event(pmu->events_table, pmu, name,
1608 				         pmu_add_cpu_aliases_map_callback,
1609 				         pmu) == 0) {
1610 		alias = perf_pmu__find_alias(pmu, name, /*load=*/ false);
1611 	}
1612 	return alias;
1613 }
1614 
1615 
check_info_data(struct perf_pmu * pmu,struct perf_pmu_alias * alias,struct perf_pmu_info * info,struct parse_events_error * err,int column)1616 static int check_info_data(struct perf_pmu *pmu,
1617 			   struct perf_pmu_alias *alias,
1618 			   struct perf_pmu_info *info,
1619 			   struct parse_events_error *err,
1620 			   int column)
1621 {
1622 	read_alias_info(pmu, alias);
1623 	/*
1624 	 * Only one term in event definition can
1625 	 * define unit, scale and snapshot, fail
1626 	 * if there's more than one.
1627 	 */
1628 	if (info->unit && alias->unit[0]) {
1629 		parse_events_error__handle(err, column,
1630 					strdup("Attempt to set event's unit twice"),
1631 					NULL);
1632 		return -EINVAL;
1633 	}
1634 	if (info->scale && alias->scale) {
1635 		parse_events_error__handle(err, column,
1636 					strdup("Attempt to set event's scale twice"),
1637 					NULL);
1638 		return -EINVAL;
1639 	}
1640 	if (info->snapshot && alias->snapshot) {
1641 		parse_events_error__handle(err, column,
1642 					strdup("Attempt to set event snapshot twice"),
1643 					NULL);
1644 		return -EINVAL;
1645 	}
1646 
1647 	if (alias->unit[0])
1648 		info->unit = alias->unit;
1649 
1650 	if (alias->scale)
1651 		info->scale = alias->scale;
1652 
1653 	if (alias->snapshot)
1654 		info->snapshot = alias->snapshot;
1655 
1656 	return 0;
1657 }
1658 
1659 /*
1660  * Find alias in the terms list and replace it with the terms
1661  * defined for the alias
1662  */
perf_pmu__check_alias(struct perf_pmu * pmu,struct parse_events_terms * head_terms,struct perf_pmu_info * info,bool * rewrote_terms,u64 * alternate_hw_config,struct parse_events_error * err)1663 int perf_pmu__check_alias(struct perf_pmu *pmu, struct parse_events_terms *head_terms,
1664 			  struct perf_pmu_info *info, bool *rewrote_terms,
1665 			  u64 *alternate_hw_config, struct parse_events_error *err)
1666 {
1667 	struct parse_events_term *term, *h;
1668 	struct perf_pmu_alias *alias;
1669 	int ret;
1670 
1671 	*rewrote_terms = false;
1672 	info->per_pkg = false;
1673 
1674 	/*
1675 	 * Mark unit and scale as not set
1676 	 * (different from default values, see below)
1677 	 */
1678 	info->unit     = NULL;
1679 	info->scale    = 0.0;
1680 	info->snapshot = false;
1681 
1682 	if (perf_pmu__is_hwmon(pmu)) {
1683 		ret = hwmon_pmu__check_alias(head_terms, info, err);
1684 		goto out;
1685 	}
1686 
1687 	/* Fake PMU doesn't rewrite terms. */
1688 	if (perf_pmu__is_fake(pmu))
1689 		goto out;
1690 
1691 	list_for_each_entry_safe(term, h, &head_terms->terms, list) {
1692 		alias = pmu_find_alias(pmu, term);
1693 		if (!alias)
1694 			continue;
1695 		ret = pmu_alias_terms(alias, term->err_term, &term->list);
1696 		if (ret) {
1697 			parse_events_error__handle(err, term->err_term,
1698 						strdup("Failure to duplicate terms"),
1699 						NULL);
1700 			return ret;
1701 		}
1702 
1703 		*rewrote_terms = true;
1704 		ret = check_info_data(pmu, alias, info, err, term->err_term);
1705 		if (ret)
1706 			return ret;
1707 
1708 		if (alias->per_pkg)
1709 			info->per_pkg = true;
1710 
1711 		if (term->alternate_hw_config)
1712 			*alternate_hw_config = term->val.num;
1713 
1714 		list_del_init(&term->list);
1715 		parse_events_term__delete(term);
1716 	}
1717 out:
1718 	/*
1719 	 * if no unit or scale found in aliases, then
1720 	 * set defaults as for evsel
1721 	 * unit cannot left to NULL
1722 	 */
1723 	if (info->unit == NULL)
1724 		info->unit   = "";
1725 
1726 	if (info->scale == 0.0)
1727 		info->scale  = 1.0;
1728 
1729 	return 0;
1730 }
1731 
1732 struct find_event_args {
1733 	const char *event;
1734 	void *state;
1735 	pmu_event_callback cb;
1736 };
1737 
find_event_callback(void * state,struct pmu_event_info * info)1738 static int find_event_callback(void *state, struct pmu_event_info *info)
1739 {
1740 	struct find_event_args *args = state;
1741 
1742 	if (!strcmp(args->event, info->name))
1743 		return args->cb(args->state, info);
1744 
1745 	return 0;
1746 }
1747 
perf_pmu__find_event(struct perf_pmu * pmu,const char * event,void * state,pmu_event_callback cb)1748 int perf_pmu__find_event(struct perf_pmu *pmu, const char *event, void *state, pmu_event_callback cb)
1749 {
1750 	struct find_event_args args = {
1751 		.event = event,
1752 		.state = state,
1753 		.cb = cb,
1754 	};
1755 
1756 	/* Sub-optimal, but function is only used by tests. */
1757 	return perf_pmu__for_each_event(pmu, /*skip_duplicate_pmus=*/ false,
1758 					&args, find_event_callback);
1759 }
1760 
perf_pmu__del_formats(struct list_head * formats)1761 static void perf_pmu__del_formats(struct list_head *formats)
1762 {
1763 	struct perf_pmu_format *fmt, *tmp;
1764 
1765 	list_for_each_entry_safe(fmt, tmp, formats, list) {
1766 		list_del(&fmt->list);
1767 		zfree(&fmt->name);
1768 		free(fmt);
1769 	}
1770 }
1771 
perf_pmu__has_format(const struct perf_pmu * pmu,const char * name)1772 bool perf_pmu__has_format(const struct perf_pmu *pmu, const char *name)
1773 {
1774 	struct perf_pmu_format *format;
1775 
1776 	list_for_each_entry(format, &pmu->format, list) {
1777 		if (!strcmp(format->name, name))
1778 			return true;
1779 	}
1780 	return false;
1781 }
1782 
perf_pmu__for_each_format(struct perf_pmu * pmu,void * state,pmu_format_callback cb)1783 int perf_pmu__for_each_format(struct perf_pmu *pmu, void *state, pmu_format_callback cb)
1784 {
1785 	static const char *const terms[] = {
1786 		"config=0..0xffffffffffffffff",
1787 		"config1=0..0xffffffffffffffff",
1788 		"config2=0..0xffffffffffffffff",
1789 		"config3=0..0xffffffffffffffff",
1790 		"name=string",
1791 		"period=number",
1792 		"freq=number",
1793 		"branch_type=(u|k|hv|any|...)",
1794 		"time",
1795 		"call-graph=(fp|dwarf|lbr)",
1796 		"stack-size=number",
1797 		"max-stack=number",
1798 		"nr=number",
1799 		"inherit",
1800 		"no-inherit",
1801 		"overwrite",
1802 		"no-overwrite",
1803 		"percore",
1804 		"aux-output",
1805 		"aux-action=(pause|resume|start-paused)",
1806 		"aux-sample-size=number",
1807 	};
1808 	struct perf_pmu_format *format;
1809 	int ret;
1810 
1811 	/*
1812 	 * max-events and driver-config are missing above as are the internal
1813 	 * types user, metric-id, raw, legacy cache and hardware. Assert against
1814 	 * the enum parse_events__term_type so they are kept in sync.
1815 	 */
1816 	_Static_assert(ARRAY_SIZE(terms) == __PARSE_EVENTS__TERM_TYPE_NR - 6,
1817 		       "perf_pmu__for_each_format()'s terms must be kept in sync with enum parse_events__term_type");
1818 	list_for_each_entry(format, &pmu->format, list) {
1819 		perf_pmu_format__load(pmu, format);
1820 		ret = cb(state, format->name, (int)format->value, format->bits);
1821 		if (ret)
1822 			return ret;
1823 	}
1824 	if (!pmu->is_core)
1825 		return 0;
1826 
1827 	for (size_t i = 0; i < ARRAY_SIZE(terms); i++) {
1828 		int config = PERF_PMU_FORMAT_VALUE_CONFIG;
1829 
1830 		if (i < PERF_PMU_FORMAT_VALUE_CONFIG_END)
1831 			config = i;
1832 
1833 		ret = cb(state, terms[i], config, /*bits=*/NULL);
1834 		if (ret)
1835 			return ret;
1836 	}
1837 	return 0;
1838 }
1839 
is_pmu_core(const char * name)1840 bool is_pmu_core(const char *name)
1841 {
1842 	return !strcmp(name, "cpu") || !strcmp(name, "cpum_cf") || is_sysfs_pmu_core(name);
1843 }
1844 
perf_pmu__supports_legacy_cache(const struct perf_pmu * pmu)1845 bool perf_pmu__supports_legacy_cache(const struct perf_pmu *pmu)
1846 {
1847 	return pmu->is_core;
1848 }
1849 
perf_pmu__auto_merge_stats(const struct perf_pmu * pmu)1850 bool perf_pmu__auto_merge_stats(const struct perf_pmu *pmu)
1851 {
1852 	return !pmu->is_core || perf_pmus__num_core_pmus() == 1;
1853 }
1854 
perf_pmu__have_event(struct perf_pmu * pmu,const char * name)1855 bool perf_pmu__have_event(struct perf_pmu *pmu, const char *name)
1856 {
1857 	if (!name)
1858 		return false;
1859 	if (perf_pmu__is_tool(pmu) && tool_pmu__skip_event(name))
1860 		return false;
1861 	if (perf_pmu__is_hwmon(pmu))
1862 		return hwmon_pmu__have_event(pmu, name);
1863 	if (perf_pmu__find_alias(pmu, name, /*load=*/ true) != NULL)
1864 		return true;
1865 	if (pmu->cpu_aliases_added || !pmu->events_table)
1866 		return false;
1867 	return pmu_events_table__find_event(pmu->events_table, pmu, name, NULL, NULL) == 0;
1868 }
1869 
perf_pmu__num_events(struct perf_pmu * pmu)1870 size_t perf_pmu__num_events(struct perf_pmu *pmu)
1871 {
1872 	size_t nr;
1873 
1874 	if (perf_pmu__is_hwmon(pmu))
1875 		return hwmon_pmu__num_events(pmu);
1876 
1877 	pmu_aliases_parse(pmu);
1878 	nr = pmu->sysfs_aliases + pmu->sys_json_aliases;
1879 
1880 	if (pmu->cpu_aliases_added)
1881 		 nr += pmu->cpu_json_aliases;
1882 	else if (pmu->events_table)
1883 		nr += pmu_events_table__num_events(pmu->events_table, pmu) -
1884 			pmu->cpu_common_json_aliases;
1885 	else
1886 		assert(pmu->cpu_json_aliases == 0 && pmu->cpu_common_json_aliases == 0);
1887 
1888 	if (perf_pmu__is_tool(pmu))
1889 		nr -= tool_pmu__num_skip_events();
1890 
1891 	return pmu->selectable ? nr + 1 : nr;
1892 }
1893 
sub_non_neg(int a,int b)1894 static int sub_non_neg(int a, int b)
1895 {
1896 	if (b > a)
1897 		return 0;
1898 	return a - b;
1899 }
1900 
format_alias(char * buf,int len,const struct perf_pmu * pmu,const struct perf_pmu_alias * alias,bool skip_duplicate_pmus)1901 static char *format_alias(char *buf, int len, const struct perf_pmu *pmu,
1902 			  const struct perf_pmu_alias *alias, bool skip_duplicate_pmus)
1903 {
1904 	struct parse_events_term *term;
1905 	size_t pmu_name_len = pmu_deduped_name_len(pmu, pmu->name,
1906 						   skip_duplicate_pmus);
1907 	int used = snprintf(buf, len, "%.*s/%s", (int)pmu_name_len, pmu->name, alias->name);
1908 
1909 	list_for_each_entry(term, &alias->terms.terms, list) {
1910 		if (term->type_val == PARSE_EVENTS__TERM_TYPE_STR)
1911 			used += snprintf(buf + used, sub_non_neg(len, used),
1912 					",%s=%s", term->config,
1913 					term->val.str);
1914 	}
1915 
1916 	if (sub_non_neg(len, used) > 0) {
1917 		buf[used] = '/';
1918 		used++;
1919 	}
1920 	if (sub_non_neg(len, used) > 0) {
1921 		buf[used] = '\0';
1922 		used++;
1923 	} else
1924 		buf[len - 1] = '\0';
1925 
1926 	return buf;
1927 }
1928 
perf_pmu__for_each_event(struct perf_pmu * pmu,bool skip_duplicate_pmus,void * state,pmu_event_callback cb)1929 int perf_pmu__for_each_event(struct perf_pmu *pmu, bool skip_duplicate_pmus,
1930 			     void *state, pmu_event_callback cb)
1931 {
1932 	char buf[1024];
1933 	struct perf_pmu_alias *event;
1934 	struct pmu_event_info info = {
1935 		.pmu = pmu,
1936 		.event_type_desc = "Kernel PMU event",
1937 	};
1938 	int ret = 0;
1939 	struct strbuf sb;
1940 
1941 	if (perf_pmu__is_hwmon(pmu))
1942 		return hwmon_pmu__for_each_event(pmu, state, cb);
1943 
1944 	strbuf_init(&sb, /*hint=*/ 0);
1945 	pmu_aliases_parse(pmu);
1946 	pmu_add_cpu_aliases(pmu);
1947 	list_for_each_entry(event, &pmu->aliases, list) {
1948 		size_t buf_used, pmu_name_len;
1949 
1950 		if (perf_pmu__is_tool(pmu) && tool_pmu__skip_event(event->name))
1951 			continue;
1952 
1953 		info.pmu_name = event->pmu_name ?: pmu->name;
1954 		pmu_name_len = pmu_deduped_name_len(pmu, info.pmu_name,
1955 						    skip_duplicate_pmus);
1956 		info.alias = NULL;
1957 		if (event->desc) {
1958 			info.name = event->name;
1959 			buf_used = 0;
1960 		} else {
1961 			info.name = format_alias(buf, sizeof(buf), pmu, event,
1962 						 skip_duplicate_pmus);
1963 			if (pmu->is_core) {
1964 				info.alias = info.name;
1965 				info.name = event->name;
1966 			}
1967 			buf_used = strlen(buf) + 1;
1968 		}
1969 		info.scale_unit = NULL;
1970 		if (strlen(event->unit) || event->scale != 1.0) {
1971 			info.scale_unit = buf + buf_used;
1972 			buf_used += snprintf(buf + buf_used, sizeof(buf) - buf_used,
1973 					"%G%s", event->scale, event->unit) + 1;
1974 		}
1975 		info.desc = event->desc;
1976 		info.long_desc = event->long_desc;
1977 		info.encoding_desc = buf + buf_used;
1978 		parse_events_terms__to_strbuf(&event->terms, &sb);
1979 		buf_used += snprintf(buf + buf_used, sizeof(buf) - buf_used,
1980 				"%.*s/%s/", (int)pmu_name_len, info.pmu_name, sb.buf) + 1;
1981 		info.topic = event->topic;
1982 		info.str = sb.buf;
1983 		info.deprecated = event->deprecated;
1984 		ret = cb(state, &info);
1985 		if (ret)
1986 			goto out;
1987 		strbuf_setlen(&sb, /*len=*/ 0);
1988 	}
1989 	if (pmu->selectable) {
1990 		info.name = buf;
1991 		snprintf(buf, sizeof(buf), "%s//", pmu->name);
1992 		info.alias = NULL;
1993 		info.scale_unit = NULL;
1994 		info.desc = NULL;
1995 		info.long_desc = NULL;
1996 		info.encoding_desc = NULL;
1997 		info.topic = NULL;
1998 		info.pmu_name = pmu->name;
1999 		info.deprecated = false;
2000 		ret = cb(state, &info);
2001 	}
2002 out:
2003 	strbuf_release(&sb);
2004 	return ret;
2005 }
2006 
perf_pmu___name_match(const struct perf_pmu * pmu,const char * to_match,bool wildcard)2007 static bool perf_pmu___name_match(const struct perf_pmu *pmu, const char *to_match, bool wildcard)
2008 {
2009 	const char *names[2] = {
2010 		pmu->name,
2011 		pmu->alias_name,
2012 	};
2013 	if (pmu->is_core) {
2014 		for (size_t i = 0; i < ARRAY_SIZE(names); i++) {
2015 			const char *name = names[i];
2016 
2017 			if (!name)
2018 				continue;
2019 
2020 			if (!strcmp(name, to_match)) {
2021 				/* Exact name match. */
2022 				return true;
2023 			}
2024 		}
2025 		if (!strcmp(to_match, "default_core")) {
2026 			/*
2027 			 * jevents and tests use default_core as a marker for any core
2028 			 * PMU as the PMU name varies across architectures.
2029 			 */
2030 			return true;
2031 		}
2032 		return false;
2033 	}
2034 	if (!pmu->is_uncore) {
2035 		/*
2036 		 * PMU isn't core or uncore, some kind of broken CPU mask
2037 		 * situation. Only match exact name.
2038 		 */
2039 		for (size_t i = 0; i < ARRAY_SIZE(names); i++) {
2040 			const char *name = names[i];
2041 
2042 			if (!name)
2043 				continue;
2044 
2045 			if (!strcmp(name, to_match)) {
2046 				/* Exact name match. */
2047 				return true;
2048 			}
2049 		}
2050 		return false;
2051 	}
2052 	for (size_t i = 0; i < ARRAY_SIZE(names); i++) {
2053 		const char *name = names[i];
2054 
2055 		if (wildcard && perf_pmu__match_wildcard_uncore(name, to_match))
2056 			return true;
2057 		if (!wildcard && perf_pmu__match_ignoring_suffix_uncore(name, to_match))
2058 			return true;
2059 	}
2060 	return false;
2061 }
2062 
2063 /**
2064  * perf_pmu__name_wildcard_match - Called by the jevents generated code to see
2065  *                                 if pmu matches the json to_match string.
2066  * @pmu: The pmu whose name/alias to match.
2067  * @to_match: The possible match to pmu_name.
2068  */
perf_pmu__name_wildcard_match(const struct perf_pmu * pmu,const char * to_match)2069 bool perf_pmu__name_wildcard_match(const struct perf_pmu *pmu, const char *to_match)
2070 {
2071 	return perf_pmu___name_match(pmu, to_match, /*wildcard=*/true);
2072 }
2073 
2074 /**
2075  * perf_pmu__name_no_suffix_match - Does pmu's name match to_match ignoring any
2076  *                                  trailing suffix on the pmu_name and/or tok?
2077  * @pmu: The pmu whose name/alias to match.
2078  * @to_match: The possible match to pmu_name.
2079  */
perf_pmu__name_no_suffix_match(const struct perf_pmu * pmu,const char * to_match)2080 bool perf_pmu__name_no_suffix_match(const struct perf_pmu *pmu, const char *to_match)
2081 {
2082 	return perf_pmu___name_match(pmu, to_match, /*wildcard=*/false);
2083 }
2084 
perf_pmu__is_software(const struct perf_pmu * pmu)2085 bool perf_pmu__is_software(const struct perf_pmu *pmu)
2086 {
2087 	const char *known_sw_pmus[] = {
2088 		"kprobe",
2089 		"msr",
2090 		"uprobe",
2091 	};
2092 
2093 	if (pmu->is_core || pmu->is_uncore || pmu->auxtrace)
2094 		return false;
2095 	switch (pmu->type) {
2096 	case PERF_TYPE_HARDWARE:	return false;
2097 	case PERF_TYPE_SOFTWARE:	return true;
2098 	case PERF_TYPE_TRACEPOINT:	return true;
2099 	case PERF_TYPE_HW_CACHE:	return false;
2100 	case PERF_TYPE_RAW:		return false;
2101 	case PERF_TYPE_BREAKPOINT:	return true;
2102 	case PERF_PMU_TYPE_TOOL:	return true;
2103 	default: break;
2104 	}
2105 	for (size_t i = 0; i < ARRAY_SIZE(known_sw_pmus); i++) {
2106 		if (!strcmp(pmu->name, known_sw_pmus[i]))
2107 			return true;
2108 	}
2109 	return false;
2110 }
2111 
perf_pmu__open_file(const struct perf_pmu * pmu,const char * name)2112 FILE *perf_pmu__open_file(const struct perf_pmu *pmu, const char *name)
2113 {
2114 	char path[PATH_MAX];
2115 
2116 	if (!perf_pmu__pathname_scnprintf(path, sizeof(path), pmu->name, name) ||
2117 	    !file_available(path))
2118 		return NULL;
2119 
2120 	return fopen(path, "r");
2121 }
2122 
perf_pmu__open_file_at(const struct perf_pmu * pmu,int dirfd,const char * name)2123 FILE *perf_pmu__open_file_at(const struct perf_pmu *pmu, int dirfd, const char *name)
2124 {
2125 	int fd;
2126 
2127 	fd = perf_pmu__pathname_fd(dirfd, pmu->name, name, O_RDONLY);
2128 	if (fd < 0)
2129 		return NULL;
2130 
2131 	return fdopen(fd, "r");
2132 }
2133 
perf_pmu__scan_file(const struct perf_pmu * pmu,const char * name,const char * fmt,...)2134 int perf_pmu__scan_file(const struct perf_pmu *pmu, const char *name, const char *fmt,
2135 			...)
2136 {
2137 	va_list args;
2138 	FILE *file;
2139 	int ret = EOF;
2140 
2141 	va_start(args, fmt);
2142 	file = perf_pmu__open_file(pmu, name);
2143 	if (file) {
2144 		ret = vfscanf(file, fmt, args);
2145 		fclose(file);
2146 	}
2147 	va_end(args);
2148 	return ret;
2149 }
2150 
perf_pmu__scan_file_at(const struct perf_pmu * pmu,int dirfd,const char * name,const char * fmt,...)2151 int perf_pmu__scan_file_at(const struct perf_pmu *pmu, int dirfd, const char *name,
2152 			   const char *fmt, ...)
2153 {
2154 	va_list args;
2155 	FILE *file;
2156 	int ret = EOF;
2157 
2158 	va_start(args, fmt);
2159 	file = perf_pmu__open_file_at(pmu, dirfd, name);
2160 	if (file) {
2161 		ret = vfscanf(file, fmt, args);
2162 		fclose(file);
2163 	}
2164 	va_end(args);
2165 	return ret;
2166 }
2167 
perf_pmu__file_exists(const struct perf_pmu * pmu,const char * name)2168 bool perf_pmu__file_exists(const struct perf_pmu *pmu, const char *name)
2169 {
2170 	char path[PATH_MAX];
2171 
2172 	if (!perf_pmu__pathname_scnprintf(path, sizeof(path), pmu->name, name))
2173 		return false;
2174 
2175 	return file_available(path);
2176 }
2177 
perf_pmu__new_caps(struct list_head * list,char * name,char * value)2178 static int perf_pmu__new_caps(struct list_head *list, char *name, char *value)
2179 {
2180 	struct perf_pmu_caps *caps = zalloc(sizeof(*caps));
2181 
2182 	if (!caps)
2183 		return -ENOMEM;
2184 
2185 	caps->name = strdup(name);
2186 	if (!caps->name)
2187 		goto free_caps;
2188 	caps->value = strndup(value, strlen(value) - 1);
2189 	if (!caps->value)
2190 		goto free_name;
2191 	list_add_tail(&caps->list, list);
2192 	return 0;
2193 
2194 free_name:
2195 	zfree(&caps->name);
2196 free_caps:
2197 	free(caps);
2198 
2199 	return -ENOMEM;
2200 }
2201 
perf_pmu__del_caps(struct perf_pmu * pmu)2202 static void perf_pmu__del_caps(struct perf_pmu *pmu)
2203 {
2204 	struct perf_pmu_caps *caps, *tmp;
2205 
2206 	list_for_each_entry_safe(caps, tmp, &pmu->caps, list) {
2207 		list_del(&caps->list);
2208 		zfree(&caps->name);
2209 		zfree(&caps->value);
2210 		free(caps);
2211 	}
2212 }
2213 
2214 /*
2215  * Reading/parsing the given pmu capabilities, which should be located at:
2216  * /sys/bus/event_source/devices/<dev>/caps as sysfs group attributes.
2217  * Return the number of capabilities
2218  */
perf_pmu__caps_parse(struct perf_pmu * pmu)2219 int perf_pmu__caps_parse(struct perf_pmu *pmu)
2220 {
2221 	char caps_path[PATH_MAX];
2222 	struct io_dir caps_dir;
2223 	struct io_dirent64 *evt_ent;
2224 	int caps_fd;
2225 
2226 	if (pmu->caps_initialized)
2227 		return pmu->nr_caps;
2228 
2229 	pmu->nr_caps = 0;
2230 
2231 	if (!perf_pmu__pathname_scnprintf(caps_path, sizeof(caps_path), pmu->name, "caps"))
2232 		return -1;
2233 
2234 	caps_fd = open(caps_path, O_CLOEXEC | O_DIRECTORY | O_RDONLY);
2235 	if (caps_fd == -1) {
2236 		pmu->caps_initialized = true;
2237 		return 0;	/* no error if caps does not exist */
2238 	}
2239 
2240 	io_dir__init(&caps_dir, caps_fd);
2241 
2242 	while ((evt_ent = io_dir__readdir(&caps_dir)) != NULL) {
2243 		char *name = evt_ent->d_name;
2244 		char value[128];
2245 		FILE *file;
2246 		int fd;
2247 
2248 		if (io_dir__is_dir(&caps_dir, evt_ent))
2249 			continue;
2250 
2251 		fd = openat(caps_fd, name, O_RDONLY);
2252 		if (fd == -1)
2253 			continue;
2254 		file = fdopen(fd, "r");
2255 		if (!file) {
2256 			close(fd);
2257 			continue;
2258 		}
2259 
2260 		if (!fgets(value, sizeof(value), file) ||
2261 		    (perf_pmu__new_caps(&pmu->caps, name, value) < 0)) {
2262 			fclose(file);
2263 			continue;
2264 		}
2265 
2266 		pmu->nr_caps++;
2267 		fclose(file);
2268 	}
2269 
2270 	close(caps_fd);
2271 
2272 	pmu->caps_initialized = true;
2273 	return pmu->nr_caps;
2274 }
2275 
perf_pmu__compute_config_masks(struct perf_pmu * pmu)2276 static void perf_pmu__compute_config_masks(struct perf_pmu *pmu)
2277 {
2278 	struct perf_pmu_format *format;
2279 
2280 	if (pmu->config_masks_computed)
2281 		return;
2282 
2283 	list_for_each_entry(format, &pmu->format, list)	{
2284 		unsigned int i;
2285 		__u64 *mask;
2286 
2287 		if (format->value >= PERF_PMU_FORMAT_VALUE_CONFIG_END)
2288 			continue;
2289 
2290 		pmu->config_masks_present = true;
2291 		mask = &pmu->config_masks[format->value];
2292 
2293 		for_each_set_bit(i, format->bits, PERF_PMU_FORMAT_BITS)
2294 			*mask |= 1ULL << i;
2295 	}
2296 	pmu->config_masks_computed = true;
2297 }
2298 
perf_pmu__warn_invalid_config(struct perf_pmu * pmu,__u64 config,const char * name,int config_num,const char * config_name)2299 void perf_pmu__warn_invalid_config(struct perf_pmu *pmu, __u64 config,
2300 				   const char *name, int config_num,
2301 				   const char *config_name)
2302 {
2303 	__u64 bits;
2304 	char buf[100];
2305 
2306 	perf_pmu__compute_config_masks(pmu);
2307 
2308 	/*
2309 	 * Kernel doesn't export any valid format bits.
2310 	 */
2311 	if (!pmu->config_masks_present)
2312 		return;
2313 
2314 	bits = config & ~pmu->config_masks[config_num];
2315 	if (bits == 0)
2316 		return;
2317 
2318 	bitmap_scnprintf((unsigned long *)&bits, sizeof(bits) * 8, buf, sizeof(buf));
2319 
2320 	pr_warning("WARNING: event '%s' not valid (bits %s of %s "
2321 		   "'%llx' not supported by kernel)!\n",
2322 		   name ?: "N/A", buf, config_name, config);
2323 }
2324 
perf_pmu__wildcard_match(const struct perf_pmu * pmu,const char * wildcard_to_match)2325 bool perf_pmu__wildcard_match(const struct perf_pmu *pmu, const char *wildcard_to_match)
2326 {
2327 	const char *names[2] = {
2328 		pmu->name,
2329 		pmu->alias_name,
2330 	};
2331 	bool need_fnmatch = strisglob(wildcard_to_match);
2332 
2333 	if (!strncmp(wildcard_to_match, "uncore_", 7))
2334 		wildcard_to_match += 7;
2335 
2336 	for (size_t i = 0; i < ARRAY_SIZE(names); i++) {
2337 		const char *pmu_name = names[i];
2338 
2339 		if (!pmu_name)
2340 			continue;
2341 
2342 		if (!strncmp(pmu_name, "uncore_", 7))
2343 			pmu_name += 7;
2344 
2345 		if (perf_pmu__match_wildcard(pmu_name, wildcard_to_match) ||
2346 		    (need_fnmatch && !fnmatch(wildcard_to_match, pmu_name, 0)))
2347 			return true;
2348 	}
2349 	return false;
2350 }
2351 
perf_pmu__event_source_devices_scnprintf(char * pathname,size_t size)2352 int perf_pmu__event_source_devices_scnprintf(char *pathname, size_t size)
2353 {
2354 	const char *sysfs = sysfs__mountpoint();
2355 
2356 	if (!sysfs)
2357 		return 0;
2358 	return scnprintf(pathname, size, "%s/bus/event_source/devices/", sysfs);
2359 }
2360 
perf_pmu__event_source_devices_fd(void)2361 int perf_pmu__event_source_devices_fd(void)
2362 {
2363 	char path[PATH_MAX];
2364 	const char *sysfs = sysfs__mountpoint();
2365 
2366 	if (!sysfs)
2367 		return -1;
2368 
2369 	scnprintf(path, sizeof(path), "%s/bus/event_source/devices/", sysfs);
2370 	return open(path, O_DIRECTORY);
2371 }
2372 
2373 /*
2374  * Fill 'buf' with the path to a file or folder in 'pmu_name' in
2375  * sysfs. For example if pmu_name = "cs_etm" and 'filename' = "format"
2376  * then pathname will be filled with
2377  * "/sys/bus/event_source/devices/cs_etm/format"
2378  *
2379  * Return 0 if the sysfs mountpoint couldn't be found, if no characters were
2380  * written or if the buffer size is exceeded.
2381  */
perf_pmu__pathname_scnprintf(char * buf,size_t size,const char * pmu_name,const char * filename)2382 int perf_pmu__pathname_scnprintf(char *buf, size_t size,
2383 				 const char *pmu_name, const char *filename)
2384 {
2385 	size_t len;
2386 
2387 	len = perf_pmu__event_source_devices_scnprintf(buf, size);
2388 	if (!len || (len + strlen(pmu_name) + strlen(filename) + 1)  >= size)
2389 		return 0;
2390 
2391 	return scnprintf(buf + len, size - len, "%s/%s", pmu_name, filename);
2392 }
2393 
perf_pmu__pathname_fd(int dirfd,const char * pmu_name,const char * filename,int flags)2394 int perf_pmu__pathname_fd(int dirfd, const char *pmu_name, const char *filename, int flags)
2395 {
2396 	char path[PATH_MAX];
2397 
2398 	scnprintf(path, sizeof(path), "%s/%s", pmu_name, filename);
2399 	return openat(dirfd, path, flags);
2400 }
2401 
perf_pmu__delete(struct perf_pmu * pmu)2402 void perf_pmu__delete(struct perf_pmu *pmu)
2403 {
2404 	if (perf_pmu__is_hwmon(pmu))
2405 		hwmon_pmu__exit(pmu);
2406 
2407 	perf_pmu__del_formats(&pmu->format);
2408 	perf_pmu__del_aliases(pmu);
2409 	perf_pmu__del_caps(pmu);
2410 
2411 	perf_cpu_map__put(pmu->cpus);
2412 
2413 	zfree(&pmu->name);
2414 	zfree(&pmu->alias_name);
2415 	zfree(&pmu->id);
2416 	free(pmu);
2417 }
2418 
perf_pmu__name_from_config(struct perf_pmu * pmu,u64 config)2419 const char *perf_pmu__name_from_config(struct perf_pmu *pmu, u64 config)
2420 {
2421 	struct perf_pmu_alias *event;
2422 
2423 	if (!pmu)
2424 		return NULL;
2425 
2426 	pmu_aliases_parse(pmu);
2427 	pmu_add_cpu_aliases(pmu);
2428 	list_for_each_entry(event, &pmu->aliases, list) {
2429 		struct perf_event_attr attr = {.config = 0,};
2430 
2431 		int ret = perf_pmu__config(pmu, &attr, &event->terms, /*apply_hardcoded=*/true,
2432 					   /*err=*/NULL);
2433 
2434 		if (ret == 0 && config == attr.config)
2435 			return event->name;
2436 	}
2437 	return NULL;
2438 }
2439