]> asedeno.scripts.mit.edu Git - linux.git/blob - tools/perf/pmu-events/jevents.c
Merge tag 'io_uring-5.6-2020-03-13' of git://git.kernel.dk/linux-block
[linux.git] / tools / perf / pmu-events / jevents.c
1 #define  _XOPEN_SOURCE 500      /* needed for nftw() */
2 #define  _GNU_SOURCE            /* needed for asprintf() */
3
4 /* Parse event JSON files */
5
6 /*
7  * Copyright (c) 2014, Intel Corporation
8  * All rights reserved.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions are met:
12  *
13  * 1. Redistributions of source code must retain the above copyright notice,
14  * this list of conditions and the following disclaimer.
15  *
16  * 2. Redistributions in binary form must reproduce the above copyright
17  * notice, this list of conditions and the following disclaimer in the
18  * documentation and/or other materials provided with the distribution.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
23  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
24  * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
25  * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
26  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
27  * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
29  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
30  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
31  * OF THE POSSIBILITY OF SUCH DAMAGE.
32 */
33
34 #include <stdio.h>
35 #include <stdlib.h>
36 #include <errno.h>
37 #include <string.h>
38 #include <ctype.h>
39 #include <unistd.h>
40 #include <stdarg.h>
41 #include <libgen.h>
42 #include <limits.h>
43 #include <dirent.h>
44 #include <sys/time.h>                   /* getrlimit */
45 #include <sys/resource.h>               /* getrlimit */
46 #include <ftw.h>
47 #include <sys/stat.h>
48 #include <linux/list.h>
49 #include "jsmn.h"
50 #include "json.h"
51 #include "jevents.h"
52
53 int verbose;
54 char *prog;
55
56 int eprintf(int level, int var, const char *fmt, ...)
57 {
58
59         int ret;
60         va_list args;
61
62         if (var < level)
63                 return 0;
64
65         va_start(args, fmt);
66
67         ret = vfprintf(stderr, fmt, args);
68
69         va_end(args);
70
71         return ret;
72 }
73
74 __attribute__((weak)) char *get_cpu_str(void)
75 {
76         return NULL;
77 }
78
79 static void addfield(char *map, char **dst, const char *sep,
80                      const char *a, jsmntok_t *bt)
81 {
82         unsigned int len = strlen(a) + 1 + strlen(sep);
83         int olen = *dst ? strlen(*dst) : 0;
84         int blen = bt ? json_len(bt) : 0;
85         char *out;
86
87         out = realloc(*dst, len + olen + blen);
88         if (!out) {
89                 /* Don't add field in this case */
90                 return;
91         }
92         *dst = out;
93
94         if (!olen)
95                 *(*dst) = 0;
96         else
97                 strcat(*dst, sep);
98         strcat(*dst, a);
99         if (bt)
100                 strncat(*dst, map + bt->start, blen);
101 }
102
103 static void fixname(char *s)
104 {
105         for (; *s; s++)
106                 *s = tolower(*s);
107 }
108
109 static void fixdesc(char *s)
110 {
111         char *e = s + strlen(s);
112
113         /* Remove trailing dots that look ugly in perf list */
114         --e;
115         while (e >= s && isspace(*e))
116                 --e;
117         if (*e == '.')
118                 *e = 0;
119 }
120
121 /* Add escapes for '\' so they are proper C strings. */
122 static char *fixregex(char *s)
123 {
124         int len = 0;
125         int esc_count = 0;
126         char *fixed = NULL;
127         char *p, *q;
128
129         /* Count the number of '\' in string */
130         for (p = s; *p; p++) {
131                 ++len;
132                 if (*p == '\\')
133                         ++esc_count;
134         }
135
136         if (esc_count == 0)
137                 return s;
138
139         /* allocate space for a new string */
140         fixed = (char *) malloc(len + 1);
141         if (!fixed)
142                 return NULL;
143
144         /* copy over the characters */
145         q = fixed;
146         for (p = s; *p; p++) {
147                 if (*p == '\\') {
148                         *q = '\\';
149                         ++q;
150                 }
151                 *q = *p;
152                 ++q;
153         }
154         *q = '\0';
155         return fixed;
156 }
157
158 static struct msrmap {
159         const char *num;
160         const char *pname;
161 } msrmap[] = {
162         { "0x3F6", "ldlat=" },
163         { "0x1A6", "offcore_rsp=" },
164         { "0x1A7", "offcore_rsp=" },
165         { "0x3F7", "frontend=" },
166         { NULL, NULL }
167 };
168
169 static struct field {
170         const char *field;
171         const char *kernel;
172 } fields[] = {
173         { "UMask",      "umask=" },
174         { "CounterMask", "cmask=" },
175         { "Invert",     "inv=" },
176         { "AnyThread",  "any=" },
177         { "EdgeDetect", "edge=" },
178         { "SampleAfterValue", "period=" },
179         { "FCMask",     "fc_mask=" },
180         { "PortMask",   "ch_mask=" },
181         { NULL, NULL }
182 };
183
184 static void cut_comma(char *map, jsmntok_t *newval)
185 {
186         int i;
187
188         /* Cut off everything after comma */
189         for (i = newval->start; i < newval->end; i++) {
190                 if (map[i] == ',')
191                         newval->end = i;
192         }
193 }
194
195 static int match_field(char *map, jsmntok_t *field, int nz,
196                        char **event, jsmntok_t *val)
197 {
198         struct field *f;
199         jsmntok_t newval = *val;
200
201         for (f = fields; f->field; f++)
202                 if (json_streq(map, field, f->field) && nz) {
203                         cut_comma(map, &newval);
204                         addfield(map, event, ",", f->kernel, &newval);
205                         return 1;
206                 }
207         return 0;
208 }
209
210 static struct msrmap *lookup_msr(char *map, jsmntok_t *val)
211 {
212         jsmntok_t newval = *val;
213         static bool warned;
214         int i;
215
216         cut_comma(map, &newval);
217         for (i = 0; msrmap[i].num; i++)
218                 if (json_streq(map, &newval, msrmap[i].num))
219                         return &msrmap[i];
220         if (!warned) {
221                 warned = true;
222                 pr_err("%s: Unknown MSR in event file %.*s\n", prog,
223                         json_len(val), map + val->start);
224         }
225         return NULL;
226 }
227
228 static struct map {
229         const char *json;
230         const char *perf;
231 } unit_to_pmu[] = {
232         { "CBO", "uncore_cbox" },
233         { "QPI LL", "uncore_qpi" },
234         { "SBO", "uncore_sbox" },
235         { "iMPH-U", "uncore_arb" },
236         { "CPU-M-CF", "cpum_cf" },
237         { "CPU-M-SF", "cpum_sf" },
238         { "UPI LL", "uncore_upi" },
239         { "hisi_sccl,ddrc", "hisi_sccl,ddrc" },
240         { "hisi_sccl,hha", "hisi_sccl,hha" },
241         { "hisi_sccl,l3c", "hisi_sccl,l3c" },
242         { "L3PMC", "amd_l3" },
243         {}
244 };
245
246 static const char *field_to_perf(struct map *table, char *map, jsmntok_t *val)
247 {
248         int i;
249
250         for (i = 0; table[i].json; i++) {
251                 if (json_streq(map, val, table[i].json))
252                         return table[i].perf;
253         }
254         return NULL;
255 }
256
257 #define EXPECT(e, t, m) do { if (!(e)) {                        \
258         jsmntok_t *loc = (t);                                   \
259         if (!(t)->start && (t) > tokens)                        \
260                 loc = (t) - 1;                                  \
261         pr_err("%s:%d: " m ", got %s\n", fn,                    \
262                json_line(map, loc),                             \
263                json_name(t));                                   \
264         err = -EIO;                                             \
265         goto out_free;                                          \
266 } } while (0)
267
268 static char *topic;
269
270 static char *get_topic(void)
271 {
272         char *tp;
273         int i;
274
275         /* tp is free'd in process_one_file() */
276         i = asprintf(&tp, "%s", topic);
277         if (i < 0) {
278                 pr_info("%s: asprintf() error %s\n", prog);
279                 return NULL;
280         }
281
282         for (i = 0; i < (int) strlen(tp); i++) {
283                 char c = tp[i];
284
285                 if (c == '-')
286                         tp[i] = ' ';
287                 else if (c == '.') {
288                         tp[i] = '\0';
289                         break;
290                 }
291         }
292
293         return tp;
294 }
295
296 static int add_topic(char *bname)
297 {
298         free(topic);
299         topic = strdup(bname);
300         if (!topic) {
301                 pr_info("%s: strdup() error %s for file %s\n", prog,
302                                 strerror(errno), bname);
303                 return -ENOMEM;
304         }
305         return 0;
306 }
307
308 struct perf_entry_data {
309         FILE *outfp;
310         char *topic;
311 };
312
313 static int close_table;
314
315 static void print_events_table_prefix(FILE *fp, const char *tblname)
316 {
317         fprintf(fp, "struct pmu_event %s[] = {\n", tblname);
318         close_table = 1;
319 }
320
321 static int print_events_table_entry(void *data, char *name, char *event,
322                                     char *desc, char *long_desc,
323                                     char *pmu, char *unit, char *perpkg,
324                                     char *metric_expr,
325                                     char *metric_name, char *metric_group,
326                                     char *deprecated)
327 {
328         struct perf_entry_data *pd = data;
329         FILE *outfp = pd->outfp;
330         char *topic = pd->topic;
331
332         /*
333          * TODO: Remove formatting chars after debugging to reduce
334          *       string lengths.
335          */
336         fprintf(outfp, "{\n");
337
338         if (name)
339                 fprintf(outfp, "\t.name = \"%s\",\n", name);
340         if (event)
341                 fprintf(outfp, "\t.event = \"%s\",\n", event);
342         fprintf(outfp, "\t.desc = \"%s\",\n", desc);
343         fprintf(outfp, "\t.topic = \"%s\",\n", topic);
344         if (long_desc && long_desc[0])
345                 fprintf(outfp, "\t.long_desc = \"%s\",\n", long_desc);
346         if (pmu)
347                 fprintf(outfp, "\t.pmu = \"%s\",\n", pmu);
348         if (unit)
349                 fprintf(outfp, "\t.unit = \"%s\",\n", unit);
350         if (perpkg)
351                 fprintf(outfp, "\t.perpkg = \"%s\",\n", perpkg);
352         if (metric_expr)
353                 fprintf(outfp, "\t.metric_expr = \"%s\",\n", metric_expr);
354         if (metric_name)
355                 fprintf(outfp, "\t.metric_name = \"%s\",\n", metric_name);
356         if (metric_group)
357                 fprintf(outfp, "\t.metric_group = \"%s\",\n", metric_group);
358         if (deprecated)
359                 fprintf(outfp, "\t.deprecated = \"%s\",\n", deprecated);
360         fprintf(outfp, "},\n");
361
362         return 0;
363 }
364
365 struct event_struct {
366         struct list_head list;
367         char *name;
368         char *event;
369         char *desc;
370         char *long_desc;
371         char *pmu;
372         char *unit;
373         char *perpkg;
374         char *metric_expr;
375         char *metric_name;
376         char *metric_group;
377         char *deprecated;
378 };
379
380 #define ADD_EVENT_FIELD(field) do { if (field) {                \
381         es->field = strdup(field);                              \
382         if (!es->field)                                         \
383                 goto out_free;                                  \
384 } } while (0)
385
386 #define FREE_EVENT_FIELD(field) free(es->field)
387
388 #define TRY_FIXUP_FIELD(field) do { if (es->field && !*field) {\
389         *field = strdup(es->field);                             \
390         if (!*field)                                            \
391                 return -ENOMEM;                                 \
392 } } while (0)
393
394 #define FOR_ALL_EVENT_STRUCT_FIELDS(op) do {                    \
395         op(name);                                               \
396         op(event);                                              \
397         op(desc);                                               \
398         op(long_desc);                                          \
399         op(pmu);                                                \
400         op(unit);                                               \
401         op(perpkg);                                             \
402         op(metric_expr);                                        \
403         op(metric_name);                                        \
404         op(metric_group);                                       \
405         op(deprecated);                                         \
406 } while (0)
407
408 static LIST_HEAD(arch_std_events);
409
410 static void free_arch_std_events(void)
411 {
412         struct event_struct *es, *next;
413
414         list_for_each_entry_safe(es, next, &arch_std_events, list) {
415                 FOR_ALL_EVENT_STRUCT_FIELDS(FREE_EVENT_FIELD);
416                 list_del_init(&es->list);
417                 free(es);
418         }
419 }
420
421 static int save_arch_std_events(void *data, char *name, char *event,
422                                 char *desc, char *long_desc, char *pmu,
423                                 char *unit, char *perpkg, char *metric_expr,
424                                 char *metric_name, char *metric_group,
425                                 char *deprecated)
426 {
427         struct event_struct *es;
428
429         es = malloc(sizeof(*es));
430         if (!es)
431                 return -ENOMEM;
432         memset(es, 0, sizeof(*es));
433         FOR_ALL_EVENT_STRUCT_FIELDS(ADD_EVENT_FIELD);
434         list_add_tail(&es->list, &arch_std_events);
435         return 0;
436 out_free:
437         FOR_ALL_EVENT_STRUCT_FIELDS(FREE_EVENT_FIELD);
438         free(es);
439         return -ENOMEM;
440 }
441
442 static void print_events_table_suffix(FILE *outfp)
443 {
444         fprintf(outfp, "{\n");
445
446         fprintf(outfp, "\t.name = 0,\n");
447         fprintf(outfp, "\t.event = 0,\n");
448         fprintf(outfp, "\t.desc = 0,\n");
449
450         fprintf(outfp, "},\n");
451         fprintf(outfp, "};\n");
452         close_table = 0;
453 }
454
455 static struct fixed {
456         const char *name;
457         const char *event;
458 } fixed[] = {
459         { "inst_retired.any", "event=0xc0,period=2000003" },
460         { "inst_retired.any_p", "event=0xc0,period=2000003" },
461         { "cpu_clk_unhalted.ref", "event=0x0,umask=0x03,period=2000003" },
462         { "cpu_clk_unhalted.thread", "event=0x3c,period=2000003" },
463         { "cpu_clk_unhalted.core", "event=0x3c,period=2000003" },
464         { "cpu_clk_unhalted.thread_any", "event=0x3c,any=1,period=2000003" },
465         { NULL, NULL},
466 };
467
468 /*
469  * Handle different fixed counter encodings between JSON and perf.
470  */
471 static char *real_event(const char *name, char *event)
472 {
473         int i;
474
475         if (!name)
476                 return NULL;
477
478         for (i = 0; fixed[i].name; i++)
479                 if (!strcasecmp(name, fixed[i].name))
480                         return (char *)fixed[i].event;
481         return event;
482 }
483
484 static int
485 try_fixup(const char *fn, char *arch_std, char **event, char **desc,
486           char **name, char **long_desc, char **pmu, char **filter,
487           char **perpkg, char **unit, char **metric_expr, char **metric_name,
488           char **metric_group, unsigned long long eventcode,
489           char **deprecated)
490 {
491         /* try to find matching event from arch standard values */
492         struct event_struct *es;
493
494         list_for_each_entry(es, &arch_std_events, list) {
495                 if (!strcmp(arch_std, es->name)) {
496                         if (!eventcode && es->event) {
497                                 /* allow EventCode to be overridden */
498                                 free(*event);
499                                 *event = NULL;
500                         }
501                         FOR_ALL_EVENT_STRUCT_FIELDS(TRY_FIXUP_FIELD);
502                         return 0;
503                 }
504         }
505
506         pr_err("%s: could not find matching %s for %s\n",
507                                         prog, arch_std, fn);
508         return -1;
509 }
510
511 /* Call func with each event in the json file */
512 int json_events(const char *fn,
513           int (*func)(void *data, char *name, char *event, char *desc,
514                       char *long_desc,
515                       char *pmu, char *unit, char *perpkg,
516                       char *metric_expr,
517                       char *metric_name, char *metric_group,
518                       char *deprecated),
519           void *data)
520 {
521         int err;
522         size_t size;
523         jsmntok_t *tokens, *tok;
524         int i, j, len;
525         char *map;
526         char buf[128];
527
528         if (!fn)
529                 return -ENOENT;
530
531         tokens = parse_json(fn, &map, &size, &len);
532         if (!tokens)
533                 return -EIO;
534         EXPECT(tokens->type == JSMN_ARRAY, tokens, "expected top level array");
535         tok = tokens + 1;
536         for (i = 0; i < tokens->size; i++) {
537                 char *event = NULL, *desc = NULL, *name = NULL;
538                 char *long_desc = NULL;
539                 char *extra_desc = NULL;
540                 char *pmu = NULL;
541                 char *filter = NULL;
542                 char *perpkg = NULL;
543                 char *unit = NULL;
544                 char *metric_expr = NULL;
545                 char *metric_name = NULL;
546                 char *metric_group = NULL;
547                 char *deprecated = NULL;
548                 char *arch_std = NULL;
549                 unsigned long long eventcode = 0;
550                 struct msrmap *msr = NULL;
551                 jsmntok_t *msrval = NULL;
552                 jsmntok_t *precise = NULL;
553                 jsmntok_t *obj = tok++;
554
555                 EXPECT(obj->type == JSMN_OBJECT, obj, "expected object");
556                 for (j = 0; j < obj->size; j += 2) {
557                         jsmntok_t *field, *val;
558                         int nz;
559                         char *s;
560
561                         field = tok + j;
562                         EXPECT(field->type == JSMN_STRING, tok + j,
563                                "Expected field name");
564                         val = tok + j + 1;
565                         EXPECT(val->type == JSMN_STRING, tok + j + 1,
566                                "Expected string value");
567
568                         nz = !json_streq(map, val, "0");
569                         if (match_field(map, field, nz, &event, val)) {
570                                 /* ok */
571                         } else if (json_streq(map, field, "EventCode")) {
572                                 char *code = NULL;
573                                 addfield(map, &code, "", "", val);
574                                 eventcode |= strtoul(code, NULL, 0);
575                                 free(code);
576                         } else if (json_streq(map, field, "ExtSel")) {
577                                 char *code = NULL;
578                                 addfield(map, &code, "", "", val);
579                                 eventcode |= strtoul(code, NULL, 0) << 21;
580                                 free(code);
581                         } else if (json_streq(map, field, "EventName")) {
582                                 addfield(map, &name, "", "", val);
583                         } else if (json_streq(map, field, "BriefDescription")) {
584                                 addfield(map, &desc, "", "", val);
585                                 fixdesc(desc);
586                         } else if (json_streq(map, field,
587                                              "PublicDescription")) {
588                                 addfield(map, &long_desc, "", "", val);
589                                 fixdesc(long_desc);
590                         } else if (json_streq(map, field, "PEBS") && nz) {
591                                 precise = val;
592                         } else if (json_streq(map, field, "MSRIndex") && nz) {
593                                 msr = lookup_msr(map, val);
594                         } else if (json_streq(map, field, "MSRValue")) {
595                                 msrval = val;
596                         } else if (json_streq(map, field, "Errata") &&
597                                    !json_streq(map, val, "null")) {
598                                 addfield(map, &extra_desc, ". ",
599                                         " Spec update: ", val);
600                         } else if (json_streq(map, field, "Data_LA") && nz) {
601                                 addfield(map, &extra_desc, ". ",
602                                         " Supports address when precise",
603                                         NULL);
604                         } else if (json_streq(map, field, "Unit")) {
605                                 const char *ppmu;
606
607                                 ppmu = field_to_perf(unit_to_pmu, map, val);
608                                 if (ppmu) {
609                                         pmu = strdup(ppmu);
610                                 } else {
611                                         if (!pmu)
612                                                 pmu = strdup("uncore_");
613                                         addfield(map, &pmu, "", "", val);
614                                         for (s = pmu; *s; s++)
615                                                 *s = tolower(*s);
616                                 }
617                                 addfield(map, &desc, ". ", "Unit: ", NULL);
618                                 addfield(map, &desc, "", pmu, NULL);
619                                 addfield(map, &desc, "", " ", NULL);
620                         } else if (json_streq(map, field, "Filter")) {
621                                 addfield(map, &filter, "", "", val);
622                         } else if (json_streq(map, field, "ScaleUnit")) {
623                                 addfield(map, &unit, "", "", val);
624                         } else if (json_streq(map, field, "PerPkg")) {
625                                 addfield(map, &perpkg, "", "", val);
626                         } else if (json_streq(map, field, "Deprecated")) {
627                                 addfield(map, &deprecated, "", "", val);
628                         } else if (json_streq(map, field, "MetricName")) {
629                                 addfield(map, &metric_name, "", "", val);
630                         } else if (json_streq(map, field, "MetricGroup")) {
631                                 addfield(map, &metric_group, "", "", val);
632                         } else if (json_streq(map, field, "MetricExpr")) {
633                                 addfield(map, &metric_expr, "", "", val);
634                                 for (s = metric_expr; *s; s++)
635                                         *s = tolower(*s);
636                         } else if (json_streq(map, field, "ArchStdEvent")) {
637                                 addfield(map, &arch_std, "", "", val);
638                                 for (s = arch_std; *s; s++)
639                                         *s = tolower(*s);
640                         }
641                         /* ignore unknown fields */
642                 }
643                 if (precise && desc && !strstr(desc, "(Precise Event)")) {
644                         if (json_streq(map, precise, "2"))
645                                 addfield(map, &extra_desc, " ",
646                                                 "(Must be precise)", NULL);
647                         else
648                                 addfield(map, &extra_desc, " ",
649                                                 "(Precise event)", NULL);
650                 }
651                 snprintf(buf, sizeof buf, "event=%#llx", eventcode);
652                 addfield(map, &event, ",", buf, NULL);
653                 if (desc && extra_desc)
654                         addfield(map, &desc, " ", extra_desc, NULL);
655                 if (long_desc && extra_desc)
656                         addfield(map, &long_desc, " ", extra_desc, NULL);
657                 if (filter)
658                         addfield(map, &event, ",", filter, NULL);
659                 if (msr != NULL)
660                         addfield(map, &event, ",", msr->pname, msrval);
661                 if (name)
662                         fixname(name);
663
664                 if (arch_std) {
665                         /*
666                          * An arch standard event is referenced, so try to
667                          * fixup any unassigned values.
668                          */
669                         err = try_fixup(fn, arch_std, &event, &desc, &name,
670                                         &long_desc, &pmu, &filter, &perpkg,
671                                         &unit, &metric_expr, &metric_name,
672                                         &metric_group, eventcode,
673                                         &deprecated);
674                         if (err)
675                                 goto free_strings;
676                 }
677                 err = func(data, name, real_event(name, event), desc, long_desc,
678                            pmu, unit, perpkg, metric_expr, metric_name,
679                            metric_group, deprecated);
680 free_strings:
681                 free(event);
682                 free(desc);
683                 free(name);
684                 free(long_desc);
685                 free(extra_desc);
686                 free(pmu);
687                 free(filter);
688                 free(perpkg);
689                 free(deprecated);
690                 free(unit);
691                 free(metric_expr);
692                 free(metric_name);
693                 free(metric_group);
694                 free(arch_std);
695
696                 if (err)
697                         break;
698                 tok += j;
699         }
700         EXPECT(tok - tokens == len, tok, "unexpected objects at end");
701         err = 0;
702 out_free:
703         free_json(map, size, tokens);
704         return err;
705 }
706
707 static char *file_name_to_table_name(char *fname)
708 {
709         unsigned int i;
710         int n;
711         int c;
712         char *tblname;
713
714         /*
715          * Ensure tablename starts with alphabetic character.
716          * Derive rest of table name from basename of the JSON file,
717          * replacing hyphens and stripping out .json suffix.
718          */
719         n = asprintf(&tblname, "pme_%s", fname);
720         if (n < 0) {
721                 pr_info("%s: asprintf() error %s for file %s\n", prog,
722                                 strerror(errno), fname);
723                 return NULL;
724         }
725
726         for (i = 0; i < strlen(tblname); i++) {
727                 c = tblname[i];
728
729                 if (c == '-' || c == '/')
730                         tblname[i] = '_';
731                 else if (c == '.') {
732                         tblname[i] = '\0';
733                         break;
734                 } else if (!isalnum(c) && c != '_') {
735                         pr_err("%s: Invalid character '%c' in file name %s\n",
736                                         prog, c, basename(fname));
737                         free(tblname);
738                         tblname = NULL;
739                         break;
740                 }
741         }
742
743         return tblname;
744 }
745
746 static void print_mapping_table_prefix(FILE *outfp)
747 {
748         fprintf(outfp, "struct pmu_events_map pmu_events_map[] = {\n");
749 }
750
751 static void print_mapping_table_suffix(FILE *outfp)
752 {
753         /*
754          * Print the terminating, NULL entry.
755          */
756         fprintf(outfp, "{\n");
757         fprintf(outfp, "\t.cpuid = 0,\n");
758         fprintf(outfp, "\t.version = 0,\n");
759         fprintf(outfp, "\t.type = 0,\n");
760         fprintf(outfp, "\t.table = 0,\n");
761         fprintf(outfp, "},\n");
762
763         /* and finally, the closing curly bracket for the struct */
764         fprintf(outfp, "};\n");
765 }
766
767 static int process_mapfile(FILE *outfp, char *fpath)
768 {
769         int n = 16384;
770         FILE *mapfp;
771         char *save = NULL;
772         char *line, *p;
773         int line_num;
774         char *tblname;
775         int ret = 0;
776
777         pr_info("%s: Processing mapfile %s\n", prog, fpath);
778
779         line = malloc(n);
780         if (!line)
781                 return -1;
782
783         mapfp = fopen(fpath, "r");
784         if (!mapfp) {
785                 pr_info("%s: Error %s opening %s\n", prog, strerror(errno),
786                                 fpath);
787                 free(line);
788                 return -1;
789         }
790
791         print_mapping_table_prefix(outfp);
792
793         /* Skip first line (header) */
794         p = fgets(line, n, mapfp);
795         if (!p)
796                 goto out;
797
798         line_num = 1;
799         while (1) {
800                 char *cpuid, *version, *type, *fname;
801
802                 line_num++;
803                 p = fgets(line, n, mapfp);
804                 if (!p)
805                         break;
806
807                 if (line[0] == '#' || line[0] == '\n')
808                         continue;
809
810                 if (line[strlen(line)-1] != '\n') {
811                         /* TODO Deal with lines longer than 16K */
812                         pr_info("%s: Mapfile %s: line %d too long, aborting\n",
813                                         prog, fpath, line_num);
814                         ret = -1;
815                         goto out;
816                 }
817                 line[strlen(line)-1] = '\0';
818
819                 cpuid = fixregex(strtok_r(p, ",", &save));
820                 version = strtok_r(NULL, ",", &save);
821                 fname = strtok_r(NULL, ",", &save);
822                 type = strtok_r(NULL, ",", &save);
823
824                 tblname = file_name_to_table_name(fname);
825                 fprintf(outfp, "{\n");
826                 fprintf(outfp, "\t.cpuid = \"%s\",\n", cpuid);
827                 fprintf(outfp, "\t.version = \"%s\",\n", version);
828                 fprintf(outfp, "\t.type = \"%s\",\n", type);
829
830                 /*
831                  * CHECK: We can't use the type (eg "core") field in the
832                  * table name. For us to do that, we need to somehow tweak
833                  * the other caller of file_name_to_table(), process_json()
834                  * to determine the type. process_json() file has no way
835                  * of knowing these are "core" events unless file name has
836                  * core in it. If filename has core in it, we can safely
837                  * ignore the type field here also.
838                  */
839                 fprintf(outfp, "\t.table = %s\n", tblname);
840                 fprintf(outfp, "},\n");
841         }
842
843 out:
844         print_mapping_table_suffix(outfp);
845         fclose(mapfp);
846         free(line);
847         return ret;
848 }
849
850 /*
851  * If we fail to locate/process JSON and map files, create a NULL mapping
852  * table. This would at least allow perf to build even if we can't find/use
853  * the aliases.
854  */
855 static void create_empty_mapping(const char *output_file)
856 {
857         FILE *outfp;
858
859         pr_info("%s: Creating empty pmu_events_map[] table\n", prog);
860
861         /* Truncate file to clear any partial writes to it */
862         outfp = fopen(output_file, "w");
863         if (!outfp) {
864                 perror("fopen()");
865                 _Exit(1);
866         }
867
868         fprintf(outfp, "#include \"pmu-events/pmu-events.h\"\n");
869         print_mapping_table_prefix(outfp);
870         print_mapping_table_suffix(outfp);
871         fclose(outfp);
872 }
873
874 static int get_maxfds(void)
875 {
876         struct rlimit rlim;
877
878         if (getrlimit(RLIMIT_NOFILE, &rlim) == 0)
879                 return min((int)rlim.rlim_max / 2, 512);
880
881         return 512;
882 }
883
884 /*
885  * nftw() doesn't let us pass an argument to the processing function,
886  * so use a global variables.
887  */
888 static FILE *eventsfp;
889 static char *mapfile;
890
891 static int is_leaf_dir(const char *fpath)
892 {
893         DIR *d;
894         struct dirent *dir;
895         int res = 1;
896
897         d = opendir(fpath);
898         if (!d)
899                 return 0;
900
901         while ((dir = readdir(d)) != NULL) {
902                 if (!strcmp(dir->d_name, ".") || !strcmp(dir->d_name, ".."))
903                         continue;
904
905                 if (dir->d_type == DT_DIR) {
906                         res = 0;
907                         break;
908                 } else if (dir->d_type == DT_UNKNOWN) {
909                         char path[PATH_MAX];
910                         struct stat st;
911
912                         sprintf(path, "%s/%s", fpath, dir->d_name);
913                         if (stat(path, &st))
914                                 break;
915
916                         if (S_ISDIR(st.st_mode)) {
917                                 res = 0;
918                                 break;
919                         }
920                 }
921         }
922
923         closedir(d);
924
925         return res;
926 }
927
928 static int is_json_file(const char *name)
929 {
930         const char *suffix;
931
932         if (strlen(name) < 5)
933                 return 0;
934
935         suffix = name + strlen(name) - 5;
936
937         if (strncmp(suffix, ".json", 5) == 0)
938                 return 1;
939         return 0;
940 }
941
942 static int preprocess_arch_std_files(const char *fpath, const struct stat *sb,
943                                 int typeflag, struct FTW *ftwbuf)
944 {
945         int level = ftwbuf->level;
946         int is_file = typeflag == FTW_F;
947
948         if (level == 1 && is_file && is_json_file(fpath))
949                 return json_events(fpath, save_arch_std_events, (void *)sb);
950
951         return 0;
952 }
953
954 static int process_one_file(const char *fpath, const struct stat *sb,
955                             int typeflag, struct FTW *ftwbuf)
956 {
957         char *tblname, *bname;
958         int is_dir  = typeflag == FTW_D;
959         int is_file = typeflag == FTW_F;
960         int level   = ftwbuf->level;
961         int err = 0;
962
963         if (level == 2 && is_dir) {
964                 /*
965                  * For level 2 directory, bname will include parent name,
966                  * like vendor/platform. So search back from platform dir
967                  * to find this.
968                  */
969                 bname = (char *) fpath + ftwbuf->base - 2;
970                 for (;;) {
971                         if (*bname == '/')
972                                 break;
973                         bname--;
974                 }
975                 bname++;
976         } else
977                 bname = (char *) fpath + ftwbuf->base;
978
979         pr_debug("%s %d %7jd %-20s %s\n",
980                  is_file ? "f" : is_dir ? "d" : "x",
981                  level, sb->st_size, bname, fpath);
982
983         /* base dir or too deep */
984         if (level == 0 || level > 3)
985                 return 0;
986
987
988         /* model directory, reset topic */
989         if ((level == 1 && is_dir && is_leaf_dir(fpath)) ||
990             (level == 2 && is_dir)) {
991                 if (close_table)
992                         print_events_table_suffix(eventsfp);
993
994                 /*
995                  * Drop file name suffix. Replace hyphens with underscores.
996                  * Fail if file name contains any alphanum characters besides
997                  * underscores.
998                  */
999                 tblname = file_name_to_table_name(bname);
1000                 if (!tblname) {
1001                         pr_info("%s: Error determining table name for %s\n", prog,
1002                                 bname);
1003                         return -1;
1004                 }
1005
1006                 print_events_table_prefix(eventsfp, tblname);
1007                 return 0;
1008         }
1009
1010         /*
1011          * Save the mapfile name for now. We will process mapfile
1012          * after processing all JSON files (so we can write out the
1013          * mapping table after all PMU events tables).
1014          *
1015          */
1016         if (level == 1 && is_file) {
1017                 if (!strcmp(bname, "mapfile.csv")) {
1018                         mapfile = strdup(fpath);
1019                         return 0;
1020                 }
1021
1022                 pr_info("%s: Ignoring file %s\n", prog, fpath);
1023                 return 0;
1024         }
1025
1026         /*
1027          * If the file name does not have a .json extension,
1028          * ignore it. It could be a readme.txt for instance.
1029          */
1030         if (is_file) {
1031                 if (!is_json_file(bname)) {
1032                         pr_info("%s: Ignoring file without .json suffix %s\n", prog,
1033                                 fpath);
1034                         return 0;
1035                 }
1036         }
1037
1038         if (level > 1 && add_topic(bname))
1039                 return -ENOMEM;
1040
1041         /*
1042          * Assume all other files are JSON files.
1043          *
1044          * If mapfile refers to 'power7_core.json', we create a table
1045          * named 'power7_core'. Any inconsistencies between the mapfile
1046          * and directory tree could result in build failure due to table
1047          * names not being found.
1048          *
1049          * Atleast for now, be strict with processing JSON file names.
1050          * i.e. if JSON file name cannot be mapped to C-style table name,
1051          * fail.
1052          */
1053         if (is_file) {
1054                 struct perf_entry_data data = {
1055                         .topic = get_topic(),
1056                         .outfp = eventsfp,
1057                 };
1058
1059                 err = json_events(fpath, print_events_table_entry, &data);
1060
1061                 free(data.topic);
1062         }
1063
1064         return err;
1065 }
1066
1067 #ifndef PATH_MAX
1068 #define PATH_MAX        4096
1069 #endif
1070
1071 /*
1072  * Starting in directory 'start_dirname', find the "mapfile.csv" and
1073  * the set of JSON files for the architecture 'arch'.
1074  *
1075  * From each JSON file, create a C-style "PMU events table" from the
1076  * JSON file (see struct pmu_event).
1077  *
1078  * From the mapfile, create a mapping between the CPU revisions and
1079  * PMU event tables (see struct pmu_events_map).
1080  *
1081  * Write out the PMU events tables and the mapping table to pmu-event.c.
1082  */
1083 int main(int argc, char *argv[])
1084 {
1085         int rc;
1086         int maxfds;
1087         char ldirname[PATH_MAX];
1088
1089         const char *arch;
1090         const char *output_file;
1091         const char *start_dirname;
1092         struct stat stbuf;
1093
1094         prog = basename(argv[0]);
1095         if (argc < 4) {
1096                 pr_err("Usage: %s <arch> <starting_dir> <output_file>\n", prog);
1097                 return 1;
1098         }
1099
1100         arch = argv[1];
1101         start_dirname = argv[2];
1102         output_file = argv[3];
1103
1104         if (argc > 4)
1105                 verbose = atoi(argv[4]);
1106
1107         eventsfp = fopen(output_file, "w");
1108         if (!eventsfp) {
1109                 pr_err("%s Unable to create required file %s (%s)\n",
1110                                 prog, output_file, strerror(errno));
1111                 return 2;
1112         }
1113
1114         sprintf(ldirname, "%s/%s", start_dirname, arch);
1115
1116         /* If architecture does not have any event lists, bail out */
1117         if (stat(ldirname, &stbuf) < 0) {
1118                 pr_info("%s: Arch %s has no PMU event lists\n", prog, arch);
1119                 goto empty_map;
1120         }
1121
1122         /* Include pmu-events.h first */
1123         fprintf(eventsfp, "#include \"pmu-events/pmu-events.h\"\n");
1124
1125         /*
1126          * The mapfile allows multiple CPUids to point to the same JSON file,
1127          * so, not sure if there is a need for symlinks within the pmu-events
1128          * directory.
1129          *
1130          * For now, treat symlinks of JSON files as regular files and create
1131          * separate tables for each symlink (presumably, each symlink refers
1132          * to specific version of the CPU).
1133          */
1134
1135         maxfds = get_maxfds();
1136         mapfile = NULL;
1137         rc = nftw(ldirname, preprocess_arch_std_files, maxfds, 0);
1138         if (rc && verbose) {
1139                 pr_info("%s: Error preprocessing arch standard files %s\n",
1140                         prog, ldirname);
1141                 goto empty_map;
1142         } else if (rc < 0) {
1143                 /* Make build fail */
1144                 fclose(eventsfp);
1145                 free_arch_std_events();
1146                 return 1;
1147         } else if (rc) {
1148                 goto empty_map;
1149         }
1150
1151         rc = nftw(ldirname, process_one_file, maxfds, 0);
1152         if (rc && verbose) {
1153                 pr_info("%s: Error walking file tree %s\n", prog, ldirname);
1154                 goto empty_map;
1155         } else if (rc < 0) {
1156                 /* Make build fail */
1157                 fclose(eventsfp);
1158                 free_arch_std_events();
1159                 return 1;
1160         } else if (rc) {
1161                 goto empty_map;
1162         }
1163
1164         if (close_table)
1165                 print_events_table_suffix(eventsfp);
1166
1167         if (!mapfile) {
1168                 pr_info("%s: No CPU->JSON mapping?\n", prog);
1169                 goto empty_map;
1170         }
1171
1172         if (process_mapfile(eventsfp, mapfile)) {
1173                 pr_info("%s: Error processing mapfile %s\n", prog, mapfile);
1174                 /* Make build fail */
1175                 fclose(eventsfp);
1176                 free_arch_std_events();
1177                 return 1;
1178         }
1179
1180         return 0;
1181
1182 empty_map:
1183         fclose(eventsfp);
1184         create_empty_mapping(output_file);
1185         free_arch_std_events();
1186         return 0;
1187 }