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