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
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
//! Metadata checksum verification (RO_COMPAT_METADATA_CSUM).
//!
//! Spec: kernel.org/doc/html/latest/filesystems/ext4/checksums.html
//!
//! When `RO_COMPAT_METADATA_CSUM` is set, ext4 stores a CRC32C of every
//! metadata structure to detect on-disk corruption. The checksum is salted
//! by the **filesystem UUID** (or by `s_checksum_seed` when
//! `INCOMPAT_CSUM_SEED` is also set) so the same byte pattern in two
//! different filesystems hashes differently.
//!
//! The spec uses a chained CRC pattern:
//!
//! 1. Start with the seed (UUID or s_checksum_seed).
//! 2. For per-group/per-inode structures, fold in the group number / inode
//!    number / generation as a "context" prefix.
//! 3. Then CRC the actual structure with the checksum field zeroed.
//!
//! This module exposes two helpers:
//!   - [`Checksummer::seed`] — derived once at mount time
//!   - [`Checksummer::superblock`], [`Checksummer::inode`], etc.
//!
//! Verification is enforced, not informational. A superblock or group
//! descriptor whose checksum does not match aborts the mount with
//! `Error::BadChecksum`, as does an inode read through
//! `Filesystem::read_inode_verified`, and extent and directory blocks are
//! checked as they are read. Every write recomputes the checksums of what it
//! rewrites -- inodes in `finalize_inode_raw`, group descriptors and the
//! superblock in `buffer_patch_bgd_counters` / `buffer_patch_sb_counters`,
//! and the tails of directory and extent blocks -- so a new write path that
//! rewrites a metadata block must recompute its checksum too (#90).

use crate::features::{Incompat, RoCompat};
use crate::superblock::Superblock;

/// CRC32C as ext4 and JBD2 chain it: the seed goes in as the register
/// value and nothing is inverted at either end. The `crc32c` crate's
/// `crc32c_append(s, d)` is `~iterate(~s, d)`; the chaining form is
/// `iterate(c, d)`. Wrap to get that form out of the crate.
///
/// Public so write-path callers that rewrite a metadata block (dir, BGD, SB)
/// can recompute the tail checksum inline without rebuilding a `Checksummer`.
#[inline]
pub fn linux_crc32c(seed: u32, data: &[u8]) -> u32 {
    !crc32c::crc32c_append(!seed, data)
}

/// CRC-16 with polynomial 0x8005, reflected, no final XOR (the parameters
/// catalogued as CRC-16/ARC). Only `GDT_CSUM` group descriptors use it; the
/// format documentation's checksum table names it as their `crc16`.
pub fn crc16(mut crc: u16, data: &[u8]) -> u16 {
    for &b in data {
        crc ^= u16::from(b);
        for _ in 0..8 {
            crc = if crc & 1 != 0 {
                (crc >> 1) ^ 0xA001
            } else {
                crc >> 1
            };
        }
    }
    crc
}

/// The checksum group descriptor `group` must carry at 0x1E, or `None`
/// when the volume asks for none.
///
/// The ingredients are the "Group Descriptors" row of the checksum table
/// in the kernel.org ext4 format documentation. With `METADATA_CSUM` it is
/// the low 16 bits of `crc32c(seed, group_le32 || desc)`. Otherwise, with
/// `GDT_CSUM`, it is `crc16(~0, uuid || group_le32 || desc[..0x1E])`, plus
/// the bytes past the checksum field only when `INCOMPAT_64BIT` is set.
/// Either way the checksum field itself counts as zero. `desc` must hold
/// at least `sb.desc_size` bytes; `None` is also returned when it doesn't.
pub fn group_desc_csum(
    sb: &Superblock,
    csum: &Checksummer,
    group: u32,
    desc: &[u8],
) -> Option<u16> {
    let n = sb.desc_size as usize;
    if desc.len() < n || n < 0x20 {
        return None;
    }
    let le_group = group.to_le_bytes();
    if sb.feature_ro_compat & RoCompat::METADATA_CSUM.bits() != 0 {
        let mut c = linux_crc32c(csum.seed, &le_group);
        c = linux_crc32c(c, &desc[..0x1E]);
        c = linux_crc32c(c, &[0, 0]);
        c = linux_crc32c(c, &desc[0x20..n]);
        return Some(c as u16);
    }
    if sb.feature_ro_compat & RoCompat::GDT_CSUM.bits() == 0 {
        return None;
    }
    let mut c = crc16(!0, &sb.uuid);
    c = crc16(c, &le_group);
    c = crc16(c, &desc[..0x1E]);
    if sb.feature_incompat & Incompat::BIT64.bits() != 0 {
        c = crc16(c, &desc[0x20..n]);
    }
    Some(c)
}

/// Per-mount checksum context: the seed and "is it enabled" flag.
#[derive(Debug, Clone, Copy)]
pub struct Checksummer {
    pub seed: u32,
    pub enabled: bool,
}

/// `file_type` of the fake dirent that ends a checksummed directory
/// block: the `det_reserved_ft` value the format documentation gives for
/// `struct ext4_dir_entry_tail`.
///
/// Not a real file type: it is out of range for one, which is how a
/// reader tells the tail apart from an entry.
pub const DIR_ENTRY_TAIL_FILE_TYPE: u8 = 0xDE;

