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