ENع
→Slab and buddy allocators
الدرس 39 · Memory in practice

Kernel memory: slab and buddy allocators

لم يُترجم بعد؛ يُعرض باللغة الإنجليزية

14 دقيقة10 خطوات5 أسئلةAdvanced
عن هذا الدرس

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.

ستتعلّم

حدّد ما تشعر بأنك أتقنته. هذا التقييم الذاتي لا يؤثر في درجة الدرس.

شكل 39 · تفاعلي
01 / 10

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.
جارٍ تحميل الرسم…
أو ← →
اقرأ الدرس خطوة بخطوة
  1. 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.
  2. 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  587
  3. A 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)
  4. 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)
  5. 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.
  6. 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, pagesperslab
  7. The 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().
  8. 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: untouched
  9. Buddies 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 back
  10. Why 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]

اختبار يتاح بعد الخطوة الأخيرة.