ENع
→Multi-level page tables
الدرس 33 · Memory management

Multi-level page tables

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

14 دقيقة11 خطوة5 أسئلةIntermediate
عن هذا الدرس

Every process needs a page table, and a flat one for a 32-bit address space is 4 MiB, almost all of it empty. Multi-level page tables fix that by turning the table into a tree: a small page directory points at page-sized pieces of the table, and pieces with nothing in them are never built. Follow one address, 0x00C05123, as the CPU splits it into three fields and walks the tree from the CR3 register to the byte it wants, then watch a second address hit a gap and fault. The Hardware lesson on virtual memory explains translation in the chip, and Managing the TLB shows how most walks are skipped.

ستتعلّم

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

شكل 33 · تفاعلي
01 / 11

One flat table is huge

On a 32-bit machine with 4 KiB pages, a flat page table needs one 4-byte entry for each of about a million pages: 4 MiB for every process. Most programs use only a few pages, so nearly all those entries are empty.

address space   2^32 bytes = 4 GiB
page size       2^12 bytes = 4 KiB
pages           2^32 / 2^12 = 2^20 = 1,048,576
entry size      4 bytes
flat table      2^20 x 4 = 4,194,304 bytes = 4 MiB
                one per process, and it must sit in one piece
جارٍ تحميل الرسم…
أو ← →
اقرأ الدرس خطوة بخطوة
  1. One flat table is huge

    On a 32-bit machine with 4 KiB pages, a flat page table needs one 4-byte entry for each of about a million pages: 4 MiB for every process. Most programs use only a few pages, so nearly all those entries are empty.

    address space   2^32 bytes = 4 GiB
    page size       2^12 bytes = 4 KiB
    pages           2^32 / 2^12 = 2^20 = 1,048,576
    entry size      4 bytes
    flat table      2^20 x 4 = 4,194,304 bytes = 4 MiB
                    one per process, and it must sit in one piece
  2. Chop it into pages

    Cut the flat table into page-sized pieces of 1024 entries. A piece with no used pages is simply never built. A small page directory, itself one page, lists where each built piece lives, or marks it not present.

    one piece       1024 entries x 4 bytes = 4096 bytes = one page
    pieces          2^20 / 1024 = 1024 pieces
    page directory  1024 entries, one per piece (one page)
      present       frame number of the piece
      not present   the piece does not exist at all
    
    your page size, from the kernel (C99, POSIX):
    
    #include <stdio.h>
    #include <unistd.h>
    
    int main(void) {
        long size = sysconf(_SC_PAGESIZE);
        printf("page size: %ld bytes\n", size);
        return 0;
    }
  3. Three parts of an address

    The program reads address 0x00C05123. The memory unit splits its 32 bits into three fields: the top 10 bits pick a directory entry (3), the next 10 pick a table entry (5), and the low 12 are the offset inside the page (0x123).

    address   0x00C05123
    bits      0000 0000 11 | 00 0000 0101 | 0001 0010 0011
              dir = 3         table = 5        offset = 0x123
    
    d   = va >> 22             top 10 bits
    t   = (va >> 12) & 0x3FF   next 10 bits
    off = va & 0xFFF           low 12 bits (2^12 = 4096 bytes)
  4. CR3 finds the directory

    Every walk starts at a CPU register. On x86 it is CR3, which holds where this process's page directory is: frame 0x50. The kernel loads CR3 on each context switch, so each process walks its own tree.

    CR3        0x00050000   physical address of the directory
               = frame 0x50 x 4096
    who sets   the kernel, in kernel mode (a privileged write)
    when       every context switch to another process
    RISC-V     the same job is done by the satp register
  5. Level 1: the directory

    The memory unit reads directory entry 3. It is present and holds a frame number, 0x52: the page of the page table that covers this 4 MiB slice of memory. That is the first read from memory.

    read 1    directory[3]   at 0x0005000C
              = 0x50000 + 3 x 4 bytes
    entry     present, frame 0x52
    covers    addresses 0x00C00000 .. 0x00FFFFFF (4 MiB)
  6. Level 2: the page table

    Next it reads entry 5 of that page table. This entry is present too, and gives the frame where the page really lives: 0x2A7. That is the second read from memory.

    read 2    table 0x52[5]   at 0x00052014
              = 0x52000 + 5 x 4 bytes
    entry     present, frame 0x2A7
    covers    addresses 0x00C05000 .. 0x00C05FFF (one page)
  7. Add the offset

    The offset is never translated. Joining frame 0x2A7 with offset 0x123 gives the physical address 0x2A7123. Now the real read happens, and the program gets its byte: 42.

    frame    0x2A7
    offset   0x123
    physical 0x2A7 x 4096 + 0x123 = 0x2A7123
    read 3   memory[0x2A7123] = 42
    
    virtual 0x00C05123  ->  physical 0x002A7123
  8. An entry that is not there

    Now the program touches 0x00400000. Its top bits pick directory entry 1, which is not present: no page table was ever built there. The walk stops and the CPU raises a page fault, so the kernel decides what happens.

    address   0x00400000
    split     dir = 1   table = 0   offset = 0x0
    read 1    directory[1]   not present
    result    page fault -> the kernel
    kernel    build a page table and map a page (valid use),
              or send SIGSEGV (a bad address)
  9. What we saved

    This process uses three slices: code, data and stack. So it needs the directory plus three page tables: 16 KiB, instead of 4 MiB for the flat table. That is 256 times less. A program using more memory gets more tables.

    present directory entries   0 (code), 3 (data), 1023 (stack)
    tables built                 3
    two-level total              (1 + 3) x 4 KiB = 16 KiB
    flat table                   4 MiB = 4096 KiB
    ratio                        4096 / 16 = 256 times smaller
    
    bonus: the pieces can sit in any free frames;
    a flat 4 MiB table needs 4 MiB in one piece
  10. The price: more reads

    Each level is one more memory read. Without help, every load costs three reads instead of two with a flat table. The TLB (see Managing the TLB) keeps recent translations, so most accesses skip the walk; only a TLB miss pays for it.

    flat table    1 read for the entry  + 1 for the data
    two levels    2 reads for entries   + 1 for the data
    four levels   4 reads for entries   + 1 for the data
    
    TLB hit       0 reads for entries: same speed as before
    TLB miss      walk the tree (hardware on x86 and RISC-V)
    
    a time-space trade-off: smaller tables, slower misses
  11. Real 64-bit machines go deeper

    With 64-bit addresses one directory would be far too big, so the same trick repeats. x86-64 walks four levels, 9 bits each, on 48-bit addresses; newer chips can use five. Linux names its levels PGD, P4D, PUD, PMD and PTE.

    x86-64 (4 levels)   9 | 9 | 9 | 9 | 12   = 48-bit address
                        512 entries x 8 bytes = one 4 KiB page each
    x86-64 (5 levels)   one more 9-bit level = 57-bit address
    RISC-V Sv39         9 | 9 | 9 | 12 (three levels)
    Linux names         PGD > P4D > PUD > PMD > PTE
                        (unused levels are "folded" away)
    
    the walk as a Python simulation:
    
    directory = {0: 0x51, 3: 0x52, 1023: 0x53}   # present entries only
    tables = {0x51: {0x48: 0x1A0}, 0x52: {5: 0x2A7}, 0x53: {1023: 0x3F1}}
    memory = {0x2A7123: 42}
    
    def walk(va):
        d = va >> 22                # top 10 bits
        t = (va >> 12) & 0x3FF      # next 10 bits
        off = va & 0xFFF            # low 12 bits
        if d not in directory:
            raise LookupError(f"page fault at {va:#010x}")
        frame = tables[directory[d]][t]
        return frame << 12 | off
    
    pa = walk(0x00C05123)
    print(hex(pa), memory[pa])
    try:
        walk(0x00400000)
    except LookupError as e:
        print(e)
    
    prints:
    0x2a7123 42
    page fault at 0x00400000

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