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