Virtual Memory & Demand Paging
Virtual memory lets a process use an address space larger than RAM. The trick is simple: load a page only when it is actually needed.
In plain English
Virtual memory is a bookshelf bigger than your desk. You keep only the pages you are reading on the desk.
By the end you will be able to
- Explain demand paging and the resident set.
- List the steps the kernel takes on a page fault.
- Know why locality makes demand paging work.
- Distinguish a page fault from an invalid access.
Demand paging
With demand paging, a process starts with few or no pages in memory. When it touches a page that is not present, the CPU raises a page fault. The kernel loads the page from disk or another backing store. Pages that are not being used can stay on disk, so the virtual address space can exceed physical memory.
The page-fault steps
The CPU traps to the kernel and saves the faulting address. The kernel checks that the address is valid. It finds a free frame or chooses a victim page. If the victim is dirty, it is written back. The requested page is read into the frame. The page table and TLB are updated, the faulting instruction is restarted, and the process continues. If the address is invalid, the kernel sends a segmentation fault instead.
1. trap: page not present
2. validate address
3. find free frame or evict victim
4. write back dirty victim
5. read page into frame
6. update page table and TLB
7. restart instructionLocality and the resident set
Demand paging works because programs exhibit locality: they reuse a small set of pages for a while. The set of pages a process is actively using is its resident set or working set. If the resident set fits in memory, page faults are rare. If it does not, the system may thrash.
Key takeaways
- Demand paging loads a page on first reference.
- A page fault traps to the kernel and may load a page from disk.
- The kernel validates the address before loading.
- The faulting instruction is restarted after the page is present.
- Locality keeps the resident set small.
Common pitfalls
- Thinking every page fault is a fatal error.
- Forgetting to write back a dirty victim page.
- Assuming the process restarts from the beginning instead of the faulting instruction.
Kernel notes
- List the page-fault steps in order.
- Explain valid versus invalid faults.
- Define the working set.
Quick check
1. What is demand paging?
2. What happens to the faulting instruction after the page is loaded?