Lesson 9 · Memory management

Demand Paging in OS

Load a page only when it is touched. That is what makes virtual memory affordable, and it means one memory reference can cost eight milliseconds.

Demand Paging in OS concept diagramA process executes load M. Page M's entry in the page table has the valid bit clear, so the reference traps to the operating system, which finds page M on the backing store, reads it into free frame F7, sets the entry to valid and restarts the instruction.processload Mpage table0F3vM—i → v2F0v3—ioperating systemillegal address → killphysical memoryF0page 2F3page 0F7free → MF5otherbacking storepage M1 reference2 trap3 locate4 read5 set valid6 restartresident page: 100 ns · steps 2–5: ≈ 8 ms, the process blocks
1

Loading Pages on First Touch

Demand paging brings a page into physical memory only when the running process actually uses it. Nothing is read from disk in advance. The part of the OS that does this is sometimes called a lazy swapper: it moves single pages, and only when asked.

The hardware hook is the valid bit in each page-table entry. Valid means the page is in a frame and the frame number can be used. Invalid means it is not: either the page is on the backing store, or the address is not part of the process at all. The MMU checks the bit on every access, and an access to an invalid entry is a page fault.

The result is that the memory a program occupies follows what it touches, not how big it is. A large program that runs one code path may never load most of itself. This is how virtual memory lets a program be larger than RAM.

  • The valid bit is what triggers the fault
  • Memory used follows what is touched, not program size
  • Edge case: a page that is never touched is never read from disk at all
2

Page Fault Handling Steps

  1. Reference: the MMU looks up the page and finds the valid bit clear.
  2. Trap: control passes to the OS; the instruction has not finished.
  3. Locate: the OS checks the address is legal and finds the page on the backing store.
  4. Read in: the OS takes a free frame (or evicts a page) and reads the page from disk.
  5. Update: the page-table entry gets the frame number and the valid bit is set.
  6. Restart: the instruction that faulted runs again from the beginning.

These six page fault handling steps are the standard answer, and the order matters. The check in step 3 comes before any disk work: if the address is outside the process, it is a segmentation fault and the process is stopped without reading anything.

Step 4 is where the time goes. The process is blocked for the whole disk read, so the scheduler runs another process meanwhile. If no frame is free, a page replacement algorithm picks a victim, and a modified victim must be written back first, which roughly doubles the cost of that fault.

  • Illegal address: stopped at step 3, no disk read
  • The faulting process blocks; the CPU runs someone else
  • A dirty victim adds a disk write before the read
3

Why the Instruction Is Restarted, Not Resumed

Step 6 is the subtle one. The instruction runs again from scratch, so the hardware must be able to run it twice and get the same result.

That is not automatic. A block-move instruction that copies between overlapping areas may fault halfway through, after some bytes are already overwritten; starting over would copy damaged data. An auto-increment addressing mode may have bumped a register before the faulting access.

CPUs handle this in one of two ways: touch every page a complex instruction needs before changing anything, or keep enough state to undo the partial work. Either way it is a property of the CPU, which is why an OS cannot add demand paging to hardware that was not built for it.

  • Restart needs instructions that are safe to re-run
  • Block moves and auto-increment modes are the hard cases
  • A CPU property, not an OS choice
Key reference

Terms, operations, and practical uses

Terms to know

  • Valid bitSet when the page is in a frame; clear when it is on disk or not part of the process.
  • Backing storeThe disk area (swap space) holding pages that are not in RAM.
  • Lazy swapperA pager that moves single pages, and only when they are needed.
  • Page fault rateThe share of memory accesses that fault; it drives the effective access time.
Implementation

Pure demand paging: the fault path, then eight more references

MEMORY_NS = 100
FAULT_NS = 8_000_000  # reading a page from a hard disk, about 8 ms
FRAMES = 3
PAGES = 4  # pages 0..3 are the whole address space


def effective_access_time(fault_rate):
    return (1 - fault_rate) * MEMORY_NS + fault_rate * FAULT_NS


