//! Shutdown flush orchestration over an owned storage backend. //! //! Unlike the state model, callers cannot supply completion counts/digests. //! The coordinator issues writes and barriers itself and advances only after //! the backend returns completion. A native driver must implement the trait //! using real queue completions; host fixtures do not establish guest I/O. use crate::{flush, quiesce::QuiesceGate}; pub type Block = [u8; 512]; pub const MAX_BLOCKS_PER_STAGE: usize = 64; #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum IoError { Eio, Timeout } pub trait Storage { fn capacity_sectors(&self) -> u64; /// Return Ok only after this exact request's device completion. fn write_sector(&mut self, lba: u64, data: &Block) -> Result<(), IoError>; /// Return Ok only after a negotiated FLUSH command completes successfully. /// On timeout the driver must retain live DMA ownership until safe reset. fn flush(&mut self) -> Result<(), IoError>; } pub struct Write<'a> { pub lba: u64, pub data: &'a Block } pub struct Plan<'a> { pub data: &'a [Write<'a>], pub metadata: &'a [Write<'a>], pub journal: &'a [Write<'a>], pub journal_sequence: u64, } #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Operation { Validate, Write, Flush, Admit } #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Error { NotQuiesced, InvalidPlan, AlreadyAttempted, Storage { stage: flush::Stage, operation: Operation, error: IoError }, Model(flush::Error), } #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct Progress { pub completed_writes: u32, pub completed_flushes: u8, pub stage: flush::Stage, pub operation: Operation, pub error: Option, pub clean: bool, } // Private fields and no Clone: only this coordinator can issue a receipt. #[derive(Debug)] pub struct Receipt { status: flush::Status, progress: Progress } impl Receipt { pub const fn status(&self) -> flush::Status { self.status } pub const fn progress(&self) -> Progress { self.progress } } pub struct Flusher<'a, B: Storage> { backend: &'a mut B, attempted: bool, progress: Progress, } impl<'a, B: Storage> Flusher<'a, B> { pub fn new(backend: &'a mut B) -> Self { Self { backend, attempted: false, progress: Progress { completed_writes: 0, completed_flushes: 0, stage: flush::Stage::None, operation: Operation::Validate, error: None, clean: false, }} } pub const fn progress(&self) -> Progress { self.progress } pub fn run(&mut self, gate: &QuiesceGate, plan: &Plan<'_>) -> Result { // A failed or successful transaction cannot be silently retried using // the same coordinator. Driver recovery requires a separate owner. if self.attempted { return Err(Error::AlreadyAttempted); } self.attempted = true; let result = self.run_once(gate, plan); if let Err(error) = result { self.progress.error = Some(error); } result } fn run_once(&mut self, gate: &QuiesceGate, plan: &Plan<'_>) -> Result { gate.require_quiesced().map_err(|_| Error::NotQuiesced)?; let stages = [plan.data, plan.metadata, plan.journal]; if plan.journal_sequence == 0 || stages.iter().any(|s| s.is_empty() || s.len() > MAX_BLOCKS_PER_STAGE) { return Err(Error::InvalidPlan); } let capacity = self.backend.capacity_sectors(); // Validate the entire plan before any write. Cross-stage aliases could // overwrite a previously flushed data/metadata block with journal data. for (i, write) in stages.iter().flat_map(|s| s.iter()).enumerate() { if write.lba >= capacity || stages.iter().flat_map(|s| s.iter()).take(i).any(|prior| prior.lba == write.lba) { return Err(Error::InvalidPlan); } } let mut model = flush::FlushCoordinator::new(true).map_err(Error::Model)?; for (stage, writes) in [(flush::Stage::Data, plan.data), (flush::Stage::Metadata, plan.metadata), (flush::Stage::Journal, plan.journal)] { self.progress.stage = stage; let mut digest = 0xcbf29ce484222325u64; for write in writes { self.progress.operation = Operation::Write; self.backend.write_sector(write.lba, write.data).map_err(|error| Error::Storage { stage, operation: Operation::Write, error })?; self.progress.completed_writes += 1; // A deterministic record checksum, not an authenticity claim. for byte in write.lba.to_le_bytes().iter().chain(write.data.iter()) { digest = (digest ^ u64::from(*byte)).wrapping_mul(0x100000001b3); } } self.progress.operation = Operation::Flush; self.backend.flush().map_err(|error| Error::Storage { stage, operation: Operation::Flush, error })?; self.progress.completed_flushes += 1; match stage { flush::Stage::Data => model.flush_data(writes.len() as u32, digest), flush::Stage::Metadata => model.flush_metadata(writes.len() as u32, digest), flush::Stage::Journal => model.flush_journal(plan.journal_sequence, digest), flush::Stage::None => unreachable!(), }.map_err(Error::Model)?; } self.progress.operation = Operation::Admit; let status = model.claim_clean_shutdown(false).map_err(Error::Model)?; self.progress.clean = true; Ok(Receipt { status, progress: self.progress }) } }