]> asedeno.scripts.mit.edu Git - linux.git/blob - tools/perf/util/pmu.c
perf pmu: Support per pmu json aliases
[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         /*
594          * Check the type first to avoid unnecessary work.
595          */
596         if (pmu_type(name, &type))
597                 return NULL;
598
599         if (pmu_aliases(name, &aliases))
600                 return NULL;
601
602         pmu_add_cpu_aliases(&aliases, name);
603         pmu = zalloc(sizeof(*pmu));
604         if (!pmu)
605                 return NULL;
606
607         pmu->cpus = pmu_cpumask(name);
608
609         INIT_LIST_HEAD(&pmu->format);
610         INIT_LIST_HEAD(&pmu->aliases);
611         list_splice(&format, &pmu->format);
612         list_splice(&aliases, &pmu->aliases);
613         pmu->name = strdup(name);
614         pmu->type = type;
615         list_add_tail(&pmu->list, &pmus);
616
617         pmu->default_config = perf_pmu__get_default_config(pmu);
618
619         return pmu;
620 }
621
622 static struct perf_pmu *pmu_find(const char *name)
623 {
624         struct perf_pmu *pmu;
625
626         list_for_each_entry(pmu, &pmus, list)
627                 if (!strcmp(pmu->name, name))
628                         return pmu;
629
630         return NULL;
631 }
632
633 struct perf_pmu *perf_pmu__scan(struct perf_pmu *pmu)
634 {
635         /*
636          * pmu iterator: If pmu is NULL, we start at the begin,
637          * otherwise return the next pmu. Returns NULL on end.
638          */
639         if (!pmu) {
640                 pmu_read_sysfs();
641                 pmu = list_prepare_entry(pmu, &pmus, list);
642         }
643         list_for_each_entry_continue(pmu, &pmus, list)
644                 return pmu;
645         return NULL;
646 }
647
648 struct perf_pmu *perf_pmu__find(const char *name)
649 {
650         struct perf_pmu *pmu;
651
652         /*
653          * Once PMU is loaded it stays in the list,
654          * so we keep us from multiple reading/parsing
655          * the pmu format definitions.
656          */
657         pmu = pmu_find(name);
658         if (pmu)
659                 return pmu;
660
661         return pmu_lookup(name);
662 }
663
664 static struct perf_pmu_format *
665 pmu_find_format(struct list_head *formats, const char *name)
666 {
667         struct perf_pmu_format *format;
668
669         list_for_each_entry(format, formats, list)
670                 if (!strcmp(format->name, name))
671                         return format;
672
673         return NULL;
674 }
675
676 __u64 perf_pmu__format_bits(struct list_head *formats, const char *name)
677 {
678         struct perf_pmu_format *format = pmu_find_format(formats, name);
679         __u64 bits = 0;
680         int fbit;
681
682         if (!format)
683                 return 0;
684
685         for_each_set_bit(fbit, format->bits, PERF_PMU_FORMAT_BITS)
686                 bits |= 1ULL << fbit;
687
688         return bits;
689 }
690
691 /*
692  * Sets value based on the format definition (format parameter)
693  * and unformated value (value parameter).
694  */
695 static void pmu_format_value(unsigned long *format, __u64 value, __u64 *v,
696                              bool zero)
697 {
698         unsigned long fbit, vbit;
699
700         for (fbit = 0, vbit = 0; fbit < PERF_PMU_FORMAT_BITS; fbit++) {
701
702                 if (!test_bit(fbit, format))
703                         continue;
704
705                 if (value & (1llu << vbit++))
706                         *v |= (1llu << fbit);
707                 else if (zero)
708                         *v &= ~(1llu << fbit);
709         }
710 }
711
712 static __u64 pmu_format_max_value(const unsigned long *format)
713 {
714         __u64 w = 0;
715         int fbit;
716
717         for_each_set_bit(fbit, format, PERF_PMU_FORMAT_BITS)
718                 w |= (1ULL << fbit);
719
720         return w;
721 }
722
723 /*
724  * Term is a string term, and might be a param-term. Try to look up it's value
725  * in the remaining terms.
726  * - We have a term like "base-or-format-term=param-term",
727  * - We need to find the value supplied for "param-term" (with param-term named
728  *   in a config string) later on in the term list.
729  */
730 static int pmu_resolve_param_term(struct parse_events_term *term,
731                                   struct list_head *head_terms,
732                                   __u64 *value)
733 {
734         struct parse_events_term *t;
735
736         list_for_each_entry(t, head_terms, list) {
737                 if (t->type_val == PARSE_EVENTS__TERM_TYPE_NUM) {
738                         if (!strcmp(t->config, term->config)) {
739                                 t->used = true;
740                                 *value = t->val.num;
741                                 return 0;
742                         }
743                 }
744         }
745
746         if (verbose)
747                 printf("Required parameter '%s' not specified\n", term->config);
748
749         return -1;
750 }
751
752 static char *pmu_formats_string(struct list_head *formats)
753 {
754         struct perf_pmu_format *format;
755         char *str = NULL;
756         struct strbuf buf = STRBUF_INIT;
757         unsigned i = 0;
758
759         if (!formats)
760                 return NULL;
761
762         /* sysfs exported terms */
763         list_for_each_entry(format, formats, list)
764                 if (strbuf_addf(&buf, i++ ? ",%s" : "%s", format->name) < 0)
765                         goto error;
766
767         str = strbuf_detach(&buf, NULL);
768 error:
769         strbuf_release(&buf);
770
771         return str;
772 }
773
774 /*
775  * Setup one of config[12] attr members based on the
776  * user input data - term parameter.
777  */
778 static int pmu_config_term(struct list_head *formats,
779                            struct perf_event_attr *attr,
780                            struct parse_events_term *term,
781                            struct list_head *head_terms,
782                            bool zero, struct parse_events_error *err)
783 {
784         struct perf_pmu_format *format;
785         __u64 *vp;
786         __u64 val, max_val;
787
788         /*
789          * If this is a parameter we've already used for parameterized-eval,
790          * skip it in normal eval.
791          */
792         if (term->used)
793                 return 0;
794
795         /*
796          * Hardcoded terms should be already in, so nothing
797          * to be done for them.
798          */
799         if (parse_events__is_hardcoded_term(term))
800                 return 0;
801
802         format = pmu_find_format(formats, term->config);
803         if (!format) {
804                 if (verbose)
805                         printf("Invalid event/parameter '%s'\n", term->config);
806                 if (err) {
807                         char *pmu_term = pmu_formats_string(formats);
808
809                         err->idx  = term->err_term;
810                         err->str  = strdup("unknown term");
811                         err->help = parse_events_formats_error_string(pmu_term);
812                         free(pmu_term);
813                 }
814                 return -EINVAL;
815         }
816
817         switch (format->value) {
818         case PERF_PMU_FORMAT_VALUE_CONFIG:
819                 vp = &attr->config;
820                 break;
821         case PERF_PMU_FORMAT_VALUE_CONFIG1:
822                 vp = &attr->config1;
823                 break;
824         case PERF_PMU_FORMAT_VALUE_CONFIG2:
825                 vp = &attr->config2;
826                 break;
827         default:
828                 return -EINVAL;
829         }
830
831         /*
832          * Either directly use a numeric term, or try to translate string terms
833          * using event parameters.
834          */
835         if (term->type_val == PARSE_EVENTS__TERM_TYPE_NUM)
836                 val = term->val.num;
837         else if (term->type_val == PARSE_EVENTS__TERM_TYPE_STR) {
838                 if (strcmp(term->val.str, "?")) {
839                         if (verbose) {
840                                 pr_info("Invalid sysfs entry %s=%s\n",
841                                                 term->config, term->val.str);
842                         }
843                         if (err) {
844                                 err->idx = term->err_val;
845                                 err->str = strdup("expected numeric value");
846                         }
847                         return -EINVAL;
848                 }
849
850                 if (pmu_resolve_param_term(term, head_terms, &val))
851                         return -EINVAL;
852         } else
853                 return -EINVAL;
854
855         max_val = pmu_format_max_value(format->bits);
856         if (val > max_val) {
857                 if (err) {
858                         err->idx = term->err_val;
859                         if (asprintf(&err->str,
860                                      "value too big for format, maximum is %llu",
861                                      (unsigned long long)max_val) < 0)
862                                 err->str = strdup("value too big for format");
863                         return -EINVAL;
864                 }
865                 /*
866                  * Assume we don't care if !err, in which case the value will be
867                  * silently truncated.
868                  */
869         }
870
871         pmu_format_value(format->bits, val, vp, zero);
872         return 0;
873 }
874
875 int perf_pmu__config_terms(struct list_head *formats,
876                            struct perf_event_attr *attr,
877                            struct list_head *head_terms,
878                            bool zero, struct parse_events_error *err)
879 {
880         struct parse_events_term *term;
881
882         list_for_each_entry(term, head_terms, list) {
883                 if (pmu_config_term(formats, attr, term, head_terms,
884                                     zero, err))
885                         return -EINVAL;
886         }
887
888         return 0;
889 }
890
891 /*
892  * Configures event's 'attr' parameter based on the:
893  * 1) users input - specified in terms parameter
894  * 2) pmu format definitions - specified by pmu parameter
895  */
896 int perf_pmu__config(struct perf_pmu *pmu, struct perf_event_attr *attr,
897                      struct list_head *head_terms,
898                      struct parse_events_error *err)
899 {
900         bool zero = !!pmu->default_config;
901
902         attr->type = pmu->type;
903         return perf_pmu__config_terms(&pmu->format, attr, head_terms,
904                                       zero, err);
905 }
906
907 static struct perf_pmu_alias *pmu_find_alias(struct perf_pmu *pmu,
908                                              struct parse_events_term *term)
909 {
910         struct perf_pmu_alias *alias;
911         char *name;
912
913         if (parse_events__is_hardcoded_term(term))
914                 return NULL;
915
916         if (term->type_val == PARSE_EVENTS__TERM_TYPE_NUM) {
917                 if (term->val.num != 1)
918                         return NULL;
919                 if (pmu_find_format(&pmu->format, term->config))
920                         return NULL;
921                 name = term->config;
922         } else if (term->type_val == PARSE_EVENTS__TERM_TYPE_STR) {
923                 if (strcasecmp(term->config, "event"))
924                         return NULL;
925                 name = term->val.str;
926         } else {
927                 return NULL;
928         }
929
930         list_for_each_entry(alias, &pmu->aliases, list) {
931                 if (!strcasecmp(alias->name, name))
932                         return alias;
933         }
934         return NULL;
935 }
936
937
938 static int check_info_data(struct perf_pmu_alias *alias,
939                            struct perf_pmu_info *info)
940 {
941         /*
942          * Only one term in event definition can
943          * define unit, scale and snapshot, fail
944          * if there's more than one.
945          */
946         if ((info->unit && alias->unit) ||
947             (info->scale && alias->scale) ||
948             (info->snapshot && alias->snapshot))
949                 return -EINVAL;
950
951         if (alias->unit)
952                 info->unit = alias->unit;
953
954         if (alias->scale)
955                 info->scale = alias->scale;
956
957         if (alias->snapshot)
958                 info->snapshot = alias->snapshot;
959
960         return 0;
961 }
962
963 /*
964  * Find alias in the terms list and replace it with the terms
965  * defined for the alias
966  */
967 int perf_pmu__check_alias(struct perf_pmu *pmu, struct list_head *head_terms,
968                           struct perf_pmu_info *info)
969 {
970         struct parse_events_term *term, *h;
971         struct perf_pmu_alias *alias;
972         int ret;
973
974         info->per_pkg = false;
975
976         /*
977          * Mark unit and scale as not set
978          * (different from default values, see below)
979          */
980         info->unit     = NULL;
981         info->scale    = 0.0;
982         info->snapshot = false;
983
984         list_for_each_entry_safe(term, h, head_terms, list) {
985                 alias = pmu_find_alias(pmu, term);
986                 if (!alias)
987                         continue;
988                 ret = pmu_alias_terms(alias, &term->list);
989                 if (ret)
990                         return ret;
991
992                 ret = check_info_data(alias, info);
993                 if (ret)
994                         return ret;
995
996                 if (alias->per_pkg)
997                         info->per_pkg = true;
998
999                 list_del(&term->list);
1000                 free(term);
1001         }
1002
1003         /*
1004          * if no unit or scale foundin aliases, then
1005          * set defaults as for evsel
1006          * unit cannot left to NULL
1007          */
1008         if (info->unit == NULL)
1009                 info->unit   = "";
1010
1011         if (info->scale == 0.0)
1012                 info->scale  = 1.0;
1013
1014         return 0;
1015 }
1016
1017 int perf_pmu__new_format(struct list_head *list, char *name,
1018                          int config, unsigned long *bits)
1019 {
1020         struct perf_pmu_format *format;
1021
1022         format = zalloc(sizeof(*format));
1023         if (!format)
1024                 return -ENOMEM;
1025
1026         format->name = strdup(name);
1027         format->value = config;
1028         memcpy(format->bits, bits, sizeof(format->bits));
1029
1030         list_add_tail(&format->list, list);
1031         return 0;
1032 }
1033
1034 void perf_pmu__set_format(unsigned long *bits, long from, long to)
1035 {
1036         long b;
1037
1038         if (!to)
1039                 to = from;
1040
1041         memset(bits, 0, BITS_TO_BYTES(PERF_PMU_FORMAT_BITS));
1042         for (b = from; b <= to; b++)
1043                 set_bit(b, bits);
1044 }
1045
1046 static int sub_non_neg(int a, int b)
1047 {
1048         if (b > a)
1049                 return 0;
1050         return a - b;
1051 }
1052
1053 static char *format_alias(char *buf, int len, struct perf_pmu *pmu,
1054                           struct perf_pmu_alias *alias)
1055 {
1056         struct parse_events_term *term;
1057         int used = snprintf(buf, len, "%s/%s", pmu->name, alias->name);
1058
1059         list_for_each_entry(term, &alias->terms, list) {
1060                 if (term->type_val == PARSE_EVENTS__TERM_TYPE_STR)
1061                         used += snprintf(buf + used, sub_non_neg(len, used),
1062                                         ",%s=%s", term->config,
1063                                         term->val.str);
1064         }
1065
1066         if (sub_non_neg(len, used) > 0) {
1067                 buf[used] = '/';
1068                 used++;
1069         }
1070         if (sub_non_neg(len, used) > 0) {
1071                 buf[used] = '\0';
1072                 used++;
1073         } else
1074                 buf[len - 1] = '\0';
1075
1076         return buf;
1077 }
1078
1079 static char *format_alias_or(char *buf, int len, struct perf_pmu *pmu,
1080                              struct perf_pmu_alias *alias)
1081 {
1082         snprintf(buf, len, "%s OR %s/%s/", alias->name, pmu->name, alias->name);
1083         return buf;
1084 }
1085
1086 struct sevent {
1087         char *name;
1088         char *desc;
1089         char *topic;
1090 };
1091
1092 static int cmp_sevent(const void *a, const void *b)
1093 {
1094         const struct sevent *as = a;
1095         const struct sevent *bs = b;
1096
1097         /* Put extra events last */
1098         if (!!as->desc != !!bs->desc)
1099                 return !!as->desc - !!bs->desc;
1100         if (as->topic && bs->topic) {
1101                 int n = strcmp(as->topic, bs->topic);
1102
1103                 if (n)
1104                         return n;
1105         }
1106         return strcmp(as->name, bs->name);
1107 }
1108
1109 static void wordwrap(char *s, int start, int max, int corr)
1110 {
1111         int column = start;
1112         int n;
1113
1114         while (*s) {
1115                 int wlen = strcspn(s, " \t");
1116
1117                 if (column + wlen >= max && column > start) {
1118                         printf("\n%*s", start, "");
1119                         column = start + corr;
1120                 }
1121                 n = printf("%s%.*s", column > start ? " " : "", wlen, s);
1122                 if (n <= 0)
1123                         break;
1124                 s += wlen;
1125                 column += n;
1126                 while (isspace(*s))
1127                         s++;
1128         }
1129 }
1130
1131 void print_pmu_events(const char *event_glob, bool name_only, bool quiet_flag,
1132                         bool long_desc)
1133 {
1134         struct perf_pmu *pmu;
1135         struct perf_pmu_alias *alias;
1136         char buf[1024];
1137         int printed = 0;
1138         int len, j;
1139         struct sevent *aliases;
1140         int numdesc = 0;
1141         int columns = pager_get_columns();
1142         char *topic = NULL;
1143
1144         pmu = NULL;
1145         len = 0;
1146         while ((pmu = perf_pmu__scan(pmu)) != NULL) {
1147                 list_for_each_entry(alias, &pmu->aliases, list)
1148                         len++;
1149                 if (pmu->selectable)
1150                         len++;
1151         }
1152         aliases = zalloc(sizeof(struct sevent) * len);
1153         if (!aliases)
1154                 goto out_enomem;
1155         pmu = NULL;
1156         j = 0;
1157         while ((pmu = perf_pmu__scan(pmu)) != NULL) {
1158                 list_for_each_entry(alias, &pmu->aliases, list) {
1159                         char *name = alias->desc ? alias->name :
1160                                 format_alias(buf, sizeof(buf), pmu, alias);
1161                         bool is_cpu = !strcmp(pmu->name, "cpu");
1162
1163                         if (event_glob != NULL &&
1164                             !(strglobmatch_nocase(name, event_glob) ||
1165                               (!is_cpu && strglobmatch_nocase(alias->name,
1166                                                        event_glob)) ||
1167                               (alias->topic &&
1168                                strglobmatch_nocase(alias->topic, event_glob))))
1169                                 continue;
1170
1171                         if (is_cpu && !name_only && !alias->desc)
1172                                 name = format_alias_or(buf, sizeof(buf), pmu, alias);
1173
1174                         aliases[j].name = name;
1175                         if (is_cpu && !name_only && !alias->desc)
1176                                 aliases[j].name = format_alias_or(buf,
1177                                                                   sizeof(buf),
1178                                                                   pmu, alias);
1179                         aliases[j].name = strdup(aliases[j].name);
1180                         if (!aliases[j].name)
1181                                 goto out_enomem;
1182
1183                         aliases[j].desc = long_desc ? alias->long_desc :
1184                                                 alias->desc;
1185                         aliases[j].topic = alias->topic;
1186                         j++;
1187                 }
1188                 if (pmu->selectable &&
1189                     (event_glob == NULL || strglobmatch(pmu->name, event_glob))) {
1190                         char *s;
1191                         if (asprintf(&s, "%s//", pmu->name) < 0)
1192                                 goto out_enomem;
1193                         aliases[j].name = s;
1194                         j++;
1195                 }
1196         }
1197         len = j;
1198         qsort(aliases, len, sizeof(struct sevent), cmp_sevent);
1199         for (j = 0; j < len; j++) {
1200                 /* Skip duplicates */
1201                 if (j > 0 && !strcmp(aliases[j].name, aliases[j - 1].name))
1202                         continue;
1203                 if (name_only) {
1204                         printf("%s ", aliases[j].name);
1205                         continue;
1206                 }
1207                 if (aliases[j].desc && !quiet_flag) {
1208                         if (numdesc++ == 0)
1209                                 printf("\n");
1210                         if (aliases[j].topic && (!topic ||
1211                                         strcmp(topic, aliases[j].topic))) {
1212                                 printf("%s%s:\n", topic ? "\n" : "",
1213                                                 aliases[j].topic);
1214                                 topic = aliases[j].topic;
1215                         }
1216                         printf("  %-50s\n", aliases[j].name);
1217                         printf("%*s", 8, "[");
1218                         wordwrap(aliases[j].desc, 8, columns, 0);
1219                         printf("]\n");
1220                 } else
1221                         printf("  %-50s [Kernel PMU event]\n", aliases[j].name);
1222                 printed++;
1223         }
1224         if (printed && pager_in_use())
1225                 printf("\n");
1226 out_free:
1227         for (j = 0; j < len; j++)
1228                 zfree(&aliases[j].name);
1229         zfree(&aliases);
1230         return;
1231
1232 out_enomem:
1233         printf("FATAL: not enough memory to print PMU events\n");
1234         if (aliases)
1235                 goto out_free;
1236 }
1237
1238 bool pmu_have_event(const char *pname, const char *name)
1239 {
1240         struct perf_pmu *pmu;
1241         struct perf_pmu_alias *alias;
1242
1243         pmu = NULL;
1244         while ((pmu = perf_pmu__scan(pmu)) != NULL) {
1245                 if (strcmp(pname, pmu->name))
1246                         continue;
1247                 list_for_each_entry(alias, &pmu->aliases, list)
1248                         if (!strcmp(alias->name, name))
1249                                 return true;
1250         }
1251         return false;
1252 }
1253
1254 static FILE *perf_pmu__open_file(struct perf_pmu *pmu, const char *name)
1255 {
1256         struct stat st;
1257         char path[PATH_MAX];
1258         const char *sysfs;
1259
1260         sysfs = sysfs__mountpoint();
1261         if (!sysfs)
1262                 return NULL;
1263
1264         snprintf(path, PATH_MAX,
1265                  "%s" EVENT_SOURCE_DEVICE_PATH "%s/%s", sysfs, pmu->name, name);
1266
1267         if (stat(path, &st) < 0)
1268                 return NULL;
1269
1270         return fopen(path, "r");
1271 }
1272
1273 int perf_pmu__scan_file(struct perf_pmu *pmu, const char *name, const char *fmt,
1274                         ...)
1275 {
1276         va_list args;
1277         FILE *file;
1278         int ret = EOF;
1279
1280         va_start(args, fmt);
1281         file = perf_pmu__open_file(pmu, name);
1282         if (file) {
1283                 ret = vfscanf(file, fmt, args);
1284                 fclose(file);
1285         }
1286         va_end(args);
1287         return ret;
1288 }