Part 5 of 7 · 2 min read
Journal modes
Think of a post office that can insure only the envelope, or the envelope and the letter, or neither. Insuring more costs more. The analogy stops in one place: insurance pays after a loss, and a journal prevents the damage.
In plain words: Logging every data block would double all writes. Most Linux systems journal only the metadata (inodes, bitmaps, directories), and offer three choices for the data. In writeback mode, data may reach the disk before or after the metadata, so a crash can leave a file whose inode is new but whose blocks hold old content. In ordered mode (the default of ext4) the data blocks are written before the metadata of their transaction is committed, so a committed inode never points to blocks that have not been written. In data mode both data and metadata are logged. It is the safest and the slowest.
| Mode | What is logged | Guarantee after a crash | Cost |
|---|---|---|---|
| writeback | metadata | structure is valid, new file may show old data | lowest |
| ordered | metadata, data written first | structure is valid, no stale data in new blocks | low |
| data | metadata and data | data and metadata are both all or nothing | data written twice |
A worked example. The model of section 1 shows what ordered mode prevents. In the state -IB, the inode and the bitmap are new but the data block was not written. Writeback mode allows this state, and the file then shows garbage or old content. The journal makes the metadata writes I and B all or nothing, and ordered mode forces D to disk before they are committed. The states -I-, DI-, --B, D-B and -IB then cannot occur, and the update ends in one of the states ---, D-- or DIB. All three are consistent.
The key lines. A journal protects the file system, not the application. After a crash, the structure is valid, but a program that wrote 10 KB in two write calls may find only the first part. For the data to be safe, the program must call fsync (Level 8, page 8) and must change files in an order that a crash cannot break.
Ordered journal mode
Ordered mode is a journaling mode in which only metadata is logged, and in which the data blocks of a transaction are written to their final places before the transaction's commit record. A committed metadata update therefore never points to a block that holds old or missing data.
Example: ext4 mounted with the default data=ordered writes the data of a new file before it commits the inode that points to it.
Check yourself:
1. Which journal mode logs the data as well?
2. What does ordered mode forbid that writeback mode allows?
3. Does a journal make an application's two write calls atomic?