Managing the TLB: misses, flushes, ASIDs and shootdowns
لم يُترجم بعد؛ يُعرض باللغة الإنجليزية
عن هذا الدرس
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.
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)
اقرأ الدرس خطوة بخطوة
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)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 9Line 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 instructionLine 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 editsFlushing 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)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)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 coreWait, 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 0Switching 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 stayTags 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 processesThe 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)]
أسئلة سريعة: 5
اختر إجابة واحدة لكل سؤال. يمكنك تغيير اختياراتك قبل التحقق منها.
01On x86-64, process A reads a page whose translation is not in the core's TLB, but the page is mapped. What happens?
x86-64 has a hardware-managed TLB: on a miss the CPU itself walks the page tables (rooted at CR3), loads the entry and retries. Software-managed TLBs such as MIPS trap to the kernel instead.
02The kernel has just cleared a page-table entry during munmap. Why must it also flush the TLB?
The TLB is a cache the hardware fills but does not keep in sync. Until the stale entry is flushed (invlpg on x86-64, sfence.vma on RISC-V), the process could still reach the old frame.
03Process A has threads on core 0 and core 1, and both TLBs cached page 6. Core 0 runs munmap on page 6. How does core 1's entry go away?
invlpg only affects the core that runs it. This cross-core flush is a TLB shootdown: an IPI makes each other core flush its own copy, and the initiating core waits for all of them.
04Why does the kernel wait for every core to answer before it reuses frame 3?
If the frame were handed out while some TLB still mapped it, the old process could scribble on the new owner's memory. Linux's x86 flush calls on_each_cpu_mask with wait set to true.
05With address-space IDs (PCIDs on x86-64), what does the kernel do with the TLB when it switches from process A to process B?
Each entry carries its address space's tag, so translations from different processes can sit side by side. The switch only sets the current tag (in CR3 on x86-64, satp on RISC-V), and no flush is needed.
المسرد
- Page / frame
- Memory is split into fixed-size blocks, 4096 bytes on x86-64. A page is a block of a process's virtual addresses; a frame is a block of physical RAM. The page table maps pages to frames.
- Context switch
- The kernel stopping one process on a core and starting another, which includes loading the new process's page table root (CR3 on x86-64, satp on RISC-V).
- TLB (translation lookaside buffer)
- A small cache inside each CPU core that holds recent virtual page → physical frame translations, so most memory accesses skip the page-table lookup.
- TLB miss
- An access whose translation is not in the TLB. Hardware (x86-64, and usually RISC-V) or the kernel (MIPS) then reads the page tables and fills an entry.
- Stale entry
- A TLB entry that no longer matches the page table, for example after the kernel unmapped the page. It must be flushed.
- TLB flush
- Removing entries from a core's TLB: one page (invlpg on x86-64, sfence.vma with an address on RISC-V) or all of them.
- TLB shootdown
- Flushing an entry on other cores: the kernel sends them an inter-processor interrupt (IPI: one core interrupting another), each flushes its own TLB, and the sender waits for all of them.
- ASID
- Address-space identifier: a tag on each TLB entry that says which process it belongs to, so a context switch need not flush. Intel and AMD call it a PCID.
الملاحظات والمصادر
- The page and frame numbers are made up to keep them short: real mmap addresses are much higher (around 0x7f... on x86-64 Linux), and real TLBs have dozens of entries, not three.
- x86-64 refills the TLB in hardware by walking the page tables, and so do most RISC-V chips (the RISC-V spec also allows a software refill). Older RISC designs such as MIPS use a software-managed TLB: a miss traps to the kernel, which fills the entry itself and returns to retry the same instruction.
- The figure shows one other core. A real shootdown sends the interrupt to every core that may be caching the address space, and waits for all of them. Some new CPUs (AMD INVLPGB, Intel RAR) can do part of this in hardware.
- ASID is the general name (MIPS, ARM, RISC-V); Intel and AMD call it PCID, the process-context identifier. Kernel pages are often marked global so they survive a switch even without tags.
- The C program is single-threaded so it runs anywhere; the second thread on core 1 is part of the scenario. It asks sysconf for the page size (4096 on x86-64), so it also runs where pages are bigger.
- R. and A. Arpaci-Dusseau, Operating Systems: Three Easy Pieces, ch. 19: Paging: Faster Translations (TLBs)
- Berkeley CS162, Lecture 16: Memory 3: TLBs (cont.), Demand Paging
- MIT 6.1810 (2024), xv6: a simple, Unix-like teaching operating system, rev. 4, §3.3 (TLB and sfence.vma)
- Linux kernel documentation: The x86 kernel, TLB
- Linux kernel documentation: Cache and TLB Flushing Under Linux
- Linux source: arch/x86/mm/tlb.c (PCIDs, shootdown IPIs, flush ceiling)
- Linux source: arch/x86/include/asm/tlbflush.h (TLB_NR_DYN_ASIDS)
- Linux source: arch/x86/include/uapi/asm/processor-flags.h (X86_CR3_PCID_BITS)
- Linux man-pages: mmap(2) and munmap(2)
اختبار يتاح بعد الخطوة الأخيرة.