xref: /linux/kernel/trace/fgraph.c (revision 1ba5ad36e00f46e3f7676f5de6b87f5a2f57f1f1)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Infrastructure to took into function calls and returns.
4  * Copyright (c) 2008-2009 Frederic Weisbecker <fweisbec@gmail.com>
5  * Mostly borrowed from function tracer which
6  * is Copyright (c) Steven Rostedt <srostedt@redhat.com>
7  *
8  * Highly modified by Steven Rostedt (VMware).
9  */
10 #include <linux/jump_label.h>
11 #include <linux/suspend.h>
12 #include <linux/ftrace.h>
13 #include <linux/slab.h>
14 
15 #include <trace/events/sched.h>
16 
17 #include "ftrace_internal.h"
18 
19 #ifdef CONFIG_DYNAMIC_FTRACE
20 #define ASSIGN_OPS_HASH(opsname, val) \
21 	.func_hash		= val, \
22 	.local_hash.regex_lock	= __MUTEX_INITIALIZER(opsname.local_hash.regex_lock),
23 #else
24 #define ASSIGN_OPS_HASH(opsname, val)
25 #endif
26 
27 DEFINE_STATIC_KEY_FALSE(kill_ftrace_graph);
28 int ftrace_graph_active;
29 
30 /* Both enabled by default (can be cleared by function_graph tracer flags */
31 static bool fgraph_sleep_time = true;
32 
33 /*
34  * archs can override this function if they must do something
35  * to enable hook for graph tracer.
36  */
37 int __weak ftrace_enable_ftrace_graph_caller(void)
38 {
39 	return 0;
40 }
41 
42 /*
43  * archs can override this function if they must do something
44  * to disable hook for graph tracer.
45  */
46 int __weak ftrace_disable_ftrace_graph_caller(void)
47 {
48 	return 0;
49 }
50 
51 /**
52  * ftrace_graph_stop - set to permanently disable function graph tracing
53  *
54  * In case of an error int function graph tracing, this is called
55  * to try to keep function graph tracing from causing any more harm.
56  * Usually this is pretty severe and this is called to try to at least
57  * get a warning out to the user.
58  */
59 void ftrace_graph_stop(void)
60 {
61 	static_branch_enable(&kill_ftrace_graph);
62 }
63 
64 /* Add a function return address to the trace stack on thread info.*/
65 static int
66 ftrace_push_return_trace(unsigned long ret, unsigned long func,
67 			 unsigned long frame_pointer, unsigned long *retp)
68 {
69 	unsigned long long calltime;
70 	int index;
71 
72 	if (unlikely(ftrace_graph_is_dead()))
73 		return -EBUSY;
74 
75 	if (!current->ret_stack)
76 		return -EBUSY;
77 
78 	/*
79 	 * We must make sure the ret_stack is tested before we read
80 	 * anything else.
81 	 */
82 	smp_rmb();
83 
84 	/* The return trace stack is full */
85 	if (current->curr_ret_stack == FTRACE_RETFUNC_DEPTH - 1) {
86 		atomic_inc(&current->trace_overrun);
87 		return -EBUSY;
88 	}
89 
90 	calltime = trace_clock_local();
91 
92 	index = ++current->curr_ret_stack;
93 	barrier();
94 	current->ret_stack[index].ret = ret;
95 	current->ret_stack[index].func = func;
96 	current->ret_stack[index].calltime = calltime;
97 #ifdef HAVE_FUNCTION_GRAPH_FP_TEST
98 	current->ret_stack[index].fp = frame_pointer;
99 #endif
100 #ifdef HAVE_FUNCTION_GRAPH_RET_ADDR_PTR
101 	current->ret_stack[index].retp = retp;
102 #endif
103 	return 0;
104 }
105 
106 /*
107  * Not all archs define MCOUNT_INSN_SIZE which is used to look for direct
108  * functions. But those archs currently don't support direct functions
109  * anyway, and ftrace_find_rec_direct() is just a stub for them.
110  * Define MCOUNT_INSN_SIZE to keep those archs compiling.
111  */
112 #ifndef MCOUNT_INSN_SIZE
113 /* Make sure this only works without direct calls */
114 # ifdef CONFIG_DYNAMIC_FTRACE_WITH_DIRECT_CALLS
115 #  error MCOUNT_INSN_SIZE not defined with direct calls enabled
116 # endif
117 # define MCOUNT_INSN_SIZE 0
118 #endif
119 
120 int function_graph_enter(unsigned long ret, unsigned long func,
121 			 unsigned long frame_pointer, unsigned long *retp)
122 {
123 	struct ftrace_graph_ent trace;
124 
125 #ifndef CONFIG_HAVE_DYNAMIC_FTRACE_WITH_ARGS
126 	/*
127 	 * Skip graph tracing if the return location is served by direct trampoline,
128 	 * since call sequence and return addresses are unpredictable anyway.
129 	 * Ex: BPF trampoline may call original function and may skip frame
130 	 * depending on type of BPF programs attached.
131 	 */
132 	if (ftrace_direct_func_count &&
133 	    ftrace_find_rec_direct(ret - MCOUNT_INSN_SIZE))
134 		return -EBUSY;
135 #endif
136 	trace.func = func;
137 	trace.depth = ++current->curr_ret_depth;
138 
139 	if (ftrace_push_return_trace(ret, func, frame_pointer, retp))
140 		goto out;
141 
142 	/* Only trace if the calling function expects to */
143 	if (!ftrace_graph_entry(&trace))
144 		goto out_ret;
145 
146 	return 0;
147  out_ret:
148 	current->curr_ret_stack--;
149  out:
150 	current->curr_ret_depth--;
151 	return -EBUSY;
152 }
153 
154 /* Retrieve a function return address to the trace stack on thread info.*/
155 static void
156 ftrace_pop_return_trace(struct ftrace_graph_ret *trace, unsigned long *ret,
157 			unsigned long frame_pointer)
158 {
159 	int index;
160 
161 	index = current->curr_ret_stack;
162 
163 	if (unlikely(index < 0 || index >= FTRACE_RETFUNC_DEPTH)) {
164 		ftrace_graph_stop();
165 		WARN_ON(1);
166 		/* Might as well panic, otherwise we have no where to go */
167 		*ret = (unsigned long)panic;
168 		return;
169 	}
170 
171 #ifdef HAVE_FUNCTION_GRAPH_FP_TEST
172 	/*
173 	 * The arch may choose to record the frame pointer used
174 	 * and check it here to make sure that it is what we expect it
175 	 * to be. If gcc does not set the place holder of the return
176 	 * address in the frame pointer, and does a copy instead, then
177 	 * the function graph trace will fail. This test detects this
178 	 * case.
179 	 *
180 	 * Currently, x86_32 with optimize for size (-Os) makes the latest
181 	 * gcc do the above.
182 	 *
183 	 * Note, -mfentry does not use frame pointers, and this test
184 	 *  is not needed if CC_USING_FENTRY is set.
185 	 */
186 	if (unlikely(current->ret_stack[index].fp != frame_pointer)) {
187 		ftrace_graph_stop();
188 		WARN(1, "Bad frame pointer: expected %lx, received %lx\n"
189 		     "  from func %ps return to %lx\n",
190 		     current->ret_stack[index].fp,
191 		     frame_pointer,
192 		     (void *)current->ret_stack[index].func,
193 		     current->ret_stack[index].ret);
194 		*ret = (unsigned long)panic;
195 		return;
196 	}
197 #endif
198 
199 	*ret = current->ret_stack[index].ret;
200 	trace->func = current->ret_stack[index].func;
201 	trace->calltime = current->ret_stack[index].calltime;
202 	trace->overrun = atomic_read(&current->trace_overrun);
203 	trace->depth = current->curr_ret_depth--;
204 	/*
205 	 * We still want to trace interrupts coming in if
206 	 * max_depth is set to 1. Make sure the decrement is
207 	 * seen before ftrace_graph_return.
208 	 */
209 	barrier();
210 }
211 
212 /*
213  * Hibernation protection.
214  * The state of the current task is too much unstable during
215  * suspend/restore to disk. We want to protect against that.
216  */
217 static int
218 ftrace_suspend_notifier_call(struct notifier_block *bl, unsigned long state,
219 							void *unused)
220 {
221 	switch (state) {
222 	case PM_HIBERNATION_PREPARE:
223 		pause_graph_tracing();
224 		break;
225 
226 	case PM_POST_HIBERNATION:
227 		unpause_graph_tracing();
228 		break;
229 	}
230 	return NOTIFY_DONE;
231 }
232 
233 static struct notifier_block ftrace_suspend_notifier = {
234 	.notifier_call = ftrace_suspend_notifier_call,
235 };
236 
237 /*
238  * Send the trace to the ring-buffer.
239  * @return the original return address.
240  */
241 unsigned long ftrace_return_to_handler(unsigned long frame_pointer)
242 {
243 	struct ftrace_graph_ret trace;
244 	unsigned long ret;
245 
246 	ftrace_pop_return_trace(&trace, &ret, frame_pointer);
247 	trace.rettime = trace_clock_local();
248 	ftrace_graph_return(&trace);
249 	/*
250 	 * The ftrace_graph_return() may still access the current
251 	 * ret_stack structure, we need to make sure the update of
252 	 * curr_ret_stack is after that.
253 	 */
254 	barrier();
255 	current->curr_ret_stack--;
256 
257 	if (unlikely(!ret)) {
258 		ftrace_graph_stop();
259 		WARN_ON(1);
260 		/* Might as well panic. What else to do? */
261 		ret = (unsigned long)panic;
262 	}
263 
264 	return ret;
265 }
266 
267 /**
268  * ftrace_graph_get_ret_stack - return the entry of the shadow stack
269  * @task: The task to read the shadow stack from
270  * @idx: Index down the shadow stack
271  *
272  * Return the ret_struct on the shadow stack of the @task at the
273  * call graph at @idx starting with zero. If @idx is zero, it
274  * will return the last saved ret_stack entry. If it is greater than
275  * zero, it will return the corresponding ret_stack for the depth
276  * of saved return addresses.
277  */
278 struct ftrace_ret_stack *
279 ftrace_graph_get_ret_stack(struct task_struct *task, int idx)
280 {
281 	idx = task->curr_ret_stack - idx;
282 
283 	if (idx >= 0 && idx <= task->curr_ret_stack)
284 		return &task->ret_stack[idx];
285 
286 	return NULL;
287 }
288 
289 /**
290  * ftrace_graph_ret_addr - convert a potentially modified stack return address
291  *			   to its original value
292  *
293  * This function can be called by stack unwinding code to convert a found stack
294  * return address ('ret') to its original value, in case the function graph
295  * tracer has modified it to be 'return_to_handler'.  If the address hasn't
296  * been modified, the unchanged value of 'ret' is returned.
297  *
298  * 'idx' is a state variable which should be initialized by the caller to zero
299  * before the first call.
300  *
301  * 'retp' is a pointer to the return address on the stack.  It's ignored if
302  * the arch doesn't have HAVE_FUNCTION_GRAPH_RET_ADDR_PTR defined.
303  */
304 #ifdef HAVE_FUNCTION_GRAPH_RET_ADDR_PTR
305 unsigned long ftrace_graph_ret_addr(struct task_struct *task, int *idx,
306 				    unsigned long ret, unsigned long *retp)
307 {
308 	int index = task->curr_ret_stack;
309 	int i;
310 
311 	if (ret != (unsigned long)dereference_kernel_function_descriptor(return_to_handler))
312 		return ret;
313 
314 	if (index < 0)
315 		return ret;
316 
317 	for (i = 0; i <= index; i++)
318 		if (task->ret_stack[i].retp == retp)
319 			return task->ret_stack[i].ret;
320 
321 	return ret;
322 }
323 #else /* !HAVE_FUNCTION_GRAPH_RET_ADDR_PTR */
324 unsigned long ftrace_graph_ret_addr(struct task_struct *task, int *idx,
325 				    unsigned long ret, unsigned long *retp)
326 {
327 	int task_idx;
328 
329 	if (ret != (unsigned long)dereference_kernel_function_descriptor(return_to_handler))
330 		return ret;
331 
332 	task_idx = task->curr_ret_stack;
333 
334 	if (!task->ret_stack || task_idx < *idx)
335 		return ret;
336 
337 	task_idx -= *idx;
338 	(*idx)++;
339 
340 	return task->ret_stack[task_idx].ret;
341 }
342 #endif /* HAVE_FUNCTION_GRAPH_RET_ADDR_PTR */
343 
344 static struct ftrace_ops graph_ops = {
345 	.func			= ftrace_graph_func,
346 	.flags			= FTRACE_OPS_FL_INITIALIZED |
347 				   FTRACE_OPS_FL_PID |
348 				   FTRACE_OPS_GRAPH_STUB,
349 #ifdef FTRACE_GRAPH_TRAMP_ADDR
350 	.trampoline		= FTRACE_GRAPH_TRAMP_ADDR,
351 	/* trampoline_size is only needed for dynamically allocated tramps */
352 #endif
353 	ASSIGN_OPS_HASH(graph_ops, &global_ops.local_hash)
354 };
355 
356 void ftrace_graph_sleep_time_control(bool enable)
357 {
358 	fgraph_sleep_time = enable;
359 }
360 
361 int ftrace_graph_entry_stub(struct ftrace_graph_ent *trace)
362 {
363 	return 0;
364 }
365 
366 /*
367  * Simply points to ftrace_stub, but with the proper protocol.
368  * Defined by the linker script in linux/vmlinux.lds.h
369  */
370 extern void ftrace_stub_graph(struct ftrace_graph_ret *);
371 
372 /* The callbacks that hook a function */
373 trace_func_graph_ret_t ftrace_graph_return = ftrace_stub_graph;
374 trace_func_graph_ent_t ftrace_graph_entry = ftrace_graph_entry_stub;
375 static trace_func_graph_ent_t __ftrace_graph_entry = ftrace_graph_entry_stub;
376 
377 /* Try to assign a return stack array on FTRACE_RETSTACK_ALLOC_SIZE tasks. */
378 static int alloc_retstack_tasklist(struct ftrace_ret_stack **ret_stack_list)
379 {
380 	int i;
381 	int ret = 0;
382 	int start = 0, end = FTRACE_RETSTACK_ALLOC_SIZE;
383 	struct task_struct *g, *t;
384 
385 	for (i = 0; i < FTRACE_RETSTACK_ALLOC_SIZE; i++) {
386 		ret_stack_list[i] =
387 			kmalloc_array(FTRACE_RETFUNC_DEPTH,
388 				      sizeof(struct ftrace_ret_stack),
389 				      GFP_KERNEL);
390 		if (!ret_stack_list[i]) {
391 			start = 0;
392 			end = i;
393 			ret = -ENOMEM;
394 			goto free;
395 		}
396 	}
397 
398 	rcu_read_lock();
399 	for_each_process_thread(g, t) {
400 		if (start == end) {
401 			ret = -EAGAIN;
402 			goto unlock;
403 		}
404 
405 		if (t->ret_stack == NULL) {
406 			atomic_set(&t->trace_overrun, 0);
407 			t->curr_ret_stack = -1;
408 			t->curr_ret_depth = -1;
409 			/* Make sure the tasks see the -1 first: */
410 			smp_wmb();
411 			t->ret_stack = ret_stack_list[start++];
412 		}
413 	}
414 
415 unlock:
416 	rcu_read_unlock();
417 free:
418 	for (i = start; i < end; i++)
419 		kfree(ret_stack_list[i]);
420 	return ret;
421 }
422 
423 static void
424 ftrace_graph_probe_sched_switch(void *ignore, bool preempt,
425 				struct task_struct *prev,
426 				struct task_struct *next,
427 				unsigned int prev_state)
428 {
429 	unsigned long long timestamp;
430 	int index;
431 
432 	/*
433 	 * Does the user want to count the time a function was asleep.
434 	 * If so, do not update the time stamps.
435 	 */
436 	if (fgraph_sleep_time)
437 		return;
438 
439 	timestamp = trace_clock_local();
440 
441 	prev->ftrace_timestamp = timestamp;
442 
443 	/* only process tasks that we timestamped */
444 	if (!next->ftrace_timestamp)
445 		return;
446 
447 	/*
448 	 * Update all the counters in next to make up for the
449 	 * time next was sleeping.
450 	 */
451 	timestamp -= next->ftrace_timestamp;
452 
453 	for (index = next->curr_ret_stack; index >= 0; index--)
454 		next->ret_stack[index].calltime += timestamp;
455 }
456 
457 static int ftrace_graph_entry_test(struct ftrace_graph_ent *trace)
458 {
459 	if (!ftrace_ops_test(&global_ops, trace->func, NULL))
460 		return 0;
461 	return __ftrace_graph_entry(trace);
462 }
463 
464 /*
465  * The function graph tracer should only trace the functions defined
466  * by set_ftrace_filter and set_ftrace_notrace. If another function
467  * tracer ops is registered, the graph tracer requires testing the
468  * function against the global ops, and not just trace any function
469  * that any ftrace_ops registered.
470  */
471 void update_function_graph_func(void)
472 {
473 	struct ftrace_ops *op;
474 	bool do_test = false;
475 
476 	/*
477 	 * The graph and global ops share the same set of functions
478 	 * to test. If any other ops is on the list, then
479 	 * the graph tracing needs to test if its the function
480 	 * it should call.
481 	 */
482 	do_for_each_ftrace_op(op, ftrace_ops_list) {
483 		if (op != &global_ops && op != &graph_ops &&
484 		    op != &ftrace_list_end) {
485 			do_test = true;
486 			/* in double loop, break out with goto */
487 			goto out;
488 		}
489 	} while_for_each_ftrace_op(op);
490  out:
491 	if (do_test)
492 		ftrace_graph_entry = ftrace_graph_entry_test;
493 	else
494 		ftrace_graph_entry = __ftrace_graph_entry;
495 }
496 
497 static DEFINE_PER_CPU(struct ftrace_ret_stack *, idle_ret_stack);
498 
499 static void
500 graph_init_task(struct task_struct *t, struct ftrace_ret_stack *ret_stack)
501 {
502 	atomic_set(&t->trace_overrun, 0);
503 	t->ftrace_timestamp = 0;
504 	/* make curr_ret_stack visible before we add the ret_stack */
505 	smp_wmb();
506 	t->ret_stack = ret_stack;
507 }
508 
509 /*
510  * Allocate a return stack for the idle task. May be the first
511  * time through, or it may be done by CPU hotplug online.
512  */
513 void ftrace_graph_init_idle_task(struct task_struct *t, int cpu)
514 {
515 	t->curr_ret_stack = -1;
516 	t->curr_ret_depth = -1;
517 	/*
518 	 * The idle task has no parent, it either has its own
519 	 * stack or no stack at all.
520 	 */
521 	if (t->ret_stack)
522 		WARN_ON(t->ret_stack != per_cpu(idle_ret_stack, cpu));
523 
524 	if (ftrace_graph_active) {
525 		struct ftrace_ret_stack *ret_stack;
526 
527 		ret_stack = per_cpu(idle_ret_stack, cpu);
528 		if (!ret_stack) {
529 			ret_stack =
530 				kmalloc_array(FTRACE_RETFUNC_DEPTH,
531 					      sizeof(struct ftrace_ret_stack),
532 					      GFP_KERNEL);
533 			if (!ret_stack)
534 				return;
535 			per_cpu(idle_ret_stack, cpu) = ret_stack;
536 		}
537 		graph_init_task(t, ret_stack);
538 	}
539 }
540 
541 /* Allocate a return stack for newly created task */
542 void ftrace_graph_init_task(struct task_struct *t)
543 {
544 	/* Make sure we do not use the parent ret_stack */
545 	t->ret_stack = NULL;
546 	t->curr_ret_stack = -1;
547 	t->curr_ret_depth = -1;
548 
549 	if (ftrace_graph_active) {
550 		struct ftrace_ret_stack *ret_stack;
551 
552 		ret_stack = kmalloc_array(FTRACE_RETFUNC_DEPTH,
553 					  sizeof(struct ftrace_ret_stack),
554 					  GFP_KERNEL);
555 		if (!ret_stack)
556 			return;
557 		graph_init_task(t, ret_stack);
558 	}
559 }
560 
561 void ftrace_graph_exit_task(struct task_struct *t)
562 {
563 	struct ftrace_ret_stack	*ret_stack = t->ret_stack;
564 
565 	t->ret_stack = NULL;
566 	/* NULL must become visible to IRQs before we free it: */
567 	barrier();
568 
569 	kfree(ret_stack);
570 }
571 
572 /* Allocate a return stack for each task */
573 static int start_graph_tracing(void)
574 {
575 	struct ftrace_ret_stack **ret_stack_list;
576 	int ret, cpu;
577 
578 	ret_stack_list = kmalloc_array(FTRACE_RETSTACK_ALLOC_SIZE,
579 				       sizeof(struct ftrace_ret_stack *),
580 				       GFP_KERNEL);
581 
582 	if (!ret_stack_list)
583 		return -ENOMEM;
584 
585 	/* The cpu_boot init_task->ret_stack will never be freed */
586 	for_each_online_cpu(cpu) {
587 		if (!idle_task(cpu)->ret_stack)
588 			ftrace_graph_init_idle_task(idle_task(cpu), cpu);
589 	}
590 
591 	do {
592 		ret = alloc_retstack_tasklist(ret_stack_list);
593 	} while (ret == -EAGAIN);
594 
595 	if (!ret) {
596 		ret = register_trace_sched_switch(ftrace_graph_probe_sched_switch, NULL);
597 		if (ret)
598 			pr_info("ftrace_graph: Couldn't activate tracepoint"
599 				" probe to kernel_sched_switch\n");
600 	}
601 
602 	kfree(ret_stack_list);
603 	return ret;
604 }
605 
606 int register_ftrace_graph(struct fgraph_ops *gops)
607 {
608 	int ret = 0;
609 
610 	mutex_lock(&ftrace_lock);
611 
612 	/* we currently allow only one tracer registered at a time */
613 	if (ftrace_graph_active) {
614 		ret = -EBUSY;
615 		goto out;
616 	}
617 
618 	register_pm_notifier(&ftrace_suspend_notifier);
619 
620 	ftrace_graph_active++;
621 	ret = start_graph_tracing();
622 	if (ret) {
623 		ftrace_graph_active--;
624 		goto out;
625 	}
626 
627 	ftrace_graph_return = gops->retfunc;
628 
629 	/*
630 	 * Update the indirect function to the entryfunc, and the
631 	 * function that gets called to the entry_test first. Then
632 	 * call the update fgraph entry function to determine if
633 	 * the entryfunc should be called directly or not.
634 	 */
635 	__ftrace_graph_entry = gops->entryfunc;
636 	ftrace_graph_entry = ftrace_graph_entry_test;
637 	update_function_graph_func();
638 
639 	ret = ftrace_startup(&graph_ops, FTRACE_START_FUNC_RET);
640 out:
641 	mutex_unlock(&ftrace_lock);
642 	return ret;
643 }
644 
645 void unregister_ftrace_graph(struct fgraph_ops *gops)
646 {
647 	mutex_lock(&ftrace_lock);
648 
649 	if (unlikely(!ftrace_graph_active))
650 		goto out;
651 
652 	ftrace_graph_active--;
653 	ftrace_graph_return = ftrace_stub_graph;
654 	ftrace_graph_entry = ftrace_graph_entry_stub;
655 	__ftrace_graph_entry = ftrace_graph_entry_stub;
656 	ftrace_shutdown(&graph_ops, FTRACE_STOP_FUNC_RET);
657 	unregister_pm_notifier(&ftrace_suspend_notifier);
658 	unregister_trace_sched_switch(ftrace_graph_probe_sched_switch, NULL);
659 
660  out:
661 	mutex_unlock(&ftrace_lock);
662 }
663