impl Checksummer {
    /// Derive the checksum context from a parsed superblock.
    ///
    /// Per spec: if `INCOMPAT_CSUM_SEED` is set, use the explicit
    /// `s_checksum_seed` field. Otherwise, the seed is crc32c(~0, UUID)
    /// (format documentation, `s_checksum_seed`) — i.e. our
    /// `linux_crc32c(!0, UUID)`.
    pub fn from_superblock(sb: &Superblock) -> Self {
        let enabled = (sb.feature_ro_compat & RoCompat::METADATA_CSUM.bits()) != 0;
        let seed = if (sb.feature_incompat & Incompat::CSUM_SEED.bits()) != 0 {
            sb.checksum_seed
        } else {
            linux_crc32c(!0, &sb.uuid)
        };
        Self { seed, enabled }
    }

    /// Linux-semantics CRC32C of a buffer using the mount-wide seed.
    pub fn crc(&self, data: &[u8]) -> u32 {
        linux_crc32c(self.seed, data)
    }

    /// Linux-semantics CRC32C with a 32-bit context prefix folded in first.
    pub fn crc_with_prefix(&self, prefix: u32, data: &[u8]) -> u32 {
        let mid = linux_crc32c(self.seed, &prefix.to_le_bytes());
        linux_crc32c(mid, data)
    }

    /// Verify the superblock checksum. Stored at byte offset 0x3FC; CRC
    /// covers the first 0x3FC bytes. Initial seed is `~0` (NOT the per-FS
    /// seed — superblock checksum is special since the seed lives inside it).
    pub fn verify_superblock(&self, sb_raw: &[u8]) -> bool {
        if !self.enabled {
            return true;
        }
        if sb_raw.len() < 1024 {
            return false;
        }
        let stored = u32::from_le_bytes(sb_raw[0x3FC..0x400].try_into().unwrap());
        let computed = linux_crc32c(!0, &sb_raw[..0x3FC]);
        stored == computed
    }

    /// Verify a block group descriptor's checksum.
    ///
    /// Per spec (`ext4/group_descr.html`), when `RO_COMPAT_METADATA_CSUM` is
    /// set the GDT checksum is computed as:
    ///
    /// ```text
    ///   crc32c(seed, group_no_le_u32 || bgd_with_csum_zeroed) & 0xFFFF
    /// ```
    ///
    /// `desc_size` is the on-disk descriptor size (32 or 64).
    /// `bgd_raw` must be at least `desc_size` bytes; the stored checksum at
    /// offset 0x1E is treated as zero for the computation.
    pub fn verify_bgd(&self, group_no: u32, bgd_raw: &[u8], desc_size: u16) -> bool {
        if !self.enabled {
            return true;
        }
        let n = desc_size as usize;
        if bgd_raw.len() < n || n < 0x20 {
            return false;
        }
        let stored = u16::from_le_bytes(bgd_raw[0x1E..0x20].try_into().unwrap());

        let mut tmp = bgd_raw[..n].to_vec();
        tmp[0x1E] = 0;
        tmp[0x1F] = 0;

        let computed16 = self.crc_with_prefix(group_no, &tmp) as u16;
        computed16 == stored
    }

    /// Verify a directory block's trailing `ext4_dir_entry_tail` checksum.
    ///
    /// Linear directory blocks with `metadata_csum` enabled end in a 12-byte
    /// `struct ext4_dir_entry_tail { u32 det_reserved_zero1; u16 det_rec_len;
    /// u8 det_reserved_zero2; u8 det_reserved_ft; u32 det_checksum; }`.
    ///
    /// The format documentation's checksum table ("Directory Entries"): the
    /// CRC covers **`block[0..block_size - 12]`** — i.e. everything BEFORE
    /// the fake entry that holds it.
    /// The tail's own bytes (including `det_checksum`) are excluded:
    ///
    /// ```text
    ///   crc32c(seed, ino_le) → crc32c(., gen_le) → crc32c(., block[..len-12])
    /// ```
    ///
    /// `block` is the whole directory block including the trailing tail.
    pub fn verify_dir_entry_tail(&self, ino: u32, generation: u32, block: &[u8]) -> bool {
        if !self.enabled {
            return true;
        }
        if block.len() < 12 {
            return false;
        }
        let end = block.len();
        let stored = u32::from_le_bytes(block[end - 4..end].try_into().unwrap());

        let mut c = linux_crc32c(self.seed, &ino.to_le_bytes());
        c = linux_crc32c(c, &generation.to_le_bytes());
        c = linux_crc32c(c, &block[..end - 12]);
        c == stored
    }

