* [PATCH 01/15] btrfs-progs: rust: introduce on-disk format definitions
2026-12-01 7:56 [PATCH RFC 00/15] btrfs-progs: experimental rust support Qu Wenruo
@ 2026-12-01 7:56 ` Qu Wenruo
2026-12-01 7:56 ` [PATCH 02/15] btrfs-progs: rust: add btrfs-rs with inspect-internal dump-super Qu Wenruo
` (13 subsequent siblings)
14 siblings, 0 replies; 16+ messages in thread
From: Qu Wenruo @ 2026-12-01 7:56 UTC (permalink / raw)
To: linux-btrfs
Start the experimental Rust part in a new top-level rust/ directory, as
a standalone Cargo package. The existing C build does not refer to it.
The disk module defines the on-disk formats of btrfs_tree.h as
They live in btrfs_tree.rs in header order, with the C field names.
Each struct has a compile-time size check, like the ioctl structures.
Constants are in consts.rs, key types are associated consts of the
KeyType newtype so that unknown values are preserved. It includes the
key types that are only defined in ctree.h.
The two unions in btrfs_disk_balance_args are plain Le64 fields with
safe min/max accessors, which avoids unsafe reads.
Signed-off-by: Qu Wenruo <wqu@suse.com>
---
rust/.gitignore | 1 +
rust/Cargo.lock | 65 +++
rust/Cargo.toml | 10 +
rust/README.md | 21 +
rust/src/disk/btrfs_tree.rs | 816 ++++++++++++++++++++++++++++++++++++
rust/src/disk/consts.rs | 526 +++++++++++++++++++++++
rust/src/disk/mod.rs | 20 +
rust/src/lib.rs | 6 +
rust/src/sizes.rs | 14 +
rust/tests/parse.rs | 82 ++++
10 files changed, 1561 insertions(+)
create mode 100644 rust/.gitignore
create mode 100644 rust/Cargo.lock
create mode 100644 rust/Cargo.toml
create mode 100644 rust/README.md
create mode 100644 rust/src/disk/btrfs_tree.rs
create mode 100644 rust/src/disk/consts.rs
create mode 100644 rust/src/disk/mod.rs
create mode 100644 rust/src/lib.rs
create mode 100644 rust/src/sizes.rs
create mode 100644 rust/tests/parse.rs
diff --git a/rust/.gitignore b/rust/.gitignore
new file mode 100644
index 000000000000..b83d22266ac8
--- /dev/null
+++ b/rust/.gitignore
@@ -0,0 +1 @@
+/target/
diff --git a/rust/Cargo.lock b/rust/Cargo.lock
new file mode 100644
index 000000000000..293784f98fda
--- /dev/null
+++ b/rust/Cargo.lock
@@ -0,0 +1,65 @@
+# This file is automatically @generated by Cargo.
+# It is not intended for manual editing.
+version = 4
+
+[[package]]
+name = "btrfs-rs"
+version = "0.0.0"
+dependencies = [
+ "zerocopy",
+]
+
+[[package]]
+name = "proc-macro2"
+version = "1.0.107"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
+dependencies = [
+ "unicode-ident",
+]
+
+[[package]]
+name = "quote"
+version = "1.0.47"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
+dependencies = [
+ "proc-macro2",
+]
+
+[[package]]
+name = "syn"
+version = "2.0.119"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "unicode-ident",
+]
+
+[[package]]
+name = "unicode-ident"
+version = "1.0.27"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"
+
+[[package]]
+name = "zerocopy"
+version = "0.8.66"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cba8a86aee14fc8cc6c208af60854b3d4ab7185a9a369a12c648faa2716ff42a"
+dependencies = [
+ "zerocopy-derive",
+]
+
+[[package]]
+name = "zerocopy-derive"
+version = "0.8.66"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f89bca3b96ceb3cfcb4572790402f977442270d252b9a8504ebc258760c55f94"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+]
diff --git a/rust/Cargo.toml b/rust/Cargo.toml
new file mode 100644
index 000000000000..bc832e7218f8
--- /dev/null
+++ b/rust/Cargo.toml
@@ -0,0 +1,10 @@
+[package]
+name = "btrfs-rs"
+description = "Experimental Rust implementation of btrfs-progs"
+version = "0.0.0"
+edition = "2021"
+license = "GPL-2.0-only"
+publish = false
+
+[dependencies]
+zerocopy = { version = "0.8", features = ["derive"] }
diff --git a/rust/README.md b/rust/README.md
new file mode 100644
index 000000000000..b2b3c9446ac2
--- /dev/null
+++ b/rust/README.md
@@ -0,0 +1,21 @@
+# btrfs-rs (experimental)
+
+Experimental Rust implementation of btrfs-progs.
+
+The long term goal is a function-parity Rust version of btrfs-progs, not just
+read-only tools. The near term goal is to evaluate the approach with
+`inspect-internal dump-super` and `inspect-internal dump-tree`.
+
+For evaluation only. Not part of the default build and not installed.
+
+## Layout
+
+- `src/disk/`: on-disk format definitions (no I/O).
+
+## Building
+
+```
+cd rust
+cargo build
+cargo test
+```
diff --git a/rust/src/disk/btrfs_tree.rs b/rust/src/disk/btrfs_tree.rs
new file mode 100644
index 000000000000..66f755348850
--- /dev/null
+++ b/rust/src/disk/btrfs_tree.rs
@@ -0,0 +1,816 @@
+//! On-disk structures of `kernel-shared/uapi/btrfs_tree.h`, in header order.
+
+use crate::disk::consts::limits;
+use crate::disk::{Le16, Le32, Le64};
+use crate::sizes::*;
+use zerocopy::{FromBytes, Immutable, IntoBytes, KnownLayout, Unaligned};
+
+/// `btrfs_disk_key`
+#[derive(
+ Debug, Clone, Copy, PartialEq, FromBytes, IntoBytes, KnownLayout, Immutable, Unaligned,
+)]
+#[repr(C)]
+pub struct DiskKey {
+ pub objectid: Le64,
+ pub r#type: u8,
+ pub offset: Le64,
+}
+const _: () = assert!(size_of::<DiskKey>() == 17);
+
+/// `btrfs_header`, at the start of every tree block.
+#[derive(
+ Debug, Clone, Copy, PartialEq, FromBytes, IntoBytes, KnownLayout, Immutable, Unaligned,
+)]
+#[repr(C)]
+pub struct Header {
+ pub csum: [u8; limits::CSUM_SIZE],
+ pub fsid: [u8; limits::FSID_SIZE],
+ pub bytenr: Le64,
+ pub flags: Le64,
+ pub chunk_tree_uuid: [u8; limits::UUID_SIZE],
+ pub generation: Le64,
+ pub owner: Le64,
+ pub nritems: Le32,
+ pub level: u8,
+}
+const _: () = assert!(size_of::<Header>() == 101);
+
+/// `btrfs_root_backup`
+#[derive(
+ Debug, Clone, Copy, PartialEq, FromBytes, IntoBytes, KnownLayout, Immutable, Unaligned,
+)]
+#[repr(C)]
+pub struct RootBackup {
+ pub tree_root: Le64,
+ pub tree_root_gen: Le64,
+ pub chunk_root: Le64,
+ pub chunk_root_gen: Le64,
+ pub extent_root: Le64,
+ pub extent_root_gen: Le64,
+ pub fs_root: Le64,
+ pub fs_root_gen: Le64,
+ pub dev_root: Le64,
+ pub dev_root_gen: Le64,
+ pub csum_root: Le64,
+ pub csum_root_gen: Le64,
+ pub total_bytes: Le64,
+ pub bytes_used: Le64,
+ pub num_devices: Le64,
+ pub unused_64: [Le64; 4],
+ pub tree_root_level: u8,
+ pub chunk_root_level: u8,
+ pub extent_root_level: u8,
+ pub fs_root_level: u8,
+ pub dev_root_level: u8,
+ pub csum_root_level: u8,
+ pub unused_8: [u8; 10],
+}
+const _: () = assert!(size_of::<RootBackup>() == 168);
+
+/// `btrfs_item`, a leaf entry. `offset` is relative to the end of the
+/// header.
+#[derive(
+ Debug, Clone, Copy, PartialEq, FromBytes, IntoBytes, KnownLayout, Immutable, Unaligned,
+)]
+#[repr(C)]
+pub struct Item {
+ pub key: DiskKey,
+ pub offset: Le32,
+ pub size: Le32,
+}
+const _: () = assert!(size_of::<Item>() == 25);
+
+/// `btrfs_key_ptr`, a node entry.
+#[derive(
+ Debug, Clone, Copy, PartialEq, FromBytes, IntoBytes, KnownLayout, Immutable, Unaligned,
+)]
+#[repr(C)]
+pub struct KeyPtr {
+ pub key: DiskKey,
+ pub blockptr: Le64,
+ pub generation: Le64,
+}
+const _: () = assert!(size_of::<KeyPtr>() == 33);
+
+/// `btrfs_dev_item`
+#[derive(
+ Debug, Clone, Copy, PartialEq, FromBytes, IntoBytes, KnownLayout, Immutable, Unaligned,
+)]
+#[repr(C)]
+pub struct DevItem {
+ pub devid: Le64,
+ pub total_bytes: Le64,
+ pub bytes_used: Le64,
+ pub io_align: Le32,
+ pub io_width: Le32,
+ pub sector_size: Le32,
+ pub r#type: Le64,
+ pub generation: Le64,
+ pub start_offset: Le64,
+ pub dev_group: Le32,
+ pub seek_speed: u8,
+ pub bandwidth: u8,
+ pub uuid: [u8; limits::UUID_SIZE],
+ pub fsid: [u8; limits::UUID_SIZE],
+}
+const _: () = assert!(size_of::<DevItem>() == 98);
+
+/// `btrfs_stripe`
+#[derive(
+ Debug, Clone, Copy, PartialEq, FromBytes, IntoBytes, KnownLayout, Immutable, Unaligned,
+)]
+#[repr(C)]
+pub struct Stripe {
+ pub devid: Le64,
+ pub offset: Le64,
+ pub dev_uuid: [u8; limits::UUID_SIZE],
+}
+const _: () = assert!(size_of::<Stripe>() == 32);
+
+/// `btrfs_chunk` item header. `num_stripes` [`Stripe`]s follow in the item payload.
+#[derive(
+ Debug, Clone, Copy, PartialEq, FromBytes, IntoBytes, KnownLayout, Immutable, Unaligned,
+)]
+#[repr(C)]
+pub struct Chunk {
+ pub length: Le64,
+ pub owner: Le64,
+ pub stripe_len: Le64,
+ pub r#type: Le64,
+ pub io_align: Le32,
+ pub io_width: Le32,
+ pub sector_size: Le32,
+ pub num_stripes: Le16,
+ pub sub_stripes: Le16,
+}
+const _: () = assert!(size_of::<Chunk>() == 48);
+
+/// `btrfs_super_block`, 4096 bytes.
+#[derive(
+ Debug, Clone, Copy, PartialEq, FromBytes, IntoBytes, KnownLayout, Immutable, Unaligned,
+)]
+#[repr(C)]
+pub struct SuperBlock {
+ pub csum: [u8; limits::CSUM_SIZE],
+ pub fsid: [u8; limits::FSID_SIZE],
+ pub bytenr: Le64,
+ pub flags: Le64,
+ pub magic: Le64,
+ pub generation: Le64,
+ pub root: Le64,
+ pub chunk_root: Le64,
+ pub log_root: Le64,
+ pub __unused_log_root_transid: Le64,
+ pub total_bytes: Le64,
+ pub bytes_used: Le64,
+ pub root_dir_objectid: Le64,
+ pub num_devices: Le64,
+ pub sectorsize: Le32,
+ pub nodesize: Le32,
+ pub __unused_leafsize: Le32,
+ pub stripesize: Le32,
+ pub sys_chunk_array_size: Le32,
+ pub chunk_root_generation: Le64,
+ pub compat_flags: Le64,
+ pub compat_ro_flags: Le64,
+ pub incompat_flags: Le64,
+ pub csum_type: Le16,
+ pub root_level: u8,
+ pub chunk_root_level: u8,
+ pub log_root_level: u8,
+ pub dev_item: DevItem,
+ pub label: [u8; limits::LABEL_SIZE],
+ pub cache_generation: Le64,
+ pub uuid_tree_generation: Le64,
+ pub metadata_uuid: [u8; limits::FSID_SIZE],
+ pub nr_global_roots: Le64,
+ pub remap_root: Le64,
+ pub remap_root_generation: Le64,
+ pub remap_root_level: u8,
+ pub reserved: [u8; 199],
+ pub sys_chunk_array: [u8; limits::SYSTEM_CHUNK_ARRAY_SIZE],
+ pub super_roots: [RootBackup; limits::NUM_BACKUP_ROOTS],
+ pub padding: [u8; 565],
+}
+const _: () = assert!(size_of::<SuperBlock>() == SZ_4K);
+
+/// `btrfs_free_space_entry`
+#[derive(
+ Debug, Clone, Copy, PartialEq, FromBytes, IntoBytes, KnownLayout, Immutable, Unaligned,
+)]
+#[repr(C)]
+pub struct FreeSpaceEntry {
+ pub offset: Le64,
+ pub bytes: Le64,
+ pub r#type: u8,
+}
+const _: () = assert!(size_of::<FreeSpaceEntry>() == 17);
+
+/// `btrfs_free_space_header`
+#[derive(
+ Debug, Clone, Copy, PartialEq, FromBytes, IntoBytes, KnownLayout, Immutable, Unaligned,
+)]
+#[repr(C)]
+pub struct FreeSpaceHeader {
+ pub location: DiskKey,
+ pub generation: Le64,
+ pub num_entries: Le64,
+ pub num_bitmaps: Le64,
+}
+const _: () = assert!(size_of::<FreeSpaceHeader>() == 41);
+
+/// `btrfs_raid_stride`, the element of a `btrfs_stripe_extent`.
+#[derive(
+ Debug, Clone, Copy, PartialEq, FromBytes, IntoBytes, KnownLayout, Immutable, Unaligned,
+)]
+#[repr(C)]
+pub struct RaidStride {
+ pub devid: Le64,
+ pub physical: Le64,
+}
+const _: () = assert!(size_of::<RaidStride>() == 16);
+
+/// `btrfs_extent_item`, inline refs follow.
+#[derive(
+ Debug, Clone, Copy, PartialEq, FromBytes, IntoBytes, KnownLayout, Immutable, Unaligned,
+)]
+#[repr(C)]
+pub struct ExtentItem {
+ pub refs: Le64,
+ pub generation: Le64,
+ pub flags: Le64,
+}
+const _: () = assert!(size_of::<ExtentItem>() == 24);
+
+/// `btrfs_extent_item_v0`, obsolete.
+#[derive(
+ Debug, Clone, Copy, PartialEq, FromBytes, IntoBytes, KnownLayout, Immutable, Unaligned,
+)]
+#[repr(C)]
+pub struct ExtentItemV0 {
+ pub refs: Le32,
+}
+const _: () = assert!(size_of::<ExtentItemV0>() == 4);
+
+/// `btrfs_tree_block_info`
+#[derive(
+ Debug, Clone, Copy, PartialEq, FromBytes, IntoBytes, KnownLayout, Immutable, Unaligned,
+)]
+#[repr(C)]
+pub struct TreeBlockInfo {
+ pub key: DiskKey,
+ pub level: u8,
+}
+const _: () = assert!(size_of::<TreeBlockInfo>() == 18);
+
+/// `btrfs_extent_data_ref`
+#[derive(
+ Debug, Clone, Copy, PartialEq, FromBytes, IntoBytes, KnownLayout, Immutable, Unaligned,
+)]
+#[repr(C)]
+pub struct ExtentDataRef {
+ pub root: Le64,
+ pub objectid: Le64,
+ pub offset: Le64,
+ pub count: Le32,
+}
+const _: () = assert!(size_of::<ExtentDataRef>() == 28);
+
+/// `btrfs_shared_data_ref`
+#[derive(
+ Debug, Clone, Copy, PartialEq, FromBytes, IntoBytes, KnownLayout, Immutable, Unaligned,
+)]
+#[repr(C)]
+pub struct SharedDataRef {
+ pub count: Le32,
+}
+const _: () = assert!(size_of::<SharedDataRef>() == 4);
+
+/// `btrfs_extent_owner_ref`
+#[derive(
+ Debug, Clone, Copy, PartialEq, FromBytes, IntoBytes, KnownLayout, Immutable, Unaligned,
+)]
+#[repr(C)]
+pub struct ExtentOwnerRef {
+ pub root_id: Le64,
+}
+const _: () = assert!(size_of::<ExtentOwnerRef>() == 8);
+
+/// `btrfs_extent_inline_ref`. For `EXTENT_DATA_REF` the offset field is
+/// the start of a [`ExtentDataRef`] instead.
+#[derive(
+ Debug, Clone, Copy, PartialEq, FromBytes, IntoBytes, KnownLayout, Immutable, Unaligned,
+)]
+#[repr(C)]
+pub struct ExtentInlineRef {
+ pub r#type: u8,
+ pub offset: Le64,
+}
+const _: () = assert!(size_of::<ExtentInlineRef>() == 9);
+
+/// `btrfs_dev_extent`
+#[derive(
+ Debug, Clone, Copy, PartialEq, FromBytes, IntoBytes, KnownLayout, Immutable, Unaligned,
+)]
+#[repr(C)]
+pub struct DevExtent {
+ pub chunk_tree: Le64,
+ pub chunk_objectid: Le64,
+ pub chunk_offset: Le64,
+ pub length: Le64,
+ pub chunk_tree_uuid: [u8; limits::UUID_SIZE],
+}
+const _: () = assert!(size_of::<DevExtent>() == 48);
+
+/// `btrfs_inode_ref`, `name_len` bytes of name follow.
+#[derive(
+ Debug, Clone, Copy, PartialEq, FromBytes, IntoBytes, KnownLayout, Immutable, Unaligned,
+)]
+#[repr(C)]
+pub struct InodeRef {
+ pub index: Le64,
+ pub name_len: Le16,
+}
+const _: () = assert!(size_of::<InodeRef>() == 10);
+
+/// `btrfs_inode_extref`, `name_len` bytes of name follow.
+#[derive(
+ Debug, Clone, Copy, PartialEq, FromBytes, IntoBytes, KnownLayout, Immutable, Unaligned,
+)]
+#[repr(C)]
+pub struct InodeExtref {
+ pub parent_objectid: Le64,
+ pub index: Le64,
+ pub name_len: Le16,
+}
+const _: () = assert!(size_of::<InodeExtref>() == 18);
+
+/// `btrfs_timespec`
+#[derive(
+ Debug, Clone, Copy, PartialEq, FromBytes, IntoBytes, KnownLayout, Immutable, Unaligned,
+)]
+#[repr(C)]
+pub struct Timespec {
+ pub sec: Le64,
+ pub nsec: Le32,
+}
+const _: () = assert!(size_of::<Timespec>() == 12);
+
+/// `btrfs_inode_item`
+#[derive(
+ Debug, Clone, Copy, PartialEq, FromBytes, IntoBytes, KnownLayout, Immutable, Unaligned,
+)]
+#[repr(C)]
+pub struct InodeItem {
+ pub generation: Le64,
+ pub transid: Le64,
+ pub size: Le64,
+ pub nbytes: Le64,
+ pub block_group: Le64,
+ pub nlink: Le32,
+ pub uid: Le32,
+ pub gid: Le32,
+ pub mode: Le32,
+ pub rdev: Le64,
+ pub flags: Le64,
+ pub sequence: Le64,
+ pub reserved: [Le64; 4],
+ pub atime: Timespec,
+ pub ctime: Timespec,
+ pub mtime: Timespec,
+ pub otime: Timespec,
+}
+const _: () = assert!(size_of::<InodeItem>() == 160);
+
+/// `btrfs_dir_log_item`
+#[derive(
+ Debug, Clone, Copy, PartialEq, FromBytes, IntoBytes, KnownLayout, Immutable, Unaligned,
+)]
+#[repr(C)]
+pub struct DirLogItem {
+ pub end: Le64,
+}
+const _: () = assert!(size_of::<DirLogItem>() == 8);
+
+/// `btrfs_dir_item`, `name_len` bytes of name and `data_len` bytes of data
+/// follow.
+#[derive(
+ Debug, Clone, Copy, PartialEq, FromBytes, IntoBytes, KnownLayout, Immutable, Unaligned,
+)]
+#[repr(C)]
+pub struct DirItem {
+ pub location: DiskKey,
+ pub transid: Le64,
+ pub data_len: Le16,
+ pub name_len: Le16,
+ pub r#type: u8,
+}
+const _: () = assert!(size_of::<DirItem>() == 30);
+
+/// `btrfs_root_item`. Items written before `generation_v2` was introduced
+/// end right before that field.
+#[derive(
+ Debug, Clone, Copy, PartialEq, FromBytes, IntoBytes, KnownLayout, Immutable, Unaligned,
+)]
+#[repr(C)]
+pub struct RootItem {
+ pub inode: InodeItem,
+ pub generation: Le64,
+ pub root_dirid: Le64,
+ pub bytenr: Le64,
+ pub byte_limit: Le64,
+ pub bytes_used: Le64,
+ pub last_snapshot: Le64,
+ pub flags: Le64,
+ pub refs: Le32,
+ pub drop_progress: DiskKey,
+ pub drop_level: u8,
+ pub level: u8,
+ pub generation_v2: Le64,
+ pub uuid: [u8; limits::UUID_SIZE],
+ pub parent_uuid: [u8; limits::UUID_SIZE],
+ pub received_uuid: [u8; limits::UUID_SIZE],
+ pub ctransid: Le64,
+ pub otransid: Le64,
+ pub stransid: Le64,
+ pub rtransid: Le64,
+ pub ctime: Timespec,
+ pub otime: Timespec,
+ pub stime: Timespec,
+ pub rtime: Timespec,
+ pub reserved: [Le64; 8],
+}
+const _: () = assert!(size_of::<RootItem>() == 439);
+
+/// `btrfs_root_ref`, `name_len` bytes of name follow.
+#[derive(
+ Debug, Clone, Copy, PartialEq, FromBytes, IntoBytes, KnownLayout, Immutable, Unaligned,
+)]
+#[repr(C)]
+pub struct RootRef {
+ pub dirid: Le64,
+ pub sequence: Le64,
+ pub name_len: Le16,
+}
+const _: () = assert!(size_of::<RootRef>() == 18);
+
+/// `btrfs_disk_balance_args`. `usage` and `limit` are unions in C: the
+/// same 8 bytes are also `usage_min`/`usage_max` and
+/// `limit_min`/`limit_max`, see the accessors.
+#[derive(
+ Debug, Clone, Copy, PartialEq, FromBytes, IntoBytes, KnownLayout, Immutable, Unaligned,
+)]
+#[repr(C)]
+pub struct DiskBalanceArgs {
+ pub profiles: Le64,
+ pub usage: Le64,
+ pub devid: Le64,
+ pub pstart: Le64,
+ pub pend: Le64,
+ pub vstart: Le64,
+ pub vend: Le64,
+ pub target: Le64,
+ pub flags: Le64,
+ pub limit: Le64,
+ pub stripes_min: Le32,
+ pub stripes_max: Le32,
+ pub unused: [Le64; 6],
+}
+const _: () = assert!(size_of::<DiskBalanceArgs>() == 136);
+
+/// `btrfs_balance_item`
+#[derive(
+ Debug, Clone, Copy, PartialEq, FromBytes, IntoBytes, KnownLayout, Immutable, Unaligned,
+)]
+#[repr(C)]
+pub struct BalanceItem {
+ pub flags: Le64,
+ pub data: DiskBalanceArgs,
+ pub meta: DiskBalanceArgs,
+ pub sys: DiskBalanceArgs,
+ pub unused: [Le64; 4],
+}
+const _: () = assert!(size_of::<BalanceItem>() == 448);
+
+/// `btrfs_file_extent_item`. For inline extents the data starts at
+/// `disk_bytenr`.
+#[derive(
+ Debug, Clone, Copy, PartialEq, FromBytes, IntoBytes, KnownLayout, Immutable, Unaligned,
+)]
+#[repr(C)]
+pub struct FileExtentItem {
+ pub generation: Le64,
+ pub ram_bytes: Le64,
+ pub compression: u8,
+ pub encryption: u8,
+ pub other_encoding: Le16,
+ pub r#type: u8,
+ pub disk_bytenr: Le64,
+ pub disk_num_bytes: Le64,
+ pub offset: Le64,
+ pub num_bytes: Le64,
+}
+const _: () = assert!(size_of::<FileExtentItem>() == 53);
+
+/// `btrfs_csum_item`, the first byte of a checksum array.
+#[derive(
+ Debug, Clone, Copy, PartialEq, FromBytes, IntoBytes, KnownLayout, Immutable, Unaligned,
+)]
+#[repr(C)]
+pub struct CsumItem {
+ pub csum: u8,
+}
+const _: () = assert!(size_of::<CsumItem>() == 1);
+
+/// `btrfs_dev_stats_item`
+#[derive(
+ Debug, Clone, Copy, PartialEq, FromBytes, IntoBytes, KnownLayout, Immutable, Unaligned,
+)]
+#[repr(C)]
+pub struct DevStatsItem {
+ pub values: [Le64; limits::DEV_STAT_VALUES_MAX],
+}
+const _: () = assert!(size_of::<DevStatsItem>() == 40);
+
+/// `btrfs_dev_replace_item`
+#[derive(
+ Debug, Clone, Copy, PartialEq, FromBytes, IntoBytes, KnownLayout, Immutable, Unaligned,
+)]
+#[repr(C)]
+pub struct DevReplaceItem {
+ pub src_devid: Le64,
+ pub cursor_left: Le64,
+ pub cursor_right: Le64,
+ pub cont_reading_from_srcdev_mode: Le64,
+ pub replace_state: Le64,
+ pub time_started: Le64,
+ pub time_stopped: Le64,
+ pub num_write_errors: Le64,
+ pub num_uncorrectable_read_errors: Le64,
+}
+const _: () = assert!(size_of::<DevReplaceItem>() == 72);
+
+/// `btrfs_block_group_item`
+#[derive(
+ Debug, Clone, Copy, PartialEq, FromBytes, IntoBytes, KnownLayout, Immutable, Unaligned,
+)]
+#[repr(C)]
+pub struct BlockGroupItem {
+ pub used: Le64,
+ pub chunk_objectid: Le64,
+ pub flags: Le64,
+}
+const _: () = assert!(size_of::<BlockGroupItem>() == 24);
+
+/// `btrfs_block_group_item_v2`
+#[derive(
+ Debug, Clone, Copy, PartialEq, FromBytes, IntoBytes, KnownLayout, Immutable, Unaligned,
+)]
+#[repr(C)]
+pub struct BlockGroupItemV2 {
+ pub used: Le64,
+ pub chunk_objectid: Le64,
+ pub flags: Le64,
+ pub remap_bytes: Le64,
+ pub identity_remap_count: Le32,
+}
+const _: () = assert!(size_of::<BlockGroupItemV2>() == 36);
+
+/// `btrfs_free_space_info`
+#[derive(
+ Debug, Clone, Copy, PartialEq, FromBytes, IntoBytes, KnownLayout, Immutable, Unaligned,
+)]
+#[repr(C)]
+pub struct FreeSpaceInfo {
+ pub extent_count: Le32,
+ pub flags: Le32,
+}
+const _: () = assert!(size_of::<FreeSpaceInfo>() == 8);
+
+/// `btrfs_qgroup_status_item`
+#[derive(
+ Debug, Clone, Copy, PartialEq, FromBytes, IntoBytes, KnownLayout, Immutable, Unaligned,
+)]
+#[repr(C)]
+pub struct QgroupStatusItem {
+ pub version: Le64,
+ pub generation: Le64,
+ pub flags: Le64,
+ pub rescan: Le64,
+ pub enable_gen: Le64,
+}
+const _: () = assert!(size_of::<QgroupStatusItem>() == 40);
+
+/// `btrfs_qgroup_info_item`
+#[derive(
+ Debug, Clone, Copy, PartialEq, FromBytes, IntoBytes, KnownLayout, Immutable, Unaligned,
+)]
+#[repr(C)]
+pub struct QgroupInfoItem {
+ pub generation: Le64,
+ pub rfer: Le64,
+ pub rfer_cmpr: Le64,
+ pub excl: Le64,
+ pub excl_cmpr: Le64,
+}
+const _: () = assert!(size_of::<QgroupInfoItem>() == 40);
+
+/// `btrfs_qgroup_limit_item`
+#[derive(
+ Debug, Clone, Copy, PartialEq, FromBytes, IntoBytes, KnownLayout, Immutable, Unaligned,
+)]
+#[repr(C)]
+pub struct QgroupLimitItem {
+ pub flags: Le64,
+ pub max_rfer: Le64,
+ pub max_excl: Le64,
+ pub rsv_rfer: Le64,
+ pub rsv_excl: Le64,
+}
+const _: () = assert!(size_of::<QgroupLimitItem>() == 40);
+
+/// `btrfs_verity_descriptor_item`
+#[derive(
+ Debug, Clone, Copy, PartialEq, FromBytes, IntoBytes, KnownLayout, Immutable, Unaligned,
+)]
+#[repr(C)]
+pub struct VerityDescriptorItem {
+ pub size: Le64,
+ pub reserved: [Le64; 2],
+ pub encryption: u8,
+}
+const _: () = assert!(size_of::<VerityDescriptorItem>() == 25);
+
+/// `btrfs_remap_item`
+#[derive(
+ Debug, Clone, Copy, PartialEq, FromBytes, IntoBytes, KnownLayout, Immutable, Unaligned,
+)]
+#[repr(C)]
+pub struct RemapItem {
+ pub address: Le64,
+}
+const _: () = assert!(size_of::<RemapItem>() == 8);
+
+impl DiskBalanceArgs {
+ pub fn usage_min(&self) -> u32 {
+ self.usage.get() as u32
+ }
+
+ pub fn usage_max(&self) -> u32 {
+ (self.usage.get() >> 32) as u32
+ }
+
+ pub fn limit_min(&self) -> u32 {
+ self.limit.get() as u32
+ }
+
+ pub fn limit_max(&self) -> u32 {
+ (self.limit.get() >> 32) as u32
+ }
+}
+
+/// The item type of a key. A newtype rather than an enum so that unknown
+/// values are preserved.
+#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
+pub struct KeyType(pub u8);
+
+/// CPU-side key (`btrfs_key`). Fields are in tree order, so the derived `Ord`
+/// is the key comparison.
+#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
+pub struct Key {
+ pub objectid: u64,
+ pub r#type: KeyType,
+ pub offset: u64,
+}
+
+impl From<&DiskKey> for Key {
+ fn from(k: &DiskKey) -> Key {
+ Key {
+ objectid: k.objectid.get(),
+ r#type: KeyType(k.r#type),
+ offset: k.offset.get(),
+ }
+ }
+}
+
+impl From<&Key> for DiskKey {
+ fn from(k: &Key) -> DiskKey {
+ DiskKey {
+ objectid: k.objectid.into(),
+ r#type: k.r#type.0,
+ offset: k.offset.into(),
+ }
+ }
+}
+
+/// Size of a root item without the fields from `generation_v2` on
+/// (`btrfs_legacy_root_item_size()`).
+pub const LEGACY_ROOT_ITEM_SIZE: usize = core::mem::offset_of!(RootItem, generation_v2);
+
+/// The level of a qgroup id (`btrfs_qgroup_level()`).
+pub const fn qgroup_level(qgroupid: u64) -> u16 {
+ (qgroupid >> crate::disk::consts::qgroup::LEVEL_SHIFT) as u16
+}
+
+impl KeyType {
+ /// `BTRFS_INODE_ITEM_KEY`
+ pub const INODE_ITEM: KeyType = KeyType(1);
+ /// `BTRFS_INODE_REF_KEY`
+ pub const INODE_REF: KeyType = KeyType(12);
+ /// `BTRFS_INODE_EXTREF_KEY`
+ pub const INODE_EXTREF: KeyType = KeyType(13);
+ /// `BTRFS_XATTR_ITEM_KEY`
+ pub const XATTR_ITEM: KeyType = KeyType(24);
+ /// `BTRFS_VERITY_DESC_ITEM_KEY`
+ pub const VERITY_DESC_ITEM: KeyType = KeyType(36);
+ /// `BTRFS_VERITY_MERKLE_ITEM_KEY`
+ pub const VERITY_MERKLE_ITEM: KeyType = KeyType(37);
+ /// `BTRFS_FSCRYPT_INODE_CTX_KEY`
+ pub const FSCRYPT_INODE_CTX: KeyType = KeyType(41);
+ /// `BTRFS_FSCRYPT_CTX_KEY`
+ pub const FSCRYPT_CTX: KeyType = KeyType(42);
+ /// `BTRFS_ORPHAN_ITEM_KEY`
+ pub const ORPHAN_ITEM: KeyType = KeyType(48);
+ /// `BTRFS_DIR_LOG_ITEM_KEY`
+ pub const DIR_LOG_ITEM: KeyType = KeyType(60);
+ /// `BTRFS_DIR_LOG_INDEX_KEY`
+ pub const DIR_LOG_INDEX: KeyType = KeyType(72);
+ /// `BTRFS_DIR_ITEM_KEY`
+ pub const DIR_ITEM: KeyType = KeyType(84);
+ /// `BTRFS_DIR_INDEX_KEY`
+ pub const DIR_INDEX: KeyType = KeyType(96);
+ /// `BTRFS_EXTENT_DATA_KEY`
+ pub const EXTENT_DATA: KeyType = KeyType(108);
+ /// `BTRFS_CSUM_ITEM_KEY`, defined in `kernel-shared/ctree.h`
+ pub const CSUM_ITEM: KeyType = KeyType(120);
+ /// `BTRFS_EXTENT_CSUM_KEY`
+ pub const EXTENT_CSUM: KeyType = KeyType(128);
+ /// `BTRFS_ROOT_ITEM_KEY`
+ pub const ROOT_ITEM: KeyType = KeyType(132);
+ /// `BTRFS_ROOT_BACKREF_KEY`
+ pub const ROOT_BACKREF: KeyType = KeyType(144);
+ /// `BTRFS_ROOT_REF_KEY`
+ pub const ROOT_REF: KeyType = KeyType(156);
+ /// `BTRFS_EXTENT_ITEM_KEY`
+ pub const EXTENT_ITEM: KeyType = KeyType(168);
+ /// `BTRFS_METADATA_ITEM_KEY`
+ pub const METADATA_ITEM: KeyType = KeyType(169);
+ /// `BTRFS_EXTENT_OWNER_REF_KEY`
+ pub const EXTENT_OWNER_REF: KeyType = KeyType(172);
+ /// `BTRFS_TREE_BLOCK_REF_KEY`
+ pub const TREE_BLOCK_REF: KeyType = KeyType(176);
+ /// `BTRFS_EXTENT_DATA_REF_KEY`
+ pub const EXTENT_DATA_REF: KeyType = KeyType(178);
+ /// `BTRFS_EXTENT_REF_V0_KEY`, defined in `kernel-shared/ctree.h`
+ pub const EXTENT_REF_V0: KeyType = KeyType(180);
+ /// `BTRFS_SHARED_BLOCK_REF_KEY`
+ pub const SHARED_BLOCK_REF: KeyType = KeyType(182);
+ /// `BTRFS_SHARED_DATA_REF_KEY`
+ pub const SHARED_DATA_REF: KeyType = KeyType(184);
+ /// `BTRFS_BLOCK_GROUP_ITEM_KEY`
+ pub const BLOCK_GROUP_ITEM: KeyType = KeyType(192);
+ /// `BTRFS_FREE_SPACE_INFO_KEY`
+ pub const FREE_SPACE_INFO: KeyType = KeyType(198);
+ /// `BTRFS_FREE_SPACE_EXTENT_KEY`
+ pub const FREE_SPACE_EXTENT: KeyType = KeyType(199);
+ /// `BTRFS_FREE_SPACE_BITMAP_KEY`
+ pub const FREE_SPACE_BITMAP: KeyType = KeyType(200);
+ /// `BTRFS_DEV_EXTENT_KEY`
+ pub const DEV_EXTENT: KeyType = KeyType(204);
+ /// `BTRFS_DEV_ITEM_KEY`
+ pub const DEV_ITEM: KeyType = KeyType(216);
+ /// `BTRFS_CHUNK_ITEM_KEY`
+ pub const CHUNK_ITEM: KeyType = KeyType(228);
+ /// `BTRFS_RAID_STRIPE_KEY`
+ pub const RAID_STRIPE: KeyType = KeyType(230);
+ /// `BTRFS_IDENTITY_REMAP_KEY`, defined in `kernel-shared/ctree.h`
+ pub const IDENTITY_REMAP: KeyType = KeyType(234);
+ /// `BTRFS_REMAP_KEY`, defined in `kernel-shared/ctree.h`
+ pub const REMAP: KeyType = KeyType(235);
+ /// `BTRFS_REMAP_BACKREF_KEY`, defined in `kernel-shared/ctree.h`
+ pub const REMAP_BACKREF: KeyType = KeyType(236);
+ /// `BTRFS_QGROUP_STATUS_KEY`
+ pub const QGROUP_STATUS: KeyType = KeyType(240);
+ /// `BTRFS_QGROUP_INFO_KEY`
+ pub const QGROUP_INFO: KeyType = KeyType(242);
+ /// `BTRFS_QGROUP_LIMIT_KEY`
+ pub const QGROUP_LIMIT: KeyType = KeyType(244);
+ /// `BTRFS_QGROUP_RELATION_KEY`
+ pub const QGROUP_RELATION: KeyType = KeyType(246);
+ /// `BTRFS_BALANCE_ITEM_KEY`
+ pub const BALANCE_ITEM: KeyType = KeyType(248);
+ /// `BTRFS_TEMPORARY_ITEM_KEY`
+ pub const TEMPORARY_ITEM: KeyType = KeyType(248);
+ /// `BTRFS_DEV_STATS_KEY`
+ pub const DEV_STATS: KeyType = KeyType(249);
+ /// `BTRFS_PERSISTENT_ITEM_KEY`
+ pub const PERSISTENT_ITEM: KeyType = KeyType(249);
+ /// `BTRFS_DEV_REPLACE_KEY`
+ pub const DEV_REPLACE: KeyType = KeyType(250);
+ /// `BTRFS_UUID_KEY_SUBVOL`
+ pub const UUID_KEY_SUBVOL: KeyType = KeyType(251);
+ /// `BTRFS_UUID_KEY_RECEIVED_SUBVOL`
+ pub const UUID_KEY_RECEIVED_SUBVOL: KeyType = KeyType(252);
+ /// `BTRFS_STRING_ITEM_KEY`
+ pub const STRING_ITEM: KeyType = KeyType(253);
+}
diff --git a/rust/src/disk/consts.rs b/rust/src/disk/consts.rs
new file mode 100644
index 000000000000..981308582389
--- /dev/null
+++ b/rust/src/disk/consts.rs
@@ -0,0 +1,526 @@
+//! Constants from `kernel-shared/uapi/btrfs_tree.h` and `btrfs.h`.
+//!
+//! One module per group, named after the C prefix without `BTRFS_` and the
+//! group suffix, e.g. `BTRFS_ROOT_TREE_OBJECTID` is `objectid::ROOT_TREE`.
+//! Key types are associated consts of [`crate::disk::KeyType`]. Each constant is
+//! documented with the C macro it mirrors.
+
+use crate::sizes::*;
+
+pub mod limits {
+ use crate::sizes::*;
+ /// `BTRFS_MAX_LEVEL`
+ pub const MAX_LEVEL: usize = 8;
+ /// `BTRFS_NAME_LEN`
+ pub const NAME_LEN: usize = 255;
+ /// `BTRFS_LINK_MAX`
+ pub const LINK_MAX: usize = SZ_64K;
+ /// `BTRFS_CSUM_SIZE`
+ pub const CSUM_SIZE: usize = 32;
+ /// `BTRFS_FSID_SIZE`
+ pub const FSID_SIZE: usize = 16;
+ /// `BTRFS_UUID_SIZE`
+ pub const UUID_SIZE: usize = 16;
+ /// `BTRFS_LABEL_SIZE`
+ pub const LABEL_SIZE: usize = 256;
+ /// `BTRFS_SYSTEM_CHUNK_ARRAY_SIZE`
+ pub const SYSTEM_CHUNK_ARRAY_SIZE: usize = SZ_2K;
+ /// `BTRFS_NUM_BACKUP_ROOTS`
+ pub const NUM_BACKUP_ROOTS: usize = 4;
+ /// `BTRFS_DEV_STAT_VALUES_MAX`
+ pub const DEV_STAT_VALUES_MAX: usize = 5;
+ /// `BTRFS_MAX_METADATA_BLOCKSIZE`
+ /// No NODESIZE_MIN, as it will be sectorsize.
+ pub const NODESIZE_MAX: usize = SZ_64K;
+ /// Proper limits on sectorsize.
+ pub const SECTORSIZE_MIN: usize = SZ_4K;
+ pub const SECTORSIZE_MAX: usize = SZ_64K;
+}
+
+pub mod magic {
+ /// `BTRFS_MAGIC`
+ pub const BTRFS: u64 = 0x4D5F_5366_5248_425F;
+}
+
+pub mod objectid {
+ /// `BTRFS_ROOT_TREE_OBJECTID`
+ pub const ROOT_TREE: u64 = 1;
+ /// `BTRFS_EXTENT_TREE_OBJECTID`
+ pub const EXTENT_TREE: u64 = 2;
+ /// `BTRFS_CHUNK_TREE_OBJECTID`
+ pub const CHUNK_TREE: u64 = 3;
+ /// `BTRFS_DEV_TREE_OBJECTID`
+ pub const DEV_TREE: u64 = 4;
+ /// `BTRFS_FS_TREE_OBJECTID`
+ pub const FS_TREE: u64 = 5;
+ /// `BTRFS_ROOT_TREE_DIR_OBJECTID`
+ pub const ROOT_TREE_DIR: u64 = 6;
+ /// `BTRFS_CSUM_TREE_OBJECTID`
+ pub const CSUM_TREE: u64 = 7;
+ /// `BTRFS_QUOTA_TREE_OBJECTID`
+ pub const QUOTA_TREE: u64 = 8;
+ /// `BTRFS_UUID_TREE_OBJECTID`
+ pub const UUID_TREE: u64 = 9;
+ /// `BTRFS_FREE_SPACE_TREE_OBJECTID`
+ pub const FREE_SPACE_TREE: u64 = 10;
+ /// `BTRFS_BLOCK_GROUP_TREE_OBJECTID`
+ pub const BLOCK_GROUP_TREE: u64 = 11;
+ /// `BTRFS_RAID_STRIPE_TREE_OBJECTID`
+ pub const RAID_STRIPE_TREE: u64 = 12;
+ /// `BTRFS_REMAP_TREE_OBJECTID`
+ pub const REMAP_TREE: u64 = 13;
+ /// `BTRFS_DEV_STATS_OBJECTID`
+ pub const DEV_STATS: u64 = 0;
+ /// `BTRFS_BALANCE_OBJECTID`
+ pub const BALANCE: u64 = (-4i64) as u64;
+ /// `BTRFS_ORPHAN_OBJECTID`
+ pub const ORPHAN: u64 = (-5i64) as u64;
+ /// `BTRFS_TREE_LOG_OBJECTID`
+ pub const TREE_LOG: u64 = (-6i64) as u64;
+ /// `BTRFS_TREE_LOG_FIXUP_OBJECTID`
+ pub const TREE_LOG_FIXUP: u64 = (-7i64) as u64;
+ /// `BTRFS_TREE_RELOC_OBJECTID`
+ pub const TREE_RELOC: u64 = (-8i64) as u64;
+ /// `BTRFS_DATA_RELOC_TREE_OBJECTID`
+ pub const DATA_RELOC_TREE: u64 = (-9i64) as u64;
+ /// `BTRFS_EXTENT_CSUM_OBJECTID`
+ pub const EXTENT_CSUM: u64 = (-10i64) as u64;
+ /// `BTRFS_FREE_SPACE_OBJECTID`
+ pub const FREE_SPACE: u64 = (-11i64) as u64;
+ /// `BTRFS_FREE_INO_OBJECTID`
+ pub const FREE_INO: u64 = (-12i64) as u64;
+ /// `BTRFS_CSUM_CHANGE_OBJECTID`
+ pub const CSUM_CHANGE: u64 = (-13i64) as u64;
+ /// `BTRFS_MULTIPLE_OBJECTIDS`
+ pub const MULTIPLE: u64 = (-255i64) as u64;
+ /// `BTRFS_FIRST_FREE_OBJECTID`
+ pub const FIRST_FREE: u64 = 256;
+ /// `BTRFS_LAST_FREE_OBJECTID`
+ pub const LAST_FREE: u64 = (-256i64) as u64;
+ /// `BTRFS_FIRST_CHUNK_TREE_OBJECTID`
+ pub const FIRST_CHUNK_TREE: u64 = 256;
+ /// `BTRFS_DEV_ITEMS_OBJECTID`
+ pub const DEV_ITEMS: u64 = 1;
+ /// `BTRFS_BTREE_INODE_OBJECTID`
+ pub const BTREE_INODE: u64 = 1;
+ /// `BTRFS_EMPTY_SUBVOL_DIR_OBJECTID`
+ pub const EMPTY_SUBVOL_DIR: u64 = 2;
+ /// `BTRFS_DEV_REPLACE_DEVID`
+ pub const DEV_REPLACE_DEVID: u64 = 0;
+}
+
+pub mod csum_type {
+ /// `BTRFS_CSUM_TYPE_CRC32`
+ pub const CRC32: u16 = 0;
+ /// `BTRFS_CSUM_TYPE_XXHASH`
+ pub const XXHASH: u16 = 1;
+ /// `BTRFS_CSUM_TYPE_SHA256`
+ pub const SHA256: u16 = 2;
+ /// `BTRFS_CSUM_TYPE_BLAKE2`
+ pub const BLAKE2: u16 = 3;
+}
+
+/// `btrfs_dir_item.type`
+pub mod file_type {
+ /// `BTRFS_FT_UNKNOWN`
+ pub const UNKNOWN: u8 = 0;
+ /// `BTRFS_FT_REG_FILE`
+ pub const REG_FILE: u8 = 1;
+ /// `BTRFS_FT_DIR`
+ pub const DIR: u8 = 2;
+ /// `BTRFS_FT_CHRDEV`
+ pub const CHRDEV: u8 = 3;
+ /// `BTRFS_FT_BLKDEV`
+ pub const BLKDEV: u8 = 4;
+ /// `BTRFS_FT_FIFO`
+ pub const FIFO: u8 = 5;
+ /// `BTRFS_FT_SOCK`
+ pub const SOCK: u8 = 6;
+ /// `BTRFS_FT_SYMLINK`
+ pub const SYMLINK: u8 = 7;
+ /// `BTRFS_FT_XATTR`
+ pub const XATTR: u8 = 8;
+ /// `BTRFS_FT_MAX`
+ pub const MAX: u8 = 9;
+ /// `BTRFS_FT_ENCRYPTED`
+ pub const ENCRYPTED: u8 = 0x80;
+}
+
+/// `btrfs_inode_item.flags`
+pub mod inode_flag {
+ /// `BTRFS_INODE_NODATASUM`
+ pub const NODATASUM: u64 = 1 << 0;
+ /// `BTRFS_INODE_NODATACOW`
+ pub const NODATACOW: u64 = 1 << 1;
+ /// `BTRFS_INODE_READONLY`
+ pub const READONLY: u64 = 1 << 2;
+ /// `BTRFS_INODE_NOCOMPRESS`
+ pub const NOCOMPRESS: u64 = 1 << 3;
+ /// `BTRFS_INODE_PREALLOC`
+ pub const PREALLOC: u64 = 1 << 4;
+ /// `BTRFS_INODE_SYNC`
+ pub const SYNC: u64 = 1 << 5;
+ /// `BTRFS_INODE_IMMUTABLE`
+ pub const IMMUTABLE: u64 = 1 << 6;
+ /// `BTRFS_INODE_APPEND`
+ pub const APPEND: u64 = 1 << 7;
+ /// `BTRFS_INODE_NODUMP`
+ pub const NODUMP: u64 = 1 << 8;
+ /// `BTRFS_INODE_NOATIME`
+ pub const NOATIME: u64 = 1 << 9;
+ /// `BTRFS_INODE_DIRSYNC`
+ pub const DIRSYNC: u64 = 1 << 10;
+ /// `BTRFS_INODE_COMPRESS`
+ pub const COMPRESS: u64 = 1 << 11;
+ /// `BTRFS_INODE_ENCRYPT`
+ pub const ENCRYPT: u64 = 1 << 12;
+ /// `BTRFS_INODE_ROOT_ITEM_INIT`
+ pub const ROOT_ITEM_INIT: u64 = 1 << 31;
+ /// `BTRFS_INODE_FLAG_MASK`
+ pub const MASK: u64 = NODATASUM
+ | NODATACOW
+ | READONLY
+ | NOCOMPRESS
+ | PREALLOC
+ | SYNC
+ | IMMUTABLE
+ | APPEND
+ | NODUMP
+ | NOATIME
+ | DIRSYNC
+ | COMPRESS
+ | ENCRYPT
+ | ROOT_ITEM_INIT;
+}
+
+pub mod inode_ro_flag {
+ /// `BTRFS_INODE_RO_VERITY`
+ pub const VERITY: u64 = 1 << 0;
+ /// `BTRFS_INODE_RO_FLAG_MASK`
+ pub const MASK: u64 = VERITY;
+}
+
+/// `btrfs_header.flags`
+pub mod header_flag {
+ /// `BTRFS_HEADER_FLAG_WRITTEN`
+ pub const WRITTEN: u64 = 1 << 0;
+ /// `BTRFS_HEADER_FLAG_RELOC`
+ pub const RELOC: u64 = 1 << 1;
+}
+
+/// `btrfs_super_block.flags`
+pub mod super_flag {
+ /// `BTRFS_SUPER_FLAG_ERROR`
+ pub const ERROR: u64 = 1 << 2;
+ /// `BTRFS_SUPER_FLAG_SEEDING`
+ pub const SEEDING: u64 = 1 << 32;
+ /// `BTRFS_SUPER_FLAG_METADUMP`
+ pub const METADUMP: u64 = 1 << 33;
+ /// `BTRFS_SUPER_FLAG_METADUMP_V2`
+ pub const METADUMP_V2: u64 = 1 << 34;
+ /// `BTRFS_SUPER_FLAG_CHANGING_FSID`
+ pub const CHANGING_FSID: u64 = 1 << 35;
+ /// `BTRFS_SUPER_FLAG_CHANGING_FSID_V2`
+ pub const CHANGING_FSID_V2: u64 = 1 << 36;
+ /// `BTRFS_SUPER_FLAG_CHANGING_BG_TREE`
+ pub const CHANGING_BG_TREE: u64 = 1 << 38;
+ /// `BTRFS_SUPER_FLAG_CHANGING_DATA_CSUM`
+ pub const CHANGING_DATA_CSUM: u64 = 1 << 39;
+ /// `BTRFS_SUPER_FLAG_CHANGING_META_CSUM`
+ pub const CHANGING_META_CSUM: u64 = 1 << 40;
+}
+
+/// `btrfs_extent_item.flags`
+pub mod extent_flag {
+ /// `BTRFS_EXTENT_FLAG_DATA`
+ pub const DATA: u64 = 1 << 0;
+ /// `BTRFS_EXTENT_FLAG_TREE_BLOCK`
+ pub const TREE_BLOCK: u64 = 1 << 1;
+ /// `BTRFS_BLOCK_FLAG_FULL_BACKREF`
+ pub const FULL_BACKREF: u64 = 1 << 8;
+ /// `BTRFS_EXTENT_FLAG_SUPER`
+ pub const SUPER: u64 = 1 << 48;
+}
+
+pub mod backref_rev {
+ /// `BTRFS_BACKREF_REV_MAX`
+ pub const MAX: u64 = 256;
+ /// `BTRFS_BACKREF_REV_SHIFT`
+ pub const SHIFT: u64 = 56;
+ /// `BTRFS_BACKREF_REV_MASK`
+ pub const MASK: u64 = (MAX - 1) << SHIFT;
+ /// `BTRFS_OLD_BACKREF_REV`
+ pub const OLD: u64 = 0;
+ /// `BTRFS_MIXED_BACKREF_REV`
+ pub const MIXED: u64 = 1;
+}
+
+/// `btrfs_file_extent_item.type`
+pub mod file_extent_type {
+ /// `BTRFS_FILE_EXTENT_INLINE`
+ pub const INLINE: u8 = 0;
+ /// `BTRFS_FILE_EXTENT_REG`
+ pub const REG: u8 = 1;
+ /// `BTRFS_FILE_EXTENT_PREALLOC`
+ pub const PREALLOC: u8 = 2;
+ /// `BTRFS_NR_FILE_EXTENT_TYPES`
+ pub const NR_TYPES: u8 = 3;
+}
+
+/// `btrfs_file_extent_item.compression`
+pub mod compress_type {
+ /// `BTRFS_COMPRESS_NONE`
+ pub const NONE: u8 = 0;
+ /// `BTRFS_COMPRESS_ZLIB`
+ pub const ZLIB: u8 = 1;
+ /// `BTRFS_COMPRESS_LZO`
+ pub const LZO: u8 = 2;
+ /// `BTRFS_COMPRESS_ZSTD`
+ pub const ZSTD: u8 = 3;
+ /// `BTRFS_COMPRESS_LAST`
+ pub const LAST: u8 = 4;
+}
+
+/// `btrfs_file_extent_item.encryption`
+pub mod encryption {
+ /// `BTRFS_ENCRYPTION_NONE`
+ pub const NONE: u8 = 0;
+ /// `BTRFS_ENCRYPTION_FSCRYPT`
+ pub const FSCRYPT: u8 = 1;
+ /// `BTRFS_NR_ENCRYPTION_TYPES`
+ pub const NR_TYPES: u8 = 2;
+}
+
+/// `btrfs_free_space_entry.type`
+pub mod free_space_entry_type {
+ /// `BTRFS_FREE_SPACE_EXTENT`
+ pub const EXTENT: u8 = 1;
+ /// `BTRFS_FREE_SPACE_BITMAP`
+ pub const BITMAP: u8 = 2;
+}
+
+/// `btrfs_free_space_info.flags`
+pub mod free_space_info_flag {
+ /// `BTRFS_FREE_SPACE_USING_BITMAPS`
+ pub const USING_BITMAPS: u32 = 1 << 0;
+}
+
+/// `btrfs_root_item.flags`
+pub mod root_flag {
+ /// `BTRFS_ROOT_SUBVOL_RDONLY`
+ pub const SUBVOL_RDONLY: u64 = 1 << 0;
+ /// `BTRFS_ROOT_SUBVOL_DEAD`
+ pub const SUBVOL_DEAD: u64 = 1 << 48;
+}
+
+/// `btrfs_chunk.type` and `btrfs_block_group_item.flags`
+pub mod block_group {
+ /// `BTRFS_BLOCK_GROUP_DATA`
+ pub const DATA: u64 = 1 << 0;
+ /// `BTRFS_BLOCK_GROUP_SYSTEM`
+ pub const SYSTEM: u64 = 1 << 1;
+ /// `BTRFS_BLOCK_GROUP_METADATA`
+ pub const METADATA: u64 = 1 << 2;
+ /// `BTRFS_BLOCK_GROUP_RAID0`
+ pub const RAID0: u64 = 1 << 3;
+ /// `BTRFS_BLOCK_GROUP_RAID1`
+ pub const RAID1: u64 = 1 << 4;
+ /// `BTRFS_BLOCK_GROUP_DUP`
+ pub const DUP: u64 = 1 << 5;
+ /// `BTRFS_BLOCK_GROUP_RAID10`
+ pub const RAID10: u64 = 1 << 6;
+ /// `BTRFS_BLOCK_GROUP_RAID5`
+ pub const RAID5: u64 = 1 << 7;
+ /// `BTRFS_BLOCK_GROUP_RAID6`
+ pub const RAID6: u64 = 1 << 8;
+ /// `BTRFS_BLOCK_GROUP_RAID1C3`
+ pub const RAID1C3: u64 = 1 << 9;
+ /// `BTRFS_BLOCK_GROUP_RAID1C4`
+ pub const RAID1C4: u64 = 1 << 10;
+ /// `BTRFS_BLOCK_GROUP_REMAPPED`
+ pub const REMAPPED: u64 = 1 << 11;
+ /// `BTRFS_BLOCK_GROUP_METADATA_REMAP`
+ pub const METADATA_REMAP: u64 = 1 << 12;
+ /// `BTRFS_AVAIL_ALLOC_BIT_SINGLE`
+ pub const AVAIL_ALLOC_BIT_SINGLE: u64 = 1 << 48;
+ /// `BTRFS_SPACE_INFO_GLOBAL_RSV`
+ pub const SPACE_INFO_GLOBAL_RSV: u64 = 1 << 49;
+ /// `BTRFS_BLOCK_GROUP_RESERVED`
+ pub const RESERVED: u64 = AVAIL_ALLOC_BIT_SINGLE | SPACE_INFO_GLOBAL_RSV;
+ /// `BTRFS_BLOCK_GROUP_TYPE_MASK`
+ pub const TYPE_MASK: u64 = DATA | SYSTEM | METADATA | METADATA_REMAP;
+ /// `BTRFS_BLOCK_GROUP_PROFILE_MASK`
+ pub const PROFILE_MASK: u64 = RAID0 | RAID1 | RAID1C3 | RAID1C4 | RAID5 | RAID6 | DUP | RAID10;
+ /// `BTRFS_BLOCK_GROUP_RAID56_MASK`
+ pub const RAID56_MASK: u64 = RAID5 | RAID6;
+ /// `BTRFS_BLOCK_GROUP_RAID1_MASK`
+ pub const RAID1_MASK: u64 = RAID1 | RAID1C3 | RAID1C4;
+ /// `BTRFS_EXTENDED_PROFILE_MASK`
+ pub const EXTENDED_PROFILE_MASK: u64 = PROFILE_MASK | AVAIL_ALLOC_BIT_SINGLE;
+}
+
+pub mod qgroup {
+ /// `BTRFS_QGROUP_LEVEL_SHIFT`
+ pub const LEVEL_SHIFT: u64 = 48;
+ /// `BTRFS_QGROUP_STATUS_VERSION`
+ pub const STATUS_VERSION: u64 = 1;
+}
+
+/// `btrfs_qgroup_status_item.flags`
+pub mod qgroup_status_flag {
+ /// `BTRFS_QGROUP_STATUS_FLAG_ON`
+ pub const ON: u64 = 1 << 0;
+ /// `BTRFS_QGROUP_STATUS_FLAG_RESCAN`
+ pub const RESCAN: u64 = 1 << 1;
+ /// `BTRFS_QGROUP_STATUS_FLAG_INCONSISTENT`
+ pub const INCONSISTENT: u64 = 1 << 2;
+ /// `BTRFS_QGROUP_STATUS_FLAG_SIMPLE_MODE`
+ pub const SIMPLE_MODE: u64 = 1 << 3;
+ /// `BTRFS_QGROUP_STATUS_FLAGS_MASK`
+ pub const MASK: u64 = ON | RESCAN | INCONSISTENT | SIMPLE_MODE;
+}
+
+/// `btrfs_super_block.compat_ro_flags`
+pub mod compat_ro {
+ /// `BTRFS_FEATURE_COMPAT_RO_FREE_SPACE_TREE`
+ pub const FREE_SPACE_TREE: u64 = 1 << 0;
+ /// `BTRFS_FEATURE_COMPAT_RO_FREE_SPACE_TREE_VALID`
+ pub const FREE_SPACE_TREE_VALID: u64 = 1 << 1;
+ /// `BTRFS_FEATURE_COMPAT_RO_VERITY`
+ pub const VERITY: u64 = 1 << 2;
+ /// `BTRFS_FEATURE_COMPAT_RO_BLOCK_GROUP_TREE`
+ pub const BLOCK_GROUP_TREE: u64 = 1 << 3;
+}
+
+/// `btrfs_super_block.incompat_flags`
+pub mod incompat {
+ /// `BTRFS_FEATURE_INCOMPAT_MIXED_BACKREF`
+ pub const MIXED_BACKREF: u64 = 1 << 0;
+ /// `BTRFS_FEATURE_INCOMPAT_DEFAULT_SUBVOL`
+ pub const DEFAULT_SUBVOL: u64 = 1 << 1;
+ /// `BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS`
+ pub const MIXED_GROUPS: u64 = 1 << 2;
+ /// `BTRFS_FEATURE_INCOMPAT_COMPRESS_LZO`
+ pub const COMPRESS_LZO: u64 = 1 << 3;
+ /// `BTRFS_FEATURE_INCOMPAT_COMPRESS_ZSTD`
+ pub const COMPRESS_ZSTD: u64 = 1 << 4;
+ /// `BTRFS_FEATURE_INCOMPAT_BIG_METADATA`
+ pub const BIG_METADATA: u64 = 1 << 5;
+ /// `BTRFS_FEATURE_INCOMPAT_EXTENDED_IREF`
+ pub const EXTENDED_IREF: u64 = 1 << 6;
+ /// `BTRFS_FEATURE_INCOMPAT_RAID56`
+ pub const RAID56: u64 = 1 << 7;
+ /// `BTRFS_FEATURE_INCOMPAT_SKINNY_METADATA`
+ pub const SKINNY_METADATA: u64 = 1 << 8;
+ /// `BTRFS_FEATURE_INCOMPAT_NO_HOLES`
+ pub const NO_HOLES: u64 = 1 << 9;
+ /// `BTRFS_FEATURE_INCOMPAT_METADATA_UUID`
+ pub const METADATA_UUID: u64 = 1 << 10;
+ /// `BTRFS_FEATURE_INCOMPAT_RAID1C34`
+ pub const RAID1C34: u64 = 1 << 11;
+ /// `BTRFS_FEATURE_INCOMPAT_ZONED`
+ pub const ZONED: u64 = 1 << 12;
+ /// `BTRFS_FEATURE_INCOMPAT_EXTENT_TREE_V2`
+ pub const EXTENT_TREE_V2: u64 = 1 << 13;
+ /// `BTRFS_FEATURE_INCOMPAT_RAID_STRIPE_TREE`
+ pub const RAID_STRIPE_TREE: u64 = 1 << 14;
+ /// `BTRFS_FEATURE_INCOMPAT_ENCRYPT`
+ pub const ENCRYPT: u64 = 1 << 15;
+ /// `BTRFS_FEATURE_INCOMPAT_SIMPLE_QUOTA`
+ pub const SIMPLE_QUOTA: u64 = 1 << 16;
+ /// `BTRFS_FEATURE_INCOMPAT_REMAP_TREE`
+ pub const REMAP_TREE: u64 = 1 << 17;
+}
+
+/// `btrfs_balance_item.flags`
+pub mod balance {
+ /// `BTRFS_BALANCE_DATA`
+ pub const DATA: u64 = 1 << 0;
+ /// `BTRFS_BALANCE_SYSTEM`
+ pub const SYSTEM: u64 = 1 << 1;
+ /// `BTRFS_BALANCE_METADATA`
+ pub const METADATA: u64 = 1 << 2;
+ /// `BTRFS_BALANCE_TYPE_MASK`
+ pub const TYPE_MASK: u64 = DATA | SYSTEM | METADATA;
+ /// `BTRFS_BALANCE_FORCE`
+ pub const FORCE: u64 = 1 << 3;
+ /// `BTRFS_BALANCE_RESUME`
+ pub const RESUME: u64 = 1 << 4;
+}
+
+/// `btrfs_disk_balance_args.flags`
+pub mod balance_args {
+ /// `BTRFS_BALANCE_ARGS_PROFILES`
+ pub const PROFILES: u64 = 1 << 0;
+ /// `BTRFS_BALANCE_ARGS_USAGE`
+ pub const USAGE: u64 = 1 << 1;
+ /// `BTRFS_BALANCE_ARGS_DEVID`
+ pub const DEVID: u64 = 1 << 2;
+ /// `BTRFS_BALANCE_ARGS_DRANGE`
+ pub const DRANGE: u64 = 1 << 3;
+ /// `BTRFS_BALANCE_ARGS_VRANGE`
+ pub const VRANGE: u64 = 1 << 4;
+ /// `BTRFS_BALANCE_ARGS_LIMIT`
+ pub const LIMIT: u64 = 1 << 5;
+ /// `BTRFS_BALANCE_ARGS_LIMIT_RANGE`
+ pub const LIMIT_RANGE: u64 = 1 << 6;
+ /// `BTRFS_BALANCE_ARGS_STRIPES_RANGE`
+ pub const STRIPES_RANGE: u64 = 1 << 7;
+ /// `BTRFS_BALANCE_ARGS_CONVERT`
+ pub const CONVERT: u64 = 1 << 8;
+ /// `BTRFS_BALANCE_ARGS_SOFT`
+ pub const SOFT: u64 = 1 << 9;
+ /// `BTRFS_BALANCE_ARGS_USAGE_RANGE`
+ pub const USAGE_RANGE: u64 = 1 << 10;
+ /// `BTRFS_BALANCE_ARGS_MASK`
+ pub const MASK: u64 = PROFILES
+ | USAGE
+ | DEVID
+ | DRANGE
+ | VRANGE
+ | LIMIT
+ | LIMIT_RANGE
+ | STRIPES_RANGE
+ | USAGE_RANGE;
+}
+
+/// `btrfs_dev_replace_item`
+pub mod dev_replace {
+ /// `BTRFS_DEV_REPLACE_ITEM_CONT_READING_FROM_SRCDEV_MODE_ALWAYS`
+ pub const CONT_READING_FROM_SRCDEV_MODE_ALWAYS: u64 = 0;
+ /// `BTRFS_DEV_REPLACE_ITEM_CONT_READING_FROM_SRCDEV_MODE_AVOID`
+ pub const CONT_READING_FROM_SRCDEV_MODE_AVOID: u64 = 1;
+ /// `BTRFS_IOCTL_DEV_REPLACE_STATE_NEVER_STARTED`
+ pub const STATE_NEVER_STARTED: u64 = 0;
+ /// `BTRFS_IOCTL_DEV_REPLACE_STATE_STARTED`
+ pub const STATE_STARTED: u64 = 1;
+ /// `BTRFS_IOCTL_DEV_REPLACE_STATE_FINISHED`
+ pub const STATE_FINISHED: u64 = 2;
+ /// `BTRFS_IOCTL_DEV_REPLACE_STATE_CANCELED`
+ pub const STATE_CANCELED: u64 = 3;
+ /// `BTRFS_IOCTL_DEV_REPLACE_STATE_SUSPENDED`
+ pub const STATE_SUSPENDED: u64 = 4;
+}
+
+/// Indexes into `btrfs_dev_stats_item.values`
+pub mod dev_stat {
+ /// `BTRFS_DEV_STAT_WRITE_ERRS`
+ pub const WRITE_ERRS: usize = 0;
+ /// `BTRFS_DEV_STAT_READ_ERRS`
+ pub const READ_ERRS: usize = 1;
+ /// `BTRFS_DEV_STAT_FLUSH_ERRS`
+ pub const FLUSH_ERRS: usize = 2;
+ /// `BTRFS_DEV_STAT_CORRUPTION_ERRS`
+ pub const CORRUPTION_ERRS: usize = 3;
+ /// `BTRFS_DEV_STAT_GENERATION_ERRS`
+ pub const GENERATION_ERRS: usize = 4;
+}
+
+/// Offset of the primary superblock (`BTRFS_SUPER_INFO_OFFSET`, `ctree.h`).
+pub const SUPER_INFO_OFFSET: u64 = SZ_64K as u64;
+/// Size of the superblock (`BTRFS_SUPER_INFO_SIZE`, `ctree.h`).
+pub const SUPER_INFO_SIZE: usize = SZ_4K;
+/// Number of superblock copies (`BTRFS_SUPER_MIRROR_MAX`, `disk-io.h`).
+pub const SUPER_MIRROR_MAX: usize = 3;
+/// Mirror spacing shift (`BTRFS_SUPER_MIRROR_SHIFT`, `disk-io.h`).
+pub const SUPER_MIRROR_SHIFT: u32 = 12;
diff --git a/rust/src/disk/mod.rs b/rust/src/disk/mod.rs
new file mode 100644
index 000000000000..6e7f2329e26b
--- /dev/null
+++ b/rust/src/disk/mod.rs
@@ -0,0 +1,20 @@
+//! btrfs on-disk format definitions.
+//!
+//! Plain `#[repr(C)]` structs with little-endian integer fields, mirroring
+//! `kernel-shared/uapi/btrfs_tree.h`, in the same order. Struct and field names
+//! are the C names without the `btrfs_` prefix, in Rust casing. Every struct
+//! has a compile-time size check. There is no I/O and no parsing logic here;
+//! read them with `zerocopy`, e.g. `SuperBlock::ref_from_bytes(buf)`.
+//!
+//! Flexible array members (`btrfs_leaf`, `btrfs_node`, `btrfs_stripe_extent`)
+//! have no struct: a leaf is a [`Header`] followed by [`Item`]s, a node a header
+//! followed by [`KeyPtr`]s, and a stripe extent is a sequence of
+//! [`RaidStride`]. Trailing names and extra stripes (`btrfs_inode_ref`,
+//! `btrfs_dir_item`, `btrfs_chunk`, ...) follow the fixed part in the item
+//! payload.
+
+pub mod btrfs_tree;
+pub mod consts;
+
+pub use btrfs_tree::*;
+pub use zerocopy::little_endian::{U16 as Le16, U32 as Le32, U64 as Le64};
diff --git a/rust/src/lib.rs b/rust/src/lib.rs
new file mode 100644
index 000000000000..d7c1e85fa6ae
--- /dev/null
+++ b/rust/src/lib.rs
@@ -0,0 +1,6 @@
+//! Experimental Rust implementation of btrfs-progs.
+//!
+//! [`disk`] has the on-disk format. The commands are in the binary.
+
+pub mod disk;
+pub mod sizes;
diff --git a/rust/src/sizes.rs b/rust/src/sizes.rs
new file mode 100644
index 000000000000..af4d44cbf5f5
--- /dev/null
+++ b/rust/src/sizes.rs
@@ -0,0 +1,14 @@
+//! Generic binary size constants mirroring `<linux/sizes.h>`.
+
+pub const SZ_1K: usize = 1024;
+pub const SZ_2K: usize = 2 * 1024;
+pub const SZ_4K: usize = 4 * 1024;
+pub const SZ_8K: usize = 8 * 1024;
+pub const SZ_16K: usize = 16 * 1024;
+pub const SZ_32K: usize = 32 * 1024;
+pub const SZ_64K: usize = 64 * 1024;
+
+pub const SZ_1M: usize = 1024 * 1024;
+pub const SZ_2M: usize = 2 * 1024 * 1024;
+pub const SZ_4M: usize = 4 * 1024 * 1024;
+pub const SZ_1G: usize = 1024 * 1024 * 1024;
diff --git a/rust/tests/parse.rs b/rust/tests/parse.rs
new file mode 100644
index 000000000000..28dc77695ca6
--- /dev/null
+++ b/rust/tests/parse.rs
@@ -0,0 +1,82 @@
+use btrfs_rs::disk::consts::{magic, objectid};
+use btrfs_rs::disk::{
+ DiskBalanceArgs, DiskKey, Header, Key, KeyType, RootItem, SuperBlock, LEGACY_ROOT_ITEM_SIZE,
+};
+use btrfs_rs::sizes::*;
+use zerocopy::{FromBytes, FromZeros, IntoBytes};
+
+#[test]
+fn superblock_roundtrip() {
+ let mut sb = SuperBlock::new_zeroed();
+ sb.magic = magic::BTRFS.into();
+ sb.nodesize = (SZ_16K as u32).into();
+ sb.label[..4].copy_from_slice(b"test");
+ sb.super_roots[3].tree_root_level = 2;
+
+ let bytes = sb.as_bytes();
+ assert_eq!(bytes.len(), SZ_4K);
+
+ let parsed = SuperBlock::ref_from_bytes(bytes).unwrap();
+ assert_eq!(parsed.magic.get(), magic::BTRFS);
+ assert_eq!(parsed.nodesize.get(), SZ_16K as u32);
+ assert_eq!(&parsed.label[..4], b"test");
+ assert_eq!(parsed.super_roots[3].tree_root_level, 2);
+ assert!(SuperBlock::ref_from_bytes(&bytes[..(SZ_4K - 1)]).is_err());
+}
+
+#[test]
+fn parse_at_unaligned_offset() {
+ let mut hdr = Header::new_zeroed();
+ hdr.bytenr = 0x1234_5678_9abc.into();
+ hdr.nritems = 7.into();
+
+ let mut buf = vec![0u8; 1 + size_of::<Header>()];
+ buf[1..].copy_from_slice(hdr.as_bytes());
+
+ let parsed = Header::ref_from_bytes(&buf[1..]).unwrap();
+ assert_eq!(parsed.bytenr.get(), 0x1234_5678_9abc);
+ assert_eq!(parsed.nritems.get(), 7);
+}
+
+#[test]
+fn key_order_and_conversion() {
+ let a = Key {
+ objectid: 5,
+ r#type: KeyType::INODE_ITEM,
+ offset: u64::MAX,
+ };
+ let b = Key {
+ objectid: 5,
+ r#type: KeyType::INODE_REF,
+ offset: 0,
+ };
+ let c = Key {
+ objectid: objectid::BALANCE,
+ r#type: KeyType::TEMPORARY_ITEM,
+ offset: 0,
+ };
+ assert!(a < b && b < c);
+
+ let disk = DiskKey::from(&c);
+ assert_eq!(disk.as_bytes().len(), 17);
+ assert_eq!(Key::from(&disk), c);
+ assert_eq!(KeyType::BALANCE_ITEM, KeyType::TEMPORARY_ITEM);
+}
+
+#[test]
+fn legacy_root_item_is_a_prefix() {
+ assert!(LEGACY_ROOT_ITEM_SIZE < size_of::<RootItem>());
+ assert_eq!(LEGACY_ROOT_ITEM_SIZE, 239);
+}
+
+#[test]
+fn balance_args_union_views() {
+ let mut args = DiskBalanceArgs::new_zeroed();
+ args.usage = (5u64 | (9u64 << 32)).into();
+ args.limit = (7u64 | (11u64 << 32)).into();
+ assert_eq!((args.usage_min(), args.usage_max()), (5, 9));
+ assert_eq!((args.limit_min(), args.limit_max()), (7, 11));
+
+ let bytes = args.as_bytes();
+ assert_eq!(&bytes[8..16], &[5, 0, 0, 0, 9, 0, 0, 0]);
+}
--
2.56.1
^ permalink raw reply related [flat|nested] 16+ messages in thread* [PATCH 02/15] btrfs-progs: rust: add btrfs-rs with inspect-internal dump-super
2026-12-01 7:56 [PATCH RFC 00/15] btrfs-progs: experimental rust support Qu Wenruo
2026-12-01 7:56 ` [PATCH 01/15] btrfs-progs: rust: introduce on-disk format definitions Qu Wenruo
@ 2026-12-01 7:56 ` Qu Wenruo
2026-12-01 7:56 ` [PATCH 03/15] btrfs-progs: rust: disk: add the tree block layout Qu Wenruo
` (12 subsequent siblings)
14 siblings, 0 replies; 16+ messages in thread
From: Qu Wenruo @ 2026-12-01 7:56 UTC (permalink / raw)
To: linux-btrfs
Add the btrfs-rs binary, with the same command and subcommand layout as
btrfs, parsed by clap. Only "inspect-internal dump-super" exists so far.
It has the same output and options as the C version, except for the
deprecated -i and "-s <bytenr>". The options -a, -s and --bytenr are
mutually exclusive instead of the last one winning.
Commands are one module per C file in cmds/. Printing keys and chunk
items is in print_tree.rs, as other commands will print them too.
The superblock checksum is verified for all four csum types, with the
crc32c, xxhash-rust, sha2 and blake2 crates, in disk/csum.rs. Zoned
devices are not handled yet.
The disk module gets super_offset().
Signed-off-by: Qu Wenruo <wqu@suse.com>
---
rust/Cargo.lock | 288 ++++++++++++-
rust/Cargo.toml | 5 +
rust/README.md | 3 +
rust/src/cmds/inspect_dump_super.rs | 227 ++++++++++
rust/src/cmds/inspect_internal.rs | 23 +
rust/src/cmds/mod.rs | 24 ++
rust/src/disk/consts.rs | 9 +
rust/src/disk/csum.rs | 49 +++
rust/src/disk/mod.rs | 3 +
rust/src/main.rs | 49 +++
rust/src/messages.rs | 21 +
rust/src/print_tree.rs | 632 ++++++++++++++++++++++++++++
rust/src/sizes.rs | 3 +
rust/src/util.rs | 11 +
rust/tests/parse.rs | 9 +-
15 files changed, 1354 insertions(+), 2 deletions(-)
create mode 100644 rust/src/cmds/inspect_dump_super.rs
create mode 100644 rust/src/cmds/inspect_internal.rs
create mode 100644 rust/src/cmds/mod.rs
create mode 100644 rust/src/disk/csum.rs
create mode 100644 rust/src/main.rs
create mode 100644 rust/src/messages.rs
create mode 100644 rust/src/print_tree.rs
create mode 100644 rust/src/util.rs
diff --git a/rust/Cargo.lock b/rust/Cargo.lock
index 293784f98fda..51750379a617 100644
--- a/rust/Cargo.lock
+++ b/rust/Cargo.lock
@@ -2,13 +2,211 @@
# It is not intended for manual editing.
version = 4
+[[package]]
+name = "anstream"
+version = "1.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d"
+dependencies = [
+ "anstyle",
+ "anstyle-parse",
+ "anstyle-query",
+ "anstyle-wincon",
+ "colorchoice",
+ "is_terminal_polyfill",
+ "utf8parse",
+]
+
+[[package]]
+name = "anstyle"
+version = "1.0.14"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000"
+
+[[package]]
+name = "anstyle-parse"
+version = "1.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e"
+dependencies = [
+ "utf8parse",
+]
+
+[[package]]
+name = "anstyle-query"
+version = "1.1.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc"
+dependencies = [
+ "windows-sys",
+]
+
+[[package]]
+name = "anstyle-wincon"
+version = "3.0.11"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d"
+dependencies = [
+ "anstyle",
+ "once_cell_polyfill",
+ "windows-sys",
+]
+
+[[package]]
+name = "blake2"
+version = "0.10.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "46502ad458c9a52b69d4d4d32775c788b7a1b85e8bc9d482d92250fc0e3f8efe"
+dependencies = [
+ "digest",
+]
+
+[[package]]
+name = "block-buffer"
+version = "0.10.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71"
+dependencies = [
+ "generic-array",
+]
+
[[package]]
name = "btrfs-rs"
version = "0.0.0"
dependencies = [
+ "blake2",
+ "clap",
+ "crc32c",
+ "sha2",
+ "xxhash-rust",
"zerocopy",
]
+[[package]]
+name = "cfg-if"
+version = "1.0.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"
+
+[[package]]
+name = "clap"
+version = "4.6.10"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "50066ca966813ca8957ee15361752f19424a8ff620dbe9c8993d9f99d99b04b3"
+dependencies = [
+ "clap_builder",
+ "clap_derive",
+]
+
+[[package]]
+name = "clap_builder"
+version = "4.6.10"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a0ed97c96ef4efb3cc84e09fa388df4463e7cc3224ec38d7b1d9e45749333590"
+dependencies = [
+ "anstream",
+ "anstyle",
+ "clap_lex",
+ "strsim",
+]
+
+[[package]]
+name = "clap_derive"
+version = "4.6.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b4c174f11f949b9ca8c60580925e282b9cbd5454750e506f08648b2038080cd7"
+dependencies = [
+ "heck",
+ "proc-macro2",
+ "quote",
+ "syn 3.0.10",
+]
+
+[[package]]
+name = "clap_lex"
+version = "1.1.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e0921b3876b3a1df8a1c9f912e7f94342458022c2e84288015893d83c4d62a79"
+
+[[package]]
+name = "colorchoice"
+version = "1.0.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570"
+
+[[package]]
+name = "cpufeatures"
+version = "0.2.17"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280"
+dependencies = [
+ "libc",
+]
+
+[[package]]
+name = "crc32c"
+version = "0.6.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7f132a176423ee852e8f0a35d43088d1850966b50745be818a88b76f64b1c6cb"
+dependencies = [
+ "rustc_version",
+]
+
+[[package]]
+name = "crypto-common"
+version = "0.1.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a"
+dependencies = [
+ "generic-array",
+ "typenum",
+]
+
+[[package]]
+name = "digest"
+version = "0.10.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
+dependencies = [
+ "block-buffer",
+ "crypto-common",
+ "subtle",
+]
+
+[[package]]
+name = "generic-array"
+version = "0.14.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a"
+dependencies = [
+ "typenum",
+ "version_check",
+]
+
+[[package]]
+name = "heck"
+version = "0.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
+
+[[package]]
+name = "is_terminal_polyfill"
+version = "1.70.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695"
+
+[[package]]
+name = "libc"
+version = "0.2.191"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"
+
+[[package]]
+name = "once_cell_polyfill"
+version = "1.70.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe"
+
[[package]]
name = "proc-macro2"
version = "1.0.107"
@@ -27,6 +225,44 @@ dependencies = [
"proc-macro2",
]
+[[package]]
+name = "rustc_version"
+version = "0.4.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92"
+dependencies = [
+ "semver",
+]
+
+[[package]]
+name = "semver"
+version = "1.0.28"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd"
+
+[[package]]
+name = "sha2"
+version = "0.10.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283"
+dependencies = [
+ "cfg-if",
+ "cpufeatures",
+ "digest",
+]
+
+[[package]]
+name = "strsim"
+version = "0.11.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"
+
+[[package]]
+name = "subtle"
+version = "2.6.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"
+
[[package]]
name = "syn"
version = "2.0.119"
@@ -38,12 +274,62 @@ dependencies = [
"unicode-ident",
]
+[[package]]
+name = "syn"
+version = "3.0.10"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "unicode-ident",
+]
+
+[[package]]
+name = "typenum"
+version = "1.20.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"
+
[[package]]
name = "unicode-ident"
version = "1.0.27"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"
+[[package]]
+name = "utf8parse"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821"
+
+[[package]]
+name = "version_check"
+version = "0.9.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
+
+[[package]]
+name = "windows-link"
+version = "0.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
+
+[[package]]
+name = "windows-sys"
+version = "0.61.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"
+dependencies = [
+ "windows-link",
+]
+
+[[package]]
+name = "xxhash-rust"
+version = "0.8.21"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "40de123dbb523ebcc00d61ec01840ad192578afc378d859f3429caa38308fad5"
+
[[package]]
name = "zerocopy"
version = "0.8.66"
@@ -61,5 +347,5 @@ checksum = "f89bca3b96ceb3cfcb4572790402f977442270d252b9a8504ebc258760c55f94"
dependencies = [
"proc-macro2",
"quote",
- "syn",
+ "syn 2.0.119",
]
diff --git a/rust/Cargo.toml b/rust/Cargo.toml
index bc832e7218f8..1353123f34aa 100644
--- a/rust/Cargo.toml
+++ b/rust/Cargo.toml
@@ -8,3 +8,8 @@ publish = false
[dependencies]
zerocopy = { version = "0.8", features = ["derive"] }
+clap = { version = "4", features = ["derive"] }
+crc32c = "0.6"
+xxhash-rust = { version = "0.8", features = ["xxh64"] }
+sha2 = "0.10"
+blake2 = "0.10"
diff --git a/rust/README.md b/rust/README.md
index b2b3c9446ac2..b1e88f9a6b82 100644
--- a/rust/README.md
+++ b/rust/README.md
@@ -11,6 +11,9 @@ For evaluation only. Not part of the default build and not installed.
## Layout
- `src/disk/`: on-disk format definitions (no I/O).
+- `src/main.rs`, `src/cmds/`: the `btrfs-rs` command, with the same command and
+ subcommand layout as `btrfs`. Implemented so far: `inspect-internal
+ dump-super`.
## Building
diff --git a/rust/src/cmds/inspect_dump_super.rs b/rust/src/cmds/inspect_dump_super.rs
new file mode 100644
index 000000000000..df5394c12338
--- /dev/null
+++ b/rust/src/cmds/inspect_dump_super.rs
@@ -0,0 +1,227 @@
+//! `btrfs-rs inspect-internal dump-super`, see `cmds/inspect-dump-super.c`.
+//!
+//! The deprecated options of the C version are not supported: `-i`, and `-s`
+//! with a byte offset (use `--bytenr`).
+
+use std::fs::File;
+use std::io::{self, BufWriter, Seek, SeekFrom, Write};
+use std::os::unix::fs::{FileExt, FileTypeExt};
+use std::path::{Path, PathBuf};
+
+use btrfs_rs::disk::consts::{magic, super_offset, SUPER_INFO_SIZE, SUPER_MIRROR_MAX};
+use btrfs_rs::disk::SuperBlock;
+use clap::Args as ClapArgs;
+use zerocopy::{FromZeros, IntoBytes};
+
+use super::{Failed, Result};
+use crate::messages::{error, error_flushing, strerror};
+use crate::print_tree::print_superblock;
+
+#[derive(ClapArgs)]
+#[command(override_usage = "btrfs-rs inspect-internal dump-super [options] device [device...]")]
+pub struct Args {
+ /// print full superblock information, backup roots etc.
+ #[arg(short, long)]
+ full: bool,
+
+ /// print information about all superblocks
+ #[arg(short, long, conflicts_with_all = ["mirror", "bytenr"])]
+ all: bool,
+
+ /// specify which copy to print out (values: 0, 1, 2)
+ #[arg(
+ short = 's',
+ long = "super",
+ value_name = "NUMBER",
+ value_parser = clap::value_parser!(u8).range(..3),
+ conflicts_with = "bytenr"
+ )]
+ mirror: Option<u8>,
+
+ /// attempt to dump superblocks with bad magic
+ #[arg(short = 'F', long)]
+ force: bool,
+
+ /// specify alternate superblock offset
+ #[arg(long, value_name = "BYTENR")]
+ bytenr: Option<u64>,
+
+ #[arg(required = true, value_name = "device")]
+ devices: Vec<PathBuf>,
+}
+
+fn load_and_dump_sb(
+ out: &mut impl Write,
+ path: &Path,
+ sb_bytenr: u64,
+ full: bool,
+ force: bool,
+) -> Result {
+ let name = path.display();
+
+ let mut file = match File::open(path) {
+ Ok(file) => file,
+ Err(e) => {
+ error_flushing(out, format!("cannot open {name}: {}", strerror(&e)));
+ return Err(Failed);
+ }
+ };
+ let file_type = match file.metadata() {
+ Ok(metadata) => metadata.file_type(),
+ Err(e) => {
+ error_flushing(
+ out,
+ format!(
+ "unable to stat {name} to when loading superblock: {}",
+ strerror(&e)
+ ),
+ );
+ return Err(Failed);
+ }
+ };
+ if file_type.is_block_device() || file_type.is_file() {
+ let last_byte = match file.seek(SeekFrom::End(0)) {
+ Ok(last_byte) => last_byte,
+ Err(e) => {
+ error_flushing(
+ out,
+ format!("cannot read end of file {name}: {}", strerror(&e)),
+ );
+ return Err(Failed);
+ }
+ };
+ // No such superblock copy on a device this small
+ if sb_bytenr > last_byte {
+ return Ok(());
+ }
+ }
+
+ let mut sb = SuperBlock::new_zeroed();
+ match file.read_at(sb.as_mut_bytes(), sb_bytenr) {
+ Ok(SUPER_INFO_SIZE) => {}
+ // The device is too short for this copy
+ Ok(0) => return Ok(()),
+ Ok(read) => {
+ error_flushing(
+ out,
+ format!(
+ "failed to read the superblock on {name} at {sb_bytenr} read {read}/{SUPER_INFO_SIZE} bytes"
+ ),
+ );
+ error("error = 'Success', errno = 0");
+ return Err(Failed);
+ }
+ Err(e) => {
+ error_flushing(
+ out,
+ format!(
+ "failed to read the superblock on {name} at {sb_bytenr} read {}/{SUPER_INFO_SIZE} bytes",
+ u64::MAX
+ ),
+ );
+ error(format!(
+ "error = '{}', errno = {}",
+ strerror(&e),
+ e.raw_os_error().unwrap_or(0)
+ ));
+ return Err(Failed);
+ }
+ }
+
+ writeln!(out, "superblock: bytenr={sb_bytenr}, device={name}")?;
+ writeln!(
+ out,
+ "---------------------------------------------------------"
+ )?;
+ if sb.magic.get() != magic::BTRFS && !force {
+ error_flushing(
+ out,
+ format!(
+ "bad magic on superblock on {name} at {sb_bytenr} (use --force to dump it anyway)"
+ ),
+ );
+ return Err(Failed);
+ }
+ print_superblock(out, &sb, full)?;
+ writeln!(out)?;
+ Ok(())
+}
+
+pub fn run(args: Args) -> Result {
+ let sb_bytenr = match (args.mirror, args.bytenr) {
+ (Some(mirror), _) => super_offset(usize::from(mirror)),
+ (None, Some(bytenr)) => bytenr,
+ (None, None) => super_offset(0),
+ };
+ let mut out = BufWriter::new(io::stdout().lock());
+
+ for path in &args.devices {
+ if args.all {
+ for mirror in 0..SUPER_MIRROR_MAX {
+ let sb_bytenr = super_offset(mirror);
+ load_and_dump_sb(&mut out, path, sb_bytenr, args.full, args.force)?;
+ }
+ } else {
+ load_and_dump_sb(&mut out, path, sb_bytenr, args.full, args.force)?;
+ }
+ }
+ out.flush()?;
+ Ok(())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ /// A device file with one superblock at the primary location, removed on
+ /// drop.
+ struct TestDevice(PathBuf);
+
+ impl TestDevice {
+ fn new(name: &str, magic: u64) -> TestDevice {
+ let path =
+ std::env::temp_dir().join(format!("btrfs-rs-{}-{name}.img", std::process::id()));
+ let mut sb = SuperBlock::new_zeroed();
+ sb.magic = magic.into();
+
+ let mut image = vec![0u8; super_offset(0) as usize];
+ image.extend_from_slice(sb.as_bytes());
+ std::fs::write(&path, image).unwrap();
+ TestDevice(path)
+ }
+
+ /// The result, and the number of bytes written
+ fn dump(&self, bytenr: u64, force: bool) -> (Result, usize) {
+ let mut out = Vec::new();
+ let result = load_and_dump_sb(&mut out, &self.0, bytenr, false, force);
+ (result, out.len())
+ }
+ }
+
+ impl Drop for TestDevice {
+ fn drop(&mut self) {
+ let _ = std::fs::remove_file(&self.0);
+ }
+ }
+
+ #[test]
+ fn bad_magic_needs_force() {
+ let device = TestDevice::new("magic", 0);
+ assert!(device.dump(super_offset(0), false).0.is_err());
+ assert!(device.dump(super_offset(0), true).0.is_ok());
+ }
+
+ #[test]
+ fn a_copy_beyond_the_end_of_the_device_is_skipped() {
+ let device = TestDevice::new("end", magic::BTRFS);
+ let (result, written) = device.dump(super_offset(1), false);
+ assert!(result.is_ok());
+ assert_eq!(written, 0);
+ }
+
+ #[test]
+ fn a_partial_copy_is_an_error() {
+ let device = TestDevice::new("partial", magic::BTRFS);
+ assert!(device.dump(super_offset(0) + 100, false).0.is_err());
+ }
+}
diff --git a/rust/src/cmds/inspect_internal.rs b/rust/src/cmds/inspect_internal.rs
new file mode 100644
index 000000000000..617f113c1d0f
--- /dev/null
+++ b/rust/src/cmds/inspect_internal.rs
@@ -0,0 +1,23 @@
+//! `btrfs-rs inspect-internal`, see `cmds/inspect.c`.
+
+use clap::{Args as ClapArgs, Subcommand};
+
+use super::{inspect_dump_super, Result};
+
+#[derive(ClapArgs)]
+pub struct Args {
+ #[command(subcommand)]
+ command: Command,
+}
+
+#[derive(Subcommand)]
+enum Command {
+ /// Dump superblock from a device in a textual form
+ DumpSuper(inspect_dump_super::Args),
+}
+
+pub fn run(args: Args) -> Result {
+ match args.command {
+ Command::DumpSuper(args) => inspect_dump_super::run(args),
+ }
+}
diff --git a/rust/src/cmds/mod.rs b/rust/src/cmds/mod.rs
new file mode 100644
index 000000000000..8b331f6e27ee
--- /dev/null
+++ b/rust/src/cmds/mod.rs
@@ -0,0 +1,24 @@
+//! One module per command, named like the C files in `cmds/`.
+
+use std::io;
+
+use crate::messages::{error, strerror};
+
+pub mod inspect_dump_super;
+pub mod inspect_internal;
+
+/// The command has failed and already reported why. The exit status is 1.
+#[derive(Debug)]
+pub struct Failed;
+
+pub type Result = std::result::Result<(), Failed>;
+
+impl From<io::Error> for Failed {
+ /// Failure to write the output. A closed pipe is not worth a message.
+ fn from(e: io::Error) -> Failed {
+ if e.kind() != io::ErrorKind::BrokenPipe {
+ error(format!("failed to write output: {}", strerror(&e)));
+ }
+ Failed
+ }
+}
diff --git a/rust/src/disk/consts.rs b/rust/src/disk/consts.rs
index 981308582389..33aa5cb6f14e 100644
--- a/rust/src/disk/consts.rs
+++ b/rust/src/disk/consts.rs
@@ -524,3 +524,12 @@ pub const SUPER_INFO_SIZE: usize = SZ_4K;
pub const SUPER_MIRROR_MAX: usize = 3;
/// Mirror spacing shift (`BTRFS_SUPER_MIRROR_SHIFT`, `disk-io.h`).
pub const SUPER_MIRROR_SHIFT: u32 = 12;
+
+/// Offset of superblock copy `mirror` (`btrfs_sb_offset()`).
+pub const fn super_offset(mirror: usize) -> u64 {
+ if mirror == 0 {
+ SUPER_INFO_OFFSET
+ } else {
+ (SZ_16K as u64) << (SUPER_MIRROR_SHIFT * mirror as u32)
+ }
+}
diff --git a/rust/src/disk/csum.rs b/rust/src/disk/csum.rs
new file mode 100644
index 000000000000..c718b8a150dd
--- /dev/null
+++ b/rust/src/disk/csum.rs
@@ -0,0 +1,49 @@
+//! Checksum types, as listed in `btrfs_csums[]`.
+
+use crate::disk::consts::{csum_type, limits};
+use blake2::digest::consts::U32;
+use blake2::{Blake2b, Digest};
+use sha2::Sha256;
+
+pub struct Info {
+ pub name: &'static str,
+ pub size: usize,
+}
+
+pub fn info(csum_type: u16) -> Option<Info> {
+ match csum_type {
+ csum_type::CRC32 => Some(Info {
+ name: "crc32c",
+ size: 4,
+ }),
+ csum_type::XXHASH => Some(Info {
+ name: "xxhash64",
+ size: 8,
+ }),
+ csum_type::SHA256 => Some(Info {
+ name: "sha256",
+ size: 32,
+ }),
+ csum_type::BLAKE2 => Some(Info {
+ name: "blake2b",
+ size: 32,
+ }),
+ _ => None,
+ }
+}
+
+/// The checksum of `data`, padded with zeros to `CSUM_SIZE`. `None` for an
+/// unknown type.
+pub fn compute(csum_type: u16, data: &[u8]) -> Option<[u8; limits::CSUM_SIZE]> {
+ let mut out = [0u8; limits::CSUM_SIZE];
+ match csum_type {
+ csum_type::CRC32 => out[..4].copy_from_slice(&crc32c::crc32c(data).to_le_bytes()),
+ csum_type::XXHASH => {
+ out[..8].copy_from_slice(&xxhash_rust::xxh64::xxh64(data, 0).to_le_bytes())
+ }
+ csum_type::SHA256 => out.copy_from_slice(&Sha256::digest(data)),
+ csum_type::BLAKE2 => out.copy_from_slice(&Blake2b::<U32>::digest(data)),
+ _ => return None,
+ }
+ Some(out)
+}
diff --git a/rust/src/disk/mod.rs b/rust/src/disk/mod.rs
index 6e7f2329e26b..104ea54b159e 100644
--- a/rust/src/disk/mod.rs
+++ b/rust/src/disk/mod.rs
@@ -6,6 +6,8 @@
//! has a compile-time size check. There is no I/O and no parsing logic here;
//! read them with `zerocopy`, e.g. `SuperBlock::ref_from_bytes(buf)`.
//!
+//! [`csum`] computes the checksums.
+//!
//! Flexible array members (`btrfs_leaf`, `btrfs_node`, `btrfs_stripe_extent`)
//! have no struct: a leaf is a [`Header`] followed by [`Item`]s, a node a header
//! followed by [`KeyPtr`]s, and a stripe extent is a sequence of
@@ -15,6 +17,7 @@
pub mod btrfs_tree;
pub mod consts;
+pub mod csum;
pub use btrfs_tree::*;
pub use zerocopy::little_endian::{U16 as Le16, U32 as Le32, U64 as Le64};
diff --git a/rust/src/main.rs b/rust/src/main.rs
new file mode 100644
index 000000000000..06a2a8da25ac
--- /dev/null
+++ b/rust/src/main.rs
@@ -0,0 +1,49 @@
+mod cmds;
+mod messages;
+mod print_tree;
+mod util;
+
+use std::process::ExitCode;
+
+use clap::{Parser, Subcommand};
+
+/// Same command and subcommand layout as `btrfs`.
+#[derive(Parser)]
+#[command(
+ name = "btrfs-rs",
+ version,
+ about = "Experimental Rust implementation of btrfs-progs",
+ infer_subcommands = true,
+ arg_required_else_help = true
+)]
+struct Cli {
+ #[command(subcommand)]
+ command: Command,
+}
+
+#[derive(Subcommand)]
+enum Command {
+ /// Query various internal information
+ InspectInternal(cmds::inspect_internal::Args),
+}
+
+fn clap_exit(e: clap::Error) -> ExitCode {
+ let _ = e.print();
+ // Usage errors exit with 1 like `btrfs`, help and version with 0
+ ExitCode::from(if e.use_stderr() { 1 } else { 0 })
+}
+
+fn main() -> ExitCode {
+ let cli = match Cli::try_parse() {
+ Ok(cli) => cli,
+ Err(e) => return clap_exit(e),
+ };
+
+ let result = match cli.command {
+ Command::InspectInternal(args) => cmds::inspect_internal::run(args),
+ };
+ match result {
+ Ok(()) => ExitCode::SUCCESS,
+ Err(cmds::Failed) => ExitCode::FAILURE,
+ }
+}
diff --git a/rust/src/messages.rs b/rust/src/messages.rs
new file mode 100644
index 000000000000..6e7d713d132e
--- /dev/null
+++ b/rust/src/messages.rs
@@ -0,0 +1,21 @@
+use std::fmt::Display;
+use std::io::{self, Write};
+
+pub fn error(msg: impl Display) {
+ eprintln!("ERROR: {msg}");
+}
+
+/// Flush the buffered output first, so that it shows up before the message.
+pub fn error_flushing(out: &mut impl Write, msg: impl Display) {
+ let _ = out.flush();
+ error(msg);
+}
+
+/// The text of an I/O error without the "(os error N)" suffix, like `%m`.
+pub fn strerror(e: &io::Error) -> String {
+ let text = e.to_string();
+ match text.find(" (os error") {
+ Some(end) => text[..end].to_string(),
+ None => text,
+ }
+}
diff --git a/rust/src/print_tree.rs b/rust/src/print_tree.rs
new file mode 100644
index 000000000000..61ab5549be49
--- /dev/null
+++ b/rust/src/print_tree.rs
@@ -0,0 +1,632 @@
+//! Text output of on-disk structures that several commands print, see
+//! `kernel-shared/print-tree.c`.
+
+use std::io::{self, Write};
+
+use btrfs_rs::disk::consts::{
+ block_group, compat_ro, header_flag, incompat, limits, magic, objectid, super_flag,
+};
+use btrfs_rs::disk::{csum, Chunk, DiskKey, KeyType, RootBackup, Stripe, SuperBlock};
+use zerocopy::{FromBytes, IntoBytes};
+
+use crate::messages::error_flushing;
+use crate::util::uuid_unparse;
+
+fn qgroup_subvolid(qgroupid: u64) -> u64 {
+ qgroupid & ((1 << btrfs_rs::disk::consts::qgroup::LEVEL_SHIFT) - 1)
+}
+
+fn key_type_name(key_type: KeyType) -> Option<&'static str> {
+ Some(match key_type {
+ KeyType::INODE_ITEM => "INODE_ITEM",
+ KeyType::INODE_REF => "INODE_REF",
+ KeyType::INODE_EXTREF => "INODE_EXTREF",
+ KeyType::DIR_ITEM => "DIR_ITEM",
+ KeyType::DIR_INDEX => "DIR_INDEX",
+ KeyType::DIR_LOG_ITEM => "DIR_LOG_ITEM",
+ KeyType::DIR_LOG_INDEX => "DIR_LOG_INDEX",
+ KeyType::XATTR_ITEM => "XATTR_ITEM",
+ KeyType::FSCRYPT_INODE_CTX => "FSCRYPT_INODE_CTX",
+ KeyType::FSCRYPT_CTX => "FSCRYPT_CTX",
+ KeyType::VERITY_DESC_ITEM => "VERITY_DESC_ITEM",
+ KeyType::VERITY_MERKLE_ITEM => "VERITY_MERKLE_ITEM",
+ KeyType::ORPHAN_ITEM => "ORPHAN_ITEM",
+ KeyType::ROOT_ITEM => "ROOT_ITEM",
+ KeyType::ROOT_REF => "ROOT_REF",
+ KeyType::ROOT_BACKREF => "ROOT_BACKREF",
+ KeyType::EXTENT_ITEM => "EXTENT_ITEM",
+ KeyType::METADATA_ITEM => "METADATA_ITEM",
+ KeyType::TREE_BLOCK_REF => "TREE_BLOCK_REF",
+ KeyType::SHARED_BLOCK_REF => "SHARED_BLOCK_REF",
+ KeyType::EXTENT_DATA_REF => "EXTENT_DATA_REF",
+ KeyType::SHARED_DATA_REF => "SHARED_DATA_REF",
+ KeyType::EXTENT_REF_V0 => "EXTENT_REF_V0",
+ KeyType::EXTENT_OWNER_REF => "EXTENT_OWNER_REF",
+ KeyType::CSUM_ITEM => "CSUM_ITEM",
+ KeyType::EXTENT_CSUM => "EXTENT_CSUM",
+ KeyType::EXTENT_DATA => "EXTENT_DATA",
+ KeyType::BLOCK_GROUP_ITEM => "BLOCK_GROUP_ITEM",
+ KeyType::FREE_SPACE_INFO => "FREE_SPACE_INFO",
+ KeyType::FREE_SPACE_EXTENT => "FREE_SPACE_EXTENT",
+ KeyType::FREE_SPACE_BITMAP => "FREE_SPACE_BITMAP",
+ KeyType::CHUNK_ITEM => "CHUNK_ITEM",
+ KeyType::DEV_ITEM => "DEV_ITEM",
+ KeyType::DEV_EXTENT => "DEV_EXTENT",
+ KeyType::TEMPORARY_ITEM => "TEMPORARY_ITEM",
+ KeyType::DEV_REPLACE => "DEV_REPLACE",
+ KeyType::STRING_ITEM => "STRING_ITEM",
+ KeyType::QGROUP_STATUS => "QGROUP_STATUS",
+ KeyType::QGROUP_RELATION => "QGROUP_RELATION",
+ KeyType::QGROUP_INFO => "QGROUP_INFO",
+ KeyType::QGROUP_LIMIT => "QGROUP_LIMIT",
+ KeyType::PERSISTENT_ITEM => "PERSISTENT_ITEM",
+ KeyType::UUID_KEY_SUBVOL => "UUID_KEY_SUBVOL",
+ KeyType::UUID_KEY_RECEIVED_SUBVOL => "UUID_KEY_RECEIVED_SUBVOL",
+ KeyType::RAID_STRIPE => "RAID_STRIPE",
+ KeyType::IDENTITY_REMAP => "IDENTITY_REMAP",
+ KeyType::REMAP => "REMAP",
+ KeyType::REMAP_BACKREF => "REMAP_BACKREF",
+ _ => return None,
+ })
+}
+
+fn key_type_string(objectid: u64, key_type: KeyType) -> String {
+ if key_type.0 == 0 && objectid == btrfs_rs::disk::consts::objectid::FREE_SPACE {
+ return "UNTYPED".to_string();
+ }
+ match key_type_name(key_type) {
+ Some(name) => name.to_string(),
+ None => format!("UNKNOWN.{}", key_type.0),
+ }
+}
+
+fn objectid_string(id: u64, key_type: KeyType) -> String {
+ match key_type {
+ KeyType::PERSISTENT_ITEM => {
+ return if id == objectid::DEV_STATS {
+ "DEV_STATS".to_string()
+ } else {
+ id.to_string()
+ };
+ }
+ KeyType::DEV_EXTENT => return id.to_string(),
+ KeyType::QGROUP_RELATION => {
+ return format!(
+ "{}/{}",
+ btrfs_rs::disk::qgroup_level(id),
+ qgroup_subvolid(id)
+ );
+ }
+ KeyType::UUID_KEY_SUBVOL | KeyType::UUID_KEY_RECEIVED_SUBVOL => {
+ return format!("0x{id:016x}");
+ }
+ _ => {}
+ }
+
+ let name = match id {
+ // Same value as DEV_ITEMS, told apart by the key type
+ objectid::ROOT_TREE if key_type == KeyType::DEV_ITEM => "DEV_ITEMS",
+ objectid::ROOT_TREE => "ROOT_TREE",
+ objectid::EXTENT_TREE => "EXTENT_TREE",
+ objectid::CHUNK_TREE => "CHUNK_TREE",
+ objectid::DEV_TREE => "DEV_TREE",
+ objectid::FS_TREE => "FS_TREE",
+ objectid::ROOT_TREE_DIR => "ROOT_TREE_DIR",
+ objectid::CSUM_TREE => "CSUM_TREE",
+ objectid::BALANCE => "BALANCE",
+ objectid::ORPHAN => "ORPHAN",
+ objectid::TREE_LOG => "TREE_LOG",
+ objectid::TREE_LOG_FIXUP => "LOG_FIXUP",
+ objectid::TREE_RELOC => "TREE_RELOC",
+ objectid::DATA_RELOC_TREE => "DATA_RELOC_TREE",
+ objectid::EXTENT_CSUM => "EXTENT_CSUM",
+ objectid::FREE_SPACE => "FREE_SPACE",
+ objectid::FREE_INO => "FREE_INO",
+ objectid::QUOTA_TREE => "QUOTA_TREE",
+ objectid::UUID_TREE => "UUID_TREE",
+ objectid::FREE_SPACE_TREE => "FREE_SPACE_TREE",
+ objectid::MULTIPLE => "MULTIPLE",
+ objectid::BLOCK_GROUP_TREE => "BLOCK_GROUP_TREE",
+ objectid::CSUM_CHANGE => "CSUM_CHANGE",
+ objectid::RAID_STRIPE_TREE => "RAID_STRIPE_TREE",
+ objectid::REMAP_TREE => "REMAP_TREE",
+ u64::MAX => "-1",
+ objectid::FIRST_CHUNK_TREE if key_type == KeyType::CHUNK_ITEM => "FIRST_CHUNK_TREE",
+ _ => return id.to_string(),
+ };
+ name.to_string()
+}
+
+/// `btrfs_print_key()`
+pub fn print_key(out: &mut impl Write, key: &DiskKey) -> io::Result<()> {
+ let id = key.objectid.get();
+ let key_type = KeyType(key.r#type);
+ let offset = key.offset.get();
+
+ write!(
+ out,
+ "key ({} {}",
+ objectid_string(id, key_type),
+ key_type_string(id, key_type)
+ )?;
+ match key_type {
+ KeyType::QGROUP_RELATION | KeyType::QGROUP_INFO | KeyType::QGROUP_LIMIT => write!(
+ out,
+ " {}/{})",
+ btrfs_rs::disk::qgroup_level(offset),
+ qgroup_subvolid(offset)
+ ),
+ KeyType::UUID_KEY_SUBVOL | KeyType::UUID_KEY_RECEIVED_SUBVOL => {
+ write!(out, " 0x{offset:016x})")
+ }
+ // The offset is the tree id, which can be negative for a reloc tree
+ KeyType::ROOT_ITEM if id == objectid::TREE_RELOC => {
+ write!(out, " {})", objectid_string(offset, key_type))
+ }
+ KeyType::ROOT_ITEM => write!(out, " {offset})"),
+ _ if offset == u64::MAX => write!(out, " -1)"),
+ _ => write!(out, " {offset})"),
+ }
+}
+
+/// The `bg_flags_to_str()` of print-tree.c, including how it joins the names.
+fn bg_flags_to_str(flags: u64) -> String {
+ let mut ret = String::new();
+ let mut empty = true;
+
+ if flags & block_group::DATA != 0 {
+ empty = false;
+ ret.push_str("DATA");
+ }
+ for (bit, name) in [
+ (block_group::METADATA, "METADATA"),
+ (block_group::SYSTEM, "SYSTEM"),
+ (block_group::METADATA_REMAP, "METADATA_REMAP"),
+ ] {
+ if flags & bit != 0 {
+ if !empty {
+ ret.push('|');
+ }
+ ret.push_str(name);
+ }
+ }
+
+ // Name of the profile, like `btrfs_bg_type_to_raid_name()`
+ let profile = if flags & block_group::RAID10 != 0 {
+ "RAID10"
+ } else if flags & block_group::RAID1 != 0 {
+ "RAID1"
+ } else if flags & block_group::RAID1C3 != 0 {
+ "RAID1C3"
+ } else if flags & block_group::RAID1C4 != 0 {
+ "RAID1C4"
+ } else if flags & block_group::DUP != 0 {
+ "DUP"
+ } else if flags & block_group::RAID0 != 0 {
+ "RAID0"
+ } else if flags & block_group::RAID5 != 0 {
+ "RAID5"
+ } else if flags & block_group::RAID6 != 0 {
+ "RAID6"
+ } else {
+ "single"
+ };
+ if !profile.starts_with("SINGLE") {
+ ret.push('|');
+ ret.push_str(profile);
+ }
+ ret
+}
+
+/// `btrfs_chunk_item_size()`
+pub fn chunk_item_size(num_stripes: usize) -> usize {
+ size_of::<Chunk>() + size_of::<Stripe>() * num_stripes
+}
+
+/// The chunk and its stripes, if the whole item is in `data`.
+fn parse_chunk_item(data: &[u8]) -> Option<(&Chunk, &[Stripe])> {
+ let (chunk, rest) = Chunk::ref_from_prefix(data).ok()?;
+ let num_stripes = usize::from(chunk.num_stripes.get());
+ if num_stripes == 0 {
+ return None;
+ }
+ let (stripes, _) = <[Stripe]>::ref_from_prefix_with_elems(rest, num_stripes).ok()?;
+ Some((chunk, stripes))
+}
+
+fn print_stripe(out: &mut impl Write, index: usize, stripe: &Stripe) -> io::Result<()> {
+ writeln!(
+ out,
+ "\t\t\tstripe {index} devid {} offset {}",
+ stripe.devid.get(),
+ stripe.offset.get()
+ )?;
+ writeln!(out, "\t\t\tdev_uuid {}", uuid_unparse(&stripe.dev_uuid))
+}
+
+/// `print_chunk_item()`, `data` is the item payload.
+pub fn print_chunk_item(out: &mut impl Write, data: &[u8]) -> io::Result<()> {
+ let Some((chunk, stripes)) = parse_chunk_item(data) else {
+ return writeln!(out, "\t\tchunk item invalid");
+ };
+
+ writeln!(
+ out,
+ "\t\tlength {} owner {} stripe_len {} type {}",
+ chunk.length.get(),
+ chunk.owner.get(),
+ chunk.stripe_len.get(),
+ bg_flags_to_str(chunk.r#type.get())
+ )?;
+ writeln!(
+ out,
+ "\t\tio_align {} io_width {} sector_size {}",
+ chunk.io_align.get(),
+ chunk.io_width.get(),
+ chunk.sector_size.get()
+ )?;
+ writeln!(
+ out,
+ "\t\tnum_stripes {} sub_stripes {}",
+ chunk.num_stripes.get(),
+ chunk.sub_stripes.get()
+ )?;
+ for (i, stripe) in stripes.iter().enumerate() {
+ print_stripe(out, i, stripe)?;
+ }
+ Ok(())
+}
+
+const SUPER_FLAGS: &[(u64, &str)] = &[
+ (header_flag::WRITTEN, "WRITTEN"),
+ (header_flag::RELOC, "RELOC"),
+ (super_flag::CHANGING_FSID, "CHANGING_FSID"),
+ (super_flag::CHANGING_FSID_V2, "CHANGING_FSID_V2"),
+ (super_flag::SEEDING, "SEEDING"),
+ (super_flag::METADUMP, "METADUMP"),
+ (super_flag::METADUMP_V2, "METADUMP_V2"),
+ (super_flag::CHANGING_BG_TREE, "CHANGING_BG_TREE"),
+ (super_flag::CHANGING_DATA_CSUM, "CHANGING_DATA_CSUM"),
+ (super_flag::CHANGING_META_CSUM, "CHANGING_META_CSUM"),
+];
+
+const COMPAT_RO_FLAGS: &[(u64, &str)] = &[
+ (compat_ro::FREE_SPACE_TREE, "FREE_SPACE_TREE"),
+ (compat_ro::FREE_SPACE_TREE_VALID, "FREE_SPACE_TREE_VALID"),
+ (compat_ro::VERITY, "VERITY"),
+ (compat_ro::BLOCK_GROUP_TREE, "BLOCK_GROUP_TREE"),
+];
+
+const INCOMPAT_FLAGS: &[(u64, &str)] = &[
+ (incompat::MIXED_BACKREF, "MIXED_BACKREF"),
+ (incompat::DEFAULT_SUBVOL, "DEFAULT_SUBVOL"),
+ (incompat::MIXED_GROUPS, "MIXED_GROUPS"),
+ (incompat::COMPRESS_LZO, "COMPRESS_LZO"),
+ (incompat::COMPRESS_ZSTD, "COMPRESS_ZSTD"),
+ (incompat::BIG_METADATA, "BIG_METADATA"),
+ (incompat::EXTENDED_IREF, "EXTENDED_IREF"),
+ (incompat::RAID56, "RAID56"),
+ (incompat::SKINNY_METADATA, "SKINNY_METADATA"),
+ (incompat::NO_HOLES, "NO_HOLES"),
+ (incompat::METADATA_UUID, "METADATA_UUID"),
+ (incompat::RAID1C34, "RAID1C34"),
+ (incompat::ZONED, "ZONED"),
+ (incompat::EXTENT_TREE_V2, "EXTENT_TREE_V2"),
+ (incompat::RAID_STRIPE_TREE, "RAID_STRIPE_TREE"),
+ (incompat::SIMPLE_QUOTA, "SIMPLE_QUOTA"),
+ (incompat::REMAP_TREE, "REMAP_TREE"),
+];
+
+fn print_readable_flag(out: &mut impl Write, flag: u64, names: &[(u64, &str)]) -> io::Result<()> {
+ if flag == 0 {
+ return Ok(());
+ }
+ let mut supported = 0;
+ for (bit, _) in names {
+ supported |= bit;
+ }
+
+ write!(out, "\t\t\t( ")?;
+ let mut first = true;
+ for (bit, name) in names {
+ if flag & bit != 0 {
+ if !first {
+ write!(out, "|\n\t\t\t ")?;
+ }
+ write!(out, "{name} ")?;
+ first = false;
+ }
+ }
+ let unknown = flag & !supported;
+ if unknown != 0 {
+ if !first {
+ write!(out, "|\n\t\t\t ")?;
+ }
+ write!(out, "unknown flag: 0x{unknown:x} ")?;
+ }
+ writeln!(out, ")")
+}
+
+fn sys_array_too_short(out: &mut impl Write, len: usize, offset: usize) {
+ error_flushing(
+ out,
+ format!("sys_array too short to read {len} bytes at offset {offset}"),
+ );
+}
+
+fn print_sys_chunk_array(out: &mut impl Write, sb: &SuperBlock) -> io::Result<()> {
+ let array_size = sb.sys_chunk_array_size.get() as usize;
+ if array_size > limits::SYSTEM_CHUNK_ARRAY_SIZE {
+ error_flushing(
+ out,
+ format!(
+ "sys_array_size {array_size} shouldn't exceed {} bytes",
+ limits::SYSTEM_CHUNK_ARRAY_SIZE
+ ),
+ );
+ return Ok(());
+ }
+ let array = &sb.sys_chunk_array[..array_size];
+
+ let mut cur_offset = 0;
+ let mut item = 0;
+ while cur_offset < array_size {
+ let Ok((key, _)) = DiskKey::ref_from_prefix(&array[cur_offset..]) else {
+ sys_array_too_short(out, size_of::<DiskKey>(), cur_offset);
+ return Ok(());
+ };
+ cur_offset += size_of::<DiskKey>();
+
+ write!(out, "\titem {item} ")?;
+ print_key(out, key)?;
+ writeln!(out)?;
+
+ if KeyType(key.r#type) != KeyType::CHUNK_ITEM {
+ error_flushing(
+ out,
+ format!(
+ "unexpected item type {} in sys_array at offset {cur_offset}",
+ key.r#type
+ ),
+ );
+ break;
+ }
+
+ // At least one chunk with one stripe must be present
+ let Ok((chunk, _)) = Chunk::ref_from_prefix(&array[cur_offset..]) else {
+ sys_array_too_short(out, chunk_item_size(1), cur_offset);
+ return Ok(());
+ };
+ let num_stripes = chunk.num_stripes.get() as usize;
+ if num_stripes == 0 {
+ error_flushing(
+ out,
+ format!(
+ "invalid number of stripes {num_stripes} in sys_array at offset {cur_offset}"
+ ),
+ );
+ break;
+ }
+ let len = chunk_item_size(num_stripes);
+ if cur_offset + len > array_size {
+ sys_array_too_short(out, len, cur_offset);
+ return Ok(());
+ }
+ print_chunk_item(out, &array[cur_offset..cur_offset + len])?;
+ cur_offset += len;
+ item += 1;
+ }
+ Ok(())
+}
+
+fn print_root_backup(
+ out: &mut impl Write,
+ backup: &RootBackup,
+ extent_tree_v2: bool,
+) -> io::Result<()> {
+ let extent_tree_str = if extent_tree_v2 {
+ "backup_block_group_root"
+ } else {
+ "backup_extent_root"
+ };
+
+ writeln!(
+ out,
+ "\t\tbackup_tree_root:\t{}\tgen: {}\tlevel: {}",
+ backup.tree_root.get(),
+ backup.tree_root_gen.get(),
+ backup.tree_root_level
+ )?;
+ writeln!(
+ out,
+ "\t\tbackup_chunk_root:\t{}\tgen: {}\tlevel: {}",
+ backup.chunk_root.get(),
+ backup.chunk_root_gen.get(),
+ backup.chunk_root_level
+ )?;
+ writeln!(
+ out,
+ "\t\t{extent_tree_str}:\t{}\tgen: {}\tlevel: {}",
+ backup.extent_root.get(),
+ backup.extent_root_gen.get(),
+ backup.extent_root_level
+ )?;
+ writeln!(
+ out,
+ "\t\tbackup_fs_root:\t\t{}\tgen: {}\tlevel: {}",
+ backup.fs_root.get(),
+ backup.fs_root_gen.get(),
+ backup.fs_root_level
+ )?;
+ writeln!(
+ out,
+ "\t\tbackup_dev_root:\t{}\tgen: {}\tlevel: {}",
+ backup.dev_root.get(),
+ backup.dev_root_gen.get(),
+ backup.dev_root_level
+ )?;
+ writeln!(
+ out,
+ "\t\tcsum_root:\t{}\tgen: {}\tlevel: {}",
+ backup.csum_root.get(),
+ backup.csum_root_gen.get(),
+ backup.csum_root_level
+ )?;
+ writeln!(out, "\t\tbackup_total_bytes:\t{}", backup.total_bytes.get())?;
+ writeln!(out, "\t\tbackup_bytes_used:\t{}", backup.bytes_used.get())?;
+ writeln!(out, "\t\tbackup_num_devices:\t{}", backup.num_devices.get())?;
+ writeln!(out)
+}
+
+fn print_backup_roots(out: &mut impl Write, sb: &SuperBlock) -> io::Result<()> {
+ let extent_tree_v2 = sb.incompat_flags.get() & incompat::EXTENT_TREE_V2 != 0;
+
+ for (i, backup) in sb.super_roots.iter().enumerate() {
+ let empty = backup.tree_root.get() == 0 && backup.tree_root_gen.get() == 0;
+ if !empty {
+ writeln!(out, "\tbackup {i}:")?;
+ print_root_backup(out, backup, extent_tree_v2)?;
+ }
+ }
+ Ok(())
+}
+
+/// Printable ASCII is shown as is, everything else as '.'
+fn printable(byte: u8) -> char {
+ if (0x20..0x7f).contains(&byte) {
+ byte as char
+ } else {
+ '.'
+ }
+}
+
+/// `btrfs_print_superblock()`
+pub fn print_superblock(out: &mut impl Write, sb: &SuperBlock, full: bool) -> io::Result<()> {
+ let metadata_uuid_present = sb.incompat_flags.get() & incompat::METADATA_UUID != 0;
+
+ let csum_type = sb.csum_type.get();
+ write!(out, "csum_type\t\t{csum_type} (")?;
+ let csum_size = match csum::info(csum_type) {
+ Some(info) => {
+ write!(out, "{}", info.name)?;
+ info.size
+ }
+ None => {
+ write!(out, "INVALID")?;
+ limits::CSUM_SIZE
+ }
+ };
+ writeln!(out, ")")?;
+ writeln!(out, "csum_size\t\t{csum_size}")?;
+
+ write!(out, "csum\t\t\t0x")?;
+ for byte in &sb.csum[..csum_size] {
+ write!(out, "{byte:02x}")?;
+ }
+ match csum::compute(csum_type, &sb.as_bytes()[limits::CSUM_SIZE..]) {
+ None => writeln!(out, " [UNKNOWN CSUM TYPE OR SIZE]")?,
+ Some(csum) if csum[..csum_size] == sb.csum[..csum_size] => writeln!(out, " [match]")?,
+ Some(_) => writeln!(out, " [DON'T MATCH]")?,
+ }
+
+ writeln!(out, "bytenr\t\t\t{}", sb.bytenr.get())?;
+ writeln!(out, "flags\t\t\t0x{:x}", sb.flags.get())?;
+ print_readable_flag(out, sb.flags.get(), SUPER_FLAGS)?;
+
+ write!(out, "magic\t\t\t")?;
+ for byte in sb.magic.as_bytes() {
+ write!(out, "{}", printable(*byte))?;
+ }
+ if sb.magic.get() == magic::BTRFS {
+ writeln!(out, " [match]")?;
+ } else {
+ writeln!(out, " [DON'T MATCH]")?;
+ }
+
+ writeln!(out, "fsid\t\t\t{}", uuid_unparse(&sb.fsid))?;
+ writeln!(out, "metadata_uuid\t\t{}", uuid_unparse(&sb.metadata_uuid))?;
+
+ write!(out, "label\t\t\t")?;
+ for &byte in &sb.label {
+ if byte == 0 {
+ break;
+ }
+ write!(out, "{}", printable(byte))?;
+ }
+ writeln!(out)?;
+
+ writeln!(out, "generation\t\t{}", sb.generation.get())?;
+ writeln!(out, "root\t\t\t{}", sb.root.get())?;
+ writeln!(out, "sys_array_size\t\t{}", sb.sys_chunk_array_size.get())?;
+ writeln!(
+ out,
+ "chunk_root_generation\t{}",
+ sb.chunk_root_generation.get()
+ )?;
+ writeln!(out, "root_level\t\t{}", sb.root_level)?;
+ writeln!(out, "chunk_root\t\t{}", sb.chunk_root.get())?;
+ writeln!(out, "chunk_root_level\t{}", sb.chunk_root_level)?;
+ writeln!(out, "log_root\t\t{}", sb.log_root.get())?;
+ writeln!(
+ out,
+ "log_root_transid (deprecated)\t{}",
+ sb.__unused_log_root_transid.get()
+ )?;
+ writeln!(out, "log_root_level\t\t{}", sb.log_root_level)?;
+ writeln!(out, "total_bytes\t\t{}", sb.total_bytes.get())?;
+ writeln!(out, "bytes_used\t\t{}", sb.bytes_used.get())?;
+ writeln!(out, "sectorsize\t\t{}", sb.sectorsize.get())?;
+ writeln!(out, "nodesize\t\t{}", sb.nodesize.get())?;
+ writeln!(out, "leafsize (deprecated)\t{}", sb.__unused_leafsize.get())?;
+ writeln!(out, "stripesize\t\t{}", sb.stripesize.get())?;
+ writeln!(out, "root_dir\t\t{}", sb.root_dir_objectid.get())?;
+ writeln!(out, "num_devices\t\t{}", sb.num_devices.get())?;
+ writeln!(out, "compat_flags\t\t0x{:x}", sb.compat_flags.get())?;
+ writeln!(out, "compat_ro_flags\t\t0x{:x}", sb.compat_ro_flags.get())?;
+ print_readable_flag(out, sb.compat_ro_flags.get(), COMPAT_RO_FLAGS)?;
+ writeln!(out, "incompat_flags\t\t0x{:x}", sb.incompat_flags.get())?;
+ print_readable_flag(out, sb.incompat_flags.get(), INCOMPAT_FLAGS)?;
+ writeln!(out, "cache_generation\t{}", sb.cache_generation.get())?;
+ writeln!(
+ out,
+ "uuid_tree_generation\t{}",
+ sb.uuid_tree_generation.get()
+ )?;
+
+ let dev_item = &sb.dev_item;
+ writeln!(out, "dev_item.uuid\t\t{}", uuid_unparse(&dev_item.uuid))?;
+ let expected_fsid = if metadata_uuid_present {
+ &sb.metadata_uuid
+ } else {
+ &sb.fsid
+ };
+ writeln!(
+ out,
+ "dev_item.fsid\t\t{} {}",
+ uuid_unparse(&dev_item.fsid),
+ if dev_item.fsid == *expected_fsid {
+ "[match]"
+ } else {
+ "[DON'T MATCH]"
+ }
+ )?;
+ writeln!(out, "dev_item.type\t\t{}", dev_item.r#type.get())?;
+ writeln!(out, "dev_item.total_bytes\t{}", dev_item.total_bytes.get())?;
+ writeln!(out, "dev_item.bytes_used\t{}", dev_item.bytes_used.get())?;
+ writeln!(out, "dev_item.io_align\t{}", dev_item.io_align.get())?;
+ writeln!(out, "dev_item.io_width\t{}", dev_item.io_width.get())?;
+ writeln!(out, "dev_item.sector_size\t{}", dev_item.sector_size.get())?;
+ writeln!(out, "dev_item.devid\t\t{}", dev_item.devid.get())?;
+ writeln!(out, "dev_item.dev_group\t{}", dev_item.dev_group.get())?;
+ writeln!(out, "dev_item.seek_speed\t{}", dev_item.seek_speed)?;
+ writeln!(out, "dev_item.bandwidth\t{}", dev_item.bandwidth)?;
+ writeln!(out, "dev_item.generation\t{}", dev_item.generation.get())?;
+
+ if full {
+ writeln!(out, "sys_chunk_array[{}]:", limits::SYSTEM_CHUNK_ARRAY_SIZE)?;
+ print_sys_chunk_array(out, sb)?;
+ writeln!(out, "backup_roots[{}]:", limits::NUM_BACKUP_ROOTS)?;
+ print_backup_roots(out, sb)?;
+ }
+ Ok(())
+}
diff --git a/rust/src/sizes.rs b/rust/src/sizes.rs
index af4d44cbf5f5..eb7aeea7bd3c 100644
--- a/rust/src/sizes.rs
+++ b/rust/src/sizes.rs
@@ -11,4 +11,7 @@ pub const SZ_64K: usize = 64 * 1024;
pub const SZ_1M: usize = 1024 * 1024;
pub const SZ_2M: usize = 2 * 1024 * 1024;
pub const SZ_4M: usize = 4 * 1024 * 1024;
+pub const SZ_64M: usize = 64 * 1024 * 1024;
pub const SZ_1G: usize = 1024 * 1024 * 1024;
+
+pub const SZ_256G: u64 = 256 * 1024 * 1024 * 1024;
diff --git a/rust/src/util.rs b/rust/src/util.rs
new file mode 100644
index 000000000000..0b59ccfa68b2
--- /dev/null
+++ b/rust/src/util.rs
@@ -0,0 +1,11 @@
+/// Like `uuid_unparse()`: lower case, hyphenated.
+pub fn uuid_unparse(uuid: &[u8; 16]) -> String {
+ let mut s = String::with_capacity(36);
+ for (i, byte) in uuid.iter().enumerate() {
+ if matches!(i, 4 | 6 | 8 | 10) {
+ s.push('-');
+ }
+ s.push_str(&format!("{byte:02x}"));
+ }
+ s
+}
diff --git a/rust/tests/parse.rs b/rust/tests/parse.rs
index 28dc77695ca6..4b37714cf8f5 100644
--- a/rust/tests/parse.rs
+++ b/rust/tests/parse.rs
@@ -1,4 +1,4 @@
-use btrfs_rs::disk::consts::{magic, objectid};
+use btrfs_rs::disk::consts::{magic, objectid, super_offset, SUPER_INFO_OFFSET};
use btrfs_rs::disk::{
DiskBalanceArgs, DiskKey, Header, Key, KeyType, RootItem, SuperBlock, LEGACY_ROOT_ITEM_SIZE,
};
@@ -80,3 +80,10 @@ fn balance_args_union_views() {
let bytes = args.as_bytes();
assert_eq!(&bytes[8..16], &[5, 0, 0, 0, 9, 0, 0, 0]);
}
+
+#[test]
+fn superblock_copy_offsets() {
+ assert_eq!(super_offset(0), SUPER_INFO_OFFSET);
+ assert_eq!(super_offset(1), SZ_64M as u64);
+ assert_eq!(super_offset(2), SZ_256G);
+}
--
2.56.1
^ permalink raw reply related [flat|nested] 16+ messages in thread* [PATCH 03/15] btrfs-progs: rust: disk: add the tree block layout
2026-12-01 7:56 [PATCH RFC 00/15] btrfs-progs: experimental rust support Qu Wenruo
2026-12-01 7:56 ` [PATCH 01/15] btrfs-progs: rust: introduce on-disk format definitions Qu Wenruo
2026-12-01 7:56 ` [PATCH 02/15] btrfs-progs: rust: add btrfs-rs with inspect-internal dump-super Qu Wenruo
@ 2026-12-01 7:56 ` Qu Wenruo
2026-12-01 7:56 ` [PATCH 04/15] btrfs-progs: rust: fs: add superblock reading Qu Wenruo
` (11 subsequent siblings)
14 siblings, 0 replies; 16+ messages in thread
From: Qu Wenruo @ 2026-12-01 7:56 UTC (permalink / raw)
To: linux-btrfs
Add block::parse_block(), which splits the bytes of a tree block into
the header and the items of a leaf, or the key pointers of a node. It
only checks the sizes, and cannot panic on a corrupted block.
Signed-off-by: Qu Wenruo <wqu@suse.com>
---
rust/src/disk/block.rs | 153 +++++++++++++++++++++++++++++++++++++++++
rust/src/disk/mod.rs | 8 ++-
2 files changed, 158 insertions(+), 3 deletions(-)
create mode 100644 rust/src/disk/block.rs
diff --git a/rust/src/disk/block.rs b/rust/src/disk/block.rs
new file mode 100644
index 000000000000..a096a8613a62
--- /dev/null
+++ b/rust/src/disk/block.rs
@@ -0,0 +1,153 @@
+//! The layout of a tree block: a node or a leaf.
+
+use std::fmt;
+
+use zerocopy::FromBytes;
+
+use crate::disk::{Header, Item, KeyPtr};
+
+/// A tree block split into its parts, borrowing the bytes of the block.
+pub enum View<'a> {
+ Node {
+ header: &'a Header,
+ ptrs: &'a [KeyPtr],
+ },
+ Leaf {
+ header: &'a Header,
+ items: &'a [Item],
+ /// Everything after the header, the `offset` of an item is relative to
+ /// its start.
+ data: &'a [u8],
+ },
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum BlockError {
+ /// Shorter than a header
+ TooShort,
+ /// `nritems` is more than the block can hold
+ TooManyItems,
+ /// The data of an item is not inside the block
+ ItemOutOfRange,
+}
+
+impl fmt::Display for BlockError {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ f.write_str(match self {
+ BlockError::TooShort => "block is shorter than a header",
+ BlockError::TooManyItems => "nritems does not fit in the block",
+ BlockError::ItemOutOfRange => "item data is out of the block",
+ })
+ }
+}
+
+impl std::error::Error for BlockError {}
+
+/// Split the bytes of a tree block. Only the sizes are checked: the checksum
+/// and the header fields are for the caller.
+pub fn parse_block(buf: &[u8]) -> Result<View<'_>, BlockError> {
+ let Ok((header, body)) = Header::ref_from_prefix(buf) else {
+ return Err(BlockError::TooShort);
+ };
+ let nritems = header.nritems.get() as usize;
+
+ if header.level == 0 {
+ let Ok((items, _)) = <[Item]>::ref_from_prefix_with_elems(body, nritems) else {
+ return Err(BlockError::TooManyItems);
+ };
+ Ok(View::Leaf {
+ header,
+ items,
+ data: body,
+ })
+ } else {
+ let Ok((ptrs, _)) = <[KeyPtr]>::ref_from_prefix_with_elems(body, nritems) else {
+ return Err(BlockError::TooManyItems);
+ };
+ Ok(View::Node { header, ptrs })
+ }
+}
+
+pub fn header<'a>(view: &View<'a>) -> &'a Header {
+ match view {
+ View::Node { header, .. } | View::Leaf { header, .. } => header,
+ }
+}
+
+/// The data of a leaf item, `data` is the one of the `View`.
+pub fn item_data<'a>(data: &'a [u8], item: &Item) -> Result<&'a [u8], BlockError> {
+ let start = item.offset.get() as usize;
+ let Some(end) = start.checked_add(item.size.get() as usize) else {
+ return Err(BlockError::ItemOutOfRange);
+ };
+ let Some(item_data) = data.get(start..end) else {
+ return Err(BlockError::ItemOutOfRange);
+ };
+ Ok(item_data)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::sizes::*;
+ use zerocopy::{FromZeros, IntoBytes};
+
+ const HEADER_SIZE: usize = size_of::<Header>();
+
+ fn block(level: u8, nritems: u32) -> Vec<u8> {
+ let mut header = Header::new_zeroed();
+ header.level = level;
+ header.nritems = nritems.into();
+
+ let mut buf = vec![0u8; SZ_4K];
+ buf[..HEADER_SIZE].copy_from_slice(header.as_bytes());
+ buf
+ }
+
+ #[test]
+ fn leaf_and_node() {
+ let buf = block(0, 3);
+ let View::Leaf { items, .. } = parse_block(&buf).unwrap() else {
+ panic!("not a leaf");
+ };
+ assert_eq!(items.len(), 3);
+
+ let buf = block(1, 5);
+ let View::Node { ptrs, .. } = parse_block(&buf).unwrap() else {
+ panic!("not a node");
+ };
+ assert_eq!(ptrs.len(), 5);
+ }
+
+ #[test]
+ fn too_short_or_too_many_items() {
+ assert_eq!(parse_block(&[0; 50]).err(), Some(BlockError::TooShort));
+ assert_eq!(
+ parse_block(&block(0, u32::MAX)).err(),
+ Some(BlockError::TooManyItems)
+ );
+ assert_eq!(
+ parse_block(&block(2, 1000)).err(),
+ Some(BlockError::TooManyItems)
+ );
+ }
+
+ #[test]
+ fn item_data_must_be_inside_the_block() {
+ let mut buf = block(0, 1);
+ let mut item = Item::new_zeroed();
+ item.offset = 100.into();
+ item.size = 20.into();
+ buf[HEADER_SIZE..HEADER_SIZE + size_of::<Item>()].copy_from_slice(item.as_bytes());
+
+ let View::Leaf { items, data, .. } = parse_block(&buf).unwrap() else {
+ panic!("not a leaf");
+ };
+ assert_eq!(item_data(data, &items[0]).unwrap().len(), 20);
+
+ let mut bad = Item::new_zeroed();
+ bad.offset = u32::MAX.into();
+ bad.size = u32::MAX.into();
+ assert_eq!(item_data(data, &bad), Err(BlockError::ItemOutOfRange));
+ }
+}
diff --git a/rust/src/disk/mod.rs b/rust/src/disk/mod.rs
index 104ea54b159e..727a652d88cd 100644
--- a/rust/src/disk/mod.rs
+++ b/rust/src/disk/mod.rs
@@ -3,10 +3,11 @@
//! Plain `#[repr(C)]` structs with little-endian integer fields, mirroring
//! `kernel-shared/uapi/btrfs_tree.h`, in the same order. Struct and field names
//! are the C names without the `btrfs_` prefix, in Rust casing. Every struct
-//! has a compile-time size check. There is no I/O and no parsing logic here;
-//! read them with `zerocopy`, e.g. `SuperBlock::ref_from_bytes(buf)`.
+//! has a compile-time size check. There is no I/O; read the structs with
+//! `zerocopy`, e.g. `SuperBlock::ref_from_bytes(buf)`.
//!
-//! [`csum`] computes the checksums.
+//! [`csum`] computes the checksums and [`block`] splits a tree block into its
+//! header and items.
//!
//! Flexible array members (`btrfs_leaf`, `btrfs_node`, `btrfs_stripe_extent`)
//! have no struct: a leaf is a [`Header`] followed by [`Item`]s, a node a header
@@ -15,6 +16,7 @@
//! `btrfs_dir_item`, `btrfs_chunk`, ...) follow the fixed part in the item
//! payload.
+pub mod block;
pub mod btrfs_tree;
pub mod consts;
pub mod csum;
--
2.56.1
^ permalink raw reply related [flat|nested] 16+ messages in thread* [PATCH 04/15] btrfs-progs: rust: fs: add superblock reading
2026-12-01 7:56 [PATCH RFC 00/15] btrfs-progs: experimental rust support Qu Wenruo
` (2 preceding siblings ...)
2026-12-01 7:56 ` [PATCH 03/15] btrfs-progs: rust: disk: add the tree block layout Qu Wenruo
@ 2026-12-01 7:56 ` Qu Wenruo
2026-12-01 7:56 ` [PATCH 05/15] btrfs-progs: rust: fs: add Fs::open() Qu Wenruo
` (10 subsequent siblings)
14 siblings, 0 replies; 16+ messages in thread
From: Qu Wenruo @ 2026-12-01 7:56 UTC (permalink / raw)
To: linux-btrfs
Add the fs module, which will read a btrfs filesystem. It starts with
the Error type and with reading a superblock copy of a device, and
checking it like btrfs_read_dev_super() and btrfs_check_super() do.
The compatibility check only accepts the incompat features known to the
disk module, and refuses a filesystem that is changing its fsid.
Signed-off-by: Qu Wenruo <wqu@suse.com>
---
rust/src/fs/error.rs | 34 ++++++
rust/src/fs/mod.rs | 6 +
rust/src/fs/superblock.rs | 247 ++++++++++++++++++++++++++++++++++++++
rust/src/lib.rs | 4 +-
4 files changed, 290 insertions(+), 1 deletion(-)
create mode 100644 rust/src/fs/error.rs
create mode 100644 rust/src/fs/mod.rs
create mode 100644 rust/src/fs/superblock.rs
diff --git a/rust/src/fs/error.rs b/rust/src/fs/error.rs
new file mode 100644
index 000000000000..f07982e3809f
--- /dev/null
+++ b/rust/src/fs/error.rs
@@ -0,0 +1,34 @@
+use std::fmt;
+use std::io;
+use std::path::PathBuf;
+
+#[derive(Debug)]
+pub enum Error {
+ /// A device could not be opened or read.
+ Io { path: PathBuf, source: io::Error },
+ /// What was read is not what a valid btrfs has.
+ Corrupt(String),
+ /// Valid, but not supported by this implementation.
+ Incompatible(String),
+}
+
+pub type Result<T> = std::result::Result<T, Error>;
+
+impl fmt::Display for Error {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ match self {
+ Error::Io { path, source } => write!(f, "{}: {source}", path.display()),
+ Error::Corrupt(msg) => f.write_str(msg),
+ Error::Incompatible(msg) => write!(f, "unsupported: {msg}"),
+ }
+ }
+}
+
+impl std::error::Error for Error {
+ fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
+ match self {
+ Error::Io { source, .. } => Some(source),
+ Error::Corrupt(_) | Error::Incompatible(_) => None,
+ }
+ }
+}
diff --git a/rust/src/fs/mod.rs b/rust/src/fs/mod.rs
new file mode 100644
index 000000000000..d1ce29d67e56
--- /dev/null
+++ b/rust/src/fs/mod.rs
@@ -0,0 +1,6 @@
+//! Reading a btrfs filesystem, on top of [`crate::disk`].
+
+pub mod error;
+pub mod superblock;
+
+pub use error::{Error, Result};
diff --git a/rust/src/fs/superblock.rs b/rust/src/fs/superblock.rs
new file mode 100644
index 000000000000..870efaa02fd1
--- /dev/null
+++ b/rust/src/fs/superblock.rs
@@ -0,0 +1,247 @@
+//! Reading and checking the superblock, see `btrfs_read_dev_super()` and
+//! `btrfs_check_super()`.
+
+use std::fs::File;
+use std::io::ErrorKind;
+use std::os::unix::fs::FileExt;
+use std::path::Path;
+
+use crate::disk::consts::{incompat, limits, magic, super_flag};
+use crate::disk::{csum, SuperBlock};
+use zerocopy::{FromZeros, IntoBytes};
+
+use crate::fs::error::{Error, Result};
+
+fn format_csum(csum: &[u8]) -> String {
+ let mut s = String::from("0x");
+ for byte in csum {
+ s.push_str(&format!("{byte:02x}"));
+ }
+ s
+}
+
+/// Read the superblock copy at `bytenr` of a device and check it.
+pub fn read_superblock(file: &File, path: &Path, bytenr: u64) -> Result<Box<SuperBlock>> {
+ let mut sb = Box::new(SuperBlock::new_zeroed());
+ match file.read_exact_at(sb.as_mut_bytes(), bytenr) {
+ Ok(()) => {}
+ Err(e) if e.kind() == ErrorKind::UnexpectedEof => {
+ return Err(Error::Corrupt(format!(
+ "{}: no superblock at {bytenr}, the device is too small",
+ path.display()
+ )));
+ }
+ Err(source) => {
+ return Err(Error::Io {
+ path: path.to_path_buf(),
+ source,
+ });
+ }
+ }
+
+ if let Err(msg) = check_superblock(&sb, bytenr) {
+ return Err(Error::Corrupt(format!("{}: {msg}", path.display())));
+ }
+ Ok(sb)
+}
+
+/// `btrfs_check_super()`, and that the superblock is where it says it is.
+pub fn check_superblock(sb: &SuperBlock, bytenr: u64) -> std::result::Result<(), String> {
+ if sb.bytenr.get() != bytenr {
+ return Err(format!(
+ "superblock bytenr mismatch, want={bytenr}, have={}",
+ sb.bytenr.get()
+ ));
+ }
+ if sb.magic.get() != magic::BTRFS {
+ return Err("superblock magic doesn't match".to_string());
+ }
+
+ let csum_type = sb.csum_type.get();
+ let Some(info) = csum::info(csum_type) else {
+ return Err(format!("unsupported checksum algorithm {csum_type}"));
+ };
+ let Some(found) = csum::compute(csum_type, &sb.as_bytes()[limits::CSUM_SIZE..]) else {
+ return Err(format!("unsupported checksum algorithm {csum_type}"));
+ };
+ if found[..info.size] != sb.csum[..info.size] {
+ return Err(format!(
+ "superblock checksum mismatch: wanted {} found {}",
+ format_csum(&sb.csum[..info.size]),
+ format_csum(&found[..info.size])
+ ));
+ }
+
+ check_sb_members(sb)
+}
+
+/// The checks of `btrfs_check_super()` after the checksum.
+fn check_sb_members(sb: &SuperBlock) -> std::result::Result<(), String> {
+ let sectorsize = sb.sectorsize.get();
+ if !sectorsize.is_power_of_two()
+ || (sectorsize as usize) < limits::SECTORSIZE_MIN
+ || (sectorsize as usize) > limits::SECTORSIZE_MAX
+ {
+ return Err(format!("invalid sectorsize: {sectorsize}"));
+ }
+ let nodesize = sb.nodesize.get();
+ if nodesize < sectorsize
+ || !nodesize.is_multiple_of(sectorsize)
+ || (nodesize as usize) > limits::NODESIZE_MAX
+ {
+ return Err(format!("invalid nodesize: {nodesize}"));
+ }
+ for (name, bytenr) in [
+ ("tree_root", sb.root.get()),
+ ("chunk_root", sb.chunk_root.get()),
+ ("log_root", sb.log_root.get()),
+ ] {
+ // Only require the tree block to be aligned to sectorsize.
+ // As we can still have unaligned metadata chunks from convert,
+ // that is only aligned to sectorsize but not to nodesize.
+ if !bytenr.is_multiple_of(u64::from(sectorsize)) {
+ return Err(format!("{name} block unaligned: {bytenr}"));
+ }
+ }
+ if sb.bytes_used.get() < 6 * u64::from(nodesize) {
+ return Err(format!("invalid bytes_used {}", sb.bytes_used.get()));
+ }
+ let stripesize = sb.stripesize.get();
+ if stripesize != sectorsize {
+ return Err(format!("invalid stripesize {stripesize}"));
+ }
+
+ let has_metadata_uuid = sb.incompat_flags.get() & incompat::METADATA_UUID != 0;
+ if (has_metadata_uuid && sb.dev_item.fsid != sb.metadata_uuid)
+ || (!has_metadata_uuid && sb.dev_item.fsid != sb.fsid)
+ {
+ return Err("dev_item UUID does not match fsid".to_string());
+ }
+ if sb.num_devices.get() == 0 {
+ return Err(format!("invalid num_devices {}", sb.num_devices.get()));
+ }
+
+ // It must hold at least one key and one chunk
+ let array_size = sb.sys_chunk_array_size.get();
+ if (array_size as usize) > limits::SYSTEM_CHUNK_ARRAY_SIZE {
+ return Err(format!("invalid system chunk array size {}", array_size));
+ }
+ let min_array_size = size_of::<crate::disk::DiskKey>() + size_of::<crate::disk::Chunk>();
+ if (array_size as usize) < min_array_size {
+ return Err(format!(
+ "system chunk array too small {array_size} < {min_array_size}"
+ ));
+ }
+ Ok(())
+}
+
+/// Features that this implementation can not deal with, as an error.
+pub fn check_compatibility(sb: &SuperBlock) -> Result<()> {
+ if sb.flags.get() & super_flag::CHANGING_FSID != 0 {
+ return Err(Error::Incompatible(
+ "filesystem UUID change in progress".to_string(),
+ ));
+ }
+
+ let known = incompat::MIXED_BACKREF
+ | incompat::DEFAULT_SUBVOL
+ | incompat::MIXED_GROUPS
+ | incompat::COMPRESS_LZO
+ | incompat::COMPRESS_ZSTD
+ | incompat::BIG_METADATA
+ | incompat::EXTENDED_IREF
+ | incompat::RAID56
+ | incompat::SKINNY_METADATA
+ | incompat::NO_HOLES
+ | incompat::METADATA_UUID
+ | incompat::RAID1C34
+ | incompat::ZONED
+ | incompat::EXTENT_TREE_V2
+ | incompat::RAID_STRIPE_TREE
+ | incompat::ENCRYPT
+ | incompat::SIMPLE_QUOTA;
+ let unknown = sb.incompat_flags.get() & !known;
+ if unknown != 0 {
+ return Err(Error::Incompatible(format!(
+ "incompat features 0x{unknown:x}"
+ )));
+ }
+ Ok(())
+}
+
+#[cfg(test)]
+pub(crate) mod tests {
+ use super::*;
+ use crate::disk::consts::csum_type;
+ use crate::sizes::*;
+
+ /// A superblock that passes the checks, for one device and nothing else.
+ pub fn valid_superblock() -> SuperBlock {
+ let mut sb = SuperBlock::new_zeroed();
+ sb.bytenr = crate::disk::consts::SUPER_INFO_OFFSET.into();
+ sb.magic = magic::BTRFS.into();
+ sb.csum_type = csum_type::CRC32.into();
+ sb.fsid = [0x11; 16];
+ sb.dev_item.fsid = [0x11; 16];
+ sb.nodesize = (SZ_16K as u32).into();
+ sb.sectorsize = (SZ_4K as u32).into();
+ sb.stripesize = (SZ_4K as u32).into();
+ sb.total_bytes = (SZ_64M as u64).into();
+ sb.bytes_used = (SZ_1M as u64).into();
+ sb.num_devices = 1.into();
+ sb.sys_chunk_array_size =
+ ((size_of::<crate::disk::DiskKey>() + size_of::<crate::disk::Chunk>()) as u32).into();
+ update_csum(&mut sb);
+ sb
+ }
+
+ pub fn update_csum(sb: &mut SuperBlock) {
+ let csum = csum::compute(sb.csum_type.get(), &sb.as_bytes()[limits::CSUM_SIZE..]).unwrap();
+ sb.csum = csum;
+ }
+
+ const BYTENR: u64 = crate::disk::consts::SUPER_INFO_OFFSET;
+
+ #[test]
+ fn valid_superblock_passes() {
+ assert_eq!(check_superblock(&valid_superblock(), BYTENR), Ok(()));
+ }
+
+ #[test]
+ fn damaged_superblock_fails() {
+ let mut sb = valid_superblock();
+ sb.csum[0] ^= 1;
+ assert!(check_superblock(&sb, BYTENR).is_err());
+
+ let mut sb = valid_superblock();
+ sb.magic = 0.into();
+ update_csum(&mut sb);
+ assert!(check_superblock(&sb, BYTENR).is_err());
+
+ let mut sb = valid_superblock();
+ sb.nodesize = 1000.into();
+ update_csum(&mut sb);
+ assert!(check_superblock(&sb, BYTENR).is_err());
+
+ // The copy is not where it claims to be
+ assert!(check_superblock(&valid_superblock(), BYTENR + (SZ_4K as u64)).is_err());
+ }
+
+ #[test]
+ fn unknown_incompat_features_are_not_supported() {
+ let mut sb = valid_superblock();
+ assert!(check_compatibility(&sb).is_ok());
+ sb.incompat_flags = (1u64 << 40).into();
+ assert!(matches!(
+ check_compatibility(&sb),
+ Err(Error::Incompatible(_))
+ ));
+
+ let mut sb = valid_superblock();
+ sb.incompat_flags = incompat::REMAP_TREE.into();
+ assert!(matches!(
+ check_compatibility(&sb),
+ Err(Error::Incompatible(_))
+ ));
+ }
+}
diff --git a/rust/src/lib.rs b/rust/src/lib.rs
index d7c1e85fa6ae..98c90722d0fe 100644
--- a/rust/src/lib.rs
+++ b/rust/src/lib.rs
@@ -1,6 +1,8 @@
//! Experimental Rust implementation of btrfs-progs.
//!
-//! [`disk`] has the on-disk format. The commands are in the binary.
+//! [`disk`] has the on-disk format, and [`fs`] reads a filesystem. The commands
+//! are in the binary.
pub mod disk;
+pub mod fs;
pub mod sizes;
--
2.56.1
^ permalink raw reply related [flat|nested] 16+ messages in thread* [PATCH 05/15] btrfs-progs: rust: fs: add Fs::open()
2026-12-01 7:56 [PATCH RFC 00/15] btrfs-progs: experimental rust support Qu Wenruo
` (3 preceding siblings ...)
2026-12-01 7:56 ` [PATCH 04/15] btrfs-progs: rust: fs: add superblock reading Qu Wenruo
@ 2026-12-01 7:56 ` Qu Wenruo
2026-12-01 7:56 ` [PATCH 06/15] btrfs-progs: rust: fs: add device scanning with libblkid for multi-device filesystems Qu Wenruo
` (9 subsequent siblings)
14 siblings, 0 replies; 16+ messages in thread
From: Qu Wenruo @ 2026-12-01 7:56 UTC (permalink / raw)
To: linux-btrfs
Add Fs and Fs::open(), the Rust version of open_ctree(). "ctree" is the
name of the btree code, while the function opens a filesystem, so it is
named after that.
It opens the devices, reads the superblock and the system chunk array,
and then the chunk tree. The mapping of the logical addresses is in
chunk.rs, for all the profiles. RAID5 and RAID6 can only read the data
stripes, there is no reconstruction.
read_tree_block() reads from the first copy that is good, which has a
valid checksum, bytenr, fsid, level and generation.
The other trees, the block groups, zoned devices and the recovery from
the other superblock copies are not handled yet.
Signed-off-by: Qu Wenruo <wqu@suse.com>
---
rust/src/disk/btrfs_tree.rs | 4 +-
rust/src/fs/device.rs | 50 ++++
rust/src/fs/error.rs | 5 +-
rust/src/fs/mod.rs | 341 +++++++++++++++++++++++++
rust/src/fs/superblock.rs | 6 +-
rust/src/fs/tree_block.rs | 135 ++++++++++
rust/src/fs/volumes.rs | 497 ++++++++++++++++++++++++++++++++++++
rust/src/sizes.rs | 1 +
8 files changed, 1034 insertions(+), 5 deletions(-)
create mode 100644 rust/src/fs/device.rs
create mode 100644 rust/src/fs/tree_block.rs
create mode 100644 rust/src/fs/volumes.rs
diff --git a/rust/src/disk/btrfs_tree.rs b/rust/src/disk/btrfs_tree.rs
index 66f755348850..eebb61c662f1 100644
--- a/rust/src/disk/btrfs_tree.rs
+++ b/rust/src/disk/btrfs_tree.rs
@@ -671,12 +671,12 @@ impl DiskBalanceArgs {
/// The item type of a key. A newtype rather than an enum so that unknown
/// values are preserved.
-#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
+#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Default)]
pub struct KeyType(pub u8);
/// CPU-side key (`btrfs_key`). Fields are in tree order, so the derived `Ord`
/// is the key comparison.
-#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
+#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Default)]
pub struct Key {
pub objectid: u64,
pub r#type: KeyType,
diff --git a/rust/src/fs/device.rs b/rust/src/fs/device.rs
new file mode 100644
index 000000000000..40d617e22cb3
--- /dev/null
+++ b/rust/src/fs/device.rs
@@ -0,0 +1,50 @@
+//! The devices of a filesystem.
+
+use std::fs::File;
+use std::os::unix::fs::FileExt;
+use std::path::{Path, PathBuf};
+
+use crate::disk::SuperBlock;
+
+use crate::fs::error::{Error, Result};
+use crate::fs::superblock::read_superblock;
+
+pub struct Device {
+ pub devid: u64,
+ pub path: PathBuf,
+ file: File,
+}
+
+impl Device {
+ pub fn read_at(&self, buf: &mut [u8], offset: u64) -> Result<()> {
+ if let Err(source) = self.file.read_exact_at(buf, offset) {
+ return Err(Error::Io {
+ path: self.path.clone(),
+ source,
+ });
+ }
+ Ok(())
+ }
+}
+
+/// Open a device and read the superblock at `sb_bytenr` of it. The device id
+/// is the one in the superblock.
+pub fn open_device(path: &Path, sb_bytenr: u64) -> Result<(Device, Box<SuperBlock>)> {
+ let file = match File::open(path) {
+ Ok(file) => file,
+ Err(source) => {
+ return Err(Error::Io {
+ path: path.to_path_buf(),
+ source,
+ });
+ }
+ };
+ let sb = read_superblock(&file, path, sb_bytenr)?;
+
+ let device = Device {
+ devid: sb.dev_item.devid.get(),
+ path: path.to_path_buf(),
+ file,
+ };
+ Ok((device, sb))
+}
diff --git a/rust/src/fs/error.rs b/rust/src/fs/error.rs
index f07982e3809f..f54bd9199fa6 100644
--- a/rust/src/fs/error.rs
+++ b/rust/src/fs/error.rs
@@ -6,6 +6,8 @@ use std::path::PathBuf;
pub enum Error {
/// A device could not be opened or read.
Io { path: PathBuf, source: io::Error },
+ /// The device with this id is not one of the opened devices.
+ DeviceMissing(u64),
/// What was read is not what a valid btrfs has.
Corrupt(String),
/// Valid, but not supported by this implementation.
@@ -18,6 +20,7 @@ impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Error::Io { path, source } => write!(f, "{}: {source}", path.display()),
+ Error::DeviceMissing(devid) => write!(f, "device {devid} is missing"),
Error::Corrupt(msg) => f.write_str(msg),
Error::Incompatible(msg) => write!(f, "unsupported: {msg}"),
}
@@ -28,7 +31,7 @@ impl std::error::Error for Error {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Error::Io { source, .. } => Some(source),
- Error::Corrupt(_) | Error::Incompatible(_) => None,
+ Error::DeviceMissing(_) | Error::Corrupt(_) | Error::Incompatible(_) => None,
}
}
}
diff --git a/rust/src/fs/mod.rs b/rust/src/fs/mod.rs
index d1ce29d67e56..e9843348b8b8 100644
--- a/rust/src/fs/mod.rs
+++ b/rust/src/fs/mod.rs
@@ -1,6 +1,347 @@
//! Reading a btrfs filesystem, on top of [`crate::disk`].
+//!
+//! [`Fs::open()`] is what `open_ctree()` is in the C code.
+pub mod device;
pub mod error;
pub mod superblock;
+pub mod tree_block;
+pub mod volumes;
pub use error::{Error, Result};
+
+use std::path::Path;
+
+use crate::disk::block::{self, item_data, View};
+use crate::disk::consts::{incompat, objectid, super_offset};
+use crate::disk::{Key, KeyType, SuperBlock};
+
+use crate::fs::device::{open_device, Device};
+use crate::fs::superblock::check_compatibility;
+use crate::fs::tree_block::{read_tree_block, Check};
+use crate::fs::volumes::{parse_chunk, read_sys_array, ChunkMap};
+
+/// The root of a tree (mirrors C `struct btrfs_root`).
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
+pub struct Root {
+ pub key: Key,
+ pub bytenr: u64,
+ pub level: u8,
+ pub generation: u64,
+}
+
+/// An opened filesystem, with its devices, the mapping of the logical
+/// addresses, and the superblock.
+pub struct Fs {
+ pub superblock: Box<SuperBlock>,
+ pub devices: Vec<Device>,
+ pub chunks: ChunkMap,
+ pub sectorsize: u32,
+ pub nodesize: u32,
+ pub csum_type: u16,
+ pub csum_size: usize,
+ /// The fsid in the header of the tree blocks, which is the metadata uuid
+ /// if the filesystem has one.
+ pub metadata_fsid: [u8; 16],
+ pub tree_root: Root,
+ pub chunk_root: Root,
+}
+
+impl Fs {
+ /// Open the filesystem of `device`, with the primary superblock of it.
+ pub fn open(device: &Path) -> Result<Fs> {
+ let sb_bytenr = super_offset(0);
+ let (first, superblock) = open_device(device, sb_bytenr)?;
+ check_compatibility(&superblock)?;
+
+ let devices = vec![first];
+
+ let sectorsize = superblock.sectorsize.get();
+ let csum_type = superblock.csum_type.get();
+ let csum_size = crate::disk::csum::info(csum_type).map_or(0, |info| info.size);
+ let metadata_fsid = if superblock.incompat_flags.get() & incompat::METADATA_UUID != 0 {
+ superblock.metadata_uuid
+ } else {
+ superblock.fsid
+ };
+ let mixed = superblock.incompat_flags.get() & incompat::MIXED_GROUPS != 0;
+
+ let chunks = read_sys_array(&superblock, sectorsize, mixed)?;
+ let tree_root = Root {
+ key: Key {
+ objectid: objectid::ROOT_TREE,
+ r#type: KeyType::ROOT_ITEM,
+ offset: 0,
+ },
+ bytenr: superblock.root.get(),
+ level: superblock.root_level,
+ generation: superblock.generation.get(),
+ };
+ let chunk_root = Root {
+ key: Key {
+ objectid: objectid::CHUNK_TREE,
+ r#type: KeyType::ROOT_ITEM,
+ offset: 0,
+ },
+ bytenr: superblock.chunk_root.get(),
+ level: superblock.chunk_root_level,
+ generation: superblock.chunk_root_generation.get(),
+ };
+
+ let mut fs = Fs {
+ nodesize: superblock.nodesize.get(),
+ superblock,
+ devices,
+ chunks,
+ sectorsize,
+ csum_type,
+ csum_size,
+ metadata_fsid,
+ tree_root,
+ chunk_root,
+ };
+ read_chunk_tree(&mut fs, mixed)?;
+ Ok(fs)
+ }
+
+ pub fn device(&self, devid: u64) -> Option<&Device> {
+ self.devices.iter().find(|device| device.devid == devid)
+ }
+}
+
+/// Read every chunk item of the tree at `bytenr`, and insert it into `fs.chunks`.
+/// For now we do not have a good way to search tree, so here we go through all
+/// items in the chunk tree.
+fn collect_chunks(fs: &mut Fs, bytenr: u64, check: &Check, mixed: bool) -> Result<()> {
+ let buf = read_tree_block(fs, bytenr, check)?;
+
+ let view = match block::parse_block(&buf) {
+ Ok(view) => view,
+ Err(e) => return Err(Error::Corrupt(format!("bad tree block {bytenr}, {e}"))),
+ };
+ match view {
+ View::Leaf {
+ items: leaf_items,
+ data,
+ ..
+ } => {
+ for item in leaf_items {
+ let key = Key::from(&item.key);
+ if key.objectid == objectid::FIRST_CHUNK_TREE && key.r#type == KeyType::CHUNK_ITEM {
+ let data = match item_data(data, item) {
+ Ok(data) => data,
+ Err(e) => {
+ return Err(Error::Corrupt(format!("bad tree block {bytenr}, {e}")));
+ }
+ };
+ let entry = parse_chunk(key.offset, data, fs.sectorsize, mixed)?;
+ fs.chunks.insert(entry);
+ }
+ }
+ }
+ View::Node { header, ptrs } => {
+ // The level is checked by `read_tree_block()`, so it goes down
+ // to the leaves
+ for ptr in ptrs {
+ let child = Check {
+ level: Some(header.level - 1),
+ generation: Some(ptr.generation.get()),
+ };
+ collect_chunks(fs, ptr.blockptr.get(), &child, mixed)?;
+ }
+ }
+ }
+ Ok(())
+}
+
+/// Add the chunks of the chunk tree to the ones of the superblock, see
+/// `btrfs_read_chunk_tree()`.
+fn read_chunk_tree(fs: &mut Fs, mixed: bool) -> Result<()> {
+ let root = fs.chunk_root;
+ let check = Check {
+ level: Some(root.level),
+ generation: Some(root.generation),
+ };
+ if let Err(e) = collect_chunks(fs, root.bytenr, &check, mixed) {
+ return Err(Error::Corrupt(format!("cannot read the chunk tree: {e}")));
+ }
+ Ok(())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::disk::consts::{block_group, csum_type, limits};
+ use crate::disk::{csum, Chunk, DiskKey, Header, Item, Stripe};
+ use crate::fs::superblock::tests::{update_csum, valid_superblock};
+ use crate::sizes::*;
+ use std::path::PathBuf;
+ use zerocopy::{FromZeros, IntoBytes};
+
+ const SYSTEM_START: u64 = 0x100000;
+ const CHUNK_ROOT: u64 = 0x110000;
+ const DATA_START: u64 = 0x200000;
+ const NODESIZE: usize = SZ_16K;
+ const HEADER_SIZE: usize = size_of::<Header>();
+
+ /// A chunk of 1MiB, which is on the device at the same address.
+ fn chunk_item(flags: u64, start: u64) -> Vec<u8> {
+ let mut chunk = Chunk::new_zeroed();
+ chunk.length = (SZ_1M as u64).into();
+ chunk.stripe_len = (SZ_64K as u64).into();
+ chunk.r#type = flags.into();
+ chunk.sector_size = (SZ_4K as u32).into();
+ chunk.num_stripes = 1.into();
+ chunk.sub_stripes = 1.into();
+
+ let mut stripe = Stripe::new_zeroed();
+ stripe.devid = 1.into();
+ stripe.offset = start.into();
+ [chunk.as_bytes(), stripe.as_bytes()].concat()
+ }
+
+ fn chunk_key(start: u64) -> DiskKey {
+ DiskKey {
+ objectid: objectid::FIRST_CHUNK_TREE.into(),
+ r#type: KeyType::CHUNK_ITEM.0,
+ offset: start.into(),
+ }
+ }
+
+ /// The chunk tree: a leaf with the system chunk and a data chunk.
+ fn chunk_tree_leaf() -> Vec<u8> {
+ let chunks = [
+ (SYSTEM_START, chunk_item(block_group::SYSTEM, SYSTEM_START)),
+ (DATA_START, chunk_item(block_group::DATA, DATA_START)),
+ ];
+
+ let mut header = Header::new_zeroed();
+ header.bytenr = CHUNK_ROOT.into();
+ header.fsid = [0x11; 16];
+ header.generation = 5.into();
+ header.owner = objectid::CHUNK_TREE.into();
+ header.nritems = (chunks.len() as u32).into();
+
+ let mut buf = vec![0u8; NODESIZE];
+ buf[..HEADER_SIZE].copy_from_slice(header.as_bytes());
+ let mut data_end = NODESIZE - HEADER_SIZE;
+ for (i, (start, data)) in chunks.iter().enumerate() {
+ data_end -= data.len();
+ let item = Item {
+ key: chunk_key(*start),
+ offset: (data_end as u32).into(),
+ size: (data.len() as u32).into(),
+ };
+ let at = HEADER_SIZE + i * size_of::<Item>();
+ buf[at..at + size_of::<Item>()].copy_from_slice(item.as_bytes());
+ buf[HEADER_SIZE + data_end..][..data.len()].copy_from_slice(data);
+ }
+ let csum = csum::compute(csum_type::CRC32, &buf[limits::CSUM_SIZE..]).unwrap();
+ buf[..limits::CSUM_SIZE].copy_from_slice(&csum);
+ buf
+ }
+
+ /// A device of 3MiB with a chunk tree, and the superblock with the system
+ /// chunk in its array.
+ fn device_image() -> Vec<u8> {
+ let mut sb = valid_superblock();
+ sb.chunk_root = CHUNK_ROOT.into();
+ sb.chunk_root_generation = 5.into();
+ sb.root = 0x120000.into();
+ sb.generation = 6.into();
+ sb.dev_item.devid = 1.into();
+
+ let array = [
+ chunk_key(SYSTEM_START).as_bytes(),
+ &chunk_item(block_group::SYSTEM, SYSTEM_START),
+ ]
+ .concat();
+ assert_eq!(array.len(), sb.sys_chunk_array_size.get() as usize);
+ sb.sys_chunk_array[..array.len()].copy_from_slice(&array);
+ update_csum(&mut sb);
+
+ let mut image = vec![0u8; 3 * SZ_1M];
+ image[super_offset(0) as usize..][..SZ_4K].copy_from_slice(sb.as_bytes());
+ image[CHUNK_ROOT as usize..][..NODESIZE].copy_from_slice(&chunk_tree_leaf());
+ image
+ }
+
+ struct TestDevice(PathBuf);
+
+ impl TestDevice {
+ fn new(name: &str, image: &[u8]) -> TestDevice {
+ let path =
+ std::env::temp_dir().join(format!("btrfs-fs-{}-{name}.img", std::process::id()));
+ std::fs::write(&path, image).unwrap();
+ TestDevice(path)
+ }
+ }
+
+ impl Drop for TestDevice {
+ fn drop(&mut self) {
+ let _ = std::fs::remove_file(&self.0);
+ }
+ }
+
+ #[test]
+ fn open_reads_the_chunk_tree() {
+ let device = TestDevice::new("open", &device_image());
+ let fs = Fs::open(&device.0).unwrap();
+
+ assert_eq!(fs.chunks.len(), 2);
+ assert_eq!(
+ fs.chunks.lookup(SYSTEM_START).unwrap().flags,
+ block_group::SYSTEM
+ );
+ assert_eq!(
+ fs.chunks.lookup(DATA_START + (SZ_4K as u64)).unwrap().flags,
+ block_group::DATA
+ );
+ assert!(fs.chunks.lookup(DATA_START + (SZ_1M as u64)).is_none());
+ assert_eq!(fs.tree_root.generation, 6);
+ assert_eq!(fs.chunk_root.bytenr, CHUNK_ROOT);
+ }
+
+ #[test]
+ fn tree_blocks_are_checked() {
+ let device = TestDevice::new("check", &device_image());
+ let fs = Fs::open(&device.0).unwrap();
+
+ let good = Check {
+ level: Some(0),
+ generation: Some(5),
+ };
+ assert_eq!(
+ read_tree_block(&fs, CHUNK_ROOT, &good).unwrap().len(),
+ NODESIZE
+ );
+ assert!(read_tree_block(&fs, CHUNK_ROOT, &Check::default()).is_ok());
+
+ let wrong_generation = Check {
+ generation: Some(4),
+ ..good
+ };
+ assert!(read_tree_block(&fs, CHUNK_ROOT, &wrong_generation).is_err());
+ let wrong_level = Check {
+ level: Some(1),
+ ..good
+ };
+ assert!(read_tree_block(&fs, CHUNK_ROOT, &wrong_level).is_err());
+
+ // Not aligned, not in a chunk, and not a tree block
+ assert!(read_tree_block(&fs, CHUNK_ROOT + 1, &good).is_err());
+ assert!(read_tree_block(&fs, 0x500000, &good).is_err());
+ assert!(read_tree_block(&fs, DATA_START, &good).is_err());
+ }
+
+ #[test]
+ fn damaged_chunk_tree_fails_to_open() {
+ let mut image = device_image();
+ image[CHUNK_ROOT as usize + 100] ^= 1;
+ let device = TestDevice::new("damaged", &image);
+ assert!(matches!(
+ Fs::open(&device.0),
+ Err(Error::Corrupt(msg)) if msg.contains("checksum verify failed")
+ ));
+ }
+}
diff --git a/rust/src/fs/superblock.rs b/rust/src/fs/superblock.rs
index 870efaa02fd1..6462e91f7bb3 100644
--- a/rust/src/fs/superblock.rs
+++ b/rust/src/fs/superblock.rs
@@ -189,8 +189,10 @@ pub(crate) mod tests {
sb.total_bytes = (SZ_64M as u64).into();
sb.bytes_used = (SZ_1M as u64).into();
sb.num_devices = 1.into();
- sb.sys_chunk_array_size =
- ((size_of::<crate::disk::DiskKey>() + size_of::<crate::disk::Chunk>()) as u32).into();
+ sb.sys_chunk_array_size = ((size_of::<crate::disk::DiskKey>()
+ + size_of::<crate::disk::Chunk>()
+ + size_of::<crate::disk::Stripe>()) as u32)
+ .into();
update_csum(&mut sb);
sb
}
diff --git a/rust/src/fs/tree_block.rs b/rust/src/fs/tree_block.rs
new file mode 100644
index 000000000000..f8cd49282221
--- /dev/null
+++ b/rust/src/fs/tree_block.rs
@@ -0,0 +1,135 @@
+//! Reading tree blocks, see `read_tree_block()`.
+
+use crate::disk::block::{self, header};
+use crate::disk::consts::limits;
+use crate::disk::csum;
+
+use crate::fs::error::{Error, Result};
+use crate::fs::volumes::{map_read, num_copies, ChunkEntry};
+use crate::fs::Fs;
+
+/// What the parent of a tree block, or the superblock, says about it.
+#[derive(Debug, Clone, Copy, Default)]
+pub struct Check {
+ pub level: Option<u8>,
+ pub generation: Option<u64>,
+}
+
+fn format_csum(csum: &[u8]) -> String {
+ let mut s = String::from("0x");
+ for byte in csum {
+ s.push_str(&format!("{byte:02x}"));
+ }
+ s
+}
+
+fn bad_block(bytenr: u64, msg: impl std::fmt::Display) -> Error {
+ Error::Corrupt(format!("bad tree block {bytenr}, {msg}"))
+}
+
+/// The checksum, `check_tree_block()` and the checks of the parent.
+fn check_tree_block(fs: &Fs, buf: &[u8], bytenr: u64, check: &Check) -> Result<()> {
+ let found = csum::compute(fs.csum_type, &buf[limits::CSUM_SIZE..])
+ .ok_or_else(|| Error::Incompatible(format!("checksum algorithm {}", fs.csum_type)))?;
+ if found[..fs.csum_size] != buf[..fs.csum_size] {
+ return Err(Error::Corrupt(format!(
+ "checksum verify failed on {bytenr} wanted {} found {}",
+ format_csum(&buf[..fs.csum_size]),
+ format_csum(&found[..fs.csum_size])
+ )));
+ }
+
+ let view = match block::parse_block(buf) {
+ Ok(view) => view,
+ Err(e) => return Err(bad_block(bytenr, e)),
+ };
+ let header = header(&view);
+ if header.bytenr.get() != bytenr {
+ return Err(bad_block(
+ bytenr,
+ format!(
+ "bytenr mismatch, want={bytenr}, have={}",
+ header.bytenr.get()
+ ),
+ ));
+ }
+ if header.fsid != fs.metadata_fsid {
+ return Err(bad_block(bytenr, "fsid mismatch"));
+ }
+ if usize::from(header.level) >= limits::MAX_LEVEL {
+ return Err(bad_block(
+ bytenr,
+ format!("bad level, {} > {}", header.level, limits::MAX_LEVEL),
+ ));
+ }
+ if let Some(level) = check.level {
+ if header.level != level {
+ return Err(bad_block(
+ bytenr,
+ format!("level mismatch, want={level}, have={}", header.level),
+ ));
+ }
+ }
+ if let Some(generation) = check.generation {
+ if header.generation.get() != generation {
+ return Err(Error::Corrupt(format!(
+ "parent transid verify failed on {bytenr} wanted {generation} found {}",
+ header.generation.get()
+ )));
+ }
+ }
+ Ok(())
+}
+
+fn read_mirror(
+ fs: &Fs,
+ entry: &ChunkEntry,
+ bytenr: u64,
+ mirror: usize,
+ check: &Check,
+) -> Result<Vec<u8>> {
+ let nodesize = fs.nodesize as usize;
+ let Some(mapping) = map_read(entry, bytenr, mirror) else {
+ return Err(Error::Incompatible(format!(
+ "no way to read the tree block {bytenr}, mirror {mirror}"
+ )));
+ };
+ if mapping.len < nodesize as u64 {
+ return Err(bad_block(bytenr, "it crosses a stripe boundary"));
+ }
+ let Some(device) = fs.device(mapping.devid) else {
+ return Err(Error::DeviceMissing(mapping.devid));
+ };
+
+ let mut buf = vec![0u8; nodesize];
+ device.read_at(&mut buf, mapping.physical)?;
+ check_tree_block(fs, &buf, bytenr, check)?;
+ Ok(buf)
+}
+
+/// Read the tree block at the logical address `bytenr`, from the first copy
+/// that is good.
+pub fn read_tree_block(fs: &Fs, bytenr: u64, check: &Check) -> Result<Vec<u8>> {
+ let sectorsize = u64::from(fs.sectorsize);
+ if bytenr < sectorsize || !bytenr.is_multiple_of(sectorsize) {
+ return Err(Error::Corrupt(format!(
+ "tree block bytenr {bytenr} is not aligned to sectorsize {sectorsize}"
+ )));
+ }
+ let Some(entry) = fs.chunks.lookup(bytenr) else {
+ return Err(Error::Corrupt(format!(
+ "no chunk maps the tree block {bytenr}"
+ )));
+ };
+
+ // There is at least one copy
+ let copies = num_copies(entry);
+ let mut mirror = 0;
+ loop {
+ match read_mirror(fs, entry, bytenr, mirror, check) {
+ Ok(buf) => return Ok(buf),
+ Err(e) if mirror + 1 >= copies => return Err(e),
+ Err(_) => mirror += 1,
+ }
+ }
+}
diff --git a/rust/src/fs/volumes.rs b/rust/src/fs/volumes.rs
new file mode 100644
index 000000000000..85b1c9c88156
--- /dev/null
+++ b/rust/src/fs/volumes.rs
@@ -0,0 +1,497 @@
+//! The mapping of logical addresses to the devices, see `volumes.c`.
+
+use std::collections::BTreeMap;
+
+use crate::disk::consts::{block_group, objectid};
+use crate::disk::{Chunk, DiskKey, KeyType, Stripe, SuperBlock};
+use crate::sizes::*;
+use zerocopy::FromBytes;
+
+use crate::fs::error::{Error, Result};
+
+const STRIPE_LEN: u64 = SZ_64K as u64;
+
+pub struct StripeLoc {
+ pub devid: u64,
+ pub physical: u64,
+}
+
+/// A chunk, what `struct map_lookup` is in the C code.
+pub struct ChunkEntry {
+ /// The logical address
+ pub start: u64,
+ pub length: u64,
+ /// The type and the profile, `btrfs_chunk.type`
+ pub flags: u64,
+ pub stripe_len: u64,
+ pub sub_stripes: usize,
+ pub stripes: Vec<StripeLoc>,
+}
+
+/// Where a range of a chunk is stored.
+#[derive(Debug, PartialEq, Eq)]
+pub struct Mapping {
+ pub devid: u64,
+ pub physical: u64,
+ /// How many bytes from here are contiguous on the device.
+ pub len: u64,
+}
+
+#[derive(Default)]
+pub struct ChunkMap {
+ entries: BTreeMap<u64, ChunkEntry>,
+}
+
+impl ChunkMap {
+ /// Add a chunk, unless a chunk starts at the same address already.
+ pub fn insert(&mut self, entry: ChunkEntry) {
+ self.entries.entry(entry.start).or_insert(entry);
+ }
+
+ /// The chunk that has the logical address.
+ pub fn lookup(&self, logical: u64) -> Option<&ChunkEntry> {
+ let (_, entry) = self.entries.range(..=logical).next_back()?;
+ (logical - entry.start < entry.length).then_some(entry)
+ }
+
+ pub fn len(&self) -> usize {
+ self.entries.len()
+ }
+
+ pub fn is_empty(&self) -> bool {
+ self.entries.is_empty()
+ }
+
+ pub fn iter(&self) -> impl Iterator<Item = &ChunkEntry> {
+ self.entries.values()
+ }
+}
+
+fn nr_parity(flags: u64) -> usize {
+ if flags & block_group::RAID6 != 0 {
+ 2
+ } else if flags & block_group::RAID5 != 0 {
+ 1
+ } else {
+ 0
+ }
+}
+
+/// How many copies of the data there are, so how many mirrors can be read.
+pub fn num_copies(entry: &ChunkEntry) -> usize {
+ match entry.flags & block_group::PROFILE_MASK {
+ block_group::RAID1C4 => 4,
+ block_group::RAID1C3 => 3,
+ block_group::RAID1 | block_group::DUP | block_group::RAID10 => 2,
+ // RAID56 rebuild from the parity is not supported.
+ _ => 1,
+ }
+}
+
+/// Read version of `btrfs_map_block()`.
+///
+/// Note that, mirror 0 no longer means auto-select. Mirror 0 really means
+/// the first mirror.
+pub fn map_read(entry: &ChunkEntry, logical: u64, mirror: usize) -> Option<Mapping> {
+ if mirror >= num_copies(entry) {
+ return None;
+ }
+ let num_stripes = entry.stripes.len() as u64;
+ let offset = logical.checked_sub(entry.start)?;
+ if num_stripes == 0 || offset >= entry.length {
+ return None;
+ }
+
+ let mut stripe_nr = offset / entry.stripe_len;
+ let stripe_offset = offset % entry.stripe_len;
+ let flags = entry.flags;
+
+ let stripe_index: usize;
+ if flags & block_group::RAID1_MASK != 0 || flags & block_group::DUP != 0 {
+ stripe_index = mirror;
+ } else if flags & block_group::RAID10 != 0 {
+ let factor = num_stripes / entry.sub_stripes as u64;
+ stripe_index = (stripe_nr % factor) as usize * entry.sub_stripes + mirror;
+ stripe_nr /= factor;
+ } else if flags & block_group::RAID56_MASK != 0 {
+ let nr_data = num_stripes - nr_parity(flags) as u64;
+ let index = stripe_nr % nr_data;
+ stripe_nr /= nr_data;
+ // The parity is spread over the devices
+ stripe_index = ((stripe_nr + index) % num_stripes) as usize;
+ } else {
+ // Single and RAID0
+ stripe_index = (stripe_nr % num_stripes) as usize;
+ stripe_nr /= num_stripes;
+ }
+
+ let stripe = entry.stripes.get(stripe_index)?;
+ Some(Mapping {
+ devid: stripe.devid,
+ physical: stripe.physical + stripe_nr * entry.stripe_len + stripe_offset,
+ len: entry.stripe_len - stripe_offset,
+ })
+}
+
+/// `btrfs_chunk_item_size()`
+pub fn chunk_item_size(num_stripes: usize) -> usize {
+ size_of::<Chunk>() + size_of::<Stripe>() * num_stripes
+}
+
+/// The profile of a chunk: the number of copies and of parity stripes, and if
+/// `num_stripes` and `sub_stripes` are valid for it.
+fn profile_is_valid(flags: u64, num_stripes: u16, sub_stripes: u16) -> bool {
+ match flags & block_group::PROFILE_MASK {
+ block_group::RAID0 => true,
+ block_group::RAID10 => sub_stripes == 2,
+ block_group::RAID1 => num_stripes == 2,
+ block_group::RAID1C3 => num_stripes == 3,
+ block_group::RAID1C4 => num_stripes == 4,
+ block_group::RAID5 => num_stripes >= 2,
+ block_group::RAID6 => num_stripes >= 3,
+ block_group::DUP => num_stripes == 2,
+ _ => num_stripes == 1,
+ }
+}
+
+/// `btrfs_check_chunk_valid()`
+fn check_chunk(
+ chunk: &Chunk,
+ logical: u64,
+ sectorsize: u32,
+ mixed: bool,
+) -> std::result::Result<(), String> {
+ let length = chunk.length.get();
+ let stripe_len = chunk.stripe_len.get();
+ let num_stripes = chunk.num_stripes.get();
+ let sub_stripes = chunk.sub_stripes.get();
+ let flags = chunk.r#type.get();
+ let profile = flags & block_group::PROFILE_MASK;
+ let sectorsize = u64::from(sectorsize);
+
+ let ncopies = match profile {
+ block_group::RAID1C4 => 4,
+ block_group::RAID1C3 => 3,
+ block_group::RAID1 | block_group::DUP | block_group::RAID10 | block_group::RAID5 => 2,
+ block_group::RAID6 => 3,
+ _ => 1,
+ };
+ let nparity = nr_parity(flags);
+
+ if num_stripes == 0 {
+ return Err(format!("invalid chunk num_stripes, have {num_stripes}"));
+ }
+ if usize::from(num_stripes) < ncopies {
+ return Err(format!(
+ "invalid chunk num_stripes < ncopies, have {num_stripes} < {ncopies}"
+ ));
+ }
+ if nparity != 0 && usize::from(num_stripes) == nparity {
+ return Err(format!(
+ "invalid chunk num_stripes == nparity, have {num_stripes} == {nparity}"
+ ));
+ }
+ if !logical.is_multiple_of(sectorsize) {
+ return Err(format!(
+ "invalid chunk logical, have {logical} should aligned to {sectorsize}"
+ ));
+ }
+ if u64::from(chunk.sector_size.get()) != sectorsize {
+ return Err(format!(
+ "invalid chunk sectorsize, have {} expect {sectorsize}",
+ chunk.sector_size.get()
+ ));
+ }
+ if length == 0 || !length.is_multiple_of(sectorsize) {
+ return Err(format!("invalid chunk length, have {length}"));
+ }
+ if logical.checked_add(length).is_none() {
+ return Err(format!(
+ "invalid chunk logical start and length, have logical start {logical} length {length}"
+ ));
+ }
+ if stripe_len != STRIPE_LEN {
+ return Err(format!("invalid chunk stripe length: {stripe_len}"));
+ }
+ if length >= u64::from(u32::MAX) * STRIPE_LEN {
+ return Err(format!("chunk length too large: have {length}"));
+ }
+ let known = block_group::TYPE_MASK | block_group::PROFILE_MASK;
+ if flags & !known != 0 {
+ return Err(format!("unrecognized chunk type: 0x{:x}", flags & !known));
+ }
+ if profile.count_ones() > 1 {
+ return Err(format!(
+ "invalid chunk profile flag: 0x{profile:x}, expect 0 or 1 bit set"
+ ));
+ }
+ if flags & block_group::TYPE_MASK == 0 {
+ return Err(format!(
+ "missing chunk type flag, have 0x{flags:x} one bit must be set in 0x{:x}",
+ block_group::TYPE_MASK
+ ));
+ }
+ if flags & block_group::SYSTEM != 0 && flags & (block_group::METADATA | block_group::DATA) != 0
+ {
+ return Err(format!(
+ "system chunk with data or metadata type: 0x{flags:x}"
+ ));
+ }
+ if !mixed && flags & block_group::METADATA != 0 && flags & block_group::DATA != 0 {
+ return Err(format!("mixed chunk type in non-mixed mode: 0x{flags:x}"));
+ }
+ if !profile_is_valid(flags, num_stripes, sub_stripes) {
+ return Err(format!(
+ "invalid num_stripes:sub_stripes {num_stripes}:{sub_stripes} for profile {profile}"
+ ));
+ }
+ Ok(())
+}
+
+fn stripe_loc(stripe: &Stripe) -> StripeLoc {
+ StripeLoc {
+ devid: stripe.devid.get(),
+ physical: stripe.offset.get(),
+ }
+}
+
+/// A chunk from the payload of a chunk item, or of the system chunk array.
+pub fn parse_chunk(logical: u64, data: &[u8], sectorsize: u32, mixed: bool) -> Result<ChunkEntry> {
+ let too_small = || Error::Corrupt(format!("chunk {logical}: the item is too small"));
+
+ let Ok((chunk, rest)) = Chunk::ref_from_prefix(data) else {
+ return Err(too_small());
+ };
+ if let Err(msg) = check_chunk(chunk, logical, sectorsize, mixed) {
+ return Err(Error::Corrupt(format!("chunk {logical}: {msg}")));
+ }
+
+ let num_stripes = usize::from(chunk.num_stripes.get());
+ let Ok((parsed_stripes, _)) = <[Stripe]>::ref_from_prefix_with_elems(rest, num_stripes) else {
+ return Err(too_small());
+ };
+ let mut stripes = Vec::with_capacity(num_stripes);
+ for stripe in parsed_stripes {
+ stripes.push(stripe_loc(stripe));
+ }
+
+ Ok(ChunkEntry {
+ start: logical,
+ length: chunk.length.get(),
+ flags: chunk.r#type.get(),
+ stripe_len: chunk.stripe_len.get(),
+ sub_stripes: usize::from(chunk.sub_stripes.get()),
+ stripes,
+ })
+}
+
+/// The chunks in the system chunk array of the superblock, which are needed to
+/// read the chunk tree, see `btrfs_read_sys_array()`.
+pub fn read_sys_array(sb: &SuperBlock, sectorsize: u32, mixed: bool) -> Result<ChunkMap> {
+ let size = sb.sys_chunk_array_size.get() as usize;
+ let Some(array) = sb.sys_chunk_array.get(..size) else {
+ return Err(Error::Corrupt(format!(
+ "sys_array_size {size} shouldn't exceed {} bytes",
+ sb.sys_chunk_array.len()
+ )));
+ };
+
+ let mut map = ChunkMap::default();
+ let mut offset = 0;
+ while offset < size {
+ let Ok((key, _)) = DiskKey::ref_from_prefix(&array[offset..]) else {
+ return Err(Error::Corrupt(format!(
+ "sys_array too short to read {} bytes at offset {offset}",
+ size_of::<DiskKey>()
+ )));
+ };
+ offset += size_of::<DiskKey>();
+
+ if KeyType(key.r#type) != KeyType::CHUNK_ITEM
+ || key.objectid.get() != objectid::FIRST_CHUNK_TREE
+ {
+ return Err(Error::Corrupt(format!(
+ "unexpected item type {} in sys_array at offset {offset}",
+ key.r#type
+ )));
+ }
+
+ // At least a chunk with one stripe must be there, the number of
+ // stripes tells how much more
+ let rest = &array[offset..];
+ let Ok((chunk, _)) = Chunk::ref_from_prefix(rest) else {
+ return Err(Error::Corrupt(format!(
+ "sys_array too short to read {} bytes at offset {offset}",
+ chunk_item_size(1)
+ )));
+ };
+ let num_stripes = usize::from(chunk.num_stripes.get());
+ if num_stripes == 0 {
+ return Err(Error::Corrupt(format!(
+ "invalid number of stripes {num_stripes} in sys_array at offset {offset}"
+ )));
+ }
+ let len = chunk_item_size(num_stripes);
+ let Some(item) = rest.get(..len) else {
+ return Err(Error::Corrupt(format!(
+ "sys_array too short to read {len} bytes at offset {offset}"
+ )));
+ };
+
+ map.insert(parse_chunk(key.offset.get(), item, sectorsize, mixed)?);
+ offset += len;
+ }
+ Ok(map)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use zerocopy::{FromZeros, IntoBytes};
+
+ const START: u64 = SZ_1M as u64;
+ const SUB_STRIPE: u64 = 0x1000_0000;
+
+ /// Stripe `i` is on device `i + 1`, at `(i + 1) * SUB_STRIPE`.
+ fn entry(flags: u64, num_stripes: u64, sub_stripes: usize) -> ChunkEntry {
+ ChunkEntry {
+ start: START,
+ length: SZ_1G as u64,
+ flags,
+ stripe_len: STRIPE_LEN,
+ sub_stripes,
+ stripes: (0..num_stripes)
+ .map(|i| StripeLoc {
+ devid: i + 1,
+ physical: (i + 1) * SUB_STRIPE,
+ })
+ .collect(),
+ }
+ }
+
+ fn mapping(devid: u64, physical: u64, len: u64) -> Option<Mapping> {
+ Some(Mapping {
+ devid,
+ physical,
+ len,
+ })
+ }
+
+ #[test]
+ fn single_and_mirrored_profiles() {
+ let offset = 70000;
+ let single = entry(block_group::DATA, 1, 1);
+ assert_eq!(
+ map_read(&single, START + offset, 0),
+ mapping(1, SUB_STRIPE + offset, STRIPE_LEN - (offset - STRIPE_LEN))
+ );
+ assert_eq!(map_read(&single, START + offset, 1), None);
+
+ let raid1 = entry(block_group::METADATA | block_group::RAID1, 2, 1);
+ assert_eq!(num_copies(&raid1), 2);
+ assert_eq!(
+ map_read(&raid1, START + offset, 1),
+ mapping(
+ 2,
+ 2 * SUB_STRIPE + offset,
+ STRIPE_LEN - (offset - STRIPE_LEN)
+ )
+ );
+
+ let dup = entry(block_group::SYSTEM | block_group::DUP, 2, 1);
+ assert_eq!(map_read(&dup, START + (SZ_4K as u64), 1).unwrap().devid, 2);
+ assert_eq!(map_read(&dup, START + (SZ_4K as u64), 2), None);
+
+ // Outside of the chunk
+ assert_eq!(map_read(&single, START - 1, 0), None);
+ assert_eq!(map_read(&single, START + (SZ_1G as u64), 0), None);
+ }
+
+ #[test]
+ fn striped_profiles() {
+ // The 4th stripe of RAID0 over 3 devices is the 2nd one of device 1
+ let raid0 = entry(block_group::DATA | block_group::RAID0, 3, 1);
+ assert_eq!(
+ map_read(&raid0, START + 3 * STRIPE_LEN + 10, 0),
+ mapping(1, SUB_STRIPE + STRIPE_LEN + 10, STRIPE_LEN - 10)
+ );
+ assert_eq!(
+ map_read(&raid0, START + 4 * STRIPE_LEN + 5, 0),
+ mapping(2, 2 * SUB_STRIPE + STRIPE_LEN + 5, STRIPE_LEN - 5)
+ );
+
+ // The 4th stripe of RAID10 is on the 2nd pair, as the 2nd stripe
+ let raid10 = entry(block_group::DATA | block_group::RAID10, 4, 2);
+ assert_eq!(
+ map_read(&raid10, START + 3 * STRIPE_LEN + 7, 0),
+ mapping(3, 3 * SUB_STRIPE + STRIPE_LEN + 7, STRIPE_LEN - 7)
+ );
+ assert_eq!(
+ map_read(&raid10, START + 3 * STRIPE_LEN + 7, 1),
+ mapping(4, 4 * SUB_STRIPE + STRIPE_LEN + 7, STRIPE_LEN - 7)
+ );
+ assert_eq!(map_read(&raid10, START + 7, 2), None);
+
+ // RAID5 over 3 devices has 2 data stripes, and the parity moves on.
+ // The 4th data stripe is the 2nd one of the 2nd full stripe, which is
+ // rotated by 1.
+ let raid5 = entry(block_group::DATA | block_group::RAID5, 3, 1);
+ assert_eq!(num_copies(&raid5), 1);
+ assert_eq!(
+ map_read(&raid5, START + 3 * STRIPE_LEN + 9, 0),
+ mapping(3, 3 * SUB_STRIPE + STRIPE_LEN + 9, STRIPE_LEN - 9)
+ );
+ assert_eq!(map_read(&raid5, START + 9, 1), None);
+ }
+
+ fn chunk_bytes(flags: u64, num_stripes: u16, stripe_len: u64) -> Vec<u8> {
+ let mut chunk = Chunk::new_zeroed();
+ chunk.length = (SZ_8M as u64).into();
+ chunk.stripe_len = stripe_len.into();
+ chunk.r#type = flags.into();
+ chunk.sector_size = (SZ_4K as u32).into();
+ chunk.num_stripes = num_stripes.into();
+ chunk.sub_stripes = 1.into();
+
+ let mut bytes = chunk.as_bytes().to_vec();
+ for _ in 0..num_stripes {
+ bytes.extend_from_slice(Stripe::new_zeroed().as_bytes());
+ }
+ bytes
+ }
+
+ #[test]
+ fn invalid_chunks_are_refused() {
+ const SECTORSIZE: u32 = SZ_4K as u32;
+ let ok = chunk_bytes(block_group::DATA, 1, STRIPE_LEN);
+ assert_eq!(
+ parse_chunk(START, &ok, SECTORSIZE, false)
+ .unwrap()
+ .stripes
+ .len(),
+ 1
+ );
+
+ let bad_stripe_len = chunk_bytes(block_group::DATA, 1, SZ_4K as u64);
+ assert!(parse_chunk(START, &bad_stripe_len, SECTORSIZE, false).is_err());
+
+ let raid1_with_one_stripe =
+ chunk_bytes(block_group::DATA | block_group::RAID1, 1, STRIPE_LEN);
+ assert!(parse_chunk(START, &raid1_with_one_stripe, SECTORSIZE, false).is_err());
+
+ let no_stripes = chunk_bytes(block_group::DATA, 0, STRIPE_LEN);
+ assert!(parse_chunk(START, &no_stripes, SECTORSIZE, false).is_err());
+
+ let mixed = chunk_bytes(block_group::DATA | block_group::METADATA, 1, STRIPE_LEN);
+ assert!(parse_chunk(START, &mixed, SECTORSIZE, false).is_err());
+ assert!(parse_chunk(START, &mixed, SECTORSIZE, true).is_ok());
+
+ let remapped = chunk_bytes(block_group::DATA | block_group::REMAPPED, 1, STRIPE_LEN);
+ assert!(parse_chunk(START, &remapped, SECTORSIZE, false).is_err());
+
+ // Unaligned, and the second stripe is cut off
+ assert!(parse_chunk(START + 1, &ok, SECTORSIZE, false).is_err());
+ let two = chunk_bytes(block_group::DATA | block_group::RAID0, 2, STRIPE_LEN);
+ assert!(parse_chunk(START, &two[..two.len() - 1], SECTORSIZE, false).is_err());
+ }
+}
diff --git a/rust/src/sizes.rs b/rust/src/sizes.rs
index eb7aeea7bd3c..370c59056da9 100644
--- a/rust/src/sizes.rs
+++ b/rust/src/sizes.rs
@@ -11,6 +11,7 @@ pub const SZ_64K: usize = 64 * 1024;
pub const SZ_1M: usize = 1024 * 1024;
pub const SZ_2M: usize = 2 * 1024 * 1024;
pub const SZ_4M: usize = 4 * 1024 * 1024;
+pub const SZ_8M: usize = 8 * 1024 * 1024;
pub const SZ_64M: usize = 64 * 1024 * 1024;
pub const SZ_1G: usize = 1024 * 1024 * 1024;
--
2.56.1
^ permalink raw reply related [flat|nested] 16+ messages in thread* [PATCH 06/15] btrfs-progs: rust: fs: add device scanning with libblkid for multi-device filesystems
2026-12-01 7:56 [PATCH RFC 00/15] btrfs-progs: experimental rust support Qu Wenruo
` (4 preceding siblings ...)
2026-12-01 7:56 ` [PATCH 05/15] btrfs-progs: rust: fs: add Fs::open() Qu Wenruo
@ 2026-12-01 7:56 ` Qu Wenruo
2026-12-01 7:56 ` [PATCH 07/15] btrfs-progs: rust: implement btrfs_print_node in print_tree Qu Wenruo
` (8 subsequent siblings)
14 siblings, 0 replies; 16+ messages in thread
From: Qu Wenruo @ 2026-12-01 7:56 UTC (permalink / raw)
To: linux-btrfs
Use libblkid-rs to implement device discovery inspired by
btrfs_scan_devices().
When opening a filesystem with Fs::open(), if superblock.num_devices > 1,
scan_devices() queries the libblkid cache for all block devices with
TYPE=btrfs, checks candidate superblocks for matching fsid and
metadata_uuid, and registers unique devices until all filesystem members
are found.
---
rust/Cargo.lock | 330 ++++++++++++++++++++++++++++++++++++++++++
rust/Cargo.toml | 1 +
rust/src/fs/device.rs | 60 ++++++++
rust/src/fs/mod.rs | 9 +-
4 files changed, 398 insertions(+), 2 deletions(-)
diff --git a/rust/Cargo.lock b/rust/Cargo.lock
index 51750379a617..54b2db544fab 100644
--- a/rust/Cargo.lock
+++ b/rust/Cargo.lock
@@ -2,6 +2,15 @@
# It is not intended for manual editing.
version = 4
+[[package]]
+name = "aho-corasick"
+version = "1.1.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba"
+dependencies = [
+ "memchr",
+]
+
[[package]]
name = "anstream"
version = "1.0.0"
@@ -52,6 +61,32 @@ dependencies = [
"windows-sys",
]
+[[package]]
+name = "bindgen"
+version = "0.72.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "993776b509cfb49c750f11b8f07a46fa23e0a1386ffc01fb1e7d343efc387895"
+dependencies = [
+ "bitflags",
+ "cexpr",
+ "clang-sys",
+ "itertools",
+ "log",
+ "prettyplease",
+ "proc-macro2",
+ "quote",
+ "regex",
+ "rustc-hash",
+ "shlex 1.3.0",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "bitflags"
+version = "2.13.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
+
[[package]]
name = "blake2"
version = "0.10.6"
@@ -77,17 +112,54 @@ dependencies = [
"blake2",
"clap",
"crc32c",
+ "libblkid-rs",
"sha2",
"xxhash-rust",
"zerocopy",
]
+[[package]]
+name = "bumpalo"
+version = "3.20.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "87a0cf66fd1eb2fb7b822cb78370d82303750809bc6ba855f3f58e517d3238db"
+
+[[package]]
+name = "cc"
+version = "1.12.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "95e45cf2980b2d467be49a9ed942c9179b701063a7ca3d037de7ee9bd67f8d66"
+dependencies = [
+ "find-msvc-tools",
+ "shlex 2.0.1",
+]
+
+[[package]]
+name = "cexpr"
+version = "0.6.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6fac387a98bb7c37292057cffc56d62ecb629900026402633ae9160df93a8766"
+dependencies = [
+ "nom",
+]
+
[[package]]
name = "cfg-if"
version = "1.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"
+[[package]]
+name = "clang-sys"
+version = "1.9.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "157a8ba7b480713b56f4c09fd13fc3e0a22a5dfab8097ba61cbc5feef950788a"
+dependencies = [
+ "glob",
+ "libc",
+ "libloading",
+]
+
[[package]]
name = "clap"
version = "4.6.10"
@@ -173,6 +245,42 @@ dependencies = [
"subtle",
]
+[[package]]
+name = "either"
+version = "1.19.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be"
+
+[[package]]
+name = "find-msvc-tools"
+version = "0.1.16"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3e44f110d1777dc6559a51e7d45083945ded4f1bf3305494350f693b6d20b9c8"
+
+[[package]]
+name = "futures-core"
+version = "0.3.34"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e"
+
+[[package]]
+name = "futures-task"
+version = "0.3.34"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd"
+
+[[package]]
+name = "futures-util"
+version = "0.3.34"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc"
+dependencies = [
+ "futures-core",
+ "futures-task",
+ "pin-project-lite",
+ "slab",
+]
+
[[package]]
name = "generic-array"
version = "0.14.7"
@@ -183,6 +291,12 @@ dependencies = [
"version_check",
]
+[[package]]
+name = "glob"
+version = "0.3.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e4eba85ea1d0a966a983acd07deee566e67395d2d96b6fb39e62b5a833f1eb0b"
+
[[package]]
name = "heck"
version = "0.5.0"
@@ -195,18 +309,121 @@ version = "1.70.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695"
+[[package]]
+name = "itertools"
+version = "0.13.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "413ee7dfc52ee1a4949ceeb7dbc8a33f2d6c088194d9f922fb8318faf1f01186"
+dependencies = [
+ "either",
+]
+
+[[package]]
+name = "js-sys"
+version = "0.3.107"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8dc09d2154098bbf4ef54eab6b117a3c24cbbffe94046b16ee6d6d4510584d3a"
+dependencies = [
+ "cfg-if",
+ "futures-util",
+ "wasm-bindgen",
+]
+
+[[package]]
+name = "libblkid-rs"
+version = "0.4.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f6eee640d2d3e939915ef2576b4d0d6aa4d40d96b37cfbcec38c3c1ff7d4f221"
+dependencies = [
+ "either",
+ "libblkid-rs-sys",
+ "libc",
+ "uuid",
+]
+
+[[package]]
+name = "libblkid-rs-sys"
+version = "0.3.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5a49302d1b1c51dd61f0ae7bc3f3700ab812250866716013eb1b0921ba089476"
+dependencies = [
+ "bindgen",
+ "cc",
+ "pkg-config",
+]
+
[[package]]
name = "libc"
version = "0.2.191"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"
+[[package]]
+name = "libloading"
+version = "0.8.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d7c4b02199fee7c5d21a5ae7d8cfa79a6ef5bb2fc834d6e9058e89c825efdc55"
+dependencies = [
+ "cfg-if",
+ "windows-link",
+]
+
+[[package]]
+name = "log"
+version = "0.4.35"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c"
+
+[[package]]
+name = "memchr"
+version = "2.8.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
+
+[[package]]
+name = "minimal-lexical"
+version = "0.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a"
+
+[[package]]
+name = "nom"
+version = "7.1.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a"
+dependencies = [
+ "memchr",
+ "minimal-lexical",
+]
+
[[package]]
name = "once_cell_polyfill"
version = "1.70.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe"
+[[package]]
+name = "pin-project-lite"
+version = "0.2.18"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c938015719552d665fd0553b90d96cd7ff58e83e4c061ca99e6bb78865a72752"
+
+[[package]]
+name = "pkg-config"
+version = "0.3.34"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548"
+
+[[package]]
+name = "prettyplease"
+version = "0.2.37"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b"
+dependencies = [
+ "proc-macro2",
+ "syn 2.0.119",
+]
+
[[package]]
name = "proc-macro2"
version = "1.0.107"
@@ -225,6 +442,41 @@ dependencies = [
"proc-macro2",
]
+[[package]]
+name = "regex"
+version = "1.13.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9807af0e638c12e753aa1b4e601791bf2a8f71274023c8bbeec12fc149950857"
+dependencies = [
+ "aho-corasick",
+ "memchr",
+ "regex-automata",
+ "regex-syntax",
+]
+
+[[package]]
+name = "regex-automata"
+version = "0.4.19"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "41d60ef07df457506a0a1a2073112eb4aae5733dbd2813c3da77d1b0fd441158"
+dependencies = [
+ "aho-corasick",
+ "memchr",
+ "regex-syntax",
+]
+
+[[package]]
+name = "regex-syntax"
+version = "0.8.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d902046e6a28a1e4c3cab97258a0ce11e994903f01c2d97a9447a0b3df85f4f6"
+
+[[package]]
+name = "rustc-hash"
+version = "2.1.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d"
+
[[package]]
name = "rustc_version"
version = "0.4.1"
@@ -234,6 +486,12 @@ dependencies = [
"semver",
]
+[[package]]
+name = "rustversion"
+version = "1.0.23"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f"
+
[[package]]
name = "semver"
version = "1.0.28"
@@ -251,6 +509,24 @@ dependencies = [
"digest",
]
+[[package]]
+name = "shlex"
+version = "1.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64"
+
+[[package]]
+name = "shlex"
+version = "2.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"
+
+[[package]]
+name = "slab"
+version = "0.4.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5"
+
[[package]]
name = "strsim"
version = "0.11.1"
@@ -303,12 +579,66 @@ version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821"
+[[package]]
+name = "uuid"
+version = "1.29.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3c14b15dffa2f4bd712103e857140aa04a4f2ff6e955c77d7eb8e53ee02a3b64"
+dependencies = [
+ "js-sys",
+ "wasm-bindgen",
+]
+
[[package]]
name = "version_check"
version = "0.9.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
+[[package]]
+name = "wasm-bindgen"
+version = "0.2.130"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a0181c14ddd6c7b8b0b0132a5f1ea2f32be0d893cd3ea97b6e3b28886b8a3d1c"
+dependencies = [
+ "cfg-if",
+ "rustversion",
+ "wasm-bindgen-macro",
+ "wasm-bindgen-shared",
+]
+
+[[package]]
+name = "wasm-bindgen-macro"
+version = "0.2.130"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6e931a02a39abdbf66966fc35902b5ed58344750a70885bed4ebb3d8eaf28ed9"
+dependencies = [
+ "quote",
+ "wasm-bindgen-macro-support",
+]
+
+[[package]]
+name = "wasm-bindgen-macro-support"
+version = "0.2.130"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2ca4b54280e455bd831e33a6b8e734baf432fe63fbc35c42ac14ce67a043a53a"
+dependencies = [
+ "bumpalo",
+ "proc-macro2",
+ "quote",
+ "syn 3.0.10",
+ "wasm-bindgen-shared",
+]
+
+[[package]]
+name = "wasm-bindgen-shared"
+version = "0.2.130"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3b1f9c3798725016c6ee5f2f57869ec0831e8bbc0ab0310a86e787e97f41389e"
+dependencies = [
+ "unicode-ident",
+]
+
[[package]]
name = "windows-link"
version = "0.2.1"
diff --git a/rust/Cargo.toml b/rust/Cargo.toml
index 1353123f34aa..c253623fe1e6 100644
--- a/rust/Cargo.toml
+++ b/rust/Cargo.toml
@@ -13,3 +13,4 @@ crc32c = "0.6"
xxhash-rust = { version = "0.8", features = ["xxh64"] }
sha2 = "0.10"
blake2 = "0.10"
+libblkid-rs = "0.4.2"
diff --git a/rust/src/fs/device.rs b/rust/src/fs/device.rs
index 40d617e22cb3..2e48588348e9 100644
--- a/rust/src/fs/device.rs
+++ b/rust/src/fs/device.rs
@@ -4,6 +4,9 @@ use std::fs::File;
use std::os::unix::fs::FileExt;
use std::path::{Path, PathBuf};
+use libblkid_rs::BlkidCache;
+
+use crate::disk::consts::super_offset;
use crate::disk::SuperBlock;
use crate::fs::error::{Error, Result};
@@ -48,3 +51,60 @@ pub fn open_device(path: &Path, sb_bytenr: u64) -> Result<(Device, Box<SuperBloc
};
Ok((device, sb))
}
+
+/// Query all devices recognized as Btrfs by `libblkid`, like `btrfs_scan_devices()`.
+pub fn scan_btrfs_devices_blkid() -> Vec<PathBuf> {
+ let mut paths = Vec::new();
+ let Ok(mut cache) = BlkidCache::get_cache(None) else {
+ return paths;
+ };
+ if cache.probe_all().is_err() {
+ return paths;
+ }
+ let Ok(iter) = cache.iter().search("TYPE", "btrfs") else {
+ return paths;
+ };
+ for dev in iter {
+ if let Ok(path) = dev.devname() {
+ paths.push(path);
+ }
+ }
+ paths
+}
+
+/// Scan for other devices belonging to the filesystem of `superblock` using
+/// `libblkid-rs`, like `btrfs_scan_devices()`.
+pub fn scan_devices(
+ first_device_path: &Path,
+ superblock: &SuperBlock,
+ known_devices: &mut Vec<Device>,
+) {
+ let target_count = superblock.num_devices.get() as usize;
+ if known_devices.len() >= target_count {
+ return;
+ }
+
+ let sb_bytenr = super_offset(0);
+ for path in scan_btrfs_devices_blkid() {
+ if path == first_device_path {
+ continue;
+ }
+
+ let Ok((device, sb)) = open_device(&path, sb_bytenr) else {
+ continue;
+ };
+
+ if sb.fsid != superblock.fsid || sb.metadata_uuid != superblock.metadata_uuid {
+ continue;
+ }
+
+ if known_devices.iter().any(|d| d.devid == device.devid) {
+ continue;
+ }
+
+ known_devices.push(device);
+ if known_devices.len() >= target_count {
+ break;
+ }
+ }
+}
diff --git a/rust/src/fs/mod.rs b/rust/src/fs/mod.rs
index e9843348b8b8..c257b08aab44 100644
--- a/rust/src/fs/mod.rs
+++ b/rust/src/fs/mod.rs
@@ -16,7 +16,7 @@ use crate::disk::block::{self, item_data, View};
use crate::disk::consts::{incompat, objectid, super_offset};
use crate::disk::{Key, KeyType, SuperBlock};
-use crate::fs::device::{open_device, Device};
+use crate::fs::device::{open_device, scan_devices, Device};
use crate::fs::superblock::check_compatibility;
use crate::fs::tree_block::{read_tree_block, Check};
use crate::fs::volumes::{parse_chunk, read_sys_array, ChunkMap};
@@ -49,12 +49,17 @@ pub struct Fs {
impl Fs {
/// Open the filesystem of `device`, with the primary superblock of it.
+ /// If the filesystem has multiple devices, scans for the other devices
+ /// using `libblkid`.
pub fn open(device: &Path) -> Result<Fs> {
let sb_bytenr = super_offset(0);
let (first, superblock) = open_device(device, sb_bytenr)?;
check_compatibility(&superblock)?;
- let devices = vec![first];
+ let mut devices = vec![first];
+ if superblock.num_devices.get() > 1 {
+ scan_devices(device, &superblock, &mut devices);
+ }
let sectorsize = superblock.sectorsize.get();
let csum_type = superblock.csum_type.get();
--
2.56.1
^ permalink raw reply related [flat|nested] 16+ messages in thread* [PATCH 07/15] btrfs-progs: rust: implement btrfs_print_node in print_tree
2026-12-01 7:56 [PATCH RFC 00/15] btrfs-progs: experimental rust support Qu Wenruo
` (5 preceding siblings ...)
2026-12-01 7:56 ` [PATCH 06/15] btrfs-progs: rust: fs: add device scanning with libblkid for multi-device filesystems Qu Wenruo
@ 2026-12-01 7:56 ` Qu Wenruo
2026-12-01 7:56 ` [PATCH 08/15] btrfs-progs: rust: print_tree: add print_leaf and chunk tree items Qu Wenruo
` (7 subsequent siblings)
14 siblings, 0 replies; 16+ messages in thread
From: Qu Wenruo @ 2026-12-01 7:56 UTC (permalink / raw)
To: linux-btrfs
Implement print_node() and print_header_info() in print_tree.rs,
mirroring btrfs_print_tree() from kernel-shared/print-tree.c.
print_node() takes &Fs and a node &View<'_>, computes the free space
using fs.nodesize, formats the node header (bytenr, level, items,
free space, generation, owner, flags, backref revision, and UUIDs),
and formats each KeyPtr entry with print_key().
Also add print_tree() and btrfs-rs inspect-internal dump-tree supporting
-b <bytenr> to dump and verify tree blocks without unused code warnings.
---
rust/src/cmds/inspect_dump_tree.rs | 271 +++++++++++++++++++++++++++++
rust/src/cmds/inspect_internal.rs | 5 +-
rust/src/cmds/mod.rs | 1 +
rust/src/print_tree.rs | 161 ++++++++++++++++-
4 files changed, 435 insertions(+), 3 deletions(-)
create mode 100644 rust/src/cmds/inspect_dump_tree.rs
diff --git a/rust/src/cmds/inspect_dump_tree.rs b/rust/src/cmds/inspect_dump_tree.rs
new file mode 100644
index 000000000000..a01e764c4b82
--- /dev/null
+++ b/rust/src/cmds/inspect_dump_tree.rs
@@ -0,0 +1,271 @@
+//! `btrfs-rs inspect-internal dump-tree`, see `cmds/inspect-dump-tree.c`.
+
+use std::io::{self, BufWriter, Write};
+use std::path::PathBuf;
+
+use btrfs_rs::disk::block;
+use btrfs_rs::fs::tree_block::{read_tree_block, Check};
+use btrfs_rs::fs::Fs;
+use clap::Args as ClapArgs;
+
+use super::{Failed, Result};
+use crate::messages::error_flushing;
+use crate::print_tree::print_tree;
+
+#[derive(ClapArgs)]
+#[command(override_usage = "btrfs-rs inspect-internal dump-tree [options] <device>")]
+pub struct Args {
+ /// specify block bytenr to dump (can be specified multiple times)
+ #[arg(short = 'b', long = "block", action = clap::ArgAction::Append)]
+ pub block: Vec<u64>,
+
+ /// device to read
+ pub device: PathBuf,
+}
+
+pub fn run(args: Args) -> Result {
+ let mut out = BufWriter::new(io::stdout().lock());
+
+ if args.block.is_empty() {
+ error_flushing(
+ &mut out,
+ "dumping the whole tree is not supported yet; please specify -b <bytenr>",
+ );
+ return Err(Failed);
+ }
+
+ let fs = match Fs::open(&args.device) {
+ Ok(fs) => fs,
+ Err(e) => {
+ error_flushing(
+ &mut out,
+ format!("unable to open {}: {e}", args.device.display()),
+ );
+ return Err(Failed);
+ }
+ };
+
+ let mut blocks = args.block;
+ blocks.sort_unstable();
+ blocks.dedup();
+
+ for bytenr in blocks {
+ let buf = match read_tree_block(&fs, bytenr, &Check::default()) {
+ Ok(buf) => buf,
+ Err(e) => {
+ error_flushing(
+ &mut out,
+ format!("failed to read tree block at {bytenr}: {e}"),
+ );
+ return Err(Failed);
+ }
+ };
+
+ let view = match block::parse_block(&buf) {
+ Ok(view) => view,
+ Err(e) => {
+ error_flushing(&mut out, format!("corrupted tree block at {bytenr}: {e}"));
+ return Err(Failed);
+ }
+ };
+
+ if let Err(e) = print_tree(&mut out, &fs, &view) {
+ error_flushing(
+ &mut out,
+ format!("failed to print tree block at {bytenr}: {e}"),
+ );
+ return Err(Failed);
+ }
+ }
+
+ out.flush()?;
+ Ok(())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use btrfs_rs::disk::consts::{block_group, csum_type, limits, magic, objectid, super_offset};
+ use btrfs_rs::disk::{csum, Chunk, DiskKey, Header, Item, KeyPtr, KeyType, SuperBlock};
+ use btrfs_rs::sizes::*;
+ use zerocopy::{FromZeros, IntoBytes};
+
+ const CHUNK_ROOT: u64 = 0x110000;
+ const SYSTEM_START: u64 = 0x100000;
+ const NODESIZE: usize = SZ_16K;
+ const HEADER_SIZE: usize = size_of::<Header>();
+
+ fn chunk_item(flags: u64, start: u64) -> Vec<u8> {
+ let mut chunk = Chunk::new_zeroed();
+ chunk.length = (SZ_1M as u64).into();
+ chunk.stripe_len = (SZ_64K as u64).into();
+ chunk.r#type = flags.into();
+ chunk.sector_size = (SZ_4K as u32).into();
+ chunk.num_stripes = 1.into();
+ chunk.sub_stripes = 1.into();
+ chunk.stripe.devid = 1.into();
+ chunk.stripe.offset = start.into();
+ chunk.as_bytes().to_vec()
+ }
+
+ fn chunk_key(start: u64) -> DiskKey {
+ DiskKey {
+ objectid: objectid::FIRST_CHUNK_TREE.into(),
+ r#type: KeyType::CHUNK_ITEM.0,
+ offset: start.into(),
+ }
+ }
+
+ fn chunk_tree_leaf() -> Vec<u8> {
+ let mut header = Header::new_zeroed();
+ header.bytenr = CHUNK_ROOT.into();
+ header.level = 0;
+ header.nritems = 1.into();
+ header.owner = objectid::CHUNK_TREE.into();
+ header.generation = 5.into();
+ header.fsid = [0x11; 16];
+
+ let chunks = [(SYSTEM_START, chunk_item(block_group::SYSTEM, SYSTEM_START))];
+ let mut buf = vec![0u8; NODESIZE];
+ buf[..HEADER_SIZE].copy_from_slice(header.as_bytes());
+
+ let mut data_end = NODESIZE - HEADER_SIZE;
+ for (i, (start, data)) in chunks.iter().enumerate() {
+ data_end -= data.len();
+ let item = Item {
+ key: chunk_key(*start),
+ offset: (data_end as u32).into(),
+ size: (data.len() as u32).into(),
+ };
+ let at = HEADER_SIZE + i * size_of::<Item>();
+ buf[at..at + size_of::<Item>()].copy_from_slice(item.as_bytes());
+ buf[HEADER_SIZE + data_end..][..data.len()].copy_from_slice(data);
+ }
+ let csum = csum::compute(csum_type::CRC32, &buf[limits::CSUM_SIZE..]).unwrap();
+ buf[..limits::CSUM_SIZE].copy_from_slice(&csum);
+ buf
+ }
+
+ fn node_block(bytenr: u64, child_bytenr: u64) -> Vec<u8> {
+ let mut header = Header::new_zeroed();
+ header.bytenr = bytenr.into();
+ header.level = 1;
+ header.nritems = 1.into();
+ header.owner = objectid::FS_TREE.into();
+ header.generation = 6.into();
+ header.fsid = [0x11; 16];
+
+ let mut ptr = KeyPtr::new_zeroed();
+ ptr.key.objectid = 256.into();
+ ptr.key.r#type = KeyType::INODE_ITEM.0;
+ ptr.key.offset = 0.into();
+ ptr.blockptr = child_bytenr.into();
+ ptr.generation = 6.into();
+
+ let mut buf = vec![0u8; NODESIZE];
+ buf[..HEADER_SIZE].copy_from_slice(header.as_bytes());
+ buf[HEADER_SIZE..HEADER_SIZE + size_of::<KeyPtr>()].copy_from_slice(ptr.as_bytes());
+
+ let csum = csum::compute(csum_type::CRC32, &buf[limits::CSUM_SIZE..]).unwrap();
+ buf[..limits::CSUM_SIZE].copy_from_slice(&csum);
+ buf
+ }
+
+ fn device_image_with_node(node_bytenr: u64) -> Vec<u8> {
+ let mut sb = SuperBlock::new_zeroed();
+ sb.bytenr = super_offset(0).into();
+ sb.magic = magic::BTRFS.into();
+ sb.csum_type = csum_type::CRC32.into();
+ sb.fsid = [0x11; 16];
+ sb.dev_item.fsid = [0x11; 16];
+ sb.nodesize = (SZ_16K as u32).into();
+ sb.sectorsize = (SZ_4K as u32).into();
+ sb.stripesize = (SZ_4K as u32).into();
+ sb.total_bytes = (SZ_64M as u64).into();
+ sb.bytes_used = (SZ_1M as u64).into();
+ sb.num_devices = 1.into();
+ sb.chunk_root = CHUNK_ROOT.into();
+ sb.chunk_root_generation = 5.into();
+ sb.root = node_bytenr.into();
+ sb.generation = 6.into();
+ sb.dev_item.devid = 1.into();
+
+ let array = [
+ chunk_key(SYSTEM_START).as_bytes(),
+ &chunk_item(block_group::SYSTEM, SYSTEM_START),
+ ]
+ .concat();
+ sb.sys_chunk_array_size = (array.len() as u32).into();
+ sb.sys_chunk_array[..array.len()].copy_from_slice(&array);
+
+ let csum = csum::compute(csum_type::CRC32, &sb.as_bytes()[limits::CSUM_SIZE..]).unwrap();
+ sb.csum = csum;
+
+ let mut image = vec![0u8; 3 * SZ_1M];
+ image[super_offset(0) as usize..][..SZ_4K].copy_from_slice(sb.as_bytes());
+ image[CHUNK_ROOT as usize..][..NODESIZE].copy_from_slice(&chunk_tree_leaf());
+ image[node_bytenr as usize..][..NODESIZE]
+ .copy_from_slice(&node_block(node_bytenr, CHUNK_ROOT));
+ image
+ }
+
+ struct TestDevice(PathBuf);
+
+ impl TestDevice {
+ fn new(name: &str, image: &[u8]) -> TestDevice {
+ let path = std::env::temp_dir()
+ .join(format!("btrfs-dump-tree-{}-{name}.img", std::process::id()));
+ std::fs::write(&path, image).unwrap();
+ TestDevice(path)
+ }
+ }
+
+ impl Drop for TestDevice {
+ fn drop(&mut self) {
+ let _ = std::fs::remove_file(&self.0);
+ }
+ }
+
+ #[test]
+ fn dump_tree_without_block_option_is_rejected() {
+ let dev = TestDevice::new("noblock", &device_image_with_node(0x120000));
+ let args = Args {
+ block: Vec::new(),
+ device: dev.0.clone(),
+ };
+ assert!(run(args).is_err());
+ }
+
+ #[test]
+ fn dump_tree_node_succeeds() {
+ let node_bytenr = 0x120000;
+ let dev = TestDevice::new("node", &device_image_with_node(node_bytenr));
+ let args = Args {
+ block: vec![node_bytenr],
+ device: dev.0.clone(),
+ };
+ assert!(run(args).is_ok());
+ }
+
+ #[test]
+ fn dump_tree_multiple_blocks_succeeds() {
+ let node_bytenr = 0x120000;
+ let dev = TestDevice::new("multiple", &device_image_with_node(node_bytenr));
+ let args = Args {
+ block: vec![node_bytenr, node_bytenr],
+ device: dev.0.clone(),
+ };
+ assert!(run(args).is_ok());
+ }
+
+ #[test]
+ fn dump_tree_leaf_is_rejected_as_unsupported() {
+ let dev = TestDevice::new("leaf", &device_image_with_node(0x120000));
+ // CHUNK_ROOT is a leaf (level 0)
+ let args = Args {
+ block: vec![CHUNK_ROOT],
+ device: dev.0.clone(),
+ };
+ assert!(run(args).is_err());
+ }
+}
diff --git a/rust/src/cmds/inspect_internal.rs b/rust/src/cmds/inspect_internal.rs
index 617f113c1d0f..a6120e69f11a 100644
--- a/rust/src/cmds/inspect_internal.rs
+++ b/rust/src/cmds/inspect_internal.rs
@@ -2,7 +2,7 @@
use clap::{Args as ClapArgs, Subcommand};
-use super::{inspect_dump_super, Result};
+use super::{inspect_dump_super, inspect_dump_tree, Result};
#[derive(ClapArgs)]
pub struct Args {
@@ -14,10 +14,13 @@ pub struct Args {
enum Command {
/// Dump superblock from a device in a textual form
DumpSuper(inspect_dump_super::Args),
+ /// Dump tree in a textual form
+ DumpTree(inspect_dump_tree::Args),
}
pub fn run(args: Args) -> Result {
match args.command {
Command::DumpSuper(args) => inspect_dump_super::run(args),
+ Command::DumpTree(args) => inspect_dump_tree::run(args),
}
}
diff --git a/rust/src/cmds/mod.rs b/rust/src/cmds/mod.rs
index 8b331f6e27ee..5f8ff124c7f9 100644
--- a/rust/src/cmds/mod.rs
+++ b/rust/src/cmds/mod.rs
@@ -5,6 +5,7 @@ use std::io;
use crate::messages::{error, strerror};
pub mod inspect_dump_super;
+pub mod inspect_dump_tree;
pub mod inspect_internal;
/// The command has failed and already reported why. The exit status is 1.
diff --git a/rust/src/print_tree.rs b/rust/src/print_tree.rs
index 61ab5549be49..3e3df39e7ad4 100644
--- a/rust/src/print_tree.rs
+++ b/rust/src/print_tree.rs
@@ -3,10 +3,14 @@
use std::io::{self, Write};
+use btrfs_rs::disk::block::View;
use btrfs_rs::disk::consts::{
- block_group, compat_ro, header_flag, incompat, limits, magic, objectid, super_flag,
+ backref_rev, block_group, compat_ro, header_flag, incompat, limits, magic, objectid, super_flag,
};
-use btrfs_rs::disk::{csum, Chunk, DiskKey, KeyType, RootBackup, Stripe, SuperBlock};
+use btrfs_rs::disk::{
+ csum, Chunk, DiskKey, Header, KeyPtr, KeyType, RootBackup, Stripe, SuperBlock,
+};
+use btrfs_rs::fs::Fs;
use zerocopy::{FromBytes, IntoBytes};
use crate::messages::error_flushing;
@@ -169,6 +173,95 @@ pub fn print_key(out: &mut impl Write, key: &DiskKey) -> io::Result<()> {
}
}
+fn header_flags_to_str(flags: u64) -> String {
+ let mut parts = Vec::new();
+ if flags & header_flag::WRITTEN != 0 {
+ parts.push("WRITTEN");
+ }
+ if flags & header_flag::RELOC != 0 {
+ parts.push("RELOC");
+ }
+ parts.join("|")
+}
+
+pub fn print_header_info(out: &mut impl Write, header: &Header, free_space: u32) -> io::Result<()> {
+ let flags = header.flags.get() & !backref_rev::MASK;
+ let backref_rev = header.flags.get() >> backref_rev::SHIFT;
+ let flags_str = header_flags_to_str(flags);
+ let owner = objectid_string(header.owner.get(), KeyType(0));
+
+ if header.level > 0 {
+ writeln!(
+ out,
+ "node {} level {} items {} free space {} generation {} owner {owner}",
+ header.bytenr.get(),
+ header.level,
+ header.nritems.get(),
+ free_space,
+ header.generation.get(),
+ )?;
+ writeln!(
+ out,
+ "node {} flags 0x{:x}({flags_str}) backref revision {backref_rev}",
+ header.bytenr.get(),
+ flags
+ )?;
+ } else {
+ writeln!(
+ out,
+ "leaf {} items {} free space {} generation {} owner {owner}",
+ header.bytenr.get(),
+ header.nritems.get(),
+ free_space,
+ header.generation.get(),
+ )?;
+ writeln!(
+ out,
+ "leaf {} flags 0x{:x}({flags_str}) backref revision {backref_rev}",
+ header.bytenr.get(),
+ flags
+ )?;
+ }
+ writeln!(out, "fs uuid {}", uuid_unparse(&header.fsid))?;
+ writeln!(out, "chunk uuid {}", uuid_unparse(&header.chunk_tree_uuid))?;
+ Ok(())
+}
+
+/// `btrfs_print_tree()` / `btrfs_print_node()` for a node.
+pub fn print_node(out: &mut impl Write, fs: &Fs, view: &View<'_>) -> io::Result<()> {
+ let View::Node { header, ptrs } = view else {
+ panic!("print_node called on a leaf");
+ };
+
+ let max_ptrs = (fs.nodesize as usize - size_of::<Header>()) / size_of::<KeyPtr>();
+ let free_space = max_ptrs.saturating_sub(ptrs.len()) as u32;
+
+ print_header_info(out, header, free_space)?;
+
+ for ptr in *ptrs {
+ write!(out, "\t")?;
+ print_key(out, &ptr.key)?;
+ writeln!(
+ out,
+ " block {} gen {}",
+ ptr.blockptr.get(),
+ ptr.generation.get()
+ )?;
+ }
+ Ok(())
+}
+
+/// `btrfs_print_tree()` for any tree block.
+pub fn print_tree(out: &mut impl Write, fs: &Fs, view: &View<'_>) -> io::Result<()> {
+ match view {
+ View::Node { .. } => print_node(out, fs, view),
+ View::Leaf { .. } => Err(io::Error::new(
+ io::ErrorKind::Unsupported,
+ "leaf printing is not supported yet",
+ )),
+ }
+}
+
/// The `bg_flags_to_str()` of print-tree.c, including how it joins the names.
fn bg_flags_to_str(flags: u64) -> String {
let mut ret = String::new();
@@ -630,3 +723,67 @@ pub fn print_superblock(out: &mut impl Write, sb: &SuperBlock, full: bool) -> io
}
Ok(())
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use btrfs_rs::disk::block;
+ use btrfs_rs::sizes::*;
+ use zerocopy::FromZeros;
+
+ #[test]
+ fn print_node_format() {
+ let mut header = Header::new_zeroed();
+ header.bytenr = (SZ_1M as u64).into();
+ header.level = 1;
+ header.nritems = 1.into();
+ header.generation = 42.into();
+ header.owner = objectid::ROOT_TREE.into();
+ header.flags = (header_flag::WRITTEN | (1u64 << backref_rev::SHIFT)).into();
+ header.fsid = [0x22; 16];
+ header.chunk_tree_uuid = [0x33; 16];
+
+ let mut ptr = KeyPtr::new_zeroed();
+ ptr.key.objectid = 256.into();
+ ptr.key.r#type = KeyType::INODE_ITEM.0;
+ ptr.key.offset = 0.into();
+ ptr.blockptr = (2 * SZ_1M as u64).into();
+ ptr.generation = 42.into();
+
+ let mut buf = vec![0u8; SZ_16K];
+ buf[..size_of::<Header>()].copy_from_slice(header.as_bytes());
+ buf[size_of::<Header>()..size_of::<Header>() + size_of::<KeyPtr>()]
+ .copy_from_slice(ptr.as_bytes());
+
+ let view = block::parse_block(&buf).unwrap();
+
+ let mut sb = SuperBlock::new_zeroed();
+ sb.nodesize = (SZ_16K as u32).into();
+ sb.sectorsize = (SZ_4K as u32).into();
+ sb.magic = magic::BTRFS.into();
+
+ let fs = Fs {
+ superblock: Box::new(sb),
+ devices: Vec::new(),
+ chunks: Default::default(),
+ sectorsize: SZ_4K as u32,
+ nodesize: SZ_16K as u32,
+ csum_type: 0,
+ csum_size: 4,
+ metadata_fsid: [0x22; 16],
+ tree_root: btrfs_rs::fs::Root::default(),
+ chunk_root: btrfs_rs::fs::Root::default(),
+ };
+
+ let mut out = Vec::new();
+ print_node(&mut out, &fs, &view).unwrap();
+ let output = String::from_utf8(out).unwrap();
+
+ assert!(output.contains("node 1048576 level 1 items 1"));
+ assert!(output.contains("owner ROOT_TREE"));
+ assert!(output.contains("flags 0x1(WRITTEN) backref revision 1"));
+ assert!(output.contains("fs uuid 22222222-2222-2222-2222-222222222222"));
+ assert!(output.contains("chunk uuid 33333333-3333-3333-3333-333333333333"));
+ assert!(output.contains("\tkey (256 INODE_ITEM 0) block 2097152 gen 42"));
+ }
+}
--
2.56.1
^ permalink raw reply related [flat|nested] 16+ messages in thread* [PATCH 08/15] btrfs-progs: rust: print_tree: add print_leaf and chunk tree items
2026-12-01 7:56 [PATCH RFC 00/15] btrfs-progs: experimental rust support Qu Wenruo
` (6 preceding siblings ...)
2026-12-01 7:56 ` [PATCH 07/15] btrfs-progs: rust: implement btrfs_print_node in print_tree Qu Wenruo
@ 2026-12-01 7:56 ` Qu Wenruo
2026-12-01 7:56 ` [PATCH 09/15] btrfs-progs: rust: print_tree: add subvolume " Qu Wenruo
` (6 subsequent siblings)
14 siblings, 0 replies; 16+ messages in thread
From: Qu Wenruo @ 2026-12-01 7:56 UTC (permalink / raw)
To: linux-btrfs
Implement print_leaf() in print_tree.rs, matching C __btrfs_print_leaf()
from kernel-shared/print-tree.c.
print_leaf() calculates leaf free space as in btrfs_leaf_free_space(),
prints the leaf header with print_header_info(), and formats each item
header. Implement print_dev_item() for DEV_ITEM alongside CHUNK_ITEM.
Update print_tree() to dispatch View::Leaf to print_leaf(), and update
inspect-internal dump-tree test to verify leaf dumping.
---
rust/src/cmds/inspect_dump_tree.rs | 16 ++-
rust/src/print_tree.rs | 200 ++++++++++++++++++++++++++++-
2 files changed, 203 insertions(+), 13 deletions(-)
diff --git a/rust/src/cmds/inspect_dump_tree.rs b/rust/src/cmds/inspect_dump_tree.rs
index a01e764c4b82..b151c21bf596 100644
--- a/rust/src/cmds/inspect_dump_tree.rs
+++ b/rust/src/cmds/inspect_dump_tree.rs
@@ -86,7 +86,7 @@ pub fn run(args: Args) -> Result {
mod tests {
use super::*;
use btrfs_rs::disk::consts::{block_group, csum_type, limits, magic, objectid, super_offset};
- use btrfs_rs::disk::{csum, Chunk, DiskKey, Header, Item, KeyPtr, KeyType, SuperBlock};
+ use btrfs_rs::disk::{csum, Chunk, DiskKey, Header, Item, KeyPtr, KeyType, Stripe, SuperBlock};
use btrfs_rs::sizes::*;
use zerocopy::{FromZeros, IntoBytes};
@@ -103,9 +103,11 @@ mod tests {
chunk.sector_size = (SZ_4K as u32).into();
chunk.num_stripes = 1.into();
chunk.sub_stripes = 1.into();
- chunk.stripe.devid = 1.into();
- chunk.stripe.offset = start.into();
- chunk.as_bytes().to_vec()
+
+ let mut stripe = Stripe::new_zeroed();
+ stripe.devid = 1.into();
+ stripe.offset = start.into();
+ [chunk.as_bytes(), stripe.as_bytes()].concat()
}
fn chunk_key(start: u64) -> DiskKey {
@@ -259,13 +261,13 @@ mod tests {
}
#[test]
- fn dump_tree_leaf_is_rejected_as_unsupported() {
+ fn dump_tree_leaf_succeeds() {
let dev = TestDevice::new("leaf", &device_image_with_node(0x120000));
- // CHUNK_ROOT is a leaf (level 0)
+ // CHUNK_ROOT is a leaf (level 0) containing CHUNK_ITEM
let args = Args {
block: vec![CHUNK_ROOT],
device: dev.0.clone(),
};
- assert!(run(args).is_err());
+ assert!(run(args).is_ok());
}
}
diff --git a/rust/src/print_tree.rs b/rust/src/print_tree.rs
index 3e3df39e7ad4..d4d9eb19503b 100644
--- a/rust/src/print_tree.rs
+++ b/rust/src/print_tree.rs
@@ -3,12 +3,12 @@
use std::io::{self, Write};
-use btrfs_rs::disk::block::View;
+use btrfs_rs::disk::block::{item_data, View};
use btrfs_rs::disk::consts::{
backref_rev, block_group, compat_ro, header_flag, incompat, limits, magic, objectid, super_flag,
};
use btrfs_rs::disk::{
- csum, Chunk, DiskKey, Header, KeyPtr, KeyType, RootBackup, Stripe, SuperBlock,
+ csum, Chunk, DevItem, DiskKey, Header, KeyPtr, KeyType, RootBackup, Stripe, SuperBlock,
};
use btrfs_rs::fs::Fs;
use zerocopy::{FromBytes, IntoBytes};
@@ -251,14 +251,91 @@ pub fn print_node(out: &mut impl Write, fs: &Fs, view: &View<'_>) -> io::Result<
Ok(())
}
+/// `print_dev_item()`, `data` is the item payload.
+pub fn print_dev_item(out: &mut impl Write, data: &[u8]) -> io::Result<()> {
+ let Ok((dev, _)) = DevItem::ref_from_prefix(data) else {
+ return writeln!(out, "\t\tdev item invalid");
+ };
+ writeln!(
+ out,
+ "\t\tdevid {} total_bytes {} bytes_used {}",
+ dev.devid.get(),
+ dev.total_bytes.get(),
+ dev.bytes_used.get()
+ )?;
+ writeln!(
+ out,
+ "\t\tio_align {} io_width {} sector_size {} type {}",
+ dev.io_align.get(),
+ dev.io_width.get(),
+ dev.sector_size.get(),
+ dev.r#type.get()
+ )?;
+ writeln!(
+ out,
+ "\t\tgeneration {} start_offset {} dev_group {}",
+ dev.generation.get(),
+ dev.start_offset.get(),
+ dev.dev_group.get()
+ )?;
+ writeln!(
+ out,
+ "\t\tseek_speed {} bandwidth {}",
+ dev.seek_speed, dev.bandwidth
+ )?;
+ writeln!(out, "\t\tuuid {}", uuid_unparse(&dev.uuid))?;
+ writeln!(out, "\t\tfsid {}", uuid_unparse(&dev.fsid))
+}
+
+/// `btrfs_print_tree()` / `__btrfs_print_leaf()` for a leaf.
+pub fn print_leaf(out: &mut impl Write, fs: &Fs, view: &View<'_>) -> io::Result<()> {
+ let View::Leaf {
+ header,
+ items,
+ data,
+ } = view
+ else {
+ panic!("print_leaf called on a node");
+ };
+
+ let leaf_data_size = (fs.nodesize as usize).saturating_sub(size_of::<Header>());
+ let free_space = if let Some(last) = items.last() {
+ (last.offset.get() as usize).saturating_sub(std::mem::size_of_val(*items)) as u32
+ } else {
+ leaf_data_size as u32
+ };
+
+ print_header_info(out, header, free_space)?;
+
+ for (i, item) in items.iter().enumerate() {
+ write!(out, "\titem {i} ")?;
+ print_key(out, &item.key)?;
+ writeln!(
+ out,
+ " itemoff {} itemsize {}",
+ item.offset.get(),
+ item.size.get()
+ )?;
+
+ let Ok(item_payload) = item_data(data, item) else {
+ writeln!(out, "\t\titem data out of range")?;
+ continue;
+ };
+
+ match KeyType(item.key.r#type) {
+ KeyType::CHUNK_ITEM => print_chunk_item(out, item_payload)?,
+ KeyType::DEV_ITEM => print_dev_item(out, item_payload)?,
+ _ => {}
+ }
+ }
+ Ok(())
+}
+
/// `btrfs_print_tree()` for any tree block.
pub fn print_tree(out: &mut impl Write, fs: &Fs, view: &View<'_>) -> io::Result<()> {
match view {
View::Node { .. } => print_node(out, fs, view),
- View::Leaf { .. } => Err(io::Error::new(
- io::ErrorKind::Unsupported,
- "leaf printing is not supported yet",
- )),
+ View::Leaf { .. } => print_leaf(out, fs, view),
}
}
@@ -728,6 +805,7 @@ pub fn print_superblock(out: &mut impl Write, sb: &SuperBlock, full: bool) -> io
mod tests {
use super::*;
use btrfs_rs::disk::block;
+ use btrfs_rs::disk::Item;
use btrfs_rs::sizes::*;
use zerocopy::FromZeros;
@@ -786,4 +864,114 @@ mod tests {
assert!(output.contains("chunk uuid 33333333-3333-3333-3333-333333333333"));
assert!(output.contains("\tkey (256 INODE_ITEM 0) block 2097152 gen 42"));
}
+
+ #[test]
+ fn print_leaf_format() {
+ let mut header = Header::new_zeroed();
+ header.bytenr = (SZ_1M as u64).into();
+ header.level = 0;
+ header.nritems = 2.into();
+ header.generation = 42.into();
+ header.owner = objectid::CHUNK_TREE.into();
+ header.flags = (header_flag::WRITTEN | (1u64 << backref_rev::SHIFT)).into();
+ header.fsid = [0x22; 16];
+ header.chunk_tree_uuid = [0x33; 16];
+
+ let mut dev = DevItem::new_zeroed();
+ dev.devid = 1.into();
+ dev.total_bytes = (SZ_1G as u64).into();
+ dev.bytes_used = (SZ_1M as u64).into();
+ dev.io_align = (SZ_4K as u32).into();
+ dev.io_width = (SZ_4K as u32).into();
+ dev.sector_size = (SZ_4K as u32).into();
+ dev.r#type = 0.into();
+ dev.uuid = [0x44; 16];
+ dev.fsid = [0x22; 16];
+
+ let mut chunk = Chunk::new_zeroed();
+ chunk.length = (SZ_1M as u64).into();
+ chunk.owner = 2.into();
+ chunk.stripe_len = (SZ_64K as u64).into();
+ chunk.r#type = block_group::SYSTEM.into();
+ chunk.num_stripes = 1.into();
+ chunk.sub_stripes = 1.into();
+
+ let mut stripe = Stripe::new_zeroed();
+ stripe.devid = 1.into();
+ stripe.offset = 0.into();
+
+ let dev_bytes = dev.as_bytes();
+ let chunk_bytes = [chunk.as_bytes(), stripe.as_bytes()].concat();
+
+ let mut buf = vec![0u8; SZ_16K];
+ buf[..size_of::<Header>()].copy_from_slice(header.as_bytes());
+
+ let dev_size = dev_bytes.len() as u32;
+ let chunk_size = chunk_bytes.len() as u32;
+
+ let dev_off = (SZ_16K - size_of::<Header>()) as u32 - dev_size;
+ let chunk_off = dev_off - chunk_size;
+
+ let item0 = Item {
+ key: DiskKey {
+ objectid: 1.into(),
+ r#type: KeyType::DEV_ITEM.0,
+ offset: 1.into(),
+ },
+ offset: dev_off.into(),
+ size: dev_size.into(),
+ };
+
+ let item1 = Item {
+ key: DiskKey {
+ objectid: objectid::FIRST_CHUNK_TREE.into(),
+ r#type: KeyType::CHUNK_ITEM.0,
+ offset: (SZ_1M as u64).into(),
+ },
+ offset: chunk_off.into(),
+ size: chunk_size.into(),
+ };
+
+ let items_start = size_of::<Header>();
+ buf[items_start..items_start + size_of::<Item>()].copy_from_slice(item0.as_bytes());
+ buf[items_start + size_of::<Item>()..items_start + 2 * size_of::<Item>()]
+ .copy_from_slice(item1.as_bytes());
+
+ let payload_start = size_of::<Header>() + dev_off as usize;
+ buf[payload_start..payload_start + dev_size as usize].copy_from_slice(dev_bytes);
+ let chunk_payload_start = size_of::<Header>() + chunk_off as usize;
+ buf[chunk_payload_start..chunk_payload_start + chunk_size as usize]
+ .copy_from_slice(&chunk_bytes);
+
+ let view = block::parse_block(&buf).unwrap();
+
+ let mut sb = SuperBlock::new_zeroed();
+ sb.nodesize = (SZ_16K as u32).into();
+ sb.sectorsize = (SZ_4K as u32).into();
+ sb.magic = magic::BTRFS.into();
+
+ let fs = Fs {
+ superblock: Box::new(sb),
+ devices: Vec::new(),
+ chunks: Default::default(),
+ sectorsize: SZ_4K as u32,
+ nodesize: SZ_16K as u32,
+ csum_type: 0,
+ csum_size: 4,
+ metadata_fsid: [0x22; 16],
+ tree_root: btrfs_rs::fs::Root::default(),
+ chunk_root: btrfs_rs::fs::Root::default(),
+ };
+
+ let mut out = Vec::new();
+ print_leaf(&mut out, &fs, &view).unwrap();
+ let output = String::from_utf8(out).unwrap();
+
+ assert!(output.contains("leaf 1048576 items 2 free space"));
+ assert!(output.contains("owner CHUNK_TREE"));
+ assert!(output.contains("\titem 0 key (DEV_ITEMS DEV_ITEM 1)"));
+ assert!(output.contains("devid 1 total_bytes 1073741824 bytes_used 1048576"));
+ assert!(output.contains("\titem 1 key (FIRST_CHUNK_TREE CHUNK_ITEM 1048576)"));
+ assert!(output.contains("length 1048576 owner 2 stripe_len 65536 type SYSTEM"));
+ }
}
--
2.56.1
^ permalink raw reply related [flat|nested] 16+ messages in thread* [PATCH 09/15] btrfs-progs: rust: print_tree: add subvolume tree items
2026-12-01 7:56 [PATCH RFC 00/15] btrfs-progs: experimental rust support Qu Wenruo
` (7 preceding siblings ...)
2026-12-01 7:56 ` [PATCH 08/15] btrfs-progs: rust: print_tree: add print_leaf and chunk tree items Qu Wenruo
@ 2026-12-01 7:56 ` Qu Wenruo
2026-12-01 7:56 ` [PATCH 10/15] btrfs-progs: rust: print_tree: add root " Qu Wenruo
` (5 subsequent siblings)
14 siblings, 0 replies; 16+ messages in thread
From: Qu Wenruo @ 2026-12-01 7:56 UTC (permalink / raw)
To: linux-btrfs
Implement printing functions in print_tree.rs for items that reside
in subvolume and filesystem trees:
- INODE_ITEM: print_inode_item()
- INODE_REF: print_inode_ref_item()
- INODE_EXTREF: print_inode_extref_item()
- DIR_ITEM, DIR_INDEX, XATTR_ITEM: print_dir_item()
- EXTENT_DATA: print_file_extent_item() (inline, regular, prealloc)
- DIR_LOG_ITEM, DIR_LOG_INDEX: print_dir_log_item()
---
rust/Cargo.lock | 121 +++++++++++++++
rust/Cargo.toml | 1 +
rust/src/print_tree.rs | 333 ++++++++++++++++++++++++++++++++++++++++-
3 files changed, 453 insertions(+), 2 deletions(-)
diff --git a/rust/Cargo.lock b/rust/Cargo.lock
index 54b2db544fab..eff88bba3923 100644
--- a/rust/Cargo.lock
+++ b/rust/Cargo.lock
@@ -11,6 +11,15 @@ dependencies = [
"memchr",
]
+[[package]]
+name = "android_system_properties"
+version = "0.1.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ae221649c9976a6f6c56ae1facf410f3ddb33cc661c4b7b61020a912d4237fbc"
+dependencies = [
+ "libc",
+]
+
[[package]]
name = "anstream"
version = "1.0.0"
@@ -61,6 +70,12 @@ dependencies = [
"windows-sys",
]
+[[package]]
+name = "autocfg"
+version = "1.5.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
+
[[package]]
name = "bindgen"
version = "0.72.1"
@@ -110,6 +125,7 @@ name = "btrfs-rs"
version = "0.0.0"
dependencies = [
"blake2",
+ "chrono",
"clap",
"crc32c",
"libblkid-rs",
@@ -149,6 +165,19 @@ version = "1.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"
+[[package]]
+name = "chrono"
+version = "0.4.45"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327"
+dependencies = [
+ "iana-time-zone",
+ "js-sys",
+ "num-traits",
+ "wasm-bindgen",
+ "windows-link",
+]
+
[[package]]
name = "clang-sys"
version = "1.9.1"
@@ -206,6 +235,12 @@ version = "1.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570"
+[[package]]
+name = "core-foundation-sys"
+version = "0.8.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b"
+
[[package]]
name = "cpufeatures"
version = "0.2.17"
@@ -303,6 +338,30 @@ version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
+[[package]]
+name = "iana-time-zone"
+version = "0.1.65"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470"
+dependencies = [
+ "android_system_properties",
+ "core-foundation-sys",
+ "iana-time-zone-haiku",
+ "js-sys",
+ "log",
+ "wasm-bindgen",
+ "windows-core",
+]
+
+[[package]]
+name = "iana-time-zone-haiku"
+version = "0.1.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f"
+dependencies = [
+ "cc",
+]
+
[[package]]
name = "is_terminal_polyfill"
version = "1.70.2"
@@ -396,6 +455,15 @@ dependencies = [
"minimal-lexical",
]
+[[package]]
+name = "num-traits"
+version = "0.2.19"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
+dependencies = [
+ "autocfg",
+]
+
[[package]]
name = "once_cell_polyfill"
version = "1.70.2"
@@ -639,12 +707,65 @@ dependencies = [
"unicode-ident",
]
+[[package]]
+name = "windows-core"
+version = "0.62.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb"
+dependencies = [
+ "windows-implement",
+ "windows-interface",
+ "windows-link",
+ "windows-result",
+ "windows-strings",
+]
+
+[[package]]
+name = "windows-implement"
+version = "0.60.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "windows-interface"
+version = "0.59.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
+
[[package]]
name = "windows-link"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
+[[package]]
+name = "windows-result"
+version = "0.4.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5"
+dependencies = [
+ "windows-link",
+]
+
+[[package]]
+name = "windows-strings"
+version = "0.5.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091"
+dependencies = [
+ "windows-link",
+]
+
[[package]]
name = "windows-sys"
version = "0.61.2"
diff --git a/rust/Cargo.toml b/rust/Cargo.toml
index c253623fe1e6..99fe82eed569 100644
--- a/rust/Cargo.toml
+++ b/rust/Cargo.toml
@@ -13,4 +13,5 @@ crc32c = "0.6"
xxhash-rust = { version = "0.8", features = ["xxh64"] }
sha2 = "0.10"
blake2 = "0.10"
+chrono = "0.4"
libblkid-rs = "0.4.2"
diff --git a/rust/src/print_tree.rs b/rust/src/print_tree.rs
index d4d9eb19503b..fc6a6bd8507f 100644
--- a/rust/src/print_tree.rs
+++ b/rust/src/print_tree.rs
@@ -3,12 +3,16 @@
use std::io::{self, Write};
+use chrono::{DateTime, Local};
+
use btrfs_rs::disk::block::{item_data, View};
use btrfs_rs::disk::consts::{
- backref_rev, block_group, compat_ro, header_flag, incompat, limits, magic, objectid, super_flag,
+ backref_rev, block_group, compat_ro, compress_type, file_extent_type, file_type, header_flag,
+ incompat, inode_flag, limits, magic, objectid, super_flag,
};
use btrfs_rs::disk::{
- csum, Chunk, DevItem, DiskKey, Header, KeyPtr, KeyType, RootBackup, Stripe, SuperBlock,
+ csum, Chunk, DevItem, DirItem, DirLogItem, DiskKey, FileExtentItem, Header, InodeExtref,
+ InodeItem, InodeRef, KeyPtr, KeyType, RootBackup, Stripe, SuperBlock, Timespec,
};
use btrfs_rs::fs::Fs;
use zerocopy::{FromBytes, IntoBytes};
@@ -287,6 +291,279 @@ pub fn print_dev_item(out: &mut impl Write, data: &[u8]) -> io::Result<()> {
writeln!(out, "\t\tfsid {}", uuid_unparse(&dev.fsid))
}
+fn print_escaped_name(out: &mut impl Write, name: &[u8]) -> io::Result<()> {
+ for &b in name {
+ if (0x20..0x7f).contains(&b) && b != b'\\' {
+ write!(out, "{}", b as char)?;
+ } else {
+ write!(out, "\\x{b:02x}")?;
+ }
+ }
+ Ok(())
+}
+
+fn print_timespec(out: &mut impl Write, prefix: &str, timespec: &Timespec) -> io::Result<()> {
+ let sec = timespec.sec.get() as i64;
+ let nsec = timespec.nsec.get();
+ match DateTime::from_timestamp(sec, nsec) {
+ Some(dt) => {
+ let local_dt: DateTime<Local> = DateTime::from(dt);
+ writeln!(
+ out,
+ "{prefix}{sec}.{nsec} ({})",
+ local_dt.format("%Y-%m-%d %H:%M:%S")
+ )
+ }
+ None => writeln!(out, "{prefix}{sec}.{nsec}"),
+ }
+}
+
+fn inode_flags_to_str(flags: u64) -> String {
+ if flags == 0 {
+ return "none".to_string();
+ }
+ let names = [
+ (inode_flag::NODATASUM, "NODATASUM"),
+ (inode_flag::NODATACOW, "NODATACOW"),
+ (inode_flag::READONLY, "READONLY"),
+ (inode_flag::NOCOMPRESS, "NOCOMPRESS"),
+ (inode_flag::PREALLOC, "PREALLOC"),
+ (inode_flag::SYNC, "SYNC"),
+ (inode_flag::IMMUTABLE, "IMMUTABLE"),
+ (inode_flag::APPEND, "APPEND"),
+ (inode_flag::NODUMP, "NODUMP"),
+ (inode_flag::NOATIME, "NOATIME"),
+ (inode_flag::DIRSYNC, "DIRSYNC"),
+ (inode_flag::COMPRESS, "COMPRESS"),
+ (inode_flag::ENCRYPT, "ENCRYPT"),
+ ];
+ let mut parts = Vec::new();
+ for (bit, name) in names {
+ if flags & bit != 0 {
+ parts.push(name);
+ }
+ }
+ if parts.is_empty() {
+ format!("unknown flag: 0x{flags:x}")
+ } else {
+ parts.join("|")
+ }
+}
+
+/// `print_inode_item()`
+pub fn print_inode_item(out: &mut impl Write, data: &[u8]) -> io::Result<()> {
+ let Ok((item, _)) = InodeItem::ref_from_prefix(data) else {
+ return writeln!(out, "\t\tinode item invalid");
+ };
+ let flags = item.flags.get();
+ let flags_str = inode_flags_to_str(flags);
+ writeln!(
+ out,
+ "\t\tgeneration {} transid {} size {} nbytes {}",
+ item.generation.get(),
+ item.transid.get(),
+ item.size.get(),
+ item.nbytes.get()
+ )?;
+ writeln!(
+ out,
+ "\t\tblock group {} mode {:o} links {} uid {} gid {} rdev {}",
+ item.block_group.get(),
+ item.mode.get(),
+ item.nlink.get(),
+ item.uid.get(),
+ item.gid.get(),
+ item.rdev.get()
+ )?;
+ writeln!(
+ out,
+ "\t\tsequence {} flags 0x{:x}({flags_str})",
+ item.sequence.get(),
+ flags
+ )?;
+ print_timespec(out, "\t\tatime ", &item.atime)?;
+ print_timespec(out, "\t\tctime ", &item.ctime)?;
+ print_timespec(out, "\t\tmtime ", &item.mtime)?;
+ print_timespec(out, "\t\totime ", &item.otime)
+}
+
+/// `print_inode_ref_item()`
+pub fn print_inode_ref_item(out: &mut impl Write, data: &[u8]) -> io::Result<()> {
+ let mut offset = 0;
+ while offset < data.len() {
+ let Ok((ref_item, rest)) = InodeRef::ref_from_prefix(&data[offset..]) else {
+ break;
+ };
+ let name_len = ref_item.name_len.get() as usize;
+ let name = rest.get(..name_len).unwrap_or(&[]);
+ write!(
+ out,
+ "\t\tindex {} namelen {name_len} name: ",
+ ref_item.index.get()
+ )?;
+ print_escaped_name(out, name)?;
+ writeln!(out)?;
+ offset += size_of::<InodeRef>() + name_len;
+ }
+ Ok(())
+}
+
+/// `print_inode_extref_item()`
+pub fn print_inode_extref_item(out: &mut impl Write, data: &[u8]) -> io::Result<()> {
+ let mut offset = 0;
+ while offset < data.len() {
+ let Ok((extref, rest)) = InodeExtref::ref_from_prefix(&data[offset..]) else {
+ break;
+ };
+ let name_len = extref.name_len.get() as usize;
+ let name = rest.get(..name_len).unwrap_or(&[]);
+ write!(
+ out,
+ "\t\tindex {} parent {} namelen {name_len} name: ",
+ extref.index.get(),
+ extref.parent_objectid.get()
+ )?;
+ print_escaped_name(out, name)?;
+ writeln!(out)?;
+ offset += size_of::<InodeExtref>() + name_len;
+ }
+ Ok(())
+}
+
+fn dir_item_type_str(ftype: u8) -> &'static str {
+ match ftype {
+ file_type::REG_FILE => "FILE",
+ file_type::DIR => "DIR",
+ file_type::CHRDEV => "CHRDEV",
+ file_type::BLKDEV => "BLKDEV",
+ file_type::FIFO => "FIFO",
+ file_type::SOCK => "SOCK",
+ file_type::SYMLINK => "SYMLINK",
+ file_type::XATTR => "XATTR",
+ _ => "UNKNOWN",
+ }
+}
+
+/// `print_dir_item()`
+pub fn print_dir_item(out: &mut impl Write, data: &[u8]) -> io::Result<()> {
+ let mut offset = 0;
+ while offset < data.len() {
+ let Ok((di, rest)) = DirItem::ref_from_prefix(&data[offset..]) else {
+ break;
+ };
+ let name_len = di.name_len.get() as usize;
+ let data_len = di.data_len.get() as usize;
+ let total_item = size_of::<DirItem>() + name_len + data_len;
+ if offset + total_item > data.len() {
+ break;
+ }
+
+ write!(out, "\t\tlocation ")?;
+ print_key(out, &di.location)?;
+ writeln!(out, " type {}", dir_item_type_str(di.r#type))?;
+
+ writeln!(
+ out,
+ "\t\ttransid {} data_len {data_len} name_len {name_len}",
+ di.transid.get()
+ )?;
+
+ let name = rest.get(..name_len).unwrap_or(&[]);
+ write!(out, "\t\tname: ")?;
+ print_escaped_name(out, name)?;
+ writeln!(out)?;
+
+ if data_len > 0 {
+ let item_data_slice = rest.get(name_len..name_len + data_len).unwrap_or(&[]);
+ write!(out, "\t\tdata ")?;
+ print_escaped_name(out, item_data_slice)?;
+ writeln!(out)?;
+ }
+
+ offset += total_item;
+ }
+ Ok(())
+}
+
+fn compress_type_str(c: u8) -> &'static str {
+ match c {
+ compress_type::NONE => "none",
+ compress_type::ZLIB => "zlib",
+ compress_type::LZO => "lzo",
+ compress_type::ZSTD => "zstd",
+ _ => "unknown",
+ }
+}
+
+/// `print_file_extent_item()`
+pub fn print_file_extent_item(out: &mut impl Write, data: &[u8]) -> io::Result<()> {
+ let Ok((fi, _)) = FileExtentItem::ref_from_prefix(data) else {
+ return writeln!(out, "\t\tfile extent invalid");
+ };
+ let gen = fi.generation.get();
+ let extent_type = fi.r#type;
+ let type_str = match extent_type {
+ file_extent_type::INLINE => "inline",
+ file_extent_type::REG => "regular",
+ file_extent_type::PREALLOC => "prealloc",
+ _ => "unknown",
+ };
+ writeln!(out, "\t\tgeneration {gen} type {extent_type} ({type_str})")?;
+
+ let compress_str = compress_type_str(fi.compression);
+ if extent_type == file_extent_type::INLINE {
+ let inline_len = data.len().saturating_sub(21);
+ writeln!(
+ out,
+ "\t\tinline extent data size {inline_len} ram_bytes {} compression {} ({compress_str}) encryption {}",
+ fi.ram_bytes.get(),
+ fi.compression,
+ fi.encryption
+ )
+ } else if extent_type == file_extent_type::PREALLOC {
+ writeln!(
+ out,
+ "\t\tprealloc data disk byte {} nr {}",
+ fi.disk_bytenr.get(),
+ fi.disk_num_bytes.get()
+ )?;
+ writeln!(
+ out,
+ "\t\tprealloc data offset {} nr {}",
+ fi.offset.get(),
+ fi.num_bytes.get()
+ )
+ } else {
+ writeln!(
+ out,
+ "\t\textent data disk byte {} nr {}",
+ fi.disk_bytenr.get(),
+ fi.disk_num_bytes.get()
+ )?;
+ writeln!(
+ out,
+ "\t\textent data offset {} nr {} ram {}",
+ fi.offset.get(),
+ fi.num_bytes.get(),
+ fi.ram_bytes.get()
+ )?;
+ writeln!(
+ out,
+ "\t\textent compression {} ({compress_str})",
+ fi.compression
+ )?;
+ writeln!(out, "\t\textent encryption {}", fi.encryption)
+ }
+}
+
+/// `print_dir_log_item()`
+pub fn print_dir_log_item(out: &mut impl Write, data: &[u8]) -> io::Result<()> {
+ let Ok((dlog, _)) = DirLogItem::ref_from_prefix(data) else {
+ return writeln!(out, "\t\tdir log item invalid");
+ };
+ writeln!(out, "\t\tdir log end {}", dlog.end.get())
+}
+
/// `btrfs_print_tree()` / `__btrfs_print_leaf()` for a leaf.
pub fn print_leaf(out: &mut impl Write, fs: &Fs, view: &View<'_>) -> io::Result<()> {
let View::Leaf {
@@ -325,6 +602,16 @@ pub fn print_leaf(out: &mut impl Write, fs: &Fs, view: &View<'_>) -> io::Result<
match KeyType(item.key.r#type) {
KeyType::CHUNK_ITEM => print_chunk_item(out, item_payload)?,
KeyType::DEV_ITEM => print_dev_item(out, item_payload)?,
+ KeyType::INODE_ITEM => print_inode_item(out, item_payload)?,
+ KeyType::INODE_REF => print_inode_ref_item(out, item_payload)?,
+ KeyType::INODE_EXTREF => print_inode_extref_item(out, item_payload)?,
+ KeyType::DIR_ITEM | KeyType::DIR_INDEX | KeyType::XATTR_ITEM => {
+ print_dir_item(out, item_payload)?;
+ }
+ KeyType::EXTENT_DATA => print_file_extent_item(out, item_payload)?,
+ KeyType::DIR_LOG_ITEM | KeyType::DIR_LOG_INDEX => {
+ print_dir_log_item(out, item_payload)?;
+ }
_ => {}
}
}
@@ -974,4 +1261,46 @@ mod tests {
assert!(output.contains("\titem 1 key (FIRST_CHUNK_TREE CHUNK_ITEM 1048576)"));
assert!(output.contains("length 1048576 owner 2 stripe_len 65536 type SYSTEM"));
}
+
+ #[test]
+ fn print_subvolume_tree_items() {
+ let mut out = Vec::new();
+
+ let mut inode = InodeItem::new_zeroed();
+ inode.generation = 1.into();
+ inode.size = 100.into();
+ inode.nbytes = 4096.into();
+ inode.nlink = 1.into();
+ inode.mode = 0o100644.into();
+ print_inode_item(&mut out, inode.as_bytes()).unwrap();
+ let s = String::from_utf8(out).unwrap();
+ assert!(s.contains("generation 1 transid 0 size 100 nbytes 4096"));
+ assert!(s.contains("mode 100644 links 1"));
+
+ let mut out = Vec::new();
+ let mut di = DirItem::new_zeroed();
+ di.location.objectid = 257.into();
+ di.location.r#type = KeyType::INODE_ITEM.0;
+ di.name_len = 4.into();
+ di.r#type = file_type::REG_FILE;
+ let mut di_bytes = di.as_bytes().to_vec();
+ di_bytes.extend_from_slice(b"test");
+ print_dir_item(&mut out, &di_bytes).unwrap();
+ let s = String::from_utf8(out).unwrap();
+ assert!(s.contains("location key (257 INODE_ITEM 0) type FILE"));
+ assert!(s.contains("name: test"));
+
+ let mut out = Vec::new();
+ let mut fe = FileExtentItem::new_zeroed();
+ fe.generation = 5.into();
+ fe.ram_bytes = 4096.into();
+ fe.r#type = file_extent_type::REG;
+ fe.disk_bytenr = (SZ_1M as u64).into();
+ fe.disk_num_bytes = 4096.into();
+ fe.num_bytes = 4096.into();
+ print_file_extent_item(&mut out, fe.as_bytes()).unwrap();
+ let s = String::from_utf8(out).unwrap();
+ assert!(s.contains("generation 5 type 1 (regular)"));
+ assert!(s.contains("extent data disk byte 1048576 nr 4096"));
+ }
}
--
2.56.1
^ permalink raw reply related [flat|nested] 16+ messages in thread* [PATCH 10/15] btrfs-progs: rust: print_tree: add root tree items
2026-12-01 7:56 [PATCH RFC 00/15] btrfs-progs: experimental rust support Qu Wenruo
` (8 preceding siblings ...)
2026-12-01 7:56 ` [PATCH 09/15] btrfs-progs: rust: print_tree: add subvolume " Qu Wenruo
@ 2026-12-01 7:56 ` Qu Wenruo
2026-12-01 7:56 ` [PATCH 11/15] btrfs-progs: rust: print_tree: add extent and block group " Qu Wenruo
` (4 subsequent siblings)
14 siblings, 0 replies; 16+ messages in thread
From: Qu Wenruo @ 2026-12-01 7:56 UTC (permalink / raw)
To: linux-btrfs
Implement printing functions in print_tree.rs for items that reside
in the root tree:
- ROOT_ITEM: print_root_item() (with legacy size support, drop_progress, UUIDs, timespecs)
- ROOT_REF / ROOT_BACKREF: print_root_ref()
- ORPHAN_ITEM: print orphan item marker
---
rust/src/print_tree.rs | 128 ++++++++++++++++++++++++++++++++++++++++-
1 file changed, 125 insertions(+), 3 deletions(-)
diff --git a/rust/src/print_tree.rs b/rust/src/print_tree.rs
index fc6a6bd8507f..674ce6c23087 100644
--- a/rust/src/print_tree.rs
+++ b/rust/src/print_tree.rs
@@ -8,14 +8,15 @@ use chrono::{DateTime, Local};
use btrfs_rs::disk::block::{item_data, View};
use btrfs_rs::disk::consts::{
backref_rev, block_group, compat_ro, compress_type, file_extent_type, file_type, header_flag,
- incompat, inode_flag, limits, magic, objectid, super_flag,
+ incompat, inode_flag, limits, magic, objectid, root_flag, super_flag,
};
use btrfs_rs::disk::{
csum, Chunk, DevItem, DirItem, DirLogItem, DiskKey, FileExtentItem, Header, InodeExtref,
- InodeItem, InodeRef, KeyPtr, KeyType, RootBackup, Stripe, SuperBlock, Timespec,
+ InodeItem, InodeRef, KeyPtr, KeyType, RootBackup, RootItem, RootRef, Stripe, SuperBlock,
+ Timespec, LEGACY_ROOT_ITEM_SIZE,
};
use btrfs_rs::fs::Fs;
-use zerocopy::{FromBytes, IntoBytes};
+use zerocopy::{FromBytes, FromZeros, IntoBytes};
use crate::messages::error_flushing;
use crate::util::uuid_unparse;
@@ -564,6 +565,94 @@ pub fn print_dir_log_item(out: &mut impl Write, data: &[u8]) -> io::Result<()> {
writeln!(out, "\t\tdir log end {}", dlog.end.get())
}
+fn root_flags_to_str(flags: u64) -> String {
+ if flags & root_flag::SUBVOL_RDONLY != 0 {
+ "RDONLY".to_string()
+ } else {
+ "none".to_string()
+ }
+}
+
+/// `print_root_item()`
+pub fn print_root_item(out: &mut impl Write, data: &[u8]) -> io::Result<()> {
+ if data.len() < LEGACY_ROOT_ITEM_SIZE {
+ return writeln!(out, "\t\tbad root item size, skipping");
+ }
+
+ let mut ri = RootItem::new_zeroed();
+ let copy_len = data.len().min(size_of::<RootItem>());
+ ri.as_mut_bytes()[..copy_len].copy_from_slice(&data[..copy_len]);
+
+ let flags_str = root_flags_to_str(ri.flags.get());
+ writeln!(
+ out,
+ "\t\tgeneration {} root_dirid {} bytenr {} byte_limit {} bytes_used {}",
+ ri.generation.get(),
+ ri.root_dirid.get(),
+ ri.bytenr.get(),
+ ri.byte_limit.get(),
+ ri.bytes_used.get()
+ )?;
+ writeln!(
+ out,
+ "\t\tlast_snapshot {} flags 0x{:x}({flags_str}) refs {}",
+ ri.last_snapshot.get(),
+ ri.flags.get(),
+ ri.refs.get()
+ )?;
+ write!(out, "\t\tdrop_progress ")?;
+ print_key(out, &ri.drop_progress)?;
+ writeln!(out, " drop_level {}", ri.drop_level)?;
+
+ if data.len() < size_of::<RootItem>() {
+ writeln!(out, "\t\tlevel {}", ri.level)?;
+ return Ok(());
+ }
+
+ writeln!(
+ out,
+ "\t\tlevel {} generation_v2 {}",
+ ri.level,
+ ri.generation_v2.get()
+ )?;
+
+ if ri.generation.get() == ri.generation_v2.get() {
+ writeln!(out, "\t\tuuid {}", uuid_unparse(&ri.uuid))?;
+ writeln!(out, "\t\tparent_uuid {}", uuid_unparse(&ri.parent_uuid))?;
+ writeln!(out, "\t\treceived_uuid {}", uuid_unparse(&ri.received_uuid))?;
+ writeln!(
+ out,
+ "\t\tctransid {} otransid {} stransid {} rtransid {}",
+ ri.ctransid.get(),
+ ri.otransid.get(),
+ ri.stransid.get(),
+ ri.rtransid.get()
+ )?;
+ print_timespec(out, "\t\tctime ", &ri.ctime)?;
+ print_timespec(out, "\t\totime ", &ri.otime)?;
+ print_timespec(out, "\t\tstime ", &ri.stime)?;
+ print_timespec(out, "\t\trtime ", &ri.rtime)?;
+ }
+ Ok(())
+}
+
+/// `print_root_ref()`
+pub fn print_root_ref(out: &mut impl Write, data: &[u8], tag: &str) -> io::Result<()> {
+ let Ok((ref_item, rest)) = RootRef::ref_from_prefix(data) else {
+ return writeln!(out, "\t\troot {tag} invalid");
+ };
+ let name_len = ref_item.name_len.get() as usize;
+ let name = rest.get(..name_len).unwrap_or(&[]);
+ write!(
+ out,
+ "\t\troot {tag} key dirid {} sequence {} name ",
+ ref_item.dirid.get(),
+ ref_item.sequence.get()
+ )?;
+ print_escaped_name(out, name)?;
+ writeln!(out)
+}
+
/// `btrfs_print_tree()` / `__btrfs_print_leaf()` for a leaf.
pub fn print_leaf(out: &mut impl Write, fs: &Fs, view: &View<'_>) -> io::Result<()> {
let View::Leaf {
@@ -612,6 +701,10 @@ pub fn print_leaf(out: &mut impl Write, fs: &Fs, view: &View<'_>) -> io::Result<
KeyType::DIR_LOG_ITEM | KeyType::DIR_LOG_INDEX => {
print_dir_log_item(out, item_payload)?;
}
+ KeyType::ROOT_ITEM => print_root_item(out, item_payload)?,
+ KeyType::ROOT_REF => print_root_ref(out, item_payload, "ref")?,
+ KeyType::ROOT_BACKREF => print_root_ref(out, item_payload, "backref")?,
+ KeyType::ORPHAN_ITEM => writeln!(out, "\t\torphan item")?,
_ => {}
}
}
@@ -1303,4 +1396,33 @@ mod tests {
assert!(s.contains("generation 5 type 1 (regular)"));
assert!(s.contains("extent data disk byte 1048576 nr 4096"));
}
+
+ #[test]
+ fn print_root_tree_items() {
+ let mut out = Vec::new();
+ let mut ri = RootItem::new_zeroed();
+ ri.generation = 1.into();
+ ri.generation_v2 = 1.into();
+ ri.bytenr = (SZ_1M as u64).into();
+ ri.level = 0;
+ ri.flags = root_flag::SUBVOL_RDONLY.into();
+ ri.uuid = [0x55; 16];
+ print_root_item(&mut out, ri.as_bytes()).unwrap();
+ let s = String::from_utf8(out).unwrap();
+ assert!(s.contains("generation 1 root_dirid 0 bytenr 1048576"));
+ assert!(s.contains("flags 0x1(RDONLY)"));
+ assert!(s.contains("level 0 generation_v2 1"));
+ assert!(s.contains("uuid 55555555-5555-5555-5555-555555555555"));
+
+ let mut out = Vec::new();
+ let mut rr = RootRef::new_zeroed();
+ rr.dirid = 256.into();
+ rr.sequence = 1.into();
+ rr.name_len = 8.into();
+ let mut rr_bytes = rr.as_bytes().to_vec();
+ rr_bytes.extend_from_slice(b"subvol_1");
+ print_root_ref(&mut out, &rr_bytes, "ref").unwrap();
+ let s = String::from_utf8(out).unwrap();
+ assert!(s.contains("root ref key dirid 256 sequence 1 name subvol_1"));
+ }
}
--
2.56.1
^ permalink raw reply related [flat|nested] 16+ messages in thread* [PATCH 11/15] btrfs-progs: rust: print_tree: add extent and block group tree items
2026-12-01 7:56 [PATCH RFC 00/15] btrfs-progs: experimental rust support Qu Wenruo
` (9 preceding siblings ...)
2026-12-01 7:56 ` [PATCH 10/15] btrfs-progs: rust: print_tree: add root " Qu Wenruo
@ 2026-12-01 7:56 ` Qu Wenruo
2026-12-01 7:56 ` [PATCH 12/15] btrfs-progs: rust: print_tree: add remaining " Qu Wenruo
` (3 subsequent siblings)
14 siblings, 0 replies; 16+ messages in thread
From: Qu Wenruo @ 2026-12-01 7:56 UTC (permalink / raw)
To: linux-btrfs
Implement printing functions in print_tree.rs for items that reside
in the extent tree and block group tree:
- BLOCK_GROUP_ITEM: print_block_group_item()
- EXTENT_ITEM and METADATA_ITEM: print_extent_item() (with tree block
info, skinny metadata level, and inline backrefs)
- Inline & standalone backref items:
- TREE_BLOCK_REF
- SHARED_BLOCK_REF
- EXTENT_DATA_REF: print_extent_data_ref() (with hash_extent_data_ref)
- SHARED_DATA_REF: print_shared_data_ref()
- EXTENT_OWNER_REF: print_extent_owner_ref()
---
rust/src/print_tree.rs | 212 ++++++++++++++++++++++++++++++++++++++++-
1 file changed, 207 insertions(+), 5 deletions(-)
diff --git a/rust/src/print_tree.rs b/rust/src/print_tree.rs
index 674ce6c23087..91abdcb208e3 100644
--- a/rust/src/print_tree.rs
+++ b/rust/src/print_tree.rs
@@ -7,13 +7,14 @@ use chrono::{DateTime, Local};
use btrfs_rs::disk::block::{item_data, View};
use btrfs_rs::disk::consts::{
- backref_rev, block_group, compat_ro, compress_type, file_extent_type, file_type, header_flag,
- incompat, inode_flag, limits, magic, objectid, root_flag, super_flag,
+ backref_rev, block_group, compat_ro, compress_type, extent_flag, file_extent_type, file_type,
+ header_flag, incompat, inode_flag, limits, magic, objectid, root_flag, super_flag,
};
use btrfs_rs::disk::{
- csum, Chunk, DevItem, DirItem, DirLogItem, DiskKey, FileExtentItem, Header, InodeExtref,
- InodeItem, InodeRef, KeyPtr, KeyType, RootBackup, RootItem, RootRef, Stripe, SuperBlock,
- Timespec, LEGACY_ROOT_ITEM_SIZE,
+ csum, BlockGroupItem, Chunk, DevItem, DirItem, DirLogItem, DiskKey, ExtentDataRef,
+ ExtentInlineRef, ExtentItem, ExtentOwnerRef, FileExtentItem, Header, InodeExtref, InodeItem,
+ InodeRef, KeyPtr, KeyType, RootBackup, RootItem, RootRef, SharedDataRef, Stripe, SuperBlock,
+ Timespec, TreeBlockInfo, LEGACY_ROOT_ITEM_SIZE,
};
use btrfs_rs::fs::Fs;
use zerocopy::{FromBytes, FromZeros, IntoBytes};
@@ -653,6 +654,163 @@ pub fn print_root_ref(out: &mut impl Write, data: &[u8], tag: &str) -> io::Resul
writeln!(out)
}
+/// `print_block_group_item()`
+pub fn print_block_group_item(out: &mut impl Write, data: &[u8]) -> io::Result<()> {
+ let Ok((bgi, _)) = BlockGroupItem::ref_from_prefix(data) else {
+ return writeln!(out, "\t\tblock group item invalid");
+ };
+ let flags_str = bg_flags_to_str(bgi.flags.get());
+ writeln!(
+ out,
+ "\t\tblock group used {} chunk_objectid {} flags {flags_str}",
+ bgi.used.get(),
+ bgi.chunk_objectid.get()
+ )
+}
+
+fn hash_extent_data_ref(root_objectid: u64, owner: u64, offset: u64) -> u64 {
+ let high_crc = crc32c::crc32c(&root_objectid.to_le_bytes());
+ let low_crc = crc32c::crc32c(&owner.to_le_bytes());
+ let low_crc = crc32c::crc32c_append(low_crc, &offset.to_le_bytes());
+ ((high_crc as u64) << 31) ^ (low_crc as u64)
+}
+
+fn extent_flags_to_str(flags: u64) -> String {
+ let mut parts = Vec::new();
+ if flags & extent_flag::DATA != 0 {
+ parts.push("DATA");
+ }
+ if flags & extent_flag::TREE_BLOCK != 0 {
+ parts.push("TREE_BLOCK");
+ }
+ if flags & extent_flag::FULL_BACKREF != 0 {
+ parts.push("FULL_BACKREF");
+ }
+ parts.join("|")
+}
+
+/// `print_extent_item()` for `EXTENT_ITEM` and `METADATA_ITEM`.
+pub fn print_extent_item(out: &mut impl Write, key: &DiskKey, data: &[u8]) -> io::Result<()> {
+ let Ok((ei, rest)) = ExtentItem::ref_from_prefix(data) else {
+ return writeln!(out, "\t\textent item invalid");
+ };
+ let flags = ei.flags.get();
+ let flags_str = extent_flags_to_str(flags);
+ writeln!(
+ out,
+ "\t\trefs {} gen {} flags {flags_str}",
+ ei.refs.get(),
+ ei.generation.get()
+ )?;
+
+ let is_metadata = KeyType(key.r#type) == KeyType::METADATA_ITEM;
+ let mut offset = 0;
+ if flags & extent_flag::TREE_BLOCK != 0 && !is_metadata {
+ if let Ok((info, _)) = TreeBlockInfo::ref_from_prefix(rest) {
+ write!(out, "\t\ttree block ")?;
+ print_key(out, &info.key)?;
+ writeln!(out, " level {}", info.level)?;
+ offset += size_of::<TreeBlockInfo>();
+ }
+ } else if is_metadata {
+ writeln!(out, "\t\ttree block skinny level {}", key.offset.get())?;
+ }
+
+ let inline_data = &rest[offset..];
+ let mut cur = 0;
+ while cur < inline_data.len() {
+ let Ok((iref, inline_rest)) = ExtentInlineRef::ref_from_prefix(&inline_data[cur..]) else {
+ break;
+ };
+ let iref_type = iref.r#type;
+ let iref_offset = iref.offset.get();
+ match KeyType(iref_type) {
+ KeyType::TREE_BLOCK_REF => {
+ let owner = objectid_string(iref_offset, KeyType(0));
+ writeln!(
+ out,
+ "\t\t({iref_type} 0x{iref_offset:x}) tree block backref root {owner}"
+ )?;
+ cur += size_of::<ExtentInlineRef>();
+ }
+ KeyType::SHARED_BLOCK_REF => {
+ writeln!(
+ out,
+ "\t\t({iref_type} 0x{iref_offset:x}) shared block backref parent {iref_offset}"
+ )?;
+ cur += size_of::<ExtentInlineRef>();
+ }
+ KeyType::EXTENT_DATA_REF => {
+ let Ok((dref, _)) = ExtentDataRef::ref_from_prefix(&inline_data[cur + 1..]) else {
+ break;
+ };
+ let root = dref.root.get();
+ let objid = dref.objectid.get();
+ let off = dref.offset.get();
+ let seq = hash_extent_data_ref(root, objid, off);
+ let root_str = objectid_string(root, KeyType(0));
+ writeln!(
+ out,
+ "\t\t({iref_type} 0x{seq:x}) extent data backref root {root_str} objectid {objid} offset {off} count {}",
+ dref.count.get()
+ )?;
+ cur += 1 + size_of::<ExtentDataRef>();
+ }
+ KeyType::SHARED_DATA_REF => {
+ let Ok((sref, _)) = SharedDataRef::ref_from_prefix(inline_rest) else {
+ break;
+ };
+ writeln!(
+ out,
+ "\t\t({iref_type} 0x{iref_offset:x}) shared data backref parent {iref_offset} count {}",
+ sref.count.get()
+ )?;
+ cur += size_of::<ExtentInlineRef>() + size_of::<SharedDataRef>();
+ }
+ KeyType::EXTENT_OWNER_REF => {
+ writeln!(
+ out,
+ "\t\t({iref_type} 0x{iref_offset:x}) extent owner root {iref_offset}"
+ )?;
+ cur += size_of::<ExtentInlineRef>();
+ }
+ _ => break,
+ }
+ }
+ Ok(())
+}
+
+/// `print_extent_data_ref()`
+pub fn print_extent_data_ref(out: &mut impl Write, data: &[u8]) -> io::Result<()> {
+ let Ok((dref, _)) = ExtentDataRef::ref_from_prefix(data) else {
+ return writeln!(out, "\t\textent data ref invalid");
+ };
+ let root_str = objectid_string(dref.root.get(), KeyType(0));
+ writeln!(
+ out,
+ "\t\textent data backref root {root_str} objectid {} offset {} count {}",
+ dref.objectid.get(),
+ dref.offset.get(),
+ dref.count.get()
+ )
+}
+
+/// `print_shared_data_ref()`
+pub fn print_shared_data_ref(out: &mut impl Write, data: &[u8]) -> io::Result<()> {
+ let Ok((sref, _)) = SharedDataRef::ref_from_prefix(data) else {
+ return writeln!(out, "\t\tshared data ref invalid");
+ };
+ writeln!(out, "\t\tshared data backref count {}", sref.count.get())
+}
+
+/// `print_extent_owner_ref()`
+pub fn print_extent_owner_ref(out: &mut impl Write, data: &[u8]) -> io::Result<()> {
+ let Ok((oref, _)) = ExtentOwnerRef::ref_from_prefix(data) else {
+ return writeln!(out, "\t\textent owner ref invalid");
+ };
+ writeln!(out, "\t\textent owner root {}", oref.root_id.get())
+}
+
/// `btrfs_print_tree()` / `__btrfs_print_leaf()` for a leaf.
pub fn print_leaf(out: &mut impl Write, fs: &Fs, view: &View<'_>) -> io::Result<()> {
let View::Leaf {
@@ -705,6 +863,16 @@ pub fn print_leaf(out: &mut impl Write, fs: &Fs, view: &View<'_>) -> io::Result<
KeyType::ROOT_REF => print_root_ref(out, item_payload, "ref")?,
KeyType::ROOT_BACKREF => print_root_ref(out, item_payload, "backref")?,
KeyType::ORPHAN_ITEM => writeln!(out, "\t\torphan item")?,
+ KeyType::BLOCK_GROUP_ITEM => print_block_group_item(out, item_payload)?,
+ KeyType::EXTENT_ITEM | KeyType::METADATA_ITEM => {
+ print_extent_item(out, &item.key, item_payload)?;
+ }
+ KeyType::TREE_BLOCK_REF => writeln!(out, "\t\ttree block backref")?,
+ KeyType::SHARED_BLOCK_REF => writeln!(out, "\t\tshared block backref")?,
+ KeyType::EXTENT_DATA_REF => print_extent_data_ref(out, item_payload)?,
+ KeyType::SHARED_DATA_REF => print_shared_data_ref(out, item_payload)?,
+ KeyType::EXTENT_OWNER_REF => print_extent_owner_ref(out, item_payload)?,
+ KeyType::EXTENT_REF_V0 => writeln!(out, "\t\textent ref v0 (deprecated)")?,
_ => {}
}
}
@@ -1425,4 +1593,38 @@ mod tests {
let s = String::from_utf8(out).unwrap();
assert!(s.contains("root ref key dirid 256 sequence 1 name subvol_1"));
}
+
+ #[test]
+ fn print_extent_tree_items() {
+ let mut out = Vec::new();
+ let mut bgi = BlockGroupItem::new_zeroed();
+ bgi.used = (SZ_1M as u64).into();
+ bgi.chunk_objectid = 256.into();
+ bgi.flags = block_group::METADATA.into();
+ print_block_group_item(&mut out, bgi.as_bytes()).unwrap();
+ let s = String::from_utf8(out).unwrap();
+ assert!(s.contains("block group used 1048576 chunk_objectid 256 flags METADATA"));
+
+ let mut out = Vec::new();
+ let key = DiskKey {
+ objectid: (SZ_1M as u64).into(),
+ r#type: KeyType::METADATA_ITEM.0,
+ offset: 0.into(),
+ };
+ let mut ei = ExtentItem::new_zeroed();
+ ei.refs = 1.into();
+ ei.generation = 5.into();
+ ei.flags = (extent_flag::TREE_BLOCK | extent_flag::FULL_BACKREF).into();
+ let mut ei_bytes = ei.as_bytes().to_vec();
+ let mut iref = ExtentInlineRef::new_zeroed();
+ iref.r#type = KeyType::TREE_BLOCK_REF.0;
+ iref.offset = objectid::FS_TREE.into();
+ ei_bytes.extend_from_slice(iref.as_bytes());
+
+ print_extent_item(&mut out, &key, &ei_bytes).unwrap();
+ let s = String::from_utf8(out).unwrap();
+ assert!(s.contains("refs 1 gen 5 flags TREE_BLOCK|FULL_BACKREF"));
+ assert!(s.contains("tree block skinny level 0"));
+ assert!(s.contains("tree block backref root FS_TREE"));
+ }
}
--
2.56.1
^ permalink raw reply related [flat|nested] 16+ messages in thread* [PATCH 12/15] btrfs-progs: rust: print_tree: add remaining tree items
2026-12-01 7:56 [PATCH RFC 00/15] btrfs-progs: experimental rust support Qu Wenruo
` (10 preceding siblings ...)
2026-12-01 7:56 ` [PATCH 11/15] btrfs-progs: rust: print_tree: add extent and block group " Qu Wenruo
@ 2026-12-01 7:56 ` Qu Wenruo
2026-12-01 7:56 ` [PATCH 13/15] btrfs-progs: rust: fs: add tree search Qu Wenruo
` (2 subsequent siblings)
14 siblings, 0 replies; 16+ messages in thread
From: Qu Wenruo @ 2026-12-01 7:56 UTC (permalink / raw)
To: linux-btrfs
Implement printing functions in print_tree.rs for remaining tree items:
- CSUM_TREE: print_csum_item()
- FREE_SPACE_TREE: print_free_space_info(), print_free_space_header(),
free space extent and bitmap markers
- DEV_TREE: print_dev_extent()
- UUID_TREE: print_uuid_item() (UUID_KEY_SUBVOL, UUID_KEY_RECEIVED_SUBVOL)
- QGROUP_TREE: print_qgroup_status(), print_qgroup_info(), print_qgroup_limit()
- RAID_STRIPE_TREE: print_raid_stride()
---
rust/src/print_tree.rs | 204 ++++++++++++++++++++++++++++++++++++++++-
1 file changed, 200 insertions(+), 4 deletions(-)
diff --git a/rust/src/print_tree.rs b/rust/src/print_tree.rs
index 91abdcb208e3..fe7c4eb1acbb 100644
--- a/rust/src/print_tree.rs
+++ b/rust/src/print_tree.rs
@@ -11,10 +11,11 @@ use btrfs_rs::disk::consts::{
header_flag, incompat, inode_flag, limits, magic, objectid, root_flag, super_flag,
};
use btrfs_rs::disk::{
- csum, BlockGroupItem, Chunk, DevItem, DirItem, DirLogItem, DiskKey, ExtentDataRef,
- ExtentInlineRef, ExtentItem, ExtentOwnerRef, FileExtentItem, Header, InodeExtref, InodeItem,
- InodeRef, KeyPtr, KeyType, RootBackup, RootItem, RootRef, SharedDataRef, Stripe, SuperBlock,
- Timespec, TreeBlockInfo, LEGACY_ROOT_ITEM_SIZE,
+ csum, BlockGroupItem, Chunk, DevExtent, DevItem, DirItem, DirLogItem, DiskKey, ExtentDataRef,
+ ExtentInlineRef, ExtentItem, ExtentOwnerRef, FileExtentItem, FreeSpaceHeader, FreeSpaceInfo,
+ Header, InodeExtref, InodeItem, InodeRef, KeyPtr, KeyType, Le64, QgroupInfoItem,
+ QgroupLimitItem, QgroupStatusItem, RaidStride, RootBackup, RootItem, RootRef, SharedDataRef,
+ Stripe, SuperBlock, Timespec, TreeBlockInfo, LEGACY_ROOT_ITEM_SIZE,
};
use btrfs_rs::fs::Fs;
use zerocopy::{FromBytes, FromZeros, IntoBytes};
@@ -811,6 +812,138 @@ pub fn print_extent_owner_ref(out: &mut impl Write, data: &[u8]) -> io::Result<(
writeln!(out, "\t\textent owner root {}", oref.root_id.get())
}
+/// `print_csum_item()`
+pub fn print_csum_item(out: &mut impl Write, fs: &Fs, offset: u64, data: &[u8]) -> io::Result<()> {
+ let csum_size = if fs.csum_size == 0 { 4 } else { fs.csum_size };
+ let length = (data.len() / csum_size) as u64 * fs.sectorsize as u64;
+ writeln!(out, "\t\trange start {offset} length {length}")
+}
+
+/// `print_free_space_info()`
+pub fn print_free_space_info(out: &mut impl Write, data: &[u8]) -> io::Result<()> {
+ let Ok((info, _)) = FreeSpaceInfo::ref_from_prefix(data) else {
+ return writeln!(out, "\t\tfree space info invalid");
+ };
+ writeln!(
+ out,
+ "\t\tfree space info extent count {} flags {}",
+ info.extent_count.get(),
+ info.flags.get()
+ )
+}
+
+/// `print_free_space_header()`
+pub fn print_free_space_header(out: &mut impl Write, data: &[u8]) -> io::Result<()> {
+ let Ok((fsh, _)) = FreeSpaceHeader::ref_from_prefix(data) else {
+ return writeln!(out, "\t\tfree space header invalid");
+ };
+ write!(out, "\t\tlocation ")?;
+ print_key(out, &fsh.location)?;
+ writeln!(out)?;
+ writeln!(
+ out,
+ "\t\tcache generation {} entries {} bitmaps {}",
+ fsh.generation.get(),
+ fsh.num_entries.get(),
+ fsh.num_bitmaps.get()
+ )
+}
+
+/// `print_dev_extent()`
+pub fn print_dev_extent(out: &mut impl Write, data: &[u8]) -> io::Result<()> {
+ let Ok((de, _)) = DevExtent::ref_from_prefix(data) else {
+ return writeln!(out, "\t\tdev extent invalid");
+ };
+ writeln!(out, "\t\tdev extent chunk_tree {}", de.chunk_tree.get())?;
+ writeln!(
+ out,
+ "\t\tchunk_objectid {} chunk_offset {} length {}",
+ de.chunk_objectid.get(),
+ de.chunk_offset.get(),
+ de.length.get()
+ )
+}
+
+/// `print_uuid_item()`
+pub fn print_uuid_item(out: &mut impl Write, data: &[u8]) -> io::Result<()> {
+ for chunk in data.as_chunks::<{ size_of::<Le64>() }>().0 {
+ if let Ok((subvol_id, _)) = Le64::ref_from_prefix(chunk) {
+ writeln!(out, "\t\tsubvol_id {}", subvol_id.get())?;
+ }
+ }
+ Ok(())
+}
+
+/// `print_qgroup_status()`
+pub fn print_qgroup_status(out: &mut impl Write, data: &[u8]) -> io::Result<()> {
+ let Ok((status, _)) = QgroupStatusItem::ref_from_prefix(data) else {
+ return writeln!(out, "\t\tqgroup status invalid");
+ };
+ writeln!(
+ out,
+ "\t\tversion {} generation {} flags 0x{:x} rescan {}",
+ status.version.get(),
+ status.generation.get(),
+ status.flags.get(),
+ status.rescan.get()
+ )
+}
+
+/// `print_qgroup_info()`
+pub fn print_qgroup_info(out: &mut impl Write, data: &[u8]) -> io::Result<()> {
+ let Ok((info, _)) = QgroupInfoItem::ref_from_prefix(data) else {
+ return writeln!(out, "\t\tqgroup info invalid");
+ };
+ writeln!(out, "\t\tgeneration {}", info.generation.get())?;
+ writeln!(
+ out,
+ "\t\treferenced {} referenced compressed {}",
+ info.rfer.get(),
+ info.rfer_cmpr.get()
+ )?;
+ writeln!(
+ out,
+ "\t\texclusive {} exclusive compressed {}",
+ info.excl.get(),
+ info.excl_cmpr.get()
+ )
+}
+
+/// `print_qgroup_limit()`
+pub fn print_qgroup_limit(out: &mut impl Write, data: &[u8]) -> io::Result<()> {
+ let Ok((lim, _)) = QgroupLimitItem::ref_from_prefix(data) else {
+ return writeln!(out, "\t\tqgroup limit invalid");
+ };
+ writeln!(out, "\t\tflags 0x{:x}", lim.flags.get())?;
+ writeln!(
+ out,
+ "\t\tmax referenced {} max exclusive {}",
+ lim.max_rfer.get(),
+ lim.max_excl.get()
+ )?;
+ writeln!(
+ out,
+ "\t\trsv referenced {} rsv exclusive {}",
+ lim.rsv_rfer.get(),
+ lim.rsv_excl.get()
+ )
+}
+
+/// `print_raid_stride()`
+pub fn print_raid_stride(out: &mut impl Write, data: &[u8]) -> io::Result<()> {
+ for chunk in data.as_chunks::<{ size_of::<RaidStride>() }>().0 {
+ if let Ok((stride, _)) = RaidStride::ref_from_prefix(chunk) {
+ writeln!(
+ out,
+ "\t\tstride devid {} physical {}",
+ stride.devid.get(),
+ stride.physical.get()
+ )?;
+ }
+ }
+ Ok(())
+}
+
/// `btrfs_print_tree()` / `__btrfs_print_leaf()` for a leaf.
pub fn print_leaf(out: &mut impl Write, fs: &Fs, view: &View<'_>) -> io::Result<()> {
let View::Leaf {
@@ -846,6 +979,10 @@ pub fn print_leaf(out: &mut impl Write, fs: &Fs, view: &View<'_>) -> io::Result<
continue;
};
+ if item.key.r#type == 0 && item.key.objectid.get() == objectid::FREE_SPACE {
+ print_free_space_header(out, item_payload)?;
+ }
+
match KeyType(item.key.r#type) {
KeyType::CHUNK_ITEM => print_chunk_item(out, item_payload)?,
KeyType::DEV_ITEM => print_dev_item(out, item_payload)?,
@@ -873,6 +1010,18 @@ pub fn print_leaf(out: &mut impl Write, fs: &Fs, view: &View<'_>) -> io::Result<
KeyType::SHARED_DATA_REF => print_shared_data_ref(out, item_payload)?,
KeyType::EXTENT_OWNER_REF => print_extent_owner_ref(out, item_payload)?,
KeyType::EXTENT_REF_V0 => writeln!(out, "\t\textent ref v0 (deprecated)")?,
+ KeyType::CSUM_ITEM => print_csum_item(out, fs, item.key.offset.get(), item_payload)?,
+ KeyType::FREE_SPACE_INFO => print_free_space_info(out, item_payload)?,
+ KeyType::FREE_SPACE_EXTENT => writeln!(out, "\t\tfree space extent")?,
+ KeyType::FREE_SPACE_BITMAP => writeln!(out, "\t\tfree space bitmap")?,
+ KeyType::DEV_EXTENT => print_dev_extent(out, item_payload)?,
+ KeyType::UUID_KEY_SUBVOL | KeyType::UUID_KEY_RECEIVED_SUBVOL => {
+ print_uuid_item(out, item_payload)?;
+ }
+ KeyType::QGROUP_STATUS => print_qgroup_status(out, item_payload)?,
+ KeyType::QGROUP_INFO => print_qgroup_info(out, item_payload)?,
+ KeyType::QGROUP_LIMIT => print_qgroup_limit(out, item_payload)?,
+ KeyType::RAID_STRIPE => print_raid_stride(out, item_payload)?,
_ => {}
}
}
@@ -1627,4 +1776,51 @@ mod tests {
assert!(s.contains("tree block skinny level 0"));
assert!(s.contains("tree block backref root FS_TREE"));
}
+
+ #[test]
+ fn print_remaining_tree_items() {
+ let mut sb = SuperBlock::new_zeroed();
+ sb.nodesize = (SZ_16K as u32).into();
+ sb.sectorsize = (SZ_4K as u32).into();
+ sb.magic = magic::BTRFS.into();
+
+ let fs = Fs {
+ superblock: Box::new(sb),
+ devices: Vec::new(),
+ chunks: Default::default(),
+ sectorsize: SZ_4K as u32,
+ nodesize: SZ_16K as u32,
+ csum_type: 0,
+ csum_size: 4,
+ metadata_fsid: [0x22; 16],
+ tree_root: btrfs_rs::fs::Root::default(),
+ chunk_root: btrfs_rs::fs::Root::default(),
+ };
+
+ let mut out = Vec::new();
+ let csum_data = [0u8; 8];
+ print_csum_item(&mut out, &fs, 1048576, &csum_data).unwrap();
+ let s = String::from_utf8(out).unwrap();
+ assert!(s.contains("range start 1048576 length 8192"));
+
+ let mut out = Vec::new();
+ let mut de = DevExtent::new_zeroed();
+ de.chunk_tree = 3.into();
+ de.chunk_objectid = 256.into();
+ de.chunk_offset = 1048576.into();
+ de.length = 2097152.into();
+ print_dev_extent(&mut out, de.as_bytes()).unwrap();
+ let s = String::from_utf8(out).unwrap();
+ assert!(s.contains("dev extent chunk_tree 3"));
+ assert!(s.contains("chunk_objectid 256 chunk_offset 1048576 length 2097152"));
+
+ let mut out = Vec::new();
+ let mut qg = QgroupStatusItem::new_zeroed();
+ qg.version = 1.into();
+ qg.generation = 10.into();
+ qg.flags = 1.into();
+ print_qgroup_status(&mut out, qg.as_bytes()).unwrap();
+ let s = String::from_utf8(out).unwrap();
+ assert!(s.contains("version 1 generation 10 flags 0x1 rescan 0"));
+ }
}
--
2.56.1
^ permalink raw reply related [flat|nested] 16+ messages in thread* [PATCH 13/15] btrfs-progs: rust: fs: add tree search
2026-12-01 7:56 [PATCH RFC 00/15] btrfs-progs: experimental rust support Qu Wenruo
` (11 preceding siblings ...)
2026-12-01 7:56 ` [PATCH 12/15] btrfs-progs: rust: print_tree: add remaining " Qu Wenruo
@ 2026-12-01 7:56 ` Qu Wenruo
2026-12-01 7:56 ` [PATCH 14/15] btrfs-progs: rust: dump-tree: implement default full tree dump with BFS Qu Wenruo
2026-12-01 7:56 ` [PATCH 15/15] btrfs-progs: rust: dump-tree: add -t option to dump specified trees Qu Wenruo
14 siblings, 0 replies; 16+ messages in thread
From: Qu Wenruo @ 2026-12-01 7:56 UTC (permalink / raw)
To: linux-btrfs
Implement read-only tree search and traversal in rust/src/fs/search.rs:
- search_slot(): finds a key in a tree starting at root, returning the
path and exact match boolean, mirroring btrfs_search_slot()
- path_item(): gets the borrowed key and data slice at current slot
- next_item() and prev_item(): advances or steps back item by item,
navigating through leaves as needed (mirroring btrfs_next_item())
Implement tree root lookup in rust/src/fs/root.rs:
- find_root(): finds the newest root item for a given objectid in the
root tree, mirroring btrfs_find_last_root()
Add unit tests and a test tree synthesis harness in rust/src/fs/testutil.rs.
---
rust/src/fs/mod.rs | 10 +-
rust/src/fs/root.rs | 102 ++++++++++
rust/src/fs/search.rs | 405 ++++++++++++++++++++++++++++++++++++++++
rust/src/fs/testutil.rs | 165 ++++++++++++++++
4 files changed, 680 insertions(+), 2 deletions(-)
create mode 100644 rust/src/fs/root.rs
create mode 100644 rust/src/fs/search.rs
create mode 100644 rust/src/fs/testutil.rs
diff --git a/rust/src/fs/mod.rs b/rust/src/fs/mod.rs
index c257b08aab44..7154e83e3571 100644
--- a/rust/src/fs/mod.rs
+++ b/rust/src/fs/mod.rs
@@ -4,13 +4,19 @@
pub mod device;
pub mod error;
+pub mod root;
+pub mod search;
pub mod superblock;
+#[cfg(test)]
+pub mod testutil;
pub mod tree_block;
pub mod volumes;
pub use error::{Error, Result};
+pub use root::find_root;
+pub use search::{next_item, path_item, prev_item, search_slot, Path, PathEntry};
-use std::path::Path;
+use std::path::Path as FilePath;
use crate::disk::block::{self, item_data, View};
use crate::disk::consts::{incompat, objectid, super_offset};
@@ -51,7 +57,7 @@ impl Fs {
/// Open the filesystem of `device`, with the primary superblock of it.
/// If the filesystem has multiple devices, scans for the other devices
/// using `libblkid`.
- pub fn open(device: &Path) -> Result<Fs> {
+ pub fn open(device: &FilePath) -> Result<Fs> {
let sb_bytenr = super_offset(0);
let (first, superblock) = open_device(device, sb_bytenr)?;
check_compatibility(&superblock)?;
diff --git a/rust/src/fs/root.rs b/rust/src/fs/root.rs
new file mode 100644
index 000000000000..9e8858ec498e
--- /dev/null
+++ b/rust/src/fs/root.rs
@@ -0,0 +1,102 @@
+//! Finding the root of a tree, see `btrfs_find_last_root()`.
+
+use crate::disk::consts::limits;
+use crate::disk::{Key, KeyType, RootItem, LEGACY_ROOT_ITEM_SIZE};
+use crate::fs::error::{Error, Result};
+use crate::fs::search::{path_item, prev_item, search_slot};
+use crate::fs::{Fs, Root};
+use zerocopy::{FromZeros, IntoBytes};
+
+/// A root item that is shorter than the current one is a legacy one, the
+/// fields it has not are zero.
+fn parse_root_item(data: &[u8]) -> Result<RootItem> {
+ if data.len() < LEGACY_ROOT_ITEM_SIZE {
+ return Err(Error::Corrupt(format!(
+ "root item is too small: {} < {LEGACY_ROOT_ITEM_SIZE}",
+ data.len()
+ )));
+ }
+ let len = data.len().min(size_of::<RootItem>());
+ let mut item = RootItem::new_zeroed();
+ item.as_mut_bytes()[..len].copy_from_slice(&data[..len]);
+ Ok(item)
+}
+
+/// The root of the tree `objectid`, from its newest root item in the root
+/// tree. `None` if there is no such tree.
+pub fn find_root(fs: &Fs, objectid: u64) -> Result<Option<Root>> {
+ let key = Key {
+ objectid,
+ r#type: KeyType::ROOT_ITEM,
+ offset: u64::MAX,
+ };
+ let (mut path, _) = search_slot(fs, &fs.tree_root, &key)?;
+ if !prev_item(fs, &mut path)? {
+ return Ok(None);
+ }
+ let Some((found, data)) = path_item(&path)? else {
+ return Ok(None);
+ };
+ if found.objectid != objectid || found.r#type != KeyType::ROOT_ITEM {
+ return Ok(None);
+ }
+
+ let item = parse_root_item(data)?;
+ if usize::from(item.level) >= limits::MAX_LEVEL {
+ return Err(Error::Corrupt(format!(
+ "root item of tree {objectid} has a level too big: {}",
+ item.level
+ )));
+ }
+ Ok(Some(Root {
+ key: found,
+ bytenr: item.bytenr.get(),
+ level: item.level,
+ generation: item.generation.get(),
+ }))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::disk::DiskKey;
+ use crate::fs::testutil::*;
+
+ const ROOT_LEAF: u64 = 0x120000;
+
+ fn root_item(bytenr: u64, level: u8, generation: u64) -> (DiskKey, Vec<u8>) {
+ let mut item = RootItem::new_zeroed();
+ item.bytenr = bytenr.into();
+ item.level = level;
+ item.generation = generation.into();
+ (
+ key(300, KeyType::ROOT_ITEM, generation),
+ item.as_bytes().to_vec(),
+ )
+ }
+
+ #[test]
+ fn find_newest_root() {
+ let items = [root_item(0x130000, 0, 5), root_item(0x140000, 1, 6)];
+ let blocks = [(ROOT_LEAF, leaf(ROOT_LEAF, 6, &items))];
+ let device = TestDevice::new("root", &device_image((ROOT_LEAF, 0), &blocks));
+ let fs = Fs::open(&device.0).unwrap();
+
+ let root = find_root(&fs, 300).unwrap().unwrap();
+ assert_eq!(root.bytenr, 0x140000);
+ assert_eq!(root.level, 1);
+ assert_eq!(root.generation, 6);
+ assert_eq!(root.key.objectid, 300);
+ assert_eq!(root.key.offset, 6);
+ }
+
+ #[test]
+ fn root_not_found() {
+ let items = [root_item(0x130000, 0, 5)];
+ let blocks = [(ROOT_LEAF, leaf(ROOT_LEAF, 6, &items))];
+ let device = TestDevice::new("noroot", &device_image((ROOT_LEAF, 0), &blocks));
+ let fs = Fs::open(&device.0).unwrap();
+
+ assert_eq!(find_root(&fs, 400).unwrap(), None);
+ }
+}
diff --git a/rust/src/fs/search.rs b/rust/src/fs/search.rs
new file mode 100644
index 000000000000..43eca4e7da9e
--- /dev/null
+++ b/rust/src/fs/search.rs
@@ -0,0 +1,405 @@
+//! Searching a tree, see `btrfs_search_slot()` and `btrfs_next_item()`.
+
+use crate::disk::block::{self, item_data, View};
+use crate::disk::Key;
+use crate::fs::error::{Error, Result};
+use crate::fs::tree_block::{read_tree_block, Check};
+use crate::fs::{Fs, Root};
+
+/// A block of the path, and the slot taken in it.
+pub struct PathEntry {
+ pub bytenr: u64,
+ pub buf: Vec<u8>,
+ pub slot: usize,
+}
+
+/// The blocks from a leaf up to the root node, `levels[0]` is the leaf. It
+/// owns the blocks, so it stays valid until it is dropped.
+pub struct Path {
+ pub levels: Vec<PathEntry>,
+}
+
+fn view(entry: &PathEntry) -> Result<View<'_>> {
+ match block::parse_block(&entry.buf) {
+ Ok(v) => Ok(v),
+ Err(e) => Err(Error::Corrupt(format!(
+ "bad tree block {}, {e}",
+ entry.bytenr
+ ))),
+ }
+}
+
+fn nritems(entry: &PathEntry) -> Result<usize> {
+ Ok(match view(entry)? {
+ View::Node { ptrs, .. } => ptrs.len(),
+ View::Leaf { items, .. } => items.len(),
+ })
+}
+
+/// Find `key` in the tree with the root `root`. This is the read only
+/// part of `btrfs_search_slot()`.
+///
+/// Returns the path to the leaf, and if the key was found. If not, the slot is
+/// where the key would be inserted: the first item that is larger, which is
+/// past the last item of the leaf if there is none in the leaf.
+pub fn search_slot(fs: &Fs, root: &Root, key: &Key) -> Result<(Path, bool)> {
+ let mut levels = Vec::new();
+ let mut bytenr = root.bytenr;
+ let mut check = Check {
+ level: Some(root.level),
+ generation: Some(root.generation),
+ };
+
+ loop {
+ let buf = read_tree_block(fs, bytenr, &check)?;
+ let entry = PathEntry {
+ bytenr,
+ buf,
+ slot: 0,
+ };
+
+ let slot: usize;
+ let exact: bool;
+ let child: Option<(u64, Check)>;
+
+ match view(&entry)? {
+ View::Node { header, ptrs } => {
+ slot = match ptrs.binary_search_by(|ptr| Key::from(&ptr.key).cmp(key)) {
+ Ok(slot) => slot,
+ Err(slot) if slot > 0 => slot - 1,
+ Err(_) => 0,
+ };
+ let Some(ptr) = ptrs.get(slot) else {
+ return Err(Error::Corrupt(format!(
+ "bad tree block {bytenr}, the node is empty"
+ )));
+ };
+ exact = false;
+ child = Some((
+ ptr.blockptr.get(),
+ Check {
+ level: Some(header.level - 1),
+ generation: Some(ptr.generation.get()),
+ },
+ ));
+ }
+ View::Leaf { items, .. } => {
+ match items.binary_search_by(|item| Key::from(&item.key).cmp(key)) {
+ Ok(s) => {
+ slot = s;
+ exact = true;
+ }
+ Err(s) => {
+ slot = s;
+ exact = false;
+ }
+ }
+ child = None;
+ }
+ }
+
+ levels.push(PathEntry { slot, ..entry });
+ match child {
+ Some((child_bytenr, child_check)) => {
+ bytenr = child_bytenr;
+ check = child_check;
+ }
+ None => {
+ levels.reverse();
+ return Ok((Path { levels }, exact));
+ }
+ }
+ }
+}
+
+/// The item that the path points at, `None` if the slot is past the last item
+/// of the leaf. The data is in the path.
+pub fn path_item(path: &Path) -> Result<Option<(Key, &[u8])>> {
+ let entry = &path.levels[0];
+ let View::Leaf { items, data, .. } = view(entry)? else {
+ return Err(Error::Corrupt(format!(
+ "bad tree block {}, the path does not end in a leaf",
+ entry.bytenr
+ )));
+ };
+ let Some(item) = items.get(entry.slot) else {
+ return Ok(None);
+ };
+ let data = match item_data(data, item) {
+ Ok(d) => d,
+ Err(e) => {
+ return Err(Error::Corrupt(format!(
+ "bad tree block {}, {e}",
+ entry.bytenr
+ )))
+ }
+ };
+ Ok(Some((Key::from(&item.key), data)))
+}
+
+fn read_child(fs: &Fs, path: &mut Path, level: usize, last_slot: bool) -> Result<()> {
+ let parent = &path.levels[level];
+ let bytenr: u64;
+ let check: Check;
+ match view(parent)? {
+ View::Node { header, ptrs } => {
+ let Some(ptr) = ptrs.get(parent.slot) else {
+ return Err(Error::Corrupt(format!(
+ "bad node block {}, slot {} >= nritems {}",
+ parent.bytenr,
+ parent.slot,
+ ptrs.len()
+ )));
+ };
+ bytenr = ptr.blockptr.get();
+ check = Check {
+ level: Some(header.level - 1),
+ generation: Some(ptr.generation.get()),
+ };
+ }
+ View::Leaf { .. } => unreachable!(),
+ }
+
+ let buf = read_tree_block(fs, bytenr, &check)?;
+ path.levels[level - 1] = PathEntry {
+ bytenr,
+ buf,
+ slot: 0,
+ };
+
+ // The slot of the child, the first one or the last one
+ let child = &mut path.levels[level - 1];
+ let count = nritems(child)?;
+ if last_slot {
+ child.slot = if level > 1 {
+ count.saturating_sub(1)
+ } else {
+ count
+ };
+ }
+ Ok(())
+}
+
+/// Go to the first item of the next leaf. `false` if there is none.
+fn next_leaf(fs: &Fs, path: &mut Path) -> Result<bool> {
+ // Up to the first node that has a pointer after the one taken
+ let mut level = 1;
+ while level < path.levels.len() {
+ if path.levels[level].slot + 1 < nritems(&path.levels[level])? {
+ path.levels[level].slot += 1;
+ break;
+ }
+ level += 1;
+ }
+ if level == path.levels.len() {
+ return Ok(false);
+ }
+
+ // And down along the first pointers
+ while level > 0 {
+ read_child(fs, path, level, false)?;
+ level -= 1;
+ }
+ Ok(true)
+}
+
+/// Go to the last item of the previous leaf, with the slot past the last item
+/// of it. `false` if there is none.
+fn prev_leaf(fs: &Fs, path: &mut Path) -> Result<bool> {
+ let mut level = 1;
+ while level < path.levels.len() {
+ if path.levels[level].slot > 0 {
+ path.levels[level].slot -= 1;
+ break;
+ }
+ level += 1;
+ }
+ if level == path.levels.len() {
+ return Ok(false);
+ }
+
+ while level > 0 {
+ read_child(fs, path, level, true)?;
+ level -= 1;
+ }
+ Ok(true)
+}
+
+/// Go to the next item, maybe in the next leaf, like `btrfs_next_item()`.
+/// `false` if there is no more item.
+pub fn next_item(fs: &Fs, path: &mut Path) -> Result<bool> {
+ path.levels[0].slot += 1;
+ // A leaf may have no items
+ while path.levels[0].slot >= nritems(&path.levels[0])? {
+ if !next_leaf(fs, path)? {
+ return Ok(false);
+ }
+ }
+ Ok(true)
+}
+
+/// Go to the previous item, maybe in the previous leaf. `false` if there is no
+/// more item before it.
+pub fn prev_item(fs: &Fs, path: &mut Path) -> Result<bool> {
+ loop {
+ let slot = path.levels[0].slot.min(nritems(&path.levels[0])?);
+ if slot > 0 {
+ path.levels[0].slot = slot - 1;
+ return Ok(true);
+ }
+ if !prev_leaf(fs, path)? {
+ return Ok(false);
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::disk::{DiskKey, KeyType};
+ use crate::fs::testutil::*;
+
+ const NODE: u64 = 0x130000;
+ const LEAF1: u64 = 0x140000;
+ const LEAF2: u64 = 0x150000;
+
+ fn search_key(offset: u64) -> Key {
+ Key {
+ objectid: 300,
+ r#type: KeyType::INODE_ITEM,
+ offset,
+ }
+ }
+
+ fn item(offset: u64) -> (DiskKey, Vec<u8>) {
+ (key(300, KeyType::INODE_ITEM, offset), vec![offset as u8; 8])
+ }
+
+ /// A tree of two levels: a node, and the leaves with the offsets 10 and
+ /// 20, and 30 and 40.
+ fn open_tree(name: &str, leaf2: Vec<u8>) -> (TestDevice, Fs, Root) {
+ let blocks = [
+ (
+ NODE,
+ node(
+ NODE,
+ 1,
+ 6,
+ &[
+ (key(300, KeyType::INODE_ITEM, 10), LEAF1, 6),
+ (key(300, KeyType::INODE_ITEM, 30), LEAF2, 6),
+ ],
+ ),
+ ),
+ (LEAF1, leaf(LEAF1, 6, &[item(10), item(20)])),
+ (LEAF2, leaf2),
+ ];
+ let device = TestDevice::new(name, &device_image((0x120000, 0), &blocks));
+ let fs = Fs::open(&device.0).unwrap();
+ let root = Root {
+ key: Key {
+ objectid: 300,
+ r#type: KeyType::ROOT_ITEM,
+ offset: 0,
+ },
+ bytenr: NODE,
+ level: 1,
+ generation: 6,
+ };
+ (device, fs, root)
+ }
+
+ fn good_leaf2() -> Vec<u8> {
+ leaf(LEAF2, 6, &[item(30), item(40)])
+ }
+
+ /// The offset of the key that the path points at
+ fn offset_at(path: &Path) -> Option<u64> {
+ path_item(path).unwrap().map(|(key, _)| key.offset)
+ }
+
+ #[test]
+ fn exact_match_and_insertion_points() {
+ let (_device, fs, root) = open_tree("search", good_leaf2());
+
+ // First item, exact
+ let (path, exact) = search_slot(&fs, &root, &search_key(10)).unwrap();
+ assert!(exact);
+ assert_eq!(offset_at(&path), Some(10));
+
+ // Between two items of a leaf
+ let (path, exact) = search_slot(&fs, &root, &search_key(15)).unwrap();
+ assert!(!exact);
+ assert_eq!(offset_at(&path), Some(20));
+
+ // The last item of the first leaf
+ let (path, exact) = search_slot(&fs, &root, &search_key(20)).unwrap();
+ assert!(exact);
+ assert_eq!(offset_at(&path), Some(20));
+
+ // Between leaves
+ let (path, exact) = search_slot(&fs, &root, &search_key(25)).unwrap();
+ assert!(!exact);
+ assert_eq!(path.levels[0].bytenr, LEAF1);
+ assert_eq!(offset_at(&path), None);
+
+ // First item of the second leaf
+ let (path, exact) = search_slot(&fs, &root, &search_key(30)).unwrap();
+ assert!(exact);
+ assert_eq!(offset_at(&path), Some(30));
+
+ // Past the last item of the tree
+ let (path, exact) = search_slot(&fs, &root, &search_key(45)).unwrap();
+ assert!(!exact);
+ assert_eq!(path.levels[0].bytenr, LEAF2);
+ assert_eq!(offset_at(&path), None);
+ }
+
+ #[test]
+ fn item_iteration() {
+ let (_device, fs, root) = open_tree("iterate", good_leaf2());
+
+ // Iterate forward from the first item
+ let (mut path, exact) = search_slot(&fs, &root, &search_key(10)).unwrap();
+ assert!(exact);
+ assert_eq!(offset_at(&path), Some(10));
+
+ assert!(next_item(&fs, &mut path).unwrap());
+ assert_eq!(offset_at(&path), Some(20));
+
+ assert!(next_item(&fs, &mut path).unwrap());
+ assert_eq!(offset_at(&path), Some(30));
+
+ assert!(next_item(&fs, &mut path).unwrap());
+ assert_eq!(offset_at(&path), Some(40));
+
+ assert!(!next_item(&fs, &mut path).unwrap());
+
+ // Iterate backwards from the insertion point past the last item
+ let (mut path, exact) = search_slot(&fs, &root, &search_key(50)).unwrap();
+ assert!(!exact);
+ assert_eq!(offset_at(&path), None);
+
+ assert!(prev_item(&fs, &mut path).unwrap());
+ assert_eq!(offset_at(&path), Some(40));
+
+ assert!(prev_item(&fs, &mut path).unwrap());
+ assert_eq!(offset_at(&path), Some(30));
+
+ assert!(prev_item(&fs, &mut path).unwrap());
+ assert_eq!(offset_at(&path), Some(20));
+
+ assert!(prev_item(&fs, &mut path).unwrap());
+ assert_eq!(offset_at(&path), Some(10));
+
+ assert!(!prev_item(&fs, &mut path).unwrap());
+ }
+
+ #[test]
+ fn iteration_crosses_empty_leaves() {
+ let (_device, fs, root) = open_tree("empty_leaf", leaf(LEAF2, 6, &[]));
+ let (mut path, _) = search_slot(&fs, &root, &search_key(20)).unwrap();
+ assert_eq!(offset_at(&path), Some(20));
+ assert!(!next_item(&fs, &mut path).unwrap());
+ }
+}
diff --git a/rust/src/fs/testutil.rs b/rust/src/fs/testutil.rs
new file mode 100644
index 000000000000..546e6d737b93
--- /dev/null
+++ b/rust/src/fs/testutil.rs
@@ -0,0 +1,165 @@
+//! Test data: a device that has a superblock, a chunk tree and more blocks.
+
+use std::path::PathBuf;
+
+use crate::disk::consts::{block_group, csum_type, limits, objectid, super_offset};
+use crate::disk::{csum, Chunk, DiskKey, Header, Item, KeyPtr, KeyType, Stripe};
+use crate::fs::superblock::tests::{update_csum, valid_superblock};
+use crate::sizes::*;
+use zerocopy::{FromZeros, IntoBytes};
+
+pub const NODESIZE: usize = SZ_16K;
+pub const HEADER_SIZE: usize = size_of::<Header>();
+
+/// The first chunk, of 1MiB. A logical address in it is on the device at the
+/// same address, as in the chunk of data.
+pub const SYSTEM_START: u64 = SZ_1M as u64;
+pub const DATA_START: u64 = (2 * SZ_1M) as u64;
+pub const CHUNK_ROOT: u64 = (SZ_1M + SZ_64K) as u64;
+
+pub fn key(objectid: u64, key_type: KeyType, offset: u64) -> DiskKey {
+ DiskKey {
+ objectid: objectid.into(),
+ r#type: key_type.0,
+ offset: offset.into(),
+ }
+}
+
+fn finish_block(buf: &mut [u8]) {
+ let csum = csum::compute(csum_type::CRC32, &buf[limits::CSUM_SIZE..]).unwrap();
+ buf[..limits::CSUM_SIZE].copy_from_slice(&csum);
+}
+
+fn block_with_header(bytenr: u64, level: u8, generation: u64, nritems: usize) -> Vec<u8> {
+ let mut header = Header::new_zeroed();
+ header.bytenr = bytenr.into();
+ header.fsid = [0x11; 16];
+ header.generation = generation.into();
+ header.owner = objectid::CHUNK_TREE.into();
+ header.nritems = (nritems as u32).into();
+ header.level = level;
+
+ let mut buf = vec![0u8; NODESIZE];
+ buf[..HEADER_SIZE].copy_from_slice(header.as_bytes());
+ buf
+}
+
+/// A leaf with the items, with a valid checksum.
+pub fn leaf(bytenr: u64, generation: u64, items: &[(DiskKey, Vec<u8>)]) -> Vec<u8> {
+ let mut buf = block_with_header(bytenr, 0, generation, items.len());
+ let mut data_end = NODESIZE - HEADER_SIZE;
+ for (i, (key, data)) in items.iter().enumerate() {
+ data_end -= data.len();
+ let item = Item {
+ key: *key,
+ offset: (data_end as u32).into(),
+ size: (data.len() as u32).into(),
+ };
+ let at = HEADER_SIZE + i * size_of::<Item>();
+ buf[at..at + size_of::<Item>()].copy_from_slice(item.as_bytes());
+ buf[HEADER_SIZE + data_end..][..data.len()].copy_from_slice(data);
+ }
+ finish_block(&mut buf);
+ buf
+}
+
+/// A node with pointers to other blocks, with a valid checksum.
+pub fn node(bytenr: u64, level: u8, generation: u64, ptrs: &[(DiskKey, u64, u64)]) -> Vec<u8> {
+ let mut buf = block_with_header(bytenr, level, generation, ptrs.len());
+ for (i, (key, blockptr, ptr_gen)) in ptrs.iter().enumerate() {
+ let ptr = KeyPtr {
+ key: *key,
+ blockptr: (*blockptr).into(),
+ generation: (*ptr_gen).into(),
+ };
+ let at = HEADER_SIZE + i * size_of::<KeyPtr>();
+ buf[at..at + size_of::<KeyPtr>()].copy_from_slice(ptr.as_bytes());
+ }
+ finish_block(&mut buf);
+ buf
+}
+
+/// A chunk item for a chunk of 1MiB with single replication.
+pub fn chunk_item(flags: u64, start: u64) -> Vec<u8> {
+ let mut chunk = Chunk::new_zeroed();
+ chunk.length = (SZ_1M as u64).into();
+ chunk.stripe_len = (SZ_64K as u64).into();
+ chunk.r#type = flags.into();
+ chunk.sector_size = (SZ_4K as u32).into();
+ chunk.num_stripes = 1.into();
+ chunk.sub_stripes = 1.into();
+
+ let mut stripe = Stripe::new_zeroed();
+ stripe.devid = 1.into();
+ stripe.offset = start.into();
+ [chunk.as_bytes(), stripe.as_bytes()].concat()
+}
+
+pub fn chunk_key(start: u64) -> DiskKey {
+ key(objectid::FIRST_CHUNK_TREE, KeyType::CHUNK_ITEM, start)
+}
+
+/// The chunk tree: a leaf with the system chunk and the data chunk.
+pub fn chunk_tree_leaf() -> Vec<u8> {
+ leaf(
+ CHUNK_ROOT,
+ 5,
+ &[
+ (
+ chunk_key(SYSTEM_START),
+ chunk_item(block_group::SYSTEM, SYSTEM_START),
+ ),
+ (
+ chunk_key(DATA_START),
+ chunk_item(block_group::DATA, DATA_START),
+ ),
+ ],
+ )
+}
+
+/// A device of 3MiB, with the superblock which has the system chunk, the chunk
+/// tree, and the `blocks` at their addresses. The root of the root tree is
+/// `tree_root`: the address and the level.
+pub fn device_image(tree_root: (u64, u8), blocks: &[(u64, Vec<u8>)]) -> Vec<u8> {
+ let mut sb = valid_superblock();
+ sb.chunk_root = CHUNK_ROOT.into();
+ sb.chunk_root_generation = 5.into();
+ sb.root = tree_root.0.into();
+ sb.root_level = tree_root.1;
+ sb.generation = 6.into();
+ sb.dev_item.devid = 1.into();
+
+ let array = [
+ chunk_key(SYSTEM_START).as_bytes(),
+ &chunk_item(block_group::SYSTEM, SYSTEM_START),
+ ]
+ .concat();
+ assert_eq!(array.len(), sb.sys_chunk_array_size.get() as usize);
+ sb.sys_chunk_array[..array.len()].copy_from_slice(&array);
+ update_csum(&mut sb);
+
+ let mut image = vec![0u8; 3 * SZ_1M];
+ image[super_offset(0) as usize..][..SZ_4K].copy_from_slice(sb.as_bytes());
+ image[CHUNK_ROOT as usize..][..NODESIZE].copy_from_slice(&chunk_tree_leaf());
+ for (bytenr, block) in blocks {
+ image[*bytenr as usize..][..block.len()].copy_from_slice(block);
+ }
+ image
+}
+
+/// A device in a file, which is removed on drop.
+pub struct TestDevice(pub PathBuf);
+
+impl TestDevice {
+ pub fn new(name: &str, image: &[u8]) -> TestDevice {
+ let path = std::env::temp_dir().join(format!("btrfs-rs-{}-{name}.img", std::process::id()));
+ std::fs::write(&path, image).unwrap();
+ TestDevice(path)
+ }
+}
+
+impl Drop for TestDevice {
+ fn drop(&mut self) {
+ let _ = std::fs::remove_file(&self.0);
+ }
+}
--
2.56.1
^ permalink raw reply related [flat|nested] 16+ messages in thread* [PATCH 14/15] btrfs-progs: rust: dump-tree: implement default full tree dump with BFS
2026-12-01 7:56 [PATCH RFC 00/15] btrfs-progs: experimental rust support Qu Wenruo
` (12 preceding siblings ...)
2026-12-01 7:56 ` [PATCH 13/15] btrfs-progs: rust: fs: add tree search Qu Wenruo
@ 2026-12-01 7:56 ` Qu Wenruo
2026-12-01 7:56 ` [PATCH 15/15] btrfs-progs: rust: dump-tree: add -t option to dump specified trees Qu Wenruo
14 siblings, 0 replies; 16+ messages in thread
From: Qu Wenruo @ 2026-12-01 7:56 UTC (permalink / raw)
To: linux-btrfs
Implement the default full tree dump behavior for btrfs-rs inspect-internal
dump-tree when -b is not specified:
- Add dump_tree_bfs() in print_tree.rs using a FIFO queue to dump nodes
and leaves level-by-level in BFS order, matching C btrfs_print_tree()
- In inspect_dump_tree.rs, dump the root tree, chunk tree, log root tree
(if present), and all trees recorded in the root tree via search_slot()
and next_item()
- Update inspect_dump_tree tests to verify default full tree dump
---
rust/src/cmds/inspect_dump_tree.rs | 236 ++++++++++++++++++++++++-----
rust/src/print_tree.rs | 53 ++++++-
2 files changed, 251 insertions(+), 38 deletions(-)
diff --git a/rust/src/cmds/inspect_dump_tree.rs b/rust/src/cmds/inspect_dump_tree.rs
index b151c21bf596..a8dcdead7c9b 100644
--- a/rust/src/cmds/inspect_dump_tree.rs
+++ b/rust/src/cmds/inspect_dump_tree.rs
@@ -4,13 +4,17 @@ use std::io::{self, BufWriter, Write};
use std::path::PathBuf;
use btrfs_rs::disk::block;
+use btrfs_rs::disk::consts::objectid;
+use btrfs_rs::disk::{DiskKey, Key, KeyType, RootItem};
+use btrfs_rs::fs::search::{next_item, path_item, search_slot};
use btrfs_rs::fs::tree_block::{read_tree_block, Check};
use btrfs_rs::fs::Fs;
use clap::Args as ClapArgs;
use super::{Failed, Result};
use crate::messages::error_flushing;
-use crate::print_tree::print_tree;
+use crate::print_tree::{dump_tree_bfs, print_key, print_tree};
+use zerocopy::FromBytes;
#[derive(ClapArgs)]
#[command(override_usage = "btrfs-rs inspect-internal dump-tree [options] <device>")]
@@ -23,17 +27,170 @@ pub struct Args {
pub device: PathBuf,
}
+fn tree_prefix(objectid: u64) -> &'static str {
+ match objectid {
+ objectid::ROOT_TREE => "root",
+ objectid::EXTENT_TREE => "extent",
+ objectid::CHUNK_TREE => "chunk",
+ objectid::DEV_TREE => "device",
+ objectid::FS_TREE => "fs",
+ objectid::ROOT_TREE_DIR => "directory",
+ objectid::CSUM_TREE => "checksum",
+ objectid::ORPHAN => "orphan",
+ objectid::TREE_LOG => "log",
+ objectid::TREE_LOG_FIXUP => "log fixup",
+ objectid::TREE_RELOC => "reloc",
+ objectid::DATA_RELOC_TREE => "data reloc",
+ objectid::EXTENT_CSUM => "extent checksum",
+ objectid::QUOTA_TREE => "quota",
+ objectid::UUID_TREE => "uuid",
+ objectid::FREE_SPACE_TREE => "free space",
+ objectid::MULTIPLE => "multiple",
+ objectid::BLOCK_GROUP_TREE => "block group",
+ objectid::RAID_STRIPE_TREE => "raid stripe",
+ _ => "file",
+ }
+}
+
+fn dump_full_tree(out: &mut impl Write, fs: &Fs) -> Result {
+ // 1. Root tree
+ if let Err(e) = writeln!(out, "root tree") {
+ return Err(e.into());
+ }
+ if let Err(e) = dump_tree_bfs(
+ out,
+ fs,
+ fs.tree_root.bytenr,
+ &Check {
+ level: Some(fs.tree_root.level),
+ generation: Some(fs.tree_root.generation),
+ },
+ ) {
+ return Err(e.into());
+ }
+
+ // 2. Chunk tree
+ if let Err(e) = writeln!(out, "chunk tree") {
+ return Err(e.into());
+ }
+ if let Err(e) = dump_tree_bfs(
+ out,
+ fs,
+ fs.chunk_root.bytenr,
+ &Check {
+ level: Some(fs.chunk_root.level),
+ generation: Some(fs.chunk_root.generation),
+ },
+ ) {
+ return Err(e.into());
+ }
+
+ // 3. Log root tree (if present in superblock)
+ let log_root = fs.superblock.log_root.get();
+ if log_root != 0 {
+ if let Err(e) = writeln!(out, "log root tree") {
+ return Err(e.into());
+ }
+ if let Err(e) = dump_tree_bfs(
+ out,
+ fs,
+ log_root,
+ &Check {
+ level: Some(fs.superblock.log_root_level),
+ generation: None,
+ },
+ ) {
+ return Err(e.into());
+ }
+ }
+
+ // 4. All trees in the tree of tree roots
+ let key = Key {
+ objectid: 0,
+ r#type: KeyType::ROOT_ITEM,
+ offset: 0,
+ };
+ let (mut path, _) = match search_slot(fs, &fs.tree_root, &key) {
+ Ok(res) => res,
+ Err(e) => {
+ error_flushing(out, format!("cannot read ROOT_ITEM from root tree: {e}"));
+ return Err(Failed);
+ }
+ };
+
+ loop {
+ let item_opt = match path_item(&path) {
+ Ok(item) => item,
+ Err(e) => {
+ error_flushing(out, format!("failed to read item from root tree: {e}"));
+ return Err(Failed);
+ }
+ };
+
+ if let Some((found_key, data)) = item_opt {
+ if found_key.r#type == KeyType::ROOT_ITEM {
+ let Ok((ri, _)) = RootItem::ref_from_prefix(data) else {
+ error_flushing(
+ out,
+ format!(
+ "bad root item size for key ({} {} {})",
+ found_key.objectid, found_key.r#type.0, found_key.offset
+ ),
+ );
+ let advanced = match next_item(fs, &mut path) {
+ Ok(b) => b,
+ Err(e) => {
+ error_flushing(out, format!("failed to advance item: {e}"));
+ return Err(Failed);
+ }
+ };
+ if !advanced {
+ break;
+ }
+ continue;
+ };
+
+ let prefix = tree_prefix(found_key.objectid);
+ if let Err(e) = write!(out, "{prefix} tree key ") {
+ return Err(e.into());
+ }
+ if let Err(e) = print_key(out, &DiskKey::from(&found_key)) {
+ return Err(e.into());
+ }
+ if let Err(e) = writeln!(out, " ") {
+ return Err(e.into());
+ }
+
+ if let Err(e) = dump_tree_bfs(
+ out,
+ fs,
+ ri.bytenr.get(),
+ &Check {
+ level: Some(ri.level),
+ generation: Some(ri.generation.get()),
+ },
+ ) {
+ return Err(e.into());
+ }
+ }
+ }
+
+ match next_item(fs, &mut path) {
+ Ok(true) => {}
+ Ok(false) => break,
+ Err(e) => {
+ error_flushing(out, format!("failed to advance item in root tree: {e}"));
+ return Err(Failed);
+ }
+ }
+ }
+
+ Ok(())
+}
+
pub fn run(args: Args) -> Result {
let mut out = BufWriter::new(io::stdout().lock());
- if args.block.is_empty() {
- error_flushing(
- &mut out,
- "dumping the whole tree is not supported yet; please specify -b <bytenr>",
- );
- return Err(Failed);
- }
-
let fs = match Fs::open(&args.device) {
Ok(fs) => fs,
Err(e) => {
@@ -45,36 +202,40 @@ pub fn run(args: Args) -> Result {
}
};
- let mut blocks = args.block;
- blocks.sort_unstable();
- blocks.dedup();
+ if args.block.is_empty() {
+ dump_full_tree(&mut out, &fs)?;
+ } else {
+ let mut blocks = args.block;
+ blocks.sort_unstable();
+ blocks.dedup();
- for bytenr in blocks {
- let buf = match read_tree_block(&fs, bytenr, &Check::default()) {
- Ok(buf) => buf,
- Err(e) => {
+ for bytenr in blocks {
+ let buf = match read_tree_block(&fs, bytenr, &Check::default()) {
+ Ok(buf) => buf,
+ Err(e) => {
+ error_flushing(
+ &mut out,
+ format!("failed to read tree block at {bytenr}: {e}"),
+ );
+ return Err(Failed);
+ }
+ };
+
+ let view = match block::parse_block(&buf) {
+ Ok(view) => view,
+ Err(e) => {
+ error_flushing(&mut out, format!("corrupted tree block at {bytenr}: {e}"));
+ return Err(Failed);
+ }
+ };
+
+ if let Err(e) = print_tree(&mut out, &fs, &view) {
error_flushing(
&mut out,
- format!("failed to read tree block at {bytenr}: {e}"),
+ format!("failed to print tree block at {bytenr}: {e}"),
);
return Err(Failed);
}
- };
-
- let view = match block::parse_block(&buf) {
- Ok(view) => view,
- Err(e) => {
- error_flushing(&mut out, format!("corrupted tree block at {bytenr}: {e}"));
- return Err(Failed);
- }
- };
-
- if let Err(e) = print_tree(&mut out, &fs, &view) {
- error_flushing(
- &mut out,
- format!("failed to print tree block at {bytenr}: {e}"),
- );
- return Err(Failed);
}
}
@@ -162,7 +323,7 @@ mod tests {
ptr.key.r#type = KeyType::INODE_ITEM.0;
ptr.key.offset = 0.into();
ptr.blockptr = child_bytenr.into();
- ptr.generation = 6.into();
+ ptr.generation = 5.into();
let mut buf = vec![0u8; NODESIZE];
buf[..HEADER_SIZE].copy_from_slice(header.as_bytes());
@@ -189,6 +350,7 @@ mod tests {
sb.chunk_root = CHUNK_ROOT.into();
sb.chunk_root_generation = 5.into();
sb.root = node_bytenr.into();
+ sb.root_level = 1;
sb.generation = 6.into();
sb.dev_item.devid = 1.into();
@@ -229,13 +391,13 @@ mod tests {
}
#[test]
- fn dump_tree_without_block_option_is_rejected() {
- let dev = TestDevice::new("noblock", &device_image_with_node(0x120000));
+ fn dump_tree_default_full_dump_succeeds() {
+ let dev = TestDevice::new("fulldump", &device_image_with_node(0x120000));
let args = Args {
block: Vec::new(),
device: dev.0.clone(),
};
- assert!(run(args).is_err());
+ assert!(run(args).is_ok());
}
#[test]
diff --git a/rust/src/print_tree.rs b/rust/src/print_tree.rs
index fe7c4eb1acbb..7fbc7a775225 100644
--- a/rust/src/print_tree.rs
+++ b/rust/src/print_tree.rs
@@ -1,11 +1,12 @@
//! Text output of on-disk structures that several commands print, see
//! `kernel-shared/print-tree.c`.
+use std::collections::VecDeque;
use std::io::{self, Write};
use chrono::{DateTime, Local};
-use btrfs_rs::disk::block::{item_data, View};
+use btrfs_rs::disk::block::{self, item_data, View};
use btrfs_rs::disk::consts::{
backref_rev, block_group, compat_ro, compress_type, extent_flag, file_extent_type, file_type,
header_flag, incompat, inode_flag, limits, magic, objectid, root_flag, super_flag,
@@ -17,6 +18,7 @@ use btrfs_rs::disk::{
QgroupLimitItem, QgroupStatusItem, RaidStride, RootBackup, RootItem, RootRef, SharedDataRef,
Stripe, SuperBlock, Timespec, TreeBlockInfo, LEGACY_ROOT_ITEM_SIZE,
};
+use btrfs_rs::fs::tree_block::{read_tree_block, Check};
use btrfs_rs::fs::Fs;
use zerocopy::{FromBytes, FromZeros, IntoBytes};
@@ -1036,6 +1038,55 @@ pub fn print_tree(out: &mut impl Write, fs: &Fs, view: &View<'_>) -> io::Result<
}
}
+/// Dumps an entire tree in BFS order (level by level, left to right).
+/// Mirrors C `bfs_print_children()` / `btrfs_print_tree()` with `BTRFS_PRINT_TREE_BFS`.
+pub fn dump_tree_bfs(
+ out: &mut impl Write,
+ fs: &Fs,
+ root_bytenr: u64,
+ check: &Check,
+) -> io::Result<()> {
+ let mut queue = VecDeque::new();
+ queue.push_back((root_bytenr, *check));
+
+ while let Some((bytenr, check)) = queue.pop_front() {
+ let buf = match read_tree_block(fs, bytenr, &check) {
+ Ok(buf) => buf,
+ Err(e) => {
+ error_flushing(out, format!("failed to read tree block at {bytenr}: {e}"));
+ continue;
+ }
+ };
+
+ let view = match block::parse_block(&buf) {
+ Ok(view) => view,
+ Err(e) => {
+ error_flushing(out, format!("corrupted tree block at {bytenr}: {e}"));
+ continue;
+ }
+ };
+
+ match &view {
+ View::Node { header, ptrs } => {
+ print_node(out, fs, &view)?;
+ for ptr in *ptrs {
+ queue.push_back((
+ ptr.blockptr.get(),
+ Check {
+ level: Some(header.level - 1),
+ generation: Some(ptr.generation.get()),
+ },
+ ));
+ }
+ }
+ View::Leaf { .. } => {
+ print_leaf(out, fs, &view)?;
+ }
+ }
+ }
+ Ok(())
+}
+
/// The `bg_flags_to_str()` of print-tree.c, including how it joins the names.
fn bg_flags_to_str(flags: u64) -> String {
let mut ret = String::new();
--
2.56.1
^ permalink raw reply related [flat|nested] 16+ messages in thread* [PATCH 15/15] btrfs-progs: rust: dump-tree: add -t option to dump specified trees
2026-12-01 7:56 [PATCH RFC 00/15] btrfs-progs: experimental rust support Qu Wenruo
` (13 preceding siblings ...)
2026-12-01 7:56 ` [PATCH 14/15] btrfs-progs: rust: dump-tree: implement default full tree dump with BFS Qu Wenruo
@ 2026-12-01 7:56 ` Qu Wenruo
14 siblings, 0 replies; 16+ messages in thread
From: Qu Wenruo @ 2026-12-01 7:56 UTC (permalink / raw)
To: linux-btrfs
Add the -t / --tree option to btrfs-rs inspect-internal dump-tree:
- Support numerical IDs (decimal and hex) and symbolic tree names (e.g.
root, chunk, extent, dev, fs, csum, etc.) matching C parse_tree_id()
- Allow specifying -t multiple times, preserving duplicates and dumping
each specified tree in the order requested
- When -t is specified, bypass full tree dump and dump only the
specified trees using dump_single_tree()
- Add unit tests for -t single, duplicate, and parse_tree_id cases
---
rust/src/cmds/inspect_dump_tree.rs | 243 ++++++++++++++++++++++++-----
1 file changed, 206 insertions(+), 37 deletions(-)
diff --git a/rust/src/cmds/inspect_dump_tree.rs b/rust/src/cmds/inspect_dump_tree.rs
index a8dcdead7c9b..afedbc675247 100644
--- a/rust/src/cmds/inspect_dump_tree.rs
+++ b/rust/src/cmds/inspect_dump_tree.rs
@@ -6,6 +6,7 @@ use std::path::PathBuf;
use btrfs_rs::disk::block;
use btrfs_rs::disk::consts::objectid;
use btrfs_rs::disk::{DiskKey, Key, KeyType, RootItem};
+use btrfs_rs::fs::find_root;
use btrfs_rs::fs::search::{next_item, path_item, search_slot};
use btrfs_rs::fs::tree_block::{read_tree_block, Check};
use btrfs_rs::fs::Fs;
@@ -23,10 +24,67 @@ pub struct Args {
#[arg(short = 'b', long = "block", action = clap::ArgAction::Append)]
pub block: Vec<u64>,
+ /// dump only trees with the given ID or name (can be specified multiple times)
+ #[arg(
+ short = 't',
+ long = "tree",
+ value_name = "TREE_ID",
+ action = clap::ArgAction::Append,
+ value_parser = parse_tree_id,
+ conflicts_with = "block",
+ )]
+ pub tree: Vec<u64>,
+
/// device to read
pub device: PathBuf,
}
+fn parse_tree_id(s: &str) -> std::result::Result<u64, String> {
+ if let Ok(id) = s.parse::<u64>() {
+ return Ok(id);
+ }
+ if let Some(hex) = s.strip_prefix("0x").or_else(|| s.strip_prefix("0X")) {
+ if let Ok(id) = u64::from_str_radix(hex, 16) {
+ return Ok(id);
+ }
+ }
+
+ let mut clean = s.trim().to_uppercase();
+ if let Some(rest) = clean.strip_prefix("BTRFS_") {
+ clean = rest.to_string();
+ }
+ if let Some(rest) = clean.strip_suffix("_OBJECTID") {
+ clean = rest.to_string();
+ }
+ if let Some(rest) = clean.strip_suffix("_TREE") {
+ clean = rest.to_string();
+ }
+
+ match clean.as_str() {
+ "ROOT" => Ok(objectid::ROOT_TREE),
+ "EXTENT" => Ok(objectid::EXTENT_TREE),
+ "CHUNK" => Ok(objectid::CHUNK_TREE),
+ "DEV" | "DEVICE" => Ok(objectid::DEV_TREE),
+ "FS" => Ok(objectid::FS_TREE),
+ "ROOT_TREE_DIR" | "DIRECTORY" => Ok(objectid::ROOT_TREE_DIR),
+ "CSUM" | "CHECKSUM" => Ok(objectid::CSUM_TREE),
+ "ORPHAN" => Ok(objectid::ORPHAN),
+ "TREE_LOG" | "TREE-LOG" | "LOG" => Ok(objectid::TREE_LOG),
+ "TREE_LOG_FIXUP" | "TREE-LOG-FIXUP" | "LOG_FIXUP" | "LOG-FIXUP" => {
+ Ok(objectid::TREE_LOG_FIXUP)
+ }
+ "TREE_RELOC" | "TREE-RELOC" | "RELOC" => Ok(objectid::TREE_RELOC),
+ "DATA_RELOC" | "DATA-RELOC" => Ok(objectid::DATA_RELOC_TREE),
+ "EXTENT_CSUM" => Ok(objectid::EXTENT_CSUM),
+ "QUOTA" => Ok(objectid::QUOTA_TREE),
+ "UUID" => Ok(objectid::UUID_TREE),
+ "FREE_SPACE" | "FREE-SPACE" => Ok(objectid::FREE_SPACE_TREE),
+ "BLOCK_GROUP" | "BLOCK-GROUP" => Ok(objectid::BLOCK_GROUP_TREE),
+ "RAID_STRIPE" | "RAID-STRIPE" => Ok(objectid::RAID_STRIPE_TREE),
+ _ => Err(format!("cannot parse tree id: {s}")),
+ }
+}
+
fn tree_prefix(objectid: u64) -> &'static str {
match objectid {
objectid::ROOT_TREE => "root",
@@ -54,10 +112,8 @@ fn tree_prefix(objectid: u64) -> &'static str {
fn dump_full_tree(out: &mut impl Write, fs: &Fs) -> Result {
// 1. Root tree
- if let Err(e) = writeln!(out, "root tree") {
- return Err(e.into());
- }
- if let Err(e) = dump_tree_bfs(
+ writeln!(out, "root tree")?;
+ dump_tree_bfs(
out,
fs,
fs.tree_root.bytenr,
@@ -65,15 +121,11 @@ fn dump_full_tree(out: &mut impl Write, fs: &Fs) -> Result {
level: Some(fs.tree_root.level),
generation: Some(fs.tree_root.generation),
},
- ) {
- return Err(e.into());
- }
+ )?;
// 2. Chunk tree
- if let Err(e) = writeln!(out, "chunk tree") {
- return Err(e.into());
- }
- if let Err(e) = dump_tree_bfs(
+ writeln!(out, "chunk tree")?;
+ dump_tree_bfs(
out,
fs,
fs.chunk_root.bytenr,
@@ -81,17 +133,13 @@ fn dump_full_tree(out: &mut impl Write, fs: &Fs) -> Result {
level: Some(fs.chunk_root.level),
generation: Some(fs.chunk_root.generation),
},
- ) {
- return Err(e.into());
- }
+ )?;
// 3. Log root tree (if present in superblock)
let log_root = fs.superblock.log_root.get();
if log_root != 0 {
- if let Err(e) = writeln!(out, "log root tree") {
- return Err(e.into());
- }
- if let Err(e) = dump_tree_bfs(
+ writeln!(out, "log root tree")?;
+ dump_tree_bfs(
out,
fs,
log_root,
@@ -99,9 +147,7 @@ fn dump_full_tree(out: &mut impl Write, fs: &Fs) -> Result {
level: Some(fs.superblock.log_root_level),
generation: None,
},
- ) {
- return Err(e.into());
- }
+ )?;
}
// 4. All trees in the tree of tree roots
@@ -151,17 +197,11 @@ fn dump_full_tree(out: &mut impl Write, fs: &Fs) -> Result {
};
let prefix = tree_prefix(found_key.objectid);
- if let Err(e) = write!(out, "{prefix} tree key ") {
- return Err(e.into());
- }
- if let Err(e) = print_key(out, &DiskKey::from(&found_key)) {
- return Err(e.into());
- }
- if let Err(e) = writeln!(out, " ") {
- return Err(e.into());
- }
+ write!(out, "{prefix} tree key ")?;
+ print_key(out, &DiskKey::from(&found_key))?;
+ writeln!(out, " ")?;
- if let Err(e) = dump_tree_bfs(
+ dump_tree_bfs(
out,
fs,
ri.bytenr.get(),
@@ -169,9 +209,7 @@ fn dump_full_tree(out: &mut impl Write, fs: &Fs) -> Result {
level: Some(ri.level),
generation: Some(ri.generation.get()),
},
- ) {
- return Err(e.into());
- }
+ )?;
}
}
@@ -188,6 +226,88 @@ fn dump_full_tree(out: &mut impl Write, fs: &Fs) -> Result {
Ok(())
}
+fn dump_single_tree(out: &mut impl Write, fs: &Fs, tree_id: u64) -> Result {
+ if tree_id == objectid::ROOT_TREE {
+ writeln!(out, "root tree")?;
+ dump_tree_bfs(
+ out,
+ fs,
+ fs.tree_root.bytenr,
+ &Check {
+ level: Some(fs.tree_root.level),
+ generation: Some(fs.tree_root.generation),
+ },
+ )?;
+ return Ok(());
+ }
+
+ if tree_id == objectid::CHUNK_TREE {
+ writeln!(out, "chunk tree")?;
+ dump_tree_bfs(
+ out,
+ fs,
+ fs.chunk_root.bytenr,
+ &Check {
+ level: Some(fs.chunk_root.level),
+ generation: Some(fs.chunk_root.generation),
+ },
+ )?;
+ return Ok(());
+ }
+
+ if tree_id == objectid::TREE_LOG {
+ let log_root = fs.superblock.log_root.get();
+ if log_root == 0 {
+ error_flushing(out, "cannot print log root tree, no log tree");
+ return Err(Failed);
+ }
+ writeln!(out, "log root tree")?;
+ dump_tree_bfs(
+ out,
+ fs,
+ log_root,
+ &Check {
+ level: Some(fs.superblock.log_root_level),
+ generation: None,
+ },
+ )?;
+ return Ok(());
+ }
+
+ let root = match find_root(fs, tree_id) {
+ Ok(Some(root)) => root,
+ Ok(None) => {
+ error_flushing(out, format!("cannot find root for tree {tree_id}"));
+ return Err(Failed);
+ }
+ Err(e) => {
+ error_flushing(
+ out,
+ format!("failed to read root item for tree {tree_id}: {e}"),
+ );
+ return Err(Failed);
+ }
+ };
+
+ let prefix = tree_prefix(tree_id);
+ let disk_key = DiskKey::from(&root.key);
+ write!(out, "{prefix} tree key ")?;
+ print_key(out, &disk_key)?;
+ writeln!(out, " ")?;
+
+ dump_tree_bfs(
+ out,
+ fs,
+ root.bytenr,
+ &Check {
+ level: Some(root.level),
+ generation: Some(root.generation),
+ },
+ )?;
+
+ Ok(())
+}
+
pub fn run(args: Args) -> Result {
let mut out = BufWriter::new(io::stdout().lock());
@@ -202,9 +322,7 @@ pub fn run(args: Args) -> Result {
}
};
- if args.block.is_empty() {
- dump_full_tree(&mut out, &fs)?;
- } else {
+ if !args.block.is_empty() {
let mut blocks = args.block;
blocks.sort_unstable();
blocks.dedup();
@@ -237,6 +355,12 @@ pub fn run(args: Args) -> Result {
return Err(Failed);
}
}
+ } else if !args.tree.is_empty() {
+ for tree_id in args.tree {
+ dump_single_tree(&mut out, &fs, tree_id)?;
+ }
+ } else {
+ dump_full_tree(&mut out, &fs)?;
}
out.flush()?;
@@ -395,6 +519,7 @@ mod tests {
let dev = TestDevice::new("fulldump", &device_image_with_node(0x120000));
let args = Args {
block: Vec::new(),
+ tree: Vec::new(),
device: dev.0.clone(),
};
assert!(run(args).is_ok());
@@ -406,6 +531,7 @@ mod tests {
let dev = TestDevice::new("node", &device_image_with_node(node_bytenr));
let args = Args {
block: vec![node_bytenr],
+ tree: Vec::new(),
device: dev.0.clone(),
};
assert!(run(args).is_ok());
@@ -417,6 +543,7 @@ mod tests {
let dev = TestDevice::new("multiple", &device_image_with_node(node_bytenr));
let args = Args {
block: vec![node_bytenr, node_bytenr],
+ tree: Vec::new(),
device: dev.0.clone(),
};
assert!(run(args).is_ok());
@@ -428,8 +555,50 @@ mod tests {
// CHUNK_ROOT is a leaf (level 0) containing CHUNK_ITEM
let args = Args {
block: vec![CHUNK_ROOT],
+ tree: Vec::new(),
device: dev.0.clone(),
};
assert!(run(args).is_ok());
}
+
+ #[test]
+ fn dump_tree_single_tree_option_succeeds() {
+ let dev = TestDevice::new("singletree", &device_image_with_node(0x120000));
+ let args = Args {
+ block: Vec::new(),
+ tree: vec![objectid::CHUNK_TREE],
+ device: dev.0.clone(),
+ };
+ assert!(run(args).is_ok());
+ }
+
+ #[test]
+ fn dump_tree_duplicated_tree_option_succeeds() {
+ let dev = TestDevice::new("duptree", &device_image_with_node(0x120000));
+ let args = Args {
+ block: Vec::new(),
+ tree: vec![objectid::CHUNK_TREE, objectid::CHUNK_TREE],
+ device: dev.0.clone(),
+ };
+ assert!(run(args).is_ok());
+ }
+
+ #[test]
+ fn parse_tree_id_names() {
+ assert_eq!(parse_tree_id("root").unwrap(), objectid::ROOT_TREE);
+ assert_eq!(parse_tree_id("ROOT_TREE").unwrap(), objectid::ROOT_TREE);
+ assert_eq!(
+ parse_tree_id("BTRFS_ROOT_TREE_OBJECTID").unwrap(),
+ objectid::ROOT_TREE
+ );
+ assert_eq!(parse_tree_id("chunk").unwrap(), objectid::CHUNK_TREE);
+ assert_eq!(parse_tree_id("extent").unwrap(), objectid::EXTENT_TREE);
+ assert_eq!(parse_tree_id("device").unwrap(), objectid::DEV_TREE);
+ assert_eq!(parse_tree_id("fs").unwrap(), objectid::FS_TREE);
+ assert_eq!(parse_tree_id("csum").unwrap(), objectid::CSUM_TREE);
+ assert_eq!(parse_tree_id("checksum").unwrap(), objectid::CSUM_TREE);
+ assert_eq!(parse_tree_id("5").unwrap(), 5);
+ assert_eq!(parse_tree_id("0x100").unwrap(), 256);
+ assert!(parse_tree_id("invalid_name").is_err());
+ }
}
--
2.56.1
^ permalink raw reply related [flat|nested] 16+ messages in thread