fstool 0.1.0

Build disk images and filesystems (ext2/3/4, MBR, GPT) from a directory tree and TOML spec, in the spirit of genext2fs.
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
//! XFS — read-only support.
//!
//! Implements enough of XFS v4/v5 to inspect the volume and stream files
//! out of it: the superblock, inodes with the v3 (CRC) and v2 cores,
//! shortform / block / leaf / node directories, the linear extent list
//! and B-tree extent maps (`BTREE` di_format) for regular files, and both
//! inline and remote symlinks. B-tree-format directories, realtime files,
//! encryption, reverse-mapping btrees, and the journal are out of scope
//! — encountering any of them returns `Error::Unsupported` with a message
//! naming the feature.
//!
//! ## Inode-number arithmetic
//!
//! XFS inode numbers are 64-bit and pack three fields: the AG index, the
//! AG-relative block number, and the slot inside that block.
//!
//! ```text
//!   ag    = ino >> (sb_agblklog + sb_inopblog)
//!   blk   = (ino >> sb_inopblog) & ((1 << sb_agblklog) - 1)
//!   slot  = ino & ((1 << sb_inopblog) - 1)
//! ```
//!
//! The on-disk byte address of an inode is then:
//!
//! ```text
//!   ag*sb_agblocks*sb_blocksize + blk*sb_blocksize + slot*sb_inodesize
//! ```
//!
//! ## Reference
//!
//! - Linux kernel documentation: <https://docs.kernel.org/admin-guide/filesystems/xfs.html>
//! - XFS Filesystem Structure (the "PDF"): <https://mirrors.edge.kernel.org/pub/linux/utils/fs/xfs/docs/xfs_filesystem_structure.pdf>
//!
//! This implementation is written from those documents only — no kernel
//! or xfsprogs source was consulted.

pub mod bmbt;
pub mod dir;
pub mod format;
pub mod inode;
pub mod journal;
pub mod superblock;
pub mod symlink;
pub mod write;
pub mod xattr;

pub use format::{FormatOpts, format};
pub use write::{DeviceKind, EntryMeta, WriteState};

use crate::Result;
use crate::block::BlockDevice;

use self::bmbt::{BmbtLayout, Extent};
use self::dir::DataEntry;
use self::inode::{DiFormat, DinodeCore};
use self::superblock::Superblock;

/// In-memory state of an opened XFS volume. Owns the parsed superblock; all
/// other reads go through the passed-in `BlockDevice`. When the volume
/// was just formatted via [`format()`] (or [`begin_writes`](Xfs::begin_writes)
/// was called after open), the `write_state` field tracks the
/// bump-pointer allocator + INOBT chunks for incremental adds.
pub struct Xfs {
    pub(crate) sb: Superblock,
    pub(crate) write_state: Option<WriteState>,
}

impl Xfs {
    /// Open an XFS volume by reading + validating the superblock at the
    /// start of AG0. Does not walk any other metadata yet.
    pub fn open(dev: &mut dyn BlockDevice) -> Result<Self> {
        if dev.total_size() < 512 {
            return Err(crate::Error::InvalidImage(
                "xfs: device too small to hold a superblock".into(),
            ));
        }
        // The superblock occupies the first sector; we read 512 bytes which
        // covers every field we touch in `Superblock::decode`.
        let mut buf = [0u8; 512];
        dev.read_at(0, &mut buf)?;
        let sb = Superblock::decode(&buf)?;
        // Refuse exotic configurations that would silently break reads.
        if sb.rblocks != 0 {
            return Err(crate::Error::Unsupported(
                "xfs: realtime subvolume not supported".into(),
            ));
        }
        Ok(Self {
            sb,
            write_state: None,
        })
    }

    /// Total bytes the volume claims: `sb_dblocks * sb_blocksize`.
    pub fn total_bytes(&self) -> u64 {
        self.sb.total_bytes()
    }

    /// FS block size in bytes.
    pub fn block_size(&self) -> u32 {
        self.sb.blocksize
    }

    /// Bytes per on-disk inode.
    pub fn inode_size(&self) -> u32 {
        self.sb.inodesize as u32
    }

    /// Number of allocation groups.
    pub fn ag_count(&self) -> u32 {
        self.sb.agcount
    }

    /// Borrow the superblock for diagnostics.
    pub fn superblock(&self) -> &Superblock {
        &self.sb
    }

