Why cache
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.
The kernel keeps copies of recently used disk blocks in spare RAM: the buffer cache. Linux calls it the page cache. Every read() and write() on a file goes through it. Here it already holds blocks 3 and 9.
Reading
Line 1 reads one byte of notes.txt. Its block, block 7, is not in the cache: a miss. The kernel reads the whole 4 KB block from disk into the cache while the program waits, then copies the byte, A, into buf.
Line 2 asks for the same byte again. Block 7 is in the cache now: a hit. The kernel copies A straight from RAM into buf. The disk does nothing at all, so the call returns much sooner.
Writing back
Line 3 writes B over that byte. The kernel changes only the copy in the cache and marks the page dirty: newer than the disk. pwrite() returns 1 straight away. The disk still says A.
Suppose the power failed right now. RAM forgets everything without power, so the dirty page would vanish. After a restart the disk would still say A: the write is lost, even though pwrite() said it worked.
Left alone, the change is still saved later. By default, Linux's flusher threads wake every 5 seconds and write out pages that have been dirty for over 30 seconds. This is write-back: fast now, on disk later.
Line 4 does not wait. fsync() tells the kernel to write this file's dirty pages to disk now. The kernel sends block 7, waits until the device reports it done, clears the dirty mark, then returns 0.
Making room
RAM is limited, so when the kernel needs room it drops a page that was used long ago. Block 3, least recently used and clean, is simply dropped: the disk has the same bytes. A dirty page would be written back first.
That is the trade-off. Write-back makes writes fast but can lose the last seconds of work in a crash. Programs that must not lose data, such as databases, call fsync() at the moments that matter.
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.