    /// Plant the `ext4_dir_entry_tail` and checksum a directory block.
    ///
    /// The mirror of [`Self::verify_dir_entry_tail`], and the sibling
    /// that was missing: `patch_extent_tail` and `patch_xattr_block`
    /// both existed, so the one recipe written most often was the one
    /// with no helper. It was hand-rolled at **sixteen** sites across
    /// `fs.rs`, `fsck.rs`, `mkfs.rs` and the tests, in two different
    /// addressing idioms (`bs - 12` with `+4/+6/+7`, and
    /// `block.len()` with `-8/-6/-5`) that a reader has to prove
    /// equivalent at each one.
    ///
    /// The tail is a **fake directory entry** occupying the last 12
    /// bytes: `inode = 0` so no scan mistakes it for a real one,
    /// `rec_len = 12` so a walk steps over it, `name_len = 0`, and
    /// `file_type = 0xDE` as the marker `has_csum_tail` looks for. The
    /// CRC then covers `block[..len - 12]` — the whole block *except*
    /// the tail entry, which is what separates this from
    /// [`Self::patch_extent_tail`], where only the trailing 4 bytes are
    /// excluded.
    ///
    /// Planting is idempotent: a block that already carries the tail
    /// gets the same twelve bytes back, so callers that only need the
    /// checksum recomputed can use this too rather than keeping a
    /// second recipe for that case.
    ///
    /// Every constant here has to agree with e2fsprogs, and a
    /// disagreement produces no error until the volume is mounted
    /// somewhere else — which is the argument for there being one copy
    /// of them.
    ///
    /// No-op when checksums are disabled or the block is under 12
    /// bytes; returns true when it patched.
    pub fn patch_dir_entry_tail(&self, ino: u32, generation: u32, block: &mut [u8]) -> bool {
        if !self.enabled || block.len() < 12 {
            return false;
        }
        let end = block.len();
        block[end - 12..end - 8].copy_from_slice(&0u32.to_le_bytes()); // inode = 0
        block[end - 8..end - 6].copy_from_slice(&12u16.to_le_bytes()); // rec_len
        block[end - 6] = 0; // name_len
        block[end - 5] = DIR_ENTRY_TAIL_FILE_TYPE;

        let mut c = linux_crc32c(self.seed, &ino.to_le_bytes());
        c = linux_crc32c(c, &generation.to_le_bytes());
        c = linux_crc32c(c, &block[..end - 12]);
        block[end - 4..end].copy_from_slice(&c.to_le_bytes());
        true
    }

    /// Whether an htree block's `dx_tail` checksum is the one its contents
    /// give: `Some(true)` or `Some(false)`, or `None` when checksums are off
    /// or the count/limit pair leaves no room for a tail to check.
    ///
    /// The same computation as [`Checksummer::patch_dx_tail`], compared
    /// rather than written.
    pub fn verify_dx_tail(
        &self,
        ino: u32,
        generation: u32,
        block: &[u8],
        count_offset: usize,
    ) -> Option<bool> {
        let mut copy = block.to_vec();
        if !self.patch_dx_tail(ino, generation, &mut copy, count_offset) {
            return None;
        }
        Some(copy == block)
    }

    /// Recompute the checksum in an htree block's `dx_tail`.
    ///
    /// The "HTREE Nodes" row of the format documentation's checksum table:
    /// crc32c over the inode number and
    /// generation, the block up to the last used `dx_entry`, and the tail's
    /// reserved word, with the checksum field itself counted as zero. The
    /// tail sits right after `limit` entries. `count_offset` is where the
    /// count/limit pair starts: 32 in a `dx_root`, 8 in an interior node.
    /// Returns `false` (and writes nothing) when checksums are off or the
    /// count/limit pair does not leave room for a tail in this block.
    pub fn patch_dx_tail(
        &self,
        ino: u32,
        generation: u32,
        block: &mut [u8],
        count_offset: usize,
    ) -> bool {
        if !self.enabled || block.len() < count_offset + 4 {
            return false;
        }
        let limit = u16::from_le_bytes([block[count_offset], block[count_offset + 1]]) as usize;
        let count = u16::from_le_bytes([block[count_offset + 2], block[count_offset + 3]]) as usize;
        let tail = count_offset + limit * 8;
        if count > limit || tail + 8 > block.len() {
            return false;
        }
        let mut c = linux_crc32c(self.seed, &ino.to_le_bytes());
        c = linux_crc32c(c, &generation.to_le_bytes());
        c = linux_crc32c(c, &block[..count_offset + count * 8]);
        c = linux_crc32c(c, &block[tail..tail + 4]);
        c = linux_crc32c(c, &[0; 4]);
        block[tail + 4..tail + 8].copy_from_slice(&c.to_le_bytes());
        true
    }

    /// Verify an extent-block tail checksum.
    ///
    /// Extent index/leaf blocks (those read off-inode when the tree has
    /// internal nodes) end in a 4-byte `struct ext4_extent_tail
    /// { u32 et_checksum; }`. Per the "Extents" row of the format
    /// documentation's checksum table the CRC covers **`block[0..len-4]`**
    /// — only the trailing `et_checksum` field is excluded:
    ///
    /// ```text
    ///   crc32c(seed, ino_le) → crc32c(., gen_le) → crc32c(., block[..len-4])
    /// ```
    ///
    /// Different from `verify_dir_entry_tail`, which excludes the full
    /// 12-byte tail entry.
    pub fn verify_extent_tail(&self, ino: u32, generation: u32, block: &[u8]) -> bool {
        if !self.enabled {
            return true;
        }
        if block.len() < 4 {
            return false;
        }
        let end = block.len();
        let stored = u32::from_le_bytes(block[end - 4..end].try_into().unwrap());

        let mut c = linux_crc32c(self.seed, &ino.to_le_bytes());
        c = linux_crc32c(c, &generation.to_le_bytes());
        c = linux_crc32c(c, &block[..end - 4]);
        c == stored
    }

