Skip to content

Virtual memory and page faults

Deep diveUnder the hood

Two processes can hold the same pointer value and see different data, and a program can reserve more memory than the machine has. Both work because every address your program uses is virtual. Here is how the CPU translates each one, what the TLB saves, and what happens on a page fault.

01 Every address your program sees is virtual

When your program reads *p, the number in p is a virtual address. Before the read reaches RAM, the CPU’s memory management unit (MMU) translates it to a physical address, using a map the kernel keeps for each process: its page table. Every process gets its own map, so each one sees a private address space that starts empty and belongs to it alone.

Two processes, the same virtual page 2, different frames
Process A page table
p0f1
p1—
p2f3
p3—
Process B page table
p0f4
p1f6
p2f0
p3—
Physical RAM · 8 frames (toy)
f0B p2
f1A p0
f2free
f3A p2
f4B p0
f5free
f6B p1
f7free
  • entry for page 2
  • where page 2 really is

Both processes can use address 0x2ABC. A’s goes to frame 3 and B’s to frame 0, so neither can see or damage the other’s memory.

The map does not have to point at RAM at all. An entry can say “not here yet” or “out on disk”, and the kernel fills it in when the page is first used. That is how a program can reserve gigabytes and only use RAM for the pages it touches.

02 Pages: translate in blocks, not bytes

A map with one entry per byte would be larger than memory itself. So memory is mapped in fixed-size blocks: pages of virtual memory onto frames of physical memory, the same size. On x86-64 Linux a page is normally 4 KiB (4,096 bytes); 64-bit Arm systems may use 4, 16 or 64 KiB. The low bits of an address are the offset inside the page and are never translated.

One 16-bit address, split into page number and offset (toy machine, 4 KiB pages)
High 4 bits: page or frame number
327681638481924096204810245122561286432168421value
virtual 0x2ABC001010101011110010940
physical 0x3ABC001110101011110015036

Only the marked top bits change in translation: page 2 becomes frame 3. The low 12 bits, the offset 0xABC, pass through as they are, because a page and a frame are the same size.

A real x86-64 address has 48 meaningful bits (57 with five-level paging), far too many for one flat table per process. So the page table is a tree of small tables, and the page number is split into four 9-bit indexes, one per level. Levels for unused parts of the address space are simply never created.

How x86-64 splits a 48-bit virtual address (4-level paging, 4 KiB pages)
BitsPicksEntries per table
47–39an entry in the top-level table (PML4)512
38–30an entry in the next table (PDPT)512
29–21an entry in the page directory (PD)512
20–12an entry in the page table (PT): the frame512
11–0the byte inside the 4 KiB page4,096 offsets

03 Translate one address, step by step

To keep the pictures small, this toy machine has 16-bit addresses, 4 KiB pages and only 4 frames of RAM. Process A uses pages 0 to 7. Watch the TLB, a small cache inside the CPU, on the second load.

Translating three addresses
Step 1 of 7
Memory reads 0
Page table of process A · ptr = page number
p0f1
p1—
p2f3
p3—
p4f0
p5—
p6swap s1
p7f2
TLB
Empty
Physical RAM · 4 frames (toy)
f0A p4
f1A p0
f2A p7
f3A p2
  • entry read in a walk
  • cached in the TLB
  • hit, or data read
  • not present

Process A has just been switched onto the CPU, so its TLB is empty. Its next instruction loads a value from virtual address 0x2ABC.

0x2ABC address

04 The TLB: a cache for translations

With four levels, a translation that misses the TLB costs four extra memory reads before the real one. The translation lookaside buffer keeps recent page-to-frame answers so most accesses skip the walk. It is small: typically a few dozen entries at the first level and one to a few thousand at the second, depending on the CPU.

The TLB belongs to the CPU core, not the process. When the kernel switches to another process, the old translations are wrong, so they are flushed, or tagged with an address-space ID (PCID on x86, ASID on Arm) so they can stay without being used. Either way, a fresh process starts with cold translations, one hidden cost of a context switch.

4 KiB pages64 entries ≈ 256 KiBA program that jumps around a few gigabytes misses the TLB constantly.
2 MiB huge pages64 entries ≈ 128 MiBOne entry covers 512 small pages. Databases and JVMs often use huge pages for big heaps.

The numbers above are the reach of a 64-entry TLB, a common size for a first-level data TLB. Linux can use huge pages explicitly (hugetlbfs) or automatically with transparent huge pages.

05 Page faults: when the map says “not here”

A page fault is the CPU telling the kernel “I could not translate this”. It is not an error in itself. Most faults are part of normal life, and the kernel fixes them and lets the instruction run again.

