A page fault is the exception that the memory management unit raises when it cannot complete a memory access under the current page table, either because the page table entry for the address is not present or because the entry forbids the access. The kernel’s fault handler then either establishes a valid mapping and restarts the faulting instruction or delivers a signal to the process.

Most page faults are not errors. They are the mechanism by which a process receives memory on first touch, by which pages shared copy-on-write after fork are copied on the first write, and by which file-mapped or swapped-out pages are read back from disk. When a fault requires a free frame and none is available, the kernel must also choose a page to evict.

Virtual pages, physical frames and page table entries (PTEs) with a valid bit are defined in paging.

What raises a fault

The memory management unit (MMU) raises a fault when the PTE for an address is not present, or when it is present but forbids the access: a write to a read-only page, a user-mode access to a kernel page, or an instruction fetch from a page marked no-execute. On x86-64 the processor puts the faulting virtual address in the CR2 register and pushes an error code whose low bits encode the cause (Intel SDM Vol. 3A, §4.7):

BitNameSet when
0Pthe page was present, so this is a protection violation (clear means not present)
1W/Rthe access was a write
2U/Sthe access came from user mode
3RSVDa reserved bit was set in some paging-structure entry
4I/Dthe access was an instruction fetch

The processor does not identify the faulting process. The kernel determines it from the task that was running, and that task’s memory map and page table root are where the handler starts.

A page fault is a fault in the x86 sense: the saved instruction pointer points at the instruction that faulted, not the one after it, and no part of that instruction has taken effect. When the handler returns, the instruction runs again from the start and this time finds a usable PTE. A system call, by contrast, returns to the instruction after the trap.

The kernel classifies every fault into one of three outcomes:

  • Bad address. No mapping covers the address, or the mapping forbids this access, such as a write to a read-only mapping. The process receives SIGSEGV.
  • Minor fault. The access is legitimate and the data is already in memory, or doesn’t need to be read at all. A first touch of anonymous memory receives a zeroed page. A file page already in the page cache only needs a PTE. A write to a page shared copy-on-write after fork receives a private copy.
  • Major fault. The data has to be read from a file or from swap first. The faulting thread sleeps while the I/O runs, and the scheduler runs something else.

Linux reports both counts per process (ru_minflt and ru_majflt from getrusage, or min_flt and maj_flt in /proc/PID/stat). Windows calls the same two kinds soft and hard faults; Windows memory management describes the standby and modified lists that make many of its soft faults possible.

What the handler does

Linux’s handler, handle_mm_fault, is one implementation of the general procedure:

flowchart TD
    F[Trap: faulting address in CR2, error code on stack] --> V{Address inside a mapping<br/>that allows this access?}
    V -->|no| SEG[Send SIGSEGV]
    V -->|yes| W[Walk the page table,<br/>allocating missing levels]
    W --> K{What is in the PTE?}
    K -->|empty, anonymous mapping| Z[Read: map the shared zero page<br/>Write: allocate and zero a frame]
    K -->|empty, file mapping| PC{Page in the page cache?}
    PC -->|yes| MAP[Map it, plus cached neighbours]
    PC -->|no| RD[Start a read, sleep until it lands]
    K -->|swap entry| SW[Read the page back from swap]
    K -->|present but write-protected,<br/>shared copy-on-write| COW[Copy to a new frame,<br/>map it writable]
    RD --> MAP
    Z --> R[Return; the faulting instruction runs again]
    MAP --> R
    SW --> R
    COW --> R
    style SEG fill:#f9d0d0,stroke:#c00
    style R fill:#e8f5e9,stroke:#2e7d32

The first step looks up the address in the process’s list of mappings, which Linux calls virtual memory areas (VMAs). Each VMA records a range, its permissions, and what backs it: nothing (anonymous memory), or a file and an offset. A fault outside every VMA, or one the VMA’s permissions don’t allow, is the SIGSEGV case. Until Linux 6.4 this lookup held mmap_lock, one lock for the whole address space, so a thread faulting in one mapping could wait behind another thread changing a different one. Since 6.4 most faults lock only the VMA they hit (LWN).

