Search code examples
clinuxlinux-kernelheap-memorykmalloc

`aligned_alloc` in Linux Kernel Space when using kmalloc


I am writing a kernel module, porting some functionality from user space that uses the aligned_alloc function from the #include <stdlib.h> library. I did not find a similar function in the function accessible from kernel modules - is there any existing functionality or easy wrapper function I could write around kmalloc to replicate the behavior of aligned_alloc?


Solution

  • In recent kernels (>= v5.4) kmalloc() is guaranteed to return naturally aligned objects of sizes that are powers of two, meaning that kmalloc(sz) is already aligned to sz IFF sz is a power of two. So if you are targeting modern kernels kmalloc is already enough. Relevant patch here.

    If you need to support older kernels, or in general if you need a lot of allocations of the same kind, you can create your own kmem_cache with the appropriate object size and object alignment using kmem_cache_create(). You will then be able to allocate objects from it using kmem_cache_alloc(). Both are from linux/slab.h. Note however that this is only feasible if all the allocations you are dealing with are of the same size and need the same alignment.