1

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?

  • 1
    https://lwn.net/Articles/802469/ – stark Jul 17 '22 at 13:26
  • If you expect to be doing a lot of those (and of the same size), you can probably create a cache with `kmem_cache_create`, allocate from it with `kmem_cache_alloc`. – Hasturkun Jul 17 '22 at 15:07

1 Answers1

1

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.

Marco Bonelli
  • 63,369
  • 21
  • 118
  • 128