Lesson 15 · Memory management

Clock Page Replacement: Second Chance

Arrange the frames in a circle and sweep a hand round them. A page whose reference bit is set is spared once and its bit cleared; the first page found with a clear bit is evicted.

Clock Page Replacement: Second Chance concept diagramA visual explanation of the layout and operations shown in this lesson.clock — sweep until a page with a clear reference bit turns up7R=1R=1 → spare, clear it0R=0R=0 → evict1R=1R=1 → spare, clear it3R=0R=0 → evictablethe MMU sets R=1on every access —free recency dataa set bit buys one full revolution of grace, which is why clock lands near LRU for almost no cost
1

How Second Chance Works

The second chance page replacement algorithm is FIFO with one extra bit per page. Each frame has a reference bit R that the MMU sets to 1 whenever the page is read or written. On a fault, the page at the head of the FIFO order is checked: if R = 0 it is evicted; if R = 1 the bit is cleared and the page goes to the back of the line, its second chance.

The clock page replacement algorithm is the same rule built without moving anything. The frames sit in a circular buffer and a hand points at the oldest one. Sparing a page just clears its bit and moves the hand on, so after a full lap the spared page is back at the head with its bit at 0.

The sweep always ends. In the worst case every bit is 1: the hand clears all of them in one lap and evicts the page it started on. So a victim is found after at most one lap plus one frame.

  • R = 0: evict the page under the hand
  • R = 1: clear R, spare the page, advance the hand
  • R is set by hardware, so hits cost no kernel work
2

Worked Example: 9 Faults in 3 Frames

This is the string the LRU, FIFO and OPT lessons use. Frames are numbered 0 to 2 round the circle, the hand starts at frame 0, and a newly loaded page gets R = 1, since loading it counts as a use. After each load the hand moves to the next frame.

The bit earns its keep at t = 6. FIFO would evict page 0 there, but 0 was used at t = 5, so its bit is 1: the hand clears it and evicts page 1 instead, and 0 hits at t = 7.

Three faults (t = 4, 8 and 11) find every bit set and need a full lap first. In those cases clock knows nothing that FIFO does not, and evicts the same page FIFO would.

Total: 9 faults and 4 hits, the same as exact LRU and one fewer than FIFO's 10. The victims differ from LRU's: at t = 9 clock evicts 0 while LRU evicts 3, because one bit cannot tell a page used at t = 7 from one used at t = 6.

Some textbooks load a page with R = 0 instead. On this string that version takes 8 faults, so check which convention an exam question uses before comparing answers.

Clock on 7,0,1,2,0,3,0,4,2,3,0,3,2 with 3 frames, hand at frame 0
tRefFramesR bitsEvent
1–37 0 17 0 11 1 13 faults into free frames
422 0 11 0 0full lap clears all bits, evicts 7
502 0 11 1 0hit, MMU sets R
632 0 31 0 1spares 0, evicts 1
702 0 31 1 1hit
844 0 31 0 0full lap, evicts 2
924 2 31 1 0evicts 0 (R = 0)
1034 2 31 1 1hit
1104 2 00 0 1full lap, evicts 3
1233 2 01 0 1evicts 4 (R = 0)
1323 2 01 1 1hit
  • Count check: 3 compulsory + 6 replacements = 9
  • Full laps at t = 4, 8 and 11: FIFO order when every bit is set
  • Loading pages with R = 0 gives 8 faults on this string
3

Enhanced Clock: Adding the Dirty Bit

Victims do not cost the same. A clean page has an identical copy on disk and can be dropped at once. A dirty page, one whose modify bit M is set, has to be written back before its frame can be reused, and the faulting process waits for that write.

The enhanced second chance algorithm reads both bits. Pass one looks for (0, 0) and changes nothing. If none is found, pass two takes the first (0, 1), clearing R on every page it passes. If that fails too, all R bits are now 0, so repeating the two passes is guaranteed to find a victim.

Real kernels pair this with background writeback, which cleans dirty pages ahead of time so the hand usually finds a clean victim.

Enhanced clock classes, best victim first
(R, M)MeaningWhat the hand does
(0, 0)Not used recently, cleanBest victim: drop it, no write
(0, 1)Not used recently, dirtyEvict after writing it back
(1, 0)Used recently, cleanSpare; R cleared on a later pass
(1, 1)Used recently, dirtySpare; worst victim
  • Dirty victims cost a disk write on the fault path
  • Search order: (0,0), then (0,1)
  • Background writeback keeps clean pages available
Key reference

Terms, operations, and practical uses

The rule

  • DecisionEvict the first page the hand finds with R = 0.
  • Second chanceR = 1 is cleared and the page spared until the hand returns.
  • Reference bitSet by the MMU on every access, at no software cost.
  • TerminationOne lap clears every bit, so a victim always exists.

Enhanced clock

  • (0, 0)Unused and clean: the best victim, no write-back.
  • (0, 1)Unused but dirty: evictable after a write.
  • (1, x)Used recently: spared, R cleared on a later pass.
  • Dirty bitA modified page must be written back before reuse.

Numbers

  • 9 faultsOn 7,0,1,2,0,3,0,4,2,3,0,3,2 with 3 frames; 8 if pages load with R = 0.
  • OthersFIFO 10, LRU 9, OPT 7 on the same string.
  • Belady's string9 faults with 3 frames, 10 with 4, like FIFO.
  • Cost modelWork on faults only, never on the memory-access path.
Implementation

Clock on 7,0,1,2,0,3,0,4,2,3,0,3,2 with 3 frames

