libperf: Move nr_members from perf's evsel to libperf's perf_evsel
[linux-2.6-block.git] / tools / perf / util / parse-events.c
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 <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 };
967
968 static bool config_term_shrinked;
969
970 static bool
971 config_term_avail(int term_type, struct parse_events_error *err)
972 {
973         if (term_type < 0 || term_type >= __PARSE_EVENTS__TERM_TYPE_NR) {
974                 err->str = strdup("Invalid term_type");
975                 return false;
976         }
977         if (!config_term_shrinked)
978                 return true;
979
980         switch (term_type) {
981         case PARSE_EVENTS__TERM_TYPE_CONFIG:
982         case PARSE_EVENTS__TERM_TYPE_CONFIG1:
983         case PARSE_EVENTS__TERM_TYPE_CONFIG2:
984         case PARSE_EVENTS__TERM_TYPE_NAME:
985         case PARSE_EVENTS__TERM_TYPE_SAMPLE_PERIOD:
986         case PARSE_EVENTS__TERM_TYPE_PERCORE:
987                 return true;
988         default:
989                 if (!err)
990                         return false;
991
992                 /* term_type is validated so indexing is safe */
993                 if (asprintf(&err->str, "'%s' is not usable in 'perf stat'",
994                              config_term_names[term_type]) < 0)
995                         err->str = NULL;
996                 return false;
997         }
998 }
999
1000 void parse_events__shrink_config_terms(void)
1001 {
1002         config_term_shrinked = true;
1003 }
1004
1005 static int config_term_common(struct perf_event_attr *attr,
1006                               struct parse_events_term *term,
1007                               struct parse_events_error *err)
1008 {
1009 #define CHECK_TYPE_VAL(type)                                               \
1010 do {                                                                       \
1011         if (check_type_val(term, err, PARSE_EVENTS__TERM_TYPE_ ## type)) \
1012                 return -EINVAL;                                            \
1013 } while (0)
1014
1015         switch (term->type_term) {
1016         case PARSE_EVENTS__TERM_TYPE_CONFIG:
1017                 CHECK_TYPE_VAL(NUM);
1018                 attr->config = term->val.num;
1019                 break;
1020         case PARSE_EVENTS__TERM_TYPE_CONFIG1:
1021                 CHECK_TYPE_VAL(NUM);
1022                 attr->config1 = term->val.num;
1023                 break;
1024         case PARSE_EVENTS__TERM_TYPE_CONFIG2:
1025                 CHECK_TYPE_VAL(NUM);
1026                 attr->config2 = term->val.num;
1027                 break;
1028         case PARSE_EVENTS__TERM_TYPE_SAMPLE_PERIOD:
1029                 CHECK_TYPE_VAL(NUM);
1030                 break;
1031         case PARSE_EVENTS__TERM_TYPE_SAMPLE_FREQ:
1032                 CHECK_TYPE_VAL(NUM);
1033                 break;
1034         case PARSE_EVENTS__TERM_TYPE_BRANCH_SAMPLE_TYPE:
1035                 CHECK_TYPE_VAL(STR);
1036                 if (strcmp(term->val.str, "no") &&
1037                     parse_branch_str(term->val.str, &attr->branch_sample_type)) {
1038                         err->str = strdup("invalid branch sample type");
1039                         err->idx = term->err_val;
1040                         return -EINVAL;
1041                 }
1042                 break;
1043         case PARSE_EVENTS__TERM_TYPE_TIME:
1044                 CHECK_TYPE_VAL(NUM);
1045                 if (term->val.num > 1) {
1046                         err->str = strdup("expected 0 or 1");
1047                         err->idx = term->err_val;
1048                         return -EINVAL;
1049                 }
1050                 break;
1051         case PARSE_EVENTS__TERM_TYPE_CALLGRAPH:
1052                 CHECK_TYPE_VAL(STR);
1053                 break;
1054         case PARSE_EVENTS__TERM_TYPE_STACKSIZE:
1055                 CHECK_TYPE_VAL(NUM);
1056                 break;
1057         case PARSE_EVENTS__TERM_TYPE_INHERIT:
1058                 CHECK_TYPE_VAL(NUM);
1059                 break;
1060         case PARSE_EVENTS__TERM_TYPE_NOINHERIT:
1061                 CHECK_TYPE_VAL(NUM);
1062                 break;
1063         case PARSE_EVENTS__TERM_TYPE_OVERWRITE:
1064                 CHECK_TYPE_VAL(NUM);
1065                 break;
1066         case PARSE_EVENTS__TERM_TYPE_NOOVERWRITE:
1067                 CHECK_TYPE_VAL(NUM);
1068                 break;
1069         case PARSE_EVENTS__TERM_TYPE_NAME:
1070                 CHECK_TYPE_VAL(STR);
1071                 break;
1072         case PARSE_EVENTS__TERM_TYPE_MAX_STACK:
1073                 CHECK_TYPE_VAL(NUM);
1074                 break;
1075         case PARSE_EVENTS__TERM_TYPE_MAX_EVENTS:
1076                 CHECK_TYPE_VAL(NUM);
1077                 break;
1078         case PARSE_EVENTS__TERM_TYPE_PERCORE:
1079                 CHECK_TYPE_VAL(NUM);
1080                 if ((unsigned int)term->val.num > 1) {
1081                         err->str = strdup("expected 0 or 1");
1082                         err->idx = term->err_val;
1083                         return -EINVAL;
1084                 }
1085                 break;
1086         default:
1087                 err->str = strdup("unknown term");
1088                 err->idx = term->err_term;
1089                 err->help = parse_events_formats_error_string(NULL);
1090                 return -EINVAL;
1091         }
1092
1093         /*
1094          * Check term availbility after basic checking so
1095          * PARSE_EVENTS__TERM_TYPE_USER can be found and filtered.
1096          *
1097          * If check availbility at the entry of this function,
1098          * user will see "'<sysfs term>' is not usable in 'perf stat'"
1099          * if an invalid config term is provided for legacy events
1100          * (for example, instructions/badterm/...), which is confusing.
1101          */
1102         if (!config_term_avail(term->type_term, err))
1103                 return -EINVAL;
1104         return 0;
1105 #undef CHECK_TYPE_VAL
1106 }
1107
1108 static int config_term_pmu(struct perf_event_attr *attr,
1109                            struct parse_events_term *term,
1110                            struct parse_events_error *err)
1111 {
1112         if (term->type_term == PARSE_EVENTS__TERM_TYPE_USER ||
1113             term->type_term == PARSE_EVENTS__TERM_TYPE_DRV_CFG)
1114                 /*
1115                  * Always succeed for sysfs terms, as we dont know
1116                  * at this point what type they need to have.
1117                  */
1118                 return 0;
1119         else
1120                 return config_term_common(attr, term, err);
1121 }
1122
1123 static int config_term_tracepoint(struct perf_event_attr *attr,
1124                                   struct parse_events_term *term,
1125                                   struct parse_events_error *err)
1126 {
1127         switch (term->type_term) {
1128         case PARSE_EVENTS__TERM_TYPE_CALLGRAPH:
1129         case PARSE_EVENTS__TERM_TYPE_STACKSIZE:
1130         case PARSE_EVENTS__TERM_TYPE_INHERIT:
1131         case PARSE_EVENTS__TERM_TYPE_NOINHERIT:
1132         case PARSE_EVENTS__TERM_TYPE_MAX_STACK:
1133         case PARSE_EVENTS__TERM_TYPE_MAX_EVENTS:
1134         case PARSE_EVENTS__TERM_TYPE_OVERWRITE:
1135         case PARSE_EVENTS__TERM_TYPE_NOOVERWRITE:
1136                 return config_term_common(attr, term, err);
1137         default:
1138                 if (err) {
1139                         err->idx = term->err_term;
1140                         err->str = strdup("unknown term");
1141                         err->help = strdup("valid terms: call-graph,stack-size\n");
1142                 }
1143                 return -EINVAL;
1144         }
1145
1146         return 0;
1147 }
1148
1149 static int config_attr(struct perf_event_attr *attr,
1150                        struct list_head *head,
1151                        struct parse_events_error *err,
1152                        config_term_func_t config_term)
1153 {
1154         struct parse_events_term *term;
1155
1156         list_for_each_entry(term, head, list)
1157                 if (config_term(attr, term, err))
1158                         return -EINVAL;
1159
1160         return 0;
1161 }
1162
1163 static int get_config_terms(struct list_head *head_config,
1164                             struct list_head *head_terms __maybe_unused)
1165 {
1166 #define ADD_CONFIG_TERM(__type, __name, __val)                  \
1167 do {                                                            \
1168         struct perf_evsel_config_term *__t;                     \
1169                                                                 \
1170         __t = zalloc(sizeof(*__t));                             \
1171         if (!__t)                                               \
1172                 return -ENOMEM;                                 \
1173                                                                 \
1174         INIT_LIST_HEAD(&__t->list);                             \
1175         __t->type       = PERF_EVSEL__CONFIG_TERM_ ## __type;   \
1176         __t->val.__name = __val;                                \
1177         __t->weak       = term->weak;                           \
1178         list_add_tail(&__t->list, head_terms);                  \
1179 } while (0)
1180
1181         struct parse_events_term *term;
1182
1183         list_for_each_entry(term, head_config, list) {
1184                 switch (term->type_term) {
1185                 case PARSE_EVENTS__TERM_TYPE_SAMPLE_PERIOD:
1186                         ADD_CONFIG_TERM(PERIOD, period, term->val.num);
1187                         break;
1188                 case PARSE_EVENTS__TERM_TYPE_SAMPLE_FREQ:
1189                         ADD_CONFIG_TERM(FREQ, freq, term->val.num);
1190                         break;
1191                 case PARSE_EVENTS__TERM_TYPE_TIME:
1192                         ADD_CONFIG_TERM(TIME, time, term->val.num);
1193                         break;
1194                 case PARSE_EVENTS__TERM_TYPE_CALLGRAPH:
1195                         ADD_CONFIG_TERM(CALLGRAPH, callgraph, term->val.str);
1196                         break;
1197                 case PARSE_EVENTS__TERM_TYPE_BRANCH_SAMPLE_TYPE:
1198                         ADD_CONFIG_TERM(BRANCH, branch, term->val.str);
1199                         break;
1200                 case PARSE_EVENTS__TERM_TYPE_STACKSIZE:
1201                         ADD_CONFIG_TERM(STACK_USER, stack_user, term->val.num);
1202                         break;
1203                 case PARSE_EVENTS__TERM_TYPE_INHERIT:
1204                         ADD_CONFIG_TERM(INHERIT, inherit, term->val.num ? 1 : 0);
1205                         break;
1206                 case PARSE_EVENTS__TERM_TYPE_NOINHERIT:
1207                         ADD_CONFIG_TERM(INHERIT, inherit, term->val.num ? 0 : 1);
1208                         break;
1209                 case PARSE_EVENTS__TERM_TYPE_MAX_STACK:
1210                         ADD_CONFIG_TERM(MAX_STACK, max_stack, term->val.num);
1211                         break;
1212                 case PARSE_EVENTS__TERM_TYPE_MAX_EVENTS:
1213                         ADD_CONFIG_TERM(MAX_EVENTS, max_events, term->val.num);
1214                         break;
1215                 case PARSE_EVENTS__TERM_TYPE_OVERWRITE:
1216                         ADD_CONFIG_TERM(OVERWRITE, overwrite, term->val.num ? 1 : 0);
1217                         break;
1218                 case PARSE_EVENTS__TERM_TYPE_NOOVERWRITE:
1219                         ADD_CONFIG_TERM(OVERWRITE, overwrite, term->val.num ? 0 : 1);
1220                         break;
1221                 case PARSE_EVENTS__TERM_TYPE_DRV_CFG:
1222                         ADD_CONFIG_TERM(DRV_CFG, drv_cfg, term->val.str);
1223                         break;
1224                 case PARSE_EVENTS__TERM_TYPE_PERCORE:
1225                         ADD_CONFIG_TERM(PERCORE, percore,
1226                                         term->val.num ? true : false);
1227                         break;
1228                 default:
1229                         break;
1230                 }
1231         }
1232 #undef ADD_EVSEL_CONFIG
1233         return 0;
1234 }
1235
1236 int parse_events_add_tracepoint(struct list_head *list, int *idx,
1237                                 const char *sys, const char *event,
1238                                 struct parse_events_error *err,
1239                                 struct list_head *head_config)
1240 {
1241         if (head_config) {
1242                 struct perf_event_attr attr;
1243
1244                 if (config_attr(&attr, head_config, err,
1245                                 config_term_tracepoint))
1246                         return -EINVAL;
1247         }
1248
1249         if (strpbrk(sys, "*?"))
1250                 return add_tracepoint_multi_sys(list, idx, sys, event,
1251                                                 err, head_config);
1252         else
1253                 return add_tracepoint_event(list, idx, sys, event,
1254                                             err, head_config);
1255 }
1256
1257 int parse_events_add_numeric(struct parse_events_state *parse_state,
1258                              struct list_head *list,
1259                              u32 type, u64 config,
1260                              struct list_head *head_config)
1261 {
1262         struct perf_event_attr attr;
1263         LIST_HEAD(config_terms);
1264
1265         memset(&attr, 0, sizeof(attr));
1266         attr.type = type;
1267         attr.config = config;
1268
1269         if (head_config) {
1270                 if (config_attr(&attr, head_config, parse_state->error,
1271                                 config_term_common))
1272                         return -EINVAL;
1273
1274                 if (get_config_terms(head_config, &config_terms))
1275                         return -ENOMEM;
1276         }
1277
1278         return add_event(list, &parse_state->idx, &attr,
1279                          get_config_name(head_config), &config_terms);
1280 }
1281
1282 int parse_events_add_tool(struct parse_events_state *parse_state,
1283                           struct list_head *list,
1284                           enum perf_tool_event tool_event)
1285 {
1286         return add_event_tool(list, &parse_state->idx, tool_event);
1287 }
1288
1289 static bool config_term_percore(struct list_head *config_terms)
1290 {
1291         struct perf_evsel_config_term *term;
1292
1293         list_for_each_entry(term, config_terms, list) {
1294                 if (term->type == PERF_EVSEL__CONFIG_TERM_PERCORE)
1295                         return term->val.percore;
1296         }
1297
1298         return false;
1299 }
1300
1301 int parse_events_add_pmu(struct parse_events_state *parse_state,
1302                          struct list_head *list, char *name,
1303                          struct list_head *head_config,
1304                          bool auto_merge_stats,
1305                          bool use_alias)
1306 {
1307         struct perf_event_attr attr;
1308         struct perf_pmu_info info;
1309         struct perf_pmu *pmu;
1310         struct evsel *evsel;
1311         struct parse_events_error *err = parse_state->error;
1312         bool use_uncore_alias;
1313         LIST_HEAD(config_terms);
1314
1315         pmu = perf_pmu__find(name);
1316         if (!pmu) {
1317                 if (asprintf(&err->str,
1318                                 "Cannot find PMU `%s'. Missing kernel support?",
1319                                 name) < 0)
1320                         err->str = NULL;
1321                 return -EINVAL;
1322         }
1323
1324         if (pmu->default_config) {
1325                 memcpy(&attr, pmu->default_config,
1326                        sizeof(struct perf_event_attr));
1327         } else {
1328                 memset(&attr, 0, sizeof(attr));
1329         }
1330
1331         use_uncore_alias = (pmu->is_uncore && use_alias);
1332
1333         if (!head_config) {
1334                 attr.type = pmu->type;
1335                 evsel = __add_event(list, &parse_state->idx, &attr, NULL, pmu, NULL,
1336                                     auto_merge_stats, NULL);
1337                 if (evsel) {
1338                         evsel->pmu_name = name;
1339                         evsel->use_uncore_alias = use_uncore_alias;
1340                         return 0;
1341                 } else {
1342                         return -ENOMEM;
1343                 }
1344         }
1345
1346         if (perf_pmu__check_alias(pmu, head_config, &info))
1347                 return -EINVAL;
1348
1349         /*
1350          * Configure hardcoded terms first, no need to check
1351          * return value when called with fail == 0 ;)
1352          */
1353         if (config_attr(&attr, head_config, parse_state->error, config_term_pmu))
1354                 return -EINVAL;
1355
1356         if (get_config_terms(head_config, &config_terms))
1357                 return -ENOMEM;
1358
1359         if (perf_pmu__config(pmu, &attr, head_config, parse_state->error))
1360                 return -EINVAL;
1361
1362         evsel = __add_event(list, &parse_state->idx, &attr,
1363                             get_config_name(head_config), pmu,
1364                             &config_terms, auto_merge_stats, NULL);
1365         if (evsel) {
1366                 evsel->unit = info.unit;
1367                 evsel->scale = info.scale;
1368                 evsel->per_pkg = info.per_pkg;
1369                 evsel->snapshot = info.snapshot;
1370                 evsel->metric_expr = info.metric_expr;
1371                 evsel->metric_name = info.metric_name;
1372                 evsel->pmu_name = name;
1373                 evsel->use_uncore_alias = use_uncore_alias;
1374                 evsel->percore = config_term_percore(&evsel->config_terms);
1375         }
1376
1377         return evsel ? 0 : -ENOMEM;
1378 }
1379
1380 int parse_events_multi_pmu_add(struct parse_events_state *parse_state,
1381                                char *str, struct list_head **listp)
1382 {
1383         struct list_head *head;
1384         struct parse_events_term *term;
1385         struct list_head *list;
1386         struct perf_pmu *pmu = NULL;
1387         int ok = 0;
1388
1389         *listp = NULL;
1390         /* Add it for all PMUs that support the alias */
1391         list = malloc(sizeof(struct list_head));
1392         if (!list)
1393                 return -1;
1394         INIT_LIST_HEAD(list);
1395         while ((pmu = perf_pmu__scan(pmu)) != NULL) {
1396                 struct perf_pmu_alias *alias;
1397
1398                 list_for_each_entry(alias, &pmu->aliases, list) {
1399                         if (!strcasecmp(alias->name, str)) {
1400                                 head = malloc(sizeof(struct list_head));
1401                                 if (!head)
1402                                         return -1;
1403                                 INIT_LIST_HEAD(head);
1404                                 if (parse_events_term__num(&term, PARSE_EVENTS__TERM_TYPE_USER,
1405                                                            str, 1, false, &str, NULL) < 0)
1406                                         return -1;
1407                                 list_add_tail(&term->list, head);
1408
1409                                 if (!parse_events_add_pmu(parse_state, list,
1410                                                           pmu->name, head,
1411                                                           true, true)) {
1412                                         pr_debug("%s -> %s/%s/\n", str,
1413                                                  pmu->name, alias->str);
1414                                         ok++;
1415                                 }
1416
1417                                 parse_events_terms__delete(head);
1418                         }
1419                 }
1420         }
1421         if (!ok)
1422                 return -1;
1423         *listp = list;
1424         return 0;
1425 }
1426
1427 int parse_events__modifier_group(struct list_head *list,
1428                                  char *event_mod)
1429 {
1430         return parse_events__modifier_event(list, event_mod, true);
1431 }
1432
1433 /*
1434  * Check if the two uncore PMUs are from the same uncore block
1435  * The format of the uncore PMU name is uncore_#blockname_#pmuidx
1436  */
1437 static bool is_same_uncore_block(const char *pmu_name_a, const char *pmu_name_b)
1438 {
1439         char *end_a, *end_b;
1440
1441         end_a = strrchr(pmu_name_a, '_');
1442         end_b = strrchr(pmu_name_b, '_');
1443
1444         if (!end_a || !end_b)
1445                 return false;
1446
1447         if ((end_a - pmu_name_a) != (end_b - pmu_name_b))
1448                 return false;
1449
1450         return (strncmp(pmu_name_a, pmu_name_b, end_a - pmu_name_a) == 0);
1451 }
1452
1453 static int
1454 parse_events__set_leader_for_uncore_aliase(char *name, struct list_head *list,
1455                                            struct parse_events_state *parse_state)
1456 {
1457         struct evsel *evsel, *leader;
1458         uintptr_t *leaders;
1459         bool is_leader = true;
1460         int i, nr_pmu = 0, total_members, ret = 0;
1461
1462         leader = list_first_entry(list, struct evsel, core.node);
1463         evsel = list_last_entry(list, struct evsel, core.node);
1464         total_members = evsel->idx - leader->idx + 1;
1465
1466         leaders = calloc(total_members, sizeof(uintptr_t));
1467         if (WARN_ON(!leaders))
1468                 return 0;
1469
1470         /*
1471          * Going through the whole group and doing sanity check.
1472          * All members must use alias, and be from the same uncore block.
1473          * Also, storing the leader events in an array.
1474          */
1475         __evlist__for_each_entry(list, evsel) {
1476
1477                 /* Only split the uncore group which members use alias */
1478                 if (!evsel->use_uncore_alias)
1479                         goto out;
1480
1481                 /* The events must be from the same uncore block */
1482                 if (!is_same_uncore_block(leader->pmu_name, evsel->pmu_name))
1483                         goto out;
1484
1485                 if (!is_leader)
1486                         continue;
1487                 /*
1488                  * If the event's PMU name starts to repeat, it must be a new
1489                  * event. That can be used to distinguish the leader from
1490                  * other members, even they have the same event name.
1491                  */
1492                 if ((leader != evsel) && (leader->pmu_name == evsel->pmu_name)) {
1493                         is_leader = false;
1494                         continue;
1495                 }
1496                 /* The name is always alias name */
1497                 WARN_ON(strcmp(leader->name, evsel->name));
1498
1499                 /* Store the leader event for each PMU */
1500                 leaders[nr_pmu++] = (uintptr_t) evsel;
1501         }
1502
1503         /* only one event alias */
1504         if (nr_pmu == total_members) {
1505                 parse_state->nr_groups--;
1506                 goto handled;
1507         }
1508
1509         /*
1510          * An uncore event alias is a joint name which means the same event
1511          * runs on all PMUs of a block.
1512          * Perf doesn't support mixed events from different PMUs in the same
1513          * group. The big group has to be split into multiple small groups
1514          * which only include the events from the same PMU.
1515          *
1516          * Here the uncore event aliases must be from the same uncore block.
1517          * The number of PMUs must be same for each alias. The number of new
1518          * small groups equals to the number of PMUs.
1519          * Setting the leader event for corresponding members in each group.
1520          */
1521         i = 0;
1522         __evlist__for_each_entry(list, evsel) {
1523                 if (i >= nr_pmu)
1524                         i = 0;
1525                 evsel->leader = (struct evsel *) leaders[i++];
1526         }
1527
1528         /* The number of members and group name are same for each group */
1529         for (i = 0; i < nr_pmu; i++) {
1530                 evsel = (struct evsel *) leaders[i];
1531                 evsel->core.nr_members = total_members / nr_pmu;
1532                 evsel->group_name = name ? strdup(name) : NULL;
1533         }
1534
1535         /* Take the new small groups into account */
1536         parse_state->nr_groups += nr_pmu - 1;
1537
1538 handled:
1539         ret = 1;
1540 out:
1541         free(leaders);
1542         return ret;
1543 }
1544
1545 void parse_events__set_leader(char *name, struct list_head *list,
1546                               struct parse_events_state *parse_state)
1547 {
1548         struct evsel *leader;
1549
1550         if (list_empty(list)) {
1551                 WARN_ONCE(true, "WARNING: failed to set leader: empty list");
1552                 return;
1553         }
1554
1555         if (parse_events__set_leader_for_uncore_aliase(name, list, parse_state))
1556                 return;
1557
1558         __perf_evlist__set_leader(list);
1559         leader = list_entry(list->next, struct evsel, core.node);
1560         leader->group_name = name ? strdup(name) : NULL;
1561 }
1562
1563 /* list_event is assumed to point to malloc'ed memory */
1564 void parse_events_update_lists(struct list_head *list_event,
1565                                struct list_head *list_all)
1566 {
1567         /*
1568          * Called for single event definition. Update the
1569          * 'all event' list, and reinit the 'single event'
1570          * list, for next event definition.
1571          */
1572         list_splice_tail(list_event, list_all);
1573         free(list_event);
1574 }
1575
1576 struct event_modifier {
1577         int eu;
1578         int ek;
1579         int eh;
1580         int eH;
1581         int eG;
1582         int eI;
1583         int precise;
1584         int precise_max;
1585         int exclude_GH;
1586         int sample_read;
1587         int pinned;
1588         int weak;
1589 };
1590
1591 static int get_event_modifier(struct event_modifier *mod, char *str,
1592                                struct evsel *evsel)
1593 {
1594         int eu = evsel ? evsel->core.attr.exclude_user : 0;
1595         int ek = evsel ? evsel->core.attr.exclude_kernel : 0;
1596         int eh = evsel ? evsel->core.attr.exclude_hv : 0;
1597         int eH = evsel ? evsel->core.attr.exclude_host : 0;
1598         int eG = evsel ? evsel->core.attr.exclude_guest : 0;
1599         int eI = evsel ? evsel->core.attr.exclude_idle : 0;
1600         int precise = evsel ? evsel->core.attr.precise_ip : 0;
1601         int precise_max = 0;
1602         int sample_read = 0;
1603         int pinned = evsel ? evsel->core.attr.pinned : 0;
1604
1605         int exclude = eu | ek | eh;
1606         int exclude_GH = evsel ? evsel->exclude_GH : 0;
1607         int weak = 0;
1608
1609         memset(mod, 0, sizeof(*mod));
1610
1611         while (*str) {
1612                 if (*str == 'u') {
1613                         if (!exclude)
1614                                 exclude = eu = ek = eh = 1;
1615                         eu = 0;
1616                 } else if (*str == 'k') {
1617                         if (!exclude)
1618                                 exclude = eu = ek = eh = 1;
1619                         ek = 0;
1620                 } else if (*str == 'h') {
1621                         if (!exclude)
1622                                 exclude = eu = ek = eh = 1;
1623                         eh = 0;
1624                 } else if (*str == 'G') {
1625                         if (!exclude_GH)
1626                                 exclude_GH = eG = eH = 1;
1627                         eG = 0;
1628                 } else if (*str == 'H') {
1629                         if (!exclude_GH)
1630                                 exclude_GH = eG = eH = 1;
1631                         eH = 0;
1632                 } else if (*str == 'I') {
1633                         eI = 1;
1634                 } else if (*str == 'p') {
1635                         precise++;
1636                         /* use of precise requires exclude_guest */
1637                         if (!exclude_GH)
1638                                 eG = 1;
1639                 } else if (*str == 'P') {
1640                         precise_max = 1;
1641                 } else if (*str == 'S') {
1642                         sample_read = 1;
1643                 } else if (*str == 'D') {
1644                         pinned = 1;
1645                 } else if (*str == 'W') {
1646                         weak = 1;
1647                 } else
1648                         break;
1649
1650                 ++str;
1651         }
1652
1653         /*
1654          * precise ip:
1655          *
1656          *  0 - SAMPLE_IP can have arbitrary skid
1657          *  1 - SAMPLE_IP must have constant skid
1658          *  2 - SAMPLE_IP requested to have 0 skid
1659          *  3 - SAMPLE_IP must have 0 skid
1660          *
1661          *  See also PERF_RECORD_MISC_EXACT_IP
1662          */
1663         if (precise > 3)
1664                 return -EINVAL;
1665
1666         mod->eu = eu;
1667         mod->ek = ek;
1668         mod->eh = eh;
1669         mod->eH = eH;
1670         mod->eG = eG;
1671         mod->eI = eI;
1672         mod->precise = precise;
1673         mod->precise_max = precise_max;
1674         mod->exclude_GH = exclude_GH;
1675         mod->sample_read = sample_read;
1676         mod->pinned = pinned;
1677         mod->weak = weak;
1678
1679         return 0;
1680 }
1681
1682 /*
1683  * Basic modifier sanity check to validate it contains only one
1684  * instance of any modifier (apart from 'p') present.
1685  */
1686 static int check_modifier(char *str)
1687 {
1688         char *p = str;
1689
1690         /* The sizeof includes 0 byte as well. */
1691         if (strlen(str) > (sizeof("ukhGHpppPSDIW") - 1))
1692                 return -1;
1693
1694         while (*p) {
1695                 if (*p != 'p' && strchr(p + 1, *p))
1696                         return -1;
1697                 p++;
1698         }
1699
1700         return 0;
1701 }
1702
1703 int parse_events__modifier_event(struct list_head *list, char *str, bool add)
1704 {
1705         struct evsel *evsel;
1706         struct event_modifier mod;
1707
1708         if (str == NULL)
1709                 return 0;
1710
1711         if (check_modifier(str))
1712                 return -EINVAL;
1713
1714         if (!add && get_event_modifier(&mod, str, NULL))
1715                 return -EINVAL;
1716
1717         __evlist__for_each_entry(list, evsel) {
1718                 if (add && get_event_modifier(&mod, str, evsel))
1719                         return -EINVAL;
1720
1721                 evsel->core.attr.exclude_user   = mod.eu;
1722                 evsel->core.attr.exclude_kernel = mod.ek;
1723                 evsel->core.attr.exclude_hv     = mod.eh;
1724                 evsel->core.attr.precise_ip     = mod.precise;
1725                 evsel->core.attr.exclude_host   = mod.eH;
1726                 evsel->core.attr.exclude_guest  = mod.eG;
1727                 evsel->core.attr.exclude_idle   = mod.eI;
1728                 evsel->exclude_GH          = mod.exclude_GH;
1729                 evsel->sample_read         = mod.sample_read;
1730                 evsel->precise_max         = mod.precise_max;
1731                 evsel->weak_group          = mod.weak;
1732
1733                 if (perf_evsel__is_group_leader(evsel))
1734                         evsel->core.attr.pinned = mod.pinned;
1735         }
1736
1737         return 0;
1738 }
1739
1740 int parse_events_name(struct list_head *list, char *name)
1741 {
1742         struct evsel *evsel;
1743
1744         __evlist__for_each_entry(list, evsel) {
1745                 if (!evsel->name)
1746                         evsel->name = strdup(name);
1747         }
1748
1749         return 0;
1750 }
1751
1752 static int
1753 comp_pmu(const void *p1, const void *p2)
1754 {
1755         struct perf_pmu_event_symbol *pmu1 = (struct perf_pmu_event_symbol *) p1;
1756         struct perf_pmu_event_symbol *pmu2 = (struct perf_pmu_event_symbol *) p2;
1757
1758         return strcasecmp(pmu1->symbol, pmu2->symbol);
1759 }
1760
1761 static void perf_pmu__parse_cleanup(void)
1762 {
1763         if (perf_pmu_events_list_num > 0) {
1764                 struct perf_pmu_event_symbol *p;
1765                 int i;
1766
1767                 for (i = 0; i < perf_pmu_events_list_num; i++) {
1768                         p = perf_pmu_events_list + i;
1769                         zfree(&p->symbol);
1770                 }
1771                 zfree(&perf_pmu_events_list);
1772                 perf_pmu_events_list_num = 0;
1773         }
1774 }
1775
1776 #define SET_SYMBOL(str, stype)          \
1777 do {                                    \
1778         p->symbol = str;                \
1779         if (!p->symbol)                 \
1780                 goto err;               \
1781         p->type = stype;                \
1782 } while (0)
1783
1784 /*
1785  * Read the pmu events list from sysfs
1786  * Save it into perf_pmu_events_list
1787  */
1788 static void perf_pmu__parse_init(void)
1789 {
1790
1791         struct perf_pmu *pmu = NULL;
1792         struct perf_pmu_alias *alias;
1793         int len = 0;
1794
1795         pmu = NULL;
1796         while ((pmu = perf_pmu__scan(pmu)) != NULL) {
1797                 list_for_each_entry(alias, &pmu->aliases, list) {
1798                         if (strchr(alias->name, '-'))
1799                                 len++;
1800                         len++;
1801                 }
1802         }
1803
1804         if (len == 0) {
1805                 perf_pmu_events_list_num = -1;
1806                 return;
1807         }
1808         perf_pmu_events_list = malloc(sizeof(struct perf_pmu_event_symbol) * len);
1809         if (!perf_pmu_events_list)
1810                 return;
1811         perf_pmu_events_list_num = len;
1812
1813         len = 0;
1814         pmu = NULL;
1815         while ((pmu = perf_pmu__scan(pmu)) != NULL) {
1816                 list_for_each_entry(alias, &pmu->aliases, list) {
1817                         struct perf_pmu_event_symbol *p = perf_pmu_events_list + len;
1818                         char *tmp = strchr(alias->name, '-');
1819
1820                         if (tmp != NULL) {
1821                                 SET_SYMBOL(strndup(alias->name, tmp - alias->name),
1822                                                 PMU_EVENT_SYMBOL_PREFIX);
1823                                 p++;
1824                                 SET_SYMBOL(strdup(++tmp), PMU_EVENT_SYMBOL_SUFFIX);
1825                                 len += 2;
1826                         } else {
1827                                 SET_SYMBOL(strdup(alias->name), PMU_EVENT_SYMBOL);
1828                                 len++;
1829                         }
1830                 }
1831         }
1832         qsort(perf_pmu_events_list, len,
1833                 sizeof(struct perf_pmu_event_symbol), comp_pmu);
1834
1835         return;
1836 err:
1837         perf_pmu__parse_cleanup();
1838 }
1839
1840 enum perf_pmu_event_symbol_type
1841 perf_pmu__parse_check(const char *name)
1842 {
1843         struct perf_pmu_event_symbol p, *r;
1844
1845         /* scan kernel pmu events from sysfs if needed */
1846         if (perf_pmu_events_list_num == 0)
1847                 perf_pmu__parse_init();
1848         /*
1849          * name "cpu" could be prefix of cpu-cycles or cpu// events.
1850          * cpu-cycles has been handled by hardcode.
1851          * So it must be cpu// events, not kernel pmu event.
1852          */
1853         if ((perf_pmu_events_list_num <= 0) || !strcmp(name, "cpu"))
1854                 return PMU_EVENT_SYMBOL_ERR;
1855
1856         p.symbol = strdup(name);
1857         r = bsearch(&p, perf_pmu_events_list,
1858                         (size_t) perf_pmu_events_list_num,
1859                         sizeof(struct perf_pmu_event_symbol), comp_pmu);
1860         zfree(&p.symbol);
1861         return r ? r->type : PMU_EVENT_SYMBOL_ERR;
1862 }
1863
1864 static int parse_events__scanner(const char *str, void *parse_state, int start_token)
1865 {
1866         YY_BUFFER_STATE buffer;
1867         void *scanner;
1868         int ret;
1869
1870         ret = parse_events_lex_init_extra(start_token, &scanner);
1871         if (ret)
1872                 return ret;
1873
1874         buffer = parse_events__scan_string(str, scanner);
1875
1876 #ifdef PARSER_DEBUG
1877         parse_events_debug = 1;
1878 #endif
1879         ret = parse_events_parse(parse_state, scanner);
1880
1881         parse_events__flush_buffer(buffer, scanner);
1882         parse_events__delete_buffer(buffer, scanner);
1883         parse_events_lex_destroy(scanner);
1884         return ret;
1885 }
1886
1887 /*
1888  * parse event config string, return a list of event terms.
1889  */
1890 int parse_events_terms(struct list_head *terms, const char *str)
1891 {
1892         struct parse_events_state parse_state = {
1893                 .terms = NULL,
1894         };
1895         int ret;
1896
1897         ret = parse_events__scanner(str, &parse_state, PE_START_TERMS);
1898         if (!ret) {
1899                 list_splice(parse_state.terms, terms);
1900                 zfree(&parse_state.terms);
1901                 return 0;
1902         }
1903
1904         parse_events_terms__delete(parse_state.terms);
1905         return ret;
1906 }
1907
1908 int parse_events(struct evlist *evlist, const char *str,
1909                  struct parse_events_error *err)
1910 {
1911         struct parse_events_state parse_state = {
1912                 .list   = LIST_HEAD_INIT(parse_state.list),
1913                 .idx    = evlist->core.nr_entries,
1914                 .error  = err,
1915                 .evlist = evlist,
1916         };
1917         int ret;
1918
1919         ret = parse_events__scanner(str, &parse_state, PE_START_EVENTS);
1920         perf_pmu__parse_cleanup();
1921         if (!ret) {
1922                 struct evsel *last;
1923
1924                 if (list_empty(&parse_state.list)) {
1925                         WARN_ONCE(true, "WARNING: event parser found nothing\n");
1926                         return -1;
1927                 }
1928
1929                 perf_evlist__splice_list_tail(evlist, &parse_state.list);
1930                 evlist->nr_groups += parse_state.nr_groups;
1931                 last = perf_evlist__last(evlist);
1932                 last->cmdline_group_boundary = true;
1933
1934                 return 0;
1935         }
1936
1937         /*
1938          * There are 2 users - builtin-record and builtin-test objects.
1939          * Both call evlist__delete in case of error, so we dont
1940          * need to bother.
1941          */
1942         return ret;
1943 }
1944
1945 #define MAX_WIDTH 1000
1946 static int get_term_width(void)
1947 {
1948         struct winsize ws;
1949
1950         get_term_dimensions(&ws);
1951         return ws.ws_col > MAX_WIDTH ? MAX_WIDTH : ws.ws_col;
1952 }
1953
1954 void parse_events_print_error(struct parse_events_error *err,
1955                               const char *event)
1956 {
1957         const char *str = "invalid or unsupported event: ";
1958         char _buf[MAX_WIDTH];
1959         char *buf = (char *) event;
1960         int idx = 0;
1961
1962         if (err->str) {
1963                 /* -2 for extra '' in the final fprintf */
1964                 int width       = get_term_width() - 2;
1965                 int len_event   = strlen(event);
1966                 int len_str, max_len, cut = 0;
1967
1968                 /*
1969                  * Maximum error index indent, we will cut
1970                  * the event string if it's bigger.
1971                  */
1972                 int max_err_idx = 13;
1973
1974                 /*
1975                  * Let's be specific with the message when
1976                  * we have the precise error.
1977                  */
1978                 str     = "event syntax error: ";
1979                 len_str = strlen(str);
1980                 max_len = width - len_str;
1981
1982                 buf = _buf;
1983
1984                 /* We're cutting from the beginning. */
1985                 if (err->idx > max_err_idx)
1986                         cut = err->idx - max_err_idx;
1987
1988                 strncpy(buf, event + cut, max_len);
1989
1990                 /* Mark cut parts with '..' on both sides. */
1991                 if (cut)
1992                         buf[0] = buf[1] = '.';
1993
1994                 if ((len_event - cut) > max_len) {
1995                         buf[max_len - 1] = buf[max_len - 2] = '.';
1996                         buf[max_len] = 0;
1997                 }
1998
1999                 idx = len_str + err->idx - cut;
2000         }
2001
2002         fprintf(stderr, "%s'%s'\n", str, buf);
2003         if (idx) {
2004                 fprintf(stderr, "%*s\\___ %s\n", idx + 1, "", err->str);
2005                 if (err->help)
2006                         fprintf(stderr, "\n%s\n", err->help);
2007                 zfree(&err->str);
2008                 zfree(&err->help);
2009         }
2010 }
2011
2012 #undef MAX_WIDTH
2013
2014 int parse_events_option(const struct option *opt, const char *str,
2015                         int unset __maybe_unused)
2016 {
2017         struct evlist *evlist = *(struct evlist **)opt->value;
2018         struct parse_events_error err = { .idx = 0, };
2019         int ret = parse_events(evlist, str, &err);
2020
2021         if (ret) {
2022                 parse_events_print_error(&err, str);
2023                 fprintf(stderr, "Run 'perf list' for a list of valid events\n");
2024         }
2025
2026         return ret;
2027 }
2028
2029 static int
2030 foreach_evsel_in_last_glob(struct evlist *evlist,
2031                            int (*func)(struct evsel *evsel,
2032                                        const void *arg),
2033                            const void *arg)
2034 {
2035         struct evsel *last = NULL;
2036         int err;
2037
2038         /*
2039          * Don't return when list_empty, give func a chance to report
2040          * error when it found last == NULL.
2041          *
2042          * So no need to WARN here, let *func do this.
2043          */
2044         if (evlist->core.nr_entries > 0)
2045                 last = perf_evlist__last(evlist);
2046
2047         do {
2048                 err = (*func)(last, arg);
2049                 if (err)
2050                         return -1;
2051                 if (!last)
2052                         return 0;
2053
2054                 if (last->core.node.prev == &evlist->core.entries)
2055                         return 0;
2056                 last = list_entry(last->core.node.prev, struct evsel, core.node);
2057         } while (!last->cmdline_group_boundary);
2058
2059         return 0;
2060 }
2061
2062 static int set_filter(struct evsel *evsel, const void *arg)
2063 {
2064         const char *str = arg;
2065         bool found = false;
2066         int nr_addr_filters = 0;
2067         struct perf_pmu *pmu = NULL;
2068
2069         if (evsel == NULL) {
2070                 fprintf(stderr,
2071                         "--filter option should follow a -e tracepoint or HW tracer option\n");
2072                 return -1;
2073         }
2074
2075         if (evsel->core.attr.type == PERF_TYPE_TRACEPOINT) {
2076                 if (perf_evsel__append_tp_filter(evsel, str) < 0) {
2077                         fprintf(stderr,
2078                                 "not enough memory to hold filter string\n");
2079                         return -1;
2080                 }
2081
2082                 return 0;
2083         }
2084
2085         while ((pmu = perf_pmu__scan(pmu)) != NULL)
2086                 if (pmu->type == evsel->core.attr.type) {
2087                         found = true;
2088                         break;
2089                 }
2090
2091         if (found)
2092                 perf_pmu__scan_file(pmu, "nr_addr_filters",
2093                                     "%d", &nr_addr_filters);
2094
2095         if (!nr_addr_filters) {
2096                 fprintf(stderr,
2097                         "This CPU does not support address filtering\n");
2098                 return -1;
2099         }
2100
2101         if (perf_evsel__append_addr_filter(evsel, str) < 0) {
2102                 fprintf(stderr,
2103                         "not enough memory to hold filter string\n");
2104                 return -1;
2105         }
2106
2107         return 0;
2108 }
2109
2110 int parse_filter(const struct option *opt, const char *str,
2111                  int unset __maybe_unused)
2112 {
2113         struct evlist *evlist = *(struct evlist **)opt->value;
2114
2115         return foreach_evsel_in_last_glob(evlist, set_filter,
2116                                           (const void *)str);
2117 }
2118
2119 static int add_exclude_perf_filter(struct evsel *evsel,
2120                                    const void *arg __maybe_unused)
2121 {
2122         char new_filter[64];
2123
2124         if (evsel == NULL || evsel->core.attr.type != PERF_TYPE_TRACEPOINT) {
2125                 fprintf(stderr,
2126                         "--exclude-perf option should follow a -e tracepoint option\n");
2127                 return -1;
2128         }
2129
2130         snprintf(new_filter, sizeof(new_filter), "common_pid != %d", getpid());
2131
2132         if (perf_evsel__append_tp_filter(evsel, new_filter) < 0) {
2133                 fprintf(stderr,
2134                         "not enough memory to hold filter string\n");
2135                 return -1;
2136         }
2137
2138         return 0;
2139 }
2140
2141 int exclude_perf(const struct option *opt,
2142                  const char *arg __maybe_unused,
2143                  int unset __maybe_unused)
2144 {
2145         struct evlist *evlist = *(struct evlist **)opt->value;
2146
2147         return foreach_evsel_in_last_glob(evlist, add_exclude_perf_filter,
2148                                           NULL);
2149 }
2150
2151 static const char * const event_type_descriptors[] = {
2152         "Hardware event",
2153         "Software event",
2154         "Tracepoint event",
2155         "Hardware cache event",
2156         "Raw hardware event descriptor",
2157         "Hardware breakpoint",
2158 };
2159
2160 static int cmp_string(const void *a, const void *b)
2161 {
2162         const char * const *as = a;
2163         const char * const *bs = b;
2164
2165         return strcmp(*as, *bs);
2166 }
2167
2168 /*
2169  * Print the events from <debugfs_mount_point>/tracing/events
2170  */
2171
2172 void print_tracepoint_events(const char *subsys_glob, const char *event_glob,
2173                              bool name_only)
2174 {
2175         DIR *sys_dir, *evt_dir;
2176         struct dirent *sys_dirent, *evt_dirent;
2177         char evt_path[MAXPATHLEN];
2178         char *dir_path;
2179         char **evt_list = NULL;
2180         unsigned int evt_i = 0, evt_num = 0;
2181         bool evt_num_known = false;
2182
2183 restart:
2184         sys_dir = tracing_events__opendir();
2185         if (!sys_dir)
2186                 return;
2187
2188         if (evt_num_known) {
2189                 evt_list = zalloc(sizeof(char *) * evt_num);
2190                 if (!evt_list)
2191                         goto out_close_sys_dir;
2192         }
2193
2194         for_each_subsystem(sys_dir, sys_dirent) {
2195                 if (subsys_glob != NULL &&
2196                     !strglobmatch(sys_dirent->d_name, subsys_glob))
2197                         continue;
2198
2199                 dir_path = get_events_file(sys_dirent->d_name);
2200                 if (!dir_path)
2201                         continue;
2202                 evt_dir = opendir(dir_path);
2203                 if (!evt_dir)
2204                         goto next;
2205
2206                 for_each_event(dir_path, evt_dir, evt_dirent) {
2207                         if (event_glob != NULL &&
2208                             !strglobmatch(evt_dirent->d_name, event_glob))
2209                                 continue;
2210
2211                         if (!evt_num_known) {
2212                                 evt_num++;
2213                                 continue;
2214                         }
2215
2216                         snprintf(evt_path, MAXPATHLEN, "%s:%s",
2217                                  sys_dirent->d_name, evt_dirent->d_name);
2218
2219                         evt_list[evt_i] = strdup(evt_path);
2220                         if (evt_list[evt_i] == NULL) {
2221                                 put_events_file(dir_path);
2222                                 goto out_close_evt_dir;
2223                         }
2224                         evt_i++;
2225                 }
2226                 closedir(evt_dir);
2227 next:
2228                 put_events_file(dir_path);
2229         }
2230         closedir(sys_dir);
2231
2232         if (!evt_num_known) {
2233                 evt_num_known = true;
2234                 goto restart;
2235         }
2236         qsort(evt_list, evt_num, sizeof(char *), cmp_string);
2237         evt_i = 0;
2238         while (evt_i < evt_num) {
2239                 if (name_only) {
2240                         printf("%s ", evt_list[evt_i++]);
2241                         continue;
2242                 }
2243                 printf("  %-50s [%s]\n", evt_list[evt_i++],
2244                                 event_type_descriptors[PERF_TYPE_TRACEPOINT]);
2245         }
2246         if (evt_num && pager_in_use())
2247                 printf("\n");
2248
2249 out_free:
2250         evt_num = evt_i;
2251         for (evt_i = 0; evt_i < evt_num; evt_i++)
2252                 zfree(&evt_list[evt_i]);
2253         zfree(&evt_list);
2254         return;
2255
2256 out_close_evt_dir:
2257         closedir(evt_dir);
2258 out_close_sys_dir:
2259         closedir(sys_dir);
2260
2261         printf("FATAL: not enough memory to print %s\n",
2262                         event_type_descriptors[PERF_TYPE_TRACEPOINT]);
2263         if (evt_list)
2264                 goto out_free;
2265 }
2266
2267 /*
2268  * Check whether event is in <debugfs_mount_point>/tracing/events
2269  */
2270
2271 int is_valid_tracepoint(const char *event_string)
2272 {
2273         DIR *sys_dir, *evt_dir;
2274         struct dirent *sys_dirent, *evt_dirent;
2275         char evt_path[MAXPATHLEN];
2276         char *dir_path;
2277
2278         sys_dir = tracing_events__opendir();
2279         if (!sys_dir)
2280                 return 0;
2281
2282         for_each_subsystem(sys_dir, sys_dirent) {
2283                 dir_path = get_events_file(sys_dirent->d_name);
2284                 if (!dir_path)
2285                         continue;
2286                 evt_dir = opendir(dir_path);
2287                 if (!evt_dir)
2288                         goto next;
2289
2290                 for_each_event(dir_path, evt_dir, evt_dirent) {
2291                         snprintf(evt_path, MAXPATHLEN, "%s:%s",
2292                                  sys_dirent->d_name, evt_dirent->d_name);
2293                         if (!strcmp(evt_path, event_string)) {
2294                                 closedir(evt_dir);
2295                                 closedir(sys_dir);
2296                                 return 1;
2297                         }
2298                 }
2299                 closedir(evt_dir);
2300 next:
2301                 put_events_file(dir_path);
2302         }
2303         closedir(sys_dir);
2304         return 0;
2305 }
2306
2307 static bool is_event_supported(u8 type, unsigned config)
2308 {
2309         bool ret = true;
2310         int open_return;
2311         struct evsel *evsel;
2312         struct perf_event_attr attr = {
2313                 .type = type,
2314                 .config = config,
2315                 .disabled = 1,
2316         };
2317         struct perf_thread_map *tmap = thread_map__new_by_tid(0);
2318
2319         if (tmap == NULL)
2320                 return false;
2321
2322         evsel = evsel__new(&attr);
2323         if (evsel) {
2324                 open_return = evsel__open(evsel, NULL, tmap);
2325                 ret = open_return >= 0;
2326
2327                 if (open_return == -EACCES) {
2328                         /*
2329                          * This happens if the paranoid value
2330                          * /proc/sys/kernel/perf_event_paranoid is set to 2
2331                          * Re-run with exclude_kernel set; we don't do that
2332                          * by default as some ARM machines do not support it.
2333                          *
2334                          */
2335                         evsel->core.attr.exclude_kernel = 1;
2336                         ret = evsel__open(evsel, NULL, tmap) >= 0;
2337                 }
2338                 evsel__delete(evsel);
2339         }
2340
2341         perf_thread_map__put(tmap);
2342         return ret;
2343 }
2344
2345 void print_sdt_events(const char *subsys_glob, const char *event_glob,
2346                       bool name_only)
2347 {
2348         struct probe_cache *pcache;
2349         struct probe_cache_entry *ent;
2350         struct strlist *bidlist, *sdtlist;
2351         struct strlist_config cfg = {.dont_dupstr = true};
2352         struct str_node *nd, *nd2;
2353         char *buf, *path, *ptr = NULL;
2354         bool show_detail = false;
2355         int ret;
2356
2357         sdtlist = strlist__new(NULL, &cfg);
2358         if (!sdtlist) {
2359                 pr_debug("Failed to allocate new strlist for SDT\n");
2360                 return;
2361         }
2362         bidlist = build_id_cache__list_all(true);
2363         if (!bidlist) {
2364                 pr_debug("Failed to get buildids: %d\n", errno);
2365                 return;
2366         }
2367         strlist__for_each_entry(nd, bidlist) {
2368                 pcache = probe_cache__new(nd->s, NULL);
2369                 if (!pcache)
2370                         continue;
2371                 list_for_each_entry(ent, &pcache->entries, node) {
2372                         if (!ent->sdt)
2373                                 continue;
2374                         if (subsys_glob &&
2375                             !strglobmatch(ent->pev.group, subsys_glob))
2376                                 continue;
2377                         if (event_glob &&
2378                             !strglobmatch(ent->pev.event, event_glob))
2379                                 continue;
2380                         ret = asprintf(&buf, "%s:%s@%s", ent->pev.group,
2381                                         ent->pev.event, nd->s);
2382                         if (ret > 0)
2383                                 strlist__add(sdtlist, buf);
2384                 }
2385                 probe_cache__delete(pcache);
2386         }
2387         strlist__delete(bidlist);
2388
2389         strlist__for_each_entry(nd, sdtlist) {
2390                 buf = strchr(nd->s, '@');
2391                 if (buf)
2392                         *(buf++) = '\0';
2393                 if (name_only) {
2394                         printf("%s ", nd->s);
2395                         continue;
2396                 }
2397                 nd2 = strlist__next(nd);
2398                 if (nd2) {
2399                         ptr = strchr(nd2->s, '@');
2400                         if (ptr)
2401                                 *ptr = '\0';
2402                         if (strcmp(nd->s, nd2->s) == 0)
2403                                 show_detail = true;
2404                 }
2405                 if (show_detail) {
2406                         path = build_id_cache__origname(buf);
2407                         ret = asprintf(&buf, "%s@%s(%.12s)", nd->s, path, buf);
2408                         if (ret > 0) {
2409                                 printf("  %-50s [%s]\n", buf, "SDT event");
2410                                 free(buf);
2411                         }
2412                         free(path);
2413                 } else
2414                         printf("  %-50s [%s]\n", nd->s, "SDT event");
2415                 if (nd2) {
2416                         if (strcmp(nd->s, nd2->s) != 0)
2417                                 show_detail = false;
2418                         if (ptr)
2419                                 *ptr = '@';
2420                 }
2421         }
2422         strlist__delete(sdtlist);
2423 }
2424
2425 int print_hwcache_events(const char *event_glob, bool name_only)
2426 {
2427         unsigned int type, op, i, evt_i = 0, evt_num = 0;
2428         char name[64];
2429         char **evt_list = NULL;
2430         bool evt_num_known = false;
2431
2432 restart:
2433         if (evt_num_known) {
2434                 evt_list = zalloc(sizeof(char *) * evt_num);
2435                 if (!evt_list)
2436                         goto out_enomem;
2437         }
2438
2439         for (type = 0; type < PERF_COUNT_HW_CACHE_MAX; type++) {
2440                 for (op = 0; op < PERF_COUNT_HW_CACHE_OP_MAX; op++) {
2441                         /* skip invalid cache type */
2442                         if (!perf_evsel__is_cache_op_valid(type, op))
2443                                 continue;
2444
2445                         for (i = 0; i < PERF_COUNT_HW_CACHE_RESULT_MAX; i++) {
2446                                 __perf_evsel__hw_cache_type_op_res_name(type, op, i,
2447                                                                         name, sizeof(name));
2448                                 if (event_glob != NULL && !strglobmatch(name, event_glob))
2449                                         continue;
2450
2451                                 if (!is_event_supported(PERF_TYPE_HW_CACHE,
2452                                                         type | (op << 8) | (i << 16)))
2453                                         continue;
2454
2455                                 if (!evt_num_known) {
2456                                         evt_num++;
2457                                         continue;
2458                                 }
2459
2460                                 evt_list[evt_i] = strdup(name);
2461                                 if (evt_list[evt_i] == NULL)
2462                                         goto out_enomem;
2463                                 evt_i++;
2464                         }
2465                 }
2466         }
2467
2468         if (!evt_num_known) {
2469                 evt_num_known = true;
2470                 goto restart;
2471         }
2472         qsort(evt_list, evt_num, sizeof(char *), cmp_string);
2473         evt_i = 0;
2474         while (evt_i < evt_num) {
2475                 if (name_only) {
2476                         printf("%s ", evt_list[evt_i++]);
2477                         continue;
2478                 }
2479                 printf("  %-50s [%s]\n", evt_list[evt_i++],
2480                                 event_type_descriptors[PERF_TYPE_HW_CACHE]);
2481         }
2482         if (evt_num && pager_in_use())
2483                 printf("\n");
2484
2485 out_free:
2486         evt_num = evt_i;
2487         for (evt_i = 0; evt_i < evt_num; evt_i++)
2488                 zfree(&evt_list[evt_i]);
2489         zfree(&evt_list);
2490         return evt_num;
2491
2492 out_enomem:
2493         printf("FATAL: not enough memory to print %s\n", event_type_descriptors[PERF_TYPE_HW_CACHE]);
2494         if (evt_list)
2495                 goto out_free;
2496         return evt_num;
2497 }
2498
2499 static void print_tool_event(const char *name, const char *event_glob,
2500                              bool name_only)
2501 {
2502         if (event_glob && !strglobmatch(name, event_glob))
2503                 return;
2504         if (name_only)
2505                 printf("%s ", name);
2506         else
2507                 printf("  %-50s [%s]\n", name, "Tool event");
2508
2509 }
2510
2511 void print_tool_events(const char *event_glob, bool name_only)
2512 {
2513         print_tool_event("duration_time", event_glob, name_only);
2514         if (pager_in_use())
2515                 printf("\n");
2516 }
2517
2518 void print_symbol_events(const char *event_glob, unsigned type,
2519                                 struct event_symbol *syms, unsigned max,
2520                                 bool name_only)
2521 {
2522         unsigned int i, evt_i = 0, evt_num = 0;
2523         char name[MAX_NAME_LEN];
2524         char **evt_list = NULL;
2525         bool evt_num_known = false;
2526
2527 restart:
2528         if (evt_num_known) {
2529                 evt_list = zalloc(sizeof(char *) * evt_num);
2530                 if (!evt_list)
2531                         goto out_enomem;
2532                 syms -= max;
2533         }
2534
2535         for (i = 0; i < max; i++, syms++) {
2536
2537                 if (event_glob != NULL && syms->symbol != NULL &&
2538                     !(strglobmatch(syms->symbol, event_glob) ||
2539                       (syms->alias && strglobmatch(syms->alias, event_glob))))
2540                         continue;
2541
2542                 if (!is_event_supported(type, i))
2543                         continue;
2544
2545                 if (!evt_num_known) {
2546                         evt_num++;
2547                         continue;
2548                 }
2549
2550                 if (!name_only && strlen(syms->alias))
2551                         snprintf(name, MAX_NAME_LEN, "%s OR %s", syms->symbol, syms->alias);
2552                 else
2553                         strlcpy(name, syms->symbol, MAX_NAME_LEN);
2554
2555                 evt_list[evt_i] = strdup(name);
2556                 if (evt_list[evt_i] == NULL)
2557                         goto out_enomem;
2558                 evt_i++;
2559         }
2560
2561         if (!evt_num_known) {
2562                 evt_num_known = true;
2563                 goto restart;
2564         }
2565         qsort(evt_list, evt_num, sizeof(char *), cmp_string);
2566         evt_i = 0;
2567         while (evt_i < evt_num) {
2568                 if (name_only) {
2569                         printf("%s ", evt_list[evt_i++]);
2570                         continue;
2571                 }
2572                 printf("  %-50s [%s]\n", evt_list[evt_i++], event_type_descriptors[type]);
2573         }
2574         if (evt_num && pager_in_use())
2575                 printf("\n");
2576
2577 out_free:
2578         evt_num = evt_i;
2579         for (evt_i = 0; evt_i < evt_num; evt_i++)
2580                 zfree(&evt_list[evt_i]);
2581         zfree(&evt_list);
2582         return;
2583
2584 out_enomem:
2585         printf("FATAL: not enough memory to print %s\n", event_type_descriptors[type]);
2586         if (evt_list)
2587                 goto out_free;
2588 }
2589
2590 /*
2591  * Print the help text for the event symbols:
2592  */
2593 void print_events(const char *event_glob, bool name_only, bool quiet_flag,
2594                         bool long_desc, bool details_flag)
2595 {
2596         print_symbol_events(event_glob, PERF_TYPE_HARDWARE,
2597                             event_symbols_hw, PERF_COUNT_HW_MAX, name_only);
2598
2599         print_symbol_events(event_glob, PERF_TYPE_SOFTWARE,
2600                             event_symbols_sw, PERF_COUNT_SW_MAX, name_only);
2601         print_tool_events(event_glob, name_only);
2602
2603         print_hwcache_events(event_glob, name_only);
2604
2605         print_pmu_events(event_glob, name_only, quiet_flag, long_desc,
2606                         details_flag);
2607
2608         if (event_glob != NULL)
2609                 return;
2610
2611         if (!name_only) {
2612                 printf("  %-50s [%s]\n",
2613                        "rNNN",
2614                        event_type_descriptors[PERF_TYPE_RAW]);
2615                 printf("  %-50s [%s]\n",
2616                        "cpu/t1=v1[,t2=v2,t3 ...]/modifier",
2617                        event_type_descriptors[PERF_TYPE_RAW]);
2618                 if (pager_in_use())
2619                         printf("   (see 'man perf-list' on how to encode it)\n\n");
2620
2621                 printf("  %-50s [%s]\n",
2622                        "mem:<addr>[/len][:access]",
2623                         event_type_descriptors[PERF_TYPE_BREAKPOINT]);
2624                 if (pager_in_use())
2625                         printf("\n");
2626         }
2627
2628         print_tracepoint_events(NULL, NULL, name_only);
2629
2630         print_sdt_events(NULL, NULL, name_only);
2631
2632         metricgroup__print(true, true, NULL, name_only, details_flag);
2633 }
2634
2635 int parse_events__is_hardcoded_term(struct parse_events_term *term)
2636 {
2637         return term->type_term != PARSE_EVENTS__TERM_TYPE_USER;
2638 }
2639
2640 static int new_term(struct parse_events_term **_term,
2641                     struct parse_events_term *temp,
2642                     char *str, u64 num)
2643 {
2644         struct parse_events_term *term;
2645
2646         term = malloc(sizeof(*term));
2647         if (!term)
2648                 return -ENOMEM;
2649
2650         *term = *temp;
2651         INIT_LIST_HEAD(&term->list);
2652         term->weak = false;
2653
2654         switch (term->type_val) {
2655         case PARSE_EVENTS__TERM_TYPE_NUM:
2656                 term->val.num = num;
2657                 break;
2658         case PARSE_EVENTS__TERM_TYPE_STR:
2659                 term->val.str = str;
2660                 break;
2661         default:
2662                 free(term);
2663                 return -EINVAL;
2664         }
2665
2666         *_term = term;
2667         return 0;
2668 }
2669
2670 int parse_events_term__num(struct parse_events_term **term,
2671                            int type_term, char *config, u64 num,
2672                            bool no_value,
2673                            void *loc_term_, void *loc_val_)
2674 {
2675         YYLTYPE *loc_term = loc_term_;
2676         YYLTYPE *loc_val = loc_val_;
2677
2678         struct parse_events_term temp = {
2679                 .type_val  = PARSE_EVENTS__TERM_TYPE_NUM,
2680                 .type_term = type_term,
2681                 .config    = config,
2682                 .no_value  = no_value,
2683                 .err_term  = loc_term ? loc_term->first_column : 0,
2684                 .err_val   = loc_val  ? loc_val->first_column  : 0,
2685         };
2686
2687         return new_term(term, &temp, NULL, num);
2688 }
2689
2690 int parse_events_term__str(struct parse_events_term **term,
2691                            int type_term, char *config, char *str,
2692                            void *loc_term_, void *loc_val_)
2693 {
2694         YYLTYPE *loc_term = loc_term_;
2695         YYLTYPE *loc_val = loc_val_;
2696
2697         struct parse_events_term temp = {
2698                 .type_val  = PARSE_EVENTS__TERM_TYPE_STR,
2699                 .type_term = type_term,
2700                 .config    = config,
2701                 .err_term  = loc_term ? loc_term->first_column : 0,
2702                 .err_val   = loc_val  ? loc_val->first_column  : 0,
2703         };
2704
2705         return new_term(term, &temp, str, 0);
2706 }
2707
2708 int parse_events_term__sym_hw(struct parse_events_term **term,
2709                               char *config, unsigned idx)
2710 {
2711         struct event_symbol *sym;
2712         struct parse_events_term temp = {
2713                 .type_val  = PARSE_EVENTS__TERM_TYPE_STR,
2714                 .type_term = PARSE_EVENTS__TERM_TYPE_USER,
2715                 .config    = config ?: (char *) "event",
2716         };
2717
2718         BUG_ON(idx >= PERF_COUNT_HW_MAX);
2719         sym = &event_symbols_hw[idx];
2720
2721         return new_term(term, &temp, (char *) sym->symbol, 0);
2722 }
2723
2724 int parse_events_term__clone(struct parse_events_term **new,
2725                              struct parse_events_term *term)
2726 {
2727         struct parse_events_term temp = {
2728                 .type_val  = term->type_val,
2729                 .type_term = term->type_term,
2730                 .config    = term->config,
2731                 .err_term  = term->err_term,
2732                 .err_val   = term->err_val,
2733         };
2734
2735         return new_term(new, &temp, term->val.str, term->val.num);
2736 }
2737
2738 int parse_events_copy_term_list(struct list_head *old,
2739                                  struct list_head **new)
2740 {
2741         struct parse_events_term *term, *n;
2742         int ret;
2743
2744         if (!old) {
2745                 *new = NULL;
2746                 return 0;
2747         }
2748
2749         *new = malloc(sizeof(struct list_head));
2750         if (!*new)
2751                 return -ENOMEM;
2752         INIT_LIST_HEAD(*new);
2753
2754         list_for_each_entry (term, old, list) {
2755                 ret = parse_events_term__clone(&n, term);
2756                 if (ret)
2757                         return ret;
2758                 list_add_tail(&n->list, *new);
2759         }
2760         return 0;
2761 }
2762
2763 void parse_events_terms__purge(struct list_head *terms)
2764 {
2765         struct parse_events_term *term, *h;
2766
2767         list_for_each_entry_safe(term, h, terms, list) {
2768                 if (term->array.nr_ranges)
2769                         zfree(&term->array.ranges);
2770                 list_del_init(&term->list);
2771                 free(term);
2772         }
2773 }
2774
2775 void parse_events_terms__delete(struct list_head *terms)
2776 {
2777         if (!terms)
2778                 return;
2779         parse_events_terms__purge(terms);
2780         free(terms);
2781 }
2782
2783 void parse_events__clear_array(struct parse_events_array *a)
2784 {
2785         zfree(&a->ranges);
2786 }
2787
2788 void parse_events_evlist_error(struct parse_events_state *parse_state,
2789                                int idx, const char *str)
2790 {
2791         struct parse_events_error *err = parse_state->error;
2792
2793         if (!err)
2794                 return;
2795         err->idx = idx;
2796         err->str = strdup(str);
2797         WARN_ONCE(!err->str, "WARNING: failed to allocate error string");
2798 }
2799
2800 static void config_terms_list(char *buf, size_t buf_sz)
2801 {
2802         int i;
2803         bool first = true;
2804
2805         buf[0] = '\0';
2806         for (i = 0; i < __PARSE_EVENTS__TERM_TYPE_NR; i++) {
2807                 const char *name = config_term_names[i];
2808
2809                 if (!config_term_avail(i, NULL))
2810                         continue;
2811                 if (!name)
2812                         continue;
2813                 if (name[0] == '<')
2814                         continue;
2815
2816                 if (strlen(buf) + strlen(name) + 2 >= buf_sz)
2817                         return;
2818
2819                 if (!first)
2820                         strcat(buf, ",");
2821                 else
2822                         first = false;
2823                 strcat(buf, name);
2824         }
2825 }
2826
2827 /*
2828  * Return string contains valid config terms of an event.
2829  * @additional_terms: For terms such as PMU sysfs terms.
2830  */
2831 char *parse_events_formats_error_string(char *additional_terms)
2832 {
2833         char *str;
2834         /* "no-overwrite" is the longest name */
2835         char static_terms[__PARSE_EVENTS__TERM_TYPE_NR *
2836                           (sizeof("no-overwrite") - 1)];
2837
2838         config_terms_list(static_terms, sizeof(static_terms));
2839         /* valid terms */
2840         if (additional_terms) {
2841                 if (asprintf(&str, "valid terms: %s,%s",
2842                              additional_terms, static_terms) < 0)
2843                         goto fail;
2844         } else {
2845                 if (asprintf(&str, "valid terms: %s", static_terms) < 0)
2846                         goto fail;
2847         }
2848         return str;
2849
2850 fail:
2851         return NULL;
2852 }