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 */
54 int eprintf(int level, int var, const char *fmt, ...)
65 ret = vfprintf(stderr, fmt, args);
72 __attribute__((weak)) char *get_cpu_str(void)
77 static void addfield(char *map, char **dst, const char *sep,
78 const char *a, jsmntok_t *bt)
80 unsigned int len = strlen(a) + 1 + strlen(sep);
81 int olen = *dst ? strlen(*dst) : 0;
82 int blen = bt ? json_len(bt) : 0;
85 out = realloc(*dst, len + olen + blen);
87 /* Don't add field in this case */
98 strncat(*dst, map + bt->start, blen);
101 static void fixname(char *s)
107 static void fixdesc(char *s)
109 char *e = s + strlen(s);
111 /* Remove trailing dots that look ugly in perf list */
113 while (e >= s && isspace(*e))
119 static struct msrmap {
123 { "0x3F6", "ldlat=" },
124 { "0x1A6", "offcore_rsp=" },
125 { "0x1A7", "offcore_rsp=" },
126 { "0x3F7", "frontend=" },
130 static struct field {
134 { "UMask", "umask=" },
135 { "CounterMask", "cmask=" },
136 { "Invert", "inv=" },
137 { "AnyThread", "any=" },
138 { "EdgeDetect", "edge=" },
139 { "SampleAfterValue", "period=" },
140 { "FCMask", "fc_mask=" },
141 { "PortMask", "ch_mask=" },
145 static void cut_comma(char *map, jsmntok_t *newval)
149 /* Cut off everything after comma */
150 for (i = newval->start; i < newval->end; i++) {
156 static int match_field(char *map, jsmntok_t *field, int nz,
157 char **event, jsmntok_t *val)
160 jsmntok_t newval = *val;
162 for (f = fields; f->field; f++)
163 if (json_streq(map, field, f->field) && nz) {
164 cut_comma(map, &newval);
165 addfield(map, event, ",", f->kernel, &newval);
171 static struct msrmap *lookup_msr(char *map, jsmntok_t *val)
173 jsmntok_t newval = *val;
177 cut_comma(map, &newval);
178 for (i = 0; msrmap[i].num; i++)
179 if (json_streq(map, &newval, msrmap[i].num))
183 pr_err("%s: Unknown MSR in event file %.*s\n", prog,
184 json_len(val), map + val->start);
193 { "CBO", "uncore_cbox" },
194 { "QPI LL", "uncore_qpi" },
195 { "SBO", "uncore_sbox" },
196 { "iMPH-U", "uncore_arb" },
200 static const char *field_to_perf(struct map *table, char *map, jsmntok_t *val)
204 for (i = 0; table[i].json; i++) {
205 if (json_streq(map, val, table[i].json))
206 return table[i].perf;
211 #define EXPECT(e, t, m) do { if (!(e)) { \
212 jsmntok_t *loc = (t); \
213 if (!(t)->start && (t) > tokens) \
215 pr_err("%s:%d: " m ", got %s\n", fn, \
216 json_line(map, loc), \
221 #define TOPIC_DEPTH 256
222 static char *topic_array[TOPIC_DEPTH];
223 static int topic_level;
225 static char *get_topic(void)
227 char *tp_old, *tp = NULL;
230 for (i = 0; i < topic_level + 1; i++) {
234 n = asprintf(&tp, "%s%s", tp ?: "", topic_array[i]);
236 pr_info("%s: asprintf() error %s\n", prog);
242 for (i = 0; i < (int) strlen(tp); i++) {
256 static int add_topic(int level, char *bname)
262 if (level >= TOPIC_DEPTH)
265 topic = strdup(bname);
267 pr_info("%s: strdup() error %s for file %s\n", prog,
268 strerror(errno), bname);
272 free(topic_array[topic_level]);
273 topic_array[topic_level] = topic;
278 struct perf_entry_data {
283 static int close_table;
285 static void print_events_table_prefix(FILE *fp, const char *tblname)
287 fprintf(fp, "struct pmu_event %s[] = {\n", tblname);
291 static int print_events_table_entry(void *data, char *name, char *event,
292 char *desc, char *long_desc,
293 char *pmu, char *unit, char *perpkg,
297 struct perf_entry_data *pd = data;
298 FILE *outfp = pd->outfp;
299 char *topic = pd->topic;
302 * TODO: Remove formatting chars after debugging to reduce
305 fprintf(outfp, "{\n");
307 fprintf(outfp, "\t.name = \"%s\",\n", name);
308 fprintf(outfp, "\t.event = \"%s\",\n", event);
309 fprintf(outfp, "\t.desc = \"%s\",\n", desc);
310 fprintf(outfp, "\t.topic = \"%s\",\n", topic);
311 if (long_desc && long_desc[0])
312 fprintf(outfp, "\t.long_desc = \"%s\",\n", long_desc);
314 fprintf(outfp, "\t.pmu = \"%s\",\n", pmu);
316 fprintf(outfp, "\t.unit = \"%s\",\n", unit);
318 fprintf(outfp, "\t.perpkg = \"%s\",\n", perpkg);
320 fprintf(outfp, "\t.metric_expr = \"%s\",\n", metric_expr);
322 fprintf(outfp, "\t.metric_name = \"%s\",\n", metric_name);
323 fprintf(outfp, "},\n");
328 static void print_events_table_suffix(FILE *outfp)
330 fprintf(outfp, "{\n");
332 fprintf(outfp, "\t.name = 0,\n");
333 fprintf(outfp, "\t.event = 0,\n");
334 fprintf(outfp, "\t.desc = 0,\n");
336 fprintf(outfp, "},\n");
337 fprintf(outfp, "};\n");
341 static struct fixed {
345 { "inst_retired.any", "event=0xc0,period=2000003" },
346 { "inst_retired.any_p", "event=0xc0,period=2000003" },
347 { "cpu_clk_unhalted.ref", "event=0x0,umask=0x03,period=2000003" },
348 { "cpu_clk_unhalted.thread", "event=0x3c,period=2000003" },
349 { "cpu_clk_unhalted.core", "event=0x3c,period=2000003" },
350 { "cpu_clk_unhalted.thread_any", "event=0x3c,any=1,period=2000003" },
355 * Handle different fixed counter encodings between JSON and perf.
357 static char *real_event(const char *name, char *event)
361 for (i = 0; fixed[i].name; i++)
362 if (!strcasecmp(name, fixed[i].name))
363 return (char *)fixed[i].event;
367 /* Call func with each event in the json file */
368 int json_events(const char *fn,
369 int (*func)(void *data, char *name, char *event, char *desc,
371 char *pmu, char *unit, char *perpkg,
378 jsmntok_t *tokens, *tok;
386 tokens = parse_json(fn, &map, &size, &len);
389 EXPECT(tokens->type == JSMN_ARRAY, tokens, "expected top level array");
391 for (i = 0; i < tokens->size; i++) {
392 char *event = NULL, *desc = NULL, *name = NULL;
393 char *long_desc = NULL;
394 char *extra_desc = NULL;
399 char *metric_expr = NULL;
400 char *metric_name = NULL;
401 unsigned long long eventcode = 0;
402 struct msrmap *msr = NULL;
403 jsmntok_t *msrval = NULL;
404 jsmntok_t *precise = NULL;
405 jsmntok_t *obj = tok++;
407 EXPECT(obj->type == JSMN_OBJECT, obj, "expected object");
408 for (j = 0; j < obj->size; j += 2) {
409 jsmntok_t *field, *val;
414 EXPECT(field->type == JSMN_STRING, tok + j,
415 "Expected field name");
417 EXPECT(val->type == JSMN_STRING, tok + j + 1,
418 "Expected string value");
420 nz = !json_streq(map, val, "0");
421 if (match_field(map, field, nz, &event, val)) {
423 } else if (json_streq(map, field, "EventCode")) {
425 addfield(map, &code, "", "", val);
426 eventcode |= strtoul(code, NULL, 0);
428 } else if (json_streq(map, field, "ExtSel")) {
430 addfield(map, &code, "", "", val);
431 eventcode |= strtoul(code, NULL, 0) << 8;
433 } else if (json_streq(map, field, "EventName")) {
434 addfield(map, &name, "", "", val);
435 } else if (json_streq(map, field, "BriefDescription")) {
436 addfield(map, &desc, "", "", val);
438 } else if (json_streq(map, field,
439 "PublicDescription")) {
440 addfield(map, &long_desc, "", "", val);
442 } else if (json_streq(map, field, "PEBS") && nz) {
444 } else if (json_streq(map, field, "MSRIndex") && nz) {
445 msr = lookup_msr(map, val);
446 } else if (json_streq(map, field, "MSRValue")) {
448 } else if (json_streq(map, field, "Errata") &&
449 !json_streq(map, val, "null")) {
450 addfield(map, &extra_desc, ". ",
451 " Spec update: ", val);
452 } else if (json_streq(map, field, "Data_LA") && nz) {
453 addfield(map, &extra_desc, ". ",
454 " Supports address when precise",
456 } else if (json_streq(map, field, "Unit")) {
459 ppmu = field_to_perf(unit_to_pmu, map, val);
464 pmu = strdup("uncore_");
465 addfield(map, &pmu, "", "", val);
466 for (s = pmu; *s; s++)
469 addfield(map, &desc, ". ", "Unit: ", NULL);
470 addfield(map, &desc, "", pmu, NULL);
471 addfield(map, &desc, "", " ", NULL);
472 } else if (json_streq(map, field, "Filter")) {
473 addfield(map, &filter, "", "", val);
474 } else if (json_streq(map, field, "ScaleUnit")) {
475 addfield(map, &unit, "", "", val);
476 } else if (json_streq(map, field, "PerPkg")) {
477 addfield(map, &perpkg, "", "", val);
478 } else if (json_streq(map, field, "MetricName")) {
479 addfield(map, &metric_name, "", "", val);
480 } else if (json_streq(map, field, "MetricExpr")) {
481 addfield(map, &metric_expr, "", "", val);
482 for (s = metric_expr; *s; s++)
485 /* ignore unknown fields */
487 if (precise && desc && !strstr(desc, "(Precise Event)")) {
488 if (json_streq(map, precise, "2"))
489 addfield(map, &extra_desc, " ",
490 "(Must be precise)", NULL);
492 addfield(map, &extra_desc, " ",
493 "(Precise event)", NULL);
495 snprintf(buf, sizeof buf, "event=%#llx", eventcode);
496 addfield(map, &event, ",", buf, NULL);
497 if (desc && extra_desc)
498 addfield(map, &desc, " ", extra_desc, NULL);
499 if (long_desc && extra_desc)
500 addfield(map, &long_desc, " ", extra_desc, NULL);
502 addfield(map, &event, ",", filter, NULL);
504 addfield(map, &event, ",", msr->pname, msrval);
507 err = func(data, name, real_event(name, event), desc, long_desc,
508 pmu, unit, perpkg, metric_expr, metric_name);
524 EXPECT(tok - tokens == len, tok, "unexpected objects at end");
527 free_json(map, size, tokens);
531 static char *file_name_to_table_name(char *fname)
539 * Ensure tablename starts with alphabetic character.
540 * Derive rest of table name from basename of the JSON file,
541 * replacing hyphens and stripping out .json suffix.
543 n = asprintf(&tblname, "pme_%s", basename(fname));
545 pr_info("%s: asprintf() error %s for file %s\n", prog,
546 strerror(errno), fname);
550 for (i = 0; i < strlen(tblname); i++) {
558 } else if (!isalnum(c) && c != '_') {
559 pr_err("%s: Invalid character '%c' in file name %s\n",
560 prog, c, basename(fname));
570 static void print_mapping_table_prefix(FILE *outfp)
572 fprintf(outfp, "struct pmu_events_map pmu_events_map[] = {\n");
575 static void print_mapping_table_suffix(FILE *outfp)
578 * Print the terminating, NULL entry.
580 fprintf(outfp, "{\n");
581 fprintf(outfp, "\t.cpuid = 0,\n");
582 fprintf(outfp, "\t.version = 0,\n");
583 fprintf(outfp, "\t.type = 0,\n");
584 fprintf(outfp, "\t.table = 0,\n");
585 fprintf(outfp, "},\n");
587 /* and finally, the closing curly bracket for the struct */
588 fprintf(outfp, "};\n");
591 static int process_mapfile(FILE *outfp, char *fpath)
600 pr_info("%s: Processing mapfile %s\n", prog, fpath);
606 mapfp = fopen(fpath, "r");
608 pr_info("%s: Error %s opening %s\n", prog, strerror(errno),
613 print_mapping_table_prefix(outfp);
615 /* Skip first line (header) */
616 p = fgets(line, n, mapfp);
622 char *cpuid, *version, *type, *fname;
625 p = fgets(line, n, mapfp);
629 if (line[0] == '#' || line[0] == '\n')
632 if (line[strlen(line)-1] != '\n') {
633 /* TODO Deal with lines longer than 16K */
634 pr_info("%s: Mapfile %s: line %d too long, aborting\n",
635 prog, fpath, line_num);
638 line[strlen(line)-1] = '\0';
640 cpuid = strtok_r(p, ",", &save);
641 version = strtok_r(NULL, ",", &save);
642 fname = strtok_r(NULL, ",", &save);
643 type = strtok_r(NULL, ",", &save);
645 tblname = file_name_to_table_name(fname);
646 fprintf(outfp, "{\n");
647 fprintf(outfp, "\t.cpuid = \"%s\",\n", cpuid);
648 fprintf(outfp, "\t.version = \"%s\",\n", version);
649 fprintf(outfp, "\t.type = \"%s\",\n", type);
652 * CHECK: We can't use the type (eg "core") field in the
653 * table name. For us to do that, we need to somehow tweak
654 * the other caller of file_name_to_table(), process_json()
655 * to determine the type. process_json() file has no way
656 * of knowing these are "core" events unless file name has
657 * core in it. If filename has core in it, we can safely
658 * ignore the type field here also.
660 fprintf(outfp, "\t.table = %s\n", tblname);
661 fprintf(outfp, "},\n");
665 print_mapping_table_suffix(outfp);
670 * If we fail to locate/process JSON and map files, create a NULL mapping
671 * table. This would at least allow perf to build even if we can't find/use
674 static void create_empty_mapping(const char *output_file)
678 pr_info("%s: Creating empty pmu_events_map[] table\n", prog);
680 /* Truncate file to clear any partial writes to it */
681 outfp = fopen(output_file, "w");
687 fprintf(outfp, "#include \"../../pmu-events/pmu-events.h\"\n");
688 print_mapping_table_prefix(outfp);
689 print_mapping_table_suffix(outfp);
693 static int get_maxfds(void)
697 if (getrlimit(RLIMIT_NOFILE, &rlim) == 0)
698 return min(rlim.rlim_max / 2, (rlim_t)512);
704 * nftw() doesn't let us pass an argument to the processing function,
705 * so use a global variables.
707 static FILE *eventsfp;
708 static char *mapfile;
710 static int process_one_file(const char *fpath, const struct stat *sb,
711 int typeflag, struct FTW *ftwbuf)
713 char *tblname, *bname = (char *) fpath + ftwbuf->base;
714 int is_dir = typeflag == FTW_D;
715 int is_file = typeflag == FTW_F;
716 int level = ftwbuf->level;
719 pr_debug("%s %d %7jd %-20s %s\n",
720 is_file ? "f" : is_dir ? "d" : "x",
721 level, sb->st_size, bname, fpath);
727 /* model directory, reset topic */
728 if (level == 1 && is_dir) {
730 print_events_table_suffix(eventsfp);
733 * Drop file name suffix. Replace hyphens with underscores.
734 * Fail if file name contains any alphanum characters besides
737 tblname = file_name_to_table_name(bname);
739 pr_info("%s: Error determining table name for %s\n", prog,
744 print_events_table_prefix(eventsfp, tblname);
749 * Save the mapfile name for now. We will process mapfile
750 * after processing all JSON files (so we can write out the
751 * mapping table after all PMU events tables).
753 * TODO: Allow for multiple mapfiles? Punt for now.
755 if (level == 1 && is_file) {
756 if (!strncmp(bname, "mapfile.csv", 11)) {
758 pr_info("%s: Many mapfiles? Using %s, ignoring %s\n",
759 prog, mapfile, fpath);
761 mapfile = strdup(fpath);
766 pr_info("%s: Ignoring file %s\n", prog, fpath);
771 * If the file name does not have a .json extension,
772 * ignore it. It could be a readme.txt for instance.
775 char *suffix = bname + strlen(bname) - 5;
777 if (strncmp(suffix, ".json", 5)) {
778 pr_info("%s: Ignoring file without .json suffix %s\n", prog,
784 if (level > 1 && add_topic(level, bname))
788 * Assume all other files are JSON files.
790 * If mapfile refers to 'power7_core.json', we create a table
791 * named 'power7_core'. Any inconsistencies between the mapfile
792 * and directory tree could result in build failure due to table
793 * names not being found.
795 * Atleast for now, be strict with processing JSON file names.
796 * i.e. if JSON file name cannot be mapped to C-style table name,
800 struct perf_entry_data data = {
801 .topic = get_topic(),
805 err = json_events(fpath, print_events_table_entry, &data);
814 #define PATH_MAX 4096
818 * Starting in directory 'start_dirname', find the "mapfile.csv" and
819 * the set of JSON files for the architecture 'arch'.
821 * From each JSON file, create a C-style "PMU events table" from the
822 * JSON file (see struct pmu_event).
824 * From the mapfile, create a mapping between the CPU revisions and
825 * PMU event tables (see struct pmu_events_map).
827 * Write out the PMU events tables and the mapping table to pmu-event.c.
829 int main(int argc, char *argv[])
833 char ldirname[PATH_MAX];
836 const char *output_file;
837 const char *start_dirname;
840 prog = basename(argv[0]);
842 pr_err("Usage: %s <arch> <starting_dir> <output_file>\n", prog);
847 start_dirname = argv[2];
848 output_file = argv[3];
851 verbose = atoi(argv[4]);
853 eventsfp = fopen(output_file, "w");
855 pr_err("%s Unable to create required file %s (%s)\n",
856 prog, output_file, strerror(errno));
860 sprintf(ldirname, "%s/%s", start_dirname, arch);
862 /* If architecture does not have any event lists, bail out */
863 if (stat(ldirname, &stbuf) < 0) {
864 pr_info("%s: Arch %s has no PMU event lists\n", prog, arch);
868 /* Include pmu-events.h first */
869 fprintf(eventsfp, "#include \"../../pmu-events/pmu-events.h\"\n");
872 * The mapfile allows multiple CPUids to point to the same JSON file,
873 * so, not sure if there is a need for symlinks within the pmu-events
876 * For now, treat symlinks of JSON files as regular files and create
877 * separate tables for each symlink (presumably, each symlink refers
878 * to specific version of the CPU).
881 maxfds = get_maxfds();
883 rc = nftw(ldirname, process_one_file, maxfds, 0);
885 pr_info("%s: Error walking file tree %s\n", prog, ldirname);
888 /* Make build fail */
895 print_events_table_suffix(eventsfp);
898 pr_info("%s: No CPU->JSON mapping?\n", prog);
902 if (process_mapfile(eventsfp, mapfile)) {
903 pr_info("%s: Error processing mapfile %s\n", prog, mapfile);
904 /* Make build fail */
912 create_empty_mapping(output_file);