Kernel memory: slab and buddy allocators
About this lesson
The kernel hands memory to every program, but it needs memory for itself too: page tables, process records, file records. It cannot call malloc, and it cannot afford to waste memory or time. Linux answers with two layers. The buddy allocator keeps physical pages in power-of-two blocks that split in half and merge back. The slab allocator takes pages from it and cuts them into equal slots for small objects. Follow one kmalloc(400) from the code down to the pages and back. The lesson on segmentation and free-space management introduces free lists and fragmentation; this one shows how a real kernel puts them to work.
The kernel needs memory too
The kernel needs memory for its own things: page tables, process records, file records. It has no malloc, which is a user library. Linux uses two layers: a buddy allocator hands out whole pages, and a slab allocator cuts pages into small objects.
who asks what it needs page tables whole pages process records small objects, thousands of them file records small objects (inodes, dentries) layer 1 buddy allocator pages, in blocks of 1, 2, 4, 8 ... layer 2 slab allocator small same-size objects, cut from pages xv6 (MIT 6.1810) has only layer 1: a free list of 4096-byte pages.
Read the lesson step by step
The kernel needs memory too
The kernel needs memory for its own things: page tables, process records, file records. It has no malloc, which is a user library. Linux uses two layers: a buddy allocator hands out whole pages, and a slab allocator cuts pages into small objects.
who asks what it needs page tables whole pages process records small objects, thousands of them file records small objects (inodes, dentries) layer 1 buddy allocator pages, in blocks of 1, 2, 4, 8 ... layer 2 slab allocator small same-size objects, cut from pages xv6 (MIT 6.1810) has only layer 1: a free list of 4096-byte pages.Pages in power-of-two blocks
Memory is cut into pages of 4096 bytes. The buddy allocator keeps free blocks of 1, 2, 4, 8 ... pages, one free list per size, called the order. Our toy zone has 8 pages: one free block of order 3, 32 KiB.
order pages size free blocks 0 1 4 KiB 0 1 2 8 KiB 0 2 4 16 KiB 0 3 8 32 KiB 1 Linux keeps orders 0 to 10 (4 KiB up to 4 MiB on x86-64). Watch them with /proc/buddyinfo, read with plain system calls: #define _POSIX_C_SOURCE 200809L #include <fcntl.h> #include <unistd.h> int main(void) { char buf[4096]; ssize_t n; int fd = open("/proc/buddyinfo", O_RDONLY); if (fd < 0) return 1; /* not Linux */ while ((n = read(fd, buf, sizeof buf)) > 0) if (write(1, buf, (size_t)n) != n) return 1; close(fd); return 0; } one line of output (orders 0 .. 10): Node 0, zone Normal 216 55 189 101 84 38 37 27 5 3 587A request for 400 bytes
Kernel code calls kmalloc(400). There is no 400-byte size, so the request goes to the next size up, the 512-byte cache kmalloc-512. That cache has no free slot yet, so it asks the buddy allocator for one page.
line 1 p = kmalloc(400, GFP_KERNEL); kmalloc sizes (bytes): 8 16 32 64 96 128 192 256 512 1024 2048 4096 8192 400 -> next size up -> 512 cache kmalloc-512 kmalloc-512: no slab with a free slot -> ask the buddy allocator for 1 page (order 0)Split until it fits
No order-0 block is free, so the allocator splits the 8-page block in half again and again: 8 into 4 + 4, 4 into 2 + 2, 2 into 1 + 1. Page 0 goes to the cache; spare halves join their free lists.
want order 0 lists [0 0 0 1] only an order-3 block split, keep 0-3 lists [0 0 1 0] split, keep 0-1 lists [0 1 1 0] split, keep 0-0 lists [1 1 1 0] page 0 given out lists [1 1 1 0] lists = free blocks of order 0, 1, 2, 3 asking for 3 pages would still take a 4-page block (internal fragmentation: only powers of two are given out)A buddy is one bit away
The two halves of a split are buddies, and their page numbers differ in exactly one bit. Buddy = page number XOR block size: page 0 pairs with page 1, block 0-1 with block 2-3, block 0-3 with block 4-7. No searching needed.
block size buddy = start XOR size page 0 1 0 ^ 1 = 1 (000 ^ 001 = 001) pages 0-1 2 0 ^ 2 = 2 (000 ^ 010 = 010) pages 0-3 4 0 ^ 4 = 4 (000 ^ 100 = 100) page 5 1 5 ^ 1 = 4 (101 ^ 001 = 100) Only buddies may merge, so a free block is always aligned to its own size.One page, 8 objects
The cache turns page 0 into a slab: 4096 bytes cut into 8 equal slots of 512 bytes, all on the slab's own free list. Equal slots leave no odd-sized gaps between objects, so nothing is lost to external fragmentation.
slab = page 0, 4096 bytes 4096 / 512 = 8 slots slot offset 0 0 1 512 2 1024 3 1536 4 2048 5 2560 6 3072 7 3584 /proc/slabinfo shows it: objsize 512, objperslab, pagesperslabThe object goes out
The cache hands slot 0 to the caller, and kmalloc returns its address in p. The caller uses 400 of the 512 bytes; the other 112 are internal fragmentation, the price of fixed sizes. The next 512-byte request just takes a free slot.
slot 0 -> p (offset 0 in page 0) used 400 bytes slot 512 bytes waste 112 bytes internal fragmentation slots in use: 1 of 8 Objects of one kind can also get their own cache: kmem_cache_create(), then kmem_cache_alloc().kfree keeps the page
kfree(p) puts slot 0 back on the slab's free list. The page stays with the cache, so the next 512-byte request is quick and the buddy allocator is not involved at all.
line 2 kfree(p); slot 0 -> back on the slab free list slots in use: 0 of 8 page 0 still belongs to kmalloc-512 buddy allocator: untouchedBuddies merge back
No object in the slab is in use now, so the cache can give the page back. The buddy allocator checks page 0's buddy: free, so they merge into 2 pages, then 4, then 8. One whole 32 KiB block is free again.
free page 0 (order 0) buddy free -> merge pages 0-1lists [0 1 1 0] buddy free -> merge pages 0-3lists [0 0 1 0] buddy free -> merge pages 0-7lists [0 0 0 1] a page with even one object in use cannot go backWhy two layers?
The buddy allocator keeps pages in blocks that split and merge cheaply, so big runs of pages can be rebuilt. Slab caches serve the many small, same-sized kernel objects quickly, without spending a whole page on each.
the buddy allocator as a Python simulation: free = {0: [], 1: [], 2: [], 3: [0]} # order -> first pages of free blocks def alloc(order): k = order while not free[k]: # find a big enough block k += 1 start = free[k].pop() while k > order: # split in half until it fits k -= 1 free[k].append(start + 2**k) # the right half is the buddy return start def release(start, order): while order < 3: buddy = start ^ 2**order # flip one bit if buddy not in free[order]: break free[order].remove(buddy) # merge with the free buddy start = min(start, buddy) order += 1 free[order].append(start) count = lambda: [len(free[k]) for k in range(4)] page = alloc(0) print("got page", page, count()) print("slab:", 4096 // 512, "objects; kmalloc(400) wastes", 512 - 400) release(page, 0) print("after free", count()) prints: got page 0 [1, 1, 1, 0] slab: 8 objects; kmalloc(400) wastes 112 after free [0, 0, 0, 1]
5 quick questions
Choose one answer per question. You can change your choices before checking them.
01The buddy allocator has one free block of 8 pages and nothing else. A request asks for 1 page. What is left on the free lists afterwards?
The block splits in half until it fits: 8 into 4 + 4, 4 into 2 + 2, 2 into 1 + 1. One page is given out and each spare half joins its own list: one block each of order 2, 1 and 0. Blocks are always powers of two, so a 7-page block cannot exist.
02Which block is the buddy of the 2-page block that starts at page 4?
Buddy = start XOR size: 4 XOR 2 = 6. The two blocks differ in exactly one bit of their page number, so the allocator finds the buddy without searching.
03kmalloc(400) is served from kmalloc-512. What is the 112-byte difference called?
The waste is inside the block that was handed out, so it is internal fragmentation. Fixed slot sizes trade a little of it for fast allocation and no odd-sized gaps between objects.
04Kernel code calls kfree(p) on the only object in use in a slab. What happens right away?
kfree only returns the slot to its slab. A page with no objects in use may then go back to the buddy allocator, where it merges with any free buddies; a page with even one object in use cannot.
05Why do kernels use slab caches on top of the buddy allocator, instead of handing out a whole page for every small object?
A 4096-byte page holds 8 objects of 512 bytes. Giving each its own page would waste most of the page; a slab serves them from one page, and a free slot is ready at once.
Glossary
- Page
- The unit of physical memory the kernel manages: 4096 bytes (4 KiB) on x86-64.
- Buddy allocator
- The kernel's page allocator. It keeps free memory in blocks of 1, 2, 4, 8 ... pages, splits a block in half to serve a smaller request, and merges two free halves (buddies) back together.
- Order
- The size class of a buddy block: a block of order n holds 2^n pages. Linux keeps one free list per order.
- Buddy
- The other half of a block that was split. Its start differs in one bit: buddy = start XOR block size. Only buddies may merge.
- Slab
- One or more pages cut into equal slots for objects of one size, with its own list of free slots.
- Slab cache
- A set of slabs for one object size or one kind of object, such as kmalloc-512. kmalloc picks the smallest cache that fits the request.
- Internal fragmentation
- Space wasted inside a block that was handed out because the block is bigger than the request, such as 112 bytes of a 512-byte slot holding 400 bytes.
- External fragmentation
- Free memory broken into pieces too small or scattered to serve a request, even though enough is free in total.
Notes and sources
- The zone is a toy of 8 pages so every block fits on the table. Real Linux zones hold millions of pages and keep free lists for orders 0 to 10; /proc/buddyinfo shows how many free blocks of each order there are.
- The figure's slab is one page. Linux's allocator today is SLUB, and it often uses slabs of several pages even for 512-byte objects; the pagesperslab column of /proc/slabinfo shows the real number. Bonwick's original slab is "one or more pages".
- The kmalloc caches are 8, 16, 32, 64, 96, 128, 192, 256, 512, 1024 bytes and up, so 400 bytes come from kmalloc-512. Large requests skip the slab layer and go to the page allocator.
- Freed pages merge at once with their free buddies. A slab cache does not always give an empty slab back straight away: it may keep a few empty slabs for the next requests, and gives them up when memory runs short.
- XOR with the block size flips the one bit that tells the two halves apart; Gorman describes the same thing as flipping the order-th bit of the page address.
- R. and A. Arpaci-Dusseau, Operating Systems: Three Easy Pieces, ch. 17: Free-Space Management (buddy and slab)
- J. Bonwick, The Slab Allocator: An Object-Caching Kernel Memory Allocator, USENIX Summer 1994
- M. Gorman, Understanding the Linux Virtual Memory Manager, ch. 6: Physical Page Allocation
- Linux kernel documentation: Memory Allocation Guide
- Linux source: mm/slab_common.c (the kmalloc cache sizes)
- Linux man-pages: proc_buddyinfo(5)
- Linux man-pages: slabinfo(5)
- MIT 6.1810 (2024), xv6: a simple, Unix-like teaching operating system, ch. 3 (physical memory allocator)
- Berkeley CS162, Lecture 14: Memory 1 (fragmentation, internal and external)
Quiz Unlocks after the last step.