Operating Systems · Lecture Notes
Chapter 9: Virtual Memory
A running program does not need all of its code and data at the same time. The error-handling code may never execute, a large array may be touched only in its first rows, and most menu options are never selected. Virtual memory exploits this observation: only the pages a process actually uses stay in physical memory, while the rest wait on disk or are never loaded at all. As a result a process can be larger than physical memory, more processes can run in the same memory, and programs start faster. These notes begin with the hardware and kernel mechanisms that make this work: the valid bit, the page fault, and instruction restart. The cost of a page fault is then measured with the effective access time, and copy-on-write and memory-mapped files are presented as two uses of the same mechanism. The longest part of the notes covers the page-replacement algorithms that decide which page to evict when memory is full. FIFO, OPT, LRU, second chance, clock, NRU, aging, the working set, and WSClock are all run step by step on the same reference string. The final sections cover frame allocation, thrashing, and design decisions such as page size. The buddy and slab allocators that the kernel uses for its own memory, together with today's Linux and Windows solutions, complete the chapter. All traces and numbers were checked by actually running the algorithms.
Learning outcomes
- Demand paging
- Explain the purpose of virtual memory; describe the valid–invalid bit, the steps of page-fault handling, and instruction restart.
- Performance
- Compute the effective access time from the page-fault probability; interpret the differences among HDD, SSD, and compressed swap.
- Copy-on-write and mmap
- Trace step by step how copy-on-write works after
fork()and how memory-mapped files relate to the page cache. - Page replacement
- Run FIFO, OPT, LRU, second chance, clock, NRU, aging, working-set, and WSClock by hand on a reference string; explain Belady's anomaly.
- Allocation and thrashing
- Compare equal and proportional allocation and local and global allocation; explain thrashing in terms of the working set and the page-fault frequency.
- Design and real systems
- Recognize the design issues of page size, TLB reach, program structure, page pinning, and the buddy and slab allocators, and the approaches of Linux (MGLRU, zswap) and Windows.
9.1Introduction to virtual memory
In a paged system a process sees its address space as a sequence of fixed-size pages, and each page occupies a frame in physical memory. Classical paging expects all of a process's pages to be in memory. Virtual memory lifts this requirement: some pages may stay in memory and others on disk, and the process still runs. This section first recalls the parts of paging we need, then explains why lifting the requirement is valuable.
9.1.1Background: paging and the TLB
Every address a process generates is a virtual address. The hardware splits it into two parts: the high-order bits form the page number p, and the low-order bits give the position inside the page, the offset d. With 4 KB pages the offset is 12 bits. The page table translates p into a frame number f; the offset is carried over to the physical address unchanged. The physical address is thus simply f and d written side by side.
Because the page table itself lives in memory, going to the table on every access would double the memory traffic. The TLB (translation lookaside buffer) prevents this. The TLB is a small, very fast cache that holds recently used page-to-frame mappings. Since programs touch only a few pages over short periods, the hit ratio is above 99%. On a miss the hardware walks the page table; on x86-64 this walk has 4 or 5 levels (Figure 9.1).
Besides the frame number, each page-table entry carries a few bits. The present (valid) bit says whether the page is in memory. The R (reference; accessed on x86) bit is set to 1 by the hardware whenever the page is accessed. The M (modified; dirty on x86) bit becomes 1 when the page is written. Protection bits specify write permission (R/W), user access (U/S), and the ban on executing code (NX). The R and M bits are the raw material of the replacement algorithms. An access to an entry whose present bit is 0 causes a page fault. If the page is not in memory, it is fetched from the backing store; if necessary it is loaded in place of a chosen victim page.
9.1.2Why virtual memory?
Looking at real programs, we see that a program is rarely used in its entirety. Code that handles error conditions does not run in most executions. Rarely used options and features occupy memory for nothing. Programmers allocate arrays for the worst case: a 100×100 table is often filled only up to 10×10. Even when the whole program is needed, it is not all needed at the same time.
The old solution was swapping: a process is either brought into memory as a whole or taken out to disk as a whole. For a large process this is very expensive, because its entire image is moved even if the process is about to use only a few of its pages.
Virtual memory is the technique that separates a process's logical memory from physical memory. The process sees a large, contiguous address space, of which only part is in physical memory. The process runs even when it is only partly in memory (Figure 9.2).
The benefits of this separation reach both the programmer and the system:
- A program is not limited by physical memory. On a 16 GB machine, processes whose virtual size exceeds 40 GB can run.
- Each process uses fewer frames, so more processes fit in the same memory. The degree of multiprogramming and CPU utilization rise.
- Less I/O is needed for loading and swapping: only the pages in use are read. Programs start faster.
- Page sharing becomes easier; the same frame can appear in the tables of several processes.
Before virtual memory, programs larger than physical memory were split into pieces by hand. In this older overlay method the programmer had to divide the program into parts that replace one another in memory and manage the loading personally. With virtual memory the operating system does the same job automatically, at page granularity.
9.1.3The virtual address space
The logical view of a process in memory is called its virtual address space. The process sees itself at contiguous addresses starting from 0. Physical memory, by contrast, consists of scattered frames, and the MMU maps between the two views.
The layout of the space follows the same logic on all Unix-like systems (Figure 9.3). At the bottom is the code (text), above it the initialized data and the zero-initialized bss section. The heap grows upward from there. The stack grows downward from the highest user address. In between lies the area where shared libraries and mmap regions are mapped. The remaining unused ranges are holes.
It matters that a hole consumes no frames. No physical memory is allocated for a page until the stack or heap grows into it. Such an address space, mostly unused, is called a sparse address space. The page table does not need entries for holes either; in a multilevel table, unused lower-level tables are never allocated.
Today's x86-64 processors use 48-bit virtual addresses; half of that, 128 TiB, is reserved for the user. With 5-level paging the virtual address grows to 57 bits. Address space layout randomization (ASLR) shifts the location of the regions randomly on every run. An attacker therefore cannot know the address of a library or of the stack in advance.
Virtual memory can be built in two ways. The universal one today is demand paging. Demand segmentation, which works with variable-size segments, is a historical approach; Burroughs computers and OS/2 used it. On Linux the regions of a process can be seen with cat /proc/self/maps. Each line of the output is a virtual memory area (VMA): a start and end address, the permissions, and the mapped file, if any.
9.1.4Shared pages and libraries
A side benefit of virtual memory is sharing. The same physical frame can appear in the page tables of several processes, and each process sees it wherever it likes in its own address space (Figure 9.4).
- Shared libraries (libc, libstdc++): the read-only code pages are mapped at their own address in each process, but there is a single physical copy. Even if a hundred processes use libc, the libc code sits in memory once.
- Interprocess communication through shared memory: two processes map the same region; what one writes, the other sees immediately.
fork(): when a child process is created, pages are shared, not copied. A copy is made only when one of them writes.
Writable data pages are private to each process. Sharing is safe because code pages are read-only: no process can modify the common copy.
9.2Demand paging
When a program is loaded from disk there are two options. The first is to read the whole program into memory up front; but if the user will use only a small part of it, this wastes time and memory. The second is to bring pages in only when they are needed. Virtual memory systems follow the second way.
9.2.1Lazy loading
In demand paging, no pages (or very few) are loaded when a process starts. A page is brought from disk into memory only at the moment it is accessed. A page that is never accessed is never loaded.
The payoff of this lazy approach is clear: less I/O, less memory, faster start-up, and more users in the same memory. The price is that every first access incurs a delay. An access falls into one of three cases:
- The address lies in none of the process's regions, so the access is invalid; the process is terminated.
- The address lies in a valid region and the page is in memory; the access proceeds normally.
- The address is valid but the page is not in memory; the page is brought in and the access is repeated.
The unit that does this job is called the pager. Older books also use the name lazy swapper, but it is misleading: a swapper moves the entire process, whereas a pager deals with individual pages (Figure 9.5).
The extreme form is called pure demand paging. The process is started with no pages in memory, so even the first instruction arrives with a page fault. During the first few hundred microseconds the faults come one after another. But as the process collects the pages it needs, the fault rate drops quickly. What makes this work is the locality of programs: over a short time a program works in a small region of its address space. Loops use the same code, arrays use neighboring addresses, and the stack uses its top few pages. Without locality every instruction would cause several page faults and demand paging would be useless.
9.2.2The valid–invalid bit
Demand paging works with a single bit in the page-table entry.
The valid–invalid bit is present in every page-table entry. v (valid) indicates that the page both belongs to the address space and is in memory. i (invalid) indicates that the page is either not in memory or does not belong to the address space at all.
The i bit covers two different situations. The hardware does not distinguish between them; it raises a trap in both. The operating system makes the distinction by consulting its own records, namely the VMA list. The example below traces this distinction step by step for a four-page region.
The process's VMA covers pages 0–3. Physical memory has six frames, numbered 0–5. The process first accesses page 2, then page 2 again, and finally page 6. What happens at each access?
- Initially. All four table entries are set to i; no frame has been allocated (Figure 9.6a).
- First access to page 2. The MMU sees i in entry 2 and raises a page-fault trap. The kernel verifies that the address is in a valid region (VMA 0–3). It reads the page into free frame 5, sets the entry to (5, v), and re-executes the instruction (Figure 9.6b).
- Second access to page 2. The entry is now valid. The translation is done directly and the mapping is also loaded into the TLB. No trap occurs.
- Access to page 6. The MMU raises a trap again. This time the kernel finds no region in the VMA list that covers page 6. This is an invalid reference; the kernel terminates the process with the
SIGSEGVsignal.
SIGSEGV.Thinking “invalid bit = bad access.” In demand paging the i bit usually means only “this page has not been loaded yet,” and the trap is a perfectly normal event. The process is terminated only if the kernel finds that the address belongs to no region or that the permissions were violated. The line int *p = NULL; *p = 5; is an example of the second case: page 0 is deliberately considered part of no region.
9.2.3Handling a page fault
A page fault is the trap the MMU raises when a page marked invalid in the page table is accessed. The trap hands control to the page-fault handler in the kernel.
Silberschatz's classic diagram describes the handling of a page fault in six steps (Figure 9.7). The process wants to load a value from address M, and the entry for M's page has the bit i.
- Reference. The MMU reads the entry and sees that the page is not in memory.
- Trap. The hardware switches to the kernel. The kernel checks whether the reference is valid; if it is not, it terminates the process.
- Page on the backing store. The location of the page on disk is found; it may be in swap space or in a file. A free frame is chosen.
- Fetch. The disk read is scheduled and the page is read into frame 7. Since the read can take milliseconds, the CPU is given to another process in the meantime.
- Update the table. Frame 7 is written into the entry and the bit is set to v.
- Restart. The instruction that caused the fault runs again from the beginning. The process continues as if the page had never been missing.
A page fault is a trap of the fault kind. For this kind, the saved program counter points to the instruction that caused the fault, not the next one. This is what makes it possible to re-execute the instruction. x86 processors also write the faulting virtual address into the CR2 register; the handler reads from it which page was requested.
One more detail concerns the free frame. If there is no free frame in the third step, a victim must be chosen. If the victim has been modified (is dirty), it is written to disk first. While the write is in progress the frame is marked “busy” so that another fault does not choose it as a victim too. Choosing the victim is the job of the page-replacement algorithms.
9.2.4Code trace: address translation and page fault
Address translation is done by hardware, but its logic can be written in a few lines of C. The function translate() below translates a virtual address into a physical address with 4 KB pages; on a TLB miss it goes to the page table and, if necessary, calls the page-fault handler.
int translate(int va) {
int p = va >> 12; /* page no */
int d = va & 0xFFF; /* offset */
int f = tlb_find(p); /* -1: miss */
if (f < 0) {
if (!pt[p].valid) /* not in memory */
page_fault(p); /* from disk */
f = pt[p].frame;
tlb_add(p, f);
}
pt[p].R = 1;
return (f << 12) | d;
}The first two lines split the address. va >> 12 shifts the address right by 12 bits to get the page number; va & 0xFFF isolates the low 12 bits, the offset. tlb_find(p) looks for the page in the TLB and returns −1 if it is not found. On a miss the if block runs: if the entry's valid bit is 0, page_fault(p) brings the page from disk and updates the entry. The frame is then read from the table and the mapping is added to the TLB. In every case the page's R bit is set to 1; the replacement algorithms use this bit. The last line shifts the frame number left by 12 bits and combines it with the offset.
Initially the TLB holds page 0 (frame 1) and page 1 (frame 4). Page 2 is in memory (frame 5) but not in the TLB. Page 3 is on disk. The function is called with three addresses in turn (Table 9.1).
| Call | p | d | TLB | Table | f | Result |
|---|---|---|---|---|---|---|
translate(0x2A10) | 2 | 0xA10 | miss | v, no page fault | 5 | (5 << 12) | 0xA10 = 0x5A10 |
translate(0x2B04) | 2 | 0xB04 | hit | not consulted | 5 | 0x5B04 |
translate(0x3008) | 3 | 0x008 | miss | i → page fault, (v, 7) | 7 | 0x7008 |
- 0x2A10. The high bits are 0x2 and the low 12 bits are 0xA10: p = 2, d = 0xA10. The TLB has no entry for p = 2, so
f = -1. Since the bit of entry 2 is v, the page-fault handler is not called. f = 5 is read from the table and (2, 5) is added to the TLB. The R bit becomes 1; the result is (5 << 12) | 0xA10 = 0x5A10. - 0x2B04. Another byte of the same page: p = 2, d = 0xB04. This time the TLB hits, the
ifblock is skipped, and the page table is never visited. The result is 0x5B04. Thanks to locality, the vast majority of accesses take this short path. - 0x3008. p = 3, d = 0x008. It is not in the TLB. The bit of entry 3 is i, so a page fault occurs. The kernel reads the page from disk into free frame 7; the process waits meanwhile. The handler sets the entry to (v, 7). When the instruction re-executes, f = 7 is read and added to the TLB; the result is 0x7008 (Figure 9.8).
Across the three translations there is 1 TLB hit and 2 misses; one of the misses turned into a page fault, that is, disk I/O. The function itself is O(1). The real cost lies in the table walk on a miss and, above all, in the disk read of the page fault. The two differ by several orders of magnitude.
9.2.5Timeline of a page fault
Textbooks describe a page fault in fifteen detailed steps. These steps group into three major costs: handling the trap (microseconds), reading the page (milliseconds on an HDD, 10–100 µs on an NVMe SSD), and restarting the process (microseconds). The timeline shows them in the rows of process A, the kernel, the disk, and process B (Figure 9.9).
- Steps 1–5. Trap to the kernel; the user registers and the process state are saved. The kernel recognizes that the interrupt is a page fault and that the reference is valid. The location of the page on disk is found.
- Steps 6–9. The read request is placed in the disk or SSD queue. The device is awaited; on an HDD, seek and rotational latency are added. Meanwhile the CPU is given to another process, B.
- Steps 10–13. The “I/O complete” interrupt arrives. B's state is saved and the interrupt is recognized as coming from the disk. The page table is updated and A is put on the ready queue.
- Steps 14–15. When A gets the CPU again, its registers and page table are loaded; the interrupted instruction runs again from the start.
The timeline shows one thing clearly: a page fault is a long wait for A but only a context switch for the system. The CPU is not wasted; B makes progress while the read is under way. But from A's point of view, a single memory access has become thousands of times longer than normal. The numerical measure of this difference is the effective access time.
9.2.6Instruction restart and kinds of faults
The ability to re-execute an instruction after a page fault is the only real feature demand paging asks of the hardware. A fault can occur while the instruction is being fetched or while an operand is being read. In most cases re-executing the instruction from the beginning is enough: the instruction has not yet changed anything.
The hard case is a fault that strikes after the instruction has already modified something. The IBM 360's MVC instruction moves a block of up to 256 bytes. If the source or destination block crosses a page boundary, the move can fault halfway through. If the blocks overlap, the source has already been corrupted and the instruction cannot simply be re-run. Autoincrement addressing creates a similar problem: the instruction has already incremented the register, so when it re-executes it starts from the wrong address.
On the Motorola 680x0 family, the instruction MOVE.L 6(A1),2(A0) is three words long. If a fault occurs while the second operand is being read, the program counter points somewhere inside the instruction. The operating system cannot tell where the instruction began. For this reason some processors copy the program counter into a hidden register before every instruction.
There are two kinds of solutions. The first is to probe both ends of the regions the instruction will touch before it starts; if a page is missing, the fault is taken before the instruction begins. The second is to keep modified values in temporary registers and restore the old state if a fault occurs. In today's processors precise exceptions guarantee this in hardware: at the moment of the fault, everything before the faulting instruction appears complete and everything after it appears never to have started.
Linux divides page faults into three kinds according to their consequences (Table 9.2). The distinction matters for performance, because only major faults require disk I/O.
| Kind | What happens? |
|---|---|
| Minor | The page is already in memory: in the page cache, in a shared library, as the zero page, or as a copy-on-write page. Only the table is updated; there is no I/O. |
| Major | The page must be read from disk or from swap. There is I/O and waiting. |
| Invalid | There is no region, or a permission was violated. The process receives SIGSEGV. |
On Linux it is easy to measure how many minor and major faults a program incurs:
$ /usr/bin/time -v ./prog | grep -i fault
$ ps -o min_flt,maj_flt -p PID
$ perf stat -e page-faults,major-faults ./prog/usr/bin/time -v prints the “Minor” and “Major page faults” lines at the end of the program. ps shows the counters of a running process. perf stat reads the kernel's event counters. When the same program is run a second time, the major-fault count is usually close to zero: the file pages read in the first run remain in the page cache and are matched by a minor fault.
9.2.7Where do pages come from?
To fetch the missing page, the page-fault handler must first know where the page comes from. Pages fall into three groups according to their source (Figure 9.10).
- File-backed pages: code, read-only data, and files mapped with
mmap. If the in-memory copy is clean, it is simply discarded; when needed, it is read again from the file. - Anonymous pages: heap, stack, and modified data. There is no file behind them. Before being dropped from memory they must be written to swap space, otherwise their contents would be lost.
- Zero-fill-on-demand pages: the first access to the bss section and to new heap pages is satisfied with a zeroed frame. Zeroing is a security requirement: the frame may previously have held another process's data.
Searching for a free frame at fault time wastes time. The operating system therefore keeps a free-frame pool, and the fault handler takes a frame from it. When the pool falls below a threshold, reclamation starts and pages are evicted to refill the pool. Swap space can be a separate disk partition or a file; on Linux, active swap areas are listed with swapon --show.
9.2.8The backing store
The backing store, or swap space, is the area on disk where the pages that are not in memory are kept.
There are two approaches to how space in swap is allocated (Figure 9.11).
- Static allocation. When the process starts, contiguous swap space as large as the whole process is set aside and its start address is recorded in the process table. The disk address of page k is computed as “base + k × page size.” Separate areas can be reserved for code, data, and stack; the stack, which can grow, then needs special handling.
- Dynamic allocation. No space is reserved in advance. When a page is written out to disk, a free slot is found and its address is stored in a per-page disk map. Unmodified code pages are never written to swap; when needed they are read again from the executable file.
The location of swap space can also vary. Linux traditionally uses a separate swap partition, but a swap file in the file system (swapfile) works too. Windows writes pages to the file pagefile.sys. A separate partition is slightly faster because it skips the file-system layer; a file is flexible because its size is easy to change.
9.3Performance: effective access time
Demand paging slows memory access on average. Most accesses run at normal speed, but the occasional page fault requires a trip to disk. The weighted average of the two tells how fast the system really is.
The effective access time (EAT) is the average memory access time that takes the page-fault probability into account. If the probability that an access causes a page fault is p (0 ≤ p ≤ 1) and the memory access time is ma, then:
EAT = (1 − p) × ma + p × page-fault time
The page-fault time is the sum of three parts: handling the trap, reading the page, and restarting the process. The first and last parts take microseconds. The read varies with the type of storage and is what determines the total. If p = 0 there are no faults and EAT = ma; if p = 1, every access is a fault. This calculation is for faults that fetch the page from disk or swap (major faults). If the page is already in memory (for example in the page cache or shared with another process) and only the page table needs updating, the fault is a minor fault; it completes in under a microsecond or a few microseconds and is much cheaper.
Memory access takes 100 ns, and the page-fault service time from a hard disk (HDD) is 25 ms. If one access in a thousand faults (p = 0.001), what is the EAT? By what factor does memory slow down?
- Units. 25 ms = 25,000,000 ns.
- Simplify. EAT = 100(1 − p) + 25,000,000 p = 100 + 24,999,900 p.
- Substitute. EAT = 100 + 24,999,900 × 0.001 = 100 + 24,999.9 = 25,099.9 ns ≈ 25 µs.
- Ratio. 25,099.9 / 100 ≈ 251. A single fault in a thousand accesses slows memory by a factor of about 251.
The result is striking. 99.9% of the accesses finish in 100 ns, but each of the remaining 0.1% takes 25 ms, so they dominate the average. The real question is therefore asked the other way around: if we accept a given slowdown, how high can the fault rate be?
In the same system we want the slowdown to be at most 10%. What is the largest possible p?
- Goal. A 10% slowdown means EAT < 110 ns.
- Inequality. 110 > 100 + 24,999,900 p → 10 > 24,999,900 p.
- Solution. p < 10 / 24,999,900 ≈ 4.0 × 10⁻⁷.
- Interpretation. 1 / (4 × 10⁻⁷) = 2,500,000: there must be fewer than one fault per roughly 2.5 million accesses.
That the fault rate can be kept this low is, once again, thanks to locality. But the result also shows that the system has no tolerance for mistakes in its replacement decisions.
As storage technology changes, so does the calculation. As of 2026, reading a page from an NVMe SSD takes 10–100 µs. In Linux's zram mechanism the page stays compressed in RAM; the “read” is a decompression and takes about 10 µs (Table 9.3, Figure 9.12).
| Storage | Fault time | EAT (p = 0.001) | Slowdown | p limit for 10% |
|---|---|---|---|---|
| HDD | 25 ms | 25,099.9 ns | ≈ 251× | 4,0 × 10⁻⁷ |
| NVMe SSD | 100 µs | 199.9 ns | ≈ 2× | 1,0 × 10⁻⁴ |
| zram | 10 µs | 109.9 ns | ≈ %10 | 1,0 × 10⁻³ |
The NVMe row is computed as follows: 0.999 × 100 + 0.001 × 100,000 = 99.9 + 100 = 199.9 ns. The 10% limit comes out as 10 / 99,900 ≈ 1.0 × 10⁻⁴. For zram, 99.9 + 0.001 × 10,000 = 109.9 ns.
Fast storage shrinks the fault penalty by two or three orders of magnitude: the HDD's 25 ms is 250 times NVMe's 100 µs and 2,500 times zram's 10 µs. Even so, memory is still hundreds of times faster, and the fault rate continues to determine the EAT. This is why replacement algorithms remain important today.
The 10th edition of Silberschatz does the same calculation with 200 ns memory and an 8 ms fault time. For p = 0.001, EAT = 200 × 0.999 + 8,000,000 × 0.001 = 199.8 + 8,000 = 8,199.8 ns ≈ 8.2 µs. This is a slowdown of 8,199.8 / 200 ≈ 41. The 10% limit follows from the inequality 220 > 200 + 7,999,800 p, giving p < 2.5 × 10⁻⁶.
Calculating without matching units. If 100 ns and 25 ms are added in the same formula without converting ms to ns, the result is meaningless. The conclusion “0.1% faults, hence 0.1% slowdown” for p = 0.001 is also wrong. The slowdown is determined not by the fault rate alone but by the product of the fault rate and the fault penalty.
9.4Copy-on-write
fork() creates a copy of the parent. In its naive form all of the parent's pages would have to be copied. Yet most children call exec() right after being created and throw all of those copies away. Virtual memory provides a way to avoid this waste.
9.4.1fork() and shared pages
In copy-on-write (COW), fork() does not copy the parent's pages. The parent and the child share the same physical pages; writable pages are marked read-only and COW in both. When either side writes to such a page, only that page is copied.
The mechanism rests on the protection bits. A write attempt to a read-only page causes a protection fault. When the kernel sees the COW mark in the entry, it understands that this is not a real violation. It takes a free frame, copies the page's contents into it, and maps the copy as writable for the writer. The write instruction then runs again (Figure 9.13).
fork(): the two processes share pages A, B, and C. On the right, after process 1 writes to C: only a copy of C has been made, and A and B remain shared.Pages that are never modified, such as code and read-only data, stay shared as long as both processes live. This is why calling exec() after fork() is almost free: only the page tables are copied, and exec() discards them too. The unit of sharing is neither a file nor a region but individual pages; only the page that is written gets copied.
The frame needed for the copy is taken from the pool of zero-filled pages. There is also vfork(). This call does not even copy the page table: the child uses the parent's address space directly, and the parent waits until the child calls exec() or _exit(). If the child modifies a variable in the meantime, the parent sees the change too; this is why vfork() is dangerous. Today posix_spawn() is preferred for starting a new program.
To manage sharing correctly, the kernel keeps a reference count for each frame: how many page tables map the frame. On a protection fault, if the reference count is greater than 1, a copy is needed. If the count is 1, the page now belongs to this process alone; no copy is needed and the page is simply made writable.
9.4.2Code trace: fork() and COW
The program below uses a global variable (data page D) and a heap buffer (heap page H). The child reads and modifies the variable, and the parent writes to the buffer.
int x = 1; /* data: D */
int main(void) {
char *b = malloc(4096); /* heap: H */
b[0] = 'a';
pid_t pid = fork();
if (pid == 0) { /* child */
printf("%d\n", x); /* read */
x = 2; /* write */
_exit(0);
}
wait(NULL);
b[0] = 'b'; /* parent */
return 0;
}The trace follows the page tables of the two processes and the reference counts of the frames step by step (Table 9.4).
| Step | Parent D, H | Child D, H | ref(f1), ref(f2) | Event |
|---|---|---|---|---|
b[0] = 'a' | f1 RW, f2 RW | — | 1, 1 | only the parent exists |
fork() | f1 RO, f2 RO | f1 RO, f2 RO | 2, 2 | only the tables are copied |
child printf | same | same | 2, 2 | read allowed, no fault |
child x = 2 | f1 RO, f2 RO | f3 RW, f2 RO | 1, 2 | protection fault; D is copied to f3 |
child _exit(0) | f1 RO, f2 RO | — | 1, 1 | f3 is freed |
parent b[0] = 'b' | f1 RO, f2 RW | — | 1, 1 | fault; ref = 1, no copy |
- Initially. The parent uses pages D and H as writable (RW);
b[0] = 'a'has already loaded H. fork(). The kernel copies only the page tables. D and H are marked read-only (RO) on both sides, and the reference counts of f1 and f2 become 2.- The child reads
x. Reading is allowed, so there is neither a fault nor a copy. 1 is printed. - The child writes
x = 2. Since D is read-only, a protection fault occurs. The kernel recognizes COW: it allocates f3, copies the contents of D into it, and maps it RW for the child. The reference count of f1 drops to 1. The parent'sxis still 1. - The child exits. Its mappings are removed, f3 returns to the free list, and the reference count of f2 drops to 1.
- The parent writes to H. A fault occurs because H is still marked read-only. But the reference count of f2 is 1, so no copy is needed; the page is simply made writable.
Over the whole program a single page was copied. The parent's page D is still marked RO. If the parent writes to D, one more fault occurs, but that too is resolved without a copy because the reference count is 1. The price of the method is one trap and one page copy for every shared page that is written. Its gain is that all the pages that are never written are never copied.
After fork(), the parent and the child share 100 pages. The child writes to 3 of them and then calls exec(). How many pages are copied?
- Pages written. Each write by the child hits a page whose reference count is 2: three protection faults, three copies.
- Pages read or never touched. They produce no copies.
exec(). It discards all of the child's mappings, copies included. The reference counts of the parent's pages drop to 1.- Result. 3 pages are copied. A naive
fork()would have copied 100 pages.
Assuming that every write produces a copy. What decides the copy is the current reference count of the frame being written. If, after the child has copied page A, the parent writes to A, the parent's frame now belongs to it alone and no copy is needed.
9.5Memory-mapped files
The usual way to read a file is through read() and write() calls. Each call is a system call and copies data between a kernel buffer and a user buffer. Virtual memory opens a second way: map the file into the address space and use it like memory.
9.5.1mmap() and mapping types
A memory-mapped file is a file whose pages are mapped into a region of a process's address space. In POSIX the mapping is established by mmap(). From then on the file is read and written not with read and write calls but with ordinary memory accesses.
The mapping itself reads nothing; it only creates a VMA. Pages are brought in on demand: the first access to each page produces a page fault. If the page is already in the page cache the fault is minor, otherwise it is major. Written pages become dirty and are written back to the file in the background or by a call to msync() or munmap() (Figure 9.14).
The flags of mmap() determine how the mapping behaves:
MAP_SHARED: changes are visible in the file and to everyone who maps the same file. Two processes can set up shared memory and communicate this way.MAP_PRIVATE: writes go to a private copy through copy-on-write, and the file does not change. The data section of executables is loaded this way: the program takes its initial values from the file and keeps its changes to itself.MAP_ANONYMOUS: a zero-filled region with no file behind it.malloc()allocates large blocks this way.
On Windows the same job is done by a mapping object created with CreateFileMapping and the MapViewOfFile call.
The advantage of memory mapping is that the copy disappears. The frame in the page cache is mapped directly into the process's address space; there is no second copy from the kernel buffer to the user buffer. The system-call cost is also eliminated for small, frequently read pieces. The price is that every new page produces a page fault and that I/O errors arrive as a signal (SIGBUS).
9.5.2Code trace: mmap
The program below maps a 12 KiB file as shared and writable, reads one byte, writes one byte, flushes the change to disk, and unmaps the file.
int fd = open("data.bin", O_RDWR);
struct stat st;
fstat(fd, &st); /* 12 KiB = 3 pages */
char *p = mmap(NULL, st.st_size,
PROT_READ | PROT_WRITE,
MAP_SHARED, fd, 0);
close(fd); /* mapping stays */
char c = p[0]; /* page 0 */
p[5000] = 'x'; /* page 1 */
msync(p, st.st_size, MS_SYNC);
munmap(p, st.st_size);The trace follows the page-table entries and the page cache together (Table 9.5).
| Line | p0 | p1 | p2 | Page cache | Event |
|---|---|---|---|---|---|
open, fstat | — | — | — | empty | size 12 KiB = 3 pages |
mmap | empty | empty | empty | empty | only the VMA is set up |
close(fd) | empty | empty | empty | empty | mapping remains |
c = p[0] | v | empty | empty | block 0 | fault, block 0 is read |
p[5000] = 'x' | v | v, M = 1 | empty | block 0, block 1 | fault, read, write |
msync | v | v, M = 0 | empty | block 0, block 1 | block 1 is written to the file |
munmap | — | — | — | block 0, block 1 | VMA is removed |
- Open. The file is opened, and
fstatreports that the size is 12 KiB, that is, 3 pages. mmap. Only a VMA is created; the table entries are empty and no page has been read.close(fd). It does not break the mapping, because the VMA holds its own reference to the file.p[0]. The first access to page 0 causes a page fault. Block 0 is read into the page cache (a major fault) and the entry becomes valid.p[5000]. 5000 / 4096 = 1 (integer division), so page 1; the offset is 5000 − 4096 = 904. Again there is a fault and a read, and then the write makes the page dirty (M = 1).msync. With theMS_SYNCflag the dirty page is written to the file, and the call does not return until the write finishes; M is cleared. Page 2 was never touched, so it was never read.munmap. The VMA is removed. The pages may stay in the page cache; if another process opens the file, it uses them with a minor fault.
munmap: the mapping of the virtual pages is gone, but block 0 and block 1 remain in the page cache. Block 2 was never read.Believing that data written through MAP_PRIVATE goes to the file at munmap time. In a private mapping the first write produces a protection fault and the kernel makes a private copy of the page. The change exists only in that process's address space and is lost at munmap. Another process that has mapped the same file with MAP_SHARED never sees this write either.
9.6Page replacement
In the description of demand paging we assumed that a free frame could be found at every page fault. In real systems memory is usually full. The reason is not waste but the opposite: idle RAM is wasted RAM. The operating system uses free memory as a page cache and takes it back only when needed. A page must therefore usually be evicted at fault time.
9.6.1When there is no free frame
With no free frame, the operating system has three options. Terminating the process is unacceptable: virtual memory must be invisible to the user. Swapping out an entire process is possible, but it is a heavy measure and is used under severe overload. The usual way is to replace a single page.
Page replacement means that, when there is no free frame, a page in memory (the victim) is chosen and evicted, and the requested page is loaded into its frame. The rule that chooses the victim is called the page-replacement algorithm.
Replacement adds five steps to the page-fault handler (Figure 9.16):
- The replacement algorithm chooses a victim frame.
- If the victim is dirty (M = 1), it is written to swap space or to its file. If it is clean, no write is needed; the copy on disk is already up to date. This halves the I/O.
- The victim's entry is made invalid and its mapping is removed from the TLB. On a multicore system the TLBs of the other cores must be flushed too; this is called a TLB shootdown.
- The requested page is read into the freed frame.
- The entry of the new page is made valid and the instruction that caused the trap is restarted.
The M bit gives an important saving here. A dirty victim costs two disk operations: one write and one read. A clean victim costs only the read. For this reason many algorithms prefer the clean one of two equally old pages.
A virtual memory system must answer two separate questions. Frame allocation: how many frames will each process get? Page replacement: which page will be evicted? This section deals with the second question. The goal of both is the same: to minimize the number of page faults and to keep the same page from moving back and forth between memory and disk again and again.
9.6.2Evaluating the algorithms
To evaluate an algorithm we run it on a sequence of memory accesses and count the page faults. Real address sequences contain millions of items, but the algorithm's decision depends only on the page number. The sequence can therefore be shortened.
A reference string is the sequence of page numbers a process accesses. The string is derived from an address trace: each address is converted to a page number, and consecutive references to the same page are counted once. This reduction does not change the result, because an access to a page immediately after the previous one never causes a fault.
The page size is 100 bytes. The address trace goes 0100, 0432, 0101, 0612, 0102, 0103, 0104, 0101, 0611, 0102, … What is the reference string?
- Page numbers. It is enough to divide the address by 100: 1, 4, 1, 6, 1, 1, 1, 1, 6, 1, …
- Dropping consecutive repeats. 0102, 0103, 0104, 0101 are all on page 1 and count as a single reference.
- Result. Silberschatz's entire trace reduces to the string 1 4 1 6 1 6 1 6 1 6 1.
In these notes the algorithms are run on Silberschatz's common string with 3 frames:
7 0 1 2 0 3 0 4 2 3 0 3 2 1 2 0 1 7 0 1
The string has 20 references and 6 distinct pages (7, 0, 1, 2, 3, 4). The first load of each distinct page is an unavoidable fault; no algorithm can therefore go below 6. As the number of frames grows, the number of faults is expected to fall (Figure 9.17). When the number of frames reaches 6, all pages fit and only the initial loads remain.
The values on the curves were checked by running the algorithms. It is striking that FIFO stays the same (15) at 2 and 3 frames: adding a frame gains nothing on this string. The algorithms to be run in this chapter are OPT, FIFO, LRU, second chance, clock, NRU, NFU and aging, the working set, and WSClock.
9.6.3FIFO
In the FIFO (first-in, first-out) algorithm, pages are kept in a queue in the order they were loaded. A newly loaded page is appended to the end of the queue. When room is needed, the page at the head of the queue, the one loaded earliest, is evicted.
FIFO is very easy to implement and requires no hardware bits. Its problem is that it never considers when a page was used. The oldest page may be the most heavily used one: if a variable loaded at the beginning is used throughout the run, FIFO still evicts it at the first opportunity.
The trace on the common string is as follows (Figure 9.18). The first three references (7, 0, 1) are loaded into free frames: 3 faults. The queue order is 7, 0, 1.
- Reference 4 (page 2). Fault. 7 at the head of the queue is evicted and 2 enters at the end. Queue: 0, 1, 2. Fault count 4.
- Reference 5 (0). In memory, a hit. In FIFO a hit does not change the queue.
- Reference 6 (3). Fault; 0 is evicted. Queue: 1, 2, 3. Faults 5.
- Reference 7 (0). Fault; 1 is evicted. 0 had been evicted one step earlier and is requested right back. Queue: 2, 3, 0. Faults 6.
- References 8–11 (4, 2, 3, 0). All four are faults. 2, 3, 0, and 4 are evicted in turn. Each will be needed again in the next steps. Faults 10, queue: 2, 3, 0.
- References 12, 13 (3, 2). Hits.
- References 14, 15 (1, 2). Fault; 2 and 3 are evicted. Faults 12, queue: 0, 1, 2.
- References 16, 17 (0, 1). Hits.
- References 18–20 (7, 0, 1). All three are faults; 0, 1, and 2 are evicted. 15 faults in total.
The order of the victims is 7, 0, 1, 2, 3, 0, 4, 2, 3, 0, 1, 2. This is exactly the load order: FIFO tracks loading, not access. Each step of the algorithm is O(1): whether a page is in memory is determined with a hash table, and the victim is found at the head of the queue.
9.6.4Belady's anomaly
It seems natural that page faults should decrease as the number of frames grows. In 1969 Belady, Nelson, and Shedler showed that this is not always true for FIFO.
Belady's anomaly is the phenomenon that, for some page-replacement algorithms, the number of page faults can increase when the number of frames increases.
The reference string is 1 2 3 4 1 2 5 1 2 3 4 5. How many faults does FIFO incur with 3 and with 4 frames?
- 3 frames, references 1–7. 1, 2, 3 are loaded into the free frames. When 4 arrives, 1 is evicted; when 1 arrives, 2 is evicted; when 2 arrives, 3 is evicted; when 5 arrives, 4 is evicted. All of the first seven references are faults.
- 3 frames, references 8–12. Memory holds {5, 1, 2}. 1 and 2 are hits. When 3 arrives, 1 is evicted; when 4 arrives, 2 is evicted. The final 5 is a hit. 9 faults in total.
- 4 frames, references 1–6. 1, 2, 3, 4 are loaded into the free frames; 1 and 2 are hits. 4 faults.
- 4 frames, references 7–12. When 5 arrives, the oldest page, 1, is evicted. Then the following 1 evicts 2; 2 evicts 3; 3 evicts 4; 4 evicts 5; and 5 evicts 1. All six are faults. 10 faults in total.
- Result. 4 frames incur 10 faults and 3 frames incur 9: more memory, more faults.
The cause of the anomaly is that, in FIFO, the memory contents for the two frame counts diverge from each other. After the 7th reference, the 3-frame memory holds {1, 2, 5} and the 4-frame memory holds {2, 3, 4, 5}. Page 1, which is in the small memory, is not in the large one. Because the next references are exactly 1 and 2, the small memory wins.
In some algorithms this divergence never happens.
Suppose that, at every moment, the set of pages in n frames is a subset of the set in n + 1 frames. Such an algorithm is called a stack algorithm. Stack algorithms do not exhibit Belady's anomaly: every fault with n + 1 frames is also a fault with n frames.
LRU is a stack algorithm. An LRU memory with n frames holds the n most recently used distinct pages. With n + 1 frames it holds the n + 1 most recently used distinct pages, and the first set is always contained in the second. OPT has the same property. On the same string LRU incurs 10 faults with 3 frames and 8 with 4 frames. FIFO, on the other hand, is not a stack algorithm; in this example the steps where the sets break the inclusion are the 7th, 8th, and 11th references.
Understanding Belady's anomaly as “FIFO always gets worse as frames are added.” The anomaly is seen only on certain strings and between certain frame counts. On the same string FIFO incurs 12, 12, 9, 10, 5 faults with 1, 2, 3, 4, 5 frames; the general trend is still downward. The anomaly says that FIFO cannot guarantee this decrease.
9.6.5OPT
The optimal algorithm (OPT or MIN) evicts the page that will be used latest in the future, or never. In 1966 Belady showed that this algorithm gives the fewest faults for a given string and number of frames.
OPT is easy to define but impossible to implement: the operating system cannot know which page a process will access in the future. This is why OPT is also called the “crystal ball” algorithm. It is still very valuable because it gives a lower bound. How close a new algorithm comes to OPT tells how good it is. In a real system OPT can be computed only by recording a trace and running it a second time; the first run is for learning the future.
The trace on the common string concentrates on the victim choices. At each fault, the next-use times (reference numbers) of the pages in memory are compared (Table 9.6).
| Reference no. | Requested | Next uses | Victim |
|---|---|---|---|
| 4 | 2 | 7 → 18, 0 → 5, 1 → 14 | 7 |
| 6 | 3 | 2 → 9, 0 → 7, 1 → 14 | 1 |
| 8 | 4 | 2 → 9, 0 → 11, 3 → 10 | 0 |
| 11 | 0 | 2 → 13, 4 → none, 3 → 12 | 4 |
| 14 | 1 | 2 → 15, 0 → 16, 3 → none | 3 |
| 18 | 7 | 2 → none, 0 → 19, 1 → 20 | 2 |
At reference 4, memory holds 7, 0, and 1. 0 is needed right away at the 5th reference, 1 at the 14th; 7 will be needed only at the 18th. The farthest one, 7, is evicted. At reference 11, page 4 will never be used again; if there is such a page, it becomes the victim immediately. Six replacements plus 3 initial loads give a total of 9 faults (Figure 9.20). This is the best value attainable for this string and 3 frames.
9.6.6LRU
OPT looks into the future. If the future cannot be known, the best guess is the recent past: by the principle of locality, a page that has not been used in the recent past will most likely not be used in the near future either. LRU turns this idea into a rule; in a sense it is OPT looking backward.
The LRU (least recently used) algorithm evicts the page that has gone unaccessed for the longest time. A last-use time is kept for each page, and the victim is the page whose last use is the oldest.
The trace on the common string starts the same as FIFO, but hits now change the order (Figure 9.21).
- References 1–3. 7, 0, 1 are loaded into the free frames. 3 faults.
- Reference 4 (2). 7, the least recently used, is evicted. Faults 4.
- Reference 5 (0). Hit; 0 is now the most recent page.
- Reference 6 (3). Memory holds 1, 2, 0; their last uses are at 3, 4, and 5. 1 is evicted. Faults 5. FIFO had evicted 0 here; LRU knows that 0 was just used.
- Reference 7 (0). Hit. LRU wins where FIFO faulted.
- References 8–11 (4, 2, 3, 0). All four are faults; 2, 3, 0, and 4 are evicted in turn. Faults 9. In these four steps the string asks every time for the page evicted one step earlier, and LRU does poorly too.
- References 12, 13 (3, 2). Hits.
- Reference 14 (1). 0 is evicted. Faults 10. Reference 15 (2) is a hit.
- Reference 16 (0). 3 is evicted. Faults 11. Reference 17 (1) is a hit.
- Reference 18 (7). 2 is evicted. Faults 12. References 19, 20 (0, 1) are hits.
LRU gives very good results in practice and is the target that many algorithms try to approximate. But it requires a record to be updated on every memory access. On a processor making billions of accesses per second, this cannot be done without hardware support. A warning about names: the algorithm that evicts the most recently used page is called MRU (most recently used). LRU evicts the oldest used one.
9.6.7Implementing LRU: counter and stack
There are two classical implementations of exact LRU.
Counter (timestamp). A logical clock that advances on every memory access is added to the CPU. On every access to a page, the value of the clock is written into that page's table entry. The victim is the page with the smallest timestamp. In this method the update is simple but frequent: every memory access means a write to the page table. Selection is expensive: the whole table must be scanned at every fault. Clock overflow also needs a solution.
Stack. Page numbers are kept in a stack. When a page is accessed, it is removed from the middle of the stack and put on top. The most recently used page is on top and the page unused for the longest time is at the bottom; the victim is the bottom one. The stack is implemented as a doubly linked list with head and tail pointers. Removing a node from the middle and adding it at the head takes at most six pointer changes. The victim is taken from the tail in O(1) and no search is needed.
The reference string is 4 7 0 7 1 0 1 2 1 2 7 1 2. How does the LRU stack change at each step? If a replacement were needed at the end of the string, which page would be evicted?
- 4, 7, 0. None of the three is on the stack; they are pushed on top in turn. Stack (top to bottom): 0, 7, 4.
- 7. It is on the stack; it is removed from the middle and put on top: 7, 0, 4.
- 1. New; on top: 1, 7, 0, 4.
- 0, 1. Both are moved to the top: first 0, 1, 7, 4; then 1, 0, 7, 4.
- 2. New; on top: 2, 1, 0, 7, 4.
- 1, 2, 7, 1, 2. All are on the stack and are moved to the top. Final state: 2, 1, 7, 0, 4.
- Result. At the bottom is 4: it has not been used since the first reference. In a replacement it would be evicted.
In the stack method the update is expensive and the selection cheap; in the counter method it is the reverse. Both demand work on every memory access, and neither is found in the hardware of any general-purpose processor today. In practice, algorithms that approximate LRU and rely on the R bit are used.
9.6.8Implementing LRU: the matrix method
Tanenbaum describes an elegant hardware solution for small numbers of frames. On a machine with n frames, the hardware maintains an n × n bit matrix. Initially all bits are 0.
The LRU matrix method: when frame k is accessed, first all bits of row k are set to 1, then all bits of column k are set to 0. At any moment, the smaller the binary value of a row, the longer that frame has gone unused. The victim is the row with the smallest binary value.
It is easy to see why the method works. An access to k makes row k “newer than everyone”: in row k every bit except its own column is 1. At the same time, bit k of every other row becomes 0, which records “I am not newer than k.” If bit j of row i is 1, then i was used more recently than j.
4 frames; access order 0 1 2 3 2 1 0 3 2 3. What are the binary values of the rows after each access and (once the frames are full) the LRU frame?
- 0. Row 0 = 1111, then column 0 is cleared: row 0 = 0111 = 7. The other rows are 0. Values 7, 0, 0, 0; the smallest rows are 1, 2, 3 (tied). While free frames exist no victim is chosen; these values only show the order.
- 1. Row 1 = 1011 = 11; bit 1 of row 0 is cleared: 0011 = 3. Values 3, 11, 0, 0 → smallest row 2 (free frames exist, no victim is chosen).
- 2. Row 2 = 1101 = 13; row 0 = 0001 = 1, row 1 = 1001 = 9. Values 1, 9, 13, 0 → smallest row 3 (free frame exists, no victim is chosen).
- 3. Row 3 = 1110 = 14; the last bit of the others is cleared: 0, 8, 12. Values 0, 8, 12, 14. The frames are now full → LRU (the victim) is 0.
- Remaining accesses. 2 → 0, 8, 13, 12 (LRU 0); 1 → 0, 11, 9, 8 (LRU 0); 0 → 7, 3, 1, 0 (LRU 3); 3 → 6, 2, 0, 14 (LRU 2); 2 → 4, 0, 13, 12 (LRU 1); 3 → 4, 0, 12, 14 (LRU 1).
To verify the final state it is enough to look at the order of use. The last accesses are, in order, 3 (tenth), 2 (ninth), 0 (seventh), and 1 (sixth). The row values from largest to smallest are 14, 12, 4, 0, that is, 3, 2, 0, 1. The matrix encodes the exact LRU order. Its cost is n² bits: for 4 frames 16 bits is no problem, but on a machine with millions of frames the method is unusable.
9.6.9Second chance
There is no hardware for exact LRU, but nearly all processors keep the R bit. The R bit tells whether the page has been used since it was last cleared. It does not give the order of use, but it answers the question “was it used recently?” FIFO's biggest flaw is precisely that it does not ask this question.
The second-chance algorithm looks at the R bit of the page at the head of the FIFO queue. If R = 0, the page is both old and unused and is evicted at once. If R = 1, the bit is cleared, the page is moved to the end of the queue as if it had just been loaded, and the search continues.
In Tanenbaum's example, eight pages A to H are in FIFO order; their load times are 0, 3, 7, 8, 12, 14, 15, 18. The R bits are A = 1, B = 0, C = 1, D = 0, E = 1, F = 0, G = 1, H = 1. A page fault occurs at time 20. Which page is evicted?
- A at the head. R = 1: it was used recently. It is not evicted; its R is set to 0 and it is moved to the end of the queue as if its load time were 20.
- New head B. R = 0: both old and unused. This is the victim.
- Result. B is evicted, and the new page I is added to the end of the queue with R = 1. The queue is now C, D, E, F, G, H, A, I (Figure 9.24).
What happens if the R bits of all pages are 1? The algorithm goes around once, clearing every page's R and moving it to the end. When the round ends, the page at the head is again the first page and its R is now 0; it is evicted. In this case second chance behaves like pure FIFO. The algorithm always terminates, because in the worst case after one round every R bit is 0.
The weakness of second chance lies in the implementation: pages are constantly moved in the list. These moves are unnecessary work, and the same decision can be made more cheaply.
9.6.10The clock algorithm
The clock algorithm makes the same decision as second chance but does not move pages. The frames are kept in a circular list and a hand (pointer) points to the oldest page. At fault time, if the R of the page the hand points to is 0, that page is evicted and the hand advances by one. If R = 1, R is cleared, the hand advances, and the search continues (Figure 9.25).
The R bit of a page that is loaded or accessed is set to 1 by the hardware. The hand moves only at fault time; on hits it stays put. The hand circulates not through the page table but through the frame list: it walks over the physical frames in order.
On the common string the clock algorithm works as follows. The first three references load 7, 0, 1 into frames 0, 1, 2; all three have R = 1 and the hand points to frame 0 (Table 9.7).
| Reference no. | Requested | R cleared | Victim | Fault |
|---|---|---|---|---|
| 4 | 2 | 7, 0, 1 | 7 | 4 |
| 6 | 3 | 0 | 1 | 5 |
| 8 | 4 | 2, 0, 3 | 2 | 6 |
| 9 | 2 | — | 0 | 7 |
| 11 | 0 | 3, 4, 2 | 3 | 8 |
| 12 | 3 | — | 4 | 9 |
| 14 | 1 | 2, 0, 3 | 2 | 10 |
| 15 | 2 | — | 0 | 11 |
| 16 | 0 | — | 3 | 12 |
| 18 | 7 | 1, 2, 0 | 1 | 13 |
| 20 | 1 | — | 2 | 14 |
- Reference 4 (2). 7, 0, and 1 all have R = 1. The hand clears the R of all three, makes a full circle, and comes back to frame 0, to 7. The R of 7 is now 0, so 7 is evicted. Since all the R bits were 1, the clock behaved like FIFO here.
- Reference 5 (0). Hit; the hardware sets the R of 0 to 1, and the hand does not move.
- Reference 6 (3). The hand is at frame 1, on page 0. Since R = 1, 0 gets a second chance. The hand moves to page 1 in the next frame; its R is 0, and 1 is evicted. FIFO had evicted 0 here.
- Reference 9 (2). Page 0, whose R was cleared in the previous scan and which has not been used since, immediately becomes the victim. The clock's weakness shows here: 0 will be requested again soon, at the 11th reference.
- Result. 14 faults in total: one fewer than FIFO (15), two more than LRU (12).
The clock algorithm is a rough approximation of LRU: it asks only “has it been used since the last scan?” In return, it does no work at all on a hit, and on a fault it usually finds a victim in a few steps. This cheapness has made it the foundation of real systems.
9.6.11Code trace: the clock algorithm
The code below implements the clock algorithm together with the M bit. frm is the frame array, hand is the clock hand, and N is the number of frames.
int pick_victim(void) {
while (frm[hand].R == 1) { /* 2nd chance */
frm[hand].R = 0;
hand = (hand + 1) % N;
}
int k = hand; /* victim */
hand = (hand + 1) % N;
return k;
}
void fault(int p) {
int k = pick_victim();
if (frm[k].M) write_back(k); /* dirty */
frm[k].page = p; frm[k].R = 1;
frm[k].M = 0;
}The while loop in pick_victim() runs as long as the R of the frame under the hand is 1: it sets R to 0 and advances the hand by one (% N makes the advance circular). The loop ends at the first frame with R = 0. That frame is the victim, and the hand moves on to the next one. If the victim is dirty, fault() first writes it to disk; then it places the new page with R = 1, M = 0.
The initial state of the four frames is as follows: frame 0 holds s3 (R = 1, M = 0), frame 1 holds s8 (R = 0, M = 1), frame 2 holds s5 (R = 1, M = 0), frame 3 holds s6 (R = 1, M = 1). The hand is at frame 2. A fault occurs first for page 9, then for page 4 (Table 9.8).
| Step | hand | Page in frame | R | Decision |
|---|---|---|---|---|
| fault(9) | 2 | s5 | 1 | R ← 0, hand to 3 |
| 3 | s6 | 1 | R ← 0, hand to 0 | |
| 0 | s3 | 1 | R ← 0, hand to 1 | |
| 1 | s8 | 0 | victim k = 1, hand to 2; M = 1 → write to disk; s9 is loaded | |
| fault(4) | 2 | s5 | 0 | victim k = 2, hand to 3; M = 0 → no write; s4 is loaded |
On the first fault the hand makes a full circle. s5, s6, and s3 were used recently and get a second chance. The R of s8 is 0, but its M bit is 1: the copy in memory is not on disk. Before being evicted it is written to disk, which is an extra I/O. s9 is loaded into frame 1 with R = 1, M = 0.
On the second fault the hand is at frame 2. The R of s5 was reset in the previous round and it has not been used since. The victim is found immediately. s5 is clean and the copy on disk is up to date; no write is needed, and a clean victim is cheaper. In the final state the frames are (s3, 0, 0), (s9, 1, 0), (s4, 1, 0), (s6, 0, 1); the hand waits at frame 3 (Figure 9.27). Over the two faults, 3 R bits were reset and 1 disk write was performed.
In the worst case pick_victim() takes N + 1 steps: if all R bits are 1, the hand makes a full circle and ends where it started. On average it is much shorter. When memory is very large, even a single hand completes its circle very late; the solution to this problem is the two-handed clock.
9.6.12NRU
The clock algorithm looks only at the R bit. Yet evicting the clean one of two equally old pages saves a disk write. NRU uses the two bits together.
In the NRU (not recently used) algorithm, each page has R and M bits. A clock interrupt clears the R bits periodically. Pages fall into four classes: class 0 = (R, M) = (0, 0), class 1 = (0, 1), class 2 = (1, 0), class 3 = (1, 1). At fault time, a page is evicted from the lowest nonempty class.
The class number is 2R + M; the R bit weighs more. This choice is deliberate: evicting a clean page that was used recently is worse than writing out an unused dirty page. At first sight class 1 may look impossible: how can a page be modified without being used? It was modified, but then a clock tick cleared its R. M, on the other hand, is not cleared by the tick, because it tells whether the page has to be written to disk.
The difference between NRU and LRU is one of detail. LRU tracks the exact order of use. NRU asks only two questions: was it used in the last clock interval, and is it dirty? The result is crude but cheap. Which page to choose within a class is undetermined; in these notes the one loaded earliest is chosen on a tie.
Common string, 3 frames. The 2nd, 6th, 9th, and 15th references are writes (0*, 3*, 2*, 2*). A clock tick arrives every 4 references and clears all the R bits. How many faults and how many dirty writes does NRU incur?
- References 1–3. 7, 0*, 1 are loaded. Because 0 was loaded by a write, M = 1.
- Reference 4 (2). Classes: 7 → 2, 0 → 3, 1 → 2. The lowest class, 2, contains 7 and 1; the one loaded earliest, 7, is evicted. Then the tick: all R bits are 0.
- Reference 6 (3*). Because 0 was just read, R = 1. Classes: 2 → 0, 0 → 3, 1 → 0. The earliest one in class 0, 1, is evicted.
- Reference 8 (4). Classes: 2 → 0, 0 → 3, 3 → 3. 2 is evicted; then the tick.
- Reference 9 (2*). The tick has cleared the R bits: 4 → 0, 0 → 1, 3 → 1. 4 is evicted. 0 and 3 are dirty but unused.
- Reference 14 (1). Classes 2 → 3, 0 → 1, 3 → 1. The earliest one in class 1, 0, is evicted; since it is dirty, it is first written to disk (write 1).
- Reference 16 (0). 2 → 3, 1 → 2, 3 → 1. 3 is evicted and written (write 2); then the tick.
- Reference 18 (7). 2 → 1, 1 → 2, 0 → 0. 0 is evicted; this time it is clean because it came back by a read.
- Reference 19 (0). 2 → 1, 1 → 2, 7 → 2. The dirty 2 is evicted and written (write 3).
- Result. 11 faults, 3 dirty-page writes.
NRU's 11 faults are fewer than LRU's 12. This does not mean that NRU is better than LRU. The result of algorithms based on the R and M bits depends on where the ticks fall and on the tie-breaking rule. On a single short string the share of luck is large.
9.6.13Enhanced clock
NRU's class idea can be combined with the circular list of the clock algorithm. Silberschatz calls this algorithm enhanced second chance; older versions of macOS used it too.
The enhanced clock algorithm makes two kinds of passes at fault time. Pass 1: starting from the hand, look for a page of class (0, 0); the bits are not touched. Pass 2: look for a page of class (0, 1); the hand sets the R of every page it passes to 0. If pass 2 also fails, go back to pass 1. Because all R bits are now 0, a victim is certain to be found by the end of the search.
The algorithm has no clock tick; the R bits are cleared only as the hand passes. The trace with the common string and the same writes is as follows:
- Reference 4 (2). Memory holds 7 (1, 0), 0 (1, 1), 1 (1, 0) and the hand is at frame 0. Pass 1 finds no (0, 0). Pass 2 finds no (0, 1) either, but as the hand passes it clears all the R bits. In pass 1 again the hand is on 7, and 7 is now (0, 0): 7 is evicted.
- Reference 6 (3*). 2 (1, 0), 0 (1, 1), 1 (0, 0); the hand is at frame 1. In pass 1 it passes 0 and finds 1 at (0, 0): 1 is evicted.
- Reference 8 (4). Pass 1 and pass 2 both fail; pass 2 clears all the R bits. In pass 1 again, 2 is found at (0, 0): 2 is evicted.
- Reference 9 (2*). Memory holds 4 (1, 0), 0 (0, 1), 3 (0, 1). Pass 1 finds no (0, 0). Pass 2 finds 0, under the hand, at (0, 1): 0 is evicted and first written to disk (write 1).
- Later faults. At the 11th reference 4 is evicted, at the 14th 0, at the 16th the dirty 3 (write 2), at the 18th the dirty 2 (write 3).
- Result. 11 faults, 3 dirty writes (Figure 9.29).
The result is the same as NRU's, but the victims differ: NRU evicts 7, 1, 2, 4, 0, 3, 0, 2, while the enhanced clock evicts 7, 1, 2, 0, 4, 0, 3, 2. The difference arises at the 9th reference. In NRU a tick has cleared all the R bits and 4 is in class 0. In the enhanced clock, the R of 4 is still 1, and the dirty but unused 0 is chosen. The price is scanning memory several times on one fault.
9.6.14NFU and aging
The R bit remembers only the last interval. A longer history can be kept in software.
In the NFU (not frequently used) algorithm, each page has a software counter. At every clock tick, the current R bit is added to the counter (counter += R) and R is cleared. At fault time, the page with the smallest counter is evicted.
NFU's flaw is that it never forgets. A page heavily used in the first phase of the program accumulates a high counter. Even if the program moves to another phase and never touches that page again, its counter stays high and the page continues to stay in memory. The counter records the number of uses, not the time of use. A small change fixes this flaw.
In the aging algorithm, at every tick the counter is first shifted right by one bit, and then the R bit is added at the left, that is, at the most significant bit. Thus recent use weighs more heavily in the counter. At fault time, the page with the smallest counter is evicted.
In Tanenbaum's example there are six pages (0–5) and 8-bit counters; the counters start at 0. The R bits seen at five ticks (for pages 0 to 5) are: tick 0: 1 0 1 0 1 1, tick 1: 1 1 0 0 1 0, tick 2: 1 1 0 1 0 1, tick 3: 1 0 0 0 1 0, tick 4: 0 1 1 0 0 0. What are the final counters, and which page is evicted?
- Tick 0. The counters of the pages with R = 1 become 10000000: pages 0, 2, 4, 5. The others are 00000000.
- Tick 1. First the shift, then R: page 0 → 11000000, 1 → 10000000, 2 → 01000000, 3 → 00000000, 4 → 11000000, 5 → 01000000.
- Ticks 2–3. The same operation: at the end of tick 3, 11110000, 01100000, 00010000, 01000000, 10110000, 01010000.
- Tick 4. 01111000 (120), 10110000 (176), 10001000 (136), 00100000 (32), 01011000 (88), 00101000 (40).
- Decision. The smallest value is 32: page 3 is evicted.
Comparing pages 3 and 5 shows the logic of aging. Neither was used in the last two ticks. Page 3 was last used at tick 2 (00100000); page 5 was also used at tick 2, but additionally at tick 0 (00101000). When the recent past is equal, the longer history decides.
Aging approximates LRU well, but it differs in two ways. First, of two pages used in the same tick interval, it cannot tell which was used later; both have 1 in the most significant bit. Second, an 8-bit counter remembers only the last 8 ticks. A page used 9 ticks ago and a page used 1,000 ticks ago have the same counter: 0. If ticks arrive about 20 ms apart, 8 bits mean a history of 160 ms, which is often enough.
Reading the bits of the counter in reverse order. The most recent tick is the most significant bit. For a page whose R bits from tick 0 to tick 4 arrive as 1, 1, 1, 0, 0, the counter is not 11100000 but 00111000 (56): it was not used in the two newest ticks. NFU would have given the same page 3 points and would have evicted a page that was used only twice but within the last two ticks.
9.6.15Aging on the common string
Running aging on the common string reveals a detail. The ticks arrive every 4 references. A newly loaded page has counter 0 and R = 1. In the comparison, the R bit that has not yet been added to the counter counts as the most significant bit, that is, a 9-bit value (R, counter) is used. Had we not done this, the newly loaded page would have counter 0 and would be evicted at the very first fault. On a tie, the page loaded earliest is chosen.
| Reference no. | Requested | Keys | Victim |
|---|---|---|---|
| 4 | 2 | 7: 100000000, 0: 100000000, 1: 100000000 | 7 |
| 6 | 3 | 2: 010000000, 0: 110000000, 1: 010000000 | 1 |
| 8 | 4 | 2: 010000000, 0: 110000000, 3: 100000000 | 2 |
| 9 | 2 | 4: 010000000, 0: 011000000, 3: 010000000 | 3 |
| 10 | 3 | 4: 010000000, 0: 011000000, 2: 100000000 | 4 |
| 14 | 1 | 3: 010000000, 0: 011100000, 2: 110000000 | 3 |
| 18 | 7 | 1: 110000000, 0: 011110000, 2: 011000000 | 2 |
At reference 4 the keys of the three pages are equal and 7, the one loaded earliest, is evicted. Then the first tick arrives and the R bits are shifted into the counters. At reference 6 the keys of 2 and 1 are equal (only their counters contain the use from one tick earlier); 1 is evicted because it was loaded earlier. 0, on the other hand, was used again at the 5th reference, so its R is 1 and it is kept. At references 9 and 10 two faults occur within a short interval: 3 is evicted for 2, and 4 for 3. 10 faults are incurred in total (Figure 9.31).
With 10 faults, aging does better than LRU (12) on this string and comes very close to OPT (9). This result, too, should not be generalized. A single short string is not enough to rank algorithms; the result changes when the tick frequency or the tie-breaking rule changes.
9.7The working set
The algorithms so far answered a single question: which page should be evicted? In 1968 Denning changed the question: for a process to run efficiently, which pages does it need to keep in memory? The answer again comes from locality, and it guides both replacement and frame allocation.
9.7.1The working-set model
A process uses a small group of pages for a while and then moves to another group. For example, when a function is called, its code, its local variables, and the global data it uses form a locality. When the function returns, the process moves to another locality. Localities may overlap.
The working set WS(t, Δ) is the set of distinct pages used in the last Δ memory references ending at time t. Δ is called the working-set window.
The choice of Δ is important. If Δ is too small, the window does not cover the whole locality and needed pages fall outside it. If it is too large, several localities overlap and the set becomes larger than necessary. With Δ = ∞ the working set is all the pages the program touches in its lifetime. The essence of the model is this: if the process's working set is in memory, few faults occur; if not, the process thrashes.
Silberschatz's string (37 references): 2 6 1 5 7 7 7 7 5 1 6 2 3 4 1 2 3 4 4 4 3 4 3 4 4 4 1 3 2 3 4 4 4 3 4 4 4. The window is Δ = 10 references. What is the working set at different moments?
- t = 10. The window is references 1–10: 2 6 1 5 7 7 7 7 5 1 → {1, 2, 5, 6, 7}, size 5. This is moment t1 in Silberschatz.
- t = 14. The window is references 5–14: 7 7 7 7 5 1 6 2 3 4 → {1, 2, 3, 4, 5, 6, 7}, size 7. The old and the new locality overlap.
- t = 18. The window is references 9–18 → {1, 2, 3, 4, 5, 6}, size 6.
- t = 22. The window is references 13–22 → {1, 2, 3, 4}, size 4.
- t = 26. The window is references 17–26: 3 4 4 4 3 4 3 4 4 4 → {3, 4}, size 2. This is Silberschatz's moment t2; the process has settled into a new locality.
- t = 30 and 37. {1, 2, 3, 4} (size 4) and {2, 3, 4} (size 3).
The size of the working set fluctuates over time: from t = 10 to 37 the sizes go 5, 4, 5, 6, 7, 7, 7, 7, 6, 5, 5, 4, 4, 4, 4, 3, 2, 3, 3, 4, … In the transition from one locality to the next, the set temporarily grows, because the window sees the pages of both localities together. When the new locality settles, the set shrinks.
9.7.2The working-set algorithm
The exact definition, the set of the last Δ references, would need a register shifted on every memory access. That is far too expensive. The practical approximation uses time instead of reference counts: the working set is the pages used during the last τ units of virtual time. Virtual time is the process's own CPU time; it does not advance while the process waits, and it is measured in clock ticks.
In the working-set algorithm, each page-table entry holds the time of last use and the R bit. At fault time the table is scanned. For a page with R = 1, the time is set to the current virtual time and R is cleared. For a page with R = 0, if its age (now − time of last use) is greater than τ, the page is not in the working set and can become the victim.
Tanenbaum's example: the current virtual time is 2204 and τ = 500. The (time of last use, R) values of the eight pages are: (2084, 1), (2003, 1), (1980, 1), (1213, 0), (2014, 1), (2020, 1), (2032, 1), (1620, 0). Which page is evicted?
- Pages with R = 1. Six pages were used in this tick; their times are set to 2204 and their R bits are cleared.
- Pages with R = 0. The ages are 2204 − 1213 = 991 and 2204 − 1620 = 584. Both are greater than τ = 500, so neither is in the working set.
- Choice. The first suitable page found, the one with time 1213, is evicted. The scan continues, updating the other entries.
If all pages are in the working set, that is, all pages with R = 0 have an age smaller than τ, the oldest among the R = 0 pages is chosen. If there is no R = 0 page at all, a random page is chosen, preferably a clean one. The algorithm's drawback is scanning the entire table on every fault.
9.7.3WSClock
The algorithm that combines the working-set idea with the clock's circular list is Carr and Hennessy's WSClock of 1981. Instead of scanning the whole table, the hand walks over the frames in order and stops at the first suitable victim.
In the WSClock algorithm each frame has a time of last use and R and M bits. When the hand arrives at a frame: if R = 1, then R ← 0, time ← now, and the hand advances. If R = 0, age > τ, and the page is clean, the page is the victim. If R = 0, age > τ, and the page is dirty, a write of the page to disk is scheduled and the hand advances. If R = 0 and age ≤ τ, the page is in the working set; the hand advances.
It is important that a dirty old page is not evicted immediately. The write is handed to the disk while the hand goes on looking for a clean page. When the write finishes, the page has become clean and can be evicted cheaply later. If the hand makes a full circle and returns to where it started, there are two cases:
- If at least one write was scheduled, the hand goes around until the first page whose write has finished and evicts it.
- If no write was scheduled, all pages are in the working set. Any clean page is evicted; if there is none, the page under the hand is written out and evicted.
In Tanenbaum's example the hand is first at the page with time 2014. R = 1, so the page was used in this tick and is not a good victim. R is cleared, the time is set to 2204, and the hand advances. The next page has time 1213 and R = 0. Its age is 2204 − 1213 = 991 > τ, so it is not in the working set. If it is clean, it becomes the victim; if it were dirty, its write would be scheduled and the hand would advance. The new page is loaded into this frame with time 2204 and R = 1. WSClock is a simple, efficient, and widely used design in practice.
9.7.4WSClock on the common string
To run WSClock on the common string, the reference number is taken as virtual time and τ = 4 is chosen. The writes are the same as in NRU (the 2nd, 6th, 9th, and 15th references). A page whose write has been scheduled is considered cleaned by the end of the round.
- Reference 4 (2). The hand walks over 7, 0, and 1 in turn; all three have R = 1. The R bits are cleared and their times are set to 4. The round ends and there is no write. The first clean page is 7 (0 is dirty), and 7 is evicted.
- Reference 6 (3*). 0: R = 1 → R = 0, time 6. 1: R = 0, age 6 − 4 = 2 ≤ τ, in the working set. 2: R = 1 → R = 0, time 6. The round ends and there is no write. Starting again from the hand, the first clean page is 1; 1 is evicted.
- References 8 and 9. In the same way, first 2 and then 4 are evicted as the first clean page.
- Reference 14 (1). Memory holds 0*, 3*, 2*; all three are dirty and their R bits are 1. The round ends and there is no clean page: 0, under the hand, is written out and evicted (write 1).
- References 16–18. Each time, no clean page outside the working set is found; at the end of the round the first clean page is evicted: 1, 0, 1 respectively.
- Reference 19 (0). 3: R = 0, age 19 − 14 = 5 > τ and dirty: its write is scheduled. 2: age 3 ≤ τ. 7: R = 1 → R = 0. The round ends; the written 3 is now clean and becomes the victim (write 2).
- Reference 20 (1). 7 is evicted as the first clean page.
- Result. 13 faults, 2 dirty writes (Figure 9.35).
13 faults is a result even worse than LRU's. The reason is the smallness of the example: with 3 frames every page is in the working set, and the τ criterion cannot distinguish any page. At most faults the algorithm falls back on the fallback rule at the end of the round, “the first clean page.” The payoff of the working-set idea appears in a memory with thousands of frames and in a long run.
9.8Comparing the algorithms
9.8.1Results on the common string
On the common string (3 frames) the results of all the algorithms can be put side by side (Table 9.10, Figure 9.36).
| Algorithm | Fault | Comment |
|---|---|---|
| OPT | 9 | Not implementable; the lower bound for comparison. |
| Aging* | 10 | An efficient algorithm that approximates LRU well. |
| NRU* | 11 | A very crude approximation of LRU; cheap. |
| Enhanced clock* | 11 | Combines NRU's classes with the clock. |
| LRU | 12 | Very good, but the exact version needs hardware. |
| WSClock* | 13 | Good and efficient; its advantage is not visible in the small example. |
| Clock | 14 | A realistic implementation of second chance. |
| FIFO | 15 | May evict important pages; Belady's anomaly. |
| Second chance | — | A big improvement over FIFO (its decisions are the same as the clock's). |
| NFU | — | A rather crude approximation of LRU; never forgets. |
| Working set | — | Good, but scanning the table on every fault is expensive. |
The ranking in the table can be misleading. Algorithms with R and M bits exploit the write and tick information that LRU does not use at all; a single short string does not give a general ranking. Tanenbaum's assessment rests on long measurements: in practice the two best algorithms are aging and WSClock. NFU does not approximate LRU well because it never forgets; the good approximation is aging.
9.8.2The workload determines the policy
How good an algorithm is depends on the access pattern. To see this, the experiment in OSTEP can be repeated. There are three synthetic workloads making 10,000 accesses to 100 distinct pages (50 pages in the loop). Each is run with five policies while the number of frames varies from 0 to 100 (Figure 9.37). For the random policy the average of 5 trials is taken.
- The no-locality workload. Each access is chosen at random from the 100 pages. The past says nothing about the future; LRU, FIFO, clock, and random all follow the same line, and the hit rate is approximately frames / 100. Only OPT, which knows the future, is ahead. With 100 frames all pages fit and all reach a 99% hit rate (the remaining 1% are the initial loads).
- The 80-20 workload. 80% of the accesses go to 20% of the pages. When there are hot pages, the policies that use the past win. With 20 frames OPT gives an 81% hit rate, LRU 58%, clock 56%, and FIFO and random about 53%. Clock is very close to LRU; FIFO is no better than random.
- The looping workload. 0, 1, …, 49, 0, 1, … are repeated in order. A loop slightly larger than memory is the worst case for LRU. With 49 frames, the page evicted is always the one that will be needed soonest, and LRU, FIFO, and clock miss on every access: 0%. Random gives a 95.5% and OPT a 97.5% hit rate. With 50 frames the loop fits and all rise to 99.5%.
This experiment was rerun in Python for these notes. The same results come out, up to small differences due to the random number generator: in 80-20 with 20 frames, OPT 80.7%, LRU 58.1%, clock 55.2%, FIFO 52.7%, random 52.4%; in the loop with 49 frames, OPT 97.5%, random 95.5%, the others 0%.
The looping pattern is not merely an artificial experiment. Reading a large file once from start to end is also a scan, and it hits LRU in real systems: file pages that will never be used again drive the hot pages out of memory. This is why Linux puts a new page first on the inactive list and moves it to the active list only on the second access.
Believing that LRU is better than FIFO and random in every case. LRU relies on locality. When the accesses follow a loop slightly larger than memory, LRU always evicts the wrong page and blind random choice beats it by a wide margin.
9.9Frame allocation
When several processes share memory, the second question arises: how many frames should each process get?
9.9.1Equal and proportional allocation
Allocation has two limits. The lower limit is set by the architecture: all the pages an instruction may touch must be in memory at the same time, or the instruction can never complete. The instruction itself, its operands, and indirect addresses may cross page boundaries. For example, the IBM 370's memory-to-memory move instruction MVC may need six frames: the instruction itself, the source block, and the destination block can each straddle two pages. The upper limit is the free physical memory. Between these two limits there are three approaches.
Equal allocation: m frames are divided among n processes as ⌊m / n⌋ frames each. Proportional allocation: if the virtual size of process i is si and the total is S = Σ si, then the process gets ai = si / S × m frames (rounded down). Priority allocation: the ratio is based on priority instead of size, or on priority together with size.
62 frames, P1 of 10 pages and P2 of 127 pages. What do equal and proportional allocation give?
- Equal. ⌊62 / 2⌋ = 31: 31 frames each. P1, with 10 pages, can never use 21 of its frames.
- Proportional. S = 137. P1: 10 / 137 × 62 ≈ 4.53 → 4. P2: 127 / 137 × 62 ≈ 57.47 → 57.
- Remainder. 4 + 57 = 61; because of rounding down, 1 frame is left unused (Figure 9.38).
In priority allocation, when a high-priority process takes a page fault, it may take a frame from a lower-priority process. As the degree of multiprogramming changes, so does the allocation: when a new process arrives, everyone's share shrinks a little. On NUMA (non-uniform memory access) systems it also matters where a frame is. A process should be fed from memory close to the processor node it runs on; the memory of a remote node is slower.
9.9.2Local and global replacement
Which frames the victim is chosen from is also a decision.
In global replacement the victim is chosen from among all frames; a process may take another process's frame. In local replacement a process chooses its victim only from among its own frames.
Three processes (A, B, C) share 16 frames. The numbers are aging counters: A0 10, A1 7, A2 5, A3 4, A4 6, A5 3; B0 9, B1 4, B2 6, B3 2, B4 5, B5 6, B6 12; C1 3, C2 5, C3 6. A faults on page A6. Which page is evicted?
- Local. The candidates are only A's frames. The smallest value is A5's 3; A5 is evicted. A's frame count stays at 6.
- Global. All frames are candidates. The smallest value is B3's 2; B3 is evicted. A grows to 7 frames and B shrinks to 6 (Figure 9.39).
The global policy uses memory more efficiently: idle frames pass to whoever needs them, and total throughput rises. The price is unpredictability. A process's running time can vary a lot depending on the memory behavior of other processes; the same program may take 10 seconds one day and 30 the next. The local policy provides this consistency, but frames lying idle in one process cannot pass to another that is cramped. It also needs a separate mechanism to adjust the number of frames as the working set grows and shrinks; page-fault frequency is that mechanism. Linux and Windows use global reclaim; limits are set with cgroups and job objects.
9.10Thrashing
9.10.1Futile paging
Thrashing is the state in which the system spends most of its time moving pages between memory and disk. It arises when the processes' active pages, that is, their working sets, do not fit in memory.
The mechanism is a vicious circle. If a process's working set does not fit in memory, the process faults continuously. The page it evicts is needed again right away; to bring that page in, it evicts another needed page. The processes spend most of their time waiting for pages, the disk queue fills, the ready queue empties, and CPU utilization falls.
There is also a feedback that makes things worse. The long-term schedulers of older systems monitored CPU utilization and interpreted low utilization as “the CPU is idle, we can take on more work.” When a new process enters the system, everyone's frame share shrinks further, faults increase, CPU utilization falls even more, and the scheduler adds yet another process. As the degree of multiprogramming rises, CPU utilization first increases, then after some point collapses (Figure 9.40).
The formula for the cause is short: Σ |WSi| > m, that is, the sum of the working sets is larger than memory. Local replacement confines thrashing to a single process: the cramped process cannot steal other processes' frames. But it does not solve the problem; that process is still thrashing, and by filling the disk queue it slows other processes' page faults too.
The remedies rest on restoring the balance between memory and demand. The degree of multiprogramming is reduced: some processes are suspended or swapped out. RAM is added. The last resort is the system's out-of-memory (OOM) killer. On Linux the symptom shows in the output of vmstat 1: high swap traffic in the si and so columns, high I/O wait in the wa column. The file /proc/pressure/memory (PSI, pressure stall information) reports memory pressure as the percentage of time that processes spend waiting because of memory.
Always taking low CPU utilization for idle capacity. If a monitor shows CPU at 7%, the swap disk at 100%, and a very high page-fault rate, the system is not idle but thrashing. In this case taking on new work is wrong; on the contrary, some processes must be suspended.
9.10.2Preventing it with the working set and PFF
The working-set strategy. The operating system tracks each process's working set and computes the total demand: D = Σ |WSi|. If D > m, thrashing is approaching and a process is suspended; its pages are written out and its frames are distributed to the others. If D is small enough, a new process can be started. For a process returning from suspension, loading its working set first, that is, prepaging, prevents a storm of faults on return.
Page-fault frequency. Tracking the working set is expensive. A more direct feedback is to look at the process's fault rate.
In the page-fault frequency (PFF) method, an upper and a lower bound are set on each process's fault rate. If the rate exceeds the upper bound, the process is given a frame; if it falls below the lower bound, a frame is taken back from the process (Figure 9.41).
If the fault rate is high but there is no free frame to give, a process is suspended and its frames are distributed. There is also a link between page faults and localities. When a process moves to a new locality, the fault rate peaks. Once the working set is loaded, the rate drops and stays low until the next transition. PFF reads these peaks as “more frames are needed” and the calm periods as “there are too many frames.”
9.10.3Code trace: PFF
The function below is a simple form of PFF. It is called at every page fault. t is the current reference number, s->last is the time of the last fault, and C is the threshold. If the time since the last fault is greater than C, faults are rare and the pages not used since the last fault are released. If it is smaller, faults are frequent and the set grows without any page being evicted.
void pff(Proc *s, int p, int t) {
if (t - s->last > C) { /* rare faults */
for (int i = s->n - 1; i >= 0; i--)
if (s->set[i].R == 0)
evict(s, i); /* unused */
}
for (int i = 0; i < s->n; i++)
s->set[i].R = 0; /* clear */
add(s, p); /* with R = 1 */
s->last = t;
}In the rare-fault branch the loop walks the set from the end toward the beginning. This direction is deliberate: when evict() removes an element, the elements behind it shift left by one. Walking from the beginning would skip an element. Then all the R bits are reset, so that at the next fault the question “was it used in this interval?” can be asked again. The new page is added with R = 1 and the fault time is recorded.
The process starts with no memory; C = 2 and the reference string (from time 1 to 14) is 1 2 1 3 1 3 1 3 4 4 5 4 5 2 (Table 9.11).
t | Page | t - last | Branch | Evicted | Set after |
|---|---|---|---|---|---|
| 1 | s1 | 1 − 0 = 1 | frequent | — | {s1} |
| 2 | s2 | 2 − 1 = 1 | frequent | — | {s1, s2} |
| 4 | s3 | 4 − 2 = 2 | frequent | — | {s1, s2, s3} |
| 9 | s4 | 9 − 4 = 5 | rare | s2 | {s1, s3, s4} |
| 11 | s5 | 11 − 9 = 2 | frequent | — | {s1, s3, s4, s5} |
| 14 | s2 | 14 − 11 = 3 | rare | s3, s1 | {s4, s5, s2} |
- t = 1, 2, 4. The intervals are 1, 1, and 2; none exceeds
C. Faults are frequent and no page is evicted; the set grows to 3 pages. Reference 3 in between (s1) is a hit. - t = 9. References 5–8 hit s1 and s3 and set their R bits to 1. At the fault on s4 the interval is 5 > 2: faults are rare. The only page not used since the last fault (R = 0) is s2, and it is evicted.
- t = 11. The interval is 2 ≤ C. No page is evicted and the set grows to 4 pages. While the process moves to a new locality (s4, s5), the old pages (s1, s3) are still in memory.
- t = 14. References 12 and 13 hit s4 and s5. At the fault on s2 the interval is 3 > 2. s3 and s1, which have R = 0, are evicted. The final set is s4 (R = 0), s5 (R = 0), s2 (R = 1).
There were 6 faults in 14 references. When the locality shifted from pages 1–3 to pages 4–5, faults first became frequent and the set grew. Then a rare fault was the opportunity to release the pages of the old locality. The cost of the function is linear in the set size, O(n); but it runs only at fault time.
9.11Design issues
The replacement algorithm and the allocation policy are only part of a virtual memory system. How well the system actually works is determined by many small decisions: when to look for a victim, whether pages are brought in ahead of time, how large a page should be, what the programmer can do, and which pages must never be evicted.
9.11.1Cleaning policy and the paging daemon
Looking for a victim only at page-fault time makes the faulting process wait needlessly. If the victim is dirty, the process waits for both the write and the read. A better way is to keep free frames ready in advance.
The paging daemon is a kernel thread that wakes up periodically. If the number of free frames is low, it frees pages ahead of time using the replacement algorithm and writes dirty pages to disk ahead of time.
The payoff of writing ahead is this: when the moment of eviction comes, the page is usually clean and the fault waits only for a read. A freed frame is not wiped immediately either. Its contents stay in place, and if the page is needed again it can be reclaimed from the pool; in this case a minor fault suffices instead of a disk read.
One way of doing this job with the clock algorithm is the two-handed clock. The front hand has dirty pages written out and clears the R bits. The back hand follows it at a certain distance and frees the pages that still have R = 0, that is, that were not used in the time between the two hands. The distance between the hands determines the time a page is given “to be used.”
On Linux this daemon is called kswapd and works with three watermarks per memory zone: min, low, and high (Figure 9.43). When the number of free pages falls below low, kswapd wakes up and reclaims pages in the background. When the number rises to high, it goes back to sleep. If the number falls below min as well, the allocating process gets to work without waiting and does the reclaim itself; this is called direct reclaim and it increases latency. Dirty file pages are also written to disk by writeback threads.
9.11.2Prepaging
Demand paging suffers a storm of faults when a process starts and when it returns from suspension: each page arrives with a separate fault and a separate I/O.
Prepaging means bringing in, ahead of time and with a single bulk read, the pages that are predicted to be needed, without waiting for faults.
Whether prepaging pays off can be seen with a simple calculation. Suppose s pages are brought in ahead of time and a fraction α of them is actually used (0 ≤ α ≤ 1). The gain is that α·s page faults are avoided. The cost is reading (1 − α)·s unnecessary pages and having them occupy memory. If α is close to 1, prepaging gains; if it is close to 0, it loses (Figure 9.44).
s = 40 pages of the working set of a process returning from suspension are brought in ahead of time, and a fraction α = 0.6 of them is used. Bringing in a page by an individual fault takes 5 ms, and reading all 40 pages at once takes 30 ms. Is prepaging profitable? Below what value of α does it lose?
- Pages used. α × s = 0.6 × 40 = 24.
- Without prepaging. 24 faults × 5 ms = 120 ms.
- With prepaging. A single bulk read, 30 ms. The gain is 90 ms.
- Threshold. The gain is 40α × 5 = 200α ms and the cost is 30 ms: 200α > 30 → α > 0.15.
- Hidden cost. (1 − α) × s = 16 unnecessary pages hold frames and may cause other pages to be evicted.
In this example the threshold is low because the bulk read is very cheap. As the cost of the bulk read approaches that of individual faults, the threshold rises. The classical practice is to remember the working set of a suspended process and load it on return. Linux uses readahead for files and the page-cluster setting for swap. An application can also give hints: madvise(MADV_WILLNEED) or mmap(MAP_POPULATE). On Windows, the Prefetcher and SysMain (formerly SuperFetch) load frequently used pages while the system is idle.
9.11.3Page size
The page size is usually determined by the hardware, but when a new architecture is designed it is a choice, and there are competing forces (Table 9.12).
| Small page | Large page |
|---|---|
| less internal fragmentation | smaller page table |
| tracks locality finely, brings in little unneeded data | fewer page faults, efficient I/O (seek and setup cost is paid once) |
| many TLB misses | large TLB reach |
The two forces can be weighed with a simple model. Let the process size be s bytes, the page-table entry size e bytes, and the page size p bytes. The page table has s/p entries, that is, se/p bytes. The last page of the process is on average half empty and creates p/2 bytes of internal fragmentation.
If the overhead is f(p) = se/p + p/2, its minimum is at p = √(2se).
The proof is by differentiation: from the equation f′(p) = −se/p² + 1/2 = 0 we get p² = 2se. Since the second derivative is positive, this point is a minimum.
What is the optimal page size for s = 1 MB and e = 8 B? What changes if s = 4 MB?
- Powers of two. 1 MB = 2²⁰, 8 = 2³. 2se = 2 × 2²⁰ × 2³ = 2²⁴.
- Square root. p = √(2²⁴) = 2¹² = 4,096 B = 4 KB.
- Overhead. f(4,096) = 2²³ / 2¹² + 2,048 = 2,048 + 2,048 = 4,096 B. With 2 KB it is 5,120, and with 8 KB again 5,120 B.
- s = 4 MB. 2 × 2²² × 2³ = 2²⁶, √(2²⁶) = 2¹³ = 8 KB.
The model is crude; it does not account for the TLB or for I/O at all. Even so, it explains why 4 KB has remained the standard for decades. As of 2026, x86-64 uses 4 KB pages and supports huge pages of 2 MB and 1 GB. Apple Silicon uses 16 KB pages. Android 15 and later support kernels with 16 KB pages. Some ARM64 servers run with 64 KB pages. 1 KB pages are seen only in old systems. The trend is that pages grow as memory grows.
9.11.4TLB reach and huge pages
The TLB reach is the amount of memory that can be accessed through the TLB without a miss: the number of TLB entries × the page size.
If the process's working set does not fit in the reach, a significant fraction of accesses end in TLB misses and time goes to page-table walks. There are two ways to increase the reach. Increasing the number of entries is expensive, because the TLB is an associative memory and each entry needs a parallel comparison circuit. Enlarging the page is far more effective (Figure 9.46).
(a) What is the reach of a 64-entry TLB with 4 KB and with 2 MB pages? (b) A database's hot data is 48 MB; the second-level TLB has 1,024 entries. Does the data fit in the reach with 4 KB and with 2 MB pages?
- (a) 64 × 4 KB = 256 KB; 64 × 2 MB = 128 MB.
- (b) 4 KB. 1,024 × 4 KB = 4 MB. The 48 MB of data does not fit; most accesses become TLB misses.
- (b) 2 MB. 1,024 × 2 MB = 2 GB. The data fits comfortably.
On x86-64 the huge pages are 2 MB and 1 GB. Linux offers two ways: hugetlbfs, which the application requests explicitly, and transparent huge pages (THP), which the kernel uses on its own. In THP the khugepaged thread merges contiguous small pages into huge pages in the background. 6.x kernels can also use sizes between 4 KB and 2 MB, with multi-size folios and mTHP support. On Windows, a special privilege is needed to use large pages.
Huge pages have costs too: internal fragmentation, the need to find a large contiguous physical region (which may require memory compaction), and a longer copy and zeroing time per page. The software that benefits most from huge pages is databases and virtual machines; both use large, frequently accessed memory regions.
9.11.5Program structure and locality
Demand paging should be invisible to the programmer, but the programmer's choices can change the number of faults greatly. The best-known example is the traversal order of a two-dimensional array. C stores arrays in row-major order: data[i][0], data[i][1], … are consecutive in memory.
int data[128][128]; /* row = 1 page */
/* A: column by column */
for (int j = 0; j < 128; j++)
for (int i = 0; i < 128; i++)
data[i][j] = 0;
/* B: row by row */
for (int i = 0; i < 128; i++)
for (int j = 0; j < 128; j++)
data[i][j] = 0;The array is 128 × 128 ints; a page is 128 words, so each row is exactly one page. The process is allocated 64 frames, none is filled at the start, and replacement is LRU.
How many page faults do loops A and B produce?
- A, column 0. The inner loop is over
i:data[0][0],data[1][0], … Eachiis a different row, that is, a different page. Over column 0 there are 128 faults. 128 pages do not fit in 64 frames; when the column ends, pages 0–63 have long since been evicted. - A, column 1.
data[0][1]is again on page 0, but page 0 has been evicted: another fault. LRU evicts the page that will be needed soonest every time. - A, total. Every access is a fault: 128 × 128 = 16,384 faults.
- B, row 0.
data[0][0]faults on page 0; thendata[0][1…127]are on the same page and are hits. - B, total. One fault per row: 128 faults. The same work, 128 times fewer faults.
The same principle holds at other sizes. In a 64 × 1024 int array (each row 4 KB = one page), filling row by row with 32 frames causes 64 faults, while filling column by column causes 64 × 1,024 = 65,536 faults: a factor of 1,024. Fortran, on the other hand, stores arrays in column-major order, and there the correct order is the reverse.
The choice of data structure also affects locality. A stack shows good locality: accesses are always near the top. A hash table deliberately scatters accesses and shows poor locality. Linked structures that chase pointers are also poor, because they scatter their nodes across memory. Compilers sometimes swap the inner and outer loops on their own with a loop interchange transformation. The compiler and the loader can also place code with page boundaries in mind: for example, putting functions that call each other on the same page.
9.11.6I/O locking and page pinning
Some pages must absolutely not be evicted, at least for a while. The most important example is I/O buffers.
Process A supplies a buffer for a disk read. The global replacement policy is in use. What can go wrong?
- Request. The kernel programs direct memory access (DMA) with the physical address of frame 42, where the buffer is.
- Waiting. A blocks; the device waits in the queue or is running. Meanwhile frame 42 looks like an ordinary page.
- Replacement. B takes a page fault. The global policy chooses frame 42 as the victim and loads B's page into it.
- Corruption. When the DMA completes, the device writes the data into frame 42, that is, over B's page. The data has gone into the wrong process's memory.
Pinning, or page locking, means setting a lock bit on a frame so that it is kept out of the replacement candidates.
There are two solutions to the problem. The first is to lock the buffer frame for the duration of the I/O. The second is always to do the I/O into kernel buffers and copy the data to the user buffer afterwards; this is safe but requires an extra copy.
Other pages are pinned too. Part of the kernel's code and data is never evicted; if the page-fault handler itself were evicted, who would bring it back? Real-time processes, which cannot tolerate latency, lock their memory with mlock() or mlockall(). Linux drivers pin user pages with pin_user_pages(); RDMA network cards, GPUs, and io_uring's fixed buffers use this. The IOMMU makes devices use translated addresses too and prevents DMA to a wrong address in hardware.
There is also a subtlety about priority. A low-priority process, after a long wait, may have just brought in its page without yet having run. The R bit of this page is 0, and a fault by a high-priority process may immediately choose it as the victim. The effort of fetching is wasted. A newly loaded page can therefore be kept locked until it has been used once.
The risk of locking is also clear: if a locked page is forgotten, the frame can never be used again. Many locks squeeze memory and make thrashing easier. For this reason the amount of memory a user can lock is limited; on Linux the limit can be seen with ulimit -l.
9.12Kernel memory
The memory of user processes is paged and comes from the free-frame pool. The kernel's own memory follows different rules. Most kernel memory is not paged, because code such as the page-fault handler must not fault. The kernel allocates structures much smaller than a page (process descriptors, file objects, semaphores), and page-level allocation is wasteful for these. Some devices need physically contiguous memory for DMA, because they do not know virtual addresses. Two allocators serve these needs.
9.12.1The buddy system
The buddy system is an allocator that divides a physically contiguous region into blocks of power-of-two sizes only. A request is rounded up to the smallest power of two that satisfies it. If there is no free block of the right size, a larger block is split into two equal halves, two buddies. When a block is released, if its buddy is also free, the two merge.
The kernel has 256 KB of physically contiguous memory. A request for 21 KB arrives. How do the splits go, and how much is the internal fragmentation?
- Rounding. The smallest power of two that satisfies 21 KB is 32 KB.
- First split. The 256 KB is split into the buddies AL and AR of 128 KB each.
- Second split. AL is split into BL and BR of 64 KB each.
- Third split. BL is split into CL and CR of 32 KB each. CL is given to the request.
- Cost. 21 requested, 32 KB given: 11 KB of internal fragmentation.
The real strength of the buddy system is coalescing. When CL is released, if its buddy CR is free, the two re-form BL; if BR is also free, AL forms, and so on. Finding the buddy's address takes a single operation: the buddy of a block of size k is found by flipping the bit of the block address that corresponds to k (address XOR size). Linux's page allocator is a buddy allocator. It keeps a separate free list for each order from 0 to 10: from 4 KB to 4 MB. The state of the lists can be seen with cat /proc/buddyinfo.
9.12.2Code trace: the buddy allocator
The code below shows the core of the buddy allocator. Sizes are kept as powers of two in KB: alloc(k) asks for a block of 2k KB. fl[j] is the list of free blocks of 2j KB. pop(j) takes a block from the list, push(j, a) adds one to the list, and remove(k, b) removes b from the list if it is there and returns true.
int alloc(int k) { /* 2^k KB */
int j = k;
while (fl[j] == NULL) j++;
int a = pop(j);
while (j > k) { /* split, right half free */
j--; push(j, a + (1 << j));
}
return a;
}
void release(int a, int k) {
int b = a ^ (1 << k); /* buddy */
while (k < MAX && remove(k, b)) {
a = a < b ? a : b; /* merge */
k++; b = a ^ (1 << k);
}
push(k, a);
}alloc() first looks for the smallest list j ≥ k that has a free block and pops a block from it. Then the block is halved until it reaches the requested size: at each split the right half (a + (1 << j)) is added to a free list, and the left half continues to be split. release() finds the buddy's address with a ^ (1 << k). If the buddy is on the free list of the same size, it removes it from the list, makes the lower-addressed of the two blocks the new block, and tries again at the next size up. If the buddy is not free, or the largest size (MAX) has been reached, the block is added to the list.
We start with a 256 KB region (MAX = 8) and call, in order, A = alloc(5), B = alloc(6), release(0, 5), release(64, 6) (Table 9.13).
| Call | Event | fl[5] | fl[6] | fl[7] | fl[8] |
|---|---|---|---|---|---|
| start | single block | — | — | — | @0 |
alloc(5) | j = 8, @0 popped; splits @128, @64, @32; A = 0 | @32 | @64 | @128 | — |
alloc(6) | @64 ready in fl[6]; B = 64 | @32 | — | @128 | — |
release(0, 5) | buddy 0 ⊕ 32 = 32 free → @0 (64); buddy 0 ⊕ 64 = 64 in use | — | @0 | @128 | — |
release(64, 6) | buddy 64 ⊕ 64 = 0 free → @0 (128); buddy @128 free → @0 (256) | — | — | — | @0 |
A = alloc(5). The 21 KB request is rounded up to 32 KB (2⁵). fl[5], fl[6], and fl[7] are empty; the first nonempty list is fl[8]: j = 8. The 256 KB block at @0 is popped. At j = 7 the right half @128, at j = 6 @64, and at j = 5 @32 go onto the free lists. When j = k, the loop ends and the left half, the 32 KB at @0, is given to A.B = alloc(6). @64 is ready in fl[6]; no split is needed. A's internal fragmentation is 32 − 21 = 11 KB.release(0, 5). The buddy's address is found by flipping a single bit: 0 ⊕ 32 = 32. @32 is in fl[5]; they merge into 64 KB at @0. The new buddy is 0 ⊕ 64 = 64, but B is using @64. The merging stops and @0 is added to fl[6].release(64, 6). The buddy 64 ⊕ 64 = 0 is free; the 128 KB block @0 forms. The new buddy @128 is also free and they merge into 256 KB. Since k = MAX, the loop stops; the region is a single piece again, as at the start.
alloc(5): A is the 32 KB at @0; @32 (32 KB), @64 (64 KB), and @128 (128 KB) are on the free lists.Allocation and release take as many steps as there are splits and merges, which is at most the number of orders, that is, O(log n). Since a separate free list is kept for each size, lookup is fast too. Finding the buddy's address with XOR relies on blocks always starting at addresses that are multiples of their own size.
9.12.3Buddy: a request-sequence example
We start with a single free block of 1 MiB (1,024 K). In order, A = 70 K, B = 35 K, C = 80 K are requested; A is released; D = 60 K is requested; B, D, and C are released. What happens at each step?
- A = 70 K. Rounded up to 128 K. 1,024 is split → 512 + 512 → 256 + 256 → 128 + 128; A takes 0–128. Internal fragmentation 58 K.
- B = 35 K. Rounded up to 64 K. The free block 128–256 is split into 64 + 64; B takes 128–192. Internal fragmentation 29 K.
- C = 80 K. Rounded up to 128 K. The free block 256–512 is split into 128 + 128; C takes 256–384. Internal fragmentation 48 K.
- A is released. Its buddy 128–256 is in a split state and contains B: no merge.
- D = 60 K. Rounded up to 64 K. B's free buddy 192–256 is given; no split is needed. Internal fragmentation 4 K.
- B is released. Its buddy D is in use: no merge.
- D is released. 128–192 and 192–256 merge into 128–256; that merges with A's free 0–128 into 0–256. Its buddy 256–512 holds C: stop.
- C is released. 256–384 + 384–512 → 256–512; with 0–256 → 0–512; with 512–1024 → 0–1024. Memory is a single block again.
The total internal fragmentation for A, B, and C is 58 + 29 + 48 = 135 K. The buddy system is fast at allocating and merging, but in the worst case about half of a block is wasted: a request of 2k + 1 bytes gets a block of 2k+1 bytes. This is why a second allocator is built on top of the buddy system for small objects.
Believing that two adjacent free blocks can always be merged. Only buddies merge: the two halves of the same size that came from splitting the same block. For example, 64–128 and 128–192 are adjacent and of the same size, but they are not buddies; the buddy of 64 is 0 and the buddy of 128 is 192.
9.12.4The slab allocator
The slab allocator keeps a separate cache for each frequently used type of kernel object. A cache consists of one or more slabs, and each slab consists of one or several physically contiguous pages. A slab is packed with objects of that type at their exact size.
A slab is in one of three states: full (all its objects in use), partial (some in use), and empty. Objects wait in the cache already initialized; allocation is simply taking an object from the list (Figure 9.51).
The path of a request is as follows. fork() asks for a new task_struct. The allocator first looks for a free object in the partial slabs; if it finds one, it hands it out. If the partial slabs fill up, it moves on to the empty slabs. If no partial or empty slab remains, new pages are obtained from the buddy allocator and a new slab is built. Under memory pressure, emptied slabs are returned to the buddy allocator.
Bonwick designed the slab allocator for Solaris in 1994. Its benefits are as follows:
- There is no fragmentation: objects are of exact size and are packed side by side within a page.
- Allocation and release are O(1); a released object is merely marked “free.”
- Objects in the cache are hot and ready; they do not have to be initialized again at every allocation.
- Per-CPU lists provide a lock-free fast path.
In Linux three implementations of the slab allocator coexisted for a long time: SLAB, SLUB, and SLOB. SLOB was removed in version 6.4 and the classic SLAB in version 6.8 (2024); today the only allocator is SLUB. The general-purpose kmalloc() is also fed from slab caches divided into size classes. The state of the caches is monitored with slabtop and /proc/slabinfo.
9.13Real systems
9.13.1Linux: page reclaim
On Linux, reclaim is triggered by watermarks. When the number of free pages in a zone falls below low, kswapd wakes up; if it falls below min, the allocating process performs direct reclaim and latency rises.
Classical Linux reclaim uses two pairs of lists that resemble the clock: the active and inactive lists. There is a separate pair for anonymous pages and for file pages (Figure 9.52). A new page enters the inactive list; if accessed again, it is promoted to the active list. Pages at the tail of the active list move down to the inactive list as they age. Victims are chosen from the tail of the inactive list. An anonymous victim goes to swap or to zswap; a clean file page is simply dropped. For locked pages there is also a separate unevictable list.
This two-list arrangement is a safeguard against the looping pattern hitting LRU: file pages read once stay in the inactive list and cannot drive out the hot pages. The vm.swappiness setting (0–200) determines the preference between swapping out anonymous pages and dropping file pages. If memory really runs out, the OOM killer selects a process and terminates it.
9.13.2Linux: MGLRU, zswap, and zram
MGLRU (multi-generational LRU) arrived in 2022 with Linux 6.1. Pages are divided into four generations instead of two lists. Access bits are collected in bulk by walking the page tables; an accessed page moves to the youngest generation, and the victim is chosen from the oldest generation (Figure 9.53). The result is less CPU spent and better victim choices. MGLRU is the default on ChromeOS and Android; many distribution kernels enable it with a build option. Its status can be read from the file /sys/kernel/mm/lru_gen/enabled.
zswap is a compressed cache that sits in front of swap. Before an anonymous page goes to disk, it is compressed in RAM and held in a pool. When the pool fills, the oldest entries are written to the real swap device. zram, on the other hand, is a compressed block device in RAM and is used directly as swap space; pages never go to disk. Fedora (since version 33), Android, and ChromeOS use zram by default.
Compression spends CPU, but it is hundreds of times cheaper than going to disk. The 10 µs fault time of zram in the EAT calculation shows this in numbers: at p = 0.001 the HDD gives a slowdown of 251, while zram brings only a 10% slowdown.
9.13.3Windows: working sets and compression
Windows uses Denning's model under its own name. Each process has a working set, with minimum and maximum limits on its size. A page fault makes room in the set or grows it. When memory runs low, the balance set manager trims the sets.
A trimmed page is not discarded immediately (Figure 9.54). If clean, it goes to the standby list; if dirty, to the modified list. Modified pages move to the standby list once written. A page on the standby list that is requested again is reclaimed with a minor fault. The free and zeroed lists feed new allocations.
Windows 10 (2015) brought memory compression: trimmed pages are held in a compression store in the System process; writing to pagefile.sys is the last resort. Prefetching is done by the Prefetcher and SysMain. Large pages are requested with VirtualAlloc(MEM_LARGE_PAGES).
macOS and iOS follow a similar path: compressed memory is used. iOS has no swap at all; under memory pressure the system terminates background applications through the Jetsam mechanism. What the three systems have in common is that they try every possibility of staying in memory before going to disk.
9.14Summary
- Virtual memory separates logical memory from physical memory. A process runs while only partly in memory; programs are not limited by physical memory, more processes are kept in the same memory, and sharing becomes easier.
- In demand paging a page is brought in only when it is accessed. An access to an invalid entry produces a page-fault trap. The kernel checks the reference, reads the page from the backing store into a free frame, updates the table, and restarts the instruction.
- Linux divides page faults into minor (no I/O), major (a read from disk), and invalid (
SIGSEGV). Pages are file-backed, anonymous, or zero-filled. - The effective access time is EAT = (1 − p) × ma + p × fault time. On an HDD (25 ms), p = 0.001 slows memory by a factor of 251; a 10% slowdown requires p < 4 × 10⁻⁷. NVMe and zram reduce the penalty but do not remove it.
- Copy-on-write shares pages after
fork()and copies only the page that is written; the frame's reference count decides whether a copy is needed.mmap()maps a file into the address space;MAP_SHAREDwrites changes to the file,MAP_PRIVATEto a private copy. - If there is no free frame, a victim is chosen; a dirty victim is written to disk first. Algorithms are compared by their number of faults on a reference string.
- On the common string (3 frames) OPT incurs 9 faults, aging 10, NRU and enhanced clock 11, LRU 12, WSClock 13, clock 14, and FIFO 15. OPT cannot be implemented but is the lower bound.
- FIFO can show Belady's anomaly: on the string 1 2 3 4 1 2 5 1 2 3 4 5, 3 frames give 9 faults and 4 frames give 10. LRU and OPT are stack algorithms and do not show the anomaly.
- Exact LRU needs hardware (counter, stack, matrix). In practice, approximations based on the R and M bits are used: second chance, clock, NRU, enhanced clock, NFU, and aging. Aging approximates LRU well; NFU cannot because it never forgets.
- The working set WS(t, Δ) is the set of pages used in the last Δ references. The working-set algorithm and WSClock implement this idea with virtual time and a threshold τ.
- The workload determines the policy: with no locality the policies are equal, with hot pages LRU wins, and on a loop slightly larger than memory LRU gets a zero hit rate.
- Frames are distributed equally, proportionally, or by priority; the victim is chosen locally or globally. Thrashing begins when Σ |WSi| > m; the working-set strategy and PFF prevent it by adjusting the degree of multiprogramming.
- Design decisions: the paging daemon and watermarks, prepaging (the α threshold), the optimal page size √(2se), TLB reach and huge pages, row-major traversal, pinning of I/O buffers.
- Kernel memory is allocated by the buddy allocator in power-of-two blocks, and buddies are found and merged with XOR; for small objects the slab allocator (SLUB on Linux) is used.
- Linux uses active/inactive lists, MGLRU, zswap, and zram; Windows uses working sets, standby lists, and memory compression.
9.15Key terms
- virtual memory
- virtual address
- demand paging
- page fault
- backing store (swap space)
- effective access time
- copy-on-write
- memory-mapped file
- page cache
- page replacement
- reference string
- reference bit / dirty bit
- Belady's anomaly
- optimal page replacement (OPT)
- least recently used (LRU)
- second chance
- clock algorithm
- aging
- locality
- working set
- thrashing
- translation lookaside buffer (TLB)
- internal fragmentation
- buddy system
- slab allocator
- compression
9.16Test Yourself
The reference string is 1 2 3 4 2 1 5 6 2 1 2 3 7 6 3 2 1 2 3 6 and the number of frames is 4. How many page faults do FIFO, LRU, and OPT incur?
Answer
FIFO 14, LRU 10, OPT 8. LRU's victims are, in order, 3, 4, 5, 6, 1, 7; OPT's are 4, 5, 1, 7. Since there are 7 distinct pages, at least 7 faults are unavoidable; OPT comes very close to this. With 3 frames the results are FIFO 16, LRU 15, OPT 11.
Memory access takes 50 ns and the page-fault service time is 10 ms. What is the largest p that keeps the slowdown at or below 20%?
Answer
A 20% slowdown means EAT < 60 ns. 10 ms = 10,000,000 ns. 60 > 50 + (10,000,000 − 50) p → p < 10 / 9,999,950 ≈ 1.0 × 10⁻⁶: fewer than one fault in about a million accesses.
With four free frames and the string 1 2 3 4 1 5 2 6 1 3, how many faults does the clock algorithm incur (the hand starts at frame 0 and moves only on a fault)? Which pages are evicted?
Answer
8 faults. The first four references are loaded into the free frames; 1 is a hit. When 5 arrives, all four pages have R = 1; the hand clears them all, makes a full circle, and evicts 1. 2 is a hit (R ← 1). When 6 arrives, the hand clears the R of 2 and evicts 3, which has R = 0. When 1 arrives, 4 (R = 0), under the hand, is evicted. When 3 arrives, the hand clears the R of 5 and evicts 2. The victims are 1, 3, 4, 2.
The reference string (from time 1) is 1 2 1 3 2 4 4 5 4 5 6 1, with Δ = 4. What are W(4), W(8), and W(12)?
Answer
W(4) = {1, 2, 3} (1 2 1 3), W(8) = {2, 4, 5} (2 4 4 5), W(12) = {1, 4, 5, 6} (4 5 6 1). The sets drift as the process moves to new pages; W(12) has grown during a locality transition.
What is the reach of a TLB with 2,048 entries and 16 KB pages? Is it sufficient for a process whose working set is 48 MB?
Answer
2,048 × 16 KB = 32,768 KB = 32 MB. A 48 MB working set does not fit; some of the accesses go to a page-table walk through a TLB miss. 2 MB huge pages would raise the reach to 4 GB.
The process size is 2 MB and the page-table entry is 4 bytes. According to the overhead model se/p + p/2, what is the optimal page size?
Answer
p = √(2se) = √(2 × 2²¹ × 2²) = √(2²⁴) = 2¹² = 4 KB.
In a 128 K buddy region, A = 10 K, B = 30 K, and C = 20 K are requested in order; then A and C are released. Where does each request go, what is the total internal fragmentation, and what are the free blocks at the end?
Answer
A is rounded up to 16 K: 128 → 64 + 64 → 32 + 32 → 16 + 16; A takes 0–16 (6 K). B is 32 K: the free block 32–64 is ready (2 K). C is 32 K: the free block 64–128 is split and C takes 64–96 (12 K). Total 20 K. When A is released, its buddy 16–32 is free and 0–32 forms; its buddy holds B, so stop. When C is released, its buddy 96–128 is free and 64–128 forms; its buddy 0–64 is split, so stop. The free blocks are 0–32 and 64–128; B is at 32–64.
After
fork(), 50 pages are shared by copy-on-write. The child writes to pages 0–4; then the parent writes to pages 0, 1, and 10. How many pages are copied?Answer
6. The child's five writes produce five copies. When the parent writes to 0 and 1, the reference count of those frames is now 1; no copy is needed and the pages are simply made writable. Page 10 is still shared (reference count 2) and produces the sixth copy.
The 8-bit aging counters of three pages (s0, s1, s2) start at 0. The R bits seen at four ticks are: tick 0: 1 1 0, tick 1: 1 0 1, tick 2: 0 1 1, tick 3: 0 1 0. Which page do aging and NFU evict?
Answer
The counters are s0 = 00110000 (48), s1 = 11010000 (208), s2 = 01100000 (96). Aging evicts s0: it was not used in the last two ticks. The NFU counters are 2, 3, 2; s0 and s2 are tied and NFU cannot tell them apart. Yet s2 was used one tick earlier and is more recent.
On a server CPU utilization has fallen to 10% and the swap disk is constantly busy. An administrator says “the CPU is idle” and wants to add new batch jobs to the queue. What happens? What is the right intervention?
Answer
The system is thrashing: Σ |WSi| exceeds memory and the processes are waiting for pages. New work shrinks every process's frame share further, faults increase, and CPU utilization falls even more. The right move is to lower the degree of multiprogramming: suspend or swap out some processes and, as a lasting fix, add RAM. PFF makes this decision automatically from the per-process fault rate.
9.17Further reading
- R. H. Arpaci-Dusseau and A. C. Arpaci-Dusseau, Operating Systems: Three Easy Pieces, the chapters “Swapping: Mechanisms,” “Swapping: Policies,” and “Complete VM Systems”: they compare replacement policies on no-locality, 80-20, and looping workloads and describe the virtual memory design of VAX/VMS and Linux; free at ostep.org.
- P. J. Denning, “The Working Set Model for Program Behavior,” Communications of the ACM, 11(5), 1968: the foundational paper that introduced the working-set concept and its use against thrashing.
- J. Bonwick, “The Slab Allocator: An Object-Caching Kernel Memory Allocator,” USENIX Summer 1994: presents the object-cache idea and the Solaris measurements in a short and readable form.
- Linux kernel documentation,
admin-guide/mm/multigen_lru.rstandadmin-guide/mm/zswap.rst: describes the generations of MGLRU and the settings of zswap in the kernel's own documentation.
9.18References
- A. Silberschatz, P. B. Galvin, G. Gagne, Operating System Concepts, 10th edition, Wiley, 2018 — Chapter 10: Virtual Memory.
- A. S. Tanenbaum, H. Bos, Modern Operating Systems, 4th edition (2014) / 5th edition (2023), Pearson — Chapter 3: Memory Management.
- R. H. Arpaci-Dusseau, A. C. Arpaci-Dusseau, Operating Systems: Three Easy Pieces (OSTEP), ostep.org — “Swapping: Mechanisms,” “Swapping: Policies,” “Complete VM Systems.”
- L. A. Belady, “A Study of Replacement Algorithms for a Virtual-Storage Computer,” IBM Systems Journal 5(2), 1966; P. J. Denning, “The Working Set Model for Program Behavior,” CACM 11(5), 1968.
- R. W. Carr, J. L. Hennessy, “WSCLOCK — A Simple and Effective Algorithm for Virtual Memory Management,” SOSP 1981; J. Bonwick, “The Slab Allocator,” USENIX Summer 1994.
- Linux kernel documentation:
admin-guide/mm/multigen_lru.rst,admin-guide/mm/zswap.rst,admin-guide/mm/transhuge.rst,admin-guide/blockdev/zram.rst. - P. Yosifovich, A. Ionescu, M. Russinovich, D. Solomon, Windows Internals, 7th edition, Part 1, Chapter 5: Memory management.