0

I'm developing a module in kernel that uses kmem_cache. While developing and testing, it's possible that something goes wrong or I want to quit the module while there are still some allocations from the cache that weren't freed. Calling kmem_cache_destroy with a cache that still has elements throws a protection fault in dmesg: kmem_cache_destroy <my_cache>: Slab cache still has objects along with the usual huge dump.

Is it possible to somehow remove all elements from a kmem_cache to avoid this issue?

Something like this reproduces the issue:

#include <linux/slab.h>

static struct kmem_cache *cache;
cache = kmem_cache_create("my_cache", 8, 4, 0, null_constructor);
c = kmem_cache_alloc(cmd_cache, GFP_KERNEL);
c1 = kmem_cache_alloc(cmd_cache, GFP_KERNEL);
//TODO: free all elements of the cache, without referencing every single object allocated
kmem_cache_destroy(cache);
hfingler
  • 1,931
  • 4
  • 29
  • 36
  • void kmem_cache_free(kmem_cache_t *cache, const void *obj); https://www.oreilly.com/library/view/linux-device-drivers/0596005903/ch08.html – gapsf Aug 24 '22 at 17:13
  • I copied the wrong line into the code. Fixed now since I am using `kmem_cache_alloc`. – hfingler Aug 24 '22 at 17:36
  • Note: I'm not sure but you probably want to use `kmem_cache_alloc_bulk` to allocate your objects and then `kmem_cache_free_bulk` once you're done. Or simply create an array to hold the objects you alloc and then loop over it and free each one. Just like you'd do with any other data type. – vmemmap Aug 26 '22 at 19:04
  • I was already storing the objects in an xarray, so I ended up iterating over it, freeing every entry. – hfingler Aug 26 '22 at 21:58

1 Answers1

0

You should allocate each object with

void *kmem_cache_alloc(kmem_cache_t *cache, int flags);

then free all objects

void kmem_cache_free(kmem_cache_t *cache, const void *obj);

https://www.oreilly.com/library/view/linux-device-drivers/0596005903/ch08.html

gapsf
  • 634
  • 4
  • 8
  • I *should* use kmem_cache_free on every element added, sure. The question is, is it possible to free all elements of the cache without having a reference to them, like a clear() function. – hfingler Aug 24 '22 at 17:36
  • I guess there is no such function. https://www.kernel.org/doc/html/latest/core-api/memory-allocation.html – gapsf Aug 24 '22 at 18:22
  • 1
    Check kmem_cache_free_bulk https://elixir.bootlin.com/linux/latest/source/mm/slab.c#L3740 – gapsf Aug 24 '22 at 18:45