Virtual Memorypageframepage table entrypermissionspresent bit

Paging

Memory is managed in fixed-size pages: each virtual page maps to a physical frame through an entry carrying present, read/write/execute, dirty and accessed bits, and the "not present" state is not an error but the hook the kernel uses to allocate, share and swap lazily.

ConceptualLinux
Interview question
Progress

You have not marked these as done yet. Read on anyway if they feel familiar; come back to them if something here does not land.

The problem

A map from every byte to every byte would be larger than memory itself. What unit should the map work in, what must each entry record for the kernel to allocate lazily, share safely and reclaim intelligently, and what changes when the unit is 2 MB instead of 4 kB?

Pages and frames

The virtual address space is divided into pages and physical memory into frames of the same size — 4 kB on x86-64 and most ARM64 Linux systems, 16 kB on Apple silicon, 64 kB on some ARM server configurations. A 4 kB page means the low 12 bits of an address are the offset within the page and never translate; only the high bits (the virtual page number) are looked up. A mapping is a page-table entry (PTE) saying "virtual page N is in frame M, with these permissions". The page is the unit of everything: allocation, protection, sharing, swapping, caching. You cannot map, protect or swap half a page.

The choice of size is a trade-off with two sides. Smaller pages waste less memory at the end of each region (internal fragmentation, at most one page per mapping) and let the kernel be finer-grained about what to load and evict. Larger pages need fewer entries — a smaller table, fewer faults to cover a region, and far more memory covered by the same number of TLB entries (The TLB). 4 kB was chosen in the 1980s when RAM was measured in megabytes; it is now widely considered too small, which is why huge pages and 16 kB defaults exist.

What a page-table entry says

Conceptual

An entry is one machine word (8 bytes on 64-bit) that packs the frame number with a set of flag bits. The exact layout is per architecture, but the flags are universal because the kernel needs each of them for something specific.

The present bit is the pivot of the whole system: if it is clear, the CPU does not interpret the rest of the entry and raises a page fault instead, and the kernel is free to use the remaining bits to remember *why* — the page is on swap at this offset, or is part of a file mapping, or has never been touched. Every lazy mechanism in this module (Page Faults, Copy-on-Write, Memory Mapping, swap in Memory Pressure, Swap and the OOM Killer) is the kernel clearing this bit on purpose and handling the fault later.

The accessed and dirty bits are set by the CPU, not by the kernel, when the page is read or written. The kernel reads and clears them periodically to learn which pages are in use (the raw material for reclaim decisions) and which have been modified since they were last written to disk (a clean page can be dropped; a dirty one must be written first). The permission bits (writable, user-accessible, no-execute) turn a violation into a fault before it becomes a corruption: writing to code, executing the stack, or user code touching a kernel page all fault with the same mechanism.

Conceptual 64-bit page-table entry (bit positions follow x86-64 as an example; other ISAs differ)
bit 63     NX       no-execute: instruction fetch from this page faults
bits 52–62 (avail)  ignored by hardware; OS may use them
bits 12–51 PFN      physical frame number (frame address = PFN << 12)
bit 8      G        global: not flushed on CR3 write (kernel pages)
bit 7      PS       page size: 1 = this entry maps a 2 MB / 1 GB page directly
bit 6      D        dirty: set by CPU on write
bit 5      A        accessed: set by CPU on read or write
bit 4/3    PCD/PWT  cache policy (uncached for device memory)
bit 2      U/S      user (1) or supervisor-only (0)
bit 1      R/W      writable (1) or read-only (0)
bit 0      P        present: 0 → any access page-faults; OS owns the other bits

4 kB pages and huge pages

Linux

x86-64 can map a page at three granularities: 4 kB, 2 MB (one entry in the second-lowest table level, with the PS bit set) and 1 GB. A huge page is one PTE covering 512 or 262,144 base pages — one TLB entry, one fault to materialise, one table entry to manage. For a process with a 40 GB heap the difference is 10 million entries against 20,000, and a TLB that covers 6 MB against one that covers 3 GB.

Linux offers huge pages two ways. hugetlbfs / MAP_HUGETLB reserves them explicitly at boot or runtime (vm.nr_hugepages), guaranteed and never swapped — how PostgreSQL (huge_pages = on), Oracle and DPDK use them. Transparent huge pages (THP) let the kernel opportunistically back anonymous memory with 2 MB pages and merge 4 kB pages later with khugepaged. THP is convenient and occasionally harmful: a 2 MB page is committed the moment one byte is touched (RSS inflation for sparse allocators), finding 2 MB of contiguous free frames can require compaction (latency spikes), and a copy-on-write fault copies 2 MB instead of 4 kB (Redis’s BGSAVE problem in Copy-on-Write). always vs madvise in /sys/kernel/mm/transparent_hugepage/enabled is the switch; databases document which they want.