    // -- inode addressing ------------------------------------------------

    /// Decompose an inode number into (ag, ag-relative block, slot).
    fn split_ino(&self, ino: u64) -> (u64, u64, u64) {
        let inopblog = self.sb.inopblog as u32;
        let agblklog = self.sb.agblklog as u32;
        let slot_mask = (1u64 << inopblog) - 1;
        let blk_mask = (1u64 << agblklog) - 1;
        let slot = ino & slot_mask;
        let blk = (ino >> inopblog) & blk_mask;
        let ag = ino >> (inopblog + agblklog);
        (ag, blk, slot)
    }

    /// Absolute byte offset on the device for inode `ino`.
    fn ino_byte_offset(&self, ino: u64) -> Result<u64> {
        let (ag, blk, slot) = self.split_ino(ino);
        if ag >= self.sb.agcount as u64 {
            return Err(crate::Error::InvalidImage(format!(
                "xfs: inode {ino} references ag {ag} but agcount = {}",
                self.sb.agcount
            )));
        }
        let ag_bytes = ag * (self.sb.agblocks as u64) * (self.sb.blocksize as u64);
        let blk_bytes = blk * (self.sb.blocksize as u64);
        let slot_bytes = slot * (self.sb.inodesize as u64);
        Ok(ag_bytes + blk_bytes + slot_bytes)
    }

    /// Read an inode by number, returning the raw bytes plus the decoded core.
    fn read_inode(&self, dev: &mut dyn BlockDevice, ino: u64) -> Result<(Vec<u8>, DinodeCore)> {
        let off = self.ino_byte_offset(ino)?;
        let mut buf = vec![0u8; self.sb.inodesize as usize];
        dev.read_at(off, &mut buf)?;
        let core = DinodeCore::decode(&buf)?;
        // For v3 inodes the di_ino field should match the address we used.
        if let Some(self_ino) = core.di_ino
            && self_ino != ino
        {
            return Err(crate::Error::InvalidImage(format!(
                "xfs: inode {ino}: di_ino self-reference is {self_ino}"
            )));
        }
        Ok((buf, core))
    }

    // -- directory walk --------------------------------------------------

    /// Resolve an absolute path to an inode number + the decoded inode.
    fn resolve_path(
        &self,
        dev: &mut dyn BlockDevice,
        path: &str,
    ) -> Result<(u64, Vec<u8>, DinodeCore)> {
        let mut cur_ino = self.sb.rootino;
        let (buf, core) = self.read_inode(dev, cur_ino)?;
        // The root inode must be a directory; otherwise the volume is broken.
        if !core.is_dir() {
            return Err(crate::Error::InvalidImage(
                "xfs: root inode is not a directory".into(),
            ));
        }
        let mut cur_buf = buf;
        let mut cur_core = core;
        for part in split_path(path) {
            let dir_entries = self.read_dir_entries(dev, &cur_buf, &cur_core)?;
            let found = dir_entries.iter().find(|e| e.name == part).ok_or_else(|| {
                crate::Error::InvalidArgument(format!("xfs: no such entry {part:?} under {path:?}"))
            })?;
            cur_ino = found.inumber;
            let (b, c) = self.read_inode(dev, cur_ino)?;
            cur_buf = b;
            cur_core = c;
        }
        Ok((cur_ino, cur_buf, cur_core))
    }

    /// Layout descriptor for B-tree / FSB walking.
    fn bmbt_layout(&self) -> BmbtLayout {
        BmbtLayout {
            blocksize: self.sb.blocksize,
            agblocks: self.sb.agblocks,
            agblklog: self.sb.agblklog,
            is_v5: self.sb.is_v5(),
        }
    }

    /// Convert an FSB (filesystem block number) to a device byte offset.
    fn fsb_to_byte(&self, fsb: u64) -> u64 {
        let ag = fsb >> self.sb.agblklog as u32;
        let agblk = fsb & ((1u64 << self.sb.agblklog as u32) - 1);
        ag * (self.sb.agblocks as u64) * (self.sb.blocksize as u64)
            + agblk * (self.sb.blocksize as u64)
    }

