The Complete Guide to Debugging the Linux Kernel
A working method for Linux 6.12 kernel bugs: debug builds, reading oopses, runtime checkers, tracing, gdb in QEMU, hangs, and capturing crashes with kdump.

A bug in user space gives you a core file, a debugger and a process you can restart. A bug in the kernel gives you a log line, a frozen machine or nothing at all. The tools are different, the failure modes are stranger, and the same symptom can come from a dozen causes. This guide is a working method for finding kernel bugs on Linux 6.12, written for someone who can build a kernel and load a module and now needs to find out why it fails. It moves from the cheapest tool, a log message, to the heaviest, a crash dump analyzed offline, and it says at each step what the tool shows, what it costs and when to put it down.
The method fits in four sentences. Make the kernel tell you more before you try to find the bug, by building a debug kernel. Read the first failure report completely, since it usually names the bug. When there is no report, observe with tracing before you change anything. And when the machine will not talk, capture its dying words with a console, a network log or a dump. Everything below is a detailed version of that.
Start with a symptom, then pick the tool
Kernel failures present in a small number of ways, and each has a first tool. Use this table as a router, then read the sections for the tools you land on.
| Symptom | First tool | Section |
|---|---|---|
A message with Oops or BUG: in the log | Read the report; decode it with faddr2line | Reading failure reports |
WARNING: with a stack trace | Find the caller that passed the bad value | Reading failure reports |
BUG: sleeping function called from invalid context | Check the context named in the second line | Runtime checkers |
possible circular locking dependency | Lockdep report, fix the order | Runtime checkers |
| Random corruption, strange crashes later | KASAN, slub_debug, KFENCE | Runtime checkers |
| Memory use keeps growing | kmemleak, /proc/meminfo, slab counters | Memory problems |
| A device does not appear or probe | Deferred probe, dmesg, dev_dbg | Driver bring-up problems |
insmod fails | The error string and dmesg | Module load errors |
| A task hangs in D state | SysRq w, /proc/PID/stack | Hangs and lockups |
soft lockup or rcu: INFO: stall | The RIP and the other CPUs' backtraces | Hangs and lockups |
| The machine reboots or freezes with no message | Serial console, netconsole, pstore, kdump | Capturing a dying machine |
| It worked in the last release | git bisect | Bisecting |
| Slow, not broken | Tracing and profiling | Tracing |
| Only breaks on real hardware | Remote gdb, JTAG, tracing in the field | Interactive debugging |
Step zero: build a kernel that tells you more
Before looking for a bug, change the kernel so the bug has fewer places to hide. A distribution kernel is tuned for speed. A debug kernel is tuned to fail early and loudly. Make two build trees from the same source: a debug one for development and a plain one for measurements.
The options that matter most, covered in detail in the debug config post, are these:
CONFIG_DEBUG_KERNEL=y
CONFIG_DEBUG_INFO_DWARF5=y
CONFIG_GDB_SCRIPTS=y
CONFIG_PRINTK_TIME=y
CONFIG_DYNAMIC_DEBUG=y
CONFIG_MAGIC_SYSRQ=y
CONFIG_DEBUG_FS=y
CONFIG_PROVE_LOCKING=y
CONFIG_DEBUG_ATOMIC_SLEEP=y
CONFIG_DEBUG_LIST=y
CONFIG_KASAN=y
CONFIG_UBSAN=y
CONFIG_DEBUG_KMEMLEAK=y
CONFIG_DETECT_HUNG_TASK=y
CONFIG_FAULT_INJECTION=y
CONFIG_FAILSLAB=y
CONFIG_PANIC_ON_OOPS=nMerge them into your configuration and check that they survived:
scripts/kconfig/merge_config.sh -m .config debug.config
make olddefconfig
grep -E '^CONFIG_(KASAN|PROVE_LOCKING|DEBUG_INFO_DWARF5)=' .config
make -j"$(nproc)"CONFIG_DEBUG_INFO_DWARF5=y
CONFIG_PROVE_LOCKING=y
CONFIG_KASAN=yIf an option is missing from the grep output, its dependencies were not met, often because the compiler is too old. Keep the vmlinux and the unstripped modules of every build you run. Decoding a report later needs the exact build, and a report from a kernel you can no longer reproduce is far less useful. Two habits make everything else faster: boot your test kernels in QEMU, where a crash costs a few seconds, and keep the console log of every run in a file.
Level 1: printing
The oldest technique remains the most used. A message at the right place answers "did we get here, and with what values". The posts on printk levels and dynamic debug cover the mechanics. The working rules:
Use
dev_dbg()andpr_debug()and leave them in the source. With dynamic debug they cost almost nothing when off, and you switch them on at run time.Print values, not intentions.
ticker: irq 45 status 0x1beatsticker: in irq handler.Rate limit anything in an interrupt or a loop.
Do not debug timing bugs with
printk(). It is slow, and it changes the timing you are trying to see.
For a hot path, trace_printk() is the tool. It writes into the ftrace ring buffer, not the console, so it costs a fraction of printk() and does not disturb the system as much:
static irqreturn_t ticker_irq(int irq, void *data)
{
struct ticker *t = data;
u32 status = readl(t->base + TICKER_STATUS);
trace_printk("irq=%d status=0x%x count=%u\n", irq, status, t->count);
...
}Read the result from tracefs:
sudo cat /sys/kernel/tracing/trace | tail -n 3 ticker-test-2411 [003] d.h1. 6130.118342: ticker_irq: irq=45 status=0x1 count=100
ticker-test-2411 [003] d.h1. 6130.118902: ticker_irq: irq=45 status=0x1 count=101
ticker-test-2411 [003] d.h1. 6130.119462: ticker_irq: irq=45 status=0x1 count=102The columns are the task, the CPU, the context flags (h means hard interrupt), a timestamp and the message. Remove trace_printk() before you ship: a stray call prints a loud banner at boot on kernels that have one, and the kernel docs state it is for debugging only.
When you can enable a switch instead of recompiling, do that. Dynamic debug, covered in its own post, switches individual messages on:
echo 'module ticker +pfl' | sudo tee /sys/kernel/debug/dynamic_debug/controlmodule ticker +pflReading failure reports
Most kernel bugs announce themselves, and the first report is the one to read. Later reports are often consequences, and every report after the first oops carries D in the taint string. Save the whole text, from the first BUG: or WARNING: line to the end marker, before you reboot or reload anything. Read it in this order:
The headline and the error line. What kind of failure: NULL dereference, page fault, invalid opcode, a
WARN, a lockup message.**The
RIPline.** The function and offset where it happened.The call trace. Who called it, and from which context: a task, an interrupt, a timer.
The taint flags and the module list. What state the kernel was in, and whose code is loaded.
The distinction between events matters. A warning continues, an oops kills the task and leaves the kernel suspect, a BUG() is an oops on purpose, and a panic stops everything, as the oops versus panic post tabulates. Another post reads one oops line by line. The short version, for a NULL pointer report:
BUG: kernel NULL pointer dereference, address: 0000000000000008
RIP: 0010:ticker_read+0x2a/0x90 [ticker]The address is NULL plus a field offset of 8. The function is ticker_read, 0x2a bytes in. Turn that into a line with the decoders:
scripts/faddr2line ticker.ko ticker_read+0x2a/0x90ticker_read+0x2a/0x90:
ticker_read at /home/dev/ticker/ticker.c:57For a whole trace at once, pipe the saved report through scripts/decode_stacktrace.sh vmlinux auto <moddir> < oops.txt, and disassemble the Code: line with scripts/decodecode. Match the fault address to the field offset with pahole. At that point you usually know which pointer was bad, and the remaining question is why, which is a reading problem, not a debugging one: trace where the pointer is assigned and find the path where it is not.
Treat warnings seriously. A WARN_ON_ONCE() marks a state the developer believed impossible. Read the stack trace to find the caller who passed the bad value, because the line in the report is the check, not the cause.
Runtime checkers: let the kernel find the bug
The most productive kernel debugging happens before you have a symptom. A checker watches every operation and reports the first invalid one, close to the mistake, not hours later. These are the ones to run, and what each catches.
| Checker | Catches | Typical report text |
|---|---|---|
Lockdep (CONFIG_PROVE_LOCKING) | Lock order inversions, recursive locking, irq-unsafe locking | possible circular locking dependency detected |
CONFIG_DEBUG_ATOMIC_SLEEP | Sleeping in atomic context | BUG: sleeping function called from invalid context |
| KASAN | Use after free, out of bounds on heap, stack and globals | BUG: KASAN: slab-use-after-free in ... |
| UBSAN | Shifts, array bounds, signed overflow | UBSAN: array-index-out-of-bounds in ... |
| KCSAN | Data races between CPUs | BUG: KCSAN: data-race in ... |
| KFENCE | Sampled heap errors at low cost | BUG: KFENCE: use-after-free read in ... |
| kmemleak | Leaked allocations | unreferenced object 0x... (size 128) via debugfs |
slub_debug | Heap corruption with red zones and poison | BUG ticker_req: Poison overwritten |
| Debug objects | Timers and work items used before init or after free | ODEBUG: assert_init not available |
| Fault injection | Unchecked allocation failures | An oops on an error path |
A KASAN report is the model of a good one. It names the bad access, the object, and the stacks where the object was allocated and freed:
==================================================================
BUG: KASAN: slab-use-after-free in ticker_read+0x5e/0x120 [ticker]
Read of size 4 at addr ffff888104f6c208 by task cat/4411
CPU: 2 UID: 0 PID: 4411 Comm: cat Tainted: G O 6.12.0 #1
Call Trace:
<TASK>
dump_stack_lvl+0x5d/0x80
print_report+0xc1/0x600
kasan_report+0xb4/0xf0
ticker_read+0x5e/0x120 [ticker]
vfs_read+0xbe/0x320
</TASK>
Allocated by task 4410:
kasan_save_stack+0x33/0x60
__kasan_kmalloc+0x8f/0xa0
ticker_open+0x24/0x70 [ticker]
Freed by task 4410:
kasan_save_stack+0x33/0x60
kfree+0xe1/0x2a0
ticker_release+0x1a/0x30 [ticker]
==================================================================Read it as a story. The object was allocated in ticker_open, freed in ticker_release, and then ticker_read read it. The same task did the first two, which tells you a file was closed while another thread, or another descriptor of a duplicated file, still read from it. The fix is in the lifetime, a reference count or a lock, not in the line that read. Without KASAN, the same bug would show up as a random crash somewhere else, much later.
Fault injection finds a different class: bugs in error paths that no test reaches. With CONFIG_FAILSLAB and the debugfs controls, you can force the Nth allocation of a task to fail:
echo 1 | sudo tee /sys/kernel/debug/failslab/times
echo 100 | sudo tee /sys/kernel/debug/failslab/probability
echo 1 | sudo tee /sys/kernel/debug/failslab/verbose1
100
1Then load the module in a task whose /proc/self/make-it-fail is set to 1. The first kmalloc() in probe() fails, and any missing check shows up as an oops you can read and fix. This is the quickest way to find the unchecked allocation that a user will meet on a loaded machine once in a year.
Run the checkers in a regular test: load, exercise every entry point, unload, repeat, with the debug kernel. A clean run under lockdep and KASAN is the baseline for any patch. When a checker reports something, fix it before chasing other symptoms, since it is often the real cause of them.
Memory problems
Three kinds of memory bug need different tools.
Corruption (writing where you should not) is caught by KASAN, slub_debug and KFENCE. If you cannot run KASAN, boot with slub_debug=FZP, which turns on sanity checks, red zones and poisoning for every slab cache, and the first corruption prints with the object's allocation site.
Leaks (forgetting to free) are found with kmemleak. Build with CONFIG_DEBUG_KMEMLEAK=y, run the workload, and ask for a scan:
echo scan | sudo tee /sys/kernel/debug/kmemleak
sudo cat /sys/kernel/debug/kmemleak | head -n 12unreferenced object 0xffff888104f6c200 (size 128):
comm "insmod", pid 4388, jiffies 4295011217
hex dump (first 32 bytes):
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
backtrace (crc 3a1b2c4d):
[<00000000b3c1a2d4>] __kmalloc+0x1a6/0x3e0
[<00000000e1f2a3b4>] ticker_probe+0x4f/0x1a0 [ticker]The backtrace is where the leaked object was allocated, and ticker_probe is the place to look for the missing kfree() on an error path. Leaks that grow with use but are not reported as unreferenced, such as a cache that keeps everything, show up in /proc/slabinfo or slabtop as a cache whose object count never falls.
Exhaustion (too much in total) is visible in /proc/meminfo and /proc/vmstat. Compare Slab, SUnreclaim and MemAvailable over time. A stack overflow, which corrupts adjacent memory silently on a build without a guard, is caught by CONFIG_VMAP_STACK, on by default, which turns an overflow into a fault with a report.
Driver bring-up problems
Many "bugs" are a device that never starts. The questions are different from those about a crash, and the tools are the driver model's.
A device that never probes may be waiting for a dependency, for a clock, a regulator or a GPIO that another driver has not provided yet. The kernel keeps such devices on a deferred list:
sudo cat /sys/kernel/debug/devices_deferredticker.0 ticker: no clk provider for coreThe second column is the reason. If the list names a resource, find which driver should provide it and why it did not load. If the device is missing entirely, check that the match data agrees: the platform device or devicetree node name, the compatible string, the ID table of the driver. A driver that was never bound shows nothing in its driver link:
ls -l /sys/devices/platform/ticker/driver 2>&1
cat /sys/bus/platform/drivers_probe 2>&1 | head -n 1
dmesg | grep -i -E 'ticker|probe|deferred'ls: cannot access '/sys/devices/platform/ticker/driver': No such file or directoryTo force a retry after you fix a dependency, write the device name to drivers_probe:
echo ticker | sudo tee /sys/bus/platform/drivers_probetickerTurn on dev_dbg() output for the driver core while you work. The drivers/base call sites, enabled with echo 'file drivers/base/dd.c +p' | sudo tee .../control, print each match and bind attempt.
Module load errors
When insmod fails, the error string tells you which class of problem it is:
| Message | Meaning | Fix |
|---|---|---|
Unknown symbol in module (see dmesg for the name) | The module needs a symbol not exported by the running kernel or a missing module | Load the dependency, or build against the running kernel |
Invalid module format | Built for a different kernel version or configuration | Rebuild against the running kernel's tree |
Required key not available | Secure boot or module signing is enforced | Sign the module or enable your own key |
Operation not permitted | Not root, or module loading is locked down | Use root; check kernel.modules_disabled |
File exists | A module with that name is already loaded | rmmod it first |
Device or resource busy | init returned -EBUSY | A conflicting driver owns the resource |
No such device | init returned -ENODEV | The hardware is not present |
Exec format error | A module for another architecture | Use the right cross build |
After any failure, read dmesg | tail, since the specific reason, such as the name of an unknown symbol, is logged there, not printed by insmod.
Tracing: watching without stopping
When there is no oops, no warning and no obvious place to put a message, observe. The kernel's tracing facility, ftrace, lives in tracefs, mounted at /sys/kernel/tracing. It can record function calls, kernel events and the time they took, with little overhead, and it needs no rebuild. Four uses cover most needs.
See what a function calls and how long each call takes, with the function graph tracer, limited to the function you care about:
cd /sys/kernel/tracing
echo 0 | sudo tee tracing_on
echo ticker_read | sudo tee set_graph_function
echo function_graph | sudo tee current_tracer
echo 1 | sudo tee tracing_on
cat /dev/ticker > /dev/null
echo 0 | sudo tee tracing_on
sudo cat trace | head -n 12 2) | ticker_read [ticker]() {
2) 0.412 us | mutex_lock();
2) 0.690 us | copy_to_user();
2) 0.203 us | mutex_unlock();
2) 2.870 us | }The numbers are examples, and durations on your machine will differ. A call that is missing from a path you expected, or one that takes far longer than its neighbors, is a lead. Reset with echo nop | sudo tee current_tracer.
See kernel events such as scheduling, interrupts and block I/O, with trace events. List the available ones in available_events, and enable a group:
echo 1 | sudo tee /sys/kernel/tracing/events/irq/irq_handler_entry/enable
sudo cat /sys/kernel/tracing/trace_pipe | head -n 2 <idle>-0 [001] d.h1. 6130.118342: irq_handler_entry: irq=45 name=ticker
<idle>-0 [001] d.h1. 6130.119402: irq_handler_entry: irq=45 name=tickerProbe any function without recompiling, with a kprobe event. This adds a probe at a function entry, with arguments if you name them:
echo 'p:myprobe ticker_read len=%dx' | sudo tee /sys/kernel/tracing/kprobe_events
echo 1 | sudo tee /sys/kernel/tracing/events/kprobes/myprobe/enable
sudo cat /sys/kernel/tracing/trace | tail -n 2 cat-4411 [002] ...1. 6130.402011: myprobe: (ticker_read+0x0/0x90 [ticker]) len=0x20000The register %dx holds the third argument on x86-64, per the calling convention, which is the length of the read. Probes can break kernels that were not built with the facility, and some functions cannot be probed, such as those marked __kprobes or notrace.
Count and aggregate with bpftrace or perf, when you want a summary, not a log. A one-liner that counts calls to a driver function by process name:
sudo bpftrace -e 'kprobe:ticker_read { @calls[comm] = count(); }'@calls[cat]: 14
@calls[ticker-test]: 3Tracing answers "what is the kernel doing" for performance problems and for bugs with no report. Because it records without stopping, it is the right tool for a machine you cannot halt.
Hangs and lockups
A hang is a failure with no report, and it comes in four kinds. Tell them apart first.
| Kind | What you see | First move |
|---|---|---|
| A task in D state | The task is stuck, the machine runs | echo w > /proc/sysrq-trigger; read the stack |
| A soft lockup | watchdog: BUG: soft lockup | The RIP and <TASK> frames name the loop |
| A hard lockup | Watchdog detected hard LOCKUP, or no messages at all | NMI backtrace; check interrupts-off loops |
| An RCU stall | rcu: INFO: rcu_sched detected stalls | The reported CPU or task, and its stack |
The magic SysRq keys are the interface to a machine that is not responding to anything else. w prints blocked tasks with stacks, l prints a backtrace of every active CPU and t prints all tasks. Write the letter to /proc/sysrq-trigger if you still have a shell, or use the key combination at the console:
echo w | sudo tee /proc/sysrq-trigger
sudo dmesg | tail -n 10sysrq: Show Blocked State
task:cat state:D stack:0 pid:4411 tgid:4411 ppid:4390 flags:0x00004002
Call Trace:
<TASK>
__schedule+0x3c1/0x9a0
schedule+0x2f/0xa0
schedule_preempt_disabled+0x15/0x30
__mutex_lock+0x3c5/0x7a0
ticker_read+0x2a/0x90 [ticker]The stack says the task waits for a mutex inside ticker_read. Find who holds it: with CONFIG_DEBUG_MUTEXES and lockdep on, echo d shows all held locks, and the task that holds t->lock is the one that never released it. A stuck holder is usually blocked on something else, so follow the chain until you find the task that is not waiting for a lock. That task is the real problem.
For a CPU in a loop, the soft lockup post describes the fixes. The signature is a RIP that never changes across reports, and the cure is nearly always a missing cond_resched(), a long lock hold or an unbounded wait on hardware, none of which a debugger would find faster than reading the function.
Interactive debugging
Sometimes you want to stop the kernel and look. There are three ways, each fitting a different setup.
QEMU with gdb is the easiest and the safest. Boot your kernel in a virtual machine with -s -S, attach gdb to vmlinux, and you can set breakpoints, inspect structures and step through code, with nothing to break. The QEMU and gdb post gives the full setup, and the kernel's helper scripts in scripts/gdb add commands such as lx-ps, lx-dmesg and lx-symbols that understand kernel structures. For driver bugs that do not need real hardware, this is the first thing to reach for.
kgdb debugs a running kernel from another machine over a serial line. Build with CONFIG_KGDB=y and CONFIG_KGDB_SERIAL_CONSOLE=y, boot the target with kgdboc=ttyS0,115200, and enter the debugger by writing g to /proc/sysrq-trigger. On the host, attach:
gdb vmlinux(gdb) set serial baud 115200
(gdb) target remote /dev/ttyUSB0
Remote debugging using /dev/ttyUSB0
kgdb_breakpoint () at kernel/debug/debug_core.c:...Use kgdbwait on the command line to stop at boot until a debugger attaches, which is how you debug early start-up on real hardware. kdb, the built-in shell with the same transport, gives a smaller set of commands on the console without a second machine: bt, ps, lsmod, md to dump memory.
JTAG or SWD probes with OpenOCD attach gdb to the CPU itself, and work even when the kernel is dead, which no software debugger can match. They are the tool for bring-up on new boards, and for hangs before the console exists.
Be aware of what stopping the machine changes. Timers keep counting while a CPU is halted, so a guest or a board may report timeouts and lockups after you resume. Interrupts that fire during the stop may be delivered in a burst. And a bug that depends on timing may vanish under a debugger, which is a reason to trace first.
Capturing a dying machine
If the machine panics and reboots, or freezes with a blank screen, the report is lost unless you captured it. Set up capture before you need it.
Serial console.
console=ttyS0,115200n8and a logged terminal on the other end. Reliable and slow, and it works during a panic.Netconsole. Kernel messages as UDP packets to a log host, covered in the netconsole post. It needs a network driver that supports polling.
pstore and ramoops. The panic log is saved into reserved RAM that survives a warm reboot, and appears under
/sys/fs/pstore/on the next boot.kdump. A second kernel is held in reserved memory, and on a panic it boots and writes the first kernel's memory to a file.
kdump gives the most information, because you get a full memory image. Configure a crash kernel with crashkernel=256M on the command line, load it with kexec, and check it is armed:
cat /sys/kernel/kexec_crash_loaded1After a crash, the dump appears, typically under /var/crash. Analyze it with the crash utility against the matching vmlinux:
crash> bt
crash> log
crash> ps
crash> files 4411bt prints the backtrace of the task that panicked, log the kernel log from the dump (the part the screen missed), ps the tasks, and files the open files of a process. A dump lets you examine the state after the fact: the locks, the lists, the half-built structures. Practice the whole path, including forcing a crash with SysRq c on a test machine, before a real failure forces you to learn it.
Bisecting a regression
If the bug appeared between two releases, git bisect finds the commit that introduced it in about log2(N) builds, as the bisect post shows. The conditions are a reliable test, verified good and bad endpoints and a fixed configuration, and the reward is a bug report that names the exact change. Automate the test with git bisect run so thirteen builds do not need thirteen manual judgments.
A worked case, end to end
A driver crashes when a program reads the device after another closes it. Follow the method.
Reproduce in QEMU with the debug kernel: a script that opens the device twice, closes one and reads from the other, in a loop.
Read the first report. KASAN prints
slab-use-after-free in ticker_read, with the allocation inticker_openand the free inticker_release.Form the hypothesis. The two descriptors share one structure through a pointer, and
releasefrees it for both.Confirm. Print the structure's address in
ticker_openwithdev_dbg(): the same pointer appears for both opens, confirming the sharing.Fix. Give the structure a
kref, take a reference inopen, drop it inrelease, as in the kref post.Verify. Rerun the loop under KASAN with the fix. The report is gone, and the loop runs a thousand iterations quietly.
Prevent. Add the loop to the module's tests so the bug cannot return unseen.
Notice how little of this was clever. The checker found the bug, the report named the lifetime, and the fix was a standard pattern. Most kernel debugging looks like this once the debug kernel exists.
A reusable test rig
Everything above gets easier when a crash costs seconds. Build a rig once and keep it. The parts: a debug kernel build tree, a tiny initramfs that loads your module and runs a test, and a script that boots them in QEMU with the console logged to a file.
#!/bin/sh
set -eu
KDIR="${KDIR:-$HOME/linux}"
MOD="${1:?usage: run-test.sh path/to/module.ko}"
WORK="$(mktemp -d)"
mkdir -p "$WORK/root/bin" "$WORK/root/lib/modules"
cp "$HOME/rig/busybox" "$WORK/root/bin/busybox"
cp "$MOD" "$WORK/root/lib/modules/"
cp "$HOME/rig/init" "$WORK/root/init" # mounts /proc and /sys, runs insmod and the test
chmod +x "$WORK/root/init"
( cd "$WORK/root" && find . | cpio -o -H newc | gzip ) > "$WORK/initramfs.cpio.gz"
timeout 180 qemu-system-x86_64 \
-nographic -m 1G -smp 2 \
-kernel "$KDIR/arch/x86/boot/bzImage" \
-initrd "$WORK/initramfs.cpio.gz" \
-append "console=ttyS0 panic=-1 oops=panic nokaslr" \
| tee "$WORK/console.log"
grep -q "TEST-PASS" "$WORK/console.log"The init script in the initramfs ends by printing TEST-PASS if the test succeeds, and oops=panic with panic=-1 makes QEMU exit on a crash instead of hanging. Because the script's exit status reflects the result, you can use it in a loop, in CI and with git bisect run. Adding -s -S to the QEMU line, and attaching gdb as in the QEMU post, turns the same rig into an interactive session.
Keep the console log of every run. A failure that appears once in a hundred runs is only useful if you saved the one that failed, and a loop that stops at the first failure with its log intact is the cheapest way to catch it.
Race conditions and ordering bugs
Concurrency bugs are the hardest class, because they depend on timing and the debugger's presence changes it. A disciplined approach beats a lucky one.
Make the race likely. Write a stress test that hammers the suspect interface from many threads at once: open and close in a loop, read while writing, remove the device while a reader runs. Pin the threads to different CPUs with taskset. Add CONFIG_DEBUG_PREEMPT and boot with more CPUs than you have cores if you want more interleavings. The race you cannot trigger in an hour of stress may still exist, but each hour raises your confidence.
Let the checkers watch. KCSAN reports two unsynchronized accesses even when no failure follows, as its post shows. Lockdep reports an order inversion the first time both orders are seen, not when they collide. KASAN catches the use after free that a race produces. Run all three in separate builds.
Name the invariant. Write down what must always be true, such as "the list is never traversed without the lock" or "a reference is held while the pointer is used". Then add lockdep_assert_held() and WARN_ON_ONCE() checks that state the rule in code. A violated assertion fires at the point of the mistake, not at the later crash:
static void ticker_remove_locked(struct ticker *t, struct ticker_req *r)
{
lockdep_assert_held(&t->lock); /* callers must hold the lock */
WARN_ON_ONCE(!list_empty(&r->node) && r->state != TICKER_QUEUED);
list_del_init(&r->node);
}Check memory ordering with the model. If the code relies on barriers, test the pattern as a litmus test, in the style of the memory model post, and read the documented guarantees of the primitives you use. A bug that shows up only on arm64 and not on x86 is almost always an ordering assumption.
Do not fix it by sleeping. An msleep() that makes the failure disappear has not fixed the race, it has widened a window past the point where your test notices. A fix is a lock, a reference count, an ordering guarantee or a design change, and you should be able to explain which invariant it restores.
Interrupt problems
Interrupt bugs look like a dead device, a machine that is slow for no reason, or a log full of repeats. A short toolkit covers them.
/proc/interrupts shows the count for every line on every CPU. A count that never moves means the interrupt never arrives, so check the hardware enable, the pin mux and the request_irq() return value. A count that races upward means a storm:
watch -n1 'grep ticker /proc/interrupts' 45: 1203442 0 IR-IO-APIC 45-fasteoi tickerA fast-growing count with the CPU pegged points at a handler that does not clear the cause, as in the soft lockup post. The kernel itself guards against the worst case. If a handler returns IRQ_NONE too often, it disables the line and prints:
irq 45: nobody cared (try booting with the "irqpoll" option)
Disabling IRQ #45The fix is in the handler: read the device's status register, return IRQ_NONE if it did not raise the interrupt, and acknowledge it otherwise. For shared lines, CONFIG_DEBUG_SHIRQ calls every handler once at free_irq() time to check that it copes with a spurious call, which finds handlers that touch hardware that is already powered down.
Trace the flow with the irq trace events: irq_handler_entry and irq_handler_exit show each interrupt and how long its handler ran, and softirq_entry shows the deferred work. A handler that takes milliseconds should move its work to a threaded handler or a work item.
Reading the source efficiently
Debugging the kernel means reading code you did not write, and some tools make that fast.
**
git grep -n symbol** searches a tree faster than any editor. Add-- drivers/miscto limit it.**
git log -S 'text' -- path** finds the commit that added or removed a string, which answers "when did this check appear".**
git blame -L 40,70 file** shows who last changed each line and the commit, whose message often explains why.Elixir, the cross-referencer at elixir.bootlin.com, shows every definition and every use of an identifier across kernel versions, which is the quickest way to see how a function changed between releases.
**
ctagsorcscope**, orclangdwithcompile_commands.jsonfromscripts/clang-tools/gen_compile_commands.py, give jump-to-definition in an editor.**
Documentation/** has an explanation for most subsystems, and thedocs.kernel.orgsite renders it. When you meet an unfamiliar API, read its document first and its header second.**
scripts/get_maintainer.pl** names the people and lists responsible for a file, which tells you where to ask.
A habit worth building is to read the commit that last touched the failing function before you form a theory. Many bugs are a recent change meeting an old assumption.
Reporting a kernel bug well
If the bug is in code you do not maintain, a good report gets it fixed and a poor one is ignored. The elements, in the order a maintainer looks for them:
A subject that names the symptom and the component, such as "ticker: NULL deref in ticker_read after open on 6.12".
The kernel version and how to get it, and whether the bug is in mainline or only in a distribution's kernel. Try the latest mainline first.
The full first report, decoded with file and line, not a screenshot of part of it.
The configuration, attached as a file, plus the command line and hardware.
Steps to reproduce, ideally a short program or script, and how often it fails.
What you already tried, including whether a bisect found the commit.
Send it to the addresses scripts/get_maintainer.pl prints for the file, with the mailing list in copy, in plain text. A bisected commit and a reproducer move a report from "someone should look" to "this is visible". The mainline kernel's own guide to reporting issues lists the details and is worth reading once before you send your first.
Debugging on a machine you cannot stop
Production changes the rules. You cannot rebuild the kernel, halt it for gdb or run KASAN, and the failure may happen once a week. The tools that remain are the ones built for it, and the preparation happens before the incident.
Keep a persistent log. Make the journal persistent so the end of the previous boot survives, as the dmesg post explains, and send kernel messages to a central log host with netconsole or the journal's remote forwarding. A crash that reboots the machine leaves nothing behind otherwise.
Decide the crash policy in advance. A production host that oopses is untrustworthy. Most fleets set kernel.panic_on_oops=1 with kernel.panic=10, so a bad state ends in a reboot and, with kdump armed, a memory image. The alternative, leaving the machine up after an oops, keeps the service running with leaked locks and corrupted state, and turns one failure into several.
Use low-overhead sampling checkers. KFENCE finds heap errors on a running system at a cost small enough to leave on, and catches use after free and out of bounds over days of uptime. The lockup detectors and the hung task detector cost almost nothing and turn a mysterious stall into a named stack.
Observe with tracing and BPF. Trace events and kprobes attach to a running kernel without a rebuild, and bpftrace or perf aggregate in the kernel so the output stays small. A few examples of questions they answer with no restart: which processes call this function, how long does it take, which path leads to this error return, who holds this lock the longest. Keep traces narrow, because an unfiltered trace on a busy machine costs real time and disk.
sudo perf record -e 'sched:sched_switch' -a -g -- sleep 10
sudo perf report --stdio | head -n 10Samples: 18K of event 'sched:sched_switch', Event count (approx.): 18321
Children Self Command Shared Object Symbol
........ ........ ........ ............. ......
41.02% 41.02% swapper [kernel] [k] __scheduleThe numbers show the shape of the output, not a real measurement.
Capture on the first occurrence. Arm kdump and pstore and keep the matching vmlinux with debug info for every kernel you deploy, indexed by build id. When the machine panics, you have the dump and the means to read it. If you wait until you need them to arrange it, the first occurrence is wasted.
Reproduce elsewhere. Once the logs and a dump give you a hypothesis, build a smaller reproducer on a test machine, where the heavier tools can run. Most production bugs get fixed there, and the production tools exist to give you the hypothesis.
Choosing a tool by cost
Pick the lightest tool that can answer the question. Each step up costs more setup and disturbs the system more.
| Tool | Setup cost | Disturbs the system | Answers |
|---|---|---|---|
| Reading the existing log | None | No | What failed first |
dev_dbg() with dynamic debug | Low | Slightly | Did we get here, with what values |
| Trace events and kprobes | Low | Slightly | What ran, in what order, how long |
bpftrace, perf | Low to medium | Slightly | Aggregates across many calls |
| Runtime checkers (KASAN, lockdep) | A rebuild | Heavily | Which operation was invalid |
| QEMU with gdb | A VM and a build | Not at all | The exact state at a point |
| kgdb, JTAG | Hardware and cables | Stops the machine | State on the real device |
kdump and crash | Reserved memory and setup | Only at the crash | The whole state after the fact |
git bisect | A reliable test | Not applicable | Which commit introduced it |
A frequent mistake is to start at the heavy end, setting up a debugger for a bug that the log already explains. Another is to stay at the light end, adding printk() calls for a corruption bug that KASAN would pinpoint in one run. Move down the table when the current tool stops giving new information, and say what you expect the next tool to show before you set it up.
Habits that save hours
Change one thing at a time. Two simultaneous changes make the result unreadable.
Write down the exact kernel version, config and command line with every report you keep.
Do not trust a fix you cannot explain. A bug that stops happening after an unrelated change is hiding, not gone.
Distrust timing-based conclusions made with
printk()in the path.Keep a minimal reproducer. Reduce the test until every line matters. It becomes the regression test.
Look at the first failure. Everything after it may be fallout.
Check the hardware last, but check it. A flaky power supply, a bad cable, a marginal memory module and an overheating chip all look like kernel bugs.
Who this guide does not fit
If your problem is in user space, gdb, strace, ltrace and valgrind are the tools, and the kernel is not at fault. If you are debugging a production machine that you cannot stop or rebuild, use the tools that need no rebuild: tracing, BPF, SysRq and a persistent log, and plan kdump before the incident. If you are bringing up a new CPU or board with no console yet, you need a hardware debugger, and this guide's software methods begin after that works. If you maintain a distribution kernel, much of the debugging is in the packaging: matching debuginfo, symbols and the exact build, for which the decoders need archived artifacts.


