Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print the current thread stack trace inside the Linux kernel?

I would like to be able to print the stack trace of a thread in the Linux kernel.

In details: I want to add code to specific functions (e.g. swap_writepage() ) that will print the complete stack trace of the thread where this function is being called. Something like this:

int swap_writepage(struct page *page, struct writeback_control *wbc)
{

    /* code goes here to print stack trace */

    int ret = 0;

    if (try_to_free_swap(page)) {
        unlock_page(page);
        goto out;
    }
    if (frontswap_store(page) == 0) {
        set_page_writeback(page);
        unlock_page(page);
        end_page_writeback(page);
        goto out;
    }
    ret = __swap_writepage(page, wbc, end_swap_bio_write);
out:
    return ret;
}
like image 803
hebbo Avatar asked Jan 15 '14 17:01

hebbo


People also ask

How do I print current stack trace?

Just use new Throwable(). printStackTrace() method and it will print complete stack trace from where a method is called, into the console.

How do I print a call stack in kernel?

Linux kernel provides a function to print the stack trace: dump_stack(). The dump_stack function produces a stack trace much like panic and oops, but causes no problems and we return to the normal control flow. Calling dump_stack() function will print the stack trace at that point.

What is kernel stack trace?

Kernel has the ability to examine the size of the kernel stack and how much stack space each function is using. Enabling the stack tracer ( CONFIG_STACK_TRACER ) will show where the biggest use of the stack takes place. The stack tracer is built form the function tracer infrastructure.


2 Answers

Linux kernel has very well known function called dump_stack() here, which prints the content of the stack. Place it in your function in according to see stack info.

like image 175
rakib_ Avatar answered Sep 18 '22 12:09

rakib_


@rakib is exactly right of course.

In addition, I'd like to point out that one can define simple and elegant macros that help print debug info as and when required. Over the years, I've put these macros and conveneince routines into a header file; you can check it out and download it here: "A Header of Convenience".

There are macros / functions to:

  • make debug prints along with funcname / line# info (via the usual printk() or trace_printk()) and only if DEBUG mode is On
  • dump the kernel-mode stack
  • print the current context (process or interrupt along with flags in the form that ftrace uses)
  • a simple assert() macro (!)
  • a cpu-intensive DELAY_LOOP (useful for test rigs that must spin on the processor)
  • an equivalent to usermode sleep functionality
  • a function to calculate the time delta given two timestamps (timeval structs)
  • convert decimal to binary, and
  • a few more.

Whew :-)

like image 34
kaiwan Avatar answered Sep 21 '22 12:09

kaiwan