    /// Read the extent list for a file/dir inode. Returns the decoded
    /// extents regardless of whether the inode is `EXTENTS` (inline list)
    /// or `BTREE` (walked tree). Other formats are an error.
    fn read_extent_list(
        &self,
        dev: &mut dyn BlockDevice,
        ino_buf: &[u8],
        core: &DinodeCore,
    ) -> Result<Vec<Extent>> {
        let lit = core.literal_area(ino_buf, self.sb.inodesize as usize);
        match core.format {
            DiFormat::Extents => bmbt::decode_extents(lit, core.nextents),
            DiFormat::Btree => {
                let layout = self.bmbt_layout();
                bmbt::walk_btree(dev, &layout, lit)
            }
            other => Err(crate::Error::InvalidArgument(format!(
                "xfs: extent list requested for non-extent inode (format={other:?})"
            ))),
        }
    }

    /// Read every directory data/block referenced by a directory inode's
    /// extent list (block + leaf format directories), parse each one, and
    /// return the concatenated list of entries. Skips the leaf index block
    /// at logical offset >= `XFS_DIR2_LEAF_OFFSET / dirblksize`.
    fn read_extent_dir_entries(
        &self,
        dev: &mut dyn BlockDevice,
        ino_buf: &[u8],
        core: &DinodeCore,
    ) -> Result<Vec<DataEntry>> {
        let extents = self.read_extent_list(dev, ino_buf, core)?;
        // First, read logical block 0 to decide between block- and leaf-
        // format. Block format: a single dir block, contains both data
        // records and a trailing leaf-entry array.
        if extents.is_empty() {
            return Ok(Vec::new());
        }
        let dir_block_size = self.sb.dir_block_size() as u64;
        let fs_blocks_per_dir_block = (dir_block_size / self.sb.blocksize as u64).max(1);
        // Logical address of the leaf block in a leaf-format directory.
        // The kernel uses 32 GiB / dir_block_size; convert to FS-block units
        // since extents are stored in FS-block units.
        let leaf_dir_block_addr_fsblk = dir::XFS_DIR2_LEAF_FIRSTDB_BYTES / self.sb.blocksize as u64;

        // Read the very first block to peek at the magic.
        let first = self.read_dir_block_at_logical(dev, &extents, 0, dir_block_size as usize)?;
        let is_v5 = self.sb.is_v5();
        if dir::is_block_format(&first)? {
            // Block format: a single directory block.
            return dir::decode_block_dir(&first, is_v5);
        }
        // Leaf or node format: walk every distinct directory-block-aligned
        // logical address that some extent covers (capped at the leaf-
        // offset boundary, which separates the data-block address range
        // from the leaf-index / free-index ranges).
        let mut out = Vec::new();
        // Cap is the LESSER of (last covered logical block + 1) and the
        // leaf-block boundary.
        let max_covered = extents
            .iter()
            .map(|e| e.offset + e.blockcount as u64)
            .max()
            .unwrap_or(0);
        let upper = max_covered.min(leaf_dir_block_addr_fsblk);
        let mut lblk = 0u64;
        while lblk < upper {
            // Is `lblk` covered by any extent?
            let covered = extents
                .iter()
                .any(|e| lblk >= e.offset && lblk < e.offset + e.blockcount as u64);
            if covered {
                let block =
                    self.read_dir_block_at_logical(dev, &extents, lblk, dir_block_size as usize)?;
                if block.len() >= 4 {
                    let magic = u32::from_be_bytes(block[0..4].try_into().unwrap());
                    if magic == dir::XFS_DIR3_DATA_MAGIC || magic == dir::XFS_DIR2_DATA_MAGIC {
                        let mut entries = dir::decode_data_block(&block, is_v5)?;
                        out.append(&mut entries);
                    }
                    // Other magics (block / leaf / node / free) are either
                    // skipped (leaf/node/free are pure index) or impossible
                    // here (block-format was handled above).
                }
            }
            lblk += fs_blocks_per_dir_block;
        }
        Ok(out)
    }

