Lesson 5 · Memory management

Page Table Structures in OS

A page table maps a process's virtual pages to physical frames. One flat array per process is too big, so real systems use a multilevel, hashed or inverted structure instead.

Page Table Structures in OS concept diagramA visual explanation of the layout and operations shown in this lesson.one job, virtual page to frame, stored four waysFLAT: one entry for every possible page, 2²⁰ entries = 4 MB per processcode, heap and stack use a few entries; the gap in between pays for the restMULTILEVELa tree of 4 KB tablesHASHEDonly mapped pages, in bucketsINVERTEDone row per physical frameouterinnerabsentabsentabsentan empty outer entry costs 4 bytesinstead of a whole 4 KB inner table0123page 17page 53h(53) = 53 mod 4 = 1entries store their page numberbecause 17 and 53 share bucket 1frame 0: P2, page 3frame 1: P1, page 2frame 2: P1, page 7frame 3: P3, page 9frame 4: freesize follows RAM, not process countlookup searches by (pid, page)1 read per level (4 on x86-64)1 hash + a short chain1 hash + a chain, row = framecost on a TLB miss; a TLB hit skips all three
1

What a Page Table Does

  1. Split the virtual address into page number p and offset d.
  2. Read entry p of the current process's page table.
  3. If the entry is not valid, raise a page fault.
  4. Otherwise physical address = frame number × page size + d.

A page table is the data structure that turns a virtual address into a physical one. Memory is split into fixed-size pages (virtual) and frames (physical). The page table records, for each virtual page of a process, which frame holds it.

The CPU splits every address into a page number and an offset. The page number selects an entry in the table; the entry gives a frame number; the frame number joined to the unchanged offset is the physical address. With 4 KB pages the offset is the low 12 bits, because 2¹² = 4096.

Each process has its own table, so the same virtual address in two processes can point to two different frames. The kernel keeps the table's physical address in the process's PCB and loads it into the page table base register (CR3 on x86) when the process is scheduled.

  • One table per process; the base register says which one is in use
  • The offset is copied through untouched; only the page number is translated
  • The MMU does this on every instruction fetch, load and store
2

Inside a Page Table Entry

A page table entry (PTE) holds more than the frame number. The remaining bits tell the hardware whether the mapping may be used and tell the OS how the page has been used.

On 32-bit x86 an entry is 4 bytes: 20 bits of frame number and 12 bits of flags. On x86-64 and ARMv8 it is 8 bytes, which leaves room for larger frame numbers and a no-execute bit.

  • Frame number: the physical frame that holds the page
  • Valid (present) bit: 0 means the page is not in memory, so access raises a page fault
  • Protection bits: read, write, execute, and whether user mode may touch the page
  • Referenced (accessed) bit: set by hardware on any access; page replacement reads it
  • Dirty (modified) bit: set on a write, so a clean page can be dropped without writing it back
  • Cache-disable bit: for pages that map device registers rather than RAM
3

Why One Flat Table Does Not Fit

The simplest layout is one array with an entry for every possible page. On a 32-bit machine with 4 KB pages the page number has 32 − 12 = 20 bits, so the array has 2²⁰ = 1,048,576 entries. At 4 bytes each that is 4 MB per process, and it must sit in contiguous physical memory.

Almost all of it is wasted. A typical process has code near address 0, a heap above it and a stack near the top, with a huge unused gap between. A process using 12 pages still pays for 1,048,576 entries, and 100 such processes pay 400 MB.

On 64-bit hardware the flat layout stops being possible at all. x86-64 uses 48-bit virtual addresses, so the page number has 36 bits: 2³⁶ entries of 8 bytes is 512 GB for one process.

  • Entries = 2^(address bits − offset bits); size = entries × entry size
  • 32-bit, 4 KB pages, 4-byte entries: 4 MB per process
  • 48-bit, 4 KB pages, 8-byte entries: 512 GB per process
  • The cost comes from the unused gap, which a flat array cannot skip
Key reference

Terms, operations, and practical uses