Next the handler walks the page table from the root, allocating any missing intermediate tables, down to the PTE for the address. The contents of that PTE determine the remaining steps:

  • An empty PTE in an anonymous mapping is a first touch. A read maps the kernel’s shared zero page read-only, so a program that only reads its newly allocated memory never receives a private copy. A write allocates a frame, zeroes it, and maps it writable.
  • An empty PTE in a file mapping means a lookup in the page cache by file and page index. If the page is there, the fault is minor, and Linux also maps neighbouring pages that are already cached (“fault-around”), so a sequential reader takes one fault per block of pages instead of one per page. If it isn’t there, the kernel starts the read, usually with readahead so the next pages arrive in the same I/O, and the thread sleeps on the page’s lock until the data arrives.
  • A non-present PTE holding a swap entry is an anonymous page that was swapped out. The hardware ignores every other bit of a PTE whose present bit is clear, so Linux writes the swap device and slot into the invalid PTE itself (kernel page table docs). The swap entry is therefore the “disk address” of an evicted anonymous page, and no separate table records it. File pages need no such entry, because the VMA’s file and offset already identify the location of the data.
  • A present PTE that is write-protected in a writable mapping is copy-on-write. If another process still shares the frame, the kernel copies it into a new frame and maps that one writable. If this process is the last user, the kernel makes the PTE writable without copying.

The frame that a read targets must remain in place until the read completes, which Linux guarantees by holding the page locked in the page cache. Once the PTE is filled in, the handler returns and the instruction restarts.

What a fault costs, measured

The cost depends on which branch the handler takes. fault_cost.c touches one byte in each page of a 64 MiB region configured in eight ways, 15 times each, and divides the time by the number of 4 KiB pages:

What the loop touchesFaults per pageTime per 4 KiB page, median (IQR)
Pages already mapped (the loop’s own cost)023 ns (19 to 26)
Anonymous memory, first read (zero page)1675 ns (629 to 766)
Anonymous memory, first write (zero a new frame)11.70 µs (1.58 to 1.95)
Anonymous memory after fork, written by the child (copy)12.89 µs (2.67 to 3.89)
Anonymous memory backed by 2 MiB huge pages, first write1/5120.82 µs (0.56 to 1.32)
File pages already in the page cache1/3273 ns (64 to 77)
File pages on disk, readahead off137.3 µs (34.9 to 38.3)
File pages on disk, default readahead1/321.48 µs (1.44 to 1.87)
  • A minor fault costs about a microsecond. Trapping, finding the VMA and filling the PTE costs about 0.7 µs when no frame is needed (the zero page). Allocating and zeroing a frame brings it to 1.7 µs, and copying 4 KiB instead of zeroing it to 2.9 µs.
  • A major fault costs about 20 times a minor one here, and far more on slower storage. This machine is a virtual machine whose disk is a virtual block device, and 37 µs per random 4 KiB read is in the range of a fast SSD. A spinning disk takes several milliseconds per random read, the cost of thousands of minor faults.
  • Batching amortizes most of the cost. With default readahead, one I/O brought in all 64 MiB and the rest of the accesses became minor faults that each mapped about 32 pages, for 1.5 µs per page instead of 37. The cached-file case shows the same batching on its own: 516 faults for 16,384 pages, 2.3 µs per fault, 73 ns per page.
  • Huge pages reduce the fault count by a factor of 512 and the time by much less. Each 2 MiB fault took about 420 µs, almost all of it zeroing 2 MiB. Per byte that is about half the cost of 4 KiB faults. The larger benefit of huge pages is in TLB reach (Huge pages).

Two kinds of fault are not measured. The VM has no swap device, so there are no swap-ins, and the dirty-page writeback that a replacement can force is not isolated.

Finding a free frame

A fault that needs a new frame takes one from the free lists. Linux is designed to avoid running page replacement inside the fault itself. Each memory zone has three watermarks, min, low and high. When free memory drops below low, the kernel wakes kswapd, a background thread that reclaims pages until free memory is back above high. Only when an allocation would take free memory below min does the allocating thread reclaim pages itself (“direct reclaim”), and in that case a page fault can take milliseconds (sysctl/vm docs, min_free_kbytes and watermark_scale_factor).

Reclaim selects victims and must then free each victim’s frame. The work required depends on the frame’s contents:

  • A clean file page can be dropped. Its data is still in the file, so the next access is a major fault that reads it back.
  • A dirty file page has to be written back to its file first.
  • An anonymous page can be evicted only to swap. It is written to a swap slot and its PTE becomes a swap entry. With no swap configured, as on the VM above, anonymous memory can’t be reclaimed at all, and the kernel can only drop file pages or, when that fails, kill a process.

