Act VI · One Machine, Many Programs
Part 34 of 61Storage
How does data survive a power cut that can arrive between any two writes to the disk?
Appending one block to a file takes three writes: the bitmap, the data and the inode. The part opens by crashing after every subset of them: two of the eight outcomes are corrupt, two lose a block, and one passes fsck yet ends the file with a deleted file's password. It then builds storage from the bottom: the disk's seek, rotation and transfer, flash with its erase blocks and write amplification, inodes and directories, and PebbleFS, a small Unix file system, with FFS's locality. The centre of the part is crash consistency. PebbleFS is crashed at every point a disk could stop: with no ordering 34 of 126 crash points corrupt it, careful ordering costs 13 flushes instead of 5, and ordered journaling leaves all 150 intact. The part turns to the other designs that never overwrite, the log-structured file system and copy-on-write trees with checksums, and to RAID, where parity and Part 28's field rebuild lost disks. It then turns to the field, where disks fail more often and more quietly than datasheets say and fsync is easy to misuse, and ends with LSM trees and PebbleOS reading the thirty novels from its own disk: ledger row 12, 2.66 seconds.
What you need. Reading and writing files in C or Python; XOR. The memory hierarchy of Part 9 and the finite field of Part 28 are assumed.
- Mathematics, ideas and history
- disks and flash, file systems, FFS, crash consistency and journaling, LFS, copy-on-write, RAID, LSM trees
- What we build or compute
- a crash-tested file system
What you will be able to do
Degree
- Compute the time of a random and of a sequential disk read from seek, rotation and transfer, and explain why flash cannot overwrite in place.
- Follow a path through superblock, inodes and directory blocks, and compute the largest file an inode's pointers allow.
- List the disk states a crash can leave after an append, and say how a journal's commit block decides between the old file and the new.
Graduate
- Compare writeback, ordered and data journaling by what each crash state can contain, and explain why the commit needs a flush or a checksum.
- Derive the cleaner's write cost 2/(1 - u), check flash's write amplification against the estimate (1 + p)/2p, and compute RAID 5's small-write cost and mean time to data loss.
- Compare leveled and tiered LSM compaction by write, read and space amplification.
Research
- Explain what FSCQ and Yggdrasil prove about a file system and how CrashMonkey tests one, given that k unflushed writes leave 2^k crash states.
- State the LSM design space of Monkey and Dostoevsky and the open problems of zoned storage.
Industry
- Replace a file safely with write, fsync and rename, and name the bugs of in-place updates and of delayed allocation.
- Estimate the chance of a second failure or an unreadable sector during a RAID rebuild from field failure rates, not the datasheet, and decide on scrubbing and checksums.
Contents
Each chapter has a home level. Choose a track to see what to read and watch: Degree 31 min · Graduate 48 min · Research 50 min · Industry 37 min.
- 0One append, three writesDegree2 min
- 1PersistenceDegree2 min
- 2DisksDegree3 min
- 3FlashDegree4 min
- 4Files and directoriesDegree2 min
- 5A simple file systemDegree2 min
- 6LocalityGraduate3 min
- 7Crash consistencyDegree3 min
- 8JournalingDegree3 min
- 9The log-structured file systemGraduate2 min
- 10Copy-on-write and checksumsGraduate3 min
- 11RAIDDegree3 min
- 12Disks in the fieldIndustry3 min
- 13fsync, and what applications must doIndustry3 min
- 14LSM treesGraduate3 min
- 15PebbleOS gets a diskDegree3 min
- 16Frontier: storage that can be trustedResearch3 min
- Recap, problems, and where this comes backAll tracks3 min
Also on this page: Lecture · Key results · Try it · Lab · Problems · Notes and sources · 中文 · Build the film.
Lecture
The text of each chapter is the film's narration, as it is spoken, so you can read along or revise without the film. The pictures are in the film.
One append, three writesDegree2 min
You add a line to a file, and the power fails. What is on the disk? To append a block, the file system must change three blocks: a bitmap, to mark a free block as used; the block itself, with the new data; and the file's inode, to point at it and record the new length. In memory all three change at once. But the disk writes one block at a time, and it is free to reorder them for speed. So a crash can leave any subset of the three on the disk. Eight possible disks.
Here they are, all eight, each mounted and checked. Nothing written: the old file, intact. Only the data written: also fine, the new block sits unused. Bitmap without inode: a block is marked used that nobody owns. A leak, harmless but wasteful. The inode without the bitmap: the file points at a block the bitmap calls free, and the next file to be written will be handed it too. Corrupt. And the worst: bitmap and inode, but not the data. The checker finds nothing wrong at all. Yet the file now ends with whatever that block held before: here, a password from a file someone deleted. Across four common operations our checker finds 34 crash points that corrupt the file system and 22 that show the wrong bytes. With a journal, every one comes back intact. This part is about why.
1PersistenceDegree2 min
Part 9 drew the memory hierarchy, and stopped at main memory. Below it is storage. On a scale of time, a register answers in a third of a nanosecond, the first cache in about one, main memory in about a hundred. Then a gap. A flash drive reads a random page in about eighty microseconds. A spinning disk takes about thirteen milliseconds. If a memory read took one second, a disk read would take a day and a half. Flash closed most of that gap, but storage is still a thousand times slower than memory, and everything in this part is shaped by that.
Why have storage at all? Because memory forgets. A bit of main memory is a little charge on a capacitor, and it leaks away; Part 5's DRAM is refreshed every sixty-four milliseconds, and when the power goes, its contents fade within minutes. Storage keeps a bit without power: as a magnetized patch on a spinning platter, or as charge trapped behind an insulator in flash. It lasts for years. The price is that storage is read and written in whole blocks, and slowly. IBM's first disk, in 1956, held five million characters on fifty platters two feet across. A modern drive holds four million times as much in the palm of a hand, by the same principle.
Underneath all the variety, the operating system sees one simple thing: a numbered array of blocks. It can read block n, or write block n; nothing smaller. Devices use blocks of 512 bytes or 4 kilobytes; our file system will use one kilobyte. Two facts about this interface carry the whole part. A single block write is atomic: after a crash, the block holds either the old contents or the new ones. But two block writes are not. A crash can come between them, and the disk may even have done the second one first. File systems and databases are, in the end, ways of building big atomic changes out of small ones.
2DisksDegree3 min
A hard disk is a stack of platters spinning on one spindle, with an arm that carries a head over each surface. Reading a block takes three steps. First the seek: the arm swings to the right track. It accelerates and then brakes, so the time grows like the square root of the distance: half a millisecond to the next track, sixteen across the whole disk, almost nine on average. Then the rotation: the head waits for the sector to come round. At 7200 turns a minute, a turn is 8.3 milliseconds, so the average wait is half that. Then the transfer, as the sector passes under the head: 150 megabytes a second, so four kilobytes take 27 microseconds. A random read: thirteen milliseconds, and nearly all of it is spent waiting for things to move.
That waiting is the whole story of disk performance. Read the disk in order, and after one seek every block arrives as it passes the head: 150 megabytes a second. Read four-kilobyte blocks at random places, and each one costs a seek and half a turn: 77 reads a second, a third of a megabyte a second. Nearly five hundred times slower, for the same disk. So the rule for everything that follows: keep together what will be read together, and write in long runs. File systems, logs and databases are designed around it.
A busy disk has a queue of requests, and the order it serves them in matters. Here is the textbook example: the head at cylinder 53, eight requests waiting. First come, first served zigzags across the disk: 640 cylinders of travel. Shortest seek first always goes to the nearest request: 236. SCAN, the elevator, sweeps one way serving everything on its path, then the other way: 299 here. C-SCAN sweeps one way only and jumps back, so every cylinder waits about the same: 322, not counting the jump.
Static queues hide the real problem, so here is a simulated disk with 72 random requests arriving every second, close to the most it can serve. First come, first served keeps up only just: the mean response is near a tenth of a second. Shortest seek first cuts the mean by a factor of three, but its worst case is long: a request at the far edge keeps losing to nearer ones. That is starvation. SCAN matches its mean and bounds the wait, because the sweep always comes back. Today the drive does much of this itself: it accepts a queue of commands and orders them, because only it knows where the platter is. For flash, with no arm at all, Linux often schedules nothing.
3FlashDegree4 min
Flash stores a bit as charge trapped on a floating gate, behind an insulator. Its shape dictates everything a flash drive does. The chip is read a page at a time, a few kilobytes, in tens of microseconds. It is written a page at a time too, but only into a page that has been erased: programming can only push bits one way. And erasing works only on a whole block of hundreds of pages, and takes milliseconds. Worse, every erase wears the insulator a little; today's dense chips survive a few thousand per block. So you cannot simply overwrite a page. Rewriting four kilobytes in place would mean erasing and rewriting a whole block, and wearing it out.
The answer is a piece of software inside every drive, the flash translation layer, and it is a log. The host writes logical pages A, B, C, D, and they go to the next free pages, in order. Now the host rewrites B. The drive does not touch the old page: it writes the new B to the next free page, marks the old one dead, and updates its map from logical to physical pages. The same for A. Free pages run out, so a garbage collector picks a victim block, copies the pages still alive in it to a fresh block, and erases it. Those copies are writes the host never asked for. The ratio of what the flash writes to what the host writes is the write amplification, and it costs both speed and lifetime.
How bad is it? We simulate a drive of 256 blocks, fill it, then write six times its capacity at random places. The one parameter that matters is the spare flash the drive keeps hidden from the host, the over-provisioning. With seven percent spare, typical of a consumer drive, the flash writes seven and a half pages for every page the host writes. With 28 percent, an enterprise figure, about two and a half. The dots follow a simple estimate closely: one plus p, over two p. With little spare, the collector's victim is still mostly alive, and copying it is most of the work. Collecting the oldest block instead of the emptiest is a little worse everywhere.
Three more things every drive must handle. Real traffic is skewed. With writes spread evenly, the blocks wear evenly. Send ninety percent of the writes to a tenth of the data, and the amplification hardly changes, but the busiest blocks are erased almost three times as often as the average, and would die first. So drives practise wear leveling, moving cold data onto worn blocks to rest them. Second, the drive cannot know which pages hold files you have deleted, and faithfully copies them forward. TRIM is the command by which the file system tells it. With a fifth of the drive trimmed, amplification falls from seven and a half to about two. And third, a drive is dozens of chips that can all work at once. NVMe gives it tens of thousands of queues, one per core, so no lock stands between the cores and the chips.
4Files and directoriesDegree2 min
To a program, a file is a name and an array of bytes. The operating system splits that in two. The bytes, wherever they are on the disk, are described by an inode: a small record of the file's type, size, owner, permissions and times, and where its blocks lie. Inodes are numbered. A directory is just another file, whose contents are a table pairing names with inode numbers. So a path is followed one step at a time: the root directory's table gives the inode of novels, whose table gives the inode of emma. Multics introduced this tree of directories in 1965, and Unix made it simple. Notice that the name is not part of the file. It lives in a directory, so a file can have several.
Programs reach files through a handful of system calls, unchanged since early Unix. Open walks the path, checks permission once, and returns a small integer, the file descriptor. Read copies bytes from the current offset and moves it forward; lseek moves it anywhere. Write copies bytes in, but usually only into memory, the page cache. It returns long before the data is on the disk. Fsync is the call that waits until it is: chapter 13 is about what that really means. Inside the kernel, the descriptor indexes the process's table, which points to an open-file entry holding the offset, which points to the inode.
Because names live in directories, a file can have more than one. Link adds a second directory entry for the same inode, and the inode counts its links: two. Unlink removes one name. There is no call to delete a file: its blocks are freed when the last name is gone and no process still has it open. Rename moves a name, atomically, even over an existing file; we will lean on that. A symbolic link is something else: a tiny file containing a path, followed when it is opened. Our file system has the first three, and the tests check every one.
5A simple file systemDegree2 min
Now we build one: PebbleFS, a small Unix file system in the style of the original, on a disk of eight thousand one-kilobyte blocks. Block zero is the superblock, which says where everything else is. Then two bitmaps, one bit per inode and one per data block, saying which are free. Then the inode table: 256 inodes of 64 bytes, sixteen to a block. A journal, which we will need in chapter 8. And the rest, almost all of the disk, for data. The bar is drawn on a square-root scale; otherwise the metadata would be invisible.
Here is a PebbleFS inode: sixteen words. The type, the number of links, the size in bytes. Then ten direct pointers, each the number of one data block: enough for a file of ten kilobytes. For larger files, a single-indirect pointer names a block that holds 256 more pointers. And a double-indirect pointer names a block of 256 pointers to such blocks: sixty-five thousand more. So the largest file is just over 64 megabytes. The tree is lopsided on purpose: most files are small, and they need no indirect block at all, while a big one pays one extra read per 256 blocks.
Watch the disk while a program opens slash novels slash emma and reads it. This is PebbleOS's kernel doing it, the one chapter 15 builds, and every block is logged. At boot, the superblock. Then the root's inode, from the inode table. The root directory's block: the entry novels gives inode 2. Its inode is in the same table block, already in the kernel's buffer, so no read. Then the novels directory, where emma is inode 3. And then the file's own blocks, one after another. Two hundred kilobytes cost 201 reads: the data, one indirect block, and the four reads of the lookup.
6LocalityGraduate3 min
The first Unix file system put blocks wherever a free one happened to be. Free blocks were kept on a list in the order they were freed, so after a while a file's blocks lay all over the disk. Measured at Berkeley, it delivered about two percent of what the disk could do. McKusick and his colleagues' fast file system of 1984 divided the disk into cylinder groups, each a little file system of its own, with its bitmaps, its inodes and its data close together. A file's inode goes in the same group as its directory, and its blocks near its inode, so a directory listing and a file read stay in one place. A very large file is moved to a fresh group every so often, so that it cannot crowd out its neighbours. And blocks grew to four kilobytes. Together these made the file system many times faster.
We can measure this with PebbleFS and the disk model. One four-megabyte file, laid out three ways, then read in full. Written alone, its blocks are handed out in a row, and reading it takes 41 milliseconds, close to the 28 it takes the platter to pass that much data under the head. Written while another file grows beside it, the two files take turns: every other block is the neighbour's. In the model the head just waits for the gaps to pass, so this costs less than twice as much; but each run is now one block long. On an aged disk, where free blocks are scattered, every block costs a seek. Seventeen seconds: four hundred times slower. Even flash, with no arm, is two hundred times slower, because it serves four thousand tiny requests instead of a few large ones.
Modern file systems push the idea further. Instead of one pointer per block, they record extents: a first block and a length. One ext4 extent maps a run of up to 128 megabytes, so a big contiguous file is described in a few records rather than thousands of pointers. Delayed allocation decides where the blocks go only when the data is finally written out, by which time the file system knows how big the file is, and two files growing together no longer interleave. And a program that knows its size can reserve a run in advance. On flash, the drive remaps blocks under the file system anyway, but large sequential requests still beat small scattered ones. Delayed allocation has a price, though, and chapter 13 will make us pay it.
7Crash consistencyDegree3 min
What does it mean for a file system to survive a crash? Its structures must agree with each other. The Unix tool fsck, the file system check, tests exactly these. Every block in use is marked used. Every block marked used belongs to some file; if not, it has leaked, which wastes space but harms nothing. No block belongs to two files. Every directory entry names a live inode. Link counts match the names. And sizes are covered by blocks. Our fsck checks all six, and can repair them. What no checker can see is a file that is perfectly consistent but full of the wrong bytes, as in the hook.
To study this honestly we need every crash, not a few lucky ones. So the file system records every block write and every flush it makes. A flush is a barrier: writes before it are safely on the disk. Of the writes after the last flush, the disk may have done any subset, in any order. For every possible disk, the checker mounts it, runs fsck, and reads the files back. Four everyday operations: appending, creating, unlinking, renaming. Written with no care at all, as the hook did, they give 126 crash points. 34 leave the file system corrupt, and 22 more show the wrong bytes.
The first defence is order. Most of the damage comes from a pointer reaching the disk before the thing it points to. So when allocating, write the data first, then the bitmap, then any indirect block, then the inode, then the directory entry, and flush between them. When freeing, go the other way: clear the pointer before freeing what it pointed to. The checker confirms it. With careful ordering, no crash point is corrupt, and no file shows the wrong bytes. The worst a crash can do is leak a block or an inode, which fsck can reclaim at leisure. The price is waiting: thirteen flushes instead of five. Ganger and Patt's soft updates keep the same order without the waits, by tracking which buffered blocks depend on which, and FreeBSD has used them for decades.
Fsck itself has two problems. It must read every inode and every directory, whatever went wrong, so its cost grows with the disk: four times the disk, about four times the reads. On a disk of many terabytes that meant hours with the machine down, after every power cut. And it restores consistency, not correctness: it can make the structures agree, but it has no idea what any file should contain. What if, instead, the file system wrote down what it was about to do before doing it? Then recovery would only have to read that note.
8JournalingDegree3 min
A journal, or write-ahead log, is a reserved area of the disk where the file system writes down what it is about to do. Here is one append, every block write in order. First, in ordered mode, the new data goes straight to its block, and the disk is flushed. Nothing points at it yet, so this is harmless. Then, into the journal: a descriptor saying which home blocks this transaction changes, here the bitmap and the inode, followed by copies of their new contents. Flush. Then one more block: the commit. A single block write is atomic, so this is the moment the whole transaction happens. Flush. Only now are the bitmap and the inode written to their real places, the checkpoint, and then the journal is cleared for the next transaction.
Now crash after each of those writes, and mount the disk. Before the commit block, the journal holds an unfinished transaction. Recovery sees no commit and throws it away: the old file, intact. After the commit, recovery copies the journaled blocks to their homes, whether or not the checkpoint got there first. Replaying twice gives the same result, so a crash during recovery is harmless too. The new file, intact. And recovery reads only the journal: a handful of blocks, on a disk of any size. That is why journaling replaced the long fsck.
There is a choice about what goes through the journal. Journal only the metadata, and let data blocks reach the disk whenever they like, and the structures always survive. But 90 of the crash points leave a file ending in someone else's old bytes. Ordered mode, the default in ext3 and ext4, writes the data to its home before the metadata that points to it commits, which is what we traced. Every crash point comes back intact. Journaling the data too is just as safe but writes every data block twice. Real journals also batch: ext4 gathers the changes of many operations into one transaction, committed every five seconds by default.
Each flush makes the file system wait for the disk, so it is tempting to drop one. Remove the flush between the journal copies and the commit block, and the disk may write the commit first. The checker finds 25 crash points where recovery sees a commit, replays the journal, and copies in blocks that were never written for this transaction: stale contents from an earlier one. Corruption, created by the recovery itself. The fix is a checksum of the copies, stored in the commit block. Recovery replays only a transaction whose copies match, and every crash point comes back intact. ext4 does exactly this. It all still rests on the disk telling the truth about its flushes, which we will question in chapter 13.
9The log-structured file systemGraduate2 min
In 1992 Rosenblum and Ousterhout asked a radical question. Memories had grown large enough that most reads were served from the cache, so what a disk mostly did was write. And small writes scattered over the disk are the slowest thing it can do. So buffer every change, file data and inodes alike, and write them all out together, in order, as one long segment, at the disk's full speed. Never write anything in place. But then an inode moves every time it changes. A map of where each inode now is is written into the log too, and a checkpoint region at a fixed place says where the newest map is. Crash recovery starts from the last checkpoint and reads forward. The catch: every overwrite leaves a dead copy behind, and the free space fills with holes.
The cleaner reclaims the holes. It reads some segments, writes their live blocks back out compactly, and the old segments are free again. To free a segment whose live fraction is u, it reads the whole segment and writes back u of it, to gain 1 minus u of space for new data. So each byte of new data costs two over one minus u bytes of disk traffic. If the cleaner had to clean segments as full as the disk is on average, the cost would explode as the disk fills. Our simulation, after Rosenblum's, does better than that line, because the cleaner picks the emptiest segments, which are emptier than average. With hot and cold data, ninety percent of the writes going to a tenth of the files, the greedy cleaner gains only a little. Rosenblum's cost-benefit policy does much better, as the next picture explains.
10Copy-on-write and checksumsGraduate3 min
A third answer to crashes: never overwrite anything. NetApp's WAFL file system did this in 1994, and ZFS and btrfs later. The whole file system is a tree of blocks hanging from one root. To change one data block, write the new contents to a fresh block. Its parent must now point somewhere else, so write a fresh copy of the parent too, and so on up to a new root. In our tree of depth three that is four blocks, and every other block is shared between the old tree and the new. The last step is one small write: the uberblock, at a fixed place, switches to the new root. Crash before that write, and the old tree is untouched. Crash after, and the new one is complete. There is no journal to replay and nothing for fsck to do.
Copy-on-write makes a second idea cheap. Since a parent is rewritten whenever a child changes anyway, let it store, next to each pointer, a checksum of the child. This is Part 29's Merkle tree. The root's checksum now vouches for every block in the file system. Suppose a bit rots in a data block, or the disk returns the wrong block. A traditional file system would hand the bad bytes to the program. Here, the parent's checksum does not match, and the error is caught. With a mirror, the file system reads the other copy, checks it, and rewrites the bad one. ZFS does this for every block, and scrubs the whole pool in the background to find rot before anyone reads it.
And a third gift. Keep an old root instead of freeing it, and you have a snapshot: the whole file system as it was, for the cost of one pointer. After thirteen writes to our tree, the current version and Monday's snapshot together need 113 blocks, where two copies would need 170: fifty-seven are still shared. There is a price. Every small write rewrites the path above it, and since nothing is updated in place, a file that is rewritten piecemeal ends up scattered. So ZFS gathers seconds of writes into one transaction group, and writes the shared upper levels once for all of them.
11RAIDDegree3 min
In 1988 Patterson, Gibson and Katz argued that an array of small, cheap disks could beat one big expensive one, if it were organised well. Striping, RAID 0, spreads consecutive blocks across the disks, so they all work at once; but one disk failing loses everything. Mirroring, RAID 1, keeps every block on two disks: half the capacity, and either copy will do. RAID 5 adds one parity block to each stripe, rotating which disk holds it so no disk becomes a bottleneck. It survives the loss of any one disk, at the cost of one disk's capacity. Here is the trade in one table, for N disks. Random writes are the weak spot of parity, for a reason we will see next.
The parity block is the exclusive or of the data blocks in its stripe, bit by bit, Part 28's simplest error-correcting code. If any one disk dies, we know which one, so each of its blocks is just the exclusive or of the survivors, parity included. But updating one block is expensive. The new parity depends on the old: read the old data and the old parity, then write the new data and the new parity. Four disk operations for one block. That is the small-write problem, and why databases often prefer mirrors. RAID 6 adds a second check block, Q, a weighted sum over the field with 256 elements, the field of Part 28's Reed-Solomon codes. Two equations, two unknowns: any two failed disks can be rebuilt. Our implementation rebuilds every one of the fifteen pairs of lost disks from six, exactly.
Now the arithmetic of a real failure. Eight disks of sixteen terabytes in RAID 5; one dies. Rebuilding its contents means reading all seven survivors from end to end, at perhaps a hundred megabytes a second: about 44 hours. What can go wrong in that time? Another disk can fail. At the failure rate on the datasheet, the chance is three in ten thousand; at the three percent a year seen in the field, about one in a thousand. But the rebuild reads nine times ten to the fourteen bits, and drives are specified to fail to read about one sector per ten to the fifteen bits, or, for cheaper drives, per ten to the fourteen. At those rates the chance of hitting an unreadable sector is 59 percent, or near certainty. Those are worst-case bounds, and real drives usually do better, but the lesson stands: the danger is not the second disk, it is the bad sector. The classic formula for the mean time to data loss, which assumes failures are independent, gives RAID 5 tens of thousands of years. Hence RAID 6, checksums, and scrubbing, which reads everything regularly so that bad sectors are found and repaired while the redundancy is still there.
12Disks in the fieldIndustry3 min
Every reliability calculation so far took the numbers on the datasheet. A million hours between failures sounds like a hundred years. It means that a large population should lose under one percent of its disks a year. In 2007 Schroeder and Gibson looked at the replacement logs of about a hundred thousand disks in real data centres. Typical yearly replacement rates were two to four percent, and on some systems thirteen. The failures did not follow the textbook bathtub, flat for years before wearing out: rates rose steadily from the second year. And they clustered. A disk being replaced made another replacement soon more likely, which is exactly what RAID's arithmetic assumes never happens. Even with independent failures, the mean time to data loss falls more than tenfold when the real rate is used.
Whole-disk failures at least announce themselves. Worse are the errors that do not. A latent sector error is a sector that has quietly become unreadable. A study of one and a half million disks found them in three and a half percent within 32 months, and they are discovered only when someone reads, which may be during a rebuild. Silent corruption is a disk returning the wrong bytes without any error at all: the same group counted over four hundred thousand checksum mismatches in that population. Some writes are acknowledged and then lost, or written to the wrong place, and the disk's own error-correcting code cannot notice, because it is correct for the block it is attached to. And every layer in between, from firmware to cables to memory, can do damage.
What can be trusted, then? Saltzer, Reed and Clark's end-to-end argument says that a check made in the middle of a path cannot vouch for the whole of it; only a check at the ends can. A disk's own error correction protects the platter, but not the cable, the controller, or a write that went to the wrong place. So the file system itself should checksum what it writes and verify what it reads, as ZFS and btrfs do, and as databases do for their pages. Scrubbing reads everything regularly, so latent errors are found and repaired while the redundancy to repair them still exists. And because whole machines and whole buildings fail too, the final defence is copies elsewhere, which Parts 39 and 45 take up.
13fsync, and what applications must doIndustry3 min
When a program writes, where do the bytes go? With buffered input and output, first into the program's own buffer, which not even the kernel can see. Then into the kernel's page cache. The write call returns here, and the kernel writes the page back to the disk at its convenience, within about thirty seconds. Even then, the drive may hold it in its own volatile cache. Only then is it durable. Fsync is the call that pushes a file through every stage: its pages, its metadata, and a flush command to the drive. A new file's name lives in its directory, so the directory needs an fsync too. And all of it, journals included, rests on drives honouring flushes, which some cheap ones have not.
Now the application's side. A program wants to replace a small file, a configuration or a saved game, and our checker crashes each way of doing it at every point, on ordered PebbleFS. Overwriting it in place tears it: a crash between the block writes leaves half old and half new. Journaling metadata does not protect data written in place. Writing a new file and renaming it over the old one is the classic idiom, because rename is atomic. With blocks allocated at once, it survives. But with delayed allocation, the rename can reach the disk before the new file's data even has blocks. A crash then leaves an empty file. This is exactly what happened when ext4 arrived in 2009, and users lost their settings. The safe way: write the new file, fsync it, then rename, then fsync the directory. Every crash point leaves either the old file or the new one.
Real programs get this wrong all the time. In 2014 Pillai and colleagues built a tool that records a program's system calls and explores the crash states a file system allows. Across eleven widely used applications, databases and version control among them, it found sixty places where a crash could lose or corrupt data. Part of the trouble is that each file system persists operations in its own order, and the standard promises very little, so code that is safe on one can fail on another. And in 2018 the PostgreSQL developers discovered that when Linux failed to write a page back, it reported the error once, then marked the page clean. PostgreSQL retried the fsync, the retry succeeded, and the write was silently lost. The lesson: a failed fsync means the data is gone. Do not retry. PostgreSQL now stops, and recovers from its own write-ahead log, which is where Part 35 picks up.
14LSM treesGraduate3 min
A B-tree updates its pages in place: each insert reads a page and writes it back, a random write. In 1996 O'Neil and colleagues proposed the log-structured merge tree, which never does that. A put is appended to a log, for crash recovery, and inserted into a sorted table in memory, the memtable. No seek at all. When the memtable fills, it is written out in one sequential sweep as a sorted, immutable run, an SSTable. A lookup checks the memtable, then each run from newest to oldest. Each run carries a Bloom filter, Part 20's, so runs that cannot hold the key are skipped without reading them. Runs accumulate, so they are merged in the background. Google's Bigtable, LevelDB, RocksDB and Cassandra are all built this way.
There are two classic ways to merge. Here is a tiny tree, four entries per memtable, growing one flush at a time. On the left, leveled compaction, LevelDB's and RocksDB's default. Each level holds a single run, three times larger than the level above. When a run arrives at a level it is merged straight into that level's run, which is rewritten. On the right, tiered compaction, Cassandra's default. A level collects up to three runs, and only when it has three are they merged together into one run on the next level. Watch the difference. Leveled keeps few runs, so a lookup checks few places, but rewrites the same data again and again. Tiered writes each entry once per level, but leaves many runs to search.
Now at scale: two hundred thousand puts over a hundred thousand keys, a memtable of a thousand, size ratio ten. Three costs. Write amplification: bytes written to disk per byte put. Read amplification: runs read per lookup. Space amplification: entries stored per live key. Leveled writes each entry about twelve times; tiered about twice. But tiered leaves nineteen runs, and without filters a lookup for a missing key reads all of them. Ten bits of Bloom filter per key bring that down to almost nothing for both. And a B-tree, for comparison, writes a whole four-kilobyte page to change a hundred-byte record: forty times amplification, falling only when much of the tree fits in memory. No design wins on all three costs. Athanassoulis and colleagues called this the RUM conjecture, and tuning an LSM tree is choosing a point in that triangle.
15PebbleOS gets a diskDegree3 min
Now our own machine. PebbleOS gets a disk. The device is three registers on the I/O page that only the kernel can reach: a block number, a memory address, and a command. Store a one in the command, and the block is copied straight into memory: direct memory access. The kernel gains a file system that reads PebbleFS, two hundred and sixty instructions of Pebble assembly: read the superblock at boot, a buffer cache of four blocks, find an inode, and bmap, which follows the direct, indirect and double-indirect pointers. There is a new system call, open, that walks a path from the root, and read now works on an open file, or on standard input when a shell has redirected it from a file. Run cat on slash novels slash emma, and two hundred thousand bytes come out exactly, from 201 block reads, in the order the Python file system says they should come.
Now the Job's own data. The thirty novels are written to a PebbleFS disk, one file each, twenty-five million bytes, and fsck finds nothing wrong. Reading all of them takes 24,640 block reads. Laid out as our allocator lays them, the model disk moves its arm only 76 times, for the lookups and indirect blocks, and the whole corpus streams off in half a second. On an aged disk, with every block somewhere else, it would take a hundred seconds. On flash, seventeen milliseconds, or two seconds if scattered.
So the ledger gets row twelve. The tokenizer now reads the novels from the file system instead of the tape, and pipes words to the job, as in Part 31. We fit the instruction counts on thirty-two passages read through PebbleOS, check the fit on held-out ones, and project the corpus: 2.65 billion instructions, priced exactly as row eleven. Reading through a real file system costs the kernel no more than the tape did, about twenty-two instructions a byte, because the work is the same byte-by-byte copy. What is new is the disk: half a second for the model disk to deliver twenty-five megabytes. Two point six six seconds in all. On flash the disk time all but vanishes; on an aged disk it would be a hundred seconds, nearly fifty times the computation. Where the blocks are matters more than the code that reads them.
16Frontier: storage that can be trustedResearch3 min
Chapter 14 found that no LSM design wins on every cost. Research now treats the whole space as one continuum to be navigated. A small example. The usual tree gives every run the same number of Bloom filter bits per key, so every level has the same false-positive rate, and a lookup for an absent key wastes that much at each level. Dayan, Athanassoulis and Idreos observed in 2017 that the levels differ enormously in size. Bits spent on a small level are cheap, so give the small levels more and the big one fewer, until each level's false-positive rate is proportional to its size. With the same total memory, the wasted reads fall three and a half times. Their next design, Dostoevsky, mixed leveling and tiering within one tree; how to choose and change such a design as a workload drifts is still open.
Our checker tried every crash, and that does not scale. With k writes between flushes the disk can be left in two to the k states: nine for three writes, over a thousand for ten. Exhaustive checking works for small operations, not for whole programs. So researchers prove instead. FSCQ, in 2015, was a file system proved correct in the Coq proof assistant, with a logic for crashes: whatever point it crashes at, recovery leads to a state its specification allows. Yggdrasil made such proofs push-button, by handing them to an SMT solver. CrashMonkey went the other way, testing Linux file systems systematically over short sequences of operations, and found new bugs in widely used ones. What is missing is a verified file system as fast as ext4, with concurrency and delayed allocation, and a precise model of what real drives actually promise.
Chapter 3's translation layer hides flash behind the old interface of rewritable blocks, and pays for it in write amplification and spare capacity. Zoned storage stops pretending. Shingled disks, whose tracks overlap like roof tiles, and the zoned SSDs standardized for NVMe in 2020, divide themselves into zones. Each zone is written strictly in order, at a write pointer, and reset as a whole. The device no longer cleans; the host does, and it can write sequentially by design. In our simulator, rewriting pages in order gives an amplification of exactly one, against seven and a half for random writes on the same spare space. Log-structured software fits zones naturally: LFS, LSM trees, flash file systems. Bringing everything else along is open.
Recap, problems, and where this comes backAll tracks3 min
What we built in this part. A model of the disk, where reading in order is nearly five hundred times faster than reading at random, and a simulated flash drive with its translation layer and garbage collector. A Unix file system, crashed at every write and checked each time. The defences: careful ordering, journaling with its commit block, logs and their cleaners, copy-on-write trees with checksums, RAID and the failure rates disks really have. What fsync means, LSM trees, and PebbleOS reading the novels from a disk of its own.
Where this comes back. Part 35's database keeps a write-ahead log, recovers with ARIES, and indexes with B-plus trees and this part's LSM trees. Part 39 puts copies on other machines, because one machine's disks are never enough. Part 45 prices durability in the cloud. Part 46 builds streaming systems on the partitioned log, the sequential write at datacenter scale. And Part 50 does availability arithmetic with the failure rates of chapter 12.
In practice. Use ext4 or XFS unless you need checksums and snapshots, which ZFS and btrfs give. To replace a file durably, write a new one, fsync it, rename it over the old, and fsync the directory; and if fsync ever fails, treat the data as lost. Leave flash some spare room, keep TRIM on, and watch its wear. Protect large disks with RAID 6 or mirrors, scrub them, and remember that RAID is not a backup: it faithfully copies your mistakes. And pick an LSM engine for write-heavy data, a B-tree for read-heavy, and tune compaction to the workload.
Six problems, with full solutions in the part's notes. Pause on any of them. The fifth is a build problem: teach PebbleOS to write files, and crash-test your code with our checker. The last, marked with a star, is a research problem: the fewest flushes that make each operation safe, which careful ordering only approximates.
Next time, Part 35: Databases. In 1970 Codd said that programs should say what data they want, never how to find it. From that came relational algebra, an optimizer that searches for the cheapest plan, and transactions that let thousands of users act as if each were alone, even through crashes, using this part's log. The Job becomes one line of SQL. Part 35, Databases.
The books and papers this part follows are on screen and in the notes. Thank you for watching.
Where it goes next. Part 35's database keeps a write-ahead log, recovers with ARIES and indexes with B+ trees and this part's LSM trees. Part 39 puts copies on other machines, Part 45 prices durability in the cloud, Part 46 builds streaming systems on the partitioned log, and Part 50 does availability arithmetic with the failure rates of Chapter 12.
Key results
The part's results in one place, for revision.
Try it
Lab 34 · Crash at every write, and what spare flash buys
Run append, create, unlink and rename on PebbleFS under four commit modes, crash at every point a disk could stop, and count the states that fsck or the file's bytes reject. Then simulate a flash translation layer and compare its write amplification with the estimate (1 + p) / 2p for spare fraction p.
python -m videos.cs.labs 34
needs numpy, scipy, matplotlib · download lab34.py ·
source on GitHubnone: 126 crash points corrupt 34 wrong bytes 22 leaks only 34 (19 writes, 5 flushes)
careful: 52 crash points corrupt 0 wrong bytes 0 leaks only 14 (19 writes, 13 flushes)
writeback: 214 crash points corrupt 0 wrong bytes 90 leaks only 0 (46 writes, 20 flushes)
ordered: 150 crash points corrupt 0 wrong bytes 0 leaks only 0 (46 writes, 22 flushes)
write amplification at 7%, 14%, 28%, 50% spare 7.46 4.07 2.34 1.61
the estimate (1 + p) / 2p 7.64 4.07 2.29 1.50 (the film: 7.5 and 2.4 measured)
sequential writes at 7% spare 1.00 (whole erase blocks die together)
With no ordering, a quarter of the crash points corrupt the file system; a journal with ordered data leaves none. On flash, every host write costs (1 + p) / 2p flash writes, so spare is speed.
The code (113 lines; it asserts its own result)
"""Lab 34: crash a small file system at every write, then measure a flash drive's write amplification."""
from videos.coursekit import labs # noqa: I001 (first, so the library imports without manim)
import numpy as np
from explainer.cs.store import flash
from explainer.cs.store.fs import crash_test
TITLE = "Crash at every write, and what spare flash buys"
GOAL = ("Run append, create, unlink and rename on PebbleFS under four commit modes, crash at every point a disk "
"could stop, and count the states that fsck or the file's bytes reject. Then simulate a flash translation "
"layer and compare its write amplification with the estimate (1 + p) / 2p for spare fraction p.")
TASKS = [
"Add the mode 'data' and compare its writes with 'ordered'. What does journaling the data buy for the cost?",
"Pass barriers=False to the ordered mode, then also jcsum=True. Which crash states does the checksum rescue?",
"Call flash.ftl with hot=(0.9, 0.1) and compare r['erase_max'] with r['erase_mean']. What does wear levelling have to fix?",
]
STALE = b"PASSWORD=hunter2 " # what a deleted file left in the free blocks
OLD, NEW = b"A" * 2000, b"B" * 3000
MODES = ("none", "careful", "writeback", "ordered")
SPARE = (0.07, 0.14, 0.28, 0.5)
def operations():
"""The part's four operations (Chapter 7): (setup, operation, check of the bytes afterwards)."""
def setup(f):
f.mkdir("/d")
f.create("/d/f")
f.append("/d/f", OLD)
def torn(c):
return "garbage" if STALE[:8] in c else "torn"
def after_append(f):
c = f.read("/d/f")
return None if c in (OLD, OLD + NEW) else torn(c)
def after_create(f):
if not f.exists("/d/g"):
return None
c = f.read("/d/g")
return None if c in (b"", NEW) else torn(c)
def after_unlink(f):
return None if not f.exists("/d/f") or f.read("/d/f") == OLD else "torn"
def after_rename(f):
a, b = f.exists("/d/f"), f.exists("/d/h")
if a == b:
return "both" if a else "lost"
return None if f.read("/d/f" if a else "/d/h") == OLD else "torn"
return [(setup, lambda f: f.append("/d/f", NEW), after_append),
(setup, lambda f: (f.create("/d/g"), f.append("/d/g", NEW)), after_create),
(setup, lambda f: f.unlink("/d/f"), after_unlink),
(setup, lambda f: f.rename("/d/f", "/d/h"), after_rename)]
def run(seed=0):
lab = labs.Lab()
# 1. crash consistency (Chapters 7 and 8)
keys = ("states", "ok", "leak_only", "corrupt", "bad_data", "writes", "flushes")
crash = {}
for mode in MODES:
tot = dict.fromkeys(keys, 0)
for setup, op, check in operations():
r = crash_test(setup, op, check, mode=mode, stale=STALE)
for k in keys:
tot[k] += r[k]
crash[mode] = tot
lab.row(f"{mode}: {tot['states']} crash points", f"corrupt {tot['corrupt']} wrong bytes {tot['bad_data']}"
f" leaks only {tot['leak_only']} ({tot['writes']} writes, {tot['flushes']} flushes)")
none, careful, wb, ordered = (crash[m] for m in MODES)
assert (none["states"], none["corrupt"], none["bad_data"]) == (126, 34, 22), "the film's count with no ordering"
assert careful["corrupt"] == 0 and careful["bad_data"] == 0 and careful["flushes"] > none["flushes"]
assert wb["corrupt"] == 0 and wb["bad_data"] > 0, "writeback keeps the structure and loses the bytes"
assert ordered["ok"] == ordered["states"] == 150, "ordered journaling: every crash state intact"
# 2. flash: write amplification against over-provisioning (Chapter 3)
wa = [flash.ftl(blocks=256, pages=64, op=p, writes=3, seed=seed)["wa"] for p in SPARE]
est = [flash.wa_greedy_estimate(p) for p in SPARE]
lab.row("write amplification at 7%, 14%, 28%, 50% spare", " ".join(f"{w:.2f}" for w in wa))
lab.row("the estimate (1 + p) / 2p", " ".join(f"{e:.2f}" for e in est) + " (the film: 7.5 and 2.4 measured)")
seq = flash.ftl(blocks=256, pages=64, op=0.07, writes=3, seed=seed, pattern="sequential")["wa"]
lab.row("sequential writes at 7% spare", f"{seq:.2f} (whole erase blocks die together)")
assert all(a > b for a, b in zip(wa, wa[1:])), "more spare, less copying"
assert all(abs(w / e - 1) < 0.15 for w, e in zip(wa, est)), "within 15% of the estimate"
assert abs(seq - 1) < 0.01
lab.note = ("With no ordering, a quarter of the crash points corrupt the file system; a journal with ordered "
"data leaves none. On flash, every host write costs (1 + p) / 2p flash writes, so spare is speed.")
fig, ax = labs.figure(2, size=(11, 4.2))
x = np.arange(len(MODES))
bottom = np.zeros(len(MODES))
for key, name, c in (("ok", "intact", labs.GREEN), ("corrupt", "fsck finds corruption", labs.RED),
("bad_data", "consistent, wrong bytes", labs.GOLD)):
h = np.array([crash[m][key] / crash[m]["states"] for m in MODES])
ax[0].bar(x, h, bottom=bottom, color=c, label=name, width=0.6)
bottom += h
ax[0].set_xticks(x, [f"{m}\n{crash[m]['states']} points" for m in MODES])
ax[0].set(title="Four operations crashed at every point", ylabel="fraction of crash states", ylim=(0, 1.25))
ax[0].legend(loc="upper center", ncols=3)
grid = np.linspace(0.05, 0.6, 100)
ax[1].plot(grid, (1 + grid) / (2 * grid), color=labs.GOLD, label="estimate (1 + p) / 2p")
ax[1].plot(SPARE, wa, "o", color=labs.BLUE, label="simulated FTL, greedy collector")
ax[1].plot([0.07], [seq], "s", color=labs.GREEN, label="sequential writes")
ax[1].set(title="Flash writes per host write", xlabel="over-provisioning p (spare / user capacity)",
ylabel="write amplification", ylim=(0, 11))
ax[1].legend()
lab.fig = fig
return lab
Now change it
- Add the mode 'data' and compare its writes with 'ordered'. What does journaling the data buy for the cost?
- Pass barriers=False to the ordered mode, then also jcsum=True. Which crash states does the checksum rescue?
- Call flash.ftl with hot=(0.9, 0.1) and compare r['erase_max'] with r['erase_mean']. What does wear levelling have to fix?
Problems, with solutions
Try each problem before opening its solution.
-
The average seek. Derive the average seek of the square-root model: show E√|U − V| = 8/15 for independent uniform U, V on [0, 1].
Solution
D = |U − V| has density 2(1 − d) on [0, 1] (the two triangles of the unit square beyond distance d have total area (1 − d)², so P(D > d) = (1 − d)²). Then E√D = ∫₀¹ 2(1 − d) d^{1/2} dd = 2(2/3 − 2/5) = 8/15. So the average seek is t_min + (t_max − t_min)·8/15 = 0.5 + 15.5 × 8/15 = 8.77 ms.
-
Write amplification and write cost. Show that a flash collector whose victims hold on average a fraction u of live pages has write amplification 1/(1 − u), and that LFS's cleaner, which also reads each segment, has write cost 2/(1 − u).
Solution
Collecting a victim of B pages copies uB live pages and frees B pages, of which (1 − u)B are new free space after the copies. The host then fills those (1 − u)B pages. In steady state, per (1 − u)B host writes the flash writes (1 − u)B + uB = B pages: amplification B / ((1 − u)B) = 1/(1 − u). LFS's cleaner must also read the whole segment (B) to find its live blocks, so the traffic per (1 − u)B of new data is B + uB + (1 − u)B = 2B: a write cost of 2/(1 − u). (For flash the FTL knows which pages are live from its map, so it reads only the uB live pages, and those reads are cheap compared with programs and erases.)
-
Ordered journaling is atomic. Show that ordered journaling with a commit block leaves, after any crash and replay, either the old file system or the new one, for an operation whose data goes only to newly allocated blocks.
Solution
The writes come in four flushed epochs: (1) the new data, into blocks free in the old file system; (2) the descriptor and copies; (3) the commit; (4) the checkpoint, then clearing the journal.
- Crash before the commit is durable. No home metadata block has been written (they are written only in epoch 4), and the data went only to blocks the old metadata calls free, so the old file system is intact. Recovery finds a descriptor without a matching commit (a stale commit from an earlier transaction has a different sequence number) and discards it.
- Crash after the commit is durable. The copies were flushed before the commit, so the journal holds the complete new metadata. Recovery writes every copy to its home. Some homes may already hold the new contents (a partial checkpoint); writing them again changes nothing, so replay is idempotent, and a crash during replay is handled by replaying again. The data was flushed in epoch 1, so the new file system is complete.
- The argument uses the flush between the copies and the commit; without it the commit can be durable while a copy is not, and replay installs a stale block, which is what the checker found (25 of 208 corrupt) and what a checksum of the copies in the commit block repairs. Data overwritten in place is not covered: chapter 13's torn files.
-
RAID 6. Derive the formula that recovers two lost data blocks from P and Q.
Solution
Let x < y be the lost disks, and let P′ and Q′ be P and Q with the surviving data added back in: P′ = Dx ⊕ Dy and Q′ = g^x·Dx ⊕ g^y·Dy, in GF(256) with g = 2. Multiply the first by g^y and add the second: g^y·P′ ⊕ Q′ = (g^x ⊕ g^y)·Dx. Since g generates the field's multiplicative group (order 255) and 0 < y − x < 255, g^x ≠ g^y, so the coefficient is nonzero and Dx = (g^y P′ ⊕ Q′)/(g^x ⊕ g^y) = (g^{y−x} P′ ⊕ g^{−x} Q′)/(g^{y−x} ⊕ 1), byte by byte. Then Dy = P′ ⊕ Dx. If one data disk and P are lost, recover the data from Q alone (Dx = Q′·g^{−x}); if P and Q are lost, recompute them.
-
Build: writing files in PebbleOS. Give PebbleOS a
writesystem call for files, allocating blocks with a bitmap, and crash-test it with the checker.Outline. Add command 2 (write) to the device, and have
DiskMachineappend each written block to aDisk.traceand treat a store of 3 as a flush. In the kernel,write(3, buf, n)reads the inode; for each block past the end of the file it reads the data bitmap, finds a clear bit, sets it, and records the block in the inode (throughbmap, extended to allocate an indirect block when needed); it copies the bytes into the data buffer and writes it. Order the writes ascarefulmode does: data and bitmap, flush, inode, flush. Then run the program, take the trace, and give it tocrash_stateswith the disk before the program ran; every state should passfsckwith at worst leaks. Count the kernel's instructions per byte written, againstread's 22. -
★ Research: minimum flushes. For each PebbleFS operation, find the fewest flushes (and a write order) so that every crash state is at worst a leak. Is there a polynomial algorithm from the dependency graph?
What is known, and a start. For one operation, write the safety rules as a dependency graph on the blocks it writes: a block must be durable before any block that points to it (data before indirect block before inode before directory entry when allocating; a pointer cleared before the block or inode is freed). A schedule with f flushes is a division of the writes into f epochs, and a crash leaves only leaks exactly when every dependency goes from an earlier epoch to a later one. So the minimum is the number of blocks on the longest dependency path, achieved by giving each write its depth in the graph: polynomial (a topological sort). Careful mode is not minimal: it puts the bitmap in an epoch of its own, though nothing the bitmap points to depends on it. Merging the data and the bitmap epochs when allocating, the checker confirms every crash point is still at worst a leak, with 11 flushes for the four operations instead of 13. The open part is many operations at once: one block holds many inodes and many bitmap bits, so two operations can require opposite orders of the same two blocks, a cycle. Soft updates break such cycles by rolling back an update in the buffer before writing the block. Minimizing flushes for a batch with shared blocks resembles feedback arc set, which is NP-hard in general; whether it is NP-hard for the structures a file system creates is open.
Notes and sources
Glossary
- block device: storage seen as a numbered array of fixed-size blocks, read and written whole.
- seek, rotational delay, transfer: the three parts of a disk access.
- FTL (flash translation layer): the drive's map from logical to physical pages, with garbage collection.
- write amplification: bytes the device (or engine) writes per byte the host asks it to write.
- over-provisioning: flash kept hidden from the host as spare space for the collector.
- TRIM: the command by which a file system tells a drive which blocks are free.
- inode: the record of a file's metadata and the location of its blocks; extent: a (first block, length) run.
- fsck: the offline check of a file system's invariants.
- journal (write-ahead log): changes recorded, and committed with one block write, before they are made.
- ordered mode: data written to its home before the metadata that points to it commits.
- copy-on-write: never overwrite; write new copies up to a new root; snapshot: an old root kept alive.
- scrub: reading everything to find and repair latent errors while redundancy exists.
- RAID: redundancy across disks: striping, mirroring, parity (RAID 5), double parity (RAID 6).
- MTTDL: mean time to data loss.
- LSM tree: a write-optimized index of sorted runs merged by compaction, leveled or tiered.
- zoned storage: devices whose zones must be written sequentially and reset whole.
Sources
- R. H. Arpaci-Dusseau and A. C. Arpaci-Dusseau, Operating Systems: Three Easy Pieces, persistence chapters.
- A. Petrov, Database Internals, part I; D. Giampaolo, Practical File System Design.
- M. K. McKusick, W. N. Joy, S. J. Leffler and R. S. Fabry, "A Fast File System for UNIX", ACM TOCS (1984).
- G. R. Ganger and Y. N. Patt, "Metadata Update Performance in File Systems", OSDI (1994): soft updates.
- R. Hagmann, "Reimplementing the Cedar File System Using Logging and Group Commit", SOSP (1987).
- M. Rosenblum and J. K. Ousterhout, "The Design and Implementation of a Log-Structured File System", ACM TOCS (1992).
- D. Hitz, J. Lau and M. Malcolm, "File System Design for an NFS File Server Appliance", USENIX (1994): WAFL.
- D. A. Patterson, G. Gibson and R. H. Katz, "A Case for Redundant Arrays of Inexpensive Disks (RAID)", SIGMOD (1988).
- H. P. Anvin, "The mathematics of RAID-6".
- B. Schroeder and G. A. Gibson, "Disk Failures in the Real World", FAST (2007).
- L. N. Bairavasundaram et al., "An Analysis of Latent Sector Errors in Disk Drives", SIGMETRICS (2007); "An Analysis of Data Corruption in the Storage Stack", FAST (2008).
- J. H. Saltzer, D. P. Reed and D. D. Clark, "End-to-End Arguments in System Design", ACM TOCS (1984).
- C. Ruemmler and J. Wilkes, "An Introduction to Disk Drive Modeling", IEEE Computer (1994).
- N. Agrawal et al., "Design Tradeoffs for SSD Performance", USENIX ATC (2008).
- T. S. Pillai et al., "All File Systems Are Not Created Equal", OSDI (2014).
- P. O'Neil, E. Cheng, D. Gawlick and E. O'Neil, "The Log-Structured Merge-Tree", Acta Informatica (1996).
- F. Chang et al., "Bigtable", OSDI (2006).
- M. Athanassoulis et al., "Designing Access Methods: The RUM Conjecture", EDBT (2016).
- N. Dayan, M. Athanassoulis and S. Idreos, "Monkey: Optimal Navigable Key-Value Store", SIGMOD (2017); "Dostoevsky", SIGMOD (2018).
- H. Chen et al., "Using Crash Hoare Logic for Certifying the FSCQ File System", SOSP (2015).
- H. Sigurbjarnarson et al., "Push-Button Verification of File Systems via Crash Refinement", OSDI (2016).
- J. Mohan et al., "Finding Crash-Consistency Bugs with Bounded Black-Box Crash Testing", OSDI (2018).
- M. Bjørling et al., "ZNS: Avoiding the Block Interface Tax for Flash-based SSDs", USENIX ATC (2021).
About this partfrom its README
Part 34 of a sixty-one-part course in computer science (see the series plan and the syllabus), and the last part of Act VI, One Machine, Many Programs. Memory forgets when the power goes, so data must live on spinning platters or in flash that wears out, both thousands of times slower than memory and both written a block at a time. An append that needs three block writes can be cut short by a crash between any two of them. Careful ordering, journals, logs and copy-on-write trees are the answers; RAID's parity is Part 28's codes at work, and real disks fail more often, and more quietly, than their datasheets say. PebbleOS gets a disk and reads the novels from its own file system.
The instruments are in explainer/cs/store/ (tested in tests/test_cs34_storage.py):
fs.py, PebbleFS, a small Unix file system on 1 KiB blocks:- superblock, inode and data bitmaps, a table of 64-byte inodes (ten direct pointers, one single- and one double-indirect), a journal, and data; directories of 32-byte entries; the largest file is (10 + 256 + 65,536) KiB;
- create, mkdir, write and append, read, link, unlink, and an atomic rename; allocation in a row (
next, with a per-file goal) or at random (an aged disk); delayed allocation withfsync; - five commit modes:
none;careful(data, bitmaps, indirect blocks, inodes, directories, with a flush between groups, the reverse when freeing);writeback,orderedanddatajournaling, with a descriptor block, copies and a commit block, optional barriers and a checksum of the copies in the commit block; recovery replays a committed transaction and discards an uncommitted one; fsck: six invariants (used blocks marked, marked blocks owned, no block owned twice, entries name live inodes, link counts, sizes covered), with repair;- crash injection: every write and flush is recorded;
crash_statesyields every disk a crash could leave (everything before the last flush, and any subset of the writes after it, since disks reorder), andcrash_testmounts, checks and reads each one.
disk.py: the hard disk model (seek time t_min + (t_max − t_min)√(d/C), half a turn, transfer; a short forward gap on the same turn costs only its passing), the time of a block trace, FCFS, SSTF, SCAN and C-SCAN on a static queue and under Poisson load; a rough flash drive for comparison.flash.py: a page-mapped flash translation layer with greedy or FIFO garbage collection, over-provisioning, skewed traffic, TRIM and sequential (zoned) writes; write amplification and erase counts.lfs.py: Rosenblum and Ousterhout's cleaner simulation (greedy and cost-benefit, uniform and hot-and-cold).raid.py: RAID 0/1/4/5/6 layouts, XOR parity, RAID 6's P and Q over GF(256) (Part 28's field, the polynomial Linux uses) with two-disk recovery, small-write costs, rebuild risk, MTTDL by formula, exact Markov chain and simulation. The exact chain uses a positive recurrence that stays accurate when failures are rare. Failures and repairs are independent exponential clocks with one repair at a time; the formulas are fast-repair approximations. Rebuild URE probabilities assume independent Poisson errors at the stated per-bit rate. Datasheet bounds are not observed rates, and an unreadable stripe does not imply loss of every byte in the array.lsm.py: an LSM tree with leveled or tiered compaction and per-run Bloom filters (Part 20's), and a B-tree's write amplification under an LRU buffer pool.cow.py: a copy-on-write tree whose pointers carry SHA-256 checksums, with snapshots, bit rot and repair from a mirror.
PebbleOS's disk (explainer/cs/os/fsos.py): three registers on the I/O page (block, address, command) copy a
block into memory by DMA. The kernel gains about 260 instructions (kernel.py grew empty hooks for them, so Parts
31–33 are unchanged): the superblock read at boot, bread with a four-block buffer cache, iget, bmap, an open
system call that walks a path, and read from an open file or from standard input redirected from a file.
predict_reads models the kernel's reads in Python; the tests check it against the device's log.
Chapter notes
- Hook. One block appended to a one-block file, with no ordering: the bitmap, data and inode writes, and all
eight subsets a crash can leave. Two are corrupt (a used block marked free); two lose a block; and one is perfectly
consistent to fsck yet ends the file with a deleted file's
PASSWORD=hunter2. Across four operations, 34 of 126 crash points corrupt the file system and 22 show the wrong bytes; ordered journaling: all 150 intact. - 1. Persistence. The bottom of Part 9's hierarchy: memory 100 ns, flash about 80 µs, the disk 13 ms (129,606×: if memory took a second, the disk would take 1.5 days). DRAM leaks; storage keeps bits without power, in blocks. IBM's 350 disk (1956). One block write is atomic; two are not.
- 2. Disks. Seek, rotation, transfer, from the model: 8.8 ms average seek, 4.17 ms half turn, 27 µs for 4 KiB at 150 MB/s; a random 4 KiB read 13.0 ms. Random 4 KiB reads deliver 0.32 MB/s against 150 MB/s in order: 475×. The textbook queue from cylinder 53: FCFS 640 cylinders, SSTF 236, SCAN 299, C-SCAN 322. Under 72 requests a second: FCFS's mean 96 ms; SSTF 30 ms but a worst case of 240 ms; SCAN 31 ms and 177 ms. NCQ; Linux's schedulers.
- 3. Flash. Pages, erase blocks, wear. The FTL as a log with a garbage collector (animated). Write amplification simulated on 256 blocks of 64 pages: 7.5 at 7% spare, 2.4 at 28%, close to the estimate (1 + p)/2p; FIFO a little worse. 90% of writes to 10% of the data: the busiest block erased 42 times against a mean of 15. TRIM: from 7.5 to 2.1 with 20% trimmed. NVMe's queues.
- 4. Files and directories. Inodes, directories as tables of names, paths (Multics 1965, Unix 1974). The Unix calls, and the descriptor → open file → inode chain. Links, unlink, an atomic rename; symbolic links.
- 5. A simple file system. PebbleFS on 8,192 blocks: 1 superblock, 1 + 1 bitmap blocks, 16 inode-table blocks,
64 journal blocks, 8,109 data blocks. The inode and its pointer tree; the largest file, 67,381,248 bytes. PebbleOS's
kernel opening
/novels/emma: block 0, the inode table, two directory blocks, then the data: 201 reads for 200,000 bytes. - 6. Locality. The old Unix file system's 2% of the bandwidth; FFS (1984) and cylinder groups. A 4 MiB file: written alone, 41 ms on the model disk (the platter's limit is 28 ms); interleaved with another file, 70 ms; on an aged disk, 16.8 s, 406× slower; on flash 1.6 ms against 329 ms. Extents, delayed allocation, preallocation.
- 7. Crash consistency. fsck's six invariants, and what it cannot see. The checker. No ordering: 19 writes in four operations, 126 crash points, 34 corrupt, 22 wrong bytes. Careful ordering: 0 and 0, with 14 leaks, at the price of 13 flushes instead of 5; soft updates (1994). fsck reads grow with the disk (25, 92, 359 distinct blocks for 2,048, 8,192, 32,768); replaying a journal reads 4 blocks for an append.
- 8. Journaling. One ordered-mode append, write by write: data, flush; descriptor and copies, flush; commit,
flush; checkpoint, flush; clear. Crash after any write: discarded before the commit, replayed after it, always the
old file or the new. Writeback (90 of 214 crash points with the wrong bytes), ordered and data (all intact; 53
writes against 46). No flush before the commit: 25 of 208 corrupt, by recovery itself; a checksum of the copies
(ext4's
journal_checksum): none. - 9. The log-structured file system. Rosenblum and Ousterhout (1992): every write sequential; the inode map and checkpoint; the cleaner's write cost 2/(1 − u). Simulated at 75% utilization: greedy 4.7 (uniform), 4.5 (hot and cold), cost-benefit 3.6; the utilizations of cleaned segments, unimodal for greedy, bimodal for cost-benefit.
- 10. Copy-on-write and checksums. WAFL (1994), ZFS (2005): copy the path to a new root, switch the uberblock. Four blocks per change in a tree of depth 3. Checksums in pointers: a flipped bit caught and repaired from a mirror. Snapshots: after 13 writes, 113 blocks instead of 170. Transaction groups.
- 11. RAID. Patterson, Gibson and Katz (1988). RAID 0, 1 and 5 layouts; capacity and random-I/O table. Parity, and the small-write problem (2 reads and 2 writes). RAID 6's P and Q over GF(256): all 15 pairs of lost disks out of six rebuilt. Eight 16 TB disks, a 44-hour rebuild: another failure 0.03% (datasheet) or 0.11% (3% a year); an unreadable sector 59% at 10⁻¹⁵ per bit, 99.99% at 10⁻¹⁴. MTTDL, RAID 5: 45,835 years by the formula; formula 1,607, exact 1,687, simulated 1,738 at MTTF/MTTR = 300.
- 12. Disks in the field. Schroeder and Gibson (2007): 2–4% replaced a year, up to 13%, against 0.88% on the datasheet; no flat bathtub; failures cluster. MTTDL at 3%: 3,913 years. Latent sector errors (3.45% of 1.53 million disks in 32 months), silent corruption (over 400,000 checksum mismatches), lost and misdirected writes. The end-to-end argument; checksums; scrubbing; replication.
- 13. fsync, and what applications must do. The four places a write waits; fsync, flushes, the directory. Replacing a file, crashed at every point: in place, 6 of 18 torn; write and rename, intact, but with delayed allocation 36 of 97 leave an empty file (ext4, 2009); write, fsync, rename: all intact. Pillai et al. (2014): 60 vulnerabilities in 11 applications. fsyncgate (PostgreSQL, 2018).
- 14. LSM trees. O'Neil et al. (1996); memtable, log, SSTables, Bloom filters. Leveled against tiered compaction on a tiny tree, flush by flush. At 200,000 puts over 100,000 keys: leveled writes 11.9× and keeps 2 runs; tiered 2.2× with 19 runs; reads for absent keys 2 and 19 without filters, 0.016 and 0.16 with 10 bits a key; space 1.01 and 1.83. A B-tree: 41× write amplification, 18× with half its leaves cached. The RUM conjecture.
- 15. PebbleOS gets a disk. The device and the kernel's file-system code;
cat /novels/emmabyte for byte. The thirty novels on PebbleFS: 24,971,526 bytes, 24,640 block reads, 76 jumps; 0.51 s on the model disk, 102 s on an aged disk, 17 ms on flash. A key-value store: Pride and Prejudice's word counts in an LSM tree whose runs are files. Ledger row 12: tok reading from PebbleFS piped to the job, fitted on 32 passages (held-out error 0.2% for tok, 1.5% for the kernel), 2.65 billion instructions, 2.15 s of computation plus 0.51 s of disk: 2.66 s. The kernel spends 22.1 instructions a byte, against 23.0 from the tape. - 16. Frontier: storage that can be trusted. The LSM design space: Monkey's Bloom allocation (0.041 against 0.012 wasted reads per absent lookup at 10 bits a key, 3.5×), Dostoevsky. Verified crash consistency: 2^k crash states (9 for 3 writes, 1,025 for 10); FSCQ, Yggdrasil, CrashMonkey. Zoned storage: write amplification 1.0 for sequential writes against 7.5 random. Six open problems.
- Outro. Recap, payoffs, practice, problems, next part.
Companion material in this repository
The syllabus's plan for this partfrom SYLLABUS.md, the plan of record
- Persistence and the bottom of the hierarchy (callback to Part 9).
- Disks: seek + rotation + transfer (computed); random against sequential (100×); SSTF, SCAN, C-SCAN.
- Flash:
- cells, pages, erase blocks, wear;
- the FTL as a log, with garbage collection;
- write amplification, simulated against over-provisioning;
- TRIM; NVMe queues.
- Files and directories, inodes, links; the Unix API (open, read, write, fsync).
- A simple file system: superblock, bitmaps, inodes, data blocks; indirect blocks and the maximum file size; a path lookup.
- Locality: FFS (McKusick et al. 1984) and cylinder groups; extents.
- Crash consistency: fsck; journaling (data and metadata, ordered mode), with a replay animated; soft updates; our file system crashed at every write point and checked each time.
- Log-structured FS (Rosenblum & Ousterhout 1992): segment cleaning and cost–benefit; bimodal utilization.
- Copy-on-write (ZFS, btrfs): Merkle checksums (callback to Part 29); snapshots for free.
- RAID (Patterson, Gibson & Katz 1988): levels 0/1/4/5/6 (callback to Part 28); the small-write problem; the chance of a second failure during rebuild (computed).
- Reliability in the field (Schroeder & Gibson 2007, cited); latent sector errors; end-to-end checksums.
- fsync and the illusion of durability: write caches and barriers; "fsyncgate" (2018).
- LSM trees (O'Neil et al. 1996): memtables, SSTables, leveled against tiered compaction; read, write and space amplification (the RUM conjecture); Bloom filters per run (callback to Part 20).
- Our file system and key-value store on PebbleOS's disk; the novels stored and read back. Ledger row 12. Outro.
Computed: the disk-time model; an FTL simulator; crash injection; LSM against B-tree amplification; RAID rebuild risk; LFS cleaning. Visuals: the head seeking while the platter spins; erase blocks being collected; the journal replaying after a crash; LSM levels compacting in cascades. In practice: choosing ext4, XFS or ZFS, SSD endurance in production, fsync and durability bugs, RocksDB and LSM tuning. Reading: OSTEP (persistence); McKusick et al. 1984; Rosenblum & Ousterhout 1992; Patterson, Gibson & Katz 1988; Pillai et al. 2014; O'Neil et al. 1996; Petrov, Database Internals part I; Agrawal et al. 2008; Giampaolo, Practical File System Design; Schroeder & Gibson 2007.
中文讲义
本讲的中文部分(与英文版对应)。
习题与解答
-
平均寻道时间。 推导平方根模型的平均寻道时间:证明对 [0, 1] 上独立均匀的 U、V,E√|U − V| = 8/15。
解答
D = |U − V| 在 [0, 1] 上的密度为 2(1 − d)(单位正方形中距离超过 d 的两个三角形面积共为 (1 − d)²,所以 P(D > d) = (1 − d)²)。于是 E√D = ∫₀¹ 2(1 − d) d^{1/2} dd = 2(2/3 − 2/5) = 8/15,平均寻道为 0.5 + 15.5 × 8/15 = 8.77 ms。
-
写放大与写代价。 证明:若闪存回收器所选的受害块平均有比例 u 的页仍然有效,写放大为 1/(1 − u);而 LFS 的清理器 还要读整个段,写代价为 2/(1 − u)。
解答
回收一个 B 页的块要复制 uB 个有效页,复制后净得 (1 − u)B 个空页,由主机写满。稳态下,每 (1 − u)B 次主机写, 闪存写 (1 − u)B + uB = B 页,写放大为 1/(1 − u)。LFS 清理器还要读整个段(B)才能找出有效块,所以每 (1 − u)B 的新数据, 磁盘流量为 B + uB + (1 − u)B = 2B,写代价 2/(1 − u)。(闪存转换层靠映射表就知道哪些页有效,只需读那 uB 页,而读远比编程 和擦除便宜。)
-
有序日志是原子的。 证明:对只把数据写进新分配块的操作,带提交块的有序日志在任何崩溃并重放之后,留下的要么是旧文件 系统,要么是新文件系统。
解答
写分四个以刷新隔开的阶段:(1) 新数据写进旧文件系统中空闲的块;(2) 描述块与副本;(3) 提交块;(4) 检查点,然后 清空日志。
- 提交块落盘之前崩溃。 元数据的原位块一个都没写(只在第 4 阶段写),数据只写进旧元数据认为空闲的块,所以旧文件系统 完好。恢复时看到没有匹配提交块的描述块(之前事务留下的旧提交块序号不同),丢弃它。
- 提交块落盘之后崩溃。 副本在提交之前已刷新,日志里有完整的新元数据,恢复把每个副本写回原位。有些原位块可能已是新 内容(检查点做了一半),再写一遍不改变任何东西,所以重放是幂等的,重放中途崩溃就再重放一次。数据在第 1 阶段已刷新, 新文件系统完整。
- 论证用到了副本与提交之间的那次刷新;去掉它,提交块可能先于某个副本落盘,重放就装上了过期的块,正是检查器找到的 (208 个中 25 个损坏),而在提交块里存副本的校验和可以修复。原地覆写的数据不在此列:第 13 章的撕裂文件。
-
RAID 6。 推导用 P 和 Q 恢复两个丢失数据块的公式。
解答
设丢失的盘为 x < y,把幸存数据加回 P、Q 得 P′ = Dx ⊕ Dy,Q′ = g^x·Dx ⊕ g^y·Dy(GF(256),g = 2)。第一式乘 g^y 再加第二式:g^y·P′ ⊕ Q′ = (g^x ⊕ g^y)·Dx。g 生成乘法群(阶 255),0 < y − x < 255,故 g^x ≠ g^y,系数非零, Dx = (g^{y−x} P′ ⊕ g^{−x} Q′)/(g^{y−x} ⊕ 1)(逐字节)。然后 Dy = P′ ⊕ Dx。若丢的是一个数据盘和 P,只用 Q 恢复 (Dx = Q′·g^{−x});若丢的是 P 和 Q,重新计算即可。
-
动手:让 PebbleOS 写文件。 给 PebbleOS 加一个写文件的
write系统调用,用位图分配块,并用检查器做崩溃测试。思路。 给设备加命令 2(写),让
DiskMachine把每个写出的块追加到Disk.trace,并把写 3 当作刷新。内核里,write(3, buf, n)读出 inode;对文件末尾之后的每个块,读数据位图、找一个空位、置位,并把块记入 inode(通过扩展后的bmap,需要时分配间接块);把字节拷进数据缓冲再写出。按careful模式排序:数据与位图,刷新,inode,刷新。运行程序, 取出 trace,连同运行前的磁盘交给crash_states;每个状态都应通过fsck,至多泄漏。统计每写一字节的内核指令数,与read的 22 条比较。 -
★ 研究:最少刷新。 对 PebbleFS 的每个操作,找出最少的刷新次数(及写入顺序),使每个崩溃状态至多是泄漏。能否从依赖图 在多项式时间内求出?
已知结果与起点。 对单个操作,把安全规则写成它所写各块上的依赖图:一个块必须先于指向它的块落盘(分配时:数据先于 间接块先于 inode 先于目录项;释放时:先清指针,再释放块或 inode)。有 f 次刷新的调度就是把写分成 f 个阶段;崩溃只会 泄漏,当且仅当每条依赖都从较早阶段指向较晚阶段。所以最少次数是最长依赖路径上的块数,按每个写在图中的深度分配阶段即可 达到:拓扑排序,多项式时间。careful 模式并不最优:它让位图单独占一个阶段,而没有什么东西依赖于位图所指的内容。分配时把 数据与位图合为一个阶段,检查器确认每个崩溃点仍至多泄漏,四个操作共 11 次刷新而不是 13 次。开放的是多个操作同时进行:一个 块里有许多 inode 和许多位图位,两个操作可能要求同一对块的相反顺序,形成环。软更新在写块前于缓冲中回滚某个更新来打破这种 环。带共享块的一批操作的最少刷新类似反馈弧集问题,后者一般是 NP 难的;对文件系统产生的结构是否 NP 难,尚未可知。
Build the film
python -m videos.cs.cs34.compute # the part's numbers, into .cache/cs34
python tools/build.py cs34 # render and assemble the film
EXPLAINER_TTS=silent python tools/qa_scene.py cs34 Hook # one chapter, silent, with a contact sheet
Scenes: videos/cs/cs34. Setup: see the course page. Source of these notes: the README and the scenes' narration.
Build it
python -m videos.cs.cs34.compute # every item (pebble takes about five minutes)
python -m unittest tests.test_cs34_storage
python tools/build.py cs34