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