tracing: Add comment to predicate_parse() about "&&" or "||"
[sfrench/cifs-2.6.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 = kmalloc_array(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                                 return ERR_PTR(-EINVAL);
456                         *(++top) = invert;
457                         continue;
458                 case '!':                                       /* #3 */
459                         if (!is_not(next))
460                                 break;
461                         invert = !invert;
462                         continue;
463                 }
464
465                 if (N >= nr_preds) {
466                         parse_error(pe, FILT_ERR_TOO_MANY_PREDS, next - str);
467                         goto out_free;
468                 }
469
470                 inverts[N] = invert;                            /* #4 */
471                 prog[N].target = N-1;
472
473                 len = parse_pred(next, data, ptr - str, pe, &prog[N].pred);
474                 if (len < 0) {
475                         ret = len;
476                         goto out_free;
477                 }
478                 ptr = next + len;
479
480                 N++;
481
482                 ret = -1;
483                 while (1) {                                     /* #5 */
484                         next = ptr++;
485                         if (isspace(*next))
486                                 continue;
487
488                         switch (*next) {
489                         case ')':
490                         case '\0':
491                                 break;
492                         case '&':
493                         case '|':
494                                 /* accepting only "&&" or "||" */
495                                 if (next[1] == next[0]) {
496                                         ptr++;
497                                         break;
498                                 }
499                                 /* fall through */
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         kfree(prog_stack);
582         return ERR_PTR(ret);
583 }
584
585 #define DEFINE_COMPARISON_PRED(type)                                    \
586 static int filter_pred_LT_##type(struct filter_pred *pred, void *event) \
587 {                                                                       \
588         type *addr = (type *)(event + pred->offset);                    \
589         type val = (type)pred->val;                                     \
590         return *addr < val;                                             \
591 }                                                                       \
592 static int filter_pred_LE_##type(struct filter_pred *pred, void *event) \
593 {                                                                       \
594         type *addr = (type *)(event + pred->offset);                    \
595         type val = (type)pred->val;                                     \
596         return *addr <= val;                                            \
597 }                                                                       \
598 static int filter_pred_GT_##type(struct filter_pred *pred, void *event) \
599 {                                                                       \
600         type *addr = (type *)(event + pred->offset);                    \
601         type val = (type)pred->val;                                     \
602         return *addr > val;                                     \
603 }                                                                       \
604 static int filter_pred_GE_##type(struct filter_pred *pred, void *event) \
605 {                                                                       \
606         type *addr = (type *)(event + pred->offset);                    \
607         type val = (type)pred->val;                                     \
608         return *addr >= val;                                            \
609 }                                                                       \
610 static int filter_pred_BAND_##type(struct filter_pred *pred, void *event) \
611 {                                                                       \
612         type *addr = (type *)(event + pred->offset);                    \
613         type val = (type)pred->val;                                     \
614         return !!(*addr & val);                                         \
615 }                                                                       \
616 static const filter_pred_fn_t pred_funcs_##type[] = {                   \
617         filter_pred_LE_##type,                                          \
618         filter_pred_LT_##type,                                          \
619         filter_pred_GE_##type,                                          \
620         filter_pred_GT_##type,                                          \
621         filter_pred_BAND_##type,                                        \
622 };
623
624 #define DEFINE_EQUALITY_PRED(size)                                      \
625 static int filter_pred_##size(struct filter_pred *pred, void *event)    \
626 {                                                                       \
627         u##size *addr = (u##size *)(event + pred->offset);              \
628         u##size val = (u##size)pred->val;                               \
629         int match;                                                      \
630                                                                         \
631         match = (val == *addr) ^ pred->not;                             \
632                                                                         \
633         return match;                                                   \
634 }
635
636 DEFINE_COMPARISON_PRED(s64);
637 DEFINE_COMPARISON_PRED(u64);
638 DEFINE_COMPARISON_PRED(s32);
639 DEFINE_COMPARISON_PRED(u32);
640 DEFINE_COMPARISON_PRED(s16);
641 DEFINE_COMPARISON_PRED(u16);
642 DEFINE_COMPARISON_PRED(s8);
643 DEFINE_COMPARISON_PRED(u8);
644
645 DEFINE_EQUALITY_PRED(64);
646 DEFINE_EQUALITY_PRED(32);
647 DEFINE_EQUALITY_PRED(16);
648 DEFINE_EQUALITY_PRED(8);
649
650 /* Filter predicate for fixed sized arrays of characters */
651 static int filter_pred_string(struct filter_pred *pred, void *event)
652 {
653         char *addr = (char *)(event + pred->offset);
654         int cmp, match;
655
656         cmp = pred->regex.match(addr, &pred->regex, pred->regex.field_len);
657
658         match = cmp ^ pred->not;
659
660         return match;
661 }
662
663 /* Filter predicate for char * pointers */
664 static int filter_pred_pchar(struct filter_pred *pred, void *event)
665 {
666         char **addr = (char **)(event + pred->offset);
667         int cmp, match;
668         int len = strlen(*addr) + 1;    /* including tailing '\0' */
669
670         cmp = pred->regex.match(*addr, &pred->regex, len);
671
672         match = cmp ^ pred->not;
673
674         return match;
675 }
676
677 /*
678  * Filter predicate for dynamic sized arrays of characters.
679  * These are implemented through a list of strings at the end
680  * of the entry.
681  * Also each of these strings have a field in the entry which
682  * contains its offset from the beginning of the entry.
683  * We have then first to get this field, dereference it
684  * and add it to the address of the entry, and at last we have
685  * the address of the string.
686  */
687 static int filter_pred_strloc(struct filter_pred *pred, void *event)
688 {
689         u32 str_item = *(u32 *)(event + pred->offset);
690         int str_loc = str_item & 0xffff;
691         int str_len = str_item >> 16;
692         char *addr = (char *)(event + str_loc);
693         int cmp, match;
694
695         cmp = pred->regex.match(addr, &pred->regex, str_len);
696
697         match = cmp ^ pred->not;
698
699         return match;
700 }
701
702 /* Filter predicate for CPUs. */
703 static int filter_pred_cpu(struct filter_pred *pred, void *event)
704 {
705         int cpu, cmp;
706
707         cpu = raw_smp_processor_id();
708         cmp = pred->val;
709
710         switch (pred->op) {
711         case OP_EQ:
712                 return cpu == cmp;
713         case OP_NE:
714                 return cpu != cmp;
715         case OP_LT:
716                 return cpu < cmp;
717         case OP_LE:
718                 return cpu <= cmp;
719         case OP_GT:
720                 return cpu > cmp;
721         case OP_GE:
722                 return cpu >= cmp;
723         default:
724                 return 0;
725         }
726 }
727
728 /* Filter predicate for COMM. */
729 static int filter_pred_comm(struct filter_pred *pred, void *event)
730 {
731         int cmp;
732
733         cmp = pred->regex.match(current->comm, &pred->regex,
734                                 TASK_COMM_LEN);
735         return cmp ^ pred->not;
736 }
737
738 static int filter_pred_none(struct filter_pred *pred, void *event)
739 {
740         return 0;
741 }
742
743 /*
744  * regex_match_foo - Basic regex callbacks
745  *
746  * @str: the string to be searched
747  * @r:   the regex structure containing the pattern string
748  * @len: the length of the string to be searched (including '\0')
749  *
750  * Note:
751  * - @str might not be NULL-terminated if it's of type DYN_STRING
752  *   or STATIC_STRING, unless @len is zero.
753  */
754
755 static int regex_match_full(char *str, struct regex *r, int len)
756 {
757         /* len of zero means str is dynamic and ends with '\0' */
758         if (!len)
759                 return strcmp(str, r->pattern) == 0;
760
761         return strncmp(str, r->pattern, len) == 0;
762 }
763
764 static int regex_match_front(char *str, struct regex *r, int len)
765 {
766         if (len && len < r->len)
767                 return 0;
768
769         return strncmp(str, r->pattern, r->len) == 0;
770 }
771
772 static int regex_match_middle(char *str, struct regex *r, int len)
773 {
774         if (!len)
775                 return strstr(str, r->pattern) != NULL;
776
777         return strnstr(str, r->pattern, len) != NULL;
778 }
779
780 static int regex_match_end(char *str, struct regex *r, int len)
781 {
782         int strlen = len - 1;
783
784         if (strlen >= r->len &&
785             memcmp(str + strlen - r->len, r->pattern, r->len) == 0)
786                 return 1;
787         return 0;
788 }
789
790 static int regex_match_glob(char *str, struct regex *r, int len __maybe_unused)
791 {
792         if (glob_match(r->pattern, str))
793                 return 1;
794         return 0;
795 }
796
797 /**
798  * filter_parse_regex - parse a basic regex
799  * @buff:   the raw regex
800  * @len:    length of the regex
801  * @search: will point to the beginning of the string to compare
802  * @not:    tell whether the match will have to be inverted
803  *
804  * This passes in a buffer containing a regex and this function will
805  * set search to point to the search part of the buffer and
806  * return the type of search it is (see enum above).
807  * This does modify buff.
808  *
809  * Returns enum type.
810  *  search returns the pointer to use for comparison.
811  *  not returns 1 if buff started with a '!'
812  *     0 otherwise.
813  */
814 enum regex_type filter_parse_regex(char *buff, int len, char **search, int *not)
815 {
816         int type = MATCH_FULL;
817         int i;
818
819         if (buff[0] == '!') {
820                 *not = 1;
821                 buff++;
822                 len--;
823         } else
824                 *not = 0;
825
826         *search = buff;
827
828         for (i = 0; i < len; i++) {
829                 if (buff[i] == '*') {
830                         if (!i) {
831                                 type = MATCH_END_ONLY;
832                         } else if (i == len - 1) {
833                                 if (type == MATCH_END_ONLY)
834                                         type = MATCH_MIDDLE_ONLY;
835                                 else
836                                         type = MATCH_FRONT_ONLY;
837                                 buff[i] = 0;
838                                 break;
839                         } else {        /* pattern continues, use full glob */
840                                 return MATCH_GLOB;
841                         }
842                 } else if (strchr("[?\\", buff[i])) {
843                         return MATCH_GLOB;
844                 }
845         }
846         if (buff[0] == '*')
847                 *search = buff + 1;
848
849         return type;
850 }
851
852 static void filter_build_regex(struct filter_pred *pred)
853 {
854         struct regex *r = &pred->regex;
855         char *search;
856         enum regex_type type = MATCH_FULL;
857
858         if (pred->op == OP_GLOB) {
859                 type = filter_parse_regex(r->pattern, r->len, &search, &pred->not);
860                 r->len = strlen(search);
861                 memmove(r->pattern, search, r->len+1);
862         }
863
864         switch (type) {
865         case MATCH_FULL:
866                 r->match = regex_match_full;
867                 break;
868         case MATCH_FRONT_ONLY:
869                 r->match = regex_match_front;
870                 break;
871         case MATCH_MIDDLE_ONLY:
872                 r->match = regex_match_middle;
873                 break;
874         case MATCH_END_ONLY:
875                 r->match = regex_match_end;
876                 break;
877         case MATCH_GLOB:
878                 r->match = regex_match_glob;
879                 break;
880         }
881 }
882
883 /* return 1 if event matches, 0 otherwise (discard) */
884 int filter_match_preds(struct event_filter *filter, void *rec)
885 {
886         struct prog_entry *prog;
887         int i;
888
889         /* no filter is considered a match */
890         if (!filter)
891                 return 1;
892
893         /* Protected by either SRCU(tracepoint_srcu) or preempt_disable */
894         prog = rcu_dereference_raw(filter->prog);
895         if (!prog)
896                 return 1;
897
898         for (i = 0; prog[i].pred; i++) {
899                 struct filter_pred *pred = prog[i].pred;
900                 int match = pred->fn(pred, rec);
901                 if (match == prog[i].when_to_branch)
902                         i = prog[i].target;
903         }
904         return prog[i].target;
905 }
906 EXPORT_SYMBOL_GPL(filter_match_preds);
907
908 static void remove_filter_string(struct event_filter *filter)
909 {
910         if (!filter)
911                 return;
912
913         kfree(filter->filter_string);
914         filter->filter_string = NULL;
915 }
916
917 static void append_filter_err(struct filter_parse_error *pe,
918                               struct event_filter *filter)
919 {
920         struct trace_seq *s;
921         int pos = pe->lasterr_pos;
922         char *buf;
923         int len;
924
925         if (WARN_ON(!filter->filter_string))
926                 return;
927
928         s = kmalloc(sizeof(*s), GFP_KERNEL);
929         if (!s)
930                 return;
931         trace_seq_init(s);
932
933         len = strlen(filter->filter_string);
934         if (pos > len)
935                 pos = len;
936
937         /* indexing is off by one */
938         if (pos)
939                 pos++;
940
941         trace_seq_puts(s, filter->filter_string);
942         if (pe->lasterr > 0) {
943                 trace_seq_printf(s, "\n%*s", pos, "^");
944                 trace_seq_printf(s, "\nparse_error: %s\n", err_text[pe->lasterr]);
945         } else {
946                 trace_seq_printf(s, "\nError: (%d)\n", pe->lasterr);
947         }
948         trace_seq_putc(s, 0);
949         buf = kmemdup_nul(s->buffer, s->seq.len, GFP_KERNEL);
950         if (buf) {
951                 kfree(filter->filter_string);
952                 filter->filter_string = buf;
953         }
954         kfree(s);
955 }
956
957 static inline struct event_filter *event_filter(struct trace_event_file *file)
958 {
959         return file->filter;
960 }
961
962 /* caller must hold event_mutex */
963 void print_event_filter(struct trace_event_file *file, struct trace_seq *s)
964 {
965         struct event_filter *filter = event_filter(file);
966
967         if (filter && filter->filter_string)
968                 trace_seq_printf(s, "%s\n", filter->filter_string);
969         else
970                 trace_seq_puts(s, "none\n");
971 }
972
973 void print_subsystem_event_filter(struct event_subsystem *system,
974                                   struct trace_seq *s)
975 {
976         struct event_filter *filter;
977
978         mutex_lock(&event_mutex);
979         filter = system->filter;
980         if (filter && filter->filter_string)
981                 trace_seq_printf(s, "%s\n", filter->filter_string);
982         else
983                 trace_seq_puts(s, DEFAULT_SYS_FILTER_MESSAGE "\n");
984         mutex_unlock(&event_mutex);
985 }
986
987 static void free_prog(struct event_filter *filter)
988 {
989         struct prog_entry *prog;
990         int i;
991
992         prog = rcu_access_pointer(filter->prog);
993         if (!prog)
994                 return;
995
996         for (i = 0; prog[i].pred; i++)
997                 kfree(prog[i].pred);
998         kfree(prog);
999 }
1000
1001 static void filter_disable(struct trace_event_file *file)
1002 {
1003         unsigned long old_flags = file->flags;
1004
1005         file->flags &= ~EVENT_FILE_FL_FILTERED;
1006
1007         if (old_flags != file->flags)
1008                 trace_buffered_event_disable();
1009 }
1010
1011 static void __free_filter(struct event_filter *filter)
1012 {
1013         if (!filter)
1014                 return;
1015
1016         free_prog(filter);
1017         kfree(filter->filter_string);
1018         kfree(filter);
1019 }
1020
1021 void free_event_filter(struct event_filter *filter)
1022 {
1023         __free_filter(filter);
1024 }
1025
1026 static inline void __remove_filter(struct trace_event_file *file)
1027 {
1028         filter_disable(file);
1029         remove_filter_string(file->filter);
1030 }
1031
1032 static void filter_free_subsystem_preds(struct trace_subsystem_dir *dir,
1033                                         struct trace_array *tr)
1034 {
1035         struct trace_event_file *file;
1036
1037         list_for_each_entry(file, &tr->events, list) {
1038                 if (file->system != dir)
1039                         continue;
1040                 __remove_filter(file);
1041         }
1042 }
1043
1044 static inline void __free_subsystem_filter(struct trace_event_file *file)
1045 {
1046         __free_filter(file->filter);
1047         file->filter = NULL;
1048 }
1049
1050 static void filter_free_subsystem_filters(struct trace_subsystem_dir *dir,
1051                                           struct trace_array *tr)
1052 {
1053         struct trace_event_file *file;
1054
1055         list_for_each_entry(file, &tr->events, list) {
1056                 if (file->system != dir)
1057                         continue;
1058                 __free_subsystem_filter(file);
1059         }
1060 }
1061
1062 int filter_assign_type(const char *type)
1063 {
1064         if (strstr(type, "__data_loc") && strstr(type, "char"))
1065                 return FILTER_DYN_STRING;
1066
1067         if (strchr(type, '[') && strstr(type, "char"))
1068                 return FILTER_STATIC_STRING;
1069
1070         return FILTER_OTHER;
1071 }
1072
1073 static filter_pred_fn_t select_comparison_fn(enum filter_op_ids op,
1074                                             int field_size, int field_is_signed)
1075 {
1076         filter_pred_fn_t fn = NULL;
1077         int pred_func_index = -1;
1078
1079         switch (op) {
1080         case OP_EQ:
1081         case OP_NE:
1082                 break;
1083         default:
1084                 if (WARN_ON_ONCE(op < PRED_FUNC_START))
1085                         return NULL;
1086                 pred_func_index = op - PRED_FUNC_START;
1087                 if (WARN_ON_ONCE(pred_func_index > PRED_FUNC_MAX))
1088                         return NULL;
1089         }
1090
1091         switch (field_size) {
1092         case 8:
1093                 if (pred_func_index < 0)
1094                         fn = filter_pred_64;
1095                 else if (field_is_signed)
1096                         fn = pred_funcs_s64[pred_func_index];
1097                 else
1098                         fn = pred_funcs_u64[pred_func_index];
1099                 break;
1100         case 4:
1101                 if (pred_func_index < 0)
1102                         fn = filter_pred_32;
1103                 else if (field_is_signed)
1104                         fn = pred_funcs_s32[pred_func_index];
1105                 else
1106                         fn = pred_funcs_u32[pred_func_index];
1107                 break;
1108         case 2:
1109                 if (pred_func_index < 0)
1110                         fn = filter_pred_16;
1111                 else if (field_is_signed)
1112                         fn = pred_funcs_s16[pred_func_index];
1113                 else
1114                         fn = pred_funcs_u16[pred_func_index];
1115                 break;
1116         case 1:
1117                 if (pred_func_index < 0)
1118                         fn = filter_pred_8;
1119                 else if (field_is_signed)
1120                         fn = pred_funcs_s8[pred_func_index];
1121                 else
1122                         fn = pred_funcs_u8[pred_func_index];
1123                 break;
1124         }
1125
1126         return fn;
1127 }
1128
1129 /* Called when a predicate is encountered by predicate_parse() */
1130 static int parse_pred(const char *str, void *data,
1131                       int pos, struct filter_parse_error *pe,
1132                       struct filter_pred **pred_ptr)
1133 {
1134         struct trace_event_call *call = data;
1135         struct ftrace_event_field *field;
1136         struct filter_pred *pred = NULL;
1137         char num_buf[24];       /* Big enough to hold an address */
1138         char *field_name;
1139         char q;
1140         u64 val;
1141         int len;
1142         int ret;
1143         int op;
1144         int s;
1145         int i = 0;
1146
1147         /* First find the field to associate to */
1148         while (isspace(str[i]))
1149                 i++;
1150         s = i;
1151
1152         while (isalnum(str[i]) || str[i] == '_')
1153                 i++;
1154
1155         len = i - s;
1156
1157         if (!len)
1158                 return -1;
1159
1160         field_name = kmemdup_nul(str + s, len, GFP_KERNEL);
1161         if (!field_name)
1162                 return -ENOMEM;
1163
1164         /* Make sure that the field exists */
1165
1166         field = trace_find_event_field(call, field_name);
1167         kfree(field_name);
1168         if (!field) {
1169                 parse_error(pe, FILT_ERR_FIELD_NOT_FOUND, pos + i);
1170                 return -EINVAL;
1171         }
1172
1173         while (isspace(str[i]))
1174                 i++;
1175
1176         /* Make sure this op is supported */
1177         for (op = 0; ops[op]; op++) {
1178                 /* This is why '<=' must come before '<' in ops[] */
1179                 if (strncmp(str + i, ops[op], strlen(ops[op])) == 0)
1180                         break;
1181         }
1182
1183         if (!ops[op]) {
1184                 parse_error(pe, FILT_ERR_INVALID_OP, pos + i);
1185                 goto err_free;
1186         }
1187
1188         i += strlen(ops[op]);
1189
1190         while (isspace(str[i]))
1191                 i++;
1192
1193         s = i;
1194
1195         pred = kzalloc(sizeof(*pred), GFP_KERNEL);
1196         if (!pred)
1197                 return -ENOMEM;
1198
1199         pred->field = field;
1200         pred->offset = field->offset;
1201         pred->op = op;
1202
1203         if (ftrace_event_is_function(call)) {
1204                 /*
1205                  * Perf does things different with function events.
1206                  * It only allows an "ip" field, and expects a string.
1207                  * But the string does not need to be surrounded by quotes.
1208                  * If it is a string, the assigned function as a nop,
1209                  * (perf doesn't use it) and grab everything.
1210                  */
1211                 if (strcmp(field->name, "ip") != 0) {
1212                          parse_error(pe, FILT_ERR_IP_FIELD_ONLY, pos + i);
1213                          goto err_free;
1214                  }
1215                  pred->fn = filter_pred_none;
1216
1217                  /*
1218                   * Quotes are not required, but if they exist then we need
1219                   * to read them till we hit a matching one.
1220                   */
1221                  if (str[i] == '\'' || str[i] == '"')
1222                          q = str[i];
1223                  else
1224                          q = 0;
1225
1226                  for (i++; str[i]; i++) {
1227                          if (q && str[i] == q)
1228                                  break;
1229                          if (!q && (str[i] == ')' || str[i] == '&' ||
1230                                     str[i] == '|'))
1231                                  break;
1232                  }
1233                  /* Skip quotes */
1234                  if (q)
1235                          s++;
1236                 len = i - s;
1237                 if (len >= MAX_FILTER_STR_VAL) {
1238                         parse_error(pe, FILT_ERR_OPERAND_TOO_LONG, pos + i);
1239                         goto err_free;
1240                 }
1241
1242                 pred->regex.len = len;
1243                 strncpy(pred->regex.pattern, str + s, len);
1244                 pred->regex.pattern[len] = 0;
1245
1246         /* This is either a string, or an integer */
1247         } else if (str[i] == '\'' || str[i] == '"') {
1248                 char q = str[i];
1249
1250                 /* Make sure the op is OK for strings */
1251                 switch (op) {
1252                 case OP_NE:
1253                         pred->not = 1;
1254                         /* Fall through */
1255                 case OP_GLOB:
1256                 case OP_EQ:
1257                         break;
1258                 default:
1259                         parse_error(pe, FILT_ERR_ILLEGAL_FIELD_OP, pos + i);
1260                         goto err_free;
1261                 }
1262
1263                 /* Make sure the field is OK for strings */
1264                 if (!is_string_field(field)) {
1265                         parse_error(pe, FILT_ERR_EXPECT_DIGIT, pos + i);
1266                         goto err_free;
1267                 }
1268
1269                 for (i++; str[i]; i++) {
1270                         if (str[i] == q)
1271                                 break;
1272                 }
1273                 if (!str[i]) {
1274                         parse_error(pe, FILT_ERR_MISSING_QUOTE, pos + i);
1275                         goto err_free;
1276                 }
1277
1278                 /* Skip quotes */
1279                 s++;
1280                 len = i - s;
1281                 if (len >= MAX_FILTER_STR_VAL) {
1282                         parse_error(pe, FILT_ERR_OPERAND_TOO_LONG, pos + i);
1283                         goto err_free;
1284                 }
1285
1286                 pred->regex.len = len;
1287                 strncpy(pred->regex.pattern, str + s, len);
1288                 pred->regex.pattern[len] = 0;
1289
1290                 filter_build_regex(pred);
1291
1292                 if (field->filter_type == FILTER_COMM) {
1293                         pred->fn = filter_pred_comm;
1294
1295                 } else if (field->filter_type == FILTER_STATIC_STRING) {
1296                         pred->fn = filter_pred_string;
1297                         pred->regex.field_len = field->size;
1298
1299                 } else if (field->filter_type == FILTER_DYN_STRING)
1300                         pred->fn = filter_pred_strloc;
1301                 else
1302                         pred->fn = filter_pred_pchar;
1303                 /* go past the last quote */
1304                 i++;
1305
1306         } else if (isdigit(str[i])) {
1307
1308                 /* Make sure the field is not a string */
1309                 if (is_string_field(field)) {
1310                         parse_error(pe, FILT_ERR_EXPECT_STRING, pos + i);
1311                         goto err_free;
1312                 }
1313
1314                 if (op == OP_GLOB) {
1315                         parse_error(pe, FILT_ERR_ILLEGAL_FIELD_OP, pos + i);
1316                         goto err_free;
1317                 }
1318
1319                 /* We allow 0xDEADBEEF */
1320                 while (isalnum(str[i]))
1321                         i++;
1322
1323                 len = i - s;
1324                 /* 0xfeedfacedeadbeef is 18 chars max */
1325                 if (len >= sizeof(num_buf)) {
1326                         parse_error(pe, FILT_ERR_OPERAND_TOO_LONG, pos + i);
1327                         goto err_free;
1328                 }
1329
1330                 strncpy(num_buf, str + s, len);
1331                 num_buf[len] = 0;
1332
1333                 /* Make sure it is a value */
1334                 if (field->is_signed)
1335                         ret = kstrtoll(num_buf, 0, &val);
1336                 else
1337                         ret = kstrtoull(num_buf, 0, &val);
1338                 if (ret) {
1339                         parse_error(pe, FILT_ERR_ILLEGAL_INTVAL, pos + s);
1340                         goto err_free;
1341                 }
1342
1343                 pred->val = val;
1344
1345                 if (field->filter_type == FILTER_CPU)
1346                         pred->fn = filter_pred_cpu;
1347                 else {
1348                         pred->fn = select_comparison_fn(pred->op, field->size,
1349                                                         field->is_signed);
1350                         if (pred->op == OP_NE)
1351                                 pred->not = 1;
1352                 }
1353
1354         } else {
1355                 parse_error(pe, FILT_ERR_INVALID_VALUE, pos + i);
1356                 goto err_free;
1357         }
1358
1359         *pred_ptr = pred;
1360         return i;
1361
1362 err_free:
1363         kfree(pred);
1364         return -EINVAL;
1365 }
1366
1367 enum {
1368         TOO_MANY_CLOSE          = -1,
1369         TOO_MANY_OPEN           = -2,
1370         MISSING_QUOTE           = -3,
1371 };
1372
1373 /*
1374  * Read the filter string once to calculate the number of predicates
1375  * as well as how deep the parentheses go.
1376  *
1377  * Returns:
1378  *   0 - everything is fine (err is undefined)
1379  *  -1 - too many ')'
1380  *  -2 - too many '('
1381  *  -3 - No matching quote
1382  */
1383 static int calc_stack(const char *str, int *parens, int *preds, int *err)
1384 {
1385         bool is_pred = false;
1386         int nr_preds = 0;
1387         int open = 1; /* Count the expression as "(E)" */
1388         int last_quote = 0;
1389         int max_open = 1;
1390         int quote = 0;
1391         int i;
1392
1393         *err = 0;
1394
1395         for (i = 0; str[i]; i++) {
1396                 if (isspace(str[i]))
1397                         continue;
1398                 if (quote) {
1399                         if (str[i] == quote)
1400                                quote = 0;
1401                         continue;
1402                 }
1403
1404                 switch (str[i]) {
1405                 case '\'':
1406                 case '"':
1407                         quote = str[i];
1408                         last_quote = i;
1409                         break;
1410                 case '|':
1411                 case '&':
1412                         if (str[i+1] != str[i])
1413                                 break;
1414                         is_pred = false;
1415                         continue;
1416                 case '(':
1417                         is_pred = false;
1418                         open++;
1419                         if (open > max_open)
1420                                 max_open = open;
1421                         continue;
1422                 case ')':
1423                         is_pred = false;
1424                         if (open == 1) {
1425                                 *err = i;
1426                                 return TOO_MANY_CLOSE;
1427                         }
1428                         open--;
1429                         continue;
1430                 }
1431                 if (!is_pred) {
1432                         nr_preds++;
1433                         is_pred = true;
1434                 }
1435         }
1436
1437         if (quote) {
1438                 *err = last_quote;
1439                 return MISSING_QUOTE;
1440         }
1441
1442         if (open != 1) {
1443                 int level = open;
1444
1445                 /* find the bad open */
1446                 for (i--; i; i--) {
1447                         if (quote) {
1448                                 if (str[i] == quote)
1449                                         quote = 0;
1450                                 continue;
1451                         }
1452                         switch (str[i]) {
1453                         case '(':
1454                                 if (level == open) {
1455                                         *err = i;
1456                                         return TOO_MANY_OPEN;
1457                                 }
1458                                 level--;
1459                                 break;
1460                         case ')':
1461                                 level++;
1462                                 break;
1463                         case '\'':
1464                         case '"':
1465                                 quote = str[i];
1466                                 break;
1467                         }
1468                 }
1469                 /* First character is the '(' with missing ')' */
1470                 *err = 0;
1471                 return TOO_MANY_OPEN;
1472         }
1473
1474         /* Set the size of the required stacks */
1475         *parens = max_open;
1476         *preds = nr_preds;
1477         return 0;
1478 }
1479
1480 static int process_preds(struct trace_event_call *call,
1481                          const char *filter_string,
1482                          struct event_filter *filter,
1483                          struct filter_parse_error *pe)
1484 {
1485         struct prog_entry *prog;
1486         int nr_parens;
1487         int nr_preds;
1488         int index;
1489         int ret;
1490
1491         ret = calc_stack(filter_string, &nr_parens, &nr_preds, &index);
1492         if (ret < 0) {
1493                 switch (ret) {
1494                 case MISSING_QUOTE:
1495                         parse_error(pe, FILT_ERR_MISSING_QUOTE, index);
1496                         break;
1497                 case TOO_MANY_OPEN:
1498                         parse_error(pe, FILT_ERR_TOO_MANY_OPEN, index);
1499                         break;
1500                 default:
1501                         parse_error(pe, FILT_ERR_TOO_MANY_CLOSE, index);
1502                 }
1503                 return ret;
1504         }
1505
1506         if (!nr_preds)
1507                 return -EINVAL;
1508
1509         prog = predicate_parse(filter_string, nr_parens, nr_preds,
1510                                parse_pred, call, pe);
1511         if (IS_ERR(prog))
1512                 return PTR_ERR(prog);
1513
1514         rcu_assign_pointer(filter->prog, prog);
1515         return 0;
1516 }
1517
1518 static inline void event_set_filtered_flag(struct trace_event_file *file)
1519 {
1520         unsigned long old_flags = file->flags;
1521
1522         file->flags |= EVENT_FILE_FL_FILTERED;
1523
1524         if (old_flags != file->flags)
1525                 trace_buffered_event_enable();
1526 }
1527
1528 static inline void event_set_filter(struct trace_event_file *file,
1529                                     struct event_filter *filter)
1530 {
1531         rcu_assign_pointer(file->filter, filter);
1532 }
1533
1534 static inline void event_clear_filter(struct trace_event_file *file)
1535 {
1536         RCU_INIT_POINTER(file->filter, NULL);
1537 }
1538
1539 static inline void
1540 event_set_no_set_filter_flag(struct trace_event_file *file)
1541 {
1542         file->flags |= EVENT_FILE_FL_NO_SET_FILTER;
1543 }
1544
1545 static inline void
1546 event_clear_no_set_filter_flag(struct trace_event_file *file)
1547 {
1548         file->flags &= ~EVENT_FILE_FL_NO_SET_FILTER;
1549 }
1550
1551 static inline bool
1552 event_no_set_filter_flag(struct trace_event_file *file)
1553 {
1554         if (file->flags & EVENT_FILE_FL_NO_SET_FILTER)
1555                 return true;
1556
1557         return false;
1558 }
1559
1560 struct filter_list {
1561         struct list_head        list;
1562         struct event_filter     *filter;
1563 };
1564
1565 static int process_system_preds(struct trace_subsystem_dir *dir,
1566                                 struct trace_array *tr,
1567                                 struct filter_parse_error *pe,
1568                                 char *filter_string)
1569 {
1570         struct trace_event_file *file;
1571         struct filter_list *filter_item;
1572         struct event_filter *filter = NULL;
1573         struct filter_list *tmp;
1574         LIST_HEAD(filter_list);
1575         bool fail = true;
1576         int err;
1577
1578         list_for_each_entry(file, &tr->events, list) {
1579
1580                 if (file->system != dir)
1581                         continue;
1582
1583                 filter = kzalloc(sizeof(*filter), GFP_KERNEL);
1584                 if (!filter)
1585                         goto fail_mem;
1586
1587                 filter->filter_string = kstrdup(filter_string, GFP_KERNEL);
1588                 if (!filter->filter_string)
1589                         goto fail_mem;
1590
1591                 err = process_preds(file->event_call, filter_string, filter, pe);
1592                 if (err) {
1593                         filter_disable(file);
1594                         parse_error(pe, FILT_ERR_BAD_SUBSYS_FILTER, 0);
1595                         append_filter_err(pe, filter);
1596                 } else
1597                         event_set_filtered_flag(file);
1598
1599
1600                 filter_item = kzalloc(sizeof(*filter_item), GFP_KERNEL);
1601                 if (!filter_item)
1602                         goto fail_mem;
1603
1604                 list_add_tail(&filter_item->list, &filter_list);
1605                 /*
1606                  * Regardless of if this returned an error, we still
1607                  * replace the filter for the call.
1608                  */
1609                 filter_item->filter = event_filter(file);
1610                 event_set_filter(file, filter);
1611                 filter = NULL;
1612
1613                 fail = false;
1614         }
1615
1616         if (fail)
1617                 goto fail;
1618
1619         /*
1620          * The calls can still be using the old filters.
1621          * Do a synchronize_rcu() and to ensure all calls are
1622          * done with them before we free them.
1623          */
1624         tracepoint_synchronize_unregister();
1625         list_for_each_entry_safe(filter_item, tmp, &filter_list, list) {
1626                 __free_filter(filter_item->filter);
1627                 list_del(&filter_item->list);
1628                 kfree(filter_item);
1629         }
1630         return 0;
1631  fail:
1632         /* No call succeeded */
1633         list_for_each_entry_safe(filter_item, tmp, &filter_list, list) {
1634                 list_del(&filter_item->list);
1635                 kfree(filter_item);
1636         }
1637         parse_error(pe, FILT_ERR_BAD_SUBSYS_FILTER, 0);
1638         return -EINVAL;
1639  fail_mem:
1640         kfree(filter);
1641         /* If any call succeeded, we still need to sync */
1642         if (!fail)
1643                 tracepoint_synchronize_unregister();
1644         list_for_each_entry_safe(filter_item, tmp, &filter_list, list) {
1645                 __free_filter(filter_item->filter);
1646                 list_del(&filter_item->list);
1647                 kfree(filter_item);
1648         }
1649         return -ENOMEM;
1650 }
1651
1652 static int create_filter_start(char *filter_string, bool set_str,
1653                                struct filter_parse_error **pse,
1654                                struct event_filter **filterp)
1655 {
1656         struct event_filter *filter;
1657         struct filter_parse_error *pe = NULL;
1658         int err = 0;
1659
1660         if (WARN_ON_ONCE(*pse || *filterp))
1661                 return -EINVAL;
1662
1663         filter = kzalloc(sizeof(*filter), GFP_KERNEL);
1664         if (filter && set_str) {
1665                 filter->filter_string = kstrdup(filter_string, GFP_KERNEL);
1666                 if (!filter->filter_string)
1667                         err = -ENOMEM;
1668         }
1669
1670         pe = kzalloc(sizeof(*pe), GFP_KERNEL);
1671
1672         if (!filter || !pe || err) {
1673                 kfree(pe);
1674                 __free_filter(filter);
1675                 return -ENOMEM;
1676         }
1677
1678         /* we're committed to creating a new filter */
1679         *filterp = filter;
1680         *pse = pe;
1681
1682         return 0;
1683 }
1684
1685 static void create_filter_finish(struct filter_parse_error *pe)
1686 {
1687         kfree(pe);
1688 }
1689
1690 /**
1691  * create_filter - create a filter for a trace_event_call
1692  * @call: trace_event_call to create a filter for
1693  * @filter_str: filter string
1694  * @set_str: remember @filter_str and enable detailed error in filter
1695  * @filterp: out param for created filter (always updated on return)
1696  *           Must be a pointer that references a NULL pointer.
1697  *
1698  * Creates a filter for @call with @filter_str.  If @set_str is %true,
1699  * @filter_str is copied and recorded in the new filter.
1700  *
1701  * On success, returns 0 and *@filterp points to the new filter.  On
1702  * failure, returns -errno and *@filterp may point to %NULL or to a new
1703  * filter.  In the latter case, the returned filter contains error
1704  * information if @set_str is %true and the caller is responsible for
1705  * freeing it.
1706  */
1707 static int create_filter(struct trace_event_call *call,
1708                          char *filter_string, bool set_str,
1709                          struct event_filter **filterp)
1710 {
1711         struct filter_parse_error *pe = NULL;
1712         int err;
1713
1714         /* filterp must point to NULL */
1715         if (WARN_ON(*filterp))
1716                 *filterp = NULL;
1717
1718         err = create_filter_start(filter_string, set_str, &pe, filterp);
1719         if (err)
1720                 return err;
1721
1722         err = process_preds(call, filter_string, *filterp, pe);
1723         if (err && set_str)
1724                 append_filter_err(pe, *filterp);
1725         create_filter_finish(pe);
1726
1727         return err;
1728 }
1729
1730 int create_event_filter(struct trace_event_call *call,
1731                         char *filter_str, bool set_str,
1732                         struct event_filter **filterp)
1733 {
1734         return create_filter(call, filter_str, set_str, filterp);
1735 }
1736
1737 /**
1738  * create_system_filter - create a filter for an event_subsystem
1739  * @system: event_subsystem to create a filter for
1740  * @filter_str: filter string
1741  * @filterp: out param for created filter (always updated on return)
1742  *
1743  * Identical to create_filter() except that it creates a subsystem filter
1744  * and always remembers @filter_str.
1745  */
1746 static int create_system_filter(struct trace_subsystem_dir *dir,
1747                                 struct trace_array *tr,
1748                                 char *filter_str, struct event_filter **filterp)
1749 {
1750         struct filter_parse_error *pe = NULL;
1751         int err;
1752
1753         err = create_filter_start(filter_str, true, &pe, filterp);
1754         if (!err) {
1755                 err = process_system_preds(dir, tr, pe, filter_str);
1756                 if (!err) {
1757                         /* System filters just show a default message */
1758                         kfree((*filterp)->filter_string);
1759                         (*filterp)->filter_string = NULL;
1760                 } else {
1761                         append_filter_err(pe, *filterp);
1762                 }
1763         }
1764         create_filter_finish(pe);
1765
1766         return err;
1767 }
1768
1769 /* caller must hold event_mutex */
1770 int apply_event_filter(struct trace_event_file *file, char *filter_string)
1771 {
1772         struct trace_event_call *call = file->event_call;
1773         struct event_filter *filter = NULL;
1774         int err;
1775
1776         if (!strcmp(strstrip(filter_string), "0")) {
1777                 filter_disable(file);
1778                 filter = event_filter(file);
1779
1780                 if (!filter)
1781                         return 0;
1782
1783                 event_clear_filter(file);
1784
1785                 /* Make sure the filter is not being used */
1786                 tracepoint_synchronize_unregister();
1787                 __free_filter(filter);
1788
1789                 return 0;
1790         }
1791
1792         err = create_filter(call, filter_string, true, &filter);
1793
1794         /*
1795          * Always swap the call filter with the new filter
1796          * even if there was an error. If there was an error
1797          * in the filter, we disable the filter and show the error
1798          * string
1799          */
1800         if (filter) {
1801                 struct event_filter *tmp;
1802
1803                 tmp = event_filter(file);
1804                 if (!err)
1805                         event_set_filtered_flag(file);
1806                 else
1807                         filter_disable(file);
1808
1809                 event_set_filter(file, filter);
1810
1811                 if (tmp) {
1812                         /* Make sure the call is done with the filter */
1813                         tracepoint_synchronize_unregister();
1814                         __free_filter(tmp);
1815                 }
1816         }
1817
1818         return err;
1819 }
1820
1821 int apply_subsystem_event_filter(struct trace_subsystem_dir *dir,
1822                                  char *filter_string)
1823 {
1824         struct event_subsystem *system = dir->subsystem;
1825         struct trace_array *tr = dir->tr;
1826         struct event_filter *filter = NULL;
1827         int err = 0;
1828
1829         mutex_lock(&event_mutex);
1830
1831         /* Make sure the system still has events */
1832         if (!dir->nr_events) {
1833                 err = -ENODEV;
1834                 goto out_unlock;
1835         }
1836
1837         if (!strcmp(strstrip(filter_string), "0")) {
1838                 filter_free_subsystem_preds(dir, tr);
1839                 remove_filter_string(system->filter);
1840                 filter = system->filter;
1841                 system->filter = NULL;
1842                 /* Ensure all filters are no longer used */
1843                 tracepoint_synchronize_unregister();
1844                 filter_free_subsystem_filters(dir, tr);
1845                 __free_filter(filter);
1846                 goto out_unlock;
1847         }
1848
1849         err = create_system_filter(dir, tr, filter_string, &filter);
1850         if (filter) {
1851                 /*
1852                  * No event actually uses the system filter
1853                  * we can free it without synchronize_rcu().
1854                  */
1855                 __free_filter(system->filter);
1856                 system->filter = filter;
1857         }
1858 out_unlock:
1859         mutex_unlock(&event_mutex);
1860
1861         return err;
1862 }
1863
1864 #ifdef CONFIG_PERF_EVENTS
1865
1866 void ftrace_profile_free_filter(struct perf_event *event)
1867 {
1868         struct event_filter *filter = event->filter;
1869
1870         event->filter = NULL;
1871         __free_filter(filter);
1872 }
1873
1874 struct function_filter_data {
1875         struct ftrace_ops *ops;
1876         int first_filter;
1877         int first_notrace;
1878 };
1879
1880 #ifdef CONFIG_FUNCTION_TRACER
1881 static char **
1882 ftrace_function_filter_re(char *buf, int len, int *count)
1883 {
1884         char *str, **re;
1885
1886         str = kstrndup(buf, len, GFP_KERNEL);
1887         if (!str)
1888                 return NULL;
1889
1890         /*
1891          * The argv_split function takes white space
1892          * as a separator, so convert ',' into spaces.
1893          */
1894         strreplace(str, ',', ' ');
1895
1896         re = argv_split(GFP_KERNEL, str, count);
1897         kfree(str);
1898         return re;
1899 }
1900
1901 static int ftrace_function_set_regexp(struct ftrace_ops *ops, int filter,
1902                                       int reset, char *re, int len)
1903 {
1904         int ret;
1905
1906         if (filter)
1907                 ret = ftrace_set_filter(ops, re, len, reset);
1908         else
1909                 ret = ftrace_set_notrace(ops, re, len, reset);
1910
1911         return ret;
1912 }
1913
1914 static int __ftrace_function_set_filter(int filter, char *buf, int len,
1915                                         struct function_filter_data *data)
1916 {
1917         int i, re_cnt, ret = -EINVAL;
1918         int *reset;
1919         char **re;
1920
1921         reset = filter ? &data->first_filter : &data->first_notrace;
1922
1923         /*
1924          * The 'ip' field could have multiple filters set, separated
1925          * either by space or comma. We first cut the filter and apply
1926          * all pieces separatelly.
1927          */
1928         re = ftrace_function_filter_re(buf, len, &re_cnt);
1929         if (!re)
1930                 return -EINVAL;
1931
1932         for (i = 0; i < re_cnt; i++) {
1933                 ret = ftrace_function_set_regexp(data->ops, filter, *reset,
1934                                                  re[i], strlen(re[i]));
1935                 if (ret)
1936                         break;
1937
1938                 if (*reset)
1939                         *reset = 0;
1940         }
1941
1942         argv_free(re);
1943         return ret;
1944 }
1945
1946 static int ftrace_function_check_pred(struct filter_pred *pred)
1947 {
1948         struct ftrace_event_field *field = pred->field;
1949
1950         /*
1951          * Check the predicate for function trace, verify:
1952          *  - only '==' and '!=' is used
1953          *  - the 'ip' field is used
1954          */
1955         if ((pred->op != OP_EQ) && (pred->op != OP_NE))
1956                 return -EINVAL;
1957
1958         if (strcmp(field->name, "ip"))
1959                 return -EINVAL;
1960
1961         return 0;
1962 }
1963
1964 static int ftrace_function_set_filter_pred(struct filter_pred *pred,
1965                                            struct function_filter_data *data)
1966 {
1967         int ret;
1968
1969         /* Checking the node is valid for function trace. */
1970         ret = ftrace_function_check_pred(pred);
1971         if (ret)
1972                 return ret;
1973
1974         return __ftrace_function_set_filter(pred->op == OP_EQ,
1975                                             pred->regex.pattern,
1976                                             pred->regex.len,
1977                                             data);
1978 }
1979
1980 static bool is_or(struct prog_entry *prog, int i)
1981 {
1982         int target;
1983
1984         /*
1985          * Only "||" is allowed for function events, thus,
1986          * all true branches should jump to true, and any
1987          * false branch should jump to false.
1988          */
1989         target = prog[i].target + 1;
1990         /* True and false have NULL preds (all prog entries should jump to one */
1991         if (prog[target].pred)
1992                 return false;
1993
1994         /* prog[target].target is 1 for TRUE, 0 for FALSE */
1995         return prog[i].when_to_branch == prog[target].target;
1996 }
1997
1998 static int ftrace_function_set_filter(struct perf_event *event,
1999                                       struct event_filter *filter)
2000 {
2001         struct prog_entry *prog = rcu_dereference_protected(filter->prog,
2002                                                 lockdep_is_held(&event_mutex));
2003         struct function_filter_data data = {
2004                 .first_filter  = 1,
2005                 .first_notrace = 1,
2006                 .ops           = &event->ftrace_ops,
2007         };
2008         int i;
2009
2010         for (i = 0; prog[i].pred; i++) {
2011                 struct filter_pred *pred = prog[i].pred;
2012
2013                 if (!is_or(prog, i))
2014                         return -EINVAL;
2015
2016                 if (ftrace_function_set_filter_pred(pred, &data) < 0)
2017                         return -EINVAL;
2018         }
2019         return 0;
2020 }
2021 #else
2022 static int ftrace_function_set_filter(struct perf_event *event,
2023                                       struct event_filter *filter)
2024 {
2025         return -ENODEV;
2026 }
2027 #endif /* CONFIG_FUNCTION_TRACER */
2028
2029 int ftrace_profile_set_filter(struct perf_event *event, int event_id,
2030                               char *filter_str)
2031 {
2032         int err;
2033         struct event_filter *filter = NULL;
2034         struct trace_event_call *call;
2035
2036         mutex_lock(&event_mutex);
2037
2038         call = event->tp_event;
2039
2040         err = -EINVAL;
2041         if (!call)
2042                 goto out_unlock;
2043
2044         err = -EEXIST;
2045         if (event->filter)
2046                 goto out_unlock;
2047
2048         err = create_filter(call, filter_str, false, &filter);
2049         if (err)
2050                 goto free_filter;
2051
2052         if (ftrace_event_is_function(call))
2053                 err = ftrace_function_set_filter(event, filter);
2054         else
2055                 event->filter = filter;
2056
2057 free_filter:
2058         if (err || ftrace_event_is_function(call))
2059                 __free_filter(filter);
2060
2061 out_unlock:
2062         mutex_unlock(&event_mutex);
2063
2064         return err;
2065 }
2066
2067 #endif /* CONFIG_PERF_EVENTS */
2068
2069 #ifdef CONFIG_FTRACE_STARTUP_TEST
2070
2071 #include <linux/types.h>
2072 #include <linux/tracepoint.h>
2073
2074 #define CREATE_TRACE_POINTS
2075 #include "trace_events_filter_test.h"
2076
2077 #define DATA_REC(m, va, vb, vc, vd, ve, vf, vg, vh, nvisit) \
2078 { \
2079         .filter = FILTER, \
2080         .rec    = { .a = va, .b = vb, .c = vc, .d = vd, \
2081                     .e = ve, .f = vf, .g = vg, .h = vh }, \
2082         .match  = m, \
2083         .not_visited = nvisit, \
2084 }
2085 #define YES 1
2086 #define NO  0
2087
2088 static struct test_filter_data_t {
2089         char *filter;
2090         struct trace_event_raw_ftrace_test_filter rec;
2091         int match;
2092         char *not_visited;
2093 } test_filter_data[] = {
2094 #define FILTER "a == 1 && b == 1 && c == 1 && d == 1 && " \
2095                "e == 1 && f == 1 && g == 1 && h == 1"
2096         DATA_REC(YES, 1, 1, 1, 1, 1, 1, 1, 1, ""),
2097         DATA_REC(NO,  0, 1, 1, 1, 1, 1, 1, 1, "bcdefgh"),
2098         DATA_REC(NO,  1, 1, 1, 1, 1, 1, 1, 0, ""),
2099 #undef FILTER
2100 #define FILTER "a == 1 || b == 1 || c == 1 || d == 1 || " \
2101                "e == 1 || f == 1 || g == 1 || h == 1"
2102         DATA_REC(NO,  0, 0, 0, 0, 0, 0, 0, 0, ""),
2103         DATA_REC(YES, 0, 0, 0, 0, 0, 0, 0, 1, ""),
2104         DATA_REC(YES, 1, 0, 0, 0, 0, 0, 0, 0, "bcdefgh"),
2105 #undef FILTER
2106 #define FILTER "(a == 1 || b == 1) && (c == 1 || d == 1) && " \
2107                "(e == 1 || f == 1) && (g == 1 || h == 1)"
2108         DATA_REC(NO,  0, 0, 1, 1, 1, 1, 1, 1, "dfh"),
2109         DATA_REC(YES, 0, 1, 0, 1, 0, 1, 0, 1, ""),
2110         DATA_REC(YES, 1, 0, 1, 0, 0, 1, 0, 1, "bd"),
2111         DATA_REC(NO,  1, 0, 1, 0, 0, 1, 0, 0, "bd"),
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(YES, 1, 0, 1, 1, 1, 1, 1, 1, "efgh"),
2116         DATA_REC(YES, 0, 0, 0, 0, 0, 0, 1, 1, ""),
2117         DATA_REC(NO,  0, 0, 0, 0, 0, 0, 0, 1, ""),
2118 #undef FILTER
2119 #define FILTER "(a == 1 && b == 1) && (c == 1 && d == 1) && " \
2120                "(e == 1 && f == 1) || (g == 1 && h == 1)"
2121         DATA_REC(YES, 1, 1, 1, 1, 1, 1, 0, 0, "gh"),
2122         DATA_REC(NO,  0, 0, 0, 0, 0, 0, 0, 1, ""),
2123         DATA_REC(YES, 1, 1, 1, 1, 1, 0, 1, 1, ""),
2124 #undef FILTER
2125 #define FILTER "((a == 1 || b == 1) || (c == 1 || d == 1) || " \
2126                "(e == 1 || f == 1)) && (g == 1 || h == 1)"
2127         DATA_REC(YES, 1, 1, 1, 1, 1, 1, 0, 1, "bcdef"),
2128         DATA_REC(NO,  0, 0, 0, 0, 0, 0, 0, 0, ""),
2129         DATA_REC(YES, 1, 1, 1, 1, 1, 0, 1, 1, "h"),
2130 #undef FILTER
2131 #define FILTER "((((((((a == 1) && (b == 1)) || (c == 1)) && (d == 1)) || " \
2132                "(e == 1)) && (f == 1)) || (g == 1)) && (h == 1))"
2133         DATA_REC(YES, 1, 1, 1, 1, 1, 1, 1, 1, "ceg"),
2134         DATA_REC(NO,  0, 1, 0, 1, 0, 1, 0, 1, ""),
2135         DATA_REC(NO,  1, 0, 1, 0, 1, 0, 1, 0, ""),
2136 #undef FILTER
2137 #define FILTER "((((((((a == 1) || (b == 1)) && (c == 1)) || (d == 1)) && " \
2138                "(e == 1)) || (f == 1)) && (g == 1)) || (h == 1))"
2139         DATA_REC(YES, 1, 1, 1, 1, 1, 1, 1, 1, "bdfh"),
2140         DATA_REC(YES, 0, 1, 0, 1, 0, 1, 0, 1, ""),
2141         DATA_REC(YES, 1, 0, 1, 0, 1, 0, 1, 0, "bdfh"),
2142 };
2143
2144 #undef DATA_REC
2145 #undef FILTER
2146 #undef YES
2147 #undef NO
2148
2149 #define DATA_CNT ARRAY_SIZE(test_filter_data)
2150
2151 static int test_pred_visited;
2152
2153 static int test_pred_visited_fn(struct filter_pred *pred, void *event)
2154 {
2155         struct ftrace_event_field *field = pred->field;
2156
2157         test_pred_visited = 1;
2158         printk(KERN_INFO "\npred visited %s\n", field->name);
2159         return 1;
2160 }
2161
2162 static void update_pred_fn(struct event_filter *filter, char *fields)
2163 {
2164         struct prog_entry *prog = rcu_dereference_protected(filter->prog,
2165                                                 lockdep_is_held(&event_mutex));
2166         int i;
2167
2168         for (i = 0; prog[i].pred; i++) {
2169                 struct filter_pred *pred = prog[i].pred;
2170                 struct ftrace_event_field *field = pred->field;
2171
2172                 WARN_ON_ONCE(!pred->fn);
2173
2174                 if (!field) {
2175                         WARN_ONCE(1, "all leafs should have field defined %d", i);
2176                         continue;
2177                 }
2178
2179                 if (!strchr(fields, *field->name))
2180                         continue;
2181
2182                 pred->fn = test_pred_visited_fn;
2183         }
2184 }
2185
2186 static __init int ftrace_test_event_filter(void)
2187 {
2188         int i;
2189
2190         printk(KERN_INFO "Testing ftrace filter: ");
2191
2192         for (i = 0; i < DATA_CNT; i++) {
2193                 struct event_filter *filter = NULL;
2194                 struct test_filter_data_t *d = &test_filter_data[i];
2195                 int err;
2196
2197                 err = create_filter(&event_ftrace_test_filter, d->filter,
2198                                     false, &filter);
2199                 if (err) {
2200                         printk(KERN_INFO
2201                                "Failed to get filter for '%s', err %d\n",
2202                                d->filter, err);
2203                         __free_filter(filter);
2204                         break;
2205                 }
2206
2207                 /* Needed to dereference filter->prog */
2208                 mutex_lock(&event_mutex);
2209                 /*
2210                  * The preemption disabling is not really needed for self
2211                  * tests, but the rcu dereference will complain without it.
2212                  */
2213                 preempt_disable();
2214                 if (*d->not_visited)
2215                         update_pred_fn(filter, d->not_visited);
2216
2217                 test_pred_visited = 0;
2218                 err = filter_match_preds(filter, &d->rec);
2219                 preempt_enable();
2220
2221                 mutex_unlock(&event_mutex);
2222
2223                 __free_filter(filter);
2224
2225                 if (test_pred_visited) {
2226                         printk(KERN_INFO
2227                                "Failed, unwanted pred visited for filter %s\n",
2228                                d->filter);
2229                         break;
2230                 }
2231
2232                 if (err != d->match) {
2233                         printk(KERN_INFO
2234                                "Failed to match filter '%s', expected %d\n",
2235                                d->filter, d->match);
2236                         break;
2237                 }
2238         }
2239
2240         if (i == DATA_CNT)
2241                 printk(KERN_CONT "OK\n");
2242
2243         return 0;
2244 }
2245
2246 late_initcall(ftrace_test_event_filter);
2247
2248 #endif /* CONFIG_FTRACE_STARTUP_TEST */