Paging & Virtual Memory

Demand paging, page faults, copy-on-write, memory-mapped files, swapping, thrashing and working sets — how the OS gives every process a huge private memory.

Advanced 4 min readLesson 11 of 16 Interview Q&A

Virtual memory gives every process the illusion of a large, private, contiguous memory, even though physical RAM is smaller, shared, and fragmented. The OS and the hardware MMU and TLB cooperate to keep that illusion fast.

Demand paging

The OS doesn't load a program into memory upfront. It sets up page-table entries marked not present and loads each page only when it's first touched:

  1. The program accesses an address whose page isn't present → the MMU raises a page fault.
  2. The kernel checks the address is valid for this process (otherwise: SIGSEGV).
  3. It finds a free frame (evicting a page if necessary — see Page replacement).
  4. It fills the frame: zeros for new heap or stack, or data read from the executable, a file, or swap.
  5. It updates the page table entry to present and restarts the faulting instruction.
Fault typeCostWhen
Minor~1 µsThe page is already in RAM (page cache, a shared library, copy-on-write) — only the mapping is set up
Major~100 µs (SSD) to ~10 ms (HDD)Data must be read from disk

Effective access time with page-fault rate p:

EAT=(1−p)×tmem+p×tfault\text{EAT} = (1 - p) \times t_{\text{mem}} + p \times t_{\text{fault}}

With 100 ns memory and an 8 ms fault, a fault rate of just 1 in 1000 accesses makes memory 80× slower. Major faults must be very rare.

Copy-on-write

After fork(), parent and child share every page, all marked read-only. When either writes, the fault handler copies just that page and makes it writable for the writer. Fork becomes nearly free, and pages that are never written are never copied. Redis uses this to snapshot its whole dataset to disk from a forked child while the parent keeps serving.

Memory-mapped files

mmap maps a file into the address space. Reading the memory triggers faults that load file pages from the page cache; writes go to the page cache and are flushed later (or on msync).

try (FileChannel ch = FileChannel.open(Path.of("data.bin"), READ)) {
    MappedByteBuffer buf = ch.map(FileChannel.MapMode.READ_ONLY, 0, ch.size());
    int first = buf.getInt(0);    // a page fault loads the page on first touch
}

Databases like LMDB and MongoDB's old MMAPv1 engine, search indexes (Lucene), and every shared library rely on mmap.

Swapping

When RAM is full, the OS writes rarely used anonymous pages (heap, stack — data with no file behind it) to a swap area on disk, and reads them back on access. File-backed pages that haven't been modified can simply be dropped and reloaded from their file.

Thrashing and the working set

If processes actively use more pages than fit in RAM, nearly every access faults, the CPU sits idle waiting for the disk, and the system thrashes: throughput collapses.

naive scheduler adds more workMore processesEach gets fewer framesFaults soar → CPU idle

The working set W(t, Δ) is the set of pages a process touched in the last Δ references: what it needs right now. If the sum of working sets exceeds RAM, thrashing follows. Remedies:

  • Suspend or swap out whole processes so the rest fit (load control).
  • Page-fault-frequency control: give more frames to processes faulting a lot, take frames from those faulting rarely.
  • In practice: add RAM, reduce memory use, or limit concurrency.

Other tricks

  • Zero page — newly allocated memory maps to a single shared page of zeros until it's written.
  • Kernel same-page merging (KSM) — merges identical pages across processes or VMs.
  • Memory compression (zswap, macOS compressed memory) — compress cold pages in RAM before resorting to disk.
  • Huge pages — 2 MB or 1 GB pages to cut TLB misses for large heaps.
  • ASLR — randomise where the stack, heap and libraries are placed, making memory-corruption exploits harder.

Seeing it in practice

Shell
$ free -h                         # RAM, page cache ("buff/cache") and swap
$ vmstat 1                        # si/so = swap in/out per second
$ cat /proc/<pid>/status | grep -E "VmRSS|VmSize"
$ /usr/bin/time -v ./program      # major and minor page faults

VSZ (virtual size) counts everything mapped, even if never touched; RSS (resident set size) counts pages actually in RAM. A JVM with a 100 GB VSZ and a 2 GB RSS is perfectly normal.

Key takeaways
  • Demand paging loads pages on first access via page faults.
  • Minor faults just set up mappings; major faults read from disk and are very expensive.
  • Copy-on-write makes fork cheap; mmap maps files into memory through the page cache.
  • Swapping moves anonymous pages to disk; thrashing happens when working sets exceed RAM.
  • VSZ ≠ RSS: virtual size is reserved address space; RSS is what actually uses RAM.
Interview questions
QWhat is thrashing and how do you detect it?medium

When active working sets exceed physical memory, the system spends most of its time handling page faults and swapping rather than doing useful work. Signs: very high major-fault and swap in/out rates (vmstat si/so), high I/O wait, low CPU utilisation, and everything becoming unresponsive.

QWhy can a process's virtual memory exceed physical RAM?easy

Virtual memory is just address space. Pages are only backed by physical frames when touched, untouched reservations cost nothing, file-backed pages can be dropped, and anonymous pages can be swapped out.