ENع
→Journaling
الدرس 46 · File systems

Crash consistency and journaling

لم يُترجم بعد؛ يُعرض باللغة الإنجليزية

14 دقيقة10 خطوات5 أسئلةAdvanced
عن هذا الدرس

Appending one block to a file means three separate disk writes: the data, the inode and the bitmap. If the power fails between them, the disk can end up contradicting itself. Follow one 4 KB append through a crash, the slow fsck repair, and then a journal: write the update to a log first, seal it with a commit block, copy it home, and replay it after a crash. The Linux lessons The file system and Disks, partitions and mounts show the user's view of the same disk, and the Databases lesson Write-ahead logging and recovery uses the same write-ahead idea.

ستتعلّم

حدّد ما تشعر بأنك أتقنته. هذا التقييم الذاتي لا يؤثر في درجة الدرس.

شكل 46 · تفاعلي
01 / 10

One append, three blocks

Your program adds 4 KB to a file. On disk that changes three blocks: the new data block Db, inode 2 that now points to it, and the bitmap B that marks it used. They wait in memory first.

line 1   write(fd, buf, 4096);

blocks to write          old            new
data bitmap  B           00001000       00001100
inode 2      I           size 1 block   size 2 blocks, -> block 5
data block 5 D           junk           Db (your 4096 bytes)

