b97412053c0a6e90953fb698d75356b53fd4cf4e
[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                         goto out;
3592                 }
3593
3594                 param = strsep(&params, ",");
3595                 if (!param) {
3596                         hist_err(tr, HIST_ERR_PARAM_NOT_FOUND, 0);
3597                         ret = -EINVAL;
3598                         goto out;
3599                 }
3600
3601                 param = strstrip(param);
3602                 if (strlen(param) < 2) {
3603                         hist_err(tr, HIST_ERR_INVALID_PARAM, errpos(param));
3604                         ret = -EINVAL;
3605                         goto out;
3606                 }
3607
3608                 saved_param = kstrdup(param, GFP_KERNEL);
3609                 if (!saved_param) {
3610                         ret = -ENOMEM;
3611                         goto out;
3612                 }
3613
3614                 if (first_param && data->use_trace_keyword) {
3615                         data->synth_event_name = saved_param;
3616                         first_param = false;
3617                         continue;
3618                 }
3619                 first_param = false;
3620
3621                 data->params[data->n_params++] = saved_param;
3622         }
3623  out:
3624         return ret;
3625 }
3626
3627 static int action_parse(struct trace_array *tr, char *str, struct action_data *data,
3628                         enum handler_id handler)
3629 {
3630         char *action_name;
3631         int ret = 0;
3632
3633         strsep(&str, ".");
3634         if (!str) {
3635                 hist_err(tr, HIST_ERR_ACTION_NOT_FOUND, 0);
3636                 ret = -EINVAL;
3637                 goto out;
3638         }
3639
3640         action_name = strsep(&str, "(");
3641         if (!action_name || !str) {
3642                 hist_err(tr, HIST_ERR_ACTION_NOT_FOUND, 0);
3643                 ret = -EINVAL;
3644                 goto out;
3645         }
3646
3647         if (str_has_prefix(action_name, "save")) {
3648                 char *params = strsep(&str, ")");
3649
3650                 if (!params) {
3651                         hist_err(tr, HIST_ERR_NO_SAVE_PARAMS, 0);
3652                         ret = -EINVAL;
3653                         goto out;
3654                 }
3655
3656                 ret = parse_action_params(tr, params, data);
3657                 if (ret)
3658                         goto out;
3659
3660                 if (handler == HANDLER_ONMAX)
3661                         data->track_data.check_val = check_track_val_max;
3662                 else if (handler == HANDLER_ONCHANGE)
3663                         data->track_data.check_val = check_track_val_changed;
3664                 else {
3665                         hist_err(tr, HIST_ERR_ACTION_MISMATCH, errpos(action_name));
3666                         ret = -EINVAL;
3667                         goto out;
3668                 }
3669
3670                 data->track_data.save_data = save_track_data_vars;
3671                 data->fn = ontrack_action;
3672                 data->action = ACTION_SAVE;
3673         } else if (str_has_prefix(action_name, "snapshot")) {
3674                 char *params = strsep(&str, ")");
3675
3676                 if (!str) {
3677                         hist_err(tr, HIST_ERR_NO_CLOSING_PAREN, errpos(params));
3678                         ret = -EINVAL;
3679                         goto out;
3680                 }
3681
3682                 if (handler == HANDLER_ONMAX)
3683                         data->track_data.check_val = check_track_val_max;
3684                 else if (handler == HANDLER_ONCHANGE)
3685                         data->track_data.check_val = check_track_val_changed;
3686                 else {
3687                         hist_err(tr, HIST_ERR_ACTION_MISMATCH, errpos(action_name));
3688                         ret = -EINVAL;
3689                         goto out;
3690                 }
3691
3692                 data->track_data.save_data = save_track_data_snapshot;
3693                 data->fn = ontrack_action;
3694                 data->action = ACTION_SNAPSHOT;
3695         } else {
3696                 char *params = strsep(&str, ")");
3697
3698                 if (str_has_prefix(action_name, "trace"))
3699                         data->use_trace_keyword = true;
3700
3701                 if (params) {
3702                         ret = parse_action_params(tr, params, data);
3703                         if (ret)
3704                                 goto out;
3705                 }
3706
3707                 if (handler == HANDLER_ONMAX)
3708                         data->track_data.check_val = check_track_val_max;
3709                 else if (handler == HANDLER_ONCHANGE)
3710                         data->track_data.check_val = check_track_val_changed;
3711
3712                 if (handler != HANDLER_ONMATCH) {
3713                         data->track_data.save_data = action_trace;
3714                         data->fn = ontrack_action;
3715                 } else
3716                         data->fn = action_trace;
3717
3718                 data->action = ACTION_TRACE;
3719         }
3720
3721         data->action_name = kstrdup(action_name, GFP_KERNEL);
3722         if (!data->action_name) {
3723                 ret = -ENOMEM;
3724                 goto out;
3725         }
3726
3727         data->handler = handler;
3728  out:
3729         return ret;
3730 }
3731
3732 static struct action_data *track_data_parse(struct hist_trigger_data *hist_data,
3733                                             char *str, enum handler_id handler)
3734 {
3735         struct action_data *data;
3736         int ret = -EINVAL;
3737         char *var_str;
3738
3739         data = kzalloc(sizeof(*data), GFP_KERNEL);
3740         if (!data)
3741                 return ERR_PTR(-ENOMEM);
3742
3743         var_str = strsep(&str, ")");
3744         if (!var_str || !str) {
3745                 ret = -EINVAL;
3746                 goto free;
3747         }
3748
3749         data->track_data.var_str = kstrdup(var_str, GFP_KERNEL);
3750         if (!data->track_data.var_str) {
3751                 ret = -ENOMEM;
3752                 goto free;
3753         }
3754
3755         ret = action_parse(hist_data->event_file->tr, str, data, handler);
3756         if (ret)
3757                 goto free;
3758  out:
3759         return data;
3760  free:
3761         track_data_destroy(hist_data, data);
3762         data = ERR_PTR(ret);
3763         goto out;
3764 }
3765
3766 static void onmatch_destroy(struct action_data *data)
3767 {
3768         kfree(data->match_data.event);
3769         kfree(data->match_data.event_system);
3770
3771         action_data_destroy(data);
3772 }
3773
3774 static void destroy_field_var(struct field_var *field_var)
3775 {
3776         if (!field_var)
3777                 return;
3778
3779         destroy_hist_field(field_var->var, 0);
3780         destroy_hist_field(field_var->val, 0);
3781
3782         kfree(field_var);
3783 }
3784
3785 static void destroy_field_vars(struct hist_trigger_data *hist_data)
3786 {
3787         unsigned int i;
3788
3789         for (i = 0; i < hist_data->n_field_vars; i++)
3790                 destroy_field_var(hist_data->field_vars[i]);
3791
3792         for (i = 0; i < hist_data->n_save_vars; i++)
3793                 destroy_field_var(hist_data->save_vars[i]);
3794 }
3795
3796 static void save_field_var(struct hist_trigger_data *hist_data,
3797                            struct field_var *field_var)
3798 {
3799         hist_data->field_vars[hist_data->n_field_vars++] = field_var;
3800
3801         if (field_var->val->flags & HIST_FIELD_FL_STRING)
3802                 hist_data->n_field_var_str++;
3803 }
3804
3805
3806 static int check_synth_field(struct synth_event *event,
3807                              struct hist_field *hist_field,
3808                              unsigned int field_pos)
3809 {
3810         struct synth_field *field;
3811
3812         if (field_pos >= event->n_fields)
3813                 return -EINVAL;
3814
3815         field = event->fields[field_pos];
3816
3817         /*
3818          * A dynamic string synth field can accept static or
3819          * dynamic. A static string synth field can only accept a
3820          * same-sized static string, which is checked for later.
3821          */
3822         if (strstr(hist_field->type, "char[") && field->is_string
3823             && field->is_dynamic)
3824                 return 0;
3825
3826         if (strcmp(field->type, hist_field->type) != 0) {
3827                 if (field->size != hist_field->size ||
3828                     (!field->is_string && field->is_signed != hist_field->is_signed))
3829                         return -EINVAL;
3830         }
3831
3832         return 0;
3833 }
3834
3835 static struct hist_field *
3836 trace_action_find_var(struct hist_trigger_data *hist_data,
3837                       struct action_data *data,
3838                       char *system, char *event, char *var)
3839 {
3840         struct trace_array *tr = hist_data->event_file->tr;
3841         struct hist_field *hist_field;
3842
3843         var++; /* skip '$' */
3844
3845         hist_field = find_target_event_var(hist_data, system, event, var);
3846         if (!hist_field) {
3847                 if (!system && data->handler == HANDLER_ONMATCH) {
3848                         system = data->match_data.event_system;
3849                         event = data->match_data.event;
3850                 }
3851
3852                 hist_field = find_event_var(hist_data, system, event, var);
3853         }
3854
3855         if (!hist_field)
3856                 hist_err(tr, HIST_ERR_PARAM_NOT_FOUND, errpos(var));
3857
3858         return hist_field;
3859 }
3860
3861 static struct hist_field *
3862 trace_action_create_field_var(struct hist_trigger_data *hist_data,
3863                               struct action_data *data, char *system,
3864                               char *event, char *var)
3865 {
3866         struct hist_field *hist_field = NULL;
3867         struct field_var *field_var;
3868
3869         /*
3870          * First try to create a field var on the target event (the
3871          * currently being defined).  This will create a variable for
3872          * unqualified fields on the target event, or if qualified,
3873          * target fields that have qualified names matching the target.
3874          */
3875         field_var = create_target_field_var(hist_data, system, event, var);
3876
3877         if (field_var && !IS_ERR(field_var)) {
3878                 save_field_var(hist_data, field_var);
3879                 hist_field = field_var->var;
3880         } else {
3881                 field_var = NULL;
3882                 /*
3883                  * If no explicit system.event is specified, default to
3884                  * looking for fields on the onmatch(system.event.xxx)
3885                  * event.
3886                  */
3887                 if (!system && data->handler == HANDLER_ONMATCH) {
3888                         system = data->match_data.event_system;
3889                         event = data->match_data.event;
3890                 }
3891
3892                 if (!event)
3893                         goto free;
3894                 /*
3895                  * At this point, we're looking at a field on another
3896                  * event.  Because we can't modify a hist trigger on
3897                  * another event to add a variable for a field, we need
3898                  * to create a new trigger on that event and create the
3899                  * variable at the same time.
3900                  */
3901                 hist_field = create_field_var_hist(hist_data, system, event, var);
3902                 if (IS_ERR(hist_field))
3903                         goto free;
3904         }
3905  out:
3906         return hist_field;
3907  free:
3908         destroy_field_var(field_var);
3909         hist_field = NULL;
3910         goto out;
3911 }
3912
3913 static int trace_action_create(struct hist_trigger_data *hist_data,
3914                                struct action_data *data)
3915 {
3916         struct trace_array *tr = hist_data->event_file->tr;
3917         char *event_name, *param, *system = NULL;
3918         struct hist_field *hist_field, *var_ref;
3919         unsigned int i;
3920         unsigned int field_pos = 0;
3921         struct synth_event *event;
3922         char *synth_event_name;
3923         int var_ref_idx, ret = 0;
3924
3925         lockdep_assert_held(&event_mutex);
3926
3927         /* Sanity check to avoid out-of-bound write on 'data->var_ref_idx' */
3928         if (data->n_params > SYNTH_FIELDS_MAX)
3929                 return -EINVAL;
3930
3931         if (data->use_trace_keyword)
3932                 synth_event_name = data->synth_event_name;
3933         else
3934                 synth_event_name = data->action_name;
3935
3936         event = find_synth_event(synth_event_name);
3937         if (!event) {
3938                 hist_err(tr, HIST_ERR_SYNTH_EVENT_NOT_FOUND, errpos(synth_event_name));
3939                 return -EINVAL;
3940         }
3941
3942         event->ref++;
3943
3944         for (i = 0; i < data->n_params; i++) {
3945                 char *p;
3946
3947                 p = param = kstrdup(data->params[i], GFP_KERNEL);
3948                 if (!param) {
3949                         ret = -ENOMEM;
3950                         goto err;
3951                 }
3952
3953                 system = strsep(&param, ".");
3954                 if (!param) {
3955                         param = (char *)system;
3956                         system = event_name = NULL;
3957                 } else {
3958                         event_name = strsep(&param, ".");
3959                         if (!param) {
3960                                 kfree(p);
3961                                 ret = -EINVAL;
3962                                 goto err;
3963                         }
3964                 }
3965
3966                 if (param[0] == '$')
3967                         hist_field = trace_action_find_var(hist_data, data,
3968                                                            system, event_name,
3969                                                            param);
3970                 else
3971                         hist_field = trace_action_create_field_var(hist_data,
3972                                                                    data,
3973                                                                    system,
3974                                                                    event_name,
3975                                                                    param);
3976
3977                 if (!hist_field) {
3978                         kfree(p);
3979                         ret = -EINVAL;
3980                         goto err;
3981                 }
3982
3983                 if (check_synth_field(event, hist_field, field_pos) == 0) {
3984                         var_ref = create_var_ref(hist_data, hist_field,
3985                                                  system, event_name);
3986                         if (!var_ref) {
3987                                 kfree(p);
3988                                 ret = -ENOMEM;
3989                                 goto err;
3990                         }
3991
3992                         var_ref_idx = find_var_ref_idx(hist_data, var_ref);
3993                         if (WARN_ON(var_ref_idx < 0)) {
3994                                 kfree(p);
3995                                 ret = var_ref_idx;
3996                                 goto err;
3997                         }
3998
3999                         data->var_ref_idx[i] = var_ref_idx;
4000
4001                         field_pos++;
4002                         kfree(p);
4003                         continue;
4004                 }
4005
4006                 hist_err(tr, HIST_ERR_SYNTH_TYPE_MISMATCH, errpos(param));
4007                 kfree(p);
4008                 ret = -EINVAL;
4009                 goto err;
4010         }
4011
4012         if (field_pos != event->n_fields) {
4013                 hist_err(tr, HIST_ERR_SYNTH_COUNT_MISMATCH, errpos(event->name));
4014                 ret = -EINVAL;
4015                 goto err;
4016         }
4017
4018         data->synth_event = event;
4019  out:
4020         return ret;
4021  err:
4022         event->ref--;
4023
4024         goto out;
4025 }
4026
4027 static int action_create(struct hist_trigger_data *hist_data,
4028                          struct action_data *data)
4029 {
4030         struct trace_event_file *file = hist_data->event_file;
4031         struct trace_array *tr = file->tr;
4032         struct track_data *track_data;
4033         struct field_var *field_var;
4034         unsigned int i;
4035         char *param;
4036         int ret = 0;
4037
4038         if (data->action == ACTION_TRACE)
4039                 return trace_action_create(hist_data, data);
4040
4041         if (data->action == ACTION_SNAPSHOT) {
4042                 track_data = track_data_alloc(hist_data->key_size, data, hist_data);
4043                 if (IS_ERR(track_data)) {
4044                         ret = PTR_ERR(track_data);
4045                         goto out;
4046                 }
4047
4048                 ret = tracing_snapshot_cond_enable(file->tr, track_data,
4049                                                    cond_snapshot_update);
4050                 if (ret)
4051                         track_data_free(track_data);
4052
4053                 goto out;
4054         }
4055
4056         if (data->action == ACTION_SAVE) {
4057                 if (hist_data->n_save_vars) {
4058                         ret = -EEXIST;
4059                         hist_err(tr, HIST_ERR_TOO_MANY_SAVE_ACTIONS, 0);
4060                         goto out;
4061                 }
4062
4063                 for (i = 0; i < data->n_params; i++) {
4064                         param = kstrdup(data->params[i], GFP_KERNEL);
4065                         if (!param) {
4066                                 ret = -ENOMEM;
4067                                 goto out;
4068                         }
4069
4070                         field_var = create_target_field_var(hist_data, NULL, NULL, param);
4071                         if (IS_ERR(field_var)) {
4072                                 hist_err(tr, HIST_ERR_FIELD_VAR_CREATE_FAIL,
4073                                          errpos(param));
4074                                 ret = PTR_ERR(field_var);
4075                                 kfree(param);
4076                                 goto out;
4077                         }
4078
4079                         hist_data->save_vars[hist_data->n_save_vars++] = field_var;
4080                         if (field_var->val->flags & HIST_FIELD_FL_STRING)
4081                                 hist_data->n_save_var_str++;
4082                         kfree(param);
4083                 }
4084         }
4085  out:
4086         return ret;
4087 }
4088
4089 static int onmatch_create(struct hist_trigger_data *hist_data,
4090                           struct action_data *data)
4091 {
4092         return action_create(hist_data, data);
4093 }
4094
4095 static struct action_data *onmatch_parse(struct trace_array *tr, char *str)
4096 {
4097         char *match_event, *match_event_system;
4098         struct action_data *data;
4099         int ret = -EINVAL;
4100
4101         data = kzalloc(sizeof(*data), GFP_KERNEL);
4102         if (!data)
4103                 return ERR_PTR(-ENOMEM);
4104
4105         match_event = strsep(&str, ")");
4106         if (!match_event || !str) {
4107                 hist_err(tr, HIST_ERR_NO_CLOSING_PAREN, errpos(match_event));
4108                 goto free;
4109         }
4110
4111         match_event_system = strsep(&match_event, ".");
4112         if (!match_event) {
4113                 hist_err(tr, HIST_ERR_SUBSYS_NOT_FOUND, errpos(match_event_system));
4114                 goto free;
4115         }
4116
4117         if (IS_ERR(event_file(tr, match_event_system, match_event))) {
4118                 hist_err(tr, HIST_ERR_INVALID_SUBSYS_EVENT, errpos(match_event));
4119                 goto free;
4120         }
4121
4122         data->match_data.event = kstrdup(match_event, GFP_KERNEL);
4123         if (!data->match_data.event) {
4124                 ret = -ENOMEM;
4125                 goto free;
4126         }
4127
4128         data->match_data.event_system = kstrdup(match_event_system, GFP_KERNEL);
4129         if (!data->match_data.event_system) {
4130                 ret = -ENOMEM;
4131                 goto free;
4132         }
4133
4134         ret = action_parse(tr, str, data, HANDLER_ONMATCH);
4135         if (ret)
4136                 goto free;
4137  out:
4138         return data;
4139  free:
4140         onmatch_destroy(data);
4141         data = ERR_PTR(ret);
4142         goto out;
4143 }
4144
4145 static int create_hitcount_val(struct hist_trigger_data *hist_data)
4146 {
4147         hist_data->fields[HITCOUNT_IDX] =
4148                 create_hist_field(hist_data, NULL, HIST_FIELD_FL_HITCOUNT, NULL);
4149         if (!hist_data->fields[HITCOUNT_IDX])
4150                 return -ENOMEM;
4151
4152         hist_data->n_vals++;
4153         hist_data->n_fields++;
4154
4155         if (WARN_ON(hist_data->n_vals > TRACING_MAP_VALS_MAX))
4156                 return -EINVAL;
4157
4158         return 0;
4159 }
4160
4161 static int __create_val_field(struct hist_trigger_data *hist_data,
4162                               unsigned int val_idx,
4163                               struct trace_event_file *file,
4164                               char *var_name, char *field_str,
4165                               unsigned long flags)
4166 {
4167         struct hist_field *hist_field;
4168         int ret = 0, n_subexprs = 0;
4169
4170         hist_field = parse_expr(hist_data, file, field_str, flags, var_name, &n_subexprs);
4171         if (IS_ERR(hist_field)) {
4172                 ret = PTR_ERR(hist_field);
4173                 goto out;
4174         }
4175
4176         hist_data->fields[val_idx] = hist_field;
4177
4178         ++hist_data->n_vals;
4179         ++hist_data->n_fields;
4180
4181         if (WARN_ON(hist_data->n_vals > TRACING_MAP_VALS_MAX + TRACING_MAP_VARS_MAX))
4182                 ret = -EINVAL;
4183  out:
4184         return ret;
4185 }
4186
4187 static int create_val_field(struct hist_trigger_data *hist_data,
4188                             unsigned int val_idx,
4189                             struct trace_event_file *file,
4190                             char *field_str)
4191 {
4192         if (WARN_ON(val_idx >= TRACING_MAP_VALS_MAX))
4193                 return -EINVAL;
4194
4195         return __create_val_field(hist_data, val_idx, file, NULL, field_str, 0);
4196 }
4197
4198 static const char no_comm[] = "(no comm)";
4199
4200 static u64 hist_field_execname(struct hist_field *hist_field,
4201                                struct tracing_map_elt *elt,
4202                                struct trace_buffer *buffer,
4203                                struct ring_buffer_event *rbe,
4204                                void *event)
4205 {
4206         struct hist_elt_data *elt_data;
4207
4208         if (WARN_ON_ONCE(!elt))
4209                 return (u64)(unsigned long)no_comm;
4210
4211         elt_data = elt->private_data;
4212
4213         if (WARN_ON_ONCE(!elt_data->comm))
4214                 return (u64)(unsigned long)no_comm;
4215
4216         return (u64)(unsigned long)(elt_data->comm);
4217 }
4218
4219 static u64 hist_fn_call(struct hist_field *hist_field,
4220                         struct tracing_map_elt *elt,
4221                         struct trace_buffer *buffer,
4222                         struct ring_buffer_event *rbe,
4223                         void *event)
4224 {
4225         switch (hist_field->fn_num) {
4226         case HIST_FIELD_FN_VAR_REF:
4227                 return hist_field_var_ref(hist_field, elt, buffer, rbe, event);
4228         case HIST_FIELD_FN_COUNTER:
4229                 return hist_field_counter(hist_field, elt, buffer, rbe, event);
4230         case HIST_FIELD_FN_CONST:
4231                 return hist_field_const(hist_field, elt, buffer, rbe, event);
4232         case HIST_FIELD_FN_LOG2:
4233                 return hist_field_log2(hist_field, elt, buffer, rbe, event);
4234         case HIST_FIELD_FN_BUCKET:
4235                 return hist_field_bucket(hist_field, elt, buffer, rbe, event);
4236         case HIST_FIELD_FN_TIMESTAMP:
4237                 return hist_field_timestamp(hist_field, elt, buffer, rbe, event);
4238         case HIST_FIELD_FN_CPU:
4239                 return hist_field_cpu(hist_field, elt, buffer, rbe, event);
4240         case HIST_FIELD_FN_STRING:
4241                 return hist_field_string(hist_field, elt, buffer, rbe, event);
4242         case HIST_FIELD_FN_DYNSTRING:
4243                 return hist_field_dynstring(hist_field, elt, buffer, rbe, event);
4244         case HIST_FIELD_FN_RELDYNSTRING:
4245                 return hist_field_reldynstring(hist_field, elt, buffer, rbe, event);
4246         case HIST_FIELD_FN_PSTRING:
4247                 return hist_field_pstring(hist_field, elt, buffer, rbe, event);
4248         case HIST_FIELD_FN_S64:
4249                 return hist_field_s64(hist_field, elt, buffer, rbe, event);
4250         case HIST_FIELD_FN_U64:
4251                 return hist_field_u64(hist_field, elt, buffer, rbe, event);
4252         case HIST_FIELD_FN_S32:
4253                 return hist_field_s32(hist_field, elt, buffer, rbe, event);
4254         case HIST_FIELD_FN_U32:
4255                 return hist_field_u32(hist_field, elt, buffer, rbe, event);
4256         case HIST_FIELD_FN_S16:
4257                 return hist_field_s16(hist_field, elt, buffer, rbe, event);
4258         case HIST_FIELD_FN_U16:
4259                 return hist_field_u16(hist_field, elt, buffer, rbe, event);
4260         case HIST_FIELD_FN_S8:
4261                 return hist_field_s8(hist_field, elt, buffer, rbe, event);
4262         case HIST_FIELD_FN_U8:
4263                 return hist_field_u8(hist_field, elt, buffer, rbe, event);
4264         case HIST_FIELD_FN_UMINUS:
4265                 return hist_field_unary_minus(hist_field, elt, buffer, rbe, event);
4266         case HIST_FIELD_FN_MINUS:
4267                 return hist_field_minus(hist_field, elt, buffer, rbe, event);
4268         case HIST_FIELD_FN_PLUS:
4269                 return hist_field_plus(hist_field, elt, buffer, rbe, event);
4270         case HIST_FIELD_FN_DIV:
4271                 return hist_field_div(hist_field, elt, buffer, rbe, event);
4272         case HIST_FIELD_FN_MULT:
4273                 return hist_field_mult(hist_field, elt, buffer, rbe, event);
4274         case HIST_FIELD_FN_DIV_POWER2:
4275                 return div_by_power_of_two(hist_field, elt, buffer, rbe, event);
4276         case HIST_FIELD_FN_DIV_NOT_POWER2:
4277                 return div_by_not_power_of_two(hist_field, elt, buffer, rbe, event);
4278         case HIST_FIELD_FN_DIV_MULT_SHIFT:
4279                 return div_by_mult_and_shift(hist_field, elt, buffer, rbe, event);
4280         case HIST_FIELD_FN_EXECNAME:
4281                 return hist_field_execname(hist_field, elt, buffer, rbe, event);
4282         default:
4283                 return 0;
4284         }
4285 }
4286
4287 /* Convert a var that points to common_pid.execname to a string */
4288 static void update_var_execname(struct hist_field *hist_field)
4289 {
4290         hist_field->flags = HIST_FIELD_FL_STRING | HIST_FIELD_FL_VAR |
4291                 HIST_FIELD_FL_EXECNAME;
4292         hist_field->size = MAX_FILTER_STR_VAL;
4293         hist_field->is_signed = 0;
4294
4295         kfree_const(hist_field->type);
4296         hist_field->type = "char[]";
4297
4298         hist_field->fn_num = HIST_FIELD_FN_EXECNAME;
4299 }
4300
4301 static int create_var_field(struct hist_trigger_data *hist_data,
4302                             unsigned int val_idx,
4303                             struct trace_event_file *file,
4304                             char *var_name, char *expr_str)
4305 {
4306         struct trace_array *tr = hist_data->event_file->tr;
4307         unsigned long flags = 0;
4308         int ret;
4309
4310         if (WARN_ON(val_idx >= TRACING_MAP_VALS_MAX + TRACING_MAP_VARS_MAX))
4311                 return -EINVAL;
4312
4313         if (find_var(hist_data, file, var_name) && !hist_data->remove) {
4314                 hist_err(tr, HIST_ERR_DUPLICATE_VAR, errpos(var_name));
4315                 return -EINVAL;
4316         }
4317
4318         flags |= HIST_FIELD_FL_VAR;
4319         hist_data->n_vars++;
4320         if (WARN_ON(hist_data->n_vars > TRACING_MAP_VARS_MAX))
4321                 return -EINVAL;
4322
4323         ret = __create_val_field(hist_data, val_idx, file, var_name, expr_str, flags);
4324
4325         if (!ret && hist_data->fields[val_idx]->flags & HIST_FIELD_FL_EXECNAME)
4326                 update_var_execname(hist_data->fields[val_idx]);
4327
4328         if (!ret && hist_data->fields[val_idx]->flags & HIST_FIELD_FL_STRING)
4329                 hist_data->fields[val_idx]->var_str_idx = hist_data->n_var_str++;
4330
4331         return ret;
4332 }
4333
4334 static int create_val_fields(struct hist_trigger_data *hist_data,
4335                              struct trace_event_file *file)
4336 {
4337         char *fields_str, *field_str;
4338         unsigned int i, j = 1;
4339         int ret;
4340
4341         ret = create_hitcount_val(hist_data);
4342         if (ret)
4343                 goto out;
4344
4345         fields_str = hist_data->attrs->vals_str;
4346         if (!fields_str)
4347                 goto out;
4348
4349         for (i = 0, j = 1; i < TRACING_MAP_VALS_MAX &&
4350                      j < TRACING_MAP_VALS_MAX; i++) {
4351                 field_str = strsep(&fields_str, ",");
4352                 if (!field_str)
4353                         break;
4354
4355                 if (strcmp(field_str, "hitcount") == 0)
4356                         continue;
4357
4358                 ret = create_val_field(hist_data, j++, file, field_str);
4359                 if (ret)
4360                         goto out;
4361         }
4362
4363         if (fields_str && (strcmp(fields_str, "hitcount") != 0))
4364                 ret = -EINVAL;
4365  out:
4366         return ret;
4367 }
4368
4369 static int create_key_field(struct hist_trigger_data *hist_data,
4370                             unsigned int key_idx,
4371                             unsigned int key_offset,
4372                             struct trace_event_file *file,
4373                             char *field_str)
4374 {
4375         struct trace_array *tr = hist_data->event_file->tr;
4376         struct hist_field *hist_field = NULL;
4377         unsigned long flags = 0;
4378         unsigned int key_size;
4379         int ret = 0, n_subexprs = 0;
4380
4381         if (WARN_ON(key_idx >= HIST_FIELDS_MAX))
4382                 return -EINVAL;
4383
4384         flags |= HIST_FIELD_FL_KEY;
4385
4386         if (strcmp(field_str, "stacktrace") == 0) {
4387                 flags |= HIST_FIELD_FL_STACKTRACE;
4388                 key_size = sizeof(unsigned long) * HIST_STACKTRACE_DEPTH;
4389                 hist_field = create_hist_field(hist_data, NULL, flags, NULL);
4390         } else {
4391                 hist_field = parse_expr(hist_data, file, field_str, flags,
4392                                         NULL, &n_subexprs);
4393                 if (IS_ERR(hist_field)) {
4394                         ret = PTR_ERR(hist_field);
4395                         goto out;
4396                 }
4397
4398                 if (field_has_hist_vars(hist_field, 0)) {
4399                         hist_err(tr, HIST_ERR_INVALID_REF_KEY, errpos(field_str));
4400                         destroy_hist_field(hist_field, 0);
4401                         ret = -EINVAL;
4402                         goto out;
4403                 }
4404
4405                 key_size = hist_field->size;
4406         }
4407
4408         hist_data->fields[key_idx] = hist_field;
4409
4410         key_size = ALIGN(key_size, sizeof(u64));
4411         hist_data->fields[key_idx]->size = key_size;
4412         hist_data->fields[key_idx]->offset = key_offset;
4413
4414         hist_data->key_size += key_size;
4415
4416         if (hist_data->key_size > HIST_KEY_SIZE_MAX) {
4417                 ret = -EINVAL;
4418                 goto out;
4419         }
4420
4421         hist_data->n_keys++;
4422         hist_data->n_fields++;
4423
4424         if (WARN_ON(hist_data->n_keys > TRACING_MAP_KEYS_MAX))
4425                 return -EINVAL;
4426
4427         ret = key_size;
4428  out:
4429         return ret;
4430 }
4431
4432 static int create_key_fields(struct hist_trigger_data *hist_data,
4433                              struct trace_event_file *file)
4434 {
4435         unsigned int i, key_offset = 0, n_vals = hist_data->n_vals;
4436         char *fields_str, *field_str;
4437         int ret = -EINVAL;
4438
4439         fields_str = hist_data->attrs->keys_str;
4440         if (!fields_str)
4441                 goto out;
4442
4443         for (i = n_vals; i < n_vals + TRACING_MAP_KEYS_MAX; i++) {
4444                 field_str = strsep(&fields_str, ",");
4445                 if (!field_str)
4446                         break;
4447                 ret = create_key_field(hist_data, i, key_offset,
4448                                        file, field_str);
4449                 if (ret < 0)
4450                         goto out;
4451                 key_offset += ret;
4452         }
4453         if (fields_str) {
4454                 ret = -EINVAL;
4455                 goto out;
4456         }
4457         ret = 0;
4458  out:
4459         return ret;
4460 }
4461
4462 static int create_var_fields(struct hist_trigger_data *hist_data,
4463                              struct trace_event_file *file)
4464 {
4465         unsigned int i, j = hist_data->n_vals;
4466         int ret = 0;
4467
4468         unsigned int n_vars = hist_data->attrs->var_defs.n_vars;
4469
4470         for (i = 0; i < n_vars; i++) {
4471                 char *var_name = hist_data->attrs->var_defs.name[i];
4472                 char *expr = hist_data->attrs->var_defs.expr[i];
4473
4474                 ret = create_var_field(hist_data, j++, file, var_name, expr);
4475                 if (ret)
4476                         goto out;
4477         }
4478  out:
4479         return ret;
4480 }
4481
4482 static void free_var_defs(struct hist_trigger_data *hist_data)
4483 {
4484         unsigned int i;
4485
4486         for (i = 0; i < hist_data->attrs->var_defs.n_vars; i++) {
4487                 kfree(hist_data->attrs->var_defs.name[i]);
4488                 kfree(hist_data->attrs->var_defs.expr[i]);
4489         }
4490
4491         hist_data->attrs->var_defs.n_vars = 0;
4492 }
4493
4494 static int parse_var_defs(struct hist_trigger_data *hist_data)
4495 {
4496         struct trace_array *tr = hist_data->event_file->tr;
4497         char *s, *str, *var_name, *field_str;
4498         unsigned int i, j, n_vars = 0;
4499         int ret = 0;
4500
4501         for (i = 0; i < hist_data->attrs->n_assignments; i++) {
4502                 str = hist_data->attrs->assignment_str[i];
4503                 for (j = 0; j < TRACING_MAP_VARS_MAX; j++) {
4504                         field_str = strsep(&str, ",");
4505                         if (!field_str)
4506                                 break;
4507
4508                         var_name = strsep(&field_str, "=");
4509                         if (!var_name || !field_str) {
4510                                 hist_err(tr, HIST_ERR_MALFORMED_ASSIGNMENT,
4511                                          errpos(var_name));
4512                                 ret = -EINVAL;
4513                                 goto free;
4514                         }
4515
4516                         if (n_vars == TRACING_MAP_VARS_MAX) {
4517                                 hist_err(tr, HIST_ERR_TOO_MANY_VARS, errpos(var_name));
4518                                 ret = -EINVAL;
4519                                 goto free;
4520                         }
4521
4522                         s = kstrdup(var_name, GFP_KERNEL);
4523                         if (!s) {
4524                                 ret = -ENOMEM;
4525                                 goto free;
4526                         }
4527                         hist_data->attrs->var_defs.name[n_vars] = s;
4528
4529                         s = kstrdup(field_str, GFP_KERNEL);
4530                         if (!s) {
4531                                 kfree(hist_data->attrs->var_defs.name[n_vars]);
4532                                 hist_data->attrs->var_defs.name[n_vars] = NULL;
4533                                 ret = -ENOMEM;
4534                                 goto free;
4535                         }
4536                         hist_data->attrs->var_defs.expr[n_vars++] = s;
4537
4538                         hist_data->attrs->var_defs.n_vars = n_vars;
4539                 }
4540         }
4541
4542         return ret;
4543  free:
4544         free_var_defs(hist_data);
4545
4546         return ret;
4547 }
4548
4549 static int create_hist_fields(struct hist_trigger_data *hist_data,
4550                               struct trace_event_file *file)
4551 {
4552         int ret;
4553
4554         ret = parse_var_defs(hist_data);
4555         if (ret)
4556                 return ret;
4557
4558         ret = create_val_fields(hist_data, file);
4559         if (ret)
4560                 goto out;
4561
4562         ret = create_var_fields(hist_data, file);
4563         if (ret)
4564                 goto out;
4565
4566         ret = create_key_fields(hist_data, file);
4567
4568  out:
4569         free_var_defs(hist_data);
4570
4571         return ret;
4572 }
4573
4574 static int is_descending(struct trace_array *tr, const char *str)
4575 {
4576         if (!str)
4577                 return 0;
4578
4579         if (strcmp(str, "descending") == 0)
4580                 return 1;
4581
4582         if (strcmp(str, "ascending") == 0)
4583                 return 0;
4584
4585         hist_err(tr, HIST_ERR_INVALID_SORT_MODIFIER, errpos((char *)str));
4586
4587         return -EINVAL;
4588 }
4589
4590 static int create_sort_keys(struct hist_trigger_data *hist_data)
4591 {
4592         struct trace_array *tr = hist_data->event_file->tr;
4593         char *fields_str = hist_data->attrs->sort_key_str;
4594         struct tracing_map_sort_key *sort_key;
4595         int descending, ret = 0;
4596         unsigned int i, j, k;
4597
4598         hist_data->n_sort_keys = 1; /* we always have at least one, hitcount */
4599
4600         if (!fields_str)
4601                 goto out;
4602
4603         for (i = 0; i < TRACING_MAP_SORT_KEYS_MAX; i++) {
4604                 struct hist_field *hist_field;
4605                 char *field_str, *field_name;
4606                 const char *test_name;
4607
4608                 sort_key = &hist_data->sort_keys[i];
4609
4610                 field_str = strsep(&fields_str, ",");
4611                 if (!field_str)
4612                         break;
4613
4614                 if (!*field_str) {
4615                         ret = -EINVAL;
4616                         hist_err(tr, HIST_ERR_EMPTY_SORT_FIELD, errpos("sort="));
4617                         break;
4618                 }
4619
4620                 if ((i == TRACING_MAP_SORT_KEYS_MAX - 1) && fields_str) {
4621                         hist_err(tr, HIST_ERR_TOO_MANY_SORT_FIELDS, errpos("sort="));
4622                         ret = -EINVAL;
4623                         break;
4624                 }
4625
4626                 field_name = strsep(&field_str, ".");
4627                 if (!field_name || !*field_name) {
4628                         ret = -EINVAL;
4629                         hist_err(tr, HIST_ERR_EMPTY_SORT_FIELD, errpos("sort="));
4630                         break;
4631                 }
4632
4633                 if (strcmp(field_name, "hitcount") == 0) {
4634                         descending = is_descending(tr, field_str);
4635                         if (descending < 0) {
4636                                 ret = descending;
4637                                 break;
4638                         }
4639                         sort_key->descending = descending;
4640                         continue;
4641                 }
4642
4643                 for (j = 1, k = 1; j < hist_data->n_fields; j++) {
4644                         unsigned int idx;
4645
4646                         hist_field = hist_data->fields[j];
4647                         if (hist_field->flags & HIST_FIELD_FL_VAR)
4648                                 continue;
4649
4650                         idx = k++;
4651
4652                         test_name = hist_field_name(hist_field, 0);
4653
4654                         if (strcmp(field_name, test_name) == 0) {
4655                                 sort_key->field_idx = idx;
4656                                 descending = is_descending(tr, field_str);
4657                                 if (descending < 0) {
4658                                         ret = descending;
4659                                         goto out;
4660                                 }
4661                                 sort_key->descending = descending;
4662                                 break;
4663                         }
4664                 }
4665                 if (j == hist_data->n_fields) {
4666                         ret = -EINVAL;
4667                         hist_err(tr, HIST_ERR_INVALID_SORT_FIELD, errpos(field_name));
4668                         break;
4669                 }
4670         }
4671
4672         hist_data->n_sort_keys = i;
4673  out:
4674         return ret;
4675 }
4676
4677 static void destroy_actions(struct hist_trigger_data *hist_data)
4678 {
4679         unsigned int i;
4680
4681         for (i = 0; i < hist_data->n_actions; i++) {
4682                 struct action_data *data = hist_data->actions[i];
4683
4684                 if (data->handler == HANDLER_ONMATCH)
4685                         onmatch_destroy(data);
4686                 else if (data->handler == HANDLER_ONMAX ||
4687                          data->handler == HANDLER_ONCHANGE)
4688                         track_data_destroy(hist_data, data);
4689                 else
4690                         kfree(data);
4691         }
4692 }
4693
4694 static int parse_actions(struct hist_trigger_data *hist_data)
4695 {
4696         struct trace_array *tr = hist_data->event_file->tr;
4697         struct action_data *data;
4698         unsigned int i;
4699         int ret = 0;
4700         char *str;
4701         int len;
4702
4703         for (i = 0; i < hist_data->attrs->n_actions; i++) {
4704                 str = hist_data->attrs->action_str[i];
4705
4706                 if ((len = str_has_prefix(str, "onmatch("))) {
4707                         char *action_str = str + len;
4708
4709                         data = onmatch_parse(tr, action_str);
4710                         if (IS_ERR(data)) {
4711                                 ret = PTR_ERR(data);
4712                                 break;
4713                         }
4714                 } else if ((len = str_has_prefix(str, "onmax("))) {
4715                         char *action_str = str + len;
4716
4717                         data = track_data_parse(hist_data, action_str,
4718                                                 HANDLER_ONMAX);
4719                         if (IS_ERR(data)) {
4720                                 ret = PTR_ERR(data);
4721                                 break;
4722                         }
4723                 } else if ((len = str_has_prefix(str, "onchange("))) {
4724                         char *action_str = str + len;
4725
4726                         data = track_data_parse(hist_data, action_str,
4727                                                 HANDLER_ONCHANGE);
4728                         if (IS_ERR(data)) {
4729                                 ret = PTR_ERR(data);
4730                                 break;
4731                         }
4732                 } else {
4733                         ret = -EINVAL;
4734                         break;
4735                 }
4736
4737                 hist_data->actions[hist_data->n_actions++] = data;
4738         }
4739
4740         return ret;
4741 }
4742
4743 static int create_actions(struct hist_trigger_data *hist_data)
4744 {
4745         struct action_data *data;
4746         unsigned int i;
4747         int ret = 0;
4748
4749         for (i = 0; i < hist_data->attrs->n_actions; i++) {
4750                 data = hist_data->actions[i];
4751
4752                 if (data->handler == HANDLER_ONMATCH) {
4753                         ret = onmatch_create(hist_data, data);
4754                         if (ret)
4755                                 break;
4756                 } else if (data->handler == HANDLER_ONMAX ||
4757                            data->handler == HANDLER_ONCHANGE) {
4758                         ret = track_data_create(hist_data, data);
4759                         if (ret)
4760                                 break;
4761                 } else {
4762                         ret = -EINVAL;
4763                         break;
4764                 }
4765         }
4766
4767         return ret;
4768 }
4769
4770 static void print_actions(struct seq_file *m,
4771                           struct hist_trigger_data *hist_data,
4772                           struct tracing_map_elt *elt)
4773 {
4774         unsigned int i;
4775
4776         for (i = 0; i < hist_data->n_actions; i++) {
4777                 struct action_data *data = hist_data->actions[i];
4778
4779                 if (data->action == ACTION_SNAPSHOT)
4780                         continue;
4781
4782                 if (data->handler == HANDLER_ONMAX ||
4783                     data->handler == HANDLER_ONCHANGE)
4784                         track_data_print(m, hist_data, elt, data);
4785         }
4786 }
4787
4788 static void print_action_spec(struct seq_file *m,
4789                               struct hist_trigger_data *hist_data,
4790                               struct action_data *data)
4791 {
4792         unsigned int i;
4793
4794         if (data->action == ACTION_SAVE) {
4795                 for (i = 0; i < hist_data->n_save_vars; i++) {
4796                         seq_printf(m, "%s", hist_data->save_vars[i]->var->var.name);
4797                         if (i < hist_data->n_save_vars - 1)
4798                                 seq_puts(m, ",");
4799                 }
4800         } else if (data->action == ACTION_TRACE) {
4801                 if (data->use_trace_keyword)
4802                         seq_printf(m, "%s", data->synth_event_name);
4803                 for (i = 0; i < data->n_params; i++) {
4804                         if (i || data->use_trace_keyword)
4805                                 seq_puts(m, ",");
4806                         seq_printf(m, "%s", data->params[i]);
4807                 }
4808         }
4809 }
4810
4811 static void print_track_data_spec(struct seq_file *m,
4812                                   struct hist_trigger_data *hist_data,
4813                                   struct action_data *data)
4814 {
4815         if (data->handler == HANDLER_ONMAX)
4816                 seq_puts(m, ":onmax(");
4817         else if (data->handler == HANDLER_ONCHANGE)
4818                 seq_puts(m, ":onchange(");
4819         seq_printf(m, "%s", data->track_data.var_str);
4820         seq_printf(m, ").%s(", data->action_name);
4821
4822         print_action_spec(m, hist_data, data);
4823
4824         seq_puts(m, ")");
4825 }
4826
4827 static void print_onmatch_spec(struct seq_file *m,
4828                                struct hist_trigger_data *hist_data,
4829                                struct action_data *data)
4830 {
4831         seq_printf(m, ":onmatch(%s.%s).", data->match_data.event_system,
4832                    data->match_data.event);
4833
4834         seq_printf(m, "%s(", data->action_name);
4835
4836         print_action_spec(m, hist_data, data);
4837
4838         seq_puts(m, ")");
4839 }
4840
4841 static bool actions_match(struct hist_trigger_data *hist_data,
4842                           struct hist_trigger_data *hist_data_test)
4843 {
4844         unsigned int i, j;
4845
4846         if (hist_data->n_actions != hist_data_test->n_actions)
4847                 return false;
4848
4849         for (i = 0; i < hist_data->n_actions; i++) {
4850                 struct action_data *data = hist_data->actions[i];
4851                 struct action_data *data_test = hist_data_test->actions[i];
4852                 char *action_name, *action_name_test;
4853
4854                 if (data->handler != data_test->handler)
4855                         return false;
4856                 if (data->action != data_test->action)
4857                         return false;
4858
4859                 if (data->n_params != data_test->n_params)
4860                         return false;
4861
4862                 for (j = 0; j < data->n_params; j++) {
4863                         if (strcmp(data->params[j], data_test->params[j]) != 0)
4864                                 return false;
4865                 }
4866
4867                 if (data->use_trace_keyword)
4868                         action_name = data->synth_event_name;
4869                 else
4870                         action_name = data->action_name;
4871
4872                 if (data_test->use_trace_keyword)
4873                         action_name_test = data_test->synth_event_name;
4874                 else
4875                         action_name_test = data_test->action_name;
4876
4877                 if (strcmp(action_name, action_name_test) != 0)
4878                         return false;
4879
4880                 if (data->handler == HANDLER_ONMATCH) {
4881                         if (strcmp(data->match_data.event_system,
4882                                    data_test->match_data.event_system) != 0)
4883                                 return false;
4884                         if (strcmp(data->match_data.event,
4885                                    data_test->match_data.event) != 0)
4886                                 return false;
4887                 } else if (data->handler == HANDLER_ONMAX ||
4888                            data->handler == HANDLER_ONCHANGE) {
4889                         if (strcmp(data->track_data.var_str,
4890                                    data_test->track_data.var_str) != 0)
4891                                 return false;
4892                 }
4893         }
4894
4895         return true;
4896 }
4897
4898
4899 static void print_actions_spec(struct seq_file *m,
4900                                struct hist_trigger_data *hist_data)
4901 {
4902         unsigned int i;
4903
4904         for (i = 0; i < hist_data->n_actions; i++) {
4905                 struct action_data *data = hist_data->actions[i];
4906
4907                 if (data->handler == HANDLER_ONMATCH)
4908                         print_onmatch_spec(m, hist_data, data);
4909                 else if (data->handler == HANDLER_ONMAX ||
4910                          data->handler == HANDLER_ONCHANGE)
4911                         print_track_data_spec(m, hist_data, data);
4912         }
4913 }
4914
4915 static void destroy_field_var_hists(struct hist_trigger_data *hist_data)
4916 {
4917         unsigned int i;
4918
4919         for (i = 0; i < hist_data->n_field_var_hists; i++) {
4920                 kfree(hist_data->field_var_hists[i]->cmd);
4921                 kfree(hist_data->field_var_hists[i]);
4922         }
4923 }
4924
4925 static void destroy_hist_data(struct hist_trigger_data *hist_data)
4926 {
4927         if (!hist_data)
4928                 return;
4929
4930         destroy_hist_trigger_attrs(hist_data->attrs);
4931         destroy_hist_fields(hist_data);
4932         tracing_map_destroy(hist_data->map);
4933
4934         destroy_actions(hist_data);
4935         destroy_field_vars(hist_data);
4936         destroy_field_var_hists(hist_data);
4937
4938         kfree(hist_data);
4939 }
4940
4941 static int create_tracing_map_fields(struct hist_trigger_data *hist_data)
4942 {
4943         struct tracing_map *map = hist_data->map;
4944         struct ftrace_event_field *field;
4945         struct hist_field *hist_field;
4946         int i, idx = 0;
4947
4948         for_each_hist_field(i, hist_data) {
4949                 hist_field = hist_data->fields[i];
4950                 if (hist_field->flags & HIST_FIELD_FL_KEY) {
4951                         tracing_map_cmp_fn_t cmp_fn;
4952
4953                         field = hist_field->field;
4954
4955                         if (hist_field->flags & HIST_FIELD_FL_STACKTRACE)
4956                                 cmp_fn = tracing_map_cmp_none;
4957                         else if (!field || hist_field->flags & HIST_FIELD_FL_CPU)
4958                                 cmp_fn = tracing_map_cmp_num(hist_field->size,
4959                                                              hist_field->is_signed);
4960                         else if (is_string_field(field))
4961                                 cmp_fn = tracing_map_cmp_string;
4962                         else
4963                                 cmp_fn = tracing_map_cmp_num(field->size,
4964                                                              field->is_signed);
4965                         idx = tracing_map_add_key_field(map,
4966                                                         hist_field->offset,
4967                                                         cmp_fn);
4968                 } else if (!(hist_field->flags & HIST_FIELD_FL_VAR))
4969                         idx = tracing_map_add_sum_field(map);
4970
4971                 if (idx < 0)
4972                         return idx;
4973
4974                 if (hist_field->flags & HIST_FIELD_FL_VAR) {
4975                         idx = tracing_map_add_var(map);
4976                         if (idx < 0)
4977                                 return idx;
4978                         hist_field->var.idx = idx;
4979                         hist_field->var.hist_data = hist_data;
4980                 }
4981         }
4982
4983         return 0;
4984 }
4985
4986 static struct hist_trigger_data *
4987 create_hist_data(unsigned int map_bits,
4988                  struct hist_trigger_attrs *attrs,
4989                  struct trace_event_file *file,
4990                  bool remove)
4991 {
4992         const struct tracing_map_ops *map_ops = NULL;
4993         struct hist_trigger_data *hist_data;
4994         int ret = 0;
4995
4996         hist_data = kzalloc(sizeof(*hist_data), GFP_KERNEL);
4997         if (!hist_data)
4998                 return ERR_PTR(-ENOMEM);
4999
5000         hist_data->attrs = attrs;
5001         hist_data->remove = remove;
5002         hist_data->event_file = file;
5003
5004         ret = parse_actions(hist_data);
5005         if (ret)
5006                 goto free;
5007
5008         ret = create_hist_fields(hist_data, file);
5009         if (ret)
5010                 goto free;
5011
5012         ret = create_sort_keys(hist_data);
5013         if (ret)
5014                 goto free;
5015
5016         map_ops = &hist_trigger_elt_data_ops;
5017
5018         hist_data->map = tracing_map_create(map_bits, hist_data->key_size,
5019                                             map_ops, hist_data);
5020         if (IS_ERR(hist_data->map)) {
5021                 ret = PTR_ERR(hist_data->map);
5022                 hist_data->map = NULL;
5023                 goto free;
5024         }
5025
5026         ret = create_tracing_map_fields(hist_data);
5027         if (ret)
5028                 goto free;
5029  out:
5030         return hist_data;
5031  free:
5032         hist_data->attrs = NULL;
5033
5034         destroy_hist_data(hist_data);
5035
5036         hist_data = ERR_PTR(ret);
5037
5038         goto out;
5039 }
5040
5041 static void hist_trigger_elt_update(struct hist_trigger_data *hist_data,
5042                                     struct tracing_map_elt *elt,
5043                                     struct trace_buffer *buffer, void *rec,
5044                                     struct ring_buffer_event *rbe,
5045                                     u64 *var_ref_vals)
5046 {
5047         struct hist_elt_data *elt_data;
5048         struct hist_field *hist_field;
5049         unsigned int i, var_idx;
5050         u64 hist_val;
5051
5052         elt_data = elt->private_data;
5053         elt_data->var_ref_vals = var_ref_vals;
5054
5055         for_each_hist_val_field(i, hist_data) {
5056                 hist_field = hist_data->fields[i];
5057                 hist_val = hist_fn_call(hist_field, elt, buffer, rbe, rec);
5058                 if (hist_field->flags & HIST_FIELD_FL_VAR) {
5059                         var_idx = hist_field->var.idx;
5060
5061                         if (hist_field->flags & HIST_FIELD_FL_STRING) {
5062                                 unsigned int str_start, var_str_idx, idx;
5063                                 char *str, *val_str;
5064                                 unsigned int size;
5065
5066                                 str_start = hist_data->n_field_var_str +
5067                                         hist_data->n_save_var_str;
5068                                 var_str_idx = hist_field->var_str_idx;
5069                                 idx = str_start + var_str_idx;
5070
5071                                 str = elt_data->field_var_str[idx];
5072                                 val_str = (char *)(uintptr_t)hist_val;
5073
5074                                 size = min(hist_field->size, STR_VAR_LEN_MAX);
5075                                 strscpy(str, val_str, size);
5076
5077                                 hist_val = (u64)(uintptr_t)str;
5078                         }
5079                         tracing_map_set_var(elt, var_idx, hist_val);
5080                         continue;
5081                 }
5082                 tracing_map_update_sum(elt, i, hist_val);
5083         }
5084
5085         for_each_hist_key_field(i, hist_data) {
5086                 hist_field = hist_data->fields[i];
5087                 if (hist_field->flags & HIST_FIELD_FL_VAR) {
5088                         hist_val = hist_fn_call(hist_field, elt, buffer, rbe, rec);
5089                         var_idx = hist_field->var.idx;
5090                         tracing_map_set_var(elt, var_idx, hist_val);
5091                 }
5092         }
5093
5094         update_field_vars(hist_data, elt, buffer, rbe, rec);
5095 }
5096
5097 static inline void add_to_key(char *compound_key, void *key,
5098                               struct hist_field *key_field, void *rec)
5099 {
5100         size_t size = key_field->size;
5101
5102         if (key_field->flags & HIST_FIELD_FL_STRING) {
5103                 struct ftrace_event_field *field;
5104
5105                 field = key_field->field;
5106                 if (field->filter_type == FILTER_DYN_STRING ||
5107                     field->filter_type == FILTER_RDYN_STRING)
5108                         size = *(u32 *)(rec + field->offset) >> 16;
5109                 else if (field->filter_type == FILTER_STATIC_STRING)
5110                         size = field->size;
5111
5112                 /* ensure NULL-termination */
5113                 if (size > key_field->size - 1)
5114                         size = key_field->size - 1;
5115
5116                 strncpy(compound_key + key_field->offset, (char *)key, size);
5117         } else
5118                 memcpy(compound_key + key_field->offset, key, size);
5119 }
5120
5121 static void
5122 hist_trigger_actions(struct hist_trigger_data *hist_data,
5123                      struct tracing_map_elt *elt,
5124                      struct trace_buffer *buffer, void *rec,
5125                      struct ring_buffer_event *rbe, void *key,
5126                      u64 *var_ref_vals)
5127 {
5128         struct action_data *data;
5129         unsigned int i;
5130
5131         for (i = 0; i < hist_data->n_actions; i++) {
5132                 data = hist_data->actions[i];
5133                 data->fn(hist_data, elt, buffer, rec, rbe, key, data, var_ref_vals);
5134         }
5135 }
5136
5137 static void event_hist_trigger(struct event_trigger_data *data,
5138                                struct trace_buffer *buffer, void *rec,
5139                                struct ring_buffer_event *rbe)
5140 {
5141         struct hist_trigger_data *hist_data = data->private_data;
5142         bool use_compound_key = (hist_data->n_keys > 1);
5143         unsigned long entries[HIST_STACKTRACE_DEPTH];
5144         u64 var_ref_vals[TRACING_MAP_VARS_MAX];
5145         char compound_key[HIST_KEY_SIZE_MAX];
5146         struct tracing_map_elt *elt = NULL;
5147         struct hist_field *key_field;
5148         u64 field_contents;
5149         void *key = NULL;
5150         unsigned int i;
5151
5152         if (unlikely(!rbe))
5153                 return;
5154
5155         memset(compound_key, 0, hist_data->key_size);
5156
5157         for_each_hist_key_field(i, hist_data) {
5158                 key_field = hist_data->fields[i];
5159
5160                 if (key_field->flags & HIST_FIELD_FL_STACKTRACE) {
5161                         memset(entries, 0, HIST_STACKTRACE_SIZE);
5162                         stack_trace_save(entries, HIST_STACKTRACE_DEPTH,
5163                                          HIST_STACKTRACE_SKIP);
5164                         key = entries;
5165                 } else {
5166                         field_contents = hist_fn_call(key_field, elt, buffer, rbe, rec);
5167                         if (key_field->flags & HIST_FIELD_FL_STRING) {
5168                                 key = (void *)(unsigned long)field_contents;
5169                                 use_compound_key = true;
5170                         } else
5171                                 key = (void *)&field_contents;
5172                 }
5173
5174                 if (use_compound_key)
5175                         add_to_key(compound_key, key, key_field, rec);
5176         }
5177
5178         if (use_compound_key)
5179                 key = compound_key;
5180
5181         if (hist_data->n_var_refs &&
5182             !resolve_var_refs(hist_data, key, var_ref_vals, false))
5183                 return;
5184
5185         elt = tracing_map_insert(hist_data->map, key);
5186         if (!elt)
5187                 return;
5188
5189         hist_trigger_elt_update(hist_data, elt, buffer, rec, rbe, var_ref_vals);
5190
5191         if (resolve_var_refs(hist_data, key, var_ref_vals, true))
5192                 hist_trigger_actions(hist_data, elt, buffer, rec, rbe, key, var_ref_vals);
5193 }
5194
5195 static void hist_trigger_stacktrace_print(struct seq_file *m,
5196                                           unsigned long *stacktrace_entries,
5197                                           unsigned int max_entries)
5198 {
5199         unsigned int spaces = 8;
5200         unsigned int i;
5201
5202         for (i = 0; i < max_entries; i++) {
5203                 if (!stacktrace_entries[i])
5204                         return;
5205
5206                 seq_printf(m, "%*c", 1 + spaces, ' ');
5207                 seq_printf(m, "%pS\n", (void*)stacktrace_entries[i]);
5208         }
5209 }
5210
5211 static void hist_trigger_print_key(struct seq_file *m,
5212                                    struct hist_trigger_data *hist_data,
5213                                    void *key,
5214                                    struct tracing_map_elt *elt)
5215 {
5216         struct hist_field *key_field;
5217         bool multiline = false;
5218         const char *field_name;
5219         unsigned int i;
5220         u64 uval;
5221
5222         seq_puts(m, "{ ");
5223
5224         for_each_hist_key_field(i, hist_data) {
5225                 key_field = hist_data->fields[i];
5226
5227                 if (i > hist_data->n_vals)
5228                         seq_puts(m, ", ");
5229
5230                 field_name = hist_field_name(key_field, 0);
5231
5232                 if (key_field->flags & HIST_FIELD_FL_HEX) {
5233                         uval = *(u64 *)(key + key_field->offset);
5234                         seq_printf(m, "%s: %llx", field_name, uval);
5235                 } else if (key_field->flags & HIST_FIELD_FL_SYM) {
5236                         uval = *(u64 *)(key + key_field->offset);
5237                         seq_printf(m, "%s: [%llx] %-45ps", field_name,
5238                                    uval, (void *)(uintptr_t)uval);
5239                 } else if (key_field->flags & HIST_FIELD_FL_SYM_OFFSET) {
5240                         uval = *(u64 *)(key + key_field->offset);
5241                         seq_printf(m, "%s: [%llx] %-55pS", field_name,
5242                                    uval, (void *)(uintptr_t)uval);
5243                 } else if (key_field->flags & HIST_FIELD_FL_EXECNAME) {
5244                         struct hist_elt_data *elt_data = elt->private_data;
5245                         char *comm;
5246
5247                         if (WARN_ON_ONCE(!elt_data))
5248                                 return;
5249
5250                         comm = elt_data->comm;
5251
5252                         uval = *(u64 *)(key + key_field->offset);
5253                         seq_printf(m, "%s: %-16s[%10llu]", field_name,
5254                                    comm, uval);
5255                 } else if (key_field->flags & HIST_FIELD_FL_SYSCALL) {
5256                         const char *syscall_name;
5257
5258                         uval = *(u64 *)(key + key_field->offset);
5259                         syscall_name = get_syscall_name(uval);
5260                         if (!syscall_name)
5261                                 syscall_name = "unknown_syscall";
5262
5263                         seq_printf(m, "%s: %-30s[%3llu]", field_name,
5264                                    syscall_name, uval);
5265                 } else if (key_field->flags & HIST_FIELD_FL_STACKTRACE) {
5266                         seq_puts(m, "stacktrace:\n");
5267                         hist_trigger_stacktrace_print(m,
5268                                                       key + key_field->offset,
5269                                                       HIST_STACKTRACE_DEPTH);
5270                         multiline = true;
5271                 } else if (key_field->flags & HIST_FIELD_FL_LOG2) {
5272                         seq_printf(m, "%s: ~ 2^%-2llu", field_name,
5273                                    *(u64 *)(key + key_field->offset));
5274                 } else if (key_field->flags & HIST_FIELD_FL_BUCKET) {
5275                         unsigned long buckets = key_field->buckets;
5276                         uval = *(u64 *)(key + key_field->offset);
5277                         seq_printf(m, "%s: ~ %llu-%llu", field_name,
5278                                    uval, uval + buckets -1);
5279                 } else if (key_field->flags & HIST_FIELD_FL_STRING) {
5280                         seq_printf(m, "%s: %-50s", field_name,
5281                                    (char *)(key + key_field->offset));
5282                 } else {
5283                         uval = *(u64 *)(key + key_field->offset);
5284                         seq_printf(m, "%s: %10llu", field_name, uval);
5285                 }
5286         }
5287
5288         if (!multiline)
5289                 seq_puts(m, " ");
5290
5291         seq_puts(m, "}");
5292 }
5293
5294 static void hist_trigger_entry_print(struct seq_file *m,
5295                                      struct hist_trigger_data *hist_data,
5296                                      void *key,
5297                                      struct tracing_map_elt *elt)
5298 {
5299         const char *field_name;
5300         unsigned int i;
5301
5302         hist_trigger_print_key(m, hist_data, key, elt);
5303
5304         seq_printf(m, " hitcount: %10llu",
5305                    tracing_map_read_sum(elt, HITCOUNT_IDX));
5306
5307         for (i = 1; i < hist_data->n_vals; i++) {
5308                 field_name = hist_field_name(hist_data->fields[i], 0);
5309
5310                 if (hist_data->fields[i]->flags & HIST_FIELD_FL_VAR ||
5311                     hist_data->fields[i]->flags & HIST_FIELD_FL_EXPR)
5312                         continue;
5313
5314                 if (hist_data->fields[i]->flags & HIST_FIELD_FL_HEX) {
5315                         seq_printf(m, "  %s: %10llx", field_name,
5316                                    tracing_map_read_sum(elt, i));
5317                 } else {
5318                         seq_printf(m, "  %s: %10llu", field_name,
5319                                    tracing_map_read_sum(elt, i));
5320                 }
5321         }
5322
5323         print_actions(m, hist_data, elt);
5324
5325         seq_puts(m, "\n");
5326 }
5327
5328 static int print_entries(struct seq_file *m,
5329                          struct hist_trigger_data *hist_data)
5330 {
5331         struct tracing_map_sort_entry **sort_entries = NULL;
5332         struct tracing_map *map = hist_data->map;
5333         int i, n_entries;
5334
5335         n_entries = tracing_map_sort_entries(map, hist_data->sort_keys,
5336                                              hist_data->n_sort_keys,
5337                                              &sort_entries);
5338         if (n_entries < 0)
5339                 return n_entries;
5340
5341         for (i = 0; i < n_entries; i++)
5342                 hist_trigger_entry_print(m, hist_data,
5343                                          sort_entries[i]->key,
5344                                          sort_entries[i]->elt);
5345
5346         tracing_map_destroy_sort_entries(sort_entries, n_entries);
5347
5348         return n_entries;
5349 }
5350
5351 static void hist_trigger_show(struct seq_file *m,
5352                               struct event_trigger_data *data, int n)
5353 {
5354         struct hist_trigger_data *hist_data;
5355         int n_entries;
5356
5357         if (n > 0)
5358                 seq_puts(m, "\n\n");
5359
5360         seq_puts(m, "# event histogram\n#\n# trigger info: ");
5361         data->ops->print(m, data);
5362         seq_puts(m, "#\n\n");
5363
5364         hist_data = data->private_data;
5365         n_entries = print_entries(m, hist_data);
5366         if (n_entries < 0)
5367                 n_entries = 0;
5368
5369         track_data_snapshot_print(m, hist_data);
5370
5371         seq_printf(m, "\nTotals:\n    Hits: %llu\n    Entries: %u\n    Dropped: %llu\n",
5372                    (u64)atomic64_read(&hist_data->map->hits),
5373                    n_entries, (u64)atomic64_read(&hist_data->map->drops));
5374 }
5375
5376 static int hist_show(struct seq_file *m, void *v)
5377 {
5378         struct event_trigger_data *data;
5379         struct trace_event_file *event_file;
5380         int n = 0, ret = 0;
5381
5382         mutex_lock(&event_mutex);
5383
5384         event_file = event_file_data(m->private);
5385         if (unlikely(!event_file)) {
5386                 ret = -ENODEV;
5387                 goto out_unlock;
5388         }
5389
5390         list_for_each_entry(data, &event_file->triggers, list) {
5391                 if (data->cmd_ops->trigger_type == ETT_EVENT_HIST)
5392                         hist_trigger_show(m, data, n++);
5393         }
5394
5395  out_unlock:
5396         mutex_unlock(&event_mutex);
5397
5398         return ret;
5399 }
5400
5401 static int event_hist_open(struct inode *inode, struct file *file)
5402 {
5403         int ret;
5404
5405         ret = security_locked_down(LOCKDOWN_TRACEFS);
5406         if (ret)
5407                 return ret;
5408
5409         return single_open(file, hist_show, file);
5410 }
5411
5412 const struct file_operations event_hist_fops = {
5413         .open = event_hist_open,
5414         .read = seq_read,
5415         .llseek = seq_lseek,
5416         .release = single_release,
5417 };
5418
5419 #ifdef CONFIG_HIST_TRIGGERS_DEBUG
5420 static void hist_field_debug_show_flags(struct seq_file *m,
5421                                         unsigned long flags)
5422 {
5423         seq_puts(m, "      flags:\n");
5424
5425         if (flags & HIST_FIELD_FL_KEY)
5426                 seq_puts(m, "        HIST_FIELD_FL_KEY\n");
5427         else if (flags & HIST_FIELD_FL_HITCOUNT)
5428                 seq_puts(m, "        VAL: HIST_FIELD_FL_HITCOUNT\n");
5429         else if (flags & HIST_FIELD_FL_VAR)
5430                 seq_puts(m, "        HIST_FIELD_FL_VAR\n");
5431         else if (flags & HIST_FIELD_FL_VAR_REF)
5432                 seq_puts(m, "        HIST_FIELD_FL_VAR_REF\n");
5433         else
5434                 seq_puts(m, "        VAL: normal u64 value\n");
5435
5436         if (flags & HIST_FIELD_FL_ALIAS)
5437                 seq_puts(m, "        HIST_FIELD_FL_ALIAS\n");
5438         else if (flags & HIST_FIELD_FL_CONST)
5439                 seq_puts(m, "        HIST_FIELD_FL_CONST\n");
5440 }
5441
5442 static int hist_field_debug_show(struct seq_file *m,
5443                                  struct hist_field *field, unsigned long flags)
5444 {
5445         if ((field->flags & flags) != flags) {
5446                 seq_printf(m, "ERROR: bad flags - %lx\n", flags);
5447                 return -EINVAL;
5448         }
5449
5450         hist_field_debug_show_flags(m, field->flags);
5451         if (field->field)
5452                 seq_printf(m, "      ftrace_event_field name: %s\n",
5453                            field->field->name);
5454
5455         if (field->flags & HIST_FIELD_FL_VAR) {
5456                 seq_printf(m, "      var.name: %s\n", field->var.name);
5457                 seq_printf(m, "      var.idx (into tracing_map_elt.vars[]): %u\n",
5458                            field->var.idx);
5459         }
5460
5461         if (field->flags & HIST_FIELD_FL_CONST)
5462                 seq_printf(m, "      constant: %llu\n", field->constant);
5463
5464         if (field->flags & HIST_FIELD_FL_ALIAS)
5465                 seq_printf(m, "      var_ref_idx (into hist_data->var_refs[]): %u\n",
5466                            field->var_ref_idx);
5467
5468         if (field->flags & HIST_FIELD_FL_VAR_REF) {
5469                 seq_printf(m, "      name: %s\n", field->name);
5470                 seq_printf(m, "      var.idx (into tracing_map_elt.vars[]): %u\n",
5471                            field->var.idx);
5472                 seq_printf(m, "      var.hist_data: %p\n", field->var.hist_data);
5473                 seq_printf(m, "      var_ref_idx (into hist_data->var_refs[]): %u\n",
5474                            field->var_ref_idx);
5475                 if (field->system)
5476                         seq_printf(m, "      system: %s\n", field->system);
5477                 if (field->event_name)
5478                         seq_printf(m, "      event_name: %s\n", field->event_name);
5479         }
5480
5481         seq_printf(m, "      type: %s\n", field->type);
5482         seq_printf(m, "      size: %u\n", field->size);
5483         seq_printf(m, "      is_signed: %u\n", field->is_signed);
5484
5485         return 0;
5486 }
5487
5488 static int field_var_debug_show(struct seq_file *m,
5489                                 struct field_var *field_var, unsigned int i,
5490                                 bool save_vars)
5491 {
5492         const char *vars_name = save_vars ? "save_vars" : "field_vars";
5493         struct hist_field *field;
5494         int ret = 0;
5495
5496         seq_printf(m, "\n    hist_data->%s[%d]:\n", vars_name, i);
5497
5498         field = field_var->var;
5499
5500         seq_printf(m, "\n      %s[%d].var:\n", vars_name, i);
5501
5502         hist_field_debug_show_flags(m, field->flags);
5503         seq_printf(m, "      var.name: %s\n", field->var.name);
5504         seq_printf(m, "      var.idx (into tracing_map_elt.vars[]): %u\n",
5505                    field->var.idx);
5506
5507         field = field_var->val;
5508
5509         seq_printf(m, "\n      %s[%d].val:\n", vars_name, i);
5510         if (field->field)
5511                 seq_printf(m, "      ftrace_event_field name: %s\n",
5512                            field->field->name);
5513         else {
5514                 ret = -EINVAL;
5515                 goto out;
5516         }
5517
5518         seq_printf(m, "      type: %s\n", field->type);
5519         seq_printf(m, "      size: %u\n", field->size);
5520         seq_printf(m, "      is_signed: %u\n", field->is_signed);
5521 out:
5522         return ret;
5523 }
5524
5525 static int hist_action_debug_show(struct seq_file *m,
5526                                   struct action_data *data, int i)
5527 {
5528         int ret = 0;
5529
5530         if (data->handler == HANDLER_ONMAX ||
5531             data->handler == HANDLER_ONCHANGE) {
5532                 seq_printf(m, "\n    hist_data->actions[%d].track_data.var_ref:\n", i);
5533                 ret = hist_field_debug_show(m, data->track_data.var_ref,
5534                                             HIST_FIELD_FL_VAR_REF);
5535                 if (ret)
5536                         goto out;
5537
5538                 seq_printf(m, "\n    hist_data->actions[%d].track_data.track_var:\n", i);
5539                 ret = hist_field_debug_show(m, data->track_data.track_var,
5540                                             HIST_FIELD_FL_VAR);
5541                 if (ret)
5542                         goto out;
5543         }
5544
5545         if (data->handler == HANDLER_ONMATCH) {
5546                 seq_printf(m, "\n    hist_data->actions[%d].match_data.event_system: %s\n",
5547                            i, data->match_data.event_system);
5548                 seq_printf(m, "    hist_data->actions[%d].match_data.event: %s\n",
5549                            i, data->match_data.event);
5550         }
5551 out:
5552         return ret;
5553 }
5554
5555 static int hist_actions_debug_show(struct seq_file *m,
5556                                    struct hist_trigger_data *hist_data)
5557 {
5558         int i, ret = 0;
5559
5560         if (hist_data->n_actions)
5561                 seq_puts(m, "\n  action tracking variables (for onmax()/onchange()/onmatch()):\n");
5562
5563         for (i = 0; i < hist_data->n_actions; i++) {
5564                 struct action_data *action = hist_data->actions[i];
5565
5566                 ret = hist_action_debug_show(m, action, i);
5567                 if (ret)
5568                         goto out;
5569         }
5570
5571         if (hist_data->n_save_vars)
5572                 seq_puts(m, "\n  save action variables (save() params):\n");
5573
5574         for (i = 0; i < hist_data->n_save_vars; i++) {
5575                 ret = field_var_debug_show(m, hist_data->save_vars[i], i, true);
5576                 if (ret)
5577                         goto out;
5578         }
5579 out:
5580         return ret;
5581 }
5582
5583 static void hist_trigger_debug_show(struct seq_file *m,
5584                                     struct event_trigger_data *data, int n)
5585 {
5586         struct hist_trigger_data *hist_data;
5587         int i, ret;
5588
5589         if (n > 0)
5590                 seq_puts(m, "\n\n");
5591
5592         seq_puts(m, "# event histogram\n#\n# trigger info: ");
5593         data->ops->print(m, data);
5594         seq_puts(m, "#\n\n");
5595
5596         hist_data = data->private_data;
5597
5598         seq_printf(m, "hist_data: %p\n\n", hist_data);
5599         seq_printf(m, "  n_vals: %u\n", hist_data->n_vals);
5600         seq_printf(m, "  n_keys: %u\n", hist_data->n_keys);
5601         seq_printf(m, "  n_fields: %u\n", hist_data->n_fields);
5602
5603         seq_puts(m, "\n  val fields:\n\n");
5604
5605         seq_puts(m, "    hist_data->fields[0]:\n");
5606         ret = hist_field_debug_show(m, hist_data->fields[0],
5607                                     HIST_FIELD_FL_HITCOUNT);
5608         if (ret)
5609                 return;
5610
5611         for (i = 1; i < hist_data->n_vals; i++) {
5612                 seq_printf(m, "\n    hist_data->fields[%d]:\n", i);
5613                 ret = hist_field_debug_show(m, hist_data->fields[i], 0);
5614                 if (ret)
5615                         return;
5616         }
5617
5618         seq_puts(m, "\n  key fields:\n");
5619
5620         for (i = hist_data->n_vals; i < hist_data->n_fields; i++) {
5621                 seq_printf(m, "\n    hist_data->fields[%d]:\n", i);
5622                 ret = hist_field_debug_show(m, hist_data->fields[i],
5623                                             HIST_FIELD_FL_KEY);
5624                 if (ret)
5625                         return;
5626         }
5627
5628         if (hist_data->n_var_refs)
5629                 seq_puts(m, "\n  variable reference fields:\n");
5630
5631         for (i = 0; i < hist_data->n_var_refs; i++) {
5632                 seq_printf(m, "\n    hist_data->var_refs[%d]:\n", i);
5633                 ret = hist_field_debug_show(m, hist_data->var_refs[i],
5634                                             HIST_FIELD_FL_VAR_REF);
5635                 if (ret)
5636                         return;
5637         }
5638
5639         if (hist_data->n_field_vars)
5640                 seq_puts(m, "\n  field variables:\n");
5641
5642         for (i = 0; i < hist_data->n_field_vars; i++) {
5643                 ret = field_var_debug_show(m, hist_data->field_vars[i], i, false);
5644                 if (ret)
5645                         return;
5646         }
5647
5648         ret = hist_actions_debug_show(m, hist_data);
5649         if (ret)
5650                 return;
5651 }
5652
5653 static int hist_debug_show(struct seq_file *m, void *v)
5654 {
5655         struct event_trigger_data *data;
5656         struct trace_event_file *event_file;
5657         int n = 0, ret = 0;
5658
5659         mutex_lock(&event_mutex);
5660
5661         event_file = event_file_data(m->private);
5662         if (unlikely(!event_file)) {
5663                 ret = -ENODEV;
5664                 goto out_unlock;
5665         }
5666
5667         list_for_each_entry(data, &event_file->triggers, list) {
5668                 if (data->cmd_ops->trigger_type == ETT_EVENT_HIST)
5669                         hist_trigger_debug_show(m, data, n++);
5670         }
5671
5672  out_unlock:
5673         mutex_unlock(&event_mutex);
5674
5675         return ret;
5676 }
5677
5678 static int event_hist_debug_open(struct inode *inode, struct file *file)
5679 {
5680         int ret;
5681
5682         ret = security_locked_down(LOCKDOWN_TRACEFS);
5683         if (ret)
5684                 return ret;
5685
5686         return single_open(file, hist_debug_show, file);
5687 }
5688
5689 const struct file_operations event_hist_debug_fops = {
5690         .open = event_hist_debug_open,
5691         .read = seq_read,
5692         .llseek = seq_lseek,
5693         .release = single_release,
5694 };
5695 #endif
5696
5697 static void hist_field_print(struct seq_file *m, struct hist_field *hist_field)
5698 {
5699         const char *field_name = hist_field_name(hist_field, 0);
5700
5701         if (hist_field->var.name)
5702                 seq_printf(m, "%s=", hist_field->var.name);
5703
5704         if (hist_field->flags & HIST_FIELD_FL_CPU)
5705                 seq_puts(m, "common_cpu");
5706         else if (hist_field->flags & HIST_FIELD_FL_CONST)
5707                 seq_printf(m, "%llu", hist_field->constant);
5708         else if (field_name) {
5709                 if (hist_field->flags & HIST_FIELD_FL_VAR_REF ||
5710                     hist_field->flags & HIST_FIELD_FL_ALIAS)
5711                         seq_putc(m, '$');
5712                 seq_printf(m, "%s", field_name);
5713         } else if (hist_field->flags & HIST_FIELD_FL_TIMESTAMP)
5714                 seq_puts(m, "common_timestamp");
5715
5716         if (hist_field->flags) {
5717                 if (!(hist_field->flags & HIST_FIELD_FL_VAR_REF) &&
5718                     !(hist_field->flags & HIST_FIELD_FL_EXPR)) {
5719                         const char *flags = get_hist_field_flags(hist_field);
5720
5721                         if (flags)
5722                                 seq_printf(m, ".%s", flags);
5723                 }
5724         }
5725         if (hist_field->buckets)
5726                 seq_printf(m, "=%ld", hist_field->buckets);
5727 }
5728
5729 static int event_hist_trigger_print(struct seq_file *m,
5730                                     struct event_trigger_data *data)
5731 {
5732         struct hist_trigger_data *hist_data = data->private_data;
5733         struct hist_field *field;
5734         bool have_var = false;
5735         unsigned int i;
5736
5737         seq_puts(m, HIST_PREFIX);
5738
5739         if (data->name)
5740                 seq_printf(m, "%s:", data->name);
5741
5742         seq_puts(m, "keys=");
5743
5744         for_each_hist_key_field(i, hist_data) {
5745                 field = hist_data->fields[i];
5746
5747                 if (i > hist_data->n_vals)
5748                         seq_puts(m, ",");
5749
5750                 if (field->flags & HIST_FIELD_FL_STACKTRACE)
5751                         seq_puts(m, "stacktrace");
5752                 else
5753                         hist_field_print(m, field);
5754         }
5755
5756         seq_puts(m, ":vals=");
5757
5758         for_each_hist_val_field(i, hist_data) {
5759                 field = hist_data->fields[i];
5760                 if (field->flags & HIST_FIELD_FL_VAR) {
5761                         have_var = true;
5762                         continue;
5763                 }
5764
5765                 if (i == HITCOUNT_IDX)
5766                         seq_puts(m, "hitcount");
5767                 else {
5768                         seq_puts(m, ",");
5769                         hist_field_print(m, field);
5770                 }
5771         }
5772
5773         if (have_var) {
5774                 unsigned int n = 0;
5775
5776                 seq_puts(m, ":");
5777
5778                 for_each_hist_val_field(i, hist_data) {
5779                         field = hist_data->fields[i];
5780
5781                         if (field->flags & HIST_FIELD_FL_VAR) {
5782                                 if (n++)
5783                                         seq_puts(m, ",");
5784                                 hist_field_print(m, field);
5785                         }
5786                 }
5787         }
5788
5789         seq_puts(m, ":sort=");
5790
5791         for (i = 0; i < hist_data->n_sort_keys; i++) {
5792                 struct tracing_map_sort_key *sort_key;
5793                 unsigned int idx, first_key_idx;
5794
5795                 /* skip VAR vals */
5796                 first_key_idx = hist_data->n_vals - hist_data->n_vars;
5797
5798                 sort_key = &hist_data->sort_keys[i];
5799                 idx = sort_key->field_idx;
5800
5801                 if (WARN_ON(idx >= HIST_FIELDS_MAX))
5802                         return -EINVAL;
5803
5804                 if (i > 0)
5805                         seq_puts(m, ",");
5806
5807                 if (idx == HITCOUNT_IDX)
5808                         seq_puts(m, "hitcount");
5809                 else {
5810                         if (idx >= first_key_idx)
5811                                 idx += hist_data->n_vars;
5812                         hist_field_print(m, hist_data->fields[idx]);
5813                 }
5814
5815                 if (sort_key->descending)
5816                         seq_puts(m, ".descending");
5817         }
5818         seq_printf(m, ":size=%u", (1 << hist_data->map->map_bits));
5819         if (hist_data->enable_timestamps)
5820                 seq_printf(m, ":clock=%s", hist_data->attrs->clock);
5821
5822         print_actions_spec(m, hist_data);
5823
5824         if (data->filter_str)
5825                 seq_printf(m, " if %s", data->filter_str);
5826
5827         if (data->paused)
5828                 seq_puts(m, " [paused]");
5829         else
5830                 seq_puts(m, " [active]");
5831
5832         seq_putc(m, '\n');
5833
5834         return 0;
5835 }
5836
5837 static int event_hist_trigger_init(struct event_trigger_data *data)
5838 {
5839         struct hist_trigger_data *hist_data = data->private_data;
5840
5841         if (!data->ref && hist_data->attrs->name)
5842                 save_named_trigger(hist_data->attrs->name, data);
5843
5844         data->ref++;
5845
5846         return 0;
5847 }
5848
5849 static void unregister_field_var_hists(struct hist_trigger_data *hist_data)
5850 {
5851         struct trace_event_file *file;
5852         unsigned int i;
5853         char *cmd;
5854         int ret;
5855
5856         for (i = 0; i < hist_data->n_field_var_hists; i++) {
5857                 file = hist_data->field_var_hists[i]->hist_data->event_file;
5858                 cmd = hist_data->field_var_hists[i]->cmd;
5859                 ret = event_hist_trigger_parse(&trigger_hist_cmd, file,
5860                                                "!hist", "hist", cmd);
5861                 WARN_ON_ONCE(ret < 0);
5862         }
5863 }
5864
5865 static void event_hist_trigger_free(struct event_trigger_data *data)
5866 {
5867         struct hist_trigger_data *hist_data = data->private_data;
5868
5869         if (WARN_ON_ONCE(data->ref <= 0))
5870                 return;
5871
5872         data->ref--;
5873         if (!data->ref) {
5874                 if (data->name)
5875                         del_named_trigger(data);
5876
5877                 trigger_data_free(data);
5878
5879                 remove_hist_vars(hist_data);
5880
5881                 unregister_field_var_hists(hist_data);
5882
5883                 destroy_hist_data(hist_data);
5884         }
5885 }
5886
5887 static struct event_trigger_ops event_hist_trigger_ops = {
5888         .trigger                = event_hist_trigger,
5889         .print                  = event_hist_trigger_print,
5890         .init                   = event_hist_trigger_init,
5891         .free                   = event_hist_trigger_free,
5892 };
5893
5894 static int event_hist_trigger_named_init(struct event_trigger_data *data)
5895 {
5896         data->ref++;
5897
5898         save_named_trigger(data->named_data->name, data);
5899
5900         event_hist_trigger_init(data->named_data);
5901
5902         return 0;
5903 }
5904
5905 static void event_hist_trigger_named_free(struct event_trigger_data *data)
5906 {
5907         if (WARN_ON_ONCE(data->ref <= 0))
5908                 return;
5909
5910         event_hist_trigger_free(data->named_data);
5911
5912         data->ref--;
5913         if (!data->ref) {
5914                 del_named_trigger(data);
5915                 trigger_data_free(data);
5916         }
5917 }
5918
5919 static struct event_trigger_ops event_hist_trigger_named_ops = {
5920         .trigger                = event_hist_trigger,
5921         .print                  = event_hist_trigger_print,
5922         .init                   = event_hist_trigger_named_init,
5923         .free                   = event_hist_trigger_named_free,
5924 };
5925
5926 static struct event_trigger_ops *event_hist_get_trigger_ops(char *cmd,
5927                                                             char *param)
5928 {
5929         return &event_hist_trigger_ops;
5930 }
5931
5932 static void hist_clear(struct event_trigger_data *data)
5933 {
5934         struct hist_trigger_data *hist_data = data->private_data;
5935
5936         if (data->name)
5937                 pause_named_trigger(data);
5938
5939         tracepoint_synchronize_unregister();
5940
5941         tracing_map_clear(hist_data->map);
5942
5943         if (data->name)
5944                 unpause_named_trigger(data);
5945 }
5946
5947 static bool compatible_field(struct ftrace_event_field *field,
5948                              struct ftrace_event_field *test_field)
5949 {
5950         if (field == test_field)
5951                 return true;
5952         if (field == NULL || test_field == NULL)
5953                 return false;
5954         if (strcmp(field->name, test_field->name) != 0)
5955                 return false;
5956         if (strcmp(field->type, test_field->type) != 0)
5957                 return false;
5958         if (field->size != test_field->size)
5959                 return false;
5960         if (field->is_signed != test_field->is_signed)
5961                 return false;
5962
5963         return true;
5964 }
5965
5966 static bool hist_trigger_match(struct event_trigger_data *data,
5967                                struct event_trigger_data *data_test,
5968                                struct event_trigger_data *named_data,
5969                                bool ignore_filter)
5970 {
5971         struct tracing_map_sort_key *sort_key, *sort_key_test;
5972         struct hist_trigger_data *hist_data, *hist_data_test;
5973         struct hist_field *key_field, *key_field_test;
5974         unsigned int i;
5975
5976         if (named_data && (named_data != data_test) &&
5977             (named_data != data_test->named_data))
5978                 return false;
5979
5980         if (!named_data && is_named_trigger(data_test))
5981                 return false;
5982
5983         hist_data = data->private_data;
5984         hist_data_test = data_test->private_data;
5985
5986         if (hist_data->n_vals != hist_data_test->n_vals ||
5987             hist_data->n_fields != hist_data_test->n_fields ||
5988             hist_data->n_sort_keys != hist_data_test->n_sort_keys)
5989                 return false;
5990
5991         if (!ignore_filter) {
5992                 if ((data->filter_str && !data_test->filter_str) ||
5993                    (!data->filter_str && data_test->filter_str))
5994                         return false;
5995         }
5996
5997         for_each_hist_field(i, hist_data) {
5998                 key_field = hist_data->fields[i];
5999                 key_field_test = hist_data_test->fields[i];
6000
6001                 if (key_field->flags != key_field_test->flags)
6002                         return false;
6003                 if (!compatible_field(key_field->field, key_field_test->field))
6004                         return false;
6005                 if (key_field->offset != key_field_test->offset)
6006                         return false;
6007                 if (key_field->size != key_field_test->size)
6008                         return false;
6009                 if (key_field->is_signed != key_field_test->is_signed)
6010                         return false;
6011                 if (!!key_field->var.name != !!key_field_test->var.name)
6012                         return false;
6013                 if (key_field->var.name &&
6014                     strcmp(key_field->var.name, key_field_test->var.name) != 0)
6015                         return false;
6016         }
6017
6018         for (i = 0; i < hist_data->n_sort_keys; i++) {
6019                 sort_key = &hist_data->sort_keys[i];
6020                 sort_key_test = &hist_data_test->sort_keys[i];
6021
6022                 if (sort_key->field_idx != sort_key_test->field_idx ||
6023                     sort_key->descending != sort_key_test->descending)
6024                         return false;
6025         }
6026
6027         if (!ignore_filter && data->filter_str &&
6028             (strcmp(data->filter_str, data_test->filter_str) != 0))
6029                 return false;
6030
6031         if (!actions_match(hist_data, hist_data_test))
6032                 return false;
6033
6034         return true;
6035 }
6036
6037 static bool existing_hist_update_only(char *glob,
6038                                       struct event_trigger_data *data,
6039                                       struct trace_event_file *file)
6040 {
6041         struct hist_trigger_data *hist_data = data->private_data;
6042         struct event_trigger_data *test, *named_data = NULL;
6043         bool updated = false;
6044
6045         if (!hist_data->attrs->pause && !hist_data->attrs->cont &&
6046             !hist_data->attrs->clear)
6047                 goto out;
6048
6049         if (hist_data->attrs->name) {
6050                 named_data = find_named_trigger(hist_data->attrs->name);
6051                 if (named_data) {
6052                         if (!hist_trigger_match(data, named_data, named_data,
6053                                                 true))
6054                                 goto out;
6055                 }
6056         }
6057
6058         if (hist_data->attrs->name && !named_data)
6059                 goto out;
6060
6061         list_for_each_entry(test, &file->triggers, list) {
6062                 if (test->cmd_ops->trigger_type == ETT_EVENT_HIST) {
6063                         if (!hist_trigger_match(data, test, named_data, false))
6064                                 continue;
6065                         if (hist_data->attrs->pause)
6066                                 test->paused = true;
6067                         else if (hist_data->attrs->cont)
6068                                 test->paused = false;
6069                         else if (hist_data->attrs->clear)
6070                                 hist_clear(test);
6071                         updated = true;
6072                         goto out;
6073                 }
6074         }
6075  out:
6076         return updated;
6077 }
6078
6079 static int hist_register_trigger(char *glob,
6080                                  struct event_trigger_data *data,
6081                                  struct trace_event_file *file)
6082 {
6083         struct hist_trigger_data *hist_data = data->private_data;
6084         struct event_trigger_data *test, *named_data = NULL;
6085         struct trace_array *tr = file->tr;
6086         int ret = 0;
6087
6088         if (hist_data->attrs->name) {
6089                 named_data = find_named_trigger(hist_data->attrs->name);
6090                 if (named_data) {
6091                         if (!hist_trigger_match(data, named_data, named_data,
6092                                                 true)) {
6093                                 hist_err(tr, HIST_ERR_NAMED_MISMATCH, errpos(hist_data->attrs->name));
6094                                 ret = -EINVAL;
6095                                 goto out;
6096                         }
6097                 }
6098         }
6099
6100         if (hist_data->attrs->name && !named_data)
6101                 goto new;
6102
6103         lockdep_assert_held(&event_mutex);
6104
6105         list_for_each_entry(test, &file->triggers, list) {
6106                 if (test->cmd_ops->trigger_type == ETT_EVENT_HIST) {
6107                         if (hist_trigger_match(data, test, named_data, false)) {
6108                                 hist_err(tr, HIST_ERR_TRIGGER_EEXIST, 0);
6109                                 ret = -EEXIST;
6110                                 goto out;
6111                         }
6112                 }
6113         }
6114  new:
6115         if (hist_data->attrs->cont || hist_data->attrs->clear) {
6116                 hist_err(tr, HIST_ERR_TRIGGER_ENOENT_CLEAR, 0);
6117                 ret = -ENOENT;
6118                 goto out;
6119         }
6120
6121         if (hist_data->attrs->pause)
6122                 data->paused = true;
6123
6124         if (named_data) {
6125                 data->private_data = named_data->private_data;
6126                 set_named_trigger_data(data, named_data);
6127                 data->ops = &event_hist_trigger_named_ops;
6128         }
6129
6130         if (data->ops->init) {
6131                 ret = data->ops->init(data);
6132                 if (ret < 0)
6133                         goto out;
6134         }
6135
6136         if (hist_data->enable_timestamps) {
6137                 char *clock = hist_data->attrs->clock;
6138
6139                 ret = tracing_set_clock(file->tr, hist_data->attrs->clock);
6140                 if (ret) {
6141                         hist_err(tr, HIST_ERR_SET_CLOCK_FAIL, errpos(clock));
6142                         goto out;
6143                 }
6144
6145                 tracing_set_filter_buffering(file->tr, true);
6146         }
6147
6148         if (named_data)
6149                 destroy_hist_data(hist_data);
6150  out:
6151         return ret;
6152 }
6153
6154 static int hist_trigger_enable(struct event_trigger_data *data,
6155                                struct trace_event_file *file)
6156 {
6157         int ret = 0;
6158
6159         list_add_tail_rcu(&data->list, &file->triggers);
6160
6161         update_cond_flag(file);
6162
6163         if (trace_event_trigger_enable_disable(file, 1) < 0) {
6164                 list_del_rcu(&data->list);
6165                 update_cond_flag(file);
6166                 ret--;
6167         }
6168
6169         return ret;
6170 }
6171
6172 static bool have_hist_trigger_match(struct event_trigger_data *data,
6173                                     struct trace_event_file *file)
6174 {
6175         struct hist_trigger_data *hist_data = data->private_data;
6176         struct event_trigger_data *test, *named_data = NULL;
6177         bool match = false;
6178
6179         lockdep_assert_held(&event_mutex);
6180
6181         if (hist_data->attrs->name)
6182                 named_data = find_named_trigger(hist_data->attrs->name);
6183
6184         list_for_each_entry(test, &file->triggers, list) {
6185                 if (test->cmd_ops->trigger_type == ETT_EVENT_HIST) {
6186                         if (hist_trigger_match(data, test, named_data, false)) {
6187                                 match = true;
6188                                 break;
6189                         }
6190                 }
6191         }
6192
6193         return match;
6194 }
6195
6196 static bool hist_trigger_check_refs(struct event_trigger_data *data,
6197                                     struct trace_event_file *file)
6198 {
6199         struct hist_trigger_data *hist_data = data->private_data;
6200         struct event_trigger_data *test, *named_data = NULL;
6201
6202         lockdep_assert_held(&event_mutex);
6203
6204         if (hist_data->attrs->name)
6205                 named_data = find_named_trigger(hist_data->attrs->name);
6206
6207         list_for_each_entry(test, &file->triggers, list) {
6208                 if (test->cmd_ops->trigger_type == ETT_EVENT_HIST) {
6209                         if (!hist_trigger_match(data, test, named_data, false))
6210                                 continue;
6211                         hist_data = test->private_data;
6212                         if (check_var_refs(hist_data))
6213                                 return true;
6214                         break;
6215                 }
6216         }
6217
6218         return false;
6219 }
6220
6221 static void hist_unregister_trigger(char *glob,
6222                                     struct event_trigger_data *data,
6223                                     struct trace_event_file *file)
6224 {
6225         struct event_trigger_data *test = NULL, *iter, *named_data = NULL;
6226         struct hist_trigger_data *hist_data = data->private_data;
6227
6228         lockdep_assert_held(&event_mutex);
6229
6230         if (hist_data->attrs->name)
6231                 named_data = find_named_trigger(hist_data->attrs->name);
6232
6233         list_for_each_entry(iter, &file->triggers, list) {
6234                 if (iter->cmd_ops->trigger_type == ETT_EVENT_HIST) {
6235                         if (!hist_trigger_match(data, iter, named_data, false))
6236                                 continue;
6237                         test = iter;
6238                         list_del_rcu(&test->list);
6239                         trace_event_trigger_enable_disable(file, 0);
6240                         update_cond_flag(file);
6241                         break;
6242                 }
6243         }
6244
6245         if (test && test->ops->free)
6246                 test->ops->free(test);
6247
6248         if (hist_data->enable_timestamps) {
6249                 if (!hist_data->remove || test)
6250                         tracing_set_filter_buffering(file->tr, false);
6251         }
6252 }
6253
6254 static bool hist_file_check_refs(struct trace_event_file *file)
6255 {
6256         struct hist_trigger_data *hist_data;
6257         struct event_trigger_data *test;
6258
6259         lockdep_assert_held(&event_mutex);
6260
6261         list_for_each_entry(test, &file->triggers, list) {
6262                 if (test->cmd_ops->trigger_type == ETT_EVENT_HIST) {
6263                         hist_data = test->private_data;
6264                         if (check_var_refs(hist_data))
6265                                 return true;
6266                 }
6267         }
6268
6269         return false;
6270 }
6271
6272 static void hist_unreg_all(struct trace_event_file *file)
6273 {
6274         struct event_trigger_data *test, *n;
6275         struct hist_trigger_data *hist_data;
6276         struct synth_event *se;
6277         const char *se_name;
6278
6279         lockdep_assert_held(&event_mutex);
6280
6281         if (hist_file_check_refs(file))
6282                 return;
6283
6284         list_for_each_entry_safe(test, n, &file->triggers, list) {
6285                 if (test->cmd_ops->trigger_type == ETT_EVENT_HIST) {
6286                         hist_data = test->private_data;
6287                         list_del_rcu(&test->list);
6288                         trace_event_trigger_enable_disable(file, 0);
6289
6290                         se_name = trace_event_name(file->event_call);
6291                         se = find_synth_event(se_name);
6292                         if (se)
6293                                 se->ref--;
6294
6295                         update_cond_flag(file);
6296                         if (hist_data->enable_timestamps)
6297                                 tracing_set_filter_buffering(file->tr, false);
6298                         if (test->ops->free)
6299                                 test->ops->free(test);
6300                 }
6301         }
6302 }
6303
6304 static int event_hist_trigger_parse(struct event_command *cmd_ops,
6305                                     struct trace_event_file *file,
6306                                     char *glob, char *cmd,
6307                                     char *param_and_filter)
6308 {
6309         unsigned int hist_trigger_bits = TRACING_MAP_BITS_DEFAULT;
6310         struct event_trigger_data *trigger_data;
6311         struct hist_trigger_attrs *attrs;
6312         struct hist_trigger_data *hist_data;
6313         char *param, *filter, *p, *start;
6314         struct synth_event *se;
6315         const char *se_name;
6316         bool remove;
6317         int ret = 0;
6318
6319         lockdep_assert_held(&event_mutex);
6320
6321         if (WARN_ON(!glob))
6322                 return -EINVAL;
6323
6324         if (glob[0]) {
6325                 hist_err_clear();
6326                 last_cmd_set(file, param_and_filter);
6327         }
6328
6329         remove = event_trigger_check_remove(glob);
6330
6331         if (event_trigger_empty_param(param_and_filter))
6332                 return -EINVAL;
6333
6334         /*
6335          * separate the trigger from the filter (k:v [if filter])
6336          * allowing for whitespace in the trigger
6337          */
6338         p = param = param_and_filter;
6339         do {
6340                 p = strstr(p, "if");
6341                 if (!p)
6342                         break;
6343                 if (p == param_and_filter)
6344                         return -EINVAL;
6345                 if (*(p - 1) != ' ' && *(p - 1) != '\t') {
6346                         p++;
6347                         continue;
6348                 }
6349                 if (p >= param_and_filter + strlen(param_and_filter) - (sizeof("if") - 1) - 1)
6350                         return -EINVAL;
6351                 if (*(p + sizeof("if") - 1) != ' ' && *(p + sizeof("if") - 1) != '\t') {
6352                         p++;
6353                         continue;
6354                 }
6355                 break;
6356         } while (1);
6357
6358         if (!p)
6359                 filter = NULL;
6360         else {
6361                 *(p - 1) = '\0';
6362                 filter = strstrip(p);
6363                 param = strstrip(param);
6364         }
6365
6366         /*
6367          * To simplify arithmetic expression parsing, replace occurrences of
6368          * '.sym-offset' modifier with '.symXoffset'
6369          */
6370         start = strstr(param, ".sym-offset");
6371         while (start) {
6372                 *(start + 4) = 'X';
6373                 start = strstr(start + 11, ".sym-offset");
6374         }
6375
6376         attrs = parse_hist_trigger_attrs(file->tr, param);
6377         if (IS_ERR(attrs))
6378                 return PTR_ERR(attrs);
6379
6380         if (attrs->map_bits)
6381                 hist_trigger_bits = attrs->map_bits;
6382
6383         hist_data = create_hist_data(hist_trigger_bits, attrs, file, remove);
6384         if (IS_ERR(hist_data)) {
6385                 destroy_hist_trigger_attrs(attrs);
6386                 return PTR_ERR(hist_data);
6387         }
6388
6389         trigger_data = event_trigger_alloc(cmd_ops, cmd, param, hist_data);
6390         if (!trigger_data) {
6391                 ret = -ENOMEM;
6392                 goto out_free;
6393         }
6394
6395         ret = event_trigger_set_filter(cmd_ops, file, filter, trigger_data);
6396         if (ret < 0)
6397                 goto out_free;
6398
6399         if (remove) {
6400                 if (!have_hist_trigger_match(trigger_data, file))
6401                         goto out_free;
6402
6403                 if (hist_trigger_check_refs(trigger_data, file)) {
6404                         ret = -EBUSY;
6405                         goto out_free;
6406                 }
6407
6408                 event_trigger_unregister(cmd_ops, file, glob+1, trigger_data);
6409                 se_name = trace_event_name(file->event_call);
6410                 se = find_synth_event(se_name);
6411                 if (se)
6412                         se->ref--;
6413                 ret = 0;
6414                 goto out_free;
6415         }
6416
6417         if (existing_hist_update_only(glob, trigger_data, file))
6418                 goto out_free;
6419
6420         ret = event_trigger_register(cmd_ops, file, glob, trigger_data);
6421         if (ret < 0)
6422                 goto out_free;
6423
6424         if (get_named_trigger_data(trigger_data))
6425                 goto enable;
6426
6427         if (has_hist_vars(hist_data))
6428                 save_hist_vars(hist_data);
6429
6430         ret = create_actions(hist_data);
6431         if (ret)
6432                 goto out_unreg;
6433
6434         ret = tracing_map_init(hist_data->map);
6435         if (ret)
6436                 goto out_unreg;
6437 enable:
6438         ret = hist_trigger_enable(trigger_data, file);
6439         if (ret)
6440                 goto out_unreg;
6441
6442         se_name = trace_event_name(file->event_call);
6443         se = find_synth_event(se_name);
6444         if (se)
6445                 se->ref++;
6446  out:
6447         if (ret == 0 && glob[0])
6448                 hist_err_clear();
6449
6450         return ret;
6451  out_unreg:
6452         event_trigger_unregister(cmd_ops, file, glob+1, trigger_data);
6453  out_free:
6454         event_trigger_reset_filter(cmd_ops, trigger_data);
6455
6456         remove_hist_vars(hist_data);
6457
6458         kfree(trigger_data);
6459
6460         destroy_hist_data(hist_data);
6461         goto out;
6462 }
6463
6464 static struct event_command trigger_hist_cmd = {
6465         .name                   = "hist",
6466         .trigger_type           = ETT_EVENT_HIST,
6467         .flags                  = EVENT_CMD_FL_NEEDS_REC,
6468         .parse                  = event_hist_trigger_parse,
6469         .reg                    = hist_register_trigger,
6470         .unreg                  = hist_unregister_trigger,
6471         .unreg_all              = hist_unreg_all,
6472         .get_trigger_ops        = event_hist_get_trigger_ops,
6473         .set_filter             = set_trigger_filter,
6474 };
6475
6476 __init int register_trigger_hist_cmd(void)
6477 {
6478         int ret;
6479
6480         ret = register_event_command(&trigger_hist_cmd);
6481         WARN_ON(ret < 0);
6482
6483         return ret;
6484 }
6485
6486 static void
6487 hist_enable_trigger(struct event_trigger_data *data,
6488                     struct trace_buffer *buffer,  void *rec,
6489                     struct ring_buffer_event *event)
6490 {
6491         struct enable_trigger_data *enable_data = data->private_data;
6492         struct event_trigger_data *test;
6493
6494         list_for_each_entry_rcu(test, &enable_data->file->triggers, list,
6495                                 lockdep_is_held(&event_mutex)) {
6496                 if (test->cmd_ops->trigger_type == ETT_EVENT_HIST) {
6497                         if (enable_data->enable)
6498                                 test->paused = false;
6499                         else
6500                                 test->paused = true;
6501                 }
6502         }
6503 }
6504
6505 static void
6506 hist_enable_count_trigger(struct event_trigger_data *data,
6507                           struct trace_buffer *buffer,  void *rec,
6508                           struct ring_buffer_event *event)
6509 {
6510         if (!data->count)
6511                 return;
6512
6513         if (data->count != -1)
6514                 (data->count)--;
6515
6516         hist_enable_trigger(data, buffer, rec, event);
6517 }
6518
6519 static struct event_trigger_ops hist_enable_trigger_ops = {
6520         .trigger                = hist_enable_trigger,
6521         .print                  = event_enable_trigger_print,
6522         .init                   = event_trigger_init,
6523         .free                   = event_enable_trigger_free,
6524 };
6525
6526 static struct event_trigger_ops hist_enable_count_trigger_ops = {
6527         .trigger                = hist_enable_count_trigger,
6528         .print                  = event_enable_trigger_print,
6529         .init                   = event_trigger_init,
6530         .free                   = event_enable_trigger_free,
6531 };
6532
6533 static struct event_trigger_ops hist_disable_trigger_ops = {
6534         .trigger                = hist_enable_trigger,
6535         .print                  = event_enable_trigger_print,
6536         .init                   = event_trigger_init,
6537         .free                   = event_enable_trigger_free,
6538 };
6539
6540 static struct event_trigger_ops hist_disable_count_trigger_ops = {
6541         .trigger                = hist_enable_count_trigger,
6542         .print                  = event_enable_trigger_print,
6543         .init                   = event_trigger_init,
6544         .free                   = event_enable_trigger_free,
6545 };
6546
6547 static struct event_trigger_ops *
6548 hist_enable_get_trigger_ops(char *cmd, char *param)
6549 {
6550         struct event_trigger_ops *ops;
6551         bool enable;
6552
6553         enable = (strcmp(cmd, ENABLE_HIST_STR) == 0);
6554
6555         if (enable)
6556                 ops = param ? &hist_enable_count_trigger_ops :
6557                         &hist_enable_trigger_ops;
6558         else
6559                 ops = param ? &hist_disable_count_trigger_ops :
6560                         &hist_disable_trigger_ops;
6561
6562         return ops;
6563 }
6564
6565 static void hist_enable_unreg_all(struct trace_event_file *file)
6566 {
6567         struct event_trigger_data *test, *n;
6568
6569         list_for_each_entry_safe(test, n, &file->triggers, list) {
6570                 if (test->cmd_ops->trigger_type == ETT_HIST_ENABLE) {
6571                         list_del_rcu(&test->list);
6572                         update_cond_flag(file);
6573                         trace_event_trigger_enable_disable(file, 0);
6574                         if (test->ops->free)
6575                                 test->ops->free(test);
6576                 }
6577         }
6578 }
6579
6580 static struct event_command trigger_hist_enable_cmd = {
6581         .name                   = ENABLE_HIST_STR,
6582         .trigger_type           = ETT_HIST_ENABLE,
6583         .parse                  = event_enable_trigger_parse,
6584         .reg                    = event_enable_register_trigger,
6585         .unreg                  = event_enable_unregister_trigger,
6586         .unreg_all              = hist_enable_unreg_all,
6587         .get_trigger_ops        = hist_enable_get_trigger_ops,
6588         .set_filter             = set_trigger_filter,
6589 };
6590
6591 static struct event_command trigger_hist_disable_cmd = {
6592         .name                   = DISABLE_HIST_STR,
6593         .trigger_type           = ETT_HIST_ENABLE,
6594         .parse                  = event_enable_trigger_parse,
6595         .reg                    = event_enable_register_trigger,
6596         .unreg                  = event_enable_unregister_trigger,
6597         .unreg_all              = hist_enable_unreg_all,
6598         .get_trigger_ops        = hist_enable_get_trigger_ops,
6599         .set_filter             = set_trigger_filter,
6600 };
6601
6602 static __init void unregister_trigger_hist_enable_disable_cmds(void)
6603 {
6604         unregister_event_command(&trigger_hist_enable_cmd);
6605         unregister_event_command(&trigger_hist_disable_cmd);
6606 }
6607
6608 __init int register_trigger_hist_enable_disable_cmds(void)
6609 {
6610         int ret;
6611
6612         ret = register_event_command(&trigger_hist_enable_cmd);
6613         if (WARN_ON(ret < 0))
6614                 return ret;
6615         ret = register_event_command(&trigger_hist_disable_cmd);
6616         if (WARN_ON(ret < 0))
6617                 unregister_trigger_hist_enable_disable_cmds();
6618
6619         return ret;
6620 }