So I am trying to find out what kernel processes are calling some functions in a block driver. I thought including backtrace() in the C library would make it easy. But I am havi
If you need to save the stack trace and process its elements somehow, save_stack_trace()
or dump_trace()
might be also an option. These functions are declared in <linux/stacktrace.h>
and <asm/stacktrace.h>
, respectively.
It is not as easy to use these as dump_stack()
but if you need more flexibility, they may be helpful.
Here is how save_stack_trace()
can be used (replace HOW_MANY_ENTRIES_TO_STORE
with the value that suits your needs, 16-32 is usually more than enough):
unsigned long stack_entries[HOW_MANY_ENTRIES_TO_STORE];
struct stack_trace trace = {
.nr_entries = 0,
.entries = &stack_entries[0],
.max_entries = HOW_MANY_ENTRIES_TO_STORE,
/* How many "lower entries" to skip. */
.skip = 0
};
save_stack_trace(&trace);
Now stack_entries
array contains the appropriate call addresses. The number of elements filled is nr_entries
.
One more thing to point out. If it is desirable not to output the stack entries that belong to the implementation of save_stack_trace()
, dump_trace()
or dump_stack()
themselves (on different systems, the number of such entries may vary), the following trick can be applied if you use save_stack_trace()
. You can use __builtin_return_address(0)
as an "anchor" entry and process only the entries "not lower" than that.
I know this question is about Linux, but since it's the first result for "backtrace kernel", here's a few more solutions:
It's print_backtrace(int count)
from /sys/sys/systm.h. It's implemented in
/sys/kern/kern_debug.c and/or /sys/platform/pc64/x86_64/db_trace.c. It can be found by searching for panic
, which is implemented in /sys/kern/kern_shutdown.c, and calls print_backtrace(6)
if DDB
is defined and trace_on_panic
is set, which are both defaults.
It's kdb_backtrace(void)
from /sys/sys/kdb.h. Likewise, it's easy to find by looking into what the panic implementation calls when trace_on_panic
is true.
Going the panic route, it appears to be db_stack_dump(), implemented in /sys/ddb/db_output.c. The only header mention is /sys/ddb/db_output.h.
dump_stack()
is function can be used to print your stack and thus can be used to backtrack . while using it be carefull that don't put it in repetitive path like loops or packet receive function it can fill your dmesg buffer can cause crash in embedded device (having less memory and cpu).
This function is declared in linux/kernel.h
.
To print the stack contents and a backtrace to the kernel log, use the dump_stack()
function in your kernel module. It's declared in linux/kernel.h
in the include folder in the kernel source directory.