1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * trace_events_synth - synthetic trace events
4  *
5  * Copyright (C) 2015, 2020 Tom Zanussi <[email protected]>
6  */
7 
8 #include <linux/module.h>
9 #include <linux/kallsyms.h>
10 #include <linux/security.h>
11 #include <linux/mutex.h>
12 #include <linux/slab.h>
13 #include <linux/stacktrace.h>
14 #include <linux/rculist.h>
15 #include <linux/tracefs.h>
16 
17 /* for gfp flag names */
18 #include <linux/trace_events.h>
19 #include <trace/events/mmflags.h>
20 #include "trace_probe.h"
21 #include "trace_probe_kernel.h"
22 
23 #include "trace_synth.h"
24 
25 #undef ERRORS
26 #define ERRORS	\
27 	C(BAD_NAME,		"Illegal name"),		\
28 	C(INVALID_CMD,		"Command must be of the form: <name> field[;field] ..."),\
29 	C(INVALID_DYN_CMD,	"Command must be of the form: s or -:[synthetic/]<name> field[;field] ..."),\
30 	C(EVENT_EXISTS,		"Event already exists"),	\
31 	C(TOO_MANY_FIELDS,	"Too many fields"),		\
32 	C(INCOMPLETE_TYPE,	"Incomplete type"),		\
33 	C(INVALID_TYPE,		"Invalid type"),		\
34 	C(INVALID_FIELD,        "Invalid field"),		\
35 	C(INVALID_ARRAY_SPEC,	"Invalid array specification"),
36 
37 #undef C
38 #define C(a, b)		SYNTH_ERR_##a
39 
40 enum { ERRORS };
41 
42 #undef C
43 #define C(a, b)		b
44 
45 static const char *err_text[] = { ERRORS };
46 
47 static DEFINE_MUTEX(lastcmd_mutex);
48 static char *last_cmd;
49 
errpos(const char * str)50 static int errpos(const char *str)
51 {
52 	guard(mutex)(&lastcmd_mutex);
53 	if (!str || !last_cmd)
54 		return 0;
55 
56 	return err_pos(last_cmd, str);
57 }
58 
last_cmd_set(const char * str)59 static void last_cmd_set(const char *str)
60 {
61 	if (!str)
62 		return;
63 
64 	mutex_lock(&lastcmd_mutex);
65 	kfree(last_cmd);
66 	last_cmd = kstrdup(str, GFP_KERNEL);
67 	mutex_unlock(&lastcmd_mutex);
68 }
69 
synth_err(u8 err_type,u16 err_pos)70 static void synth_err(u8 err_type, u16 err_pos)
71 {
72 	guard(mutex)(&lastcmd_mutex);
73 	if (!last_cmd)
74 		return;
75 
76 	tracing_log_err(NULL, "synthetic_events", last_cmd, err_text,
77 			err_type, err_pos);
78 }
79 
80 static int create_synth_event(const char *raw_command);
81 static int synth_event_show(struct seq_file *m, struct dyn_event *ev);
82 static int synth_event_release(struct dyn_event *ev);
83 static bool synth_event_is_busy(struct dyn_event *ev);
84 static bool synth_event_match(const char *system, const char *event,
85 			int argc, const char **argv, struct dyn_event *ev);
86 
87 static struct dyn_event_operations synth_event_ops = {
88 	.create = create_synth_event,
89 	.show = synth_event_show,
90 	.is_busy = synth_event_is_busy,
91 	.free = synth_event_release,
92 	.match = synth_event_match,
93 };
94 
is_synth_event(struct dyn_event * ev)95 static bool is_synth_event(struct dyn_event *ev)
96 {
97 	return ev->ops == &synth_event_ops;
98 }
99 
to_synth_event(struct dyn_event * ev)100 static struct synth_event *to_synth_event(struct dyn_event *ev)
101 {
102 	return container_of(ev, struct synth_event, devent);
103 }
104 
synth_event_is_busy(struct dyn_event * ev)105 static bool synth_event_is_busy(struct dyn_event *ev)
106 {
107 	struct synth_event *event = to_synth_event(ev);
108 
109 	return event->ref != 0;
110 }
111 
synth_event_match(const char * system,const char * event,int argc,const char ** argv,struct dyn_event * ev)112 static bool synth_event_match(const char *system, const char *event,
113 			int argc, const char **argv, struct dyn_event *ev)
114 {
115 	struct synth_event *sev = to_synth_event(ev);
116 
117 	return strcmp(sev->name, event) == 0 &&
118 		(!system || strcmp(system, SYNTH_SYSTEM) == 0);
119 }
120 
121 struct synth_trace_event {
122 	struct trace_entry	ent;
123 	union trace_synth_field	fields[];
124 };
125 
synth_event_define_fields(struct trace_event_call * call)126 static int synth_event_define_fields(struct trace_event_call *call)
127 {
128 	struct synth_trace_event trace;
129 	int offset = offsetof(typeof(trace), fields);
130 	struct synth_event *event = call->data;
131 	unsigned int i, size, n_u64;
132 	char *name, *type;
133 	bool is_signed;
134 	int ret = 0;
135 
136 	for (i = 0, n_u64 = 0; i < event->n_fields; i++) {
137 		size = event->fields[i]->size;
138 		is_signed = event->fields[i]->is_signed;
139 		type = event->fields[i]->type;
140 		name = event->fields[i]->name;
141 		ret = trace_define_field(call, type, name, offset, size,
142 					 is_signed, FILTER_OTHER);
143 		if (ret)
144 			break;
145 
146 		event->fields[i]->offset = n_u64;
147 
148 		if (event->fields[i]->is_string && !event->fields[i]->is_dynamic) {
149 			offset += STR_VAR_LEN_MAX;
150 			n_u64 += STR_VAR_LEN_MAX / sizeof(u64);
151 		} else {
152 			offset += sizeof(u64);
153 			n_u64++;
154 		}
155 	}
156 
157 	event->n_u64 = n_u64;
158 
159 	return ret;
160 }
161 
synth_field_signed(char * type)162 static bool synth_field_signed(char *type)
163 {
164 	if (str_has_prefix(type, "u"))
165 		return false;
166 	if (strcmp(type, "gfp_t") == 0)
167 		return false;
168 
169 	return true;
170 }
171 
synth_field_is_string(char * type)172 static int synth_field_is_string(char *type)
173 {
174 	if (strstr(type, "char[") != NULL)
175 		return true;
176 
177 	return false;
178 }
179 
synth_field_is_stack(char * type)180 static int synth_field_is_stack(char *type)
181 {
182 	if (strstr(type, "long[") != NULL)
183 		return true;
184 
185 	return false;
186 }
187 
synth_field_string_size(char * type)188 static int synth_field_string_size(char *type)
189 {
190 	char buf[4], *end, *start;
191 	unsigned int len;
192 	int size, err;
193 
194 	start = strstr(type, "char[");
195 	if (start == NULL)
196 		return -EINVAL;
197 	start += sizeof("char[") - 1;
198 
199 	end = strchr(type, ']');
200 	if (!end || end < start || type + strlen(type) > end + 1)
201 		return -EINVAL;
202 
203 	len = end - start;
204 	if (len > 3)
205 		return -EINVAL;
206 
207 	if (len == 0)
208 		return 0; /* variable-length string */
209 
210 	strncpy(buf, start, len);
211 	buf[len] = '\0';
212 
213 	err = kstrtouint(buf, 0, &size);
214 	if (err)
215 		return err;
216 
217 	if (size > STR_VAR_LEN_MAX)
218 		return -EINVAL;
219 
220 	return size;
221 }
222 
synth_field_size(char * type)223 static int synth_field_size(char *type)
224 {
225 	int size = 0;
226 
227 	if (strcmp(type, "s64") == 0)
228 		size = sizeof(s64);
229 	else if (strcmp(type, "u64") == 0)
230 		size = sizeof(u64);
231 	else if (strcmp(type, "s32") == 0)
232 		size = sizeof(s32);
233 	else if (strcmp(type, "u32") == 0)
234 		size = sizeof(u32);
235 	else if (strcmp(type, "s16") == 0)
236 		size = sizeof(s16);
237 	else if (strcmp(type, "u16") == 0)
238 		size = sizeof(u16);
239 	else if (strcmp(type, "s8") == 0)
240 		size = sizeof(s8);
241 	else if (strcmp(type, "u8") == 0)
242 		size = sizeof(u8);
243 	else if (strcmp(type, "char") == 0)
244 		size = sizeof(char);
245 	else if (strcmp(type, "unsigned char") == 0)
246 		size = sizeof(unsigned char);
247 	else if (strcmp(type, "int") == 0)
248 		size = sizeof(int);
249 	else if (strcmp(type, "unsigned int") == 0)
250 		size = sizeof(unsigned int);
251 	else if (strcmp(type, "long") == 0)
252 		size = sizeof(long);
253 	else if (strcmp(type, "unsigned long") == 0)
254 		size = sizeof(unsigned long);
255 	else if (strcmp(type, "bool") == 0)
256 		size = sizeof(bool);
257 	else if (strcmp(type, "pid_t") == 0)
258 		size = sizeof(pid_t);
259 	else if (strcmp(type, "gfp_t") == 0)
260 		size = sizeof(gfp_t);
261 	else if (synth_field_is_string(type))
262 		size = synth_field_string_size(type);
263 	else if (synth_field_is_stack(type))
264 		size = 0;
265 
266 	return size;
267 }
268 
synth_field_fmt(char * type)269 static const char *synth_field_fmt(char *type)
270 {
271 	const char *fmt = "%llu";
272 
273 	if (strcmp(type, "s64") == 0)
274 		fmt = "%lld";
275 	else if (strcmp(type, "u64") == 0)
276 		fmt = "%llu";
277 	else if (strcmp(type, "s32") == 0)
278 		fmt = "%d";
279 	else if (strcmp(type, "u32") == 0)
280 		fmt = "%u";
281 	else if (strcmp(type, "s16") == 0)
282 		fmt = "%d";
283 	else if (strcmp(type, "u16") == 0)
284 		fmt = "%u";
285 	else if (strcmp(type, "s8") == 0)
286 		fmt = "%d";
287 	else if (strcmp(type, "u8") == 0)
288 		fmt = "%u";
289 	else if (strcmp(type, "char") == 0)
290 		fmt = "%d";
291 	else if (strcmp(type, "unsigned char") == 0)
292 		fmt = "%u";
293 	else if (strcmp(type, "int") == 0)
294 		fmt = "%d";
295 	else if (strcmp(type, "unsigned int") == 0)
296 		fmt = "%u";
297 	else if (strcmp(type, "long") == 0)
298 		fmt = "%ld";
299 	else if (strcmp(type, "unsigned long") == 0)
300 		fmt = "%lu";
301 	else if (strcmp(type, "bool") == 0)
302 		fmt = "%d";
303 	else if (strcmp(type, "pid_t") == 0)
304 		fmt = "%d";
305 	else if (strcmp(type, "gfp_t") == 0)
306 		fmt = "%x";
307 	else if (synth_field_is_string(type))
308 		fmt = "%s";
309 	else if (synth_field_is_stack(type))
310 		fmt = "%s";
311 
312 	return fmt;
313 }
314 
print_synth_event_num_val(struct trace_seq * s,char * print_fmt,char * name,int size,union trace_synth_field * val,char * space)315 static void print_synth_event_num_val(struct trace_seq *s,
316 				      char *print_fmt, char *name,
317 				      int size, union trace_synth_field *val, char *space)
318 {
319 	switch (size) {
320 	case 1:
321 		trace_seq_printf(s, print_fmt, name, val->as_u8, space);
322 		break;
323 
324 	case 2:
325 		trace_seq_printf(s, print_fmt, name, val->as_u16, space);
326 		break;
327 
328 	case 4:
329 		trace_seq_printf(s, print_fmt, name, val->as_u32, space);
330 		break;
331 
332 	default:
333 		trace_seq_printf(s, print_fmt, name, val->as_u64, space);
334 		break;
335 	}
336 }
337 
print_synth_event(struct trace_iterator * iter,int flags,struct trace_event * event)338 static enum print_line_t print_synth_event(struct trace_iterator *iter,
339 					   int flags,
340 					   struct trace_event *event)
341 {
342 	struct trace_array *tr = iter->tr;
343 	struct trace_seq *s = &iter->seq;
344 	struct synth_trace_event *entry;
345 	struct synth_event *se;
346 	unsigned int i, j, n_u64;
347 	char print_fmt[32];
348 	const char *fmt;
349 
350 	entry = (struct synth_trace_event *)iter->ent;
351 	se = container_of(event, struct synth_event, call.event);
352 
353 	trace_seq_printf(s, "%s: ", se->name);
354 
355 	for (i = 0, n_u64 = 0; i < se->n_fields; i++) {
356 		if (trace_seq_has_overflowed(s))
357 			goto end;
358 
359 		fmt = synth_field_fmt(se->fields[i]->type);
360 
361 		/* parameter types */
362 		if (tr && tr->trace_flags & TRACE_ITER_VERBOSE)
363 			trace_seq_printf(s, "%s ", fmt);
364 
365 		snprintf(print_fmt, sizeof(print_fmt), "%%s=%s%%s", fmt);
366 
367 		/* parameter values */
368 		if (se->fields[i]->is_string) {
369 			if (se->fields[i]->is_dynamic) {
370 				union trace_synth_field *data = &entry->fields[n_u64];
371 
372 				trace_seq_printf(s, print_fmt, se->fields[i]->name,
373 						 (char *)entry + data->as_dynamic.offset,
374 						 i == se->n_fields - 1 ? "" : " ");
375 				n_u64++;
376 			} else {
377 				trace_seq_printf(s, print_fmt, se->fields[i]->name,
378 						 STR_VAR_LEN_MAX,
379 						 (char *)&entry->fields[n_u64].as_u64,
380 						 i == se->n_fields - 1 ? "" : " ");
381 				n_u64 += STR_VAR_LEN_MAX / sizeof(u64);
382 			}
383 		} else if (se->fields[i]->is_stack) {
384 			union trace_synth_field *data = &entry->fields[n_u64];
385 			unsigned long *p = (void *)entry + data->as_dynamic.offset;
386 
387 			trace_seq_printf(s, "%s=STACK:\n", se->fields[i]->name);
388 			for (j = 1; j < data->as_dynamic.len / sizeof(long); j++)
389 				trace_seq_printf(s, "=> %pS\n", (void *)p[j]);
390 			n_u64++;
391 		} else {
392 			struct trace_print_flags __flags[] = {
393 			    __def_gfpflag_names, {-1, NULL} };
394 			char *space = (i == se->n_fields - 1 ? "" : " ");
395 
396 			print_synth_event_num_val(s, print_fmt,
397 						  se->fields[i]->name,
398 						  se->fields[i]->size,
399 						  &entry->fields[n_u64],
400 						  space);
401 
402 			if (strcmp(se->fields[i]->type, "gfp_t") == 0) {
403 				trace_seq_puts(s, " (");
404 				trace_print_flags_seq(s, "|",
405 						      entry->fields[n_u64].as_u64,
406 						      __flags);
407 				trace_seq_putc(s, ')');
408 			}
409 			n_u64++;
410 		}
411 	}
412 end:
413 	trace_seq_putc(s, '\n');
414 
415 	return trace_handle_return(s);
416 }
417 
418 static struct trace_event_functions synth_event_funcs = {
419 	.trace		= print_synth_event
420 };
421 
trace_string(struct synth_trace_event * entry,struct synth_event * event,char * str_val,bool is_dynamic,unsigned int data_size,unsigned int * n_u64)422 static unsigned int trace_string(struct synth_trace_event *entry,
423 				 struct synth_event *event,
424 				 char *str_val,
425 				 bool is_dynamic,
426 				 unsigned int data_size,
427 				 unsigned int *n_u64)
428 {
429 	unsigned int len = 0;
430 	char *str_field;
431 	int ret;
432 
433 	if (is_dynamic) {
434 		union trace_synth_field *data = &entry->fields[*n_u64];
435 
436 		len = fetch_store_strlen((unsigned long)str_val);
437 		data->as_dynamic.offset = struct_size(entry, fields, event->n_u64) + data_size;
438 		data->as_dynamic.len = len;
439 
440 		ret = fetch_store_string((unsigned long)str_val, &entry->fields[*n_u64], entry);
441 
442 		(*n_u64)++;
443 	} else {
444 		str_field = (char *)&entry->fields[*n_u64].as_u64;
445 
446 #ifdef CONFIG_ARCH_HAS_NON_OVERLAPPING_ADDRESS_SPACE
447 		if ((unsigned long)str_val < TASK_SIZE)
448 			ret = strncpy_from_user_nofault(str_field, (const void __user *)str_val, STR_VAR_LEN_MAX);
449 		else
450 #endif
451 			ret = strncpy_from_kernel_nofault(str_field, str_val, STR_VAR_LEN_MAX);
452 
453 		if (ret < 0)
454 			strcpy(str_field, FAULT_STRING);
455 
456 		(*n_u64) += STR_VAR_LEN_MAX / sizeof(u64);
457 	}
458 
459 	return len;
460 }
461 
trace_stack(struct synth_trace_event * entry,struct synth_event * event,long * stack,unsigned int data_size,unsigned int * n_u64)462 static unsigned int trace_stack(struct synth_trace_event *entry,
463 				 struct synth_event *event,
464 				 long *stack,
465 				 unsigned int data_size,
466 				 unsigned int *n_u64)
467 {
468 	union trace_synth_field *data = &entry->fields[*n_u64];
469 	unsigned int len;
470 	u32 data_offset;
471 	void *data_loc;
472 
473 	data_offset = struct_size(entry, fields, event->n_u64);
474 	data_offset += data_size;
475 
476 	for (len = 0; len < HIST_STACKTRACE_DEPTH; len++) {
477 		if (!stack[len])
478 			break;
479 	}
480 
481 	len *= sizeof(long);
482 
483 	/* Find the dynamic section to copy the stack into. */
484 	data_loc = (void *)entry + data_offset;
485 	memcpy(data_loc, stack, len);
486 
487 	/* Fill in the field that holds the offset/len combo */
488 
489 	data->as_dynamic.offset = data_offset;
490 	data->as_dynamic.len = len;
491 
492 	(*n_u64)++;
493 
494 	return len;
495 }
496 
trace_event_raw_event_synth(void * __data,u64 * var_ref_vals,unsigned int * var_ref_idx)497 static notrace void trace_event_raw_event_synth(void *__data,
498 						u64 *var_ref_vals,
499 						unsigned int *var_ref_idx)
500 {
501 	unsigned int i, n_u64, val_idx, len, data_size = 0;
502 	struct trace_event_file *trace_file = __data;
503 	struct synth_trace_event *entry;
504 	struct trace_event_buffer fbuffer;
505 	struct trace_buffer *buffer;
506 	struct synth_event *event;
507 	int fields_size = 0;
508 
509 	event = trace_file->event_call->data;
510 
511 	if (trace_trigger_soft_disabled(trace_file))
512 		return;
513 
514 	fields_size = event->n_u64 * sizeof(u64);
515 
516 	for (i = 0; i < event->n_dynamic_fields; i++) {
517 		unsigned int field_pos = event->dynamic_fields[i]->field_pos;
518 		char *str_val;
519 
520 		val_idx = var_ref_idx[field_pos];
521 		str_val = (char *)(long)var_ref_vals[val_idx];
522 
523 		if (event->dynamic_fields[i]->is_stack) {
524 			/* reserve one extra element for size */
525 			len = *((unsigned long *)str_val) + 1;
526 			len *= sizeof(unsigned long);
527 		} else {
528 			len = fetch_store_strlen((unsigned long)str_val);
529 		}
530 
531 		fields_size += len;
532 	}
533 
534 	/*
535 	 * Avoid ring buffer recursion detection, as this event
536 	 * is being performed within another event.
537 	 */
538 	buffer = trace_file->tr->array_buffer.buffer;
539 	ring_buffer_nest_start(buffer);
540 
541 	entry = trace_event_buffer_reserve(&fbuffer, trace_file,
542 					   sizeof(*entry) + fields_size);
543 	if (!entry)
544 		goto out;
545 
546 	for (i = 0, n_u64 = 0; i < event->n_fields; i++) {
547 		val_idx = var_ref_idx[i];
548 		if (event->fields[i]->is_string) {
549 			char *str_val = (char *)(long)var_ref_vals[val_idx];
550 
551 			len = trace_string(entry, event, str_val,
552 					   event->fields[i]->is_dynamic,
553 					   data_size, &n_u64);
554 			data_size += len; /* only dynamic string increments */
555 		} else if (event->fields[i]->is_stack) {
556 			long *stack = (long *)(long)var_ref_vals[val_idx];
557 
558 			len = trace_stack(entry, event, stack,
559 					   data_size, &n_u64);
560 			data_size += len;
561 		} else {
562 			struct synth_field *field = event->fields[i];
563 			u64 val = var_ref_vals[val_idx];
564 
565 			switch (field->size) {
566 			case 1:
567 				entry->fields[n_u64].as_u8 = (u8)val;
568 				break;
569 
570 			case 2:
571 				entry->fields[n_u64].as_u16 = (u16)val;
572 				break;
573 
574 			case 4:
575 				entry->fields[n_u64].as_u32 = (u32)val;
576 				break;
577 
578 			default:
579 				entry->fields[n_u64].as_u64 = val;
580 				break;
581 			}
582 			n_u64++;
583 		}
584 	}
585 
586 	trace_event_buffer_commit(&fbuffer);
587 out:
588 	ring_buffer_nest_end(buffer);
589 }
590 
free_synth_event_print_fmt(struct trace_event_call * call)591 static void free_synth_event_print_fmt(struct trace_event_call *call)
592 {
593 	if (call) {
594 		kfree(call->print_fmt);
595 		call->print_fmt = NULL;
596 	}
597 }
598 
__set_synth_event_print_fmt(struct synth_event * event,char * buf,int len)599 static int __set_synth_event_print_fmt(struct synth_event *event,
600 				       char *buf, int len)
601 {
602 	const char *fmt;
603 	int pos = 0;
604 	int i;
605 
606 	/* When len=0, we just calculate the needed length */
607 #define LEN_OR_ZERO (len ? len - pos : 0)
608 
609 	pos += snprintf(buf + pos, LEN_OR_ZERO, "\"");
610 	for (i = 0; i < event->n_fields; i++) {
611 		fmt = synth_field_fmt(event->fields[i]->type);
612 		pos += snprintf(buf + pos, LEN_OR_ZERO, "%s=%s%s",
613 				event->fields[i]->name, fmt,
614 				i == event->n_fields - 1 ? "" : ", ");
615 	}
616 	pos += snprintf(buf + pos, LEN_OR_ZERO, "\"");
617 
618 	for (i = 0; i < event->n_fields; i++) {
619 		if (event->fields[i]->is_string &&
620 		    event->fields[i]->is_dynamic)
621 			pos += snprintf(buf + pos, LEN_OR_ZERO,
622 				", __get_str(%s)", event->fields[i]->name);
623 		else if (event->fields[i]->is_stack)
624 			pos += snprintf(buf + pos, LEN_OR_ZERO,
625 				", __get_stacktrace(%s)", event->fields[i]->name);
626 		else
627 			pos += snprintf(buf + pos, LEN_OR_ZERO,
628 					", REC->%s", event->fields[i]->name);
629 	}
630 
631 #undef LEN_OR_ZERO
632 
633 	/* return the length of print_fmt */
634 	return pos;
635 }
636 
set_synth_event_print_fmt(struct trace_event_call * call)637 static int set_synth_event_print_fmt(struct trace_event_call *call)
638 {
639 	struct synth_event *event = call->data;
640 	char *print_fmt;
641 	int len;
642 
643 	/* First: called with 0 length to calculate the needed length */
644 	len = __set_synth_event_print_fmt(event, NULL, 0);
645 
646 	print_fmt = kmalloc(len + 1, GFP_KERNEL);
647 	if (!print_fmt)
648 		return -ENOMEM;
649 
650 	/* Second: actually write the @print_fmt */
651 	__set_synth_event_print_fmt(event, print_fmt, len + 1);
652 	call->print_fmt = print_fmt;
653 
654 	return 0;
655 }
656 
free_synth_field(struct synth_field * field)657 static void free_synth_field(struct synth_field *field)
658 {
659 	kfree(field->type);
660 	kfree(field->name);
661 	kfree(field);
662 }
663 
check_field_version(const char * prefix,const char * field_type,const char * field_name)664 static int check_field_version(const char *prefix, const char *field_type,
665 			       const char *field_name)
666 {
667 	/*
668 	 * For backward compatibility, the old synthetic event command
669 	 * format did not require semicolons, and in order to not
670 	 * break user space, that old format must still work. If a new
671 	 * feature is added, then the format that uses the new feature
672 	 * will be required to have semicolons, as nothing that uses
673 	 * the old format would be using the new, yet to be created,
674 	 * feature. When a new feature is added, this will detect it,
675 	 * and return a number greater than 1, and require the format
676 	 * to use semicolons.
677 	 */
678 	return 1;
679 }
680 
parse_synth_field(int argc,char ** argv,int * consumed,int * field_version)681 static struct synth_field *parse_synth_field(int argc, char **argv,
682 					     int *consumed, int *field_version)
683 {
684 	const char *prefix = NULL, *field_type = argv[0], *field_name, *array;
685 	struct synth_field *field;
686 	int len, ret = -ENOMEM;
687 	struct seq_buf s;
688 	ssize_t size;
689 
690 	if (!strcmp(field_type, "unsigned")) {
691 		if (argc < 3) {
692 			synth_err(SYNTH_ERR_INCOMPLETE_TYPE, errpos(field_type));
693 			return ERR_PTR(-EINVAL);
694 		}
695 		prefix = "unsigned ";
696 		field_type = argv[1];
697 		field_name = argv[2];
698 		*consumed += 3;
699 	} else {
700 		field_name = argv[1];
701 		*consumed += 2;
702 	}
703 
704 	if (!field_name) {
705 		synth_err(SYNTH_ERR_INVALID_FIELD, errpos(field_type));
706 		return ERR_PTR(-EINVAL);
707 	}
708 
709 	*field_version = check_field_version(prefix, field_type, field_name);
710 
711 	field = kzalloc(sizeof(*field), GFP_KERNEL);
712 	if (!field)
713 		return ERR_PTR(-ENOMEM);
714 
715 	len = strlen(field_name);
716 	array = strchr(field_name, '[');
717 	if (array)
718 		len -= strlen(array);
719 
720 	field->name = kmemdup_nul(field_name, len, GFP_KERNEL);
721 	if (!field->name)
722 		goto free;
723 
724 	if (!is_good_name(field->name)) {
725 		synth_err(SYNTH_ERR_BAD_NAME, errpos(field_name));
726 		ret = -EINVAL;
727 		goto free;
728 	}
729 
730 	len = strlen(field_type) + 1;
731 
732 	if (array)
733 		len += strlen(array);
734 
735 	if (prefix)
736 		len += strlen(prefix);
737 
738 	field->type = kzalloc(len, GFP_KERNEL);
739 	if (!field->type)
740 		goto free;
741 
742 	seq_buf_init(&s, field->type, len);
743 	if (prefix)
744 		seq_buf_puts(&s, prefix);
745 	seq_buf_puts(&s, field_type);
746 	if (array)
747 		seq_buf_puts(&s, array);
748 	if (WARN_ON_ONCE(!seq_buf_buffer_left(&s)))
749 		goto free;
750 
751 	s.buffer[s.len] = '\0';
752 
753 	size = synth_field_size(field->type);
754 	if (size < 0) {
755 		if (array)
756 			synth_err(SYNTH_ERR_INVALID_ARRAY_SPEC, errpos(field_name));
757 		else
758 			synth_err(SYNTH_ERR_INVALID_TYPE, errpos(field_type));
759 		ret = -EINVAL;
760 		goto free;
761 	} else if (size == 0) {
762 		if (synth_field_is_string(field->type) ||
763 		    synth_field_is_stack(field->type)) {
764 			char *type;
765 
766 			len = sizeof("__data_loc ") + strlen(field->type) + 1;
767 			type = kzalloc(len, GFP_KERNEL);
768 			if (!type)
769 				goto free;
770 
771 			seq_buf_init(&s, type, len);
772 			seq_buf_puts(&s, "__data_loc ");
773 			seq_buf_puts(&s, field->type);
774 
775 			if (WARN_ON_ONCE(!seq_buf_buffer_left(&s)))
776 				goto free;
777 			s.buffer[s.len] = '\0';
778 
779 			kfree(field->type);
780 			field->type = type;
781 
782 			field->is_dynamic = true;
783 			size = sizeof(u64);
784 		} else {
785 			synth_err(SYNTH_ERR_INVALID_TYPE, errpos(field_type));
786 			ret = -EINVAL;
787 			goto free;
788 		}
789 	}
790 	field->size = size;
791 
792 	if (synth_field_is_string(field->type))
793 		field->is_string = true;
794 	else if (synth_field_is_stack(field->type))
795 		field->is_stack = true;
796 
797 	field->is_signed = synth_field_signed(field->type);
798  out:
799 	return field;
800  free:
801 	free_synth_field(field);
802 	field = ERR_PTR(ret);
803 	goto out;
804 }
805 
free_synth_tracepoint(struct tracepoint * tp)806 static void free_synth_tracepoint(struct tracepoint *tp)
807 {
808 	if (!tp)
809 		return;
810 
811 	kfree(tp->name);
812 	kfree(tp);
813 }
814 
alloc_synth_tracepoint(char * name)815 static struct tracepoint *alloc_synth_tracepoint(char *name)
816 {
817 	struct tracepoint *tp;
818 
819 	tp = kzalloc(sizeof(*tp), GFP_KERNEL);
820 	if (!tp)
821 		return ERR_PTR(-ENOMEM);
822 
823 	tp->name = kstrdup(name, GFP_KERNEL);
824 	if (!tp->name) {
825 		kfree(tp);
826 		return ERR_PTR(-ENOMEM);
827 	}
828 
829 	return tp;
830 }
831 
find_synth_event(const char * name)832 struct synth_event *find_synth_event(const char *name)
833 {
834 	struct dyn_event *pos;
835 	struct synth_event *event;
836 
837 	for_each_dyn_event(pos) {
838 		if (!is_synth_event(pos))
839 			continue;
840 		event = to_synth_event(pos);
841 		if (strcmp(event->name, name) == 0)
842 			return event;
843 	}
844 
845 	return NULL;
846 }
847 
848 static struct trace_event_fields synth_event_fields_array[] = {
849 	{ .type = TRACE_FUNCTION_TYPE,
850 	  .define_fields = synth_event_define_fields },
851 	{}
852 };
853 
synth_event_reg(struct trace_event_call * call,enum trace_reg type,void * data)854 static int synth_event_reg(struct trace_event_call *call,
855 		    enum trace_reg type, void *data)
856 {
857 	struct synth_event *event = container_of(call, struct synth_event, call);
858 
859 	switch (type) {
860 #ifdef CONFIG_PERF_EVENTS
861 	case TRACE_REG_PERF_REGISTER:
862 #endif
863 	case TRACE_REG_REGISTER:
864 		if (!try_module_get(event->mod))
865 			return -EBUSY;
866 		break;
867 	default:
868 		break;
869 	}
870 
871 	int ret = trace_event_reg(call, type, data);
872 
873 	switch (type) {
874 #ifdef CONFIG_PERF_EVENTS
875 	case TRACE_REG_PERF_UNREGISTER:
876 #endif
877 	case TRACE_REG_UNREGISTER:
878 		module_put(event->mod);
879 		break;
880 	default:
881 		break;
882 	}
883 	return ret;
884 }
885 
register_synth_event(struct synth_event * event)886 static int register_synth_event(struct synth_event *event)
887 {
888 	struct trace_event_call *call = &event->call;
889 	int ret = 0;
890 
891 	event->call.class = &event->class;
892 	event->class.system = kstrdup(SYNTH_SYSTEM, GFP_KERNEL);
893 	if (!event->class.system) {
894 		ret = -ENOMEM;
895 		goto out;
896 	}
897 
898 	event->tp = alloc_synth_tracepoint(event->name);
899 	if (IS_ERR(event->tp)) {
900 		ret = PTR_ERR(event->tp);
901 		event->tp = NULL;
902 		goto out;
903 	}
904 
905 	INIT_LIST_HEAD(&call->class->fields);
906 	call->event.funcs = &synth_event_funcs;
907 	call->class->fields_array = synth_event_fields_array;
908 
909 	ret = register_trace_event(&call->event);
910 	if (!ret) {
911 		ret = -ENODEV;
912 		goto out;
913 	}
914 	call->flags = TRACE_EVENT_FL_TRACEPOINT;
915 	call->class->reg = synth_event_reg;
916 	call->class->probe = trace_event_raw_event_synth;
917 	call->data = event;
918 	call->tp = event->tp;
919 
920 	ret = trace_add_event_call(call);
921 	if (ret) {
922 		pr_warn("Failed to register synthetic event: %s\n",
923 			trace_event_name(call));
924 		goto err;
925 	}
926 
927 	ret = set_synth_event_print_fmt(call);
928 	/* unregister_trace_event() will be called inside */
929 	if (ret < 0)
930 		trace_remove_event_call(call);
931  out:
932 	return ret;
933  err:
934 	unregister_trace_event(&call->event);
935 	goto out;
936 }
937 
unregister_synth_event(struct synth_event * event)938 static int unregister_synth_event(struct synth_event *event)
939 {
940 	struct trace_event_call *call = &event->call;
941 	int ret;
942 
943 	ret = trace_remove_event_call(call);
944 
945 	return ret;
946 }
947 
free_synth_event(struct synth_event * event)948 static void free_synth_event(struct synth_event *event)
949 {
950 	unsigned int i;
951 
952 	if (!event)
953 		return;
954 
955 	for (i = 0; i < event->n_fields; i++)
956 		free_synth_field(event->fields[i]);
957 
958 	kfree(event->fields);
959 	kfree(event->dynamic_fields);
960 	kfree(event->name);
961 	kfree(event->class.system);
962 	free_synth_tracepoint(event->tp);
963 	free_synth_event_print_fmt(&event->call);
964 	kfree(event);
965 }
966 
alloc_synth_event(const char * name,int n_fields,struct synth_field ** fields)967 static struct synth_event *alloc_synth_event(const char *name, int n_fields,
968 					     struct synth_field **fields)
969 {
970 	unsigned int i, j, n_dynamic_fields = 0;
971 	struct synth_event *event;
972 
973 	event = kzalloc(sizeof(*event), GFP_KERNEL);
974 	if (!event) {
975 		event = ERR_PTR(-ENOMEM);
976 		goto out;
977 	}
978 
979 	event->name = kstrdup(name, GFP_KERNEL);
980 	if (!event->name) {
981 		kfree(event);
982 		event = ERR_PTR(-ENOMEM);
983 		goto out;
984 	}
985 
986 	event->fields = kcalloc(n_fields, sizeof(*event->fields), GFP_KERNEL);
987 	if (!event->fields) {
988 		free_synth_event(event);
989 		event = ERR_PTR(-ENOMEM);
990 		goto out;
991 	}
992 
993 	for (i = 0; i < n_fields; i++)
994 		if (fields[i]->is_dynamic)
995 			n_dynamic_fields++;
996 
997 	if (n_dynamic_fields) {
998 		event->dynamic_fields = kcalloc(n_dynamic_fields,
999 						sizeof(*event->dynamic_fields),
1000 						GFP_KERNEL);
1001 		if (!event->dynamic_fields) {
1002 			free_synth_event(event);
1003 			event = ERR_PTR(-ENOMEM);
1004 			goto out;
1005 		}
1006 	}
1007 
1008 	dyn_event_init(&event->devent, &synth_event_ops);
1009 
1010 	for (i = 0, j = 0; i < n_fields; i++) {
1011 		fields[i]->field_pos = i;
1012 		event->fields[i] = fields[i];
1013 
1014 		if (fields[i]->is_dynamic)
1015 			event->dynamic_fields[j++] = fields[i];
1016 	}
1017 	event->n_dynamic_fields = j;
1018 	event->n_fields = n_fields;
1019  out:
1020 	return event;
1021 }
1022 
synth_event_check_arg_fn(void * data)1023 static int synth_event_check_arg_fn(void *data)
1024 {
1025 	struct dynevent_arg_pair *arg_pair = data;
1026 	int size;
1027 
1028 	size = synth_field_size((char *)arg_pair->lhs);
1029 	if (size == 0) {
1030 		if (strstr((char *)arg_pair->lhs, "["))
1031 			return 0;
1032 	}
1033 
1034 	return size ? 0 : -EINVAL;
1035 }
1036 
1037 /**
1038  * synth_event_add_field - Add a new field to a synthetic event cmd
1039  * @cmd: A pointer to the dynevent_cmd struct representing the new event
1040  * @type: The type of the new field to add
1041  * @name: The name of the new field to add
1042  *
1043  * Add a new field to a synthetic event cmd object.  Field ordering is in
1044  * the same order the fields are added.
1045  *
1046  * See synth_field_size() for available types. If field_name contains
1047  * [n] the field is considered to be an array.
1048  *
1049  * Return: 0 if successful, error otherwise.
1050  */
synth_event_add_field(struct dynevent_cmd * cmd,const char * type,const char * name)1051 int synth_event_add_field(struct dynevent_cmd *cmd, const char *type,
1052 			  const char *name)
1053 {
1054 	struct dynevent_arg_pair arg_pair;
1055 	int ret;
1056 
1057 	if (cmd->type != DYNEVENT_TYPE_SYNTH)
1058 		return -EINVAL;
1059 
1060 	if (!type || !name)
1061 		return -EINVAL;
1062 
1063 	dynevent_arg_pair_init(&arg_pair, 0, ';');
1064 
1065 	arg_pair.lhs = type;
1066 	arg_pair.rhs = name;
1067 
1068 	ret = dynevent_arg_pair_add(cmd, &arg_pair, synth_event_check_arg_fn);
1069 	if (ret)
1070 		return ret;
1071 
1072 	if (++cmd->n_fields > SYNTH_FIELDS_MAX)
1073 		ret = -EINVAL;
1074 
1075 	return ret;
1076 }
1077 EXPORT_SYMBOL_GPL(synth_event_add_field);
1078 
1079 /**
1080  * synth_event_add_field_str - Add a new field to a synthetic event cmd
1081  * @cmd: A pointer to the dynevent_cmd struct representing the new event
1082  * @type_name: The type and name of the new field to add, as a single string
1083  *
1084  * Add a new field to a synthetic event cmd object, as a single
1085  * string.  The @type_name string is expected to be of the form 'type
1086  * name', which will be appended by ';'.  No sanity checking is done -
1087  * what's passed in is assumed to already be well-formed.  Field
1088  * ordering is in the same order the fields are added.
1089  *
1090  * See synth_field_size() for available types. If field_name contains
1091  * [n] the field is considered to be an array.
1092  *
1093  * Return: 0 if successful, error otherwise.
1094  */
synth_event_add_field_str(struct dynevent_cmd * cmd,const char * type_name)1095 int synth_event_add_field_str(struct dynevent_cmd *cmd, const char *type_name)
1096 {
1097 	struct dynevent_arg arg;
1098 	int ret;
1099 
1100 	if (cmd->type != DYNEVENT_TYPE_SYNTH)
1101 		return -EINVAL;
1102 
1103 	if (!type_name)
1104 		return -EINVAL;
1105 
1106 	dynevent_arg_init(&arg, ';');
1107 
1108 	arg.str = type_name;
1109 
1110 	ret = dynevent_arg_add(cmd, &arg, NULL);
1111 	if (ret)
1112 		return ret;
1113 
1114 	if (++cmd->n_fields > SYNTH_FIELDS_MAX)
1115 		ret = -EINVAL;
1116 
1117 	return ret;
1118 }
1119 EXPORT_SYMBOL_GPL(synth_event_add_field_str);
1120 
1121 /**
1122  * synth_event_add_fields - Add multiple fields to a synthetic event cmd
1123  * @cmd: A pointer to the dynevent_cmd struct representing the new event
1124  * @fields: An array of type/name field descriptions
1125  * @n_fields: The number of field descriptions contained in the fields array
1126  *
1127  * Add a new set of fields to a synthetic event cmd object.  The event
1128  * fields that will be defined for the event should be passed in as an
1129  * array of struct synth_field_desc, and the number of elements in the
1130  * array passed in as n_fields.  Field ordering will retain the
1131  * ordering given in the fields array.
1132  *
1133  * See synth_field_size() for available types. If field_name contains
1134  * [n] the field is considered to be an array.
1135  *
1136  * Return: 0 if successful, error otherwise.
1137  */
synth_event_add_fields(struct dynevent_cmd * cmd,struct synth_field_desc * fields,unsigned int n_fields)1138 int synth_event_add_fields(struct dynevent_cmd *cmd,
1139 			   struct synth_field_desc *fields,
1140 			   unsigned int n_fields)
1141 {
1142 	unsigned int i;
1143 	int ret = 0;
1144 
1145 	for (i = 0; i < n_fields; i++) {
1146 		if (fields[i].type == NULL || fields[i].name == NULL) {
1147 			ret = -EINVAL;
1148 			break;
1149 		}
1150 
1151 		ret = synth_event_add_field(cmd, fields[i].type, fields[i].name);
1152 		if (ret)
1153 			break;
1154 	}
1155 
1156 	return ret;
1157 }
1158 EXPORT_SYMBOL_GPL(synth_event_add_fields);
1159 
1160 /**
1161  * __synth_event_gen_cmd_start - Start a synthetic event command from arg list
1162  * @cmd: A pointer to the dynevent_cmd struct representing the new event
1163  * @name: The name of the synthetic event
1164  * @mod: The module creating the event, NULL if not created from a module
1165  * @...: Variable number of arg (pairs), one pair for each field
1166  *
1167  * NOTE: Users normally won't want to call this function directly, but
1168  * rather use the synth_event_gen_cmd_start() wrapper, which
1169  * automatically adds a NULL to the end of the arg list.  If this
1170  * function is used directly, make sure the last arg in the variable
1171  * arg list is NULL.
1172  *
1173  * Generate a synthetic event command to be executed by
1174  * synth_event_gen_cmd_end().  This function can be used to generate
1175  * the complete command or only the first part of it; in the latter
1176  * case, synth_event_add_field(), synth_event_add_field_str(), or
1177  * synth_event_add_fields() can be used to add more fields following
1178  * this.
1179  *
1180  * There should be an even number variable args, each pair consisting
1181  * of a type followed by a field name.
1182  *
1183  * See synth_field_size() for available types. If field_name contains
1184  * [n] the field is considered to be an array.
1185  *
1186  * Return: 0 if successful, error otherwise.
1187  */
__synth_event_gen_cmd_start(struct dynevent_cmd * cmd,const char * name,struct module * mod,...)1188 int __synth_event_gen_cmd_start(struct dynevent_cmd *cmd, const char *name,
1189 				struct module *mod, ...)
1190 {
1191 	struct dynevent_arg arg;
1192 	va_list args;
1193 	int ret;
1194 
1195 	cmd->event_name = name;
1196 	cmd->private_data = mod;
1197 
1198 	if (cmd->type != DYNEVENT_TYPE_SYNTH)
1199 		return -EINVAL;
1200 
1201 	dynevent_arg_init(&arg, 0);
1202 	arg.str = name;
1203 	ret = dynevent_arg_add(cmd, &arg, NULL);
1204 	if (ret)
1205 		return ret;
1206 
1207 	va_start(args, mod);
1208 	for (;;) {
1209 		const char *type, *name;
1210 
1211 		type = va_arg(args, const char *);
1212 		if (!type)
1213 			break;
1214 		name = va_arg(args, const char *);
1215 		if (!name)
1216 			break;
1217 
1218 		if (++cmd->n_fields > SYNTH_FIELDS_MAX) {
1219 			ret = -EINVAL;
1220 			break;
1221 		}
1222 
1223 		ret = synth_event_add_field(cmd, type, name);
1224 		if (ret)
1225 			break;
1226 	}
1227 	va_end(args);
1228 
1229 	return ret;
1230 }
1231 EXPORT_SYMBOL_GPL(__synth_event_gen_cmd_start);
1232 
1233 /**
1234  * synth_event_gen_cmd_array_start - Start synthetic event command from an array
1235  * @cmd: A pointer to the dynevent_cmd struct representing the new event
1236  * @name: The name of the synthetic event
1237  * @mod: The module creating the event, NULL if not created from a module
1238  * @fields: An array of type/name field descriptions
1239  * @n_fields: The number of field descriptions contained in the fields array
1240  *
1241  * Generate a synthetic event command to be executed by
1242  * synth_event_gen_cmd_end().  This function can be used to generate
1243  * the complete command or only the first part of it; in the latter
1244  * case, synth_event_add_field(), synth_event_add_field_str(), or
1245  * synth_event_add_fields() can be used to add more fields following
1246  * this.
1247  *
1248  * The event fields that will be defined for the event should be
1249  * passed in as an array of struct synth_field_desc, and the number of
1250  * elements in the array passed in as n_fields.  Field ordering will
1251  * retain the ordering given in the fields array.
1252  *
1253  * See synth_field_size() for available types. If field_name contains
1254  * [n] the field is considered to be an array.
1255  *
1256  * Return: 0 if successful, error otherwise.
1257  */
synth_event_gen_cmd_array_start(struct dynevent_cmd * cmd,const char * name,struct module * mod,struct synth_field_desc * fields,unsigned int n_fields)1258 int synth_event_gen_cmd_array_start(struct dynevent_cmd *cmd, const char *name,
1259 				    struct module *mod,
1260 				    struct synth_field_desc *fields,
1261 				    unsigned int n_fields)
1262 {
1263 	struct dynevent_arg arg;
1264 	unsigned int i;
1265 	int ret = 0;
1266 
1267 	cmd->event_name = name;
1268 	cmd->private_data = mod;
1269 
1270 	if (cmd->type != DYNEVENT_TYPE_SYNTH)
1271 		return -EINVAL;
1272 
1273 	if (n_fields > SYNTH_FIELDS_MAX)
1274 		return -EINVAL;
1275 
1276 	dynevent_arg_init(&arg, 0);
1277 	arg.str = name;
1278 	ret = dynevent_arg_add(cmd, &arg, NULL);
1279 	if (ret)
1280 		return ret;
1281 
1282 	for (i = 0; i < n_fields; i++) {
1283 		if (fields[i].type == NULL || fields[i].name == NULL)
1284 			return -EINVAL;
1285 
1286 		ret = synth_event_add_field(cmd, fields[i].type, fields[i].name);
1287 		if (ret)
1288 			break;
1289 	}
1290 
1291 	return ret;
1292 }
1293 EXPORT_SYMBOL_GPL(synth_event_gen_cmd_array_start);
1294 
__create_synth_event(const char * name,const char * raw_fields)1295 static int __create_synth_event(const char *name, const char *raw_fields)
1296 {
1297 	char **argv, *field_str, *tmp_fields, *saved_fields = NULL;
1298 	struct synth_field *field, *fields[SYNTH_FIELDS_MAX];
1299 	int consumed, cmd_version = 1, n_fields_this_loop;
1300 	int i, argc, n_fields = 0, ret = 0;
1301 	struct synth_event *event = NULL;
1302 
1303 	/*
1304 	 * Argument syntax:
1305 	 *  - Add synthetic event: <event_name> field[;field] ...
1306 	 *  - Remove synthetic event: !<event_name> field[;field] ...
1307 	 *      where 'field' = type field_name
1308 	 */
1309 
1310 	if (name[0] == '\0') {
1311 		synth_err(SYNTH_ERR_INVALID_CMD, 0);
1312 		return -EINVAL;
1313 	}
1314 
1315 	if (!is_good_name(name)) {
1316 		synth_err(SYNTH_ERR_BAD_NAME, errpos(name));
1317 		return -EINVAL;
1318 	}
1319 
1320 	mutex_lock(&event_mutex);
1321 
1322 	event = find_synth_event(name);
1323 	if (event) {
1324 		synth_err(SYNTH_ERR_EVENT_EXISTS, errpos(name));
1325 		ret = -EEXIST;
1326 		goto err;
1327 	}
1328 
1329 	tmp_fields = saved_fields = kstrdup(raw_fields, GFP_KERNEL);
1330 	if (!tmp_fields) {
1331 		ret = -ENOMEM;
1332 		goto err;
1333 	}
1334 
1335 	while ((field_str = strsep(&tmp_fields, ";")) != NULL) {
1336 		argv = argv_split(GFP_KERNEL, field_str, &argc);
1337 		if (!argv) {
1338 			ret = -ENOMEM;
1339 			goto err;
1340 		}
1341 
1342 		if (!argc) {
1343 			argv_free(argv);
1344 			continue;
1345 		}
1346 
1347 		n_fields_this_loop = 0;
1348 		consumed = 0;
1349 		while (argc > consumed) {
1350 			int field_version;
1351 
1352 			field = parse_synth_field(argc - consumed,
1353 						  argv + consumed, &consumed,
1354 						  &field_version);
1355 			if (IS_ERR(field)) {
1356 				ret = PTR_ERR(field);
1357 				goto err_free_arg;
1358 			}
1359 
1360 			/*
1361 			 * Track the highest version of any field we
1362 			 * found in the command.
1363 			 */
1364 			if (field_version > cmd_version)
1365 				cmd_version = field_version;
1366 
1367 			/*
1368 			 * Now sort out what is and isn't valid for
1369 			 * each supported version.
1370 			 *
1371 			 * If we see more than 1 field per loop, it
1372 			 * means we have multiple fields between
1373 			 * semicolons, and that's something we no
1374 			 * longer support in a version 2 or greater
1375 			 * command.
1376 			 */
1377 			if (cmd_version > 1 && n_fields_this_loop >= 1) {
1378 				synth_err(SYNTH_ERR_INVALID_CMD, errpos(field_str));
1379 				ret = -EINVAL;
1380 				goto err_free_arg;
1381 			}
1382 
1383 			if (n_fields == SYNTH_FIELDS_MAX) {
1384 				synth_err(SYNTH_ERR_TOO_MANY_FIELDS, 0);
1385 				ret = -EINVAL;
1386 				goto err_free_arg;
1387 			}
1388 			fields[n_fields++] = field;
1389 
1390 			n_fields_this_loop++;
1391 		}
1392 		argv_free(argv);
1393 
1394 		if (consumed < argc) {
1395 			synth_err(SYNTH_ERR_INVALID_CMD, 0);
1396 			ret = -EINVAL;
1397 			goto err;
1398 		}
1399 
1400 	}
1401 
1402 	if (n_fields == 0) {
1403 		synth_err(SYNTH_ERR_INVALID_CMD, 0);
1404 		ret = -EINVAL;
1405 		goto err;
1406 	}
1407 
1408 	event = alloc_synth_event(name, n_fields, fields);
1409 	if (IS_ERR(event)) {
1410 		ret = PTR_ERR(event);
1411 		event = NULL;
1412 		goto err;
1413 	}
1414 	ret = register_synth_event(event);
1415 	if (!ret)
1416 		dyn_event_add(&event->devent, &event->call);
1417 	else
1418 		free_synth_event(event);
1419  out:
1420 	mutex_unlock(&event_mutex);
1421 
1422 	kfree(saved_fields);
1423 
1424 	return ret;
1425  err_free_arg:
1426 	argv_free(argv);
1427  err:
1428 	for (i = 0; i < n_fields; i++)
1429 		free_synth_field(fields[i]);
1430 
1431 	goto out;
1432 }
1433 
1434 /**
1435  * synth_event_create - Create a new synthetic event
1436  * @name: The name of the new synthetic event
1437  * @fields: An array of type/name field descriptions
1438  * @n_fields: The number of field descriptions contained in the fields array
1439  * @mod: The module creating the event, NULL if not created from a module
1440  *
1441  * Create a new synthetic event with the given name under the
1442  * trace/events/synthetic/ directory.  The event fields that will be
1443  * defined for the event should be passed in as an array of struct
1444  * synth_field_desc, and the number elements in the array passed in as
1445  * n_fields. Field ordering will retain the ordering given in the
1446  * fields array.
1447  *
1448  * If the new synthetic event is being created from a module, the mod
1449  * param must be non-NULL.  This will ensure that the trace buffer
1450  * won't contain unreadable events.
1451  *
1452  * The new synth event should be deleted using synth_event_delete()
1453  * function.  The new synthetic event can be generated from modules or
1454  * other kernel code using trace_synth_event() and related functions.
1455  *
1456  * Return: 0 if successful, error otherwise.
1457  */
synth_event_create(const char * name,struct synth_field_desc * fields,unsigned int n_fields,struct module * mod)1458 int synth_event_create(const char *name, struct synth_field_desc *fields,
1459 		       unsigned int n_fields, struct module *mod)
1460 {
1461 	struct dynevent_cmd cmd;
1462 	char *buf;
1463 	int ret;
1464 
1465 	buf = kzalloc(MAX_DYNEVENT_CMD_LEN, GFP_KERNEL);
1466 	if (!buf)
1467 		return -ENOMEM;
1468 
1469 	synth_event_cmd_init(&cmd, buf, MAX_DYNEVENT_CMD_LEN);
1470 
1471 	ret = synth_event_gen_cmd_array_start(&cmd, name, mod,
1472 					      fields, n_fields);
1473 	if (ret)
1474 		goto out;
1475 
1476 	ret = synth_event_gen_cmd_end(&cmd);
1477  out:
1478 	kfree(buf);
1479 
1480 	return ret;
1481 }
1482 EXPORT_SYMBOL_GPL(synth_event_create);
1483 
destroy_synth_event(struct synth_event * se)1484 static int destroy_synth_event(struct synth_event *se)
1485 {
1486 	int ret;
1487 
1488 	if (se->ref)
1489 		return -EBUSY;
1490 
1491 	if (trace_event_dyn_busy(&se->call))
1492 		return -EBUSY;
1493 
1494 	ret = unregister_synth_event(se);
1495 	if (!ret) {
1496 		dyn_event_remove(&se->devent);
1497 		free_synth_event(se);
1498 	}
1499 
1500 	return ret;
1501 }
1502 
1503 /**
1504  * synth_event_delete - Delete a synthetic event
1505  * @event_name: The name of the new synthetic event
1506  *
1507  * Delete a synthetic event that was created with synth_event_create().
1508  *
1509  * Return: 0 if successful, error otherwise.
1510  */
synth_event_delete(const char * event_name)1511 int synth_event_delete(const char *event_name)
1512 {
1513 	struct synth_event *se = NULL;
1514 	struct module *mod = NULL;
1515 	int ret = -ENOENT;
1516 
1517 	mutex_lock(&event_mutex);
1518 	se = find_synth_event(event_name);
1519 	if (se) {
1520 		mod = se->mod;
1521 		ret = destroy_synth_event(se);
1522 	}
1523 	mutex_unlock(&event_mutex);
1524 
1525 	if (mod) {
1526 		/*
1527 		 * It is safest to reset the ring buffer if the module
1528 		 * being unloaded registered any events that were
1529 		 * used. The only worry is if a new module gets
1530 		 * loaded, and takes on the same id as the events of
1531 		 * this module. When printing out the buffer, traced
1532 		 * events left over from this module may be passed to
1533 		 * the new module events and unexpected results may
1534 		 * occur.
1535 		 */
1536 		tracing_reset_all_online_cpus();
1537 	}
1538 
1539 	return ret;
1540 }
1541 EXPORT_SYMBOL_GPL(synth_event_delete);
1542 
check_command(const char * raw_command)1543 static int check_command(const char *raw_command)
1544 {
1545 	char **argv = NULL, *cmd, *saved_cmd, *name_and_field;
1546 	int argc, ret = 0;
1547 
1548 	cmd = saved_cmd = kstrdup(raw_command, GFP_KERNEL);
1549 	if (!cmd)
1550 		return -ENOMEM;
1551 
1552 	name_and_field = strsep(&cmd, ";");
1553 	if (!name_and_field) {
1554 		ret = -EINVAL;
1555 		goto free;
1556 	}
1557 
1558 	if (name_and_field[0] == '!')
1559 		goto free;
1560 
1561 	argv = argv_split(GFP_KERNEL, name_and_field, &argc);
1562 	if (!argv) {
1563 		ret = -ENOMEM;
1564 		goto free;
1565 	}
1566 	argv_free(argv);
1567 
1568 	if (argc < 3)
1569 		ret = -EINVAL;
1570 free:
1571 	kfree(saved_cmd);
1572 
1573 	return ret;
1574 }
1575 
create_or_delete_synth_event(const char * raw_command)1576 static int create_or_delete_synth_event(const char *raw_command)
1577 {
1578 	char *name = NULL, *fields, *p;
1579 	int ret = 0;
1580 
1581 	raw_command = skip_spaces(raw_command);
1582 	if (raw_command[0] == '\0')
1583 		return ret;
1584 
1585 	last_cmd_set(raw_command);
1586 
1587 	ret = check_command(raw_command);
1588 	if (ret) {
1589 		synth_err(SYNTH_ERR_INVALID_CMD, 0);
1590 		return ret;
1591 	}
1592 
1593 	p = strpbrk(raw_command, " \t");
1594 	if (!p && raw_command[0] != '!') {
1595 		synth_err(SYNTH_ERR_INVALID_CMD, 0);
1596 		ret = -EINVAL;
1597 		goto free;
1598 	}
1599 
1600 	name = kmemdup_nul(raw_command, p ? p - raw_command : strlen(raw_command), GFP_KERNEL);
1601 	if (!name)
1602 		return -ENOMEM;
1603 
1604 	if (name[0] == '!') {
1605 		ret = synth_event_delete(name + 1);
1606 		goto free;
1607 	}
1608 
1609 	fields = skip_spaces(p);
1610 
1611 	ret = __create_synth_event(name, fields);
1612 free:
1613 	kfree(name);
1614 
1615 	return ret;
1616 }
1617 
synth_event_run_command(struct dynevent_cmd * cmd)1618 static int synth_event_run_command(struct dynevent_cmd *cmd)
1619 {
1620 	struct synth_event *se;
1621 	int ret;
1622 
1623 	ret = create_or_delete_synth_event(cmd->seq.buffer);
1624 	if (ret)
1625 		return ret;
1626 
1627 	se = find_synth_event(cmd->event_name);
1628 	if (WARN_ON(!se))
1629 		return -ENOENT;
1630 
1631 	se->mod = cmd->private_data;
1632 
1633 	return ret;
1634 }
1635 
1636 /**
1637  * synth_event_cmd_init - Initialize a synthetic event command object
1638  * @cmd: A pointer to the dynevent_cmd struct representing the new event
1639  * @buf: A pointer to the buffer used to build the command
1640  * @maxlen: The length of the buffer passed in @buf
1641  *
1642  * Initialize a synthetic event command object.  Use this before
1643  * calling any of the other dyenvent_cmd functions.
1644  */
synth_event_cmd_init(struct dynevent_cmd * cmd,char * buf,int maxlen)1645 void synth_event_cmd_init(struct dynevent_cmd *cmd, char *buf, int maxlen)
1646 {
1647 	dynevent_cmd_init(cmd, buf, maxlen, DYNEVENT_TYPE_SYNTH,
1648 			  synth_event_run_command);
1649 }
1650 EXPORT_SYMBOL_GPL(synth_event_cmd_init);
1651 
1652 static inline int
__synth_event_trace_init(struct trace_event_file * file,struct synth_event_trace_state * trace_state)1653 __synth_event_trace_init(struct trace_event_file *file,
1654 			 struct synth_event_trace_state *trace_state)
1655 {
1656 	int ret = 0;
1657 
1658 	memset(trace_state, '\0', sizeof(*trace_state));
1659 
1660 	/*
1661 	 * Normal event tracing doesn't get called at all unless the
1662 	 * ENABLED bit is set (which attaches the probe thus allowing
1663 	 * this code to be called, etc).  Because this is called
1664 	 * directly by the user, we don't have that but we still need
1665 	 * to honor not logging when disabled.  For the iterated
1666 	 * trace case, we save the enabled state upon start and just
1667 	 * ignore the following data calls.
1668 	 */
1669 	if (!(file->flags & EVENT_FILE_FL_ENABLED) ||
1670 	    trace_trigger_soft_disabled(file)) {
1671 		trace_state->disabled = true;
1672 		ret = -ENOENT;
1673 		goto out;
1674 	}
1675 
1676 	trace_state->event = file->event_call->data;
1677 out:
1678 	return ret;
1679 }
1680 
1681 static inline int
__synth_event_trace_start(struct trace_event_file * file,struct synth_event_trace_state * trace_state,int dynamic_fields_size)1682 __synth_event_trace_start(struct trace_event_file *file,
1683 			  struct synth_event_trace_state *trace_state,
1684 			  int dynamic_fields_size)
1685 {
1686 	int entry_size, fields_size = 0;
1687 	int ret = 0;
1688 
1689 	fields_size = trace_state->event->n_u64 * sizeof(u64);
1690 	fields_size += dynamic_fields_size;
1691 
1692 	/*
1693 	 * Avoid ring buffer recursion detection, as this event
1694 	 * is being performed within another event.
1695 	 */
1696 	trace_state->buffer = file->tr->array_buffer.buffer;
1697 	ring_buffer_nest_start(trace_state->buffer);
1698 
1699 	entry_size = sizeof(*trace_state->entry) + fields_size;
1700 	trace_state->entry = trace_event_buffer_reserve(&trace_state->fbuffer,
1701 							file,
1702 							entry_size);
1703 	if (!trace_state->entry) {
1704 		ring_buffer_nest_end(trace_state->buffer);
1705 		ret = -EINVAL;
1706 	}
1707 
1708 	return ret;
1709 }
1710 
1711 static inline void
__synth_event_trace_end(struct synth_event_trace_state * trace_state)1712 __synth_event_trace_end(struct synth_event_trace_state *trace_state)
1713 {
1714 	trace_event_buffer_commit(&trace_state->fbuffer);
1715 
1716 	ring_buffer_nest_end(trace_state->buffer);
1717 }
1718 
1719 /**
1720  * synth_event_trace - Trace a synthetic event
1721  * @file: The trace_event_file representing the synthetic event
1722  * @n_vals: The number of values in vals
1723  * @...: Variable number of args containing the event values
1724  *
1725  * Trace a synthetic event using the values passed in the variable
1726  * argument list.
1727  *
1728  * The argument list should be a list 'n_vals' u64 values.  The number
1729  * of vals must match the number of field in the synthetic event, and
1730  * must be in the same order as the synthetic event fields.
1731  *
1732  * All vals should be cast to u64, and string vals are just pointers
1733  * to strings, cast to u64.  Strings will be copied into space
1734  * reserved in the event for the string, using these pointers.
1735  *
1736  * Return: 0 on success, err otherwise.
1737  */
synth_event_trace(struct trace_event_file * file,unsigned int n_vals,...)1738 int synth_event_trace(struct trace_event_file *file, unsigned int n_vals, ...)
1739 {
1740 	unsigned int i, n_u64, len, data_size = 0;
1741 	struct synth_event_trace_state state;
1742 	va_list args;
1743 	int ret;
1744 
1745 	ret = __synth_event_trace_init(file, &state);
1746 	if (ret) {
1747 		if (ret == -ENOENT)
1748 			ret = 0; /* just disabled, not really an error */
1749 		return ret;
1750 	}
1751 
1752 	if (state.event->n_dynamic_fields) {
1753 		va_start(args, n_vals);
1754 
1755 		for (i = 0; i < state.event->n_fields; i++) {
1756 			u64 val = va_arg(args, u64);
1757 
1758 			if (state.event->fields[i]->is_string &&
1759 			    state.event->fields[i]->is_dynamic) {
1760 				char *str_val = (char *)(long)val;
1761 
1762 				data_size += strlen(str_val) + 1;
1763 			}
1764 		}
1765 
1766 		va_end(args);
1767 	}
1768 
1769 	ret = __synth_event_trace_start(file, &state, data_size);
1770 	if (ret)
1771 		return ret;
1772 
1773 	if (n_vals != state.event->n_fields) {
1774 		ret = -EINVAL;
1775 		goto out;
1776 	}
1777 
1778 	data_size = 0;
1779 
1780 	va_start(args, n_vals);
1781 	for (i = 0, n_u64 = 0; i < state.event->n_fields; i++) {
1782 		u64 val;
1783 
1784 		val = va_arg(args, u64);
1785 
1786 		if (state.event->fields[i]->is_string) {
1787 			char *str_val = (char *)(long)val;
1788 
1789 			len = trace_string(state.entry, state.event, str_val,
1790 					   state.event->fields[i]->is_dynamic,
1791 					   data_size, &n_u64);
1792 			data_size += len; /* only dynamic string increments */
1793 		} else {
1794 			struct synth_field *field = state.event->fields[i];
1795 
1796 			switch (field->size) {
1797 			case 1:
1798 				state.entry->fields[n_u64].as_u8 = (u8)val;
1799 				break;
1800 
1801 			case 2:
1802 				state.entry->fields[n_u64].as_u16 = (u16)val;
1803 				break;
1804 
1805 			case 4:
1806 				state.entry->fields[n_u64].as_u32 = (u32)val;
1807 				break;
1808 
1809 			default:
1810 				state.entry->fields[n_u64].as_u64 = val;
1811 				break;
1812 			}
1813 			n_u64++;
1814 		}
1815 	}
1816 	va_end(args);
1817 out:
1818 	__synth_event_trace_end(&state);
1819 
1820 	return ret;
1821 }
1822 EXPORT_SYMBOL_GPL(synth_event_trace);
1823 
1824 /**
1825  * synth_event_trace_array - Trace a synthetic event from an array
1826  * @file: The trace_event_file representing the synthetic event
1827  * @vals: Array of values
1828  * @n_vals: The number of values in vals
1829  *
1830  * Trace a synthetic event using the values passed in as 'vals'.
1831  *
1832  * The 'vals' array is just an array of 'n_vals' u64.  The number of
1833  * vals must match the number of field in the synthetic event, and
1834  * must be in the same order as the synthetic event fields.
1835  *
1836  * All vals should be cast to u64, and string vals are just pointers
1837  * to strings, cast to u64.  Strings will be copied into space
1838  * reserved in the event for the string, using these pointers.
1839  *
1840  * Return: 0 on success, err otherwise.
1841  */
synth_event_trace_array(struct trace_event_file * file,u64 * vals,unsigned int n_vals)1842 int synth_event_trace_array(struct trace_event_file *file, u64 *vals,
1843 			    unsigned int n_vals)
1844 {
1845 	unsigned int i, n_u64, field_pos, len, data_size = 0;
1846 	struct synth_event_trace_state state;
1847 	char *str_val;
1848 	int ret;
1849 
1850 	ret = __synth_event_trace_init(file, &state);
1851 	if (ret) {
1852 		if (ret == -ENOENT)
1853 			ret = 0; /* just disabled, not really an error */
1854 		return ret;
1855 	}
1856 
1857 	if (state.event->n_dynamic_fields) {
1858 		for (i = 0; i < state.event->n_dynamic_fields; i++) {
1859 			field_pos = state.event->dynamic_fields[i]->field_pos;
1860 			str_val = (char *)(long)vals[field_pos];
1861 			len = strlen(str_val) + 1;
1862 			data_size += len;
1863 		}
1864 	}
1865 
1866 	ret = __synth_event_trace_start(file, &state, data_size);
1867 	if (ret)
1868 		return ret;
1869 
1870 	if (n_vals != state.event->n_fields) {
1871 		ret = -EINVAL;
1872 		goto out;
1873 	}
1874 
1875 	data_size = 0;
1876 
1877 	for (i = 0, n_u64 = 0; i < state.event->n_fields; i++) {
1878 		if (state.event->fields[i]->is_string) {
1879 			char *str_val = (char *)(long)vals[i];
1880 
1881 			len = trace_string(state.entry, state.event, str_val,
1882 					   state.event->fields[i]->is_dynamic,
1883 					   data_size, &n_u64);
1884 			data_size += len; /* only dynamic string increments */
1885 		} else {
1886 			struct synth_field *field = state.event->fields[i];
1887 			u64 val = vals[i];
1888 
1889 			switch (field->size) {
1890 			case 1:
1891 				state.entry->fields[n_u64].as_u8 = (u8)val;
1892 				break;
1893 
1894 			case 2:
1895 				state.entry->fields[n_u64].as_u16 = (u16)val;
1896 				break;
1897 
1898 			case 4:
1899 				state.entry->fields[n_u64].as_u32 = (u32)val;
1900 				break;
1901 
1902 			default:
1903 				state.entry->fields[n_u64].as_u64 = val;
1904 				break;
1905 			}
1906 			n_u64++;
1907 		}
1908 	}
1909 out:
1910 	__synth_event_trace_end(&state);
1911 
1912 	return ret;
1913 }
1914 EXPORT_SYMBOL_GPL(synth_event_trace_array);
1915 
1916 /**
1917  * synth_event_trace_start - Start piecewise synthetic event trace
1918  * @file: The trace_event_file representing the synthetic event
1919  * @trace_state: A pointer to object tracking the piecewise trace state
1920  *
1921  * Start the trace of a synthetic event field-by-field rather than all
1922  * at once.
1923  *
1924  * This function 'opens' an event trace, which means space is reserved
1925  * for the event in the trace buffer, after which the event's
1926  * individual field values can be set through either
1927  * synth_event_add_next_val() or synth_event_add_val().
1928  *
1929  * A pointer to a trace_state object is passed in, which will keep
1930  * track of the current event trace state until the event trace is
1931  * closed (and the event finally traced) using
1932  * synth_event_trace_end().
1933  *
1934  * Note that synth_event_trace_end() must be called after all values
1935  * have been added for each event trace, regardless of whether adding
1936  * all field values succeeded or not.
1937  *
1938  * Note also that for a given event trace, all fields must be added
1939  * using either synth_event_add_next_val() or synth_event_add_val()
1940  * but not both together or interleaved.
1941  *
1942  * Return: 0 on success, err otherwise.
1943  */
synth_event_trace_start(struct trace_event_file * file,struct synth_event_trace_state * trace_state)1944 int synth_event_trace_start(struct trace_event_file *file,
1945 			    struct synth_event_trace_state *trace_state)
1946 {
1947 	int ret;
1948 
1949 	if (!trace_state)
1950 		return -EINVAL;
1951 
1952 	ret = __synth_event_trace_init(file, trace_state);
1953 	if (ret) {
1954 		if (ret == -ENOENT)
1955 			ret = 0; /* just disabled, not really an error */
1956 		return ret;
1957 	}
1958 
1959 	if (trace_state->event->n_dynamic_fields)
1960 		return -ENOTSUPP;
1961 
1962 	ret = __synth_event_trace_start(file, trace_state, 0);
1963 
1964 	return ret;
1965 }
1966 EXPORT_SYMBOL_GPL(synth_event_trace_start);
1967 
__synth_event_add_val(const char * field_name,u64 val,struct synth_event_trace_state * trace_state)1968 static int __synth_event_add_val(const char *field_name, u64 val,
1969 				 struct synth_event_trace_state *trace_state)
1970 {
1971 	struct synth_field *field = NULL;
1972 	struct synth_trace_event *entry;
1973 	struct synth_event *event;
1974 	int i, ret = 0;
1975 
1976 	if (!trace_state) {
1977 		ret = -EINVAL;
1978 		goto out;
1979 	}
1980 
1981 	/* can't mix add_next_synth_val() with add_synth_val() */
1982 	if (field_name) {
1983 		if (trace_state->add_next) {
1984 			ret = -EINVAL;
1985 			goto out;
1986 		}
1987 		trace_state->add_name = true;
1988 	} else {
1989 		if (trace_state->add_name) {
1990 			ret = -EINVAL;
1991 			goto out;
1992 		}
1993 		trace_state->add_next = true;
1994 	}
1995 
1996 	if (trace_state->disabled)
1997 		goto out;
1998 
1999 	event = trace_state->event;
2000 	if (trace_state->add_name) {
2001 		for (i = 0; i < event->n_fields; i++) {
2002 			field = event->fields[i];
2003 			if (strcmp(field->name, field_name) == 0)
2004 				break;
2005 		}
2006 		if (!field) {
2007 			ret = -EINVAL;
2008 			goto out;
2009 		}
2010 	} else {
2011 		if (trace_state->cur_field >= event->n_fields) {
2012 			ret = -EINVAL;
2013 			goto out;
2014 		}
2015 		field = event->fields[trace_state->cur_field++];
2016 	}
2017 
2018 	entry = trace_state->entry;
2019 	if (field->is_string) {
2020 		char *str_val = (char *)(long)val;
2021 		char *str_field;
2022 
2023 		if (field->is_dynamic) { /* add_val can't do dynamic strings */
2024 			ret = -EINVAL;
2025 			goto out;
2026 		}
2027 
2028 		if (!str_val) {
2029 			ret = -EINVAL;
2030 			goto out;
2031 		}
2032 
2033 		str_field = (char *)&entry->fields[field->offset];
2034 		strscpy(str_field, str_val, STR_VAR_LEN_MAX);
2035 	} else {
2036 		switch (field->size) {
2037 		case 1:
2038 			trace_state->entry->fields[field->offset].as_u8 = (u8)val;
2039 			break;
2040 
2041 		case 2:
2042 			trace_state->entry->fields[field->offset].as_u16 = (u16)val;
2043 			break;
2044 
2045 		case 4:
2046 			trace_state->entry->fields[field->offset].as_u32 = (u32)val;
2047 			break;
2048 
2049 		default:
2050 			trace_state->entry->fields[field->offset].as_u64 = val;
2051 			break;
2052 		}
2053 	}
2054  out:
2055 	return ret;
2056 }
2057 
2058 /**
2059  * synth_event_add_next_val - Add the next field's value to an open synth trace
2060  * @val: The value to set the next field to
2061  * @trace_state: A pointer to object tracking the piecewise trace state
2062  *
2063  * Set the value of the next field in an event that's been opened by
2064  * synth_event_trace_start().
2065  *
2066  * The val param should be the value cast to u64.  If the value points
2067  * to a string, the val param should be a char * cast to u64.
2068  *
2069  * This function assumes all the fields in an event are to be set one
2070  * after another - successive calls to this function are made, one for
2071  * each field, in the order of the fields in the event, until all
2072  * fields have been set.  If you'd rather set each field individually
2073  * without regard to ordering, synth_event_add_val() can be used
2074  * instead.
2075  *
2076  * Note however that synth_event_add_next_val() and
2077  * synth_event_add_val() can't be intermixed for a given event trace -
2078  * one or the other but not both can be used at the same time.
2079  *
2080  * Note also that synth_event_trace_end() must be called after all
2081  * values have been added for each event trace, regardless of whether
2082  * adding all field values succeeded or not.
2083  *
2084  * Return: 0 on success, err otherwise.
2085  */
synth_event_add_next_val(u64 val,struct synth_event_trace_state * trace_state)2086 int synth_event_add_next_val(u64 val,
2087 			     struct synth_event_trace_state *trace_state)
2088 {
2089 	return __synth_event_add_val(NULL, val, trace_state);
2090 }
2091 EXPORT_SYMBOL_GPL(synth_event_add_next_val);
2092 
2093 /**
2094  * synth_event_add_val - Add a named field's value to an open synth trace
2095  * @field_name: The name of the synthetic event field value to set
2096  * @val: The value to set the named field to
2097  * @trace_state: A pointer to object tracking the piecewise trace state
2098  *
2099  * Set the value of the named field in an event that's been opened by
2100  * synth_event_trace_start().
2101  *
2102  * The val param should be the value cast to u64.  If the value points
2103  * to a string, the val param should be a char * cast to u64.
2104  *
2105  * This function looks up the field name, and if found, sets the field
2106  * to the specified value.  This lookup makes this function more
2107  * expensive than synth_event_add_next_val(), so use that or the
2108  * none-piecewise synth_event_trace() instead if efficiency is more
2109  * important.
2110  *
2111  * Note however that synth_event_add_next_val() and
2112  * synth_event_add_val() can't be intermixed for a given event trace -
2113  * one or the other but not both can be used at the same time.
2114  *
2115  * Note also that synth_event_trace_end() must be called after all
2116  * values have been added for each event trace, regardless of whether
2117  * adding all field values succeeded or not.
2118  *
2119  * Return: 0 on success, err otherwise.
2120  */
synth_event_add_val(const char * field_name,u64 val,struct synth_event_trace_state * trace_state)2121 int synth_event_add_val(const char *field_name, u64 val,
2122 			struct synth_event_trace_state *trace_state)
2123 {
2124 	return __synth_event_add_val(field_name, val, trace_state);
2125 }
2126 EXPORT_SYMBOL_GPL(synth_event_add_val);
2127 
2128 /**
2129  * synth_event_trace_end - End piecewise synthetic event trace
2130  * @trace_state: A pointer to object tracking the piecewise trace state
2131  *
2132  * End the trace of a synthetic event opened by
2133  * synth_event_trace__start().
2134  *
2135  * This function 'closes' an event trace, which basically means that
2136  * it commits the reserved event and cleans up other loose ends.
2137  *
2138  * A pointer to a trace_state object is passed in, which will keep
2139  * track of the current event trace state opened with
2140  * synth_event_trace_start().
2141  *
2142  * Note that this function must be called after all values have been
2143  * added for each event trace, regardless of whether adding all field
2144  * values succeeded or not.
2145  *
2146  * Return: 0 on success, err otherwise.
2147  */
synth_event_trace_end(struct synth_event_trace_state * trace_state)2148 int synth_event_trace_end(struct synth_event_trace_state *trace_state)
2149 {
2150 	if (!trace_state)
2151 		return -EINVAL;
2152 
2153 	__synth_event_trace_end(trace_state);
2154 
2155 	return 0;
2156 }
2157 EXPORT_SYMBOL_GPL(synth_event_trace_end);
2158 
create_synth_event(const char * raw_command)2159 static int create_synth_event(const char *raw_command)
2160 {
2161 	char *fields, *p;
2162 	const char *name;
2163 	int len, ret = 0;
2164 
2165 	raw_command = skip_spaces(raw_command);
2166 	if (raw_command[0] == '\0')
2167 		return ret;
2168 
2169 	last_cmd_set(raw_command);
2170 
2171 	name = raw_command;
2172 
2173 	/* Don't try to process if not our system */
2174 	if (name[0] != 's' || name[1] != ':')
2175 		return -ECANCELED;
2176 	name += 2;
2177 
2178 	p = strpbrk(raw_command, " \t");
2179 	if (!p) {
2180 		synth_err(SYNTH_ERR_INVALID_CMD, 0);
2181 		return -EINVAL;
2182 	}
2183 
2184 	fields = skip_spaces(p);
2185 
2186 	/* This interface accepts group name prefix */
2187 	if (strchr(name, '/')) {
2188 		len = str_has_prefix(name, SYNTH_SYSTEM "/");
2189 		if (len == 0) {
2190 			synth_err(SYNTH_ERR_INVALID_DYN_CMD, 0);
2191 			return -EINVAL;
2192 		}
2193 		name += len;
2194 	}
2195 
2196 	len = name - raw_command;
2197 
2198 	ret = check_command(raw_command + len);
2199 	if (ret) {
2200 		synth_err(SYNTH_ERR_INVALID_CMD, 0);
2201 		return ret;
2202 	}
2203 
2204 	name = kmemdup_nul(raw_command + len, p - raw_command - len, GFP_KERNEL);
2205 	if (!name)
2206 		return -ENOMEM;
2207 
2208 	ret = __create_synth_event(name, fields);
2209 
2210 	kfree(name);
2211 
2212 	return ret;
2213 }
2214 
synth_event_release(struct dyn_event * ev)2215 static int synth_event_release(struct dyn_event *ev)
2216 {
2217 	struct synth_event *event = to_synth_event(ev);
2218 	int ret;
2219 
2220 	if (event->ref)
2221 		return -EBUSY;
2222 
2223 	if (trace_event_dyn_busy(&event->call))
2224 		return -EBUSY;
2225 
2226 	ret = unregister_synth_event(event);
2227 	if (ret)
2228 		return ret;
2229 
2230 	dyn_event_remove(ev);
2231 	free_synth_event(event);
2232 	return 0;
2233 }
2234 
__synth_event_show(struct seq_file * m,struct synth_event * event)2235 static int __synth_event_show(struct seq_file *m, struct synth_event *event)
2236 {
2237 	struct synth_field *field;
2238 	unsigned int i;
2239 	char *type, *t;
2240 
2241 	seq_printf(m, "%s\t", event->name);
2242 
2243 	for (i = 0; i < event->n_fields; i++) {
2244 		field = event->fields[i];
2245 
2246 		type = field->type;
2247 		t = strstr(type, "__data_loc");
2248 		if (t) { /* __data_loc belongs in format but not event desc */
2249 			t += sizeof("__data_loc");
2250 			type = t;
2251 		}
2252 
2253 		/* parameter values */
2254 		seq_printf(m, "%s %s%s", type, field->name,
2255 			   i == event->n_fields - 1 ? "" : "; ");
2256 	}
2257 
2258 	seq_putc(m, '\n');
2259 
2260 	return 0;
2261 }
2262 
synth_event_show(struct seq_file * m,struct dyn_event * ev)2263 static int synth_event_show(struct seq_file *m, struct dyn_event *ev)
2264 {
2265 	struct synth_event *event = to_synth_event(ev);
2266 
2267 	seq_printf(m, "s:%s/", event->class.system);
2268 
2269 	return __synth_event_show(m, event);
2270 }
2271 
synth_events_seq_show(struct seq_file * m,void * v)2272 static int synth_events_seq_show(struct seq_file *m, void *v)
2273 {
2274 	struct dyn_event *ev = v;
2275 
2276 	if (!is_synth_event(ev))
2277 		return 0;
2278 
2279 	return __synth_event_show(m, to_synth_event(ev));
2280 }
2281 
2282 static const struct seq_operations synth_events_seq_op = {
2283 	.start	= dyn_event_seq_start,
2284 	.next	= dyn_event_seq_next,
2285 	.stop	= dyn_event_seq_stop,
2286 	.show	= synth_events_seq_show,
2287 };
2288 
synth_events_open(struct inode * inode,struct file * file)2289 static int synth_events_open(struct inode *inode, struct file *file)
2290 {
2291 	int ret;
2292 
2293 	ret = security_locked_down(LOCKDOWN_TRACEFS);
2294 	if (ret)
2295 		return ret;
2296 
2297 	if ((file->f_mode & FMODE_WRITE) && (file->f_flags & O_TRUNC)) {
2298 		ret = dyn_events_release_all(&synth_event_ops);
2299 		if (ret < 0)
2300 			return ret;
2301 	}
2302 
2303 	return seq_open(file, &synth_events_seq_op);
2304 }
2305 
synth_events_write(struct file * file,const char __user * buffer,size_t count,loff_t * ppos)2306 static ssize_t synth_events_write(struct file *file,
2307 				  const char __user *buffer,
2308 				  size_t count, loff_t *ppos)
2309 {
2310 	return trace_parse_run_command(file, buffer, count, ppos,
2311 				       create_or_delete_synth_event);
2312 }
2313 
2314 static const struct file_operations synth_events_fops = {
2315 	.open           = synth_events_open,
2316 	.write		= synth_events_write,
2317 	.read           = seq_read,
2318 	.llseek         = seq_lseek,
2319 	.release        = seq_release,
2320 };
2321 
2322 /*
2323  * Register dynevent at core_initcall. This allows kernel to setup kprobe
2324  * events in postcore_initcall without tracefs.
2325  */
trace_events_synth_init_early(void)2326 static __init int trace_events_synth_init_early(void)
2327 {
2328 	int err = 0;
2329 
2330 	err = dyn_event_register(&synth_event_ops);
2331 	if (err)
2332 		pr_warn("Could not register synth_event_ops\n");
2333 
2334 	return err;
2335 }
2336 core_initcall(trace_events_synth_init_early);
2337 
trace_events_synth_init(void)2338 static __init int trace_events_synth_init(void)
2339 {
2340 	struct dentry *entry = NULL;
2341 	int err = 0;
2342 	err = tracing_init_dentry();
2343 	if (err)
2344 		goto err;
2345 
2346 	entry = tracefs_create_file("synthetic_events", TRACE_MODE_WRITE,
2347 				    NULL, NULL, &synth_events_fops);
2348 	if (!entry) {
2349 		err = -ENODEV;
2350 		goto err;
2351 	}
2352 
2353 	return err;
2354  err:
2355 	pr_warn("Could not create tracefs 'synthetic_events' entry\n");
2356 
2357 	return err;
2358 }
2359 
2360 fs_initcall(trace_events_synth_init);
2361