Paging & Page Tables

Understanding how paging divides memory into fixed-size pages, how page tables track virtual-to-physical mappings, and how the TLB accelerates address translation.

published: reading time: 31 min read author: Geek Workbench updated: November 24, 2026
Quick Summary

Understanding how paging divides memory into fixed-size pages, how page tables track virtual-to-physical mappings, and how the TLB accelerates address translation.

Paging & Page Tables

Paging divides a process’s virtual address space into fixed-size pages and maps them to physical-memory frames. A process can use a contiguous range of virtual addresses even when its pages occupy separate physical frames.

The operating system builds page tables, and the processor’s memory-management unit (MMU) uses them to translate virtual addresses and enforce access permissions. The details depend on the CPU architecture and the paging mode enabled by the operating system.

Introduction

Programs use virtual addresses. The address range available to a process depends on the CPU and operating-system configuration; physical RAM is shared among processes and does not need to be contiguous for a process’s virtual range to appear contiguous.

This article uses a specific x86-64 configuration to walk through address translation, then separates the hardware translation path from page faults and operating-system demand allocation.

When to Use / When Not to Use

Paging is a fundamental OS mechanism — it is always in use. You do not choose to use it; your hardware and OS cooperate to apply it whether you want it or not. However, you make choices about how your application interacts with it.

When understanding paging helps you:

  • Allocating large buffers with malloc — understanding page boundaries explains allocator alignment behavior
  • Memory-mapping files with mmap — understanding page faults reveals why first access to mmap’d regions can be slow
  • Debugging OOM kills or excessive page fault rates
  • Writing lock-free data structures where cache line alignment and false sharing are concerns
  • Database optimization (PostgreSQL huge pages, InnoDB buffer pool pages)

When you can ignore it:

  • Purely functional, managed-language applications where the runtime handles all memory
  • Applications where memory access patterns are uniformly distributed (no concentrated hot spots)

Architecture and translation model

The diagram below shows a classic 32-bit, non-PAE x86 paging model with 4 KiB pages. It splits a 32-bit address into a 10-bit page-directory index, a 10-bit page-table index, and a 12-bit offset. It illustrates the lookup idea; the x86-64 configuration used later has four levels.

flowchart TD
    LA["Virtual address (32-bit)<br/>31..22: 10-bit PD index<br/>21..12: 10-bit PT index<br/>11..0: 12-bit offset"]
    PD["Page Directory<br/>1024 entries"]
    PT["Page Table<br/>1024 entries"]
    PDE["Directory entry<br/>present and access bits"]
    PTE["Table entry<br/>present, access bits, frame"]
    PF["Physical frame"]
    PA["Physical address<br/>frame base + offset"]
    DRAM["Physical memory"]

    LA -->|"CR3 identifies directory"| PD
    PD -->|"PD index"| PDE
    PDE -->|"points to table"| PT
    PT -->|"PT index"| PTE
    PTE --> PF
    PF -->|"append 12-bit offset"| PA
    PA --> DRAM

The x86-64 example in this article uses four-level paging: PML4 (Page Map Level 4) → PDPT (Page Directory Pointer Table) → PD (Page Directory) → PT (Page Table). CR3 identifies the root table. x86-64 also supports five-level paging, and the CPU and operating-system configuration determine which mode is active.

Core Concepts

Pages and Frames

A page is a fixed-size block in a virtual address space. A frame is a same-size block in physical memory. Page sizes depend on the architecture and configuration. The examples here use 4 KiB base pages on x86-64; other architectures can support different base page sizes.

A page-table entry may describe a present page, a valid page that is not currently resident, or an address/access that is invalid. A valid nonresident page can cause a recoverable page fault when accessed. An unmapped or disallowed access can instead cause the operating system to report an error to the process.

The OS maintains a page-table hierarchy for each process. Leaf entries map virtual pages to physical frames; non-present entries can also hold OS-specific information such as a swap location.

Multi-Level Page Tables

A flat page table for a full 32-bit address space with 4 KiB pages would need 2^20 entries. At four bytes per entry, that is 4 MiB for one address space. This is a 32-bit example; entry sizes and layouts vary by architecture.

