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