perf pmu: Use relative path for sysfs scan
[platform/kernel/linux-starfive.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 <linux/ctype.h>
7 #include <subcmd/pager.h>
8 #include <sys/types.h>
9 #include <errno.h>
10 #include <fcntl.h>
11 #include <sys/stat.h>
12 #include <unistd.h>
13 #include <stdio.h>
14 #include <stdbool.h>
15 #include <stdarg.h>
16 #include <dirent.h>
17 #include <api/fs/fs.h>
18 #include <locale.h>
19 #include <regex.h>
20 #include <perf/cpumap.h>
21 #include <fnmatch.h>
22 #include <math.h>
23 #include "debug.h"
24 #include "evsel.h"
25 #include "pmu.h"
26 #include "pmus.h"
27 #include "parse-events.h"
28 #include "print-events.h"
29 #include "header.h"
30 #include "string2.h"
31 #include "strbuf.h"
32 #include "fncache.h"
33 #include "pmu-hybrid.h"
34
35 struct perf_pmu perf_pmu__fake;
36
37 /**
38  * struct perf_pmu_format - Values from a format file read from
39  * <sysfs>/devices/cpu/format/ held in struct perf_pmu.
40  *
41  * For example, the contents of <sysfs>/devices/cpu/format/event may be
42  * "config:0-7" and will be represented here as name="event",
43  * value=PERF_PMU_FORMAT_VALUE_CONFIG and bits 0 to 7 will be set.
44  */
45 struct perf_pmu_format {
46         /** @name: The modifier/file name. */
47         char *name;
48         /**
49          * @value : Which config value the format relates to. Supported values
50          * are from PERF_PMU_FORMAT_VALUE_CONFIG to
51          * PERF_PMU_FORMAT_VALUE_CONFIG_END.
52          */
53         int value;
54         /** @bits: Which config bits are set by this format value. */
55         DECLARE_BITMAP(bits, PERF_PMU_FORMAT_BITS);
56         /** @list: Element on list within struct perf_pmu. */
57         struct list_head list;
58 };
59
60 int perf_pmu_parse(struct list_head *list, char *name);
61 extern FILE *perf_pmu_in;
62
63 static bool hybrid_scanned;
64
65 static struct perf_pmu *perf_pmu__find2(int dirfd, const char *name);
66
67 /*
68  * Parse & process all the sysfs attributes located under
69  * the directory specified in 'dir' parameter.
70  */
71 int perf_pmu__format_parse(int dirfd, struct list_head *head)
72 {
73         struct dirent *evt_ent;
74         DIR *format_dir;
75         int ret = 0;
76
77         format_dir = fdopendir(dirfd);
78         if (!format_dir)
79                 return -EINVAL;
80
81         while (!ret && (evt_ent = readdir(format_dir))) {
82                 char *name = evt_ent->d_name;
83                 int fd;
84
85                 if (!strcmp(name, ".") || !strcmp(name, ".."))
86                         continue;
87
88
89                 ret = -EINVAL;
90                 fd = openat(dirfd, name, O_RDONLY);
91                 if (fd < 0)
92                         break;
93
94                 perf_pmu_in = fdopen(fd, "r");
95                 ret = perf_pmu_parse(head, name);
96                 fclose(perf_pmu_in);
97         }
98
99         closedir(format_dir);
100         return ret;
101 }
102
103 /*
104  * Reading/parsing the default pmu format definition, which should be
105  * located at:
106  * /sys/bus/event_source/devices/<dev>/format as sysfs group attributes.
107  */
108 static int pmu_format(int dirfd, const char *name, struct list_head *format)
109 {
110         int fd;
111
112         fd = perf_pmu__pathname_fd(dirfd, name, "format", O_DIRECTORY);
113         if (fd < 0)
114                 return 0;
115
116         /* it'll close the fd */
117         if (perf_pmu__format_parse(fd, format))
118                 return -1;
119
120         return 0;
121 }
122
123 int perf_pmu__convert_scale(const char *scale, char **end, double *sval)
124 {
125         char *lc;
126         int ret = 0;
127
128         /*
129          * save current locale
130          */
131         lc = setlocale(LC_NUMERIC, NULL);
132
133         /*
134          * The lc string may be allocated in static storage,
135          * so get a dynamic copy to make it survive setlocale
136          * call below.
137          */
138         lc = strdup(lc);
139         if (!lc) {
140                 ret = -ENOMEM;
141                 goto out;
142         }
143
144         /*
145          * force to C locale to ensure kernel
146          * scale string is converted correctly.
147          * kernel uses default C locale.
148          */
149         setlocale(LC_NUMERIC, "C");
150
151         *sval = strtod(scale, end);
152
153 out:
154         /* restore locale */
155         setlocale(LC_NUMERIC, lc);
156         free(lc);
157         return ret;
158 }
159
160 static int perf_pmu__parse_scale(struct perf_pmu_alias *alias, int dirfd, char *name)
161 {
162         struct stat st;
163         ssize_t sret;
164         char scale[128];
165         int fd, ret = -1;
166         char path[PATH_MAX];
167
168         scnprintf(path, PATH_MAX, "%s.scale", name);
169
170         fd = openat(dirfd, path, O_RDONLY);
171         if (fd == -1)
172                 return -1;
173
174         if (fstat(fd, &st) < 0)
175                 goto error;
176
177         sret = read(fd, scale, sizeof(scale)-1);
178         if (sret < 0)
179                 goto error;
180
181         if (scale[sret - 1] == '\n')
182                 scale[sret - 1] = '\0';
183         else
184                 scale[sret] = '\0';
185
186         ret = perf_pmu__convert_scale(scale, NULL, &alias->scale);
187 error:
188         close(fd);
189         return ret;
190 }
191
192 static int perf_pmu__parse_unit(struct perf_pmu_alias *alias, int dirfd, char *name)
193 {
194         char path[PATH_MAX];
195         ssize_t sret;
196         int fd;
197
198         scnprintf(path, PATH_MAX, "%s.unit", name);
199
200         fd = openat(dirfd, path, O_RDONLY);
201         if (fd == -1)
202                 return -1;
203
204         sret = read(fd, alias->unit, UNIT_MAX_LEN);
205         if (sret < 0)
206                 goto error;
207
208         close(fd);
209
210         if (alias->unit[sret - 1] == '\n')
211                 alias->unit[sret - 1] = '\0';
212         else
213                 alias->unit[sret] = '\0';
214
215         return 0;
216 error:
217         close(fd);
218         alias->unit[0] = '\0';
219         return -1;
220 }
221
222 static int
223 perf_pmu__parse_per_pkg(struct perf_pmu_alias *alias, int dirfd, char *name)
224 {
225         char path[PATH_MAX];
226         int fd;
227
228         scnprintf(path, PATH_MAX, "%s.per-pkg", name);
229
230         fd = openat(dirfd, path, O_RDONLY);
231         if (fd == -1)
232                 return -1;
233
234         close(fd);
235
236         alias->per_pkg = true;
237         return 0;
238 }
239
240 static int perf_pmu__parse_snapshot(struct perf_pmu_alias *alias,
241                                     int dirfd, char *name)
242 {
243         char path[PATH_MAX];
244         int fd;
245
246         scnprintf(path, PATH_MAX, "%s.snapshot", name);
247
248         fd = openat(dirfd, path, O_RDONLY);
249         if (fd == -1)
250                 return -1;
251
252         alias->snapshot = true;
253         close(fd);
254         return 0;
255 }
256
257 static void perf_pmu_assign_str(char *name, const char *field, char **old_str,
258                                 char **new_str)
259 {
260         if (!*old_str)
261                 goto set_new;
262
263         if (*new_str) { /* Have new string, check with old */
264                 if (strcasecmp(*old_str, *new_str))
265                         pr_debug("alias %s differs in field '%s'\n",
266                                  name, field);
267                 zfree(old_str);
268         } else          /* Nothing new --> keep old string */
269                 return;
270 set_new:
271         *old_str = *new_str;
272         *new_str = NULL;
273 }
274
275 static void perf_pmu_update_alias(struct perf_pmu_alias *old,
276                                   struct perf_pmu_alias *newalias)
277 {
278         perf_pmu_assign_str(old->name, "desc", &old->desc, &newalias->desc);
279         perf_pmu_assign_str(old->name, "long_desc", &old->long_desc,
280                             &newalias->long_desc);
281         perf_pmu_assign_str(old->name, "topic", &old->topic, &newalias->topic);
282         perf_pmu_assign_str(old->name, "value", &old->str, &newalias->str);
283         old->scale = newalias->scale;
284         old->per_pkg = newalias->per_pkg;
285         old->snapshot = newalias->snapshot;
286         memcpy(old->unit, newalias->unit, sizeof(old->unit));
287 }
288
289 /* Delete an alias entry. */
290 void perf_pmu_free_alias(struct perf_pmu_alias *newalias)
291 {
292         zfree(&newalias->name);
293         zfree(&newalias->desc);
294         zfree(&newalias->long_desc);
295         zfree(&newalias->topic);
296         zfree(&newalias->str);
297         zfree(&newalias->pmu_name);
298         parse_events_terms__purge(&newalias->terms);
299         free(newalias);
300 }
301
302 static void perf_pmu__del_aliases(struct perf_pmu *pmu)
303 {
304         struct perf_pmu_alias *alias, *tmp;
305
306         list_for_each_entry_safe(alias, tmp, &pmu->aliases, list) {
307                 list_del(&alias->list);
308                 perf_pmu_free_alias(alias);
309         }
310 }
311
312 /* Merge an alias, search in alias list. If this name is already
313  * present merge both of them to combine all information.
314  */
315 static bool perf_pmu_merge_alias(struct perf_pmu_alias *newalias,
316                                  struct list_head *alist)
317 {
318         struct perf_pmu_alias *a;
319
320         list_for_each_entry(a, alist, list) {
321                 if (!strcasecmp(newalias->name, a->name)) {
322                         if (newalias->pmu_name && a->pmu_name &&
323                             !strcasecmp(newalias->pmu_name, a->pmu_name)) {
324                                 continue;
325                         }
326                         perf_pmu_update_alias(a, newalias);
327                         perf_pmu_free_alias(newalias);
328                         return true;
329                 }
330         }
331         return false;
332 }
333
334 static int __perf_pmu__new_alias(struct list_head *list, int dirfd, char *name,
335                                  char *desc, char *val, const struct pmu_event *pe)
336 {
337         struct parse_events_term *term;
338         struct perf_pmu_alias *alias;
339         int ret;
340         char newval[256];
341         char *long_desc = NULL, *topic = NULL, *unit = NULL, *pmu_name = NULL;
342         bool deprecated = false, perpkg = false;
343
344         if (pe) {
345                 long_desc = (char *)pe->long_desc;
346                 topic = (char *)pe->topic;
347                 unit = (char *)pe->unit;
348                 perpkg = pe->perpkg;
349                 deprecated = pe->deprecated;
350                 pmu_name = (char *)pe->pmu;
351         }
352
353         alias = malloc(sizeof(*alias));
354         if (!alias)
355                 return -ENOMEM;
356
357         INIT_LIST_HEAD(&alias->terms);
358         alias->scale = 1.0;
359         alias->unit[0] = '\0';
360         alias->per_pkg = perpkg;
361         alias->snapshot = false;
362         alias->deprecated = deprecated;
363
364         ret = parse_events_terms(&alias->terms, val);
365         if (ret) {
366                 pr_err("Cannot parse alias %s: %d\n", val, ret);
367                 free(alias);
368                 return ret;
369         }
370
371         /* Scan event and remove leading zeroes, spaces, newlines, some
372          * platforms have terms specified as
373          * event=0x0091 (read from files ../<PMU>/events/<FILE>
374          * and terms specified as event=0x91 (read from JSON files).
375          *
376          * Rebuild string to make alias->str member comparable.
377          */
378         memset(newval, 0, sizeof(newval));
379         ret = 0;
380         list_for_each_entry(term, &alias->terms, list) {
381                 if (ret)
382                         ret += scnprintf(newval + ret, sizeof(newval) - ret,
383                                          ",");
384                 if (term->type_val == PARSE_EVENTS__TERM_TYPE_NUM)
385                         ret += scnprintf(newval + ret, sizeof(newval) - ret,
386                                          "%s=%#x", term->config, term->val.num);
387                 else if (term->type_val == PARSE_EVENTS__TERM_TYPE_STR)
388                         ret += scnprintf(newval + ret, sizeof(newval) - ret,
389                                          "%s=%s", term->config, term->val.str);
390         }
391
392         alias->name = strdup(name);
393         if (dirfd >= 0) {
394                 /*
395                  * load unit name and scale if available
396                  */
397                 perf_pmu__parse_unit(alias, dirfd, name);
398                 perf_pmu__parse_scale(alias, dirfd, name);
399                 perf_pmu__parse_per_pkg(alias, dirfd, name);
400                 perf_pmu__parse_snapshot(alias, dirfd, name);
401         }
402
403         alias->desc = desc ? strdup(desc) : NULL;
404         alias->long_desc = long_desc ? strdup(long_desc) :
405                                 desc ? strdup(desc) : NULL;
406         alias->topic = topic ? strdup(topic) : NULL;
407         if (unit) {
408                 if (perf_pmu__convert_scale(unit, &unit, &alias->scale) < 0)
409                         return -1;
410                 snprintf(alias->unit, sizeof(alias->unit), "%s", unit);
411         }
412         alias->str = strdup(newval);
413         alias->pmu_name = pmu_name ? strdup(pmu_name) : NULL;
414
415         if (!perf_pmu_merge_alias(alias, list))
416                 list_add_tail(&alias->list, list);
417
418         return 0;
419 }
420
421 static int perf_pmu__new_alias(struct list_head *list, int dirfd, char *name, FILE *file)
422 {
423         char buf[256];
424         int ret;
425
426         ret = fread(buf, 1, sizeof(buf), file);
427         if (ret == 0)
428                 return -EINVAL;
429
430         buf[ret] = 0;
431
432         /* Remove trailing newline from sysfs file */
433         strim(buf);
434
435         return __perf_pmu__new_alias(list, dirfd, name, NULL, buf, NULL);
436 }
437
438 static inline bool pmu_alias_info_file(char *name)
439 {
440         size_t len;
441
442         len = strlen(name);
443         if (len > 5 && !strcmp(name + len - 5, ".unit"))
444                 return true;
445         if (len > 6 && !strcmp(name + len - 6, ".scale"))
446                 return true;
447         if (len > 8 && !strcmp(name + len - 8, ".per-pkg"))
448                 return true;
449         if (len > 9 && !strcmp(name + len - 9, ".snapshot"))
450                 return true;
451
452         return false;
453 }
454
455 /*
456  * Process all the sysfs attributes located under the directory
457  * specified in 'dir' parameter.
458  */
459 static int pmu_aliases_parse(int dirfd, struct list_head *head)
460 {
461         struct dirent *evt_ent;
462         DIR *event_dir;
463         int fd;
464
465         event_dir = fdopendir(dirfd);
466         if (!event_dir)
467                 return -EINVAL;
468
469         while ((evt_ent = readdir(event_dir))) {
470                 char *name = evt_ent->d_name;
471                 FILE *file;
472
473                 if (!strcmp(name, ".") || !strcmp(name, ".."))
474                         continue;
475
476                 /*
477                  * skip info files parsed in perf_pmu__new_alias()
478                  */
479                 if (pmu_alias_info_file(name))
480                         continue;
481
482                 fd = openat(dirfd, name, O_RDONLY);
483                 file = fdopen(fd, "r");
484                 if (!file) {
485                         pr_debug("Cannot open %s\n", name);
486                         continue;
487                 }
488
489                 if (perf_pmu__new_alias(head, dirfd, name, file) < 0)
490                         pr_debug("Cannot set up %s\n", name);
491                 fclose(file);
492         }
493
494         closedir(event_dir);
495         return 0;
496 }
497
498 /*
499  * Reading the pmu event aliases definition, which should be located at:
500  * /sys/bus/event_source/devices/<dev>/events as sysfs group attributes.
501  */
502 static int pmu_aliases(int dirfd, const char *name, struct list_head *head)
503 {
504         int fd;
505
506         fd = perf_pmu__pathname_fd(dirfd, name, "events", O_DIRECTORY);
507         if (fd < 0)
508                 return 0;
509
510         /* it'll close the fd */
511         if (pmu_aliases_parse(fd, head))
512                 return -1;
513
514         return 0;
515 }
516
517 static int pmu_alias_terms(struct perf_pmu_alias *alias,
518                            struct list_head *terms)
519 {
520         struct parse_events_term *term, *cloned;
521         LIST_HEAD(list);
522         int ret;
523
524         list_for_each_entry(term, &alias->terms, list) {
525                 ret = parse_events_term__clone(&cloned, term);
526                 if (ret) {
527                         parse_events_terms__purge(&list);
528                         return ret;
529                 }
530                 /*
531                  * Weak terms don't override command line options,
532                  * which we don't want for implicit terms in aliases.
533                  */
534                 cloned->weak = true;
535                 list_add_tail(&cloned->list, &list);
536         }
537         list_splice(&list, terms);
538         return 0;
539 }
540
541 /* Add all pmus in sysfs to pmu list: */
542 static void pmu_read_sysfs(void)
543 {
544         int fd;
545         DIR *dir;
546         struct dirent *dent;
547
548         fd = perf_pmu__event_source_devices_fd();
549         if (fd < 0)
550                 return;
551
552         dir = fdopendir(fd);
553         if (!dir)
554                 return;
555
556         while ((dent = readdir(dir))) {
557                 if (!strcmp(dent->d_name, ".") || !strcmp(dent->d_name, ".."))
558                         continue;
559                 /* add to static LIST_HEAD(pmus): */
560                 perf_pmu__find2(fd, dent->d_name);
561         }
562
563         closedir(dir);
564 }
565
566 /*
567  * Uncore PMUs have a "cpumask" file under sysfs. CPU PMUs (e.g. on arm/arm64)
568  * may have a "cpus" file.
569  */
570 static struct perf_cpu_map *pmu_cpumask(const char *name)
571 {
572         struct perf_cpu_map *cpus;
573         const char *templates[] = {
574                 "cpumask",
575                 "cpus",
576                 NULL
577         };
578         const char **template;
579         char pmu_name[PATH_MAX];
580         struct perf_pmu pmu = {.name = pmu_name};
581         FILE *file;
582
583         strlcpy(pmu_name, name, sizeof(pmu_name));
584         for (template = templates; *template; template++) {
585                 file = perf_pmu__open_file(&pmu, *template);
586                 if (!file)
587                         continue;
588                 cpus = perf_cpu_map__read(file);
589                 if (cpus)
590                         return cpus;
591         }
592
593         return NULL;
594 }
595
596 static bool pmu_is_uncore(const char *name)
597 {
598         char path[PATH_MAX];
599
600         if (perf_pmu__hybrid_mounted(name))
601                 return false;
602
603         perf_pmu__pathname_scnprintf(path, sizeof(path), name, "cpumask");
604         return file_available(path);
605 }
606
607 static char *pmu_id(const char *name)
608 {
609         char path[PATH_MAX], *str;
610         size_t len;
611
612         perf_pmu__pathname_scnprintf(path, sizeof(path), name, "identifier");
613
614         if (filename__read_str(path, &str, &len) < 0)
615                 return NULL;
616
617         str[len - 1] = 0; /* remove line feed */
618
619         return str;
620 }
621
622 /*
623  *  PMU CORE devices have different name other than cpu in sysfs on some
624  *  platforms.
625  *  Looking for possible sysfs files to identify the arm core device.
626  */
627 static int is_arm_pmu_core(const char *name)
628 {
629         char path[PATH_MAX];
630
631         if (!perf_pmu__pathname_scnprintf(path, sizeof(path), name, "cpus"))
632                 return 0;
633         return file_available(path);
634 }
635
636 char *perf_pmu__getcpuid(struct perf_pmu *pmu)
637 {
638         char *cpuid;
639         static bool printed;
640
641         cpuid = getenv("PERF_CPUID");
642         if (cpuid)
643                 cpuid = strdup(cpuid);
644         if (!cpuid)
645                 cpuid = get_cpuid_str(pmu);
646         if (!cpuid)
647                 return NULL;
648
649         if (!printed) {
650                 pr_debug("Using CPUID %s\n", cpuid);
651                 printed = true;
652         }
653         return cpuid;
654 }
655
656 __weak const struct pmu_events_table *pmu_events_table__find(void)
657 {
658         return perf_pmu__find_events_table(NULL);
659 }
660
661 __weak const struct pmu_metrics_table *pmu_metrics_table__find(void)
662 {
663         return perf_pmu__find_metrics_table(NULL);
664 }
665
666 /*
667  * Suffix must be in form tok_{digits}, or tok{digits}, or same as pmu_name
668  * to be valid.
669  */
670 static bool perf_pmu__valid_suffix(const char *pmu_name, char *tok)
671 {
672         const char *p;
673
674         if (strncmp(pmu_name, tok, strlen(tok)))
675                 return false;
676
677         p = pmu_name + strlen(tok);
678         if (*p == 0)
679                 return true;
680
681         if (*p == '_')
682                 ++p;
683
684         /* Ensure we end in a number */
685         while (1) {
686                 if (!isdigit(*p))
687                         return false;
688                 if (*(++p) == 0)
689                         break;
690         }
691
692         return true;
693 }
694
695 bool pmu_uncore_alias_match(const char *pmu_name, const char *name)
696 {
697         char *tmp = NULL, *tok, *str;
698         bool res;
699
700         str = strdup(pmu_name);
701         if (!str)
702                 return false;
703
704         /*
705          * uncore alias may be from different PMU with common prefix
706          */
707         tok = strtok_r(str, ",", &tmp);
708         if (strncmp(pmu_name, tok, strlen(tok))) {
709                 res = false;
710                 goto out;
711         }
712
713         /*
714          * Match more complex aliases where the alias name is a comma-delimited
715          * list of tokens, orderly contained in the matching PMU name.
716          *
717          * Example: For alias "socket,pmuname" and PMU "socketX_pmunameY", we
718          *          match "socket" in "socketX_pmunameY" and then "pmuname" in
719          *          "pmunameY".
720          */
721         while (1) {
722                 char *next_tok = strtok_r(NULL, ",", &tmp);
723
724                 name = strstr(name, tok);
725                 if (!name ||
726                     (!next_tok && !perf_pmu__valid_suffix(name, tok))) {
727                         res = false;
728                         goto out;
729                 }
730                 if (!next_tok)
731                         break;
732                 tok = next_tok;
733                 name += strlen(tok);
734         }
735
736         res = true;
737 out:
738         free(str);
739         return res;
740 }
741
742 struct pmu_add_cpu_aliases_map_data {
743         struct list_head *head;
744         const char *name;
745         const char *cpu_name;
746         struct perf_pmu *pmu;
747 };
748
749 static int pmu_add_cpu_aliases_map_callback(const struct pmu_event *pe,
750                                         const struct pmu_events_table *table __maybe_unused,
751                                         void *vdata)
752 {
753         struct pmu_add_cpu_aliases_map_data *data = vdata;
754         const char *pname = pe->pmu ? pe->pmu : data->cpu_name;
755
756         if (data->pmu->is_uncore && pmu_uncore_alias_match(pname, data->name))
757                 goto new_alias;
758
759         if (strcmp(pname, data->name))
760                 return 0;
761
762 new_alias:
763         /* need type casts to override 'const' */
764         __perf_pmu__new_alias(data->head, -1, (char *)pe->name, (char *)pe->desc,
765                               (char *)pe->event, pe);
766         return 0;
767 }
768
769 /*
770  * From the pmu_events_map, find the table of PMU events that corresponds
771  * to the current running CPU. Then, add all PMU events from that table
772  * as aliases.
773  */
774 void pmu_add_cpu_aliases_table(struct list_head *head, struct perf_pmu *pmu,
775                                const struct pmu_events_table *table)
776 {
777         struct pmu_add_cpu_aliases_map_data data = {
778                 .head = head,
779                 .name = pmu->name,
780                 .cpu_name = is_arm_pmu_core(pmu->name) ? pmu->name : "cpu",
781                 .pmu = pmu,
782         };
783
784         pmu_events_table_for_each_event(table, pmu_add_cpu_aliases_map_callback, &data);
785 }
786
787 static void pmu_add_cpu_aliases(struct list_head *head, struct perf_pmu *pmu)
788 {
789         const struct pmu_events_table *table;
790
791         table = perf_pmu__find_events_table(pmu);
792         if (!table)
793                 return;
794
795         pmu_add_cpu_aliases_table(head, pmu, table);
796 }
797
798 struct pmu_sys_event_iter_data {
799         struct list_head *head;
800         struct perf_pmu *pmu;
801 };
802
803 static int pmu_add_sys_aliases_iter_fn(const struct pmu_event *pe,
804                                        const struct pmu_events_table *table __maybe_unused,
805                                        void *data)
806 {
807         struct pmu_sys_event_iter_data *idata = data;
808         struct perf_pmu *pmu = idata->pmu;
809
810         if (!pe->compat || !pe->pmu)
811                 return 0;
812
813         if (!strcmp(pmu->id, pe->compat) &&
814             pmu_uncore_alias_match(pe->pmu, pmu->name)) {
815                 __perf_pmu__new_alias(idata->head, -1,
816                                       (char *)pe->name,
817                                       (char *)pe->desc,
818                                       (char *)pe->event,
819                                       pe);
820         }
821
822         return 0;
823 }
824
825 void pmu_add_sys_aliases(struct list_head *head, struct perf_pmu *pmu)
826 {
827         struct pmu_sys_event_iter_data idata = {
828                 .head = head,
829                 .pmu = pmu,
830         };
831
832         if (!pmu->id)
833                 return;
834
835         pmu_for_each_sys_event(pmu_add_sys_aliases_iter_fn, &idata);
836 }
837
838 struct perf_event_attr * __weak
839 perf_pmu__get_default_config(struct perf_pmu *pmu __maybe_unused)
840 {
841         return NULL;
842 }
843
844 char * __weak
845 pmu_find_real_name(const char *name)
846 {
847         return (char *)name;
848 }
849
850 char * __weak
851 pmu_find_alias_name(const char *name __maybe_unused)
852 {
853         return NULL;
854 }
855
856 static int pmu_max_precise(struct perf_pmu *pmu)
857 {
858         int max_precise = -1;
859
860         perf_pmu__scan_file(pmu, "caps/max_precise", "%d", &max_precise);
861         return max_precise;
862 }
863
864 static struct perf_pmu *pmu_lookup(int dirfd, const char *lookup_name)
865 {
866         struct perf_pmu *pmu;
867         LIST_HEAD(format);
868         LIST_HEAD(aliases);
869         __u32 type;
870         char *name = pmu_find_real_name(lookup_name);
871         bool is_hybrid = perf_pmu__hybrid_mounted(name);
872         char *alias_name;
873
874         /*
875          * Check pmu name for hybrid and the pmu may be invalid in sysfs
876          */
877         if (!strncmp(name, "cpu_", 4) && !is_hybrid)
878                 return NULL;
879
880         /*
881          * The pmu data we store & need consists of the pmu
882          * type value and format definitions. Load both right
883          * now.
884          */
885         if (pmu_format(dirfd, name, &format))
886                 return NULL;
887
888         /*
889          * Check the aliases first to avoid unnecessary work.
890          */
891         if (pmu_aliases(dirfd, name, &aliases))
892                 return NULL;
893
894         pmu = zalloc(sizeof(*pmu));
895         if (!pmu)
896                 return NULL;
897
898         pmu->cpus = pmu_cpumask(name);
899         pmu->name = strdup(name);
900
901         if (!pmu->name)
902                 goto err;
903
904         /* Read type, and ensure that type value is successfully assigned (return 1) */
905         if (perf_pmu__scan_file(pmu, "type", "%u", &type) != 1)
906                 goto err;
907
908         alias_name = pmu_find_alias_name(name);
909         if (alias_name) {
910                 pmu->alias_name = strdup(alias_name);
911                 if (!pmu->alias_name)
912                         goto err;
913         }
914
915         pmu->type = type;
916         pmu->is_uncore = pmu_is_uncore(name);
917         if (pmu->is_uncore)
918                 pmu->id = pmu_id(name);
919         pmu->max_precise = pmu_max_precise(pmu);
920         pmu_add_cpu_aliases(&aliases, pmu);
921         pmu_add_sys_aliases(&aliases, pmu);
922
923         INIT_LIST_HEAD(&pmu->format);
924         INIT_LIST_HEAD(&pmu->aliases);
925         INIT_LIST_HEAD(&pmu->caps);
926         list_splice(&format, &pmu->format);
927         list_splice(&aliases, &pmu->aliases);
928         list_add_tail(&pmu->list, &pmus);
929
930         if (is_hybrid)
931                 list_add_tail(&pmu->hybrid_list, &perf_pmu__hybrid_pmus);
932         else
933                 INIT_LIST_HEAD(&pmu->hybrid_list);
934
935         pmu->default_config = perf_pmu__get_default_config(pmu);
936
937         return pmu;
938 err:
939         if (pmu->name)
940                 free(pmu->name);
941         free(pmu);
942         return NULL;
943 }
944
945 void perf_pmu__warn_invalid_formats(struct perf_pmu *pmu)
946 {
947         struct perf_pmu_format *format;
948
949         /* fake pmu doesn't have format list */
950         if (pmu == &perf_pmu__fake)
951                 return;
952
953         list_for_each_entry(format, &pmu->format, list)
954                 if (format->value >= PERF_PMU_FORMAT_VALUE_CONFIG_END) {
955                         pr_warning("WARNING: '%s' format '%s' requires 'perf_event_attr::config%d'"
956                                    "which is not supported by this version of perf!\n",
957                                    pmu->name, format->name, format->value);
958                         return;
959                 }
960 }
961
962 static struct perf_pmu *pmu_find(const char *name)
963 {
964         struct perf_pmu *pmu;
965
966         list_for_each_entry(pmu, &pmus, list) {
967                 if (!strcmp(pmu->name, name) ||
968                     (pmu->alias_name && !strcmp(pmu->alias_name, name)))
969                         return pmu;
970         }
971
972         return NULL;
973 }
974
975 struct perf_pmu *perf_pmu__find_by_type(unsigned int type)
976 {
977         struct perf_pmu *pmu;
978
979         list_for_each_entry(pmu, &pmus, list)
980                 if (pmu->type == type)
981                         return pmu;
982
983         return NULL;
984 }
985
986 struct perf_pmu *perf_pmu__scan(struct perf_pmu *pmu)
987 {
988         /*
989          * pmu iterator: If pmu is NULL, we start at the begin,
990          * otherwise return the next pmu. Returns NULL on end.
991          */
992         if (!pmu) {
993                 pmu_read_sysfs();
994                 pmu = list_prepare_entry(pmu, &pmus, list);
995         }
996         list_for_each_entry_continue(pmu, &pmus, list)
997                 return pmu;
998         return NULL;
999 }
1000
1001 struct perf_pmu *evsel__find_pmu(const struct evsel *evsel)
1002 {
1003         struct perf_pmu *pmu = NULL;
1004
1005         if (evsel->pmu)
1006                 return evsel->pmu;
1007
1008         while ((pmu = perf_pmu__scan(pmu)) != NULL) {
1009                 if (pmu->type == evsel->core.attr.type)
1010                         break;
1011         }
1012
1013         ((struct evsel *)evsel)->pmu = pmu;
1014         return pmu;
1015 }
1016
1017 bool evsel__is_aux_event(const struct evsel *evsel)
1018 {
1019         struct perf_pmu *pmu = evsel__find_pmu(evsel);
1020
1021         return pmu && pmu->auxtrace;
1022 }
1023
1024 struct perf_pmu *perf_pmu__find(const char *name)
1025 {
1026         struct perf_pmu *pmu;
1027         int dirfd;
1028
1029         /*
1030          * Once PMU is loaded it stays in the list,
1031          * so we keep us from multiple reading/parsing
1032          * the pmu format definitions.
1033          */
1034         pmu = pmu_find(name);
1035         if (pmu)
1036                 return pmu;
1037
1038         dirfd = perf_pmu__event_source_devices_fd();
1039         pmu = pmu_lookup(dirfd, name);
1040         close(dirfd);
1041
1042         return pmu;
1043 }
1044
1045 static struct perf_pmu *perf_pmu__find2(int dirfd, const char *name)
1046 {
1047         struct perf_pmu *pmu;
1048
1049         /*
1050          * Once PMU is loaded it stays in the list,
1051          * so we keep us from multiple reading/parsing
1052          * the pmu format definitions.
1053          */
1054         pmu = pmu_find(name);
1055         if (pmu)
1056                 return pmu;
1057
1058         return pmu_lookup(dirfd, name);
1059 }
1060
1061 static struct perf_pmu_format *
1062 pmu_find_format(struct list_head *formats, const char *name)
1063 {
1064         struct perf_pmu_format *format;
1065
1066         list_for_each_entry(format, formats, list)
1067                 if (!strcmp(format->name, name))
1068                         return format;
1069
1070         return NULL;
1071 }
1072
1073 __u64 perf_pmu__format_bits(struct list_head *formats, const char *name)
1074 {
1075         struct perf_pmu_format *format = pmu_find_format(formats, name);
1076         __u64 bits = 0;
1077         int fbit;
1078
1079         if (!format)
1080                 return 0;
1081
1082         for_each_set_bit(fbit, format->bits, PERF_PMU_FORMAT_BITS)
1083                 bits |= 1ULL << fbit;
1084
1085         return bits;
1086 }
1087
1088 int perf_pmu__format_type(struct list_head *formats, const char *name)
1089 {
1090         struct perf_pmu_format *format = pmu_find_format(formats, name);
1091
1092         if (!format)
1093                 return -1;
1094
1095         return format->value;
1096 }
1097
1098 /*
1099  * Sets value based on the format definition (format parameter)
1100  * and unformatted value (value parameter).
1101  */
1102 static void pmu_format_value(unsigned long *format, __u64 value, __u64 *v,
1103                              bool zero)
1104 {
1105         unsigned long fbit, vbit;
1106
1107         for (fbit = 0, vbit = 0; fbit < PERF_PMU_FORMAT_BITS; fbit++) {
1108
1109                 if (!test_bit(fbit, format))
1110                         continue;
1111
1112                 if (value & (1llu << vbit++))
1113                         *v |= (1llu << fbit);
1114                 else if (zero)
1115                         *v &= ~(1llu << fbit);
1116         }
1117 }
1118
1119 static __u64 pmu_format_max_value(const unsigned long *format)
1120 {
1121         int w;
1122
1123         w = bitmap_weight(format, PERF_PMU_FORMAT_BITS);
1124         if (!w)
1125                 return 0;
1126         if (w < 64)
1127                 return (1ULL << w) - 1;
1128         return -1;
1129 }
1130
1131 /*
1132  * Term is a string term, and might be a param-term. Try to look up it's value
1133  * in the remaining terms.
1134  * - We have a term like "base-or-format-term=param-term",
1135  * - We need to find the value supplied for "param-term" (with param-term named
1136  *   in a config string) later on in the term list.
1137  */
1138 static int pmu_resolve_param_term(struct parse_events_term *term,
1139                                   struct list_head *head_terms,
1140                                   __u64 *value)
1141 {
1142         struct parse_events_term *t;
1143
1144         list_for_each_entry(t, head_terms, list) {
1145                 if (t->type_val == PARSE_EVENTS__TERM_TYPE_NUM &&
1146                     t->config && !strcmp(t->config, term->config)) {
1147                         t->used = true;
1148                         *value = t->val.num;
1149                         return 0;
1150                 }
1151         }
1152
1153         if (verbose > 0)
1154                 printf("Required parameter '%s' not specified\n", term->config);
1155
1156         return -1;
1157 }
1158
1159 static char *pmu_formats_string(struct list_head *formats)
1160 {
1161         struct perf_pmu_format *format;
1162         char *str = NULL;
1163         struct strbuf buf = STRBUF_INIT;
1164         unsigned int i = 0;
1165
1166         if (!formats)
1167                 return NULL;
1168
1169         /* sysfs exported terms */
1170         list_for_each_entry(format, formats, list)
1171                 if (strbuf_addf(&buf, i++ ? ",%s" : "%s", format->name) < 0)
1172                         goto error;
1173
1174         str = strbuf_detach(&buf, NULL);
1175 error:
1176         strbuf_release(&buf);
1177
1178         return str;
1179 }
1180
1181 /*
1182  * Setup one of config[12] attr members based on the
1183  * user input data - term parameter.
1184  */
1185 static int pmu_config_term(const char *pmu_name,
1186                            struct list_head *formats,
1187                            struct perf_event_attr *attr,
1188                            struct parse_events_term *term,
1189                            struct list_head *head_terms,
1190                            bool zero, struct parse_events_error *err)
1191 {
1192         struct perf_pmu_format *format;
1193         __u64 *vp;
1194         __u64 val, max_val;
1195
1196         /*
1197          * If this is a parameter we've already used for parameterized-eval,
1198          * skip it in normal eval.
1199          */
1200         if (term->used)
1201                 return 0;
1202
1203         /*
1204          * Hardcoded terms should be already in, so nothing
1205          * to be done for them.
1206          */
1207         if (parse_events__is_hardcoded_term(term))
1208                 return 0;
1209
1210         format = pmu_find_format(formats, term->config);
1211         if (!format) {
1212                 char *pmu_term = pmu_formats_string(formats);
1213                 char *unknown_term;
1214                 char *help_msg;
1215
1216                 if (asprintf(&unknown_term,
1217                                 "unknown term '%s' for pmu '%s'",
1218                                 term->config, pmu_name) < 0)
1219                         unknown_term = NULL;
1220                 help_msg = parse_events_formats_error_string(pmu_term);
1221                 if (err) {
1222                         parse_events_error__handle(err, term->err_term,
1223                                                    unknown_term,
1224                                                    help_msg);
1225                 } else {
1226                         pr_debug("%s (%s)\n", unknown_term, help_msg);
1227                         free(unknown_term);
1228                 }
1229                 free(pmu_term);
1230                 return -EINVAL;
1231         }
1232
1233         switch (format->value) {
1234         case PERF_PMU_FORMAT_VALUE_CONFIG:
1235                 vp = &attr->config;
1236                 break;
1237         case PERF_PMU_FORMAT_VALUE_CONFIG1:
1238                 vp = &attr->config1;
1239                 break;
1240         case PERF_PMU_FORMAT_VALUE_CONFIG2:
1241                 vp = &attr->config2;
1242                 break;
1243         case PERF_PMU_FORMAT_VALUE_CONFIG3:
1244                 vp = &attr->config3;
1245                 break;
1246         default:
1247                 return -EINVAL;
1248         }
1249
1250         /*
1251          * Either directly use a numeric term, or try to translate string terms
1252          * using event parameters.
1253          */
1254         if (term->type_val == PARSE_EVENTS__TERM_TYPE_NUM) {
1255                 if (term->no_value &&
1256                     bitmap_weight(format->bits, PERF_PMU_FORMAT_BITS) > 1) {
1257                         if (err) {
1258                                 parse_events_error__handle(err, term->err_val,
1259                                            strdup("no value assigned for term"),
1260                                            NULL);
1261                         }
1262                         return -EINVAL;
1263                 }
1264
1265                 val = term->val.num;
1266         } else if (term->type_val == PARSE_EVENTS__TERM_TYPE_STR) {
1267                 if (strcmp(term->val.str, "?")) {
1268                         if (verbose > 0) {
1269                                 pr_info("Invalid sysfs entry %s=%s\n",
1270                                                 term->config, term->val.str);
1271                         }
1272                         if (err) {
1273                                 parse_events_error__handle(err, term->err_val,
1274                                         strdup("expected numeric value"),
1275                                         NULL);
1276                         }
1277                         return -EINVAL;
1278                 }
1279
1280                 if (pmu_resolve_param_term(term, head_terms, &val))
1281                         return -EINVAL;
1282         } else
1283                 return -EINVAL;
1284
1285         max_val = pmu_format_max_value(format->bits);
1286         if (val > max_val) {
1287                 if (err) {
1288                         char *err_str;
1289
1290                         parse_events_error__handle(err, term->err_val,
1291                                 asprintf(&err_str,
1292                                     "value too big for format, maximum is %llu",
1293                                     (unsigned long long)max_val) < 0
1294                                     ? strdup("value too big for format")
1295                                     : err_str,
1296                                     NULL);
1297                         return -EINVAL;
1298                 }
1299                 /*
1300                  * Assume we don't care if !err, in which case the value will be
1301                  * silently truncated.
1302                  */
1303         }
1304
1305         pmu_format_value(format->bits, val, vp, zero);
1306         return 0;
1307 }
1308
1309 int perf_pmu__config_terms(const char *pmu_name, struct list_head *formats,
1310                            struct perf_event_attr *attr,
1311                            struct list_head *head_terms,
1312                            bool zero, struct parse_events_error *err)
1313 {
1314         struct parse_events_term *term;
1315
1316         list_for_each_entry(term, head_terms, list) {
1317                 if (pmu_config_term(pmu_name, formats, attr, term, head_terms,
1318                                     zero, err))
1319                         return -EINVAL;
1320         }
1321
1322         return 0;
1323 }
1324
1325 /*
1326  * Configures event's 'attr' parameter based on the:
1327  * 1) users input - specified in terms parameter
1328  * 2) pmu format definitions - specified by pmu parameter
1329  */
1330 int perf_pmu__config(struct perf_pmu *pmu, struct perf_event_attr *attr,
1331                      struct list_head *head_terms,
1332                      struct parse_events_error *err)
1333 {
1334         bool zero = !!pmu->default_config;
1335
1336         attr->type = pmu->type;
1337         return perf_pmu__config_terms(pmu->name, &pmu->format, attr,
1338                                       head_terms, zero, err);
1339 }
1340
1341 static struct perf_pmu_alias *pmu_find_alias(struct perf_pmu *pmu,
1342                                              struct parse_events_term *term)
1343 {
1344         struct perf_pmu_alias *alias;
1345         char *name;
1346
1347         if (parse_events__is_hardcoded_term(term))
1348                 return NULL;
1349
1350         if (term->type_val == PARSE_EVENTS__TERM_TYPE_NUM) {
1351                 if (term->val.num != 1)
1352                         return NULL;
1353                 if (pmu_find_format(&pmu->format, term->config))
1354                         return NULL;
1355                 name = term->config;
1356         } else if (term->type_val == PARSE_EVENTS__TERM_TYPE_STR) {
1357                 if (strcasecmp(term->config, "event"))
1358                         return NULL;
1359                 name = term->val.str;
1360         } else {
1361                 return NULL;
1362         }
1363
1364         list_for_each_entry(alias, &pmu->aliases, list) {
1365                 if (!strcasecmp(alias->name, name))
1366                         return alias;
1367         }
1368         return NULL;
1369 }
1370
1371
1372 static int check_info_data(struct perf_pmu_alias *alias,
1373                            struct perf_pmu_info *info)
1374 {
1375         /*
1376          * Only one term in event definition can
1377          * define unit, scale and snapshot, fail
1378          * if there's more than one.
1379          */
1380         if ((info->unit && alias->unit[0]) ||
1381             (info->scale && alias->scale) ||
1382             (info->snapshot && alias->snapshot))
1383                 return -EINVAL;
1384
1385         if (alias->unit[0])
1386                 info->unit = alias->unit;
1387
1388         if (alias->scale)
1389                 info->scale = alias->scale;
1390
1391         if (alias->snapshot)
1392                 info->snapshot = alias->snapshot;
1393
1394         return 0;
1395 }
1396
1397 /*
1398  * Find alias in the terms list and replace it with the terms
1399  * defined for the alias
1400  */
1401 int perf_pmu__check_alias(struct perf_pmu *pmu, struct list_head *head_terms,
1402                           struct perf_pmu_info *info)
1403 {
1404         struct parse_events_term *term, *h;
1405         struct perf_pmu_alias *alias;
1406         int ret;
1407
1408         info->per_pkg = false;
1409
1410         /*
1411          * Mark unit and scale as not set
1412          * (different from default values, see below)
1413          */
1414         info->unit     = NULL;
1415         info->scale    = 0.0;
1416         info->snapshot = false;
1417
1418         list_for_each_entry_safe(term, h, head_terms, list) {
1419                 alias = pmu_find_alias(pmu, term);
1420                 if (!alias)
1421                         continue;
1422                 ret = pmu_alias_terms(alias, &term->list);
1423                 if (ret)
1424                         return ret;
1425
1426                 ret = check_info_data(alias, info);
1427                 if (ret)
1428                         return ret;
1429
1430                 if (alias->per_pkg)
1431                         info->per_pkg = true;
1432
1433                 list_del_init(&term->list);
1434                 parse_events_term__delete(term);
1435         }
1436
1437         /*
1438          * if no unit or scale found in aliases, then
1439          * set defaults as for evsel
1440          * unit cannot left to NULL
1441          */
1442         if (info->unit == NULL)
1443                 info->unit   = "";
1444
1445         if (info->scale == 0.0)
1446                 info->scale  = 1.0;
1447
1448         return 0;
1449 }
1450
1451 int perf_pmu__new_format(struct list_head *list, char *name,
1452                          int config, unsigned long *bits)
1453 {
1454         struct perf_pmu_format *format;
1455
1456         format = zalloc(sizeof(*format));
1457         if (!format)
1458                 return -ENOMEM;
1459
1460         format->name = strdup(name);
1461         format->value = config;
1462         memcpy(format->bits, bits, sizeof(format->bits));
1463
1464         list_add_tail(&format->list, list);
1465         return 0;
1466 }
1467
1468 void perf_pmu__set_format(unsigned long *bits, long from, long to)
1469 {
1470         long b;
1471
1472         if (!to)
1473                 to = from;
1474
1475         memset(bits, 0, BITS_TO_BYTES(PERF_PMU_FORMAT_BITS));
1476         for (b = from; b <= to; b++)
1477                 __set_bit(b, bits);
1478 }
1479
1480 void perf_pmu__del_formats(struct list_head *formats)
1481 {
1482         struct perf_pmu_format *fmt, *tmp;
1483
1484         list_for_each_entry_safe(fmt, tmp, formats, list) {
1485                 list_del(&fmt->list);
1486                 free(fmt->name);
1487                 free(fmt);
1488         }
1489 }
1490
1491 static int sub_non_neg(int a, int b)
1492 {
1493         if (b > a)
1494                 return 0;
1495         return a - b;
1496 }
1497
1498 static char *format_alias(char *buf, int len, const struct perf_pmu *pmu,
1499                           const struct perf_pmu_alias *alias)
1500 {
1501         struct parse_events_term *term;
1502         int used = snprintf(buf, len, "%s/%s", pmu->name, alias->name);
1503
1504         list_for_each_entry(term, &alias->terms, list) {
1505                 if (term->type_val == PARSE_EVENTS__TERM_TYPE_STR)
1506                         used += snprintf(buf + used, sub_non_neg(len, used),
1507                                         ",%s=%s", term->config,
1508                                         term->val.str);
1509         }
1510
1511         if (sub_non_neg(len, used) > 0) {
1512                 buf[used] = '/';
1513                 used++;
1514         }
1515         if (sub_non_neg(len, used) > 0) {
1516                 buf[used] = '\0';
1517                 used++;
1518         } else
1519                 buf[len - 1] = '\0';
1520
1521         return buf;
1522 }
1523
1524 /** Struct for ordering events as output in perf list. */
1525 struct sevent {
1526         /** PMU for event. */
1527         const struct perf_pmu *pmu;
1528         /**
1529          * Optional event for name, desc, etc. If not present then this is a
1530          * selectable PMU and the event name is shown as "//".
1531          */
1532         const struct perf_pmu_alias *event;
1533         /** Is the PMU for the CPU? */
1534         bool is_cpu;
1535 };
1536
1537 static int cmp_sevent(const void *a, const void *b)
1538 {
1539         const struct sevent *as = a;
1540         const struct sevent *bs = b;
1541         const char *a_pmu_name, *b_pmu_name;
1542         const char *a_name = "//", *a_desc = NULL, *a_topic = "";
1543         const char *b_name = "//", *b_desc = NULL, *b_topic = "";
1544         int ret;
1545
1546         if (as->event) {
1547                 a_name = as->event->name;
1548                 a_desc = as->event->desc;
1549                 a_topic = as->event->topic ?: "";
1550         }
1551         if (bs->event) {
1552                 b_name = bs->event->name;
1553                 b_desc = bs->event->desc;
1554                 b_topic = bs->event->topic ?: "";
1555         }
1556         /* Put extra events last. */
1557         if (!!a_desc != !!b_desc)
1558                 return !!a_desc - !!b_desc;
1559
1560         /* Order by topics. */
1561         ret = strcmp(a_topic, b_topic);
1562         if (ret)
1563                 return ret;
1564
1565         /* Order CPU core events to be first */
1566         if (as->is_cpu != bs->is_cpu)
1567                 return as->is_cpu ? -1 : 1;
1568
1569         /* Order by PMU name. */
1570         a_pmu_name = as->pmu->name ?: "";
1571         b_pmu_name = bs->pmu->name ?: "";
1572         ret = strcmp(a_pmu_name, b_pmu_name);
1573         if (ret)
1574                 return ret;
1575
1576         /* Order by event name. */
1577         return strcmp(a_name, b_name);
1578 }
1579
1580 bool is_pmu_core(const char *name)
1581 {
1582         return !strcmp(name, "cpu") || is_arm_pmu_core(name);
1583 }
1584
1585 static bool pmu_alias_is_duplicate(struct sevent *alias_a,
1586                                    struct sevent *alias_b)
1587 {
1588         const char *a_pmu_name, *b_pmu_name;
1589         const char *a_name = alias_a->event ? alias_a->event->name : "//";
1590         const char *b_name = alias_b->event ? alias_b->event->name : "//";
1591
1592         /* Different names -> never duplicates */
1593         if (strcmp(a_name, b_name))
1594                 return false;
1595
1596         /* Don't remove duplicates for different PMUs */
1597         a_pmu_name = alias_a->pmu->name ?: "";
1598         b_pmu_name = alias_b->pmu->name ?: "";
1599         return strcmp(a_pmu_name, b_pmu_name) == 0;
1600 }
1601
1602 void print_pmu_events(const struct print_callbacks *print_cb, void *print_state)
1603 {
1604         struct perf_pmu *pmu;
1605         struct perf_pmu_alias *event;
1606         char buf[1024];
1607         int printed = 0;
1608         int len, j;
1609         struct sevent *aliases;
1610
1611         pmu = NULL;
1612         len = 0;
1613         while ((pmu = perf_pmu__scan(pmu)) != NULL) {
1614                 list_for_each_entry(event, &pmu->aliases, list)
1615                         len++;
1616                 if (pmu->selectable)
1617                         len++;
1618         }
1619         aliases = zalloc(sizeof(struct sevent) * len);
1620         if (!aliases) {
1621                 pr_err("FATAL: not enough memory to print PMU events\n");
1622                 return;
1623         }
1624         pmu = NULL;
1625         j = 0;
1626         while ((pmu = perf_pmu__scan(pmu)) != NULL) {
1627                 bool is_cpu = is_pmu_core(pmu->name) || perf_pmu__is_hybrid(pmu->name);
1628
1629                 list_for_each_entry(event, &pmu->aliases, list) {
1630                         aliases[j].event = event;
1631                         aliases[j].pmu = pmu;
1632                         aliases[j].is_cpu = is_cpu;
1633                         j++;
1634                 }
1635                 if (pmu->selectable) {
1636                         aliases[j].event = NULL;
1637                         aliases[j].pmu = pmu;
1638                         aliases[j].is_cpu = is_cpu;
1639                         j++;
1640                 }
1641         }
1642         len = j;
1643         qsort(aliases, len, sizeof(struct sevent), cmp_sevent);
1644         for (j = 0; j < len; j++) {
1645                 const char *name, *alias = NULL, *scale_unit = NULL,
1646                         *desc = NULL, *long_desc = NULL,
1647                         *encoding_desc = NULL, *topic = NULL;
1648                 bool deprecated = false;
1649                 size_t buf_used;
1650
1651                 /* Skip duplicates */
1652                 if (j > 0 && pmu_alias_is_duplicate(&aliases[j], &aliases[j - 1]))
1653                         continue;
1654
1655                 if (!aliases[j].event) {
1656                         /* A selectable event. */
1657                         buf_used = snprintf(buf, sizeof(buf), "%s//", aliases[j].pmu->name) + 1;
1658                         name = buf;
1659                 } else {
1660                         if (aliases[j].event->desc) {
1661                                 name = aliases[j].event->name;
1662                                 buf_used = 0;
1663                         } else {
1664                                 name = format_alias(buf, sizeof(buf), aliases[j].pmu,
1665                                                     aliases[j].event);
1666                                 if (aliases[j].is_cpu) {
1667                                         alias = name;
1668                                         name = aliases[j].event->name;
1669                                 }
1670                                 buf_used = strlen(buf) + 1;
1671                         }
1672                         if (strlen(aliases[j].event->unit) || aliases[j].event->scale != 1.0) {
1673                                 scale_unit = buf + buf_used;
1674                                 buf_used += snprintf(buf + buf_used, sizeof(buf) - buf_used,
1675                                                 "%G%s", aliases[j].event->scale,
1676                                                 aliases[j].event->unit) + 1;
1677                         }
1678                         desc = aliases[j].event->desc;
1679                         long_desc = aliases[j].event->long_desc;
1680                         topic = aliases[j].event->topic;
1681                         encoding_desc = buf + buf_used;
1682                         buf_used += snprintf(buf + buf_used, sizeof(buf) - buf_used,
1683                                         "%s/%s/", aliases[j].pmu->name,
1684                                         aliases[j].event->str) + 1;
1685                         deprecated = aliases[j].event->deprecated;
1686                 }
1687                 print_cb->print_event(print_state,
1688                                 aliases[j].pmu->name,
1689                                 topic,
1690                                 name,
1691                                 alias,
1692                                 scale_unit,
1693                                 deprecated,
1694                                 "Kernel PMU event",
1695                                 desc,
1696                                 long_desc,
1697                                 encoding_desc);
1698         }
1699         if (printed && pager_in_use())
1700                 printf("\n");
1701
1702         zfree(&aliases);
1703         return;
1704 }
1705
1706 bool pmu_have_event(const char *pname, const char *name)
1707 {
1708         struct perf_pmu *pmu;
1709         struct perf_pmu_alias *alias;
1710
1711         pmu = NULL;
1712         while ((pmu = perf_pmu__scan(pmu)) != NULL) {
1713                 if (strcmp(pname, pmu->name))
1714                         continue;
1715                 list_for_each_entry(alias, &pmu->aliases, list)
1716                         if (!strcmp(alias->name, name))
1717                                 return true;
1718         }
1719         return false;
1720 }
1721
1722 FILE *perf_pmu__open_file(struct perf_pmu *pmu, const char *name)
1723 {
1724         char path[PATH_MAX];
1725
1726         if (!perf_pmu__pathname_scnprintf(path, sizeof(path), pmu->name, name) ||
1727             !file_available(path))
1728                 return NULL;
1729
1730         return fopen(path, "r");
1731 }
1732
1733 int perf_pmu__scan_file(struct perf_pmu *pmu, const char *name, const char *fmt,
1734                         ...)
1735 {
1736         va_list args;
1737         FILE *file;
1738         int ret = EOF;
1739
1740         va_start(args, fmt);
1741         file = perf_pmu__open_file(pmu, name);
1742         if (file) {
1743                 ret = vfscanf(file, fmt, args);
1744                 fclose(file);
1745         }
1746         va_end(args);
1747         return ret;
1748 }
1749
1750 bool perf_pmu__file_exists(struct perf_pmu *pmu, const char *name)
1751 {
1752         char path[PATH_MAX];
1753
1754         if (!perf_pmu__pathname_scnprintf(path, sizeof(path), pmu->name, name))
1755                 return false;
1756
1757         return file_available(path);
1758 }
1759
1760 static int perf_pmu__new_caps(struct list_head *list, char *name, char *value)
1761 {
1762         struct perf_pmu_caps *caps = zalloc(sizeof(*caps));
1763
1764         if (!caps)
1765                 return -ENOMEM;
1766
1767         caps->name = strdup(name);
1768         if (!caps->name)
1769                 goto free_caps;
1770         caps->value = strndup(value, strlen(value) - 1);
1771         if (!caps->value)
1772                 goto free_name;
1773         list_add_tail(&caps->list, list);
1774         return 0;
1775
1776 free_name:
1777         zfree(caps->name);
1778 free_caps:
1779         free(caps);
1780
1781         return -ENOMEM;
1782 }
1783
1784 static void perf_pmu__del_caps(struct perf_pmu *pmu)
1785 {
1786         struct perf_pmu_caps *caps, *tmp;
1787
1788         list_for_each_entry_safe(caps, tmp, &pmu->caps, list) {
1789                 list_del(&caps->list);
1790                 free(caps->name);
1791                 free(caps->value);
1792                 free(caps);
1793         }
1794 }
1795
1796 /*
1797  * Reading/parsing the given pmu capabilities, which should be located at:
1798  * /sys/bus/event_source/devices/<dev>/caps as sysfs group attributes.
1799  * Return the number of capabilities
1800  */
1801 int perf_pmu__caps_parse(struct perf_pmu *pmu)
1802 {
1803         struct stat st;
1804         char caps_path[PATH_MAX];
1805         DIR *caps_dir;
1806         struct dirent *evt_ent;
1807
1808         if (pmu->caps_initialized)
1809                 return pmu->nr_caps;
1810
1811         pmu->nr_caps = 0;
1812
1813         if (!perf_pmu__pathname_scnprintf(caps_path, sizeof(caps_path), pmu->name, "caps"))
1814                 return -1;
1815
1816         if (stat(caps_path, &st) < 0) {
1817                 pmu->caps_initialized = true;
1818                 return 0;       /* no error if caps does not exist */
1819         }
1820
1821         caps_dir = opendir(caps_path);
1822         if (!caps_dir)
1823                 return -EINVAL;
1824
1825         while ((evt_ent = readdir(caps_dir)) != NULL) {
1826                 char path[PATH_MAX + NAME_MAX + 1];
1827                 char *name = evt_ent->d_name;
1828                 char value[128];
1829                 FILE *file;
1830
1831                 if (!strcmp(name, ".") || !strcmp(name, ".."))
1832                         continue;
1833
1834                 snprintf(path, sizeof(path), "%s/%s", caps_path, name);
1835
1836                 file = fopen(path, "r");
1837                 if (!file)
1838                         continue;
1839
1840                 if (!fgets(value, sizeof(value), file) ||
1841                     (perf_pmu__new_caps(&pmu->caps, name, value) < 0)) {
1842                         fclose(file);
1843                         continue;
1844                 }
1845
1846                 pmu->nr_caps++;
1847                 fclose(file);
1848         }
1849
1850         closedir(caps_dir);
1851
1852         pmu->caps_initialized = true;
1853         return pmu->nr_caps;
1854 }
1855
1856 void perf_pmu__warn_invalid_config(struct perf_pmu *pmu, __u64 config,
1857                                    const char *name)
1858 {
1859         struct perf_pmu_format *format;
1860         __u64 masks = 0, bits;
1861         char buf[100];
1862         unsigned int i;
1863
1864         list_for_each_entry(format, &pmu->format, list) {
1865                 if (format->value != PERF_PMU_FORMAT_VALUE_CONFIG)
1866                         continue;
1867
1868                 for_each_set_bit(i, format->bits, PERF_PMU_FORMAT_BITS)
1869                         masks |= 1ULL << i;
1870         }
1871
1872         /*
1873          * Kernel doesn't export any valid format bits.
1874          */
1875         if (masks == 0)
1876                 return;
1877
1878         bits = config & ~masks;
1879         if (bits == 0)
1880                 return;
1881
1882         bitmap_scnprintf((unsigned long *)&bits, sizeof(bits) * 8, buf, sizeof(buf));
1883
1884         pr_warning("WARNING: event '%s' not valid (bits %s of config "
1885                    "'%llx' not supported by kernel)!\n",
1886                    name ?: "N/A", buf, config);
1887 }
1888
1889 bool perf_pmu__has_hybrid(void)
1890 {
1891         if (!hybrid_scanned) {
1892                 hybrid_scanned = true;
1893                 perf_pmu__scan(NULL);
1894         }
1895
1896         return !list_empty(&perf_pmu__hybrid_pmus);
1897 }
1898
1899 int perf_pmu__match(char *pattern, char *name, char *tok)
1900 {
1901         if (!name)
1902                 return -1;
1903
1904         if (fnmatch(pattern, name, 0))
1905                 return -1;
1906
1907         if (tok && !perf_pmu__valid_suffix(name, tok))
1908                 return -1;
1909
1910         return 0;
1911 }
1912
1913 int perf_pmu__cpus_match(struct perf_pmu *pmu, struct perf_cpu_map *cpus,
1914                          struct perf_cpu_map **mcpus_ptr,
1915                          struct perf_cpu_map **ucpus_ptr)
1916 {
1917         struct perf_cpu_map *pmu_cpus = pmu->cpus;
1918         struct perf_cpu_map *matched_cpus, *unmatched_cpus;
1919         struct perf_cpu cpu;
1920         int i, matched_nr = 0, unmatched_nr = 0;
1921
1922         matched_cpus = perf_cpu_map__default_new();
1923         if (!matched_cpus)
1924                 return -1;
1925
1926         unmatched_cpus = perf_cpu_map__default_new();
1927         if (!unmatched_cpus) {
1928                 perf_cpu_map__put(matched_cpus);
1929                 return -1;
1930         }
1931
1932         perf_cpu_map__for_each_cpu(cpu, i, cpus) {
1933                 if (!perf_cpu_map__has(pmu_cpus, cpu))
1934                         unmatched_cpus->map[unmatched_nr++] = cpu;
1935                 else
1936                         matched_cpus->map[matched_nr++] = cpu;
1937         }
1938
1939         unmatched_cpus->nr = unmatched_nr;
1940         matched_cpus->nr = matched_nr;
1941         *mcpus_ptr = matched_cpus;
1942         *ucpus_ptr = unmatched_cpus;
1943         return 0;
1944 }
1945
1946 double __weak perf_pmu__cpu_slots_per_cycle(void)
1947 {
1948         return NAN;
1949 }
1950
1951 int perf_pmu__event_source_devices_scnprintf(char *pathname, size_t size)
1952 {
1953         const char *sysfs = sysfs__mountpoint();
1954
1955         if (!sysfs)
1956                 return 0;
1957         return scnprintf(pathname, size, "%s/bus/event_source/devices/", sysfs);
1958 }
1959
1960 int perf_pmu__event_source_devices_fd(void)
1961 {
1962         char path[PATH_MAX];
1963         const char *sysfs = sysfs__mountpoint();
1964
1965         if (!sysfs)
1966                 return -1;
1967
1968         scnprintf(path, sizeof(path), "%s/bus/event_source/devices/", sysfs);
1969         return open(path, O_DIRECTORY);
1970 }
1971
1972 /*
1973  * Fill 'buf' with the path to a file or folder in 'pmu_name' in
1974  * sysfs. For example if pmu_name = "cs_etm" and 'filename' = "format"
1975  * then pathname will be filled with
1976  * "/sys/bus/event_source/devices/cs_etm/format"
1977  *
1978  * Return 0 if the sysfs mountpoint couldn't be found or if no
1979  * characters were written.
1980  */
1981 int perf_pmu__pathname_scnprintf(char *buf, size_t size,
1982                                  const char *pmu_name, const char *filename)
1983 {
1984         char base_path[PATH_MAX];
1985
1986         if (!perf_pmu__event_source_devices_scnprintf(base_path, sizeof(base_path)))
1987                 return 0;
1988         return scnprintf(buf, size, "%s%s/%s", base_path, pmu_name, filename);
1989 }
1990
1991 int perf_pmu__pathname_fd(int dirfd, const char *pmu_name, const char *filename, int flags)
1992 {
1993         char path[PATH_MAX];
1994
1995         scnprintf(path, sizeof(path), "%s/%s", pmu_name, filename);
1996         return openat(dirfd, path, flags);
1997 }
1998
1999 static void perf_pmu__delete(struct perf_pmu *pmu)
2000 {
2001         perf_pmu__del_formats(&pmu->format);
2002         perf_pmu__del_aliases(pmu);
2003         perf_pmu__del_caps(pmu);
2004
2005         perf_cpu_map__put(pmu->cpus);
2006
2007         free(pmu->default_config);
2008         free(pmu->name);
2009         free(pmu->alias_name);
2010         free(pmu);
2011 }
2012
2013 void perf_pmu__destroy(void)
2014 {
2015         struct perf_pmu *pmu, *tmp;
2016
2017         list_for_each_entry_safe(pmu, tmp, &pmus, list) {
2018                 list_del(&pmu->list);
2019                 list_del(&pmu->hybrid_list);
2020
2021                 perf_pmu__delete(pmu);
2022         }
2023 }