1 /* Parse event JSON files */
4 * Copyright (c) 2014, Intel Corporation
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions are met:
10 * 1. Redistributions of source code must retain the above copyright notice,
11 * this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
17 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
20 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
21 * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
22 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
23 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
24 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
25 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
26 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
27 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
28 * OF THE POSSIBILITY OF SUCH DAMAGE.
31 #include <sys/param.h>
32 #include <sys/resource.h> /* getrlimit */
34 #include <sys/time.h> /* getrlimit */
50 #include "pmu-events.h"
53 nftw_ordered(const char *path, int (*fn)(const char *, const struct stat *, int,
54 struct FTW *), int nfds, int ftwflags);
55 #define nftw nftw_ordered
57 _Noreturn void _Exit(int);
58 char *get_cpu_str(void);
77 char *metric_constraint;
80 static enum aggr_mode_class convert(const char *aggr_mode)
82 if (!strcmp(aggr_mode, "PerCore"))
84 else if (!strcmp(aggr_mode, "PerChip"))
87 pr_err("%s: Wrong AggregationMode value '%s'\n", prog, aggr_mode);
91 static LIST_HEAD(sys_event_tables);
93 struct sys_event_table {
94 struct list_head list;
98 static void free_sys_event_tables(void)
100 struct sys_event_table *et, *next;
102 list_for_each_entry_safe(et, next, &sys_event_tables, list) {
108 int eprintf(int level, int var, const char *fmt, ...)
119 ret = vfprintf(stderr, fmt, args);
126 static void addfield(char *map, char **dst, const char *sep,
127 const char *a, jsmntok_t *bt)
129 unsigned int len = strlen(a) + 1 + strlen(sep);
130 int olen = *dst ? strlen(*dst) : 0;
131 int blen = bt ? json_len(bt) : 0;
134 out = realloc(*dst, len + olen + blen);
136 /* Don't add field in this case */
147 strncat(*dst, map + bt->start, blen);
150 static void fixname(char *s)
156 static void fixdesc(char *s)
158 char *e = s + strlen(s);
160 /* Remove trailing dots that look ugly in perf list */
162 while (e >= s && isspace(*e))
164 if (e >= s && *e == '.')
168 /* Add escapes for '\' so they are proper C strings. */
169 static char *fixregex(char *s)
176 /* Count the number of '\' in string */
177 for (p = s; *p; p++) {
186 /* allocate space for a new string */
187 fixed = (char *) malloc(len + esc_count + 1);
191 /* copy over the characters */
193 for (p = s; *p; p++) {
205 static struct msrmap {
209 { "0x3F6", "ldlat=" },
210 { "0x1A6", "offcore_rsp=" },
211 { "0x1A7", "offcore_rsp=" },
212 { "0x3F7", "frontend=" },
216 static void cut_comma(char *map, jsmntok_t *newval)
220 /* Cut off everything after comma */
221 for (i = newval->start; i < newval->end; i++) {
227 static struct msrmap *lookup_msr(char *map, jsmntok_t *val)
229 jsmntok_t newval = *val;
233 cut_comma(map, &newval);
234 for (i = 0; msrmap[i].num; i++)
235 if (json_streq(map, &newval, msrmap[i].num))
239 pr_err("%s: Unknown MSR in event file %.*s\n", prog,
240 json_len(val), map + val->start);
249 { "CBO", "uncore_cbox" },
250 { "QPI LL", "uncore_qpi" },
251 { "SBO", "uncore_sbox" },
252 { "iMPH-U", "uncore_arb" },
253 { "CPU-M-CF", "cpum_cf" },
254 { "CPU-M-SF", "cpum_sf" },
255 { "UPI LL", "uncore_upi" },
256 { "hisi_sicl,cpa", "hisi_sicl,cpa"},
257 { "hisi_sccl,ddrc", "hisi_sccl,ddrc" },
258 { "hisi_sccl,hha", "hisi_sccl,hha" },
259 { "hisi_sccl,l3c", "hisi_sccl,l3c" },
260 /* it's not realistic to keep adding these, we need something more scalable ... */
261 { "imx8_ddr", "imx8_ddr" },
262 { "L3PMC", "amd_l3" },
263 { "DFPMC", "amd_df" },
264 { "cpu_core", "cpu_core" },
265 { "cpu_atom", "cpu_atom" },
269 static const char *field_to_perf(struct map *table, char *map, jsmntok_t *val)
273 for (i = 0; table[i].json; i++) {
274 if (json_streq(map, val, table[i].json))
275 return table[i].perf;
280 #define EXPECT(e, t, m) do { if (!(e)) { \
281 jsmntok_t *loc = (t); \
282 if (!(t)->start && (t) > tokens) \
284 pr_err("%s:%d: " m ", got %s\n", fn, \
285 json_line(map, loc), \
293 static char *get_topic(void)
298 /* tp is free'd in process_one_file() */
299 i = asprintf(&tp, "%s", topic);
301 pr_info("%s: asprintf() error %s\n", prog);
305 for (i = 0; i < (int) strlen(tp); i++) {
319 static int add_topic(char *bname)
322 topic = strdup(bname);
324 pr_info("%s: strdup() error %s for file %s\n", prog,
325 strerror(errno), bname);
331 struct perf_entry_data {
336 static int close_table;
338 static void print_events_table_prefix(FILE *fp, const char *tblname)
340 fprintf(fp, "static const struct pmu_event %s[] = {\n", tblname);
344 static int print_events_table_entry(void *data, struct json_event *je)
346 struct perf_entry_data *pd = data;
347 FILE *outfp = pd->outfp;
348 char *topic_local = pd->topic;
351 * TODO: Remove formatting chars after debugging to reduce
354 fprintf(outfp, "{\n");
357 fprintf(outfp, "\t.name = \"%s\",\n", je->name);
359 fprintf(outfp, "\t.event = \"%s\",\n", je->event);
360 fprintf(outfp, "\t.desc = \"%s\",\n", je->desc);
362 fprintf(outfp, "\t.compat = \"%s\",\n", je->compat);
363 fprintf(outfp, "\t.topic = \"%s\",\n", topic_local);
364 if (je->long_desc && je->long_desc[0])
365 fprintf(outfp, "\t.long_desc = \"%s\",\n", je->long_desc);
367 fprintf(outfp, "\t.pmu = \"%s\",\n", je->pmu);
369 fprintf(outfp, "\t.unit = \"%s\",\n", je->unit);
371 fprintf(outfp, "\t.perpkg = \"%s\",\n", je->perpkg);
373 fprintf(outfp, "\t.aggr_mode = \"%d\",\n", convert(je->aggr_mode));
375 fprintf(outfp, "\t.metric_expr = \"%s\",\n", je->metric_expr);
377 fprintf(outfp, "\t.metric_name = \"%s\",\n", je->metric_name);
378 if (je->metric_group)
379 fprintf(outfp, "\t.metric_group = \"%s\",\n", je->metric_group);
381 fprintf(outfp, "\t.deprecated = \"%s\",\n", je->deprecated);
382 if (je->metric_constraint)
383 fprintf(outfp, "\t.metric_constraint = \"%s\",\n", je->metric_constraint);
384 fprintf(outfp, "},\n");
389 struct event_struct {
390 struct list_head list;
404 char *metric_constraint;
407 #define ADD_EVENT_FIELD(field) do { if (je->field) { \
408 es->field = strdup(je->field); \
413 #define FREE_EVENT_FIELD(field) free(es->field)
415 #define TRY_FIXUP_FIELD(field) do { if (es->field && !je->field) {\
416 je->field = strdup(es->field); \
421 #define FOR_ALL_EVENT_STRUCT_FIELDS(op) do { \
436 static LIST_HEAD(arch_std_events);
438 static void free_arch_std_events(void)
440 struct event_struct *es, *next;
442 list_for_each_entry_safe(es, next, &arch_std_events, list) {
443 FOR_ALL_EVENT_STRUCT_FIELDS(FREE_EVENT_FIELD);
444 list_del_init(&es->list);
449 static int save_arch_std_events(void *data __unused, struct json_event *je)
451 struct event_struct *es;
453 es = malloc(sizeof(*es));
456 memset(es, 0, sizeof(*es));
457 FOR_ALL_EVENT_STRUCT_FIELDS(ADD_EVENT_FIELD);
458 list_add_tail(&es->list, &arch_std_events);
461 FOR_ALL_EVENT_STRUCT_FIELDS(FREE_EVENT_FIELD);
466 static void print_events_table_suffix(FILE *outfp)
468 fprintf(outfp, "{\n");
470 fprintf(outfp, "\t.name = 0,\n");
471 fprintf(outfp, "\t.event = 0,\n");
472 fprintf(outfp, "\t.desc = 0,\n");
474 fprintf(outfp, "},\n");
475 fprintf(outfp, "};\n");
479 static struct fixed {
483 { "inst_retired.any", "event=0xc0,period=2000003" },
484 { "inst_retired.any_p", "event=0xc0,period=2000003" },
485 { "cpu_clk_unhalted.ref", "event=0x0,umask=0x03,period=2000003" },
486 { "cpu_clk_unhalted.thread", "event=0x3c,period=2000003" },
487 { "cpu_clk_unhalted.core", "event=0x3c,period=2000003" },
488 { "cpu_clk_unhalted.thread_any", "event=0x3c,any=1,period=2000003" },
493 * Handle different fixed counter encodings between JSON and perf.
495 static char *real_event(const char *name, char *event)
502 for (i = 0; fixed[i].name; i++)
503 if (!strcasecmp(name, fixed[i].name))
504 return (char *)fixed[i].event;
509 try_fixup(const char *fn, char *arch_std, struct json_event *je, char **event)
511 /* try to find matching event from arch standard values */
512 struct event_struct *es;
514 list_for_each_entry(es, &arch_std_events, list) {
515 if (!strcmp(arch_std, es->name)) {
516 FOR_ALL_EVENT_STRUCT_FIELDS(TRY_FIXUP_FIELD);
522 pr_err("%s: could not find matching %s for %s\n",
527 /* Call func with each event in the json file */
528 static int json_events(const char *fn,
529 int (*func)(void *data, struct json_event *je),
534 jsmntok_t *tokens, *tok;
542 tokens = parse_json(fn, &map, &size, &len);
545 EXPECT(tokens->type == JSMN_ARRAY, tokens, "expected top level array");
547 for (i = 0; i < tokens->size; i++) {
549 char *extra_desc = NULL;
551 struct json_event je = {};
552 char *arch_std = NULL;
553 unsigned long long eventcode = 0;
554 unsigned long long configcode = 0;
555 struct msrmap *msr = NULL;
556 jsmntok_t *msrval = NULL;
557 jsmntok_t *precise = NULL;
558 jsmntok_t *obj = tok++;
559 bool configcode_present = false;
566 char *fc_mask = NULL;
567 char *ch_mask = NULL;
569 EXPECT(obj->type == JSMN_OBJECT, obj, "expected object");
570 for (j = 0; j < obj->size; j += 2) {
571 jsmntok_t *field, *val;
576 EXPECT(field->type == JSMN_STRING, tok + j,
577 "Expected field name");
579 EXPECT(val->type == JSMN_STRING, tok + j + 1,
580 "Expected string value");
582 nz = !json_streq(map, val, "0");
584 if (json_streq(map, field, "UMask") && nz) {
585 addfield(map, &umask, "", "umask=", val);
586 } else if (json_streq(map, field, "CounterMask") && nz) {
587 addfield(map, &cmask, "", "cmask=", val);
588 } else if (json_streq(map, field, "Invert") && nz) {
589 addfield(map, &inv, "", "inv=", val);
590 } else if (json_streq(map, field, "AnyThread") && nz) {
591 addfield(map, &any, "", "any=", val);
592 } else if (json_streq(map, field, "EdgeDetect") && nz) {
593 addfield(map, &edge, "", "edge=", val);
594 } else if (json_streq(map, field, "SampleAfterValue") && nz) {
595 addfield(map, &period, "", "period=", val);
596 } else if (json_streq(map, field, "FCMask") && nz) {
597 addfield(map, &fc_mask, "", "fc_mask=", val);
598 } else if (json_streq(map, field, "PortMask") && nz) {
599 addfield(map, &ch_mask, "", "ch_mask=", val);
600 } else if (json_streq(map, field, "EventCode")) {
602 addfield(map, &code, "", "", val);
603 eventcode |= strtoul(code, NULL, 0);
605 } else if (json_streq(map, field, "ConfigCode")) {
607 addfield(map, &code, "", "", val);
608 configcode |= strtoul(code, NULL, 0);
610 configcode_present = true;
611 } else if (json_streq(map, field, "ExtSel")) {
613 addfield(map, &code, "", "", val);
614 eventcode |= strtoul(code, NULL, 0) << 8;
616 } else if (json_streq(map, field, "EventName")) {
617 addfield(map, &je.name, "", "", val);
618 } else if (json_streq(map, field, "Compat")) {
619 addfield(map, &je.compat, "", "", val);
620 } else if (json_streq(map, field, "BriefDescription")) {
621 addfield(map, &je.desc, "", "", val);
623 } else if (json_streq(map, field,
624 "PublicDescription")) {
625 addfield(map, &je.long_desc, "", "", val);
626 fixdesc(je.long_desc);
627 } else if (json_streq(map, field, "PEBS") && nz) {
629 } else if (json_streq(map, field, "MSRIndex") && nz) {
630 msr = lookup_msr(map, val);
631 } else if (json_streq(map, field, "MSRValue")) {
633 } else if (json_streq(map, field, "Errata") &&
634 !json_streq(map, val, "null")) {
635 addfield(map, &extra_desc, ". ",
636 " Spec update: ", val);
637 } else if (json_streq(map, field, "Data_LA") && nz) {
638 addfield(map, &extra_desc, ". ",
639 " Supports address when precise",
641 } else if (json_streq(map, field, "Unit")) {
644 ppmu = field_to_perf(unit_to_pmu, map, val);
646 je.pmu = strdup(ppmu);
649 je.pmu = strdup("uncore_");
650 addfield(map, &je.pmu, "", "", val);
651 for (s = je.pmu; *s; s++)
654 } else if (json_streq(map, field, "Filter")) {
655 addfield(map, &filter, "", "", val);
656 } else if (json_streq(map, field, "ScaleUnit")) {
657 addfield(map, &je.unit, "", "", val);
658 } else if (json_streq(map, field, "PerPkg")) {
659 addfield(map, &je.perpkg, "", "", val);
660 } else if (json_streq(map, field, "AggregationMode")) {
661 addfield(map, &je.aggr_mode, "", "", val);
662 } else if (json_streq(map, field, "Deprecated")) {
663 addfield(map, &je.deprecated, "", "", val);
664 } else if (json_streq(map, field, "MetricName")) {
665 addfield(map, &je.metric_name, "", "", val);
666 } else if (json_streq(map, field, "MetricGroup")) {
667 addfield(map, &je.metric_group, "", "", val);
668 } else if (json_streq(map, field, "MetricConstraint")) {
669 addfield(map, &je.metric_constraint, "", "", val);
670 } else if (json_streq(map, field, "MetricExpr")) {
671 addfield(map, &je.metric_expr, "", "", val);
672 } else if (json_streq(map, field, "ArchStdEvent")) {
673 addfield(map, &arch_std, "", "", val);
674 for (s = arch_std; *s; s++)
677 /* ignore unknown fields */
679 if (precise && je.desc && !strstr(je.desc, "(Precise Event)")) {
680 if (json_streq(map, precise, "2"))
681 addfield(map, &extra_desc, " ",
682 "(Must be precise)", NULL);
684 addfield(map, &extra_desc, " ",
685 "(Precise event)", NULL);
687 if (configcode_present)
688 snprintf(buf, sizeof buf, "config=%#llx", configcode);
690 snprintf(buf, sizeof buf, "event=%#llx", eventcode);
691 addfield(map, &event, ",", buf, NULL);
693 addfield(map, &event, ",", any, NULL);
695 addfield(map, &event, ",", ch_mask, NULL);
697 addfield(map, &event, ",", cmask, NULL);
699 addfield(map, &event, ",", edge, NULL);
701 addfield(map, &event, ",", fc_mask, NULL);
703 addfield(map, &event, ",", inv, NULL);
705 addfield(map, &event, ",", period, NULL);
707 addfield(map, &event, ",", umask, NULL);
709 if (je.desc && extra_desc)
710 addfield(map, &je.desc, " ", extra_desc, NULL);
711 if (je.long_desc && extra_desc)
712 addfield(map, &je.long_desc, " ", extra_desc, NULL);
714 addfield(map, &je.desc, ". ", "Unit: ", NULL);
715 addfield(map, &je.desc, "", je.pmu, NULL);
716 addfield(map, &je.desc, "", " ", NULL);
719 addfield(map, &event, ",", filter, NULL);
721 addfield(map, &event, ",", msr->pname, msrval);
727 * An arch standard event is referenced, so try to
728 * fixup any unassigned values.
730 err = try_fixup(fn, arch_std, &je, &event);
734 je.event = real_event(je.name, event);
735 err = func(data, &je);
757 free(je.metric_expr);
758 free(je.metric_name);
759 free(je.metric_group);
760 free(je.metric_constraint);
767 EXPECT(tok - tokens == len, tok, "unexpected objects at end");
770 free_json(map, size, tokens);
774 static char *file_name_to_table_name(char *fname)
782 * Ensure tablename starts with alphabetic character.
783 * Derive rest of table name from basename of the JSON file,
784 * replacing hyphens and stripping out .json suffix.
786 n = asprintf(&tblname, "pme_%s", fname);
788 pr_info("%s: asprintf() error %s for file %s\n", prog,
789 strerror(errno), fname);
793 for (i = 0; i < strlen(tblname); i++) {
796 if (c == '-' || c == '/')
801 } else if (!isalnum(c) && c != '_') {
802 pr_err("%s: Invalid character '%c' in file name '%s'\n",
813 static bool is_sys_dir(char *fname)
815 size_t len = strlen(fname), len2 = strlen("/sys");
819 return !strcmp(fname+len-len2, "/sys");
822 static void print_mapping_table_prefix(FILE *outfp)
824 fprintf(outfp, "const struct pmu_events_map pmu_events_map[] = {\n");
827 static void print_mapping_table_suffix(FILE *outfp)
830 * Print the terminating, NULL entry.
832 fprintf(outfp, "{\n");
833 fprintf(outfp, "\t.cpuid = 0,\n");
834 fprintf(outfp, "\t.version = 0,\n");
835 fprintf(outfp, "\t.type = 0,\n");
836 fprintf(outfp, "\t.table = 0,\n");
837 fprintf(outfp, "},\n");
839 /* and finally, the closing curly bracket for the struct */
840 fprintf(outfp, "};\n");
843 static void print_mapping_test_table(FILE *outfp)
846 * Print the terminating, NULL entry.
848 fprintf(outfp, "{\n");
849 fprintf(outfp, "\t.cpuid = \"testcpu\",\n");
850 fprintf(outfp, "\t.version = \"v1\",\n");
851 fprintf(outfp, "\t.type = \"core\",\n");
852 fprintf(outfp, "\t.table = pme_test_soc_cpu,\n");
853 fprintf(outfp, "},\n");
856 static void print_system_event_mapping_table_prefix(FILE *outfp)
858 fprintf(outfp, "\nconst struct pmu_sys_events pmu_sys_event_tables[] = {");
861 static void print_system_event_mapping_table_suffix(FILE *outfp)
863 fprintf(outfp, "\n\t{\n\t\t.table = 0\n\t},");
864 fprintf(outfp, "\n};\n");
867 static int process_system_event_tables(FILE *outfp)
869 struct sys_event_table *sys_event_table;
871 print_system_event_mapping_table_prefix(outfp);
873 list_for_each_entry(sys_event_table, &sys_event_tables, list) {
874 fprintf(outfp, "\n\t{\n\t\t.table = %s,\n\t\t.name = \"%s\",\n\t},",
875 sys_event_table->soc_id,
876 sys_event_table->soc_id);
879 print_system_event_mapping_table_suffix(outfp);
884 static int process_mapfile(FILE *outfp, char *fpath)
894 pr_info("%s: Processing mapfile %s\n", prog, fpath);
900 mapfp = fopen(fpath, "r");
902 pr_info("%s: Error %s opening %s\n", prog, strerror(errno),
908 print_mapping_table_prefix(outfp);
910 /* Skip first line (header) */
911 p = fgets(line, n, mapfp);
917 char *cpuid, *version, *type, *fname;
920 p = fgets(line, n, mapfp);
924 if (line[0] == '#' || line[0] == '\n')
927 if (line[strlen(line)-1] != '\n') {
928 /* TODO Deal with lines longer than 16K */
929 pr_info("%s: Mapfile %s: line %d too long, aborting\n",
930 prog, fpath, line_num);
934 line[strlen(line)-1] = '\0';
936 cpuid = fixregex(strtok_r(p, ",", &save));
937 version = strtok_r(NULL, ",", &save);
938 fname = strtok_r(NULL, ",", &save);
939 type = strtok_r(NULL, ",", &save);
941 tblname = file_name_to_table_name(fname);
942 fprintf(outfp, "{\n");
943 fprintf(outfp, "\t.cpuid = \"%s\",\n", cpuid);
944 fprintf(outfp, "\t.version = \"%s\",\n", version);
945 fprintf(outfp, "\t.type = \"%s\",\n", type);
948 * CHECK: We can't use the type (eg "core") field in the
949 * table name. For us to do that, we need to somehow tweak
950 * the other caller of file_name_to_table(), process_json()
951 * to determine the type. process_json() file has no way
952 * of knowing these are "core" events unless file name has
953 * core in it. If filename has core in it, we can safely
954 * ignore the type field here also.
956 fprintf(outfp, "\t.table = %s\n", tblname);
957 fprintf(outfp, "},\n");
961 print_mapping_test_table(outfp);
962 print_mapping_table_suffix(outfp);
969 * If we fail to locate/process JSON and map files, create a NULL mapping
970 * table. This would at least allow perf to build even if we can't find/use
973 static void create_empty_mapping(const char *output_file)
977 pr_info("%s: Creating empty pmu_events_map[] table\n", prog);
979 /* Truncate file to clear any partial writes to it */
980 outfp = fopen(output_file, "w");
986 fprintf(outfp, "#include \"pmu-events/pmu-events.h\"\n");
987 print_mapping_table_prefix(outfp);
988 print_mapping_table_suffix(outfp);
989 print_system_event_mapping_table_prefix(outfp);
990 print_system_event_mapping_table_suffix(outfp);
994 static int get_maxfds(void)
998 if (getrlimit(RLIMIT_NOFILE, &rlim) == 0) {
999 if (rlim.rlim_max == RLIM_INFINITY)
1001 return MIN(rlim.rlim_max / 2, 512);
1008 * nftw() doesn't let us pass an argument to the processing function,
1009 * so use a global variables.
1011 static FILE *eventsfp;
1012 static char *mapfile;
1014 static int is_leaf_dir(const char *fpath)
1024 while ((dir = readdir(d)) != NULL) {
1025 if (!strcmp(dir->d_name, ".") || !strcmp(dir->d_name, ".."))
1028 if (dir->d_type == DT_DIR) {
1031 } else if (dir->d_type == DT_UNKNOWN) {
1032 char path[PATH_MAX];
1035 snprintf(path, sizeof(path), "%s/%s", fpath, dir->d_name);
1036 if (stat(path, &st))
1039 if (S_ISDIR(st.st_mode)) {
1051 static int is_json_file(const char *name)
1055 if (strlen(name) < 5)
1058 suffix = name + strlen(name) - 5;
1060 if (strncmp(suffix, ".json", 5) == 0)
1065 static int preprocess_arch_std_files(const char *fpath, const struct stat *sb,
1066 int typeflag, struct FTW *ftwbuf)
1068 int level = ftwbuf->level;
1069 int is_file = typeflag == FTW_F;
1071 if (level == 1 && is_file && is_json_file(fpath))
1072 return json_events(fpath, save_arch_std_events, (void *)(uintptr_t)sb);
1077 static int process_one_file(const char *fpath, const struct stat *sb,
1078 int typeflag, struct FTW *ftwbuf)
1080 char *tblname, *bname;
1081 int is_dir = typeflag == FTW_D;
1082 int is_file = typeflag == FTW_F;
1083 int level = ftwbuf->level;
1086 if (level >= 2 && is_dir) {
1089 * For level 2 directory, bname will include parent name,
1090 * like vendor/platform. So search back from platform dir
1092 * Something similar for level 3 directory, but we're a PMU
1093 * category folder, like vendor/platform/cpu.
1095 bname = (char *) fpath + ftwbuf->base - 2;
1099 if (count == level - 1)
1105 bname = (char *) fpath + ftwbuf->base;
1107 pr_debug("%s %d %7jd %-20s %s\n",
1108 is_file ? "f" : is_dir ? "d" : "x",
1109 level, sb->st_size, bname, fpath);
1111 /* base dir or too deep */
1112 if (level == 0 || level > 4)
1116 /* model directory, reset topic */
1117 if ((level == 1 && is_dir && is_leaf_dir(fpath)) ||
1118 (level >= 2 && is_dir && is_leaf_dir(fpath))) {
1120 print_events_table_suffix(eventsfp);
1123 * Drop file name suffix. Replace hyphens with underscores.
1124 * Fail if file name contains any alphanum characters besides
1127 tblname = file_name_to_table_name(bname);
1129 pr_info("%s: Error determining table name for %s\n", prog,
1134 if (is_sys_dir(bname)) {
1135 struct sys_event_table *sys_event_table;
1137 sys_event_table = malloc(sizeof(*sys_event_table));
1138 if (!sys_event_table)
1141 sys_event_table->soc_id = strdup(tblname);
1142 if (!sys_event_table->soc_id) {
1143 free(sys_event_table);
1146 list_add_tail(&sys_event_table->list,
1150 print_events_table_prefix(eventsfp, tblname);
1155 * Save the mapfile name for now. We will process mapfile
1156 * after processing all JSON files (so we can write out the
1157 * mapping table after all PMU events tables).
1160 if (level == 1 && is_file) {
1161 if (!strcmp(bname, "mapfile.csv")) {
1162 mapfile = strdup(fpath);
1165 if (is_json_file(bname))
1166 pr_debug("%s: ArchStd json is preprocessed %s\n", prog, fpath);
1168 pr_info("%s: Ignoring file %s\n", prog, fpath);
1173 * If the file name does not have a .json extension,
1174 * ignore it. It could be a readme.txt for instance.
1177 if (!is_json_file(bname)) {
1178 pr_info("%s: Ignoring file without .json suffix %s\n", prog,
1184 if (level > 1 && add_topic(bname))
1188 * Assume all other files are JSON files.
1190 * If mapfile refers to 'power7_core.json', we create a table
1191 * named 'power7_core'. Any inconsistencies between the mapfile
1192 * and directory tree could result in build failure due to table
1193 * names not being found.
1195 * At least for now, be strict with processing JSON file names.
1196 * i.e. if JSON file name cannot be mapped to C-style table name,
1200 struct perf_entry_data data = {
1201 .topic = get_topic(),
1205 err = json_events(fpath, print_events_table_entry, &data);
1214 #define PATH_MAX 4096
1218 * Starting in directory 'start_dirname', find the "mapfile.csv" and
1219 * the set of JSON files for the architecture 'arch'.
1221 * From each JSON file, create a C-style "PMU events table" from the
1222 * JSON file (see struct pmu_event).
1224 * From the mapfile, create a mapping between the CPU revisions and
1225 * PMU event tables (see struct pmu_events_map).
1227 * Write out the PMU events tables and the mapping table to pmu-event.c.
1229 int main(int argc, char *argv[])
1231 int rc, ret = 0, empty_map = 0;
1233 char ldirname[PATH_MAX];
1235 const char *output_file;
1236 const char *start_dirname;
1237 const char *err_string_ext = "";
1240 prog = basename(argv[0]);
1242 pr_err("Usage: %s <arch> <starting_dir> <output_file>\n", prog);
1247 start_dirname = argv[2];
1248 output_file = argv[3];
1251 verbose = atoi(argv[4]);
1253 eventsfp = fopen(output_file, "w");
1255 pr_err("%s Unable to create required file %s (%s)\n",
1256 prog, output_file, strerror(errno));
1260 snprintf(ldirname, sizeof(ldirname), "%s/%s", start_dirname, arch);
1262 /* If architecture does not have any event lists, bail out */
1263 if (stat(ldirname, &stbuf) < 0) {
1264 pr_info("%s: Arch %s has no PMU event lists\n", prog, arch);
1266 goto err_close_eventsfp;
1269 /* Include pmu-events.h first */
1270 fprintf(eventsfp, "#include \"pmu-events/pmu-events.h\"\n");
1273 * The mapfile allows multiple CPUids to point to the same JSON file,
1274 * so, not sure if there is a need for symlinks within the pmu-events
1277 * For now, treat symlinks of JSON files as regular files and create
1278 * separate tables for each symlink (presumably, each symlink refers
1279 * to specific version of the CPU).
1282 maxfds = get_maxfds();
1283 rc = nftw(ldirname, preprocess_arch_std_files, maxfds, 0);
1285 goto err_processing_std_arch_event_dir;
1287 rc = nftw(ldirname, process_one_file, maxfds, 0);
1289 goto err_processing_dir;
1291 sprintf(ldirname, "%s/test", start_dirname);
1293 rc = nftw(ldirname, preprocess_arch_std_files, maxfds, 0);
1295 goto err_processing_std_arch_event_dir;
1297 rc = nftw(ldirname, process_one_file, maxfds, 0);
1299 goto err_processing_dir;
1302 print_events_table_suffix(eventsfp);
1305 pr_info("%s: No CPU->JSON mapping?\n", prog);
1307 goto err_close_eventsfp;
1310 rc = process_mapfile(eventsfp, mapfile);
1312 pr_info("%s: Error processing mapfile %s\n", prog, mapfile);
1313 /* Make build fail */
1315 goto err_close_eventsfp;
1318 rc = process_system_event_tables(eventsfp);
1325 free_arch_std_events();
1326 free_sys_event_tables();
1330 err_processing_std_arch_event_dir:
1331 err_string_ext = " for std arch event";
1334 pr_info("%s: Error walking file tree %s%s\n", prog, ldirname,
1337 } else if (rc < 0) {
1345 create_empty_mapping(output_file);
1347 free_arch_std_events();
1348 free_sys_event_tables();
1356 fts_compare(const FTSENT * const *a, const FTSENT * const *b)
1358 return (strcmp((*a)->fts_name, (*b)->fts_name));
1362 nftw_ordered(const char *path, int (*fn)(const char *, const struct stat *, int,
1363 struct FTW *), int nfds, int ftwflags)
1365 char * const paths[2] = { (char *)path, NULL };
1369 int error = 0, ftsflags, fnflag, postorder, sverrno;
1371 /* XXX - nfds is currently unused */
1377 ftsflags = FTS_COMFOLLOW;
1378 if (!(ftwflags & FTW_CHDIR))
1379 ftsflags |= FTS_NOCHDIR;
1380 if (ftwflags & FTW_MOUNT)
1381 ftsflags |= FTS_XDEV;
1382 if (ftwflags & FTW_PHYS)
1383 ftsflags |= FTS_PHYSICAL;
1385 ftsflags |= FTS_LOGICAL;
1386 postorder = (ftwflags & FTW_DEPTH) != 0;
1387 ftsp = fts_open(paths, ftsflags, fts_compare);
1390 while ((cur = fts_read(ftsp)) != NULL) {
1391 switch (cur->fts_info) {
1425 ftw.base = cur->fts_pathlen - cur->fts_namelen;
1426 ftw.level = cur->fts_level;
1427 error = fn(cur->fts_path, cur->fts_statp, fnflag, &ftw);
1433 if (fts_close(ftsp) != 0 && error == 0)