{}DSA Atlas

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.

Intermediate → Advanced7 interview questions

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.

Process A page 0 page 1 page 2 Process B page 0 (libc) page 1 Physical RAM (frames) frame 0: A0 frame 1: libc frame 2: B1 frame 3: A2 frame 4: free Disk (swap / file) A1 (swapped) A1 not present → touching it causes a page fault
Pages map to any frame; shared libraries occupy one frame for everyone; some pages live on disk.

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 typeCauseCost
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)
Invalidaddress not in any mapping or permission violationSIGSEGV

Effective access time with page faults

Let memory access = 200 ns, page-fault service time = 8 ms, fault probability = p:

Text
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:

Text
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.

Ref70120304230321201701
F177722224440000000777
F20000333222221111100
F3111100033333222221
Fault✗✗✗✗✗✗✗✗✗✗✗✗✗✗✗

Optimal (OPT / MIN) — evict the page used furthest in the future

Provably minimal, but needs future knowledge — used as a benchmark. 9 faults.

Ref70120304230321201701
F177722222222222222777
F20000004440000000000
F3111333333331111111
Fault✗✗✗✗✗✗✗✗✗

LRU — evict the least recently used page

Uses the past as a predictor of the future. 12 faults.

Ref70120304230321201701
F177722224440001111111
F20000000033333300000
F3111333222222222777
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.

Text
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

AlgorithmFaults (example)Cost to implementBelady's anomaly?
FIFO15trivialyes
Optimal9impossible (future)no
LRU12expensive (exact)no
Clock14cheap (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:

FramesFIFO faultsLRU faults
3910
410 ↑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.

degree of multiprogramming (number of processes) CPU utilisation thrashing begins more parallelism helps
Past the peak, adding processes makes everything slower.

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.
Python
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

0 / 7 marked confident

Answer out loud first, then open the model answer. Mark a question confident only when you could explain it to an interviewer without notes.