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