How to View Linux Kernel and User Space Stacks – Free Linux Device Driver Training

🚀 Learn BLE on Linux (BlueZ) – Programming Part 1

Hands-on Bluetooth Low Energy course. Special price: ₹399

Enroll Now on Udemy →
💬 Need help or career guidance? Ask us!Contact Us →
How to View Linux Kernel and User Space Stacks | Free Linux Kernel Programming Course – EmbeddedPathashala

How to View Linux Kernel and User Space Stacks
Free Linux Kernel Programming Course | EmbeddedPathashala
Level
Intermediate
Topic
Kernel Debugging
Kernel
Linux 6.x

Viewing the Kernel-Mode and User-Mode Stack of Any Linux Thread — A Practical Guide

When something goes wrong in a kernel module or a device driver, the call stack is almost always the first place you look. It tells you exactly where the thread was when the problem occurred and how it got there. But Linux threads have two stacks — a user-mode stack and a kernel-mode stack — and knowing how to view both is an essential skill for any Linux kernel or embedded systems developer.

This is part of the free Linux kernel development course at EmbeddedPathashala. In this tutorial we cover the traditional approach to viewing stacks via the /proc filesystem, and introduce the modern eBPF-based approach available on Linux 6.x systems.

What You Will Learn

  • Why the call stack is critical for debugging kernel and driver issues
  • How to view the kernel-mode stack of any thread via /proc/<pid>/stack
  • What a kernel stack backtrace looks like and how to read it
  • Security restrictions on stack viewing in modern Linux kernels
  • How to view the user-mode stack of a process
  • Introduction to eBPF-based stack tracing as a modern alternative
  • Practical debugging workflow using kernel and user stack information
  • Comparison of all available stack inspection tools

Prerequisites

  • Understanding of Linux threads, processes, and PIDs
  • Familiarity with the concept of kernel-mode stacks (covered in the previous tutorial)
  • Root access on a Linux system to view kernel stacks
  • Basic command-line knowledge
Key Concepts in This Article
/proc/pid/stack kernel call chain backtrace eBPF stack tracing kernel debugging user stack perf tool kptr_restrict

Why the Stack is the Key to Kernel Debugging

The stack is not just a memory region — it is a live record of what a thread is doing right now and how it got there. When you look at a thread’s call stack (also called a call chain or backtrace), you can answer these questions instantly:

  • Which function is currently executing?
  • Which function called it?
  • And what called that, all the way back to the original entry point?

This information is indispensable when debugging a kernel panic, a deadlock, a device driver hang, or unexpected behaviour in a kernel module. For user-space bugs, tools like gdb and strace are familiar. For kernel-space, the /proc filesystem gives you direct access to the kernel-mode call chain of any thread on the system.

Figure 1 — The Two Stacks of a User Thread: What Each Stack Shows You
User-Mode Stack
Shows:
main()
app_init()
read_config()
libc: read() wrapper
← Application-level call chain (what your app is doing)
⇄
Kernel-Mode Stack
Shows:
entry_SYSCALL_64
sys_read()
vfs_read()
ext4_file_read_iter()
← Kernel-level call chain (what the kernel is doing for your app)
Together, both stacks give you the complete picture of what a thread is doing at any moment

Traditional Approach: Viewing the Kernel-Mode Stack via /proc

The Linux kernel exposes the kernel-mode call stack of every thread through the proc filesystem — specifically via /proc/<pid>/stack. This is the most straightforward way to inspect what a thread is doing in kernel space, and it requires no special tools beyond shell access.

Step-by-Step: Reading the Kernel Stack of a Process

1
Find the PID of the process you want to inspect
# Find the PID of your target process
ps aux | grep bash

# Or use pgrep
pgrep bash
Let’s say the bash process we want to inspect has PID 3085.
2
Read the kernel-mode stack via /proc
# Must be root (or have CAP_SYS_PTRACE)
sudo cat /proc/3085/stack
3
Interpret the output — example kernel stack backtrace
[<0>] do_wait+0x1d2/0x230
[<0>] kernel_wait4+0x8d/0x130
[<0>] __do_sys_wait4+0x87/0xa0
[<0>] do_syscall_64+0x5b/0x1d0
[<0>] entry_SYSCALL_64_after_hwframe+0x65/0xca

Reading this from bottom to top (as is standard for call stacks):

  • entry_SYSCALL_64_after_hwframe — the user-space program made a system call, entering the kernel
  • do_syscall_64 — the kernel’s system call dispatcher
  • __do_sys_wait4 — the wait4() system call implementation
  • kernel_wait4 — internal wait implementation
  • do_wait — the current top of the call chain — the bash process is waiting for a child process
