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