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