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