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