1 #define _XOPEN_SOURCE 500 /* needed for nftw() */
2 #define _GNU_SOURCE /* needed for asprintf() */
4 /* Parse event JSON files */
7 * Copyright (c) 2014, Intel Corporation
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions are met:
13 * 1. Redistributions of source code must retain the above copyright notice,
14 * this list of conditions and the following disclaimer.
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.
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.
43 #include <sys/time.h> /* getrlimit */
44 #include <sys/resource.h> /* getrlimit */
51 #ifndef __maybe_unused
52 #define __maybe_unused __attribute__((unused))
58 int eprintf(int level, int var, const char *fmt, ...)
69 ret = vfprintf(stderr, fmt, args);
76 __attribute__((weak)) char *get_cpu_str(void)
81 static void addfield(char *map, char **dst, const char *sep,
82 const char *a, jsmntok_t *bt)
84 unsigned int len = strlen(a) + 1 + strlen(sep);
85 int olen = *dst ? strlen(*dst) : 0;
86 int blen = bt ? json_len(bt) : 0;
89 out = realloc(*dst, len + olen + blen);
91 /* Don't add field in this case */
102 strncat(*dst, map + bt->start, blen);
105 static void fixname(char *s)
111 static void fixdesc(char *s)
113 char *e = s + strlen(s);
115 /* Remove trailing dots that look ugly in perf list */
117 while (e >= s && isspace(*e))
123 static struct msrmap {
127 { "0x3F6", "ldlat=" },
128 { "0x1A6", "offcore_rsp=" },
129 { "0x1A7", "offcore_rsp=" },
133 static struct field {
137 { "EventCode", "event=" },
138 { "UMask", "umask=" },
139 { "CounterMask", "cmask=" },
140 { "Invert", "inv=" },
141 { "AnyThread", "any=" },
142 { "EdgeDetect", "edge=" },
143 { "SampleAfterValue", "period=" },
147 static void cut_comma(char *map, jsmntok_t *newval)
151 /* Cut off everything after comma */
152 for (i = newval->start; i < newval->end; i++) {
158 static int match_field(char *map, jsmntok_t *field, int nz,
159 char **event, jsmntok_t *val)
162 jsmntok_t newval = *val;
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);
173 static struct msrmap *lookup_msr(char *map, jsmntok_t *val)
175 jsmntok_t newval = *val;
179 cut_comma(map, &newval);
180 for (i = 0; msrmap[i].num; i++)
181 if (json_streq(map, &newval, msrmap[i].num))
185 pr_err("%s: Unknown MSR in event file %.*s\n", prog,
186 json_len(val), map + val->start);
191 #define EXPECT(e, t, m) do { if (!(e)) { \
192 jsmntok_t *loc = (t); \
193 if (!(t)->start && (t) > tokens) \
195 pr_err("%s:%d: " m ", got %s\n", fn, \
196 json_line(map, loc), \
201 #define TOPIC_DEPTH 256
202 static char *topic_array[TOPIC_DEPTH];
203 static int topic_level;
205 static char *get_topic(void)
207 char *tp_old, *tp = NULL;
210 for (i = 0; i < topic_level + 1; i++) {
214 n = asprintf(&tp, "%s%s", tp ?: "", topic_array[i]);
216 pr_info("%s: asprintf() error %s\n", prog);
222 for (i = 0; i < (int) strlen(tp); i++) {
236 static int add_topic(int level, char *bname)
242 if (level >= TOPIC_DEPTH)
245 topic = strdup(bname);
247 pr_info("%s: strdup() error %s for file %s\n", prog,
248 strerror(errno), bname);
252 free(topic_array[topic_level]);
253 topic_array[topic_level] = topic;
258 struct perf_entry_data {
263 static int close_table;
265 static void print_events_table_prefix(FILE *fp, const char *tblname)
267 fprintf(fp, "struct pmu_event %s[] = {\n", tblname);
271 static int print_events_table_entry(void *data, char *name, char *event,
274 struct perf_entry_data *pd = data;
275 FILE *outfp = pd->outfp;
276 char *topic = pd->topic;
279 * TODO: Remove formatting chars after debugging to reduce
282 fprintf(outfp, "{\n");
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);
289 fprintf(outfp, "},\n");
294 static void print_events_table_suffix(FILE *outfp)
296 fprintf(outfp, "{\n");
298 fprintf(outfp, "\t.name = 0,\n");
299 fprintf(outfp, "\t.event = 0,\n");
300 fprintf(outfp, "\t.desc = 0,\n");
302 fprintf(outfp, "},\n");
303 fprintf(outfp, "};\n");
307 /* Call func with each event in the json file */
308 int json_events(const char *fn,
309 int (*func)(void *data, char *name, char *event, char *desc),
314 jsmntok_t *tokens, *tok;
321 tokens = parse_json(fn, &map, &size, &len);
324 EXPECT(tokens->type == JSMN_ARRAY, tokens, "expected top level array");
326 for (i = 0; i < tokens->size; i++) {
327 char *event = NULL, *desc = NULL, *name = NULL;
328 struct msrmap *msr = NULL;
329 jsmntok_t *msrval = NULL;
330 jsmntok_t *precise = NULL;
331 jsmntok_t *obj = tok++;
333 EXPECT(obj->type == JSMN_OBJECT, obj, "expected object");
334 for (j = 0; j < obj->size; j += 2) {
335 jsmntok_t *field, *val;
339 EXPECT(field->type == JSMN_STRING, tok + j,
340 "Expected field name");
342 EXPECT(val->type == JSMN_STRING, tok + j + 1,
343 "Expected string value");
345 nz = !json_streq(map, val, "0");
346 if (match_field(map, field, nz, &event, val)) {
348 } else if (json_streq(map, field, "EventName")) {
349 addfield(map, &name, "", "", val);
350 } else if (json_streq(map, field, "BriefDescription")) {
351 addfield(map, &desc, "", "", val);
353 } else if (json_streq(map, field, "PEBS") && nz) {
355 } else if (json_streq(map, field, "MSRIndex") && nz) {
356 msr = lookup_msr(map, val);
357 } else if (json_streq(map, field, "MSRValue")) {
359 } else if (json_streq(map, field, "Errata") &&
360 !json_streq(map, val, "null")) {
361 addfield(map, &desc, ". ",
362 " Spec update: ", val);
363 } else if (json_streq(map, field, "Data_LA") && nz) {
364 addfield(map, &desc, ". ",
365 " Supports address when precise",
368 /* ignore unknown fields */
370 if (precise && desc && !strstr(desc, "(Precise Event)")) {
371 if (json_streq(map, precise, "2"))
372 addfield(map, &desc, " ", "(Must be precise)",
375 addfield(map, &desc, " ",
376 "(Precise event)", NULL);
379 addfield(map, &event, ",", msr->pname, msrval);
381 err = func(data, name, event, desc);
389 EXPECT(tok - tokens == len, tok, "unexpected objects at end");
392 free_json(map, size, tokens);
396 static char *file_name_to_table_name(char *fname)
404 * Ensure tablename starts with alphabetic character.
405 * Derive rest of table name from basename of the JSON file,
406 * replacing hyphens and stripping out .json suffix.
408 n = asprintf(&tblname, "pme_%s", basename(fname));
410 pr_info("%s: asprintf() error %s for file %s\n", prog,
411 strerror(errno), fname);
415 for (i = 0; i < strlen(tblname); i++) {
423 } else if (!isalnum(c) && c != '_') {
424 pr_err("%s: Invalid character '%c' in file name %s\n",
425 prog, c, basename(fname));
435 static void print_mapping_table_prefix(FILE *outfp)
437 fprintf(outfp, "struct pmu_events_map pmu_events_map[] = {\n");
440 static void print_mapping_table_suffix(FILE *outfp)
443 * Print the terminating, NULL entry.
445 fprintf(outfp, "{\n");
446 fprintf(outfp, "\t.cpuid = 0,\n");
447 fprintf(outfp, "\t.version = 0,\n");
448 fprintf(outfp, "\t.type = 0,\n");
449 fprintf(outfp, "\t.table = 0,\n");
450 fprintf(outfp, "},\n");
452 /* and finally, the closing curly bracket for the struct */
453 fprintf(outfp, "};\n");
456 static int process_mapfile(FILE *outfp, char *fpath)
465 pr_info("%s: Processing mapfile %s\n", prog, fpath);
471 mapfp = fopen(fpath, "r");
473 pr_info("%s: Error %s opening %s\n", prog, strerror(errno),
478 print_mapping_table_prefix(outfp);
482 char *cpuid, *version, *type, *fname;
485 p = fgets(line, n, mapfp);
489 if (line[0] == '#' || line[0] == '\n')
492 if (line[strlen(line)-1] != '\n') {
493 /* TODO Deal with lines longer than 16K */
494 pr_info("%s: Mapfile %s: line %d too long, aborting\n",
495 prog, fpath, line_num);
498 line[strlen(line)-1] = '\0';
500 cpuid = strtok_r(p, ",", &save);
501 version = strtok_r(NULL, ",", &save);
502 fname = strtok_r(NULL, ",", &save);
503 type = strtok_r(NULL, ",", &save);
505 tblname = file_name_to_table_name(fname);
506 fprintf(outfp, "{\n");
507 fprintf(outfp, "\t.cpuid = \"%s\",\n", cpuid);
508 fprintf(outfp, "\t.version = \"%s\",\n", version);
509 fprintf(outfp, "\t.type = \"%s\",\n", type);
512 * CHECK: We can't use the type (eg "core") field in the
513 * table name. For us to do that, we need to somehow tweak
514 * the other caller of file_name_to_table(), process_json()
515 * to determine the type. process_json() file has no way
516 * of knowing these are "core" events unless file name has
517 * core in it. If filename has core in it, we can safely
518 * ignore the type field here also.
520 fprintf(outfp, "\t.table = %s\n", tblname);
521 fprintf(outfp, "},\n");
524 print_mapping_table_suffix(outfp);
530 * If we fail to locate/process JSON and map files, create a NULL mapping
531 * table. This would at least allow perf to build even if we can't find/use
534 static void create_empty_mapping(const char *output_file)
538 pr_info("%s: Creating empty pmu_events_map[] table\n", prog);
540 /* Truncate file to clear any partial writes to it */
541 outfp = fopen(output_file, "w");
547 fprintf(outfp, "#include \"../../pmu-events/pmu-events.h\"\n");
548 print_mapping_table_prefix(outfp);
549 print_mapping_table_suffix(outfp);
553 static int get_maxfds(void)
557 if (getrlimit(RLIMIT_NOFILE, &rlim) == 0)
558 return min((int)rlim.rlim_max / 2, 512);
564 * nftw() doesn't let us pass an argument to the processing function,
565 * so use a global variables.
567 static FILE *eventsfp;
568 static char *mapfile;
570 static int process_one_file(const char *fpath, const struct stat *sb,
571 int typeflag, struct FTW *ftwbuf)
573 char *tblname, *bname = (char *) fpath + ftwbuf->base;
574 int is_dir = typeflag == FTW_D;
575 int is_file = typeflag == FTW_F;
576 int level = ftwbuf->level;
579 pr_debug("%s %d %7jd %-20s %s\n",
580 is_file ? "f" : is_dir ? "d" : "x",
581 level, sb->st_size, bname, fpath);
587 /* model directory, reset topic */
588 if (level == 1 && is_dir) {
590 print_events_table_suffix(eventsfp);
593 * Drop file name suffix. Replace hyphens with underscores.
594 * Fail if file name contains any alphanum characters besides
597 tblname = file_name_to_table_name(bname);
599 pr_info("%s: Error determining table name for %s\n", prog,
604 print_events_table_prefix(eventsfp, tblname);
609 * Save the mapfile name for now. We will process mapfile
610 * after processing all JSON files (so we can write out the
611 * mapping table after all PMU events tables).
613 * TODO: Allow for multiple mapfiles? Punt for now.
615 if (level == 1 && is_file) {
616 if (!strncmp(bname, "mapfile.csv", 11)) {
618 pr_info("%s: Many mapfiles? Using %s, ignoring %s\n",
619 prog, mapfile, fpath);
621 mapfile = strdup(fpath);
626 pr_info("%s: Ignoring file %s\n", prog, fpath);
631 * If the file name does not have a .json extension,
632 * ignore it. It could be a readme.txt for instance.
635 char *suffix = bname + strlen(bname) - 5;
637 if (strncmp(suffix, ".json", 5)) {
638 pr_info("%s: Ignoring file without .json suffix %s\n", prog,
644 if (level > 1 && add_topic(level, bname))
648 * Assume all other files are JSON files.
650 * If mapfile refers to 'power7_core.json', we create a table
651 * named 'power7_core'. Any inconsistencies between the mapfile
652 * and directory tree could result in build failure due to table
653 * names not being found.
655 * Atleast for now, be strict with processing JSON file names.
656 * i.e. if JSON file name cannot be mapped to C-style table name,
660 struct perf_entry_data data = {
661 .topic = get_topic(),
665 err = json_events(fpath, print_events_table_entry, &data);
674 #define PATH_MAX 4096
678 * Starting in directory 'start_dirname', find the "mapfile.csv" and
679 * the set of JSON files for the architecture 'arch'.
681 * From each JSON file, create a C-style "PMU events table" from the
682 * JSON file (see struct pmu_event).
684 * From the mapfile, create a mapping between the CPU revisions and
685 * PMU event tables (see struct pmu_events_map).
687 * Write out the PMU events tables and the mapping table to pmu-event.c.
689 * If unable to process the JSON or arch files, create an empty mapping
690 * table so we can continue to build/use perf even if we cannot use the
693 int main(int argc, char *argv[])
697 char ldirname[PATH_MAX];
700 const char *output_file;
701 const char *start_dirname;
703 prog = basename(argv[0]);
705 pr_err("Usage: %s <arch> <starting_dir> <output_file>\n", prog);
710 start_dirname = argv[2];
711 output_file = argv[3];
714 verbose = atoi(argv[4]);
716 eventsfp = fopen(output_file, "w");
718 pr_err("%s Unable to create required file %s (%s)\n",
719 prog, output_file, strerror(errno));
723 /* Include pmu-events.h first */
724 fprintf(eventsfp, "#include \"../../pmu-events/pmu-events.h\"\n");
726 sprintf(ldirname, "%s/%s", start_dirname, arch);
729 * The mapfile allows multiple CPUids to point to the same JSON file,
730 * so, not sure if there is a need for symlinks within the pmu-events
733 * For now, treat symlinks of JSON files as regular files and create
734 * separate tables for each symlink (presumably, each symlink refers
735 * to specific version of the CPU).
738 maxfds = get_maxfds();
740 rc = nftw(ldirname, process_one_file, maxfds, 0);
742 pr_info("%s: Error walking file tree %s\n", prog, ldirname);
749 print_events_table_suffix(eventsfp);
752 pr_info("%s: No CPU->JSON mapping?\n", prog);
756 if (process_mapfile(eventsfp, mapfile)) {
757 pr_info("%s: Error processing mapfile %s\n", prog, mapfile);
765 create_empty_mapping(output_file);