xref: /linux/tools/perf/util/parse-events.c (revision e04e2b760ddbe3d7b283a05898c3a029085cd8cd)
1 // SPDX-License-Identifier: GPL-2.0
2 #include <linux/hw_breakpoint.h>
3 #include <linux/err.h>
4 #include <linux/list_sort.h>
5 #include <linux/zalloc.h>
6 #include <dirent.h>
7 #include <errno.h>
8 #include <sys/ioctl.h>
9 #include <sys/param.h>
10 #include "term.h"
11 #include "evlist.h"
12 #include "evsel.h"
13 #include <subcmd/parse-options.h>
14 #include "parse-events.h"
15 #include "string2.h"
16 #include "strbuf.h"
17 #include "debug.h"
18 #include <api/fs/tracing_path.h>
19 #include <perf/cpumap.h>
20 #include <util/parse-events-bison.h>
21 #include <util/parse-events-flex.h>
22 #include "pmu.h"
23 #include "pmus.h"
24 #include "asm/bug.h"
25 #include "util/parse-branch-options.h"
26 #include "util/evsel_config.h"
27 #include "util/event.h"
28 #include "util/bpf-filter.h"
29 #include "util/util.h"
30 #include "tracepoint.h"
31 
32 #define MAX_NAME_LEN 100
33 
34 static int get_config_terms(const struct parse_events_terms *head_config,
35 			    struct list_head *head_terms);
36 static int parse_events_terms__copy(const struct parse_events_terms *src,
37 				    struct parse_events_terms *dest);
38 
39 const struct event_symbol event_symbols_hw[PERF_COUNT_HW_MAX] = {
40 	[PERF_COUNT_HW_CPU_CYCLES] = {
41 		.symbol = "cpu-cycles",
42 		.alias  = "cycles",
43 	},
44 	[PERF_COUNT_HW_INSTRUCTIONS] = {
45 		.symbol = "instructions",
46 		.alias  = "",
47 	},
48 	[PERF_COUNT_HW_CACHE_REFERENCES] = {
49 		.symbol = "cache-references",
50 		.alias  = "",
51 	},
52 	[PERF_COUNT_HW_CACHE_MISSES] = {
53 		.symbol = "cache-misses",
54 		.alias  = "",
55 	},
56 	[PERF_COUNT_HW_BRANCH_INSTRUCTIONS] = {
57 		.symbol = "branch-instructions",
58 		.alias  = "branches",
59 	},
60 	[PERF_COUNT_HW_BRANCH_MISSES] = {
61 		.symbol = "branch-misses",
62 		.alias  = "",
63 	},
64 	[PERF_COUNT_HW_BUS_CYCLES] = {
65 		.symbol = "bus-cycles",
66 		.alias  = "",
67 	},
68 	[PERF_COUNT_HW_STALLED_CYCLES_FRONTEND] = {
69 		.symbol = "stalled-cycles-frontend",
70 		.alias  = "idle-cycles-frontend",
71 	},
72 	[PERF_COUNT_HW_STALLED_CYCLES_BACKEND] = {
73 		.symbol = "stalled-cycles-backend",
74 		.alias  = "idle-cycles-backend",
75 	},
76 	[PERF_COUNT_HW_REF_CPU_CYCLES] = {
77 		.symbol = "ref-cycles",
78 		.alias  = "",
79 	},
80 };
81 
82 const struct event_symbol event_symbols_sw[PERF_COUNT_SW_MAX] = {
83 	[PERF_COUNT_SW_CPU_CLOCK] = {
84 		.symbol = "cpu-clock",
85 		.alias  = "",
86 	},
87 	[PERF_COUNT_SW_TASK_CLOCK] = {
88 		.symbol = "task-clock",
89 		.alias  = "",
90 	},
91 	[PERF_COUNT_SW_PAGE_FAULTS] = {
92 		.symbol = "page-faults",
93 		.alias  = "faults",
94 	},
95 	[PERF_COUNT_SW_CONTEXT_SWITCHES] = {
96 		.symbol = "context-switches",
97 		.alias  = "cs",
98 	},
99 	[PERF_COUNT_SW_CPU_MIGRATIONS] = {
100 		.symbol = "cpu-migrations",
101 		.alias  = "migrations",
102 	},
103 	[PERF_COUNT_SW_PAGE_FAULTS_MIN] = {
104 		.symbol = "minor-faults",
105 		.alias  = "",
106 	},
107 	[PERF_COUNT_SW_PAGE_FAULTS_MAJ] = {
108 		.symbol = "major-faults",
109 		.alias  = "",
110 	},
111 	[PERF_COUNT_SW_ALIGNMENT_FAULTS] = {
112 		.symbol = "alignment-faults",
113 		.alias  = "",
114 	},
115 	[PERF_COUNT_SW_EMULATION_FAULTS] = {
116 		.symbol = "emulation-faults",
117 		.alias  = "",
118 	},
119 	[PERF_COUNT_SW_DUMMY] = {
120 		.symbol = "dummy",
121 		.alias  = "",
122 	},
123 	[PERF_COUNT_SW_BPF_OUTPUT] = {
124 		.symbol = "bpf-output",
125 		.alias  = "",
126 	},
127 	[PERF_COUNT_SW_CGROUP_SWITCHES] = {
128 		.symbol = "cgroup-switches",
129 		.alias  = "",
130 	},
131 };
132 
133 const char *event_type(int type)
134 {
135 	switch (type) {
136 	case PERF_TYPE_HARDWARE:
137 		return "hardware";
138 
139 	case PERF_TYPE_SOFTWARE:
140 		return "software";
141 
142 	case PERF_TYPE_TRACEPOINT:
143 		return "tracepoint";
144 
145 	case PERF_TYPE_HW_CACHE:
146 		return "hardware-cache";
147 
148 	default:
149 		break;
150 	}
151 
152 	return "unknown";
153 }
154 
155 static char *get_config_str(const struct parse_events_terms *head_terms,
156 			    enum parse_events__term_type type_term)
157 {
158 	struct parse_events_term *term;
159 
160 	if (!head_terms)
161 		return NULL;
162 
163 	list_for_each_entry(term, &head_terms->terms, list)
164 		if (term->type_term == type_term)
165 			return term->val.str;
166 
167 	return NULL;
168 }
169 
170 static char *get_config_metric_id(const struct parse_events_terms *head_terms)
171 {
172 	return get_config_str(head_terms, PARSE_EVENTS__TERM_TYPE_METRIC_ID);
173 }
174 
175 static char *get_config_name(const struct parse_events_terms *head_terms)
176 {
177 	return get_config_str(head_terms, PARSE_EVENTS__TERM_TYPE_NAME);
178 }
179 
180 /**
181  * fix_raw - For each raw term see if there is an event (aka alias) in pmu that
182  *           matches the raw's string value. If the string value matches an
183  *           event then change the term to be an event, if not then change it to
184  *           be a config term. For example, "read" may be an event of the PMU or
185  *           a raw hex encoding of 0xead. The fix-up is done late so the PMU of
186  *           the event can be determined and we don't need to scan all PMUs
187  *           ahead-of-time.
188  * @config_terms: the list of terms that may contain a raw term.
189  * @pmu: the PMU to scan for events from.
190  */
191 static void fix_raw(struct parse_events_terms *config_terms, struct perf_pmu *pmu)
192 {
193 	struct parse_events_term *term;
194 
195 	list_for_each_entry(term, &config_terms->terms, list) {
196 		u64 num;
197 
198 		if (term->type_term != PARSE_EVENTS__TERM_TYPE_RAW)
199 			continue;
200 
201 		if (perf_pmu__have_event(pmu, term->val.str)) {
202 			zfree(&term->config);
203 			term->config = term->val.str;
204 			term->type_val = PARSE_EVENTS__TERM_TYPE_NUM;
205 			term->type_term = PARSE_EVENTS__TERM_TYPE_USER;
206 			term->val.num = 1;
207 			term->no_value = true;
208 			continue;
209 		}
210 
211 		zfree(&term->config);
212 		term->config = strdup("config");
213 		errno = 0;
214 		num = strtoull(term->val.str + 1, NULL, 16);
215 		assert(errno == 0);
216 		free(term->val.str);
217 		term->type_val = PARSE_EVENTS__TERM_TYPE_NUM;
218 		term->type_term = PARSE_EVENTS__TERM_TYPE_CONFIG;
219 		term->val.num = num;
220 		term->no_value = false;
221 	}
222 }
223 
224 static struct evsel *
225 __add_event(struct list_head *list, int *idx,
226 	    struct perf_event_attr *attr,
227 	    bool init_attr,
228 	    const char *name, const char *metric_id, struct perf_pmu *pmu,
229 	    struct list_head *config_terms, bool auto_merge_stats,
230 	    const char *cpu_list)
231 {
232 	struct evsel *evsel;
233 	struct perf_cpu_map *cpus = pmu ? perf_cpu_map__get(pmu->cpus) :
234 			       cpu_list ? perf_cpu_map__new(cpu_list) : NULL;
235 
236 	if (pmu)
237 		perf_pmu__warn_invalid_formats(pmu);
238 
239 	if (pmu && (attr->type == PERF_TYPE_RAW || attr->type >= PERF_TYPE_MAX)) {
240 		perf_pmu__warn_invalid_config(pmu, attr->config, name,
241 					      PERF_PMU_FORMAT_VALUE_CONFIG, "config");
242 		perf_pmu__warn_invalid_config(pmu, attr->config1, name,
243 					      PERF_PMU_FORMAT_VALUE_CONFIG1, "config1");
244 		perf_pmu__warn_invalid_config(pmu, attr->config2, name,
245 					      PERF_PMU_FORMAT_VALUE_CONFIG2, "config2");
246 		perf_pmu__warn_invalid_config(pmu, attr->config3, name,
247 					      PERF_PMU_FORMAT_VALUE_CONFIG3, "config3");
248 	}
249 	if (init_attr)
250 		event_attr_init(attr);
251 
252 	evsel = evsel__new_idx(attr, *idx);
253 	if (!evsel) {
254 		perf_cpu_map__put(cpus);
255 		return NULL;
256 	}
257 
258 	(*idx)++;
259 	evsel->core.cpus = cpus;
260 	evsel->core.own_cpus = perf_cpu_map__get(cpus);
261 	evsel->core.requires_cpu = pmu ? pmu->is_uncore : false;
262 	evsel->core.is_pmu_core = pmu ? pmu->is_core : false;
263 	evsel->auto_merge_stats = auto_merge_stats;
264 	evsel->pmu = pmu;
265 	evsel->pmu_name = pmu ? strdup(pmu->name) : NULL;
266 
267 	if (name)
268 		evsel->name = strdup(name);
269 
270 	if (metric_id)
271 		evsel->metric_id = strdup(metric_id);
272 
273 	if (config_terms)
274 		list_splice_init(config_terms, &evsel->config_terms);
275 
276 	if (list)
277 		list_add_tail(&evsel->core.node, list);
278 
279 	return evsel;
280 }
281 
282 struct evsel *parse_events__add_event(int idx, struct perf_event_attr *attr,
283 				      const char *name, const char *metric_id,
284 				      struct perf_pmu *pmu)
285 {
286 	return __add_event(/*list=*/NULL, &idx, attr, /*init_attr=*/false, name,
287 			   metric_id, pmu, /*config_terms=*/NULL,
288 			   /*auto_merge_stats=*/false, /*cpu_list=*/NULL);
289 }
290 
291 static int add_event(struct list_head *list, int *idx,
292 		     struct perf_event_attr *attr, const char *name,
293 		     const char *metric_id, struct list_head *config_terms)
294 {
295 	return __add_event(list, idx, attr, /*init_attr*/true, name, metric_id,
296 			   /*pmu=*/NULL, config_terms,
297 			   /*auto_merge_stats=*/false, /*cpu_list=*/NULL) ? 0 : -ENOMEM;
298 }
299 
300 static int add_event_tool(struct list_head *list, int *idx,
301 			  enum perf_tool_event tool_event)
302 {
303 	struct evsel *evsel;
304 	struct perf_event_attr attr = {
305 		.type = PERF_TYPE_SOFTWARE,
306 		.config = PERF_COUNT_SW_DUMMY,
307 	};
308 	const char *cpu_list = NULL;
309 
310 	if (tool_event == PERF_TOOL_DURATION_TIME) {
311 		/* Duration time is gathered globally, pretend it is only on CPU0. */
312 		cpu_list = "0";
313 	}
314 	evsel = __add_event(list, idx, &attr, /*init_attr=*/true, /*name=*/NULL,
315 			    /*metric_id=*/NULL, /*pmu=*/NULL,
316 			    /*config_terms=*/NULL, /*auto_merge_stats=*/false,
317 			    cpu_list);
318 	if (!evsel)
319 		return -ENOMEM;
320 	evsel->tool_event = tool_event;
321 	if (tool_event == PERF_TOOL_DURATION_TIME
322 	    || tool_event == PERF_TOOL_USER_TIME
323 	    || tool_event == PERF_TOOL_SYSTEM_TIME) {
324 		free((char *)evsel->unit);
325 		evsel->unit = strdup("ns");
326 	}
327 	return 0;
328 }
329 
330 /**
331  * parse_aliases - search names for entries beginning or equalling str ignoring
332  *                 case. If mutliple entries in names match str then the longest
333  *                 is chosen.
334  * @str: The needle to look for.
335  * @names: The haystack to search.
336  * @size: The size of the haystack.
337  * @longest: Out argument giving the length of the matching entry.
338  */
339 static int parse_aliases(const char *str, const char *const names[][EVSEL__MAX_ALIASES], int size,
340 			 int *longest)
341 {
342 	*longest = -1;
343 	for (int i = 0; i < size; i++) {
344 		for (int j = 0; j < EVSEL__MAX_ALIASES && names[i][j]; j++) {
345 			int n = strlen(names[i][j]);
346 
347 			if (n > *longest && !strncasecmp(str, names[i][j], n))
348 				*longest = n;
349 		}
350 		if (*longest > 0)
351 			return i;
352 	}
353 
354 	return -1;
355 }
356 
357 typedef int config_term_func_t(struct perf_event_attr *attr,
358 			       struct parse_events_term *term,
359 			       struct parse_events_error *err);
360 static int config_term_common(struct perf_event_attr *attr,
361 			      struct parse_events_term *term,
362 			      struct parse_events_error *err);
363 static int config_attr(struct perf_event_attr *attr,
364 		       const struct parse_events_terms *head,
365 		       struct parse_events_error *err,
366 		       config_term_func_t config_term);
367 
368 /**
369  * parse_events__decode_legacy_cache - Search name for the legacy cache event
370  *                                     name composed of 1, 2 or 3 hyphen
371  *                                     separated sections. The first section is
372  *                                     the cache type while the others are the
373  *                                     optional op and optional result. To make
374  *                                     life hard the names in the table also
375  *                                     contain hyphens and the longest name
376  *                                     should always be selected.
377  */
378 int parse_events__decode_legacy_cache(const char *name, int extended_pmu_type, __u64 *config)
379 {
380 	int len, cache_type = -1, cache_op = -1, cache_result = -1;
381 	const char *name_end = &name[strlen(name) + 1];
382 	const char *str = name;
383 
384 	cache_type = parse_aliases(str, evsel__hw_cache, PERF_COUNT_HW_CACHE_MAX, &len);
385 	if (cache_type == -1)
386 		return -EINVAL;
387 	str += len + 1;
388 
389 	if (str < name_end) {
390 		cache_op = parse_aliases(str, evsel__hw_cache_op,
391 					PERF_COUNT_HW_CACHE_OP_MAX, &len);
392 		if (cache_op >= 0) {
393 			if (!evsel__is_cache_op_valid(cache_type, cache_op))
394 				return -EINVAL;
395 			str += len + 1;
396 		} else {
397 			cache_result = parse_aliases(str, evsel__hw_cache_result,
398 						PERF_COUNT_HW_CACHE_RESULT_MAX, &len);
399 			if (cache_result >= 0)
400 				str += len + 1;
401 		}
402 	}
403 	if (str < name_end) {
404 		if (cache_op < 0) {
405 			cache_op = parse_aliases(str, evsel__hw_cache_op,
406 						PERF_COUNT_HW_CACHE_OP_MAX, &len);
407 			if (cache_op >= 0) {
408 				if (!evsel__is_cache_op_valid(cache_type, cache_op))
409 					return -EINVAL;
410 			}
411 		} else if (cache_result < 0) {
412 			cache_result = parse_aliases(str, evsel__hw_cache_result,
413 						PERF_COUNT_HW_CACHE_RESULT_MAX, &len);
414 		}
415 	}
416 
417 	/*
418 	 * Fall back to reads:
419 	 */
420 	if (cache_op == -1)
421 		cache_op = PERF_COUNT_HW_CACHE_OP_READ;
422 
423 	/*
424 	 * Fall back to accesses:
425 	 */
426 	if (cache_result == -1)
427 		cache_result = PERF_COUNT_HW_CACHE_RESULT_ACCESS;
428 
429 	*config = cache_type | (cache_op << 8) | (cache_result << 16);
430 	if (perf_pmus__supports_extended_type())
431 		*config |= (__u64)extended_pmu_type << PERF_PMU_TYPE_SHIFT;
432 	return 0;
433 }
434 
435 /**
436  * parse_events__filter_pmu - returns false if a wildcard PMU should be
437  *                            considered, true if it should be filtered.
438  */
439 bool parse_events__filter_pmu(const struct parse_events_state *parse_state,
440 			      const struct perf_pmu *pmu)
441 {
442 	if (parse_state->pmu_filter == NULL)
443 		return false;
444 
445 	return strcmp(parse_state->pmu_filter, pmu->name) != 0;
446 }
447 
448 static int parse_events_add_pmu(struct parse_events_state *parse_state,
449 				struct list_head *list, struct perf_pmu *pmu,
450 				const struct parse_events_terms *const_parsed_terms,
451 				bool auto_merge_stats);
452 
453 int parse_events_add_cache(struct list_head *list, int *idx, const char *name,
454 			   struct parse_events_state *parse_state,
455 			   struct parse_events_terms *parsed_terms)
456 {
457 	struct perf_pmu *pmu = NULL;
458 	bool found_supported = false;
459 	const char *config_name = get_config_name(parsed_terms);
460 	const char *metric_id = get_config_metric_id(parsed_terms);
461 
462 	while ((pmu = perf_pmus__scan(pmu)) != NULL) {
463 		LIST_HEAD(config_terms);
464 		struct perf_event_attr attr;
465 		int ret;
466 
467 		if (parse_events__filter_pmu(parse_state, pmu))
468 			continue;
469 
470 		if (perf_pmu__have_event(pmu, name)) {
471 			/*
472 			 * The PMU has the event so add as not a legacy cache
473 			 * event.
474 			 */
475 			ret = parse_events_add_pmu(parse_state, list, pmu,
476 						   parsed_terms,
477 						   perf_pmu__auto_merge_stats(pmu));
478 			if (ret)
479 				return ret;
480 			continue;
481 		}
482 
483 		if (!pmu->is_core) {
484 			/* Legacy cache events are only supported by core PMUs. */
485 			continue;
486 		}
487 
488 		memset(&attr, 0, sizeof(attr));
489 		attr.type = PERF_TYPE_HW_CACHE;
490 
491 		ret = parse_events__decode_legacy_cache(name, pmu->type, &attr.config);
492 		if (ret)
493 			return ret;
494 
495 		found_supported = true;
496 
497 		if (parsed_terms) {
498 			if (config_attr(&attr, parsed_terms, parse_state->error,
499 					config_term_common))
500 				return -EINVAL;
501 
502 			if (get_config_terms(parsed_terms, &config_terms))
503 				return -ENOMEM;
504 		}
505 
506 		if (__add_event(list, idx, &attr, /*init_attr*/true, config_name ?: name,
507 				metric_id, pmu, &config_terms, /*auto_merge_stats=*/false,
508 				/*cpu_list=*/NULL) == NULL)
509 			return -ENOMEM;
510 
511 		free_config_terms(&config_terms);
512 	}
513 	return found_supported ? 0 : -EINVAL;
514 }
515 
516 #ifdef HAVE_LIBTRACEEVENT
517 static void tracepoint_error(struct parse_events_error *e, int err,
518 			     const char *sys, const char *name, int column)
519 {
520 	const char *str;
521 	char help[BUFSIZ];
522 
523 	if (!e)
524 		return;
525 
526 	/*
527 	 * We get error directly from syscall errno ( > 0),
528 	 * or from encoded pointer's error ( < 0).
529 	 */
530 	err = abs(err);
531 
532 	switch (err) {
533 	case EACCES:
534 		str = "can't access trace events";
535 		break;
536 	case ENOENT:
537 		str = "unknown tracepoint";
538 		break;
539 	default:
540 		str = "failed to add tracepoint";
541 		break;
542 	}
543 
544 	tracing_path__strerror_open_tp(err, help, sizeof(help), sys, name);
545 	parse_events_error__handle(e, column, strdup(str), strdup(help));
546 }
547 
548 static int add_tracepoint(struct parse_events_state *parse_state,
549 			  struct list_head *list,
550 			  const char *sys_name, const char *evt_name,
551 			  struct parse_events_error *err,
552 			  struct parse_events_terms *head_config, void *loc_)
553 {
554 	YYLTYPE *loc = loc_;
555 	struct evsel *evsel = evsel__newtp_idx(sys_name, evt_name, parse_state->idx++,
556 					       !parse_state->fake_tp);
557 
558 	if (IS_ERR(evsel)) {
559 		tracepoint_error(err, PTR_ERR(evsel), sys_name, evt_name, loc->first_column);
560 		return PTR_ERR(evsel);
561 	}
562 
563 	if (head_config) {
564 		LIST_HEAD(config_terms);
565 
566 		if (get_config_terms(head_config, &config_terms))
567 			return -ENOMEM;
568 		list_splice(&config_terms, &evsel->config_terms);
569 	}
570 
571 	list_add_tail(&evsel->core.node, list);
572 	return 0;
573 }
574 
575 static int add_tracepoint_multi_event(struct parse_events_state *parse_state,
576 				      struct list_head *list,
577 				      const char *sys_name, const char *evt_name,
578 				      struct parse_events_error *err,
579 				      struct parse_events_terms *head_config, YYLTYPE *loc)
580 {
581 	char *evt_path;
582 	struct dirent *evt_ent;
583 	DIR *evt_dir;
584 	int ret = 0, found = 0;
585 
586 	evt_path = get_events_file(sys_name);
587 	if (!evt_path) {
588 		tracepoint_error(err, errno, sys_name, evt_name, loc->first_column);
589 		return -1;
590 	}
591 	evt_dir = opendir(evt_path);
592 	if (!evt_dir) {
593 		put_events_file(evt_path);
594 		tracepoint_error(err, errno, sys_name, evt_name, loc->first_column);
595 		return -1;
596 	}
597 
598 	while (!ret && (evt_ent = readdir(evt_dir))) {
599 		if (!strcmp(evt_ent->d_name, ".")
600 		    || !strcmp(evt_ent->d_name, "..")
601 		    || !strcmp(evt_ent->d_name, "enable")
602 		    || !strcmp(evt_ent->d_name, "filter"))
603 			continue;
604 
605 		if (!strglobmatch(evt_ent->d_name, evt_name))
606 			continue;
607 
608 		found++;
609 
610 		ret = add_tracepoint(parse_state, list, sys_name, evt_ent->d_name,
611 				     err, head_config, loc);
612 	}
613 
614 	if (!found) {
615 		tracepoint_error(err, ENOENT, sys_name, evt_name, loc->first_column);
616 		ret = -1;
617 	}
618 
619 	put_events_file(evt_path);
620 	closedir(evt_dir);
621 	return ret;
622 }
623 
624 static int add_tracepoint_event(struct parse_events_state *parse_state,
625 				struct list_head *list,
626 				const char *sys_name, const char *evt_name,
627 				struct parse_events_error *err,
628 				struct parse_events_terms *head_config, YYLTYPE *loc)
629 {
630 	return strpbrk(evt_name, "*?") ?
631 		add_tracepoint_multi_event(parse_state, list, sys_name, evt_name,
632 					   err, head_config, loc) :
633 		add_tracepoint(parse_state, list, sys_name, evt_name,
634 			       err, head_config, loc);
635 }
636 
637 static int add_tracepoint_multi_sys(struct parse_events_state *parse_state,
638 				    struct list_head *list,
639 				    const char *sys_name, const char *evt_name,
640 				    struct parse_events_error *err,
641 				    struct parse_events_terms *head_config, YYLTYPE *loc)
642 {
643 	struct dirent *events_ent;
644 	DIR *events_dir;
645 	int ret = 0;
646 
647 	events_dir = tracing_events__opendir();
648 	if (!events_dir) {
649 		tracepoint_error(err, errno, sys_name, evt_name, loc->first_column);
650 		return -1;
651 	}
652 
653 	while (!ret && (events_ent = readdir(events_dir))) {
654 		if (!strcmp(events_ent->d_name, ".")
655 		    || !strcmp(events_ent->d_name, "..")
656 		    || !strcmp(events_ent->d_name, "enable")
657 		    || !strcmp(events_ent->d_name, "header_event")
658 		    || !strcmp(events_ent->d_name, "header_page"))
659 			continue;
660 
661 		if (!strglobmatch(events_ent->d_name, sys_name))
662 			continue;
663 
664 		ret = add_tracepoint_event(parse_state, list, events_ent->d_name,
665 					   evt_name, err, head_config, loc);
666 	}
667 
668 	closedir(events_dir);
669 	return ret;
670 }
671 #endif /* HAVE_LIBTRACEEVENT */
672 
673 static int
674 parse_breakpoint_type(const char *type, struct perf_event_attr *attr)
675 {
676 	int i;
677 
678 	for (i = 0; i < 3; i++) {
679 		if (!type || !type[i])
680 			break;
681 
682 #define CHECK_SET_TYPE(bit)		\
683 do {					\
684 	if (attr->bp_type & bit)	\
685 		return -EINVAL;		\
686 	else				\
687 		attr->bp_type |= bit;	\
688 } while (0)
689 
690 		switch (type[i]) {
691 		case 'r':
692 			CHECK_SET_TYPE(HW_BREAKPOINT_R);
693 			break;
694 		case 'w':
695 			CHECK_SET_TYPE(HW_BREAKPOINT_W);
696 			break;
697 		case 'x':
698 			CHECK_SET_TYPE(HW_BREAKPOINT_X);
699 			break;
700 		default:
701 			return -EINVAL;
702 		}
703 	}
704 
705 #undef CHECK_SET_TYPE
706 
707 	if (!attr->bp_type) /* Default */
708 		attr->bp_type = HW_BREAKPOINT_R | HW_BREAKPOINT_W;
709 
710 	return 0;
711 }
712 
713 int parse_events_add_breakpoint(struct parse_events_state *parse_state,
714 				struct list_head *list,
715 				u64 addr, char *type, u64 len,
716 				struct parse_events_terms *head_config)
717 {
718 	struct perf_event_attr attr;
719 	LIST_HEAD(config_terms);
720 	const char *name;
721 
722 	memset(&attr, 0, sizeof(attr));
723 	attr.bp_addr = addr;
724 
725 	if (parse_breakpoint_type(type, &attr))
726 		return -EINVAL;
727 
728 	/* Provide some defaults if len is not specified */
729 	if (!len) {
730 		if (attr.bp_type == HW_BREAKPOINT_X)
731 			len = sizeof(long);
732 		else
733 			len = HW_BREAKPOINT_LEN_4;
734 	}
735 
736 	attr.bp_len = len;
737 
738 	attr.type = PERF_TYPE_BREAKPOINT;
739 	attr.sample_period = 1;
740 
741 	if (head_config) {
742 		if (config_attr(&attr, head_config, parse_state->error,
743 				config_term_common))
744 			return -EINVAL;
745 
746 		if (get_config_terms(head_config, &config_terms))
747 			return -ENOMEM;
748 	}
749 
750 	name = get_config_name(head_config);
751 
752 	return add_event(list, &parse_state->idx, &attr, name, /*mertic_id=*/NULL,
753 			 &config_terms);
754 }
755 
756 static int check_type_val(struct parse_events_term *term,
757 			  struct parse_events_error *err,
758 			  enum parse_events__term_val_type type)
759 {
760 	if (type == term->type_val)
761 		return 0;
762 
763 	if (err) {
764 		parse_events_error__handle(err, term->err_val,
765 					type == PARSE_EVENTS__TERM_TYPE_NUM
766 					? strdup("expected numeric value")
767 					: strdup("expected string value"),
768 					NULL);
769 	}
770 	return -EINVAL;
771 }
772 
773 static bool config_term_shrinked;
774 
775 static const char *config_term_name(enum parse_events__term_type term_type)
776 {
777 	/*
778 	 * Update according to parse-events.l
779 	 */
780 	static const char *config_term_names[__PARSE_EVENTS__TERM_TYPE_NR] = {
781 		[PARSE_EVENTS__TERM_TYPE_USER]			= "<sysfs term>",
782 		[PARSE_EVENTS__TERM_TYPE_CONFIG]		= "config",
783 		[PARSE_EVENTS__TERM_TYPE_CONFIG1]		= "config1",
784 		[PARSE_EVENTS__TERM_TYPE_CONFIG2]		= "config2",
785 		[PARSE_EVENTS__TERM_TYPE_CONFIG3]		= "config3",
786 		[PARSE_EVENTS__TERM_TYPE_NAME]			= "name",
787 		[PARSE_EVENTS__TERM_TYPE_SAMPLE_PERIOD]		= "period",
788 		[PARSE_EVENTS__TERM_TYPE_SAMPLE_FREQ]		= "freq",
789 		[PARSE_EVENTS__TERM_TYPE_BRANCH_SAMPLE_TYPE]	= "branch_type",
790 		[PARSE_EVENTS__TERM_TYPE_TIME]			= "time",
791 		[PARSE_EVENTS__TERM_TYPE_CALLGRAPH]		= "call-graph",
792 		[PARSE_EVENTS__TERM_TYPE_STACKSIZE]		= "stack-size",
793 		[PARSE_EVENTS__TERM_TYPE_NOINHERIT]		= "no-inherit",
794 		[PARSE_EVENTS__TERM_TYPE_INHERIT]		= "inherit",
795 		[PARSE_EVENTS__TERM_TYPE_MAX_STACK]		= "max-stack",
796 		[PARSE_EVENTS__TERM_TYPE_MAX_EVENTS]		= "nr",
797 		[PARSE_EVENTS__TERM_TYPE_OVERWRITE]		= "overwrite",
798 		[PARSE_EVENTS__TERM_TYPE_NOOVERWRITE]		= "no-overwrite",
799 		[PARSE_EVENTS__TERM_TYPE_DRV_CFG]		= "driver-config",
800 		[PARSE_EVENTS__TERM_TYPE_PERCORE]		= "percore",
801 		[PARSE_EVENTS__TERM_TYPE_AUX_OUTPUT]		= "aux-output",
802 		[PARSE_EVENTS__TERM_TYPE_AUX_SAMPLE_SIZE]	= "aux-sample-size",
803 		[PARSE_EVENTS__TERM_TYPE_METRIC_ID]		= "metric-id",
804 		[PARSE_EVENTS__TERM_TYPE_RAW]                   = "raw",
805 		[PARSE_EVENTS__TERM_TYPE_LEGACY_CACHE]          = "legacy-cache",
806 		[PARSE_EVENTS__TERM_TYPE_HARDWARE]              = "hardware",
807 	};
808 	if ((unsigned int)term_type >= __PARSE_EVENTS__TERM_TYPE_NR)
809 		return "unknown term";
810 
811 	return config_term_names[term_type];
812 }
813 
814 static bool
815 config_term_avail(enum parse_events__term_type term_type, struct parse_events_error *err)
816 {
817 	char *err_str;
818 
819 	if (term_type < 0 || term_type >= __PARSE_EVENTS__TERM_TYPE_NR) {
820 		parse_events_error__handle(err, -1,
821 					strdup("Invalid term_type"), NULL);
822 		return false;
823 	}
824 	if (!config_term_shrinked)
825 		return true;
826 
827 	switch (term_type) {
828 	case PARSE_EVENTS__TERM_TYPE_CONFIG:
829 	case PARSE_EVENTS__TERM_TYPE_CONFIG1:
830 	case PARSE_EVENTS__TERM_TYPE_CONFIG2:
831 	case PARSE_EVENTS__TERM_TYPE_CONFIG3:
832 	case PARSE_EVENTS__TERM_TYPE_NAME:
833 	case PARSE_EVENTS__TERM_TYPE_METRIC_ID:
834 	case PARSE_EVENTS__TERM_TYPE_SAMPLE_PERIOD:
835 	case PARSE_EVENTS__TERM_TYPE_PERCORE:
836 		return true;
837 	case PARSE_EVENTS__TERM_TYPE_USER:
838 	case PARSE_EVENTS__TERM_TYPE_SAMPLE_FREQ:
839 	case PARSE_EVENTS__TERM_TYPE_BRANCH_SAMPLE_TYPE:
840 	case PARSE_EVENTS__TERM_TYPE_TIME:
841 	case PARSE_EVENTS__TERM_TYPE_CALLGRAPH:
842 	case PARSE_EVENTS__TERM_TYPE_STACKSIZE:
843 	case PARSE_EVENTS__TERM_TYPE_NOINHERIT:
844 	case PARSE_EVENTS__TERM_TYPE_INHERIT:
845 	case PARSE_EVENTS__TERM_TYPE_MAX_STACK:
846 	case PARSE_EVENTS__TERM_TYPE_MAX_EVENTS:
847 	case PARSE_EVENTS__TERM_TYPE_NOOVERWRITE:
848 	case PARSE_EVENTS__TERM_TYPE_OVERWRITE:
849 	case PARSE_EVENTS__TERM_TYPE_DRV_CFG:
850 	case PARSE_EVENTS__TERM_TYPE_AUX_OUTPUT:
851 	case PARSE_EVENTS__TERM_TYPE_AUX_SAMPLE_SIZE:
852 	case PARSE_EVENTS__TERM_TYPE_RAW:
853 	case PARSE_EVENTS__TERM_TYPE_LEGACY_CACHE:
854 	case PARSE_EVENTS__TERM_TYPE_HARDWARE:
855 	default:
856 		if (!err)
857 			return false;
858 
859 		/* term_type is validated so indexing is safe */
860 		if (asprintf(&err_str, "'%s' is not usable in 'perf stat'",
861 			     config_term_name(term_type)) >= 0)
862 			parse_events_error__handle(err, -1, err_str, NULL);
863 		return false;
864 	}
865 }
866 
867 void parse_events__shrink_config_terms(void)
868 {
869 	config_term_shrinked = true;
870 }
871 
872 static int config_term_common(struct perf_event_attr *attr,
873 			      struct parse_events_term *term,
874 			      struct parse_events_error *err)
875 {
876 #define CHECK_TYPE_VAL(type)						   \
877 do {									   \
878 	if (check_type_val(term, err, PARSE_EVENTS__TERM_TYPE_ ## type)) \
879 		return -EINVAL;						   \
880 } while (0)
881 
882 	switch (term->type_term) {
883 	case PARSE_EVENTS__TERM_TYPE_CONFIG:
884 		CHECK_TYPE_VAL(NUM);
885 		attr->config = term->val.num;
886 		break;
887 	case PARSE_EVENTS__TERM_TYPE_CONFIG1:
888 		CHECK_TYPE_VAL(NUM);
889 		attr->config1 = term->val.num;
890 		break;
891 	case PARSE_EVENTS__TERM_TYPE_CONFIG2:
892 		CHECK_TYPE_VAL(NUM);
893 		attr->config2 = term->val.num;
894 		break;
895 	case PARSE_EVENTS__TERM_TYPE_CONFIG3:
896 		CHECK_TYPE_VAL(NUM);
897 		attr->config3 = term->val.num;
898 		break;
899 	case PARSE_EVENTS__TERM_TYPE_SAMPLE_PERIOD:
900 		CHECK_TYPE_VAL(NUM);
901 		break;
902 	case PARSE_EVENTS__TERM_TYPE_SAMPLE_FREQ:
903 		CHECK_TYPE_VAL(NUM);
904 		break;
905 	case PARSE_EVENTS__TERM_TYPE_BRANCH_SAMPLE_TYPE:
906 		CHECK_TYPE_VAL(STR);
907 		if (strcmp(term->val.str, "no") &&
908 		    parse_branch_str(term->val.str,
909 				    &attr->branch_sample_type)) {
910 			parse_events_error__handle(err, term->err_val,
911 					strdup("invalid branch sample type"),
912 					NULL);
913 			return -EINVAL;
914 		}
915 		break;
916 	case PARSE_EVENTS__TERM_TYPE_TIME:
917 		CHECK_TYPE_VAL(NUM);
918 		if (term->val.num > 1) {
919 			parse_events_error__handle(err, term->err_val,
920 						strdup("expected 0 or 1"),
921 						NULL);
922 			return -EINVAL;
923 		}
924 		break;
925 	case PARSE_EVENTS__TERM_TYPE_CALLGRAPH:
926 		CHECK_TYPE_VAL(STR);
927 		break;
928 	case PARSE_EVENTS__TERM_TYPE_STACKSIZE:
929 		CHECK_TYPE_VAL(NUM);
930 		break;
931 	case PARSE_EVENTS__TERM_TYPE_INHERIT:
932 		CHECK_TYPE_VAL(NUM);
933 		break;
934 	case PARSE_EVENTS__TERM_TYPE_NOINHERIT:
935 		CHECK_TYPE_VAL(NUM);
936 		break;
937 	case PARSE_EVENTS__TERM_TYPE_OVERWRITE:
938 		CHECK_TYPE_VAL(NUM);
939 		break;
940 	case PARSE_EVENTS__TERM_TYPE_NOOVERWRITE:
941 		CHECK_TYPE_VAL(NUM);
942 		break;
943 	case PARSE_EVENTS__TERM_TYPE_NAME:
944 		CHECK_TYPE_VAL(STR);
945 		break;
946 	case PARSE_EVENTS__TERM_TYPE_METRIC_ID:
947 		CHECK_TYPE_VAL(STR);
948 		break;
949 	case PARSE_EVENTS__TERM_TYPE_RAW:
950 		CHECK_TYPE_VAL(STR);
951 		break;
952 	case PARSE_EVENTS__TERM_TYPE_MAX_STACK:
953 		CHECK_TYPE_VAL(NUM);
954 		break;
955 	case PARSE_EVENTS__TERM_TYPE_MAX_EVENTS:
956 		CHECK_TYPE_VAL(NUM);
957 		break;
958 	case PARSE_EVENTS__TERM_TYPE_PERCORE:
959 		CHECK_TYPE_VAL(NUM);
960 		if ((unsigned int)term->val.num > 1) {
961 			parse_events_error__handle(err, term->err_val,
962 						strdup("expected 0 or 1"),
963 						NULL);
964 			return -EINVAL;
965 		}
966 		break;
967 	case PARSE_EVENTS__TERM_TYPE_AUX_OUTPUT:
968 		CHECK_TYPE_VAL(NUM);
969 		break;
970 	case PARSE_EVENTS__TERM_TYPE_AUX_SAMPLE_SIZE:
971 		CHECK_TYPE_VAL(NUM);
972 		if (term->val.num > UINT_MAX) {
973 			parse_events_error__handle(err, term->err_val,
974 						strdup("too big"),
975 						NULL);
976 			return -EINVAL;
977 		}
978 		break;
979 	case PARSE_EVENTS__TERM_TYPE_DRV_CFG:
980 	case PARSE_EVENTS__TERM_TYPE_USER:
981 	case PARSE_EVENTS__TERM_TYPE_LEGACY_CACHE:
982 	case PARSE_EVENTS__TERM_TYPE_HARDWARE:
983 	default:
984 		parse_events_error__handle(err, term->err_term,
985 					strdup(config_term_name(term->type_term)),
986 					parse_events_formats_error_string(NULL));
987 		return -EINVAL;
988 	}
989 
990 	/*
991 	 * Check term availability after basic checking so
992 	 * PARSE_EVENTS__TERM_TYPE_USER can be found and filtered.
993 	 *
994 	 * If check availability at the entry of this function,
995 	 * user will see "'<sysfs term>' is not usable in 'perf stat'"
996 	 * if an invalid config term is provided for legacy events
997 	 * (for example, instructions/badterm/...), which is confusing.
998 	 */
999 	if (!config_term_avail(term->type_term, err))
1000 		return -EINVAL;
1001 	return 0;
1002 #undef CHECK_TYPE_VAL
1003 }
1004 
1005 static int config_term_pmu(struct perf_event_attr *attr,
1006 			   struct parse_events_term *term,
1007 			   struct parse_events_error *err)
1008 {
1009 	if (term->type_term == PARSE_EVENTS__TERM_TYPE_LEGACY_CACHE) {
1010 		struct perf_pmu *pmu = perf_pmus__find_by_type(attr->type);
1011 
1012 		if (!pmu) {
1013 			char *err_str;
1014 
1015 			if (asprintf(&err_str, "Failed to find PMU for type %d", attr->type) >= 0)
1016 				parse_events_error__handle(err, term->err_term,
1017 							   err_str, /*help=*/NULL);
1018 			return -EINVAL;
1019 		}
1020 		/*
1021 		 * Rewrite the PMU event to a legacy cache one unless the PMU
1022 		 * doesn't support legacy cache events or the event is present
1023 		 * within the PMU.
1024 		 */
1025 		if (perf_pmu__supports_legacy_cache(pmu) &&
1026 		    !perf_pmu__have_event(pmu, term->config)) {
1027 			attr->type = PERF_TYPE_HW_CACHE;
1028 			return parse_events__decode_legacy_cache(term->config, pmu->type,
1029 								 &attr->config);
1030 		} else {
1031 			term->type_term = PARSE_EVENTS__TERM_TYPE_USER;
1032 			term->no_value = true;
1033 		}
1034 	}
1035 	if (term->type_term == PARSE_EVENTS__TERM_TYPE_HARDWARE) {
1036 		struct perf_pmu *pmu = perf_pmus__find_by_type(attr->type);
1037 
1038 		if (!pmu) {
1039 			char *err_str;
1040 
1041 			if (asprintf(&err_str, "Failed to find PMU for type %d", attr->type) >= 0)
1042 				parse_events_error__handle(err, term->err_term,
1043 							   err_str, /*help=*/NULL);
1044 			return -EINVAL;
1045 		}
1046 		/*
1047 		 * If the PMU has a sysfs or json event prefer it over
1048 		 * legacy. ARM requires this.
1049 		 */
1050 		if (perf_pmu__have_event(pmu, term->config)) {
1051 			term->type_term = PARSE_EVENTS__TERM_TYPE_USER;
1052 			term->no_value = true;
1053 		} else {
1054 			attr->type = PERF_TYPE_HARDWARE;
1055 			attr->config = term->val.num;
1056 			if (perf_pmus__supports_extended_type())
1057 				attr->config |= (__u64)pmu->type << PERF_PMU_TYPE_SHIFT;
1058 		}
1059 		return 0;
1060 	}
1061 	if (term->type_term == PARSE_EVENTS__TERM_TYPE_USER ||
1062 	    term->type_term == PARSE_EVENTS__TERM_TYPE_DRV_CFG) {
1063 		/*
1064 		 * Always succeed for sysfs terms, as we dont know
1065 		 * at this point what type they need to have.
1066 		 */
1067 		return 0;
1068 	}
1069 	return config_term_common(attr, term, err);
1070 }
1071 
1072 #ifdef HAVE_LIBTRACEEVENT
1073 static int config_term_tracepoint(struct perf_event_attr *attr,
1074 				  struct parse_events_term *term,
1075 				  struct parse_events_error *err)
1076 {
1077 	switch (term->type_term) {
1078 	case PARSE_EVENTS__TERM_TYPE_CALLGRAPH:
1079 	case PARSE_EVENTS__TERM_TYPE_STACKSIZE:
1080 	case PARSE_EVENTS__TERM_TYPE_INHERIT:
1081 	case PARSE_EVENTS__TERM_TYPE_NOINHERIT:
1082 	case PARSE_EVENTS__TERM_TYPE_MAX_STACK:
1083 	case PARSE_EVENTS__TERM_TYPE_MAX_EVENTS:
1084 	case PARSE_EVENTS__TERM_TYPE_OVERWRITE:
1085 	case PARSE_EVENTS__TERM_TYPE_NOOVERWRITE:
1086 	case PARSE_EVENTS__TERM_TYPE_AUX_OUTPUT:
1087 	case PARSE_EVENTS__TERM_TYPE_AUX_SAMPLE_SIZE:
1088 		return config_term_common(attr, term, err);
1089 	case PARSE_EVENTS__TERM_TYPE_USER:
1090 	case PARSE_EVENTS__TERM_TYPE_CONFIG:
1091 	case PARSE_EVENTS__TERM_TYPE_CONFIG1:
1092 	case PARSE_EVENTS__TERM_TYPE_CONFIG2:
1093 	case PARSE_EVENTS__TERM_TYPE_CONFIG3:
1094 	case PARSE_EVENTS__TERM_TYPE_NAME:
1095 	case PARSE_EVENTS__TERM_TYPE_SAMPLE_PERIOD:
1096 	case PARSE_EVENTS__TERM_TYPE_SAMPLE_FREQ:
1097 	case PARSE_EVENTS__TERM_TYPE_BRANCH_SAMPLE_TYPE:
1098 	case PARSE_EVENTS__TERM_TYPE_TIME:
1099 	case PARSE_EVENTS__TERM_TYPE_DRV_CFG:
1100 	case PARSE_EVENTS__TERM_TYPE_PERCORE:
1101 	case PARSE_EVENTS__TERM_TYPE_METRIC_ID:
1102 	case PARSE_EVENTS__TERM_TYPE_RAW:
1103 	case PARSE_EVENTS__TERM_TYPE_LEGACY_CACHE:
1104 	case PARSE_EVENTS__TERM_TYPE_HARDWARE:
1105 	default:
1106 		if (err) {
1107 			parse_events_error__handle(err, term->err_term,
1108 						   strdup(config_term_name(term->type_term)),
1109 				strdup("valid terms: call-graph,stack-size\n"));
1110 		}
1111 		return -EINVAL;
1112 	}
1113 
1114 	return 0;
1115 }
1116 #endif
1117 
1118 static int config_attr(struct perf_event_attr *attr,
1119 		       const struct parse_events_terms *head,
1120 		       struct parse_events_error *err,
1121 		       config_term_func_t config_term)
1122 {
1123 	struct parse_events_term *term;
1124 
1125 	list_for_each_entry(term, &head->terms, list)
1126 		if (config_term(attr, term, err))
1127 			return -EINVAL;
1128 
1129 	return 0;
1130 }
1131 
1132 static int get_config_terms(const struct parse_events_terms *head_config,
1133 			    struct list_head *head_terms)
1134 {
1135 #define ADD_CONFIG_TERM(__type, __weak)				\
1136 	struct evsel_config_term *__t;			\
1137 								\
1138 	__t = zalloc(sizeof(*__t));				\
1139 	if (!__t)						\
1140 		return -ENOMEM;					\
1141 								\
1142 	INIT_LIST_HEAD(&__t->list);				\
1143 	__t->type       = EVSEL__CONFIG_TERM_ ## __type;	\
1144 	__t->weak	= __weak;				\
1145 	list_add_tail(&__t->list, head_terms)
1146 
1147 #define ADD_CONFIG_TERM_VAL(__type, __name, __val, __weak)	\
1148 do {								\
1149 	ADD_CONFIG_TERM(__type, __weak);			\
1150 	__t->val.__name = __val;				\
1151 } while (0)
1152 
1153 #define ADD_CONFIG_TERM_STR(__type, __val, __weak)		\
1154 do {								\
1155 	ADD_CONFIG_TERM(__type, __weak);			\
1156 	__t->val.str = strdup(__val);				\
1157 	if (!__t->val.str) {					\
1158 		zfree(&__t);					\
1159 		return -ENOMEM;					\
1160 	}							\
1161 	__t->free_str = true;					\
1162 } while (0)
1163 
1164 	struct parse_events_term *term;
1165 
1166 	list_for_each_entry(term, &head_config->terms, list) {
1167 		switch (term->type_term) {
1168 		case PARSE_EVENTS__TERM_TYPE_SAMPLE_PERIOD:
1169 			ADD_CONFIG_TERM_VAL(PERIOD, period, term->val.num, term->weak);
1170 			break;
1171 		case PARSE_EVENTS__TERM_TYPE_SAMPLE_FREQ:
1172 			ADD_CONFIG_TERM_VAL(FREQ, freq, term->val.num, term->weak);
1173 			break;
1174 		case PARSE_EVENTS__TERM_TYPE_TIME:
1175 			ADD_CONFIG_TERM_VAL(TIME, time, term->val.num, term->weak);
1176 			break;
1177 		case PARSE_EVENTS__TERM_TYPE_CALLGRAPH:
1178 			ADD_CONFIG_TERM_STR(CALLGRAPH, term->val.str, term->weak);
1179 			break;
1180 		case PARSE_EVENTS__TERM_TYPE_BRANCH_SAMPLE_TYPE:
1181 			ADD_CONFIG_TERM_STR(BRANCH, term->val.str, term->weak);
1182 			break;
1183 		case PARSE_EVENTS__TERM_TYPE_STACKSIZE:
1184 			ADD_CONFIG_TERM_VAL(STACK_USER, stack_user,
1185 					    term->val.num, term->weak);
1186 			break;
1187 		case PARSE_EVENTS__TERM_TYPE_INHERIT:
1188 			ADD_CONFIG_TERM_VAL(INHERIT, inherit,
1189 					    term->val.num ? 1 : 0, term->weak);
1190 			break;
1191 		case PARSE_EVENTS__TERM_TYPE_NOINHERIT:
1192 			ADD_CONFIG_TERM_VAL(INHERIT, inherit,
1193 					    term->val.num ? 0 : 1, term->weak);
1194 			break;
1195 		case PARSE_EVENTS__TERM_TYPE_MAX_STACK:
1196 			ADD_CONFIG_TERM_VAL(MAX_STACK, max_stack,
1197 					    term->val.num, term->weak);
1198 			break;
1199 		case PARSE_EVENTS__TERM_TYPE_MAX_EVENTS:
1200 			ADD_CONFIG_TERM_VAL(MAX_EVENTS, max_events,
1201 					    term->val.num, term->weak);
1202 			break;
1203 		case PARSE_EVENTS__TERM_TYPE_OVERWRITE:
1204 			ADD_CONFIG_TERM_VAL(OVERWRITE, overwrite,
1205 					    term->val.num ? 1 : 0, term->weak);
1206 			break;
1207 		case PARSE_EVENTS__TERM_TYPE_NOOVERWRITE:
1208 			ADD_CONFIG_TERM_VAL(OVERWRITE, overwrite,
1209 					    term->val.num ? 0 : 1, term->weak);
1210 			break;
1211 		case PARSE_EVENTS__TERM_TYPE_DRV_CFG:
1212 			ADD_CONFIG_TERM_STR(DRV_CFG, term->val.str, term->weak);
1213 			break;
1214 		case PARSE_EVENTS__TERM_TYPE_PERCORE:
1215 			ADD_CONFIG_TERM_VAL(PERCORE, percore,
1216 					    term->val.num ? true : false, term->weak);
1217 			break;
1218 		case PARSE_EVENTS__TERM_TYPE_AUX_OUTPUT:
1219 			ADD_CONFIG_TERM_VAL(AUX_OUTPUT, aux_output,
1220 					    term->val.num ? 1 : 0, term->weak);
1221 			break;
1222 		case PARSE_EVENTS__TERM_TYPE_AUX_SAMPLE_SIZE:
1223 			ADD_CONFIG_TERM_VAL(AUX_SAMPLE_SIZE, aux_sample_size,
1224 					    term->val.num, term->weak);
1225 			break;
1226 		case PARSE_EVENTS__TERM_TYPE_USER:
1227 		case PARSE_EVENTS__TERM_TYPE_CONFIG:
1228 		case PARSE_EVENTS__TERM_TYPE_CONFIG1:
1229 		case PARSE_EVENTS__TERM_TYPE_CONFIG2:
1230 		case PARSE_EVENTS__TERM_TYPE_CONFIG3:
1231 		case PARSE_EVENTS__TERM_TYPE_NAME:
1232 		case PARSE_EVENTS__TERM_TYPE_METRIC_ID:
1233 		case PARSE_EVENTS__TERM_TYPE_RAW:
1234 		case PARSE_EVENTS__TERM_TYPE_LEGACY_CACHE:
1235 		case PARSE_EVENTS__TERM_TYPE_HARDWARE:
1236 		default:
1237 			break;
1238 		}
1239 	}
1240 	return 0;
1241 }
1242 
1243 /*
1244  * Add EVSEL__CONFIG_TERM_CFG_CHG where cfg_chg will have a bit set for
1245  * each bit of attr->config that the user has changed.
1246  */
1247 static int get_config_chgs(struct perf_pmu *pmu, struct parse_events_terms *head_config,
1248 			   struct list_head *head_terms)
1249 {
1250 	struct parse_events_term *term;
1251 	u64 bits = 0;
1252 	int type;
1253 
1254 	list_for_each_entry(term, &head_config->terms, list) {
1255 		switch (term->type_term) {
1256 		case PARSE_EVENTS__TERM_TYPE_USER:
1257 			type = perf_pmu__format_type(pmu, term->config);
1258 			if (type != PERF_PMU_FORMAT_VALUE_CONFIG)
1259 				continue;
1260 			bits |= perf_pmu__format_bits(pmu, term->config);
1261 			break;
1262 		case PARSE_EVENTS__TERM_TYPE_CONFIG:
1263 			bits = ~(u64)0;
1264 			break;
1265 		case PARSE_EVENTS__TERM_TYPE_CONFIG1:
1266 		case PARSE_EVENTS__TERM_TYPE_CONFIG2:
1267 		case PARSE_EVENTS__TERM_TYPE_CONFIG3:
1268 		case PARSE_EVENTS__TERM_TYPE_NAME:
1269 		case PARSE_EVENTS__TERM_TYPE_SAMPLE_PERIOD:
1270 		case PARSE_EVENTS__TERM_TYPE_SAMPLE_FREQ:
1271 		case PARSE_EVENTS__TERM_TYPE_BRANCH_SAMPLE_TYPE:
1272 		case PARSE_EVENTS__TERM_TYPE_TIME:
1273 		case PARSE_EVENTS__TERM_TYPE_CALLGRAPH:
1274 		case PARSE_EVENTS__TERM_TYPE_STACKSIZE:
1275 		case PARSE_EVENTS__TERM_TYPE_NOINHERIT:
1276 		case PARSE_EVENTS__TERM_TYPE_INHERIT:
1277 		case PARSE_EVENTS__TERM_TYPE_MAX_STACK:
1278 		case PARSE_EVENTS__TERM_TYPE_MAX_EVENTS:
1279 		case PARSE_EVENTS__TERM_TYPE_NOOVERWRITE:
1280 		case PARSE_EVENTS__TERM_TYPE_OVERWRITE:
1281 		case PARSE_EVENTS__TERM_TYPE_DRV_CFG:
1282 		case PARSE_EVENTS__TERM_TYPE_PERCORE:
1283 		case PARSE_EVENTS__TERM_TYPE_AUX_OUTPUT:
1284 		case PARSE_EVENTS__TERM_TYPE_AUX_SAMPLE_SIZE:
1285 		case PARSE_EVENTS__TERM_TYPE_METRIC_ID:
1286 		case PARSE_EVENTS__TERM_TYPE_RAW:
1287 		case PARSE_EVENTS__TERM_TYPE_LEGACY_CACHE:
1288 		case PARSE_EVENTS__TERM_TYPE_HARDWARE:
1289 		default:
1290 			break;
1291 		}
1292 	}
1293 
1294 	if (bits)
1295 		ADD_CONFIG_TERM_VAL(CFG_CHG, cfg_chg, bits, false);
1296 
1297 #undef ADD_CONFIG_TERM
1298 	return 0;
1299 }
1300 
1301 int parse_events_add_tracepoint(struct parse_events_state *parse_state,
1302 				struct list_head *list,
1303 				const char *sys, const char *event,
1304 				struct parse_events_error *err,
1305 				struct parse_events_terms *head_config, void *loc_)
1306 {
1307 	YYLTYPE *loc = loc_;
1308 #ifdef HAVE_LIBTRACEEVENT
1309 	if (head_config) {
1310 		struct perf_event_attr attr;
1311 
1312 		if (config_attr(&attr, head_config, err,
1313 				config_term_tracepoint))
1314 			return -EINVAL;
1315 	}
1316 
1317 	if (strpbrk(sys, "*?"))
1318 		return add_tracepoint_multi_sys(parse_state, list, sys, event,
1319 						err, head_config, loc);
1320 	else
1321 		return add_tracepoint_event(parse_state, list, sys, event,
1322 					    err, head_config, loc);
1323 #else
1324 	(void)parse_state;
1325 	(void)list;
1326 	(void)sys;
1327 	(void)event;
1328 	(void)head_config;
1329 	parse_events_error__handle(err, loc->first_column, strdup("unsupported tracepoint"),
1330 				strdup("libtraceevent is necessary for tracepoint support"));
1331 	return -1;
1332 #endif
1333 }
1334 
1335 static int __parse_events_add_numeric(struct parse_events_state *parse_state,
1336 				struct list_head *list,
1337 				struct perf_pmu *pmu, u32 type, u32 extended_type,
1338 				u64 config, const struct parse_events_terms *head_config)
1339 {
1340 	struct perf_event_attr attr;
1341 	LIST_HEAD(config_terms);
1342 	const char *name, *metric_id;
1343 	int ret;
1344 
1345 	memset(&attr, 0, sizeof(attr));
1346 	attr.type = type;
1347 	attr.config = config;
1348 	if (extended_type && (type == PERF_TYPE_HARDWARE || type == PERF_TYPE_HW_CACHE)) {
1349 		assert(perf_pmus__supports_extended_type());
1350 		attr.config |= (u64)extended_type << PERF_PMU_TYPE_SHIFT;
1351 	}
1352 
1353 	if (head_config) {
1354 		if (config_attr(&attr, head_config, parse_state->error,
1355 				config_term_common))
1356 			return -EINVAL;
1357 
1358 		if (get_config_terms(head_config, &config_terms))
1359 			return -ENOMEM;
1360 	}
1361 
1362 	name = get_config_name(head_config);
1363 	metric_id = get_config_metric_id(head_config);
1364 	ret = __add_event(list, &parse_state->idx, &attr, /*init_attr*/true, name,
1365 			metric_id, pmu, &config_terms, /*auto_merge_stats=*/false,
1366 			/*cpu_list=*/NULL) ? 0 : -ENOMEM;
1367 	free_config_terms(&config_terms);
1368 	return ret;
1369 }
1370 
1371 int parse_events_add_numeric(struct parse_events_state *parse_state,
1372 			     struct list_head *list,
1373 			     u32 type, u64 config,
1374 			     const struct parse_events_terms *head_config,
1375 			     bool wildcard)
1376 {
1377 	struct perf_pmu *pmu = NULL;
1378 	bool found_supported = false;
1379 
1380 	/* Wildcards on numeric values are only supported by core PMUs. */
1381 	if (wildcard && perf_pmus__supports_extended_type()) {
1382 		while ((pmu = perf_pmus__scan_core(pmu)) != NULL) {
1383 			int ret;
1384 
1385 			found_supported = true;
1386 			if (parse_events__filter_pmu(parse_state, pmu))
1387 				continue;
1388 
1389 			ret = __parse_events_add_numeric(parse_state, list, pmu,
1390 							 type, pmu->type,
1391 							 config, head_config);
1392 			if (ret)
1393 				return ret;
1394 		}
1395 		if (found_supported)
1396 			return 0;
1397 	}
1398 	return __parse_events_add_numeric(parse_state, list, perf_pmus__find_by_type(type),
1399 					type, /*extended_type=*/0, config, head_config);
1400 }
1401 
1402 int parse_events_add_tool(struct parse_events_state *parse_state,
1403 			  struct list_head *list,
1404 			  int tool_event)
1405 {
1406 	return add_event_tool(list, &parse_state->idx, tool_event);
1407 }
1408 
1409 static bool config_term_percore(struct list_head *config_terms)
1410 {
1411 	struct evsel_config_term *term;
1412 
1413 	list_for_each_entry(term, config_terms, list) {
1414 		if (term->type == EVSEL__CONFIG_TERM_PERCORE)
1415 			return term->val.percore;
1416 	}
1417 
1418 	return false;
1419 }
1420 
1421 static int parse_events_add_pmu(struct parse_events_state *parse_state,
1422 				struct list_head *list, struct perf_pmu *pmu,
1423 				const struct parse_events_terms *const_parsed_terms,
1424 				bool auto_merge_stats)
1425 {
1426 	struct perf_event_attr attr;
1427 	struct perf_pmu_info info;
1428 	struct evsel *evsel;
1429 	struct parse_events_error *err = parse_state->error;
1430 	LIST_HEAD(config_terms);
1431 	struct parse_events_terms parsed_terms;
1432 	bool alias_rewrote_terms = false;
1433 
1434 	if (verbose > 1) {
1435 		struct strbuf sb;
1436 
1437 		strbuf_init(&sb, /*hint=*/ 0);
1438 		if (pmu->selectable && const_parsed_terms &&
1439 		    list_empty(&const_parsed_terms->terms)) {
1440 			strbuf_addf(&sb, "%s//", pmu->name);
1441 		} else {
1442 			strbuf_addf(&sb, "%s/", pmu->name);
1443 			parse_events_terms__to_strbuf(const_parsed_terms, &sb);
1444 			strbuf_addch(&sb, '/');
1445 		}
1446 		fprintf(stderr, "Attempt to add: %s\n", sb.buf);
1447 		strbuf_release(&sb);
1448 	}
1449 
1450 	memset(&attr, 0, sizeof(attr));
1451 	if (pmu->perf_event_attr_init_default)
1452 		pmu->perf_event_attr_init_default(pmu, &attr);
1453 
1454 	attr.type = pmu->type;
1455 
1456 	if (!const_parsed_terms || list_empty(&const_parsed_terms->terms)) {
1457 		evsel = __add_event(list, &parse_state->idx, &attr,
1458 				    /*init_attr=*/true, /*name=*/NULL,
1459 				    /*metric_id=*/NULL, pmu,
1460 				    /*config_terms=*/NULL, auto_merge_stats,
1461 				    /*cpu_list=*/NULL);
1462 		return evsel ? 0 : -ENOMEM;
1463 	}
1464 
1465 	parse_events_terms__init(&parsed_terms);
1466 	if (const_parsed_terms) {
1467 		int ret = parse_events_terms__copy(const_parsed_terms, &parsed_terms);
1468 
1469 		if (ret)
1470 			return ret;
1471 	}
1472 	fix_raw(&parsed_terms, pmu);
1473 
1474 	/* Configure attr/terms with a known PMU, this will set hardcoded terms. */
1475 	if (config_attr(&attr, &parsed_terms, parse_state->error, config_term_pmu)) {
1476 		parse_events_terms__exit(&parsed_terms);
1477 		return -EINVAL;
1478 	}
1479 
1480 	/* Look for event names in the terms and rewrite into format based terms. */
1481 	if (!parse_state->fake_pmu && perf_pmu__check_alias(pmu, &parsed_terms,
1482 							    &info, &alias_rewrote_terms, err)) {
1483 		parse_events_terms__exit(&parsed_terms);
1484 		return -EINVAL;
1485 	}
1486 
1487 	if (verbose > 1) {
1488 		struct strbuf sb;
1489 
1490 		strbuf_init(&sb, /*hint=*/ 0);
1491 		parse_events_terms__to_strbuf(&parsed_terms, &sb);
1492 		fprintf(stderr, "..after resolving event: %s/%s/\n", pmu->name, sb.buf);
1493 		strbuf_release(&sb);
1494 	}
1495 
1496 	/* Configure attr/terms again if an alias was expanded. */
1497 	if (alias_rewrote_terms &&
1498 	    config_attr(&attr, &parsed_terms, parse_state->error, config_term_pmu)) {
1499 		parse_events_terms__exit(&parsed_terms);
1500 		return -EINVAL;
1501 	}
1502 
1503 	if (get_config_terms(&parsed_terms, &config_terms)) {
1504 		parse_events_terms__exit(&parsed_terms);
1505 		return -ENOMEM;
1506 	}
1507 
1508 	/*
1509 	 * When using default config, record which bits of attr->config were
1510 	 * changed by the user.
1511 	 */
1512 	if (pmu->perf_event_attr_init_default &&
1513 	    get_config_chgs(pmu, &parsed_terms, &config_terms)) {
1514 		parse_events_terms__exit(&parsed_terms);
1515 		return -ENOMEM;
1516 	}
1517 
1518 	if (!parse_state->fake_pmu &&
1519 	    perf_pmu__config(pmu, &attr, &parsed_terms, parse_state->error)) {
1520 		free_config_terms(&config_terms);
1521 		parse_events_terms__exit(&parsed_terms);
1522 		return -EINVAL;
1523 	}
1524 
1525 	evsel = __add_event(list, &parse_state->idx, &attr, /*init_attr=*/true,
1526 			    get_config_name(&parsed_terms),
1527 			    get_config_metric_id(&parsed_terms), pmu,
1528 			    &config_terms, auto_merge_stats, /*cpu_list=*/NULL);
1529 	if (!evsel) {
1530 		parse_events_terms__exit(&parsed_terms);
1531 		return -ENOMEM;
1532 	}
1533 
1534 	if (evsel->name)
1535 		evsel->use_config_name = true;
1536 
1537 	evsel->percore = config_term_percore(&evsel->config_terms);
1538 
1539 	if (parse_state->fake_pmu) {
1540 		parse_events_terms__exit(&parsed_terms);
1541 		return 0;
1542 	}
1543 
1544 	parse_events_terms__exit(&parsed_terms);
1545 	free((char *)evsel->unit);
1546 	evsel->unit = strdup(info.unit);
1547 	evsel->scale = info.scale;
1548 	evsel->per_pkg = info.per_pkg;
1549 	evsel->snapshot = info.snapshot;
1550 	return 0;
1551 }
1552 
1553 int parse_events_multi_pmu_add(struct parse_events_state *parse_state,
1554 			       const char *event_name,
1555 			       const struct parse_events_terms *const_parsed_terms,
1556 			       struct list_head **listp, void *loc_)
1557 {
1558 	struct parse_events_term *term;
1559 	struct list_head *list = NULL;
1560 	struct perf_pmu *pmu = NULL;
1561 	YYLTYPE *loc = loc_;
1562 	int ok = 0;
1563 	const char *config;
1564 	struct parse_events_terms parsed_terms;
1565 
1566 	*listp = NULL;
1567 
1568 	parse_events_terms__init(&parsed_terms);
1569 	if (const_parsed_terms) {
1570 		int ret = parse_events_terms__copy(const_parsed_terms, &parsed_terms);
1571 
1572 		if (ret)
1573 			return ret;
1574 	}
1575 
1576 	config = strdup(event_name);
1577 	if (!config)
1578 		goto out_err;
1579 
1580 	if (parse_events_term__num(&term,
1581 				   PARSE_EVENTS__TERM_TYPE_USER,
1582 				   config, /*num=*/1, /*novalue=*/true,
1583 				   loc, /*loc_val=*/NULL) < 0) {
1584 		zfree(&config);
1585 		goto out_err;
1586 	}
1587 	list_add_tail(&term->list, &parsed_terms.terms);
1588 
1589 	/* Add it for all PMUs that support the alias */
1590 	list = malloc(sizeof(struct list_head));
1591 	if (!list)
1592 		goto out_err;
1593 
1594 	INIT_LIST_HEAD(list);
1595 
1596 	while ((pmu = perf_pmus__scan(pmu)) != NULL) {
1597 		bool auto_merge_stats;
1598 
1599 		if (parse_events__filter_pmu(parse_state, pmu))
1600 			continue;
1601 
1602 		if (!perf_pmu__have_event(pmu, event_name))
1603 			continue;
1604 
1605 		auto_merge_stats = perf_pmu__auto_merge_stats(pmu);
1606 		if (!parse_events_add_pmu(parse_state, list, pmu,
1607 					  &parsed_terms, auto_merge_stats)) {
1608 			struct strbuf sb;
1609 
1610 			strbuf_init(&sb, /*hint=*/ 0);
1611 			parse_events_terms__to_strbuf(&parsed_terms, &sb);
1612 			pr_debug("%s -> %s/%s/\n", event_name, pmu->name, sb.buf);
1613 			strbuf_release(&sb);
1614 			ok++;
1615 		}
1616 	}
1617 
1618 	if (parse_state->fake_pmu) {
1619 		if (!parse_events_add_pmu(parse_state, list, parse_state->fake_pmu, &parsed_terms,
1620 					  /*auto_merge_stats=*/true)) {
1621 			struct strbuf sb;
1622 
1623 			strbuf_init(&sb, /*hint=*/ 0);
1624 			parse_events_terms__to_strbuf(&parsed_terms, &sb);
1625 			pr_debug("%s -> %s/%s/\n", event_name, "fake_pmu", sb.buf);
1626 			strbuf_release(&sb);
1627 			ok++;
1628 		}
1629 	}
1630 
1631 out_err:
1632 	parse_events_terms__exit(&parsed_terms);
1633 	if (ok)
1634 		*listp = list;
1635 	else
1636 		free(list);
1637 
1638 	return ok ? 0 : -1;
1639 }
1640 
1641 int parse_events_multi_pmu_add_or_add_pmu(struct parse_events_state *parse_state,
1642 					const char *event_or_pmu,
1643 					const struct parse_events_terms *const_parsed_terms,
1644 					struct list_head **listp,
1645 					void *loc_)
1646 {
1647 	YYLTYPE *loc = loc_;
1648 	struct perf_pmu *pmu;
1649 	int ok = 0;
1650 	char *help;
1651 
1652 	*listp = malloc(sizeof(**listp));
1653 	if (!*listp)
1654 		return -ENOMEM;
1655 
1656 	INIT_LIST_HEAD(*listp);
1657 
1658 	/* Attempt to add to list assuming event_or_pmu is a PMU name. */
1659 	pmu = parse_state->fake_pmu ?: perf_pmus__find(event_or_pmu);
1660 	if (pmu && !parse_events_add_pmu(parse_state, *listp, pmu, const_parsed_terms,
1661 					/*auto_merge_stats=*/false))
1662 		return 0;
1663 
1664 	pmu = NULL;
1665 	/* Failed to add, try wildcard expansion of event_or_pmu as a PMU name. */
1666 	while ((pmu = perf_pmus__scan(pmu)) != NULL) {
1667 		if (!parse_events__filter_pmu(parse_state, pmu) &&
1668 		    perf_pmu__match(pmu, event_or_pmu)) {
1669 			bool auto_merge_stats = perf_pmu__auto_merge_stats(pmu);
1670 
1671 			if (!parse_events_add_pmu(parse_state, *listp, pmu,
1672 						  const_parsed_terms,
1673 						  auto_merge_stats)) {
1674 				ok++;
1675 				parse_state->wild_card_pmus = true;
1676 			}
1677 		}
1678 	}
1679 	if (ok)
1680 		return 0;
1681 
1682 	/* Failure to add, assume event_or_pmu is an event name. */
1683 	zfree(listp);
1684 	if (!parse_events_multi_pmu_add(parse_state, event_or_pmu, const_parsed_terms, listp, loc))
1685 		return 0;
1686 
1687 	if (asprintf(&help, "Unable to find PMU or event on a PMU of '%s'", event_or_pmu) < 0)
1688 		help = NULL;
1689 	parse_events_error__handle(parse_state->error, loc->first_column,
1690 				strdup("Bad event or PMU"),
1691 				help);
1692 	zfree(listp);
1693 	return -EINVAL;
1694 }
1695 
1696 void parse_events__set_leader(char *name, struct list_head *list)
1697 {
1698 	struct evsel *leader;
1699 
1700 	if (list_empty(list)) {
1701 		WARN_ONCE(true, "WARNING: failed to set leader: empty list");
1702 		return;
1703 	}
1704 
1705 	leader = list_first_entry(list, struct evsel, core.node);
1706 	__perf_evlist__set_leader(list, &leader->core);
1707 	zfree(&leader->group_name);
1708 	leader->group_name = name;
1709 }
1710 
1711 static int parse_events__modifier_list(struct parse_events_state *parse_state,
1712 				       YYLTYPE *loc,
1713 				       struct list_head *list,
1714 				       struct parse_events_modifier mod,
1715 				       bool group)
1716 {
1717 	struct evsel *evsel;
1718 
1719 	if (!group && mod.weak) {
1720 		parse_events_error__handle(parse_state->error, loc->first_column,
1721 					   strdup("Weak modifier is for use with groups"), NULL);
1722 		return -EINVAL;
1723 	}
1724 
1725 	__evlist__for_each_entry(list, evsel) {
1726 		/* Translate modifiers into the equivalent evsel excludes. */
1727 		int eu = group ? evsel->core.attr.exclude_user : 0;
1728 		int ek = group ? evsel->core.attr.exclude_kernel : 0;
1729 		int eh = group ? evsel->core.attr.exclude_hv : 0;
1730 		int eH = group ? evsel->core.attr.exclude_host : 0;
1731 		int eG = group ? evsel->core.attr.exclude_guest : 0;
1732 		int exclude = eu | ek | eh;
1733 		int exclude_GH = group ? evsel->exclude_GH : 0;
1734 
1735 		if (mod.precise) {
1736 			/* use of precise requires exclude_guest */
1737 			eG = 1;
1738 		}
1739 		if (mod.user) {
1740 			if (!exclude)
1741 				exclude = eu = ek = eh = 1;
1742 			if (!exclude_GH && !perf_guest)
1743 				eG = 1;
1744 			eu = 0;
1745 		}
1746 		if (mod.kernel) {
1747 			if (!exclude)
1748 				exclude = eu = ek = eh = 1;
1749 			ek = 0;
1750 		}
1751 		if (mod.hypervisor) {
1752 			if (!exclude)
1753 				exclude = eu = ek = eh = 1;
1754 			eh = 0;
1755 		}
1756 		if (mod.guest) {
1757 			if (!exclude_GH)
1758 				exclude_GH = eG = eH = 1;
1759 			eG = 0;
1760 		}
1761 		if (mod.host) {
1762 			if (!exclude_GH)
1763 				exclude_GH = eG = eH = 1;
1764 			eH = 0;
1765 		}
1766 		evsel->core.attr.exclude_user   = eu;
1767 		evsel->core.attr.exclude_kernel = ek;
1768 		evsel->core.attr.exclude_hv     = eh;
1769 		evsel->core.attr.exclude_host   = eH;
1770 		evsel->core.attr.exclude_guest  = eG;
1771 		evsel->exclude_GH               = exclude_GH;
1772 
1773 		/* Simple modifiers copied to the evsel. */
1774 		if (mod.precise) {
1775 			u8 precise = evsel->core.attr.precise_ip + mod.precise;
1776 			/*
1777 			 * precise ip:
1778 			 *
1779 			 *  0 - SAMPLE_IP can have arbitrary skid
1780 			 *  1 - SAMPLE_IP must have constant skid
1781 			 *  2 - SAMPLE_IP requested to have 0 skid
1782 			 *  3 - SAMPLE_IP must have 0 skid
1783 			 *
1784 			 *  See also PERF_RECORD_MISC_EXACT_IP
1785 			 */
1786 			if (precise > 3) {
1787 				char *help;
1788 
1789 				if (asprintf(&help,
1790 					     "Maximum combined precise value is 3, adding precision to \"%s\"",
1791 					     evsel__name(evsel)) > 0) {
1792 					parse_events_error__handle(parse_state->error,
1793 								   loc->first_column,
1794 								   help, NULL);
1795 				}
1796 				return -EINVAL;
1797 			}
1798 			evsel->core.attr.precise_ip = precise;
1799 		}
1800 		if (mod.precise_max)
1801 			evsel->precise_max = 1;
1802 		if (mod.non_idle)
1803 			evsel->core.attr.exclude_idle = 1;
1804 		if (mod.sample_read)
1805 			evsel->sample_read = 1;
1806 		if (mod.pinned && evsel__is_group_leader(evsel))
1807 			evsel->core.attr.pinned = 1;
1808 		if (mod.exclusive && evsel__is_group_leader(evsel))
1809 			evsel->core.attr.exclusive = 1;
1810 		if (mod.weak)
1811 			evsel->weak_group = true;
1812 		if (mod.bpf)
1813 			evsel->bpf_counter = true;
1814 	}
1815 	return 0;
1816 }
1817 
1818 int parse_events__modifier_group(struct parse_events_state *parse_state, void *loc,
1819 				 struct list_head *list,
1820 				 struct parse_events_modifier mod)
1821 {
1822 	return parse_events__modifier_list(parse_state, loc, list, mod, /*group=*/true);
1823 }
1824 
1825 int parse_events__modifier_event(struct parse_events_state *parse_state, void *loc,
1826 				 struct list_head *list,
1827 				 struct parse_events_modifier mod)
1828 {
1829 	return parse_events__modifier_list(parse_state, loc, list, mod, /*group=*/false);
1830 }
1831 
1832 int parse_events__set_default_name(struct list_head *list, char *name)
1833 {
1834 	struct evsel *evsel;
1835 	bool used_name = false;
1836 
1837 	__evlist__for_each_entry(list, evsel) {
1838 		if (!evsel->name) {
1839 			evsel->name = used_name ? strdup(name) : name;
1840 			used_name = true;
1841 			if (!evsel->name)
1842 				return -ENOMEM;
1843 		}
1844 	}
1845 	if (!used_name)
1846 		free(name);
1847 	return 0;
1848 }
1849 
1850 static int parse_events__scanner(const char *str,
1851 				 FILE *input,
1852 				 struct parse_events_state *parse_state)
1853 {
1854 	YY_BUFFER_STATE buffer;
1855 	void *scanner;
1856 	int ret;
1857 
1858 	ret = parse_events_lex_init_extra(parse_state, &scanner);
1859 	if (ret)
1860 		return ret;
1861 
1862 	if (str)
1863 		buffer = parse_events__scan_string(str, scanner);
1864 	else
1865 	        parse_events_set_in(input, scanner);
1866 
1867 #ifdef PARSER_DEBUG
1868 	parse_events_debug = 1;
1869 	parse_events_set_debug(1, scanner);
1870 #endif
1871 	ret = parse_events_parse(parse_state, scanner);
1872 
1873 	if (str) {
1874 		parse_events__flush_buffer(buffer, scanner);
1875 		parse_events__delete_buffer(buffer, scanner);
1876 	}
1877 	parse_events_lex_destroy(scanner);
1878 	return ret;
1879 }
1880 
1881 /*
1882  * parse event config string, return a list of event terms.
1883  */
1884 int parse_events_terms(struct parse_events_terms *terms, const char *str, FILE *input)
1885 {
1886 	struct parse_events_state parse_state = {
1887 		.terms  = NULL,
1888 		.stoken = PE_START_TERMS,
1889 	};
1890 	int ret;
1891 
1892 	ret = parse_events__scanner(str, input, &parse_state);
1893 	if (!ret)
1894 		list_splice(&parse_state.terms->terms, &terms->terms);
1895 
1896 	zfree(&parse_state.terms);
1897 	return ret;
1898 }
1899 
1900 static int evsel__compute_group_pmu_name(struct evsel *evsel,
1901 					  const struct list_head *head)
1902 {
1903 	struct evsel *leader = evsel__leader(evsel);
1904 	struct evsel *pos;
1905 	const char *group_pmu_name;
1906 	struct perf_pmu *pmu = evsel__find_pmu(evsel);
1907 
1908 	if (!pmu) {
1909 		/*
1910 		 * For PERF_TYPE_HARDWARE and PERF_TYPE_HW_CACHE types the PMU
1911 		 * is a core PMU, but in heterogeneous systems this is
1912 		 * unknown. For now pick the first core PMU.
1913 		 */
1914 		pmu = perf_pmus__scan_core(NULL);
1915 	}
1916 	if (!pmu) {
1917 		pr_debug("No PMU found for '%s'\n", evsel__name(evsel));
1918 		return -EINVAL;
1919 	}
1920 	group_pmu_name = pmu->name;
1921 	/*
1922 	 * Software events may be in a group with other uncore PMU events. Use
1923 	 * the pmu_name of the first non-software event to avoid breaking the
1924 	 * software event out of the group.
1925 	 *
1926 	 * Aux event leaders, like intel_pt, expect a group with events from
1927 	 * other PMUs, so substitute the AUX event's PMU in this case.
1928 	 */
1929 	if (perf_pmu__is_software(pmu) || evsel__is_aux_event(leader)) {
1930 		struct perf_pmu *leader_pmu = evsel__find_pmu(leader);
1931 
1932 		if (!leader_pmu) {
1933 			/* As with determining pmu above. */
1934 			leader_pmu = perf_pmus__scan_core(NULL);
1935 		}
1936 		/*
1937 		 * Starting with the leader, find the first event with a named
1938 		 * non-software PMU. for_each_group_(member|evsel) isn't used as
1939 		 * the list isn't yet sorted putting evsel's in the same group
1940 		 * together.
1941 		 */
1942 		if (leader_pmu && !perf_pmu__is_software(leader_pmu)) {
1943 			group_pmu_name = leader_pmu->name;
1944 		} else if (leader->core.nr_members > 1) {
1945 			list_for_each_entry(pos, head, core.node) {
1946 				struct perf_pmu *pos_pmu;
1947 
1948 				if (pos == leader || evsel__leader(pos) != leader)
1949 					continue;
1950 				pos_pmu = evsel__find_pmu(pos);
1951 				if (!pos_pmu) {
1952 					/* As with determining pmu above. */
1953 					pos_pmu = perf_pmus__scan_core(NULL);
1954 				}
1955 				if (pos_pmu && !perf_pmu__is_software(pos_pmu)) {
1956 					group_pmu_name = pos_pmu->name;
1957 					break;
1958 				}
1959 			}
1960 		}
1961 	}
1962 	/* Assign the actual name taking care that the fake PMU lacks a name. */
1963 	evsel->group_pmu_name = strdup(group_pmu_name ?: "fake");
1964 	return evsel->group_pmu_name ? 0 : -ENOMEM;
1965 }
1966 
1967 __weak int arch_evlist__cmp(const struct evsel *lhs, const struct evsel *rhs)
1968 {
1969 	/* Order by insertion index. */
1970 	return lhs->core.idx - rhs->core.idx;
1971 }
1972 
1973 static int evlist__cmp(void *_fg_idx, const struct list_head *l, const struct list_head *r)
1974 {
1975 	const struct perf_evsel *lhs_core = container_of(l, struct perf_evsel, node);
1976 	const struct evsel *lhs = container_of(lhs_core, struct evsel, core);
1977 	const struct perf_evsel *rhs_core = container_of(r, struct perf_evsel, node);
1978 	const struct evsel *rhs = container_of(rhs_core, struct evsel, core);
1979 	int *force_grouped_idx = _fg_idx;
1980 	int lhs_sort_idx, rhs_sort_idx, ret;
1981 	const char *lhs_pmu_name, *rhs_pmu_name;
1982 	bool lhs_has_group, rhs_has_group;
1983 
1984 	/*
1985 	 * First sort by grouping/leader. Read the leader idx only if the evsel
1986 	 * is part of a group, by default ungrouped events will be sorted
1987 	 * relative to grouped events based on where the first ungrouped event
1988 	 * occurs. If both events don't have a group we want to fall-through to
1989 	 * the arch specific sorting, that can reorder and fix things like
1990 	 * Intel's topdown events.
1991 	 */
1992 	if (lhs_core->leader != lhs_core || lhs_core->nr_members > 1) {
1993 		lhs_has_group = true;
1994 		lhs_sort_idx = lhs_core->leader->idx;
1995 	} else {
1996 		lhs_has_group = false;
1997 		lhs_sort_idx = *force_grouped_idx != -1 && arch_evsel__must_be_in_group(lhs)
1998 			? *force_grouped_idx
1999 			: lhs_core->idx;
2000 	}
2001 	if (rhs_core->leader != rhs_core || rhs_core->nr_members > 1) {
2002 		rhs_has_group = true;
2003 		rhs_sort_idx = rhs_core->leader->idx;
2004 	} else {
2005 		rhs_has_group = false;
2006 		rhs_sort_idx = *force_grouped_idx != -1 && arch_evsel__must_be_in_group(rhs)
2007 			? *force_grouped_idx
2008 			: rhs_core->idx;
2009 	}
2010 
2011 	if (lhs_sort_idx != rhs_sort_idx)
2012 		return lhs_sort_idx - rhs_sort_idx;
2013 
2014 	/* Group by PMU if there is a group. Groups can't span PMUs. */
2015 	if (lhs_has_group && rhs_has_group) {
2016 		lhs_pmu_name = lhs->group_pmu_name;
2017 		rhs_pmu_name = rhs->group_pmu_name;
2018 		ret = strcmp(lhs_pmu_name, rhs_pmu_name);
2019 		if (ret)
2020 			return ret;
2021 	}
2022 
2023 	/* Architecture specific sorting. */
2024 	return arch_evlist__cmp(lhs, rhs);
2025 }
2026 
2027 static int parse_events__sort_events_and_fix_groups(struct list_head *list)
2028 {
2029 	int idx = 0, force_grouped_idx = -1;
2030 	struct evsel *pos, *cur_leader = NULL;
2031 	struct perf_evsel *cur_leaders_grp = NULL;
2032 	bool idx_changed = false, cur_leader_force_grouped = false;
2033 	int orig_num_leaders = 0, num_leaders = 0;
2034 	int ret;
2035 
2036 	/*
2037 	 * Compute index to insert ungrouped events at. Place them where the
2038 	 * first ungrouped event appears.
2039 	 */
2040 	list_for_each_entry(pos, list, core.node) {
2041 		const struct evsel *pos_leader = evsel__leader(pos);
2042 
2043 		ret = evsel__compute_group_pmu_name(pos, list);
2044 		if (ret)
2045 			return ret;
2046 
2047 		if (pos == pos_leader)
2048 			orig_num_leaders++;
2049 
2050 		/*
2051 		 * Ensure indexes are sequential, in particular for multiple
2052 		 * event lists being merged. The indexes are used to detect when
2053 		 * the user order is modified.
2054 		 */
2055 		pos->core.idx = idx++;
2056 
2057 		/* Remember an index to sort all forced grouped events together to. */
2058 		if (force_grouped_idx == -1 && pos == pos_leader && pos->core.nr_members < 2 &&
2059 		    arch_evsel__must_be_in_group(pos))
2060 			force_grouped_idx = pos->core.idx;
2061 	}
2062 
2063 	/* Sort events. */
2064 	list_sort(&force_grouped_idx, list, evlist__cmp);
2065 
2066 	/*
2067 	 * Recompute groups, splitting for PMUs and adding groups for events
2068 	 * that require them.
2069 	 */
2070 	idx = 0;
2071 	list_for_each_entry(pos, list, core.node) {
2072 		const struct evsel *pos_leader = evsel__leader(pos);
2073 		const char *pos_pmu_name = pos->group_pmu_name;
2074 		const char *cur_leader_pmu_name;
2075 		bool pos_force_grouped = force_grouped_idx != -1 &&
2076 			arch_evsel__must_be_in_group(pos);
2077 
2078 		/* Reset index and nr_members. */
2079 		if (pos->core.idx != idx)
2080 			idx_changed = true;
2081 		pos->core.idx = idx++;
2082 		pos->core.nr_members = 0;
2083 
2084 		/*
2085 		 * Set the group leader respecting the given groupings and that
2086 		 * groups can't span PMUs.
2087 		 */
2088 		if (!cur_leader)
2089 			cur_leader = pos;
2090 
2091 		cur_leader_pmu_name = cur_leader->group_pmu_name;
2092 		if ((cur_leaders_grp != pos->core.leader &&
2093 		     (!pos_force_grouped || !cur_leader_force_grouped)) ||
2094 		    strcmp(cur_leader_pmu_name, pos_pmu_name)) {
2095 			/* Event is for a different group/PMU than last. */
2096 			cur_leader = pos;
2097 			/*
2098 			 * Remember the leader's group before it is overwritten,
2099 			 * so that later events match as being in the same
2100 			 * group.
2101 			 */
2102 			cur_leaders_grp = pos->core.leader;
2103 			/*
2104 			 * Avoid forcing events into groups with events that
2105 			 * don't need to be in the group.
2106 			 */
2107 			cur_leader_force_grouped = pos_force_grouped;
2108 		}
2109 		if (pos_leader != cur_leader) {
2110 			/* The leader changed so update it. */
2111 			evsel__set_leader(pos, cur_leader);
2112 		}
2113 	}
2114 	list_for_each_entry(pos, list, core.node) {
2115 		struct evsel *pos_leader = evsel__leader(pos);
2116 
2117 		if (pos == pos_leader)
2118 			num_leaders++;
2119 		pos_leader->core.nr_members++;
2120 	}
2121 	return (idx_changed || num_leaders != orig_num_leaders) ? 1 : 0;
2122 }
2123 
2124 int __parse_events(struct evlist *evlist, const char *str, const char *pmu_filter,
2125 		   struct parse_events_error *err, struct perf_pmu *fake_pmu,
2126 		   bool warn_if_reordered, bool fake_tp)
2127 {
2128 	struct parse_events_state parse_state = {
2129 		.list	  = LIST_HEAD_INIT(parse_state.list),
2130 		.idx	  = evlist->core.nr_entries,
2131 		.error	  = err,
2132 		.stoken	  = PE_START_EVENTS,
2133 		.fake_pmu = fake_pmu,
2134 		.fake_tp  = fake_tp,
2135 		.pmu_filter = pmu_filter,
2136 		.match_legacy_cache_terms = true,
2137 	};
2138 	int ret, ret2;
2139 
2140 	ret = parse_events__scanner(str, /*input=*/ NULL, &parse_state);
2141 
2142 	if (!ret && list_empty(&parse_state.list)) {
2143 		WARN_ONCE(true, "WARNING: event parser found nothing\n");
2144 		return -1;
2145 	}
2146 
2147 	ret2 = parse_events__sort_events_and_fix_groups(&parse_state.list);
2148 	if (ret2 < 0)
2149 		return ret;
2150 
2151 	if (ret2 && warn_if_reordered && !parse_state.wild_card_pmus)
2152 		pr_warning("WARNING: events were regrouped to match PMUs\n");
2153 
2154 	/*
2155 	 * Add list to the evlist even with errors to allow callers to clean up.
2156 	 */
2157 	evlist__splice_list_tail(evlist, &parse_state.list);
2158 
2159 	if (!ret) {
2160 		struct evsel *last;
2161 
2162 		last = evlist__last(evlist);
2163 		last->cmdline_group_boundary = true;
2164 
2165 		return 0;
2166 	}
2167 
2168 	/*
2169 	 * There are 2 users - builtin-record and builtin-test objects.
2170 	 * Both call evlist__delete in case of error, so we dont
2171 	 * need to bother.
2172 	 */
2173 	return ret;
2174 }
2175 
2176 int parse_event(struct evlist *evlist, const char *str)
2177 {
2178 	struct parse_events_error err;
2179 	int ret;
2180 
2181 	parse_events_error__init(&err);
2182 	ret = parse_events(evlist, str, &err);
2183 	parse_events_error__exit(&err);
2184 	return ret;
2185 }
2186 
2187 struct parse_events_error_entry {
2188 	/** @list: The list the error is part of. */
2189 	struct list_head list;
2190 	/** @idx: index in the parsed string */
2191 	int   idx;
2192 	/** @str: string to display at the index */
2193 	char *str;
2194 	/** @help: optional help string */
2195 	char *help;
2196 };
2197 
2198 void parse_events_error__init(struct parse_events_error *err)
2199 {
2200 	INIT_LIST_HEAD(&err->list);
2201 }
2202 
2203 void parse_events_error__exit(struct parse_events_error *err)
2204 {
2205 	struct parse_events_error_entry *pos, *tmp;
2206 
2207 	list_for_each_entry_safe(pos, tmp, &err->list, list) {
2208 		zfree(&pos->str);
2209 		zfree(&pos->help);
2210 		list_del_init(&pos->list);
2211 		free(pos);
2212 	}
2213 }
2214 
2215 void parse_events_error__handle(struct parse_events_error *err, int idx,
2216 				char *str, char *help)
2217 {
2218 	struct parse_events_error_entry *entry;
2219 
2220 	if (WARN(!str || !err, "WARNING: failed to provide error string or struct\n"))
2221 		goto out_free;
2222 
2223 	entry = zalloc(sizeof(*entry));
2224 	if (!entry) {
2225 		pr_err("Failed to allocate memory for event parsing error: %s (%s)\n",
2226 			str, help ?: "<no help>");
2227 		goto out_free;
2228 	}
2229 	entry->idx = idx;
2230 	entry->str = str;
2231 	entry->help = help;
2232 	list_add(&entry->list, &err->list);
2233 	return;
2234 out_free:
2235 	free(str);
2236 	free(help);
2237 }
2238 
2239 #define MAX_WIDTH 1000
2240 static int get_term_width(void)
2241 {
2242 	struct winsize ws;
2243 
2244 	get_term_dimensions(&ws);
2245 	return ws.ws_col > MAX_WIDTH ? MAX_WIDTH : ws.ws_col;
2246 }
2247 
2248 static void __parse_events_error__print(int err_idx, const char *err_str,
2249 					const char *err_help, const char *event)
2250 {
2251 	const char *str = "invalid or unsupported event: ";
2252 	char _buf[MAX_WIDTH];
2253 	char *buf = (char *) event;
2254 	int idx = 0;
2255 	if (err_str) {
2256 		/* -2 for extra '' in the final fprintf */
2257 		int width       = get_term_width() - 2;
2258 		int len_event   = strlen(event);
2259 		int len_str, max_len, cut = 0;
2260 
2261 		/*
2262 		 * Maximum error index indent, we will cut
2263 		 * the event string if it's bigger.
2264 		 */
2265 		int max_err_idx = 13;
2266 
2267 		/*
2268 		 * Let's be specific with the message when
2269 		 * we have the precise error.
2270 		 */
2271 		str     = "event syntax error: ";
2272 		len_str = strlen(str);
2273 		max_len = width - len_str;
2274 
2275 		buf = _buf;
2276 
2277 		/* We're cutting from the beginning. */
2278 		if (err_idx > max_err_idx)
2279 			cut = err_idx - max_err_idx;
2280 
2281 		strncpy(buf, event + cut, max_len);
2282 
2283 		/* Mark cut parts with '..' on both sides. */
2284 		if (cut)
2285 			buf[0] = buf[1] = '.';
2286 
2287 		if ((len_event - cut) > max_len) {
2288 			buf[max_len - 1] = buf[max_len - 2] = '.';
2289 			buf[max_len] = 0;
2290 		}
2291 
2292 		idx = len_str + err_idx - cut;
2293 	}
2294 
2295 	fprintf(stderr, "%s'%s'\n", str, buf);
2296 	if (idx) {
2297 		fprintf(stderr, "%*s\\___ %s\n", idx + 1, "", err_str);
2298 		if (err_help)
2299 			fprintf(stderr, "\n%s\n", err_help);
2300 	}
2301 }
2302 
2303 void parse_events_error__print(const struct parse_events_error *err,
2304 			       const char *event)
2305 {
2306 	struct parse_events_error_entry *pos;
2307 	bool first = true;
2308 
2309 	list_for_each_entry(pos, &err->list, list) {
2310 		if (!first)
2311 			fputs("\n", stderr);
2312 		__parse_events_error__print(pos->idx, pos->str, pos->help, event);
2313 		first = false;
2314 	}
2315 }
2316 
2317 /*
2318  * In the list of errors err, do any of the error strings (str) contain the
2319  * given needle string?
2320  */
2321 bool parse_events_error__contains(const struct parse_events_error *err,
2322 				  const char *needle)
2323 {
2324 	struct parse_events_error_entry *pos;
2325 
2326 	list_for_each_entry(pos, &err->list, list) {
2327 		if (strstr(pos->str, needle) != NULL)
2328 			return true;
2329 	}
2330 	return false;
2331 }
2332 
2333 #undef MAX_WIDTH
2334 
2335 int parse_events_option(const struct option *opt, const char *str,
2336 			int unset __maybe_unused)
2337 {
2338 	struct parse_events_option_args *args = opt->value;
2339 	struct parse_events_error err;
2340 	int ret;
2341 
2342 	parse_events_error__init(&err);
2343 	ret = __parse_events(*args->evlistp, str, args->pmu_filter, &err,
2344 			     /*fake_pmu=*/NULL, /*warn_if_reordered=*/true,
2345 			     /*fake_tp=*/false);
2346 
2347 	if (ret) {
2348 		parse_events_error__print(&err, str);
2349 		fprintf(stderr, "Run 'perf list' for a list of valid events\n");
2350 	}
2351 	parse_events_error__exit(&err);
2352 
2353 	return ret;
2354 }
2355 
2356 int parse_events_option_new_evlist(const struct option *opt, const char *str, int unset)
2357 {
2358 	struct parse_events_option_args *args = opt->value;
2359 	int ret;
2360 
2361 	if (*args->evlistp == NULL) {
2362 		*args->evlistp = evlist__new();
2363 
2364 		if (*args->evlistp == NULL) {
2365 			fprintf(stderr, "Not enough memory to create evlist\n");
2366 			return -1;
2367 		}
2368 	}
2369 	ret = parse_events_option(opt, str, unset);
2370 	if (ret) {
2371 		evlist__delete(*args->evlistp);
2372 		*args->evlistp = NULL;
2373 	}
2374 
2375 	return ret;
2376 }
2377 
2378 static int
2379 foreach_evsel_in_last_glob(struct evlist *evlist,
2380 			   int (*func)(struct evsel *evsel,
2381 				       const void *arg),
2382 			   const void *arg)
2383 {
2384 	struct evsel *last = NULL;
2385 	int err;
2386 
2387 	/*
2388 	 * Don't return when list_empty, give func a chance to report
2389 	 * error when it found last == NULL.
2390 	 *
2391 	 * So no need to WARN here, let *func do this.
2392 	 */
2393 	if (evlist->core.nr_entries > 0)
2394 		last = evlist__last(evlist);
2395 
2396 	do {
2397 		err = (*func)(last, arg);
2398 		if (err)
2399 			return -1;
2400 		if (!last)
2401 			return 0;
2402 
2403 		if (last->core.node.prev == &evlist->core.entries)
2404 			return 0;
2405 		last = list_entry(last->core.node.prev, struct evsel, core.node);
2406 	} while (!last->cmdline_group_boundary);
2407 
2408 	return 0;
2409 }
2410 
2411 static int set_filter(struct evsel *evsel, const void *arg)
2412 {
2413 	const char *str = arg;
2414 	bool found = false;
2415 	int nr_addr_filters = 0;
2416 	struct perf_pmu *pmu = NULL;
2417 
2418 	if (evsel == NULL) {
2419 		fprintf(stderr,
2420 			"--filter option should follow a -e tracepoint or HW tracer option\n");
2421 		return -1;
2422 	}
2423 
2424 	if (evsel->core.attr.type == PERF_TYPE_TRACEPOINT) {
2425 		if (evsel__append_tp_filter(evsel, str) < 0) {
2426 			fprintf(stderr,
2427 				"not enough memory to hold filter string\n");
2428 			return -1;
2429 		}
2430 
2431 		return 0;
2432 	}
2433 
2434 	while ((pmu = perf_pmus__scan(pmu)) != NULL)
2435 		if (pmu->type == evsel->core.attr.type) {
2436 			found = true;
2437 			break;
2438 		}
2439 
2440 	if (found)
2441 		perf_pmu__scan_file(pmu, "nr_addr_filters",
2442 				    "%d", &nr_addr_filters);
2443 
2444 	if (!nr_addr_filters)
2445 		return perf_bpf_filter__parse(&evsel->bpf_filters, str);
2446 
2447 	if (evsel__append_addr_filter(evsel, str) < 0) {
2448 		fprintf(stderr,
2449 			"not enough memory to hold filter string\n");
2450 		return -1;
2451 	}
2452 
2453 	return 0;
2454 }
2455 
2456 int parse_filter(const struct option *opt, const char *str,
2457 		 int unset __maybe_unused)
2458 {
2459 	struct evlist *evlist = *(struct evlist **)opt->value;
2460 
2461 	return foreach_evsel_in_last_glob(evlist, set_filter,
2462 					  (const void *)str);
2463 }
2464 
2465 static int add_exclude_perf_filter(struct evsel *evsel,
2466 				   const void *arg __maybe_unused)
2467 {
2468 	char new_filter[64];
2469 
2470 	if (evsel == NULL || evsel->core.attr.type != PERF_TYPE_TRACEPOINT) {
2471 		fprintf(stderr,
2472 			"--exclude-perf option should follow a -e tracepoint option\n");
2473 		return -1;
2474 	}
2475 
2476 	snprintf(new_filter, sizeof(new_filter), "common_pid != %d", getpid());
2477 
2478 	if (evsel__append_tp_filter(evsel, new_filter) < 0) {
2479 		fprintf(stderr,
2480 			"not enough memory to hold filter string\n");
2481 		return -1;
2482 	}
2483 
2484 	return 0;
2485 }
2486 
2487 int exclude_perf(const struct option *opt,
2488 		 const char *arg __maybe_unused,
2489 		 int unset __maybe_unused)
2490 {
2491 	struct evlist *evlist = *(struct evlist **)opt->value;
2492 
2493 	return foreach_evsel_in_last_glob(evlist, add_exclude_perf_filter,
2494 					  NULL);
2495 }
2496 
2497 int parse_events__is_hardcoded_term(struct parse_events_term *term)
2498 {
2499 	return term->type_term != PARSE_EVENTS__TERM_TYPE_USER;
2500 }
2501 
2502 static int new_term(struct parse_events_term **_term,
2503 		    struct parse_events_term *temp,
2504 		    char *str, u64 num)
2505 {
2506 	struct parse_events_term *term;
2507 
2508 	term = malloc(sizeof(*term));
2509 	if (!term)
2510 		return -ENOMEM;
2511 
2512 	*term = *temp;
2513 	INIT_LIST_HEAD(&term->list);
2514 	term->weak = false;
2515 
2516 	switch (term->type_val) {
2517 	case PARSE_EVENTS__TERM_TYPE_NUM:
2518 		term->val.num = num;
2519 		break;
2520 	case PARSE_EVENTS__TERM_TYPE_STR:
2521 		term->val.str = str;
2522 		break;
2523 	default:
2524 		free(term);
2525 		return -EINVAL;
2526 	}
2527 
2528 	*_term = term;
2529 	return 0;
2530 }
2531 
2532 int parse_events_term__num(struct parse_events_term **term,
2533 			   enum parse_events__term_type type_term,
2534 			   const char *config, u64 num,
2535 			   bool no_value,
2536 			   void *loc_term_, void *loc_val_)
2537 {
2538 	YYLTYPE *loc_term = loc_term_;
2539 	YYLTYPE *loc_val = loc_val_;
2540 
2541 	struct parse_events_term temp = {
2542 		.type_val  = PARSE_EVENTS__TERM_TYPE_NUM,
2543 		.type_term = type_term,
2544 		.config    = config ? : strdup(config_term_name(type_term)),
2545 		.no_value  = no_value,
2546 		.err_term  = loc_term ? loc_term->first_column : 0,
2547 		.err_val   = loc_val  ? loc_val->first_column  : 0,
2548 	};
2549 
2550 	return new_term(term, &temp, /*str=*/NULL, num);
2551 }
2552 
2553 int parse_events_term__str(struct parse_events_term **term,
2554 			   enum parse_events__term_type type_term,
2555 			   char *config, char *str,
2556 			   void *loc_term_, void *loc_val_)
2557 {
2558 	YYLTYPE *loc_term = loc_term_;
2559 	YYLTYPE *loc_val = loc_val_;
2560 
2561 	struct parse_events_term temp = {
2562 		.type_val  = PARSE_EVENTS__TERM_TYPE_STR,
2563 		.type_term = type_term,
2564 		.config    = config,
2565 		.err_term  = loc_term ? loc_term->first_column : 0,
2566 		.err_val   = loc_val  ? loc_val->first_column  : 0,
2567 	};
2568 
2569 	return new_term(term, &temp, str, /*num=*/0);
2570 }
2571 
2572 int parse_events_term__term(struct parse_events_term **term,
2573 			    enum parse_events__term_type term_lhs,
2574 			    enum parse_events__term_type term_rhs,
2575 			    void *loc_term, void *loc_val)
2576 {
2577 	return parse_events_term__str(term, term_lhs, NULL,
2578 				      strdup(config_term_name(term_rhs)),
2579 				      loc_term, loc_val);
2580 }
2581 
2582 int parse_events_term__clone(struct parse_events_term **new,
2583 			     const struct parse_events_term *term)
2584 {
2585 	char *str;
2586 	struct parse_events_term temp = *term;
2587 
2588 	temp.used = false;
2589 	if (term->config) {
2590 		temp.config = strdup(term->config);
2591 		if (!temp.config)
2592 			return -ENOMEM;
2593 	}
2594 	if (term->type_val == PARSE_EVENTS__TERM_TYPE_NUM)
2595 		return new_term(new, &temp, /*str=*/NULL, term->val.num);
2596 
2597 	str = strdup(term->val.str);
2598 	if (!str) {
2599 		zfree(&temp.config);
2600 		return -ENOMEM;
2601 	}
2602 	return new_term(new, &temp, str, /*num=*/0);
2603 }
2604 
2605 void parse_events_term__delete(struct parse_events_term *term)
2606 {
2607 	if (term->type_val != PARSE_EVENTS__TERM_TYPE_NUM)
2608 		zfree(&term->val.str);
2609 
2610 	zfree(&term->config);
2611 	free(term);
2612 }
2613 
2614 static int parse_events_terms__copy(const struct parse_events_terms *src,
2615 				    struct parse_events_terms *dest)
2616 {
2617 	struct parse_events_term *term;
2618 
2619 	list_for_each_entry (term, &src->terms, list) {
2620 		struct parse_events_term *n;
2621 		int ret;
2622 
2623 		ret = parse_events_term__clone(&n, term);
2624 		if (ret)
2625 			return ret;
2626 
2627 		list_add_tail(&n->list, &dest->terms);
2628 	}
2629 	return 0;
2630 }
2631 
2632 void parse_events_terms__init(struct parse_events_terms *terms)
2633 {
2634 	INIT_LIST_HEAD(&terms->terms);
2635 }
2636 
2637 void parse_events_terms__exit(struct parse_events_terms *terms)
2638 {
2639 	struct parse_events_term *term, *h;
2640 
2641 	list_for_each_entry_safe(term, h, &terms->terms, list) {
2642 		list_del_init(&term->list);
2643 		parse_events_term__delete(term);
2644 	}
2645 }
2646 
2647 void parse_events_terms__delete(struct parse_events_terms *terms)
2648 {
2649 	if (!terms)
2650 		return;
2651 	parse_events_terms__exit(terms);
2652 	free(terms);
2653 }
2654 
2655 int parse_events_terms__to_strbuf(const struct parse_events_terms *terms, struct strbuf *sb)
2656 {
2657 	struct parse_events_term *term;
2658 	bool first = true;
2659 
2660 	if (!terms)
2661 		return 0;
2662 
2663 	list_for_each_entry(term, &terms->terms, list) {
2664 		int ret;
2665 
2666 		if (!first) {
2667 			ret = strbuf_addch(sb, ',');
2668 			if (ret < 0)
2669 				return ret;
2670 		}
2671 		first = false;
2672 
2673 		if (term->type_val == PARSE_EVENTS__TERM_TYPE_NUM)
2674 			if (term->no_value) {
2675 				assert(term->val.num == 1);
2676 				ret = strbuf_addf(sb, "%s", term->config);
2677 			} else
2678 				ret = strbuf_addf(sb, "%s=%#"PRIx64, term->config, term->val.num);
2679 		else if (term->type_val == PARSE_EVENTS__TERM_TYPE_STR) {
2680 			if (term->config) {
2681 				ret = strbuf_addf(sb, "%s=", term->config);
2682 				if (ret < 0)
2683 					return ret;
2684 			} else if ((unsigned int)term->type_term < __PARSE_EVENTS__TERM_TYPE_NR) {
2685 				ret = strbuf_addf(sb, "%s=", config_term_name(term->type_term));
2686 				if (ret < 0)
2687 					return ret;
2688 			}
2689 			assert(!term->no_value);
2690 			ret = strbuf_addf(sb, "%s", term->val.str);
2691 		}
2692 		if (ret < 0)
2693 			return ret;
2694 	}
2695 	return 0;
2696 }
2697 
2698 static void config_terms_list(char *buf, size_t buf_sz)
2699 {
2700 	int i;
2701 	bool first = true;
2702 
2703 	buf[0] = '\0';
2704 	for (i = 0; i < __PARSE_EVENTS__TERM_TYPE_NR; i++) {
2705 		const char *name = config_term_name(i);
2706 
2707 		if (!config_term_avail(i, NULL))
2708 			continue;
2709 		if (!name)
2710 			continue;
2711 		if (name[0] == '<')
2712 			continue;
2713 
2714 		if (strlen(buf) + strlen(name) + 2 >= buf_sz)
2715 			return;
2716 
2717 		if (!first)
2718 			strcat(buf, ",");
2719 		else
2720 			first = false;
2721 		strcat(buf, name);
2722 	}
2723 }
2724 
2725 /*
2726  * Return string contains valid config terms of an event.
2727  * @additional_terms: For terms such as PMU sysfs terms.
2728  */
2729 char *parse_events_formats_error_string(char *additional_terms)
2730 {
2731 	char *str;
2732 	/* "no-overwrite" is the longest name */
2733 	char static_terms[__PARSE_EVENTS__TERM_TYPE_NR *
2734 			  (sizeof("no-overwrite") - 1)];
2735 
2736 	config_terms_list(static_terms, sizeof(static_terms));
2737 	/* valid terms */
2738 	if (additional_terms) {
2739 		if (asprintf(&str, "valid terms: %s,%s",
2740 			     additional_terms, static_terms) < 0)
2741 			goto fail;
2742 	} else {
2743 		if (asprintf(&str, "valid terms: %s", static_terms) < 0)
2744 			goto fail;
2745 	}
2746 	return str;
2747 
2748 fail:
2749 	return NULL;
2750 }
2751