Note — Addresses Shown as <0> in Modern Kernels:
On Linux kernels with kptr_restrict set to 1 or 2 (which is the default on most modern distributions), kernel pointer addresses are hidden from non-root users and shown as <0>. This is a security measure to prevent address leaks that could be exploited for kernel exploits. Even as root, some distributions may still restrict this. The function names are still visible and are the important part.
Figure 2 — How to Read a /proc/pid/stack Kernel Backtrace
[<0>] do_wait+0x1d2/0x230
← TOP: currently executing
[<0>] kernel_wait4+0x8d/0x130
called do_wait()
[<0>] __do_sys_wait4+0x87/0xa0
syscall impl.
[<0>] do_syscall_64+0x5b/0x1d0
syscall dispatcher
[<0>] entry_SYSCALL_64_after_hwframe+0x65/0xca
← BOTTOM: entry from user space
Read bottom → top to follow the execution path from entry to current position

Viewing the Kernel Stack of All Threads of a Multi-threaded Process

In a multi-threaded process, each thread has its own TID (Thread ID). To view the kernel stack of a specific thread, use its TID rather than the process PID:

# List all threads of a process (PID 3085 in this example)
ls /proc/3085/task/

# View the kernel stack of a specific thread (TID 3087)
sudo cat /proc/3085/task/3087/stack
Tip: On Linux 6.x, the /proc/<pid>/task/ directory contains one subdirectory per thread. Each subdirectory is named with the thread’s TID. Each has its own stack file showing that specific thread’s current kernel-mode call chain.

Security Restrictions on Kernel Stack Viewing in Linux 6.x

Modern Linux kernels include several security controls that restrict who can view kernel stack information. Understanding these is important when debugging on hardened production systems.

Kernel Parameter Value Effect on /proc/pid/stack
kptr_restrict 0 Kernel addresses visible to all users (insecure — not default)
kptr_restrict 1 (default) Addresses shown as 0x0 to non-privileged users; visible to root
kptr_restrict 2 Addresses hidden from all users including root
perf_event_paranoid -1 to 3 Controls access to perf events (affects eBPF stack tracing)
# Check current kptr_restrict setting
cat /proc/sys/kernel/kptr_restrict

# Temporarily allow kernel addresses in output (for debugging only — revert afterward)
sudo sysctl -w kernel.kptr_restrict=0

# View stack with addresses visible
sudo cat /proc/3085/stack

# Revert to secure setting
sudo sysctl -w kernel.kptr_restrict=1
Security Warning: Never leave kptr_restrict=0 on a production system. Kernel pointer leakage can be exploited by attackers to bypass KASLR (Kernel Address Space Layout Randomization) protections. Only set it to 0 temporarily during kernel debugging on a development machine.

Viewing the User-Mode Stack of a Process

Viewing the user-mode stack is different from viewing the kernel stack. The user-mode stack lives in user space and requires either the process’s own unwinding logic or an external tool that can attach to the process and read its user-space memory.

Method 1: Using /proc/pid/wchan — What Channel is the Thread Waiting On?

A quick way to understand what a thread is doing in kernel space without reading the full stack is /proc/<pid>/wchan — it shows the kernel function where the thread is currently sleeping (waiting).

# What is the bash process waiting on?
cat /proc/3085/wchan

# Example output:
do_wait

This tells you that the bash process is currently sleeping inside the do_wait() kernel function — meaning it is waiting for a child process to finish. This matches what we saw in the full kernel stack earlier.

Method 2: Using pstack or gdb to Get a Full User-Mode Backtrace

For a complete user-mode call chain, you can use pstack (which wraps gdb) or gdb directly:

# Using pstack (if installed — usually in gdb package on some distros)
sudo pstack 3085

# Using gdb to attach to a running process
sudo gdb -p 3085

# Inside gdb:
(gdb) info threads          # list all threads
(gdb) thread 1              # switch to thread 1
(gdb) bt                    # print backtrace (user-mode call chain)
(gdb) bt full               # print backtrace with local variables

Method 3: Using perf to Capture Call Stacks System-Wide

The perf tool is a powerful Linux performance analysis tool that can capture both user-mode and kernel-mode call stacks across all processes simultaneously. This is very useful for understanding what the entire system is doing.

# Record call stacks for 10 seconds, including both user and kernel stacks
sudo perf record -g -a -- sleep 10