Multi-level tables allocate lower-level table pages only for portions of the address space that are mapped. That keeps sparse address spaces from needing one dense array of entries.

For the x86-64 example, assume four-level paging, 4 KiB base pages, 48-bit canonical virtual addresses, and 512 entries in each 4 KiB table page. Each entry is 8 bytes.

  • PML4: 512 entries; CR3 identifies the root table.
  • PDPT: 512 entries per PML4 entry; points to page directories.
  • PD: 512 entries per PDPT entry; points to page tables or maps a 2 MiB page when supported and configured.
  • PT: 512 entries per page directory entry; leaf entries map 4 KiB pages.

Bits 47:39 select the PML4 entry, bits 38:30 the PDPT entry, bits 29:21 the PD entry, bits 20:12 the PT entry, and bits 11:0 the byte offset. Bits 63:48 repeat bit 47 for a canonical address. The OS controls which canonical ranges are available to user space. Five-level paging adds a PML5 index and can expose a wider address range.

If four mapped pages share the same path through the hierarchy, they can use one table page at each level. The resulting 16 KiB of table pages is only an example; actual page-table memory depends on the shape of the process’s mappings.

On x86-64, a page-directory-pointer entry can map a 1 GiB page and a page-directory entry can map a 2 MiB page when supported and configured. A PML4 entry points to the next table level; it does not map a 512 GiB page.

Worked translation: four-level x86-64

Use the declared 48-bit, four-level, 4 KiB configuration and virtual address 0x0000123456789ABC:

Field Address bits Index or value
PML4 index 47:39 0x024
PDPT index 38:30 0x0D1
PD index 29:21 0x0B3
PT index 20:12 0x189
Page offset 11:0 0xABC

The MMU uses the four indices to find the leaf entry. Suppose that entry is present and maps the virtual page to physical frame base 0x00000001234000. The physical address is the frame base plus the unchanged offset: 0x00000001234ABC. The frame mapping is illustrative; actual physical-address width and mappings depend on the machine and operating system.

Translation Lookaside Buffer (TLB)

The translation lookaside buffer (TLB) caches recent virtual-to-physical translations. On a TLB hit, the MMU can use the cached translation. On a TLB miss, hardware walks the page tables. If the entries describe a present page and the access is allowed, the processor can cache the translation and continue; a TLB miss alone is not a page fault. TLB size and lookup latency vary by CPU.

Context switches can require the operating system to invalidate translations or use address-space tags such as x86 PCIDs. The exact behavior depends on the processor and kernel; a context switch does not imply that every TLB entry is always flushed.

Page-table entry fields (x86-64)

This simplified table applies to common x86-64 paging entries. Some bits change meaning by entry level, and the usable physical-address width depends on the processor.

Field Meaning
Present (bit 0) Entry is valid for a present mapping or next-level table
Read/write (bit 1) Controls write access
User/supervisor (bit 2) Controls user-mode access
Accessed (bit 5) Hardware records access to the entry
Dirty (bit 6) Hardware records writes to a mapped page
Page size (bit 7 in a PDPT or PD entry) Maps a 1 GiB or 2 MiB page; in a leaf PTE, this bit has a different use
Address field Identifies the next-level table or mapped frame, within the processor’s physical-address width

Consult the processor manual for the complete format, including reserved bits and feature-dependent fields.

Page Fault Handling

A page fault is a processor exception raised when the MMU cannot complete an address translation or the requested access fails a permission check. It is not automatically a program error. A TLB miss followed by a successful page-table walk does not raise a page fault.

On x86, the faulting virtual address is recorded in CR2. The operating system checks the address and access type, then decides whether it can resolve the fault:

  1. A first access to a valid anonymous page can allocate a zero-filled frame.
  2. A file-backed page may already be in memory, or the OS may read it from storage.
  3. A swapped page may need to be read back into memory.
  4. A copy-on-write mapping may need a private copy before a write can proceed.
  5. An unmapped address or disallowed access may be reported to the process, for example as SIGSEGV on Linux.

