Caching and virtual memory
On this page
Caches, demand paging and memory-mapped files, and how to choose which page to evict: FIFO, MIN, LRU, LFU and the clock algorithm. Ends with working sets, thrashing and Zipf workloads.
Caching basics
- Cache
- A copy of data that is faster to access than the original. A hit if the cache has a copy, a miss if it doesn't.
- Cache block
- The unit of cache storage (several memory locations).
- Temporal locality
- Programs tend to reference the same memory locations again: memory accessed recently is likely to be used again soon. Example: instructions in a loop.
- Spatial locality
- Programs tend to reference nearby locations. Example: data in a loop.
- Write-through
- Changes are sent immediately to the next level of storage.
- Write-back
- Changes stay in the cache until the cache block is replaced.
Cache lookup
- Fully associative: a block can go anywhere; check every entry.
- Direct mapped: each address can go in exactly one place, so there's no replacement choice.
- Set associative: each address maps to a small set of places.
Page colouring: when the cache is much bigger than a page (say an 8 MB cache and 4 KB pages), many pages map to the same cache lines – one in every 2K pages lands in the same place. The OS can assign physical pages so that a process's pages spread evenly over the cache.
Hardware translation as a power tool
Because the kernel can make the hardware trap on a read or write to selected addresses, it can implement: copy-on-write, fill on reference, zero on use, demand-paged virtual memory, memory-mapped files, and emulated modified and use bits.
Demand paging
Can we give the illusion of near-infinite memory with limited physical memory? Keep only the pages in use in memory, and bring others in from disk when referenced:
- TLB miss
- Page table walk
- Page fault (the page is invalid in the page table)
- Trap to the kernel
- Convert the virtual address to a file and offset
- Allocate a page frame, evicting a page if needed
- Start reading the disk block into the frame
- Disk interrupt when the DMA is complete
- Mark the page as valid
- Resume the process at the faulting instruction
- TLB miss
- Page table walk to fetch the translation
- Execute the instruction
Page faults are normal and happen all the time.
Evicting a page
- Select an old page to evict.
- Find all page table entries that refer to it (the frame may be shared), and set each one invalid.
- Remove any TLB entries that are copies of those entries.
- Write the page back to disk if it was changed.
Dirty and use bits
Each page table entry has bookkeeping bits, set by the hardware: modified (dirty) on a store, and recently used on every TLB miss. The kernel resets them when it writes the page to disk, or to track recent use. A physical page is modified if any page table entry pointing to it is modified. On MIPS it's simpler to keep these bits in the core map (the map of physical frames).
If the hardware has no modified bit, the kernel can emulate one: mark clean pages read-only; on the first write, trap, set the modified bit, mark the page read-write and resume. A recently-used bit can be emulated the same way by marking unused pages invalid. Either way, the kernel must track both the current permission and the true one.
Memory-mapped files
Two ways for an application to do file I/O:
- Explicit read/write system calls: data is copied into the process, the application works on it, and it is copied back to the kernel.
- Memory-mapped files (
mmap): open the file as a memory segment and use load and store instructions on it. A page fault brings in any part that isn't in memory yet.
Advantages of memory mapping:
- Simpler programming, especially for large files.
- Zero-copy I/O: data goes from disk straight into the page frame.
- Pipelining: the process can start before all pages are loaded.
- Interprocess communication: a shared memory segment instead of a temporary file.
Taken further, every segment of a process can be backed by a file: code by the executable, data, heap and stack by temporary files, shared libraries by their code file. That unifies memory management for the file buffer and process memory.
In the fileread_multi.c exercise, sequential reads take about the same time with fread and mmap. Random reads punish the system-call path, because every fseek, fread and write crosses into the kernel. All runs share the kernel's page cache, so a rerun is faster unless you drop the cache first.
First touch
Declaring a 256 MiB array only reserves virtual address space; the resident set (VmRSS) stays at a few MB. In firsttouch.c the first pass over the array is slow because every page faults and the kernel allocates and zeroes a fresh frame (zero-on-reference). VmRSS jumps to about 256 MB. The second pass is fast: every page is resident and writable.
Replacement policies
On a miss, which entry should be replaced? The goal is to reduce cache misses: improve the expected case, and reduce the chance of very poor performance.
- Random
- Replace a random entry.
- FIFO
- Replace the entry that has been in the cache longest. Worst case: a program striding through memory larger than the cache misses every time.
- MIN (optimal)
- Replace the entry that will not be used for the longest time into the future. Optimal (if you evict something used sooner, that triggers an earlier miss), but it needs to know the future.
- LRU (least recently used)
- Replace the entry not used for the longest time in the past. An approximation of MIN for programs with locality.
- LFU (least frequently used)
- Replace the entry used least often in the recent past.
How to count faults
Keep a row of frames. For each reference: if the page is there, it's a hit; if not, it's a fault, and if all frames are full you evict according to the policy.
- FIFO: evict the page that was loaded earliest. Hits do not change the order.
- LRU: evict the page whose last use is furthest back. Hits do count as use.
- MIN: look ahead and evict the page whose next use is furthest away (or never comes).
Worked example, 3 frames, references A B C A D B E F A C D (2025 exam):
| Ref | FIFO frames | LRU frames | MIN frames | |||
|---|---|---|---|---|---|---|
| A | A | fault | A | fault | A | fault |
| B | A B | fault | A B | fault | A B | fault |
| C | A B C | fault | A B C | fault | A B C | fault |
| A | A B C | hit | A B C | hit | A B C | hit |
| D | D B C | fault | A D C | fault | A B D | fault |
| B | D B C | hit | A D B | fault | A B D | hit |
| E | D E C | fault | E D B | fault | A E D | fault |
| F | D E F | fault | E F B | fault | A F D | fault |
| A | A E F | fault | E F A | fault | A F D | hit |
| C | A C F | fault | C F A | fault | C F D | fault |
| D | A C D | fault | C D A | fault | C F D | hit |
| Faults: FIFO 9, LRU 10, MIN 7 | ||||||
The frames are shown by slot; the evicted page is replaced in place.
Exercise string 7 0 1 2 0 3 0 4 2 3 0 3 2 1 2 0 1 7 0 1 with 3 frames gives FIFO 15, LRU 12, MIN 9 faults.
Belady's anomaly
With FIFO, more memory can mean more faults. The string 3 2 1 0 3 2 4 3 2 1 0 4 gives 9 faults with 3 frames and 10 with 4. MIN and LRU never behave this way (they have the stack property).
Clock and Nth chance
Exact LRU is expensive. The clock algorithm approximates it: periodically sweep through all pages; if a page is unused, reclaim it; if it is used, mark it unused. Linux's page cache approximates LRU this way.
Nth chance keeps an integer per page instead of one bit: the number of sweeps since last use.
if (page is used) {
notInUseSince = 0;
} else if (notInUseSince < N) {
notInUseSince++;
} else {
reclaim page;
}
Both can run in the page fault handler, or asynchronously in a thread that keeps a pool of recently unused clean pages (writing dirty ones back first). On a page fault, check the pool first.
Recap: MIN is optimal. LRU approximates MIN for programs with spatial and temporal locality. Clock and Nth chance approximate LRU.
Working sets and thrashing
The working set is the set of memory locations that must be cached for a reasonable hit rate. When a program runs in a loop, after some page faults it has its working set in memory and runs without faults.
Thrashing is when the cache is too small. If the sum of the working sets of all processes is larger than physical memory, processes keep stealing pages from each other: each one faults as soon as it runs. Many processes are running but the CPU does little useful work. Programs also show phase change behaviour: the working set changes over time.
Zipf workloads
Many systems don't follow the working set model. In a Zipf distribution the popularity of the k-th most popular item is about 1/kc, with 1 < c < 2. Examples: web pages, movies, library books, words in text, salaries, city populations. The common thread is that popularity is self-reinforcing. Caching helps with the popular items, but the long tail means the hit rate grows only slowly with cache size.
On earlier exams
- 2023, question 16 – Page replacement policies
- 2025, question 1 – Temporal locality
- 2025, question 15 – Write-through cache
- 2025, question 25 – Page replacement policies
- 2025, question 27 – Zero-on-reference and copy-on-write
Practise this topic in the quiz (12 questions)