]> asedeno.scripts.mit.edu Git - linux.git/blob - tools/perf/pmu-events/jevents.c
Merge branches 'pm-core', 'pm-qos', 'pm-domains' and 'pm-opp'
[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 <dirent.h>
43 #include <sys/time.h>                   /* getrlimit */
44 #include <sys/resource.h>               /* getrlimit */
45 #include <ftw.h>
46 #include <sys/stat.h>
47 #include "jsmn.h"
48 #include "json.h"
49 #include "jevents.h"
50
51 #ifndef __maybe_unused
52 #define __maybe_unused                  __attribute__((unused))
53 #endif
54
55 int verbose;
56 char *prog;
57
58 int eprintf(int level, int var, const char *fmt, ...)
59 {
60
61         int ret;
62         va_list args;
63
64         if (var < level)
65                 return 0;
66
67         va_start(args, fmt);
68
69         ret = vfprintf(stderr, fmt, args);
70
71         va_end(args);
72
73         return ret;
74 }
75
76 __attribute__((weak)) char *get_cpu_str(void)
77 {
78         return NULL;
79 }
80
81 static void addfield(char *map, char **dst, const char *sep,
82                      const char *a, jsmntok_t *bt)
83 {
84         unsigned int len = strlen(a) + 1 + strlen(sep);
85         int olen = *dst ? strlen(*dst) : 0;
86         int blen = bt ? json_len(bt) : 0;
87         char *out;
88
89         out = realloc(*dst, len + olen + blen);
90         if (!out) {
91                 /* Don't add field in this case */
92                 return;
93         }
94         *dst = out;
95
96         if (!olen)
97                 *(*dst) = 0;
98         else
99                 strcat(*dst, sep);
100         strcat(*dst, a);
101         if (bt)
102                 strncat(*dst, map + bt->start, blen);
103 }
104
105 static void fixname(char *s)
106 {
107         for (; *s; s++)
108                 *s = tolower(*s);
109 }
110
111 static void fixdesc(char *s)
112 {
113         char *e = s + strlen(s);
114
115         /* Remove trailing dots that look ugly in perf list */
116         --e;
117         while (e >= s && isspace(*e))
118                 --e;
119         if (*e == '.')
120                 *e = 0;
121 }
122
123 static struct msrmap {
124         const char *num;
125         const char *pname;
126 } msrmap[] = {
127         { "0x3F6", "ldlat=" },
128         { "0x1A6", "offcore_rsp=" },
129         { "0x1A7", "offcore_rsp=" },
130         { "0x3F7", "frontend=" },
131         { NULL, NULL }
132 };
133
134 static struct field {
135         const char *field;
136         const char *kernel;
137 } fields[] = {
138         { "UMask",      "umask=" },
139         { "CounterMask", "cmask=" },
140         { "Invert",     "inv=" },
141         { "AnyThread",  "any=" },
142         { "EdgeDetect", "edge=" },
143         { "SampleAfterValue", "period=" },
144         { NULL, NULL }
145 };
146
147 static void cut_comma(char *map, jsmntok_t *newval)
148 {
149         int i;
150
151         /* Cut off everything after comma */
152         for (i = newval->start; i < newval->end; i++) {
153                 if (map[i] == ',')
154                         newval->end = i;
155         }
156 }
157
158 static int match_field(char *map, jsmntok_t *field, int nz,
159                        char **event, jsmntok_t *val)
160 {
161         struct field *f;
162         jsmntok_t newval = *val;
163
164         for (f = fields; f->field; f++)
165                 if (json_streq(map, field, f->field) && nz) {
166                         cut_comma(map, &newval);
167                         addfield(map, event, ",", f->kernel, &newval);
168                         return 1;
169                 }
170         return 0;
171 }
172
173 static struct msrmap *lookup_msr(char *map, jsmntok_t *val)
174 {
175         jsmntok_t newval = *val;
176         static bool warned;
177         int i;
178
179         cut_comma(map, &newval);
180         for (i = 0; msrmap[i].num; i++)
181                 if (json_streq(map, &newval, msrmap[i].num))
182                         return &msrmap[i];
183         if (!warned) {
184                 warned = true;
185                 pr_err("%s: Unknown MSR in event file %.*s\n", prog,
186                         json_len(val), map + val->start);
187         }
188         return NULL;
189 }
190
191 static struct map {
192         const char *json;
193         const char *perf;
194 } unit_to_pmu[] = {
195         { "CBO", "uncore_cbox" },
196         { "QPI LL", "uncore_qpi" },
197         { "SBO", "uncore_sbox" },
198         {}
199 };
200
201 static const char *field_to_perf(struct map *table, char *map, jsmntok_t *val)
202 {
203         int i;
204
205         for (i = 0; table[i].json; i++) {
206                 if (json_streq(map, val, table[i].json))
207                         return table[i].perf;
208         }
209         return NULL;
210 }
211
212 #define EXPECT(e, t, m) do { if (!(e)) {                        \
213         jsmntok_t *loc = (t);                                   \
214         if (!(t)->start && (t) > tokens)                        \
215                 loc = (t) - 1;                                  \
216                 pr_err("%s:%d: " m ", got %s\n", fn,            \
217                         json_line(map, loc),                    \
218                         json_name(t));                          \
219         goto out_free;                                          \
220 } } while (0)
221
222 #define TOPIC_DEPTH 256
223 static char *topic_array[TOPIC_DEPTH];
224 static int   topic_level;
225
226 static char *get_topic(void)
227 {
228         char *tp_old, *tp = NULL;
229         int i;
230
231         for (i = 0; i < topic_level + 1; i++) {
232                 int n;
233
234                 tp_old = tp;
235                 n = asprintf(&tp, "%s%s", tp ?: "", topic_array[i]);
236                 if (n < 0) {
237                         pr_info("%s: asprintf() error %s\n", prog);
238                         return NULL;
239                 }
240                 free(tp_old);
241         }
242
243         for (i = 0; i < (int) strlen(tp); i++) {
244                 char c = tp[i];
245
246                 if (c == '-')
247                         tp[i] = ' ';
248                 else if (c == '.') {
249                         tp[i] = '\0';
250                         break;
251                 }
252         }
253
254         return tp;
255 }
256
257 static int add_topic(int level, char *bname)
258 {
259         char *topic;
260
261         level -= 2;
262
263         if (level >= TOPIC_DEPTH)
264                 return -EINVAL;
265
266         topic = strdup(bname);
267         if (!topic) {
268                 pr_info("%s: strdup() error %s for file %s\n", prog,
269                                 strerror(errno), bname);
270                 return -ENOMEM;
271         }
272
273         free(topic_array[topic_level]);
274         topic_array[topic_level] = topic;
275         topic_level              = level;
276         return 0;
277 }
278
279 struct perf_entry_data {
280         FILE *outfp;
281         char *topic;
282 };
283
284 static int close_table;
285
286 static void print_events_table_prefix(FILE *fp, const char *tblname)
287 {
288         fprintf(fp, "struct pmu_event %s[] = {\n", tblname);
289         close_table = 1;
290 }
291
292 static int print_events_table_entry(void *data, char *name, char *event,
293                                     char *desc, char *long_desc,
294                                     char *pmu, char *unit, char *perpkg)
295 {
296         struct perf_entry_data *pd = data;
297         FILE *outfp = pd->outfp;
298         char *topic = pd->topic;
299
300         /*
301          * TODO: Remove formatting chars after debugging to reduce
302          *       string lengths.
303          */
304         fprintf(outfp, "{\n");
305
306         fprintf(outfp, "\t.name = \"%s\",\n", name);
307         fprintf(outfp, "\t.event = \"%s\",\n", event);
308         fprintf(outfp, "\t.desc = \"%s\",\n", desc);
309         fprintf(outfp, "\t.topic = \"%s\",\n", topic);
310         if (long_desc && long_desc[0])
311                 fprintf(outfp, "\t.long_desc = \"%s\",\n", long_desc);
312         if (pmu)
313                 fprintf(outfp, "\t.pmu = \"%s\",\n", pmu);
314         if (unit)
315                 fprintf(outfp, "\t.unit = \"%s\",\n", unit);
316         if (perpkg)
317                 fprintf(outfp, "\t.perpkg = \"%s\",\n", perpkg);
318         fprintf(outfp, "},\n");
319
320         return 0;
321 }
322
323 static void print_events_table_suffix(FILE *outfp)
324 {
325         fprintf(outfp, "{\n");
326
327         fprintf(outfp, "\t.name = 0,\n");
328         fprintf(outfp, "\t.event = 0,\n");
329         fprintf(outfp, "\t.desc = 0,\n");
330
331         fprintf(outfp, "},\n");
332         fprintf(outfp, "};\n");
333         close_table = 0;
334 }
335
336 static struct fixed {
337         const char *name;
338         const char *event;
339 } fixed[] = {
340         { "inst_retired.any", "event=0xc0" },
341         { "inst_retired.any_p", "event=0xc0" },
342         { "cpu_clk_unhalted.ref", "event=0x0,umask=0x03" },
343         { "cpu_clk_unhalted.thread", "event=0x3c" },
344         { "cpu_clk_unhalted.thread_any", "event=0x3c,any=1" },
345         { NULL, NULL},
346 };
347
348 /*
349  * Handle different fixed counter encodings between JSON and perf.
350  */
351 static char *real_event(const char *name, char *event)
352 {
353         int i;
354
355         for (i = 0; fixed[i].name; i++)
356                 if (!strcasecmp(name, fixed[i].name))
357                         return (char *)fixed[i].event;
358         return event;
359 }
360
361 /* Call func with each event in the json file */
362 int json_events(const char *fn,
363           int (*func)(void *data, char *name, char *event, char *desc,
364                       char *long_desc,
365                       char *pmu, char *unit, char *perpkg),
366           void *data)
367 {
368         int err = -EIO;
369         size_t size;
370         jsmntok_t *tokens, *tok;
371         int i, j, len;
372         char *map;
373         char buf[128];
374
375         if (!fn)
376                 return -ENOENT;
377
378         tokens = parse_json(fn, &map, &size, &len);
379         if (!tokens)
380                 return -EIO;
381         EXPECT(tokens->type == JSMN_ARRAY, tokens, "expected top level array");
382         tok = tokens + 1;
383         for (i = 0; i < tokens->size; i++) {
384                 char *event = NULL, *desc = NULL, *name = NULL;
385                 char *long_desc = NULL;
386                 char *extra_desc = NULL;
387                 char *pmu = NULL;
388                 char *filter = NULL;
389                 char *perpkg = NULL;
390                 char *unit = NULL;
391                 unsigned long long eventcode = 0;
392                 struct msrmap *msr = NULL;
393                 jsmntok_t *msrval = NULL;
394                 jsmntok_t *precise = NULL;
395                 jsmntok_t *obj = tok++;
396
397                 EXPECT(obj->type == JSMN_OBJECT, obj, "expected object");
398                 for (j = 0; j < obj->size; j += 2) {
399                         jsmntok_t *field, *val;
400                         int nz;
401
402                         field = tok + j;
403                         EXPECT(field->type == JSMN_STRING, tok + j,
404                                "Expected field name");
405                         val = tok + j + 1;
406                         EXPECT(val->type == JSMN_STRING, tok + j + 1,
407                                "Expected string value");
408
409                         nz = !json_streq(map, val, "0");
410                         if (match_field(map, field, nz, &event, val)) {
411                                 /* ok */
412                         } else if (json_streq(map, field, "EventCode")) {
413                                 char *code = NULL;
414                                 addfield(map, &code, "", "", val);
415                                 eventcode |= strtoul(code, NULL, 0);
416                                 free(code);
417                         } else if (json_streq(map, field, "ExtSel")) {
418                                 char *code = NULL;
419                                 addfield(map, &code, "", "", val);
420                                 eventcode |= strtoul(code, NULL, 0) << 21;
421                                 free(code);
422                         } else if (json_streq(map, field, "EventName")) {
423                                 addfield(map, &name, "", "", val);
424                         } else if (json_streq(map, field, "BriefDescription")) {
425                                 addfield(map, &desc, "", "", val);
426                                 fixdesc(desc);
427                         } else if (json_streq(map, field,
428                                              "PublicDescription")) {
429                                 addfield(map, &long_desc, "", "", val);
430                                 fixdesc(long_desc);
431                         } else if (json_streq(map, field, "PEBS") && nz) {
432                                 precise = val;
433                         } else if (json_streq(map, field, "MSRIndex") && nz) {
434                                 msr = lookup_msr(map, val);
435                         } else if (json_streq(map, field, "MSRValue")) {
436                                 msrval = val;
437                         } else if (json_streq(map, field, "Errata") &&
438                                    !json_streq(map, val, "null")) {
439                                 addfield(map, &extra_desc, ". ",
440                                         " Spec update: ", val);
441                         } else if (json_streq(map, field, "Data_LA") && nz) {
442                                 addfield(map, &extra_desc, ". ",
443                                         " Supports address when precise",
444                                         NULL);
445                         } else if (json_streq(map, field, "Unit")) {
446                                 const char *ppmu;
447                                 char *s;
448
449                                 ppmu = field_to_perf(unit_to_pmu, map, val);
450                                 if (ppmu) {
451                                         pmu = strdup(ppmu);
452                                 } else {
453                                         if (!pmu)
454                                                 pmu = strdup("uncore_");
455                                         addfield(map, &pmu, "", "", val);
456                                         for (s = pmu; *s; s++)
457                                                 *s = tolower(*s);
458                                 }
459                                 addfield(map, &desc, ". ", "Unit: ", NULL);
460                                 addfield(map, &desc, "", pmu, NULL);
461                         } else if (json_streq(map, field, "Filter")) {
462                                 addfield(map, &filter, "", "", val);
463                         } else if (json_streq(map, field, "ScaleUnit")) {
464                                 addfield(map, &unit, "", "", val);
465                         } else if (json_streq(map, field, "PerPkg")) {
466                                 addfield(map, &perpkg, "", "", val);
467                         }
468                         /* ignore unknown fields */
469                 }
470                 if (precise && desc && !strstr(desc, "(Precise Event)")) {
471                         if (json_streq(map, precise, "2"))
472                                 addfield(map, &extra_desc, " ",
473                                                 "(Must be precise)", NULL);
474                         else
475                                 addfield(map, &extra_desc, " ",
476                                                 "(Precise event)", NULL);
477                 }
478                 snprintf(buf, sizeof buf, "event=%#llx", eventcode);
479                 addfield(map, &event, ",", buf, NULL);
480                 if (desc && extra_desc)
481                         addfield(map, &desc, " ", extra_desc, NULL);
482                 if (long_desc && extra_desc)
483                         addfield(map, &long_desc, " ", extra_desc, NULL);
484                 if (filter)
485                         addfield(map, &event, ",", filter, NULL);
486                 if (msr != NULL)
487                         addfield(map, &event, ",", msr->pname, msrval);
488                 fixname(name);
489
490                 err = func(data, name, real_event(name, event), desc, long_desc,
491                                 pmu, unit, perpkg);
492                 free(event);
493                 free(desc);
494                 free(name);
495                 free(long_desc);
496                 free(extra_desc);
497                 free(pmu);
498                 free(filter);
499                 free(perpkg);
500                 free(unit);
501                 if (err)
502                         break;
503                 tok += j;
504         }
505         EXPECT(tok - tokens == len, tok, "unexpected objects at end");
506         err = 0;
507 out_free:
508         free_json(map, size, tokens);
509         return err;
510 }
511
512 static char *file_name_to_table_name(char *fname)
513 {
514         unsigned int i;
515         int n;
516         int c;
517         char *tblname;
518
519         /*
520          * Ensure tablename starts with alphabetic character.
521          * Derive rest of table name from basename of the JSON file,
522          * replacing hyphens and stripping out .json suffix.
523          */
524         n = asprintf(&tblname, "pme_%s", basename(fname));
525         if (n < 0) {
526                 pr_info("%s: asprintf() error %s for file %s\n", prog,
527                                 strerror(errno), fname);
528                 return NULL;
529         }
530
531         for (i = 0; i < strlen(tblname); i++) {
532                 c = tblname[i];
533
534                 if (c == '-')
535                         tblname[i] = '_';
536                 else if (c == '.') {
537                         tblname[i] = '\0';
538                         break;
539                 } else if (!isalnum(c) && c != '_') {
540                         pr_err("%s: Invalid character '%c' in file name %s\n",
541                                         prog, c, basename(fname));
542                         free(tblname);
543                         tblname = NULL;
544                         break;
545                 }
546         }
547
548         return tblname;
549 }
550
551 static void print_mapping_table_prefix(FILE *outfp)
552 {
553         fprintf(outfp, "struct pmu_events_map pmu_events_map[] = {\n");
554 }
555
556 static void print_mapping_table_suffix(FILE *outfp)
557 {
558         /*
559          * Print the terminating, NULL entry.
560          */
561         fprintf(outfp, "{\n");
562         fprintf(outfp, "\t.cpuid = 0,\n");
563         fprintf(outfp, "\t.version = 0,\n");
564         fprintf(outfp, "\t.type = 0,\n");
565         fprintf(outfp, "\t.table = 0,\n");
566         fprintf(outfp, "},\n");
567
568         /* and finally, the closing curly bracket for the struct */
569         fprintf(outfp, "};\n");
570 }
571
572 static int process_mapfile(FILE *outfp, char *fpath)
573 {
574         int n = 16384;
575         FILE *mapfp;
576         char *save = NULL;
577         char *line, *p;
578         int line_num;
579         char *tblname;
580
581         pr_info("%s: Processing mapfile %s\n", prog, fpath);
582
583         line = malloc(n);
584         if (!line)
585                 return -1;
586
587         mapfp = fopen(fpath, "r");
588         if (!mapfp) {
589                 pr_info("%s: Error %s opening %s\n", prog, strerror(errno),
590                                 fpath);
591                 return -1;
592         }
593
594         print_mapping_table_prefix(outfp);
595
596         /* Skip first line (header) */
597         p = fgets(line, n, mapfp);
598         if (!p)
599                 goto out;
600
601         line_num = 1;
602         while (1) {
603                 char *cpuid, *version, *type, *fname;
604
605                 line_num++;
606                 p = fgets(line, n, mapfp);
607                 if (!p)
608                         break;
609
610                 if (line[0] == '#' || line[0] == '\n')
611                         continue;
612
613                 if (line[strlen(line)-1] != '\n') {
614                         /* TODO Deal with lines longer than 16K */
615                         pr_info("%s: Mapfile %s: line %d too long, aborting\n",
616                                         prog, fpath, line_num);
617                         return -1;
618                 }
619                 line[strlen(line)-1] = '\0';
620
621                 cpuid = strtok_r(p, ",", &save);
622                 version = strtok_r(NULL, ",", &save);
623                 fname = strtok_r(NULL, ",", &save);
624                 type = strtok_r(NULL, ",", &save);
625
626                 tblname = file_name_to_table_name(fname);
627                 fprintf(outfp, "{\n");
628                 fprintf(outfp, "\t.cpuid = \"%s\",\n", cpuid);
629                 fprintf(outfp, "\t.version = \"%s\",\n", version);
630                 fprintf(outfp, "\t.type = \"%s\",\n", type);
631
632                 /*
633                  * CHECK: We can't use the type (eg "core") field in the
634                  * table name. For us to do that, we need to somehow tweak
635                  * the other caller of file_name_to_table(), process_json()
636                  * to determine the type. process_json() file has no way
637                  * of knowing these are "core" events unless file name has
638                  * core in it. If filename has core in it, we can safely
639                  * ignore the type field here also.
640                  */
641                 fprintf(outfp, "\t.table = %s\n", tblname);
642                 fprintf(outfp, "},\n");
643         }
644
645 out:
646         print_mapping_table_suffix(outfp);
647         return 0;
648 }
649
650 /*
651  * If we fail to locate/process JSON and map files, create a NULL mapping
652  * table. This would at least allow perf to build even if we can't find/use
653  * the aliases.
654  */
655 static void create_empty_mapping(const char *output_file)
656 {
657         FILE *outfp;
658
659         pr_info("%s: Creating empty pmu_events_map[] table\n", prog);
660
661         /* Truncate file to clear any partial writes to it */
662         outfp = fopen(output_file, "w");
663         if (!outfp) {
664                 perror("fopen()");
665                 _Exit(1);
666         }
667
668         fprintf(outfp, "#include \"../../pmu-events/pmu-events.h\"\n");
669         print_mapping_table_prefix(outfp);
670         print_mapping_table_suffix(outfp);
671         fclose(outfp);
672 }
673
674 static int get_maxfds(void)
675 {
676         struct rlimit rlim;
677
678         if (getrlimit(RLIMIT_NOFILE, &rlim) == 0)
679                 return min((int)rlim.rlim_max / 2, 512);
680
681         return 512;
682 }
683
684 /*
685  * nftw() doesn't let us pass an argument to the processing function,
686  * so use a global variables.
687  */
688 static FILE *eventsfp;
689 static char *mapfile;
690
691 static int process_one_file(const char *fpath, const struct stat *sb,
692                             int typeflag, struct FTW *ftwbuf)
693 {
694         char *tblname, *bname  = (char *) fpath + ftwbuf->base;
695         int is_dir  = typeflag == FTW_D;
696         int is_file = typeflag == FTW_F;
697         int level   = ftwbuf->level;
698         int err = 0;
699
700         pr_debug("%s %d %7jd %-20s %s\n",
701                  is_file ? "f" : is_dir ? "d" : "x",
702                  level, sb->st_size, bname, fpath);
703
704         /* base dir */
705         if (level == 0)
706                 return 0;
707
708         /* model directory, reset topic */
709         if (level == 1 && is_dir) {
710                 if (close_table)
711                         print_events_table_suffix(eventsfp);
712
713                 /*
714                  * Drop file name suffix. Replace hyphens with underscores.
715                  * Fail if file name contains any alphanum characters besides
716                  * underscores.
717                  */
718                 tblname = file_name_to_table_name(bname);
719                 if (!tblname) {
720                         pr_info("%s: Error determining table name for %s\n", prog,
721                                 bname);
722                         return -1;
723                 }
724
725                 print_events_table_prefix(eventsfp, tblname);
726                 return 0;
727         }
728
729         /*
730          * Save the mapfile name for now. We will process mapfile
731          * after processing all JSON files (so we can write out the
732          * mapping table after all PMU events tables).
733          *
734          * TODO: Allow for multiple mapfiles? Punt for now.
735          */
736         if (level == 1 && is_file) {
737                 if (!strncmp(bname, "mapfile.csv", 11)) {
738                         if (mapfile) {
739                                 pr_info("%s: Many mapfiles? Using %s, ignoring %s\n",
740                                                 prog, mapfile, fpath);
741                         } else {
742                                 mapfile = strdup(fpath);
743                         }
744                         return 0;
745                 }
746
747                 pr_info("%s: Ignoring file %s\n", prog, fpath);
748                 return 0;
749         }
750
751         /*
752          * If the file name does not have a .json extension,
753          * ignore it. It could be a readme.txt for instance.
754          */
755         if (is_file) {
756                 char *suffix = bname + strlen(bname) - 5;
757
758                 if (strncmp(suffix, ".json", 5)) {
759                         pr_info("%s: Ignoring file without .json suffix %s\n", prog,
760                                 fpath);
761                         return 0;
762                 }
763         }
764
765         if (level > 1 && add_topic(level, bname))
766                 return -ENOMEM;
767
768         /*
769          * Assume all other files are JSON files.
770          *
771          * If mapfile refers to 'power7_core.json', we create a table
772          * named 'power7_core'. Any inconsistencies between the mapfile
773          * and directory tree could result in build failure due to table
774          * names not being found.
775          *
776          * Atleast for now, be strict with processing JSON file names.
777          * i.e. if JSON file name cannot be mapped to C-style table name,
778          * fail.
779          */
780         if (is_file) {
781                 struct perf_entry_data data = {
782                         .topic = get_topic(),
783                         .outfp = eventsfp,
784                 };
785
786                 err = json_events(fpath, print_events_table_entry, &data);
787
788                 free(data.topic);
789         }
790
791         return err;
792 }
793
794 #ifndef PATH_MAX
795 #define PATH_MAX        4096
796 #endif
797
798 /*
799  * Starting in directory 'start_dirname', find the "mapfile.csv" and
800  * the set of JSON files for the architecture 'arch'.
801  *
802  * From each JSON file, create a C-style "PMU events table" from the
803  * JSON file (see struct pmu_event).
804  *
805  * From the mapfile, create a mapping between the CPU revisions and
806  * PMU event tables (see struct pmu_events_map).
807  *
808  * Write out the PMU events tables and the mapping table to pmu-event.c.
809  *
810  * If unable to process the JSON or arch files, create an empty mapping
811  * table so we can continue to build/use  perf even if we cannot use the
812  * PMU event aliases.
813  */
814 int main(int argc, char *argv[])
815 {
816         int rc;
817         int maxfds;
818         char ldirname[PATH_MAX];
819
820         const char *arch;
821         const char *output_file;
822         const char *start_dirname;
823
824         prog = basename(argv[0]);
825         if (argc < 4) {
826                 pr_err("Usage: %s <arch> <starting_dir> <output_file>\n", prog);
827                 return 1;
828         }
829
830         arch = argv[1];
831         start_dirname = argv[2];
832         output_file = argv[3];
833
834         if (argc > 4)
835                 verbose = atoi(argv[4]);
836
837         eventsfp = fopen(output_file, "w");
838         if (!eventsfp) {
839                 pr_err("%s Unable to create required file %s (%s)\n",
840                                 prog, output_file, strerror(errno));
841                 return 2;
842         }
843
844         /* Include pmu-events.h first */
845         fprintf(eventsfp, "#include \"../../pmu-events/pmu-events.h\"\n");
846
847         sprintf(ldirname, "%s/%s", start_dirname, arch);
848
849         /*
850          * The mapfile allows multiple CPUids to point to the same JSON file,
851          * so, not sure if there is a need for symlinks within the pmu-events
852          * directory.
853          *
854          * For now, treat symlinks of JSON files as regular files and create
855          * separate tables for each symlink (presumably, each symlink refers
856          * to specific version of the CPU).
857          */
858
859         maxfds = get_maxfds();
860         mapfile = NULL;
861         rc = nftw(ldirname, process_one_file, maxfds, 0);
862         if (rc && verbose) {
863                 pr_info("%s: Error walking file tree %s\n", prog, ldirname);
864                 goto empty_map;
865         } else if (rc) {
866                 goto empty_map;
867         }
868
869         if (close_table)
870                 print_events_table_suffix(eventsfp);
871
872         if (!mapfile) {
873                 pr_info("%s: No CPU->JSON mapping?\n", prog);
874                 goto empty_map;
875         }
876
877         if (process_mapfile(eventsfp, mapfile)) {
878                 pr_info("%s: Error processing mapfile %s\n", prog, mapfile);
879                 goto empty_map;
880         }
881
882         return 0;
883
884 empty_map:
885         fclose(eventsfp);
886         create_empty_mapping(output_file);
887         return 0;
888 }