Linux’s minor/major fault counters describe whether servicing a fault required storage I/O; they do not mean that a minor fault is harmless or a major fault is always a bug. Demand allocation is an OS policy that defers some physical-frame work until a valid virtual page is first accessed.

Production Failure Scenarios

Thrashing: Excessive page-ins and page-outs

When active working sets no longer fit in physical memory, the OS has to reclaim pages. If a process soon needs a reclaimed page again, it faults and the OS may need storage I/O to bring it back. Repeated refaults can keep storage busy and leave less time for useful work. A page fault does not always cause disk I/O; check major-fault counts and swap activity alongside memory pressure.

For example, if process A’s active pages are reclaimed to make room for process B, A may fault when it touches them again. If the same pattern repeats across processes, page-ins and page-outs can dominate the workload. Watch sustained swap activity, I/O latency, and application response times rather than using one fixed major-fault threshold for every machine.

Excessive TLB misses for a large working set

When a workload touches more virtual pages than its TLB can keep cached, address translation may require more page-table walks. The impact depends on access locality, TLB organization, page size, and CPU. A 512 MiB working set made of 4 KiB pages spans 131,072 pages. If a processor has 4,096 TLB entries available for those 4 KiB mappings, those entries cover up to 16 MiB at a time. That is an arithmetic example, not a claim about every CPU or workload.

Page-table walks can also benefit from cache hits, so a TLB miss does not have one fixed cycle cost. Measure translation events on the target processor and compare them with the workload’s memory-access pattern. Large pages may increase TLB coverage when the OS can use them, but they are not a substitute for measuring locality.

Useful measurements include hardware TLB-miss counters and the application latency under the same workload. Interpret CPU-specific PMU event names using the processor’s performance-monitoring documentation.

Page-table memory for large mappings

A fully populated 100 GiB mapping with 4 KiB base pages has about 26.2 million leaf entries. At eight bytes per x86-64 entry, the leaf-entry data alone is about 200 MiB. The operating system allocates page-table pages as mappings are populated; reserving a large virtual range without touching its pages does not require a dense array of present leaf entries.

For a fully populated mapping, each 4 KiB table page holds 512 entries. The leaf tables therefore account for roughly 200 MiB, plus the intermediate tables. Sparse mappings can use much less because multiple pages share upper-level tables and untouched regions need no leaf table.

For a 10 GiB file mapping that is fully faulted in with 4 KiB pages, the leaf-entry data is about 20 MiB. A 20 GiB mapping across eight processes would be about 320 MiB of leaf-entry data if all pages were populated independently. These estimates assume 4 KiB pages and fully populated mappings; measure actual page-table memory on the target OS.

Checking page-table memory:

Use the operating system’s process and system memory reports where available. Linux exposes system-wide page-table use in /proc/meminfo; per-process accounting varies by kernel and tooling.

Trade-off Table

The sizes below refer to the x86-64 example in this article. Actual page sizes, TLB coverage, and fragmentation depend on the architecture, operating-system policy, and mapping.

Strategy Page size Potential benefit Cost or limit
Base pages 4 KiB Fine-grained mapping and protection More translations for a large working set
Large pages 2 MiB One translation can cover more memory Larger alignment and allocation requirements; more internal waste is possible
Huge pages 1 GiB Useful for large, stable mappings when supported Harder to allocate and can waste substantial memory
Multi-level tables Architecture-dependent Avoids a dense table for unmapped regions Each mapped region needs table pages along its path
Inverted page table OS-dependent Table size can track physical frames Lookup and sharing rules differ by implementation

Implementation Snippets

Simulating Two-Level Page Table Lookup (Python)

This toy program uses a 32-bit, two-level model with 4 KiB pages. It illustrates index splitting and is separate from the four-level x86-64 example above.

#!/usr/bin/env python3
"""Simplified two-level page table simulation.
Demonstrates how address translation works:
  - VPN (Virtual Page Number) split into:
      PD_INDEX (top bits) + PT_INDEX (bottom bits)
  - Each level is an array of entries
  - PFN (Page Frame Number) + offset = Physical Address
"""

