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