Re: [PATCH v3] mm, slub: change run-time assertion in kmalloc_index() to compile-time

Marco Elver
2021-05-13T12:29:39Z

On Thu, 13 May 2021 at 14:03, Hyeonggon Yoo <42.hyeyoo@gmail.com> wrote:
> On Thu, May 13, 2021 at 12:31:38PM +0200, Marco Elver wrote:
[...]
> what about checking size it on top of kmalloc_index? because by definition of
> KMALLOC_SHIFT_HIGH, it's not always 25. it can be less than 25. for some
> situations.
>
> below is what I suggested beofre. for just reference:

This doesn't solve the problem. We want the compiler to complain
whenever kmalloc_index() is used with non-constant in normal code. But
it should be possible to use it in allocator tests regardless of size.
Either that or export kmalloc_slab(), but I think that's worse. I'll
send my patch with an updated comment.

> --- include/linux/slab.h.orig 2021-05-12 17:56:54.504738768 +0900
> +++ include/linux/slab.h 2021-05-13 15:06:25.724565850 +0900
> @@ -346,9 +346,18 @@ static __always_inline enum kmalloc_cach
> * 1 = 65 .. 96 bytes
> * 2 = 129 .. 192 bytes
> * n = 2^(n-1)+1 .. 2^n
> + *
> + * Note: there's no need to optimize kmalloc_index because it's evaluated
> + * in compile-time.
> */
> static __always_inline unsigned int kmalloc_index(size_t size)
> {
> + if (__builtin_constant_p(size)) {
> + BUILD_BUG_ON_MSG(size > KMALLOC_MAX_CACHE_SIZE , "unexpected size in kmalloc_index()");
> + } else if (size > KMALLOC_MAX_CACHE_SIZE) {
> + BUG();
> + }
> +
> if (!size)
> return 0;
>
> @@ -382,8 +391,6 @@ static __always_inline unsigned int kmal
> if (size <= 8 * 1024 * 1024) return 23;
> if (size <= 16 * 1024 * 1024) return 24;
> if (size <= 32 * 1024 * 1024) return 25;
> - if (size <= 64 * 1024 * 1024) return 26;
> - BUG();
>
> /* Will never be reached. Needed because the compiler may complain */
> return -1;