Virtual Memory & Page Replacement
Demand paging, what happens on a page fault, effective access time with faults, page replacement (FIFO, Optimal, LRU, Clock, LFU) worked step by step, Belady's anomaly, frame allocation, thrashing and the working set, copy-on-write, mmap and swap.
The idea
Virtual memory separates the memory a program sees from the physical RAM it actually uses. Each process gets a huge private address space; pages are mapped to RAM only when needed, and can be evicted to disk when RAM runs short.
Demand paging
Pages are loaded only when first accessed (lazy loading). A program that touches 10% of its code only ever loads 10% of it.
- Pure demand paging — start with no pages resident; fault everything in.
- Prepaging / readahead — load neighbouring pages speculatively (Linux reads ahead on sequential file access).
Minor vs major faults
| Fault type | Cause | Cost |
|---|---|---|
| Minor (soft) | page is in RAM (page cache, zero page, COW) but not mapped | ~0.1–1 µs |
| Major (hard) | page must be read from disk/swap | ~100 µs (NVMe) to ~10 ms (HDD) |
| Invalid | address not in any mapping or permission violation | SIGSEGV |
Effective access time with page faults
Let memory access = 200 ns, page-fault service time = 8 ms, fault probability = p:
EAT = (1 − p) × 200 ns + p × 8,000,000 ns
= 200 + 7,999,800·p ns
With p = 1/1000 → EAT ≈ 8.2 µs — a 40× slowdown. To keep the slowdown under 10% (EAT < 220 ns), we need p < 2.5 × 10⁻⁶: fewer than one fault per 400,000 accesses. Page faults must be rare.
Page replacement
When a fault occurs and no frame is free, the OS must choose a victim page to evict (writing it back first if it's dirty). The goal: minimise future faults.
The reference string
All examples use 3 frames and the classic reference string:
7 0 1 2 0 3 0 4 2 3 0 3 2 1 2 0 1 7 0 1
FIFO — evict the oldest page
Simple queue. Ignores how often or recently a page is used. 15 faults.
| Ref | 7 | 0 | 1 | 2 | 0 | 3 | 0 | 4 | 2 | 3 | 0 | 3 | 2 | 1 | 2 | 0 | 1 | 7 | 0 | 1 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| F1 | 7 | 7 | 7 | 2 | 2 | 2 | 2 | 4 | 4 | 4 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 7 | 7 | 7 |
| F2 | 0 | 0 | 0 | 0 | 3 | 3 | 3 | 2 | 2 | 2 | 2 | 2 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | |
| F3 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 3 | 3 | 3 | 3 | 3 | 2 | 2 | 2 | 2 | 2 | 1 | ||
| Fault | ✗ | ✗ | ✗ | ✗ | ✗ | ✗ | ✗ | ✗ | ✗ | ✗ | ✗ | ✗ | ✗ | ✗ | ✗ |
Optimal (OPT / MIN) — evict the page used furthest in the future
Provably minimal, but needs future knowledge — used as a benchmark. 9 faults.
| Ref | 7 | 0 | 1 | 2 | 0 | 3 | 0 | 4 | 2 | 3 | 0 | 3 | 2 | 1 | 2 | 0 | 1 | 7 | 0 | 1 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| F1 | 7 | 7 | 7 | 2 | 2 | 2 | 2 | 2 | 2 | 2 | 2 | 2 | 2 | 2 | 2 | 2 | 2 | 7 | 7 | 7 |
| F2 | 0 | 0 | 0 | 0 | 0 | 0 | 4 | 4 | 4 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | |
| F3 | 1 | 1 | 1 | 3 | 3 | 3 | 3 | 3 | 3 | 3 | 3 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | ||
| Fault | ✗ | ✗ | ✗ | ✗ | ✗ | ✗ | ✗ | ✗ | ✗ |
LRU — evict the least recently used page
Uses the past as a predictor of the future. 12 faults.
| Ref | 7 | 0 | 1 | 2 | 0 | 3 | 0 | 4 | 2 | 3 | 0 | 3 | 2 | 1 | 2 | 0 | 1 | 7 | 0 | 1 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| F1 | 7 | 7 | 7 | 2 | 2 | 2 | 2 | 4 | 4 | 4 | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 1 |
| F2 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 3 | 3 | 3 | 3 | 3 | 3 | 0 | 0 | 0 | 0 | 0 | |
| F3 | 1 | 1 | 1 | 3 | 3 | 3 | 2 | 2 | 2 | 2 | 2 | 2 | 2 | 2 | 2 | 7 | 7 | 7 | ||
| Fault | ✗ | ✗ | ✗ | ✗ | ✗ | ✗ | ✗ | ✗ | ✗ | ✗ | ✗ | ✗ |
Walk-through of one decision: at the reference to 4 (position 8), frames hold {2, 0, 3}. Their last uses were 2 at position 4, 0 at position 7, 3 at position 6 → 2 is least recently used → evict 2.
Implementing exact LRU (the same structure as the LRU cache): a hash map + doubly linked list, or a counter/timestamp per page. In hardware that's too expensive for every memory access, so OSes approximate it.
Clock (second chance) — practical LRU approximation
Frames form a circle with a hand. Each page has a reference bit set by hardware on access.
on fault:
while frame[hand].ref == 1:
frame[hand].ref = 0 # give it a second chance
hand = (hand + 1) % n
evict frame[hand]; load new page there with ref = 1
hand = (hand + 1) % n
On our reference string Clock produces 14 faults — between FIFO and LRU, at a fraction of LRU's cost. Enhanced clock uses (referenced, dirty) pairs and prefers (0,0) victims: unreferenced and clean (no write-back needed).
Counting algorithms
- LFU — evict the least frequently used. Suffers when a page was heavily used once and never again (fix with decay/aging).
- MFU — evict the most frequently used (argument: low-count pages were just loaded). Rarely good.
Summary
| Algorithm | Faults (example) | Cost to implement | Belady's anomaly? |
|---|---|---|---|
| FIFO | 15 | trivial | yes |
| Optimal | 9 | impossible (future) | no |
| LRU | 12 | expensive (exact) | no |
| Clock | 14 | cheap (1 bit/page) | yes (in theory) |
Belady's anomaly
With FIFO, more frames can mean more faults. Reference string 1 2 3 4 1 2 5 1 2 3 4 5:
| Frames | FIFO faults | LRU faults |
|---|---|---|
| 3 | 9 | 10 |
| 4 | 10 ↑ | 8 ↓ |
LRU and OPT are stack algorithms (the pages held with n frames are always a subset of those held with n + 1), so they can't exhibit the anomaly.
Frame allocation
How many frames does each process get?
- Equal allocation: m frames / n processes.
- Proportional: by process size (or priority).
- Global replacement: a victim may belong to any process — better throughput, less predictable (Linux).
- Local replacement: victims come only from the faulting process's own frames — more isolation.
- NUMA: prefer frames on the memory node near the CPU running the process.
Thrashing
If processes have fewer frames than their actively used pages, they fault continuously: the disk is saturated, CPU utilisation drops, and a naive scheduler admits even more work.
The working-set model
The working set W(t, Δ) is the set of pages referenced in the last Δ references. If the sum of all working-set sizes exceeds available frames → thrashing. The OS should keep each process's working set resident or suspend whole processes.
Page-fault frequency (PFF) control is the practical version: if a process's fault rate is above an upper bound, give it more frames; below a lower bound, take some away.
Copy-on-write, zero pages and memory-mapped files
- COW: after
fork, pages are shared read-only and copied only when written (see Processes). - Zero page: newly allocated anonymous memory maps a shared all-zero page until written.
- Memory-mapped files (
mmap): file pages are mapped into the address space through the page cache; reading memory reads the file.
import mmap
with open("big.bin", "r+b") as f:
mm = mmap.mmap(f.fileno(), 0) # map the whole file
header = mm[:16] # page faults pull data in lazily
mm[100:104] = b"\x00\x01\x02\x03" # dirties a page; written back later
mm.flush() # msync
mm.close()
Swap
Swap space holds evicted anonymous pages (heap, stack). File-backed pages don't need swap — clean ones are simply dropped and re-read from the file. Linux's vm.swappiness tunes the balance between dropping page cache and swapping anonymous memory. Many production database/Kubernetes nodes disable or limit swap to keep latency predictable (Kubernetes added swap support as beta, but most clusters still run without it).
The page cache
All file I/O goes through the page cache: free RAM is used to cache file data, which is why free -h shows little "free" but plenty of "available" memory. Writes go to the cache and are flushed by background writeback; fsync forces dirty pages (and metadata) to disk — critical for databases' durability guarantees.
Interview questions
Answer out loud first, then open the model answer. Mark a question confident only when you could explain it to an interviewer without notes.