Demand paging

On this page 7

Demand paging is a virtual memory technique in which the operating system loads a page into physical memory only when a process first touches it, instead of reading the whole program before execution starts. In memory management, it is the default strategy of modern operating systems such as Linux, Windows and macOS, and it is the reason a large application can start before most of its code has been read from disk.

The mechanism depends on cooperation between the memory management unit and the kernel. Pages that are not yet resident are marked invalid in the page table, and the first access to such a page triggers a page fault that the kernel resolves by bringing the data in.

How demand paging resolves a page fault

Demand paging works by treating the first access as a request. When a process reads or writes a virtual address whose page table entry has the present bit cleared, the processor stops the instruction and raises a page fault exception that transfers control to the kernel.

The kernel then checks whether the address belongs to a valid region of the address space. If it does, the kernel finds a free page frame, fills it with the right content, updates the page table entry and restarts the faulting instruction, which now succeeds as if nothing had happened.

The table below summarizes the steps of a typical demand-paging fault.

StepComponentAction
AccessProcess and MMUTranslation finds a non-present page and raises a fault
ValidationKernelConfirms the address lies in a mapped region with correct permissions
Frame allocationKernel allocatorTakes a free frame or evicts a page to create one
FillKernel and storageReads from file or swap, or zero-fills an anonymous page
MappingKernel and MMUSets the present bit and the frame number in the page table
RestartProcessorReexecutes the instruction that caused the fault
Steps in handling a demand-paging fault

If the address is not part of any mapping, or the access violates the permissions of the region, the kernel does not load anything. It delivers a segmentation fault or an access violation to the process instead.

Minor and major page faults

Not every fault requires disk access, and the difference determines its cost. A minor fault can be satisfied from data already in memory, while a major fault must wait for storage I/O, which is orders of magnitude slower.

The following table compares the main fault types that demand paging produces and their typical cost.

Fault typeSource of dataTypical cost
Minor faultPage already in the page cache or shared by another processAround a microsecond
Zero-fill faultFresh anonymous memory cleared by the kernelA few microseconds
Major fault from SSDExecutable, library or swap on solid-state storageTens to hundreds of microseconds
Major fault from HDDData on a rotating diskSeveral milliseconds
Invalid accessNo valid mapping existsProcess receives a signal or exception
Page fault types under demand paging

Operating system tools report these counters separately. A high rate of minor faults is usually harmless, whereas a sustained rate of major faults points to insufficient memory or cold storage reads.

Demand paging compared with other loading strategies

Demand paging is one point on a spectrum between loading everything eagerly and loading nothing until it is needed. Real systems combine it with prefetching and copy-on-write to reduce the number of expensive faults.

The table below places demand paging next to related strategies.

StrategyWhen pages are loadedMain benefitMain drawback
Eager loadingEntire program before executionNo faults during runSlow start and wasted memory
Pure demand pagingOnly on first accessMinimal memory useMany faults at startup
Demand paging with read-aheadOn access, plus neighboring pagesFewer major faults for sequential accessMay load unused pages
PrepagingPredicted working set before it is neededFaster resume after swappingWrong predictions waste I/O
Copy-on-writePrivate copy only on first writeCheap process creation with forkExtra fault on the first write
Memory loading strategies

Memory-mapped files are a direct application of the same principle. Mapping a large file costs almost nothing, and only the regions actually read generate I/O, which makes memory mapping attractive for databases and large data sets.

Why operating systems rely on demand paging

The main advantage of demand paging is that programs use physical memory in proportion to what they touch, not to their size. Large applications contain code for rarely used features, error handling and locales that may never execute in a given session.

  • Faster startup, because execution begins after only a few pages are loaded.
  • Higher multiprogramming level, because more processes fit into the same amount of RAM.
  • Virtual address spaces larger than RAM, combined with swapping for inactive pages.
  • Lazy allocation, so a large memory request succeeds immediately and frames are assigned on use.

Lazy allocation also enables memory overcommit, where the kernel promises more memory than it can physically provide. This works well on average but means that a shortage may appear later, at the moment of a fault, rather than at allocation time.

Limitations and failure modes

Demand paging performs well only when the working set fits in memory. When active processes together need more frames than exist, the system keeps evicting pages that are needed again soon, and it enters thrashing, a state in which most time is spent on paging I/O.

The decision table below lists common symptoms and the usual remedies.

SymptomLikely causeTypical remedy
Constant disk activity and stallsThrashing from an oversized working setAdd RAM or reduce concurrent workload
Slow first response after idlePages evicted while the process sleptLock critical pages or tune swappiness
Unpredictable latency spikesMajor faults on a time-critical pathPrefault and lock memory before real-time work
Process killed under loadOvercommit exhausted at fault timeLimit overcommit or set memory limits
Demand paging problems and remedies

Real-time and low-latency software therefore often disables demand paging for itself by touching and locking all of its memory at startup, trading a larger footprint for predictable timing.

The idea in brief

Imagine a huge reference library where you never carry every book to your desk at once. You fetch a book only when you actually need to look something up, and you return books you have not opened in a while to make room.

Demand paging lets a computer treat programs the same way. The system brings in pieces of a program only when they are used, so applications open quickly and many programs can share limited memory. The cost is a short pause whenever a missing piece must be fetched.

A practical scenario

A data analyst opens a 40 GB memory-mapped data file on a workstation with 32 GB of RAM. The mapping is created in milliseconds, because demand paging reads nothing until the analysis code touches specific rows. A query that filters one month of records reads only about 2 GB of pages from the SSD, and the operating system adds read-ahead for the sequential scan.

Later, the analyst runs a join that randomly accesses the whole file while a virtual machine also consumes 12 GB. Major page faults climb into the thousands per second and the query slows dramatically. After the virtual machine is shut down, the working set fits again and the same join finishes about five times faster, illustrating that demand paging is efficient only while active data fits in RAM.