xref: /linux/kernel/trace/trace_events_hist.c (revision e0ad4d68548005adb54cc7c35fd9abf760a2a050)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * trace_events_hist - trace event hist triggers
4  *
5  * Copyright (C) 2015 Tom Zanussi <tom.zanussi@linux.intel.com>
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 
21 #include "tracing_map.h"
22 #include "trace.h"
23 #include "trace_dynevent.h"
24 
25 #define SYNTH_SYSTEM		"synthetic"
26 #define SYNTH_FIELDS_MAX	32
27 
28 #define STR_VAR_LEN_MAX		32 /* must be multiple of sizeof(u64) */
29 
30 #define ERRORS								\
31 	C(NONE,			"No error"),				\
32 	C(DUPLICATE_VAR,	"Variable already defined"),		\
33 	C(VAR_NOT_UNIQUE,	"Variable name not unique, need to use fully qualified name (subsys.event.var) for variable"), \
34 	C(TOO_MANY_VARS,	"Too many variables defined"),		\
35 	C(MALFORMED_ASSIGNMENT,	"Malformed assignment"),		\
36 	C(NAMED_MISMATCH,	"Named hist trigger doesn't match existing named trigger (includes variables)"), \
37 	C(TRIGGER_EEXIST,	"Hist trigger already exists"),		\
38 	C(TRIGGER_ENOENT_CLEAR,	"Can't clear or continue a nonexistent hist trigger"), \
39 	C(SET_CLOCK_FAIL,	"Couldn't set trace_clock"),		\
40 	C(BAD_FIELD_MODIFIER,	"Invalid field modifier"),		\
41 	C(TOO_MANY_SUBEXPR,	"Too many subexpressions (3 max)"),	\
42 	C(TIMESTAMP_MISMATCH,	"Timestamp units in expression don't match"), \
43 	C(TOO_MANY_FIELD_VARS,	"Too many field variables defined"),	\
44 	C(EVENT_FILE_NOT_FOUND,	"Event file not found"),		\
45 	C(HIST_NOT_FOUND,	"Matching event histogram not found"),	\
46 	C(HIST_CREATE_FAIL,	"Couldn't create histogram for field"),	\
47 	C(SYNTH_VAR_NOT_FOUND,	"Couldn't find synthetic variable"),	\
48 	C(SYNTH_EVENT_NOT_FOUND,"Couldn't find synthetic event"),	\
49 	C(SYNTH_TYPE_MISMATCH,	"Param type doesn't match synthetic event field type"), \
50 	C(SYNTH_COUNT_MISMATCH,	"Param count doesn't match synthetic event field count"), \
51 	C(FIELD_VAR_PARSE_FAIL,	"Couldn't parse field variable"),	\
52 	C(VAR_CREATE_FIND_FAIL,	"Couldn't create or find variable"),	\
53 	C(ONX_NOT_VAR,		"For onmax(x) or onchange(x), x must be a variable"), \
54 	C(ONX_VAR_NOT_FOUND,	"Couldn't find onmax or onchange variable"), \
55 	C(ONX_VAR_CREATE_FAIL,	"Couldn't create onmax or onchange variable"), \
56 	C(FIELD_VAR_CREATE_FAIL,"Couldn't create field variable"),	\
57 	C(TOO_MANY_PARAMS,	"Too many action params"),		\
58 	C(PARAM_NOT_FOUND,	"Couldn't find param"),			\
59 	C(INVALID_PARAM,	"Invalid action param"),		\
60 	C(ACTION_NOT_FOUND,	"No action found"),			\
61 	C(NO_SAVE_PARAMS,	"No params found for save()"),		\
62 	C(TOO_MANY_SAVE_ACTIONS,"Can't have more than one save() action per hist"), \
63 	C(ACTION_MISMATCH,	"Handler doesn't support action"),	\
64 	C(NO_CLOSING_PAREN,	"No closing paren found"),		\
65 	C(SUBSYS_NOT_FOUND,	"Missing subsystem"),			\
66 	C(INVALID_SUBSYS_EVENT,	"Invalid subsystem or event name"),	\
67 	C(INVALID_REF_KEY,	"Using variable references in keys not supported"), \
68 	C(VAR_NOT_FOUND,	"Couldn't find variable"),		\
69 	C(FIELD_NOT_FOUND,	"Couldn't find field"),			\
70 	C(EMPTY_ASSIGNMENT,	"Empty assignment"),			\
71 	C(INVALID_SORT_MODIFIER,"Invalid sort modifier"),		\
72 	C(EMPTY_SORT_FIELD,	"Empty sort field"),			\
73 	C(TOO_MANY_SORT_FIELDS,	"Too many sort fields (Max = 2)"),	\
74 	C(INVALID_SORT_FIELD,	"Sort field must be a key or a val"),
75 
76 #undef C
77 #define C(a, b)		HIST_ERR_##a
78 
79 enum { ERRORS };
80 
81 #undef C
82 #define C(a, b)		b
83 
84 static const char *err_text[] = { ERRORS };
85 
86 struct hist_field;
87 
88 typedef u64 (*hist_field_fn_t) (struct hist_field *field,
89 				struct tracing_map_elt *elt,
90 				struct ring_buffer_event *rbe,
91 				void *event);
92 
93 #define HIST_FIELD_OPERANDS_MAX	2
94 #define HIST_FIELDS_MAX		(TRACING_MAP_FIELDS_MAX + TRACING_MAP_VARS_MAX)
95 #define HIST_ACTIONS_MAX	8
96 
97 enum field_op_id {
98 	FIELD_OP_NONE,
99 	FIELD_OP_PLUS,
100 	FIELD_OP_MINUS,
101 	FIELD_OP_UNARY_MINUS,
102 };
103 
104 /*
105  * A hist_var (histogram variable) contains variable information for
106  * hist_fields having the HIST_FIELD_FL_VAR or HIST_FIELD_FL_VAR_REF
107  * flag set.  A hist_var has a variable name e.g. ts0, and is
108  * associated with a given histogram trigger, as specified by
109  * hist_data.  The hist_var idx is the unique index assigned to the
110  * variable by the hist trigger's tracing_map.  The idx is what is
111  * used to set a variable's value and, by a variable reference, to
112  * retrieve it.
113  */
114 struct hist_var {
115 	char				*name;
116 	struct hist_trigger_data	*hist_data;
117 	unsigned int			idx;
118 };
119 
120 struct hist_field {
121 	struct ftrace_event_field	*field;
122 	unsigned long			flags;
123 	hist_field_fn_t			fn;
124 	unsigned int			ref;
125 	unsigned int			size;
126 	unsigned int			offset;
127 	unsigned int                    is_signed;
128 	const char			*type;
129 	struct hist_field		*operands[HIST_FIELD_OPERANDS_MAX];
130 	struct hist_trigger_data	*hist_data;
131 
132 	/*
133 	 * Variable fields contain variable-specific info in var.
134 	 */
135 	struct hist_var			var;
136 	enum field_op_id		operator;
137 	char				*system;
138 	char				*event_name;
139 
140 	/*
141 	 * The name field is used for EXPR and VAR_REF fields.  VAR
142 	 * fields contain the variable name in var.name.
143 	 */
144 	char				*name;
145 
146 	/*
147 	 * When a histogram trigger is hit, if it has any references
148 	 * to variables, the values of those variables are collected
149 	 * into a var_ref_vals array by resolve_var_refs().  The
150 	 * current value of each variable is read from the tracing_map
151 	 * using the hist field's hist_var.idx and entered into the
152 	 * var_ref_idx entry i.e. var_ref_vals[var_ref_idx].
153 	 */
154 	unsigned int			var_ref_idx;
155 	bool                            read_once;
156 };
157 
158 static u64 hist_field_none(struct hist_field *field,
159 			   struct tracing_map_elt *elt,
160 			   struct ring_buffer_event *rbe,
161 			   void *event)
162 {
163 	return 0;
164 }
165 
166 static u64 hist_field_counter(struct hist_field *field,
167 			      struct tracing_map_elt *elt,
168 			      struct ring_buffer_event *rbe,
169 			      void *event)
170 {
171 	return 1;
172 }
173 
174 static u64 hist_field_string(struct hist_field *hist_field,
175 			     struct tracing_map_elt *elt,
176 			     struct ring_buffer_event *rbe,
177 			     void *event)
178 {
179 	char *addr = (char *)(event + hist_field->field->offset);
180 
181 	return (u64)(unsigned long)addr;
182 }
183 
184 static u64 hist_field_dynstring(struct hist_field *hist_field,
185 				struct tracing_map_elt *elt,
186 				struct ring_buffer_event *rbe,
187 				void *event)
188 {
189 	u32 str_item = *(u32 *)(event + hist_field->field->offset);
190 	int str_loc = str_item & 0xffff;
191 	char *addr = (char *)(event + str_loc);
192 
193 	return (u64)(unsigned long)addr;
194 }
195 
196 static u64 hist_field_pstring(struct hist_field *hist_field,
197 			      struct tracing_map_elt *elt,
198 			      struct ring_buffer_event *rbe,
199 			      void *event)
200 {
201 	char **addr = (char **)(event + hist_field->field->offset);
202 
203 	return (u64)(unsigned long)*addr;
204 }
205 
206 static u64 hist_field_log2(struct hist_field *hist_field,
207 			   struct tracing_map_elt *elt,
208 			   struct ring_buffer_event *rbe,
209 			   void *event)
210 {
211 	struct hist_field *operand = hist_field->operands[0];
212 
213 	u64 val = operand->fn(operand, elt, rbe, event);
214 
215 	return (u64) ilog2(roundup_pow_of_two(val));
216 }
217 
218 static u64 hist_field_plus(struct hist_field *hist_field,
219 			   struct tracing_map_elt *elt,
220 			   struct ring_buffer_event *rbe,
221 			   void *event)
222 {
223 	struct hist_field *operand1 = hist_field->operands[0];
224 	struct hist_field *operand2 = hist_field->operands[1];
225 
226 	u64 val1 = operand1->fn(operand1, elt, rbe, event);
227 	u64 val2 = operand2->fn(operand2, elt, rbe, event);
228 
229 	return val1 + val2;
230 }
231 
232 static u64 hist_field_minus(struct hist_field *hist_field,
233 			    struct tracing_map_elt *elt,
234 			    struct ring_buffer_event *rbe,
235 			    void *event)
236 {
237 	struct hist_field *operand1 = hist_field->operands[0];
238 	struct hist_field *operand2 = hist_field->operands[1];
239 
240 	u64 val1 = operand1->fn(operand1, elt, rbe, event);
241 	u64 val2 = operand2->fn(operand2, elt, rbe, event);
242 
243 	return val1 - val2;
244 }
245 
246 static u64 hist_field_unary_minus(struct hist_field *hist_field,
247 				  struct tracing_map_elt *elt,
248 				  struct ring_buffer_event *rbe,
249 				  void *event)
250 {
251 	struct hist_field *operand = hist_field->operands[0];
252 
253 	s64 sval = (s64)operand->fn(operand, elt, rbe, event);
254 	u64 val = (u64)-sval;
255 
256 	return val;
257 }
258 
259 #define DEFINE_HIST_FIELD_FN(type)					\
260 	static u64 hist_field_##type(struct hist_field *hist_field,	\
261 				     struct tracing_map_elt *elt,	\
262 				     struct ring_buffer_event *rbe,	\
263 				     void *event)			\
264 {									\
265 	type *addr = (type *)(event + hist_field->field->offset);	\
266 									\
267 	return (u64)(unsigned long)*addr;				\
268 }
269 
270 DEFINE_HIST_FIELD_FN(s64);
271 DEFINE_HIST_FIELD_FN(u64);
272 DEFINE_HIST_FIELD_FN(s32);
273 DEFINE_HIST_FIELD_FN(u32);
274 DEFINE_HIST_FIELD_FN(s16);
275 DEFINE_HIST_FIELD_FN(u16);
276 DEFINE_HIST_FIELD_FN(s8);
277 DEFINE_HIST_FIELD_FN(u8);
278 
279 #define for_each_hist_field(i, hist_data)	\
280 	for ((i) = 0; (i) < (hist_data)->n_fields; (i)++)
281 
282 #define for_each_hist_val_field(i, hist_data)	\
283 	for ((i) = 0; (i) < (hist_data)->n_vals; (i)++)
284 
285 #define for_each_hist_key_field(i, hist_data)	\
286 	for ((i) = (hist_data)->n_vals; (i) < (hist_data)->n_fields; (i)++)
287 
288 #define HIST_STACKTRACE_DEPTH	16
289 #define HIST_STACKTRACE_SIZE	(HIST_STACKTRACE_DEPTH * sizeof(unsigned long))
290 #define HIST_STACKTRACE_SKIP	5
291 
292 #define HITCOUNT_IDX		0
293 #define HIST_KEY_SIZE_MAX	(MAX_FILTER_STR_VAL + HIST_STACKTRACE_SIZE)
294 
295 enum hist_field_flags {
296 	HIST_FIELD_FL_HITCOUNT		= 1 << 0,
297 	HIST_FIELD_FL_KEY		= 1 << 1,
298 	HIST_FIELD_FL_STRING		= 1 << 2,
299 	HIST_FIELD_FL_HEX		= 1 << 3,
300 	HIST_FIELD_FL_SYM		= 1 << 4,
301 	HIST_FIELD_FL_SYM_OFFSET	= 1 << 5,
302 	HIST_FIELD_FL_EXECNAME		= 1 << 6,
303 	HIST_FIELD_FL_SYSCALL		= 1 << 7,
304 	HIST_FIELD_FL_STACKTRACE	= 1 << 8,
305 	HIST_FIELD_FL_LOG2		= 1 << 9,
306 	HIST_FIELD_FL_TIMESTAMP		= 1 << 10,
307 	HIST_FIELD_FL_TIMESTAMP_USECS	= 1 << 11,
308 	HIST_FIELD_FL_VAR		= 1 << 12,
309 	HIST_FIELD_FL_EXPR		= 1 << 13,
310 	HIST_FIELD_FL_VAR_REF		= 1 << 14,
311 	HIST_FIELD_FL_CPU		= 1 << 15,
312 	HIST_FIELD_FL_ALIAS		= 1 << 16,
313 };
314 
315 struct var_defs {
316 	unsigned int	n_vars;
317 	char		*name[TRACING_MAP_VARS_MAX];
318 	char		*expr[TRACING_MAP_VARS_MAX];
319 };
320 
321 struct hist_trigger_attrs {
322 	char		*keys_str;
323 	char		*vals_str;
324 	char		*sort_key_str;
325 	char		*name;
326 	char		*clock;
327 	bool		pause;
328 	bool		cont;
329 	bool		clear;
330 	bool		ts_in_usecs;
331 	unsigned int	map_bits;
332 
333 	char		*assignment_str[TRACING_MAP_VARS_MAX];
334 	unsigned int	n_assignments;
335 
336 	char		*action_str[HIST_ACTIONS_MAX];
337 	unsigned int	n_actions;
338 
339 	struct var_defs	var_defs;
340 };
341 
342 struct field_var {
343 	struct hist_field	*var;
344 	struct hist_field	*val;
345 };
346 
347 struct field_var_hist {
348 	struct hist_trigger_data	*hist_data;
349 	char				*cmd;
350 };
351 
352 struct hist_trigger_data {
353 	struct hist_field               *fields[HIST_FIELDS_MAX];
354 	unsigned int			n_vals;
355 	unsigned int			n_keys;
356 	unsigned int			n_fields;
357 	unsigned int			n_vars;
358 	unsigned int			key_size;
359 	struct tracing_map_sort_key	sort_keys[TRACING_MAP_SORT_KEYS_MAX];
360 	unsigned int			n_sort_keys;
361 	struct trace_event_file		*event_file;
362 	struct hist_trigger_attrs	*attrs;
363 	struct tracing_map		*map;
364 	bool				enable_timestamps;
365 	bool				remove;
366 	struct hist_field               *var_refs[TRACING_MAP_VARS_MAX];
367 	unsigned int			n_var_refs;
368 
369 	struct action_data		*actions[HIST_ACTIONS_MAX];
370 	unsigned int			n_actions;
371 
372 	struct field_var		*field_vars[SYNTH_FIELDS_MAX];
373 	unsigned int			n_field_vars;
374 	unsigned int			n_field_var_str;
375 	struct field_var_hist		*field_var_hists[SYNTH_FIELDS_MAX];
376 	unsigned int			n_field_var_hists;
377 
378 	struct field_var		*save_vars[SYNTH_FIELDS_MAX];
379 	unsigned int			n_save_vars;
380 	unsigned int			n_save_var_str;
381 };
382 
383 static int create_synth_event(int argc, const char **argv);
384 static int synth_event_show(struct seq_file *m, struct dyn_event *ev);
385 static int synth_event_release(struct dyn_event *ev);
386 static bool synth_event_is_busy(struct dyn_event *ev);
387 static bool synth_event_match(const char *system, const char *event,
388 			int argc, const char **argv, struct dyn_event *ev);
389 
390 static struct dyn_event_operations synth_event_ops = {
391 	.create = create_synth_event,
392 	.show = synth_event_show,
393 	.is_busy = synth_event_is_busy,
394 	.free = synth_event_release,
395 	.match = synth_event_match,
396 };
397 
398 struct synth_field {
399 	char *type;
400 	char *name;
401 	size_t size;
402 	unsigned int offset;
403 	bool is_signed;
404 	bool is_string;
405 };
406 
407 struct synth_event {
408 	struct dyn_event			devent;
409 	int					ref;
410 	char					*name;
411 	struct synth_field			**fields;
412 	unsigned int				n_fields;
413 	unsigned int				n_u64;
414 	struct trace_event_class		class;
415 	struct trace_event_call			call;
416 	struct tracepoint			*tp;
417 	struct module				*mod;
418 };
419 
420 static bool is_synth_event(struct dyn_event *ev)
421 {
422 	return ev->ops == &synth_event_ops;
423 }
424 
425 static struct synth_event *to_synth_event(struct dyn_event *ev)
426 {
427 	return container_of(ev, struct synth_event, devent);
428 }
429 
430 static bool synth_event_is_busy(struct dyn_event *ev)
431 {
432 	struct synth_event *event = to_synth_event(ev);
433 
434 	return event->ref != 0;
435 }
436 
437 static bool synth_event_match(const char *system, const char *event,
438 			int argc, const char **argv, struct dyn_event *ev)
439 {
440 	struct synth_event *sev = to_synth_event(ev);
441 
442 	return strcmp(sev->name, event) == 0 &&
443 		(!system || strcmp(system, SYNTH_SYSTEM) == 0);
444 }
445 
446 struct action_data;
447 
448 typedef void (*action_fn_t) (struct hist_trigger_data *hist_data,
449 			     struct tracing_map_elt *elt, void *rec,
450 			     struct ring_buffer_event *rbe, void *key,
451 			     struct action_data *data, u64 *var_ref_vals);
452 
453 typedef bool (*check_track_val_fn_t) (u64 track_val, u64 var_val);
454 
455 enum handler_id {
456 	HANDLER_ONMATCH = 1,
457 	HANDLER_ONMAX,
458 	HANDLER_ONCHANGE,
459 };
460 
461 enum action_id {
462 	ACTION_SAVE = 1,
463 	ACTION_TRACE,
464 	ACTION_SNAPSHOT,
465 };
466 
467 struct action_data {
468 	enum handler_id		handler;
469 	enum action_id		action;
470 	char			*action_name;
471 	action_fn_t		fn;
472 
473 	unsigned int		n_params;
474 	char			*params[SYNTH_FIELDS_MAX];
475 
476 	/*
477 	 * When a histogram trigger is hit, the values of any
478 	 * references to variables, including variables being passed
479 	 * as parameters to synthetic events, are collected into a
480 	 * var_ref_vals array.  This var_ref_idx array is an array of
481 	 * indices into the var_ref_vals array, one for each synthetic
482 	 * event param, and is passed to the synthetic event
483 	 * invocation.
484 	 */
485 	unsigned int		var_ref_idx[TRACING_MAP_VARS_MAX];
486 	struct synth_event	*synth_event;
487 	bool			use_trace_keyword;
488 	char			*synth_event_name;
489 
490 	union {
491 		struct {
492 			char			*event;
493 			char			*event_system;
494 		} match_data;
495 
496 		struct {
497 			/*
498 			 * var_str contains the $-unstripped variable
499 			 * name referenced by var_ref, and used when
500 			 * printing the action.  Because var_ref
501 			 * creation is deferred to create_actions(),
502 			 * we need a per-action way to save it until
503 			 * then, thus var_str.
504 			 */
505 			char			*var_str;
506 
507 			/*
508 			 * var_ref refers to the variable being
509 			 * tracked e.g onmax($var).
510 			 */
511 			struct hist_field	*var_ref;
512 
513 			/*
514 			 * track_var contains the 'invisible' tracking
515 			 * variable created to keep the current
516 			 * e.g. max value.
517 			 */
518 			struct hist_field	*track_var;
519 
520 			check_track_val_fn_t	check_val;
521 			action_fn_t		save_data;
522 		} track_data;
523 	};
524 };
525 
526 struct track_data {
527 	u64				track_val;
528 	bool				updated;
529 
530 	unsigned int			key_len;
531 	void				*key;
532 	struct tracing_map_elt		elt;
533 
534 	struct action_data		*action_data;
535 	struct hist_trigger_data	*hist_data;
536 };
537 
538 struct hist_elt_data {
539 	char *comm;
540 	u64 *var_ref_vals;
541 	char *field_var_str[SYNTH_FIELDS_MAX];
542 };
543 
544 struct snapshot_context {
545 	struct tracing_map_elt	*elt;
546 	void			*key;
547 };
548 
549 static void track_data_free(struct track_data *track_data)
550 {
551 	struct hist_elt_data *elt_data;
552 
553 	if (!track_data)
554 		return;
555 
556 	kfree(track_data->key);
557 
558 	elt_data = track_data->elt.private_data;
559 	if (elt_data) {
560 		kfree(elt_data->comm);
561 		kfree(elt_data);
562 	}
563 
564 	kfree(track_data);
565 }
566 
567 static struct track_data *track_data_alloc(unsigned int key_len,
568 					   struct action_data *action_data,
569 					   struct hist_trigger_data *hist_data)
570 {
571 	struct track_data *data = kzalloc(sizeof(*data), GFP_KERNEL);
572 	struct hist_elt_data *elt_data;
573 
574 	if (!data)
575 		return ERR_PTR(-ENOMEM);
576 
577 	data->key = kzalloc(key_len, GFP_KERNEL);
578 	if (!data->key) {
579 		track_data_free(data);
580 		return ERR_PTR(-ENOMEM);
581 	}
582 
583 	data->key_len = key_len;
584 	data->action_data = action_data;
585 	data->hist_data = hist_data;
586 
587 	elt_data = kzalloc(sizeof(*elt_data), GFP_KERNEL);
588 	if (!elt_data) {
589 		track_data_free(data);
590 		return ERR_PTR(-ENOMEM);
591 	}
592 	data->elt.private_data = elt_data;
593 
594 	elt_data->comm = kzalloc(TASK_COMM_LEN, GFP_KERNEL);
595 	if (!elt_data->comm) {
596 		track_data_free(data);
597 		return ERR_PTR(-ENOMEM);
598 	}
599 
600 	return data;
601 }
602 
603 static char last_cmd[MAX_FILTER_STR_VAL];
604 static char last_cmd_loc[MAX_FILTER_STR_VAL];
605 
606 static int errpos(char *str)
607 {
608 	return err_pos(last_cmd, str);
609 }
610 
611 static void last_cmd_set(struct trace_event_file *file, char *str)
612 {
613 	const char *system = NULL, *name = NULL;
614 	struct trace_event_call *call;
615 
616 	if (!str)
617 		return;
618 
619 	strcpy(last_cmd, "hist:");
620 	strncat(last_cmd, str, MAX_FILTER_STR_VAL - 1 - sizeof("hist:"));
621 
622 	if (file) {
623 		call = file->event_call;
624 
625 		system = call->class->system;
626 		if (system) {
627 			name = trace_event_name(call);
628 			if (!name)
629 				system = NULL;
630 		}
631 	}
632 
633 	if (system)
634 		snprintf(last_cmd_loc, MAX_FILTER_STR_VAL, "hist:%s:%s", system, name);
635 }
636 
637 static void hist_err(struct trace_array *tr, u8 err_type, u8 err_pos)
638 {
639 	tracing_log_err(tr, last_cmd_loc, last_cmd, err_text,
640 			err_type, err_pos);
641 }
642 
643 static void hist_err_clear(void)
644 {
645 	last_cmd[0] = '\0';
646 	last_cmd_loc[0] = '\0';
647 }
648 
649 struct synth_trace_event {
650 	struct trace_entry	ent;
651 	u64			fields[];
652 };
653 
654 static int synth_event_define_fields(struct trace_event_call *call)
655 {
656 	struct synth_trace_event trace;
657 	int offset = offsetof(typeof(trace), fields);
658 	struct synth_event *event = call->data;
659 	unsigned int i, size, n_u64;
660 	char *name, *type;
661 	bool is_signed;
662 	int ret = 0;
663 
664 	for (i = 0, n_u64 = 0; i < event->n_fields; i++) {
665 		size = event->fields[i]->size;
666 		is_signed = event->fields[i]->is_signed;
667 		type = event->fields[i]->type;
668 		name = event->fields[i]->name;
669 		ret = trace_define_field(call, type, name, offset, size,
670 					 is_signed, FILTER_OTHER);
671 		if (ret)
672 			break;
673 
674 		event->fields[i]->offset = n_u64;
675 
676 		if (event->fields[i]->is_string) {
677 			offset += STR_VAR_LEN_MAX;
678 			n_u64 += STR_VAR_LEN_MAX / sizeof(u64);
679 		} else {
680 			offset += sizeof(u64);
681 			n_u64++;
682 		}
683 	}
684 
685 	event->n_u64 = n_u64;
686 
687 	return ret;
688 }
689 
690 static bool synth_field_signed(char *type)
691 {
692 	if (str_has_prefix(type, "u"))
693 		return false;
694 	if (strcmp(type, "gfp_t") == 0)
695 		return false;
696 
697 	return true;
698 }
699 
700 static int synth_field_is_string(char *type)
701 {
702 	if (strstr(type, "char[") != NULL)
703 		return true;
704 
705 	return false;
706 }
707 
708 static int synth_field_string_size(char *type)
709 {
710 	char buf[4], *end, *start;
711 	unsigned int len;
712 	int size, err;
713 
714 	start = strstr(type, "char[");
715 	if (start == NULL)
716 		return -EINVAL;
717 	start += sizeof("char[") - 1;
718 
719 	end = strchr(type, ']');
720 	if (!end || end < start)
721 		return -EINVAL;
722 
723 	len = end - start;
724 	if (len > 3)
725 		return -EINVAL;
726 
727 	strncpy(buf, start, len);
728 	buf[len] = '\0';
729 
730 	err = kstrtouint(buf, 0, &size);
731 	if (err)
732 		return err;
733 
734 	if (size > STR_VAR_LEN_MAX)
735 		return -EINVAL;
736 
737 	return size;
738 }
739 
740 static int synth_field_size(char *type)
741 {
742 	int size = 0;
743 
744 	if (strcmp(type, "s64") == 0)
745 		size = sizeof(s64);
746 	else if (strcmp(type, "u64") == 0)
747 		size = sizeof(u64);
748 	else if (strcmp(type, "s32") == 0)
749 		size = sizeof(s32);
750 	else if (strcmp(type, "u32") == 0)
751 		size = sizeof(u32);
752 	else if (strcmp(type, "s16") == 0)
753 		size = sizeof(s16);
754 	else if (strcmp(type, "u16") == 0)
755 		size = sizeof(u16);
756 	else if (strcmp(type, "s8") == 0)
757 		size = sizeof(s8);
758 	else if (strcmp(type, "u8") == 0)
759 		size = sizeof(u8);
760 	else if (strcmp(type, "char") == 0)
761 		size = sizeof(char);
762 	else if (strcmp(type, "unsigned char") == 0)
763 		size = sizeof(unsigned char);
764 	else if (strcmp(type, "int") == 0)
765 		size = sizeof(int);
766 	else if (strcmp(type, "unsigned int") == 0)
767 		size = sizeof(unsigned int);
768 	else if (strcmp(type, "long") == 0)
769 		size = sizeof(long);
770 	else if (strcmp(type, "unsigned long") == 0)
771 		size = sizeof(unsigned long);
772 	else if (strcmp(type, "pid_t") == 0)
773 		size = sizeof(pid_t);
774 	else if (strcmp(type, "gfp_t") == 0)
775 		size = sizeof(gfp_t);
776 	else if (synth_field_is_string(type))
777 		size = synth_field_string_size(type);
778 
779 	return size;
780 }
781 
782 static const char *synth_field_fmt(char *type)
783 {
784 	const char *fmt = "%llu";
785 
786 	if (strcmp(type, "s64") == 0)
787 		fmt = "%lld";
788 	else if (strcmp(type, "u64") == 0)
789 		fmt = "%llu";
790 	else if (strcmp(type, "s32") == 0)
791 		fmt = "%d";
792 	else if (strcmp(type, "u32") == 0)
793 		fmt = "%u";
794 	else if (strcmp(type, "s16") == 0)
795 		fmt = "%d";
796 	else if (strcmp(type, "u16") == 0)
797 		fmt = "%u";
798 	else if (strcmp(type, "s8") == 0)
799 		fmt = "%d";
800 	else if (strcmp(type, "u8") == 0)
801 		fmt = "%u";
802 	else if (strcmp(type, "char") == 0)
803 		fmt = "%d";
804 	else if (strcmp(type, "unsigned char") == 0)
805 		fmt = "%u";
806 	else if (strcmp(type, "int") == 0)
807 		fmt = "%d";
808 	else if (strcmp(type, "unsigned int") == 0)
809 		fmt = "%u";
810 	else if (strcmp(type, "long") == 0)
811 		fmt = "%ld";
812 	else if (strcmp(type, "unsigned long") == 0)
813 		fmt = "%lu";
814 	else if (strcmp(type, "pid_t") == 0)
815 		fmt = "%d";
816 	else if (strcmp(type, "gfp_t") == 0)
817 		fmt = "%x";
818 	else if (synth_field_is_string(type))
819 		fmt = "%s";
820 
821 	return fmt;
822 }
823 
824 static enum print_line_t print_synth_event(struct trace_iterator *iter,
825 					   int flags,
826 					   struct trace_event *event)
827 {
828 	struct trace_array *tr = iter->tr;
829 	struct trace_seq *s = &iter->seq;
830 	struct synth_trace_event *entry;
831 	struct synth_event *se;
832 	unsigned int i, n_u64;
833 	char print_fmt[32];
834 	const char *fmt;
835 
836 	entry = (struct synth_trace_event *)iter->ent;
837 	se = container_of(event, struct synth_event, call.event);
838 
839 	trace_seq_printf(s, "%s: ", se->name);
840 
841 	for (i = 0, n_u64 = 0; i < se->n_fields; i++) {
842 		if (trace_seq_has_overflowed(s))
843 			goto end;
844 
845 		fmt = synth_field_fmt(se->fields[i]->type);
846 
847 		/* parameter types */
848 		if (tr && tr->trace_flags & TRACE_ITER_VERBOSE)
849 			trace_seq_printf(s, "%s ", fmt);
850 
851 		snprintf(print_fmt, sizeof(print_fmt), "%%s=%s%%s", fmt);
852 
853 		/* parameter values */
854 		if (se->fields[i]->is_string) {
855 			trace_seq_printf(s, print_fmt, se->fields[i]->name,
856 					 (char *)&entry->fields[n_u64],
857 					 i == se->n_fields - 1 ? "" : " ");
858 			n_u64 += STR_VAR_LEN_MAX / sizeof(u64);
859 		} else {
860 			struct trace_print_flags __flags[] = {
861 			    __def_gfpflag_names, {-1, NULL} };
862 
863 			trace_seq_printf(s, print_fmt, se->fields[i]->name,
864 					 entry->fields[n_u64],
865 					 i == se->n_fields - 1 ? "" : " ");
866 
867 			if (strcmp(se->fields[i]->type, "gfp_t") == 0) {
868 				trace_seq_puts(s, " (");
869 				trace_print_flags_seq(s, "|",
870 						      entry->fields[n_u64],
871 						      __flags);
872 				trace_seq_putc(s, ')');
873 			}
874 			n_u64++;
875 		}
876 	}
877 end:
878 	trace_seq_putc(s, '\n');
879 
880 	return trace_handle_return(s);
881 }
882 
883 static struct trace_event_functions synth_event_funcs = {
884 	.trace		= print_synth_event
885 };
886 
887 static notrace void trace_event_raw_event_synth(void *__data,
888 						u64 *var_ref_vals,
889 						unsigned int *var_ref_idx)
890 {
891 	struct trace_event_file *trace_file = __data;
892 	struct synth_trace_event *entry;
893 	struct trace_event_buffer fbuffer;
894 	struct trace_buffer *buffer;
895 	struct synth_event *event;
896 	unsigned int i, n_u64, val_idx;
897 	int fields_size = 0;
898 
899 	event = trace_file->event_call->data;
900 
901 	if (trace_trigger_soft_disabled(trace_file))
902 		return;
903 
904 	fields_size = event->n_u64 * sizeof(u64);
905 
906 	/*
907 	 * Avoid ring buffer recursion detection, as this event
908 	 * is being performed within another event.
909 	 */
910 	buffer = trace_file->tr->array_buffer.buffer;
911 	ring_buffer_nest_start(buffer);
912 
913 	entry = trace_event_buffer_reserve(&fbuffer, trace_file,
914 					   sizeof(*entry) + fields_size);
915 	if (!entry)
916 		goto out;
917 
918 	for (i = 0, n_u64 = 0; i < event->n_fields; i++) {
919 		val_idx = var_ref_idx[i];
920 		if (event->fields[i]->is_string) {
921 			char *str_val = (char *)(long)var_ref_vals[val_idx];
922 			char *str_field = (char *)&entry->fields[n_u64];
923 
924 			strscpy(str_field, str_val, STR_VAR_LEN_MAX);
925 			n_u64 += STR_VAR_LEN_MAX / sizeof(u64);
926 		} else {
927 			struct synth_field *field = event->fields[i];
928 			u64 val = var_ref_vals[val_idx];
929 
930 			switch (field->size) {
931 			case 1:
932 				*(u8 *)&entry->fields[n_u64] = (u8)val;
933 				break;
934 
935 			case 2:
936 				*(u16 *)&entry->fields[n_u64] = (u16)val;
937 				break;
938 
939 			case 4:
940 				*(u32 *)&entry->fields[n_u64] = (u32)val;
941 				break;
942 
943 			default:
944 				entry->fields[n_u64] = val;
945 				break;
946 			}
947 			n_u64++;
948 		}
949 	}
950 
951 	trace_event_buffer_commit(&fbuffer);
952 out:
953 	ring_buffer_nest_end(buffer);
954 }
955 
956 static void free_synth_event_print_fmt(struct trace_event_call *call)
957 {
958 	if (call) {
959 		kfree(call->print_fmt);
960 		call->print_fmt = NULL;
961 	}
962 }
963 
964 static int __set_synth_event_print_fmt(struct synth_event *event,
965 				       char *buf, int len)
966 {
967 	const char *fmt;
968 	int pos = 0;
969 	int i;
970 
971 	/* When len=0, we just calculate the needed length */
972 #define LEN_OR_ZERO (len ? len - pos : 0)
973 
974 	pos += snprintf(buf + pos, LEN_OR_ZERO, "\"");
975 	for (i = 0; i < event->n_fields; i++) {
976 		fmt = synth_field_fmt(event->fields[i]->type);
977 		pos += snprintf(buf + pos, LEN_OR_ZERO, "%s=%s%s",
978 				event->fields[i]->name, fmt,
979 				i == event->n_fields - 1 ? "" : ", ");
980 	}
981 	pos += snprintf(buf + pos, LEN_OR_ZERO, "\"");
982 
983 	for (i = 0; i < event->n_fields; i++) {
984 		pos += snprintf(buf + pos, LEN_OR_ZERO,
985 				", REC->%s", event->fields[i]->name);
986 	}
987 
988 #undef LEN_OR_ZERO
989 
990 	/* return the length of print_fmt */
991 	return pos;
992 }
993 
994 static int set_synth_event_print_fmt(struct trace_event_call *call)
995 {
996 	struct synth_event *event = call->data;
997 	char *print_fmt;
998 	int len;
999 
1000 	/* First: called with 0 length to calculate the needed length */
1001 	len = __set_synth_event_print_fmt(event, NULL, 0);
1002 
1003 	print_fmt = kmalloc(len + 1, GFP_KERNEL);
1004 	if (!print_fmt)
1005 		return -ENOMEM;
1006 
1007 	/* Second: actually write the @print_fmt */
1008 	__set_synth_event_print_fmt(event, print_fmt, len + 1);
1009 	call->print_fmt = print_fmt;
1010 
1011 	return 0;
1012 }
1013 
1014 static void free_synth_field(struct synth_field *field)
1015 {
1016 	kfree(field->type);
1017 	kfree(field->name);
1018 	kfree(field);
1019 }
1020 
1021 static struct synth_field *parse_synth_field(int argc, const char **argv,
1022 					     int *consumed)
1023 {
1024 	struct synth_field *field;
1025 	const char *prefix = NULL, *field_type = argv[0], *field_name, *array;
1026 	int len, ret = 0;
1027 
1028 	if (field_type[0] == ';')
1029 		field_type++;
1030 
1031 	if (!strcmp(field_type, "unsigned")) {
1032 		if (argc < 3)
1033 			return ERR_PTR(-EINVAL);
1034 		prefix = "unsigned ";
1035 		field_type = argv[1];
1036 		field_name = argv[2];
1037 		*consumed = 3;
1038 	} else {
1039 		field_name = argv[1];
1040 		*consumed = 2;
1041 	}
1042 
1043 	field = kzalloc(sizeof(*field), GFP_KERNEL);
1044 	if (!field)
1045 		return ERR_PTR(-ENOMEM);
1046 
1047 	len = strlen(field_name);
1048 	array = strchr(field_name, '[');
1049 	if (array)
1050 		len -= strlen(array);
1051 	else if (field_name[len - 1] == ';')
1052 		len--;
1053 
1054 	field->name = kmemdup_nul(field_name, len, GFP_KERNEL);
1055 	if (!field->name) {
1056 		ret = -ENOMEM;
1057 		goto free;
1058 	}
1059 
1060 	if (field_type[0] == ';')
1061 		field_type++;
1062 	len = strlen(field_type) + 1;
1063 	if (array)
1064 		len += strlen(array);
1065 	if (prefix)
1066 		len += strlen(prefix);
1067 
1068 	field->type = kzalloc(len, GFP_KERNEL);
1069 	if (!field->type) {
1070 		ret = -ENOMEM;
1071 		goto free;
1072 	}
1073 	if (prefix)
1074 		strcat(field->type, prefix);
1075 	strcat(field->type, field_type);
1076 	if (array) {
1077 		strcat(field->type, array);
1078 		if (field->type[len - 1] == ';')
1079 			field->type[len - 1] = '\0';
1080 	}
1081 
1082 	field->size = synth_field_size(field->type);
1083 	if (!field->size) {
1084 		ret = -EINVAL;
1085 		goto free;
1086 	}
1087 
1088 	if (synth_field_is_string(field->type))
1089 		field->is_string = true;
1090 
1091 	field->is_signed = synth_field_signed(field->type);
1092 
1093  out:
1094 	return field;
1095  free:
1096 	free_synth_field(field);
1097 	field = ERR_PTR(ret);
1098 	goto out;
1099 }
1100 
1101 static void free_synth_tracepoint(struct tracepoint *tp)
1102 {
1103 	if (!tp)
1104 		return;
1105 
1106 	kfree(tp->name);
1107 	kfree(tp);
1108 }
1109 
1110 static struct tracepoint *alloc_synth_tracepoint(char *name)
1111 {
1112 	struct tracepoint *tp;
1113 
1114 	tp = kzalloc(sizeof(*tp), GFP_KERNEL);
1115 	if (!tp)
1116 		return ERR_PTR(-ENOMEM);
1117 
1118 	tp->name = kstrdup(name, GFP_KERNEL);
1119 	if (!tp->name) {
1120 		kfree(tp);
1121 		return ERR_PTR(-ENOMEM);
1122 	}
1123 
1124 	return tp;
1125 }
1126 
1127 typedef void (*synth_probe_func_t) (void *__data, u64 *var_ref_vals,
1128 				    unsigned int *var_ref_idx);
1129 
1130 static inline void trace_synth(struct synth_event *event, u64 *var_ref_vals,
1131 			       unsigned int *var_ref_idx)
1132 {
1133 	struct tracepoint *tp = event->tp;
1134 
1135 	if (unlikely(atomic_read(&tp->key.enabled) > 0)) {
1136 		struct tracepoint_func *probe_func_ptr;
1137 		synth_probe_func_t probe_func;
1138 		void *__data;
1139 
1140 		if (!(cpu_online(raw_smp_processor_id())))
1141 			return;
1142 
1143 		probe_func_ptr = rcu_dereference_sched((tp)->funcs);
1144 		if (probe_func_ptr) {
1145 			do {
1146 				probe_func = probe_func_ptr->func;
1147 				__data = probe_func_ptr->data;
1148 				probe_func(__data, var_ref_vals, var_ref_idx);
1149 			} while ((++probe_func_ptr)->func);
1150 		}
1151 	}
1152 }
1153 
1154 static struct synth_event *find_synth_event(const char *name)
1155 {
1156 	struct dyn_event *pos;
1157 	struct synth_event *event;
1158 
1159 	for_each_dyn_event(pos) {
1160 		if (!is_synth_event(pos))
1161 			continue;
1162 		event = to_synth_event(pos);
1163 		if (strcmp(event->name, name) == 0)
1164 			return event;
1165 	}
1166 
1167 	return NULL;
1168 }
1169 
1170 static struct trace_event_fields synth_event_fields_array[] = {
1171 	{ .type = TRACE_FUNCTION_TYPE,
1172 	  .define_fields = synth_event_define_fields },
1173 	{}
1174 };
1175 
1176 static int register_synth_event(struct synth_event *event)
1177 {
1178 	struct trace_event_call *call = &event->call;
1179 	int ret = 0;
1180 
1181 	event->call.class = &event->class;
1182 	event->class.system = kstrdup(SYNTH_SYSTEM, GFP_KERNEL);
1183 	if (!event->class.system) {
1184 		ret = -ENOMEM;
1185 		goto out;
1186 	}
1187 
1188 	event->tp = alloc_synth_tracepoint(event->name);
1189 	if (IS_ERR(event->tp)) {
1190 		ret = PTR_ERR(event->tp);
1191 		event->tp = NULL;
1192 		goto out;
1193 	}
1194 
1195 	INIT_LIST_HEAD(&call->class->fields);
1196 	call->event.funcs = &synth_event_funcs;
1197 	call->class->fields_array = synth_event_fields_array;
1198 
1199 	ret = register_trace_event(&call->event);
1200 	if (!ret) {
1201 		ret = -ENODEV;
1202 		goto out;
1203 	}
1204 	call->flags = TRACE_EVENT_FL_TRACEPOINT;
1205 	call->class->reg = trace_event_reg;
1206 	call->class->probe = trace_event_raw_event_synth;
1207 	call->data = event;
1208 	call->tp = event->tp;
1209 
1210 	ret = trace_add_event_call(call);
1211 	if (ret) {
1212 		pr_warn("Failed to register synthetic event: %s\n",
1213 			trace_event_name(call));
1214 		goto err;
1215 	}
1216 
1217 	ret = set_synth_event_print_fmt(call);
1218 	if (ret < 0) {
1219 		trace_remove_event_call(call);
1220 		goto err;
1221 	}
1222  out:
1223 	return ret;
1224  err:
1225 	unregister_trace_event(&call->event);
1226 	goto out;
1227 }
1228 
1229 static int unregister_synth_event(struct synth_event *event)
1230 {
1231 	struct trace_event_call *call = &event->call;
1232 	int ret;
1233 
1234 	ret = trace_remove_event_call(call);
1235 
1236 	return ret;
1237 }
1238 
1239 static void free_synth_event(struct synth_event *event)
1240 {
1241 	unsigned int i;
1242 
1243 	if (!event)
1244 		return;
1245 
1246 	for (i = 0; i < event->n_fields; i++)
1247 		free_synth_field(event->fields[i]);
1248 
1249 	kfree(event->fields);
1250 	kfree(event->name);
1251 	kfree(event->class.system);
1252 	free_synth_tracepoint(event->tp);
1253 	free_synth_event_print_fmt(&event->call);
1254 	kfree(event);
1255 }
1256 
1257 static struct synth_event *alloc_synth_event(const char *name, int n_fields,
1258 					     struct synth_field **fields)
1259 {
1260 	struct synth_event *event;
1261 	unsigned int i;
1262 
1263 	event = kzalloc(sizeof(*event), GFP_KERNEL);
1264 	if (!event) {
1265 		event = ERR_PTR(-ENOMEM);
1266 		goto out;
1267 	}
1268 
1269 	event->name = kstrdup(name, GFP_KERNEL);
1270 	if (!event->name) {
1271 		kfree(event);
1272 		event = ERR_PTR(-ENOMEM);
1273 		goto out;
1274 	}
1275 
1276 	event->fields = kcalloc(n_fields, sizeof(*event->fields), GFP_KERNEL);
1277 	if (!event->fields) {
1278 		free_synth_event(event);
1279 		event = ERR_PTR(-ENOMEM);
1280 		goto out;
1281 	}
1282 
1283 	dyn_event_init(&event->devent, &synth_event_ops);
1284 
1285 	for (i = 0; i < n_fields; i++)
1286 		event->fields[i] = fields[i];
1287 
1288 	event->n_fields = n_fields;
1289  out:
1290 	return event;
1291 }
1292 
1293 static void action_trace(struct hist_trigger_data *hist_data,
1294 			 struct tracing_map_elt *elt, void *rec,
1295 			 struct ring_buffer_event *rbe, void *key,
1296 			 struct action_data *data, u64 *var_ref_vals)
1297 {
1298 	struct synth_event *event = data->synth_event;
1299 
1300 	trace_synth(event, var_ref_vals, data->var_ref_idx);
1301 }
1302 
1303 struct hist_var_data {
1304 	struct list_head list;
1305 	struct hist_trigger_data *hist_data;
1306 };
1307 
1308 static int synth_event_check_arg_fn(void *data)
1309 {
1310 	struct dynevent_arg_pair *arg_pair = data;
1311 	int size;
1312 
1313 	size = synth_field_size((char *)arg_pair->lhs);
1314 
1315 	return size ? 0 : -EINVAL;
1316 }
1317 
1318 /**
1319  * synth_event_add_field - Add a new field to a synthetic event cmd
1320  * @cmd: A pointer to the dynevent_cmd struct representing the new event
1321  * @type: The type of the new field to add
1322  * @name: The name of the new field to add
1323  *
1324  * Add a new field to a synthetic event cmd object.  Field ordering is in
1325  * the same order the fields are added.
1326  *
1327  * See synth_field_size() for available types. If field_name contains
1328  * [n] the field is considered to be an array.
1329  *
1330  * Return: 0 if successful, error otherwise.
1331  */
1332 int synth_event_add_field(struct dynevent_cmd *cmd, const char *type,
1333 			  const char *name)
1334 {
1335 	struct dynevent_arg_pair arg_pair;
1336 	int ret;
1337 
1338 	if (cmd->type != DYNEVENT_TYPE_SYNTH)
1339 		return -EINVAL;
1340 
1341 	if (!type || !name)
1342 		return -EINVAL;
1343 
1344 	dynevent_arg_pair_init(&arg_pair, 0, ';');
1345 
1346 	arg_pair.lhs = type;
1347 	arg_pair.rhs = name;
1348 
1349 	ret = dynevent_arg_pair_add(cmd, &arg_pair, synth_event_check_arg_fn);
1350 	if (ret)
1351 		return ret;
1352 
1353 	if (++cmd->n_fields > SYNTH_FIELDS_MAX)
1354 		ret = -EINVAL;
1355 
1356 	return ret;
1357 }
1358 EXPORT_SYMBOL_GPL(synth_event_add_field);
1359 
1360 /**
1361  * synth_event_add_field_str - Add a new field to a synthetic event cmd
1362  * @cmd: A pointer to the dynevent_cmd struct representing the new event
1363  * @type_name: The type and name of the new field to add, as a single string
1364  *
1365  * Add a new field to a synthetic event cmd object, as a single
1366  * string.  The @type_name string is expected to be of the form 'type
1367  * name', which will be appended by ';'.  No sanity checking is done -
1368  * what's passed in is assumed to already be well-formed.  Field
1369  * ordering is in the same order the fields are added.
1370  *
1371  * See synth_field_size() for available types. If field_name contains
1372  * [n] the field is considered to be an array.
1373  *
1374  * Return: 0 if successful, error otherwise.
1375  */
1376 int synth_event_add_field_str(struct dynevent_cmd *cmd, const char *type_name)
1377 {
1378 	struct dynevent_arg arg;
1379 	int ret;
1380 
1381 	if (cmd->type != DYNEVENT_TYPE_SYNTH)
1382 		return -EINVAL;
1383 
1384 	if (!type_name)
1385 		return -EINVAL;
1386 
1387 	dynevent_arg_init(&arg, ';');
1388 
1389 	arg.str = type_name;
1390 
1391 	ret = dynevent_arg_add(cmd, &arg, NULL);
1392 	if (ret)
1393 		return ret;
1394 
1395 	if (++cmd->n_fields > SYNTH_FIELDS_MAX)
1396 		ret = -EINVAL;
1397 
1398 	return ret;
1399 }
1400 EXPORT_SYMBOL_GPL(synth_event_add_field_str);
1401 
1402 /**
1403  * synth_event_add_fields - Add multiple fields to a synthetic event cmd
1404  * @cmd: A pointer to the dynevent_cmd struct representing the new event
1405  * @fields: An array of type/name field descriptions
1406  * @n_fields: The number of field descriptions contained in the fields array
1407  *
1408  * Add a new set of fields to a synthetic event cmd object.  The event
1409  * fields that will be defined for the event should be passed in as an
1410  * array of struct synth_field_desc, and the number of elements in the
1411  * array passed in as n_fields.  Field ordering will retain the
1412  * ordering given in the fields array.
1413  *
1414  * See synth_field_size() for available types. If field_name contains
1415  * [n] the field is considered to be an array.
1416  *
1417  * Return: 0 if successful, error otherwise.
1418  */
1419 int synth_event_add_fields(struct dynevent_cmd *cmd,
1420 			   struct synth_field_desc *fields,
1421 			   unsigned int n_fields)
1422 {
1423 	unsigned int i;
1424 	int ret = 0;
1425 
1426 	for (i = 0; i < n_fields; i++) {
1427 		if (fields[i].type == NULL || fields[i].name == NULL) {
1428 			ret = -EINVAL;
1429 			break;
1430 		}
1431 
1432 		ret = synth_event_add_field(cmd, fields[i].type, fields[i].name);
1433 		if (ret)
1434 			break;
1435 	}
1436 
1437 	return ret;
1438 }
1439 EXPORT_SYMBOL_GPL(synth_event_add_fields);
1440 
1441 /**
1442  * __synth_event_gen_cmd_start - Start a synthetic event command from arg list
1443  * @cmd: A pointer to the dynevent_cmd struct representing the new event
1444  * @name: The name of the synthetic event
1445  * @mod: The module creating the event, NULL if not created from a module
1446  * @args: Variable number of arg (pairs), one pair for each field
1447  *
1448  * NOTE: Users normally won't want to call this function directly, but
1449  * rather use the synth_event_gen_cmd_start() wrapper, which
1450  * automatically adds a NULL to the end of the arg list.  If this
1451  * function is used directly, make sure the last arg in the variable
1452  * arg list is NULL.
1453  *
1454  * Generate a synthetic event command to be executed by
1455  * synth_event_gen_cmd_end().  This function can be used to generate
1456  * the complete command or only the first part of it; in the latter
1457  * case, synth_event_add_field(), synth_event_add_field_str(), or
1458  * synth_event_add_fields() can be used to add more fields following
1459  * this.
1460  *
1461  * There should be an even number variable args, each pair consisting
1462  * of a type followed by a field name.
1463  *
1464  * See synth_field_size() for available types. If field_name contains
1465  * [n] the field is considered to be an array.
1466  *
1467  * Return: 0 if successful, error otherwise.
1468  */
1469 int __synth_event_gen_cmd_start(struct dynevent_cmd *cmd, const char *name,
1470 				struct module *mod, ...)
1471 {
1472 	struct dynevent_arg arg;
1473 	va_list args;
1474 	int ret;
1475 
1476 	cmd->event_name = name;
1477 	cmd->private_data = mod;
1478 
1479 	if (cmd->type != DYNEVENT_TYPE_SYNTH)
1480 		return -EINVAL;
1481 
1482 	dynevent_arg_init(&arg, 0);
1483 	arg.str = name;
1484 	ret = dynevent_arg_add(cmd, &arg, NULL);
1485 	if (ret)
1486 		return ret;
1487 
1488 	va_start(args, mod);
1489 	for (;;) {
1490 		const char *type, *name;
1491 
1492 		type = va_arg(args, const char *);
1493 		if (!type)
1494 			break;
1495 		name = va_arg(args, const char *);
1496 		if (!name)
1497 			break;
1498 
1499 		if (++cmd->n_fields > SYNTH_FIELDS_MAX) {
1500 			ret = -EINVAL;
1501 			break;
1502 		}
1503 
1504 		ret = synth_event_add_field(cmd, type, name);
1505 		if (ret)
1506 			break;
1507 	}
1508 	va_end(args);
1509 
1510 	return ret;
1511 }
1512 EXPORT_SYMBOL_GPL(__synth_event_gen_cmd_start);
1513 
1514 /**
1515  * synth_event_gen_cmd_array_start - Start synthetic event command from an array
1516  * @cmd: A pointer to the dynevent_cmd struct representing the new event
1517  * @name: The name of the synthetic event
1518  * @fields: An array of type/name field descriptions
1519  * @n_fields: The number of field descriptions contained in the fields array
1520  *
1521  * Generate a synthetic event command to be executed by
1522  * synth_event_gen_cmd_end().  This function can be used to generate
1523  * the complete command or only the first part of it; in the latter
1524  * case, synth_event_add_field(), synth_event_add_field_str(), or
1525  * synth_event_add_fields() can be used to add more fields following
1526  * this.
1527  *
1528  * The event fields that will be defined for the event should be
1529  * passed in as an array of struct synth_field_desc, and the number of
1530  * elements in the array passed in as n_fields.  Field ordering will
1531  * retain the ordering given in the fields array.
1532  *
1533  * See synth_field_size() for available types. If field_name contains
1534  * [n] the field is considered to be an array.
1535  *
1536  * Return: 0 if successful, error otherwise.
1537  */
1538 int synth_event_gen_cmd_array_start(struct dynevent_cmd *cmd, const char *name,
1539 				    struct module *mod,
1540 				    struct synth_field_desc *fields,
1541 				    unsigned int n_fields)
1542 {
1543 	struct dynevent_arg arg;
1544 	unsigned int i;
1545 	int ret = 0;
1546 
1547 	cmd->event_name = name;
1548 	cmd->private_data = mod;
1549 
1550 	if (cmd->type != DYNEVENT_TYPE_SYNTH)
1551 		return -EINVAL;
1552 
1553 	if (n_fields > SYNTH_FIELDS_MAX)
1554 		return -EINVAL;
1555 
1556 	dynevent_arg_init(&arg, 0);
1557 	arg.str = name;
1558 	ret = dynevent_arg_add(cmd, &arg, NULL);
1559 	if (ret)
1560 		return ret;
1561 
1562 	for (i = 0; i < n_fields; i++) {
1563 		if (fields[i].type == NULL || fields[i].name == NULL)
1564 			return -EINVAL;
1565 
1566 		ret = synth_event_add_field(cmd, fields[i].type, fields[i].name);
1567 		if (ret)
1568 			break;
1569 	}
1570 
1571 	return ret;
1572 }
1573 EXPORT_SYMBOL_GPL(synth_event_gen_cmd_array_start);
1574 
1575 static int __create_synth_event(int argc, const char *name, const char **argv)
1576 {
1577 	struct synth_field *field, *fields[SYNTH_FIELDS_MAX];
1578 	struct synth_event *event = NULL;
1579 	int i, consumed = 0, n_fields = 0, ret = 0;
1580 
1581 	/*
1582 	 * Argument syntax:
1583 	 *  - Add synthetic event: <event_name> field[;field] ...
1584 	 *  - Remove synthetic event: !<event_name> field[;field] ...
1585 	 *      where 'field' = type field_name
1586 	 */
1587 
1588 	if (name[0] == '\0' || argc < 1)
1589 		return -EINVAL;
1590 
1591 	mutex_lock(&event_mutex);
1592 
1593 	event = find_synth_event(name);
1594 	if (event) {
1595 		ret = -EEXIST;
1596 		goto out;
1597 	}
1598 
1599 	for (i = 0; i < argc - 1; i++) {
1600 		if (strcmp(argv[i], ";") == 0)
1601 			continue;
1602 		if (n_fields == SYNTH_FIELDS_MAX) {
1603 			ret = -EINVAL;
1604 			goto err;
1605 		}
1606 
1607 		field = parse_synth_field(argc - i, &argv[i], &consumed);
1608 		if (IS_ERR(field)) {
1609 			ret = PTR_ERR(field);
1610 			goto err;
1611 		}
1612 		fields[n_fields++] = field;
1613 		i += consumed - 1;
1614 	}
1615 
1616 	if (i < argc && strcmp(argv[i], ";") != 0) {
1617 		ret = -EINVAL;
1618 		goto err;
1619 	}
1620 
1621 	event = alloc_synth_event(name, n_fields, fields);
1622 	if (IS_ERR(event)) {
1623 		ret = PTR_ERR(event);
1624 		event = NULL;
1625 		goto err;
1626 	}
1627 	ret = register_synth_event(event);
1628 	if (!ret)
1629 		dyn_event_add(&event->devent);
1630 	else
1631 		free_synth_event(event);
1632  out:
1633 	mutex_unlock(&event_mutex);
1634 
1635 	return ret;
1636  err:
1637 	for (i = 0; i < n_fields; i++)
1638 		free_synth_field(fields[i]);
1639 
1640 	goto out;
1641 }
1642 
1643 /**
1644  * synth_event_create - Create a new synthetic event
1645  * @name: The name of the new sythetic event
1646  * @fields: An array of type/name field descriptions
1647  * @n_fields: The number of field descriptions contained in the fields array
1648  * @mod: The module creating the event, NULL if not created from a module
1649  *
1650  * Create a new synthetic event with the given name under the
1651  * trace/events/synthetic/ directory.  The event fields that will be
1652  * defined for the event should be passed in as an array of struct
1653  * synth_field_desc, and the number elements in the array passed in as
1654  * n_fields. Field ordering will retain the ordering given in the
1655  * fields array.
1656  *
1657  * If the new synthetic event is being created from a module, the mod
1658  * param must be non-NULL.  This will ensure that the trace buffer
1659  * won't contain unreadable events.
1660  *
1661  * The new synth event should be deleted using synth_event_delete()
1662  * function.  The new synthetic event can be generated from modules or
1663  * other kernel code using trace_synth_event() and related functions.
1664  *
1665  * Return: 0 if successful, error otherwise.
1666  */
1667 int synth_event_create(const char *name, struct synth_field_desc *fields,
1668 		       unsigned int n_fields, struct module *mod)
1669 {
1670 	struct dynevent_cmd cmd;
1671 	char *buf;
1672 	int ret;
1673 
1674 	buf = kzalloc(MAX_DYNEVENT_CMD_LEN, GFP_KERNEL);
1675 	if (!buf)
1676 		return -ENOMEM;
1677 
1678 	synth_event_cmd_init(&cmd, buf, MAX_DYNEVENT_CMD_LEN);
1679 
1680 	ret = synth_event_gen_cmd_array_start(&cmd, name, mod,
1681 					      fields, n_fields);
1682 	if (ret)
1683 		goto out;
1684 
1685 	ret = synth_event_gen_cmd_end(&cmd);
1686  out:
1687 	kfree(buf);
1688 
1689 	return ret;
1690 }
1691 EXPORT_SYMBOL_GPL(synth_event_create);
1692 
1693 static int destroy_synth_event(struct synth_event *se)
1694 {
1695 	int ret;
1696 
1697 	if (se->ref)
1698 		ret = -EBUSY;
1699 	else {
1700 		ret = unregister_synth_event(se);
1701 		if (!ret) {
1702 			dyn_event_remove(&se->devent);
1703 			free_synth_event(se);
1704 		}
1705 	}
1706 
1707 	return ret;
1708 }
1709 
1710 /**
1711  * synth_event_delete - Delete a synthetic event
1712  * @event_name: The name of the new sythetic event
1713  *
1714  * Delete a synthetic event that was created with synth_event_create().
1715  *
1716  * Return: 0 if successful, error otherwise.
1717  */
1718 int synth_event_delete(const char *event_name)
1719 {
1720 	struct synth_event *se = NULL;
1721 	struct module *mod = NULL;
1722 	int ret = -ENOENT;
1723 
1724 	mutex_lock(&event_mutex);
1725 	se = find_synth_event(event_name);
1726 	if (se) {
1727 		mod = se->mod;
1728 		ret = destroy_synth_event(se);
1729 	}
1730 	mutex_unlock(&event_mutex);
1731 
1732 	if (mod) {
1733 		mutex_lock(&trace_types_lock);
1734 		/*
1735 		 * It is safest to reset the ring buffer if the module
1736 		 * being unloaded registered any events that were
1737 		 * used. The only worry is if a new module gets
1738 		 * loaded, and takes on the same id as the events of
1739 		 * this module. When printing out the buffer, traced
1740 		 * events left over from this module may be passed to
1741 		 * the new module events and unexpected results may
1742 		 * occur.
1743 		 */
1744 		tracing_reset_all_online_cpus();
1745 		mutex_unlock(&trace_types_lock);
1746 	}
1747 
1748 	return ret;
1749 }
1750 EXPORT_SYMBOL_GPL(synth_event_delete);
1751 
1752 static int create_or_delete_synth_event(int argc, char **argv)
1753 {
1754 	const char *name = argv[0];
1755 	int ret;
1756 
1757 	/* trace_run_command() ensures argc != 0 */
1758 	if (name[0] == '!') {
1759 		ret = synth_event_delete(name + 1);
1760 		return ret;
1761 	}
1762 
1763 	ret = __create_synth_event(argc - 1, name, (const char **)argv + 1);
1764 	return ret == -ECANCELED ? -EINVAL : ret;
1765 }
1766 
1767 static int synth_event_run_command(struct dynevent_cmd *cmd)
1768 {
1769 	struct synth_event *se;
1770 	int ret;
1771 
1772 	ret = trace_run_command(cmd->seq.buffer, create_or_delete_synth_event);
1773 	if (ret)
1774 		return ret;
1775 
1776 	se = find_synth_event(cmd->event_name);
1777 	if (WARN_ON(!se))
1778 		return -ENOENT;
1779 
1780 	se->mod = cmd->private_data;
1781 
1782 	return ret;
1783 }
1784 
1785 /**
1786  * synth_event_cmd_init - Initialize a synthetic event command object
1787  * @cmd: A pointer to the dynevent_cmd struct representing the new event
1788  * @buf: A pointer to the buffer used to build the command
1789  * @maxlen: The length of the buffer passed in @buf
1790  *
1791  * Initialize a synthetic event command object.  Use this before
1792  * calling any of the other dyenvent_cmd functions.
1793  */
1794 void synth_event_cmd_init(struct dynevent_cmd *cmd, char *buf, int maxlen)
1795 {
1796 	dynevent_cmd_init(cmd, buf, maxlen, DYNEVENT_TYPE_SYNTH,
1797 			  synth_event_run_command);
1798 }
1799 EXPORT_SYMBOL_GPL(synth_event_cmd_init);
1800 
1801 static inline int
1802 __synth_event_trace_start(struct trace_event_file *file,
1803 			  struct synth_event_trace_state *trace_state)
1804 {
1805 	int entry_size, fields_size = 0;
1806 	int ret = 0;
1807 
1808 	/*
1809 	 * Normal event tracing doesn't get called at all unless the
1810 	 * ENABLED bit is set (which attaches the probe thus allowing
1811 	 * this code to be called, etc).  Because this is called
1812 	 * directly by the user, we don't have that but we still need
1813 	 * to honor not logging when disabled.  For the the iterated
1814 	 * trace case, we save the enabed state upon start and just
1815 	 * ignore the following data calls.
1816 	 */
1817 	if (!(file->flags & EVENT_FILE_FL_ENABLED) ||
1818 	    trace_trigger_soft_disabled(file)) {
1819 		trace_state->disabled = true;
1820 		ret = -ENOENT;
1821 		goto out;
1822 	}
1823 
1824 	trace_state->event = file->event_call->data;
1825 
1826 	fields_size = trace_state->event->n_u64 * sizeof(u64);
1827 
1828 	/*
1829 	 * Avoid ring buffer recursion detection, as this event
1830 	 * is being performed within another event.
1831 	 */
1832 	trace_state->buffer = file->tr->array_buffer.buffer;
1833 	ring_buffer_nest_start(trace_state->buffer);
1834 
1835 	entry_size = sizeof(*trace_state->entry) + fields_size;
1836 	trace_state->entry = trace_event_buffer_reserve(&trace_state->fbuffer,
1837 							file,
1838 							entry_size);
1839 	if (!trace_state->entry) {
1840 		ring_buffer_nest_end(trace_state->buffer);
1841 		ret = -EINVAL;
1842 	}
1843 out:
1844 	return ret;
1845 }
1846 
1847 static inline void
1848 __synth_event_trace_end(struct synth_event_trace_state *trace_state)
1849 {
1850 	trace_event_buffer_commit(&trace_state->fbuffer);
1851 
1852 	ring_buffer_nest_end(trace_state->buffer);
1853 }
1854 
1855 /**
1856  * synth_event_trace - Trace a synthetic event
1857  * @file: The trace_event_file representing the synthetic event
1858  * @n_vals: The number of values in vals
1859  * @args: Variable number of args containing the event values
1860  *
1861  * Trace a synthetic event using the values passed in the variable
1862  * argument list.
1863  *
1864  * The argument list should be a list 'n_vals' u64 values.  The number
1865  * of vals must match the number of field in the synthetic event, and
1866  * must be in the same order as the synthetic event fields.
1867  *
1868  * All vals should be cast to u64, and string vals are just pointers
1869  * to strings, cast to u64.  Strings will be copied into space
1870  * reserved in the event for the string, using these pointers.
1871  *
1872  * Return: 0 on success, err otherwise.
1873  */
1874 int synth_event_trace(struct trace_event_file *file, unsigned int n_vals, ...)
1875 {
1876 	struct synth_event_trace_state state;
1877 	unsigned int i, n_u64;
1878 	va_list args;
1879 	int ret;
1880 
1881 	ret = __synth_event_trace_start(file, &state);
1882 	if (ret) {
1883 		if (ret == -ENOENT)
1884 			ret = 0; /* just disabled, not really an error */
1885 		return ret;
1886 	}
1887 
1888 	va_start(args, n_vals);
1889 	for (i = 0, n_u64 = 0; i < state.event->n_fields; i++) {
1890 		u64 val;
1891 
1892 		val = va_arg(args, u64);
1893 
1894 		if (state.event->fields[i]->is_string) {
1895 			char *str_val = (char *)(long)val;
1896 			char *str_field = (char *)&state.entry->fields[n_u64];
1897 
1898 			strscpy(str_field, str_val, STR_VAR_LEN_MAX);
1899 			n_u64 += STR_VAR_LEN_MAX / sizeof(u64);
1900 		} else {
1901 			state.entry->fields[n_u64] = val;
1902 			n_u64++;
1903 		}
1904 	}
1905 	va_end(args);
1906 
1907 	__synth_event_trace_end(&state);
1908 
1909 	return ret;
1910 }
1911 EXPORT_SYMBOL_GPL(synth_event_trace);
1912 
1913 /**
1914  * synth_event_trace_array - Trace a synthetic event from an array
1915  * @file: The trace_event_file representing the synthetic event
1916  * @vals: Array of values
1917  * @n_vals: The number of values in vals
1918  *
1919  * Trace a synthetic event using the values passed in as 'vals'.
1920  *
1921  * The 'vals' array is just an array of 'n_vals' u64.  The number of
1922  * vals must match the number of field in the synthetic event, and
1923  * must be in the same order as the synthetic event fields.
1924  *
1925  * All vals should be cast to u64, and string vals are just pointers
1926  * to strings, cast to u64.  Strings will be copied into space
1927  * reserved in the event for the string, using these pointers.
1928  *
1929  * Return: 0 on success, err otherwise.
1930  */
1931 int synth_event_trace_array(struct trace_event_file *file, u64 *vals,
1932 			    unsigned int n_vals)
1933 {
1934 	struct synth_event_trace_state state;
1935 	unsigned int i, n_u64;
1936 	int ret;
1937 
1938 	ret = __synth_event_trace_start(file, &state);
1939 	if (ret) {
1940 		if (ret == -ENOENT)
1941 			ret = 0; /* just disabled, not really an error */
1942 		return ret;
1943 	}
1944 
1945 	for (i = 0, n_u64 = 0; i < state.event->n_fields; i++) {
1946 		if (state.event->fields[i]->is_string) {
1947 			char *str_val = (char *)(long)vals[i];
1948 			char *str_field = (char *)&state.entry->fields[n_u64];
1949 
1950 			strscpy(str_field, str_val, STR_VAR_LEN_MAX);
1951 			n_u64 += STR_VAR_LEN_MAX / sizeof(u64);
1952 		} else {
1953 			state.entry->fields[n_u64] = vals[i];
1954 			n_u64++;
1955 		}
1956 	}
1957 
1958 	__synth_event_trace_end(&state);
1959 
1960 	return ret;
1961 }
1962 EXPORT_SYMBOL_GPL(synth_event_trace_array);
1963 
1964 /**
1965  * synth_event_trace_start - Start piecewise synthetic event trace
1966  * @file: The trace_event_file representing the synthetic event
1967  * @trace_state: A pointer to object tracking the piecewise trace state
1968  *
1969  * Start the trace of a synthetic event field-by-field rather than all
1970  * at once.
1971  *
1972  * This function 'opens' an event trace, which means space is reserved
1973  * for the event in the trace buffer, after which the event's
1974  * individual field values can be set through either
1975  * synth_event_add_next_val() or synth_event_add_val().
1976  *
1977  * A pointer to a trace_state object is passed in, which will keep
1978  * track of the current event trace state until the event trace is
1979  * closed (and the event finally traced) using
1980  * synth_event_trace_end().
1981  *
1982  * Note that synth_event_trace_end() must be called after all values
1983  * have been added for each event trace, regardless of whether adding
1984  * all field values succeeded or not.
1985  *
1986  * Note also that for a given event trace, all fields must be added
1987  * using either synth_event_add_next_val() or synth_event_add_val()
1988  * but not both together or interleaved.
1989  *
1990  * Return: 0 on success, err otherwise.
1991  */
1992 int synth_event_trace_start(struct trace_event_file *file,
1993 			    struct synth_event_trace_state *trace_state)
1994 {
1995 	int ret;
1996 
1997 	if (!trace_state)
1998 		return -EINVAL;
1999 
2000 	memset(trace_state, '\0', sizeof(*trace_state));
2001 
2002 	ret = __synth_event_trace_start(file, trace_state);
2003 	if (ret == -ENOENT)
2004 		ret = 0; /* just disabled, not really an error */
2005 
2006 	return ret;
2007 }
2008 EXPORT_SYMBOL_GPL(synth_event_trace_start);
2009 
2010 static int __synth_event_add_val(const char *field_name, u64 val,
2011 				 struct synth_event_trace_state *trace_state)
2012 {
2013 	struct synth_field *field = NULL;
2014 	struct synth_trace_event *entry;
2015 	struct synth_event *event;
2016 	int i, ret = 0;
2017 
2018 	if (!trace_state) {
2019 		ret = -EINVAL;
2020 		goto out;
2021 	}
2022 
2023 	/* can't mix add_next_synth_val() with add_synth_val() */
2024 	if (field_name) {
2025 		if (trace_state->add_next) {
2026 			ret = -EINVAL;
2027 			goto out;
2028 		}
2029 		trace_state->add_name = true;
2030 	} else {
2031 		if (trace_state->add_name) {
2032 			ret = -EINVAL;
2033 			goto out;
2034 		}
2035 		trace_state->add_next = true;
2036 	}
2037 
2038 	if (trace_state->disabled)
2039 		goto out;
2040 
2041 	event = trace_state->event;
2042 	if (trace_state->add_name) {
2043 		for (i = 0; i < event->n_fields; i++) {
2044 			field = event->fields[i];
2045 			if (strcmp(field->name, field_name) == 0)
2046 				break;
2047 		}
2048 		if (!field) {
2049 			ret = -EINVAL;
2050 			goto out;
2051 		}
2052 	} else {
2053 		if (trace_state->cur_field >= event->n_fields) {
2054 			ret = -EINVAL;
2055 			goto out;
2056 		}
2057 		field = event->fields[trace_state->cur_field++];
2058 	}
2059 
2060 	entry = trace_state->entry;
2061 	if (field->is_string) {
2062 		char *str_val = (char *)(long)val;
2063 		char *str_field;
2064 
2065 		if (!str_val) {
2066 			ret = -EINVAL;
2067 			goto out;
2068 		}
2069 
2070 		str_field = (char *)&entry->fields[field->offset];
2071 		strscpy(str_field, str_val, STR_VAR_LEN_MAX);
2072 	} else
2073 		entry->fields[field->offset] = val;
2074  out:
2075 	return ret;
2076 }
2077 
2078 /**
2079  * synth_event_add_next_val - Add the next field's value to an open synth trace
2080  * @val: The value to set the next field to
2081  * @trace_state: A pointer to object tracking the piecewise trace state
2082  *
2083  * Set the value of the next field in an event that's been opened by
2084  * synth_event_trace_start().
2085  *
2086  * The val param should be the value cast to u64.  If the value points
2087  * to a string, the val param should be a char * cast to u64.
2088  *
2089  * This function assumes all the fields in an event are to be set one
2090  * after another - successive calls to this function are made, one for
2091  * each field, in the order of the fields in the event, until all
2092  * fields have been set.  If you'd rather set each field individually
2093  * without regard to ordering, synth_event_add_val() can be used
2094  * instead.
2095  *
2096  * Note however that synth_event_add_next_val() and
2097  * synth_event_add_val() can't be intermixed for a given event trace -
2098  * one or the other but not both can be used at the same time.
2099  *
2100  * Note also that synth_event_trace_end() must be called after all
2101  * values have been added for each event trace, regardless of whether
2102  * adding all field values succeeded or not.
2103  *
2104  * Return: 0 on success, err otherwise.
2105  */
2106 int synth_event_add_next_val(u64 val,
2107 			     struct synth_event_trace_state *trace_state)
2108 {
2109 	return __synth_event_add_val(NULL, val, trace_state);
2110 }
2111 EXPORT_SYMBOL_GPL(synth_event_add_next_val);
2112 
2113 /**
2114  * synth_event_add_val - Add a named field's value to an open synth trace
2115  * @field_name: The name of the synthetic event field value to set
2116  * @val: The value to set the next field to
2117  * @trace_state: A pointer to object tracking the piecewise trace state
2118  *
2119  * Set the value of the named field in an event that's been opened by
2120  * synth_event_trace_start().
2121  *
2122  * The val param should be the value cast to u64.  If the value points
2123  * to a string, the val param should be a char * cast to u64.
2124  *
2125  * This function looks up the field name, and if found, sets the field
2126  * to the specified value.  This lookup makes this function more
2127  * expensive than synth_event_add_next_val(), so use that or the
2128  * none-piecewise synth_event_trace() instead if efficiency is more
2129  * important.
2130  *
2131  * Note however that synth_event_add_next_val() and
2132  * synth_event_add_val() can't be intermixed for a given event trace -
2133  * one or the other but not both can be used at the same time.
2134  *
2135  * Note also that synth_event_trace_end() must be called after all
2136  * values have been added for each event trace, regardless of whether
2137  * adding all field values succeeded or not.
2138  *
2139  * Return: 0 on success, err otherwise.
2140  */
2141 int synth_event_add_val(const char *field_name, u64 val,
2142 			struct synth_event_trace_state *trace_state)
2143 {
2144 	return __synth_event_add_val(field_name, val, trace_state);
2145 }
2146 EXPORT_SYMBOL_GPL(synth_event_add_val);
2147 
2148 /**
2149  * synth_event_trace_end - End piecewise synthetic event trace
2150  * @trace_state: A pointer to object tracking the piecewise trace state
2151  *
2152  * End the trace of a synthetic event opened by
2153  * synth_event_trace__start().
2154  *
2155  * This function 'closes' an event trace, which basically means that
2156  * it commits the reserved event and cleans up other loose ends.
2157  *
2158  * A pointer to a trace_state object is passed in, which will keep
2159  * track of the current event trace state opened with
2160  * synth_event_trace_start().
2161  *
2162  * Note that this function must be called after all values have been
2163  * added for each event trace, regardless of whether adding all field
2164  * values succeeded or not.
2165  *
2166  * Return: 0 on success, err otherwise.
2167  */
2168 int synth_event_trace_end(struct synth_event_trace_state *trace_state)
2169 {
2170 	if (!trace_state)
2171 		return -EINVAL;
2172 
2173 	__synth_event_trace_end(trace_state);
2174 
2175 	return 0;
2176 }
2177 EXPORT_SYMBOL_GPL(synth_event_trace_end);
2178 
2179 static int create_synth_event(int argc, const char **argv)
2180 {
2181 	const char *name = argv[0];
2182 	int len;
2183 
2184 	if (name[0] != 's' || name[1] != ':')
2185 		return -ECANCELED;
2186 	name += 2;
2187 
2188 	/* This interface accepts group name prefix */
2189 	if (strchr(name, '/')) {
2190 		len = str_has_prefix(name, SYNTH_SYSTEM "/");
2191 		if (len == 0)
2192 			return -EINVAL;
2193 		name += len;
2194 	}
2195 	return __create_synth_event(argc - 1, name, argv + 1);
2196 }
2197 
2198 static int synth_event_release(struct dyn_event *ev)
2199 {
2200 	struct synth_event *event = to_synth_event(ev);
2201 	int ret;
2202 
2203 	if (event->ref)
2204 		return -EBUSY;
2205 
2206 	ret = unregister_synth_event(event);
2207 	if (ret)
2208 		return ret;
2209 
2210 	dyn_event_remove(ev);
2211 	free_synth_event(event);
2212 	return 0;
2213 }
2214 
2215 static int __synth_event_show(struct seq_file *m, struct synth_event *event)
2216 {
2217 	struct synth_field *field;
2218 	unsigned int i;
2219 
2220 	seq_printf(m, "%s\t", event->name);
2221 
2222 	for (i = 0; i < event->n_fields; i++) {
2223 		field = event->fields[i];
2224 
2225 		/* parameter values */
2226 		seq_printf(m, "%s %s%s", field->type, field->name,
2227 			   i == event->n_fields - 1 ? "" : "; ");
2228 	}
2229 
2230 	seq_putc(m, '\n');
2231 
2232 	return 0;
2233 }
2234 
2235 static int synth_event_show(struct seq_file *m, struct dyn_event *ev)
2236 {
2237 	struct synth_event *event = to_synth_event(ev);
2238 
2239 	seq_printf(m, "s:%s/", event->class.system);
2240 
2241 	return __synth_event_show(m, event);
2242 }
2243 
2244 static int synth_events_seq_show(struct seq_file *m, void *v)
2245 {
2246 	struct dyn_event *ev = v;
2247 
2248 	if (!is_synth_event(ev))
2249 		return 0;
2250 
2251 	return __synth_event_show(m, to_synth_event(ev));
2252 }
2253 
2254 static const struct seq_operations synth_events_seq_op = {
2255 	.start	= dyn_event_seq_start,
2256 	.next	= dyn_event_seq_next,
2257 	.stop	= dyn_event_seq_stop,
2258 	.show	= synth_events_seq_show,
2259 };
2260 
2261 static int synth_events_open(struct inode *inode, struct file *file)
2262 {
2263 	int ret;
2264 
2265 	ret = security_locked_down(LOCKDOWN_TRACEFS);
2266 	if (ret)
2267 		return ret;
2268 
2269 	if ((file->f_mode & FMODE_WRITE) && (file->f_flags & O_TRUNC)) {
2270 		ret = dyn_events_release_all(&synth_event_ops);
2271 		if (ret < 0)
2272 			return ret;
2273 	}
2274 
2275 	return seq_open(file, &synth_events_seq_op);
2276 }
2277 
2278 static ssize_t synth_events_write(struct file *file,
2279 				  const char __user *buffer,
2280 				  size_t count, loff_t *ppos)
2281 {
2282 	return trace_parse_run_command(file, buffer, count, ppos,
2283 				       create_or_delete_synth_event);
2284 }
2285 
2286 static const struct file_operations synth_events_fops = {
2287 	.open           = synth_events_open,
2288 	.write		= synth_events_write,
2289 	.read           = seq_read,
2290 	.llseek         = seq_lseek,
2291 	.release        = seq_release,
2292 };
2293 
2294 static u64 hist_field_timestamp(struct hist_field *hist_field,
2295 				struct tracing_map_elt *elt,
2296 				struct ring_buffer_event *rbe,
2297 				void *event)
2298 {
2299 	struct hist_trigger_data *hist_data = hist_field->hist_data;
2300 	struct trace_array *tr = hist_data->event_file->tr;
2301 
2302 	u64 ts = ring_buffer_event_time_stamp(rbe);
2303 
2304 	if (hist_data->attrs->ts_in_usecs && trace_clock_in_ns(tr))
2305 		ts = ns2usecs(ts);
2306 
2307 	return ts;
2308 }
2309 
2310 static u64 hist_field_cpu(struct hist_field *hist_field,
2311 			  struct tracing_map_elt *elt,
2312 			  struct ring_buffer_event *rbe,
2313 			  void *event)
2314 {
2315 	int cpu = smp_processor_id();
2316 
2317 	return cpu;
2318 }
2319 
2320 /**
2321  * check_field_for_var_ref - Check if a VAR_REF field references a variable
2322  * @hist_field: The VAR_REF field to check
2323  * @var_data: The hist trigger that owns the variable
2324  * @var_idx: The trigger variable identifier
2325  *
2326  * Check the given VAR_REF field to see whether or not it references
2327  * the given variable associated with the given trigger.
2328  *
2329  * Return: The VAR_REF field if it does reference the variable, NULL if not
2330  */
2331 static struct hist_field *
2332 check_field_for_var_ref(struct hist_field *hist_field,
2333 			struct hist_trigger_data *var_data,
2334 			unsigned int var_idx)
2335 {
2336 	WARN_ON(!(hist_field && hist_field->flags & HIST_FIELD_FL_VAR_REF));
2337 
2338 	if (hist_field && hist_field->var.idx == var_idx &&
2339 	    hist_field->var.hist_data == var_data)
2340 		return hist_field;
2341 
2342 	return NULL;
2343 }
2344 
2345 /**
2346  * find_var_ref - Check if a trigger has a reference to a trigger variable
2347  * @hist_data: The hist trigger that might have a reference to the variable
2348  * @var_data: The hist trigger that owns the variable
2349  * @var_idx: The trigger variable identifier
2350  *
2351  * Check the list of var_refs[] on the first hist trigger to see
2352  * whether any of them are references to the variable on the second
2353  * trigger.
2354  *
2355  * Return: The VAR_REF field referencing the variable if so, NULL if not
2356  */
2357 static struct hist_field *find_var_ref(struct hist_trigger_data *hist_data,
2358 				       struct hist_trigger_data *var_data,
2359 				       unsigned int var_idx)
2360 {
2361 	struct hist_field *hist_field;
2362 	unsigned int i;
2363 
2364 	for (i = 0; i < hist_data->n_var_refs; i++) {
2365 		hist_field = hist_data->var_refs[i];
2366 		if (check_field_for_var_ref(hist_field, var_data, var_idx))
2367 			return hist_field;
2368 	}
2369 
2370 	return NULL;
2371 }
2372 
2373 /**
2374  * find_any_var_ref - Check if there is a reference to a given trigger variable
2375  * @hist_data: The hist trigger
2376  * @var_idx: The trigger variable identifier
2377  *
2378  * Check to see whether the given variable is currently referenced by
2379  * any other trigger.
2380  *
2381  * The trigger the variable is defined on is explicitly excluded - the
2382  * assumption being that a self-reference doesn't prevent a trigger
2383  * from being removed.
2384  *
2385  * Return: The VAR_REF field referencing the variable if so, NULL if not
2386  */
2387 static struct hist_field *find_any_var_ref(struct hist_trigger_data *hist_data,
2388 					   unsigned int var_idx)
2389 {
2390 	struct trace_array *tr = hist_data->event_file->tr;
2391 	struct hist_field *found = NULL;
2392 	struct hist_var_data *var_data;
2393 
2394 	list_for_each_entry(var_data, &tr->hist_vars, list) {
2395 		if (var_data->hist_data == hist_data)
2396 			continue;
2397 		found = find_var_ref(var_data->hist_data, hist_data, var_idx);
2398 		if (found)
2399 			break;
2400 	}
2401 
2402 	return found;
2403 }
2404 
2405 /**
2406  * check_var_refs - Check if there is a reference to any of trigger's variables
2407  * @hist_data: The hist trigger
2408  *
2409  * A trigger can define one or more variables.  If any one of them is
2410  * currently referenced by any other trigger, this function will
2411  * determine that.
2412 
2413  * Typically used to determine whether or not a trigger can be removed
2414  * - if there are any references to a trigger's variables, it cannot.
2415  *
2416  * Return: True if there is a reference to any of trigger's variables
2417  */
2418 static bool check_var_refs(struct hist_trigger_data *hist_data)
2419 {
2420 	struct hist_field *field;
2421 	bool found = false;
2422 	int i;
2423 
2424 	for_each_hist_field(i, hist_data) {
2425 		field = hist_data->fields[i];
2426 		if (field && field->flags & HIST_FIELD_FL_VAR) {
2427 			if (find_any_var_ref(hist_data, field->var.idx)) {
2428 				found = true;
2429 				break;
2430 			}
2431 		}
2432 	}
2433 
2434 	return found;
2435 }
2436 
2437 static struct hist_var_data *find_hist_vars(struct hist_trigger_data *hist_data)
2438 {
2439 	struct trace_array *tr = hist_data->event_file->tr;
2440 	struct hist_var_data *var_data, *found = NULL;
2441 
2442 	list_for_each_entry(var_data, &tr->hist_vars, list) {
2443 		if (var_data->hist_data == hist_data) {
2444 			found = var_data;
2445 			break;
2446 		}
2447 	}
2448 
2449 	return found;
2450 }
2451 
2452 static bool field_has_hist_vars(struct hist_field *hist_field,
2453 				unsigned int level)
2454 {
2455 	int i;
2456 
2457 	if (level > 3)
2458 		return false;
2459 
2460 	if (!hist_field)
2461 		return false;
2462 
2463 	if (hist_field->flags & HIST_FIELD_FL_VAR ||
2464 	    hist_field->flags & HIST_FIELD_FL_VAR_REF)
2465 		return true;
2466 
2467 	for (i = 0; i < HIST_FIELD_OPERANDS_MAX; i++) {
2468 		struct hist_field *operand;
2469 
2470 		operand = hist_field->operands[i];
2471 		if (field_has_hist_vars(operand, level + 1))
2472 			return true;
2473 	}
2474 
2475 	return false;
2476 }
2477 
2478 static bool has_hist_vars(struct hist_trigger_data *hist_data)
2479 {
2480 	struct hist_field *hist_field;
2481 	int i;
2482 
2483 	for_each_hist_field(i, hist_data) {
2484 		hist_field = hist_data->fields[i];
2485 		if (field_has_hist_vars(hist_field, 0))
2486 			return true;
2487 	}
2488 
2489 	return false;
2490 }
2491 
2492 static int save_hist_vars(struct hist_trigger_data *hist_data)
2493 {
2494 	struct trace_array *tr = hist_data->event_file->tr;
2495 	struct hist_var_data *var_data;
2496 
2497 	var_data = find_hist_vars(hist_data);
2498 	if (var_data)
2499 		return 0;
2500 
2501 	if (tracing_check_open_get_tr(tr))
2502 		return -ENODEV;
2503 
2504 	var_data = kzalloc(sizeof(*var_data), GFP_KERNEL);
2505 	if (!var_data) {
2506 		trace_array_put(tr);
2507 		return -ENOMEM;
2508 	}
2509 
2510 	var_data->hist_data = hist_data;
2511 	list_add(&var_data->list, &tr->hist_vars);
2512 
2513 	return 0;
2514 }
2515 
2516 static void remove_hist_vars(struct hist_trigger_data *hist_data)
2517 {
2518 	struct trace_array *tr = hist_data->event_file->tr;
2519 	struct hist_var_data *var_data;
2520 
2521 	var_data = find_hist_vars(hist_data);
2522 	if (!var_data)
2523 		return;
2524 
2525 	if (WARN_ON(check_var_refs(hist_data)))
2526 		return;
2527 
2528 	list_del(&var_data->list);
2529 
2530 	kfree(var_data);
2531 
2532 	trace_array_put(tr);
2533 }
2534 
2535 static struct hist_field *find_var_field(struct hist_trigger_data *hist_data,
2536 					 const char *var_name)
2537 {
2538 	struct hist_field *hist_field, *found = NULL;
2539 	int i;
2540 
2541 	for_each_hist_field(i, hist_data) {
2542 		hist_field = hist_data->fields[i];
2543 		if (hist_field && hist_field->flags & HIST_FIELD_FL_VAR &&
2544 		    strcmp(hist_field->var.name, var_name) == 0) {
2545 			found = hist_field;
2546 			break;
2547 		}
2548 	}
2549 
2550 	return found;
2551 }
2552 
2553 static struct hist_field *find_var(struct hist_trigger_data *hist_data,
2554 				   struct trace_event_file *file,
2555 				   const char *var_name)
2556 {
2557 	struct hist_trigger_data *test_data;
2558 	struct event_trigger_data *test;
2559 	struct hist_field *hist_field;
2560 
2561 	lockdep_assert_held(&event_mutex);
2562 
2563 	hist_field = find_var_field(hist_data, var_name);
2564 	if (hist_field)
2565 		return hist_field;
2566 
2567 	list_for_each_entry(test, &file->triggers, list) {
2568 		if (test->cmd_ops->trigger_type == ETT_EVENT_HIST) {
2569 			test_data = test->private_data;
2570 			hist_field = find_var_field(test_data, var_name);
2571 			if (hist_field)
2572 				return hist_field;
2573 		}
2574 	}
2575 
2576 	return NULL;
2577 }
2578 
2579 static struct trace_event_file *find_var_file(struct trace_array *tr,
2580 					      char *system,
2581 					      char *event_name,
2582 					      char *var_name)
2583 {
2584 	struct hist_trigger_data *var_hist_data;
2585 	struct hist_var_data *var_data;
2586 	struct trace_event_file *file, *found = NULL;
2587 
2588 	if (system)
2589 		return find_event_file(tr, system, event_name);
2590 
2591 	list_for_each_entry(var_data, &tr->hist_vars, list) {
2592 		var_hist_data = var_data->hist_data;
2593 		file = var_hist_data->event_file;
2594 		if (file == found)
2595 			continue;
2596 
2597 		if (find_var_field(var_hist_data, var_name)) {
2598 			if (found) {
2599 				hist_err(tr, HIST_ERR_VAR_NOT_UNIQUE, errpos(var_name));
2600 				return NULL;
2601 			}
2602 
2603 			found = file;
2604 		}
2605 	}
2606 
2607 	return found;
2608 }
2609 
2610 static struct hist_field *find_file_var(struct trace_event_file *file,
2611 					const char *var_name)
2612 {
2613 	struct hist_trigger_data *test_data;
2614 	struct event_trigger_data *test;
2615 	struct hist_field *hist_field;
2616 
2617 	lockdep_assert_held(&event_mutex);
2618 
2619 	list_for_each_entry(test, &file->triggers, list) {
2620 		if (test->cmd_ops->trigger_type == ETT_EVENT_HIST) {
2621 			test_data = test->private_data;
2622 			hist_field = find_var_field(test_data, var_name);
2623 			if (hist_field)
2624 				return hist_field;
2625 		}
2626 	}
2627 
2628 	return NULL;
2629 }
2630 
2631 static struct hist_field *
2632 find_match_var(struct hist_trigger_data *hist_data, char *var_name)
2633 {
2634 	struct trace_array *tr = hist_data->event_file->tr;
2635 	struct hist_field *hist_field, *found = NULL;
2636 	struct trace_event_file *file;
2637 	unsigned int i;
2638 
2639 	for (i = 0; i < hist_data->n_actions; i++) {
2640 		struct action_data *data = hist_data->actions[i];
2641 
2642 		if (data->handler == HANDLER_ONMATCH) {
2643 			char *system = data->match_data.event_system;
2644 			char *event_name = data->match_data.event;
2645 
2646 			file = find_var_file(tr, system, event_name, var_name);
2647 			if (!file)
2648 				continue;
2649 			hist_field = find_file_var(file, var_name);
2650 			if (hist_field) {
2651 				if (found) {
2652 					hist_err(tr, HIST_ERR_VAR_NOT_UNIQUE,
2653 						 errpos(var_name));
2654 					return ERR_PTR(-EINVAL);
2655 				}
2656 
2657 				found = hist_field;
2658 			}
2659 		}
2660 	}
2661 	return found;
2662 }
2663 
2664 static struct hist_field *find_event_var(struct hist_trigger_data *hist_data,
2665 					 char *system,
2666 					 char *event_name,
2667 					 char *var_name)
2668 {
2669 	struct trace_array *tr = hist_data->event_file->tr;
2670 	struct hist_field *hist_field = NULL;
2671 	struct trace_event_file *file;
2672 
2673 	if (!system || !event_name) {
2674 		hist_field = find_match_var(hist_data, var_name);
2675 		if (IS_ERR(hist_field))
2676 			return NULL;
2677 		if (hist_field)
2678 			return hist_field;
2679 	}
2680 
2681 	file = find_var_file(tr, system, event_name, var_name);
2682 	if (!file)
2683 		return NULL;
2684 
2685 	hist_field = find_file_var(file, var_name);
2686 
2687 	return hist_field;
2688 }
2689 
2690 static u64 hist_field_var_ref(struct hist_field *hist_field,
2691 			      struct tracing_map_elt *elt,
2692 			      struct ring_buffer_event *rbe,
2693 			      void *event)
2694 {
2695 	struct hist_elt_data *elt_data;
2696 	u64 var_val = 0;
2697 
2698 	if (WARN_ON_ONCE(!elt))
2699 		return var_val;
2700 
2701 	elt_data = elt->private_data;
2702 	var_val = elt_data->var_ref_vals[hist_field->var_ref_idx];
2703 
2704 	return var_val;
2705 }
2706 
2707 static bool resolve_var_refs(struct hist_trigger_data *hist_data, void *key,
2708 			     u64 *var_ref_vals, bool self)
2709 {
2710 	struct hist_trigger_data *var_data;
2711 	struct tracing_map_elt *var_elt;
2712 	struct hist_field *hist_field;
2713 	unsigned int i, var_idx;
2714 	bool resolved = true;
2715 	u64 var_val = 0;
2716 
2717 	for (i = 0; i < hist_data->n_var_refs; i++) {
2718 		hist_field = hist_data->var_refs[i];
2719 		var_idx = hist_field->var.idx;
2720 		var_data = hist_field->var.hist_data;
2721 
2722 		if (var_data == NULL) {
2723 			resolved = false;
2724 			break;
2725 		}
2726 
2727 		if ((self && var_data != hist_data) ||
2728 		    (!self && var_data == hist_data))
2729 			continue;
2730 
2731 		var_elt = tracing_map_lookup(var_data->map, key);
2732 		if (!var_elt) {
2733 			resolved = false;
2734 			break;
2735 		}
2736 
2737 		if (!tracing_map_var_set(var_elt, var_idx)) {
2738 			resolved = false;
2739 			break;
2740 		}
2741 
2742 		if (self || !hist_field->read_once)
2743 			var_val = tracing_map_read_var(var_elt, var_idx);
2744 		else
2745 			var_val = tracing_map_read_var_once(var_elt, var_idx);
2746 
2747 		var_ref_vals[i] = var_val;
2748 	}
2749 
2750 	return resolved;
2751 }
2752 
2753 static const char *hist_field_name(struct hist_field *field,
2754 				   unsigned int level)
2755 {
2756 	const char *field_name = "";
2757 
2758 	if (level > 1)
2759 		return field_name;
2760 
2761 	if (field->field)
2762 		field_name = field->field->name;
2763 	else if (field->flags & HIST_FIELD_FL_LOG2 ||
2764 		 field->flags & HIST_FIELD_FL_ALIAS)
2765 		field_name = hist_field_name(field->operands[0], ++level);
2766 	else if (field->flags & HIST_FIELD_FL_CPU)
2767 		field_name = "cpu";
2768 	else if (field->flags & HIST_FIELD_FL_EXPR ||
2769 		 field->flags & HIST_FIELD_FL_VAR_REF) {
2770 		if (field->system) {
2771 			static char full_name[MAX_FILTER_STR_VAL];
2772 
2773 			strcat(full_name, field->system);
2774 			strcat(full_name, ".");
2775 			strcat(full_name, field->event_name);
2776 			strcat(full_name, ".");
2777 			strcat(full_name, field->name);
2778 			field_name = full_name;
2779 		} else
2780 			field_name = field->name;
2781 	} else if (field->flags & HIST_FIELD_FL_TIMESTAMP)
2782 		field_name = "common_timestamp";
2783 
2784 	if (field_name == NULL)
2785 		field_name = "";
2786 
2787 	return field_name;
2788 }
2789 
2790 static hist_field_fn_t select_value_fn(int field_size, int field_is_signed)
2791 {
2792 	hist_field_fn_t fn = NULL;
2793 
2794 	switch (field_size) {
2795 	case 8:
2796 		if (field_is_signed)
2797 			fn = hist_field_s64;
2798 		else
2799 			fn = hist_field_u64;
2800 		break;
2801 	case 4:
2802 		if (field_is_signed)
2803 			fn = hist_field_s32;
2804 		else
2805 			fn = hist_field_u32;
2806 		break;
2807 	case 2:
2808 		if (field_is_signed)
2809 			fn = hist_field_s16;
2810 		else
2811 			fn = hist_field_u16;
2812 		break;
2813 	case 1:
2814 		if (field_is_signed)
2815 			fn = hist_field_s8;
2816 		else
2817 			fn = hist_field_u8;
2818 		break;
2819 	}
2820 
2821 	return fn;
2822 }
2823 
2824 static int parse_map_size(char *str)
2825 {
2826 	unsigned long size, map_bits;
2827 	int ret;
2828 
2829 	ret = kstrtoul(str, 0, &size);
2830 	if (ret)
2831 		goto out;
2832 
2833 	map_bits = ilog2(roundup_pow_of_two(size));
2834 	if (map_bits < TRACING_MAP_BITS_MIN ||
2835 	    map_bits > TRACING_MAP_BITS_MAX)
2836 		ret = -EINVAL;
2837 	else
2838 		ret = map_bits;
2839  out:
2840 	return ret;
2841 }
2842 
2843 static void destroy_hist_trigger_attrs(struct hist_trigger_attrs *attrs)
2844 {
2845 	unsigned int i;
2846 
2847 	if (!attrs)
2848 		return;
2849 
2850 	for (i = 0; i < attrs->n_assignments; i++)
2851 		kfree(attrs->assignment_str[i]);
2852 
2853 	for (i = 0; i < attrs->n_actions; i++)
2854 		kfree(attrs->action_str[i]);
2855 
2856 	kfree(attrs->name);
2857 	kfree(attrs->sort_key_str);
2858 	kfree(attrs->keys_str);
2859 	kfree(attrs->vals_str);
2860 	kfree(attrs->clock);
2861 	kfree(attrs);
2862 }
2863 
2864 static int parse_action(char *str, struct hist_trigger_attrs *attrs)
2865 {
2866 	int ret = -EINVAL;
2867 
2868 	if (attrs->n_actions >= HIST_ACTIONS_MAX)
2869 		return ret;
2870 
2871 	if ((str_has_prefix(str, "onmatch(")) ||
2872 	    (str_has_prefix(str, "onmax(")) ||
2873 	    (str_has_prefix(str, "onchange("))) {
2874 		attrs->action_str[attrs->n_actions] = kstrdup(str, GFP_KERNEL);
2875 		if (!attrs->action_str[attrs->n_actions]) {
2876 			ret = -ENOMEM;
2877 			return ret;
2878 		}
2879 		attrs->n_actions++;
2880 		ret = 0;
2881 	}
2882 	return ret;
2883 }
2884 
2885 static int parse_assignment(struct trace_array *tr,
2886 			    char *str, struct hist_trigger_attrs *attrs)
2887 {
2888 	int len, ret = 0;
2889 
2890 	if ((len = str_has_prefix(str, "key=")) ||
2891 	    (len = str_has_prefix(str, "keys="))) {
2892 		attrs->keys_str = kstrdup(str + len, GFP_KERNEL);
2893 		if (!attrs->keys_str) {
2894 			ret = -ENOMEM;
2895 			goto out;
2896 		}
2897 	} else if ((len = str_has_prefix(str, "val=")) ||
2898 		   (len = str_has_prefix(str, "vals=")) ||
2899 		   (len = str_has_prefix(str, "values="))) {
2900 		attrs->vals_str = kstrdup(str + len, GFP_KERNEL);
2901 		if (!attrs->vals_str) {
2902 			ret = -ENOMEM;
2903 			goto out;
2904 		}
2905 	} else if ((len = str_has_prefix(str, "sort="))) {
2906 		attrs->sort_key_str = kstrdup(str + len, GFP_KERNEL);
2907 		if (!attrs->sort_key_str) {
2908 			ret = -ENOMEM;
2909 			goto out;
2910 		}
2911 	} else if (str_has_prefix(str, "name=")) {
2912 		attrs->name = kstrdup(str, GFP_KERNEL);
2913 		if (!attrs->name) {
2914 			ret = -ENOMEM;
2915 			goto out;
2916 		}
2917 	} else if ((len = str_has_prefix(str, "clock="))) {
2918 		str += len;
2919 
2920 		str = strstrip(str);
2921 		attrs->clock = kstrdup(str, GFP_KERNEL);
2922 		if (!attrs->clock) {
2923 			ret = -ENOMEM;
2924 			goto out;
2925 		}
2926 	} else if ((len = str_has_prefix(str, "size="))) {
2927 		int map_bits = parse_map_size(str + len);
2928 
2929 		if (map_bits < 0) {
2930 			ret = map_bits;
2931 			goto out;
2932 		}
2933 		attrs->map_bits = map_bits;
2934 	} else {
2935 		char *assignment;
2936 
2937 		if (attrs->n_assignments == TRACING_MAP_VARS_MAX) {
2938 			hist_err(tr, HIST_ERR_TOO_MANY_VARS, errpos(str));
2939 			ret = -EINVAL;
2940 			goto out;
2941 		}
2942 
2943 		assignment = kstrdup(str, GFP_KERNEL);
2944 		if (!assignment) {
2945 			ret = -ENOMEM;
2946 			goto out;
2947 		}
2948 
2949 		attrs->assignment_str[attrs->n_assignments++] = assignment;
2950 	}
2951  out:
2952 	return ret;
2953 }
2954 
2955 static struct hist_trigger_attrs *
2956 parse_hist_trigger_attrs(struct trace_array *tr, char *trigger_str)
2957 {
2958 	struct hist_trigger_attrs *attrs;
2959 	int ret = 0;
2960 
2961 	attrs = kzalloc(sizeof(*attrs), GFP_KERNEL);
2962 	if (!attrs)
2963 		return ERR_PTR(-ENOMEM);
2964 
2965 	while (trigger_str) {
2966 		char *str = strsep(&trigger_str, ":");
2967 		char *rhs;
2968 
2969 		rhs = strchr(str, '=');
2970 		if (rhs) {
2971 			if (!strlen(++rhs)) {
2972 				ret = -EINVAL;
2973 				hist_err(tr, HIST_ERR_EMPTY_ASSIGNMENT, errpos(str));
2974 				goto free;
2975 			}
2976 			ret = parse_assignment(tr, str, attrs);
2977 			if (ret)
2978 				goto free;
2979 		} else if (strcmp(str, "pause") == 0)
2980 			attrs->pause = true;
2981 		else if ((strcmp(str, "cont") == 0) ||
2982 			 (strcmp(str, "continue") == 0))
2983 			attrs->cont = true;
2984 		else if (strcmp(str, "clear") == 0)
2985 			attrs->clear = true;
2986 		else {
2987 			ret = parse_action(str, attrs);
2988 			if (ret)
2989 				goto free;
2990 		}
2991 	}
2992 
2993 	if (!attrs->keys_str) {
2994 		ret = -EINVAL;
2995 		goto free;
2996 	}
2997 
2998 	if (!attrs->clock) {
2999 		attrs->clock = kstrdup("global", GFP_KERNEL);
3000 		if (!attrs->clock) {
3001 			ret = -ENOMEM;
3002 			goto free;
3003 		}
3004 	}
3005 
3006 	return attrs;
3007  free:
3008 	destroy_hist_trigger_attrs(attrs);
3009 
3010 	return ERR_PTR(ret);
3011 }
3012 
3013 static inline void save_comm(char *comm, struct task_struct *task)
3014 {
3015 	if (!task->pid) {
3016 		strcpy(comm, "<idle>");
3017 		return;
3018 	}
3019 
3020 	if (WARN_ON_ONCE(task->pid < 0)) {
3021 		strcpy(comm, "<XXX>");
3022 		return;
3023 	}
3024 
3025 	strncpy(comm, task->comm, TASK_COMM_LEN);
3026 }
3027 
3028 static void hist_elt_data_free(struct hist_elt_data *elt_data)
3029 {
3030 	unsigned int i;
3031 
3032 	for (i = 0; i < SYNTH_FIELDS_MAX; i++)
3033 		kfree(elt_data->field_var_str[i]);
3034 
3035 	kfree(elt_data->comm);
3036 	kfree(elt_data);
3037 }
3038 
3039 static void hist_trigger_elt_data_free(struct tracing_map_elt *elt)
3040 {
3041 	struct hist_elt_data *elt_data = elt->private_data;
3042 
3043 	hist_elt_data_free(elt_data);
3044 }
3045 
3046 static int hist_trigger_elt_data_alloc(struct tracing_map_elt *elt)
3047 {
3048 	struct hist_trigger_data *hist_data = elt->map->private_data;
3049 	unsigned int size = TASK_COMM_LEN;
3050 	struct hist_elt_data *elt_data;
3051 	struct hist_field *key_field;
3052 	unsigned int i, n_str;
3053 
3054 	elt_data = kzalloc(sizeof(*elt_data), GFP_KERNEL);
3055 	if (!elt_data)
3056 		return -ENOMEM;
3057 
3058 	for_each_hist_key_field(i, hist_data) {
3059 		key_field = hist_data->fields[i];
3060 
3061 		if (key_field->flags & HIST_FIELD_FL_EXECNAME) {
3062 			elt_data->comm = kzalloc(size, GFP_KERNEL);
3063 			if (!elt_data->comm) {
3064 				kfree(elt_data);
3065 				return -ENOMEM;
3066 			}
3067 			break;
3068 		}
3069 	}
3070 
3071 	n_str = hist_data->n_field_var_str + hist_data->n_save_var_str;
3072 
3073 	size = STR_VAR_LEN_MAX;
3074 
3075 	for (i = 0; i < n_str; i++) {
3076 		elt_data->field_var_str[i] = kzalloc(size, GFP_KERNEL);
3077 		if (!elt_data->field_var_str[i]) {
3078 			hist_elt_data_free(elt_data);
3079 			return -ENOMEM;
3080 		}
3081 	}
3082 
3083 	elt->private_data = elt_data;
3084 
3085 	return 0;
3086 }
3087 
3088 static void hist_trigger_elt_data_init(struct tracing_map_elt *elt)
3089 {
3090 	struct hist_elt_data *elt_data = elt->private_data;
3091 
3092 	if (elt_data->comm)
3093 		save_comm(elt_data->comm, current);
3094 }
3095 
3096 static const struct tracing_map_ops hist_trigger_elt_data_ops = {
3097 	.elt_alloc	= hist_trigger_elt_data_alloc,
3098 	.elt_free	= hist_trigger_elt_data_free,
3099 	.elt_init	= hist_trigger_elt_data_init,
3100 };
3101 
3102 static const char *get_hist_field_flags(struct hist_field *hist_field)
3103 {
3104 	const char *flags_str = NULL;
3105 
3106 	if (hist_field->flags & HIST_FIELD_FL_HEX)
3107 		flags_str = "hex";
3108 	else if (hist_field->flags & HIST_FIELD_FL_SYM)
3109 		flags_str = "sym";
3110 	else if (hist_field->flags & HIST_FIELD_FL_SYM_OFFSET)
3111 		flags_str = "sym-offset";
3112 	else if (hist_field->flags & HIST_FIELD_FL_EXECNAME)
3113 		flags_str = "execname";
3114 	else if (hist_field->flags & HIST_FIELD_FL_SYSCALL)
3115 		flags_str = "syscall";
3116 	else if (hist_field->flags & HIST_FIELD_FL_LOG2)
3117 		flags_str = "log2";
3118 	else if (hist_field->flags & HIST_FIELD_FL_TIMESTAMP_USECS)
3119 		flags_str = "usecs";
3120 
3121 	return flags_str;
3122 }
3123 
3124 static void expr_field_str(struct hist_field *field, char *expr)
3125 {
3126 	if (field->flags & HIST_FIELD_FL_VAR_REF)
3127 		strcat(expr, "$");
3128 
3129 	strcat(expr, hist_field_name(field, 0));
3130 
3131 	if (field->flags && !(field->flags & HIST_FIELD_FL_VAR_REF)) {
3132 		const char *flags_str = get_hist_field_flags(field);
3133 
3134 		if (flags_str) {
3135 			strcat(expr, ".");
3136 			strcat(expr, flags_str);
3137 		}
3138 	}
3139 }
3140 
3141 static char *expr_str(struct hist_field *field, unsigned int level)
3142 {
3143 	char *expr;
3144 
3145 	if (level > 1)
3146 		return NULL;
3147 
3148 	expr = kzalloc(MAX_FILTER_STR_VAL, GFP_KERNEL);
3149 	if (!expr)
3150 		return NULL;
3151 
3152 	if (!field->operands[0]) {
3153 		expr_field_str(field, expr);
3154 		return expr;
3155 	}
3156 
3157 	if (field->operator == FIELD_OP_UNARY_MINUS) {
3158 		char *subexpr;
3159 
3160 		strcat(expr, "-(");
3161 		subexpr = expr_str(field->operands[0], ++level);
3162 		if (!subexpr) {
3163 			kfree(expr);
3164 			return NULL;
3165 		}
3166 		strcat(expr, subexpr);
3167 		strcat(expr, ")");
3168 
3169 		kfree(subexpr);
3170 
3171 		return expr;
3172 	}
3173 
3174 	expr_field_str(field->operands[0], expr);
3175 
3176 	switch (field->operator) {
3177 	case FIELD_OP_MINUS:
3178 		strcat(expr, "-");
3179 		break;
3180 	case FIELD_OP_PLUS:
3181 		strcat(expr, "+");
3182 		break;
3183 	default:
3184 		kfree(expr);
3185 		return NULL;
3186 	}
3187 
3188 	expr_field_str(field->operands[1], expr);
3189 
3190 	return expr;
3191 }
3192 
3193 static int contains_operator(char *str)
3194 {
3195 	enum field_op_id field_op = FIELD_OP_NONE;
3196 	char *op;
3197 
3198 	op = strpbrk(str, "+-");
3199 	if (!op)
3200 		return FIELD_OP_NONE;
3201 
3202 	switch (*op) {
3203 	case '-':
3204 		if (*str == '-')
3205 			field_op = FIELD_OP_UNARY_MINUS;
3206 		else
3207 			field_op = FIELD_OP_MINUS;
3208 		break;
3209 	case '+':
3210 		field_op = FIELD_OP_PLUS;
3211 		break;
3212 	default:
3213 		break;
3214 	}
3215 
3216 	return field_op;
3217 }
3218 
3219 static void get_hist_field(struct hist_field *hist_field)
3220 {
3221 	hist_field->ref++;
3222 }
3223 
3224 static void __destroy_hist_field(struct hist_field *hist_field)
3225 {
3226 	if (--hist_field->ref > 1)
3227 		return;
3228 
3229 	kfree(hist_field->var.name);
3230 	kfree(hist_field->name);
3231 	kfree(hist_field->type);
3232 
3233 	kfree(hist_field);
3234 }
3235 
3236 static void destroy_hist_field(struct hist_field *hist_field,
3237 			       unsigned int level)
3238 {
3239 	unsigned int i;
3240 
3241 	if (level > 3)
3242 		return;
3243 
3244 	if (!hist_field)
3245 		return;
3246 
3247 	if (hist_field->flags & HIST_FIELD_FL_VAR_REF)
3248 		return; /* var refs will be destroyed separately */
3249 
3250 	for (i = 0; i < HIST_FIELD_OPERANDS_MAX; i++)
3251 		destroy_hist_field(hist_field->operands[i], level + 1);
3252 
3253 	__destroy_hist_field(hist_field);
3254 }
3255 
3256 static struct hist_field *create_hist_field(struct hist_trigger_data *hist_data,
3257 					    struct ftrace_event_field *field,
3258 					    unsigned long flags,
3259 					    char *var_name)
3260 {
3261 	struct hist_field *hist_field;
3262 
3263 	if (field && is_function_field(field))
3264 		return NULL;
3265 
3266 	hist_field = kzalloc(sizeof(struct hist_field), GFP_KERNEL);
3267 	if (!hist_field)
3268 		return NULL;
3269 
3270 	hist_field->ref = 1;
3271 
3272 	hist_field->hist_data = hist_data;
3273 
3274 	if (flags & HIST_FIELD_FL_EXPR || flags & HIST_FIELD_FL_ALIAS)
3275 		goto out; /* caller will populate */
3276 
3277 	if (flags & HIST_FIELD_FL_VAR_REF) {
3278 		hist_field->fn = hist_field_var_ref;
3279 		goto out;
3280 	}
3281 
3282 	if (flags & HIST_FIELD_FL_HITCOUNT) {
3283 		hist_field->fn = hist_field_counter;
3284 		hist_field->size = sizeof(u64);
3285 		hist_field->type = kstrdup("u64", GFP_KERNEL);
3286 		if (!hist_field->type)
3287 			goto free;
3288 		goto out;
3289 	}
3290 
3291 	if (flags & HIST_FIELD_FL_STACKTRACE) {
3292 		hist_field->fn = hist_field_none;
3293 		goto out;
3294 	}
3295 
3296 	if (flags & HIST_FIELD_FL_LOG2) {
3297 		unsigned long fl = flags & ~HIST_FIELD_FL_LOG2;
3298 		hist_field->fn = hist_field_log2;
3299 		hist_field->operands[0] = create_hist_field(hist_data, field, fl, NULL);
3300 		hist_field->size = hist_field->operands[0]->size;
3301 		hist_field->type = kstrdup(hist_field->operands[0]->type, GFP_KERNEL);
3302 		if (!hist_field->type)
3303 			goto free;
3304 		goto out;
3305 	}
3306 
3307 	if (flags & HIST_FIELD_FL_TIMESTAMP) {
3308 		hist_field->fn = hist_field_timestamp;
3309 		hist_field->size = sizeof(u64);
3310 		hist_field->type = kstrdup("u64", GFP_KERNEL);
3311 		if (!hist_field->type)
3312 			goto free;
3313 		goto out;
3314 	}
3315 
3316 	if (flags & HIST_FIELD_FL_CPU) {
3317 		hist_field->fn = hist_field_cpu;
3318 		hist_field->size = sizeof(int);
3319 		hist_field->type = kstrdup("unsigned int", GFP_KERNEL);
3320 		if (!hist_field->type)
3321 			goto free;
3322 		goto out;
3323 	}
3324 
3325 	if (WARN_ON_ONCE(!field))
3326 		goto out;
3327 
3328 	if (is_string_field(field)) {
3329 		flags |= HIST_FIELD_FL_STRING;
3330 
3331 		hist_field->size = MAX_FILTER_STR_VAL;
3332 		hist_field->type = kstrdup(field->type, GFP_KERNEL);
3333 		if (!hist_field->type)
3334 			goto free;
3335 
3336 		if (field->filter_type == FILTER_STATIC_STRING)
3337 			hist_field->fn = hist_field_string;
3338 		else if (field->filter_type == FILTER_DYN_STRING)
3339 			hist_field->fn = hist_field_dynstring;
3340 		else
3341 			hist_field->fn = hist_field_pstring;
3342 	} else {
3343 		hist_field->size = field->size;
3344 		hist_field->is_signed = field->is_signed;
3345 		hist_field->type = kstrdup(field->type, GFP_KERNEL);
3346 		if (!hist_field->type)
3347 			goto free;
3348 
3349 		hist_field->fn = select_value_fn(field->size,
3350 						 field->is_signed);
3351 		if (!hist_field->fn) {
3352 			destroy_hist_field(hist_field, 0);
3353 			return NULL;
3354 		}
3355 	}
3356  out:
3357 	hist_field->field = field;
3358 	hist_field->flags = flags;
3359 
3360 	if (var_name) {
3361 		hist_field->var.name = kstrdup(var_name, GFP_KERNEL);
3362 		if (!hist_field->var.name)
3363 			goto free;
3364 	}
3365 
3366 	return hist_field;
3367  free:
3368 	destroy_hist_field(hist_field, 0);
3369 	return NULL;
3370 }
3371 
3372 static void destroy_hist_fields(struct hist_trigger_data *hist_data)
3373 {
3374 	unsigned int i;
3375 
3376 	for (i = 0; i < HIST_FIELDS_MAX; i++) {
3377 		if (hist_data->fields[i]) {
3378 			destroy_hist_field(hist_data->fields[i], 0);
3379 			hist_data->fields[i] = NULL;
3380 		}
3381 	}
3382 
3383 	for (i = 0; i < hist_data->n_var_refs; i++) {
3384 		WARN_ON(!(hist_data->var_refs[i]->flags & HIST_FIELD_FL_VAR_REF));
3385 		__destroy_hist_field(hist_data->var_refs[i]);
3386 		hist_data->var_refs[i] = NULL;
3387 	}
3388 }
3389 
3390 static int init_var_ref(struct hist_field *ref_field,
3391 			struct hist_field *var_field,
3392 			char *system, char *event_name)
3393 {
3394 	int err = 0;
3395 
3396 	ref_field->var.idx = var_field->var.idx;
3397 	ref_field->var.hist_data = var_field->hist_data;
3398 	ref_field->size = var_field->size;
3399 	ref_field->is_signed = var_field->is_signed;
3400 	ref_field->flags |= var_field->flags &
3401 		(HIST_FIELD_FL_TIMESTAMP | HIST_FIELD_FL_TIMESTAMP_USECS);
3402 
3403 	if (system) {
3404 		ref_field->system = kstrdup(system, GFP_KERNEL);
3405 		if (!ref_field->system)
3406 			return -ENOMEM;
3407 	}
3408 
3409 	if (event_name) {
3410 		ref_field->event_name = kstrdup(event_name, GFP_KERNEL);
3411 		if (!ref_field->event_name) {
3412 			err = -ENOMEM;
3413 			goto free;
3414 		}
3415 	}
3416 
3417 	if (var_field->var.name) {
3418 		ref_field->name = kstrdup(var_field->var.name, GFP_KERNEL);
3419 		if (!ref_field->name) {
3420 			err = -ENOMEM;
3421 			goto free;
3422 		}
3423 	} else if (var_field->name) {
3424 		ref_field->name = kstrdup(var_field->name, GFP_KERNEL);
3425 		if (!ref_field->name) {
3426 			err = -ENOMEM;
3427 			goto free;
3428 		}
3429 	}
3430 
3431 	ref_field->type = kstrdup(var_field->type, GFP_KERNEL);
3432 	if (!ref_field->type) {
3433 		err = -ENOMEM;
3434 		goto free;
3435 	}
3436  out:
3437 	return err;
3438  free:
3439 	kfree(ref_field->system);
3440 	kfree(ref_field->event_name);
3441 	kfree(ref_field->name);
3442 
3443 	goto out;
3444 }
3445 
3446 static int find_var_ref_idx(struct hist_trigger_data *hist_data,
3447 			    struct hist_field *var_field)
3448 {
3449 	struct hist_field *ref_field;
3450 	int i;
3451 
3452 	for (i = 0; i < hist_data->n_var_refs; i++) {
3453 		ref_field = hist_data->var_refs[i];
3454 		if (ref_field->var.idx == var_field->var.idx &&
3455 		    ref_field->var.hist_data == var_field->hist_data)
3456 			return i;
3457 	}
3458 
3459 	return -ENOENT;
3460 }
3461 
3462 /**
3463  * create_var_ref - Create a variable reference and attach it to trigger
3464  * @hist_data: The trigger that will be referencing the variable
3465  * @var_field: The VAR field to create a reference to
3466  * @system: The optional system string
3467  * @event_name: The optional event_name string
3468  *
3469  * Given a variable hist_field, create a VAR_REF hist_field that
3470  * represents a reference to it.
3471  *
3472  * This function also adds the reference to the trigger that
3473  * now references the variable.
3474  *
3475  * Return: The VAR_REF field if successful, NULL if not
3476  */
3477 static struct hist_field *create_var_ref(struct hist_trigger_data *hist_data,
3478 					 struct hist_field *var_field,
3479 					 char *system, char *event_name)
3480 {
3481 	unsigned long flags = HIST_FIELD_FL_VAR_REF;
3482 	struct hist_field *ref_field;
3483 	int i;
3484 
3485 	/* Check if the variable already exists */
3486 	for (i = 0; i < hist_data->n_var_refs; i++) {
3487 		ref_field = hist_data->var_refs[i];
3488 		if (ref_field->var.idx == var_field->var.idx &&
3489 		    ref_field->var.hist_data == var_field->hist_data) {
3490 			get_hist_field(ref_field);
3491 			return ref_field;
3492 		}
3493 	}
3494 
3495 	ref_field = create_hist_field(var_field->hist_data, NULL, flags, NULL);
3496 	if (ref_field) {
3497 		if (init_var_ref(ref_field, var_field, system, event_name)) {
3498 			destroy_hist_field(ref_field, 0);
3499 			return NULL;
3500 		}
3501 
3502 		hist_data->var_refs[hist_data->n_var_refs] = ref_field;
3503 		ref_field->var_ref_idx = hist_data->n_var_refs++;
3504 	}
3505 
3506 	return ref_field;
3507 }
3508 
3509 static bool is_var_ref(char *var_name)
3510 {
3511 	if (!var_name || strlen(var_name) < 2 || var_name[0] != '$')
3512 		return false;
3513 
3514 	return true;
3515 }
3516 
3517 static char *field_name_from_var(struct hist_trigger_data *hist_data,
3518 				 char *var_name)
3519 {
3520 	char *name, *field;
3521 	unsigned int i;
3522 
3523 	for (i = 0; i < hist_data->attrs->var_defs.n_vars; i++) {
3524 		name = hist_data->attrs->var_defs.name[i];
3525 
3526 		if (strcmp(var_name, name) == 0) {
3527 			field = hist_data->attrs->var_defs.expr[i];
3528 			if (contains_operator(field) || is_var_ref(field))
3529 				continue;
3530 			return field;
3531 		}
3532 	}
3533 
3534 	return NULL;
3535 }
3536 
3537 static char *local_field_var_ref(struct hist_trigger_data *hist_data,
3538 				 char *system, char *event_name,
3539 				 char *var_name)
3540 {
3541 	struct trace_event_call *call;
3542 
3543 	if (system && event_name) {
3544 		call = hist_data->event_file->event_call;
3545 
3546 		if (strcmp(system, call->class->system) != 0)
3547 			return NULL;
3548 
3549 		if (strcmp(event_name, trace_event_name(call)) != 0)
3550 			return NULL;
3551 	}
3552 
3553 	if (!!system != !!event_name)
3554 		return NULL;
3555 
3556 	if (!is_var_ref(var_name))
3557 		return NULL;
3558 
3559 	var_name++;
3560 
3561 	return field_name_from_var(hist_data, var_name);
3562 }
3563 
3564 static struct hist_field *parse_var_ref(struct hist_trigger_data *hist_data,
3565 					char *system, char *event_name,
3566 					char *var_name)
3567 {
3568 	struct hist_field *var_field = NULL, *ref_field = NULL;
3569 	struct trace_array *tr = hist_data->event_file->tr;
3570 
3571 	if (!is_var_ref(var_name))
3572 		return NULL;
3573 
3574 	var_name++;
3575 
3576 	var_field = find_event_var(hist_data, system, event_name, var_name);
3577 	if (var_field)
3578 		ref_field = create_var_ref(hist_data, var_field,
3579 					   system, event_name);
3580 
3581 	if (!ref_field)
3582 		hist_err(tr, HIST_ERR_VAR_NOT_FOUND, errpos(var_name));
3583 
3584 	return ref_field;
3585 }
3586 
3587 static struct ftrace_event_field *
3588 parse_field(struct hist_trigger_data *hist_data, struct trace_event_file *file,
3589 	    char *field_str, unsigned long *flags)
3590 {
3591 	struct ftrace_event_field *field = NULL;
3592 	char *field_name, *modifier, *str;
3593 	struct trace_array *tr = file->tr;
3594 
3595 	modifier = str = kstrdup(field_str, GFP_KERNEL);
3596 	if (!modifier)
3597 		return ERR_PTR(-ENOMEM);
3598 
3599 	field_name = strsep(&modifier, ".");
3600 	if (modifier) {
3601 		if (strcmp(modifier, "hex") == 0)
3602 			*flags |= HIST_FIELD_FL_HEX;
3603 		else if (strcmp(modifier, "sym") == 0)
3604 			*flags |= HIST_FIELD_FL_SYM;
3605 		else if (strcmp(modifier, "sym-offset") == 0)
3606 			*flags |= HIST_FIELD_FL_SYM_OFFSET;
3607 		else if ((strcmp(modifier, "execname") == 0) &&
3608 			 (strcmp(field_name, "common_pid") == 0))
3609 			*flags |= HIST_FIELD_FL_EXECNAME;
3610 		else if (strcmp(modifier, "syscall") == 0)
3611 			*flags |= HIST_FIELD_FL_SYSCALL;
3612 		else if (strcmp(modifier, "log2") == 0)
3613 			*flags |= HIST_FIELD_FL_LOG2;
3614 		else if (strcmp(modifier, "usecs") == 0)
3615 			*flags |= HIST_FIELD_FL_TIMESTAMP_USECS;
3616 		else {
3617 			hist_err(tr, HIST_ERR_BAD_FIELD_MODIFIER, errpos(modifier));
3618 			field = ERR_PTR(-EINVAL);
3619 			goto out;
3620 		}
3621 	}
3622 
3623 	if (strcmp(field_name, "common_timestamp") == 0) {
3624 		*flags |= HIST_FIELD_FL_TIMESTAMP;
3625 		hist_data->enable_timestamps = true;
3626 		if (*flags & HIST_FIELD_FL_TIMESTAMP_USECS)
3627 			hist_data->attrs->ts_in_usecs = true;
3628 	} else if (strcmp(field_name, "cpu") == 0)
3629 		*flags |= HIST_FIELD_FL_CPU;
3630 	else {
3631 		field = trace_find_event_field(file->event_call, field_name);
3632 		if (!field || !field->size) {
3633 			hist_err(tr, HIST_ERR_FIELD_NOT_FOUND, errpos(field_name));
3634 			field = ERR_PTR(-EINVAL);
3635 			goto out;
3636 		}
3637 	}
3638  out:
3639 	kfree(str);
3640 
3641 	return field;
3642 }
3643 
3644 static struct hist_field *create_alias(struct hist_trigger_data *hist_data,
3645 				       struct hist_field *var_ref,
3646 				       char *var_name)
3647 {
3648 	struct hist_field *alias = NULL;
3649 	unsigned long flags = HIST_FIELD_FL_ALIAS | HIST_FIELD_FL_VAR;
3650 
3651 	alias = create_hist_field(hist_data, NULL, flags, var_name);
3652 	if (!alias)
3653 		return NULL;
3654 
3655 	alias->fn = var_ref->fn;
3656 	alias->operands[0] = var_ref;
3657 
3658 	if (init_var_ref(alias, var_ref, var_ref->system, var_ref->event_name)) {
3659 		destroy_hist_field(alias, 0);
3660 		return NULL;
3661 	}
3662 
3663 	alias->var_ref_idx = var_ref->var_ref_idx;
3664 
3665 	return alias;
3666 }
3667 
3668 static struct hist_field *parse_atom(struct hist_trigger_data *hist_data,
3669 				     struct trace_event_file *file, char *str,
3670 				     unsigned long *flags, char *var_name)
3671 {
3672 	char *s, *ref_system = NULL, *ref_event = NULL, *ref_var = str;
3673 	struct ftrace_event_field *field = NULL;
3674 	struct hist_field *hist_field = NULL;
3675 	int ret = 0;
3676 
3677 	s = strchr(str, '.');
3678 	if (s) {
3679 		s = strchr(++s, '.');
3680 		if (s) {
3681 			ref_system = strsep(&str, ".");
3682 			if (!str) {
3683 				ret = -EINVAL;
3684 				goto out;
3685 			}
3686 			ref_event = strsep(&str, ".");
3687 			if (!str) {
3688 				ret = -EINVAL;
3689 				goto out;
3690 			}
3691 			ref_var = str;
3692 		}
3693 	}
3694 
3695 	s = local_field_var_ref(hist_data, ref_system, ref_event, ref_var);
3696 	if (!s) {
3697 		hist_field = parse_var_ref(hist_data, ref_system,
3698 					   ref_event, ref_var);
3699 		if (hist_field) {
3700 			if (var_name) {
3701 				hist_field = create_alias(hist_data, hist_field, var_name);
3702 				if (!hist_field) {
3703 					ret = -ENOMEM;
3704 					goto out;
3705 				}
3706 			}
3707 			return hist_field;
3708 		}
3709 	} else
3710 		str = s;
3711 
3712 	field = parse_field(hist_data, file, str, flags);
3713 	if (IS_ERR(field)) {
3714 		ret = PTR_ERR(field);
3715 		goto out;
3716 	}
3717 
3718 	hist_field = create_hist_field(hist_data, field, *flags, var_name);
3719 	if (!hist_field) {
3720 		ret = -ENOMEM;
3721 		goto out;
3722 	}
3723 
3724 	return hist_field;
3725  out:
3726 	return ERR_PTR(ret);
3727 }
3728 
3729 static struct hist_field *parse_expr(struct hist_trigger_data *hist_data,
3730 				     struct trace_event_file *file,
3731 				     char *str, unsigned long flags,
3732 				     char *var_name, unsigned int level);
3733 
3734 static struct hist_field *parse_unary(struct hist_trigger_data *hist_data,
3735 				      struct trace_event_file *file,
3736 				      char *str, unsigned long flags,
3737 				      char *var_name, unsigned int level)
3738 {
3739 	struct hist_field *operand1, *expr = NULL;
3740 	unsigned long operand_flags;
3741 	int ret = 0;
3742 	char *s;
3743 
3744 	/* we support only -(xxx) i.e. explicit parens required */
3745 
3746 	if (level > 3) {
3747 		hist_err(file->tr, HIST_ERR_TOO_MANY_SUBEXPR, errpos(str));
3748 		ret = -EINVAL;
3749 		goto free;
3750 	}
3751 
3752 	str++; /* skip leading '-' */
3753 
3754 	s = strchr(str, '(');
3755 	if (s)
3756 		str++;
3757 	else {
3758 		ret = -EINVAL;
3759 		goto free;
3760 	}
3761 
3762 	s = strrchr(str, ')');
3763 	if (s)
3764 		*s = '\0';
3765 	else {
3766 		ret = -EINVAL; /* no closing ')' */
3767 		goto free;
3768 	}
3769 
3770 	flags |= HIST_FIELD_FL_EXPR;
3771 	expr = create_hist_field(hist_data, NULL, flags, var_name);
3772 	if (!expr) {
3773 		ret = -ENOMEM;
3774 		goto free;
3775 	}
3776 
3777 	operand_flags = 0;
3778 	operand1 = parse_expr(hist_data, file, str, operand_flags, NULL, ++level);
3779 	if (IS_ERR(operand1)) {
3780 		ret = PTR_ERR(operand1);
3781 		goto free;
3782 	}
3783 
3784 	expr->flags |= operand1->flags &
3785 		(HIST_FIELD_FL_TIMESTAMP | HIST_FIELD_FL_TIMESTAMP_USECS);
3786 	expr->fn = hist_field_unary_minus;
3787 	expr->operands[0] = operand1;
3788 	expr->operator = FIELD_OP_UNARY_MINUS;
3789 	expr->name = expr_str(expr, 0);
3790 	expr->type = kstrdup(operand1->type, GFP_KERNEL);
3791 	if (!expr->type) {
3792 		ret = -ENOMEM;
3793 		goto free;
3794 	}
3795 
3796 	return expr;
3797  free:
3798 	destroy_hist_field(expr, 0);
3799 	return ERR_PTR(ret);
3800 }
3801 
3802 static int check_expr_operands(struct trace_array *tr,
3803 			       struct hist_field *operand1,
3804 			       struct hist_field *operand2)
3805 {
3806 	unsigned long operand1_flags = operand1->flags;
3807 	unsigned long operand2_flags = operand2->flags;
3808 
3809 	if ((operand1_flags & HIST_FIELD_FL_VAR_REF) ||
3810 	    (operand1_flags & HIST_FIELD_FL_ALIAS)) {
3811 		struct hist_field *var;
3812 
3813 		var = find_var_field(operand1->var.hist_data, operand1->name);
3814 		if (!var)
3815 			return -EINVAL;
3816 		operand1_flags = var->flags;
3817 	}
3818 
3819 	if ((operand2_flags & HIST_FIELD_FL_VAR_REF) ||
3820 	    (operand2_flags & HIST_FIELD_FL_ALIAS)) {
3821 		struct hist_field *var;
3822 
3823 		var = find_var_field(operand2->var.hist_data, operand2->name);
3824 		if (!var)
3825 			return -EINVAL;
3826 		operand2_flags = var->flags;
3827 	}
3828 
3829 	if ((operand1_flags & HIST_FIELD_FL_TIMESTAMP_USECS) !=
3830 	    (operand2_flags & HIST_FIELD_FL_TIMESTAMP_USECS)) {
3831 		hist_err(tr, HIST_ERR_TIMESTAMP_MISMATCH, 0);
3832 		return -EINVAL;
3833 	}
3834 
3835 	return 0;
3836 }
3837 
3838 static struct hist_field *parse_expr(struct hist_trigger_data *hist_data,
3839 				     struct trace_event_file *file,
3840 				     char *str, unsigned long flags,
3841 				     char *var_name, unsigned int level)
3842 {
3843 	struct hist_field *operand1 = NULL, *operand2 = NULL, *expr = NULL;
3844 	unsigned long operand_flags;
3845 	int field_op, ret = -EINVAL;
3846 	char *sep, *operand1_str;
3847 
3848 	if (level > 3) {
3849 		hist_err(file->tr, HIST_ERR_TOO_MANY_SUBEXPR, errpos(str));
3850 		return ERR_PTR(-EINVAL);
3851 	}
3852 
3853 	field_op = contains_operator(str);
3854 
3855 	if (field_op == FIELD_OP_NONE)
3856 		return parse_atom(hist_data, file, str, &flags, var_name);
3857 
3858 	if (field_op == FIELD_OP_UNARY_MINUS)
3859 		return parse_unary(hist_data, file, str, flags, var_name, ++level);
3860 
3861 	switch (field_op) {
3862 	case FIELD_OP_MINUS:
3863 		sep = "-";
3864 		break;
3865 	case FIELD_OP_PLUS:
3866 		sep = "+";
3867 		break;
3868 	default:
3869 		goto free;
3870 	}
3871 
3872 	operand1_str = strsep(&str, sep);
3873 	if (!operand1_str || !str)
3874 		goto free;
3875 
3876 	operand_flags = 0;
3877 	operand1 = parse_atom(hist_data, file, operand1_str,
3878 			      &operand_flags, NULL);
3879 	if (IS_ERR(operand1)) {
3880 		ret = PTR_ERR(operand1);
3881 		operand1 = NULL;
3882 		goto free;
3883 	}
3884 
3885 	/* rest of string could be another expression e.g. b+c in a+b+c */
3886 	operand_flags = 0;
3887 	operand2 = parse_expr(hist_data, file, str, operand_flags, NULL, ++level);
3888 	if (IS_ERR(operand2)) {
3889 		ret = PTR_ERR(operand2);
3890 		operand2 = NULL;
3891 		goto free;
3892 	}
3893 
3894 	ret = check_expr_operands(file->tr, operand1, operand2);
3895 	if (ret)
3896 		goto free;
3897 
3898 	flags |= HIST_FIELD_FL_EXPR;
3899 
3900 	flags |= operand1->flags &
3901 		(HIST_FIELD_FL_TIMESTAMP | HIST_FIELD_FL_TIMESTAMP_USECS);
3902 
3903 	expr = create_hist_field(hist_data, NULL, flags, var_name);
3904 	if (!expr) {
3905 		ret = -ENOMEM;
3906 		goto free;
3907 	}
3908 
3909 	operand1->read_once = true;
3910 	operand2->read_once = true;
3911 
3912 	expr->operands[0] = operand1;
3913 	expr->operands[1] = operand2;
3914 	expr->operator = field_op;
3915 	expr->name = expr_str(expr, 0);
3916 	expr->type = kstrdup(operand1->type, GFP_KERNEL);
3917 	if (!expr->type) {
3918 		ret = -ENOMEM;
3919 		goto free;
3920 	}
3921 
3922 	switch (field_op) {
3923 	case FIELD_OP_MINUS:
3924 		expr->fn = hist_field_minus;
3925 		break;
3926 	case FIELD_OP_PLUS:
3927 		expr->fn = hist_field_plus;
3928 		break;
3929 	default:
3930 		ret = -EINVAL;
3931 		goto free;
3932 	}
3933 
3934 	return expr;
3935  free:
3936 	destroy_hist_field(operand1, 0);
3937 	destroy_hist_field(operand2, 0);
3938 	destroy_hist_field(expr, 0);
3939 
3940 	return ERR_PTR(ret);
3941 }
3942 
3943 static char *find_trigger_filter(struct hist_trigger_data *hist_data,
3944 				 struct trace_event_file *file)
3945 {
3946 	struct event_trigger_data *test;
3947 
3948 	lockdep_assert_held(&event_mutex);
3949 
3950 	list_for_each_entry(test, &file->triggers, list) {
3951 		if (test->cmd_ops->trigger_type == ETT_EVENT_HIST) {
3952 			if (test->private_data == hist_data)
3953 				return test->filter_str;
3954 		}
3955 	}
3956 
3957 	return NULL;
3958 }
3959 
3960 static struct event_command trigger_hist_cmd;
3961 static int event_hist_trigger_func(struct event_command *cmd_ops,
3962 				   struct trace_event_file *file,
3963 				   char *glob, char *cmd, char *param);
3964 
3965 static bool compatible_keys(struct hist_trigger_data *target_hist_data,
3966 			    struct hist_trigger_data *hist_data,
3967 			    unsigned int n_keys)
3968 {
3969 	struct hist_field *target_hist_field, *hist_field;
3970 	unsigned int n, i, j;
3971 
3972 	if (hist_data->n_fields - hist_data->n_vals != n_keys)
3973 		return false;
3974 
3975 	i = hist_data->n_vals;
3976 	j = target_hist_data->n_vals;
3977 
3978 	for (n = 0; n < n_keys; n++) {
3979 		hist_field = hist_data->fields[i + n];
3980 		target_hist_field = target_hist_data->fields[j + n];
3981 
3982 		if (strcmp(hist_field->type, target_hist_field->type) != 0)
3983 			return false;
3984 		if (hist_field->size != target_hist_field->size)
3985 			return false;
3986 		if (hist_field->is_signed != target_hist_field->is_signed)
3987 			return false;
3988 	}
3989 
3990 	return true;
3991 }
3992 
3993 static struct hist_trigger_data *
3994 find_compatible_hist(struct hist_trigger_data *target_hist_data,
3995 		     struct trace_event_file *file)
3996 {
3997 	struct hist_trigger_data *hist_data;
3998 	struct event_trigger_data *test;
3999 	unsigned int n_keys;
4000 
4001 	lockdep_assert_held(&event_mutex);
4002 
4003 	n_keys = target_hist_data->n_fields - target_hist_data->n_vals;
4004 
4005 	list_for_each_entry(test, &file->triggers, list) {
4006 		if (test->cmd_ops->trigger_type == ETT_EVENT_HIST) {
4007 			hist_data = test->private_data;
4008 
4009 			if (compatible_keys(target_hist_data, hist_data, n_keys))
4010 				return hist_data;
4011 		}
4012 	}
4013 
4014 	return NULL;
4015 }
4016 
4017 static struct trace_event_file *event_file(struct trace_array *tr,
4018 					   char *system, char *event_name)
4019 {
4020 	struct trace_event_file *file;
4021 
4022 	file = __find_event_file(tr, system, event_name);
4023 	if (!file)
4024 		return ERR_PTR(-EINVAL);
4025 
4026 	return file;
4027 }
4028 
4029 static struct hist_field *
4030 find_synthetic_field_var(struct hist_trigger_data *target_hist_data,
4031 			 char *system, char *event_name, char *field_name)
4032 {
4033 	struct hist_field *event_var;
4034 	char *synthetic_name;
4035 
4036 	synthetic_name = kzalloc(MAX_FILTER_STR_VAL, GFP_KERNEL);
4037 	if (!synthetic_name)
4038 		return ERR_PTR(-ENOMEM);
4039 
4040 	strcpy(synthetic_name, "synthetic_");
4041 	strcat(synthetic_name, field_name);
4042 
4043 	event_var = find_event_var(target_hist_data, system, event_name, synthetic_name);
4044 
4045 	kfree(synthetic_name);
4046 
4047 	return event_var;
4048 }
4049 
4050 /**
4051  * create_field_var_hist - Automatically create a histogram and var for a field
4052  * @target_hist_data: The target hist trigger
4053  * @subsys_name: Optional subsystem name
4054  * @event_name: Optional event name
4055  * @field_name: The name of the field (and the resulting variable)
4056  *
4057  * Hist trigger actions fetch data from variables, not directly from
4058  * events.  However, for convenience, users are allowed to directly
4059  * specify an event field in an action, which will be automatically
4060  * converted into a variable on their behalf.
4061 
4062  * If a user specifies a field on an event that isn't the event the
4063  * histogram currently being defined (the target event histogram), the
4064  * only way that can be accomplished is if a new hist trigger is
4065  * created and the field variable defined on that.
4066  *
4067  * This function creates a new histogram compatible with the target
4068  * event (meaning a histogram with the same key as the target
4069  * histogram), and creates a variable for the specified field, but
4070  * with 'synthetic_' prepended to the variable name in order to avoid
4071  * collision with normal field variables.
4072  *
4073  * Return: The variable created for the field.
4074  */
4075 static struct hist_field *
4076 create_field_var_hist(struct hist_trigger_data *target_hist_data,
4077 		      char *subsys_name, char *event_name, char *field_name)
4078 {
4079 	struct trace_array *tr = target_hist_data->event_file->tr;
4080 	struct hist_field *event_var = ERR_PTR(-EINVAL);
4081 	struct hist_trigger_data *hist_data;
4082 	unsigned int i, n, first = true;
4083 	struct field_var_hist *var_hist;
4084 	struct trace_event_file *file;
4085 	struct hist_field *key_field;
4086 	char *saved_filter;
4087 	char *cmd;
4088 	int ret;
4089 
4090 	if (target_hist_data->n_field_var_hists >= SYNTH_FIELDS_MAX) {
4091 		hist_err(tr, HIST_ERR_TOO_MANY_FIELD_VARS, errpos(field_name));
4092 		return ERR_PTR(-EINVAL);
4093 	}
4094 
4095 	file = event_file(tr, subsys_name, event_name);
4096 
4097 	if (IS_ERR(file)) {
4098 		hist_err(tr, HIST_ERR_EVENT_FILE_NOT_FOUND, errpos(field_name));
4099 		ret = PTR_ERR(file);
4100 		return ERR_PTR(ret);
4101 	}
4102 
4103 	/*
4104 	 * Look for a histogram compatible with target.  We'll use the
4105 	 * found histogram specification to create a new matching
4106 	 * histogram with our variable on it.  target_hist_data is not
4107 	 * yet a registered histogram so we can't use that.
4108 	 */
4109 	hist_data = find_compatible_hist(target_hist_data, file);
4110 	if (!hist_data) {
4111 		hist_err(tr, HIST_ERR_HIST_NOT_FOUND, errpos(field_name));
4112 		return ERR_PTR(-EINVAL);
4113 	}
4114 
4115 	/* See if a synthetic field variable has already been created */
4116 	event_var = find_synthetic_field_var(target_hist_data, subsys_name,
4117 					     event_name, field_name);
4118 	if (!IS_ERR_OR_NULL(event_var))
4119 		return event_var;
4120 
4121 	var_hist = kzalloc(sizeof(*var_hist), GFP_KERNEL);
4122 	if (!var_hist)
4123 		return ERR_PTR(-ENOMEM);
4124 
4125 	cmd = kzalloc(MAX_FILTER_STR_VAL, GFP_KERNEL);
4126 	if (!cmd) {
4127 		kfree(var_hist);
4128 		return ERR_PTR(-ENOMEM);
4129 	}
4130 
4131 	/* Use the same keys as the compatible histogram */
4132 	strcat(cmd, "keys=");
4133 
4134 	for_each_hist_key_field(i, hist_data) {
4135 		key_field = hist_data->fields[i];
4136 		if (!first)
4137 			strcat(cmd, ",");
4138 		strcat(cmd, key_field->field->name);
4139 		first = false;
4140 	}
4141 
4142 	/* Create the synthetic field variable specification */
4143 	strcat(cmd, ":synthetic_");
4144 	strcat(cmd, field_name);
4145 	strcat(cmd, "=");
4146 	strcat(cmd, field_name);
4147 
4148 	/* Use the same filter as the compatible histogram */
4149 	saved_filter = find_trigger_filter(hist_data, file);
4150 	if (saved_filter) {
4151 		strcat(cmd, " if ");
4152 		strcat(cmd, saved_filter);
4153 	}
4154 
4155 	var_hist->cmd = kstrdup(cmd, GFP_KERNEL);
4156 	if (!var_hist->cmd) {
4157 		kfree(cmd);
4158 		kfree(var_hist);
4159 		return ERR_PTR(-ENOMEM);
4160 	}
4161 
4162 	/* Save the compatible histogram information */
4163 	var_hist->hist_data = hist_data;
4164 
4165 	/* Create the new histogram with our variable */
4166 	ret = event_hist_trigger_func(&trigger_hist_cmd, file,
4167 				      "", "hist", cmd);
4168 	if (ret) {
4169 		kfree(cmd);
4170 		kfree(var_hist->cmd);
4171 		kfree(var_hist);
4172 		hist_err(tr, HIST_ERR_HIST_CREATE_FAIL, errpos(field_name));
4173 		return ERR_PTR(ret);
4174 	}
4175 
4176 	kfree(cmd);
4177 
4178 	/* If we can't find the variable, something went wrong */
4179 	event_var = find_synthetic_field_var(target_hist_data, subsys_name,
4180 					     event_name, field_name);
4181 	if (IS_ERR_OR_NULL(event_var)) {
4182 		kfree(var_hist->cmd);
4183 		kfree(var_hist);
4184 		hist_err(tr, HIST_ERR_SYNTH_VAR_NOT_FOUND, errpos(field_name));
4185 		return ERR_PTR(-EINVAL);
4186 	}
4187 
4188 	n = target_hist_data->n_field_var_hists;
4189 	target_hist_data->field_var_hists[n] = var_hist;
4190 	target_hist_data->n_field_var_hists++;
4191 
4192 	return event_var;
4193 }
4194 
4195 static struct hist_field *
4196 find_target_event_var(struct hist_trigger_data *hist_data,
4197 		      char *subsys_name, char *event_name, char *var_name)
4198 {
4199 	struct trace_event_file *file = hist_data->event_file;
4200 	struct hist_field *hist_field = NULL;
4201 
4202 	if (subsys_name) {
4203 		struct trace_event_call *call;
4204 
4205 		if (!event_name)
4206 			return NULL;
4207 
4208 		call = file->event_call;
4209 
4210 		if (strcmp(subsys_name, call->class->system) != 0)
4211 			return NULL;
4212 
4213 		if (strcmp(event_name, trace_event_name(call)) != 0)
4214 			return NULL;
4215 	}
4216 
4217 	hist_field = find_var_field(hist_data, var_name);
4218 
4219 	return hist_field;
4220 }
4221 
4222 static inline void __update_field_vars(struct tracing_map_elt *elt,
4223 				       struct ring_buffer_event *rbe,
4224 				       void *rec,
4225 				       struct field_var **field_vars,
4226 				       unsigned int n_field_vars,
4227 				       unsigned int field_var_str_start)
4228 {
4229 	struct hist_elt_data *elt_data = elt->private_data;
4230 	unsigned int i, j, var_idx;
4231 	u64 var_val;
4232 
4233 	for (i = 0, j = field_var_str_start; i < n_field_vars; i++) {
4234 		struct field_var *field_var = field_vars[i];
4235 		struct hist_field *var = field_var->var;
4236 		struct hist_field *val = field_var->val;
4237 
4238 		var_val = val->fn(val, elt, rbe, rec);
4239 		var_idx = var->var.idx;
4240 
4241 		if (val->flags & HIST_FIELD_FL_STRING) {
4242 			char *str = elt_data->field_var_str[j++];
4243 			char *val_str = (char *)(uintptr_t)var_val;
4244 
4245 			strscpy(str, val_str, STR_VAR_LEN_MAX);
4246 			var_val = (u64)(uintptr_t)str;
4247 		}
4248 		tracing_map_set_var(elt, var_idx, var_val);
4249 	}
4250 }
4251 
4252 static void update_field_vars(struct hist_trigger_data *hist_data,
4253 			      struct tracing_map_elt *elt,
4254 			      struct ring_buffer_event *rbe,
4255 			      void *rec)
4256 {
4257 	__update_field_vars(elt, rbe, rec, hist_data->field_vars,
4258 			    hist_data->n_field_vars, 0);
4259 }
4260 
4261 static void save_track_data_vars(struct hist_trigger_data *hist_data,
4262 				 struct tracing_map_elt *elt, void *rec,
4263 				 struct ring_buffer_event *rbe, void *key,
4264 				 struct action_data *data, u64 *var_ref_vals)
4265 {
4266 	__update_field_vars(elt, rbe, rec, hist_data->save_vars,
4267 			    hist_data->n_save_vars, hist_data->n_field_var_str);
4268 }
4269 
4270 static struct hist_field *create_var(struct hist_trigger_data *hist_data,
4271 				     struct trace_event_file *file,
4272 				     char *name, int size, const char *type)
4273 {
4274 	struct hist_field *var;
4275 	int idx;
4276 
4277 	if (find_var(hist_data, file, name) && !hist_data->remove) {
4278 		var = ERR_PTR(-EINVAL);
4279 		goto out;
4280 	}
4281 
4282 	var = kzalloc(sizeof(struct hist_field), GFP_KERNEL);
4283 	if (!var) {
4284 		var = ERR_PTR(-ENOMEM);
4285 		goto out;
4286 	}
4287 
4288 	idx = tracing_map_add_var(hist_data->map);
4289 	if (idx < 0) {
4290 		kfree(var);
4291 		var = ERR_PTR(-EINVAL);
4292 		goto out;
4293 	}
4294 
4295 	var->flags = HIST_FIELD_FL_VAR;
4296 	var->var.idx = idx;
4297 	var->var.hist_data = var->hist_data = hist_data;
4298 	var->size = size;
4299 	var->var.name = kstrdup(name, GFP_KERNEL);
4300 	var->type = kstrdup(type, GFP_KERNEL);
4301 	if (!var->var.name || !var->type) {
4302 		kfree(var->var.name);
4303 		kfree(var->type);
4304 		kfree(var);
4305 		var = ERR_PTR(-ENOMEM);
4306 	}
4307  out:
4308 	return var;
4309 }
4310 
4311 static struct field_var *create_field_var(struct hist_trigger_data *hist_data,
4312 					  struct trace_event_file *file,
4313 					  char *field_name)
4314 {
4315 	struct hist_field *val = NULL, *var = NULL;
4316 	unsigned long flags = HIST_FIELD_FL_VAR;
4317 	struct trace_array *tr = file->tr;
4318 	struct field_var *field_var;
4319 	int ret = 0;
4320 
4321 	if (hist_data->n_field_vars >= SYNTH_FIELDS_MAX) {
4322 		hist_err(tr, HIST_ERR_TOO_MANY_FIELD_VARS, errpos(field_name));
4323 		ret = -EINVAL;
4324 		goto err;
4325 	}
4326 
4327 	val = parse_atom(hist_data, file, field_name, &flags, NULL);
4328 	if (IS_ERR(val)) {
4329 		hist_err(tr, HIST_ERR_FIELD_VAR_PARSE_FAIL, errpos(field_name));
4330 		ret = PTR_ERR(val);
4331 		goto err;
4332 	}
4333 
4334 	var = create_var(hist_data, file, field_name, val->size, val->type);
4335 	if (IS_ERR(var)) {
4336 		hist_err(tr, HIST_ERR_VAR_CREATE_FIND_FAIL, errpos(field_name));
4337 		kfree(val);
4338 		ret = PTR_ERR(var);
4339 		goto err;
4340 	}
4341 
4342 	field_var = kzalloc(sizeof(struct field_var), GFP_KERNEL);
4343 	if (!field_var) {
4344 		kfree(val);
4345 		kfree(var);
4346 		ret =  -ENOMEM;
4347 		goto err;
4348 	}
4349 
4350 	field_var->var = var;
4351 	field_var->val = val;
4352  out:
4353 	return field_var;
4354  err:
4355 	field_var = ERR_PTR(ret);
4356 	goto out;
4357 }
4358 
4359 /**
4360  * create_target_field_var - Automatically create a variable for a field
4361  * @target_hist_data: The target hist trigger
4362  * @subsys_name: Optional subsystem name
4363  * @event_name: Optional event name
4364  * @var_name: The name of the field (and the resulting variable)
4365  *
4366  * Hist trigger actions fetch data from variables, not directly from
4367  * events.  However, for convenience, users are allowed to directly
4368  * specify an event field in an action, which will be automatically
4369  * converted into a variable on their behalf.
4370 
4371  * This function creates a field variable with the name var_name on
4372  * the hist trigger currently being defined on the target event.  If
4373  * subsys_name and event_name are specified, this function simply
4374  * verifies that they do in fact match the target event subsystem and
4375  * event name.
4376  *
4377  * Return: The variable created for the field.
4378  */
4379 static struct field_var *
4380 create_target_field_var(struct hist_trigger_data *target_hist_data,
4381 			char *subsys_name, char *event_name, char *var_name)
4382 {
4383 	struct trace_event_file *file = target_hist_data->event_file;
4384 
4385 	if (subsys_name) {
4386 		struct trace_event_call *call;
4387 
4388 		if (!event_name)
4389 			return NULL;
4390 
4391 		call = file->event_call;
4392 
4393 		if (strcmp(subsys_name, call->class->system) != 0)
4394 			return NULL;
4395 
4396 		if (strcmp(event_name, trace_event_name(call)) != 0)
4397 			return NULL;
4398 	}
4399 
4400 	return create_field_var(target_hist_data, file, var_name);
4401 }
4402 
4403 static bool check_track_val_max(u64 track_val, u64 var_val)
4404 {
4405 	if (var_val <= track_val)
4406 		return false;
4407 
4408 	return true;
4409 }
4410 
4411 static bool check_track_val_changed(u64 track_val, u64 var_val)
4412 {
4413 	if (var_val == track_val)
4414 		return false;
4415 
4416 	return true;
4417 }
4418 
4419 static u64 get_track_val(struct hist_trigger_data *hist_data,
4420 			 struct tracing_map_elt *elt,
4421 			 struct action_data *data)
4422 {
4423 	unsigned int track_var_idx = data->track_data.track_var->var.idx;
4424 	u64 track_val;
4425 
4426 	track_val = tracing_map_read_var(elt, track_var_idx);
4427 
4428 	return track_val;
4429 }
4430 
4431 static void save_track_val(struct hist_trigger_data *hist_data,
4432 			   struct tracing_map_elt *elt,
4433 			   struct action_data *data, u64 var_val)
4434 {
4435 	unsigned int track_var_idx = data->track_data.track_var->var.idx;
4436 
4437 	tracing_map_set_var(elt, track_var_idx, var_val);
4438 }
4439 
4440 static void save_track_data(struct hist_trigger_data *hist_data,
4441 			    struct tracing_map_elt *elt, void *rec,
4442 			    struct ring_buffer_event *rbe, void *key,
4443 			    struct action_data *data, u64 *var_ref_vals)
4444 {
4445 	if (data->track_data.save_data)
4446 		data->track_data.save_data(hist_data, elt, rec, rbe, key, data, var_ref_vals);
4447 }
4448 
4449 static bool check_track_val(struct tracing_map_elt *elt,
4450 			    struct action_data *data,
4451 			    u64 var_val)
4452 {
4453 	struct hist_trigger_data *hist_data;
4454 	u64 track_val;
4455 
4456 	hist_data = data->track_data.track_var->hist_data;
4457 	track_val = get_track_val(hist_data, elt, data);
4458 
4459 	return data->track_data.check_val(track_val, var_val);
4460 }
4461 
4462 #ifdef CONFIG_TRACER_SNAPSHOT
4463 static bool cond_snapshot_update(struct trace_array *tr, void *cond_data)
4464 {
4465 	/* called with tr->max_lock held */
4466 	struct track_data *track_data = tr->cond_snapshot->cond_data;
4467 	struct hist_elt_data *elt_data, *track_elt_data;
4468 	struct snapshot_context *context = cond_data;
4469 	struct action_data *action;
4470 	u64 track_val;
4471 
4472 	if (!track_data)
4473 		return false;
4474 
4475 	action = track_data->action_data;
4476 
4477 	track_val = get_track_val(track_data->hist_data, context->elt,
4478 				  track_data->action_data);
4479 
4480 	if (!action->track_data.check_val(track_data->track_val, track_val))
4481 		return false;
4482 
4483 	track_data->track_val = track_val;
4484 	memcpy(track_data->key, context->key, track_data->key_len);
4485 
4486 	elt_data = context->elt->private_data;
4487 	track_elt_data = track_data->elt.private_data;
4488 	if (elt_data->comm)
4489 		strncpy(track_elt_data->comm, elt_data->comm, TASK_COMM_LEN);
4490 
4491 	track_data->updated = true;
4492 
4493 	return true;
4494 }
4495 
4496 static void save_track_data_snapshot(struct hist_trigger_data *hist_data,
4497 				     struct tracing_map_elt *elt, void *rec,
4498 				     struct ring_buffer_event *rbe, void *key,
4499 				     struct action_data *data,
4500 				     u64 *var_ref_vals)
4501 {
4502 	struct trace_event_file *file = hist_data->event_file;
4503 	struct snapshot_context context;
4504 
4505 	context.elt = elt;
4506 	context.key = key;
4507 
4508 	tracing_snapshot_cond(file->tr, &context);
4509 }
4510 
4511 static void hist_trigger_print_key(struct seq_file *m,
4512 				   struct hist_trigger_data *hist_data,
4513 				   void *key,
4514 				   struct tracing_map_elt *elt);
4515 
4516 static struct action_data *snapshot_action(struct hist_trigger_data *hist_data)
4517 {
4518 	unsigned int i;
4519 
4520 	if (!hist_data->n_actions)
4521 		return NULL;
4522 
4523 	for (i = 0; i < hist_data->n_actions; i++) {
4524 		struct action_data *data = hist_data->actions[i];
4525 
4526 		if (data->action == ACTION_SNAPSHOT)
4527 			return data;
4528 	}
4529 
4530 	return NULL;
4531 }
4532 
4533 static void track_data_snapshot_print(struct seq_file *m,
4534 				      struct hist_trigger_data *hist_data)
4535 {
4536 	struct trace_event_file *file = hist_data->event_file;
4537 	struct track_data *track_data;
4538 	struct action_data *action;
4539 
4540 	track_data = tracing_cond_snapshot_data(file->tr);
4541 	if (!track_data)
4542 		return;
4543 
4544 	if (!track_data->updated)
4545 		return;
4546 
4547 	action = snapshot_action(hist_data);
4548 	if (!action)
4549 		return;
4550 
4551 	seq_puts(m, "\nSnapshot taken (see tracing/snapshot).  Details:\n");
4552 	seq_printf(m, "\ttriggering value { %s(%s) }: %10llu",
4553 		   action->handler == HANDLER_ONMAX ? "onmax" : "onchange",
4554 		   action->track_data.var_str, track_data->track_val);
4555 
4556 	seq_puts(m, "\ttriggered by event with key: ");
4557 	hist_trigger_print_key(m, hist_data, track_data->key, &track_data->elt);
4558 	seq_putc(m, '\n');
4559 }
4560 #else
4561 static bool cond_snapshot_update(struct trace_array *tr, void *cond_data)
4562 {
4563 	return false;
4564 }
4565 static void save_track_data_snapshot(struct hist_trigger_data *hist_data,
4566 				     struct tracing_map_elt *elt, void *rec,
4567 				     struct ring_buffer_event *rbe, void *key,
4568 				     struct action_data *data,
4569 				     u64 *var_ref_vals) {}
4570 static void track_data_snapshot_print(struct seq_file *m,
4571 				      struct hist_trigger_data *hist_data) {}
4572 #endif /* CONFIG_TRACER_SNAPSHOT */
4573 
4574 static void track_data_print(struct seq_file *m,
4575 			     struct hist_trigger_data *hist_data,
4576 			     struct tracing_map_elt *elt,
4577 			     struct action_data *data)
4578 {
4579 	u64 track_val = get_track_val(hist_data, elt, data);
4580 	unsigned int i, save_var_idx;
4581 
4582 	if (data->handler == HANDLER_ONMAX)
4583 		seq_printf(m, "\n\tmax: %10llu", track_val);
4584 	else if (data->handler == HANDLER_ONCHANGE)
4585 		seq_printf(m, "\n\tchanged: %10llu", track_val);
4586 
4587 	if (data->action == ACTION_SNAPSHOT)
4588 		return;
4589 
4590 	for (i = 0; i < hist_data->n_save_vars; i++) {
4591 		struct hist_field *save_val = hist_data->save_vars[i]->val;
4592 		struct hist_field *save_var = hist_data->save_vars[i]->var;
4593 		u64 val;
4594 
4595 		save_var_idx = save_var->var.idx;
4596 
4597 		val = tracing_map_read_var(elt, save_var_idx);
4598 
4599 		if (save_val->flags & HIST_FIELD_FL_STRING) {
4600 			seq_printf(m, "  %s: %-32s", save_var->var.name,
4601 				   (char *)(uintptr_t)(val));
4602 		} else
4603 			seq_printf(m, "  %s: %10llu", save_var->var.name, val);
4604 	}
4605 }
4606 
4607 static void ontrack_action(struct hist_trigger_data *hist_data,
4608 			   struct tracing_map_elt *elt, void *rec,
4609 			   struct ring_buffer_event *rbe, void *key,
4610 			   struct action_data *data, u64 *var_ref_vals)
4611 {
4612 	u64 var_val = var_ref_vals[data->track_data.var_ref->var_ref_idx];
4613 
4614 	if (check_track_val(elt, data, var_val)) {
4615 		save_track_val(hist_data, elt, data, var_val);
4616 		save_track_data(hist_data, elt, rec, rbe, key, data, var_ref_vals);
4617 	}
4618 }
4619 
4620 static void action_data_destroy(struct action_data *data)
4621 {
4622 	unsigned int i;
4623 
4624 	lockdep_assert_held(&event_mutex);
4625 
4626 	kfree(data->action_name);
4627 
4628 	for (i = 0; i < data->n_params; i++)
4629 		kfree(data->params[i]);
4630 
4631 	if (data->synth_event)
4632 		data->synth_event->ref--;
4633 
4634 	kfree(data->synth_event_name);
4635 
4636 	kfree(data);
4637 }
4638 
4639 static void track_data_destroy(struct hist_trigger_data *hist_data,
4640 			       struct action_data *data)
4641 {
4642 	struct trace_event_file *file = hist_data->event_file;
4643 
4644 	destroy_hist_field(data->track_data.track_var, 0);
4645 
4646 	if (data->action == ACTION_SNAPSHOT) {
4647 		struct track_data *track_data;
4648 
4649 		track_data = tracing_cond_snapshot_data(file->tr);
4650 		if (track_data && track_data->hist_data == hist_data) {
4651 			tracing_snapshot_cond_disable(file->tr);
4652 			track_data_free(track_data);
4653 		}
4654 	}
4655 
4656 	kfree(data->track_data.var_str);
4657 
4658 	action_data_destroy(data);
4659 }
4660 
4661 static int action_create(struct hist_trigger_data *hist_data,
4662 			 struct action_data *data);
4663 
4664 static int track_data_create(struct hist_trigger_data *hist_data,
4665 			     struct action_data *data)
4666 {
4667 	struct hist_field *var_field, *ref_field, *track_var = NULL;
4668 	struct trace_event_file *file = hist_data->event_file;
4669 	struct trace_array *tr = file->tr;
4670 	char *track_data_var_str;
4671 	int ret = 0;
4672 
4673 	track_data_var_str = data->track_data.var_str;
4674 	if (track_data_var_str[0] != '$') {
4675 		hist_err(tr, HIST_ERR_ONX_NOT_VAR, errpos(track_data_var_str));
4676 		return -EINVAL;
4677 	}
4678 	track_data_var_str++;
4679 
4680 	var_field = find_target_event_var(hist_data, NULL, NULL, track_data_var_str);
4681 	if (!var_field) {
4682 		hist_err(tr, HIST_ERR_ONX_VAR_NOT_FOUND, errpos(track_data_var_str));
4683 		return -EINVAL;
4684 	}
4685 
4686 	ref_field = create_var_ref(hist_data, var_field, NULL, NULL);
4687 	if (!ref_field)
4688 		return -ENOMEM;
4689 
4690 	data->track_data.var_ref = ref_field;
4691 
4692 	if (data->handler == HANDLER_ONMAX)
4693 		track_var = create_var(hist_data, file, "__max", sizeof(u64), "u64");
4694 	if (IS_ERR(track_var)) {
4695 		hist_err(tr, HIST_ERR_ONX_VAR_CREATE_FAIL, 0);
4696 		ret = PTR_ERR(track_var);
4697 		goto out;
4698 	}
4699 
4700 	if (data->handler == HANDLER_ONCHANGE)
4701 		track_var = create_var(hist_data, file, "__change", sizeof(u64), "u64");
4702 	if (IS_ERR(track_var)) {
4703 		hist_err(tr, HIST_ERR_ONX_VAR_CREATE_FAIL, 0);
4704 		ret = PTR_ERR(track_var);
4705 		goto out;
4706 	}
4707 	data->track_data.track_var = track_var;
4708 
4709 	ret = action_create(hist_data, data);
4710  out:
4711 	return ret;
4712 }
4713 
4714 static int parse_action_params(struct trace_array *tr, char *params,
4715 			       struct action_data *data)
4716 {
4717 	char *param, *saved_param;
4718 	bool first_param = true;
4719 	int ret = 0;
4720 
4721 	while (params) {
4722 		if (data->n_params >= SYNTH_FIELDS_MAX) {
4723 			hist_err(tr, HIST_ERR_TOO_MANY_PARAMS, 0);
4724 			goto out;
4725 		}
4726 
4727 		param = strsep(&params, ",");
4728 		if (!param) {
4729 			hist_err(tr, HIST_ERR_PARAM_NOT_FOUND, 0);
4730 			ret = -EINVAL;
4731 			goto out;
4732 		}
4733 
4734 		param = strstrip(param);
4735 		if (strlen(param) < 2) {
4736 			hist_err(tr, HIST_ERR_INVALID_PARAM, errpos(param));
4737 			ret = -EINVAL;
4738 			goto out;
4739 		}
4740 
4741 		saved_param = kstrdup(param, GFP_KERNEL);
4742 		if (!saved_param) {
4743 			ret = -ENOMEM;
4744 			goto out;
4745 		}
4746 
4747 		if (first_param && data->use_trace_keyword) {
4748 			data->synth_event_name = saved_param;
4749 			first_param = false;
4750 			continue;
4751 		}
4752 		first_param = false;
4753 
4754 		data->params[data->n_params++] = saved_param;
4755 	}
4756  out:
4757 	return ret;
4758 }
4759 
4760 static int action_parse(struct trace_array *tr, char *str, struct action_data *data,
4761 			enum handler_id handler)
4762 {
4763 	char *action_name;
4764 	int ret = 0;
4765 
4766 	strsep(&str, ".");
4767 	if (!str) {
4768 		hist_err(tr, HIST_ERR_ACTION_NOT_FOUND, 0);
4769 		ret = -EINVAL;
4770 		goto out;
4771 	}
4772 
4773 	action_name = strsep(&str, "(");
4774 	if (!action_name || !str) {
4775 		hist_err(tr, HIST_ERR_ACTION_NOT_FOUND, 0);
4776 		ret = -EINVAL;
4777 		goto out;
4778 	}
4779 
4780 	if (str_has_prefix(action_name, "save")) {
4781 		char *params = strsep(&str, ")");
4782 
4783 		if (!params) {
4784 			hist_err(tr, HIST_ERR_NO_SAVE_PARAMS, 0);
4785 			ret = -EINVAL;
4786 			goto out;
4787 		}
4788 
4789 		ret = parse_action_params(tr, params, data);
4790 		if (ret)
4791 			goto out;
4792 
4793 		if (handler == HANDLER_ONMAX)
4794 			data->track_data.check_val = check_track_val_max;
4795 		else if (handler == HANDLER_ONCHANGE)
4796 			data->track_data.check_val = check_track_val_changed;
4797 		else {
4798 			hist_err(tr, HIST_ERR_ACTION_MISMATCH, errpos(action_name));
4799 			ret = -EINVAL;
4800 			goto out;
4801 		}
4802 
4803 		data->track_data.save_data = save_track_data_vars;
4804 		data->fn = ontrack_action;
4805 		data->action = ACTION_SAVE;
4806 	} else if (str_has_prefix(action_name, "snapshot")) {
4807 		char *params = strsep(&str, ")");
4808 
4809 		if (!str) {
4810 			hist_err(tr, HIST_ERR_NO_CLOSING_PAREN, errpos(params));
4811 			ret = -EINVAL;
4812 			goto out;
4813 		}
4814 
4815 		if (handler == HANDLER_ONMAX)
4816 			data->track_data.check_val = check_track_val_max;
4817 		else if (handler == HANDLER_ONCHANGE)
4818 			data->track_data.check_val = check_track_val_changed;
4819 		else {
4820 			hist_err(tr, HIST_ERR_ACTION_MISMATCH, errpos(action_name));
4821 			ret = -EINVAL;
4822 			goto out;
4823 		}
4824 
4825 		data->track_data.save_data = save_track_data_snapshot;
4826 		data->fn = ontrack_action;
4827 		data->action = ACTION_SNAPSHOT;
4828 	} else {
4829 		char *params = strsep(&str, ")");
4830 
4831 		if (str_has_prefix(action_name, "trace"))
4832 			data->use_trace_keyword = true;
4833 
4834 		if (params) {
4835 			ret = parse_action_params(tr, params, data);
4836 			if (ret)
4837 				goto out;
4838 		}
4839 
4840 		if (handler == HANDLER_ONMAX)
4841 			data->track_data.check_val = check_track_val_max;
4842 		else if (handler == HANDLER_ONCHANGE)
4843 			data->track_data.check_val = check_track_val_changed;
4844 
4845 		if (handler != HANDLER_ONMATCH) {
4846 			data->track_data.save_data = action_trace;
4847 			data->fn = ontrack_action;
4848 		} else
4849 			data->fn = action_trace;
4850 
4851 		data->action = ACTION_TRACE;
4852 	}
4853 
4854 	data->action_name = kstrdup(action_name, GFP_KERNEL);
4855 	if (!data->action_name) {
4856 		ret = -ENOMEM;
4857 		goto out;
4858 	}
4859 
4860 	data->handler = handler;
4861  out:
4862 	return ret;
4863 }
4864 
4865 static struct action_data *track_data_parse(struct hist_trigger_data *hist_data,
4866 					    char *str, enum handler_id handler)
4867 {
4868 	struct action_data *data;
4869 	int ret = -EINVAL;
4870 	char *var_str;
4871 
4872 	data = kzalloc(sizeof(*data), GFP_KERNEL);
4873 	if (!data)
4874 		return ERR_PTR(-ENOMEM);
4875 
4876 	var_str = strsep(&str, ")");
4877 	if (!var_str || !str) {
4878 		ret = -EINVAL;
4879 		goto free;
4880 	}
4881 
4882 	data->track_data.var_str = kstrdup(var_str, GFP_KERNEL);
4883 	if (!data->track_data.var_str) {
4884 		ret = -ENOMEM;
4885 		goto free;
4886 	}
4887 
4888 	ret = action_parse(hist_data->event_file->tr, str, data, handler);
4889 	if (ret)
4890 		goto free;
4891  out:
4892 	return data;
4893  free:
4894 	track_data_destroy(hist_data, data);
4895 	data = ERR_PTR(ret);
4896 	goto out;
4897 }
4898 
4899 static void onmatch_destroy(struct action_data *data)
4900 {
4901 	kfree(data->match_data.event);
4902 	kfree(data->match_data.event_system);
4903 
4904 	action_data_destroy(data);
4905 }
4906 
4907 static void destroy_field_var(struct field_var *field_var)
4908 {
4909 	if (!field_var)
4910 		return;
4911 
4912 	destroy_hist_field(field_var->var, 0);
4913 	destroy_hist_field(field_var->val, 0);
4914 
4915 	kfree(field_var);
4916 }
4917 
4918 static void destroy_field_vars(struct hist_trigger_data *hist_data)
4919 {
4920 	unsigned int i;
4921 
4922 	for (i = 0; i < hist_data->n_field_vars; i++)
4923 		destroy_field_var(hist_data->field_vars[i]);
4924 }
4925 
4926 static void save_field_var(struct hist_trigger_data *hist_data,
4927 			   struct field_var *field_var)
4928 {
4929 	hist_data->field_vars[hist_data->n_field_vars++] = field_var;
4930 
4931 	if (field_var->val->flags & HIST_FIELD_FL_STRING)
4932 		hist_data->n_field_var_str++;
4933 }
4934 
4935 
4936 static int check_synth_field(struct synth_event *event,
4937 			     struct hist_field *hist_field,
4938 			     unsigned int field_pos)
4939 {
4940 	struct synth_field *field;
4941 
4942 	if (field_pos >= event->n_fields)
4943 		return -EINVAL;
4944 
4945 	field = event->fields[field_pos];
4946 
4947 	if (strcmp(field->type, hist_field->type) != 0) {
4948 		if (field->size != hist_field->size ||
4949 		    field->is_signed != hist_field->is_signed)
4950 			return -EINVAL;
4951 	}
4952 
4953 	return 0;
4954 }
4955 
4956 static struct hist_field *
4957 trace_action_find_var(struct hist_trigger_data *hist_data,
4958 		      struct action_data *data,
4959 		      char *system, char *event, char *var)
4960 {
4961 	struct trace_array *tr = hist_data->event_file->tr;
4962 	struct hist_field *hist_field;
4963 
4964 	var++; /* skip '$' */
4965 
4966 	hist_field = find_target_event_var(hist_data, system, event, var);
4967 	if (!hist_field) {
4968 		if (!system && data->handler == HANDLER_ONMATCH) {
4969 			system = data->match_data.event_system;
4970 			event = data->match_data.event;
4971 		}
4972 
4973 		hist_field = find_event_var(hist_data, system, event, var);
4974 	}
4975 
4976 	if (!hist_field)
4977 		hist_err(tr, HIST_ERR_PARAM_NOT_FOUND, errpos(var));
4978 
4979 	return hist_field;
4980 }
4981 
4982 static struct hist_field *
4983 trace_action_create_field_var(struct hist_trigger_data *hist_data,
4984 			      struct action_data *data, char *system,
4985 			      char *event, char *var)
4986 {
4987 	struct hist_field *hist_field = NULL;
4988 	struct field_var *field_var;
4989 
4990 	/*
4991 	 * First try to create a field var on the target event (the
4992 	 * currently being defined).  This will create a variable for
4993 	 * unqualified fields on the target event, or if qualified,
4994 	 * target fields that have qualified names matching the target.
4995 	 */
4996 	field_var = create_target_field_var(hist_data, system, event, var);
4997 
4998 	if (field_var && !IS_ERR(field_var)) {
4999 		save_field_var(hist_data, field_var);
5000 		hist_field = field_var->var;
5001 	} else {
5002 		field_var = NULL;
5003 		/*
5004 		 * If no explicit system.event is specfied, default to
5005 		 * looking for fields on the onmatch(system.event.xxx)
5006 		 * event.
5007 		 */
5008 		if (!system && data->handler == HANDLER_ONMATCH) {
5009 			system = data->match_data.event_system;
5010 			event = data->match_data.event;
5011 		}
5012 
5013 		/*
5014 		 * At this point, we're looking at a field on another
5015 		 * event.  Because we can't modify a hist trigger on
5016 		 * another event to add a variable for a field, we need
5017 		 * to create a new trigger on that event and create the
5018 		 * variable at the same time.
5019 		 */
5020 		hist_field = create_field_var_hist(hist_data, system, event, var);
5021 		if (IS_ERR(hist_field))
5022 			goto free;
5023 	}
5024  out:
5025 	return hist_field;
5026  free:
5027 	destroy_field_var(field_var);
5028 	hist_field = NULL;
5029 	goto out;
5030 }
5031 
5032 static int trace_action_create(struct hist_trigger_data *hist_data,
5033 			       struct action_data *data)
5034 {
5035 	struct trace_array *tr = hist_data->event_file->tr;
5036 	char *event_name, *param, *system = NULL;
5037 	struct hist_field *hist_field, *var_ref;
5038 	unsigned int i;
5039 	unsigned int field_pos = 0;
5040 	struct synth_event *event;
5041 	char *synth_event_name;
5042 	int var_ref_idx, ret = 0;
5043 
5044 	lockdep_assert_held(&event_mutex);
5045 
5046 	if (data->use_trace_keyword)
5047 		synth_event_name = data->synth_event_name;
5048 	else
5049 		synth_event_name = data->action_name;
5050 
5051 	event = find_synth_event(synth_event_name);
5052 	if (!event) {
5053 		hist_err(tr, HIST_ERR_SYNTH_EVENT_NOT_FOUND, errpos(synth_event_name));
5054 		return -EINVAL;
5055 	}
5056 
5057 	event->ref++;
5058 
5059 	for (i = 0; i < data->n_params; i++) {
5060 		char *p;
5061 
5062 		p = param = kstrdup(data->params[i], GFP_KERNEL);
5063 		if (!param) {
5064 			ret = -ENOMEM;
5065 			goto err;
5066 		}
5067 
5068 		system = strsep(&param, ".");
5069 		if (!param) {
5070 			param = (char *)system;
5071 			system = event_name = NULL;
5072 		} else {
5073 			event_name = strsep(&param, ".");
5074 			if (!param) {
5075 				kfree(p);
5076 				ret = -EINVAL;
5077 				goto err;
5078 			}
5079 		}
5080 
5081 		if (param[0] == '$')
5082 			hist_field = trace_action_find_var(hist_data, data,
5083 							   system, event_name,
5084 							   param);
5085 		else
5086 			hist_field = trace_action_create_field_var(hist_data,
5087 								   data,
5088 								   system,
5089 								   event_name,
5090 								   param);
5091 
5092 		if (!hist_field) {
5093 			kfree(p);
5094 			ret = -EINVAL;
5095 			goto err;
5096 		}
5097 
5098 		if (check_synth_field(event, hist_field, field_pos) == 0) {
5099 			var_ref = create_var_ref(hist_data, hist_field,
5100 						 system, event_name);
5101 			if (!var_ref) {
5102 				kfree(p);
5103 				ret = -ENOMEM;
5104 				goto err;
5105 			}
5106 
5107 			var_ref_idx = find_var_ref_idx(hist_data, var_ref);
5108 			if (WARN_ON(var_ref_idx < 0)) {
5109 				ret = var_ref_idx;
5110 				goto err;
5111 			}
5112 
5113 			data->var_ref_idx[i] = var_ref_idx;
5114 
5115 			field_pos++;
5116 			kfree(p);
5117 			continue;
5118 		}
5119 
5120 		hist_err(tr, HIST_ERR_SYNTH_TYPE_MISMATCH, errpos(param));
5121 		kfree(p);
5122 		ret = -EINVAL;
5123 		goto err;
5124 	}
5125 
5126 	if (field_pos != event->n_fields) {
5127 		hist_err(tr, HIST_ERR_SYNTH_COUNT_MISMATCH, errpos(event->name));
5128 		ret = -EINVAL;
5129 		goto err;
5130 	}
5131 
5132 	data->synth_event = event;
5133  out:
5134 	return ret;
5135  err:
5136 	event->ref--;
5137 
5138 	goto out;
5139 }
5140 
5141 static int action_create(struct hist_trigger_data *hist_data,
5142 			 struct action_data *data)
5143 {
5144 	struct trace_event_file *file = hist_data->event_file;
5145 	struct trace_array *tr = file->tr;
5146 	struct track_data *track_data;
5147 	struct field_var *field_var;
5148 	unsigned int i;
5149 	char *param;
5150 	int ret = 0;
5151 
5152 	if (data->action == ACTION_TRACE)
5153 		return trace_action_create(hist_data, data);
5154 
5155 	if (data->action == ACTION_SNAPSHOT) {
5156 		track_data = track_data_alloc(hist_data->key_size, data, hist_data);
5157 		if (IS_ERR(track_data)) {
5158 			ret = PTR_ERR(track_data);
5159 			goto out;
5160 		}
5161 
5162 		ret = tracing_snapshot_cond_enable(file->tr, track_data,
5163 						   cond_snapshot_update);
5164 		if (ret)
5165 			track_data_free(track_data);
5166 
5167 		goto out;
5168 	}
5169 
5170 	if (data->action == ACTION_SAVE) {
5171 		if (hist_data->n_save_vars) {
5172 			ret = -EEXIST;
5173 			hist_err(tr, HIST_ERR_TOO_MANY_SAVE_ACTIONS, 0);
5174 			goto out;
5175 		}
5176 
5177 		for (i = 0; i < data->n_params; i++) {
5178 			param = kstrdup(data->params[i], GFP_KERNEL);
5179 			if (!param) {
5180 				ret = -ENOMEM;
5181 				goto out;
5182 			}
5183 
5184 			field_var = create_target_field_var(hist_data, NULL, NULL, param);
5185 			if (IS_ERR(field_var)) {
5186 				hist_err(tr, HIST_ERR_FIELD_VAR_CREATE_FAIL,
5187 					 errpos(param));
5188 				ret = PTR_ERR(field_var);
5189 				kfree(param);
5190 				goto out;
5191 			}
5192 
5193 			hist_data->save_vars[hist_data->n_save_vars++] = field_var;
5194 			if (field_var->val->flags & HIST_FIELD_FL_STRING)
5195 				hist_data->n_save_var_str++;
5196 			kfree(param);
5197 		}
5198 	}
5199  out:
5200 	return ret;
5201 }
5202 
5203 static int onmatch_create(struct hist_trigger_data *hist_data,
5204 			  struct action_data *data)
5205 {
5206 	return action_create(hist_data, data);
5207 }
5208 
5209 static struct action_data *onmatch_parse(struct trace_array *tr, char *str)
5210 {
5211 	char *match_event, *match_event_system;
5212 	struct action_data *data;
5213 	int ret = -EINVAL;
5214 
5215 	data = kzalloc(sizeof(*data), GFP_KERNEL);
5216 	if (!data)
5217 		return ERR_PTR(-ENOMEM);
5218 
5219 	match_event = strsep(&str, ")");
5220 	if (!match_event || !str) {
5221 		hist_err(tr, HIST_ERR_NO_CLOSING_PAREN, errpos(match_event));
5222 		goto free;
5223 	}
5224 
5225 	match_event_system = strsep(&match_event, ".");
5226 	if (!match_event) {
5227 		hist_err(tr, HIST_ERR_SUBSYS_NOT_FOUND, errpos(match_event_system));
5228 		goto free;
5229 	}
5230 
5231 	if (IS_ERR(event_file(tr, match_event_system, match_event))) {
5232 		hist_err(tr, HIST_ERR_INVALID_SUBSYS_EVENT, errpos(match_event));
5233 		goto free;
5234 	}
5235 
5236 	data->match_data.event = kstrdup(match_event, GFP_KERNEL);
5237 	if (!data->match_data.event) {
5238 		ret = -ENOMEM;
5239 		goto free;
5240 	}
5241 
5242 	data->match_data.event_system = kstrdup(match_event_system, GFP_KERNEL);
5243 	if (!data->match_data.event_system) {
5244 		ret = -ENOMEM;
5245 		goto free;
5246 	}
5247 
5248 	ret = action_parse(tr, str, data, HANDLER_ONMATCH);
5249 	if (ret)
5250 		goto free;
5251  out:
5252 	return data;
5253  free:
5254 	onmatch_destroy(data);
5255 	data = ERR_PTR(ret);
5256 	goto out;
5257 }
5258 
5259 static int create_hitcount_val(struct hist_trigger_data *hist_data)
5260 {
5261 	hist_data->fields[HITCOUNT_IDX] =
5262 		create_hist_field(hist_data, NULL, HIST_FIELD_FL_HITCOUNT, NULL);
5263 	if (!hist_data->fields[HITCOUNT_IDX])
5264 		return -ENOMEM;
5265 
5266 	hist_data->n_vals++;
5267 	hist_data->n_fields++;
5268 
5269 	if (WARN_ON(hist_data->n_vals > TRACING_MAP_VALS_MAX))
5270 		return -EINVAL;
5271 
5272 	return 0;
5273 }
5274 
5275 static int __create_val_field(struct hist_trigger_data *hist_data,
5276 			      unsigned int val_idx,
5277 			      struct trace_event_file *file,
5278 			      char *var_name, char *field_str,
5279 			      unsigned long flags)
5280 {
5281 	struct hist_field *hist_field;
5282 	int ret = 0;
5283 
5284 	hist_field = parse_expr(hist_data, file, field_str, flags, var_name, 0);
5285 	if (IS_ERR(hist_field)) {
5286 		ret = PTR_ERR(hist_field);
5287 		goto out;
5288 	}
5289 
5290 	hist_data->fields[val_idx] = hist_field;
5291 
5292 	++hist_data->n_vals;
5293 	++hist_data->n_fields;
5294 
5295 	if (WARN_ON(hist_data->n_vals > TRACING_MAP_VALS_MAX + TRACING_MAP_VARS_MAX))
5296 		ret = -EINVAL;
5297  out:
5298 	return ret;
5299 }
5300 
5301 static int create_val_field(struct hist_trigger_data *hist_data,
5302 			    unsigned int val_idx,
5303 			    struct trace_event_file *file,
5304 			    char *field_str)
5305 {
5306 	if (WARN_ON(val_idx >= TRACING_MAP_VALS_MAX))
5307 		return -EINVAL;
5308 
5309 	return __create_val_field(hist_data, val_idx, file, NULL, field_str, 0);
5310 }
5311 
5312 static int create_var_field(struct hist_trigger_data *hist_data,
5313 			    unsigned int val_idx,
5314 			    struct trace_event_file *file,
5315 			    char *var_name, char *expr_str)
5316 {
5317 	struct trace_array *tr = hist_data->event_file->tr;
5318 	unsigned long flags = 0;
5319 
5320 	if (WARN_ON(val_idx >= TRACING_MAP_VALS_MAX + TRACING_MAP_VARS_MAX))
5321 		return -EINVAL;
5322 
5323 	if (find_var(hist_data, file, var_name) && !hist_data->remove) {
5324 		hist_err(tr, HIST_ERR_DUPLICATE_VAR, errpos(var_name));
5325 		return -EINVAL;
5326 	}
5327 
5328 	flags |= HIST_FIELD_FL_VAR;
5329 	hist_data->n_vars++;
5330 	if (WARN_ON(hist_data->n_vars > TRACING_MAP_VARS_MAX))
5331 		return -EINVAL;
5332 
5333 	return __create_val_field(hist_data, val_idx, file, var_name, expr_str, flags);
5334 }
5335 
5336 static int create_val_fields(struct hist_trigger_data *hist_data,
5337 			     struct trace_event_file *file)
5338 {
5339 	char *fields_str, *field_str;
5340 	unsigned int i, j = 1;
5341 	int ret;
5342 
5343 	ret = create_hitcount_val(hist_data);
5344 	if (ret)
5345 		goto out;
5346 
5347 	fields_str = hist_data->attrs->vals_str;
5348 	if (!fields_str)
5349 		goto out;
5350 
5351 	for (i = 0, j = 1; i < TRACING_MAP_VALS_MAX &&
5352 		     j < TRACING_MAP_VALS_MAX; i++) {
5353 		field_str = strsep(&fields_str, ",");
5354 		if (!field_str)
5355 			break;
5356 
5357 		if (strcmp(field_str, "hitcount") == 0)
5358 			continue;
5359 
5360 		ret = create_val_field(hist_data, j++, file, field_str);
5361 		if (ret)
5362 			goto out;
5363 	}
5364 
5365 	if (fields_str && (strcmp(fields_str, "hitcount") != 0))
5366 		ret = -EINVAL;
5367  out:
5368 	return ret;
5369 }
5370 
5371 static int create_key_field(struct hist_trigger_data *hist_data,
5372 			    unsigned int key_idx,
5373 			    unsigned int key_offset,
5374 			    struct trace_event_file *file,
5375 			    char *field_str)
5376 {
5377 	struct trace_array *tr = hist_data->event_file->tr;
5378 	struct hist_field *hist_field = NULL;
5379 	unsigned long flags = 0;
5380 	unsigned int key_size;
5381 	int ret = 0;
5382 
5383 	if (WARN_ON(key_idx >= HIST_FIELDS_MAX))
5384 		return -EINVAL;
5385 
5386 	flags |= HIST_FIELD_FL_KEY;
5387 
5388 	if (strcmp(field_str, "stacktrace") == 0) {
5389 		flags |= HIST_FIELD_FL_STACKTRACE;
5390 		key_size = sizeof(unsigned long) * HIST_STACKTRACE_DEPTH;
5391 		hist_field = create_hist_field(hist_data, NULL, flags, NULL);
5392 	} else {
5393 		hist_field = parse_expr(hist_data, file, field_str, flags,
5394 					NULL, 0);
5395 		if (IS_ERR(hist_field)) {
5396 			ret = PTR_ERR(hist_field);
5397 			goto out;
5398 		}
5399 
5400 		if (field_has_hist_vars(hist_field, 0))	{
5401 			hist_err(tr, HIST_ERR_INVALID_REF_KEY, errpos(field_str));
5402 			destroy_hist_field(hist_field, 0);
5403 			ret = -EINVAL;
5404 			goto out;
5405 		}
5406 
5407 		key_size = hist_field->size;
5408 	}
5409 
5410 	hist_data->fields[key_idx] = hist_field;
5411 
5412 	key_size = ALIGN(key_size, sizeof(u64));
5413 	hist_data->fields[key_idx]->size = key_size;
5414 	hist_data->fields[key_idx]->offset = key_offset;
5415 
5416 	hist_data->key_size += key_size;
5417 
5418 	if (hist_data->key_size > HIST_KEY_SIZE_MAX) {
5419 		ret = -EINVAL;
5420 		goto out;
5421 	}
5422 
5423 	hist_data->n_keys++;
5424 	hist_data->n_fields++;
5425 
5426 	if (WARN_ON(hist_data->n_keys > TRACING_MAP_KEYS_MAX))
5427 		return -EINVAL;
5428 
5429 	ret = key_size;
5430  out:
5431 	return ret;
5432 }
5433 
5434 static int create_key_fields(struct hist_trigger_data *hist_data,
5435 			     struct trace_event_file *file)
5436 {
5437 	unsigned int i, key_offset = 0, n_vals = hist_data->n_vals;
5438 	char *fields_str, *field_str;
5439 	int ret = -EINVAL;
5440 
5441 	fields_str = hist_data->attrs->keys_str;
5442 	if (!fields_str)
5443 		goto out;
5444 
5445 	for (i = n_vals; i < n_vals + TRACING_MAP_KEYS_MAX; i++) {
5446 		field_str = strsep(&fields_str, ",");
5447 		if (!field_str)
5448 			break;
5449 		ret = create_key_field(hist_data, i, key_offset,
5450 				       file, field_str);
5451 		if (ret < 0)
5452 			goto out;
5453 		key_offset += ret;
5454 	}
5455 	if (fields_str) {
5456 		ret = -EINVAL;
5457 		goto out;
5458 	}
5459 	ret = 0;
5460  out:
5461 	return ret;
5462 }
5463 
5464 static int create_var_fields(struct hist_trigger_data *hist_data,
5465 			     struct trace_event_file *file)
5466 {
5467 	unsigned int i, j = hist_data->n_vals;
5468 	int ret = 0;
5469 
5470 	unsigned int n_vars = hist_data->attrs->var_defs.n_vars;
5471 
5472 	for (i = 0; i < n_vars; i++) {
5473 		char *var_name = hist_data->attrs->var_defs.name[i];
5474 		char *expr = hist_data->attrs->var_defs.expr[i];
5475 
5476 		ret = create_var_field(hist_data, j++, file, var_name, expr);
5477 		if (ret)
5478 			goto out;
5479 	}
5480  out:
5481 	return ret;
5482 }
5483 
5484 static void free_var_defs(struct hist_trigger_data *hist_data)
5485 {
5486 	unsigned int i;
5487 
5488 	for (i = 0; i < hist_data->attrs->var_defs.n_vars; i++) {
5489 		kfree(hist_data->attrs->var_defs.name[i]);
5490 		kfree(hist_data->attrs->var_defs.expr[i]);
5491 	}
5492 
5493 	hist_data->attrs->var_defs.n_vars = 0;
5494 }
5495 
5496 static int parse_var_defs(struct hist_trigger_data *hist_data)
5497 {
5498 	struct trace_array *tr = hist_data->event_file->tr;
5499 	char *s, *str, *var_name, *field_str;
5500 	unsigned int i, j, n_vars = 0;
5501 	int ret = 0;
5502 
5503 	for (i = 0; i < hist_data->attrs->n_assignments; i++) {
5504 		str = hist_data->attrs->assignment_str[i];
5505 		for (j = 0; j < TRACING_MAP_VARS_MAX; j++) {
5506 			field_str = strsep(&str, ",");
5507 			if (!field_str)
5508 				break;
5509 
5510 			var_name = strsep(&field_str, "=");
5511 			if (!var_name || !field_str) {
5512 				hist_err(tr, HIST_ERR_MALFORMED_ASSIGNMENT,
5513 					 errpos(var_name));
5514 				ret = -EINVAL;
5515 				goto free;
5516 			}
5517 
5518 			if (n_vars == TRACING_MAP_VARS_MAX) {
5519 				hist_err(tr, HIST_ERR_TOO_MANY_VARS, errpos(var_name));
5520 				ret = -EINVAL;
5521 				goto free;
5522 			}
5523 
5524 			s = kstrdup(var_name, GFP_KERNEL);
5525 			if (!s) {
5526 				ret = -ENOMEM;
5527 				goto free;
5528 			}
5529 			hist_data->attrs->var_defs.name[n_vars] = s;
5530 
5531 			s = kstrdup(field_str, GFP_KERNEL);
5532 			if (!s) {
5533 				kfree(hist_data->attrs->var_defs.name[n_vars]);
5534 				ret = -ENOMEM;
5535 				goto free;
5536 			}
5537 			hist_data->attrs->var_defs.expr[n_vars++] = s;
5538 
5539 			hist_data->attrs->var_defs.n_vars = n_vars;
5540 		}
5541 	}
5542 
5543 	return ret;
5544  free:
5545 	free_var_defs(hist_data);
5546 
5547 	return ret;
5548 }
5549 
5550 static int create_hist_fields(struct hist_trigger_data *hist_data,
5551 			      struct trace_event_file *file)
5552 {
5553 	int ret;
5554 
5555 	ret = parse_var_defs(hist_data);
5556 	if (ret)
5557 		goto out;
5558 
5559 	ret = create_val_fields(hist_data, file);
5560 	if (ret)
5561 		goto out;
5562 
5563 	ret = create_var_fields(hist_data, file);
5564 	if (ret)
5565 		goto out;
5566 
5567 	ret = create_key_fields(hist_data, file);
5568 	if (ret)
5569 		goto out;
5570  out:
5571 	free_var_defs(hist_data);
5572 
5573 	return ret;
5574 }
5575 
5576 static int is_descending(struct trace_array *tr, const char *str)
5577 {
5578 	if (!str)
5579 		return 0;
5580 
5581 	if (strcmp(str, "descending") == 0)
5582 		return 1;
5583 
5584 	if (strcmp(str, "ascending") == 0)
5585 		return 0;
5586 
5587 	hist_err(tr, HIST_ERR_INVALID_SORT_MODIFIER, errpos((char *)str));
5588 
5589 	return -EINVAL;
5590 }
5591 
5592 static int create_sort_keys(struct hist_trigger_data *hist_data)
5593 {
5594 	struct trace_array *tr = hist_data->event_file->tr;
5595 	char *fields_str = hist_data->attrs->sort_key_str;
5596 	struct tracing_map_sort_key *sort_key;
5597 	int descending, ret = 0;
5598 	unsigned int i, j, k;
5599 
5600 	hist_data->n_sort_keys = 1; /* we always have at least one, hitcount */
5601 
5602 	if (!fields_str)
5603 		goto out;
5604 
5605 	for (i = 0; i < TRACING_MAP_SORT_KEYS_MAX; i++) {
5606 		struct hist_field *hist_field;
5607 		char *field_str, *field_name;
5608 		const char *test_name;
5609 
5610 		sort_key = &hist_data->sort_keys[i];
5611 
5612 		field_str = strsep(&fields_str, ",");
5613 		if (!field_str)
5614 			break;
5615 
5616 		if (!*field_str) {
5617 			ret = -EINVAL;
5618 			hist_err(tr, HIST_ERR_EMPTY_SORT_FIELD, errpos("sort="));
5619 			break;
5620 		}
5621 
5622 		if ((i == TRACING_MAP_SORT_KEYS_MAX - 1) && fields_str) {
5623 			hist_err(tr, HIST_ERR_TOO_MANY_SORT_FIELDS, errpos("sort="));
5624 			ret = -EINVAL;
5625 			break;
5626 		}
5627 
5628 		field_name = strsep(&field_str, ".");
5629 		if (!field_name || !*field_name) {
5630 			ret = -EINVAL;
5631 			hist_err(tr, HIST_ERR_EMPTY_SORT_FIELD, errpos("sort="));
5632 			break;
5633 		}
5634 
5635 		if (strcmp(field_name, "hitcount") == 0) {
5636 			descending = is_descending(tr, field_str);
5637 			if (descending < 0) {
5638 				ret = descending;
5639 				break;
5640 			}
5641 			sort_key->descending = descending;
5642 			continue;
5643 		}
5644 
5645 		for (j = 1, k = 1; j < hist_data->n_fields; j++) {
5646 			unsigned int idx;
5647 
5648 			hist_field = hist_data->fields[j];
5649 			if (hist_field->flags & HIST_FIELD_FL_VAR)
5650 				continue;
5651 
5652 			idx = k++;
5653 
5654 			test_name = hist_field_name(hist_field, 0);
5655 
5656 			if (strcmp(field_name, test_name) == 0) {
5657 				sort_key->field_idx = idx;
5658 				descending = is_descending(tr, field_str);
5659 				if (descending < 0) {
5660 					ret = descending;
5661 					goto out;
5662 				}
5663 				sort_key->descending = descending;
5664 				break;
5665 			}
5666 		}
5667 		if (j == hist_data->n_fields) {
5668 			ret = -EINVAL;
5669 			hist_err(tr, HIST_ERR_INVALID_SORT_FIELD, errpos(field_name));
5670 			break;
5671 		}
5672 	}
5673 
5674 	hist_data->n_sort_keys = i;
5675  out:
5676 	return ret;
5677 }
5678 
5679 static void destroy_actions(struct hist_trigger_data *hist_data)
5680 {
5681 	unsigned int i;
5682 
5683 	for (i = 0; i < hist_data->n_actions; i++) {
5684 		struct action_data *data = hist_data->actions[i];
5685 
5686 		if (data->handler == HANDLER_ONMATCH)
5687 			onmatch_destroy(data);
5688 		else if (data->handler == HANDLER_ONMAX ||
5689 			 data->handler == HANDLER_ONCHANGE)
5690 			track_data_destroy(hist_data, data);
5691 		else
5692 			kfree(data);
5693 	}
5694 }
5695 
5696 static int parse_actions(struct hist_trigger_data *hist_data)
5697 {
5698 	struct trace_array *tr = hist_data->event_file->tr;
5699 	struct action_data *data;
5700 	unsigned int i;
5701 	int ret = 0;
5702 	char *str;
5703 	int len;
5704 
5705 	for (i = 0; i < hist_data->attrs->n_actions; i++) {
5706 		str = hist_data->attrs->action_str[i];
5707 
5708 		if ((len = str_has_prefix(str, "onmatch("))) {
5709 			char *action_str = str + len;
5710 
5711 			data = onmatch_parse(tr, action_str);
5712 			if (IS_ERR(data)) {
5713 				ret = PTR_ERR(data);
5714 				break;
5715 			}
5716 		} else if ((len = str_has_prefix(str, "onmax("))) {
5717 			char *action_str = str + len;
5718 
5719 			data = track_data_parse(hist_data, action_str,
5720 						HANDLER_ONMAX);
5721 			if (IS_ERR(data)) {
5722 				ret = PTR_ERR(data);
5723 				break;
5724 			}
5725 		} else if ((len = str_has_prefix(str, "onchange("))) {
5726 			char *action_str = str + len;
5727 
5728 			data = track_data_parse(hist_data, action_str,
5729 						HANDLER_ONCHANGE);
5730 			if (IS_ERR(data)) {
5731 				ret = PTR_ERR(data);
5732 				break;
5733 			}
5734 		} else {
5735 			ret = -EINVAL;
5736 			break;
5737 		}
5738 
5739 		hist_data->actions[hist_data->n_actions++] = data;
5740 	}
5741 
5742 	return ret;
5743 }
5744 
5745 static int create_actions(struct hist_trigger_data *hist_data)
5746 {
5747 	struct action_data *data;
5748 	unsigned int i;
5749 	int ret = 0;
5750 
5751 	for (i = 0; i < hist_data->attrs->n_actions; i++) {
5752 		data = hist_data->actions[i];
5753 
5754 		if (data->handler == HANDLER_ONMATCH) {
5755 			ret = onmatch_create(hist_data, data);
5756 			if (ret)
5757 				break;
5758 		} else if (data->handler == HANDLER_ONMAX ||
5759 			   data->handler == HANDLER_ONCHANGE) {
5760 			ret = track_data_create(hist_data, data);
5761 			if (ret)
5762 				break;
5763 		} else {
5764 			ret = -EINVAL;
5765 			break;
5766 		}
5767 	}
5768 
5769 	return ret;
5770 }
5771 
5772 static void print_actions(struct seq_file *m,
5773 			  struct hist_trigger_data *hist_data,
5774 			  struct tracing_map_elt *elt)
5775 {
5776 	unsigned int i;
5777 
5778 	for (i = 0; i < hist_data->n_actions; i++) {
5779 		struct action_data *data = hist_data->actions[i];
5780 
5781 		if (data->action == ACTION_SNAPSHOT)
5782 			continue;
5783 
5784 		if (data->handler == HANDLER_ONMAX ||
5785 		    data->handler == HANDLER_ONCHANGE)
5786 			track_data_print(m, hist_data, elt, data);
5787 	}
5788 }
5789 
5790 static void print_action_spec(struct seq_file *m,
5791 			      struct hist_trigger_data *hist_data,
5792 			      struct action_data *data)
5793 {
5794 	unsigned int i;
5795 
5796 	if (data->action == ACTION_SAVE) {
5797 		for (i = 0; i < hist_data->n_save_vars; i++) {
5798 			seq_printf(m, "%s", hist_data->save_vars[i]->var->var.name);
5799 			if (i < hist_data->n_save_vars - 1)
5800 				seq_puts(m, ",");
5801 		}
5802 	} else if (data->action == ACTION_TRACE) {
5803 		if (data->use_trace_keyword)
5804 			seq_printf(m, "%s", data->synth_event_name);
5805 		for (i = 0; i < data->n_params; i++) {
5806 			if (i || data->use_trace_keyword)
5807 				seq_puts(m, ",");
5808 			seq_printf(m, "%s", data->params[i]);
5809 		}
5810 	}
5811 }
5812 
5813 static void print_track_data_spec(struct seq_file *m,
5814 				  struct hist_trigger_data *hist_data,
5815 				  struct action_data *data)
5816 {
5817 	if (data->handler == HANDLER_ONMAX)
5818 		seq_puts(m, ":onmax(");
5819 	else if (data->handler == HANDLER_ONCHANGE)
5820 		seq_puts(m, ":onchange(");
5821 	seq_printf(m, "%s", data->track_data.var_str);
5822 	seq_printf(m, ").%s(", data->action_name);
5823 
5824 	print_action_spec(m, hist_data, data);
5825 
5826 	seq_puts(m, ")");
5827 }
5828 
5829 static void print_onmatch_spec(struct seq_file *m,
5830 			       struct hist_trigger_data *hist_data,
5831 			       struct action_data *data)
5832 {
5833 	seq_printf(m, ":onmatch(%s.%s).", data->match_data.event_system,
5834 		   data->match_data.event);
5835 
5836 	seq_printf(m, "%s(", data->action_name);
5837 
5838 	print_action_spec(m, hist_data, data);
5839 
5840 	seq_puts(m, ")");
5841 }
5842 
5843 static bool actions_match(struct hist_trigger_data *hist_data,
5844 			  struct hist_trigger_data *hist_data_test)
5845 {
5846 	unsigned int i, j;
5847 
5848 	if (hist_data->n_actions != hist_data_test->n_actions)
5849 		return false;
5850 
5851 	for (i = 0; i < hist_data->n_actions; i++) {
5852 		struct action_data *data = hist_data->actions[i];
5853 		struct action_data *data_test = hist_data_test->actions[i];
5854 		char *action_name, *action_name_test;
5855 
5856 		if (data->handler != data_test->handler)
5857 			return false;
5858 		if (data->action != data_test->action)
5859 			return false;
5860 
5861 		if (data->n_params != data_test->n_params)
5862 			return false;
5863 
5864 		for (j = 0; j < data->n_params; j++) {
5865 			if (strcmp(data->params[j], data_test->params[j]) != 0)
5866 				return false;
5867 		}
5868 
5869 		if (data->use_trace_keyword)
5870 			action_name = data->synth_event_name;
5871 		else
5872 			action_name = data->action_name;
5873 
5874 		if (data_test->use_trace_keyword)
5875 			action_name_test = data_test->synth_event_name;
5876 		else
5877 			action_name_test = data_test->action_name;
5878 
5879 		if (strcmp(action_name, action_name_test) != 0)
5880 			return false;
5881 
5882 		if (data->handler == HANDLER_ONMATCH) {
5883 			if (strcmp(data->match_data.event_system,
5884 				   data_test->match_data.event_system) != 0)
5885 				return false;
5886 			if (strcmp(data->match_data.event,
5887 				   data_test->match_data.event) != 0)
5888 				return false;
5889 		} else if (data->handler == HANDLER_ONMAX ||
5890 			   data->handler == HANDLER_ONCHANGE) {
5891 			if (strcmp(data->track_data.var_str,
5892 				   data_test->track_data.var_str) != 0)
5893 				return false;
5894 		}
5895 	}
5896 
5897 	return true;
5898 }
5899 
5900 
5901 static void print_actions_spec(struct seq_file *m,
5902 			       struct hist_trigger_data *hist_data)
5903 {
5904 	unsigned int i;
5905 
5906 	for (i = 0; i < hist_data->n_actions; i++) {
5907 		struct action_data *data = hist_data->actions[i];
5908 
5909 		if (data->handler == HANDLER_ONMATCH)
5910 			print_onmatch_spec(m, hist_data, data);
5911 		else if (data->handler == HANDLER_ONMAX ||
5912 			 data->handler == HANDLER_ONCHANGE)
5913 			print_track_data_spec(m, hist_data, data);
5914 	}
5915 }
5916 
5917 static void destroy_field_var_hists(struct hist_trigger_data *hist_data)
5918 {
5919 	unsigned int i;
5920 
5921 	for (i = 0; i < hist_data->n_field_var_hists; i++) {
5922 		kfree(hist_data->field_var_hists[i]->cmd);
5923 		kfree(hist_data->field_var_hists[i]);
5924 	}
5925 }
5926 
5927 static void destroy_hist_data(struct hist_trigger_data *hist_data)
5928 {
5929 	if (!hist_data)
5930 		return;
5931 
5932 	destroy_hist_trigger_attrs(hist_data->attrs);
5933 	destroy_hist_fields(hist_data);
5934 	tracing_map_destroy(hist_data->map);
5935 
5936 	destroy_actions(hist_data);
5937 	destroy_field_vars(hist_data);
5938 	destroy_field_var_hists(hist_data);
5939 
5940 	kfree(hist_data);
5941 }
5942 
5943 static int create_tracing_map_fields(struct hist_trigger_data *hist_data)
5944 {
5945 	struct tracing_map *map = hist_data->map;
5946 	struct ftrace_event_field *field;
5947 	struct hist_field *hist_field;
5948 	int i, idx = 0;
5949 
5950 	for_each_hist_field(i, hist_data) {
5951 		hist_field = hist_data->fields[i];
5952 		if (hist_field->flags & HIST_FIELD_FL_KEY) {
5953 			tracing_map_cmp_fn_t cmp_fn;
5954 
5955 			field = hist_field->field;
5956 
5957 			if (hist_field->flags & HIST_FIELD_FL_STACKTRACE)
5958 				cmp_fn = tracing_map_cmp_none;
5959 			else if (!field)
5960 				cmp_fn = tracing_map_cmp_num(hist_field->size,
5961 							     hist_field->is_signed);
5962 			else if (is_string_field(field))
5963 				cmp_fn = tracing_map_cmp_string;
5964 			else
5965 				cmp_fn = tracing_map_cmp_num(field->size,
5966 							     field->is_signed);
5967 			idx = tracing_map_add_key_field(map,
5968 							hist_field->offset,
5969 							cmp_fn);
5970 		} else if (!(hist_field->flags & HIST_FIELD_FL_VAR))
5971 			idx = tracing_map_add_sum_field(map);
5972 
5973 		if (idx < 0)
5974 			return idx;
5975 
5976 		if (hist_field->flags & HIST_FIELD_FL_VAR) {
5977 			idx = tracing_map_add_var(map);
5978 			if (idx < 0)
5979 				return idx;
5980 			hist_field->var.idx = idx;
5981 			hist_field->var.hist_data = hist_data;
5982 		}
5983 	}
5984 
5985 	return 0;
5986 }
5987 
5988 static struct hist_trigger_data *
5989 create_hist_data(unsigned int map_bits,
5990 		 struct hist_trigger_attrs *attrs,
5991 		 struct trace_event_file *file,
5992 		 bool remove)
5993 {
5994 	const struct tracing_map_ops *map_ops = NULL;
5995 	struct hist_trigger_data *hist_data;
5996 	int ret = 0;
5997 
5998 	hist_data = kzalloc(sizeof(*hist_data), GFP_KERNEL);
5999 	if (!hist_data)
6000 		return ERR_PTR(-ENOMEM);
6001 
6002 	hist_data->attrs = attrs;
6003 	hist_data->remove = remove;
6004 	hist_data->event_file = file;
6005 
6006 	ret = parse_actions(hist_data);
6007 	if (ret)
6008 		goto free;
6009 
6010 	ret = create_hist_fields(hist_data, file);
6011 	if (ret)
6012 		goto free;
6013 
6014 	ret = create_sort_keys(hist_data);
6015 	if (ret)
6016 		goto free;
6017 
6018 	map_ops = &hist_trigger_elt_data_ops;
6019 
6020 	hist_data->map = tracing_map_create(map_bits, hist_data->key_size,
6021 					    map_ops, hist_data);
6022 	if (IS_ERR(hist_data->map)) {
6023 		ret = PTR_ERR(hist_data->map);
6024 		hist_data->map = NULL;
6025 		goto free;
6026 	}
6027 
6028 	ret = create_tracing_map_fields(hist_data);
6029 	if (ret)
6030 		goto free;
6031  out:
6032 	return hist_data;
6033  free:
6034 	hist_data->attrs = NULL;
6035 
6036 	destroy_hist_data(hist_data);
6037 
6038 	hist_data = ERR_PTR(ret);
6039 
6040 	goto out;
6041 }
6042 
6043 static void hist_trigger_elt_update(struct hist_trigger_data *hist_data,
6044 				    struct tracing_map_elt *elt, void *rec,
6045 				    struct ring_buffer_event *rbe,
6046 				    u64 *var_ref_vals)
6047 {
6048 	struct hist_elt_data *elt_data;
6049 	struct hist_field *hist_field;
6050 	unsigned int i, var_idx;
6051 	u64 hist_val;
6052 
6053 	elt_data = elt->private_data;
6054 	elt_data->var_ref_vals = var_ref_vals;
6055 
6056 	for_each_hist_val_field(i, hist_data) {
6057 		hist_field = hist_data->fields[i];
6058 		hist_val = hist_field->fn(hist_field, elt, rbe, rec);
6059 		if (hist_field->flags & HIST_FIELD_FL_VAR) {
6060 			var_idx = hist_field->var.idx;
6061 			tracing_map_set_var(elt, var_idx, hist_val);
6062 			continue;
6063 		}
6064 		tracing_map_update_sum(elt, i, hist_val);
6065 	}
6066 
6067 	for_each_hist_key_field(i, hist_data) {
6068 		hist_field = hist_data->fields[i];
6069 		if (hist_field->flags & HIST_FIELD_FL_VAR) {
6070 			hist_val = hist_field->fn(hist_field, elt, rbe, rec);
6071 			var_idx = hist_field->var.idx;
6072 			tracing_map_set_var(elt, var_idx, hist_val);
6073 		}
6074 	}
6075 
6076 	update_field_vars(hist_data, elt, rbe, rec);
6077 }
6078 
6079 static inline void add_to_key(char *compound_key, void *key,
6080 			      struct hist_field *key_field, void *rec)
6081 {
6082 	size_t size = key_field->size;
6083 
6084 	if (key_field->flags & HIST_FIELD_FL_STRING) {
6085 		struct ftrace_event_field *field;
6086 
6087 		field = key_field->field;
6088 		if (field->filter_type == FILTER_DYN_STRING)
6089 			size = *(u32 *)(rec + field->offset) >> 16;
6090 		else if (field->filter_type == FILTER_PTR_STRING)
6091 			size = strlen(key);
6092 		else if (field->filter_type == FILTER_STATIC_STRING)
6093 			size = field->size;
6094 
6095 		/* ensure NULL-termination */
6096 		if (size > key_field->size - 1)
6097 			size = key_field->size - 1;
6098 
6099 		strncpy(compound_key + key_field->offset, (char *)key, size);
6100 	} else
6101 		memcpy(compound_key + key_field->offset, key, size);
6102 }
6103 
6104 static void
6105 hist_trigger_actions(struct hist_trigger_data *hist_data,
6106 		     struct tracing_map_elt *elt, void *rec,
6107 		     struct ring_buffer_event *rbe, void *key,
6108 		     u64 *var_ref_vals)
6109 {
6110 	struct action_data *data;
6111 	unsigned int i;
6112 
6113 	for (i = 0; i < hist_data->n_actions; i++) {
6114 		data = hist_data->actions[i];
6115 		data->fn(hist_data, elt, rec, rbe, key, data, var_ref_vals);
6116 	}
6117 }
6118 
6119 static void event_hist_trigger(struct event_trigger_data *data, void *rec,
6120 			       struct ring_buffer_event *rbe)
6121 {
6122 	struct hist_trigger_data *hist_data = data->private_data;
6123 	bool use_compound_key = (hist_data->n_keys > 1);
6124 	unsigned long entries[HIST_STACKTRACE_DEPTH];
6125 	u64 var_ref_vals[TRACING_MAP_VARS_MAX];
6126 	char compound_key[HIST_KEY_SIZE_MAX];
6127 	struct tracing_map_elt *elt = NULL;
6128 	struct hist_field *key_field;
6129 	u64 field_contents;
6130 	void *key = NULL;
6131 	unsigned int i;
6132 
6133 	memset(compound_key, 0, hist_data->key_size);
6134 
6135 	for_each_hist_key_field(i, hist_data) {
6136 		key_field = hist_data->fields[i];
6137 
6138 		if (key_field->flags & HIST_FIELD_FL_STACKTRACE) {
6139 			memset(entries, 0, HIST_STACKTRACE_SIZE);
6140 			stack_trace_save(entries, HIST_STACKTRACE_DEPTH,
6141 					 HIST_STACKTRACE_SKIP);
6142 			key = entries;
6143 		} else {
6144 			field_contents = key_field->fn(key_field, elt, rbe, rec);
6145 			if (key_field->flags & HIST_FIELD_FL_STRING) {
6146 				key = (void *)(unsigned long)field_contents;
6147 				use_compound_key = true;
6148 			} else
6149 				key = (void *)&field_contents;
6150 		}
6151 
6152 		if (use_compound_key)
6153 			add_to_key(compound_key, key, key_field, rec);
6154 	}
6155 
6156 	if (use_compound_key)
6157 		key = compound_key;
6158 
6159 	if (hist_data->n_var_refs &&
6160 	    !resolve_var_refs(hist_data, key, var_ref_vals, false))
6161 		return;
6162 
6163 	elt = tracing_map_insert(hist_data->map, key);
6164 	if (!elt)
6165 		return;
6166 
6167 	hist_trigger_elt_update(hist_data, elt, rec, rbe, var_ref_vals);
6168 
6169 	if (resolve_var_refs(hist_data, key, var_ref_vals, true))
6170 		hist_trigger_actions(hist_data, elt, rec, rbe, key, var_ref_vals);
6171 }
6172 
6173 static void hist_trigger_stacktrace_print(struct seq_file *m,
6174 					  unsigned long *stacktrace_entries,
6175 					  unsigned int max_entries)
6176 {
6177 	char str[KSYM_SYMBOL_LEN];
6178 	unsigned int spaces = 8;
6179 	unsigned int i;
6180 
6181 	for (i = 0; i < max_entries; i++) {
6182 		if (!stacktrace_entries[i])
6183 			return;
6184 
6185 		seq_printf(m, "%*c", 1 + spaces, ' ');
6186 		sprint_symbol(str, stacktrace_entries[i]);
6187 		seq_printf(m, "%s\n", str);
6188 	}
6189 }
6190 
6191 static void hist_trigger_print_key(struct seq_file *m,
6192 				   struct hist_trigger_data *hist_data,
6193 				   void *key,
6194 				   struct tracing_map_elt *elt)
6195 {
6196 	struct hist_field *key_field;
6197 	char str[KSYM_SYMBOL_LEN];
6198 	bool multiline = false;
6199 	const char *field_name;
6200 	unsigned int i;
6201 	u64 uval;
6202 
6203 	seq_puts(m, "{ ");
6204 
6205 	for_each_hist_key_field(i, hist_data) {
6206 		key_field = hist_data->fields[i];
6207 
6208 		if (i > hist_data->n_vals)
6209 			seq_puts(m, ", ");
6210 
6211 		field_name = hist_field_name(key_field, 0);
6212 
6213 		if (key_field->flags & HIST_FIELD_FL_HEX) {
6214 			uval = *(u64 *)(key + key_field->offset);
6215 			seq_printf(m, "%s: %llx", field_name, uval);
6216 		} else if (key_field->flags & HIST_FIELD_FL_SYM) {
6217 			uval = *(u64 *)(key + key_field->offset);
6218 			sprint_symbol_no_offset(str, uval);
6219 			seq_printf(m, "%s: [%llx] %-45s", field_name,
6220 				   uval, str);
6221 		} else if (key_field->flags & HIST_FIELD_FL_SYM_OFFSET) {
6222 			uval = *(u64 *)(key + key_field->offset);
6223 			sprint_symbol(str, uval);
6224 			seq_printf(m, "%s: [%llx] %-55s", field_name,
6225 				   uval, str);
6226 		} else if (key_field->flags & HIST_FIELD_FL_EXECNAME) {
6227 			struct hist_elt_data *elt_data = elt->private_data;
6228 			char *comm;
6229 
6230 			if (WARN_ON_ONCE(!elt_data))
6231 				return;
6232 
6233 			comm = elt_data->comm;
6234 
6235 			uval = *(u64 *)(key + key_field->offset);
6236 			seq_printf(m, "%s: %-16s[%10llu]", field_name,
6237 				   comm, uval);
6238 		} else if (key_field->flags & HIST_FIELD_FL_SYSCALL) {
6239 			const char *syscall_name;
6240 
6241 			uval = *(u64 *)(key + key_field->offset);
6242 			syscall_name = get_syscall_name(uval);
6243 			if (!syscall_name)
6244 				syscall_name = "unknown_syscall";
6245 
6246 			seq_printf(m, "%s: %-30s[%3llu]", field_name,
6247 				   syscall_name, uval);
6248 		} else if (key_field->flags & HIST_FIELD_FL_STACKTRACE) {
6249 			seq_puts(m, "stacktrace:\n");
6250 			hist_trigger_stacktrace_print(m,
6251 						      key + key_field->offset,
6252 						      HIST_STACKTRACE_DEPTH);
6253 			multiline = true;
6254 		} else if (key_field->flags & HIST_FIELD_FL_LOG2) {
6255 			seq_printf(m, "%s: ~ 2^%-2llu", field_name,
6256 				   *(u64 *)(key + key_field->offset));
6257 		} else if (key_field->flags & HIST_FIELD_FL_STRING) {
6258 			seq_printf(m, "%s: %-50s", field_name,
6259 				   (char *)(key + key_field->offset));
6260 		} else {
6261 			uval = *(u64 *)(key + key_field->offset);
6262 			seq_printf(m, "%s: %10llu", field_name, uval);
6263 		}
6264 	}
6265 
6266 	if (!multiline)
6267 		seq_puts(m, " ");
6268 
6269 	seq_puts(m, "}");
6270 }
6271 
6272 static void hist_trigger_entry_print(struct seq_file *m,
6273 				     struct hist_trigger_data *hist_data,
6274 				     void *key,
6275 				     struct tracing_map_elt *elt)
6276 {
6277 	const char *field_name;
6278 	unsigned int i;
6279 
6280 	hist_trigger_print_key(m, hist_data, key, elt);
6281 
6282 	seq_printf(m, " hitcount: %10llu",
6283 		   tracing_map_read_sum(elt, HITCOUNT_IDX));
6284 
6285 	for (i = 1; i < hist_data->n_vals; i++) {
6286 		field_name = hist_field_name(hist_data->fields[i], 0);
6287 
6288 		if (hist_data->fields[i]->flags & HIST_FIELD_FL_VAR ||
6289 		    hist_data->fields[i]->flags & HIST_FIELD_FL_EXPR)
6290 			continue;
6291 
6292 		if (hist_data->fields[i]->flags & HIST_FIELD_FL_HEX) {
6293 			seq_printf(m, "  %s: %10llx", field_name,
6294 				   tracing_map_read_sum(elt, i));
6295 		} else {
6296 			seq_printf(m, "  %s: %10llu", field_name,
6297 				   tracing_map_read_sum(elt, i));
6298 		}
6299 	}
6300 
6301 	print_actions(m, hist_data, elt);
6302 
6303 	seq_puts(m, "\n");
6304 }
6305 
6306 static int print_entries(struct seq_file *m,
6307 			 struct hist_trigger_data *hist_data)
6308 {
6309 	struct tracing_map_sort_entry **sort_entries = NULL;
6310 	struct tracing_map *map = hist_data->map;
6311 	int i, n_entries;
6312 
6313 	n_entries = tracing_map_sort_entries(map, hist_data->sort_keys,
6314 					     hist_data->n_sort_keys,
6315 					     &sort_entries);
6316 	if (n_entries < 0)
6317 		return n_entries;
6318 
6319 	for (i = 0; i < n_entries; i++)
6320 		hist_trigger_entry_print(m, hist_data,
6321 					 sort_entries[i]->key,
6322 					 sort_entries[i]->elt);
6323 
6324 	tracing_map_destroy_sort_entries(sort_entries, n_entries);
6325 
6326 	return n_entries;
6327 }
6328 
6329 static void hist_trigger_show(struct seq_file *m,
6330 			      struct event_trigger_data *data, int n)
6331 {
6332 	struct hist_trigger_data *hist_data;
6333 	int n_entries;
6334 
6335 	if (n > 0)
6336 		seq_puts(m, "\n\n");
6337 
6338 	seq_puts(m, "# event histogram\n#\n# trigger info: ");
6339 	data->ops->print(m, data->ops, data);
6340 	seq_puts(m, "#\n\n");
6341 
6342 	hist_data = data->private_data;
6343 	n_entries = print_entries(m, hist_data);
6344 	if (n_entries < 0)
6345 		n_entries = 0;
6346 
6347 	track_data_snapshot_print(m, hist_data);
6348 
6349 	seq_printf(m, "\nTotals:\n    Hits: %llu\n    Entries: %u\n    Dropped: %llu\n",
6350 		   (u64)atomic64_read(&hist_data->map->hits),
6351 		   n_entries, (u64)atomic64_read(&hist_data->map->drops));
6352 }
6353 
6354 static int hist_show(struct seq_file *m, void *v)
6355 {
6356 	struct event_trigger_data *data;
6357 	struct trace_event_file *event_file;
6358 	int n = 0, ret = 0;
6359 
6360 	mutex_lock(&event_mutex);
6361 
6362 	event_file = event_file_data(m->private);
6363 	if (unlikely(!event_file)) {
6364 		ret = -ENODEV;
6365 		goto out_unlock;
6366 	}
6367 
6368 	list_for_each_entry(data, &event_file->triggers, list) {
6369 		if (data->cmd_ops->trigger_type == ETT_EVENT_HIST)
6370 			hist_trigger_show(m, data, n++);
6371 	}
6372 
6373  out_unlock:
6374 	mutex_unlock(&event_mutex);
6375 
6376 	return ret;
6377 }
6378 
6379 static int event_hist_open(struct inode *inode, struct file *file)
6380 {
6381 	int ret;
6382 
6383 	ret = security_locked_down(LOCKDOWN_TRACEFS);
6384 	if (ret)
6385 		return ret;
6386 
6387 	return single_open(file, hist_show, file);
6388 }
6389 
6390 const struct file_operations event_hist_fops = {
6391 	.open = event_hist_open,
6392 	.read = seq_read,
6393 	.llseek = seq_lseek,
6394 	.release = single_release,
6395 };
6396 
6397 static void hist_field_print(struct seq_file *m, struct hist_field *hist_field)
6398 {
6399 	const char *field_name = hist_field_name(hist_field, 0);
6400 
6401 	if (hist_field->var.name)
6402 		seq_printf(m, "%s=", hist_field->var.name);
6403 
6404 	if (hist_field->flags & HIST_FIELD_FL_CPU)
6405 		seq_puts(m, "cpu");
6406 	else if (field_name) {
6407 		if (hist_field->flags & HIST_FIELD_FL_VAR_REF ||
6408 		    hist_field->flags & HIST_FIELD_FL_ALIAS)
6409 			seq_putc(m, '$');
6410 		seq_printf(m, "%s", field_name);
6411 	} else if (hist_field->flags & HIST_FIELD_FL_TIMESTAMP)
6412 		seq_puts(m, "common_timestamp");
6413 
6414 	if (hist_field->flags) {
6415 		if (!(hist_field->flags & HIST_FIELD_FL_VAR_REF) &&
6416 		    !(hist_field->flags & HIST_FIELD_FL_EXPR)) {
6417 			const char *flags = get_hist_field_flags(hist_field);
6418 
6419 			if (flags)
6420 				seq_printf(m, ".%s", flags);
6421 		}
6422 	}
6423 }
6424 
6425 static int event_hist_trigger_print(struct seq_file *m,
6426 				    struct event_trigger_ops *ops,
6427 				    struct event_trigger_data *data)
6428 {
6429 	struct hist_trigger_data *hist_data = data->private_data;
6430 	struct hist_field *field;
6431 	bool have_var = false;
6432 	unsigned int i;
6433 
6434 	seq_puts(m, "hist:");
6435 
6436 	if (data->name)
6437 		seq_printf(m, "%s:", data->name);
6438 
6439 	seq_puts(m, "keys=");
6440 
6441 	for_each_hist_key_field(i, hist_data) {
6442 		field = hist_data->fields[i];
6443 
6444 		if (i > hist_data->n_vals)
6445 			seq_puts(m, ",");
6446 
6447 		if (field->flags & HIST_FIELD_FL_STACKTRACE)
6448 			seq_puts(m, "stacktrace");
6449 		else
6450 			hist_field_print(m, field);
6451 	}
6452 
6453 	seq_puts(m, ":vals=");
6454 
6455 	for_each_hist_val_field(i, hist_data) {
6456 		field = hist_data->fields[i];
6457 		if (field->flags & HIST_FIELD_FL_VAR) {
6458 			have_var = true;
6459 			continue;
6460 		}
6461 
6462 		if (i == HITCOUNT_IDX)
6463 			seq_puts(m, "hitcount");
6464 		else {
6465 			seq_puts(m, ",");
6466 			hist_field_print(m, field);
6467 		}
6468 	}
6469 
6470 	if (have_var) {
6471 		unsigned int n = 0;
6472 
6473 		seq_puts(m, ":");
6474 
6475 		for_each_hist_val_field(i, hist_data) {
6476 			field = hist_data->fields[i];
6477 
6478 			if (field->flags & HIST_FIELD_FL_VAR) {
6479 				if (n++)
6480 					seq_puts(m, ",");
6481 				hist_field_print(m, field);
6482 			}
6483 		}
6484 	}
6485 
6486 	seq_puts(m, ":sort=");
6487 
6488 	for (i = 0; i < hist_data->n_sort_keys; i++) {
6489 		struct tracing_map_sort_key *sort_key;
6490 		unsigned int idx, first_key_idx;
6491 
6492 		/* skip VAR vals */
6493 		first_key_idx = hist_data->n_vals - hist_data->n_vars;
6494 
6495 		sort_key = &hist_data->sort_keys[i];
6496 		idx = sort_key->field_idx;
6497 
6498 		if (WARN_ON(idx >= HIST_FIELDS_MAX))
6499 			return -EINVAL;
6500 
6501 		if (i > 0)
6502 			seq_puts(m, ",");
6503 
6504 		if (idx == HITCOUNT_IDX)
6505 			seq_puts(m, "hitcount");
6506 		else {
6507 			if (idx >= first_key_idx)
6508 				idx += hist_data->n_vars;
6509 			hist_field_print(m, hist_data->fields[idx]);
6510 		}
6511 
6512 		if (sort_key->descending)
6513 			seq_puts(m, ".descending");
6514 	}
6515 	seq_printf(m, ":size=%u", (1 << hist_data->map->map_bits));
6516 	if (hist_data->enable_timestamps)
6517 		seq_printf(m, ":clock=%s", hist_data->attrs->clock);
6518 
6519 	print_actions_spec(m, hist_data);
6520 
6521 	if (data->filter_str)
6522 		seq_printf(m, " if %s", data->filter_str);
6523 
6524 	if (data->paused)
6525 		seq_puts(m, " [paused]");
6526 	else
6527 		seq_puts(m, " [active]");
6528 
6529 	seq_putc(m, '\n');
6530 
6531 	return 0;
6532 }
6533 
6534 static int event_hist_trigger_init(struct event_trigger_ops *ops,
6535 				   struct event_trigger_data *data)
6536 {
6537 	struct hist_trigger_data *hist_data = data->private_data;
6538 
6539 	if (!data->ref && hist_data->attrs->name)
6540 		save_named_trigger(hist_data->attrs->name, data);
6541 
6542 	data->ref++;
6543 
6544 	return 0;
6545 }
6546 
6547 static void unregister_field_var_hists(struct hist_trigger_data *hist_data)
6548 {
6549 	struct trace_event_file *file;
6550 	unsigned int i;
6551 	char *cmd;
6552 	int ret;
6553 
6554 	for (i = 0; i < hist_data->n_field_var_hists; i++) {
6555 		file = hist_data->field_var_hists[i]->hist_data->event_file;
6556 		cmd = hist_data->field_var_hists[i]->cmd;
6557 		ret = event_hist_trigger_func(&trigger_hist_cmd, file,
6558 					      "!hist", "hist", cmd);
6559 	}
6560 }
6561 
6562 static void event_hist_trigger_free(struct event_trigger_ops *ops,
6563 				    struct event_trigger_data *data)
6564 {
6565 	struct hist_trigger_data *hist_data = data->private_data;
6566 
6567 	if (WARN_ON_ONCE(data->ref <= 0))
6568 		return;
6569 
6570 	data->ref--;
6571 	if (!data->ref) {
6572 		if (data->name)
6573 			del_named_trigger(data);
6574 
6575 		trigger_data_free(data);
6576 
6577 		remove_hist_vars(hist_data);
6578 
6579 		unregister_field_var_hists(hist_data);
6580 
6581 		destroy_hist_data(hist_data);
6582 	}
6583 }
6584 
6585 static struct event_trigger_ops event_hist_trigger_ops = {
6586 	.func			= event_hist_trigger,
6587 	.print			= event_hist_trigger_print,
6588 	.init			= event_hist_trigger_init,
6589 	.free			= event_hist_trigger_free,
6590 };
6591 
6592 static int event_hist_trigger_named_init(struct event_trigger_ops *ops,
6593 					 struct event_trigger_data *data)
6594 {
6595 	data->ref++;
6596 
6597 	save_named_trigger(data->named_data->name, data);
6598 
6599 	event_hist_trigger_init(ops, data->named_data);
6600 
6601 	return 0;
6602 }
6603 
6604 static void event_hist_trigger_named_free(struct event_trigger_ops *ops,
6605 					  struct event_trigger_data *data)
6606 {
6607 	if (WARN_ON_ONCE(data->ref <= 0))
6608 		return;
6609 
6610 	event_hist_trigger_free(ops, data->named_data);
6611 
6612 	data->ref--;
6613 	if (!data->ref) {
6614 		del_named_trigger(data);
6615 		trigger_data_free(data);
6616 	}
6617 }
6618 
6619 static struct event_trigger_ops event_hist_trigger_named_ops = {
6620 	.func			= event_hist_trigger,
6621 	.print			= event_hist_trigger_print,
6622 	.init			= event_hist_trigger_named_init,
6623 	.free			= event_hist_trigger_named_free,
6624 };
6625 
6626 static struct event_trigger_ops *event_hist_get_trigger_ops(char *cmd,
6627 							    char *param)
6628 {
6629 	return &event_hist_trigger_ops;
6630 }
6631 
6632 static void hist_clear(struct event_trigger_data *data)
6633 {
6634 	struct hist_trigger_data *hist_data = data->private_data;
6635 
6636 	if (data->name)
6637 		pause_named_trigger(data);
6638 
6639 	tracepoint_synchronize_unregister();
6640 
6641 	tracing_map_clear(hist_data->map);
6642 
6643 	if (data->name)
6644 		unpause_named_trigger(data);
6645 }
6646 
6647 static bool compatible_field(struct ftrace_event_field *field,
6648 			     struct ftrace_event_field *test_field)
6649 {
6650 	if (field == test_field)
6651 		return true;
6652 	if (field == NULL || test_field == NULL)
6653 		return false;
6654 	if (strcmp(field->name, test_field->name) != 0)
6655 		return false;
6656 	if (strcmp(field->type, test_field->type) != 0)
6657 		return false;
6658 	if (field->size != test_field->size)
6659 		return false;
6660 	if (field->is_signed != test_field->is_signed)
6661 		return false;
6662 
6663 	return true;
6664 }
6665 
6666 static bool hist_trigger_match(struct event_trigger_data *data,
6667 			       struct event_trigger_data *data_test,
6668 			       struct event_trigger_data *named_data,
6669 			       bool ignore_filter)
6670 {
6671 	struct tracing_map_sort_key *sort_key, *sort_key_test;
6672 	struct hist_trigger_data *hist_data, *hist_data_test;
6673 	struct hist_field *key_field, *key_field_test;
6674 	unsigned int i;
6675 
6676 	if (named_data && (named_data != data_test) &&
6677 	    (named_data != data_test->named_data))
6678 		return false;
6679 
6680 	if (!named_data && is_named_trigger(data_test))
6681 		return false;
6682 
6683 	hist_data = data->private_data;
6684 	hist_data_test = data_test->private_data;
6685 
6686 	if (hist_data->n_vals != hist_data_test->n_vals ||
6687 	    hist_data->n_fields != hist_data_test->n_fields ||
6688 	    hist_data->n_sort_keys != hist_data_test->n_sort_keys)
6689 		return false;
6690 
6691 	if (!ignore_filter) {
6692 		if ((data->filter_str && !data_test->filter_str) ||
6693 		   (!data->filter_str && data_test->filter_str))
6694 			return false;
6695 	}
6696 
6697 	for_each_hist_field(i, hist_data) {
6698 		key_field = hist_data->fields[i];
6699 		key_field_test = hist_data_test->fields[i];
6700 
6701 		if (key_field->flags != key_field_test->flags)
6702 			return false;
6703 		if (!compatible_field(key_field->field, key_field_test->field))
6704 			return false;
6705 		if (key_field->offset != key_field_test->offset)
6706 			return false;
6707 		if (key_field->size != key_field_test->size)
6708 			return false;
6709 		if (key_field->is_signed != key_field_test->is_signed)
6710 			return false;
6711 		if (!!key_field->var.name != !!key_field_test->var.name)
6712 			return false;
6713 		if (key_field->var.name &&
6714 		    strcmp(key_field->var.name, key_field_test->var.name) != 0)
6715 			return false;
6716 	}
6717 
6718 	for (i = 0; i < hist_data->n_sort_keys; i++) {
6719 		sort_key = &hist_data->sort_keys[i];
6720 		sort_key_test = &hist_data_test->sort_keys[i];
6721 
6722 		if (sort_key->field_idx != sort_key_test->field_idx ||
6723 		    sort_key->descending != sort_key_test->descending)
6724 			return false;
6725 	}
6726 
6727 	if (!ignore_filter && data->filter_str &&
6728 	    (strcmp(data->filter_str, data_test->filter_str) != 0))
6729 		return false;
6730 
6731 	if (!actions_match(hist_data, hist_data_test))
6732 		return false;
6733 
6734 	return true;
6735 }
6736 
6737 static int hist_register_trigger(char *glob, struct event_trigger_ops *ops,
6738 				 struct event_trigger_data *data,
6739 				 struct trace_event_file *file)
6740 {
6741 	struct hist_trigger_data *hist_data = data->private_data;
6742 	struct event_trigger_data *test, *named_data = NULL;
6743 	struct trace_array *tr = file->tr;
6744 	int ret = 0;
6745 
6746 	if (hist_data->attrs->name) {
6747 		named_data = find_named_trigger(hist_data->attrs->name);
6748 		if (named_data) {
6749 			if (!hist_trigger_match(data, named_data, named_data,
6750 						true)) {
6751 				hist_err(tr, HIST_ERR_NAMED_MISMATCH, errpos(hist_data->attrs->name));
6752 				ret = -EINVAL;
6753 				goto out;
6754 			}
6755 		}
6756 	}
6757 
6758 	if (hist_data->attrs->name && !named_data)
6759 		goto new;
6760 
6761 	lockdep_assert_held(&event_mutex);
6762 
6763 	list_for_each_entry(test, &file->triggers, list) {
6764 		if (test->cmd_ops->trigger_type == ETT_EVENT_HIST) {
6765 			if (!hist_trigger_match(data, test, named_data, false))
6766 				continue;
6767 			if (hist_data->attrs->pause)
6768 				test->paused = true;
6769 			else if (hist_data->attrs->cont)
6770 				test->paused = false;
6771 			else if (hist_data->attrs->clear)
6772 				hist_clear(test);
6773 			else {
6774 				hist_err(tr, HIST_ERR_TRIGGER_EEXIST, 0);
6775 				ret = -EEXIST;
6776 			}
6777 			goto out;
6778 		}
6779 	}
6780  new:
6781 	if (hist_data->attrs->cont || hist_data->attrs->clear) {
6782 		hist_err(tr, HIST_ERR_TRIGGER_ENOENT_CLEAR, 0);
6783 		ret = -ENOENT;
6784 		goto out;
6785 	}
6786 
6787 	if (hist_data->attrs->pause)
6788 		data->paused = true;
6789 
6790 	if (named_data) {
6791 		data->private_data = named_data->private_data;
6792 		set_named_trigger_data(data, named_data);
6793 		data->ops = &event_hist_trigger_named_ops;
6794 	}
6795 
6796 	if (data->ops->init) {
6797 		ret = data->ops->init(data->ops, data);
6798 		if (ret < 0)
6799 			goto out;
6800 	}
6801 
6802 	if (hist_data->enable_timestamps) {
6803 		char *clock = hist_data->attrs->clock;
6804 
6805 		ret = tracing_set_clock(file->tr, hist_data->attrs->clock);
6806 		if (ret) {
6807 			hist_err(tr, HIST_ERR_SET_CLOCK_FAIL, errpos(clock));
6808 			goto out;
6809 		}
6810 
6811 		tracing_set_time_stamp_abs(file->tr, true);
6812 	}
6813 
6814 	if (named_data)
6815 		destroy_hist_data(hist_data);
6816 
6817 	ret++;
6818  out:
6819 	return ret;
6820 }
6821 
6822 static int hist_trigger_enable(struct event_trigger_data *data,
6823 			       struct trace_event_file *file)
6824 {
6825 	int ret = 0;
6826 
6827 	list_add_tail_rcu(&data->list, &file->triggers);
6828 
6829 	update_cond_flag(file);
6830 
6831 	if (trace_event_trigger_enable_disable(file, 1) < 0) {
6832 		list_del_rcu(&data->list);
6833 		update_cond_flag(file);
6834 		ret--;
6835 	}
6836 
6837 	return ret;
6838 }
6839 
6840 static bool have_hist_trigger_match(struct event_trigger_data *data,
6841 				    struct trace_event_file *file)
6842 {
6843 	struct hist_trigger_data *hist_data = data->private_data;
6844 	struct event_trigger_data *test, *named_data = NULL;
6845 	bool match = false;
6846 
6847 	lockdep_assert_held(&event_mutex);
6848 
6849 	if (hist_data->attrs->name)
6850 		named_data = find_named_trigger(hist_data->attrs->name);
6851 
6852 	list_for_each_entry(test, &file->triggers, list) {
6853 		if (test->cmd_ops->trigger_type == ETT_EVENT_HIST) {
6854 			if (hist_trigger_match(data, test, named_data, false)) {
6855 				match = true;
6856 				break;
6857 			}
6858 		}
6859 	}
6860 
6861 	return match;
6862 }
6863 
6864 static bool hist_trigger_check_refs(struct event_trigger_data *data,
6865 				    struct trace_event_file *file)
6866 {
6867 	struct hist_trigger_data *hist_data = data->private_data;
6868 	struct event_trigger_data *test, *named_data = NULL;
6869 
6870 	lockdep_assert_held(&event_mutex);
6871 
6872 	if (hist_data->attrs->name)
6873 		named_data = find_named_trigger(hist_data->attrs->name);
6874 
6875 	list_for_each_entry(test, &file->triggers, list) {
6876 		if (test->cmd_ops->trigger_type == ETT_EVENT_HIST) {
6877 			if (!hist_trigger_match(data, test, named_data, false))
6878 				continue;
6879 			hist_data = test->private_data;
6880 			if (check_var_refs(hist_data))
6881 				return true;
6882 			break;
6883 		}
6884 	}
6885 
6886 	return false;
6887 }
6888 
6889 static void hist_unregister_trigger(char *glob, struct event_trigger_ops *ops,
6890 				    struct event_trigger_data *data,
6891 				    struct trace_event_file *file)
6892 {
6893 	struct hist_trigger_data *hist_data = data->private_data;
6894 	struct event_trigger_data *test, *named_data = NULL;
6895 	bool unregistered = false;
6896 
6897 	lockdep_assert_held(&event_mutex);
6898 
6899 	if (hist_data->attrs->name)
6900 		named_data = find_named_trigger(hist_data->attrs->name);
6901 
6902 	list_for_each_entry(test, &file->triggers, list) {
6903 		if (test->cmd_ops->trigger_type == ETT_EVENT_HIST) {
6904 			if (!hist_trigger_match(data, test, named_data, false))
6905 				continue;
6906 			unregistered = true;
6907 			list_del_rcu(&test->list);
6908 			trace_event_trigger_enable_disable(file, 0);
6909 			update_cond_flag(file);
6910 			break;
6911 		}
6912 	}
6913 
6914 	if (unregistered && test->ops->free)
6915 		test->ops->free(test->ops, test);
6916 
6917 	if (hist_data->enable_timestamps) {
6918 		if (!hist_data->remove || unregistered)
6919 			tracing_set_time_stamp_abs(file->tr, false);
6920 	}
6921 }
6922 
6923 static bool hist_file_check_refs(struct trace_event_file *file)
6924 {
6925 	struct hist_trigger_data *hist_data;
6926 	struct event_trigger_data *test;
6927 
6928 	lockdep_assert_held(&event_mutex);
6929 
6930 	list_for_each_entry(test, &file->triggers, list) {
6931 		if (test->cmd_ops->trigger_type == ETT_EVENT_HIST) {
6932 			hist_data = test->private_data;
6933 			if (check_var_refs(hist_data))
6934 				return true;
6935 		}
6936 	}
6937 
6938 	return false;
6939 }
6940 
6941 static void hist_unreg_all(struct trace_event_file *file)
6942 {
6943 	struct event_trigger_data *test, *n;
6944 	struct hist_trigger_data *hist_data;
6945 	struct synth_event *se;
6946 	const char *se_name;
6947 
6948 	lockdep_assert_held(&event_mutex);
6949 
6950 	if (hist_file_check_refs(file))
6951 		return;
6952 
6953 	list_for_each_entry_safe(test, n, &file->triggers, list) {
6954 		if (test->cmd_ops->trigger_type == ETT_EVENT_HIST) {
6955 			hist_data = test->private_data;
6956 			list_del_rcu(&test->list);
6957 			trace_event_trigger_enable_disable(file, 0);
6958 
6959 			se_name = trace_event_name(file->event_call);
6960 			se = find_synth_event(se_name);
6961 			if (se)
6962 				se->ref--;
6963 
6964 			update_cond_flag(file);
6965 			if (hist_data->enable_timestamps)
6966 				tracing_set_time_stamp_abs(file->tr, false);
6967 			if (test->ops->free)
6968 				test->ops->free(test->ops, test);
6969 		}
6970 	}
6971 }
6972 
6973 static int event_hist_trigger_func(struct event_command *cmd_ops,
6974 				   struct trace_event_file *file,
6975 				   char *glob, char *cmd, char *param)
6976 {
6977 	unsigned int hist_trigger_bits = TRACING_MAP_BITS_DEFAULT;
6978 	struct event_trigger_data *trigger_data;
6979 	struct hist_trigger_attrs *attrs;
6980 	struct event_trigger_ops *trigger_ops;
6981 	struct hist_trigger_data *hist_data;
6982 	struct synth_event *se;
6983 	const char *se_name;
6984 	bool remove = false;
6985 	char *trigger, *p;
6986 	int ret = 0;
6987 
6988 	lockdep_assert_held(&event_mutex);
6989 
6990 	if (glob && strlen(glob)) {
6991 		hist_err_clear();
6992 		last_cmd_set(file, param);
6993 	}
6994 
6995 	if (!param)
6996 		return -EINVAL;
6997 
6998 	if (glob[0] == '!')
6999 		remove = true;
7000 
7001 	/*
7002 	 * separate the trigger from the filter (k:v [if filter])
7003 	 * allowing for whitespace in the trigger
7004 	 */
7005 	p = trigger = param;
7006 	do {
7007 		p = strstr(p, "if");
7008 		if (!p)
7009 			break;
7010 		if (p == param)
7011 			return -EINVAL;
7012 		if (*(p - 1) != ' ' && *(p - 1) != '\t') {
7013 			p++;
7014 			continue;
7015 		}
7016 		if (p >= param + strlen(param) - (sizeof("if") - 1) - 1)
7017 			return -EINVAL;
7018 		if (*(p + sizeof("if") - 1) != ' ' && *(p + sizeof("if") - 1) != '\t') {
7019 			p++;
7020 			continue;
7021 		}
7022 		break;
7023 	} while (p);
7024 
7025 	if (!p)
7026 		param = NULL;
7027 	else {
7028 		*(p - 1) = '\0';
7029 		param = strstrip(p);
7030 		trigger = strstrip(trigger);
7031 	}
7032 
7033 	attrs = parse_hist_trigger_attrs(file->tr, trigger);
7034 	if (IS_ERR(attrs))
7035 		return PTR_ERR(attrs);
7036 
7037 	if (attrs->map_bits)
7038 		hist_trigger_bits = attrs->map_bits;
7039 
7040 	hist_data = create_hist_data(hist_trigger_bits, attrs, file, remove);
7041 	if (IS_ERR(hist_data)) {
7042 		destroy_hist_trigger_attrs(attrs);
7043 		return PTR_ERR(hist_data);
7044 	}
7045 
7046 	trigger_ops = cmd_ops->get_trigger_ops(cmd, trigger);
7047 
7048 	trigger_data = kzalloc(sizeof(*trigger_data), GFP_KERNEL);
7049 	if (!trigger_data) {
7050 		ret = -ENOMEM;
7051 		goto out_free;
7052 	}
7053 
7054 	trigger_data->count = -1;
7055 	trigger_data->ops = trigger_ops;
7056 	trigger_data->cmd_ops = cmd_ops;
7057 
7058 	INIT_LIST_HEAD(&trigger_data->list);
7059 	RCU_INIT_POINTER(trigger_data->filter, NULL);
7060 
7061 	trigger_data->private_data = hist_data;
7062 
7063 	/* if param is non-empty, it's supposed to be a filter */
7064 	if (param && cmd_ops->set_filter) {
7065 		ret = cmd_ops->set_filter(param, trigger_data, file);
7066 		if (ret < 0)
7067 			goto out_free;
7068 	}
7069 
7070 	if (remove) {
7071 		if (!have_hist_trigger_match(trigger_data, file))
7072 			goto out_free;
7073 
7074 		if (hist_trigger_check_refs(trigger_data, file)) {
7075 			ret = -EBUSY;
7076 			goto out_free;
7077 		}
7078 
7079 		cmd_ops->unreg(glob+1, trigger_ops, trigger_data, file);
7080 		se_name = trace_event_name(file->event_call);
7081 		se = find_synth_event(se_name);
7082 		if (se)
7083 			se->ref--;
7084 		ret = 0;
7085 		goto out_free;
7086 	}
7087 
7088 	ret = cmd_ops->reg(glob, trigger_ops, trigger_data, file);
7089 	/*
7090 	 * The above returns on success the # of triggers registered,
7091 	 * but if it didn't register any it returns zero.  Consider no
7092 	 * triggers registered a failure too.
7093 	 */
7094 	if (!ret) {
7095 		if (!(attrs->pause || attrs->cont || attrs->clear))
7096 			ret = -ENOENT;
7097 		goto out_free;
7098 	} else if (ret < 0)
7099 		goto out_free;
7100 
7101 	if (get_named_trigger_data(trigger_data))
7102 		goto enable;
7103 
7104 	if (has_hist_vars(hist_data))
7105 		save_hist_vars(hist_data);
7106 
7107 	ret = create_actions(hist_data);
7108 	if (ret)
7109 		goto out_unreg;
7110 
7111 	ret = tracing_map_init(hist_data->map);
7112 	if (ret)
7113 		goto out_unreg;
7114 enable:
7115 	ret = hist_trigger_enable(trigger_data, file);
7116 	if (ret)
7117 		goto out_unreg;
7118 
7119 	se_name = trace_event_name(file->event_call);
7120 	se = find_synth_event(se_name);
7121 	if (se)
7122 		se->ref++;
7123 	/* Just return zero, not the number of registered triggers */
7124 	ret = 0;
7125  out:
7126 	if (ret == 0)
7127 		hist_err_clear();
7128 
7129 	return ret;
7130  out_unreg:
7131 	cmd_ops->unreg(glob+1, trigger_ops, trigger_data, file);
7132  out_free:
7133 	if (cmd_ops->set_filter)
7134 		cmd_ops->set_filter(NULL, trigger_data, NULL);
7135 
7136 	remove_hist_vars(hist_data);
7137 
7138 	kfree(trigger_data);
7139 
7140 	destroy_hist_data(hist_data);
7141 	goto out;
7142 }
7143 
7144 static struct event_command trigger_hist_cmd = {
7145 	.name			= "hist",
7146 	.trigger_type		= ETT_EVENT_HIST,
7147 	.flags			= EVENT_CMD_FL_NEEDS_REC,
7148 	.func			= event_hist_trigger_func,
7149 	.reg			= hist_register_trigger,
7150 	.unreg			= hist_unregister_trigger,
7151 	.unreg_all		= hist_unreg_all,
7152 	.get_trigger_ops	= event_hist_get_trigger_ops,
7153 	.set_filter		= set_trigger_filter,
7154 };
7155 
7156 __init int register_trigger_hist_cmd(void)
7157 {
7158 	int ret;
7159 
7160 	ret = register_event_command(&trigger_hist_cmd);
7161 	WARN_ON(ret < 0);
7162 
7163 	return ret;
7164 }
7165 
7166 static void
7167 hist_enable_trigger(struct event_trigger_data *data, void *rec,
7168 		    struct ring_buffer_event *event)
7169 {
7170 	struct enable_trigger_data *enable_data = data->private_data;
7171 	struct event_trigger_data *test;
7172 
7173 	list_for_each_entry_rcu(test, &enable_data->file->triggers, list,
7174 				lockdep_is_held(&event_mutex)) {
7175 		if (test->cmd_ops->trigger_type == ETT_EVENT_HIST) {
7176 			if (enable_data->enable)
7177 				test->paused = false;
7178 			else
7179 				test->paused = true;
7180 		}
7181 	}
7182 }
7183 
7184 static void
7185 hist_enable_count_trigger(struct event_trigger_data *data, void *rec,
7186 			  struct ring_buffer_event *event)
7187 {
7188 	if (!data->count)
7189 		return;
7190 
7191 	if (data->count != -1)
7192 		(data->count)--;
7193 
7194 	hist_enable_trigger(data, rec, event);
7195 }
7196 
7197 static struct event_trigger_ops hist_enable_trigger_ops = {
7198 	.func			= hist_enable_trigger,
7199 	.print			= event_enable_trigger_print,
7200 	.init			= event_trigger_init,
7201 	.free			= event_enable_trigger_free,
7202 };
7203 
7204 static struct event_trigger_ops hist_enable_count_trigger_ops = {
7205 	.func			= hist_enable_count_trigger,
7206 	.print			= event_enable_trigger_print,
7207 	.init			= event_trigger_init,
7208 	.free			= event_enable_trigger_free,
7209 };
7210 
7211 static struct event_trigger_ops hist_disable_trigger_ops = {
7212 	.func			= hist_enable_trigger,
7213 	.print			= event_enable_trigger_print,
7214 	.init			= event_trigger_init,
7215 	.free			= event_enable_trigger_free,
7216 };
7217 
7218 static struct event_trigger_ops hist_disable_count_trigger_ops = {
7219 	.func			= hist_enable_count_trigger,
7220 	.print			= event_enable_trigger_print,
7221 	.init			= event_trigger_init,
7222 	.free			= event_enable_trigger_free,
7223 };
7224 
7225 static struct event_trigger_ops *
7226 hist_enable_get_trigger_ops(char *cmd, char *param)
7227 {
7228 	struct event_trigger_ops *ops;
7229 	bool enable;
7230 
7231 	enable = (strcmp(cmd, ENABLE_HIST_STR) == 0);
7232 
7233 	if (enable)
7234 		ops = param ? &hist_enable_count_trigger_ops :
7235 			&hist_enable_trigger_ops;
7236 	else
7237 		ops = param ? &hist_disable_count_trigger_ops :
7238 			&hist_disable_trigger_ops;
7239 
7240 	return ops;
7241 }
7242 
7243 static void hist_enable_unreg_all(struct trace_event_file *file)
7244 {
7245 	struct event_trigger_data *test, *n;
7246 
7247 	list_for_each_entry_safe(test, n, &file->triggers, list) {
7248 		if (test->cmd_ops->trigger_type == ETT_HIST_ENABLE) {
7249 			list_del_rcu(&test->list);
7250 			update_cond_flag(file);
7251 			trace_event_trigger_enable_disable(file, 0);
7252 			if (test->ops->free)
7253 				test->ops->free(test->ops, test);
7254 		}
7255 	}
7256 }
7257 
7258 static struct event_command trigger_hist_enable_cmd = {
7259 	.name			= ENABLE_HIST_STR,
7260 	.trigger_type		= ETT_HIST_ENABLE,
7261 	.func			= event_enable_trigger_func,
7262 	.reg			= event_enable_register_trigger,
7263 	.unreg			= event_enable_unregister_trigger,
7264 	.unreg_all		= hist_enable_unreg_all,
7265 	.get_trigger_ops	= hist_enable_get_trigger_ops,
7266 	.set_filter		= set_trigger_filter,
7267 };
7268 
7269 static struct event_command trigger_hist_disable_cmd = {
7270 	.name			= DISABLE_HIST_STR,
7271 	.trigger_type		= ETT_HIST_ENABLE,
7272 	.func			= event_enable_trigger_func,
7273 	.reg			= event_enable_register_trigger,
7274 	.unreg			= event_enable_unregister_trigger,
7275 	.unreg_all		= hist_enable_unreg_all,
7276 	.get_trigger_ops	= hist_enable_get_trigger_ops,
7277 	.set_filter		= set_trigger_filter,
7278 };
7279 
7280 static __init void unregister_trigger_hist_enable_disable_cmds(void)
7281 {
7282 	unregister_event_command(&trigger_hist_enable_cmd);
7283 	unregister_event_command(&trigger_hist_disable_cmd);
7284 }
7285 
7286 __init int register_trigger_hist_enable_disable_cmds(void)
7287 {
7288 	int ret;
7289 
7290 	ret = register_event_command(&trigger_hist_enable_cmd);
7291 	if (WARN_ON(ret < 0))
7292 		return ret;
7293 	ret = register_event_command(&trigger_hist_disable_cmd);
7294 	if (WARN_ON(ret < 0))
7295 		unregister_trigger_hist_enable_disable_cmds();
7296 
7297 	return ret;
7298 }
7299 
7300 static __init int trace_events_hist_init(void)
7301 {
7302 	struct dentry *entry = NULL;
7303 	struct dentry *d_tracer;
7304 	int err = 0;
7305 
7306 	err = dyn_event_register(&synth_event_ops);
7307 	if (err) {
7308 		pr_warn("Could not register synth_event_ops\n");
7309 		return err;
7310 	}
7311 
7312 	d_tracer = tracing_init_dentry();
7313 	if (IS_ERR(d_tracer)) {
7314 		err = PTR_ERR(d_tracer);
7315 		goto err;
7316 	}
7317 
7318 	entry = tracefs_create_file("synthetic_events", 0644, d_tracer,
7319 				    NULL, &synth_events_fops);
7320 	if (!entry) {
7321 		err = -ENODEV;
7322 		goto err;
7323 	}
7324 
7325 	return err;
7326  err:
7327 	pr_warn("Could not create tracefs 'synthetic_events' entry\n");
7328 
7329 	return err;
7330 }
7331 
7332 fs_initcall(trace_events_hist_init);
7333