The buffer cache and writing back
About this lesson
Disks are slow and RAM is fast, so the kernel keeps copies of disk blocks in memory: the buffer cache, which Linux calls the page cache. Follow four lines of C as a read misses and fetches a block from disk, the same read hits in RAM, a write changes only the cached copy and leaves it dirty, and fsync() finally puts it on the disk. Along the way you will see why a crash can lose data that write() said was written, how the kernel's flusher threads write back on their own, and how the cache makes room. FAT and ext4: two on-disk layouts shows where blocks live on the disk; the Linux lessons on the file system and on disks, partitions and mounts show the user's view. Crash consistency and journaling builds on this, with the same write-ahead idea as the Databases lesson on write-ahead logging and recovery.
The disk is slow
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.
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.
Read the lesson step by step
The disk is slow
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.
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.A cache of disk blocks
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.
page cache block -> copy in RAM slot 1 block 3 x slot 2 block 9 y slot 3 (free) block 3 was used longest ago. Linux: one unified page cache for files and memory.Line 1: a miss
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 1 n = pread(fd, buf, 1, 0); cache block 7? no -> miss disk read block 7 (all 4 KB) into a free slot copy 1 byte to buf: A returns n = 1 (bytes read) disk reads so far: 1Line 2: a hit
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.
line 2 n = pread(fd, buf, 1, 0); cache block 7? yes -> hit copy 1 byte to buf: A returns n = 1 disk reads so far: still 1Line 3: write to RAM only
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.
line 3 n = pwrite(fd, "B", 1, 0); cache block 7: A -> B, marked dirty returns n = 1 (bytes written) disk block 7: still A write(2): "A successful return from write() does not make any guarantee that data has been committed to disk."What if the power fails?
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.
what if: power fails now cache gone (RAM needs power) disk block 7: A lost the B that pwrite() accepted (only imagined: the program carries on)Writing back, later
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.
Linux defaults (mm/page-writeback.c) dirty_writeback_centisecs 500 wake every 5 s dirty_expire_centisecs 3000 dirty > 30 s: write dirty_background_ratio 10 % of memory dirty: start writing now OSTEP: most file systems buffer writes 5 to 30 s.Line 4: fsync, now
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.
line 4 r = fsync(fd); write block 7 -> disk, wait for the device disk block 7: B cache clean again (dirty mark cleared) returns r = 0 (success) the whole program (C99, POSIX): #define _POSIX_C_SOURCE 200809L #include <fcntl.h> #include <stdio.h> #include <unistd.h> int main(void) { char buf[1]; ssize_t n; int r; int fd = open("notes.txt", O_RDWR); /* holds one byte: A */ if (fd < 0) return 1; n = pread(fd, buf, 1, 0); n = pread(fd, buf, 1, 0); n = pwrite(fd, "B", 1, 0); r = fsync(fd); printf("%c %d %d\n", buf[0], (int)n, r); n = pread(fd, buf, 1, 0); printf("%c\n", buf[0]); return close(fd); } prints: A 1 0 BMaking 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.
least recently used first: block 3 (cached before the program ran) block 9 block 7 (used by lines 1 to 4) evict block 3: clean -> just drop it a dirty victim -> write it to disk, then drop itSpeed or safety
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.
write-back fast writes, a crash can lose the last seconds fsync() safe, but waits for the disk the cache as a Python simulation: disk = {3: "x", 7: "A", 9: "y"} # block -> bytes cache = {} # block -> [bytes, dirty] lru = [] # least recently used first reads = 0 def get(b): global reads if b in cache: lru.remove(b) # hit else: reads += 1 # miss: one slow disk read cache[b] = [disk[b], False] lru.append(b) return cache[b] def write(b, v): page = get(b) page[0], page[1] = v, True # RAM only: dirty def fsync(): for b, page in cache.items(): if page[1]: disk[b], page[1] = page[0], False def evict(): b = lru.pop(0) if cache[b][1]: disk[b] = cache[b][0] # dirty: write back first del cache[b] return b get(3); get(9); reads = 0 # warm cache print(get(7)[0], get(7)[0], "disk reads:", reads) write(7, "B") print("cache", cache[7][0], "disk", disk[7]) fsync() print("after fsync disk", disk[7]) print("evicted block", evict()) prints: A A disk reads: 1 cache B disk A after fsync disk B evicted block 3
5 quick questions
Choose one answer per question. You can change your choices before checking them.
01A program reads one byte of a file whose block is not in the page cache. What does the kernel read from the disk?
The cache holds whole blocks (4 KB here). On a miss the kernel reads the entire block into the cache, then copies the requested byte to the program. The next read of anything in that block is a hit.
02pwrite() has just returned 1 for a write to a cached page. Where is the new byte right now?
With write-back, the write changes the cached copy and marks it dirty. As write(2) puts it, a successful return does not guarantee the data has been committed to disk.
03The power fails a moment after that pwrite(), before any writeback. What does the file hold after a restart?
RAM loses its contents without power, so the dirty page is gone. The disk was never updated, so it still holds the old byte. This is the durability/performance trade-off of write buffering.
04What does fsync(fd) do?
fsync(2) flushes the file's modified buffer cache pages to the storage device and blocks until the device reports completion. It returns 0 on success. That is why databases call it at commit time.
05The cache is full and needs a slot. Which page does an LRU policy pick, and what happens if that page is dirty?
LRU drops the page used longest ago, betting it is the least likely to be needed soon. A clean page is simply dropped because the disk has the same bytes; a dirty one must be written back first or the change would be lost.
Glossary
- Buffer cache / page cache
- Copies of disk blocks that the kernel keeps in RAM so reads and writes can avoid the slow disk. Linux uses one unified page cache for files and memory.
- Block
- The unit a file system reads and writes on the disk, often 4 KB. A one-byte read still brings in the whole block.
- Cache hit / miss
- A hit finds the block already in the cache and needs no disk access. A miss must read the block from the disk first.
- Dirty page
- A cached page that has been changed in RAM and is newer than the copy on the disk.
- Write-back
- Writing changes to the cache now and to the disk later, in the background. Fast, but a crash can lose the changes not yet written.
- Flusher threads
- Linux kernel threads that wake up regularly (by default every 5 seconds) and write old dirty pages to disk.
- fsync()
- A system call that writes a file's dirty pages to the storage device and waits until the device reports they are stored.
- LRU (least recently used)
- An eviction policy: when room is needed, drop the page that was used longest ago.
Notes and sources
- 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.
- Whether line 1 misses depends on what is cached. A file read or written since the last reboot may still be in the page cache, and then even the first read is a hit.
- 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.
- fsync() also flushes the drive's own write cache when it has one, and it is where Linux reports errors from earlier background writes. Some programs, such as databases, skip the page cache entirely with direct I/O.
- xv6, the teaching kernel used at MIT, recycles exactly the least recently used buffer from a fixed set. Other kernels use LRU or cheaper variants of it.
- R. and A. Arpaci-Dusseau, Operating Systems: Three Easy Pieces, ch. 40: File System Implementation (40.7 Caching and Buffering)
- R. and A. Arpaci-Dusseau, Operating Systems: Three Easy Pieces, ch. 37: Hard Disk Drives
- MIT 6.1810: xv6, a simple Unix-like teaching operating system (book, rev. 4), section 8.2 Buffer cache layer
- Berkeley CS162, Lecture 20: File Systems 1
- Linux man-pages: fsync(2)
- Linux man-pages: pread(2) and pwrite(2)
- Linux man-pages: write(2)
- Linux kernel documentation: /proc/sys/vm (dirty_expire_centisecs, dirty_writeback_centisecs)
- Linux source: mm/page-writeback.c (writeback defaults)
Quiz Unlocks after the last step.