Skip to content
LeetQuant
QD05 Operating Systems and Computer Architecture

QD05 · Operating Systems and Computer Architecture · Lesson 3 of 6

Virtual Memory

Pages and multi-level page tables, the TLB and what a miss costs, minor and major page faults, mmap, huge pages and memory overcommit, with the latency consequences for trading systems.

17 min

The idea

Every process sees its own private, contiguous range of virtual addresses. The hardware's memory management unit (MMU) translates each virtual address to a physical one on every load and store, using tables the kernel maintains. This gives:

  • isolation: a process cannot even name another process's memory;
  • flexibility: physical memory can be scattered, shared (the same library mapped into many processes), lazily allocated, or backed by a file;
  • overcommit: processes can reserve more virtual memory than there is physical memory.

Translation works at the granularity of a page: 4 KiB on x86-64 Linux by default (Apple silicon uses 16 KiB). The low bits of an address are the offset inside the page and pass through unchanged; the high bits are the virtual page number, which the MMU maps to a physical frame.

Multi-level page tables

A flat table for a 48-bit address space with 4 KiB pages would need 2362^{36} entries per process. Instead x86-64 uses a four-level radix tree. Each table is one 4 KiB page holding 512 eight-byte entries, so each level consumes 9 bits of the address:

48=9⏟PML4+9⏟PDPT+9⏟PD+9⏟PT+12⏟offset48 = \underbrace{9}_{\text{PML4}} + \underbrace{9}_{\text{PDPT}} + \underbrace{9}_{\text{PD}} + \underbrace{9}_{\text{PT}} + \underbrace{12}_{\text{offset}}

A register (CR3) points to the top table. The hardware page walk reads one entry per level. Unused regions need no lower-level tables, so a sparse address space is cheap. (Newer CPUs support five levels and 57-bit addresses.)

Each page-table entry holds the physical frame number plus flag bits: present, writable, user-accessible, accessed, dirty and no-execute. Copy-on-write is implemented by clearing the writable bit; demand paging by clearing the present bit.

Worked example

walking an address

Split the x86-64 virtual address 0x7f3a12345678 into its four table indices and page offset (4 KiB pages). How much page-table memory does it take to map 1 GiB of memory with 4 KiB pages?

Show solution

Take bit fields from the bottom: offset = bits 0–11, PT index = bits 12–20, PD = 21–29, PDPT = 30–38, PML4 = 39–47.

  • offset: 0x7f3a12345678 & 0xfff = 0x678 = 1656
  • PT index: (va >> 12) & 0x1ff = 325
  • PD index: (va >> 21) & 0x1ff = 145
  • PDPT index: (va >> 30) & 0x1ff = 232
  • PML4 index: (va >> 39) & 0x1ff = 254

So the walk reads entry 254 of the top table, entry 232 of the next, entry 145, then entry 325 of the last-level table, whose frame number is combined with offset 1656.

Mapping 1 GiB takes 230/212=262,1442^{30} / 2^{12} = 262{,}144 leaf entries of 8 bytes, which is 2 MiB of last-level tables (512 table pages), plus a single page at each level above. With 2 MiB pages the walk stops one level earlier, the 2 MiB of leaf tables disappear, and 1 GiB needs just 512 entries.

The TLB

Walking four levels on every access would be ruinous, so the MMU caches recent translations in the translation lookaside buffer (TLB). A recent x86-64 server core has, roughly, 64 first-level data-TLB entries and 1,500 to 2,000 second-level entries for 4 KiB pages, with separate or shared entries for huge pages.

  • A TLB hit adds essentially nothing.
  • A TLB miss triggers a hardware page walk. If the page-table entries are in the data caches it costs tens of cycles; if they must come from DRAM, a few hundred.

The useful quantity is TLB reach: entries times page size. With 1,536 second-level entries, reach is 1,536×4 KiB=61{,}536 \times 4\ \text{KiB} = 6 MiB. A program that touches a few gigabytes at random therefore misses the TLB on almost every access, on top of missing the data caches.

When the kernel changes a mapping (munmap, mprotect, page migration) it must invalidate stale TLB entries on every core running that process, which costs an inter-processor interrupt called a TLB shootdown. Frequent munmap in a multithreaded process shows up as latency spikes on other threads.

Page faults

If the walk finds an entry that is not present, or a write to a read-only page, the CPU raises a page fault and the kernel decides what to do:

  • Minor fault: the data is already in RAM or needs no I/O. The first touch of freshly allocated anonymous memory (the kernel hands out a zeroed frame), a copy-on-write copy, or a file page already in the page cache. Cost: roughly a microsecond, mostly zeroing or copying the page.
  • Major fault: the page must be read from disk, for example a file-backed page not in the page cache, or a page that was swapped out. Cost: about 100 µs on a fast SSD, milliseconds on a spinning disk.
  • Invalid access: no mapping at all, or a write to genuinely read-only memory. The kernel sends SIGSEGV.

Allocation is lazy. malloc or mmap only reserves virtual addresses; physical frames are assigned at first touch, one fault per page.

#include <cstdio>
#include <sys/mman.h>
#include <sys/resource.h>
#include <unistd.h>

long minor_faults() {
    rusage ru{};
    getrusage(RUSAGE_SELF, &ru);
    return ru.ru_minflt;
}

int main() {
    const size_t page = sysconf(_SC_PAGESIZE);
    const size_t len = 64 * 1024 * 1024;  // 64 MiB of virtual address space
    char* p = static_cast<char*>(
        mmap(nullptr, len, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0));
    if (p == MAP_FAILED) { std::perror("mmap"); return 1; }

    long before = minor_faults();
    for (size_t i = 0; i < len; i += page) p[i] = 1;   // first touch of each page
    long first = minor_faults() - before;

    before = minor_faults();
    for (size_t i = 0; i < len; i += page) p[i] = 2;   // pages are now mapped
    long second = minor_faults() - before;

    std::printf("page size %zu, pages %zu\n", page, len / page);
    std::printf("faults on first touch: %ld, on second touch: %ld\n", first, second);
    munmap(p, len);
}

