rust-fs-ext4 0.8.0

Pure-Rust ext4 filesystem driver. Exposes a C ABI (fs_ext4_*) suitable for FFI from C/C++/Go/etc.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
//! JBD2 journal superblock parser.
//!
//! Spec: kernel.org/doc/html/latest/filesystems/ext4/journal.html.
//!
//! JBD2 writes journal metadata in **big-endian**, unlike the ext4 filesystem
//! body which is little-endian. Every block in the journal begins with a
//! 12-byte `journal_header_t` whose magic is `0xc03b3998`. Block-type 3 or 4
//! identifies the superblock (v1 / v2). The superblock is at journal block 0.
//!
//! Locating the journal: `sb.journal_inode` (usually 8) names an inode whose
//! extent tree maps the journal file. Journal block N = logical block N of
//! that inode; convert to a physical fs block via the extent tree.
//!
//! This module parses the journal superblock. Walking transactions is
//! [`crate::journal`], replaying them [`crate::journal_apply`], and writing
//! them [`crate::journal_writer`].
//!
//! Layout summary:
//! ```text
//!   0x0000 journal_header_t (12 bytes)
//!            __be32 h_magic       = 0xc03b3998
//!            __be32 h_blocktype   = 3 (V1) or 4 (V2)
//!            __be32 h_sequence
//!   0x000C __be32 s_blocksize   (journal block size)
//!   0x0010 __be32 s_maxlen      (total blocks in journal)
//!   0x0014 __be32 s_first       (first block of log information)
//!   0x0018 __be32 s_sequence    (first commit ID expected on next replay)
//!   0x001C __be32 s_start       (block number of the log start; 0 = clean)
//!   0x0020 __be32 s_errno
//!   --- V2 fields begin (0x0024+) ---
//!   0x0024 __be32 s_feature_compat
//!   0x0028 __be32 s_feature_incompat
//!   0x002C __be32 s_feature_ro_compat
//!   0x0030 u8[16] s_uuid
//!   0x0040 __be32 s_nr_users
//!   0x0044 __be32 s_dynsuper
//!   0x0048 __be32 s_max_transaction
//!   0x004C __be32 s_max_trans_data
//!   0x0050 u8     s_checksum_type
//!   0x0051 u8[3]  padding
//!   0x0054 __be32 s_num_fc_blks
//!   0x0058 __be32 s_head
//!   0x005C u8[160] padding
//!   0x00FC __be32 s_checksum
//!   0x0100 u8[16*48] s_users
//!   0x0400 end
//! ```

use crate::error::{Error, Result};
use crate::fs::Filesystem;
use crate::inode::Inode;

/// JBD2 header magic — big-endian `0xc0 0x3b 0x39 0x98` on disk.
pub const JBD2_MAGIC_NUMBER: u32 = 0xc03b_3998;

/// Header block-type values.
pub const JBD2_DESCRIPTOR_BLOCK: u32 = 1;
pub const JBD2_COMMIT_BLOCK: u32 = 2;
pub const JBD2_SUPERBLOCK_V1: u32 = 3;
pub const JBD2_SUPERBLOCK_V2: u32 = 4;
pub const JBD2_REVOKE_BLOCK: u32 = 5;

bitflags::bitflags! {
    /// `s_feature_incompat` — kernel must refuse to replay if any unknown bit set.
    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
    pub struct JbdIncompat: u32 {
        const REVOKE        = 0x0000_0001;
        const BIT64         = 0x0000_0002;
        const ASYNC_COMMIT  = 0x0000_0004;
        const CSUM_V2       = 0x0000_0008;
        const CSUM_V3       = 0x0000_0010;
        const FAST_COMMIT   = 0x0000_0020;
    }
}

