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