Lesson 2 · Memory management

Virtual Memory

Give every process its own private address space, larger than RAM if needed, and let the hardware translate each address page by page — fetching from disk only the pages that are actually used.

Virtual Memory concept diagramProcess A and process B each see virtual pages 0 to 3. Their pages are scattered across five physical frames, one frame holds a shared library used by both, and two pages are on disk.process Avirtual addresses 0–4095page 0→ F2page 1→ F0page 2→ F4 · sharedpage 3→ on diskprocess Bvirtual addresses 0–4095page 0→ F1page 1→ F4 · sharedpage 2→ on diskpage 3→ F3physical RAM5 frames, shared by everyoneF0A · page 1F1B · page 0F2A · page 0F3B · page 3F4shared librarydisk (swap space)A · page 3, B · page 2same address in A and B→ different framesdashed = not in RAM:touching it causes a page fault
1

Two Kinds of Address

  1. Virtual address – the address a program uses; every process's addresses start at 0.
  2. Physical address – the real location in RAM.
  3. Page / frame – the virtual address space is cut into fixed-size pages, RAM into frames of the same size.
  4. Page table – one per process; maps each virtual page to a frame, or marks it as not in memory.
  5. Backing store – pages that are not in RAM are kept on disk (swap space).

Virtual memory is the technique that separates the addresses a program uses from the physical memory that holds its data. Every process gets its own virtual address space, as if it had the whole machine to itself, and the operating system and hardware map that space onto real RAM behind the scenes.

So the difference between a virtual and a physical address has a short answer: the program only ever sees the first, and the hardware turns it into the second on every access. Two things follow. Processes are isolated: address 4096 in process A and address 4096 in process B are different memory, so one cannot read or corrupt the other. And a program can be larger than RAM: only the pages it is using need to be in memory, while the rest wait on disk and are brought in on demand.

  • Built from paging, a page table per process and the MMU
  • Edge case: an address no page-table entry covers is a crash, not a page fault
2

Address Translation, Step by Step

  1. Split – page number p = VA ÷ page size; offset d = VA mod page size.
  2. Look up – the MMU reads the page-table entry for p (the TLB caches recent entries).
  3. Valid – if the entry is valid, it holds frame number f.
  4. Combine – physical address = f × page size + d.
  5. Not valid – the MMU raises a page fault and the OS takes over.

Because the page size is a power of two, splitting is just taking bits: with 4 KB pages, the low 12 bits of the address are the offset and the remaining high bits are the page number. For an m-bit virtual address and a page size of 2ⁿ, the page number has m − n bits and the offset n bits.

Only the page number is translated. The offset is the position inside the page, and a page is copied into a frame as a whole, so the byte at offset d of the page is at offset d of the frame. The translation happens in hardware on every memory access; the OS is involved only when the page is not in memory.

  • m-bit address, 2ⁿ-byte pages → m − n page bits, n offset bits
  • The TLB caches recent translations so most lookups skip the page table
  • Large address spaces split the table into levels; see multilevel paging
3

When the Page Is Not in RAM

If the valid bit is 0, the MMU cannot finish the translation and raises a page fault. That is not an error: the address is legal, the page simply lives on disk. The OS finds a frame, reads the page in, marks the entry valid and re-runs the instruction. Loading pages only when they are first touched is demand paging, which has the full fault-handling sequence.

When no frame is free, the OS must evict a page, and choosing it is the job of a page replacement algorithm. The tracer below evicts the least recently used page.

  • Page fault: legal address, page on disk; the OS loads it
  • Illegal address: segmentation fault, the process is stopped
  • No free frame: evict a victim, writing it back first if it was modified
Key reference

Terms, operations, and practical uses

Terms to know

  • MMUThe memory management unit: hardware that translates every virtual address.
  • Page tablePer-process map from virtual page to frame, with a valid bit.
  • Page faultA trap when the page is legal but not in RAM.
  • Working setThe pages a process is actively using over a recent window.
Implementation

Translate six virtual addresses, with page faults

PAGE_SIZE = 1024

# Page table: virtual page -> frame, only for pages currently in RAM.
page_table = {0: 1, 1: 3, 4: 0}
free_frames = [2]
last_used = {page: 0 for page in page_table}  # for LRU replacement