The victim’s PTE may belong to another process, and a shared page may be mapped by many. The kernel finds every PTE that maps a frame through its reverse map, clears each one, and flushes the stale translations from every CPU’s TLB, which on a multiprocessor means interrupting the other CPUs (a TLB shootdown; see translation lookaside buffers). Doing this ahead of time, in kswapd and in background writeback that cleans dirty pages before their frames are needed, keeps most faults minor.

Choosing the victim

When memory is full, a page must be evicted, and the choice of victim determines the number of future faults. Textbooks treat four policies:

  • OPT (Belady’s MIN): evict the page whose next use is furthest in the future. It requires knowledge of future references, so no kernel can implement it, but it gives the fewest faults possible for a given memory size (Belady 1966). Every other policy is measured against it.
  • FIFO: evict the page that was loaded earliest, however recently it was used.
  • LRU: evict the page whose last use is furthest in the past. Exact LRU requires a record of every access, which the hardware does not provide.
  • CLOCK: the frames sit in a circle with a reference bit each, which the hardware sets on every access. A hand sweeps the circle on each eviction, clearing set bits and evicting the first page whose bit is already clear. It needs only the bit the hardware already provides, and approximates LRU (Corbató 1968).

The paging note defines these and the counter-based LRU approximations in more detail. They are evaluated on traces of real programs. Each trace is the full list of 4 KiB pages a program touched, in order: every instruction fetch, load and store, recorded with Valgrind’s Lackey tool, with back-to-back repeats of the same page merged. The merge changes no policy’s fault count, because a repeat is always a hit and changes no state that matters. The simulator replays one million consecutive references from the middle of each run.

Suggested uses of the simulator:

  • Drag the memory slider on sort between 8 and 12 frames. LRU faults 53,195 times with 9 frames, 27,289 with 10 and 3,729 with 11. Sort’s inner loop cycles through about 11 pages, and once they all fit nearly every reference hits. Below that, LRU repeatedly evicts the page the loop references next. OPT, which sacrifices some pages to retain others, faults about a third as often at 8 and 9 frames.
  • Switch the map between policies. Each mark is a fault. LRU and FIFO fault in dense bands when the program cycles through more pages than fit. OPT’s faults are sparser at the same size.
  • Step through an eviction. Each row says which page the policy evicted and why: when it was loaded, when it was last used, how far the clock hand swept, or when it will next be needed. At 16 frames or fewer the rows also draw the frames.
  • Try the textbook string with 3 and then 4 frames. FIFO takes 9 faults with 3 frames and 10 with 4. This is Belady’s anomaly, which also occurs in the real traces (Belady’s anomaly in real traces).

GNU sort sorting 200 KB of text. Shown: references 2,539,917 to 3,539,916 of 6,079,832, which touch 85 distinct 4 KiB pages.

1002005001k2k5k10k20k50k100k200k500k1M125102050frames of memory (log scale)page faults (log scale)CLOCK: 87 faults with 47 frames, 88 with 48CLOCK: 86 faults with 49 frames, 87 with 50CLOCK: 86 faults with 52 frames, 87 with 53CLOCK: 86 faults with 55 frames, 88 with 56CLOCK: 86 faults with 58 frames, 87 with 59CLOCK: 86 faults with 60 frames, 88 with 61CLOCK: 86 faults with 67 frames, 87 with 68CLOCK: 87 faults with 68 frames, 88 with 69CLOCK: 87 faults with 71 frames, 88 with 72CLOCK: 87 faults with 74 frames, 88 with 75CLOCK: 87 faults with 76 frames, 88 with 77CLOCK: 87 faults with 78 frames, 88 with 79CLOCK: 87 faults with 80 frames, 88 with 81CLOCK: 86 faults with 82 frames, 87 with 83
  • FIFO 14,694 (4.90× OPT)
  • CLOCK 10,269 (3.42× OPT)
  • LRU 3,729 (1.24× OPT)
  • OPT 3,001 (the minimum)

Rings mark frame counts where one more frame caused more faults: 0 for FIFO and 14 for CLOCK on this trace.

Where the faults fall time runs left to right, pages by first use top to bottom; marks are faults under

The step view needs the reference string, which loads with the page's script.

