Course contentsShow
← Linux
Lesson 1680 of 1,81914. Observability and Performance TroubleshootingFree lesson

Detecting Kernel Module Memory Leaks

Profile kmalloc/kfree calls within kernel modules to identify leaked memory blocks.

In this lesson, you will learn how to systematically track kmalloc and kfree patterns to pinpoint memory leaks within custom kernel modules.

The Challenge of Kernel Leaks

Unlike user-space applications, a kernel module that leaks memory doesn't just crash itself; it slowly degrades the entire system’s performance by depleting the SLAB or SLUB allocator caches. Because kernel memory is not reclaimed upon module unloading unless explicitly freed, even small, recurring leaks can eventually lead to an Out of Memory (OOM) condition or system instability.

Tracking Allocations with Tracepoints

To identify these leaks, we leverage the kernel's built-in tracing infrastructure. We want to correlate every successful kmalloc call with its corresponding kfree. If a specific call site allocates memory but never invokes kfree for that specific address, we have found a leak.

Using ftrace or bpftrace, we can map the return address of allocations. A common strategy is to attach a probe to kmem_cache_alloc and kfree:

// Simplified logic for a bpftrace one-liner
kprobe:kmalloc { @allocs[reg("ax")] = stack; }
kprobe:kfree { delete(@allocs[arg0]); }
END { printf("Leaked pointers: %p\n", @allocs); }

Analyzing the Discrepancy

When inspecting a module, you should look for "orphan" allocations—addresses that exist in the @allocs map after a specific workload has completed. If you see a consistent growth in the number of unique pointers associated with a specific stack trace inside your module, you have found the leak point.

It is critical to focus on the lifecycle of the allocation. Ensure that error-handling paths in your module also trigger a kfree if an allocation succeeds but a subsequent operation fails. Often, leaks occur not in the "happy path," but in those neglected goto out; error-cleanup sequences where the programmer forgot to roll back the memory allocation. By profiling the total count of allocations versus deallocations during a module's lifecycle, you can mathematically prove the existence of a leak before it manifests as a system-wide resource starvation event.

Key Takeaway: Identifying memory leaks requires correlating individual kmalloc return addresses with kfree events; any allocation that persists without a matching free after the module's target operation is a candidate for a leak.