def translate(address, clock):
    page, offset = divmod(address, PAGE_SIZE)
    fault = page not in page_table
    if fault:
        if free_frames:
            frame = free_frames.pop()
        else:
            # No free frame: evict the least recently used page.
            victim = min(page_table, key=last_used.get)
            frame = page_table.pop(victim)
            del last_used[victim]
        page_table[page] = frame  # the OS loads the page from disk here
    last_used[page] = clock
    frame = page_table[page]
    return page, offset, frame, frame * PAGE_SIZE + offset, fault


faults = 0
for clock, address in enumerate([1500, 4200, 6500, 7000, 3100, 200], start=1):
    page, offset, frame, physical, fault = translate(address, clock)
    faults += fault
    status = "PAGE FAULT" if fault else "hit"
    print(f"VA {address:>4} -> page {page}, offset {offset:>3} -> frame {frame} -> PA {physical:>4}  {status}")
print("page faults:", faults, "of 6 accesses")
#include <cstdio>
#include <map>
#include <vector>
using namespace std;

const int PAGE_SIZE = 1024;

// Page table: virtual page -> frame, only for pages currently in RAM.
map<int, int> pageTable = {{0, 1}, {1, 3}, {4, 0}};
map<int, int> lastUsed = {{0, 0}, {1, 0}, {4, 0}};  // for LRU replacement
vector<int> freeFrames = {2};

bool translate(int address, int clock, int& page, int& offset, int& frame) {
    page = address / PAGE_SIZE;
    offset = address % PAGE_SIZE;
    bool fault = pageTable.find(page) == pageTable.end();
    if (fault) {
        if (!freeFrames.empty()) {
            frame = freeFrames.back();
            freeFrames.pop_back();
        } else {
            // No free frame: evict the least recently used page.
            int victim = lastUsed.begin()->first;
            for (auto& [p, t] : lastUsed) {
                if (t < lastUsed[victim]) victim = p;
            }
            frame = pageTable[victim];
            pageTable.erase(victim);
            lastUsed.erase(victim);
        }
        pageTable[page] = frame;  // the OS loads the page from disk here
    }
    lastUsed[page] = clock;
    frame = pageTable[page];
    return fault;
}

int main() {
    int addresses[] = {1500, 4200, 6500, 7000, 3100, 200};
    int faults = 0, clock = 0;
    for (int address : addresses) {
        int page, offset, frame;
        bool fault = translate(address, ++clock, page, offset, frame);
        faults += fault;
        printf("VA %4d -> page %d, offset %3d -> frame %d -> PA %4d  %s\n", address, page, offset, frame,
               frame * PAGE_SIZE + offset, fault ? "PAGE FAULT" : "hit");
    }
    printf("page faults: %d of 6 accesses\n", faults);
    return 0;
}
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Main {
    static final int PAGE_SIZE = 1024;

    // Page table: virtual page -> frame, only for pages currently in RAM.
    static final Map<Integer, Integer> pageTable = new HashMap<>(Map.of(0, 1, 1, 3, 4, 0));
    static final Map<Integer, Integer> lastUsed = new HashMap<>(Map.of(0, 0, 1, 0, 4, 0));
    static final Deque<Integer> freeFrames = new ArrayDeque<>(List.of(2));

    public static void main(String[] args) {
        int[] addresses = {1500, 4200, 6500, 7000, 3100, 200};
        int faults = 0, clock = 0;
        for (int address : addresses) {
            clock++;
            int page = address / PAGE_SIZE, offset = address % PAGE_SIZE;
            boolean fault = !pageTable.containsKey(page);
            if (fault) {
                int frame;
                if (!freeFrames.isEmpty()) {
                    frame = freeFrames.pop();
                } else {
                    // No free frame: evict the least recently used page.
                    int victim = lastUsed.entrySet().stream()
                            .min(Map.Entry.comparingByValue()).get().getKey();
                    frame = pageTable.remove(victim);
                    lastUsed.remove(victim);
                }
                pageTable.put(page, frame); // the OS loads the page from disk here
                faults++;
            }
            lastUsed.put(page, clock);
            int frame = pageTable.get(page);
            System.out.printf("VA %4d -> page %d, offset %3d -> frame %d -> PA %4d  %s%n",
                    address, page, offset, frame, frame * PAGE_SIZE + offset, fault ? "PAGE FAULT" : "hit");
        }
        System.out.println("page faults: " + faults + " of 6 accesses");
    }
}
Watch it run

