Writing an OS Kernel from Scratch – Part 15: Slab Allocator — Efficiently Managing Kernel Small Objects
“The Buddy system is great at allocating large memory blocks, but what about the kernel’s frequent 32-byte, 128-byte small object allocations? Today, we implement the Slab allocator, making kernel memory allocation lightning fast!”
In the previous post, we built a complete memory management system:
- Buddy system: manages physical pages (4KB granularity)
- User-mode malloc: requests memory via brk/mmap
But the kernel itself also needs to frequently allocate/release many small objects:
✅ Process control blocks (PCB)
✅ File descriptors (file)
✅ VFS directory entries (dentry)
✅ Network buffers (skb)
If every kmalloc requested 4KB from Buddy and cut a small piece from it, internal fragmentation would reach 99%!
Today, we implement the Slab allocator — an efficient memory pool designed for kernel small objects, enabling zero-fragmentation, zero-initialization-overhead PCB allocation!
Why Slab? Buddy’s Pain Points
| Scenario | Problem |
|---|---|
| Allocate 32 bytes | Buddy returns 4KB page, wastes 99.2% |
| Frequent alloc/free | Must zero memory each time (safety requirement) |
| Poor cache locality | Objects scattered across pages, low CPU cache hit rate |
Slab’s core idea: “Pre-allocate a batch of same-type objects, take when needed, return when done.”
- Slab: One or more contiguous physical pages, divided into fixed-size objects
- Cache: Manages the Slab pool for same-type objects (e.g., task_cache, file_cache)
- Object reuse: freed objects returned to free list, not to Buddy
Comments