/// Parsed JBD2 superblock (read-only view).
#[derive(Debug, Clone)]
pub struct JournalSuperblock {
    /// Header block-type (`JBD2_SUPERBLOCK_V1` or `_V2`).
    pub block_type: u32,
    /// Next expected sequence number from the header (not s_sequence).
    pub header_sequence: u32,
    /// Journal block size in bytes.
    pub block_size: u32,
    /// Total blocks in the journal.
    pub max_len: u32,
    /// First block of log information (typically 1 — block 0 is the sb).
    pub first: u32,
    /// First commit ID expected when replay starts.
    pub sequence: u32,
    /// Start block of the log. **0 means clean unmount** (nothing to replay).
    pub start: u32,
    /// `s_errno`: the error an aborted journal records, 0 if healthy.
    pub errno: u32,
    /// V2-only feature flags (zero on V1 superblocks).
    pub feature_compat: u32,
    pub feature_incompat: u32,
    pub feature_ro_compat: u32,
    /// UUID identifying this journal (V2 only).
    pub uuid: [u8; 16],
    /// Number of filesystems sharing this journal (V2 only; always 1 for
    /// internal ext4 journals).
    pub nr_users: u32,
    /// Checksum algorithm id (V2 only; 1 = crc32, 4 = crc32c).
    pub checksum_type: u8,
    /// Total fast-commit blocks (V2, INCOMPAT_FAST_COMMIT only).
    pub num_fc_blocks: u32,
    /// Superblock checksum as stored on disk (V2 only).
    pub checksum: u32,
}

impl JournalSuperblock {
    /// The journal format supported by the checked recovery/write lifecycle.
    /// Feature refusal is a dependency capability boundary, not filesystem damage.
    pub fn validate_plain_recovery(&self, block_size: u32, blocks_count: u64) -> Result<()> {
        let supported = JbdIncompat::REVOKE.bits() | JbdIncompat::BIT64.bits();
        if self.feature_compat != 0
            || self.feature_ro_compat != 0
            || self.feature_incompat & !supported != 0
        {
            return Err(Error::Unsupported("checked lifecycle supports plain JBD2 only; checksummed/async/fast-commit journals need separate qualification"));
        }
        if self.block_type != JBD2_SUPERBLOCK_V2
            || self.block_size != block_size
            || self.first != 1
            || self.max_len <= self.first
            || u64::from(self.max_len) > blocks_count
            || (self.start != 0 && (self.start < self.first || self.start >= self.max_len))
            || self.nr_users != 1
        {
            return Err(Error::Corrupt("unsupported internal journal geometry"));
        }
        if self.errno != 0 {
            return Err(Error::Corrupt("journal records an outstanding error"));
        }
        Ok(())
    }

    /// True when the log has no outstanding transactions and replay is a no-op.
    pub fn is_clean(&self) -> bool {
        self.start == 0
    }

    /// Returns true if the journal uses v2 or v3 checksum tags.
    /// Whether this journal uses the v3 tag layout.
    ///
    /// Distinct from [`Self::uses_csum_v2_or_v3`], which says whether it
    /// is checksummed at all: the tag layout changes with V3 alone, and
    /// confusing the two lays tags neither this crate's reader nor the
    /// kernel can parse.
    pub fn uses_csum_v3(&self) -> bool {
        self.feature_incompat & JbdIncompat::CSUM_V3.bits() != 0
    }

    pub fn uses_csum_v2_or_v3(&self) -> bool {
        self.feature_incompat & (JbdIncompat::CSUM_V2.bits() | JbdIncompat::CSUM_V3.bits()) != 0
    }

    /// Returns true if the journal uses 64-bit block numbers (tag.t_blocknr_high).
    pub fn uses_64bit(&self) -> bool {
        self.feature_incompat & JbdIncompat::BIT64.bits() != 0
    }

    /// Returns true if revoke blocks are used.
    pub fn has_revoke(&self) -> bool {
        self.feature_incompat & JbdIncompat::REVOKE.bits() != 0
    }

