Repository navigation
Operating Systems 07 memory
Relevant source files
The following references were used as context for generating this wiki page:
- Wikipedia: Memory paging
- Wikipedia: Memory segmentation
- Wikipedia: Page table
- Wikipedia: Translation lookaside buffer
- Book: Silberschatz, Galvin and Gagne, Operating System Concepts, chapter 9
Many processes share one physical memory, but each one should see its own private memory starting at address 0, and none should be able to touch another's. The OS and the hardware memory management unit (MMU) achieve this by translating every address a program uses (a virtual or logical address) into a physical address in RAM. This page explains how that translation works.
Numbers and addresses on this page are illustrative; the worked arithmetic was checked with a short script.
This page covers logical versus physical addresses, contiguous allocation and fragmentation, paging, page tables (single-level, multi-level, inverted), the TLB with an effective-access-time calculation, and segmentation. Paging to disk, page faults and replacement are on Virtual Memory.
| Building | Memory |
|---|---|
| Each tenant calls their rooms "room 1, room 2, ..." | Each process uses its own virtual addresses from 0 |
| The building manager's list: "tenant A's room 1 is flat 37" | The page table |
| Rooms are all the same size | Pages and frames are all the same size |
| A tenant can't open a door that isn't on their list | Memory protection |
| The manager remembers the last few lookups | The TLB |
flowchart LR
CPU["CPU issues<br/>virtual address"] --> MMU["MMU<br/>(TLB + page table walk)"]
MMU -->|"physical address"| RAM["RAM"]
MMU -->|"not allowed / not present"| F["Fault to the kernel"]
| Logical (virtual) address | Physical address | |
|---|---|---|
| Seen by | The program | The memory chips |
| Range | Same for every process (e.g. 0 to 2⁴⁸) | Size of installed RAM |
| Translated by | The MMU, on every access |
The simplest scheme gives each process one contiguous block of physical memory, using a base register (where it starts) and a limit register (how big it is).
When processes come and go, free memory becomes scattered holes:
flowchart LR
A["P1<br/>100 KB"] --- H1["free 30 KB"] --- B["P2<br/>200 KB"] --- H2["free 50 KB"] --- C["P3<br/>80 KB"] --- H3["free 40 KB"]
A new 100 KB process cannot fit, even though 120 KB is free in total.
| Kind | What is wasted | Caused by | Fix |
|---|---|---|---|
| External fragmentation | Free memory split into holes too small to use | Variable-size allocation | Compaction (move processes), or paging |
| Internal fragmentation | Unused space inside an allocated block | Fixed-size allocation units | Smaller units |
| Placement rule | Picks | Note |
|---|---|---|
| First fit | The first hole big enough | Fast |
| Best fit | The smallest hole big enough | Leaves tiny useless holes |
| Worst fit | The largest hole | Leaves big holes, usually worse overall |
Paging removes external fragmentation by cutting both spaces into equal fixed-size pieces:
- virtual memory into pages,
- physical memory into frames (same size, commonly 4 KB),
and allowing any page to go in any frame. A process's pages need not be next to each other in RAM.
flowchart LR
subgraph V["Process virtual pages"]
v0["page 0"]
v1["page 1"]
v2["page 2"]
v3["page 3"]
end
subgraph PT["Page table"]
t0["0 → frame 5"]
t1["1 → frame 2"]
t2["2 → not present"]
t3["3 → frame 7"]
end
subgraph P["Physical frames"]
f2["frame 2"]
f5["frame 5"]
f7["frame 7"]
end
v0 --> t0 --> f5
v1 --> t1 --> f2
v3 --> t3 --> f7
Paging has no external fragmentation, but on average wastes half a page per region at the end (internal fragmentation).
A virtual address splits into a page number and an offset. With page size 2ᵏ bytes, the offset is the low k bits.
flowchart LR
VA["Virtual address"] --> PN["Page number<br/>(high bits)"]
VA --> OF["Offset<br/>(low k bits)"]
PN --> PT["Page table lookup"] --> FN["Frame number"]
FN --> PA["Physical address =<br/>frame number × page size + offset"]
OF --> PA
Worked example. Page size 4 KB = 4096 = 2¹², so the offset is the low 12 bits (3 hex digits).
| Step | Value |
|---|---|
| Virtual address | 0x3A7F |
Page number = 0x3A7F >> 12 |
3 |
Offset = 0x3A7F & 0xFFF
|
0xA7F |
| Page table says page 3 → frame 7 | 7 |
Physical address = 7 × 4096 + 0xA7F
|
0x7A7F |
| Bit or field | Meaning |
|---|---|
| Frame number | Where the page is in RAM |
| Valid / present | Is the page in memory? If not, a page fault (Virtual Memory) |
| Read / write / execute | Protection: a write to a read-only page faults |
| User / kernel | Can user mode access it? |
| Dirty | Written since loaded; must be saved before eviction |
| Accessed (referenced) | Used recently; helps replacement |
Sources: Wikipedia: Memory paging
A flat table needs one entry per virtual page:
32-bit addresses, 4 KB pages: 2^32 / 2^12 = 2^20 entries
× 4 bytes per entry = 4 MB per process
That is wasteful because most of the address space is unused. A multi-level (hierarchical) page table only builds the lower levels where memory is actually used.
flowchart LR
VA["Virtual address:<br/>L1 index | L2 index | offset"] --> R["Table base register<br/>(Arm TTBR, x86 CR3)"]
R --> L1["Level-1 table"]
L1 -->|"L1 index"| L2["Level-2 table<br/>(only exists if used)"]
L2 -->|"L2 index"| F["Frame number"]
F --> PA["+ offset = physical address"]
64-bit systems typically use 4 levels (48-bit addresses with 4 KB pages: 9 + 9 + 9 + 9 index bits + 12 offset bits). The cost is one memory access per level on every translation, which is why the TLB is essential.
| Type | Idea | Trade-off |
|---|---|---|
| Flat | One big array | Simple; huge for large address spaces |
| Multi-level | Tree of tables | Small for sparse address spaces; several memory accesses per walk |
| Hashed | Hash of page number → entry | Good for very large sparse spaces |
| Inverted | One entry per physical frame, holding (process, page) | Size depends on RAM, not address space; lookup needs a search or hash |
Sources: Wikipedia: Page table
The translation lookaside buffer is a small, fast cache of recent page-to-frame translations inside the MMU.
flowchart TD
VA["Virtual address"] --> T{"In TLB?"}
T -->|"hit (most accesses)"| PA["Physical address, no extra memory access"]
T -->|"miss"| W["Walk the page table in memory"]
W --> V{"Entry valid?"}
V -->|"yes"| U["Put translation in TLB"] --> PA
V -->|"no"| PF["Page fault → kernel"]
With a single-level page table, a TLB miss costs one extra memory access.
EAT = hit ratio × (TLB time + memory time) + miss ratio × (TLB time + 2 × memory time)
Memory access 100 ns, TLB hit ratio 90%:
| TLB lookup time | EAT |
|---|---|
| Ignored (0 ns) | 0.9 × 100 + 0.1 × 200 = 110 ns |
| 20 ns | 0.9 × 120 + 0.1 × 220 = 130 ns |
Without any TLB every access would cost 200 ns, so even a small TLB nearly halves the cost.
Different processes use the same virtual addresses for different data. On a switch the OS must either flush the TLB or tag each entry with an address-space ID (ASID on Arm, PCID on x86) so entries from different processes can coexist. Threads in the same process share the address space, so their switches keep the TLB.
Sources: Wikipedia: Translation lookaside buffer
Segmentation divides memory by meaning instead of fixed size: a code segment, a data segment, a stack segment, each with its own base, limit and permissions. An address is (segment, offset).
| Paging | Segmentation | |
|---|---|---|
| Unit | Fixed-size page | Variable-size segment |
| Visible to the programmer | No | Yes (logical divisions) |
| External fragmentation | No | Yes |
| Internal fragmentation | Yes, a little | No |
| Used today | Everywhere | Mostly historical; x86-64 keeps it only in vestigial form |
Sources: Wikipedia: Memory segmentation
- Paging removes external fragmentation but not internal.
- Physical address = frame × page size + offset; the offset is never translated.
- A TLB miss is not a page fault: a miss means "walk the table"; a fault means "the page is not present or not allowed".
- Page table size depends on the virtual address space; inverted tables depend on physical memory.
- Why do we need virtual memory addresses? Isolation (each process has its own space), relocation (load anywhere), and the ability to use more memory than RAM.
- Internal vs external fragmentation? Internal: unused space inside an allocated block. External: free memory split into holes too small to use.
- How is a virtual address translated with paging? Split into page number and offset; look up the page number in the page table (or TLB) to get the frame; physical address = frame × page size + offset.
- Why multi-level page tables? A flat table for a large, sparse address space is huge; multi-level tables only allocate the parts in use.
- What is a TLB and why does it matter? A cache of recent translations; without it every memory access would need extra accesses to walk the page table.
- Compute: 4 KB pages, address 0x3A7F, page 3 maps to frame 7. Physical 0x7A7F.
- The MMU translates virtual to physical addresses on every access, giving isolation and relocation.
- Paging uses fixed-size pages and frames, avoiding external fragmentation; page tables can be multi-level.
- The TLB caches translations; EAT = hit × (TLB + mem) + miss × (TLB + 2 × mem) for one level.
- 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