ENع
←Page faults and swap
Lesson 34 · Memory management

Page faults and swapping to disk

14 min10 steps5 questionsIntermediate
About this lesson

A process's pages do not all have to sit in RAM. The kernel can keep some of them on disk, in swap space, and mark them not present in the page table. When the program touches one, the MMU raises a page fault and the kernel steps in: it finds the page on disk, frees a frame by evicting another page (writing it back if it is dirty), reads the page in while the process waits, fixes the page table and runs the same instruction again. Follow three lines of pseudo-code through one hit, one full page fault and one bad address that ends in SIGSEGV, then see why every trip to disk is so costly. Multi-level page tables shows how the entries are stored; the Hardware lesson on virtual memory shows the chip's side of a fault.

You'll learn to

Tick what you feel confident about. These self-checks do not affect your lesson score.

Fig 34 · Interactive
01 / 10

Not every page fits

Process P has four 4 KB pages, but only two RAM frames, 5 and 6. Pages 2 and 3 wait on disk, in swap space. Each page table entry says where: F5 means present in frame 5; S0 means not present, in swap slot 0.

page table of P (one entry per 4 KB page)
  page 0   F5   present bit 1, frame 5
  page 1   F6   present bit 1, frame 6
  page 2   S0   present bit 0, swap slot 0
  page 3   S1   present bit 0, swap slot 1

RAM (P may use 2 frames)   frame 5: page 0   frame 6: page 1
swap space on disk         slot 0: page 2    slot 1: page 3
                           slot 2: free