    /// Read `dir_block_size` bytes from the directory at logical FS-block
    /// `lblk`, by mapping through the extent list. Returns the assembled
    /// buffer.
    fn read_dir_block_at_logical(
        &self,
        dev: &mut dyn BlockDevice,
        extents: &[Extent],
        lblk: u64,
        dir_block_size: usize,
    ) -> Result<Vec<u8>> {
        let bs = self.sb.blocksize as u64;
        let fs_blocks_per_dir_block = (dir_block_size as u64 / bs).max(1);
        let mut out = vec![0u8; dir_block_size];
        for i in 0..fs_blocks_per_dir_block {
            let target = lblk + i;
            let ext = extents
                .iter()
                .find(|e| target >= e.offset && target < e.offset + e.blockcount as u64)
                .ok_or_else(|| {
                    crate::Error::InvalidImage(format!(
                        "xfs: dir logical block {target} not covered by extent list"
                    ))
                })?;
            let phys_fsb = ext.startblock + (target - ext.offset);
            let phys_byte = self.fsb_to_byte(phys_fsb);
            let off = (i * bs) as usize;
            dev.read_at(phys_byte, &mut out[off..off + bs as usize])?;
        }
        Ok(out)
    }

    /// Read a directory's entries given the inode's bytes + core. Handles
    /// shortform (local), block, leaf, and node format directories.
    /// Returns `Error::Unsupported` for the `BTREE` di_format.
    fn read_dir_entries(
        &self,
        dev: &mut dyn BlockDevice,
        ino_buf: &[u8],
        core: &DinodeCore,
    ) -> Result<Vec<DataEntry>> {
        if !core.is_dir() {
            return Err(crate::Error::InvalidArgument(
                "xfs: target is not a directory".into(),
            ));
        }
        match core.format {
            DiFormat::Local => {
                let lit = core.literal_area(ino_buf, self.sb.inodesize as usize);
                let has_ftype = core.version >= 3;
                let (_parent, entries) = dir::decode_shortform(lit, has_ftype)?;
                // Promote ShortformEntry → DataEntry (identical fields).
                Ok(entries
                    .into_iter()
                    .map(|e| DataEntry {
                        name: e.name,
                        inumber: e.inumber,
                        ftype: e.ftype,
                    })
                    .collect())
            }
            DiFormat::Extents => self.read_extent_dir_entries(dev, ino_buf, core),
            // BTREE-format directories — the inode-fork holds a bmbt root
            // (same shape as for files); leaves still contain XDD3/XDB3
            // data blocks plus a LEAFN / NODE index above the
            // XFS_DIR2_LEAF_OFFSET boundary. `read_extent_dir_entries`
            // walks the extent list and scans every data-block-aligned
            // logical address it covers, so it works unmodified once
            // `read_extent_list` returns the bmbt-walked extents.
            DiFormat::Btree => self.read_extent_dir_entries(dev, ino_buf, core),
            DiFormat::Dev => Err(crate::Error::InvalidImage(
                "xfs: directory inode has di_format=dev".into(),
            )),
            DiFormat::Unknown(b) => Err(crate::Error::Unsupported(format!(
                "xfs: directory inode has unknown di_format {b}"
            ))),
        }
    }

    /// List the entries of a directory by absolute path. `/` resolves to
    /// the root directory.
    pub fn list_path(
        &self,
        dev: &mut dyn BlockDevice,
        path: &str,
    ) -> Result<Vec<crate::fs::DirEntry>> {
        let (_ino, buf, core) = self.resolve_path(dev, path)?;
        let entries = self.read_dir_entries(dev, &buf, &core)?;
        Ok(dir::data_entries_to_generic(&entries))
    }

    /// Read the target of a symlink at an absolute path. Supports both
    /// inline (local) and remote (extent-list) symlink targets.
    pub fn read_symlink(&self, dev: &mut dyn BlockDevice, path: &str) -> Result<String> {
        let (_ino, buf, core) = self.resolve_path(dev, path)?;
        if !core.is_symlink() {
            return Err(crate::Error::InvalidArgument(format!(
                "xfs: {path:?} is not a symlink"
            )));
        }
        match core.format {
            DiFormat::Local => {
                let lit = core.literal_area(&buf, self.sb.inodesize as usize);
                symlink::decode_local(lit, core.size)
            }
            DiFormat::Extents => {
                let extents = self.read_extent_list(dev, &buf, &core)?;
                let layout = self.bmbt_layout();
                symlink::decode_remote(dev, &layout, &extents, core.size)
            }
            DiFormat::Btree => Err(crate::Error::Unsupported(
                "xfs: B-tree (di_format=BTREE) symlinks not implemented".into(),
            )),
            DiFormat::Dev => Err(crate::Error::InvalidArgument(
                "xfs: symlink inode with di_format=dev".into(),
            )),
            DiFormat::Unknown(b) => Err(crate::Error::Unsupported(format!(
                "xfs: symlink inode with unknown di_format {b}"
            ))),
        }
    }

