ENع
→Managing the TLB
الدرس 32 · Memory management

Managing the TLB: misses, flushes, ASIDs and shootdowns

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

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

Every memory access needs a page-table lookup, so each CPU core keeps a tiny cache of recent translations: the TLB. The hardware fills it, but it never notices when the kernel removes or changes a mapping, so the kernel has to clean up after itself. Follow three lines of C on a two-core machine: a TLB hit, a miss, and an munmap that leaves stale copies behind, which the kernel flushes locally and shoots down on the other core. Then see why a context switch empties the TLB, unless address-space IDs tag the entries. The Hardware lessons “Virtual memory” and “Caches: keeping memory close to the CPU” explain the TLB inside the chip, and “The kernel's page tables: entry bits, building and switching tables” shows the tables it caches.

ستتعلّم

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

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

A cache for translations

Every memory access needs its virtual page translated to a physical frame. Reading the page tables in RAM each time would be slow, so each core keeps a tiny cache of recent translations: the TLB (translation lookaside buffer).

one TLB per core, inside the CPU
entry      virtual page -> physical frame (+ valid, protection)
size       small: a typical TLB has 32, 64 or 128 entries
page       4096 bytes on x86-64, so page = address >> 12

process A (example numbers):
  page 5 -> frame 9     page 6 -> frame 3
