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