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

Hyeonggon Yoo
2021-05-13T13:09:02Z

On Thu, May 13, 2021 at 02:29:13PM +0200, Marco Elver wrote:
> 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.

to explain in more detail,

in include/linux/slab.h:

static __always_inline void *kmalloc(size_t size, gfp_t flags)
{
if (__builtin_constant_p(size)) {
#ifndef CONFIG_SLOB
unsigned int index;
#endif
if (size > KMALLOC_MAX_CACHE_SIZE)
return kmalloc_large(size, flags);
#ifndef CONFIG_SLOB
index = kmalloc_index(size);

it checks if size is bigger than KMALLOC_MAX_CACHE_SIZE.
so kmalloc_index works safely because the size was already checked.

and definition of KMALLOC_MAX_CACHE_SIZE is

in include/linux/slab.h:
#ifdef CONFIG_SLAB
#define KMALLOC_SHIFT_HIGH ((MAX_ORDER + PAGE_SHIFT - 1) <= 25 ? \
(MAX_ORDER + PAGE_SHIFT - 1) : 25)
#define KMALLOC_SHIFT_MAX KMALLOC_SHIFT_HIGH
#ifndef KMALLOC_SHIFT_LOW
#define KMALLOC_SHIFT_LOW 5
#endif
#endif

#ifdef CONFIG_SLUB
#define KMALLOC_SHIFT_HIGH (PAGE_SHIFT + 1)
#define KMALLOC_SHIFT_MAX (MAX_ORDER + PAGE_SHIFT - 1)
#ifndef KMALLOC_SHIFT_LOW
#define KMALLOC_SHIFT_LOW 3
#endif
#endif

#ifdef CONFIG_SLOB
#define KMALLOC_SHIFT_HIGH PAGE_SHIFT
#define KMALLOC_SHIFT_MAX (MAX_ORDER + PAGE_SHIFT - 1)
#ifndef KMALLOC_SHIFT_LOW
#define KMALLOC_SHIFT_LOW 3
#endif
#endif

so if kmalloc_index is called from another place other than kmalloc,
it's not safe to assume that the supported size is 32MB.

Thanks, Hyeonggon