GNU Linux-libre 4.19.245-gnu1
[releases.git] / kernel / trace / trace_events_filter.c
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * trace_events_filter - generic event filtering
4  *
5  * Copyright (C) 2009 Tom Zanussi <tzanussi@gmail.com>
6  */
7
8 #include <linux/module.h>
9 #include <linux/ctype.h>
10 #include <linux/mutex.h>
11 #include <linux/perf_event.h>
12 #include <linux/slab.h>
13
14 #include "trace.h"
15 #include "trace_output.h"
16
17 #define DEFAULT_SYS_FILTER_MESSAGE                                      \
18         "### global filter ###\n"                                       \
19         "# Use this to set filters for multiple events.\n"              \
20         "# Only events with the given fields will be affected.\n"       \
21         "# If no events are modified, an error message will be displayed here"
22
23 /* Due to token parsing '<=' must be before '<' and '>=' must be before '>' */
24 #define OPS                                     \
25         C( OP_GLOB,     "~"  ),                 \
26         C( OP_NE,       "!=" ),                 \
27         C( OP_EQ,       "==" ),                 \
28         C( OP_LE,       "<=" ),                 \
29         C( OP_LT,       "<"  ),                 \
30         C( OP_GE,       ">=" ),                 \
31         C( OP_GT,       ">"  ),                 \
32         C( OP_BAND,     "&"  ),                 \
33         C( OP_MAX,      NULL )
34
35 #undef C
36 #define C(a, b) a
37
38 enum filter_op_ids { OPS };
39
40 #undef C
41 #define C(a, b) b
42
43 static const char * ops[] = { OPS };
44
45 /*
46  * pred functions are OP_LE, OP_LT, OP_GE, OP_GT, and OP_BAND
47  * pred_funcs_##type below must match the order of them above.
48  */
49 #define PRED_FUNC_START                 OP_LE
50 #define PRED_FUNC_MAX                   (OP_BAND - PRED_FUNC_START)
51
52 #define ERRORS                                                          \
53         C(NONE,                 "No error"),                            \
54         C(INVALID_OP,           "Invalid operator"),                    \
55         C(TOO_MANY_OPEN,        "Too many '('"),                        \
56         C(TOO_MANY_CLOSE,       "Too few '('"),                         \
57         C(MISSING_QUOTE,        "Missing matching quote"),              \
58         C(OPERAND_TOO_LONG,     "Operand too long"),                    \
59         C(EXPECT_STRING,        "Expecting string field"),              \
60         C(EXPECT_DIGIT,         "Expecting numeric field"),             \
61         C(ILLEGAL_FIELD_OP,     "Illegal operation for field type"),    \
62         C(FIELD_NOT_FOUND,      "Field not found"),                     \
63         C(ILLEGAL_INTVAL,       "Illegal integer value"),               \
64         C(BAD_SUBSYS_FILTER,    "Couldn't find or set field in one of a subsystem's events"), \
65         C(TOO_MANY_PREDS,       "Too many terms in predicate expression"), \
66         C(INVALID_FILTER,       "Meaningless filter expression"),       \
67         C(IP_FIELD_ONLY,        "Only 'ip' field is supported for function trace"), \
68         C(INVALID_VALUE,        "Invalid value (did you forget quotes)?"), \
69         C(NO_FILTER,            "No filter found"),
70
71 #undef C
72 #define C(a, b)         FILT_ERR_##a
73
74 enum { ERRORS };
75
76 #undef C
77 #define C(a, b)         b
78
79 static char *err_text[] = { ERRORS };
80
81 /* Called after a '!' character but "!=" and "!~" are not "not"s */
82 static bool is_not(const char *str)
83 {
84         switch (str[1]) {
85         case '=':
86         case '~':
87                 return false;
88         }
89         return true;
90 }
91
92 /**
93  * prog_entry - a singe entry in the filter program
94  * @target:          Index to jump to on a branch (actually one minus the index)
95  * @when_to_branch:  The value of the result of the predicate to do a branch
96  * @pred:            The predicate to execute.
97  */
98 struct prog_entry {
99         int                     target;
100         int                     when_to_branch;
101         struct filter_pred      *pred;
102 };
103
104 /**
105  * update_preds- assign a program entry a label target
106  * @prog: The program array
107  * @N: The index of the current entry in @prog
108  * @when_to_branch: What to assign a program entry for its branch condition
109  *
110  * The program entry at @N has a target that points to the index of a program
111  * entry that can have its target and when_to_branch fields updated.
112  * Update the current program entry denoted by index @N target field to be
113  * that of the updated entry. This will denote the entry to update if
114  * we are processing an "||" after an "&&"
115  */
116 static void update_preds(struct prog_entry *prog, int N, int invert)
117 {
118         int t, s;
119
120         t = prog[N].target;
121         s = prog[t].target;
122         prog[t].when_to_branch = invert;
123         prog[t].target = N;
124         prog[N].target = s;
125 }
126
127 struct filter_parse_error {
128         int lasterr;
129         int lasterr_pos;
130 };
131
132 static void parse_error(struct filter_parse_error *pe, int err, int pos)
133 {
134         pe->lasterr = err;
135         pe->lasterr_pos = pos;
136 }
137
138 typedef int (*parse_pred_fn)(const char *str, void *data, int pos,
139                              struct filter_parse_error *pe,
140                              struct filter_pred **pred);
141
142 enum {
143         INVERT          = 1,
144         PROCESS_AND     = 2,
145         PROCESS_OR      = 4,
146 };
147
148 /*
149  * Without going into a formal proof, this explains the method that is used in
150  * parsing the logical expressions.
151  *
152  * For example, if we have: "a && !(!b || (c && g)) || d || e && !f"
153  * The first pass will convert it into the following program:
154  *
155  * n1: r=a;       l1: if (!r) goto l4;
156  * n2: r=b;       l2: if (!r) goto l4;
157  * n3: r=c; r=!r; l3: if (r) goto l4;
158  * n4: r=g; r=!r; l4: if (r) goto l5;
159  * n5: r=d;       l5: if (r) goto T
160  * n6: r=e;       l6: if (!r) goto l7;
161  * n7: r=f; r=!r; l7: if (!r) goto F
162  * T: return TRUE
163  * F: return FALSE
164  *
165  * To do this, we use a data structure to represent each of the above
166  * predicate and conditions that has:
167  *
168  *  predicate, when_to_branch, invert, target
169  *
170  * The "predicate" will hold the function to determine the result "r".
171  * The "when_to_branch" denotes what "r" should be if a branch is to be taken
172  * "&&" would contain "!r" or (0) and "||" would contain "r" or (1).
173  * The "invert" holds whether the value should be reversed before testing.
174  * The "target" contains the label "l#" to jump to.
175  *
176  * A stack is created to hold values when parentheses are used.
177  *
178  * To simplify the logic, the labels will start at 0 and not 1.
179  *
180  * The possible invert values are 1 and 0. The number of "!"s that are in scope
181  * before the predicate determines the invert value, if the number is odd then
182  * the invert value is 1 and 0 otherwise. This means the invert value only
183  * needs to be toggled when a new "!" is introduced compared to what is stored
184  * on the stack, where parentheses were used.
185  *
186  * The top of the stack and "invert" are initialized to zero.
187  *
188  * ** FIRST PASS **
189  *
190  * #1 A loop through all the tokens is done:
191  *
192  * #2 If the token is an "(", the stack is push, and the current stack value
193  *    gets the current invert value, and the loop continues to the next token.
194  *    The top of the stack saves the "invert" value to keep track of what
195  *    the current inversion is. As "!(a && !b || c)" would require all
196  *    predicates being affected separately by the "!" before the parentheses.
197  *    And that would end up being equivalent to "(!a || b) && !c"
198  *
199  * #3 If the token is an "!", the current "invert" value gets inverted, and
200  *    the loop continues. Note, if the next token is a predicate, then
201  *    this "invert" value is only valid for the current program entry,
202  *    and does not affect other predicates later on.
203  *
204  * The only other acceptable token is the predicate string.
205  *
206  * #4 A new entry into the program is added saving: the predicate and the
207  *    current value of "invert". The target is currently assigned to the
208  *    previous program index (this will not be its final value).
209  *
210  * #5 We now enter another loop and look at the next token. The only valid
211  *    tokens are ")", "&&", "||" or end of the input string "\0".
212  *
213  * #6 The invert variable is reset to the current value saved on the top of
214  *    the stack.
215  *
216  * #7 The top of the stack holds not only the current invert value, but also
217  *    if a "&&" or "||" needs to be processed. Note, the "&&" takes higher
218  *    precedence than "||". That is "a && b || c && d" is equivalent to
219  *    "(a && b) || (c && d)". Thus the first thing to do is to see if "&&" needs
220  *    to be processed. This is the case if an "&&" was the last token. If it was
221  *    then we call update_preds(). This takes the program, the current index in
222  *    the program, and the current value of "invert".  More will be described
223  *    below about this function.
224  *
225  * #8 If the next token is "&&" then we set a flag in the top of the stack
226  *    that denotes that "&&" needs to be processed, break out of this loop
227  *    and continue with the outer loop.
228  *
229  * #9 Otherwise, if a "||" needs to be processed then update_preds() is called.
230  *    This is called with the program, the current index in the program, but
231  *    this time with an inverted value of "invert" (that is !invert). This is
232  *    because the value taken will become the "when_to_branch" value of the
233  *    program.
234  *    Note, this is called when the next token is not an "&&". As stated before,
235  *    "&&" takes higher precedence, and "||" should not be processed yet if the
236  *    next logical operation is "&&".
237  *
238  * #10 If the next token is "||" then we set a flag in the top of the stack
239  *     that denotes that "||" needs to be processed, break out of this loop
240  *     and continue with the outer loop.
241  *
242  * #11 If this is the end of the input string "\0" then we break out of both
243  *     loops.
244  *
245  * #12 Otherwise, the next token is ")", where we pop the stack and continue
246  *     this inner loop.
247  *
248  * Now to discuss the update_pred() function, as that is key to the setting up
249  * of the program. Remember the "target" of the program is initialized to the
250  * previous index and not the "l" label. The target holds the index into the
251  * program that gets affected by the operand. Thus if we have something like
252  *  "a || b && c", when we process "a" the target will be "-1" (undefined).
253  * When we process "b", its target is "0", which is the index of "a", as that's
254  * the predicate that is affected by "||". But because the next token after "b"
255  * is "&&" we don't call update_preds(). Instead continue to "c". As the
256  * next token after "c" is not "&&" but the end of input, we first process the
257  * "&&" by calling update_preds() for the "&&" then we process the "||" by
258  * callin updates_preds() with the values for processing "||".
259  *
260  * What does that mean? What update_preds() does is to first save the "target"
261  * of the program entry indexed by the current program entry's "target"
262  * (remember the "target" is initialized to previous program entry), and then
263  * sets that "target" to the current index which represents the label "l#".
264  * That entry's "when_to_branch" is set to the value passed in (the "invert"
265  * or "!invert"). Then it sets the current program entry's target to the saved
266  * "target" value (the old value of the program that had its "target" updated
267  * to the label).
268  *
269  * Looking back at "a || b && c", we have the following steps:
270  *  "a"  - prog[0] = { "a", X, -1 } // pred, when_to_branch, target
271  *  "||" - flag that we need to process "||"; continue outer loop
272  *  "b"  - prog[1] = { "b", X, 0 }
273  *  "&&" - flag that we need to process "&&"; continue outer loop
274  * (Notice we did not process "||")
275  *  "c"  - prog[2] = { "c", X, 1 }
276  *  update_preds(prog, 2, 0); // invert = 0 as we are processing "&&"
277  *    t = prog[2].target; // t = 1
278  *    s = prog[t].target; // s = 0
279  *    prog[t].target = 2; // Set target to "l2"
280  *    prog[t].when_to_branch = 0;
281  *    prog[2].target = s;
282  * update_preds(prog, 2, 1); // invert = 1 as we are now processing "||"
283  *    t = prog[2].target; // t = 0
284  *    s = prog[t].target; // s = -1
285  *    prog[t].target = 2; // Set target to "l2"
286  *    prog[t].when_to_branch = 1;
287  *    prog[2].target = s;
288  *
289  * #13 Which brings us to the final step of the first pass, which is to set
290  *     the last program entry's when_to_branch and target, which will be
291  *     when_to_branch = 0; target = N; ( the label after the program entry after
292  *     the last program entry processed above).
293  *
294  * If we denote "TRUE" to be the entry after the last program entry processed,
295  * and "FALSE" the program entry after that, we are now done with the first
296  * pass.
297  *
298  * Making the above "a || b && c" have a progam of:
299  *  prog[0] = { "a", 1, 2 }
300  *  prog[1] = { "b", 0, 2 }
301  *  prog[2] = { "c", 0, 3 }
302  *
303  * Which translates into:
304  * n0: r = a; l0: if (r) goto l2;
305  * n1: r = b; l1: if (!r) goto l2;
306  * n2: r = c; l2: if (!r) goto l3;  // Which is the same as "goto F;"
307  * T: return TRUE; l3:
308  * F: return FALSE
309  *
310  * Although, after the first pass, the program is correct, it is
311  * inefficient. The simple sample of "a || b && c" could be easily been
312  * converted into:
313  * n0: r = a; if (r) goto T
314  * n1: r = b; if (!r) goto F
315  * n2: r = c; if (!r) goto F
316  * T: return TRUE;
317  * F: return FALSE;
318  *
319  * The First Pass is over the input string. The next too passes are over
320  * the program itself.
321  *
322  * ** SECOND PASS **
323  *
324  * Which brings us to the second pass. If a jump to a label has the
325  * same condition as that label, it can instead jump to its target.
326  * The original example of "a && !(!b || (c && g)) || d || e && !f"
327  * where the first pass gives us:
328  *
329  * n1: r=a;       l1: if (!r) goto l4;
330  * n2: r=b;       l2: if (!r) goto l4;
331  * n3: r=c; r=!r; l3: if (r) goto l4;
332  * n4: r=g; r=!r; l4: if (r) goto l5;
333  * n5: r=d;       l5: if (r) goto T
334  * n6: r=e;       l6: if (!r) goto l7;
335  * n7: r=f; r=!r; l7: if (!r) goto F:
336  * T: return TRUE;
337  * F: return FALSE
338  *
339  * We can see that "l3: if (r) goto l4;" and at l4, we have "if (r) goto l5;".
340  * And "l5: if (r) goto T", we could optimize this by converting l3 and l4
341  * to go directly to T. To accomplish this, we start from the last
342  * entry in the program and work our way back. If the target of the entry
343  * has the same "when_to_branch" then we could use that entry's target.
344  * Doing this, the above would end up as:
345  *
346  * n1: r=a;       l1: if (!r) goto l4;
347  * n2: r=b;       l2: if (!r) goto l4;
348  * n3: r=c; r=!r; l3: if (r) goto T;
349  * n4: r=g; r=!r; l4: if (r) goto T;
350  * n5: r=d;       l5: if (r) goto T;
351  * n6: r=e;       l6: if (!r) goto F;
352  * n7: r=f; r=!r; l7: if (!r) goto F;
353  * T: return TRUE
354  * F: return FALSE
355  *
356  * In that same pass, if the "when_to_branch" doesn't match, we can simply
357  * go to the program entry after the label. That is, "l2: if (!r) goto l4;"
358  * where "l4: if (r) goto T;", then we can convert l2 to be:
359  * "l2: if (!r) goto n5;".
360  *
361  * This will have the second pass give us:
362  * n1: r=a;       l1: if (!r) goto n5;
363  * n2: r=b;       l2: if (!r) goto n5;
364  * n3: r=c; r=!r; l3: if (r) goto T;
365  * n4: r=g; r=!r; l4: if (r) goto T;
366  * n5: r=d;       l5: if (r) goto T
367  * n6: r=e;       l6: if (!r) goto F;
368  * n7: r=f; r=!r; l7: if (!r) goto F
369  * T: return TRUE
370  * F: return FALSE
371  *
372  * Notice, all the "l#" labels are no longer used, and they can now
373  * be discarded.
374  *
375  * ** THIRD PASS **
376  *
377  * For the third pass we deal with the inverts. As they simply just
378  * make the "when_to_branch" get inverted, a simple loop over the
379  * program to that does: "when_to_branch ^= invert;" will do the
380  * job, leaving us with:
381  * n1: r=a; if (!r) goto n5;
382  * n2: r=b; if (!r) goto n5;
383  * n3: r=c: if (!r) goto T;
384  * n4: r=g; if (!r) goto T;
385  * n5: r=d; if (r) goto T
386  * n6: r=e; if (!r) goto F;
387  * n7: r=f; if (r) goto F
388  * T: return TRUE
389  * F: return FALSE
390  *
391  * As "r = a; if (!r) goto n5;" is obviously the same as
392  * "if (!a) goto n5;" without doing anything we can interperate the
393  * program as:
394  * n1: if (!a) goto n5;
395  * n2: if (!b) goto n5;
396  * n3: if (!c) goto T;
397  * n4: if (!g) goto T;
398  * n5: if (d) goto T
399  * n6: if (!e) goto F;
400  * n7: if (f) goto F
401  * T: return TRUE
402  * F: return FALSE
403  *
404  * Since the inverts are discarded at the end, there's no reason to store
405  * them in the program array (and waste memory). A separate array to hold
406  * the inverts is used and freed at the end.
407  */
408 static struct prog_entry *
409 predicate_parse(const char *str, int nr_parens, int nr_preds,
410                 parse_pred_fn parse_pred, void *data,
411                 struct filter_parse_error *pe)
412 {
413         struct prog_entry *prog_stack;
414         struct prog_entry *prog;
415         const char *ptr = str;
416         char *inverts = NULL;
417         int *op_stack;
418         int *top;
419         int invert = 0;
420         int ret = -ENOMEM;
421         int len;
422         int N = 0;
423         int i;
424
425         nr_preds += 2; /* For TRUE and FALSE */
426
427         op_stack = kmalloc_array(nr_parens, sizeof(*op_stack), GFP_KERNEL);
428         if (!op_stack)
429                 return ERR_PTR(-ENOMEM);
430         prog_stack = kcalloc(nr_preds, sizeof(*prog_stack), GFP_KERNEL);
431         if (!prog_stack) {
432                 parse_error(pe, -ENOMEM, 0);
433                 goto out_free;
434         }
435         inverts = kmalloc_array(nr_preds, sizeof(*inverts), GFP_KERNEL);
436         if (!inverts) {
437                 parse_error(pe, -ENOMEM, 0);
438                 goto out_free;
439         }
440
441         top = op_stack;
442         prog = prog_stack;
443         *top = 0;
444
445         /* First pass */
446         while (*ptr) {                                          /* #1 */
447                 const char *next = ptr++;
448
449                 if (isspace(*next))
450                         continue;
451
452                 switch (*next) {
453                 case '(':                                       /* #2 */
454                         if (top - op_stack > nr_parens) {
455                                 ret = -EINVAL;
456                                 goto out_free;
457                         }
458                         *(++top) = invert;
459                         continue;
460                 case '!':                                       /* #3 */
461                         if (!is_not(next))
462                                 break;
463                         invert = !invert;
464                         continue;
465                 }
466
467                 if (N >= nr_preds) {
468                         parse_error(pe, FILT_ERR_TOO_MANY_PREDS, next - str);
469                         goto out_free;
470                 }
471
472                 inverts[N] = invert;                            /* #4 */
473                 prog[N].target = N-1;
474
475                 len = parse_pred(next, data, ptr - str, pe, &prog[N].pred);
476                 if (len < 0) {
477                         ret = len;
478                         goto out_free;
479                 }
480                 ptr = next + len;
481
482                 N++;
483
484                 ret = -1;
485                 while (1) {                                     /* #5 */
486                         next = ptr++;
487                         if (isspace(*next))
488                                 continue;
489
490                         switch (*next) {
491                         case ')':
492                         case '\0':
493                                 break;
494                         case '&':
495                         case '|':
496                                 if (next[1] == next[0]) {
497                                         ptr++;
498                                         break;
499                                 }
500                         default:
501                                 parse_error(pe, FILT_ERR_TOO_MANY_PREDS,
502                                             next - str);
503                                 goto out_free;
504                         }
505
506                         invert = *top & INVERT;
507
508                         if (*top & PROCESS_AND) {               /* #7 */
509                                 update_preds(prog, N - 1, invert);
510                                 *top &= ~PROCESS_AND;
511                         }
512                         if (*next == '&') {                     /* #8 */
513                                 *top |= PROCESS_AND;
514                                 break;
515                         }
516                         if (*top & PROCESS_OR) {                /* #9 */
517                                 update_preds(prog, N - 1, !invert);
518                                 *top &= ~PROCESS_OR;
519                         }
520                         if (*next == '|') {                     /* #10 */
521                                 *top |= PROCESS_OR;
522                                 break;
523                         }
524                         if (!*next)                             /* #11 */
525                                 goto out;
526
527                         if (top == op_stack) {
528                                 ret = -1;
529                                 /* Too few '(' */
530                                 parse_error(pe, FILT_ERR_TOO_MANY_CLOSE, ptr - str);
531                                 goto out_free;
532                         }
533                         top--;                                  /* #12 */
534                 }
535         }
536  out:
537         if (top != op_stack) {
538                 /* Too many '(' */
539                 parse_error(pe, FILT_ERR_TOO_MANY_OPEN, ptr - str);
540                 goto out_free;
541         }
542
543         if (!N) {
544                 /* No program? */
545                 ret = -EINVAL;
546                 parse_error(pe, FILT_ERR_NO_FILTER, ptr - str);
547                 goto out_free;
548         }
549
550         prog[N].pred = NULL;                                    /* #13 */
551         prog[N].target = 1;             /* TRUE */
552         prog[N+1].pred = NULL;
553         prog[N+1].target = 0;           /* FALSE */
554         prog[N-1].target = N;
555         prog[N-1].when_to_branch = false;
556
557         /* Second Pass */
558         for (i = N-1 ; i--; ) {
559                 int target = prog[i].target;
560                 if (prog[i].when_to_branch == prog[target].when_to_branch)
561                         prog[i].target = prog[target].target;
562         }
563
564         /* Third Pass */
565         for (i = 0; i < N; i++) {
566                 invert = inverts[i] ^ prog[i].when_to_branch;
567                 prog[i].when_to_branch = invert;
568                 /* Make sure the program always moves forward */
569                 if (WARN_ON(prog[i].target <= i)) {
570                         ret = -EINVAL;
571                         goto out_free;
572                 }
573         }
574
575         kfree(op_stack);
576         kfree(inverts);
577         return prog;
578 out_free:
579         kfree(op_stack);
580         kfree(inverts);
581         if (prog_stack) {
582                 for (i = 0; prog_stack[i].pred; i++)
583                         kfree(prog_stack[i].pred);
584                 kfree(prog_stack);
585         }
586         return ERR_PTR(ret);
587 }
588
589 #define DEFINE_COMPARISON_PRED(type)                                    \
590 static int filter_pred_LT_##type(struct filter_pred *pred, void *event) \
591 {                                                                       \
592         type *addr = (type *)(event + pred->offset);                    \
593         type val = (type)pred->val;                                     \
594         return *addr < val;                                             \
595 }                                                                       \
596 static int filter_pred_LE_##type(struct filter_pred *pred, void *event) \
597 {                                                                       \
598         type *addr = (type *)(event + pred->offset);                    \
599         type val = (type)pred->val;                                     \
600         return *addr <= val;                                            \
601 }                                                                       \
602 static int filter_pred_GT_##type(struct filter_pred *pred, void *event) \
603 {                                                                       \
604         type *addr = (type *)(event + pred->offset);                    \
605         type val = (type)pred->val;                                     \
606         return *addr > val;                                     \
607 }                                                                       \
608 static int filter_pred_GE_##type(struct filter_pred *pred, void *event) \
609 {                                                                       \
610         type *addr = (type *)(event + pred->offset);                    \
611         type val = (type)pred->val;                                     \
612         return *addr >= val;                                            \
613 }                                                                       \
614 static int filter_pred_BAND_##type(struct filter_pred *pred, void *event) \
615 {                                                                       \
616         type *addr = (type *)(event + pred->offset);                    \
617         type val = (type)pred->val;                                     \
618         return !!(*addr & val);                                         \
619 }                                                                       \
620 static const filter_pred_fn_t pred_funcs_##type[] = {                   \
621         filter_pred_LE_##type,                                          \
622         filter_pred_LT_##type,                                          \
623         filter_pred_GE_##type,                                          \
624         filter_pred_GT_##type,                                          \
625         filter_pred_BAND_##type,                                        \
626 };
627
628 #define DEFINE_EQUALITY_PRED(size)                                      \
629 static int filter_pred_##size(struct filter_pred *pred, void *event)    \
630 {                                                                       \
631         u##size *addr = (u##size *)(event + pred->offset);              \
632         u##size val = (u##size)pred->val;                               \
633         int match;                                                      \
634                                                                         \
635         match = (val == *addr) ^ pred->not;                             \
636                                                                         \
637         return match;                                                   \
638 }
639
640 DEFINE_COMPARISON_PRED(s64);
641 DEFINE_COMPARISON_PRED(u64);
642 DEFINE_COMPARISON_PRED(s32);
643 DEFINE_COMPARISON_PRED(u32);
644 DEFINE_COMPARISON_PRED(s16);
645 DEFINE_COMPARISON_PRED(u16);
646 DEFINE_COMPARISON_PRED(s8);
647 DEFINE_COMPARISON_PRED(u8);
648
649 DEFINE_EQUALITY_PRED(64);
650 DEFINE_EQUALITY_PRED(32);
651 DEFINE_EQUALITY_PRED(16);
652 DEFINE_EQUALITY_PRED(8);
653
654 /* Filter predicate for fixed sized arrays of characters */
655 static int filter_pred_string(struct filter_pred *pred, void *event)
656 {
657         char *addr = (char *)(event + pred->offset);
658         int cmp, match;
659
660         cmp = pred->regex.match(addr, &pred->regex, pred->regex.field_len);
661
662         match = cmp ^ pred->not;
663
664         return match;
665 }
666
667 /* Filter predicate for char * pointers */
668 static int filter_pred_pchar(struct filter_pred *pred, void *event)
669 {
670         char **addr = (char **)(event + pred->offset);
671         int cmp, match;
672         int len = strlen(*addr) + 1;    /* including tailing '\0' */
673
674         cmp = pred->regex.match(*addr, &pred->regex, len);
675
676         match = cmp ^ pred->not;
677
678         return match;
679 }
680
681 /*
682  * Filter predicate for dynamic sized arrays of characters.
683  * These are implemented through a list of strings at the end
684  * of the entry.
685  * Also each of these strings have a field in the entry which
686  * contains its offset from the beginning of the entry.
687  * We have then first to get this field, dereference it
688  * and add it to the address of the entry, and at last we have
689  * the address of the string.
690  */
691 static int filter_pred_strloc(struct filter_pred *pred, void *event)
692 {
693         u32 str_item = *(u32 *)(event + pred->offset);
694         int str_loc = str_item & 0xffff;
695         int str_len = str_item >> 16;
696         char *addr = (char *)(event + str_loc);
697         int cmp, match;
698
699         cmp = pred->regex.match(addr, &pred->regex, str_len);
700
701         match = cmp ^ pred->not;
702
703         return match;
704 }
705
706 /* Filter predicate for CPUs. */
707 static int filter_pred_cpu(struct filter_pred *pred, void *event)
708 {
709         int cpu, cmp;
710
711         cpu = raw_smp_processor_id();
712         cmp = pred->val;
713
714         switch (pred->op) {
715         case OP_EQ:
716                 return cpu == cmp;
717         case OP_NE:
718                 return cpu != cmp;
719         case OP_LT:
720                 return cpu < cmp;
721         case OP_LE:
722                 return cpu <= cmp;
723         case OP_GT:
724                 return cpu > cmp;
725         case OP_GE:
726                 return cpu >= cmp;
727         default:
728                 return 0;
729         }
730 }
731
732 /* Filter predicate for COMM. */
733 static int filter_pred_comm(struct filter_pred *pred, void *event)
734 {
735         int cmp;
736
737         cmp = pred->regex.match(current->comm, &pred->regex,
738                                 TASK_COMM_LEN);
739         return cmp ^ pred->not;
740 }
741
742 static int filter_pred_none(struct filter_pred *pred, void *event)
743 {
744         return 0;
745 }
746
747 /*
748  * regex_match_foo - Basic regex callbacks
749  *
750  * @str: the string to be searched
751  * @r:   the regex structure containing the pattern string
752  * @len: the length of the string to be searched (including '\0')
753  *
754  * Note:
755  * - @str might not be NULL-terminated if it's of type DYN_STRING
756  *   or STATIC_STRING, unless @len is zero.
757  */
758
759 static int regex_match_full(char *str, struct regex *r, int len)
760 {
761         /* len of zero means str is dynamic and ends with '\0' */
762         if (!len)
763                 return strcmp(str, r->pattern) == 0;
764
765         return strncmp(str, r->pattern, len) == 0;
766 }
767
768 static int regex_match_front(char *str, struct regex *r, int len)
769 {
770         if (len && len < r->len)
771                 return 0;
772
773         return strncmp(str, r->pattern, r->len) == 0;
774 }
775
776 static int regex_match_middle(char *str, struct regex *r, int len)
777 {
778         if (!len)
779                 return strstr(str, r->pattern) != NULL;
780
781         return strnstr(str, r->pattern, len) != NULL;
782 }
783
784 static int regex_match_end(char *str, struct regex *r, int len)
785 {
786         int strlen = len - 1;
787
788         if (strlen >= r->len &&
789             memcmp(str + strlen - r->len, r->pattern, r->len) == 0)
790                 return 1;
791         return 0;
792 }
793
794 static int regex_match_glob(char *str, struct regex *r, int len __maybe_unused)
795 {
796         if (glob_match(r->pattern, str))
797                 return 1;
798         return 0;
799 }
800
801 /**
802  * filter_parse_regex - parse a basic regex
803  * @buff:   the raw regex
804  * @len:    length of the regex
805  * @search: will point to the beginning of the string to compare
806  * @not:    tell whether the match will have to be inverted
807  *
808  * This passes in a buffer containing a regex and this function will
809  * set search to point to the search part of the buffer and
810  * return the type of search it is (see enum above).
811  * This does modify buff.
812  *
813  * Returns enum type.
814  *  search returns the pointer to use for comparison.
815  *  not returns 1 if buff started with a '!'
816  *     0 otherwise.
817  */
818 enum regex_type filter_parse_regex(char *buff, int len, char **search, int *not)
819 {
820         int type = MATCH_FULL;
821         int i;
822
823         if (buff[0] == '!') {
824                 *not = 1;
825                 buff++;
826                 len--;
827         } else
828                 *not = 0;
829
830         *search = buff;
831
832         for (i = 0; i < len; i++) {
833                 if (buff[i] == '*') {
834                         if (!i) {
835                                 type = MATCH_END_ONLY;
836                         } else if (i == len - 1) {
837                                 if (type == MATCH_END_ONLY)
838                                         type = MATCH_MIDDLE_ONLY;
839                                 else
840                                         type = MATCH_FRONT_ONLY;
841                                 buff[i] = 0;
842                                 break;
843                         } else {        /* pattern continues, use full glob */
844                                 return MATCH_GLOB;
845                         }
846                 } else if (strchr("[?\\", buff[i])) {
847                         return MATCH_GLOB;
848                 }
849         }
850         if (buff[0] == '*')
851                 *search = buff + 1;
852
853         return type;
854 }
855
856 static void filter_build_regex(struct filter_pred *pred)
857 {
858         struct regex *r = &pred->regex;
859         char *search;
860         enum regex_type type = MATCH_FULL;
861
862         if (pred->op == OP_GLOB) {
863                 type = filter_parse_regex(r->pattern, r->len, &search, &pred->not);
864                 r->len = strlen(search);
865                 memmove(r->pattern, search, r->len+1);
866         }
867
868         switch (type) {
869         case MATCH_FULL:
870                 r->match = regex_match_full;
871                 break;
872         case MATCH_FRONT_ONLY:
873                 r->match = regex_match_front;
874                 break;
875         case MATCH_MIDDLE_ONLY:
876                 r->match = regex_match_middle;
877                 break;
878         case MATCH_END_ONLY:
879                 r->match = regex_match_end;
880                 break;
881         case MATCH_GLOB:
882                 r->match = regex_match_glob;
883                 break;
884         }
885 }
886
887 /* return 1 if event matches, 0 otherwise (discard) */
888 int filter_match_preds(struct event_filter *filter, void *rec)
889 {
890         struct prog_entry *prog;
891         int i;
892
893         /* no filter is considered a match */
894         if (!filter)
895                 return 1;
896
897         /* Protected by either SRCU(tracepoint_srcu) or preempt_disable */
898         prog = rcu_dereference_raw(filter->prog);
899         if (!prog)
900                 return 1;
901
902         for (i = 0; prog[i].pred; i++) {
903                 struct filter_pred *pred = prog[i].pred;
904                 int match = pred->fn(pred, rec);
905                 if (match == prog[i].when_to_branch)
906                         i = prog[i].target;
907         }
908         return prog[i].target;
909 }
910 EXPORT_SYMBOL_GPL(filter_match_preds);
911
912 static void remove_filter_string(struct event_filter *filter)
913 {
914         if (!filter)
915                 return;
916
917         kfree(filter->filter_string);
918         filter->filter_string = NULL;
919 }
920
921 static void append_filter_err(struct filter_parse_error *pe,
922                               struct event_filter *filter)
923 {
924         struct trace_seq *s;
925         int pos = pe->lasterr_pos;
926         char *buf;
927         int len;
928
929         if (WARN_ON(!filter->filter_string))
930                 return;
931
932         s = kmalloc(sizeof(*s), GFP_KERNEL);
933         if (!s)
934                 return;
935         trace_seq_init(s);
936
937         len = strlen(filter->filter_string);
938         if (pos > len)
939                 pos = len;
940
941         /* indexing is off by one */
942         if (pos)
943                 pos++;
944
945         trace_seq_puts(s, filter->filter_string);
946         if (pe->lasterr > 0) {
947                 trace_seq_printf(s, "\n%*s", pos, "^");
948                 trace_seq_printf(s, "\nparse_error: %s\n", err_text[pe->lasterr]);
949         } else {
950                 trace_seq_printf(s, "\nError: (%d)\n", pe->lasterr);
951         }
952         trace_seq_putc(s, 0);
953         buf = kmemdup_nul(s->buffer, s->seq.len, GFP_KERNEL);
954         if (buf) {
955                 kfree(filter->filter_string);
956                 filter->filter_string = buf;
957         }
958         kfree(s);
959 }
960
961 static inline struct event_filter *event_filter(struct trace_event_file *file)
962 {
963         return file->filter;
964 }
965
966 /* caller must hold event_mutex */
967 void print_event_filter(struct trace_event_file *file, struct trace_seq *s)
968 {
969         struct event_filter *filter = event_filter(file);
970
971         if (filter && filter->filter_string)
972                 trace_seq_printf(s, "%s\n", filter->filter_string);
973         else
974                 trace_seq_puts(s, "none\n");
975 }
976
977 void print_subsystem_event_filter(struct event_subsystem *system,
978                                   struct trace_seq *s)
979 {
980         struct event_filter *filter;
981
982         mutex_lock(&event_mutex);
983         filter = system->filter;
984         if (filter && filter->filter_string)
985                 trace_seq_printf(s, "%s\n", filter->filter_string);
986         else
987                 trace_seq_puts(s, DEFAULT_SYS_FILTER_MESSAGE "\n");
988         mutex_unlock(&event_mutex);
989 }
990
991 static void free_prog(struct event_filter *filter)
992 {
993         struct prog_entry *prog;
994         int i;
995
996         prog = rcu_access_pointer(filter->prog);
997         if (!prog)
998                 return;
999
1000         for (i = 0; prog[i].pred; i++)
1001                 kfree(prog[i].pred);
1002         kfree(prog);
1003 }
1004
1005 static void filter_disable(struct trace_event_file *file)
1006 {
1007         unsigned long old_flags = file->flags;
1008
1009         file->flags &= ~EVENT_FILE_FL_FILTERED;
1010
1011         if (old_flags != file->flags)
1012                 trace_buffered_event_disable();
1013 }
1014
1015 static void __free_filter(struct event_filter *filter)
1016 {
1017         if (!filter)
1018                 return;
1019
1020         free_prog(filter);
1021         kfree(filter->filter_string);
1022         kfree(filter);
1023 }
1024
1025 void free_event_filter(struct event_filter *filter)
1026 {
1027         __free_filter(filter);
1028 }
1029
1030 static inline void __remove_filter(struct trace_event_file *file)
1031 {
1032         filter_disable(file);
1033         remove_filter_string(file->filter);
1034 }
1035
1036 static void filter_free_subsystem_preds(struct trace_subsystem_dir *dir,
1037                                         struct trace_array *tr)
1038 {
1039         struct trace_event_file *file;
1040
1041         list_for_each_entry(file, &tr->events, list) {
1042                 if (file->system != dir)
1043                         continue;
1044                 __remove_filter(file);
1045         }
1046 }
1047
1048 static inline void __free_subsystem_filter(struct trace_event_file *file)
1049 {
1050         __free_filter(file->filter);
1051         file->filter = NULL;
1052 }
1053
1054 static void filter_free_subsystem_filters(struct trace_subsystem_dir *dir,
1055                                           struct trace_array *tr)
1056 {
1057         struct trace_event_file *file;
1058
1059         list_for_each_entry(file, &tr->events, list) {
1060                 if (file->system != dir)
1061                         continue;
1062                 __free_subsystem_filter(file);
1063         }
1064 }
1065
1066 int filter_assign_type(const char *type)
1067 {
1068         if (strstr(type, "__data_loc") && strstr(type, "char"))
1069                 return FILTER_DYN_STRING;
1070
1071         if (strchr(type, '[') && strstr(type, "char"))
1072                 return FILTER_STATIC_STRING;
1073
1074         return FILTER_OTHER;
1075 }
1076
1077 static filter_pred_fn_t select_comparison_fn(enum filter_op_ids op,
1078                                             int field_size, int field_is_signed)
1079 {
1080         filter_pred_fn_t fn = NULL;
1081         int pred_func_index = -1;
1082
1083         switch (op) {
1084         case OP_EQ:
1085         case OP_NE:
1086                 break;
1087         default:
1088                 if (WARN_ON_ONCE(op < PRED_FUNC_START))
1089                         return NULL;
1090                 pred_func_index = op - PRED_FUNC_START;
1091                 if (WARN_ON_ONCE(pred_func_index > PRED_FUNC_MAX))
1092                         return NULL;
1093         }
1094
1095         switch (field_size) {
1096         case 8:
1097                 if (pred_func_index < 0)
1098                         fn = filter_pred_64;
1099                 else if (field_is_signed)
1100                         fn = pred_funcs_s64[pred_func_index];
1101                 else
1102                         fn = pred_funcs_u64[pred_func_index];
1103                 break;
1104         case 4:
1105                 if (pred_func_index < 0)
1106                         fn = filter_pred_32;
1107                 else if (field_is_signed)
1108                         fn = pred_funcs_s32[pred_func_index];
1109                 else
1110                         fn = pred_funcs_u32[pred_func_index];
1111                 break;
1112         case 2:
1113                 if (pred_func_index < 0)
1114                         fn = filter_pred_16;
1115                 else if (field_is_signed)
1116                         fn = pred_funcs_s16[pred_func_index];
1117                 else
1118                         fn = pred_funcs_u16[pred_func_index];
1119                 break;
1120         case 1:
1121                 if (pred_func_index < 0)
1122                         fn = filter_pred_8;
1123                 else if (field_is_signed)
1124                         fn = pred_funcs_s8[pred_func_index];
1125                 else
1126                         fn = pred_funcs_u8[pred_func_index];
1127                 break;
1128         }
1129
1130         return fn;
1131 }
1132
1133 /* Called when a predicate is encountered by predicate_parse() */
1134 static int parse_pred(const char *str, void *data,
1135                       int pos, struct filter_parse_error *pe,
1136                       struct filter_pred **pred_ptr)
1137 {
1138         struct trace_event_call *call = data;
1139         struct ftrace_event_field *field;
1140         struct filter_pred *pred = NULL;
1141         char num_buf[24];       /* Big enough to hold an address */
1142         char *field_name;
1143         char q;
1144         u64 val;
1145         int len;
1146         int ret;
1147         int op;
1148         int s;
1149         int i = 0;
1150
1151         /* First find the field to associate to */
1152         while (isspace(str[i]))
1153                 i++;
1154         s = i;
1155
1156         while (isalnum(str[i]) || str[i] == '_')
1157                 i++;
1158
1159         len = i - s;
1160
1161         if (!len)
1162                 return -1;
1163
1164         field_name = kmemdup_nul(str + s, len, GFP_KERNEL);
1165         if (!field_name)
1166                 return -ENOMEM;
1167
1168         /* Make sure that the field exists */
1169
1170         field = trace_find_event_field(call, field_name);
1171         kfree(field_name);
1172         if (!field) {
1173                 parse_error(pe, FILT_ERR_FIELD_NOT_FOUND, pos + i);
1174                 return -EINVAL;
1175         }
1176
1177         while (isspace(str[i]))
1178                 i++;
1179
1180         /* Make sure this op is supported */
1181         for (op = 0; ops[op]; op++) {
1182                 /* This is why '<=' must come before '<' in ops[] */
1183                 if (strncmp(str + i, ops[op], strlen(ops[op])) == 0)
1184                         break;
1185         }
1186
1187         if (!ops[op]) {
1188                 parse_error(pe, FILT_ERR_INVALID_OP, pos + i);
1189                 goto err_free;
1190         }
1191
1192         i += strlen(ops[op]);
1193
1194         while (isspace(str[i]))
1195                 i++;
1196
1197         s = i;
1198
1199         pred = kzalloc(sizeof(*pred), GFP_KERNEL);
1200         if (!pred)
1201                 return -ENOMEM;
1202
1203         pred->field = field;
1204         pred->offset = field->offset;
1205         pred->op = op;
1206
1207         if (ftrace_event_is_function(call)) {
1208                 /*
1209                  * Perf does things different with function events.
1210                  * It only allows an "ip" field, and expects a string.
1211                  * But the string does not need to be surrounded by quotes.
1212                  * If it is a string, the assigned function as a nop,
1213                  * (perf doesn't use it) and grab everything.
1214                  */
1215                 if (strcmp(field->name, "ip") != 0) {
1216                          parse_error(pe, FILT_ERR_IP_FIELD_ONLY, pos + i);
1217                          goto err_free;
1218                  }
1219                  pred->fn = filter_pred_none;
1220
1221                  /*
1222                   * Quotes are not required, but if they exist then we need
1223                   * to read them till we hit a matching one.
1224                   */
1225                  if (str[i] == '\'' || str[i] == '"')
1226                          q = str[i];
1227                  else
1228                          q = 0;
1229
1230                  for (i++; str[i]; i++) {
1231                          if (q && str[i] == q)
1232                                  break;
1233                          if (!q && (str[i] == ')' || str[i] == '&' ||
1234                                     str[i] == '|'))
1235                                  break;
1236                  }
1237                  /* Skip quotes */
1238                  if (q)
1239                          s++;
1240                 len = i - s;
1241                 if (len >= MAX_FILTER_STR_VAL) {
1242                         parse_error(pe, FILT_ERR_OPERAND_TOO_LONG, pos + i);
1243                         goto err_free;
1244                 }
1245
1246                 pred->regex.len = len;
1247                 strncpy(pred->regex.pattern, str + s, len);
1248                 pred->regex.pattern[len] = 0;
1249
1250         /* This is either a string, or an integer */
1251         } else if (str[i] == '\'' || str[i] == '"') {
1252                 char q = str[i];
1253
1254                 /* Make sure the op is OK for strings */
1255                 switch (op) {
1256                 case OP_NE:
1257                         pred->not = 1;
1258                         /* Fall through */
1259                 case OP_GLOB:
1260                 case OP_EQ:
1261                         break;
1262                 default:
1263                         parse_error(pe, FILT_ERR_ILLEGAL_FIELD_OP, pos + i);
1264                         goto err_free;
1265                 }
1266
1267                 /* Make sure the field is OK for strings */
1268                 if (!is_string_field(field)) {
1269                         parse_error(pe, FILT_ERR_EXPECT_DIGIT, pos + i);
1270                         goto err_free;
1271                 }
1272
1273                 for (i++; str[i]; i++) {
1274                         if (str[i] == q)
1275                                 break;
1276                 }
1277                 if (!str[i]) {
1278                         parse_error(pe, FILT_ERR_MISSING_QUOTE, pos + i);
1279                         goto err_free;
1280                 }
1281
1282                 /* Skip quotes */
1283                 s++;
1284                 len = i - s;
1285                 if (len >= MAX_FILTER_STR_VAL) {
1286                         parse_error(pe, FILT_ERR_OPERAND_TOO_LONG, pos + i);
1287                         goto err_free;
1288                 }
1289
1290                 pred->regex.len = len;
1291                 strncpy(pred->regex.pattern, str + s, len);
1292                 pred->regex.pattern[len] = 0;
1293
1294                 filter_build_regex(pred);
1295
1296                 if (field->filter_type == FILTER_COMM) {
1297                         pred->fn = filter_pred_comm;
1298
1299                 } else if (field->filter_type == FILTER_STATIC_STRING) {
1300                         pred->fn = filter_pred_string;
1301                         pred->regex.field_len = field->size;
1302
1303                 } else if (field->filter_type == FILTER_DYN_STRING)
1304                         pred->fn = filter_pred_strloc;
1305                 else
1306                         pred->fn = filter_pred_pchar;
1307                 /* go past the last quote */
1308                 i++;
1309
1310         } else if (isdigit(str[i]) || str[i] == '-') {
1311
1312                 /* Make sure the field is not a string */
1313                 if (is_string_field(field)) {
1314                         parse_error(pe, FILT_ERR_EXPECT_STRING, pos + i);
1315                         goto err_free;
1316                 }
1317
1318                 if (op == OP_GLOB) {
1319                         parse_error(pe, FILT_ERR_ILLEGAL_FIELD_OP, pos + i);
1320                         goto err_free;
1321                 }
1322
1323                 if (str[i] == '-')
1324                         i++;
1325
1326                 /* We allow 0xDEADBEEF */
1327                 while (isalnum(str[i]))
1328                         i++;
1329
1330                 len = i - s;
1331                 /* 0xfeedfacedeadbeef is 18 chars max */
1332                 if (len >= sizeof(num_buf)) {
1333                         parse_error(pe, FILT_ERR_OPERAND_TOO_LONG, pos + i);
1334                         goto err_free;
1335                 }
1336
1337                 strncpy(num_buf, str + s, len);
1338                 num_buf[len] = 0;
1339
1340                 /* Make sure it is a value */
1341                 if (field->is_signed)
1342                         ret = kstrtoll(num_buf, 0, &val);
1343                 else
1344                         ret = kstrtoull(num_buf, 0, &val);
1345                 if (ret) {
1346                         parse_error(pe, FILT_ERR_ILLEGAL_INTVAL, pos + s);
1347                         goto err_free;
1348                 }
1349
1350                 pred->val = val;
1351
1352                 if (field->filter_type == FILTER_CPU)
1353                         pred->fn = filter_pred_cpu;
1354                 else {
1355                         pred->fn = select_comparison_fn(pred->op, field->size,
1356                                                         field->is_signed);
1357                         if (pred->op == OP_NE)
1358                                 pred->not = 1;
1359                 }
1360
1361         } else {
1362                 parse_error(pe, FILT_ERR_INVALID_VALUE, pos + i);
1363                 goto err_free;
1364         }
1365
1366         *pred_ptr = pred;
1367         return i;
1368
1369 err_free:
1370         kfree(pred);
1371         return -EINVAL;
1372 }
1373
1374 enum {
1375         TOO_MANY_CLOSE          = -1,
1376         TOO_MANY_OPEN           = -2,
1377         MISSING_QUOTE           = -3,
1378 };
1379
1380 /*
1381  * Read the filter string once to calculate the number of predicates
1382  * as well as how deep the parentheses go.
1383  *
1384  * Returns:
1385  *   0 - everything is fine (err is undefined)
1386  *  -1 - too many ')'
1387  *  -2 - too many '('
1388  *  -3 - No matching quote
1389  */
1390 static int calc_stack(const char *str, int *parens, int *preds, int *err)
1391 {
1392         bool is_pred = false;
1393         int nr_preds = 0;
1394         int open = 1; /* Count the expression as "(E)" */
1395         int last_quote = 0;
1396         int max_open = 1;
1397         int quote = 0;
1398         int i;
1399
1400         *err = 0;
1401
1402         for (i = 0; str[i]; i++) {
1403                 if (isspace(str[i]))
1404                         continue;
1405                 if (quote) {
1406                         if (str[i] == quote)
1407                                quote = 0;
1408                         continue;
1409                 }
1410
1411                 switch (str[i]) {
1412                 case '\'':
1413                 case '"':
1414                         quote = str[i];
1415                         last_quote = i;
1416                         break;
1417                 case '|':
1418                 case '&':
1419                         if (str[i+1] != str[i])
1420                                 break;
1421                         is_pred = false;
1422                         continue;
1423                 case '(':
1424                         is_pred = false;
1425                         open++;
1426                         if (open > max_open)
1427                                 max_open = open;
1428                         continue;
1429                 case ')':
1430                         is_pred = false;
1431                         if (open == 1) {
1432                                 *err = i;
1433                                 return TOO_MANY_CLOSE;
1434                         }
1435                         open--;
1436                         continue;
1437                 }
1438                 if (!is_pred) {
1439                         nr_preds++;
1440                         is_pred = true;
1441                 }
1442         }
1443
1444         if (quote) {
1445                 *err = last_quote;
1446                 return MISSING_QUOTE;
1447         }
1448
1449         if (open != 1) {
1450                 int level = open;
1451
1452                 /* find the bad open */
1453                 for (i--; i; i--) {
1454                         if (quote) {
1455                                 if (str[i] == quote)
1456                                         quote = 0;
1457                                 continue;
1458                         }
1459                         switch (str[i]) {
1460                         case '(':
1461                                 if (level == open) {
1462                                         *err = i;
1463                                         return TOO_MANY_OPEN;
1464                                 }
1465                                 level--;
1466                                 break;
1467                         case ')':
1468                                 level++;
1469                                 break;
1470                         case '\'':
1471                         case '"':
1472                                 quote = str[i];
1473                                 break;
1474                         }
1475                 }
1476                 /* First character is the '(' with missing ')' */
1477                 *err = 0;
1478                 return TOO_MANY_OPEN;
1479         }
1480
1481         /* Set the size of the required stacks */
1482         *parens = max_open;
1483         *preds = nr_preds;
1484         return 0;
1485 }
1486
1487 static int process_preds(struct trace_event_call *call,
1488                          const char *filter_string,
1489                          struct event_filter *filter,
1490                          struct filter_parse_error *pe)
1491 {
1492         struct prog_entry *prog;
1493         int nr_parens;
1494         int nr_preds;
1495         int index;
1496         int ret;
1497
1498         ret = calc_stack(filter_string, &nr_parens, &nr_preds, &index);
1499         if (ret < 0) {
1500                 switch (ret) {
1501                 case MISSING_QUOTE:
1502                         parse_error(pe, FILT_ERR_MISSING_QUOTE, index);
1503                         break;
1504                 case TOO_MANY_OPEN:
1505                         parse_error(pe, FILT_ERR_TOO_MANY_OPEN, index);
1506                         break;
1507                 default:
1508                         parse_error(pe, FILT_ERR_TOO_MANY_CLOSE, index);
1509                 }
1510                 return ret;
1511         }
1512
1513         if (!nr_preds)
1514                 return -EINVAL;
1515
1516         prog = predicate_parse(filter_string, nr_parens, nr_preds,
1517                                parse_pred, call, pe);
1518         if (IS_ERR(prog))
1519                 return PTR_ERR(prog);
1520
1521         rcu_assign_pointer(filter->prog, prog);
1522         return 0;
1523 }
1524
1525 static inline void event_set_filtered_flag(struct trace_event_file *file)
1526 {
1527         unsigned long old_flags = file->flags;
1528
1529         file->flags |= EVENT_FILE_FL_FILTERED;
1530
1531         if (old_flags != file->flags)
1532                 trace_buffered_event_enable();
1533 }
1534
1535 static inline void event_set_filter(struct trace_event_file *file,
1536                                     struct event_filter *filter)
1537 {
1538         rcu_assign_pointer(file->filter, filter);
1539 }
1540
1541 static inline void event_clear_filter(struct trace_event_file *file)
1542 {
1543         RCU_INIT_POINTER(file->filter, NULL);
1544 }
1545
1546 static inline void
1547 event_set_no_set_filter_flag(struct trace_event_file *file)
1548 {
1549         file->flags |= EVENT_FILE_FL_NO_SET_FILTER;
1550 }
1551
1552 static inline void
1553 event_clear_no_set_filter_flag(struct trace_event_file *file)
1554 {
1555         file->flags &= ~EVENT_FILE_FL_NO_SET_FILTER;
1556 }
1557
1558 static inline bool
1559 event_no_set_filter_flag(struct trace_event_file *file)
1560 {
1561         if (file->flags & EVENT_FILE_FL_NO_SET_FILTER)
1562                 return true;
1563
1564         return false;
1565 }
1566
1567 struct filter_list {
1568         struct list_head        list;
1569         struct event_filter     *filter;
1570 };
1571
1572 static int process_system_preds(struct trace_subsystem_dir *dir,
1573                                 struct trace_array *tr,
1574                                 struct filter_parse_error *pe,
1575                                 char *filter_string)
1576 {
1577         struct trace_event_file *file;
1578         struct filter_list *filter_item;
1579         struct event_filter *filter = NULL;
1580         struct filter_list *tmp;
1581         LIST_HEAD(filter_list);
1582         bool fail = true;
1583         int err;
1584
1585         list_for_each_entry(file, &tr->events, list) {
1586
1587                 if (file->system != dir)
1588                         continue;
1589
1590                 filter = kzalloc(sizeof(*filter), GFP_KERNEL);
1591                 if (!filter)
1592                         goto fail_mem;
1593
1594                 filter->filter_string = kstrdup(filter_string, GFP_KERNEL);
1595                 if (!filter->filter_string)
1596                         goto fail_mem;
1597
1598                 err = process_preds(file->event_call, filter_string, filter, pe);
1599                 if (err) {
1600                         filter_disable(file);
1601                         parse_error(pe, FILT_ERR_BAD_SUBSYS_FILTER, 0);
1602                         append_filter_err(pe, filter);
1603                 } else
1604                         event_set_filtered_flag(file);
1605
1606
1607                 filter_item = kzalloc(sizeof(*filter_item), GFP_KERNEL);
1608                 if (!filter_item)
1609                         goto fail_mem;
1610
1611                 list_add_tail(&filter_item->list, &filter_list);
1612                 /*
1613                  * Regardless of if this returned an error, we still
1614                  * replace the filter for the call.
1615                  */
1616                 filter_item->filter = event_filter(file);
1617                 event_set_filter(file, filter);
1618                 filter = NULL;
1619
1620                 fail = false;
1621         }
1622
1623         if (fail)
1624                 goto fail;
1625
1626         /*
1627          * The calls can still be using the old filters.
1628          * Do a synchronize_sched() and to ensure all calls are
1629          * done with them before we free them.
1630          */
1631         tracepoint_synchronize_unregister();
1632         list_for_each_entry_safe(filter_item, tmp, &filter_list, list) {
1633                 __free_filter(filter_item->filter);
1634                 list_del(&filter_item->list);
1635                 kfree(filter_item);
1636         }
1637         return 0;
1638  fail:
1639         /* No call succeeded */
1640         list_for_each_entry_safe(filter_item, tmp, &filter_list, list) {
1641                 list_del(&filter_item->list);
1642                 kfree(filter_item);
1643         }
1644         parse_error(pe, FILT_ERR_BAD_SUBSYS_FILTER, 0);
1645         return -EINVAL;
1646  fail_mem:
1647         __free_filter(filter);
1648         /* If any call succeeded, we still need to sync */
1649         if (!fail)
1650                 tracepoint_synchronize_unregister();
1651         list_for_each_entry_safe(filter_item, tmp, &filter_list, list) {
1652                 __free_filter(filter_item->filter);
1653                 list_del(&filter_item->list);
1654                 kfree(filter_item);
1655         }
1656         return -ENOMEM;
1657 }
1658
1659 static int create_filter_start(char *filter_string, bool set_str,
1660                                struct filter_parse_error **pse,
1661                                struct event_filter **filterp)
1662 {
1663         struct event_filter *filter;
1664         struct filter_parse_error *pe = NULL;
1665         int err = 0;
1666
1667         if (WARN_ON_ONCE(*pse || *filterp))
1668                 return -EINVAL;
1669
1670         filter = kzalloc(sizeof(*filter), GFP_KERNEL);
1671         if (filter && set_str) {
1672                 filter->filter_string = kstrdup(filter_string, GFP_KERNEL);
1673                 if (!filter->filter_string)
1674                         err = -ENOMEM;
1675         }
1676
1677         pe = kzalloc(sizeof(*pe), GFP_KERNEL);
1678
1679         if (!filter || !pe || err) {
1680                 kfree(pe);
1681                 __free_filter(filter);
1682                 return -ENOMEM;
1683         }
1684
1685         /* we're committed to creating a new filter */
1686         *filterp = filter;
1687         *pse = pe;
1688
1689         return 0;
1690 }
1691
1692 static void create_filter_finish(struct filter_parse_error *pe)
1693 {
1694         kfree(pe);
1695 }
1696
1697 /**
1698  * create_filter - create a filter for a trace_event_call
1699  * @call: trace_event_call to create a filter for
1700  * @filter_str: filter string
1701  * @set_str: remember @filter_str and enable detailed error in filter
1702  * @filterp: out param for created filter (always updated on return)
1703  *           Must be a pointer that references a NULL pointer.
1704  *
1705  * Creates a filter for @call with @filter_str.  If @set_str is %true,
1706  * @filter_str is copied and recorded in the new filter.
1707  *
1708  * On success, returns 0 and *@filterp points to the new filter.  On
1709  * failure, returns -errno and *@filterp may point to %NULL or to a new
1710  * filter.  In the latter case, the returned filter contains error
1711  * information if @set_str is %true and the caller is responsible for
1712  * freeing it.
1713  */
1714 static int create_filter(struct trace_event_call *call,
1715                          char *filter_string, bool set_str,
1716                          struct event_filter **filterp)
1717 {
1718         struct filter_parse_error *pe = NULL;
1719         int err;
1720
1721         /* filterp must point to NULL */
1722         if (WARN_ON(*filterp))
1723                 *filterp = NULL;
1724
1725         err = create_filter_start(filter_string, set_str, &pe, filterp);
1726         if (err)
1727                 return err;
1728
1729         err = process_preds(call, filter_string, *filterp, pe);
1730         if (err && set_str)
1731                 append_filter_err(pe, *filterp);
1732         create_filter_finish(pe);
1733
1734         return err;
1735 }
1736
1737 int create_event_filter(struct trace_event_call *call,
1738                         char *filter_str, bool set_str,
1739                         struct event_filter **filterp)
1740 {
1741         return create_filter(call, filter_str, set_str, filterp);
1742 }
1743
1744 /**
1745  * create_system_filter - create a filter for an event_subsystem
1746  * @system: event_subsystem to create a filter for
1747  * @filter_str: filter string
1748  * @filterp: out param for created filter (always updated on return)
1749  *
1750  * Identical to create_filter() except that it creates a subsystem filter
1751  * and always remembers @filter_str.
1752  */
1753 static int create_system_filter(struct trace_subsystem_dir *dir,
1754                                 struct trace_array *tr,
1755                                 char *filter_str, struct event_filter **filterp)
1756 {
1757         struct filter_parse_error *pe = NULL;
1758         int err;
1759
1760         err = create_filter_start(filter_str, true, &pe, filterp);
1761         if (!err) {
1762                 err = process_system_preds(dir, tr, pe, filter_str);
1763                 if (!err) {
1764                         /* System filters just show a default message */
1765                         kfree((*filterp)->filter_string);
1766                         (*filterp)->filter_string = NULL;
1767                 } else {
1768                         append_filter_err(pe, *filterp);
1769                 }
1770         }
1771         create_filter_finish(pe);
1772
1773         return err;
1774 }
1775
1776 /* caller must hold event_mutex */
1777 int apply_event_filter(struct trace_event_file *file, char *filter_string)
1778 {
1779         struct trace_event_call *call = file->event_call;
1780         struct event_filter *filter = NULL;
1781         int err;
1782
1783         if (!strcmp(strstrip(filter_string), "0")) {
1784                 filter_disable(file);
1785                 filter = event_filter(file);
1786
1787                 if (!filter)
1788                         return 0;
1789
1790                 event_clear_filter(file);
1791
1792                 /* Make sure the filter is not being used */
1793                 tracepoint_synchronize_unregister();
1794                 __free_filter(filter);
1795
1796                 return 0;
1797         }
1798
1799         err = create_filter(call, filter_string, true, &filter);
1800
1801         /*
1802          * Always swap the call filter with the new filter
1803          * even if there was an error. If there was an error
1804          * in the filter, we disable the filter and show the error
1805          * string
1806          */
1807         if (filter) {
1808                 struct event_filter *tmp;
1809
1810                 tmp = event_filter(file);
1811                 if (!err)
1812                         event_set_filtered_flag(file);
1813                 else
1814                         filter_disable(file);
1815
1816                 event_set_filter(file, filter);
1817
1818                 if (tmp) {
1819                         /* Make sure the call is done with the filter */
1820                         tracepoint_synchronize_unregister();
1821                         __free_filter(tmp);
1822                 }
1823         }
1824
1825         return err;
1826 }
1827
1828 int apply_subsystem_event_filter(struct trace_subsystem_dir *dir,
1829                                  char *filter_string)
1830 {
1831         struct event_subsystem *system = dir->subsystem;
1832         struct trace_array *tr = dir->tr;
1833         struct event_filter *filter = NULL;
1834         int err = 0;
1835
1836         mutex_lock(&event_mutex);
1837
1838         /* Make sure the system still has events */
1839         if (!dir->nr_events) {
1840                 err = -ENODEV;
1841                 goto out_unlock;
1842         }
1843
1844         if (!strcmp(strstrip(filter_string), "0")) {
1845                 filter_free_subsystem_preds(dir, tr);
1846                 remove_filter_string(system->filter);
1847                 filter = system->filter;
1848                 system->filter = NULL;
1849                 /* Ensure all filters are no longer used */
1850                 tracepoint_synchronize_unregister();
1851                 filter_free_subsystem_filters(dir, tr);
1852                 __free_filter(filter);
1853                 goto out_unlock;
1854         }
1855
1856         err = create_system_filter(dir, tr, filter_string, &filter);
1857         if (filter) {
1858                 /*
1859                  * No event actually uses the system filter
1860                  * we can free it without synchronize_sched().
1861                  */
1862                 __free_filter(system->filter);
1863                 system->filter = filter;
1864         }
1865 out_unlock:
1866         mutex_unlock(&event_mutex);
1867
1868         return err;
1869 }
1870
1871 #ifdef CONFIG_PERF_EVENTS
1872
1873 void ftrace_profile_free_filter(struct perf_event *event)
1874 {
1875         struct event_filter *filter = event->filter;
1876
1877         event->filter = NULL;
1878         __free_filter(filter);
1879 }
1880
1881 struct function_filter_data {
1882         struct ftrace_ops *ops;
1883         int first_filter;
1884         int first_notrace;
1885 };
1886
1887 #ifdef CONFIG_FUNCTION_TRACER
1888 static char **
1889 ftrace_function_filter_re(char *buf, int len, int *count)
1890 {
1891         char *str, **re;
1892
1893         str = kstrndup(buf, len, GFP_KERNEL);
1894         if (!str)
1895                 return NULL;
1896
1897         /*
1898          * The argv_split function takes white space
1899          * as a separator, so convert ',' into spaces.
1900          */
1901         strreplace(str, ',', ' ');
1902
1903         re = argv_split(GFP_KERNEL, str, count);
1904         kfree(str);
1905         return re;
1906 }
1907
1908 static int ftrace_function_set_regexp(struct ftrace_ops *ops, int filter,
1909                                       int reset, char *re, int len)
1910 {
1911         int ret;
1912
1913         if (filter)
1914                 ret = ftrace_set_filter(ops, re, len, reset);
1915         else
1916                 ret = ftrace_set_notrace(ops, re, len, reset);
1917
1918         return ret;
1919 }
1920
1921 static int __ftrace_function_set_filter(int filter, char *buf, int len,
1922                                         struct function_filter_data *data)
1923 {
1924         int i, re_cnt, ret = -EINVAL;
1925         int *reset;
1926         char **re;
1927
1928         reset = filter ? &data->first_filter : &data->first_notrace;
1929
1930         /*
1931          * The 'ip' field could have multiple filters set, separated
1932          * either by space or comma. We first cut the filter and apply
1933          * all pieces separatelly.
1934          */
1935         re = ftrace_function_filter_re(buf, len, &re_cnt);
1936         if (!re)
1937                 return -EINVAL;
1938
1939         for (i = 0; i < re_cnt; i++) {
1940                 ret = ftrace_function_set_regexp(data->ops, filter, *reset,
1941                                                  re[i], strlen(re[i]));
1942                 if (ret)
1943                         break;
1944
1945                 if (*reset)
1946                         *reset = 0;
1947         }
1948
1949         argv_free(re);
1950         return ret;
1951 }
1952
1953 static int ftrace_function_check_pred(struct filter_pred *pred)
1954 {
1955         struct ftrace_event_field *field = pred->field;
1956
1957         /*
1958          * Check the predicate for function trace, verify:
1959          *  - only '==' and '!=' is used
1960          *  - the 'ip' field is used
1961          */
1962         if ((pred->op != OP_EQ) && (pred->op != OP_NE))
1963                 return -EINVAL;
1964
1965         if (strcmp(field->name, "ip"))
1966                 return -EINVAL;
1967
1968         return 0;
1969 }
1970
1971 static int ftrace_function_set_filter_pred(struct filter_pred *pred,
1972                                            struct function_filter_data *data)
1973 {
1974         int ret;
1975
1976         /* Checking the node is valid for function trace. */
1977         ret = ftrace_function_check_pred(pred);
1978         if (ret)
1979                 return ret;
1980
1981         return __ftrace_function_set_filter(pred->op == OP_EQ,
1982                                             pred->regex.pattern,
1983                                             pred->regex.len,
1984                                             data);
1985 }
1986
1987 static bool is_or(struct prog_entry *prog, int i)
1988 {
1989         int target;
1990
1991         /*
1992          * Only "||" is allowed for function events, thus,
1993          * all true branches should jump to true, and any
1994          * false branch should jump to false.
1995          */
1996         target = prog[i].target + 1;
1997         /* True and false have NULL preds (all prog entries should jump to one */
1998         if (prog[target].pred)
1999                 return false;
2000
2001         /* prog[target].target is 1 for TRUE, 0 for FALSE */
2002         return prog[i].when_to_branch == prog[target].target;
2003 }
2004
2005 static int ftrace_function_set_filter(struct perf_event *event,
2006                                       struct event_filter *filter)
2007 {
2008         struct prog_entry *prog = rcu_dereference_protected(filter->prog,
2009                                                 lockdep_is_held(&event_mutex));
2010         struct function_filter_data data = {
2011                 .first_filter  = 1,
2012                 .first_notrace = 1,
2013                 .ops           = &event->ftrace_ops,
2014         };
2015         int i;
2016
2017         for (i = 0; prog[i].pred; i++) {
2018                 struct filter_pred *pred = prog[i].pred;
2019
2020                 if (!is_or(prog, i))
2021                         return -EINVAL;
2022
2023                 if (ftrace_function_set_filter_pred(pred, &data) < 0)
2024                         return -EINVAL;
2025         }
2026         return 0;
2027 }
2028 #else
2029 static int ftrace_function_set_filter(struct perf_event *event,
2030                                       struct event_filter *filter)
2031 {
2032         return -ENODEV;
2033 }
2034 #endif /* CONFIG_FUNCTION_TRACER */
2035
2036 int ftrace_profile_set_filter(struct perf_event *event, int event_id,
2037                               char *filter_str)
2038 {
2039         int err;
2040         struct event_filter *filter = NULL;
2041         struct trace_event_call *call;
2042
2043         mutex_lock(&event_mutex);
2044
2045         call = event->tp_event;
2046
2047         err = -EINVAL;
2048         if (!call)
2049                 goto out_unlock;
2050
2051         err = -EEXIST;
2052         if (event->filter)
2053                 goto out_unlock;
2054
2055         err = create_filter(call, filter_str, false, &filter);
2056         if (err)
2057                 goto free_filter;
2058
2059         if (ftrace_event_is_function(call))
2060                 err = ftrace_function_set_filter(event, filter);
2061         else
2062                 event->filter = filter;
2063
2064 free_filter:
2065         if (err || ftrace_event_is_function(call))
2066                 __free_filter(filter);
2067
2068 out_unlock:
2069         mutex_unlock(&event_mutex);
2070
2071         return err;
2072 }
2073
2074 #endif /* CONFIG_PERF_EVENTS */
2075
2076 #ifdef CONFIG_FTRACE_STARTUP_TEST
2077
2078 #include <linux/types.h>
2079 #include <linux/tracepoint.h>
2080
2081 #define CREATE_TRACE_POINTS
2082 #include "trace_events_filter_test.h"
2083
2084 #define DATA_REC(m, va, vb, vc, vd, ve, vf, vg, vh, nvisit) \
2085 { \
2086         .filter = FILTER, \
2087         .rec    = { .a = va, .b = vb, .c = vc, .d = vd, \
2088                     .e = ve, .f = vf, .g = vg, .h = vh }, \
2089         .match  = m, \
2090         .not_visited = nvisit, \
2091 }
2092 #define YES 1
2093 #define NO  0
2094
2095 static struct test_filter_data_t {
2096         char *filter;
2097         struct trace_event_raw_ftrace_test_filter rec;
2098         int match;
2099         char *not_visited;
2100 } test_filter_data[] = {
2101 #define FILTER "a == 1 && b == 1 && c == 1 && d == 1 && " \
2102                "e == 1 && f == 1 && g == 1 && h == 1"
2103         DATA_REC(YES, 1, 1, 1, 1, 1, 1, 1, 1, ""),
2104         DATA_REC(NO,  0, 1, 1, 1, 1, 1, 1, 1, "bcdefgh"),
2105         DATA_REC(NO,  1, 1, 1, 1, 1, 1, 1, 0, ""),
2106 #undef FILTER
2107 #define FILTER "a == 1 || b == 1 || c == 1 || d == 1 || " \
2108                "e == 1 || f == 1 || g == 1 || h == 1"
2109         DATA_REC(NO,  0, 0, 0, 0, 0, 0, 0, 0, ""),
2110         DATA_REC(YES, 0, 0, 0, 0, 0, 0, 0, 1, ""),
2111         DATA_REC(YES, 1, 0, 0, 0, 0, 0, 0, 0, "bcdefgh"),
2112 #undef FILTER
2113 #define FILTER "(a == 1 || b == 1) && (c == 1 || d == 1) && " \
2114                "(e == 1 || f == 1) && (g == 1 || h == 1)"
2115         DATA_REC(NO,  0, 0, 1, 1, 1, 1, 1, 1, "dfh"),
2116         DATA_REC(YES, 0, 1, 0, 1, 0, 1, 0, 1, ""),
2117         DATA_REC(YES, 1, 0, 1, 0, 0, 1, 0, 1, "bd"),
2118         DATA_REC(NO,  1, 0, 1, 0, 0, 1, 0, 0, "bd"),
2119 #undef FILTER
2120 #define FILTER "(a == 1 && b == 1) || (c == 1 && d == 1) || " \
2121                "(e == 1 && f == 1) || (g == 1 && h == 1)"
2122         DATA_REC(YES, 1, 0, 1, 1, 1, 1, 1, 1, "efgh"),
2123         DATA_REC(YES, 0, 0, 0, 0, 0, 0, 1, 1, ""),
2124         DATA_REC(NO,  0, 0, 0, 0, 0, 0, 0, 1, ""),
2125 #undef FILTER
2126 #define FILTER "(a == 1 && b == 1) && (c == 1 && d == 1) && " \
2127                "(e == 1 && f == 1) || (g == 1 && h == 1)"
2128         DATA_REC(YES, 1, 1, 1, 1, 1, 1, 0, 0, "gh"),
2129         DATA_REC(NO,  0, 0, 0, 0, 0, 0, 0, 1, ""),
2130         DATA_REC(YES, 1, 1, 1, 1, 1, 0, 1, 1, ""),
2131 #undef FILTER
2132 #define FILTER "((a == 1 || b == 1) || (c == 1 || d == 1) || " \
2133                "(e == 1 || f == 1)) && (g == 1 || h == 1)"
2134         DATA_REC(YES, 1, 1, 1, 1, 1, 1, 0, 1, "bcdef"),
2135         DATA_REC(NO,  0, 0, 0, 0, 0, 0, 0, 0, ""),
2136         DATA_REC(YES, 1, 1, 1, 1, 1, 0, 1, 1, "h"),
2137 #undef FILTER
2138 #define FILTER "((((((((a == 1) && (b == 1)) || (c == 1)) && (d == 1)) || " \
2139                "(e == 1)) && (f == 1)) || (g == 1)) && (h == 1))"
2140         DATA_REC(YES, 1, 1, 1, 1, 1, 1, 1, 1, "ceg"),
2141         DATA_REC(NO,  0, 1, 0, 1, 0, 1, 0, 1, ""),
2142         DATA_REC(NO,  1, 0, 1, 0, 1, 0, 1, 0, ""),
2143 #undef FILTER
2144 #define FILTER "((((((((a == 1) || (b == 1)) && (c == 1)) || (d == 1)) && " \
2145                "(e == 1)) || (f == 1)) && (g == 1)) || (h == 1))"
2146         DATA_REC(YES, 1, 1, 1, 1, 1, 1, 1, 1, "bdfh"),
2147         DATA_REC(YES, 0, 1, 0, 1, 0, 1, 0, 1, ""),
2148         DATA_REC(YES, 1, 0, 1, 0, 1, 0, 1, 0, "bdfh"),
2149 };
2150
2151 #undef DATA_REC
2152 #undef FILTER
2153 #undef YES
2154 #undef NO
2155
2156 #define DATA_CNT ARRAY_SIZE(test_filter_data)
2157
2158 static int test_pred_visited;
2159
2160 static int test_pred_visited_fn(struct filter_pred *pred, void *event)
2161 {
2162         struct ftrace_event_field *field = pred->field;
2163
2164         test_pred_visited = 1;
2165         printk(KERN_INFO "\npred visited %s\n", field->name);
2166         return 1;
2167 }
2168
2169 static void update_pred_fn(struct event_filter *filter, char *fields)
2170 {
2171         struct prog_entry *prog = rcu_dereference_protected(filter->prog,
2172                                                 lockdep_is_held(&event_mutex));
2173         int i;
2174
2175         for (i = 0; prog[i].pred; i++) {
2176                 struct filter_pred *pred = prog[i].pred;
2177                 struct ftrace_event_field *field = pred->field;
2178
2179                 WARN_ON_ONCE(!pred->fn);
2180
2181                 if (!field) {
2182                         WARN_ONCE(1, "all leafs should have field defined %d", i);
2183                         continue;
2184                 }
2185
2186                 if (!strchr(fields, *field->name))
2187                         continue;
2188
2189                 pred->fn = test_pred_visited_fn;
2190         }
2191 }
2192
2193 static __init int ftrace_test_event_filter(void)
2194 {
2195         int i;
2196
2197         printk(KERN_INFO "Testing ftrace filter: ");
2198
2199         for (i = 0; i < DATA_CNT; i++) {
2200                 struct event_filter *filter = NULL;
2201                 struct test_filter_data_t *d = &test_filter_data[i];
2202                 int err;
2203
2204                 err = create_filter(&event_ftrace_test_filter, d->filter,
2205                                     false, &filter);
2206                 if (err) {
2207                         printk(KERN_INFO
2208                                "Failed to get filter for '%s', err %d\n",
2209                                d->filter, err);
2210                         __free_filter(filter);
2211                         break;
2212                 }
2213
2214                 /* Needed to dereference filter->prog */
2215                 mutex_lock(&event_mutex);
2216                 /*
2217                  * The preemption disabling is not really needed for self
2218                  * tests, but the rcu dereference will complain without it.
2219                  */
2220                 preempt_disable();
2221                 if (*d->not_visited)
2222                         update_pred_fn(filter, d->not_visited);
2223
2224                 test_pred_visited = 0;
2225                 err = filter_match_preds(filter, &d->rec);
2226                 preempt_enable();
2227
2228                 mutex_unlock(&event_mutex);
2229
2230                 __free_filter(filter);
2231
2232                 if (test_pred_visited) {
2233                         printk(KERN_INFO
2234                                "Failed, unwanted pred visited for filter %s\n",
2235                                d->filter);
2236                         break;
2237                 }
2238
2239                 if (err != d->match) {
2240                         printk(KERN_INFO
2241                                "Failed to match filter '%s', expected %d\n",
2242                                d->filter, d->match);
2243                         break;
2244                 }
2245         }
2246
2247         if (i == DATA_CNT)
2248                 printk(KERN_CONT "OK\n");
2249
2250         return 0;
2251 }
2252
2253 late_initcall(ftrace_test_event_filter);
2254
2255 #endif /* CONFIG_FTRACE_STARTUP_TEST */