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