🚀 Learn BLE on Linux (BlueZ) – Programming Part 1
Hands-on Bluetooth Low Energy course. Special price: ₹399
Enroll Now on Udemy →Intermediate
Kernel Debugging
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
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.
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
# 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.
# Must be root (or have CAP_SYS_PTRACE)
sudo cat /proc/3085/stack
[<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 kerneldo_syscall_64— the kernel’s system call dispatcher__do_sys_wait4— thewait4()system call implementationkernel_wait4— internal wait implementationdo_wait— the current top of the call chain — the bash process is waiting for a child process
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.
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
/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
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.
(your eBPF program)
(Python + eBPF)
(perf + eBPF)
(safety check)
(attach point)
(captures stack)
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); }'
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
- Identify the stuck process:
ps aux | grep D(state ‘D’ = uninterruptible sleep — classic sign of a stuck kernel wait) - Get the kernel stack instantly:
sudo cat /proc/<pid>/stack - Read the call chain bottom to top to understand the code path that led to the current state
- Check wchan to confirm which kernel function the thread is sleeping in:
cat /proc/<pid>/wchan - 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 (
-gflag in the Makefile) so that function names in stack traces are human-readable rather than raw addresses. - Keep
CONFIG_KALLSYMS=yin your kernel configuration to ensure function name resolution works in stack traces. - Enable
CONFIG_FRAME_POINTER=yduring development to improve the accuracy of kernel stack backtraces. - Use
CONFIG_DEBUG_KERNEL=yand 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>/stackand 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>/wchangives a quick one-word summary of what a thread is currently waiting on in the kernel.perf record -gcaptures both user and kernel stacks across all processes for profiling and analysis.bpftraceprovides 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)
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.
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.
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.
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.
/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.
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.
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.
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
- Linux Kernel Documentation: The /proc Filesystem
- BPF Performance Tools — Brendan Gregg (book reference)
- Linux Kernel eBPF Documentation
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