diff --git a/crates/stela-boot/src/engine/storage.rs b/crates/stela-boot/src/engine/storage.rs index 35f9ddb5fc..1b191666cb 100644 --- a/crates/stela-boot/src/engine/storage.rs +++ b/crates/stela-boot/src/engine/storage.rs @@ -697,6 +697,8 @@ impl Service { result: Result, ) -> Result { if let Err(error) = &result { + // What the USB storage recovery did for it comes first. + report_usb_recoveries(); self.failures += 1; if self.failures <= 16 || self.failures.is_power_of_two() { output::arguments(format_args!( @@ -710,6 +712,21 @@ impl Service { } } +/// One line per USB storage command the recovery ladder ran for since the +/// last call (`stela_drivers::usb::storage::take_recoveries`): what failed +/// it, the furthest step that ran, and whether it completed. +fn report_usb_recoveries() { + let (recoveries, replaced) = stela_drivers::usb::storage::take_recoveries(); + for recovery in &recoveries { + output::arguments(format_args!("HOST USB DISK RECOVERY {recovery}\n")); + } + if replaced != 0 { + output::arguments(format_args!( + "HOST USB DISK RECOVERY {replaced} more commands recovered or failed since the last report\n" + )); + } +} + impl Service { /// A call `call` of this disk for `command`, begun at counter `since`, /// has ended: one that held its processor over 50 ms is named once a @@ -1597,6 +1614,7 @@ impl HostDisks { Self::report_callback(serial, callbacks, tsc_hz, "periodic"); } } + report_usb_recoveries(); let refused = stela_drivers::usb::storage::take_cache_refusals(); if refused != 0 { output::arguments(format_args!( diff --git a/crates/stela-drivers/src/usb/storage.rs b/crates/stela-drivers/src/usb/storage.rs index a75ea27ed8..4aa349b649 100644 --- a/crates/stela-drivers/src/usb/storage.rs +++ b/crates/stela-drivers/src/usb/storage.rs @@ -25,6 +25,8 @@ use stela_driver_base::stepped::block_on; mod media; pub use media::UsbStorage; mod bot; +mod recovery; +pub use recovery::{Cause, End, Recovery, Step, take_recoveries}; mod scsi; pub mod uas; use bot::{Bot, Io, Native}; diff --git a/crates/stela-drivers/src/usb/storage/bot.rs b/crates/stela-drivers/src/usb/storage/bot.rs index eac108d7db..0948bf39f9 100644 --- a/crates/stela-drivers/src/usb/storage/bot.rs +++ b/crates/stela-drivers/src/usb/storage/bot.rs @@ -41,7 +41,8 @@ const RESET_RECOVERY_US: u64 = 6_000_000; const MAX_LUN: u8 = 15; /// xHCI completion code 22: the slot must be retired, not cancelled. const INCOMPATIBLE_DEVICE: u32 = 22; -const PROTOCOL_ERROR: BlockError = BlockError::Protocol("malformed Bulk-Only wrapper or transfer"); +pub(super) const PROTOCOL_ERROR: BlockError = + BlockError::Protocol("malformed Bulk-Only wrapper or transfer"); const SHORT_WRITE: BlockError = BlockError::Protocol("short Bulk-Only write"); pub(super) fn supported(device: &Device) -> Result<(), &'static str> { diff --git a/crates/stela-drivers/src/usb/storage/bot/tests.rs b/crates/stela-drivers/src/usb/storage/bot/tests.rs index e75cd50f4d..af9f685830 100644 --- a/crates/stela-drivers/src/usb/storage/bot/tests.rs +++ b/crates/stela-drivers/src/usb/storage/bot/tests.rs @@ -1460,15 +1460,15 @@ fn synchronous_read_keeps_full_recovered_data_across_autosense() { "the class reset ends the read, not the disk" ); assert_eq!(state.borrow().sense_polls, Some(18)); + // The wrapper error resets the class each time and the read runs again + // within sd's retries, as Linux requeues a DID_ERROR command. + let mut expected = vec![(1, scsi::READ_10), (1, scsi::REQUEST_SENSE)]; + expected.extend([(1, scsi::READ_10); 6]); assert!( state.borrow().history[first..] .iter() .map(|(lun, _, cdb)| (*lun, cdb[0])) - .eq([ - (1, scsi::READ_10), - (1, scsi::REQUEST_SENSE), - (1, scsi::READ_10) - ]) + .eq(expected) ); } @@ -2070,22 +2070,21 @@ fn an_owned_begun_command_is_retried_as_a_waiting_one_is() { .find_map(|_| disk.finish(tag)) .expect("a begun command ended") }; - // A class reset ends one command; the device's UNIT ATTENTION after it - // is retried once. + // A phase error's class reset settles before the read runs again, as + // Linux requeues a DID_ERROR command; the device's UNIT ATTENTION + // after the reset is retried once. // (A flush would send nothing: the unit reports no write cache.) state.borrow_mut().fault = Fault::Phase; let tag = disks[1] .start(Command::Read { lba: 0, bytes: 512 }) .unwrap(); - assert!(finish(&mut disks[1], tag).is_err()); + assert!((0..64).all(|_| disks[1].finish(tag).is_none())); + assert!(!disks[1].room(), "the waiting read goes first"); state.borrow_mut().fault = Fault::None; state.borrow_mut().now += RESET_RECOVERY_US; state.borrow_mut().units[1].as_mut().unwrap().attention = true; - assert!(disks[1].room()); - let tag = disks[1] - .start(Command::Read { lba: 0, bytes: 512 }) - .unwrap(); assert_eq!(finish(&mut disks[1], tag).unwrap().unwrap(), vec![2; 512]); + assert!(disks[1].room()); // A failed class reset resets the port and runs the write once more. state.borrow_mut().port_reset = true; state.borrow_mut().fault = Fault::Reset; diff --git a/crates/stela-drivers/src/usb/storage/media.rs b/crates/stela-drivers/src/usb/storage/media.rs index cf6cce51d7..0bf1f5441f 100644 --- a/crates/stela-drivers/src/usb/storage/media.rs +++ b/crates/stela-drivers/src/usb/storage/media.rs @@ -2,6 +2,7 @@ // SPDX-License-Identifier: GPL-2.0-only // Linux sd.c::sd_check_events/media_not_present/sd_revalidate_disk and // scsi_lib.c::scsi_io_completion_action. See NOTICE. +use super::recovery::{Ladder, Step}; use super::resume::{OTHER_IDENTITY, OTHER_MEDIUM, UNCHECKED_MEDIUM}; use super::*; @@ -121,16 +122,18 @@ struct Begun { generation: u64, /// A UNIT ATTENTION after a reset may still retry this attempt. attention: bool, - /// A command a port reset ended may still run once more. - rebound: bool, + /// Its runs down the recovery ladder ([`Ladder`]). + ladder: Ladder, /// The unit's first blocks once the command completes, where it /// writes them ([`Owner::first_blocks_after`]). first_blocks: Option>>, } /// A command begun without waiting: running on the transport under its -/// handle there, or ended with its result. +/// handle there, waiting to run again until the transport's recovery has +/// settled and it has room, or ended with its result. enum Queued { Running(Begun, usize), + Waiting(Begun), Ended(Result, BlockError>), } /// A begun command's data, kept for its retry. @@ -295,6 +298,11 @@ impl Owner { .collect(); } + /// Run `command` on a published unit down the recovery ladder: a + /// transport error, or any failure a port reset ended, runs it again + /// once the transport's recovery has settled, as Linux's SCSI midlayer + /// requeues a `DID_ERROR` or `DID_RESET` command within sd's retries + /// and runtime ([`Ladder`]). A unit not yet published runs it once. fn run( &mut self, lun: T::Lun, @@ -302,14 +310,47 @@ impl Owner { mut command: impl FnMut(&mut T) -> Result, ) -> Result { self.end_first(); - self.rebound = false; - let mut result = self.attempt(lun, cdb, &mut command); - // Linux's SCSI error handler retries the command a reset ended. - if result.is_err() && core::mem::take(&mut self.rebound) && self.valid(lun) { - result = self.attempt(lun, cdb, &mut command); + let published = self.units.iter().any(|unit| unit.lun == lun); + let mut ladder = Ladder::new(self.transport.now_us()); + loop { self.rebound = false; + let generation = self.transport.generation(); + let result = self.attempt(lun, cdb, &mut command); + let rebound = core::mem::take(&mut self.rebound); + let Err(error) = &result else { + ladder.completed(); + return result; + }; + let step = self.step(generation, rebound); + if !published || !ladder.again(error, step, self.transport.now_us(), self.usable(lun)) { + return result; + } } - result + } + + /// The step of the recovery ladder that ran since a command began at + /// transport generation `generation`; `rebound` when a port reset + /// replaced the transport. + fn step(&self, generation: u64, rebound: bool) -> Step { + if rebound { + Step::PortReset + } else if generation != self.transport.generation() { + Step::ClassReset + } else { + Step::Again + } + } + + /// Whether `lun` is published, valid, on a transport that takes commands. + fn usable(&self, lun: T::Lun) -> bool { + self.valid(lun) && !self.transport.poisoned() + } + + /// Whether a command waits to run again ([`Queued::Waiting`]). + fn waiting(&self) -> bool { + self.commands + .iter() + .any(|queued| matches!(queued, Some(Queued::Waiting(_)))) } /// One run of `command` and what its end means for the units. @@ -350,7 +391,10 @@ impl Owner { loop { let mut running = false; for handle in 0..self.commands.len() { - if !matches!(self.commands[handle], Some(Queued::Running(..))) { + if !matches!( + self.commands[handle], + Some(Queued::Running(..) | Queued::Waiting(_)) + ) { continue; } match self.end_begun(handle) { @@ -405,8 +449,9 @@ impl Owner { /// Command `handle`'s result once it has one, after the retries /// [`Self::run`] makes of a waiting command: once for a UNIT ATTENTION - /// a reset raised, and once more after a port reset rebound the - /// transport. A retry begins at once; its result comes at a later look. + /// a reset raised, and down the recovery ladder ([`Ladder`]) after a + /// transport error or a port reset. A retry begins once the transport + /// has room; its result comes at a later look. fn end_begun(&mut self, handle: usize) -> Option, BlockError>> { match self.commands.get(handle)? { None => None, @@ -421,6 +466,16 @@ impl Owner { }; self.ended_with(handle, begun, result) } + // Its run again begins once the transport has room. + Some(Queued::Waiting(_)) => { + if !self.transport.room() { + return None; + } + let Some(Queued::Waiting(begun)) = self.commands[handle].take() else { + return None; + }; + self.retry(handle, begun) + } } } @@ -451,14 +506,19 @@ impl Owner { } self.settle(begun.generation, &result); let rebound = core::mem::take(&mut self.rebound); - if result.is_err() - && rebound - && core::mem::take(&mut begun.rebound) - && self.valid(begun.lun) - { - begun.attention = true; - begun.generation = self.transport.generation(); - return self.retry(handle, begun); + match &result { + Err(error) => { + let step = self.step(begun.generation, rebound); + let usable = self.usable(begun.lun); + if begun + .ladder + .again(error, step, self.transport.now_us(), usable) + { + begun.attention = true; + return self.retry(handle, begun); + } + } + Ok(_) => begun.ladder.completed(), } if result.is_ok() && let Some(Some(first)) = begun.first_blocks @@ -468,13 +528,25 @@ impl Owner { Some(result) } - /// Begin `begun` again: `None` while it runs, its failure to begin as - /// its result. + /// Begin `begun` again: `None` while it runs or waits for the + /// transport's recovery to settle ([`Queued::Waiting`]), its failure to + /// begin as its result. A class reset that completed since it began + /// raises the UNIT ATTENTION its run again may meet first. fn retry( &mut self, handle: usize, - begun: Begun, + mut begun: Begun, ) -> Option, BlockError>> { + if !self.transport.room() { + self.store(handle, Queued::Waiting(begun)); + return None; + } + let generation = self.transport.generation(); + if generation != begun.generation { + self.expecting_reset = true; + begun.ladder.reached(Step::ClassReset); + } + begun.generation = generation; match self.begin_attempt(handle, begun)? { Ok(()) => None, Err(error) => Some(Err(error)), @@ -482,9 +554,9 @@ impl Owner { } /// The commands still running on a transport a device reset replaced: - /// each that may run once more begins again on the new one, as Linux's - /// SCSI error handling retries the commands a uas host reset ended - /// (`DID_RESET`); the others end failed. + /// each within its retries ([`Ladder`]) begins again on the new one, as + /// Linux's SCSI error handling retries the commands a uas host reset + /// ended (`DID_RESET`); the others end failed. fn restart_after_reset(&mut self) { for handle in 0..self.commands.len() { if !matches!(self.commands[handle], Some(Queued::Running(..))) { @@ -493,7 +565,13 @@ impl Owner { let Some(Queued::Running(mut begun, _)) = self.commands[handle].take() else { continue; }; - if !(core::mem::take(&mut begun.rebound) && self.valid(begun.lun)) { + let usable = self.valid(begun.lun); + if !begun.ladder.again( + &RESET_ENDED, + Step::PortReset, + self.transport.now_us(), + usable, + ) { self.commands[handle] = Some(Queued::Ended(Err(RESET_ENDED))); continue; } @@ -544,7 +622,8 @@ impl Owner { /// Linux usb-storage's ladder after a failed class reset: reset the /// device's port, rebind a fresh transport to the same device, and keep /// every unit that probes as it was published, so the disks published on - /// it go on working; [`Owner::run`] then retries the failed command once. At most + /// it go on working; [`Owner::run`] then runs the failed command again + /// within its retries ([`Ladder`]). At most /// [`RESET_LIMIT`] resets run in [`RESET_WINDOW_US`]; past that, or when /// the reset fails, every unit fails until an explicit rescan. fn reset_device(&mut self) { @@ -660,7 +739,7 @@ impl Owner { return Err(why); } for queued in &mut self.commands { - if matches!(queued, Some(Queued::Running(..))) { + if matches!(queued, Some(Queued::Running(..) | Queued::Waiting(_))) { *queued = Some(Queued::Ended(Err(BlockError::Unsupported( "USB storage device left the bus during the command", )))); @@ -764,8 +843,9 @@ impl Scsi for Owner { fn signals(&self) -> bool { self.transport.signals() } + /// A command waiting to run again is looked at until it begins. fn posted(&self) -> bool { - self.transport.posted() + self.waiting() || self.transport.posted() } fn write_protect_page(&self) -> Option { self.transport.write_protect_page() @@ -827,7 +907,7 @@ impl Scsi for Owner { cdb: &[u8], data: Data<'_>, ) -> Option> { - if !self.transport.room() { + if !self.room() { return Some(Err(BlockError::Protocol( "every command tag of the USB storage transport is in use", ))); @@ -846,7 +926,7 @@ impl Scsi for Owner { data: Retry::new(&data), generation: self.transport.generation(), attention: true, - rebound: true, + ladder: Ladder::new(self.transport.now_us()), first_blocks, }; Some(self.begin_attempt(handle, begun)?.map(|()| handle)) @@ -857,8 +937,9 @@ impl Scsi for Owner { fn busy(&mut self) -> bool { self.commands.iter().any(Option::is_some) || self.transport.busy() } + /// A command waiting to run again goes first. fn room(&mut self) -> bool { - self.transport.room() + !self.waiting() && self.transport.room() } } @@ -1130,6 +1211,8 @@ impl UsbDisk { } } +#[cfg(test)] +mod ladder_tests; #[cfg(test)] mod tests { use super::*; diff --git a/crates/stela-drivers/src/usb/storage/media/ladder_tests.rs b/crates/stela-drivers/src/usb/storage/media/ladder_tests.rs new file mode 100644 index 0000000000..2f085f7eb5 --- /dev/null +++ b/crates/stela-drivers/src/usb/storage/media/ladder_tests.rs @@ -0,0 +1,287 @@ +//! The recovery ladder of a published unit's commands, on a transport that +//! fails each step once ([`Flaky`]). +use super::super::recovery::{Cause, End, Step, take_recoveries}; +use super::*; +use crate::block::BlockDevice; +use alloc::collections::VecDeque; +use alloc::vec; + +const TRANSACTION: BlockError = BlockError::Device { status: 4 }; + +/// What a data command does. +#[derive(Clone, Copy)] +enum Fail { + /// A transaction error the transport recovers from by itself. + Again, + /// A transaction error after which a class reset clears both halts; + /// the device then raises a UNIT ATTENTION, and the transport takes no + /// command for a few looks while the reset settles. + ClassReset, + /// A transaction error that leaves the transport needing a port reset. + Poison, + /// As [`Self::Poison`], and the port reset fails. + Lost, +} + +#[derive(Default)] +struct Script { + data: VecDeque, + /// Data commands run. + runs: u32, + port_resets: u32, + port_reset_fails: bool, +} + +/// A removable unit of eight 512-byte blocks. +struct Flaky { + script: Rc>, + now: Rc>, + generation: u64, + poisoned: bool, + attention: bool, + settling: u32, + begun: Option, BlockError>>, +} +impl Flaky { + fn new(script: Rc>, now: Rc>) -> Self { + Self { + script, + now, + generation: 0, + poisoned: false, + attention: false, + settling: 0, + begun: None, + } + } +} +impl Scsi for Flaky { + type Lun = u8; + fn command(&mut self, _: u8, cdb: &[u8], data: Data<'_>) -> Result, BlockError> { + if self.poisoned { + return Err(BlockError::Unsupported( + "USB storage interface requires rebind", + )); + } + self.now.set(self.now.get() + 1_000); + if core::mem::take(&mut self.attention) { + return Err(BlockError::Sense(Sense { + key: Sense::UNIT_ATTENTION, + asc: Sense::RESET_OCCURRED, + ascq: 0, + })); + } + let bytes = |length| match data { + Data::In(bytes) => vec![0x5a; bytes.min(length)], + _ => Vec::new(), + }; + match cdb[0] { + scsi::INQUIRY => { + let mut inquiry = vec![0; scsi::INQUIRY_BYTES]; + inquiry[1] = 0x80; + Ok(inquiry) + } + scsi::READ_CAPACITY_10 => Ok(vec![0, 0, 0, 7, 0, 0, 2, 0]), + scsi::READ_10 | scsi::WRITE_10 => { + let mut script = self.script.borrow_mut(); + script.runs += 1; + match script.data.pop_front() { + None => Ok(bytes(usize::MAX)), + Some(Fail::Again) => Err(TRANSACTION), + Some(Fail::ClassReset) => { + self.generation += 1; + self.attention = true; + self.settling = 3; + Err(TRANSACTION) + } + Some(Fail::Poison) => { + self.poisoned = true; + Err(TRANSACTION) + } + Some(Fail::Lost) => { + self.poisoned = true; + script.port_reset_fails = true; + Err(TRANSACTION) + } + } + } + _ => Ok(bytes(usize::MAX)), + } + } + fn delay(&mut self, micros: u64) -> Result<(), BlockError> { + self.now.set(self.now.get() + micros); + Ok(()) + } + fn now_us(&self) -> u64 { + self.now.get() + } + fn poisoned(&self) -> bool { + self.poisoned + } + fn take_failed_data(&mut self) -> Option> { + None + } + fn queued(&self) -> bool { + true + } + fn begin(&mut self, lun: u8, cdb: &[u8], data: Data<'_>) -> Option> { + if self.busy() { + return Some(Err(BlockError::Protocol("busy"))); + } + let result = self.command(lun, cdb, data); + self.begun = Some(result); + Some(Ok(0)) + } + fn end(&mut self, _: usize) -> Option, BlockError>> { + self.begun.take() + } + fn busy(&mut self) -> bool { + if self.settling > 0 && self.begun.is_none() { + self.settling -= 1; + return true; + } + self.begun.is_some() + } + fn write_protect_page(&self) -> Option { + None + } + fn caching(&self) -> Caching { + Caching::WriteThrough + } + fn generation(&self) -> u64 { + self.generation + } + fn reset_device( + &mut self, + _: &mut dyn crate::bus::dma::DmaAllocator, + ) -> Option> { + let mut script = self.script.borrow_mut(); + script.port_resets += 1; + Some(if script.port_reset_fails { + Err(("port reset".into(), TRANSACTION)) + } else { + let mut fresh = Flaky::new(self.script.clone(), self.now.clone()); + fresh.attention = true; + Ok(fresh) + }) + } +} + +/// A published disk on a [`Flaky`] transport that runs `data` for its +/// data commands, and its script. +fn published(data: &[Fail]) -> (Disk>, Rc>) { + let script = Rc::new(RefCell::new(Script::default())); + let now = Rc::new(Cell::new(0)); + let owner = Rc::new(RefCell::new(Owner::new( + Flaky::new(script.clone(), now), + "port 1 interface 0".into(), + "serial".into(), + ))); + let mut failures = Vec::new(); + let mut disks = scan_bot(owner, &mut failures).unwrap(); + assert!(failures.is_empty()); + script.borrow_mut().data = data.iter().copied().collect(); + (disks.pop().unwrap(), script) +} + +fn recoveries() -> Vec<(Cause, Step, u32, End)> { + take_recoveries() + .0 + .into_iter() + .map(|recovery| (recovery.first, recovery.step, recovery.runs, recovery.end)) + .collect() +} + +#[test] +fn a_transaction_error_recovered_by_a_class_reset_runs_the_read_again() { + let (mut disk, script) = published(&[Fail::ClassReset]); + let mut block = [0; 512]; + assert_eq!(disk.read(0, &mut block), Ok(())); + assert_eq!(block, [0x5a; 512]); + // The reset's UNIT ATTENTION is expected: the removable unit keeps its + // medium. + assert!(disk.media.get()); + assert_eq!(script.borrow().runs, 2); + assert_eq!( + recoveries(), + [(Cause::Device(4), Step::ClassReset, 2, End::Completed)] + ); +} + +#[test] +fn each_step_failing_once_climbs_the_ladder_to_a_port_reset() { + let (mut disk, script) = published(&[Fail::Again, Fail::ClassReset, Fail::Poison]); + assert_eq!(disk.write(1, &[7; 512]), Ok(())); + assert!(disk.media.get()); + assert_eq!(script.borrow().runs, 4); + assert_eq!(script.borrow().port_resets, 1); + assert_eq!( + recoveries(), + [(Cause::Device(4), Step::PortReset, 4, End::Completed)] + ); +} + +#[test] +fn a_device_that_keeps_failing_ends_the_command_after_sd_retries() { + let (mut disk, script) = published(&[Fail::ClassReset; 8]); + assert_eq!(disk.read(0, &mut [0; 512]), Err(TRANSACTION)); + assert_eq!(script.borrow().runs, SD_MAX_RETRIES + 1); + assert_eq!( + recoveries(), + [( + Cause::Device(4), + Step::ClassReset, + SD_MAX_RETRIES + 1, + End::Retries + )] + ); + // The next command runs: the unit is still published. + assert_eq!(disk.read(0, &mut [0; 512]), Ok(())); +} + +#[test] +fn a_failed_port_reset_ends_the_command_and_the_disk() { + let (mut disk, script) = published(&[Fail::Lost]); + assert_eq!(disk.read(0, &mut [0; 512]), Err(TRANSACTION)); + assert_eq!(script.borrow().runs, 1); + assert_eq!(script.borrow().port_resets, 1); + assert_eq!( + recoveries(), + [(Cause::Device(4), Step::Again, 1, End::Lost)] + ); + assert!(disk.read(0, &mut [0; 512]).is_err()); + assert_eq!(script.borrow().runs, 1); +} + +#[test] +fn a_queued_read_waits_for_the_class_reset_to_settle_and_runs_again() { + let (mut disk, script) = published(&[Fail::ClassReset]); + let tag = disk + .start(Command::Read { + lba: 2, + bytes: 1024, + }) + .unwrap(); + let (mut looks, mut waits) = (0, 0); + let finished = loop { + if let Some(finished) = disk.finish(tag) { + break finished; + } + // A waiting command is looked at, and goes before new ones. + if disk.bot.borrow().waiting() { + assert!(disk.posted()); + assert!(!disk.room()); + waits += 1; + } + looks += 1; + assert!(looks < 10); + }; + assert_eq!(finished, Ok(Some(vec![0x5a; 1024]))); + assert_eq!(waits, 3, "one per look while the reset settles"); + assert!(disk.media.get()); + assert_eq!(script.borrow().runs, 2); + assert_eq!( + recoveries(), + [(Cause::Device(4), Step::ClassReset, 2, End::Completed)] + ); +} diff --git a/crates/stela-drivers/src/usb/storage/recovery.rs b/crates/stela-drivers/src/usb/storage/recovery.rs new file mode 100644 index 0000000000..eecd765447 --- /dev/null +++ b/crates/stela-drivers/src/usb/storage/recovery.rs @@ -0,0 +1,442 @@ +// SPDX-License-Identifier: GPL-2.0-only +//! The retries of a USB storage command its transport failed, and their +//! log records. Linux usb-storage answers a transport error +//! (`USB_STOR_TRANSPORT_ERROR`) with a reset and completes the command with +//! `DID_ERROR`; the SCSI midlayer then requeues it while it has retries +//! left (`scsi_decide_disposition`'s `maybe_retry`: sd allows +//! `SD_MAX_RETRIES`) and has not run past its runtime limit. The reset +//! ladder itself is the transport's and its owner's: the xHCI's soft retries +//! of a transaction error, a halt's clear on a stall, the Bulk-Only class +//! reset with both halts cleared, and a port reset when that fails +//! ([`super::media::Owner`]). This module counts the runs and keeps one +//! record per command the ladder ran for. +use super::{SD_MAX_RETRIES, SD_RUNTIME_US}; +use crate::block::BlockError; +use core::fmt; +use core::sync::atomic::{AtomicU32, AtomicU64, Ordering}; + +/// Whether `error` is a failure of the transport rather than an answer of +/// the unit: Linux's `DID_ERROR` (a transfer error, a malformed wrapper or +/// status, a failed auto-sense) and `DID_TIME_OUT`. +pub(super) fn transport_error(error: &BlockError) -> bool { + matches!( + error, + BlockError::Device { .. } | BlockError::Timeout | BlockError::CheckCondition + ) || *error == super::bot::PROTOCOL_ERROR + || *error == super::uas::PROTOCOL_ERROR +} + +/// What ended a run of a command. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Cause { + /// An xHCI completion code. + Device(u32), + Timeout, + /// CHECK CONDITION without readable sense data. + NoSense, + /// A malformed wrapper, status or information unit. + Protocol, + /// A reset run for another command ended it. + Reset, + /// Any other answer, such as the unit's sense or a refusal. + Other, +} +impl Cause { + fn of(error: &BlockError) -> Self { + match error { + BlockError::Device { status } => Self::Device(*status), + BlockError::Timeout => Self::Timeout, + BlockError::CheckCondition => Self::NoSense, + _ if *error == super::bot::PROTOCOL_ERROR || *error == super::uas::PROTOCOL_ERROR => { + Self::Protocol + } + _ if *error == super::media::RESET_ENDED => Self::Reset, + _ => Self::Other, + } + } + fn encode(self) -> u64 { + let (kind, status) = match self { + Self::Device(status) => (1, status.min(0xffff)), + Self::Timeout => (2, 0), + Self::NoSense => (3, 0), + Self::Protocol => (4, 0), + Self::Reset => (5, 0), + Self::Other => (6, 0), + }; + (kind << 16 | u64::from(status)) & 0x7_ffff + } + fn decode(bits: u64) -> Self { + let status = (bits & 0xffff) as u32; + match bits >> 16 & 7 { + 1 => Self::Device(status), + 2 => Self::Timeout, + 3 => Self::NoSense, + 4 => Self::Protocol, + 5 => Self::Reset, + _ => Self::Other, + } + } +} +impl fmt::Display for Cause { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Device(status) => f.write_str(&crate::usb::xhci::explain(&BlockError::Device { + status: *status, + })), + Self::Timeout => f.write_str("a time-out"), + Self::NoSense => f.write_str("a failed status without sense data"), + Self::Protocol => f.write_str("a malformed wrapper or status"), + Self::Reset => f.write_str("a device reset for another command"), + Self::Other => f.write_str("the unit's answer"), + } + } +} + +/// The furthest step of the ladder a command's runs went through. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] +pub enum Step { + /// The transport took the command again as it was. + Again, + /// A Bulk-Only class reset and both halts' clears. + ClassReset, + /// A port reset and a fresh transport bound to the same device. + PortReset, +} +impl fmt::Display for Step { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(match self { + Self::Again => "running it again", + Self::ClassReset => "a class reset and both halt clears", + Self::PortReset => "a port reset and rebind", + }) + } +} + +/// How a command the ladder ran for ended. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum End { + Completed, + /// Its runs reached sd's retries. + Retries, + /// It ran past sd's runtime limit. + Runtime, + /// Its unit is no longer published: the device was lost, its medium + /// changed, or its transport needs a rebind the owner cannot run. + Lost, + /// A run ended with an answer that is no transport error. + Answered, +} +impl End { + fn encode(self) -> u64 { + self as u64 + } + fn decode(bits: u64) -> Self { + match bits & 7 { + 0 => Self::Completed, + 1 => Self::Retries, + 2 => Self::Runtime, + 3 => Self::Lost, + _ => Self::Answered, + } + } +} + +/// One command the recovery ladder ran for: what first failed it, the +/// furthest step it took, how many times it ran and how it ended. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Recovery { + pub first: Cause, + pub last: Cause, + pub step: Step, + pub runs: u32, + pub end: End, +} +impl fmt::Display for Recovery { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let total = SD_MAX_RETRIES + 1; + write!(f, "{} failed a command; ", self.first)?; + match self.end { + End::Completed => write!( + f, + "{} recovered it, and it completed on run {} of {total}", + self.step, self.runs + ), + End::Retries => write!( + f, + "after {} runs with {} it still failed with {}: retries exhausted", + self.runs, self.step, self.last + ), + End::Runtime => write!( + f, + "after {} runs with {} it failed with {}: past the {} s runtime limit", + self.runs, + self.step, + self.last, + SD_RUNTIME_US / 1_000_000 + ), + End::Lost if self.runs <= 1 => write!( + f, + "the device needs a reset this owner cannot run, or left the bus: the disk \ + fails until it is bound again" + ), + End::Lost => write!( + f, + "after {} runs with {} it failed with {}: the device needs a reset this \ + owner cannot run, or left the bus", + self.runs, self.step, self.last + ), + End::Answered => write!( + f, + "after {} runs with {} the unit answered with an error", + self.runs, self.step + ), + } + } +} + +/// Records kept between two [`take_recoveries`]; a later one replaces the +/// oldest past that. +const KEPT: usize = 16; +const VALID: u64 = 1 << 63; +static RECORDS: [AtomicU64; KEPT] = [const { AtomicU64::new(0) }; KEPT]; +static NEXT: AtomicU32 = AtomicU32::new(0); +static DROPPED: AtomicU32 = AtomicU32::new(0); +const SEQUENCE_BITS: u32 = 15; + +impl Recovery { + fn encode(&self, sequence: u32) -> u64 { + VALID + | u64::from(sequence & ((1 << SEQUENCE_BITS) - 1)) << 48 + | self.end.encode() << 45 + | (u64::from(self.runs.min(15))) << 41 + | (self.step as u64) << 38 + | self.last.encode() << 19 + | self.first.encode() + } + fn decode(bits: u64) -> (u32, Self) { + let step = match bits >> 38 & 3 { + 0 => Step::Again, + 1 => Step::ClassReset, + _ => Step::PortReset, + }; + ( + (bits >> 48) as u32 & ((1 << SEQUENCE_BITS) - 1), + Self { + first: Cause::decode(bits & 0x7_ffff), + last: Cause::decode(bits >> 19 & 0x7_ffff), + step, + runs: (bits >> 41 & 15) as u32, + end: End::decode(bits >> 45), + }, + ) + } +} + +fn ring_record(recovery: Recovery) { + let sequence = NEXT.fetch_add(1, Ordering::Relaxed); + let slot = &RECORDS[sequence as usize % KEPT]; + if slot.swap(recovery.encode(sequence), Ordering::AcqRel) != 0 { + DROPPED.fetch_add(1, Ordering::Relaxed); + } +} + +fn ring_take() -> (alloc::vec::Vec, u32) { + let mut taken: alloc::vec::Vec<(u32, Recovery)> = RECORDS + .iter() + .map(|slot| slot.swap(0, Ordering::AcqRel)) + .filter(|bits| bits & VALID != 0) + .map(Recovery::decode) + .collect(); + let newest = NEXT.load(Ordering::Relaxed); + // Ages from the newest sequence number, which wrap as it does. + let mask = (1 << SEQUENCE_BITS) - 1; + taken.sort_by_key(|(sequence, _)| core::cmp::Reverse(newest.wrapping_sub(*sequence) & mask)); + ( + taken.into_iter().map(|(_, recovery)| recovery).collect(), + DROPPED.swap(0, Ordering::Relaxed), + ) +} + +#[cfg(not(test))] +fn record(recovery: Recovery) { + ring_record(recovery); +} + +/// The commands the recovery ladder ran for since the last call, oldest +/// first, and how many records were replaced before they were taken. +#[cfg(not(test))] +pub fn take_recoveries() -> (alloc::vec::Vec, u32) { + ring_take() +} + +// Tests run in parallel threads: each keeps its own records. +#[cfg(test)] +extern crate std; +#[cfg(test)] +std::thread_local! { + static TEST_RECORDS: core::cell::RefCell> = + const { core::cell::RefCell::new(alloc::vec::Vec::new()) }; +} +#[cfg(test)] +fn record(recovery: Recovery) { + TEST_RECORDS.with(|records| records.borrow_mut().push(recovery)); +} +#[cfg(test)] +pub fn take_recoveries() -> (alloc::vec::Vec, u32) { + (TEST_RECORDS.with(|records| records.take()), 0) +} + +/// A command's runs on its way down the ladder. +#[derive(Clone, Copy, Debug)] +pub(super) struct Ladder { + started: u64, + /// Runs after the first. + retries: u32, + first: Option, + step: Step, +} +impl Ladder { + pub(super) fn new(started: u64) -> Self { + Self { + started, + retries: 0, + first: None, + step: Step::Again, + } + } + /// Whether the command, which ended with `error` at `now` after the + /// ladder ran `step` for it, runs again: a transport error, or any + /// failure a port reset ended (Linux retries what a reset ended, + /// `DID_RESET`), while within sd's retries and runtime and while its + /// unit is still published on a usable transport (`usable`). Records + /// the command's end when it does not run again. + pub(super) fn again(&mut self, error: &BlockError, step: Step, now: u64, usable: bool) -> bool { + let transport = transport_error(error) || step == Step::PortReset; + if transport && self.first.is_none() { + self.first = Some(Cause::of(error)); + } + if transport { + self.step = self.step.max(step); + } + let end = if !transport { + End::Answered + } else if !usable { + End::Lost + } else if self.retries >= SD_MAX_RETRIES { + End::Retries + } else if now.wrapping_sub(self.started) > SD_RUNTIME_US { + End::Runtime + } else { + self.retries += 1; + return true; + }; + self.end(end, Cause::of(error)); + false + } + /// The ladder ran `step` for the command since its last failure. + pub(super) fn reached(&mut self, step: Step) { + if self.first.is_some() { + self.step = self.step.max(step); + } + } + /// The command completed. + pub(super) fn completed(&mut self) { + self.end(End::Completed, Cause::Other); + } + fn end(&mut self, end: End, last: Cause) { + // A command the ladder never ran for needs no record, nor one a + // unit's answer ended at its first run. + let Some(first) = self.first.take() else { + return; + }; + record(Recovery { + first, + last, + step: self.step, + runs: self.retries + 1, + end, + }); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_record_survives_its_encoding() { + let recovery = Recovery { + first: Cause::Device(4), + last: Cause::Timeout, + step: Step::PortReset, + runs: 6, + end: End::Retries, + }; + let (sequence, decoded) = Recovery::decode(recovery.encode(1234)); + assert_eq!((sequence, decoded), (1234, recovery)); + } + + /// The one test of the static ring: the rest keep their records apart. + #[test] + fn the_ring_keeps_the_newest_records_in_order_and_counts_the_replaced() { + let recovery = |runs| Recovery { + first: Cause::Device(4), + last: Cause::Device(4), + step: Step::ClassReset, + runs, + end: End::Completed, + }; + ring_take(); + for runs in 0..KEPT as u32 + 3 { + ring_record(recovery(runs % 16)); + } + let (records, dropped) = ring_take(); + assert_eq!(dropped, 3); + let runs: alloc::vec::Vec = records.iter().map(|r| r.runs).collect(); + let expected: alloc::vec::Vec = (3..KEPT as u32 + 3).map(|runs| runs % 16).collect(); + assert_eq!(runs, expected); + assert_eq!(ring_take(), (alloc::vec::Vec::new(), 0)); + } + + #[test] + fn the_ladder_retries_transport_errors_within_sd_limits_and_records_once() { + take_recoveries(); + let error = BlockError::Device { status: 4 }; + // Five retries, then exhausted. + let mut ladder = Ladder::new(0); + for _ in 0..SD_MAX_RETRIES { + assert!(ladder.again(&error, Step::ClassReset, 0, true)); + } + assert!(!ladder.again(&error, Step::ClassReset, 0, true)); + // Past the runtime limit. + let mut late = Ladder::new(0); + assert!(!late.again(&BlockError::Timeout, Step::Again, SD_RUNTIME_US + 1, true)); + // A unit's answer is no transport error, and needs no record. + let mut answered = Ladder::new(0); + assert!(!answered.again(&BlockError::ReadOnly, Step::Again, 0, true)); + answered.completed(); + // One recovered after a retry. + let mut recovered = Ladder::new(0); + assert!(recovered.again(&error, Step::ClassReset, 0, true)); + recovered.completed(); + // A lost unit does not run again. + let mut lost = Ladder::new(0); + assert!(!lost.again(&error, Step::ClassReset, 0, false)); + let (records, dropped) = take_recoveries(); + assert_eq!(dropped, 0); + let ends: alloc::vec::Vec<_> = records.iter().map(|r| (r.end, r.runs)).collect(); + assert_eq!( + ends, + [ + (End::Retries, SD_MAX_RETRIES + 1), + (End::Runtime, 1), + (End::Completed, 2), + (End::Lost, 1) + ] + ); + assert_eq!(records[0].first, Cause::Device(4)); + assert!(std::format!("{}", records[2]).starts_with( + "USB transaction error (xHCI completion code 4) failed a command; a class reset" + )); + } +} diff --git a/crates/stela-drivers/src/usb/storage/uas.rs b/crates/stela-drivers/src/usb/storage/uas.rs index cc3ea122a1..c297ddca02 100644 --- a/crates/stela-drivers/src/usb/storage/uas.rs +++ b/crates/stela-drivers/src/usb/storage/uas.rs @@ -51,7 +51,8 @@ const WRITE_READY_IU: u8 = 7; const TIMEOUT_US: u64 = 30_000_000; const IU_BUFFER_BYTES: usize = 512; const MAX_CDB: usize = 260; -const PROTOCOL_ERROR: BlockError = BlockError::Protocol("malformed UAS information unit"); +pub(super) const PROTOCOL_ERROR: BlockError = + BlockError::Protocol("malformed UAS information unit"); #[derive(Clone, Copy, Debug, PartialEq, Eq)] enum Pipe { diff --git a/crates/stela-drivers/src/usb/storage/uas/tests/queued.rs b/crates/stela-drivers/src/usb/storage/uas/tests/queued.rs index b073ac2768..2f9f398e49 100644 --- a/crates/stela-drivers/src/usb/storage/uas/tests/queued.rs +++ b/crates/stela-drivers/src/usb/storage/uas/tests/queued.rs @@ -654,8 +654,10 @@ fn a_stalled_or_hung_tag_resets_the_device_and_each_running_command_runs_again() } } +/// Linux requeues a command a reset ended, and one that failed, while it +/// has retries left: each read runs again after each of the two resets. #[test] -fn a_command_a_second_reset_ends_after_its_one_more_run_fails() { +fn commands_two_resets_end_run_again_within_their_retries() { let mut memory = vec![0u64; 512 * 1024]; let (mut disk, device, _owner) = stack(&mut memory, 32); let lbas: Vec = (0..3).map(|i| 512 + i * 8).collect(); @@ -670,11 +672,9 @@ fn a_command_a_second_reset_ends_after_its_one_more_run_fails() { .map(|&lba| disk.start(Command::Read { lba, bytes: 4096 }).unwrap()) .collect(); let results = drain(&mut disk, &device, &tags); - assert_eq!(results[&tags[0]], Ok(Some(vec![0x5a; 4096]))); - assert_eq!(results[&tags[1]], Err(BlockError::Device { status: STALL })); - // The second reset found the third read running again, its one more - // run spent: it ends, as Linux fails a command past its retries. - assert_eq!(results[&tags[2]], Err(media::RESET_ENDED)); + for tag in &tags { + assert_eq!(results[tag], Ok(Some(vec![0x5a; 4096]))); + } assert_eq!(device.borrow().resets, 2); }