xref: /freebsd/lib/libpmc/pmu-events/jevents.c (revision a6578a04e440f79f3b913660221caa9cde3e722c)
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 	{ "L3ThreadMask", "l3_thread_mask=" },
188 	{ "L3SliceMask", "l3_slice_mask=" },
189 	{ NULL, NULL }
190 };
191 
192 static void cut_comma(char *map, jsmntok_t *newval)
193 {
194 	int i;
195 
196 	/* Cut off everything after comma */
197 	for (i = newval->start; i < newval->end; i++) {
198 		if (map[i] == ',')
199 			newval->end = i;
200 	}
201 }
202 
203 static int match_field(char *map, jsmntok_t *field, int nz,
204 		       char **event, jsmntok_t *val)
205 {
206 	struct field *f;
207 	jsmntok_t newval = *val;
208 
209 	for (f = fields; f->field; f++)
210 		if (json_streq(map, field, f->field) && nz) {
211 			cut_comma(map, &newval);
212 			addfield(map, event, ",", f->kernel, &newval);
213 			return 1;
214 		}
215 	return 0;
216 }
217 
218 static struct msrmap *lookup_msr(char *map, jsmntok_t *val)
219 {
220 	jsmntok_t newval = *val;
221 	static bool warned;
222 	int i;
223 
224 	cut_comma(map, &newval);
225 	for (i = 0; msrmap[i].num; i++)
226 		if (json_streq(map, &newval, msrmap[i].num))
227 			return &msrmap[i];
228 	if (!warned) {
229 		warned = true;
230 		pr_err("%s: Unknown MSR in event file %.*s\n", prog,
231 			json_len(val), map + val->start);
232 	}
233 	return NULL;
234 }
235 
236 static struct map {
237 	const char *json;
238 	const char *perf;
239 } unit_to_pmu[] = {
240 	{ "CBO", "uncore_cbox" },
241 	{ "QPI LL", "uncore_qpi" },
242 	{ "SBO", "uncore_sbox" },
243 	{ "iMPH-U", "uncore_arb" },
244 	{}
245 };
246 
247 static const char *field_to_perf(struct map *table, char *map, jsmntok_t *val)
248 {
249 	int i;
250 
251 	for (i = 0; table[i].json; i++) {
252 		if (json_streq(map, val, table[i].json))
253 			return table[i].perf;
254 	}
255 	return NULL;
256 }
257 
258 #define EXPECT(e, t, m) do { if (!(e)) {			\
259 	jsmntok_t *loc = (t);					\
260 	if (!(t)->start && (t) > tokens)			\
261 		loc = (t) - 1;					\
262 	pr_err("%s:%d: " m ", got %s\n", fn,			\
263 	       json_line(map, loc),				\
264 	       json_name(t));					\
265 	err = -EIO;						\
266 	goto out_free;						\
267 } } while (0)
268 
269 static char *topic;
270 
271 static char *get_topic(void)
272 {
273 	char *tp;
274 	int i;
275 
276 	/* tp is free'd in process_one_file() */
277 	i = asprintf(&tp, "%s", topic);
278 	if (i < 0) {
279 		pr_info("%s: asprintf() error %s\n", prog);
280 		return NULL;
281 	}
282 
283 	for (i = 0; i < (int) strlen(tp); i++) {
284 		char c = tp[i];
285 
286 		if (c == '-')
287 			tp[i] = ' ';
288 		else if (c == '.') {
289 			tp[i] = '\0';
290 			break;
291 		}
292 	}
293 
294 	return tp;
295 }
296 
297 static int add_topic(const char *bname)
298 {
299 	free(topic);
300 	topic = strdup(bname);
301 	if (!topic) {
302 		pr_info("%s: strdup() error %s for file %s\n", prog,
303 				strerror(errno), bname);
304 		return -ENOMEM;
305 	}
306 	return 0;
307 }
308 
309 struct perf_entry_data {
310 	FILE *outfp;
311 	char *topic;
312 };
313 
314 static int close_table;
315 
316 static void print_events_table_prefix(FILE *fp, const char *tblname)
317 {
318 	fprintf(fp, "static struct pmu_event %s[] = {\n", tblname);
319 	close_table = 1;
320 }
321 
322 static int print_events_table_entry(void *data, char *name, const char *event,
323 				    char *desc, char *long_desc,
324 				    char *pmu, char *unit, char *perpkg,
325 				    char *metric_expr,
326 				    char *metric_name, char *metric_group)
327 {
328 	struct perf_entry_data *pd = data;
329 	FILE *outfp = pd->outfp;
330 	char *etopic = pd->topic;
331 
332 	/*
333 	 * TODO: Remove formatting chars after debugging to reduce
334 	 *	 string lengths.
335 	 */
336 	fprintf(outfp, "{\n");
337 
338 	if (name)
339 		fprintf(outfp, "\t.name = \"%s\",\n", name);
340 	if (event)
341 		fprintf(outfp, "\t.event = \"%s\",\n", event);
342 	fprintf(outfp, "\t.desc = \"%s\",\n", desc);
343 	fprintf(outfp, "\t.topic = \"%s\",\n", etopic);
344 	if (long_desc && long_desc[0])
345 		fprintf(outfp, "\t.long_desc = \"%s\",\n", long_desc);
346 	if (pmu)
347 		fprintf(outfp, "\t.pmu = \"%s\",\n", pmu);
348 	if (unit)
349 		fprintf(outfp, "\t.unit = \"%s\",\n", unit);
350 	if (perpkg)
351 		fprintf(outfp, "\t.perpkg = \"%s\",\n", perpkg);
352 	if (metric_expr)
353 		fprintf(outfp, "\t.metric_expr = \"%s\",\n", metric_expr);
354 	if (metric_name)
355 		fprintf(outfp, "\t.metric_name = \"%s\",\n", metric_name);
356 	if (metric_group)
357 		fprintf(outfp, "\t.metric_group = \"%s\",\n", metric_group);
358 	fprintf(outfp, "},\n");
359 
360 	return 0;
361 }
362 
363 struct event_struct {
364 	struct list_head list;
365 	char *name;
366 	char *event;
367 	char *desc;
368 	char *long_desc;
369 	char *pmu;
370 	char *unit;
371 	char *perpkg;
372 	char *metric_expr;
373 	char *metric_name;
374 	char *metric_group;
375 };
376 
377 #define ADD_EVENT_FIELD(field) do { if (field) {		\
378 	es->field = strdup(field);				\
379 	if (!es->field)						\
380 		goto out_free;					\
381 } } while (0)
382 
383 #define FREE_EVENT_FIELD(field) free(es->field)
384 
385 #define TRY_FIXUP_FIELD(field) do { if (es->field && !*field) {\
386 	*field = strdup(es->field);				\
387 	if (!*field)						\
388 		return -ENOMEM;					\
389 } } while (0)
390 
391 #define FOR_ALL_EVENT_STRUCT_FIELDS(op) do {			\
392 	op(name);						\
393 	op(event);						\
394 	op(desc);						\
395 	op(long_desc);						\
396 	op(pmu);						\
397 	op(unit);						\
398 	op(perpkg);						\
399 	op(metric_expr);					\
400 	op(metric_name);					\
401 	op(metric_group);					\
402 } while (0)
403 
404 static LIST_HEAD(arch_std_events);
405 
406 static void free_arch_std_events(void)
407 {
408 	struct event_struct *es, *next;
409 
410 	list_for_each_entry_safe(es, next, &arch_std_events, list) {
411 		FOR_ALL_EVENT_STRUCT_FIELDS(FREE_EVENT_FIELD);
412 		list_del(&es->list);
413 		free(es);
414 	}
415 }
416 
417 static int save_arch_std_events(void *data __unused, char *name, const char *event,
418 				char *desc, char *long_desc, char *pmu,
419 				char *unit, char *perpkg, char *metric_expr,
420 				char *metric_name, char *metric_group)
421 {
422 	struct event_struct *es;
423 
424 	es = malloc(sizeof(*es));
425 	if (!es)
426 		return -ENOMEM;
427 	memset(es, 0, sizeof(*es));
428 	FOR_ALL_EVENT_STRUCT_FIELDS(ADD_EVENT_FIELD);
429 	list_add_tail(&es->list, &arch_std_events);
430 	return 0;
431 out_free:
432 	FOR_ALL_EVENT_STRUCT_FIELDS(FREE_EVENT_FIELD);
433 	free(es);
434 	return -ENOMEM;
435 }
436 
437 static void print_events_table_suffix(FILE *outfp)
438 {
439 	fprintf(outfp, "{\n");
440 
441 	fprintf(outfp, "\t.name = 0,\n");
442 	fprintf(outfp, "\t.event = 0,\n");
443 	fprintf(outfp, "\t.desc = 0,\n");
444 
445 	fprintf(outfp, "},\n");
446 	fprintf(outfp, "};\n");
447 	close_table = 0;
448 }
449 
450 static struct fixed {
451 	const char *name;
452 	const char *event;
453 } fixed[] = {
454 	{ "inst_retired.any", "event=0xc0" },
455 	{ "inst_retired.any_p", "event=0xc0" },
456 	{ "cpu_clk_unhalted.ref", "event=0x0,umask=0x03" },
457 	{ "cpu_clk_unhalted.thread", "event=0x3c" },
458 	{ "cpu_clk_unhalted.thread_any", "event=0x3c,any=1" },
459 	{ NULL, NULL},
460 };
461 
462 /*
463  * Handle different fixed counter encodings between JSON and perf.
464  */
465 static const char *real_event(const char *name, char *event)
466 {
467 	int i;
468 
469 	if (!name)
470 		return NULL;
471 
472 	for (i = 0; fixed[i].name; i++)
473 		if (!strcasecmp(name, fixed[i].name))
474 			return fixed[i].event;
475 	return event;
476 }
477 
478 static int
479 try_fixup(const char *fn, char *arch_std, char **event, char **desc,
480 	  char **name, char **long_desc, char **pmu, char **filter __unused,
481 	  char **perpkg, char **unit, char **metric_expr, char **metric_name,
482 	  char **metric_group, unsigned long long eventcode)
483 {
484 	/* try to find matching event from arch standard values */
485 	struct event_struct *es;
486 
487 	list_for_each_entry(es, &arch_std_events, list) {
488 		if (!strcmp(arch_std, es->name)) {
489 			if (!eventcode && es->event) {
490 				/* allow EventCode to be overridden */
491 				free(*event);
492 				*event = NULL;
493 			}
494 			FOR_ALL_EVENT_STRUCT_FIELDS(TRY_FIXUP_FIELD);
495 			return 0;
496 		}
497 	}
498 
499 	pr_err("%s: could not find matching %s for %s\n",
500 					prog, arch_std, fn);
501 	return -1;
502 }
503 
504 /* Call func with each event in the json file */
505 int json_events(const char *fn,
506 	  int (*func)(void *data, char *name, const char *event, char *desc,
507 		      char *long_desc,
508 		      char *pmu, char *unit, char *perpkg,
509 		      char *metric_expr,
510 		      char *metric_name, char *metric_group),
511 	  void *data)
512 {
513 	int err;
514 	size_t size;
515 	jsmntok_t *tokens, *tok;
516 	int i, j, len;
517 	char *map;
518 	char buf[128];
519 
520 	if (!fn)
521 		return -ENOENT;
522 
523 	tokens = parse_json(fn, &map, &size, &len);
524 	if (!tokens)
525 		return -EIO;
526 	EXPECT(tokens->type == JSMN_ARRAY, tokens, "expected top level array");
527 	tok = tokens + 1;
528 	for (i = 0; i < tokens->size; i++) {
529 		char *event = NULL, *desc = NULL, *name = NULL;
530 		char *long_desc = NULL;
531 		char *extra_desc = NULL;
532 		char *pmu = NULL;
533 		char *filter = NULL;
534 		char *perpkg = NULL;
535 		char *unit = NULL;
536 		char *metric_expr = NULL;
537 		char *metric_name = NULL;
538 		char *metric_group = NULL;
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, &name, "", "", val);
574 			} else if (json_streq(map, field, "BriefDescription")) {
575 				addfield(map, &desc, "", "", val);
576 				fixdesc(desc);
577 			} else if (json_streq(map, field,
578 					     "PublicDescription")) {
579 				addfield(map, &long_desc, "", "", val);
580 				fixdesc(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 					pmu = strdup(ppmu);
601 				} else {
602 					if (!pmu)
603 						pmu = strdup("uncore_");
604 					addfield(map, &pmu, "", "", val);
605 					for (s = pmu; *s; s++)
606 						*s = tolower(*s);
607 				}
608 				addfield(map, &desc, ". ", "Unit: ", NULL);
609 				addfield(map, &desc, "", pmu, NULL);
610 				addfield(map, &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, &unit, "", "", val);
615 			} else if (json_streq(map, field, "PerPkg")) {
616 				addfield(map, &perpkg, "", "", val);
617 			} else if (json_streq(map, field, "MetricName")) {
618 				addfield(map, &metric_name, "", "", val);
619 			} else if (json_streq(map, field, "MetricGroup")) {
620 				addfield(map, &metric_group, "", "", val);
621 			} else if (json_streq(map, field, "MetricExpr")) {
622 				addfield(map, &metric_expr, "", "", val);
623 				for (s = metric_expr; *s; s++)
624 					*s = tolower(*s);
625 			} else if (json_streq(map, field, "ArchStdEvent")) {
626 				addfield(map, &arch_std, "", "", val);
627 				for (s = arch_std; *s; s++)
628 					*s = tolower(*s);
629 			}
630 			/* ignore unknown fields */
631 		}
632 		if (precise && desc && !strstr(desc, "(Precise Event)")) {
633 			if (json_streq(map, precise, "2"))
634 				addfield(map, &extra_desc, " ",
635 						"(Must be precise)", NULL);
636 			else
637 				addfield(map, &extra_desc, " ",
638 						"(Precise event)", NULL);
639 		}
640 		snprintf(buf, sizeof buf, "event=%#llx", eventcode);
641 		addfield(map, &event, ",", buf, NULL);
642 		if (desc && extra_desc)
643 			addfield(map, &desc, " ", extra_desc, NULL);
644 		if (long_desc && extra_desc)
645 			addfield(map, &long_desc, " ", extra_desc, NULL);
646 		if (filter)
647 			addfield(map, &event, ",", filter, NULL);
648 		if (msr != NULL)
649 			addfield(map, &event, ",", msr->pname, msrval);
650 		if (name)
651 			fixname(name);
652 
653 		if (arch_std) {
654 			/*
655 			 * An arch standard event is referenced, so try to
656 			 * fixup any unassigned values.
657 			 */
658 			err = try_fixup(fn, arch_std, &event, &desc, &name,
659 					&long_desc, &pmu, &filter, &perpkg,
660 					&unit, &metric_expr, &metric_name,
661 					&metric_group, eventcode);
662 			if (err)
663 				goto free_strings;
664 		}
665 		err = func(data, name, real_event(name, event), desc, long_desc,
666 			   pmu, unit, perpkg, metric_expr, metric_name, metric_group);
667 free_strings:
668 		free(event);
669 		free(desc);
670 		free(name);
671 		free(long_desc);
672 		free(extra_desc);
673 		free(pmu);
674 		free(filter);
675 		free(perpkg);
676 		free(unit);
677 		free(metric_expr);
678 		free(metric_name);
679 		free(metric_group);
680 		free(arch_std);
681 
682 		if (err)
683 			break;
684 		tok += j;
685 	}
686 	EXPECT(tok - tokens == len, tok, "unexpected objects at end");
687 	err = 0;
688 out_free:
689 	free_json(map, size, tokens);
690 	return err;
691 }
692 
693 static char *file_name_to_table_name(const char *fname)
694 {
695 	unsigned int i;
696 	int n;
697 	int c;
698 	char *tblname;
699 
700 
701 	/*
702 	 * Ensure tablename starts with alphabetic character.
703 	 * Derive rest of table name from basename of the JSON file,
704 	 * replacing hyphens and stripping out .json suffix.
705 	 */
706 	n = asprintf(&tblname, "pme_%s", fname);
707 	if (n < 0) {
708 		pr_info("%s: asprintf() error %s for file %s\n", prog,
709 				strerror(errno), fname);
710 		return NULL;
711 	}
712 
713 	for (i = 0; i < strlen(tblname); i++) {
714 		c = tblname[i];
715 
716 		if (c == '-' || c == '/')
717 			tblname[i] = '_';
718 		else if (c == '.') {
719 			tblname[i] = '\0';
720 			break;
721 		} else if (!isalnum(c) && c != '_') {
722 			char *tmp = strdup(fname);
723 			pr_err("%s: Invalid character '%c' in file name %s\n",
724 					prog, c, basename(tmp));
725 			free(tblname);
726 			free(tmp);
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 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 
765 	pr_info("%s: Processing mapfile %s\n", prog, fpath);
766 
767 	line = malloc(n);
768 	if (!line)
769 		return -1;
770 
771 	mapfp = fopen(fpath, "r");
772 	if (!mapfp) {
773 		pr_info("%s: Error %s opening %s\n", prog, strerror(errno),
774 				fpath);
775 		return -1;
776 	}
777 
778 	print_mapping_table_prefix(outfp);
779 
780 	/* Skip first line (header) */
781 	p = fgets(line, n, mapfp);
782 	if (!p)
783 		goto out;
784 
785 	line_num = 1;
786 	while (1) {
787 		char *cpuid, *version, *type, *fname;
788 
789 		line_num++;
790 		p = fgets(line, n, mapfp);
791 		if (!p)
792 			break;
793 
794 		if (line[0] == '#' || line[0] == '\n')
795 			continue;
796 
797 		if (line[strlen(line)-1] != '\n') {
798 			/* TODO Deal with lines longer than 16K */
799 			pr_info("%s: Mapfile %s: line %d too long, aborting\n",
800 					prog, fpath, line_num);
801 			return -1;
802 		}
803 		line[strlen(line)-1] = '\0';
804 
805 		cpuid = fixregex(strtok_r(p, ",", &save));
806 		version = strtok_r(NULL, ",", &save);
807 		fname = strtok_r(NULL, ",", &save);
808 		type = strtok_r(NULL, ",", &save);
809 
810 		tblname = file_name_to_table_name(fname);
811 		fprintf(outfp, "{\n");
812 		fprintf(outfp, "\t.cpuid = \"%s\",\n", cpuid);
813 		fprintf(outfp, "\t.version = \"%s\",\n", version);
814 		fprintf(outfp, "\t.type = \"%s\",\n", type);
815 
816 		/*
817 		 * CHECK: We can't use the type (eg "core") field in the
818 		 * table name. For us to do that, we need to somehow tweak
819 		 * the other caller of file_name_to_table(), process_json()
820 		 * to determine the type. process_json() file has no way
821 		 * of knowing these are "core" events unless file name has
822 		 * core in it. If filename has core in it, we can safely
823 		 * ignore the type field here also.
824 		 */
825 		fprintf(outfp, "\t.table = %s\n", tblname);
826 		fprintf(outfp, "},\n");
827 	}
828 
829 out:
830 	print_mapping_table_suffix(outfp);
831 	return 0;
832 }
833 
834 /*
835  * If we fail to locate/process JSON and map files, create a NULL mapping
836  * table. This would at least allow perf to build even if we can't find/use
837  * the aliases.
838  */
839 static void create_empty_mapping(const char *output_file)
840 {
841 	FILE *outfp;
842 
843 	pr_info("%s: Creating empty pmu_events_map[] table\n", prog);
844 
845 	/* Truncate file to clear any partial writes to it */
846 	outfp = fopen(output_file, "w");
847 	if (!outfp) {
848 		perror("fopen()");
849 		_Exit(1);
850 	}
851 
852 	fprintf(outfp, "#include \"pmu-events/pmu-events.h\"\n");
853 	print_mapping_table_prefix(outfp);
854 	print_mapping_table_suffix(outfp);
855 	fclose(outfp);
856 }
857 
858 static int get_maxfds(void)
859 {
860 	struct rlimit rlim;
861 
862 	if (getrlimit(RLIMIT_NOFILE, &rlim) == 0) {
863 		if (rlim.rlim_max == RLIM_INFINITY)
864 			return 512;
865 		return min((unsigned)rlim.rlim_max / 2, 512);
866 	}
867 
868 	return 512;
869 }
870 
871 /*
872  * nftw() doesn't let us pass an argument to the processing function,
873  * so use a global variables.
874  */
875 static FILE *eventsfp;
876 static char *mapfile;
877 
878 static int is_leaf_dir(const char *fpath)
879 {
880 	DIR *d;
881 	struct dirent *dir;
882 	int res = 1;
883 
884 	d = opendir(fpath);
885 	if (!d)
886 		return 0;
887 
888 	while ((dir = readdir(d)) != NULL) {
889 		if (!strcmp(dir->d_name, ".") || !strcmp(dir->d_name, ".."))
890 			continue;
891 
892 		if (dir->d_type == DT_DIR) {
893 			res = 0;
894 			break;
895 		} else if (dir->d_type == DT_UNKNOWN) {
896 			char path[PATH_MAX];
897 			struct stat st;
898 
899 			sprintf(path, "%s/%s", fpath, dir->d_name);
900 			if (stat(path, &st))
901 				break;
902 
903 			if (S_ISDIR(st.st_mode)) {
904 				res = 0;
905 				break;
906 			}
907 		}
908 	}
909 
910 	closedir(d);
911 
912 	return res;
913 }
914 
915 static int is_json_file(const char *name)
916 {
917 	const char *suffix;
918 
919 	if (strlen(name) < 5)
920 		return 0;
921 
922 	suffix = name + strlen(name) - 5;
923 
924 	if (strncmp(suffix, ".json", 5) == 0)
925 		return 1;
926 	return 0;
927 }
928 
929 static int preprocess_arch_std_files(const char *fpath, const struct stat *sb,
930 				int typeflag, struct FTW *ftwbuf)
931 {
932 	int level = ftwbuf->level;
933 	int is_file = typeflag == FTW_F;
934 
935 	if (level == 1 && is_file && is_json_file(fpath))
936 		return json_events(fpath, save_arch_std_events, (void *)(uintptr_t)sb);
937 
938 	return 0;
939 }
940 
941 static int process_one_file(const char *fpath, const struct stat *sb,
942 			    int typeflag, struct FTW *ftwbuf)
943 {
944 	char *tblname;
945 	const char *bname;
946 	int is_dir  = typeflag == FTW_D;
947 	int is_file = typeflag == FTW_F;
948 	int level   = ftwbuf->level;
949 	int err = 0;
950 
951 	if (level == 2 && is_dir) {
952 		/*
953 		 * For level 2 directory, bname will include parent name,
954 		 * like vendor/platform. So search back from platform dir
955 		 * to find this.
956 		 */
957 		bname = fpath + ftwbuf->base - 2;
958 		for (;;) {
959 			if (*bname == '/')
960 				break;
961 			bname--;
962 		}
963 		bname++;
964 	} else
965 		bname = fpath + ftwbuf->base;
966 
967 	pr_debug("%s %d %7jd %-20s %s\n",
968 		 is_file ? "f" : is_dir ? "d" : "x",
969 		 level, sb->st_size, bname, fpath);
970 
971 	/* base dir or too deep */
972 	if (level == 0 || level > 3)
973 		return 0;
974 
975 
976 	/* model directory, reset topic */
977 	if ((level == 1 && is_dir && is_leaf_dir(fpath)) ||
978 	    (level == 2 && is_dir)) {
979 		if (close_table)
980 			print_events_table_suffix(eventsfp);
981 
982 		/*
983 		 * Drop file name suffix. Replace hyphens with underscores.
984 		 * Fail if file name contains any alphanum characters besides
985 		 * underscores.
986 		 */
987 		tblname = file_name_to_table_name(bname);
988 		if (!tblname) {
989 			pr_info("%s: Error determining table name for %s\n", prog,
990 				bname);
991 			return -1;
992 		}
993 
994 		print_events_table_prefix(eventsfp, tblname);
995 		return 0;
996 	}
997 
998 	/*
999 	 * Save the mapfile name for now. We will process mapfile
1000 	 * after processing all JSON files (so we can write out the
1001 	 * mapping table after all PMU events tables).
1002 	 *
1003 	 */
1004 	if (level == 1 && is_file) {
1005 		if (!strcmp(bname, "mapfile.csv")) {
1006 			mapfile = strdup(fpath);
1007 			return 0;
1008 		}
1009 
1010 		pr_info("%s: Ignoring file %s\n", prog, fpath);
1011 		return 0;
1012 	}
1013 
1014 	/*
1015 	 * If the file name does not have a .json extension,
1016 	 * ignore it. It could be a readme.txt for instance.
1017 	 */
1018 	if (is_file) {
1019 		if (!is_json_file(bname)) {
1020 			pr_info("%s: Ignoring file without .json suffix %s\n", prog,
1021 				fpath);
1022 			return 0;
1023 		}
1024 	}
1025 
1026 	if (level > 1 && add_topic(bname))
1027 		return -ENOMEM;
1028 
1029 	/*
1030 	 * Assume all other files are JSON files.
1031 	 *
1032 	 * If mapfile refers to 'power7_core.json', we create a table
1033 	 * named 'power7_core'. Any inconsistencies between the mapfile
1034 	 * and directory tree could result in build failure due to table
1035 	 * names not being found.
1036 	 *
1037 	 * Atleast for now, be strict with processing JSON file names.
1038 	 * i.e. if JSON file name cannot be mapped to C-style table name,
1039 	 * fail.
1040 	 */
1041 	if (is_file) {
1042 		struct perf_entry_data data = {
1043 			.topic = get_topic(),
1044 			.outfp = eventsfp,
1045 		};
1046 
1047 		err = json_events(fpath, print_events_table_entry, &data);
1048 
1049 		free(data.topic);
1050 	}
1051 
1052 	return err;
1053 }
1054 
1055 #ifndef PATH_MAX
1056 #define PATH_MAX	4096
1057 #endif
1058 
1059 /*
1060  * Starting in directory 'start_dirname', find the "mapfile.csv" and
1061  * the set of JSON files for the architecture 'arch'.
1062  *
1063  * From each JSON file, create a C-style "PMU events table" from the
1064  * JSON file (see struct pmu_event).
1065  *
1066  * From the mapfile, create a mapping between the CPU revisions and
1067  * PMU event tables (see struct pmu_events_map).
1068  *
1069  * Write out the PMU events tables and the mapping table to pmu-event.c.
1070  */
1071 int main(int argc, char *argv[])
1072 {
1073 	int rc;
1074 	int maxfds;
1075 	char ldirname[PATH_MAX];
1076 
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: %s\n",
1128 			prog, ldirname, strerror(errno));
1129 		goto empty_map;
1130 	} else if (rc < 0) {
1131 		/* Make build fail */
1132 		free_arch_std_events();
1133 		return 1;
1134 	} else if (rc) {
1135 		goto empty_map;
1136 	}
1137 
1138 	rc = nftw(ldirname, process_one_file, maxfds, 0);
1139 	if (rc && verbose) {
1140 		pr_info("%s: Error walking file tree %s\n", prog, ldirname);
1141 		goto empty_map;
1142 	} else if (rc < 0) {
1143 		/* Make build fail */
1144 		free_arch_std_events();
1145 		return 1;
1146 	} else if (rc) {
1147 		goto empty_map;
1148 	}
1149 
1150 	if (close_table)
1151 		print_events_table_suffix(eventsfp);
1152 
1153 	if (!mapfile) {
1154 		pr_info("%s: No CPU->JSON mapping?\n", prog);
1155 		goto empty_map;
1156 	}
1157 
1158 	if (process_mapfile(eventsfp, mapfile)) {
1159 		pr_info("%s: Error processing mapfile %s\n", prog, mapfile);
1160 		/* Make build fail */
1161 		return 1;
1162 	}
1163 
1164 	return 0;
1165 
1166 empty_map:
1167 	fclose(eventsfp);
1168 	create_empty_mapping(output_file);
1169 	free_arch_std_events();
1170 	return 0;
1171 }
1172