On 08/10/2025 06:20, Kees Cook wrote:
On Tue, Oct 07, 2025 at 08:18:28PM +0200, Marco Elver wrote:
On Tue, 7 Oct 2025 at 19:47, Christoph Lameter (Ampere) <[email protected]> wrote:
On Tue, 7 Oct 2025, Kees Cook wrote:
iOS did go the path of creating basically one slab cache for each
"type" of kmalloc for security reasons.

See 
https://security.apple.com/blog/towards-the-next-generation-of-xnu-memory-safety/

We can get something similar to that with:
https://lore.kernel.org/all/[email protected]/
Pending compiler support which is going to become available in a few
months (probably).
That version used the existing RANDOM_KMALLOC_CACHES choice of 16 slab
caches, but there's no fundamental limitation to go higher.

Right -- having compiler support for dealing with types at compile time
means we can create the slab caches statically (instead of any particular
fixed number, even the 16 from RANDOM_KMALLOC_CACHES).

Maybe I'm missing the point here, but I think we can already do per-
callsite static caches without specific new compiler support:

struct kmalloc_cache {
    const char *type_name;
    unsigned long caller;
    unsigned int alignment;
    unsigned int size;
    gfp_t gfp_flags;
    // ...
};

extern void *_kmalloc_cache(struct kmalloc_cache *cache);

#define kmalloc_type(type, _gfp_flags) \
    ({ \
        __label__ __here; __here: \
        static struct kmalloc_cache \
            __attribute__((__section__(".kmalloc_caches"))) \
            _cache = { \
                .type_name = #type, \
                .caller = (unsigned long)&&__here, \
                .alignment = alignof(type), \
                .size = sizeof(type), \
                .gfp_flags = (_gfp_flags), \
            }; \
        (type *) _kmalloc_cache(&_cache); \
    })

struct device {
    int name[32];
    void *priv;
};

int foo()
{
    struct device *dev = kmalloc_type(struct device, GFP_KERNEL);
    // ...
}

// initialize all static kmalloc caches during boot if needed
// (requires linker script support)

extern struct kmalloc_cache kmalloc_caches_start[];
extern struct kmalloc_cache kmalloc_caches_end[];

void init_cache(struct kmalloc_cache *)
{
    // ...
}

void init_caches()
{
    for (struct kmalloc_cache *cache = kmalloc_caches_start;
        cache != kmalloc_caches_end; ++cache)
    {
        init_cache(cache);
    }
}

Godbolt for playing with it: https://godbolt.org/z/E1c6q9avn

If you really want just one cache per type, you can funnel all the
callers through a single function (single allocation point)?


Vegard

Reply via email to