xref: /openbmc/linux/tools/perf/util/parse-events.c (revision c4f7ac64)
1 // SPDX-License-Identifier: GPL-2.0
2 #include <linux/hw_breakpoint.h>
3 #include <linux/err.h>
4 #include <linux/zalloc.h>
5 #include <dirent.h>
6 #include <errno.h>
7 #include <sys/ioctl.h>
8 #include <sys/types.h>
9 #include <sys/stat.h>
10 #include <fcntl.h>
11 #include <sys/param.h>
12 #include "term.h"
13 #include "build-id.h"
14 #include "evlist.h"
15 #include "evsel.h"
16 #include <subcmd/pager.h>
17 #include <subcmd/parse-options.h>
18 #include "parse-events.h"
19 #include <subcmd/exec-cmd.h>
20 #include "string2.h"
21 #include "strlist.h"
22 #include "symbol.h"
23 #include "header.h"
24 #include "bpf-loader.h"
25 #include "debug.h"
26 #include <api/fs/tracing_path.h>
27 #include <perf/cpumap.h>
28 #include "parse-events-bison.h"
29 #define YY_EXTRA_TYPE void*
30 #include "parse-events-flex.h"
31 #include "pmu.h"
32 #include "thread_map.h"
33 #include "probe-file.h"
34 #include "asm/bug.h"
35 #include "util/parse-branch-options.h"
36 #include "metricgroup.h"
37 #include "util/evsel_config.h"
38 #include "util/event.h"
39 #include "util/pfm.h"
40 #include "util/parse-events-hybrid.h"
41 #include "util/pmu-hybrid.h"
42 #include "perf.h"
43 
44 #define MAX_NAME_LEN 100
45 
46 #ifdef PARSER_DEBUG
47 extern int parse_events_debug;
48 #endif
49 int parse_events_parse(void *parse_state, void *scanner);
50 static int get_config_terms(struct list_head *head_config,
51 			    struct list_head *head_terms __maybe_unused);
52 static int parse_events__with_hybrid_pmu(struct parse_events_state *parse_state,
53 					 const char *str, char *pmu_name,
54 					 struct list_head *list);
55 
56 static struct perf_pmu_event_symbol *perf_pmu_events_list;
57 /*
58  * The variable indicates the number of supported pmu event symbols.
59  * 0 means not initialized and ready to init
60  * -1 means failed to init, don't try anymore
61  * >0 is the number of supported pmu event symbols
62  */
63 static int perf_pmu_events_list_num;
64 
65 struct event_symbol event_symbols_hw[PERF_COUNT_HW_MAX] = {
66 	[PERF_COUNT_HW_CPU_CYCLES] = {
67 		.symbol = "cpu-cycles",
68 		.alias  = "cycles",
69 	},
70 	[PERF_COUNT_HW_INSTRUCTIONS] = {
71 		.symbol = "instructions",
72 		.alias  = "",
73 	},
74 	[PERF_COUNT_HW_CACHE_REFERENCES] = {
75 		.symbol = "cache-references",
76 		.alias  = "",
77 	},
78 	[PERF_COUNT_HW_CACHE_MISSES] = {
79 		.symbol = "cache-misses",
80 		.alias  = "",
81 	},
82 	[PERF_COUNT_HW_BRANCH_INSTRUCTIONS] = {
83 		.symbol = "branch-instructions",
84 		.alias  = "branches",
85 	},
86 	[PERF_COUNT_HW_BRANCH_MISSES] = {
87 		.symbol = "branch-misses",
88 		.alias  = "",
89 	},
90 	[PERF_COUNT_HW_BUS_CYCLES] = {
91 		.symbol = "bus-cycles",
92 		.alias  = "",
93 	},
94 	[PERF_COUNT_HW_STALLED_CYCLES_FRONTEND] = {
95 		.symbol = "stalled-cycles-frontend",
96 		.alias  = "idle-cycles-frontend",
97 	},
98 	[PERF_COUNT_HW_STALLED_CYCLES_BACKEND] = {
99 		.symbol = "stalled-cycles-backend",
100 		.alias  = "idle-cycles-backend",
101 	},
102 	[PERF_COUNT_HW_REF_CPU_CYCLES] = {
103 		.symbol = "ref-cycles",
104 		.alias  = "",
105 	},
106 };
107 
108 struct event_symbol event_symbols_sw[PERF_COUNT_SW_MAX] = {
109 	[PERF_COUNT_SW_CPU_CLOCK] = {
110 		.symbol = "cpu-clock",
111 		.alias  = "",
112 	},
113 	[PERF_COUNT_SW_TASK_CLOCK] = {
114 		.symbol = "task-clock",
115 		.alias  = "",
116 	},
117 	[PERF_COUNT_SW_PAGE_FAULTS] = {
118 		.symbol = "page-faults",
119 		.alias  = "faults",
120 	},
121 	[PERF_COUNT_SW_CONTEXT_SWITCHES] = {
122 		.symbol = "context-switches",
123 		.alias  = "cs",
124 	},
125 	[PERF_COUNT_SW_CPU_MIGRATIONS] = {
126 		.symbol = "cpu-migrations",
127 		.alias  = "migrations",
128 	},
129 	[PERF_COUNT_SW_PAGE_FAULTS_MIN] = {
130 		.symbol = "minor-faults",
131 		.alias  = "",
132 	},
133 	[PERF_COUNT_SW_PAGE_FAULTS_MAJ] = {
134 		.symbol = "major-faults",
135 		.alias  = "",
136 	},
137 	[PERF_COUNT_SW_ALIGNMENT_FAULTS] = {
138 		.symbol = "alignment-faults",
139 		.alias  = "",
140 	},
141 	[PERF_COUNT_SW_EMULATION_FAULTS] = {
142 		.symbol = "emulation-faults",
143 		.alias  = "",
144 	},
145 	[PERF_COUNT_SW_DUMMY] = {
146 		.symbol = "dummy",
147 		.alias  = "",
148 	},
149 	[PERF_COUNT_SW_BPF_OUTPUT] = {
150 		.symbol = "bpf-output",
151 		.alias  = "",
152 	},
153 };
154 
155 #define __PERF_EVENT_FIELD(config, name) \
156 	((config & PERF_EVENT_##name##_MASK) >> PERF_EVENT_##name##_SHIFT)
157 
158 #define PERF_EVENT_RAW(config)		__PERF_EVENT_FIELD(config, RAW)
159 #define PERF_EVENT_CONFIG(config)	__PERF_EVENT_FIELD(config, CONFIG)
160 #define PERF_EVENT_TYPE(config)		__PERF_EVENT_FIELD(config, TYPE)
161 #define PERF_EVENT_ID(config)		__PERF_EVENT_FIELD(config, EVENT)
162 
163 #define for_each_subsystem(sys_dir, sys_dirent)			\
164 	while ((sys_dirent = readdir(sys_dir)) != NULL)		\
165 		if (sys_dirent->d_type == DT_DIR &&		\
166 		    (strcmp(sys_dirent->d_name, ".")) &&	\
167 		    (strcmp(sys_dirent->d_name, "..")))
168 
169 static int tp_event_has_id(const char *dir_path, struct dirent *evt_dir)
170 {
171 	char evt_path[MAXPATHLEN];
172 	int fd;
173 
174 	snprintf(evt_path, MAXPATHLEN, "%s/%s/id", dir_path, evt_dir->d_name);
175 	fd = open(evt_path, O_RDONLY);
176 	if (fd < 0)
177 		return -EINVAL;
178 	close(fd);
179 
180 	return 0;
181 }
182 
183 #define for_each_event(dir_path, evt_dir, evt_dirent)		\
184 	while ((evt_dirent = readdir(evt_dir)) != NULL)		\
185 		if (evt_dirent->d_type == DT_DIR &&		\
186 		    (strcmp(evt_dirent->d_name, ".")) &&	\
187 		    (strcmp(evt_dirent->d_name, "..")) &&	\
188 		    (!tp_event_has_id(dir_path, evt_dirent)))
189 
190 #define MAX_EVENT_LENGTH 512
191 
192 void parse_events__handle_error(struct parse_events_error *err, int idx,
193 				char *str, char *help)
194 {
195 	if (WARN(!str, "WARNING: failed to provide error string\n")) {
196 		free(help);
197 		return;
198 	}
199 	switch (err->num_errors) {
200 	case 0:
201 		err->idx = idx;
202 		err->str = str;
203 		err->help = help;
204 		break;
205 	case 1:
206 		err->first_idx = err->idx;
207 		err->idx = idx;
208 		err->first_str = err->str;
209 		err->str = str;
210 		err->first_help = err->help;
211 		err->help = help;
212 		break;
213 	default:
214 		pr_debug("Multiple errors dropping message: %s (%s)\n",
215 			err->str, err->help);
216 		free(err->str);
217 		err->str = str;
218 		free(err->help);
219 		err->help = help;
220 		break;
221 	}
222 	err->num_errors++;
223 }
224 
225 struct tracepoint_path *tracepoint_id_to_path(u64 config)
226 {
227 	struct tracepoint_path *path = NULL;
228 	DIR *sys_dir, *evt_dir;
229 	struct dirent *sys_dirent, *evt_dirent;
230 	char id_buf[24];
231 	int fd;
232 	u64 id;
233 	char evt_path[MAXPATHLEN];
234 	char *dir_path;
235 
236 	sys_dir = tracing_events__opendir();
237 	if (!sys_dir)
238 		return NULL;
239 
240 	for_each_subsystem(sys_dir, sys_dirent) {
241 		dir_path = get_events_file(sys_dirent->d_name);
242 		if (!dir_path)
243 			continue;
244 		evt_dir = opendir(dir_path);
245 		if (!evt_dir)
246 			goto next;
247 
248 		for_each_event(dir_path, evt_dir, evt_dirent) {
249 
250 			scnprintf(evt_path, MAXPATHLEN, "%s/%s/id", dir_path,
251 				  evt_dirent->d_name);
252 			fd = open(evt_path, O_RDONLY);
253 			if (fd < 0)
254 				continue;
255 			if (read(fd, id_buf, sizeof(id_buf)) < 0) {
256 				close(fd);
257 				continue;
258 			}
259 			close(fd);
260 			id = atoll(id_buf);
261 			if (id == config) {
262 				put_events_file(dir_path);
263 				closedir(evt_dir);
264 				closedir(sys_dir);
265 				path = zalloc(sizeof(*path));
266 				if (!path)
267 					return NULL;
268 				if (asprintf(&path->system, "%.*s", MAX_EVENT_LENGTH, sys_dirent->d_name) < 0) {
269 					free(path);
270 					return NULL;
271 				}
272 				if (asprintf(&path->name, "%.*s", MAX_EVENT_LENGTH, evt_dirent->d_name) < 0) {
273 					zfree(&path->system);
274 					free(path);
275 					return NULL;
276 				}
277 				return path;
278 			}
279 		}
280 		closedir(evt_dir);
281 next:
282 		put_events_file(dir_path);
283 	}
284 
285 	closedir(sys_dir);
286 	return NULL;
287 }
288 
289 struct tracepoint_path *tracepoint_name_to_path(const char *name)
290 {
291 	struct tracepoint_path *path = zalloc(sizeof(*path));
292 	char *str = strchr(name, ':');
293 
294 	if (path == NULL || str == NULL) {
295 		free(path);
296 		return NULL;
297 	}
298 
299 	path->system = strndup(name, str - name);
300 	path->name = strdup(str+1);
301 
302 	if (path->system == NULL || path->name == NULL) {
303 		zfree(&path->system);
304 		zfree(&path->name);
305 		zfree(&path);
306 	}
307 
308 	return path;
309 }
310 
311 const char *event_type(int type)
312 {
313 	switch (type) {
314 	case PERF_TYPE_HARDWARE:
315 		return "hardware";
316 
317 	case PERF_TYPE_SOFTWARE:
318 		return "software";
319 
320 	case PERF_TYPE_TRACEPOINT:
321 		return "tracepoint";
322 
323 	case PERF_TYPE_HW_CACHE:
324 		return "hardware-cache";
325 
326 	default:
327 		break;
328 	}
329 
330 	return "unknown";
331 }
332 
333 static int parse_events__is_name_term(struct parse_events_term *term)
334 {
335 	return term->type_term == PARSE_EVENTS__TERM_TYPE_NAME;
336 }
337 
338 static char *get_config_name(struct list_head *head_terms)
339 {
340 	struct parse_events_term *term;
341 
342 	if (!head_terms)
343 		return NULL;
344 
345 	list_for_each_entry(term, head_terms, list)
346 		if (parse_events__is_name_term(term))
347 			return term->val.str;
348 
349 	return NULL;
350 }
351 
352 static struct evsel *
353 __add_event(struct list_head *list, int *idx,
354 	    struct perf_event_attr *attr,
355 	    bool init_attr,
356 	    char *name, struct perf_pmu *pmu,
357 	    struct list_head *config_terms, bool auto_merge_stats,
358 	    const char *cpu_list)
359 {
360 	struct evsel *evsel;
361 	struct perf_cpu_map *cpus = pmu ? perf_cpu_map__get(pmu->cpus) :
362 			       cpu_list ? perf_cpu_map__new(cpu_list) : NULL;
363 
364 	if (pmu && attr->type == PERF_TYPE_RAW)
365 		perf_pmu__warn_invalid_config(pmu, attr->config, name);
366 
367 	if (init_attr)
368 		event_attr_init(attr);
369 
370 	evsel = evsel__new_idx(attr, *idx);
371 	if (!evsel) {
372 		perf_cpu_map__put(cpus);
373 		return NULL;
374 	}
375 
376 	(*idx)++;
377 	evsel->core.cpus = cpus;
378 	evsel->core.own_cpus = perf_cpu_map__get(cpus);
379 	evsel->core.system_wide = pmu ? pmu->is_uncore : false;
380 	evsel->auto_merge_stats = auto_merge_stats;
381 
382 	if (name)
383 		evsel->name = strdup(name);
384 
385 	if (config_terms)
386 		list_splice(config_terms, &evsel->config_terms);
387 
388 	if (list)
389 		list_add_tail(&evsel->core.node, list);
390 
391 	return evsel;
392 }
393 
394 struct evsel *parse_events__add_event(int idx, struct perf_event_attr *attr,
395 					char *name, struct perf_pmu *pmu)
396 {
397 	return __add_event(NULL, &idx, attr, false, name, pmu, NULL, false,
398 			   NULL);
399 }
400 
401 static int add_event(struct list_head *list, int *idx,
402 		     struct perf_event_attr *attr, char *name,
403 		     struct list_head *config_terms)
404 {
405 	return __add_event(list, idx, attr, true, name, NULL, config_terms,
406 			   false, NULL) ? 0 : -ENOMEM;
407 }
408 
409 static int add_event_tool(struct list_head *list, int *idx,
410 			  enum perf_tool_event tool_event)
411 {
412 	struct evsel *evsel;
413 	struct perf_event_attr attr = {
414 		.type = PERF_TYPE_SOFTWARE,
415 		.config = PERF_COUNT_SW_DUMMY,
416 	};
417 
418 	evsel = __add_event(list, idx, &attr, true, NULL, NULL, NULL, false,
419 			    "0");
420 	if (!evsel)
421 		return -ENOMEM;
422 	evsel->tool_event = tool_event;
423 	if (tool_event == PERF_TOOL_DURATION_TIME)
424 		evsel->unit = "ns";
425 	return 0;
426 }
427 
428 static int parse_aliases(char *str, const char *names[][EVSEL__MAX_ALIASES], int size)
429 {
430 	int i, j;
431 	int n, longest = -1;
432 
433 	for (i = 0; i < size; i++) {
434 		for (j = 0; j < EVSEL__MAX_ALIASES && names[i][j]; j++) {
435 			n = strlen(names[i][j]);
436 			if (n > longest && !strncasecmp(str, names[i][j], n))
437 				longest = n;
438 		}
439 		if (longest > 0)
440 			return i;
441 	}
442 
443 	return -1;
444 }
445 
446 typedef int config_term_func_t(struct perf_event_attr *attr,
447 			       struct parse_events_term *term,
448 			       struct parse_events_error *err);
449 static int config_term_common(struct perf_event_attr *attr,
450 			      struct parse_events_term *term,
451 			      struct parse_events_error *err);
452 static int config_attr(struct perf_event_attr *attr,
453 		       struct list_head *head,
454 		       struct parse_events_error *err,
455 		       config_term_func_t config_term);
456 
457 int parse_events_add_cache(struct list_head *list, int *idx,
458 			   char *type, char *op_result1, char *op_result2,
459 			   struct parse_events_error *err,
460 			   struct list_head *head_config,
461 			   struct parse_events_state *parse_state)
462 {
463 	struct perf_event_attr attr;
464 	LIST_HEAD(config_terms);
465 	char name[MAX_NAME_LEN], *config_name;
466 	int cache_type = -1, cache_op = -1, cache_result = -1;
467 	char *op_result[2] = { op_result1, op_result2 };
468 	int i, n, ret;
469 	bool hybrid;
470 
471 	/*
472 	 * No fallback - if we cannot get a clear cache type
473 	 * then bail out:
474 	 */
475 	cache_type = parse_aliases(type, evsel__hw_cache, PERF_COUNT_HW_CACHE_MAX);
476 	if (cache_type == -1)
477 		return -EINVAL;
478 
479 	config_name = get_config_name(head_config);
480 	n = snprintf(name, MAX_NAME_LEN, "%s", type);
481 
482 	for (i = 0; (i < 2) && (op_result[i]); i++) {
483 		char *str = op_result[i];
484 
485 		n += snprintf(name + n, MAX_NAME_LEN - n, "-%s", str);
486 
487 		if (cache_op == -1) {
488 			cache_op = parse_aliases(str, evsel__hw_cache_op,
489 						 PERF_COUNT_HW_CACHE_OP_MAX);
490 			if (cache_op >= 0) {
491 				if (!evsel__is_cache_op_valid(cache_type, cache_op))
492 					return -EINVAL;
493 				continue;
494 			}
495 		}
496 
497 		if (cache_result == -1) {
498 			cache_result = parse_aliases(str, evsel__hw_cache_result,
499 						     PERF_COUNT_HW_CACHE_RESULT_MAX);
500 			if (cache_result >= 0)
501 				continue;
502 		}
503 	}
504 
505 	/*
506 	 * Fall back to reads:
507 	 */
508 	if (cache_op == -1)
509 		cache_op = PERF_COUNT_HW_CACHE_OP_READ;
510 
511 	/*
512 	 * Fall back to accesses:
513 	 */
514 	if (cache_result == -1)
515 		cache_result = PERF_COUNT_HW_CACHE_RESULT_ACCESS;
516 
517 	memset(&attr, 0, sizeof(attr));
518 	attr.config = cache_type | (cache_op << 8) | (cache_result << 16);
519 	attr.type = PERF_TYPE_HW_CACHE;
520 
521 	if (head_config) {
522 		if (config_attr(&attr, head_config, err,
523 				config_term_common))
524 			return -EINVAL;
525 
526 		if (get_config_terms(head_config, &config_terms))
527 			return -ENOMEM;
528 	}
529 
530 	ret = parse_events__add_cache_hybrid(list, idx, &attr,
531 					     config_name ? : name, &config_terms,
532 					     &hybrid, parse_state);
533 	if (hybrid)
534 		return ret;
535 
536 	return add_event(list, idx, &attr, config_name ? : name, &config_terms);
537 }
538 
539 static void tracepoint_error(struct parse_events_error *e, int err,
540 			     const char *sys, const char *name)
541 {
542 	const char *str;
543 	char help[BUFSIZ];
544 
545 	if (!e)
546 		return;
547 
548 	/*
549 	 * We get error directly from syscall errno ( > 0),
550 	 * or from encoded pointer's error ( < 0).
551 	 */
552 	err = abs(err);
553 
554 	switch (err) {
555 	case EACCES:
556 		str = "can't access trace events";
557 		break;
558 	case ENOENT:
559 		str = "unknown tracepoint";
560 		break;
561 	default:
562 		str = "failed to add tracepoint";
563 		break;
564 	}
565 
566 	tracing_path__strerror_open_tp(err, help, sizeof(help), sys, name);
567 	parse_events__handle_error(e, 0, strdup(str), strdup(help));
568 }
569 
570 static int add_tracepoint(struct list_head *list, int *idx,
571 			  const char *sys_name, const char *evt_name,
572 			  struct parse_events_error *err,
573 			  struct list_head *head_config)
574 {
575 	struct evsel *evsel = evsel__newtp_idx(sys_name, evt_name, (*idx)++);
576 
577 	if (IS_ERR(evsel)) {
578 		tracepoint_error(err, PTR_ERR(evsel), sys_name, evt_name);
579 		return PTR_ERR(evsel);
580 	}
581 
582 	if (head_config) {
583 		LIST_HEAD(config_terms);
584 
585 		if (get_config_terms(head_config, &config_terms))
586 			return -ENOMEM;
587 		list_splice(&config_terms, &evsel->config_terms);
588 	}
589 
590 	list_add_tail(&evsel->core.node, list);
591 	return 0;
592 }
593 
594 static int add_tracepoint_multi_event(struct list_head *list, int *idx,
595 				      const char *sys_name, const char *evt_name,
596 				      struct parse_events_error *err,
597 				      struct list_head *head_config)
598 {
599 	char *evt_path;
600 	struct dirent *evt_ent;
601 	DIR *evt_dir;
602 	int ret = 0, found = 0;
603 
604 	evt_path = get_events_file(sys_name);
605 	if (!evt_path) {
606 		tracepoint_error(err, errno, sys_name, evt_name);
607 		return -1;
608 	}
609 	evt_dir = opendir(evt_path);
610 	if (!evt_dir) {
611 		put_events_file(evt_path);
612 		tracepoint_error(err, errno, sys_name, evt_name);
613 		return -1;
614 	}
615 
616 	while (!ret && (evt_ent = readdir(evt_dir))) {
617 		if (!strcmp(evt_ent->d_name, ".")
618 		    || !strcmp(evt_ent->d_name, "..")
619 		    || !strcmp(evt_ent->d_name, "enable")
620 		    || !strcmp(evt_ent->d_name, "filter"))
621 			continue;
622 
623 		if (!strglobmatch(evt_ent->d_name, evt_name))
624 			continue;
625 
626 		found++;
627 
628 		ret = add_tracepoint(list, idx, sys_name, evt_ent->d_name,
629 				     err, head_config);
630 	}
631 
632 	if (!found) {
633 		tracepoint_error(err, ENOENT, sys_name, evt_name);
634 		ret = -1;
635 	}
636 
637 	put_events_file(evt_path);
638 	closedir(evt_dir);
639 	return ret;
640 }
641 
642 static int add_tracepoint_event(struct list_head *list, int *idx,
643 				const char *sys_name, const char *evt_name,
644 				struct parse_events_error *err,
645 				struct list_head *head_config)
646 {
647 	return strpbrk(evt_name, "*?") ?
648 	       add_tracepoint_multi_event(list, idx, sys_name, evt_name,
649 					  err, head_config) :
650 	       add_tracepoint(list, idx, sys_name, evt_name,
651 			      err, head_config);
652 }
653 
654 static int add_tracepoint_multi_sys(struct list_head *list, int *idx,
655 				    const char *sys_name, const char *evt_name,
656 				    struct parse_events_error *err,
657 				    struct list_head *head_config)
658 {
659 	struct dirent *events_ent;
660 	DIR *events_dir;
661 	int ret = 0;
662 
663 	events_dir = tracing_events__opendir();
664 	if (!events_dir) {
665 		tracepoint_error(err, errno, sys_name, evt_name);
666 		return -1;
667 	}
668 
669 	while (!ret && (events_ent = readdir(events_dir))) {
670 		if (!strcmp(events_ent->d_name, ".")
671 		    || !strcmp(events_ent->d_name, "..")
672 		    || !strcmp(events_ent->d_name, "enable")
673 		    || !strcmp(events_ent->d_name, "header_event")
674 		    || !strcmp(events_ent->d_name, "header_page"))
675 			continue;
676 
677 		if (!strglobmatch(events_ent->d_name, sys_name))
678 			continue;
679 
680 		ret = add_tracepoint_event(list, idx, events_ent->d_name,
681 					   evt_name, err, head_config);
682 	}
683 
684 	closedir(events_dir);
685 	return ret;
686 }
687 
688 #ifdef HAVE_LIBBPF_SUPPORT
689 struct __add_bpf_event_param {
690 	struct parse_events_state *parse_state;
691 	struct list_head *list;
692 	struct list_head *head_config;
693 };
694 
695 static int add_bpf_event(const char *group, const char *event, int fd, struct bpf_object *obj,
696 			 void *_param)
697 {
698 	LIST_HEAD(new_evsels);
699 	struct __add_bpf_event_param *param = _param;
700 	struct parse_events_state *parse_state = param->parse_state;
701 	struct list_head *list = param->list;
702 	struct evsel *pos;
703 	int err;
704 	/*
705 	 * Check if we should add the event, i.e. if it is a TP but starts with a '!',
706 	 * then don't add the tracepoint, this will be used for something else, like
707 	 * adding to a BPF_MAP_TYPE_PROG_ARRAY.
708 	 *
709 	 * See tools/perf/examples/bpf/augmented_raw_syscalls.c
710 	 */
711 	if (group[0] == '!')
712 		return 0;
713 
714 	pr_debug("add bpf event %s:%s and attach bpf program %d\n",
715 		 group, event, fd);
716 
717 	err = parse_events_add_tracepoint(&new_evsels, &parse_state->idx, group,
718 					  event, parse_state->error,
719 					  param->head_config);
720 	if (err) {
721 		struct evsel *evsel, *tmp;
722 
723 		pr_debug("Failed to add BPF event %s:%s\n",
724 			 group, event);
725 		list_for_each_entry_safe(evsel, tmp, &new_evsels, core.node) {
726 			list_del_init(&evsel->core.node);
727 			evsel__delete(evsel);
728 		}
729 		return err;
730 	}
731 	pr_debug("adding %s:%s\n", group, event);
732 
733 	list_for_each_entry(pos, &new_evsels, core.node) {
734 		pr_debug("adding %s:%s to %p\n",
735 			 group, event, pos);
736 		pos->bpf_fd = fd;
737 		pos->bpf_obj = obj;
738 	}
739 	list_splice(&new_evsels, list);
740 	return 0;
741 }
742 
743 int parse_events_load_bpf_obj(struct parse_events_state *parse_state,
744 			      struct list_head *list,
745 			      struct bpf_object *obj,
746 			      struct list_head *head_config)
747 {
748 	int err;
749 	char errbuf[BUFSIZ];
750 	struct __add_bpf_event_param param = {parse_state, list, head_config};
751 	static bool registered_unprobe_atexit = false;
752 
753 	if (IS_ERR(obj) || !obj) {
754 		snprintf(errbuf, sizeof(errbuf),
755 			 "Internal error: load bpf obj with NULL");
756 		err = -EINVAL;
757 		goto errout;
758 	}
759 
760 	/*
761 	 * Register atexit handler before calling bpf__probe() so
762 	 * bpf__probe() don't need to unprobe probe points its already
763 	 * created when failure.
764 	 */
765 	if (!registered_unprobe_atexit) {
766 		atexit(bpf__clear);
767 		registered_unprobe_atexit = true;
768 	}
769 
770 	err = bpf__probe(obj);
771 	if (err) {
772 		bpf__strerror_probe(obj, err, errbuf, sizeof(errbuf));
773 		goto errout;
774 	}
775 
776 	err = bpf__load(obj);
777 	if (err) {
778 		bpf__strerror_load(obj, err, errbuf, sizeof(errbuf));
779 		goto errout;
780 	}
781 
782 	err = bpf__foreach_event(obj, add_bpf_event, &param);
783 	if (err) {
784 		snprintf(errbuf, sizeof(errbuf),
785 			 "Attach events in BPF object failed");
786 		goto errout;
787 	}
788 
789 	return 0;
790 errout:
791 	parse_events__handle_error(parse_state->error, 0,
792 				strdup(errbuf), strdup("(add -v to see detail)"));
793 	return err;
794 }
795 
796 static int
797 parse_events_config_bpf(struct parse_events_state *parse_state,
798 			struct bpf_object *obj,
799 			struct list_head *head_config)
800 {
801 	struct parse_events_term *term;
802 	int error_pos;
803 
804 	if (!head_config || list_empty(head_config))
805 		return 0;
806 
807 	list_for_each_entry(term, head_config, list) {
808 		int err;
809 
810 		if (term->type_term != PARSE_EVENTS__TERM_TYPE_USER) {
811 			parse_events__handle_error(parse_state->error, term->err_term,
812 						strdup("Invalid config term for BPF object"),
813 						NULL);
814 			return -EINVAL;
815 		}
816 
817 		err = bpf__config_obj(obj, term, parse_state->evlist, &error_pos);
818 		if (err) {
819 			char errbuf[BUFSIZ];
820 			int idx;
821 
822 			bpf__strerror_config_obj(obj, term, parse_state->evlist,
823 						 &error_pos, err, errbuf,
824 						 sizeof(errbuf));
825 
826 			if (err == -BPF_LOADER_ERRNO__OBJCONF_MAP_VALUE)
827 				idx = term->err_val;
828 			else
829 				idx = term->err_term + error_pos;
830 
831 			parse_events__handle_error(parse_state->error, idx,
832 						strdup(errbuf),
833 						strdup(
834 "Hint:\tValid config terms:\n"
835 "     \tmap:[<arraymap>].value<indices>=[value]\n"
836 "     \tmap:[<eventmap>].event<indices>=[event]\n"
837 "\n"
838 "     \twhere <indices> is something like [0,3...5] or [all]\n"
839 "     \t(add -v to see detail)"));
840 			return err;
841 		}
842 	}
843 	return 0;
844 }
845 
846 /*
847  * Split config terms:
848  * perf record -e bpf.c/call-graph=fp,map:array.value[0]=1/ ...
849  *  'call-graph=fp' is 'evt config', should be applied to each
850  *  events in bpf.c.
851  * 'map:array.value[0]=1' is 'obj config', should be processed
852  * with parse_events_config_bpf.
853  *
854  * Move object config terms from the first list to obj_head_config.
855  */
856 static void
857 split_bpf_config_terms(struct list_head *evt_head_config,
858 		       struct list_head *obj_head_config)
859 {
860 	struct parse_events_term *term, *temp;
861 
862 	/*
863 	 * Currently, all possible user config term
864 	 * belong to bpf object. parse_events__is_hardcoded_term()
865 	 * happens to be a good flag.
866 	 *
867 	 * See parse_events_config_bpf() and
868 	 * config_term_tracepoint().
869 	 */
870 	list_for_each_entry_safe(term, temp, evt_head_config, list)
871 		if (!parse_events__is_hardcoded_term(term))
872 			list_move_tail(&term->list, obj_head_config);
873 }
874 
875 int parse_events_load_bpf(struct parse_events_state *parse_state,
876 			  struct list_head *list,
877 			  char *bpf_file_name,
878 			  bool source,
879 			  struct list_head *head_config)
880 {
881 	int err;
882 	struct bpf_object *obj;
883 	LIST_HEAD(obj_head_config);
884 
885 	if (head_config)
886 		split_bpf_config_terms(head_config, &obj_head_config);
887 
888 	obj = bpf__prepare_load(bpf_file_name, source);
889 	if (IS_ERR(obj)) {
890 		char errbuf[BUFSIZ];
891 
892 		err = PTR_ERR(obj);
893 
894 		if (err == -ENOTSUP)
895 			snprintf(errbuf, sizeof(errbuf),
896 				 "BPF support is not compiled");
897 		else
898 			bpf__strerror_prepare_load(bpf_file_name,
899 						   source,
900 						   -err, errbuf,
901 						   sizeof(errbuf));
902 
903 		parse_events__handle_error(parse_state->error, 0,
904 					strdup(errbuf), strdup("(add -v to see detail)"));
905 		return err;
906 	}
907 
908 	err = parse_events_load_bpf_obj(parse_state, list, obj, head_config);
909 	if (err)
910 		return err;
911 	err = parse_events_config_bpf(parse_state, obj, &obj_head_config);
912 
913 	/*
914 	 * Caller doesn't know anything about obj_head_config,
915 	 * so combine them together again before returning.
916 	 */
917 	if (head_config)
918 		list_splice_tail(&obj_head_config, head_config);
919 	return err;
920 }
921 #else // HAVE_LIBBPF_SUPPORT
922 int parse_events_load_bpf_obj(struct parse_events_state *parse_state,
923 			      struct list_head *list __maybe_unused,
924 			      struct bpf_object *obj __maybe_unused,
925 			      struct list_head *head_config __maybe_unused)
926 {
927 	parse_events__handle_error(parse_state->error, 0,
928 				   strdup("BPF support is not compiled"),
929 				   strdup("Make sure libbpf-devel is available at build time."));
930 	return -ENOTSUP;
931 }
932 
933 int parse_events_load_bpf(struct parse_events_state *parse_state,
934 			  struct list_head *list __maybe_unused,
935 			  char *bpf_file_name __maybe_unused,
936 			  bool source __maybe_unused,
937 			  struct list_head *head_config __maybe_unused)
938 {
939 	parse_events__handle_error(parse_state->error, 0,
940 				   strdup("BPF support is not compiled"),
941 				   strdup("Make sure libbpf-devel is available at build time."));
942 	return -ENOTSUP;
943 }
944 #endif // HAVE_LIBBPF_SUPPORT
945 
946 static int
947 parse_breakpoint_type(const char *type, struct perf_event_attr *attr)
948 {
949 	int i;
950 
951 	for (i = 0; i < 3; i++) {
952 		if (!type || !type[i])
953 			break;
954 
955 #define CHECK_SET_TYPE(bit)		\
956 do {					\
957 	if (attr->bp_type & bit)	\
958 		return -EINVAL;		\
959 	else				\
960 		attr->bp_type |= bit;	\
961 } while (0)
962 
963 		switch (type[i]) {
964 		case 'r':
965 			CHECK_SET_TYPE(HW_BREAKPOINT_R);
966 			break;
967 		case 'w':
968 			CHECK_SET_TYPE(HW_BREAKPOINT_W);
969 			break;
970 		case 'x':
971 			CHECK_SET_TYPE(HW_BREAKPOINT_X);
972 			break;
973 		default:
974 			return -EINVAL;
975 		}
976 	}
977 
978 #undef CHECK_SET_TYPE
979 
980 	if (!attr->bp_type) /* Default */
981 		attr->bp_type = HW_BREAKPOINT_R | HW_BREAKPOINT_W;
982 
983 	return 0;
984 }
985 
986 int parse_events_add_breakpoint(struct list_head *list, int *idx,
987 				u64 addr, char *type, u64 len)
988 {
989 	struct perf_event_attr attr;
990 
991 	memset(&attr, 0, sizeof(attr));
992 	attr.bp_addr = addr;
993 
994 	if (parse_breakpoint_type(type, &attr))
995 		return -EINVAL;
996 
997 	/* Provide some defaults if len is not specified */
998 	if (!len) {
999 		if (attr.bp_type == HW_BREAKPOINT_X)
1000 			len = sizeof(long);
1001 		else
1002 			len = HW_BREAKPOINT_LEN_4;
1003 	}
1004 
1005 	attr.bp_len = len;
1006 
1007 	attr.type = PERF_TYPE_BREAKPOINT;
1008 	attr.sample_period = 1;
1009 
1010 	return add_event(list, idx, &attr, NULL, NULL);
1011 }
1012 
1013 static int check_type_val(struct parse_events_term *term,
1014 			  struct parse_events_error *err,
1015 			  int type)
1016 {
1017 	if (type == term->type_val)
1018 		return 0;
1019 
1020 	if (err) {
1021 		parse_events__handle_error(err, term->err_val,
1022 					type == PARSE_EVENTS__TERM_TYPE_NUM
1023 					? strdup("expected numeric value")
1024 					: strdup("expected string value"),
1025 					NULL);
1026 	}
1027 	return -EINVAL;
1028 }
1029 
1030 /*
1031  * Update according to parse-events.l
1032  */
1033 static const char *config_term_names[__PARSE_EVENTS__TERM_TYPE_NR] = {
1034 	[PARSE_EVENTS__TERM_TYPE_USER]			= "<sysfs term>",
1035 	[PARSE_EVENTS__TERM_TYPE_CONFIG]		= "config",
1036 	[PARSE_EVENTS__TERM_TYPE_CONFIG1]		= "config1",
1037 	[PARSE_EVENTS__TERM_TYPE_CONFIG2]		= "config2",
1038 	[PARSE_EVENTS__TERM_TYPE_NAME]			= "name",
1039 	[PARSE_EVENTS__TERM_TYPE_SAMPLE_PERIOD]		= "period",
1040 	[PARSE_EVENTS__TERM_TYPE_SAMPLE_FREQ]		= "freq",
1041 	[PARSE_EVENTS__TERM_TYPE_BRANCH_SAMPLE_TYPE]	= "branch_type",
1042 	[PARSE_EVENTS__TERM_TYPE_TIME]			= "time",
1043 	[PARSE_EVENTS__TERM_TYPE_CALLGRAPH]		= "call-graph",
1044 	[PARSE_EVENTS__TERM_TYPE_STACKSIZE]		= "stack-size",
1045 	[PARSE_EVENTS__TERM_TYPE_NOINHERIT]		= "no-inherit",
1046 	[PARSE_EVENTS__TERM_TYPE_INHERIT]		= "inherit",
1047 	[PARSE_EVENTS__TERM_TYPE_MAX_STACK]		= "max-stack",
1048 	[PARSE_EVENTS__TERM_TYPE_MAX_EVENTS]		= "nr",
1049 	[PARSE_EVENTS__TERM_TYPE_OVERWRITE]		= "overwrite",
1050 	[PARSE_EVENTS__TERM_TYPE_NOOVERWRITE]		= "no-overwrite",
1051 	[PARSE_EVENTS__TERM_TYPE_DRV_CFG]		= "driver-config",
1052 	[PARSE_EVENTS__TERM_TYPE_PERCORE]		= "percore",
1053 	[PARSE_EVENTS__TERM_TYPE_AUX_OUTPUT]		= "aux-output",
1054 	[PARSE_EVENTS__TERM_TYPE_AUX_SAMPLE_SIZE]	= "aux-sample-size",
1055 };
1056 
1057 static bool config_term_shrinked;
1058 
1059 static bool
1060 config_term_avail(int term_type, struct parse_events_error *err)
1061 {
1062 	char *err_str;
1063 
1064 	if (term_type < 0 || term_type >= __PARSE_EVENTS__TERM_TYPE_NR) {
1065 		parse_events__handle_error(err, -1,
1066 					strdup("Invalid term_type"), NULL);
1067 		return false;
1068 	}
1069 	if (!config_term_shrinked)
1070 		return true;
1071 
1072 	switch (term_type) {
1073 	case PARSE_EVENTS__TERM_TYPE_CONFIG:
1074 	case PARSE_EVENTS__TERM_TYPE_CONFIG1:
1075 	case PARSE_EVENTS__TERM_TYPE_CONFIG2:
1076 	case PARSE_EVENTS__TERM_TYPE_NAME:
1077 	case PARSE_EVENTS__TERM_TYPE_SAMPLE_PERIOD:
1078 	case PARSE_EVENTS__TERM_TYPE_PERCORE:
1079 		return true;
1080 	default:
1081 		if (!err)
1082 			return false;
1083 
1084 		/* term_type is validated so indexing is safe */
1085 		if (asprintf(&err_str, "'%s' is not usable in 'perf stat'",
1086 				config_term_names[term_type]) >= 0)
1087 			parse_events__handle_error(err, -1, err_str, NULL);
1088 		return false;
1089 	}
1090 }
1091 
1092 void parse_events__shrink_config_terms(void)
1093 {
1094 	config_term_shrinked = true;
1095 }
1096 
1097 static int config_term_common(struct perf_event_attr *attr,
1098 			      struct parse_events_term *term,
1099 			      struct parse_events_error *err)
1100 {
1101 #define CHECK_TYPE_VAL(type)						   \
1102 do {									   \
1103 	if (check_type_val(term, err, PARSE_EVENTS__TERM_TYPE_ ## type)) \
1104 		return -EINVAL;						   \
1105 } while (0)
1106 
1107 	switch (term->type_term) {
1108 	case PARSE_EVENTS__TERM_TYPE_CONFIG:
1109 		CHECK_TYPE_VAL(NUM);
1110 		attr->config = term->val.num;
1111 		break;
1112 	case PARSE_EVENTS__TERM_TYPE_CONFIG1:
1113 		CHECK_TYPE_VAL(NUM);
1114 		attr->config1 = term->val.num;
1115 		break;
1116 	case PARSE_EVENTS__TERM_TYPE_CONFIG2:
1117 		CHECK_TYPE_VAL(NUM);
1118 		attr->config2 = term->val.num;
1119 		break;
1120 	case PARSE_EVENTS__TERM_TYPE_SAMPLE_PERIOD:
1121 		CHECK_TYPE_VAL(NUM);
1122 		break;
1123 	case PARSE_EVENTS__TERM_TYPE_SAMPLE_FREQ:
1124 		CHECK_TYPE_VAL(NUM);
1125 		break;
1126 	case PARSE_EVENTS__TERM_TYPE_BRANCH_SAMPLE_TYPE:
1127 		CHECK_TYPE_VAL(STR);
1128 		if (strcmp(term->val.str, "no") &&
1129 		    parse_branch_str(term->val.str,
1130 				    &attr->branch_sample_type)) {
1131 			parse_events__handle_error(err, term->err_val,
1132 					strdup("invalid branch sample type"),
1133 					NULL);
1134 			return -EINVAL;
1135 		}
1136 		break;
1137 	case PARSE_EVENTS__TERM_TYPE_TIME:
1138 		CHECK_TYPE_VAL(NUM);
1139 		if (term->val.num > 1) {
1140 			parse_events__handle_error(err, term->err_val,
1141 						strdup("expected 0 or 1"),
1142 						NULL);
1143 			return -EINVAL;
1144 		}
1145 		break;
1146 	case PARSE_EVENTS__TERM_TYPE_CALLGRAPH:
1147 		CHECK_TYPE_VAL(STR);
1148 		break;
1149 	case PARSE_EVENTS__TERM_TYPE_STACKSIZE:
1150 		CHECK_TYPE_VAL(NUM);
1151 		break;
1152 	case PARSE_EVENTS__TERM_TYPE_INHERIT:
1153 		CHECK_TYPE_VAL(NUM);
1154 		break;
1155 	case PARSE_EVENTS__TERM_TYPE_NOINHERIT:
1156 		CHECK_TYPE_VAL(NUM);
1157 		break;
1158 	case PARSE_EVENTS__TERM_TYPE_OVERWRITE:
1159 		CHECK_TYPE_VAL(NUM);
1160 		break;
1161 	case PARSE_EVENTS__TERM_TYPE_NOOVERWRITE:
1162 		CHECK_TYPE_VAL(NUM);
1163 		break;
1164 	case PARSE_EVENTS__TERM_TYPE_NAME:
1165 		CHECK_TYPE_VAL(STR);
1166 		break;
1167 	case PARSE_EVENTS__TERM_TYPE_MAX_STACK:
1168 		CHECK_TYPE_VAL(NUM);
1169 		break;
1170 	case PARSE_EVENTS__TERM_TYPE_MAX_EVENTS:
1171 		CHECK_TYPE_VAL(NUM);
1172 		break;
1173 	case PARSE_EVENTS__TERM_TYPE_PERCORE:
1174 		CHECK_TYPE_VAL(NUM);
1175 		if ((unsigned int)term->val.num > 1) {
1176 			parse_events__handle_error(err, term->err_val,
1177 						strdup("expected 0 or 1"),
1178 						NULL);
1179 			return -EINVAL;
1180 		}
1181 		break;
1182 	case PARSE_EVENTS__TERM_TYPE_AUX_OUTPUT:
1183 		CHECK_TYPE_VAL(NUM);
1184 		break;
1185 	case PARSE_EVENTS__TERM_TYPE_AUX_SAMPLE_SIZE:
1186 		CHECK_TYPE_VAL(NUM);
1187 		if (term->val.num > UINT_MAX) {
1188 			parse_events__handle_error(err, term->err_val,
1189 						strdup("too big"),
1190 						NULL);
1191 			return -EINVAL;
1192 		}
1193 		break;
1194 	default:
1195 		parse_events__handle_error(err, term->err_term,
1196 				strdup("unknown term"),
1197 				parse_events_formats_error_string(NULL));
1198 		return -EINVAL;
1199 	}
1200 
1201 	/*
1202 	 * Check term availability after basic checking so
1203 	 * PARSE_EVENTS__TERM_TYPE_USER can be found and filtered.
1204 	 *
1205 	 * If check availability at the entry of this function,
1206 	 * user will see "'<sysfs term>' is not usable in 'perf stat'"
1207 	 * if an invalid config term is provided for legacy events
1208 	 * (for example, instructions/badterm/...), which is confusing.
1209 	 */
1210 	if (!config_term_avail(term->type_term, err))
1211 		return -EINVAL;
1212 	return 0;
1213 #undef CHECK_TYPE_VAL
1214 }
1215 
1216 static int config_term_pmu(struct perf_event_attr *attr,
1217 			   struct parse_events_term *term,
1218 			   struct parse_events_error *err)
1219 {
1220 	if (term->type_term == PARSE_EVENTS__TERM_TYPE_USER ||
1221 	    term->type_term == PARSE_EVENTS__TERM_TYPE_DRV_CFG)
1222 		/*
1223 		 * Always succeed for sysfs terms, as we dont know
1224 		 * at this point what type they need to have.
1225 		 */
1226 		return 0;
1227 	else
1228 		return config_term_common(attr, term, err);
1229 }
1230 
1231 static int config_term_tracepoint(struct perf_event_attr *attr,
1232 				  struct parse_events_term *term,
1233 				  struct parse_events_error *err)
1234 {
1235 	switch (term->type_term) {
1236 	case PARSE_EVENTS__TERM_TYPE_CALLGRAPH:
1237 	case PARSE_EVENTS__TERM_TYPE_STACKSIZE:
1238 	case PARSE_EVENTS__TERM_TYPE_INHERIT:
1239 	case PARSE_EVENTS__TERM_TYPE_NOINHERIT:
1240 	case PARSE_EVENTS__TERM_TYPE_MAX_STACK:
1241 	case PARSE_EVENTS__TERM_TYPE_MAX_EVENTS:
1242 	case PARSE_EVENTS__TERM_TYPE_OVERWRITE:
1243 	case PARSE_EVENTS__TERM_TYPE_NOOVERWRITE:
1244 	case PARSE_EVENTS__TERM_TYPE_AUX_OUTPUT:
1245 	case PARSE_EVENTS__TERM_TYPE_AUX_SAMPLE_SIZE:
1246 		return config_term_common(attr, term, err);
1247 	default:
1248 		if (err) {
1249 			parse_events__handle_error(err, term->err_term,
1250 				strdup("unknown term"),
1251 				strdup("valid terms: call-graph,stack-size\n"));
1252 		}
1253 		return -EINVAL;
1254 	}
1255 
1256 	return 0;
1257 }
1258 
1259 static int config_attr(struct perf_event_attr *attr,
1260 		       struct list_head *head,
1261 		       struct parse_events_error *err,
1262 		       config_term_func_t config_term)
1263 {
1264 	struct parse_events_term *term;
1265 
1266 	list_for_each_entry(term, head, list)
1267 		if (config_term(attr, term, err))
1268 			return -EINVAL;
1269 
1270 	return 0;
1271 }
1272 
1273 static int get_config_terms(struct list_head *head_config,
1274 			    struct list_head *head_terms __maybe_unused)
1275 {
1276 #define ADD_CONFIG_TERM(__type, __weak)				\
1277 	struct evsel_config_term *__t;			\
1278 								\
1279 	__t = zalloc(sizeof(*__t));				\
1280 	if (!__t)						\
1281 		return -ENOMEM;					\
1282 								\
1283 	INIT_LIST_HEAD(&__t->list);				\
1284 	__t->type       = EVSEL__CONFIG_TERM_ ## __type;	\
1285 	__t->weak	= __weak;				\
1286 	list_add_tail(&__t->list, head_terms)
1287 
1288 #define ADD_CONFIG_TERM_VAL(__type, __name, __val, __weak)	\
1289 do {								\
1290 	ADD_CONFIG_TERM(__type, __weak);			\
1291 	__t->val.__name = __val;				\
1292 } while (0)
1293 
1294 #define ADD_CONFIG_TERM_STR(__type, __val, __weak)		\
1295 do {								\
1296 	ADD_CONFIG_TERM(__type, __weak);			\
1297 	__t->val.str = strdup(__val);				\
1298 	if (!__t->val.str) {					\
1299 		zfree(&__t);					\
1300 		return -ENOMEM;					\
1301 	}							\
1302 	__t->free_str = true;					\
1303 } while (0)
1304 
1305 	struct parse_events_term *term;
1306 
1307 	list_for_each_entry(term, head_config, list) {
1308 		switch (term->type_term) {
1309 		case PARSE_EVENTS__TERM_TYPE_SAMPLE_PERIOD:
1310 			ADD_CONFIG_TERM_VAL(PERIOD, period, term->val.num, term->weak);
1311 			break;
1312 		case PARSE_EVENTS__TERM_TYPE_SAMPLE_FREQ:
1313 			ADD_CONFIG_TERM_VAL(FREQ, freq, term->val.num, term->weak);
1314 			break;
1315 		case PARSE_EVENTS__TERM_TYPE_TIME:
1316 			ADD_CONFIG_TERM_VAL(TIME, time, term->val.num, term->weak);
1317 			break;
1318 		case PARSE_EVENTS__TERM_TYPE_CALLGRAPH:
1319 			ADD_CONFIG_TERM_STR(CALLGRAPH, term->val.str, term->weak);
1320 			break;
1321 		case PARSE_EVENTS__TERM_TYPE_BRANCH_SAMPLE_TYPE:
1322 			ADD_CONFIG_TERM_STR(BRANCH, term->val.str, term->weak);
1323 			break;
1324 		case PARSE_EVENTS__TERM_TYPE_STACKSIZE:
1325 			ADD_CONFIG_TERM_VAL(STACK_USER, stack_user,
1326 					    term->val.num, term->weak);
1327 			break;
1328 		case PARSE_EVENTS__TERM_TYPE_INHERIT:
1329 			ADD_CONFIG_TERM_VAL(INHERIT, inherit,
1330 					    term->val.num ? 1 : 0, term->weak);
1331 			break;
1332 		case PARSE_EVENTS__TERM_TYPE_NOINHERIT:
1333 			ADD_CONFIG_TERM_VAL(INHERIT, inherit,
1334 					    term->val.num ? 0 : 1, term->weak);
1335 			break;
1336 		case PARSE_EVENTS__TERM_TYPE_MAX_STACK:
1337 			ADD_CONFIG_TERM_VAL(MAX_STACK, max_stack,
1338 					    term->val.num, term->weak);
1339 			break;
1340 		case PARSE_EVENTS__TERM_TYPE_MAX_EVENTS:
1341 			ADD_CONFIG_TERM_VAL(MAX_EVENTS, max_events,
1342 					    term->val.num, term->weak);
1343 			break;
1344 		case PARSE_EVENTS__TERM_TYPE_OVERWRITE:
1345 			ADD_CONFIG_TERM_VAL(OVERWRITE, overwrite,
1346 					    term->val.num ? 1 : 0, term->weak);
1347 			break;
1348 		case PARSE_EVENTS__TERM_TYPE_NOOVERWRITE:
1349 			ADD_CONFIG_TERM_VAL(OVERWRITE, overwrite,
1350 					    term->val.num ? 0 : 1, term->weak);
1351 			break;
1352 		case PARSE_EVENTS__TERM_TYPE_DRV_CFG:
1353 			ADD_CONFIG_TERM_STR(DRV_CFG, term->val.str, term->weak);
1354 			break;
1355 		case PARSE_EVENTS__TERM_TYPE_PERCORE:
1356 			ADD_CONFIG_TERM_VAL(PERCORE, percore,
1357 					    term->val.num ? true : false, term->weak);
1358 			break;
1359 		case PARSE_EVENTS__TERM_TYPE_AUX_OUTPUT:
1360 			ADD_CONFIG_TERM_VAL(AUX_OUTPUT, aux_output,
1361 					    term->val.num ? 1 : 0, term->weak);
1362 			break;
1363 		case PARSE_EVENTS__TERM_TYPE_AUX_SAMPLE_SIZE:
1364 			ADD_CONFIG_TERM_VAL(AUX_SAMPLE_SIZE, aux_sample_size,
1365 					    term->val.num, term->weak);
1366 			break;
1367 		default:
1368 			break;
1369 		}
1370 	}
1371 	return 0;
1372 }
1373 
1374 /*
1375  * Add EVSEL__CONFIG_TERM_CFG_CHG where cfg_chg will have a bit set for
1376  * each bit of attr->config that the user has changed.
1377  */
1378 static int get_config_chgs(struct perf_pmu *pmu, struct list_head *head_config,
1379 			   struct list_head *head_terms)
1380 {
1381 	struct parse_events_term *term;
1382 	u64 bits = 0;
1383 	int type;
1384 
1385 	list_for_each_entry(term, head_config, list) {
1386 		switch (term->type_term) {
1387 		case PARSE_EVENTS__TERM_TYPE_USER:
1388 			type = perf_pmu__format_type(&pmu->format, term->config);
1389 			if (type != PERF_PMU_FORMAT_VALUE_CONFIG)
1390 				continue;
1391 			bits |= perf_pmu__format_bits(&pmu->format, term->config);
1392 			break;
1393 		case PARSE_EVENTS__TERM_TYPE_CONFIG:
1394 			bits = ~(u64)0;
1395 			break;
1396 		default:
1397 			break;
1398 		}
1399 	}
1400 
1401 	if (bits)
1402 		ADD_CONFIG_TERM_VAL(CFG_CHG, cfg_chg, bits, false);
1403 
1404 #undef ADD_CONFIG_TERM
1405 	return 0;
1406 }
1407 
1408 int parse_events_add_tracepoint(struct list_head *list, int *idx,
1409 				const char *sys, const char *event,
1410 				struct parse_events_error *err,
1411 				struct list_head *head_config)
1412 {
1413 	if (head_config) {
1414 		struct perf_event_attr attr;
1415 
1416 		if (config_attr(&attr, head_config, err,
1417 				config_term_tracepoint))
1418 			return -EINVAL;
1419 	}
1420 
1421 	if (strpbrk(sys, "*?"))
1422 		return add_tracepoint_multi_sys(list, idx, sys, event,
1423 						err, head_config);
1424 	else
1425 		return add_tracepoint_event(list, idx, sys, event,
1426 					    err, head_config);
1427 }
1428 
1429 int parse_events_add_numeric(struct parse_events_state *parse_state,
1430 			     struct list_head *list,
1431 			     u32 type, u64 config,
1432 			     struct list_head *head_config)
1433 {
1434 	struct perf_event_attr attr;
1435 	LIST_HEAD(config_terms);
1436 	bool hybrid;
1437 	int ret;
1438 
1439 	memset(&attr, 0, sizeof(attr));
1440 	attr.type = type;
1441 	attr.config = config;
1442 
1443 	if (head_config) {
1444 		if (config_attr(&attr, head_config, parse_state->error,
1445 				config_term_common))
1446 			return -EINVAL;
1447 
1448 		if (get_config_terms(head_config, &config_terms))
1449 			return -ENOMEM;
1450 	}
1451 
1452 	ret = parse_events__add_numeric_hybrid(parse_state, list, &attr,
1453 					       get_config_name(head_config),
1454 					       &config_terms, &hybrid);
1455 	if (hybrid)
1456 		return ret;
1457 
1458 	return add_event(list, &parse_state->idx, &attr,
1459 			 get_config_name(head_config), &config_terms);
1460 }
1461 
1462 int parse_events_add_tool(struct parse_events_state *parse_state,
1463 			  struct list_head *list,
1464 			  enum perf_tool_event tool_event)
1465 {
1466 	return add_event_tool(list, &parse_state->idx, tool_event);
1467 }
1468 
1469 static bool config_term_percore(struct list_head *config_terms)
1470 {
1471 	struct evsel_config_term *term;
1472 
1473 	list_for_each_entry(term, config_terms, list) {
1474 		if (term->type == EVSEL__CONFIG_TERM_PERCORE)
1475 			return term->val.percore;
1476 	}
1477 
1478 	return false;
1479 }
1480 
1481 static int parse_events__inside_hybrid_pmu(struct parse_events_state *parse_state,
1482 					   struct list_head *list, char *name,
1483 					   struct list_head *head_config)
1484 {
1485 	struct parse_events_term *term;
1486 	int ret = -1;
1487 
1488 	if (parse_state->fake_pmu || !head_config || list_empty(head_config) ||
1489 	    !perf_pmu__is_hybrid(name)) {
1490 		return -1;
1491 	}
1492 
1493 	/*
1494 	 * More than one term in list.
1495 	 */
1496 	if (head_config->next && head_config->next->next != head_config)
1497 		return -1;
1498 
1499 	term = list_first_entry(head_config, struct parse_events_term, list);
1500 	if (term && term->config && strcmp(term->config, "event")) {
1501 		ret = parse_events__with_hybrid_pmu(parse_state, term->config,
1502 						    name, list);
1503 	}
1504 
1505 	return ret;
1506 }
1507 
1508 int parse_events_add_pmu(struct parse_events_state *parse_state,
1509 			 struct list_head *list, char *name,
1510 			 struct list_head *head_config,
1511 			 bool auto_merge_stats,
1512 			 bool use_alias)
1513 {
1514 	struct perf_event_attr attr;
1515 	struct perf_pmu_info info;
1516 	struct perf_pmu *pmu;
1517 	struct evsel *evsel;
1518 	struct parse_events_error *err = parse_state->error;
1519 	bool use_uncore_alias;
1520 	LIST_HEAD(config_terms);
1521 
1522 	if (verbose > 1) {
1523 		fprintf(stderr, "Attempting to add event pmu '%s' with '",
1524 			name);
1525 		if (head_config) {
1526 			struct parse_events_term *term;
1527 
1528 			list_for_each_entry(term, head_config, list) {
1529 				fprintf(stderr, "%s,", term->config);
1530 			}
1531 		}
1532 		fprintf(stderr, "' that may result in non-fatal errors\n");
1533 	}
1534 
1535 	pmu = parse_state->fake_pmu ?: perf_pmu__find(name);
1536 	if (!pmu) {
1537 		char *err_str;
1538 
1539 		if (asprintf(&err_str,
1540 				"Cannot find PMU `%s'. Missing kernel support?",
1541 				name) >= 0)
1542 			parse_events__handle_error(err, 0, err_str, NULL);
1543 		return -EINVAL;
1544 	}
1545 
1546 	if (pmu->default_config) {
1547 		memcpy(&attr, pmu->default_config,
1548 		       sizeof(struct perf_event_attr));
1549 	} else {
1550 		memset(&attr, 0, sizeof(attr));
1551 	}
1552 
1553 	use_uncore_alias = (pmu->is_uncore && use_alias);
1554 
1555 	if (!head_config) {
1556 		attr.type = pmu->type;
1557 		evsel = __add_event(list, &parse_state->idx, &attr, true, NULL,
1558 				    pmu, NULL, auto_merge_stats, NULL);
1559 		if (evsel) {
1560 			evsel->pmu_name = name ? strdup(name) : NULL;
1561 			evsel->use_uncore_alias = use_uncore_alias;
1562 			return 0;
1563 		} else {
1564 			return -ENOMEM;
1565 		}
1566 	}
1567 
1568 	if (!parse_state->fake_pmu && perf_pmu__check_alias(pmu, head_config, &info))
1569 		return -EINVAL;
1570 
1571 	if (verbose > 1) {
1572 		fprintf(stderr, "After aliases, add event pmu '%s' with '",
1573 			name);
1574 		if (head_config) {
1575 			struct parse_events_term *term;
1576 
1577 			list_for_each_entry(term, head_config, list) {
1578 				fprintf(stderr, "%s,", term->config);
1579 			}
1580 		}
1581 		fprintf(stderr, "' that may result in non-fatal errors\n");
1582 	}
1583 
1584 	/*
1585 	 * Configure hardcoded terms first, no need to check
1586 	 * return value when called with fail == 0 ;)
1587 	 */
1588 	if (config_attr(&attr, head_config, parse_state->error, config_term_pmu))
1589 		return -EINVAL;
1590 
1591 	if (get_config_terms(head_config, &config_terms))
1592 		return -ENOMEM;
1593 
1594 	/*
1595 	 * When using default config, record which bits of attr->config were
1596 	 * changed by the user.
1597 	 */
1598 	if (pmu->default_config && get_config_chgs(pmu, head_config, &config_terms))
1599 		return -ENOMEM;
1600 
1601 	if (!parse_events__inside_hybrid_pmu(parse_state, list, name,
1602 					     head_config)) {
1603 		return 0;
1604 	}
1605 
1606 	if (!parse_state->fake_pmu && perf_pmu__config(pmu, &attr, head_config, parse_state->error)) {
1607 		struct evsel_config_term *pos, *tmp;
1608 
1609 		list_for_each_entry_safe(pos, tmp, &config_terms, list) {
1610 			list_del_init(&pos->list);
1611 			if (pos->free_str)
1612 				zfree(&pos->val.str);
1613 			free(pos);
1614 		}
1615 		return -EINVAL;
1616 	}
1617 
1618 	evsel = __add_event(list, &parse_state->idx, &attr, true,
1619 			    get_config_name(head_config), pmu,
1620 			    &config_terms, auto_merge_stats, NULL);
1621 	if (!evsel)
1622 		return -ENOMEM;
1623 
1624 	if (evsel->name)
1625 		evsel->use_config_name = true;
1626 
1627 	evsel->pmu_name = name ? strdup(name) : NULL;
1628 	evsel->use_uncore_alias = use_uncore_alias;
1629 	evsel->percore = config_term_percore(&evsel->config_terms);
1630 
1631 	if (parse_state->fake_pmu)
1632 		return 0;
1633 
1634 	evsel->unit = info.unit;
1635 	evsel->scale = info.scale;
1636 	evsel->per_pkg = info.per_pkg;
1637 	evsel->snapshot = info.snapshot;
1638 	evsel->metric_expr = info.metric_expr;
1639 	evsel->metric_name = info.metric_name;
1640 	return 0;
1641 }
1642 
1643 int parse_events_multi_pmu_add(struct parse_events_state *parse_state,
1644 			       char *str, struct list_head **listp)
1645 {
1646 	struct parse_events_term *term;
1647 	struct list_head *list;
1648 	struct perf_pmu *pmu = NULL;
1649 	int ok = 0;
1650 
1651 	*listp = NULL;
1652 	/* Add it for all PMUs that support the alias */
1653 	list = malloc(sizeof(struct list_head));
1654 	if (!list)
1655 		return -1;
1656 	INIT_LIST_HEAD(list);
1657 	while ((pmu = perf_pmu__scan(pmu)) != NULL) {
1658 		struct perf_pmu_alias *alias;
1659 
1660 		list_for_each_entry(alias, &pmu->aliases, list) {
1661 			if (!strcasecmp(alias->name, str)) {
1662 				struct list_head *head;
1663 				char *config;
1664 
1665 				head = malloc(sizeof(struct list_head));
1666 				if (!head)
1667 					return -1;
1668 				INIT_LIST_HEAD(head);
1669 				config = strdup(str);
1670 				if (!config)
1671 					return -1;
1672 				if (parse_events_term__num(&term,
1673 						   PARSE_EVENTS__TERM_TYPE_USER,
1674 						   config, 1, false, &config,
1675 						   NULL) < 0) {
1676 					free(list);
1677 					free(config);
1678 					return -1;
1679 				}
1680 				list_add_tail(&term->list, head);
1681 
1682 				if (!parse_events_add_pmu(parse_state, list,
1683 							  pmu->name, head,
1684 							  true, true)) {
1685 					pr_debug("%s -> %s/%s/\n", str,
1686 						 pmu->name, alias->str);
1687 					ok++;
1688 				}
1689 
1690 				parse_events_terms__delete(head);
1691 			}
1692 		}
1693 	}
1694 	if (!ok) {
1695 		free(list);
1696 		return -1;
1697 	}
1698 	*listp = list;
1699 	return 0;
1700 }
1701 
1702 int parse_events__modifier_group(struct list_head *list,
1703 				 char *event_mod)
1704 {
1705 	return parse_events__modifier_event(list, event_mod, true);
1706 }
1707 
1708 /*
1709  * Check if the two uncore PMUs are from the same uncore block
1710  * The format of the uncore PMU name is uncore_#blockname_#pmuidx
1711  */
1712 static bool is_same_uncore_block(const char *pmu_name_a, const char *pmu_name_b)
1713 {
1714 	char *end_a, *end_b;
1715 
1716 	end_a = strrchr(pmu_name_a, '_');
1717 	end_b = strrchr(pmu_name_b, '_');
1718 
1719 	if (!end_a || !end_b)
1720 		return false;
1721 
1722 	if ((end_a - pmu_name_a) != (end_b - pmu_name_b))
1723 		return false;
1724 
1725 	return (strncmp(pmu_name_a, pmu_name_b, end_a - pmu_name_a) == 0);
1726 }
1727 
1728 static int
1729 parse_events__set_leader_for_uncore_aliase(char *name, struct list_head *list,
1730 					   struct parse_events_state *parse_state)
1731 {
1732 	struct evsel *evsel, *leader;
1733 	uintptr_t *leaders;
1734 	bool is_leader = true;
1735 	int i, nr_pmu = 0, total_members, ret = 0;
1736 
1737 	leader = list_first_entry(list, struct evsel, core.node);
1738 	evsel = list_last_entry(list, struct evsel, core.node);
1739 	total_members = evsel->idx - leader->idx + 1;
1740 
1741 	leaders = calloc(total_members, sizeof(uintptr_t));
1742 	if (WARN_ON(!leaders))
1743 		return 0;
1744 
1745 	/*
1746 	 * Going through the whole group and doing sanity check.
1747 	 * All members must use alias, and be from the same uncore block.
1748 	 * Also, storing the leader events in an array.
1749 	 */
1750 	__evlist__for_each_entry(list, evsel) {
1751 
1752 		/* Only split the uncore group which members use alias */
1753 		if (!evsel->use_uncore_alias)
1754 			goto out;
1755 
1756 		/* The events must be from the same uncore block */
1757 		if (!is_same_uncore_block(leader->pmu_name, evsel->pmu_name))
1758 			goto out;
1759 
1760 		if (!is_leader)
1761 			continue;
1762 		/*
1763 		 * If the event's PMU name starts to repeat, it must be a new
1764 		 * event. That can be used to distinguish the leader from
1765 		 * other members, even they have the same event name.
1766 		 */
1767 		if ((leader != evsel) &&
1768 		    !strcmp(leader->pmu_name, evsel->pmu_name)) {
1769 			is_leader = false;
1770 			continue;
1771 		}
1772 
1773 		/* Store the leader event for each PMU */
1774 		leaders[nr_pmu++] = (uintptr_t) evsel;
1775 	}
1776 
1777 	/* only one event alias */
1778 	if (nr_pmu == total_members) {
1779 		parse_state->nr_groups--;
1780 		goto handled;
1781 	}
1782 
1783 	/*
1784 	 * An uncore event alias is a joint name which means the same event
1785 	 * runs on all PMUs of a block.
1786 	 * Perf doesn't support mixed events from different PMUs in the same
1787 	 * group. The big group has to be split into multiple small groups
1788 	 * which only include the events from the same PMU.
1789 	 *
1790 	 * Here the uncore event aliases must be from the same uncore block.
1791 	 * The number of PMUs must be same for each alias. The number of new
1792 	 * small groups equals to the number of PMUs.
1793 	 * Setting the leader event for corresponding members in each group.
1794 	 */
1795 	i = 0;
1796 	__evlist__for_each_entry(list, evsel) {
1797 		if (i >= nr_pmu)
1798 			i = 0;
1799 		evsel->leader = (struct evsel *) leaders[i++];
1800 	}
1801 
1802 	/* The number of members and group name are same for each group */
1803 	for (i = 0; i < nr_pmu; i++) {
1804 		evsel = (struct evsel *) leaders[i];
1805 		evsel->core.nr_members = total_members / nr_pmu;
1806 		evsel->group_name = name ? strdup(name) : NULL;
1807 	}
1808 
1809 	/* Take the new small groups into account */
1810 	parse_state->nr_groups += nr_pmu - 1;
1811 
1812 handled:
1813 	ret = 1;
1814 out:
1815 	free(leaders);
1816 	return ret;
1817 }
1818 
1819 void parse_events__set_leader(char *name, struct list_head *list,
1820 			      struct parse_events_state *parse_state)
1821 {
1822 	struct evsel *leader;
1823 
1824 	if (list_empty(list)) {
1825 		WARN_ONCE(true, "WARNING: failed to set leader: empty list");
1826 		return;
1827 	}
1828 
1829 	if (parse_events__set_leader_for_uncore_aliase(name, list, parse_state))
1830 		return;
1831 
1832 	__evlist__set_leader(list);
1833 	leader = list_entry(list->next, struct evsel, core.node);
1834 	leader->group_name = name ? strdup(name) : NULL;
1835 }
1836 
1837 /* list_event is assumed to point to malloc'ed memory */
1838 void parse_events_update_lists(struct list_head *list_event,
1839 			       struct list_head *list_all)
1840 {
1841 	/*
1842 	 * Called for single event definition. Update the
1843 	 * 'all event' list, and reinit the 'single event'
1844 	 * list, for next event definition.
1845 	 */
1846 	list_splice_tail(list_event, list_all);
1847 	free(list_event);
1848 }
1849 
1850 struct event_modifier {
1851 	int eu;
1852 	int ek;
1853 	int eh;
1854 	int eH;
1855 	int eG;
1856 	int eI;
1857 	int precise;
1858 	int precise_max;
1859 	int exclude_GH;
1860 	int sample_read;
1861 	int pinned;
1862 	int weak;
1863 	int exclusive;
1864 	int bpf_counter;
1865 };
1866 
1867 static int get_event_modifier(struct event_modifier *mod, char *str,
1868 			       struct evsel *evsel)
1869 {
1870 	int eu = evsel ? evsel->core.attr.exclude_user : 0;
1871 	int ek = evsel ? evsel->core.attr.exclude_kernel : 0;
1872 	int eh = evsel ? evsel->core.attr.exclude_hv : 0;
1873 	int eH = evsel ? evsel->core.attr.exclude_host : 0;
1874 	int eG = evsel ? evsel->core.attr.exclude_guest : 0;
1875 	int eI = evsel ? evsel->core.attr.exclude_idle : 0;
1876 	int precise = evsel ? evsel->core.attr.precise_ip : 0;
1877 	int precise_max = 0;
1878 	int sample_read = 0;
1879 	int pinned = evsel ? evsel->core.attr.pinned : 0;
1880 	int exclusive = evsel ? evsel->core.attr.exclusive : 0;
1881 
1882 	int exclude = eu | ek | eh;
1883 	int exclude_GH = evsel ? evsel->exclude_GH : 0;
1884 	int weak = 0;
1885 	int bpf_counter = 0;
1886 
1887 	memset(mod, 0, sizeof(*mod));
1888 
1889 	while (*str) {
1890 		if (*str == 'u') {
1891 			if (!exclude)
1892 				exclude = eu = ek = eh = 1;
1893 			if (!exclude_GH && !perf_guest)
1894 				eG = 1;
1895 			eu = 0;
1896 		} else if (*str == 'k') {
1897 			if (!exclude)
1898 				exclude = eu = ek = eh = 1;
1899 			ek = 0;
1900 		} else if (*str == 'h') {
1901 			if (!exclude)
1902 				exclude = eu = ek = eh = 1;
1903 			eh = 0;
1904 		} else if (*str == 'G') {
1905 			if (!exclude_GH)
1906 				exclude_GH = eG = eH = 1;
1907 			eG = 0;
1908 		} else if (*str == 'H') {
1909 			if (!exclude_GH)
1910 				exclude_GH = eG = eH = 1;
1911 			eH = 0;
1912 		} else if (*str == 'I') {
1913 			eI = 1;
1914 		} else if (*str == 'p') {
1915 			precise++;
1916 			/* use of precise requires exclude_guest */
1917 			if (!exclude_GH)
1918 				eG = 1;
1919 		} else if (*str == 'P') {
1920 			precise_max = 1;
1921 		} else if (*str == 'S') {
1922 			sample_read = 1;
1923 		} else if (*str == 'D') {
1924 			pinned = 1;
1925 		} else if (*str == 'e') {
1926 			exclusive = 1;
1927 		} else if (*str == 'W') {
1928 			weak = 1;
1929 		} else if (*str == 'b') {
1930 			bpf_counter = 1;
1931 		} else
1932 			break;
1933 
1934 		++str;
1935 	}
1936 
1937 	/*
1938 	 * precise ip:
1939 	 *
1940 	 *  0 - SAMPLE_IP can have arbitrary skid
1941 	 *  1 - SAMPLE_IP must have constant skid
1942 	 *  2 - SAMPLE_IP requested to have 0 skid
1943 	 *  3 - SAMPLE_IP must have 0 skid
1944 	 *
1945 	 *  See also PERF_RECORD_MISC_EXACT_IP
1946 	 */
1947 	if (precise > 3)
1948 		return -EINVAL;
1949 
1950 	mod->eu = eu;
1951 	mod->ek = ek;
1952 	mod->eh = eh;
1953 	mod->eH = eH;
1954 	mod->eG = eG;
1955 	mod->eI = eI;
1956 	mod->precise = precise;
1957 	mod->precise_max = precise_max;
1958 	mod->exclude_GH = exclude_GH;
1959 	mod->sample_read = sample_read;
1960 	mod->pinned = pinned;
1961 	mod->weak = weak;
1962 	mod->bpf_counter = bpf_counter;
1963 	mod->exclusive = exclusive;
1964 
1965 	return 0;
1966 }
1967 
1968 /*
1969  * Basic modifier sanity check to validate it contains only one
1970  * instance of any modifier (apart from 'p') present.
1971  */
1972 static int check_modifier(char *str)
1973 {
1974 	char *p = str;
1975 
1976 	/* The sizeof includes 0 byte as well. */
1977 	if (strlen(str) > (sizeof("ukhGHpppPSDIWeb") - 1))
1978 		return -1;
1979 
1980 	while (*p) {
1981 		if (*p != 'p' && strchr(p + 1, *p))
1982 			return -1;
1983 		p++;
1984 	}
1985 
1986 	return 0;
1987 }
1988 
1989 int parse_events__modifier_event(struct list_head *list, char *str, bool add)
1990 {
1991 	struct evsel *evsel;
1992 	struct event_modifier mod;
1993 
1994 	if (str == NULL)
1995 		return 0;
1996 
1997 	if (check_modifier(str))
1998 		return -EINVAL;
1999 
2000 	if (!add && get_event_modifier(&mod, str, NULL))
2001 		return -EINVAL;
2002 
2003 	__evlist__for_each_entry(list, evsel) {
2004 		if (add && get_event_modifier(&mod, str, evsel))
2005 			return -EINVAL;
2006 
2007 		evsel->core.attr.exclude_user   = mod.eu;
2008 		evsel->core.attr.exclude_kernel = mod.ek;
2009 		evsel->core.attr.exclude_hv     = mod.eh;
2010 		evsel->core.attr.precise_ip     = mod.precise;
2011 		evsel->core.attr.exclude_host   = mod.eH;
2012 		evsel->core.attr.exclude_guest  = mod.eG;
2013 		evsel->core.attr.exclude_idle   = mod.eI;
2014 		evsel->exclude_GH          = mod.exclude_GH;
2015 		evsel->sample_read         = mod.sample_read;
2016 		evsel->precise_max         = mod.precise_max;
2017 		evsel->weak_group	   = mod.weak;
2018 		evsel->bpf_counter	   = mod.bpf_counter;
2019 
2020 		if (evsel__is_group_leader(evsel)) {
2021 			evsel->core.attr.pinned = mod.pinned;
2022 			evsel->core.attr.exclusive = mod.exclusive;
2023 		}
2024 	}
2025 
2026 	return 0;
2027 }
2028 
2029 int parse_events_name(struct list_head *list, char *name)
2030 {
2031 	struct evsel *evsel;
2032 
2033 	__evlist__for_each_entry(list, evsel) {
2034 		if (!evsel->name)
2035 			evsel->name = strdup(name);
2036 	}
2037 
2038 	return 0;
2039 }
2040 
2041 static int
2042 comp_pmu(const void *p1, const void *p2)
2043 {
2044 	struct perf_pmu_event_symbol *pmu1 = (struct perf_pmu_event_symbol *) p1;
2045 	struct perf_pmu_event_symbol *pmu2 = (struct perf_pmu_event_symbol *) p2;
2046 
2047 	return strcasecmp(pmu1->symbol, pmu2->symbol);
2048 }
2049 
2050 static void perf_pmu__parse_cleanup(void)
2051 {
2052 	if (perf_pmu_events_list_num > 0) {
2053 		struct perf_pmu_event_symbol *p;
2054 		int i;
2055 
2056 		for (i = 0; i < perf_pmu_events_list_num; i++) {
2057 			p = perf_pmu_events_list + i;
2058 			zfree(&p->symbol);
2059 		}
2060 		zfree(&perf_pmu_events_list);
2061 		perf_pmu_events_list_num = 0;
2062 	}
2063 }
2064 
2065 #define SET_SYMBOL(str, stype)		\
2066 do {					\
2067 	p->symbol = str;		\
2068 	if (!p->symbol)			\
2069 		goto err;		\
2070 	p->type = stype;		\
2071 } while (0)
2072 
2073 /*
2074  * Read the pmu events list from sysfs
2075  * Save it into perf_pmu_events_list
2076  */
2077 static void perf_pmu__parse_init(void)
2078 {
2079 
2080 	struct perf_pmu *pmu = NULL;
2081 	struct perf_pmu_alias *alias;
2082 	int len = 0;
2083 
2084 	pmu = NULL;
2085 	while ((pmu = perf_pmu__scan(pmu)) != NULL) {
2086 		list_for_each_entry(alias, &pmu->aliases, list) {
2087 			if (strchr(alias->name, '-'))
2088 				len++;
2089 			len++;
2090 		}
2091 	}
2092 
2093 	if (len == 0) {
2094 		perf_pmu_events_list_num = -1;
2095 		return;
2096 	}
2097 	perf_pmu_events_list = malloc(sizeof(struct perf_pmu_event_symbol) * len);
2098 	if (!perf_pmu_events_list)
2099 		return;
2100 	perf_pmu_events_list_num = len;
2101 
2102 	len = 0;
2103 	pmu = NULL;
2104 	while ((pmu = perf_pmu__scan(pmu)) != NULL) {
2105 		list_for_each_entry(alias, &pmu->aliases, list) {
2106 			struct perf_pmu_event_symbol *p = perf_pmu_events_list + len;
2107 			char *tmp = strchr(alias->name, '-');
2108 
2109 			if (tmp != NULL) {
2110 				SET_SYMBOL(strndup(alias->name, tmp - alias->name),
2111 						PMU_EVENT_SYMBOL_PREFIX);
2112 				p++;
2113 				SET_SYMBOL(strdup(++tmp), PMU_EVENT_SYMBOL_SUFFIX);
2114 				len += 2;
2115 			} else {
2116 				SET_SYMBOL(strdup(alias->name), PMU_EVENT_SYMBOL);
2117 				len++;
2118 			}
2119 		}
2120 	}
2121 	qsort(perf_pmu_events_list, len,
2122 		sizeof(struct perf_pmu_event_symbol), comp_pmu);
2123 
2124 	return;
2125 err:
2126 	perf_pmu__parse_cleanup();
2127 }
2128 
2129 /*
2130  * This function injects special term in
2131  * perf_pmu_events_list so the test code
2132  * can check on this functionality.
2133  */
2134 int perf_pmu__test_parse_init(void)
2135 {
2136 	struct perf_pmu_event_symbol *list;
2137 
2138 	list = malloc(sizeof(*list) * 1);
2139 	if (!list)
2140 		return -ENOMEM;
2141 
2142 	list->type   = PMU_EVENT_SYMBOL;
2143 	list->symbol = strdup("read");
2144 
2145 	if (!list->symbol) {
2146 		free(list);
2147 		return -ENOMEM;
2148 	}
2149 
2150 	perf_pmu_events_list = list;
2151 	perf_pmu_events_list_num = 1;
2152 	return 0;
2153 }
2154 
2155 enum perf_pmu_event_symbol_type
2156 perf_pmu__parse_check(const char *name)
2157 {
2158 	struct perf_pmu_event_symbol p, *r;
2159 
2160 	/* scan kernel pmu events from sysfs if needed */
2161 	if (perf_pmu_events_list_num == 0)
2162 		perf_pmu__parse_init();
2163 	/*
2164 	 * name "cpu" could be prefix of cpu-cycles or cpu// events.
2165 	 * cpu-cycles has been handled by hardcode.
2166 	 * So it must be cpu// events, not kernel pmu event.
2167 	 */
2168 	if ((perf_pmu_events_list_num <= 0) || !strcmp(name, "cpu"))
2169 		return PMU_EVENT_SYMBOL_ERR;
2170 
2171 	p.symbol = strdup(name);
2172 	r = bsearch(&p, perf_pmu_events_list,
2173 			(size_t) perf_pmu_events_list_num,
2174 			sizeof(struct perf_pmu_event_symbol), comp_pmu);
2175 	zfree(&p.symbol);
2176 	return r ? r->type : PMU_EVENT_SYMBOL_ERR;
2177 }
2178 
2179 static int parse_events__scanner(const char *str,
2180 				 struct parse_events_state *parse_state)
2181 {
2182 	YY_BUFFER_STATE buffer;
2183 	void *scanner;
2184 	int ret;
2185 
2186 	ret = parse_events_lex_init_extra(parse_state, &scanner);
2187 	if (ret)
2188 		return ret;
2189 
2190 	buffer = parse_events__scan_string(str, scanner);
2191 
2192 #ifdef PARSER_DEBUG
2193 	parse_events_debug = 1;
2194 	parse_events_set_debug(1, scanner);
2195 #endif
2196 	ret = parse_events_parse(parse_state, scanner);
2197 
2198 	parse_events__flush_buffer(buffer, scanner);
2199 	parse_events__delete_buffer(buffer, scanner);
2200 	parse_events_lex_destroy(scanner);
2201 	return ret;
2202 }
2203 
2204 /*
2205  * parse event config string, return a list of event terms.
2206  */
2207 int parse_events_terms(struct list_head *terms, const char *str)
2208 {
2209 	struct parse_events_state parse_state = {
2210 		.terms  = NULL,
2211 		.stoken = PE_START_TERMS,
2212 	};
2213 	int ret;
2214 
2215 	ret = parse_events__scanner(str, &parse_state);
2216 	perf_pmu__parse_cleanup();
2217 
2218 	if (!ret) {
2219 		list_splice(parse_state.terms, terms);
2220 		zfree(&parse_state.terms);
2221 		return 0;
2222 	}
2223 
2224 	parse_events_terms__delete(parse_state.terms);
2225 	return ret;
2226 }
2227 
2228 static int parse_events__with_hybrid_pmu(struct parse_events_state *parse_state,
2229 					 const char *str, char *pmu_name,
2230 					 struct list_head *list)
2231 {
2232 	struct parse_events_state ps = {
2233 		.list            = LIST_HEAD_INIT(ps.list),
2234 		.stoken          = PE_START_EVENTS,
2235 		.hybrid_pmu_name = pmu_name,
2236 		.idx             = parse_state->idx,
2237 	};
2238 	int ret;
2239 
2240 	ret = parse_events__scanner(str, &ps);
2241 	perf_pmu__parse_cleanup();
2242 
2243 	if (!ret) {
2244 		if (!list_empty(&ps.list)) {
2245 			list_splice(&ps.list, list);
2246 			parse_state->idx = ps.idx;
2247 			return 0;
2248 		} else
2249 			return -1;
2250 	}
2251 
2252 	return ret;
2253 }
2254 
2255 int __parse_events(struct evlist *evlist, const char *str,
2256 		   struct parse_events_error *err, struct perf_pmu *fake_pmu)
2257 {
2258 	struct parse_events_state parse_state = {
2259 		.list	  = LIST_HEAD_INIT(parse_state.list),
2260 		.idx	  = evlist->core.nr_entries,
2261 		.error	  = err,
2262 		.evlist	  = evlist,
2263 		.stoken	  = PE_START_EVENTS,
2264 		.fake_pmu = fake_pmu,
2265 	};
2266 	int ret;
2267 
2268 	ret = parse_events__scanner(str, &parse_state);
2269 	perf_pmu__parse_cleanup();
2270 
2271 	if (!ret && list_empty(&parse_state.list)) {
2272 		WARN_ONCE(true, "WARNING: event parser found nothing\n");
2273 		return -1;
2274 	}
2275 
2276 	/*
2277 	 * Add list to the evlist even with errors to allow callers to clean up.
2278 	 */
2279 	evlist__splice_list_tail(evlist, &parse_state.list);
2280 
2281 	if (!ret) {
2282 		struct evsel *last;
2283 
2284 		evlist->nr_groups += parse_state.nr_groups;
2285 		last = evlist__last(evlist);
2286 		last->cmdline_group_boundary = true;
2287 
2288 		return 0;
2289 	}
2290 
2291 	/*
2292 	 * There are 2 users - builtin-record and builtin-test objects.
2293 	 * Both call evlist__delete in case of error, so we dont
2294 	 * need to bother.
2295 	 */
2296 	return ret;
2297 }
2298 
2299 #define MAX_WIDTH 1000
2300 static int get_term_width(void)
2301 {
2302 	struct winsize ws;
2303 
2304 	get_term_dimensions(&ws);
2305 	return ws.ws_col > MAX_WIDTH ? MAX_WIDTH : ws.ws_col;
2306 }
2307 
2308 static void __parse_events_print_error(int err_idx, const char *err_str,
2309 				const char *err_help, const char *event)
2310 {
2311 	const char *str = "invalid or unsupported event: ";
2312 	char _buf[MAX_WIDTH];
2313 	char *buf = (char *) event;
2314 	int idx = 0;
2315 	if (err_str) {
2316 		/* -2 for extra '' in the final fprintf */
2317 		int width       = get_term_width() - 2;
2318 		int len_event   = strlen(event);
2319 		int len_str, max_len, cut = 0;
2320 
2321 		/*
2322 		 * Maximum error index indent, we will cut
2323 		 * the event string if it's bigger.
2324 		 */
2325 		int max_err_idx = 13;
2326 
2327 		/*
2328 		 * Let's be specific with the message when
2329 		 * we have the precise error.
2330 		 */
2331 		str     = "event syntax error: ";
2332 		len_str = strlen(str);
2333 		max_len = width - len_str;
2334 
2335 		buf = _buf;
2336 
2337 		/* We're cutting from the beginning. */
2338 		if (err_idx > max_err_idx)
2339 			cut = err_idx - max_err_idx;
2340 
2341 		strncpy(buf, event + cut, max_len);
2342 
2343 		/* Mark cut parts with '..' on both sides. */
2344 		if (cut)
2345 			buf[0] = buf[1] = '.';
2346 
2347 		if ((len_event - cut) > max_len) {
2348 			buf[max_len - 1] = buf[max_len - 2] = '.';
2349 			buf[max_len] = 0;
2350 		}
2351 
2352 		idx = len_str + err_idx - cut;
2353 	}
2354 
2355 	fprintf(stderr, "%s'%s'\n", str, buf);
2356 	if (idx) {
2357 		fprintf(stderr, "%*s\\___ %s\n", idx + 1, "", err_str);
2358 		if (err_help)
2359 			fprintf(stderr, "\n%s\n", err_help);
2360 	}
2361 }
2362 
2363 void parse_events_print_error(struct parse_events_error *err,
2364 			      const char *event)
2365 {
2366 	if (!err->num_errors)
2367 		return;
2368 
2369 	__parse_events_print_error(err->idx, err->str, err->help, event);
2370 	zfree(&err->str);
2371 	zfree(&err->help);
2372 
2373 	if (err->num_errors > 1) {
2374 		fputs("\nInitial error:\n", stderr);
2375 		__parse_events_print_error(err->first_idx, err->first_str,
2376 					err->first_help, event);
2377 		zfree(&err->first_str);
2378 		zfree(&err->first_help);
2379 	}
2380 }
2381 
2382 #undef MAX_WIDTH
2383 
2384 int parse_events_option(const struct option *opt, const char *str,
2385 			int unset __maybe_unused)
2386 {
2387 	struct evlist *evlist = *(struct evlist **)opt->value;
2388 	struct parse_events_error err;
2389 	int ret;
2390 
2391 	bzero(&err, sizeof(err));
2392 	ret = parse_events(evlist, str, &err);
2393 
2394 	if (ret) {
2395 		parse_events_print_error(&err, str);
2396 		fprintf(stderr, "Run 'perf list' for a list of valid events\n");
2397 	}
2398 
2399 	return ret;
2400 }
2401 
2402 int parse_events_option_new_evlist(const struct option *opt, const char *str, int unset)
2403 {
2404 	struct evlist **evlistp = opt->value;
2405 	int ret;
2406 
2407 	if (*evlistp == NULL) {
2408 		*evlistp = evlist__new();
2409 
2410 		if (*evlistp == NULL) {
2411 			fprintf(stderr, "Not enough memory to create evlist\n");
2412 			return -1;
2413 		}
2414 	}
2415 
2416 	ret = parse_events_option(opt, str, unset);
2417 	if (ret) {
2418 		evlist__delete(*evlistp);
2419 		*evlistp = NULL;
2420 	}
2421 
2422 	return ret;
2423 }
2424 
2425 static int
2426 foreach_evsel_in_last_glob(struct evlist *evlist,
2427 			   int (*func)(struct evsel *evsel,
2428 				       const void *arg),
2429 			   const void *arg)
2430 {
2431 	struct evsel *last = NULL;
2432 	int err;
2433 
2434 	/*
2435 	 * Don't return when list_empty, give func a chance to report
2436 	 * error when it found last == NULL.
2437 	 *
2438 	 * So no need to WARN here, let *func do this.
2439 	 */
2440 	if (evlist->core.nr_entries > 0)
2441 		last = evlist__last(evlist);
2442 
2443 	do {
2444 		err = (*func)(last, arg);
2445 		if (err)
2446 			return -1;
2447 		if (!last)
2448 			return 0;
2449 
2450 		if (last->core.node.prev == &evlist->core.entries)
2451 			return 0;
2452 		last = list_entry(last->core.node.prev, struct evsel, core.node);
2453 	} while (!last->cmdline_group_boundary);
2454 
2455 	return 0;
2456 }
2457 
2458 static int set_filter(struct evsel *evsel, const void *arg)
2459 {
2460 	const char *str = arg;
2461 	bool found = false;
2462 	int nr_addr_filters = 0;
2463 	struct perf_pmu *pmu = NULL;
2464 
2465 	if (evsel == NULL) {
2466 		fprintf(stderr,
2467 			"--filter option should follow a -e tracepoint or HW tracer option\n");
2468 		return -1;
2469 	}
2470 
2471 	if (evsel->core.attr.type == PERF_TYPE_TRACEPOINT) {
2472 		if (evsel__append_tp_filter(evsel, str) < 0) {
2473 			fprintf(stderr,
2474 				"not enough memory to hold filter string\n");
2475 			return -1;
2476 		}
2477 
2478 		return 0;
2479 	}
2480 
2481 	while ((pmu = perf_pmu__scan(pmu)) != NULL)
2482 		if (pmu->type == evsel->core.attr.type) {
2483 			found = true;
2484 			break;
2485 		}
2486 
2487 	if (found)
2488 		perf_pmu__scan_file(pmu, "nr_addr_filters",
2489 				    "%d", &nr_addr_filters);
2490 
2491 	if (!nr_addr_filters) {
2492 		fprintf(stderr,
2493 			"This CPU does not support address filtering\n");
2494 		return -1;
2495 	}
2496 
2497 	if (evsel__append_addr_filter(evsel, str) < 0) {
2498 		fprintf(stderr,
2499 			"not enough memory to hold filter string\n");
2500 		return -1;
2501 	}
2502 
2503 	return 0;
2504 }
2505 
2506 int parse_filter(const struct option *opt, const char *str,
2507 		 int unset __maybe_unused)
2508 {
2509 	struct evlist *evlist = *(struct evlist **)opt->value;
2510 
2511 	return foreach_evsel_in_last_glob(evlist, set_filter,
2512 					  (const void *)str);
2513 }
2514 
2515 static int add_exclude_perf_filter(struct evsel *evsel,
2516 				   const void *arg __maybe_unused)
2517 {
2518 	char new_filter[64];
2519 
2520 	if (evsel == NULL || evsel->core.attr.type != PERF_TYPE_TRACEPOINT) {
2521 		fprintf(stderr,
2522 			"--exclude-perf option should follow a -e tracepoint option\n");
2523 		return -1;
2524 	}
2525 
2526 	snprintf(new_filter, sizeof(new_filter), "common_pid != %d", getpid());
2527 
2528 	if (evsel__append_tp_filter(evsel, new_filter) < 0) {
2529 		fprintf(stderr,
2530 			"not enough memory to hold filter string\n");
2531 		return -1;
2532 	}
2533 
2534 	return 0;
2535 }
2536 
2537 int exclude_perf(const struct option *opt,
2538 		 const char *arg __maybe_unused,
2539 		 int unset __maybe_unused)
2540 {
2541 	struct evlist *evlist = *(struct evlist **)opt->value;
2542 
2543 	return foreach_evsel_in_last_glob(evlist, add_exclude_perf_filter,
2544 					  NULL);
2545 }
2546 
2547 static const char * const event_type_descriptors[] = {
2548 	"Hardware event",
2549 	"Software event",
2550 	"Tracepoint event",
2551 	"Hardware cache event",
2552 	"Raw hardware event descriptor",
2553 	"Hardware breakpoint",
2554 };
2555 
2556 static int cmp_string(const void *a, const void *b)
2557 {
2558 	const char * const *as = a;
2559 	const char * const *bs = b;
2560 
2561 	return strcmp(*as, *bs);
2562 }
2563 
2564 /*
2565  * Print the events from <debugfs_mount_point>/tracing/events
2566  */
2567 
2568 void print_tracepoint_events(const char *subsys_glob, const char *event_glob,
2569 			     bool name_only)
2570 {
2571 	DIR *sys_dir, *evt_dir;
2572 	struct dirent *sys_dirent, *evt_dirent;
2573 	char evt_path[MAXPATHLEN];
2574 	char *dir_path;
2575 	char **evt_list = NULL;
2576 	unsigned int evt_i = 0, evt_num = 0;
2577 	bool evt_num_known = false;
2578 
2579 restart:
2580 	sys_dir = tracing_events__opendir();
2581 	if (!sys_dir)
2582 		return;
2583 
2584 	if (evt_num_known) {
2585 		evt_list = zalloc(sizeof(char *) * evt_num);
2586 		if (!evt_list)
2587 			goto out_close_sys_dir;
2588 	}
2589 
2590 	for_each_subsystem(sys_dir, sys_dirent) {
2591 		if (subsys_glob != NULL &&
2592 		    !strglobmatch(sys_dirent->d_name, subsys_glob))
2593 			continue;
2594 
2595 		dir_path = get_events_file(sys_dirent->d_name);
2596 		if (!dir_path)
2597 			continue;
2598 		evt_dir = opendir(dir_path);
2599 		if (!evt_dir)
2600 			goto next;
2601 
2602 		for_each_event(dir_path, evt_dir, evt_dirent) {
2603 			if (event_glob != NULL &&
2604 			    !strglobmatch(evt_dirent->d_name, event_glob))
2605 				continue;
2606 
2607 			if (!evt_num_known) {
2608 				evt_num++;
2609 				continue;
2610 			}
2611 
2612 			snprintf(evt_path, MAXPATHLEN, "%s:%s",
2613 				 sys_dirent->d_name, evt_dirent->d_name);
2614 
2615 			evt_list[evt_i] = strdup(evt_path);
2616 			if (evt_list[evt_i] == NULL) {
2617 				put_events_file(dir_path);
2618 				goto out_close_evt_dir;
2619 			}
2620 			evt_i++;
2621 		}
2622 		closedir(evt_dir);
2623 next:
2624 		put_events_file(dir_path);
2625 	}
2626 	closedir(sys_dir);
2627 
2628 	if (!evt_num_known) {
2629 		evt_num_known = true;
2630 		goto restart;
2631 	}
2632 	qsort(evt_list, evt_num, sizeof(char *), cmp_string);
2633 	evt_i = 0;
2634 	while (evt_i < evt_num) {
2635 		if (name_only) {
2636 			printf("%s ", evt_list[evt_i++]);
2637 			continue;
2638 		}
2639 		printf("  %-50s [%s]\n", evt_list[evt_i++],
2640 				event_type_descriptors[PERF_TYPE_TRACEPOINT]);
2641 	}
2642 	if (evt_num && pager_in_use())
2643 		printf("\n");
2644 
2645 out_free:
2646 	evt_num = evt_i;
2647 	for (evt_i = 0; evt_i < evt_num; evt_i++)
2648 		zfree(&evt_list[evt_i]);
2649 	zfree(&evt_list);
2650 	return;
2651 
2652 out_close_evt_dir:
2653 	closedir(evt_dir);
2654 out_close_sys_dir:
2655 	closedir(sys_dir);
2656 
2657 	printf("FATAL: not enough memory to print %s\n",
2658 			event_type_descriptors[PERF_TYPE_TRACEPOINT]);
2659 	if (evt_list)
2660 		goto out_free;
2661 }
2662 
2663 /*
2664  * Check whether event is in <debugfs_mount_point>/tracing/events
2665  */
2666 
2667 int is_valid_tracepoint(const char *event_string)
2668 {
2669 	DIR *sys_dir, *evt_dir;
2670 	struct dirent *sys_dirent, *evt_dirent;
2671 	char evt_path[MAXPATHLEN];
2672 	char *dir_path;
2673 
2674 	sys_dir = tracing_events__opendir();
2675 	if (!sys_dir)
2676 		return 0;
2677 
2678 	for_each_subsystem(sys_dir, sys_dirent) {
2679 		dir_path = get_events_file(sys_dirent->d_name);
2680 		if (!dir_path)
2681 			continue;
2682 		evt_dir = opendir(dir_path);
2683 		if (!evt_dir)
2684 			goto next;
2685 
2686 		for_each_event(dir_path, evt_dir, evt_dirent) {
2687 			snprintf(evt_path, MAXPATHLEN, "%s:%s",
2688 				 sys_dirent->d_name, evt_dirent->d_name);
2689 			if (!strcmp(evt_path, event_string)) {
2690 				closedir(evt_dir);
2691 				closedir(sys_dir);
2692 				return 1;
2693 			}
2694 		}
2695 		closedir(evt_dir);
2696 next:
2697 		put_events_file(dir_path);
2698 	}
2699 	closedir(sys_dir);
2700 	return 0;
2701 }
2702 
2703 static bool is_event_supported(u8 type, unsigned config)
2704 {
2705 	bool ret = true;
2706 	int open_return;
2707 	struct evsel *evsel;
2708 	struct perf_event_attr attr = {
2709 		.type = type,
2710 		.config = config,
2711 		.disabled = 1,
2712 	};
2713 	struct perf_thread_map *tmap = thread_map__new_by_tid(0);
2714 
2715 	if (tmap == NULL)
2716 		return false;
2717 
2718 	evsel = evsel__new(&attr);
2719 	if (evsel) {
2720 		open_return = evsel__open(evsel, NULL, tmap);
2721 		ret = open_return >= 0;
2722 
2723 		if (open_return == -EACCES) {
2724 			/*
2725 			 * This happens if the paranoid value
2726 			 * /proc/sys/kernel/perf_event_paranoid is set to 2
2727 			 * Re-run with exclude_kernel set; we don't do that
2728 			 * by default as some ARM machines do not support it.
2729 			 *
2730 			 */
2731 			evsel->core.attr.exclude_kernel = 1;
2732 			ret = evsel__open(evsel, NULL, tmap) >= 0;
2733 		}
2734 		evsel__delete(evsel);
2735 	}
2736 
2737 	perf_thread_map__put(tmap);
2738 	return ret;
2739 }
2740 
2741 void print_sdt_events(const char *subsys_glob, const char *event_glob,
2742 		      bool name_only)
2743 {
2744 	struct probe_cache *pcache;
2745 	struct probe_cache_entry *ent;
2746 	struct strlist *bidlist, *sdtlist;
2747 	struct strlist_config cfg = {.dont_dupstr = true};
2748 	struct str_node *nd, *nd2;
2749 	char *buf, *path, *ptr = NULL;
2750 	bool show_detail = false;
2751 	int ret;
2752 
2753 	sdtlist = strlist__new(NULL, &cfg);
2754 	if (!sdtlist) {
2755 		pr_debug("Failed to allocate new strlist for SDT\n");
2756 		return;
2757 	}
2758 	bidlist = build_id_cache__list_all(true);
2759 	if (!bidlist) {
2760 		pr_debug("Failed to get buildids: %d\n", errno);
2761 		return;
2762 	}
2763 	strlist__for_each_entry(nd, bidlist) {
2764 		pcache = probe_cache__new(nd->s, NULL);
2765 		if (!pcache)
2766 			continue;
2767 		list_for_each_entry(ent, &pcache->entries, node) {
2768 			if (!ent->sdt)
2769 				continue;
2770 			if (subsys_glob &&
2771 			    !strglobmatch(ent->pev.group, subsys_glob))
2772 				continue;
2773 			if (event_glob &&
2774 			    !strglobmatch(ent->pev.event, event_glob))
2775 				continue;
2776 			ret = asprintf(&buf, "%s:%s@%s", ent->pev.group,
2777 					ent->pev.event, nd->s);
2778 			if (ret > 0)
2779 				strlist__add(sdtlist, buf);
2780 		}
2781 		probe_cache__delete(pcache);
2782 	}
2783 	strlist__delete(bidlist);
2784 
2785 	strlist__for_each_entry(nd, sdtlist) {
2786 		buf = strchr(nd->s, '@');
2787 		if (buf)
2788 			*(buf++) = '\0';
2789 		if (name_only) {
2790 			printf("%s ", nd->s);
2791 			continue;
2792 		}
2793 		nd2 = strlist__next(nd);
2794 		if (nd2) {
2795 			ptr = strchr(nd2->s, '@');
2796 			if (ptr)
2797 				*ptr = '\0';
2798 			if (strcmp(nd->s, nd2->s) == 0)
2799 				show_detail = true;
2800 		}
2801 		if (show_detail) {
2802 			path = build_id_cache__origname(buf);
2803 			ret = asprintf(&buf, "%s@%s(%.12s)", nd->s, path, buf);
2804 			if (ret > 0) {
2805 				printf("  %-50s [%s]\n", buf, "SDT event");
2806 				free(buf);
2807 			}
2808 			free(path);
2809 		} else
2810 			printf("  %-50s [%s]\n", nd->s, "SDT event");
2811 		if (nd2) {
2812 			if (strcmp(nd->s, nd2->s) != 0)
2813 				show_detail = false;
2814 			if (ptr)
2815 				*ptr = '@';
2816 		}
2817 	}
2818 	strlist__delete(sdtlist);
2819 }
2820 
2821 int print_hwcache_events(const char *event_glob, bool name_only)
2822 {
2823 	unsigned int type, op, i, evt_i = 0, evt_num = 0;
2824 	char name[64];
2825 	char **evt_list = NULL;
2826 	bool evt_num_known = false;
2827 
2828 restart:
2829 	if (evt_num_known) {
2830 		evt_list = zalloc(sizeof(char *) * evt_num);
2831 		if (!evt_list)
2832 			goto out_enomem;
2833 	}
2834 
2835 	for (type = 0; type < PERF_COUNT_HW_CACHE_MAX; type++) {
2836 		for (op = 0; op < PERF_COUNT_HW_CACHE_OP_MAX; op++) {
2837 			/* skip invalid cache type */
2838 			if (!evsel__is_cache_op_valid(type, op))
2839 				continue;
2840 
2841 			for (i = 0; i < PERF_COUNT_HW_CACHE_RESULT_MAX; i++) {
2842 				__evsel__hw_cache_type_op_res_name(type, op, i, name, sizeof(name));
2843 				if (event_glob != NULL && !strglobmatch(name, event_glob))
2844 					continue;
2845 
2846 				if (!is_event_supported(PERF_TYPE_HW_CACHE,
2847 							type | (op << 8) | (i << 16)))
2848 					continue;
2849 
2850 				if (!evt_num_known) {
2851 					evt_num++;
2852 					continue;
2853 				}
2854 
2855 				evt_list[evt_i] = strdup(name);
2856 				if (evt_list[evt_i] == NULL)
2857 					goto out_enomem;
2858 				evt_i++;
2859 			}
2860 		}
2861 	}
2862 
2863 	if (!evt_num_known) {
2864 		evt_num_known = true;
2865 		goto restart;
2866 	}
2867 	qsort(evt_list, evt_num, sizeof(char *), cmp_string);
2868 	evt_i = 0;
2869 	while (evt_i < evt_num) {
2870 		if (name_only) {
2871 			printf("%s ", evt_list[evt_i++]);
2872 			continue;
2873 		}
2874 		printf("  %-50s [%s]\n", evt_list[evt_i++],
2875 				event_type_descriptors[PERF_TYPE_HW_CACHE]);
2876 	}
2877 	if (evt_num && pager_in_use())
2878 		printf("\n");
2879 
2880 out_free:
2881 	evt_num = evt_i;
2882 	for (evt_i = 0; evt_i < evt_num; evt_i++)
2883 		zfree(&evt_list[evt_i]);
2884 	zfree(&evt_list);
2885 	return evt_num;
2886 
2887 out_enomem:
2888 	printf("FATAL: not enough memory to print %s\n", event_type_descriptors[PERF_TYPE_HW_CACHE]);
2889 	if (evt_list)
2890 		goto out_free;
2891 	return evt_num;
2892 }
2893 
2894 static void print_tool_event(const char *name, const char *event_glob,
2895 			     bool name_only)
2896 {
2897 	if (event_glob && !strglobmatch(name, event_glob))
2898 		return;
2899 	if (name_only)
2900 		printf("%s ", name);
2901 	else
2902 		printf("  %-50s [%s]\n", name, "Tool event");
2903 
2904 }
2905 
2906 void print_tool_events(const char *event_glob, bool name_only)
2907 {
2908 	print_tool_event("duration_time", event_glob, name_only);
2909 	if (pager_in_use())
2910 		printf("\n");
2911 }
2912 
2913 void print_symbol_events(const char *event_glob, unsigned type,
2914 				struct event_symbol *syms, unsigned max,
2915 				bool name_only)
2916 {
2917 	unsigned int i, evt_i = 0, evt_num = 0;
2918 	char name[MAX_NAME_LEN];
2919 	char **evt_list = NULL;
2920 	bool evt_num_known = false;
2921 
2922 restart:
2923 	if (evt_num_known) {
2924 		evt_list = zalloc(sizeof(char *) * evt_num);
2925 		if (!evt_list)
2926 			goto out_enomem;
2927 		syms -= max;
2928 	}
2929 
2930 	for (i = 0; i < max; i++, syms++) {
2931 
2932 		if (event_glob != NULL && syms->symbol != NULL &&
2933 		    !(strglobmatch(syms->symbol, event_glob) ||
2934 		      (syms->alias && strglobmatch(syms->alias, event_glob))))
2935 			continue;
2936 
2937 		if (!is_event_supported(type, i))
2938 			continue;
2939 
2940 		if (!evt_num_known) {
2941 			evt_num++;
2942 			continue;
2943 		}
2944 
2945 		if (!name_only && strlen(syms->alias))
2946 			snprintf(name, MAX_NAME_LEN, "%s OR %s", syms->symbol, syms->alias);
2947 		else
2948 			strlcpy(name, syms->symbol, MAX_NAME_LEN);
2949 
2950 		evt_list[evt_i] = strdup(name);
2951 		if (evt_list[evt_i] == NULL)
2952 			goto out_enomem;
2953 		evt_i++;
2954 	}
2955 
2956 	if (!evt_num_known) {
2957 		evt_num_known = true;
2958 		goto restart;
2959 	}
2960 	qsort(evt_list, evt_num, sizeof(char *), cmp_string);
2961 	evt_i = 0;
2962 	while (evt_i < evt_num) {
2963 		if (name_only) {
2964 			printf("%s ", evt_list[evt_i++]);
2965 			continue;
2966 		}
2967 		printf("  %-50s [%s]\n", evt_list[evt_i++], event_type_descriptors[type]);
2968 	}
2969 	if (evt_num && pager_in_use())
2970 		printf("\n");
2971 
2972 out_free:
2973 	evt_num = evt_i;
2974 	for (evt_i = 0; evt_i < evt_num; evt_i++)
2975 		zfree(&evt_list[evt_i]);
2976 	zfree(&evt_list);
2977 	return;
2978 
2979 out_enomem:
2980 	printf("FATAL: not enough memory to print %s\n", event_type_descriptors[type]);
2981 	if (evt_list)
2982 		goto out_free;
2983 }
2984 
2985 /*
2986  * Print the help text for the event symbols:
2987  */
2988 void print_events(const char *event_glob, bool name_only, bool quiet_flag,
2989 			bool long_desc, bool details_flag, bool deprecated)
2990 {
2991 	print_symbol_events(event_glob, PERF_TYPE_HARDWARE,
2992 			    event_symbols_hw, PERF_COUNT_HW_MAX, name_only);
2993 
2994 	print_symbol_events(event_glob, PERF_TYPE_SOFTWARE,
2995 			    event_symbols_sw, PERF_COUNT_SW_MAX, name_only);
2996 	print_tool_events(event_glob, name_only);
2997 
2998 	print_hwcache_events(event_glob, name_only);
2999 
3000 	print_pmu_events(event_glob, name_only, quiet_flag, long_desc,
3001 			details_flag, deprecated);
3002 
3003 	if (event_glob != NULL)
3004 		return;
3005 
3006 	if (!name_only) {
3007 		printf("  %-50s [%s]\n",
3008 		       "rNNN",
3009 		       event_type_descriptors[PERF_TYPE_RAW]);
3010 		printf("  %-50s [%s]\n",
3011 		       "cpu/t1=v1[,t2=v2,t3 ...]/modifier",
3012 		       event_type_descriptors[PERF_TYPE_RAW]);
3013 		if (pager_in_use())
3014 			printf("   (see 'man perf-list' on how to encode it)\n\n");
3015 
3016 		printf("  %-50s [%s]\n",
3017 		       "mem:<addr>[/len][:access]",
3018 			event_type_descriptors[PERF_TYPE_BREAKPOINT]);
3019 		if (pager_in_use())
3020 			printf("\n");
3021 	}
3022 
3023 	print_tracepoint_events(NULL, NULL, name_only);
3024 
3025 	print_sdt_events(NULL, NULL, name_only);
3026 
3027 	metricgroup__print(true, true, NULL, name_only, details_flag);
3028 
3029 	print_libpfm_events(name_only, long_desc);
3030 }
3031 
3032 int parse_events__is_hardcoded_term(struct parse_events_term *term)
3033 {
3034 	return term->type_term != PARSE_EVENTS__TERM_TYPE_USER;
3035 }
3036 
3037 static int new_term(struct parse_events_term **_term,
3038 		    struct parse_events_term *temp,
3039 		    char *str, u64 num)
3040 {
3041 	struct parse_events_term *term;
3042 
3043 	term = malloc(sizeof(*term));
3044 	if (!term)
3045 		return -ENOMEM;
3046 
3047 	*term = *temp;
3048 	INIT_LIST_HEAD(&term->list);
3049 	term->weak = false;
3050 
3051 	switch (term->type_val) {
3052 	case PARSE_EVENTS__TERM_TYPE_NUM:
3053 		term->val.num = num;
3054 		break;
3055 	case PARSE_EVENTS__TERM_TYPE_STR:
3056 		term->val.str = str;
3057 		break;
3058 	default:
3059 		free(term);
3060 		return -EINVAL;
3061 	}
3062 
3063 	*_term = term;
3064 	return 0;
3065 }
3066 
3067 int parse_events_term__num(struct parse_events_term **term,
3068 			   int type_term, char *config, u64 num,
3069 			   bool no_value,
3070 			   void *loc_term_, void *loc_val_)
3071 {
3072 	YYLTYPE *loc_term = loc_term_;
3073 	YYLTYPE *loc_val = loc_val_;
3074 
3075 	struct parse_events_term temp = {
3076 		.type_val  = PARSE_EVENTS__TERM_TYPE_NUM,
3077 		.type_term = type_term,
3078 		.config    = config,
3079 		.no_value  = no_value,
3080 		.err_term  = loc_term ? loc_term->first_column : 0,
3081 		.err_val   = loc_val  ? loc_val->first_column  : 0,
3082 	};
3083 
3084 	return new_term(term, &temp, NULL, num);
3085 }
3086 
3087 int parse_events_term__str(struct parse_events_term **term,
3088 			   int type_term, char *config, char *str,
3089 			   void *loc_term_, void *loc_val_)
3090 {
3091 	YYLTYPE *loc_term = loc_term_;
3092 	YYLTYPE *loc_val = loc_val_;
3093 
3094 	struct parse_events_term temp = {
3095 		.type_val  = PARSE_EVENTS__TERM_TYPE_STR,
3096 		.type_term = type_term,
3097 		.config    = config,
3098 		.err_term  = loc_term ? loc_term->first_column : 0,
3099 		.err_val   = loc_val  ? loc_val->first_column  : 0,
3100 	};
3101 
3102 	return new_term(term, &temp, str, 0);
3103 }
3104 
3105 int parse_events_term__sym_hw(struct parse_events_term **term,
3106 			      char *config, unsigned idx)
3107 {
3108 	struct event_symbol *sym;
3109 	char *str;
3110 	struct parse_events_term temp = {
3111 		.type_val  = PARSE_EVENTS__TERM_TYPE_STR,
3112 		.type_term = PARSE_EVENTS__TERM_TYPE_USER,
3113 		.config    = config,
3114 	};
3115 
3116 	if (!temp.config) {
3117 		temp.config = strdup("event");
3118 		if (!temp.config)
3119 			return -ENOMEM;
3120 	}
3121 	BUG_ON(idx >= PERF_COUNT_HW_MAX);
3122 	sym = &event_symbols_hw[idx];
3123 
3124 	str = strdup(sym->symbol);
3125 	if (!str)
3126 		return -ENOMEM;
3127 	return new_term(term, &temp, str, 0);
3128 }
3129 
3130 int parse_events_term__clone(struct parse_events_term **new,
3131 			     struct parse_events_term *term)
3132 {
3133 	char *str;
3134 	struct parse_events_term temp = {
3135 		.type_val  = term->type_val,
3136 		.type_term = term->type_term,
3137 		.config    = NULL,
3138 		.err_term  = term->err_term,
3139 		.err_val   = term->err_val,
3140 	};
3141 
3142 	if (term->config) {
3143 		temp.config = strdup(term->config);
3144 		if (!temp.config)
3145 			return -ENOMEM;
3146 	}
3147 	if (term->type_val == PARSE_EVENTS__TERM_TYPE_NUM)
3148 		return new_term(new, &temp, NULL, term->val.num);
3149 
3150 	str = strdup(term->val.str);
3151 	if (!str)
3152 		return -ENOMEM;
3153 	return new_term(new, &temp, str, 0);
3154 }
3155 
3156 void parse_events_term__delete(struct parse_events_term *term)
3157 {
3158 	if (term->array.nr_ranges)
3159 		zfree(&term->array.ranges);
3160 
3161 	if (term->type_val != PARSE_EVENTS__TERM_TYPE_NUM)
3162 		zfree(&term->val.str);
3163 
3164 	zfree(&term->config);
3165 	free(term);
3166 }
3167 
3168 int parse_events_copy_term_list(struct list_head *old,
3169 				 struct list_head **new)
3170 {
3171 	struct parse_events_term *term, *n;
3172 	int ret;
3173 
3174 	if (!old) {
3175 		*new = NULL;
3176 		return 0;
3177 	}
3178 
3179 	*new = malloc(sizeof(struct list_head));
3180 	if (!*new)
3181 		return -ENOMEM;
3182 	INIT_LIST_HEAD(*new);
3183 
3184 	list_for_each_entry (term, old, list) {
3185 		ret = parse_events_term__clone(&n, term);
3186 		if (ret)
3187 			return ret;
3188 		list_add_tail(&n->list, *new);
3189 	}
3190 	return 0;
3191 }
3192 
3193 void parse_events_terms__purge(struct list_head *terms)
3194 {
3195 	struct parse_events_term *term, *h;
3196 
3197 	list_for_each_entry_safe(term, h, terms, list) {
3198 		list_del_init(&term->list);
3199 		parse_events_term__delete(term);
3200 	}
3201 }
3202 
3203 void parse_events_terms__delete(struct list_head *terms)
3204 {
3205 	if (!terms)
3206 		return;
3207 	parse_events_terms__purge(terms);
3208 	free(terms);
3209 }
3210 
3211 void parse_events__clear_array(struct parse_events_array *a)
3212 {
3213 	zfree(&a->ranges);
3214 }
3215 
3216 void parse_events_evlist_error(struct parse_events_state *parse_state,
3217 			       int idx, const char *str)
3218 {
3219 	if (!parse_state->error)
3220 		return;
3221 
3222 	parse_events__handle_error(parse_state->error, idx, strdup(str), NULL);
3223 }
3224 
3225 static void config_terms_list(char *buf, size_t buf_sz)
3226 {
3227 	int i;
3228 	bool first = true;
3229 
3230 	buf[0] = '\0';
3231 	for (i = 0; i < __PARSE_EVENTS__TERM_TYPE_NR; i++) {
3232 		const char *name = config_term_names[i];
3233 
3234 		if (!config_term_avail(i, NULL))
3235 			continue;
3236 		if (!name)
3237 			continue;
3238 		if (name[0] == '<')
3239 			continue;
3240 
3241 		if (strlen(buf) + strlen(name) + 2 >= buf_sz)
3242 			return;
3243 
3244 		if (!first)
3245 			strcat(buf, ",");
3246 		else
3247 			first = false;
3248 		strcat(buf, name);
3249 	}
3250 }
3251 
3252 /*
3253  * Return string contains valid config terms of an event.
3254  * @additional_terms: For terms such as PMU sysfs terms.
3255  */
3256 char *parse_events_formats_error_string(char *additional_terms)
3257 {
3258 	char *str;
3259 	/* "no-overwrite" is the longest name */
3260 	char static_terms[__PARSE_EVENTS__TERM_TYPE_NR *
3261 			  (sizeof("no-overwrite") - 1)];
3262 
3263 	config_terms_list(static_terms, sizeof(static_terms));
3264 	/* valid terms */
3265 	if (additional_terms) {
3266 		if (asprintf(&str, "valid terms: %s,%s",
3267 			     additional_terms, static_terms) < 0)
3268 			goto fail;
3269 	} else {
3270 		if (asprintf(&str, "valid terms: %s", static_terms) < 0)
3271 			goto fail;
3272 	}
3273 	return str;
3274 
3275 fail:
3276 	return NULL;
3277 }
3278 
3279 struct evsel *parse_events__add_event_hybrid(struct list_head *list, int *idx,
3280 					     struct perf_event_attr *attr,
3281 					     char *name, struct perf_pmu *pmu,
3282 					     struct list_head *config_terms)
3283 {
3284 	return __add_event(list, idx, attr, true, name, pmu,
3285 			   config_terms, false, NULL);
3286 }
3287