On an Apple-silicon Mac (16 KiB pages) this prints page size 16384, pages 4096 and faults on first touch: 4096, on second touch: 0. On x86-64 Linux with 4 KiB pages expect 16,384 first-touch faults, or far fewer if transparent huge pages back the region. Either way the second pass faults zero times.

mmap

mmap maps a range of virtual addresses to either:

  • anonymous memory (MAP_ANONYMOUS): zero-filled, used by malloc for large allocations (glibc's default threshold is 128 KiB) and for thread stacks;
  • a file: reads fault pages in from the page cache, so the file is accessed as memory with no read() calls.

With MAP_PRIVATE writes are copy-on-write and private to the process. With MAP_SHARED writes go to the shared pages, are visible to every process mapping the same file or shared-memory object, and (for files) are eventually written back. Shared memory created with shm_open plus mmap(MAP_SHARED) is the standard way for a feed-handler process to pass data to strategy processes without system calls per message.

Huge pages

x86-64 also supports 2 MiB and 1 GiB pages. One 2 MiB TLB entry covers what 512 small-page entries would, and page walks are one level shorter. Two ways to get them on Linux:

  • Explicit huge pages (hugetlbfs, MAP_HUGETLB): reserved up front (for example via vm.nr_hugepages), never swapped, deterministic. Preferred for latency-critical systems.
  • Transparent huge pages (THP): the kernel uses 2 MiB pages automatically when an aligned region allows, either always or only where the program calls madvise(MADV_HUGEPAGE), depending on /sys/kernel/mm/transparent_hugepage/enabled. Convenient, but finding a free 2 MiB block can require compaction (moving pages around), and background collapsing by khugepaged can stall a thread for milliseconds. Many low-latency shops set THP to madvise or never.

Overcommit and the OOM killer

Because frames are assigned at first touch, Linux lets processes reserve more virtual memory than RAM plus swap. The policy is vm.overcommit_memory:

ValuePolicy
0 (default)Heuristic: refuse only obviously impossible requests
1Always allow
2Strict: total commitments are capped at swap plus overcommit_ratio per cent of RAM (or overcommit_kbytes)

The consequence: under the default, malloc rarely returns NULL. Running out of memory shows up later, when pages are touched and no frame can be found. The kernel then invokes the OOM killer, which picks a process (by memory use, adjusted by /proc/<pid>/oom_score_adj) and kills it with SIGKILL, so it cannot be caught.

What a trading system does with all this

  • Pre-fault at start-up: touch every page of every pool and buffer, or map with MAP_POPULATE, so no first-touch fault lands on the hot path.
  • Lock memory: mlockall(MCL_CURRENT | MCL_FUTURE) stops pages from being swapped or reclaimed.
  • Use explicit huge pages for large tables such as order books and instrument maps, to raise TLB reach.
  • Avoid munmap/mprotect churn at run time, which causes TLB shootdowns across cores.

Worked example

TLB reach for a large lookup table

A pricing service does random lookups into a 16 GiB table. The core has 1,536 second-level TLB entries usable by either 4 KiB or 2 MiB pages. Ignoring page-table caching, what fraction of random lookups can hit the TLB with 4 KiB pages, with 2 MiB pages, and with 1 GiB pages?

Show solution

For uniformly random lookups the best-case hit rate is TLB reach divided by table size (the TLB can hold translations for at most that much of the table).

  • 4 KiB pages: reach =1,536×4= 1{,}536 \times 4 KiB =6= 6 MiB, and 66 MiB /16/ 16 GiB =6/16,384≈0.037%= 6 / 16{,}384 \approx 0.037\%. Essentially every lookup takes a page walk.
  • 2 MiB pages: reach =1,536×2= 1{,}536 \times 2 MiB =3= 3 GiB, so up to 3/16=18.75%3/16 = 18.75\% of lookups hit, and each miss walks only three levels.
  • 1 GiB pages: 16 entries map the whole table, so after warm-up every translation hits (CPUs typically have only a few dozen 1 GiB entries, which is plenty here).

The data access is still a cache miss in all three cases; huge pages remove the extra miss for the translation. Say this distinction out loud in an interview: huge pages fix TLB misses, not data-cache misses.

Knowledge check

Why does each level of the x86-64 page table use exactly 9 bits of the virtual address?

Knowledge check

On a 16 GiB Linux machine with default overcommit and about 2 GiB free, a process calls malloc for 8 GiB and the call succeeds. What most likely happens as the process writes to all of it?

Knowledge check

A strategy's first order of the day is 40 µs slower than all later ones, although it runs identical code. Which fix addresses the most likely memory-related cause?

Key takeaways

  • Virtual addresses are translated per page (4 KiB typical on x86-64) through a four-level table of 512-entry pages: 9 + 9 + 9 + 9 + 12 bits.
  • The TLB caches translations; its reach (entries times page size) is a few megabytes with small pages. Huge pages multiply reach by 512.
  • Memory is assigned at first touch. Minor faults cost about a microsecond, major faults need I/O and cost far more.
  • Under default overcommit, failure shows up as the OOM killer, not as malloc returning NULL.
  • Latency-critical code pre-faults, locks memory, prefers explicit huge pages, and avoids mapping changes at run time.

Finished reading?

Answer the 3 knowledge checks to complete this lesson (0 done).