From ca07c707b2b166abef8bd0d1de2ecd12e5376254 Mon Sep 17 00:00:00 2001 From: Tyler Smith <74526874+tylertms@users.noreply.github.com> Date: Wed, 11 Nov 2026 21:08:58 -0500 Subject: [PATCH] perf(soc): settle a write's masters by one rule, the step of each master the write did not reach running only when its exact work predicate holds, in place of quiet devices --- crates/stela-soc/src/dwc3.rs | 14 ++ crates/stela-soc/src/dwc3/xhci.rs | 5 + crates/stela-soc/src/machine.rs | 183 ++++++++---------- crates/stela-soc/src/machine/buses.rs | 3 - crates/stela-soc/src/machine/processors.rs | 4 - crates/stela-soc/src/machine/tests/passive.rs | 60 ++++++ .../stela-soc/src/machine/transfer_times.rs | 77 -------- 7 files changed, 163 insertions(+), 183 deletions(-) diff --git a/crates/stela-soc/src/dwc3.rs b/crates/stela-soc/src/dwc3.rs index f330313797..17bb74dba4 100644 --- a/crates/stela-soc/src/dwc3.rs +++ b/crates/stela-soc/src/dwc3.rs @@ -567,6 +567,15 @@ impl Dwc3 { } } + /// Whether [`Self::sync_port`] with `state` would change nothing: no + /// PHY disconnection to report and the port's generation and readiness + /// already `state`'s. + pub fn port_synced(&self, state: &impl PortState) -> bool { + !self.pending_phy_disconnect + && self.port_generation == state.generation() + && self.port_ready == state.high_speed_device_ready() + } + pub fn sync_port(&mut self, state: &impl PortState) -> Result<()> { self.activity_ready()?; if self.pending_phy_disconnect { @@ -651,6 +660,11 @@ impl Dwc3 { } } + /// The USB2 function [`Self::attach_host_function`] last cabled. + pub fn host_function(&self) -> Option { + self.host.attached() + } + /// Cables a USB2 function of `speed` to the host personality's root /// port, or nothing. pub fn attach_host_function(&mut self, speed: Option) -> Result<()> { diff --git a/crates/stela-soc/src/dwc3/xhci.rs b/crates/stela-soc/src/dwc3/xhci.rs index 7780c819f4..0df8809ef0 100644 --- a/crates/stela-soc/src/dwc3/xhci.rs +++ b/crates/stela-soc/src/dwc3/xhci.rs @@ -466,6 +466,11 @@ impl Xhci { Some(start.saturating_add(ahead.saturating_mul(MICROFRAME))) } + /// What [`Self::attach`] last cabled to the USB2 port. + pub fn attached(&self) -> Option { + self.ports[0].attached + } + /// Cables `attached` to the USB2 port, or nothing. pub fn attach(&mut self, attached: Option) { if self.ports[0].attached == attached { diff --git a/crates/stela-soc/src/machine.rs b/crates/stela-soc/src/machine.rs index e211f76f01..856d16a965 100644 --- a/crates/stela-soc/src/machine.rs +++ b/crates/stela-soc/src/machine.rs @@ -268,13 +268,6 @@ pub struct AppleDevices { /// DMA the current transfer runs ([`Devices::settle_write`]). last_write: Vec>, writer: Option<(u64, u8)>, - /// Devices that start no DMA and reach no master's registers (the - /// console UART, the AIC): a write to one runs the masters' steps only when - /// their DMA is due or every [`QUIET_WRITES`] writes - /// ([`Self::quiet_write`]). - quiet: Vec, - /// Writes to [`Self::quiet`] devices since the masters last ran. - quiet_streak: u32, /// Whether DMA data copies are left to [`Devices::take_unlocked`]. defer_dma: bool, /// The displays' composes left since the last @@ -686,8 +679,6 @@ impl AppleDevices { passive: crate::passive::PassiveMap::default(), last_write: Vec::new(), writer: None, - quiet: Vec::new(), - quiet_streak: 0, defer_dma: false, composes: Vec::new(), } @@ -1363,52 +1354,14 @@ impl Devices for AppleDevices { .finish(outcome.answer); } + /// The entry, each master's DMA step and the wires it settles. After a + /// device write ([`Self::settle_write`]) a master that write did not + /// reach takes its step only when it has work ([`takes_step`]). fn transfer( &mut self, cpu: usize, memory: &mut dyn Memory, now: u64, - ) -> Result<(), DeviceError> { - self.transfer_with(cpu, memory, now, true) - } - - /// As the default, with the transfer knowing PE `cpu`'s write: a USB - /// master that write did not reach runs its schedule only when it has - /// work ([`AppleDevices::usb_due`]); the home machine's transfers run - /// it whatever, as before. - fn settle_write( - &mut self, - cpu: usize, - now: u64, - memory: &mut dyn stela_engine::machine::engine::LockedMemory, - ) -> stela_engine::machine::engine::Settled { - self.writer = self.last_write.get_mut(cpu).and_then(Option::take); - let lock = self.memory_lock(); - let masters = !self.quiet_write(now); - let transfer = self.transfer_with(cpu, memory.under(lock), now, masters); - self.writer = None; - stela_engine::machine::engine::Settled { - transfer, - lock, - call: self.take_call(cpu), - after: self.memory_lock(), - } - } -} - -/// The most writes to [`AppleDevices::quiet`] devices in a row whose -/// transfer leaves the masters' steps out: a console line's worth of bytes. -const QUIET_WRITES: u32 = 16; - -impl AppleDevices { - /// A transfer ([`Devices::transfer`]): its entry, each master's DMA step - /// when `masters`, and the wires it settles. - fn transfer_with( - &mut self, - cpu: usize, - memory: &mut dyn Memory, - now: u64, - masters: bool, ) -> Result<(), DeviceError> { let mut lap = self.transfer_times.lap(); self.observe_time(now, "transfer"); @@ -1418,7 +1371,7 @@ impl AppleDevices { // A master's refused work stops only that master: the others and the // devices' timers go on, and the first refusal is what is reported. let mut results = [const { Ok(()) }; 7]; - for (index, result) in results.iter_mut().enumerate().filter(|_| masters) { + for (index, result) in results.iter_mut().enumerate() { *result = match index { 0 => self.transfer_pmp(cpu, memory, now), 1 => self.transfer_aes(cpu, memory, now), @@ -1435,25 +1388,48 @@ impl AppleDevices { results.into_iter().find(Result::is_err).unwrap_or(settled) } - /// Whether the write being settled ([`Self::writer`]) went to a - /// [`Self::quiet`] device while no master's DMA is due at `now`, so the - /// masters' steps can wait: the write changed no master's state, and work - /// a master has pending is what its DMA deadline names, as for a guest - /// that only reads. The masters still run every [`QUIET_WRITES`] such - /// writes, so a long run of console output never holds them back longer. - fn quiet_write(&mut self, now: u64) -> bool { - let quiet = !self.quiet.is_empty() - && self.quiet_streak < QUIET_WRITES - && self.writer.is_some_and(|(physical, bytes)| { - Width::from_bytes(u64::from(bytes)) - .and_then(|width| self.bus.route(physical, width).ok()) - .is_some_and(|(device, _)| self.quiet.contains(&device)) - }) - && self.dma_deadline().is_none_or(|due| due > now); - self.quiet_streak = if quiet { self.quiet_streak + 1 } else { 0 }; - quiet + /// As the default, with the transfer knowing PE `cpu`'s write: each + /// master that write did not reach takes its step only when it has work + /// ([`takes_step`]); the home machine's transfers run every step. + fn settle_write( + &mut self, + cpu: usize, + now: u64, + memory: &mut dyn stela_engine::machine::engine::LockedMemory, + ) -> stela_engine::machine::engine::Settled { + self.writer = self.last_write.get_mut(cpu).and_then(Option::take); + let lock = self.memory_lock(); + let transfer = self.transfer(cpu, memory.under(lock), now); + self.writer = None; + stela_engine::machine::engine::Settled { + transfer, + lock, + call: self.take_call(cpu), + after: self.memory_lock(), + } } +} +/// Whether a master whose devices are `devices` takes its step in a +/// transfer after the write `written` ([`AppleDevices::written_device`]): +/// always in a transfer of the home machine's own (`None`) or after a write +/// that reached one of `devices`, and otherwise only when `due` says the +/// step has work. Each master's `due` is exact: everything its step would +/// act on, its deadlines and the state other devices' writes and the +/// transfer's entry (power, PHYs, cables) can change. A step that only acts +/// on its devices' pending work (AES, storage, GFX, SEP) is its own test. +fn takes_step( + written: Option>, + devices: &[DeviceId], + due: impl FnOnce() -> bool, +) -> bool { + match written { + None => true, + Some(device) => device.is_some_and(|device| devices.contains(&device)) || due(), + } +} + +impl AppleDevices { fn transfer_pmp( &mut self, cpu: usize, @@ -1628,9 +1604,8 @@ impl AppleDevices { /// notice the AP sent is seen by this step's vblank; then the display at /// `now` (its vblank, a present latched at it); then the link DMA again /// for the callbacks the vblank queued, its vsync and the completions. - /// After a write that reached none of a DCP's devices (its ASC, link - /// DART, surface DART) the DCP skips its step unless it has work - /// ([`Self::dcp_due`]); the home machine's transfers always run it. + /// Its devices are its ASC, link DART and surface DART, and its work + /// [`Self::dcp_due`] ([`takes_step`]). fn transfer_dcp( &mut self, cpu: usize, @@ -1640,14 +1615,9 @@ impl AppleDevices { let written = self.written_device(); for index in 0..self.dcp_masters.len() { let master = &self.dcp_masters[index]; - let optional = written.is_some_and(|device| { - device.is_some_and(|device| { - device != master.asc - && device != master.dart - && master.surface.is_none_or(|(surface, _)| device != surface) - }) - }); - if optional && !self.dcp_due(index, now) { + let surface = master.surface.map(|(surface, _)| surface); + let devices = [master.asc, master.dart, surface.unwrap_or(master.dart)]; + if !takes_step(written, &devices, || self.dcp_due(index, now)) { continue; } self.service_dcp_link(index, cpu, memory, now)?; @@ -1791,11 +1761,31 @@ impl AppleDevices { }) } - /// Whether USB master `master`'s schedule has work at `now`, its cable - /// and PHY already brought up to date: what the home machine's DMA - /// deadline is for ([`Devices::dma_deadline`]), and the work a step takes - /// whatever the time. + /// Whether USB master `master`'s step has work at `now`: a session to + /// cancel, a new cable generation, a port or host cable the controller + /// has not taken up (the PHY and power the transfer's entry settled can + /// change it), and, with the controller active, its schedule's work: what + /// the home machine's DMA deadline is for ([`Devices::dma_deadline`]), + /// and the work a step takes whatever the time. fn usb_due(controller: &Dwc3, master: &UsbMaster, now: u64) -> bool { + let connector = UsbPort::of(&master.connector); + if master.session_reset || controller.service_due() || connector != master.port { + return true; + } + if !controller.lifecycle_active() { + return false; + } + let physical_port = UsbPort { + generation: connector.generation, + ready: connector.ready && controller.phy_ready(), + }; + let cable = controller + .phy_ready() + .then(|| host_function(&master.connector)) + .flatten(); + if !controller.port_synced(&physical_port) || controller.host_function() != cable { + return true; + } if master.phy_changed || master.session_reset || controller.service_due() @@ -1812,10 +1802,9 @@ impl AppleDevices { .any(|due| due <= now) } - /// Each USB master's step. After a write that reached none of a master's - /// devices (core, PHY, DART) the master skips its schedule unless it has - /// work ([`Self::usb_due`]), keeping its session clock where the step - /// would have; the home machine's transfers always run it. + /// Each USB master's step. Its devices are its core, PHY and DART, and + /// its work [`Self::usb_due`] ([`takes_step`]); a master that skips its + /// step keeps its session clock where the step would have. fn transfer_usb( &mut self, cpu: usize, @@ -1828,6 +1817,14 @@ impl AppleDevices { .bus .pair_mut::(master.device, master.dart) .expect("USB master retains its DART"); + let devices = [master.device, master.phy, master.dart]; + if !takes_step(written, &devices, || Self::usb_due(controller, master, now)) { + // A detached session moves nothing; its clock moves on. + if controller.lifecycle_active() && !master.attached && now >= master.next_poll { + master.next_poll = usb_poll(now, master.next_poll).1; + } + continue; + } let mut access = Access::new(cpu, now, &mut self.latch); let mut port = Port { iommu: dart, @@ -1867,18 +1864,6 @@ impl AppleDevices { .flatten(), ) .map_err(fail)?; - let optional = written.is_some_and(|device| { - device.is_some_and(|device| { - ![master.device, master.phy, master.dart].contains(&device) - }) - }); - if optional && !Self::usb_due(controller, master, now) { - // A detached session moves nothing; its clock moves on. - if !master.attached && now >= master.next_poll { - master.next_poll = usb_poll(now, master.next_poll).1; - } - continue; - } let function = master.peripheral.as_mut().map(|p| p as &mut dyn Function); controller.service_host(&mut port, function).map_err(fail)?; controller.flush(&mut port).map_err(fail)?; diff --git a/crates/stela-soc/src/machine/buses.rs b/crates/stela-soc/src/machine/buses.rs index 0a5959617c..d0a6f8e941 100644 --- a/crates/stela-soc/src/machine/buses.rs +++ b/crates/stela-soc/src/machine/buses.rs @@ -137,9 +137,6 @@ impl AppleDevices { let device = self.bus.add(Box::new(S5lUart::new(console, irq))); self.map(device, ranges) .map_err(|error| refuse!("UART placement: {error}", ?error))?; - // The UART has no DMA (UCON refuses its DMA modes) and no master's - // registers: its writes leave the masters' state alone. - self.quiet.push(device); self.register_power_device(first.physical, device, false) } diff --git a/crates/stela-soc/src/machine/processors.rs b/crates/stela-soc/src/machine/processors.rs index 55a4726727..2b4c6a874b 100644 --- a/crates/stela-soc/src/machine/processors.rs +++ b/crates/stela-soc/src/machine/processors.rs @@ -270,10 +270,6 @@ impl AppleDevices { Controller::V2(id) }; self.aic = Some(device); - // The AIC starts no DMA and holds no master's registers: its - // writes (unmasks after each acknowledge, software IRQs, routes, - // timestamps) change only interrupt state, which its lines carry. - self.quiet.push(id); if matches!(device, Controller::V2(_)) { self.register_power_device(physical, id, false)?; } diff --git a/crates/stela-soc/src/machine/tests/passive.rs b/crates/stela-soc/src/machine/tests/passive.rs index a87c5210fd..7872cb001c 100644 --- a/crates/stela-soc/src/machine/tests/passive.rs +++ b/crates/stela-soc/src/machine/tests/passive.rs @@ -96,6 +96,66 @@ fn a_write_elsewhere_runs_the_usb_schedule_only_with_work() { ); } +/// A cable change reaches the USB master through its connector, not a +/// write to its devices: a write elsewhere still takes it up, a device-mode +/// attach as the controller's port and a host-mode one as its host cable, +/// and then leaves the master alone again. +#[test] +fn a_write_elsewhere_takes_up_a_cable_change() { + use crate::typec::{Attached, DataRole, Orientation, Usb2Speed}; + let mut d = AppleDevices::new(); + let dart = d + .add_dart( + Range { + physical: 0x382f00000, + bytes: 0x4000, + }, + 16, + None, + None, + ) + .unwrap(); + let phy = add_usb_phy(&mut d); + d.add_usb(&usb_placement(), dart).unwrap(); + release_usb_phy(&mut d, &phy); + d.add_cpm_power(CPM, false).unwrap(); + let mut ram = Ram::new(0x800000000, 0x10000); + let settle = |d: &mut AppleDevices, ram: &mut Ram| { + d.write(0, CPM + 0x250, 8, 1, 0).unwrap(); + d.settle_write(0, 0, &mut Locked(ram)).transfer.unwrap(); + }; + settle(&mut d, &mut ram); + let cable = |role| Attached { + orientation: Orientation::Normal, + role, + source: role == DataRole::Dfp, + vbus: true, + speed: Usb2Speed::Full, + }; + let connector = d.usb_masters[0].connector.clone(); + connector + .set_connection(Some(cable(DataRole::Ufp))) + .unwrap(); + let due = |d: &mut AppleDevices| { + let master = &d.usb_masters[0]; + let controller = d.bus.device::(master.device).unwrap(); + AppleDevices::usb_due(controller, master, 0) + }; + assert!(due(&mut d)); + settle(&mut d, &mut ram); + assert!(d.usb_masters[0].port == UsbPort::of(&connector)); + connector + .set_connection(Some(cable(DataRole::Dfp))) + .unwrap(); + assert!(due(&mut d)); + settle(&mut d, &mut ram); + let master = &d.usb_masters[0]; + let controller = d.bus.device::(master.device).unwrap(); + assert!(master.port == UsbPort::of(&connector)); + assert_eq!(controller.host_function(), Some(Usb2Speed::Full)); + assert!(!due(&mut d)); +} + /// Host cost of a CLPC counter read through a shared board, locked and /// passive, and of a write elsewhere's transfer with a USB master, full and /// with the schedule left to its work: `cargo test --release -p stela-soc diff --git a/crates/stela-soc/src/machine/transfer_times.rs b/crates/stela-soc/src/machine/transfer_times.rs index c609479c6e..82ab8dd727 100644 --- a/crates/stela-soc/src/machine/transfer_times.rs +++ b/crates/stela-soc/src/machine/transfer_times.rs @@ -110,81 +110,4 @@ mod tests { devices.transfer(0, &mut ram, 3).unwrap(); assert_eq!(devices.take_transfer_times(), [PartTime::default(); 9]); } - - struct Sink; - impl crate::uart::ConsoleSink for Sink { - fn transmit(&mut self, _: u8) -> Result<(), crate::uart::ConsoleBusy> { - Ok(()) - } - } - - struct Locked(Ram); - impl stela_engine::machine::engine::LockedMemory for Locked { - fn under( - &mut self, - _: stela_engine::machine::mmu::MemoryLocks, - ) -> &mut dyn stela_engine::machine::engine::Memory { - &mut self.0 - } - } - - /// A console byte's write settles its wires without the masters' steps, - /// except every `QUIET_WRITES + 1`th; a transfer of its own runs them. - #[test] - fn a_console_write_runs_the_masters_only_every_few_writes() { - const UART: u64 = 0x2_3520_0000; - let mut devices = AppleDevices::new(); - devices - .add_uart( - Sink, - &[crate::machine::Range { - physical: UART, - bytes: 0x4000, - }], - None, - ) - .unwrap(); - let mut ram = Locked(Ram::new(0x8_0000_0000, 0x1000)); - devices.time_transfers(Some(clock)); - let writes = super::super::QUIET_WRITES as u64 + 4; - for now in 1..=writes { - devices - .write(0, UART + 0x20, 4, u64::from(b'a'), now) - .unwrap(); - devices.settle_write(0, now, &mut ram).transfer.unwrap(); - } - let times = devices.take_transfer_times(); - // Every write settled its wires; the masters ran once, at the write - // after a full run of quiet ones. - assert_eq!(times[0].calls, writes, "{times:?}"); - assert_eq!(times[8].calls, writes, "{times:?}"); - assert!(times[1..8].iter().all(|time| time.calls == 1), "{times:?}"); - // A transfer of its own, as at a DMA deadline, always runs them. - devices.transfer(0, &mut ram.0, writes + 1).unwrap(); - let times = devices.take_transfer_times(); - assert!(times.iter().all(|time| time.calls == 1), "{times:?}"); - } - - /// An AIC unmask, the write that follows each acknowledged interrupt, - /// is as quiet as a console byte: the masters run every few writes. - #[test] - fn an_aic_unmask_runs_the_masters_only_every_few_writes() { - const AIC: u64 = 0x2_3b0c_0000; - const MASK_CLR: u64 = 0x6600; - let mut devices = AppleDevices::new(); - devices - .add_aic(AIC, 1152, stela_soc_data::aic::AicLayout::aic2(0x8000, 16)) - .unwrap(); - let mut ram = Locked(Ram::new(0x8_0000_0000, 0x1000)); - devices.time_transfers(Some(clock)); - let writes = super::super::QUIET_WRITES as u64 + 4; - for now in 1..=writes { - devices.write(0, AIC + MASK_CLR, 4, 1, now).unwrap(); - devices.settle_write(0, now, &mut ram).transfer.unwrap(); - } - let times = devices.take_transfer_times(); - assert_eq!(times[0].calls, writes, "{times:?}"); - assert_eq!(times[8].calls, writes, "{times:?}"); - assert!(times[1..8].iter().all(|time| time.calls == 1), "{times:?}"); - } }