Sub topic 19
Journaling and crash consistency
This chapter assumes you know the inode, data block and free-space bitmap structures from the earlier chapters. It also assumes you know that disks write in whole blocks. You should be able to explain why one file operation touches several blocks.
The crash-consistency problem
Appending one block to a file looks like a single operation. On disk it is three separate block writes:
- The data bitmap is updated to mark a new block as used.
- The inode is updated to point to the new block and to record the new size.
- The data block receives the new contents.
The disk completes these writes one at a time, and it may reorder them. If power fails partway through, any subset of the three may have reached the disk. A file system is consistent when its metadata agrees with itself. For example, every block marked used belongs to exactly one inode, and every block an inode points to is marked used.
| Writes that reached disk | Result | Severity |
|---|---|---|
| Data only | The block is unreferenced and the append is lost. | Harmless |
| Inode only | The inode points to a block that the bitmap calls free, and the block holds garbage. The block could also be given to another file later. | Metadata inconsistent, data wrong |
| Bitmap only | The block is marked used but no inode owns it. This is a space leak. | Metadata inconsistent |
| Inode and bitmap | The metadata is consistent, but the file contains garbage. | Metadata consistent, data wrong |
| Bitmap and data | The block is leaked and the data is orphaned. | Metadata inconsistent |
| Inode and data | The inode points to valid data, but the bitmap calls the block free. | Metadata inconsistent |
The case in the middle of the table is the dangerous one for GATE questions. A file system can be consistent and still return wrong data, so consistency of metadata does not guarantee correct file contents.
The fsck approach
The older fix is fsck (file system check). After a crash it scans the entire disk. It walks all inodes, rebuilds the set of used blocks, and compares that set with the bitmap. It also checks link counts and directory entries.
fsck repairs metadata only. It cannot tell whether a block's contents are correct. It is also slow, because its running time grows with the size of the disk, not with the amount of work that was in progress. Scanning a multi-terabyte volume can take hours.
Write-ahead logging
Journaling borrows write-ahead logging from databases. Before updating the file system in place, the OS writes a description of the intended update to a reserved area called the journal. Recovery then reads only the journal, so its cost depends on the journal size. The disk size does not matter.
A transaction for our append has this layout in the journal:
- TxB (transaction begin), which contains a transaction ID.
- The blocks to be updated: the bitmap, the inode, and optionally the data.
- TxE (transaction end, the commit block), which contains the same ID.
The protocol has four phases:
- Journal write. Write TxB and the update blocks to the journal.
- Journal commit. Write TxE. The transaction is now committed.
- Checkpoint. Write the updated blocks to their real locations in the file system.
- Free. Mark the transaction free in the journal so the space can be reused.
Why the order matters
TxE must be written only after all earlier journal blocks are safely on disk. If TxE could reach the disk first, a crash might leave a commit block next to journal blocks that were never written. Recovery would replay garbage into the file system. Real systems issue the journal blocks, wait for them to finish (a cache flush or write barrier), and only then issue TxE. Some implementations add a checksum over the transaction so that the commit can be validated.
Recovery
At mount time after a crash, the OS scans the journal:
- A transaction with a matching TxB and TxE is committed. Recovery replays it by writing its blocks to their final locations. This is a redo log.
- A transaction without a valid TxE is ignored. The file system looks as it did before the transaction.
Replay is idempotent: writing the same block contents a second time changes nothing. A crash during recovery, or during the checkpoint phase, is therefore safe. Recovery simply runs again.
def recover(journal, disk):
"""Replay committed transactions; ignore incomplete ones."""
replayed = []
pending = None
for rec in journal:
if rec[0] == "TxB":
pending = (rec[1], [])
elif rec[0] == "W" and pending is not None:
pending[1].append(rec)
elif rec[0] == "TxE" and pending is not None and pending[0] == rec[1]:
for _, block, value in pending[1]:
disk[block] = value
replayed.append(rec[1])
pending = None
return replayed
disk = {"bitmap": "free", "inode": "empty", "data": "old"}
journal = [
("TxB", 1),
("W", "bitmap", "used"),
("W", "inode", "ptr->D"),
("W", "data", "hello"),
("TxE", 1),
("TxB", 2), # crash: transaction 2 was never committed
("W", "inode", "ptr->E"),
]
print(recover(journal, disk)) # [1]
print(disk) # {'bitmap': 'used', 'inode': 'ptr->D', 'data': 'hello'}Transaction 1 is replayed. Transaction 2 has no TxE, so it is discarded and the inode keeps the value from transaction 1.
Journaling modes
Journaling data blocks costs a lot, because every data block is written twice, once to the journal and once in place. Most systems offer weaker modes that journal only metadata.
| Mode | What is journaled | Order of writes | Trade-off |
|---|---|---|---|
| Data journaling | Metadata and data | All go to the journal, then in place | Safest, slowest, with data written twice |
| Ordered | Metadata only | Data is written in place first, then metadata is journaled and committed | Common default. A committed inode never points to unwritten data. |
| Writeback | Metadata only | No ordering between data and journal | Fastest. Metadata is consistent, but a file may contain stale or garbage data. |
In ordered mode the data write comes before the metadata commit. A crash before the commit leaves unreferenced data blocks, which are harmless. A crash after the commit finds the data already in place.
Gotchas
- Consistency is not durability. After a crash, an uncommitted update is lost even though the file system is consistent.
- Metadata journaling does not protect file contents in writeback mode.
- Disks and controllers cache and reorder writes. Without barriers or flushes, the ordering the protocol depends on is not guaranteed.
- Journaling does not remove all checking. It protects against crash inconsistency, not against media corruption or software bugs.
- Alternatives exist. Copy-on-write file systems never overwrite live blocks, and soft updates order in-place writes carefully. Both avoid a separate journal. GATE questions focus on journaling.
Exercise
A file system journals metadata only, in ordered mode. A process appends one block to a file. The system crashes after the data block is written in place and the journal transaction (TxB, bitmap, inode) is written, but before TxE is written. After reboot, what is the state of the file, and does the system need a full-disk fsck?
Show answer
The transaction has no commit block, so recovery discards it. The bitmap and inode stay in their old state, and the append is lost. The data block that was written is unreferenced and harmless. The file system is consistent, so no full-disk fsck is needed. Recovery reads only the journal.
Exercise
Why must TxE be written only after the other journal blocks are durable? What goes wrong if the disk reorders the writes so TxE lands first and a crash occurs before the other journal blocks are written?
Show answer
Recovery treats a transaction with a matching TxB and TxE as committed and replays it. If TxE reaches the disk before the update blocks, recovery would replay journal blocks that are missing or stale and write garbage over real metadata. Waiting for the earlier writes to complete, with a flush or barrier, prevents this.
Exercise
A 2 TB disk takes about 3 hours for fsck, and the journal is 128 MB. Why is journal recovery far faster, and what does its time depend on?
Show answer
Journal recovery reads only the journal and replays the committed transactions in it. Its time depends on the journal size and the number of committed transactions, at most 128 MB of reads. fsck scans every inode and block, so its time grows with the disk size.