xref: /linux/tools/perf/util/parse-events.c (revision a3a02a52bcfcbcc4a637d4b68bf1bc391c9fad02)
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 		if (mod.retire_lat)
1815 			evsel->retire_lat = true;
1816 	}
1817 	return 0;
1818 }
1819 
1820 int parse_events__modifier_group(struct parse_events_state *parse_state, void *loc,
1821 				 struct list_head *list,
1822 				 struct parse_events_modifier mod)
1823 {
1824 	return parse_events__modifier_list(parse_state, loc, list, mod, /*group=*/true);
1825 }
1826 
1827 int parse_events__modifier_event(struct parse_events_state *parse_state, void *loc,
1828 				 struct list_head *list,
1829 				 struct parse_events_modifier mod)
1830 {
1831 	return parse_events__modifier_list(parse_state, loc, list, mod, /*group=*/false);
1832 }
1833 
1834 int parse_events__set_default_name(struct list_head *list, char *name)
1835 {
1836 	struct evsel *evsel;
1837 	bool used_name = false;
1838 
1839 	__evlist__for_each_entry(list, evsel) {
1840 		if (!evsel->name) {
1841 			evsel->name = used_name ? strdup(name) : name;
1842 			used_name = true;
1843 			if (!evsel->name)
1844 				return -ENOMEM;
1845 		}
1846 	}
1847 	if (!used_name)
1848 		free(name);
1849 	return 0;
1850 }
1851 
1852 static int parse_events__scanner(const char *str,
1853 				 FILE *input,
1854 				 struct parse_events_state *parse_state)
1855 {
1856 	YY_BUFFER_STATE buffer;
1857 	void *scanner;
1858 	int ret;
1859 
1860 	ret = parse_events_lex_init_extra(parse_state, &scanner);
1861 	if (ret)
1862 		return ret;
1863 
1864 	if (str)
1865 		buffer = parse_events__scan_string(str, scanner);
1866 	else
1867 	        parse_events_set_in(input, scanner);
1868 
1869 #ifdef PARSER_DEBUG
1870 	parse_events_debug = 1;
1871 	parse_events_set_debug(1, scanner);
1872 #endif
1873 	ret = parse_events_parse(parse_state, scanner);
1874 
1875 	if (str) {
1876 		parse_events__flush_buffer(buffer, scanner);
1877 		parse_events__delete_buffer(buffer, scanner);
1878 	}
1879 	parse_events_lex_destroy(scanner);
1880 	return ret;
1881 }
1882 
1883 /*
1884  * parse event config string, return a list of event terms.
1885  */
1886 int parse_events_terms(struct parse_events_terms *terms, const char *str, FILE *input)
1887 {
1888 	struct parse_events_state parse_state = {
1889 		.terms  = NULL,
1890 		.stoken = PE_START_TERMS,
1891 	};
1892 	int ret;
1893 
1894 	ret = parse_events__scanner(str, input, &parse_state);
1895 	if (!ret)
1896 		list_splice(&parse_state.terms->terms, &terms->terms);
1897 
1898 	zfree(&parse_state.terms);
1899 	return ret;
1900 }
1901 
1902 static int evsel__compute_group_pmu_name(struct evsel *evsel,
1903 					  const struct list_head *head)
1904 {
1905 	struct evsel *leader = evsel__leader(evsel);
1906 	struct evsel *pos;
1907 	const char *group_pmu_name;
1908 	struct perf_pmu *pmu = evsel__find_pmu(evsel);
1909 
1910 	if (!pmu) {
1911 		/*
1912 		 * For PERF_TYPE_HARDWARE and PERF_TYPE_HW_CACHE types the PMU
1913 		 * is a core PMU, but in heterogeneous systems this is
1914 		 * unknown. For now pick the first core PMU.
1915 		 */
1916 		pmu = perf_pmus__scan_core(NULL);
1917 	}
1918 	if (!pmu) {
1919 		pr_debug("No PMU found for '%s'\n", evsel__name(evsel));
1920 		return -EINVAL;
1921 	}
1922 	group_pmu_name = pmu->name;
1923 	/*
1924 	 * Software events may be in a group with other uncore PMU events. Use
1925 	 * the pmu_name of the first non-software event to avoid breaking the
1926 	 * software event out of the group.
1927 	 *
1928 	 * Aux event leaders, like intel_pt, expect a group with events from
1929 	 * other PMUs, so substitute the AUX event's PMU in this case.
1930 	 */
1931 	if (perf_pmu__is_software(pmu) || evsel__is_aux_event(leader)) {
1932 		struct perf_pmu *leader_pmu = evsel__find_pmu(leader);
1933 
1934 		if (!leader_pmu) {
1935 			/* As with determining pmu above. */
1936 			leader_pmu = perf_pmus__scan_core(NULL);
1937 		}
1938 		/*
1939 		 * Starting with the leader, find the first event with a named
1940 		 * non-software PMU. for_each_group_(member|evsel) isn't used as
1941 		 * the list isn't yet sorted putting evsel's in the same group
1942 		 * together.
1943 		 */
1944 		if (leader_pmu && !perf_pmu__is_software(leader_pmu)) {
1945 			group_pmu_name = leader_pmu->name;
1946 		} else if (leader->core.nr_members > 1) {
1947 			list_for_each_entry(pos, head, core.node) {
1948 				struct perf_pmu *pos_pmu;
1949 
1950 				if (pos == leader || evsel__leader(pos) != leader)
1951 					continue;
1952 				pos_pmu = evsel__find_pmu(pos);
1953 				if (!pos_pmu) {
1954 					/* As with determining pmu above. */
1955 					pos_pmu = perf_pmus__scan_core(NULL);
1956 				}
1957 				if (pos_pmu && !perf_pmu__is_software(pos_pmu)) {
1958 					group_pmu_name = pos_pmu->name;
1959 					break;
1960 				}
1961 			}
1962 		}
1963 	}
1964 	/* Assign the actual name taking care that the fake PMU lacks a name. */
1965 	evsel->group_pmu_name = strdup(group_pmu_name ?: "fake");
1966 	return evsel->group_pmu_name ? 0 : -ENOMEM;
1967 }
1968 
1969 __weak int arch_evlist__cmp(const struct evsel *lhs, const struct evsel *rhs)
1970 {
1971 	/* Order by insertion index. */
1972 	return lhs->core.idx - rhs->core.idx;
1973 }
1974 
1975 static int evlist__cmp(void *_fg_idx, const struct list_head *l, const struct list_head *r)
1976 {
1977 	const struct perf_evsel *lhs_core = container_of(l, struct perf_evsel, node);
1978 	const struct evsel *lhs = container_of(lhs_core, struct evsel, core);
1979 	const struct perf_evsel *rhs_core = container_of(r, struct perf_evsel, node);
1980 	const struct evsel *rhs = container_of(rhs_core, struct evsel, core);
1981 	int *force_grouped_idx = _fg_idx;
1982 	int lhs_sort_idx, rhs_sort_idx, ret;
1983 	const char *lhs_pmu_name, *rhs_pmu_name;
1984 	bool lhs_has_group, rhs_has_group;
1985 
1986 	/*
1987 	 * First sort by grouping/leader. Read the leader idx only if the evsel
1988 	 * is part of a group, by default ungrouped events will be sorted
1989 	 * relative to grouped events based on where the first ungrouped event
1990 	 * occurs. If both events don't have a group we want to fall-through to
1991 	 * the arch specific sorting, that can reorder and fix things like
1992 	 * Intel's topdown events.
1993 	 */
1994 	if (lhs_core->leader != lhs_core || lhs_core->nr_members > 1) {
1995 		lhs_has_group = true;
1996 		lhs_sort_idx = lhs_core->leader->idx;
1997 	} else {
1998 		lhs_has_group = false;
1999 		lhs_sort_idx = *force_grouped_idx != -1 && arch_evsel__must_be_in_group(lhs)
2000 			? *force_grouped_idx
2001 			: lhs_core->idx;
2002 	}
2003 	if (rhs_core->leader != rhs_core || rhs_core->nr_members > 1) {
2004 		rhs_has_group = true;
2005 		rhs_sort_idx = rhs_core->leader->idx;
2006 	} else {
2007 		rhs_has_group = false;
2008 		rhs_sort_idx = *force_grouped_idx != -1 && arch_evsel__must_be_in_group(rhs)
2009 			? *force_grouped_idx
2010 			: rhs_core->idx;
2011 	}
2012 
2013 	if (lhs_sort_idx != rhs_sort_idx)
2014 		return lhs_sort_idx - rhs_sort_idx;
2015 
2016 	/* Group by PMU if there is a group. Groups can't span PMUs. */
2017 	if (lhs_has_group && rhs_has_group) {
2018 		lhs_pmu_name = lhs->group_pmu_name;
2019 		rhs_pmu_name = rhs->group_pmu_name;
2020 		ret = strcmp(lhs_pmu_name, rhs_pmu_name);
2021 		if (ret)
2022 			return ret;
2023 	}
2024 
2025 	/* Architecture specific sorting. */
2026 	return arch_evlist__cmp(lhs, rhs);
2027 }
2028 
2029 static int parse_events__sort_events_and_fix_groups(struct list_head *list)
2030 {
2031 	int idx = 0, force_grouped_idx = -1;
2032 	struct evsel *pos, *cur_leader = NULL;
2033 	struct perf_evsel *cur_leaders_grp = NULL;
2034 	bool idx_changed = false, cur_leader_force_grouped = false;
2035 	int orig_num_leaders = 0, num_leaders = 0;
2036 	int ret;
2037 
2038 	/*
2039 	 * Compute index to insert ungrouped events at. Place them where the
2040 	 * first ungrouped event appears.
2041 	 */
2042 	list_for_each_entry(pos, list, core.node) {
2043 		const struct evsel *pos_leader = evsel__leader(pos);
2044 
2045 		ret = evsel__compute_group_pmu_name(pos, list);
2046 		if (ret)
2047 			return ret;
2048 
2049 		if (pos == pos_leader)
2050 			orig_num_leaders++;
2051 
2052 		/*
2053 		 * Ensure indexes are sequential, in particular for multiple
2054 		 * event lists being merged. The indexes are used to detect when
2055 		 * the user order is modified.
2056 		 */
2057 		pos->core.idx = idx++;
2058 
2059 		/* Remember an index to sort all forced grouped events together to. */
2060 		if (force_grouped_idx == -1 && pos == pos_leader && pos->core.nr_members < 2 &&
2061 		    arch_evsel__must_be_in_group(pos))
2062 			force_grouped_idx = pos->core.idx;
2063 	}
2064 
2065 	/* Sort events. */
2066 	list_sort(&force_grouped_idx, list, evlist__cmp);
2067 
2068 	/*
2069 	 * Recompute groups, splitting for PMUs and adding groups for events
2070 	 * that require them.
2071 	 */
2072 	idx = 0;
2073 	list_for_each_entry(pos, list, core.node) {
2074 		const struct evsel *pos_leader = evsel__leader(pos);
2075 		const char *pos_pmu_name = pos->group_pmu_name;
2076 		const char *cur_leader_pmu_name;
2077 		bool pos_force_grouped = force_grouped_idx != -1 &&
2078 			arch_evsel__must_be_in_group(pos);
2079 
2080 		/* Reset index and nr_members. */
2081 		if (pos->core.idx != idx)
2082 			idx_changed = true;
2083 		pos->core.idx = idx++;
2084 		pos->core.nr_members = 0;
2085 
2086 		/*
2087 		 * Set the group leader respecting the given groupings and that
2088 		 * groups can't span PMUs.
2089 		 */
2090 		if (!cur_leader)
2091 			cur_leader = pos;
2092 
2093 		cur_leader_pmu_name = cur_leader->group_pmu_name;
2094 		if ((cur_leaders_grp != pos->core.leader &&
2095 		     (!pos_force_grouped || !cur_leader_force_grouped)) ||
2096 		    strcmp(cur_leader_pmu_name, pos_pmu_name)) {
2097 			/* Event is for a different group/PMU than last. */
2098 			cur_leader = pos;
2099 			/*
2100 			 * Remember the leader's group before it is overwritten,
2101 			 * so that later events match as being in the same
2102 			 * group.
2103 			 */
2104 			cur_leaders_grp = pos->core.leader;
2105 			/*
2106 			 * Avoid forcing events into groups with events that
2107 			 * don't need to be in the group.
2108 			 */
2109 			cur_leader_force_grouped = pos_force_grouped;
2110 		}
2111 		if (pos_leader != cur_leader) {
2112 			/* The leader changed so update it. */
2113 			evsel__set_leader(pos, cur_leader);
2114 		}
2115 	}
2116 	list_for_each_entry(pos, list, core.node) {
2117 		struct evsel *pos_leader = evsel__leader(pos);
2118 
2119 		if (pos == pos_leader)
2120 			num_leaders++;
2121 		pos_leader->core.nr_members++;
2122 	}
2123 	return (idx_changed || num_leaders != orig_num_leaders) ? 1 : 0;
2124 }
2125 
2126 int __parse_events(struct evlist *evlist, const char *str, const char *pmu_filter,
2127 		   struct parse_events_error *err, struct perf_pmu *fake_pmu,
2128 		   bool warn_if_reordered, bool fake_tp)
2129 {
2130 	struct parse_events_state parse_state = {
2131 		.list	  = LIST_HEAD_INIT(parse_state.list),
2132 		.idx	  = evlist->core.nr_entries,
2133 		.error	  = err,
2134 		.stoken	  = PE_START_EVENTS,
2135 		.fake_pmu = fake_pmu,
2136 		.fake_tp  = fake_tp,
2137 		.pmu_filter = pmu_filter,
2138 		.match_legacy_cache_terms = true,
2139 	};
2140 	int ret, ret2;
2141 
2142 	ret = parse_events__scanner(str, /*input=*/ NULL, &parse_state);
2143 
2144 	if (!ret && list_empty(&parse_state.list)) {
2145 		WARN_ONCE(true, "WARNING: event parser found nothing\n");
2146 		return -1;
2147 	}
2148 
2149 	ret2 = parse_events__sort_events_and_fix_groups(&parse_state.list);
2150 	if (ret2 < 0)
2151 		return ret;
2152 
2153 	if (ret2 && warn_if_reordered && !parse_state.wild_card_pmus)
2154 		pr_warning("WARNING: events were regrouped to match PMUs\n");
2155 
2156 	/*
2157 	 * Add list to the evlist even with errors to allow callers to clean up.
2158 	 */
2159 	evlist__splice_list_tail(evlist, &parse_state.list);
2160 
2161 	if (!ret) {
2162 		struct evsel *last;
2163 
2164 		last = evlist__last(evlist);
2165 		last->cmdline_group_boundary = true;
2166 
2167 		return 0;
2168 	}
2169 
2170 	/*
2171 	 * There are 2 users - builtin-record and builtin-test objects.
2172 	 * Both call evlist__delete in case of error, so we dont
2173 	 * need to bother.
2174 	 */
2175 	return ret;
2176 }
2177 
2178 int parse_event(struct evlist *evlist, const char *str)
2179 {
2180 	struct parse_events_error err;
2181 	int ret;
2182 
2183 	parse_events_error__init(&err);
2184 	ret = parse_events(evlist, str, &err);
2185 	parse_events_error__exit(&err);
2186 	return ret;
2187 }
2188 
2189 struct parse_events_error_entry {
2190 	/** @list: The list the error is part of. */
2191 	struct list_head list;
2192 	/** @idx: index in the parsed string */
2193 	int   idx;
2194 	/** @str: string to display at the index */
2195 	char *str;
2196 	/** @help: optional help string */
2197 	char *help;
2198 };
2199 
2200 void parse_events_error__init(struct parse_events_error *err)
2201 {
2202 	INIT_LIST_HEAD(&err->list);
2203 }
2204 
2205 void parse_events_error__exit(struct parse_events_error *err)
2206 {
2207 	struct parse_events_error_entry *pos, *tmp;
2208 
2209 	list_for_each_entry_safe(pos, tmp, &err->list, list) {
2210 		zfree(&pos->str);
2211 		zfree(&pos->help);
2212 		list_del_init(&pos->list);
2213 		free(pos);
2214 	}
2215 }
2216 
2217 void parse_events_error__handle(struct parse_events_error *err, int idx,
2218 				char *str, char *help)
2219 {
2220 	struct parse_events_error_entry *entry;
2221 
2222 	if (WARN(!str || !err, "WARNING: failed to provide error string or struct\n"))
2223 		goto out_free;
2224 
2225 	entry = zalloc(sizeof(*entry));
2226 	if (!entry) {
2227 		pr_err("Failed to allocate memory for event parsing error: %s (%s)\n",
2228 			str, help ?: "<no help>");
2229 		goto out_free;
2230 	}
2231 	entry->idx = idx;
2232 	entry->str = str;
2233 	entry->help = help;
2234 	list_add(&entry->list, &err->list);
2235 	return;
2236 out_free:
2237 	free(str);
2238 	free(help);
2239 }
2240 
2241 #define MAX_WIDTH 1000
2242 static int get_term_width(void)
2243 {
2244 	struct winsize ws;
2245 
2246 	get_term_dimensions(&ws);
2247 	return ws.ws_col > MAX_WIDTH ? MAX_WIDTH : ws.ws_col;
2248 }
2249 
2250 static void __parse_events_error__print(int err_idx, const char *err_str,
2251 					const char *err_help, const char *event)
2252 {
2253 	const char *str = "invalid or unsupported event: ";
2254 	char _buf[MAX_WIDTH];
2255 	char *buf = (char *) event;
2256 	int idx = 0;
2257 	if (err_str) {
2258 		/* -2 for extra '' in the final fprintf */
2259 		int width       = get_term_width() - 2;
2260 		int len_event   = strlen(event);
2261 		int len_str, max_len, cut = 0;
2262 
2263 		/*
2264 		 * Maximum error index indent, we will cut
2265 		 * the event string if it's bigger.
2266 		 */
2267 		int max_err_idx = 13;
2268 
2269 		/*
2270 		 * Let's be specific with the message when
2271 		 * we have the precise error.
2272 		 */
2273 		str     = "event syntax error: ";
2274 		len_str = strlen(str);
2275 		max_len = width - len_str;
2276 
2277 		buf = _buf;
2278 
2279 		/* We're cutting from the beginning. */
2280 		if (err_idx > max_err_idx)
2281 			cut = err_idx - max_err_idx;
2282 
2283 		strncpy(buf, event + cut, max_len);
2284 
2285 		/* Mark cut parts with '..' on both sides. */
2286 		if (cut)
2287 			buf[0] = buf[1] = '.';
2288 
2289 		if ((len_event - cut) > max_len) {
2290 			buf[max_len - 1] = buf[max_len - 2] = '.';
2291 			buf[max_len] = 0;
2292 		}
2293 
2294 		idx = len_str + err_idx - cut;
2295 	}
2296 
2297 	fprintf(stderr, "%s'%s'\n", str, buf);
2298 	if (idx) {
2299 		fprintf(stderr, "%*s\\___ %s\n", idx + 1, "", err_str);
2300 		if (err_help)
2301 			fprintf(stderr, "\n%s\n", err_help);
2302 	}
2303 }
2304 
2305 void parse_events_error__print(const struct parse_events_error *err,
2306 			       const char *event)
2307 {
2308 	struct parse_events_error_entry *pos;
2309 	bool first = true;
2310 
2311 	list_for_each_entry(pos, &err->list, list) {
2312 		if (!first)
2313 			fputs("\n", stderr);
2314 		__parse_events_error__print(pos->idx, pos->str, pos->help, event);
2315 		first = false;
2316 	}
2317 }
2318 
2319 /*
2320  * In the list of errors err, do any of the error strings (str) contain the
2321  * given needle string?
2322  */
2323 bool parse_events_error__contains(const struct parse_events_error *err,
2324 				  const char *needle)
2325 {
2326 	struct parse_events_error_entry *pos;
2327 
2328 	list_for_each_entry(pos, &err->list, list) {
2329 		if (strstr(pos->str, needle) != NULL)
2330 			return true;
2331 	}
2332 	return false;
2333 }
2334 
2335 #undef MAX_WIDTH
2336 
2337 int parse_events_option(const struct option *opt, const char *str,
2338 			int unset __maybe_unused)
2339 {
2340 	struct parse_events_option_args *args = opt->value;
2341 	struct parse_events_error err;
2342 	int ret;
2343 
2344 	parse_events_error__init(&err);
2345 	ret = __parse_events(*args->evlistp, str, args->pmu_filter, &err,
2346 			     /*fake_pmu=*/NULL, /*warn_if_reordered=*/true,
2347 			     /*fake_tp=*/false);
2348 
2349 	if (ret) {
2350 		parse_events_error__print(&err, str);
2351 		fprintf(stderr, "Run 'perf list' for a list of valid events\n");
2352 	}
2353 	parse_events_error__exit(&err);
2354 
2355 	return ret;
2356 }
2357 
2358 int parse_events_option_new_evlist(const struct option *opt, const char *str, int unset)
2359 {
2360 	struct parse_events_option_args *args = opt->value;
2361 	int ret;
2362 
2363 	if (*args->evlistp == NULL) {
2364 		*args->evlistp = evlist__new();
2365 
2366 		if (*args->evlistp == NULL) {
2367 			fprintf(stderr, "Not enough memory to create evlist\n");
2368 			return -1;
2369 		}
2370 	}
2371 	ret = parse_events_option(opt, str, unset);
2372 	if (ret) {
2373 		evlist__delete(*args->evlistp);
2374 		*args->evlistp = NULL;
2375 	}
2376 
2377 	return ret;
2378 }
2379 
2380 static int
2381 foreach_evsel_in_last_glob(struct evlist *evlist,
2382 			   int (*func)(struct evsel *evsel,
2383 				       const void *arg),
2384 			   const void *arg)
2385 {
2386 	struct evsel *last = NULL;
2387 	int err;
2388 
2389 	/*
2390 	 * Don't return when list_empty, give func a chance to report
2391 	 * error when it found last == NULL.
2392 	 *
2393 	 * So no need to WARN here, let *func do this.
2394 	 */
2395 	if (evlist->core.nr_entries > 0)
2396 		last = evlist__last(evlist);
2397 
2398 	do {
2399 		err = (*func)(last, arg);
2400 		if (err)
2401 			return -1;
2402 		if (!last)
2403 			return 0;
2404 
2405 		if (last->core.node.prev == &evlist->core.entries)
2406 			return 0;
2407 		last = list_entry(last->core.node.prev, struct evsel, core.node);
2408 	} while (!last->cmdline_group_boundary);
2409 
2410 	return 0;
2411 }
2412 
2413 static int set_filter(struct evsel *evsel, const void *arg)
2414 {
2415 	const char *str = arg;
2416 	bool found = false;
2417 	int nr_addr_filters = 0;
2418 	struct perf_pmu *pmu = NULL;
2419 
2420 	if (evsel == NULL) {
2421 		fprintf(stderr,
2422 			"--filter option should follow a -e tracepoint or HW tracer option\n");
2423 		return -1;
2424 	}
2425 
2426 	if (evsel->core.attr.type == PERF_TYPE_TRACEPOINT) {
2427 		if (evsel__append_tp_filter(evsel, str) < 0) {
2428 			fprintf(stderr,
2429 				"not enough memory to hold filter string\n");
2430 			return -1;
2431 		}
2432 
2433 		return 0;
2434 	}
2435 
2436 	while ((pmu = perf_pmus__scan(pmu)) != NULL)
2437 		if (pmu->type == evsel->core.attr.type) {
2438 			found = true;
2439 			break;
2440 		}
2441 
2442 	if (found)
2443 		perf_pmu__scan_file(pmu, "nr_addr_filters",
2444 				    "%d", &nr_addr_filters);
2445 
2446 	if (!nr_addr_filters)
2447 		return perf_bpf_filter__parse(&evsel->bpf_filters, str);
2448 
2449 	if (evsel__append_addr_filter(evsel, str) < 0) {
2450 		fprintf(stderr,
2451 			"not enough memory to hold filter string\n");
2452 		return -1;
2453 	}
2454 
2455 	return 0;
2456 }
2457 
2458 int parse_filter(const struct option *opt, const char *str,
2459 		 int unset __maybe_unused)
2460 {
2461 	struct evlist *evlist = *(struct evlist **)opt->value;
2462 
2463 	return foreach_evsel_in_last_glob(evlist, set_filter,
2464 					  (const void *)str);
2465 }
2466 
2467 static int add_exclude_perf_filter(struct evsel *evsel,
2468 				   const void *arg __maybe_unused)
2469 {
2470 	char new_filter[64];
2471 
2472 	if (evsel == NULL || evsel->core.attr.type != PERF_TYPE_TRACEPOINT) {
2473 		fprintf(stderr,
2474 			"--exclude-perf option should follow a -e tracepoint option\n");
2475 		return -1;
2476 	}
2477 
2478 	snprintf(new_filter, sizeof(new_filter), "common_pid != %d", getpid());
2479 
2480 	if (evsel__append_tp_filter(evsel, new_filter) < 0) {
2481 		fprintf(stderr,
2482 			"not enough memory to hold filter string\n");
2483 		return -1;
2484 	}
2485 
2486 	return 0;
2487 }
2488 
2489 int exclude_perf(const struct option *opt,
2490 		 const char *arg __maybe_unused,
2491 		 int unset __maybe_unused)
2492 {
2493 	struct evlist *evlist = *(struct evlist **)opt->value;
2494 
2495 	return foreach_evsel_in_last_glob(evlist, add_exclude_perf_filter,
2496 					  NULL);
2497 }
2498 
2499 int parse_events__is_hardcoded_term(struct parse_events_term *term)
2500 {
2501 	return term->type_term != PARSE_EVENTS__TERM_TYPE_USER;
2502 }
2503 
2504 static int new_term(struct parse_events_term **_term,
2505 		    struct parse_events_term *temp,
2506 		    char *str, u64 num)
2507 {
2508 	struct parse_events_term *term;
2509 
2510 	term = malloc(sizeof(*term));
2511 	if (!term)
2512 		return -ENOMEM;
2513 
2514 	*term = *temp;
2515 	INIT_LIST_HEAD(&term->list);
2516 	term->weak = false;
2517 
2518 	switch (term->type_val) {
2519 	case PARSE_EVENTS__TERM_TYPE_NUM:
2520 		term->val.num = num;
2521 		break;
2522 	case PARSE_EVENTS__TERM_TYPE_STR:
2523 		term->val.str = str;
2524 		break;
2525 	default:
2526 		free(term);
2527 		return -EINVAL;
2528 	}
2529 
2530 	*_term = term;
2531 	return 0;
2532 }
2533 
2534 int parse_events_term__num(struct parse_events_term **term,
2535 			   enum parse_events__term_type type_term,
2536 			   const char *config, u64 num,
2537 			   bool no_value,
2538 			   void *loc_term_, void *loc_val_)
2539 {
2540 	YYLTYPE *loc_term = loc_term_;
2541 	YYLTYPE *loc_val = loc_val_;
2542 
2543 	struct parse_events_term temp = {
2544 		.type_val  = PARSE_EVENTS__TERM_TYPE_NUM,
2545 		.type_term = type_term,
2546 		.config    = config ? : strdup(config_term_name(type_term)),
2547 		.no_value  = no_value,
2548 		.err_term  = loc_term ? loc_term->first_column : 0,
2549 		.err_val   = loc_val  ? loc_val->first_column  : 0,
2550 	};
2551 
2552 	return new_term(term, &temp, /*str=*/NULL, num);
2553 }
2554 
2555 int parse_events_term__str(struct parse_events_term **term,
2556 			   enum parse_events__term_type type_term,
2557 			   char *config, char *str,
2558 			   void *loc_term_, void *loc_val_)
2559 {
2560 	YYLTYPE *loc_term = loc_term_;
2561 	YYLTYPE *loc_val = loc_val_;
2562 
2563 	struct parse_events_term temp = {
2564 		.type_val  = PARSE_EVENTS__TERM_TYPE_STR,
2565 		.type_term = type_term,
2566 		.config    = config,
2567 		.err_term  = loc_term ? loc_term->first_column : 0,
2568 		.err_val   = loc_val  ? loc_val->first_column  : 0,
2569 	};
2570 
2571 	return new_term(term, &temp, str, /*num=*/0);
2572 }
2573 
2574 int parse_events_term__term(struct parse_events_term **term,
2575 			    enum parse_events__term_type term_lhs,
2576 			    enum parse_events__term_type term_rhs,
2577 			    void *loc_term, void *loc_val)
2578 {
2579 	return parse_events_term__str(term, term_lhs, NULL,
2580 				      strdup(config_term_name(term_rhs)),
2581 				      loc_term, loc_val);
2582 }
2583 
2584 int parse_events_term__clone(struct parse_events_term **new,
2585 			     const struct parse_events_term *term)
2586 {
2587 	char *str;
2588 	struct parse_events_term temp = *term;
2589 
2590 	temp.used = false;
2591 	if (term->config) {
2592 		temp.config = strdup(term->config);
2593 		if (!temp.config)
2594 			return -ENOMEM;
2595 	}
2596 	if (term->type_val == PARSE_EVENTS__TERM_TYPE_NUM)
2597 		return new_term(new, &temp, /*str=*/NULL, term->val.num);
2598 
2599 	str = strdup(term->val.str);
2600 	if (!str) {
2601 		zfree(&temp.config);
2602 		return -ENOMEM;
2603 	}
2604 	return new_term(new, &temp, str, /*num=*/0);
2605 }
2606 
2607 void parse_events_term__delete(struct parse_events_term *term)
2608 {
2609 	if (term->type_val != PARSE_EVENTS__TERM_TYPE_NUM)
2610 		zfree(&term->val.str);
2611 
2612 	zfree(&term->config);
2613 	free(term);
2614 }
2615 
2616 static int parse_events_terms__copy(const struct parse_events_terms *src,
2617 				    struct parse_events_terms *dest)
2618 {
2619 	struct parse_events_term *term;
2620 
2621 	list_for_each_entry (term, &src->terms, list) {
2622 		struct parse_events_term *n;
2623 		int ret;
2624 
2625 		ret = parse_events_term__clone(&n, term);
2626 		if (ret)
2627 			return ret;
2628 
2629 		list_add_tail(&n->list, &dest->terms);
2630 	}
2631 	return 0;
2632 }
2633 
2634 void parse_events_terms__init(struct parse_events_terms *terms)
2635 {
2636 	INIT_LIST_HEAD(&terms->terms);
2637 }
2638 
2639 void parse_events_terms__exit(struct parse_events_terms *terms)
2640 {
2641 	struct parse_events_term *term, *h;
2642 
2643 	list_for_each_entry_safe(term, h, &terms->terms, list) {
2644 		list_del_init(&term->list);
2645 		parse_events_term__delete(term);
2646 	}
2647 }
2648 
2649 void parse_events_terms__delete(struct parse_events_terms *terms)
2650 {
2651 	if (!terms)
2652 		return;
2653 	parse_events_terms__exit(terms);
2654 	free(terms);
2655 }
2656 
2657 int parse_events_terms__to_strbuf(const struct parse_events_terms *terms, struct strbuf *sb)
2658 {
2659 	struct parse_events_term *term;
2660 	bool first = true;
2661 
2662 	if (!terms)
2663 		return 0;
2664 
2665 	list_for_each_entry(term, &terms->terms, list) {
2666 		int ret;
2667 
2668 		if (!first) {
2669 			ret = strbuf_addch(sb, ',');
2670 			if (ret < 0)
2671 				return ret;
2672 		}
2673 		first = false;
2674 
2675 		if (term->type_val == PARSE_EVENTS__TERM_TYPE_NUM)
2676 			if (term->no_value) {
2677 				assert(term->val.num == 1);
2678 				ret = strbuf_addf(sb, "%s", term->config);
2679 			} else
2680 				ret = strbuf_addf(sb, "%s=%#"PRIx64, term->config, term->val.num);
2681 		else if (term->type_val == PARSE_EVENTS__TERM_TYPE_STR) {
2682 			if (term->config) {
2683 				ret = strbuf_addf(sb, "%s=", term->config);
2684 				if (ret < 0)
2685 					return ret;
2686 			} else if ((unsigned int)term->type_term < __PARSE_EVENTS__TERM_TYPE_NR) {
2687 				ret = strbuf_addf(sb, "%s=", config_term_name(term->type_term));
2688 				if (ret < 0)
2689 					return ret;
2690 			}
2691 			assert(!term->no_value);
2692 			ret = strbuf_addf(sb, "%s", term->val.str);
2693 		}
2694 		if (ret < 0)
2695 			return ret;
2696 	}
2697 	return 0;
2698 }
2699 
2700 static void config_terms_list(char *buf, size_t buf_sz)
2701 {
2702 	int i;
2703 	bool first = true;
2704 
2705 	buf[0] = '\0';
2706 	for (i = 0; i < __PARSE_EVENTS__TERM_TYPE_NR; i++) {
2707 		const char *name = config_term_name(i);
2708 
2709 		if (!config_term_avail(i, NULL))
2710 			continue;
2711 		if (!name)
2712 			continue;
2713 		if (name[0] == '<')
2714 			continue;
2715 
2716 		if (strlen(buf) + strlen(name) + 2 >= buf_sz)
2717 			return;
2718 
2719 		if (!first)
2720 			strcat(buf, ",");
2721 		else
2722 			first = false;
2723 		strcat(buf, name);
2724 	}
2725 }
2726 
2727 /*
2728  * Return string contains valid config terms of an event.
2729  * @additional_terms: For terms such as PMU sysfs terms.
2730  */
2731 char *parse_events_formats_error_string(char *additional_terms)
2732 {
2733 	char *str;
2734 	/* "no-overwrite" is the longest name */
2735 	char static_terms[__PARSE_EVENTS__TERM_TYPE_NR *
2736 			  (sizeof("no-overwrite") - 1)];
2737 
2738 	config_terms_list(static_terms, sizeof(static_terms));
2739 	/* valid terms */
2740 	if (additional_terms) {
2741 		if (asprintf(&str, "valid terms: %s,%s",
2742 			     additional_terms, static_terms) < 0)
2743 			goto fail;
2744 	} else {
2745 		if (asprintf(&str, "valid terms: %s", static_terms) < 0)
2746 			goto fail;
2747 	}
2748 	return str;
2749 
2750 fail:
2751 	return NULL;
2752 }
2753