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