Virtual Memory
Virtual memory on one page: how the MMU turns a virtual address into a physical one, TLB hits and misses, a page fault step by step, the layout of a process’s address space, page table entry bits, and FIFO, LRU, Clock and LFU page replacement.
Cheat sheet · Offered as a template
In this diagram
- Virtual Memory
- Every process sees one private, contiguous address space. The MMU and the kernel map it onto real RAM a page at a time.
- ① Why virtual memory?
- Isolation: one process cannot read another’s memory
- Every program gets the same simple layout
- Programs can use more memory than there is RAM
- Pages load lazily, only when touched
- Shared libraries are mapped once and used by all
- ② Translating an address
- CPU
- Virtual address page # + offset
- In the TLB?
- Physical address frame # + offset
- RAM
- Walk the page table
- Page present?
- Page fault
- Swap or file
- A TLB hit costs about a nanosecond. A fault that reads from disk costs milliseconds: a million times slower.
- ③ A process’s address space
- high addresses
- Kernel space
- Stack ↓ grows down
- mmap: files, shared libraries
- Heap ↑ grows up
- Data + BSS: globals
- Text: code, read-only
- 0x0
- ④ Page replacement
- ⑤ Handling a page fault
- The CPU traps to the kernel with the faulting address
- Not a valid address? Send SIGSEGV
- Find a free frame, or evict one (write it back if dirty)
- Read the page from swap or its file
- Update the page table and the TLB
- Restart the instruction that faulted
- ⑥ A page table entry
- PTE bits (x86-64)
- ⑦ Paging or segmentation?
- Paging
- Fixed-size pages, 4 KB by default
- No external fragmentation