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