    /// Open a regular file by absolute path for streaming reads.
    pub fn open_file_reader<'a>(
        &self,
        dev: &'a mut dyn BlockDevice,
        path: &str,
    ) -> Result<XfsFileReader<'a>> {
        let (_ino, buf, core) = self.resolve_path(dev, path)?;
        if !core.is_reg() {
            return Err(crate::Error::InvalidArgument(format!(
                "xfs: {path:?} is not a regular file"
            )));
        }
        match core.format {
            DiFormat::Extents | DiFormat::Btree => {
                let extents = self.read_extent_list(dev, &buf, &core)?;
                for e in &extents {
                    if e.unwritten {
                        return Err(crate::Error::Unsupported(
                            "xfs: unwritten extents not supported in read path".into(),
                        ));
                    }
                }
                let layout = self.bmbt_layout();
                Ok(XfsFileReader {
                    dev,
                    extents,
                    blocksize: self.sb.blocksize as u64,
                    agblocks: self.sb.agblocks as u64,
                    agblklog: self.sb.agblklog,
                    size: core.size,
                    pos: 0,
                    inline: None,
                    _layout: layout,
                })
            }
            DiFormat::Local => {
                // Tiny files stored entirely in the inode literal area.
                // The file's bytes are the first `size` bytes of the literal.
                let lit = core.literal_area(&buf, self.sb.inodesize as usize);
                if (core.size as usize) > lit.len() {
                    return Err(crate::Error::InvalidImage(format!(
                        "xfs: local-format file claims size {} > literal area {}",
                        core.size,
                        lit.len()
                    )));
                }
                let data = lit[..core.size as usize].to_vec();
                Ok(XfsFileReader {
                    dev,
                    extents: Vec::new(),
                    blocksize: self.sb.blocksize as u64,
                    agblocks: self.sb.agblocks as u64,
                    agblklog: self.sb.agblklog,
                    size: core.size,
                    pos: 0,
                    inline: Some(data),
                    _layout: self.bmbt_layout(),
                })
            }
            DiFormat::Dev => Err(crate::Error::InvalidArgument(
                "xfs: device-special inode has no file data".into(),
            )),
            DiFormat::Unknown(b) => Err(crate::Error::Unsupported(format!(
                "xfs: file inode has unknown di_format {b}"
            ))),
        }
    }
}

/// Streaming reader for an XFS regular file. Walks the inode's extent list
/// on demand, reading at most one `read()`-buffer worth at a time.
pub struct XfsFileReader<'a> {
    dev: &'a mut dyn BlockDevice,
    extents: Vec<Extent>,
    blocksize: u64,
    /// AG width in blocks (for FSB → byte translation).
    agblocks: u64,
    /// log2 of the *power-of-two AG stride* used to pack FSBs. Comes from
    /// `sb_agblklog`; the address is `(ag << agblklog) | agblk`.
    agblklog: u8,
    size: u64,
    /// Logical byte position of the next byte to return.
    pos: u64,
    /// Set when the file was tiny enough to live entirely in the inode's
    /// literal area (`DiFormat::Local`). When present, `extents` is empty
    /// and reads come from this buffer.
    inline: Option<Vec<u8>>,
    /// Layout (kept for symmetry with other readers; not used by the hot
    /// path).
    _layout: BmbtLayout,
}

impl<'a> XfsFileReader<'a> {
    /// FSB → device byte address. Identical math to [`Xfs::fsb_to_byte`].
    fn fsb_to_byte(&self, fsb: u64) -> u64 {
        let ag = fsb >> self.agblklog as u32;
        let agblk = fsb & ((1u64 << self.agblklog as u32) - 1);
        ag * self.agblocks * self.blocksize + agblk * self.blocksize
    }
}

impl<'a> std::io::Read for XfsFileReader<'a> {
    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
        if self.pos >= self.size || buf.is_empty() {
            return Ok(0);
        }
        let want = buf.len() as u64;
        let avail = self.size - self.pos;
        let n = want.min(avail) as usize;

        if let Some(inline) = &self.inline {
            let start = self.pos as usize;
            let end = start + n;
            buf[..n].copy_from_slice(&inline[start..end]);
            self.pos += n as u64;
            return Ok(n);
        }