    /// Verify a parsed inode's checksum.
    /// Chained: seed → ino_le → gen_le → inode_bytes (with checksum slots zeroed).
    pub fn verify_inode(&self, ino: u32, generation: u32, inode_raw: &[u8]) -> bool {
        if !self.enabled {
            return true;
        }
        // A truncated read is a refusal, not a pass — the same answer
        // `verify_superblock`, `verify_dir_entry_tail` and
        // `verify_extent_tail` give, and for the same reason: the
        // caller got fewer bytes than it asked for, so a checksum
        // computed here would cover bytes that are not the ones on
        // disk. Reporting `true` says an inode verified when nothing
        // verified it.
        //
        // This used to read `if !self.enabled || inode_raw.len() < 128`,
        // one `||` instead of two `if`s — a difference invisible unless
        // you read all four verifiers together.
        if inode_raw.len() < crate::inode::GOOD_OLD_INODE_SIZE {
            return false;
        }
        let stored_lo = u16::from_le_bytes(inode_raw[0x7C..0x7E].try_into().unwrap()) as u32;
        // Only where `i_checksum_hi` exists. Below `i_extra_isize = 4` the
        // bytes at 0x82 are ordinary inode bytes the checksum covers, and
        // the kernel and libext2fs compare the low 16 bits alone (#380).
        let stored_hi = if checksum_hi_fits(inode_raw) {
            u16::from_le_bytes(inode_raw[0x82..0x84].try_into().unwrap()) as u32
        } else {
            0
        };
        let stored = (stored_hi << 16) | stored_lo;
        match self.compute_inode_checksum(ino, generation, inode_raw) {
            Some((lo, hi)) => ((hi as u32) << 16 | lo as u32) == stored,
            None => true, // disabled / too short — accept
        }
    }

    /// Write the `ext4_extent_tail.et_checksum` u32 at the end of a freshly-
    /// built extent index/leaf block. Mirrors `verify_extent_tail`: the CRC
    /// covers `block[..len-4]`, chained seed → ino → generation → body.
    /// No-op when checksums are disabled; returns true when it patched.
    pub fn patch_extent_tail(&self, ino: u32, generation: u32, block: &mut [u8]) -> bool {
        if !self.enabled || block.len() < 4 {
            return false;
        }
        let end = block.len();
        let mut c = linux_crc32c(self.seed, &ino.to_le_bytes());
        c = linux_crc32c(c, &generation.to_le_bytes());
        c = linux_crc32c(c, &block[..end - 4]);
        block[end - 4..end].copy_from_slice(&c.to_le_bytes());
        true
    }

    /// Verify an external xattr block's checksum.
    ///
    /// The format documentation's checksum table gives the block with its
    /// checksum field zeroed; the block number goes in ahead of it as well,
    /// and blocks the kernel and e2fsprogs write verify this way. The
    /// recipe is:
    ///
    /// ```text
    ///   crc32c(seed, block_nr_le_u64)
    ///   → crc32c(., block[0x00..0x10])      // magic, refcount, blocks, hash
    ///   → crc32c(., [0u32])                  // h_checksum slot zeroed (4 bytes)
    ///   → crc32c(., block[0x14..end])        // rest of block
    /// ```
    ///
    /// The stored u32 lives at offset 0x10 of the block.
    pub fn verify_xattr_block(&self, block_nr: u64, block: &[u8]) -> bool {
        if !self.enabled {
            return true;
        }
        if block.len() < 0x20 {
            return false;
        }
        let stored = u32::from_le_bytes(block[0x10..0x14].try_into().unwrap());
        let computed = self.compute_xattr_block_csum(block_nr, block);
        stored == computed
    }

    /// Patch the `h_checksum` field of an external xattr block in place.
    /// Mirrors [`verify_xattr_block`]. No-op when checksums are disabled.
    /// Returns `true` when the block was patched.
    pub fn patch_xattr_block(&self, block_nr: u64, block: &mut [u8]) -> bool {
        if !self.enabled || block.len() < 0x20 {
            return false;
        }
        let csum = self.compute_xattr_block_csum(block_nr, block);
        block[0x10..0x14].copy_from_slice(&csum.to_le_bytes());
        true
    }

    fn compute_xattr_block_csum(&self, block_nr: u64, block: &[u8]) -> u32 {
        let mut c = linux_crc32c(self.seed, &block_nr.to_le_bytes());
        c = linux_crc32c(c, &block[0x00..0x10]);
        c = linux_crc32c(c, &0u32.to_le_bytes());
        c = linux_crc32c(c, &block[0x14..]);
        c
    }

