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