interplane.Get Omega
Read in your language

synapse

A component of the AienOS ecosystem.

Brought by drakestapleton

branch main Branches Tags History

synapse / crates / synapse-store / src / blockdev.rs

1327 lines · 50854 bytes Raw Blame History
1//! R1 raw block segment store (ADR 0003 section 9 step 27): the A2 segment store on a
2//! block device with no filesystem. The specification is `docs/R1_RAW_BLOCK_STORE.md`.
3//!
4//! The device is one byte range opened with `O_DIRECT` (page cache bypassed). On Linux
5//! that is a dedicated partition; tests and benchmarks use a preallocated regular file at
6//! a path the caller names. Nothing else is ever opened: no `/dev` scan, no globbing, no
7//! derived paths. The opened device is held under an exclusive lock (`flock`, plus
8//! `O_EXCL` for a block device). A device that carries a recognisable filesystem,
9//! partition, or volume signature anywhere it is looked for ([`SIGNATURES`], including
10//! the backup GPT header, MD RAID and ZFS labels near the end), or any other non-zero
11//! byte in its label area, is refused unless the caller sets
12//! [`BlockDeviceConfig::allow_foreign_signature`]. Formatting is never the default.
13//!
14//! On-device layout (little-endian, 4 KiB blocks):
15//!
16//! * `0..128 KiB` label area. Superblock copy 0 at byte 0, copy 1 at byte 4096; the rest
17//! is zero. Generation `g` is written to copy `g % 2`, so the newest valid copy and
18//! the one before it are always on the device.
19//! * Two metadata regions of `meta_region_bytes` each (region 0 at 1 MiB). A metadata
20//! region holds the named objects the A2 store keeps as small files (`wal.log`,
21//! `checkpoint.v1`, `checkpoint.v2`, `wal.v2.index.*`): `"SBM1" | u32 count |
22//! count x (u16 name_len | name | u64 len | bytes)`, names strictly increasing.
23//! * Segment slots from `data_offset` (1 MiB aligned): slot `k >= 1` is a 4 KiB segment
24//! header (`"SBSG" | u32 version | uuid[16] | u64 segment id | u64 segment_bytes |
25//! u32 crc32c`) followed by `segment_bytes` of segment data in the WAL v2 batch format
26//! ([`crate::wal2`]), unchanged from A2.
27//!
28//! Superblock (first 164 bytes of its 4 KiB block, rest zero): `"SYNBLKS1" | u32 version
29//! | u32 block | uuid[16] | u64 generation | u64 device_bytes | u64 meta_offset0 | u64
30//! meta_offset1 | u64 meta_region_bytes | u64 data_offset | u64 slot_stride | u64
31//! segment_bytes | u64 slot_count | u64 segment_count | u64 meta_len | u8 meta_slot |
32//! 7 zero bytes | meta_sha256[32] | u32 crc32c(preceding 160 bytes)`, where `meta_sha256
33//! = SHA-256("SYNAPSE_BLOCK_META_V1\0" || meta bytes)`.
34//!
35//! Durability (one `fdatasync` of the device per step; on a block device that is a
36//! FLUSH of the drive's volatile cache):
37//!
38//! * Metadata commit (the A2 "temp file, sync, rename, directory sync"): write the whole
39//! new namespace into the region no valid superblock copy points at, write superblock
40//! generation `g + 1` into copy `(g + 1) % 2`, `fdatasync`. Recovery takes the newest
41//! copy whose CRC holds and whose region matches its digest, else the older copy,
42//! whose region was not touched. One flush suffices because a superblock without its
43//! region is detected and skipped.
44//! * Segment rotation (the A2 "create, sync, directory flush"): zero the whole data area,
45//! `fdatasync`; write the slot header, `fdatasync`; then a superblock-only commit
46//! raises `segment_count`, `fdatasync`. Only then does a batch go into the slot. A slot
47//! past `segment_count` is never data: without a valid header its bytes are ignored
48//! (they may be stale from earlier use of the device) and the next rotation zeroes it.
49//! A valid header always sits on a zeroed slot, so slot `segment_count + 1` with a valid
50//! header and any non-zero byte means its commit was flushed and the superblock copy
51//! in use is older than the newest: mount refuses it (`CheckpointCorrupt`) rather than
52//! drop the changes acknowledged there.
53//! * Batch: one aligned positioned write plus one `fdatasync` (unchanged from A2).
54
55use super::*;
56
57pub mod repair;
58
59use std::os::unix::fs::{FileExt, FileTypeExt, MetadataExt, OpenOptionsExt};
60use std::sync::{Arc, Mutex};
61
62/// I/O block size: offsets, lengths and buffers of `O_DIRECT` transfers are multiples of it.
63pub const BLOCK: u64 = 4096;
64/// Superblock magic.
65pub const SUPERBLOCK_MAGIC: [u8; 8] = *b"SYNBLKS1";
66/// Superblock format version.
67pub const SUPERBLOCK_VERSION: u32 = 1;
68/// Label area at the start of the device: superblocks plus zeros. It covers the
69/// start-of-device offsets of the common signatures; [`classify_device`] also checks the
70/// ones further in and near the end of the device.
71pub const LABEL_BYTES: u64 = 128 * 1024;
72/// Segment header magic.
73pub const SEGMENT_HEADER_MAGIC: [u8; 4] = *b"SBSG";
74/// Metadata region magic.
75pub const META_MAGIC: [u8; 4] = *b"SBM1";
76/// Domain tag of the metadata digest.
77pub const DOMAIN_BLOCK_META: &[u8] = b"SYNAPSE_BLOCK_META_V1\0";
78/// Default size of each of the two metadata regions.
79pub const DEFAULT_META_REGION_BYTES: u64 = 64 << 20;
80/// Byte offset of metadata region 0.
81const META_START: u64 = 1 << 20;
82/// Bytes zeroed per write when a segment slot is cleared.
83const ZERO_CHUNK: usize = 1 << 20;
84const SB_LEN: usize = 164;
85
86const fn align_up(x: u64, a: u64) -> u64 {
87 x.div_ceil(a) * a
88}
89
90fn refuse(msg: impl Into<String>) -> SynapseError {
91 SynapseError::new(RefusalCode::IoFailure, msg.into())
92}
93
94fn corrupt(msg: impl Into<String>) -> SynapseError {
95 SynapseError::new(RefusalCode::CheckpointCorrupt, msg.into())
96}
97
98// --- device I/O ----------------------------------------------------------------
99
100/// Byte-addressed device I/O. Implementations may require nothing of the caller's
101/// alignment; [`DirectFile`] turns every call into aligned `O_DIRECT` transfers.
102pub trait BlockIo: Send + Sync + std::fmt::Debug {
103 /// Device length in bytes.
104 fn len(&self) -> u64;
105 /// True when the device has no bytes.
106 fn is_empty(&self) -> bool {
107 self.len() == 0
108 }
109 /// Read exactly `buf.len()` bytes at `off`.
110 fn read_at(&self, buf: &mut [u8], off: u64) -> std::io::Result<()>;
111 /// Write all of `data` at `off`. Not durable until [`BlockIo::flush`] returns.
112 fn write_at(&self, data: &[u8], off: u64) -> std::io::Result<()>;
113 /// Make every completed write durable (`fdatasync`).
114 fn flush(&self) -> std::io::Result<()>;
115}
116
117/// A heap buffer whose usable part starts at a [`BLOCK`]-aligned address (safe Rust:
118/// the start is found with `align_offset` inside an over-allocated `Vec`).
119struct AlignedBuf {
120 raw: Vec<u8>,
121 start: usize,
122 len: usize,
123}
124
125impl AlignedBuf {
126 fn zeroed(len: usize) -> Self {
127 let raw = vec![0u8; len + BLOCK as usize];
128 let start = raw.as_ptr().align_offset(BLOCK as usize);
129 assert!(start <= BLOCK as usize, "alignment offset out of range");
130 Self { raw, start, len }
131 }
132 fn as_slice(&self) -> &[u8] {
133 &self.raw[self.start..self.start + self.len]
134 }
135 fn as_mut_slice(&mut self) -> &mut [u8] {
136 &mut self.raw[self.start..self.start + self.len]
137 }
138}
139
140const O_DIRECT: i32 = libc::O_DIRECT;
141
142/// The device opened with `O_DIRECT`: a dedicated partition, or for tests and benchmarks a
143/// preallocated regular file. Unaligned requests are served through aligned bounce
144/// buffers (read-modify-write of the edge blocks for writes); the store's batch, zeroing,
145/// header and metadata writes are all block-aligned.
146#[derive(Debug)]
147pub struct DirectFile {
148 file: File,
149 len: u64,
150}
151
152impl DirectFile {
153 /// Open exactly `path` (absolute; a regular file or a block device, nothing else).
154 /// A block device is opened with `O_EXCL`, so the kernel refuses one that is mounted
155 /// or held by another opener. The opened file must be the one `path` named when it
156 /// was checked (same device and inode). The opened file is held under an exclusive
157 /// advisory lock (`flock`): a second opener is refused while this one lives.
158 pub fn open(path: &Path) -> SynapseResult<Self> {
159 Self::open_with(path, true, true)
160 }
161
162 /// Like [`Self::open`] but the file is opened read-only (still exclusive-locked):
163 /// every write through it fails. The diagnosis mode of the repair tool uses it.
164 pub fn open_read_only(path: &Path) -> SynapseResult<Self> {
165 Self::open_with(path, true, false)
166 }
167
168 /// Test inspection only: open without taking the lock (the A2 suite shim reads the
169 /// device while the store under test holds it).
170 #[cfg(test)]
171 pub(crate) fn open_unlocked(path: &Path) -> SynapseResult<Self> {
172 Self::open_with(path, false, true)
173 }
174
175 fn open_with(path: &Path, lock: bool, write: bool) -> SynapseResult<Self> {
176 if !path.is_absolute() {
177 return Err(refuse(format!(
178 "block device path must be absolute: {}",
179 path.display()
180 )));
181 }
182 // `symlink_metadata` plus `O_NOFOLLOW`: a symbolic link is refused, so the path
183 // opened is the configured one and never a link target.
184 let meta = fs::symlink_metadata(path)
185 .map_err(|e| refuse(format!("block device {}: {e}", path.display())))?;
186 let ft = meta.file_type();
187 let is_block = ft.is_block_device();
188 if !is_block && !ft.is_file() {
189 return Err(refuse(format!(
190 "{} is neither a block device nor a regular file (symbolic links are refused)",
191 path.display()
192 )));
193 }
194 let mut flags = O_DIRECT | libc::O_NOFOLLOW;
195 if is_block {
196 flags |= libc::O_EXCL;
197 }
198 let file = OpenOptions::new()
199 .read(true)
200 .write(write)
201 .custom_flags(flags)
202 .open(path)
203 .map_err(|e| refuse(format!("open {} with O_DIRECT: {e}", path.display())))?;
204 let opened = file.metadata().map_err(io_err)?;
205 if opened.dev() != meta.dev() || opened.ino() != meta.ino() || opened.rdev() != meta.rdev()
206 {
207 return Err(refuse(format!(
208 "{} changed between the check and the open",
209 path.display()
210 )));
211 }
212 // One opener at a time: an exclusive advisory lock (flock) on the opened file, on
213 // top of O_EXCL for block devices. A second store on the same device would
214 // overwrite the first one's slots and metadata.
215 match if lock { file.try_lock() } else { Ok(()) } {
216 Ok(()) => {}
217 Err(fs::TryLockError::WouldBlock) => {
218 return Err(refuse(format!(
219 "{} is in use: another opener holds its exclusive lock",
220 path.display()
221 )))
222 }
223 Err(fs::TryLockError::Error(e)) => {
224 return Err(refuse(format!("lock {}: {e}", path.display())))
225 }
226 }
227 let len = if is_block {
228 use std::io::Seek;
229 let mut f = &file;
230 f.seek(SeekFrom::End(0)).map_err(io_err)?
231 } else {
232 opened.len()
233 };
234 if len % BLOCK != 0 {
235 return Err(refuse(format!(
236 "{}: length {len} is not a multiple of {BLOCK}",
237 path.display()
238 )));
239 }
240 Ok(Self { file, len })
241 }
242}
243
244impl Drop for DirectFile {
245 fn drop(&mut self) {
246 // flock belongs to an open file description, which a helper briefly inherits
247 // between fork and exec. Release our advisory lock explicitly before close so
248 // that helper cannot retain it after this actual owner has gone away.
249 // Arc owners still keep this wrapper alive until its final drop.
250 let _ = self.file.unlock();
251 }
252}
253
254impl BlockIo for DirectFile {
255 fn len(&self) -> u64 {
256 self.len
257 }
258
259 fn read_at(&self, buf: &mut [u8], off: u64) -> std::io::Result<()> {
260 if buf.is_empty() {
261 return Ok(());
262 }
263 let end = off
264 .checked_add(buf.len() as u64)
265 .filter(|e| *e <= self.len)
266 .ok_or_else(|| std::io::Error::other("read past the end of the device"))?;
267 let a = off / BLOCK * BLOCK;
268 let b = align_up(end, BLOCK);
269 let mut bounce = AlignedBuf::zeroed((b - a) as usize);
270 self.file.read_exact_at(bounce.as_mut_slice(), a)?;
271 let at = (off - a) as usize;
272 buf.copy_from_slice(&bounce.as_slice()[at..at + buf.len()]);
273 Ok(())
274 }
275
276 fn write_at(&self, data: &[u8], off: u64) -> std::io::Result<()> {
277 if data.is_empty() {
278 return Ok(());
279 }
280 let end = off
281 .checked_add(data.len() as u64)
282 .filter(|e| *e <= self.len)
283 .ok_or_else(|| std::io::Error::other("write past the end of the device"))?;
284 let a = off / BLOCK * BLOCK;
285 let b = align_up(end, BLOCK);
286 let mut bounce = AlignedBuf::zeroed((b - a) as usize);
287 let s = bounce.as_mut_slice();
288 // Read-modify-write of partly covered edge blocks.
289 if off != a {
290 self.file.read_exact_at(&mut s[..BLOCK as usize], a)?;
291 }
292 if end != b && (b - BLOCK >= a + BLOCK || off == a) {
293 let last = s.len() - BLOCK as usize;
294 self.file.read_exact_at(&mut s[last..], b - BLOCK)?;
295 }
296 let at = (off - a) as usize;
297 s[at..at + data.len()].copy_from_slice(data);
298 self.file.write_all_at(bounce.as_slice(), a)
299 }
300
301 fn flush(&self) -> std::io::Result<()> {
302 self.file.sync_data()
303 }
304}
305
306// --- label classification -------------------------------------------------------
307
308/// What a device holds before Synapse touches it.
309#[derive(Debug, Clone, PartialEq, Eq)]
310pub enum DeviceLabel {
311 /// Every byte of the label area is zero and no known signature is anywhere.
312 Blank,
313 /// A Synapse superblock magic is present at byte 0 or 4096 (valid or not).
314 Synapse,
315 /// A recognised filesystem, partition table, or volume signature.
316 Foreign(&'static str),
317 /// Non-zero bytes in the label area that match no known signature.
318 Unknown,
319}
320
321/// Where a signature sits on a device of `len` bytes.
322#[derive(Debug, Clone, Copy, PartialEq, Eq)]
323pub enum SigAt {
324 /// Byte offset from the start.
325 Start(u64),
326 /// Bytes before the end.
327 End(u64),
328 /// Linux MD RAID 0.90 superblock: `(len & !(64 KiB - 1)) - 64 KiB`.
329 Md090,
330 /// Linux MD RAID 1.0 superblock: `(len - 8 KiB) & !(4 KiB - 1)`.
331 Md10,
332 /// ZFS vdev label `n` (L0 at 0, L1 at 256 KiB, L2 and L3 at 512 KiB and 256 KiB
333 /// below the length rounded down to 256 KiB): any 1 KiB uberblock slot of its
334 /// 128 KiB uberblock array (label offset 128 KiB).
335 ZfsLabel(u8),
336}
337
338/// One recognised signature.
339#[derive(Debug, Clone, Copy)]
340pub struct Signature {
341 pub name: &'static str,
342 pub at: SigAt,
343 pub magic: &'static [u8],
344}
345
346const fn sig(name: &'static str, at: SigAt, magic: &'static [u8]) -> Signature {
347 Signature { name, at, magic }
348}
349
350const MD_MAGIC: &[u8] = &[0xFC, 0x4E, 0x2B, 0xA9];
351const ZFS_UB_LE: &[u8] = &[0x0C, 0xB1, 0xBA, 0, 0, 0, 0, 0];
352const ZFS_UB_BE: &[u8] = &[0, 0, 0, 0, 0, 0xBA, 0xB1, 0x0C];
353const KIB: u64 = 1024;
354
355/// Every signature that makes a device foreign, in the order they are checked (the
356/// first match names the refusal). Each entry is pinned by its own test.
357pub const SIGNATURES: &[Signature] = &[
358 sig("GPT partition table", SigAt::Start(512), b"EFI PART"),
359 sig(
360 "GPT partition table (4 KiB sectors)",
361 SigAt::Start(4096),
362 b"EFI PART",
363 ),
364 sig("GPT backup header", SigAt::End(512), b"EFI PART"),
365 sig(
366 "GPT backup header (4 KiB sectors)",
367 SigAt::End(4096),
368 b"EFI PART",
369 ),
370 sig("ext2/ext3/ext4", SigAt::Start(1080), &[0x53, 0xEF]),
371 sig("XFS", SigAt::Start(0), b"XFSB"),
372 sig("btrfs", SigAt::Start(0x1_0040), b"_BHRfS_M"),
373 sig(
374 "btrfs (mirror at 64 MiB)",
375 SigAt::Start(0x400_0040),
376 b"_BHRfS_M",
377 ),
378 sig(
379 "btrfs (mirror at 256 GiB)",
380 SigAt::Start(0x40_0000_0040),
381 b"_BHRfS_M",
382 ),
383 sig("NTFS", SigAt::Start(3), b"NTFS "),
384 sig("exFAT", SigAt::Start(3), b"EXFAT "),
385 sig("FAT12/FAT16", SigAt::Start(54), b"FAT1"),
386 sig("FAT32", SigAt::Start(82), b"FAT32 "),
387 sig("LUKS", SigAt::Start(0), b"LUKS\xba\xbe"),
388 sig(
389 "LVM2 physical volume (sector 0)",
390 SigAt::Start(0),
391 b"LABELONE",
392 ),
393 sig(
394 "LVM2 physical volume (sector 1)",
395 SigAt::Start(512),
396 b"LABELONE",
397 ),
398 sig(
399 "LVM2 physical volume (sector 2)",
400 SigAt::Start(1024),
401 b"LABELONE",
402 ),
403 sig(
404 "LVM2 physical volume (sector 3)",
405 SigAt::Start(1536),
406 b"LABELONE",
407 ),
408 sig(
409 "Linux swap (4 KiB pages)",
410 SigAt::Start(4096 - 10),
411 b"SWAPSPACE2",
412 ),
413 sig(
414 "Linux swap, old (4 KiB pages)",
415 SigAt::Start(4096 - 10),
416 b"SWAP-SPACE",
417 ),
418 sig(
419 "Linux swap (16 KiB pages)",
420 SigAt::Start(16384 - 10),
421 b"SWAPSPACE2",
422 ),
423 sig(
424 "Linux swap (64 KiB pages)",
425 SigAt::Start(65536 - 10),
426 b"SWAPSPACE2",
427 ),
428 sig("ISO 9660", SigAt::Start(0x8001), b"CD001"),
429 sig("squashfs", SigAt::Start(0), b"hsqs"),
430 sig("F2FS", SigAt::Start(1024), &[0x10, 0x20, 0xF5, 0xF2]),
431 sig("Linux MD RAID (1.2)", SigAt::Start(4096), MD_MAGIC),
432 sig("Linux MD RAID (1.1)", SigAt::Start(0), MD_MAGIC),
433 sig("Linux MD RAID (1.0)", SigAt::Md10, MD_MAGIC),
434 sig("Linux MD RAID (0.90)", SigAt::Md090, MD_MAGIC),
435 sig("ZFS label L0", SigAt::ZfsLabel(0), ZFS_UB_LE),
436 sig("ZFS label L0 (big-endian)", SigAt::ZfsLabel(0), ZFS_UB_BE),
437 sig("ZFS label L1", SigAt::ZfsLabel(1), ZFS_UB_LE),
438 sig("ZFS label L1 (big-endian)", SigAt::ZfsLabel(1), ZFS_UB_BE),
439 sig("ZFS label L2", SigAt::ZfsLabel(2), ZFS_UB_LE),
440 sig("ZFS label L2 (big-endian)", SigAt::ZfsLabel(2), ZFS_UB_BE),
441 sig("ZFS label L3", SigAt::ZfsLabel(3), ZFS_UB_LE),
442 sig("ZFS label L3 (big-endian)", SigAt::ZfsLabel(3), ZFS_UB_BE),
443 sig("MBR or boot sector", SigAt::Start(510), &[0x55, 0xAA]),
444];
445
446impl Signature {
447 /// Whether this signature is on `io`.
448 pub fn found(&self, io: &dyn BlockIo) -> std::io::Result<bool> {
449 let len = io.len();
450 let n = self.magic.len() as u64;
451 let at = |off: Option<u64>| -> std::io::Result<bool> {
452 match off.filter(|o| o.checked_add(n).is_some_and(|e| e <= len)) {
453 Some(o) => {
454 let mut b = vec![0u8; n as usize];
455 io.read_at(&mut b, o)?;
456 Ok(b == self.magic)
457 }
458 None => Ok(false),
459 }
460 };
461 match self.at {
462 SigAt::Start(o) => at(Some(o)),
463 SigAt::End(b) => at(len.checked_sub(b)),
464 SigAt::Md090 => at((len & !(64 * KIB - 1)).checked_sub(64 * KIB)),
465 SigAt::Md10 => at(len.checked_sub(8 * KIB).map(|o| o & !(4 * KIB - 1))),
466 SigAt::ZfsLabel(l) => {
467 let end = len & !(256 * KIB - 1);
468 let base = match l {
469 0 => Some(0),
470 1 => Some(256 * KIB),
471 2 => end.checked_sub(512 * KIB),
472 _ => end.checked_sub(256 * KIB),
473 };
474 let Some(arr) = base.map(|b| b + 128 * KIB) else {
475 return Ok(false);
476 };
477 if arr + 128 * KIB > len {
478 return Ok(false);
479 }
480 let mut b = vec![0u8; (128 * KIB) as usize];
481 io.read_at(&mut b, arr)?;
482 Ok(b.chunks(KIB as usize).any(|s| s.starts_with(self.magic)))
483 }
484 }
485 }
486}
487
488/// Classify a device: its label area (the first [`LABEL_BYTES`]) and every
489/// [`SIGNATURES`] location, including the ones near the end of the device.
490pub fn classify_device(io: &dyn BlockIo) -> std::io::Result<DeviceLabel> {
491 let mut label = vec![0u8; LABEL_BYTES.min(io.len()) as usize];
492 io.read_at(&mut label, 0)?;
493 let at =
494 |off: usize| label.get(off..off + SUPERBLOCK_MAGIC.len()) == Some(&SUPERBLOCK_MAGIC[..]);
495 if at(0) || at(BLOCK as usize) {
496 return Ok(DeviceLabel::Synapse);
497 }
498 for s in SIGNATURES {
499 if s.found(io)? {
500 return Ok(DeviceLabel::Foreign(s.name));
501 }
502 }
503 Ok(if label.iter().all(|b| *b == 0) {
504 DeviceLabel::Blank
505 } else {
506 DeviceLabel::Unknown
507 })
508}
509
510// --- superblock -----------------------------------------------------------------
511
512/// Fixed geometry of a formatted device.
513#[derive(Debug, Clone, Copy, PartialEq, Eq)]
514pub struct Geometry {
515 pub uuid: [u8; 16],
516 pub device_bytes: u64,
517 pub meta_offset: [u64; 2],
518 pub meta_region_bytes: u64,
519 pub data_offset: u64,
520 pub slot_stride: u64,
521 pub segment_bytes: u64,
522 pub slot_count: u64,
523}
524
525impl Geometry {
526 fn new(
527 uuid: [u8; 16],
528 device_bytes: u64,
529 meta_region_bytes: u64,
530 segment_bytes: u64,
531 ) -> SynapseResult<Self> {
532 let meta_region_bytes = align_up(meta_region_bytes.max(BLOCK), BLOCK);
533 let segment_bytes = align_up(segment_bytes.max(BLOCK), BLOCK);
534 let meta_offset = [META_START, META_START + meta_region_bytes];
535 let data_offset = align_up(meta_offset[1] + meta_region_bytes, 1 << 20);
536 let slot_stride = BLOCK + segment_bytes;
537 let slot_count = device_bytes.saturating_sub(data_offset) / slot_stride;
538 if slot_count < 2 {
539 return Err(refuse(format!(
540 "device of {device_bytes} bytes holds {slot_count} segment slots of {segment_bytes} bytes after {data_offset} bytes of label and metadata; at least 2 are needed"
541 )));
542 }
543 Ok(Self {
544 uuid,
545 device_bytes,
546 meta_offset,
547 meta_region_bytes,
548 data_offset,
549 slot_stride,
550 segment_bytes,
551 slot_count,
552 })
553 }
554
555 /// Byte offset of slot `id`'s header (`1 <= id <= slot_count`).
556 pub fn slot_offset(&self, id: u64) -> u64 {
557 self.data_offset + (id - 1) * self.slot_stride
558 }
559}
560
561#[derive(Debug, Clone, PartialEq, Eq)]
562struct Superblock {
563 geo: Geometry,
564 generation: u64,
565 segment_count: u64,
566 meta_len: u64,
567 meta_slot: u8,
568 meta_sha256: [u8; 32],
569}
570
571fn meta_digest(bytes: &[u8]) -> [u8; 32] {
572 let mut h = Sha256::new();
573 h.update(DOMAIN_BLOCK_META);
574 h.update(bytes);
575 h.finalize().into()
576}
577
578impl Superblock {
579 fn encode(&self) -> Vec<u8> {
580 let g = &self.geo;
581 let mut b = Vec::with_capacity(BLOCK as usize);
582 b.extend_from_slice(&SUPERBLOCK_MAGIC);
583 b.extend_from_slice(&SUPERBLOCK_VERSION.to_le_bytes());
584 b.extend_from_slice(&(BLOCK as u32).to_le_bytes());
585 b.extend_from_slice(&g.uuid);
586 for v in [
587 self.generation,
588 g.device_bytes,
589 g.meta_offset[0],
590 g.meta_offset[1],
591 g.meta_region_bytes,
592 g.data_offset,
593 g.slot_stride,
594 g.segment_bytes,
595 g.slot_count,
596 self.segment_count,
597 self.meta_len,
598 ] {
599 b.extend_from_slice(&v.to_le_bytes());
600 }
601 b.push(self.meta_slot);
602 b.extend_from_slice(&[0u8; 7]);
603 b.extend_from_slice(&self.meta_sha256);
604 let crc = crc32c(&b);
605 b.extend_from_slice(&crc.to_le_bytes());
606 debug_assert_eq!(b.len(), SB_LEN);
607 b.resize(BLOCK as usize, 0);
608 b
609 }
610
611 /// Strict decoder; `None` for anything but a valid superblock.
612 fn decode(b: &[u8]) -> Option<Self> {
613 if b.len() < BLOCK as usize || b[0..8] != SUPERBLOCK_MAGIC {
614 return None;
615 }
616 let crc = u32::from_le_bytes(b[160..164].try_into().ok()?);
617 if crc32c(&b[..160]) != crc || b[SB_LEN..BLOCK as usize].iter().any(|x| *x != 0) {
618 return None;
619 }
620 let u32_at = |at: usize| u32::from_le_bytes(b[at..at + 4].try_into().expect("4"));
621 let u64_at = |at: usize| u64::from_le_bytes(b[at..at + 8].try_into().expect("8"));
622 if u32_at(8) != SUPERBLOCK_VERSION || u64::from(u32_at(12)) != BLOCK {
623 return None;
624 }
625 if b[121..128].iter().any(|x| *x != 0) || b[120] > 1 {
626 return None;
627 }
628 let uuid: [u8; 16] = b[16..32].try_into().ok()?;
629 let sb = Self {
630 geo: Geometry {
631 uuid,
632 device_bytes: u64_at(40),
633 meta_offset: [u64_at(48), u64_at(56)],
634 meta_region_bytes: u64_at(64),
635 data_offset: u64_at(72),
636 slot_stride: u64_at(80),
637 segment_bytes: u64_at(88),
638 slot_count: u64_at(96),
639 },
640 generation: u64_at(32),
641 segment_count: u64_at(104),
642 meta_len: u64_at(112),
643 meta_slot: b[120],
644 meta_sha256: b[128..160].try_into().ok()?,
645 };
646 // The geometry must be the one `Geometry::new` derives from its own inputs.
647 let expect = Geometry::new(
648 uuid,
649 sb.geo.device_bytes,
650 sb.geo.meta_region_bytes,
651 sb.geo.segment_bytes,
652 )
653 .ok()?;
654 if expect != sb.geo
655 || sb.meta_len > sb.geo.meta_region_bytes
656 || sb.segment_count > sb.geo.slot_count
657 || sb.generation == 0
658 {
659 return None;
660 }
661 Some(sb)
662 }
663}
664
665fn encode_meta(names: &BTreeMap<String, Vec<u8>>) -> Vec<u8> {
666 let mut b = Vec::new();
667 b.extend_from_slice(&META_MAGIC);
668 b.extend_from_slice(&(names.len() as u32).to_le_bytes());
669 for (name, bytes) in names {
670 b.extend_from_slice(&(name.len() as u16).to_le_bytes());
671 b.extend_from_slice(name.as_bytes());
672 b.extend_from_slice(&(bytes.len() as u64).to_le_bytes());
673 b.extend_from_slice(bytes);
674 }
675 b
676}
677
678fn decode_meta(b: &[u8]) -> Option<BTreeMap<String, Vec<u8>>> {
679 let take = |at: &mut usize, n: usize| -> Option<&[u8]> {
680 let s = b.get(*at..at.checked_add(n)?)?;
681 *at += n;
682 Some(s)
683 };
684 let mut at = 0usize;
685 if take(&mut at, 4)? != META_MAGIC {
686 return None;
687 }
688 let count = u32::from_le_bytes(take(&mut at, 4)?.try_into().ok()?);
689 let mut names = BTreeMap::new();
690 let mut prev: Option<String> = None;
691 for _ in 0..count {
692 let nl = u16::from_le_bytes(take(&mut at, 2)?.try_into().ok()?) as usize;
693 let name = std::str::from_utf8(take(&mut at, nl)?).ok()?.to_string();
694 if name.is_empty() || prev.as_ref().is_some_and(|p| *p >= name) {
695 return None;
696 }
697 let len = usize::try_from(u64::from_le_bytes(take(&mut at, 8)?.try_into().ok()?)).ok()?;
698 let bytes = take(&mut at, len)?.to_vec();
699 prev = Some(name.clone());
700 names.insert(name, bytes);
701 }
702 (at == b.len()).then_some(names)
703}
704
705fn segment_header(geo: &Geometry, id: u64) -> Vec<u8> {
706 let mut b = Vec::with_capacity(BLOCK as usize);
707 b.extend_from_slice(&SEGMENT_HEADER_MAGIC);
708 b.extend_from_slice(&1u32.to_le_bytes());
709 b.extend_from_slice(&geo.uuid);
710 b.extend_from_slice(&id.to_le_bytes());
711 b.extend_from_slice(&geo.segment_bytes.to_le_bytes());
712 let crc = crc32c(&b);
713 b.extend_from_slice(&crc.to_le_bytes());
714 b.resize(BLOCK as usize, 0);
715 b
716}
717
718// --- the device -------------------------------------------------------------------
719
720/// How [`BlockDevice::open`] treats a device without a Synapse superblock.
721#[derive(Debug, Clone, Copy, PartialEq, Eq)]
722pub enum FormatPolicy {
723 /// Open only a device that already holds a Synapse store.
724 OpenExisting,
725 /// Format a blank device (label area all zero); open an existing store as it is.
726 FormatIfBlank,
727}
728
729/// Where and how to open the raw block store.
730#[derive(Debug, Clone, PartialEq, Eq)]
731pub struct BlockDeviceConfig {
732 /// The one device path this store may open (absolute). Nothing else is opened.
733 pub path: PathBuf,
734 /// Treatment of a device without a Synapse superblock.
735 pub format: FormatPolicy,
736 /// Size of each of the two metadata regions, used when formatting.
737 pub meta_region_bytes: u64,
738 /// Format over a recognised filesystem/partition signature or other non-zero label
739 /// bytes. Destroys what was there; never set it for a device you have not checked.
740 pub allow_foreign_signature: bool,
741}
742
743impl BlockDeviceConfig {
744 /// Open the existing store at `path`: no formatting (set [`FormatPolicy::FormatIfBlank`]
745 /// to format a blank device deliberately), default metadata regions, no override.
746 pub fn new(path: impl Into<PathBuf>) -> Self {
747 Self {
748 path: path.into(),
749 format: FormatPolicy::OpenExisting,
750 meta_region_bytes: DEFAULT_META_REGION_BYTES,
751 allow_foreign_signature: false,
752 }
753 }
754}
755
756#[derive(Debug)]
757struct MetaState {
758 generation: u64,
759 meta_slot: u8,
760 segment_count: u64,
761 names: BTreeMap<String, Vec<u8>>,
762}
763
764/// An opened raw block store device: geometry, the committed metadata namespace and
765/// segment count, and the segment slots.
766#[derive(Debug)]
767pub struct BlockDevice {
768 io: Box<dyn BlockIo>,
769 geo: Geometry,
770 state: Mutex<MetaState>,
771}
772
773fn new_uuid(io: &dyn BlockIo) -> [u8; 16] {
774 let mut h = Sha256::new();
775 h.update(b"SYNAPSE_BLOCK_UUID_V1\0");
776 let now = std::time::SystemTime::now()
777 .duration_since(std::time::UNIX_EPOCH)
778 .map(|d| d.as_nanos())
779 .unwrap_or(0);
780 h.update(now.to_le_bytes());
781 h.update(std::process::id().to_le_bytes());
782 h.update(io.len().to_le_bytes());
783 let d: [u8; 32] = h.finalize().into();
784 d[..16].try_into().expect("16")
785}
786
787impl BlockDevice {
788 /// Open the device at `cfg.path` with `O_DIRECT`. `segment_bytes` is used only when
789 /// a blank device is formatted; an existing store keeps its own.
790 pub fn open_path(cfg: &BlockDeviceConfig, segment_bytes: u64) -> SynapseResult<Arc<Self>> {
791 let io = DirectFile::open(&cfg.path)?;
792 Self::open(Box::new(io), cfg, segment_bytes)
793 }
794
795 /// Test inspection only: [`Self::open_path`] without the exclusive lock.
796 #[cfg(test)]
797 pub(crate) fn open_path_unlocked(cfg: &BlockDeviceConfig) -> SynapseResult<Arc<Self>> {
798 let io = DirectFile::open_unlocked(&cfg.path)?;
799 Self::open(Box::new(io), cfg, 0)
800 }
801
802 /// Open (or format, per `cfg`) the store on `io`.
803 pub fn open(
804 io: Box<dyn BlockIo>,
805 cfg: &BlockDeviceConfig,
806 segment_bytes: u64,
807 ) -> SynapseResult<Arc<Self>> {
808 if io.len() < LABEL_BYTES {
809 return Err(refuse(format!(
810 "device of {} bytes is smaller than the label area",
811 io.len()
812 )));
813 }
814 match classify_device(io.as_ref()).map_err(io_err)? {
815 DeviceLabel::Synapse => {}
816 DeviceLabel::Blank if cfg.format == FormatPolicy::FormatIfBlank => {
817 Self::format(io.as_ref(), cfg.meta_region_bytes, segment_bytes)?;
818 }
819 DeviceLabel::Blank => {
820 return Err(refuse(format!(
821 "{} is blank and the format policy is OpenExisting",
822 cfg.path.display()
823 )))
824 }
825 other if cfg.allow_foreign_signature && cfg.format == FormatPolicy::FormatIfBlank => {
826 let _ = other;
827 Self::format(io.as_ref(), cfg.meta_region_bytes, segment_bytes)?;
828 }
829 DeviceLabel::Foreign(what) => {
830 return Err(refuse(format!(
831 "refusing {}: it carries a {what} signature (set allow_foreign_signature to format over it)",
832 cfg.path.display()
833 )))
834 }
835 DeviceLabel::Unknown => {
836 return Err(refuse(format!(
837 "refusing {}: its first {LABEL_BYTES} bytes are not blank and hold no Synapse superblock (set allow_foreign_signature to format over them)",
838 cfg.path.display()
839 )))
840 }
841 }
842 Self::mount(io)
843 }
844
845 /// Write a new, empty store: zero the label area, write an empty namespace into
846 /// metadata region 0 and superblock generation 1, `fdatasync`.
847 fn format(io: &dyn BlockIo, meta_region_bytes: u64, segment_bytes: u64) -> SynapseResult<()> {
848 let geo = Geometry::new(new_uuid(io), io.len(), meta_region_bytes, segment_bytes)?;
849 let meta = encode_meta(&BTreeMap::new());
850 let sb = Superblock {
851 geo,
852 generation: 1,
853 segment_count: 0,
854 meta_len: meta.len() as u64,
855 meta_slot: 0,
856 meta_sha256: meta_digest(&meta),
857 };
858 let mut label = vec![0u8; LABEL_BYTES as usize];
859 label[BLOCK as usize..2 * BLOCK as usize].copy_from_slice(&sb.encode());
860 let mut region = meta;
861 region.resize(align_up(region.len() as u64, BLOCK) as usize, 0);
862 io.write_at(&region, geo.meta_offset[0]).map_err(io_err)?;
863 io.write_at(&label, 0).map_err(io_err)?;
864 io.flush().map_err(io_err)
865 }
866
867 /// Recover the committed state: the newest superblock copy whose CRC holds and whose
868 /// metadata region matches its digest, else the older copy.
869 fn mount(io: Box<dyn BlockIo>) -> SynapseResult<Arc<Self>> {
870 let mut copies = Vec::new();
871 for i in 0..2u64 {
872 let mut b = vec![0u8; BLOCK as usize];
873 io.read_at(&mut b, i * BLOCK).map_err(io_err)?;
874 if let Some(sb) = Superblock::decode(&b) {
875 if sb.generation % 2 == i {
876 copies.push(sb);
877 }
878 }
879 }
880 copies.sort_by_key(|sb| std::cmp::Reverse(sb.generation));
881 if copies.len() == 2 && copies[0].geo != copies[1].geo {
882 return Err(corrupt(
883 "the two superblock copies disagree on the geometry",
884 ));
885 }
886 for sb in copies {
887 if sb.geo.device_bytes > io.len() {
888 return Err(corrupt(format!(
889 "superblock describes {} bytes, device has {}",
890 sb.geo.device_bytes,
891 io.len()
892 )));
893 }
894 let mut meta = vec![0u8; sb.meta_len as usize];
895 io.read_at(&mut meta, sb.geo.meta_offset[sb.meta_slot as usize])
896 .map_err(io_err)?;
897 if meta_digest(&meta) != sb.meta_sha256 {
898 continue;
899 }
900 let Some(names) = decode_meta(&meta) else {
901 continue;
902 };
903 // A repair log that does not verify is never skipped: falling back to the
904 // older copy would hide a repair (or a forged one).
905 if let Some(log) = names.get(repair::REPAIR_LOG_NAME) {
906 repair::verify_repair_log(log, &sb.geo.uuid)?;
907 }
908 let dev = Self {
909 io,
910 geo: sb.geo,
911 state: Mutex::new(MetaState {
912 generation: sb.generation,
913 meta_slot: sb.meta_slot,
914 segment_count: sb.segment_count,
915 names,
916 }),
917 };
918 dev.refuse_data_past_segment_count()?;
919 return Ok(Arc::new(dev));
920 }
921 Err(corrupt(
922 "no superblock copy with an intact metadata region (the device carries the Synapse magic but no valid store)",
923 ))
924 }
925
926 /// Refuse a mount whose segment count is behind the data on the device. Slot
927 /// `segment_count + 1` can hold a non-zero byte only after the commit that raised the
928 /// count to it was flushed (a rotation zeroes the slot and flushes before that
929 /// commit, and no batch goes in before it). So a valid header there with data means
930 /// the newest superblock copy was lost (damaged) and the copy in use is older:
931 /// mounting it would silently drop every change acknowledged in that slot.
932 fn refuse_data_past_segment_count(&self) -> SynapseResult<()> {
933 let next = self.lock().segment_count + 1;
934 if !self.header_valid(next).map_err(io_err)? {
935 return Ok(());
936 }
937 let start = self.data_offset(next);
938 let mut buf = vec![0u8; (ZERO_CHUNK as u64).min(self.geo.segment_bytes) as usize];
939 let mut at = 0;
940 while at < self.geo.segment_bytes {
941 let n = buf.len().min((self.geo.segment_bytes - at) as usize);
942 self.io.read_at(&mut buf[..n], start + at).map_err(io_err)?;
943 if buf[..n].iter().any(|b| *b != 0) {
944 return Err(corrupt(format!(
945 "segment slot {next} holds data past the committed segment count {}: the \
946 newest superblock copy is damaged and the older copy would drop \
947 acknowledged changes",
948 next - 1
949 )));
950 }
951 at += n as u64;
952 }
953 Ok(())
954 }
955
956 fn lock(&self) -> std::sync::MutexGuard<'_, MetaState> {
957 self.state.lock().unwrap_or_else(|p| p.into_inner())
958 }
959
960 /// The device geometry.
961 pub fn geometry(&self) -> Geometry {
962 self.geo
963 }
964
965 /// Committed segment count (segments `1..=count` may hold data).
966 pub fn segment_count(&self) -> u64 {
967 self.lock().segment_count
968 }
969
970 /// Metadata region the superblock in force points at.
971 #[cfg(test)]
972 pub(crate) fn meta_slot(&self) -> u8 {
973 self.lock().meta_slot
974 }
975
976 /// Commit generation of the superblock in force.
977 pub fn generation(&self) -> u64 {
978 self.lock().generation
979 }
980
981 /// `fdatasync` the device.
982 pub fn flush(&self) -> std::io::Result<()> {
983 self.io.flush()
984 }
985
986 /// Write a new superblock generation (and, with `names`, a new metadata region),
987 /// then `fdatasync`. On failure the in-memory state is unchanged.
988 fn commit(
989 &self,
990 st: &mut MetaState,
991 names: Option<BTreeMap<String, Vec<u8>>>,
992 segment_count: u64,
993 ) -> std::io::Result<()> {
994 let generation = st.generation + 1;
995 let (meta_slot, meta) = match &names {
996 Some(n) => (1 - st.meta_slot, encode_meta(n)),
997 None => (st.meta_slot, encode_meta(&st.names)),
998 };
999 if meta.len() as u64 > self.geo.meta_region_bytes {
1000 return Err(std::io::Error::other(format!(
1001 "metadata of {} bytes does not fit the {}-byte metadata region",
1002 meta.len(),
1003 self.geo.meta_region_bytes
1004 )));
1005 }
1006 if names.is_some() {
1007 let mut region = meta.clone();
1008 region.resize(align_up(region.len() as u64, BLOCK) as usize, 0);
1009 self.io
1010 .write_at(&region, self.geo.meta_offset[meta_slot as usize])?;
1011 }
1012 let sb = Superblock {
1013 geo: self.geo,
1014 generation,
1015 segment_count,
1016 meta_len: meta.len() as u64,
1017 meta_slot,
1018 meta_sha256: meta_digest(&meta),
1019 };
1020 self.io.write_at(&sb.encode(), (generation % 2) * BLOCK)?;
1021 self.io.flush()?;
1022 st.generation = generation;
1023 st.meta_slot = meta_slot;
1024 st.segment_count = segment_count;
1025 if let Some(n) = names {
1026 st.names = n;
1027 }
1028 Ok(())
1029 }
1030
1031 // --- named objects (the A2 store's small files) ---
1032
1033 /// Bytes of named object `name`, if present.
1034 pub fn read_named(&self, name: &str) -> Option<Vec<u8>> {
1035 self.lock().names.get(name).cloned()
1036 }
1037
1038 /// Names of every object, ascending.
1039 pub fn list_named(&self) -> Vec<String> {
1040 self.lock().names.keys().cloned().collect()
1041 }
1042
1043 /// Atomically create or replace `name` (one metadata commit).
1044 pub fn write_named(&self, name: &str, bytes: &[u8]) -> std::io::Result<()> {
1045 if name.is_empty() || name.len() > usize::from(u16::MAX) {
1046 return Err(std::io::Error::other("invalid object name"));
1047 }
1048 let mut st = self.lock();
1049 let mut names = st.names.clone();
1050 names.insert(name.to_string(), bytes.to_vec());
1051 let count = st.segment_count;
1052 self.commit(&mut st, Some(names), count)
1053 }
1054
1055 /// Atomically remove every object whose name satisfies `pred` (one metadata commit,
1056 /// none when nothing matches). Returns whether anything was removed.
1057 pub fn remove_named_where(&self, pred: impl Fn(&str) -> bool) -> std::io::Result<bool> {
1058 let mut st = self.lock();
1059 let mut names = st.names.clone();
1060 names.retain(|n, _| !pred(n));
1061 if names.len() == st.names.len() {
1062 return Ok(false);
1063 }
1064 let count = st.segment_count;
1065 self.commit(&mut st, Some(names), count)?;
1066 Ok(true)
1067 }
1068
1069 // --- segment slots ---
1070
1071 fn check_slot(&self, id: u64) -> std::io::Result<()> {
1072 if id == 0 || id > self.geo.slot_count {
1073 return Err(std::io::Error::other(format!(
1074 "no segment slot {id}: the device has {} slots (device full)",
1075 self.geo.slot_count
1076 )));
1077 }
1078 Ok(())
1079 }
1080
1081 fn data_offset(&self, id: u64) -> u64 {
1082 self.geo.slot_offset(id) + BLOCK
1083 }
1084
1085 /// True when slot `id` carries this store's header for segment `id`.
1086 pub fn header_valid(&self, id: u64) -> std::io::Result<bool> {
1087 if id == 0 || id > self.geo.slot_count {
1088 return Ok(false);
1089 }
1090 let mut b = vec![0u8; BLOCK as usize];
1091 self.io.read_at(&mut b, self.geo.slot_offset(id))?;
1092 Ok(b == segment_header(&self.geo, id))
1093 }
1094
1095 /// Segment ids present: slots `1..=count` with a valid header, plus slot `count + 1`
1096 /// when it carries a header (created by a rotation that never committed). A missing
1097 /// id inside `1..=count` is reported by recovery as a gap.
1098 pub fn list_segments(&self) -> std::io::Result<Vec<u64>> {
1099 let count = self.segment_count();
1100 let mut ids = Vec::new();
1101 for id in 1..=count + 1 {
1102 if self.header_valid(id)? {
1103 ids.push(id);
1104 }
1105 }
1106 Ok(ids)
1107 }
1108
1109 /// Segment `id`'s data from byte `from` on. A slot past the committed count is never
1110 /// data: it reads back empty.
1111 pub fn read_segment(&self, id: u64, from: u64) -> std::io::Result<Vec<u8>> {
1112 if id > self.segment_count() || from >= self.geo.segment_bytes {
1113 return Ok(Vec::new());
1114 }
1115 self.check_slot(id)?;
1116 let mut b = vec![0u8; (self.geo.segment_bytes - from) as usize];
1117 self.io.read_at(&mut b, self.data_offset(id) + from)?;
1118 Ok(b)
1119 }
1120
1121 /// Read `len` bytes at `offset` of segment `id` (blob reads).
1122 pub fn read_segment_at(&self, id: u64, offset: u64, len: u32) -> std::io::Result<Vec<u8>> {
1123 self.check_slot(id)?;
1124 if offset + u64::from(len) > self.geo.segment_bytes {
1125 return Err(std::io::Error::other("read past the end of the segment"));
1126 }
1127 let mut b = vec![0u8; len as usize];
1128 self.io.read_at(&mut b, self.data_offset(id) + offset)?;
1129 Ok(b)
1130 }
1131
1132 /// Write `data` at `offset` of segment `id` (not durable until [`Self::flush`]).
1133 pub fn write_segment(&self, id: u64, offset: u64, data: &[u8]) -> std::io::Result<()> {
1134 self.check_slot(id)?;
1135 if offset + data.len() as u64 > self.geo.segment_bytes {
1136 return Err(std::io::Error::other(format!(
1137 "write of {} bytes at {offset} does not fit the {}-byte segment slot",
1138 data.len(),
1139 self.geo.segment_bytes
1140 )));
1141 }
1142 self.io.write_at(data, self.data_offset(id) + offset)
1143 }
1144
1145 /// Rotation step 2: write slot `id`'s header (not yet durable; the caller flushes).
1146 pub fn write_segment_header(&self, id: u64) -> std::io::Result<()> {
1147 self.check_slot(id)?;
1148 self.io
1149 .write_at(&segment_header(&self.geo, id), self.geo.slot_offset(id))
1150 }
1151
1152 /// Rotation step 1: zero slot `id`'s whole data area, then `fdatasync`.
1153 pub fn zero_segment(&self, id: u64) -> std::io::Result<()> {
1154 self.check_slot(id)?;
1155 let zeros = vec![0u8; ZERO_CHUNK];
1156 let mut at = 0u64;
1157 while at < self.geo.segment_bytes {
1158 let n = ((self.geo.segment_bytes - at) as usize).min(ZERO_CHUNK);
1159 self.io.write_at(&zeros[..n], self.data_offset(id) + at)?;
1160 at += n as u64;
1161 }
1162 self.io.flush()
1163 }
1164
1165 /// Rotation step 3 (the directory flush): commit `segment_count = id`. Only the next
1166 /// segment can be committed.
1167 pub fn commit_segment(&self, id: u64) -> std::io::Result<()> {
1168 let mut st = self.lock();
1169 if st.segment_count >= id {
1170 return Ok(());
1171 }
1172 if id != st.segment_count + 1 {
1173 return Err(std::io::Error::other(format!(
1174 "segment {id} cannot follow committed segment {}",
1175 st.segment_count
1176 )));
1177 }
1178 self.commit(&mut st, None, id)
1179 }
1180
1181 /// Zero bytes `from..to` of segment `id`, then `fdatasync` (torn-tail truncation).
1182 pub fn zero_segment_range(&self, id: u64, from: u64, to: u64) -> std::io::Result<()> {
1183 if to > from {
1184 self.write_segment(id, from, &vec![0u8; (to - from) as usize])?;
1185 }
1186 self.io.flush()
1187 }
1188
1189 /// Erase slot `id`'s header (test view: a lost segment file).
1190 #[cfg(test)]
1191 pub(crate) fn erase_segment_header(&self, id: u64) -> std::io::Result<()> {
1192 self.check_slot(id)?;
1193 self.io
1194 .write_at(&vec![0u8; BLOCK as usize], self.geo.slot_offset(id))?;
1195 self.io.flush()
1196 }
1197}
1198
1199/// The segment medium of a store: a directory of files (A2) or a raw block device (R1).
1200#[derive(Debug, Clone)]
1201pub(crate) enum Medium {
1202 Dir(PathBuf),
1203 Block(Arc<BlockDevice>),
1204}
1205
1206impl Medium {
1207 pub fn exists(&self, name: &str) -> bool {
1208 match self {
1209 Medium::Dir(root) => root.join(name).exists(),
1210 Medium::Block(dev) => dev.read_named(name).is_some(),
1211 }
1212 }
1213
1214 pub fn read(&self, name: &str) -> std::io::Result<Vec<u8>> {
1215 match self {
1216 Medium::Dir(root) => fs::read(root.join(name)),
1217 Medium::Block(dev) => dev.read_named(name).ok_or_else(|| {
1218 std::io::Error::new(std::io::ErrorKind::NotFound, format!("no object {name}"))
1219 }),
1220 }
1221 }
1222
1223 /// Atomically create or replace `name` (A2: `<name>.tmp`, sync, rename, directory
1224 /// sync; R1: one metadata commit).
1225 pub fn write_atomic(&self, name: &str, bytes: &[u8]) -> SynapseResult<()> {
1226 match self {
1227 Medium::Dir(root) => write_file_atomic(
1228 root,
1229 &root.join(format!("{name}.tmp")),
1230 &root.join(name),
1231 bytes,
1232 ),
1233 Medium::Block(dev) => dev.write_named(name, bytes).map_err(io_err),
1234 }
1235 }
1236
1237 pub fn list_segments(&self) -> SynapseResult<Vec<u64>> {
1238 match self {
1239 Medium::Dir(root) => segment::list_segments(root),
1240 Medium::Block(dev) => dev.list_segments().map_err(io_err),
1241 }
1242 }
1243
1244 /// True when segment `id` exists and holds a non-zero byte.
1245 pub fn segment_has_data(&self, id: u64) -> SynapseResult<bool> {
1246 match self {
1247 Medium::Dir(root) => match fs::read(root.join(segment::segment_file_name(id))) {
1248 Ok(b) => Ok(b.iter().any(|x| *x != 0)),
1249 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(false),
1250 Err(e) => Err(io_err(e)),
1251 },
1252 Medium::Block(dev) => Ok(dev
1253 .read_segment(id, 0)
1254 .map_err(io_err)?
1255 .iter()
1256 .any(|x| *x != 0)),
1257 }
1258 }
1259
1260 /// Segment `id` from byte `base` on; `None` when the segment does not exist.
1261 pub fn read_segment_from(&self, id: u64, base: u64) -> SynapseResult<Option<Vec<u8>>> {
1262 match self {
1263 Medium::Dir(root) => {
1264 let path = root.join(segment::segment_file_name(id));
1265 if !path.exists() {
1266 return Ok(None);
1267 }
1268 let mut f = File::open(&path).map_err(io_err)?;
1269 f.seek(SeekFrom::Start(base)).map_err(io_err)?;
1270 let mut b = Vec::new();
1271 f.read_to_end(&mut b).map_err(io_err)?;
1272 Ok(Some(b))
1273 }
1274 Medium::Block(dev) => {
1275 if !dev.header_valid(id).map_err(io_err)? {
1276 return Ok(None);
1277 }
1278 Ok(Some(dev.read_segment(id, base).map_err(io_err)?))
1279 }
1280 }
1281 }
1282
1283 /// Zero bytes `from..to` of segment `id` and `fdatasync` it (torn-tail truncation).
1284 pub fn zero_segment_range(&self, id: u64, from: u64, to: u64) -> SynapseResult<()> {
1285 match self {
1286 Medium::Dir(root) => {
1287 let f = OpenOptions::new()
1288 .write(true)
1289 .open(root.join(segment::segment_file_name(id)))
1290 .map_err(io_err)?;
1291 f.write_all_at(&vec![0u8; (to - from) as usize], from)
1292 .map_err(io_err)?;
1293 f.sync_data().map_err(io_err)
1294 }
1295 Medium::Block(dev) => dev.zero_segment_range(id, from, to).map_err(io_err),
1296 }
1297 }
1298
1299 /// A read handle on segment `id` (`NotFound` when it does not exist or, on a
1300 /// device, is not committed).
1301 pub fn open_reader(&self, id: u64) -> std::io::Result<segment::SegReader> {
1302 match self {
1303 Medium::Dir(root) => {
1304 File::open(root.join(segment::segment_file_name(id))).map(segment::SegReader::File)
1305 }
1306 Medium::Block(dev) => {
1307 if id <= dev.segment_count() && dev.header_valid(id)? {
1308 Ok(segment::SegReader::Block(dev.clone(), id))
1309 } else {
1310 Err(std::io::Error::new(
1311 std::io::ErrorKind::NotFound,
1312 format!("segment {id} is not on the device"),
1313 ))
1314 }
1315 }
1316 }
1317 }
1318
1319 /// Flush the namespace (A2: `fsync` the store directory; R1: every metadata commit
1320 /// is already durable, so nothing is left to do).
1321 pub fn sync_namespace(&self) -> SynapseResult<()> {
1322 match self {
1323 Medium::Dir(root) => sync_dir(root),
1324 Medium::Block(_) => Ok(()),
1325 }
1326 }
1327}