Skip to main content

zfs_core/
dnode.rs

1//! `dnode_phys_t` — the on-disk DMU object metadata (512-byte base).
2//!
3//! A dnode describes one DMU object: its type, the shape of its block tree
4//! (`dn_nlevels` levels of indirection, `dn_nblkptr` top-level pointers, a data
5//! block size), and a bonus buffer carrying object-specific metadata (a
6//! `dsl_dataset_phys_t`, a znode/SA registry, …).
7//!
8//! # On-disk layout (`dnode_phys_t`, 512-byte base — verified against `dnode.h`)
9//!
10//! | offset | field              | size |
11//! |--------|--------------------|------|
12//! | 0      | `dn_type`          | 1    |
13//! | 1      | `dn_indblkshift`   | 1    |
14//! | 2      | `dn_nlevels`       | 1    |
15//! | 3      | `dn_nblkptr`       | 1    |
16//! | 4      | `dn_bonustype`     | 1    |
17//! | 5      | `dn_checksum`      | 1    |
18//! | 6      | `dn_compress`      | 1    |
19//! | 7      | `dn_flags`         | 1    |
20//! | 8      | `dn_datablkszsec`  | 2    |
21//! | 10     | `dn_bonuslen`      | 2    |
22//! | 12     | `dn_extra_slots`   | 1    |
23//! | 13     | `dn_pad2[3]`       | 3    |
24//! | 16     | `dn_maxblkid`      | 8    |
25//! | 24     | `dn_used`          | 8    |
26//! | 32     | `dn_pad3[4]`       | 32   |
27//! | 64     | `dn_blkptr[]`      | 128× `dn_nblkptr` |
28//! | …      | `dn_bonus[]` / `dn_spill` | tail |
29//!
30//! `DNODE_CORE_SIZE` = 64, so the first block pointer begins at offset 64. A
31//! dnode may span multiple 512-byte slots (`dn_extra_slots`); the bonus buffer
32//! begins after the `dn_nblkptr` block pointers.
33
34use crate::blkptr::Blkptr;
35use crate::bytes::{u8_at, Endian, Reader};
36
37/// The base size of a dnode (`DNODE_MIN_SIZE`), one slot.
38pub const DNODE_SIZE: usize = 512;
39/// The size of a dnode's fixed core, before the block-pointer array
40/// (`DNODE_CORE_SIZE`).
41pub const DNODE_CORE_SIZE: usize = 64;
42/// The size of one block pointer.
43pub const BLKPTR_SIZE: usize = 128;
44
45/// A parsed `dnode_phys_t`.
46#[derive(Debug, Clone)]
47pub struct Dnode {
48    /// `dn_type` — DMU object type (raw; map via `DmuType::from_raw`).
49    pub dn_type: u8,
50    /// `dn_indblkshift` — log2 of the indirect block size in bytes.
51    pub dn_indblkshift: u8,
52    /// `dn_nlevels` — indirection depth (1 = `dn_blkptr` point at data blocks).
53    pub dn_nlevels: u8,
54    /// `dn_nblkptr` — number of block pointers in `dn_blkptr[]`.
55    pub dn_nblkptr: u8,
56    /// `dn_bonustype` — type of data in the bonus buffer.
57    pub dn_bonustype: u8,
58    /// `dn_checksum` — ZIO checksum type for this object's blocks.
59    pub dn_checksum: u8,
60    /// `dn_compress` — ZIO compression type for this object's blocks.
61    pub dn_compress: u8,
62    /// `dn_flags` — `DNODE_FLAG_*`.
63    pub dn_flags: u8,
64    /// `dn_datablkszsec` — data block size in 512-byte sectors.
65    pub dn_datablkszsec: u16,
66    /// `dn_bonuslen` — length of the bonus buffer in bytes.
67    pub dn_bonuslen: u16,
68    /// `dn_extra_slots` — subsequent 512-byte slots this dnode consumes.
69    pub dn_extra_slots: u8,
70    /// `dn_maxblkid` — largest allocated block id (object spans blocks `0..=max`).
71    pub dn_maxblkid: u64,
72    /// `dn_used` — disk space used, in bytes or sectors (see `DNODE_FLAG_USED_BYTES`).
73    pub dn_used: u64,
74    /// The on-disk byte order this dnode (and its block tree) is written in.
75    pub endian: Endian,
76    /// The decoded top-level block pointers (`dn_blkptr[0..dn_nblkptr]`, capped
77    /// at the physical maximum that fits the dnode's slots).
78    pub blkptrs: Vec<Blkptr>,
79    /// The bonus buffer bytes (`dn_bonus[0..dn_bonuslen]`), if present.
80    pub bonus: Vec<u8>,
81}
82
83impl Dnode {
84    /// Data block size in bytes (`dn_datablkszsec << 9`).
85    #[must_use]
86    pub fn data_block_size(&self) -> usize {
87        (self.dn_datablkszsec as usize) << 9
88    }
89
90    /// Indirect block size in bytes (`1 << dn_indblkshift`), the number of L(n)
91    /// block pointers per indirect block being `indirect_block_size / 128`.
92    #[must_use]
93    pub fn indirect_block_size(&self) -> usize {
94        1usize << (self.dn_indblkshift.min(24))
95    }
96
97    /// A top-level block pointer by index, if present.
98    #[must_use]
99    pub fn blkptr(&self, i: usize) -> Option<&Blkptr> {
100        self.blkptrs.get(i)
101    }
102
103    /// Parse a `dnode_phys_t` from `raw` (at least 512 bytes), in `endian` order.
104    ///
105    /// Returns `None` only if `raw` is shorter than the 64-byte core; a dnode
106    /// with `dn_type == DMU_OT_NONE` still parses (it is a valid empty slot).
107    #[must_use]
108    pub fn parse(raw: &[u8], endian: Endian) -> Option<Self> {
109        if raw.len() < DNODE_CORE_SIZE {
110            return None;
111        }
112        let rd = Reader::new(endian);
113        let dn_type = u8_at(raw, 0);
114        let dn_indblkshift = u8_at(raw, 1);
115        let dn_nlevels = u8_at(raw, 2);
116        let dn_nblkptr = u8_at(raw, 3);
117        let dn_bonustype = u8_at(raw, 4);
118        let dn_checksum = u8_at(raw, 5);
119        let dn_compress = u8_at(raw, 6);
120        let dn_flags = u8_at(raw, 7);
121        let dn_datablkszsec = rd.u16(raw, 8);
122        let dn_bonuslen = rd.u16(raw, 10);
123        let dn_extra_slots = u8_at(raw, 12);
124        let dn_maxblkid = rd.u64(raw, 16);
125        let dn_used = rd.u64(raw, 24);
126
127        // How many blkptrs physically fit: the dnode occupies (1 + extra) slots;
128        // its tail (after the 64-byte core) holds blkptrs then bonus. Cap
129        // dn_nblkptr against a lying value so we never read past the dnode.
130        let total_bytes = (usize::from(dn_extra_slots).saturating_add(1)) * DNODE_SIZE;
131        let tail_bytes = total_bytes.saturating_sub(DNODE_CORE_SIZE);
132        let max_blkptrs = tail_bytes / BLKPTR_SIZE;
133        let nblkptr = usize::from(dn_nblkptr).min(max_blkptrs);
134
135        let mut blkptrs = Vec::with_capacity(nblkptr);
136        for i in 0..nblkptr {
137            let off = DNODE_CORE_SIZE + i * BLKPTR_SIZE;
138            match raw.get(off..off + BLKPTR_SIZE) {
139                Some(bp) => blkptrs.push(Blkptr::parse(bp, endian)),
140                None => break, // cov:unreachable: nblkptr capped to fit total_bytes
141            }
142        }
143
144        // The bonus buffer begins after the block pointers, bounded by dn_bonuslen
145        // and the space actually available in the dnode tail.
146        let bonus_off = DNODE_CORE_SIZE + nblkptr * BLKPTR_SIZE;
147        let bonus_avail = total_bytes.saturating_sub(bonus_off);
148        let bonus_len = usize::from(dn_bonuslen).min(bonus_avail);
149        let bonus = raw
150            .get(bonus_off..bonus_off + bonus_len)
151            .map(<[u8]>::to_vec)
152            .unwrap_or_default();
153
154        Some(Dnode {
155            dn_type,
156            dn_indblkshift,
157            dn_nlevels,
158            dn_nblkptr,
159            dn_bonustype,
160            dn_checksum,
161            dn_compress,
162            dn_flags,
163            dn_datablkszsec,
164            dn_bonuslen,
165            dn_extra_slots,
166            dn_maxblkid,
167            dn_used,
168            endian,
169            blkptrs,
170            bonus,
171        })
172    }
173}
174
175#[cfg(test)]
176mod unit {
177    use super::Dnode;
178    use crate::bytes::Endian;
179
180    #[test]
181    fn parse_none_when_shorter_than_core() {
182        assert!(Dnode::parse(&[0u8; 63], Endian::Little).is_none());
183    }
184
185    #[test]
186    fn parse_reads_core_fields_and_blkptrs() {
187        let mut raw = [0u8; 512];
188        raw[0] = 10; // dn_type = DNODE
189        raw[1] = 17; // indblkshift
190        raw[2] = 2; // nlevels
191        raw[3] = 3; // nblkptr
192        raw[8..10].copy_from_slice(&32u16.to_le_bytes()); // datablkszsec = 16 KiB
193        raw[10..12].copy_from_slice(&0u16.to_le_bytes()); // bonuslen
194        raw[16..24].copy_from_slice(&1u64.to_le_bytes()); // maxblkid
195                                                          // blkptr[0] at offset 64: give it a recognisable prop level=1.
196        let prop = 1u64 << 56 | (1u64 << 63);
197        raw[64 + 48..64 + 56].copy_from_slice(&prop.to_le_bytes());
198        let d = Dnode::parse(&raw, Endian::Little).unwrap();
199        assert_eq!(d.dn_type, 10);
200        assert_eq!(d.dn_nlevels, 2);
201        assert_eq!(d.dn_nblkptr, 3);
202        assert_eq!(d.dn_datablkszsec, 32);
203        assert_eq!(d.data_block_size(), 16 * 1024);
204        assert_eq!(d.dn_maxblkid, 1);
205        assert_eq!(d.blkptrs.len(), 3);
206        assert_eq!(d.blkptr(0).unwrap().level, 1);
207        assert!(d.blkptr(3).is_none());
208        assert_eq!(d.indirect_block_size(), 1 << 17);
209    }
210
211    #[test]
212    fn nblkptr_is_capped_to_what_fits_the_slots() {
213        // A single-slot dnode has room for (512-64)/128 = 3 blkptrs; a lying
214        // dn_nblkptr of 200 is capped, not over-read.
215        let mut raw = [0u8; 512];
216        raw[3] = 200; // dn_nblkptr (lie)
217        let d = Dnode::parse(&raw, Endian::Little).unwrap();
218        assert_eq!(d.blkptrs.len(), 3);
219    }
220
221    #[test]
222    fn bonus_buffer_is_bounded() {
223        // 1 blkptr, then a 64-byte bonus buffer with a marker.
224        let mut raw = [0u8; 512];
225        raw[3] = 1; // nblkptr
226        raw[10..12].copy_from_slice(&64u16.to_le_bytes()); // bonuslen
227        let bonus_off = 64 + 128;
228        raw[bonus_off] = 0xAB;
229        let d = Dnode::parse(&raw, Endian::Little).unwrap();
230        assert_eq!(d.bonus.len(), 64);
231        assert_eq!(d.bonus[0], 0xAB);
232    }
233
234    #[test]
235    fn lying_bonuslen_is_clamped_to_available_space() {
236        let mut raw = [0u8; 512];
237        raw[3] = 0; // no blkptrs
238        raw[10..12].copy_from_slice(&60000u16.to_le_bytes()); // absurd bonuslen
239        let d = Dnode::parse(&raw, Endian::Little).unwrap();
240        // Available tail = 512 - 64 = 448 bytes.
241        assert_eq!(d.bonus.len(), 448);
242    }
243}