Back to home page

LXR

 
 

    


0001 #define  _XOPEN_SOURCE 500  /* needed for nftw() */
0002 #define  _GNU_SOURCE        /* needed for asprintf() */
0003 
0004 /* Parse event JSON files */
0005 
0006 /*
0007  * Copyright (c) 2014, Intel Corporation
0008  * All rights reserved.
0009  *
0010  * Redistribution and use in source and binary forms, with or without
0011  * modification, are permitted provided that the following conditions are met:
0012  *
0013  * 1. Redistributions of source code must retain the above copyright notice,
0014  * this list of conditions and the following disclaimer.
0015  *
0016  * 2. Redistributions in binary form must reproduce the above copyright
0017  * notice, this list of conditions and the following disclaimer in the
0018  * documentation and/or other materials provided with the distribution.
0019  *
0020  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
0021  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
0022  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
0023  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
0024  * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
0025  * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
0026  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
0027  * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
0028  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
0029  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
0030  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
0031  * OF THE POSSIBILITY OF SUCH DAMAGE.
0032 */
0033 
0034 #include <stdio.h>
0035 #include <stdlib.h>
0036 #include <errno.h>
0037 #include <string.h>
0038 #include <ctype.h>
0039 #include <unistd.h>
0040 #include <stdarg.h>
0041 #include <libgen.h>
0042 #include <dirent.h>
0043 #include <sys/time.h>           /* getrlimit */
0044 #include <sys/resource.h>       /* getrlimit */
0045 #include <ftw.h>
0046 #include <sys/stat.h>
0047 #include "jsmn.h"
0048 #include "json.h"
0049 #include "jevents.h"
0050 
0051 #ifndef __maybe_unused
0052 #define __maybe_unused                  __attribute__((unused))
0053 #endif
0054 
0055 int verbose;
0056 char *prog;
0057 
0058 int eprintf(int level, int var, const char *fmt, ...)
0059 {
0060 
0061     int ret;
0062     va_list args;
0063 
0064     if (var < level)
0065         return 0;
0066 
0067     va_start(args, fmt);
0068 
0069     ret = vfprintf(stderr, fmt, args);
0070 
0071     va_end(args);
0072 
0073     return ret;
0074 }
0075 
0076 __attribute__((weak)) char *get_cpu_str(void)
0077 {
0078     return NULL;
0079 }
0080 
0081 static void addfield(char *map, char **dst, const char *sep,
0082              const char *a, jsmntok_t *bt)
0083 {
0084     unsigned int len = strlen(a) + 1 + strlen(sep);
0085     int olen = *dst ? strlen(*dst) : 0;
0086     int blen = bt ? json_len(bt) : 0;
0087     char *out;
0088 
0089     out = realloc(*dst, len + olen + blen);
0090     if (!out) {
0091         /* Don't add field in this case */
0092         return;
0093     }
0094     *dst = out;
0095 
0096     if (!olen)
0097         *(*dst) = 0;
0098     else
0099         strcat(*dst, sep);
0100     strcat(*dst, a);
0101     if (bt)
0102         strncat(*dst, map + bt->start, blen);
0103 }
0104 
0105 static void fixname(char *s)
0106 {
0107     for (; *s; s++)
0108         *s = tolower(*s);
0109 }
0110 
0111 static void fixdesc(char *s)
0112 {
0113     char *e = s + strlen(s);
0114 
0115     /* Remove trailing dots that look ugly in perf list */
0116     --e;
0117     while (e >= s && isspace(*e))
0118         --e;
0119     if (*e == '.')
0120         *e = 0;
0121 }
0122 
0123 static struct msrmap {
0124     const char *num;
0125     const char *pname;
0126 } msrmap[] = {
0127     { "0x3F6", "ldlat=" },
0128     { "0x1A6", "offcore_rsp=" },
0129     { "0x1A7", "offcore_rsp=" },
0130     { "0x3F7", "frontend=" },
0131     { NULL, NULL }
0132 };
0133 
0134 static struct field {
0135     const char *field;
0136     const char *kernel;
0137 } fields[] = {
0138     { "EventCode",  "event=" },
0139     { "UMask",  "umask=" },
0140     { "CounterMask", "cmask=" },
0141     { "Invert", "inv=" },
0142     { "AnyThread",  "any=" },
0143     { "EdgeDetect", "edge=" },
0144     { "SampleAfterValue", "period=" },
0145     { NULL, NULL }
0146 };
0147 
0148 static void cut_comma(char *map, jsmntok_t *newval)
0149 {
0150     int i;
0151 
0152     /* Cut off everything after comma */
0153     for (i = newval->start; i < newval->end; i++) {
0154         if (map[i] == ',')
0155             newval->end = i;
0156     }
0157 }
0158 
0159 static int match_field(char *map, jsmntok_t *field, int nz,
0160                char **event, jsmntok_t *val)
0161 {
0162     struct field *f;
0163     jsmntok_t newval = *val;
0164 
0165     for (f = fields; f->field; f++)
0166         if (json_streq(map, field, f->field) && nz) {
0167             cut_comma(map, &newval);
0168             addfield(map, event, ",", f->kernel, &newval);
0169             return 1;
0170         }
0171     return 0;
0172 }
0173 
0174 static struct msrmap *lookup_msr(char *map, jsmntok_t *val)
0175 {
0176     jsmntok_t newval = *val;
0177     static bool warned;
0178     int i;
0179 
0180     cut_comma(map, &newval);
0181     for (i = 0; msrmap[i].num; i++)
0182         if (json_streq(map, &newval, msrmap[i].num))
0183             return &msrmap[i];
0184     if (!warned) {
0185         warned = true;
0186         pr_err("%s: Unknown MSR in event file %.*s\n", prog,
0187             json_len(val), map + val->start);
0188     }
0189     return NULL;
0190 }
0191 
0192 #define EXPECT(e, t, m) do { if (!(e)) {            \
0193     jsmntok_t *loc = (t);                   \
0194     if (!(t)->start && (t) > tokens)            \
0195         loc = (t) - 1;                  \
0196         pr_err("%s:%d: " m ", got %s\n", fn,        \
0197             json_line(map, loc),            \
0198             json_name(t));              \
0199     goto out_free;                      \
0200 } } while (0)
0201 
0202 #define TOPIC_DEPTH 256
0203 static char *topic_array[TOPIC_DEPTH];
0204 static int   topic_level;
0205 
0206 static char *get_topic(void)
0207 {
0208     char *tp_old, *tp = NULL;
0209     int i;
0210 
0211     for (i = 0; i < topic_level + 1; i++) {
0212         int n;
0213 
0214         tp_old = tp;
0215         n = asprintf(&tp, "%s%s", tp ?: "", topic_array[i]);
0216         if (n < 0) {
0217             pr_info("%s: asprintf() error %s\n", prog);
0218             return NULL;
0219         }
0220         free(tp_old);
0221     }
0222 
0223     for (i = 0; i < (int) strlen(tp); i++) {
0224         char c = tp[i];
0225 
0226         if (c == '-')
0227             tp[i] = ' ';
0228         else if (c == '.') {
0229             tp[i] = '\0';
0230             break;
0231         }
0232     }
0233 
0234     return tp;
0235 }
0236 
0237 static int add_topic(int level, char *bname)
0238 {
0239     char *topic;
0240 
0241     level -= 2;
0242 
0243     if (level >= TOPIC_DEPTH)
0244         return -EINVAL;
0245 
0246     topic = strdup(bname);
0247     if (!topic) {
0248         pr_info("%s: strdup() error %s for file %s\n", prog,
0249                 strerror(errno), bname);
0250         return -ENOMEM;
0251     }
0252 
0253     free(topic_array[topic_level]);
0254     topic_array[topic_level] = topic;
0255     topic_level              = level;
0256     return 0;
0257 }
0258 
0259 struct perf_entry_data {
0260     FILE *outfp;
0261     char *topic;
0262 };
0263 
0264 static int close_table;
0265 
0266 static void print_events_table_prefix(FILE *fp, const char *tblname)
0267 {
0268     fprintf(fp, "struct pmu_event %s[] = {\n", tblname);
0269     close_table = 1;
0270 }
0271 
0272 static int print_events_table_entry(void *data, char *name, char *event,
0273                     char *desc, char *long_desc)
0274 {
0275     struct perf_entry_data *pd = data;
0276     FILE *outfp = pd->outfp;
0277     char *topic = pd->topic;
0278 
0279     /*
0280      * TODO: Remove formatting chars after debugging to reduce
0281      *   string lengths.
0282      */
0283     fprintf(outfp, "{\n");
0284 
0285     fprintf(outfp, "\t.name = \"%s\",\n", name);
0286     fprintf(outfp, "\t.event = \"%s\",\n", event);
0287     fprintf(outfp, "\t.desc = \"%s\",\n", desc);
0288     fprintf(outfp, "\t.topic = \"%s\",\n", topic);
0289     if (long_desc && long_desc[0])
0290         fprintf(outfp, "\t.long_desc = \"%s\",\n", long_desc);
0291 
0292     fprintf(outfp, "},\n");
0293 
0294     return 0;
0295 }
0296 
0297 static void print_events_table_suffix(FILE *outfp)
0298 {
0299     fprintf(outfp, "{\n");
0300 
0301     fprintf(outfp, "\t.name = 0,\n");
0302     fprintf(outfp, "\t.event = 0,\n");
0303     fprintf(outfp, "\t.desc = 0,\n");
0304 
0305     fprintf(outfp, "},\n");
0306     fprintf(outfp, "};\n");
0307     close_table = 0;
0308 }
0309 
0310 static struct fixed {
0311     const char *name;
0312     const char *event;
0313 } fixed[] = {
0314     { "inst_retired.any", "event=0xc0" },
0315     { "inst_retired.any_p", "event=0xc0" },
0316     { "cpu_clk_unhalted.ref", "event=0x0,umask=0x03" },
0317     { "cpu_clk_unhalted.thread", "event=0x3c" },
0318     { "cpu_clk_unhalted.thread_any", "event=0x3c,any=1" },
0319     { NULL, NULL},
0320 };
0321 
0322 /*
0323  * Handle different fixed counter encodings between JSON and perf.
0324  */
0325 static char *real_event(const char *name, char *event)
0326 {
0327     int i;
0328 
0329     for (i = 0; fixed[i].name; i++)
0330         if (!strcasecmp(name, fixed[i].name))
0331             return (char *)fixed[i].event;
0332     return event;
0333 }
0334 
0335 /* Call func with each event in the json file */
0336 int json_events(const char *fn,
0337       int (*func)(void *data, char *name, char *event, char *desc,
0338               char *long_desc),
0339       void *data)
0340 {
0341     int err = -EIO;
0342     size_t size;
0343     jsmntok_t *tokens, *tok;
0344     int i, j, len;
0345     char *map;
0346 
0347     if (!fn)
0348         return -ENOENT;
0349 
0350     tokens = parse_json(fn, &map, &size, &len);
0351     if (!tokens)
0352         return -EIO;
0353     EXPECT(tokens->type == JSMN_ARRAY, tokens, "expected top level array");
0354     tok = tokens + 1;
0355     for (i = 0; i < tokens->size; i++) {
0356         char *event = NULL, *desc = NULL, *name = NULL;
0357         char *long_desc = NULL;
0358         char *extra_desc = NULL;
0359         struct msrmap *msr = NULL;
0360         jsmntok_t *msrval = NULL;
0361         jsmntok_t *precise = NULL;
0362         jsmntok_t *obj = tok++;
0363 
0364         EXPECT(obj->type == JSMN_OBJECT, obj, "expected object");
0365         for (j = 0; j < obj->size; j += 2) {
0366             jsmntok_t *field, *val;
0367             int nz;
0368 
0369             field = tok + j;
0370             EXPECT(field->type == JSMN_STRING, tok + j,
0371                    "Expected field name");
0372             val = tok + j + 1;
0373             EXPECT(val->type == JSMN_STRING, tok + j + 1,
0374                    "Expected string value");
0375 
0376             nz = !json_streq(map, val, "0");
0377             if (match_field(map, field, nz, &event, val)) {
0378                 /* ok */
0379             } else if (json_streq(map, field, "EventName")) {
0380                 addfield(map, &name, "", "", val);
0381             } else if (json_streq(map, field, "BriefDescription")) {
0382                 addfield(map, &desc, "", "", val);
0383                 fixdesc(desc);
0384             } else if (json_streq(map, field,
0385                          "PublicDescription")) {
0386                 addfield(map, &long_desc, "", "", val);
0387                 fixdesc(long_desc);
0388             } else if (json_streq(map, field, "PEBS") && nz) {
0389                 precise = val;
0390             } else if (json_streq(map, field, "MSRIndex") && nz) {
0391                 msr = lookup_msr(map, val);
0392             } else if (json_streq(map, field, "MSRValue")) {
0393                 msrval = val;
0394             } else if (json_streq(map, field, "Errata") &&
0395                    !json_streq(map, val, "null")) {
0396                 addfield(map, &extra_desc, ". ",
0397                     " Spec update: ", val);
0398             } else if (json_streq(map, field, "Data_LA") && nz) {
0399                 addfield(map, &extra_desc, ". ",
0400                     " Supports address when precise",
0401                     NULL);
0402             }
0403             /* ignore unknown fields */
0404         }
0405         if (precise && desc && !strstr(desc, "(Precise Event)")) {
0406             if (json_streq(map, precise, "2"))
0407                 addfield(map, &extra_desc, " ",
0408                         "(Must be precise)", NULL);
0409             else
0410                 addfield(map, &extra_desc, " ",
0411                         "(Precise event)", NULL);
0412         }
0413         if (desc && extra_desc)
0414             addfield(map, &desc, " ", extra_desc, NULL);
0415         if (long_desc && extra_desc)
0416             addfield(map, &long_desc, " ", extra_desc, NULL);
0417         if (msr != NULL)
0418             addfield(map, &event, ",", msr->pname, msrval);
0419         fixname(name);
0420 
0421         err = func(data, name, real_event(name, event), desc, long_desc);
0422         free(event);
0423         free(desc);
0424         free(name);
0425         free(long_desc);
0426         free(extra_desc);
0427         if (err)
0428             break;
0429         tok += j;
0430     }
0431     EXPECT(tok - tokens == len, tok, "unexpected objects at end");
0432     err = 0;
0433 out_free:
0434     free_json(map, size, tokens);
0435     return err;
0436 }
0437 
0438 static char *file_name_to_table_name(char *fname)
0439 {
0440     unsigned int i;
0441     int n;
0442     int c;
0443     char *tblname;
0444 
0445     /*
0446      * Ensure tablename starts with alphabetic character.
0447      * Derive rest of table name from basename of the JSON file,
0448      * replacing hyphens and stripping out .json suffix.
0449      */
0450     n = asprintf(&tblname, "pme_%s", basename(fname));
0451     if (n < 0) {
0452         pr_info("%s: asprintf() error %s for file %s\n", prog,
0453                 strerror(errno), fname);
0454         return NULL;
0455     }
0456 
0457     for (i = 0; i < strlen(tblname); i++) {
0458         c = tblname[i];
0459 
0460         if (c == '-')
0461             tblname[i] = '_';
0462         else if (c == '.') {
0463             tblname[i] = '\0';
0464             break;
0465         } else if (!isalnum(c) && c != '_') {
0466             pr_err("%s: Invalid character '%c' in file name %s\n",
0467                     prog, c, basename(fname));
0468             free(tblname);
0469             tblname = NULL;
0470             break;
0471         }
0472     }
0473 
0474     return tblname;
0475 }
0476 
0477 static void print_mapping_table_prefix(FILE *outfp)
0478 {
0479     fprintf(outfp, "struct pmu_events_map pmu_events_map[] = {\n");
0480 }
0481 
0482 static void print_mapping_table_suffix(FILE *outfp)
0483 {
0484     /*
0485      * Print the terminating, NULL entry.
0486      */
0487     fprintf(outfp, "{\n");
0488     fprintf(outfp, "\t.cpuid = 0,\n");
0489     fprintf(outfp, "\t.version = 0,\n");
0490     fprintf(outfp, "\t.type = 0,\n");
0491     fprintf(outfp, "\t.table = 0,\n");
0492     fprintf(outfp, "},\n");
0493 
0494     /* and finally, the closing curly bracket for the struct */
0495     fprintf(outfp, "};\n");
0496 }
0497 
0498 static int process_mapfile(FILE *outfp, char *fpath)
0499 {
0500     int n = 16384;
0501     FILE *mapfp;
0502     char *save = NULL;
0503     char *line, *p;
0504     int line_num;
0505     char *tblname;
0506 
0507     pr_info("%s: Processing mapfile %s\n", prog, fpath);
0508 
0509     line = malloc(n);
0510     if (!line)
0511         return -1;
0512 
0513     mapfp = fopen(fpath, "r");
0514     if (!mapfp) {
0515         pr_info("%s: Error %s opening %s\n", prog, strerror(errno),
0516                 fpath);
0517         return -1;
0518     }
0519 
0520     print_mapping_table_prefix(outfp);
0521 
0522     /* Skip first line (header) */
0523     p = fgets(line, n, mapfp);
0524     if (!p)
0525         goto out;
0526 
0527     line_num = 1;
0528     while (1) {
0529         char *cpuid, *version, *type, *fname;
0530 
0531         line_num++;
0532         p = fgets(line, n, mapfp);
0533         if (!p)
0534             break;
0535 
0536         if (line[0] == '#' || line[0] == '\n')
0537             continue;
0538 
0539         if (line[strlen(line)-1] != '\n') {
0540             /* TODO Deal with lines longer than 16K */
0541             pr_info("%s: Mapfile %s: line %d too long, aborting\n",
0542                     prog, fpath, line_num);
0543             return -1;
0544         }
0545         line[strlen(line)-1] = '\0';
0546 
0547         cpuid = strtok_r(p, ",", &save);
0548         version = strtok_r(NULL, ",", &save);
0549         fname = strtok_r(NULL, ",", &save);
0550         type = strtok_r(NULL, ",", &save);
0551 
0552         tblname = file_name_to_table_name(fname);
0553         fprintf(outfp, "{\n");
0554         fprintf(outfp, "\t.cpuid = \"%s\",\n", cpuid);
0555         fprintf(outfp, "\t.version = \"%s\",\n", version);
0556         fprintf(outfp, "\t.type = \"%s\",\n", type);
0557 
0558         /*
0559          * CHECK: We can't use the type (eg "core") field in the
0560          * table name. For us to do that, we need to somehow tweak
0561          * the other caller of file_name_to_table(), process_json()
0562          * to determine the type. process_json() file has no way
0563          * of knowing these are "core" events unless file name has
0564          * core in it. If filename has core in it, we can safely
0565          * ignore the type field here also.
0566          */
0567         fprintf(outfp, "\t.table = %s\n", tblname);
0568         fprintf(outfp, "},\n");
0569     }
0570 
0571 out:
0572     print_mapping_table_suffix(outfp);
0573     return 0;
0574 }
0575 
0576 /*
0577  * If we fail to locate/process JSON and map files, create a NULL mapping
0578  * table. This would at least allow perf to build even if we can't find/use
0579  * the aliases.
0580  */
0581 static void create_empty_mapping(const char *output_file)
0582 {
0583     FILE *outfp;
0584 
0585     pr_info("%s: Creating empty pmu_events_map[] table\n", prog);
0586 
0587     /* Truncate file to clear any partial writes to it */
0588     outfp = fopen(output_file, "w");
0589     if (!outfp) {
0590         perror("fopen()");
0591         _Exit(1);
0592     }
0593 
0594     fprintf(outfp, "#include \"../../pmu-events/pmu-events.h\"\n");
0595     print_mapping_table_prefix(outfp);
0596     print_mapping_table_suffix(outfp);
0597     fclose(outfp);
0598 }
0599 
0600 static int get_maxfds(void)
0601 {
0602     struct rlimit rlim;
0603 
0604     if (getrlimit(RLIMIT_NOFILE, &rlim) == 0)
0605         return min((int)rlim.rlim_max / 2, 512);
0606 
0607     return 512;
0608 }
0609 
0610 /*
0611  * nftw() doesn't let us pass an argument to the processing function,
0612  * so use a global variables.
0613  */
0614 static FILE *eventsfp;
0615 static char *mapfile;
0616 
0617 static int process_one_file(const char *fpath, const struct stat *sb,
0618                 int typeflag, struct FTW *ftwbuf)
0619 {
0620     char *tblname, *bname  = (char *) fpath + ftwbuf->base;
0621     int is_dir  = typeflag == FTW_D;
0622     int is_file = typeflag == FTW_F;
0623     int level   = ftwbuf->level;
0624     int err = 0;
0625 
0626     pr_debug("%s %d %7jd %-20s %s\n",
0627          is_file ? "f" : is_dir ? "d" : "x",
0628          level, sb->st_size, bname, fpath);
0629 
0630     /* base dir */
0631     if (level == 0)
0632         return 0;
0633 
0634     /* model directory, reset topic */
0635     if (level == 1 && is_dir) {
0636         if (close_table)
0637             print_events_table_suffix(eventsfp);
0638 
0639         /*
0640          * Drop file name suffix. Replace hyphens with underscores.
0641          * Fail if file name contains any alphanum characters besides
0642          * underscores.
0643          */
0644         tblname = file_name_to_table_name(bname);
0645         if (!tblname) {
0646             pr_info("%s: Error determining table name for %s\n", prog,
0647                 bname);
0648             return -1;
0649         }
0650 
0651         print_events_table_prefix(eventsfp, tblname);
0652         return 0;
0653     }
0654 
0655     /*
0656      * Save the mapfile name for now. We will process mapfile
0657      * after processing all JSON files (so we can write out the
0658      * mapping table after all PMU events tables).
0659      *
0660      * TODO: Allow for multiple mapfiles? Punt for now.
0661      */
0662     if (level == 1 && is_file) {
0663         if (!strncmp(bname, "mapfile.csv", 11)) {
0664             if (mapfile) {
0665                 pr_info("%s: Many mapfiles? Using %s, ignoring %s\n",
0666                         prog, mapfile, fpath);
0667             } else {
0668                 mapfile = strdup(fpath);
0669             }
0670             return 0;
0671         }
0672 
0673         pr_info("%s: Ignoring file %s\n", prog, fpath);
0674         return 0;
0675     }
0676 
0677     /*
0678      * If the file name does not have a .json extension,
0679      * ignore it. It could be a readme.txt for instance.
0680      */
0681     if (is_file) {
0682         char *suffix = bname + strlen(bname) - 5;
0683 
0684         if (strncmp(suffix, ".json", 5)) {
0685             pr_info("%s: Ignoring file without .json suffix %s\n", prog,
0686                 fpath);
0687             return 0;
0688         }
0689     }
0690 
0691     if (level > 1 && add_topic(level, bname))
0692         return -ENOMEM;
0693 
0694     /*
0695      * Assume all other files are JSON files.
0696      *
0697      * If mapfile refers to 'power7_core.json', we create a table
0698      * named 'power7_core'. Any inconsistencies between the mapfile
0699      * and directory tree could result in build failure due to table
0700      * names not being found.
0701      *
0702      * Atleast for now, be strict with processing JSON file names.
0703      * i.e. if JSON file name cannot be mapped to C-style table name,
0704      * fail.
0705      */
0706     if (is_file) {
0707         struct perf_entry_data data = {
0708             .topic = get_topic(),
0709             .outfp = eventsfp,
0710         };
0711 
0712         err = json_events(fpath, print_events_table_entry, &data);
0713 
0714         free(data.topic);
0715     }
0716 
0717     return err;
0718 }
0719 
0720 #ifndef PATH_MAX
0721 #define PATH_MAX    4096
0722 #endif
0723 
0724 /*
0725  * Starting in directory 'start_dirname', find the "mapfile.csv" and
0726  * the set of JSON files for the architecture 'arch'.
0727  *
0728  * From each JSON file, create a C-style "PMU events table" from the
0729  * JSON file (see struct pmu_event).
0730  *
0731  * From the mapfile, create a mapping between the CPU revisions and
0732  * PMU event tables (see struct pmu_events_map).
0733  *
0734  * Write out the PMU events tables and the mapping table to pmu-event.c.
0735  *
0736  * If unable to process the JSON or arch files, create an empty mapping
0737  * table so we can continue to build/use  perf even if we cannot use the
0738  * PMU event aliases.
0739  */
0740 int main(int argc, char *argv[])
0741 {
0742     int rc;
0743     int maxfds;
0744     char ldirname[PATH_MAX];
0745 
0746     const char *arch;
0747     const char *output_file;
0748     const char *start_dirname;
0749 
0750     prog = basename(argv[0]);
0751     if (argc < 4) {
0752         pr_err("Usage: %s <arch> <starting_dir> <output_file>\n", prog);
0753         return 1;
0754     }
0755 
0756     arch = argv[1];
0757     start_dirname = argv[2];
0758     output_file = argv[3];
0759 
0760     if (argc > 4)
0761         verbose = atoi(argv[4]);
0762 
0763     eventsfp = fopen(output_file, "w");
0764     if (!eventsfp) {
0765         pr_err("%s Unable to create required file %s (%s)\n",
0766                 prog, output_file, strerror(errno));
0767         return 2;
0768     }
0769 
0770     /* Include pmu-events.h first */
0771     fprintf(eventsfp, "#include \"../../pmu-events/pmu-events.h\"\n");
0772 
0773     sprintf(ldirname, "%s/%s", start_dirname, arch);
0774 
0775     /*
0776      * The mapfile allows multiple CPUids to point to the same JSON file,
0777      * so, not sure if there is a need for symlinks within the pmu-events
0778      * directory.
0779      *
0780      * For now, treat symlinks of JSON files as regular files and create
0781      * separate tables for each symlink (presumably, each symlink refers
0782      * to specific version of the CPU).
0783      */
0784 
0785     maxfds = get_maxfds();
0786     mapfile = NULL;
0787     rc = nftw(ldirname, process_one_file, maxfds, 0);
0788     if (rc && verbose) {
0789         pr_info("%s: Error walking file tree %s\n", prog, ldirname);
0790         goto empty_map;
0791     } else if (rc) {
0792         goto empty_map;
0793     }
0794 
0795     if (close_table)
0796         print_events_table_suffix(eventsfp);
0797 
0798     if (!mapfile) {
0799         pr_info("%s: No CPU->JSON mapping?\n", prog);
0800         goto empty_map;
0801     }
0802 
0803     if (process_mapfile(eventsfp, mapfile)) {
0804         pr_info("%s: Error processing mapfile %s\n", prog, mapfile);
0805         goto empty_map;
0806     }
0807 
0808     return 0;
0809 
0810 empty_map:
0811     fclose(eventsfp);
0812     create_empty_mapping(output_file);
0813     return 0;
0814 }