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