Real page reference strings, recorded by running each program under Valgrind and keeping every instruction fetch, load and store as a 4 KiB page number. Each program trace shown is one million consecutive references from the middle of the run. The curves are fault counts that pagesim.c computed for every frame count; the map and the step view rerun the same policies in your browser, and a test checks that they agree.

Results on the full runs

The figure uses a window of each run so that the browser can replay it. The table uses the four complete runs, from 6 to 36 million references each. At each memory size it gives LRU’s faults and every other policy’s faults relative to LRU:

ProgramFootprintFramesLRU faultsFIFOCLOCKARCRandom (5 seeds)OPT
sort593 pages16120,6721.31×1.16×1.01×1.09×0.48×
(2.3 MiB)642,1721.47×1.01×1.00×1.62×0.57×
gzip -9260 pages16753,8091.14×1.03×1.00×1.14×0.56×
(1.0 MiB)645271.48×1.10×1.00×1.73×0.69×
bzip2 -9508 pages16548,8281.30×1.03×0.96×1.36×0.60×
(2.0 MiB)64114,4291.05×0.94×1.00×1.07×0.41×
gcc (cc1)1,883 pages64231,2241.41×1.18×1.01×1.32×0.42×
(7.4 MiB)2565,3281.54×1.07×1.01×1.76×0.68×
  • The gap to OPT is large at every size measured. LRU incurs 1.5 to 2.5 times OPT’s faults at these sizes. No online policy closes much of that gap on these traces. The best case is ARC on bzip2 with 16 frames, at 4% fewer faults than LRU.
  • CLOCK stays close to LRU. It is within 18% of LRU everywhere in the table, and on bzip2 at 64 frames it incurs 6% fewer faults than LRU.
  • FIFO incurs the most faults of the deterministic policies on these traces. It evicts pages that are still referenced frequently if they were loaded early. On sort at 16 frames and gcc at 64 it incurs more faults than random eviction. Random eviction’s results across 5 seeds differ by less than 1% where faults are frequent and by up to about 6% either way where they are rare.
  • ARC gives no improvement over LRU on these traces. ARC was designed for disk and database caches, where it splits the cache between pages seen once recently and pages seen more than once. In a memory reference string nearly every page is referenced again within a few instructions, so almost everything counts as “seen more than once” and ARC behaves like LRU.
  • Faults drop steeply once the working set fits. gzip’s LRU faults fall from 29,562 at 48 frames to 527 at 64. Quadrupling memory again to 256 frames only brings them to 260, one compulsory fault per page. Denning’s working set model is built on this shape.

Belady’s anomaly in real traces

Under FIFO, adding a frame can increase the number of faults. Belady, Nelson and Shedler constructed reference strings where it does (1969), and the textbook string in the figure is the small example commonly given. The anomaly also occurs in real programs. The table counts, over every frame count from 1 to each program’s footprint (to 600 frames for gcc), the frame counts at which one more frame increased the faults.

ProgramFrame counts where one more frame added faultsLargest case
sortFIFO 3 of 592, CLOCK 60 of 592CLOCK, 152 → 153 frames: 805 → 839 faults
gzip -9FIFO 0 of 259, CLOCK 18 of 259CLOCK, 129 → 130 frames: 285 → 290 faults
bzip2 -9FIFO 20 of 507, CLOCK 38 of 507FIFO, 173 → 174 frames: 5,777 → 7,527 faults (+30%)
gcc (cc1)FIFO 15 of 599, CLOCK 101 of 599FIFO, 148 → 149 frames: 31,495 → 32,732 faults

LRU and OPT cannot exhibit the anomaly. Both are stack algorithms (Mattson et al. 1970): the set of pages they keep in frames is always a subset of what they would keep in , so anything that hits with less memory also hits with more. FIFO lacks this property because the order it loads pages in depends on the memory size, and CLOCK lacks it because the hand’s position does. The anomaly in these traces is local, a few percent at scattered sizes with one 30% case, and the curves still fall overall. In theory it has no bound: Fornai and Iványi construct strings where the ratio of faults with more memory to faults with less is arbitrarily large.

Huge pages

A 2 MiB huge page replaces 512 PTEs with one entry a level up. Linux backs anonymous memory with transparent huge pages (THP) when an aligned 2 MiB range is available, either at fault time or later, when the khugepaged thread collapses runs of small pages into large ones (THP docs). The fault table shows the fault-side effect: 512 times fewer faults, each costing hundreds of microseconds to zero 2 MiB.

