xref: /openbmc/linux/tools/perf/util/parse-events.c (revision bbecb07f)
1 // SPDX-License-Identifier: GPL-2.0
2 #include <linux/hw_breakpoint.h>
3 #include <linux/err.h>
4 #include <dirent.h>
5 #include <errno.h>
6 #include <sys/ioctl.h>
7 #include <sys/param.h>
8 #include "term.h"
9 #include "../perf.h"
10 #include "evlist.h"
11 #include "evsel.h"
12 #include <subcmd/parse-options.h>
13 #include "parse-events.h"
14 #include <subcmd/exec-cmd.h>
15 #include "string2.h"
16 #include "strlist.h"
17 #include "symbol.h"
18 #include "cache.h"
19 #include "header.h"
20 #include "bpf-loader.h"
21 #include "debug.h"
22 #include <api/fs/tracing_path.h>
23 #include "parse-events-bison.h"
24 #define YY_EXTRA_TYPE int
25 #include "parse-events-flex.h"
26 #include "pmu.h"
27 #include "thread_map.h"
28 #include "cpumap.h"
29 #include "probe-file.h"
30 #include "asm/bug.h"
31 #include "util/parse-branch-options.h"
32 #include "metricgroup.h"
33 
34 #define MAX_NAME_LEN 100
35 
36 #ifdef PARSER_DEBUG
37 extern int parse_events_debug;
38 #endif
39 int parse_events_parse(void *parse_state, void *scanner);
40 static int get_config_terms(struct list_head *head_config,
41 			    struct list_head *head_terms __maybe_unused);
42 
43 static struct perf_pmu_event_symbol *perf_pmu_events_list;
44 /*
45  * The variable indicates the number of supported pmu event symbols.
46  * 0 means not initialized and ready to init
47  * -1 means failed to init, don't try anymore
48  * >0 is the number of supported pmu event symbols
49  */
50 static int perf_pmu_events_list_num;
51 
52 struct event_symbol event_symbols_hw[PERF_COUNT_HW_MAX] = {
53 	[PERF_COUNT_HW_CPU_CYCLES] = {
54 		.symbol = "cpu-cycles",
55 		.alias  = "cycles",
56 	},
57 	[PERF_COUNT_HW_INSTRUCTIONS] = {
58 		.symbol = "instructions",
59 		.alias  = "",
60 	},
61 	[PERF_COUNT_HW_CACHE_REFERENCES] = {
62 		.symbol = "cache-references",
63 		.alias  = "",
64 	},
65 	[PERF_COUNT_HW_CACHE_MISSES] = {
66 		.symbol = "cache-misses",
67 		.alias  = "",
68 	},
69 	[PERF_COUNT_HW_BRANCH_INSTRUCTIONS] = {
70 		.symbol = "branch-instructions",
71 		.alias  = "branches",
72 	},
73 	[PERF_COUNT_HW_BRANCH_MISSES] = {
74 		.symbol = "branch-misses",
75 		.alias  = "",
76 	},
77 	[PERF_COUNT_HW_BUS_CYCLES] = {
78 		.symbol = "bus-cycles",
79 		.alias  = "",
80 	},
81 	[PERF_COUNT_HW_STALLED_CYCLES_FRONTEND] = {
82 		.symbol = "stalled-cycles-frontend",
83 		.alias  = "idle-cycles-frontend",
84 	},
85 	[PERF_COUNT_HW_STALLED_CYCLES_BACKEND] = {
86 		.symbol = "stalled-cycles-backend",
87 		.alias  = "idle-cycles-backend",
88 	},
89 	[PERF_COUNT_HW_REF_CPU_CYCLES] = {
90 		.symbol = "ref-cycles",
91 		.alias  = "",
92 	},
93 };
94 
95 struct event_symbol event_symbols_sw[PERF_COUNT_SW_MAX] = {
96 	[PERF_COUNT_SW_CPU_CLOCK] = {
97 		.symbol = "cpu-clock",
98 		.alias  = "",
99 	},
100 	[PERF_COUNT_SW_TASK_CLOCK] = {
101 		.symbol = "task-clock",
102 		.alias  = "",
103 	},
104 	[PERF_COUNT_SW_PAGE_FAULTS] = {
105 		.symbol = "page-faults",
106 		.alias  = "faults",
107 	},
108 	[PERF_COUNT_SW_CONTEXT_SWITCHES] = {
109 		.symbol = "context-switches",
110 		.alias  = "cs",
111 	},
112 	[PERF_COUNT_SW_CPU_MIGRATIONS] = {
113 		.symbol = "cpu-migrations",
114 		.alias  = "migrations",
115 	},
116 	[PERF_COUNT_SW_PAGE_FAULTS_MIN] = {
117 		.symbol = "minor-faults",
118 		.alias  = "",
119 	},
120 	[PERF_COUNT_SW_PAGE_FAULTS_MAJ] = {
121 		.symbol = "major-faults",
122 		.alias  = "",
123 	},
124 	[PERF_COUNT_SW_ALIGNMENT_FAULTS] = {
125 		.symbol = "alignment-faults",
126 		.alias  = "",
127 	},
128 	[PERF_COUNT_SW_EMULATION_FAULTS] = {
129 		.symbol = "emulation-faults",
130 		.alias  = "",
131 	},
132 	[PERF_COUNT_SW_DUMMY] = {
133 		.symbol = "dummy",
134 		.alias  = "",
135 	},
136 	[PERF_COUNT_SW_BPF_OUTPUT] = {
137 		.symbol = "bpf-output",
138 		.alias  = "",
139 	},
140 };
141 
142 #define __PERF_EVENT_FIELD(config, name) \
143 	((config & PERF_EVENT_##name##_MASK) >> PERF_EVENT_##name##_SHIFT)
144 
145 #define PERF_EVENT_RAW(config)		__PERF_EVENT_FIELD(config, RAW)
146 #define PERF_EVENT_CONFIG(config)	__PERF_EVENT_FIELD(config, CONFIG)
147 #define PERF_EVENT_TYPE(config)		__PERF_EVENT_FIELD(config, TYPE)
148 #define PERF_EVENT_ID(config)		__PERF_EVENT_FIELD(config, EVENT)
149 
150 #define for_each_subsystem(sys_dir, sys_dirent)			\
151 	while ((sys_dirent = readdir(sys_dir)) != NULL)		\
152 		if (sys_dirent->d_type == DT_DIR &&		\
153 		    (strcmp(sys_dirent->d_name, ".")) &&	\
154 		    (strcmp(sys_dirent->d_name, "..")))
155 
156 static int tp_event_has_id(struct dirent *sys_dir, struct dirent *evt_dir)
157 {
158 	char evt_path[MAXPATHLEN];
159 	int fd;
160 
161 	snprintf(evt_path, MAXPATHLEN, "%s/%s/%s/id", tracing_events_path,
162 			sys_dir->d_name, evt_dir->d_name);
163 	fd = open(evt_path, O_RDONLY);
164 	if (fd < 0)
165 		return -EINVAL;
166 	close(fd);
167 
168 	return 0;
169 }
170 
171 #define for_each_event(sys_dirent, evt_dir, evt_dirent)		\
172 	while ((evt_dirent = readdir(evt_dir)) != NULL)		\
173 		if (evt_dirent->d_type == DT_DIR &&		\
174 		    (strcmp(evt_dirent->d_name, ".")) &&	\
175 		    (strcmp(evt_dirent->d_name, "..")) &&	\
176 		    (!tp_event_has_id(sys_dirent, evt_dirent)))
177 
178 #define MAX_EVENT_LENGTH 512
179 
180 
181 struct tracepoint_path *tracepoint_id_to_path(u64 config)
182 {
183 	struct tracepoint_path *path = NULL;
184 	DIR *sys_dir, *evt_dir;
185 	struct dirent *sys_dirent, *evt_dirent;
186 	char id_buf[24];
187 	int fd;
188 	u64 id;
189 	char evt_path[MAXPATHLEN];
190 	char dir_path[MAXPATHLEN];
191 
192 	sys_dir = opendir(tracing_events_path);
193 	if (!sys_dir)
194 		return NULL;
195 
196 	for_each_subsystem(sys_dir, sys_dirent) {
197 
198 		snprintf(dir_path, MAXPATHLEN, "%s/%s", tracing_events_path,
199 			 sys_dirent->d_name);
200 		evt_dir = opendir(dir_path);
201 		if (!evt_dir)
202 			continue;
203 
204 		for_each_event(sys_dirent, evt_dir, evt_dirent) {
205 
206 			snprintf(evt_path, MAXPATHLEN, "%s/%s/id", dir_path,
207 				 evt_dirent->d_name);
208 			fd = open(evt_path, O_RDONLY);
209 			if (fd < 0)
210 				continue;
211 			if (read(fd, id_buf, sizeof(id_buf)) < 0) {
212 				close(fd);
213 				continue;
214 			}
215 			close(fd);
216 			id = atoll(id_buf);
217 			if (id == config) {
218 				closedir(evt_dir);
219 				closedir(sys_dir);
220 				path = zalloc(sizeof(*path));
221 				if (!path)
222 					return NULL;
223 				path->system = malloc(MAX_EVENT_LENGTH);
224 				if (!path->system) {
225 					free(path);
226 					return NULL;
227 				}
228 				path->name = malloc(MAX_EVENT_LENGTH);
229 				if (!path->name) {
230 					zfree(&path->system);
231 					free(path);
232 					return NULL;
233 				}
234 				strncpy(path->system, sys_dirent->d_name,
235 					MAX_EVENT_LENGTH);
236 				strncpy(path->name, evt_dirent->d_name,
237 					MAX_EVENT_LENGTH);
238 				return path;
239 			}
240 		}
241 		closedir(evt_dir);
242 	}
243 
244 	closedir(sys_dir);
245 	return NULL;
246 }
247 
248 struct tracepoint_path *tracepoint_name_to_path(const char *name)
249 {
250 	struct tracepoint_path *path = zalloc(sizeof(*path));
251 	char *str = strchr(name, ':');
252 
253 	if (path == NULL || str == NULL) {
254 		free(path);
255 		return NULL;
256 	}
257 
258 	path->system = strndup(name, str - name);
259 	path->name = strdup(str+1);
260 
261 	if (path->system == NULL || path->name == NULL) {
262 		zfree(&path->system);
263 		zfree(&path->name);
264 		zfree(&path);
265 	}
266 
267 	return path;
268 }
269 
270 const char *event_type(int type)
271 {
272 	switch (type) {
273 	case PERF_TYPE_HARDWARE:
274 		return "hardware";
275 
276 	case PERF_TYPE_SOFTWARE:
277 		return "software";
278 
279 	case PERF_TYPE_TRACEPOINT:
280 		return "tracepoint";
281 
282 	case PERF_TYPE_HW_CACHE:
283 		return "hardware-cache";
284 
285 	default:
286 		break;
287 	}
288 
289 	return "unknown";
290 }
291 
292 static int parse_events__is_name_term(struct parse_events_term *term)
293 {
294 	return term->type_term == PARSE_EVENTS__TERM_TYPE_NAME;
295 }
296 
297 static char *get_config_name(struct list_head *head_terms)
298 {
299 	struct parse_events_term *term;
300 
301 	if (!head_terms)
302 		return NULL;
303 
304 	list_for_each_entry(term, head_terms, list)
305 		if (parse_events__is_name_term(term))
306 			return term->val.str;
307 
308 	return NULL;
309 }
310 
311 static struct perf_evsel *
312 __add_event(struct list_head *list, int *idx,
313 	    struct perf_event_attr *attr,
314 	    char *name, struct perf_pmu *pmu,
315 	    struct list_head *config_terms, bool auto_merge_stats)
316 {
317 	struct perf_evsel *evsel;
318 	struct cpu_map *cpus = pmu ? pmu->cpus : NULL;
319 
320 	event_attr_init(attr);
321 
322 	evsel = perf_evsel__new_idx(attr, *idx);
323 	if (!evsel)
324 		return NULL;
325 
326 	(*idx)++;
327 	evsel->cpus        = cpu_map__get(cpus);
328 	evsel->own_cpus    = cpu_map__get(cpus);
329 	evsel->system_wide = pmu ? pmu->is_uncore : false;
330 	evsel->auto_merge_stats = auto_merge_stats;
331 
332 	if (name)
333 		evsel->name = strdup(name);
334 
335 	if (config_terms)
336 		list_splice(config_terms, &evsel->config_terms);
337 
338 	list_add_tail(&evsel->node, list);
339 	return evsel;
340 }
341 
342 static int add_event(struct list_head *list, int *idx,
343 		     struct perf_event_attr *attr, char *name,
344 		     struct list_head *config_terms)
345 {
346 	return __add_event(list, idx, attr, name, NULL, config_terms, false) ? 0 : -ENOMEM;
347 }
348 
349 static int parse_aliases(char *str, const char *names[][PERF_EVSEL__MAX_ALIASES], int size)
350 {
351 	int i, j;
352 	int n, longest = -1;
353 
354 	for (i = 0; i < size; i++) {
355 		for (j = 0; j < PERF_EVSEL__MAX_ALIASES && names[i][j]; j++) {
356 			n = strlen(names[i][j]);
357 			if (n > longest && !strncasecmp(str, names[i][j], n))
358 				longest = n;
359 		}
360 		if (longest > 0)
361 			return i;
362 	}
363 
364 	return -1;
365 }
366 
367 typedef int config_term_func_t(struct perf_event_attr *attr,
368 			       struct parse_events_term *term,
369 			       struct parse_events_error *err);
370 static int config_term_common(struct perf_event_attr *attr,
371 			      struct parse_events_term *term,
372 			      struct parse_events_error *err);
373 static int config_attr(struct perf_event_attr *attr,
374 		       struct list_head *head,
375 		       struct parse_events_error *err,
376 		       config_term_func_t config_term);
377 
378 int parse_events_add_cache(struct list_head *list, int *idx,
379 			   char *type, char *op_result1, char *op_result2,
380 			   struct parse_events_error *err,
381 			   struct list_head *head_config)
382 {
383 	struct perf_event_attr attr;
384 	LIST_HEAD(config_terms);
385 	char name[MAX_NAME_LEN], *config_name;
386 	int cache_type = -1, cache_op = -1, cache_result = -1;
387 	char *op_result[2] = { op_result1, op_result2 };
388 	int i, n;
389 
390 	/*
391 	 * No fallback - if we cannot get a clear cache type
392 	 * then bail out:
393 	 */
394 	cache_type = parse_aliases(type, perf_evsel__hw_cache,
395 				   PERF_COUNT_HW_CACHE_MAX);
396 	if (cache_type == -1)
397 		return -EINVAL;
398 
399 	config_name = get_config_name(head_config);
400 	n = snprintf(name, MAX_NAME_LEN, "%s", type);
401 
402 	for (i = 0; (i < 2) && (op_result[i]); i++) {
403 		char *str = op_result[i];
404 
405 		n += snprintf(name + n, MAX_NAME_LEN - n, "-%s", str);
406 
407 		if (cache_op == -1) {
408 			cache_op = parse_aliases(str, perf_evsel__hw_cache_op,
409 						 PERF_COUNT_HW_CACHE_OP_MAX);
410 			if (cache_op >= 0) {
411 				if (!perf_evsel__is_cache_op_valid(cache_type, cache_op))
412 					return -EINVAL;
413 				continue;
414 			}
415 		}
416 
417 		if (cache_result == -1) {
418 			cache_result = parse_aliases(str, perf_evsel__hw_cache_result,
419 						     PERF_COUNT_HW_CACHE_RESULT_MAX);
420 			if (cache_result >= 0)
421 				continue;
422 		}
423 	}
424 
425 	/*
426 	 * Fall back to reads:
427 	 */
428 	if (cache_op == -1)
429 		cache_op = PERF_COUNT_HW_CACHE_OP_READ;
430 
431 	/*
432 	 * Fall back to accesses:
433 	 */
434 	if (cache_result == -1)
435 		cache_result = PERF_COUNT_HW_CACHE_RESULT_ACCESS;
436 
437 	memset(&attr, 0, sizeof(attr));
438 	attr.config = cache_type | (cache_op << 8) | (cache_result << 16);
439 	attr.type = PERF_TYPE_HW_CACHE;
440 
441 	if (head_config) {
442 		if (config_attr(&attr, head_config, err,
443 				config_term_common))
444 			return -EINVAL;
445 
446 		if (get_config_terms(head_config, &config_terms))
447 			return -ENOMEM;
448 	}
449 	return add_event(list, idx, &attr, config_name ? : name, &config_terms);
450 }
451 
452 static void tracepoint_error(struct parse_events_error *e, int err,
453 			     const char *sys, const char *name)
454 {
455 	char help[BUFSIZ];
456 
457 	if (!e)
458 		return;
459 
460 	/*
461 	 * We get error directly from syscall errno ( > 0),
462 	 * or from encoded pointer's error ( < 0).
463 	 */
464 	err = abs(err);
465 
466 	switch (err) {
467 	case EACCES:
468 		e->str = strdup("can't access trace events");
469 		break;
470 	case ENOENT:
471 		e->str = strdup("unknown tracepoint");
472 		break;
473 	default:
474 		e->str = strdup("failed to add tracepoint");
475 		break;
476 	}
477 
478 	tracing_path__strerror_open_tp(err, help, sizeof(help), sys, name);
479 	e->help = strdup(help);
480 }
481 
482 static int add_tracepoint(struct list_head *list, int *idx,
483 			  const char *sys_name, const char *evt_name,
484 			  struct parse_events_error *err,
485 			  struct list_head *head_config)
486 {
487 	struct perf_evsel *evsel;
488 
489 	evsel = perf_evsel__newtp_idx(sys_name, evt_name, (*idx)++);
490 	if (IS_ERR(evsel)) {
491 		tracepoint_error(err, PTR_ERR(evsel), sys_name, evt_name);
492 		return PTR_ERR(evsel);
493 	}
494 
495 	if (head_config) {
496 		LIST_HEAD(config_terms);
497 
498 		if (get_config_terms(head_config, &config_terms))
499 			return -ENOMEM;
500 		list_splice(&config_terms, &evsel->config_terms);
501 	}
502 
503 	list_add_tail(&evsel->node, list);
504 	return 0;
505 }
506 
507 static int add_tracepoint_multi_event(struct list_head *list, int *idx,
508 				      const char *sys_name, const char *evt_name,
509 				      struct parse_events_error *err,
510 				      struct list_head *head_config)
511 {
512 	char evt_path[MAXPATHLEN];
513 	struct dirent *evt_ent;
514 	DIR *evt_dir;
515 	int ret = 0, found = 0;
516 
517 	snprintf(evt_path, MAXPATHLEN, "%s/%s", tracing_events_path, sys_name);
518 	evt_dir = opendir(evt_path);
519 	if (!evt_dir) {
520 		tracepoint_error(err, errno, sys_name, evt_name);
521 		return -1;
522 	}
523 
524 	while (!ret && (evt_ent = readdir(evt_dir))) {
525 		if (!strcmp(evt_ent->d_name, ".")
526 		    || !strcmp(evt_ent->d_name, "..")
527 		    || !strcmp(evt_ent->d_name, "enable")
528 		    || !strcmp(evt_ent->d_name, "filter"))
529 			continue;
530 
531 		if (!strglobmatch(evt_ent->d_name, evt_name))
532 			continue;
533 
534 		found++;
535 
536 		ret = add_tracepoint(list, idx, sys_name, evt_ent->d_name,
537 				     err, head_config);
538 	}
539 
540 	if (!found) {
541 		tracepoint_error(err, ENOENT, sys_name, evt_name);
542 		ret = -1;
543 	}
544 
545 	closedir(evt_dir);
546 	return ret;
547 }
548 
549 static int add_tracepoint_event(struct list_head *list, int *idx,
550 				const char *sys_name, const char *evt_name,
551 				struct parse_events_error *err,
552 				struct list_head *head_config)
553 {
554 	return strpbrk(evt_name, "*?") ?
555 	       add_tracepoint_multi_event(list, idx, sys_name, evt_name,
556 					  err, head_config) :
557 	       add_tracepoint(list, idx, sys_name, evt_name,
558 			      err, head_config);
559 }
560 
561 static int add_tracepoint_multi_sys(struct list_head *list, int *idx,
562 				    const char *sys_name, const char *evt_name,
563 				    struct parse_events_error *err,
564 				    struct list_head *head_config)
565 {
566 	struct dirent *events_ent;
567 	DIR *events_dir;
568 	int ret = 0;
569 
570 	events_dir = opendir(tracing_events_path);
571 	if (!events_dir) {
572 		tracepoint_error(err, errno, sys_name, evt_name);
573 		return -1;
574 	}
575 
576 	while (!ret && (events_ent = readdir(events_dir))) {
577 		if (!strcmp(events_ent->d_name, ".")
578 		    || !strcmp(events_ent->d_name, "..")
579 		    || !strcmp(events_ent->d_name, "enable")
580 		    || !strcmp(events_ent->d_name, "header_event")
581 		    || !strcmp(events_ent->d_name, "header_page"))
582 			continue;
583 
584 		if (!strglobmatch(events_ent->d_name, sys_name))
585 			continue;
586 
587 		ret = add_tracepoint_event(list, idx, events_ent->d_name,
588 					   evt_name, err, head_config);
589 	}
590 
591 	closedir(events_dir);
592 	return ret;
593 }
594 
595 struct __add_bpf_event_param {
596 	struct parse_events_state *parse_state;
597 	struct list_head *list;
598 	struct list_head *head_config;
599 };
600 
601 static int add_bpf_event(const char *group, const char *event, int fd,
602 			 void *_param)
603 {
604 	LIST_HEAD(new_evsels);
605 	struct __add_bpf_event_param *param = _param;
606 	struct parse_events_state *parse_state = param->parse_state;
607 	struct list_head *list = param->list;
608 	struct perf_evsel *pos;
609 	int err;
610 
611 	pr_debug("add bpf event %s:%s and attach bpf program %d\n",
612 		 group, event, fd);
613 
614 	err = parse_events_add_tracepoint(&new_evsels, &parse_state->idx, group,
615 					  event, parse_state->error,
616 					  param->head_config);
617 	if (err) {
618 		struct perf_evsel *evsel, *tmp;
619 
620 		pr_debug("Failed to add BPF event %s:%s\n",
621 			 group, event);
622 		list_for_each_entry_safe(evsel, tmp, &new_evsels, node) {
623 			list_del(&evsel->node);
624 			perf_evsel__delete(evsel);
625 		}
626 		return err;
627 	}
628 	pr_debug("adding %s:%s\n", group, event);
629 
630 	list_for_each_entry(pos, &new_evsels, node) {
631 		pr_debug("adding %s:%s to %p\n",
632 			 group, event, pos);
633 		pos->bpf_fd = fd;
634 	}
635 	list_splice(&new_evsels, list);
636 	return 0;
637 }
638 
639 int parse_events_load_bpf_obj(struct parse_events_state *parse_state,
640 			      struct list_head *list,
641 			      struct bpf_object *obj,
642 			      struct list_head *head_config)
643 {
644 	int err;
645 	char errbuf[BUFSIZ];
646 	struct __add_bpf_event_param param = {parse_state, list, head_config};
647 	static bool registered_unprobe_atexit = false;
648 
649 	if (IS_ERR(obj) || !obj) {
650 		snprintf(errbuf, sizeof(errbuf),
651 			 "Internal error: load bpf obj with NULL");
652 		err = -EINVAL;
653 		goto errout;
654 	}
655 
656 	/*
657 	 * Register atexit handler before calling bpf__probe() so
658 	 * bpf__probe() don't need to unprobe probe points its already
659 	 * created when failure.
660 	 */
661 	if (!registered_unprobe_atexit) {
662 		atexit(bpf__clear);
663 		registered_unprobe_atexit = true;
664 	}
665 
666 	err = bpf__probe(obj);
667 	if (err) {
668 		bpf__strerror_probe(obj, err, errbuf, sizeof(errbuf));
669 		goto errout;
670 	}
671 
672 	err = bpf__load(obj);
673 	if (err) {
674 		bpf__strerror_load(obj, err, errbuf, sizeof(errbuf));
675 		goto errout;
676 	}
677 
678 	err = bpf__foreach_event(obj, add_bpf_event, &param);
679 	if (err) {
680 		snprintf(errbuf, sizeof(errbuf),
681 			 "Attach events in BPF object failed");
682 		goto errout;
683 	}
684 
685 	return 0;
686 errout:
687 	parse_state->error->help = strdup("(add -v to see detail)");
688 	parse_state->error->str = strdup(errbuf);
689 	return err;
690 }
691 
692 static int
693 parse_events_config_bpf(struct parse_events_state *parse_state,
694 			struct bpf_object *obj,
695 			struct list_head *head_config)
696 {
697 	struct parse_events_term *term;
698 	int error_pos;
699 
700 	if (!head_config || list_empty(head_config))
701 		return 0;
702 
703 	list_for_each_entry(term, head_config, list) {
704 		char errbuf[BUFSIZ];
705 		int err;
706 
707 		if (term->type_term != PARSE_EVENTS__TERM_TYPE_USER) {
708 			snprintf(errbuf, sizeof(errbuf),
709 				 "Invalid config term for BPF object");
710 			errbuf[BUFSIZ - 1] = '\0';
711 
712 			parse_state->error->idx = term->err_term;
713 			parse_state->error->str = strdup(errbuf);
714 			return -EINVAL;
715 		}
716 
717 		err = bpf__config_obj(obj, term, parse_state->evlist, &error_pos);
718 		if (err) {
719 			bpf__strerror_config_obj(obj, term, parse_state->evlist,
720 						 &error_pos, err, errbuf,
721 						 sizeof(errbuf));
722 			parse_state->error->help = strdup(
723 "Hint:\tValid config terms:\n"
724 "     \tmap:[<arraymap>].value<indices>=[value]\n"
725 "     \tmap:[<eventmap>].event<indices>=[event]\n"
726 "\n"
727 "     \twhere <indices> is something like [0,3...5] or [all]\n"
728 "     \t(add -v to see detail)");
729 			parse_state->error->str = strdup(errbuf);
730 			if (err == -BPF_LOADER_ERRNO__OBJCONF_MAP_VALUE)
731 				parse_state->error->idx = term->err_val;
732 			else
733 				parse_state->error->idx = term->err_term + error_pos;
734 			return err;
735 		}
736 	}
737 	return 0;
738 }
739 
740 /*
741  * Split config terms:
742  * perf record -e bpf.c/call-graph=fp,map:array.value[0]=1/ ...
743  *  'call-graph=fp' is 'evt config', should be applied to each
744  *  events in bpf.c.
745  * 'map:array.value[0]=1' is 'obj config', should be processed
746  * with parse_events_config_bpf.
747  *
748  * Move object config terms from the first list to obj_head_config.
749  */
750 static void
751 split_bpf_config_terms(struct list_head *evt_head_config,
752 		       struct list_head *obj_head_config)
753 {
754 	struct parse_events_term *term, *temp;
755 
756 	/*
757 	 * Currectly, all possible user config term
758 	 * belong to bpf object. parse_events__is_hardcoded_term()
759 	 * happends to be a good flag.
760 	 *
761 	 * See parse_events_config_bpf() and
762 	 * config_term_tracepoint().
763 	 */
764 	list_for_each_entry_safe(term, temp, evt_head_config, list)
765 		if (!parse_events__is_hardcoded_term(term))
766 			list_move_tail(&term->list, obj_head_config);
767 }
768 
769 int parse_events_load_bpf(struct parse_events_state *parse_state,
770 			  struct list_head *list,
771 			  char *bpf_file_name,
772 			  bool source,
773 			  struct list_head *head_config)
774 {
775 	int err;
776 	struct bpf_object *obj;
777 	LIST_HEAD(obj_head_config);
778 
779 	if (head_config)
780 		split_bpf_config_terms(head_config, &obj_head_config);
781 
782 	obj = bpf__prepare_load(bpf_file_name, source);
783 	if (IS_ERR(obj)) {
784 		char errbuf[BUFSIZ];
785 
786 		err = PTR_ERR(obj);
787 
788 		if (err == -ENOTSUP)
789 			snprintf(errbuf, sizeof(errbuf),
790 				 "BPF support is not compiled");
791 		else
792 			bpf__strerror_prepare_load(bpf_file_name,
793 						   source,
794 						   -err, errbuf,
795 						   sizeof(errbuf));
796 
797 		parse_state->error->help = strdup("(add -v to see detail)");
798 		parse_state->error->str = strdup(errbuf);
799 		return err;
800 	}
801 
802 	err = parse_events_load_bpf_obj(parse_state, list, obj, head_config);
803 	if (err)
804 		return err;
805 	err = parse_events_config_bpf(parse_state, obj, &obj_head_config);
806 
807 	/*
808 	 * Caller doesn't know anything about obj_head_config,
809 	 * so combine them together again before returnning.
810 	 */
811 	if (head_config)
812 		list_splice_tail(&obj_head_config, head_config);
813 	return err;
814 }
815 
816 static int
817 parse_breakpoint_type(const char *type, struct perf_event_attr *attr)
818 {
819 	int i;
820 
821 	for (i = 0; i < 3; i++) {
822 		if (!type || !type[i])
823 			break;
824 
825 #define CHECK_SET_TYPE(bit)		\
826 do {					\
827 	if (attr->bp_type & bit)	\
828 		return -EINVAL;		\
829 	else				\
830 		attr->bp_type |= bit;	\
831 } while (0)
832 
833 		switch (type[i]) {
834 		case 'r':
835 			CHECK_SET_TYPE(HW_BREAKPOINT_R);
836 			break;
837 		case 'w':
838 			CHECK_SET_TYPE(HW_BREAKPOINT_W);
839 			break;
840 		case 'x':
841 			CHECK_SET_TYPE(HW_BREAKPOINT_X);
842 			break;
843 		default:
844 			return -EINVAL;
845 		}
846 	}
847 
848 #undef CHECK_SET_TYPE
849 
850 	if (!attr->bp_type) /* Default */
851 		attr->bp_type = HW_BREAKPOINT_R | HW_BREAKPOINT_W;
852 
853 	return 0;
854 }
855 
856 int parse_events_add_breakpoint(struct list_head *list, int *idx,
857 				void *ptr, char *type, u64 len)
858 {
859 	struct perf_event_attr attr;
860 
861 	memset(&attr, 0, sizeof(attr));
862 	attr.bp_addr = (unsigned long) ptr;
863 
864 	if (parse_breakpoint_type(type, &attr))
865 		return -EINVAL;
866 
867 	/* Provide some defaults if len is not specified */
868 	if (!len) {
869 		if (attr.bp_type == HW_BREAKPOINT_X)
870 			len = sizeof(long);
871 		else
872 			len = HW_BREAKPOINT_LEN_4;
873 	}
874 
875 	attr.bp_len = len;
876 
877 	attr.type = PERF_TYPE_BREAKPOINT;
878 	attr.sample_period = 1;
879 
880 	return add_event(list, idx, &attr, NULL, NULL);
881 }
882 
883 static int check_type_val(struct parse_events_term *term,
884 			  struct parse_events_error *err,
885 			  int type)
886 {
887 	if (type == term->type_val)
888 		return 0;
889 
890 	if (err) {
891 		err->idx = term->err_val;
892 		if (type == PARSE_EVENTS__TERM_TYPE_NUM)
893 			err->str = strdup("expected numeric value");
894 		else
895 			err->str = strdup("expected string value");
896 	}
897 	return -EINVAL;
898 }
899 
900 /*
901  * Update according to parse-events.l
902  */
903 static const char *config_term_names[__PARSE_EVENTS__TERM_TYPE_NR] = {
904 	[PARSE_EVENTS__TERM_TYPE_USER]			= "<sysfs term>",
905 	[PARSE_EVENTS__TERM_TYPE_CONFIG]		= "config",
906 	[PARSE_EVENTS__TERM_TYPE_CONFIG1]		= "config1",
907 	[PARSE_EVENTS__TERM_TYPE_CONFIG2]		= "config2",
908 	[PARSE_EVENTS__TERM_TYPE_NAME]			= "name",
909 	[PARSE_EVENTS__TERM_TYPE_SAMPLE_PERIOD]		= "period",
910 	[PARSE_EVENTS__TERM_TYPE_SAMPLE_FREQ]		= "freq",
911 	[PARSE_EVENTS__TERM_TYPE_BRANCH_SAMPLE_TYPE]	= "branch_type",
912 	[PARSE_EVENTS__TERM_TYPE_TIME]			= "time",
913 	[PARSE_EVENTS__TERM_TYPE_CALLGRAPH]		= "call-graph",
914 	[PARSE_EVENTS__TERM_TYPE_STACKSIZE]		= "stack-size",
915 	[PARSE_EVENTS__TERM_TYPE_NOINHERIT]		= "no-inherit",
916 	[PARSE_EVENTS__TERM_TYPE_INHERIT]		= "inherit",
917 	[PARSE_EVENTS__TERM_TYPE_MAX_STACK]		= "max-stack",
918 	[PARSE_EVENTS__TERM_TYPE_OVERWRITE]		= "overwrite",
919 	[PARSE_EVENTS__TERM_TYPE_NOOVERWRITE]		= "no-overwrite",
920 	[PARSE_EVENTS__TERM_TYPE_DRV_CFG]		= "driver-config",
921 };
922 
923 static bool config_term_shrinked;
924 
925 static bool
926 config_term_avail(int term_type, struct parse_events_error *err)
927 {
928 	if (term_type < 0 || term_type >= __PARSE_EVENTS__TERM_TYPE_NR) {
929 		err->str = strdup("Invalid term_type");
930 		return false;
931 	}
932 	if (!config_term_shrinked)
933 		return true;
934 
935 	switch (term_type) {
936 	case PARSE_EVENTS__TERM_TYPE_CONFIG:
937 	case PARSE_EVENTS__TERM_TYPE_CONFIG1:
938 	case PARSE_EVENTS__TERM_TYPE_CONFIG2:
939 	case PARSE_EVENTS__TERM_TYPE_NAME:
940 	case PARSE_EVENTS__TERM_TYPE_SAMPLE_PERIOD:
941 		return true;
942 	default:
943 		if (!err)
944 			return false;
945 
946 		/* term_type is validated so indexing is safe */
947 		if (asprintf(&err->str, "'%s' is not usable in 'perf stat'",
948 			     config_term_names[term_type]) < 0)
949 			err->str = NULL;
950 		return false;
951 	}
952 }
953 
954 void parse_events__shrink_config_terms(void)
955 {
956 	config_term_shrinked = true;
957 }
958 
959 static int config_term_common(struct perf_event_attr *attr,
960 			      struct parse_events_term *term,
961 			      struct parse_events_error *err)
962 {
963 #define CHECK_TYPE_VAL(type)						   \
964 do {									   \
965 	if (check_type_val(term, err, PARSE_EVENTS__TERM_TYPE_ ## type)) \
966 		return -EINVAL;						   \
967 } while (0)
968 
969 	switch (term->type_term) {
970 	case PARSE_EVENTS__TERM_TYPE_CONFIG:
971 		CHECK_TYPE_VAL(NUM);
972 		attr->config = term->val.num;
973 		break;
974 	case PARSE_EVENTS__TERM_TYPE_CONFIG1:
975 		CHECK_TYPE_VAL(NUM);
976 		attr->config1 = term->val.num;
977 		break;
978 	case PARSE_EVENTS__TERM_TYPE_CONFIG2:
979 		CHECK_TYPE_VAL(NUM);
980 		attr->config2 = term->val.num;
981 		break;
982 	case PARSE_EVENTS__TERM_TYPE_SAMPLE_PERIOD:
983 		CHECK_TYPE_VAL(NUM);
984 		break;
985 	case PARSE_EVENTS__TERM_TYPE_SAMPLE_FREQ:
986 		CHECK_TYPE_VAL(NUM);
987 		break;
988 	case PARSE_EVENTS__TERM_TYPE_BRANCH_SAMPLE_TYPE:
989 		CHECK_TYPE_VAL(STR);
990 		if (strcmp(term->val.str, "no") &&
991 		    parse_branch_str(term->val.str, &attr->branch_sample_type)) {
992 			err->str = strdup("invalid branch sample type");
993 			err->idx = term->err_val;
994 			return -EINVAL;
995 		}
996 		break;
997 	case PARSE_EVENTS__TERM_TYPE_TIME:
998 		CHECK_TYPE_VAL(NUM);
999 		if (term->val.num > 1) {
1000 			err->str = strdup("expected 0 or 1");
1001 			err->idx = term->err_val;
1002 			return -EINVAL;
1003 		}
1004 		break;
1005 	case PARSE_EVENTS__TERM_TYPE_CALLGRAPH:
1006 		CHECK_TYPE_VAL(STR);
1007 		break;
1008 	case PARSE_EVENTS__TERM_TYPE_STACKSIZE:
1009 		CHECK_TYPE_VAL(NUM);
1010 		break;
1011 	case PARSE_EVENTS__TERM_TYPE_INHERIT:
1012 		CHECK_TYPE_VAL(NUM);
1013 		break;
1014 	case PARSE_EVENTS__TERM_TYPE_NOINHERIT:
1015 		CHECK_TYPE_VAL(NUM);
1016 		break;
1017 	case PARSE_EVENTS__TERM_TYPE_OVERWRITE:
1018 		CHECK_TYPE_VAL(NUM);
1019 		break;
1020 	case PARSE_EVENTS__TERM_TYPE_NOOVERWRITE:
1021 		CHECK_TYPE_VAL(NUM);
1022 		break;
1023 	case PARSE_EVENTS__TERM_TYPE_NAME:
1024 		CHECK_TYPE_VAL(STR);
1025 		break;
1026 	case PARSE_EVENTS__TERM_TYPE_MAX_STACK:
1027 		CHECK_TYPE_VAL(NUM);
1028 		break;
1029 	default:
1030 		err->str = strdup("unknown term");
1031 		err->idx = term->err_term;
1032 		err->help = parse_events_formats_error_string(NULL);
1033 		return -EINVAL;
1034 	}
1035 
1036 	/*
1037 	 * Check term availbility after basic checking so
1038 	 * PARSE_EVENTS__TERM_TYPE_USER can be found and filtered.
1039 	 *
1040 	 * If check availbility at the entry of this function,
1041 	 * user will see "'<sysfs term>' is not usable in 'perf stat'"
1042 	 * if an invalid config term is provided for legacy events
1043 	 * (for example, instructions/badterm/...), which is confusing.
1044 	 */
1045 	if (!config_term_avail(term->type_term, err))
1046 		return -EINVAL;
1047 	return 0;
1048 #undef CHECK_TYPE_VAL
1049 }
1050 
1051 static int config_term_pmu(struct perf_event_attr *attr,
1052 			   struct parse_events_term *term,
1053 			   struct parse_events_error *err)
1054 {
1055 	if (term->type_term == PARSE_EVENTS__TERM_TYPE_USER ||
1056 	    term->type_term == PARSE_EVENTS__TERM_TYPE_DRV_CFG)
1057 		/*
1058 		 * Always succeed for sysfs terms, as we dont know
1059 		 * at this point what type they need to have.
1060 		 */
1061 		return 0;
1062 	else
1063 		return config_term_common(attr, term, err);
1064 }
1065 
1066 static int config_term_tracepoint(struct perf_event_attr *attr,
1067 				  struct parse_events_term *term,
1068 				  struct parse_events_error *err)
1069 {
1070 	switch (term->type_term) {
1071 	case PARSE_EVENTS__TERM_TYPE_CALLGRAPH:
1072 	case PARSE_EVENTS__TERM_TYPE_STACKSIZE:
1073 	case PARSE_EVENTS__TERM_TYPE_INHERIT:
1074 	case PARSE_EVENTS__TERM_TYPE_NOINHERIT:
1075 	case PARSE_EVENTS__TERM_TYPE_MAX_STACK:
1076 	case PARSE_EVENTS__TERM_TYPE_OVERWRITE:
1077 	case PARSE_EVENTS__TERM_TYPE_NOOVERWRITE:
1078 		return config_term_common(attr, term, err);
1079 	default:
1080 		if (err) {
1081 			err->idx = term->err_term;
1082 			err->str = strdup("unknown term");
1083 			err->help = strdup("valid terms: call-graph,stack-size\n");
1084 		}
1085 		return -EINVAL;
1086 	}
1087 
1088 	return 0;
1089 }
1090 
1091 static int config_attr(struct perf_event_attr *attr,
1092 		       struct list_head *head,
1093 		       struct parse_events_error *err,
1094 		       config_term_func_t config_term)
1095 {
1096 	struct parse_events_term *term;
1097 
1098 	list_for_each_entry(term, head, list)
1099 		if (config_term(attr, term, err))
1100 			return -EINVAL;
1101 
1102 	return 0;
1103 }
1104 
1105 static int get_config_terms(struct list_head *head_config,
1106 			    struct list_head *head_terms __maybe_unused)
1107 {
1108 #define ADD_CONFIG_TERM(__type, __name, __val)			\
1109 do {								\
1110 	struct perf_evsel_config_term *__t;			\
1111 								\
1112 	__t = zalloc(sizeof(*__t));				\
1113 	if (!__t)						\
1114 		return -ENOMEM;					\
1115 								\
1116 	INIT_LIST_HEAD(&__t->list);				\
1117 	__t->type       = PERF_EVSEL__CONFIG_TERM_ ## __type;	\
1118 	__t->val.__name = __val;				\
1119 	__t->weak	= term->weak;				\
1120 	list_add_tail(&__t->list, head_terms);			\
1121 } while (0)
1122 
1123 	struct parse_events_term *term;
1124 
1125 	list_for_each_entry(term, head_config, list) {
1126 		switch (term->type_term) {
1127 		case PARSE_EVENTS__TERM_TYPE_SAMPLE_PERIOD:
1128 			ADD_CONFIG_TERM(PERIOD, period, term->val.num);
1129 			break;
1130 		case PARSE_EVENTS__TERM_TYPE_SAMPLE_FREQ:
1131 			ADD_CONFIG_TERM(FREQ, freq, term->val.num);
1132 			break;
1133 		case PARSE_EVENTS__TERM_TYPE_TIME:
1134 			ADD_CONFIG_TERM(TIME, time, term->val.num);
1135 			break;
1136 		case PARSE_EVENTS__TERM_TYPE_CALLGRAPH:
1137 			ADD_CONFIG_TERM(CALLGRAPH, callgraph, term->val.str);
1138 			break;
1139 		case PARSE_EVENTS__TERM_TYPE_BRANCH_SAMPLE_TYPE:
1140 			ADD_CONFIG_TERM(BRANCH, branch, term->val.str);
1141 			break;
1142 		case PARSE_EVENTS__TERM_TYPE_STACKSIZE:
1143 			ADD_CONFIG_TERM(STACK_USER, stack_user, term->val.num);
1144 			break;
1145 		case PARSE_EVENTS__TERM_TYPE_INHERIT:
1146 			ADD_CONFIG_TERM(INHERIT, inherit, term->val.num ? 1 : 0);
1147 			break;
1148 		case PARSE_EVENTS__TERM_TYPE_NOINHERIT:
1149 			ADD_CONFIG_TERM(INHERIT, inherit, term->val.num ? 0 : 1);
1150 			break;
1151 		case PARSE_EVENTS__TERM_TYPE_MAX_STACK:
1152 			ADD_CONFIG_TERM(MAX_STACK, max_stack, term->val.num);
1153 			break;
1154 		case PARSE_EVENTS__TERM_TYPE_OVERWRITE:
1155 			ADD_CONFIG_TERM(OVERWRITE, overwrite, term->val.num ? 1 : 0);
1156 			break;
1157 		case PARSE_EVENTS__TERM_TYPE_NOOVERWRITE:
1158 			ADD_CONFIG_TERM(OVERWRITE, overwrite, term->val.num ? 0 : 1);
1159 			break;
1160 		case PARSE_EVENTS__TERM_TYPE_DRV_CFG:
1161 			ADD_CONFIG_TERM(DRV_CFG, drv_cfg, term->val.str);
1162 			break;
1163 		default:
1164 			break;
1165 		}
1166 	}
1167 #undef ADD_EVSEL_CONFIG
1168 	return 0;
1169 }
1170 
1171 int parse_events_add_tracepoint(struct list_head *list, int *idx,
1172 				const char *sys, const char *event,
1173 				struct parse_events_error *err,
1174 				struct list_head *head_config)
1175 {
1176 	if (head_config) {
1177 		struct perf_event_attr attr;
1178 
1179 		if (config_attr(&attr, head_config, err,
1180 				config_term_tracepoint))
1181 			return -EINVAL;
1182 	}
1183 
1184 	if (strpbrk(sys, "*?"))
1185 		return add_tracepoint_multi_sys(list, idx, sys, event,
1186 						err, head_config);
1187 	else
1188 		return add_tracepoint_event(list, idx, sys, event,
1189 					    err, head_config);
1190 }
1191 
1192 int parse_events_add_numeric(struct parse_events_state *parse_state,
1193 			     struct list_head *list,
1194 			     u32 type, u64 config,
1195 			     struct list_head *head_config)
1196 {
1197 	struct perf_event_attr attr;
1198 	LIST_HEAD(config_terms);
1199 
1200 	memset(&attr, 0, sizeof(attr));
1201 	attr.type = type;
1202 	attr.config = config;
1203 
1204 	if (head_config) {
1205 		if (config_attr(&attr, head_config, parse_state->error,
1206 				config_term_common))
1207 			return -EINVAL;
1208 
1209 		if (get_config_terms(head_config, &config_terms))
1210 			return -ENOMEM;
1211 	}
1212 
1213 	return add_event(list, &parse_state->idx, &attr,
1214 			 get_config_name(head_config), &config_terms);
1215 }
1216 
1217 static int __parse_events_add_pmu(struct parse_events_state *parse_state,
1218 			 struct list_head *list, char *name,
1219 			 struct list_head *head_config, bool auto_merge_stats)
1220 {
1221 	struct perf_event_attr attr;
1222 	struct perf_pmu_info info;
1223 	struct perf_pmu *pmu;
1224 	struct perf_evsel *evsel;
1225 	struct parse_events_error *err = parse_state->error;
1226 	LIST_HEAD(config_terms);
1227 
1228 	pmu = perf_pmu__find(name);
1229 	if (!pmu) {
1230 		if (asprintf(&err->str,
1231 				"Cannot find PMU `%s'. Missing kernel support?",
1232 				name) < 0)
1233 			err->str = NULL;
1234 		return -EINVAL;
1235 	}
1236 
1237 	if (pmu->default_config) {
1238 		memcpy(&attr, pmu->default_config,
1239 		       sizeof(struct perf_event_attr));
1240 	} else {
1241 		memset(&attr, 0, sizeof(attr));
1242 	}
1243 
1244 	if (!head_config) {
1245 		attr.type = pmu->type;
1246 		evsel = __add_event(list, &parse_state->idx, &attr, NULL, pmu, NULL, auto_merge_stats);
1247 		return evsel ? 0 : -ENOMEM;
1248 	}
1249 
1250 	if (perf_pmu__check_alias(pmu, head_config, &info))
1251 		return -EINVAL;
1252 
1253 	/*
1254 	 * Configure hardcoded terms first, no need to check
1255 	 * return value when called with fail == 0 ;)
1256 	 */
1257 	if (config_attr(&attr, head_config, parse_state->error, config_term_pmu))
1258 		return -EINVAL;
1259 
1260 	if (get_config_terms(head_config, &config_terms))
1261 		return -ENOMEM;
1262 
1263 	if (perf_pmu__config(pmu, &attr, head_config, parse_state->error))
1264 		return -EINVAL;
1265 
1266 	evsel = __add_event(list, &parse_state->idx, &attr,
1267 			    get_config_name(head_config), pmu,
1268 			    &config_terms, auto_merge_stats);
1269 	if (evsel) {
1270 		evsel->unit = info.unit;
1271 		evsel->scale = info.scale;
1272 		evsel->per_pkg = info.per_pkg;
1273 		evsel->snapshot = info.snapshot;
1274 		evsel->metric_expr = info.metric_expr;
1275 		evsel->metric_name = info.metric_name;
1276 	}
1277 
1278 	return evsel ? 0 : -ENOMEM;
1279 }
1280 
1281 int parse_events_add_pmu(struct parse_events_state *parse_state,
1282 			 struct list_head *list, char *name,
1283 			 struct list_head *head_config)
1284 {
1285 	return __parse_events_add_pmu(parse_state, list, name, head_config, false);
1286 }
1287 
1288 int parse_events_multi_pmu_add(struct parse_events_state *parse_state,
1289 			       char *str, struct list_head **listp)
1290 {
1291 	struct list_head *head;
1292 	struct parse_events_term *term;
1293 	struct list_head *list;
1294 	struct perf_pmu *pmu = NULL;
1295 	int ok = 0;
1296 
1297 	*listp = NULL;
1298 	/* Add it for all PMUs that support the alias */
1299 	list = malloc(sizeof(struct list_head));
1300 	if (!list)
1301 		return -1;
1302 	INIT_LIST_HEAD(list);
1303 	while ((pmu = perf_pmu__scan(pmu)) != NULL) {
1304 		struct perf_pmu_alias *alias;
1305 
1306 		list_for_each_entry(alias, &pmu->aliases, list) {
1307 			if (!strcasecmp(alias->name, str)) {
1308 				head = malloc(sizeof(struct list_head));
1309 				if (!head)
1310 					return -1;
1311 				INIT_LIST_HEAD(head);
1312 				if (parse_events_term__num(&term, PARSE_EVENTS__TERM_TYPE_USER,
1313 							   str, 1, false, &str, NULL) < 0)
1314 					return -1;
1315 				list_add_tail(&term->list, head);
1316 
1317 				if (!__parse_events_add_pmu(parse_state, list,
1318 							    pmu->name, head, true)) {
1319 					pr_debug("%s -> %s/%s/\n", str,
1320 						 pmu->name, alias->str);
1321 					ok++;
1322 				}
1323 
1324 				parse_events_terms__delete(head);
1325 			}
1326 		}
1327 	}
1328 	if (!ok)
1329 		return -1;
1330 	*listp = list;
1331 	return 0;
1332 }
1333 
1334 int parse_events__modifier_group(struct list_head *list,
1335 				 char *event_mod)
1336 {
1337 	return parse_events__modifier_event(list, event_mod, true);
1338 }
1339 
1340 void parse_events__set_leader(char *name, struct list_head *list)
1341 {
1342 	struct perf_evsel *leader;
1343 
1344 	if (list_empty(list)) {
1345 		WARN_ONCE(true, "WARNING: failed to set leader: empty list");
1346 		return;
1347 	}
1348 
1349 	__perf_evlist__set_leader(list);
1350 	leader = list_entry(list->next, struct perf_evsel, node);
1351 	leader->group_name = name ? strdup(name) : NULL;
1352 }
1353 
1354 /* list_event is assumed to point to malloc'ed memory */
1355 void parse_events_update_lists(struct list_head *list_event,
1356 			       struct list_head *list_all)
1357 {
1358 	/*
1359 	 * Called for single event definition. Update the
1360 	 * 'all event' list, and reinit the 'single event'
1361 	 * list, for next event definition.
1362 	 */
1363 	list_splice_tail(list_event, list_all);
1364 	free(list_event);
1365 }
1366 
1367 struct event_modifier {
1368 	int eu;
1369 	int ek;
1370 	int eh;
1371 	int eH;
1372 	int eG;
1373 	int eI;
1374 	int precise;
1375 	int precise_max;
1376 	int exclude_GH;
1377 	int sample_read;
1378 	int pinned;
1379 	int weak;
1380 };
1381 
1382 static int get_event_modifier(struct event_modifier *mod, char *str,
1383 			       struct perf_evsel *evsel)
1384 {
1385 	int eu = evsel ? evsel->attr.exclude_user : 0;
1386 	int ek = evsel ? evsel->attr.exclude_kernel : 0;
1387 	int eh = evsel ? evsel->attr.exclude_hv : 0;
1388 	int eH = evsel ? evsel->attr.exclude_host : 0;
1389 	int eG = evsel ? evsel->attr.exclude_guest : 0;
1390 	int eI = evsel ? evsel->attr.exclude_idle : 0;
1391 	int precise = evsel ? evsel->attr.precise_ip : 0;
1392 	int precise_max = 0;
1393 	int sample_read = 0;
1394 	int pinned = evsel ? evsel->attr.pinned : 0;
1395 
1396 	int exclude = eu | ek | eh;
1397 	int exclude_GH = evsel ? evsel->exclude_GH : 0;
1398 	int weak = 0;
1399 
1400 	memset(mod, 0, sizeof(*mod));
1401 
1402 	while (*str) {
1403 		if (*str == 'u') {
1404 			if (!exclude)
1405 				exclude = eu = ek = eh = 1;
1406 			eu = 0;
1407 		} else if (*str == 'k') {
1408 			if (!exclude)
1409 				exclude = eu = ek = eh = 1;
1410 			ek = 0;
1411 		} else if (*str == 'h') {
1412 			if (!exclude)
1413 				exclude = eu = ek = eh = 1;
1414 			eh = 0;
1415 		} else if (*str == 'G') {
1416 			if (!exclude_GH)
1417 				exclude_GH = eG = eH = 1;
1418 			eG = 0;
1419 		} else if (*str == 'H') {
1420 			if (!exclude_GH)
1421 				exclude_GH = eG = eH = 1;
1422 			eH = 0;
1423 		} else if (*str == 'I') {
1424 			eI = 1;
1425 		} else if (*str == 'p') {
1426 			precise++;
1427 			/* use of precise requires exclude_guest */
1428 			if (!exclude_GH)
1429 				eG = 1;
1430 		} else if (*str == 'P') {
1431 			precise_max = 1;
1432 		} else if (*str == 'S') {
1433 			sample_read = 1;
1434 		} else if (*str == 'D') {
1435 			pinned = 1;
1436 		} else if (*str == 'W') {
1437 			weak = 1;
1438 		} else
1439 			break;
1440 
1441 		++str;
1442 	}
1443 
1444 	/*
1445 	 * precise ip:
1446 	 *
1447 	 *  0 - SAMPLE_IP can have arbitrary skid
1448 	 *  1 - SAMPLE_IP must have constant skid
1449 	 *  2 - SAMPLE_IP requested to have 0 skid
1450 	 *  3 - SAMPLE_IP must have 0 skid
1451 	 *
1452 	 *  See also PERF_RECORD_MISC_EXACT_IP
1453 	 */
1454 	if (precise > 3)
1455 		return -EINVAL;
1456 
1457 	mod->eu = eu;
1458 	mod->ek = ek;
1459 	mod->eh = eh;
1460 	mod->eH = eH;
1461 	mod->eG = eG;
1462 	mod->eI = eI;
1463 	mod->precise = precise;
1464 	mod->precise_max = precise_max;
1465 	mod->exclude_GH = exclude_GH;
1466 	mod->sample_read = sample_read;
1467 	mod->pinned = pinned;
1468 	mod->weak = weak;
1469 
1470 	return 0;
1471 }
1472 
1473 /*
1474  * Basic modifier sanity check to validate it contains only one
1475  * instance of any modifier (apart from 'p') present.
1476  */
1477 static int check_modifier(char *str)
1478 {
1479 	char *p = str;
1480 
1481 	/* The sizeof includes 0 byte as well. */
1482 	if (strlen(str) > (sizeof("ukhGHpppPSDIW") - 1))
1483 		return -1;
1484 
1485 	while (*p) {
1486 		if (*p != 'p' && strchr(p + 1, *p))
1487 			return -1;
1488 		p++;
1489 	}
1490 
1491 	return 0;
1492 }
1493 
1494 int parse_events__modifier_event(struct list_head *list, char *str, bool add)
1495 {
1496 	struct perf_evsel *evsel;
1497 	struct event_modifier mod;
1498 
1499 	if (str == NULL)
1500 		return 0;
1501 
1502 	if (check_modifier(str))
1503 		return -EINVAL;
1504 
1505 	if (!add && get_event_modifier(&mod, str, NULL))
1506 		return -EINVAL;
1507 
1508 	__evlist__for_each_entry(list, evsel) {
1509 		if (add && get_event_modifier(&mod, str, evsel))
1510 			return -EINVAL;
1511 
1512 		evsel->attr.exclude_user   = mod.eu;
1513 		evsel->attr.exclude_kernel = mod.ek;
1514 		evsel->attr.exclude_hv     = mod.eh;
1515 		evsel->attr.precise_ip     = mod.precise;
1516 		evsel->attr.exclude_host   = mod.eH;
1517 		evsel->attr.exclude_guest  = mod.eG;
1518 		evsel->attr.exclude_idle   = mod.eI;
1519 		evsel->exclude_GH          = mod.exclude_GH;
1520 		evsel->sample_read         = mod.sample_read;
1521 		evsel->precise_max         = mod.precise_max;
1522 		evsel->weak_group	   = mod.weak;
1523 
1524 		if (perf_evsel__is_group_leader(evsel))
1525 			evsel->attr.pinned = mod.pinned;
1526 	}
1527 
1528 	return 0;
1529 }
1530 
1531 int parse_events_name(struct list_head *list, char *name)
1532 {
1533 	struct perf_evsel *evsel;
1534 
1535 	__evlist__for_each_entry(list, evsel) {
1536 		if (!evsel->name)
1537 			evsel->name = strdup(name);
1538 	}
1539 
1540 	return 0;
1541 }
1542 
1543 static int
1544 comp_pmu(const void *p1, const void *p2)
1545 {
1546 	struct perf_pmu_event_symbol *pmu1 = (struct perf_pmu_event_symbol *) p1;
1547 	struct perf_pmu_event_symbol *pmu2 = (struct perf_pmu_event_symbol *) p2;
1548 
1549 	return strcasecmp(pmu1->symbol, pmu2->symbol);
1550 }
1551 
1552 static void perf_pmu__parse_cleanup(void)
1553 {
1554 	if (perf_pmu_events_list_num > 0) {
1555 		struct perf_pmu_event_symbol *p;
1556 		int i;
1557 
1558 		for (i = 0; i < perf_pmu_events_list_num; i++) {
1559 			p = perf_pmu_events_list + i;
1560 			zfree(&p->symbol);
1561 		}
1562 		zfree(&perf_pmu_events_list);
1563 		perf_pmu_events_list_num = 0;
1564 	}
1565 }
1566 
1567 #define SET_SYMBOL(str, stype)		\
1568 do {					\
1569 	p->symbol = str;		\
1570 	if (!p->symbol)			\
1571 		goto err;		\
1572 	p->type = stype;		\
1573 } while (0)
1574 
1575 /*
1576  * Read the pmu events list from sysfs
1577  * Save it into perf_pmu_events_list
1578  */
1579 static void perf_pmu__parse_init(void)
1580 {
1581 
1582 	struct perf_pmu *pmu = NULL;
1583 	struct perf_pmu_alias *alias;
1584 	int len = 0;
1585 
1586 	pmu = NULL;
1587 	while ((pmu = perf_pmu__scan(pmu)) != NULL) {
1588 		list_for_each_entry(alias, &pmu->aliases, list) {
1589 			if (strchr(alias->name, '-'))
1590 				len++;
1591 			len++;
1592 		}
1593 	}
1594 
1595 	if (len == 0) {
1596 		perf_pmu_events_list_num = -1;
1597 		return;
1598 	}
1599 	perf_pmu_events_list = malloc(sizeof(struct perf_pmu_event_symbol) * len);
1600 	if (!perf_pmu_events_list)
1601 		return;
1602 	perf_pmu_events_list_num = len;
1603 
1604 	len = 0;
1605 	pmu = NULL;
1606 	while ((pmu = perf_pmu__scan(pmu)) != NULL) {
1607 		list_for_each_entry(alias, &pmu->aliases, list) {
1608 			struct perf_pmu_event_symbol *p = perf_pmu_events_list + len;
1609 			char *tmp = strchr(alias->name, '-');
1610 
1611 			if (tmp != NULL) {
1612 				SET_SYMBOL(strndup(alias->name, tmp - alias->name),
1613 						PMU_EVENT_SYMBOL_PREFIX);
1614 				p++;
1615 				SET_SYMBOL(strdup(++tmp), PMU_EVENT_SYMBOL_SUFFIX);
1616 				len += 2;
1617 			} else {
1618 				SET_SYMBOL(strdup(alias->name), PMU_EVENT_SYMBOL);
1619 				len++;
1620 			}
1621 		}
1622 	}
1623 	qsort(perf_pmu_events_list, len,
1624 		sizeof(struct perf_pmu_event_symbol), comp_pmu);
1625 
1626 	return;
1627 err:
1628 	perf_pmu__parse_cleanup();
1629 }
1630 
1631 enum perf_pmu_event_symbol_type
1632 perf_pmu__parse_check(const char *name)
1633 {
1634 	struct perf_pmu_event_symbol p, *r;
1635 
1636 	/* scan kernel pmu events from sysfs if needed */
1637 	if (perf_pmu_events_list_num == 0)
1638 		perf_pmu__parse_init();
1639 	/*
1640 	 * name "cpu" could be prefix of cpu-cycles or cpu// events.
1641 	 * cpu-cycles has been handled by hardcode.
1642 	 * So it must be cpu// events, not kernel pmu event.
1643 	 */
1644 	if ((perf_pmu_events_list_num <= 0) || !strcmp(name, "cpu"))
1645 		return PMU_EVENT_SYMBOL_ERR;
1646 
1647 	p.symbol = strdup(name);
1648 	r = bsearch(&p, perf_pmu_events_list,
1649 			(size_t) perf_pmu_events_list_num,
1650 			sizeof(struct perf_pmu_event_symbol), comp_pmu);
1651 	zfree(&p.symbol);
1652 	return r ? r->type : PMU_EVENT_SYMBOL_ERR;
1653 }
1654 
1655 static int parse_events__scanner(const char *str, void *parse_state, int start_token)
1656 {
1657 	YY_BUFFER_STATE buffer;
1658 	void *scanner;
1659 	int ret;
1660 
1661 	ret = parse_events_lex_init_extra(start_token, &scanner);
1662 	if (ret)
1663 		return ret;
1664 
1665 	buffer = parse_events__scan_string(str, scanner);
1666 
1667 #ifdef PARSER_DEBUG
1668 	parse_events_debug = 1;
1669 #endif
1670 	ret = parse_events_parse(parse_state, scanner);
1671 
1672 	parse_events__flush_buffer(buffer, scanner);
1673 	parse_events__delete_buffer(buffer, scanner);
1674 	parse_events_lex_destroy(scanner);
1675 	return ret;
1676 }
1677 
1678 /*
1679  * parse event config string, return a list of event terms.
1680  */
1681 int parse_events_terms(struct list_head *terms, const char *str)
1682 {
1683 	struct parse_events_state parse_state = {
1684 		.terms = NULL,
1685 	};
1686 	int ret;
1687 
1688 	ret = parse_events__scanner(str, &parse_state, PE_START_TERMS);
1689 	if (!ret) {
1690 		list_splice(parse_state.terms, terms);
1691 		zfree(&parse_state.terms);
1692 		return 0;
1693 	}
1694 
1695 	parse_events_terms__delete(parse_state.terms);
1696 	return ret;
1697 }
1698 
1699 int parse_events(struct perf_evlist *evlist, const char *str,
1700 		 struct parse_events_error *err)
1701 {
1702 	struct parse_events_state parse_state = {
1703 		.list   = LIST_HEAD_INIT(parse_state.list),
1704 		.idx    = evlist->nr_entries,
1705 		.error  = err,
1706 		.evlist = evlist,
1707 	};
1708 	int ret;
1709 
1710 	ret = parse_events__scanner(str, &parse_state, PE_START_EVENTS);
1711 	perf_pmu__parse_cleanup();
1712 	if (!ret) {
1713 		struct perf_evsel *last;
1714 
1715 		if (list_empty(&parse_state.list)) {
1716 			WARN_ONCE(true, "WARNING: event parser found nothing");
1717 			return -1;
1718 		}
1719 
1720 		perf_evlist__splice_list_tail(evlist, &parse_state.list);
1721 		evlist->nr_groups += parse_state.nr_groups;
1722 		last = perf_evlist__last(evlist);
1723 		last->cmdline_group_boundary = true;
1724 
1725 		return 0;
1726 	}
1727 
1728 	/*
1729 	 * There are 2 users - builtin-record and builtin-test objects.
1730 	 * Both call perf_evlist__delete in case of error, so we dont
1731 	 * need to bother.
1732 	 */
1733 	return ret;
1734 }
1735 
1736 #define MAX_WIDTH 1000
1737 static int get_term_width(void)
1738 {
1739 	struct winsize ws;
1740 
1741 	get_term_dimensions(&ws);
1742 	return ws.ws_col > MAX_WIDTH ? MAX_WIDTH : ws.ws_col;
1743 }
1744 
1745 void parse_events_print_error(struct parse_events_error *err,
1746 			      const char *event)
1747 {
1748 	const char *str = "invalid or unsupported event: ";
1749 	char _buf[MAX_WIDTH];
1750 	char *buf = (char *) event;
1751 	int idx = 0;
1752 
1753 	if (err->str) {
1754 		/* -2 for extra '' in the final fprintf */
1755 		int width       = get_term_width() - 2;
1756 		int len_event   = strlen(event);
1757 		int len_str, max_len, cut = 0;
1758 
1759 		/*
1760 		 * Maximum error index indent, we will cut
1761 		 * the event string if it's bigger.
1762 		 */
1763 		int max_err_idx = 13;
1764 
1765 		/*
1766 		 * Let's be specific with the message when
1767 		 * we have the precise error.
1768 		 */
1769 		str     = "event syntax error: ";
1770 		len_str = strlen(str);
1771 		max_len = width - len_str;
1772 
1773 		buf = _buf;
1774 
1775 		/* We're cutting from the beginning. */
1776 		if (err->idx > max_err_idx)
1777 			cut = err->idx - max_err_idx;
1778 
1779 		strncpy(buf, event + cut, max_len);
1780 
1781 		/* Mark cut parts with '..' on both sides. */
1782 		if (cut)
1783 			buf[0] = buf[1] = '.';
1784 
1785 		if ((len_event - cut) > max_len) {
1786 			buf[max_len - 1] = buf[max_len - 2] = '.';
1787 			buf[max_len] = 0;
1788 		}
1789 
1790 		idx = len_str + err->idx - cut;
1791 	}
1792 
1793 	fprintf(stderr, "%s'%s'\n", str, buf);
1794 	if (idx) {
1795 		fprintf(stderr, "%*s\\___ %s\n", idx + 1, "", err->str);
1796 		if (err->help)
1797 			fprintf(stderr, "\n%s\n", err->help);
1798 		zfree(&err->str);
1799 		zfree(&err->help);
1800 	}
1801 }
1802 
1803 #undef MAX_WIDTH
1804 
1805 int parse_events_option(const struct option *opt, const char *str,
1806 			int unset __maybe_unused)
1807 {
1808 	struct perf_evlist *evlist = *(struct perf_evlist **)opt->value;
1809 	struct parse_events_error err = { .idx = 0, };
1810 	int ret = parse_events(evlist, str, &err);
1811 
1812 	if (ret) {
1813 		parse_events_print_error(&err, str);
1814 		fprintf(stderr, "Run 'perf list' for a list of valid events\n");
1815 	}
1816 
1817 	return ret;
1818 }
1819 
1820 static int
1821 foreach_evsel_in_last_glob(struct perf_evlist *evlist,
1822 			   int (*func)(struct perf_evsel *evsel,
1823 				       const void *arg),
1824 			   const void *arg)
1825 {
1826 	struct perf_evsel *last = NULL;
1827 	int err;
1828 
1829 	/*
1830 	 * Don't return when list_empty, give func a chance to report
1831 	 * error when it found last == NULL.
1832 	 *
1833 	 * So no need to WARN here, let *func do this.
1834 	 */
1835 	if (evlist->nr_entries > 0)
1836 		last = perf_evlist__last(evlist);
1837 
1838 	do {
1839 		err = (*func)(last, arg);
1840 		if (err)
1841 			return -1;
1842 		if (!last)
1843 			return 0;
1844 
1845 		if (last->node.prev == &evlist->entries)
1846 			return 0;
1847 		last = list_entry(last->node.prev, struct perf_evsel, node);
1848 	} while (!last->cmdline_group_boundary);
1849 
1850 	return 0;
1851 }
1852 
1853 static int set_filter(struct perf_evsel *evsel, const void *arg)
1854 {
1855 	const char *str = arg;
1856 	bool found = false;
1857 	int nr_addr_filters = 0;
1858 	struct perf_pmu *pmu = NULL;
1859 
1860 	if (evsel == NULL)
1861 		goto err;
1862 
1863 	if (evsel->attr.type == PERF_TYPE_TRACEPOINT) {
1864 		if (perf_evsel__append_tp_filter(evsel, str) < 0) {
1865 			fprintf(stderr,
1866 				"not enough memory to hold filter string\n");
1867 			return -1;
1868 		}
1869 
1870 		return 0;
1871 	}
1872 
1873 	while ((pmu = perf_pmu__scan(pmu)) != NULL)
1874 		if (pmu->type == evsel->attr.type) {
1875 			found = true;
1876 			break;
1877 		}
1878 
1879 	if (found)
1880 		perf_pmu__scan_file(pmu, "nr_addr_filters",
1881 				    "%d", &nr_addr_filters);
1882 
1883 	if (!nr_addr_filters)
1884 		goto err;
1885 
1886 	if (perf_evsel__append_addr_filter(evsel, str) < 0) {
1887 		fprintf(stderr,
1888 			"not enough memory to hold filter string\n");
1889 		return -1;
1890 	}
1891 
1892 	return 0;
1893 
1894 err:
1895 	fprintf(stderr,
1896 		"--filter option should follow a -e tracepoint or HW tracer option\n");
1897 
1898 	return -1;
1899 }
1900 
1901 int parse_filter(const struct option *opt, const char *str,
1902 		 int unset __maybe_unused)
1903 {
1904 	struct perf_evlist *evlist = *(struct perf_evlist **)opt->value;
1905 
1906 	return foreach_evsel_in_last_glob(evlist, set_filter,
1907 					  (const void *)str);
1908 }
1909 
1910 static int add_exclude_perf_filter(struct perf_evsel *evsel,
1911 				   const void *arg __maybe_unused)
1912 {
1913 	char new_filter[64];
1914 
1915 	if (evsel == NULL || evsel->attr.type != PERF_TYPE_TRACEPOINT) {
1916 		fprintf(stderr,
1917 			"--exclude-perf option should follow a -e tracepoint option\n");
1918 		return -1;
1919 	}
1920 
1921 	snprintf(new_filter, sizeof(new_filter), "common_pid != %d", getpid());
1922 
1923 	if (perf_evsel__append_tp_filter(evsel, new_filter) < 0) {
1924 		fprintf(stderr,
1925 			"not enough memory to hold filter string\n");
1926 		return -1;
1927 	}
1928 
1929 	return 0;
1930 }
1931 
1932 int exclude_perf(const struct option *opt,
1933 		 const char *arg __maybe_unused,
1934 		 int unset __maybe_unused)
1935 {
1936 	struct perf_evlist *evlist = *(struct perf_evlist **)opt->value;
1937 
1938 	return foreach_evsel_in_last_glob(evlist, add_exclude_perf_filter,
1939 					  NULL);
1940 }
1941 
1942 static const char * const event_type_descriptors[] = {
1943 	"Hardware event",
1944 	"Software event",
1945 	"Tracepoint event",
1946 	"Hardware cache event",
1947 	"Raw hardware event descriptor",
1948 	"Hardware breakpoint",
1949 };
1950 
1951 static int cmp_string(const void *a, const void *b)
1952 {
1953 	const char * const *as = a;
1954 	const char * const *bs = b;
1955 
1956 	return strcmp(*as, *bs);
1957 }
1958 
1959 /*
1960  * Print the events from <debugfs_mount_point>/tracing/events
1961  */
1962 
1963 void print_tracepoint_events(const char *subsys_glob, const char *event_glob,
1964 			     bool name_only)
1965 {
1966 	DIR *sys_dir, *evt_dir;
1967 	struct dirent *sys_dirent, *evt_dirent;
1968 	char evt_path[MAXPATHLEN];
1969 	char dir_path[MAXPATHLEN];
1970 	char **evt_list = NULL;
1971 	unsigned int evt_i = 0, evt_num = 0;
1972 	bool evt_num_known = false;
1973 
1974 restart:
1975 	sys_dir = opendir(tracing_events_path);
1976 	if (!sys_dir)
1977 		return;
1978 
1979 	if (evt_num_known) {
1980 		evt_list = zalloc(sizeof(char *) * evt_num);
1981 		if (!evt_list)
1982 			goto out_close_sys_dir;
1983 	}
1984 
1985 	for_each_subsystem(sys_dir, sys_dirent) {
1986 		if (subsys_glob != NULL &&
1987 		    !strglobmatch(sys_dirent->d_name, subsys_glob))
1988 			continue;
1989 
1990 		snprintf(dir_path, MAXPATHLEN, "%s/%s", tracing_events_path,
1991 			 sys_dirent->d_name);
1992 		evt_dir = opendir(dir_path);
1993 		if (!evt_dir)
1994 			continue;
1995 
1996 		for_each_event(sys_dirent, evt_dir, evt_dirent) {
1997 			if (event_glob != NULL &&
1998 			    !strglobmatch(evt_dirent->d_name, event_glob))
1999 				continue;
2000 
2001 			if (!evt_num_known) {
2002 				evt_num++;
2003 				continue;
2004 			}
2005 
2006 			snprintf(evt_path, MAXPATHLEN, "%s:%s",
2007 				 sys_dirent->d_name, evt_dirent->d_name);
2008 
2009 			evt_list[evt_i] = strdup(evt_path);
2010 			if (evt_list[evt_i] == NULL)
2011 				goto out_close_evt_dir;
2012 			evt_i++;
2013 		}
2014 		closedir(evt_dir);
2015 	}
2016 	closedir(sys_dir);
2017 
2018 	if (!evt_num_known) {
2019 		evt_num_known = true;
2020 		goto restart;
2021 	}
2022 	qsort(evt_list, evt_num, sizeof(char *), cmp_string);
2023 	evt_i = 0;
2024 	while (evt_i < evt_num) {
2025 		if (name_only) {
2026 			printf("%s ", evt_list[evt_i++]);
2027 			continue;
2028 		}
2029 		printf("  %-50s [%s]\n", evt_list[evt_i++],
2030 				event_type_descriptors[PERF_TYPE_TRACEPOINT]);
2031 	}
2032 	if (evt_num && pager_in_use())
2033 		printf("\n");
2034 
2035 out_free:
2036 	evt_num = evt_i;
2037 	for (evt_i = 0; evt_i < evt_num; evt_i++)
2038 		zfree(&evt_list[evt_i]);
2039 	zfree(&evt_list);
2040 	return;
2041 
2042 out_close_evt_dir:
2043 	closedir(evt_dir);
2044 out_close_sys_dir:
2045 	closedir(sys_dir);
2046 
2047 	printf("FATAL: not enough memory to print %s\n",
2048 			event_type_descriptors[PERF_TYPE_TRACEPOINT]);
2049 	if (evt_list)
2050 		goto out_free;
2051 }
2052 
2053 /*
2054  * Check whether event is in <debugfs_mount_point>/tracing/events
2055  */
2056 
2057 int is_valid_tracepoint(const char *event_string)
2058 {
2059 	DIR *sys_dir, *evt_dir;
2060 	struct dirent *sys_dirent, *evt_dirent;
2061 	char evt_path[MAXPATHLEN];
2062 	char dir_path[MAXPATHLEN];
2063 
2064 	sys_dir = opendir(tracing_events_path);
2065 	if (!sys_dir)
2066 		return 0;
2067 
2068 	for_each_subsystem(sys_dir, sys_dirent) {
2069 
2070 		snprintf(dir_path, MAXPATHLEN, "%s/%s", tracing_events_path,
2071 			 sys_dirent->d_name);
2072 		evt_dir = opendir(dir_path);
2073 		if (!evt_dir)
2074 			continue;
2075 
2076 		for_each_event(sys_dirent, evt_dir, evt_dirent) {
2077 			snprintf(evt_path, MAXPATHLEN, "%s:%s",
2078 				 sys_dirent->d_name, evt_dirent->d_name);
2079 			if (!strcmp(evt_path, event_string)) {
2080 				closedir(evt_dir);
2081 				closedir(sys_dir);
2082 				return 1;
2083 			}
2084 		}
2085 		closedir(evt_dir);
2086 	}
2087 	closedir(sys_dir);
2088 	return 0;
2089 }
2090 
2091 static bool is_event_supported(u8 type, unsigned config)
2092 {
2093 	bool ret = true;
2094 	int open_return;
2095 	struct perf_evsel *evsel;
2096 	struct perf_event_attr attr = {
2097 		.type = type,
2098 		.config = config,
2099 		.disabled = 1,
2100 	};
2101 	struct thread_map *tmap = thread_map__new_by_tid(0);
2102 
2103 	if (tmap == NULL)
2104 		return false;
2105 
2106 	evsel = perf_evsel__new(&attr);
2107 	if (evsel) {
2108 		open_return = perf_evsel__open(evsel, NULL, tmap);
2109 		ret = open_return >= 0;
2110 
2111 		if (open_return == -EACCES) {
2112 			/*
2113 			 * This happens if the paranoid value
2114 			 * /proc/sys/kernel/perf_event_paranoid is set to 2
2115 			 * Re-run with exclude_kernel set; we don't do that
2116 			 * by default as some ARM machines do not support it.
2117 			 *
2118 			 */
2119 			evsel->attr.exclude_kernel = 1;
2120 			ret = perf_evsel__open(evsel, NULL, tmap) >= 0;
2121 		}
2122 		perf_evsel__delete(evsel);
2123 	}
2124 
2125 	return ret;
2126 }
2127 
2128 void print_sdt_events(const char *subsys_glob, const char *event_glob,
2129 		      bool name_only)
2130 {
2131 	struct probe_cache *pcache;
2132 	struct probe_cache_entry *ent;
2133 	struct strlist *bidlist, *sdtlist;
2134 	struct strlist_config cfg = {.dont_dupstr = true};
2135 	struct str_node *nd, *nd2;
2136 	char *buf, *path, *ptr = NULL;
2137 	bool show_detail = false;
2138 	int ret;
2139 
2140 	sdtlist = strlist__new(NULL, &cfg);
2141 	if (!sdtlist) {
2142 		pr_debug("Failed to allocate new strlist for SDT\n");
2143 		return;
2144 	}
2145 	bidlist = build_id_cache__list_all(true);
2146 	if (!bidlist) {
2147 		pr_debug("Failed to get buildids: %d\n", errno);
2148 		return;
2149 	}
2150 	strlist__for_each_entry(nd, bidlist) {
2151 		pcache = probe_cache__new(nd->s, NULL);
2152 		if (!pcache)
2153 			continue;
2154 		list_for_each_entry(ent, &pcache->entries, node) {
2155 			if (!ent->sdt)
2156 				continue;
2157 			if (subsys_glob &&
2158 			    !strglobmatch(ent->pev.group, subsys_glob))
2159 				continue;
2160 			if (event_glob &&
2161 			    !strglobmatch(ent->pev.event, event_glob))
2162 				continue;
2163 			ret = asprintf(&buf, "%s:%s@%s", ent->pev.group,
2164 					ent->pev.event, nd->s);
2165 			if (ret > 0)
2166 				strlist__add(sdtlist, buf);
2167 		}
2168 		probe_cache__delete(pcache);
2169 	}
2170 	strlist__delete(bidlist);
2171 
2172 	strlist__for_each_entry(nd, sdtlist) {
2173 		buf = strchr(nd->s, '@');
2174 		if (buf)
2175 			*(buf++) = '\0';
2176 		if (name_only) {
2177 			printf("%s ", nd->s);
2178 			continue;
2179 		}
2180 		nd2 = strlist__next(nd);
2181 		if (nd2) {
2182 			ptr = strchr(nd2->s, '@');
2183 			if (ptr)
2184 				*ptr = '\0';
2185 			if (strcmp(nd->s, nd2->s) == 0)
2186 				show_detail = true;
2187 		}
2188 		if (show_detail) {
2189 			path = build_id_cache__origname(buf);
2190 			ret = asprintf(&buf, "%s@%s(%.12s)", nd->s, path, buf);
2191 			if (ret > 0) {
2192 				printf("  %-50s [%s]\n", buf, "SDT event");
2193 				free(buf);
2194 			}
2195 		} else
2196 			printf("  %-50s [%s]\n", nd->s, "SDT event");
2197 		if (nd2) {
2198 			if (strcmp(nd->s, nd2->s) != 0)
2199 				show_detail = false;
2200 			if (ptr)
2201 				*ptr = '@';
2202 		}
2203 	}
2204 	strlist__delete(sdtlist);
2205 }
2206 
2207 int print_hwcache_events(const char *event_glob, bool name_only)
2208 {
2209 	unsigned int type, op, i, evt_i = 0, evt_num = 0;
2210 	char name[64];
2211 	char **evt_list = NULL;
2212 	bool evt_num_known = false;
2213 
2214 restart:
2215 	if (evt_num_known) {
2216 		evt_list = zalloc(sizeof(char *) * evt_num);
2217 		if (!evt_list)
2218 			goto out_enomem;
2219 	}
2220 
2221 	for (type = 0; type < PERF_COUNT_HW_CACHE_MAX; type++) {
2222 		for (op = 0; op < PERF_COUNT_HW_CACHE_OP_MAX; op++) {
2223 			/* skip invalid cache type */
2224 			if (!perf_evsel__is_cache_op_valid(type, op))
2225 				continue;
2226 
2227 			for (i = 0; i < PERF_COUNT_HW_CACHE_RESULT_MAX; i++) {
2228 				__perf_evsel__hw_cache_type_op_res_name(type, op, i,
2229 									name, sizeof(name));
2230 				if (event_glob != NULL && !strglobmatch(name, event_glob))
2231 					continue;
2232 
2233 				if (!is_event_supported(PERF_TYPE_HW_CACHE,
2234 							type | (op << 8) | (i << 16)))
2235 					continue;
2236 
2237 				if (!evt_num_known) {
2238 					evt_num++;
2239 					continue;
2240 				}
2241 
2242 				evt_list[evt_i] = strdup(name);
2243 				if (evt_list[evt_i] == NULL)
2244 					goto out_enomem;
2245 				evt_i++;
2246 			}
2247 		}
2248 	}
2249 
2250 	if (!evt_num_known) {
2251 		evt_num_known = true;
2252 		goto restart;
2253 	}
2254 	qsort(evt_list, evt_num, sizeof(char *), cmp_string);
2255 	evt_i = 0;
2256 	while (evt_i < evt_num) {
2257 		if (name_only) {
2258 			printf("%s ", evt_list[evt_i++]);
2259 			continue;
2260 		}
2261 		printf("  %-50s [%s]\n", evt_list[evt_i++],
2262 				event_type_descriptors[PERF_TYPE_HW_CACHE]);
2263 	}
2264 	if (evt_num && pager_in_use())
2265 		printf("\n");
2266 
2267 out_free:
2268 	evt_num = evt_i;
2269 	for (evt_i = 0; evt_i < evt_num; evt_i++)
2270 		zfree(&evt_list[evt_i]);
2271 	zfree(&evt_list);
2272 	return evt_num;
2273 
2274 out_enomem:
2275 	printf("FATAL: not enough memory to print %s\n", event_type_descriptors[PERF_TYPE_HW_CACHE]);
2276 	if (evt_list)
2277 		goto out_free;
2278 	return evt_num;
2279 }
2280 
2281 void print_symbol_events(const char *event_glob, unsigned type,
2282 				struct event_symbol *syms, unsigned max,
2283 				bool name_only)
2284 {
2285 	unsigned int i, evt_i = 0, evt_num = 0;
2286 	char name[MAX_NAME_LEN];
2287 	char **evt_list = NULL;
2288 	bool evt_num_known = false;
2289 
2290 restart:
2291 	if (evt_num_known) {
2292 		evt_list = zalloc(sizeof(char *) * evt_num);
2293 		if (!evt_list)
2294 			goto out_enomem;
2295 		syms -= max;
2296 	}
2297 
2298 	for (i = 0; i < max; i++, syms++) {
2299 
2300 		if (event_glob != NULL && syms->symbol != NULL &&
2301 		    !(strglobmatch(syms->symbol, event_glob) ||
2302 		      (syms->alias && strglobmatch(syms->alias, event_glob))))
2303 			continue;
2304 
2305 		if (!is_event_supported(type, i))
2306 			continue;
2307 
2308 		if (!evt_num_known) {
2309 			evt_num++;
2310 			continue;
2311 		}
2312 
2313 		if (!name_only && strlen(syms->alias))
2314 			snprintf(name, MAX_NAME_LEN, "%s OR %s", syms->symbol, syms->alias);
2315 		else
2316 			strncpy(name, syms->symbol, MAX_NAME_LEN);
2317 
2318 		evt_list[evt_i] = strdup(name);
2319 		if (evt_list[evt_i] == NULL)
2320 			goto out_enomem;
2321 		evt_i++;
2322 	}
2323 
2324 	if (!evt_num_known) {
2325 		evt_num_known = true;
2326 		goto restart;
2327 	}
2328 	qsort(evt_list, evt_num, sizeof(char *), cmp_string);
2329 	evt_i = 0;
2330 	while (evt_i < evt_num) {
2331 		if (name_only) {
2332 			printf("%s ", evt_list[evt_i++]);
2333 			continue;
2334 		}
2335 		printf("  %-50s [%s]\n", evt_list[evt_i++], event_type_descriptors[type]);
2336 	}
2337 	if (evt_num && pager_in_use())
2338 		printf("\n");
2339 
2340 out_free:
2341 	evt_num = evt_i;
2342 	for (evt_i = 0; evt_i < evt_num; evt_i++)
2343 		zfree(&evt_list[evt_i]);
2344 	zfree(&evt_list);
2345 	return;
2346 
2347 out_enomem:
2348 	printf("FATAL: not enough memory to print %s\n", event_type_descriptors[type]);
2349 	if (evt_list)
2350 		goto out_free;
2351 }
2352 
2353 /*
2354  * Print the help text for the event symbols:
2355  */
2356 void print_events(const char *event_glob, bool name_only, bool quiet_flag,
2357 			bool long_desc, bool details_flag)
2358 {
2359 	print_symbol_events(event_glob, PERF_TYPE_HARDWARE,
2360 			    event_symbols_hw, PERF_COUNT_HW_MAX, name_only);
2361 
2362 	print_symbol_events(event_glob, PERF_TYPE_SOFTWARE,
2363 			    event_symbols_sw, PERF_COUNT_SW_MAX, name_only);
2364 
2365 	print_hwcache_events(event_glob, name_only);
2366 
2367 	print_pmu_events(event_glob, name_only, quiet_flag, long_desc,
2368 			details_flag);
2369 
2370 	if (event_glob != NULL)
2371 		return;
2372 
2373 	if (!name_only) {
2374 		printf("  %-50s [%s]\n",
2375 		       "rNNN",
2376 		       event_type_descriptors[PERF_TYPE_RAW]);
2377 		printf("  %-50s [%s]\n",
2378 		       "cpu/t1=v1[,t2=v2,t3 ...]/modifier",
2379 		       event_type_descriptors[PERF_TYPE_RAW]);
2380 		if (pager_in_use())
2381 			printf("   (see 'man perf-list' on how to encode it)\n\n");
2382 
2383 		printf("  %-50s [%s]\n",
2384 		       "mem:<addr>[/len][:access]",
2385 			event_type_descriptors[PERF_TYPE_BREAKPOINT]);
2386 		if (pager_in_use())
2387 			printf("\n");
2388 	}
2389 
2390 	print_tracepoint_events(NULL, NULL, name_only);
2391 
2392 	print_sdt_events(NULL, NULL, name_only);
2393 
2394 	metricgroup__print(true, true, NULL, name_only);
2395 }
2396 
2397 int parse_events__is_hardcoded_term(struct parse_events_term *term)
2398 {
2399 	return term->type_term != PARSE_EVENTS__TERM_TYPE_USER;
2400 }
2401 
2402 static int new_term(struct parse_events_term **_term,
2403 		    struct parse_events_term *temp,
2404 		    char *str, u64 num)
2405 {
2406 	struct parse_events_term *term;
2407 
2408 	term = malloc(sizeof(*term));
2409 	if (!term)
2410 		return -ENOMEM;
2411 
2412 	*term = *temp;
2413 	INIT_LIST_HEAD(&term->list);
2414 	term->weak = false;
2415 
2416 	switch (term->type_val) {
2417 	case PARSE_EVENTS__TERM_TYPE_NUM:
2418 		term->val.num = num;
2419 		break;
2420 	case PARSE_EVENTS__TERM_TYPE_STR:
2421 		term->val.str = str;
2422 		break;
2423 	default:
2424 		free(term);
2425 		return -EINVAL;
2426 	}
2427 
2428 	*_term = term;
2429 	return 0;
2430 }
2431 
2432 int parse_events_term__num(struct parse_events_term **term,
2433 			   int type_term, char *config, u64 num,
2434 			   bool no_value,
2435 			   void *loc_term_, void *loc_val_)
2436 {
2437 	YYLTYPE *loc_term = loc_term_;
2438 	YYLTYPE *loc_val = loc_val_;
2439 
2440 	struct parse_events_term temp = {
2441 		.type_val  = PARSE_EVENTS__TERM_TYPE_NUM,
2442 		.type_term = type_term,
2443 		.config    = config,
2444 		.no_value  = no_value,
2445 		.err_term  = loc_term ? loc_term->first_column : 0,
2446 		.err_val   = loc_val  ? loc_val->first_column  : 0,
2447 	};
2448 
2449 	return new_term(term, &temp, NULL, num);
2450 }
2451 
2452 int parse_events_term__str(struct parse_events_term **term,
2453 			   int type_term, char *config, char *str,
2454 			   void *loc_term_, void *loc_val_)
2455 {
2456 	YYLTYPE *loc_term = loc_term_;
2457 	YYLTYPE *loc_val = loc_val_;
2458 
2459 	struct parse_events_term temp = {
2460 		.type_val  = PARSE_EVENTS__TERM_TYPE_STR,
2461 		.type_term = type_term,
2462 		.config    = config,
2463 		.err_term  = loc_term ? loc_term->first_column : 0,
2464 		.err_val   = loc_val  ? loc_val->first_column  : 0,
2465 	};
2466 
2467 	return new_term(term, &temp, str, 0);
2468 }
2469 
2470 int parse_events_term__sym_hw(struct parse_events_term **term,
2471 			      char *config, unsigned idx)
2472 {
2473 	struct event_symbol *sym;
2474 	struct parse_events_term temp = {
2475 		.type_val  = PARSE_EVENTS__TERM_TYPE_STR,
2476 		.type_term = PARSE_EVENTS__TERM_TYPE_USER,
2477 		.config    = config ?: (char *) "event",
2478 	};
2479 
2480 	BUG_ON(idx >= PERF_COUNT_HW_MAX);
2481 	sym = &event_symbols_hw[idx];
2482 
2483 	return new_term(term, &temp, (char *) sym->symbol, 0);
2484 }
2485 
2486 int parse_events_term__clone(struct parse_events_term **new,
2487 			     struct parse_events_term *term)
2488 {
2489 	struct parse_events_term temp = {
2490 		.type_val  = term->type_val,
2491 		.type_term = term->type_term,
2492 		.config    = term->config,
2493 		.err_term  = term->err_term,
2494 		.err_val   = term->err_val,
2495 	};
2496 
2497 	return new_term(new, &temp, term->val.str, term->val.num);
2498 }
2499 
2500 int parse_events_copy_term_list(struct list_head *old,
2501 				 struct list_head **new)
2502 {
2503 	struct parse_events_term *term, *n;
2504 	int ret;
2505 
2506 	if (!old) {
2507 		*new = NULL;
2508 		return 0;
2509 	}
2510 
2511 	*new = malloc(sizeof(struct list_head));
2512 	if (!*new)
2513 		return -ENOMEM;
2514 	INIT_LIST_HEAD(*new);
2515 
2516 	list_for_each_entry (term, old, list) {
2517 		ret = parse_events_term__clone(&n, term);
2518 		if (ret)
2519 			return ret;
2520 		list_add_tail(&n->list, *new);
2521 	}
2522 	return 0;
2523 }
2524 
2525 void parse_events_terms__purge(struct list_head *terms)
2526 {
2527 	struct parse_events_term *term, *h;
2528 
2529 	list_for_each_entry_safe(term, h, terms, list) {
2530 		if (term->array.nr_ranges)
2531 			zfree(&term->array.ranges);
2532 		list_del_init(&term->list);
2533 		free(term);
2534 	}
2535 }
2536 
2537 void parse_events_terms__delete(struct list_head *terms)
2538 {
2539 	if (!terms)
2540 		return;
2541 	parse_events_terms__purge(terms);
2542 	free(terms);
2543 }
2544 
2545 void parse_events__clear_array(struct parse_events_array *a)
2546 {
2547 	zfree(&a->ranges);
2548 }
2549 
2550 void parse_events_evlist_error(struct parse_events_state *parse_state,
2551 			       int idx, const char *str)
2552 {
2553 	struct parse_events_error *err = parse_state->error;
2554 
2555 	if (!err)
2556 		return;
2557 	err->idx = idx;
2558 	err->str = strdup(str);
2559 	WARN_ONCE(!err->str, "WARNING: failed to allocate error string");
2560 }
2561 
2562 static void config_terms_list(char *buf, size_t buf_sz)
2563 {
2564 	int i;
2565 	bool first = true;
2566 
2567 	buf[0] = '\0';
2568 	for (i = 0; i < __PARSE_EVENTS__TERM_TYPE_NR; i++) {
2569 		const char *name = config_term_names[i];
2570 
2571 		if (!config_term_avail(i, NULL))
2572 			continue;
2573 		if (!name)
2574 			continue;
2575 		if (name[0] == '<')
2576 			continue;
2577 
2578 		if (strlen(buf) + strlen(name) + 2 >= buf_sz)
2579 			return;
2580 
2581 		if (!first)
2582 			strcat(buf, ",");
2583 		else
2584 			first = false;
2585 		strcat(buf, name);
2586 	}
2587 }
2588 
2589 /*
2590  * Return string contains valid config terms of an event.
2591  * @additional_terms: For terms such as PMU sysfs terms.
2592  */
2593 char *parse_events_formats_error_string(char *additional_terms)
2594 {
2595 	char *str;
2596 	/* "no-overwrite" is the longest name */
2597 	char static_terms[__PARSE_EVENTS__TERM_TYPE_NR *
2598 			  (sizeof("no-overwrite") - 1)];
2599 
2600 	config_terms_list(static_terms, sizeof(static_terms));
2601 	/* valid terms */
2602 	if (additional_terms) {
2603 		if (asprintf(&str, "valid terms: %s,%s",
2604 			     additional_terms, static_terms) < 0)
2605 			goto fail;
2606 	} else {
2607 		if (asprintf(&str, "valid terms: %s", static_terms) < 0)
2608 			goto fail;
2609 	}
2610 	return str;
2611 
2612 fail:
2613 	return NULL;
2614 }
2615