Pages in RAM and on disk
Process P has four 4 KB pages, but only two RAM frames, 5 and 6. Pages 2 and 3 wait on disk, in swap space. Each page table entry says where: F5 means present in frame 5; S0 means not present, in swap slot 0.
Line 1 writes to 0x0008: page 0, offset 8. Its entry says frame 5, present, so the MMU sends the write to 0x5008. It also sets the entry's dirty bit, D: page 0 has changed. The kernel is not involved.
Handling a page fault
Line 2 reads 0x2010: page 2. Its entry says S0, present bit 0: the page is on disk, not in RAM. The MMU cannot finish the read, so it raises a page fault. The CPU traps into the kernel and records the faulting address.
The kernel's page-fault handler first checks that page 2 is a legal part of P's address space: it is. Then it finds where the page lives. The entry holds a disk address, swap slot 0, in the bits that normally hold a frame number.
Both frames are in use, so a page must leave. This kernel picks the oldest: page 0 in frame 5. It is dirty, so the kernel first writes it to free swap slot 2. Page 0 becomes not present; its TLB entry is dropped.
The kernel asks the disk to copy swap slot 0 into frame 5. A disk takes milliseconds, so P is marked blocked and the CPU runs other ready processes meanwhile. When the read is done, the disk interrupts and the kernel carries on.
The kernel updates page 2's entry: frame 5, present bit 1. Swap slot 0 is free again. P moves from blocked to ready, so the scheduler can run it again.
The kernel returns from the trap to the same instruction, not the next one. Line 2 runs again: page 2 is present in frame 5, so 0x2010 becomes 0x5010. P never notices the fault; it only ran slower.
Limits and cost
Line 3 reads 0x9000: page 9. P's address space has only pages 0 to 3, so there is no entry and no copy anywhere. The fault reaches the kernel as before, but this one is a bug: the kernel sends SIGSEGV, which ends P.
A memory access takes about 100 ns; a disk read about 10 ms, 100,000 times longer. If just 1 access in 1,000 went to disk, the average would be 10.1 µs: about 100 times slower than RAM. So kernels keep busy pages in memory.
What happens
;; step 1/10 · pages
page table of P (one entry per 4 KB page)
page 0 F5 present bit 1, frame 5
page 1 F6 present bit 1, frame 6
page 2 S0 present bit 0, swap slot 0
page 3 S1 present bit 0, swap slot 1
RAM (P may use 2 frames) frame 5: page 0 frame 6: page 1
swap space on disk slot 0: page 2 slot 1: page 3
slot 2: free
The machine is a toy: four 4 KB pages, two frames and three swap slots. Real processes have many thousands of pages, and the kernel shares all of RAM between them. F5 and S0 are this figure's shorthand for a page table entry. A real entry packs a present bit, a dirty bit, permission bits and either a frame number or a disk address into one 64-bit word.