Swapping
Idea
- Swap frames between physical memory and disk
- Load data from swap back into memory on-demand
- If a process access a page that has been swapped out,
page fault occurs
- OS swap the frame back in,
insert it into the page table,
restart the instruction
Naive Example
- Suppose memory is full
- User opens a new program
- Swap out idle pages to disk
- If the idle pages are accessed, page them back in
Implementation
- Data strctures are needed to track the mapping between pages in memory and pages on disk
- Meta-data about memory pages must be kept
- When should pages be evicted
- Which page should be evicted
- OS's page fault handler must be modified
Page Table Entry

- P - Present bit - is in physical memory?
- 1 means the page is in physical memory
- 0 means the page is valid, but swapped to disk
- Attempts to access an invalid page or a page isn't present trigger a page fault
Handling Page Fault
- If the PTE is invalid, OS kill the process
- If the PTE is valid, but present = 0
1. OS swaps the page back into memory
2. OS updates the PTE
3. OS instructs the CPU to retry the instruction
When should the OS evict pages?
- On-demand approach
- If a page needs to be created and no free pages, swap a page to disk
- Proactive approach
- Maintain a small pool of free pages
- High watermark = threshold
- Once memory utilization crosses the high watermark, a background process starts swapping out pages
What pages should be evicted? = Page Replacement Policy
- The optimal eviction stragy
- Evict the page that will be accessed furthest in the future
- Unfortunately, impossible to implement (we don't know about the future)
- All memory accesses are to 100% random

- 80% memory accesses are for 20% of pages

- Sequential access in 50 pages, then loops

Implementing historical algorithms
- Record each access to the page table
- Additional overhead to page table lookups
- Approximate LRU with help from the hardware

- A - accessed bit - has been read recently?
- D - dirty bit - has been written recently?
- MMU sets the accessed bit when it reads a PTE
- MMU sets the dirty bit when it writes to the page
- OS may clear these flags
Approximating LRU
- On eviction, LRU needs to scan all PTEs to determine which have not been used
The Clock Algorithm
- If the access bit is 0, evict
else set the access bit to 0 and pass
- Incorporating the Dirty Bit
- When modified pages(Dirty bit is 1) are evicted,
dirty pages must always be written to disk (more expensive to swap)
- Evict the non-dirty pages first
RAM as cache
- High-speed cache for disk storage