core 0 TLB   5→9       (A used page 5 earlier)
core 1 TLB   6→3       (A's second thread used page 6)
جارٍ تحميل الرسم…
أو ← →
اقرأ الدرس خطوة بخطوة
  1. A cache for translations

    Every memory access needs its virtual page translated to a physical frame. Reading the page tables in RAM each time would be slow, so each core keeps a tiny cache of recent translations: the TLB (translation lookaside buffer).

    one TLB per core, inside the CPU
    entry      virtual page -> physical frame (+ valid, protection)
    size       small: a typical TLB has 32, 64 or 128 entries
    page       4096 bytes on x86-64, so page = address >> 12
    
    process A (example numbers):
      page 5 -> frame 9     page 6 -> frame 3
    core 0 TLB   5→9       (A used page 5 earlier)
    core 1 TLB   6→3       (A's second thread used page 6)
  2. Line 1: a TLB hit

    Process A reads p[0], on virtual page 5. Core 0's TLB already holds page 5 → frame 9, so the translation is one quick lookup. No page table read, and the kernel does nothing at all.

    the whole program (C99 + POSIX):
    
    #define _DEFAULT_SOURCE  /* MAP_ANONYMOUS on glibc */
    #include <stdio.h>
    #include <sys/mman.h>
    #include <unistd.h>
    
    int main(void) {
        long ps = sysconf(_SC_PAGESIZE);   /* 4096 on x86-64 */
        char *p = mmap(NULL, 2 * ps, PROT_READ | PROT_WRITE,
                       MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
        if (p == MAP_FAILED) return 1;
        p[0] = 'A'; p[ps] = 'B';
        char x = p[0];
        char y = p[ps];
        int r = munmap(p + ps, ps);
        printf("%c%c %d\n", x, y, r);
        return 0;
    }
    
    line 1   x = p[0];
    page 5   TLB hit -> frame 9
  3. Line 2: a TLB miss

    p[ps] is one page further, page 6 (ps is the page size), and core 0's TLB has no entry for it: a miss. On x86-64 the hardware walks the page tables the kernel built, finds frame 3, fills the TLB and retries the load.

    line 2   y = p[ps];       ps = 4096 on x86-64
    page 6   not in core 0 TLB -> miss
    walk     hardware reads A's page tables (root in CR3)
    fill     TLB gets 6→3, the load is retried and hits
    
    software-managed TLBs (MIPS, SPARC v9):
      the miss traps to the kernel, which looks up the
      page table, writes the TLB with a privileged
      instruction and returns to the same instruction
  4. Line 3: unmapping a page

    munmap asks the kernel to remove page 6. The kernel clears page 6's entry in A's page table. But a TLB is a copy: core 0 still holds 6 → 3, a stale entry that would let A keep using frame 3.

    line 3   r = munmap(p + ps, ps);
    syscall  munmap: the kernel takes over
    kernel   clears the page table entry for page 6
    core 0   TLB still says 6→3   (stale!)
    core 1   TLB still says 6→3   (stale!)
    the hardware never notices page table edits
  5. Flushing one entry

    So the kernel must flush the stale entry itself. It runs a privileged instruction for that one page: invlpg on x86-64, sfence.vma on RISC-V. Page 5's entry survives, so A keeps its fast hits.

    x86-64   invlpg <address of page 6>
    RISC-V   sfence.vma <address>, <asid>
    only this core's TLB; no other entry is touched
    
    Linux flushes a range page by page up to
    33 pages; above that one full flush is cheaper
    (x86 tlb_single_page_flush_ceiling)
  6. Another core's copy

    Process A has a second thread running on core 1, and it used page 6 earlier. Core 1's TLB still holds 6 → 3. Core 0 cannot reach into another core's TLB: each core can only flush its own.

    threads of one process share one address space,
    so every core running A may cache A's pages
    core 1 TLB   6→3   stale
    invlpg and sfence.vma act on the local core only
    Linux tracks which cores ran A (mm_cpumask)
  7. The TLB shootdown

    So the kernel on core 0 sends an inter-processor interrupt (IPI) to core 1. Core 1 stops what it was doing, runs the kernel's flush handler, removes its 6 → 3 entry and reports back.

    core 0   IPI -> core 1: "flush page 6 of A"
    core 1   interrupted; runs the flush handler
             invlpg page 6 on its own TLB
             marks the request done
    
    Linux x86: native_flush_tlb_multi ->
      on_each_cpu_mask(cpus, flush_tlb_func, info, true)
      true = wait for every target core
  8. Wait, then free the frame

    Core 0 waits until every core that may hold the page has answered. Only then is frame 3 safe to give to another process, and munmap returns 0. A later touch of page 6 now faults.

    core 0   waits for core 1's answer
    frame 3  freed only after all copies are gone
             (else a stale entry could write into memory
              that now belongs to another process)
    munmap   returns 0
    later    p[ps] -> page fault -> SIGSEGV
    
    program prints   AB 0
  9. Switching processes: flush all

    Now the kernel switches core 0 to process B. B's page 5 is frame 12, not 9. Without tags, A's old entries would translate B's addresses wrongly, so the TLB is flushed, and B starts with misses.

    context switch   core 0: A -> B
    kernel           loads B's page table root (CR3 / satp)
    no ASIDs         whole TLB flushed
                     (A's 5→9 would map B's page 5 to A's frame!)
    B reads page 5   miss, walk -> frame 12
    
    entries marked global (shared kernel pages) can stay
  10. Tags instead of flushes

    With address-space IDs (ASIDs; x86-64 calls them PCIDs), each entry carries its process's tag. The switch just sets B's tag in a register. A's 5 → 9 and B's 5 → 12 sit side by side; only matching tags hit.

    ASID 1   A   5→9
    ASID 2   B   5→12
    switch   CR3 (x86-64) or satp (RISC-V) gets B's
             table and B's tag; no flush
    back to A later: 5→9 may still be there, a hit
    
    tag sizes: MIPS R4000 8 bits, x86-64 PCID 12 bits
    Linux x86 keeps 6 PCIDs per core for recent processes
  11. The kernel's TLB rules

    The TLB makes translation fast, but it is a copy the hardware never updates. So whenever the kernel removes or changes a mapping, it flushes: one entry locally, other cores by shootdown, and on a switch either everything or, with ASIDs, nothing.

    the rules as a Python simulation:
    
    tables = {"A": {5: 9, 6: 3}, "B": {5: 12}}
    asid = {"A": 1, "B": 2}
    core0 = {(1, 5): 9}  # (asid, page): frame
    core1 = {(1, 6): 3}  # A's 2nd thread
    
    def load(tlb, proc, page):
        key = (asid[proc], page)
        if key in tlb:
            return "hit", tlb[key]
        tlb[key] = tables[proc][page]  # walk
        return "miss", tlb[key]
    
    print(load(core0, "A", 5))  # line 1
    print(load(core0, "A", 6))  # line 2
    del tables["A"][6]          # munmap
    core0.pop((1, 6))           # invlpg
    core1.pop((1, 6))           # shootdown
    print(load(core0, "B", 5))  # B, ASIDs
    print(sorted(core0.items()))
    
    prints:
    ('hit', 9)
    ('miss', 3)
    ('miss', 12)
    [((1, 5), 9), ((2, 5), 12)]

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