← 💾 Virtual Memory
Subtopic 1 of 5

6.1Demand paging and page faults

The idea

Demand paging loads a page only when it is first used. A reference to a page not in memory causes a page fault, handled by the OS.

Think of it like this: Fetching books from a library stack only when someone asks for them, instead of carrying the whole library to your desk.

Why it exists

Programs touch only part of their address space at a time, so memory is used for what is actually needed, and programs larger than RAM can run.

How it works

  1. The page table entry is invalid: the MMU traps.
  2. The OS finds a free frame (or a victim, saving it if dirty).
  3. It reads the page from disk; the process waits and another one runs.
  4. The OS updates the table and the instruction is restarted.

Worked example: Why must the instruction be restartable?

The fault can occur in the middle of an instruction (for example the second operand). After the page arrives the whole instruction is run again, so the hardware must not have changed state in a way that breaks that.

Now play with it

  • →Step through the six stages in the animation.
  • →Notice that the CPU runs another process during the disk read.
Page table entryvalid = 0
OSidle
Disk·
Frame·
  • The CPU references page 7: the page table says valid = 0 (not in memory).
  • The MMU raises a page-fault trap and the OS takes over.
  • The OS checks the reference is legal and finds a free frame (or picks a victim, writing it back if dirty).
  • It schedules a disk read of page 7 into frame 12. The process waits and another one runs.
  • The disk interrupt arrives; the OS updates the page table: frame 12, valid = 1.
  • The faulting instruction is restarted and now succeeds.

Restarting the instruction is the hard part: the hardware must be able to undo any side effects of the partly executed instruction.

Check yourself

A page fault is handled by

Remember: Page fault: trap, find frame, read page, update table, restart instruction.
Exam notes (the dense version)

With demand paging a page is brought in only when first referenced. Each page-table entry has a valid bit. On a reference to an invalid page the hardware traps (page fault); the OS finds a free frame (or evicts a victim), reads the page from disk, updates the table and restarts the instruction. A page fault is far more expensive than a memory access (milliseconds against nanoseconds), so the fault rate must be tiny. Copy-on-write and memory-mapped files use the same mechanism.

Previous year questions: Virtual Memory (9)

PYQs are grouped by topic, so this is the full set for Virtual Memory; try the ones that match this subtopic. Open all 9 on the topic page.