Virtual Memory & Demand Paging

a page fault

Suppose you are reading a book and turn to a chapter, only to find that chapter is not in your copy — it is back at the library. You cannot keep reading until you go fetch it. You pause, walk to the library, bring the chapter back, slot it into your book, and then resume reading from exactly the sentence where you stopped. A page fault is the computer's version of this pause: the program reaches for a page that is not in RAM, so it must stop, the missing page is fetched, and then the program continues from the exact instruction it was on.

Concretely, a page fault is the trap that fires when a process references a page whose valid-invalid bit says it is not currently in physical memory. The word 'fault' sounds like an error, but in demand paging it is the normal, expected mechanism. When the reference happens, the memory-management hardware detects the invalid bit and transfers control to the OS instead of completing the access. The OS examines the situation, and if the page is a legitimate part of the process that simply has not been loaded, it goes through page-fault service: locate the page on the backing store, get a free frame, read the page in, update the page table to valid, and restart the instruction that faulted. From the program's perspective the instruction simply executed; it has no idea it was paused for milliseconds.

Why it matters: page faults are the heartbeat of virtual memory — they are how pages get loaded lazily, exactly when needed. But each fault that must touch the disk is enormously expensive compared with an ordinary memory access (a gap of perhaps a hundred thousand times), so the page-fault rate dominates real performance. A handful of faults at startup is fine; a steady storm of faults means the system is spending its time waiting for disk rather than computing, which in the extreme becomes thrashing. The crucial distinction: a page fault (page is on disk, recoverable) is not the same as an illegal-memory fault (the address is not yours at all, usually fatal), even though the same valid-invalid bit triggers both.

A program executes 'load r1, [page 5]'. Page 5's entry is invalid, so the CPU traps. The OS reads page 5 from swap into a frame, marks it valid, and the CPU re-executes the very same 'load' instruction — this time it succeeds and r1 gets its value.

A fault pauses the instruction, the page is fetched, and the same instruction is retried.

A 'fault' here is not a bug. In demand paging the very first reference to nearly every page is a page fault by design; only a fault on an address outside the process's legal space is a true error (often reported to the user as a segmentation fault).

Also called
缺頁缺頁中斷