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