Core vocabulary

  • Page tablePer-process map from virtual page number to physical frame number.
  • Page table entry (PTE)One mapping: frame number plus valid, protection, referenced and dirty bits.
  • Page table base registerHolds the physical address of the running process's table (CR3 on x86).
  • Page faultThe trap raised when the entry's valid bit is 0.

Formulas and rules

  • Offset bitslog₂(page size): 12 for 4 KB pages
  • Entries2^(virtual address bits − offset bits)
  • Flat table sizeentries × entry size: 2²⁰ × 4 B = 4 MB on 32-bit
  • Physical addressframe number × page size + offset
Implementation

One address through four page tables

OFFSET_BITS = 12  # 4 KB pages


def flat_bytes(address_bits, entry_bytes):
    """One entry for every possible page, used or not."""
    return (1 << (address_bits - OFFSET_BITS)) * entry_bytes


def two_level_bytes(pages, entry_bytes=4):
    """One outer table plus one inner table per 4 MB region in use."""
    inner_tables = len({page >> 10 for page in pages})
    return (1 + inner_tables) * 1024 * entry_bytes


def inverted_bytes(ram_bytes, entry_bytes=8):
    """One entry per physical frame, shared by every process."""
    return (ram_bytes >> OFFSET_BITS) * entry_bytes


def main():
    code = range(0x00000, 0x00004)
    heap = range(0x00400, 0x00406)
    stack = range(0xFFFFE, 0x100000)
    pages = [*code, *heap, *stack]

    flat = flat_bytes(32, 4)
    two = two_level_bytes(pages)

    print(f"mapped pages        {len(pages):>16,}")
    print(f"flat, 32-bit        {flat:>16,} bytes")
    print(f"two-level           {two:>16,} bytes")
    print(f"saving              {flat // two:>16,}x")
    print(f"flat, 48-bit        {flat_bytes(48, 8):>16,} bytes")
    print(f"inverted, 4 GB RAM  {inverted_bytes(4 << 30):>16,} bytes")


if __name__ == "__main__":
    main()
#include <cstdint>
#include <iostream>
#include <set>
#include <string>
#include <vector>

constexpr int OFFSET_BITS = 12;  // 4 KB pages

// One entry for every possible page, used or not.
uint64_t flatBytes(int addressBits, uint64_t entryBytes) {
    return (1ULL << (addressBits - OFFSET_BITS)) * entryBytes;
}

// One outer table plus one inner table per 4 MB region in use.
uint64_t twoLevelBytes(const std::vector<uint32_t>& pages, uint64_t entryBytes = 4) {
    std::set<uint32_t> innerTables;
    for (uint32_t page : pages) innerTables.insert(page >> 10);
    return (1 + innerTables.size()) * 1024 * entryBytes;
}

// One entry per physical frame, shared by every process.
uint64_t invertedBytes(uint64_t ramBytes, uint64_t entryBytes = 8) {
    return (ramBytes >> OFFSET_BITS) * entryBytes;
}

std::string commas(uint64_t n) {
    std::string s = std::to_string(n);
    for (int i = (int)s.size() - 3; i > 0; i -= 3) s.insert(i, ",");
    return s;
}

void row(const std::string& label, uint64_t n, const std::string& unit) {
    std::string v = commas(n);
    std::cout << label << std::string(20 - label.size(), ' ')
              << std::string(16 - v.size(), ' ') << v << unit << "\n";
}

int main() {
    std::vector<uint32_t> pages;
    for (uint32_t p = 0x00000; p < 0x00004; p++) pages.push_back(p);   // code
    for (uint32_t p = 0x00400; p < 0x00406; p++) pages.push_back(p);   // heap
    for (uint32_t p = 0xFFFFE; p < 0x100000; p++) pages.push_back(p);  // stack

    uint64_t flat = flatBytes(32, 4);
    uint64_t two = twoLevelBytes(pages);

    row("mapped pages", pages.size(), "");
    row("flat, 32-bit", flat, " bytes");
    row("two-level", two, " bytes");
    row("saving", flat / two, "x");
    row("flat, 48-bit", flatBytes(48, 8), " bytes");
    row("inverted, 4 GB RAM", invertedBytes(4ULL << 30), " bytes");
}
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

class Main {
    static final int OFFSET_BITS = 12; // 4 KB pages

