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