Merge tag 'v5.4-rockchip-dts32-2' of git://git.kernel.org/pub/scm/linux/kernel/git...
[sfrench/cifs-2.6.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         {}
243 };
244
245 static const char *field_to_perf(struct map *table, char *map, jsmntok_t *val)
246 {
247         int i;
248
249         for (i = 0; table[i].json; i++) {
250                 if (json_streq(map, val, table[i].json))
251                         return table[i].perf;
252         }
253         return NULL;
254 }
255
256 #define EXPECT(e, t, m) do { if (!(e)) {                        \
257         jsmntok_t *loc = (t);                                   \
258         if (!(t)->start && (t) > tokens)                        \
259                 loc = (t) - 1;                                  \
260         pr_err("%s:%d: " m ", got %s\n", fn,                    \
261                json_line(map, loc),                             \
262                json_name(t));                                   \
263         err = -EIO;                                             \
264         goto out_free;                                          \
265 } } while (0)
266
267 static char *topic;
268
269 static char *get_topic(void)
270 {
271         char *tp;
272         int i;
273
274         /* tp is free'd in process_one_file() */
275         i = asprintf(&tp, "%s", topic);
276         if (i < 0) {
277                 pr_info("%s: asprintf() error %s\n", prog);
278                 return NULL;
279         }
280
281         for (i = 0; i < (int) strlen(tp); i++) {
282                 char c = tp[i];
283
284                 if (c == '-')
285                         tp[i] = ' ';
286                 else if (c == '.') {
287                         tp[i] = '\0';
288                         break;
289                 }
290         }
291
292         return tp;
293 }
294
295 static int add_topic(char *bname)
296 {
297         free(topic);
298         topic = strdup(bname);
299         if (!topic) {
300                 pr_info("%s: strdup() error %s for file %s\n", prog,
301                                 strerror(errno), bname);
302                 return -ENOMEM;
303         }
304         return 0;
305 }
306
307 struct perf_entry_data {
308         FILE *outfp;
309         char *topic;
310 };
311
312 static int close_table;
313
314 static void print_events_table_prefix(FILE *fp, const char *tblname)
315 {
316         fprintf(fp, "struct pmu_event %s[] = {\n", tblname);
317         close_table = 1;
318 }
319
320 static int print_events_table_entry(void *data, char *name, char *event,
321                                     char *desc, char *long_desc,
322                                     char *pmu, char *unit, char *perpkg,
323                                     char *metric_expr,
324                                     char *metric_name, char *metric_group)
325 {
326         struct perf_entry_data *pd = data;
327         FILE *outfp = pd->outfp;
328         char *topic = pd->topic;
329
330         /*
331          * TODO: Remove formatting chars after debugging to reduce
332          *       string lengths.
333          */
334         fprintf(outfp, "{\n");
335
336         if (name)
337                 fprintf(outfp, "\t.name = \"%s\",\n", name);
338         if (event)
339                 fprintf(outfp, "\t.event = \"%s\",\n", event);
340         fprintf(outfp, "\t.desc = \"%s\",\n", desc);
341         fprintf(outfp, "\t.topic = \"%s\",\n", topic);
342         if (long_desc && long_desc[0])
343                 fprintf(outfp, "\t.long_desc = \"%s\",\n", long_desc);
344         if (pmu)
345                 fprintf(outfp, "\t.pmu = \"%s\",\n", pmu);
346         if (unit)
347                 fprintf(outfp, "\t.unit = \"%s\",\n", unit);
348         if (perpkg)
349                 fprintf(outfp, "\t.perpkg = \"%s\",\n", perpkg);
350         if (metric_expr)
351                 fprintf(outfp, "\t.metric_expr = \"%s\",\n", metric_expr);
352         if (metric_name)
353                 fprintf(outfp, "\t.metric_name = \"%s\",\n", metric_name);
354         if (metric_group)
355                 fprintf(outfp, "\t.metric_group = \"%s\",\n", metric_group);
356         fprintf(outfp, "},\n");
357
358         return 0;
359 }
360
361 struct event_struct {
362         struct list_head list;
363         char *name;
364         char *event;
365         char *desc;
366         char *long_desc;
367         char *pmu;
368         char *unit;
369         char *perpkg;
370         char *metric_expr;
371         char *metric_name;
372         char *metric_group;
373 };
374
375 #define ADD_EVENT_FIELD(field) do { if (field) {                \
376         es->field = strdup(field);                              \
377         if (!es->field)                                         \
378                 goto out_free;                                  \
379 } } while (0)
380
381 #define FREE_EVENT_FIELD(field) free(es->field)
382
383 #define TRY_FIXUP_FIELD(field) do { if (es->field && !*field) {\
384         *field = strdup(es->field);                             \
385         if (!*field)                                            \
386                 return -ENOMEM;                                 \
387 } } while (0)
388
389 #define FOR_ALL_EVENT_STRUCT_FIELDS(op) do {                    \
390         op(name);                                               \
391         op(event);                                              \
392         op(desc);                                               \
393         op(long_desc);                                          \
394         op(pmu);                                                \
395         op(unit);                                               \
396         op(perpkg);                                             \
397         op(metric_expr);                                        \
398         op(metric_name);                                        \
399         op(metric_group);                                       \
400 } while (0)
401
402 static LIST_HEAD(arch_std_events);
403
404 static void free_arch_std_events(void)
405 {
406         struct event_struct *es, *next;
407
408         list_for_each_entry_safe(es, next, &arch_std_events, list) {
409                 FOR_ALL_EVENT_STRUCT_FIELDS(FREE_EVENT_FIELD);
410                 list_del_init(&es->list);
411                 free(es);
412         }
413 }
414
415 static int save_arch_std_events(void *data, char *name, char *event,
416                                 char *desc, char *long_desc, char *pmu,
417                                 char *unit, char *perpkg, char *metric_expr,
418                                 char *metric_name, char *metric_group)
419 {
420         struct event_struct *es;
421
422         es = malloc(sizeof(*es));
423         if (!es)
424                 return -ENOMEM;
425         memset(es, 0, sizeof(*es));
426         FOR_ALL_EVENT_STRUCT_FIELDS(ADD_EVENT_FIELD);
427         list_add_tail(&es->list, &arch_std_events);
428         return 0;
429 out_free:
430         FOR_ALL_EVENT_STRUCT_FIELDS(FREE_EVENT_FIELD);
431         free(es);
432         return -ENOMEM;
433 }
434
435 static void print_events_table_suffix(FILE *outfp)
436 {
437         fprintf(outfp, "{\n");
438
439         fprintf(outfp, "\t.name = 0,\n");
440         fprintf(outfp, "\t.event = 0,\n");
441         fprintf(outfp, "\t.desc = 0,\n");
442
443         fprintf(outfp, "},\n");
444         fprintf(outfp, "};\n");
445         close_table = 0;
446 }
447
448 static struct fixed {
449         const char *name;
450         const char *event;
451 } fixed[] = {
452         { "inst_retired.any", "event=0xc0" },
453         { "inst_retired.any_p", "event=0xc0" },
454         { "cpu_clk_unhalted.ref", "event=0x0,umask=0x03" },
455         { "cpu_clk_unhalted.thread", "event=0x3c" },
456         { "cpu_clk_unhalted.core", "event=0x3c" },
457         { "cpu_clk_unhalted.thread_any", "event=0x3c,any=1" },
458         { NULL, NULL},
459 };
460
461 /*
462  * Handle different fixed counter encodings between JSON and perf.
463  */
464 static char *real_event(const char *name, char *event)
465 {
466         int i;
467
468         if (!name)
469                 return NULL;
470
471         for (i = 0; fixed[i].name; i++)
472                 if (!strcasecmp(name, fixed[i].name))
473                         return (char *)fixed[i].event;
474         return event;
475 }
476
477 static int
478 try_fixup(const char *fn, char *arch_std, char **event, char **desc,
479           char **name, char **long_desc, char **pmu, char **filter,
480           char **perpkg, char **unit, char **metric_expr, char **metric_name,
481           char **metric_group, unsigned long long eventcode)
482 {
483         /* try to find matching event from arch standard values */
484         struct event_struct *es;
485
486         list_for_each_entry(es, &arch_std_events, list) {
487                 if (!strcmp(arch_std, es->name)) {
488                         if (!eventcode && es->event) {
489                                 /* allow EventCode to be overridden */
490                                 free(*event);
491                                 *event = NULL;
492                         }
493                         FOR_ALL_EVENT_STRUCT_FIELDS(TRY_FIXUP_FIELD);
494                         return 0;
495                 }
496         }
497
498         pr_err("%s: could not find matching %s for %s\n",
499                                         prog, arch_std, fn);
500         return -1;
501 }
502
503 /* Call func with each event in the json file */
504 int json_events(const char *fn,
505           int (*func)(void *data, char *name, char *event, char *desc,
506                       char *long_desc,
507                       char *pmu, char *unit, char *perpkg,
508                       char *metric_expr,
509                       char *metric_name, char *metric_group),
510           void *data)
511 {
512         int err;
513         size_t size;
514         jsmntok_t *tokens, *tok;
515         int i, j, len;
516         char *map;
517         char buf[128];
518
519         if (!fn)
520                 return -ENOENT;
521
522         tokens = parse_json(fn, &map, &size, &len);
523         if (!tokens)
524                 return -EIO;
525         EXPECT(tokens->type == JSMN_ARRAY, tokens, "expected top level array");
526         tok = tokens + 1;
527         for (i = 0; i < tokens->size; i++) {
528                 char *event = NULL, *desc = NULL, *name = NULL;
529                 char *long_desc = NULL;
530                 char *extra_desc = NULL;
531                 char *pmu = NULL;
532                 char *filter = NULL;
533                 char *perpkg = NULL;
534                 char *unit = NULL;
535                 char *metric_expr = NULL;
536                 char *metric_name = NULL;
537                 char *metric_group = NULL;
538                 char *arch_std = NULL;
539                 unsigned long long eventcode = 0;
540                 struct msrmap *msr = NULL;
541                 jsmntok_t *msrval = NULL;
542                 jsmntok_t *precise = NULL;
543                 jsmntok_t *obj = tok++;
544
545                 EXPECT(obj->type == JSMN_OBJECT, obj, "expected object");
546                 for (j = 0; j < obj->size; j += 2) {
547                         jsmntok_t *field, *val;
548                         int nz;
549                         char *s;
550
551                         field = tok + j;
552                         EXPECT(field->type == JSMN_STRING, tok + j,
553                                "Expected field name");
554                         val = tok + j + 1;
555                         EXPECT(val->type == JSMN_STRING, tok + j + 1,
556                                "Expected string value");
557
558                         nz = !json_streq(map, val, "0");
559                         if (match_field(map, field, nz, &event, val)) {
560                                 /* ok */
561                         } else if (json_streq(map, field, "EventCode")) {
562                                 char *code = NULL;
563                                 addfield(map, &code, "", "", val);
564                                 eventcode |= strtoul(code, NULL, 0);
565                                 free(code);
566                         } else if (json_streq(map, field, "ExtSel")) {
567                                 char *code = NULL;
568                                 addfield(map, &code, "", "", val);
569                                 eventcode |= strtoul(code, NULL, 0) << 21;
570                                 free(code);
571                         } else if (json_streq(map, field, "EventName")) {
572                                 addfield(map, &name, "", "", val);
573                         } else if (json_streq(map, field, "BriefDescription")) {
574                                 addfield(map, &desc, "", "", val);
575                                 fixdesc(desc);
576                         } else if (json_streq(map, field,
577                                              "PublicDescription")) {
578                                 addfield(map, &long_desc, "", "", val);
579                                 fixdesc(long_desc);
580                         } else if (json_streq(map, field, "PEBS") && nz) {
581                                 precise = val;
582                         } else if (json_streq(map, field, "MSRIndex") && nz) {
583                                 msr = lookup_msr(map, val);
584                         } else if (json_streq(map, field, "MSRValue")) {
585                                 msrval = val;
586                         } else if (json_streq(map, field, "Errata") &&
587                                    !json_streq(map, val, "null")) {
588                                 addfield(map, &extra_desc, ". ",
589                                         " Spec update: ", val);
590                         } else if (json_streq(map, field, "Data_LA") && nz) {
591                                 addfield(map, &extra_desc, ". ",
592                                         " Supports address when precise",
593                                         NULL);
594                         } else if (json_streq(map, field, "Unit")) {
595                                 const char *ppmu;
596
597                                 ppmu = field_to_perf(unit_to_pmu, map, val);
598                                 if (ppmu) {
599                                         pmu = strdup(ppmu);
600                                 } else {
601                                         if (!pmu)
602                                                 pmu = strdup("uncore_");
603                                         addfield(map, &pmu, "", "", val);
604                                         for (s = pmu; *s; s++)
605                                                 *s = tolower(*s);
606                                 }
607                                 addfield(map, &desc, ". ", "Unit: ", NULL);
608                                 addfield(map, &desc, "", pmu, NULL);
609                                 addfield(map, &desc, "", " ", NULL);
610                         } else if (json_streq(map, field, "Filter")) {
611                                 addfield(map, &filter, "", "", val);
612                         } else if (json_streq(map, field, "ScaleUnit")) {
613                                 addfield(map, &unit, "", "", val);
614                         } else if (json_streq(map, field, "PerPkg")) {
615                                 addfield(map, &perpkg, "", "", val);
616                         } else if (json_streq(map, field, "MetricName")) {
617                                 addfield(map, &metric_name, "", "", val);
618                         } else if (json_streq(map, field, "MetricGroup")) {
619                                 addfield(map, &metric_group, "", "", val);
620                         } else if (json_streq(map, field, "MetricExpr")) {
621                                 addfield(map, &metric_expr, "", "", val);
622                                 for (s = metric_expr; *s; s++)
623                                         *s = tolower(*s);
624                         } else if (json_streq(map, field, "ArchStdEvent")) {
625                                 addfield(map, &arch_std, "", "", val);
626                                 for (s = arch_std; *s; s++)
627                                         *s = tolower(*s);
628                         }
629                         /* ignore unknown fields */
630                 }
631                 if (precise && desc && !strstr(desc, "(Precise Event)")) {
632                         if (json_streq(map, precise, "2"))
633                                 addfield(map, &extra_desc, " ",
634                                                 "(Must be precise)", NULL);
635                         else
636                                 addfield(map, &extra_desc, " ",
637                                                 "(Precise event)", NULL);
638                 }
639                 snprintf(buf, sizeof buf, "event=%#llx", eventcode);
640                 addfield(map, &event, ",", buf, NULL);
641                 if (desc && extra_desc)
642                         addfield(map, &desc, " ", extra_desc, NULL);
643                 if (long_desc && extra_desc)
644                         addfield(map, &long_desc, " ", extra_desc, NULL);
645                 if (filter)
646                         addfield(map, &event, ",", filter, NULL);
647                 if (msr != NULL)
648                         addfield(map, &event, ",", msr->pname, msrval);
649                 if (name)
650                         fixname(name);
651
652                 if (arch_std) {
653                         /*
654                          * An arch standard event is referenced, so try to
655                          * fixup any unassigned values.
656                          */
657                         err = try_fixup(fn, arch_std, &event, &desc, &name,
658                                         &long_desc, &pmu, &filter, &perpkg,
659                                         &unit, &metric_expr, &metric_name,
660                                         &metric_group, eventcode);
661                         if (err)
662                                 goto free_strings;
663                 }
664                 err = func(data, name, real_event(name, event), desc, long_desc,
665                            pmu, unit, perpkg, metric_expr, metric_name, metric_group);
666 free_strings:
667                 free(event);
668                 free(desc);
669                 free(name);
670                 free(long_desc);
671                 free(extra_desc);
672                 free(pmu);
673                 free(filter);
674                 free(perpkg);
675                 free(unit);
676                 free(metric_expr);
677                 free(metric_name);
678                 free(metric_group);
679                 free(arch_std);
680
681                 if (err)
682                         break;
683                 tok += j;
684         }
685         EXPECT(tok - tokens == len, tok, "unexpected objects at end");
686         err = 0;
687 out_free:
688         free_json(map, size, tokens);
689         return err;
690 }
691
692 static char *file_name_to_table_name(char *fname)
693 {
694         unsigned int i;
695         int n;
696         int c;
697         char *tblname;
698
699         /*
700          * Ensure tablename starts with alphabetic character.
701          * Derive rest of table name from basename of the JSON file,
702          * replacing hyphens and stripping out .json suffix.
703          */
704         n = asprintf(&tblname, "pme_%s", fname);
705         if (n < 0) {
706                 pr_info("%s: asprintf() error %s for file %s\n", prog,
707                                 strerror(errno), fname);
708                 return NULL;
709         }
710
711         for (i = 0; i < strlen(tblname); i++) {
712                 c = tblname[i];
713
714                 if (c == '-' || c == '/')
715                         tblname[i] = '_';
716                 else if (c == '.') {
717                         tblname[i] = '\0';
718                         break;
719                 } else if (!isalnum(c) && c != '_') {
720                         pr_err("%s: Invalid character '%c' in file name %s\n",
721                                         prog, c, basename(fname));
722                         free(tblname);
723                         tblname = NULL;
724                         break;
725                 }
726         }
727
728         return tblname;
729 }
730
731 static void print_mapping_table_prefix(FILE *outfp)
732 {
733         fprintf(outfp, "struct pmu_events_map pmu_events_map[] = {\n");
734 }
735
736 static void print_mapping_table_suffix(FILE *outfp)
737 {
738         /*
739          * Print the terminating, NULL entry.
740          */
741         fprintf(outfp, "{\n");
742         fprintf(outfp, "\t.cpuid = 0,\n");
743         fprintf(outfp, "\t.version = 0,\n");
744         fprintf(outfp, "\t.type = 0,\n");
745         fprintf(outfp, "\t.table = 0,\n");
746         fprintf(outfp, "},\n");
747
748         /* and finally, the closing curly bracket for the struct */
749         fprintf(outfp, "};\n");
750 }
751
752 static int process_mapfile(FILE *outfp, char *fpath)
753 {
754         int n = 16384;
755         FILE *mapfp;
756         char *save = NULL;
757         char *line, *p;
758         int line_num;
759         char *tblname;
760
761         pr_info("%s: Processing mapfile %s\n", prog, fpath);
762
763         line = malloc(n);
764         if (!line)
765                 return -1;
766
767         mapfp = fopen(fpath, "r");
768         if (!mapfp) {
769                 pr_info("%s: Error %s opening %s\n", prog, strerror(errno),
770                                 fpath);
771                 return -1;
772         }
773
774         print_mapping_table_prefix(outfp);
775
776         /* Skip first line (header) */
777         p = fgets(line, n, mapfp);
778         if (!p)
779                 goto out;
780
781         line_num = 1;
782         while (1) {
783                 char *cpuid, *version, *type, *fname;
784
785                 line_num++;
786                 p = fgets(line, n, mapfp);
787                 if (!p)
788                         break;
789
790                 if (line[0] == '#' || line[0] == '\n')
791                         continue;
792
793                 if (line[strlen(line)-1] != '\n') {
794                         /* TODO Deal with lines longer than 16K */
795                         pr_info("%s: Mapfile %s: line %d too long, aborting\n",
796                                         prog, fpath, line_num);
797                         return -1;
798                 }
799                 line[strlen(line)-1] = '\0';
800
801                 cpuid = fixregex(strtok_r(p, ",", &save));
802                 version = strtok_r(NULL, ",", &save);
803                 fname = strtok_r(NULL, ",", &save);
804                 type = strtok_r(NULL, ",", &save);
805
806                 tblname = file_name_to_table_name(fname);
807                 fprintf(outfp, "{\n");
808                 fprintf(outfp, "\t.cpuid = \"%s\",\n", cpuid);
809                 fprintf(outfp, "\t.version = \"%s\",\n", version);
810                 fprintf(outfp, "\t.type = \"%s\",\n", type);
811
812                 /*
813                  * CHECK: We can't use the type (eg "core") field in the
814                  * table name. For us to do that, we need to somehow tweak
815                  * the other caller of file_name_to_table(), process_json()
816                  * to determine the type. process_json() file has no way
817                  * of knowing these are "core" events unless file name has
818                  * core in it. If filename has core in it, we can safely
819                  * ignore the type field here also.
820                  */
821                 fprintf(outfp, "\t.table = %s\n", tblname);
822                 fprintf(outfp, "},\n");
823         }
824
825 out:
826         print_mapping_table_suffix(outfp);
827         return 0;
828 }
829
830 /*
831  * If we fail to locate/process JSON and map files, create a NULL mapping
832  * table. This would at least allow perf to build even if we can't find/use
833  * the aliases.
834  */
835 static void create_empty_mapping(const char *output_file)
836 {
837         FILE *outfp;
838
839         pr_info("%s: Creating empty pmu_events_map[] table\n", prog);
840
841         /* Truncate file to clear any partial writes to it */
842         outfp = fopen(output_file, "w");
843         if (!outfp) {
844                 perror("fopen()");
845                 _Exit(1);
846         }
847
848         fprintf(outfp, "#include \"pmu-events/pmu-events.h\"\n");
849         print_mapping_table_prefix(outfp);
850         print_mapping_table_suffix(outfp);
851         fclose(outfp);
852 }
853
854 static int get_maxfds(void)
855 {
856         struct rlimit rlim;
857
858         if (getrlimit(RLIMIT_NOFILE, &rlim) == 0)
859                 return min((int)rlim.rlim_max / 2, 512);
860
861         return 512;
862 }
863
864 /*
865  * nftw() doesn't let us pass an argument to the processing function,
866  * so use a global variables.
867  */
868 static FILE *eventsfp;
869 static char *mapfile;
870
871 static int is_leaf_dir(const char *fpath)
872 {
873         DIR *d;
874         struct dirent *dir;
875         int res = 1;
876
877         d = opendir(fpath);
878         if (!d)
879                 return 0;
880
881         while ((dir = readdir(d)) != NULL) {
882                 if (!strcmp(dir->d_name, ".") || !strcmp(dir->d_name, ".."))
883                         continue;
884
885                 if (dir->d_type == DT_DIR) {
886                         res = 0;
887                         break;
888                 } else if (dir->d_type == DT_UNKNOWN) {
889                         char path[PATH_MAX];
890                         struct stat st;
891
892                         sprintf(path, "%s/%s", fpath, dir->d_name);
893                         if (stat(path, &st))
894                                 break;
895
896                         if (S_ISDIR(st.st_mode)) {
897                                 res = 0;
898                                 break;
899                         }
900                 }
901         }
902
903         closedir(d);
904
905         return res;
906 }
907
908 static int is_json_file(const char *name)
909 {
910         const char *suffix;
911
912         if (strlen(name) < 5)
913                 return 0;
914
915         suffix = name + strlen(name) - 5;
916
917         if (strncmp(suffix, ".json", 5) == 0)
918                 return 1;
919         return 0;
920 }
921
922 static int preprocess_arch_std_files(const char *fpath, const struct stat *sb,
923                                 int typeflag, struct FTW *ftwbuf)
924 {
925         int level = ftwbuf->level;
926         int is_file = typeflag == FTW_F;
927
928         if (level == 1 && is_file && is_json_file(fpath))
929                 return json_events(fpath, save_arch_std_events, (void *)sb);
930
931         return 0;
932 }
933
934 static int process_one_file(const char *fpath, const struct stat *sb,
935                             int typeflag, struct FTW *ftwbuf)
936 {
937         char *tblname, *bname;
938         int is_dir  = typeflag == FTW_D;
939         int is_file = typeflag == FTW_F;
940         int level   = ftwbuf->level;
941         int err = 0;
942
943         if (level == 2 && is_dir) {
944                 /*
945                  * For level 2 directory, bname will include parent name,
946                  * like vendor/platform. So search back from platform dir
947                  * to find this.
948                  */
949                 bname = (char *) fpath + ftwbuf->base - 2;
950                 for (;;) {
951                         if (*bname == '/')
952                                 break;
953                         bname--;
954                 }
955                 bname++;
956         } else
957                 bname = (char *) fpath + ftwbuf->base;
958
959         pr_debug("%s %d %7jd %-20s %s\n",
960                  is_file ? "f" : is_dir ? "d" : "x",
961                  level, sb->st_size, bname, fpath);
962
963         /* base dir or too deep */
964         if (level == 0 || level > 3)
965                 return 0;
966
967
968         /* model directory, reset topic */
969         if ((level == 1 && is_dir && is_leaf_dir(fpath)) ||
970             (level == 2 && is_dir)) {
971                 if (close_table)
972                         print_events_table_suffix(eventsfp);
973
974                 /*
975                  * Drop file name suffix. Replace hyphens with underscores.
976                  * Fail if file name contains any alphanum characters besides
977                  * underscores.
978                  */
979                 tblname = file_name_to_table_name(bname);
980                 if (!tblname) {
981                         pr_info("%s: Error determining table name for %s\n", prog,
982                                 bname);
983                         return -1;
984                 }
985
986                 print_events_table_prefix(eventsfp, tblname);
987                 return 0;
988         }
989
990         /*
991          * Save the mapfile name for now. We will process mapfile
992          * after processing all JSON files (so we can write out the
993          * mapping table after all PMU events tables).
994          *
995          */
996         if (level == 1 && is_file) {
997                 if (!strcmp(bname, "mapfile.csv")) {
998                         mapfile = strdup(fpath);
999                         return 0;
1000                 }
1001
1002                 pr_info("%s: Ignoring file %s\n", prog, fpath);
1003                 return 0;
1004         }
1005
1006         /*
1007          * If the file name does not have a .json extension,
1008          * ignore it. It could be a readme.txt for instance.
1009          */
1010         if (is_file) {
1011                 if (!is_json_file(bname)) {
1012                         pr_info("%s: Ignoring file without .json suffix %s\n", prog,
1013                                 fpath);
1014                         return 0;
1015                 }
1016         }
1017
1018         if (level > 1 && add_topic(bname))
1019                 return -ENOMEM;
1020
1021         /*
1022          * Assume all other files are JSON files.
1023          *
1024          * If mapfile refers to 'power7_core.json', we create a table
1025          * named 'power7_core'. Any inconsistencies between the mapfile
1026          * and directory tree could result in build failure due to table
1027          * names not being found.
1028          *
1029          * Atleast for now, be strict with processing JSON file names.
1030          * i.e. if JSON file name cannot be mapped to C-style table name,
1031          * fail.
1032          */
1033         if (is_file) {
1034                 struct perf_entry_data data = {
1035                         .topic = get_topic(),
1036                         .outfp = eventsfp,
1037                 };
1038
1039                 err = json_events(fpath, print_events_table_entry, &data);
1040
1041                 free(data.topic);
1042         }
1043
1044         return err;
1045 }
1046
1047 #ifndef PATH_MAX
1048 #define PATH_MAX        4096
1049 #endif
1050
1051 /*
1052  * Starting in directory 'start_dirname', find the "mapfile.csv" and
1053  * the set of JSON files for the architecture 'arch'.
1054  *
1055  * From each JSON file, create a C-style "PMU events table" from the
1056  * JSON file (see struct pmu_event).
1057  *
1058  * From the mapfile, create a mapping between the CPU revisions and
1059  * PMU event tables (see struct pmu_events_map).
1060  *
1061  * Write out the PMU events tables and the mapping table to pmu-event.c.
1062  */
1063 int main(int argc, char *argv[])
1064 {
1065         int rc;
1066         int maxfds;
1067         char ldirname[PATH_MAX];
1068
1069         const char *arch;
1070         const char *output_file;
1071         const char *start_dirname;
1072         struct stat stbuf;
1073
1074         prog = basename(argv[0]);
1075         if (argc < 4) {
1076                 pr_err("Usage: %s <arch> <starting_dir> <output_file>\n", prog);
1077                 return 1;
1078         }
1079
1080         arch = argv[1];
1081         start_dirname = argv[2];
1082         output_file = argv[3];
1083
1084         if (argc > 4)
1085                 verbose = atoi(argv[4]);
1086
1087         eventsfp = fopen(output_file, "w");
1088         if (!eventsfp) {
1089                 pr_err("%s Unable to create required file %s (%s)\n",
1090                                 prog, output_file, strerror(errno));
1091                 return 2;
1092         }
1093
1094         sprintf(ldirname, "%s/%s", start_dirname, arch);
1095
1096         /* If architecture does not have any event lists, bail out */
1097         if (stat(ldirname, &stbuf) < 0) {
1098                 pr_info("%s: Arch %s has no PMU event lists\n", prog, arch);
1099                 goto empty_map;
1100         }
1101
1102         /* Include pmu-events.h first */
1103         fprintf(eventsfp, "#include \"pmu-events/pmu-events.h\"\n");
1104
1105         /*
1106          * The mapfile allows multiple CPUids to point to the same JSON file,
1107          * so, not sure if there is a need for symlinks within the pmu-events
1108          * directory.
1109          *
1110          * For now, treat symlinks of JSON files as regular files and create
1111          * separate tables for each symlink (presumably, each symlink refers
1112          * to specific version of the CPU).
1113          */
1114
1115         maxfds = get_maxfds();
1116         mapfile = NULL;
1117         rc = nftw(ldirname, preprocess_arch_std_files, maxfds, 0);
1118         if (rc && verbose) {
1119                 pr_info("%s: Error preprocessing arch standard files %s\n",
1120                         prog, ldirname);
1121                 goto empty_map;
1122         } else if (rc < 0) {
1123                 /* Make build fail */
1124                 free_arch_std_events();
1125                 return 1;
1126         } else if (rc) {
1127                 goto empty_map;
1128         }
1129
1130         rc = nftw(ldirname, process_one_file, maxfds, 0);
1131         if (rc && verbose) {
1132                 pr_info("%s: Error walking file tree %s\n", prog, ldirname);
1133                 goto empty_map;
1134         } else if (rc < 0) {
1135                 /* Make build fail */
1136                 free_arch_std_events();
1137                 return 1;
1138         } else if (rc) {
1139                 goto empty_map;
1140         }
1141
1142         if (close_table)
1143                 print_events_table_suffix(eventsfp);
1144
1145         if (!mapfile) {
1146                 pr_info("%s: No CPU->JSON mapping?\n", prog);
1147                 goto empty_map;
1148         }
1149
1150         if (process_mapfile(eventsfp, mapfile)) {
1151                 pr_info("%s: Error processing mapfile %s\n", prog, mapfile);
1152                 /* Make build fail */
1153                 return 1;
1154         }
1155
1156         return 0;
1157
1158 empty_map:
1159         fclose(eventsfp);
1160         create_empty_mapping(output_file);
1161         free_arch_std_events();
1162         return 0;
1163 }