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