    /// The `s_feature_incompat` bits this driver does not handle. Replay
    /// and writing both refuse a journal carrying any (#81): the field's
    /// own rule. `ASYNC_COMMIT` makes a transaction's completeness rest on
    /// checksums alone, and `FAST_COMMIT` keeps committed updates in an
    /// area the walker never visits.
    pub fn unsupported_incompat(&self) -> u32 {
        self.feature_incompat & !SUPPORTED_JBD_INCOMPAT
    }

    /// Why this journal's checksum declaration is one that cannot be
    /// honoured, or `None` when it names a single, usable scheme.
    ///
    /// A journal declares at most one way of checksumming its blocks: the
    /// v1 commit-block checksum (compat bit 0x1), or the per-block v2
    /// (incompat 0x8) or v3 (incompat 0x10) scheme, whose checksums are
    /// crc32c (`s_checksum_type` 4). journal.html lists the bits and the
    /// type codes; which combinations are refused was observed in the
    /// harness VM by patching the superblock of a clean journal (tests/
    /// jbd2_layouts_oracle.rs): the kernel will not load, and `e2fsck -fn`
    /// calls "Journal superblock is corrupt", exactly the three cases below.
    /// A journal without v2 or v3 is accepted whatever its type byte says.
    ///
    /// Replay and the writer each support v2 and v3 one at a time, so a
    /// journal naming both would otherwise pass the incompat check and be
    /// read with a layout its declaration does not name.
    pub fn checksum_declaration_error(&self) -> Option<&'static str> {
        let has = |bit: JbdIncompat| self.feature_incompat & bit.bits() != 0;
        let per_block = [has(JbdIncompat::CSUM_V2), has(JbdIncompat::CSUM_V3)];
        let commit_only = self.feature_compat & JBD2_FEATURE_COMPAT_CHECKSUM != 0;
        match per_block {
            [false, false] => None,
            [true, true] => Some("journal declares both CSUM_V2 and CSUM_V3"),
            _ if commit_only => Some("journal declares v1 checksums alongside CSUM_V2/V3"),
            _ if self.checksum_type != JBD2_CRC32C_CHKSUM => {
                Some("journal checksum type is not crc32c")
            }
            _ => None,
        }
    }

    /// The journal checksum seed: the crc32c of the journal's UUID, from
    /// `~0`. Every transaction-block checksum starts from it.
    pub fn csum_seed(&self) -> u32 {
        crate::checksum::linux_crc32c(!0, &self.uuid)
    }

    /// Bytes per descriptor-block tag, not counting the 16-byte UUID that
    /// follows a tag without the "same UUID" flag.
    ///
    /// journal.html describes two tag records: the v3 one (block number,
    /// flags, high block number, 32-bit checksum -- always all four
    /// words) and the older one (block number, 16-bit checksum, 16-bit
    /// flags, and the high block number only under `64BIT`). It does not
    /// say the older record's checksum slot exists only under v2; that was
    /// measured on journals `debugfs jo`/`jw` wrote in the harness VM
    /// (tests/jbd2_layouts_oracle.rs), where the distance between
    /// consecutive tags is exactly this table.
    pub fn tag_bytes(&self) -> usize {
        let per_block_scheme = if self.uses_csum_v3() {
            TagChecksum::V3
        } else if self.feature_incompat & JbdIncompat::CSUM_V2.bits() != 0 {
            TagChecksum::V2
        } else {
            TagChecksum::None
        };
        match (per_block_scheme, self.uses_64bit()) {
            (TagChecksum::None, false) => 8,
            (TagChecksum::None, true) => 12,
            (TagChecksum::V2, false) => 10,
            (TagChecksum::V2, true) => 14,
            (TagChecksum::V3, _) => 16,
        }
    }
}

/// Which per-block checksum a descriptor tag carries, for [`JournalSuperblock::tag_bytes`].
#[derive(Clone, Copy)]
enum TagChecksum {
    None,
    V2,
    V3,
}

/// `JBD2_FEATURE_COMPAT_CHECKSUM`: the v1 commit-block checksum.
pub const JBD2_FEATURE_COMPAT_CHECKSUM: u32 = 0x1;

