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