    // One entry for every possible page, used or not.
    static long flatBytes(int addressBits, long entryBytes) {
        return (1L << (addressBits - OFFSET_BITS)) * entryBytes;
    }

    // One outer table plus one inner table per 4 MB region in use.
    static long twoLevelBytes(List<Integer> pages) {
        Set<Integer> innerTables = new HashSet<>();
        for (int page : pages) innerTables.add(page >> 10);
        return (1L + innerTables.size()) * 1024 * 4;
    }

    // One entry per physical frame, shared by every process.
    static long invertedBytes(long ramBytes) {
        return (ramBytes >> OFFSET_BITS) * 8;
    }

    public static void main(String[] args) {
        List<Integer> pages = new ArrayList<>();
        for (int p = 0x00000; p < 0x00004; p++) pages.add(p);   // code
        for (int p = 0x00400; p < 0x00406; p++) pages.add(p);   // heap
        for (int p = 0xFFFFE; p < 0x100000; p++) pages.add(p);  // stack

        long flat = flatBytes(32, 4);
        long two = twoLevelBytes(pages);

        System.out.printf("mapped pages        %,16d%n", pages.size());
        System.out.printf("flat, 32-bit        %,16d bytes%n", flat);
        System.out.printf("two-level           %,16d bytes%n", two);
        System.out.printf("saving              %,16dx%n", flat / two);
        System.out.printf("flat, 48-bit        %,16d bytes%n", flatBytes(48, 8));
        System.out.printf("inverted, 4 GB RAM  %,16d bytes%n", invertedBytes(4L << 30));
    }
}
Watch it run

Step through it

Running on 32-bit address 0x00403004, 4 KB pages, a process mapping 12 pages (code, heap, stack)

0x00403004page number 0x00403top 20 bits: translatedoffset 0x004low 12 bits: copied as ispage table → frame ?frame ? + 0x004The page table maps page numbers to frame numbers
Step 1

One address, two parts

With 4 KB pages the low 12 bits of an address are the offset inside the page, because 2^12 = 4096. The other 20 bits are the page number. Only the page number is translated, so the page table's whole job is to say which physical frame holds page 0x00403.

Output
1 / 11
4

Types of Page Table

Textbooks cover the structure of page table under three headings, and each one avoids paying for the unused gap in its own way.

Hierarchical paging (multilevel paging) splits the page number into several indexes and pages the table itself. An outer entry for an unused region is simply empty, so no inner table is allocated for it. The price is one memory read per level on a TLB miss.

A hashed page table stores only the pages that are mapped. The page number is hashed to a bucket, and the bucket's chain is searched for an entry with that page number.

An inverted page table turns the mapping around: one entry per physical frame, holding the process id and page number that live there. There is one table for the whole machine, so its size depends on RAM, not on how many processes run.

The four layouts compared
LayoutSize grows withWork on a TLB missUsed on
FlatThe whole virtual address space, per process1 table readSmall 16- and 32-bit systems
MultilevelRegions in use, per process1 read per level (4 on x86-64)x86, x86-64, ARM
HashedPages mappedA hash plus a short chain walkPowerPC, IA-64
InvertedPhysical frames, one table in totalA hash plus a chain, then the row index is the frameIBM RT, PowerPC, UltraSPARC
  • Every structure is smaller than a flat array and slower to search
  • Multilevel is the common choice on today's desktop and phone processors
  • Inverted tables make sharing a frame between processes awkward
5

What a Miss Costs

None of these structures is walked on most memory references. The TLB caches recent translations, and with typical hit rates the walk happens only on a small fraction of accesses.

So the choice of structure decides the price of a miss, not everyday speed. A four-level walk on x86-64 costs four table reads before the data read. Large pages shorten the walk: a 2 MB page stops one level early, and one TLB entry then covers 512 times as much memory.

If the entry it reaches is not valid, the walk ends in a page fault and the OS takes over; demand paging covers that path.

  • TLB hit: no table read at all
  • TLB miss: one read per level, or one hash and a chain walk
  • Invalid entry: page fault, handled by the OS
  • Edge case: the page table itself must stay resident, or the walk would fault on its own table