012345674 KiBSLAB8 KiB4 KiB16 KiB4 KiB8 KiB4 KiB32 KiB4 KiB8 KiB4 KiB16 KiB4 KiB8 KiB4 KiBorder 00order 10order 20order 310·512·1024·1536·2048·2560·3072·3584·KMALLOC-5121p = kmalloc(400, GFP_KERNEL);2kfree(p);PAGE 0p
Back: physical pages as buddy blocks, and the free listsMiddle: the slab (one page, 8 slots) and the kmalloc-512 cacheTokens: the request, the page and the object p moving between themBack: 8 physical pages carrying the buddy blocks, and the free lists, one count per order. Middle: the slab tray and the kmalloc-512 cache. Front: the kernel code. kmalloc(400) goes to kmalloc-512, which takes one page from the buddy allocator: the 32 KiB block splits 8 → 4 + 4 → 2 + 2 → 1 + 1. Page 0 becomes a slab of 8 slots; slot 0 goes out as p and comes back on kfree; the page returns and the buddies merge. 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.

Two allocators

  1. 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.

A request

Slabs of objects

Giving it back

What happens

;; step 1/10 · two-layers
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.

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".