Virtual Memory & Paging
Every address your program uses, from a pointer in C to the location of a Python object, is a virtual address. The CPU's memory management unit (MMU) translates it to a physical address in RAM on every single access, using tables that the kernel builds for each process. Linux and Windows both rely on this hardware mechanism, called paging, and it gives them isolation, lazy allocation, shared libraries, copy-on-write and the ability to use more memory than the machine has.
Pages and frames
Virtual memory is cut into fixed-size pages, physical memory into frames of the same size. On x86-64 and on most ARM64 systems the base size is 4 KiB (Apple Silicon Macs use 16 KiB). A page table maps each virtual page number to a frame number plus a few permission bits:
virtual address (process A) page table of A physical RAM
+------------------+------------+ +------+-------+-----+ +---------+
| page number (VPN)| offset | --> | VPN | frame | bits| --> | frame 0 |
+------------------+------------+ | 0 | 7 | R-X | | frame 1 |
| 1 | 3 | RW- | | ... |
offset is copied unchanged | 2 | - | not present | frame 7 |
+------+-------+-----+ +---------+The low 12 bits of an address (212 = 4096) are the offset inside the page and are never translated; only the page number is looked up. Each entry also carries flags: present, writable, user-accessible, no-execute (NX), accessed and dirty. The kernel uses the last two to decide which pages to evict (see Page Replacement).
You can ask Linux for its page size with getconf. The last line checks that /proc/meminfo reports a huge-page
size (huge pages are explained below):
echo "base page size: $(getconf PAGESIZE) bytes"
echo "offset bits: $(( $(getconf PAGESIZE) == 4096 ? 12 : 0 ))"
grep -o '^Hugepagesize' /proc/meminfobase page size: 4096 bytes
offset bits: 12
Hugepagesize
On Windows, GetSystemInfo reports the same 4 KiB page size, plus a 64 KiB allocation granularity: every
VirtualAlloc reservation starts on a 64 KiB boundary, a Windows-specific detail.
A tiny MMU in Python
This simulation translates virtual addresses for a process with 4 KiB pages and a single-level page table. A missing entry is a page fault:
PAGE = 4096
page_table = {0: (5, "r-x"), 1: (9, "rw-"), 2: (2, "rw-")} # vpn -> (frame, perms)
def translate(vaddr, access="r"):
vpn, offset = divmod(vaddr, PAGE)
entry = page_table.get(vpn)
if entry is None:
return f"0x{vaddr:05x} vpn={vpn} offset=0x{offset:03x} -> PAGE FAULT (not present)"
frame, perms = entry
if access not in perms:
return f"0x{vaddr:05x} vpn={vpn} offset=0x{offset:03x} -> PROTECTION FAULT ({access} on {perms})"
return f"0x{vaddr:05x} vpn={vpn} offset=0x{offset:03x} -> frame {frame} -> phys 0x{frame * PAGE + offset:05x}"
print(translate(0x00123))
print(translate(0x01ff0, "w"))
print(translate(0x02004))
print(translate(0x00010, "w"))
print(translate(0x07000))0x00123 vpn=0 offset=0x123 -> frame 5 -> phys 0x05123
0x01ff0 vpn=1 offset=0xff0 -> frame 9 -> phys 0x09ff0
0x02004 vpn=2 offset=0x004 -> frame 2 -> phys 0x02004
0x00010 vpn=0 offset=0x010 -> PROTECTION FAULT (w on r-x)
0x07000 vpn=7 offset=0x000 -> PAGE FAULT (not present)
The protection fault is what happens when buggy code writes to its own machine code: Linux delivers SIGSEGV
("Segmentation fault"), Windows raises STATUS_ACCESS_VIOLATION (exception code 0xC0000005).
Multi-level page tables
A flat table for a 48-bit address space would need 236 entries per process, which is far too big. x86-64 therefore uses a 4-level tree (5 levels on newer CPUs with 57-bit addresses). Each level is one 4 KiB page holding 512 entries of 8 bytes, so each level consumes 9 bits of the address:
47 39 38 30 29 21 20 12 11 0
+-----------+-----------+-----------+-----------+---------------+
| PML4 (9) | PDPT (9) | PD (9) | PT (9) | offset (12) |
+-----------+-----------+-----------+-----------+---------------+
| | | |
CR3 -> PML4 -> PDPT ------> PD -------> PT -------> frame + offsetTables for unused regions simply don't exist, so a process with a few megabytes of memory needs only a handful of table pages. The register CR3 points at the top-level table; switching processes means loading a new CR3. Linux calls the levels PGD, PUD, PMD and PTE; Windows calls them PXE, PPE, PDE and PTE, but the hardware format is the same because it is defined by the CPU.
def split(vaddr):
names = ["PML4", "PDPT", "PD", "PT"]
parts = {n: (vaddr >> shift) & 0x1FF for n, shift in zip(names, (39, 30, 21, 12))}
parts["offset"] = vaddr & 0xFFF
return parts
for addr in (0x0000_7FFF_FFFF_E010, 0x0000_5555_5555_4123, 0x0000_0000_0040_1000):
p = split(addr)
print(f"0x{addr:016x}: " + " ".join(f"{k}={v}" for k, v in p.items()))
# how much memory do the page tables of a 1 GiB contiguous region need?
pages = (1 << 30) // 4096
print(f"1 GiB = {pages} pages -> {pages // 512} PT pages + 1 PD + 1 PDPT + 1 PML4 "
f"= {(pages // 512 + 3) * 4} KiB of tables")0x00007fffffffe010: PML4=255 PDPT=511 PD=511 PT=510 offset=16
0x0000555555554123: PML4=170 PDPT=341 PD=170 PT=340 offset=291
0x0000000000401000: PML4=0 PDPT=0 PD=2 PT=1 offset=0
1 GiB = 262144 pages -> 512 PT pages + 1 PD + 1 PDPT + 1 PML4 = 2060 KiB of tables
The first address is near the top of user space (where the main stack lives); its PML4 index 255 is the last entry of the user half. Entries 256–511 belong to the kernel half, which is mapped into every process but marked supervisor-only (see User Mode & Kernel Mode).
The TLB: caching translations
Walking four tables in memory for every access would make programs several times slower. The CPU keeps recent translations in the translation lookaside buffer (TLB), a small cache (typically 64 entries at L1 and around 1,500–2,000 at L2). A TLB hit costs nothing extra; a miss costs a page-table walk.
from collections import OrderedDict
def run(trace, tlb_size):
tlb = OrderedDict() # vpn -> frame, kept in LRU order
hits = 0
for vaddr in trace:
vpn = vaddr >> 12
if vpn in tlb:
hits += 1
tlb.move_to_end(vpn)
else:
if len(tlb) == tlb_size:
tlb.popitem(last=False) # evict least recently used
tlb[vpn] = vpn + 100 # pretend the walk found this frame
return hits
# walk an array of 8-byte items twice: 4 pages, 512 items per page
sequential = [0x10000 + i * 8 for i in range(2048)] * 2
# jump one page per access over 16 pages, 256 times
strided = [0x10000 + (i % 16) * 4096 for i in range(4096)]
for name, trace in (("sequential", sequential), ("page-strided", strided)):
for size in (4, 16):
h = run(trace, size)
print(f"{name:<12} TLB={size:>2}: {h}/{len(trace)} hits ({100 * h / len(trace):.1f}%)")sequential TLB= 4: 4092/4096 hits (99.9%)
sequential TLB=16: 4092/4096 hits (99.9%)
page-strided TLB= 4: 0/4096 hits (0.0%)
page-strided TLB=16: 4080/4096 hits (99.6%)
Sequential access touches each page hundreds of times in a row, so almost everything hits. A pattern that jumps between more pages than the TLB holds misses on every access, which is why data layout matters for performance.
Two techniques reduce TLB pressure on both systems:
- Huge pages (2 MiB or 1 GiB): one TLB entry covers 512× more memory. Linux has transparent huge pages (THP)
and
hugetlbfs; Windows calls them large pages (MEM_LARGE_PAGES, needs the "Lock pages in memory" privilege). - PCID / ASID tags let TLB entries of several processes coexist, so a context switch doesn't have to flush the whole TLB.
Page faults are normal
A page fault is not an error, it is how the OS fills memory lazily:
| Fault kind | Cause | Who handles it |
|---|---|---|
| Minor (Linux) / soft (Windows) | Page is in RAM already (page cache, standby list, shared library) but not mapped yet | Kernel maps it, no disk I/O |
| Major (Linux) / hard (Windows) | Page must be read from disk (file or swap/page file) | Kernel starts I/O, thread sleeps |
| Copy-on-write | Write to a shared private page (after fork, or to a DLL's data) |
Kernel copies the page, then maps the copy |
| Invalid | Address not mapped or permission violated | SIGSEGV / access violation |
ps can show both counters per process. Their values change from run to run, so this example prints only the
column headers and checks that the counters are numbers:
ps -o min_flt,maj_flt -p $ | head -n 1
ps -o min_flt=,maj_flt= -p $ | grep -Eq '^ *[0-9]+ +[0-9]+