• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Infrastructure for profiling code inserted by 'gcc -pg'.
4  *
5  * Copyright (C) 2007-2008 Steven Rostedt <srostedt@redhat.com>
6  * Copyright (C) 2004-2008 Ingo Molnar <mingo@redhat.com>
7  *
8  * Originally ported from the -rt patch by:
9  *   Copyright (C) 2007 Arnaldo Carvalho de Melo <acme@redhat.com>
10  *
11  * Based on code in the latency_tracer, that is:
12  *
13  *  Copyright (C) 2004-2006 Ingo Molnar
14  *  Copyright (C) 2004 Nadia Yvette Chambers
15  */
16 
17 #include <linux/stop_machine.h>
18 #include <linux/clocksource.h>
19 #include <linux/sched/task.h>
20 #include <linux/kallsyms.h>
21 #include <linux/security.h>
22 #include <linux/seq_file.h>
23 #include <linux/tracefs.h>
24 #include <linux/hardirq.h>
25 #include <linux/kthread.h>
26 #include <linux/uaccess.h>
27 #include <linux/bsearch.h>
28 #include <linux/module.h>
29 #include <linux/ftrace.h>
30 #include <linux/sysctl.h>
31 #include <linux/slab.h>
32 #include <linux/ctype.h>
33 #include <linux/sort.h>
34 #include <linux/list.h>
35 #include <linux/hash.h>
36 #include <linux/rcupdate.h>
37 #include <linux/kprobes.h>
38 
39 #include <trace/events/sched.h>
40 
41 #include <asm/sections.h>
42 #include <asm/setup.h>
43 
44 #include "ftrace_internal.h"
45 #include "trace_output.h"
46 #include "trace_stat.h"
47 
48 /* Flags that do not get reset */
49 #define FTRACE_NOCLEAR_FLAGS	(FTRACE_FL_DISABLED | FTRACE_FL_TOUCHED | \
50 				 FTRACE_FL_MODIFIED)
51 
52 #define FTRACE_INVALID_FUNCTION		"__ftrace_invalid_address__"
53 
54 #define FTRACE_WARN_ON(cond)			\
55 	({					\
56 		int ___r = cond;		\
57 		if (WARN_ON(___r))		\
58 			ftrace_kill();		\
59 		___r;				\
60 	})
61 
62 #define FTRACE_WARN_ON_ONCE(cond)		\
63 	({					\
64 		int ___r = cond;		\
65 		if (WARN_ON_ONCE(___r))		\
66 			ftrace_kill();		\
67 		___r;				\
68 	})
69 
70 /* hash bits for specific function selection */
71 #define FTRACE_HASH_DEFAULT_BITS 10
72 #define FTRACE_HASH_MAX_BITS 12
73 
74 #ifdef CONFIG_DYNAMIC_FTRACE
75 #define INIT_OPS_HASH(opsname)	\
76 	.func_hash		= &opsname.local_hash,			\
77 	.local_hash.regex_lock	= __MUTEX_INITIALIZER(opsname.local_hash.regex_lock), \
78 	.subop_list		= LIST_HEAD_INIT(opsname.subop_list),
79 #else
80 #define INIT_OPS_HASH(opsname)
81 #endif
82 
83 enum {
84 	FTRACE_MODIFY_ENABLE_FL		= (1 << 0),
85 	FTRACE_MODIFY_MAY_SLEEP_FL	= (1 << 1),
86 };
87 
88 struct ftrace_ops ftrace_list_end __read_mostly = {
89 	.func		= ftrace_stub,
90 	.flags		= FTRACE_OPS_FL_STUB,
91 	INIT_OPS_HASH(ftrace_list_end)
92 };
93 
94 /* ftrace_enabled is a method to turn ftrace on or off */
95 int ftrace_enabled __read_mostly;
96 static int __maybe_unused last_ftrace_enabled;
97 
98 /* Current function tracing op */
99 struct ftrace_ops *function_trace_op __read_mostly = &ftrace_list_end;
100 /* What to set function_trace_op to */
101 static struct ftrace_ops *set_function_trace_op;
102 
ftrace_pids_enabled(struct ftrace_ops * ops)103 bool ftrace_pids_enabled(struct ftrace_ops *ops)
104 {
105 	struct trace_array *tr;
106 
107 	if (!(ops->flags & FTRACE_OPS_FL_PID) || !ops->private)
108 		return false;
109 
110 	tr = ops->private;
111 
112 	return tr->function_pids != NULL || tr->function_no_pids != NULL;
113 }
114 
115 static void ftrace_update_trampoline(struct ftrace_ops *ops);
116 
117 /*
118  * ftrace_disabled is set when an anomaly is discovered.
119  * ftrace_disabled is much stronger than ftrace_enabled.
120  */
121 static int ftrace_disabled __read_mostly;
122 
123 DEFINE_MUTEX(ftrace_lock);
124 
125 struct ftrace_ops __rcu *ftrace_ops_list __read_mostly = (struct ftrace_ops __rcu *)&ftrace_list_end;
126 ftrace_func_t ftrace_trace_function __read_mostly = ftrace_stub;
127 struct ftrace_ops global_ops;
128 
129 /* Defined by vmlinux.lds.h see the comment above arch_ftrace_ops_list_func for details */
130 void ftrace_ops_list_func(unsigned long ip, unsigned long parent_ip,
131 			  struct ftrace_ops *op, struct ftrace_regs *fregs);
132 
133 #ifdef CONFIG_DYNAMIC_FTRACE_WITH_CALL_OPS
134 /*
135  * Stub used to invoke the list ops without requiring a separate trampoline.
136  */
137 const struct ftrace_ops ftrace_list_ops = {
138 	.func	= ftrace_ops_list_func,
139 	.flags	= FTRACE_OPS_FL_STUB,
140 };
141 
ftrace_ops_nop_func(unsigned long ip,unsigned long parent_ip,struct ftrace_ops * op,struct ftrace_regs * fregs)142 static void ftrace_ops_nop_func(unsigned long ip, unsigned long parent_ip,
143 				struct ftrace_ops *op,
144 				struct ftrace_regs *fregs)
145 {
146 	/* do nothing */
147 }
148 
149 /*
150  * Stub used when a call site is disabled. May be called transiently by threads
151  * which have made it into ftrace_caller but haven't yet recovered the ops at
152  * the point the call site is disabled.
153  */
154 const struct ftrace_ops ftrace_nop_ops = {
155 	.func	= ftrace_ops_nop_func,
156 	.flags  = FTRACE_OPS_FL_STUB,
157 };
158 #endif
159 
ftrace_ops_init(struct ftrace_ops * ops)160 static inline void ftrace_ops_init(struct ftrace_ops *ops)
161 {
162 #ifdef CONFIG_DYNAMIC_FTRACE
163 	if (!(ops->flags & FTRACE_OPS_FL_INITIALIZED)) {
164 		mutex_init(&ops->local_hash.regex_lock);
165 		INIT_LIST_HEAD(&ops->subop_list);
166 		ops->func_hash = &ops->local_hash;
167 		ops->flags |= FTRACE_OPS_FL_INITIALIZED;
168 	}
169 #endif
170 }
171 
172 /* Call this function for when a callback filters on set_ftrace_pid */
ftrace_pid_func(unsigned long ip,unsigned long parent_ip,struct ftrace_ops * op,struct ftrace_regs * fregs)173 static void ftrace_pid_func(unsigned long ip, unsigned long parent_ip,
174 			    struct ftrace_ops *op, struct ftrace_regs *fregs)
175 {
176 	struct trace_array *tr = op->private;
177 	int pid;
178 
179 	if (tr) {
180 		pid = this_cpu_read(tr->array_buffer.data->ftrace_ignore_pid);
181 		if (pid == FTRACE_PID_IGNORE)
182 			return;
183 		if (pid != FTRACE_PID_TRACE &&
184 		    pid != current->pid)
185 			return;
186 	}
187 
188 	op->saved_func(ip, parent_ip, op, fregs);
189 }
190 
ftrace_sync_ipi(void * data)191 static void ftrace_sync_ipi(void *data)
192 {
193 	/* Probably not needed, but do it anyway */
194 	smp_rmb();
195 }
196 
ftrace_ops_get_list_func(struct ftrace_ops * ops)197 static ftrace_func_t ftrace_ops_get_list_func(struct ftrace_ops *ops)
198 {
199 	/*
200 	 * If this is a dynamic or RCU ops, or we force list func,
201 	 * then it needs to call the list anyway.
202 	 */
203 	if (ops->flags & (FTRACE_OPS_FL_DYNAMIC | FTRACE_OPS_FL_RCU) ||
204 	    FTRACE_FORCE_LIST_FUNC)
205 		return ftrace_ops_list_func;
206 
207 	return ftrace_ops_get_func(ops);
208 }
209 
update_ftrace_function(void)210 static void update_ftrace_function(void)
211 {
212 	ftrace_func_t func;
213 
214 	/*
215 	 * Prepare the ftrace_ops that the arch callback will use.
216 	 * If there's only one ftrace_ops registered, the ftrace_ops_list
217 	 * will point to the ops we want.
218 	 */
219 	set_function_trace_op = rcu_dereference_protected(ftrace_ops_list,
220 						lockdep_is_held(&ftrace_lock));
221 
222 	/* If there's no ftrace_ops registered, just call the stub function */
223 	if (set_function_trace_op == &ftrace_list_end) {
224 		func = ftrace_stub;
225 
226 	/*
227 	 * If we are at the end of the list and this ops is
228 	 * recursion safe and not dynamic and the arch supports passing ops,
229 	 * then have the mcount trampoline call the function directly.
230 	 */
231 	} else if (rcu_dereference_protected(ftrace_ops_list->next,
232 			lockdep_is_held(&ftrace_lock)) == &ftrace_list_end) {
233 		func = ftrace_ops_get_list_func(ftrace_ops_list);
234 
235 	} else {
236 		/* Just use the default ftrace_ops */
237 		set_function_trace_op = &ftrace_list_end;
238 		func = ftrace_ops_list_func;
239 	}
240 
241 	/* If there's no change, then do nothing more here */
242 	if (ftrace_trace_function == func)
243 		return;
244 
245 	/*
246 	 * If we are using the list function, it doesn't care
247 	 * about the function_trace_ops.
248 	 */
249 	if (func == ftrace_ops_list_func) {
250 		ftrace_trace_function = func;
251 		/*
252 		 * Don't even bother setting function_trace_ops,
253 		 * it would be racy to do so anyway.
254 		 */
255 		return;
256 	}
257 
258 #ifndef CONFIG_DYNAMIC_FTRACE
259 	/*
260 	 * For static tracing, we need to be a bit more careful.
261 	 * The function change takes affect immediately. Thus,
262 	 * we need to coordinate the setting of the function_trace_ops
263 	 * with the setting of the ftrace_trace_function.
264 	 *
265 	 * Set the function to the list ops, which will call the
266 	 * function we want, albeit indirectly, but it handles the
267 	 * ftrace_ops and doesn't depend on function_trace_op.
268 	 */
269 	ftrace_trace_function = ftrace_ops_list_func;
270 	/*
271 	 * Make sure all CPUs see this. Yes this is slow, but static
272 	 * tracing is slow and nasty to have enabled.
273 	 */
274 	synchronize_rcu_tasks_rude();
275 	/* Now all cpus are using the list ops. */
276 	function_trace_op = set_function_trace_op;
277 	/* Make sure the function_trace_op is visible on all CPUs */
278 	smp_wmb();
279 	/* Nasty way to force a rmb on all cpus */
280 	smp_call_function(ftrace_sync_ipi, NULL, 1);
281 	/* OK, we are all set to update the ftrace_trace_function now! */
282 #endif /* !CONFIG_DYNAMIC_FTRACE */
283 
284 	ftrace_trace_function = func;
285 }
286 
add_ftrace_ops(struct ftrace_ops __rcu ** list,struct ftrace_ops * ops)287 static void add_ftrace_ops(struct ftrace_ops __rcu **list,
288 			   struct ftrace_ops *ops)
289 {
290 	rcu_assign_pointer(ops->next, *list);
291 
292 	/*
293 	 * We are entering ops into the list but another
294 	 * CPU might be walking that list. We need to make sure
295 	 * the ops->next pointer is valid before another CPU sees
296 	 * the ops pointer included into the list.
297 	 */
298 	rcu_assign_pointer(*list, ops);
299 }
300 
remove_ftrace_ops(struct ftrace_ops __rcu ** list,struct ftrace_ops * ops)301 static int remove_ftrace_ops(struct ftrace_ops __rcu **list,
302 			     struct ftrace_ops *ops)
303 {
304 	struct ftrace_ops **p;
305 
306 	/*
307 	 * If we are removing the last function, then simply point
308 	 * to the ftrace_stub.
309 	 */
310 	if (rcu_dereference_protected(*list,
311 			lockdep_is_held(&ftrace_lock)) == ops &&
312 	    rcu_dereference_protected(ops->next,
313 			lockdep_is_held(&ftrace_lock)) == &ftrace_list_end) {
314 		rcu_assign_pointer(*list, &ftrace_list_end);
315 		return 0;
316 	}
317 
318 	for (p = list; *p != &ftrace_list_end; p = &(*p)->next)
319 		if (*p == ops)
320 			break;
321 
322 	if (*p != ops)
323 		return -1;
324 
325 	*p = (*p)->next;
326 	return 0;
327 }
328 
329 static void ftrace_update_trampoline(struct ftrace_ops *ops);
330 
__register_ftrace_function(struct ftrace_ops * ops)331 int __register_ftrace_function(struct ftrace_ops *ops)
332 {
333 	if (ops->flags & FTRACE_OPS_FL_DELETED)
334 		return -EINVAL;
335 
336 	if (WARN_ON(ops->flags & FTRACE_OPS_FL_ENABLED))
337 		return -EBUSY;
338 
339 #ifndef CONFIG_DYNAMIC_FTRACE_WITH_REGS
340 	/*
341 	 * If the ftrace_ops specifies SAVE_REGS, then it only can be used
342 	 * if the arch supports it, or SAVE_REGS_IF_SUPPORTED is also set.
343 	 * Setting SAVE_REGS_IF_SUPPORTED makes SAVE_REGS irrelevant.
344 	 */
345 	if (ops->flags & FTRACE_OPS_FL_SAVE_REGS &&
346 	    !(ops->flags & FTRACE_OPS_FL_SAVE_REGS_IF_SUPPORTED))
347 		return -EINVAL;
348 
349 	if (ops->flags & FTRACE_OPS_FL_SAVE_REGS_IF_SUPPORTED)
350 		ops->flags |= FTRACE_OPS_FL_SAVE_REGS;
351 #endif
352 	if (!ftrace_enabled && (ops->flags & FTRACE_OPS_FL_PERMANENT))
353 		return -EBUSY;
354 
355 	if (!is_kernel_core_data((unsigned long)ops))
356 		ops->flags |= FTRACE_OPS_FL_DYNAMIC;
357 
358 	add_ftrace_ops(&ftrace_ops_list, ops);
359 
360 	/* Always save the function, and reset at unregistering */
361 	ops->saved_func = ops->func;
362 
363 	if (ftrace_pids_enabled(ops))
364 		ops->func = ftrace_pid_func;
365 
366 	ftrace_update_trampoline(ops);
367 
368 	if (ftrace_enabled)
369 		update_ftrace_function();
370 
371 	return 0;
372 }
373 
__unregister_ftrace_function(struct ftrace_ops * ops)374 int __unregister_ftrace_function(struct ftrace_ops *ops)
375 {
376 	int ret;
377 
378 	if (WARN_ON(!(ops->flags & FTRACE_OPS_FL_ENABLED)))
379 		return -EBUSY;
380 
381 	ret = remove_ftrace_ops(&ftrace_ops_list, ops);
382 
383 	if (ret < 0)
384 		return ret;
385 
386 	if (ftrace_enabled)
387 		update_ftrace_function();
388 
389 	ops->func = ops->saved_func;
390 
391 	return 0;
392 }
393 
ftrace_update_pid_func(void)394 static void ftrace_update_pid_func(void)
395 {
396 	struct ftrace_ops *op;
397 
398 	/* Only do something if we are tracing something */
399 	if (ftrace_trace_function == ftrace_stub)
400 		return;
401 
402 	do_for_each_ftrace_op(op, ftrace_ops_list) {
403 		if (op->flags & FTRACE_OPS_FL_PID) {
404 			op->func = ftrace_pids_enabled(op) ?
405 				ftrace_pid_func : op->saved_func;
406 			ftrace_update_trampoline(op);
407 		}
408 	} while_for_each_ftrace_op(op);
409 
410 	fgraph_update_pid_func();
411 
412 	update_ftrace_function();
413 }
414 
415 #ifdef CONFIG_FUNCTION_PROFILER
416 struct ftrace_profile {
417 	struct hlist_node		node;
418 	unsigned long			ip;
419 	unsigned long			counter;
420 #ifdef CONFIG_FUNCTION_GRAPH_TRACER
421 	unsigned long long		time;
422 	unsigned long long		time_squared;
423 #endif
424 };
425 
426 struct ftrace_profile_page {
427 	struct ftrace_profile_page	*next;
428 	unsigned long			index;
429 	struct ftrace_profile		records[];
430 };
431 
432 struct ftrace_profile_stat {
433 	atomic_t			disabled;
434 	struct hlist_head		*hash;
435 	struct ftrace_profile_page	*pages;
436 	struct ftrace_profile_page	*start;
437 	struct tracer_stat		stat;
438 };
439 
440 #define PROFILE_RECORDS_SIZE						\
441 	(PAGE_SIZE - offsetof(struct ftrace_profile_page, records))
442 
443 #define PROFILES_PER_PAGE					\
444 	(PROFILE_RECORDS_SIZE / sizeof(struct ftrace_profile))
445 
446 static int ftrace_profile_enabled __read_mostly;
447 
448 /* ftrace_profile_lock - synchronize the enable and disable of the profiler */
449 static DEFINE_MUTEX(ftrace_profile_lock);
450 
451 static DEFINE_PER_CPU(struct ftrace_profile_stat, ftrace_profile_stats);
452 
453 #define FTRACE_PROFILE_HASH_BITS 10
454 #define FTRACE_PROFILE_HASH_SIZE (1 << FTRACE_PROFILE_HASH_BITS)
455 
456 static void *
function_stat_next(void * v,int idx)457 function_stat_next(void *v, int idx)
458 {
459 	struct ftrace_profile *rec = v;
460 	struct ftrace_profile_page *pg;
461 
462 	pg = (struct ftrace_profile_page *)((unsigned long)rec & PAGE_MASK);
463 
464  again:
465 	if (idx != 0)
466 		rec++;
467 
468 	if ((void *)rec >= (void *)&pg->records[pg->index]) {
469 		pg = pg->next;
470 		if (!pg)
471 			return NULL;
472 		rec = &pg->records[0];
473 		if (!rec->counter)
474 			goto again;
475 	}
476 
477 	return rec;
478 }
479 
function_stat_start(struct tracer_stat * trace)480 static void *function_stat_start(struct tracer_stat *trace)
481 {
482 	struct ftrace_profile_stat *stat =
483 		container_of(trace, struct ftrace_profile_stat, stat);
484 
485 	if (!stat || !stat->start)
486 		return NULL;
487 
488 	return function_stat_next(&stat->start->records[0], 0);
489 }
490 
491 #ifdef CONFIG_FUNCTION_GRAPH_TRACER
492 /* function graph compares on total time */
function_stat_cmp(const void * p1,const void * p2)493 static int function_stat_cmp(const void *p1, const void *p2)
494 {
495 	const struct ftrace_profile *a = p1;
496 	const struct ftrace_profile *b = p2;
497 
498 	if (a->time < b->time)
499 		return -1;
500 	if (a->time > b->time)
501 		return 1;
502 	else
503 		return 0;
504 }
505 #else
506 /* not function graph compares against hits */
function_stat_cmp(const void * p1,const void * p2)507 static int function_stat_cmp(const void *p1, const void *p2)
508 {
509 	const struct ftrace_profile *a = p1;
510 	const struct ftrace_profile *b = p2;
511 
512 	if (a->counter < b->counter)
513 		return -1;
514 	if (a->counter > b->counter)
515 		return 1;
516 	else
517 		return 0;
518 }
519 #endif
520 
function_stat_headers(struct seq_file * m)521 static int function_stat_headers(struct seq_file *m)
522 {
523 #ifdef CONFIG_FUNCTION_GRAPH_TRACER
524 	seq_puts(m, "  Function                               "
525 		 "Hit    Time            Avg             s^2\n"
526 		    "  --------                               "
527 		 "---    ----            ---             ---\n");
528 #else
529 	seq_puts(m, "  Function                               Hit\n"
530 		    "  --------                               ---\n");
531 #endif
532 	return 0;
533 }
534 
function_stat_show(struct seq_file * m,void * v)535 static int function_stat_show(struct seq_file *m, void *v)
536 {
537 	struct ftrace_profile *rec = v;
538 	char str[KSYM_SYMBOL_LEN];
539 	int ret = 0;
540 #ifdef CONFIG_FUNCTION_GRAPH_TRACER
541 	static struct trace_seq s;
542 	unsigned long long avg;
543 	unsigned long long stddev;
544 	unsigned long long stddev_denom;
545 #endif
546 	mutex_lock(&ftrace_profile_lock);
547 
548 	/* we raced with function_profile_reset() */
549 	if (unlikely(rec->counter == 0)) {
550 		ret = -EBUSY;
551 		goto out;
552 	}
553 
554 #ifdef CONFIG_FUNCTION_GRAPH_TRACER
555 	avg = div64_ul(rec->time, rec->counter);
556 	if (tracing_thresh && (avg < tracing_thresh))
557 		goto out;
558 #endif
559 
560 	kallsyms_lookup(rec->ip, NULL, NULL, NULL, str);
561 	seq_printf(m, "  %-30.30s  %10lu", str, rec->counter);
562 
563 #ifdef CONFIG_FUNCTION_GRAPH_TRACER
564 	seq_puts(m, "    ");
565 
566 	/*
567 	 * Variance formula:
568 	 * s^2 = 1 / (n * (n-1)) * (n * \Sum (x_i)^2 - (\Sum x_i)^2)
569 	 * Maybe Welford's method is better here?
570 	 * Divide only by 1000 for ns^2 -> us^2 conversion.
571 	 * trace_print_graph_duration will divide by 1000 again.
572 	 */
573 	stddev = 0;
574 	stddev_denom = rec->counter * (rec->counter - 1) * 1000;
575 	if (stddev_denom) {
576 		stddev = rec->counter * rec->time_squared -
577 			 rec->time * rec->time;
578 		stddev = div64_ul(stddev, stddev_denom);
579 	}
580 
581 	trace_seq_init(&s);
582 	trace_print_graph_duration(rec->time, &s);
583 	trace_seq_puts(&s, "    ");
584 	trace_print_graph_duration(avg, &s);
585 	trace_seq_puts(&s, "    ");
586 	trace_print_graph_duration(stddev, &s);
587 	trace_print_seq(m, &s);
588 #endif
589 	seq_putc(m, '\n');
590 out:
591 	mutex_unlock(&ftrace_profile_lock);
592 
593 	return ret;
594 }
595 
ftrace_profile_reset(struct ftrace_profile_stat * stat)596 static void ftrace_profile_reset(struct ftrace_profile_stat *stat)
597 {
598 	struct ftrace_profile_page *pg;
599 
600 	pg = stat->pages = stat->start;
601 
602 	while (pg) {
603 		memset(pg->records, 0, PROFILE_RECORDS_SIZE);
604 		pg->index = 0;
605 		pg = pg->next;
606 	}
607 
608 	memset(stat->hash, 0,
609 	       FTRACE_PROFILE_HASH_SIZE * sizeof(struct hlist_head));
610 }
611 
ftrace_profile_pages_init(struct ftrace_profile_stat * stat)612 static int ftrace_profile_pages_init(struct ftrace_profile_stat *stat)
613 {
614 	struct ftrace_profile_page *pg;
615 	int functions;
616 	int pages;
617 	int i;
618 
619 	/* If we already allocated, do nothing */
620 	if (stat->pages)
621 		return 0;
622 
623 	stat->pages = (void *)get_zeroed_page(GFP_KERNEL);
624 	if (!stat->pages)
625 		return -ENOMEM;
626 
627 #ifdef CONFIG_DYNAMIC_FTRACE
628 	functions = ftrace_update_tot_cnt;
629 #else
630 	/*
631 	 * We do not know the number of functions that exist because
632 	 * dynamic tracing is what counts them. With past experience
633 	 * we have around 20K functions. That should be more than enough.
634 	 * It is highly unlikely we will execute every function in
635 	 * the kernel.
636 	 */
637 	functions = 20000;
638 #endif
639 
640 	pg = stat->start = stat->pages;
641 
642 	pages = DIV_ROUND_UP(functions, PROFILES_PER_PAGE);
643 
644 	for (i = 1; i < pages; i++) {
645 		pg->next = (void *)get_zeroed_page(GFP_KERNEL);
646 		if (!pg->next)
647 			goto out_free;
648 		pg = pg->next;
649 	}
650 
651 	return 0;
652 
653  out_free:
654 	pg = stat->start;
655 	while (pg) {
656 		unsigned long tmp = (unsigned long)pg;
657 
658 		pg = pg->next;
659 		free_page(tmp);
660 	}
661 
662 	stat->pages = NULL;
663 	stat->start = NULL;
664 
665 	return -ENOMEM;
666 }
667 
ftrace_profile_init_cpu(int cpu)668 static int ftrace_profile_init_cpu(int cpu)
669 {
670 	struct ftrace_profile_stat *stat;
671 	int size;
672 
673 	stat = &per_cpu(ftrace_profile_stats, cpu);
674 
675 	if (stat->hash) {
676 		/* If the profile is already created, simply reset it */
677 		ftrace_profile_reset(stat);
678 		return 0;
679 	}
680 
681 	/*
682 	 * We are profiling all functions, but usually only a few thousand
683 	 * functions are hit. We'll make a hash of 1024 items.
684 	 */
685 	size = FTRACE_PROFILE_HASH_SIZE;
686 
687 	stat->hash = kcalloc(size, sizeof(struct hlist_head), GFP_KERNEL);
688 
689 	if (!stat->hash)
690 		return -ENOMEM;
691 
692 	/* Preallocate the function profiling pages */
693 	if (ftrace_profile_pages_init(stat) < 0) {
694 		kfree(stat->hash);
695 		stat->hash = NULL;
696 		return -ENOMEM;
697 	}
698 
699 	return 0;
700 }
701 
ftrace_profile_init(void)702 static int ftrace_profile_init(void)
703 {
704 	int cpu;
705 	int ret = 0;
706 
707 	for_each_possible_cpu(cpu) {
708 		ret = ftrace_profile_init_cpu(cpu);
709 		if (ret)
710 			break;
711 	}
712 
713 	return ret;
714 }
715 
716 /* interrupts must be disabled */
717 static struct ftrace_profile *
ftrace_find_profiled_func(struct ftrace_profile_stat * stat,unsigned long ip)718 ftrace_find_profiled_func(struct ftrace_profile_stat *stat, unsigned long ip)
719 {
720 	struct ftrace_profile *rec;
721 	struct hlist_head *hhd;
722 	unsigned long key;
723 
724 	key = hash_long(ip, FTRACE_PROFILE_HASH_BITS);
725 	hhd = &stat->hash[key];
726 
727 	if (hlist_empty(hhd))
728 		return NULL;
729 
730 	hlist_for_each_entry_rcu_notrace(rec, hhd, node) {
731 		if (rec->ip == ip)
732 			return rec;
733 	}
734 
735 	return NULL;
736 }
737 
ftrace_add_profile(struct ftrace_profile_stat * stat,struct ftrace_profile * rec)738 static void ftrace_add_profile(struct ftrace_profile_stat *stat,
739 			       struct ftrace_profile *rec)
740 {
741 	unsigned long key;
742 
743 	key = hash_long(rec->ip, FTRACE_PROFILE_HASH_BITS);
744 	hlist_add_head_rcu(&rec->node, &stat->hash[key]);
745 }
746 
747 /*
748  * The memory is already allocated, this simply finds a new record to use.
749  */
750 static struct ftrace_profile *
ftrace_profile_alloc(struct ftrace_profile_stat * stat,unsigned long ip)751 ftrace_profile_alloc(struct ftrace_profile_stat *stat, unsigned long ip)
752 {
753 	struct ftrace_profile *rec = NULL;
754 
755 	/* prevent recursion (from NMIs) */
756 	if (atomic_inc_return(&stat->disabled) != 1)
757 		goto out;
758 
759 	/*
760 	 * Try to find the function again since an NMI
761 	 * could have added it
762 	 */
763 	rec = ftrace_find_profiled_func(stat, ip);
764 	if (rec)
765 		goto out;
766 
767 	if (stat->pages->index == PROFILES_PER_PAGE) {
768 		if (!stat->pages->next)
769 			goto out;
770 		stat->pages = stat->pages->next;
771 	}
772 
773 	rec = &stat->pages->records[stat->pages->index++];
774 	rec->ip = ip;
775 	ftrace_add_profile(stat, rec);
776 
777  out:
778 	atomic_dec(&stat->disabled);
779 
780 	return rec;
781 }
782 
783 static void
function_profile_call(unsigned long ip,unsigned long parent_ip,struct ftrace_ops * ops,struct ftrace_regs * fregs)784 function_profile_call(unsigned long ip, unsigned long parent_ip,
785 		      struct ftrace_ops *ops, struct ftrace_regs *fregs)
786 {
787 	struct ftrace_profile_stat *stat;
788 	struct ftrace_profile *rec;
789 	unsigned long flags;
790 
791 	if (!ftrace_profile_enabled)
792 		return;
793 
794 	local_irq_save(flags);
795 
796 	stat = this_cpu_ptr(&ftrace_profile_stats);
797 	if (!stat->hash || !ftrace_profile_enabled)
798 		goto out;
799 
800 	rec = ftrace_find_profiled_func(stat, ip);
801 	if (!rec) {
802 		rec = ftrace_profile_alloc(stat, ip);
803 		if (!rec)
804 			goto out;
805 	}
806 
807 	rec->counter++;
808  out:
809 	local_irq_restore(flags);
810 }
811 
812 #ifdef CONFIG_FUNCTION_GRAPH_TRACER
813 static bool fgraph_graph_time = true;
814 
ftrace_graph_graph_time_control(bool enable)815 void ftrace_graph_graph_time_control(bool enable)
816 {
817 	fgraph_graph_time = enable;
818 }
819 
profile_graph_entry(struct ftrace_graph_ent * trace,struct fgraph_ops * gops)820 static int profile_graph_entry(struct ftrace_graph_ent *trace,
821 			       struct fgraph_ops *gops)
822 {
823 	struct ftrace_ret_stack *ret_stack;
824 
825 	function_profile_call(trace->func, 0, NULL, NULL);
826 
827 	/* If function graph is shutting down, ret_stack can be NULL */
828 	if (!current->ret_stack)
829 		return 0;
830 
831 	ret_stack = ftrace_graph_get_ret_stack(current, 0);
832 	if (ret_stack)
833 		ret_stack->subtime = 0;
834 
835 	return 1;
836 }
837 
profile_graph_return(struct ftrace_graph_ret * trace,struct fgraph_ops * gops)838 static void profile_graph_return(struct ftrace_graph_ret *trace,
839 				 struct fgraph_ops *gops)
840 {
841 	struct ftrace_ret_stack *ret_stack;
842 	struct ftrace_profile_stat *stat;
843 	unsigned long long calltime;
844 	struct ftrace_profile *rec;
845 	unsigned long flags;
846 
847 	local_irq_save(flags);
848 	stat = this_cpu_ptr(&ftrace_profile_stats);
849 	if (!stat->hash || !ftrace_profile_enabled)
850 		goto out;
851 
852 	/* If the calltime was zero'd ignore it */
853 	if (!trace->calltime)
854 		goto out;
855 
856 	calltime = trace->rettime - trace->calltime;
857 
858 	if (!fgraph_graph_time) {
859 
860 		/* Append this call time to the parent time to subtract */
861 		ret_stack = ftrace_graph_get_ret_stack(current, 1);
862 		if (ret_stack)
863 			ret_stack->subtime += calltime;
864 
865 		ret_stack = ftrace_graph_get_ret_stack(current, 0);
866 		if (ret_stack && ret_stack->subtime < calltime)
867 			calltime -= ret_stack->subtime;
868 		else
869 			calltime = 0;
870 	}
871 
872 	rec = ftrace_find_profiled_func(stat, trace->func);
873 	if (rec) {
874 		rec->time += calltime;
875 		rec->time_squared += calltime * calltime;
876 	}
877 
878  out:
879 	local_irq_restore(flags);
880 }
881 
882 static struct fgraph_ops fprofiler_ops = {
883 	.entryfunc = &profile_graph_entry,
884 	.retfunc = &profile_graph_return,
885 };
886 
register_ftrace_profiler(void)887 static int register_ftrace_profiler(void)
888 {
889 	ftrace_ops_set_global_filter(&fprofiler_ops.ops);
890 	return register_ftrace_graph(&fprofiler_ops);
891 }
892 
unregister_ftrace_profiler(void)893 static void unregister_ftrace_profiler(void)
894 {
895 	unregister_ftrace_graph(&fprofiler_ops);
896 }
897 #else
898 static struct ftrace_ops ftrace_profile_ops __read_mostly = {
899 	.func		= function_profile_call,
900 };
901 
register_ftrace_profiler(void)902 static int register_ftrace_profiler(void)
903 {
904 	ftrace_ops_set_global_filter(&ftrace_profile_ops);
905 	return register_ftrace_function(&ftrace_profile_ops);
906 }
907 
unregister_ftrace_profiler(void)908 static void unregister_ftrace_profiler(void)
909 {
910 	unregister_ftrace_function(&ftrace_profile_ops);
911 }
912 #endif /* CONFIG_FUNCTION_GRAPH_TRACER */
913 
914 static ssize_t
ftrace_profile_write(struct file * filp,const char __user * ubuf,size_t cnt,loff_t * ppos)915 ftrace_profile_write(struct file *filp, const char __user *ubuf,
916 		     size_t cnt, loff_t *ppos)
917 {
918 	unsigned long val;
919 	int ret;
920 
921 	ret = kstrtoul_from_user(ubuf, cnt, 10, &val);
922 	if (ret)
923 		return ret;
924 
925 	val = !!val;
926 
927 	mutex_lock(&ftrace_profile_lock);
928 	if (ftrace_profile_enabled ^ val) {
929 		if (val) {
930 			ret = ftrace_profile_init();
931 			if (ret < 0) {
932 				cnt = ret;
933 				goto out;
934 			}
935 
936 			ret = register_ftrace_profiler();
937 			if (ret < 0) {
938 				cnt = ret;
939 				goto out;
940 			}
941 			ftrace_profile_enabled = 1;
942 		} else {
943 			ftrace_profile_enabled = 0;
944 			/*
945 			 * unregister_ftrace_profiler calls stop_machine
946 			 * so this acts like an synchronize_rcu.
947 			 */
948 			unregister_ftrace_profiler();
949 		}
950 	}
951  out:
952 	mutex_unlock(&ftrace_profile_lock);
953 
954 	*ppos += cnt;
955 
956 	return cnt;
957 }
958 
959 static ssize_t
ftrace_profile_read(struct file * filp,char __user * ubuf,size_t cnt,loff_t * ppos)960 ftrace_profile_read(struct file *filp, char __user *ubuf,
961 		     size_t cnt, loff_t *ppos)
962 {
963 	char buf[64];		/* big enough to hold a number */
964 	int r;
965 
966 	r = sprintf(buf, "%u\n", ftrace_profile_enabled);
967 	return simple_read_from_buffer(ubuf, cnt, ppos, buf, r);
968 }
969 
970 static const struct file_operations ftrace_profile_fops = {
971 	.open		= tracing_open_generic,
972 	.read		= ftrace_profile_read,
973 	.write		= ftrace_profile_write,
974 	.llseek		= default_llseek,
975 };
976 
977 /* used to initialize the real stat files */
978 static struct tracer_stat function_stats __initdata = {
979 	.name		= "functions",
980 	.stat_start	= function_stat_start,
981 	.stat_next	= function_stat_next,
982 	.stat_cmp	= function_stat_cmp,
983 	.stat_headers	= function_stat_headers,
984 	.stat_show	= function_stat_show
985 };
986 
ftrace_profile_tracefs(struct dentry * d_tracer)987 static __init void ftrace_profile_tracefs(struct dentry *d_tracer)
988 {
989 	struct ftrace_profile_stat *stat;
990 	char *name;
991 	int ret;
992 	int cpu;
993 
994 	for_each_possible_cpu(cpu) {
995 		stat = &per_cpu(ftrace_profile_stats, cpu);
996 
997 		name = kasprintf(GFP_KERNEL, "function%d", cpu);
998 		if (!name) {
999 			/*
1000 			 * The files created are permanent, if something happens
1001 			 * we still do not free memory.
1002 			 */
1003 			WARN(1,
1004 			     "Could not allocate stat file for cpu %d\n",
1005 			     cpu);
1006 			return;
1007 		}
1008 		stat->stat = function_stats;
1009 		stat->stat.name = name;
1010 		ret = register_stat_tracer(&stat->stat);
1011 		if (ret) {
1012 			WARN(1,
1013 			     "Could not register function stat for cpu %d\n",
1014 			     cpu);
1015 			kfree(name);
1016 			return;
1017 		}
1018 	}
1019 
1020 	trace_create_file("function_profile_enabled",
1021 			  TRACE_MODE_WRITE, d_tracer, NULL,
1022 			  &ftrace_profile_fops);
1023 }
1024 
1025 #else /* CONFIG_FUNCTION_PROFILER */
ftrace_profile_tracefs(struct dentry * d_tracer)1026 static __init void ftrace_profile_tracefs(struct dentry *d_tracer)
1027 {
1028 }
1029 #endif /* CONFIG_FUNCTION_PROFILER */
1030 
1031 #ifdef CONFIG_DYNAMIC_FTRACE
1032 
1033 static struct ftrace_ops *removed_ops;
1034 
1035 /*
1036  * Set when doing a global update, like enabling all recs or disabling them.
1037  * It is not set when just updating a single ftrace_ops.
1038  */
1039 static bool update_all_ops;
1040 
1041 #ifndef CONFIG_FTRACE_MCOUNT_RECORD
1042 # error Dynamic ftrace depends on MCOUNT_RECORD
1043 #endif
1044 
1045 struct ftrace_func_probe {
1046 	struct ftrace_probe_ops	*probe_ops;
1047 	struct ftrace_ops	ops;
1048 	struct trace_array	*tr;
1049 	struct list_head	list;
1050 	void			*data;
1051 	int			ref;
1052 };
1053 
1054 /*
1055  * We make these constant because no one should touch them,
1056  * but they are used as the default "empty hash", to avoid allocating
1057  * it all the time. These are in a read only section such that if
1058  * anyone does try to modify it, it will cause an exception.
1059  */
1060 static const struct hlist_head empty_buckets[1];
1061 static const struct ftrace_hash empty_hash = {
1062 	.buckets = (struct hlist_head *)empty_buckets,
1063 };
1064 #define EMPTY_HASH	((struct ftrace_hash *)&empty_hash)
1065 
1066 struct ftrace_ops global_ops = {
1067 	.func				= ftrace_stub,
1068 	.local_hash.notrace_hash	= EMPTY_HASH,
1069 	.local_hash.filter_hash		= EMPTY_HASH,
1070 	INIT_OPS_HASH(global_ops)
1071 	.flags				= FTRACE_OPS_FL_INITIALIZED |
1072 					  FTRACE_OPS_FL_PID,
1073 };
1074 
1075 /*
1076  * Used by the stack unwinder to know about dynamic ftrace trampolines.
1077  */
ftrace_ops_trampoline(unsigned long addr)1078 struct ftrace_ops *ftrace_ops_trampoline(unsigned long addr)
1079 {
1080 	struct ftrace_ops *op = NULL;
1081 
1082 	/*
1083 	 * Some of the ops may be dynamically allocated,
1084 	 * they are freed after a synchronize_rcu().
1085 	 */
1086 	preempt_disable_notrace();
1087 
1088 	do_for_each_ftrace_op(op, ftrace_ops_list) {
1089 		/*
1090 		 * This is to check for dynamically allocated trampolines.
1091 		 * Trampolines that are in kernel text will have
1092 		 * core_kernel_text() return true.
1093 		 */
1094 		if (op->trampoline && op->trampoline_size)
1095 			if (addr >= op->trampoline &&
1096 			    addr < op->trampoline + op->trampoline_size) {
1097 				preempt_enable_notrace();
1098 				return op;
1099 			}
1100 	} while_for_each_ftrace_op(op);
1101 	preempt_enable_notrace();
1102 
1103 	return NULL;
1104 }
1105 
1106 /*
1107  * This is used by __kernel_text_address() to return true if the
1108  * address is on a dynamically allocated trampoline that would
1109  * not return true for either core_kernel_text() or
1110  * is_module_text_address().
1111  */
is_ftrace_trampoline(unsigned long addr)1112 bool is_ftrace_trampoline(unsigned long addr)
1113 {
1114 	return ftrace_ops_trampoline(addr) != NULL;
1115 }
1116 
1117 struct ftrace_page {
1118 	struct ftrace_page	*next;
1119 	struct dyn_ftrace	*records;
1120 	int			index;
1121 	int			order;
1122 };
1123 
1124 #define ENTRY_SIZE sizeof(struct dyn_ftrace)
1125 #define ENTRIES_PER_PAGE (PAGE_SIZE / ENTRY_SIZE)
1126 
1127 static struct ftrace_page	*ftrace_pages_start;
1128 static struct ftrace_page	*ftrace_pages;
1129 
1130 static __always_inline unsigned long
ftrace_hash_key(struct ftrace_hash * hash,unsigned long ip)1131 ftrace_hash_key(struct ftrace_hash *hash, unsigned long ip)
1132 {
1133 	if (hash->size_bits > 0)
1134 		return hash_long(ip, hash->size_bits);
1135 
1136 	return 0;
1137 }
1138 
1139 /* Only use this function if ftrace_hash_empty() has already been tested */
1140 static __always_inline struct ftrace_func_entry *
__ftrace_lookup_ip(struct ftrace_hash * hash,unsigned long ip)1141 __ftrace_lookup_ip(struct ftrace_hash *hash, unsigned long ip)
1142 {
1143 	unsigned long key;
1144 	struct ftrace_func_entry *entry;
1145 	struct hlist_head *hhd;
1146 
1147 	key = ftrace_hash_key(hash, ip);
1148 	hhd = &hash->buckets[key];
1149 
1150 	hlist_for_each_entry_rcu_notrace(entry, hhd, hlist) {
1151 		if (entry->ip == ip)
1152 			return entry;
1153 	}
1154 	return NULL;
1155 }
1156 
1157 /**
1158  * ftrace_lookup_ip - Test to see if an ip exists in an ftrace_hash
1159  * @hash: The hash to look at
1160  * @ip: The instruction pointer to test
1161  *
1162  * Search a given @hash to see if a given instruction pointer (@ip)
1163  * exists in it.
1164  *
1165  * Returns: the entry that holds the @ip if found. NULL otherwise.
1166  */
1167 struct ftrace_func_entry *
ftrace_lookup_ip(struct ftrace_hash * hash,unsigned long ip)1168 ftrace_lookup_ip(struct ftrace_hash *hash, unsigned long ip)
1169 {
1170 	if (ftrace_hash_empty(hash))
1171 		return NULL;
1172 
1173 	return __ftrace_lookup_ip(hash, ip);
1174 }
1175 
__add_hash_entry(struct ftrace_hash * hash,struct ftrace_func_entry * entry)1176 static void __add_hash_entry(struct ftrace_hash *hash,
1177 			     struct ftrace_func_entry *entry)
1178 {
1179 	struct hlist_head *hhd;
1180 	unsigned long key;
1181 
1182 	key = ftrace_hash_key(hash, entry->ip);
1183 	hhd = &hash->buckets[key];
1184 	hlist_add_head(&entry->hlist, hhd);
1185 	hash->count++;
1186 }
1187 
1188 static struct ftrace_func_entry *
add_hash_entry(struct ftrace_hash * hash,unsigned long ip)1189 add_hash_entry(struct ftrace_hash *hash, unsigned long ip)
1190 {
1191 	struct ftrace_func_entry *entry;
1192 
1193 	entry = kmalloc(sizeof(*entry), GFP_KERNEL);
1194 	if (!entry)
1195 		return NULL;
1196 
1197 	entry->ip = ip;
1198 	__add_hash_entry(hash, entry);
1199 
1200 	return entry;
1201 }
1202 
1203 static void
free_hash_entry(struct ftrace_hash * hash,struct ftrace_func_entry * entry)1204 free_hash_entry(struct ftrace_hash *hash,
1205 		  struct ftrace_func_entry *entry)
1206 {
1207 	hlist_del(&entry->hlist);
1208 	kfree(entry);
1209 	hash->count--;
1210 }
1211 
1212 static void
remove_hash_entry(struct ftrace_hash * hash,struct ftrace_func_entry * entry)1213 remove_hash_entry(struct ftrace_hash *hash,
1214 		  struct ftrace_func_entry *entry)
1215 {
1216 	hlist_del_rcu(&entry->hlist);
1217 	hash->count--;
1218 }
1219 
ftrace_hash_clear(struct ftrace_hash * hash)1220 static void ftrace_hash_clear(struct ftrace_hash *hash)
1221 {
1222 	struct hlist_head *hhd;
1223 	struct hlist_node *tn;
1224 	struct ftrace_func_entry *entry;
1225 	int size = 1 << hash->size_bits;
1226 	int i;
1227 
1228 	if (!hash->count)
1229 		return;
1230 
1231 	for (i = 0; i < size; i++) {
1232 		hhd = &hash->buckets[i];
1233 		hlist_for_each_entry_safe(entry, tn, hhd, hlist)
1234 			free_hash_entry(hash, entry);
1235 	}
1236 	FTRACE_WARN_ON(hash->count);
1237 }
1238 
free_ftrace_mod(struct ftrace_mod_load * ftrace_mod)1239 static void free_ftrace_mod(struct ftrace_mod_load *ftrace_mod)
1240 {
1241 	list_del(&ftrace_mod->list);
1242 	kfree(ftrace_mod->module);
1243 	kfree(ftrace_mod->func);
1244 	kfree(ftrace_mod);
1245 }
1246 
clear_ftrace_mod_list(struct list_head * head)1247 static void clear_ftrace_mod_list(struct list_head *head)
1248 {
1249 	struct ftrace_mod_load *p, *n;
1250 
1251 	/* stack tracer isn't supported yet */
1252 	if (!head)
1253 		return;
1254 
1255 	mutex_lock(&ftrace_lock);
1256 	list_for_each_entry_safe(p, n, head, list)
1257 		free_ftrace_mod(p);
1258 	mutex_unlock(&ftrace_lock);
1259 }
1260 
free_ftrace_hash(struct ftrace_hash * hash)1261 static void free_ftrace_hash(struct ftrace_hash *hash)
1262 {
1263 	if (!hash || hash == EMPTY_HASH)
1264 		return;
1265 	ftrace_hash_clear(hash);
1266 	kfree(hash->buckets);
1267 	kfree(hash);
1268 }
1269 
__free_ftrace_hash_rcu(struct rcu_head * rcu)1270 static void __free_ftrace_hash_rcu(struct rcu_head *rcu)
1271 {
1272 	struct ftrace_hash *hash;
1273 
1274 	hash = container_of(rcu, struct ftrace_hash, rcu);
1275 	free_ftrace_hash(hash);
1276 }
1277 
free_ftrace_hash_rcu(struct ftrace_hash * hash)1278 static void free_ftrace_hash_rcu(struct ftrace_hash *hash)
1279 {
1280 	if (!hash || hash == EMPTY_HASH)
1281 		return;
1282 	call_rcu(&hash->rcu, __free_ftrace_hash_rcu);
1283 }
1284 
1285 /**
1286  * ftrace_free_filter - remove all filters for an ftrace_ops
1287  * @ops: the ops to remove the filters from
1288  */
ftrace_free_filter(struct ftrace_ops * ops)1289 void ftrace_free_filter(struct ftrace_ops *ops)
1290 {
1291 	ftrace_ops_init(ops);
1292 	free_ftrace_hash(ops->func_hash->filter_hash);
1293 	free_ftrace_hash(ops->func_hash->notrace_hash);
1294 }
1295 EXPORT_SYMBOL_GPL(ftrace_free_filter);
1296 
alloc_ftrace_hash(int size_bits)1297 static struct ftrace_hash *alloc_ftrace_hash(int size_bits)
1298 {
1299 	struct ftrace_hash *hash;
1300 	int size;
1301 
1302 	hash = kzalloc(sizeof(*hash), GFP_KERNEL);
1303 	if (!hash)
1304 		return NULL;
1305 
1306 	size = 1 << size_bits;
1307 	hash->buckets = kcalloc(size, sizeof(*hash->buckets), GFP_KERNEL);
1308 
1309 	if (!hash->buckets) {
1310 		kfree(hash);
1311 		return NULL;
1312 	}
1313 
1314 	hash->size_bits = size_bits;
1315 
1316 	return hash;
1317 }
1318 
1319 /* Used to save filters on functions for modules not loaded yet */
ftrace_add_mod(struct trace_array * tr,const char * func,const char * module,int enable)1320 static int ftrace_add_mod(struct trace_array *tr,
1321 			  const char *func, const char *module,
1322 			  int enable)
1323 {
1324 	struct ftrace_mod_load *ftrace_mod;
1325 	struct list_head *mod_head = enable ? &tr->mod_trace : &tr->mod_notrace;
1326 
1327 	ftrace_mod = kzalloc(sizeof(*ftrace_mod), GFP_KERNEL);
1328 	if (!ftrace_mod)
1329 		return -ENOMEM;
1330 
1331 	INIT_LIST_HEAD(&ftrace_mod->list);
1332 	ftrace_mod->func = kstrdup(func, GFP_KERNEL);
1333 	ftrace_mod->module = kstrdup(module, GFP_KERNEL);
1334 	ftrace_mod->enable = enable;
1335 
1336 	if (!ftrace_mod->func || !ftrace_mod->module)
1337 		goto out_free;
1338 
1339 	list_add(&ftrace_mod->list, mod_head);
1340 
1341 	return 0;
1342 
1343  out_free:
1344 	free_ftrace_mod(ftrace_mod);
1345 
1346 	return -ENOMEM;
1347 }
1348 
1349 static struct ftrace_hash *
alloc_and_copy_ftrace_hash(int size_bits,struct ftrace_hash * hash)1350 alloc_and_copy_ftrace_hash(int size_bits, struct ftrace_hash *hash)
1351 {
1352 	struct ftrace_func_entry *entry;
1353 	struct ftrace_hash *new_hash;
1354 	int size;
1355 	int i;
1356 
1357 	new_hash = alloc_ftrace_hash(size_bits);
1358 	if (!new_hash)
1359 		return NULL;
1360 
1361 	if (hash)
1362 		new_hash->flags = hash->flags;
1363 
1364 	/* Empty hash? */
1365 	if (ftrace_hash_empty(hash))
1366 		return new_hash;
1367 
1368 	size = 1 << hash->size_bits;
1369 	for (i = 0; i < size; i++) {
1370 		hlist_for_each_entry(entry, &hash->buckets[i], hlist) {
1371 			if (add_hash_entry(new_hash, entry->ip) == NULL)
1372 				goto free_hash;
1373 		}
1374 	}
1375 
1376 	FTRACE_WARN_ON(new_hash->count != hash->count);
1377 
1378 	return new_hash;
1379 
1380  free_hash:
1381 	free_ftrace_hash(new_hash);
1382 	return NULL;
1383 }
1384 
1385 static void ftrace_hash_rec_disable_modify(struct ftrace_ops *ops);
1386 static void ftrace_hash_rec_enable_modify(struct ftrace_ops *ops);
1387 
1388 static int ftrace_hash_ipmodify_update(struct ftrace_ops *ops,
1389 				       struct ftrace_hash *new_hash);
1390 
1391 /*
1392  * Allocate a new hash and remove entries from @src and move them to the new hash.
1393  * On success, the @src hash will be empty and should be freed.
1394  */
__move_hash(struct ftrace_hash * src,int size)1395 static struct ftrace_hash *__move_hash(struct ftrace_hash *src, int size)
1396 {
1397 	struct ftrace_func_entry *entry;
1398 	struct ftrace_hash *new_hash;
1399 	struct hlist_head *hhd;
1400 	struct hlist_node *tn;
1401 	int bits = 0;
1402 	int i;
1403 
1404 	/*
1405 	 * Use around half the size (max bit of it), but
1406 	 * a minimum of 2 is fine (as size of 0 or 1 both give 1 for bits).
1407 	 */
1408 	bits = fls(size / 2);
1409 
1410 	/* Don't allocate too much */
1411 	if (bits > FTRACE_HASH_MAX_BITS)
1412 		bits = FTRACE_HASH_MAX_BITS;
1413 
1414 	new_hash = alloc_ftrace_hash(bits);
1415 	if (!new_hash)
1416 		return NULL;
1417 
1418 	new_hash->flags = src->flags;
1419 
1420 	size = 1 << src->size_bits;
1421 	for (i = 0; i < size; i++) {
1422 		hhd = &src->buckets[i];
1423 		hlist_for_each_entry_safe(entry, tn, hhd, hlist) {
1424 			remove_hash_entry(src, entry);
1425 			__add_hash_entry(new_hash, entry);
1426 		}
1427 	}
1428 	return new_hash;
1429 }
1430 
1431 /* Move the @src entries to a newly allocated hash */
1432 static struct ftrace_hash *
__ftrace_hash_move(struct ftrace_hash * src)1433 __ftrace_hash_move(struct ftrace_hash *src)
1434 {
1435 	int size = src->count;
1436 
1437 	/*
1438 	 * If the new source is empty, just return the empty_hash.
1439 	 */
1440 	if (ftrace_hash_empty(src))
1441 		return EMPTY_HASH;
1442 
1443 	return __move_hash(src, size);
1444 }
1445 
1446 /**
1447  * ftrace_hash_move - move a new hash to a filter and do updates
1448  * @ops: The ops with the hash that @dst points to
1449  * @enable: True if for the filter hash, false for the notrace hash
1450  * @dst: Points to the @ops hash that should be updated
1451  * @src: The hash to update @dst with
1452  *
1453  * This is called when an ftrace_ops hash is being updated and the
1454  * the kernel needs to reflect this. Note, this only updates the kernel
1455  * function callbacks if the @ops is enabled (not to be confused with
1456  * @enable above). If the @ops is enabled, its hash determines what
1457  * callbacks get called. This function gets called when the @ops hash
1458  * is updated and it requires new callbacks.
1459  *
1460  * On success the elements of @src is moved to @dst, and @dst is updated
1461  * properly, as well as the functions determined by the @ops hashes
1462  * are now calling the @ops callback function.
1463  *
1464  * Regardless of return type, @src should be freed with free_ftrace_hash().
1465  */
1466 static int
ftrace_hash_move(struct ftrace_ops * ops,int enable,struct ftrace_hash ** dst,struct ftrace_hash * src)1467 ftrace_hash_move(struct ftrace_ops *ops, int enable,
1468 		 struct ftrace_hash **dst, struct ftrace_hash *src)
1469 {
1470 	struct ftrace_hash *new_hash;
1471 	int ret;
1472 
1473 	/* Reject setting notrace hash on IPMODIFY ftrace_ops */
1474 	if (ops->flags & FTRACE_OPS_FL_IPMODIFY && !enable)
1475 		return -EINVAL;
1476 
1477 	new_hash = __ftrace_hash_move(src);
1478 	if (!new_hash)
1479 		return -ENOMEM;
1480 
1481 	/* Make sure this can be applied if it is IPMODIFY ftrace_ops */
1482 	if (enable) {
1483 		/* IPMODIFY should be updated only when filter_hash updating */
1484 		ret = ftrace_hash_ipmodify_update(ops, new_hash);
1485 		if (ret < 0) {
1486 			free_ftrace_hash(new_hash);
1487 			return ret;
1488 		}
1489 	}
1490 
1491 	/*
1492 	 * Remove the current set, update the hash and add
1493 	 * them back.
1494 	 */
1495 	ftrace_hash_rec_disable_modify(ops);
1496 
1497 	rcu_assign_pointer(*dst, new_hash);
1498 
1499 	ftrace_hash_rec_enable_modify(ops);
1500 
1501 	return 0;
1502 }
1503 
hash_contains_ip(unsigned long ip,struct ftrace_ops_hash * hash)1504 static bool hash_contains_ip(unsigned long ip,
1505 			     struct ftrace_ops_hash *hash)
1506 {
1507 	/*
1508 	 * The function record is a match if it exists in the filter
1509 	 * hash and not in the notrace hash. Note, an empty hash is
1510 	 * considered a match for the filter hash, but an empty
1511 	 * notrace hash is considered not in the notrace hash.
1512 	 */
1513 	return (ftrace_hash_empty(hash->filter_hash) ||
1514 		__ftrace_lookup_ip(hash->filter_hash, ip)) &&
1515 		(ftrace_hash_empty(hash->notrace_hash) ||
1516 		 !__ftrace_lookup_ip(hash->notrace_hash, ip));
1517 }
1518 
1519 /*
1520  * Test the hashes for this ops to see if we want to call
1521  * the ops->func or not.
1522  *
1523  * It's a match if the ip is in the ops->filter_hash or
1524  * the filter_hash does not exist or is empty,
1525  *  AND
1526  * the ip is not in the ops->notrace_hash.
1527  *
1528  * This needs to be called with preemption disabled as
1529  * the hashes are freed with call_rcu().
1530  */
1531 int
ftrace_ops_test(struct ftrace_ops * ops,unsigned long ip,void * regs)1532 ftrace_ops_test(struct ftrace_ops *ops, unsigned long ip, void *regs)
1533 {
1534 	struct ftrace_ops_hash hash;
1535 	int ret;
1536 
1537 #ifdef CONFIG_DYNAMIC_FTRACE_WITH_REGS
1538 	/*
1539 	 * There's a small race when adding ops that the ftrace handler
1540 	 * that wants regs, may be called without them. We can not
1541 	 * allow that handler to be called if regs is NULL.
1542 	 */
1543 	if (regs == NULL && (ops->flags & FTRACE_OPS_FL_SAVE_REGS))
1544 		return 0;
1545 #endif
1546 
1547 	rcu_assign_pointer(hash.filter_hash, ops->func_hash->filter_hash);
1548 	rcu_assign_pointer(hash.notrace_hash, ops->func_hash->notrace_hash);
1549 
1550 	if (hash_contains_ip(ip, &hash))
1551 		ret = 1;
1552 	else
1553 		ret = 0;
1554 
1555 	return ret;
1556 }
1557 
1558 /*
1559  * This is a double for. Do not use 'break' to break out of the loop,
1560  * you must use a goto.
1561  */
1562 #define do_for_each_ftrace_rec(pg, rec)					\
1563 	for (pg = ftrace_pages_start; pg; pg = pg->next) {		\
1564 		int _____i;						\
1565 		for (_____i = 0; _____i < pg->index; _____i++) {	\
1566 			rec = &pg->records[_____i];
1567 
1568 #define while_for_each_ftrace_rec()		\
1569 		}				\
1570 	}
1571 
1572 
ftrace_cmp_recs(const void * a,const void * b)1573 static int ftrace_cmp_recs(const void *a, const void *b)
1574 {
1575 	const struct dyn_ftrace *key = a;
1576 	const struct dyn_ftrace *rec = b;
1577 
1578 	if (key->flags < rec->ip)
1579 		return -1;
1580 	if (key->ip >= rec->ip + MCOUNT_INSN_SIZE)
1581 		return 1;
1582 	return 0;
1583 }
1584 
lookup_rec(unsigned long start,unsigned long end)1585 static struct dyn_ftrace *lookup_rec(unsigned long start, unsigned long end)
1586 {
1587 	struct ftrace_page *pg;
1588 	struct dyn_ftrace *rec = NULL;
1589 	struct dyn_ftrace key;
1590 
1591 	key.ip = start;
1592 	key.flags = end;	/* overload flags, as it is unsigned long */
1593 
1594 	for (pg = ftrace_pages_start; pg; pg = pg->next) {
1595 		if (pg->index == 0 ||
1596 		    end < pg->records[0].ip ||
1597 		    start >= (pg->records[pg->index - 1].ip + MCOUNT_INSN_SIZE))
1598 			continue;
1599 		rec = bsearch(&key, pg->records, pg->index,
1600 			      sizeof(struct dyn_ftrace),
1601 			      ftrace_cmp_recs);
1602 		if (rec)
1603 			break;
1604 	}
1605 	return rec;
1606 }
1607 
1608 /**
1609  * ftrace_location_range - return the first address of a traced location
1610  *	if it touches the given ip range
1611  * @start: start of range to search.
1612  * @end: end of range to search (inclusive). @end points to the last byte
1613  *	to check.
1614  *
1615  * Returns: rec->ip if the related ftrace location is a least partly within
1616  * the given address range. That is, the first address of the instruction
1617  * that is either a NOP or call to the function tracer. It checks the ftrace
1618  * internal tables to determine if the address belongs or not.
1619  */
ftrace_location_range(unsigned long start,unsigned long end)1620 unsigned long ftrace_location_range(unsigned long start, unsigned long end)
1621 {
1622 	struct dyn_ftrace *rec;
1623 	unsigned long ip = 0;
1624 
1625 	rcu_read_lock();
1626 	rec = lookup_rec(start, end);
1627 	if (rec)
1628 		ip = rec->ip;
1629 	rcu_read_unlock();
1630 
1631 	return ip;
1632 }
1633 
1634 /**
1635  * ftrace_location - return the ftrace location
1636  * @ip: the instruction pointer to check
1637  *
1638  * Returns:
1639  * * If @ip matches the ftrace location, return @ip.
1640  * * If @ip matches sym+0, return sym's ftrace location.
1641  * * Otherwise, return 0.
1642  */
ftrace_location(unsigned long ip)1643 unsigned long ftrace_location(unsigned long ip)
1644 {
1645 	unsigned long loc;
1646 	unsigned long offset;
1647 	unsigned long size;
1648 
1649 	loc = ftrace_location_range(ip, ip);
1650 	if (!loc) {
1651 		if (!kallsyms_lookup_size_offset(ip, &size, &offset))
1652 			goto out;
1653 
1654 		/* map sym+0 to __fentry__ */
1655 		if (!offset)
1656 			loc = ftrace_location_range(ip, ip + size - 1);
1657 	}
1658 
1659 out:
1660 	return loc;
1661 }
1662 
1663 /**
1664  * ftrace_text_reserved - return true if range contains an ftrace location
1665  * @start: start of range to search
1666  * @end: end of range to search (inclusive). @end points to the last byte to check.
1667  *
1668  * Returns: 1 if @start and @end contains a ftrace location.
1669  * That is, the instruction that is either a NOP or call to
1670  * the function tracer. It checks the ftrace internal tables to
1671  * determine if the address belongs or not.
1672  */
ftrace_text_reserved(const void * start,const void * end)1673 int ftrace_text_reserved(const void *start, const void *end)
1674 {
1675 	unsigned long ret;
1676 
1677 	ret = ftrace_location_range((unsigned long)start,
1678 				    (unsigned long)end);
1679 
1680 	return (int)!!ret;
1681 }
1682 
1683 /* Test if ops registered to this rec needs regs */
test_rec_ops_needs_regs(struct dyn_ftrace * rec)1684 static bool test_rec_ops_needs_regs(struct dyn_ftrace *rec)
1685 {
1686 	struct ftrace_ops *ops;
1687 	bool keep_regs = false;
1688 
1689 	for (ops = ftrace_ops_list;
1690 	     ops != &ftrace_list_end; ops = ops->next) {
1691 		/* pass rec in as regs to have non-NULL val */
1692 		if (ftrace_ops_test(ops, rec->ip, rec)) {
1693 			if (ops->flags & FTRACE_OPS_FL_SAVE_REGS) {
1694 				keep_regs = true;
1695 				break;
1696 			}
1697 		}
1698 	}
1699 
1700 	return  keep_regs;
1701 }
1702 
1703 static struct ftrace_ops *
1704 ftrace_find_tramp_ops_any(struct dyn_ftrace *rec);
1705 static struct ftrace_ops *
1706 ftrace_find_tramp_ops_any_other(struct dyn_ftrace *rec, struct ftrace_ops *op_exclude);
1707 static struct ftrace_ops *
1708 ftrace_find_tramp_ops_next(struct dyn_ftrace *rec, struct ftrace_ops *ops);
1709 
skip_record(struct dyn_ftrace * rec)1710 static bool skip_record(struct dyn_ftrace *rec)
1711 {
1712 	/*
1713 	 * At boot up, weak functions are set to disable. Function tracing
1714 	 * can be enabled before they are, and they still need to be disabled now.
1715 	 * If the record is disabled, still continue if it is marked as already
1716 	 * enabled (this is needed to keep the accounting working).
1717 	 */
1718 	return rec->flags & FTRACE_FL_DISABLED &&
1719 		!(rec->flags & FTRACE_FL_ENABLED);
1720 }
1721 
1722 /*
1723  * This is the main engine to the ftrace updates to the dyn_ftrace records.
1724  *
1725  * It will iterate through all the available ftrace functions
1726  * (the ones that ftrace can have callbacks to) and set the flags
1727  * in the associated dyn_ftrace records.
1728  *
1729  * @inc: If true, the functions associated to @ops are added to
1730  *       the dyn_ftrace records, otherwise they are removed.
1731  */
__ftrace_hash_rec_update(struct ftrace_ops * ops,bool inc)1732 static bool __ftrace_hash_rec_update(struct ftrace_ops *ops,
1733 				     bool inc)
1734 {
1735 	struct ftrace_hash *hash;
1736 	struct ftrace_hash *notrace_hash;
1737 	struct ftrace_page *pg;
1738 	struct dyn_ftrace *rec;
1739 	bool update = false;
1740 	int count = 0;
1741 	int all = false;
1742 
1743 	/* Only update if the ops has been registered */
1744 	if (!(ops->flags & FTRACE_OPS_FL_ENABLED))
1745 		return false;
1746 
1747 	/*
1748 	 *   If the count is zero, we update all records.
1749 	 *   Otherwise we just update the items in the hash.
1750 	 */
1751 	hash = ops->func_hash->filter_hash;
1752 	notrace_hash = ops->func_hash->notrace_hash;
1753 	if (ftrace_hash_empty(hash))
1754 		all = true;
1755 
1756 	do_for_each_ftrace_rec(pg, rec) {
1757 		int in_notrace_hash = 0;
1758 		int in_hash = 0;
1759 		int match = 0;
1760 
1761 		if (skip_record(rec))
1762 			continue;
1763 
1764 		if (all) {
1765 			/*
1766 			 * Only the filter_hash affects all records.
1767 			 * Update if the record is not in the notrace hash.
1768 			 */
1769 			if (!notrace_hash || !ftrace_lookup_ip(notrace_hash, rec->ip))
1770 				match = 1;
1771 		} else {
1772 			in_hash = !!ftrace_lookup_ip(hash, rec->ip);
1773 			in_notrace_hash = !!ftrace_lookup_ip(notrace_hash, rec->ip);
1774 
1775 			/*
1776 			 * We want to match all functions that are in the hash but
1777 			 * not in the other hash.
1778 			 */
1779 			if (in_hash && !in_notrace_hash)
1780 				match = 1;
1781 		}
1782 		if (!match)
1783 			continue;
1784 
1785 		if (inc) {
1786 			rec->flags++;
1787 			if (FTRACE_WARN_ON(ftrace_rec_count(rec) == FTRACE_REF_MAX))
1788 				return false;
1789 
1790 			if (ops->flags & FTRACE_OPS_FL_DIRECT)
1791 				rec->flags |= FTRACE_FL_DIRECT;
1792 
1793 			/*
1794 			 * If there's only a single callback registered to a
1795 			 * function, and the ops has a trampoline registered
1796 			 * for it, then we can call it directly.
1797 			 */
1798 			if (ftrace_rec_count(rec) == 1 && ops->trampoline)
1799 				rec->flags |= FTRACE_FL_TRAMP;
1800 			else
1801 				/*
1802 				 * If we are adding another function callback
1803 				 * to this function, and the previous had a
1804 				 * custom trampoline in use, then we need to go
1805 				 * back to the default trampoline.
1806 				 */
1807 				rec->flags &= ~FTRACE_FL_TRAMP;
1808 
1809 			/*
1810 			 * If any ops wants regs saved for this function
1811 			 * then all ops will get saved regs.
1812 			 */
1813 			if (ops->flags & FTRACE_OPS_FL_SAVE_REGS)
1814 				rec->flags |= FTRACE_FL_REGS;
1815 		} else {
1816 			if (FTRACE_WARN_ON(ftrace_rec_count(rec) == 0))
1817 				return false;
1818 			rec->flags--;
1819 
1820 			/*
1821 			 * Only the internal direct_ops should have the
1822 			 * DIRECT flag set. Thus, if it is removing a
1823 			 * function, then that function should no longer
1824 			 * be direct.
1825 			 */
1826 			if (ops->flags & FTRACE_OPS_FL_DIRECT)
1827 				rec->flags &= ~FTRACE_FL_DIRECT;
1828 
1829 			/*
1830 			 * If the rec had REGS enabled and the ops that is
1831 			 * being removed had REGS set, then see if there is
1832 			 * still any ops for this record that wants regs.
1833 			 * If not, we can stop recording them.
1834 			 */
1835 			if (ftrace_rec_count(rec) > 0 &&
1836 			    rec->flags & FTRACE_FL_REGS &&
1837 			    ops->flags & FTRACE_OPS_FL_SAVE_REGS) {
1838 				if (!test_rec_ops_needs_regs(rec))
1839 					rec->flags &= ~FTRACE_FL_REGS;
1840 			}
1841 
1842 			/*
1843 			 * The TRAMP needs to be set only if rec count
1844 			 * is decremented to one, and the ops that is
1845 			 * left has a trampoline. As TRAMP can only be
1846 			 * enabled if there is only a single ops attached
1847 			 * to it.
1848 			 */
1849 			if (ftrace_rec_count(rec) == 1 &&
1850 			    ftrace_find_tramp_ops_any_other(rec, ops))
1851 				rec->flags |= FTRACE_FL_TRAMP;
1852 			else
1853 				rec->flags &= ~FTRACE_FL_TRAMP;
1854 
1855 			/*
1856 			 * flags will be cleared in ftrace_check_record()
1857 			 * if rec count is zero.
1858 			 */
1859 		}
1860 
1861 		/*
1862 		 * If the rec has a single associated ops, and ops->func can be
1863 		 * called directly, allow the call site to call via the ops.
1864 		 */
1865 		if (IS_ENABLED(CONFIG_DYNAMIC_FTRACE_WITH_CALL_OPS) &&
1866 		    ftrace_rec_count(rec) == 1 &&
1867 		    ftrace_ops_get_func(ops) == ops->func)
1868 			rec->flags |= FTRACE_FL_CALL_OPS;
1869 		else
1870 			rec->flags &= ~FTRACE_FL_CALL_OPS;
1871 
1872 		count++;
1873 
1874 		/* Must match FTRACE_UPDATE_CALLS in ftrace_modify_all_code() */
1875 		update |= ftrace_test_record(rec, true) != FTRACE_UPDATE_IGNORE;
1876 
1877 		/* Shortcut, if we handled all records, we are done. */
1878 		if (!all && count == hash->count)
1879 			return update;
1880 	} while_for_each_ftrace_rec();
1881 
1882 	return update;
1883 }
1884 
1885 /*
1886  * This is called when an ops is removed from tracing. It will decrement
1887  * the counters of the dyn_ftrace records for all the functions that
1888  * the @ops attached to.
1889  */
ftrace_hash_rec_disable(struct ftrace_ops * ops)1890 static bool ftrace_hash_rec_disable(struct ftrace_ops *ops)
1891 {
1892 	return __ftrace_hash_rec_update(ops, false);
1893 }
1894 
1895 /*
1896  * This is called when an ops is added to tracing. It will increment
1897  * the counters of the dyn_ftrace records for all the functions that
1898  * the @ops attached to.
1899  */
ftrace_hash_rec_enable(struct ftrace_ops * ops)1900 static bool ftrace_hash_rec_enable(struct ftrace_ops *ops)
1901 {
1902 	return __ftrace_hash_rec_update(ops, true);
1903 }
1904 
1905 /*
1906  * This function will update what functions @ops traces when its filter
1907  * changes.
1908  *
1909  * The @inc states if the @ops callbacks are going to be added or removed.
1910  * When one of the @ops hashes are updated to a "new_hash" the dyn_ftrace
1911  * records are update via:
1912  *
1913  * ftrace_hash_rec_disable_modify(ops);
1914  * ops->hash = new_hash
1915  * ftrace_hash_rec_enable_modify(ops);
1916  *
1917  * Where the @ops is removed from all the records it is tracing using
1918  * its old hash. The @ops hash is updated to the new hash, and then
1919  * the @ops is added back to the records so that it is tracing all
1920  * the new functions.
1921  */
ftrace_hash_rec_update_modify(struct ftrace_ops * ops,bool inc)1922 static void ftrace_hash_rec_update_modify(struct ftrace_ops *ops, bool inc)
1923 {
1924 	struct ftrace_ops *op;
1925 
1926 	__ftrace_hash_rec_update(ops, inc);
1927 
1928 	if (ops->func_hash != &global_ops.local_hash)
1929 		return;
1930 
1931 	/*
1932 	 * If the ops shares the global_ops hash, then we need to update
1933 	 * all ops that are enabled and use this hash.
1934 	 */
1935 	do_for_each_ftrace_op(op, ftrace_ops_list) {
1936 		/* Already done */
1937 		if (op == ops)
1938 			continue;
1939 		if (op->func_hash == &global_ops.local_hash)
1940 			__ftrace_hash_rec_update(op, inc);
1941 	} while_for_each_ftrace_op(op);
1942 }
1943 
ftrace_hash_rec_disable_modify(struct ftrace_ops * ops)1944 static void ftrace_hash_rec_disable_modify(struct ftrace_ops *ops)
1945 {
1946 	ftrace_hash_rec_update_modify(ops, false);
1947 }
1948 
ftrace_hash_rec_enable_modify(struct ftrace_ops * ops)1949 static void ftrace_hash_rec_enable_modify(struct ftrace_ops *ops)
1950 {
1951 	ftrace_hash_rec_update_modify(ops, true);
1952 }
1953 
1954 /*
1955  * Try to update IPMODIFY flag on each ftrace_rec. Return 0 if it is OK
1956  * or no-needed to update, -EBUSY if it detects a conflict of the flag
1957  * on a ftrace_rec, and -EINVAL if the new_hash tries to trace all recs.
1958  * Note that old_hash and new_hash has below meanings
1959  *  - If the hash is NULL, it hits all recs (if IPMODIFY is set, this is rejected)
1960  *  - If the hash is EMPTY_HASH, it hits nothing
1961  *  - Anything else hits the recs which match the hash entries.
1962  *
1963  * DIRECT ops does not have IPMODIFY flag, but we still need to check it
1964  * against functions with FTRACE_FL_IPMODIFY. If there is any overlap, call
1965  * ops_func(SHARE_IPMODIFY_SELF) to make sure current ops can share with
1966  * IPMODIFY. If ops_func(SHARE_IPMODIFY_SELF) returns non-zero, propagate
1967  * the return value to the caller and eventually to the owner of the DIRECT
1968  * ops.
1969  */
__ftrace_hash_update_ipmodify(struct ftrace_ops * ops,struct ftrace_hash * old_hash,struct ftrace_hash * new_hash)1970 static int __ftrace_hash_update_ipmodify(struct ftrace_ops *ops,
1971 					 struct ftrace_hash *old_hash,
1972 					 struct ftrace_hash *new_hash)
1973 {
1974 	struct ftrace_page *pg;
1975 	struct dyn_ftrace *rec, *end = NULL;
1976 	int in_old, in_new;
1977 	bool is_ipmodify, is_direct;
1978 
1979 	/* Only update if the ops has been registered */
1980 	if (!(ops->flags & FTRACE_OPS_FL_ENABLED))
1981 		return 0;
1982 
1983 	is_ipmodify = ops->flags & FTRACE_OPS_FL_IPMODIFY;
1984 	is_direct = ops->flags & FTRACE_OPS_FL_DIRECT;
1985 
1986 	/* neither IPMODIFY nor DIRECT, skip */
1987 	if (!is_ipmodify && !is_direct)
1988 		return 0;
1989 
1990 	if (WARN_ON_ONCE(is_ipmodify && is_direct))
1991 		return 0;
1992 
1993 	/*
1994 	 * Since the IPMODIFY and DIRECT are very address sensitive
1995 	 * actions, we do not allow ftrace_ops to set all functions to new
1996 	 * hash.
1997 	 */
1998 	if (!new_hash || !old_hash)
1999 		return -EINVAL;
2000 
2001 	/* Update rec->flags */
2002 	do_for_each_ftrace_rec(pg, rec) {
2003 
2004 		if (rec->flags & FTRACE_FL_DISABLED)
2005 			continue;
2006 
2007 		/* We need to update only differences of filter_hash */
2008 		in_old = !!ftrace_lookup_ip(old_hash, rec->ip);
2009 		in_new = !!ftrace_lookup_ip(new_hash, rec->ip);
2010 		if (in_old == in_new)
2011 			continue;
2012 
2013 		if (in_new) {
2014 			if (rec->flags & FTRACE_FL_IPMODIFY) {
2015 				int ret;
2016 
2017 				/* Cannot have two ipmodify on same rec */
2018 				if (is_ipmodify)
2019 					goto rollback;
2020 
2021 				FTRACE_WARN_ON(rec->flags & FTRACE_FL_DIRECT);
2022 
2023 				/*
2024 				 * Another ops with IPMODIFY is already
2025 				 * attached. We are now attaching a direct
2026 				 * ops. Run SHARE_IPMODIFY_SELF, to check
2027 				 * whether sharing is supported.
2028 				 */
2029 				if (!ops->ops_func)
2030 					return -EBUSY;
2031 				ret = ops->ops_func(ops, FTRACE_OPS_CMD_ENABLE_SHARE_IPMODIFY_SELF);
2032 				if (ret)
2033 					return ret;
2034 			} else if (is_ipmodify) {
2035 				rec->flags |= FTRACE_FL_IPMODIFY;
2036 			}
2037 		} else if (is_ipmodify) {
2038 			rec->flags &= ~FTRACE_FL_IPMODIFY;
2039 		}
2040 	} while_for_each_ftrace_rec();
2041 
2042 	return 0;
2043 
2044 rollback:
2045 	end = rec;
2046 
2047 	/* Roll back what we did above */
2048 	do_for_each_ftrace_rec(pg, rec) {
2049 
2050 		if (rec->flags & FTRACE_FL_DISABLED)
2051 			continue;
2052 
2053 		if (rec == end)
2054 			goto err_out;
2055 
2056 		in_old = !!ftrace_lookup_ip(old_hash, rec->ip);
2057 		in_new = !!ftrace_lookup_ip(new_hash, rec->ip);
2058 		if (in_old == in_new)
2059 			continue;
2060 
2061 		if (in_new)
2062 			rec->flags &= ~FTRACE_FL_IPMODIFY;
2063 		else
2064 			rec->flags |= FTRACE_FL_IPMODIFY;
2065 	} while_for_each_ftrace_rec();
2066 
2067 err_out:
2068 	return -EBUSY;
2069 }
2070 
ftrace_hash_ipmodify_enable(struct ftrace_ops * ops)2071 static int ftrace_hash_ipmodify_enable(struct ftrace_ops *ops)
2072 {
2073 	struct ftrace_hash *hash = ops->func_hash->filter_hash;
2074 
2075 	if (ftrace_hash_empty(hash))
2076 		hash = NULL;
2077 
2078 	return __ftrace_hash_update_ipmodify(ops, EMPTY_HASH, hash);
2079 }
2080 
2081 /* Disabling always succeeds */
ftrace_hash_ipmodify_disable(struct ftrace_ops * ops)2082 static void ftrace_hash_ipmodify_disable(struct ftrace_ops *ops)
2083 {
2084 	struct ftrace_hash *hash = ops->func_hash->filter_hash;
2085 
2086 	if (ftrace_hash_empty(hash))
2087 		hash = NULL;
2088 
2089 	__ftrace_hash_update_ipmodify(ops, hash, EMPTY_HASH);
2090 }
2091 
ftrace_hash_ipmodify_update(struct ftrace_ops * ops,struct ftrace_hash * new_hash)2092 static int ftrace_hash_ipmodify_update(struct ftrace_ops *ops,
2093 				       struct ftrace_hash *new_hash)
2094 {
2095 	struct ftrace_hash *old_hash = ops->func_hash->filter_hash;
2096 
2097 	if (ftrace_hash_empty(old_hash))
2098 		old_hash = NULL;
2099 
2100 	if (ftrace_hash_empty(new_hash))
2101 		new_hash = NULL;
2102 
2103 	return __ftrace_hash_update_ipmodify(ops, old_hash, new_hash);
2104 }
2105 
print_ip_ins(const char * fmt,const unsigned char * p)2106 static void print_ip_ins(const char *fmt, const unsigned char *p)
2107 {
2108 	char ins[MCOUNT_INSN_SIZE];
2109 
2110 	if (copy_from_kernel_nofault(ins, p, MCOUNT_INSN_SIZE)) {
2111 		printk(KERN_CONT "%s[FAULT] %px\n", fmt, p);
2112 		return;
2113 	}
2114 
2115 	printk(KERN_CONT "%s", fmt);
2116 	pr_cont("%*phC", MCOUNT_INSN_SIZE, ins);
2117 }
2118 
2119 enum ftrace_bug_type ftrace_bug_type;
2120 const void *ftrace_expected;
2121 
print_bug_type(void)2122 static void print_bug_type(void)
2123 {
2124 	switch (ftrace_bug_type) {
2125 	case FTRACE_BUG_UNKNOWN:
2126 		break;
2127 	case FTRACE_BUG_INIT:
2128 		pr_info("Initializing ftrace call sites\n");
2129 		break;
2130 	case FTRACE_BUG_NOP:
2131 		pr_info("Setting ftrace call site to NOP\n");
2132 		break;
2133 	case FTRACE_BUG_CALL:
2134 		pr_info("Setting ftrace call site to call ftrace function\n");
2135 		break;
2136 	case FTRACE_BUG_UPDATE:
2137 		pr_info("Updating ftrace call site to call a different ftrace function\n");
2138 		break;
2139 	}
2140 }
2141 
2142 /**
2143  * ftrace_bug - report and shutdown function tracer
2144  * @failed: The failed type (EFAULT, EINVAL, EPERM)
2145  * @rec: The record that failed
2146  *
2147  * The arch code that enables or disables the function tracing
2148  * can call ftrace_bug() when it has detected a problem in
2149  * modifying the code. @failed should be one of either:
2150  * EFAULT - if the problem happens on reading the @ip address
2151  * EINVAL - if what is read at @ip is not what was expected
2152  * EPERM - if the problem happens on writing to the @ip address
2153  */
ftrace_bug(int failed,struct dyn_ftrace * rec)2154 void ftrace_bug(int failed, struct dyn_ftrace *rec)
2155 {
2156 	unsigned long ip = rec ? rec->ip : 0;
2157 
2158 	pr_info("------------[ ftrace bug ]------------\n");
2159 
2160 	switch (failed) {
2161 	case -EFAULT:
2162 		pr_info("ftrace faulted on modifying ");
2163 		print_ip_sym(KERN_INFO, ip);
2164 		break;
2165 	case -EINVAL:
2166 		pr_info("ftrace failed to modify ");
2167 		print_ip_sym(KERN_INFO, ip);
2168 		print_ip_ins(" actual:   ", (unsigned char *)ip);
2169 		pr_cont("\n");
2170 		if (ftrace_expected) {
2171 			print_ip_ins(" expected: ", ftrace_expected);
2172 			pr_cont("\n");
2173 		}
2174 		break;
2175 	case -EPERM:
2176 		pr_info("ftrace faulted on writing ");
2177 		print_ip_sym(KERN_INFO, ip);
2178 		break;
2179 	default:
2180 		pr_info("ftrace faulted on unknown error ");
2181 		print_ip_sym(KERN_INFO, ip);
2182 	}
2183 	print_bug_type();
2184 	if (rec) {
2185 		struct ftrace_ops *ops = NULL;
2186 
2187 		pr_info("ftrace record flags: %lx\n", rec->flags);
2188 		pr_cont(" (%ld)%s%s", ftrace_rec_count(rec),
2189 			rec->flags & FTRACE_FL_REGS ? " R" : "  ",
2190 			rec->flags & FTRACE_FL_CALL_OPS ? " O" : "  ");
2191 		if (rec->flags & FTRACE_FL_TRAMP_EN) {
2192 			ops = ftrace_find_tramp_ops_any(rec);
2193 			if (ops) {
2194 				do {
2195 					pr_cont("\ttramp: %pS (%pS)",
2196 						(void *)ops->trampoline,
2197 						(void *)ops->func);
2198 					ops = ftrace_find_tramp_ops_next(rec, ops);
2199 				} while (ops);
2200 			} else
2201 				pr_cont("\ttramp: ERROR!");
2202 
2203 		}
2204 		ip = ftrace_get_addr_curr(rec);
2205 		pr_cont("\n expected tramp: %lx\n", ip);
2206 	}
2207 
2208 	FTRACE_WARN_ON_ONCE(1);
2209 }
2210 
ftrace_check_record(struct dyn_ftrace * rec,bool enable,bool update)2211 static int ftrace_check_record(struct dyn_ftrace *rec, bool enable, bool update)
2212 {
2213 	unsigned long flag = 0UL;
2214 
2215 	ftrace_bug_type = FTRACE_BUG_UNKNOWN;
2216 
2217 	if (skip_record(rec))
2218 		return FTRACE_UPDATE_IGNORE;
2219 
2220 	/*
2221 	 * If we are updating calls:
2222 	 *
2223 	 *   If the record has a ref count, then we need to enable it
2224 	 *   because someone is using it.
2225 	 *
2226 	 *   Otherwise we make sure its disabled.
2227 	 *
2228 	 * If we are disabling calls, then disable all records that
2229 	 * are enabled.
2230 	 */
2231 	if (enable && ftrace_rec_count(rec))
2232 		flag = FTRACE_FL_ENABLED;
2233 
2234 	/*
2235 	 * If enabling and the REGS flag does not match the REGS_EN, or
2236 	 * the TRAMP flag doesn't match the TRAMP_EN, then do not ignore
2237 	 * this record. Set flags to fail the compare against ENABLED.
2238 	 * Same for direct calls.
2239 	 */
2240 	if (flag) {
2241 		if (!(rec->flags & FTRACE_FL_REGS) !=
2242 		    !(rec->flags & FTRACE_FL_REGS_EN))
2243 			flag |= FTRACE_FL_REGS;
2244 
2245 		if (!(rec->flags & FTRACE_FL_TRAMP) !=
2246 		    !(rec->flags & FTRACE_FL_TRAMP_EN))
2247 			flag |= FTRACE_FL_TRAMP;
2248 
2249 		/*
2250 		 * Direct calls are special, as count matters.
2251 		 * We must test the record for direct, if the
2252 		 * DIRECT and DIRECT_EN do not match, but only
2253 		 * if the count is 1. That's because, if the
2254 		 * count is something other than one, we do not
2255 		 * want the direct enabled (it will be done via the
2256 		 * direct helper). But if DIRECT_EN is set, and
2257 		 * the count is not one, we need to clear it.
2258 		 *
2259 		 */
2260 		if (ftrace_rec_count(rec) == 1) {
2261 			if (!(rec->flags & FTRACE_FL_DIRECT) !=
2262 			    !(rec->flags & FTRACE_FL_DIRECT_EN))
2263 				flag |= FTRACE_FL_DIRECT;
2264 		} else if (rec->flags & FTRACE_FL_DIRECT_EN) {
2265 			flag |= FTRACE_FL_DIRECT;
2266 		}
2267 
2268 		/*
2269 		 * Ops calls are special, as count matters.
2270 		 * As with direct calls, they must only be enabled when count
2271 		 * is one, otherwise they'll be handled via the list ops.
2272 		 */
2273 		if (ftrace_rec_count(rec) == 1) {
2274 			if (!(rec->flags & FTRACE_FL_CALL_OPS) !=
2275 			    !(rec->flags & FTRACE_FL_CALL_OPS_EN))
2276 				flag |= FTRACE_FL_CALL_OPS;
2277 		} else if (rec->flags & FTRACE_FL_CALL_OPS_EN) {
2278 			flag |= FTRACE_FL_CALL_OPS;
2279 		}
2280 	}
2281 
2282 	/* If the state of this record hasn't changed, then do nothing */
2283 	if ((rec->flags & FTRACE_FL_ENABLED) == flag)
2284 		return FTRACE_UPDATE_IGNORE;
2285 
2286 	if (flag) {
2287 		/* Save off if rec is being enabled (for return value) */
2288 		flag ^= rec->flags & FTRACE_FL_ENABLED;
2289 
2290 		if (update) {
2291 			rec->flags |= FTRACE_FL_ENABLED | FTRACE_FL_TOUCHED;
2292 			if (flag & FTRACE_FL_REGS) {
2293 				if (rec->flags & FTRACE_FL_REGS)
2294 					rec->flags |= FTRACE_FL_REGS_EN;
2295 				else
2296 					rec->flags &= ~FTRACE_FL_REGS_EN;
2297 			}
2298 			if (flag & FTRACE_FL_TRAMP) {
2299 				if (rec->flags & FTRACE_FL_TRAMP)
2300 					rec->flags |= FTRACE_FL_TRAMP_EN;
2301 				else
2302 					rec->flags &= ~FTRACE_FL_TRAMP_EN;
2303 			}
2304 
2305 			/* Keep track of anything that modifies the function */
2306 			if (rec->flags & (FTRACE_FL_DIRECT | FTRACE_FL_IPMODIFY))
2307 				rec->flags |= FTRACE_FL_MODIFIED;
2308 
2309 			if (flag & FTRACE_FL_DIRECT) {
2310 				/*
2311 				 * If there's only one user (direct_ops helper)
2312 				 * then we can call the direct function
2313 				 * directly (no ftrace trampoline).
2314 				 */
2315 				if (ftrace_rec_count(rec) == 1) {
2316 					if (rec->flags & FTRACE_FL_DIRECT)
2317 						rec->flags |= FTRACE_FL_DIRECT_EN;
2318 					else
2319 						rec->flags &= ~FTRACE_FL_DIRECT_EN;
2320 				} else {
2321 					/*
2322 					 * Can only call directly if there's
2323 					 * only one callback to the function.
2324 					 */
2325 					rec->flags &= ~FTRACE_FL_DIRECT_EN;
2326 				}
2327 			}
2328 
2329 			if (flag & FTRACE_FL_CALL_OPS) {
2330 				if (ftrace_rec_count(rec) == 1) {
2331 					if (rec->flags & FTRACE_FL_CALL_OPS)
2332 						rec->flags |= FTRACE_FL_CALL_OPS_EN;
2333 					else
2334 						rec->flags &= ~FTRACE_FL_CALL_OPS_EN;
2335 				} else {
2336 					/*
2337 					 * Can only call directly if there's
2338 					 * only one set of associated ops.
2339 					 */
2340 					rec->flags &= ~FTRACE_FL_CALL_OPS_EN;
2341 				}
2342 			}
2343 		}
2344 
2345 		/*
2346 		 * If this record is being updated from a nop, then
2347 		 *   return UPDATE_MAKE_CALL.
2348 		 * Otherwise,
2349 		 *   return UPDATE_MODIFY_CALL to tell the caller to convert
2350 		 *   from the save regs, to a non-save regs function or
2351 		 *   vice versa, or from a trampoline call.
2352 		 */
2353 		if (flag & FTRACE_FL_ENABLED) {
2354 			ftrace_bug_type = FTRACE_BUG_CALL;
2355 			return FTRACE_UPDATE_MAKE_CALL;
2356 		}
2357 
2358 		ftrace_bug_type = FTRACE_BUG_UPDATE;
2359 		return FTRACE_UPDATE_MODIFY_CALL;
2360 	}
2361 
2362 	if (update) {
2363 		/* If there's no more users, clear all flags */
2364 		if (!ftrace_rec_count(rec))
2365 			rec->flags &= FTRACE_NOCLEAR_FLAGS;
2366 		else
2367 			/*
2368 			 * Just disable the record, but keep the ops TRAMP
2369 			 * and REGS states. The _EN flags must be disabled though.
2370 			 */
2371 			rec->flags &= ~(FTRACE_FL_ENABLED | FTRACE_FL_TRAMP_EN |
2372 					FTRACE_FL_REGS_EN | FTRACE_FL_DIRECT_EN |
2373 					FTRACE_FL_CALL_OPS_EN);
2374 	}
2375 
2376 	ftrace_bug_type = FTRACE_BUG_NOP;
2377 	return FTRACE_UPDATE_MAKE_NOP;
2378 }
2379 
2380 /**
2381  * ftrace_update_record - set a record that now is tracing or not
2382  * @rec: the record to update
2383  * @enable: set to true if the record is tracing, false to force disable
2384  *
2385  * The records that represent all functions that can be traced need
2386  * to be updated when tracing has been enabled.
2387  */
ftrace_update_record(struct dyn_ftrace * rec,bool enable)2388 int ftrace_update_record(struct dyn_ftrace *rec, bool enable)
2389 {
2390 	return ftrace_check_record(rec, enable, true);
2391 }
2392 
2393 /**
2394  * ftrace_test_record - check if the record has been enabled or not
2395  * @rec: the record to test
2396  * @enable: set to true to check if enabled, false if it is disabled
2397  *
2398  * The arch code may need to test if a record is already set to
2399  * tracing to determine how to modify the function code that it
2400  * represents.
2401  */
ftrace_test_record(struct dyn_ftrace * rec,bool enable)2402 int ftrace_test_record(struct dyn_ftrace *rec, bool enable)
2403 {
2404 	return ftrace_check_record(rec, enable, false);
2405 }
2406 
2407 static struct ftrace_ops *
ftrace_find_tramp_ops_any(struct dyn_ftrace * rec)2408 ftrace_find_tramp_ops_any(struct dyn_ftrace *rec)
2409 {
2410 	struct ftrace_ops *op;
2411 	unsigned long ip = rec->ip;
2412 
2413 	do_for_each_ftrace_op(op, ftrace_ops_list) {
2414 
2415 		if (!op->trampoline)
2416 			continue;
2417 
2418 		if (hash_contains_ip(ip, op->func_hash))
2419 			return op;
2420 	} while_for_each_ftrace_op(op);
2421 
2422 	return NULL;
2423 }
2424 
2425 static struct ftrace_ops *
ftrace_find_tramp_ops_any_other(struct dyn_ftrace * rec,struct ftrace_ops * op_exclude)2426 ftrace_find_tramp_ops_any_other(struct dyn_ftrace *rec, struct ftrace_ops *op_exclude)
2427 {
2428 	struct ftrace_ops *op;
2429 	unsigned long ip = rec->ip;
2430 
2431 	do_for_each_ftrace_op(op, ftrace_ops_list) {
2432 
2433 		if (op == op_exclude || !op->trampoline)
2434 			continue;
2435 
2436 		if (hash_contains_ip(ip, op->func_hash))
2437 			return op;
2438 	} while_for_each_ftrace_op(op);
2439 
2440 	return NULL;
2441 }
2442 
2443 static struct ftrace_ops *
ftrace_find_tramp_ops_next(struct dyn_ftrace * rec,struct ftrace_ops * op)2444 ftrace_find_tramp_ops_next(struct dyn_ftrace *rec,
2445 			   struct ftrace_ops *op)
2446 {
2447 	unsigned long ip = rec->ip;
2448 
2449 	while_for_each_ftrace_op(op) {
2450 
2451 		if (!op->trampoline)
2452 			continue;
2453 
2454 		if (hash_contains_ip(ip, op->func_hash))
2455 			return op;
2456 	}
2457 
2458 	return NULL;
2459 }
2460 
2461 static struct ftrace_ops *
ftrace_find_tramp_ops_curr(struct dyn_ftrace * rec)2462 ftrace_find_tramp_ops_curr(struct dyn_ftrace *rec)
2463 {
2464 	struct ftrace_ops *op;
2465 	unsigned long ip = rec->ip;
2466 
2467 	/*
2468 	 * Need to check removed ops first.
2469 	 * If they are being removed, and this rec has a tramp,
2470 	 * and this rec is in the ops list, then it would be the
2471 	 * one with the tramp.
2472 	 */
2473 	if (removed_ops) {
2474 		if (hash_contains_ip(ip, &removed_ops->old_hash))
2475 			return removed_ops;
2476 	}
2477 
2478 	/*
2479 	 * Need to find the current trampoline for a rec.
2480 	 * Now, a trampoline is only attached to a rec if there
2481 	 * was a single 'ops' attached to it. But this can be called
2482 	 * when we are adding another op to the rec or removing the
2483 	 * current one. Thus, if the op is being added, we can
2484 	 * ignore it because it hasn't attached itself to the rec
2485 	 * yet.
2486 	 *
2487 	 * If an ops is being modified (hooking to different functions)
2488 	 * then we don't care about the new functions that are being
2489 	 * added, just the old ones (that are probably being removed).
2490 	 *
2491 	 * If we are adding an ops to a function that already is using
2492 	 * a trampoline, it needs to be removed (trampolines are only
2493 	 * for single ops connected), then an ops that is not being
2494 	 * modified also needs to be checked.
2495 	 */
2496 	do_for_each_ftrace_op(op, ftrace_ops_list) {
2497 
2498 		if (!op->trampoline)
2499 			continue;
2500 
2501 		/*
2502 		 * If the ops is being added, it hasn't gotten to
2503 		 * the point to be removed from this tree yet.
2504 		 */
2505 		if (op->flags & FTRACE_OPS_FL_ADDING)
2506 			continue;
2507 
2508 
2509 		/*
2510 		 * If the ops is being modified and is in the old
2511 		 * hash, then it is probably being removed from this
2512 		 * function.
2513 		 */
2514 		if ((op->flags & FTRACE_OPS_FL_MODIFYING) &&
2515 		    hash_contains_ip(ip, &op->old_hash))
2516 			return op;
2517 		/*
2518 		 * If the ops is not being added or modified, and it's
2519 		 * in its normal filter hash, then this must be the one
2520 		 * we want!
2521 		 */
2522 		if (!(op->flags & FTRACE_OPS_FL_MODIFYING) &&
2523 		    hash_contains_ip(ip, op->func_hash))
2524 			return op;
2525 
2526 	} while_for_each_ftrace_op(op);
2527 
2528 	return NULL;
2529 }
2530 
2531 static struct ftrace_ops *
ftrace_find_tramp_ops_new(struct dyn_ftrace * rec)2532 ftrace_find_tramp_ops_new(struct dyn_ftrace *rec)
2533 {
2534 	struct ftrace_ops *op;
2535 	unsigned long ip = rec->ip;
2536 
2537 	do_for_each_ftrace_op(op, ftrace_ops_list) {
2538 		/* pass rec in as regs to have non-NULL val */
2539 		if (hash_contains_ip(ip, op->func_hash))
2540 			return op;
2541 	} while_for_each_ftrace_op(op);
2542 
2543 	return NULL;
2544 }
2545 
2546 struct ftrace_ops *
ftrace_find_unique_ops(struct dyn_ftrace * rec)2547 ftrace_find_unique_ops(struct dyn_ftrace *rec)
2548 {
2549 	struct ftrace_ops *op, *found = NULL;
2550 	unsigned long ip = rec->ip;
2551 
2552 	do_for_each_ftrace_op(op, ftrace_ops_list) {
2553 
2554 		if (hash_contains_ip(ip, op->func_hash)) {
2555 			if (found)
2556 				return NULL;
2557 			found = op;
2558 		}
2559 
2560 	} while_for_each_ftrace_op(op);
2561 
2562 	return found;
2563 }
2564 
2565 #ifdef CONFIG_DYNAMIC_FTRACE_WITH_DIRECT_CALLS
2566 /* Protected by rcu_tasks for reading, and direct_mutex for writing */
2567 static struct ftrace_hash __rcu *direct_functions = EMPTY_HASH;
2568 static DEFINE_MUTEX(direct_mutex);
2569 
2570 /*
2571  * Search the direct_functions hash to see if the given instruction pointer
2572  * has a direct caller attached to it.
2573  */
ftrace_find_rec_direct(unsigned long ip)2574 unsigned long ftrace_find_rec_direct(unsigned long ip)
2575 {
2576 	struct ftrace_func_entry *entry;
2577 
2578 	entry = __ftrace_lookup_ip(direct_functions, ip);
2579 	if (!entry)
2580 		return 0;
2581 
2582 	return entry->direct;
2583 }
2584 
call_direct_funcs(unsigned long ip,unsigned long pip,struct ftrace_ops * ops,struct ftrace_regs * fregs)2585 static void call_direct_funcs(unsigned long ip, unsigned long pip,
2586 			      struct ftrace_ops *ops, struct ftrace_regs *fregs)
2587 {
2588 	unsigned long addr = READ_ONCE(ops->direct_call);
2589 
2590 	if (!addr)
2591 		return;
2592 
2593 	arch_ftrace_set_direct_caller(fregs, addr);
2594 }
2595 #endif /* CONFIG_DYNAMIC_FTRACE_WITH_DIRECT_CALLS */
2596 
2597 /**
2598  * ftrace_get_addr_new - Get the call address to set to
2599  * @rec:  The ftrace record descriptor
2600  *
2601  * If the record has the FTRACE_FL_REGS set, that means that it
2602  * wants to convert to a callback that saves all regs. If FTRACE_FL_REGS
2603  * is not set, then it wants to convert to the normal callback.
2604  *
2605  * Returns: the address of the trampoline to set to
2606  */
ftrace_get_addr_new(struct dyn_ftrace * rec)2607 unsigned long ftrace_get_addr_new(struct dyn_ftrace *rec)
2608 {
2609 	struct ftrace_ops *ops;
2610 	unsigned long addr;
2611 
2612 	if ((rec->flags & FTRACE_FL_DIRECT) &&
2613 	    (ftrace_rec_count(rec) == 1)) {
2614 		addr = ftrace_find_rec_direct(rec->ip);
2615 		if (addr)
2616 			return addr;
2617 		WARN_ON_ONCE(1);
2618 	}
2619 
2620 	/* Trampolines take precedence over regs */
2621 	if (rec->flags & FTRACE_FL_TRAMP) {
2622 		ops = ftrace_find_tramp_ops_new(rec);
2623 		if (FTRACE_WARN_ON(!ops || !ops->trampoline)) {
2624 			pr_warn("Bad trampoline accounting at: %p (%pS) (%lx)\n",
2625 				(void *)rec->ip, (void *)rec->ip, rec->flags);
2626 			/* Ftrace is shutting down, return anything */
2627 			return (unsigned long)FTRACE_ADDR;
2628 		}
2629 		return ops->trampoline;
2630 	}
2631 
2632 	if (rec->flags & FTRACE_FL_REGS)
2633 		return (unsigned long)FTRACE_REGS_ADDR;
2634 	else
2635 		return (unsigned long)FTRACE_ADDR;
2636 }
2637 
2638 /**
2639  * ftrace_get_addr_curr - Get the call address that is already there
2640  * @rec:  The ftrace record descriptor
2641  *
2642  * The FTRACE_FL_REGS_EN is set when the record already points to
2643  * a function that saves all the regs. Basically the '_EN' version
2644  * represents the current state of the function.
2645  *
2646  * Returns: the address of the trampoline that is currently being called
2647  */
ftrace_get_addr_curr(struct dyn_ftrace * rec)2648 unsigned long ftrace_get_addr_curr(struct dyn_ftrace *rec)
2649 {
2650 	struct ftrace_ops *ops;
2651 	unsigned long addr;
2652 
2653 	/* Direct calls take precedence over trampolines */
2654 	if (rec->flags & FTRACE_FL_DIRECT_EN) {
2655 		addr = ftrace_find_rec_direct(rec->ip);
2656 		if (addr)
2657 			return addr;
2658 		WARN_ON_ONCE(1);
2659 	}
2660 
2661 	/* Trampolines take precedence over regs */
2662 	if (rec->flags & FTRACE_FL_TRAMP_EN) {
2663 		ops = ftrace_find_tramp_ops_curr(rec);
2664 		if (FTRACE_WARN_ON(!ops)) {
2665 			pr_warn("Bad trampoline accounting at: %p (%pS)\n",
2666 				(void *)rec->ip, (void *)rec->ip);
2667 			/* Ftrace is shutting down, return anything */
2668 			return (unsigned long)FTRACE_ADDR;
2669 		}
2670 		return ops->trampoline;
2671 	}
2672 
2673 	if (rec->flags & FTRACE_FL_REGS_EN)
2674 		return (unsigned long)FTRACE_REGS_ADDR;
2675 	else
2676 		return (unsigned long)FTRACE_ADDR;
2677 }
2678 
2679 static int
__ftrace_replace_code(struct dyn_ftrace * rec,bool enable)2680 __ftrace_replace_code(struct dyn_ftrace *rec, bool enable)
2681 {
2682 	unsigned long ftrace_old_addr;
2683 	unsigned long ftrace_addr;
2684 	int ret;
2685 
2686 	ftrace_addr = ftrace_get_addr_new(rec);
2687 
2688 	/* This needs to be done before we call ftrace_update_record */
2689 	ftrace_old_addr = ftrace_get_addr_curr(rec);
2690 
2691 	ret = ftrace_update_record(rec, enable);
2692 
2693 	ftrace_bug_type = FTRACE_BUG_UNKNOWN;
2694 
2695 	switch (ret) {
2696 	case FTRACE_UPDATE_IGNORE:
2697 		return 0;
2698 
2699 	case FTRACE_UPDATE_MAKE_CALL:
2700 		ftrace_bug_type = FTRACE_BUG_CALL;
2701 		return ftrace_make_call(rec, ftrace_addr);
2702 
2703 	case FTRACE_UPDATE_MAKE_NOP:
2704 		ftrace_bug_type = FTRACE_BUG_NOP;
2705 		return ftrace_make_nop(NULL, rec, ftrace_old_addr);
2706 
2707 	case FTRACE_UPDATE_MODIFY_CALL:
2708 		ftrace_bug_type = FTRACE_BUG_UPDATE;
2709 		return ftrace_modify_call(rec, ftrace_old_addr, ftrace_addr);
2710 	}
2711 
2712 	return -1; /* unknown ftrace bug */
2713 }
2714 
ftrace_replace_code(int mod_flags)2715 void __weak ftrace_replace_code(int mod_flags)
2716 {
2717 	struct dyn_ftrace *rec;
2718 	struct ftrace_page *pg;
2719 	bool enable = mod_flags & FTRACE_MODIFY_ENABLE_FL;
2720 	int schedulable = mod_flags & FTRACE_MODIFY_MAY_SLEEP_FL;
2721 	int failed;
2722 
2723 	if (unlikely(ftrace_disabled))
2724 		return;
2725 
2726 	do_for_each_ftrace_rec(pg, rec) {
2727 
2728 		if (skip_record(rec))
2729 			continue;
2730 
2731 		failed = __ftrace_replace_code(rec, enable);
2732 		if (failed) {
2733 			ftrace_bug(failed, rec);
2734 			/* Stop processing */
2735 			return;
2736 		}
2737 		if (schedulable)
2738 			cond_resched();
2739 	} while_for_each_ftrace_rec();
2740 }
2741 
2742 struct ftrace_rec_iter {
2743 	struct ftrace_page	*pg;
2744 	int			index;
2745 };
2746 
2747 /**
2748  * ftrace_rec_iter_start - start up iterating over traced functions
2749  *
2750  * Returns: an iterator handle that is used to iterate over all
2751  * the records that represent address locations where functions
2752  * are traced.
2753  *
2754  * May return NULL if no records are available.
2755  */
ftrace_rec_iter_start(void)2756 struct ftrace_rec_iter *ftrace_rec_iter_start(void)
2757 {
2758 	/*
2759 	 * We only use a single iterator.
2760 	 * Protected by the ftrace_lock mutex.
2761 	 */
2762 	static struct ftrace_rec_iter ftrace_rec_iter;
2763 	struct ftrace_rec_iter *iter = &ftrace_rec_iter;
2764 
2765 	iter->pg = ftrace_pages_start;
2766 	iter->index = 0;
2767 
2768 	/* Could have empty pages */
2769 	while (iter->pg && !iter->pg->index)
2770 		iter->pg = iter->pg->next;
2771 
2772 	if (!iter->pg)
2773 		return NULL;
2774 
2775 	return iter;
2776 }
2777 
2778 /**
2779  * ftrace_rec_iter_next - get the next record to process.
2780  * @iter: The handle to the iterator.
2781  *
2782  * Returns: the next iterator after the given iterator @iter.
2783  */
ftrace_rec_iter_next(struct ftrace_rec_iter * iter)2784 struct ftrace_rec_iter *ftrace_rec_iter_next(struct ftrace_rec_iter *iter)
2785 {
2786 	iter->index++;
2787 
2788 	if (iter->index >= iter->pg->index) {
2789 		iter->pg = iter->pg->next;
2790 		iter->index = 0;
2791 
2792 		/* Could have empty pages */
2793 		while (iter->pg && !iter->pg->index)
2794 			iter->pg = iter->pg->next;
2795 	}
2796 
2797 	if (!iter->pg)
2798 		return NULL;
2799 
2800 	return iter;
2801 }
2802 
2803 /**
2804  * ftrace_rec_iter_record - get the record at the iterator location
2805  * @iter: The current iterator location
2806  *
2807  * Returns: the record that the current @iter is at.
2808  */
ftrace_rec_iter_record(struct ftrace_rec_iter * iter)2809 struct dyn_ftrace *ftrace_rec_iter_record(struct ftrace_rec_iter *iter)
2810 {
2811 	return &iter->pg->records[iter->index];
2812 }
2813 
2814 static int
ftrace_nop_initialize(struct module * mod,struct dyn_ftrace * rec)2815 ftrace_nop_initialize(struct module *mod, struct dyn_ftrace *rec)
2816 {
2817 	int ret;
2818 
2819 	if (unlikely(ftrace_disabled))
2820 		return 0;
2821 
2822 	ret = ftrace_init_nop(mod, rec);
2823 	if (ret) {
2824 		ftrace_bug_type = FTRACE_BUG_INIT;
2825 		ftrace_bug(ret, rec);
2826 		return 0;
2827 	}
2828 	return 1;
2829 }
2830 
2831 /*
2832  * archs can override this function if they must do something
2833  * before the modifying code is performed.
2834  */
ftrace_arch_code_modify_prepare(void)2835 void __weak ftrace_arch_code_modify_prepare(void)
2836 {
2837 }
2838 
2839 /*
2840  * archs can override this function if they must do something
2841  * after the modifying code is performed.
2842  */
ftrace_arch_code_modify_post_process(void)2843 void __weak ftrace_arch_code_modify_post_process(void)
2844 {
2845 }
2846 
update_ftrace_func(ftrace_func_t func)2847 static int update_ftrace_func(ftrace_func_t func)
2848 {
2849 	static ftrace_func_t save_func;
2850 
2851 	/* Avoid updating if it hasn't changed */
2852 	if (func == save_func)
2853 		return 0;
2854 
2855 	save_func = func;
2856 
2857 	return ftrace_update_ftrace_func(func);
2858 }
2859 
ftrace_modify_all_code(int command)2860 void ftrace_modify_all_code(int command)
2861 {
2862 	int update = command & FTRACE_UPDATE_TRACE_FUNC;
2863 	int mod_flags = 0;
2864 	int err = 0;
2865 
2866 	if (command & FTRACE_MAY_SLEEP)
2867 		mod_flags = FTRACE_MODIFY_MAY_SLEEP_FL;
2868 
2869 	/*
2870 	 * If the ftrace_caller calls a ftrace_ops func directly,
2871 	 * we need to make sure that it only traces functions it
2872 	 * expects to trace. When doing the switch of functions,
2873 	 * we need to update to the ftrace_ops_list_func first
2874 	 * before the transition between old and new calls are set,
2875 	 * as the ftrace_ops_list_func will check the ops hashes
2876 	 * to make sure the ops are having the right functions
2877 	 * traced.
2878 	 */
2879 	if (update) {
2880 		err = update_ftrace_func(ftrace_ops_list_func);
2881 		if (FTRACE_WARN_ON(err))
2882 			return;
2883 	}
2884 
2885 	if (command & FTRACE_UPDATE_CALLS)
2886 		ftrace_replace_code(mod_flags | FTRACE_MODIFY_ENABLE_FL);
2887 	else if (command & FTRACE_DISABLE_CALLS)
2888 		ftrace_replace_code(mod_flags);
2889 
2890 	if (update && ftrace_trace_function != ftrace_ops_list_func) {
2891 		function_trace_op = set_function_trace_op;
2892 		smp_wmb();
2893 		/* If irqs are disabled, we are in stop machine */
2894 		if (!irqs_disabled())
2895 			smp_call_function(ftrace_sync_ipi, NULL, 1);
2896 		err = update_ftrace_func(ftrace_trace_function);
2897 		if (FTRACE_WARN_ON(err))
2898 			return;
2899 	}
2900 
2901 	if (command & FTRACE_START_FUNC_RET)
2902 		err = ftrace_enable_ftrace_graph_caller();
2903 	else if (command & FTRACE_STOP_FUNC_RET)
2904 		err = ftrace_disable_ftrace_graph_caller();
2905 	FTRACE_WARN_ON(err);
2906 }
2907 
__ftrace_modify_code(void * data)2908 static int __ftrace_modify_code(void *data)
2909 {
2910 	int *command = data;
2911 
2912 	ftrace_modify_all_code(*command);
2913 
2914 	return 0;
2915 }
2916 
2917 /**
2918  * ftrace_run_stop_machine - go back to the stop machine method
2919  * @command: The command to tell ftrace what to do
2920  *
2921  * If an arch needs to fall back to the stop machine method, the
2922  * it can call this function.
2923  */
ftrace_run_stop_machine(int command)2924 void ftrace_run_stop_machine(int command)
2925 {
2926 	stop_machine(__ftrace_modify_code, &command, NULL);
2927 }
2928 
2929 /**
2930  * arch_ftrace_update_code - modify the code to trace or not trace
2931  * @command: The command that needs to be done
2932  *
2933  * Archs can override this function if it does not need to
2934  * run stop_machine() to modify code.
2935  */
arch_ftrace_update_code(int command)2936 void __weak arch_ftrace_update_code(int command)
2937 {
2938 	ftrace_run_stop_machine(command);
2939 }
2940 
ftrace_run_update_code(int command)2941 static void ftrace_run_update_code(int command)
2942 {
2943 	ftrace_arch_code_modify_prepare();
2944 
2945 	/*
2946 	 * By default we use stop_machine() to modify the code.
2947 	 * But archs can do what ever they want as long as it
2948 	 * is safe. The stop_machine() is the safest, but also
2949 	 * produces the most overhead.
2950 	 */
2951 	arch_ftrace_update_code(command);
2952 
2953 	ftrace_arch_code_modify_post_process();
2954 }
2955 
ftrace_run_modify_code(struct ftrace_ops * ops,int command,struct ftrace_ops_hash * old_hash)2956 static void ftrace_run_modify_code(struct ftrace_ops *ops, int command,
2957 				   struct ftrace_ops_hash *old_hash)
2958 {
2959 	ops->flags |= FTRACE_OPS_FL_MODIFYING;
2960 	ops->old_hash.filter_hash = old_hash->filter_hash;
2961 	ops->old_hash.notrace_hash = old_hash->notrace_hash;
2962 	ftrace_run_update_code(command);
2963 	ops->old_hash.filter_hash = NULL;
2964 	ops->old_hash.notrace_hash = NULL;
2965 	ops->flags &= ~FTRACE_OPS_FL_MODIFYING;
2966 }
2967 
2968 static ftrace_func_t saved_ftrace_func;
2969 static int ftrace_start_up;
2970 
arch_ftrace_trampoline_free(struct ftrace_ops * ops)2971 void __weak arch_ftrace_trampoline_free(struct ftrace_ops *ops)
2972 {
2973 }
2974 
2975 /* List of trace_ops that have allocated trampolines */
2976 static LIST_HEAD(ftrace_ops_trampoline_list);
2977 
ftrace_add_trampoline_to_kallsyms(struct ftrace_ops * ops)2978 static void ftrace_add_trampoline_to_kallsyms(struct ftrace_ops *ops)
2979 {
2980 	lockdep_assert_held(&ftrace_lock);
2981 	list_add_rcu(&ops->list, &ftrace_ops_trampoline_list);
2982 }
2983 
ftrace_remove_trampoline_from_kallsyms(struct ftrace_ops * ops)2984 static void ftrace_remove_trampoline_from_kallsyms(struct ftrace_ops *ops)
2985 {
2986 	lockdep_assert_held(&ftrace_lock);
2987 	list_del_rcu(&ops->list);
2988 	synchronize_rcu();
2989 }
2990 
2991 /*
2992  * "__builtin__ftrace" is used as a module name in /proc/kallsyms for symbols
2993  * for pages allocated for ftrace purposes, even though "__builtin__ftrace" is
2994  * not a module.
2995  */
2996 #define FTRACE_TRAMPOLINE_MOD "__builtin__ftrace"
2997 #define FTRACE_TRAMPOLINE_SYM "ftrace_trampoline"
2998 
ftrace_trampoline_free(struct ftrace_ops * ops)2999 static void ftrace_trampoline_free(struct ftrace_ops *ops)
3000 {
3001 	if (ops && (ops->flags & FTRACE_OPS_FL_ALLOC_TRAMP) &&
3002 	    ops->trampoline) {
3003 		/*
3004 		 * Record the text poke event before the ksymbol unregister
3005 		 * event.
3006 		 */
3007 		perf_event_text_poke((void *)ops->trampoline,
3008 				     (void *)ops->trampoline,
3009 				     ops->trampoline_size, NULL, 0);
3010 		perf_event_ksymbol(PERF_RECORD_KSYMBOL_TYPE_OOL,
3011 				   ops->trampoline, ops->trampoline_size,
3012 				   true, FTRACE_TRAMPOLINE_SYM);
3013 		/* Remove from kallsyms after the perf events */
3014 		ftrace_remove_trampoline_from_kallsyms(ops);
3015 	}
3016 
3017 	arch_ftrace_trampoline_free(ops);
3018 }
3019 
ftrace_startup_enable(int command)3020 static void ftrace_startup_enable(int command)
3021 {
3022 	if (saved_ftrace_func != ftrace_trace_function) {
3023 		saved_ftrace_func = ftrace_trace_function;
3024 		command |= FTRACE_UPDATE_TRACE_FUNC;
3025 	}
3026 
3027 	if (!command || !ftrace_enabled)
3028 		return;
3029 
3030 	ftrace_run_update_code(command);
3031 }
3032 
ftrace_startup_all(int command)3033 static void ftrace_startup_all(int command)
3034 {
3035 	update_all_ops = true;
3036 	ftrace_startup_enable(command);
3037 	update_all_ops = false;
3038 }
3039 
ftrace_startup(struct ftrace_ops * ops,int command)3040 int ftrace_startup(struct ftrace_ops *ops, int command)
3041 {
3042 	int ret;
3043 
3044 	if (unlikely(ftrace_disabled))
3045 		return -ENODEV;
3046 
3047 	ret = __register_ftrace_function(ops);
3048 	if (ret)
3049 		return ret;
3050 
3051 	ftrace_start_up++;
3052 
3053 	/*
3054 	 * Note that ftrace probes uses this to start up
3055 	 * and modify functions it will probe. But we still
3056 	 * set the ADDING flag for modification, as probes
3057 	 * do not have trampolines. If they add them in the
3058 	 * future, then the probes will need to distinguish
3059 	 * between adding and updating probes.
3060 	 */
3061 	ops->flags |= FTRACE_OPS_FL_ENABLED | FTRACE_OPS_FL_ADDING;
3062 
3063 	ret = ftrace_hash_ipmodify_enable(ops);
3064 	if (ret < 0) {
3065 		/* Rollback registration process */
3066 		__unregister_ftrace_function(ops);
3067 		ftrace_start_up--;
3068 		ops->flags &= ~FTRACE_OPS_FL_ENABLED;
3069 		if (ops->flags & FTRACE_OPS_FL_DYNAMIC)
3070 			ftrace_trampoline_free(ops);
3071 		return ret;
3072 	}
3073 
3074 	if (ftrace_hash_rec_enable(ops))
3075 		command |= FTRACE_UPDATE_CALLS;
3076 
3077 	ftrace_startup_enable(command);
3078 
3079 	/*
3080 	 * If ftrace is in an undefined state, we just remove ops from list
3081 	 * to prevent the NULL pointer, instead of totally rolling it back and
3082 	 * free trampoline, because those actions could cause further damage.
3083 	 */
3084 	if (unlikely(ftrace_disabled)) {
3085 		__unregister_ftrace_function(ops);
3086 		return -ENODEV;
3087 	}
3088 
3089 	ops->flags &= ~FTRACE_OPS_FL_ADDING;
3090 
3091 	return 0;
3092 }
3093 
ftrace_shutdown(struct ftrace_ops * ops,int command)3094 int ftrace_shutdown(struct ftrace_ops *ops, int command)
3095 {
3096 	int ret;
3097 
3098 	if (unlikely(ftrace_disabled))
3099 		return -ENODEV;
3100 
3101 	ret = __unregister_ftrace_function(ops);
3102 	if (ret)
3103 		return ret;
3104 
3105 	ftrace_start_up--;
3106 	/*
3107 	 * Just warn in case of unbalance, no need to kill ftrace, it's not
3108 	 * critical but the ftrace_call callers may be never nopped again after
3109 	 * further ftrace uses.
3110 	 */
3111 	WARN_ON_ONCE(ftrace_start_up < 0);
3112 
3113 	/* Disabling ipmodify never fails */
3114 	ftrace_hash_ipmodify_disable(ops);
3115 
3116 	if (ftrace_hash_rec_disable(ops))
3117 		command |= FTRACE_UPDATE_CALLS;
3118 
3119 	ops->flags &= ~FTRACE_OPS_FL_ENABLED;
3120 
3121 	if (saved_ftrace_func != ftrace_trace_function) {
3122 		saved_ftrace_func = ftrace_trace_function;
3123 		command |= FTRACE_UPDATE_TRACE_FUNC;
3124 	}
3125 
3126 	if (!command || !ftrace_enabled)
3127 		goto out;
3128 
3129 	/*
3130 	 * If the ops uses a trampoline, then it needs to be
3131 	 * tested first on update.
3132 	 */
3133 	ops->flags |= FTRACE_OPS_FL_REMOVING;
3134 	removed_ops = ops;
3135 
3136 	/* The trampoline logic checks the old hashes */
3137 	ops->old_hash.filter_hash = ops->func_hash->filter_hash;
3138 	ops->old_hash.notrace_hash = ops->func_hash->notrace_hash;
3139 
3140 	ftrace_run_update_code(command);
3141 
3142 	/*
3143 	 * If there's no more ops registered with ftrace, run a
3144 	 * sanity check to make sure all rec flags are cleared.
3145 	 */
3146 	if (rcu_dereference_protected(ftrace_ops_list,
3147 			lockdep_is_held(&ftrace_lock)) == &ftrace_list_end) {
3148 		struct ftrace_page *pg;
3149 		struct dyn_ftrace *rec;
3150 
3151 		do_for_each_ftrace_rec(pg, rec) {
3152 			if (FTRACE_WARN_ON_ONCE(rec->flags & ~FTRACE_NOCLEAR_FLAGS))
3153 				pr_warn("  %pS flags:%lx\n",
3154 					(void *)rec->ip, rec->flags);
3155 		} while_for_each_ftrace_rec();
3156 	}
3157 
3158 	ops->old_hash.filter_hash = NULL;
3159 	ops->old_hash.notrace_hash = NULL;
3160 
3161 	removed_ops = NULL;
3162 	ops->flags &= ~FTRACE_OPS_FL_REMOVING;
3163 
3164 out:
3165 	/*
3166 	 * Dynamic ops may be freed, we must make sure that all
3167 	 * callers are done before leaving this function.
3168 	 */
3169 	if (ops->flags & FTRACE_OPS_FL_DYNAMIC) {
3170 		/*
3171 		 * We need to do a hard force of sched synchronization.
3172 		 * This is because we use preempt_disable() to do RCU, but
3173 		 * the function tracers can be called where RCU is not watching
3174 		 * (like before user_exit()). We can not rely on the RCU
3175 		 * infrastructure to do the synchronization, thus we must do it
3176 		 * ourselves.
3177 		 */
3178 		synchronize_rcu_tasks_rude();
3179 
3180 		/*
3181 		 * When the kernel is preemptive, tasks can be preempted
3182 		 * while on a ftrace trampoline. Just scheduling a task on
3183 		 * a CPU is not good enough to flush them. Calling
3184 		 * synchronize_rcu_tasks() will wait for those tasks to
3185 		 * execute and either schedule voluntarily or enter user space.
3186 		 */
3187 		synchronize_rcu_tasks();
3188 
3189 		ftrace_trampoline_free(ops);
3190 	}
3191 
3192 	return 0;
3193 }
3194 
3195 /* Simply make a copy of @src and return it */
copy_hash(struct ftrace_hash * src)3196 static struct ftrace_hash *copy_hash(struct ftrace_hash *src)
3197 {
3198 	if (ftrace_hash_empty(src))
3199 		return EMPTY_HASH;
3200 
3201 	return alloc_and_copy_ftrace_hash(src->size_bits, src);
3202 }
3203 
3204 /*
3205  * Append @new_hash entries to @hash:
3206  *
3207  *  If @hash is the EMPTY_HASH then it traces all functions and nothing
3208  *  needs to be done.
3209  *
3210  *  If @new_hash is the EMPTY_HASH, then make *hash the EMPTY_HASH so
3211  *  that it traces everything.
3212  *
3213  *  Otherwise, go through all of @new_hash and add anything that @hash
3214  *  doesn't already have, to @hash.
3215  *
3216  *  The filter_hash updates uses just the append_hash() function
3217  *  and the notrace_hash does not.
3218  */
append_hash(struct ftrace_hash ** hash,struct ftrace_hash * new_hash,int size_bits)3219 static int append_hash(struct ftrace_hash **hash, struct ftrace_hash *new_hash,
3220 		       int size_bits)
3221 {
3222 	struct ftrace_func_entry *entry;
3223 	int size;
3224 	int i;
3225 
3226 	if (*hash) {
3227 		/* An empty hash does everything */
3228 		if (ftrace_hash_empty(*hash))
3229 			return 0;
3230 	} else {
3231 		*hash = alloc_ftrace_hash(size_bits);
3232 		if (!*hash)
3233 			return -ENOMEM;
3234 	}
3235 
3236 	/* If new_hash has everything make hash have everything */
3237 	if (ftrace_hash_empty(new_hash)) {
3238 		free_ftrace_hash(*hash);
3239 		*hash = EMPTY_HASH;
3240 		return 0;
3241 	}
3242 
3243 	size = 1 << new_hash->size_bits;
3244 	for (i = 0; i < size; i++) {
3245 		hlist_for_each_entry(entry, &new_hash->buckets[i], hlist) {
3246 			/* Only add if not already in hash */
3247 			if (!__ftrace_lookup_ip(*hash, entry->ip) &&
3248 			    add_hash_entry(*hash, entry->ip) == NULL)
3249 				return -ENOMEM;
3250 		}
3251 	}
3252 	return 0;
3253 }
3254 
3255 /*
3256  * Add to @hash only those that are in both @new_hash1 and @new_hash2
3257  *
3258  * The notrace_hash updates uses just the intersect_hash() function
3259  * and the filter_hash does not.
3260  */
intersect_hash(struct ftrace_hash ** hash,struct ftrace_hash * new_hash1,struct ftrace_hash * new_hash2)3261 static int intersect_hash(struct ftrace_hash **hash, struct ftrace_hash *new_hash1,
3262 			  struct ftrace_hash *new_hash2)
3263 {
3264 	struct ftrace_func_entry *entry;
3265 	int size;
3266 	int i;
3267 
3268 	/*
3269 	 * If new_hash1 or new_hash2 is the EMPTY_HASH then make the hash
3270 	 * empty as well as empty for notrace means none are notraced.
3271 	 */
3272 	if (ftrace_hash_empty(new_hash1) || ftrace_hash_empty(new_hash2)) {
3273 		free_ftrace_hash(*hash);
3274 		*hash = EMPTY_HASH;
3275 		return 0;
3276 	}
3277 
3278 	size = 1 << new_hash1->size_bits;
3279 	for (i = 0; i < size; i++) {
3280 		hlist_for_each_entry(entry, &new_hash1->buckets[i], hlist) {
3281 			/* Only add if in both @new_hash1 and @new_hash2 */
3282 			if (__ftrace_lookup_ip(new_hash2, entry->ip) &&
3283 			    add_hash_entry(*hash, entry->ip) == NULL)
3284 				return -ENOMEM;
3285 		}
3286 	}
3287 	/* If nothing intersects, make it the empty set */
3288 	if (ftrace_hash_empty(*hash)) {
3289 		free_ftrace_hash(*hash);
3290 		*hash = EMPTY_HASH;
3291 	}
3292 	return 0;
3293 }
3294 
3295 /* Return a new hash that has a union of all @ops->filter_hash entries */
append_hashes(struct ftrace_ops * ops)3296 static struct ftrace_hash *append_hashes(struct ftrace_ops *ops)
3297 {
3298 	struct ftrace_hash *new_hash = NULL;
3299 	struct ftrace_ops *subops;
3300 	int size_bits;
3301 	int ret;
3302 
3303 	if (ops->func_hash->filter_hash)
3304 		size_bits = ops->func_hash->filter_hash->size_bits;
3305 	else
3306 		size_bits = FTRACE_HASH_DEFAULT_BITS;
3307 
3308 	list_for_each_entry(subops, &ops->subop_list, list) {
3309 		ret = append_hash(&new_hash, subops->func_hash->filter_hash, size_bits);
3310 		if (ret < 0) {
3311 			free_ftrace_hash(new_hash);
3312 			return NULL;
3313 		}
3314 		/* Nothing more to do if new_hash is empty */
3315 		if (ftrace_hash_empty(new_hash))
3316 			break;
3317 	}
3318 	/* Can't return NULL as that means this failed */
3319 	return new_hash ? : EMPTY_HASH;
3320 }
3321 
3322 /* Make @ops trace evenything except what all its subops do not trace */
intersect_hashes(struct ftrace_ops * ops)3323 static struct ftrace_hash *intersect_hashes(struct ftrace_ops *ops)
3324 {
3325 	struct ftrace_hash *new_hash = NULL;
3326 	struct ftrace_ops *subops;
3327 	int size_bits;
3328 	int ret;
3329 
3330 	list_for_each_entry(subops, &ops->subop_list, list) {
3331 		struct ftrace_hash *next_hash;
3332 
3333 		if (!new_hash) {
3334 			size_bits = subops->func_hash->notrace_hash->size_bits;
3335 			new_hash = alloc_and_copy_ftrace_hash(size_bits, ops->func_hash->notrace_hash);
3336 			if (!new_hash)
3337 				return NULL;
3338 			continue;
3339 		}
3340 		size_bits = new_hash->size_bits;
3341 		next_hash = new_hash;
3342 		new_hash = alloc_ftrace_hash(size_bits);
3343 		ret = intersect_hash(&new_hash, next_hash, subops->func_hash->notrace_hash);
3344 		free_ftrace_hash(next_hash);
3345 		if (ret < 0) {
3346 			free_ftrace_hash(new_hash);
3347 			return NULL;
3348 		}
3349 		/* Nothing more to do if new_hash is empty */
3350 		if (ftrace_hash_empty(new_hash))
3351 			break;
3352 	}
3353 	return new_hash;
3354 }
3355 
ops_equal(struct ftrace_hash * A,struct ftrace_hash * B)3356 static bool ops_equal(struct ftrace_hash *A, struct ftrace_hash *B)
3357 {
3358 	struct ftrace_func_entry *entry;
3359 	int size;
3360 	int i;
3361 
3362 	if (ftrace_hash_empty(A))
3363 		return ftrace_hash_empty(B);
3364 
3365 	if (ftrace_hash_empty(B))
3366 		return ftrace_hash_empty(A);
3367 
3368 	if (A->count != B->count)
3369 		return false;
3370 
3371 	size = 1 << A->size_bits;
3372 	for (i = 0; i < size; i++) {
3373 		hlist_for_each_entry(entry, &A->buckets[i], hlist) {
3374 			if (!__ftrace_lookup_ip(B, entry->ip))
3375 				return false;
3376 		}
3377 	}
3378 
3379 	return true;
3380 }
3381 
3382 static void ftrace_ops_update_code(struct ftrace_ops *ops,
3383 				   struct ftrace_ops_hash *old_hash);
3384 
__ftrace_hash_move_and_update_ops(struct ftrace_ops * ops,struct ftrace_hash ** orig_hash,struct ftrace_hash * hash,int enable)3385 static int __ftrace_hash_move_and_update_ops(struct ftrace_ops *ops,
3386 					     struct ftrace_hash **orig_hash,
3387 					     struct ftrace_hash *hash,
3388 					     int enable)
3389 {
3390 	struct ftrace_ops_hash old_hash_ops;
3391 	struct ftrace_hash *old_hash;
3392 	int ret;
3393 
3394 	old_hash = *orig_hash;
3395 	old_hash_ops.filter_hash = ops->func_hash->filter_hash;
3396 	old_hash_ops.notrace_hash = ops->func_hash->notrace_hash;
3397 	ret = ftrace_hash_move(ops, enable, orig_hash, hash);
3398 	if (!ret) {
3399 		ftrace_ops_update_code(ops, &old_hash_ops);
3400 		free_ftrace_hash_rcu(old_hash);
3401 	}
3402 	return ret;
3403 }
3404 
ftrace_update_ops(struct ftrace_ops * ops,struct ftrace_hash * filter_hash,struct ftrace_hash * notrace_hash)3405 static int ftrace_update_ops(struct ftrace_ops *ops, struct ftrace_hash *filter_hash,
3406 			     struct ftrace_hash *notrace_hash)
3407 {
3408 	int ret;
3409 
3410 	if (!ops_equal(filter_hash, ops->func_hash->filter_hash)) {
3411 		ret = __ftrace_hash_move_and_update_ops(ops, &ops->func_hash->filter_hash,
3412 							filter_hash, 1);
3413 		if (ret < 0)
3414 			return ret;
3415 	}
3416 
3417 	if (!ops_equal(notrace_hash, ops->func_hash->notrace_hash)) {
3418 		ret = __ftrace_hash_move_and_update_ops(ops, &ops->func_hash->notrace_hash,
3419 							notrace_hash, 0);
3420 		if (ret < 0)
3421 			return ret;
3422 	}
3423 
3424 	return 0;
3425 }
3426 
3427 /**
3428  * ftrace_startup_subops - enable tracing for subops of an ops
3429  * @ops: Manager ops (used to pick all the functions of its subops)
3430  * @subops: A new ops to add to @ops
3431  * @command: Extra commands to use to enable tracing
3432  *
3433  * The @ops is a manager @ops that has the filter that includes all the functions
3434  * that its list of subops are tracing. Adding a new @subops will add the
3435  * functions of @subops to @ops.
3436  */
ftrace_startup_subops(struct ftrace_ops * ops,struct ftrace_ops * subops,int command)3437 int ftrace_startup_subops(struct ftrace_ops *ops, struct ftrace_ops *subops, int command)
3438 {
3439 	struct ftrace_hash *filter_hash;
3440 	struct ftrace_hash *notrace_hash;
3441 	struct ftrace_hash *save_filter_hash;
3442 	struct ftrace_hash *save_notrace_hash;
3443 	int size_bits;
3444 	int ret;
3445 
3446 	if (unlikely(ftrace_disabled))
3447 		return -ENODEV;
3448 
3449 	ftrace_ops_init(ops);
3450 	ftrace_ops_init(subops);
3451 
3452 	if (WARN_ON_ONCE(subops->flags & FTRACE_OPS_FL_ENABLED))
3453 		return -EBUSY;
3454 
3455 	/* Make everything canonical (Just in case!) */
3456 	if (!ops->func_hash->filter_hash)
3457 		ops->func_hash->filter_hash = EMPTY_HASH;
3458 	if (!ops->func_hash->notrace_hash)
3459 		ops->func_hash->notrace_hash = EMPTY_HASH;
3460 	if (!subops->func_hash->filter_hash)
3461 		subops->func_hash->filter_hash = EMPTY_HASH;
3462 	if (!subops->func_hash->notrace_hash)
3463 		subops->func_hash->notrace_hash = EMPTY_HASH;
3464 
3465 	/* For the first subops to ops just enable it normally */
3466 	if (list_empty(&ops->subop_list)) {
3467 		/* Just use the subops hashes */
3468 		filter_hash = copy_hash(subops->func_hash->filter_hash);
3469 		notrace_hash = copy_hash(subops->func_hash->notrace_hash);
3470 		if (!filter_hash || !notrace_hash) {
3471 			free_ftrace_hash(filter_hash);
3472 			free_ftrace_hash(notrace_hash);
3473 			return -ENOMEM;
3474 		}
3475 
3476 		save_filter_hash = ops->func_hash->filter_hash;
3477 		save_notrace_hash = ops->func_hash->notrace_hash;
3478 
3479 		ops->func_hash->filter_hash = filter_hash;
3480 		ops->func_hash->notrace_hash = notrace_hash;
3481 		list_add(&subops->list, &ops->subop_list);
3482 		ret = ftrace_startup(ops, command);
3483 		if (ret < 0) {
3484 			list_del(&subops->list);
3485 			ops->func_hash->filter_hash = save_filter_hash;
3486 			ops->func_hash->notrace_hash = save_notrace_hash;
3487 			free_ftrace_hash(filter_hash);
3488 			free_ftrace_hash(notrace_hash);
3489 		} else {
3490 			free_ftrace_hash(save_filter_hash);
3491 			free_ftrace_hash(save_notrace_hash);
3492 			subops->flags |= FTRACE_OPS_FL_ENABLED | FTRACE_OPS_FL_SUBOP;
3493 			subops->managed = ops;
3494 		}
3495 		return ret;
3496 	}
3497 
3498 	/*
3499 	 * Here there's already something attached. Here are the rules:
3500 	 *   o If either filter_hash is empty then the final stays empty
3501 	 *      o Otherwise, the final is a superset of both hashes
3502 	 *   o If either notrace_hash is empty then the final stays empty
3503 	 *      o Otherwise, the final is an intersection between the hashes
3504 	 */
3505 	if (ftrace_hash_empty(ops->func_hash->filter_hash) ||
3506 	    ftrace_hash_empty(subops->func_hash->filter_hash)) {
3507 		filter_hash = EMPTY_HASH;
3508 	} else {
3509 		size_bits = max(ops->func_hash->filter_hash->size_bits,
3510 				subops->func_hash->filter_hash->size_bits);
3511 		filter_hash = alloc_and_copy_ftrace_hash(size_bits, ops->func_hash->filter_hash);
3512 		if (!filter_hash)
3513 			return -ENOMEM;
3514 		ret = append_hash(&filter_hash, subops->func_hash->filter_hash,
3515 				  size_bits);
3516 		if (ret < 0) {
3517 			free_ftrace_hash(filter_hash);
3518 			return ret;
3519 		}
3520 	}
3521 
3522 	if (ftrace_hash_empty(ops->func_hash->notrace_hash) ||
3523 	    ftrace_hash_empty(subops->func_hash->notrace_hash)) {
3524 		notrace_hash = EMPTY_HASH;
3525 	} else {
3526 		size_bits = max(ops->func_hash->notrace_hash->size_bits,
3527 				subops->func_hash->notrace_hash->size_bits);
3528 		notrace_hash = alloc_ftrace_hash(size_bits);
3529 		if (!notrace_hash) {
3530 			free_ftrace_hash(filter_hash);
3531 			return -ENOMEM;
3532 		}
3533 
3534 		ret = intersect_hash(&notrace_hash, ops->func_hash->notrace_hash,
3535 				     subops->func_hash->notrace_hash);
3536 		if (ret < 0) {
3537 			free_ftrace_hash(filter_hash);
3538 			free_ftrace_hash(notrace_hash);
3539 			return ret;
3540 		}
3541 	}
3542 
3543 	list_add(&subops->list, &ops->subop_list);
3544 
3545 	ret = ftrace_update_ops(ops, filter_hash, notrace_hash);
3546 	free_ftrace_hash(filter_hash);
3547 	free_ftrace_hash(notrace_hash);
3548 	if (ret < 0) {
3549 		list_del(&subops->list);
3550 	} else {
3551 		subops->flags |= FTRACE_OPS_FL_ENABLED | FTRACE_OPS_FL_SUBOP;
3552 		subops->managed = ops;
3553 	}
3554 	return ret;
3555 }
3556 
3557 /**
3558  * ftrace_shutdown_subops - Remove a subops from a manager ops
3559  * @ops: A manager ops to remove @subops from
3560  * @subops: The subops to remove from @ops
3561  * @command: Any extra command flags to add to modifying the text
3562  *
3563  * Removes the functions being traced by the @subops from @ops. Note, it
3564  * will not affect functions that are being traced by other subops that
3565  * still exist in @ops.
3566  *
3567  * If the last subops is removed from @ops, then @ops is shutdown normally.
3568  */
ftrace_shutdown_subops(struct ftrace_ops * ops,struct ftrace_ops * subops,int command)3569 int ftrace_shutdown_subops(struct ftrace_ops *ops, struct ftrace_ops *subops, int command)
3570 {
3571 	struct ftrace_hash *filter_hash;
3572 	struct ftrace_hash *notrace_hash;
3573 	int ret;
3574 
3575 	if (unlikely(ftrace_disabled))
3576 		return -ENODEV;
3577 
3578 	if (WARN_ON_ONCE(!(subops->flags & FTRACE_OPS_FL_ENABLED)))
3579 		return -EINVAL;
3580 
3581 	list_del(&subops->list);
3582 
3583 	if (list_empty(&ops->subop_list)) {
3584 		/* Last one, just disable the current ops */
3585 
3586 		ret = ftrace_shutdown(ops, command);
3587 		if (ret < 0) {
3588 			list_add(&subops->list, &ops->subop_list);
3589 			return ret;
3590 		}
3591 
3592 		subops->flags &= ~FTRACE_OPS_FL_ENABLED;
3593 
3594 		free_ftrace_hash(ops->func_hash->filter_hash);
3595 		free_ftrace_hash(ops->func_hash->notrace_hash);
3596 		ops->func_hash->filter_hash = EMPTY_HASH;
3597 		ops->func_hash->notrace_hash = EMPTY_HASH;
3598 		subops->flags &= ~(FTRACE_OPS_FL_ENABLED | FTRACE_OPS_FL_SUBOP);
3599 		subops->managed = NULL;
3600 
3601 		return 0;
3602 	}
3603 
3604 	/* Rebuild the hashes without subops */
3605 	filter_hash = append_hashes(ops);
3606 	notrace_hash = intersect_hashes(ops);
3607 	if (!filter_hash || !notrace_hash) {
3608 		free_ftrace_hash(filter_hash);
3609 		free_ftrace_hash(notrace_hash);
3610 		list_add(&subops->list, &ops->subop_list);
3611 		return -ENOMEM;
3612 	}
3613 
3614 	ret = ftrace_update_ops(ops, filter_hash, notrace_hash);
3615 	if (ret < 0) {
3616 		list_add(&subops->list, &ops->subop_list);
3617 	} else {
3618 		subops->flags &= ~(FTRACE_OPS_FL_ENABLED | FTRACE_OPS_FL_SUBOP);
3619 		subops->managed = NULL;
3620 	}
3621 	free_ftrace_hash(filter_hash);
3622 	free_ftrace_hash(notrace_hash);
3623 	return ret;
3624 }
3625 
ftrace_hash_move_and_update_subops(struct ftrace_ops * subops,struct ftrace_hash ** orig_subhash,struct ftrace_hash * hash,int enable)3626 static int ftrace_hash_move_and_update_subops(struct ftrace_ops *subops,
3627 					      struct ftrace_hash **orig_subhash,
3628 					      struct ftrace_hash *hash,
3629 					      int enable)
3630 {
3631 	struct ftrace_ops *ops = subops->managed;
3632 	struct ftrace_hash **orig_hash;
3633 	struct ftrace_hash *save_hash;
3634 	struct ftrace_hash *new_hash;
3635 	int ret;
3636 
3637 	/* Manager ops can not be subops (yet) */
3638 	if (WARN_ON_ONCE(!ops || ops->flags & FTRACE_OPS_FL_SUBOP))
3639 		return -EINVAL;
3640 
3641 	/* Move the new hash over to the subops hash */
3642 	save_hash = *orig_subhash;
3643 	*orig_subhash = __ftrace_hash_move(hash);
3644 	if (!*orig_subhash) {
3645 		*orig_subhash = save_hash;
3646 		return -ENOMEM;
3647 	}
3648 
3649 	/* Create a new_hash to hold the ops new functions */
3650 	if (enable) {
3651 		orig_hash = &ops->func_hash->filter_hash;
3652 		new_hash = append_hashes(ops);
3653 	} else {
3654 		orig_hash = &ops->func_hash->notrace_hash;
3655 		new_hash = intersect_hashes(ops);
3656 	}
3657 
3658 	/* Move the hash over to the new hash */
3659 	ret = __ftrace_hash_move_and_update_ops(ops, orig_hash, new_hash, enable);
3660 
3661 	free_ftrace_hash(new_hash);
3662 
3663 	if (ret) {
3664 		/* Put back the original hash */
3665 		free_ftrace_hash_rcu(*orig_subhash);
3666 		*orig_subhash = save_hash;
3667 	} else {
3668 		free_ftrace_hash_rcu(save_hash);
3669 	}
3670 	return ret;
3671 }
3672 
3673 
3674 static u64		ftrace_update_time;
3675 unsigned long		ftrace_update_tot_cnt;
3676 unsigned long		ftrace_number_of_pages;
3677 unsigned long		ftrace_number_of_groups;
3678 
ops_traces_mod(struct ftrace_ops * ops)3679 static inline int ops_traces_mod(struct ftrace_ops *ops)
3680 {
3681 	/*
3682 	 * Filter_hash being empty will default to trace module.
3683 	 * But notrace hash requires a test of individual module functions.
3684 	 */
3685 	return ftrace_hash_empty(ops->func_hash->filter_hash) &&
3686 		ftrace_hash_empty(ops->func_hash->notrace_hash);
3687 }
3688 
ftrace_update_code(struct module * mod,struct ftrace_page * new_pgs)3689 static int ftrace_update_code(struct module *mod, struct ftrace_page *new_pgs)
3690 {
3691 	bool init_nop = ftrace_need_init_nop();
3692 	struct ftrace_page *pg;
3693 	struct dyn_ftrace *p;
3694 	u64 start, stop;
3695 	unsigned long update_cnt = 0;
3696 	unsigned long rec_flags = 0;
3697 	int i;
3698 
3699 	start = ftrace_now(raw_smp_processor_id());
3700 
3701 	/*
3702 	 * When a module is loaded, this function is called to convert
3703 	 * the calls to mcount in its text to nops, and also to create
3704 	 * an entry in the ftrace data. Now, if ftrace is activated
3705 	 * after this call, but before the module sets its text to
3706 	 * read-only, the modification of enabling ftrace can fail if
3707 	 * the read-only is done while ftrace is converting the calls.
3708 	 * To prevent this, the module's records are set as disabled
3709 	 * and will be enabled after the call to set the module's text
3710 	 * to read-only.
3711 	 */
3712 	if (mod)
3713 		rec_flags |= FTRACE_FL_DISABLED;
3714 
3715 	for (pg = new_pgs; pg; pg = pg->next) {
3716 
3717 		for (i = 0; i < pg->index; i++) {
3718 
3719 			/* If something went wrong, bail without enabling anything */
3720 			if (unlikely(ftrace_disabled))
3721 				return -1;
3722 
3723 			p = &pg->records[i];
3724 			p->flags = rec_flags;
3725 
3726 			/*
3727 			 * Do the initial record conversion from mcount jump
3728 			 * to the NOP instructions.
3729 			 */
3730 			if (init_nop && !ftrace_nop_initialize(mod, p))
3731 				break;
3732 
3733 			update_cnt++;
3734 		}
3735 	}
3736 
3737 	stop = ftrace_now(raw_smp_processor_id());
3738 	ftrace_update_time = stop - start;
3739 	ftrace_update_tot_cnt += update_cnt;
3740 
3741 	return 0;
3742 }
3743 
ftrace_allocate_records(struct ftrace_page * pg,int count)3744 static int ftrace_allocate_records(struct ftrace_page *pg, int count)
3745 {
3746 	int order;
3747 	int pages;
3748 	int cnt;
3749 
3750 	if (WARN_ON(!count))
3751 		return -EINVAL;
3752 
3753 	/* We want to fill as much as possible, with no empty pages */
3754 	pages = DIV_ROUND_UP(count, ENTRIES_PER_PAGE);
3755 	order = fls(pages) - 1;
3756 
3757  again:
3758 	pg->records = (void *)__get_free_pages(GFP_KERNEL | __GFP_ZERO, order);
3759 
3760 	if (!pg->records) {
3761 		/* if we can't allocate this size, try something smaller */
3762 		if (!order)
3763 			return -ENOMEM;
3764 		order--;
3765 		goto again;
3766 	}
3767 
3768 	ftrace_number_of_pages += 1 << order;
3769 	ftrace_number_of_groups++;
3770 
3771 	cnt = (PAGE_SIZE << order) / ENTRY_SIZE;
3772 	pg->order = order;
3773 
3774 	if (cnt > count)
3775 		cnt = count;
3776 
3777 	return cnt;
3778 }
3779 
ftrace_free_pages(struct ftrace_page * pages)3780 static void ftrace_free_pages(struct ftrace_page *pages)
3781 {
3782 	struct ftrace_page *pg = pages;
3783 
3784 	while (pg) {
3785 		if (pg->records) {
3786 			free_pages((unsigned long)pg->records, pg->order);
3787 			ftrace_number_of_pages -= 1 << pg->order;
3788 		}
3789 		pages = pg->next;
3790 		kfree(pg);
3791 		pg = pages;
3792 		ftrace_number_of_groups--;
3793 	}
3794 }
3795 
3796 static struct ftrace_page *
ftrace_allocate_pages(unsigned long num_to_init)3797 ftrace_allocate_pages(unsigned long num_to_init)
3798 {
3799 	struct ftrace_page *start_pg;
3800 	struct ftrace_page *pg;
3801 	int cnt;
3802 
3803 	if (!num_to_init)
3804 		return NULL;
3805 
3806 	start_pg = pg = kzalloc(sizeof(*pg), GFP_KERNEL);
3807 	if (!pg)
3808 		return NULL;
3809 
3810 	/*
3811 	 * Try to allocate as much as possible in one continues
3812 	 * location that fills in all of the space. We want to
3813 	 * waste as little space as possible.
3814 	 */
3815 	for (;;) {
3816 		cnt = ftrace_allocate_records(pg, num_to_init);
3817 		if (cnt < 0)
3818 			goto free_pages;
3819 
3820 		num_to_init -= cnt;
3821 		if (!num_to_init)
3822 			break;
3823 
3824 		pg->next = kzalloc(sizeof(*pg), GFP_KERNEL);
3825 		if (!pg->next)
3826 			goto free_pages;
3827 
3828 		pg = pg->next;
3829 	}
3830 
3831 	return start_pg;
3832 
3833  free_pages:
3834 	ftrace_free_pages(start_pg);
3835 	pr_info("ftrace: FAILED to allocate memory for functions\n");
3836 	return NULL;
3837 }
3838 
3839 #define FTRACE_BUFF_MAX (KSYM_SYMBOL_LEN+4) /* room for wildcards */
3840 
3841 struct ftrace_iterator {
3842 	loff_t				pos;
3843 	loff_t				func_pos;
3844 	loff_t				mod_pos;
3845 	struct ftrace_page		*pg;
3846 	struct dyn_ftrace		*func;
3847 	struct ftrace_func_probe	*probe;
3848 	struct ftrace_func_entry	*probe_entry;
3849 	struct trace_parser		parser;
3850 	struct ftrace_hash		*hash;
3851 	struct ftrace_ops		*ops;
3852 	struct trace_array		*tr;
3853 	struct list_head		*mod_list;
3854 	int				pidx;
3855 	int				idx;
3856 	unsigned			flags;
3857 };
3858 
3859 static void *
t_probe_next(struct seq_file * m,loff_t * pos)3860 t_probe_next(struct seq_file *m, loff_t *pos)
3861 {
3862 	struct ftrace_iterator *iter = m->private;
3863 	struct trace_array *tr = iter->ops->private;
3864 	struct list_head *func_probes;
3865 	struct ftrace_hash *hash;
3866 	struct list_head *next;
3867 	struct hlist_node *hnd = NULL;
3868 	struct hlist_head *hhd;
3869 	int size;
3870 
3871 	(*pos)++;
3872 	iter->pos = *pos;
3873 
3874 	if (!tr)
3875 		return NULL;
3876 
3877 	func_probes = &tr->func_probes;
3878 	if (list_empty(func_probes))
3879 		return NULL;
3880 
3881 	if (!iter->probe) {
3882 		next = func_probes->next;
3883 		iter->probe = list_entry(next, struct ftrace_func_probe, list);
3884 	}
3885 
3886 	if (iter->probe_entry)
3887 		hnd = &iter->probe_entry->hlist;
3888 
3889 	hash = iter->probe->ops.func_hash->filter_hash;
3890 
3891 	/*
3892 	 * A probe being registered may temporarily have an empty hash
3893 	 * and it's at the end of the func_probes list.
3894 	 */
3895 	if (!hash || hash == EMPTY_HASH)
3896 		return NULL;
3897 
3898 	size = 1 << hash->size_bits;
3899 
3900  retry:
3901 	if (iter->pidx >= size) {
3902 		if (iter->probe->list.next == func_probes)
3903 			return NULL;
3904 		next = iter->probe->list.next;
3905 		iter->probe = list_entry(next, struct ftrace_func_probe, list);
3906 		hash = iter->probe->ops.func_hash->filter_hash;
3907 		size = 1 << hash->size_bits;
3908 		iter->pidx = 0;
3909 	}
3910 
3911 	hhd = &hash->buckets[iter->pidx];
3912 
3913 	if (hlist_empty(hhd)) {
3914 		iter->pidx++;
3915 		hnd = NULL;
3916 		goto retry;
3917 	}
3918 
3919 	if (!hnd)
3920 		hnd = hhd->first;
3921 	else {
3922 		hnd = hnd->next;
3923 		if (!hnd) {
3924 			iter->pidx++;
3925 			goto retry;
3926 		}
3927 	}
3928 
3929 	if (WARN_ON_ONCE(!hnd))
3930 		return NULL;
3931 
3932 	iter->probe_entry = hlist_entry(hnd, struct ftrace_func_entry, hlist);
3933 
3934 	return iter;
3935 }
3936 
t_probe_start(struct seq_file * m,loff_t * pos)3937 static void *t_probe_start(struct seq_file *m, loff_t *pos)
3938 {
3939 	struct ftrace_iterator *iter = m->private;
3940 	void *p = NULL;
3941 	loff_t l;
3942 
3943 	if (!(iter->flags & FTRACE_ITER_DO_PROBES))
3944 		return NULL;
3945 
3946 	if (iter->mod_pos > *pos)
3947 		return NULL;
3948 
3949 	iter->probe = NULL;
3950 	iter->probe_entry = NULL;
3951 	iter->pidx = 0;
3952 	for (l = 0; l <= (*pos - iter->mod_pos); ) {
3953 		p = t_probe_next(m, &l);
3954 		if (!p)
3955 			break;
3956 	}
3957 	if (!p)
3958 		return NULL;
3959 
3960 	/* Only set this if we have an item */
3961 	iter->flags |= FTRACE_ITER_PROBE;
3962 
3963 	return iter;
3964 }
3965 
3966 static int
t_probe_show(struct seq_file * m,struct ftrace_iterator * iter)3967 t_probe_show(struct seq_file *m, struct ftrace_iterator *iter)
3968 {
3969 	struct ftrace_func_entry *probe_entry;
3970 	struct ftrace_probe_ops *probe_ops;
3971 	struct ftrace_func_probe *probe;
3972 
3973 	probe = iter->probe;
3974 	probe_entry = iter->probe_entry;
3975 
3976 	if (WARN_ON_ONCE(!probe || !probe_entry))
3977 		return -EIO;
3978 
3979 	probe_ops = probe->probe_ops;
3980 
3981 	if (probe_ops->print)
3982 		return probe_ops->print(m, probe_entry->ip, probe_ops, probe->data);
3983 
3984 	seq_printf(m, "%ps:%ps\n", (void *)probe_entry->ip,
3985 		   (void *)probe_ops->func);
3986 
3987 	return 0;
3988 }
3989 
3990 static void *
t_mod_next(struct seq_file * m,loff_t * pos)3991 t_mod_next(struct seq_file *m, loff_t *pos)
3992 {
3993 	struct ftrace_iterator *iter = m->private;
3994 	struct trace_array *tr = iter->tr;
3995 
3996 	(*pos)++;
3997 	iter->pos = *pos;
3998 
3999 	iter->mod_list = iter->mod_list->next;
4000 
4001 	if (iter->mod_list == &tr->mod_trace ||
4002 	    iter->mod_list == &tr->mod_notrace) {
4003 		iter->flags &= ~FTRACE_ITER_MOD;
4004 		return NULL;
4005 	}
4006 
4007 	iter->mod_pos = *pos;
4008 
4009 	return iter;
4010 }
4011 
t_mod_start(struct seq_file * m,loff_t * pos)4012 static void *t_mod_start(struct seq_file *m, loff_t *pos)
4013 {
4014 	struct ftrace_iterator *iter = m->private;
4015 	void *p = NULL;
4016 	loff_t l;
4017 
4018 	if (iter->func_pos > *pos)
4019 		return NULL;
4020 
4021 	iter->mod_pos = iter->func_pos;
4022 
4023 	/* probes are only available if tr is set */
4024 	if (!iter->tr)
4025 		return NULL;
4026 
4027 	for (l = 0; l <= (*pos - iter->func_pos); ) {
4028 		p = t_mod_next(m, &l);
4029 		if (!p)
4030 			break;
4031 	}
4032 	if (!p) {
4033 		iter->flags &= ~FTRACE_ITER_MOD;
4034 		return t_probe_start(m, pos);
4035 	}
4036 
4037 	/* Only set this if we have an item */
4038 	iter->flags |= FTRACE_ITER_MOD;
4039 
4040 	return iter;
4041 }
4042 
4043 static int
t_mod_show(struct seq_file * m,struct ftrace_iterator * iter)4044 t_mod_show(struct seq_file *m, struct ftrace_iterator *iter)
4045 {
4046 	struct ftrace_mod_load *ftrace_mod;
4047 	struct trace_array *tr = iter->tr;
4048 
4049 	if (WARN_ON_ONCE(!iter->mod_list) ||
4050 			 iter->mod_list == &tr->mod_trace ||
4051 			 iter->mod_list == &tr->mod_notrace)
4052 		return -EIO;
4053 
4054 	ftrace_mod = list_entry(iter->mod_list, struct ftrace_mod_load, list);
4055 
4056 	if (ftrace_mod->func)
4057 		seq_printf(m, "%s", ftrace_mod->func);
4058 	else
4059 		seq_putc(m, '*');
4060 
4061 	seq_printf(m, ":mod:%s\n", ftrace_mod->module);
4062 
4063 	return 0;
4064 }
4065 
4066 static void *
t_func_next(struct seq_file * m,loff_t * pos)4067 t_func_next(struct seq_file *m, loff_t *pos)
4068 {
4069 	struct ftrace_iterator *iter = m->private;
4070 	struct dyn_ftrace *rec = NULL;
4071 
4072 	(*pos)++;
4073 
4074  retry:
4075 	if (iter->idx >= iter->pg->index) {
4076 		if (iter->pg->next) {
4077 			iter->pg = iter->pg->next;
4078 			iter->idx = 0;
4079 			goto retry;
4080 		}
4081 	} else {
4082 		rec = &iter->pg->records[iter->idx++];
4083 		if (((iter->flags & (FTRACE_ITER_FILTER | FTRACE_ITER_NOTRACE)) &&
4084 		     !ftrace_lookup_ip(iter->hash, rec->ip)) ||
4085 
4086 		    ((iter->flags & FTRACE_ITER_ENABLED) &&
4087 		     !(rec->flags & FTRACE_FL_ENABLED)) ||
4088 
4089 		    ((iter->flags & FTRACE_ITER_TOUCHED) &&
4090 		     !(rec->flags & FTRACE_FL_TOUCHED))) {
4091 
4092 			rec = NULL;
4093 			goto retry;
4094 		}
4095 	}
4096 
4097 	if (!rec)
4098 		return NULL;
4099 
4100 	iter->pos = iter->func_pos = *pos;
4101 	iter->func = rec;
4102 
4103 	return iter;
4104 }
4105 
4106 static void *
t_next(struct seq_file * m,void * v,loff_t * pos)4107 t_next(struct seq_file *m, void *v, loff_t *pos)
4108 {
4109 	struct ftrace_iterator *iter = m->private;
4110 	loff_t l = *pos; /* t_probe_start() must use original pos */
4111 	void *ret;
4112 
4113 	if (unlikely(ftrace_disabled))
4114 		return NULL;
4115 
4116 	if (iter->flags & FTRACE_ITER_PROBE)
4117 		return t_probe_next(m, pos);
4118 
4119 	if (iter->flags & FTRACE_ITER_MOD)
4120 		return t_mod_next(m, pos);
4121 
4122 	if (iter->flags & FTRACE_ITER_PRINTALL) {
4123 		/* next must increment pos, and t_probe_start does not */
4124 		(*pos)++;
4125 		return t_mod_start(m, &l);
4126 	}
4127 
4128 	ret = t_func_next(m, pos);
4129 
4130 	if (!ret)
4131 		return t_mod_start(m, &l);
4132 
4133 	return ret;
4134 }
4135 
reset_iter_read(struct ftrace_iterator * iter)4136 static void reset_iter_read(struct ftrace_iterator *iter)
4137 {
4138 	iter->pos = 0;
4139 	iter->func_pos = 0;
4140 	iter->flags &= ~(FTRACE_ITER_PRINTALL | FTRACE_ITER_PROBE | FTRACE_ITER_MOD);
4141 }
4142 
t_start(struct seq_file * m,loff_t * pos)4143 static void *t_start(struct seq_file *m, loff_t *pos)
4144 {
4145 	struct ftrace_iterator *iter = m->private;
4146 	void *p = NULL;
4147 	loff_t l;
4148 
4149 	mutex_lock(&ftrace_lock);
4150 
4151 	if (unlikely(ftrace_disabled))
4152 		return NULL;
4153 
4154 	/*
4155 	 * If an lseek was done, then reset and start from beginning.
4156 	 */
4157 	if (*pos < iter->pos)
4158 		reset_iter_read(iter);
4159 
4160 	/*
4161 	 * For set_ftrace_filter reading, if we have the filter
4162 	 * off, we can short cut and just print out that all
4163 	 * functions are enabled.
4164 	 */
4165 	if ((iter->flags & (FTRACE_ITER_FILTER | FTRACE_ITER_NOTRACE)) &&
4166 	    ftrace_hash_empty(iter->hash)) {
4167 		iter->func_pos = 1; /* Account for the message */
4168 		if (*pos > 0)
4169 			return t_mod_start(m, pos);
4170 		iter->flags |= FTRACE_ITER_PRINTALL;
4171 		/* reset in case of seek/pread */
4172 		iter->flags &= ~FTRACE_ITER_PROBE;
4173 		return iter;
4174 	}
4175 
4176 	if (iter->flags & FTRACE_ITER_MOD)
4177 		return t_mod_start(m, pos);
4178 
4179 	/*
4180 	 * Unfortunately, we need to restart at ftrace_pages_start
4181 	 * every time we let go of the ftrace_mutex. This is because
4182 	 * those pointers can change without the lock.
4183 	 */
4184 	iter->pg = ftrace_pages_start;
4185 	iter->idx = 0;
4186 	for (l = 0; l <= *pos; ) {
4187 		p = t_func_next(m, &l);
4188 		if (!p)
4189 			break;
4190 	}
4191 
4192 	if (!p)
4193 		return t_mod_start(m, pos);
4194 
4195 	return iter;
4196 }
4197 
t_stop(struct seq_file * m,void * p)4198 static void t_stop(struct seq_file *m, void *p)
4199 {
4200 	mutex_unlock(&ftrace_lock);
4201 }
4202 
4203 void * __weak
arch_ftrace_trampoline_func(struct ftrace_ops * ops,struct dyn_ftrace * rec)4204 arch_ftrace_trampoline_func(struct ftrace_ops *ops, struct dyn_ftrace *rec)
4205 {
4206 	return NULL;
4207 }
4208 
add_trampoline_func(struct seq_file * m,struct ftrace_ops * ops,struct dyn_ftrace * rec)4209 static void add_trampoline_func(struct seq_file *m, struct ftrace_ops *ops,
4210 				struct dyn_ftrace *rec)
4211 {
4212 	void *ptr;
4213 
4214 	ptr = arch_ftrace_trampoline_func(ops, rec);
4215 	if (ptr)
4216 		seq_printf(m, " ->%pS", ptr);
4217 }
4218 
4219 #ifdef FTRACE_MCOUNT_MAX_OFFSET
4220 /*
4221  * Weak functions can still have an mcount/fentry that is saved in
4222  * the __mcount_loc section. These can be detected by having a
4223  * symbol offset of greater than FTRACE_MCOUNT_MAX_OFFSET, as the
4224  * symbol found by kallsyms is not the function that the mcount/fentry
4225  * is part of. The offset is much greater in these cases.
4226  *
4227  * Test the record to make sure that the ip points to a valid kallsyms
4228  * and if not, mark it disabled.
4229  */
test_for_valid_rec(struct dyn_ftrace * rec)4230 static int test_for_valid_rec(struct dyn_ftrace *rec)
4231 {
4232 	char str[KSYM_SYMBOL_LEN];
4233 	unsigned long offset;
4234 	const char *ret;
4235 
4236 	ret = kallsyms_lookup(rec->ip, NULL, &offset, NULL, str);
4237 
4238 	/* Weak functions can cause invalid addresses */
4239 	if (!ret || offset > FTRACE_MCOUNT_MAX_OFFSET) {
4240 		rec->flags |= FTRACE_FL_DISABLED;
4241 		return 0;
4242 	}
4243 	return 1;
4244 }
4245 
4246 static struct workqueue_struct *ftrace_check_wq __initdata;
4247 static struct work_struct ftrace_check_work __initdata;
4248 
4249 /*
4250  * Scan all the mcount/fentry entries to make sure they are valid.
4251  */
ftrace_check_work_func(struct work_struct * work)4252 static __init void ftrace_check_work_func(struct work_struct *work)
4253 {
4254 	struct ftrace_page *pg;
4255 	struct dyn_ftrace *rec;
4256 
4257 	mutex_lock(&ftrace_lock);
4258 	do_for_each_ftrace_rec(pg, rec) {
4259 		test_for_valid_rec(rec);
4260 	} while_for_each_ftrace_rec();
4261 	mutex_unlock(&ftrace_lock);
4262 }
4263 
ftrace_check_for_weak_functions(void)4264 static int __init ftrace_check_for_weak_functions(void)
4265 {
4266 	INIT_WORK(&ftrace_check_work, ftrace_check_work_func);
4267 
4268 	ftrace_check_wq = alloc_workqueue("ftrace_check_wq", WQ_UNBOUND, 0);
4269 
4270 	queue_work(ftrace_check_wq, &ftrace_check_work);
4271 	return 0;
4272 }
4273 
ftrace_check_sync(void)4274 static int __init ftrace_check_sync(void)
4275 {
4276 	/* Make sure the ftrace_check updates are finished */
4277 	if (ftrace_check_wq)
4278 		destroy_workqueue(ftrace_check_wq);
4279 	return 0;
4280 }
4281 
4282 late_initcall_sync(ftrace_check_sync);
4283 subsys_initcall(ftrace_check_for_weak_functions);
4284 
print_rec(struct seq_file * m,unsigned long ip)4285 static int print_rec(struct seq_file *m, unsigned long ip)
4286 {
4287 	unsigned long offset;
4288 	char str[KSYM_SYMBOL_LEN];
4289 	char *modname;
4290 	const char *ret;
4291 
4292 	ret = kallsyms_lookup(ip, NULL, &offset, &modname, str);
4293 	/* Weak functions can cause invalid addresses */
4294 	if (!ret || offset > FTRACE_MCOUNT_MAX_OFFSET) {
4295 		snprintf(str, KSYM_SYMBOL_LEN, "%s_%ld",
4296 			 FTRACE_INVALID_FUNCTION, offset);
4297 		ret = NULL;
4298 	}
4299 
4300 	seq_puts(m, str);
4301 	if (modname)
4302 		seq_printf(m, " [%s]", modname);
4303 	return ret == NULL ? -1 : 0;
4304 }
4305 #else
test_for_valid_rec(struct dyn_ftrace * rec)4306 static inline int test_for_valid_rec(struct dyn_ftrace *rec)
4307 {
4308 	return 1;
4309 }
4310 
print_rec(struct seq_file * m,unsigned long ip)4311 static inline int print_rec(struct seq_file *m, unsigned long ip)
4312 {
4313 	seq_printf(m, "%ps", (void *)ip);
4314 	return 0;
4315 }
4316 #endif
4317 
t_show(struct seq_file * m,void * v)4318 static int t_show(struct seq_file *m, void *v)
4319 {
4320 	struct ftrace_iterator *iter = m->private;
4321 	struct dyn_ftrace *rec;
4322 
4323 	if (iter->flags & FTRACE_ITER_PROBE)
4324 		return t_probe_show(m, iter);
4325 
4326 	if (iter->flags & FTRACE_ITER_MOD)
4327 		return t_mod_show(m, iter);
4328 
4329 	if (iter->flags & FTRACE_ITER_PRINTALL) {
4330 		if (iter->flags & FTRACE_ITER_NOTRACE)
4331 			seq_puts(m, "#### no functions disabled ####\n");
4332 		else
4333 			seq_puts(m, "#### all functions enabled ####\n");
4334 		return 0;
4335 	}
4336 
4337 	rec = iter->func;
4338 
4339 	if (!rec)
4340 		return 0;
4341 
4342 	if (iter->flags & FTRACE_ITER_ADDRS)
4343 		seq_printf(m, "%lx ", rec->ip);
4344 
4345 	if (print_rec(m, rec->ip)) {
4346 		/* This should only happen when a rec is disabled */
4347 		WARN_ON_ONCE(!(rec->flags & FTRACE_FL_DISABLED));
4348 		seq_putc(m, '\n');
4349 		return 0;
4350 	}
4351 
4352 	if (iter->flags & (FTRACE_ITER_ENABLED | FTRACE_ITER_TOUCHED)) {
4353 		struct ftrace_ops *ops;
4354 
4355 		seq_printf(m, " (%ld)%s%s%s%s%s",
4356 			   ftrace_rec_count(rec),
4357 			   rec->flags & FTRACE_FL_REGS ? " R" : "  ",
4358 			   rec->flags & FTRACE_FL_IPMODIFY ? " I" : "  ",
4359 			   rec->flags & FTRACE_FL_DIRECT ? " D" : "  ",
4360 			   rec->flags & FTRACE_FL_CALL_OPS ? " O" : "  ",
4361 			   rec->flags & FTRACE_FL_MODIFIED ? " M " : "   ");
4362 		if (rec->flags & FTRACE_FL_TRAMP_EN) {
4363 			ops = ftrace_find_tramp_ops_any(rec);
4364 			if (ops) {
4365 				do {
4366 					seq_printf(m, "\ttramp: %pS (%pS)",
4367 						   (void *)ops->trampoline,
4368 						   (void *)ops->func);
4369 					add_trampoline_func(m, ops, rec);
4370 					ops = ftrace_find_tramp_ops_next(rec, ops);
4371 				} while (ops);
4372 			} else
4373 				seq_puts(m, "\ttramp: ERROR!");
4374 		} else {
4375 			add_trampoline_func(m, NULL, rec);
4376 		}
4377 		if (rec->flags & FTRACE_FL_CALL_OPS_EN) {
4378 			ops = ftrace_find_unique_ops(rec);
4379 			if (ops) {
4380 				seq_printf(m, "\tops: %pS (%pS)",
4381 					   ops, ops->func);
4382 			} else {
4383 				seq_puts(m, "\tops: ERROR!");
4384 			}
4385 		}
4386 		if (rec->flags & FTRACE_FL_DIRECT) {
4387 			unsigned long direct;
4388 
4389 			direct = ftrace_find_rec_direct(rec->ip);
4390 			if (direct)
4391 				seq_printf(m, "\n\tdirect-->%pS", (void *)direct);
4392 		}
4393 	}
4394 
4395 	seq_putc(m, '\n');
4396 
4397 	return 0;
4398 }
4399 
4400 static const struct seq_operations show_ftrace_seq_ops = {
4401 	.start = t_start,
4402 	.next = t_next,
4403 	.stop = t_stop,
4404 	.show = t_show,
4405 };
4406 
4407 static int
ftrace_avail_open(struct inode * inode,struct file * file)4408 ftrace_avail_open(struct inode *inode, struct file *file)
4409 {
4410 	struct ftrace_iterator *iter;
4411 	int ret;
4412 
4413 	ret = security_locked_down(LOCKDOWN_TRACEFS);
4414 	if (ret)
4415 		return ret;
4416 
4417 	if (unlikely(ftrace_disabled))
4418 		return -ENODEV;
4419 
4420 	iter = __seq_open_private(file, &show_ftrace_seq_ops, sizeof(*iter));
4421 	if (!iter)
4422 		return -ENOMEM;
4423 
4424 	iter->pg = ftrace_pages_start;
4425 	iter->ops = &global_ops;
4426 
4427 	return 0;
4428 }
4429 
4430 static int
ftrace_enabled_open(struct inode * inode,struct file * file)4431 ftrace_enabled_open(struct inode *inode, struct file *file)
4432 {
4433 	struct ftrace_iterator *iter;
4434 
4435 	/*
4436 	 * This shows us what functions are currently being
4437 	 * traced and by what. Not sure if we want lockdown
4438 	 * to hide such critical information for an admin.
4439 	 * Although, perhaps it can show information we don't
4440 	 * want people to see, but if something is tracing
4441 	 * something, we probably want to know about it.
4442 	 */
4443 
4444 	iter = __seq_open_private(file, &show_ftrace_seq_ops, sizeof(*iter));
4445 	if (!iter)
4446 		return -ENOMEM;
4447 
4448 	iter->pg = ftrace_pages_start;
4449 	iter->flags = FTRACE_ITER_ENABLED;
4450 	iter->ops = &global_ops;
4451 
4452 	return 0;
4453 }
4454 
4455 static int
ftrace_touched_open(struct inode * inode,struct file * file)4456 ftrace_touched_open(struct inode *inode, struct file *file)
4457 {
4458 	struct ftrace_iterator *iter;
4459 
4460 	/*
4461 	 * This shows us what functions have ever been enabled
4462 	 * (traced, direct, patched, etc). Not sure if we want lockdown
4463 	 * to hide such critical information for an admin.
4464 	 * Although, perhaps it can show information we don't
4465 	 * want people to see, but if something had traced
4466 	 * something, we probably want to know about it.
4467 	 */
4468 
4469 	iter = __seq_open_private(file, &show_ftrace_seq_ops, sizeof(*iter));
4470 	if (!iter)
4471 		return -ENOMEM;
4472 
4473 	iter->pg = ftrace_pages_start;
4474 	iter->flags = FTRACE_ITER_TOUCHED;
4475 	iter->ops = &global_ops;
4476 
4477 	return 0;
4478 }
4479 
4480 static int
ftrace_avail_addrs_open(struct inode * inode,struct file * file)4481 ftrace_avail_addrs_open(struct inode *inode, struct file *file)
4482 {
4483 	struct ftrace_iterator *iter;
4484 	int ret;
4485 
4486 	ret = security_locked_down(LOCKDOWN_TRACEFS);
4487 	if (ret)
4488 		return ret;
4489 
4490 	if (unlikely(ftrace_disabled))
4491 		return -ENODEV;
4492 
4493 	iter = __seq_open_private(file, &show_ftrace_seq_ops, sizeof(*iter));
4494 	if (!iter)
4495 		return -ENOMEM;
4496 
4497 	iter->pg = ftrace_pages_start;
4498 	iter->flags = FTRACE_ITER_ADDRS;
4499 	iter->ops = &global_ops;
4500 
4501 	return 0;
4502 }
4503 
4504 /**
4505  * ftrace_regex_open - initialize function tracer filter files
4506  * @ops: The ftrace_ops that hold the hash filters
4507  * @flag: The type of filter to process
4508  * @inode: The inode, usually passed in to your open routine
4509  * @file: The file, usually passed in to your open routine
4510  *
4511  * ftrace_regex_open() initializes the filter files for the
4512  * @ops. Depending on @flag it may process the filter hash or
4513  * the notrace hash of @ops. With this called from the open
4514  * routine, you can use ftrace_filter_write() for the write
4515  * routine if @flag has FTRACE_ITER_FILTER set, or
4516  * ftrace_notrace_write() if @flag has FTRACE_ITER_NOTRACE set.
4517  * tracing_lseek() should be used as the lseek routine, and
4518  * release must call ftrace_regex_release().
4519  *
4520  * Returns: 0 on success or a negative errno value on failure
4521  */
4522 int
ftrace_regex_open(struct ftrace_ops * ops,int flag,struct inode * inode,struct file * file)4523 ftrace_regex_open(struct ftrace_ops *ops, int flag,
4524 		  struct inode *inode, struct file *file)
4525 {
4526 	struct ftrace_iterator *iter;
4527 	struct ftrace_hash *hash;
4528 	struct list_head *mod_head;
4529 	struct trace_array *tr = ops->private;
4530 	int ret = -ENOMEM;
4531 
4532 	ftrace_ops_init(ops);
4533 
4534 	if (unlikely(ftrace_disabled))
4535 		return -ENODEV;
4536 
4537 	if (tracing_check_open_get_tr(tr))
4538 		return -ENODEV;
4539 
4540 	iter = kzalloc(sizeof(*iter), GFP_KERNEL);
4541 	if (!iter)
4542 		goto out;
4543 
4544 	if (trace_parser_get_init(&iter->parser, FTRACE_BUFF_MAX))
4545 		goto out;
4546 
4547 	iter->ops = ops;
4548 	iter->flags = flag;
4549 	iter->tr = tr;
4550 
4551 	mutex_lock(&ops->func_hash->regex_lock);
4552 
4553 	if (flag & FTRACE_ITER_NOTRACE) {
4554 		hash = ops->func_hash->notrace_hash;
4555 		mod_head = tr ? &tr->mod_notrace : NULL;
4556 	} else {
4557 		hash = ops->func_hash->filter_hash;
4558 		mod_head = tr ? &tr->mod_trace : NULL;
4559 	}
4560 
4561 	iter->mod_list = mod_head;
4562 
4563 	if (file->f_mode & FMODE_WRITE) {
4564 		const int size_bits = FTRACE_HASH_DEFAULT_BITS;
4565 
4566 		if (file->f_flags & O_TRUNC) {
4567 			iter->hash = alloc_ftrace_hash(size_bits);
4568 			clear_ftrace_mod_list(mod_head);
4569 	        } else {
4570 			iter->hash = alloc_and_copy_ftrace_hash(size_bits, hash);
4571 		}
4572 	} else {
4573 		if (hash)
4574 			iter->hash = alloc_and_copy_ftrace_hash(hash->size_bits, hash);
4575 		else
4576 			iter->hash = EMPTY_HASH;
4577 	}
4578 
4579 	if (!iter->hash) {
4580 		trace_parser_put(&iter->parser);
4581 		goto out_unlock;
4582 	}
4583 
4584 	ret = 0;
4585 
4586 	if (file->f_mode & FMODE_READ) {
4587 		iter->pg = ftrace_pages_start;
4588 
4589 		ret = seq_open(file, &show_ftrace_seq_ops);
4590 		if (!ret) {
4591 			struct seq_file *m = file->private_data;
4592 			m->private = iter;
4593 		} else {
4594 			/* Failed */
4595 			free_ftrace_hash(iter->hash);
4596 			trace_parser_put(&iter->parser);
4597 		}
4598 	} else
4599 		file->private_data = iter;
4600 
4601  out_unlock:
4602 	mutex_unlock(&ops->func_hash->regex_lock);
4603 
4604  out:
4605 	if (ret) {
4606 		kfree(iter);
4607 		if (tr)
4608 			trace_array_put(tr);
4609 	}
4610 
4611 	return ret;
4612 }
4613 
4614 static int
ftrace_filter_open(struct inode * inode,struct file * file)4615 ftrace_filter_open(struct inode *inode, struct file *file)
4616 {
4617 	struct ftrace_ops *ops = inode->i_private;
4618 
4619 	/* Checks for tracefs lockdown */
4620 	return ftrace_regex_open(ops,
4621 			FTRACE_ITER_FILTER | FTRACE_ITER_DO_PROBES,
4622 			inode, file);
4623 }
4624 
4625 static int
ftrace_notrace_open(struct inode * inode,struct file * file)4626 ftrace_notrace_open(struct inode *inode, struct file *file)
4627 {
4628 	struct ftrace_ops *ops = inode->i_private;
4629 
4630 	/* Checks for tracefs lockdown */
4631 	return ftrace_regex_open(ops, FTRACE_ITER_NOTRACE,
4632 				 inode, file);
4633 }
4634 
4635 /* Type for quick search ftrace basic regexes (globs) from filter_parse_regex */
4636 struct ftrace_glob {
4637 	char *search;
4638 	unsigned len;
4639 	int type;
4640 };
4641 
4642 /*
4643  * If symbols in an architecture don't correspond exactly to the user-visible
4644  * name of what they represent, it is possible to define this function to
4645  * perform the necessary adjustments.
4646 */
arch_ftrace_match_adjust(char * str,const char * search)4647 char * __weak arch_ftrace_match_adjust(char *str, const char *search)
4648 {
4649 	return str;
4650 }
4651 
ftrace_match(char * str,struct ftrace_glob * g)4652 static int ftrace_match(char *str, struct ftrace_glob *g)
4653 {
4654 	int matched = 0;
4655 	int slen;
4656 
4657 	str = arch_ftrace_match_adjust(str, g->search);
4658 
4659 	switch (g->type) {
4660 	case MATCH_FULL:
4661 		if (strcmp(str, g->search) == 0)
4662 			matched = 1;
4663 		break;
4664 	case MATCH_FRONT_ONLY:
4665 		if (strncmp(str, g->search, g->len) == 0)
4666 			matched = 1;
4667 		break;
4668 	case MATCH_MIDDLE_ONLY:
4669 		if (strstr(str, g->search))
4670 			matched = 1;
4671 		break;
4672 	case MATCH_END_ONLY:
4673 		slen = strlen(str);
4674 		if (slen >= g->len &&
4675 		    memcmp(str + slen - g->len, g->search, g->len) == 0)
4676 			matched = 1;
4677 		break;
4678 	case MATCH_GLOB:
4679 		if (glob_match(g->search, str))
4680 			matched = 1;
4681 		break;
4682 	}
4683 
4684 	return matched;
4685 }
4686 
4687 static int
enter_record(struct ftrace_hash * hash,struct dyn_ftrace * rec,int clear_filter)4688 enter_record(struct ftrace_hash *hash, struct dyn_ftrace *rec, int clear_filter)
4689 {
4690 	struct ftrace_func_entry *entry;
4691 	int ret = 0;
4692 
4693 	entry = ftrace_lookup_ip(hash, rec->ip);
4694 	if (clear_filter) {
4695 		/* Do nothing if it doesn't exist */
4696 		if (!entry)
4697 			return 0;
4698 
4699 		free_hash_entry(hash, entry);
4700 	} else {
4701 		/* Do nothing if it exists */
4702 		if (entry)
4703 			return 0;
4704 		if (add_hash_entry(hash, rec->ip) == NULL)
4705 			ret = -ENOMEM;
4706 	}
4707 	return ret;
4708 }
4709 
4710 static int
add_rec_by_index(struct ftrace_hash * hash,struct ftrace_glob * func_g,int clear_filter)4711 add_rec_by_index(struct ftrace_hash *hash, struct ftrace_glob *func_g,
4712 		 int clear_filter)
4713 {
4714 	long index;
4715 	struct ftrace_page *pg;
4716 	struct dyn_ftrace *rec;
4717 
4718 	/* The index starts at 1 */
4719 	if (kstrtoul(func_g->search, 0, &index) || --index < 0)
4720 		return 0;
4721 
4722 	do_for_each_ftrace_rec(pg, rec) {
4723 		if (pg->index <= index) {
4724 			index -= pg->index;
4725 			/* this is a double loop, break goes to the next page */
4726 			break;
4727 		}
4728 		rec = &pg->records[index];
4729 		enter_record(hash, rec, clear_filter);
4730 		return 1;
4731 	} while_for_each_ftrace_rec();
4732 	return 0;
4733 }
4734 
4735 #ifdef FTRACE_MCOUNT_MAX_OFFSET
lookup_ip(unsigned long ip,char ** modname,char * str)4736 static int lookup_ip(unsigned long ip, char **modname, char *str)
4737 {
4738 	unsigned long offset;
4739 
4740 	kallsyms_lookup(ip, NULL, &offset, modname, str);
4741 	if (offset > FTRACE_MCOUNT_MAX_OFFSET)
4742 		return -1;
4743 	return 0;
4744 }
4745 #else
lookup_ip(unsigned long ip,char ** modname,char * str)4746 static int lookup_ip(unsigned long ip, char **modname, char *str)
4747 {
4748 	kallsyms_lookup(ip, NULL, NULL, modname, str);
4749 	return 0;
4750 }
4751 #endif
4752 
4753 static int
ftrace_match_record(struct dyn_ftrace * rec,struct ftrace_glob * func_g,struct ftrace_glob * mod_g,int exclude_mod)4754 ftrace_match_record(struct dyn_ftrace *rec, struct ftrace_glob *func_g,
4755 		struct ftrace_glob *mod_g, int exclude_mod)
4756 {
4757 	char str[KSYM_SYMBOL_LEN];
4758 	char *modname;
4759 
4760 	if (lookup_ip(rec->ip, &modname, str)) {
4761 		/* This should only happen when a rec is disabled */
4762 		WARN_ON_ONCE(system_state == SYSTEM_RUNNING &&
4763 			     !(rec->flags & FTRACE_FL_DISABLED));
4764 		return 0;
4765 	}
4766 
4767 	if (mod_g) {
4768 		int mod_matches = (modname) ? ftrace_match(modname, mod_g) : 0;
4769 
4770 		/* blank module name to match all modules */
4771 		if (!mod_g->len) {
4772 			/* blank module globbing: modname xor exclude_mod */
4773 			if (!exclude_mod != !modname)
4774 				goto func_match;
4775 			return 0;
4776 		}
4777 
4778 		/*
4779 		 * exclude_mod is set to trace everything but the given
4780 		 * module. If it is set and the module matches, then
4781 		 * return 0. If it is not set, and the module doesn't match
4782 		 * also return 0. Otherwise, check the function to see if
4783 		 * that matches.
4784 		 */
4785 		if (!mod_matches == !exclude_mod)
4786 			return 0;
4787 func_match:
4788 		/* blank search means to match all funcs in the mod */
4789 		if (!func_g->len)
4790 			return 1;
4791 	}
4792 
4793 	return ftrace_match(str, func_g);
4794 }
4795 
4796 static int
match_records(struct ftrace_hash * hash,char * func,int len,char * mod)4797 match_records(struct ftrace_hash *hash, char *func, int len, char *mod)
4798 {
4799 	struct ftrace_page *pg;
4800 	struct dyn_ftrace *rec;
4801 	struct ftrace_glob func_g = { .type = MATCH_FULL };
4802 	struct ftrace_glob mod_g = { .type = MATCH_FULL };
4803 	struct ftrace_glob *mod_match = (mod) ? &mod_g : NULL;
4804 	int exclude_mod = 0;
4805 	int found = 0;
4806 	int ret;
4807 	int clear_filter = 0;
4808 
4809 	if (func) {
4810 		func_g.type = filter_parse_regex(func, len, &func_g.search,
4811 						 &clear_filter);
4812 		func_g.len = strlen(func_g.search);
4813 	}
4814 
4815 	if (mod) {
4816 		mod_g.type = filter_parse_regex(mod, strlen(mod),
4817 				&mod_g.search, &exclude_mod);
4818 		mod_g.len = strlen(mod_g.search);
4819 	}
4820 
4821 	mutex_lock(&ftrace_lock);
4822 
4823 	if (unlikely(ftrace_disabled))
4824 		goto out_unlock;
4825 
4826 	if (func_g.type == MATCH_INDEX) {
4827 		found = add_rec_by_index(hash, &func_g, clear_filter);
4828 		goto out_unlock;
4829 	}
4830 
4831 	do_for_each_ftrace_rec(pg, rec) {
4832 
4833 		if (rec->flags & FTRACE_FL_DISABLED)
4834 			continue;
4835 
4836 		if (ftrace_match_record(rec, &func_g, mod_match, exclude_mod)) {
4837 			ret = enter_record(hash, rec, clear_filter);
4838 			if (ret < 0) {
4839 				found = ret;
4840 				goto out_unlock;
4841 			}
4842 			found = 1;
4843 		}
4844 		cond_resched();
4845 	} while_for_each_ftrace_rec();
4846  out_unlock:
4847 	mutex_unlock(&ftrace_lock);
4848 
4849 	return found;
4850 }
4851 
4852 static int
ftrace_match_records(struct ftrace_hash * hash,char * buff,int len)4853 ftrace_match_records(struct ftrace_hash *hash, char *buff, int len)
4854 {
4855 	return match_records(hash, buff, len, NULL);
4856 }
4857 
ftrace_ops_update_code(struct ftrace_ops * ops,struct ftrace_ops_hash * old_hash)4858 static void ftrace_ops_update_code(struct ftrace_ops *ops,
4859 				   struct ftrace_ops_hash *old_hash)
4860 {
4861 	struct ftrace_ops *op;
4862 
4863 	if (!ftrace_enabled)
4864 		return;
4865 
4866 	if (ops->flags & FTRACE_OPS_FL_ENABLED) {
4867 		ftrace_run_modify_code(ops, FTRACE_UPDATE_CALLS, old_hash);
4868 		return;
4869 	}
4870 
4871 	/*
4872 	 * If this is the shared global_ops filter, then we need to
4873 	 * check if there is another ops that shares it, is enabled.
4874 	 * If so, we still need to run the modify code.
4875 	 */
4876 	if (ops->func_hash != &global_ops.local_hash)
4877 		return;
4878 
4879 	do_for_each_ftrace_op(op, ftrace_ops_list) {
4880 		if (op->func_hash == &global_ops.local_hash &&
4881 		    op->flags & FTRACE_OPS_FL_ENABLED) {
4882 			ftrace_run_modify_code(op, FTRACE_UPDATE_CALLS, old_hash);
4883 			/* Only need to do this once */
4884 			return;
4885 		}
4886 	} while_for_each_ftrace_op(op);
4887 }
4888 
ftrace_hash_move_and_update_ops(struct ftrace_ops * ops,struct ftrace_hash ** orig_hash,struct ftrace_hash * hash,int enable)4889 static int ftrace_hash_move_and_update_ops(struct ftrace_ops *ops,
4890 					   struct ftrace_hash **orig_hash,
4891 					   struct ftrace_hash *hash,
4892 					   int enable)
4893 {
4894 	if (ops->flags & FTRACE_OPS_FL_SUBOP)
4895 		return ftrace_hash_move_and_update_subops(ops, orig_hash, hash, enable);
4896 
4897 	/*
4898 	 * If this ops is not enabled, it could be sharing its filters
4899 	 * with a subop. If that's the case, update the subop instead of
4900 	 * this ops. Shared filters are only allowed to have one ops set
4901 	 * at a time, and if we update the ops that is not enabled,
4902 	 * it will not affect subops that share it.
4903 	 */
4904 	if (!(ops->flags & FTRACE_OPS_FL_ENABLED)) {
4905 		struct ftrace_ops *op;
4906 
4907 		/* Check if any other manager subops maps to this hash */
4908 		do_for_each_ftrace_op(op, ftrace_ops_list) {
4909 			struct ftrace_ops *subops;
4910 
4911 			list_for_each_entry(subops, &op->subop_list, list) {
4912 				if ((subops->flags & FTRACE_OPS_FL_ENABLED) &&
4913 				     subops->func_hash == ops->func_hash) {
4914 					return ftrace_hash_move_and_update_subops(subops, orig_hash, hash, enable);
4915 				}
4916 			}
4917 		} while_for_each_ftrace_op(op);
4918 	}
4919 
4920 	return __ftrace_hash_move_and_update_ops(ops, orig_hash, hash, enable);
4921 }
4922 
module_exists(const char * module)4923 static bool module_exists(const char *module)
4924 {
4925 	/* All modules have the symbol __this_module */
4926 	static const char this_mod[] = "__this_module";
4927 	char modname[MAX_PARAM_PREFIX_LEN + sizeof(this_mod) + 2];
4928 	unsigned long val;
4929 	int n;
4930 
4931 	n = snprintf(modname, sizeof(modname), "%s:%s", module, this_mod);
4932 
4933 	if (n > sizeof(modname) - 1)
4934 		return false;
4935 
4936 	val = module_kallsyms_lookup_name(modname);
4937 	return val != 0;
4938 }
4939 
cache_mod(struct trace_array * tr,const char * func,char * module,int enable)4940 static int cache_mod(struct trace_array *tr,
4941 		     const char *func, char *module, int enable)
4942 {
4943 	struct ftrace_mod_load *ftrace_mod, *n;
4944 	struct list_head *head = enable ? &tr->mod_trace : &tr->mod_notrace;
4945 	int ret;
4946 
4947 	mutex_lock(&ftrace_lock);
4948 
4949 	/* We do not cache inverse filters */
4950 	if (func[0] == '!') {
4951 		func++;
4952 		ret = -EINVAL;
4953 
4954 		/* Look to remove this hash */
4955 		list_for_each_entry_safe(ftrace_mod, n, head, list) {
4956 			if (strcmp(ftrace_mod->module, module) != 0)
4957 				continue;
4958 
4959 			/* no func matches all */
4960 			if (strcmp(func, "*") == 0 ||
4961 			    (ftrace_mod->func &&
4962 			     strcmp(ftrace_mod->func, func) == 0)) {
4963 				ret = 0;
4964 				free_ftrace_mod(ftrace_mod);
4965 				continue;
4966 			}
4967 		}
4968 		goto out;
4969 	}
4970 
4971 	ret = -EINVAL;
4972 	/* We only care about modules that have not been loaded yet */
4973 	if (module_exists(module))
4974 		goto out;
4975 
4976 	/* Save this string off, and execute it when the module is loaded */
4977 	ret = ftrace_add_mod(tr, func, module, enable);
4978  out:
4979 	mutex_unlock(&ftrace_lock);
4980 
4981 	return ret;
4982 }
4983 
4984 static int
4985 ftrace_set_regex(struct ftrace_ops *ops, unsigned char *buf, int len,
4986 		 int reset, int enable);
4987 
4988 #ifdef CONFIG_MODULES
process_mod_list(struct list_head * head,struct ftrace_ops * ops,char * mod,bool enable)4989 static void process_mod_list(struct list_head *head, struct ftrace_ops *ops,
4990 			     char *mod, bool enable)
4991 {
4992 	struct ftrace_mod_load *ftrace_mod, *n;
4993 	struct ftrace_hash **orig_hash, *new_hash;
4994 	LIST_HEAD(process_mods);
4995 	char *func;
4996 
4997 	mutex_lock(&ops->func_hash->regex_lock);
4998 
4999 	if (enable)
5000 		orig_hash = &ops->func_hash->filter_hash;
5001 	else
5002 		orig_hash = &ops->func_hash->notrace_hash;
5003 
5004 	new_hash = alloc_and_copy_ftrace_hash(FTRACE_HASH_DEFAULT_BITS,
5005 					      *orig_hash);
5006 	if (!new_hash)
5007 		goto out; /* warn? */
5008 
5009 	mutex_lock(&ftrace_lock);
5010 
5011 	list_for_each_entry_safe(ftrace_mod, n, head, list) {
5012 
5013 		if (strcmp(ftrace_mod->module, mod) != 0)
5014 			continue;
5015 
5016 		if (ftrace_mod->func)
5017 			func = kstrdup(ftrace_mod->func, GFP_KERNEL);
5018 		else
5019 			func = kstrdup("*", GFP_KERNEL);
5020 
5021 		if (!func) /* warn? */
5022 			continue;
5023 
5024 		list_move(&ftrace_mod->list, &process_mods);
5025 
5026 		/* Use the newly allocated func, as it may be "*" */
5027 		kfree(ftrace_mod->func);
5028 		ftrace_mod->func = func;
5029 	}
5030 
5031 	mutex_unlock(&ftrace_lock);
5032 
5033 	list_for_each_entry_safe(ftrace_mod, n, &process_mods, list) {
5034 
5035 		func = ftrace_mod->func;
5036 
5037 		/* Grabs ftrace_lock, which is why we have this extra step */
5038 		match_records(new_hash, func, strlen(func), mod);
5039 		free_ftrace_mod(ftrace_mod);
5040 	}
5041 
5042 	if (enable && list_empty(head))
5043 		new_hash->flags &= ~FTRACE_HASH_FL_MOD;
5044 
5045 	mutex_lock(&ftrace_lock);
5046 
5047 	ftrace_hash_move_and_update_ops(ops, orig_hash,
5048 					      new_hash, enable);
5049 	mutex_unlock(&ftrace_lock);
5050 
5051  out:
5052 	mutex_unlock(&ops->func_hash->regex_lock);
5053 
5054 	free_ftrace_hash(new_hash);
5055 }
5056 
process_cached_mods(const char * mod_name)5057 static void process_cached_mods(const char *mod_name)
5058 {
5059 	struct trace_array *tr;
5060 	char *mod;
5061 
5062 	mod = kstrdup(mod_name, GFP_KERNEL);
5063 	if (!mod)
5064 		return;
5065 
5066 	mutex_lock(&trace_types_lock);
5067 	list_for_each_entry(tr, &ftrace_trace_arrays, list) {
5068 		if (!list_empty(&tr->mod_trace))
5069 			process_mod_list(&tr->mod_trace, tr->ops, mod, true);
5070 		if (!list_empty(&tr->mod_notrace))
5071 			process_mod_list(&tr->mod_notrace, tr->ops, mod, false);
5072 	}
5073 	mutex_unlock(&trace_types_lock);
5074 
5075 	kfree(mod);
5076 }
5077 #endif
5078 
5079 /*
5080  * We register the module command as a template to show others how
5081  * to register the a command as well.
5082  */
5083 
5084 static int
ftrace_mod_callback(struct trace_array * tr,struct ftrace_hash * hash,char * func_orig,char * cmd,char * module,int enable)5085 ftrace_mod_callback(struct trace_array *tr, struct ftrace_hash *hash,
5086 		    char *func_orig, char *cmd, char *module, int enable)
5087 {
5088 	char *func;
5089 	int ret;
5090 
5091 	if (!tr)
5092 		return -ENODEV;
5093 
5094 	/* match_records() modifies func, and we need the original */
5095 	func = kstrdup(func_orig, GFP_KERNEL);
5096 	if (!func)
5097 		return -ENOMEM;
5098 
5099 	/*
5100 	 * cmd == 'mod' because we only registered this func
5101 	 * for the 'mod' ftrace_func_command.
5102 	 * But if you register one func with multiple commands,
5103 	 * you can tell which command was used by the cmd
5104 	 * parameter.
5105 	 */
5106 	ret = match_records(hash, func, strlen(func), module);
5107 	kfree(func);
5108 
5109 	if (!ret)
5110 		return cache_mod(tr, func_orig, module, enable);
5111 	if (ret < 0)
5112 		return ret;
5113 	return 0;
5114 }
5115 
5116 static struct ftrace_func_command ftrace_mod_cmd = {
5117 	.name			= "mod",
5118 	.func			= ftrace_mod_callback,
5119 };
5120 
ftrace_mod_cmd_init(void)5121 static int __init ftrace_mod_cmd_init(void)
5122 {
5123 	return register_ftrace_command(&ftrace_mod_cmd);
5124 }
5125 core_initcall(ftrace_mod_cmd_init);
5126 
function_trace_probe_call(unsigned long ip,unsigned long parent_ip,struct ftrace_ops * op,struct ftrace_regs * fregs)5127 static void function_trace_probe_call(unsigned long ip, unsigned long parent_ip,
5128 				      struct ftrace_ops *op, struct ftrace_regs *fregs)
5129 {
5130 	struct ftrace_probe_ops *probe_ops;
5131 	struct ftrace_func_probe *probe;
5132 
5133 	probe = container_of(op, struct ftrace_func_probe, ops);
5134 	probe_ops = probe->probe_ops;
5135 
5136 	/*
5137 	 * Disable preemption for these calls to prevent a RCU grace
5138 	 * period. This syncs the hash iteration and freeing of items
5139 	 * on the hash. rcu_read_lock is too dangerous here.
5140 	 */
5141 	preempt_disable_notrace();
5142 	probe_ops->func(ip, parent_ip, probe->tr, probe_ops, probe->data);
5143 	preempt_enable_notrace();
5144 }
5145 
5146 struct ftrace_func_map {
5147 	struct ftrace_func_entry	entry;
5148 	void				*data;
5149 };
5150 
5151 struct ftrace_func_mapper {
5152 	struct ftrace_hash		hash;
5153 };
5154 
5155 /**
5156  * allocate_ftrace_func_mapper - allocate a new ftrace_func_mapper
5157  *
5158  * Returns: a ftrace_func_mapper descriptor that can be used to map ips to data.
5159  */
allocate_ftrace_func_mapper(void)5160 struct ftrace_func_mapper *allocate_ftrace_func_mapper(void)
5161 {
5162 	struct ftrace_hash *hash;
5163 
5164 	/*
5165 	 * The mapper is simply a ftrace_hash, but since the entries
5166 	 * in the hash are not ftrace_func_entry type, we define it
5167 	 * as a separate structure.
5168 	 */
5169 	hash = alloc_ftrace_hash(FTRACE_HASH_DEFAULT_BITS);
5170 	return (struct ftrace_func_mapper *)hash;
5171 }
5172 
5173 /**
5174  * ftrace_func_mapper_find_ip - Find some data mapped to an ip
5175  * @mapper: The mapper that has the ip maps
5176  * @ip: the instruction pointer to find the data for
5177  *
5178  * Returns: the data mapped to @ip if found otherwise NULL. The return
5179  * is actually the address of the mapper data pointer. The address is
5180  * returned for use cases where the data is no bigger than a long, and
5181  * the user can use the data pointer as its data instead of having to
5182  * allocate more memory for the reference.
5183  */
ftrace_func_mapper_find_ip(struct ftrace_func_mapper * mapper,unsigned long ip)5184 void **ftrace_func_mapper_find_ip(struct ftrace_func_mapper *mapper,
5185 				  unsigned long ip)
5186 {
5187 	struct ftrace_func_entry *entry;
5188 	struct ftrace_func_map *map;
5189 
5190 	entry = ftrace_lookup_ip(&mapper->hash, ip);
5191 	if (!entry)
5192 		return NULL;
5193 
5194 	map = (struct ftrace_func_map *)entry;
5195 	return &map->data;
5196 }
5197 
5198 /**
5199  * ftrace_func_mapper_add_ip - Map some data to an ip
5200  * @mapper: The mapper that has the ip maps
5201  * @ip: The instruction pointer address to map @data to
5202  * @data: The data to map to @ip
5203  *
5204  * Returns: 0 on success otherwise an error.
5205  */
ftrace_func_mapper_add_ip(struct ftrace_func_mapper * mapper,unsigned long ip,void * data)5206 int ftrace_func_mapper_add_ip(struct ftrace_func_mapper *mapper,
5207 			      unsigned long ip, void *data)
5208 {
5209 	struct ftrace_func_entry *entry;
5210 	struct ftrace_func_map *map;
5211 
5212 	entry = ftrace_lookup_ip(&mapper->hash, ip);
5213 	if (entry)
5214 		return -EBUSY;
5215 
5216 	map = kmalloc(sizeof(*map), GFP_KERNEL);
5217 	if (!map)
5218 		return -ENOMEM;
5219 
5220 	map->entry.ip = ip;
5221 	map->data = data;
5222 
5223 	__add_hash_entry(&mapper->hash, &map->entry);
5224 
5225 	return 0;
5226 }
5227 
5228 /**
5229  * ftrace_func_mapper_remove_ip - Remove an ip from the mapping
5230  * @mapper: The mapper that has the ip maps
5231  * @ip: The instruction pointer address to remove the data from
5232  *
5233  * Returns: the data if it is found, otherwise NULL.
5234  * Note, if the data pointer is used as the data itself, (see
5235  * ftrace_func_mapper_find_ip(), then the return value may be meaningless,
5236  * if the data pointer was set to zero.
5237  */
ftrace_func_mapper_remove_ip(struct ftrace_func_mapper * mapper,unsigned long ip)5238 void *ftrace_func_mapper_remove_ip(struct ftrace_func_mapper *mapper,
5239 				   unsigned long ip)
5240 {
5241 	struct ftrace_func_entry *entry;
5242 	struct ftrace_func_map *map;
5243 	void *data;
5244 
5245 	entry = ftrace_lookup_ip(&mapper->hash, ip);
5246 	if (!entry)
5247 		return NULL;
5248 
5249 	map = (struct ftrace_func_map *)entry;
5250 	data = map->data;
5251 
5252 	remove_hash_entry(&mapper->hash, entry);
5253 	kfree(entry);
5254 
5255 	return data;
5256 }
5257 
5258 /**
5259  * free_ftrace_func_mapper - free a mapping of ips and data
5260  * @mapper: The mapper that has the ip maps
5261  * @free_func: A function to be called on each data item.
5262  *
5263  * This is used to free the function mapper. The @free_func is optional
5264  * and can be used if the data needs to be freed as well.
5265  */
free_ftrace_func_mapper(struct ftrace_func_mapper * mapper,ftrace_mapper_func free_func)5266 void free_ftrace_func_mapper(struct ftrace_func_mapper *mapper,
5267 			     ftrace_mapper_func free_func)
5268 {
5269 	struct ftrace_func_entry *entry;
5270 	struct ftrace_func_map *map;
5271 	struct hlist_head *hhd;
5272 	int size, i;
5273 
5274 	if (!mapper)
5275 		return;
5276 
5277 	if (free_func && mapper->hash.count) {
5278 		size = 1 << mapper->hash.size_bits;
5279 		for (i = 0; i < size; i++) {
5280 			hhd = &mapper->hash.buckets[i];
5281 			hlist_for_each_entry(entry, hhd, hlist) {
5282 				map = (struct ftrace_func_map *)entry;
5283 				free_func(map);
5284 			}
5285 		}
5286 	}
5287 	free_ftrace_hash(&mapper->hash);
5288 }
5289 
release_probe(struct ftrace_func_probe * probe)5290 static void release_probe(struct ftrace_func_probe *probe)
5291 {
5292 	struct ftrace_probe_ops *probe_ops;
5293 
5294 	mutex_lock(&ftrace_lock);
5295 
5296 	WARN_ON(probe->ref <= 0);
5297 
5298 	/* Subtract the ref that was used to protect this instance */
5299 	probe->ref--;
5300 
5301 	if (!probe->ref) {
5302 		probe_ops = probe->probe_ops;
5303 		/*
5304 		 * Sending zero as ip tells probe_ops to free
5305 		 * the probe->data itself
5306 		 */
5307 		if (probe_ops->free)
5308 			probe_ops->free(probe_ops, probe->tr, 0, probe->data);
5309 		list_del(&probe->list);
5310 		kfree(probe);
5311 	}
5312 	mutex_unlock(&ftrace_lock);
5313 }
5314 
acquire_probe_locked(struct ftrace_func_probe * probe)5315 static void acquire_probe_locked(struct ftrace_func_probe *probe)
5316 {
5317 	/*
5318 	 * Add one ref to keep it from being freed when releasing the
5319 	 * ftrace_lock mutex.
5320 	 */
5321 	probe->ref++;
5322 }
5323 
5324 int
register_ftrace_function_probe(char * glob,struct trace_array * tr,struct ftrace_probe_ops * probe_ops,void * data)5325 register_ftrace_function_probe(char *glob, struct trace_array *tr,
5326 			       struct ftrace_probe_ops *probe_ops,
5327 			       void *data)
5328 {
5329 	struct ftrace_func_probe *probe = NULL, *iter;
5330 	struct ftrace_func_entry *entry;
5331 	struct ftrace_hash **orig_hash;
5332 	struct ftrace_hash *old_hash;
5333 	struct ftrace_hash *hash;
5334 	int count = 0;
5335 	int size;
5336 	int ret;
5337 	int i;
5338 
5339 	if (WARN_ON(!tr))
5340 		return -EINVAL;
5341 
5342 	/* We do not support '!' for function probes */
5343 	if (WARN_ON(glob[0] == '!'))
5344 		return -EINVAL;
5345 
5346 
5347 	mutex_lock(&ftrace_lock);
5348 	/* Check if the probe_ops is already registered */
5349 	list_for_each_entry(iter, &tr->func_probes, list) {
5350 		if (iter->probe_ops == probe_ops) {
5351 			probe = iter;
5352 			break;
5353 		}
5354 	}
5355 	if (!probe) {
5356 		probe = kzalloc(sizeof(*probe), GFP_KERNEL);
5357 		if (!probe) {
5358 			mutex_unlock(&ftrace_lock);
5359 			return -ENOMEM;
5360 		}
5361 		probe->probe_ops = probe_ops;
5362 		probe->ops.func = function_trace_probe_call;
5363 		probe->tr = tr;
5364 		ftrace_ops_init(&probe->ops);
5365 		list_add(&probe->list, &tr->func_probes);
5366 	}
5367 
5368 	acquire_probe_locked(probe);
5369 
5370 	mutex_unlock(&ftrace_lock);
5371 
5372 	/*
5373 	 * Note, there's a small window here that the func_hash->filter_hash
5374 	 * may be NULL or empty. Need to be careful when reading the loop.
5375 	 */
5376 	mutex_lock(&probe->ops.func_hash->regex_lock);
5377 
5378 	orig_hash = &probe->ops.func_hash->filter_hash;
5379 	old_hash = *orig_hash;
5380 	hash = alloc_and_copy_ftrace_hash(FTRACE_HASH_DEFAULT_BITS, old_hash);
5381 
5382 	if (!hash) {
5383 		ret = -ENOMEM;
5384 		goto out;
5385 	}
5386 
5387 	ret = ftrace_match_records(hash, glob, strlen(glob));
5388 
5389 	/* Nothing found? */
5390 	if (!ret)
5391 		ret = -EINVAL;
5392 
5393 	if (ret < 0)
5394 		goto out;
5395 
5396 	size = 1 << hash->size_bits;
5397 	for (i = 0; i < size; i++) {
5398 		hlist_for_each_entry(entry, &hash->buckets[i], hlist) {
5399 			if (ftrace_lookup_ip(old_hash, entry->ip))
5400 				continue;
5401 			/*
5402 			 * The caller might want to do something special
5403 			 * for each function we find. We call the callback
5404 			 * to give the caller an opportunity to do so.
5405 			 */
5406 			if (probe_ops->init) {
5407 				ret = probe_ops->init(probe_ops, tr,
5408 						      entry->ip, data,
5409 						      &probe->data);
5410 				if (ret < 0) {
5411 					if (probe_ops->free && count)
5412 						probe_ops->free(probe_ops, tr,
5413 								0, probe->data);
5414 					probe->data = NULL;
5415 					goto out;
5416 				}
5417 			}
5418 			count++;
5419 		}
5420 	}
5421 
5422 	mutex_lock(&ftrace_lock);
5423 
5424 	if (!count) {
5425 		/* Nothing was added? */
5426 		ret = -EINVAL;
5427 		goto out_unlock;
5428 	}
5429 
5430 	ret = ftrace_hash_move_and_update_ops(&probe->ops, orig_hash,
5431 					      hash, 1);
5432 	if (ret < 0)
5433 		goto err_unlock;
5434 
5435 	/* One ref for each new function traced */
5436 	probe->ref += count;
5437 
5438 	if (!(probe->ops.flags & FTRACE_OPS_FL_ENABLED))
5439 		ret = ftrace_startup(&probe->ops, 0);
5440 
5441  out_unlock:
5442 	mutex_unlock(&ftrace_lock);
5443 
5444 	if (!ret)
5445 		ret = count;
5446  out:
5447 	mutex_unlock(&probe->ops.func_hash->regex_lock);
5448 	free_ftrace_hash(hash);
5449 
5450 	release_probe(probe);
5451 
5452 	return ret;
5453 
5454  err_unlock:
5455 	if (!probe_ops->free || !count)
5456 		goto out_unlock;
5457 
5458 	/* Failed to do the move, need to call the free functions */
5459 	for (i = 0; i < size; i++) {
5460 		hlist_for_each_entry(entry, &hash->buckets[i], hlist) {
5461 			if (ftrace_lookup_ip(old_hash, entry->ip))
5462 				continue;
5463 			probe_ops->free(probe_ops, tr, entry->ip, probe->data);
5464 		}
5465 	}
5466 	goto out_unlock;
5467 }
5468 
5469 int
unregister_ftrace_function_probe_func(char * glob,struct trace_array * tr,struct ftrace_probe_ops * probe_ops)5470 unregister_ftrace_function_probe_func(char *glob, struct trace_array *tr,
5471 				      struct ftrace_probe_ops *probe_ops)
5472 {
5473 	struct ftrace_func_probe *probe = NULL, *iter;
5474 	struct ftrace_ops_hash old_hash_ops;
5475 	struct ftrace_func_entry *entry;
5476 	struct ftrace_glob func_g;
5477 	struct ftrace_hash **orig_hash;
5478 	struct ftrace_hash *old_hash;
5479 	struct ftrace_hash *hash = NULL;
5480 	struct hlist_node *tmp;
5481 	struct hlist_head hhd;
5482 	char str[KSYM_SYMBOL_LEN];
5483 	int count = 0;
5484 	int i, ret = -ENODEV;
5485 	int size;
5486 
5487 	if (!glob || !strlen(glob) || !strcmp(glob, "*"))
5488 		func_g.search = NULL;
5489 	else {
5490 		int not;
5491 
5492 		func_g.type = filter_parse_regex(glob, strlen(glob),
5493 						 &func_g.search, &not);
5494 		func_g.len = strlen(func_g.search);
5495 
5496 		/* we do not support '!' for function probes */
5497 		if (WARN_ON(not))
5498 			return -EINVAL;
5499 	}
5500 
5501 	mutex_lock(&ftrace_lock);
5502 	/* Check if the probe_ops is already registered */
5503 	list_for_each_entry(iter, &tr->func_probes, list) {
5504 		if (iter->probe_ops == probe_ops) {
5505 			probe = iter;
5506 			break;
5507 		}
5508 	}
5509 	if (!probe)
5510 		goto err_unlock_ftrace;
5511 
5512 	ret = -EINVAL;
5513 	if (!(probe->ops.flags & FTRACE_OPS_FL_INITIALIZED))
5514 		goto err_unlock_ftrace;
5515 
5516 	acquire_probe_locked(probe);
5517 
5518 	mutex_unlock(&ftrace_lock);
5519 
5520 	mutex_lock(&probe->ops.func_hash->regex_lock);
5521 
5522 	orig_hash = &probe->ops.func_hash->filter_hash;
5523 	old_hash = *orig_hash;
5524 
5525 	if (ftrace_hash_empty(old_hash))
5526 		goto out_unlock;
5527 
5528 	old_hash_ops.filter_hash = old_hash;
5529 	/* Probes only have filters */
5530 	old_hash_ops.notrace_hash = NULL;
5531 
5532 	ret = -ENOMEM;
5533 	hash = alloc_and_copy_ftrace_hash(FTRACE_HASH_DEFAULT_BITS, old_hash);
5534 	if (!hash)
5535 		goto out_unlock;
5536 
5537 	INIT_HLIST_HEAD(&hhd);
5538 
5539 	size = 1 << hash->size_bits;
5540 	for (i = 0; i < size; i++) {
5541 		hlist_for_each_entry_safe(entry, tmp, &hash->buckets[i], hlist) {
5542 
5543 			if (func_g.search) {
5544 				kallsyms_lookup(entry->ip, NULL, NULL,
5545 						NULL, str);
5546 				if (!ftrace_match(str, &func_g))
5547 					continue;
5548 			}
5549 			count++;
5550 			remove_hash_entry(hash, entry);
5551 			hlist_add_head(&entry->hlist, &hhd);
5552 		}
5553 	}
5554 
5555 	/* Nothing found? */
5556 	if (!count) {
5557 		ret = -EINVAL;
5558 		goto out_unlock;
5559 	}
5560 
5561 	mutex_lock(&ftrace_lock);
5562 
5563 	WARN_ON(probe->ref < count);
5564 
5565 	probe->ref -= count;
5566 
5567 	if (ftrace_hash_empty(hash))
5568 		ftrace_shutdown(&probe->ops, 0);
5569 
5570 	ret = ftrace_hash_move_and_update_ops(&probe->ops, orig_hash,
5571 					      hash, 1);
5572 
5573 	/* still need to update the function call sites */
5574 	if (ftrace_enabled && !ftrace_hash_empty(hash))
5575 		ftrace_run_modify_code(&probe->ops, FTRACE_UPDATE_CALLS,
5576 				       &old_hash_ops);
5577 	synchronize_rcu();
5578 
5579 	hlist_for_each_entry_safe(entry, tmp, &hhd, hlist) {
5580 		hlist_del(&entry->hlist);
5581 		if (probe_ops->free)
5582 			probe_ops->free(probe_ops, tr, entry->ip, probe->data);
5583 		kfree(entry);
5584 	}
5585 	mutex_unlock(&ftrace_lock);
5586 
5587  out_unlock:
5588 	mutex_unlock(&probe->ops.func_hash->regex_lock);
5589 	free_ftrace_hash(hash);
5590 
5591 	release_probe(probe);
5592 
5593 	return ret;
5594 
5595  err_unlock_ftrace:
5596 	mutex_unlock(&ftrace_lock);
5597 	return ret;
5598 }
5599 
clear_ftrace_function_probes(struct trace_array * tr)5600 void clear_ftrace_function_probes(struct trace_array *tr)
5601 {
5602 	struct ftrace_func_probe *probe, *n;
5603 
5604 	list_for_each_entry_safe(probe, n, &tr->func_probes, list)
5605 		unregister_ftrace_function_probe_func(NULL, tr, probe->probe_ops);
5606 }
5607 
5608 static LIST_HEAD(ftrace_commands);
5609 static DEFINE_MUTEX(ftrace_cmd_mutex);
5610 
5611 /*
5612  * Currently we only register ftrace commands from __init, so mark this
5613  * __init too.
5614  */
register_ftrace_command(struct ftrace_func_command * cmd)5615 __init int register_ftrace_command(struct ftrace_func_command *cmd)
5616 {
5617 	struct ftrace_func_command *p;
5618 	int ret = 0;
5619 
5620 	mutex_lock(&ftrace_cmd_mutex);
5621 	list_for_each_entry(p, &ftrace_commands, list) {
5622 		if (strcmp(cmd->name, p->name) == 0) {
5623 			ret = -EBUSY;
5624 			goto out_unlock;
5625 		}
5626 	}
5627 	list_add(&cmd->list, &ftrace_commands);
5628  out_unlock:
5629 	mutex_unlock(&ftrace_cmd_mutex);
5630 
5631 	return ret;
5632 }
5633 
5634 /*
5635  * Currently we only unregister ftrace commands from __init, so mark
5636  * this __init too.
5637  */
unregister_ftrace_command(struct ftrace_func_command * cmd)5638 __init int unregister_ftrace_command(struct ftrace_func_command *cmd)
5639 {
5640 	struct ftrace_func_command *p, *n;
5641 	int ret = -ENODEV;
5642 
5643 	mutex_lock(&ftrace_cmd_mutex);
5644 	list_for_each_entry_safe(p, n, &ftrace_commands, list) {
5645 		if (strcmp(cmd->name, p->name) == 0) {
5646 			ret = 0;
5647 			list_del_init(&p->list);
5648 			goto out_unlock;
5649 		}
5650 	}
5651  out_unlock:
5652 	mutex_unlock(&ftrace_cmd_mutex);
5653 
5654 	return ret;
5655 }
5656 
ftrace_process_regex(struct ftrace_iterator * iter,char * buff,int len,int enable)5657 static int ftrace_process_regex(struct ftrace_iterator *iter,
5658 				char *buff, int len, int enable)
5659 {
5660 	struct ftrace_hash *hash = iter->hash;
5661 	struct trace_array *tr = iter->ops->private;
5662 	char *func, *command, *next = buff;
5663 	struct ftrace_func_command *p;
5664 	int ret = -EINVAL;
5665 
5666 	func = strsep(&next, ":");
5667 
5668 	if (!next) {
5669 		ret = ftrace_match_records(hash, func, len);
5670 		if (!ret)
5671 			ret = -EINVAL;
5672 		if (ret < 0)
5673 			return ret;
5674 		return 0;
5675 	}
5676 
5677 	/* command found */
5678 
5679 	command = strsep(&next, ":");
5680 
5681 	mutex_lock(&ftrace_cmd_mutex);
5682 	list_for_each_entry(p, &ftrace_commands, list) {
5683 		if (strcmp(p->name, command) == 0) {
5684 			ret = p->func(tr, hash, func, command, next, enable);
5685 			goto out_unlock;
5686 		}
5687 	}
5688  out_unlock:
5689 	mutex_unlock(&ftrace_cmd_mutex);
5690 
5691 	return ret;
5692 }
5693 
5694 static ssize_t
ftrace_regex_write(struct file * file,const char __user * ubuf,size_t cnt,loff_t * ppos,int enable)5695 ftrace_regex_write(struct file *file, const char __user *ubuf,
5696 		   size_t cnt, loff_t *ppos, int enable)
5697 {
5698 	struct ftrace_iterator *iter;
5699 	struct trace_parser *parser;
5700 	ssize_t ret, read;
5701 
5702 	if (!cnt)
5703 		return 0;
5704 
5705 	if (file->f_mode & FMODE_READ) {
5706 		struct seq_file *m = file->private_data;
5707 		iter = m->private;
5708 	} else
5709 		iter = file->private_data;
5710 
5711 	if (unlikely(ftrace_disabled))
5712 		return -ENODEV;
5713 
5714 	/* iter->hash is a local copy, so we don't need regex_lock */
5715 
5716 	parser = &iter->parser;
5717 	read = trace_get_user(parser, ubuf, cnt, ppos);
5718 
5719 	if (read >= 0 && trace_parser_loaded(parser) &&
5720 	    !trace_parser_cont(parser)) {
5721 		ret = ftrace_process_regex(iter, parser->buffer,
5722 					   parser->idx, enable);
5723 		trace_parser_clear(parser);
5724 		if (ret < 0)
5725 			goto out;
5726 	}
5727 
5728 	ret = read;
5729  out:
5730 	return ret;
5731 }
5732 
5733 ssize_t
ftrace_filter_write(struct file * file,const char __user * ubuf,size_t cnt,loff_t * ppos)5734 ftrace_filter_write(struct file *file, const char __user *ubuf,
5735 		    size_t cnt, loff_t *ppos)
5736 {
5737 	return ftrace_regex_write(file, ubuf, cnt, ppos, 1);
5738 }
5739 
5740 ssize_t
ftrace_notrace_write(struct file * file,const char __user * ubuf,size_t cnt,loff_t * ppos)5741 ftrace_notrace_write(struct file *file, const char __user *ubuf,
5742 		     size_t cnt, loff_t *ppos)
5743 {
5744 	return ftrace_regex_write(file, ubuf, cnt, ppos, 0);
5745 }
5746 
5747 static int
__ftrace_match_addr(struct ftrace_hash * hash,unsigned long ip,int remove)5748 __ftrace_match_addr(struct ftrace_hash *hash, unsigned long ip, int remove)
5749 {
5750 	struct ftrace_func_entry *entry;
5751 
5752 	ip = ftrace_location(ip);
5753 	if (!ip)
5754 		return -EINVAL;
5755 
5756 	if (remove) {
5757 		entry = ftrace_lookup_ip(hash, ip);
5758 		if (!entry)
5759 			return -ENOENT;
5760 		free_hash_entry(hash, entry);
5761 		return 0;
5762 	} else if (__ftrace_lookup_ip(hash, ip) != NULL) {
5763 		/* Already exists */
5764 		return 0;
5765 	}
5766 
5767 	entry = add_hash_entry(hash, ip);
5768 	return entry ? 0 :  -ENOMEM;
5769 }
5770 
5771 static int
ftrace_match_addr(struct ftrace_hash * hash,unsigned long * ips,unsigned int cnt,int remove)5772 ftrace_match_addr(struct ftrace_hash *hash, unsigned long *ips,
5773 		  unsigned int cnt, int remove)
5774 {
5775 	unsigned int i;
5776 	int err;
5777 
5778 	for (i = 0; i < cnt; i++) {
5779 		err = __ftrace_match_addr(hash, ips[i], remove);
5780 		if (err) {
5781 			/*
5782 			 * This expects the @hash is a temporary hash and if this
5783 			 * fails the caller must free the @hash.
5784 			 */
5785 			return err;
5786 		}
5787 	}
5788 	return 0;
5789 }
5790 
5791 static int
ftrace_set_hash(struct ftrace_ops * ops,unsigned char * buf,int len,unsigned long * ips,unsigned int cnt,int remove,int reset,int enable)5792 ftrace_set_hash(struct ftrace_ops *ops, unsigned char *buf, int len,
5793 		unsigned long *ips, unsigned int cnt,
5794 		int remove, int reset, int enable)
5795 {
5796 	struct ftrace_hash **orig_hash;
5797 	struct ftrace_hash *hash;
5798 	int ret;
5799 
5800 	if (unlikely(ftrace_disabled))
5801 		return -ENODEV;
5802 
5803 	mutex_lock(&ops->func_hash->regex_lock);
5804 
5805 	if (enable)
5806 		orig_hash = &ops->func_hash->filter_hash;
5807 	else
5808 		orig_hash = &ops->func_hash->notrace_hash;
5809 
5810 	if (reset)
5811 		hash = alloc_ftrace_hash(FTRACE_HASH_DEFAULT_BITS);
5812 	else
5813 		hash = alloc_and_copy_ftrace_hash(FTRACE_HASH_DEFAULT_BITS, *orig_hash);
5814 
5815 	if (!hash) {
5816 		ret = -ENOMEM;
5817 		goto out_regex_unlock;
5818 	}
5819 
5820 	if (buf && !ftrace_match_records(hash, buf, len)) {
5821 		ret = -EINVAL;
5822 		goto out_regex_unlock;
5823 	}
5824 	if (ips) {
5825 		ret = ftrace_match_addr(hash, ips, cnt, remove);
5826 		if (ret < 0)
5827 			goto out_regex_unlock;
5828 	}
5829 
5830 	mutex_lock(&ftrace_lock);
5831 	ret = ftrace_hash_move_and_update_ops(ops, orig_hash, hash, enable);
5832 	mutex_unlock(&ftrace_lock);
5833 
5834  out_regex_unlock:
5835 	mutex_unlock(&ops->func_hash->regex_lock);
5836 
5837 	free_ftrace_hash(hash);
5838 	return ret;
5839 }
5840 
5841 static int
ftrace_set_addr(struct ftrace_ops * ops,unsigned long * ips,unsigned int cnt,int remove,int reset,int enable)5842 ftrace_set_addr(struct ftrace_ops *ops, unsigned long *ips, unsigned int cnt,
5843 		int remove, int reset, int enable)
5844 {
5845 	return ftrace_set_hash(ops, NULL, 0, ips, cnt, remove, reset, enable);
5846 }
5847 
5848 #ifdef CONFIG_DYNAMIC_FTRACE_WITH_DIRECT_CALLS
5849 
5850 static int register_ftrace_function_nolock(struct ftrace_ops *ops);
5851 
5852 /*
5853  * If there are multiple ftrace_ops, use SAVE_REGS by default, so that direct
5854  * call will be jumped from ftrace_regs_caller. Only if the architecture does
5855  * not support ftrace_regs_caller but direct_call, use SAVE_ARGS so that it
5856  * jumps from ftrace_caller for multiple ftrace_ops.
5857  */
5858 #ifndef CONFIG_HAVE_DYNAMIC_FTRACE_WITH_REGS
5859 #define MULTI_FLAGS (FTRACE_OPS_FL_DIRECT | FTRACE_OPS_FL_SAVE_ARGS)
5860 #else
5861 #define MULTI_FLAGS (FTRACE_OPS_FL_DIRECT | FTRACE_OPS_FL_SAVE_REGS)
5862 #endif
5863 
check_direct_multi(struct ftrace_ops * ops)5864 static int check_direct_multi(struct ftrace_ops *ops)
5865 {
5866 	if (!(ops->flags & FTRACE_OPS_FL_INITIALIZED))
5867 		return -EINVAL;
5868 	if ((ops->flags & MULTI_FLAGS) != MULTI_FLAGS)
5869 		return -EINVAL;
5870 	return 0;
5871 }
5872 
remove_direct_functions_hash(struct ftrace_hash * hash,unsigned long addr)5873 static void remove_direct_functions_hash(struct ftrace_hash *hash, unsigned long addr)
5874 {
5875 	struct ftrace_func_entry *entry, *del;
5876 	int size, i;
5877 
5878 	size = 1 << hash->size_bits;
5879 	for (i = 0; i < size; i++) {
5880 		hlist_for_each_entry(entry, &hash->buckets[i], hlist) {
5881 			del = __ftrace_lookup_ip(direct_functions, entry->ip);
5882 			if (del && del->direct == addr) {
5883 				remove_hash_entry(direct_functions, del);
5884 				kfree(del);
5885 			}
5886 		}
5887 	}
5888 }
5889 
register_ftrace_direct_cb(struct rcu_head * rhp)5890 static void register_ftrace_direct_cb(struct rcu_head *rhp)
5891 {
5892 	struct ftrace_hash *fhp = container_of(rhp, struct ftrace_hash, rcu);
5893 
5894 	free_ftrace_hash(fhp);
5895 }
5896 
5897 /**
5898  * register_ftrace_direct - Call a custom trampoline directly
5899  * for multiple functions registered in @ops
5900  * @ops: The address of the struct ftrace_ops object
5901  * @addr: The address of the trampoline to call at @ops functions
5902  *
5903  * This is used to connect a direct calls to @addr from the nop locations
5904  * of the functions registered in @ops (with by ftrace_set_filter_ip
5905  * function).
5906  *
5907  * The location that it calls (@addr) must be able to handle a direct call,
5908  * and save the parameters of the function being traced, and restore them
5909  * (or inject new ones if needed), before returning.
5910  *
5911  * Returns:
5912  *  0 on success
5913  *  -EINVAL  - The @ops object was already registered with this call or
5914  *             when there are no functions in @ops object.
5915  *  -EBUSY   - Another direct function is already attached (there can be only one)
5916  *  -ENODEV  - @ip does not point to a ftrace nop location (or not supported)
5917  *  -ENOMEM  - There was an allocation failure.
5918  */
register_ftrace_direct(struct ftrace_ops * ops,unsigned long addr)5919 int register_ftrace_direct(struct ftrace_ops *ops, unsigned long addr)
5920 {
5921 	struct ftrace_hash *hash, *new_hash = NULL, *free_hash = NULL;
5922 	struct ftrace_func_entry *entry, *new;
5923 	int err = -EBUSY, size, i;
5924 
5925 	if (ops->func || ops->trampoline)
5926 		return -EINVAL;
5927 	if (!(ops->flags & FTRACE_OPS_FL_INITIALIZED))
5928 		return -EINVAL;
5929 	if (ops->flags & FTRACE_OPS_FL_ENABLED)
5930 		return -EINVAL;
5931 
5932 	hash = ops->func_hash->filter_hash;
5933 	if (ftrace_hash_empty(hash))
5934 		return -EINVAL;
5935 
5936 	mutex_lock(&direct_mutex);
5937 
5938 	/* Make sure requested entries are not already registered.. */
5939 	size = 1 << hash->size_bits;
5940 	for (i = 0; i < size; i++) {
5941 		hlist_for_each_entry(entry, &hash->buckets[i], hlist) {
5942 			if (ftrace_find_rec_direct(entry->ip))
5943 				goto out_unlock;
5944 		}
5945 	}
5946 
5947 	err = -ENOMEM;
5948 
5949 	/* Make a copy hash to place the new and the old entries in */
5950 	size = hash->count + direct_functions->count;
5951 	size = fls(size);
5952 	if (size > FTRACE_HASH_MAX_BITS)
5953 		size = FTRACE_HASH_MAX_BITS;
5954 	new_hash = alloc_ftrace_hash(size);
5955 	if (!new_hash)
5956 		goto out_unlock;
5957 
5958 	/* Now copy over the existing direct entries */
5959 	size = 1 << direct_functions->size_bits;
5960 	for (i = 0; i < size; i++) {
5961 		hlist_for_each_entry(entry, &direct_functions->buckets[i], hlist) {
5962 			new = add_hash_entry(new_hash, entry->ip);
5963 			if (!new)
5964 				goto out_unlock;
5965 			new->direct = entry->direct;
5966 		}
5967 	}
5968 
5969 	/* ... and add the new entries */
5970 	size = 1 << hash->size_bits;
5971 	for (i = 0; i < size; i++) {
5972 		hlist_for_each_entry(entry, &hash->buckets[i], hlist) {
5973 			new = add_hash_entry(new_hash, entry->ip);
5974 			if (!new)
5975 				goto out_unlock;
5976 			/* Update both the copy and the hash entry */
5977 			new->direct = addr;
5978 			entry->direct = addr;
5979 		}
5980 	}
5981 
5982 	free_hash = direct_functions;
5983 	rcu_assign_pointer(direct_functions, new_hash);
5984 	new_hash = NULL;
5985 
5986 	ops->func = call_direct_funcs;
5987 	ops->flags = MULTI_FLAGS;
5988 	ops->trampoline = FTRACE_REGS_ADDR;
5989 	ops->direct_call = addr;
5990 
5991 	err = register_ftrace_function_nolock(ops);
5992 
5993  out_unlock:
5994 	mutex_unlock(&direct_mutex);
5995 
5996 	if (free_hash && free_hash != EMPTY_HASH)
5997 		call_rcu_tasks(&free_hash->rcu, register_ftrace_direct_cb);
5998 
5999 	if (new_hash)
6000 		free_ftrace_hash(new_hash);
6001 
6002 	return err;
6003 }
6004 EXPORT_SYMBOL_GPL(register_ftrace_direct);
6005 
6006 /**
6007  * unregister_ftrace_direct - Remove calls to custom trampoline
6008  * previously registered by register_ftrace_direct for @ops object.
6009  * @ops: The address of the struct ftrace_ops object
6010  * @addr: The address of the direct function that is called by the @ops functions
6011  * @free_filters: Set to true to remove all filters for the ftrace_ops, false otherwise
6012  *
6013  * This is used to remove a direct calls to @addr from the nop locations
6014  * of the functions registered in @ops (with by ftrace_set_filter_ip
6015  * function).
6016  *
6017  * Returns:
6018  *  0 on success
6019  *  -EINVAL - The @ops object was not properly registered.
6020  */
unregister_ftrace_direct(struct ftrace_ops * ops,unsigned long addr,bool free_filters)6021 int unregister_ftrace_direct(struct ftrace_ops *ops, unsigned long addr,
6022 			     bool free_filters)
6023 {
6024 	struct ftrace_hash *hash = ops->func_hash->filter_hash;
6025 	int err;
6026 
6027 	if (check_direct_multi(ops))
6028 		return -EINVAL;
6029 	if (!(ops->flags & FTRACE_OPS_FL_ENABLED))
6030 		return -EINVAL;
6031 
6032 	mutex_lock(&direct_mutex);
6033 	err = unregister_ftrace_function(ops);
6034 	remove_direct_functions_hash(hash, addr);
6035 	mutex_unlock(&direct_mutex);
6036 
6037 	/* cleanup for possible another register call */
6038 	ops->func = NULL;
6039 	ops->trampoline = 0;
6040 
6041 	if (free_filters)
6042 		ftrace_free_filter(ops);
6043 	return err;
6044 }
6045 EXPORT_SYMBOL_GPL(unregister_ftrace_direct);
6046 
6047 static int
__modify_ftrace_direct(struct ftrace_ops * ops,unsigned long addr)6048 __modify_ftrace_direct(struct ftrace_ops *ops, unsigned long addr)
6049 {
6050 	struct ftrace_hash *hash;
6051 	struct ftrace_func_entry *entry, *iter;
6052 	static struct ftrace_ops tmp_ops = {
6053 		.func		= ftrace_stub,
6054 		.flags		= FTRACE_OPS_FL_STUB,
6055 	};
6056 	int i, size;
6057 	int err;
6058 
6059 	lockdep_assert_held_once(&direct_mutex);
6060 
6061 	/* Enable the tmp_ops to have the same functions as the direct ops */
6062 	ftrace_ops_init(&tmp_ops);
6063 	tmp_ops.func_hash = ops->func_hash;
6064 	tmp_ops.direct_call = addr;
6065 
6066 	err = register_ftrace_function_nolock(&tmp_ops);
6067 	if (err)
6068 		return err;
6069 
6070 	/*
6071 	 * Now the ftrace_ops_list_func() is called to do the direct callers.
6072 	 * We can safely change the direct functions attached to each entry.
6073 	 */
6074 	mutex_lock(&ftrace_lock);
6075 
6076 	hash = ops->func_hash->filter_hash;
6077 	size = 1 << hash->size_bits;
6078 	for (i = 0; i < size; i++) {
6079 		hlist_for_each_entry(iter, &hash->buckets[i], hlist) {
6080 			entry = __ftrace_lookup_ip(direct_functions, iter->ip);
6081 			if (!entry)
6082 				continue;
6083 			entry->direct = addr;
6084 		}
6085 	}
6086 	/* Prevent store tearing if a trampoline concurrently accesses the value */
6087 	WRITE_ONCE(ops->direct_call, addr);
6088 
6089 	mutex_unlock(&ftrace_lock);
6090 
6091 	/* Removing the tmp_ops will add the updated direct callers to the functions */
6092 	unregister_ftrace_function(&tmp_ops);
6093 
6094 	return err;
6095 }
6096 
6097 /**
6098  * modify_ftrace_direct_nolock - Modify an existing direct 'multi' call
6099  * to call something else
6100  * @ops: The address of the struct ftrace_ops object
6101  * @addr: The address of the new trampoline to call at @ops functions
6102  *
6103  * This is used to unregister currently registered direct caller and
6104  * register new one @addr on functions registered in @ops object.
6105  *
6106  * Note there's window between ftrace_shutdown and ftrace_startup calls
6107  * where there will be no callbacks called.
6108  *
6109  * Caller should already have direct_mutex locked, so we don't lock
6110  * direct_mutex here.
6111  *
6112  * Returns: zero on success. Non zero on error, which includes:
6113  *  -EINVAL - The @ops object was not properly registered.
6114  */
modify_ftrace_direct_nolock(struct ftrace_ops * ops,unsigned long addr)6115 int modify_ftrace_direct_nolock(struct ftrace_ops *ops, unsigned long addr)
6116 {
6117 	if (check_direct_multi(ops))
6118 		return -EINVAL;
6119 	if (!(ops->flags & FTRACE_OPS_FL_ENABLED))
6120 		return -EINVAL;
6121 
6122 	return __modify_ftrace_direct(ops, addr);
6123 }
6124 EXPORT_SYMBOL_GPL(modify_ftrace_direct_nolock);
6125 
6126 /**
6127  * modify_ftrace_direct - Modify an existing direct 'multi' call
6128  * to call something else
6129  * @ops: The address of the struct ftrace_ops object
6130  * @addr: The address of the new trampoline to call at @ops functions
6131  *
6132  * This is used to unregister currently registered direct caller and
6133  * register new one @addr on functions registered in @ops object.
6134  *
6135  * Note there's window between ftrace_shutdown and ftrace_startup calls
6136  * where there will be no callbacks called.
6137  *
6138  * Returns: zero on success. Non zero on error, which includes:
6139  *  -EINVAL - The @ops object was not properly registered.
6140  */
modify_ftrace_direct(struct ftrace_ops * ops,unsigned long addr)6141 int modify_ftrace_direct(struct ftrace_ops *ops, unsigned long addr)
6142 {
6143 	int err;
6144 
6145 	if (check_direct_multi(ops))
6146 		return -EINVAL;
6147 	if (!(ops->flags & FTRACE_OPS_FL_ENABLED))
6148 		return -EINVAL;
6149 
6150 	mutex_lock(&direct_mutex);
6151 	err = __modify_ftrace_direct(ops, addr);
6152 	mutex_unlock(&direct_mutex);
6153 	return err;
6154 }
6155 EXPORT_SYMBOL_GPL(modify_ftrace_direct);
6156 #endif /* CONFIG_DYNAMIC_FTRACE_WITH_DIRECT_CALLS */
6157 
6158 /**
6159  * ftrace_set_filter_ip - set a function to filter on in ftrace by address
6160  * @ops: the ops to set the filter with
6161  * @ip: the address to add to or remove from the filter.
6162  * @remove: non zero to remove the ip from the filter
6163  * @reset: non zero to reset all filters before applying this filter.
6164  *
6165  * Filters denote which functions should be enabled when tracing is enabled
6166  * If @ip is NULL, it fails to update filter.
6167  *
6168  * This can allocate memory which must be freed before @ops can be freed,
6169  * either by removing each filtered addr or by using
6170  * ftrace_free_filter(@ops).
6171  */
ftrace_set_filter_ip(struct ftrace_ops * ops,unsigned long ip,int remove,int reset)6172 int ftrace_set_filter_ip(struct ftrace_ops *ops, unsigned long ip,
6173 			 int remove, int reset)
6174 {
6175 	ftrace_ops_init(ops);
6176 	return ftrace_set_addr(ops, &ip, 1, remove, reset, 1);
6177 }
6178 EXPORT_SYMBOL_GPL(ftrace_set_filter_ip);
6179 
6180 /**
6181  * ftrace_set_filter_ips - set functions to filter on in ftrace by addresses
6182  * @ops: the ops to set the filter with
6183  * @ips: the array of addresses to add to or remove from the filter.
6184  * @cnt: the number of addresses in @ips
6185  * @remove: non zero to remove ips from the filter
6186  * @reset: non zero to reset all filters before applying this filter.
6187  *
6188  * Filters denote which functions should be enabled when tracing is enabled
6189  * If @ips array or any ip specified within is NULL , it fails to update filter.
6190  *
6191  * This can allocate memory which must be freed before @ops can be freed,
6192  * either by removing each filtered addr or by using
6193  * ftrace_free_filter(@ops).
6194 */
ftrace_set_filter_ips(struct ftrace_ops * ops,unsigned long * ips,unsigned int cnt,int remove,int reset)6195 int ftrace_set_filter_ips(struct ftrace_ops *ops, unsigned long *ips,
6196 			  unsigned int cnt, int remove, int reset)
6197 {
6198 	ftrace_ops_init(ops);
6199 	return ftrace_set_addr(ops, ips, cnt, remove, reset, 1);
6200 }
6201 EXPORT_SYMBOL_GPL(ftrace_set_filter_ips);
6202 
6203 /**
6204  * ftrace_ops_set_global_filter - setup ops to use global filters
6205  * @ops: the ops which will use the global filters
6206  *
6207  * ftrace users who need global function trace filtering should call this.
6208  * It can set the global filter only if ops were not initialized before.
6209  */
ftrace_ops_set_global_filter(struct ftrace_ops * ops)6210 void ftrace_ops_set_global_filter(struct ftrace_ops *ops)
6211 {
6212 	if (ops->flags & FTRACE_OPS_FL_INITIALIZED)
6213 		return;
6214 
6215 	ftrace_ops_init(ops);
6216 	ops->func_hash = &global_ops.local_hash;
6217 }
6218 EXPORT_SYMBOL_GPL(ftrace_ops_set_global_filter);
6219 
6220 static int
ftrace_set_regex(struct ftrace_ops * ops,unsigned char * buf,int len,int reset,int enable)6221 ftrace_set_regex(struct ftrace_ops *ops, unsigned char *buf, int len,
6222 		 int reset, int enable)
6223 {
6224 	return ftrace_set_hash(ops, buf, len, NULL, 0, 0, reset, enable);
6225 }
6226 
6227 /**
6228  * ftrace_set_filter - set a function to filter on in ftrace
6229  * @ops: the ops to set the filter with
6230  * @buf: the string that holds the function filter text.
6231  * @len: the length of the string.
6232  * @reset: non-zero to reset all filters before applying this filter.
6233  *
6234  * Filters denote which functions should be enabled when tracing is enabled.
6235  * If @buf is NULL and reset is set, all functions will be enabled for tracing.
6236  *
6237  * This can allocate memory which must be freed before @ops can be freed,
6238  * either by removing each filtered addr or by using
6239  * ftrace_free_filter(@ops).
6240  */
ftrace_set_filter(struct ftrace_ops * ops,unsigned char * buf,int len,int reset)6241 int ftrace_set_filter(struct ftrace_ops *ops, unsigned char *buf,
6242 		       int len, int reset)
6243 {
6244 	ftrace_ops_init(ops);
6245 	return ftrace_set_regex(ops, buf, len, reset, 1);
6246 }
6247 EXPORT_SYMBOL_GPL(ftrace_set_filter);
6248 
6249 /**
6250  * ftrace_set_notrace - set a function to not trace in ftrace
6251  * @ops: the ops to set the notrace filter with
6252  * @buf: the string that holds the function notrace text.
6253  * @len: the length of the string.
6254  * @reset: non-zero to reset all filters before applying this filter.
6255  *
6256  * Notrace Filters denote which functions should not be enabled when tracing
6257  * is enabled. If @buf is NULL and reset is set, all functions will be enabled
6258  * for tracing.
6259  *
6260  * This can allocate memory which must be freed before @ops can be freed,
6261  * either by removing each filtered addr or by using
6262  * ftrace_free_filter(@ops).
6263  */
ftrace_set_notrace(struct ftrace_ops * ops,unsigned char * buf,int len,int reset)6264 int ftrace_set_notrace(struct ftrace_ops *ops, unsigned char *buf,
6265 			int len, int reset)
6266 {
6267 	ftrace_ops_init(ops);
6268 	return ftrace_set_regex(ops, buf, len, reset, 0);
6269 }
6270 EXPORT_SYMBOL_GPL(ftrace_set_notrace);
6271 /**
6272  * ftrace_set_global_filter - set a function to filter on with global tracers
6273  * @buf: the string that holds the function filter text.
6274  * @len: the length of the string.
6275  * @reset: non-zero to reset all filters before applying this filter.
6276  *
6277  * Filters denote which functions should be enabled when tracing is enabled.
6278  * If @buf is NULL and reset is set, all functions will be enabled for tracing.
6279  */
ftrace_set_global_filter(unsigned char * buf,int len,int reset)6280 void ftrace_set_global_filter(unsigned char *buf, int len, int reset)
6281 {
6282 	ftrace_set_regex(&global_ops, buf, len, reset, 1);
6283 }
6284 EXPORT_SYMBOL_GPL(ftrace_set_global_filter);
6285 
6286 /**
6287  * ftrace_set_global_notrace - set a function to not trace with global tracers
6288  * @buf: the string that holds the function notrace text.
6289  * @len: the length of the string.
6290  * @reset: non-zero to reset all filters before applying this filter.
6291  *
6292  * Notrace Filters denote which functions should not be enabled when tracing
6293  * is enabled. If @buf is NULL and reset is set, all functions will be enabled
6294  * for tracing.
6295  */
ftrace_set_global_notrace(unsigned char * buf,int len,int reset)6296 void ftrace_set_global_notrace(unsigned char *buf, int len, int reset)
6297 {
6298 	ftrace_set_regex(&global_ops, buf, len, reset, 0);
6299 }
6300 EXPORT_SYMBOL_GPL(ftrace_set_global_notrace);
6301 
6302 /*
6303  * command line interface to allow users to set filters on boot up.
6304  */
6305 #define FTRACE_FILTER_SIZE		COMMAND_LINE_SIZE
6306 static char ftrace_notrace_buf[FTRACE_FILTER_SIZE] __initdata;
6307 static char ftrace_filter_buf[FTRACE_FILTER_SIZE] __initdata;
6308 
6309 /* Used by function selftest to not test if filter is set */
6310 bool ftrace_filter_param __initdata;
6311 
set_ftrace_notrace(char * str)6312 static int __init set_ftrace_notrace(char *str)
6313 {
6314 	ftrace_filter_param = true;
6315 	strscpy(ftrace_notrace_buf, str, FTRACE_FILTER_SIZE);
6316 	return 1;
6317 }
6318 __setup("ftrace_notrace=", set_ftrace_notrace);
6319 
set_ftrace_filter(char * str)6320 static int __init set_ftrace_filter(char *str)
6321 {
6322 	ftrace_filter_param = true;
6323 	strscpy(ftrace_filter_buf, str, FTRACE_FILTER_SIZE);
6324 	return 1;
6325 }
6326 __setup("ftrace_filter=", set_ftrace_filter);
6327 
6328 #ifdef CONFIG_FUNCTION_GRAPH_TRACER
6329 static char ftrace_graph_buf[FTRACE_FILTER_SIZE] __initdata;
6330 static char ftrace_graph_notrace_buf[FTRACE_FILTER_SIZE] __initdata;
6331 static int ftrace_graph_set_hash(struct ftrace_hash *hash, char *buffer);
6332 
set_graph_function(char * str)6333 static int __init set_graph_function(char *str)
6334 {
6335 	strscpy(ftrace_graph_buf, str, FTRACE_FILTER_SIZE);
6336 	return 1;
6337 }
6338 __setup("ftrace_graph_filter=", set_graph_function);
6339 
set_graph_notrace_function(char * str)6340 static int __init set_graph_notrace_function(char *str)
6341 {
6342 	strscpy(ftrace_graph_notrace_buf, str, FTRACE_FILTER_SIZE);
6343 	return 1;
6344 }
6345 __setup("ftrace_graph_notrace=", set_graph_notrace_function);
6346 
set_graph_max_depth_function(char * str)6347 static int __init set_graph_max_depth_function(char *str)
6348 {
6349 	if (!str || kstrtouint(str, 0, &fgraph_max_depth))
6350 		return 0;
6351 	return 1;
6352 }
6353 __setup("ftrace_graph_max_depth=", set_graph_max_depth_function);
6354 
set_ftrace_early_graph(char * buf,int enable)6355 static void __init set_ftrace_early_graph(char *buf, int enable)
6356 {
6357 	int ret;
6358 	char *func;
6359 	struct ftrace_hash *hash;
6360 
6361 	hash = alloc_ftrace_hash(FTRACE_HASH_DEFAULT_BITS);
6362 	if (MEM_FAIL(!hash, "Failed to allocate hash\n"))
6363 		return;
6364 
6365 	while (buf) {
6366 		func = strsep(&buf, ",");
6367 		/* we allow only one expression at a time */
6368 		ret = ftrace_graph_set_hash(hash, func);
6369 		if (ret)
6370 			printk(KERN_DEBUG "ftrace: function %s not "
6371 					  "traceable\n", func);
6372 	}
6373 
6374 	if (enable)
6375 		ftrace_graph_hash = hash;
6376 	else
6377 		ftrace_graph_notrace_hash = hash;
6378 }
6379 #endif /* CONFIG_FUNCTION_GRAPH_TRACER */
6380 
6381 void __init
ftrace_set_early_filter(struct ftrace_ops * ops,char * buf,int enable)6382 ftrace_set_early_filter(struct ftrace_ops *ops, char *buf, int enable)
6383 {
6384 	char *func;
6385 
6386 	ftrace_ops_init(ops);
6387 
6388 	while (buf) {
6389 		func = strsep(&buf, ",");
6390 		ftrace_set_regex(ops, func, strlen(func), 0, enable);
6391 	}
6392 }
6393 
set_ftrace_early_filters(void)6394 static void __init set_ftrace_early_filters(void)
6395 {
6396 	if (ftrace_filter_buf[0])
6397 		ftrace_set_early_filter(&global_ops, ftrace_filter_buf, 1);
6398 	if (ftrace_notrace_buf[0])
6399 		ftrace_set_early_filter(&global_ops, ftrace_notrace_buf, 0);
6400 #ifdef CONFIG_FUNCTION_GRAPH_TRACER
6401 	if (ftrace_graph_buf[0])
6402 		set_ftrace_early_graph(ftrace_graph_buf, 1);
6403 	if (ftrace_graph_notrace_buf[0])
6404 		set_ftrace_early_graph(ftrace_graph_notrace_buf, 0);
6405 #endif /* CONFIG_FUNCTION_GRAPH_TRACER */
6406 }
6407 
ftrace_regex_release(struct inode * inode,struct file * file)6408 int ftrace_regex_release(struct inode *inode, struct file *file)
6409 {
6410 	struct seq_file *m = (struct seq_file *)file->private_data;
6411 	struct ftrace_iterator *iter;
6412 	struct ftrace_hash **orig_hash;
6413 	struct trace_parser *parser;
6414 	int filter_hash;
6415 
6416 	if (file->f_mode & FMODE_READ) {
6417 		iter = m->private;
6418 		seq_release(inode, file);
6419 	} else
6420 		iter = file->private_data;
6421 
6422 	parser = &iter->parser;
6423 	if (trace_parser_loaded(parser)) {
6424 		int enable = !(iter->flags & FTRACE_ITER_NOTRACE);
6425 
6426 		ftrace_process_regex(iter, parser->buffer,
6427 				     parser->idx, enable);
6428 	}
6429 
6430 	trace_parser_put(parser);
6431 
6432 	mutex_lock(&iter->ops->func_hash->regex_lock);
6433 
6434 	if (file->f_mode & FMODE_WRITE) {
6435 		filter_hash = !!(iter->flags & FTRACE_ITER_FILTER);
6436 
6437 		if (filter_hash) {
6438 			orig_hash = &iter->ops->func_hash->filter_hash;
6439 			if (iter->tr) {
6440 				if (list_empty(&iter->tr->mod_trace))
6441 					iter->hash->flags &= ~FTRACE_HASH_FL_MOD;
6442 				else
6443 					iter->hash->flags |= FTRACE_HASH_FL_MOD;
6444 			}
6445 		} else
6446 			orig_hash = &iter->ops->func_hash->notrace_hash;
6447 
6448 		mutex_lock(&ftrace_lock);
6449 		ftrace_hash_move_and_update_ops(iter->ops, orig_hash,
6450 						      iter->hash, filter_hash);
6451 		mutex_unlock(&ftrace_lock);
6452 	}
6453 
6454 	mutex_unlock(&iter->ops->func_hash->regex_lock);
6455 	free_ftrace_hash(iter->hash);
6456 	if (iter->tr)
6457 		trace_array_put(iter->tr);
6458 	kfree(iter);
6459 
6460 	return 0;
6461 }
6462 
6463 static const struct file_operations ftrace_avail_fops = {
6464 	.open = ftrace_avail_open,
6465 	.read = seq_read,
6466 	.llseek = seq_lseek,
6467 	.release = seq_release_private,
6468 };
6469 
6470 static const struct file_operations ftrace_enabled_fops = {
6471 	.open = ftrace_enabled_open,
6472 	.read = seq_read,
6473 	.llseek = seq_lseek,
6474 	.release = seq_release_private,
6475 };
6476 
6477 static const struct file_operations ftrace_touched_fops = {
6478 	.open = ftrace_touched_open,
6479 	.read = seq_read,
6480 	.llseek = seq_lseek,
6481 	.release = seq_release_private,
6482 };
6483 
6484 static const struct file_operations ftrace_avail_addrs_fops = {
6485 	.open = ftrace_avail_addrs_open,
6486 	.read = seq_read,
6487 	.llseek = seq_lseek,
6488 	.release = seq_release_private,
6489 };
6490 
6491 static const struct file_operations ftrace_filter_fops = {
6492 	.open = ftrace_filter_open,
6493 	.read = seq_read,
6494 	.write = ftrace_filter_write,
6495 	.llseek = tracing_lseek,
6496 	.release = ftrace_regex_release,
6497 };
6498 
6499 static const struct file_operations ftrace_notrace_fops = {
6500 	.open = ftrace_notrace_open,
6501 	.read = seq_read,
6502 	.write = ftrace_notrace_write,
6503 	.llseek = tracing_lseek,
6504 	.release = ftrace_regex_release,
6505 };
6506 
6507 #ifdef CONFIG_FUNCTION_GRAPH_TRACER
6508 
6509 static DEFINE_MUTEX(graph_lock);
6510 
6511 struct ftrace_hash __rcu *ftrace_graph_hash = EMPTY_HASH;
6512 struct ftrace_hash __rcu *ftrace_graph_notrace_hash = EMPTY_HASH;
6513 
6514 enum graph_filter_type {
6515 	GRAPH_FILTER_NOTRACE	= 0,
6516 	GRAPH_FILTER_FUNCTION,
6517 };
6518 
6519 #define FTRACE_GRAPH_EMPTY	((void *)1)
6520 
6521 struct ftrace_graph_data {
6522 	struct ftrace_hash		*hash;
6523 	struct ftrace_func_entry	*entry;
6524 	int				idx;   /* for hash table iteration */
6525 	enum graph_filter_type		type;
6526 	struct ftrace_hash		*new_hash;
6527 	const struct seq_operations	*seq_ops;
6528 	struct trace_parser		parser;
6529 };
6530 
6531 static void *
__g_next(struct seq_file * m,loff_t * pos)6532 __g_next(struct seq_file *m, loff_t *pos)
6533 {
6534 	struct ftrace_graph_data *fgd = m->private;
6535 	struct ftrace_func_entry *entry = fgd->entry;
6536 	struct hlist_head *head;
6537 	int i, idx = fgd->idx;
6538 
6539 	if (*pos >= fgd->hash->count)
6540 		return NULL;
6541 
6542 	if (entry) {
6543 		hlist_for_each_entry_continue(entry, hlist) {
6544 			fgd->entry = entry;
6545 			return entry;
6546 		}
6547 
6548 		idx++;
6549 	}
6550 
6551 	for (i = idx; i < 1 << fgd->hash->size_bits; i++) {
6552 		head = &fgd->hash->buckets[i];
6553 		hlist_for_each_entry(entry, head, hlist) {
6554 			fgd->entry = entry;
6555 			fgd->idx = i;
6556 			return entry;
6557 		}
6558 	}
6559 	return NULL;
6560 }
6561 
6562 static void *
g_next(struct seq_file * m,void * v,loff_t * pos)6563 g_next(struct seq_file *m, void *v, loff_t *pos)
6564 {
6565 	(*pos)++;
6566 	return __g_next(m, pos);
6567 }
6568 
g_start(struct seq_file * m,loff_t * pos)6569 static void *g_start(struct seq_file *m, loff_t *pos)
6570 {
6571 	struct ftrace_graph_data *fgd = m->private;
6572 
6573 	mutex_lock(&graph_lock);
6574 
6575 	if (fgd->type == GRAPH_FILTER_FUNCTION)
6576 		fgd->hash = rcu_dereference_protected(ftrace_graph_hash,
6577 					lockdep_is_held(&graph_lock));
6578 	else
6579 		fgd->hash = rcu_dereference_protected(ftrace_graph_notrace_hash,
6580 					lockdep_is_held(&graph_lock));
6581 
6582 	/* Nothing, tell g_show to print all functions are enabled */
6583 	if (ftrace_hash_empty(fgd->hash) && !*pos)
6584 		return FTRACE_GRAPH_EMPTY;
6585 
6586 	fgd->idx = 0;
6587 	fgd->entry = NULL;
6588 	return __g_next(m, pos);
6589 }
6590 
g_stop(struct seq_file * m,void * p)6591 static void g_stop(struct seq_file *m, void *p)
6592 {
6593 	mutex_unlock(&graph_lock);
6594 }
6595 
g_show(struct seq_file * m,void * v)6596 static int g_show(struct seq_file *m, void *v)
6597 {
6598 	struct ftrace_func_entry *entry = v;
6599 
6600 	if (!entry)
6601 		return 0;
6602 
6603 	if (entry == FTRACE_GRAPH_EMPTY) {
6604 		struct ftrace_graph_data *fgd = m->private;
6605 
6606 		if (fgd->type == GRAPH_FILTER_FUNCTION)
6607 			seq_puts(m, "#### all functions enabled ####\n");
6608 		else
6609 			seq_puts(m, "#### no functions disabled ####\n");
6610 		return 0;
6611 	}
6612 
6613 	seq_printf(m, "%ps\n", (void *)entry->ip);
6614 
6615 	return 0;
6616 }
6617 
6618 static const struct seq_operations ftrace_graph_seq_ops = {
6619 	.start = g_start,
6620 	.next = g_next,
6621 	.stop = g_stop,
6622 	.show = g_show,
6623 };
6624 
6625 static int
__ftrace_graph_open(struct inode * inode,struct file * file,struct ftrace_graph_data * fgd)6626 __ftrace_graph_open(struct inode *inode, struct file *file,
6627 		    struct ftrace_graph_data *fgd)
6628 {
6629 	int ret;
6630 	struct ftrace_hash *new_hash = NULL;
6631 
6632 	ret = security_locked_down(LOCKDOWN_TRACEFS);
6633 	if (ret)
6634 		return ret;
6635 
6636 	if (file->f_mode & FMODE_WRITE) {
6637 		const int size_bits = FTRACE_HASH_DEFAULT_BITS;
6638 
6639 		if (trace_parser_get_init(&fgd->parser, FTRACE_BUFF_MAX))
6640 			return -ENOMEM;
6641 
6642 		if (file->f_flags & O_TRUNC)
6643 			new_hash = alloc_ftrace_hash(size_bits);
6644 		else
6645 			new_hash = alloc_and_copy_ftrace_hash(size_bits,
6646 							      fgd->hash);
6647 		if (!new_hash) {
6648 			ret = -ENOMEM;
6649 			goto out;
6650 		}
6651 	}
6652 
6653 	if (file->f_mode & FMODE_READ) {
6654 		ret = seq_open(file, &ftrace_graph_seq_ops);
6655 		if (!ret) {
6656 			struct seq_file *m = file->private_data;
6657 			m->private = fgd;
6658 		} else {
6659 			/* Failed */
6660 			free_ftrace_hash(new_hash);
6661 			new_hash = NULL;
6662 		}
6663 	} else
6664 		file->private_data = fgd;
6665 
6666 out:
6667 	if (ret < 0 && file->f_mode & FMODE_WRITE)
6668 		trace_parser_put(&fgd->parser);
6669 
6670 	fgd->new_hash = new_hash;
6671 
6672 	/*
6673 	 * All uses of fgd->hash must be taken with the graph_lock
6674 	 * held. The graph_lock is going to be released, so force
6675 	 * fgd->hash to be reinitialized when it is taken again.
6676 	 */
6677 	fgd->hash = NULL;
6678 
6679 	return ret;
6680 }
6681 
6682 static int
ftrace_graph_open(struct inode * inode,struct file * file)6683 ftrace_graph_open(struct inode *inode, struct file *file)
6684 {
6685 	struct ftrace_graph_data *fgd;
6686 	int ret;
6687 
6688 	if (unlikely(ftrace_disabled))
6689 		return -ENODEV;
6690 
6691 	fgd = kmalloc(sizeof(*fgd), GFP_KERNEL);
6692 	if (fgd == NULL)
6693 		return -ENOMEM;
6694 
6695 	mutex_lock(&graph_lock);
6696 
6697 	fgd->hash = rcu_dereference_protected(ftrace_graph_hash,
6698 					lockdep_is_held(&graph_lock));
6699 	fgd->type = GRAPH_FILTER_FUNCTION;
6700 	fgd->seq_ops = &ftrace_graph_seq_ops;
6701 
6702 	ret = __ftrace_graph_open(inode, file, fgd);
6703 	if (ret < 0)
6704 		kfree(fgd);
6705 
6706 	mutex_unlock(&graph_lock);
6707 	return ret;
6708 }
6709 
6710 static int
ftrace_graph_notrace_open(struct inode * inode,struct file * file)6711 ftrace_graph_notrace_open(struct inode *inode, struct file *file)
6712 {
6713 	struct ftrace_graph_data *fgd;
6714 	int ret;
6715 
6716 	if (unlikely(ftrace_disabled))
6717 		return -ENODEV;
6718 
6719 	fgd = kmalloc(sizeof(*fgd), GFP_KERNEL);
6720 	if (fgd == NULL)
6721 		return -ENOMEM;
6722 
6723 	mutex_lock(&graph_lock);
6724 
6725 	fgd->hash = rcu_dereference_protected(ftrace_graph_notrace_hash,
6726 					lockdep_is_held(&graph_lock));
6727 	fgd->type = GRAPH_FILTER_NOTRACE;
6728 	fgd->seq_ops = &ftrace_graph_seq_ops;
6729 
6730 	ret = __ftrace_graph_open(inode, file, fgd);
6731 	if (ret < 0)
6732 		kfree(fgd);
6733 
6734 	mutex_unlock(&graph_lock);
6735 	return ret;
6736 }
6737 
6738 static int
ftrace_graph_release(struct inode * inode,struct file * file)6739 ftrace_graph_release(struct inode *inode, struct file *file)
6740 {
6741 	struct ftrace_graph_data *fgd;
6742 	struct ftrace_hash *old_hash, *new_hash;
6743 	struct trace_parser *parser;
6744 	int ret = 0;
6745 
6746 	if (file->f_mode & FMODE_READ) {
6747 		struct seq_file *m = file->private_data;
6748 
6749 		fgd = m->private;
6750 		seq_release(inode, file);
6751 	} else {
6752 		fgd = file->private_data;
6753 	}
6754 
6755 
6756 	if (file->f_mode & FMODE_WRITE) {
6757 
6758 		parser = &fgd->parser;
6759 
6760 		if (trace_parser_loaded((parser))) {
6761 			ret = ftrace_graph_set_hash(fgd->new_hash,
6762 						    parser->buffer);
6763 		}
6764 
6765 		trace_parser_put(parser);
6766 
6767 		new_hash = __ftrace_hash_move(fgd->new_hash);
6768 		if (!new_hash) {
6769 			ret = -ENOMEM;
6770 			goto out;
6771 		}
6772 
6773 		mutex_lock(&graph_lock);
6774 
6775 		if (fgd->type == GRAPH_FILTER_FUNCTION) {
6776 			old_hash = rcu_dereference_protected(ftrace_graph_hash,
6777 					lockdep_is_held(&graph_lock));
6778 			rcu_assign_pointer(ftrace_graph_hash, new_hash);
6779 		} else {
6780 			old_hash = rcu_dereference_protected(ftrace_graph_notrace_hash,
6781 					lockdep_is_held(&graph_lock));
6782 			rcu_assign_pointer(ftrace_graph_notrace_hash, new_hash);
6783 		}
6784 
6785 		mutex_unlock(&graph_lock);
6786 
6787 		/*
6788 		 * We need to do a hard force of sched synchronization.
6789 		 * This is because we use preempt_disable() to do RCU, but
6790 		 * the function tracers can be called where RCU is not watching
6791 		 * (like before user_exit()). We can not rely on the RCU
6792 		 * infrastructure to do the synchronization, thus we must do it
6793 		 * ourselves.
6794 		 */
6795 		if (old_hash != EMPTY_HASH)
6796 			synchronize_rcu_tasks_rude();
6797 
6798 		free_ftrace_hash(old_hash);
6799 	}
6800 
6801  out:
6802 	free_ftrace_hash(fgd->new_hash);
6803 	kfree(fgd);
6804 
6805 	return ret;
6806 }
6807 
6808 static int
ftrace_graph_set_hash(struct ftrace_hash * hash,char * buffer)6809 ftrace_graph_set_hash(struct ftrace_hash *hash, char *buffer)
6810 {
6811 	struct ftrace_glob func_g;
6812 	struct dyn_ftrace *rec;
6813 	struct ftrace_page *pg;
6814 	struct ftrace_func_entry *entry;
6815 	int fail = 1;
6816 	int not;
6817 
6818 	/* decode regex */
6819 	func_g.type = filter_parse_regex(buffer, strlen(buffer),
6820 					 &func_g.search, &not);
6821 
6822 	func_g.len = strlen(func_g.search);
6823 
6824 	mutex_lock(&ftrace_lock);
6825 
6826 	if (unlikely(ftrace_disabled)) {
6827 		mutex_unlock(&ftrace_lock);
6828 		return -ENODEV;
6829 	}
6830 
6831 	do_for_each_ftrace_rec(pg, rec) {
6832 
6833 		if (rec->flags & FTRACE_FL_DISABLED)
6834 			continue;
6835 
6836 		if (ftrace_match_record(rec, &func_g, NULL, 0)) {
6837 			entry = ftrace_lookup_ip(hash, rec->ip);
6838 
6839 			if (!not) {
6840 				fail = 0;
6841 
6842 				if (entry)
6843 					continue;
6844 				if (add_hash_entry(hash, rec->ip) == NULL)
6845 					goto out;
6846 			} else {
6847 				if (entry) {
6848 					free_hash_entry(hash, entry);
6849 					fail = 0;
6850 				}
6851 			}
6852 		}
6853 		cond_resched();
6854 	} while_for_each_ftrace_rec();
6855 out:
6856 	mutex_unlock(&ftrace_lock);
6857 
6858 	if (fail)
6859 		return -EINVAL;
6860 
6861 	return 0;
6862 }
6863 
6864 static ssize_t
ftrace_graph_write(struct file * file,const char __user * ubuf,size_t cnt,loff_t * ppos)6865 ftrace_graph_write(struct file *file, const char __user *ubuf,
6866 		   size_t cnt, loff_t *ppos)
6867 {
6868 	ssize_t read, ret = 0;
6869 	struct ftrace_graph_data *fgd = file->private_data;
6870 	struct trace_parser *parser;
6871 
6872 	if (!cnt)
6873 		return 0;
6874 
6875 	/* Read mode uses seq functions */
6876 	if (file->f_mode & FMODE_READ) {
6877 		struct seq_file *m = file->private_data;
6878 		fgd = m->private;
6879 	}
6880 
6881 	parser = &fgd->parser;
6882 
6883 	read = trace_get_user(parser, ubuf, cnt, ppos);
6884 
6885 	if (read >= 0 && trace_parser_loaded(parser) &&
6886 	    !trace_parser_cont(parser)) {
6887 
6888 		ret = ftrace_graph_set_hash(fgd->new_hash,
6889 					    parser->buffer);
6890 		trace_parser_clear(parser);
6891 	}
6892 
6893 	if (!ret)
6894 		ret = read;
6895 
6896 	return ret;
6897 }
6898 
6899 static const struct file_operations ftrace_graph_fops = {
6900 	.open		= ftrace_graph_open,
6901 	.read		= seq_read,
6902 	.write		= ftrace_graph_write,
6903 	.llseek		= tracing_lseek,
6904 	.release	= ftrace_graph_release,
6905 };
6906 
6907 static const struct file_operations ftrace_graph_notrace_fops = {
6908 	.open		= ftrace_graph_notrace_open,
6909 	.read		= seq_read,
6910 	.write		= ftrace_graph_write,
6911 	.llseek		= tracing_lseek,
6912 	.release	= ftrace_graph_release,
6913 };
6914 #endif /* CONFIG_FUNCTION_GRAPH_TRACER */
6915 
ftrace_create_filter_files(struct ftrace_ops * ops,struct dentry * parent)6916 void ftrace_create_filter_files(struct ftrace_ops *ops,
6917 				struct dentry *parent)
6918 {
6919 
6920 	trace_create_file("set_ftrace_filter", TRACE_MODE_WRITE, parent,
6921 			  ops, &ftrace_filter_fops);
6922 
6923 	trace_create_file("set_ftrace_notrace", TRACE_MODE_WRITE, parent,
6924 			  ops, &ftrace_notrace_fops);
6925 }
6926 
6927 /*
6928  * The name "destroy_filter_files" is really a misnomer. Although
6929  * in the future, it may actually delete the files, but this is
6930  * really intended to make sure the ops passed in are disabled
6931  * and that when this function returns, the caller is free to
6932  * free the ops.
6933  *
6934  * The "destroy" name is only to match the "create" name that this
6935  * should be paired with.
6936  */
ftrace_destroy_filter_files(struct ftrace_ops * ops)6937 void ftrace_destroy_filter_files(struct ftrace_ops *ops)
6938 {
6939 	mutex_lock(&ftrace_lock);
6940 	if (ops->flags & FTRACE_OPS_FL_ENABLED)
6941 		ftrace_shutdown(ops, 0);
6942 	ops->flags |= FTRACE_OPS_FL_DELETED;
6943 	ftrace_free_filter(ops);
6944 	mutex_unlock(&ftrace_lock);
6945 }
6946 
ftrace_init_dyn_tracefs(struct dentry * d_tracer)6947 static __init int ftrace_init_dyn_tracefs(struct dentry *d_tracer)
6948 {
6949 
6950 	trace_create_file("available_filter_functions", TRACE_MODE_READ,
6951 			d_tracer, NULL, &ftrace_avail_fops);
6952 
6953 	trace_create_file("available_filter_functions_addrs", TRACE_MODE_READ,
6954 			d_tracer, NULL, &ftrace_avail_addrs_fops);
6955 
6956 	trace_create_file("enabled_functions", TRACE_MODE_READ,
6957 			d_tracer, NULL, &ftrace_enabled_fops);
6958 
6959 	trace_create_file("touched_functions", TRACE_MODE_READ,
6960 			d_tracer, NULL, &ftrace_touched_fops);
6961 
6962 	ftrace_create_filter_files(&global_ops, d_tracer);
6963 
6964 #ifdef CONFIG_FUNCTION_GRAPH_TRACER
6965 	trace_create_file("set_graph_function", TRACE_MODE_WRITE, d_tracer,
6966 				    NULL,
6967 				    &ftrace_graph_fops);
6968 	trace_create_file("set_graph_notrace", TRACE_MODE_WRITE, d_tracer,
6969 				    NULL,
6970 				    &ftrace_graph_notrace_fops);
6971 #endif /* CONFIG_FUNCTION_GRAPH_TRACER */
6972 
6973 	return 0;
6974 }
6975 
ftrace_cmp_ips(const void * a,const void * b)6976 static int ftrace_cmp_ips(const void *a, const void *b)
6977 {
6978 	const unsigned long *ipa = a;
6979 	const unsigned long *ipb = b;
6980 
6981 	if (*ipa > *ipb)
6982 		return 1;
6983 	if (*ipa < *ipb)
6984 		return -1;
6985 	return 0;
6986 }
6987 
6988 #ifdef CONFIG_FTRACE_SORT_STARTUP_TEST
test_is_sorted(unsigned long * start,unsigned long count)6989 static void test_is_sorted(unsigned long *start, unsigned long count)
6990 {
6991 	int i;
6992 
6993 	for (i = 1; i < count; i++) {
6994 		if (WARN(start[i - 1] > start[i],
6995 			 "[%d] %pS at %lx is not sorted with %pS at %lx\n", i,
6996 			 (void *)start[i - 1], start[i - 1],
6997 			 (void *)start[i], start[i]))
6998 			break;
6999 	}
7000 	if (i == count)
7001 		pr_info("ftrace section at %px sorted properly\n", start);
7002 }
7003 #else
test_is_sorted(unsigned long * start,unsigned long count)7004 static void test_is_sorted(unsigned long *start, unsigned long count)
7005 {
7006 }
7007 #endif
7008 
ftrace_process_locs(struct module * mod,unsigned long * start,unsigned long * end)7009 static int ftrace_process_locs(struct module *mod,
7010 			       unsigned long *start,
7011 			       unsigned long *end)
7012 {
7013 	struct ftrace_page *pg_unuse = NULL;
7014 	struct ftrace_page *start_pg;
7015 	struct ftrace_page *pg;
7016 	struct dyn_ftrace *rec;
7017 	unsigned long skipped = 0;
7018 	unsigned long count;
7019 	unsigned long *p;
7020 	unsigned long addr;
7021 	unsigned long flags = 0; /* Shut up gcc */
7022 	int ret = -ENOMEM;
7023 
7024 	count = end - start;
7025 
7026 	if (!count)
7027 		return 0;
7028 
7029 	/*
7030 	 * Sorting mcount in vmlinux at build time depend on
7031 	 * CONFIG_BUILDTIME_MCOUNT_SORT, while mcount loc in
7032 	 * modules can not be sorted at build time.
7033 	 */
7034 	if (!IS_ENABLED(CONFIG_BUILDTIME_MCOUNT_SORT) || mod) {
7035 		sort(start, count, sizeof(*start),
7036 		     ftrace_cmp_ips, NULL);
7037 	} else {
7038 		test_is_sorted(start, count);
7039 	}
7040 
7041 	start_pg = ftrace_allocate_pages(count);
7042 	if (!start_pg)
7043 		return -ENOMEM;
7044 
7045 	mutex_lock(&ftrace_lock);
7046 
7047 	/*
7048 	 * Core and each module needs their own pages, as
7049 	 * modules will free them when they are removed.
7050 	 * Force a new page to be allocated for modules.
7051 	 */
7052 	if (!mod) {
7053 		WARN_ON(ftrace_pages || ftrace_pages_start);
7054 		/* First initialization */
7055 		ftrace_pages = ftrace_pages_start = start_pg;
7056 	} else {
7057 		if (!ftrace_pages)
7058 			goto out;
7059 
7060 		if (WARN_ON(ftrace_pages->next)) {
7061 			/* Hmm, we have free pages? */
7062 			while (ftrace_pages->next)
7063 				ftrace_pages = ftrace_pages->next;
7064 		}
7065 
7066 		ftrace_pages->next = start_pg;
7067 	}
7068 
7069 	p = start;
7070 	pg = start_pg;
7071 	while (p < end) {
7072 		unsigned long end_offset;
7073 		addr = ftrace_call_adjust(*p++);
7074 		/*
7075 		 * Some architecture linkers will pad between
7076 		 * the different mcount_loc sections of different
7077 		 * object files to satisfy alignments.
7078 		 * Skip any NULL pointers.
7079 		 */
7080 		if (!addr) {
7081 			skipped++;
7082 			continue;
7083 		}
7084 
7085 		end_offset = (pg->index+1) * sizeof(pg->records[0]);
7086 		if (end_offset > PAGE_SIZE << pg->order) {
7087 			/* We should have allocated enough */
7088 			if (WARN_ON(!pg->next))
7089 				break;
7090 			pg = pg->next;
7091 		}
7092 
7093 		rec = &pg->records[pg->index++];
7094 		rec->ip = addr;
7095 	}
7096 
7097 	if (pg->next) {
7098 		pg_unuse = pg->next;
7099 		pg->next = NULL;
7100 	}
7101 
7102 	/* Assign the last page to ftrace_pages */
7103 	ftrace_pages = pg;
7104 
7105 	/*
7106 	 * We only need to disable interrupts on start up
7107 	 * because we are modifying code that an interrupt
7108 	 * may execute, and the modification is not atomic.
7109 	 * But for modules, nothing runs the code we modify
7110 	 * until we are finished with it, and there's no
7111 	 * reason to cause large interrupt latencies while we do it.
7112 	 */
7113 	if (!mod)
7114 		local_irq_save(flags);
7115 	ftrace_update_code(mod, start_pg);
7116 	if (!mod)
7117 		local_irq_restore(flags);
7118 	ret = 0;
7119  out:
7120 	mutex_unlock(&ftrace_lock);
7121 
7122 	/* We should have used all pages unless we skipped some */
7123 	if (pg_unuse) {
7124 		WARN_ON(!skipped);
7125 		/* Need to synchronize with ftrace_location_range() */
7126 		synchronize_rcu();
7127 		ftrace_free_pages(pg_unuse);
7128 	}
7129 	return ret;
7130 }
7131 
7132 struct ftrace_mod_func {
7133 	struct list_head	list;
7134 	char			*name;
7135 	unsigned long		ip;
7136 	unsigned int		size;
7137 };
7138 
7139 struct ftrace_mod_map {
7140 	struct rcu_head		rcu;
7141 	struct list_head	list;
7142 	struct module		*mod;
7143 	unsigned long		start_addr;
7144 	unsigned long		end_addr;
7145 	struct list_head	funcs;
7146 	unsigned int		num_funcs;
7147 };
7148 
ftrace_get_trampoline_kallsym(unsigned int symnum,unsigned long * value,char * type,char * name,char * module_name,int * exported)7149 static int ftrace_get_trampoline_kallsym(unsigned int symnum,
7150 					 unsigned long *value, char *type,
7151 					 char *name, char *module_name,
7152 					 int *exported)
7153 {
7154 	struct ftrace_ops *op;
7155 
7156 	list_for_each_entry_rcu(op, &ftrace_ops_trampoline_list, list) {
7157 		if (!op->trampoline || symnum--)
7158 			continue;
7159 		*value = op->trampoline;
7160 		*type = 't';
7161 		strscpy(name, FTRACE_TRAMPOLINE_SYM, KSYM_NAME_LEN);
7162 		strscpy(module_name, FTRACE_TRAMPOLINE_MOD, MODULE_NAME_LEN);
7163 		*exported = 0;
7164 		return 0;
7165 	}
7166 
7167 	return -ERANGE;
7168 }
7169 
7170 #if defined(CONFIG_DYNAMIC_FTRACE_WITH_DIRECT_CALLS) || defined(CONFIG_MODULES)
7171 /*
7172  * Check if the current ops references the given ip.
7173  *
7174  * If the ops traces all functions, then it was already accounted for.
7175  * If the ops does not trace the current record function, skip it.
7176  * If the ops ignores the function via notrace filter, skip it.
7177  */
7178 static bool
ops_references_ip(struct ftrace_ops * ops,unsigned long ip)7179 ops_references_ip(struct ftrace_ops *ops, unsigned long ip)
7180 {
7181 	/* If ops isn't enabled, ignore it */
7182 	if (!(ops->flags & FTRACE_OPS_FL_ENABLED))
7183 		return false;
7184 
7185 	/* If ops traces all then it includes this function */
7186 	if (ops_traces_mod(ops))
7187 		return true;
7188 
7189 	/* The function must be in the filter */
7190 	if (!ftrace_hash_empty(ops->func_hash->filter_hash) &&
7191 	    !__ftrace_lookup_ip(ops->func_hash->filter_hash, ip))
7192 		return false;
7193 
7194 	/* If in notrace hash, we ignore it too */
7195 	if (ftrace_lookup_ip(ops->func_hash->notrace_hash, ip))
7196 		return false;
7197 
7198 	return true;
7199 }
7200 #endif
7201 
7202 #ifdef CONFIG_MODULES
7203 
7204 #define next_to_ftrace_page(p) container_of(p, struct ftrace_page, next)
7205 
7206 static LIST_HEAD(ftrace_mod_maps);
7207 
referenced_filters(struct dyn_ftrace * rec)7208 static int referenced_filters(struct dyn_ftrace *rec)
7209 {
7210 	struct ftrace_ops *ops;
7211 	int cnt = 0;
7212 
7213 	for (ops = ftrace_ops_list; ops != &ftrace_list_end; ops = ops->next) {
7214 		if (ops_references_ip(ops, rec->ip)) {
7215 			if (WARN_ON_ONCE(ops->flags & FTRACE_OPS_FL_DIRECT))
7216 				continue;
7217 			if (WARN_ON_ONCE(ops->flags & FTRACE_OPS_FL_IPMODIFY))
7218 				continue;
7219 			cnt++;
7220 			if (ops->flags & FTRACE_OPS_FL_SAVE_REGS)
7221 				rec->flags |= FTRACE_FL_REGS;
7222 			if (cnt == 1 && ops->trampoline)
7223 				rec->flags |= FTRACE_FL_TRAMP;
7224 			else
7225 				rec->flags &= ~FTRACE_FL_TRAMP;
7226 		}
7227 	}
7228 
7229 	return cnt;
7230 }
7231 
7232 static void
clear_mod_from_hash(struct ftrace_page * pg,struct ftrace_hash * hash)7233 clear_mod_from_hash(struct ftrace_page *pg, struct ftrace_hash *hash)
7234 {
7235 	struct ftrace_func_entry *entry;
7236 	struct dyn_ftrace *rec;
7237 	int i;
7238 
7239 	if (ftrace_hash_empty(hash))
7240 		return;
7241 
7242 	for (i = 0; i < pg->index; i++) {
7243 		rec = &pg->records[i];
7244 		entry = __ftrace_lookup_ip(hash, rec->ip);
7245 		/*
7246 		 * Do not allow this rec to match again.
7247 		 * Yeah, it may waste some memory, but will be removed
7248 		 * if/when the hash is modified again.
7249 		 */
7250 		if (entry)
7251 			entry->ip = 0;
7252 	}
7253 }
7254 
7255 /* Clear any records from hashes */
clear_mod_from_hashes(struct ftrace_page * pg)7256 static void clear_mod_from_hashes(struct ftrace_page *pg)
7257 {
7258 	struct trace_array *tr;
7259 
7260 	mutex_lock(&trace_types_lock);
7261 	list_for_each_entry(tr, &ftrace_trace_arrays, list) {
7262 		if (!tr->ops || !tr->ops->func_hash)
7263 			continue;
7264 		mutex_lock(&tr->ops->func_hash->regex_lock);
7265 		clear_mod_from_hash(pg, tr->ops->func_hash->filter_hash);
7266 		clear_mod_from_hash(pg, tr->ops->func_hash->notrace_hash);
7267 		mutex_unlock(&tr->ops->func_hash->regex_lock);
7268 	}
7269 	mutex_unlock(&trace_types_lock);
7270 }
7271 
ftrace_free_mod_map(struct rcu_head * rcu)7272 static void ftrace_free_mod_map(struct rcu_head *rcu)
7273 {
7274 	struct ftrace_mod_map *mod_map = container_of(rcu, struct ftrace_mod_map, rcu);
7275 	struct ftrace_mod_func *mod_func;
7276 	struct ftrace_mod_func *n;
7277 
7278 	/* All the contents of mod_map are now not visible to readers */
7279 	list_for_each_entry_safe(mod_func, n, &mod_map->funcs, list) {
7280 		kfree(mod_func->name);
7281 		list_del(&mod_func->list);
7282 		kfree(mod_func);
7283 	}
7284 
7285 	kfree(mod_map);
7286 }
7287 
ftrace_release_mod(struct module * mod)7288 void ftrace_release_mod(struct module *mod)
7289 {
7290 	struct ftrace_mod_map *mod_map;
7291 	struct ftrace_mod_map *n;
7292 	struct dyn_ftrace *rec;
7293 	struct ftrace_page **last_pg;
7294 	struct ftrace_page *tmp_page = NULL;
7295 	struct ftrace_page *pg;
7296 
7297 	mutex_lock(&ftrace_lock);
7298 
7299 	/*
7300 	 * To avoid the UAF problem after the module is unloaded, the
7301 	 * 'mod_map' resource needs to be released unconditionally.
7302 	 */
7303 	list_for_each_entry_safe(mod_map, n, &ftrace_mod_maps, list) {
7304 		if (mod_map->mod == mod) {
7305 			list_del_rcu(&mod_map->list);
7306 			call_rcu(&mod_map->rcu, ftrace_free_mod_map);
7307 			break;
7308 		}
7309 	}
7310 
7311 	if (ftrace_disabled)
7312 		goto out_unlock;
7313 
7314 	/*
7315 	 * Each module has its own ftrace_pages, remove
7316 	 * them from the list.
7317 	 */
7318 	last_pg = &ftrace_pages_start;
7319 	for (pg = ftrace_pages_start; pg; pg = *last_pg) {
7320 		rec = &pg->records[0];
7321 		if (within_module(rec->ip, mod)) {
7322 			/*
7323 			 * As core pages are first, the first
7324 			 * page should never be a module page.
7325 			 */
7326 			if (WARN_ON(pg == ftrace_pages_start))
7327 				goto out_unlock;
7328 
7329 			/* Check if we are deleting the last page */
7330 			if (pg == ftrace_pages)
7331 				ftrace_pages = next_to_ftrace_page(last_pg);
7332 
7333 			ftrace_update_tot_cnt -= pg->index;
7334 			*last_pg = pg->next;
7335 
7336 			pg->next = tmp_page;
7337 			tmp_page = pg;
7338 		} else
7339 			last_pg = &pg->next;
7340 	}
7341  out_unlock:
7342 	mutex_unlock(&ftrace_lock);
7343 
7344 	/* Need to synchronize with ftrace_location_range() */
7345 	if (tmp_page)
7346 		synchronize_rcu();
7347 	for (pg = tmp_page; pg; pg = tmp_page) {
7348 
7349 		/* Needs to be called outside of ftrace_lock */
7350 		clear_mod_from_hashes(pg);
7351 
7352 		if (pg->records) {
7353 			free_pages((unsigned long)pg->records, pg->order);
7354 			ftrace_number_of_pages -= 1 << pg->order;
7355 		}
7356 		tmp_page = pg->next;
7357 		kfree(pg);
7358 		ftrace_number_of_groups--;
7359 	}
7360 }
7361 
ftrace_module_enable(struct module * mod)7362 void ftrace_module_enable(struct module *mod)
7363 {
7364 	struct dyn_ftrace *rec;
7365 	struct ftrace_page *pg;
7366 
7367 	mutex_lock(&ftrace_lock);
7368 
7369 	if (ftrace_disabled)
7370 		goto out_unlock;
7371 
7372 	/*
7373 	 * If the tracing is enabled, go ahead and enable the record.
7374 	 *
7375 	 * The reason not to enable the record immediately is the
7376 	 * inherent check of ftrace_make_nop/ftrace_make_call for
7377 	 * correct previous instructions.  Making first the NOP
7378 	 * conversion puts the module to the correct state, thus
7379 	 * passing the ftrace_make_call check.
7380 	 *
7381 	 * We also delay this to after the module code already set the
7382 	 * text to read-only, as we now need to set it back to read-write
7383 	 * so that we can modify the text.
7384 	 */
7385 	if (ftrace_start_up)
7386 		ftrace_arch_code_modify_prepare();
7387 
7388 	do_for_each_ftrace_rec(pg, rec) {
7389 		int cnt;
7390 		/*
7391 		 * do_for_each_ftrace_rec() is a double loop.
7392 		 * module text shares the pg. If a record is
7393 		 * not part of this module, then skip this pg,
7394 		 * which the "break" will do.
7395 		 */
7396 		if (!within_module(rec->ip, mod))
7397 			break;
7398 
7399 		/* Weak functions should still be ignored */
7400 		if (!test_for_valid_rec(rec)) {
7401 			/* Clear all other flags. Should not be enabled anyway */
7402 			rec->flags = FTRACE_FL_DISABLED;
7403 			continue;
7404 		}
7405 
7406 		cnt = 0;
7407 
7408 		/*
7409 		 * When adding a module, we need to check if tracers are
7410 		 * currently enabled and if they are, and can trace this record,
7411 		 * we need to enable the module functions as well as update the
7412 		 * reference counts for those function records.
7413 		 */
7414 		if (ftrace_start_up)
7415 			cnt += referenced_filters(rec);
7416 
7417 		rec->flags &= ~FTRACE_FL_DISABLED;
7418 		rec->flags += cnt;
7419 
7420 		if (ftrace_start_up && cnt) {
7421 			int failed = __ftrace_replace_code(rec, 1);
7422 			if (failed) {
7423 				ftrace_bug(failed, rec);
7424 				goto out_loop;
7425 			}
7426 		}
7427 
7428 	} while_for_each_ftrace_rec();
7429 
7430  out_loop:
7431 	if (ftrace_start_up)
7432 		ftrace_arch_code_modify_post_process();
7433 
7434  out_unlock:
7435 	mutex_unlock(&ftrace_lock);
7436 
7437 	process_cached_mods(mod->name);
7438 }
7439 
ftrace_module_init(struct module * mod)7440 void ftrace_module_init(struct module *mod)
7441 {
7442 	int ret;
7443 
7444 	if (ftrace_disabled || !mod->num_ftrace_callsites)
7445 		return;
7446 
7447 	ret = ftrace_process_locs(mod, mod->ftrace_callsites,
7448 				  mod->ftrace_callsites + mod->num_ftrace_callsites);
7449 	if (ret)
7450 		pr_warn("ftrace: failed to allocate entries for module '%s' functions\n",
7451 			mod->name);
7452 }
7453 
save_ftrace_mod_rec(struct ftrace_mod_map * mod_map,struct dyn_ftrace * rec)7454 static void save_ftrace_mod_rec(struct ftrace_mod_map *mod_map,
7455 				struct dyn_ftrace *rec)
7456 {
7457 	struct ftrace_mod_func *mod_func;
7458 	unsigned long symsize;
7459 	unsigned long offset;
7460 	char str[KSYM_SYMBOL_LEN];
7461 	char *modname;
7462 	const char *ret;
7463 
7464 	ret = kallsyms_lookup(rec->ip, &symsize, &offset, &modname, str);
7465 	if (!ret)
7466 		return;
7467 
7468 	mod_func = kmalloc(sizeof(*mod_func), GFP_KERNEL);
7469 	if (!mod_func)
7470 		return;
7471 
7472 	mod_func->name = kstrdup(str, GFP_KERNEL);
7473 	if (!mod_func->name) {
7474 		kfree(mod_func);
7475 		return;
7476 	}
7477 
7478 	mod_func->ip = rec->ip - offset;
7479 	mod_func->size = symsize;
7480 
7481 	mod_map->num_funcs++;
7482 
7483 	list_add_rcu(&mod_func->list, &mod_map->funcs);
7484 }
7485 
7486 static struct ftrace_mod_map *
allocate_ftrace_mod_map(struct module * mod,unsigned long start,unsigned long end)7487 allocate_ftrace_mod_map(struct module *mod,
7488 			unsigned long start, unsigned long end)
7489 {
7490 	struct ftrace_mod_map *mod_map;
7491 
7492 	mod_map = kmalloc(sizeof(*mod_map), GFP_KERNEL);
7493 	if (!mod_map)
7494 		return NULL;
7495 
7496 	mod_map->mod = mod;
7497 	mod_map->start_addr = start;
7498 	mod_map->end_addr = end;
7499 	mod_map->num_funcs = 0;
7500 
7501 	INIT_LIST_HEAD_RCU(&mod_map->funcs);
7502 
7503 	list_add_rcu(&mod_map->list, &ftrace_mod_maps);
7504 
7505 	return mod_map;
7506 }
7507 
7508 static int
ftrace_func_address_lookup(struct ftrace_mod_map * mod_map,unsigned long addr,unsigned long * size,unsigned long * off,char * sym)7509 ftrace_func_address_lookup(struct ftrace_mod_map *mod_map,
7510 			   unsigned long addr, unsigned long *size,
7511 			   unsigned long *off, char *sym)
7512 {
7513 	struct ftrace_mod_func *found_func =  NULL;
7514 	struct ftrace_mod_func *mod_func;
7515 
7516 	list_for_each_entry_rcu(mod_func, &mod_map->funcs, list) {
7517 		if (addr >= mod_func->ip &&
7518 		    addr < mod_func->ip + mod_func->size) {
7519 			found_func = mod_func;
7520 			break;
7521 		}
7522 	}
7523 
7524 	if (found_func) {
7525 		if (size)
7526 			*size = found_func->size;
7527 		if (off)
7528 			*off = addr - found_func->ip;
7529 		return strscpy(sym, found_func->name, KSYM_NAME_LEN);
7530 	}
7531 
7532 	return 0;
7533 }
7534 
7535 int
ftrace_mod_address_lookup(unsigned long addr,unsigned long * size,unsigned long * off,char ** modname,char * sym)7536 ftrace_mod_address_lookup(unsigned long addr, unsigned long *size,
7537 		   unsigned long *off, char **modname, char *sym)
7538 {
7539 	struct ftrace_mod_map *mod_map;
7540 	int ret = 0;
7541 
7542 	/* mod_map is freed via call_rcu() */
7543 	preempt_disable();
7544 	list_for_each_entry_rcu(mod_map, &ftrace_mod_maps, list) {
7545 		ret = ftrace_func_address_lookup(mod_map, addr, size, off, sym);
7546 		if (ret) {
7547 			if (modname)
7548 				*modname = mod_map->mod->name;
7549 			break;
7550 		}
7551 	}
7552 	preempt_enable();
7553 
7554 	return ret;
7555 }
7556 
ftrace_mod_get_kallsym(unsigned int symnum,unsigned long * value,char * type,char * name,char * module_name,int * exported)7557 int ftrace_mod_get_kallsym(unsigned int symnum, unsigned long *value,
7558 			   char *type, char *name,
7559 			   char *module_name, int *exported)
7560 {
7561 	struct ftrace_mod_map *mod_map;
7562 	struct ftrace_mod_func *mod_func;
7563 	int ret;
7564 
7565 	preempt_disable();
7566 	list_for_each_entry_rcu(mod_map, &ftrace_mod_maps, list) {
7567 
7568 		if (symnum >= mod_map->num_funcs) {
7569 			symnum -= mod_map->num_funcs;
7570 			continue;
7571 		}
7572 
7573 		list_for_each_entry_rcu(mod_func, &mod_map->funcs, list) {
7574 			if (symnum > 1) {
7575 				symnum--;
7576 				continue;
7577 			}
7578 
7579 			*value = mod_func->ip;
7580 			*type = 'T';
7581 			strscpy(name, mod_func->name, KSYM_NAME_LEN);
7582 			strscpy(module_name, mod_map->mod->name, MODULE_NAME_LEN);
7583 			*exported = 1;
7584 			preempt_enable();
7585 			return 0;
7586 		}
7587 		WARN_ON(1);
7588 		break;
7589 	}
7590 	ret = ftrace_get_trampoline_kallsym(symnum, value, type, name,
7591 					    module_name, exported);
7592 	preempt_enable();
7593 	return ret;
7594 }
7595 
7596 #else
save_ftrace_mod_rec(struct ftrace_mod_map * mod_map,struct dyn_ftrace * rec)7597 static void save_ftrace_mod_rec(struct ftrace_mod_map *mod_map,
7598 				struct dyn_ftrace *rec) { }
7599 static inline struct ftrace_mod_map *
allocate_ftrace_mod_map(struct module * mod,unsigned long start,unsigned long end)7600 allocate_ftrace_mod_map(struct module *mod,
7601 			unsigned long start, unsigned long end)
7602 {
7603 	return NULL;
7604 }
ftrace_mod_get_kallsym(unsigned int symnum,unsigned long * value,char * type,char * name,char * module_name,int * exported)7605 int ftrace_mod_get_kallsym(unsigned int symnum, unsigned long *value,
7606 			   char *type, char *name, char *module_name,
7607 			   int *exported)
7608 {
7609 	int ret;
7610 
7611 	preempt_disable();
7612 	ret = ftrace_get_trampoline_kallsym(symnum, value, type, name,
7613 					    module_name, exported);
7614 	preempt_enable();
7615 	return ret;
7616 }
7617 #endif /* CONFIG_MODULES */
7618 
7619 struct ftrace_init_func {
7620 	struct list_head list;
7621 	unsigned long ip;
7622 };
7623 
7624 /* Clear any init ips from hashes */
7625 static void
clear_func_from_hash(struct ftrace_init_func * func,struct ftrace_hash * hash)7626 clear_func_from_hash(struct ftrace_init_func *func, struct ftrace_hash *hash)
7627 {
7628 	struct ftrace_func_entry *entry;
7629 
7630 	entry = ftrace_lookup_ip(hash, func->ip);
7631 	/*
7632 	 * Do not allow this rec to match again.
7633 	 * Yeah, it may waste some memory, but will be removed
7634 	 * if/when the hash is modified again.
7635 	 */
7636 	if (entry)
7637 		entry->ip = 0;
7638 }
7639 
7640 static void
clear_func_from_hashes(struct ftrace_init_func * func)7641 clear_func_from_hashes(struct ftrace_init_func *func)
7642 {
7643 	struct trace_array *tr;
7644 
7645 	mutex_lock(&trace_types_lock);
7646 	list_for_each_entry(tr, &ftrace_trace_arrays, list) {
7647 		if (!tr->ops || !tr->ops->func_hash)
7648 			continue;
7649 		mutex_lock(&tr->ops->func_hash->regex_lock);
7650 		clear_func_from_hash(func, tr->ops->func_hash->filter_hash);
7651 		clear_func_from_hash(func, tr->ops->func_hash->notrace_hash);
7652 		mutex_unlock(&tr->ops->func_hash->regex_lock);
7653 	}
7654 	mutex_unlock(&trace_types_lock);
7655 }
7656 
add_to_clear_hash_list(struct list_head * clear_list,struct dyn_ftrace * rec)7657 static void add_to_clear_hash_list(struct list_head *clear_list,
7658 				   struct dyn_ftrace *rec)
7659 {
7660 	struct ftrace_init_func *func;
7661 
7662 	func = kmalloc(sizeof(*func), GFP_KERNEL);
7663 	if (!func) {
7664 		MEM_FAIL(1, "alloc failure, ftrace filter could be stale\n");
7665 		return;
7666 	}
7667 
7668 	func->ip = rec->ip;
7669 	list_add(&func->list, clear_list);
7670 }
7671 
ftrace_free_mem(struct module * mod,void * start_ptr,void * end_ptr)7672 void ftrace_free_mem(struct module *mod, void *start_ptr, void *end_ptr)
7673 {
7674 	unsigned long start = (unsigned long)(start_ptr);
7675 	unsigned long end = (unsigned long)(end_ptr);
7676 	struct ftrace_page **last_pg = &ftrace_pages_start;
7677 	struct ftrace_page *tmp_page = NULL;
7678 	struct ftrace_page *pg;
7679 	struct dyn_ftrace *rec;
7680 	struct dyn_ftrace key;
7681 	struct ftrace_mod_map *mod_map = NULL;
7682 	struct ftrace_init_func *func, *func_next;
7683 	LIST_HEAD(clear_hash);
7684 
7685 	key.ip = start;
7686 	key.flags = end;	/* overload flags, as it is unsigned long */
7687 
7688 	mutex_lock(&ftrace_lock);
7689 
7690 	/*
7691 	 * If we are freeing module init memory, then check if
7692 	 * any tracer is active. If so, we need to save a mapping of
7693 	 * the module functions being freed with the address.
7694 	 */
7695 	if (mod && ftrace_ops_list != &ftrace_list_end)
7696 		mod_map = allocate_ftrace_mod_map(mod, start, end);
7697 
7698 	for (pg = ftrace_pages_start; pg; last_pg = &pg->next, pg = *last_pg) {
7699 		if (end < pg->records[0].ip ||
7700 		    start >= (pg->records[pg->index - 1].ip + MCOUNT_INSN_SIZE))
7701 			continue;
7702  again:
7703 		rec = bsearch(&key, pg->records, pg->index,
7704 			      sizeof(struct dyn_ftrace),
7705 			      ftrace_cmp_recs);
7706 		if (!rec)
7707 			continue;
7708 
7709 		/* rec will be cleared from hashes after ftrace_lock unlock */
7710 		add_to_clear_hash_list(&clear_hash, rec);
7711 
7712 		if (mod_map)
7713 			save_ftrace_mod_rec(mod_map, rec);
7714 
7715 		pg->index--;
7716 		ftrace_update_tot_cnt--;
7717 		if (!pg->index) {
7718 			*last_pg = pg->next;
7719 			pg->next = tmp_page;
7720 			tmp_page = pg;
7721 			pg = container_of(last_pg, struct ftrace_page, next);
7722 			if (!(*last_pg))
7723 				ftrace_pages = pg;
7724 			continue;
7725 		}
7726 		memmove(rec, rec + 1,
7727 			(pg->index - (rec - pg->records)) * sizeof(*rec));
7728 		/* More than one function may be in this block */
7729 		goto again;
7730 	}
7731 	mutex_unlock(&ftrace_lock);
7732 
7733 	list_for_each_entry_safe(func, func_next, &clear_hash, list) {
7734 		clear_func_from_hashes(func);
7735 		kfree(func);
7736 	}
7737 	/* Need to synchronize with ftrace_location_range() */
7738 	if (tmp_page) {
7739 		synchronize_rcu();
7740 		ftrace_free_pages(tmp_page);
7741 	}
7742 }
7743 
ftrace_free_init_mem(void)7744 void __init ftrace_free_init_mem(void)
7745 {
7746 	void *start = (void *)(&__init_begin);
7747 	void *end = (void *)(&__init_end);
7748 
7749 	ftrace_boot_snapshot();
7750 
7751 	ftrace_free_mem(NULL, start, end);
7752 }
7753 
ftrace_dyn_arch_init(void)7754 int __init __weak ftrace_dyn_arch_init(void)
7755 {
7756 	return 0;
7757 }
7758 
ftrace_init(void)7759 void __init ftrace_init(void)
7760 {
7761 	extern unsigned long __start_mcount_loc[];
7762 	extern unsigned long __stop_mcount_loc[];
7763 	unsigned long count, flags;
7764 	int ret;
7765 
7766 	local_irq_save(flags);
7767 	ret = ftrace_dyn_arch_init();
7768 	local_irq_restore(flags);
7769 	if (ret)
7770 		goto failed;
7771 
7772 	count = __stop_mcount_loc - __start_mcount_loc;
7773 	if (!count) {
7774 		pr_info("ftrace: No functions to be traced?\n");
7775 		goto failed;
7776 	}
7777 
7778 	pr_info("ftrace: allocating %ld entries in %ld pages\n",
7779 		count, DIV_ROUND_UP(count, ENTRIES_PER_PAGE));
7780 
7781 	ret = ftrace_process_locs(NULL,
7782 				  __start_mcount_loc,
7783 				  __stop_mcount_loc);
7784 	if (ret) {
7785 		pr_warn("ftrace: failed to allocate entries for functions\n");
7786 		goto failed;
7787 	}
7788 
7789 	pr_info("ftrace: allocated %ld pages with %ld groups\n",
7790 		ftrace_number_of_pages, ftrace_number_of_groups);
7791 
7792 	last_ftrace_enabled = ftrace_enabled = 1;
7793 
7794 	set_ftrace_early_filters();
7795 
7796 	return;
7797  failed:
7798 	ftrace_disabled = 1;
7799 }
7800 
7801 /* Do nothing if arch does not support this */
arch_ftrace_update_trampoline(struct ftrace_ops * ops)7802 void __weak arch_ftrace_update_trampoline(struct ftrace_ops *ops)
7803 {
7804 }
7805 
ftrace_update_trampoline(struct ftrace_ops * ops)7806 static void ftrace_update_trampoline(struct ftrace_ops *ops)
7807 {
7808 	unsigned long trampoline = ops->trampoline;
7809 
7810 	arch_ftrace_update_trampoline(ops);
7811 	if (ops->trampoline && ops->trampoline != trampoline &&
7812 	    (ops->flags & FTRACE_OPS_FL_ALLOC_TRAMP)) {
7813 		/* Add to kallsyms before the perf events */
7814 		ftrace_add_trampoline_to_kallsyms(ops);
7815 		perf_event_ksymbol(PERF_RECORD_KSYMBOL_TYPE_OOL,
7816 				   ops->trampoline, ops->trampoline_size, false,
7817 				   FTRACE_TRAMPOLINE_SYM);
7818 		/*
7819 		 * Record the perf text poke event after the ksymbol register
7820 		 * event.
7821 		 */
7822 		perf_event_text_poke((void *)ops->trampoline, NULL, 0,
7823 				     (void *)ops->trampoline,
7824 				     ops->trampoline_size);
7825 	}
7826 }
7827 
ftrace_init_trace_array(struct trace_array * tr)7828 void ftrace_init_trace_array(struct trace_array *tr)
7829 {
7830 	INIT_LIST_HEAD(&tr->func_probes);
7831 	INIT_LIST_HEAD(&tr->mod_trace);
7832 	INIT_LIST_HEAD(&tr->mod_notrace);
7833 }
7834 #else
7835 
7836 struct ftrace_ops global_ops = {
7837 	.func			= ftrace_stub,
7838 	.flags			= FTRACE_OPS_FL_INITIALIZED |
7839 				  FTRACE_OPS_FL_PID,
7840 };
7841 
ftrace_nodyn_init(void)7842 static int __init ftrace_nodyn_init(void)
7843 {
7844 	ftrace_enabled = 1;
7845 	return 0;
7846 }
7847 core_initcall(ftrace_nodyn_init);
7848 
ftrace_init_dyn_tracefs(struct dentry * d_tracer)7849 static inline int ftrace_init_dyn_tracefs(struct dentry *d_tracer) { return 0; }
ftrace_startup_all(int command)7850 static inline void ftrace_startup_all(int command) { }
7851 
ftrace_update_trampoline(struct ftrace_ops * ops)7852 static void ftrace_update_trampoline(struct ftrace_ops *ops)
7853 {
7854 }
7855 
7856 #endif /* CONFIG_DYNAMIC_FTRACE */
7857 
ftrace_init_global_array_ops(struct trace_array * tr)7858 __init void ftrace_init_global_array_ops(struct trace_array *tr)
7859 {
7860 	tr->ops = &global_ops;
7861 	tr->ops->private = tr;
7862 	ftrace_init_trace_array(tr);
7863 	init_array_fgraph_ops(tr, tr->ops);
7864 }
7865 
ftrace_init_array_ops(struct trace_array * tr,ftrace_func_t func)7866 void ftrace_init_array_ops(struct trace_array *tr, ftrace_func_t func)
7867 {
7868 	/* If we filter on pids, update to use the pid function */
7869 	if (tr->flags & TRACE_ARRAY_FL_GLOBAL) {
7870 		if (WARN_ON(tr->ops->func != ftrace_stub))
7871 			printk("ftrace ops had %pS for function\n",
7872 			       tr->ops->func);
7873 	}
7874 	tr->ops->func = func;
7875 	tr->ops->private = tr;
7876 }
7877 
ftrace_reset_array_ops(struct trace_array * tr)7878 void ftrace_reset_array_ops(struct trace_array *tr)
7879 {
7880 	tr->ops->func = ftrace_stub;
7881 }
7882 
7883 static nokprobe_inline void
__ftrace_ops_list_func(unsigned long ip,unsigned long parent_ip,struct ftrace_ops * ignored,struct ftrace_regs * fregs)7884 __ftrace_ops_list_func(unsigned long ip, unsigned long parent_ip,
7885 		       struct ftrace_ops *ignored, struct ftrace_regs *fregs)
7886 {
7887 	struct pt_regs *regs = ftrace_get_regs(fregs);
7888 	struct ftrace_ops *op;
7889 	int bit;
7890 
7891 	/*
7892 	 * The ftrace_test_and_set_recursion() will disable preemption,
7893 	 * which is required since some of the ops may be dynamically
7894 	 * allocated, they must be freed after a synchronize_rcu().
7895 	 */
7896 	bit = trace_test_and_set_recursion(ip, parent_ip, TRACE_LIST_START);
7897 	if (bit < 0)
7898 		return;
7899 
7900 	do_for_each_ftrace_op(op, ftrace_ops_list) {
7901 		/* Stub functions don't need to be called nor tested */
7902 		if (op->flags & FTRACE_OPS_FL_STUB)
7903 			continue;
7904 		/*
7905 		 * Check the following for each ops before calling their func:
7906 		 *  if RCU flag is set, then rcu_is_watching() must be true
7907 		 *  Otherwise test if the ip matches the ops filter
7908 		 *
7909 		 * If any of the above fails then the op->func() is not executed.
7910 		 */
7911 		if ((!(op->flags & FTRACE_OPS_FL_RCU) || rcu_is_watching()) &&
7912 		    ftrace_ops_test(op, ip, regs)) {
7913 			if (FTRACE_WARN_ON(!op->func)) {
7914 				pr_warn("op=%p %pS\n", op, op);
7915 				goto out;
7916 			}
7917 			op->func(ip, parent_ip, op, fregs);
7918 		}
7919 	} while_for_each_ftrace_op(op);
7920 out:
7921 	trace_clear_recursion(bit);
7922 }
7923 
7924 /*
7925  * Some archs only support passing ip and parent_ip. Even though
7926  * the list function ignores the op parameter, we do not want any
7927  * C side effects, where a function is called without the caller
7928  * sending a third parameter.
7929  * Archs are to support both the regs and ftrace_ops at the same time.
7930  * If they support ftrace_ops, it is assumed they support regs.
7931  * If call backs want to use regs, they must either check for regs
7932  * being NULL, or CONFIG_DYNAMIC_FTRACE_WITH_REGS.
7933  * Note, CONFIG_DYNAMIC_FTRACE_WITH_REGS expects a full regs to be saved.
7934  * An architecture can pass partial regs with ftrace_ops and still
7935  * set the ARCH_SUPPORTS_FTRACE_OPS.
7936  *
7937  * In vmlinux.lds.h, ftrace_ops_list_func() is defined to be
7938  * arch_ftrace_ops_list_func.
7939  */
7940 #if ARCH_SUPPORTS_FTRACE_OPS
arch_ftrace_ops_list_func(unsigned long ip,unsigned long parent_ip,struct ftrace_ops * op,struct ftrace_regs * fregs)7941 void arch_ftrace_ops_list_func(unsigned long ip, unsigned long parent_ip,
7942 			       struct ftrace_ops *op, struct ftrace_regs *fregs)
7943 {
7944 	kmsan_unpoison_memory(fregs, sizeof(*fregs));
7945 	__ftrace_ops_list_func(ip, parent_ip, NULL, fregs);
7946 }
7947 #else
arch_ftrace_ops_list_func(unsigned long ip,unsigned long parent_ip)7948 void arch_ftrace_ops_list_func(unsigned long ip, unsigned long parent_ip)
7949 {
7950 	__ftrace_ops_list_func(ip, parent_ip, NULL, NULL);
7951 }
7952 #endif
7953 NOKPROBE_SYMBOL(arch_ftrace_ops_list_func);
7954 
7955 /*
7956  * If there's only one function registered but it does not support
7957  * recursion, needs RCU protection, then this function will be called
7958  * by the mcount trampoline.
7959  */
ftrace_ops_assist_func(unsigned long ip,unsigned long parent_ip,struct ftrace_ops * op,struct ftrace_regs * fregs)7960 static void ftrace_ops_assist_func(unsigned long ip, unsigned long parent_ip,
7961 				   struct ftrace_ops *op, struct ftrace_regs *fregs)
7962 {
7963 	int bit;
7964 
7965 	bit = trace_test_and_set_recursion(ip, parent_ip, TRACE_LIST_START);
7966 	if (bit < 0)
7967 		return;
7968 
7969 	if (!(op->flags & FTRACE_OPS_FL_RCU) || rcu_is_watching())
7970 		op->func(ip, parent_ip, op, fregs);
7971 
7972 	trace_clear_recursion(bit);
7973 }
7974 NOKPROBE_SYMBOL(ftrace_ops_assist_func);
7975 
7976 /**
7977  * ftrace_ops_get_func - get the function a trampoline should call
7978  * @ops: the ops to get the function for
7979  *
7980  * Normally the mcount trampoline will call the ops->func, but there
7981  * are times that it should not. For example, if the ops does not
7982  * have its own recursion protection, then it should call the
7983  * ftrace_ops_assist_func() instead.
7984  *
7985  * Returns: the function that the trampoline should call for @ops.
7986  */
ftrace_ops_get_func(struct ftrace_ops * ops)7987 ftrace_func_t ftrace_ops_get_func(struct ftrace_ops *ops)
7988 {
7989 	/*
7990 	 * If the function does not handle recursion or needs to be RCU safe,
7991 	 * then we need to call the assist handler.
7992 	 */
7993 	if (ops->flags & (FTRACE_OPS_FL_RECURSION |
7994 			  FTRACE_OPS_FL_RCU))
7995 		return ftrace_ops_assist_func;
7996 
7997 	return ops->func;
7998 }
7999 
8000 static void
ftrace_filter_pid_sched_switch_probe(void * data,bool preempt,struct task_struct * prev,struct task_struct * next,unsigned int prev_state)8001 ftrace_filter_pid_sched_switch_probe(void *data, bool preempt,
8002 				     struct task_struct *prev,
8003 				     struct task_struct *next,
8004 				     unsigned int prev_state)
8005 {
8006 	struct trace_array *tr = data;
8007 	struct trace_pid_list *pid_list;
8008 	struct trace_pid_list *no_pid_list;
8009 
8010 	pid_list = rcu_dereference_sched(tr->function_pids);
8011 	no_pid_list = rcu_dereference_sched(tr->function_no_pids);
8012 
8013 	if (trace_ignore_this_task(pid_list, no_pid_list, next))
8014 		this_cpu_write(tr->array_buffer.data->ftrace_ignore_pid,
8015 			       FTRACE_PID_IGNORE);
8016 	else
8017 		this_cpu_write(tr->array_buffer.data->ftrace_ignore_pid,
8018 			       next->pid);
8019 }
8020 
8021 static void
ftrace_pid_follow_sched_process_fork(void * data,struct task_struct * self,struct task_struct * task)8022 ftrace_pid_follow_sched_process_fork(void *data,
8023 				     struct task_struct *self,
8024 				     struct task_struct *task)
8025 {
8026 	struct trace_pid_list *pid_list;
8027 	struct trace_array *tr = data;
8028 
8029 	pid_list = rcu_dereference_sched(tr->function_pids);
8030 	trace_filter_add_remove_task(pid_list, self, task);
8031 
8032 	pid_list = rcu_dereference_sched(tr->function_no_pids);
8033 	trace_filter_add_remove_task(pid_list, self, task);
8034 }
8035 
8036 static void
ftrace_pid_follow_sched_process_exit(void * data,struct task_struct * task)8037 ftrace_pid_follow_sched_process_exit(void *data, struct task_struct *task)
8038 {
8039 	struct trace_pid_list *pid_list;
8040 	struct trace_array *tr = data;
8041 
8042 	pid_list = rcu_dereference_sched(tr->function_pids);
8043 	trace_filter_add_remove_task(pid_list, NULL, task);
8044 
8045 	pid_list = rcu_dereference_sched(tr->function_no_pids);
8046 	trace_filter_add_remove_task(pid_list, NULL, task);
8047 }
8048 
ftrace_pid_follow_fork(struct trace_array * tr,bool enable)8049 void ftrace_pid_follow_fork(struct trace_array *tr, bool enable)
8050 {
8051 	if (enable) {
8052 		register_trace_sched_process_fork(ftrace_pid_follow_sched_process_fork,
8053 						  tr);
8054 		register_trace_sched_process_free(ftrace_pid_follow_sched_process_exit,
8055 						  tr);
8056 	} else {
8057 		unregister_trace_sched_process_fork(ftrace_pid_follow_sched_process_fork,
8058 						    tr);
8059 		unregister_trace_sched_process_free(ftrace_pid_follow_sched_process_exit,
8060 						    tr);
8061 	}
8062 }
8063 
clear_ftrace_pids(struct trace_array * tr,int type)8064 static void clear_ftrace_pids(struct trace_array *tr, int type)
8065 {
8066 	struct trace_pid_list *pid_list;
8067 	struct trace_pid_list *no_pid_list;
8068 	int cpu;
8069 
8070 	pid_list = rcu_dereference_protected(tr->function_pids,
8071 					     lockdep_is_held(&ftrace_lock));
8072 	no_pid_list = rcu_dereference_protected(tr->function_no_pids,
8073 						lockdep_is_held(&ftrace_lock));
8074 
8075 	/* Make sure there's something to do */
8076 	if (!pid_type_enabled(type, pid_list, no_pid_list))
8077 		return;
8078 
8079 	/* See if the pids still need to be checked after this */
8080 	if (!still_need_pid_events(type, pid_list, no_pid_list)) {
8081 		unregister_trace_sched_switch(ftrace_filter_pid_sched_switch_probe, tr);
8082 		for_each_possible_cpu(cpu)
8083 			per_cpu_ptr(tr->array_buffer.data, cpu)->ftrace_ignore_pid = FTRACE_PID_TRACE;
8084 	}
8085 
8086 	if (type & TRACE_PIDS)
8087 		rcu_assign_pointer(tr->function_pids, NULL);
8088 
8089 	if (type & TRACE_NO_PIDS)
8090 		rcu_assign_pointer(tr->function_no_pids, NULL);
8091 
8092 	/* Wait till all users are no longer using pid filtering */
8093 	synchronize_rcu();
8094 
8095 	if ((type & TRACE_PIDS) && pid_list)
8096 		trace_pid_list_free(pid_list);
8097 
8098 	if ((type & TRACE_NO_PIDS) && no_pid_list)
8099 		trace_pid_list_free(no_pid_list);
8100 }
8101 
ftrace_clear_pids(struct trace_array * tr)8102 void ftrace_clear_pids(struct trace_array *tr)
8103 {
8104 	mutex_lock(&ftrace_lock);
8105 
8106 	clear_ftrace_pids(tr, TRACE_PIDS | TRACE_NO_PIDS);
8107 
8108 	mutex_unlock(&ftrace_lock);
8109 }
8110 
ftrace_pid_reset(struct trace_array * tr,int type)8111 static void ftrace_pid_reset(struct trace_array *tr, int type)
8112 {
8113 	mutex_lock(&ftrace_lock);
8114 	clear_ftrace_pids(tr, type);
8115 
8116 	ftrace_update_pid_func();
8117 	ftrace_startup_all(0);
8118 
8119 	mutex_unlock(&ftrace_lock);
8120 }
8121 
8122 /* Greater than any max PID */
8123 #define FTRACE_NO_PIDS		(void *)(PID_MAX_LIMIT + 1)
8124 
fpid_start(struct seq_file * m,loff_t * pos)8125 static void *fpid_start(struct seq_file *m, loff_t *pos)
8126 	__acquires(RCU)
8127 {
8128 	struct trace_pid_list *pid_list;
8129 	struct trace_array *tr = m->private;
8130 
8131 	mutex_lock(&ftrace_lock);
8132 	rcu_read_lock_sched();
8133 
8134 	pid_list = rcu_dereference_sched(tr->function_pids);
8135 
8136 	if (!pid_list)
8137 		return !(*pos) ? FTRACE_NO_PIDS : NULL;
8138 
8139 	return trace_pid_start(pid_list, pos);
8140 }
8141 
fpid_next(struct seq_file * m,void * v,loff_t * pos)8142 static void *fpid_next(struct seq_file *m, void *v, loff_t *pos)
8143 {
8144 	struct trace_array *tr = m->private;
8145 	struct trace_pid_list *pid_list = rcu_dereference_sched(tr->function_pids);
8146 
8147 	if (v == FTRACE_NO_PIDS) {
8148 		(*pos)++;
8149 		return NULL;
8150 	}
8151 	return trace_pid_next(pid_list, v, pos);
8152 }
8153 
fpid_stop(struct seq_file * m,void * p)8154 static void fpid_stop(struct seq_file *m, void *p)
8155 	__releases(RCU)
8156 {
8157 	rcu_read_unlock_sched();
8158 	mutex_unlock(&ftrace_lock);
8159 }
8160 
fpid_show(struct seq_file * m,void * v)8161 static int fpid_show(struct seq_file *m, void *v)
8162 {
8163 	if (v == FTRACE_NO_PIDS) {
8164 		seq_puts(m, "no pid\n");
8165 		return 0;
8166 	}
8167 
8168 	return trace_pid_show(m, v);
8169 }
8170 
8171 static const struct seq_operations ftrace_pid_sops = {
8172 	.start = fpid_start,
8173 	.next = fpid_next,
8174 	.stop = fpid_stop,
8175 	.show = fpid_show,
8176 };
8177 
fnpid_start(struct seq_file * m,loff_t * pos)8178 static void *fnpid_start(struct seq_file *m, loff_t *pos)
8179 	__acquires(RCU)
8180 {
8181 	struct trace_pid_list *pid_list;
8182 	struct trace_array *tr = m->private;
8183 
8184 	mutex_lock(&ftrace_lock);
8185 	rcu_read_lock_sched();
8186 
8187 	pid_list = rcu_dereference_sched(tr->function_no_pids);
8188 
8189 	if (!pid_list)
8190 		return !(*pos) ? FTRACE_NO_PIDS : NULL;
8191 
8192 	return trace_pid_start(pid_list, pos);
8193 }
8194 
fnpid_next(struct seq_file * m,void * v,loff_t * pos)8195 static void *fnpid_next(struct seq_file *m, void *v, loff_t *pos)
8196 {
8197 	struct trace_array *tr = m->private;
8198 	struct trace_pid_list *pid_list = rcu_dereference_sched(tr->function_no_pids);
8199 
8200 	if (v == FTRACE_NO_PIDS) {
8201 		(*pos)++;
8202 		return NULL;
8203 	}
8204 	return trace_pid_next(pid_list, v, pos);
8205 }
8206 
8207 static const struct seq_operations ftrace_no_pid_sops = {
8208 	.start = fnpid_start,
8209 	.next = fnpid_next,
8210 	.stop = fpid_stop,
8211 	.show = fpid_show,
8212 };
8213 
pid_open(struct inode * inode,struct file * file,int type)8214 static int pid_open(struct inode *inode, struct file *file, int type)
8215 {
8216 	const struct seq_operations *seq_ops;
8217 	struct trace_array *tr = inode->i_private;
8218 	struct seq_file *m;
8219 	int ret = 0;
8220 
8221 	ret = tracing_check_open_get_tr(tr);
8222 	if (ret)
8223 		return ret;
8224 
8225 	if ((file->f_mode & FMODE_WRITE) &&
8226 	    (file->f_flags & O_TRUNC))
8227 		ftrace_pid_reset(tr, type);
8228 
8229 	switch (type) {
8230 	case TRACE_PIDS:
8231 		seq_ops = &ftrace_pid_sops;
8232 		break;
8233 	case TRACE_NO_PIDS:
8234 		seq_ops = &ftrace_no_pid_sops;
8235 		break;
8236 	default:
8237 		trace_array_put(tr);
8238 		WARN_ON_ONCE(1);
8239 		return -EINVAL;
8240 	}
8241 
8242 	ret = seq_open(file, seq_ops);
8243 	if (ret < 0) {
8244 		trace_array_put(tr);
8245 	} else {
8246 		m = file->private_data;
8247 		/* copy tr over to seq ops */
8248 		m->private = tr;
8249 	}
8250 
8251 	return ret;
8252 }
8253 
8254 static int
ftrace_pid_open(struct inode * inode,struct file * file)8255 ftrace_pid_open(struct inode *inode, struct file *file)
8256 {
8257 	return pid_open(inode, file, TRACE_PIDS);
8258 }
8259 
8260 static int
ftrace_no_pid_open(struct inode * inode,struct file * file)8261 ftrace_no_pid_open(struct inode *inode, struct file *file)
8262 {
8263 	return pid_open(inode, file, TRACE_NO_PIDS);
8264 }
8265 
ignore_task_cpu(void * data)8266 static void ignore_task_cpu(void *data)
8267 {
8268 	struct trace_array *tr = data;
8269 	struct trace_pid_list *pid_list;
8270 	struct trace_pid_list *no_pid_list;
8271 
8272 	/*
8273 	 * This function is called by on_each_cpu() while the
8274 	 * event_mutex is held.
8275 	 */
8276 	pid_list = rcu_dereference_protected(tr->function_pids,
8277 					     mutex_is_locked(&ftrace_lock));
8278 	no_pid_list = rcu_dereference_protected(tr->function_no_pids,
8279 						mutex_is_locked(&ftrace_lock));
8280 
8281 	if (trace_ignore_this_task(pid_list, no_pid_list, current))
8282 		this_cpu_write(tr->array_buffer.data->ftrace_ignore_pid,
8283 			       FTRACE_PID_IGNORE);
8284 	else
8285 		this_cpu_write(tr->array_buffer.data->ftrace_ignore_pid,
8286 			       current->pid);
8287 }
8288 
8289 static ssize_t
pid_write(struct file * filp,const char __user * ubuf,size_t cnt,loff_t * ppos,int type)8290 pid_write(struct file *filp, const char __user *ubuf,
8291 	  size_t cnt, loff_t *ppos, int type)
8292 {
8293 	struct seq_file *m = filp->private_data;
8294 	struct trace_array *tr = m->private;
8295 	struct trace_pid_list *filtered_pids;
8296 	struct trace_pid_list *other_pids;
8297 	struct trace_pid_list *pid_list;
8298 	ssize_t ret;
8299 
8300 	if (!cnt)
8301 		return 0;
8302 
8303 	mutex_lock(&ftrace_lock);
8304 
8305 	switch (type) {
8306 	case TRACE_PIDS:
8307 		filtered_pids = rcu_dereference_protected(tr->function_pids,
8308 					     lockdep_is_held(&ftrace_lock));
8309 		other_pids = rcu_dereference_protected(tr->function_no_pids,
8310 					     lockdep_is_held(&ftrace_lock));
8311 		break;
8312 	case TRACE_NO_PIDS:
8313 		filtered_pids = rcu_dereference_protected(tr->function_no_pids,
8314 					     lockdep_is_held(&ftrace_lock));
8315 		other_pids = rcu_dereference_protected(tr->function_pids,
8316 					     lockdep_is_held(&ftrace_lock));
8317 		break;
8318 	default:
8319 		ret = -EINVAL;
8320 		WARN_ON_ONCE(1);
8321 		goto out;
8322 	}
8323 
8324 	ret = trace_pid_write(filtered_pids, &pid_list, ubuf, cnt);
8325 	if (ret < 0)
8326 		goto out;
8327 
8328 	switch (type) {
8329 	case TRACE_PIDS:
8330 		rcu_assign_pointer(tr->function_pids, pid_list);
8331 		break;
8332 	case TRACE_NO_PIDS:
8333 		rcu_assign_pointer(tr->function_no_pids, pid_list);
8334 		break;
8335 	}
8336 
8337 
8338 	if (filtered_pids) {
8339 		synchronize_rcu();
8340 		trace_pid_list_free(filtered_pids);
8341 	} else if (pid_list && !other_pids) {
8342 		/* Register a probe to set whether to ignore the tracing of a task */
8343 		register_trace_sched_switch(ftrace_filter_pid_sched_switch_probe, tr);
8344 	}
8345 
8346 	/*
8347 	 * Ignoring of pids is done at task switch. But we have to
8348 	 * check for those tasks that are currently running.
8349 	 * Always do this in case a pid was appended or removed.
8350 	 */
8351 	on_each_cpu(ignore_task_cpu, tr, 1);
8352 
8353 	ftrace_update_pid_func();
8354 	ftrace_startup_all(0);
8355  out:
8356 	mutex_unlock(&ftrace_lock);
8357 
8358 	if (ret > 0)
8359 		*ppos += ret;
8360 
8361 	return ret;
8362 }
8363 
8364 static ssize_t
ftrace_pid_write(struct file * filp,const char __user * ubuf,size_t cnt,loff_t * ppos)8365 ftrace_pid_write(struct file *filp, const char __user *ubuf,
8366 		 size_t cnt, loff_t *ppos)
8367 {
8368 	return pid_write(filp, ubuf, cnt, ppos, TRACE_PIDS);
8369 }
8370 
8371 static ssize_t
ftrace_no_pid_write(struct file * filp,const char __user * ubuf,size_t cnt,loff_t * ppos)8372 ftrace_no_pid_write(struct file *filp, const char __user *ubuf,
8373 		    size_t cnt, loff_t *ppos)
8374 {
8375 	return pid_write(filp, ubuf, cnt, ppos, TRACE_NO_PIDS);
8376 }
8377 
8378 static int
ftrace_pid_release(struct inode * inode,struct file * file)8379 ftrace_pid_release(struct inode *inode, struct file *file)
8380 {
8381 	struct trace_array *tr = inode->i_private;
8382 
8383 	trace_array_put(tr);
8384 
8385 	return seq_release(inode, file);
8386 }
8387 
8388 static const struct file_operations ftrace_pid_fops = {
8389 	.open		= ftrace_pid_open,
8390 	.write		= ftrace_pid_write,
8391 	.read		= seq_read,
8392 	.llseek		= tracing_lseek,
8393 	.release	= ftrace_pid_release,
8394 };
8395 
8396 static const struct file_operations ftrace_no_pid_fops = {
8397 	.open		= ftrace_no_pid_open,
8398 	.write		= ftrace_no_pid_write,
8399 	.read		= seq_read,
8400 	.llseek		= tracing_lseek,
8401 	.release	= ftrace_pid_release,
8402 };
8403 
ftrace_init_tracefs(struct trace_array * tr,struct dentry * d_tracer)8404 void ftrace_init_tracefs(struct trace_array *tr, struct dentry *d_tracer)
8405 {
8406 	trace_create_file("set_ftrace_pid", TRACE_MODE_WRITE, d_tracer,
8407 			    tr, &ftrace_pid_fops);
8408 	trace_create_file("set_ftrace_notrace_pid", TRACE_MODE_WRITE,
8409 			  d_tracer, tr, &ftrace_no_pid_fops);
8410 }
8411 
ftrace_init_tracefs_toplevel(struct trace_array * tr,struct dentry * d_tracer)8412 void __init ftrace_init_tracefs_toplevel(struct trace_array *tr,
8413 					 struct dentry *d_tracer)
8414 {
8415 	/* Only the top level directory has the dyn_tracefs and profile */
8416 	WARN_ON(!(tr->flags & TRACE_ARRAY_FL_GLOBAL));
8417 
8418 	ftrace_init_dyn_tracefs(d_tracer);
8419 	ftrace_profile_tracefs(d_tracer);
8420 }
8421 
8422 /**
8423  * ftrace_kill - kill ftrace
8424  *
8425  * This function should be used by panic code. It stops ftrace
8426  * but in a not so nice way. If you need to simply kill ftrace
8427  * from a non-atomic section, use ftrace_kill.
8428  */
ftrace_kill(void)8429 void ftrace_kill(void)
8430 {
8431 	ftrace_disabled = 1;
8432 	ftrace_enabled = 0;
8433 	ftrace_trace_function = ftrace_stub;
8434 	kprobe_ftrace_kill();
8435 }
8436 
8437 /**
8438  * ftrace_is_dead - Test if ftrace is dead or not.
8439  *
8440  * Returns: 1 if ftrace is "dead", zero otherwise.
8441  */
ftrace_is_dead(void)8442 int ftrace_is_dead(void)
8443 {
8444 	return ftrace_disabled;
8445 }
8446 
8447 #ifdef CONFIG_DYNAMIC_FTRACE_WITH_DIRECT_CALLS
8448 /*
8449  * When registering ftrace_ops with IPMODIFY, it is necessary to make sure
8450  * it doesn't conflict with any direct ftrace_ops. If there is existing
8451  * direct ftrace_ops on a kernel function being patched, call
8452  * FTRACE_OPS_CMD_ENABLE_SHARE_IPMODIFY_PEER on it to enable sharing.
8453  *
8454  * @ops:     ftrace_ops being registered.
8455  *
8456  * Returns:
8457  *         0 on success;
8458  *         Negative on failure.
8459  */
prepare_direct_functions_for_ipmodify(struct ftrace_ops * ops)8460 static int prepare_direct_functions_for_ipmodify(struct ftrace_ops *ops)
8461 {
8462 	struct ftrace_func_entry *entry;
8463 	struct ftrace_hash *hash;
8464 	struct ftrace_ops *op;
8465 	int size, i, ret;
8466 
8467 	lockdep_assert_held_once(&direct_mutex);
8468 
8469 	if (!(ops->flags & FTRACE_OPS_FL_IPMODIFY))
8470 		return 0;
8471 
8472 	hash = ops->func_hash->filter_hash;
8473 	size = 1 << hash->size_bits;
8474 	for (i = 0; i < size; i++) {
8475 		hlist_for_each_entry(entry, &hash->buckets[i], hlist) {
8476 			unsigned long ip = entry->ip;
8477 			bool found_op = false;
8478 
8479 			mutex_lock(&ftrace_lock);
8480 			do_for_each_ftrace_op(op, ftrace_ops_list) {
8481 				if (!(op->flags & FTRACE_OPS_FL_DIRECT))
8482 					continue;
8483 				if (ops_references_ip(op, ip)) {
8484 					found_op = true;
8485 					break;
8486 				}
8487 			} while_for_each_ftrace_op(op);
8488 			mutex_unlock(&ftrace_lock);
8489 
8490 			if (found_op) {
8491 				if (!op->ops_func)
8492 					return -EBUSY;
8493 
8494 				ret = op->ops_func(op, FTRACE_OPS_CMD_ENABLE_SHARE_IPMODIFY_PEER);
8495 				if (ret)
8496 					return ret;
8497 			}
8498 		}
8499 	}
8500 
8501 	return 0;
8502 }
8503 
8504 /*
8505  * Similar to prepare_direct_functions_for_ipmodify, clean up after ops
8506  * with IPMODIFY is unregistered. The cleanup is optional for most DIRECT
8507  * ops.
8508  */
cleanup_direct_functions_after_ipmodify(struct ftrace_ops * ops)8509 static void cleanup_direct_functions_after_ipmodify(struct ftrace_ops *ops)
8510 {
8511 	struct ftrace_func_entry *entry;
8512 	struct ftrace_hash *hash;
8513 	struct ftrace_ops *op;
8514 	int size, i;
8515 
8516 	if (!(ops->flags & FTRACE_OPS_FL_IPMODIFY))
8517 		return;
8518 
8519 	mutex_lock(&direct_mutex);
8520 
8521 	hash = ops->func_hash->filter_hash;
8522 	size = 1 << hash->size_bits;
8523 	for (i = 0; i < size; i++) {
8524 		hlist_for_each_entry(entry, &hash->buckets[i], hlist) {
8525 			unsigned long ip = entry->ip;
8526 			bool found_op = false;
8527 
8528 			mutex_lock(&ftrace_lock);
8529 			do_for_each_ftrace_op(op, ftrace_ops_list) {
8530 				if (!(op->flags & FTRACE_OPS_FL_DIRECT))
8531 					continue;
8532 				if (ops_references_ip(op, ip)) {
8533 					found_op = true;
8534 					break;
8535 				}
8536 			} while_for_each_ftrace_op(op);
8537 			mutex_unlock(&ftrace_lock);
8538 
8539 			/* The cleanup is optional, ignore any errors */
8540 			if (found_op && op->ops_func)
8541 				op->ops_func(op, FTRACE_OPS_CMD_DISABLE_SHARE_IPMODIFY_PEER);
8542 		}
8543 	}
8544 	mutex_unlock(&direct_mutex);
8545 }
8546 
8547 #define lock_direct_mutex()	mutex_lock(&direct_mutex)
8548 #define unlock_direct_mutex()	mutex_unlock(&direct_mutex)
8549 
8550 #else  /* CONFIG_DYNAMIC_FTRACE_WITH_DIRECT_CALLS */
8551 
prepare_direct_functions_for_ipmodify(struct ftrace_ops * ops)8552 static int prepare_direct_functions_for_ipmodify(struct ftrace_ops *ops)
8553 {
8554 	return 0;
8555 }
8556 
cleanup_direct_functions_after_ipmodify(struct ftrace_ops * ops)8557 static void cleanup_direct_functions_after_ipmodify(struct ftrace_ops *ops)
8558 {
8559 }
8560 
8561 #define lock_direct_mutex()	do { } while (0)
8562 #define unlock_direct_mutex()	do { } while (0)
8563 
8564 #endif  /* CONFIG_DYNAMIC_FTRACE_WITH_DIRECT_CALLS */
8565 
8566 /*
8567  * Similar to register_ftrace_function, except we don't lock direct_mutex.
8568  */
register_ftrace_function_nolock(struct ftrace_ops * ops)8569 static int register_ftrace_function_nolock(struct ftrace_ops *ops)
8570 {
8571 	int ret;
8572 
8573 	ftrace_ops_init(ops);
8574 
8575 	mutex_lock(&ftrace_lock);
8576 
8577 	ret = ftrace_startup(ops, 0);
8578 
8579 	mutex_unlock(&ftrace_lock);
8580 
8581 	return ret;
8582 }
8583 
8584 /**
8585  * register_ftrace_function - register a function for profiling
8586  * @ops:	ops structure that holds the function for profiling.
8587  *
8588  * Register a function to be called by all functions in the
8589  * kernel.
8590  *
8591  * Note: @ops->func and all the functions it calls must be labeled
8592  *       with "notrace", otherwise it will go into a
8593  *       recursive loop.
8594  */
register_ftrace_function(struct ftrace_ops * ops)8595 int register_ftrace_function(struct ftrace_ops *ops)
8596 {
8597 	int ret;
8598 
8599 	lock_direct_mutex();
8600 	ret = prepare_direct_functions_for_ipmodify(ops);
8601 	if (ret < 0)
8602 		goto out_unlock;
8603 
8604 	ret = register_ftrace_function_nolock(ops);
8605 
8606 out_unlock:
8607 	unlock_direct_mutex();
8608 	return ret;
8609 }
8610 EXPORT_SYMBOL_GPL(register_ftrace_function);
8611 
8612 /**
8613  * unregister_ftrace_function - unregister a function for profiling.
8614  * @ops:	ops structure that holds the function to unregister
8615  *
8616  * Unregister a function that was added to be called by ftrace profiling.
8617  */
unregister_ftrace_function(struct ftrace_ops * ops)8618 int unregister_ftrace_function(struct ftrace_ops *ops)
8619 {
8620 	int ret;
8621 
8622 	mutex_lock(&ftrace_lock);
8623 	ret = ftrace_shutdown(ops, 0);
8624 	mutex_unlock(&ftrace_lock);
8625 
8626 	cleanup_direct_functions_after_ipmodify(ops);
8627 	return ret;
8628 }
8629 EXPORT_SYMBOL_GPL(unregister_ftrace_function);
8630 
symbols_cmp(const void * a,const void * b)8631 static int symbols_cmp(const void *a, const void *b)
8632 {
8633 	const char **str_a = (const char **) a;
8634 	const char **str_b = (const char **) b;
8635 
8636 	return strcmp(*str_a, *str_b);
8637 }
8638 
8639 struct kallsyms_data {
8640 	unsigned long *addrs;
8641 	const char **syms;
8642 	size_t cnt;
8643 	size_t found;
8644 };
8645 
8646 /* This function gets called for all kernel and module symbols
8647  * and returns 1 in case we resolved all the requested symbols,
8648  * 0 otherwise.
8649  */
kallsyms_callback(void * data,const char * name,unsigned long addr)8650 static int kallsyms_callback(void *data, const char *name, unsigned long addr)
8651 {
8652 	struct kallsyms_data *args = data;
8653 	const char **sym;
8654 	int idx;
8655 
8656 	sym = bsearch(&name, args->syms, args->cnt, sizeof(*args->syms), symbols_cmp);
8657 	if (!sym)
8658 		return 0;
8659 
8660 	idx = sym - args->syms;
8661 	if (args->addrs[idx])
8662 		return 0;
8663 
8664 	if (!ftrace_location(addr))
8665 		return 0;
8666 
8667 	args->addrs[idx] = addr;
8668 	args->found++;
8669 	return args->found == args->cnt ? 1 : 0;
8670 }
8671 
8672 /**
8673  * ftrace_lookup_symbols - Lookup addresses for array of symbols
8674  *
8675  * @sorted_syms: array of symbols pointers symbols to resolve,
8676  * must be alphabetically sorted
8677  * @cnt: number of symbols/addresses in @syms/@addrs arrays
8678  * @addrs: array for storing resulting addresses
8679  *
8680  * This function looks up addresses for array of symbols provided in
8681  * @syms array (must be alphabetically sorted) and stores them in
8682  * @addrs array, which needs to be big enough to store at least @cnt
8683  * addresses.
8684  *
8685  * Returns: 0 if all provided symbols are found, -ESRCH otherwise.
8686  */
ftrace_lookup_symbols(const char ** sorted_syms,size_t cnt,unsigned long * addrs)8687 int ftrace_lookup_symbols(const char **sorted_syms, size_t cnt, unsigned long *addrs)
8688 {
8689 	struct kallsyms_data args;
8690 	int found_all;
8691 
8692 	memset(addrs, 0, sizeof(*addrs) * cnt);
8693 	args.addrs = addrs;
8694 	args.syms = sorted_syms;
8695 	args.cnt = cnt;
8696 	args.found = 0;
8697 
8698 	found_all = kallsyms_on_each_symbol(kallsyms_callback, &args);
8699 	if (found_all)
8700 		return 0;
8701 	found_all = module_kallsyms_on_each_symbol(NULL, kallsyms_callback, &args);
8702 	return found_all ? 0 : -ESRCH;
8703 }
8704 
8705 #ifdef CONFIG_SYSCTL
8706 
8707 #ifdef CONFIG_DYNAMIC_FTRACE
ftrace_startup_sysctl(void)8708 static void ftrace_startup_sysctl(void)
8709 {
8710 	int command;
8711 
8712 	if (unlikely(ftrace_disabled))
8713 		return;
8714 
8715 	/* Force update next time */
8716 	saved_ftrace_func = NULL;
8717 	/* ftrace_start_up is true if we want ftrace running */
8718 	if (ftrace_start_up) {
8719 		command = FTRACE_UPDATE_CALLS;
8720 		if (ftrace_graph_active)
8721 			command |= FTRACE_START_FUNC_RET;
8722 		ftrace_startup_enable(command);
8723 	}
8724 }
8725 
ftrace_shutdown_sysctl(void)8726 static void ftrace_shutdown_sysctl(void)
8727 {
8728 	int command;
8729 
8730 	if (unlikely(ftrace_disabled))
8731 		return;
8732 
8733 	/* ftrace_start_up is true if ftrace is running */
8734 	if (ftrace_start_up) {
8735 		command = FTRACE_DISABLE_CALLS;
8736 		if (ftrace_graph_active)
8737 			command |= FTRACE_STOP_FUNC_RET;
8738 		ftrace_run_update_code(command);
8739 	}
8740 }
8741 #else
8742 # define ftrace_startup_sysctl()       do { } while (0)
8743 # define ftrace_shutdown_sysctl()      do { } while (0)
8744 #endif /* CONFIG_DYNAMIC_FTRACE */
8745 
is_permanent_ops_registered(void)8746 static bool is_permanent_ops_registered(void)
8747 {
8748 	struct ftrace_ops *op;
8749 
8750 	do_for_each_ftrace_op(op, ftrace_ops_list) {
8751 		if (op->flags & FTRACE_OPS_FL_PERMANENT)
8752 			return true;
8753 	} while_for_each_ftrace_op(op);
8754 
8755 	return false;
8756 }
8757 
8758 static int
ftrace_enable_sysctl(const struct ctl_table * table,int write,void * buffer,size_t * lenp,loff_t * ppos)8759 ftrace_enable_sysctl(const struct ctl_table *table, int write,
8760 		     void *buffer, size_t *lenp, loff_t *ppos)
8761 {
8762 	int ret = -ENODEV;
8763 
8764 	mutex_lock(&ftrace_lock);
8765 
8766 	if (unlikely(ftrace_disabled))
8767 		goto out;
8768 
8769 	ret = proc_dointvec(table, write, buffer, lenp, ppos);
8770 
8771 	if (ret || !write || (last_ftrace_enabled == !!ftrace_enabled))
8772 		goto out;
8773 
8774 	if (ftrace_enabled) {
8775 
8776 		/* we are starting ftrace again */
8777 		if (rcu_dereference_protected(ftrace_ops_list,
8778 			lockdep_is_held(&ftrace_lock)) != &ftrace_list_end)
8779 			update_ftrace_function();
8780 
8781 		ftrace_startup_sysctl();
8782 
8783 	} else {
8784 		if (is_permanent_ops_registered()) {
8785 			ftrace_enabled = true;
8786 			ret = -EBUSY;
8787 			goto out;
8788 		}
8789 
8790 		/* stopping ftrace calls (just send to ftrace_stub) */
8791 		ftrace_trace_function = ftrace_stub;
8792 
8793 		ftrace_shutdown_sysctl();
8794 	}
8795 
8796 	last_ftrace_enabled = !!ftrace_enabled;
8797  out:
8798 	mutex_unlock(&ftrace_lock);
8799 	return ret;
8800 }
8801 
8802 static struct ctl_table ftrace_sysctls[] = {
8803 	{
8804 		.procname       = "ftrace_enabled",
8805 		.data           = &ftrace_enabled,
8806 		.maxlen         = sizeof(int),
8807 		.mode           = 0644,
8808 		.proc_handler   = ftrace_enable_sysctl,
8809 	},
8810 };
8811 
ftrace_sysctl_init(void)8812 static int __init ftrace_sysctl_init(void)
8813 {
8814 	register_sysctl_init("kernel", ftrace_sysctls);
8815 	return 0;
8816 }
8817 late_initcall(ftrace_sysctl_init);
8818 #endif
8819