def run(references):
    slots = [None] * FRAMES  # which page each frame holds
    loaded = []              # resident pages, oldest first (FIFO eviction)
    faults = served = 0
    for page in references:
        if page >= PAGES:
            print(f"page {page}  outside the address space -> segmentation fault")
            break
        served += 1
        if page in slots:
            print(f"page {page}  hit")
            continue
        faults += 1
        if None in slots:
            frame, note = slots.index(None), ""
        else:
            victim = loaded.pop(0)
            frame, note = slots.index(victim), f", evicting page {victim}"
        slots[frame] = page
        loaded.append(page)
        print(f"page {page}  FAULT -> frame {frame}{note}")
    return faults, served


faults, served = run([0, 1, 0, 3, 1, 2, 0, 3, 9])
print(f"\n{faults} faults in {served} references")
eat = effective_access_time(0.001)
print(f"p = 0.001: EAT = {eat:.1f} ns, {eat / MEMORY_NS:.0f}x slower than memory")
# Largest p that keeps EAT within 10% of a plain memory access.
limit = 0.1 * MEMORY_NS / (FAULT_NS - MEMORY_NS)
print(f"within 10%: at most one fault per {1 / limit:.0f} references")
#include <algorithm>
#include <cstdio>
#include <deque>
#include <string>
#include <vector>

const double MEMORY_NS = 100;
const double FAULT_NS = 8000000;  // reading a page from a hard disk, about 8 ms
const int FRAMES = 3;
const int PAGES = 4;  // pages 0..3 are the whole address space

double effectiveAccessTime(double faultRate) {
    return (1 - faultRate) * MEMORY_NS + faultRate * FAULT_NS;
}

void run(const std::vector<int>& references, int& faults, int& served) {
    std::vector<int> slots(FRAMES, -1);  // which page each frame holds
    std::deque<int> loaded;              // resident pages, oldest first (FIFO eviction)
    faults = served = 0;
    for (int page : references) {
        if (page >= PAGES) {
            std::printf("page %d  outside the address space -> segmentation fault\n", page);
            break;
        }
        served++;
        if (std::find(slots.begin(), slots.end(), page) != slots.end()) {
            std::printf("page %d  hit\n", page);
            continue;
        }
        faults++;
        int frame;
        std::string note;
        auto empty = std::find(slots.begin(), slots.end(), -1);
        if (empty != slots.end()) {
            frame = empty - slots.begin();
        } else {
            int victim = loaded.front();
            loaded.pop_front();
            frame = std::find(slots.begin(), slots.end(), victim) - slots.begin();
            note = ", evicting page " + std::to_string(victim);
        }
        slots[frame] = page;
        loaded.push_back(page);
        std::printf("page %d  FAULT -> frame %d%s\n", page, frame, note.c_str());
    }
}

int main() {
    int faults, served;
    run({0, 1, 0, 3, 1, 2, 0, 3, 9}, faults, served);
    std::printf("\n%d faults in %d references\n", faults, served);
    double eat = effectiveAccessTime(0.001);
    std::printf("p = 0.001: EAT = %.1f ns, %.0fx slower than memory\n", eat, eat / MEMORY_NS);
    // Largest p that keeps EAT within 10% of a plain memory access.
    double limit = 0.1 * MEMORY_NS / (FAULT_NS - MEMORY_NS);
    std::printf("within 10%%: at most one fault per %.0f references\n", 1 / limit);
}
import java.util.ArrayDeque;
import java.util.Arrays;

public class Main {
    static final double MEMORY_NS = 100;
    static final double FAULT_NS = 8_000_000;  // reading a page from a hard disk, about 8 ms
    static final int FRAMES = 3;
    static final int PAGES = 4;  // pages 0..3 are the whole address space

    static double effectiveAccessTime(double faultRate) {
        return (1 - faultRate) * MEMORY_NS + faultRate * FAULT_NS;
    }

    static int indexOf(int[] a, int v) {
        for (int i = 0; i < a.length; i++) if (a[i] == v) return i;
        return -1;
    }

    // returns {faults, served}
    static int[] run(int[] references) {
        int[] slots = new int[FRAMES];               // which page each frame holds
        Arrays.fill(slots, -1);
        ArrayDeque<Integer> loaded = new ArrayDeque<>();  // resident pages, oldest first (FIFO eviction)
        int faults = 0, served = 0;
        for (int page : references) {
            if (page >= PAGES) {
                System.out.printf("page %d  outside the address space -> segmentation fault%n", page);
                break;
            }
            served++;
            if (indexOf(slots, page) >= 0) {
                System.out.printf("page %d  hit%n", page);
                continue;
            }
            faults++;
            int frame = indexOf(slots, -1);
            String note = "";
            if (frame < 0) {
                int victim = loaded.pollFirst();
                frame = indexOf(slots, victim);
                note = ", evicting page " + victim;
            }
            slots[frame] = page;
            loaded.addLast(page);
            System.out.printf("page %d  FAULT -> frame %d%s%n", page, frame, note);
        }
        return new int[] {faults, served};
    }

