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