The kernel's page tables: entry bits, building and switching tables
لم يُترجم بعد؛ يُعرض باللغة الإنجليزية
عن هذا الدرس
The MMU translates every address through a page table, but who writes those tables? The kernel. It keeps one table per process in its own memory, fills in each entry (a frame number plus flag bits such as present, writable and user), lets the hardware set the accessed and dirty bits, rewrites entries when a program calls mmap, mprotect or munmap, and points the CPU at another table on every context switch. Follow four lines of C as the kernel builds one entry on a page fault, changes it and tears it down, then switches to another process. The Hardware lesson Virtual memory explains the translation itself and is a good warm-up.
A table for every process
The kernel keeps one page table for each process, in the kernel's own memory. Entry n says which physical frame holds that process's page n. The CPU's MMU reads the table on every access; only the kernel writes it.
page table one per process, in kernel memory
entry n -> the frame holding page n
A's table page 0 -> frame 3 page 1 -> frame 1
page 2 -> (none)
B's table page 0 -> frame 0 page 1 -> frame 2
page 2 -> (none)
free frames 4, 5
MMU (hardware) reads entries on every access
kernel writes themاقرأ الدرس خطوة بخطوة
A table for every process
The kernel keeps one page table for each process, in the kernel's own memory. Entry n says which physical frame holds that process's page n. The CPU's MMU reads the table on every access; only the kernel writes it.
page table one per process, in kernel memory entry n -> the frame holding page n A's table page 0 -> frame 3 page 1 -> frame 1 page 2 -> (none) B's table page 0 -> frame 0 page 1 -> frame 2 page 2 -> (none) free frames 4, 5 MMU (hardware) reads entries on every access kernel writes themInside one entry
Zoom into A's page 2. An x86 entry holds a frame number and flag bits: P (present), R/W (writes allowed), U/S (user mode allowed), A (accessed) and D (dirty: written). This one is all zeros: page 2 is not mapped.
one page-table entry (x86): frame which physical frame holds the page P present: 1 = the frame number is good R/W 1 = writes allowed, 0 = read only U/S 1 = user mode may use it, 0 = kernel only A accessed: set by the MMU on any use D dirty: set by the MMU on a write A's page 2 now: frame - P 0 R/W 0 U/S 0 A 0 D 0Line 1: asking for a page
mmap asks the kernel for one page of fresh memory. The kernel only writes a note in its own records: A may use page 2. It takes no frame yet and leaves the entry at P = 0.
the whole program (C99, POSIX): #define _DEFAULT_SOURCE #include <stdio.h> #include <sys/mman.h> #include <unistd.h> #define RW (PROT_READ | PROT_WRITE) #define ANON (MAP_PRIVATE | MAP_ANONYMOUS) int main(void) { size_t pg = (size_t)sysconf(_SC_PAGESIZE); char *p; p = mmap(0, pg, RW, ANON, -1, 0); if (p == MAP_FAILED) return 1; p[0] = 'x'; mprotect(p, pg, PROT_READ); printf("%c\n", p[0]); munmap(p, pg); return 0; } line 1 p = mmap(0, pg, RW, ANON, -1, 0); kernel notes: page 2 of A is valid, zero-filled entry unchanged: P = 0 (no frame yet)Line 2: the first write faults
Line 2 stores x in page 2. The MMU reads the entry, finds P = 0 and traps to the kernel: a page fault. The kernel checks its notes. Page 2 is valid, just not filled in yet.
line 2 p[0] = 'x'; MMU entry for page 2: P = 0 -> page fault trap user mode -> kernel mode, fault handler kernel is page 2 in one of A's regions? yes (mmap) so: fill it in (otherwise: SIGSEGV)The kernel builds the entry
The kernel takes free frame 4 and fills it with zeros. Then it writes the entry: frame 4, P = 1, R/W = 1, U/S = 1. It returns from the trap, and the CPU retries the store.
free list [4, 5] -> take frame 4 -> [5] frame 4 fill with zeros (MAP_ANONYMOUS reads as 0) entry frame 4 P 1 R/W 1 U/S 1 A 0 D 0 return back to user mode, retry line 2The hardware sets A and D
This time the MMU finds frame 4, and x lands there. The MMU itself sets A, because the page was used, and D, because it was written. Later the kernel reads these bits to choose which pages to keep.
retry page 2 -> frame 4: allowed, x stored MMU sets A = 1 (used) and D = 1 (written) entry frame 4 P 1 R/W 1 U/S 1 A 1 D 1 the hardware sets A and D; only the kernel clears themLine 3: read only now
mprotect asks the kernel to make the page read only. The kernel clears R/W and makes the CPU drop any cached copy of the entry. Reads still work; a write would fault, and the kernel would stop the program with SIGSEGV, the segmentation-fault signal.
line 3 mprotect(p, pg, PROT_READ); kernel entry R/W 1 -> 0 flush the old copy from the TLB entry frame 4 P 1 R/W 0 U/S 1 A 1 D 1 printf reads p[0]: prints x p[0]='y' would fault -> SIGSEGVLine 4: giving it back
munmap gives the page back. The kernel clears the entry, so P = 0 again, flushes the cached copy and puts frame 4 back on its free list. Touching page 2 now would end the program with SIGSEGV.
line 4 munmap(p, pg); entry cleared: frame - P 0 R/W 0 U/S 0 A 0 D 0 TLB flushed for that page frame 4 back on the free list -> [5, 4] p[0] now would raise SIGSEGVSwitching tables
When A's turn ends, the kernel switches to process B. Besides the registers, it writes the address of B's table into the CPU's table register (CR3 on x86-64). Only kernel mode may. Now page 1 means frame 2, not frame 1.
context switch A -> B (in kernel mode): save A's registers, load B's CR3 = address of B's table (RISC-V: satp) page 1 A: frame 1 B: frame 2 user mode cannot write CR3: it is privileged A's table stays in kernel memory for A's next turnOne table, one private world
A process can only reach the frames its own table lists, and only the kernel can edit a table or point the CPU at one. Building entries, setting bits and switching tables is how the kernel gives every process its own memory.
the whole story as a Python simulation: free = [4, 5] # free physical frames A = {0: [3, {"P", "US"}], 1: [1, {"P", "RW", "US"}]} B = {0: [0, {"P", "US"}], 1: [2, {"P", "RW", "US"}]} cr3 = A # the table the MMU uses def mmu(page, write=False): # hardware: check, then set A / D e = cr3.get(page) if e is None or "P" not in e[1] or (write and "RW" not in e[1]): return "fault" e[1] |= {"A", "D"} if write else {"A"} return e[0] print(mmu(2, write=True)) # page 2: no entry yet A[2] = [free.pop(0), {"P", "RW", "US"}] # kernel fills it in print(mmu(2, write=True), sorted(A[2][1])) A[2][1].discard("RW") # mprotect(PROT_READ) print(mmu(2), mmu(2, write=True)) free.append(A.pop(2)[0]) # munmap cr3 = B # context switch to B print(mmu(1), free) prints: fault 4 ['A', 'D', 'P', 'RW', 'US'] 4 fault 2 [5, 4]
أسئلة سريعة: 5
اختر إجابة واحدة لكل سؤال. يمكنك تغيير اختياراتك قبل التحقق منها.
01Who writes the entries of a process's page table?
Page tables live in kernel memory and only the kernel writes them. The MMU reads them on every access. The one exception is the A and D bits, which the hardware itself sets.
02A program calls mmap for one page of anonymous memory and then writes to it for the first time. On Linux, what happens on that first write?
By default the kernel only records the new region at mmap time. The first touch faults, the kernel checks its records, finds the page is valid, builds the entry and returns; the CPU retries the store. MAP_POPULATE asks for the entries to be filled up front instead.
03Which bits of an x86 page-table entry does the hardware set by itself?
The MMU sets A whenever the page is used and D whenever it is written. It never clears them; the kernel does. A tells the kernel which pages were used lately, so which to keep in memory; D tells it which pages must be written back to disk before their frame is reused.
04After mprotect(p, pg, PROT_READ), what has the kernel changed, and what happens if the program then writes to p[0]?
mprotect changes the protection bits of the entries in the range. Reads still work, but a write breaks R/W = 0, faults, and mprotect(2) says the kernel then generates SIGSEGV.
05On a context switch from process A to process B, how does the kernel make the MMU use B's table?
Each process keeps its own table in kernel memory. Switching is just pointing the table register at another one, which only kernel mode may do; that is why a process cannot reach another process's frames.
المسرد
- Page table
- The kernel's per-process list that says, for each virtual page, which physical frame holds it and what the process may do with it.
- Page-table entry (PTE)
- One row of a page table: a frame number plus flag bits such as P, R/W, U/S, A and D.
- Frame
- A page-sized slot of physical memory. The kernel keeps the unused ones on a free list.
- Present bit (P)
- 1 means the entry's frame number is good. An access to a page with P = 0 traps to the kernel as a page fault.
- Accessed and dirty bits (A, D)
- Bits the hardware sets when a page is used (A) or written (D). The kernel reads and clears them.
- MMU
- The memory management unit: the part of the CPU that turns each virtual address into a physical one by reading the current page table.
- Page fault
- The trap the MMU raises when an entry does not allow an access, for example P = 0 or a write to a read-only page.
- Table register
- The CPU register that holds the physical address of the current page table: CR3 on x86-64, satp on RISC-V. Only kernel mode may write it.
الملاحظات والمصادر
- The drawing shows three pages per process and six frames, numbered from 0. On a real 64-bit system mmap returns a large address, and the table has several levels; the lesson Multi-level page tables shows how.
- Real x86 entries have more bits (PWT, PCD, PAT and G for caching, and on x86-64 an execute-disable bit). RISC-V, used by MIT 6.1810, names its flags V, R, W, X and U, with A and D besides.
- Linux fills an anonymous page on its first touch, as drawn; the MAP_POPULATE flag asks it to fill the entries at mmap time instead. Either way the page reads as zeros.
- The CPU keeps recent entries in a small cache, the TLB, so after changing an entry the kernel must make sure no stale copy is used. The lesson Managing the TLB shows how.
- CR3 holds the physical address of the top of the current table; on RISC-V the register is satp. With page-table isolation, Linux on x86-64 also switches CR3 on every entry to and exit from the kernel.
- The drawing follows OSTEP: the hardware sets A and D on the retried store. Real kernels may set them already when they build the entry; Linux marks a writable anonymous page dirty in do_anonymous_page (mm/memory.c), so the MMU finds D = 1.
- The card shows the four lines that change the table. The whole program also asks sysconf for the page size (4096 bytes on x86-64 Linux), checks for MAP_FAILED and prints the x it wrote.
- R. and A. Arpaci-Dusseau, Operating Systems: Three Easy Pieces, ch. 18: Paging: Introduction
- OSTEP ch. 21: Beyond Physical Memory: Mechanisms
- OSTEP ch. 22: Beyond Physical Memory: Policies
- Berkeley CS162, Lecture 14: Virtual Memory, Segments and Page Tables
- Berkeley CS162, Lecture 2: Four Fundamental OS Concepts
- MIT 6.1810 (2024), lecture notes: Virtual memory
- Linux kernel documentation: Page Tables
- Linux kernel documentation: Cache and TLB Flushing Under Linux
- Linux kernel documentation: Page Table Isolation (x86)
- Linux man-pages: mmap(2)
- Linux man-pages: mprotect(2)
اختبار يتاح بعد الخطوة الأخيرة.