]> asedeno.scripts.mit.edu Git - linux.git/blob - tools/perf/util/pmu.c
perf jevents: Add support for parsing uncore json files
[linux.git] / tools / perf / util / pmu.c
1 #include <linux/list.h>
2 #include <linux/compiler.h>
3 #include <sys/types.h>
4 #include <unistd.h>
5 #include <stdio.h>
6 #include <stdbool.h>
7 #include <stdarg.h>
8 #include <dirent.h>
9 #include <api/fs/fs.h>
10 #include <locale.h>
11 #include "util.h"
12 #include "pmu.h"
13 #include "parse-events.h"
14 #include "cpumap.h"
15 #include "header.h"
16 #include "pmu-events/pmu-events.h"
17 #include "cache.h"
18
19 struct perf_pmu_format {
20         char *name;
21         int value;
22         DECLARE_BITMAP(bits, PERF_PMU_FORMAT_BITS);
23         struct list_head list;
24 };
25
26 #define EVENT_SOURCE_DEVICE_PATH "/bus/event_source/devices/"
27
28 int perf_pmu_parse(struct list_head *list, char *name);
29 extern FILE *perf_pmu_in;
30
31 static LIST_HEAD(pmus);
32
33 /*
34  * Parse & process all the sysfs attributes located under
35  * the directory specified in 'dir' parameter.
36  */
37 int perf_pmu__format_parse(char *dir, struct list_head *head)
38 {
39         struct dirent *evt_ent;
40         DIR *format_dir;
41         int ret = 0;
42
43         format_dir = opendir(dir);
44         if (!format_dir)
45                 return -EINVAL;
46
47         while (!ret && (evt_ent = readdir(format_dir))) {
48                 char path[PATH_MAX];
49                 char *name = evt_ent->d_name;
50                 FILE *file;
51
52                 if (!strcmp(name, ".") || !strcmp(name, ".."))
53                         continue;
54
55                 snprintf(path, PATH_MAX, "%s/%s", dir, name);
56
57                 ret = -EINVAL;
58                 file = fopen(path, "r");
59                 if (!file)
60                         break;
61
62                 perf_pmu_in = file;
63                 ret = perf_pmu_parse(head, name);
64                 fclose(file);
65         }
66
67         closedir(format_dir);
68         return ret;
69 }
70
71 /*
72  * Reading/parsing the default pmu format definition, which should be
73  * located at:
74  * /sys/bus/event_source/devices/<dev>/format as sysfs group attributes.
75  */
76 static int pmu_format(const char *name, struct list_head *format)
77 {
78         struct stat st;
79         char path[PATH_MAX];
80         const char *sysfs = sysfs__mountpoint();
81
82         if (!sysfs)
83                 return -1;
84
85         snprintf(path, PATH_MAX,
86                  "%s" EVENT_SOURCE_DEVICE_PATH "%s/format", sysfs, name);
87
88         if (stat(path, &st) < 0)
89                 return 0;       /* no error if format does not exist */
90
91         if (perf_pmu__format_parse(path, format))
92                 return -1;
93
94         return 0;
95 }
96
97 static int convert_scale(const char *scale, char **end, double *sval)
98 {
99         char *lc;
100         int ret = 0;
101
102         /*
103          * save current locale
104          */
105         lc = setlocale(LC_NUMERIC, NULL);
106
107         /*
108          * The lc string may be allocated in static storage,
109          * so get a dynamic copy to make it survive setlocale
110          * call below.
111          */
112         lc = strdup(lc);
113         if (!lc) {
114                 ret = -ENOMEM;
115                 goto out;
116         }
117
118         /*
119          * force to C locale to ensure kernel
120          * scale string is converted correctly.
121          * kernel uses default C locale.
122          */
123         setlocale(LC_NUMERIC, "C");
124
125         *sval = strtod(scale, end);
126
127 out:
128         /* restore locale */
129         setlocale(LC_NUMERIC, lc);
130         free(lc);
131         return ret;
132 }
133
134 static int perf_pmu__parse_scale(struct perf_pmu_alias *alias, char *dir, char *name)
135 {
136         struct stat st;
137         ssize_t sret;
138         char scale[128];
139         int fd, ret = -1;
140         char path[PATH_MAX];
141
142         snprintf(path, PATH_MAX, "%s/%s.scale", dir, name);
143
144         fd = open(path, O_RDONLY);
145         if (fd == -1)
146                 return -1;
147
148         if (fstat(fd, &st) < 0)
149                 goto error;
150
151         sret = read(fd, scale, sizeof(scale)-1);
152         if (sret < 0)
153                 goto error;
154
155         if (scale[sret - 1] == '\n')
156                 scale[sret - 1] = '\0';
157         else
158                 scale[sret] = '\0';
159
160         ret = convert_scale(scale, NULL, &alias->scale);
161 error:
162         close(fd);
163         return ret;
164 }
165
166 static int perf_pmu__parse_unit(struct perf_pmu_alias *alias, char *dir, char *name)
167 {
168         char path[PATH_MAX];
169         ssize_t sret;
170         int fd;
171
172         snprintf(path, PATH_MAX, "%s/%s.unit", dir, name);
173
174         fd = open(path, O_RDONLY);
175         if (fd == -1)
176                 return -1;
177
178         sret = read(fd, alias->unit, UNIT_MAX_LEN);
179         if (sret < 0)
180                 goto error;
181
182         close(fd);
183
184         if (alias->unit[sret - 1] == '\n')
185                 alias->unit[sret - 1] = '\0';
186         else
187                 alias->unit[sret] = '\0';
188
189         return 0;
190 error:
191         close(fd);
192         alias->unit[0] = '\0';
193         return -1;
194 }
195
196 static int
197 perf_pmu__parse_per_pkg(struct perf_pmu_alias *alias, char *dir, char *name)
198 {
199         char path[PATH_MAX];
200         int fd;
201
202         snprintf(path, PATH_MAX, "%s/%s.per-pkg", dir, name);
203
204         fd = open(path, O_RDONLY);
205         if (fd == -1)
206                 return -1;
207
208         close(fd);
209
210         alias->per_pkg = true;
211         return 0;
212 }
213
214 static int perf_pmu__parse_snapshot(struct perf_pmu_alias *alias,
215                                     char *dir, char *name)
216 {
217         char path[PATH_MAX];
218         int fd;
219
220         snprintf(path, PATH_MAX, "%s/%s.snapshot", dir, name);
221
222         fd = open(path, O_RDONLY);
223         if (fd == -1)
224                 return -1;
225
226         alias->snapshot = true;
227         close(fd);
228         return 0;
229 }
230
231 static int __perf_pmu__new_alias(struct list_head *list, char *dir, char *name,
232                                  char *desc, char *val,
233                                  char *long_desc, char *topic,
234                                  char *unit, char *perpkg)
235 {
236         struct perf_pmu_alias *alias;
237         int ret;
238         int num;
239
240         alias = malloc(sizeof(*alias));
241         if (!alias)
242                 return -ENOMEM;
243
244         INIT_LIST_HEAD(&alias->terms);
245         alias->scale = 1.0;
246         alias->unit[0] = '\0';
247         alias->per_pkg = false;
248         alias->snapshot = false;
249
250         ret = parse_events_terms(&alias->terms, val);
251         if (ret) {
252                 pr_err("Cannot parse alias %s: %d\n", val, ret);
253                 free(alias);
254                 return ret;
255         }
256
257         alias->name = strdup(name);
258         if (dir) {
259                 /*
260                  * load unit name and scale if available
261                  */
262                 perf_pmu__parse_unit(alias, dir, name);
263                 perf_pmu__parse_scale(alias, dir, name);
264                 perf_pmu__parse_per_pkg(alias, dir, name);
265                 perf_pmu__parse_snapshot(alias, dir, name);
266         }
267
268         alias->desc = desc ? strdup(desc) : NULL;
269         alias->long_desc = long_desc ? strdup(long_desc) :
270                                 desc ? strdup(desc) : NULL;
271         alias->topic = topic ? strdup(topic) : NULL;
272         if (unit) {
273                 if (convert_scale(unit, &unit, &alias->scale) < 0)
274                         return -1;
275                 snprintf(alias->unit, sizeof(alias->unit), "%s", unit);
276         }
277         alias->per_pkg = perpkg && sscanf(perpkg, "%d", &num) == 1 && num == 1;
278         list_add_tail(&alias->list, list);
279
280         return 0;
281 }
282
283 static int perf_pmu__new_alias(struct list_head *list, char *dir, char *name, FILE *file)
284 {
285         char buf[256];
286         int ret;
287
288         ret = fread(buf, 1, sizeof(buf), file);
289         if (ret == 0)
290                 return -EINVAL;
291
292         buf[ret] = 0;
293
294         return __perf_pmu__new_alias(list, dir, name, NULL, buf, NULL, NULL, NULL,
295                                      NULL);
296 }
297
298 static inline bool pmu_alias_info_file(char *name)
299 {
300         size_t len;
301
302         len = strlen(name);
303         if (len > 5 && !strcmp(name + len - 5, ".unit"))
304                 return true;
305         if (len > 6 && !strcmp(name + len - 6, ".scale"))
306                 return true;
307         if (len > 8 && !strcmp(name + len - 8, ".per-pkg"))
308                 return true;
309         if (len > 9 && !strcmp(name + len - 9, ".snapshot"))
310                 return true;
311
312         return false;
313 }
314
315 /*
316  * Process all the sysfs attributes located under the directory
317  * specified in 'dir' parameter.
318  */
319 static int pmu_aliases_parse(char *dir, struct list_head *head)
320 {
321         struct dirent *evt_ent;
322         DIR *event_dir;
323
324         event_dir = opendir(dir);
325         if (!event_dir)
326                 return -EINVAL;
327
328         while ((evt_ent = readdir(event_dir))) {
329                 char path[PATH_MAX];
330                 char *name = evt_ent->d_name;
331                 FILE *file;
332
333                 if (!strcmp(name, ".") || !strcmp(name, ".."))
334                         continue;
335
336                 /*
337                  * skip info files parsed in perf_pmu__new_alias()
338                  */
339                 if (pmu_alias_info_file(name))
340                         continue;
341
342                 snprintf(path, PATH_MAX, "%s/%s", dir, name);
343
344                 file = fopen(path, "r");
345                 if (!file) {
346                         pr_debug("Cannot open %s\n", path);
347                         continue;
348                 }
349
350                 if (perf_pmu__new_alias(head, dir, name, file) < 0)
351                         pr_debug("Cannot set up %s\n", name);
352                 fclose(file);
353         }
354
355         closedir(event_dir);
356         return 0;
357 }
358
359 /*
360  * Reading the pmu event aliases definition, which should be located at:
361  * /sys/bus/event_source/devices/<dev>/events as sysfs group attributes.
362  */
363 static int pmu_aliases(const char *name, struct list_head *head)
364 {
365         struct stat st;
366         char path[PATH_MAX];
367         const char *sysfs = sysfs__mountpoint();
368
369         if (!sysfs)
370                 return -1;
371
372         snprintf(path, PATH_MAX,
373                  "%s/bus/event_source/devices/%s/events", sysfs, name);
374
375         if (stat(path, &st) < 0)
376                 return 0;        /* no error if 'events' does not exist */
377
378         if (pmu_aliases_parse(path, head))
379                 return -1;
380
381         return 0;
382 }
383
384 static int pmu_alias_terms(struct perf_pmu_alias *alias,
385                            struct list_head *terms)
386 {
387         struct parse_events_term *term, *cloned;
388         LIST_HEAD(list);
389         int ret;
390
391         list_for_each_entry(term, &alias->terms, list) {
392                 ret = parse_events_term__clone(&cloned, term);
393                 if (ret) {
394                         parse_events_terms__purge(&list);
395                         return ret;
396                 }
397                 list_add_tail(&cloned->list, &list);
398         }
399         list_splice(&list, terms);
400         return 0;
401 }
402
403 /*
404  * Reading/parsing the default pmu type value, which should be
405  * located at:
406  * /sys/bus/event_source/devices/<dev>/type as sysfs attribute.
407  */
408 static int pmu_type(const char *name, __u32 *type)
409 {
410         struct stat st;
411         char path[PATH_MAX];
412         FILE *file;
413         int ret = 0;
414         const char *sysfs = sysfs__mountpoint();
415
416         if (!sysfs)
417                 return -1;
418
419         snprintf(path, PATH_MAX,
420                  "%s" EVENT_SOURCE_DEVICE_PATH "%s/type", sysfs, name);
421
422         if (stat(path, &st) < 0)
423                 return -1;
424
425         file = fopen(path, "r");
426         if (!file)
427                 return -EINVAL;
428
429         if (1 != fscanf(file, "%u", type))
430                 ret = -1;
431
432         fclose(file);
433         return ret;
434 }
435
436 /* Add all pmus in sysfs to pmu list: */
437 static void pmu_read_sysfs(void)
438 {
439         char path[PATH_MAX];
440         DIR *dir;
441         struct dirent *dent;
442         const char *sysfs = sysfs__mountpoint();
443
444         if (!sysfs)
445                 return;
446
447         snprintf(path, PATH_MAX,
448                  "%s" EVENT_SOURCE_DEVICE_PATH, sysfs);
449
450         dir = opendir(path);
451         if (!dir)
452                 return;
453
454         while ((dent = readdir(dir))) {
455                 if (!strcmp(dent->d_name, ".") || !strcmp(dent->d_name, ".."))
456                         continue;
457                 /* add to static LIST_HEAD(pmus): */
458                 perf_pmu__find(dent->d_name);
459         }
460
461         closedir(dir);
462 }
463
464 static struct cpu_map *pmu_cpumask(const char *name)
465 {
466         struct stat st;
467         char path[PATH_MAX];
468         FILE *file;
469         struct cpu_map *cpus;
470         const char *sysfs = sysfs__mountpoint();
471         const char *templates[] = {
472                  "%s/bus/event_source/devices/%s/cpumask",
473                  "%s/bus/event_source/devices/%s/cpus",
474                  NULL
475         };
476         const char **template;
477
478         if (!sysfs)
479                 return NULL;
480
481         for (template = templates; *template; template++) {
482                 snprintf(path, PATH_MAX, *template, sysfs, name);
483                 if (stat(path, &st) == 0)
484                         break;
485         }
486
487         if (!*template)
488                 return NULL;
489
490         file = fopen(path, "r");
491         if (!file)
492                 return NULL;
493
494         cpus = cpu_map__read(file);
495         fclose(file);
496         return cpus;
497 }
498
499 /*
500  * Return the CPU id as a raw string.
501  *
502  * Each architecture should provide a more precise id string that
503  * can be use to match the architecture's "mapfile".
504  */
505 char * __weak get_cpuid_str(void)
506 {
507         return NULL;
508 }
509
510 /*
511  * From the pmu_events_map, find the table of PMU events that corresponds
512  * to the current running CPU. Then, add all PMU events from that table
513  * as aliases.
514  */
515 static void pmu_add_cpu_aliases(struct list_head *head, const char *name)
516 {
517         int i;
518         struct pmu_events_map *map;
519         struct pmu_event *pe;
520         char *cpuid;
521         static bool printed;
522
523         cpuid = getenv("PERF_CPUID");
524         if (cpuid)
525                 cpuid = strdup(cpuid);
526         if (!cpuid)
527                 cpuid = get_cpuid_str();
528         if (!cpuid)
529                 return;
530
531         if (!printed) {
532                 pr_debug("Using CPUID %s\n", cpuid);
533                 printed = true;
534         }
535
536         i = 0;
537         while (1) {
538                 map = &pmu_events_map[i++];
539                 if (!map->table)
540                         goto out;
541
542                 if (!strcmp(map->cpuid, cpuid))
543                         break;
544         }
545
546         /*
547          * Found a matching PMU events table. Create aliases
548          */
549         i = 0;
550         while (1) {
551                 const char *pname;
552
553                 pe = &map->table[i++];
554                 if (!pe->name)
555                         break;
556
557                 pname = pe->pmu ? pe->pmu : "cpu";
558                 if (strncmp(pname, name, strlen(pname)))
559                         continue;
560
561                 /* need type casts to override 'const' */
562                 __perf_pmu__new_alias(head, NULL, (char *)pe->name,
563                                 (char *)pe->desc, (char *)pe->event,
564                                 (char *)pe->long_desc, (char *)pe->topic,
565                                 (char *)pe->unit, (char *)pe->perpkg);
566         }
567
568 out:
569         free(cpuid);
570 }
571
572 struct perf_event_attr * __weak
573 perf_pmu__get_default_config(struct perf_pmu *pmu __maybe_unused)
574 {
575         return NULL;
576 }
577
578 static struct perf_pmu *pmu_lookup(const char *name)
579 {
580         struct perf_pmu *pmu;
581         LIST_HEAD(format);
582         LIST_HEAD(aliases);
583         __u32 type;
584
585         /*
586          * The pmu data we store & need consists of the pmu
587          * type value and format definitions. Load both right
588          * now.
589          */
590         if (pmu_format(name, &format))
591                 return NULL;
592
593         if (pmu_aliases(name, &aliases))
594                 return NULL;
595
596         pmu_add_cpu_aliases(&aliases, name);
597
598         if (pmu_type(name, &type))
599                 return NULL;
600
601         pmu = zalloc(sizeof(*pmu));
602         if (!pmu)
603                 return NULL;
604
605         pmu->cpus = pmu_cpumask(name);
606
607         INIT_LIST_HEAD(&pmu->format);
608         INIT_LIST_HEAD(&pmu->aliases);
609         list_splice(&format, &pmu->format);
610         list_splice(&aliases, &pmu->aliases);
611         pmu->name = strdup(name);
612         pmu->type = type;
613         list_add_tail(&pmu->list, &pmus);
614
615         pmu->default_config = perf_pmu__get_default_config(pmu);
616
617         return pmu;
618 }
619
620 static struct perf_pmu *pmu_find(const char *name)
621 {
622         struct perf_pmu *pmu;
623
624         list_for_each_entry(pmu, &pmus, list)
625                 if (!strcmp(pmu->name, name))
626                         return pmu;
627
628         return NULL;
629 }
630
631 struct perf_pmu *perf_pmu__scan(struct perf_pmu *pmu)
632 {
633         /*
634          * pmu iterator: If pmu is NULL, we start at the begin,
635          * otherwise return the next pmu. Returns NULL on end.
636          */
637         if (!pmu) {
638                 pmu_read_sysfs();
639                 pmu = list_prepare_entry(pmu, &pmus, list);
640         }
641         list_for_each_entry_continue(pmu, &pmus, list)
642                 return pmu;
643         return NULL;
644 }
645
646 struct perf_pmu *perf_pmu__find(const char *name)
647 {
648         struct perf_pmu *pmu;
649
650         /*
651          * Once PMU is loaded it stays in the list,
652          * so we keep us from multiple reading/parsing
653          * the pmu format definitions.
654          */
655         pmu = pmu_find(name);
656         if (pmu)
657                 return pmu;
658
659         return pmu_lookup(name);
660 }
661
662 static struct perf_pmu_format *
663 pmu_find_format(struct list_head *formats, const char *name)
664 {
665         struct perf_pmu_format *format;
666
667         list_for_each_entry(format, formats, list)
668                 if (!strcmp(format->name, name))
669                         return format;
670
671         return NULL;
672 }
673
674 __u64 perf_pmu__format_bits(struct list_head *formats, const char *name)
675 {
676         struct perf_pmu_format *format = pmu_find_format(formats, name);
677         __u64 bits = 0;
678         int fbit;
679
680         if (!format)
681                 return 0;
682
683         for_each_set_bit(fbit, format->bits, PERF_PMU_FORMAT_BITS)
684                 bits |= 1ULL << fbit;
685
686         return bits;
687 }
688
689 /*
690  * Sets value based on the format definition (format parameter)
691  * and unformated value (value parameter).
692  */
693 static void pmu_format_value(unsigned long *format, __u64 value, __u64 *v,
694                              bool zero)
695 {
696         unsigned long fbit, vbit;
697
698         for (fbit = 0, vbit = 0; fbit < PERF_PMU_FORMAT_BITS; fbit++) {
699
700                 if (!test_bit(fbit, format))
701                         continue;
702
703                 if (value & (1llu << vbit++))
704                         *v |= (1llu << fbit);
705                 else if (zero)
706                         *v &= ~(1llu << fbit);
707         }
708 }
709
710 static __u64 pmu_format_max_value(const unsigned long *format)
711 {
712         __u64 w = 0;
713         int fbit;
714
715         for_each_set_bit(fbit, format, PERF_PMU_FORMAT_BITS)
716                 w |= (1ULL << fbit);
717
718         return w;
719 }
720
721 /*
722  * Term is a string term, and might be a param-term. Try to look up it's value
723  * in the remaining terms.
724  * - We have a term like "base-or-format-term=param-term",
725  * - We need to find the value supplied for "param-term" (with param-term named
726  *   in a config string) later on in the term list.
727  */
728 static int pmu_resolve_param_term(struct parse_events_term *term,
729                                   struct list_head *head_terms,
730                                   __u64 *value)
731 {
732         struct parse_events_term *t;
733
734         list_for_each_entry(t, head_terms, list) {
735                 if (t->type_val == PARSE_EVENTS__TERM_TYPE_NUM) {
736                         if (!strcmp(t->config, term->config)) {
737                                 t->used = true;
738                                 *value = t->val.num;
739                                 return 0;
740                         }
741                 }
742         }
743
744         if (verbose)
745                 printf("Required parameter '%s' not specified\n", term->config);
746
747         return -1;
748 }
749
750 static char *pmu_formats_string(struct list_head *formats)
751 {
752         struct perf_pmu_format *format;
753         char *str = NULL;
754         struct strbuf buf = STRBUF_INIT;
755         unsigned i = 0;
756
757         if (!formats)
758                 return NULL;
759
760         /* sysfs exported terms */
761         list_for_each_entry(format, formats, list)
762                 if (strbuf_addf(&buf, i++ ? ",%s" : "%s", format->name) < 0)
763                         goto error;
764
765         str = strbuf_detach(&buf, NULL);
766 error:
767         strbuf_release(&buf);
768
769         return str;
770 }
771
772 /*
773  * Setup one of config[12] attr members based on the
774  * user input data - term parameter.
775  */
776 static int pmu_config_term(struct list_head *formats,
777                            struct perf_event_attr *attr,
778                            struct parse_events_term *term,
779                            struct list_head *head_terms,
780                            bool zero, struct parse_events_error *err)
781 {
782         struct perf_pmu_format *format;
783         __u64 *vp;
784         __u64 val, max_val;
785
786         /*
787          * If this is a parameter we've already used for parameterized-eval,
788          * skip it in normal eval.
789          */
790         if (term->used)
791                 return 0;
792
793         /*
794          * Hardcoded terms should be already in, so nothing
795          * to be done for them.
796          */
797         if (parse_events__is_hardcoded_term(term))
798                 return 0;
799
800         format = pmu_find_format(formats, term->config);
801         if (!format) {
802                 if (verbose)
803                         printf("Invalid event/parameter '%s'\n", term->config);
804                 if (err) {
805                         char *pmu_term = pmu_formats_string(formats);
806
807                         err->idx  = term->err_term;
808                         err->str  = strdup("unknown term");
809                         err->help = parse_events_formats_error_string(pmu_term);
810                         free(pmu_term);
811                 }
812                 return -EINVAL;
813         }
814
815         switch (format->value) {
816         case PERF_PMU_FORMAT_VALUE_CONFIG:
817                 vp = &attr->config;
818                 break;
819         case PERF_PMU_FORMAT_VALUE_CONFIG1:
820                 vp = &attr->config1;
821                 break;
822         case PERF_PMU_FORMAT_VALUE_CONFIG2:
823                 vp = &attr->config2;
824                 break;
825         default:
826                 return -EINVAL;
827         }
828
829         /*
830          * Either directly use a numeric term, or try to translate string terms
831          * using event parameters.
832          */
833         if (term->type_val == PARSE_EVENTS__TERM_TYPE_NUM)
834                 val = term->val.num;
835         else if (term->type_val == PARSE_EVENTS__TERM_TYPE_STR) {
836                 if (strcmp(term->val.str, "?")) {
837                         if (verbose) {
838                                 pr_info("Invalid sysfs entry %s=%s\n",
839                                                 term->config, term->val.str);
840                         }
841                         if (err) {
842                                 err->idx = term->err_val;
843                                 err->str = strdup("expected numeric value");
844                         }
845                         return -EINVAL;
846                 }
847
848                 if (pmu_resolve_param_term(term, head_terms, &val))
849                         return -EINVAL;
850         } else
851                 return -EINVAL;
852
853         max_val = pmu_format_max_value(format->bits);
854         if (val > max_val) {
855                 if (err) {
856                         err->idx = term->err_val;
857                         if (asprintf(&err->str,
858                                      "value too big for format, maximum is %llu",
859                                      (unsigned long long)max_val) < 0)
860                                 err->str = strdup("value too big for format");
861                         return -EINVAL;
862                 }
863                 /*
864                  * Assume we don't care if !err, in which case the value will be
865                  * silently truncated.
866                  */
867         }
868
869         pmu_format_value(format->bits, val, vp, zero);
870         return 0;
871 }
872
873 int perf_pmu__config_terms(struct list_head *formats,
874                            struct perf_event_attr *attr,
875                            struct list_head *head_terms,
876                            bool zero, struct parse_events_error *err)
877 {
878         struct parse_events_term *term;
879
880         list_for_each_entry(term, head_terms, list) {
881                 if (pmu_config_term(formats, attr, term, head_terms,
882                                     zero, err))
883                         return -EINVAL;
884         }
885
886         return 0;
887 }
888
889 /*
890  * Configures event's 'attr' parameter based on the:
891  * 1) users input - specified in terms parameter
892  * 2) pmu format definitions - specified by pmu parameter
893  */
894 int perf_pmu__config(struct perf_pmu *pmu, struct perf_event_attr *attr,
895                      struct list_head *head_terms,
896                      struct parse_events_error *err)
897 {
898         bool zero = !!pmu->default_config;
899
900         attr->type = pmu->type;
901         return perf_pmu__config_terms(&pmu->format, attr, head_terms,
902                                       zero, err);
903 }
904
905 static struct perf_pmu_alias *pmu_find_alias(struct perf_pmu *pmu,
906                                              struct parse_events_term *term)
907 {
908         struct perf_pmu_alias *alias;
909         char *name;
910
911         if (parse_events__is_hardcoded_term(term))
912                 return NULL;
913
914         if (term->type_val == PARSE_EVENTS__TERM_TYPE_NUM) {
915                 if (term->val.num != 1)
916                         return NULL;
917                 if (pmu_find_format(&pmu->format, term->config))
918                         return NULL;
919                 name = term->config;
920         } else if (term->type_val == PARSE_EVENTS__TERM_TYPE_STR) {
921                 if (strcasecmp(term->config, "event"))
922                         return NULL;
923                 name = term->val.str;
924         } else {
925                 return NULL;
926         }
927
928         list_for_each_entry(alias, &pmu->aliases, list) {
929                 if (!strcasecmp(alias->name, name))
930                         return alias;
931         }
932         return NULL;
933 }
934
935
936 static int check_info_data(struct perf_pmu_alias *alias,
937                            struct perf_pmu_info *info)
938 {
939         /*
940          * Only one term in event definition can
941          * define unit, scale and snapshot, fail
942          * if there's more than one.
943          */
944         if ((info->unit && alias->unit) ||
945             (info->scale && alias->scale) ||
946             (info->snapshot && alias->snapshot))
947                 return -EINVAL;
948
949         if (alias->unit)
950                 info->unit = alias->unit;
951
952         if (alias->scale)
953                 info->scale = alias->scale;
954
955         if (alias->snapshot)
956                 info->snapshot = alias->snapshot;
957
958         return 0;
959 }
960
961 /*
962  * Find alias in the terms list and replace it with the terms
963  * defined for the alias
964  */
965 int perf_pmu__check_alias(struct perf_pmu *pmu, struct list_head *head_terms,
966                           struct perf_pmu_info *info)
967 {
968         struct parse_events_term *term, *h;
969         struct perf_pmu_alias *alias;
970         int ret;
971
972         info->per_pkg = false;
973
974         /*
975          * Mark unit and scale as not set
976          * (different from default values, see below)
977          */
978         info->unit     = NULL;
979         info->scale    = 0.0;
980         info->snapshot = false;
981
982         list_for_each_entry_safe(term, h, head_terms, list) {
983                 alias = pmu_find_alias(pmu, term);
984                 if (!alias)
985                         continue;
986                 ret = pmu_alias_terms(alias, &term->list);
987                 if (ret)
988                         return ret;
989
990                 ret = check_info_data(alias, info);
991                 if (ret)
992                         return ret;
993
994                 if (alias->per_pkg)
995                         info->per_pkg = true;
996
997                 list_del(&term->list);
998                 free(term);
999         }
1000
1001         /*
1002          * if no unit or scale foundin aliases, then
1003          * set defaults as for evsel
1004          * unit cannot left to NULL
1005          */
1006         if (info->unit == NULL)
1007                 info->unit   = "";
1008
1009         if (info->scale == 0.0)
1010                 info->scale  = 1.0;
1011
1012         return 0;
1013 }
1014
1015 int perf_pmu__new_format(struct list_head *list, char *name,
1016                          int config, unsigned long *bits)
1017 {
1018         struct perf_pmu_format *format;
1019
1020         format = zalloc(sizeof(*format));
1021         if (!format)
1022                 return -ENOMEM;
1023
1024         format->name = strdup(name);
1025         format->value = config;
1026         memcpy(format->bits, bits, sizeof(format->bits));
1027
1028         list_add_tail(&format->list, list);
1029         return 0;
1030 }
1031
1032 void perf_pmu__set_format(unsigned long *bits, long from, long to)
1033 {
1034         long b;
1035
1036         if (!to)
1037                 to = from;
1038
1039         memset(bits, 0, BITS_TO_BYTES(PERF_PMU_FORMAT_BITS));
1040         for (b = from; b <= to; b++)
1041                 set_bit(b, bits);
1042 }
1043
1044 static int sub_non_neg(int a, int b)
1045 {
1046         if (b > a)
1047                 return 0;
1048         return a - b;
1049 }
1050
1051 static char *format_alias(char *buf, int len, struct perf_pmu *pmu,
1052                           struct perf_pmu_alias *alias)
1053 {
1054         struct parse_events_term *term;
1055         int used = snprintf(buf, len, "%s/%s", pmu->name, alias->name);
1056
1057         list_for_each_entry(term, &alias->terms, list) {
1058                 if (term->type_val == PARSE_EVENTS__TERM_TYPE_STR)
1059                         used += snprintf(buf + used, sub_non_neg(len, used),
1060                                         ",%s=%s", term->config,
1061                                         term->val.str);
1062         }
1063
1064         if (sub_non_neg(len, used) > 0) {
1065                 buf[used] = '/';
1066                 used++;
1067         }
1068         if (sub_non_neg(len, used) > 0) {
1069                 buf[used] = '\0';
1070                 used++;
1071         } else
1072                 buf[len - 1] = '\0';
1073
1074         return buf;
1075 }
1076
1077 static char *format_alias_or(char *buf, int len, struct perf_pmu *pmu,
1078                              struct perf_pmu_alias *alias)
1079 {
1080         snprintf(buf, len, "%s OR %s/%s/", alias->name, pmu->name, alias->name);
1081         return buf;
1082 }
1083
1084 struct sevent {
1085         char *name;
1086         char *desc;
1087         char *topic;
1088 };
1089
1090 static int cmp_sevent(const void *a, const void *b)
1091 {
1092         const struct sevent *as = a;
1093         const struct sevent *bs = b;
1094
1095         /* Put extra events last */
1096         if (!!as->desc != !!bs->desc)
1097                 return !!as->desc - !!bs->desc;
1098         if (as->topic && bs->topic) {
1099                 int n = strcmp(as->topic, bs->topic);
1100
1101                 if (n)
1102                         return n;
1103         }
1104         return strcmp(as->name, bs->name);
1105 }
1106
1107 static void wordwrap(char *s, int start, int max, int corr)
1108 {
1109         int column = start;
1110         int n;
1111
1112         while (*s) {
1113                 int wlen = strcspn(s, " \t");
1114
1115                 if (column + wlen >= max && column > start) {
1116                         printf("\n%*s", start, "");
1117                         column = start + corr;
1118                 }
1119                 n = printf("%s%.*s", column > start ? " " : "", wlen, s);
1120                 if (n <= 0)
1121                         break;
1122                 s += wlen;
1123                 column += n;
1124                 while (isspace(*s))
1125                         s++;
1126         }
1127 }
1128
1129 void print_pmu_events(const char *event_glob, bool name_only, bool quiet_flag,
1130                         bool long_desc)
1131 {
1132         struct perf_pmu *pmu;
1133         struct perf_pmu_alias *alias;
1134         char buf[1024];
1135         int printed = 0;
1136         int len, j;
1137         struct sevent *aliases;
1138         int numdesc = 0;
1139         int columns = pager_get_columns();
1140         char *topic = NULL;
1141
1142         pmu = NULL;
1143         len = 0;
1144         while ((pmu = perf_pmu__scan(pmu)) != NULL) {
1145                 list_for_each_entry(alias, &pmu->aliases, list)
1146                         len++;
1147                 if (pmu->selectable)
1148                         len++;
1149         }
1150         aliases = zalloc(sizeof(struct sevent) * len);
1151         if (!aliases)
1152                 goto out_enomem;
1153         pmu = NULL;
1154         j = 0;
1155         while ((pmu = perf_pmu__scan(pmu)) != NULL) {
1156                 list_for_each_entry(alias, &pmu->aliases, list) {
1157                         char *name = alias->desc ? alias->name :
1158                                 format_alias(buf, sizeof(buf), pmu, alias);
1159                         bool is_cpu = !strcmp(pmu->name, "cpu");
1160
1161                         if (event_glob != NULL &&
1162                             !(strglobmatch_nocase(name, event_glob) ||
1163                               (!is_cpu && strglobmatch_nocase(alias->name,
1164                                                        event_glob)) ||
1165                               (alias->topic &&
1166                                strglobmatch_nocase(alias->topic, event_glob))))
1167                                 continue;
1168
1169                         if (is_cpu && !name_only && !alias->desc)
1170                                 name = format_alias_or(buf, sizeof(buf), pmu, alias);
1171
1172                         aliases[j].name = name;
1173                         if (is_cpu && !name_only && !alias->desc)
1174                                 aliases[j].name = format_alias_or(buf,
1175                                                                   sizeof(buf),
1176                                                                   pmu, alias);
1177                         aliases[j].name = strdup(aliases[j].name);
1178                         if (!aliases[j].name)
1179                                 goto out_enomem;
1180
1181                         aliases[j].desc = long_desc ? alias->long_desc :
1182                                                 alias->desc;
1183                         aliases[j].topic = alias->topic;
1184                         j++;
1185                 }
1186                 if (pmu->selectable &&
1187                     (event_glob == NULL || strglobmatch(pmu->name, event_glob))) {
1188                         char *s;
1189                         if (asprintf(&s, "%s//", pmu->name) < 0)
1190                                 goto out_enomem;
1191                         aliases[j].name = s;
1192                         j++;
1193                 }
1194         }
1195         len = j;
1196         qsort(aliases, len, sizeof(struct sevent), cmp_sevent);
1197         for (j = 0; j < len; j++) {
1198                 if (name_only) {
1199                         printf("%s ", aliases[j].name);
1200                         continue;
1201                 }
1202                 if (aliases[j].desc && !quiet_flag) {
1203                         if (numdesc++ == 0)
1204                                 printf("\n");
1205                         if (aliases[j].topic && (!topic ||
1206                                         strcmp(topic, aliases[j].topic))) {
1207                                 printf("%s%s:\n", topic ? "\n" : "",
1208                                                 aliases[j].topic);
1209                                 topic = aliases[j].topic;
1210                         }
1211                         printf("  %-50s\n", aliases[j].name);
1212                         printf("%*s", 8, "[");
1213                         wordwrap(aliases[j].desc, 8, columns, 0);
1214                         printf("]\n");
1215                 } else
1216                         printf("  %-50s [Kernel PMU event]\n", aliases[j].name);
1217                 printed++;
1218         }
1219         if (printed && pager_in_use())
1220                 printf("\n");
1221 out_free:
1222         for (j = 0; j < len; j++)
1223                 zfree(&aliases[j].name);
1224         zfree(&aliases);
1225         return;
1226
1227 out_enomem:
1228         printf("FATAL: not enough memory to print PMU events\n");
1229         if (aliases)
1230                 goto out_free;
1231 }
1232
1233 bool pmu_have_event(const char *pname, const char *name)
1234 {
1235         struct perf_pmu *pmu;
1236         struct perf_pmu_alias *alias;
1237
1238         pmu = NULL;
1239         while ((pmu = perf_pmu__scan(pmu)) != NULL) {
1240                 if (strcmp(pname, pmu->name))
1241                         continue;
1242                 list_for_each_entry(alias, &pmu->aliases, list)
1243                         if (!strcmp(alias->name, name))
1244                                 return true;
1245         }
1246         return false;
1247 }
1248
1249 static FILE *perf_pmu__open_file(struct perf_pmu *pmu, const char *name)
1250 {
1251         struct stat st;
1252         char path[PATH_MAX];
1253         const char *sysfs;
1254
1255         sysfs = sysfs__mountpoint();
1256         if (!sysfs)
1257                 return NULL;
1258
1259         snprintf(path, PATH_MAX,
1260                  "%s" EVENT_SOURCE_DEVICE_PATH "%s/%s", sysfs, pmu->name, name);
1261
1262         if (stat(path, &st) < 0)
1263                 return NULL;
1264
1265         return fopen(path, "r");
1266 }
1267
1268 int perf_pmu__scan_file(struct perf_pmu *pmu, const char *name, const char *fmt,
1269                         ...)
1270 {
1271         va_list args;
1272         FILE *file;
1273         int ret = EOF;
1274
1275         va_start(args, fmt);
1276         file = perf_pmu__open_file(pmu, name);
1277         if (file) {
1278                 ret = vfscanf(file, fmt, args);
1279                 fclose(file);
1280         }
1281         va_end(args);
1282         return ret;
1283 }