/// `JBD2_CRC32C_CHKSUM`, the one `s_checksum_type` CSUM_V2/V3 allow.
pub const JBD2_CRC32C_CHKSUM: u8 = 4;

/// Journal incompat bits this driver replays and writes.
pub const SUPPORTED_JBD_INCOMPAT: u32 = JbdIncompat::REVOKE.bits()
    | JbdIncompat::BIT64.bits()
    | JbdIncompat::CSUM_V2.bits()
    | JbdIncompat::CSUM_V3.bits();

/// Bytes a checksummed journal reserves at the end of a descriptor or
/// revoke block for its `t_checksum` / `r_checksum` tail.
pub const BLOCK_TAIL_BYTES: usize = 4;

/// Offset of `h_chksum[0]` in a commit block (after the 12-byte header,
/// `h_chksum_type`, `h_chksum_size` and two bytes of padding).
pub const COMMIT_CHECKSUM_AT: usize = 16;

/// A tag's checksum: crc32c of the big-endian transaction sequence then
/// the journal copy of the block, from the journal's seed (the tag's
/// `t_checksum` in the format documentation). CSUM_V3 stores all 32 bits;
/// CSUM_V2 the
/// low 16.
pub fn tag_checksum(seed: u32, sequence: u32, data: &[u8]) -> u32 {
    let seq = crate::checksum::linux_crc32c(seed, &sequence.to_be_bytes());
    crate::checksum::linux_crc32c(seq, data)
}

/// A descriptor or revoke block's tail checksum: crc32c of the whole
/// block with the last four bytes taken as zero (the format
/// documentation's `jbd2_journal_block_tail` and `r_checksum`).
pub fn block_tail_checksum(seed: u32, block: &[u8]) -> u32 {
    let body = block.len().saturating_sub(BLOCK_TAIL_BYTES);
    let crc = crate::checksum::linux_crc32c(seed, &block[..body]);
    crate::checksum::linux_crc32c(crc, &[0u8; BLOCK_TAIL_BYTES])
}

/// A commit block's checksum: crc32c of the whole block with `h_chksum[0]`
/// taken as zero (the format documentation's `h_chksum`).
pub fn commit_block_checksum(seed: u32, block: &[u8]) -> u32 {
    let at = COMMIT_CHECKSUM_AT;
    let crc = crate::checksum::linux_crc32c(seed, &block[..at]);
    let crc = crate::checksum::linux_crc32c(crc, &[0u8; 4]);
    crate::checksum::linux_crc32c(crc, &block[at + 4..])
}