    /// Compute the inode checksum as two u16 halves (lo=checksum_lo at 0x7C,
    /// hi=checksum_hi at 0x82). Returns `None` when checksums are disabled
    /// or the buffer is too short to patch. Callers use this after mutating
    /// an inode image to restore the checksum before writing back.
    pub fn compute_inode_checksum(
        &self,
        ino: u32,
        generation: u32,
        inode_raw: &[u8],
    ) -> Option<(u16, u16)> {
        if !self.enabled || inode_raw.len() < crate::inode::GOOD_OLD_INODE_SIZE {
            return None;
        }
        // i_checksum_hi (0x82) is part of the checksum only when i_extra_isize
        // (0x80) is large enough to cover it: a field past the 128-byte base
        // exists only if i_extra_isize reaches its end, which here means
        // i_extra_isize >= 4 (the format documentation's inode table puts
        // i_checksum_hi at 0x82). On a zeroed freed inode
        // (i_extra_isize = 0) the kernel uses ONLY the 16-bit lo checksum and
        // treats 0x82 as ordinary (zero) data; zeroing hi and storing a full
        // 32-bit value there mismatches ("checksum does not match inode").
        let fits_hi = checksum_hi_fits(inode_raw);
        let mut tmp = inode_raw.to_vec();
        tmp[0x7C] = 0;
        tmp[0x7D] = 0;
        if fits_hi {
            tmp[0x82] = 0;
            tmp[0x83] = 0;
        }
        let mut c = linux_crc32c(self.seed, &ino.to_le_bytes());
        c = linux_crc32c(c, &generation.to_le_bytes());
        c = linux_crc32c(c, &tmp);
        let lo = (c & 0xFFFF) as u16;
        let hi = if fits_hi {
            ((c >> 16) & 0xFFFF) as u16
        } else {
            0
        };
        Some((lo, hi))
    }

    /// Checksum `inode_raw` and store it: `i_checksum_lo` always, and
    /// `i_checksum_hi` only where the inode has one.
    ///
    /// EVERY WRITER USED TO STORE BOTH HALVES. With `i_extra_isize < 4`
    /// [`compute_inode_checksum`](Self::compute_inode_checksum) covers
    /// 0x82..0x84 as ordinary bytes and returns a `hi` of 0, and storing
    /// that 0 at 0x82 afterwards changed a byte the checksum had just
    /// covered -- and on an inode whose in-inode xattr area was placed at
    /// 0x80, erased the area's magic (#380). No-op when checksums are off.
    pub(crate) fn patch_inode_checksum(&self, ino: u32, generation: u32, inode_raw: &mut [u8]) {
        if let Some((lo, hi)) = self.compute_inode_checksum(ino, generation, inode_raw) {
            inode_raw[0x7C..0x7E].copy_from_slice(&lo.to_le_bytes());
            if checksum_hi_fits(inode_raw) {
                inode_raw[0x82..0x84].copy_from_slice(&hi.to_le_bytes());
            }
        }
    }
}

/// Whether the inode has an `i_checksum_hi`: `i_extra_isize` (0x80) covers
/// 0x82..0x84. A field in the extended part of the inode exists only when
/// `i_extra_isize` reaches its end (format documentation, "Inode Size").
fn checksum_hi_fits(inode_raw: &[u8]) -> bool {
    inode_raw.len() >= 0x84 && u16::from_le_bytes(inode_raw[0x80..0x82].try_into().unwrap()) >= 4
}

#[cfg(test)]
mod tests {

    // --- a short buffer is a refusal, on every verifier ------------------
    //
    // Written before the fix. `verify_inode` passed a truncated buffer;
    // its three siblings refused one. Nothing in the crate noticed the
    // difference, because the short-buffer axis had no coverage at all.

    /// A checksummer that is switched on, with an arbitrary seed.
    fn enabled() -> Checksummer {
        Checksummer {
            enabled: true,
            seed: 0xDEAD_BEEF,
        }
    }

    /// Every verifier refuses a buffer too short to hold the field it
    /// checks.
    ///
    /// This is a policy, not four separate decisions, and it is the
    /// safe direction: a truncated read means the caller got less than
    /// it asked for, and the checksum it would compute covers bytes
    /// that are not the ones on disk. Returning `true` there reports a
    /// structure as verified when nothing verified it.
    ///
    /// Asserted as a set so a fifth verifier cannot quietly pick the
    /// other answer — which is exactly how `verify_inode` came to
    /// differ from the other three.
    #[test]
    fn every_verifier_refuses_a_buffer_too_short_to_check() {
        let c = enabled();
        assert!(
            !c.verify_superblock(&[0u8; 64]),
            "superblock: a 64-byte buffer cannot hold a checksum at 0x3FC"
        );
        assert!(
            !c.verify_dir_entry_tail(2, 0, &[0u8; 8]),
            "dir entry tail: an 8-byte buffer cannot hold a 12-byte tail"
        );
        assert!(
            !c.verify_extent_tail(2, 0, &[0u8; 2]),
            "extent tail: a 2-byte buffer cannot hold a 4-byte checksum"
        );
        assert!(
            !c.verify_inode(2, 0, &[0u8; 64]),
            "inode: a 64-byte buffer cannot hold a checksum at 0x7C"
        );
    }

