ENع
←Working sets and thrashing
Lesson 36 · Memory in practice

Working sets and thrashing

12 min10 steps5 questionsAdvanced
About this lesson

Paging lets programs use more memory than the machine has, but only up to a point. Each program actively uses a small set of pages, its working set. While the working sets of everything running fit in RAM, faults are rare. Once they do not, every fault throws out a page that is needed next, the disk becomes the bottleneck and the CPU sits idle: thrashing. Follow six page frames as two programs fit, a third tips them over, and the kernel recovers by running fewer programs. The lesson Page replacement: FIFO, LRU and clock explains the eviction policy used here, and Page faults and swapping to disk covers the fault itself.

You'll learn to

Tick what you feel confident about. These self-checks do not affect your lesson score.

Fig 36 · Interactive
01 / 10

RAM is a few shared frames

RAM is split into page frames, here just six, and every running program keeps its pages in them. A page that is not in RAM waits in swap on the disk. Touching it is a page fault: the kernel must fetch it first.

page frame   one page-sized slot of RAM (4 KiB on most PCs)
swap         disk space for pages that do not fit in RAM
page fault   the page is not in RAM: the kernel reads it
             from swap, maybe evicting another page first

this example: 6 frames, global LRU replacement
RAM access   about 100 ns     disk access   about 10 ms (OSTEP)
Loading figure…
or ← →
Read the lesson step by step
  1. RAM is a few shared frames

    RAM is split into page frames, here just six, and every running program keeps its pages in them. A page that is not in RAM waits in swap on the disk. Touching it is a page fault: the kernel must fetch it first.

    page frame   one page-sized slot of RAM (4 KiB on most PCs)
    swap         disk space for pages that do not fit in RAM
    page fault   the page is not in RAM: the kernel reads it
                 from swap, maybe evicting another page first
    
    this example: 6 frames, global LRU replacement
    RAM access   about 100 ns     disk access   about 10 ms (OSTEP)
  2. The working set

    A program uses only a few pages at a time. Its working set is the pages it touched in its last few references, here the last 4. Program A loops over three pages, so its working set is a1, a2, a3: three frames.

    A's references   a1 a2 a3 a1 a2 a3 ...
    
    window 1   a1 a2 a3 a1   ->  working set {a1, a2, a3}
    window 2   a2 a3 a1 a2   ->  working set {a1, a2, a3}
    window 3   a3 a1 a2 a3   ->  working set {a1, a2, a3}
    
    window size Δ = 4 references; the set keeps 3 pages
    Δ too small misses part of the loop; too large mixes
    in pages from older phases of the program (CS162).
  3. Two programs fit

    Programs A and B take turns, one reference each. Their working sets need 3 + 3 = 6 frames, and RAM has 6. The first touch of each page faults and loads it from swap: 6 faults, once.

    turns: A, B, A, B, ...  one reference each
      A needs a1: fault, load into frame 0
      B needs b1: fault, load into frame 1
      A needs a2: fault, load into frame 2
      B needs b2: fault, load into frame 3
      A needs a3: fault, load into frame 4
      B needs b3: fault, load into frame 5
    
    frames  0:a1  1:b1  2:a2  3:b2  4:a3  5:b3
    these first-touch faults are compulsory: every page
    must be loaded once before it can hit
  4. Then every access hits

    Now every page A and B use is already in RAM. Each access takes about 100 nanoseconds and never waits for the disk. In the next 18 references not one faults, so the CPU spends its time on real work.

    next 18 references: 0 faults
    fault rate   0%
    time per access   about 100 ns
    
    average access time (OSTEP):
      AMAT = T_mem + fault rate x T_disk
           = 100 ns + 0 x 10 ms = 100 ns
  5. A third program arrives

    Program C starts and also needs three pages: 3 + 3 + 3 = 9 frames wanted, 6 available. C touches c1, which is not in RAM. To make room, LRU (least recently used) evicts the page used longest ago, a1.

    turns now: C, A, B, C, A, B, ...
      C needs c1: fault, evict a1, load into frame 0
    
    demand  3 + 3 + 3 = 9 frames     RAM  6 frames
    LRU picked a1: A used it longest ago...
    ...and A is about to use it again
  6. Each fault evicts a needed page

    A needs a1 next: fault, and LRU evicts b1. B needs b1: fault, evicting a2. C needs c2: fault, evicting b2. Every page thrown out is one a program will need a moment later.

      A needs a1: fault, evict b1, load into frame 1
      B needs b1: fault, evict a2, load into frame 2
      C needs c2: fault, evict b2, load into frame 3
    
    a loop over more pages than fit is the worst case
    for LRU: the oldest page is always the next one used
    (OSTEP: 50 pages looping in 49 frames hit 0%)
  7. Thrashing

    Now every reference faults, and each fault waits about 10 milliseconds for the disk, 100,000 times longer than a RAM access. The programs only wait, and the CPU does useful work about 0.001% of the time. This is thrashing.

      A needs a2: fault, evict a3, load into frame 4
      B needs b2: fault, evict b3, load into frame 5
      C needs c3: fault, evict c1, load into frame 0
      A needs a3: fault, evict a1, load into frame 1
      B needs b3: fault, evict b1, load into frame 2
      C needs c1: fault, evict c2, load into frame 3
    
    frames  0:c3  1:a3  2:b3  3:c1  4:a2  5:b2
    fault rate   100%   (every reference)
      AMAT = 100 ns + 1 x 10 ms = about 10 ms per access
    useful work  100 ns / (100 ns + 10 ms) = 0.001%
    Thrashing: busy swapping pages in and out
    with little or no actual progress (CS162).
  8. Run fewer programs

    The cure is admission control: run fewer programs. The kernel suspends C and swaps its pages out. A and B fit again: after 2 faults bring back their missing pages, every access hits and the CPU is busy again.

    suspend C:   c3 (frame 0) -> swap, c1 (frame 3) -> swap
    frames  0:--  1:a3  2:b3  3:--  4:a2  5:b2
    turns: A, B, A, B, ...
      A needs a1: fault, load into frame 0
      B needs b1: fault, load into frame 3
    frames  0:a1  1:a3  2:b3  3:b1  4:a2  5:b2
    next 30 references: 0 faults
    C waits on the side and runs later, when A or B ends.
  9. How Linux sees it

    Linux measures the stalls: /proc/pressure/memory reports the share of time tasks wait for memory, and a long "full" stall, every task waiting at once, means thrashing. If memory runs out entirely, the out-of-memory killer ends a large process.

    $ cat /proc/pressure/memory        (format)
    some avg10=0.00 avg60=0.00 avg300=0.00 total=0
    full avg10=0.00 avg60=0.00 avg300=0.00 total=0
      some: share of time at least one task stalled
      full: share of time all non-idle tasks stalled
    
    count your own faults with getrusage(2), C99 on Linux:
    (ru_majflt and ru_minflt are Linux/BSD fields, not POSIX)
    
    #include <stdio.h>
    #include <sys/resource.h>
    
    int main(void) {
        struct rusage u;
        if (getrusage(RUSAGE_SELF, &u) != 0)
            return 1;
        printf("major faults: %ld\n", u.ru_majflt);  /* needed the disk */
        printf("minor faults: %ld\n", u.ru_minflt);  /* no disk I/O */
        return 0;
    }
  10. The rule: add up working sets

    Add up the working sets of everything running and compare with RAM: 3 + 3 = 6 frames fits in 6, but 3 + 3 + 3 = 9 does not. When total demand exceeds RAM, the system thrashes; running fewer programs fixes it.

    D = sum of |WS_i|   total demand, in frames
    m = frames of RAM
    D > m  ->  thrashing; suspend programs until D <= m
    
    the example as a Python simulation:
    
    from collections import OrderedDict
    
    def run(programs, frames=6, refs=36):
        ram = OrderedDict()               # resident pages, least recent first
        faults = 0
        for t in range(refs):             # programs take turns, one reference each
            p = programs[t % len(programs)]
            page = p + str(t // len(programs) % 3 + 1)   # each loops over 3 pages
            if page in ram:
                ram.move_to_end(page)     # hit: now the most recent
            else:
                faults += 1               # page fault
                if len(ram) == frames:
                    ram.popitem(last=False)   # evict the least recently used
                ram[page] = True
        return faults
    
    print("A+B:  ", run("AB"), "faults in 36 refs")
    print("A+B+C:", run("ABC"), "faults in 36 refs")
    
    prints:
    A+B:   6 faults in 36 refs
    A+B+C: 36 faults in 36 refs

Quiz Unlocks after the last step.