        // Find the extent covering `pos`. Logical units are FS blocks.
        let pos_blk = self.pos / self.blocksize;
        let pos_off = self.pos % self.blocksize;
        let extent = self
            .extents
            .iter()
            .find(|e| pos_blk >= e.offset && pos_blk < e.offset + e.blockcount as u64);
        let n_done = match extent {
            Some(e) => {
                // Read across this extent until the next extent boundary
                // or the user's buffer is full.
                let extent_blocks_left = e.offset + e.blockcount as u64 - pos_blk;
                let extent_bytes_left = extent_blocks_left * self.blocksize - pos_off;
                let to_read = (n as u64).min(extent_bytes_left) as usize;
                let phys_fsb = e.startblock + (pos_blk - e.offset);
                let phys_byte = self.fsb_to_byte(phys_fsb) + pos_off;
                self.dev
                    .read_at(phys_byte, &mut buf[..to_read])
                    .map_err(std::io::Error::other)?;
                to_read
            }
            None => {
                // Hole — synthesise zeros up to the next extent or EOF.
                let next_extent_block = self
                    .extents
                    .iter()
                    .filter(|e| e.offset > pos_blk)
                    .map(|e| e.offset)
                    .min();
                let next_byte = next_extent_block
                    .map(|b| b * self.blocksize)
                    .unwrap_or(self.size);
                let hole_bytes = next_byte.saturating_sub(self.pos);
                let to_zero = (n as u64).min(hole_bytes) as usize;
                buf[..to_zero].fill(0);
                to_zero
            }
        };
        // Defensive: don't loop forever if both branches yielded zero.
        if n_done == 0 {
            return Ok(0);
        }
        self.pos += n_done as u64;
        Ok(n_done)
    }
}

/// Probe for the XFS superblock magic `"XFSB"` at offset 0 of LBA 0.
pub fn probe(dev: &mut dyn BlockDevice) -> Result<bool> {
    if dev.total_size() < 512 {
        return Ok(false);
    }
    let mut head = [0u8; 4];
    dev.read_at(0, &mut head)?;
    Ok(&head == b"XFSB")
}