# View the report with call chain information
sudo perf report --call-graph

# Record stacks for a specific PID only
sudo perf record -g -p 3085 -- sleep 5
sudo perf report

Modern Approach: eBPF-Based Stack Tracing on Linux 6.x

The traditional /proc-based approach is excellent for inspecting a specific process at a specific moment. But for dynamic tracing — capturing stack information over time, across all processes, without stopping execution — eBPF (extended Berkeley Packet Filter) is the modern approach on Linux 6.x.

What is eBPF and Why Does it Matter for Stack Tracing?

eBPF allows you to run safe, sandboxed programs inside the Linux kernel without modifying kernel source code or loading a kernel module. For stack tracing, eBPF programs can be attached to kernel functions, tracepoints, or hardware performance counters, and they can capture the complete call chain — both kernel and user space — with extremely low overhead.

Figure 3 — eBPF Stack Tracing Architecture on Linux 6.x
User Space
bpftrace script
(your eBPF program)
BCC tools
(Python + eBPF)
perf
(perf + eBPF)
↓ compiled and loaded via BPF syscall ↓
Kernel Space — eBPF Verifier + Runtime
BPF verifier
(safety check)
Kprobe / Tracepoint
(attach point)
bpf_get_stackid()
(captures stack)
↓ stack data sent to user space via BPF maps ↓
Output: Complete kernel + user-space call chains for every relevant event

Practical Example: Capture All Kernel Stack Traces with bpftrace

bpftrace is the recommended tool for eBPF-based stack tracing on modern Linux. It provides a high-level scripting language for writing eBPF programs without needing to understand the full eBPF C API.

# Install bpftrace (on Ubuntu/Debian)
sudo apt install bpftrace

# Print kernel stack every time any process calls the 'do_sys_open' function
sudo bpftrace -e 'kprobe:do_sys_openat2 { printf("PID %d opened a file\n", pid); print(kstack); }'

Example output:

PID 3085 opened a file
        do_sys_openat2+1
        do_syscall_64+84
        entry_SYSCALL_64_after_hwframe+101

PID 2947 opened a file
        do_sys_openat2+1
        do_syscall_64+84
        entry_SYSCALL_64_after_hwframe+101
# Capture both kernel AND user stack for a specific process (PID 3085)
sudo bpftrace -e 'kprobe:vfs_read /pid == 3085/ { print(kstack); print(ustack); }'
Note on Function Names in Linux 6.x: Some function names changed between kernel versions. For example, do_sys_open() was replaced by do_sys_openat2() in newer kernels. If a kprobe does not attach, check the current function name using sudo bpftrace -l 'kprobe:*open*' to list available probe points.

Comparison of Stack Viewing Methods

Method Stack Type Root Required? Best For Linux Version
/proc/<pid>/stack Kernel-mode only Yes Quick point-in-time snapshot All modern kernels
/proc/<pid>/wchan Kernel (wait channel) No See what a thread is sleeping on All modern kernels
pstack / gdb bt User-mode only Yes (for other processes) Full user-space call chain All
perf record -g Both (kernel + user) Yes Profiling and call chain analysis Linux 3.x+
bpftrace kstack/ustack Both (kernel + user) Yes Dynamic tracing without stopping execution Linux 4.9+ (full support 5.x+)

Practical Debugging Workflow: Using Stack Information to Diagnose Kernel Issues

Scenario: A Driver is Stuck — How Do You Find Out Why?
  1. Identify the stuck process:
    ps aux | grep D (state ‘D’ = uninterruptible sleep — classic sign of a stuck kernel wait)
  2. Get the kernel stack instantly:
    sudo cat /proc/<pid>/stack
  3. Read the call chain bottom to top to understand the code path that led to the current state
  4. Check wchan to confirm which kernel function the thread is sleeping in:
    cat /proc/<pid>/wchan
  5. If the issue is intermittent, use bpftrace to capture stack traces dynamically across multiple occurrences without modifying the driver

Best Practices for Stack-Based Kernel Debugging

  • Always build your kernel modules with debug symbols (-g flag in the Makefile) so that function names in stack traces are human-readable rather than raw addresses.
  • Keep CONFIG_KALLSYMS=y in your kernel configuration to ensure function name resolution works in stack traces.
  • Enable CONFIG_FRAME_POINTER=y during development to improve the accuracy of kernel stack backtraces.
  • Use CONFIG_DEBUG_KERNEL=y and related options during driver development to enable additional kernel self-checks.
  • Document your debugging findings — when a kernel stack trace reveals the root cause of a bug, note the call chain so future debugging sessions are faster.