    public static void main(String[] args) {
        int[] r = run(new int[] {0, 1, 0, 3, 1, 2, 0, 3, 9});
        System.out.printf("%n%d faults in %d references%n", r[0], r[1]);
        double eat = effectiveAccessTime(0.001);
        System.out.printf("p = 0.001: EAT = %.1f ns, %.0fx slower than memory%n", eat, eat / MEMORY_NS);
        // Largest p that keeps EAT within 10% of a plain memory access.
        double limit = 0.1 * MEMORY_NS / (FAULT_NS - MEMORY_NS);
        System.out.printf("within 10%%: at most one fault per %.0f references%n", 1 / limit);
    }
}
Watch it run

Step through it

Running on 4 pages, 3 frames, FIFO eviction; references 0 1 0 3 1 2 0 3, then page 9

1 reference2 trap3 locate4 read in5 update6 restartreferences010312039page tablepage valid frame00—10—20—30—frames (RAM)F0 freeF1 freeF2 freedisk · backing storepages 0 1 2 3process: runningfaults 0 · references 00 pages in RAM, 3 free frames
Step 1

A new process with nothing in RAM

Under pure demand paging the process starts with every valid bit at 0: not one of its 4 pages is in a frame, not even the page with its first instruction. All 3 frames are free.

Output
1 / 16
4

Pure Demand Paging and Prepaging

Pure demand paging is the extreme form: a process starts with no pages in memory at all, not even the one holding its first instruction. The first instruction fetch faults, then its data, then its stack, then each new code page. A process can take dozens of faults before it does anything useful.

The benefit is that nothing unused is ever loaded. The cost is that burst of faults at start-up, which is why real systems soften it with prepaging: on a fault, read in a few neighbouring pages as well, betting on locality. When the bet is right, several faults become one disk read; when it is wrong, it wastes I/O and frames.

Linux does this for files as read-ahead, and Windows as prefetching at program start. Plain demand paging is the middle ground: the OS may load something before the first instruction, but everything else waits to be touched.

  • Pure: zero pages in RAM at start, everything faults in
  • Prepaging: guess the next pages and read them with the faulting one
  • A wrong guess costs frames and disk bandwidth
5

What a Fault Costs

Let p be the page fault rate, the share of memory accesses that fault. The effective access time is EAT = (1 − p) × memory access time + p × fault service time.

Take a 100 ns memory access and an 8 ms (8,000,000 ns) fault service on a hard disk. With p = 0.001, one fault per thousand accesses: EAT = 0.999 × 100 + 0.001 × 8,000,000 = 99.9 + 8,000 = 8,099.9 ns, which is 81 times slower than memory, from a fault rate that sounds tiny.

To stay within 10% of memory speed, EAT must be at most 110 ns: 100 + p × 7,999,900 ≤ 110, so p ≤ 1.25 × 10⁻⁶, about one fault in 800,000 accesses. That is the real target behind every replacement algorithm, and it is why thrashing wrecks performance once the fault rate climbs.

An SSD cuts the service time to around 0.1 ms. The same 10% target then allows one fault in about 10,000 accesses: 80 times more, but still rare.

  • One fault in a thousand makes memory 81 times slower
  • The fault term dominates the sum
  • Faster disks shrink the cost of a fault, not the need to avoid them
6

Gains and Costs

Demand paging trades a rare, expensive event for a large saving in memory and start-up time. It works well exactly when programs show locality, and badly when they jump across more pages than they have frames.

  • Gain: programs start before they are fully loaded
  • Gain: more processes fit in RAM, since each holds only its used pages
  • Gain: a program can be larger than physical memory
  • Cost: each fault blocks the process for milliseconds
  • Cost: needs restartable instructions and a valid bit in hardware
  • Cost: with too few frames, faults pile up into thrashing