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=" },
130 { "0x3F7", "frontend=" },
134 static struct field {
138 { "EventCode", "event=" },
139 { "UMask", "umask=" },
140 { "CounterMask", "cmask=" },
141 { "Invert", "inv=" },
142 { "AnyThread", "any=" },
143 { "EdgeDetect", "edge=" },
144 { "SampleAfterValue", "period=" },
148 static void cut_comma(char *map, jsmntok_t *newval)
152 /* Cut off everything after comma */
153 for (i = newval->start; i < newval->end; i++) {
159 static int match_field(char *map, jsmntok_t *field, int nz,
160 char **event, jsmntok_t *val)
163 jsmntok_t newval = *val;
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);
174 static struct msrmap *lookup_msr(char *map, jsmntok_t *val)
176 jsmntok_t newval = *val;
180 cut_comma(map, &newval);
181 for (i = 0; msrmap[i].num; i++)
182 if (json_streq(map, &newval, msrmap[i].num))
186 pr_err("%s: Unknown MSR in event file %.*s\n", prog,
187 json_len(val), map + val->start);
192 #define EXPECT(e, t, m) do { if (!(e)) { \
193 jsmntok_t *loc = (t); \
194 if (!(t)->start && (t) > tokens) \
196 pr_err("%s:%d: " m ", got %s\n", fn, \
197 json_line(map, loc), \
202 #define TOPIC_DEPTH 256
203 static char *topic_array[TOPIC_DEPTH];
204 static int topic_level;
206 static char *get_topic(void)
208 char *tp_old, *tp = NULL;
211 for (i = 0; i < topic_level + 1; i++) {
215 n = asprintf(&tp, "%s%s", tp ?: "", topic_array[i]);
217 pr_info("%s: asprintf() error %s\n", prog);
223 for (i = 0; i < (int) strlen(tp); i++) {
237 static int add_topic(int level, char *bname)
243 if (level >= TOPIC_DEPTH)
246 topic = strdup(bname);
248 pr_info("%s: strdup() error %s for file %s\n", prog,
249 strerror(errno), bname);
253 free(topic_array[topic_level]);
254 topic_array[topic_level] = topic;
259 struct perf_entry_data {
264 static int close_table;
266 static void print_events_table_prefix(FILE *fp, const char *tblname)
268 fprintf(fp, "struct pmu_event %s[] = {\n", tblname);
272 static int print_events_table_entry(void *data, char *name, char *event,
273 char *desc, char *long_desc)
275 struct perf_entry_data *pd = data;
276 FILE *outfp = pd->outfp;
277 char *topic = pd->topic;
280 * TODO: Remove formatting chars after debugging to reduce
283 fprintf(outfp, "{\n");
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);
292 fprintf(outfp, "},\n");
297 static void print_events_table_suffix(FILE *outfp)
299 fprintf(outfp, "{\n");
301 fprintf(outfp, "\t.name = 0,\n");
302 fprintf(outfp, "\t.event = 0,\n");
303 fprintf(outfp, "\t.desc = 0,\n");
305 fprintf(outfp, "},\n");
306 fprintf(outfp, "};\n");
310 static struct fixed {
314 { "inst_retired.any", "event=0xc0" },
315 { "inst_retired.any_p", "event=0xc0" },
316 { "cpu_clk_unhalted.ref", "event=0x0,umask=0x03" },
317 { "cpu_clk_unhalted.thread", "event=0x3c" },
318 { "cpu_clk_unhalted.thread_any", "event=0x3c,any=1" },
323 * Handle different fixed counter encodings between JSON and perf.
325 static char *real_event(const char *name, char *event)
329 for (i = 0; fixed[i].name; i++)
330 if (!strcasecmp(name, fixed[i].name))
331 return (char *)fixed[i].event;
335 /* Call func with each event in the json file */
336 int json_events(const char *fn,
337 int (*func)(void *data, char *name, char *event, char *desc,
343 jsmntok_t *tokens, *tok;
350 tokens = parse_json(fn, &map, &size, &len);
353 EXPECT(tokens->type == JSMN_ARRAY, tokens, "expected top level array");
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 struct msrmap *msr = NULL;
360 jsmntok_t *msrval = NULL;
361 jsmntok_t *precise = NULL;
362 jsmntok_t *obj = tok++;
364 EXPECT(obj->type == JSMN_OBJECT, obj, "expected object");
365 for (j = 0; j < obj->size; j += 2) {
366 jsmntok_t *field, *val;
370 EXPECT(field->type == JSMN_STRING, tok + j,
371 "Expected field name");
373 EXPECT(val->type == JSMN_STRING, tok + j + 1,
374 "Expected string value");
376 nz = !json_streq(map, val, "0");
377 if (match_field(map, field, nz, &event, val)) {
379 } else if (json_streq(map, field, "EventName")) {
380 addfield(map, &name, "", "", val);
381 } else if (json_streq(map, field, "BriefDescription")) {
382 addfield(map, &desc, "", "", val);
384 } else if (json_streq(map, field,
385 "PublicDescription")) {
386 addfield(map, &long_desc, "", "", val);
388 } else if (json_streq(map, field, "PEBS") && nz) {
390 } else if (json_streq(map, field, "MSRIndex") && nz) {
391 msr = lookup_msr(map, val);
392 } else if (json_streq(map, field, "MSRValue")) {
394 } else if (json_streq(map, field, "Errata") &&
395 !json_streq(map, val, "null")) {
396 addfield(map, &extra_desc, ". ",
397 " Spec update: ", val);
398 } else if (json_streq(map, field, "Data_LA") && nz) {
399 addfield(map, &extra_desc, ". ",
400 " Supports address when precise",
403 /* ignore unknown fields */
405 if (precise && desc && !strstr(desc, "(Precise Event)")) {
406 if (json_streq(map, precise, "2"))
407 addfield(map, &extra_desc, " ",
408 "(Must be precise)", NULL);
410 addfield(map, &extra_desc, " ",
411 "(Precise event)", NULL);
413 if (desc && extra_desc)
414 addfield(map, &desc, " ", extra_desc, NULL);
415 if (long_desc && extra_desc)
416 addfield(map, &long_desc, " ", extra_desc, NULL);
418 addfield(map, &event, ",", msr->pname, msrval);
421 err = func(data, name, real_event(name, event), desc, long_desc);
431 EXPECT(tok - tokens == len, tok, "unexpected objects at end");
434 free_json(map, size, tokens);
438 static char *file_name_to_table_name(char *fname)
446 * Ensure tablename starts with alphabetic character.
447 * Derive rest of table name from basename of the JSON file,
448 * replacing hyphens and stripping out .json suffix.
450 n = asprintf(&tblname, "pme_%s", basename(fname));
452 pr_info("%s: asprintf() error %s for file %s\n", prog,
453 strerror(errno), fname);
457 for (i = 0; i < strlen(tblname); i++) {
465 } else if (!isalnum(c) && c != '_') {
466 pr_err("%s: Invalid character '%c' in file name %s\n",
467 prog, c, basename(fname));
477 static void print_mapping_table_prefix(FILE *outfp)
479 fprintf(outfp, "struct pmu_events_map pmu_events_map[] = {\n");
482 static void print_mapping_table_suffix(FILE *outfp)
485 * Print the terminating, NULL entry.
487 fprintf(outfp, "{\n");
488 fprintf(outfp, "\t.cpuid = 0,\n");
489 fprintf(outfp, "\t.version = 0,\n");
490 fprintf(outfp, "\t.type = 0,\n");
491 fprintf(outfp, "\t.table = 0,\n");
492 fprintf(outfp, "},\n");
494 /* and finally, the closing curly bracket for the struct */
495 fprintf(outfp, "};\n");
498 static int process_mapfile(FILE *outfp, char *fpath)
507 pr_info("%s: Processing mapfile %s\n", prog, fpath);
513 mapfp = fopen(fpath, "r");
515 pr_info("%s: Error %s opening %s\n", prog, strerror(errno),
520 print_mapping_table_prefix(outfp);
522 /* Skip first line (header) */
523 p = fgets(line, n, mapfp);
529 char *cpuid, *version, *type, *fname;
532 p = fgets(line, n, mapfp);
536 if (line[0] == '#' || line[0] == '\n')
539 if (line[strlen(line)-1] != '\n') {
540 /* TODO Deal with lines longer than 16K */
541 pr_info("%s: Mapfile %s: line %d too long, aborting\n",
542 prog, fpath, line_num);
545 line[strlen(line)-1] = '\0';
547 cpuid = strtok_r(p, ",", &save);
548 version = strtok_r(NULL, ",", &save);
549 fname = strtok_r(NULL, ",", &save);
550 type = strtok_r(NULL, ",", &save);
552 tblname = file_name_to_table_name(fname);
553 fprintf(outfp, "{\n");
554 fprintf(outfp, "\t.cpuid = \"%s\",\n", cpuid);
555 fprintf(outfp, "\t.version = \"%s\",\n", version);
556 fprintf(outfp, "\t.type = \"%s\",\n", type);
559 * CHECK: We can't use the type (eg "core") field in the
560 * table name. For us to do that, we need to somehow tweak
561 * the other caller of file_name_to_table(), process_json()
562 * to determine the type. process_json() file has no way
563 * of knowing these are "core" events unless file name has
564 * core in it. If filename has core in it, we can safely
565 * ignore the type field here also.
567 fprintf(outfp, "\t.table = %s\n", tblname);
568 fprintf(outfp, "},\n");
572 print_mapping_table_suffix(outfp);
577 * If we fail to locate/process JSON and map files, create a NULL mapping
578 * table. This would at least allow perf to build even if we can't find/use
581 static void create_empty_mapping(const char *output_file)
585 pr_info("%s: Creating empty pmu_events_map[] table\n", prog);
587 /* Truncate file to clear any partial writes to it */
588 outfp = fopen(output_file, "w");
594 fprintf(outfp, "#include \"../../pmu-events/pmu-events.h\"\n");
595 print_mapping_table_prefix(outfp);
596 print_mapping_table_suffix(outfp);
600 static int get_maxfds(void)
604 if (getrlimit(RLIMIT_NOFILE, &rlim) == 0)
605 return min((int)rlim.rlim_max / 2, 512);
611 * nftw() doesn't let us pass an argument to the processing function,
612 * so use a global variables.
614 static FILE *eventsfp;
615 static char *mapfile;
617 static int process_one_file(const char *fpath, const struct stat *sb,
618 int typeflag, struct FTW *ftwbuf)
620 char *tblname, *bname = (char *) fpath + ftwbuf->base;
621 int is_dir = typeflag == FTW_D;
622 int is_file = typeflag == FTW_F;
623 int level = ftwbuf->level;
626 pr_debug("%s %d %7jd %-20s %s\n",
627 is_file ? "f" : is_dir ? "d" : "x",
628 level, sb->st_size, bname, fpath);
634 /* model directory, reset topic */
635 if (level == 1 && is_dir) {
637 print_events_table_suffix(eventsfp);
640 * Drop file name suffix. Replace hyphens with underscores.
641 * Fail if file name contains any alphanum characters besides
644 tblname = file_name_to_table_name(bname);
646 pr_info("%s: Error determining table name for %s\n", prog,
651 print_events_table_prefix(eventsfp, tblname);
656 * Save the mapfile name for now. We will process mapfile
657 * after processing all JSON files (so we can write out the
658 * mapping table after all PMU events tables).
660 * TODO: Allow for multiple mapfiles? Punt for now.
662 if (level == 1 && is_file) {
663 if (!strncmp(bname, "mapfile.csv", 11)) {
665 pr_info("%s: Many mapfiles? Using %s, ignoring %s\n",
666 prog, mapfile, fpath);
668 mapfile = strdup(fpath);
673 pr_info("%s: Ignoring file %s\n", prog, fpath);
678 * If the file name does not have a .json extension,
679 * ignore it. It could be a readme.txt for instance.
682 char *suffix = bname + strlen(bname) - 5;
684 if (strncmp(suffix, ".json", 5)) {
685 pr_info("%s: Ignoring file without .json suffix %s\n", prog,
691 if (level > 1 && add_topic(level, bname))
695 * Assume all other files are JSON files.
697 * If mapfile refers to 'power7_core.json', we create a table
698 * named 'power7_core'. Any inconsistencies between the mapfile
699 * and directory tree could result in build failure due to table
700 * names not being found.
702 * Atleast for now, be strict with processing JSON file names.
703 * i.e. if JSON file name cannot be mapped to C-style table name,
707 struct perf_entry_data data = {
708 .topic = get_topic(),
712 err = json_events(fpath, print_events_table_entry, &data);
721 #define PATH_MAX 4096
725 * Starting in directory 'start_dirname', find the "mapfile.csv" and
726 * the set of JSON files for the architecture 'arch'.
728 * From each JSON file, create a C-style "PMU events table" from the
729 * JSON file (see struct pmu_event).
731 * From the mapfile, create a mapping between the CPU revisions and
732 * PMU event tables (see struct pmu_events_map).
734 * Write out the PMU events tables and the mapping table to pmu-event.c.
736 * If unable to process the JSON or arch files, create an empty mapping
737 * table so we can continue to build/use perf even if we cannot use the
740 int main(int argc, char *argv[])
744 char ldirname[PATH_MAX];
747 const char *output_file;
748 const char *start_dirname;
750 prog = basename(argv[0]);
752 pr_err("Usage: %s <arch> <starting_dir> <output_file>\n", prog);
757 start_dirname = argv[2];
758 output_file = argv[3];
761 verbose = atoi(argv[4]);
763 eventsfp = fopen(output_file, "w");
765 pr_err("%s Unable to create required file %s (%s)\n",
766 prog, output_file, strerror(errno));
770 /* Include pmu-events.h first */
771 fprintf(eventsfp, "#include \"../../pmu-events/pmu-events.h\"\n");
773 sprintf(ldirname, "%s/%s", start_dirname, arch);
776 * The mapfile allows multiple CPUids to point to the same JSON file,
777 * so, not sure if there is a need for symlinks within the pmu-events
780 * For now, treat symlinks of JSON files as regular files and create
781 * separate tables for each symlink (presumably, each symlink refers
782 * to specific version of the CPU).
785 maxfds = get_maxfds();
787 rc = nftw(ldirname, process_one_file, maxfds, 0);
789 pr_info("%s: Error walking file tree %s\n", prog, ldirname);
796 print_events_table_suffix(eventsfp);
799 pr_info("%s: No CPU->JSON mapping?\n", prog);
803 if (process_mapfile(eventsfp, mapfile)) {
804 pr_info("%s: Error processing mapfile %s\n", prog, mapfile);
812 create_empty_mapping(output_file);