Key Takeaways

  • Every thread has two stacks: a user-mode stack (user space execution) and a kernel-mode stack (kernel execution on behalf of that thread).
  • The kernel-mode stack is exposed via /proc/<pid>/stack and requires root access on modern Linux.
  • Kernel pointer addresses are hidden by default (kptr_restrict=1) but function names remain visible.
  • Read kernel backtraces bottom to top — the bottom entry is the entry point (e.g., syscall entry) and the top entry is the current position.
  • /proc/<pid>/wchan gives a quick one-word summary of what a thread is currently waiting on in the kernel.
  • perf record -g captures both user and kernel stacks across all processes for profiling and analysis.
  • bpftrace provides dynamic, low-overhead stack tracing with eBPF — the recommended modern approach on Linux 6.x.

Conclusion

The ability to view and interpret both the kernel-mode and user-mode stacks of any Linux thread is a superpower for kernel and embedded systems developers. Whether you are debugging a deadlock in a device driver, investigating a kernel panic, or understanding the code path through the kernel for a specific system call, the techniques covered in this tutorial are your primary tools.

This free Linux kernel programming course at EmbeddedPathashala continues with a deep dive into struct task_struct — the data structure at the heart of every thread on the system. Understanding task_struct will give you even deeper insight into how the kernel manages processes, scheduling, and resources.

Frequently Asked Questions (FAQ)

Q1: How do I view the kernel stack of a process on Linux 6.x?

Run sudo cat /proc/<pid>/stack as root. Replace <pid> with the process ID. The output shows the kernel-mode call chain, read from bottom to top.

Q2: Why does /proc/pid/stack show <0> instead of addresses?

This is controlled by the kptr_restrict kernel parameter. When set to 1 (the default), kernel addresses are hidden to prevent information leakage. Function names are still shown. You can temporarily set kptr_restrict=0 as root on a development machine to see actual addresses.

Q3: What does process state ‘D’ mean and how do I debug it?

State ‘D’ (uninterruptible sleep) means the thread is waiting inside the kernel for a resource (typically I/O) and cannot be interrupted by signals. To find out why, read its kernel stack with sudo cat /proc/<pid>/stack. The call chain will show exactly which kernel function it is waiting in.

Q4: Can I view the kernel stack without root access?

No. Viewing the kernel-mode stack of a process requires root access (or CAP_SYS_PTRACE) on modern Linux kernels for security reasons. You can view a process’s own user-mode stack if it has debugging symbols, but kernel stacks are always root-restricted.

Q5: What is wchan in /proc?

/proc/<pid>/wchan shows the name of the kernel function where the thread is currently sleeping. It is a quick one-word summary — for example, do_wait means the thread is waiting for a child process. It requires no root access and is less detailed than the full /stack output.

Q6: What is bpftrace and how is it different from /proc/pid/stack?

bpftrace uses eBPF to dynamically trace kernel and user-space events in real time without stopping execution. Unlike /proc/pid/stack which gives a static point-in-time snapshot, bpftrace can capture stacks from specific events (e.g., every time vfs_read() is called), across all processes, with minimal overhead.

Q7: Do I need to recompile the kernel to use these debugging techniques?

No. The /proc filesystem interface is available in all standard Linux kernels. For bpftrace and eBPF tools, you need a kernel with CONFIG_BPF=y and CONFIG_BPF_SYSCALL=y (enabled by default in most modern distros). For better backtraces, building your kernel modules with -g and enabling CONFIG_FRAME_POINTER is recommended.

Q8: How do I view the stack of a kernel thread (not a user thread)?

Exactly the same way — sudo cat /proc/<tid>/stack where <tid> is the kernel thread’s TID. You can find kernel thread TIDs with ps -eLf | grep '\[kworker\]' for example. Kernel threads show only their kernel-mode stack (they have no user-mode stack).

References and Further Reading

Keep Learning — Free Linux Kernel and Device Driver Course

EmbeddedPathashala offers 100% free, depth-first courses on Linux kernel internals, device drivers, embedded systems, and Bluetooth/BLE development.

Next: Understanding task_struct → ← Back to Course Index
💬 Need help or career guidance? Ask us!Contact Us →

Leave a Reply

Your email address will not be published. Required fields are marked *

×

🚀 BLE on Linux (BlueZ)

Hands-on course. Only ₹399

Enroll Now →