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