DISKblock 7AFLUSHERPAGE CACHE · RAMblock 3xblock 9yblock 7ADIRTY1n = pread(fd, buf, 1, 0);2n = pread(fd, buf, 1, 0);3n = pwrite(fd, "B", 1, 0);4r = fsync(fd);bufABAB0
Back: the disk and the kernel's flusher threadsMiddle: the page cache in RAM; front: your program and its bufferTokens: requests, block 7 moving between disk and cache, bytes moving to the programAt the back, the disk holding block 7 and the kernel's flusher threads. In the middle, the page cache in RAM, with blocks 3 and 9 and one free slot. In front, the program and its buffer. The first read misses and pulls block 7 up from the disk; the second hits in RAM. The write changes only the cached copy and raises the dirty flag, so a power cut would lose it; fsync writes it to the disk. Block 3, least recently used, is dropped to make room. The 5 and 30 second figures are Linux defaults, set in /proc/sys/vm/dirty_writeback_centisecs and dirty_expire_centisecs. Writeback also starts early when too much memory is dirty, and a dirty page is written before its memory is reused.

Why cache

  1. A file lives on the disk, and disks are slow: OSTEP works out about 13.2 ms for one random 4 KB read on a 7,200 RPM hard disk. Memory (RAM) answers far faster, so the kernel avoids the disk whenever it can.

Reading

Writing back

Making room

What happens

;; step 1/10 · slow-disk
one random 4 KB read (OSTEP ch. 37)
  disk                 seek + rotation + transfer
  Cheetah 15K.5        about 6 ms
  Barracuda 7,200 RPM  about 13.2 ms

RAM loses everything when the power goes;
the disk keeps it. Speed vs safety starts here.

Early file systems kept a fixed-size cache of disk blocks, set at boot to roughly 10% of memory. Modern systems such as Linux use one unified page cache for file data and program memory, so the cache can use whatever RAM is free. The idea in this lesson is the same for both. Block 7 and the blocks 3 and 9 are made-up numbers for the picture; 4 KB is a common block and page size. The program in step 8 is real C99: run on a notes.txt holding A, it prints "A 1 0" and then B.