Lesson 10 · Memory management

Thrashing in OS

Every process faults on its next access, the CPU sits idle waiting on the disk, and the scheduler responds by adding more processes, which makes it worse.

Thrashing in OS concept diagramCPU utilisation against the number of processes on a 90-frame machine where each working set is 15 frames: 50% with 1 process, 87.5% with 3, 98.4% with 6, then a collapse to 5% at 7 and 8. The knee sits at 6 processes, and an arrow shows that suspending back to 6 restores it.thrashing0%50%100%CPU123456789045302218151211procsframesknee: 6 × 15 = 90 frames, memory full50%87.5%98.4%5%suspend → back to 6one process past the knee drops every process below its working set
1

Busy Disk, Idle CPU

Thrashing is the state in which a system spends more time handling page faults than running programs. The paging disk is busy all the time, the CPU is mostly idle, and almost no useful work gets done.

It is not simply being slow because of paging. It has a sharp start: as load grows, throughput does not sink gently but falls off a cliff at a point called the knee.

The mechanism is that each process holds fewer frames than the pages it is actively using, so almost every access faults, and the page it throws out to make room is usually one it needs again a moment later.

  • More time paging than running
  • Starts suddenly, not gradually
  • Edge case: one huge process can thrash on its own, with nothing else running
2

Causes of Thrashing

  1. A process gets fewer frames than its working set.
  2. It faults on almost every reference.
  3. The CPU idles while processes wait on the disk.
  4. The scheduler sees low CPU use and admits more processes.
  5. Each process gets even fewer frames, and the loop tightens.

The causes of thrashing are few, and they feed each other. The root cause is too few frames per process: if the pages a process is using do not fit in its frames, it faults on nearly every reference whichever replacement algorithm is used. The tracer shows a loop over 4 pages: 4 frames give no faults after the first pass, 3 frames make every reference fault.

The amplifier is a degree of multiprogramming that is too high, meaning too many processes in memory at once. Each new process takes frames from the others; below a threshold everyone still fits, past it nobody does.

What turns this into a collapse is the scheduler. It reads low CPU use as spare capacity and admits more processes, which is exactly the wrong move. Global page replacement spreads the damage, because a thrashing process steals frames from healthy ones.

  • Root cause: frames below the working set
  • Amplifier: too many processes, and a scheduler that adds more
  • Global replacement spreads it; local replacement contains it to one process
3

The Knee, and Why the Curve Collapses

Plot CPU use against the number of processes, as in the diagram above. It rises at first: with more processes, one is usually ready to run while others wait for I/O. A common estimate is 1 − wⁿ, where w is the share of time a process waits and n the number of processes.

The rise stops at the knee, where the working sets of all processes together fill physical memory. In the diagram, 6 processes of 15 pages fill 90 frames exactly and the CPU is busy 98.4% of the time.

One more process and every process drops below its working set at once, so CPU use falls almost straight down, here to 5%, because the CPU can only run as fast as the disk serves faults.

  • Before the knee: CPU use rises with load
  • At the knee: the working sets exactly fill memory
  • After it: the disk sets the pace and CPU use collapses
Key reference

Terms, operations, and practical uses

Terms to know

  • Working setThe pages a process used in its last Δ references.
  • Degree of multiprogrammingHow many processes are in memory at once.
  • KneeThe load at which working sets stop fitting and CPU use collapses.
  • Local replacementA faulting process may only evict its own pages.
Implementation

One frame short, then one process too many

TOTAL_FRAMES = 12
LOOP = [1, 2, 3, 4]  # each process cycles over these 4 pages: its working set
IO_WAIT = 0.5        # share of time a process waits on ordinary I/O
FAULT_TIME = 20      # one page fault takes as long as 20 references


def lru_faults(frames, references):
    memory = []  # least recently used first
    faults = 0
    for page in references:
        if page in memory:
            memory.remove(page)
        else:
            faults += 1
            if len(memory) == frames:
                memory.pop(0)
        memory.append(page)
    return faults