    /// And every one of them still passes everything when checksums are
    /// off, short buffer included.
    ///
    /// The two conditions are separate for a reason: "we do not check"
    /// and "we checked and it failed" are different answers, and a
    /// filesystem without `metadata_csum` must not start failing reads
    /// because a buffer was short.
    #[test]
    fn a_disabled_checksummer_passes_even_a_short_buffer() {
        let c = Checksummer {
            enabled: false,
            seed: 0,
        };
        assert!(c.verify_superblock(&[0u8; 4]));
        assert!(c.verify_dir_entry_tail(2, 0, &[0u8; 4]));
        assert!(c.verify_extent_tail(2, 0, &[0u8; 1]));
        assert!(c.verify_inode(2, 0, &[0u8; 4]));
    }

    /// The boundary itself: 127 bytes is refused, 128 is checked.
    ///
    /// 128 is not where `verify_inode`'s own field ends — `i_checksum_lo`
    /// sits at 0x7C..0x7E, so 126 bytes would hold it. It is the whole
    /// fixed ext2 inode, every byte of which the checksum covers, so a
    /// shorter buffer cannot be checked even when it holds the field.
    #[test]
    fn the_inode_length_boundary_is_the_whole_fixed_inode() {
        let c = enabled();
        assert!(!c.verify_inode(2, 0, &[0u8; 127]), "127 is too short");
        // 128 bytes of zeros is a real check that simply fails: the
        // stored checksum is zero and the computed one is not.
        assert!(
            !c.verify_inode(2, 0, &[0u8; 128]),
            "128 is checked, and all-zero bytes do not verify"
        );

        // A 128-byte inode with a correct checksum verifies.
        let mut raw: Vec<u8> = (0..128u32).map(|i| (i * 7 + 3) as u8).collect();
        let (lo, _) = c.compute_inode_checksum(2, 5, &raw).unwrap();
        raw[0x7C..0x7E].copy_from_slice(&lo.to_le_bytes());
        assert!(c.verify_inode(2, 5, &raw), "a correct checksum verifies");

        // The bytes past the field are covered: 0x7E..0x80 is after
        // `i_checksum_lo` and still inside the fixed inode.
        let mut past_the_field = raw.clone();
        past_the_field[0x7F] ^= 0x01;
        assert!(
            !c.verify_inode(2, 5, &past_the_field),
            "a byte after i_checksum_lo is part of the checksum"
        );

        // 126 bytes hold the field, and carry a checksum that is correct
        // over those 126 bytes — and are still refused, because they are
        // not the whole fixed inode the checksum is defined over.
        let mut holds_the_field = raw[..0x7E].to_vec();
        holds_the_field[0x7C..0x7E].fill(0);
        let mut crc = linux_crc32c(c.seed, &2u32.to_le_bytes());
        crc = linux_crc32c(crc, &5u32.to_le_bytes());
        crc = linux_crc32c(crc, &holds_the_field);
        holds_the_field[0x7C..0x7E].copy_from_slice(&(crc as u16).to_le_bytes());
        assert!(
            !c.verify_inode(2, 5, &holds_the_field),
            "126 bytes hold i_checksum_lo and are still too short"
        );
    }

    use super::*;

    #[test]
    fn disabled_when_feature_off() {
        // crc32c of an empty seed always yields 0; not interesting.
        let c = Checksummer {
            seed: 0,
            enabled: false,
        };
        assert!(c.verify_superblock(&[]));
        assert!(c.verify_inode(2, 0, &[]));
        assert!(c.verify_dir_entry_tail(2, 0, &[0u8; 12]));
        assert!(c.verify_extent_tail(2, 0, &[0u8; 64]));
    }

    #[test]
    fn dir_tail_roundtrip_and_tamper() {
        let c = Checksummer {
            seed: 0xCAFEBABE,
            enabled: true,
        };
        let ino = 42u32;
        let gen = 0xDEADBEEFu32;
        let mut block = vec![0u8; 4096];
        // Plant a fake `ext4_dir_entry_tail` at the last 12 bytes — the spec
        // reserves these and the CRC excludes them entirely.
        let end = block.len();
        block[end - 12..end - 8].copy_from_slice(&0u32.to_le_bytes()); // det_reserved_zero1
        block[end - 8..end - 6].copy_from_slice(&12u16.to_le_bytes()); // det_rec_len
        block[end - 6] = 0; // det_reserved_zero2
        block[end - 5] = 0xDE; // det_reserved_ft
                               // Some plausible directory content bytes (BEFORE the tail).
        block[0..8].copy_from_slice(&[2, 0, 0, 0, 12, 0, 1, 2]);
        block[100] = 0x5A;
        // CRC covers block[..len-12]; tail's last 4 bytes hold the result.
        let mut expected = linux_crc32c(c.seed, &ino.to_le_bytes());
        expected = linux_crc32c(expected, &gen.to_le_bytes());
        expected = linux_crc32c(expected, &block[..end - 12]);
        block[end - 4..end].copy_from_slice(&expected.to_le_bytes());
        assert!(c.verify_dir_entry_tail(ino, gen, &block));

        // Tamper one byte inside the covered region, expect failure.
        block[100] ^= 0xFF;
        assert!(!c.verify_dir_entry_tail(ino, gen, &block));
    }

