TExcelTAD
Home › Operating Systems: Linux & Windows › Virtual Memory & Paging

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:

text
  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):

bash · try it yourself
echo "base page size: $(getconf PAGESIZE) bytes"
echo "offset bits:    $(( $(getconf PAGESIZE) == 4096 ? 12 : 0 ))"
grep -o '^Hugepagesize' /proc/meminfo
base 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:

python · try it yourself
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:

text
 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 + offset

Tables 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.

python · try it yourself
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.

python · try it yourself
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:

bash · try it yourself
ps -o min_flt,maj_flt -p $ | head -n 1
ps -o min_flt=,maj_flt= -p $ | grep -Eq '^ *[0-9]+ +[0-9]+
  

 && echo "both counters are numeric"
 MINFL  MAJFL
both counters are numeric

On a real machine, ps -o pid,min_flt,maj_flt,cmd -p <pid> or /usr/bin/time -v show the numbers. Windows exposes them per process as PageFaultCount (soft and hard combined) and system-wide in Performance Monitor (sample output):

powershell
PS C:\Users\ada> Get-CimInstance Win32_Process -Filter "Name='msedge.exe'" |
>>   Select-Object -First 2 ProcessId, PageFaults, WorkingSetSize

ProcessId PageFaults WorkingSetSize
--------- ---------- --------------
    10412    1834567      189304832
    11288      48211       43122688

PS C:\Users\ada> (Get-Counter '\Memory\Page Faults/sec').CounterSamples.CookedValue
2312.48

How Linux and Windows organise an address space

Linux Windows
Per-process description mm_struct with a tree of VMAs (vm_area_struct) VAD tree (Virtual Address Descriptors)
Map a file / shared memory mmap CreateFileMapping + MapViewOfFile (section objects)
Reserve / commit one mmap (overcommit) VirtualAlloc(MEM_RESERVE) then MEM_COMMIT
Change protection mprotect VirtualProtect
Inspect /proc/<pid>/maps, pmap Sysinternals VMMap, !address in WinDbg
User space size (x86-64) 128 TiB 128 TiB

Learn more: Memory Management · Page Replacement · Swap & the Page File

Go further: The Process Address Space shows why the layout of the stack, heap and libraries matters for memory-safety bugs and ASLR.

Test yourself

With 4 KiB pages, how many bits of a virtual address are the page offset?

  1. 9
  2. 12
  3. 21
  4. 48

What does the TLB store?

  1. Recently used file blocks
  2. Recent virtual-to-physical page translations
  3. The list of free physical frames
  4. Pages that were swapped out

A process touches a page of a shared library that another process already loaded into RAM. What kind of fault occurs?

  1. A major (hard) fault
  2. A minor (soft) fault
  3. A protection fault
  4. No fault can occur for libraries