Kernel Memory
Kernel Memory
What is kmalloc()?
• Allocates physically contiguous memory in the kernel address
space.
• Similar to malloc() in user-space but for kernel use.
Key Characteristics:
• Allocates memory from the slab allocator.
• Suitable for small, frequent allocations.
• Works well for DMA (Direct Memory Access) operations.
Use Cases for kmalloc()
Typical Scenarios:
1.Device Drivers:
• Allocating small buffers for data transfers.
• Allocating memory for hardware registers.
2.Interrupt Handlers:
• Needs fast allocation for handling real-time operations.
3.Short-lived Structures:
• Temporary allocations that are frequently created and destroyed.
Device Driver Buffer Allocation
Example:
char *buffer;
buffer = kmalloc(1024, GFP_KERNEL);
if (!buffer) {
printk(KERN_ERR "Memory allocation failed\n");
}
Why kmalloc?
• Physically contiguous memory needed for DMA.
• Low latency memory access.
Function Signatures and Details
kmalloc()
void *kmalloc(size_t size, gfp_t flags);
Arguments:
• size: Size of the allocation.
• flags: Allocation behaviour (e.g., GFP_KERNEL, GFP_ATOMIC).
Overview of vmalloc()
What is vmalloc()?
• Allocates virtually contiguous memory but physically scattered.
• Used when large memory allocations are required.
Key Characteristics:
• Memory is allocated via page tables, not slab caches.
• Suitable for large allocations (e.g., >4KB).
• Higher overhead due to page table mapping.
Use Cases for vmalloc()
Typical Scenarios:
1.Large Kernel Buffers:
• Allocating buffers for logs, packet processing, and cache systems.
2.Module Initialization:
• Modules requiring significant memory on load.
3.Sparse Data Structures:
• When physical contiguity is not critical but virtual continuity is needed.
Large Buffer Allocation for Logging
Example:
char *buffer;
buffer = vmalloc(10 * 1024 * 1024); // 10MB buffer
if (!buffer) {
printk(KERN_ERR "Memory allocation failed\n");
}
Why vmalloc?
•Large buffer size beyond slab allocator limits.
•No strict need for physical contiguity.
Function Signatures and Details
vmalloc()
void *vmalloc(unsigned long size);
Arguments:
• size: Size of the allocation.
Advantages and Disadvantages