On 11/22/25 21:54, Linus Torvalds wrote: > Btw, I realize that we don't have a good way to do the alignment with > the current kmalloc() interface (we do for some of the vmalloc > interfaces). > > So for now, it should just have some static build-time warning if the > type of the object we allocate has a bigger alignment than the > guaranteed slab allocation alignment (ARCH_KMALLOC_MINALIGN or > whatever).
Note that these days we guarantee more than that, and it depends on size. >From Documentation/core-api/memory-allocation.rst: The address of a chunk allocated with `kmalloc` is aligned to at least ARCH_KMALLOC_MINALIGN bytes. For sizes which are a power of two, the alignment is also guaranteed to be at least the respective size. For other sizes, the alignment is guaranteed to be at least the largest power-of-two divisor of the size. > And I really think the first version should do the minimal thing that > actually matters, and strive to deal with the simple cases. The main > things that matter are > > - the return type should be a proper pointer type (so that you get > warnings for mis-uses, but also so that you can use automatic typing) > > - making the 'sizeof()' match the type > > so honestly, I think 99% of the gain would come from something fairly > simple like > > #define kmalloc_verify(type) \ > BUILD_BUG_ON_ZERO(__alignof__(type) > ARCH_KMALLOC_MINALIGN) > > #define kmalloc_size(type) \ > (sizeof(type) + kmalloc_verify(type)) > > #define allocator(name, type, size, ...) \ > (typeof(type) *)name(size, __VA_ARGS__) So AFAIU this would be too pessimistic. I'm not sure if the alignment rules can be sensibly encoded in build time checks. Perhaps yes, in a similar way that we have compile-time size bucket selection via __kmalloc_index(). > #define kmalloc_obj(type, gfp) \ > allocator(kmalloc, type, kmalloc_size(type), gfp) > #define kzalloc_obj(type, gfp) \ > allocator(kzalloc, type, kmalloc_size(type), gfp) > #define kzalloc_struct(type, member, count, gfp) \ > allocator(kzalloc, type, struct_size_t(typeof(type), member, > count), gfp) > > The above macros are entirely untested. But they are simple enough > that even if they are buggy and I miscounted the parentheses or used > the wrong name somewhere, I think the idea is clear. No? > > (And I made that "allocator()" macro use __VA_ARGS__ because > kzalloc_node() and friends would want that, but I think it's starting > to hit diminishing returns at that point) > > Hmm? > > Linus
