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