Loading figure…
or ← →
Read the lesson step by step
  1. Not every page fits

    Process P has four 4 KB pages, but only two RAM frames, 5 and 6. Pages 2 and 3 wait on disk, in swap space. Each page table entry says where: F5 means present in frame 5; S0 means not present, in swap slot 0.

    page table of P (one entry per 4 KB page)
      page 0   F5   present bit 1, frame 5
      page 1   F6   present bit 1, frame 6
      page 2   S0   present bit 0, swap slot 0
      page 3   S1   present bit 0, swap slot 1
    
    RAM (P may use 2 frames)   frame 5: page 0   frame 6: page 1
    swap space on disk         slot 0: page 2    slot 1: page 3
                               slot 2: free
  2. Line 1: page in RAM

    Line 1 writes to 0x0008: page 0, offset 8. Its entry says frame 5, present, so the MMU sends the write to 0x5008. It also sets the entry's dirty bit, D: page 0 has changed. The kernel is not involved.

    line 1             mem[0x0008] = 7
    virtual address    0x0008 = page 0, offset 0x008
    page table entry   F5, present bit 1
    physical address   frame 5 * 0x1000 + 0x008 = 0x5008
    dirty bit          D = 1 (set by the hardware on a write)
    
    the common case: done by the MMU, no kernel code
  3. Line 2: a page fault

    Line 2 reads 0x2010: page 2. Its entry says S0, present bit 0: the page is on disk, not in RAM. The MMU cannot finish the read, so it raises a page fault. The CPU traps into the kernel and records the faulting address.

    line 2             x = mem[0x2010]
    virtual address    0x2010 = page 2, offset 0x010
    page table entry   S0, present bit 0  -> page fault
    
    CPU   user mode -> kernel mode, jump to the fault handler
          the faulting address is saved for the kernel
          (in the stval register on RISC-V)
          line 2 has not finished: nothing was read
  4. The kernel looks it up

    The kernel's page-fault handler first checks that page 2 is a legal part of P's address space: it is. Then it finds where the page lives. The entry holds a disk address, swap slot 0, in the bits that normally hold a frame number.

    page-fault handler (kernel code)
      address   0x2010  -> page 2
      legal?    yes, pages 0..3 belong to P
      entry     present bit 0, disk address = swap slot 0
    
    the hardware only says "not present";
    deciding what that means is the kernel's job
  5. RAM is full: evict a page

    Both frames are in use, so a page must leave. This kernel picks the oldest: page 0 in frame 5. It is dirty, so the kernel first writes it to free swap slot 2. Page 0 becomes not present; its TLB entry is dropped.

    free frame for P?   none (frames 5 and 6 in use)
    victim              page 0 (oldest), frame 5
    dirty bit           D = 1 -> write it to disk first
                        (a clean page that still has a
                        disk copy could be dropped for free)
    disk write          frame 5 -> swap slot 2
    entry for page 0    F5·D  ->  S2  (present bit 0)
    TLB                 old entry for page 0 invalidated
    
    choosing the victim well is a topic of its own:
    page replacement (FIFO, LRU, clock)
  6. Reading page 2 from disk

    The kernel asks the disk to copy swap slot 0 into frame 5. A disk takes milliseconds, so P is marked blocked and the CPU runs other ready processes meanwhile. When the read is done, the disk interrupts and the kernel carries on.

    disk read    swap slot 0 -> frame 5   (one 4 KB page)
    process P    blocked while the I/O is in flight
    CPU          runs other ready processes meanwhile
    disk         interrupt: read complete
    
    a fault that needs disk I/O is a major fault;
    one fixed without I/O is a minor fault
  7. Fixing the page table

    The kernel updates page 2's entry: frame 5, present bit 1. Swap slot 0 is free again. P moves from blocked to ready, so the scheduler can run it again.

    entry for page 2    S0  ->  F5   (present bit 1)
    swap slot 0         free
    process P           blocked -> ready
    
    page table now   0: S2   1: F6   2: F5   3: S1
  8. Line 2 again: a hit

    The kernel returns from the trap to the same instruction, not the next one. Line 2 runs again: page 2 is present in frame 5, so 0x2010 becomes 0x5010. P never notices the fault; it only ran slower.

    return from trap  -> re-run line 2 (same instruction)
    virtual address   0x2010 = page 2, offset 0x010
    entry F5          -> 0x5010
    
    the whole fault path as a Python simulation:
    
    PAGE = 4096
    pt = {0: "F5", 1: "F6", 2: "S0", 3: "S1"}  # page -> frame or swap slot
    in_ram = [0, 1]                           # pages in RAM, oldest first
    free_slots = ["S2"]
    
    def access(addr):
        page, offset = divmod(addr, PAGE)
        if page not in pt:                    # not in the address space
            return "SIGSEGV"
        if pt[page].startswith("S"):          # present bit 0: page fault
            victim = in_ram.pop(0)            # RAM full: the oldest page goes
            frame = pt[victim]
            pt[victim] = free_slots.pop(0)    # written to swap (it is dirty)
            print(f"  fault: page {victim} out to {pt[victim]},"
                  f" page {page} in from {pt[page]}")
            free_slots.append(pt[page])       # its slot is free again
            pt[page] = frame                  # present bit 1
            in_ram.append(page)
        return hex(int(pt[page][1:]) * PAGE + offset)
    
    for addr in [0x0008, 0x2010, 0x9000]:
        print(hex(addr), "->", access(addr))
    
    prints:
    0x8 -> 0x5008
      fault: page 0 out to S2, page 2 in from S0
    0x2010 -> 0x5010
    0x9000 -> SIGSEGV
  9. Line 3: a bad address

    Line 3 reads 0x9000: page 9. P's address space has only pages 0 to 3, so there is no entry and no copy anywhere. The fault reaches the kernel as before, but this one is a bug: the kernel sends SIGSEGV, which ends P.

    line 3             y = mem[0x9000]
    virtual address    0x9000 = page 9
    page 9             not part of P (pages 0..3)
    
    not present but valid  -> fetch it from disk
    not valid at all       -> a bug: SIGSEGV
                              (invalid memory reference,
                              default action: end P, dump core)
  10. Why faults must be rare

    A memory access takes about 100 ns; a disk read about 10 ms, 100,000 times longer. If just 1 access in 1,000 went to disk, the average would be 10.1 µs: about 100 times slower than RAM. So kernels keep busy pages in memory.

    average access time = T_mem + miss rate * T_disk
      T_mem = 100 ns, T_disk = 10 ms (a hard disk)
      miss rate 1/1000:  100 ns + 10 us = 10.1 us
    
    count the page faults of a real program (C, Linux/macOS):
    
    #define _DEFAULT_SOURCE            /* ru_minflt, ru_majflt on glibc */
    #include <stdio.h>
    #include <sys/resource.h>
    #include <unistd.h>
    
    static volatile char buf[1 << 20];  /* 1 MiB, never touched yet */
    
    static long faults(void) {
        struct rusage u;
        getrusage(RUSAGE_SELF, &u);
        return u.ru_minflt + u.ru_majflt;
    }
    
    int main(void) {
        long page = sysconf(_SC_PAGESIZE);
        long before = faults();
        for (long i = 0; i < (long)sizeof buf; i += page)
            buf[i] = 1;                 /* first touch of each page */
        long after = faults();
        printf("pages touched: %ld\n", (long)sizeof buf / page);
        printf("page faults:   %ld\n", after - before);
        return 0;
    }
    
    each first touch of a page is a fault (a minor one,
    no disk I/O): pages touched = page faults, e.g. 256
    with 4 KB pages

Quiz Unlocks after the last step.