kmalloc & kfree
Linux kernel modules often require dynamic memory allocation for managing data structures, buffers, or temporary storage. The kmalloc() and kfree() functions are fundamental tools for this task, providing a way to allocate and free memory in the kernel's virtual address space. These functions are part of the slab allocator, which optimizes memory usage for small, frequently allocated objects. However, their usage is constrained by size limits and context-specific requirements.
Function Signatures and Flags¶
The kmalloc() function allocates a contiguous block of memory, while kfree() releases it. Their signatures are:
size: The requested size in bytes. Must be a power of two for optimal slab allocation (though this is often handled internally).flags: A bitmask specifying memory allocation behavior. Common flags include:GFP_KERNEL: For normal process context (default).GFP_ATOMIC: For interrupt or softirq context (no blocking).GFP_NOIO: Disables I/O operations during allocation.GFP_NOFS: Disables filesystem operations during allocation.
Example Usage¶
Here’s a simple kernel module demonstrating kmalloc() and kfree():
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/kernel.h>
static void *my_buffer;
static int __init kmalloc_example_init(void) {
size_t size = 1024; // 1 KB
my_buffer = kmalloc(size, GFP_KERNEL);
if (!my_buffer) {
pr_err("Failed to allocate memory\n");
return -ENOMEM;
}
pr_info("Allocated %zu bytes at %p\n", size, my_buffer);
// Use my_buffer here...
kfree(my_buffer);
return 0;
}
static void __exit kmalloc_example_exit(void) {
pr_info("Module exiting\n");
}
module_init(kmalloc_example_init);
module_exit(kmalloc_example_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Your Name");
MODULE_DESCRIPTION("KMALLOC Example");
Key points:
- Always check if kmalloc() returns NULL to handle allocation failures.
- kfree() must be called exactly once per allocated block to avoid memory leaks.
Size Constraints and Limits¶
- Maximum size:
kmalloc()is limited to a maximum size, typically 131072 bytes (128 KB), though this depends on architecture and kernel configuration. Larger allocations should usevmalloc(). - Alignment: The allocated block is aligned to the architecture’s natural alignment (e.g., 4 bytes on 32-bit systems).
- Power-of-two sizing: While not strictly required, passing sizes that are powers of two improves slab cache efficiency.
Common Pitfalls¶
- Forgetting to free memory: Leads to memory leaks and eventual system instability.
- Using incorrect
GFPflags:GFP_ATOMICin process context can cause deadlocks;GFP_KERNELis generally preferred. - Exceeding size limits: Attempting to allocate more than the maximum size results in
NULLreturn fromkmalloc().
Key takeaways¶
- Use
kmalloc()for small, contiguous memory allocations in kernel modules. - Always pair
kmalloc()withkfree()to avoid leaks. - Adhere to size limits (typically 128 KB) and use
vmalloc()for larger allocations. - Choose appropriate
GFPflags based on context (e.g.,GFP_KERNELfor process context).