import struct

PAGE_BITS = 12          # 4 KiB pages: 2^12 = 4096 bytes
PAGE_SIZE = 1 << PAGE_BITS
ADDR_BITS = 32          # Simplified 32-bit virtual address

# How many bits for each level of the page table
PD_BITS = 10
PT_BITS = ADDR_BITS - PAGE_BITS - PD_BITS

PD_SIZE = 1 << PD_BITS   # 1024 entries
PT_SIZE = 1 << PT_BITS   # 1024 entries

class PageTableEntry:
    """Simulates a single page table entry (PTE)."""
    def __init__(self, present: bool = False, pfn: int = 0, readonly: bool = False):
        self.present = present
        self.pfn = pfn          # Physical Frame Number
        self.readonly = readonly

    def to_int(self) -> int:
        # Simplified PTE encoding
        val = (self.pfn << 12) | (0b1 if self.present else 0) | (0b10 if self.readonly else 0)
        return val

    @classmethod
    def from_int(cls, val: int):
        present = bool(val & 0b1)
        readonly = bool(val & 0b10)
        pfn = val >> 12
        return cls(present, pfn, readonly)

class PageDirectory:
    """Top-level page directory. Contains PT_BASE addresses."""
    def __init__(self):
        self.entries = [None] * PD_SIZE

    def set_pt_base(self, pd_index: int, pt_base_phys: int):
        self.entries[pd_index] = pt_base_phys

    def get_pt_base(self, pd_index: int):
        return self.entries[pd_index]

class PageTable:
    """Second-level page table. Contains PFN mappings."""
    def __init__(self):
        self.entries = [PageTableEntry() for _ in range(PT_SIZE)]

    def map_page(self, pt_index: int, pfn: int, readonly: bool = False):
        self.entries[pt_index] = PageTableEntry(present=True, pfn=pfn, readonly=readonly)

def translate(logical_addr: int, pd: PageDirectory, pt_pages: dict) -> int:
    """Translate a logical address to a physical address."""
    # Split VPN into PD index and PT index
    pd_index = (logical_addr >> (ADDR_BITS - PD_BITS)) & ((1 << PD_BITS) - 1)
    pt_index = (logical_addr >> PAGE_BITS) & ((1 << PT_BITS) - 1)
    offset   = logical_addr & (PAGE_SIZE - 1)

    # Lookup PD entry to find PT location
    pt_base = pd.get_pt_base(pd_index)
    if pt_base is None:
        raise PageFaultException(f"Page table not present at PD[{pd_index}]")

    # Get PTE from the page table
    pte = pt_pages[pt_base].entries[pt_index]
    if not pte.present:
        raise PageFaultException(f"Virtual page {pt_index} not present")

    # Compute physical address
    physical_addr = (pte.pfn << PAGE_BITS) | offset
    return physical_addr

class PageFaultException(Exception):
    pass

# Example: Map virtual pages 0, 1, and 1024 to physical frames 0x1A, 0x2B, 0x3C
pd = PageDirectory()
# In real hardware, these would be physical addresses of the page tables themselves
PT_BASE = 0x1000
pt_pages = {}

for pd_index in range(2):  # Just PD[0] and PD[1]
    pt_phys = PT_BASE + pd_index * PAGE_SIZE
    pt_pages[pt_phys] = PageTable()
    pd.set_pt_base(pd_index, pt_phys)

# Map pages 0 and 1 through PD[0], then page 1024 through PD[1]
pt_pages[PT_BASE + 0].map_page(0, 0x1A)   # VPage 0 -> PFrame 0x1A
pt_pages[PT_BASE + 0].map_page(1, 0x2B)   # VPage 1 -> PFrame 0x2B
pt_pages[PT_BASE + PAGE_SIZE].map_page(0, 0x3C)  # VPage 1024 (PD[1],PT[0]) -> PFrame 0x3C

