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