1 #define _XOPEN_SOURCE 500 /* needed for nftw() */
2 #define _GNU_SOURCE /* needed for asprintf() */
3
4 /* Parse event JSON files */
5
6 /*
7 * Copyright (c) 2014, Intel Corporation
8 * All rights reserved.
9 *
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions are met:
12 *
13 * 1. Redistributions of source code must retain the above copyright notice,
14 * this list of conditions and the following disclaimer.
15 *
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.
19 *
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.
32 */
33
34 #include <stdio.h>
35 #include <stdlib.h>
36 #include <errno.h>
37 #include <string.h>
38 #include <ctype.h>
39 #include <unistd.h>
40 #include <stdarg.h>
41 #include <libgen.h>
42 #include <limits.h>
43 #include <dirent.h>
44 #include <sys/time.h> /* getrlimit */
45 #include <sys/resource.h> /* getrlimit */
46 #include <ftw.h>
47 #include <sys/stat.h>
48 #include <linux/compiler.h>
49 #include <linux/list.h>
50 #include "jsmn.h"
51 #include "json.h"
52 #include "pmu-events.h"
53
54 int verbose;
55 char *prog;
56
57 struct json_event {
58 char *name;
59 char *compat;
60 char *event;
61 char *desc;
62 char *long_desc;
63 char *pmu;
64 char *unit;
65 char *perpkg;
66 char *aggr_mode;
67 char *metric_expr;
68 char *metric_name;
69 char *metric_group;
70 char *deprecated;
71 char *metric_constraint;
72 };
73
convert(const char * aggr_mode)74 static enum aggr_mode_class convert(const char *aggr_mode)
75 {
76 if (!strcmp(aggr_mode, "PerCore"))
77 return PerCore;
78 else if (!strcmp(aggr_mode, "PerChip"))
79 return PerChip;
80
81 pr_err("%s: Wrong AggregationMode value '%s'\n", prog, aggr_mode);
82 return -1;
83 }
84
85 static LIST_HEAD(sys_event_tables);
86
87 struct sys_event_table {
88 struct list_head list;
89 char *soc_id;
90 };
91
free_sys_event_tables(void)92 static void free_sys_event_tables(void)
93 {
94 struct sys_event_table *et, *next;
95
96 list_for_each_entry_safe(et, next, &sys_event_tables, list) {
97 free(et->soc_id);
98 free(et);
99 }
100 }
101
eprintf(int level,int var,const char * fmt,...)102 int eprintf(int level, int var, const char *fmt, ...)
103 {
104
105 int ret;
106 va_list args;
107
108 if (var < level)
109 return 0;
110
111 va_start(args, fmt);
112
113 ret = vfprintf(stderr, fmt, args);
114
115 va_end(args);
116
117 return ret;
118 }
119
addfield(char * map,char ** dst,const char * sep,const char * a,jsmntok_t * bt)120 static void addfield(char *map, char **dst, const char *sep,
121 const char *a, jsmntok_t *bt)
122 {
123 unsigned int len = strlen(a) + 1 + strlen(sep);
124 int olen = *dst ? strlen(*dst) : 0;
125 int blen = bt ? json_len(bt) : 0;
126 char *out;
127
128 out = realloc(*dst, len + olen + blen);
129 if (!out) {
130 /* Don't add field in this case */
131 return;
132 }
133 *dst = out;
134
135 if (!olen)
136 *(*dst) = 0;
137 else
138 strcat(*dst, sep);
139 strcat(*dst, a);
140 if (bt)
141 strncat(*dst, map + bt->start, blen);
142 }
143
fixname(char * s)144 static void fixname(char *s)
145 {
146 for (; *s; s++)
147 *s = tolower(*s);
148 }
149
fixdesc(char * s)150 static void fixdesc(char *s)
151 {
152 char *e = s + strlen(s);
153
154 /* Remove trailing dots that look ugly in perf list */
155 --e;
156 while (e >= s && isspace(*e))
157 --e;
158 if (*e == '.')
159 *e = 0;
160 }
161
162 /* Add escapes for '\' so they are proper C strings. */
fixregex(char * s)163 static char *fixregex(char *s)
164 {
165 int len = 0;
166 int esc_count = 0;
167 char *fixed = NULL;
168 char *p, *q;
169
170 /* Count the number of '\' in string */
171 for (p = s; *p; p++) {
172 ++len;
173 if (*p == '\\')
174 ++esc_count;
175 }
176
177 if (esc_count == 0)
178 return s;
179
180 /* allocate space for a new string */
181 fixed = (char *) malloc(len + esc_count + 1);
182 if (!fixed)
183 return NULL;
184
185 /* copy over the characters */
186 q = fixed;
187 for (p = s; *p; p++) {
188 if (*p == '\\') {
189 *q = '\\';
190 ++q;
191 }
192 *q = *p;
193 ++q;
194 }
195 *q = '\0';
196 return fixed;
197 }
198
199 static struct msrmap {
200 const char *num;
201 const char *pname;
202 } msrmap[] = {
203 { "0x3F6", "ldlat=" },
204 { "0x1A6", "offcore_rsp=" },
205 { "0x1A7", "offcore_rsp=" },
206 { "0x3F7", "frontend=" },
207 { NULL, NULL }
208 };
209
210 static struct field {
211 const char *field;
212 const char *kernel;
213 } fields[] = {
214 { "UMask", "umask=" },
215 { "CounterMask", "cmask=" },
216 { "Invert", "inv=" },
217 { "AnyThread", "any=" },
218 { "EdgeDetect", "edge=" },
219 { "SampleAfterValue", "period=" },
220 { "FCMask", "fc_mask=" },
221 { "PortMask", "ch_mask=" },
222 { NULL, NULL }
223 };
224
cut_comma(char * map,jsmntok_t * newval)225 static void cut_comma(char *map, jsmntok_t *newval)
226 {
227 int i;
228
229 /* Cut off everything after comma */
230 for (i = newval->start; i < newval->end; i++) {
231 if (map[i] == ',')
232 newval->end = i;
233 }
234 }
235
match_field(char * map,jsmntok_t * field,int nz,char ** event,jsmntok_t * val)236 static int match_field(char *map, jsmntok_t *field, int nz,
237 char **event, jsmntok_t *val)
238 {
239 struct field *f;
240 jsmntok_t newval = *val;
241
242 for (f = fields; f->field; f++)
243 if (json_streq(map, field, f->field) && nz) {
244 cut_comma(map, &newval);
245 addfield(map, event, ",", f->kernel, &newval);
246 return 1;
247 }
248 return 0;
249 }
250
lookup_msr(char * map,jsmntok_t * val)251 static struct msrmap *lookup_msr(char *map, jsmntok_t *val)
252 {
253 jsmntok_t newval = *val;
254 static bool warned;
255 int i;
256
257 cut_comma(map, &newval);
258 for (i = 0; msrmap[i].num; i++)
259 if (json_streq(map, &newval, msrmap[i].num))
260 return &msrmap[i];
261 if (!warned) {
262 warned = true;
263 pr_err("%s: Unknown MSR in event file %.*s\n", prog,
264 json_len(val), map + val->start);
265 }
266 return NULL;
267 }
268
269 static struct map {
270 const char *json;
271 const char *perf;
272 } unit_to_pmu[] = {
273 { "CBO", "uncore_cbox" },
274 { "QPI LL", "uncore_qpi" },
275 { "SBO", "uncore_sbox" },
276 { "iMPH-U", "uncore_arb" },
277 { "CPU-M-CF", "cpum_cf" },
278 { "CPU-M-SF", "cpum_sf" },
279 { "UPI LL", "uncore_upi" },
280 { "hisi_sccl,ddrc", "hisi_sccl,ddrc" },
281 { "hisi_sccl,hha", "hisi_sccl,hha" },
282 { "hisi_sccl,l3c", "hisi_sccl,l3c" },
283 /* it's not realistic to keep adding these, we need something more scalable ... */
284 { "imx8_ddr", "imx8_ddr" },
285 { "L3PMC", "amd_l3" },
286 { "DFPMC", "amd_df" },
287 { "cpu_core", "cpu_core" },
288 { "cpu_atom", "cpu_atom" },
289 {}
290 };
291
field_to_perf(struct map * table,char * map,jsmntok_t * val)292 static const char *field_to_perf(struct map *table, char *map, jsmntok_t *val)
293 {
294 int i;
295
296 for (i = 0; table[i].json; i++) {
297 if (json_streq(map, val, table[i].json))
298 return table[i].perf;
299 }
300 return NULL;
301 }
302
303 #define EXPECT(e, t, m) do { if (!(e)) { \
304 jsmntok_t *loc = (t); \
305 if (!(t)->start && (t) > tokens) \
306 loc = (t) - 1; \
307 pr_err("%s:%d: " m ", got %s\n", fn, \
308 json_line(map, loc), \
309 json_name(t)); \
310 err = -EIO; \
311 goto out_free; \
312 } } while (0)
313
314 static char *topic;
315
get_topic(void)316 static char *get_topic(void)
317 {
318 char *tp;
319 int i;
320
321 /* tp is free'd in process_one_file() */
322 i = asprintf(&tp, "%s", topic);
323 if (i < 0) {
324 pr_info("%s: asprintf() error %s\n", prog);
325 return NULL;
326 }
327
328 for (i = 0; i < (int) strlen(tp); i++) {
329 char c = tp[i];
330
331 if (c == '-')
332 tp[i] = ' ';
333 else if (c == '.') {
334 tp[i] = '\0';
335 break;
336 }
337 }
338
339 return tp;
340 }
341
add_topic(char * bname)342 static int add_topic(char *bname)
343 {
344 free(topic);
345 topic = strdup(bname);
346 if (!topic) {
347 pr_info("%s: strdup() error %s for file %s\n", prog,
348 strerror(errno), bname);
349 return -ENOMEM;
350 }
351 return 0;
352 }
353
354 struct perf_entry_data {
355 FILE *outfp;
356 char *topic;
357 };
358
359 static int close_table;
360
print_events_table_prefix(FILE * fp,const char * tblname)361 static void print_events_table_prefix(FILE *fp, const char *tblname)
362 {
363 fprintf(fp, "static const struct pmu_event %s[] = {\n", tblname);
364 close_table = 1;
365 }
366
print_events_table_entry(void * data,struct json_event * je)367 static int print_events_table_entry(void *data, struct json_event *je)
368 {
369 struct perf_entry_data *pd = data;
370 FILE *outfp = pd->outfp;
371 char *topic_local = pd->topic;
372
373 /*
374 * TODO: Remove formatting chars after debugging to reduce
375 * string lengths.
376 */
377 fprintf(outfp, "{\n");
378
379 if (je->name)
380 fprintf(outfp, "\t.name = \"%s\",\n", je->name);
381 if (je->event)
382 fprintf(outfp, "\t.event = \"%s\",\n", je->event);
383 fprintf(outfp, "\t.desc = \"%s\",\n", je->desc);
384 if (je->compat)
385 fprintf(outfp, "\t.compat = \"%s\",\n", je->compat);
386 fprintf(outfp, "\t.topic = \"%s\",\n", topic_local);
387 if (je->long_desc && je->long_desc[0])
388 fprintf(outfp, "\t.long_desc = \"%s\",\n", je->long_desc);
389 if (je->pmu)
390 fprintf(outfp, "\t.pmu = \"%s\",\n", je->pmu);
391 if (je->unit)
392 fprintf(outfp, "\t.unit = \"%s\",\n", je->unit);
393 if (je->perpkg)
394 fprintf(outfp, "\t.perpkg = \"%s\",\n", je->perpkg);
395 if (je->aggr_mode)
396 fprintf(outfp, "\t.aggr_mode = \"%d\",\n", convert(je->aggr_mode));
397 if (je->metric_expr)
398 fprintf(outfp, "\t.metric_expr = \"%s\",\n", je->metric_expr);
399 if (je->metric_name)
400 fprintf(outfp, "\t.metric_name = \"%s\",\n", je->metric_name);
401 if (je->metric_group)
402 fprintf(outfp, "\t.metric_group = \"%s\",\n", je->metric_group);
403 if (je->deprecated)
404 fprintf(outfp, "\t.deprecated = \"%s\",\n", je->deprecated);
405 if (je->metric_constraint)
406 fprintf(outfp, "\t.metric_constraint = \"%s\",\n", je->metric_constraint);
407 fprintf(outfp, "},\n");
408
409 return 0;
410 }
411
412 struct event_struct {
413 struct list_head list;
414 char *name;
415 char *event;
416 char *compat;
417 char *desc;
418 char *long_desc;
419 char *pmu;
420 char *unit;
421 char *perpkg;
422 char *aggr_mode;
423 char *metric_expr;
424 char *metric_name;
425 char *metric_group;
426 char *deprecated;
427 char *metric_constraint;
428 };
429
430 #define ADD_EVENT_FIELD(field) do { if (je->field) { \
431 es->field = strdup(je->field); \
432 if (!es->field) \
433 goto out_free; \
434 } } while (0)
435
436 #define FREE_EVENT_FIELD(field) free(es->field)
437
438 #define TRY_FIXUP_FIELD(field) do { if (es->field && !je->field) {\
439 je->field = strdup(es->field); \
440 if (!je->field) \
441 return -ENOMEM; \
442 } } while (0)
443
444 #define FOR_ALL_EVENT_STRUCT_FIELDS(op) do { \
445 op(name); \
446 op(event); \
447 op(desc); \
448 op(long_desc); \
449 op(pmu); \
450 op(unit); \
451 op(perpkg); \
452 op(aggr_mode); \
453 op(metric_expr); \
454 op(metric_name); \
455 op(metric_group); \
456 op(deprecated); \
457 } while (0)
458
459 static LIST_HEAD(arch_std_events);
460
free_arch_std_events(void)461 static void free_arch_std_events(void)
462 {
463 struct event_struct *es, *next;
464
465 list_for_each_entry_safe(es, next, &arch_std_events, list) {
466 FOR_ALL_EVENT_STRUCT_FIELDS(FREE_EVENT_FIELD);
467 list_del_init(&es->list);
468 free(es);
469 }
470 }
471
save_arch_std_events(void * data __maybe_unused,struct json_event * je)472 static int save_arch_std_events(void *data __maybe_unused, struct json_event *je)
473 {
474 struct event_struct *es;
475
476 es = malloc(sizeof(*es));
477 if (!es)
478 return -ENOMEM;
479 memset(es, 0, sizeof(*es));
480 FOR_ALL_EVENT_STRUCT_FIELDS(ADD_EVENT_FIELD);
481 list_add_tail(&es->list, &arch_std_events);
482 return 0;
483 out_free:
484 FOR_ALL_EVENT_STRUCT_FIELDS(FREE_EVENT_FIELD);
485 free(es);
486 return -ENOMEM;
487 }
488
print_events_table_suffix(FILE * outfp)489 static void print_events_table_suffix(FILE *outfp)
490 {
491 fprintf(outfp, "{\n");
492
493 fprintf(outfp, "\t.name = 0,\n");
494 fprintf(outfp, "\t.event = 0,\n");
495 fprintf(outfp, "\t.desc = 0,\n");
496
497 fprintf(outfp, "},\n");
498 fprintf(outfp, "};\n");
499 close_table = 0;
500 }
501
502 static struct fixed {
503 const char *name;
504 const char *event;
505 } fixed[] = {
506 { "inst_retired.any", "event=0xc0,period=2000003" },
507 { "inst_retired.any_p", "event=0xc0,period=2000003" },
508 { "cpu_clk_unhalted.ref", "event=0x0,umask=0x03,period=2000003" },
509 { "cpu_clk_unhalted.thread", "event=0x3c,period=2000003" },
510 { "cpu_clk_unhalted.core", "event=0x3c,period=2000003" },
511 { "cpu_clk_unhalted.thread_any", "event=0x3c,any=1,period=2000003" },
512 { NULL, NULL},
513 };
514
515 /*
516 * Handle different fixed counter encodings between JSON and perf.
517 */
real_event(const char * name,char * event)518 static char *real_event(const char *name, char *event)
519 {
520 int i;
521
522 if (!name)
523 return NULL;
524
525 for (i = 0; fixed[i].name; i++)
526 if (!strcasecmp(name, fixed[i].name))
527 return (char *)fixed[i].event;
528 return event;
529 }
530
531 static int
try_fixup(const char * fn,char * arch_std,struct json_event * je,char ** event)532 try_fixup(const char *fn, char *arch_std, struct json_event *je, char **event)
533 {
534 /* try to find matching event from arch standard values */
535 struct event_struct *es;
536
537 list_for_each_entry(es, &arch_std_events, list) {
538 if (!strcmp(arch_std, es->name)) {
539 FOR_ALL_EVENT_STRUCT_FIELDS(TRY_FIXUP_FIELD);
540 *event = je->event;
541 return 0;
542 }
543 }
544
545 pr_err("%s: could not find matching %s for %s\n",
546 prog, arch_std, fn);
547 return -1;
548 }
549
550 /* Call func with each event in the json file */
json_events(const char * fn,int (* func)(void * data,struct json_event * je),void * data)551 static int json_events(const char *fn,
552 int (*func)(void *data, struct json_event *je),
553 void *data)
554 {
555 int err;
556 size_t size;
557 jsmntok_t *tokens, *tok;
558 int i, j, len;
559 char *map;
560 char buf[128];
561
562 if (!fn)
563 return -ENOENT;
564
565 tokens = parse_json(fn, &map, &size, &len);
566 if (!tokens)
567 return -EIO;
568 EXPECT(tokens->type == JSMN_ARRAY, tokens, "expected top level array");
569 tok = tokens + 1;
570 for (i = 0; i < tokens->size; i++) {
571 char *event = NULL;
572 char *extra_desc = NULL;
573 char *filter = NULL;
574 struct json_event je = {};
575 char *arch_std = NULL;
576 unsigned long long eventcode = 0;
577 unsigned long long configcode = 0;
578 struct msrmap *msr = NULL;
579 jsmntok_t *msrval = NULL;
580 jsmntok_t *precise = NULL;
581 jsmntok_t *obj = tok++;
582 bool configcode_present = false;
583
584 EXPECT(obj->type == JSMN_OBJECT, obj, "expected object");
585 for (j = 0; j < obj->size; j += 2) {
586 jsmntok_t *field, *val;
587 int nz;
588 char *s;
589
590 field = tok + j;
591 EXPECT(field->type == JSMN_STRING, tok + j,
592 "Expected field name");
593 val = tok + j + 1;
594 EXPECT(val->type == JSMN_STRING, tok + j + 1,
595 "Expected string value");
596
597 nz = !json_streq(map, val, "0");
598 if (match_field(map, field, nz, &event, val)) {
599 /* ok */
600 } else if (json_streq(map, field, "EventCode")) {
601 char *code = NULL;
602 addfield(map, &code, "", "", val);
603 eventcode |= strtoul(code, NULL, 0);
604 free(code);
605 } else if (json_streq(map, field, "ConfigCode")) {
606 char *code = NULL;
607 addfield(map, &code, "", "", val);
608 configcode |= strtoul(code, NULL, 0);
609 free(code);
610 configcode_present = true;
611 } else if (json_streq(map, field, "ExtSel")) {
612 char *code = NULL;
613 addfield(map, &code, "", "", val);
614 eventcode |= strtoul(code, NULL, 0) << 21;
615 free(code);
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);
622 fixdesc(je.desc);
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) {
628 precise = val;
629 } else if (json_streq(map, field, "MSRIndex") && nz) {
630 msr = lookup_msr(map, val);
631 } else if (json_streq(map, field, "MSRValue")) {
632 msrval = val;
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",
640 NULL);
641 } else if (json_streq(map, field, "Unit")) {
642 const char *ppmu;
643
644 ppmu = field_to_perf(unit_to_pmu, map, val);
645 if (ppmu) {
646 je.pmu = strdup(ppmu);
647 } else {
648 if (!je.pmu)
649 je.pmu = strdup("uncore_");
650 addfield(map, &je.pmu, "", "", val);
651 for (s = je.pmu; *s; s++)
652 *s = tolower(*s);
653 }
654 addfield(map, &je.desc, ". ", "Unit: ", NULL);
655 addfield(map, &je.desc, "", je.pmu, NULL);
656 addfield(map, &je.desc, "", " ", NULL);
657 } else if (json_streq(map, field, "Filter")) {
658 addfield(map, &filter, "", "", val);
659 } else if (json_streq(map, field, "ScaleUnit")) {
660 addfield(map, &je.unit, "", "", val);
661 } else if (json_streq(map, field, "PerPkg")) {
662 addfield(map, &je.perpkg, "", "", val);
663 } else if (json_streq(map, field, "AggregationMode")) {
664 addfield(map, &je.aggr_mode, "", "", val);
665 } else if (json_streq(map, field, "Deprecated")) {
666 addfield(map, &je.deprecated, "", "", val);
667 } else if (json_streq(map, field, "MetricName")) {
668 addfield(map, &je.metric_name, "", "", val);
669 } else if (json_streq(map, field, "MetricGroup")) {
670 addfield(map, &je.metric_group, "", "", val);
671 } else if (json_streq(map, field, "MetricConstraint")) {
672 addfield(map, &je.metric_constraint, "", "", val);
673 } else if (json_streq(map, field, "MetricExpr")) {
674 addfield(map, &je.metric_expr, "", "", val);
675 for (s = je.metric_expr; *s; s++)
676 *s = tolower(*s);
677 } else if (json_streq(map, field, "ArchStdEvent")) {
678 addfield(map, &arch_std, "", "", val);
679 for (s = arch_std; *s; s++)
680 *s = tolower(*s);
681 }
682 /* ignore unknown fields */
683 }
684 if (precise && je.desc && !strstr(je.desc, "(Precise Event)")) {
685 if (json_streq(map, precise, "2"))
686 addfield(map, &extra_desc, " ",
687 "(Must be precise)", NULL);
688 else
689 addfield(map, &extra_desc, " ",
690 "(Precise event)", NULL);
691 }
692 if (configcode_present)
693 snprintf(buf, sizeof buf, "config=%#llx", configcode);
694 else
695 snprintf(buf, sizeof buf, "event=%#llx", eventcode);
696 addfield(map, &event, ",", buf, NULL);
697 if (je.desc && extra_desc)
698 addfield(map, &je.desc, " ", extra_desc, NULL);
699 if (je.long_desc && extra_desc)
700 addfield(map, &je.long_desc, " ", extra_desc, NULL);
701 if (filter)
702 addfield(map, &event, ",", filter, NULL);
703 if (msr != NULL)
704 addfield(map, &event, ",", msr->pname, msrval);
705 if (je.name)
706 fixname(je.name);
707
708 if (arch_std) {
709 /*
710 * An arch standard event is referenced, so try to
711 * fixup any unassigned values.
712 */
713 err = try_fixup(fn, arch_std, &je, &event);
714 if (err)
715 goto free_strings;
716 }
717 je.event = real_event(je.name, event);
718 err = func(data, &je);
719 free_strings:
720 free(event);
721 free(je.desc);
722 free(je.name);
723 free(je.compat);
724 free(je.long_desc);
725 free(extra_desc);
726 free(je.pmu);
727 free(filter);
728 free(je.perpkg);
729 free(je.aggr_mode);
730 free(je.deprecated);
731 free(je.unit);
732 free(je.metric_expr);
733 free(je.metric_name);
734 free(je.metric_group);
735 free(je.metric_constraint);
736 free(arch_std);
737
738 if (err)
739 break;
740 tok += j;
741 }
742 EXPECT(tok - tokens == len, tok, "unexpected objects at end");
743 err = 0;
744 out_free:
745 free_json(map, size, tokens);
746 return err;
747 }
748
file_name_to_table_name(char * fname)749 static char *file_name_to_table_name(char *fname)
750 {
751 unsigned int i;
752 int n;
753 int c;
754 char *tblname;
755
756 /*
757 * Ensure tablename starts with alphabetic character.
758 * Derive rest of table name from basename of the JSON file,
759 * replacing hyphens and stripping out .json suffix.
760 */
761 n = asprintf(&tblname, "pme_%s", fname);
762 if (n < 0) {
763 pr_info("%s: asprintf() error %s for file %s\n", prog,
764 strerror(errno), fname);
765 return NULL;
766 }
767
768 for (i = 0; i < strlen(tblname); i++) {
769 c = tblname[i];
770
771 if (c == '-' || c == '/')
772 tblname[i] = '_';
773 else if (c == '.') {
774 tblname[i] = '\0';
775 break;
776 } else if (!isalnum(c) && c != '_') {
777 pr_err("%s: Invalid character '%c' in file name %s\n",
778 prog, c, basename(fname));
779 free(tblname);
780 tblname = NULL;
781 break;
782 }
783 }
784
785 return tblname;
786 }
787
is_sys_dir(char * fname)788 static bool is_sys_dir(char *fname)
789 {
790 size_t len = strlen(fname), len2 = strlen("/sys");
791
792 if (len2 > len)
793 return false;
794 return !strcmp(fname+len-len2, "/sys");
795 }
796
print_mapping_table_prefix(FILE * outfp)797 static void print_mapping_table_prefix(FILE *outfp)
798 {
799 fprintf(outfp, "const struct pmu_events_map pmu_events_map[] = {\n");
800 }
801
print_mapping_table_suffix(FILE * outfp)802 static void print_mapping_table_suffix(FILE *outfp)
803 {
804 /*
805 * Print the terminating, NULL entry.
806 */
807 fprintf(outfp, "{\n");
808 fprintf(outfp, "\t.cpuid = 0,\n");
809 fprintf(outfp, "\t.version = 0,\n");
810 fprintf(outfp, "\t.type = 0,\n");
811 fprintf(outfp, "\t.table = 0,\n");
812 fprintf(outfp, "},\n");
813
814 /* and finally, the closing curly bracket for the struct */
815 fprintf(outfp, "};\n");
816 }
817
print_mapping_test_table(FILE * outfp)818 static void print_mapping_test_table(FILE *outfp)
819 {
820 /*
821 * Print the terminating, NULL entry.
822 */
823 fprintf(outfp, "{\n");
824 fprintf(outfp, "\t.cpuid = \"testcpu\",\n");
825 fprintf(outfp, "\t.version = \"v1\",\n");
826 fprintf(outfp, "\t.type = \"core\",\n");
827 fprintf(outfp, "\t.table = pme_test_soc_cpu,\n");
828 fprintf(outfp, "},\n");
829 }
830
print_system_event_mapping_table_prefix(FILE * outfp)831 static void print_system_event_mapping_table_prefix(FILE *outfp)
832 {
833 fprintf(outfp, "\nconst struct pmu_sys_events pmu_sys_event_tables[] = {");
834 }
835
print_system_event_mapping_table_suffix(FILE * outfp)836 static void print_system_event_mapping_table_suffix(FILE *outfp)
837 {
838 fprintf(outfp, "\n\t{\n\t\t.table = 0\n\t},");
839 fprintf(outfp, "\n};\n");
840 }
841
process_system_event_tables(FILE * outfp)842 static int process_system_event_tables(FILE *outfp)
843 {
844 struct sys_event_table *sys_event_table;
845
846 print_system_event_mapping_table_prefix(outfp);
847
848 list_for_each_entry(sys_event_table, &sys_event_tables, list) {
849 fprintf(outfp, "\n\t{\n\t\t.table = %s,\n\t\t.name = \"%s\",\n\t},",
850 sys_event_table->soc_id,
851 sys_event_table->soc_id);
852 }
853
854 print_system_event_mapping_table_suffix(outfp);
855
856 return 0;
857 }
858
process_mapfile(FILE * outfp,char * fpath)859 static int process_mapfile(FILE *outfp, char *fpath)
860 {
861 int n = 16384;
862 FILE *mapfp;
863 char *save = NULL;
864 char *line, *p;
865 int line_num;
866 char *tblname;
867 int ret = 0;
868
869 pr_info("%s: Processing mapfile %s\n", prog, fpath);
870
871 line = malloc(n);
872 if (!line)
873 return -1;
874
875 mapfp = fopen(fpath, "r");
876 if (!mapfp) {
877 pr_info("%s: Error %s opening %s\n", prog, strerror(errno),
878 fpath);
879 free(line);
880 return -1;
881 }
882
883 print_mapping_table_prefix(outfp);
884
885 /* Skip first line (header) */
886 p = fgets(line, n, mapfp);
887 if (!p)
888 goto out;
889
890 line_num = 1;
891 while (1) {
892 char *cpuid, *version, *type, *fname;
893
894 line_num++;
895 p = fgets(line, n, mapfp);
896 if (!p)
897 break;
898
899 if (line[0] == '#' || line[0] == '\n')
900 continue;
901
902 if (line[strlen(line)-1] != '\n') {
903 /* TODO Deal with lines longer than 16K */
904 pr_info("%s: Mapfile %s: line %d too long, aborting\n",
905 prog, fpath, line_num);
906 ret = -1;
907 goto out;
908 }
909 line[strlen(line)-1] = '\0';
910
911 cpuid = fixregex(strtok_r(p, ",", &save));
912 version = strtok_r(NULL, ",", &save);
913 fname = strtok_r(NULL, ",", &save);
914 type = strtok_r(NULL, ",", &save);
915
916 tblname = file_name_to_table_name(fname);
917 fprintf(outfp, "{\n");
918 fprintf(outfp, "\t.cpuid = \"%s\",\n", cpuid);
919 fprintf(outfp, "\t.version = \"%s\",\n", version);
920 fprintf(outfp, "\t.type = \"%s\",\n", type);
921
922 /*
923 * CHECK: We can't use the type (eg "core") field in the
924 * table name. For us to do that, we need to somehow tweak
925 * the other caller of file_name_to_table(), process_json()
926 * to determine the type. process_json() file has no way
927 * of knowing these are "core" events unless file name has
928 * core in it. If filename has core in it, we can safely
929 * ignore the type field here also.
930 */
931 fprintf(outfp, "\t.table = %s\n", tblname);
932 fprintf(outfp, "},\n");
933 }
934
935 out:
936 print_mapping_test_table(outfp);
937 print_mapping_table_suffix(outfp);
938 fclose(mapfp);
939 free(line);
940 return ret;
941 }
942
943 /*
944 * If we fail to locate/process JSON and map files, create a NULL mapping
945 * table. This would at least allow perf to build even if we can't find/use
946 * the aliases.
947 */
create_empty_mapping(const char * output_file)948 static void create_empty_mapping(const char *output_file)
949 {
950 FILE *outfp;
951
952 pr_info("%s: Creating empty pmu_events_map[] table\n", prog);
953
954 /* Truncate file to clear any partial writes to it */
955 outfp = fopen(output_file, "w");
956 if (!outfp) {
957 perror("fopen()");
958 _Exit(1);
959 }
960
961 fprintf(outfp, "#include \"pmu-events/pmu-events.h\"\n");
962 print_mapping_table_prefix(outfp);
963 print_mapping_table_suffix(outfp);
964 print_system_event_mapping_table_prefix(outfp);
965 print_system_event_mapping_table_suffix(outfp);
966 fclose(outfp);
967 }
968
get_maxfds(void)969 static int get_maxfds(void)
970 {
971 struct rlimit rlim;
972
973 if (getrlimit(RLIMIT_NOFILE, &rlim) == 0)
974 return min(rlim.rlim_max / 2, (rlim_t)512);
975
976 return 512;
977 }
978
979 /*
980 * nftw() doesn't let us pass an argument to the processing function,
981 * so use a global variables.
982 */
983 static FILE *eventsfp;
984 static char *mapfile;
985
is_leaf_dir(const char * fpath)986 static int is_leaf_dir(const char *fpath)
987 {
988 DIR *d;
989 struct dirent *dir;
990 int res = 1;
991
992 d = opendir(fpath);
993 if (!d)
994 return 0;
995
996 while ((dir = readdir(d)) != NULL) {
997 if (!strcmp(dir->d_name, ".") || !strcmp(dir->d_name, ".."))
998 continue;
999
1000 if (dir->d_type == DT_DIR) {
1001 res = 0;
1002 break;
1003 } else if (dir->d_type == DT_UNKNOWN) {
1004 char path[PATH_MAX];
1005 struct stat st;
1006
1007 sprintf(path, "%s/%s", fpath, dir->d_name);
1008 if (stat(path, &st))
1009 break;
1010
1011 if (S_ISDIR(st.st_mode)) {
1012 res = 0;
1013 break;
1014 }
1015 }
1016 }
1017
1018 closedir(d);
1019
1020 return res;
1021 }
1022
is_json_file(const char * name)1023 static int is_json_file(const char *name)
1024 {
1025 const char *suffix;
1026
1027 if (strlen(name) < 5)
1028 return 0;
1029
1030 suffix = name + strlen(name) - 5;
1031
1032 if (strncmp(suffix, ".json", 5) == 0)
1033 return 1;
1034 return 0;
1035 }
1036
preprocess_arch_std_files(const char * fpath,const struct stat * sb,int typeflag,struct FTW * ftwbuf)1037 static int preprocess_arch_std_files(const char *fpath, const struct stat *sb,
1038 int typeflag, struct FTW *ftwbuf)
1039 {
1040 int level = ftwbuf->level;
1041 int is_file = typeflag == FTW_F;
1042
1043 if (level == 1 && is_file && is_json_file(fpath))
1044 return json_events(fpath, save_arch_std_events, (void *)sb);
1045
1046 return 0;
1047 }
1048
process_one_file(const char * fpath,const struct stat * sb,int typeflag,struct FTW * ftwbuf)1049 static int process_one_file(const char *fpath, const struct stat *sb,
1050 int typeflag, struct FTW *ftwbuf)
1051 {
1052 char *tblname, *bname;
1053 int is_dir = typeflag == FTW_D;
1054 int is_file = typeflag == FTW_F;
1055 int level = ftwbuf->level;
1056 int err = 0;
1057
1058 if (level >= 2 && is_dir) {
1059 int count = 0;
1060 /*
1061 * For level 2 directory, bname will include parent name,
1062 * like vendor/platform. So search back from platform dir
1063 * to find this.
1064 * Something similar for level 3 directory, but we're a PMU
1065 * category folder, like vendor/platform/cpu.
1066 */
1067 bname = (char *) fpath + ftwbuf->base - 2;
1068 for (;;) {
1069 if (*bname == '/')
1070 count++;
1071 if (count == level - 1)
1072 break;
1073 bname--;
1074 }
1075 bname++;
1076 } else
1077 bname = (char *) fpath + ftwbuf->base;
1078
1079 pr_debug("%s %d %7jd %-20s %s\n",
1080 is_file ? "f" : is_dir ? "d" : "x",
1081 level, sb->st_size, bname, fpath);
1082
1083 /* base dir or too deep */
1084 if (level == 0 || level > 4)
1085 return 0;
1086
1087
1088 /* model directory, reset topic */
1089 if ((level == 1 && is_dir && is_leaf_dir(fpath)) ||
1090 (level >= 2 && is_dir && is_leaf_dir(fpath))) {
1091 if (close_table)
1092 print_events_table_suffix(eventsfp);
1093
1094 /*
1095 * Drop file name suffix. Replace hyphens with underscores.
1096 * Fail if file name contains any alphanum characters besides
1097 * underscores.
1098 */
1099 tblname = file_name_to_table_name(bname);
1100 if (!tblname) {
1101 pr_info("%s: Error determining table name for %s\n", prog,
1102 bname);
1103 return -1;
1104 }
1105
1106 if (is_sys_dir(bname)) {
1107 struct sys_event_table *sys_event_table;
1108
1109 sys_event_table = malloc(sizeof(*sys_event_table));
1110 if (!sys_event_table)
1111 return -1;
1112
1113 sys_event_table->soc_id = strdup(tblname);
1114 if (!sys_event_table->soc_id) {
1115 free(sys_event_table);
1116 return -1;
1117 }
1118 list_add_tail(&sys_event_table->list,
1119 &sys_event_tables);
1120 }
1121
1122 print_events_table_prefix(eventsfp, tblname);
1123 return 0;
1124 }
1125
1126 /*
1127 * Save the mapfile name for now. We will process mapfile
1128 * after processing all JSON files (so we can write out the
1129 * mapping table after all PMU events tables).
1130 *
1131 */
1132 if (level == 1 && is_file) {
1133 if (!strcmp(bname, "mapfile.csv")) {
1134 mapfile = strdup(fpath);
1135 return 0;
1136 }
1137 if (is_json_file(bname))
1138 pr_debug("%s: ArchStd json is preprocessed %s\n", prog, fpath);
1139 else
1140 pr_info("%s: Ignoring file %s\n", prog, fpath);
1141 return 0;
1142 }
1143
1144 /*
1145 * If the file name does not have a .json extension,
1146 * ignore it. It could be a readme.txt for instance.
1147 */
1148 if (is_file) {
1149 if (!is_json_file(bname)) {
1150 pr_info("%s: Ignoring file without .json suffix %s\n", prog,
1151 fpath);
1152 return 0;
1153 }
1154 }
1155
1156 if (level > 1 && add_topic(bname))
1157 return -ENOMEM;
1158
1159 /*
1160 * Assume all other files are JSON files.
1161 *
1162 * If mapfile refers to 'power7_core.json', we create a table
1163 * named 'power7_core'. Any inconsistencies between the mapfile
1164 * and directory tree could result in build failure due to table
1165 * names not being found.
1166 *
1167 * At least for now, be strict with processing JSON file names.
1168 * i.e. if JSON file name cannot be mapped to C-style table name,
1169 * fail.
1170 */
1171 if (is_file) {
1172 struct perf_entry_data data = {
1173 .topic = get_topic(),
1174 .outfp = eventsfp,
1175 };
1176
1177 err = json_events(fpath, print_events_table_entry, &data);
1178
1179 free(data.topic);
1180 }
1181
1182 return err;
1183 }
1184
1185 #ifndef PATH_MAX
1186 #define PATH_MAX 4096
1187 #endif
1188
1189 /*
1190 * Starting in directory 'start_dirname', find the "mapfile.csv" and
1191 * the set of JSON files for the architecture 'arch'.
1192 *
1193 * From each JSON file, create a C-style "PMU events table" from the
1194 * JSON file (see struct pmu_event).
1195 *
1196 * From the mapfile, create a mapping between the CPU revisions and
1197 * PMU event tables (see struct pmu_events_map).
1198 *
1199 * Write out the PMU events tables and the mapping table to pmu-event.c.
1200 */
main(int argc,char * argv[])1201 int main(int argc, char *argv[])
1202 {
1203 int rc, ret = 0, empty_map = 0;
1204 int maxfds;
1205 char ldirname[PATH_MAX];
1206 const char *arch;
1207 const char *output_file;
1208 const char *start_dirname;
1209 const char *err_string_ext = "";
1210 struct stat stbuf;
1211
1212 prog = basename(argv[0]);
1213 if (argc < 4) {
1214 pr_err("Usage: %s <arch> <starting_dir> <output_file>\n", prog);
1215 return 1;
1216 }
1217
1218 arch = argv[1];
1219 start_dirname = argv[2];
1220 output_file = argv[3];
1221
1222 if (argc > 4)
1223 verbose = atoi(argv[4]);
1224
1225 eventsfp = fopen(output_file, "w");
1226 if (!eventsfp) {
1227 pr_err("%s Unable to create required file %s (%s)\n",
1228 prog, output_file, strerror(errno));
1229 return 2;
1230 }
1231
1232 sprintf(ldirname, "%s/%s", start_dirname, arch);
1233
1234 /* If architecture does not have any event lists, bail out */
1235 if (stat(ldirname, &stbuf) < 0) {
1236 pr_info("%s: Arch %s has no PMU event lists\n", prog, arch);
1237 empty_map = 1;
1238 goto err_close_eventsfp;
1239 }
1240
1241 /* Include pmu-events.h first */
1242 fprintf(eventsfp, "#include \"pmu-events/pmu-events.h\"\n");
1243
1244 /*
1245 * The mapfile allows multiple CPUids to point to the same JSON file,
1246 * so, not sure if there is a need for symlinks within the pmu-events
1247 * directory.
1248 *
1249 * For now, treat symlinks of JSON files as regular files and create
1250 * separate tables for each symlink (presumably, each symlink refers
1251 * to specific version of the CPU).
1252 */
1253
1254 maxfds = get_maxfds();
1255 rc = nftw(ldirname, preprocess_arch_std_files, maxfds, 0);
1256 if (rc)
1257 goto err_processing_std_arch_event_dir;
1258
1259 rc = nftw(ldirname, process_one_file, maxfds, 0);
1260 if (rc)
1261 goto err_processing_dir;
1262
1263 sprintf(ldirname, "%s/test", start_dirname);
1264
1265 rc = nftw(ldirname, preprocess_arch_std_files, maxfds, 0);
1266 if (rc)
1267 goto err_processing_std_arch_event_dir;
1268
1269 rc = nftw(ldirname, process_one_file, maxfds, 0);
1270 if (rc)
1271 goto err_processing_dir;
1272
1273 if (close_table)
1274 print_events_table_suffix(eventsfp);
1275
1276 if (!mapfile) {
1277 pr_info("%s: No CPU->JSON mapping?\n", prog);
1278 empty_map = 1;
1279 goto err_close_eventsfp;
1280 }
1281
1282 rc = process_mapfile(eventsfp, mapfile);
1283 if (rc) {
1284 pr_info("%s: Error processing mapfile %s\n", prog, mapfile);
1285 /* Make build fail */
1286 ret = 1;
1287 goto err_close_eventsfp;
1288 }
1289
1290 rc = process_system_event_tables(eventsfp);
1291 fclose(eventsfp);
1292 if (rc) {
1293 ret = 1;
1294 goto err_out;
1295 }
1296
1297 free_arch_std_events();
1298 free_sys_event_tables();
1299 free(mapfile);
1300 return 0;
1301
1302 err_processing_std_arch_event_dir:
1303 err_string_ext = " for std arch event";
1304 err_processing_dir:
1305 if (verbose) {
1306 pr_info("%s: Error walking file tree %s%s\n", prog, ldirname,
1307 err_string_ext);
1308 empty_map = 1;
1309 } else if (rc < 0) {
1310 ret = 1;
1311 } else {
1312 empty_map = 1;
1313 }
1314 err_close_eventsfp:
1315 fclose(eventsfp);
1316 if (empty_map)
1317 create_empty_mapping(output_file);
1318 err_out:
1319 free_arch_std_events();
1320 free_sys_event_tables();
1321 free(mapfile);
1322 return ret;
1323 }
1324