until then they sit in the page cache, in memory
جارٍ تحميل الرسم…
أو ← →
اقرأ الدرس خطوة بخطوة
  1. One append, three blocks

    Your program adds 4 KB to a file. On disk that changes three blocks: the new data block Db, inode 2 that now points to it, and the bitmap B that marks it used. They wait in memory first.

    line 1   write(fd, buf, 4096);
    
    blocks to write          old            new
    data bitmap  B           00001000       00001100
    inode 2      I           size 1 block   size 2 blocks, -> block 5
    data block 5 D           junk           Db (your 4096 bytes)
    
    until then they sit in the page cache, in memory
  2. A crash in the middle

    The disk writes one block at a time. Say the new inode lands, then the power fails and memory is lost. Inode 2 now points to block 5, but the bitmap says block 5 is free, and block 5 holds junk.

    on disk after the crash:
      bitmap   00001000   block 5 free      (old)
      inode 2  -> block 5       size 2      (new)
      block 5  junk                        (old)
    
    the bitmap and the inode disagree: inconsistent
    read the file and you get junk at the end
    two files could later be given block 5
  3. The slow fix: fsck

    The old fix is fsck, a checker run after the crash. It reads every inode and bitmap and trusts the inode, so it marks block 5 used. Now it is consistent, but the file ends in junk, and the scan can take hours.

    fsck reads the whole disk:
      superblock, every inode, every bitmap, every directory
    mismatch  inode 2 uses block 5, bitmap says free
    fix       trust the inode: bitmap -> 00001100
    
    consistent again, but:
      block 5 still holds junk (fsck cannot know)
      time grows with the disk: minutes or hours (OSTEP)
  4. Write a note first

    Rewind to before the crash. Journaling adds one rule: before changing anything in its real place, write the whole update into the journal, a reserved area of the disk. Databases call the same idea write-ahead logging.

    disk layout with a journal:
      journal   TxB | I | B | D | TxE      a reserved log area
      home      bitmap, inode 2, block 5   the real places
    
    the rule (write-ahead):
      install none of the update in place
      until all of it is safely in the journal
    
    ext3 and ext4 on Linux keep their journal this way (jbd2)
  5. 1. Journal write

    fsync() asks for the file to be safe on disk, and waits. The file system writes a begin block, TxB, then copies of I2, B2 and Db, into the journal. The home blocks are not touched yet.

    line 2   fsync(fd);     blocks until the disk says done
    
    journal   TxB  I2  B2  Db  .
      TxB     begin: transaction id and where each block goes
      I2 B2 Db  exact copies of the three new blocks
      (these four may be written together, in any order)
    home      untouched: B1  I1  junk
  6. 2. Journal commit

    Only when those four blocks are on disk does it write the end block, TxE. TxE fits in one 512-byte sector, which the disk writes whole or not at all. With TxE on disk, the update is committed.

    wait     TxB, I2, B2, Db are on disk
    then     write TxE (same transaction id)
    
    TxE fits one 512-byte sector: the disk writes it
    all or nothing, so the commit cannot be half done
    
    journal  TxB  I2  B2  Db  TxE    committed
    fsync() can now return 0
  7. 3. Checkpoint, 4. free

    Now the checkpoint: the file system writes I2, B2 and Db to their real places. Later it marks the transaction free, so the journal space can be used again. The journal is a loop, reused over and over.

    checkpoint   I2 -> inode 2
                 B2 -> bitmap   (00001100)
                 Db -> block 5
    free         journal superblock: transaction done
    
    the protocol (OSTEP ch. 42):
      1 journal write   2 journal commit
      3 checkpoint      4 free
  8. Crash before the commit

    Now crash at the worst moments. If power fails before TxE is written, recovery at boot finds TxB but no TxE, so it skips the transaction. The disk still has the old blocks: the append is lost, nothing is broken.

    crash after   TxB  I2  B2  Db       (no TxE)
    reboot        recovery scans the journal
                  no commit block -> discard
    home          B1  I1  junk          all old, consistent
    
    the program never got fsync() == 0,
    so it was never told the data was safe
  9. Crash after: replay

    If power fails after the commit, say mid-checkpoint, recovery finds a full transaction, TxB to TxE, and writes all its blocks home again. Writing a block twice is harmless, so even a crash during recovery is fine.

    crash after   TxE, and inode 2 checkpointed
    home then     B1  I2  junk          inconsistent!
    reboot        TxB ... TxE found: committed
                  replay I2, B2, Db to their homes
    home          B2  I2  Db            all new
    
    redo logging: replaying twice gives the same result
  10. Ordered mode: data first

    Journaling data writes it twice. So ext4 by default journals only metadata: it writes Db straight to block 5 first, then logs I2 and B2 and commits. A crash can lose new data, but never leave a pointer to junk.

    ext4 data=ordered (the default):
      1 Db -> block 5            data first, written once
      2 journal TxB  I2  B2  .  TxE
      3 checkpoint I2, B2      4 free
    
    every crash point, then recovery (Python, below):
    no journal: 4 crash points, 2 broken
    data journal: 10 crash points, 0 broken
    ordered: 9 crash points, 0 broken
    
    PLANS = {
        "no journal": ["home I", "home B", "home D"],
        "data journal": ["log TxB", "log I", "log B", "log D", "log TxE",
                         "home I", "home B", "home D", "free"],
        "ordered": ["home D", "log TxB", "log I", "log B", "log TxE",
                    "home I", "home B", "free"],
    }
    NEW = {"B": "B2", "I": "I2", "D": "Db"}
    
    def crash_after(plan, n):
        disk, log = {"B": "B1", "I": "I1", "D": "junk"}, []
        for op in plan[:n]:                 # power fails after n writes
            where, x = op.split()[0], op.split()[-1]
            if where == "home": disk[x] = NEW[x]
            elif where == "log": log.append(x)
            else: log = []                  # free the journal
        if "TxE" in log:                    # recovery: replay if committed
            for x in log[1:-1]: disk[x] = NEW[x]
        return disk
    
    def broken(d):
        return ((d["B"] == "B2") != (d["I"] == "I2")
                or (d["I"] == "I2" and d["D"] == "junk"))
    
    for name, plan in PLANS.items():
        bad = sum(broken(crash_after(plan, n)) for n in range(len(plan) + 1))
        print(f"{name}: {len(plan) + 1} crash points, {bad} broken")

اختبار يتاح بعد الخطوة الأخيرة.