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