From 82e72a12902fe51db07a9eb871bb2e28f1058c7a Mon Sep 17 00:00:00 2001 From: Tyler Smith <74526874+tylertms@users.noreply.github.com> Date: Thu, 22 Oct 2026 01:31:39 +0000 Subject: [PATCH] feat(drivers): schedule native USB2 isochronous queues on PC xHCI profiles --- crates/stela-drivers/src/usb/xhci.rs | 73 +- crates/stela-drivers/src/usb/xhci/endpoint.rs | 5 +- crates/stela-drivers/src/usb/xhci/iso.rs | 408 ++++++++ .../stela-drivers/src/usb/xhci/iso/tests.rs | 937 ++++++++++++++++++ .../stela-drivers/src/usb/xhci/reset/tests.rs | 1 + crates/stela-drivers/src/usb/xhci/streams.rs | 1 + crates/stela-drivers/src/usb/xhci/teardown.rs | 85 ++ .../tests/reference/xhci_amd_pci_oracle.py | 64 ++ .../tests/reference/xhci_iso_oracle.py | 177 ++++ 9 files changed, 1740 insertions(+), 11 deletions(-) create mode 100644 crates/stela-drivers/src/usb/xhci/iso.rs create mode 100644 crates/stela-drivers/src/usb/xhci/iso/tests.rs create mode 100644 crates/stela-drivers/src/usb/xhci/teardown.rs create mode 100644 crates/stela-drivers/tests/reference/xhci_amd_pci_oracle.py create mode 100644 crates/stela-drivers/tests/reference/xhci_iso_oracle.py diff --git a/crates/stela-drivers/src/usb/xhci.rs b/crates/stela-drivers/src/usb/xhci.rs index 86d21d0180..22f0596456 100644 --- a/crates/stela-drivers/src/usb/xhci.rs +++ b/crates/stela-drivers/src/usb/xhci.rs @@ -29,9 +29,13 @@ //! fatal controller status prevents all later DMA/ring mutation until an //! independently proven controller reset (not implemented as recovery here). //! +//! Root-direct FS/HS isochronous service intervals use the dedicated queued +//! submit_iso/completed_iso API on audited AMD/QEMU PCI profiles. Payloads fit +//! one TRB/service and completion ownership survives uncertain cancellation. +//! //! Refused rather than handled: SuperSpeed hubs (they need Set Hub Depth //! and SuperSpeed port control, and no class driver here needs one), -//! isochronous endpoints, secondary stream arrays, hubs more than five tiers +//! SuperSpeed/hub-routed isochronous endpoints, secondary stream arrays, hubs more than five tiers //! deep, and controllers without 4 KiB pages. Hot plug after attach is not seen. use super::{bluetooth, cdc, ethernet, hid, storage}; use crate::{ @@ -58,8 +62,11 @@ mod reset; pub(crate) use reset::tests::{ Fault as ResetFault, Hardware as ResetHardware, fixture as reset_fixture, }; +mod iso; mod streams; +mod teardown; +pub use iso::{IsoCompletion, IsoStatus, IsoTransfer}; pub use streams::StreamTransfer; pub const CLASS: [u8; 3] = [0x0c, 0x03, 0x30]; @@ -506,6 +513,7 @@ impl Device { struct Transfer { ring: Ring, streams: Option, + iso: Option, is_in: bool, /// A failed cancellation leaves hardware ownership unresolved. poisoned: bool, @@ -549,6 +557,7 @@ pub struct Controller { dma_profile: dma::Profile, max_primary_streams: u32, stream_policy: streams::Policy, + iso_caps: iso::Capabilities, max_slots: usize, max_ports: u8, /// Each root port's USB major revision from the Supported Protocol @@ -705,6 +714,7 @@ impl Controller { dma_profile: profile, max_primary_streams: 1 << ((capabilities1 >> 12 & 0xf) + 1), stream_policy: streams::Policy::Unknown, + iso_caps: iso::Capabilities::new((capability >> 16) as u16, parameters2, capabilities1), max_slots, max_ports, port_major, @@ -900,6 +910,7 @@ impl Controller { endpoints[1] = Some(Transfer { ring, streams: None, + iso: None, is_in: false, poisoned: false, enabled: true, @@ -1226,7 +1237,7 @@ impl Controller { if endpoint.address & 0x70 != 0 || dci < 2 || endpoint.max_packet & 0x7ff == 0 - || !matches!(endpoint.kind(), 2 | 3) + || !matches!(endpoint.kind(), 1..=3) || selected & (1 << dci) != 0 { return Err(BlockError::Unsupported( @@ -1243,6 +1254,15 @@ impl Controller { contexts.push(endpoint::Context::new(endpoint, speed)?); selected |= 1 << dci; } + if endpoints.iter().any(|ep| ep.kind() == 1) { + self.iso_caps.admit()?; + let attachment = self.slot(slot)?.attachment; + if attachment.tier != 0 || attachment.route != 0 || attachment.translator.is_some() { + return Err(BlockError::Unsupported( + "isochronous transport currently requires root-direct USB2", + )); + } + } let layout = if stream_endpoints.is_empty() { None } else { @@ -1288,6 +1308,11 @@ impl Controller { state.endpoints[usize::from(dci)] = Some(Transfer { ring, streams: stream, + iso: if endpoint.kind() == 1 { + Some(iso::Queue::new(iso::Recipe::new(endpoint, speed)?)) + } else { + None + }, is_in: endpoint.is_in(), poisoned: false, enabled: false, @@ -1352,6 +1377,11 @@ impl Controller { if transfer.poisoned { return Err(BlockError::Unsupported("xHCI endpoint cancellation failed")); } + if transfer.iso.is_some() { + return Err(BlockError::Unsupported( + "isochronous endpoint requires submit_iso", + )); + } if transfer.streams.is_some() { return Err(BlockError::Unsupported( "stream ID required for this endpoint", @@ -1378,6 +1408,16 @@ impl Controller { if let Err(error) = self.endpoint_ready(slot, dci) { return Some(Err(error)); } + if self + .slot(slot) + .ok() + .and_then(|slot| slot.endpoints[usize::from(dci)].as_ref()) + .is_some_and(|endpoint| endpoint.iso.is_some()) + { + return Some(Err(BlockError::Unsupported( + "isochronous endpoint requires completed_iso", + ))); + } let event = self.take(|e| { e.kind() == TRANSFER_EVENT && e.slot() == slot @@ -1517,12 +1557,20 @@ impl Controller { if let Some(streams) = &mut endpoint.streams { streams.cancelled(); } + if let Some(iso) = &mut endpoint.iso { + iso.cancelled(); + } endpoint.poisoned = false; Ok(()) } /// Clears a halted bulk or interrupt endpoint on both sides. pub fn clear(&mut self, slot: u8, endpoint: &Endpoint) -> Result<(), BlockError> { + if endpoint.kind() == 1 { + return Err(BlockError::Unsupported( + "isochronous endpoints have no USB halt feature", + )); + } self.recover(slot, endpoint.dci())?; let request = setup(0x02, CLEAR_FEATURE, 0, u16::from(endpoint.address), 0); self.control(slot, request, &[])?; @@ -2024,13 +2072,16 @@ pub fn attach_with_provider( "xhci {:04x}:{:02x}:{:02x}.{}", address.segment, address.bus, address.device, address.function ); - start_with_stream_policy( + start_with_policies( Box::new(registers), handoff.clock, dma, location, firmware, - stream_policy, + ( + stream_policy, + iso::Policy::pci(function.vendor, function.device), + ), dma_profile, ) } @@ -2061,32 +2112,33 @@ pub fn start_with_provider( location: String, firmware: &dyn crate::firmware::Provider, ) -> Result { - start_with_stream_policy( + start_with_policies( registers, clock, dma, location, firmware, - streams::Policy::Unknown, + (streams::Policy::Unknown, iso::Policy::Unknown), dma::Profile::SPEC, ) } -fn start_with_stream_policy( +fn start_with_policies( registers: Box, clock: Clock, dma: &mut dyn DmaAllocator, location: String, firmware: &dyn crate::firmware::Provider, - policy: streams::Policy, + policy: (streams::Policy, iso::Policy), dma_profile: dma::Profile, ) -> Result { let mut controller = Controller::with_dma_profile(registers, clock, dma, location, dma_profile)?; // The policy came from this same actual PCI function before BAR access, // and applies only to the controller reset just completed above. No public - // raw-register caller can supply a guessed PCI identity or enable streams. - controller.stream_policy = policy; + // raw-register caller can supply a guessed PCI identity or enable streams/iso. + controller.stream_policy = policy.0; + controller.iso_caps.qualify(policy.1); let mut found = Found::default(); let devices = controller.enumerate(dma, &mut found.failures); let shared: Shared = Rc::new(RefCell::new(controller)); @@ -2398,6 +2450,7 @@ pub(crate) mod tests { dma_profile: dma::Profile::SPEC, max_primary_streams: 4, stream_policy: streams::Policy::Unknown, + iso_caps: iso::Capabilities::new(0x100, 0, 0), max_slots: 1, max_ports: 1, port_major: vec![2], diff --git a/crates/stela-drivers/src/usb/xhci/endpoint.rs b/crates/stela-drivers/src/usb/xhci/endpoint.rs index 67d2b603b1..7cf81072ef 100644 --- a/crates/stela-drivers/src/usb/xhci/endpoint.rs +++ b/crates/stela-drivers/src/usb/xhci/endpoint.rs @@ -1,7 +1,7 @@ // SPDX-License-Identifier: GPL-2.0-only // Interval/burst mapping follows Linux xhci-mem.c, pinned in THIRD_PARTY.md. // Copyright (C) 2008 Intel Corp. Author: Sarah Sharp. -//! Validated bulk/interrupt context fields. Validate before allocating or +//! Validated bulk/interrupt and root-direct USB2 isochronous context fields. Validate before allocating or //! publishing DMA: invalid descriptors cannot partially configure a device. use super::{ BlockError, Endpoint, FULL_SPEED, HIGH_SPEED, LOW_SPEED, SUPER_SPEED, SUPER_SPEED_PLUS, @@ -16,6 +16,9 @@ pub(super) struct Context { impl Context { pub fn new(ep: &Endpoint, speed: u8) -> Result { + if ep.kind() == 1 { + return super::iso::Recipe::new(ep, speed).map(|recipe| recipe.context()); + } let invalid = || BlockError::Unsupported("invalid speed-specific USB endpoint descriptor"); let packet = u32::from(ep.max_packet & 0x7ff); let interrupt = ep.kind() == 3; diff --git a/crates/stela-drivers/src/usb/xhci/iso.rs b/crates/stela-drivers/src/usb/xhci/iso.rs new file mode 100644 index 0000000000..89cf1b59ae --- /dev/null +++ b/crates/stela-drivers/src/usb/xhci/iso.rs @@ -0,0 +1,408 @@ +// SPDX-License-Identifier: GPL-2.0-only +// Isochronous scheduling/completion follows pinned Linux xhci-ring.c and xhci-mem.c. +// Copyright (C) 2008 Intel Corp. Author: Sarah Sharp. +//! Queued root-direct USB2 service intervals on retained native transfer rings. +use super::*; +use core::sync::atomic::{AtomicU64, Ordering}; + +const ISOCH: u32 = 5; +const BABBLE: u32 = 3; +const TRANSACTION_ERROR: u32 = 4; +const BANDWIDTH_OVERRUN: u32 = 18; +const INCOMPATIBLE_DEVICE: u32 = 22; +const MISSED_SERVICE: u32 = 23; +const ISO_BUFFER_OVERRUN: u32 = 31; +const EVENT_DATA: u32 = 1 << 2; +const SIA: u32 = 1 << 31; +const FRAMES: u32 = 2048; +const MICROFRAMES: u32 = FRAMES * 8; +const CFC_DELAY: u32 = 10; +static NEXT_TICKET: AtomicU64 = AtomicU64::new(1); + +/// A terminal packet status. Every variant is a completed service interval; +/// transport errors are returned separately and do not release DMA ownership. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum IsoStatus { + Success, + Short, + MissedService, + Transaction, + Babble, + Bandwidth, + BufferOverrun, +} +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct IsoCompletion { + pub bytes: usize, + pub status: IsoStatus, +} +/// An exact controller/endpoint service interval. Dropping this ticket does not +/// cancel DMA; the endpoint retains it until completion or acknowledged cancel. +#[derive(Debug)] +pub struct IsoTransfer { + id: u64, + slot: u8, + dci: u8, + trb: u64, +} + +/// Exact source-audited PCI profiles for this bounded PC cut. No older AMD +/// quirk predicate is selected from a CPU/chipset family name. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum Policy { + Unknown, + Amd(u16), + Qemu, +} +impl Policy { + pub fn pci(vendor: u16, device: u16) -> Self { + match (vendor, device) { + (0x1022, 0x15b6 | 0x15b7 | 0x15b8 | 0x43fc) => Self::Amd(device), + (0x1b36, 0x000d) => Self::Qemu, + _ => Self::Unknown, + } + } +} +#[derive(Clone, Copy)] +pub(super) struct Capabilities { + version: u16, + policy: Policy, + ist: u32, + cfc: bool, +} +impl Capabilities { + pub fn new(version: u16, hcs2: u32, hcc1: u32) -> Self { + Self { + version, + policy: Policy::Unknown, + ist: (hcs2 & 7) * if hcs2 & 8 != 0 { 8 } else { 1 }, + cfc: hcc1 & (1 << 11) != 0, + } + } + pub fn qualify(&mut self, policy: Policy) { + self.policy = policy; + } + pub fn admit(self) -> Result<(), BlockError> { + if self.policy == Policy::Unknown { + return Err(BlockError::Unsupported( + "isochronous transport requires an audited actual PCI controller profile", + )); + } + // Legacy 0.96 AMD/NEC isoch Link-TRB quirks are outside these actual + // PC profiles. Do not silently apply 1.0 TLBPC/FrameID semantics there. + if self.version < 0x100 { + return Err(BlockError::Unsupported( + "isochronous transport requires xHCI 1.0 or newer", + )); + } + Ok(()) + } +} + +#[derive(Clone, Copy)] +pub(super) struct Recipe { + packet: u32, + burst: u32, + exponent: u32, + payload: u32, + is_in: bool, +} +impl Recipe { + pub fn new(ep: &Endpoint, speed: u8) -> Result { + let invalid = || BlockError::Unsupported("invalid root-direct USB2 isochronous endpoint"); + let packet = u32::from(ep.max_packet & 0x7ff); + let transactions = u32::from(ep.max_packet >> 11 & 3); + if ep.kind() != 1 + || ep.address & 0x70 != 0 + || ep.dci() < 2 + || ep.attributes & 0xc0 != 0 + || ep.attributes >> 4 & 3 == 3 + || ep.max_packet & 0xe000 != 0 + || packet == 0 + || !(1..=16).contains(&ep.interval) + || ep.companion.is_some() + { + return Err(invalid()); + } + let (burst, exponent) = match speed { + FULL_SPEED if packet <= 1023 && transactions == 0 => (0, u32::from(ep.interval) + 2), + HIGH_SPEED if packet <= 1024 && transactions <= 2 => { + (transactions, u32::from(ep.interval) - 1) + } + _ => return Err(invalid()), + }; + // A single submission must fit xHCI's bounded scheduling window. The + // USB descriptor can express longer intervals; they are not discarded. + if exponent > 12 { + return Err(BlockError::Unsupported( + "isochronous interval exceeds scheduling window", + )); + } + Ok(Self { + packet, + burst, + exponent, + payload: packet * (burst + 1), + is_in: ep.is_in(), + }) + } + pub fn context(self) -> endpoint::Context { + endpoint::Context { + info: self.exponent << 16, + info2: (if self.is_in { 5 } else { 1 }) << 3 | self.burst << 8 | self.packet << 16, + tx_info: self.payload | self.payload << 16, + } + } +} +struct Active { + id: u64, + trb: u64, + bytes: usize, +} +pub(super) struct Queue { + recipe: Recipe, + active: Vec, + next: Option, + recovery: bool, +} +impl Queue { + pub fn new(recipe: Recipe) -> Self { + Self { + recipe, + active: Vec::new(), + next: None, + recovery: false, + } + } + pub fn cancelled(&mut self) { + self.active.clear(); + self.next = None; + self.recovery = false; + } +} + +fn in_window(frame: u32, start: u32, end: u32) -> bool { + if start > end { + frame >= start || frame <= end + } else { + frame >= start && frame <= end + } +} +fn schedule( + mfindex: u32, + caps: Capabilities, + interval: u32, + next: Option, +) -> Result<(u32, u32), BlockError> { + let mfindex = mfindex & (MICROFRAMES - 1); + let first = next.is_none(); + let start = next.unwrap_or_else(|| { + (mfindex + caps.ist + CFC_DELAY) + .next_multiple_of(8) + .next_multiple_of(interval) + % MICROFRAMES + }); + let current = mfindex / 8; + let low = (current + caps.ist.div_ceil(8) + 1) % FRAMES; + let high = (current + 895) % FRAMES; + if !in_window(start / 8, low, high) { + return Err(BlockError::Unsupported( + "isochronous service interval missed scheduling window", + )); + } + let field = if caps.cfc || first { + (start / 8) << 20 + } else { + SIA + }; + Ok((start, field)) +} +fn completion(code: u32, bytes: usize, residual: usize) -> Result { + if residual > bytes { + return Err(BlockError::Unsupported( + "invalid isochronous completion residual", + )); + } + let status = match code { + SUCCESS => IsoStatus::Success, + SHORT_PACKET => IsoStatus::Short, + MISSED_SERVICE => IsoStatus::MissedService, + TRANSACTION_ERROR => IsoStatus::Transaction, + BABBLE => IsoStatus::Babble, + BANDWIDTH_OVERRUN => IsoStatus::Bandwidth, + ISO_BUFFER_OVERRUN => IsoStatus::BufferOverrun, + status => return Err(BlockError::Device { status }), + }; + Ok(IsoCompletion { + bytes: match status { + IsoStatus::Bandwidth | IsoStatus::BufferOverrun => bytes, + _ => bytes - residual, + }, + status, + }) +} + +fn trb_control(recipe: Recipe, length: usize, frame: u32) -> u32 { + let packets = (length as u32).div_ceil(recipe.packet).max(1); + ISOCH << 10 | IOC | frame | (packets - 1) << 16 | if recipe.is_in { ISP } else { 0 } +} + +impl Controller { + /// Test fixtures supply an explicit observed profile without claiming native + /// PCI qualification. This grant is absent from production/raw starts. + #[cfg(test)] + pub(crate) fn qualify_iso_test_model(&mut self, vendor: u16, device: u16) { + self.iso_caps.qualify(Policy::pci(vendor, device)); + } + /// Queue one USB2 isochronous service interval. The entire DMA extent must + /// stay live and unmodified until terminal completion or successful endpoint + /// cancellation. Buffers must not cross 64 KiB; maximum payload is the actual + /// endpoint's packet size times its advertised HS transactions (<=3072). + /// A full queue or late schedule is refused before any ring publication. + pub fn submit_iso( + &mut self, + slot: u8, + dci: u8, + buffer: u64, + length: usize, + ) -> Result { + self.endpoint_ready(slot, dci)?; + self.iso_caps.admit()?; + self.dma_profile.check(buffer, length)?; + if length > MAX_TD || buffer % MAX_TD as u64 + length as u64 > MAX_TD as u64 { + return Err(BlockError::Unsupported( + "isochronous TD crosses a 64 KiB boundary", + )); + } + let mfindex = self.registers.read32(self.runtime); + let caps = self.iso_caps; + let state = self.slot(slot)?; + let transfer = state.endpoints[usize::from(dci)].as_mut().unwrap(); + let queue = transfer + .iso + .as_mut() + .ok_or(BlockError::Unsupported("endpoint is not isochronous"))?; + if queue.recovery { + return Err(BlockError::Unsupported( + "isochronous endpoint requires cancellation", + )); + } + if length > queue.recipe.payload as usize { + return Err(BlockError::Unsupported( + "isochronous service payload exceeds descriptor", + )); + } + let trb = transfer.ring.address(); + if queue.active.len() >= RING_TRBS - 2 + || queue.active.iter().any(|active| active.trb == trb) + { + return Err(BlockError::Unsupported("isochronous ring is full")); + } + let interval = 1 << queue.recipe.exponent; + let (start, frame) = schedule(mfindex, caps, interval, queue.next)?; + let id = NEXT_TICKET + .try_update(Ordering::Relaxed, Ordering::Relaxed, |old| { + old.checked_add(1) + }) + .map_err(|_| BlockError::Unsupported("isochronous ticket identities exhausted"))?; + queue + .active + .try_reserve(1) + .map_err(|_| BlockError::NoDmaMemory)?; + let control = trb_control(queue.recipe, length, frame); + // Reserve identity before DMA publication. One TRB is a complete TD; + // no intermediate-error event can release a later contributor. + queue.active.push(Active { + id, + trb, + bytes: length, + }); + transfer.ring.push(&[(buffer, length as u32, control)]); + queue.next = Some((start + interval) % MICROFRAMES); + self.doorbell(slot, dci); + Ok(IsoTransfer { id, slot, dci, trb }) + } + + /// Poll an exact service interval. Ok (including packet-error statuses) is + /// terminal and releases that TD's buffer. Err is a transport/identity error; + /// retain all outstanding DMA until successful endpoint-wide cancel. None + /// means no terminal event. Dropped/retired tickets never name a new TD. + pub fn completed_iso( + &mut self, + ticket: &IsoTransfer, + ) -> Option> { + if let Err(error) = self.endpoint_ready(ticket.slot, ticket.dci) { + return Some(Err(error)); + } + let valid = self + .slot(ticket.slot) + .ok() + .and_then(|slot| slot.endpoints[usize::from(ticket.dci)].as_ref()) + .and_then(|transfer| transfer.iso.as_ref()) + .is_some_and(|queue| { + !queue.recovery + && queue + .active + .iter() + .any(|active| active.id == ticket.id && active.trb == ticket.trb) + }); + if !valid { + return Some(Err(BlockError::Unsupported( + "stale or foreign isochronous ticket", + ))); + } + // Missed-service and ring-xrun events may legally have no valid TRB + // pointer. They cannot complete an arbitrary ticket. Force a bounded + // endpoint-wide cancellation, retaining every contributor. + let index = self.pending.iter().position(|event| { + event.kind() == TRANSFER_EVENT + && event.slot() == ticket.slot + && event.endpoint() == ticket.dci + && (event.parameter == ticket.trb + || !matches!(event.code(), SUCCESS | SHORT_PACKET)) + })?; + let event = self.pending.remove(index); + if event.code() == INCOMPATIBLE_DEVICE { + // Incompatible Device requires Disable Slot (Linux handle_tx_event), + // not merely Stop/Reset/Set Dequeue. Keep permanent poison until a + // separate exclusive slot-retirement service establishes ownership. + let endpoint = self.slot(ticket.slot).unwrap().endpoints[usize::from(ticket.dci)] + .as_mut() + .unwrap(); + endpoint.poisoned = true; + return Some(Err(BlockError::Device { + status: INCOMPATIBLE_DEVICE, + })); + } + let queue = self.slot(ticket.slot).unwrap().endpoints[usize::from(ticket.dci)] + .as_mut() + .unwrap() + .iso + .as_mut() + .unwrap(); + let index = queue + .active + .iter() + .position(|active| active.id == ticket.id) + .unwrap(); + let result = if event.parameter != ticket.trb || event.control & EVENT_DATA != 0 { + Err(BlockError::Device { + status: event.code(), + }) + } else { + completion(event.code(), queue.active[index].bytes, event.residual()) + }; + if result.is_ok() { + queue.active.remove(index); + // A valid pointer identifies this TD, but other earlier service + // intervals may also have been missed without their own events. + queue.recovery = event.code() == MISSED_SERVICE; + } else { + queue.recovery = true; + } + Some(result) + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/stela-drivers/src/usb/xhci/iso/tests.rs b/crates/stela-drivers/src/usb/xhci/iso/tests.rs new file mode 100644 index 0000000000..af1cd0be62 --- /dev/null +++ b/crates/stela-drivers/src/usb/xhci/iso/tests.rs @@ -0,0 +1,937 @@ +use super::*; +use crate::bus::dma::RegionAllocator; +use alloc::collections::BTreeMap; +extern crate std; + +struct Td { + trb: u64, + buffer: u64, + bytes: usize, + control: u32, +} +struct Hardware { + commands: u64, + command_index: usize, + events: u64, + event_index: usize, + output: u64, + context_bytes: usize, + cursors: BTreeMap, + active: Vec<(u8, Td)>, + seen: Vec<(u32, u8)>, + mfindex: u32, + fail: Option, + silent: Option, + fatal: bool, + output_bytes: Vec, +} +impl Hardware { + fn word(address: u64) -> u32 { + assert!(address > 65536 && address.is_multiple_of(4)); + unsafe { (address as *const u32).read_volatile() } + } + fn long(address: u64) -> u64 { + assert!(address > 65536 && address.is_multiple_of(8)); + unsafe { (address as *const u64).read_volatile() } + } + fn state(&mut self, dci: u8, state: u32) { + let at = self.output + u64::from(dci) * self.context_bytes as u64; + unsafe { + (at as *mut u32).write_volatile(Self::word(at) & !7 | state); + } + } + fn event(&mut self, parameter: u64, code: u32, dci: u8, residual: usize, kind: u32) { + let at = self.events + (self.event_index % RING_TRBS * TRB) as u64; + unsafe { + (at as *mut u64).write_volatile(parameter); + ((at + 8) as *mut u32).write_volatile(code << 24 | residual as u32); + ((at + 12) as *mut u32).write_volatile( + 1 << 24 + | u32::from(dci) << 16 + | kind << 10 + | u32::from((self.event_index / RING_TRBS).is_multiple_of(2)), + ); + } + self.event_index += 1; + } + fn command(&mut self) { + let at = self.commands + (self.command_index % (RING_TRBS - 1) * TRB) as u64; + let parameter = Self::long(at); + let control = Self::word(at + 12); + assert_eq!( + control & CYCLE, + u32::from((self.command_index / (RING_TRBS - 1)).is_multiple_of(2)) + ); + let kind = control >> 10 & 63; + let dci = (control >> 16 & 31) as u8; + self.command_index += 1; + self.seen.push((kind, dci)); + if self.silent == Some(kind) { + return; + } + let code = if self.fail == Some(kind) { 17 } else { SUCCESS }; + if code == SUCCESS { + match kind { + CONFIGURE_ENDPOINT => { + let add = Self::word(parameter + 4); + let drop = Self::word(parameter); + for ep in 2..32u8 { + if drop & (1 << ep) != 0 { + self.state(ep, 0); + self.cursors.remove(&ep); + } + if add & (1 << ep) == 0 { + continue; + } + let from = parameter + (u64::from(ep) + 1) * self.context_bytes as u64; + let to = self.output + u64::from(ep) * self.context_bytes as u64; + unsafe { + core::ptr::copy_nonoverlapping( + from as *const u8, + to as *mut u8, + self.context_bytes, + ); + } + let info2 = Self::word(to + 4); + assert!(matches!(info2 >> 3 & 7, 1 | 5)); + assert_eq!(info2 & 6, 0); + assert_eq!(Self::word(to + 16) & 0xffff, Self::word(to + 16) >> 16); + self.state(ep, ENDPOINT_RUNNING); + } + } + STOP_ENDPOINT => self.state(dci, ENDPOINT_STOPPED), + RESET_ENDPOINT => self.state(dci, ENDPOINT_STOPPED), + SET_DEQUEUE => { + let endpoint = self.output + u64::from(dci) * self.context_bytes as u64; + assert_eq!(Self::word(endpoint) & 7, ENDPOINT_STOPPED); + let base = Self::long(endpoint + 8) & !15; + self.cursors.insert( + dci, + ( + base, + ((parameter & !15) - base) as usize / TRB, + parameter as u32 & 1, + ), + ); + let old = core::mem::take(&mut self.active); + for (ep, td) in old { + if ep == dci { + self.event(td.trb, 26, dci, td.bytes, TRANSFER_EVENT); + } else { + self.active.push((ep, td)); + } + } + } + _ => panic!("unexpected command {kind}"), + } + } + self.event(at, code, 0, 0, COMMAND_COMPLETION); + } + fn transfer(&mut self, dci: u8) { + let ep = self.output + u64::from(dci) * self.context_bytes as u64; + let initial = Self::long(ep + 8); + let cursor = self + .cursors + .entry(dci) + .or_insert((initial & !15, 0, initial as u32 & 1)); + let trb = cursor.0 + (cursor.1 * TRB) as u64; + let control = Self::word(trb + 12); + let bytes = (Self::word(trb + 8) & 0x1ffff) as usize; + assert_eq!(control & CYCLE, cursor.2); + assert_eq!(control >> 10 & 63, ISOCH); + assert_ne!(control & IOC, 0); + let packet = Self::word(ep + 4) >> 16; + assert_eq!( + control >> 16 & 15, + (bytes as u32).div_ceil(packet).max(1) - 1 + ); + let buffer = Self::long(trb); + assert!(buffer % 65536 + bytes as u64 <= 65536); + assert!( + !self + .active + .iter() + .any(|(ep, td)| *ep == dci && td.trb == trb) + ); + self.active.push(( + dci, + Td { + trb, + buffer, + bytes, + control, + }, + )); + cursor.1 += 1; + if cursor.1 == RING_TRBS - 1 { + let link = cursor.0 + ((RING_TRBS - 1) * TRB) as u64; + assert_eq!(Self::long(link), cursor.0); + assert_eq!(Self::word(link + 12) & 1, cursor.2); + assert_eq!(Self::word(link + 12) >> 10 & 63, LINK); + assert_ne!(Self::word(link + 12) & TOGGLE, 0); + cursor.1 = 0; + cursor.2 ^= 1; + } + self.state(dci, ENDPOINT_RUNNING); + } + fn complete(&mut self, dci: u8, index: usize, code: u32, residual: usize) { + let at = self + .active + .iter() + .enumerate() + .filter(|(_, (ep, _))| *ep == dci) + .nth(index) + .unwrap() + .0; + let (_, td) = self.active.remove(at); + if code == 6 { + self.state(dci, ENDPOINT_HALTED); + } + if matches!(code, SUCCESS | SHORT_PACKET) && residual <= td.bytes { + let n = td.bytes - residual; + if dci & 1 != 0 { + unsafe { + core::ptr::write_bytes(td.buffer as *mut u8, 0x5a, n); + } + } else { + self.output_bytes.extend_from_slice(unsafe { + core::slice::from_raw_parts(td.buffer as *const u8, n) + }); + } + } + self.event(td.trb, code, dci, residual, TRANSFER_EVENT); + } +} +struct Model(Rc>); +impl Registers for Model { + fn read32(&mut self, offset: usize) -> u32 { + let model = self.0.borrow(); + if offset == 0x800 { + model.mfindex + } else if offset == 0x40 + USBSTS && model.fatal { + HSE + } else { + 0 + } + } + fn write32(&mut self, offset: usize, value: u32) { + match offset { + 0x1000 => self.0.borrow_mut().command(), + 0x1004 => self.0.borrow_mut().transfer(value as u8), + _ => {} + } + } +} +fn endpoint(address: u8, speed: u8) -> Endpoint { + Endpoint { + address, + attributes: 1, + max_packet: if speed == FULL_SPEED { + 192 + } else { + 1024 | 2 << 11 + }, + interval: 1, + companion: None, + } +} +fn controller( + dma: &mut dyn DmaAllocator, + speed: u8, + context_bytes: usize, + cfc: bool, +) -> (Controller, Rc>) { + let commands = Ring::new(dma).unwrap(); + let events = dma.allocate(RING_TRBS * TRB, RING_TRBS * TRB).unwrap(); + let output = dma.allocate(32 * context_bytes, 64).unwrap(); + let model = Rc::new(RefCell::new(Hardware { + commands: commands.buffer.physical(), + command_index: 0, + events: events.physical(), + event_index: 0, + output: output.physical(), + context_bytes, + cursors: BTreeMap::new(), + active: Vec::new(), + seen: Vec::new(), + mfindex: 0x3ff0, + fail: None, + silent: None, + fatal: false, + output_bytes: Vec::new(), + })); + let mut slots = vec![None]; + slots.push(Some(Slot { + attachment: Attachment { + root_port: 1, + route: 0, + tier: 0, + speed, + translator: None, + }, + retiring: false, + input: dma.allocate(33 * context_bytes, 64).unwrap(), + _output: output, + context: [u32::from(speed) << 20 | 1 << 27, 1 << 16, 0, 0], + endpoints: Default::default(), + control: dma.allocate(CONTROL_BYTES, CONTROL_BYTES).unwrap(), + speed, + current_configuration: Some(1), + })); + ( + Controller { + registers: Box::new(Model(model.clone())), + clock: Clock { + ticks_per_microsecond: 1, + }, + operational: 0x40, + runtime: 0x800, + doorbells: 0x1000, + context_bytes, + dma_profile: dma::Profile::SPEC, + max_primary_streams: 4, + stream_policy: streams::Policy::Unknown, + iso_caps: { + let mut caps = Capabilities::new(0x110, 0xb, if cfc { 1 << 11 } else { 0 }); + caps.qualify(Policy::pci(0x1022, 0x15b6)); + caps + }, + max_slots: 1, + max_ports: 1, + port_major: vec![2], + dcbaa: dma.allocate(16, 64).unwrap(), + _scratchpads: Vec::new(), + commands, + events, + _event_table: dma.allocate(16, 64).unwrap(), + event_index: 0, + event_cycle: true, + slots, + slot_ownership: vec![reset::Ownership::Vacant, reset::Ownership::Enabled], + pending: Vec::new(), + error: None, + command_poisoned: false, + location: String::from("native iso model"), + }, + model, + ) +} + +#[test] +fn queued_native_iso_contexts_and_scheduling_complete_actual_dma_for_both_directions() { + for speed in [FULL_SPEED, HIGH_SPEED] { + for context_bytes in [32, 64] { + for cfc in [false, true] { + let mut backing = vec![0u64; 128 * 1024]; + let start = backing.as_mut_ptr() as u64; + let mut dma = + unsafe { RegionAllocator::new(start..start + backing.len() as u64 * 8) }; + let (mut controller, model) = controller(&mut dma, speed, context_bytes, cfc); + controller.qualify_iso_test_model(0x1022, 0x15b6); + let endpoints = [endpoint(1, speed), endpoint(0x82, speed)]; + controller.configure(1, &endpoints, None, &mut dma).unwrap(); + let out = dma.allocate(4096, 4096).unwrap(); + let input = dma.allocate(4096, 4096).unwrap(); + unsafe { + core::ptr::write_bytes(out.as_ptr(), 0xa5, out.len()); + } + let mut tickets = Vec::new(); + for n in 0..32 { + for endpoint in &endpoints { + tickets.push( + controller + .submit_iso( + 1, + endpoint.dci(), + if endpoint.is_in() { + input.physical() + } else { + out.physical() + } + n * 32, + 32, + ) + .unwrap(), + ); + } + } + assert_eq!(model.borrow().active.len(), 64); + for dci in [2, 5] { + let fields: Vec = model + .borrow() + .active + .iter() + .filter(|(ep, _)| *ep == dci) + .map(|(_, td)| td.control) + .collect(); + assert_eq!(fields[0] & SIA, 0); + assert_eq!(fields[1] & SIA, if cfc { 0 } else { SIA }); + for n in 0..32 { + model.borrow_mut().complete( + dci, + 0, + if n % 2 == 0 { SUCCESS } else { SHORT_PACKET }, + if n % 2 == 0 { 0 } else { 4 }, + ); + } + } + for (n, ticket) in tickets.iter().enumerate() { + let completion = controller.completed_iso(ticket).unwrap().unwrap(); + assert_eq!(completion.bytes, if n / 2 % 2 == 0 { 32 } else { 28 }); + assert!(controller.completed_iso(ticket).unwrap().is_err()); + } + assert_eq!(model.borrow().output_bytes.len(), 16 * 32 + 16 * 28); + assert_eq!(&input.bytes()[..32], &[0x5a; 32]); + } + } + } +} + +#[test] +fn packet_failures_are_terminal_but_invalid_residual_and_transport_faults_retain_dma() { + for (code, status) in [ + (23, IsoStatus::MissedService), + (4, IsoStatus::Transaction), + (3, IsoStatus::Babble), + (18, IsoStatus::Bandwidth), + (31, IsoStatus::BufferOverrun), + ] { + let mut backing = vec![0u64; 32 * 1024]; + let start = backing.as_mut_ptr() as u64; + let mut dma = unsafe { RegionAllocator::new(start..start + backing.len() as u64 * 8) }; + let (mut controller, model) = controller(&mut dma, HIGH_SPEED, 32, true); + controller + .configure(1, &[endpoint(0x81, HIGH_SPEED)], None, &mut dma) + .unwrap(); + let buffer = dma.allocate(4096, 4096).unwrap(); + let ticket = controller.submit_iso(1, 3, buffer.physical(), 128).unwrap(); + model.borrow_mut().complete(3, 0, code, 32); + assert_eq!( + controller.completed_iso(&ticket).unwrap().unwrap().status, + status + ); + if status == IsoStatus::MissedService { + assert!(controller.submit_iso(1, 3, buffer.physical(), 128).is_err()); + controller.cancel(1, 3).unwrap(); + } + let ticket = controller.submit_iso(1, 3, buffer.physical(), 128).unwrap(); + model.borrow_mut().complete(3, 0, SUCCESS, 129); + assert!(controller.completed_iso(&ticket).unwrap().is_err()); + assert!(controller.submit_iso(1, 3, buffer.physical(), 128).is_err()); + controller.cancel(1, 3).unwrap(); + assert!(controller.completed_iso(&ticket).unwrap().is_err()); + } +} + +#[test] +fn cancellation_acknowledges_all_intervals_and_stale_events_before_reuse() { + for failure in [None, Some(STOP_ENDPOINT), Some(SET_DEQUEUE)] { + let mut backing = vec![0u64; 32 * 1024]; + let start = backing.as_mut_ptr() as u64; + let mut dma = unsafe { RegionAllocator::new(start..start + backing.len() as u64 * 8) }; + let (mut controller, model) = controller(&mut dma, HIGH_SPEED, 64, true); + controller + .configure(1, &[endpoint(0x81, HIGH_SPEED)], None, &mut dma) + .unwrap(); + let buffer = dma.allocate(4096, 4096).unwrap(); + let tickets: Vec<_> = (0..32) + .map(|n| { + controller + .submit_iso(1, 3, buffer.physical() + n * 32, 32) + .unwrap() + }) + .collect(); + model.borrow_mut().fail = failure; + let result = controller.cancel(1, 3); + if failure.is_some() { + assert!(result.is_err()); + assert!(controller.submit_iso(1, 3, buffer.physical(), 32).is_err()); + assert_eq!( + controller.slot(1).unwrap().endpoints[3] + .as_ref() + .unwrap() + .iso + .as_ref() + .unwrap() + .active + .len(), + 32 + ); + assert_eq!(model.borrow().active.len(), 32); + } else { + result.unwrap(); + assert!(controller.pending.is_empty()); + assert!(model.borrow().active.is_empty()); + for ticket in tickets { + assert!(controller.completed_iso(&ticket).unwrap().is_err()); + } + controller.submit_iso(1, 3, buffer.physical(), 32).unwrap(); + } + } +} + +#[test] +fn occupancy_wrap_schedule_and_descriptor_failures_do_not_overwrite_owned_trbs() { + let mut backing = vec![0u64; 32 * 1024]; + let start = backing.as_mut_ptr() as u64; + let mut dma = unsafe { RegionAllocator::new(start..start + backing.len() as u64 * 8) }; + let (mut controller, model) = controller(&mut dma, HIGH_SPEED, 32, true); + controller + .configure(1, &[endpoint(0x81, HIGH_SPEED)], None, &mut dma) + .unwrap(); + let buffer = dma.allocate(4096, 4096).unwrap(); + let tickets: Vec<_> = (0..RING_TRBS - 2) + .map(|_| controller.submit_iso(1, 3, buffer.physical(), 16).unwrap()) + .collect(); + let before = controller.slot(1).unwrap().endpoints[3] + .as_ref() + .unwrap() + .ring + .address(); + assert!(controller.submit_iso(1, 3, buffer.physical(), 16).is_err()); + assert_eq!( + controller.slot(1).unwrap().endpoints[3] + .as_ref() + .unwrap() + .ring + .address(), + before + ); + for ticket in tickets { + model.borrow_mut().complete(3, 0, SUCCESS, 0); + assert_eq!( + controller.completed_iso(&ticket).unwrap().unwrap().bytes, + 16 + ); + } + for _ in 0..300 { + let ticket = controller.submit_iso(1, 3, buffer.physical(), 16).unwrap(); + model.borrow_mut().complete(3, 0, SUCCESS, 0); + controller.completed_iso(&ticket).unwrap().unwrap(); + } + model.borrow_mut().mfindex = 1024; + assert!(controller.submit_iso(1, 3, buffer.physical(), 16).is_err()); + controller.cancel(1, 3).unwrap(); + controller.submit_iso(1, 3, buffer.physical(), 16).unwrap(); + assert!(controller.submit(1, 3, buffer.physical(), 16).is_err()); + for speed in [LOW_SPEED, SUPER_SPEED, SUPER_SPEED_PLUS] { + assert!(Recipe::new(&endpoint(0x81, HIGH_SPEED), speed).is_err()); + } + let mut endpoint = endpoint(0x81, HIGH_SPEED); + endpoint.max_packet |= 3 << 11; + assert!(Recipe::new(&endpoint, HIGH_SPEED).is_err()); + endpoint.max_packet = 1024; + endpoint.attributes = 0x31; + assert!(Recipe::new(&endpoint, HIGH_SPEED).is_err()); +} + +#[test] +fn acknowledged_endpoint_drop_allows_fresh_rings_and_failure_quarantines_every_selected_owner() { + for failure in [ + None, + Some(CONFIGURE_ENDPOINT), + Some(STOP_ENDPOINT), + Some(SET_DEQUEUE), + ] { + let mut backing = vec![0u64; 32 * 1024]; + let start = backing.as_mut_ptr() as u64; + let mut dma = unsafe { RegionAllocator::new(start..start + backing.len() as u64 * 8) }; + let (mut controller, model) = controller(&mut dma, HIGH_SPEED, 64, true); + let endpoints = [ + endpoint(1, HIGH_SPEED), + endpoint(0x82, HIGH_SPEED), + endpoint(0x83, HIGH_SPEED), + ]; + controller.configure(1, &endpoints, None, &mut dma).unwrap(); + let buffer = dma.allocate(4096, 4096).unwrap(); + let a = controller.submit_iso(1, 2, buffer.physical(), 32).unwrap(); + let b = controller + .submit_iso(1, 5, buffer.physical() + 32, 32) + .unwrap(); + let keep = controller + .submit_iso(1, 7, buffer.physical() + 64, 32) + .unwrap(); + let old_ring = controller.slot(1).unwrap().endpoints[2] + .as_ref() + .unwrap() + .ring + .buffer + .physical(); + model.borrow_mut().fail = failure; + let result = controller.deconfigure(1, &endpoints[..2]); + if failure.is_some() { + assert!(result.is_err()); + let slot = controller.slot(1).unwrap(); + assert!(slot.endpoints[2].as_ref().unwrap().poisoned); + assert!(slot.endpoints[5].as_ref().unwrap().poisoned); + assert!(!slot.endpoints[7].as_ref().unwrap().poisoned); + assert!(controller.submit_iso(1, 2, buffer.physical(), 32).is_err()); + assert!( + controller + .configure(1, &endpoints[..2], None, &mut dma) + .is_err() + ); + } else { + result.unwrap(); + assert!(controller.slot(1).unwrap().endpoints[2].is_none()); + assert!(controller.slot(1).unwrap().endpoints[5].is_none()); + assert!(controller.slot(1).unwrap().endpoints[7].is_some()); + controller + .configure(1, &endpoints[..2], None, &mut dma) + .unwrap(); + assert_ne!( + old_ring, + controller.slot(1).unwrap().endpoints[2] + .as_ref() + .unwrap() + .ring + .buffer + .physical() + ); + assert!(controller.completed_iso(&a).unwrap().is_err()); + assert!(controller.completed_iso(&b).unwrap().is_err()); + model.borrow_mut().complete(7, 0, SUCCESS, 0); + controller.completed_iso(&keep).unwrap().unwrap(); + let fresh = controller.submit_iso(1, 2, buffer.physical(), 32).unwrap(); + model + .borrow_mut() + .event(a.trb, SUCCESS, 2, 0, TRANSFER_EVENT); + assert!(controller.completed_iso(&fresh).is_none()); + model.borrow_mut().complete(2, 0, SUCCESS, 0); + controller.completed_iso(&fresh).unwrap().unwrap(); + } + } +} + +#[test] +fn invalid_descriptor_route_teardown_and_submission_have_no_dma_publication() { + let mut backing = vec![0u64; 32 * 1024]; + let start = backing.as_mut_ptr() as u64; + let mut dma = unsafe { RegionAllocator::new(start..start + backing.len() as u64 * 8) }; + let (mut controller, model) = controller(&mut dma, HIGH_SPEED, 32, true); + let endpoint = endpoint(0x81, HIGH_SPEED); + controller.slot(1).unwrap().attachment.tier = 1; + assert!( + controller + .configure(1, &[endpoint], None, &mut dma) + .is_err() + ); + assert!(model.borrow().seen.is_empty()); + controller.slot(1).unwrap().attachment.tier = 0; + controller + .configure(1, &[endpoint], None, &mut dma) + .unwrap(); + let buffer = dma.allocate(4096, 4096).unwrap(); + let commands = model.borrow().seen.len(); + let remaining = dma.remaining(); + assert!(controller.deconfigure(1, &[endpoint, endpoint]).is_err()); + assert_eq!(model.borrow().seen.len(), commands); + assert!( + controller + .submit_iso(1, 3, buffer.physical(), 3073) + .is_err() + ); + assert!( + controller + .submit_iso(1, 3, buffer.physical().next_multiple_of(65536) - 1, 32) + .is_err() + ); + assert_eq!(dma.remaining(), remaining); + assert!(model.borrow().active.is_empty()); + assert!(controller.clear(1, &endpoint).is_err()); + assert_eq!(model.borrow().seen.len(), commands); + let ticket = controller.submit_iso(1, 3, buffer.physical(), 0).unwrap(); + assert_eq!(model.borrow().active[0].1.control >> 16 & 15, 0); + model.borrow_mut().complete(3, 0, SUCCESS, 0); + assert_eq!(controller.completed_iso(&ticket).unwrap().unwrap().bytes, 0); +} + +#[test] +fn silent_cancellation_and_fatal_controller_status_never_release_queued_buffers() { + for silent in [STOP_ENDPOINT, SET_DEQUEUE] { + let mut backing = vec![0u64; 32 * 1024]; + let start = backing.as_mut_ptr() as u64; + let mut dma = unsafe { RegionAllocator::new(start..start + backing.len() as u64 * 8) }; + let (mut controller, model) = controller(&mut dma, HIGH_SPEED, 32, true); + controller + .configure(1, &[endpoint(0x81, HIGH_SPEED)], None, &mut dma) + .unwrap(); + let buffer = dma.allocate(4096, 4096).unwrap(); + let ticket = controller.submit_iso(1, 3, buffer.physical(), 32).unwrap(); + model.borrow_mut().silent = Some(silent); + assert!(controller.cancel(1, 3).is_err()); + assert!(controller.command_poisoned); + assert_eq!( + controller.slot(1).unwrap().endpoints[3] + .as_ref() + .unwrap() + .iso + .as_ref() + .unwrap() + .active + .len(), + 1 + ); + assert!(controller.completed_iso(&ticket).unwrap().is_err()); + } + let mut backing = vec![0u64; 32 * 1024]; + let start = backing.as_mut_ptr() as u64; + let mut dma = unsafe { RegionAllocator::new(start..start + backing.len() as u64 * 8) }; + let (mut controller, model) = controller(&mut dma, HIGH_SPEED, 32, true); + controller + .configure(1, &[endpoint(0x81, HIGH_SPEED)], None, &mut dma) + .unwrap(); + let buffer = dma.allocate(4096, 4096).unwrap(); + let ticket = controller.submit_iso(1, 3, buffer.physical(), 32).unwrap(); + model.borrow_mut().fatal = true; + assert!(controller.completed_iso(&ticket).unwrap().is_err()); + assert!(controller.cancel(1, 3).is_err()); + assert_eq!( + controller.slot(1).unwrap().endpoints[3] + .as_ref() + .unwrap() + .iso + .as_ref() + .unwrap() + .active + .len(), + 1 + ); +} + +#[test] +fn actual_profile_scope_rejects_unknown_raw_and_legacy_controllers() { + for vendor in [0, 0x1022, 0x1b36] { + for device in [ + 0, 0x15b6, 0x15b7, 0x15b8, 0x43fc, 0x15e0, 0x15e5, 0x43bb, 0x000d, + ] { + let mut caps = Capabilities::new(0x110, 0, 0); + assert!(caps.admit().is_err()); + caps.qualify(Policy::pci(vendor, device)); + assert_eq!( + caps.admit().is_ok(), + vendor == 0x1022 && matches!(device, 0x15b6 | 0x15b7 | 0x15b8 | 0x43fc) + || vendor == 0x1b36 && device == 0x000d + ); + } + } + let mut old = Capabilities::new(0x96, 0, 0); + old.qualify(Policy::Qemu); + assert!(old.admit().is_err()); +} + +#[test] +#[ignore = "requires immutable pinned Linux isochronous helper trace"] +fn unchanged_linux_iso_context_scheduling_burst_and_terminal_completion() { + use sha2::{Digest, Sha256}; + let trace = std::fs::read_to_string( + std::env::var("STELA_XHCI_ISO_ORACLE").expect("path to fresh source oracle trace"), + ) + .unwrap(); + assert_eq!( + alloc::format!("{:x}", Sha256::digest(trace.as_bytes())), + "8dff7cfded211423e137dde9864585635f4ac2467fe7c93057081a0c925927e6" + ); + let mut count = 0; + for line in trace.lines() { + let mut fields = line.split_whitespace(); + let kind = fields.next().unwrap(); + let values: Vec = fields.map(|v| v.parse().unwrap()).collect(); + match kind { + "E" => { + assert_eq!(values.len(), 8); + let speed = if values[0] == 2 { + FULL_SPEED + } else { + HIGH_SPEED + }; + let ep = Endpoint { + address: if values[3] != 0 { 0x81 } else { 1 }, + attributes: 1, + max_packet: values[4] as u16 | (values[2] as u16) << 11, + interval: values[1] as u8, + companion: None, + }; + match Recipe::new(&ep, speed) { + Ok(recipe) => { + let context = recipe.context(); + assert_eq!( + [context.info, context.info2, context.tx_info], + [values[5] as u32, values[6] as u32, values[7] as u32] + ); + } + Err(_) => assert!(values[5] >> 16 > 12), + } + } + "S" => { + assert_eq!(values.len(), 8); + let caps = Capabilities::new( + 0x110, + values[1] as u32, + if values[2] != 0 { 1 << 11 } else { 0 }, + ); + let next = if values[4] < 0 { + None + } else { + Some(values[4] as u32) + }; + match schedule(values[0] as u32, caps, values[3] as u32, next) { + Ok((start, field)) => { + assert_eq!(values[7], 1); + assert_eq!(start, values[5] as u32); + assert_eq!( + field, + if values[6] != 0 { + (start / 8) << 20 + } else { + SIA + } + ); + } + Err(_) => assert_eq!(values[7], 0), + } + } + "C" => { + assert_eq!(values.len(), 6); + assert_eq!(values[4], 1); // process_isoc_td reached finish callback. + if matches!(values[0], 6 | 22) { + // The original finish path still requires halt/slot recovery: + // its packet-status assignment is not a DMA-release ACK. + assert!(completion(values[0] as u32, 128, values[1] as usize).is_err()); + assert_eq!(values[3], -71); + assert_eq!(values[5], i64::from(values[0] == 6)); + } else { + assert_eq!(values[5], 0); + let packet = completion(values[0] as u32, 128, values[1] as usize).unwrap(); + assert_eq!(packet.bytes, values[2] as usize); + assert_eq!( + match packet.status { + IsoStatus::Success | IsoStatus::Short => 0, + IsoStatus::MissedService => -18, + IsoStatus::Transaction => -71, + IsoStatus::Babble | IsoStatus::BufferOverrun => -75, + IsoStatus::Bandwidth => -70, + }, + values[3] + ); + } + } + "B" => { + assert_eq!(values.len(), 3); + let recipe = Recipe::new(&endpoint(0x81, HIGH_SPEED), HIGH_SPEED).unwrap(); + let field = trb_control(recipe, values[0] as usize * 1024, 0); + assert_eq!(field >> 7 & 3, values[1] as u32); + assert_eq!(field >> 16 & 15, values[2] as u32); + } + _ => panic!("unknown source trace row"), + } + count += 1; + } + assert_eq!(count, 4656); +} + +#[test] +fn transferless_errors_stalls_and_incompatible_slots_never_release_an_arbitrary_ticket() { + for code in [6, 14, 15, 22, 23, 36, 99] { + let mut backing = vec![0u64; 32 * 1024]; + let start = backing.as_mut_ptr() as u64; + let mut dma = unsafe { RegionAllocator::new(start..start + backing.len() as u64 * 8) }; + let (mut controller, model) = controller(&mut dma, HIGH_SPEED, 32, true); + controller + .configure(1, &[endpoint(0x81, HIGH_SPEED)], None, &mut dma) + .unwrap(); + let buffer = dma.allocate(4096, 4096).unwrap(); + let ticket = controller.submit_iso(1, 3, buffer.physical(), 32).unwrap(); + let other = controller + .submit_iso(1, 3, buffer.physical() + 32, 32) + .unwrap(); + if code == 6 || code == 22 { + model.borrow_mut().complete(3, 0, code, 0); + } else { + model.borrow_mut().event(0, code, 3, 0, TRANSFER_EVENT); + } + assert!(controller.completed_iso(&ticket).unwrap().is_err()); + assert_eq!( + controller.slot(1).unwrap().endpoints[3] + .as_ref() + .unwrap() + .iso + .as_ref() + .unwrap() + .active + .len(), + 2 + ); + assert!(controller.completed_iso(&other).unwrap().is_err()); + assert!( + controller + .submit_iso(1, 3, buffer.physical() + 64, 32) + .is_err() + ); + if code == 22 { + let n = model.borrow().seen.len(); + assert!(controller.cancel(1, 3).is_err()); + assert_eq!(model.borrow().seen.len(), n); + } else { + controller.cancel(1, 3).unwrap(); + assert!(model.borrow().active.is_empty()); + assert!(controller.completed_iso(&ticket).unwrap().is_err()); + controller.submit_iso(1, 3, buffer.physical(), 32).unwrap(); + if code == 6 { + assert!( + model + .borrow() + .seen + .iter() + .any(|(kind, _)| *kind == RESET_ENDPOINT) + ); + } + } + } +} + +#[test] +#[ignore = "requires immutable pinned Linux AMD PCI quirk and PLL trace"] +fn unchanged_linux_actual_amd_pci_profiles_and_saved_smbus_do_not_inherit_legacy_quirks() { + use sha2::{Digest, Sha256}; + let trace = std::fs::read_to_string( + std::env::var("STELA_XHCI_AMD_PCI_ORACLE").expect("path to fresh source oracle trace"), + ) + .unwrap(); + assert_eq!( + alloc::format!("{:x}", Sha256::digest(trace.as_bytes())), + "f15c7bae3478f2cbf04438ef5fa64d24799ee708dc73d32fec4d1f687c4e57b9" + ); + let mut count = 0; + let mut legacy_positive = false; + let mut actual_negative = 0; + for line in trace.lines() { + let mut fields = line.split_whitespace(); + let kind = fields.next().unwrap(); + let values: Vec = fields.map(|v| v.parse().unwrap()).collect(); + assert_eq!(values.len(), 5); + match kind { + "P" => { + assert!(matches!(values[0], 0x15b6 | 0x15b7 | 0x15b8 | 0x43fc)); + let mut caps = Capabilities::new(values[2] as u16, 0, 0); + caps.qualify(Policy::pci(0x1022, values[0] as u16)); + caps.admit().unwrap(); + // xHCI>=1.2 permits runtime PM generically; this cold polled + // backend does not claim a suspend/runtime-power service. + assert_eq!(values[3], if values[2] >= 0x120 { 1 << 33 } else { 0 }); + assert_eq!(values[4], 0); + } + "L" => { + if values[0] == 0x1022 && values[1] == 0x790b { + assert_eq!(values[3], 0); + actual_negative += 1; + } + legacy_positive |= values[3] != 0; + } + _ => panic!("unknown PCI source trace"), + } + count += 1; + } + assert_eq!(count, 4096); + assert_eq!(actual_negative, 256); + assert!(legacy_positive); +} diff --git a/crates/stela-drivers/src/usb/xhci/reset/tests.rs b/crates/stela-drivers/src/usb/xhci/reset/tests.rs index de6b800da3..569da56b1c 100644 --- a/crates/stela-drivers/src/usb/xhci/reset/tests.rs +++ b/crates/stela-drivers/src/usb/xhci/reset/tests.rs @@ -694,6 +694,7 @@ pub(crate) fn fixture( dma_profile: super::super::dma::Profile::SPEC, max_primary_streams: 4, stream_policy: streams::Policy::Standard, + iso_caps: iso::Capabilities::new(0x100, 0, 0), max_slots, max_ports: 1, port_major: vec![if speed >= SUPER_SPEED { 3 } else { 2 }], diff --git a/crates/stela-drivers/src/usb/xhci/streams.rs b/crates/stela-drivers/src/usb/xhci/streams.rs index 6e93516828..289a26122c 100644 --- a/crates/stela-drivers/src/usb/xhci/streams.rs +++ b/crates/stela-drivers/src/usb/xhci/streams.rs @@ -752,6 +752,7 @@ mod tests { dma_profile: dma::Profile::SPEC, max_primary_streams: 16, stream_policy: Policy::Standard, + iso_caps: iso::Capabilities::new(0x100, 0, 0), max_slots: 1, max_ports: 1, port_major: vec![3], diff --git a/crates/stela-drivers/src/usb/xhci/teardown.rs b/crates/stela-drivers/src/usb/xhci/teardown.rs new file mode 100644 index 0000000000..b01c7713d4 --- /dev/null +++ b/crates/stela-drivers/src/usb/xhci/teardown.rs @@ -0,0 +1,85 @@ +// SPDX-License-Identifier: GPL-2.0-only +// Endpoint retirement follows pinned Linux xhci.c/xhci-mem.c and xHCI 4.6.6. +// Copyright (C) 2008 Intel Corp. Author: Sarah Sharp. +//! Acknowledged endpoint removal before a class changes its alternate setting. +use super::*; + +impl Controller { + /// Quiesce and remove the exclusively owned endpoint DCIs before changing + /// a USB interface. This does not issue SET_INTERFACE: the class owner must + /// perform that actual request, then configure fresh endpoints. All selected + /// DCIs are validated before any mutation. Every old TD requires successful + /// Stop/Reset/Set Dequeue + drain, followed by Configure Endpoint Drop ACK. + /// Any uncertain step retains and poisons every selected endpoint. Success + /// permits DMA reuse; old ring allocations remain boot-lived and are never + /// handed to a replacement endpoint, preventing late-address aliasing. + pub fn deconfigure(&mut self, slot: u8, endpoints: &[Endpoint]) -> Result<(), BlockError> { + self.live_slot(slot)?; + self.ready()?; + if endpoints.is_empty() { + return Err(BlockError::Unsupported("empty endpoint teardown")); + } + let mut selected = 0u32; + for endpoint in endpoints { + let dci = endpoint.dci(); + if endpoint.address & 0x70 != 0 || dci < 2 || selected & (1 << dci) != 0 { + return Err(BlockError::Unsupported( + "invalid or duplicate teardown endpoint", + )); + } + self.endpoint_ready(slot, dci)?; + selected |= 1 << dci; + } + let result = self.deconfigure_inner(slot, endpoints, selected); + if result.is_err() { + for endpoint in endpoints { + if let Some(transfer) = + self.slot(slot)?.endpoints[usize::from(endpoint.dci())].as_mut() + { + transfer.poisoned = true; + } + } + } + result + } + fn deconfigure_inner( + &mut self, + slot: u8, + endpoints: &[Endpoint], + selected: u32, + ) -> Result<(), BlockError> { + for endpoint in endpoints { + self.cancel_inner(slot, endpoint.dci())?; + } + self.clear_input(slot)?; + let context = self.context(); + let input = { + let state = self.slot(slot)?; + let last = (2..32usize) + .rev() + .find(|dci| selected & (1 << dci) == 0 && state.endpoints[*dci].is_some()) + .unwrap_or(1); + let mut words = state.context; + words[0] = words[0] & !(31 << 27) | (last as u32) << 27; + state.input.write(0, selected); + state.input.write(4, 1u32); + for (n, word) in words.iter().enumerate() { + state.input.write(context + 4 * n, *word); + } + (state.input.physical(), words) + }; + self.command(input.0, 0, CONFIGURE_ENDPOINT << 10 | u32::from(slot) << 24)?; + self.ready()?; + self.pending.retain(|event| { + !(event.kind() == TRANSFER_EVENT + && event.slot() == slot + && selected & (1 << event.endpoint()) != 0) + }); + let state = self.slot(slot)?; + state.context = input.1; + for endpoint in endpoints { + state.endpoints[usize::from(endpoint.dci())] = None; + } + Ok(()) + } +} diff --git a/crates/stela-drivers/tests/reference/xhci_amd_pci_oracle.py b/crates/stela-drivers/tests/reference/xhci_amd_pci_oracle.py new file mode 100644 index 0000000000..5e9be923f9 --- /dev/null +++ b/crates/stela-drivers/tests/reference/xhci_amd_pci_oracle.py @@ -0,0 +1,64 @@ +#!/usr/bin/env python3 +"""Execute unchanged pinned PCI quirks + AMD chipset/PLL discovery on saved IDs. +Usage: xhci_amd_pci_oracle.py FLAT_REFERENCE_DIRECTORY NEW_OUTPUT_DIRECTORY +All PCI reads are immutable logical fixtures. No actual host access or Linux ABI. +""" +import hashlib,json,re,subprocess,sys +from pathlib import Path +source,out=map(Path,sys.argv[1:]) +expected={'xhci-pci.c':'56659d07018ff7ae99334e910065c7bf46f80deb65c4445443ee52313422d6e8','xhci.h':'44ca06ce699192d60302896df23ef3ee243abe979ac5f3c759de9830ec311cc0','pci-quirks.c':'490a44a2447031469c30f734380580fe45facf03d19a7c03e075434338c8de64','pci_ids.h':'020fac001871c0f8441c1294f787231fb6cfbf2c55915ca8f918262e2db4487c'} +texts={} +for name,digest in expected.items(): + raw=(source/name).read_bytes();assert hashlib.sha256(raw).hexdigest()==digest,name;texts[name]=raw.decode() +out.mkdir(parents=True,exist_ok=False) +fragments=[] +def function(file,name): + text=texts[file];m=re.search(r'^(?:static\s+)?(?:int|bool|void)\s+'+name+r'\([^;{}]*?\)\n\{',text,re.M);assert m,name + at,depth=m.end(),1 + while depth:depth+=(text[at]=='{')-(text[at]=='}');at+=1 + value=text[m.start():at];fragments.append(dict(source=file,function=name,sha256=hashlib.sha256(value.encode()).hexdigest()));return value +# Definitions used by the entire original PCI quirk function are retained. +defines='\n'.join(line for line in texts['xhci-pci.c'].splitlines() if line.startswith('#define PCI_')) +defines+='\n'+'\n'.join(line for line in texts['xhci.h'].splitlines() if re.match(r'#define\s+XHCI_\w+\s+BIT_ULL\(',line)) +prelude=r''' +#include +#include +#include +typedef uint8_t u8; +#define BIT_ULL(n) (1ull<<(n)) +#define xhci_dbg_trace(...) ((void)0) +#define KERN_DEBUG "" +#define printk(...) ((void)0) +#define spin_lock_irqsave(lock,flags) ((void)0) +#define spin_unlock_irqrestore(lock,flags) ((void)0) +struct device {unsigned vendor,device,revision;}; +struct pci_dev {unsigned vendor,device,revision;}; +#define to_pci_dev(d) ((struct pci_dev *)(d)) +struct xhci_hcd {unsigned hci_version,limit_active_eps,dma_mask_bits;uint64_t quirks;}; +static struct pci_dev inventory; +static struct pci_dev *pci_get_device(unsigned vendor,unsigned device,void *from) {(void)from;return inventory.vendor==vendor&&inventory.device==device?&inventory:NULL;} +static void pci_dev_put(struct pci_dev *p) {(void)p;} +''' +# Original generation/type declarations (no lock implementation is copied). +a=texts['pci-quirks.c'].index('enum amd_chipset_gen {');b=texts['pci-quirks.c'].index('static DEFINE_SPINLOCK',a) +body=texts['pci-quirks.c'][a:b]+'\n' +body+='\n'.join(function('pci-quirks.c',n) for n in ['amd_chipset_sb_type_init','usb_amd_find_chipset_info','usb_amd_quirk_pll_check']) +body+='\n'+function('xhci-pci.c','xhci_pci_quirks') +main=r''' +int main(void) { + unsigned ids[]={0x15b6,0x15b7,0x15b8,0x43fc};unsigned versions[]={0x100,0x110,0x120}; + inventory=(struct pci_dev){.vendor=0x1022,.device=0x790b,.revision=0x71}; + for(unsigned i=0;i<4;i++)for(unsigned rev=0;rev<256;rev++)for(unsigned v=0;v<3;v++){ + amd_chipset=(struct amd_chipset_info){0};struct device dev={.vendor=0x1022,.device=ids[i],.revision=rev};struct xhci_hcd x={.hci_version=versions[v]};xhci_pci_quirks(&dev,&x);printf("P %u %u %u %llu %d\n",ids[i],rev,versions[v],(unsigned long long)x.quirks,amd_chipset.need_pll_quirk); + } + unsigned vendors[]={0x1002,0x1022,0x1022,0x1022};unsigned devices[]={0x4385,0x780b,0x145c,0x790b}; + for(unsigned i=0;i<4;i++)for(unsigned rev=0;rev<256;rev++){ + inventory=(struct pci_dev){.vendor=vendors[i],.device=devices[i],.revision=rev};amd_chipset=(struct amd_chipset_info){0};bool pll=usb_amd_quirk_pll_check();printf("L %u %u %u %u %d\n",vendors[i],devices[i],rev,pll,amd_chipset.sb_type.gen); + } + return 0; +} +''' +unit=out/'linux-amd-xhci.c';unit.write_text(prelude+'\n'+texts['pci_ids.h']+'\n'+defines+'\n'+body+'\n'+main) +exe=out/'linux-amd-xhci';subprocess.run(['cc','-std=gnu11','-O1','-g','-fno-strict-aliasing','-fsanitize=address,undefined',str(unit),'-o',str(exe)],check=True) +with (out/'trace.txt').open('wb') as f:subprocess.run([str(exe.resolve())],stdout=f,check=True) +trace=(out/'trace.txt').read_bytes();(out/'receipt.json').write_text(json.dumps(dict(donors=expected,functions=fragments,trace_sha256=hashlib.sha256(trace).hexdigest(),rows=len(trace.splitlines())),indent=2)+'\n');print(hashlib.sha256(trace).hexdigest(),len(trace.splitlines())) diff --git a/crates/stela-drivers/tests/reference/xhci_iso_oracle.py b/crates/stela-drivers/tests/reference/xhci_iso_oracle.py new file mode 100644 index 0000000000..30b527b7de --- /dev/null +++ b/crates/stela-drivers/tests/reference/xhci_iso_oracle.py @@ -0,0 +1,177 @@ +#!/usr/bin/env python3 +"""Execute pinned unchanged USB2 isoch context/scheduling/completion helpers. +Usage: xhci_iso_oracle.py FLAT_REFERENCE_DIRECTORY NEW_OUTPUT_DIRECTORY +Fixture boundaries: logical USB objects, one retained TD/TRB per service, +zero quirks for the exact audited AMD profiles, no Linux DMA/workqueue runtime. +""" +import ast +import hashlib +import json +from pathlib import Path +import re +import subprocess +import sys + +source, out = map(Path, sys.argv[1:]) +expected = { + 'xhci-mem.c': 'abfe6f6f70bdeaf7a279a734bdab034ef014f329785ccb8c5f5cf3e763320198', + 'xhci-ring.c': '8c15822f3e118fc5ee9e647b5fc82f75d72f51519f1d9f6dee96d222fe6c9882', + 'xhci.h': '44ca06ce699192d60302896df23ef3ee243abe979ac5f3c759de9830ec311cc0', + 'xhci-caps.h': '096eb25ef1cceefe6a54f0e661b585ac19fa102db9b9807c4073c660cd452b43', + 'xhci-pci.c': '56659d07018ff7ae99334e910065c7bf46f80deb65c4445443ee52313422d6e8', +} +texts = {} +for name, digest in expected.items(): + raw = (source/name).read_bytes() + assert hashlib.sha256(raw).hexdigest() == digest, name + texts[name] = raw.decode() +out.mkdir(parents=True, exist_ok=False) +fragments = [] +def function(file, name): + text = texts[file] + match = re.search(r'^(?:static\s+)?(?:unsigned int|u32|int|bool|void)\s+' + name + r'\([^;{}]*?\)\n\{', text, re.M) + assert match, name + at, depth = match.end(), 1 + while depth: + depth += (text[at]=='{') - (text[at]=='}') + at += 1 + value = text[match.start():at] + fragments.append(dict(file=file, name=name, sha256=hashlib.sha256(value.encode()).hexdigest())) + return value +# Existing fixture helper declarations are reused without executing its script. +tree = ast.parse(Path(__file__).with_name('xhci_endpoint_oracle.py').read_text()) +prelude = next(ast.literal_eval(n.value) for n in tree.body if isinstance(n,ast.Assign) and any(isinstance(t,ast.Name) and t.id=='prelude' for t in n.targets)) +prelude = prelude.replace('unsigned char bMaxBurst;', 'unsigned char bMaxBurst, bmAttributes;') +prelude += r''' +#define EINVAL 22 +#define ENOMEM 12 +#define ECOMM 70 +#define EOVERFLOW 75 +#define EXDEV 18 +#define EPROTO 71 +typedef uint64_t u64; +typedef int gfp_t; +#define cpu_to_le32(x) (x) +#define cpu_to_le64(x) (x) +#define le32_to_cpu(x) (x) +#define BIT(n) (1u<<(n)) +#define FIELD_GET(mask,x) (((x)&(mask))>>__builtin_ctz(mask)) +#define DIV_ROUND_UP(x,y) (((x)+(y)-1)/(y)) +#define DIV_ROUND_UP_POW2(x,y) DIV_ROUND_UP(x,y) +#define roundup(x,y) (DIV_ROUND_UP(x,y)*(y)) +#define HCS_IST_VALUE 7 +#define HCS_IST_UNIT BIT(3) +#define HCC_CFC BIT(11) +#define HCC2_LEC BIT(4) +#define HCC2_EUSB2_DIC BIT(11) +#define XHCI_CFC_DELAY 10 +#define MFINDEX_TO_FRAME(p) (((p)>>3)&0x7ff) +#define MAX_FRAMES 2048 +#define MAX_UFRAMES (8*MAX_FRAMES) +#define URB_ISO_ASAP 1 +#define XHCI_INTEL_HOST BIT(0) +#define XHCI_LIMIT_ENDPOINT_INTERVAL_9 BIT(1) +#define XHCI_LIMIT_ENDPOINT_INTERVAL_7 BIT(2) +#define EP_MAX_ESIT_PAYLOAD_HI(p) ((((p)>>16)&255)<<24) +#define EP_MAX_ESIT_PAYLOAD_LO(p) (((p)&65535)<<16) +#define EP_INTERVAL(p) (((p)&255)<<16) +#define EP_MULT(p) (((p)&3)<<8) +#define EP_TYPE(p) ((p)<<3) +#define ERROR_COUNT(p) (((p)&3)<<1) +#define MAX_PACKET(p) (((p)&65535)<<16) +#define MAX_BURST(p) (((p)&255)<<8) +#define EP_AVG_TRB_LENGTH(p) ((p)&65535) +#define CTRL_EP 4 +#define BULK_IN_EP 6 +#define BULK_OUT_EP 2 +#define ISOC_IN_EP 5 +#define ISOC_OUT_EP 1 +#define INT_IN_EP 7 +#define INT_OUT_EP 3 +#define USB_ENDPOINT_XFER_CONTROL 0 +#define USB_ENDPOINT_XFER_ISOC 1 +#define USB_ENDPOINT_XFER_BULK 2 +#define USB_ENDPOINT_XFER_INT 3 +#define xhci_dbg(...) ((void)0) +#define xhci_usb_endpoint_maxp(u,e) ((e)->desc.wMaxPacketSize&2047) +#define xhci_ring_init(x,r) ((void)0) +#define readl(p) (*(p)) +#define rounddown_pow_of_two(p) (1u<<(31-__builtin_clz(p))) +struct xhci_run_regs { u32 microframe_index; }; +struct xhci_hcd { unsigned hci_version,hcs_params2,hcc_params,hcc_params2,quirks; struct xhci_run_regs *run_regs; }; +struct xhci_ep_ctx { u32 ep_info,ep_info2; u64 deq; u32 tx_info; }; +struct segment {u64 dma;}; +struct xhci_ring { struct segment *first_seg; unsigned cycle_state; }; +enum xhci_ring_type { TYPE_CTRL,TYPE_ISOC,TYPE_BULK,TYPE_INT }; +struct xhci_virt_ep { struct xhci_ring *new_ring; bool skip; int next_uframe; }; +struct xhci_virt_device { struct xhci_ep_ctx *in_ctx; struct xhci_virt_ep eps[32]; }; +static unsigned usb_endpoint_type(const struct usb_endpoint_descriptor *d) {return d->bmAttributes&3;} +static bool usb_endpoint_dir_in(const struct usb_endpoint_descriptor *d) {return d->bEndpointAddress&128;} +static unsigned xhci_get_endpoint_index(const struct usb_endpoint_descriptor *d) {return (d->bEndpointAddress&15)*2+!!(d->bEndpointAddress&128)-1;} +static struct xhci_ep_ctx *xhci_get_ep_ctx(struct xhci_hcd *x,struct xhci_ep_ctx *c,unsigned i) {(void)x;return c+i;} +static struct xhci_ring *xhci_ring_alloc(struct xhci_hcd *x,int n,enum xhci_ring_type t,unsigned m,gfp_t f) {(void)x;(void)n;(void)t;(void)m;(void)f;static struct segment s={65536};static struct xhci_ring r={&s,1};return &r;} +static unsigned usb_endpoint_max_periodic_payload(struct usb_device *u,struct usb_host_endpoint *e) {return (e->desc.wMaxPacketSize&2047)*(u->speed==USB_SPEED_HIGH?usb_endpoint_maxp_mult(&e->desc):1);} +struct usb_iso_packet_descriptor {unsigned length,actual_length;int status;}; +struct urb {struct usb_device *dev;struct usb_host_endpoint *ep;unsigned transfer_flags;int interval,number_of_packets,start_frame;void *hcpriv;struct usb_iso_packet_descriptor iso_frame_desc[1];unsigned actual_length;}; +struct urb_priv {int num_tds_done;}; +union xhci_trb {struct {u32 field[4];}generic;}; +struct xhci_td {struct urb *urb;union xhci_trb *end_trb;bool error_mid_td,urb_length_set;}; +struct xhci_transfer_event {u32 transfer_len;}; +#define GET_COMP_CODE(p) ((p)>>24) +#define EVENT_TRB_LEN(p) ((p)&0xffffff) +#define TRB_LEN(p) ((p)&0x1ffff) +#define CTX_TO_EP_TYPE(p) (((p)>>3)&7) +#define GET_EP_CTX_STATE(p) ((p)->ep_info&7) +#define EP_STATE_HALTED 2 +#define COMP_SUCCESS 1 +#define COMP_BABBLE_DETECTED_ERROR 3 +#define COMP_USB_TRANSACTION_ERROR 4 +#define COMP_SPLIT_TRANSACTION_ERROR 36 +#define COMP_STALL_ERROR 6 +#define COMP_SHORT_PACKET 13 +#define COMP_BANDWIDTH_OVERRUN_ERROR 18 +#define COMP_INCOMPATIBLE_DEVICE_ERROR 22 +#define COMP_MISSED_SERVICE_ERROR 23 +#define COMP_STOPPED 26 +#define COMP_STOPPED_LENGTH_INVALID 27 +#define COMP_STOPPED_SHORT_PACKET 28 +#define COMP_ISOCH_BUFFER_OVERRUN 31 +static unsigned sum_trb_lengths(struct xhci_td *t,union xhci_trb *b) {(void)t;(void)b;return 0;} +static unsigned finished; +static void finish_td(struct xhci_hcd *x,struct xhci_virt_ep *e,struct xhci_ring *r,struct xhci_td *t,u32 c) {(void)x;(void)e;(void)r;(void)t;(void)c;finished++;} +''' +mem_names = ['xhci_parse_exponent_interval','xhci_microframes_to_exponent','xhci_parse_microframe_interval','xhci_parse_frame_interval','xhci_get_endpoint_interval','xhci_get_endpoint_mult','xhci_get_endpoint_max_burst','xhci_get_endpoint_type','xhci_endpoint_init'] +ring_names = ['xhci_get_burst_count','xhci_get_last_burst_packet_count','xhci_ist_microframes','xhci_isoc_td_uses_frame_id','xhci_frame_in_range','xhci_get_isoc_start_frame','process_isoc_td','xhci_halted_host_endpoint'] +body = '\n'.join(function('xhci-mem.c',n) for n in mem_names)+'\n'+'\n'.join(function('xhci-ring.c',n) for n in ring_names) +main = r''' +int main(void) { + struct xhci_run_regs regs={0};struct xhci_hcd x={.hci_version=0x110,.run_regs=®s}; + /* Execute non-isoc interval dependencies as bounded logical fixture probes. */ + struct usb_device probe_u={.speed=USB_SPEED_HIGH};struct usb_host_endpoint probe_e={.desc={.bmAttributes=2,.bInterval=4}}; + if(xhci_parse_microframe_interval(&probe_u,&probe_e)!=2)abort(); + probe_u.speed=USB_SPEED_FULL;probe_e.desc.bmAttributes=3;probe_e.desc.bInterval=8; + if(xhci_parse_frame_interval(&probe_u,&probe_e)!=6)abort(); + for(int speed=2;speed<=3;speed++)for(unsigned interval=1;interval<=16;interval++)for(unsigned burst=0;burst<=(speed==3?2:0);burst++)for(unsigned dir=0;dir<2;dir++) { + unsigned packet=speed==2?192:1024;struct usb_device u={.speed=speed};struct usb_host_endpoint e={.desc={.bEndpointAddress=dir?0x81:1,.bmAttributes=1,.bInterval=interval,.wMaxPacketSize=packet|(burst<<11)}};struct xhci_ep_ctx ctx[32]={0};struct xhci_virt_device v={.in_ctx=ctx}; + if(xhci_endpoint_init(&x,&v,&u,&e,0))abort();unsigned n=xhci_get_endpoint_index(&e.desc);printf("E %d %u %u %u %u %u %u %u\n",speed,interval,burst,dir,packet,ctx[n].ep_info,ctx[n].ep_info2,ctx[n].tx_info); + } + unsigned values[]={0,1,7,8,8190,16370,16383};unsigned intervals[]={1,2,8,32,4096}; + for(unsigned i=0;i<7;i++)for(unsigned hcs=0;hcs<16;hcs++)for(unsigned cfc=0;cfc<2;cfc++)for(unsigned j=0;j<5;j++)for(int next=-1;next<3;next++) { + struct usb_device u={.speed=USB_SPEED_HIGH};struct usb_host_endpoint e={0};struct urb urb={.dev=&u,.ep=&e,.interval=intervals[j],.number_of_packets=1};struct xhci_virt_ep ep={.next_uframe=next<0?-1:(int)((values[i]+next*8)%MAX_UFRAMES)};regs.microframe_index=values[i];x.hcs_params2=hcs;x.hcc_params=cfc?HCC_CFC:0;unsigned start=xhci_get_isoc_start_frame(&x,&urb,&ep);unsigned low=(values[i]/8+DIV_ROUND_UP(xhci_ist_microframes(&x),8)+1)%MAX_FRAMES;unsigned high=(values[i]/8+895)%MAX_FRAMES; + printf("S %u %u %u %u %d %u %u %u\n",values[i],hcs,cfc,intervals[j],ep.next_uframe,start,xhci_isoc_td_uses_frame_id(&x,&urb,&ep,0),xhci_frame_in_range(start/8,low,high)); + } + unsigned codes[]={1,13,23,4,3,18,31,6,22}; + for(unsigned i=0;i<9;i++)for(unsigned residual=0;residual<=128;residual+=32) { + struct usb_device u={0};struct urb_priv priv={0};struct urb urb={.dev=&u,.hcpriv=&priv,.iso_frame_desc={{.length=128}}};union xhci_trb trb={.generic={{0,0,128,0}}};struct xhci_td td={.urb=&urb,.end_trb=&trb};struct xhci_virt_ep ep={0};struct xhci_transfer_event event={.transfer_len=(codes[i]<<24)|residual};finished=0;process_isoc_td(&x,&ep,0,&td,&trb,&event);struct xhci_ep_ctx context={.ep_info2=ISOC_IN_EP<<3};printf("C %u %u %u %d %u %u\n",codes[i],residual,urb.iso_frame_desc[0].actual_length,urb.iso_frame_desc[0].status,finished,xhci_halted_host_endpoint(&x,&context,codes[i])); + } + for(unsigned packets=1;packets<=3;packets++){struct usb_device u={.speed=USB_SPEED_HIGH};struct usb_host_endpoint e={0};struct urb urb={.dev=&u,.ep=&e};printf("B %u %u %u\n",packets,xhci_get_burst_count(&x,&urb,packets),xhci_get_last_burst_packet_count(&x,&urb,packets));} + return 0; +} +''' +unit=out/'linux-xhci-iso.c';unit.write_text(prelude+'\n'+body+'\n'+main) +exe=out/'linux-xhci-iso' +subprocess.run(['cc','-std=gnu11','-O1','-g','-fsanitize=address,undefined',str(unit),'-o',str(exe)],check=True) +with (out/'trace.txt').open('wb') as trace:subprocess.run([str(exe.resolve())],stdout=trace,check=True) +trace=(out/'trace.txt').read_bytes() +(out/'receipt.json').write_text(json.dumps(dict(donors=expected,functions=fragments,trace_sha256=hashlib.sha256(trace).hexdigest(),rows=len(trace.splitlines())),indent=2)+'\n') +print(hashlib.sha256(trace).hexdigest(),len(trace.splitlines()))