impl JournalSuperblock {
    /// Parse a journal superblock from its 1024-byte on-disk representation.
    /// `raw` should be at least 1024 bytes (block-size bytes in practice); we
    /// only read up to offset 0x100.
    pub fn parse(raw: &[u8]) -> Result<Self> {
        if raw.len() < 0x100 {
            return Err(Error::Corrupt("jbd2 superblock buffer too small"));
        }

        let h_magic = u32::from_be_bytes(raw[0x00..0x04].try_into().unwrap());
        if h_magic != JBD2_MAGIC_NUMBER {
            return Err(Error::Corrupt("jbd2 superblock magic mismatch"));
        }
        let block_type = u32::from_be_bytes(raw[0x04..0x08].try_into().unwrap());
        if block_type != JBD2_SUPERBLOCK_V1 && block_type != JBD2_SUPERBLOCK_V2 {
            return Err(Error::Corrupt("jbd2 header is not a superblock block type"));
        }
        let header_sequence = u32::from_be_bytes(raw[0x08..0x0C].try_into().unwrap());

        let block_size = u32::from_be_bytes(raw[0x0C..0x10].try_into().unwrap());
        let max_len = u32::from_be_bytes(raw[0x10..0x14].try_into().unwrap());
        let first = u32::from_be_bytes(raw[0x14..0x18].try_into().unwrap());
        let sequence = u32::from_be_bytes(raw[0x18..0x1C].try_into().unwrap());
        let start = u32::from_be_bytes(raw[0x1C..0x20].try_into().unwrap());
        let errno = u32::from_be_bytes(raw[0x20..0x24].try_into().unwrap());

        let mut out = Self {
            block_type,
            header_sequence,
            block_size,
            max_len,
            first,
            sequence,
            start,
            errno,
            feature_compat: 0,
            feature_incompat: 0,
            feature_ro_compat: 0,
            uuid: [0; 16],
            nr_users: 0,
            checksum_type: 0,
            num_fc_blocks: 0,
            checksum: 0,
        };

        // V2 extends with the dynamic-journal-features section.
        if block_type == JBD2_SUPERBLOCK_V2 {
            out.feature_compat = u32::from_be_bytes(raw[0x24..0x28].try_into().unwrap());
            out.feature_incompat = u32::from_be_bytes(raw[0x28..0x2C].try_into().unwrap());
            out.feature_ro_compat = u32::from_be_bytes(raw[0x2C..0x30].try_into().unwrap());
            out.uuid.copy_from_slice(&raw[0x30..0x40]);
            out.nr_users = u32::from_be_bytes(raw[0x40..0x44].try_into().unwrap());
            // 0x44 s_dynsuper ignored (never used by upstream)
            // 0x48 s_max_transaction / 0x4C s_max_trans_data ignored (hints only)
            out.checksum_type = raw[0x50];
            // 0x51..0x54 padding
            out.num_fc_blocks = u32::from_be_bytes(raw[0x54..0x58].try_into().unwrap());
            // 0x58 s_head / padding
            out.checksum = u32::from_be_bytes(raw[0xFC..0x100].try_into().unwrap());
        }

        Ok(out)
    }
}

/// Map a journal-relative block number to its physical fs block. Journal
/// block 0 contains the superblock.
///
/// Flavor-aware via [`crate::indirect::map_logical_any`]: ext4 journals
/// (whose journal inode carries `EXT4_EXTENTS_FL`) traverse the extent
/// tree; ext3 journals (legacy direct/indirect block pointers) walk the
/// indirect tree. Both schemes return `Ok(Some(physical))` for mapped
/// blocks, `Ok(None)` for sparse holes (which a healthy journal should
/// never have, but we don't enforce that here).
pub fn journal_block_to_physical(
    fs: &Filesystem,
    journal_inode: &Inode,
    journal_block: u64,
) -> Result<Option<u64>> {
    crate::indirect::map_logical_any(
        &journal_inode.block,
        journal_inode.flags,
        fs.dev.as_ref(),
        fs.sb.block_size(),
        journal_block,
    )
}

/// Read and parse the JBD2 superblock at block 0 of the journal.
///
/// Flow:
///   1. Look up `sb.journal_inode` (typically ino 8).
///   2. Map journal logical block 0 → physical fs block via its extent tree.
///   3. Read the block (one fs block; the JBD2 sb fits within it).
///   4. Parse the first 256 bytes as a `JournalSuperblock`.
///
/// Returns `Ok(None)` if `sb.journal_inode == 0` (filesystem lacks a journal).
pub fn read_superblock(fs: &Filesystem) -> Result<Option<JournalSuperblock>> {
    let jino_num = fs.sb.journal_inode;
    if jino_num == 0 {
        return Ok(None);
    }

    let raw = fs.read_inode_raw(jino_num)?;
    let jinode = Inode::parse(&raw)?;

    let phys = journal_block_to_physical(fs, &jinode, 0)?
        .ok_or(Error::Corrupt("journal block 0 unmapped (sparse journal?)"))?;

    let block_size = fs.sb.block_size() as u64;
    let mut buf = vec![0u8; block_size as usize];
    fs.dev.read_at(phys * block_size, &mut buf)?;
    Ok(Some(JournalSuperblock::parse(&buf)?))
}

#[cfg(test)]
mod tests {
    use super::*;

    fn jsb_with(incompat: u32) -> JournalSuperblock {
        let mut jsb = JournalSuperblock::parse(&make_v2_sb()).unwrap();
        jsb.feature_incompat = incompat;
        jsb
    }