Apple silicon and iOS use 16 kB base pages; ARM64 Linux can be built for 4, 16 or 64 kB. Code that assumes 4096 — custom allocators, memory-mapped file offsets, JIT code buffers — breaks on those systems; always ask (sysconf(_SC_PAGESIZE), os.sysconf, mmap.PAGESIZE).

Base pages vs huge pages
4 kB page2 MB huge page
Entries for 1 GB262,144512
TLB reach with 1,536 entries6 MB3 GB
Faults to touch 1 GB262,144 (~250 ms)512 (~ms, but each zeroes 2 MB)
Internal fragmentation≤ 4 kB per region≤ 2 MB per region
Copy-on-write cost per faultCopy 4 kBCopy 2 MB
SwappableYesTHP: split first; hugetlbfs: never
Best forGeneral purpose, sparse mappingsLarge hot heaps: databases, JVMs, packet buffers

Page faults as the mechanism for laziness

Everything the kernel does "on demand" is implemented by leaving a present bit clear and catching the fault. A new mmap region has no entries at all; the first touch of each page faults, and the handler finds the region, allocates a zeroed frame, and installs the entry (What Happens When I Allocate Memory?). A mapped file’s pages fault in from the page cache or from disk (Memory Mapping). A forked child’s pages are present but read-only; a write faults and the handler copies (Copy-on-Write). A page written to swap has its entry rewritten to "not present, swap slot 4711"; touching it faults and the handler reads it back (Memory Pressure, Swap and the OOM Killer).

The fault is cheap enough to be used this way — around a microsecond when no I/O is needed — and precise enough: the CPU delivers the faulting address and whether it was a read, a write or an instruction fetch, and after the handler returns the *same instruction* re-executes as if nothing had happened. The program cannot tell that its memory was materialised, copied or fetched from disk in the middle of a load. That transparency is what makes virtual memory an abstraction rather than an API, and Page Faults follows one fault through the kernel step by step.

Key points

  • Memory is mapped, protected, shared and swapped in whole pages: 4 kB on x86-64 and most ARM64 Linux, 16 kB on Apple silicon.
  • A PTE packs the frame number with present, R/W, user/supervisor, NX, accessed and dirty bits; the CPU sets A and D, the kernel reads them.
  • Present = 0 is not an error; it is the kernel’s hook. The remaining bits then record where the page really is (swap slot, file, nowhere yet).
  • Permission bits turn writes to code, execution of data and user access to kernel memory into faults before they become corruptions.
  • Huge pages (2 MB / 1 GB) cut entries and faults by 512× and multiply TLB reach; THP is automatic and can inflate RSS and spike latency.
  • Never hard-code the page size; ask the OS.

Why does this exist?

Mechanisms are answers to constraints. Open each question before reading the answer.

▸Why fixed-size pages?

Fixed sizes make the map an array-like structure the hardware can walk, bound waste to one page per region, and let any frame back any page — no fitting, no external fragmentation.

▸Why does the CPU maintain the dirty and accessed bits?

Only the CPU sees every access. Without hardware-maintained bits the kernel would have to trap on every first access and every first write to learn what is used and what is modified — which some architectures actually did, expensively.

▸Why is 4 kB still the default if it is too small?

Compatibility: file formats, allocators, and decades of software assume it, and huge pages exist as an opt-in on top. Apple could change the default because it controls the whole stack.

▸Why can a page fault be transparent?

Because the CPU raises it before the instruction completes and re-executes the instruction afterwards. The handler changes the map, not the program state, so from the program’s side the load merely took longer.

How it fails

What the failure looks like from inside real software.
Reference · show
  • THP always on a Redis or MongoDB host: RSS 30% higher than the data, and latency spikes during compaction and fork; madvise or never fixes both.
  • A custom allocator assumes 4 kB pages and misaligns mmap offsets on an Apple silicon build: EINVAL from mmap, or silent overlap.
  • A JIT writes machine code into a read/write page and jumps to it: SIGSEGV with the NX bit set; the fix is mprotect(PROT_READ|PROT_EXEC) after writing (W^X).
  • hugetlbfs pages reserved at boot but unused by the database due to a misconfiguration: 8 GB of RAM invisible to everything else, "missing" from free.
  • Dirty pages of a huge mapped file accumulate faster than writeback drains them: dirty_ratio reached, every writer stalls in the kernel.

