Reading — step 1 of 6
Read
Slab Allocator
Jeff Bonwick introduced the slab allocator in 1994 for SunOS 5.4 (Solaris) (paper). It is now everywhere: Linux's kmem_cache, FreeBSD's UMA, illumos, OS X kernel zones, Carl Lerche's slab crate in Rust, even userspace caches like Memcached.
The key insight
Most kernel allocations are for the SAME TYPE of object — struct dentry, struct inode, struct task_struct. They have a known, fixed size. Why pay the cost of general-purpose kmalloc for each one?
A cache is a named pool of slabs for one type. A slab is a contiguous run of memory pre-divided into N fixed-size object slots.
cache: "inode_cache" (object size = 256 bytes)
+----------+----------+----------+----------+
| slab 0 | slab 1 | slab 2 | slab 3 |
| 32 slots | 32 slots | 32 slots | 32 slots |
| (full) | (partial)| (partial)| (empty) |
+----------+----------+----------+----------+
Allocation
- Find a slab with free slots (prefer partial > empty).
- Pop a slot from its free list. O(1).
- If everything is full, grow the cache by allocating a new slab.
Free
- Push the slot onto its slab's free list. O(1).
- If a slab becomes empty for a while, the kernel can reclaim its pages.
Why it dominates
- No bookkeeping per object — size is implied by the cache.
- Cache locality — same-type objects sit together, raising hit rates.
- Object construction caching — Bonwick's original paper highlights that the slab can keep objects in their "constructed" state, so allocation skips initialization.
- Per-CPU caches (SLUB/SLAB/SLOB variants) — eliminate locking on the common path.
Linux variants
- SLAB (Bonwick's design): classic.
- SLUB (default since 2.6.23): simpler; fewer per-CPU data structures; better scaling on big SMP.
- SLOB: tiny systems; one heap, no slabs — just a free list.
When to reach for it (userspace)
- Object pools for high-rate, single-type allocations (game entity pools, packet buffers).
- When you want zero allocator overhead per object.
- When your workload's allocation pattern is dominated by a few sizes.
For general-purpose userspace allocations, the size-class allocators (jemalloc, tcmalloc) effectively implement slab-style caches per size class — same idea, generalized.
This lesson
You'll build a cache/slab manager that grows on demand, supports multiple named caches, and reports per-cache stats (empty/partial/full slab counts).
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…