TExcelTAD
Home › Operating Systems: Linux & Windows › Page Replacement

Page Replacement

RAM is always full on a healthy system: whatever programs don't use, the OS fills with cached file data. So when a process needs a new page, the kernel usually has to take a frame away from someone else. Choosing which page to evict is the page-replacement problem. A good choice keeps the pages that will be used soon; a bad one causes a storm of page faults, each costing a disk read that is thousands of times slower than a RAM access.

What happens on eviction

text
  need a free frame
        |
        v
  pick a victim page  (replacement policy)
        |
        +-- clean page (unchanged since it was read)?  --> just drop it; it can be re-read from its file
        |
        +-- dirty file page?    --> write it back to its file first
        |
        +-- dirty anonymous page (heap, stack)?  --> write it to swap / the page file first
        |
        v
  clear the page-table entry (next access = page fault), flush the TLB entry, reuse the frame

The page-table accessed bit (set by the CPU on every access) and dirty bit (set on every write) are the only usage information the kernel gets for free. Every real policy is built on them.

The classic algorithms

Textbooks compare policies by replaying a reference string, the sequence of page numbers a program touches, on a fixed number of frames and counting page faults.

Algorithm Evicts Notes
FIFO The page that was loaded longest ago Simple; ignores how often a page is used
LRU The page not used for the longest time Very good, but exact LRU needs a timestamp on every access
Optimal (OPT, Bélády's) The page whose next use is farthest in the future Impossible in practice (needs the future); the benchmark
Clock (second chance) Sweeps frames in a circle; a page with its accessed bit set gets the bit cleared and is spared once Cheap LRU approximation; what real kernels build on

This simulation runs all four on the same reference string and frame count:

python · try it yourself
def fifo(refs, n):
    frames, queue, faults = set(), [], 0
    for p in refs:
        if p not in frames:
            faults += 1
            if len(frames) == n:
                frames.remove(queue.pop(0))
            frames.add(p)
            queue.append(p)
    return faults

def lru(refs, n):
    stack, faults = [], 0                     # most recently used at the end
    for p in refs:
        if p in stack:
            stack.remove(p)
        else:
            faults += 1
            if len(stack) == n:
                stack.pop(0)
        stack.append(p)
    return faults

def optimal(refs, n):
    frames, faults = [], 0
    for i, p in enumerate(refs):
        if p in frames:
            continue
        faults += 1
        if len(frames) == n:
            future = refs[i + 1:]
            victim = max(frames, key=lambda f: future.index(f) if f in future else len(future))
            frames.remove(victim)
        frames.append(p)
    return faults

def clock(refs, n):
    frames, ref_bit, hand, faults = [None] * n, [0] * n, 0, 0
    for p in refs:
        if p in frames:
            ref_bit[frames.index(p)] = 1
            continue
        faults += 1
        while ref_bit[hand]:                  # second chance
            ref_bit[hand] = 0
            hand = (hand + 1) % n
        frames[hand], ref_bit[hand] = p, 1
        hand = (hand + 1) % n
    return faults

refs = [7, 0, 1, 2, 0, 3, 0, 4, 2, 3, 0, 3, 2, 1, 2, 0, 1, 7, 0, 1]
print("reference string:", " ".join(map(str, refs)))
for n in (3, 4):
    results = {f.__name__: f(refs, n) for f in (fifo, lru, optimal, clock)}
    print(f"{n} frames: " + "  ".join(f"{k}={v}" for k, v in results.items()))
reference string: 7 0 1 2 0 3 0 4 2 3 0 3 2 1 2 0 1 7 0 1
3 frames: fifo=15  lru=12  optimal=9  clock=14
4 frames: fifo=10  lru=8  optimal=8  clock=9

Optimal is always the lowest; LRU and Clock come close; FIFO is worst here. Adding a frame helps every algorithm.

Watching LRU step by step

A frame-by-frame table makes the decisions visible. * marks a page fault:

python · try it yourself
refs = [1, 2, 3, 4, 1, 2, 5, 1, 2, 3, 4, 5]
n = 3
stack, faults = [], 0
print("ref | frames (LRU first)  | fault")
for p in refs:
    fault = p not in stack
    faults += fault
    evicted = ""
    if not fault:
        stack.remove(p)
    elif len(stack) == n:
        evicted = f"evict {stack.pop(0)}"
    stack.append(p)
    print(f" {p}  | {' '.join(map(str, stack)):<19} | {'*' if fault else ' '} {evicted}")
print("faults:", faults)
ref | frames (LRU first)  | fault
 1  | 1                   | *
 2  | 1 2                 | *
 3  | 1 2 3               | *
 4  | 2 3 4               | * evict 1
 1  | 3 4 1               | * evict 2
 2  | 4 1 2               | * evict 3
 5  | 1 2 5               | * evict 4
 1  | 2 5 1               |
 2  | 5 1 2               |
 3  | 1 2 3               | * evict 5
 4  | 2 3 4               | * evict 1
 5  | 3 4 5               | * evict 2
faults: 10

Bélády's anomaly

You would expect more frames to mean fewer faults. For FIFO that is not guaranteed: on some reference strings a bigger memory produces more faults. LRU and Optimal are stack algorithms (the pages held with n frames are always a subset of those held with n+1) and can never show this anomaly.

python · try it yourself
def fifo(refs, n):
    frames, faults = [], 0
    for p in refs:
        if p not in frames:
            faults += 1
            if len(frames) == n:
                frames.pop(0)
            frames.append(p)
    return faults

def lru(refs, n):
    stack, faults = [], 0
    for p in refs:
        if p in stack:
            stack.remove(p)
        else:
            faults += 1
            if len(stack) == n:
                stack.pop(0)
        stack.append(p)
    return faults

refs = [1, 2, 3, 4, 1, 2, 5, 1, 2, 3, 4, 5]
for n in range(1, 6):
    print(f"{n} frames: FIFO {fifo(refs, n):>2} faults   LRU {lru(refs, n):>2} faults")
1 frames: FIFO 12 faults   LRU 12 faults
2 frames: FIFO 12 faults   LRU 12 faults
3 frames: FIFO  9 faults   LRU 10 faults
4 frames: FIFO 10 faults   LRU  8 faults
5 frames: FIFO  5 faults   LRU  5 faults

FIFO faults 9 times with 3 frames but 10 times with 4: the extra frame made things worse. LRU only ever improves as frames are added (12, 12, 10, 8, 5). This is one more reason real kernels don't use plain FIFO.

Thrashing and the working set

The working set of a process is the set of pages it used during a recent window of time. If the frames given to a process are fewer than its working set, almost every access faults, the disk becomes the bottleneck and the CPU sits idle: this is thrashing. The cure is not a better algorithm but more RAM, fewer running programs, or programs with better locality.

python · try it yourself
def lru_faults(refs, n):
    stack, faults = [], 0
    for p in refs:
        if p in stack:
            stack.remove(p)
        else:
            faults += 1
            if len(stack) == n:
                stack.pop(0)
        stack.append(p)
    return faults

# a loop that cycles over 6 pages, 20 times
refs = list(range(6)) * 20
for frames in range(3, 9):
    f = lru_faults(refs, frames)
    bar = "#" * (f // 4)
    print(f"{frames} frames: {f:>3} faults / {len(refs)}  {bar}")
3 frames: 120 faults / 120  ##############################
4 frames: 120 faults / 120  ##############################
5 frames: 120 faults / 120  ##############################
6 frames:   6 faults / 120  #
7 frames:   6 faults / 120  #
8 frames:   6 faults / 120  #

With 5 frames (or fewer) for a 6-page loop, LRU evicts exactly the page that is needed next, every time: 100% faults. With 6 frames only the first touch of each page faults. Real systems show the same cliff.

What Linux actually does

Linux keeps pages on LRU lists: active and inactive, each split into anon (heap/stack, needs swap) and file (page cache, can simply be dropped or written back). New pages start inactive; a second access promotes them to active. The background thread kswapd wakes up when free memory drops below a watermark and reclaims from the tail of the inactive lists, using the accessed bit as a second chance, much like Clock. Since kernel 6.1 many distributions enable MGLRU (multi-generational LRU), which sorts pages into several age generations and scans page tables more efficiently.

The list sizes are visible in /proc/meminfo (we print the names; the numbers are machine-specific):

bash · try it yourself
grep -E '^(Active|Inactive)' /proc/meminfo | cut -d: -f1
Active
Inactive
Active(anon)
Inactive(anon)
Active(file)
Inactive(file)

vm.swappiness (0–200, default 60) tells the kernel how willing it is to evict anonymous pages to swap versus dropping file cache. See Swap & the Page File.

What Windows actually does

Windows manages memory per process as a working set, plus system-wide page lists:

text
   process working sets (pages in use)
        |  trimmed by the working-set manager (oldest / least-accessed pages first)
        v
   +------------------+     dirty pages    +-------------------+
   |  standby list    | <-- written out -- |   modified list   |
   |  (clean, cached) |                    | (must be written) |
   +------------------+                    +-------------------+
        |  if not reused soon
        v
   free list --> zero list (pages zeroed by a background thread) --> handed to a process
  • The balance set manager runs every second and, under memory pressure, the working-set manager trims pages from processes using an aging scheme based on the accessed bit (a Clock-like approximation of LRU).
  • A trimmed page is not lost immediately: it moves to the standby list (clean) or modified list (dirty, to be written to the page file by the modified page writer). If the process touches it again it gets a cheap soft fault back.
  • SysMain (formerly SuperFetch) pre-loads pages it predicts you will need onto the standby list, with priorities 0–7.
  • Since Windows 10, trimmed pages can also be compressed in RAM in the hidden Memory Compression process before any disk write; Linux's equivalent is zswap/zram.

Task Manager's Memory tab shows the lists as "In use", "Modified", "Standby" and "Free". From PowerShell (sample output, yours will differ):

powershell
PS C:\Users\ada> Get-Counter '\Memory\Standby Cache Normal Priority Bytes','\Memory\Modified Page List Bytes',
>>   '\Memory\Free & Zero Page List Bytes' | Select-Object -ExpandProperty CounterSamples |
>>   Format-Table Path, CookedValue

Path                                                  CookedValue
----                                                  -----------
\\ada-pc\memory\standby cache normal priority bytes    4128309248
\\ada-pc\memory\modified page list bytes                214749184
\\ada-pc\memory\free & zero page list bytes            1673117696
Linux Windows
Unit of policy Global LRU lists (per memory cgroup) Per-process working sets + global page lists
Approximation Active/inactive lists or MGLRU + accessed bit Working-set aging + accessed bit
Background reclaimer kswapd Balance set manager, modified page writer
Second chance for evicted pages Page cache, swap cache Standby / modified lists
Compression in RAM zswap, zram Memory Compression (store in the System process)

Learn more: Virtual Memory & Paging · Swap & the Page File

Test yourself

Which page does the Optimal (Bélády) algorithm evict?

  1. The oldest loaded page
  2. The least recently used page
  3. The page whose next use is farthest in the future
  4. A random page

What is Bélády's anomaly?

  1. LRU faulting more than FIFO
  2. More frames causing more page faults with FIFO
  3. Page faults that occur in kernel mode
  4. The TLB being slower than the page table

On Windows, where does a clean page go when it is trimmed from a working set?

  1. Directly to the page file
  2. To the standby list, from which it can be soft-faulted back
  3. It is zeroed immediately
  4. To the modified list