    /// The tag sizes measured on debugfs-written journals: the distance
    /// between the second and third tag of a descriptor block, for each
    /// scheme with and without 64BIT.
    #[test]
    fn tag_sizes_are_the_measured_table() {
        let b64 = JbdIncompat::BIT64.bits();
        let v2 = JbdIncompat::CSUM_V2.bits();
        let v3 = JbdIncompat::CSUM_V3.bits();
        for (incompat, bytes) in [
            (0, 8),
            (b64, 12),
            (v2, 10),
            (v2 | b64, 14),
            (v3, 16),
            (v3 | b64, 16),
        ] {
            assert_eq!(
                jsb_with(incompat).tag_bytes(),
                bytes,
                "incompat {incompat:#x}"
            );
        }
    }

    /// The accept/refuse table the kernel and e2fsck gave for patched
    /// journal superblocks (tests/jbd2_layouts_oracle.rs runs it live).
    #[test]
    fn checksum_declarations_follow_the_observed_table() {
        let v2 = JbdIncompat::CSUM_V2.bits();
        let v3 = JbdIncompat::CSUM_V3.bits();
        let v1 = JBD2_FEATURE_COMPAT_CHECKSUM;
        let with = |compat: u32, incompat: u32, kind: u8| {
            let mut jsb = jsb_with(incompat);
            jsb.feature_compat = compat;
            jsb.checksum_type = kind;
            jsb.checksum_declaration_error().is_none()
        };
        let accepted = [
            (0, 0, 0),
            (0, 0, 4),
            (v1, 0, 0),
            (v1, 0, 1),
            (v1, 0, 4),
            (0, v2, 4),
            (0, v3, 4),
        ];
        let refused = [
            (0, v2 | v3, 4),
            (v1, v2, 4),
            (v1, v3, 4),
            (0, v2, 1),
            (0, v3, 1),
            (0, v3, 2),
            (0, v3, 0),
        ];
        for (compat, incompat, kind) in accepted {
            assert!(
                with(compat, incompat, kind),
                "{compat:#x}/{incompat:#x}/{kind}"
            );
        }
        for (compat, incompat, kind) in refused {
            assert!(
                !with(compat, incompat, kind),
                "{compat:#x}/{incompat:#x}/{kind}"
            );
        }
    }

    #[test]
    fn async_commit_and_fast_commit_are_unsupported() {
        let known =
            JbdIncompat::REVOKE.bits() | JbdIncompat::BIT64.bits() | JbdIncompat::CSUM_V3.bits();
        assert_eq!(jsb_with(known).unsupported_incompat(), 0);
        for bit in [
            JbdIncompat::ASYNC_COMMIT.bits(),
            JbdIncompat::FAST_COMMIT.bits(),
            0x8000_0000,
        ] {
            assert_eq!(jsb_with(known | bit).unsupported_incompat(), bit);
        }
    }

    /// The tail and commit checksums treat their own field as zero, so what
    /// is stored there does not change them, and every other byte does.
    #[test]
    fn block_checksums_skip_only_their_own_field() {
        let seed = jsb_with(0).csum_seed();
        let mut block = vec![0x5Au8; 4096];
        let tail = block_tail_checksum(seed, &block);
        block[4092..].fill(0xFF);
        assert_eq!(block_tail_checksum(seed, &block), tail);
        let commit = commit_block_checksum(seed, &block);
        block[COMMIT_CHECKSUM_AT..COMMIT_CHECKSUM_AT + 4].fill(0x00);
        assert_eq!(commit_block_checksum(seed, &block), commit);
        block[4091] ^= 1;
        assert_ne!(block_tail_checksum(seed, &block), tail);
        assert_ne!(commit_block_checksum(seed, &block), commit);
        assert_ne!(tag_checksum(seed, 1, &block), tag_checksum(seed, 2, &block));
    }

