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