feat(usb): retain native xHCI CPU and DMA ownership
This commit is contained in:
1 parent
889e41b956
commit
be07a72e33
26 files changed
+2209
-148
No files matched your search
@@ -76,8 +76,10 @@ mod hub;
|
||||
mod identity;
|
||||
mod iso;
|
||||
mod lifecycle;
|
||||
mod memory;
|
||||
#[cfg(test)]
|
||||
pub(crate) mod model;
|
||||
pub mod native;
|
||||
mod power;
|
||||
mod quirks;
|
||||
pub mod renesas;
|
||||
@@ -373,8 +375,8 @@ struct Slot {
|
||||
suspended: bool,
|
||||
attachment: Attachment,
|
||||
retiring: bool,
|
||||
input: DmaBuffer,
|
||||
_output: DmaBuffer,
|
||||
input: memory::Buffer,
|
||||
_output: memory::Buffer,
|
||||
/// The slot context as software last set it.
|
||||
context: [u32; 4],
|
||||
endpoints: [Option<Transfer>; 32],
|
||||
@@ -382,7 +384,7 @@ struct Slot {
|
||||
/// Preserve the acknowledged producer pointer/cycle rather than restarting
|
||||
/// at an old TRB address or recycling the caller's backing DMA arena.
|
||||
retired_rings: [Option<Ring>; 32],
|
||||
control: DmaBuffer,
|
||||
control: memory::Buffer,
|
||||
speed: u8,
|
||||
/// None after an unresolved SET_CONFIGURATION; Some(0) is Address state.
|
||||
current_configuration: Option<u8>,
|
||||
@@ -421,11 +423,12 @@ pub struct Controller {
|
||||
/// capabilities.
|
||||
port_major: Vec<u8>,
|
||||
power: power::Ledger,
|
||||
dcbaa: DmaBuffer,
|
||||
_scratchpads: Vec<DmaBuffer>,
|
||||
native_memory: Option<Rc<memory::Native>>,
|
||||
dcbaa: memory::Buffer,
|
||||
_scratchpads: Vec<memory::Buffer>,
|
||||
commands: Ring,
|
||||
events: DmaBuffer,
|
||||
_event_table: DmaBuffer,
|
||||
events: memory::Buffer,
|
||||
_event_table: memory::Buffer,
|
||||
event_index: usize,
|
||||
event_cycle: bool,
|
||||
slots: Vec<Option<Slot>>,
|
||||
@@ -481,13 +484,26 @@ impl Controller {
|
||||
}
|
||||
|
||||
fn with_hardware_profile(
|
||||
mut registers: Box<dyn Registers>,
|
||||
registers: Box<dyn Registers>,
|
||||
clock: Clock,
|
||||
dma: &mut dyn DmaAllocator,
|
||||
location: String,
|
||||
policy: hardware::Policy,
|
||||
after_reset: impl FnOnce() -> Result<(), BlockError>,
|
||||
) -> Result<Self, BlockError> {
|
||||
Self::with_memory_profile(registers, clock, dma, location, policy, after_reset, None)
|
||||
}
|
||||
|
||||
fn with_memory_profile(
|
||||
mut registers: Box<dyn Registers>,
|
||||
clock: Clock,
|
||||
dma: &mut dyn DmaAllocator,
|
||||
location: String,
|
||||
policy: hardware::Policy,
|
||||
after_reset: impl FnOnce() -> Result<(), BlockError>,
|
||||
native_memory: Option<Rc<memory::Native>>,
|
||||
) -> Result<Self, BlockError> {
|
||||
clock_ready(clock)?;
|
||||
let profile = policy.dma;
|
||||
let capability = registers.read32(0);
|
||||
let operational = (capability & 0xff) as usize;
|
||||
@@ -574,7 +590,9 @@ impl Controller {
|
||||
"xHCI controller without 4 KiB pages",
|
||||
));
|
||||
}
|
||||
let mut allocate = |bytes: usize, align: usize| profile.allocate(dma, bytes, align);
|
||||
let mut allocate = |bytes: usize, align: usize| {
|
||||
profile.allocate_memory(dma, bytes, align, native_memory.as_ref())
|
||||
};
|
||||
registers.write32(operational + CONFIG, max_slots as u32);
|
||||
let mut dcbaa = allocate((max_slots + 1) * 8, 64)?;
|
||||
let scratchpad_count =
|
||||
@@ -584,25 +602,40 @@ impl Controller {
|
||||
let mut array = allocate(scratchpad_count * 8, 64)?;
|
||||
for n in 0..scratchpad_count {
|
||||
let page = allocate(4096, 4096)?;
|
||||
array.write(n * 8, page.physical());
|
||||
array.write(n * 8, page.device_address());
|
||||
scratchpads.push(page);
|
||||
}
|
||||
dcbaa.write(0, array.physical());
|
||||
dcbaa.write(0, array.device_address());
|
||||
scratchpads.push(array);
|
||||
}
|
||||
let commands = Ring::with_profile(dma, profile)?;
|
||||
let events = profile.allocate(dma, profile.segment_bytes(), profile.segment_bytes())?;
|
||||
let mut event_table = profile.allocate(dma, 16, 64)?;
|
||||
event_table.write(0, events.physical());
|
||||
let commands = Ring::with_memory(dma, profile, native_memory.as_ref())?;
|
||||
let events = profile.allocate_memory(
|
||||
dma,
|
||||
profile.segment_bytes(),
|
||||
profile.segment_bytes(),
|
||||
native_memory.as_ref(),
|
||||
)?;
|
||||
let mut event_table = profile.allocate_memory(dma, 16, 64, native_memory.as_ref())?;
|
||||
event_table.write(0, events.device_address());
|
||||
event_table.write(8, RING_TRBS as u32);
|
||||
dcbaa.sync_dirty()?;
|
||||
for buffer in &scratchpads {
|
||||
buffer.sync_dirty()?;
|
||||
}
|
||||
commands.buffer.sync_dirty()?;
|
||||
events.sync_dirty()?;
|
||||
event_table.sync_dirty()?;
|
||||
// Native coherent polling must be qualified by the actual domain
|
||||
// before publishing any controller pointer or starting DMA.
|
||||
events.coherent_u32(12)?;
|
||||
// All buffers satisfy the same immutable aperture before any pointer
|
||||
// register is published, including the event and command segments.
|
||||
registers.write64(operational + DCBAAP, dcbaa.physical());
|
||||
registers.write64(operational + DCBAAP, dcbaa.device_address());
|
||||
registers.write64(operational + CRCR, commands.dequeue_pointer());
|
||||
registers.write32(runtime + IMAN, 1); // clear IP; IE stays off
|
||||
registers.write32(runtime + ERSTSZ, 1);
|
||||
registers.write64(runtime + ERDP, events.physical());
|
||||
registers.write64(runtime + ERSTBA, event_table.physical());
|
||||
registers.write64(runtime + ERDP, events.device_address());
|
||||
registers.write64(runtime + ERSTBA, event_table.device_address());
|
||||
hardware::start(&mut *registers, clock, operational)?;
|
||||
let iso_caps =
|
||||
iso::Capabilities::new((capability >> 16) as u16, parameters2, capabilities1);
|
||||
@@ -629,6 +662,7 @@ impl Controller {
|
||||
max_slots,
|
||||
max_ports,
|
||||
port_major,
|
||||
native_memory,
|
||||
dcbaa,
|
||||
_scratchpads: scratchpads,
|
||||
commands,
|
||||
@@ -648,6 +682,33 @@ impl Controller {
|
||||
})
|
||||
}
|
||||
|
||||
fn sync_command_buffers(&self) -> Result<(), BlockError> {
|
||||
self.dcbaa.sync_dirty()?;
|
||||
for state in self.slots.iter().flatten() {
|
||||
state.input.sync_dirty()?;
|
||||
for endpoint in state.endpoints.iter().flatten() {
|
||||
if let Some(streams) = &endpoint.streams {
|
||||
streams.sync_device()?;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn allocate(
|
||||
&self,
|
||||
dma: &mut dyn DmaAllocator,
|
||||
bytes: usize,
|
||||
align: usize,
|
||||
) -> Result<memory::Buffer, BlockError> {
|
||||
self.dma_profile
|
||||
.allocate_memory(dma, bytes, align, self.native_memory.as_ref())
|
||||
}
|
||||
|
||||
fn allocate_ring(&self, dma: &mut dyn DmaAllocator) -> Result<Ring, BlockError> {
|
||||
Ring::with_memory(dma, self.dma_profile, self.native_memory.as_ref())
|
||||
}
|
||||
|
||||
fn doorbell(&mut self, slot: u8, target: u8) {
|
||||
fence(Ordering::SeqCst);
|
||||
self.registers
|
||||
@@ -657,11 +718,25 @@ impl Controller {
|
||||
/// The next event on the ring, if the controller has posted one.
|
||||
fn next_event(&mut self) -> Option<Event> {
|
||||
let at = self.event_index * TRB;
|
||||
let control: u32 = self.events.read(at + 12);
|
||||
let control = match self.events.coherent_u32(at + 12) {
|
||||
Ok(control) => control,
|
||||
Err(_) => {
|
||||
self.command_poisoned = true;
|
||||
self.hardware = hardware::State::Failed;
|
||||
return None;
|
||||
}
|
||||
};
|
||||
if (control & CYCLE != 0) != self.event_cycle {
|
||||
return None;
|
||||
}
|
||||
fence(Ordering::Acquire);
|
||||
// SAFETY: this exact TRB's observed Cycle grants software ownership.
|
||||
// The controller cannot reuse it until the later ERDP publication.
|
||||
if unsafe { self.events.sync_cpu(at..at + TRB) }.is_err() {
|
||||
self.command_poisoned = true;
|
||||
self.hardware = hardware::State::Failed;
|
||||
return None;
|
||||
}
|
||||
let event = Event {
|
||||
parameter: self.events.read(at),
|
||||
status: self.events.read(at + 8),
|
||||
@@ -672,7 +747,7 @@ impl Controller {
|
||||
self.event_index = 0;
|
||||
self.event_cycle = !self.event_cycle;
|
||||
}
|
||||
let dequeue = self.events.physical() + (self.event_index * TRB) as u64;
|
||||
let dequeue = self.events.device_address() + (self.event_index * TRB) as u64;
|
||||
self.registers.write64(self.runtime + ERDP, dequeue | EHB);
|
||||
Some(event)
|
||||
}
|
||||
@@ -726,9 +801,15 @@ impl Controller {
|
||||
microseconds: u64,
|
||||
wanted: impl Fn(&Event) -> bool,
|
||||
) -> Result<Event, BlockError> {
|
||||
let deadline = self.clock.deadline(microseconds);
|
||||
let deadline = self.clock.try_deadline(microseconds).map_err(|_| {
|
||||
BlockError::Unsupported("xHCI event timeout clock unavailable or duration out of range")
|
||||
})?;
|
||||
loop {
|
||||
self.drain();
|
||||
if let Some(memory) = &self.native_memory {
|
||||
memory.ready()?;
|
||||
}
|
||||
self.hardware.ready()?;
|
||||
if let Some(event) = self.take(&wanted) {
|
||||
return Ok(event);
|
||||
}
|
||||
@@ -747,6 +828,9 @@ impl Controller {
|
||||
/// completion cannot establish a new command generation or undo poison.
|
||||
fn ready(&mut self) -> Result<(), BlockError> {
|
||||
self.hardware.ready()?;
|
||||
if let Some(memory) = &self.native_memory {
|
||||
memory.ready()?;
|
||||
}
|
||||
self.drain();
|
||||
if let Some(status) = self.error {
|
||||
self.command_poisoned = true;
|
||||
@@ -762,7 +846,8 @@ impl Controller {
|
||||
|
||||
fn command(&mut self, parameter: u64, status: u32, control: u32) -> Result<Event, BlockError> {
|
||||
self.ready()?;
|
||||
let address = self.commands.push(&[(parameter, status, control)])[0];
|
||||
self.sync_command_buffers()?;
|
||||
let address = self.commands.push(&[(parameter, status, control)])?[0];
|
||||
self.doorbell(0, 0);
|
||||
let event = match self.wait_event(COMMAND_US, |e| {
|
||||
e.kind() == COMMAND_COMPLETION && e.parameter == address
|
||||
@@ -817,6 +902,14 @@ impl Controller {
|
||||
}
|
||||
}
|
||||
|
||||
/// All fixed controller/port waits fit this interval. Caller-supplied budgets
|
||||
/// also pass fallible admission at their actual submission boundary.
|
||||
fn clock_ready(clock: Clock) -> Result<(), BlockError> {
|
||||
clock
|
||||
.check_duration(60_000_000)
|
||||
.map_err(|_| BlockError::Unsupported("xHCI requires an available calibrated clock"))
|
||||
}
|
||||
|
||||
/// Polls `ready` against the registers until it holds or time runs out.
|
||||
fn wait(
|
||||
registers: &mut dyn Registers,
|
||||
@@ -905,6 +998,7 @@ pub fn attach_with_firmware_diagnostics(
|
||||
dma: &mut dyn DmaAllocator,
|
||||
firmware: &dyn crate::firmware::Provider,
|
||||
) -> Result<Found, renesas::Error> {
|
||||
clock_ready(handoff.clock)?;
|
||||
let stream_policy = streams::pci_policy(function)?;
|
||||
let dma_profile = dma::Profile::pci(function.vendor, function.device);
|
||||
let quirks = quirks::Profile::pci(function)?;
|
||||
@@ -1014,6 +1108,45 @@ mod tests {
|
||||
use super::*;
|
||||
use crate::bus::dma::RegionAllocator;
|
||||
|
||||
#[test]
|
||||
fn unavailable_native_clock_refuses_before_any_controller_register_or_dma_effect() {
|
||||
struct Trap;
|
||||
impl Registers for Trap {
|
||||
fn read32(&mut self, _: usize) -> u32 {
|
||||
panic!("unavailable clock read controller")
|
||||
}
|
||||
fn write32(&mut self, _: usize, _: u32) {
|
||||
panic!("unavailable clock wrote controller")
|
||||
}
|
||||
}
|
||||
impl DmaAllocator for Trap {
|
||||
fn allocate(&mut self, _: usize, _: usize) -> Result<DmaBuffer, BlockError> {
|
||||
panic!("unavailable clock allocated DMA")
|
||||
}
|
||||
}
|
||||
for rate in [
|
||||
0,
|
||||
u64::MAX,
|
||||
u64::MAX / 60_000_000 + 1,
|
||||
(u64::MAX / 2) / 60_000_000 + 1,
|
||||
] {
|
||||
let result = Controller::new(
|
||||
Box::new(Trap),
|
||||
Clock {
|
||||
ticks_per_microsecond: rate,
|
||||
},
|
||||
&mut Trap,
|
||||
"unavailable-clock owner".into(),
|
||||
);
|
||||
assert!(matches!(
|
||||
result,
|
||||
Err(BlockError::Unsupported(
|
||||
"xHCI requires an available calibrated clock"
|
||||
))
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn completion_codes_are_named() {
|
||||
assert_eq!(
|
||||
|
||||
@@ -200,11 +200,12 @@ impl Controller {
|
||||
}
|
||||
let streamed = stream_endpoints.contains(&endpoint.address);
|
||||
let stream = if streamed {
|
||||
Some(streams::Streams::new(
|
||||
Some(streams::Streams::with_memory(
|
||||
dma,
|
||||
layout.unwrap(),
|
||||
self.dma_profile,
|
||||
self.stream_policy == streams::Policy::Cadence,
|
||||
self.native_memory.as_ref(),
|
||||
)?)
|
||||
} else {
|
||||
None
|
||||
@@ -216,7 +217,7 @@ impl Controller {
|
||||
};
|
||||
let ring = match retained {
|
||||
Some(ring) => ring,
|
||||
None => Ring::with_profile(dma, self.dma_profile)?,
|
||||
None => self.allocate_ring(dma)?,
|
||||
};
|
||||
Ok((ring, stream))
|
||||
})();
|
||||
@@ -295,7 +296,7 @@ impl Controller {
|
||||
for (n, word) in words.iter().enumerate() {
|
||||
state.input.write(context + 4 * n, *word);
|
||||
}
|
||||
state.input.physical()
|
||||
state.input.device_address()
|
||||
};
|
||||
let result = self.command(
|
||||
input_address,
|
||||
@@ -541,8 +542,8 @@ mod tests {
|
||||
let slot = controller.slots[1].as_mut().unwrap();
|
||||
slot.speed = speed;
|
||||
slot.context[0] = slot.context[0] & !(15 << 20) | u32::from(speed) << 20;
|
||||
slot.input = dma.allocate(33 * context, 64).unwrap();
|
||||
slot._output = dma.allocate(32 * context, 64).unwrap();
|
||||
slot.input = dma.allocate(33 * context, 64).unwrap().into();
|
||||
slot._output = dma.allocate(32 * context, 64).unwrap().into();
|
||||
model.borrow_mut().output = slot._output.physical();
|
||||
model.borrow_mut().context_bytes = context;
|
||||
model.borrow_mut().set_state(1, 1);
|
||||
|
||||
@@ -66,6 +66,14 @@ impl Profile {
|
||||
RING_TRBS * TRB * if self.overfetch { 2 } else { 1 }
|
||||
}
|
||||
|
||||
pub(super) fn maximum(self) -> u64 {
|
||||
if self.bits == 64 {
|
||||
u64::MAX
|
||||
} else {
|
||||
(1u64 << self.bits) - 1
|
||||
}
|
||||
}
|
||||
|
||||
pub fn check(self, address: u64, bytes: usize) -> Result<(), BlockError> {
|
||||
let last = address.checked_add(bytes.saturating_sub(1) as u64);
|
||||
let maximum = if self.bits == 64 {
|
||||
@@ -82,17 +90,22 @@ impl Profile {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn allocate(
|
||||
pub(super) fn allocate_memory(
|
||||
self,
|
||||
dma: &mut dyn DmaAllocator,
|
||||
bytes: usize,
|
||||
align: usize,
|
||||
) -> Result<DmaBuffer, BlockError> {
|
||||
let buffer = dma.allocate(bytes, align)?;
|
||||
if buffer.len() < bytes || !buffer.physical().is_multiple_of(align as u64) {
|
||||
native: Option<&Rc<memory::Native>>,
|
||||
) -> Result<memory::Buffer, BlockError> {
|
||||
let buffer = if let Some(native) = native {
|
||||
native.allocate(bytes, align, self.maximum())?
|
||||
} else {
|
||||
dma.allocate(bytes, align)?.into()
|
||||
};
|
||||
if buffer.len() < bytes || !buffer.device_address().is_multiple_of(align as u64) {
|
||||
return Err(BlockError::Unsupported("invalid xHCI DMA allocation"));
|
||||
}
|
||||
self.check(buffer.physical(), bytes)?;
|
||||
self.check(buffer.device_address(), bytes)?;
|
||||
Ok(buffer)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,7 +7,18 @@ use super::*;
|
||||
/// connection and connect change, clearing a change it reports.
|
||||
pub(super) fn debounce(
|
||||
clock: Clock,
|
||||
sample: impl FnMut() -> Result<(bool, bool), BlockError>,
|
||||
) -> Result<bool, BlockError> {
|
||||
clock_ready(clock)?;
|
||||
debounce_with_delay(sample, || {
|
||||
crate::bus::pci::power::Timer::wait_us(&clock, DEBOUNCE_STEP_US)
|
||||
.map_err(|_| BlockError::Unsupported("xHCI debounce clock unavailable"))
|
||||
})
|
||||
}
|
||||
|
||||
fn debounce_with_delay(
|
||||
mut sample: impl FnMut() -> Result<(bool, bool), BlockError>,
|
||||
mut delay: impl FnMut() -> Result<(), BlockError>,
|
||||
) -> Result<bool, BlockError> {
|
||||
let mut connection = None;
|
||||
let mut stable = 0;
|
||||
@@ -26,7 +37,7 @@ pub(super) fn debounce(
|
||||
if total >= DEBOUNCE_TIMEOUT_US {
|
||||
return Err(BlockError::Unsupported("USB port connection never settled"));
|
||||
}
|
||||
clock.delay(DEBOUNCE_STEP_US);
|
||||
delay()?;
|
||||
total += DEBOUNCE_STEP_US;
|
||||
}
|
||||
}
|
||||
@@ -116,8 +127,9 @@ impl Controller {
|
||||
enabled: true,
|
||||
in_flight: 0,
|
||||
});
|
||||
let input_address = input.physical();
|
||||
self.dcbaa.write(usize::from(slot) * 8, output.physical());
|
||||
let input_address = input.device_address();
|
||||
self.dcbaa
|
||||
.write(usize::from(slot) * 8, output.device_address());
|
||||
self.slots[usize::from(slot)] = Some(Slot {
|
||||
generation,
|
||||
parent_id,
|
||||
@@ -162,7 +174,7 @@ impl Controller {
|
||||
state
|
||||
.input
|
||||
.write(2 * context + 4, u32::from(max_packet) << 16);
|
||||
state.input.physical()
|
||||
state.input.device_address()
|
||||
};
|
||||
self.command(
|
||||
input_address,
|
||||
@@ -791,9 +803,6 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn port_connections_count_after_a_steady_hundred_milliseconds() {
|
||||
let clock = Clock {
|
||||
ticks_per_microsecond: 0,
|
||||
};
|
||||
// A bounce (connected, changed, gone, back) restarts the window.
|
||||
let samples = [(true, true), (false, true), (true, true), (true, false)];
|
||||
let mut taken = samples
|
||||
@@ -801,24 +810,57 @@ mod tests {
|
||||
.copied()
|
||||
.chain(core::iter::repeat((true, false)));
|
||||
let mut count = 0;
|
||||
let connected = debounce(clock, || {
|
||||
count += 1;
|
||||
Ok(taken.next().unwrap())
|
||||
});
|
||||
let mut waits = 0;
|
||||
let connected = debounce_with_delay(
|
||||
|| {
|
||||
count += 1;
|
||||
Ok(taken.next().unwrap())
|
||||
},
|
||||
|| {
|
||||
waits += 1;
|
||||
Ok(())
|
||||
},
|
||||
);
|
||||
assert_eq!(connected, Ok(true));
|
||||
// Three changing samples, then four steady ones of 25 ms each.
|
||||
assert_eq!(count, 3 + (DEBOUNCE_STABLE_US / DEBOUNCE_STEP_US) as usize);
|
||||
assert_eq!(debounce(clock, || Ok((false, false))), Ok(false));
|
||||
assert_eq!(waits, count - 1);
|
||||
assert_eq!(
|
||||
debounce_with_delay(|| Ok((false, false)), || Ok(())),
|
||||
Ok(false)
|
||||
);
|
||||
let mut flapping = false;
|
||||
assert_eq!(
|
||||
debounce(clock, || {
|
||||
flapping = !flapping;
|
||||
Ok((flapping, true))
|
||||
}),
|
||||
debounce_with_delay(
|
||||
|| {
|
||||
flapping = !flapping;
|
||||
Ok((flapping, true))
|
||||
},
|
||||
|| Ok(())
|
||||
),
|
||||
Err(BlockError::Unsupported("USB port connection never settled"))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unavailable_debounce_timing_refuses_before_port_sampling_and_failed_wait_is_explicit() {
|
||||
for rate in [0, u64::MAX, (u64::MAX / 2) / 60_000_000 + 1] {
|
||||
assert!(
|
||||
debounce(
|
||||
Clock {
|
||||
ticks_per_microsecond: rate
|
||||
},
|
||||
|| panic!("unavailable clock sampled real port")
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
debounce_with_delay(|| Ok((true, false)), || Err(BlockError::Timeout)),
|
||||
Err(BlockError::Timeout)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hub_ports_past_fifteen_route_as_fifteen() {
|
||||
assert_eq!(child_route(0, 0, 3), 3);
|
||||
|
||||
@@ -258,10 +258,11 @@ impl Controller {
|
||||
// CRCR only accepts a 64-byte-aligned pointer, so restart this empty
|
||||
// ring at its base; transfer and event rings keep their exact cursors.
|
||||
self.commands.buffer.bytes_mut()[..RING_TRBS * TRB].fill(0);
|
||||
let base = self.commands.buffer.physical();
|
||||
let base = self.commands.buffer.device_address();
|
||||
self.commands.buffer.write((RING_TRBS - 1) * TRB, base);
|
||||
self.commands.index = 0;
|
||||
self.commands.cycle = true;
|
||||
self.commands.buffer.sync_dirty()?;
|
||||
self.registers
|
||||
.write64(self.operational + CRCR, self.commands.dequeue_pointer());
|
||||
let snapshot = Snapshot::read(self);
|
||||
|
||||
@@ -114,7 +114,7 @@ impl Controller {
|
||||
if !endpoint.enabled
|
||||
|| endpoint.poisoned
|
||||
|| endpoint.in_flight != 0
|
||||
|| state._output.read::<u32>(dci * self.context()) & 7 != ENDPOINT_STOPPED
|
||||
|| state._output.coherent_u32(dci * self.context())? & 7 != ENDPOINT_STOPPED
|
||||
{
|
||||
return Err(BlockError::Unsupported(
|
||||
"USB suspend requires acknowledged subtree endpoint stops",
|
||||
|
||||
@@ -78,12 +78,12 @@ fn superspeed_cold_hub_uses_actual_contexts_depth_power_routes_and_bulk_io() {
|
||||
let mut payload = dma.allocate(64, 64).unwrap();
|
||||
payload.bytes_mut().fill(0xee);
|
||||
assert_eq!(
|
||||
controller.transfer(child.slot, 3, payload.physical(), 64, 1000),
|
||||
controller.transfer(child.slot, 3, payload.physical(), 64, 50_000_000),
|
||||
Ok(64)
|
||||
);
|
||||
assert_eq!(payload.bytes(), &[child.slot; 64]);
|
||||
assert_eq!(
|
||||
controller.transfer(child.slot, 4, payload.physical(), 64, 1000),
|
||||
controller.transfer(child.slot, 4, payload.physical(), 64, 50_000_000),
|
||||
Ok(64)
|
||||
);
|
||||
assert_eq!(model.borrow().outgoing, [vec![child.slot; 64]]);
|
||||
@@ -591,7 +591,7 @@ fn failed_later_port_preserves_prior_child_dma_and_does_not_authorize_behind_hub
|
||||
.unwrap();
|
||||
let payload = dma.allocate(64, 64).unwrap();
|
||||
assert_eq!(
|
||||
controller.transfer(child.slot, 3, payload.physical(), 64, 1000),
|
||||
controller.transfer(child.slot, 3, payload.physical(), 64, 50_000_000),
|
||||
Ok(64)
|
||||
);
|
||||
let commands = model.borrow().commands.len();
|
||||
@@ -609,7 +609,7 @@ fn failed_later_port_preserves_prior_child_dma_and_does_not_authorize_behind_hub
|
||||
assert_eq!(model.borrow().commands.len(), commands);
|
||||
assert!(controller.live_slot(child.slot).is_ok());
|
||||
assert_eq!(
|
||||
controller.transfer(child.slot, 3, payload.physical(), 64, 1000),
|
||||
controller.transfer(child.slot, 3, payload.physical(), 64, 50_000_000),
|
||||
Ok(64)
|
||||
);
|
||||
let old_output = controller.slot(child.slot).unwrap()._output.physical();
|
||||
|
||||
@@ -50,8 +50,8 @@ impl Controller {
|
||||
"USB2 split endpoint has no Configure ACK",
|
||||
));
|
||||
}
|
||||
let word0 = state._output.read::<u32>(usize::from(dci) * context);
|
||||
let word1 = state._output.read::<u32>(usize::from(dci) * context + 4);
|
||||
let word0 = state._output.coherent_u32(usize::from(dci) * context)?;
|
||||
let word1 = state._output.coherent_u32(usize::from(dci) * context + 4)?;
|
||||
let kind = word1 >> ENDPOINT_TYPE_SHIFT & ENDPOINT_TYPE_MASK;
|
||||
// TT buffer recovery is for control/bulk, never interrupt/isochronous.
|
||||
if matches!(kind, 1 | 3 | 5 | 7) {
|
||||
@@ -71,7 +71,7 @@ impl Controller {
|
||||
"USB2 TT clear requires acknowledged endpoint stop",
|
||||
));
|
||||
}
|
||||
let address = state._output.read::<u32>(12) & DEVICE_ADDRESS_MASK;
|
||||
let address = state._output.coherent_u32(12)? & DEVICE_ADDRESS_MASK;
|
||||
if address == 0 {
|
||||
return Err(BlockError::Unsupported(
|
||||
"USB2 TT clear requires actual addressed slot context",
|
||||
|
||||
@@ -426,6 +426,26 @@ fn trb_control(recipe: Recipe, length: usize, frame: u32) -> u32 {
|
||||
}
|
||||
|
||||
impl Controller {
|
||||
pub(super) fn cancel_native_iso(&mut self, ticket: &IsoTransfer) -> Result<(), BlockError> {
|
||||
let slot = self.validate_id(ticket.device_id())?;
|
||||
let valid = self.slots[usize::from(slot)]
|
||||
.as_ref()
|
||||
.and_then(|state| state.endpoints[usize::from(ticket.dci)].as_ref())
|
||||
.and_then(|endpoint| endpoint.iso.as_ref())
|
||||
.is_some_and(|queue| {
|
||||
queue
|
||||
.active
|
||||
.iter()
|
||||
.any(|active| active.id == ticket.id && active.trb == ticket.trb)
|
||||
});
|
||||
if !valid {
|
||||
return Err(BlockError::Unsupported(
|
||||
"stale or foreign native ISO cancellation",
|
||||
));
|
||||
}
|
||||
self.cancel_owned(slot, ticket.dci)
|
||||
}
|
||||
|
||||
/// Preflight a bounded list of requests against the current native endpoint.
|
||||
/// This neither reserves ring space nor publishes DMA: the returned values
|
||||
/// are requests, and every `submit_iso_scheduled` must revalidate them. Time
|
||||
@@ -483,7 +503,7 @@ impl Controller {
|
||||
};
|
||||
for offset in 0..packet_count {
|
||||
let index = (transfer.ring.index + offset) % (RING_TRBS - 1);
|
||||
let trb = transfer.ring.buffer.physical() + (index * TRB) as u64;
|
||||
let trb = transfer.ring.buffer.device_address() + (index * TRB) as u64;
|
||||
if queue.active.iter().any(|active| active.trb == trb) {
|
||||
return Err(BlockError::Unsupported("isochronous ring is full"));
|
||||
}
|
||||
@@ -563,6 +583,23 @@ impl Controller {
|
||||
buffer: u64,
|
||||
length: usize,
|
||||
requested: IsoSchedule,
|
||||
) -> Result<IsoTransfer, BlockError> {
|
||||
self.device_id(slot)?;
|
||||
if self.native_memory.is_some() {
|
||||
return Err(BlockError::Unsupported(
|
||||
"native xHCI requires a retained typed payload",
|
||||
));
|
||||
}
|
||||
self.submit_iso_scheduled_buffer(slot, dci, buffer, length, requested)
|
||||
}
|
||||
|
||||
pub(in crate::usb::xhci) fn submit_iso_scheduled_buffer(
|
||||
&mut self,
|
||||
slot: u8,
|
||||
dci: u8,
|
||||
buffer: u64,
|
||||
length: usize,
|
||||
requested: IsoSchedule,
|
||||
) -> Result<IsoTransfer, BlockError> {
|
||||
let device = self.device_id(slot)?;
|
||||
self.validate_id(device)?;
|
||||
@@ -631,7 +668,7 @@ impl Controller {
|
||||
bytes: length,
|
||||
done: None,
|
||||
});
|
||||
transfer.ring.push(&[(buffer, length as u32, control)]);
|
||||
transfer.ring.push(&[(buffer, length as u32, control)])?;
|
||||
queue.next = Some((start + interval) % MICROFRAMES);
|
||||
self.doorbell(slot, dci);
|
||||
Ok(IsoTransfer {
|
||||
@@ -1041,17 +1078,18 @@ pub(super) mod tests {
|
||||
parent: None,
|
||||
},
|
||||
retiring: false,
|
||||
input: dma.allocate(33 * context_bytes, 64).unwrap(),
|
||||
_output: output,
|
||||
input: dma.allocate(33 * context_bytes, 64).unwrap().into(),
|
||||
_output: output.into(),
|
||||
context: [u32::from(speed) << 20 | 1 << 27, 1 << 16, 0, 0],
|
||||
endpoints: Default::default(),
|
||||
retired_rings: Default::default(),
|
||||
control: dma.allocate(CONTROL_BYTES, CONTROL_BYTES).unwrap(),
|
||||
control: dma.allocate(CONTROL_BYTES, CONTROL_BYTES).unwrap().into(),
|
||||
speed,
|
||||
current_configuration: Some(1),
|
||||
}));
|
||||
(
|
||||
Controller {
|
||||
native_memory: None,
|
||||
registers: Box::new(Model(model.clone())),
|
||||
clock: Clock {
|
||||
ticks_per_microsecond: 1,
|
||||
@@ -1069,11 +1107,11 @@ pub(super) mod tests {
|
||||
max_slots: 1,
|
||||
max_ports: 1,
|
||||
port_major: vec![2],
|
||||
dcbaa: dma.allocate(16, 64).unwrap(),
|
||||
dcbaa: dma.allocate(16, 64).unwrap().into(),
|
||||
_scratchpads: Vec::new(),
|
||||
commands,
|
||||
events,
|
||||
_event_table: dma.allocate(16, 64).unwrap(),
|
||||
events: events.into(),
|
||||
_event_table: dma.allocate(16, 64).unwrap().into(),
|
||||
event_index: 0,
|
||||
event_cycle: true,
|
||||
legacy_slot_fenced: vec![false; slots.len()],
|
||||
@@ -2912,6 +2950,10 @@ pub(super) mod tests {
|
||||
pub(crate) fn set_mfindex(&self, value: u32) {
|
||||
self.hardware.borrow_mut().mfindex = value;
|
||||
}
|
||||
/// Service actual queued FrameID/interval words at this model tick.
|
||||
pub(crate) fn service_at(&self, dci: u8, microframe: u32, code: u32) {
|
||||
self.hardware.borrow_mut().service_at(dci, microframe, code);
|
||||
}
|
||||
/// Complete the oldest actual queued service on this endpoint.
|
||||
pub(crate) fn complete(&self, dci: u8, code: u32, residual: usize) {
|
||||
self.hardware.borrow_mut().complete(dci, 0, code, residual);
|
||||
|
||||
@@ -42,7 +42,7 @@ struct Hub {
|
||||
endpoint: Endpoint,
|
||||
ports: u8,
|
||||
ssp: Option<hub::descriptor::Ssp>,
|
||||
bitmap: DmaBuffer,
|
||||
bitmap: memory::Buffer,
|
||||
pending: Option<u64>,
|
||||
retired: bool,
|
||||
recovery: Option<Recovery>,
|
||||
@@ -154,7 +154,7 @@ impl Host {
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let bitmap = c.dma_profile.allocate(dma, 64, 64)?;
|
||||
let bitmap = c.allocate(dma, 64, 64)?;
|
||||
Ok(Hub {
|
||||
device: device.clone(),
|
||||
attachment,
|
||||
@@ -431,7 +431,7 @@ impl Host {
|
||||
owner.bitmap.bytes_mut().fill(0);
|
||||
owner.pending = Some(c.device(owner.device.id)?.submit(
|
||||
owner.endpoint.dci(),
|
||||
owner.bitmap.physical(),
|
||||
owner.bitmap.device_address(),
|
||||
length,
|
||||
)?);
|
||||
return Ok(());
|
||||
@@ -487,7 +487,7 @@ impl Host {
|
||||
self.controller
|
||||
.borrow_mut()
|
||||
.device(owner.device.id)?
|
||||
.submit(owner.endpoint.dci(), owner.bitmap.physical(), length)?,
|
||||
.submit(owner.endpoint.dci(), owner.bitmap.device_address(), length)?,
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
//! xhci_bus_suspend/xhci_bus_resume provide the physical ordering. Canceled
|
||||
//! class TDs are never replayed: resume resets and publishes fresh generations.
|
||||
use super::*;
|
||||
mod time;
|
||||
|
||||
const LINK_STROBE: u32 = 1 << 16;
|
||||
const LINK_CHANGE: u32 = 1 << 22;
|
||||
@@ -12,8 +13,10 @@ const OVER_CURRENT: u32 = 1 << 3;
|
||||
const U3: u32 = 3;
|
||||
const RESUME: u32 = 15;
|
||||
const SUSPEND_SETTLE_US: u64 = 10_000;
|
||||
const RESUME_SIGNAL_US: u64 = 20_000;
|
||||
// xhci_bus_resume uses include/linux/usb.h USB_RESUME_TIMEOUT, 40ms.
|
||||
const RESUME_SIGNAL_US: u64 = 40_000;
|
||||
const LINK_TIMEOUT_US: u64 = 100_000;
|
||||
const RESUME_LINK_TIMEOUT_US: u64 = 10_000;
|
||||
const RESUME_RECOVERY_US: u64 = 10_000;
|
||||
|
||||
#[derive(Default)]
|
||||
@@ -49,6 +52,13 @@ impl Host {
|
||||
));
|
||||
return changes;
|
||||
}
|
||||
if let Err(error) = time::check(self.controller.borrow().clock) {
|
||||
changes
|
||||
.added
|
||||
.failures
|
||||
.push(("USB suspend timing".into(), error));
|
||||
return changes;
|
||||
}
|
||||
self.reconcile(&mut changes);
|
||||
let result = self.prepare_suspend(&mut changes);
|
||||
match result {
|
||||
@@ -139,7 +149,7 @@ impl Host {
|
||||
c.root_link_write(port, actual, U3, LINK_CHANGE);
|
||||
c.wait_root_link(port, before, U3, false)?;
|
||||
}
|
||||
c.clock.delay(SUSPEND_SETTLE_US);
|
||||
time::delay(c.clock, SUSPEND_SETTLE_US)?;
|
||||
c.suspend_controller()?;
|
||||
for hub in &mut self.hubs {
|
||||
hub.pending = None;
|
||||
@@ -157,6 +167,15 @@ impl Host {
|
||||
firmware: &dyn crate::firmware::Provider,
|
||||
) -> Changes {
|
||||
let mut changes = Changes::default();
|
||||
if matches!(&self.sleep, Sleep::Suspended(_))
|
||||
&& let Err(error) = time::check(self.controller.borrow().clock)
|
||||
{
|
||||
changes
|
||||
.added
|
||||
.failures
|
||||
.push(("USB resume timing".into(), error));
|
||||
return changes;
|
||||
}
|
||||
let previous = core::mem::replace(&mut self.sleep, Sleep::Failed);
|
||||
let Sleep::Suspended(snapshot) = previous else {
|
||||
self.sleep = previous;
|
||||
@@ -243,6 +262,7 @@ impl Host {
|
||||
|
||||
fn restore_suspend(&mut self, snapshot: &Snapshot) -> Result<(), BlockError> {
|
||||
let mut c = self.controller.borrow_mut();
|
||||
time::check(c.clock)?;
|
||||
c.validate_suspend_snapshot(snapshot)?;
|
||||
c.resume_controller()?;
|
||||
for &(port, before) in &snapshot.roots {
|
||||
@@ -257,7 +277,7 @@ impl Host {
|
||||
let usb2 = c.port_major[usize::from(port - 1)] == 2;
|
||||
c.root_link_write(port, actual, if usb2 { RESUME } else { 0 }, LINK_CHANGE);
|
||||
if usb2 {
|
||||
c.clock.delay(RESUME_SIGNAL_US);
|
||||
time::delay(c.clock, RESUME_SIGNAL_US)?;
|
||||
let actual = c.read_suspend_port(port);
|
||||
root_session(before, actual)?;
|
||||
c.root_link_write(port, actual, 0, LINK_CHANGE);
|
||||
@@ -266,7 +286,7 @@ impl Host {
|
||||
let actual = c.read_suspend_port(port);
|
||||
c.root_link_write(port, actual, 0, LINK_CHANGE);
|
||||
}
|
||||
c.clock.delay(RESUME_RECOVERY_US);
|
||||
time::delay(c.clock, RESUME_RECOVERY_US)?;
|
||||
// Restore parents before sending controls through their EP0 to children.
|
||||
for &(id, attachment) in snapshot.topology.iter().rev() {
|
||||
if !c.known_id(id)
|
||||
@@ -376,7 +396,14 @@ impl Controller {
|
||||
link: u32,
|
||||
change: bool,
|
||||
) -> Result<(), BlockError> {
|
||||
let deadline = self.clock.deadline(LINK_TIMEOUT_US);
|
||||
let deadline = time::Deadline::new(
|
||||
self.clock,
|
||||
if change {
|
||||
RESUME_LINK_TIMEOUT_US
|
||||
} else {
|
||||
LINK_TIMEOUT_US
|
||||
},
|
||||
)?;
|
||||
loop {
|
||||
self.ready()?;
|
||||
let actual = self.read_suspend_port(port);
|
||||
@@ -387,7 +414,7 @@ impl Controller {
|
||||
if deadline.passed() {
|
||||
return Err(BlockError::Timeout);
|
||||
}
|
||||
self.clock.delay(100);
|
||||
time::delay(self.clock, 100)?;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -16,6 +16,10 @@ struct State {
|
||||
save: usize,
|
||||
restore: usize,
|
||||
refuse_suspend: bool,
|
||||
refuse_resume: bool,
|
||||
resume_started: Option<u64>,
|
||||
resume_durations: Vec<u64>,
|
||||
minimum_resume_ticks: u64,
|
||||
}
|
||||
impl RegisterIo for Registers {
|
||||
fn read32(&mut self, at: usize) -> u32 {
|
||||
@@ -27,8 +31,24 @@ impl RegisterIo for Registers {
|
||||
let mut bus = self.bus.0.borrow_mut();
|
||||
let port = bus.root_status.as_mut().unwrap();
|
||||
let requested = value & PLS;
|
||||
if requested != U3 << PLS_SHIFT || !self.state.borrow().refuse_suspend {
|
||||
let previous = *port & PLS;
|
||||
let previous = *port & PLS;
|
||||
let refused = requested == U3 << PLS_SHIFT && self.state.borrow().refuse_suspend
|
||||
|| previous == RESUME << PLS_SHIFT
|
||||
&& requested == 0
|
||||
&& self.state.borrow().refuse_resume;
|
||||
if !refused {
|
||||
if requested == RESUME << PLS_SHIFT && previous != requested {
|
||||
self.state.borrow_mut().resume_started = Some(Clock::ticks());
|
||||
}
|
||||
if previous == RESUME << PLS_SHIFT && requested == 0 {
|
||||
let mut state = self.state.borrow_mut();
|
||||
let elapsed = Clock::ticks().wrapping_sub(state.resume_started.take().unwrap());
|
||||
assert!(
|
||||
elapsed >= state.minimum_resume_ticks,
|
||||
"actual USB2 root left Resume before source 40ms"
|
||||
);
|
||||
state.resume_durations.push(elapsed);
|
||||
}
|
||||
*port = *port & !PLS | requested;
|
||||
if previous != requested {
|
||||
*port |= LINK_CHANGE;
|
||||
@@ -54,6 +74,200 @@ impl RegisterIo for Registers {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn actual_usb2_root_resume_preserves_source_forty_millisecond_signal_before_u0() {
|
||||
for speed in [HIGH_SPEED, SUPER_SPEED] {
|
||||
let mut memory = vec![0u64; 512 * 1024];
|
||||
let (mut host, devices, hardware, state, mut dma) =
|
||||
fixture_with_leaf(&mut memory, speed, false, Node::bot_disk(speed));
|
||||
let mut original = bind_root_disk(&host, &devices, &mut dma);
|
||||
let payload = [0x6c; 512];
|
||||
original.disks[0].write(2, &payload).unwrap();
|
||||
// Independent test TSC scale, not a measured host-clock calibration.
|
||||
// The model's physical PORTSC
|
||||
// assertion uses the original source macro, not the production constant.
|
||||
host.controller.borrow_mut().clock.ticks_per_microsecond = 1_000;
|
||||
state.borrow_mut().minimum_resume_ticks = 40_000 * 1_000;
|
||||
let suspended = host.suspend();
|
||||
assert!(
|
||||
suspended.added.failures.is_empty(),
|
||||
"{:?}",
|
||||
suspended.added.failures
|
||||
);
|
||||
let mut resumed = host.resume(&mut dma, &crate::firmware::HandoffProvider::new(None));
|
||||
assert!(
|
||||
resumed.added.failures.is_empty(),
|
||||
"{:?}",
|
||||
resumed.added.failures
|
||||
);
|
||||
assert!(host.sleep.awake());
|
||||
assert_eq!(hardware.borrow().root_status.unwrap() & PLS, 0);
|
||||
assert_eq!(
|
||||
state.borrow().resume_durations.len(),
|
||||
usize::from(speed == HIGH_SPEED)
|
||||
);
|
||||
assert_eq!(resumed.added.disks.len(), 1);
|
||||
let mut actual = [0; 512];
|
||||
resumed.added.disks[0].read(2, &mut actual).unwrap();
|
||||
assert_eq!(actual, payload);
|
||||
assert!(original.disks[0].read(2, &mut actual).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unavailable_root_timing_preserves_live_consumers_before_any_suspend_effect() {
|
||||
for rate in [0, u64::MAX] {
|
||||
let mut memory = vec![0u64; 512 * 1024];
|
||||
let (mut host, devices, hardware, state, mut dma) = fixture(&mut memory, HIGH_SPEED, false);
|
||||
let mut consumer = RawConsumer::retain(&host, &devices[0], &mut dma);
|
||||
host.controller.borrow_mut().clock.ticks_per_microsecond = rate;
|
||||
let before = {
|
||||
let bus = hardware.borrow();
|
||||
(
|
||||
bus.mmio_reads,
|
||||
bus.mmio_writes,
|
||||
bus.commands.clone(),
|
||||
bus.requests.clone(),
|
||||
bus.root_status,
|
||||
)
|
||||
};
|
||||
let refused = host.suspend();
|
||||
assert_eq!(refused.added.failures.len(), 1);
|
||||
assert!(refused.removed.is_empty());
|
||||
assert!(host.sleep.awake());
|
||||
assert_eq!(state.borrow().save, 0);
|
||||
let after = {
|
||||
let bus = hardware.borrow();
|
||||
(
|
||||
bus.mmio_reads,
|
||||
bus.mmio_writes,
|
||||
bus.commands.clone(),
|
||||
bus.requests.clone(),
|
||||
bus.root_status,
|
||||
)
|
||||
};
|
||||
assert_eq!(before, after);
|
||||
host.controller.borrow_mut().clock.ticks_per_microsecond = 1;
|
||||
assert!(consumer.submit().is_ok());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_actual_root_u0_acknowledgement_retains_fenced_original_consumers() {
|
||||
let mut memory = vec![0u64; 512 * 1024];
|
||||
let (mut host, devices, hardware, state, mut dma) = fixture(&mut memory, HIGH_SPEED, false);
|
||||
let mut consumer = RawConsumer::retain(&host, &devices[0], &mut dma);
|
||||
let suspended = host.suspend();
|
||||
assert!(suspended.added.failures.is_empty());
|
||||
state.borrow_mut().refuse_resume = true;
|
||||
let before = hardware.borrow().commands.len();
|
||||
let refused = host.resume(&mut dma, &crate::firmware::HandoffProvider::new(None));
|
||||
assert!(
|
||||
refused
|
||||
.added
|
||||
.failures
|
||||
.iter()
|
||||
.any(|(_, error)| *error == BlockError::Timeout)
|
||||
);
|
||||
assert!(refused.added.devices.is_empty());
|
||||
assert!(matches!(host.sleep, Sleep::Failed));
|
||||
assert_eq!(
|
||||
hardware.borrow().root_status.unwrap() & PLS,
|
||||
RESUME << PLS_SHIFT
|
||||
);
|
||||
assert!(
|
||||
hardware.borrow().commands[before..]
|
||||
.iter()
|
||||
.all(|(kind, _)| *kind != reset::DISABLE_SLOT)
|
||||
);
|
||||
consumer.assert_fenced(&hardware);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unavailable_resume_timing_retains_private_snapshot_without_an_extra_consumer_fence() {
|
||||
for rate in [0, u64::MAX] {
|
||||
let mut memory = vec![0u64; 512 * 1024];
|
||||
let (mut host, devices, hardware, state, mut dma) =
|
||||
fixture_with_leaf(&mut memory, HIGH_SPEED, false, Node::bot_disk(HIGH_SPEED));
|
||||
let mut original = bind_root_disk(&host, &devices, &mut dma);
|
||||
let payload = [0x7d; 512];
|
||||
original.disks[0].write(3, &payload).unwrap();
|
||||
assert!(host.suspend().added.failures.is_empty());
|
||||
let before = {
|
||||
let bus = hardware.borrow();
|
||||
(
|
||||
bus.mmio_reads,
|
||||
bus.mmio_writes,
|
||||
bus.commands.clone(),
|
||||
bus.requests.clone(),
|
||||
bus.root_status,
|
||||
)
|
||||
};
|
||||
let prior_roots = match &host.sleep {
|
||||
Sleep::Suspended(snapshot) => snapshot.roots.clone(),
|
||||
_ => panic!("actual suspend snapshot required"),
|
||||
};
|
||||
let prior_slots: Vec<_> = host
|
||||
.controller
|
||||
.borrow()
|
||||
.slots
|
||||
.iter()
|
||||
.map(|slot| slot.as_ref().map(|slot| (slot.retiring, slot.suspended)))
|
||||
.collect();
|
||||
host.controller.borrow_mut().clock.ticks_per_microsecond = rate;
|
||||
let refused = host.resume(&mut dma, &crate::firmware::HandoffProvider::new(None));
|
||||
assert_eq!(refused.added.failures.len(), 1);
|
||||
assert!(refused.added.devices.is_empty() && refused.removed.is_empty());
|
||||
match &host.sleep {
|
||||
Sleep::Suspended(snapshot) => assert_eq!(snapshot.roots, prior_roots),
|
||||
_ => panic!("pure timing refusal lost original private snapshot"),
|
||||
}
|
||||
let after = {
|
||||
let bus = hardware.borrow();
|
||||
(
|
||||
bus.mmio_reads,
|
||||
bus.mmio_writes,
|
||||
bus.commands.clone(),
|
||||
bus.requests.clone(),
|
||||
bus.root_status,
|
||||
)
|
||||
};
|
||||
assert_eq!(before, after);
|
||||
let current_slots: Vec<_> = host
|
||||
.controller
|
||||
.borrow()
|
||||
.slots
|
||||
.iter()
|
||||
.map(|slot| slot.as_ref().map(|slot| (slot.retiring, slot.suspended)))
|
||||
.collect();
|
||||
assert_eq!(current_slots, prior_slots);
|
||||
assert_eq!(state.borrow().restore, 0);
|
||||
host.controller.borrow_mut().clock.ticks_per_microsecond = 1;
|
||||
let mut resumed = host.resume(&mut dma, &crate::firmware::HandoffProvider::new(None));
|
||||
assert!(
|
||||
resumed.added.failures.is_empty(),
|
||||
"{:?}",
|
||||
resumed.added.failures
|
||||
);
|
||||
assert!(host.sleep.awake());
|
||||
assert_eq!(state.borrow().restore, 1);
|
||||
assert_eq!(resumed.added.disks.len(), 1);
|
||||
let mut actual = [0; 512];
|
||||
resumed.added.disks[0].read(3, &mut actual).unwrap();
|
||||
assert_eq!(actual, payload);
|
||||
assert!(original.disks[0].read(3, &mut actual).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
fn bind_root_disk(host: &Host, devices: &[Device], dma: &mut RegionAllocator) -> Found {
|
||||
assert_eq!(devices.len(), 1);
|
||||
let mut found = Found::default();
|
||||
crate::usb::xhci::bind::bind(&host.controller, devices[0].clone(), dma, &mut found);
|
||||
assert!(found.failures.is_empty(), "{:?}", found.failures);
|
||||
assert_eq!(found.disks.len(), 1);
|
||||
found
|
||||
}
|
||||
|
||||
type Fixture = (
|
||||
Host,
|
||||
Vec<Device>,
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
//! Checked original calibrated timer for root-link transitions only.
|
||||
use super::*;
|
||||
use crate::bus::pci::power::Timer;
|
||||
|
||||
fn ticks(clock: Clock, microseconds: u64) -> Result<u64, BlockError> {
|
||||
clock
|
||||
.ticks_per_microsecond
|
||||
.checked_mul(microseconds)
|
||||
.filter(|value| clock.ticks_per_microsecond != 0 && *value <= u64::MAX / 2)
|
||||
.ok_or(BlockError::Unsupported(
|
||||
"USB root transition clock unavailable or out of range",
|
||||
))
|
||||
}
|
||||
pub(super) fn check(clock: Clock) -> Result<(), BlockError> {
|
||||
clock.check().map_err(|_| {
|
||||
BlockError::Unsupported("USB root transition clock unavailable or out of range")
|
||||
})?;
|
||||
ticks(clock, LINK_TIMEOUT_US).map(|_| ())
|
||||
}
|
||||
pub(super) fn delay(clock: Clock, microseconds: u64) -> Result<(), BlockError> {
|
||||
ticks(clock, microseconds)?;
|
||||
clock.wait_us(microseconds).map_err(|_| {
|
||||
BlockError::Unsupported("USB root transition clock unavailable or out of range")
|
||||
})
|
||||
}
|
||||
pub(super) struct Deadline {
|
||||
start: u64,
|
||||
ticks: u64,
|
||||
}
|
||||
impl Deadline {
|
||||
pub(super) fn new(clock: Clock, microseconds: u64) -> Result<Self, BlockError> {
|
||||
let ticks = ticks(clock, microseconds)?;
|
||||
Ok(Self {
|
||||
start: Clock::ticks(),
|
||||
ticks,
|
||||
})
|
||||
}
|
||||
fn passed_at(&self, now: u64) -> bool {
|
||||
now.wrapping_sub(self.start) >= self.ticks
|
||||
}
|
||||
pub(super) fn passed(&self) -> bool {
|
||||
self.passed_at(Clock::ticks())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn checked_root_deadlines_preserve_full_duration_across_raw_counter_wrap() {
|
||||
for rate in [1, 3, 3_000, 100_000] {
|
||||
for duration in [100, 10_000, 40_000, 100_000] {
|
||||
let clock = Clock {
|
||||
ticks_per_microsecond: rate,
|
||||
};
|
||||
let wanted = ticks(clock, duration).unwrap();
|
||||
let deadline = Deadline {
|
||||
start: u64::MAX - wanted / 2,
|
||||
ticks: wanted,
|
||||
};
|
||||
assert!(!deadline.passed_at(deadline.start));
|
||||
assert!(!deadline.passed_at(deadline.start.wrapping_add(wanted - 1)));
|
||||
assert!(deadline.passed_at(deadline.start.wrapping_add(wanted)));
|
||||
assert!(deadline.passed_at(deadline.start.wrapping_add(wanted + 1)));
|
||||
}
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn invalid_root_rates_refuse_before_counter_or_delay_use() {
|
||||
for rate in [0, u64::MAX, u64::MAX / 100_000 + 1] {
|
||||
let clock = Clock {
|
||||
ticks_per_microsecond: rate,
|
||||
};
|
||||
assert!(check(clock).is_err());
|
||||
assert!(Deadline::new(clock, 100_000).is_err());
|
||||
}
|
||||
assert_eq!(
|
||||
ticks(
|
||||
Clock {
|
||||
ticks_per_microsecond: 3_000
|
||||
},
|
||||
40_000
|
||||
),
|
||||
Ok(120_000_000)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,213 @@
|
||||
//! Distinct CPU and device views for xHCI-owned storage.
|
||||
//!
|
||||
//! The boot allocator remains an explicitly separate lifetime. Native storage
|
||||
//! retains the original domain and pins; no IOVA is interpreted as a pointer.
|
||||
use super::*;
|
||||
use crate::bus::dma::{
|
||||
DmaValue,
|
||||
mapping::{Direction, DmaDomain},
|
||||
memory::{CacheAttribute, PageSource},
|
||||
region::{self, DmaRegion},
|
||||
};
|
||||
use alloc::sync::Arc;
|
||||
use core::{any::Any, cell::Cell, ops::Range};
|
||||
|
||||
pub(super) struct Native {
|
||||
pub(super) pages: Arc<dyn PageSource>,
|
||||
pub(super) domain: Arc<dyn DmaDomain>,
|
||||
// The real requester/configuration/UC/IRQ owner, independent of RAM pins.
|
||||
pub(super) _owner: Rc<dyn Any>,
|
||||
register_failure: Rc<Cell<Option<usize>>>,
|
||||
failure: RefCell<Option<region::Error>>,
|
||||
}
|
||||
|
||||
impl Native {
|
||||
pub(super) fn new(
|
||||
pages: Arc<dyn PageSource>,
|
||||
domain: Arc<dyn DmaDomain>,
|
||||
owner: Rc<dyn Any>,
|
||||
register_failure: Rc<Cell<Option<usize>>>,
|
||||
) -> Self {
|
||||
Self {
|
||||
pages,
|
||||
domain,
|
||||
_owner: owner,
|
||||
register_failure,
|
||||
failure: RefCell::new(None),
|
||||
}
|
||||
}
|
||||
|
||||
fn result<T>(&self, result: Result<T, region::Error>) -> Result<T, BlockError> {
|
||||
result.map_err(|error| {
|
||||
self.failure.borrow_mut().get_or_insert(error);
|
||||
BlockError::Unsupported("xHCI original DMA mapping or visibility failed")
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn ready(&self) -> Result<(), BlockError> {
|
||||
if self.register_failure.get().is_some() {
|
||||
return Err(BlockError::Unsupported(
|
||||
"xHCI original register mapping is uncertain",
|
||||
));
|
||||
}
|
||||
if self.failure.borrow().is_some() {
|
||||
Err(BlockError::Unsupported(
|
||||
"xHCI original DMA owner is uncertain",
|
||||
))
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn error(&self) -> Option<region::Error> {
|
||||
*self.failure.borrow()
|
||||
}
|
||||
|
||||
pub(super) fn allocate(
|
||||
self: &Rc<Self>,
|
||||
bytes: usize,
|
||||
align: usize,
|
||||
limit: u64,
|
||||
) -> Result<Buffer, BlockError> {
|
||||
self.ready()?;
|
||||
let region = self.result(DmaRegion::allocate(
|
||||
&*self.pages,
|
||||
self.domain.clone(),
|
||||
bytes,
|
||||
align,
|
||||
CacheAttribute::WriteBack,
|
||||
Direction::Bidirectional,
|
||||
limit,
|
||||
))?;
|
||||
let pointer = self.result(region.cpu_address(0, bytes))?;
|
||||
// SAFETY: the native attachment grants exclusive fresh RAM ownership.
|
||||
// Mapping does not itself zero pages. No device pointer is published.
|
||||
unsafe {
|
||||
pointer.as_ptr().write_bytes(0, bytes);
|
||||
}
|
||||
Ok(Buffer {
|
||||
backing: Backing::Native(Box::new(region), self.clone()),
|
||||
dirty: Cell::new(true),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
enum Backing {
|
||||
Boot(DmaBuffer),
|
||||
Native(Box<DmaRegion>, Rc<Native>),
|
||||
}
|
||||
|
||||
pub(super) struct Buffer {
|
||||
backing: Backing,
|
||||
dirty: Cell<bool>,
|
||||
}
|
||||
|
||||
impl From<DmaBuffer> for Buffer {
|
||||
fn from(buffer: DmaBuffer) -> Self {
|
||||
Self {
|
||||
backing: Backing::Boot(buffer),
|
||||
dirty: Cell::new(false),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Buffer {
|
||||
pub(super) fn len(&self) -> usize {
|
||||
match &self.backing {
|
||||
Backing::Boot(b) => b.len(),
|
||||
Backing::Native(b, _) => b.bytes(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn device_address(&self) -> u64 {
|
||||
match &self.backing {
|
||||
Backing::Boot(b) => b.physical(),
|
||||
Backing::Native(b, _) => b
|
||||
.device_address(0, b.bytes())
|
||||
.expect("live private xHCI mapping"),
|
||||
}
|
||||
}
|
||||
|
||||
// Legacy test peers use their model address as the CPU/physical label.
|
||||
#[cfg(test)]
|
||||
pub(super) fn physical(&self) -> u64 {
|
||||
self.device_address()
|
||||
}
|
||||
|
||||
pub(super) fn as_ptr(&self) -> *mut u8 {
|
||||
match &self.backing {
|
||||
Backing::Boot(b) => b.as_ptr(),
|
||||
Backing::Native(b, _) => b
|
||||
.cpu_address(0, b.bytes())
|
||||
.expect("retained CPU pin")
|
||||
.as_ptr(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn bytes(&self) -> &[u8] {
|
||||
// SAFETY: private users must establish completed CPU ownership before
|
||||
// borrowing. This never uses the device address as a CPU address.
|
||||
unsafe { core::slice::from_raw_parts(self.as_ptr(), self.len()) }
|
||||
}
|
||||
|
||||
pub(super) fn bytes_mut(&mut self) -> &mut [u8] {
|
||||
self.dirty.set(true);
|
||||
// SAFETY: private users hold exclusive stopped/unpublished CPU storage.
|
||||
unsafe { core::slice::from_raw_parts_mut(self.as_ptr(), self.len()) }
|
||||
}
|
||||
|
||||
fn word<T: DmaValue>(&self, at: usize) -> *mut T {
|
||||
assert!(at <= self.len() && size_of::<T>() <= self.len() - at);
|
||||
// SAFETY: checked complete range into the actual CPU mapping.
|
||||
let pointer = unsafe { self.as_ptr().add(at) }.cast::<T>();
|
||||
assert!((pointer as usize).is_multiple_of(align_of::<T>()));
|
||||
pointer
|
||||
}
|
||||
|
||||
pub(super) fn read<T: DmaValue>(&self, at: usize) -> T {
|
||||
// SAFETY: checked CPU word; callers supply ownership, not a timeout.
|
||||
unsafe { self.word::<T>(at).read_volatile() }
|
||||
}
|
||||
|
||||
pub(super) fn write<T: DmaValue>(&mut self, at: usize, value: T) {
|
||||
// SAFETY: checked exclusive software-owned CPU word.
|
||||
unsafe {
|
||||
self.word::<T>(at).write_volatile(value);
|
||||
}
|
||||
self.dirty.set(true);
|
||||
}
|
||||
|
||||
pub(super) fn coherent_u32(&self, at: usize) -> Result<u32, BlockError> {
|
||||
match &self.backing {
|
||||
Backing::Boot(_) => Ok(self.read(at)),
|
||||
Backing::Native(b, owner) => owner.result(b.read_coherent_u32(at)),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn sync_device(&self, range: Range<usize>) -> Result<(), BlockError> {
|
||||
match &self.backing {
|
||||
Backing::Boot(_) => Ok(()),
|
||||
Backing::Native(b, owner) => owner.result(b.sync_for_device(range)),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn sync_dirty(&self) -> Result<(), BlockError> {
|
||||
if self.dirty.get() {
|
||||
self.sync_device(0..self.len())?;
|
||||
self.dirty.set(false);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Actual completion establishes CPU ownership of this exact range.
|
||||
pub(super) unsafe fn sync_cpu(&self, range: Range<usize>) -> Result<(), BlockError> {
|
||||
match &self.backing {
|
||||
Backing::Boot(_) => Ok(()),
|
||||
// SAFETY: caller supplies original hardware completion.
|
||||
Backing::Native(b, owner) => owner.result(unsafe { b.sync_for_cpu(range) }),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,474 @@
|
||||
//! Actual retained RAM with independent CPU/device caches and nonidentity labels.
|
||||
//! This peer checks production core publication; it is not physical xHCI evidence.
|
||||
use super::*;
|
||||
use crate::bus::dma::{
|
||||
mapping::{DmaError, DomainMapping},
|
||||
memory::{MemoryError, PageBacking, PageGeometry, PinnedPages},
|
||||
pages::DmaPages,
|
||||
};
|
||||
use alloc::{
|
||||
alloc::{alloc_zeroed, dealloc},
|
||||
collections::BTreeMap,
|
||||
};
|
||||
use core::{
|
||||
alloc::Layout,
|
||||
ptr::NonNull,
|
||||
sync::atomic::{AtomicUsize, Ordering},
|
||||
};
|
||||
extern crate std;
|
||||
use std::sync::Mutex;
|
||||
|
||||
struct Backing {
|
||||
pointer: NonNull<u8>,
|
||||
layout: Layout,
|
||||
physical: Vec<u64>,
|
||||
drops: Arc<AtomicUsize>,
|
||||
}
|
||||
// SAFETY: fixture CPU effects are serialized by the peer; stable exclusive RAM.
|
||||
unsafe impl Send for Backing {}
|
||||
// SAFETY: same serialized peer, no concurrent device/CPU writers or safe slices.
|
||||
unsafe impl Sync for Backing {}
|
||||
// SAFETY: aligned zeroed actual fixture RAM retains these immutable model pages.
|
||||
unsafe impl PageBacking for Backing {
|
||||
fn cpu_base(&self) -> NonNull<u8> {
|
||||
self.pointer
|
||||
}
|
||||
fn physical_pages(&self) -> &[u64] {
|
||||
&self.physical
|
||||
}
|
||||
fn page_shift(&self) -> u8 {
|
||||
12
|
||||
}
|
||||
fn cache_attribute(&self) -> CacheAttribute {
|
||||
CacheAttribute::WriteBack
|
||||
}
|
||||
}
|
||||
impl Drop for Backing {
|
||||
fn drop(&mut self) {
|
||||
self.drops.fetch_add(1, Ordering::Relaxed);
|
||||
// SAFETY: original unique fixture allocation after all pins end.
|
||||
unsafe {
|
||||
dealloc(self.pointer.as_ptr(), self.layout);
|
||||
}
|
||||
}
|
||||
}
|
||||
struct Binding {
|
||||
token: DomainMapping,
|
||||
pages: DmaPages,
|
||||
device: Vec<u8>,
|
||||
}
|
||||
struct State {
|
||||
next_iova: u64,
|
||||
next_physical: u64,
|
||||
bindings: BTreeMap<u64, Binding>,
|
||||
syncs: Vec<(bool, u64, Range<usize>, u32)>,
|
||||
observations: Vec<(u64, usize)>,
|
||||
coherent: bool,
|
||||
fail_sync: Option<usize>,
|
||||
fail_after_copy: bool,
|
||||
}
|
||||
struct Peer {
|
||||
state: Mutex<State>,
|
||||
drops: Arc<AtomicUsize>,
|
||||
}
|
||||
impl Peer {
|
||||
fn new() -> Arc<Self> {
|
||||
Arc::new(Self {
|
||||
state: Mutex::new(State {
|
||||
next_iova: 0x1_0000_1000,
|
||||
next_physical: 0x2000_0000,
|
||||
bindings: BTreeMap::new(),
|
||||
syncs: Vec::new(),
|
||||
observations: Vec::new(),
|
||||
coherent: true,
|
||||
fail_sync: None,
|
||||
fail_after_copy: false,
|
||||
}),
|
||||
drops: Arc::new(AtomicUsize::new(0)),
|
||||
})
|
||||
}
|
||||
fn range(state: &State, address: u64, bytes: usize) -> (u64, usize) {
|
||||
state
|
||||
.bindings
|
||||
.iter()
|
||||
.find_map(|(id, b)| {
|
||||
address.checked_sub(b.token.address).and_then(|offset| {
|
||||
let offset = usize::try_from(offset).ok()?;
|
||||
(offset.checked_add(bytes)? <= b.token.bytes).then_some((*id, offset))
|
||||
})
|
||||
})
|
||||
.expect("actual mapped IOVA")
|
||||
}
|
||||
fn device(&self, address: u64, bytes: usize) -> Vec<u8> {
|
||||
let state = self.state.lock().unwrap();
|
||||
let (id, offset) = Self::range(&state, address, bytes);
|
||||
state.bindings[&id].device[offset..offset + bytes].to_vec()
|
||||
}
|
||||
fn post(&self, address: u64, bytes: &[u8]) {
|
||||
let mut state = self.state.lock().unwrap();
|
||||
let (id, offset) = Self::range(&state, address, bytes.len());
|
||||
state.bindings.get_mut(&id).unwrap().device[offset..offset + bytes.len()]
|
||||
.copy_from_slice(bytes);
|
||||
}
|
||||
}
|
||||
impl PageSource for Peer {
|
||||
fn page_geometry(&self) -> Result<PageGeometry, MemoryError> {
|
||||
PageGeometry::base_only(12)
|
||||
}
|
||||
fn allocate(
|
||||
&self,
|
||||
bytes: usize,
|
||||
alignment: usize,
|
||||
attribute: CacheAttribute,
|
||||
) -> Result<PinnedPages, MemoryError> {
|
||||
assert_eq!(attribute, CacheAttribute::WriteBack);
|
||||
let bytes = bytes.next_multiple_of(4096);
|
||||
let layout = Layout::from_size_align(bytes, alignment).unwrap();
|
||||
// SAFETY: checked fixture layout and owned zeroed storage; null checked.
|
||||
let pointer =
|
||||
NonNull::new(unsafe { alloc_zeroed(layout) }).ok_or(MemoryError::OutOfMemory)?;
|
||||
let mut state = self.state.lock().unwrap();
|
||||
let physical = (0..bytes / 4096)
|
||||
.map(|n| state.next_physical + n as u64 * 8192)
|
||||
.collect();
|
||||
state.next_physical += bytes as u64 * 2;
|
||||
PinnedPages::new(
|
||||
Box::new(Backing {
|
||||
pointer,
|
||||
layout,
|
||||
physical,
|
||||
drops: self.drops.clone(),
|
||||
}),
|
||||
bytes,
|
||||
alignment,
|
||||
)
|
||||
}
|
||||
}
|
||||
fn cpu(binding: &Binding, range: Range<usize>) -> NonNull<u8> {
|
||||
binding
|
||||
.pages
|
||||
.as_single()
|
||||
.unwrap()
|
||||
.cpu_mapping(CacheAttribute::WriteBack)
|
||||
.unwrap()
|
||||
.address(range.start, range.len())
|
||||
.unwrap()
|
||||
}
|
||||
// SAFETY: unique exact IOVAs/tokens, same original retained pins, real copy-based
|
||||
// CPU/device visibility, failures retain ownership. Only serialized model I/O.
|
||||
unsafe impl DmaDomain for Peer {
|
||||
unsafe fn map(
|
||||
&self,
|
||||
pages: &DmaPages,
|
||||
_: Direction,
|
||||
limit: u64,
|
||||
) -> Result<DomainMapping, DmaError> {
|
||||
let mut state = self.state.lock().unwrap();
|
||||
let address = state.next_iova;
|
||||
if address
|
||||
.checked_add(pages.bytes() as u64)
|
||||
.is_none_or(|end| end - 1 > limit)
|
||||
{
|
||||
return Err(DmaError::AddressLimit);
|
||||
}
|
||||
let token = DomainMapping {
|
||||
id: address,
|
||||
address,
|
||||
bytes: pages.bytes(),
|
||||
};
|
||||
state.next_iova += pages.bytes() as u64;
|
||||
state.bindings.insert(
|
||||
address,
|
||||
Binding {
|
||||
token,
|
||||
pages: pages.clone(),
|
||||
device: vec![0xa6; pages.bytes()],
|
||||
},
|
||||
);
|
||||
Ok(token)
|
||||
}
|
||||
unsafe fn unmap(&self, token: DomainMapping) -> Result<(), DmaError> {
|
||||
let mut state = self.state.lock().unwrap();
|
||||
if state
|
||||
.bindings
|
||||
.get(&token.id)
|
||||
.is_none_or(|b| b.token != token)
|
||||
{
|
||||
return Err(DmaError::Unmapped);
|
||||
}
|
||||
state.bindings.remove(&token.id);
|
||||
Ok(())
|
||||
}
|
||||
unsafe fn sync_for_device(
|
||||
&self,
|
||||
token: DomainMapping,
|
||||
range: Range<usize>,
|
||||
_: Direction,
|
||||
) -> Result<(), DmaError> {
|
||||
let mut state = self.state.lock().unwrap();
|
||||
let failed = state.fail_sync == Some(state.syncs.len());
|
||||
let after = state.fail_after_copy;
|
||||
if !failed || after {
|
||||
let binding = state.bindings.get_mut(&token.id).unwrap();
|
||||
// SAFETY: same exact retained pins and checked range, CPU-owned writes.
|
||||
let data = unsafe {
|
||||
core::slice::from_raw_parts(cpu(binding, range.clone()).as_ptr(), range.len())
|
||||
};
|
||||
binding.device[range.clone()].copy_from_slice(data);
|
||||
}
|
||||
let binding = &state.bindings[&token.id];
|
||||
let cycle = if range.len() == 4 {
|
||||
u32::from_le_bytes(binding.device[range.clone()].try_into().unwrap())
|
||||
} else {
|
||||
0
|
||||
};
|
||||
state.syncs.push((true, token.id, range, cycle));
|
||||
if failed {
|
||||
Err(DmaError::VisibilityFailed)
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
unsafe fn sync_for_cpu(
|
||||
&self,
|
||||
token: DomainMapping,
|
||||
range: Range<usize>,
|
||||
_: Direction,
|
||||
) -> Result<(), DmaError> {
|
||||
let mut state = self.state.lock().unwrap();
|
||||
if state.fail_sync == Some(state.syncs.len()) {
|
||||
return Err(DmaError::VisibilityFailed);
|
||||
}
|
||||
let binding = &state.bindings[&token.id];
|
||||
// SAFETY: caller's actual completion owns this precise range; peer serial.
|
||||
unsafe {
|
||||
core::ptr::copy_nonoverlapping(
|
||||
binding.device[range.clone()].as_ptr(),
|
||||
cpu(binding, range.clone()).as_ptr(),
|
||||
range.len(),
|
||||
);
|
||||
}
|
||||
state.syncs.push((false, token.id, range, 0));
|
||||
Ok(())
|
||||
}
|
||||
unsafe fn read_coherent_u32(
|
||||
&self,
|
||||
token: DomainMapping,
|
||||
offset: usize,
|
||||
_: Direction,
|
||||
) -> Result<u32, DmaError> {
|
||||
let mut state = self.state.lock().unwrap();
|
||||
if !state.coherent {
|
||||
return Err(DmaError::CoherenceUnavailable);
|
||||
}
|
||||
state.observations.push((token.id, offset));
|
||||
Ok(u32::from_le_bytes(
|
||||
state.bindings[&token.id].device[offset..offset + 4]
|
||||
.try_into()
|
||||
.unwrap(),
|
||||
))
|
||||
}
|
||||
}
|
||||
struct NoBoot;
|
||||
impl DmaAllocator for NoBoot {
|
||||
fn allocate(&mut self, _: usize, _: usize) -> Result<DmaBuffer, BlockError> {
|
||||
panic!("native core reached identity allocator")
|
||||
}
|
||||
}
|
||||
fn memory(peer: &Arc<Peer>) -> Rc<Native> {
|
||||
Rc::new(Native::new(
|
||||
peer.clone(),
|
||||
peer.clone(),
|
||||
Rc::new(()),
|
||||
Rc::new(Cell::new(None)),
|
||||
))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn native_ring_publishes_real_iova_td_before_first_cycle_and_retains_failed_visibility() {
|
||||
for failure in [None, Some(0), Some(1)] {
|
||||
let peer = Peer::new();
|
||||
let memory = memory(&peer);
|
||||
let profile = dma::Profile::pci(0x1106, 0x3483);
|
||||
let mut ring = Ring::with_memory(&mut NoBoot, profile, Some(&memory)).unwrap();
|
||||
assert_eq!(ring.buffer.len(), 8192);
|
||||
assert!(ring.buffer.device_address().is_multiple_of(8192));
|
||||
assert_ne!(ring.buffer.device_address(), ring.buffer.as_ptr() as u64);
|
||||
{
|
||||
let mut state = peer.state.lock().unwrap();
|
||||
state.fail_sync = failure;
|
||||
state.fail_after_copy = true;
|
||||
assert!(
|
||||
state
|
||||
.bindings
|
||||
.values()
|
||||
.all(|b| b.pages.physical_pages()[0] != b.token.address)
|
||||
);
|
||||
}
|
||||
let address = ring.address();
|
||||
let result = ring.push(&[(0x1234_5000, 32, NORMAL << 10 | IOC)]);
|
||||
if failure.is_some() {
|
||||
assert!(result.is_err());
|
||||
assert_eq!(
|
||||
memory.error(),
|
||||
Some(region::Error::Dma(DmaError::VisibilityFailed))
|
||||
);
|
||||
assert!(memory.ready().is_err());
|
||||
} else {
|
||||
assert_eq!(result.unwrap(), vec![address]);
|
||||
let td = peer.device(address, TRB);
|
||||
assert_eq!(u64::from_le_bytes(td[..8].try_into().unwrap()), 0x1234_5000);
|
||||
assert_eq!(u32::from_le_bytes(td[8..12].try_into().unwrap()), 32);
|
||||
assert_eq!(
|
||||
u32::from_le_bytes(td[12..].try_into().unwrap()) & CYCLE,
|
||||
CYCLE
|
||||
);
|
||||
let state = peer.state.lock().unwrap();
|
||||
assert_eq!(state.syncs.len(), 2);
|
||||
assert_eq!(state.syncs[1].2.len(), 4);
|
||||
assert_eq!(state.syncs[1].3 & CYCLE, CYCLE);
|
||||
}
|
||||
let drops = peer.drops.clone();
|
||||
drop(ring);
|
||||
assert_eq!(
|
||||
drops.load(Ordering::Relaxed),
|
||||
0,
|
||||
"active original mapping/pins must remain quarantined"
|
||||
);
|
||||
assert_eq!(peer.state.lock().unwrap().bindings.len(), 1);
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct RegistersState {
|
||||
running: bool,
|
||||
writes: Vec<(usize, u32)>,
|
||||
}
|
||||
struct CoreRegisters(Rc<RefCell<RegistersState>>);
|
||||
impl Registers for CoreRegisters {
|
||||
fn read32(&mut self, at: usize) -> u32 {
|
||||
match at {
|
||||
0 => 0x0110_0040,
|
||||
HCSPARAMS1 => 1 << 24 | 8,
|
||||
HCSPARAMS2 => 2 << 27,
|
||||
HCCPARAMS1 => 1,
|
||||
DBOFF => 0x1000,
|
||||
RTSOFF => 0x800,
|
||||
0x48 => 1,
|
||||
0x44 => {
|
||||
if self.0.borrow().running {
|
||||
0
|
||||
} else {
|
||||
HCH
|
||||
}
|
||||
}
|
||||
0x40 if self.0.borrow().running => RUN,
|
||||
_ => 0,
|
||||
}
|
||||
}
|
||||
fn write32(&mut self, at: usize, value: u32) {
|
||||
let mut state = self.0.borrow_mut();
|
||||
state.writes.push((at, value));
|
||||
if at == 0x40 {
|
||||
state.running = value & RUN != 0;
|
||||
}
|
||||
}
|
||||
fn size(&self) -> Option<usize> {
|
||||
Some(0x4000)
|
||||
}
|
||||
}
|
||||
fn core(
|
||||
peer: &Arc<Peer>,
|
||||
registers: Rc<RefCell<RegistersState>>,
|
||||
) -> Result<Controller, BlockError> {
|
||||
Controller::with_memory_profile(
|
||||
Box::new(CoreRegisters(registers)),
|
||||
Clock {
|
||||
ticks_per_microsecond: 1000,
|
||||
},
|
||||
&mut NoBoot,
|
||||
"native nonidentity model".into(),
|
||||
hardware::Policy {
|
||||
dma: dma::Profile::pci(0x1106, 0x3483),
|
||||
..Default::default()
|
||||
},
|
||||
|| Ok(()),
|
||||
Some(memory(peer)),
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn native_core_uses_real_dcbaa_erst_scratchpads_and_coherent_owned_event_trbs() {
|
||||
let peer = Peer::new();
|
||||
let registers = Rc::new(RefCell::new(RegistersState::default()));
|
||||
let mut controller = core(&peer, registers.clone()).unwrap();
|
||||
let dcbaa = controller.dcbaa.device_address();
|
||||
let table = controller._event_table.device_address();
|
||||
let events = controller.events.device_address();
|
||||
let scratch_array = u64::from_le_bytes(peer.device(dcbaa, 8).try_into().unwrap());
|
||||
assert_eq!(controller._scratchpads.len(), 3);
|
||||
for index in 0..2 {
|
||||
let page = u64::from_le_bytes(
|
||||
peer.device(scratch_array + index * 8, 8)
|
||||
.try_into()
|
||||
.unwrap(),
|
||||
);
|
||||
assert_eq!(peer.device(page, 4096), vec![0; 4096]);
|
||||
}
|
||||
assert_eq!(
|
||||
u64::from_le_bytes(peer.device(table, 8).try_into().unwrap()),
|
||||
events
|
||||
);
|
||||
assert_eq!(
|
||||
u32::from_le_bytes(peer.device(table + 8, 4).try_into().unwrap()),
|
||||
RING_TRBS as u32
|
||||
);
|
||||
assert_eq!(
|
||||
controller.events.read::<u32>(12),
|
||||
0,
|
||||
"CPU cache initially owns no posted event"
|
||||
);
|
||||
let mut event = [0u8; TRB];
|
||||
event[..8].copy_from_slice(&0x9876_5000u64.to_le_bytes());
|
||||
event[8..12].copy_from_slice(&(SUCCESS << 24).to_le_bytes());
|
||||
event[12..].copy_from_slice(&(COMMAND_COMPLETION << 10 | CYCLE).to_le_bytes());
|
||||
peer.post(events, &event);
|
||||
let observed = controller.next_event().unwrap();
|
||||
assert_eq!(observed.parameter, 0x9876_5000);
|
||||
assert_eq!(observed.code(), SUCCESS);
|
||||
let state = peer.state.lock().unwrap();
|
||||
assert!(
|
||||
state
|
||||
.observations
|
||||
.iter()
|
||||
.any(|(_, at)| *at == 12 || *at == 4108)
|
||||
);
|
||||
assert!(
|
||||
state
|
||||
.syncs
|
||||
.iter()
|
||||
.any(|(device, _, range, _)| !*device && range.len() == TRB)
|
||||
);
|
||||
assert_eq!(controller.event_index, 1);
|
||||
let writes = ®isters.borrow().writes;
|
||||
assert!(writes.contains(&(0x40 + DCBAAP, dcbaa as u32)));
|
||||
assert!(writes.contains(&(0x800 + ERDP, (events + TRB as u64) as u32 | EHB as u32)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn native_missing_coherence_refuses_before_pointer_publication_or_run_and_retains_original_maps() {
|
||||
let peer = Peer::new();
|
||||
peer.state.lock().unwrap().coherent = false;
|
||||
let registers = Rc::new(RefCell::new(RegistersState::default()));
|
||||
assert!(core(&peer, registers.clone()).is_err());
|
||||
let state = registers.borrow();
|
||||
assert!(!state.running);
|
||||
assert!(
|
||||
!state
|
||||
.writes
|
||||
.iter()
|
||||
.any(|(at, _)| [0x40 + DCBAAP, 0x40 + CRCR, 0x800 + ERSTBA].contains(at))
|
||||
);
|
||||
assert!(!peer.state.lock().unwrap().bindings.is_empty());
|
||||
assert_eq!(peer.drops.load(Ordering::Relaxed), 0);
|
||||
}
|
||||
@@ -264,6 +264,7 @@ fn address_controller_with_capabilities(
|
||||
iso::Capabilities::new(0x100, 0, 0)
|
||||
};
|
||||
let controller = Controller {
|
||||
native_memory: None,
|
||||
registers,
|
||||
clock,
|
||||
operational: 0x40,
|
||||
@@ -279,11 +280,11 @@ fn address_controller_with_capabilities(
|
||||
max_slots: 1,
|
||||
max_ports: 1,
|
||||
port_major: vec![2],
|
||||
dcbaa: dma.allocate(16, 64).unwrap(),
|
||||
dcbaa: dma.allocate(16, 64).unwrap().into(),
|
||||
_scratchpads: Vec::new(),
|
||||
commands,
|
||||
events,
|
||||
_event_table: dma.allocate(16, 64).unwrap(),
|
||||
events: events.into(),
|
||||
_event_table: dma.allocate(16, 64).unwrap().into(),
|
||||
event_index: 0,
|
||||
event_cycle: true,
|
||||
slots: vec![None, None],
|
||||
@@ -324,6 +325,10 @@ pub(crate) struct CancelModel {
|
||||
pub(crate) setup: Vec<([u8; 8], Vec<u8>)>,
|
||||
pub(crate) incoming_events: alloc::collections::VecDeque<Vec<u8>>,
|
||||
pub(crate) incoming_acl: alloc::collections::VecDeque<Vec<u8>>,
|
||||
/// Opt-in independent test peripherals, keyed by actual configured DCI.
|
||||
pub(crate) incoming_bulk:
|
||||
alloc::collections::BTreeMap<usize, alloc::collections::VecDeque<Vec<u8>>>,
|
||||
pub(crate) outgoing_bulk: alloc::collections::BTreeMap<usize, Vec<Vec<u8>>>,
|
||||
pub(crate) outgoing: Vec<Vec<u8>>,
|
||||
pub(crate) fatal_status: u32,
|
||||
pub(crate) fatal_on_command: Option<u32>,
|
||||
@@ -376,7 +381,10 @@ impl CancelModel {
|
||||
self.event_index += 1;
|
||||
}
|
||||
pub(crate) fn receive(&mut self, dci: usize) {
|
||||
let queue = if (self.asix.is_some() || self.asix_legacy.is_some())
|
||||
let queue = if let Some(queue) = self.incoming_bulk.get_mut(&dci) {
|
||||
assert!((3..32).contains(&dci) && !dci.is_multiple_of(2));
|
||||
queue
|
||||
} else if (self.asix.is_some() || self.asix_legacy.is_some())
|
||||
&& dci >= 3
|
||||
&& !dci.is_multiple_of(2)
|
||||
{
|
||||
@@ -656,6 +664,7 @@ impl CancelModel {
|
||||
} else {
|
||||
self.indices[dci] += 1;
|
||||
if dci == 4
|
||||
|| self.outgoing_bulk.contains_key(&dci)
|
||||
|| ((self.asix.is_some() || self.asix_legacy.is_some())
|
||||
&& dci >= 2
|
||||
&& dci.is_multiple_of(2))
|
||||
@@ -664,8 +673,13 @@ impl CancelModel {
|
||||
// completion below acknowledges its bytes.
|
||||
let packet =
|
||||
unsafe { core::slice::from_raw_parts(parameter as *const u8, length).to_vec() };
|
||||
self.scripted(true, &packet);
|
||||
self.outgoing.push(packet);
|
||||
if let Some(queue) = self.outgoing_bulk.get_mut(&dci) {
|
||||
assert!((2..32).contains(&dci) && dci.is_multiple_of(2));
|
||||
queue.push(packet);
|
||||
} else {
|
||||
self.scripted(true, &packet);
|
||||
self.outgoing.push(packet);
|
||||
}
|
||||
if self.silence_transfer == Some(dci) {
|
||||
self.active[dci] = Some((at, parameter, length));
|
||||
} else {
|
||||
@@ -696,6 +710,10 @@ impl Registers for CancelRegisters {
|
||||
| if model.connected { CCS | PED } else { 0 };
|
||||
}
|
||||
if offset == 0x40 + USBSTS {
|
||||
let registered: Vec<_> = model.incoming_bulk.keys().copied().collect();
|
||||
for dci in registered {
|
||||
model.receive(dci);
|
||||
}
|
||||
if model.asix.is_some() || model.asix_legacy.is_some() {
|
||||
for dci in (3..32).step_by(2) {
|
||||
model.receive(dci);
|
||||
@@ -831,6 +849,8 @@ fn cancellation_controller_with_context(
|
||||
setup: Vec::new(),
|
||||
incoming_events: Default::default(),
|
||||
incoming_acl: Default::default(),
|
||||
incoming_bulk: Default::default(),
|
||||
outgoing_bulk: Default::default(),
|
||||
outgoing: Vec::new(),
|
||||
fatal_status: 0,
|
||||
fatal_on_command: None,
|
||||
|
||||
@@ -0,0 +1,514 @@
|
||||
//! Retained native requester and register ownership for the polled xHCI core.
|
||||
use super::*;
|
||||
use crate::bus::{
|
||||
dma::{
|
||||
mapping::DmaDomain,
|
||||
memory::{CacheAttribute, PageSource},
|
||||
region,
|
||||
},
|
||||
irq::{IrqError, IrqRegistration},
|
||||
mmio::owned::{Mapping, Protection},
|
||||
pci::{ConfigSpace, owned::OwnedConfig},
|
||||
};
|
||||
use alloc::sync::Arc;
|
||||
use core::{cell::Cell, mem::ManuallyDrop};
|
||||
|
||||
/// The actual paired resources. Numeric PCI/BAR geometry does not grant them.
|
||||
pub struct Resources {
|
||||
pub function: Function<OwnedConfig>,
|
||||
pub registers: Mapping,
|
||||
pub pages: Arc<dyn PageSource>,
|
||||
pub domain: Arc<dyn DmaDomain>,
|
||||
pub irq: Box<dyn IrqRegistration>,
|
||||
pub clock: Clock,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum Error {
|
||||
Controller(BlockError),
|
||||
Irq(IrqError),
|
||||
Registers,
|
||||
BusMaster,
|
||||
}
|
||||
|
||||
struct Owner {
|
||||
// Until an actual stop/original-domain drain/IRQ drain/unmap boundary is
|
||||
// implemented, dropping any native handle retains this complete owner.
|
||||
// Neither a replacement domain nor HCRST certifies old-route retirement.
|
||||
resources: RefCell<ManuallyDrop<Resources>>,
|
||||
register_failure: Rc<Cell<Option<usize>>>,
|
||||
}
|
||||
|
||||
struct Access(Rc<Owner>);
|
||||
impl Registers for Access {
|
||||
fn read32(&mut self, offset: usize) -> u32 {
|
||||
if self.0.register_failure.get().is_some() {
|
||||
return u32::MAX;
|
||||
}
|
||||
let resources = self.0.resources.borrow();
|
||||
let Ok(pointer) = resources.registers.address(offset, 4) else {
|
||||
self.0.register_failure.set(Some(offset));
|
||||
return u32::MAX;
|
||||
};
|
||||
if !(pointer.as_ptr() as usize).is_multiple_of(4) {
|
||||
self.0.register_failure.set(Some(offset));
|
||||
return u32::MAX;
|
||||
}
|
||||
// SAFETY: actual retained UC BAR mapping; exclusive serialized access.
|
||||
u32::from_le(unsafe { pointer.as_ptr().cast::<u32>().read_volatile() })
|
||||
}
|
||||
fn write32(&mut self, offset: usize, value: u32) {
|
||||
if self.0.register_failure.get().is_some() {
|
||||
return;
|
||||
}
|
||||
let resources = self.0.resources.borrow();
|
||||
let Ok(pointer) = resources.registers.address(offset, 4) else {
|
||||
self.0.register_failure.set(Some(offset));
|
||||
return;
|
||||
};
|
||||
if !(pointer.as_ptr() as usize).is_multiple_of(4) {
|
||||
self.0.register_failure.set(Some(offset));
|
||||
return;
|
||||
}
|
||||
// SAFETY: same checked original UC BAR, exclusive writer.
|
||||
unsafe {
|
||||
pointer.as_ptr().cast::<u32>().write_volatile(value.to_le());
|
||||
}
|
||||
}
|
||||
fn size(&self) -> Option<usize> {
|
||||
self.0.resources.borrow().registers.bytes().ok()
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Failure {
|
||||
pub error: Error,
|
||||
owner: Rc<Owner>,
|
||||
controller: Option<Box<Controller>>,
|
||||
memory: Option<Rc<memory::Native>>,
|
||||
}
|
||||
impl Failure {
|
||||
pub fn dma_error(&self) -> Option<region::Error> {
|
||||
self.memory.as_ref().and_then(|m| m.error())
|
||||
}
|
||||
pub fn register_error(&self) -> Option<usize> {
|
||||
self.owner.register_failure.get()
|
||||
}
|
||||
pub fn retains_controller_storage(&self) -> bool {
|
||||
self.controller.is_some()
|
||||
}
|
||||
pub fn retains_original_requester(&self) -> bool {
|
||||
Rc::strong_count(&self.owner) != 0
|
||||
}
|
||||
}
|
||||
|
||||
struct NoBoot;
|
||||
impl DmaAllocator for NoBoot {
|
||||
fn allocate(&mut self, _: usize, _: usize) -> Result<DmaBuffer, BlockError> {
|
||||
Err(BlockError::Unsupported(
|
||||
"native xHCI cannot allocate identity DMA",
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
/// CPU-owned actual requester-domain payload. No device address escapes.
|
||||
/// Submission consumes this owner; a live/uncertain TD exposes no CPU slice.
|
||||
pub struct Payload {
|
||||
buffer: memory::Buffer,
|
||||
memory: Rc<memory::Native>,
|
||||
}
|
||||
impl Payload {
|
||||
pub fn len(&self) -> usize {
|
||||
self.buffer.len()
|
||||
}
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.len() == 0
|
||||
}
|
||||
pub fn write(&mut self, offset: usize, bytes: &[u8]) -> Result<(), BlockError> {
|
||||
let end = offset
|
||||
.checked_add(bytes.len())
|
||||
.filter(|end| *end <= self.len())
|
||||
.ok_or(BlockError::Unsupported("native USB payload bounds"))?;
|
||||
self.buffer.bytes_mut()[offset..end].copy_from_slice(bytes);
|
||||
Ok(())
|
||||
}
|
||||
pub fn read(&self, offset: usize, bytes: &mut [u8]) -> Result<(), BlockError> {
|
||||
let end = offset
|
||||
.checked_add(bytes.len())
|
||||
.filter(|end| *end <= self.len())
|
||||
.ok_or(BlockError::Unsupported("native USB payload bounds"))?;
|
||||
bytes.copy_from_slice(&self.buffer.bytes()[offset..end]);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub enum Service {
|
||||
Ordinary,
|
||||
Stream(u16),
|
||||
Isochronous(IsoSchedule),
|
||||
}
|
||||
|
||||
enum Ticket {
|
||||
Ordinary(TransferTicket),
|
||||
Stream(StreamTransfer),
|
||||
Isochronous(IsoTransfer),
|
||||
}
|
||||
|
||||
pub struct Transfer {
|
||||
payload: Payload,
|
||||
ticket: Ticket,
|
||||
length: usize,
|
||||
retired: bool,
|
||||
}
|
||||
impl Transfer {
|
||||
fn device_id(&self) -> SlotId {
|
||||
match &self.ticket {
|
||||
Ticket::Ordinary(ticket) => ticket.device_id(),
|
||||
Ticket::Stream(ticket) => ticket.device_id(),
|
||||
Ticket::Isochronous(ticket) => ticket.device_id(),
|
||||
}
|
||||
}
|
||||
/// Only a real successful completion or acknowledged cancellation returns
|
||||
/// CPU access. Dropping an unresolved transfer quarantines original pins.
|
||||
pub fn into_payload(self) -> Result<Payload, Self> {
|
||||
if self.retired {
|
||||
Ok(self.payload)
|
||||
} else {
|
||||
Err(self)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Completion {
|
||||
Ordinary(usize),
|
||||
Stream(usize),
|
||||
Isochronous(IsoCompletion),
|
||||
}
|
||||
|
||||
pub struct SubmitFailure {
|
||||
pub error: BlockError,
|
||||
retained: Payload,
|
||||
}
|
||||
impl SubmitFailure {
|
||||
pub fn retains_original_payload(&self) -> bool {
|
||||
self.retained.buffer.len() != 0
|
||||
}
|
||||
}
|
||||
|
||||
impl Controller {
|
||||
pub fn native_dma_error(&self) -> Option<region::Error> {
|
||||
self.native_memory
|
||||
.as_ref()
|
||||
.and_then(|memory| memory.error())
|
||||
}
|
||||
|
||||
pub fn allocate_native_payload(&mut self, bytes: usize) -> Result<Payload, BlockError> {
|
||||
self.ready()?;
|
||||
if bytes == 0 || bytes > MAX_TD {
|
||||
return Err(BlockError::Unsupported("native USB payload size"));
|
||||
}
|
||||
let memory = self
|
||||
.native_memory
|
||||
.as_ref()
|
||||
.ok_or(BlockError::Unsupported("USB controller uses boot DMA"))?;
|
||||
// Match the one-TRB 64KiB boundary using the actual allocated IOVA.
|
||||
let buffer = memory.allocate(bytes, MAX_TD, self.dma_profile.maximum())?;
|
||||
Ok(Payload {
|
||||
buffer,
|
||||
memory: memory.clone(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Reuses actual descriptor/TT/route enumeration, allocating every context
|
||||
/// and EP0 buffer through this retained native memory owner.
|
||||
pub fn enumerate_native(
|
||||
&mut self,
|
||||
failures: &mut Vec<(String, BlockError)>,
|
||||
) -> Result<Vec<Device>, BlockError> {
|
||||
if self.native_memory.is_none() {
|
||||
return Err(BlockError::Unsupported("USB controller uses boot DMA"));
|
||||
}
|
||||
self.ready()?;
|
||||
Ok(self.enumerate(&mut NoBoot, failures))
|
||||
}
|
||||
|
||||
pub fn configure_native(
|
||||
&mut self,
|
||||
id: SlotId,
|
||||
endpoints: &[Endpoint],
|
||||
) -> Result<(), BlockError> {
|
||||
if self.native_memory.is_none() {
|
||||
return Err(BlockError::Unsupported("USB controller uses boot DMA"));
|
||||
}
|
||||
self.device(id)?.configure(endpoints, None, &mut NoBoot)
|
||||
}
|
||||
|
||||
pub fn configure_native_streams(
|
||||
&mut self,
|
||||
id: SlotId,
|
||||
endpoints: &[Endpoint],
|
||||
selected: &[u8],
|
||||
requested: u16,
|
||||
) -> Result<u16, BlockError> {
|
||||
if self.native_memory.is_none() {
|
||||
return Err(BlockError::Unsupported("USB controller uses boot DMA"));
|
||||
}
|
||||
self.device(id)?
|
||||
.configure_streams(endpoints, selected, requested, &mut NoBoot)
|
||||
}
|
||||
|
||||
pub fn submit_native(
|
||||
&mut self,
|
||||
id: SlotId,
|
||||
dci: u8,
|
||||
payload: Payload,
|
||||
length: usize,
|
||||
service: Service,
|
||||
) -> Result<Transfer, SubmitFailure> {
|
||||
let result = (|| {
|
||||
let slot = self.validate_id(id)?;
|
||||
let memory = self
|
||||
.native_memory
|
||||
.as_ref()
|
||||
.ok_or(BlockError::Unsupported("USB controller uses boot DMA"))?;
|
||||
if !Rc::ptr_eq(memory, &payload.memory) || length > payload.len() {
|
||||
return Err(BlockError::Unsupported(
|
||||
"foreign native USB payload or bounds",
|
||||
));
|
||||
}
|
||||
memory.ready()?;
|
||||
payload.buffer.sync_dirty()?;
|
||||
let address = payload.buffer.device_address();
|
||||
match service {
|
||||
Service::Ordinary => self
|
||||
.submit_ticket_buffer(slot, dci, address, length)
|
||||
.map(Ticket::Ordinary),
|
||||
Service::Stream(stream) => self
|
||||
.submit_stream_buffer(slot, dci, stream, address, length)
|
||||
.map(Ticket::Stream),
|
||||
Service::Isochronous(schedule) => self
|
||||
.submit_iso_scheduled_buffer(slot, dci, address, length, schedule)
|
||||
.map(Ticket::Isochronous),
|
||||
}
|
||||
})();
|
||||
match result {
|
||||
Ok(ticket) => Ok(Transfer {
|
||||
payload,
|
||||
ticket,
|
||||
length,
|
||||
retired: false,
|
||||
}),
|
||||
// Errors can follow Cycle publication. Never return CPU access by
|
||||
// assuming that a failed sync or doorbell means no DMA occurred.
|
||||
Err(error) => Err(SubmitFailure {
|
||||
error,
|
||||
retained: payload,
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn completed_native(
|
||||
&mut self,
|
||||
transfer: &mut Transfer,
|
||||
) -> Option<Result<Completion, BlockError>> {
|
||||
if transfer.retired {
|
||||
return Some(Err(BlockError::Unsupported(
|
||||
"native USB transfer already retired",
|
||||
)));
|
||||
}
|
||||
if let Err(error) = self.validate_id(transfer.device_id()) {
|
||||
return Some(Err(error));
|
||||
}
|
||||
if self
|
||||
.native_memory
|
||||
.as_ref()
|
||||
.is_none_or(|m| !Rc::ptr_eq(m, &transfer.payload.memory))
|
||||
{
|
||||
return Some(Err(BlockError::Unsupported("foreign native USB transfer")));
|
||||
}
|
||||
let result = match &transfer.ticket {
|
||||
Ticket::Ordinary(ticket) => self
|
||||
.completed_ticket(ticket)
|
||||
.map(|r| r.map(Completion::Ordinary)),
|
||||
Ticket::Stream(ticket) => self
|
||||
.completed_stream(ticket)
|
||||
.map(|r| r.map(Completion::Stream)),
|
||||
Ticket::Isochronous(ticket) => self
|
||||
.completed_iso(ticket)
|
||||
.map(|r| r.map(Completion::Isochronous)),
|
||||
}?;
|
||||
Some(result.and_then(|completion| {
|
||||
// SAFETY: genuine terminal event granted this exact TD's payload.
|
||||
unsafe {
|
||||
transfer.payload.buffer.sync_cpu(0..transfer.length)?;
|
||||
}
|
||||
transfer.retired = true;
|
||||
Ok(completion)
|
||||
}))
|
||||
}
|
||||
|
||||
/// Actual Stop/Set-Dequeue (and any required Reset/TT clear) must ACK.
|
||||
/// Success supplies ownership only, never a fabricated receive byte count.
|
||||
pub fn cancel_native(&mut self, transfer: &mut Transfer) -> Result<(), BlockError> {
|
||||
self.validate_id(transfer.device_id())?;
|
||||
if self
|
||||
.native_memory
|
||||
.as_ref()
|
||||
.is_none_or(|m| !Rc::ptr_eq(m, &transfer.payload.memory))
|
||||
{
|
||||
return Err(BlockError::Unsupported("foreign native USB transfer"));
|
||||
}
|
||||
if transfer.retired {
|
||||
return Ok(());
|
||||
}
|
||||
match &transfer.ticket {
|
||||
Ticket::Ordinary(ticket) => {
|
||||
self.cancel_ticket(ticket)?;
|
||||
}
|
||||
Ticket::Stream(ticket) => {
|
||||
self.cancel_native_stream(ticket)?;
|
||||
}
|
||||
Ticket::Isochronous(ticket) => {
|
||||
self.cancel_native_iso(ticket)?;
|
||||
}
|
||||
}
|
||||
// SAFETY: acknowledged actual endpoint retirement, not a timeout.
|
||||
unsafe {
|
||||
transfer.payload.buffer.sync_cpu(0..transfer.length)?;
|
||||
}
|
||||
transfer.retired = true;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Attach the actual retained requester using separate native CPU and IOVA views.
|
||||
///
|
||||
/// # Safety
|
||||
/// These are the exclusively owned actual requester, UC BAR0, D0 power/root
|
||||
/// route, isolated original DMA domain, fresh exclusive RAM source and original
|
||||
/// IRQ registration. The requester is initially stopped with BME clear. Every
|
||||
/// former firmware/driver/bypass/peer DMA path and callback is already stopped
|
||||
/// and drained with its original backing retained; attaching a new domain does
|
||||
/// not establish that fact. In particular, an unresolved boot controller cannot
|
||||
/// be replaced by passing its BDF and a new domain here. The IRQ registration
|
||||
/// covers every old source/callback and can acknowledge their actual retirement.
|
||||
/// The clock is calibrated/advancing in this serialized process context. No
|
||||
/// concurrent firmware, hot-removal, class, MMIO or reset actor may run. RAM
|
||||
/// returned by the source is exclusively CPU-owned until publication.
|
||||
///
|
||||
/// Native raw-address payload submission is unavailable; use consumed typed
|
||||
/// payloads. Full controller retirement is a separate boundary. Dropping this owner
|
||||
/// permanently retains its actual configuration/BAR/IRQ/power resources.
|
||||
pub unsafe fn attach(
|
||||
resources: Resources,
|
||||
firmware: &dyn crate::firmware::Provider,
|
||||
) -> Result<Controller, Failure> {
|
||||
let owner = Rc::new(Owner {
|
||||
resources: RefCell::new(ManuallyDrop::new(resources)),
|
||||
register_failure: Rc::new(Cell::new(None)),
|
||||
});
|
||||
let mut controller = None;
|
||||
let mut retained_memory = None;
|
||||
let result = (|| {
|
||||
let (clock, native_memory, policy, location) = {
|
||||
let mut resources = owner.resources.borrow_mut();
|
||||
clock_ready(resources.clock).map_err(Error::Controller)?;
|
||||
if resources.registers.attribute() != Ok(CacheAttribute::Uncached)
|
||||
|| resources.registers.protection() != Ok(Protection::ReadWrite)
|
||||
{
|
||||
return Err(Error::Registers);
|
||||
}
|
||||
let streams =
|
||||
streams::pci_policy(&mut resources.function).map_err(Error::Controller)?;
|
||||
let quirks =
|
||||
quirks::Profile::pci(&mut resources.function).map_err(Error::Controller)?;
|
||||
let function = &mut resources.function;
|
||||
let low = function.config().read32(0x10);
|
||||
if low & 1 != 0 || !matches!(low & 6, 0 | 4) {
|
||||
return Err(Error::Registers);
|
||||
}
|
||||
let high = if low & 6 == 4 {
|
||||
u64::from(function.config().read32(0x14)) << 32
|
||||
} else {
|
||||
0
|
||||
};
|
||||
if resources
|
||||
.registers
|
||||
.physical_span()
|
||||
.map_err(|_| Error::Registers)?
|
||||
.start()
|
||||
!= high | u64::from(low & !15)
|
||||
{
|
||||
return Err(Error::Registers);
|
||||
}
|
||||
if resources.function.config().read16(4) & 4 != 0 {
|
||||
return Err(Error::BusMaster);
|
||||
}
|
||||
// Actual original source mask, callback synchronization and route
|
||||
// retirement; IMAN.IE=0 alone cannot establish these facts.
|
||||
resources.irq.retire().map_err(Error::Irq)?;
|
||||
let command = resources.function.config().read16(4);
|
||||
resources.function.config().write16(4, command | 2 | 0x400);
|
||||
if resources.function.config().read16(4) & 0x406 != 0x402 {
|
||||
return Err(Error::BusMaster);
|
||||
}
|
||||
let clock = resources.clock;
|
||||
renesas::prepare(&mut resources.function, clock, firmware)
|
||||
.map_err(|e| Error::Controller(e.transport()))?;
|
||||
let function = &resources.function;
|
||||
let address = function.address;
|
||||
let location = format!(
|
||||
"native xhci {:04x}:{:02x}:{:02x}.{}",
|
||||
address.segment, address.bus, address.device, address.function
|
||||
);
|
||||
let policy = hardware::Policy {
|
||||
dma: dma::Profile::pci(function.vendor, function.device),
|
||||
streams,
|
||||
quirks,
|
||||
};
|
||||
let memory = Rc::new(memory::Native::new(
|
||||
resources.pages.clone(),
|
||||
resources.domain.clone(),
|
||||
owner.clone(),
|
||||
owner.register_failure.clone(),
|
||||
));
|
||||
(clock, memory, policy, location)
|
||||
};
|
||||
let reset_owner = owner.clone();
|
||||
retained_memory = Some(native_memory.clone());
|
||||
let core = Controller::with_memory_profile(
|
||||
Box::new(Access(owner.clone())),
|
||||
clock,
|
||||
&mut NoBoot,
|
||||
location,
|
||||
policy,
|
||||
move || quirks::after_reset(&mut reset_owner.resources.borrow_mut().function, clock),
|
||||
Some(native_memory),
|
||||
)
|
||||
.map_err(Error::Controller)?;
|
||||
controller = Some(Box::new(core));
|
||||
if owner.register_failure.get().is_some() {
|
||||
return Err(Error::Registers);
|
||||
}
|
||||
let mut resources = owner.resources.borrow_mut();
|
||||
let command = resources.function.config().read16(4);
|
||||
resources.function.config().write16(4, command | 6 | 0x400);
|
||||
if resources.function.config().read16(4) & 0x406 != 0x406 {
|
||||
return Err(Error::BusMaster);
|
||||
}
|
||||
if owner.register_failure.get().is_some() {
|
||||
return Err(Error::Registers);
|
||||
}
|
||||
Ok(())
|
||||
})();
|
||||
match result {
|
||||
Ok(()) => Ok(*controller.take().expect("initialized native controller")),
|
||||
Err(error) => Err(Failure {
|
||||
error,
|
||||
owner,
|
||||
controller,
|
||||
memory: retained_memory,
|
||||
}),
|
||||
}
|
||||
}
|
||||
@@ -1301,6 +1301,7 @@ pub(crate) mod tests {
|
||||
uas_abort: abort_peer::State::default(),
|
||||
}));
|
||||
let mut controller = Controller {
|
||||
native_memory: None,
|
||||
registers: Box::new(Model(hardware.clone())),
|
||||
clock: Clock {
|
||||
ticks_per_microsecond: 1,
|
||||
@@ -1318,11 +1319,11 @@ pub(crate) mod tests {
|
||||
max_slots,
|
||||
max_ports: 1,
|
||||
port_major: vec![if speed >= SUPER_SPEED { 3 } else { 2 }],
|
||||
dcbaa,
|
||||
dcbaa: dcbaa.into(),
|
||||
_scratchpads: Vec::new(),
|
||||
commands,
|
||||
events,
|
||||
_event_table: dma.allocate(16, 64).unwrap(),
|
||||
events: events.into(),
|
||||
_event_table: dma.allocate(16, 64).unwrap().into(),
|
||||
event_index: 0,
|
||||
event_cycle: true,
|
||||
slots: core::iter::repeat_with(|| None)
|
||||
@@ -1690,12 +1691,12 @@ pub(crate) mod tests {
|
||||
..source
|
||||
},
|
||||
retiring: other_state == 1,
|
||||
input,
|
||||
_output: output,
|
||||
input: input.into(),
|
||||
_output: output.into(),
|
||||
context: [0; 4],
|
||||
endpoints: Default::default(),
|
||||
retired_rings: Default::default(),
|
||||
control,
|
||||
control: control.into(),
|
||||
speed: HIGH_SPEED,
|
||||
current_configuration: Some(0),
|
||||
});
|
||||
|
||||
@@ -78,6 +78,7 @@ fn unpublished_profile(
|
||||
uas_abort: abort_peer::State::default(),
|
||||
}));
|
||||
let mut controller = Controller {
|
||||
native_memory: None,
|
||||
registers: Box::new(Model(hardware.clone())),
|
||||
clock: Clock {
|
||||
ticks_per_microsecond: 1,
|
||||
@@ -95,11 +96,11 @@ fn unpublished_profile(
|
||||
max_slots,
|
||||
max_ports: 1,
|
||||
port_major: vec![if speed >= SUPER_SPEED { 3 } else { 2 }],
|
||||
dcbaa,
|
||||
dcbaa: dcbaa.into(),
|
||||
_scratchpads: Vec::new(),
|
||||
commands,
|
||||
events,
|
||||
_event_table: dma.allocate(16, 64).unwrap(),
|
||||
events: events.into(),
|
||||
_event_table: dma.allocate(16, 64).unwrap().into(),
|
||||
event_index: 0,
|
||||
event_cycle: true,
|
||||
slots: core::iter::repeat_with(|| None)
|
||||
@@ -305,7 +306,7 @@ fn generations(kind: Kind) {
|
||||
assert_eq!(
|
||||
c.device(current)
|
||||
.unwrap()
|
||||
.transfer(2, command.physical(), 32, 1000),
|
||||
.transfer(2, command.physical(), 32, 50_000_000),
|
||||
Ok(32)
|
||||
);
|
||||
c.device(current)
|
||||
|
||||
@@ -223,7 +223,11 @@ impl<'a> Quiesced<'a> {
|
||||
continue;
|
||||
}
|
||||
fence(Ordering::Acquire);
|
||||
let endpoint_state = state._output.read::<u32>(dci * context) & 7;
|
||||
let endpoint_state = state
|
||||
._output
|
||||
.coherent_u32(dci * context)
|
||||
.map_err(|error| ("observe actual endpoint DMA context", error))?
|
||||
& 7;
|
||||
if unaddressed && dci == 1 && endpoint_state == ENDPOINT_DISABLED {
|
||||
continue;
|
||||
}
|
||||
@@ -245,7 +249,11 @@ impl<'a> Quiesced<'a> {
|
||||
fence(Ordering::Acquire);
|
||||
for (dci, endpoint) in state.endpoints.iter().enumerate().skip(1) {
|
||||
if let Some(endpoint) = endpoint {
|
||||
let actual = state._output.read::<u32>(dci * context) & 7;
|
||||
let actual = state
|
||||
._output
|
||||
.coherent_u32(dci * context)
|
||||
.map_err(|error| ("observe actual endpoint DMA context", error))?
|
||||
& 7;
|
||||
if endpoint.poisoned
|
||||
|| ownership == Ownership::Vacant
|
||||
&& (endpoint.in_flight != 0 || !endpoint.ring.normal.idle())
|
||||
|
||||
@@ -30,7 +30,7 @@ impl Event {
|
||||
|
||||
/// A producer ring of one segment closed by a toggling Link TRB.
|
||||
pub(super) struct Ring {
|
||||
pub(super) buffer: DmaBuffer,
|
||||
pub(super) buffer: memory::Buffer,
|
||||
pub(super) index: usize,
|
||||
pub(super) cycle: bool,
|
||||
pub(super) normal: transfer::Queue,
|
||||
@@ -42,16 +42,25 @@ impl Ring {
|
||||
Self::with_profile(dma, dma::Profile::SPEC)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(super) fn with_profile(
|
||||
dma: &mut dyn DmaAllocator,
|
||||
profile: dma::Profile,
|
||||
) -> Result<Self, BlockError> {
|
||||
Self::with_memory(dma, profile, None)
|
||||
}
|
||||
|
||||
pub(super) fn with_memory(
|
||||
dma: &mut dyn DmaAllocator,
|
||||
profile: dma::Profile,
|
||||
memory: Option<&Rc<memory::Native>>,
|
||||
) -> Result<Self, BlockError> {
|
||||
// A segment cannot cross a 64 KiB boundary (xHCI 1.2 4.9.2).
|
||||
// Its whole allocation (including a quirk's dummy second page) is
|
||||
// aligned to its size, keeping both within one 64 KiB boundary.
|
||||
let bytes = profile.segment_bytes();
|
||||
let mut buffer = profile.allocate(dma, bytes, bytes)?;
|
||||
let physical = buffer.physical();
|
||||
let mut buffer = profile.allocate_memory(dma, bytes, bytes, memory)?;
|
||||
let physical = buffer.device_address();
|
||||
buffer.write((RING_TRBS - 1) * TRB, physical);
|
||||
Ok(Self {
|
||||
buffer,
|
||||
@@ -65,14 +74,14 @@ impl Ring {
|
||||
pub(super) fn reinitialize(&mut self) {
|
||||
self.buffer.bytes_mut().fill(0);
|
||||
self.buffer
|
||||
.write((RING_TRBS - 1) * TRB, self.buffer.physical());
|
||||
.write((RING_TRBS - 1) * TRB, self.buffer.device_address());
|
||||
self.index = 0;
|
||||
self.cycle = true;
|
||||
self.normal = transfer::Queue::default();
|
||||
}
|
||||
|
||||
pub(super) fn address(&self) -> u64 {
|
||||
self.buffer.physical() + (self.index * TRB) as u64
|
||||
self.buffer.device_address() + (self.index * TRB) as u64
|
||||
}
|
||||
|
||||
/// The enqueue pointer with its cycle state, for CRCR or Set TR Dequeue.
|
||||
@@ -82,7 +91,7 @@ impl Ring {
|
||||
|
||||
/// Writes one TD, its first TRB owned last, and returns each TRB's
|
||||
/// address.
|
||||
pub(super) fn push(&mut self, trbs: &[(u64, u32, u32)]) -> Vec<u64> {
|
||||
pub(super) fn push(&mut self, trbs: &[(u64, u32, u32)]) -> Result<Vec<u64>, BlockError> {
|
||||
let mut addresses = Vec::with_capacity(trbs.len());
|
||||
let mut first = None;
|
||||
for (n, &(parameter, status, control)) in trbs.iter().enumerate() {
|
||||
@@ -111,11 +120,15 @@ impl Ring {
|
||||
self.cycle = !self.cycle;
|
||||
}
|
||||
}
|
||||
// Make the complete TD and Link visible while its first Cycle still
|
||||
// belongs to software. Only then publish that actual ownership word.
|
||||
self.buffer.sync_dirty()?;
|
||||
if let Some((at, control, cycle)) = first {
|
||||
fence(Ordering::Release);
|
||||
self.buffer.write(at + 12, control | cycle);
|
||||
self.buffer.sync_device(at + 12..at + 16)?;
|
||||
}
|
||||
addresses
|
||||
Ok(addresses)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -170,10 +183,12 @@ mod tests {
|
||||
let mut dma = unsafe { RegionAllocator::new(start..start + 8192) };
|
||||
let mut ring = Ring::new(&mut dma).unwrap();
|
||||
for _ in 0..RING_TRBS - 2 {
|
||||
ring.push(&[(0, 0, NORMAL << 10)]);
|
||||
ring.push(&[(0, 0, NORMAL << 10)]).unwrap();
|
||||
}
|
||||
assert!(ring.cycle);
|
||||
let addresses = ring.push(&[(1, 0, NORMAL << 10), (2, 0, NORMAL << 10)]);
|
||||
let addresses = ring
|
||||
.push(&[(1, 0, NORMAL << 10), (2, 0, NORMAL << 10)])
|
||||
.unwrap();
|
||||
assert_eq!(addresses[1], ring.buffer.physical());
|
||||
assert!(!ring.cycle);
|
||||
let link: u32 = ring.buffer.read((RING_TRBS - 1) * TRB + 12);
|
||||
|
||||
@@ -8,9 +8,9 @@
|
||||
use super::*;
|
||||
|
||||
pub(super) struct Resources {
|
||||
pub(super) output: DmaBuffer,
|
||||
pub(super) input: DmaBuffer,
|
||||
pub(super) control: DmaBuffer,
|
||||
pub(super) output: memory::Buffer,
|
||||
pub(super) input: memory::Buffer,
|
||||
pub(super) control: memory::Buffer,
|
||||
pub(super) ring: Ring,
|
||||
}
|
||||
|
||||
@@ -168,23 +168,23 @@ impl Cache {
|
||||
let mut all = Vec::new();
|
||||
for state in self.slots.iter().flatten() {
|
||||
all.extend([
|
||||
(state.input.physical(), state.input.len()),
|
||||
(state._output.physical(), state._output.len()),
|
||||
(state.control.physical(), state.control.len()),
|
||||
(state.input.device_address(), state.input.len()),
|
||||
(state._output.device_address(), state._output.len()),
|
||||
(state.control.device_address(), state.control.len()),
|
||||
]);
|
||||
for ep in state.endpoints.iter().flatten() {
|
||||
all.push((ep.ring.buffer.physical(), ep.ring.buffer.len()));
|
||||
all.push((ep.ring.buffer.device_address(), ep.ring.buffer.len()));
|
||||
if let Some(streams) = &ep.streams {
|
||||
all.extend(streams.allocation_geometry());
|
||||
}
|
||||
}
|
||||
for ring in state.retired_rings.iter().flatten() {
|
||||
all.push((ring.buffer.physical(), ring.buffer.len()));
|
||||
all.push((ring.buffer.device_address(), ring.buffer.len()));
|
||||
}
|
||||
}
|
||||
for endpoints in &self.endpoints {
|
||||
for ep in endpoints.iter().flatten() {
|
||||
all.push((ep.ring.buffer.physical(), ep.ring.buffer.len()));
|
||||
all.push((ep.ring.buffer.device_address(), ep.ring.buffer.len()));
|
||||
if let Some(streams) = &ep.streams {
|
||||
all.extend(streams.allocation_geometry());
|
||||
}
|
||||
@@ -192,7 +192,7 @@ impl Cache {
|
||||
}
|
||||
for rings in &self.rings {
|
||||
for ring in rings.iter().flatten() {
|
||||
all.push((ring.buffer.physical(), ring.buffer.len()));
|
||||
all.push((ring.buffer.device_address(), ring.buffer.len()));
|
||||
}
|
||||
}
|
||||
all.sort_unstable();
|
||||
@@ -295,12 +295,10 @@ impl Controller {
|
||||
}
|
||||
let context = self.context();
|
||||
Ok(Resources {
|
||||
output: self.dma_profile.allocate(dma, 32 * context, 64)?,
|
||||
input: self.dma_profile.allocate(dma, 33 * context, 64)?,
|
||||
control: self
|
||||
.dma_profile
|
||||
.allocate(dma, CONTROL_BYTES, CONTROL_BYTES)?,
|
||||
ring: Ring::with_profile(dma, self.dma_profile)?,
|
||||
output: self.allocate(dma, 32 * context, 64)?,
|
||||
input: self.allocate(dma, 33 * context, 64)?,
|
||||
control: self.allocate(dma, CONTROL_BYTES, CONTROL_BYTES)?,
|
||||
ring: self.allocate_ring(dma)?,
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -178,7 +178,7 @@ struct Stream {
|
||||
}
|
||||
|
||||
pub(super) struct Streams {
|
||||
array: DmaBuffer,
|
||||
array: memory::Buffer,
|
||||
layout: Layout,
|
||||
rings: Vec<Stream>,
|
||||
recovery: bool,
|
||||
@@ -186,20 +186,31 @@ pub(super) struct Streams {
|
||||
}
|
||||
|
||||
impl Streams {
|
||||
#[cfg(test)]
|
||||
pub fn new(
|
||||
dma: &mut dyn DmaAllocator,
|
||||
layout: Layout,
|
||||
profile: dma::Profile,
|
||||
cadence: bool,
|
||||
) -> Result<Self, BlockError> {
|
||||
Self::with_memory(dma, layout, profile, cadence, None)
|
||||
}
|
||||
|
||||
pub(super) fn with_memory(
|
||||
dma: &mut dyn DmaAllocator,
|
||||
layout: Layout,
|
||||
profile: dma::Profile,
|
||||
cadence: bool,
|
||||
memory: Option<&Rc<memory::Native>>,
|
||||
) -> Result<Self, BlockError> {
|
||||
let bytes = layout.contexts as usize * STREAM_CONTEXT_BYTES;
|
||||
let mut array = profile.allocate(dma, bytes, 64)?;
|
||||
let mut array = profile.allocate_memory(dma, bytes, 64, memory)?;
|
||||
let mut rings = Vec::new();
|
||||
rings
|
||||
.try_reserve_exact(usize::from(layout.usable))
|
||||
.map_err(|_| BlockError::NoDmaMemory)?;
|
||||
for stream in 1..=layout.usable {
|
||||
let ring = Ring::with_profile(dma, profile)?;
|
||||
let ring = Ring::with_memory(dma, profile, memory)?;
|
||||
array.write(
|
||||
usize::from(stream) * STREAM_CONTEXT_BYTES,
|
||||
ring.dequeue_pointer() | PRIMARY_TRANSFER_RING,
|
||||
@@ -215,13 +226,21 @@ impl Streams {
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn sync_device(&self) -> Result<(), BlockError> {
|
||||
self.array.sync_dirty()?;
|
||||
for stream in &self.rings {
|
||||
stream.ring.buffer.sync_dirty()?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(super) fn allocation_geometry(&self) -> Vec<(u64, usize)> {
|
||||
core::iter::once((self.array.physical(), self.array.len()))
|
||||
core::iter::once((self.array.device_address(), self.array.len()))
|
||||
.chain(
|
||||
self.rings
|
||||
.iter()
|
||||
.map(|s| (s.ring.buffer.physical(), s.ring.buffer.len())),
|
||||
.map(|s| (s.ring.buffer.device_address(), s.ring.buffer.len())),
|
||||
)
|
||||
.collect()
|
||||
}
|
||||
@@ -247,7 +266,7 @@ impl Streams {
|
||||
}
|
||||
|
||||
pub fn context(&self) -> (u32, u64) {
|
||||
(self.layout.info(), self.array.physical())
|
||||
(self.layout.info(), self.array.device_address())
|
||||
}
|
||||
|
||||
fn stream(&mut self, id: u16) -> Result<&mut Stream, BlockError> {
|
||||
@@ -297,6 +316,28 @@ impl Streams {
|
||||
}
|
||||
|
||||
impl Controller {
|
||||
pub(super) fn cancel_native_stream(
|
||||
&mut self,
|
||||
ticket: &StreamTransfer,
|
||||
) -> Result<(), BlockError> {
|
||||
let slot = self.validate_id(ticket.device_id())?;
|
||||
let valid = self.slots[usize::from(slot)]
|
||||
.as_ref()
|
||||
.and_then(|state| state.endpoints[usize::from(ticket.dci)].as_ref())
|
||||
.and_then(|endpoint| endpoint.streams.as_ref())
|
||||
.and_then(|streams| streams.rings.get(usize::from(ticket.stream) - 1))
|
||||
.and_then(|stream| stream.active.as_ref())
|
||||
.is_some_and(|active| {
|
||||
(active.id, active.trb, active.length) == (ticket.id, ticket.trb, ticket.length)
|
||||
});
|
||||
if !valid {
|
||||
return Err(BlockError::Unsupported(
|
||||
"stale or foreign native stream cancellation",
|
||||
));
|
||||
}
|
||||
self.cancel_owned(slot, ticket.dci)
|
||||
}
|
||||
|
||||
/// Pure planning query for an addressed slot in this controller epoch.
|
||||
/// The result is a negotiable limit, not an allocation/configuration ACK.
|
||||
/// It intentionally works before SET_CONFIGURATION so a selector can fall
|
||||
@@ -408,6 +449,23 @@ impl Controller {
|
||||
stream_id: u16,
|
||||
buffer: u64,
|
||||
length: usize,
|
||||
) -> Result<StreamTransfer, BlockError> {
|
||||
self.device_id(slot)?;
|
||||
if self.native_memory.is_some() {
|
||||
return Err(BlockError::Unsupported(
|
||||
"native xHCI requires a retained typed payload",
|
||||
));
|
||||
}
|
||||
self.submit_stream_buffer(slot, dci, stream_id, buffer, length)
|
||||
}
|
||||
|
||||
pub(in crate::usb::xhci) fn submit_stream_buffer(
|
||||
&mut self,
|
||||
slot: u8,
|
||||
dci: u8,
|
||||
stream_id: u16,
|
||||
buffer: u64,
|
||||
length: usize,
|
||||
) -> Result<StreamTransfer, BlockError> {
|
||||
let device = self.device_id(slot)?;
|
||||
self.validate_id(device)?;
|
||||
@@ -443,7 +501,7 @@ impl Controller {
|
||||
let direction = if endpoint.is_in { ISP } else { 0 };
|
||||
let trb = stream
|
||||
.ring
|
||||
.push(&[(buffer, length as u32, NORMAL << 10 | IOC | direction)])[0];
|
||||
.push(&[(buffer, length as u32, NORMAL << 10 | IOC | direction)])?[0];
|
||||
stream.active = Some(Active {
|
||||
id,
|
||||
trb,
|
||||
@@ -852,17 +910,18 @@ mod tests {
|
||||
parent: None,
|
||||
},
|
||||
retiring: false,
|
||||
input: dma.allocate(33 * context_bytes, 64).unwrap(),
|
||||
_output: output,
|
||||
input: dma.allocate(33 * context_bytes, 64).unwrap().into(),
|
||||
_output: output.into(),
|
||||
context: [u32::from(SUPER_SPEED) << 20 | 1 << 27, 1 << 16, 0, 0],
|
||||
endpoints: Default::default(),
|
||||
retired_rings: Default::default(),
|
||||
control: dma.allocate(CONTROL_BYTES, CONTROL_BYTES).unwrap(),
|
||||
control: dma.allocate(CONTROL_BYTES, CONTROL_BYTES).unwrap().into(),
|
||||
speed: SUPER_SPEED,
|
||||
current_configuration: Some(1),
|
||||
}));
|
||||
(
|
||||
Controller {
|
||||
native_memory: None,
|
||||
registers: Box::new(Model(model.clone())),
|
||||
clock: Clock {
|
||||
ticks_per_microsecond: 1,
|
||||
@@ -880,11 +939,11 @@ mod tests {
|
||||
max_slots: 1,
|
||||
max_ports: 1,
|
||||
port_major: vec![3],
|
||||
dcbaa: dma.allocate(16, 64).unwrap(),
|
||||
dcbaa: dma.allocate(16, 64).unwrap().into(),
|
||||
_scratchpads: Vec::new(),
|
||||
commands,
|
||||
events,
|
||||
_event_table: dma.allocate(16, 64).unwrap(),
|
||||
events: events.into(),
|
||||
_event_table: dma.allocate(16, 64).unwrap().into(),
|
||||
event_index: 0,
|
||||
event_cycle: true,
|
||||
legacy_slot_fenced: vec![false; slots.len()],
|
||||
|
||||
@@ -78,7 +78,7 @@ impl Controller {
|
||||
for (n, word) in words.iter().enumerate() {
|
||||
state.input.write(context + 4 * n, *word);
|
||||
}
|
||||
(state.input.physical(), words)
|
||||
(state.input.device_address(), words)
|
||||
};
|
||||
self.command(input.0, 0, CONFIGURE_ENDPOINT << 10 | u32::from(slot) << 24)?;
|
||||
self.ready()?;
|
||||
|
||||
@@ -233,7 +233,8 @@ impl Controller {
|
||||
if !is_in {
|
||||
state.control.bytes_mut()[..length].copy_from_slice(out);
|
||||
}
|
||||
state.control.physical()
|
||||
state.control.sync_dirty()?;
|
||||
state.control.device_address()
|
||||
};
|
||||
let transfer_type = match (length, is_in) {
|
||||
(0, _) => 0,
|
||||
@@ -257,7 +258,7 @@ impl Controller {
|
||||
.as_mut()
|
||||
.ok_or(BlockError::Unsupported("xHCI control endpoint"))?
|
||||
.ring;
|
||||
ring.push(&trbs)
|
||||
ring.push(&trbs)?
|
||||
};
|
||||
self.doorbell(slot, 1);
|
||||
let status_address = *addresses.last().unwrap();
|
||||
@@ -327,6 +328,10 @@ impl Controller {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
let state = self.slot(slot)?;
|
||||
// SAFETY: the actual Status completion retired this EP0 TD's Data stage.
|
||||
unsafe {
|
||||
state.control.sync_cpu(0..received)?;
|
||||
}
|
||||
Ok(state.control.bytes()[..received].to_vec())
|
||||
}
|
||||
|
||||
@@ -449,7 +454,7 @@ impl Controller {
|
||||
Ok(controller
|
||||
.slot(slot)?
|
||||
._output
|
||||
.read::<u32>(usize::from(dci) * context)
|
||||
.coherent_u32(usize::from(dci) * context)?
|
||||
& 7)
|
||||
};
|
||||
let mut current = state(self)?;
|
||||
@@ -824,7 +829,9 @@ mod tests {
|
||||
if fail_stop {
|
||||
model.borrow_mut().fail = Some((STOP_ENDPOINT, CONTEXT_STATE_ERROR));
|
||||
}
|
||||
let result = controller.transfer(1, 5, buffer.physical(), 512, 1);
|
||||
// Keep a valid publication window in this shortened Clock1 model;
|
||||
// the actual held TD then consumes the budget and must stop.
|
||||
let result = controller.transfer(1, 5, buffer.physical(), 512, 3_000_000);
|
||||
if fail_stop {
|
||||
assert!(matches!(
|
||||
result,
|
||||
@@ -859,7 +866,7 @@ mod tests {
|
||||
assert!(model.borrow().active[5].is_none());
|
||||
model.borrow_mut().incoming_acl.push_back(vec![1, 2, 3]);
|
||||
assert_eq!(
|
||||
controller.transfer(1, 5, buffer.physical(), 512, 1000),
|
||||
controller.transfer(1, 5, buffer.physical(), 512, 50_000_000),
|
||||
Ok(3)
|
||||
);
|
||||
assert_eq!(&buffer.bytes()[..3], &[1, 2, 3]);
|
||||
|
||||
@@ -115,6 +115,22 @@ impl Controller {
|
||||
dci: u8,
|
||||
buffer: u64,
|
||||
length: usize,
|
||||
) -> Result<TransferTicket, BlockError> {
|
||||
self.device_id(slot)?;
|
||||
if self.native_memory.is_some() {
|
||||
return Err(BlockError::Unsupported(
|
||||
"native xHCI requires a retained typed payload",
|
||||
));
|
||||
}
|
||||
self.submit_ticket_buffer(slot, dci, buffer, length)
|
||||
}
|
||||
|
||||
pub(in crate::usb::xhci) fn submit_ticket_buffer(
|
||||
&mut self,
|
||||
slot: u8,
|
||||
dci: u8,
|
||||
buffer: u64,
|
||||
length: usize,
|
||||
) -> Result<TransferTicket, BlockError> {
|
||||
let device = self.device_id(slot)?;
|
||||
self.validate_id(device)?;
|
||||
@@ -146,7 +162,7 @@ impl Controller {
|
||||
let direction = if transfer.is_in { ISP } else { 0 };
|
||||
transfer
|
||||
.ring
|
||||
.push(&[(buffer, length as u32, NORMAL << 10 | IOC | direction)]);
|
||||
.push(&[(buffer, length as u32, NORMAL << 10 | IOC | direction)])?;
|
||||
transfer.in_flight += 1;
|
||||
self.doorbell(slot, dci);
|
||||
Ok(TransferTicket {
|
||||
@@ -294,7 +310,9 @@ impl Controller {
|
||||
))
|
||||
}
|
||||
|
||||
/// One TD, waited for.
|
||||
/// One TD with a budget covering publication and observed completion.
|
||||
/// An already expired budget publishes no TD. Actual DMA retirement after
|
||||
/// expiry may outlast the budget; failed retirement retains endpoint poison.
|
||||
pub fn transfer(
|
||||
&mut self,
|
||||
slot: u8,
|
||||
@@ -315,10 +333,32 @@ impl Controller {
|
||||
length: usize,
|
||||
microseconds: u64,
|
||||
) -> Result<usize, BlockError> {
|
||||
// Admit the complete caller budget before publishing any actual TD.
|
||||
// The budget includes submission; invalid timing cannot leave a new
|
||||
// DMA owner behind an infallible legacy Clock panic.
|
||||
let deadline = self.clock.try_deadline(microseconds).map_err(|_| {
|
||||
BlockError::Unsupported(
|
||||
"xHCI transfer timeout clock unavailable or duration out of range",
|
||||
)
|
||||
})?;
|
||||
if deadline.passed() {
|
||||
return Err(BlockError::Timeout);
|
||||
}
|
||||
let ticket = self.submit_ticket_owned(slot, dci, buffer, length)?;
|
||||
let deadline = self.clock.deadline(microseconds);
|
||||
loop {
|
||||
if let Some(result) = self.completed_ticket(&ticket) {
|
||||
if deadline.passed() {
|
||||
self.cancel_owned(slot, dci)?;
|
||||
return Err(BlockError::Timeout);
|
||||
}
|
||||
let observed = self.completed_ticket(&ticket);
|
||||
// Polling can itself consume the rest of the caller's budget.
|
||||
// A late actual completion is not success within this deadline;
|
||||
// stop/dequeue still must acknowledge before the buffer returns.
|
||||
if deadline.passed() {
|
||||
self.cancel_owned(slot, dci)?;
|
||||
return Err(BlockError::Timeout);
|
||||
}
|
||||
if let Some(result) = observed {
|
||||
return match result {
|
||||
Ok(bytes) => Ok(bytes),
|
||||
Err(error) => {
|
||||
@@ -337,10 +377,6 @@ impl Controller {
|
||||
}
|
||||
};
|
||||
}
|
||||
if deadline.passed() {
|
||||
self.cancel_owned(slot, dci)?;
|
||||
return Err(BlockError::Timeout);
|
||||
}
|
||||
crate::waiting();
|
||||
core::hint::spin_loop();
|
||||
}
|
||||
@@ -353,6 +389,157 @@ mod tests {
|
||||
use crate::bus::dma::RegionAllocator;
|
||||
use crate::usb::xhci::model::*;
|
||||
#[test]
|
||||
fn invalid_synchronous_budget_refuses_before_mmio_and_preserves_current_actual_dma_receipt() {
|
||||
struct NoAccess;
|
||||
impl Registers for NoAccess {
|
||||
fn read32(&mut self, _: usize) -> u32 {
|
||||
panic!("invalid budget read controller")
|
||||
}
|
||||
fn write32(&mut self, _: usize, _: u32) {
|
||||
panic!("invalid budget wrote controller")
|
||||
}
|
||||
}
|
||||
let mut memory = vec![0u64; 64 * 1024];
|
||||
let start = memory.as_mut_ptr() as u64;
|
||||
// SAFETY: actual fixture RAM remains retained through every owner.
|
||||
let mut dma = unsafe { RegionAllocator::new(start..start + memory.len() as u64 * 8) };
|
||||
let (mut c, peer) = cancellation_controller(&mut dma);
|
||||
let buffer = dma.allocate(128, 64).unwrap();
|
||||
let old = c.submit_ticket(1, 3, buffer.physical(), 64).unwrap();
|
||||
peer.borrow_mut()
|
||||
.event(old.trb, SUCCESS, TRANSFER_EVENT, 3, 0);
|
||||
let before = memory.clone();
|
||||
let cursor = (c.event_index, c.event_cycle);
|
||||
let registers = core::mem::replace(&mut c.registers, Box::new(NoAccess));
|
||||
for (rate, duration, error) in [
|
||||
(
|
||||
0,
|
||||
1,
|
||||
BlockError::Unsupported(
|
||||
"xHCI transfer timeout clock unavailable or duration out of range",
|
||||
),
|
||||
),
|
||||
(
|
||||
3,
|
||||
u64::MAX,
|
||||
BlockError::Unsupported(
|
||||
"xHCI transfer timeout clock unavailable or duration out of range",
|
||||
),
|
||||
),
|
||||
(
|
||||
1,
|
||||
u64::MAX / 2 + 1,
|
||||
BlockError::Unsupported(
|
||||
"xHCI transfer timeout clock unavailable or duration out of range",
|
||||
),
|
||||
),
|
||||
(1, 0, BlockError::Timeout),
|
||||
] {
|
||||
c.clock.ticks_per_microsecond = rate;
|
||||
assert_eq!(
|
||||
c.transfer(1, 3, buffer.physical() + 64, 64, duration),
|
||||
Err(error)
|
||||
);
|
||||
assert_eq!(memory, before);
|
||||
assert_eq!((c.event_index, c.event_cycle), cursor);
|
||||
let ep = c.slots[1].as_ref().unwrap().endpoints[3].as_ref().unwrap();
|
||||
assert_eq!(ep.in_flight, 1);
|
||||
assert!(ep.ring.normal.contains(old.id, old.trb));
|
||||
assert!(peer.borrow().active[3].is_some());
|
||||
assert!(!c.command_poisoned);
|
||||
}
|
||||
c.registers = registers;
|
||||
c.clock.ticks_per_microsecond = 1;
|
||||
assert_eq!(c.completed_ticket(&old), Some(Ok(64)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn expired_valid_budget_retires_actual_late_td_and_never_credits_late_completion() {
|
||||
struct Empty;
|
||||
impl Registers for Empty {
|
||||
fn read32(&mut self, _: usize) -> u32 {
|
||||
panic!("temporary owner read")
|
||||
}
|
||||
fn write32(&mut self, _: usize, _: u32) {
|
||||
panic!("temporary owner wrote")
|
||||
}
|
||||
}
|
||||
struct Delayed {
|
||||
inner: Box<dyn Registers>,
|
||||
after_submit: bool,
|
||||
armed: bool,
|
||||
}
|
||||
impl Delayed {
|
||||
fn expire(&mut self) {
|
||||
self.armed = false;
|
||||
// Explicit test TSC scale: consume four times the complete
|
||||
// caller budget after an actual TD was published (and, when
|
||||
// polling, after its actual device-side completion).
|
||||
let start = Clock::ticks();
|
||||
while Clock::ticks().wrapping_sub(start) < 12_000_000 {
|
||||
core::hint::spin_loop();
|
||||
}
|
||||
}
|
||||
}
|
||||
impl Registers for Delayed {
|
||||
fn read32(&mut self, at: usize) -> u32 {
|
||||
let value = self.inner.read32(at);
|
||||
if self.armed && !self.after_submit && at == 0x40 + USBSTS {
|
||||
self.expire();
|
||||
}
|
||||
value
|
||||
}
|
||||
fn write32(&mut self, at: usize, value: u32) {
|
||||
self.inner.write32(at, value);
|
||||
if at == 0x1004 {
|
||||
self.armed = true;
|
||||
if self.after_submit {
|
||||
self.expire();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for after_submit in [false, true] {
|
||||
for failing in [None, Some(STOP_ENDPOINT), Some(SET_DEQUEUE)] {
|
||||
let mut memory = vec![0u64; 64 * 1024];
|
||||
let start = memory.as_mut_ptr() as u64;
|
||||
// SAFETY: actual native-layout fixture RAM outlives every owner.
|
||||
let mut dma =
|
||||
unsafe { RegionAllocator::new(start..start + memory.len() as u64 * 8) };
|
||||
let (mut c, peer) = cancellation_controller(&mut dma);
|
||||
let mut buffer = dma.allocate(64, 64).unwrap();
|
||||
buffer.bytes_mut().fill(0xa5);
|
||||
peer.borrow_mut().incoming_events.push_back(vec![0x79; 64]);
|
||||
peer.borrow_mut().fail = failing.map(|kind| (kind, 17));
|
||||
let inner = core::mem::replace(&mut c.registers, Box::new(Empty));
|
||||
c.registers = Box::new(Delayed {
|
||||
inner,
|
||||
after_submit,
|
||||
armed: false,
|
||||
});
|
||||
let result = c.transfer(1, 3, buffer.physical(), 64, 3_000_000);
|
||||
assert_eq!(buffer.bytes(), &[0x79; 64]); // Real device-side DMA completed.
|
||||
let endpoint = c.slots[1].as_ref().unwrap().endpoints[3].as_ref().unwrap();
|
||||
assert!(peer.borrow().seen.contains(&STOP_ENDPOINT));
|
||||
if failing.is_none() {
|
||||
assert_eq!(result, Err(BlockError::Timeout));
|
||||
assert!(peer.borrow().seen.contains(&SET_DEQUEUE));
|
||||
assert!(!endpoint.poisoned);
|
||||
assert_eq!(endpoint.in_flight, 0);
|
||||
assert!(peer.borrow().active[3].is_none());
|
||||
c.endpoint_ready(1, 3).unwrap();
|
||||
} else {
|
||||
assert_eq!(result, Err(BlockError::Device { status: 17 }));
|
||||
assert!(endpoint.poisoned);
|
||||
// Even when polling observed the real terminal event,
|
||||
// failed Stop/dequeue keeps endpoint/context ownership.
|
||||
assert!(c.endpoint_ready(1, 3).is_err());
|
||||
assert_eq!(buffer.bytes(), &[0x79; 64]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn retired_device_ticket_is_pure_before_readiness_and_preserves_current_dma() {
|
||||
struct NoAccess;
|
||||
impl Registers for NoAccess {
|
||||
@@ -871,7 +1058,9 @@ mod tests {
|
||||
if fail_dequeue {
|
||||
model.borrow_mut().fail = Some((SET_DEQUEUE, 17));
|
||||
}
|
||||
let result = controller.transfer(1, 5, buffer.physical(), 64, 1000);
|
||||
// Clock1 is a shortened test TSC scale; this case exercises STALL
|
||||
// retirement, not a sub-microsecond whole-operation deadline.
|
||||
let result = controller.transfer(1, 5, buffer.physical(), 64, 50_000_000);
|
||||
assert!(result.is_err());
|
||||
assert_eq!(model.borrow().seen, vec![RESET_ENDPOINT, SET_DEQUEUE]);
|
||||
assert_eq!(controller.endpoint_ready(1, 5).is_err(), fail_dequeue);
|
||||
|
||||
Reference in new issue
Block a user