def thrashes(frames):
    # After the first pass every miss is a repeat miss: the loop does not fit.
    return lru_faults(frames, LOOP * 2) > len(LOOP)


for frames in (4, 3):
    print(f"{frames} frames: {lru_faults(frames, LOOP * 3)} faults in {len(LOOP) * 3} references")

print("\nprocs  frames each  CPU")
for n in range(1, 6):
    each = TOTAL_FRAMES // n
    if thrashes(each):
        cpu = 1 / FAULT_TIME  # every reference faults; the paging disk sets the pace
    else:
        cpu = 1 - IO_WAIT ** n  # chance that at least one process is ready
    print(f"{n:>5}  {each:>11}  {cpu * 100:5.1f}%")

# Working set model: suspend processes until the working sets fit.
n = 5
while n * len(LOOP) > TOTAL_FRAMES:
    print(f"{n} working sets need {n * len(LOOP)} frames, only {TOTAL_FRAMES}: suspend one")
    n -= 1
print(f"{n} processes fit in {n * len(LOOP)} frames")
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <vector>

const int TOTAL_FRAMES = 12;
const std::vector<int> LOOP = {1, 2, 3, 4};  // each process cycles over these 4 pages: its working set
const double IO_WAIT = 0.5;                  // share of time a process waits on ordinary I/O
const double FAULT_TIME = 20;                // one page fault takes as long as 20 references

std::vector<int> repeat(int times) {
    std::vector<int> r;
    for (int t = 0; t < times; t++) r.insert(r.end(), LOOP.begin(), LOOP.end());
    return r;
}

int lruFaults(int frames, const std::vector<int>& references) {
    std::vector<int> memory;  // least recently used first
    int faults = 0;
    for (int page : references) {
        auto it = std::find(memory.begin(), memory.end(), page);
        if (it != memory.end()) {
            memory.erase(it);
        } else {
            faults++;
            if ((int)memory.size() == frames) memory.erase(memory.begin());
        }
        memory.push_back(page);
    }
    return faults;
}

bool thrashes(int frames) {
    // After the first pass every miss is a repeat miss: the loop does not fit.
    return lruFaults(frames, repeat(2)) > (int)LOOP.size();
}

int main() {
    for (int frames : {4, 3})
        std::printf("%d frames: %d faults in %d references\n", frames, lruFaults(frames, repeat(3)), (int)LOOP.size() * 3);

    std::printf("\nprocs  frames each  CPU\n");
    for (int n = 1; n <= 5; n++) {
        int each = TOTAL_FRAMES / n;
        double cpu = thrashes(each)
            ? 1 / FAULT_TIME               // every reference faults; the paging disk sets the pace
            : 1 - std::pow(IO_WAIT, n);    // chance that at least one process is ready
        std::printf("%5d  %11d  %5.1f%%\n", n, each, cpu * 100);
    }

    // Working set model: suspend processes until the working sets fit.
    int n = 5;
    while (n * (int)LOOP.size() > TOTAL_FRAMES) {
        std::printf("%d working sets need %d frames, only %d: suspend one\n", n, n * (int)LOOP.size(), TOTAL_FRAMES);
        n--;
    }
    std::printf("%d processes fit in %d frames\n", n, n * (int)LOOP.size());
}
import java.util.ArrayList;
import java.util.List;

public class Main {
    static final int TOTAL_FRAMES = 12;
    static final int[] LOOP = {1, 2, 3, 4};  // each process cycles over these 4 pages: its working set
    static final double IO_WAIT = 0.5;       // share of time a process waits on ordinary I/O
    static final double FAULT_TIME = 20;     // one page fault takes as long as 20 references

    static List<Integer> repeat(int times) {
        List<Integer> r = new ArrayList<>();
        for (int t = 0; t < times; t++) for (int p : LOOP) r.add(p);
        return r;
    }

    static int lruFaults(int frames, List<Integer> references) {
        List<Integer> memory = new ArrayList<>();  // least recently used first
        int faults = 0;
        for (int page : references) {
            if (memory.contains(page)) {
                memory.remove(Integer.valueOf(page));
            } else {
                faults++;
                if (memory.size() == frames) memory.remove(0);
            }
            memory.add(page);
        }
        return faults;
    }