# Test translations
print("Logical addr 0x00000 -> Physical 0x{:05X}".format(translate(0x00000, pd, pt_pages)))
print("Logical addr 0x01000 -> Physical 0x{:05X}".format(translate(0x01000, pd, pt_pages)))
print("Logical addr 0x400000 -> Physical 0x{:05X}".format(translate(0x400000, pd, pt_pages)))

Examining Page Fault Types (bash)

#!/bin/bash
# Show page fault statistics for a target process
# Use after observing poor performance to identify page fault causes

PID=${1:-$$}
echo "=== Page fault analysis for PID $PID ==="

# Show lifetime minor and major fault counts for this process
ps -p "$PID" -o pid,comm,min_flt,maj_flt

echo ""
echo "=== Minor vs Major page faults over 2 samples ==="
for i in 1 2; do
    echo "--- Sample $i ---"
    ps -p "$PID" -o pid,comm,min_flt,maj_flt
    sleep 1
done

echo ""
echo "=== Swap usage ==="
grep -i swap /proc/$PID/status 2>/dev/null || echo "No swap used or not found"

echo ""
echo "=== Memory map (first 10 entries) ==="
cat /proc/$PID/maps | head -10

Observability Checklist

  • Minor vs major page fault counts: ps -p PID -o pid,comm,min_flt,maj_flt; compare samples over time and correlate major faults with I/O pressure
  • TLB misses: event names vary by CPU and kernel. Check perf list and the processor’s PMU documentation first; if supported, try perf stat -e dTLB-load-misses,dTLB-store-misses ./program.
  • Per-process page-table memory: check VmPTE in /proc/PID/status when the kernel exposes it
  • Huge page usage: cat /proc/meminfo | grep -i huge
  • OOM killer invocation log: dmesg | grep -i "out of memory\|oom-killer"
  • Swappiness setting: cat /proc/sys/vm/swappiness. Many Linux kernels use 60 as the default, but distributions and administrators can override it. Swappiness is a relative I/O-cost setting, not a percentage of RAM in use; measure a workload before tuning it. See the Linux kernel documentation.
  • Page cache pressure: cat /proc/sys/vm/pagecache (older kernels) or cat /proc/sys/vm/vfs_cache_pressure

Common Pitfalls / Anti-Patterns

Pitfall: Assuming that malloc returns zero-initialized memory. malloc returns storage whose contents are indeterminate to the program. An allocator may reuse a block that held data earlier in the same process, so initialize memory before reading it; use calloc when you need zero-initialized storage. A normal malloc call does not expose another process’s former physical-frame contents: the OS enforces process isolation and clears pages before reusing them for a different process.

Pitfall: Accessing mmap regions without understanding fault behavior. The first access to a mapped page may fault so the OS can install a mapping. It may use data already in the page cache, allocate a zero-filled page, or read file contents from storage. A scan of a 10 GiB file using 4 KiB pages can touch about 2.6 million pages, but that does not mean every access waits for disk. On Linux, MAP_POPULATE can prefault a mapping; it may increase startup work and does not guarantee that all data stays resident.

Pitfall: Using a very large malloc without accounting for page tables. An 8 GiB mapping split into 4 KiB pages has about 2.1 million leaf entries if all pages are populated, or about 16 MiB of leaf-entry data. The TLB holds only a working subset of translations, and its coverage depends on the CPU and page size. If 2 MiB pages are available and suitable, 4,096 such entries could cover 8 GiB, but the OS may not be able to allocate or use them for every mapping.

Anti-pattern: Writing code that assumes contiguous virtual memory. Code can walk a large virtual array with pointer increments even when its 4 KiB pages map to scattered physical frames. A 2 MiB x86-64 huge-page mapping is different: it covers a 2 MiB aligned virtual range backed by a physically contiguous 2 MiB range. The OS and CPU must support the mapping, and the system must have a suitable physical range available.

Page-level Access Control: Page table entries contain protection bits: read (R), write (W), execute (X), and user/supervisor (U/S). The OS sets these when allocating pages. User-space code cannot write to kernel-only pages (U=0), and code pages are marked non-writable (W=0). This is enforced by hardware on every memory access — no software check needed.

