Repository navigation
Operating Systems 08 virtual memory
Relevant source files
The following references were used as context for generating this wiki page:
- Wikipedia: Virtual memory
- Wikipedia: Page replacement algorithm
- Wikipedia: Bélády's anomaly
- Wikipedia: Thrashing (computer science)
- Wikipedia: Copy-on-write
- Book: Silberschatz, Galvin and Gagne, Operating System Concepts, chapter 10
Virtual memory lets a process use more memory than the machine has RAM. Only the pages a process is actually using need to be in RAM; the rest can stay on disk and are brought in when first touched. When RAM fills up, the OS chooses a page to push out. Page-fault counting with FIFO, LRU and optimal replacement is one of the most common OS interview problems.
All page-fault counts on this page were computed with a short script and the step tables were checked against it.
This page covers demand paging, what happens on a page fault, effective access time with faults, the replacement algorithms (FIFO, optimal, LRU, clock) with worked traces, Bélády's anomaly, thrashing and the working set, and copy-on-write and memory-mapped files. Address translation and the TLB are on Memory Management.
| Study | Virtual memory |
|---|---|
| Your desk holds 3 books | RAM holds a few frames |
| The bookshelf holds all your books | Disk (swap or the program file) |
| Fetching a book from the shelf | A page fault |
| Desk full: put one book back to make room | Page replacement |
| Which book to put back? | FIFO, LRU, optimal, clock |
| Constantly swapping books, never reading | Thrashing |
Pages are loaded only when a program first touches them. A page not in RAM has its valid/present bit clear in the page table.
sequenceDiagram
participant P as Process
participant M as MMU
participant K as Kernel
participant D as Disk
P->>M: access address in page 5
M-->>K: page fault (present bit = 0)
K->>K: is the address legal? if not: segmentation fault
K->>K: find a free frame (or evict a victim)
K->>D: read page 5 into the frame
Note over K,D: process blocked; another runs meanwhile
D-->>K: read done
K->>K: update page table: present, frame number
K->>P: restart the faulting instruction
| Kind of fault | Meaning | Cost |
|---|---|---|
| Minor (soft) | The page is already in RAM (e.g. shared library, page cache); just map it | Microseconds |
| Major (hard) | Must read from disk | Milliseconds on HDD; tens to hundreds of µs on SSD |
| Invalid | Address not part of the process at all | The process gets SIGSEGV
|
Sources: Wikipedia: Virtual memory
EAT = (1 − p) × memory access time + p × page-fault service time
Memory access 100 ns, fault service 8 ms (8,000,000 ns), fault rate p = 1/1000:
EAT = 0.999 × 100 + 0.001 × 8,000,000 = 99.9 + 8,000 ≈ 8,100 ns
One fault per thousand accesses makes memory about 80 times slower. To keep the slowdown under 10% (EAT ≤ 110 ns) the fault rate must be below about 1 in 800,000. That is why good replacement matters so much.
When a fault needs a frame and none is free, a victim page is chosen. If it is dirty it must first be written back to disk.
flowchart TD
F["Page fault"] --> Q{"Free frame?"}
Q -->|"yes"| L["Load page into it"]
Q -->|"no"| V["Choose victim (replacement algorithm)"]
V --> D{"Victim dirty?"}
D -->|"yes"| W["Write victim to disk"] --> L
D -->|"no"| L
L --> U["Update page tables, restart instruction"]
| Algorithm | Evicts | Notes |
|---|---|---|
| FIFO | The page loaded longest ago | Simple; ignores use; suffers Bélády's anomaly |
| Optimal (OPT / Bélády's MIN) | The page that will not be used for the longest time in the future | Fewest possible faults; needs the future, so only a benchmark |
| LRU | The page not used for the longest time in the past | Close to optimal in practice; exact LRU is expensive in hardware |
| Clock (second chance) | Sweeps frames like a clock hand; a page with its accessed bit set gets the bit cleared and a second chance | Cheap LRU approximation used by real kernels |
| LFU / MFU | Least / most frequently used | Rarely good on their own |
Reference string (12 references), 3 frames, all empty at the start:
7 0 1 2 0 3 0 4 2 3 0 3
In the tables, F marks a fault; the frame column shows the three frames' contents after each reference.
FIFO: 10 faults
| Ref | 7 | 0 | 1 | 2 | 0 | 3 | 0 | 4 | 2 | 3 | 0 | 3 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Frames | 7 | 7 0 | 7 0 1 | 2 0 1 | 2 0 1 | 2 3 1 | 2 3 0 | 4 3 0 | 4 2 0 | 4 2 3 | 0 2 3 | 0 2 3 |
| Fault | F | F | F | F | F | F | F | F | F | F |
LRU: 9 faults
| Ref | 7 | 0 | 1 | 2 | 0 | 3 | 0 | 4 | 2 | 3 | 0 | 3 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Frames | 7 | 7 0 | 7 0 1 | 2 0 1 | 2 0 1 | 2 0 3 | 2 0 3 | 4 0 3 | 4 0 2 | 4 3 2 | 0 3 2 | 0 3 2 |
| Fault | F | F | F | F | F | F | F | F | F |
Optimal: 7 faults
| Ref | 7 | 0 | 1 | 2 | 0 | 3 | 0 | 4 | 2 | 3 | 0 | 3 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Frames | 7 | 7 0 | 7 0 1 | 2 0 1 | 2 0 1 | 2 0 3 | 2 0 3 | 2 4 3 | 2 4 3 | 2 4 3 | 0 4 3 | 0 4 3 |
| Fault | F | F | F | F | F | F | F |
How to choose the victim at the reference to 3 (time 6, frames 2 0 1):
| Algorithm | Reasoning | Evicts |
|---|---|---|
| FIFO | 2 was loaded most recently, 0 and 1 earlier; 0 was loaded first | 0 |
| LRU | Last used: 2 at time 4, 0 at time 5, 1 at time 3 | 1 |
| OPT | Next use: 0 at time 7, 2 at time 9, 1 never in this string | 1 |
The full classic 20-reference string 7 0 1 2 0 3 0 4 2 3 0 3 2 1 2 0 1 7 0 1 gives:
| Frames | FIFO | LRU | OPT |
|---|---|---|---|
| 3 | 15 | 12 | 9 |
| 4 | 10 | 8 | 8 |
Sources: Wikipedia: Page replacement algorithm
flowchart TD
H["Look at frame under the hand"] --> A{"Accessed bit = 1?"}
A -->|"yes"| C["Clear it to 0 (second chance)<br/>advance hand"] --> H
A -->|"no"| E["Evict this page<br/>load new page here, advance hand"]
Hardware sets the accessed bit on every use, so the kernel gets an approximate "used recently" signal for free.
Normally more frames mean fewer faults. With FIFO that is not guaranteed:
Reference string 1 2 3 4 1 2 5 1 2 3 4 5
|
FIFO faults |
|---|---|
| 3 frames | 9 |
| 4 frames | 10 |
LRU and OPT never show this: they are stack algorithms, where the pages kept with n frames are always a subset of those kept with n + 1.
Sources: Wikipedia: Bélády's anomaly
If the processes together need more pages than there are frames, nearly every access faults; the system spends its time moving pages and CPU utilisation collapses. This is thrashing.
flowchart LR
A["More processes"] --> B["Fewer frames each"] --> C["More page faults"] --> D["CPU idle waiting for disk"]
D --> E["Naive scheduler sees low CPU use,<br/>admits even more processes"] --> A
The working set of a process is the set of pages it used in the last Δ references. If the sum of all working sets exceeds RAM, thrashing follows.
| Remedy | How |
|---|---|
| Working-set model | Keep each process's working set resident; suspend a process if they don't all fit |
| Page-fault-frequency control | Give more frames to processes faulting a lot, take frames from those faulting little |
| Reduce load | Swap out whole processes, or kill one (Linux OOM killer) |
| Add RAM | The real fix |
Sources: Wikipedia: Thrashing (computer science)
After fork, parent and child would each need a full copy of memory, but the child usually calls exec almost at once. Copy-on-write (COW) shares the pages, marked read-only, and copies a page only when one side writes to it.
flowchart TD
F["fork()"] --> S["Parent and child page tables point to<br/>the same frames, all marked read-only"]
S --> W{"Someone writes a page"}
W --> PF["Protection fault"]
PF --> C["Kernel copies just that page,<br/>gives the writer its own writable copy"]
This makes fork fast and is why counting fork calls says nothing about memory use. (Processes)
Sources: Wikipedia: Copy-on-write
mmap maps a file into the address space. Reading the memory faults pages in from the file, and dirty pages are written back to it. The same mechanism loads program code and shared libraries, and lets several processes share one physical copy of a library.
- OPT needs the future; use it only to compare other algorithms.
- On a tie, state your rule; with FIFO the victim is by load time, not last use.
- A page hit under FIFO does not change the queue order; under LRU it does.
- Bélády's anomaly affects FIFO, not LRU or OPT.
- More processes do not mean more throughput once the working sets exceed RAM.
- What is a page fault, step by step? The MMU finds the present bit clear and traps to the kernel; the kernel checks the address is valid, finds or frees a frame, reads the page from disk, updates the page table and restarts the instruction.
- FIFO vs LRU vs OPT? FIFO evicts the oldest loaded page, LRU the least recently used, OPT the one used furthest in the future. OPT is the lower bound; LRU is usually close.
-
What is Bélády's anomaly? More frames causing more faults, possible with FIFO; e.g.
1 2 3 4 1 2 5 1 2 3 4 5gives 9 faults with 3 frames and 10 with 4. - What is thrashing and how do you stop it? Constant paging because working sets exceed RAM; reduce the degree of multiprogramming, use working-set or fault-frequency control, or add memory.
-
How does copy-on-write make
forkcheap? Pages are shared read-only and copied only when written. - Why is LRU approximated rather than implemented exactly? Exact LRU needs an update on every memory access; the clock algorithm uses the hardware accessed bit instead.
- Demand paging loads pages on first use; a fault costs milliseconds, so fault rates must be tiny.
- FIFO, LRU and OPT give different fault counts; OPT is the minimum and LRU approximates it; FIFO can show Bélády's anomaly.
- Thrashing happens when working sets exceed RAM; copy-on-write and
mmapreuse the same paging machinery.
- Computer Architecture Overview
- Fundamentals: CPU, Memory and Instructions
- Pipelining
- Branches and Remedies
- Instruction-Level Parallelism
- Memory and Ordering
- Caches and Coherence
- Multicore
- Multithreading in Hardware
- SIMD and GPUs
- Glossary and Summary
- Hexagon Overview and Processor Properties
- ISA Fundamentals: Packets, Slots and Threads
- Registers
- Instruction Encoding and Mnemonics
- Data, Memory and Control Instructions
- Floating Point, HVX and Alignment
- Caches, MMU and Glossary
- Operating Systems Overview
- Processes
- Threads
- CPU Scheduling
- Synchronization
- Deadlock
- Memory Management
- Virtual Memory
- Files, Storage and I/O
- Kernel and System Calls
- Interview Q&A and Glossary
- C++ for LLVM Development: Overview
- C++ Basics
- Classes and RAII
- Ownership and Move Semantics
- Templates and Lambdas
- LLVM Data Structures (ADT)
- LLVM-Style RTTI: isa, cast, dyn_cast
- Errors, Output and Assertions
- Iterators and Ranges
- Building, Debugging and Exercises
- LLVM IR Overview
- Structure: Modules, Functions, Blocks and Values
- Type System
- Arithmetic, Bitwise and Cast Instructions
- Compare and Select
- Memory: alloca, load, store and getelementptr
- Control Flow: br, switch, ret and call
- SSA and Phi
- Control Flow Graph and Loops
- Dominance, Dominator Tree and Dominance Frontier
- Data-flow Analysis
- Writing an IR Pass
- Common Passes
- Exercises, Tooling and Glossary
- SelectionDAG Overview
- Pipeline, Phases and Traversal Orders
- Core Data Structures
- DAG Construction
- DAG Combiner
- Legalization
- Type Legalization
- Operation and Vector Legalization
- Instruction Selection
- TableGen Pattern Language
- Matcher Interpreter and Folding
- AArch64 Instruction Selection
- Scheduling and MIR Emission
- PHI Node Resolution
- AArch64 Walkthroughs
- Arithmetic and Data Movement
- Memory Instructions
- Control Flow and Calls
- End-to-End Example
- Tooling, Debugging and Extending
- Selector Comparison and Glossary
- Assignments: Build the Toy Backend
- Stage 1: Build Setup
- Stage 2: Target Registration
- Stage 3: TableGen Skeleton
- Stage 4: MC Layer for Assembly Output
- Stage 5: TargetMachine and Subtarget
- Stage 6: TargetLowering, Arguments and Returns
- Stage 7: Instruction Selection and the First Function
- Stage 8: Registers, Copies and Spills
- Stage 9: Frame Lowering
- Stage 10: Memory, Globals and Control Flow
- Stage 11: Calls
- Stage 12: Scheduling Model
- Stage 13: Object Files
- Stage 14: Capstone, a Complete Toy Backend
- Target Bring-up Overview
- Directory Layout, CMake and Registration
- The Target .td File
- TargetMachine and Subtarget
- TargetLowering Setup
- Calling Conventions
- Instructions and Instruction Selection
- Registers and Allocation Hooks
- Frame Lowering
- AsmPrinter and the MC Layer
- Scheduling
- A Minimal Toy Target
- Bring-up Checklist and AArch64 File Map
- Tooling and Glossary
- Calling Conventions Overview
- The CallingConv.td Language
- CCState and CCValAssign
- LowerFormalArguments
- LowerCall
- LowerReturn and CanLowerReturn
- Varargs, byval, sret and swifterror
- Tail Calls and Sibling Calls
- Custom Backend Guide and Checklist
- AArch64 Walkthroughs
- Tooling and Glossary
- Frame Lowering Overview
- MachineFrameInfo
- TargetFrameLowering Hooks
- The PEI Pass
- Callee-Saved Registers and Stack Layout
- Frame Index Elimination and the Register Scavenger
- Shrink Wrapping
- CFI and Unwind Information
- Custom Backend Guide and Checklist
- AArch64 Walkthroughs
- Tooling and Glossary
- MC Layer Overview
- Core Data Structures
- Streamers
- Assembler and Layout
- Fixups and Relocations
- Writing an MC Layer for a Custom Backend
- MCAsmInfo and the Instruction Printer
- Code Emitter
- AsmBackend and Object Writer
- Assembly Parser and Disassembler
- Bring-up Checklist and Common Failures
- Tooling and Glossary
- Register Allocation Overview
- The Register Allocation Pipeline
- Registers, Virtual Registers and Register Classes
- Liveness: Slot Indexes and Live Intervals
- Preparing Code for Allocation
- PHI Elimination and Two-Address Lowering
- Register Coalescer
- Allocation Framework
- The Register Allocators
- Fast Register Allocator
- Basic Register Allocator
- Greedy Register Allocator
- PBQP Register Allocator
- Spilling and Splitting
- Spill Weights and Copy Hints
- The Inline Spiller
- Live Range Splitting
- Rewriting and Post-RA Passes
- Writing Register Allocation Support for a Custom Backend
- Register Definitions in TableGen
- TargetRegisterInfo Hooks
- TargetInstrInfo Hooks
- Pass Pipeline Hooks
- Bring-up Checklist and Common Failures
- AArch64 Walkthroughs
- Tooling and Debugging
- Glossary and Where Do I Look