OSDN Git Service

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