    #[test]
    fn extent_tail_excludes_only_last_4_bytes() {
        // The extent tail recipe excludes only the final u32 et_checksum,
        // unlike dir_entry_tail which excludes the full 12-byte tail.
        let c = Checksummer {
            seed: 0x12345678,
            enabled: true,
        };
        let mut block = vec![0u8; 1024];
        block[0..12].copy_from_slice(&[0x0A, 0xF3, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0]);
        block[500] = 0xAB;
        let end = block.len();
        let mut expected = linux_crc32c(c.seed, &7u32.to_le_bytes());
        expected = linux_crc32c(expected, &9u32.to_le_bytes());
        expected = linux_crc32c(expected, &block[..end - 4]);
        block[end - 4..end].copy_from_slice(&expected.to_le_bytes());
        assert!(c.verify_extent_tail(7, 9, &block));
    }

    #[test]
    fn patch_extent_tail_is_verify_inverse() {
        let c = Checksummer {
            seed: 0xFEEDFACE,
            enabled: true,
        };
        let mut block = vec![0u8; 4096];
        // Synthetic leaf header + one entry so the body is interesting.
        block[0..12].copy_from_slice(&[0x0A, 0xF3, 1, 0, 0x54, 0x01, 0, 0, 1, 2, 3, 4]);
        block[12..24].copy_from_slice(&[0, 0, 0, 0, 5, 0, 0, 0, 0, 0, 0xE8, 0x03]);
        let patched = c.patch_extent_tail(42, 0xABCDEF01, &mut block);
        assert!(patched);
        assert!(c.verify_extent_tail(42, 0xABCDEF01, &block));
        // Tampering with body invalidates.
        block[200] ^= 0xFF;
        assert!(!c.verify_extent_tail(42, 0xABCDEF01, &block));
    }

    #[test]
    fn patch_extent_tail_disabled_is_noop() {
        let c = Checksummer {
            seed: 0,
            enabled: false,
        };
        let mut block = vec![0u8; 64];
        assert!(!c.patch_extent_tail(1, 1, &mut block));
        assert_eq!(&block[..], &[0u8; 64]);
    }

    #[test]
    fn dir_tail_rejects_too_short_block_when_enabled() {
        let c = Checksummer {
            seed: 0,
            enabled: true,
        };
        // Less than 12 bytes cannot even hold the tail struct.
        assert!(!c.verify_dir_entry_tail(2, 0, &[0u8; 8]));
    }

    #[test]
    fn crc_helpers_are_deterministic() {
        let c = Checksummer {
            seed: 0xDEAD_BEEF,
            enabled: true,
        };
        let a = c.crc(b"hello");
        let b = c.crc(b"hello");
        assert_eq!(a, b);
        let p1 = c.crc_with_prefix(1, b"hello");
        let p2 = c.crc_with_prefix(2, b"hello");
        assert_ne!(p1, p2, "prefix changes hash");
    }

    /// Tests that read a fixture from `test-disks/` (`chore fixtures`).
    mod needs_host {
        use super::*;

        /// Verify our superblock-checksum routine against a real ext4-basic.img
        /// (which has metadata_csum enabled).
        #[test]
        fn verifies_real_superblock() {
            use crate::block_io::FileDevice;

            let path = fs_ext4_test_support::fixture(env!("CARGO_MANIFEST_DIR"), "ext4-basic.img");
            let dev = FileDevice::open(&path).unwrap_or_else(|e| panic!("open {path}: {e}"));
            let sb = Superblock::read(&dev).expect("parse sb");
            let csum = Checksummer::from_superblock(&sb);
            assert!(
                csum.enabled,
                "ext4-basic.img is built with metadata_csum (test-disks/guest-build-images.sh)"
            );
            assert!(
                csum.verify_superblock(&sb.raw),
                "superblock checksum mismatch on {path}"
            );
        }

        /// Verify our BGD checksum against a real image — every group must pass.
        #[test]
        fn verifies_real_bgd() {
            use crate::block_io::{BlockDevice, FileDevice};

            let path = fs_ext4_test_support::fixture(env!("CARGO_MANIFEST_DIR"), "ext4-basic.img");
            let dev = FileDevice::open(&path).unwrap_or_else(|e| panic!("open {path}: {e}"));
            let sb = Superblock::read(&dev).expect("parse sb");
            let csum = Checksummer::from_superblock(&sb);
            assert!(
                csum.enabled,
                "{path} is built with metadata_csum (test-disks/guest-build-images.sh)"
            );
            // Read raw BGT and verify each descriptor.
            let block_size = sb.block_size() as u64;
            let bgt_off = (sb.first_data_block as u64 + 1) * block_size;
            let group_count = sb.block_group_count();
            let total = group_count as usize * sb.desc_size as usize;
            let mut buf = vec![0u8; total];
            dev.read_at(bgt_off, &mut buf).expect("read bgt");
            for i in 0..group_count as usize {
                let off = i * sb.desc_size as usize;
                let raw = &buf[off..off + sb.desc_size as usize];
                assert!(
                    csum.verify_bgd(i as u32, raw, sb.desc_size),
                    "BGD {i} checksum mismatch on {path}"
                );
            }
        }