SMEP and SMAP: On x86, SMEP blocks supervisor-mode instruction fetches from pages marked as user-accessible. It does not block supervisor data reads or writes. SMAP restricts those supervisor-mode data accesses to user pages unless the kernel temporarily enables access for a controlled operation.

Speculative-execution mitigations: Meltdown exploited speculative execution to infer data from supervisor-mapped memory. Linux’s Page Table Isolation (PTI, also called KPTI) is a software mitigation that separates user and kernel page-table views; see the Linux kernel PTI documentation. IBRS and Enhanced IBRS address Spectre variant 2 indirect-branch prediction attacks, not Meltdown in general; see the Linux kernel Spectre guide.

Cold boot attacks and memory forensics: RAM can retain data for seconds to minutes after power loss. Investigators can cold-boot a machine and image the physical memory to recover page tables, encryption keys, and process data. Full-disk encryption (FDE) with a TPM-bound key mitigates this for persistent data. For memory at rest, use memory encryption features like AMD SEV or Intel TME.

Quick Recap Checklist

  • Page size and address splitting depend on the architecture and paging mode; the worked example uses four-level x86-64 paging with 4 KiB pages.
  • A TLB hit reuses a cached translation. A TLB miss starts a page-table walk.
  • A successful page-table walk is not a page fault. A fault occurs when translation or access checks need operating-system handling.
  • A valid page fault can be resolved by allocating a zero-filled page, mapping cached file data, reading storage, or handling copy-on-write.
  • An invalid address or disallowed access may be reported to the process.
  • Huge pages change how many bytes one translation covers; availability and policy depend on the CPU and OS.
  • Use measurements such as fault counters and TLB events to diagnose a workload instead of assuming every fault means disk I/O.

Interview Questions

1. What is the purpose of having multiple levels of page tables instead of a single flat page table?

A flat table for a full 32-bit, non-PAE address space with 4 KiB pages has 2^20 entries; at four bytes each, it takes 4 MiB. That is a specific 32-bit example. Multi-level tables allocate lower-level tables only for mapped regions. In the four-level x86-64 example, four nearby pages can share one table page at each level, but actual table memory depends on where the process maps memory.

2. What is a page fault, and what is the difference between a minor page fault and a major page fault?

A page fault occurs when address translation or an access-permission check needs operating-system handling. The OS may resolve it, as with a first access to a valid page or a copy-on-write mapping, or reject it if the address or access is invalid. On Linux, a minor fault is serviced without storage I/O; a major fault requires storage I/O. Either counter needs workload context before it signals a problem.

3. How can context switching affect TLB entries?

A context switch changes the active address space. CPUs and operating systems may invalidate translations or use address-space tags such as PCID on x86 or ASIDs on other architectures. The exact invalidation policy depends on hardware and kernel behavior; it is not accurate to say every switch always flushes the entire TLB.

4. What is the translation lookaside buffer, and what is the performance impact of a TLB miss?

The TLB caches virtual-to-physical translations. On a hit, the CPU can use the cached mapping. On a miss, hardware walks the page tables; if the mapping is present and permissions allow the access, the CPU can continue without raising a page fault. Walk latency depends on the CPU, paging mode, and cache state, so one cycle or a fixed number of cycles is not a general rule.

5. How do huge pages improve performance for workloads like databases or JVM heaps?

A larger page lets one TLB entry cover more virtual memory when the CPU and operating system support that page size. For example, a 2 MiB page covers 512 times as much address space as a 4 KiB page. The trade-off is coarser allocation and possible internal waste; whether it improves a database or JVM workload depends on its access pattern and memory policy.

6. What are the different page sizes supported on x86-64 and when would you use each?

In the four-level x86-64 mode used in this article, base pages are 4 KiB. When supported and configured, a page-directory entry can map 2 MiB and a page-directory-pointer entry can map 1 GiB. A PML4 entry points to the next level; it does not map a huge page. Operating-system policy determines whether applications can use large pages.