/// Split a `/`-rooted path into non-empty components. Treats `/`, `""`,
/// and `.` as "the root" (empty vec). Multiple slashes are collapsed.
fn split_path(path: &str) -> Vec<&str> {
    path.split('/')
        .filter(|p| !p.is_empty() && *p != ".")
        .collect()
}

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

    /// Build a minimal XFS image to drive the reader through realistic
    /// addressing math. Layout: 4 KiB blocks, 4 AGs of 8 blocks each, 256-byte
    /// inodes, 16 inodes per block. Total 128 KiB. The image only has a valid
    /// superblock at offset 0; deeper structures (AG headers, inode bitmaps)
    /// are zero, so `open` succeeds but `list_path("/")` will fail because the
    /// root-inode bytes are zero (no IN magic). That's fine — these tests
    /// only exercise the addressing math.
    fn minimal_image() -> MemoryBackend {
        let blocksize = 4096u32;
        let agblocks = 8u32;
        let agcount = 4u32;
        let inodesize = 256u16;
        let inopblock = (blocksize as u16) / inodesize;
        let dblocks = (agblocks as u64) * (agcount as u64);
        let rootino = 128u64;
        let buf = superblock::synth_sb_for_tests(
            blocksize,
            dblocks,
            agblocks,
            agcount,
            inodesize,
            inopblock,
            rootino,
            superblock::XFS_SB_VERSION_5,
        );
        let total = dblocks * (blocksize as u64);
        let mut dev = MemoryBackend::new(total);
        dev.write_at(0, &buf).unwrap();
        dev
    }

    #[test]
    fn open_reads_superblock() {
        let mut dev = minimal_image();
        let xfs = Xfs::open(&mut dev).unwrap();
        assert_eq!(xfs.block_size(), 4096);
        assert_eq!(xfs.inode_size(), 256);
        assert_eq!(xfs.ag_count(), 4);
        assert_eq!(xfs.total_bytes(), 32 * 4096);
    }

    #[test]
    fn probe_returns_true_for_xfs() {
        let mut dev = minimal_image();
        assert!(probe(&mut dev).unwrap());
    }

    #[test]
    fn probe_returns_false_for_garbage() {
        let mut dev = MemoryBackend::new(4096);
        assert!(!probe(&mut dev).unwrap());
    }

    #[test]
    fn ino_split_matches_manual_math() {
        let mut dev = minimal_image();
        let xfs = Xfs::open(&mut dev).unwrap();
        // 16 inodes per block, agblocks=8 ⇒ inopblog=4, agblklog=3.
        assert_eq!(xfs.sb.inopblog, 4);
        assert_eq!(xfs.sb.agblklog, 3);
        // Inode 128 = 0b1000_0000:
        //   slot  = 128 & 0xf  = 0
        //   blk   = (128>>4) & 0x7 = 0
        //   ag    = 128 >> 7   = 1
        let (ag, blk, slot) = xfs.split_ino(128);
        assert_eq!((ag, blk, slot), (1, 0, 0));
        // Inode 0: everything zero.
        let (ag, blk, slot) = xfs.split_ino(0);
        assert_eq!((ag, blk, slot), (0, 0, 0));
        // Inode (ag=2, blk=3, slot=5) = 2*128 + 3*16 + 5 = 256 + 48 + 5 = 309.
        let (ag, blk, slot) = xfs.split_ino(309);
        assert_eq!((ag, blk, slot), (2, 3, 5));
    }

    #[test]
    fn ino_byte_offset_rejects_out_of_range_ag() {
        let mut dev = minimal_image();
        let xfs = Xfs::open(&mut dev).unwrap();
        // ag=4 is one past the end (agcount=4 ⇒ valid 0..3).
        // 4 * 128 = 512 (since agblklog+inopblog = 7).
        let bad_ino = 4u64 * 128;
        assert!(matches!(
            xfs.ino_byte_offset(bad_ino),
            Err(crate::Error::InvalidImage(_))
        ));
    }

    #[test]
    fn ino_byte_offset_arithmetic() {
        let mut dev = minimal_image();
        let xfs = Xfs::open(&mut dev).unwrap();
        // Inode 128 = ag=1, blk=0, slot=0.
        // Byte = 1 * 8 * 4096 + 0 + 0 = 32768.
        let off = xfs.ino_byte_offset(128).unwrap();
        assert_eq!(off, 8 * 4096);
        // Inode 309 = ag=2, blk=3, slot=5.
        // Byte = 2*8*4096 + 3*4096 + 5*256
        //      = 65536 + 12288 + 1280 = 79104.
        let off = xfs.ino_byte_offset(309).unwrap();
        assert_eq!(off, 2 * 8 * 4096 + 3 * 4096 + 5 * 256);
    }

    #[test]
    fn split_path_handles_edge_cases() {
        assert!(split_path("/").is_empty());
        assert!(split_path("").is_empty());
        assert!(split_path("/.").is_empty());
        assert_eq!(split_path("/a/b"), vec!["a", "b"]);
        assert_eq!(split_path("a//b///c"), vec!["a", "b", "c"]);
    }

    /// A handcrafted v3 inode + a shortform directory pointing at one entry,
    /// then verify the full `list_path("/")` plumbing.
    #[test]
    fn list_root_shortform() {
        // Use the synthetic superblock from `minimal_image`, then carve a
        // root inode at the address `split_ino(rootino)` yields.
        let mut dev = minimal_image();
        let xfs = Xfs::open(&mut dev).unwrap();
        let rootino = xfs.sb.rootino;
        let off = xfs.ino_byte_offset(rootino).unwrap();
        let mut ino_buf = vec![0u8; 256];
        ino_buf[0..2].copy_from_slice(&inode::XFS_DINODE_MAGIC.to_be_bytes());
        ino_buf[2..4].copy_from_slice(&(inode::S_IFDIR | 0o755).to_be_bytes());
        ino_buf[4] = 3; // v3
        ino_buf[5] = 1; // local
        ino_buf[16..20].copy_from_slice(&2u32.to_be_bytes()); // nlink
        ino_buf[152..160].copy_from_slice(&rootino.to_be_bytes()); // di_ino
        // Literal area starts at 176 — write the shortform header + entries.
        let lit_off = 176;
        ino_buf[lit_off] = 1; // count
        ino_buf[lit_off + 1] = 0; // i8count
        ino_buf[lit_off + 2..lit_off + 6].copy_from_slice(&(rootino as u32).to_be_bytes());
        // One entry: name "hi" → ino 200, ftype=REG.
        let entry_off = lit_off + 6;
        ino_buf[entry_off] = 2; // namelen
        ino_buf[entry_off + 1] = 0;
        ino_buf[entry_off + 2] = 0; // dir-offset placeholder
        ino_buf[entry_off + 3..entry_off + 5].copy_from_slice(b"hi");
        ino_buf[entry_off + 5] = dir::XFS_DIR3_FT_REG_FILE;
        ino_buf[entry_off + 6..entry_off + 10].copy_from_slice(&200u32.to_be_bytes());
        dev.write_at(off, &ino_buf).unwrap();

        // Re-open and list.
        let xfs = Xfs::open(&mut dev).unwrap();
        let entries = xfs.list_path(&mut dev, "/").unwrap();
        assert_eq!(entries.len(), 1);
        assert_eq!(entries[0].name, "hi");
        assert_eq!(entries[0].inode, 200);
        assert_eq!(entries[0].kind, crate::fs::EntryKind::Regular);
    }

    /// Build the same minimal image as `list_root_shortform`, but route the
    /// shortform entry "lnk" → ino 200, then carve inode 200 as an inline
    /// symlink with target "/etc/hostname". Verify `read_symlink` returns
    /// that target.
    #[test]
    fn read_inline_symlink_end_to_end() {
        let mut dev = minimal_image();
        let xfs = Xfs::open(&mut dev).unwrap();
        let rootino = xfs.sb.rootino;

        // Carve the root dir inode as before but with one entry pointing at
        // ino 200 (ftype = SYMLINK).
        let root_off = xfs.ino_byte_offset(rootino).unwrap();
        let mut root_buf = vec![0u8; 256];
        root_buf[0..2].copy_from_slice(&inode::XFS_DINODE_MAGIC.to_be_bytes());
        root_buf[2..4].copy_from_slice(&(inode::S_IFDIR | 0o755).to_be_bytes());
        root_buf[4] = 3; // v3
        root_buf[5] = 1; // local
        root_buf[16..20].copy_from_slice(&2u32.to_be_bytes()); // nlink
        root_buf[152..160].copy_from_slice(&rootino.to_be_bytes()); // di_ino
        let lit_off = 176;
        root_buf[lit_off] = 1; // count
        root_buf[lit_off + 1] = 0; // i8count
        root_buf[lit_off + 2..lit_off + 6].copy_from_slice(&(rootino as u32).to_be_bytes());
        let e = lit_off + 6;
        root_buf[e] = 3; // namelen "lnk"
        root_buf[e + 1] = 0;
        root_buf[e + 2] = 0;
        root_buf[e + 3..e + 6].copy_from_slice(b"lnk");
        root_buf[e + 6] = dir::XFS_DIR3_FT_SYMLINK;
        root_buf[e + 7..e + 11].copy_from_slice(&200u32.to_be_bytes());
        dev.write_at(root_off, &root_buf).unwrap();

        // Carve inode 200 as an inline symlink. Inode 200 in our scheme:
        //   inopblog=4, agblklog=3 ⇒ ag=200>>7=1, blk=(200>>4)&7=4, slot=200&15=8.
        //   byte = 1*8*4096 + 4*4096 + 8*256 = 32768 + 16384 + 2048 = 51200.
        let off200 = xfs.ino_byte_offset(200).unwrap();
        let mut buf = vec![0u8; 256];
        buf[0..2].copy_from_slice(&inode::XFS_DINODE_MAGIC.to_be_bytes());
        buf[2..4].copy_from_slice(&(inode::S_IFLNK | 0o777).to_be_bytes());
        buf[4] = 3; // v3
        buf[5] = 1; // local
        buf[16..20].copy_from_slice(&1u32.to_be_bytes()); // nlink
        let target = "/etc/hostname";
        buf[56..64].copy_from_slice(&(target.len() as u64).to_be_bytes());
        buf[152..160].copy_from_slice(&200u64.to_be_bytes()); // di_ino
        let lit = 176;
        buf[lit..lit + target.len()].copy_from_slice(target.as_bytes());
        dev.write_at(off200, &buf).unwrap();

        let xfs = Xfs::open(&mut dev).unwrap();
        let got = xfs.read_symlink(&mut dev, "/lnk").unwrap();
        assert_eq!(got, target);
    }
}