Check yourself

Answer out loud or on paper first, then compare. These come from the interview questions linked to this lesson.

  1. Why does virtual memory exist? List the problems we would have without it, and then the costs it introduces.

    Show a strong answer

    Without it, every process would address physical RAM directly. Then: a bug in one program could overwrite another’s memory or the kernel’s (no isolation); every program would have to be linked for the exact physical addresses it will get (no relocation); two programs could not share one copy of libc; a program needing 1 GB would need 1 GB of *contiguous* free RAM (fragmentation); and a program could not ask for memory it might not use. Virtual memory fixes all of these with one indirection: each process sees its own private address space, and the hardware translates (Why Virtual Memory?).

    The mechanism is paging: the address space is split into fixed pages (4 KB on x86-64 and most Linux builds; 16 KB on Apple silicon), physical memory into frames of the same size, and a per-process page table maps page → frame with permission bits (read, write, execute, user/kernel). The MMU consults it on every access. A page with no valid mapping raises a page fault, which is not an error but the kernel’s hook: it can lazily allocate a zero page, load a file page, copy a copy-on-write page, or — if the access really is invalid — deliver SIGSEGV (Paging, Page Faults).

    The costs: every memory access now needs a translation, which would double or quadruple memory traffic if done by walking the table each time — so the CPU caches translations in the TLB, and TLB misses are a real cost for large working sets (The TLB). Page tables themselves consume memory (a 4-level x86-64 table is a few MB per GB of mapped memory). And faults, when they hit disk, cost ~100 µs on SSD — the "swap" case beginners lead with is the pathological end of a spectrum whose normal end is free.

    Production consequences follow directly. Virtual size (VSZ) is mostly reservations and means little; RSS is the pages actually resident. malloc(1 GB) succeeds and costs nothing until touched (Linux overcommit), so a process can be killed by the OOM killer *later*, when it touches pages it was promised. Shared libraries and the page cache are the same frames mapped into many processes, which is why summed RSS exceeds RAM.

    Full interview question, with follow-ups and red flags →
  2. What is a page fault? Are all page faults bad? How would you find out whether a slow process is suffering from them?

    Show a strong answer

    A page fault is the CPU telling the kernel "I could not translate this address" — either no page-table entry exists or the permission bits forbid the access. Control traps into the kernel’s fault handler, which looks at the process’s mapping list to decide what the access *should* mean (Page Faults).

    Three outcomes. A minor fault: the page is legitimately part of the address space but not yet mapped — the first touch of freshly malloced memory (the kernel hands out a zeroed frame), a page of a file that is already in the page cache, a shared-library page another process already loaded, or a copy-on-write page that must now be duplicated. Cost: a microsecond or a few. A major fault: the data is not in RAM and must come from storage — a file page not cached, or a page that was swapped out. Cost: ~100 µs on an SSD, ~10 ms on a spinning disk, during which the thread is blocked. An invalid fault: the address is not mapped at all or the access violates permissions (writing to code, dereferencing null) — the kernel delivers SIGSEGV.

    So no, faults are not bad; they are the mechanism of demand paging. malloc(1 GB) returns instantly because nothing is mapped; the process then takes 262,144 minor faults as it touches the pages. Program start-up is a burst of faults as code pages are mapped from the executable. What *is* bad is a stream of major faults — that means the working set does not fit and the process is waiting on disk (Memory Pressure, Swap and the OOM Killer).

    To tell: ps -o min_flt,maj_flt, /usr/bin/time -v (major/minor faults), perf stat -e page-faults,major-faults -p <pid>, sar -B for system-wide majflt/s (label: Linux). A process that is slow with high majflt/s and wa in top is memory-bound, not CPU-bound; a process taking millions of minor faults per second is allocating and freeing pages in a churn (an allocator returning memory to the kernel too eagerly, or huge fresh buffers per request).

    Full interview question, with follow-ups and red flags →
  3. Why can a process with 40 GB virtual size run on a 16 GB machine?

    Show a strong answer

    Most of the address space is reserved, unmapped or untouched; only resident pages need RAM.

    Full interview question, with follow-ups and red flags →