FullStack AI Hub
Studio
lesson depth
Mastery
not started · 0%

Virtual Memory & Paging Mechanics

Page tables, TLB cache hits, page faults (major/minor), and mmap() memory mapping.

Freshness: current•15 min read•Computer Science and Programming

Key Learning Outcomes

  • ✓Analyze virtual memory allocation and page table translation
  • ✓Optimize file I/O performance using mmap() memory mapping
Full Technical Reference Document

Mental model

Linux gives every process its own isolated contiguous Virtual Address Space cleanly mapped dynamically onto fragmented physical DRAM frames (typically 4 KiB pages) through hierarchical kernel Page Tables. At runtime, CPU MMU (Memory Management Unit) hardware translates virtual pointers cleanly using a tiny ultra-fast on-die TLB (Translation Lookaside Buffer) cache—falling back onto multi-step DRAM walks on TLB misses or kernel Page Faults when pages aren't mapped yet cleanly.

Process dereferences Virtual Pointer
CPU checks hardware TLB cache
TLB Miss -> MMU 4/5-level table walk
Not mapped -> Kernel Page Fault trap
Minor (RAM hit) vs Major (Disk/Swap I/O)
Conceptual teaching model synthesized from:Linux Kernel Kernel.org Official Architecture & Systems DocumentationSite Reliability Engineering

Learning outcomes

  • Trace virtual-to-physical translation steps across TLB cache lookups, multi-level x86-64/ARM64 page-table walks, and demand-zero allocation.
  • Distinguish fast in-memory Minor Page Faults (demand zero, CoW, page-cache hit) cleanly from disk-stalling Major Page Faults (swap / uncached mmap read).
  • Optimize multi-gigabyte LLM weight loading (safetensors / GGUF) and DB engines cleanly using mmap(), madvise(), and 2 MiB HugePages (THP) cleanly avoiding TLB thrashing!

Theory

Allocating malloc(10 * 1024 * 1024 * 1024) (10 GB) on Linux succeeds virtually instantaneously (O(1)) cleanly without reserving 10 GB of physical DRAM immediately! Because the kernel assigns virtual VMA regions (demand paging) and wires actual physical 4 KiB frames solely cleanly on first byte access:

Paging Event / OptimizationHardware / Kernel CostPhysical I/O Involved?Crucial Engineering Rule
TLB Cache Hit (~0.5–1 ns)Instant hardware translation inside CPU L1 TLBNoneKeep working-set pages packed cleanly or use larger page sizes (HugePages)
TLB Miss -> 4-Level Walk (~10–50 ns)CPU walks PGD -> P4D -> PUD -> PMD -> PTE in RAM (4+ extra mem fetches per pointer!)NoneLarge multi-GB pointer-chasing DBs (HNSW, Postgres) lose 5–15% throughput on 4 KiB TLB thrashing unless 2 MiB HugePages tune
Minor Page Fault (~1–3 us)Kernel trap wiring PTE onto already-present RAM (first zeroed write or Page Cache map!)Zero disk I/OPre-fault critical low-latency RAM buffers cleanly (memset at startup / mlock)
Major Page Fault (~0.1–20+ ms)Thread freezes synchronously waiting cleanly on NVMe SSD / network / swap read!Full slow disk I/OSpiking major faults (sar -B / ps) signals severe RAM pressure cleanly!

Notice how AI inference tools like llama.cpp and safetensors exploit mmap() cleanly: mapping a 40 GB model file straight into virtual address space skips double buffering through user-space read() buffers completely (zero-copy reads cleanly out of Linux Kernel Page Cache) AND lets multiple containers cleanly share one physical read-only weights copy in RAM!

c
#define _GNU_SOURCE
#include <fcntl.h>
#include <stdio.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <unistd.h>
​
int inspect_weights_header_mmap(const char *weights_path) {
int fd = open(weights_path, O_RDONLY);
if (fd < 0) return -1;
​
struct stat st;
if (fstat(fd, &st) < 0 || st.st_size < 16) { close(fd); return -1; }
​
/* Zero-copy mapping directly into virtual memory backed by kernel Page Cache */
char *mapped = mmap(NULL, (size_t)st.st_size, PROT_READ, MAP_SHARED, fd, 0);
close(fd); /* Safe to close fd immediately once mmap establishes PTE backing */
if (mapped == MAP_FAILED) return -1;
​
/* Hint kernel sequential readahead + HugePages (if available) to minimize major stalls & TLB misses */
(void)madvise(mapped, (size_t)st.st_size, MADV_SEQUENTIAL);
printf("Mapped %ld bytes cleanly via kernel Page Cache; magic=0x%02x\n",
(long)st.st_size, (unsigned char)mapped[0]);
​
munmap(mapped, (size_t)st.st_size);
return 0;
}

Trade-offs

Using mmap() with kernel page cache and madvise(MADV_WILLNEED / MADV_SEQUENTIAL) cuts RAM duplication cleanly across multi-worker model weights and lowers startup latency dramatically (loading pages strictly on demand), yet shifts unpredictable disk major page fault stalls directly into synchronous query threads whenever container memory limits force kernel page-cache eviction silently (making async explicit O_DIRECT + pre-allocated user ring buffers superior inside strict database buffer managers like Postgres Shared Buffers / RocksDB). Meanwhile, 2 MiB Transparent HugePages (THP = madvise) cuts TLB misses 512x on big HNSW vector indexes while setting always risks background compaction stalls inside tiny latency-sensitive Redis workloads (where madvise is ideal cleanly!).

Failure modes and misconceptions

  • Counting VIRT (VSZ) Instead of RSS / PSS in Kubernetes: A Java or Go or mmap'd Python process mapping 64 GB virtual weights may hold strictly 4 GB actual physical RSS pages (and shared cleanly via PSS); killing pods on VSZ triggers false OOM alerts!
  • TLB Thrashing on 100 GB Dense Vector Graph Traversals: Navigating random graph hops across millions of tiny 4 KiB HNSW pages burns 10–25% CPU solely on MMU walks unless huge pages (2 MiB) cover the index arena cleanly.
  • Latency Jitter on Cold mmap First Request (Warmup Miss): Returning ready immediately cleanly after calling mmap() shifts multi-second disk major faults straight onto the very first customer request unless pre-faulted (MAP_POPULATE / sequential touch warmup).
  • Silent SIGBUS Crashes on Truncated mmap Files: Modifying or truncating a backing file externally while mapped triggers abrupt SIGBUS process termination cleanly on next touch.

Decision scenario

A containerized local-inference service serves a 32 GB GGUF checkpoint via mmap() inside a 40 GB cgroup pod alongside another container loading datasets, suffering sudden 12-second freezes during random bursts and 15% high CPU kernel walk overhead inside HNSW vector lookup! Add madvise(MADV_WILLNEED) warmup cleanly before passing readiness probes, separate vector memory with MADV_HUGEPAGE, and verify major faults == 0 under pinned container headroom cleanly.

Reflect before revealing the guide

Prerequisites & Related Concepts (2)

Private notes

0 words
Recommended Free Track
Free · Verifiable Credential

FS-102LLM Systems Foundations

Build a connected mental model from tokens through retrieval evaluation security and operations.

24 concepts~18h self-paced
Start Free Course
Weekly Engineering Dispatch

Get the weekly systems teardown

One technical note per week covering inference bottlenecks, retrieval harnesses, and commit-pinned teardowns.

Next