use crate::bytes::{
get_arr, get_u8, get_u16, get_u32, get_u64, put_arr, put_u16, put_u32, put_u64,
};
use crate::flags::flag_set;
use super::ParseError;
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct BlockGroupFlags(u64);
flag_set!(BlockGroupFlags: u64);
impl BlockGroupFlags {
pub const DATA: Self = Self(1 << 0);
pub const SYSTEM: Self = Self(1 << 1);
pub const METADATA: Self = Self(1 << 2);
pub const RAID0: Self = Self(1 << 3);
pub const RAID1: Self = Self(1 << 4);
pub const DUP: Self = Self(1 << 5);
pub const RAID10: Self = Self(1 << 6);
pub const RAID5: Self = Self(1 << 7);
pub const RAID6: Self = Self(1 << 8);
pub const RAID1C3: Self = Self(1 << 9);
pub const RAID1C4: Self = Self(1 << 10);
pub const REMAPPED: Self = Self(1 << 11);
pub const METADATA_REMAP: Self = Self(1 << 12);
pub const TYPE_MASK: Self = Self(Self::DATA.0 | Self::SYSTEM.0 | Self::METADATA.0);
pub const PROFILE_MASK: Self = Self(
Self::RAID0.0
| Self::RAID1.0
| Self::DUP.0
| Self::RAID10.0
| Self::RAID5.0
| Self::RAID6.0
| Self::RAID1C3.0
| Self::RAID1C4.0,
);
#[must_use]
pub const fn is_mirrored(self) -> bool {
let profile = self.0 & Self::PROFILE_MASK.0;
profile == 0
|| profile == Self::DUP.0
|| profile == Self::RAID1.0
|| profile == Self::RAID1C3.0
|| profile == Self::RAID1C4.0
}
#[must_use]
pub const fn is_striped(self) -> bool {
let profile = self.0 & Self::PROFILE_MASK.0;
profile == Self::RAID0.0
|| profile == Self::RAID10.0
|| profile == Self::RAID5.0
|| profile == Self::RAID6.0
}
#[must_use]
pub const fn profile_name(self) -> Option<&'static str> {
Some(match Self(self.0 & Self::PROFILE_MASK.0) {
Self::NONE => "single",
Self::RAID0 => "raid0",
Self::RAID1 => "raid1",
Self::DUP => "dup",
Self::RAID10 => "raid10",
Self::RAID5 => "raid5",
Self::RAID6 => "raid6",
Self::RAID1C3 => "raid1c3",
Self::RAID1C4 => "raid1c4",
_ => return None,
})
}
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub struct Stripe {
pub devid: u64,
pub offset: u64,
pub dev_uuid: [u8; 16],
}
impl Stripe {
pub const SIZE: usize = 32;
pub fn read_from(buf: &[u8]) -> Result<Self, ParseError> {
if buf.len() < Self::SIZE {
return Err(ParseError::TooShort {
structure: "btrfs_stripe",
need: Self::SIZE,
got: buf.len(),
});
}
Ok(Self {
devid: get_u64(buf, 0),
offset: get_u64(buf, 8),
dev_uuid: get_arr(buf, 16),
})
}
pub fn write_to(&self, buf: &mut [u8]) {
assert!(
buf.len() >= Self::SIZE,
"a chunk stripe needs {} bytes and was given {}",
Self::SIZE,
buf.len()
);
put_u64(buf, 0, self.devid);
put_u64(buf, 8, self.offset);
put_arr(buf, 16, &self.dev_uuid);
}
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub struct Chunk {
pub length: u64,
pub owner: u64,
pub stripe_len: u64,
pub ty: BlockGroupFlags,
pub io_align: u32,
pub io_width: u32,
pub sector_size: u32,
pub num_stripes: u16,
pub sub_stripes: u16,
}
impl Chunk {
pub const SIZE: usize = 48;
pub fn read_from(buf: &[u8]) -> Result<Self, ParseError> {
if buf.len() < Self::SIZE {
return Err(ParseError::TooShort {
structure: "btrfs_chunk",
need: Self::SIZE,
got: buf.len(),
});
}
Ok(Self {
length: get_u64(buf, 0),
owner: get_u64(buf, 8),
stripe_len: get_u64(buf, 16),
ty: BlockGroupFlags::from_bits(get_u64(buf, 24)),
io_align: get_u32(buf, 32),
io_width: get_u32(buf, 36),
sector_size: get_u32(buf, 40),
num_stripes: get_u16(buf, 44),
sub_stripes: get_u16(buf, 46),
})
}
pub fn write_to(&self, buf: &mut [u8]) {
assert!(
buf.len() >= Self::SIZE,
"a chunk head needs {} bytes and was given {}",
Self::SIZE,
buf.len()
);
put_u64(buf, 0, self.length);
put_u64(buf, 8, self.owner);
put_u64(buf, 16, self.stripe_len);
put_u64(buf, 24, self.ty.bits());
put_u32(buf, 32, self.io_align);
put_u32(buf, 36, self.io_width);
put_u32(buf, 40, self.sector_size);
put_u16(buf, 44, self.num_stripes);
put_u16(buf, 46, self.sub_stripes);
}
#[must_use]
pub const fn encoded_len(&self) -> usize {
Self::SIZE + self.num_stripes as usize * Stripe::SIZE
}
pub fn stripe_at(&self, buf: &[u8], index: u16) -> Result<Stripe, ParseError> {
if index >= self.num_stripes {
return Err(ParseError::TooShort {
structure: "btrfs_stripe",
need: self.encoded_len(),
got: buf.len(),
});
}
let at = Self::SIZE + index as usize * Stripe::SIZE;
let end = at + Stripe::SIZE;
if buf.len() < end {
return Err(ParseError::TooShort {
structure: "btrfs_stripe",
need: end,
got: buf.len(),
});
}
Stripe::read_from(&buf[at..end])
}
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub struct DevItem {
pub devid: u64,
pub total_bytes: u64,
pub bytes_used: u64,
pub io_align: u32,
pub io_width: u32,
pub sector_size: u32,
pub ty: u64,
pub generation: u64,
pub start_offset: u64,
pub dev_group: u32,
pub seek_speed: u8,
pub bandwidth: u8,
pub uuid: [u8; 16],
pub fsid: [u8; 16],
}
impl DevItem {
pub const SIZE: usize = 98;
pub fn read_from(buf: &[u8]) -> Result<Self, ParseError> {
if buf.len() < Self::SIZE {
return Err(ParseError::TooShort {
structure: "btrfs_dev_item",
need: Self::SIZE,
got: buf.len(),
});
}
Ok(Self {
devid: get_u64(buf, 0),
total_bytes: get_u64(buf, 8),
bytes_used: get_u64(buf, 16),
io_align: get_u32(buf, 24),
io_width: get_u32(buf, 28),
sector_size: get_u32(buf, 32),
ty: get_u64(buf, 36),
generation: get_u64(buf, 44),
start_offset: get_u64(buf, 52),
dev_group: get_u32(buf, 60),
seek_speed: get_u8(buf, 64),
bandwidth: get_u8(buf, 65),
uuid: get_arr(buf, 66),
fsid: get_arr(buf, 82),
})
}
pub fn write_to(&self, buf: &mut [u8]) {
assert!(
buf.len() >= Self::SIZE,
"a device item needs {} bytes and was given {}",
Self::SIZE,
buf.len()
);
put_u64(buf, 0, self.devid);
put_u64(buf, 8, self.total_bytes);
put_u64(buf, 16, self.bytes_used);
put_u32(buf, 24, self.io_align);
put_u32(buf, 28, self.io_width);
put_u32(buf, 32, self.sector_size);
put_u64(buf, 36, self.ty);
put_u64(buf, 44, self.generation);
put_u64(buf, 52, self.start_offset);
put_u32(buf, 60, self.dev_group);
buf[64] = self.seek_speed;
buf[65] = self.bandwidth;
put_arr(buf, 66, &self.uuid);
put_arr(buf, 82, &self.fsid);
}
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub struct DevExtent {
pub chunk_tree: u64,
pub chunk_objectid: u64,
pub chunk_offset: u64,
pub length: u64,
pub chunk_tree_uuid: [u8; 16],
}
impl DevExtent {
pub const SIZE: usize = 48;
pub fn read_from(buf: &[u8]) -> Result<Self, ParseError> {
if buf.len() < Self::SIZE {
return Err(ParseError::TooShort {
structure: "btrfs_dev_extent",
need: Self::SIZE,
got: buf.len(),
});
}
Ok(Self {
chunk_tree: get_u64(buf, 0),
chunk_objectid: get_u64(buf, 8),
chunk_offset: get_u64(buf, 16),
length: get_u64(buf, 24),
chunk_tree_uuid: get_arr(buf, 32),
})
}
pub fn write_to(&self, buf: &mut [u8]) {
assert!(
buf.len() >= Self::SIZE,
"a device extent needs {} bytes and was given {}",
Self::SIZE,
buf.len()
);
put_u64(buf, 0, self.chunk_tree);
put_u64(buf, 8, self.chunk_objectid);
put_u64(buf, 16, self.chunk_offset);
put_u64(buf, 24, self.length);
put_arr(buf, 32, &self.chunk_tree_uuid);
}
}
#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
pub struct DevStats {
pub write_errs: u64,
pub read_errs: u64,
pub flush_errs: u64,
pub corruption_errs: u64,
pub generation_errs: u64,
}
impl DevStats {
pub const SIZE: usize = 40;
pub const DEV_STATS: u64 = 0;
pub fn read_from(buf: &[u8]) -> Result<Self, ParseError> {
if buf.len() < Self::SIZE {
return Err(ParseError::TooShort {
structure: "btrfs_dev_stats_item",
need: Self::SIZE,
got: buf.len(),
});
}
Ok(Self {
write_errs: get_u64(buf, 0),
read_errs: get_u64(buf, 8),
flush_errs: get_u64(buf, 16),
corruption_errs: get_u64(buf, 24),
generation_errs: get_u64(buf, 32),
})
}
pub fn write_to(&self, buf: &mut [u8]) {
assert!(
buf.len() >= Self::SIZE,
"a device statistics record needs {} bytes and was given {}",
Self::SIZE,
buf.len()
);
put_u64(buf, 0, self.write_errs);
put_u64(buf, 8, self.read_errs);
put_u64(buf, 16, self.flush_errs);
put_u64(buf, 24, self.corruption_errs);
put_u64(buf, 32, self.generation_errs);
}
}
#[cfg(test)]
mod tests {
use super::*;
fn a_chunk() -> Chunk {
Chunk {
length: 8 << 20,
owner: 2,
stripe_len: 64 << 10,
ty: BlockGroupFlags::SYSTEM | BlockGroupFlags::DUP,
io_align: 64 << 10,
io_width: 64 << 10,
sector_size: 4096,
num_stripes: 2,
sub_stripes: 1,
}
}
#[test]
fn a_chunk_head_round_trips_and_the_type_word_is_the_baselines() {
let chunk = a_chunk();
let mut buf = [0u8; Chunk::SIZE];
chunk.write_to(&mut buf);
assert_eq!(Chunk::read_from(&buf).expect("a full head"), chunk);
assert_eq!(chunk.ty.bits(), 0x22);
assert_eq!(&buf[24..32], &0x22u64.to_le_bytes());
assert_eq!(&buf[44..46], &2u16.to_le_bytes());
assert_eq!(chunk.encoded_len(), 112);
}
#[test]
fn a_stripe_is_taken_out_of_the_record_the_head_came_from() {
let chunk = a_chunk();
let mut buf = vec![0u8; chunk.encoded_len()];
chunk.write_to(&mut buf);
let stripes = [
Stripe {
devid: 1,
offset: 22_020_096,
dev_uuid: [0xec; 16],
},
Stripe {
devid: 1,
offset: 30_408_704,
dev_uuid: [0xec; 16],
},
];
for (index, stripe) in stripes.iter().enumerate() {
stripe.write_to(&mut buf[Chunk::SIZE + index * Stripe::SIZE..]);
}
assert_eq!(chunk.stripe_at(&buf, 0).expect("stripe 0"), stripes[0]);
assert_eq!(chunk.stripe_at(&buf, 1).expect("stripe 1"), stripes[1]);
}
#[test]
fn a_stripe_past_the_count_or_past_the_buffer_is_no_stripe() {
let chunk = a_chunk();
let buf = vec![0u8; chunk.encoded_len()];
assert!(matches!(
chunk.stripe_at(&buf, 2),
Err(ParseError::TooShort { .. })
));
let inflated = Chunk {
num_stripes: 64,
..chunk
};
assert!(matches!(
inflated.stripe_at(&buf, 63),
Err(ParseError::TooShort { .. })
));
assert_eq!(inflated.stripe_at(&buf, 1).expect("still inside").devid, 0);
}
#[test]
fn single_is_the_absence_of_a_profile_and_still_reads_as_one_copy() {
let single = BlockGroupFlags::DATA;
assert_eq!(single.profile_name(), Some("single"));
assert!(single.is_mirrored(), "one copy is trivially every copy");
assert!(!single.contains(BlockGroupFlags::PROFILE_MASK));
for mirrored in [
BlockGroupFlags::DUP,
BlockGroupFlags::RAID1,
BlockGroupFlags::RAID1C3,
BlockGroupFlags::RAID1C4,
] {
assert!((BlockGroupFlags::METADATA | mirrored).is_mirrored());
}
for striped in [
BlockGroupFlags::RAID0,
BlockGroupFlags::RAID10,
BlockGroupFlags::RAID5,
BlockGroupFlags::RAID6,
] {
let chunk = BlockGroupFlags::DATA | striped;
assert!(
!chunk.is_mirrored(),
"a stripe of a striped chunk is a piece, not a copy"
);
assert!(chunk.is_striped());
}
assert!(!single.is_striped());
}
#[test]
fn a_profile_word_the_format_does_not_define_is_neither_copies_nor_stripes() {
let both = BlockGroupFlags::DATA | BlockGroupFlags::RAID1 | BlockGroupFlags::DUP;
assert_eq!(both.profile_name(), None);
assert!(
!both.is_mirrored(),
"an undefined profile is not read as copies"
);
assert!(!both.is_striped(), "and the two are not complements");
}
#[test]
fn a_device_item_round_trips_through_its_ninety_eight_bytes() {
let dev = DevItem {
devid: 1,
total_bytes: 1 << 30,
bytes_used: 132_513_792,
io_align: 4096,
io_width: 4096,
sector_size: 4096,
ty: 0,
generation: 0,
start_offset: 0,
dev_group: 0,
seek_speed: 0,
bandwidth: 0,
uuid: [0xec; 16],
fsid: [0x11; 16],
};
let mut buf = [0u8; DevItem::SIZE];
dev.write_to(&mut buf);
assert_eq!(DevItem::read_from(&buf).expect("a full item"), dev);
assert_eq!(&buf[66..82], &[0xec; 16]);
assert_eq!(&buf[82..98], &[0x11; 16]);
}
#[test]
fn a_device_extent_round_trips_and_carries_the_chunk_tree_at_its_tail() {
let extent = DevExtent {
chunk_tree: 3,
chunk_objectid: 256,
chunk_offset: 30_408_704,
length: 53_673_984,
chunk_tree_uuid: [0xc7; 16],
};
let mut buf = [0u8; DevExtent::SIZE];
extent.write_to(&mut buf);
assert_eq!(DevExtent::read_from(&buf).expect("a full record"), extent);
assert_eq!(&buf[32..48], &[0xc7; 16]);
for got in 0..DevExtent::SIZE {
assert!(DevExtent::read_from(&vec![0u8; got]).is_err(), "{got}");
}
}
#[test]
fn a_devices_statistics_round_trip_and_are_five_counters_rather_than_forty_zeros() {
let stats = DevStats {
write_errs: 1,
read_errs: 2,
flush_errs: 3,
corruption_errs: 4,
generation_errs: 5,
};
let mut buf = [0u8; DevStats::SIZE];
stats.write_to(&mut buf);
assert_eq!(DevStats::read_from(&buf).expect("a full record"), stats);
assert_eq!(
DevStats::default(),
DevStats::read_from(&[0u8; 40]).unwrap()
);
for got in 0..DevStats::SIZE {
assert!(DevStats::read_from(&vec![0u8; got]).is_err(), "{got}");
}
}
}