What You Will Learn
This lecture continues our free Linux kernel programming course and free Linux device drivers course. Here you will learn how to actually use the Linux kernel slab allocator through its kmalloc() and kzalloc() APIs, understand GFP allocation flags, see how kmalloc() picks a slab cache size internally, write and free memory safely inside a kernel module, and avoid the most common allocation mistakes new driver authors make.
Prerequisites
- Completion of Part 1 of this series: Understanding the Linux Kernel Slab Allocator
- Basic knowledge of writing and loading a Linux kernel module
- Familiarity with C pointers and structures
Topics Covered In This Lecture
kzalloc example
GFP flags
kfree
Slab allocator usage
Kernel module memory
The Core Slab Allocator APIs for Driver Authors
As a kernel module or device driver author, you rarely talk to the slab allocator directly. Instead, you use a small set of well-known wrapper functions declared in a single header:
#include <linux/slab.h>
The two functions you will reach for most often are:
void *kmalloc(size_t size, gfp_t flags);
void *kzalloc(size_t size, gfp_t flags);
kmalloc() returns a pointer to a block of at least size bytes, backed by the slab allocator, with uninitialized contents. kzalloc() does exactly the same thing but also zeroes out the memory before returning it — this is simply a convenience wrapper that saves you from calling memset() yourself, and it is the safer default for most driver code.
How kmalloc() Chooses a Slab Cache Internally
You do not create a slab cache yourself for a simple allocation. Instead, the kernel maintains a set of general-purpose caches sized in powers of two, and kmalloc() automatically rounds your requested size up to the nearest matching cache.
A request for 100 bytes does not get an exact 100-byte block — it is served from the nearest cache that is large enough, here kmalloc-128, so a little padding is normal and expected.
Understanding GFP Allocation Flags
Every slab allocation call takes a gfp_t flags argument that tells the kernel how and where it is allowed to look for free memory, and what it should do if memory is currently tight. Choosing the right flag matters for correctness, not just style.
| Flag | Meaning | When to Use |
|---|---|---|
GFP_KERNEL |
Normal allocation, may sleep | Most driver code running in process context, e.g. during open() or ioctl() |
GFP_ATOMIC |
Never sleeps | Interrupt handlers, spinlock-protected sections, or any context that cannot block |
GFP_NOWAIT |
Similar to atomic but slightly different reclaim behavior | Non-blocking paths where failure is acceptable and handled gracefully |
GFP_DMA |
Memory usable by older DMA-limited hardware | Legacy device drivers with strict physical address requirements |
Rule of thumb: if you are not sure whether your code can sleep, check the context. Process context (a normal function called from user space, like a file operation) can usually use GFP_KERNEL. Anything running with interrupts disabled or inside a spinlock must use GFP_ATOMIC.
Practical Example: Allocating Memory in a Kernel Module
Here is a minimal, complete example showing safe allocation and freeing of a small structure inside a kernel module’s init and exit functions.
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/slab.h>
struct ep_device_data {
int status;
char label[32];
};
static struct ep_device_data *ep_data;
static int __init ep_slab_demo_init(void)
{
ep_data = kzalloc(sizeof(*ep_data), GFP_KERNEL);
if (!ep_data) {
pr_err("ep_slab_demo: allocation failed\n");
return -ENOMEM;
}
ep_data->status = 1;
pr_info("ep_slab_demo: allocated %zu bytes via slab allocator\n",
sizeof(*ep_data));
return 0;
}
static void __exit ep_slab_demo_exit(void)
{
kfree(ep_data);
pr_info("ep_slab_demo: memory freed\n");
}
module_init(ep_slab_demo_init);
module_exit(ep_slab_demo_exit);
MODULE_LICENSE("GPL");
Notice three things about this example: the allocation is checked for failure before use, kzalloc() is used so the structure starts zeroed out, and kfree() is called exactly once during module exit to release the memory back to the slab allocator.
Freeing Memory Correctly with kfree()
void kfree(const void *objp);
Every successful call to kmalloc() or kzalloc() must be matched with exactly one call to kfree(). Calling kfree() on the same pointer twice (a “double free”) corrupts the slab allocator’s internal freelist and can crash the system or, worse, be exploited. Calling kfree(NULL) is always safe and does nothing, which is convenient in cleanup paths.
When kmalloc() Is Not Enough: kvmalloc()
kmalloc() is backed by physically contiguous memory from the slab allocator, which is fast but limited in how large a single allocation can practically be. For larger buffers where physical contiguity is not required, the kernel provides kvmalloc(), which transparently falls back to virtually contiguous memory when a large physically contiguous block is not available. As a general guideline, prefer kmalloc()/kzalloc() for small, fixed-size structures, and consider kvmalloc() when allocating larger buffers whose exact size may vary at runtime.
Common Mistakes When Using kmalloc/kzalloc
| Mistake | Consequence |
|---|---|
| Not checking the return value for NULL | Dereferencing a NULL pointer crashes the kernel |
| Using GFP_KERNEL inside an interrupt handler | The allocator may try to sleep in a context where sleeping is illegal, causing a kernel warning or crash |
| Forgetting to call kfree() | Memory leak that grows every time the code path runs |
| Calling kfree() twice on the same pointer | Slab freelist corruption, a serious and potentially exploitable bug |
| Using kmalloc() when zeroed memory is actually needed | Uninitialized fields can leak stale kernel memory contents or cause undefined behavior |
Best Practices for Slab Allocator Usage
- Prefer
kzalloc()overkmalloc()unless you have a specific performance reason not to zero the memory. - Always check the returned pointer before use, and return
-ENOMEMon failure. - Match every allocation with exactly one free, and set the pointer to NULL after freeing if it might be checked again.
- Choose GFP flags based on context, not habit — get this wrong and the bug may only appear rarely, under real memory pressure.
- Use
sizeof(*pointer)instead of hardcoding a struct size, so the allocation size always tracks the structure definition.
Performance and Security Considerations
Performance: Repeated small kmalloc()/kfree() calls in a hot path are usually fine thanks to the SLUB allocator’s per-CPU fast path, but allocating inside tight loops should still be avoided where possible — allocate once outside the loop when the size is known in advance.
Security: Double-free and use-after-free bugs involving kmalloc()-backed memory are among the most common classes of kernel security vulnerabilities. Careful ownership tracking of every allocated pointer is one of the most important habits a driver author can build.
Key Takeaways
- kmalloc() and kzalloc() are the primary driver-facing APIs for the Linux kernel slab allocator.
- kzalloc() is generally the safer default since it zeroes memory automatically.
- GFP flags must match the calling context — GFP_KERNEL when sleeping is allowed, GFP_ATOMIC when it is not.
- Every allocation needs exactly one matching kfree() call.
- kvmalloc() is the right tool when you need larger buffers without a physical contiguity requirement.
Frequently Asked Questions
What is the difference between kmalloc and kzalloc?
kmalloc() returns uninitialized memory, while kzalloc() returns memory that has already been zeroed, saving you a separate memset() call.
Can I use kmalloc inside an interrupt handler?
Yes, but only with a non-sleeping flag such as GFP_ATOMIC. Using GFP_KERNEL inside an interrupt handler is a common bug because that flag can put the calling code to sleep.
What happens if kmalloc fails?
kmalloc() and kzalloc() return NULL if they cannot satisfy the request. Well-written driver code always checks for this and returns an error such as -ENOMEM instead of dereferencing a NULL pointer.
Is there a maximum size for kmalloc?
Yes, kmalloc() is intended for relatively small, physically contiguous allocations. For larger buffers, kvmalloc() or dedicated page allocator APIs are more appropriate.
Do I need to create my own slab cache for a simple driver?
No. For most drivers, the general-purpose kmalloc() caches are sufficient. Creating a dedicated slab cache is only needed when you allocate the same fixed-size structure very frequently and want finer control over its caching behavior.
Why is my kfree causing a kernel crash?
This is almost always caused by either freeing a pointer twice, freeing memory that was never allocated with kmalloc-family functions, or writing past the end of the allocated block before freeing it.
Conclusion
You now know how to put the Linux kernel slab allocator to practical use through kmalloc() and kzalloc(), how to pick the correct GFP flag for your context, and how to avoid the allocation bugs that trip up most new kernel and device driver developers. This wraps up the memory allocator section of our free Linux kernel programming course. Practice by modifying the module example above, load it, check dmesg for the print statements, and confirm with slabtop that your structure’s memory is being allocated and released as expected.
More lectures on memory management, device drivers, and Bluetooth/BLE are available on EmbeddedPathashala — completely free.
