Virtual Memory
Imagine if every program needed to know exactly where in physical memory it would be stored - chaos! Virtual memory solves this by giving each program the illusion of having its own private, contiguous address space.
The Virtual Memory Concept
Virtual vs Physical Memory
+---------------------------------------------+
| |
| Program's View (Virtual) Actual (Physical)|
| +------------------+ +-----------+ |
| | Virtual Address | | Physical | |
| | Space | | Memory | |
| | | | | |
| | +--------------+ | MMU | +---------+| |
| | | Program A | |------->| | Page 0 ||| |
| | | (0x00000000) | | | | Page 3 ||| |
| | +--------------+ | | | Page 1 ||| |
| | +--------------+ | | | Page 7 ||| |
| | | Program B | | | | ... ||| |
| | | (0x00000000) | | | +---------+|| |
| | +--------------+ | +-----------+ |
+---------------------------------------------+
Both programs think they start at address 0x00000000,
but they're actually at different physical locations!
How Virtual Memory Works
Virtual memory works by breaking memory into fixed-size blocks called "pages" (typically 4KB):
- Page Tables: Each process has a page table mapping virtual to physical addresses
- MMU (Memory Management Unit): Hardware that translates addresses automatically
- Page Faults: When requested page isn't in RAM, the OS loads it from disk
- Page Replacement: When RAM is full, less-used pages are swapped to disk
Benefits of Virtual Memory
- Memory Protection: Programs can't accidentally access each other's memory
- Larger Address Space: Programs can use more memory than physically available
- Simplified Programming: Programmers don't worry about physical memory layout
- Efficient Memory Use: Only needed pages are loaded into RAM
- Process Isolation: Each process has its own address space
TLB: Translation Lookaside Buffer
Translating every memory access through page tables would be slow! The TLB is a special cache that stores recent address translations.
TLB Lookup Process
+---------------------------------------------+
| |
| CPU generates virtual address |
| | |
| v |
| +-------------+ |
| | TLB | |
| | (Cache of | |
| | recent | |
| | translations| |
| +------+------+ |
| | |
| +----+----+ |
| | | |
| v v |
| TLB Hit! TLB Miss! |
| | | |
| v v |
| Use Walk page |
| physical table in |
| address memory |
| | | |
| +----+----+ |
| | |
| v |
| Access physical memory |
+---------------------------------------------+