    /// Build a synthetic V2 superblock buffer for parser unit-testing.
    fn make_v2_sb() -> Vec<u8> {
        let mut buf = vec![0u8; 1024];
        buf[0x00..0x04].copy_from_slice(&JBD2_MAGIC_NUMBER.to_be_bytes());
        buf[0x04..0x08].copy_from_slice(&JBD2_SUPERBLOCK_V2.to_be_bytes());
        buf[0x08..0x0C].copy_from_slice(&1u32.to_be_bytes()); // header seq
        buf[0x0C..0x10].copy_from_slice(&4096u32.to_be_bytes()); // block_size
        buf[0x10..0x14].copy_from_slice(&8192u32.to_be_bytes()); // max_len
        buf[0x14..0x18].copy_from_slice(&1u32.to_be_bytes()); // first
        buf[0x18..0x1C].copy_from_slice(&42u32.to_be_bytes()); // sequence
        buf[0x1C..0x20].copy_from_slice(&0u32.to_be_bytes()); // start = 0 (clean)
        buf[0x20..0x24].copy_from_slice(&0u32.to_be_bytes()); // errno
        buf[0x24..0x28].copy_from_slice(&0u32.to_be_bytes()); // feat_compat
        buf[0x28..0x2C].copy_from_slice(
            &(JbdIncompat::REVOKE.bits() | JbdIncompat::CSUM_V3.bits()).to_be_bytes(),
        );
        buf[0x2C..0x30].copy_from_slice(&0u32.to_be_bytes()); // feat_ro
        buf[0x30..0x40].copy_from_slice(&[0xAA; 16]);
        buf[0x40..0x44].copy_from_slice(&1u32.to_be_bytes()); // nr_users
        buf[0x50] = 4; // crc32c
        buf[0xFC..0x100].copy_from_slice(&0xDEADBEEFu32.to_be_bytes());
        buf
    }

    #[test]
    fn parses_v2_superblock() {
        let buf = make_v2_sb();
        let sb = JournalSuperblock::parse(&buf).unwrap();
        assert_eq!(sb.block_type, JBD2_SUPERBLOCK_V2);
        assert_eq!(sb.block_size, 4096);
        assert_eq!(sb.max_len, 8192);
        assert_eq!(sb.first, 1);
        assert_eq!(sb.sequence, 42);
        assert!(sb.is_clean());
        assert!(sb.has_revoke());
        assert!(sb.uses_csum_v2_or_v3());
        assert!(!sb.uses_64bit());
        assert_eq!(sb.checksum_type, 4);
        assert_eq!(sb.checksum, 0xDEADBEEF);
    }

    #[test]
    fn rejects_bad_magic() {
        let mut buf = make_v2_sb();
        buf[0] = 0;
        assert!(JournalSuperblock::parse(&buf).is_err());
    }

    #[test]
    fn rejects_non_superblock_block_type() {
        let mut buf = make_v2_sb();
        buf[0x04..0x08].copy_from_slice(&JBD2_DESCRIPTOR_BLOCK.to_be_bytes());
        assert!(JournalSuperblock::parse(&buf).is_err());
    }

    #[test]
    fn v1_leaves_feature_fields_zero() {
        let mut buf = make_v2_sb();
        buf[0x04..0x08].copy_from_slice(&JBD2_SUPERBLOCK_V1.to_be_bytes());
        // Even though we wrote feature bytes, parse skips them on V1.
        let sb = JournalSuperblock::parse(&buf).unwrap();
        assert_eq!(sb.feature_incompat, 0);
        assert_eq!(sb.uuid, [0; 16]);
        assert_eq!(sb.checksum, 0);
    }

    #[test]
    fn dirty_sb_is_not_clean() {
        let mut buf = make_v2_sb();
        buf[0x1C..0x20].copy_from_slice(&100u32.to_be_bytes()); // start != 0
        let sb = JournalSuperblock::parse(&buf).unwrap();
        assert!(!sb.is_clean());
        assert_eq!(sb.start, 100);
    }
}