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