7. What is the purpose of the Accessed and Dirty bits in a page table entry?

The Accessed bit (A, bit 5) is set by the CPU hardware on every read or write access to a page — regardless of whether it hits or misses in the TLB. The OS reads this bit to implement page replacement algorithms (like LRU) by identifying pages that have been recently used. On x86, the bit is never cleared by hardware; the OS must clear it during page replacement scanning.

The Dirty bit (D, bit 6) is set by the CPU on every write to a page. It indicates whether the page's content differs from what's on disk (for file-mapped pages) or in swap (for anonymous pages). Before evicting a dirty page, the OS must write it back to its backing store — otherwise data is lost. Clean pages can be evicted without I/O. This is why copying to a write buffer before file I/O is important: it ensures the dirty bit is set and the OS writes the correct data to disk.

8. What is PCID and how does it improve context switch performance?

PCID is an x86 feature that can tag TLB entries with a process-context identifier, allowing some translations to remain cached across address-space switches. The OS still has to invalidate stale entries when mappings change. Whether PCID is supported and enabled, and when entries are flushed, depends on the CPU and kernel.

9. What is the difference between a global (G) TLB entry and a per-process TLB entry?

The Global bit (G, bit 8) in a PTE marks pages that are visible across all address spaces — primarily used for kernel text (the kernel code segment). When a context switch occurs, TLB entries with G=1 are NOT invalidated, because the kernel code is the same in every address space. Without the G bit, the OS would have to invalidate all kernel page TLB entries on every context switch — a significant overhead on many-core systems. User-space pages have G=0, so they are flushed on context switch (or with PCID, tagged with the outgoing ASID). Setting G=1 on user pages is incorrect and dangerous because it would allow the user to access those pages after switching to a different process that also has those physical pages.

10. How does demand paging reduce startup time and memory usage?

Demand paging defers some physical-memory work until a valid virtual page is first accessed. That access can fault so the OS can allocate a zero-filled page, map file data already in memory, or read data from storage. The OS does not need to create a present page-table entry for every address in the process's virtual range at startup. Shared file-backed pages may be reused by multiple processes.

11. What is the performance cost of a TLB miss vs a cache miss?

A TLB miss means the translation was not cached. Hardware then walks the page tables, and the required entries may themselves be in cache or require memory access. A data-cache miss is a separate event. Their costs vary by CPU, paging mode, access pattern, and cache state, so fixed cycle counts are only useful when measured on a named system.

12. What is an inverted page table and when is it used?

An inverted page table maintains one entry per physical frame (instead of one entry per virtual page). Each entry records which virtual page and address space owns that physical frame. This reduces memory overhead for systems with large physical memory but sparse virtual usage — a 64 GB system with 4 KB pages needs ~16 MB for an inverted page table (one entry per frame) vs a multi-level page table that might require 1-2 GB for a full process page table. Inverted page tables use hash lookups to find the entry for a given virtual address. They are used in some embedded systems, database engines (e.g., Oracle, DB2), and the SPARC architecture. The downside is that hash collisions add lookup latency and the table is a shared resource requiring locking in multi-processor systems.

13. What happens when a process accesses a page with the read-only bit set to 0 (read-only page)?

On x86, writing to a read-only page raises a page-fault exception for a protection violation. The OS may resolve it when the mapping is copy-on-write by creating a private writable page. If the write is not permitted by the mapping, Linux reports the invalid access to the process, commonly with SIGSEGV.

14. Why must the OS invalidate translations after page-table changes?

If the OS changes or removes a mapping, cached TLB entries can point to the old frame or preserve old permissions. The OS must invalidate the affected translations on the relevant CPUs before it relies on the new mapping. The mechanism and scope of that invalidation depend on the architecture and kernel.

15. What is a page table entry's PFN field and why is it critical for address translation?

A leaf page-table entry contains the physical frame address with its page-offset bits cleared, subject to the processor's supported physical-address width and entry format. The MMU combines that frame base with the offset from the virtual address. Do not assume a fixed physical-address bit range across all x86-64 processors.