Three kinds of page fault
KindCauseWhat the kernel doesCost
MinorFirst touch of new memory; a page already in RAM (shared library, file cache); a write to a copy-on-write page after fork()Points the entry at a frame, zero-filling or copying if neededtypically around a microsecond
MajorThe page’s data is on disk: swapped out, or a file not yet readReads it from disk into a frame, maybe evicting another page firsta disk read: far slower
InvalidThe address is in no area the process owns, or the access is not allowed (a write to read-only code)Sends SIGSEGV; usually the process diesthe process
A page fault that has to swap
Step 1 of 8
Disk transfers 0
Page table of process A · ptr = page number
p0f1
p1—
p2f3
p3—
p4f0
p5—
p6swap s1
p7f2
Physical RAM · 4 frames (toy)
f0A p4
f1A p0
f2A p7
f3A p2
Swap on disk · 4 slots
s0–
s1A p6
s2–
s3–
  • being changed
  • looked up
  • just written
  • access succeeds
  • free frame

The CPU is stopped on the load from 0x6010. Entry 6 says page 6 is not present; the kernel noted it is in swap slot s1. All 4 frames of RAM are in use.

process A running

06 Count page faults yourself

This script reserves 100 MiB, then touches one byte in each page. Reserving costs no RAM; each first touch is a minor fault in which the kernel hands the process a zeroed frame.

touch.py
import mmap
import resource
def faults():
r = resource.getrusage(resource.RUSAGE_SELF)
return r.ru_minflt, r.ru_majflt
PAGE = mmap.PAGESIZE
pages = 25_600 # 100 MiB in 4 KiB pages
buf = mmap.mmap(-1, pages * PAGE) # reserved, but no RAM used yet
minor0, major0 = faults()
for i in range(0, pages * PAGE, PAGE):
buf[i] = 1 # touch one byte in each page
minor1, major1 = faults()

A real run in a Linux container (python:3.12-slim) prints one fault per page:

Text
page size: 4096
minor faults: 25600
major faults: 0

On a Mac with Apple silicon the same script reports a page size of 16384, because macOS uses 16 KiB pages there. On a Linux machine that backs this memory with transparent huge pages, you can see far fewer faults, since one fault maps a whole 2 MiB. Other ways to look on Linux:

Shell
getconf PAGESIZE # 4096 on most x86-64 Linux
ps -o pid,min_flt,maj_flt,rss,vsz -p 4242 # faults so far, resident and virtual size (KiB)
grep -E "VmSize|VmRSS" /proc/4242/status
vmstat 1 # si / so columns: KiB swapped in and out per second

07 Swapping, and when it turns into thrashing

When RAM runs short, the kernel frees frames. Clean pages backed by a file, such as program code, are simply dropped and read again later. Dirty anonymous pages, such as your heap, can only go to swap. Pages that have not been used lately go first, judged from the accessed bit the MMU sets in each page table entry.

RAMAbout 100 nsA typical main-memory access.
SSDTens to hundreds of µsHundreds to thousands of times slower than RAM.
Spinning diskAround 10 msAbout a hundred thousand times slower than RAM.

Swapping out pages nobody uses is harmless. Trouble starts when the pages a program uses all the time, its working set, no longer fit in RAM. Every eviction throws out a page that is needed again a moment later, so the machine spends its time moving pages instead of running code. This is thrashing: the disk is busy, the CPU is idle, and everything slows to a crawl. With no swap, or swap full, Linux’s OOM killer picks a process and sends it SIGKILL instead.

08 When it bites

VSZ 8.1g RSS 300mVirtual size is not memory useReserved address space costs nothing until it is touched. Watch RSS, the frames actually held, and remember it counts shared pages in every process that maps them.
malloc() succeededAllocation succeeds, then the OOM killer strikesBy default Linux lets programs reserve more than RAM plus swap could back, and only finds out at first touch that there is no frame left. The process that dies may not be the one that asked.
fork() + writesCopy-on-write is not free foreverAfter fork(), parent and child share frames until one of them writes. A Redis snapshot forks and keeps serving; under heavy writes, each written page is copied and memory use can climb towards double.
memory.max = 512MContainers hit their own limit firstA cgroup memory limit makes the kernel reclaim and then OOM-kill inside the container, even when the host has free RAM.
random reads over 64 GBTLB misses on huge working setsRandom access over many gigabytes misses the TLB on almost every access. Huge pages can help a lot; transparent huge pages can also add latency spikes while the kernel assembles them, which is why some databases recommend turning them off.

On a latency-sensitive server, a little swapping looks harmless on a dashboard, but each major fault stalls a request for a disk read. Watch the si/so columns of vmstat and the major-fault count, not just free memory.

09 Check yourself

Question

With 4 KiB pages, a program reads 0x7F3A2C10 and then 0x7F3A2FF0. What happens on the second read?

Question

A program mmaps 1 GiB and writes to only the first 10 MiB. Roughly how much RAM does it use for that mapping?

Question

A server’s working set grows from 6 GB to 9 GB on a machine with 8 GB of RAM and plenty of swap. What do you expect?

10 Practise this

Was this tutorial useful?Your vote tells us what to improve next.
Spotted a mistake, or something unclear?