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