def clock(refs, frames):
    """Clock (second chance) page replacement. Returns (faults, hits).

    Frames sit in a circular buffer. On a fault the hand advances past any page
    whose reference bit is set, clearing it on the way -- that is the second
    chance -- and evicts the first page it finds with a clear bit.
    """
    pages = [None] * frames
    referenced = [False] * frames
    hand = faults = hits = 0

    for page in refs:
        if page in pages:
            hits += 1
            referenced[pages.index(page)] = True  # the MMU does this in hardware
            continue

        faults += 1
        # Sweep. A full revolution clears every bit, so this always terminates.
        while pages[hand] is not None and referenced[hand]:
            referenced[hand] = False
            hand = (hand + 1) % frames

        pages[hand] = page
        referenced[hand] = True
        hand = (hand + 1) % frames

    return faults, hits


refs = [7, 0, 1, 2, 0, 3, 0, 4, 2, 3, 0, 3, 2]
faults, hits = clock(refs, 3)
print(f"{faults} faults, {hits} hits")  # 9 faults, 4 hits
#include <iostream>
#include <vector>

// Clock (second chance): a circular buffer of frames and a hand. A set
// reference bit buys the page one more revolution instead of eviction.
int clockReplace(const std::vector<int>& refs, int frames, int& hits) {
    std::vector<int> pages(frames, -1);
    std::vector<bool> referenced(frames, false);
    int hand = 0;
    int faults = 0;
    hits = 0;

    for (int page : refs) {
        bool resident = false;
        for (int i = 0; i < frames; ++i) {
            if (pages[i] == page) {
                ++hits;
                referenced[i] = true;  // set by the MMU on a real machine
                resident = true;
                break;
            }
        }
        if (resident) {
            continue;
        }

        ++faults;
        // A full revolution clears every bit, so the sweep always terminates.
        while (pages[hand] != -1 && referenced[hand]) {
            referenced[hand] = false;
            hand = (hand + 1) % frames;
        }

        pages[hand] = page;
        referenced[hand] = true;
        hand = (hand + 1) % frames;
    }

    return faults;
}

int main() {
    std::vector<int> refs = {7, 0, 1, 2, 0, 3, 0, 4, 2, 3, 0, 3, 2};
    int hits = 0;
    std::cout << clockReplace(refs, 3, hits) << " faults, " << hits << " hits\n";
    return 0;
}
import java.util.Arrays;

public class Main {

    /**
     * Clock (second chance). The hand sweeps a circular buffer, clearing set
     * reference bits and evicting the first page whose bit is already clear.
     */
    static int hits = 0;

    static int clock(int[] refs, int frames) {
        int[] pages = new int[frames];
        boolean[] referenced = new boolean[frames];
        Arrays.fill(pages, -1);
        int hand = 0;
        int faults = 0;

        for (int page : refs) {
            int slot = -1;
            for (int i = 0; i < frames; i++) {
                if (pages[i] == page) {
                    slot = i;
                    break;
                }
            }

            if (slot >= 0) {
                hits++;
                referenced[slot] = true;  // hardware sets this on a real machine
                continue;
            }

            faults++;
            // One full revolution clears every bit, so this terminates.
            while (pages[hand] != -1 && referenced[hand]) {
                referenced[hand] = false;
                hand = (hand + 1) % frames;
            }

            pages[hand] = page;
            referenced[hand] = true;
            hand = (hand + 1) % frames;
        }

        return faults;
    }

    public static void main(String[] args) {
        int[] refs = {7, 0, 1, 2, 0, 3, 0, 4, 2, 3, 0, 3, 2};
        int faults = clock(refs, 3);
        System.out.println(faults + " faults, " + hits + " hits");
    }
}
Watch it run

Step through it

Running on refs 7,0,1,2,0,3,0,4,2,3,0,3,2 · 3 frames, hand at frame 0

clock, 3 framesreference string7012030423032after frame 2 the hand wraps to frame 0frame 0frame 1frame 2handfaults 0 · hits 0
Step 1

Three frames in a ring, hand at frame 0

Clock keeps the frames in a circle with a hand pointing at the next candidate. Each frame has a reference bit R that the MMU sets to 1 whenever the page is used. On a fault the hand checks its frame: R = 0 means evict; R = 1 means clear it, spare the page and move on.

Output
1 / 16
4

Why Kernels Use Clock, and Where It Falls Short

Exact LRU must update an ordering on every memory access, which hardware cannot afford. Clock page replacement moves all its work to faults, when the process is already waiting for the disk and a short sweep is cheap by comparison. The recency information comes from a bit the MMU sets anyway.

The cost is resolution. One bit only says whether a page was used since the hand last passed. When every page was used, clock cannot rank them and evicts in FIFO order. On Belady's string 1,2,3,4,1,2,5,1,2,3,4,5 that happens on every fault, so clock takes 9 faults with three frames and 10 with four, the same anomaly as FIFO. Clock is not a stack algorithm.

Production systems refine the idea. Linux keeps active and inactive lists and promotes a page only after a second use, so one large scan cannot flush the working set. Solaris used a two-handed clock, where a front hand clears bits and a back hand evicts pages still at 0, with the gap between them setting how long a page has to prove itself.

Some processors, such as MIPS, have no hardware reference bit. The kernel then fakes one by marking pages invalid and setting the bit in the resulting fault, which turns a free signal into a costly one.

  • Work happens on faults, not on every memory access
  • All bits set: clock evicts in FIFO order
  • Not a stack algorithm: Belady's anomaly is possible
  • Without a hardware bit, the kernel simulates it with faults