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