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