Skip to main content

xfs/
superblock.rs

1//! XFS superblock (`xfs_dsb`) parse and geometry.
2//!
3//! One superblock sits at **offset 0** of every allocation group (AG 0 primary;
4//! secondaries are backups). Field offsets follow the kernel on-disk struct
5//! `struct xfs_dsb` in `fs/xfs/libxfs/xfs_format.h`; `XFSLABEL_MAX = 12`.
6
7use crate::bytes::{be_u16, be_u32, be_u64, u8_at};
8use crate::crc::{crc_status, SB_CRC_OFF};
9use crate::error::XfsError;
10use crate::inode::Inode;
11
12/// The XFS superblock magic number, ASCII `"XFSB"` at byte 0.
13pub const XFS_SB_MAGIC: u32 = 0x5846_5342;
14
15/// Minimum bytes required to parse every field this reader extracts
16/// (through `sb_features_incompat` at offset 216, +4 = 220).
17const SB_MIN_LEN: usize = 220;
18
19/// `XFS_SB_VERSION2_FTYPE` — the v4 `sb_features2` bit that turns on the
20/// directory-entry `ftype` field.
21const XFS_SB_VERSION2_FTYPE: u32 = 0x0000_0200;
22
23/// `XFS_SB_FEAT_INCOMPAT_FTYPE` — the v5 `sb_features_incompat` bit for the same
24/// per-dirent `ftype` field.
25const XFS_SB_FEAT_INCOMPAT_FTYPE: u32 = 0x0000_0001;
26
27/// Parsed XFS superblock — geometry and the log2 shift fields the inode-number
28/// decode (P1) needs.
29///
30/// This carries the subset of `xfs_dsb` the reader currently uses; it is
31/// `#[non_exhaustive]` so later phases add fields without a breaking change.
32#[derive(Debug, Clone, PartialEq, Eq)]
33#[non_exhaustive]
34pub struct Superblock {
35    /// `sb_magicnum` (offset 0) — validated to equal [`XFS_SB_MAGIC`].
36    pub magic: u32,
37    /// `sb_blocksize` (offset 4) — logical block size in bytes.
38    pub blocksize: u32,
39    /// `sb_rootino` (offset 56) — root inode number.
40    pub rootino: u64,
41    /// `sb_agblocks` (offset 84) — blocks per allocation group.
42    pub agblocks: u32,
43    /// `sb_agcount` (offset 88) — number of allocation groups.
44    pub agcount: u32,
45    /// `sb_versionnum` (offset 100) — low nibble = format version (4 vs 5).
46    pub versionnum: u16,
47    /// `sb_inodesize` (offset 104) — inode size in bytes.
48    pub inodesize: u16,
49    /// `sb_inopblock` (offset 106) — inodes per block.
50    pub inopblock: u16,
51    /// `sb_blocklog` (offset 120) — log2 of `blocksize`.
52    pub blocklog: u8,
53    /// `sb_inodelog` (offset 122) — log2 of `inodesize`.
54    pub inodelog: u8,
55    /// `sb_inopblog` (offset 123) — log2 of `inopblock`.
56    pub inopblog: u8,
57    /// `sb_agblklog` (offset 124) — log2 of `agblocks` (rounded up).
58    pub agblklog: u8,
59    /// `sb_features2` (offset 200) — v4 extended feature flags; the FTYPE bit
60    /// (`0x200`) here says v4 directory entries carry the trailing `ftype` byte.
61    pub features2: u32,
62    /// `sb_features_incompat` (offset 216) — v5 incompatible feature flags; the
63    /// FTYPE bit (`0x1`) here is the v5 equivalent of the `features2` FTYPE bit.
64    pub features_incompat: u32,
65    /// The v5 CRC32c status of the superblock sector: `Some(true)` if `sb_crc`
66    /// (offset 224) verifies over the whole sector, `Some(false)` if it does not
67    /// (corrupt/tampered), or `None` on a v4 filesystem (no CRC). **Non-fatal**:
68    /// a bad CRC does not fail the parse — the `-forensic` layer turns it into a
69    /// Finding. Computed only when [`Self::parse`] receives the full sector; a
70    /// short buffer (< sector) verifies as `Some(false)`.
71    pub crc_valid: Option<bool>,
72}
73
74impl Superblock {
75    /// Parse a superblock from the start of `data`.
76    ///
77    /// # Errors
78    ///
79    /// - [`XfsError::Truncated`] if `data` is shorter than the fields read.
80    /// - [`XfsError::BadMagic`] if byte 0 is not `XFSB` — the four offending
81    ///   bytes are carried in the error.
82    pub fn parse(data: &[u8]) -> Result<Self, XfsError> {
83        // Validate magic before length so a wrong-image identity error names the
84        // offending bytes even on a short buffer (fail loud with the value).
85        let bytes = [
86            u8_at(data, 0),
87            u8_at(data, 1),
88            u8_at(data, 2),
89            u8_at(data, 3),
90        ];
91        let magic = u32::from_be_bytes(bytes);
92        if magic != XFS_SB_MAGIC {
93            return Err(XfsError::BadMagic {
94                found: magic,
95                bytes,
96            });
97        }
98
99        // All parsed fields lie within the first SB_MIN_LEN bytes; range-check
100        // once so the bounds-checked readers below never mask a short image.
101        if data.len() < SB_MIN_LEN {
102            return Err(XfsError::Truncated {
103                structure: "superblock",
104                need: SB_MIN_LEN,
105                have: data.len(),
106            });
107        }
108
109        // Offsets from `struct xfs_dsb` (fs/xfs/libxfs/xfs_format.h),
110        // XFSLABEL_MAX = 12.
111        let versionnum = be_u16(data, 100);
112        // v5 iff the low nibble of sb_versionnum is 5. The CRC covers the whole
113        // sector `data`; on v4 there is no CRC field so the status is `None`.
114        let is_v5 = versionnum & 0x000f == 5;
115        let crc_valid = crc_status(is_v5, data, SB_CRC_OFF);
116        Ok(Self {
117            magic,
118            blocksize: be_u32(data, 4),
119            rootino: be_u64(data, 56),
120            agblocks: be_u32(data, 84),
121            agcount: be_u32(data, 88),
122            versionnum,
123            inodesize: be_u16(data, 104),
124            inopblock: be_u16(data, 106),
125            blocklog: u8_at(data, 120),
126            inodelog: u8_at(data, 122),
127            inopblog: u8_at(data, 123),
128            agblklog: u8_at(data, 124),
129            features2: be_u32(data, 200),
130            features_incompat: be_u32(data, 216),
131            crc_valid,
132        })
133    }
134
135    /// True if the filesystem's `ftype` feature is enabled — i.e. every
136    /// directory entry (short-form and block) carries a trailing `ftype` byte.
137    ///
138    /// The bit lives in a different field per format: v5 uses
139    /// `sb_features_incompat & XFS_SB_FEAT_INCOMPAT_FTYPE`; v4 uses
140    /// `sb_features2 & XFS_SB_VERSION2_FTYPE`. Modern `mkfs.xfs` enables it by
141    /// default even on v4, so a directory reader MUST branch on this feature bit
142    /// rather than on the v4/v5 version (the classic off-by-one source).
143    #[must_use]
144    pub fn has_ftype(&self) -> bool {
145        if self.is_v5() {
146            self.features_incompat & XFS_SB_FEAT_INCOMPAT_FTYPE != 0
147        } else {
148            self.features2 & XFS_SB_VERSION2_FTYPE != 0
149        }
150    }
151
152    /// The on-disk format version: `4` (legacy) or `5` (self-describing/CRC),
153    /// taken from the low nibble of `sb_versionnum`.
154    #[must_use]
155    pub fn version(&self) -> u8 {
156        (self.versionnum & 0x000f) as u8
157    }
158
159    /// True for a v5 (CRC / self-describing metadata) filesystem.
160    #[must_use]
161    pub fn is_v5(&self) -> bool {
162        self.version() == 5
163    }
164
165    /// Decode an inode number into its allocation-group location and absolute
166    /// byte position — the exact split `xfs_db convert` performs.
167    ///
168    /// The math (from the XFS on-disk format, using the superblock's log2 shift
169    /// fields):
170    ///
171    /// ```text
172    /// shift   = agblklog + inopblog          (bits held by agino)
173    /// agno    = ino >> shift
174    /// agino   = ino & ((1 << shift) - 1)
175    /// agblock = agino >> inopblog
176    /// offset  = agino & ((1 << inopblog) - 1)
177    /// fsblock = agno * agblocks + agblock
178    /// byte    = fsblock * blocksize + offset * inodesize
179    /// ```
180    ///
181    /// Panic-free: every shift is masked to `< 64` and every multiply is
182    /// saturating, so a hostile inode number or absurd geometry yields a
183    /// clamped location rather than a panic or overflow (the Paranoid
184    /// Gatekeeper standard). It never fails, so it returns the location
185    /// directly rather than a `Result`.
186    #[must_use]
187    pub fn inode_to_location(&self, ino: u64) -> InodeLocation {
188        let inopblog = u32::from(self.inopblog);
189        let agino_bits = u32::from(self.agblklog) + inopblog;
190
191        // agno takes the high bits, agino the low `agino_bits`. A shift >= 64
192        // (malformed geometry) means agino holds the whole value and agno is 0.
193        let agno = shr(ino, agino_bits);
194        let agino = ino & low_mask(agino_bits);
195
196        // Split agino into (agblock, offset) on the inopblog boundary.
197        let agblock = shr(agino, inopblog);
198        let offset = agino & low_mask(inopblog);
199
200        // fsblock = agno * agblocks + agblock; saturate so absurd geometry can
201        // never overflow (a hostile ino must yield a clamped value, not UB).
202        let fsblock = agno
203            .saturating_mul(u64::from(self.agblocks))
204            .saturating_add(agblock);
205
206        // byte = fsblock * blocksize + offset * inodesize (saturating).
207        let byte_offset = fsblock
208            .saturating_mul(u64::from(self.blocksize))
209            .saturating_add(offset.saturating_mul(u64::from(self.inodesize)));
210
211        InodeLocation {
212            agno,
213            agino,
214            agblock,
215            offset,
216            fsblock,
217            byte_offset,
218        }
219    }
220
221    /// Read and parse the inode `ino` from a whole-image byte buffer.
222    ///
223    /// Locates the inode via [`Self::inode_to_location`], slices exactly
224    /// `sb_inodesize` bytes at its byte offset, and parses the core with
225    /// [`Inode::parse`]. This is the convenience path the reader exposes on top
226    /// of the raw [`Inode::parse`] (which takes the already-sliced bytes).
227    ///
228    /// # Errors
229    ///
230    /// - [`XfsError::Truncated`] if the located byte window lies wholly or
231    ///   partly past the end of `image` (a hostile inode number, or a truncated
232    ///   image) — never a panic.
233    /// - Any error from [`Inode::parse`] (bad magic, short core).
234    pub fn read_inode(&self, image: &[u8], ino: u64) -> Result<Inode, XfsError> {
235        let loc = self.inode_to_location(ino);
236        let start = usize::try_from(loc.byte_offset).unwrap_or(usize::MAX);
237        let size = usize::from(self.inodesize);
238        let end = start.saturating_add(size);
239        let slice = image.get(start..end).ok_or(XfsError::Truncated {
240            structure: "inode (image slice)",
241            need: end,
242            have: image.len(),
243        })?;
244        Inode::parse(slice)
245    }
246}
247
248/// Right-shift that yields `0` when `bits >= 64` (rather than panicking on an
249/// out-of-range shift — a malformed superblock can carry shift fields >= 64).
250#[inline]
251fn shr(value: u64, bits: u32) -> u64 {
252    value.checked_shr(bits).unwrap_or(0)
253}
254
255/// A mask of the low `bits` bits: `(1 << bits) - 1`, saturating to all-ones
256/// when `bits >= 64` so the mask never overflows.
257#[inline]
258fn low_mask(bits: u32) -> u64 {
259    if bits >= 64 {
260        u64::MAX
261    } else {
262        (1u64 << bits) - 1
263    }
264}
265
266/// The decoded location of an inode: its allocation group, in-AG coordinates,
267/// absolute filesystem block, and absolute byte position in the image.
268///
269/// Produced by [`Superblock::inode_to_location`]; every field mirrors the
270/// corresponding `xfs_db convert inode N <field>` output.
271#[derive(Debug, Clone, Copy, PartialEq, Eq)]
272pub struct InodeLocation {
273    /// Allocation-group number (`ino >> (agblklog + inopblog)`).
274    pub agno: u64,
275    /// AG-relative inode number (`ino & ((1 << (agblklog + inopblog)) - 1)`).
276    pub agino: u64,
277    /// AG-relative block holding the inode (`agino >> inopblog`).
278    pub agblock: u64,
279    /// Inode slot within its block (`agino & ((1 << inopblog) - 1)`).
280    pub offset: u64,
281    /// Absolute filesystem block (`agno * agblocks + agblock`).
282    pub fsblock: u64,
283    /// Absolute byte position in the image
284    /// (`fsblock * blocksize + offset * inodesize`).
285    pub byte_offset: u64,
286}