Kernel Internals & OS Construction

the slab allocator

/ slab /

The kernel creates and destroys vast numbers of small, identical objects over and over — a new file descriptor here, a network buffer header there, a task structure for each new process. Asking the page allocator for memory every time would be wasteful: a whole 4 KB page for a 200-byte object wastes most of the page, and constantly initializing fresh objects is slow. The slab allocator solves this by keeping pre-formed pools of same-type objects ready to reuse. Think of a busy diner that does not wash a plate, dry it, and put it in the cupboard between every customer; it keeps a stack of clean plates of each kind right at the counter, hands one out instantly, and drops the used one back on the stack.

Concretely, the slab allocator (and its successor in Linux, slub) works on top of the buddy system. It asks the buddy allocator for whole pages once, then carves each page into many slots all sized for one particular object type — a slab is such a page (or run of pages) full of object-sized slots, and a cache is the collection of slabs dedicated to one type. When the kernel needs, say, a new inode, the allocator pops a free slot from the inode cache in O(1) time, often already partly initialized; when the inode is freed, the slot goes back on the cache's free list rather than back to the buddy system. This packs many small objects tightly into pages (little waste), avoids repeated page-allocation overhead, and keeps objects of the same type together, which is friendly to the CPU cache.

It matters because it answers the question of why the kernel cannot just use the user-space malloc: malloc relies on system calls and a user heap that do not exist inside the kernel, can sleep or fault in ways forbidden in interrupt context, and are not tuned for the kernel's torrent of tiny fixed-size objects. A common confusion is thinking slab replaces the buddy system; it sits above it — the buddy system hands out pages, and the slab allocator retails those pages as small objects.

Linux keeps named caches you can inspect with the slabtop tool, such as one for dentry (directory-entry) objects and one for inode_cache. When you open many files, the kernel pops dentry and inode objects from those caches in constant time; closing files returns the slots to the cache, ready for the next open — no trip back to the page allocator for each one.

Pre-carved pools of same-type objects make allocation a fast pop, not a fresh page request.

Slab does not magically eliminate waste: each cache reserves whole pages for its object type, so memory held by a cache is not freely available to others until the slabs are reclaimed. And because objects of one type cluster together, a use-after-free bug in the kernel can be exploited by carefully grooming a slab cache.

Also called
slabslub allocatorobject cache物件快取