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