    static boolean thrashes(int frames) {
        // After the first pass every miss is a repeat miss: the loop does not fit.
        return lruFaults(frames, repeat(2)) > LOOP.length;
    }

    public static void main(String[] args) {
        for (int frames : new int[] {4, 3})
            System.out.printf("%d frames: %d faults in %d references%n", frames, lruFaults(frames, repeat(3)), LOOP.length * 3);

        System.out.printf("%nprocs  frames each  CPU%n");
        for (int n = 1; n <= 5; n++) {
            int each = TOTAL_FRAMES / n;
            double cpu = thrashes(each)
                ? 1 / FAULT_TIME                // every reference faults; the paging disk sets the pace
                : 1 - Math.pow(IO_WAIT, n);     // chance that at least one process is ready
            System.out.printf("%5d  %11d  %5.1f%%%n", n, each, cpu * 100);
        }

        // Working set model: suspend processes until the working sets fit.
        int n = 5;
        while (n * LOOP.length > TOTAL_FRAMES) {
            System.out.printf("%d working sets need %d frames, only %d: suspend one%n", n, n * LOOP.length, TOTAL_FRAMES);
            n--;
        }
        System.out.printf("%d processes fit in %d frames%n", n, n * LOOP.length);
    }
}
Watch it run

Step through it

Running on each process loops over pages 1 2 3 4; LRU; 12 frames in total; half of each process's time is ordinary I/O; a fault costs 20 references

one process · loops over pages 1 2 3 4 · LRU1234123412344 framesfreefreefreefreefaults 0 of 0 references12 frames · CPU utilisation by number of processesworking set = 4 pages per process
Step 1

12 frames, processes that loop over 4 pages

Each process runs a loop that touches pages 1, 2, 3, 4 again and again, so its working set is 4 pages. The machine has 12 frames to share. First, one process on its own.

Output
1 / 12
4

The Working Set Model

  1. W(t, Δ) = the distinct pages a process used in its last Δ references.
  2. Add up the working set sizes of all processes.
  3. If the total is more than the frames available, suspend a process.
  4. Give its frames to the processes that keep running.

The working set model, from Peter Denning, measures what each process is really using. Its working set is the set of distinct pages it referenced in the last Δ references, a window that slides as it runs.

Δ has to be chosen with care. Too small and the window misses pages the process is still using; too large and it keeps pages from a phase that has ended. A good Δ covers one locality: the pages one phase of the program works on.

The rule is then simple: if the working sets add up to more than memory, suspend a process and swap it out. That lowers the degree of multiprogramming, which is the opposite of what the scheduler does on its own. Tracking the window exactly is costly, so real systems approximate it with a timer and the reference bits.

  • Δ should span one locality
  • Cure is fewer processes, not more
  • Approximated in practice with reference bits sampled on a timer
5

Page Fault Frequency Control

Page fault frequency (PFF) watches the symptom instead: each process's fault rate. The OS sets an upper and a lower bound for it.

If a process faults more often than the upper bound, it has too few frames, so it gets more. If it faults less often than the lower bound, it has more than it needs, so some are taken back. If there are no free frames to give, a process is suspended, as in the working set model.

PFF is cheaper because the fault rate is counted anyway and there is no window to track. Both methods give the same answer: allocate memory by what a process is actively using, and when that cannot be done for everyone, run fewer processes.

  • Above the upper bound → give the process more frames
  • Below the lower bound → take frames back
  • No free frames → suspend a process
6

Spotting It and Avoiding It

On a running system, thrashing shows up as high disk activity on the swap device, a high page-in rate, and low CPU use in user code. On Linux, the si/so columns of vmstat stay high; the usual last resort is the out-of-memory killer, which ends a process to free its memory.

  • Add RAM, or run fewer memory-hungry jobs at once
  • Use local page replacement so one process cannot steal everyone's frames
  • Improve locality: work on data in blocks instead of jumping across it