        /// Verify our inode checksum against a real image — root inode (2) must pass.
        #[test]
        fn verifies_real_inode() {
            use crate::block_io::FileDevice;
            use crate::fs::Filesystem;
            use std::sync::Arc;

            let path = fs_ext4_test_support::fixture(env!("CARGO_MANIFEST_DIR"), "ext4-basic.img");
            let dev = FileDevice::open(&path).unwrap_or_else(|e| panic!("open {path}: {e}"));
            let dev_dyn: Arc<dyn crate::block_io::BlockDevice> = Arc::new(dev);
            let fs = Filesystem::mount(dev_dyn).expect("mount");
            assert!(
                fs.csum.enabled,
                "{path} is built with metadata_csum (test-disks/guest-build-images.sh)"
            );
            // Inode 2 = root dir.
            let (inode, raw) = fs.read_inode_verified(2).expect("read root inode");
            assert!(inode.is_dir());
            assert!(fs.csum.verify_inode(2, inode.generation, &raw));
        }

        /// Verify dir-block tail csum against a real image. Root dir on
        /// ext4-basic.img is a single-block linear directory with a tail.
        #[test]
        fn verifies_real_dir_tail() {
            use crate::block_io::{BlockDevice, FileDevice};
            use crate::dir;
            use crate::extent;
            use crate::fs::Filesystem;
            use std::sync::Arc;

            let path = fs_ext4_test_support::fixture(env!("CARGO_MANIFEST_DIR"), "ext4-basic.img");
            let dev = FileDevice::open(&path).unwrap_or_else(|e| panic!("open {path}: {e}"));
            let dev_dyn: Arc<dyn BlockDevice> = Arc::new(dev);
            let fs = Filesystem::mount(dev_dyn.clone()).expect("mount");
            assert!(
                fs.csum.enabled,
                "{path} is built with metadata_csum (test-disks/guest-build-images.sh)"
            );
            let (root_inode, _raw) = fs.read_inode_verified(2).expect("root inode");
            let bs = fs.sb.block_size();
            let phys = extent::map_logical(&root_inode.block, dev_dyn.as_ref(), bs, 0)
                .expect("map_logical")
                .expect("dir block 0 mapped");
            let mut block = vec![0u8; bs as usize];
            dev_dyn.read_at(phys * bs as u64, &mut block).unwrap();
            assert!(
                dir::has_csum_tail(&block),
                "expected tail on root dir block"
            );
            assert!(
                fs.csum
                    .verify_dir_entry_tail(2, root_inode.generation, &block),
                "dir tail csum mismatch on {path} root dir"
            );
        }

        /// Verify extent-block tail csum against ext4-deep-extents.img: any file
        /// with depth > 0 has off-inode extent index/leaf blocks. We pick the
        /// largest regular file and traverse one internal-node block.
        #[test]
        fn verifies_real_extent_tail() {
            use crate::block_io::{BlockDevice, FileDevice};
            use crate::extent::{self, ExtentHeader, ExtentIdx, EXT4_EXT_NODE_SIZE};
            use crate::fs::Filesystem;
            use std::sync::Arc;

            let path =
                fs_ext4_test_support::fixture(env!("CARGO_MANIFEST_DIR"), "ext4-deep-extents.img");
            let dev = FileDevice::open(&path).unwrap_or_else(|e| panic!("open {path}: {e}"));
            let dev_dyn: Arc<dyn BlockDevice> = Arc::new(dev);
            let fs = Filesystem::mount(dev_dyn.clone()).expect("mount");
            assert!(
                fs.csum.enabled,
                "{path} is built with metadata_csum (test-disks/guest-build-images.sh)"
            );
            // Walk first ~50 inodes looking for one with depth>0.
            let bs = fs.sb.block_size();
            let mut found = None;
            for ino in 11..200u32 {
                let (inode, _raw) = match fs.read_inode_verified(ino) {
                    Ok(x) => x,
                    Err(_) => continue,
                };
                if !inode.is_file() || !inode.has_extents() {
                    continue;
                }
                let header = match ExtentHeader::parse(&inode.block) {
                    Ok(h) => h,
                    Err(_) => continue,
                };
                if header.depth > 0 && header.entries >= 1 {
                    let idx =
                        ExtentIdx::parse(&inode.block[EXT4_EXT_NODE_SIZE..2 * EXT4_EXT_NODE_SIZE])
                            .expect("parse first idx");
                    found = Some((ino, inode.generation, idx.leaf_block));
                    break;
                }
            }
            let (ino, gen, child_block) = found.unwrap_or_else(|| {
                panic!(
                    "no depth>0 inode in the first 200 of {path}: its sparse.bin is built \
                 with a multi-level extent tree (test-disks/guest-build-images.sh)"
                )
            });
            let mut buf = vec![0u8; bs as usize];
            dev_dyn.read_at(child_block * bs as u64, &mut buf).unwrap();
            assert!(
                fs.csum.verify_extent_tail(ino, gen, &buf),
                "extent block csum mismatch (ino={ino} child_block={child_block} on {path})"
            );

            // Also exercise the verified traversal API end-to-end.
            let (inode, _) = fs.read_inode_verified(ino).unwrap();
            let ctx = extent::ExtentVerifyCtx {
                ino,
                generation: gen,
                csum: &fs.csum,
            };
            let _ = extent::lookup_verified(&inode.block, dev_dyn.as_ref(), bs, 0, Some(&ctx))
                .expect("lookup_verified must accept valid extent blocks");
        }
    }
}