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