Step through it

Running on page size 1024; resident: page 0→F1, 1→F3, 4→F0; addresses 1500, 4200, 6500, 7000, 3100, 200

page size 1024 B · 8 virtual pages · 4 framespagevalidframe01F111F320disk30disk41F050disk60disk70diskphysical memoryframe 0 · 0–1023page 4frame 1 · 1024–2047page 0frame 2 · 2048–3071freeframe 3 · 3072–4095page 1disk (swap)every page lives here3 pages resident, 5 on disk, 1 free frame
Step 1

8 KB of virtual memory, 4 KB of RAM

The process sees 8 pages of addresses, but only 4 frames of physical memory exist. The page table records which pages are in RAM (valid = 1) and where; the other pages are on disk. Frame 2 is free.

Output
1 / 12
4

Solved Translation and Address Widths

  1. Given – page size 4 KB (4096 bytes); page table entry 4 → frame 7; virtual address 20000.
  2. Page number – 20000 ÷ 4096 = 4 (4 × 4096 = 16384).
  3. Offset – 20000 − 16384 = 3616.
  4. Frame – page 4 is in frame 7.
  5. Physical address – 7 × 4096 + 3616 = 28672 + 3616 = 32288.

Exam questions here usually ask for exactly this: split the address, look up the page, and rebuild the physical address. Show the division and the remainder separately so each step can be checked.

A related question asks for address widths. With a logical address space of 8 pages of 1024 bytes and 32 physical frames, the logical address needs log₂(8 × 1024) = 13 bits (3 page bits + 10 offset bits), and the physical address needs log₂(32 × 1024) = 15 bits (5 frame bits + 10 offset bits). The offset width is the same on both sides because pages and frames are the same size.

Address-width example: 8 pages × 1 KB, 32 frames
AddressSizeBitsSplit
Logical8 × 1024 = 8192 bytes133 page bits + 10 offset bits
Physical32 × 1024 = 32768 bytes155 frame bits + 10 offset bits
page size 4 KB = 4096 bytes; page table entry 4 → frame 7VA 20000virtual addresspage 420000 ÷ 4096offset 361620000 mod 4096table[4] = 7page table lookupframe 77 × 4096 = 28672offset 3616unchangedPA 32288physical addressoffset iscopied as isPA = frame × page size + offset = 28672 + 3616 = 32288
  • Offset bits = log₂(page size), the same on both sides
  • Page bits and frame bits can differ: virtual space can be larger or smaller than RAM
5

The Cost of a Fault

A RAM access takes about 100 ns; reading a page from disk takes milliseconds, tens of thousands of times longer. So virtual memory is only fast when faults are very rare, and it is rare faults that real programs deliver, because of locality of reference: they reuse a small set of pages for long stretches. The effective access time section of the demand paging lesson puts numbers on it.

When the pages a process is actively using, its working set, do not fit in the frames it has, it faults on almost every access and the CPU waits on the disk. That collapse is thrashing.

  • A fault costs milliseconds; a memory access costs nanoseconds
  • Locality keeps real fault rates tiny
  • Working set larger than the frames given → thrashing
6

Advantages and Disadvantages

The advantages of virtual memory go well beyond running large programs, which is why every general-purpose OS uses it. The costs are real too, and they are what the rest of this section of the course is about.

  • Larger than RAM: a program needs only its used pages in memory
  • Isolation: separate address spaces are the basis of process protection
  • Sharing: many processes map one copy of a library; copy-on-write makes fork() cheap
  • No contiguous RAM needed: any free frame can hold any page
  • Cost, hardware: needs an MMU and a TLB
  • Cost, memory: page tables take space, especially for large address spaces
  • Cost, speed: each fault is slow, and overcommitted memory thrashes