16. How does the OS choose which physical frame to allocate when servicing a page fault?

The OS uses a page replacement algorithm to select a victim frame from the free frame list or the inactive page list. Linux uses a variant of LRU called Clock-Pro (or the two-list strategy: active list + inactive list) to approximate LRU without the high overhead of scanning all pages. When a frame is selected, the OS checks its Dirty bit — if dirty, the page is written to its backing store (swap or file) before the frame is reused. The page table entry for the evicted virtual page is then updated to reflect that the page is no longer resident. The newly freed frame is assigned to the faulting process and marked present in its page table. The choice of victim matters for performance: a frame still in active use that gets evicted will cause another fault shortly after.

17. What is the difference between anonymous pages and file-backed pages in terms of page replacement behavior?

Anonymous pages, such as heap and stack pages, have no file-backed origin. Dirty anonymous pages need swap backing before reclaim; clean file-backed pages can be dropped and read from the file again if needed. MAP_ANONYMOUS creates anonymous mappings, while a file-backed mmap() maps file contents. Linux uses swappiness as one input when balancing swap-backed pages against file cache. Its effect depends on kernel version, memory-cgroup limits, swap availability, and workload; it does not choose a specific victim page by itself.

18. Why does multi-level paging cause higher TLB miss rates for sparse address access patterns?

A TLB miss is not a page-table page fault. The hardware walker reads the page-table hierarchy; the operating system keeps the structures needed for the walk available according to its architecture and memory-management rules. Sparse mappings can reduce the number of table pages allocated, while mappings spread across many regions can need more intermediate tables. Measure page-table memory and TLB misses separately.

19. What is a page table entry use-after-free vulnerability and how does the OS mitigate it?

In a use-after-free vulnerability related to page tables, a malicious or buggy process can retain a reference to a physical frame after the OS has freed it (e.g., after munmap or process exit). If the OS reallocates that same physical frame to a different process before the old page table entries are fully cleared, the first process could potentially read or write data belonging to the second process through stale TLB entries or mappings. Mitigation includes: clearing PTE entries immediately when a virtual address range is unmapped (via madvise(MADV_DONTNEED) or munmap), using ASID/PCID tags to invalidate stale TLB entries, and in modern kernels, immediately unlinking the page from the victim's address space so the physical frame goes back to the free list with its page tables cleared. The kernel also poisons freed pages with known patterns to detect residual references.

20. How do 1 GB huge pages work at the hardware level and what are the allocation constraints?

In four-level x86-64 paging, a page-directory-pointer entry can map a 1 GiB page when the CPU supports it and the OS configures it. A page-directory entry can map a 2 MiB page. Neither mapping uses a PML4 entry as a leaf. Large-page allocation needs suitable alignment and available physical memory, so runtime allocation can fail even when total free memory appears sufficient.

Further Reading

Conclusion

The address-translation details depend on the CPU architecture and the paging mode enabled by the OS. In the four-level x86-64 example, a 48-bit canonical virtual address uses four 9-bit table indices and a 12-bit offset for a 4 KiB page.

The TLB caches recent translations. A miss can be resolved by a page-table walk without raising an exception. A page fault occurs when the hardware cannot complete the translation or access check; the OS may resolve it, or report an invalid access to the process. Demand allocation is one reason a valid first access can fault.

For related concepts, continue with Virtual Memory or Memory Allocation: Kernel Allocators.

Category

Related Posts

ASLR & Stack Protection

Explore ASLR, PIE, stack canaries, and NX on Linux with GCC, then inspect a harmless C program to see what each mitigation does and where it falls short.

#operating-systems #aslr-stack-protection #computer-science

Assembly Language Basics: Writing Code the CPU Understands

Learn x86-64 Linux assembly with the System V ABI: track registers, assemble and run a small program, debug it in GDB, then compare AArch64.

#operating-systems #assembly-language-basics #computer-science

Boolean Logic & Gates

Understanding AND, OR, NOT gates and how they combine into arithmetic logic units — the building blocks of every processor.

#operating-systems #boolean-logic-gates #computer-science