SLUB Allocator APIs¶
Purpose¶
The SLUB allocator manages caches of fixed-size kernel objects.
Instead of allocating pages directly for every object, Linux groups objects of the same size into a kmem_cache. Objects are allocated from these caches, while the Buddy Allocator provides page-backed memory when new slabs are required.
Most kernel drivers use kmalloc() or kzalloc(). Dedicated kmem_cache instances are typically created only when allocating a large number of objects with the same size and lifetime.
Common APIs¶
kmem_cache_create()¶
struct kmem_cache *kmem_cache_create(
const char *name,
unsigned int size,
unsigned int align,
slab_flags_t flags,
void (*ctor)(void *));
Creates a new SLUB cache for objects of a fixed size.
Typical usage:
- Frequently allocated objects
- Kernel subsystems
- Internal kernel object caches
Returns a pointer to the created kmem_cache on success, or NULL on failure.
kmem_cache_alloc()¶
Allocates one object from the specified cache.
If no free object exists, the SLUB allocator allocates a new slab from the Buddy Allocator and retries the allocation.
Typical usage:
- Allocate one object from a dedicated cache
- Internal object allocation within kernel subsystems
Returns a pointer to the allocated object on success, or NULL on failure.
kmem_cache_free()¶
Returns an object to its owning cache.
The freed object becomes available for future allocations.
kmem_cache_destroy()¶
Destroys a previously created cache.
All slabs owned by the cache are released, and their backing pages are returned to the Buddy Allocator.
Typical Workflow¶
A dedicated SLUB cache is typically used as follows:
kmem_cache_create()
│
▼
kmem_cache_alloc()
│
▼
Use object
│
▼
kmem_cache_free()
│
▼
kmem_cache_destroy()
Relationship with kmalloc()¶
Most kernel code does not create a dedicated kmem_cache.
Instead, Linux provides a set of predefined kmalloc caches.
The allocation path is:
For general-purpose kernel memory allocation:
- Use
kmalloc()for small allocations. - Use
kzalloc()when zero-initialized memory is required. - Use
kcalloc()when allocating arrays. - Create a dedicated
kmem_cacheonly when allocating many objects of the same size.
When to Create a Dedicated Cache¶
Creating a dedicated kmem_cache is beneficial when:
- Objects have the same size.
- Objects are allocated and freed frequently.
- Object reuse improves allocation performance.
- Constructor callbacks or cache-specific behavior are required.
For ordinary driver development, kmalloc() is usually sufficient.
Common Pitfalls¶
Warning
Most device drivers should use kmalloc() or kzalloc() instead of creating a dedicated kmem_cache.
Warning
Every successful kmem_cache_create() should eventually be paired with kmem_cache_destroy().
Warning
Objects allocated from a kmem_cache must be released with kmem_cache_free(). They must not be released with kfree().