The other effect is translation reach. tlb_walk.c follows a random cycle of pointers, one per 4 KiB page, through 1 GiB, so every load lands on a different page. With 4 KiB pages it took 166 ns per load (median of 10 runs, range 162 to 185). With 2 MiB pages, touching exactly the same cache lines, it took 125 ns (range 121 to 130). The 41 ns difference is attributable to TLB misses and page walks: 262,144 small pages are far more than the TLB holds, while 512 huge ones nearly fit. The TLB benchmark note measures the 4 KiB side of this with strided scans.

Huge pages have costs. Zeroing 2 MiB in one fault adds latency to that one access. A process that touches one byte of a 2 MiB range gets all 2 MiB, and finding free aligned 2 MiB ranges can force the kernel to move pages around (compaction). For these reasons many distributions set THP to madvise, so only programs that ask for huge pages get them.

Costs of paging

Extra memory references

Every access needs a translation. A TLB hit adds no memory references. A miss makes the hardware walk the page table, one dependent memory read per level: four levels on x86-64 with 48-bit addresses, five with 57-bit addresses. Caches inside the page walker hold upper-level entries and shorten most walks. In a virtual machine both the guest’s and the host’s page tables have to be walked, and a walk through two 4-level tables can take up to 24 memory references (Bhargava et al. 2008). The measurement above ran in a VM, so its 41 ns includes that nesting.

Page table size

A flat page table needs one PTE per page of the address space, used or not. With 32-bit addresses, 4 KiB pages and 4-byte PTEs:

x86-64 PTEs are 8 bytes, and a flat table for a 48-bit address space would need of them, 512 GiB per process. Address spaces are sparse, and multi-level and hashed designs exploit that sparsity.

Old fix: page the page table

VAX/VMS kept the system page table in physical memory and placed each process’s page tables in the system’s virtual address space, so they could be paged like anything else, and a reference could fault on its page table before it faulted on its data (Levy and Lipman 1982). Linux keeps page tables in unswappable kernel memory.

Current fix: multi-level page tables

A multi-level page table adds levels of indirection and creates only the tables that cover addresses in use. With two levels, the virtual address splits into a master page number, a secondary page number and an offset. The master table maps the master page number to a secondary table, and the secondary table maps the secondary page number to a frame:

flowchart LR
    VA[Virtual address] --> M[Master page number]
    VA --> S[Secondary page number]
    VA --> O[Offset]
    M -->|index| MPT[(Master page table)]
    MPT -->|points to| SPT[(Secondary page table)]
    S -->|index| SPT
    SPT --> PFN[Page frame number]
    PFN --> PA[Physical address]
    O --> PA
    style MPT fill:#e3f2fd,stroke:#1565c0
    style SPT fill:#e3f2fd,stroke:#1565c0
    style PA fill:#e8f5e9,stroke:#2e7d32

x86-64 uses four levels of 512 eight-byte entries: 9 bits of index per level and 12 bits of offset, 48 bits in all. One 4 KiB table at the bottom level covers 2 MiB, and one at the level above covers 1 GiB.

This granularity determines how much page table memory a sparse layout requires. pt_size.c touches the same 16 MiB of data, 4,096 pages, in three layouts and reads the page table size the kernel reports (VmPTE in /proc/self/status):

Layout of 4,096 touched pagesAddress range spannedPage table memory
Contiguous16 MiB32 KiB (0.2% of the data)
One page per 2 MiB8 GiB16,416 KiB (100%)
One page per 1 GiB4 TiB32,800 KiB (200%)

Dense data requires 8 bytes of page table per 4 KiB page. With one page per 2 MiB, every page requires its own bottom-level table; with one page per 1 GiB, each also requires a table at the next level up. Multi-level tables bound the cost by the portion of the address space in use rather than by its size, but sparse use within each 2 MiB region still requires whole tables.

Other designs

  • Hashed page tables. Hash the virtual page number into a table whose entries hold the VPN and the frame, chaining on collisions. The table’s size scales with physical memory rather than with the address space. PowerPC’s hashed page table and Itanium’s optional virtually hashed page table worked this way.
  • Inverted page tables. One entry per physical frame, holding the process ID and VPN that live there. The space is minimal, but translation becomes a search, so it goes through a hash of (process ID, VPN), and sharing a frame between processes is difficult because the frame has only one entry. IBM’s RT PC used an inverted table.