From 09c74ca1e54d4fb8eeef059180d1394e3719e0f2 Mon Sep 17 00:00:00 2001 From: James Braid Date: Thu, 26 Nov 2026 21:55:07 -0700 Subject: [PATCH 1/5] cpu: fix the instruction clock's Count, Compare and WAIT Three things in the ci_clock build made the guest's time depend on how it read the clock, or on the host. Count kept no sub-tick remainder. Each read moved the cycle anchor on by the nanoseconds its whole ticks used, divided down to whole instructions. At 90 MHz a tick is 11.1 ns, so the anchor moved a full 10 ns instruction per tick and the rest was counted again on the next read. A guest that reads Count every other instruction, as a delay calibration does, saw one tick per instruction (100 MHz) instead of the R5000's 90 MHz. The remainder is now kept exactly, in nanoseconds times Hz, and the anchor advances to the current cycle on every read. A Count write, a re-anchor and a reset start it over. The host-clock path is unchanged. The Compare deadline check raised IP7 and bumped the tick counter without claiming the deadline's delivery ticket. The handler's next Count read then crossed Compare, found the ticket still armed and delivered it a second time, so the tick counter ran at 2000 Hz against the 1000 Hz the guest programmed. The check now claims the ticket, as the host timer does. Two tests armed the deadline without one, which no guest can do, and now arm it through a Compare write. A WAIT with interrupts enabled stalled inside one instruction, advancing time by host time until an interrupt arrived. Idle time was then a function of the host, and no deadline check ran while it waited. Under ci_clock WAIT now answers retry, as the masked case already does, until an interrupt the IM bits pass is pending; each retry is a dispatch, so time is counted per instruction. The stall loop is unreachable under ci_clock, so its Compare check goes, and the two tests of the stall's pacing apply only to the host-clock build. Production lines: +34 -14 --- src/cpu/mips_core.rs | 41 ++++++++++++++----- src/cpu/mips_exec.rs | 7 ++-- src/cpu/mips_exec_test.rs | 86 +++++++++++++++++++++++++-------------- 3 files changed, 90 insertions(+), 44 deletions(-) diff --git a/src/cpu/mips_core.rs b/src/cpu/mips_core.rs index 4c2ac1623..a23bbf47f 100644 --- a/src/cpu/mips_core.rs +++ b/src/cpu/mips_core.rs @@ -966,6 +966,9 @@ pub struct MipsCore { /// stay deterministic). #[cfg(feature = "ci_clock")] pub(crate) count_anchor_cycle: u64, + /// ci_clock: the part of a Count tick the anchor has run, in ns times Hz. + #[cfg(feature = "ci_clock")] + pub(crate) count_frac: u64, /// ci_clock: `hot.cycles` value at which IP7 fires (checked in step()'s /// preamble instead of an hptimer). u64::MAX = disarmed. #[cfg(feature = "ci_clock")] @@ -1468,6 +1471,8 @@ impl MipsCore { #[cfg(feature = "ci_clock")] count_anchor_cycle: 0, #[cfg(feature = "ci_clock")] + count_frac: 0, + #[cfg(feature = "ci_clock")] count_fire_cycle: u64::MAX, irqs_taken: 0, count_last_guest_read: 0, @@ -1513,6 +1518,7 @@ impl MipsCore { #[cfg(feature = "ci_clock")] { self.count_anchor_cycle = 0; + self.count_frac = 0; self.count_fire_cycle = u64::MAX; } self.disarm_compare_timer(); @@ -1734,13 +1740,22 @@ impl MipsCore { let elapsed_ns = cycles.wrapping_sub(self.count_anchor_cycle).saturating_mul(NS_PER_GUEST_CYCLE); #[cfg(not(feature = "ci_clock"))] let elapsed_ns = self.count_anchor_instant.elapsed().as_nanos() as u64; - let ticks = ((elapsed_ns as u128 * self.count_hz as u128) / 1_000_000_000) as u64; + #[cfg_attr(not(feature = "ci_clock"), allow(unused_mut))] + let mut acc = elapsed_ns as u128 * self.count_hz as u128; + #[cfg(feature = "ci_clock")] + { + acc += self.count_frac as u128; + // A tick is not a whole number of cycles: keep the remainder exactly. + self.count_anchor_cycle = cycles; + self.count_frac = (acc % 1_000_000_000) as u64; + } + let ticks = (acc / 1_000_000_000) as u64; if ticks != 0 { - let consumed_ns = ((ticks as u128 * 1_000_000_000) / self.count_hz as u128) as u64; - #[cfg(feature = "ci_clock")] - { self.count_anchor_cycle = self.count_anchor_cycle.wrapping_add(consumed_ns / NS_PER_GUEST_CYCLE); } #[cfg(not(feature = "ci_clock"))] - { self.count_anchor_instant += std::time::Duration::from_nanos(consumed_ns); } + { + let consumed_ns = ((ticks as u128 * 1_000_000_000) / self.count_hz as u128) as u64; + self.count_anchor_instant += std::time::Duration::from_nanos(consumed_ns); + } let before = self.cp0_count as u32; let after = before.wrapping_add(ticks as u32); self.cp0_count = after as u64; @@ -1807,7 +1822,11 @@ impl MipsCore { let elapsed_ns = self.hot.cycles.wrapping_sub(self.count_anchor_cycle).saturating_mul(NS_PER_GUEST_CYCLE); #[cfg(not(feature = "ci_clock"))] let elapsed_ns = self.count_anchor_instant.elapsed().as_nanos() as u64; - let ticks = ((elapsed_ns as u128 * self.count_hz as u128) / 1_000_000_000) as u64; + #[cfg(feature = "ci_clock")] + let frac = self.count_frac as u128; + #[cfg(not(feature = "ci_clock"))] + let frac = 0; + let ticks = ((elapsed_ns as u128 * self.count_hz as u128 + frac) / 1_000_000_000) as u64; (self.cp0_count as u32).wrapping_add(ticks as u32) } @@ -1952,9 +1971,8 @@ impl MipsCore { // normally a Compare write re-arms much sooner. let wrap_ns = ((1u128 << 32) * 1_000_000_000) / self.count_hz as u128; self.count_fire_cycle = self.hot.cycles.saturating_add(wrap_ns as u64 / NS_PER_GUEST_CYCLE); - self.hot.interrupts.fetch_or(CAUSE_IP7 as u64, Ordering::SeqCst); - crate::pf_level!(crate::perfetto::events::IP7_LEVEL[self.cpu_id as usize % crate::perfetto::events::IP7_CPUS], crate::perfetto::events::IP7_COMPARE[self.cpu_id as usize % crate::perfetto::events::IP7_CPUS], true); - self.fasttick_count.fetch_add(1, Ordering::Relaxed); + // Claim the armed ticket, as the host timer does, so a Count read crossing Compare does not deliver it again. + claim_ip7(&self.ip7_seq_shared, self.ip7_seq, &self.hot.interrupts, &self.fasttick_count, self.cpu_id); } } @@ -1982,7 +2000,10 @@ impl MipsCore { pub fn reanchor_count_and_reschedule(&mut self) { self.count_read_cycle = self.hot.cycles; #[cfg(feature = "ci_clock")] - { self.count_anchor_cycle = self.hot.cycles; } + { + self.count_anchor_cycle = self.hot.cycles; + self.count_frac = 0; + } #[cfg(not(feature = "ci_clock"))] { self.count_anchor_instant = std::time::Instant::now(); } self.schedule_compare_timer(); diff --git a/src/cpu/mips_exec.rs b/src/cpu/mips_exec.rs index 1ed1978f2..033e9a0b0 100644 --- a/src/cpu/mips_exec.rs +++ b/src/cpu/mips_exec.rs @@ -8017,7 +8017,9 @@ va={:#018x} phys={:#010x} (code pfn {:#x}, page {:#010x}, word {}/{})", // held an idle OpenBSD O2 on the WAIT for good with its clock // interrupt pending. So the masked case polls once per dispatch and // completes when an interrupt the IM bits pass is pending. - if !self.core.interrupts_enabled() { + // ci_clock retries even with interrupts enabled: the stall below runs no steps, so no + // deadline would be checked and no instruction counted while it waited. + if cfg!(feature = "ci_clock") || !self.core.interrupts_enabled() { if self.wait_wake_pending() { return self.handle_exec_complete(); } @@ -8030,9 +8032,6 @@ va={:#018x} phys={:#010x} (code pfn {:#x}, page {:#010x}, word {}/{})", let stall_start = std::time::Instant::now(); let mut issued: u64 = 0; loop { - // ci_clock has no timer thread and no step runs while this stalls. - #[cfg(feature = "ci_clock")] - self.core.fire_compare_if_due(); let pending = self.core.hot.interrupts.load(Ordering::Relaxed); if pending & (SOFT_RESET_BIT | crate::cpu::smp::HOST_PARK_BIT) != 0 { break; diff --git a/src/cpu/mips_exec_test.rs b/src/cpu/mips_exec_test.rs index 45586cb7f..129d89aa7 100644 --- a/src/cpu/mips_exec_test.rs +++ b/src/cpu/mips_exec_test.rs @@ -2268,6 +2268,7 @@ mod tests { /// The stall moves the cycle counter at the pacing rate so cycle readers /// see time pass, but it retires nothing: the MIPS figure must not count /// it, or an idle guest sitting in WAIT reads about 100 MIPS. + #[cfg(not(feature = "ci_clock"))] #[test] fn test_wait_stall_is_not_retired() { let (mut exec, _) = create_executor(); @@ -2304,6 +2305,7 @@ mod tests { /// A soft reset must escape the stall even when interrupts are enabled but /// nothing is pending — otherwise a reset could not break into an idle /// guest. + #[cfg(not(feature = "ci_clock"))] #[test] fn test_wait_breaks_out_on_soft_reset() { let (mut exec, _) = create_executor(); @@ -2345,41 +2347,64 @@ mod tests { assert_eq!(exec.core.read_gpr(2), 7, "released, the instruction runs"); } - /// Under `ci_clock` a WAIT stall runs no steps, so the stall must raise - /// IP7 when it passes the Compare deadline. A soft reset after 1 s stops - /// a regression instead of hanging. + /// A Compare the deadline check delivers is one tick: the handler's Count + /// read that follows must not deliver it again. #[cfg(feature = "ci_clock")] #[test] - fn ci_clock_wait_wakes_on_the_compare_deadline() { - let (mut exec, _) = create_executor(); - exec.core.pc = 0xFFFF_FFFF_8000_1000; + fn ci_clock_compare_counts_one_tick() { + use std::sync::atomic::Ordering; + let mut core = crate::cpu::mips_core::MipsCore::default(); + core.set_count_hz(90_000_000); + core.write_cp0(11, 900); + core.hot.cycles += 2_000; + core.fire_compare_if_due(); + assert_ne!(core.hot.interrupts.load(Ordering::SeqCst) & crate::cpu::mips_core::CAUSE_IP7 as u64, 0); + core.count_now(); + assert_eq!(core.fasttick_count.load(Ordering::Relaxed), 1); + } + + /// A 90 MHz Count read every other instruction, as a calibration loop does, still runs at + /// 90 MHz, not one tick a cycle. + #[cfg(feature = "ci_clock")] + #[test] + fn ci_clock_count_read_often_keeps_its_rate() { + let mut core = crate::cpu::mips_core::MipsCore::default(); + core.set_count_hz(90_000_000); + for _ in 0..500_000 { + core.hot.cycles += 2; + core.count_now(); + } + assert_eq!(core.count_now(), 900_000, "10 ms of instructions"); + } + + /// Under `ci_clock` a WAIT with interrupts enabled retries once per dispatch, so the Compare + /// deadline is checked and time counted while it waits. + #[cfg(feature = "ci_clock")] + #[test] + fn ci_clock_wait_retries_until_the_compare_deadline() { + let (mut exec, mem) = create_executor(); + let wait_pc = 0xFFFF_FFFF_8000_1000u64; + mem.set_word(0x1000, (OP_COP0 << 26) | (RS_TLB << 21) | FUNCT_WAIT); + mem.set_word(0x1004, 0); + exec.core.pc = wait_pc; exec.core.cp0_status |= crate::cpu::mips_core::STATUS_IE | (1 << (crate::cpu::mips_core::STATUS_IM_SHIFT + 7)); exec.core.cp0_status &= !(crate::cpu::mips_core::STATUS_EXL | crate::cpu::mips_core::STATUS_ERL); - let deadline = exec.core.hot.cycles + 100_000; // 1 ms of stall at 10 ns/cycle - exec.core.count_fire_cycle = deadline; - - struct Irq(*const std::sync::atomic::AtomicU64); - unsafe impl Send for Irq {} - let irq = Irq(exec.interrupts_ptr()); - let (done, stop) = std::sync::mpsc::channel::<()>(); - let watchdog = std::thread::spawn(move || { - let irq = irq; - if stop.recv_timeout(std::time::Duration::from_secs(1)).is_err() { - // SAFETY: the executor outlives this thread, which is joined below. - unsafe { &*irq.0 }.fetch_or(crate::cpu::mips_exec::SOFT_RESET_BIT, std::sync::atomic::Ordering::SeqCst); - } - }); - let wait_instr = (OP_COP0 << 26) | (RS_TLB << 21) | FUNCT_WAIT; - assert_eq!(exec.exec(wait_instr), EXEC_COMPLETE); - let _ = done.send(()); - watchdog.join().unwrap(); - - let pending = exec.core.hot.interrupts.load(std::sync::atomic::Ordering::SeqCst); - assert_eq!(pending & crate::cpu::mips_exec::SOFT_RESET_BIT, 0, - "the stall ran 1 s past a 1 ms Compare deadline"); - assert_ne!(pending & crate::cpu::mips_core::CAUSE_IP7 as u64, 0, "IP7 must be pending"); + // 1 ms of stall at 10 ns/cycle, armed as the guest arms it. + let count = exec.core.count_now(); + exec.core.write_cp0(11, count.wrapping_add((exec.core.count_hz / 1000) as u32) as u64); + let deadline = exec.core.count_fire_cycle; + assert!(deadline <= exec.core.hot.cycles + 100_000); + let mut steps = 0u64; + while exec.core.pc == wait_pc && steps < 1_000_000 { + exec.step_int(); + steps += 1; + } + assert_ne!(exec.core.pc, wait_pc, "the WAIT never ended"); assert!(exec.core.hot.cycles >= deadline); + assert!(steps >= deadline - 100, "{steps} dispatches reached cycle {deadline}: the stall skipped time"); + let pending = exec.core.hot.interrupts.load(std::sync::atomic::Ordering::SeqCst); + assert_ne!((pending as u32 | exec.core.cp0_cause) & crate::cpu::mips_core::CAUSE_IP7, 0, "IP7 must be pending"); } #[test] @@ -8238,7 +8263,8 @@ mod tests { mem.set_word(0x1004, 0); exec.core.pc = 0xffff_ffff_8000_1000; exec.core.cp0_status = STATUS_IE | (1 << (STATUS_IM_SHIFT + 7)); - exec.core.count_fire_cycle = 100; + let count = exec.core.count_now(); + exec.core.write_cp0(11, count.wrapping_add(33) as u64); // 1 us at 33 MHz: 100 cycles // A failed run spins in compiled code for good; the park bit, which // compiled code does see, gets it out so the test fails instead. From 4a15b8377dae669684a14028a4d0101da7f13604 Mon Sep 17 00:00:00 2001 From: James Braid Date: Fri, 27 Nov 2026 17:49:42 -0700 Subject: [PATCH 2/5] hptimer: run a counting clock's timers from its CPU With ci_clock the Indy's and the O2's machine time is CPU 0's retired instructions, but the timers still ran on the host timer thread. Their callbacks (the 8254, the UARTs, the display's retrace and line events, the O2's device service pass) then fired at host-chosen instructions, so two runs of one PROM diverged. A manager on a counting clock now spawns no thread. CPU 0 runs TimerManager::run_expired between batches with the executor unlocked, so a callback that needs the executor cannot deadlock. It is the host thread's own loop, made generic over the time it reads and over having a waiter, so there is one scheduler. Deadlines are machine time, which is why add_recurring now takes a first delay as a Duration, as add_one_shot already does, in place of an Instant that could not be machine time. A batch is not the only place time must be checked. Compiled code stays in a region until the interrupt word is nonzero, and Compare is the only deadline it sees. A guest that never arms Compare (the IP28 kernel leaves it at zero) would spin in a compiled loop for a whole Count wrap. The cycle threshold that already ends such a spin for Compare is now the earlier of Compare and the manager's next deadline. Reaching a timer's deadline claims no IP7: it sets a free high bit in the interrupt word, kept out of Cause, WAIT and park wake like the park bit. Arming a timer from any thread sets the same bit, so the loop leaves its batch, runs the timers, clears the bit and sets the next deadline. Only the CPU thread writes the threshold. Machine setup shares one clock constructor, Clock::cpu_or_host, and set_cpu_cycles is now a no-op on a host clock, which removes the cfg pairs at those sites. The display refresh runs from the timers on a counting clock, composes a requested frame on the caller's thread while the CPU is stopped, and the O2 service pass is a recurring timer. CRIME reset, power-off and the flash save stay on the service thread because they stop and start the CPU. Battery clocks start at 2026-01-01 so the date does not depend on when the run is made, and idle-pause stays off on a counting machine because it paces the CPU on host time. The manager finds the CPU's interrupt word through a pointer it keeps under its own lock, set when the machine is built and cleared by the core's Drop before the word goes. The manager can outlive the core, as the display holds it too, so a late timer then wakes nothing. O2Machine now stops the machine clock when it drops, as Machine does, so nothing reads the CPU's cycle counter afterwards. Default builds only change in shape: add_recurring's argument, the generic timer loop and an unused run_expired. Production lines: +276 -64 --- FEATURES.md | 2 +- src/chime_tests.rs | 5 +- src/clock.rs | 29 +++++++++- src/cpu/mips_core.rs | 75 ++++++++++++++++++++---- src/cpu/mips_exec.rs | 35 ++++++++++-- src/cpu/mips_exec_test.rs | 116 +++++++++++++++++++++++++++++++++++++- src/cpu/smp.rs | 4 ++ src/dev/battery_clock.rs | 30 ++++++++-- src/dev/ds1x86.rs | 10 ++-- src/dev/hal2.rs | 2 +- src/display/mod.rs | 56 +++++++++++++----- src/display/tests.rs | 45 +++++++++++++++ src/hptimer.rs | 82 ++++++++++++++++++++++----- src/hptimer_tests.rs | 6 +- src/ip32_machine.rs | 25 ++++++-- src/machine.rs | 11 ++-- src/test_board.rs | 16 ++++++ src/ui.rs | 2 +- 18 files changed, 475 insertions(+), 76 deletions(-) diff --git a/FEATURES.md b/FEATURES.md index 1b8d9dfa9..f38925e52 100644 --- a/FEATURES.md +++ b/FEATURES.md @@ -22,7 +22,7 @@ Select with `cargo build --release --features `; add | `perfetto` | Perfetto trace recording (`--perfetto FILE`, monitor `perfetto`); see [docs/perfetto.md](docs/perfetto.md). Lightning-compatible. | — | | `rexdiag` | REX3 per-GO activity and dispatch counters. Default on; removable in a core build. | — | | `fetchverify` | Compare executed instruction bytes with memory in interpreter/JIT; expensive stale-code detector. | — | -| `ci_clock` | Synthetic deterministic Count clock for CI/snapshot validation; replaces real-time Count timing. Also times the Indy's DS1386 and 8254 on the cycle count. | — | +| `ci_clock` | Synthetic deterministic Count clock for CI/snapshot validation; replaces real-time Count timing. Also times the Indy's DS1386 and 8254 on the cycle count, starts every battery clock at 2026-01-01T00:00:00Z, and on the Indy and the O2 runs the timers and the display's retrace on CPU 0's instructions: two runs of one PROM are byte-identical. Not repeatable with `idle-pause` (which it turns off on those machines), after a CPU hard reset, which sets the clock back, or on the O2's CRIME cold reset and power-off, which the service thread still performs at a host-chosen instruction. | — | | `opcodefusion` | Interpreter instruction fusion; breakpoints on a fused second instruction cannot fire. | — | | `lightning` | Strip breakpoints/traceback for speed; hides GUI Debug controls. | `opcodefusion` | | `tlbvmap` | O(1) TLB fast path (the vmap); without it lookups use the MRU scan. On by default. | — | diff --git a/src/chime_tests.rs b/src/chime_tests.rs index 1ab83b207..1d047c40a 100644 --- a/src/chime_tests.rs +++ b/src/chime_tests.rs @@ -31,6 +31,9 @@ fn boot(profile: MachineProfile, cpu: &str, quiet: usize, edit: fn(&mut MachineC m.start(); m.cpu_start(); let deadline = Instant::now() + Duration::from_secs(1700); + // Sound follows machine time on a counting clock, which a debug build under load + // advances slowly: five host seconds of nothing new is then not the end. + let patience = if crate::clock::COUNTING { 400 } else { 20 }; let (mut seen, mut still) = (0, 0); let played = loop { std::thread::sleep(Duration::from_millis(250)); @@ -39,7 +42,7 @@ fn boot(profile: MachineProfile, cpu: &str, quiet: usize, edit: fn(&mut MachineC still = if all.len() == seen { still + 1 } else { 0 }; seen = all.len(); let tail = all.iter().rev().take_while(|&&f| f == (0, 0)).count(); - if all.iter().any(|&f| f != (0, 0)) && (tail >= quiet || still >= 20) { + if all.iter().any(|&f| f != (0, 0)) && (tail >= quiet || still >= patience) { let rate = recs[0].0; assert!(recs.iter().all(|r| r.0 == rate), "the card changed rate"); break (rate, all.into_iter().filter(|&f| f != (0, 0)).collect()); diff --git a/src/clock.rs b/src/clock.rs index d2220df2f..0762d80fa 100644 --- a/src/clock.rs +++ b/src/clock.rs @@ -2,6 +2,10 @@ use std::sync::{atomic::{AtomicBool, AtomicU64, Ordering::{Acquire, Relaxed, Release}}, Arc}; +/// Whether this build runs machines on instruction counts, not host time (`ci_clock`). The one +/// switch the devices test; a machine whose clock counts says so with [`Clock::is_counting`]. +pub const COUNTING: bool = cfg!(feature = "ci_clock"); + #[derive(Default)] struct Inner { /// Source minus machine nanoseconds, while running. @@ -9,7 +13,7 @@ struct Inner { /// The reading while stopped. held: AtomicU64, stopped: AtomicBool, - /// ci_clock, the Indy's clock only: the source is the first CPU's retired instructions. + /// ci_clock, a machine whose timers run on its CPU: the source is the first CPU's retired instructions. #[cfg(feature = "ci_clock")] cycles: Option>, #[cfg(test)] @@ -50,9 +54,30 @@ impl Clock { Clock(Arc::new(Inner { cycles: Some(Default::default()), ..Default::default() })) } - #[cfg(feature = "ci_clock")] + /// The clock of a machine whose timers can run on its one CPU: that CPU's instructions when + /// the build counts, else host time. + pub fn cpu_or_host() -> Self { + #[cfg(feature = "ci_clock")] + return Self::counting(); + #[cfg(not(feature = "ci_clock"))] + Self::new() + } + + /// Whether the clock counts the CPU's instructions: its timers then run on that CPU. + #[inline] + pub fn is_counting(&self) -> bool { + #[cfg(feature = "ci_clock")] + return self.0.cycles.is_some(); + #[cfg(not(feature = "ci_clock"))] + false + } + + /// Give a counting clock its counter; any other clock ignores it. pub fn set_cpu_cycles(&self, cycles: crate::cpu::mips_core::CyclesPtr) { + #[cfg(feature = "ci_clock")] let _ = self.0.cycles.as_ref().map(|o| o.set(cycles)); + #[cfg(not(feature = "ci_clock"))] + let _ = cycles; } pub fn now(&self) -> u64 { diff --git a/src/cpu/mips_core.rs b/src/cpu/mips_core.rs index a23bbf47f..d13c71a6f 100644 --- a/src/cpu/mips_core.rs +++ b/src/cpu/mips_core.rs @@ -68,7 +68,6 @@ pub const DEFAULT_COUNT_HZ: u64 = 33_000_000; /// ci_clock: synthetic nanoseconds per retired instruction (~100 MIPS R4400). /// Virtual time is derived from `hot.cycles` instead of the wall clock so the /// snapshot determinism validator stays reproducible at any host speed. -#[cfg(feature = "ci_clock")] pub const NS_PER_GUEST_CYCLE: u64 = 10; /// Claim the right to deliver IP7 for the armed deadline `ticket`. @@ -129,7 +128,7 @@ const IP7_SEQ_CLAIMING: u64 = u64::MAX; /// `Ioc::set_interrupts`'s stored pointer: it points into the core owned by /// the executor's top-level `Arc>`, and `Drop for MipsCore` removes /// the timer before the core goes away. -struct TimerIrqPtr(*const AtomicU64); +pub(crate) struct TimerIrqPtr(pub(crate) *const AtomicU64); unsafe impl Send for TimerIrqPtr {} pub const CAUSE_CE_MASK: u32 = 0x3 << 28; // Coprocessor Error mask pub const CAUSE_CE_SHIFT: u32 = 28; // Coprocessor Error shift @@ -969,10 +968,16 @@ pub struct MipsCore { /// ci_clock: the part of a Count tick the anchor has run, in ns times Hz. #[cfg(feature = "ci_clock")] pub(crate) count_frac: u64, - /// ci_clock: `hot.cycles` value at which IP7 fires (checked in step()'s - /// preamble instead of an hptimer). u64::MAX = disarmed. + /// ci_clock: `hot.cycles` of the next deadline, Compare's or the timers' (checked in step() + /// and at compiled code's cycle flushes). u64::MAX = none; only the CPU thread writes it. #[cfg(feature = "ci_clock")] pub count_fire_cycle: u64, + /// ci_clock: the part of `count_fire_cycle` that is Compare's, and the part that is the + /// timer manager's next deadline. u64::MAX = none. + #[cfg(feature = "ci_clock")] + count_compare_cycle: u64, + #[cfg(feature = "ci_clock")] + count_timer_cycle: u64, /// Interrupt exceptions this CPU has taken for a line other than the CP0 /// timer (IP7) alone. The idle parker reads it to tell whether the CPU /// ran a device or inter-processor handler since its last park: on a @@ -1311,6 +1316,10 @@ impl Drop for MipsCore { // core (`TimerIrqPtr`) — take it out of the manager before the // pointee goes away. self.disarm_compare_timer(); + // So is the counting manager's pointer to the interrupt word, which only CPU 0 hands over. + if let Some(tm) = self.timer_mgr.as_ref().filter(|_| self.cpu_id == 0) { + tm.set_interrupts(std::ptr::null()); + } } } @@ -1474,6 +1483,10 @@ impl MipsCore { count_frac: 0, #[cfg(feature = "ci_clock")] count_fire_cycle: u64::MAX, + #[cfg(feature = "ci_clock")] + count_compare_cycle: u64::MAX, + #[cfg(feature = "ci_clock")] + count_timer_cycle: u64::MAX, irqs_taken: 0, count_last_guest_read: 0, count_write_samples: false, @@ -1519,7 +1532,7 @@ impl MipsCore { { self.count_anchor_cycle = 0; self.count_frac = 0; - self.count_fire_cycle = u64::MAX; + self.count_timer_cycle = u64::MAX; } self.disarm_compare_timer(); self.tick_rate.reset(0); @@ -1568,6 +1581,18 @@ impl MipsCore { self.reset_registers(soft); // A reset does not release a CPU another thread is holding. self.hot.interrupts.fetch_and(crate::cpu::smp::HOST_PARK_BIT, Ordering::SeqCst); + self.ask_for_timers(); + } + + /// Have a counting manager's timers run at the next batch end: a reset or a restart loses the + /// deadline this CPU was watching. + fn ask_for_timers(&self) { + if crate::clock::COUNTING + && self.cpu_id == 0 + && self.timer_mgr.as_ref().is_some_and(|tm| tm.clock().is_counting()) + { + self.hot.interrupts.fetch_or(crate::cpu::smp::TIMERS_BIT, Ordering::SeqCst); + } } /// Read a GPR by index. gpr\[0\] is always kept at zero. @@ -1893,7 +1918,8 @@ impl MipsCore { let ns = compare_delay_ns(self.cp0_compare as u32, self.cp0_count as u32, self.count_hz); #[cfg(feature = "ci_clock")] { - self.count_fire_cycle = self.hot.cycles.saturating_add(ns / NS_PER_GUEST_CYCLE); + self.count_compare_cycle = self.hot.cycles.saturating_add(ns / NS_PER_GUEST_CYCLE); + self.count_fire_cycle = self.count_compare_cycle.min(self.count_timer_cycle); } #[cfg(not(feature = "ci_clock"))] { @@ -1960,26 +1986,50 @@ impl MipsCore { } } - /// ci_clock: raise IP7 once `hot.cycles` has reached the Compare - /// deadline. A threshold, not an edge, so a caller that looks late still - /// delivers it, once. + /// ci_clock: act on the deadline `hot.cycles` has reached: Compare's raises IP7, the timers' + /// set `TIMERS_BIT`. A threshold, not an edge, so a late caller still delivers each once. #[cfg(feature = "ci_clock")] #[inline(always)] pub(crate) fn fire_compare_if_due(&mut self) { - if self.hot.cycles >= self.count_fire_cycle { + if self.hot.cycles < self.count_fire_cycle { + return; + } + if self.hot.cycles >= self.count_compare_cycle { // Next architectural match is a full 32-bit Count wrap away; // normally a Compare write re-arms much sooner. let wrap_ns = ((1u128 << 32) * 1_000_000_000) / self.count_hz as u128; - self.count_fire_cycle = self.hot.cycles.saturating_add(wrap_ns as u64 / NS_PER_GUEST_CYCLE); + self.count_compare_cycle = self.hot.cycles.saturating_add(wrap_ns as u64 / NS_PER_GUEST_CYCLE); // Claim the armed ticket, as the host timer does, so a Count read crossing Compare does not deliver it again. claim_ip7(&self.ip7_seq_shared, self.ip7_seq, &self.hot.interrupts, &self.fasttick_count, self.cpu_id); } + if self.hot.cycles >= self.count_timer_cycle { + // The CPU loop runs them and sets the next deadline. + self.count_timer_cycle = u64::MAX; + self.hot.interrupts.fetch_or(crate::cpu::smp::TIMERS_BIT, Ordering::SeqCst); + } + self.count_fire_cycle = self.count_compare_cycle.min(self.count_timer_cycle); + } + + /// The timers have run, `now` machine nanoseconds in, and the next is due at `next`: set the + /// deadline `fire_compare_if_due` watches for them. + pub(crate) fn set_timer_deadline(&mut self, next: Option, now: u64) { + #[cfg(feature = "ci_clock")] + { + let wait = next.map_or(u64::MAX, |due| due.saturating_sub(now).div_ceil(NS_PER_GUEST_CYCLE)); + self.count_timer_cycle = self.hot.cycles.saturating_add(wait); + self.count_fire_cycle = self.count_compare_cycle.min(self.count_timer_cycle); + } + #[cfg(not(feature = "ci_clock"))] + let _ = (next, now); } /// Cancel any armed Count==Compare interrupt source. fn disarm_compare_timer(&mut self) { #[cfg(feature = "ci_clock")] - { self.count_fire_cycle = u64::MAX; } + { + self.count_compare_cycle = u64::MAX; + self.count_fire_cycle = self.count_timer_cycle; + } if let (Some(tm), Some(id)) = (self.timer_mgr.as_ref(), self.timer_id.take()) { tm.remove(id); } @@ -2077,6 +2127,7 @@ impl MipsCore { pub fn on_cpu_start(&mut self) { self.count_paused = false; self.reanchor_count_and_reschedule(); + self.ask_for_timers(); } /// Write CP0 register by index. diff --git a/src/cpu/mips_exec.rs b/src/cpu/mips_exec.rs index 033e9a0b0..2257aee61 100644 --- a/src/cpu/mips_exec.rs +++ b/src/cpu/mips_exec.rs @@ -8019,7 +8019,7 @@ va={:#018x} phys={:#010x} (code pfn {:#x}, page {:#010x}, word {}/{})", // completes when an interrupt the IM bits pass is pending. // ci_clock retries even with interrupts enabled: the stall below runs no steps, so no // deadline would be checked and no instruction counted while it waited. - if cfg!(feature = "ci_clock") || !self.core.interrupts_enabled() { + if crate::clock::COUNTING || !self.core.interrupts_enabled() { if self.wait_wake_pending() { return self.handle_exec_complete(); } @@ -8063,10 +8063,8 @@ va={:#018x} phys={:#010x} (code pfn {:#x}, page {:#010x}, word {}/{})", // then tracks wall time the same way a running one does. let now = std::time::Instant::now(); let elapsed_ns = now.duration_since(stall_start).as_nanos() as u64; - // 10ns/cycle — the same rate `mips_core::NS_PER_GUEST_CYCLE` - // defines, restated here because that constant is `ci_clock`-only - // while this pacing must hold in every build. - const STALL_NS_PER_CYCLE: u64 = 10; + // 10ns/cycle: the rate `mips_core::NS_PER_GUEST_CYCLE` defines. + const STALL_NS_PER_CYCLE: u64 = crate::cpu::mips_core::NS_PER_GUEST_CYCLE; let want = elapsed_ns / STALL_NS_PER_CYCLE; if want > issued { let delta = want - issued; @@ -11434,6 +11432,13 @@ impl Device for MipsCpu Device for MipsCpu { // Reported through the stop note (`status`, `wait`), @@ -11543,8 +11554,20 @@ impl Device for MipsCpu Option { + let (mut exec, mem) = create_executor(); + mem.set_word(0x1000, (OP_BEQ << 26) | 0xFFFF); // beq $0, $0, self + mem.set_word(0x1004, 0); + exec.core.pc = 0xffff_ffff_8000_1000; + exec.core.cpu_id = cpu_id; + let tm = Arc::new(crate::hptimer::TimerManager::with_clock(crate::clock::Clock::counting())); + exec.core.set_timer_manager(tm.clone()); + let ran = Arc::new(parking_lot::Mutex::new(None)); + let by = ran.clone(); + tm.add_one_shot(std::time::Duration::from_micros(1), move || { + *by.lock() = Some(std::thread::current().name().unwrap_or("").to_string()); + crate::hptimer::TimerReturn::Delete + }); + let cpu = Arc::new(crate::cpu::mips_exec::MipsCpu::new(exec)); + tm.clock().set_cpu_cycles(cpu.cycles_ptr()); + if cpu_id == 0 { + tm.set_interrupts(cpu.interrupts_ptr()); + } + crate::traits::Device::start(&*cpu); + // Run until the CPU is far past the deadline, not for a fixed host time. + assert!(crate::test_board::until(|| cpu.cycles_ptr().get() > 1_000_000)); + crate::traits::Device::stop(&*cpu); + tm.set_interrupts(std::ptr::null()); + let by = ran.lock().take(); + by + }; + let by = spin(0).expect("the timer ran"); + assert_ne!(by, "hptimer", "run by the CPU, not the host timer thread"); + assert_eq!(spin(1), None); + } + + /// A timer's deadline is not Compare's: reaching it asks the CPU loop to run the timers and + /// leaves IP7 alone. + #[cfg(feature = "ci_clock")] + #[test] + fn ci_clock_a_due_timer_asks_for_the_timers_and_not_for_ip7() { + use std::sync::atomic::Ordering; + let mut core = crate::cpu::mips_core::MipsCore::default(); + core.write_cp0(11, 0x10_0000); // Compare far away + core.hot.cycles = 1_000; + core.set_timer_deadline(Some(5_000), 0); // due in 500 cycles + core.hot.cycles += 499; + core.fire_compare_if_due(); + assert_eq!(core.hot.interrupts.load(Ordering::SeqCst), 0, "not yet"); + core.hot.cycles += 1; + core.fire_compare_if_due(); + assert_eq!(core.hot.interrupts.load(Ordering::SeqCst), crate::cpu::smp::TIMERS_BIT); + assert_eq!(core.fasttick_count.load(Ordering::Relaxed), 0, "no Compare tick"); + core.hot.cycles += 1; + core.fire_compare_if_due(); + assert_eq!(core.hot.interrupts.load(Ordering::SeqCst), crate::cpu::smp::TIMERS_BIT, "asked once"); + } + #[test] fn test_eret() { let (mut exec, _) = create_executor(); @@ -8293,6 +8353,60 @@ mod tests { assert_ne!(exec.core.cp0_status & STATUS_EXL, 0, "no interrupt taken"); } + /// A spin on one `beq` leaves compiled code only for a nonzero interrupt word, and nothing + /// arms Compare here: the timers' deadline alone must reach it. + #[cfg(all(feature = "jitv2", feature = "ci_clock"))] + #[test] + fn ci_clock_a_compiled_spin_takes_a_timer_deadline() { + use crate::cpu::mips_core::STATUS_IE; + use crate::cpu::smp::{HOST_PARK_BIT, TIMERS_BIT}; + use std::sync::atomic::Ordering; + let mem = Arc::new(MockMemory::new()); + let bus: Arc = mem.clone(); + let mut exec: MipsExecutor = + MipsExecutor::new(bus, PassthroughTlb::default(), &MipsCpuConfig::indy()); + exec.jitv2_inline_compile = true; + exec.install_jit_hooks(); + #[cfg(feature = "fetchverify")] + { exec.core.fetch_verify_on = false; } + mem.set_word(0x1000, (OP_BEQ << 26) | 0xFFFF); // beq $0, $0, self + mem.set_word(0x1004, 0); + exec.core.pc = 0xffff_ffff_8000_1000; + exec.core.cp0_status = STATUS_IE; + let tm = Arc::new(crate::hptimer::TimerManager::with_clock(crate::clock::Clock::counting())); + exec.core.set_timer_manager(tm.clone()); + tm.clock().set_cpu_cycles(crate::cpu::mips_core::CyclesPtr::new(&exec.core.hot.cycles)); + tm.set_interrupts(exec.interrupts_ptr()); + tm.add_one_shot(std::time::Duration::from_micros(1), || crate::hptimer::TimerReturn::Delete); // 100 cycles + assert_ne!(exec.core.hot.interrupts.load(Ordering::SeqCst) & TIMERS_BIT, 0, "arming asked for the timers"); + exec.core.hot.interrupts.fetch_and(!TIMERS_BIT, Ordering::SeqCst); + let next = tm.run_expired(); + exec.core.set_timer_deadline(next, tm.clock().now()); + + struct Irq(*const std::sync::atomic::AtomicU64); + unsafe impl Send for Irq {} + let irq = Irq(exec.interrupts_ptr()); + let (done, stop) = std::sync::mpsc::channel::<()>(); + let watchdog = std::thread::spawn(move || { + let irq = irq; + if stop.recv_timeout(std::time::Duration::from_secs(2)).is_err() { + // SAFETY: the executor outlives this thread, which is joined below. + unsafe { &*irq.0 }.fetch_or(HOST_PARK_BIT, Ordering::SeqCst); + } + }); + for _ in 0..100_000 { + exec.step_jit(); + if exec.core.hot.interrupts.load(Ordering::SeqCst) & (TIMERS_BIT | HOST_PARK_BIT) != 0 { + break; + } + } + let _ = done.send(()); + watchdog.join().unwrap(); + let word = exec.core.hot.interrupts.load(Ordering::SeqCst); + assert_eq!(word & HOST_PARK_BIT, 0, "the compiled spin ran 2 s past the deadline"); + assert_ne!(word & TIMERS_BIT, 0, "the deadline asked for the timers"); + } + #[test] fn bad_conditions_are_refused_and_lists_round_trip() { let cpu = nop_cpu(); diff --git a/src/cpu/smp.rs b/src/cpu/smp.rs index 2047aa5b0..16ba60184 100644 --- a/src/cpu/smp.rs +++ b/src/cpu/smp.rs @@ -33,6 +33,10 @@ pub const MAX_CPUS: usize = 8; /// soft-reset request; Cause only takes bits 8..15. pub const HOST_PARK_BIT: u64 = 1 << 62; +/// Bit of `MipsCore::hot.interrupts` that makes a counting machine's CPU leave its batch and +/// run its timers. Like [`HOST_PARK_BIT`] it stays out of Cause and wakes nothing. +pub(crate) const TIMERS_BIT: u64 = 1 << 61; + /// HEART's MODE register disables this processor. pub const HOLD_HEART: u32 = 1 << 0; /// Another thread needs the machine still ([`World::stop_others`]). diff --git a/src/dev/battery_clock.rs b/src/dev/battery_clock.rs index 830b9746b..b0fe55932 100644 --- a/src/dev/battery_clock.rs +++ b/src/dev/battery_clock.rs @@ -109,20 +109,27 @@ pub fn write(path: &Path, bytes: &[u8]) -> std::io::Result<()> { crate::nv_storage::save(name, bytes) } -/// Host Unix time in whole seconds. +/// Where every clock starts when the machine counts instructions: 2026-01-01T00:00:00Z, so two +/// runs agree whenever they are made. +const COUNTING_EPOCH: i64 = 1_767_225_600; + +/// Host Unix time in whole seconds, or `COUNTING_EPOCH` when the machine counts instructions. pub fn unix_now() -> i64 { + if crate::clock::COUNTING { + return COUNTING_EPOCH; + } SystemTime::now().duration_since(UNIX_EPOCH).unwrap_or_default().as_secs() as i64 } /// Host time in whole seconds since 1970, and a reading of `clock` to count them from: where the -/// host's second began, or 0 while the clock is younger than the subsecond part. Under `ci_clock` -/// there is no host second to align to: it is now. +/// host's second began, or 0 while the clock is younger than the subsecond part. When the machine +/// counts instructions there is no host second to align to: it is `COUNTING_EPOCH` and now. pub fn host_second(clock: &crate::clock::Clock) -> (i64, u64) { + if crate::clock::COUNTING { + return (COUNTING_EPOCH, clock.now()); + } let since = SystemTime::now().duration_since(UNIX_EPOCH).unwrap_or_default(); - #[cfg(not(feature = "ci_clock"))] let at = clock.now().saturating_sub(u64::from(since.subsec_nanos())); - #[cfg(feature = "ci_clock")] - let at = clock.now(); (since.as_secs() as i64, at) } @@ -178,6 +185,17 @@ mod tests { assert_eq!(decode(&m, b"M48TREF1", false), Some(Reference { saved_at: 5, seconds: None })); } + /// Clocks made at different host times read the same date, and `[rtc_offset]` counts from it. + #[cfg(feature = "ci_clock")] + #[test] + fn ci_clock_clocks_start_at_the_fixed_date() { + let first = host_second(&crate::clock::Clock::stepped()).0; + assert_eq!(first, 1_767_225_600, "2026-01-01T00:00:00Z"); + let host = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs() as i64; + assert_ne!(host, first, "the host's date is not the fixed one"); + assert_eq!(unix_now() + seed(&RtcOffset { hours: 2, ..Default::default() }), first + 7200); + } + #[test] fn rtc_offset_seeds_the_clock_within_the_ds1386_years() { assert_eq!(seed(&RtcOffset::default()), 0); diff --git a/src/dev/ds1x86.rs b/src/dev/ds1x86.rs index 86c821e4f..03f6ba52e 100644 --- a/src/dev/ds1x86.rs +++ b/src/dev/ds1x86.rs @@ -586,7 +586,7 @@ mod tests { fn offset_shifts_seeded_time() { let off = RtcOffset { years: -18, days: -3, ..Default::default() }; let rtc = Ds1x86::new(8192, "test_rtc_offset_missing.bin".to_string(), off, Clock::new()); - let host = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs() as i64; + let host = battery_clock::unix_now(); let want = off.apply(host); let d = rtc.data.lock(); let got = rtc.regs_to_centiseconds(&d.regs, 0) as i64 / 100; @@ -636,9 +636,7 @@ mod tests { /// A date the guest sets survives a relaunch, still running, from the /// reference beside the file, and wins over `[rtc_offset]`; the file - /// stays the chip's 8192 bytes. Host time runs the clock here, which a - /// `ci_clock` build does not use. - #[cfg(not(feature = "ci_clock"))] + /// stays the chip's 8192 bytes. #[test] fn a_set_date_survives_a_relaunch() { let path = std::env::temp_dir().join(format!("ds1x86-clock-{}", std::process::id())); @@ -662,7 +660,7 @@ mod tests { assert_eq!(std::fs::metadata(&path).unwrap().len(), 8192); assert_eq!(&std::fs::read(&clock).unwrap()[..8], b"DS138RF1"); let set = 1_086_116_430; - let again = Ds1x86::new(8192, path.clone(), RtcOffset { years: -5, ..Default::default() }, Clock::new()); + let again = Ds1x86::new(8192, path.clone(), RtcOffset { years: -5, ..Default::default() }, Clock::stepped()); assert_eq!(again.read(100).data, 0x5a); let t = now(&again); assert!((set + 3599..=set + 3601).contains(&t), "2004-06-01 20:00:30, got {}", format_unix_utc(t)); @@ -682,7 +680,7 @@ mod tests { let off = RtcOffset { years: -5, ..Default::default() }; let rtc = Ds1x86::new(8192, path.clone(), off, Clock::new()); assert_eq!(rtc.read(100).data, 0x5a); - let host = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs() as i64; + let host = battery_clock::unix_now(); assert!((now(&rtc) - off.apply(host)).abs() <= 2); std::fs::remove_file(&path).ok(); } diff --git a/src/dev/hal2.rs b/src/dev/hal2.rs index 27101ef55..edd821f4b 100644 --- a/src/dev/hal2.rs +++ b/src/dev/hal2.rs @@ -580,7 +580,7 @@ impl Hal2 { let mut timers = self.timers.lock(); if timers[engine].is_some() { return; } let mut pacer = Pacer::new(rate, self.tm.clock()); - timers[engine] = Some(self.tm.add_recurring(Instant::now() + PACE_PERIOD, PACE_PERIOD, move || tick(&mut pacer))); + timers[engine] = Some(self.tm.add_recurring(PACE_PERIOD, PACE_PERIOD, move || tick(&mut pacer))); } fn stop_timer(&self, engine: usize) { diff --git a/src/display/mod.rs b/src/display/mod.rs index 67492c083..36002874d 100644 --- a/src/display/mod.rs +++ b/src/display/mod.rs @@ -465,7 +465,7 @@ impl HeadHandle { /// Now, on the clock [`beam`](Self::beam) takes. pub fn now_ns(&self) -> u64 { - self.refresh.upgrade().map_or(0, |s| (s.clock)()) + self.refresh.upgrade().map_or(0, |s| s.now()) } /// Ask for the next frame in `screen().rgba` and a PNG of it. @@ -486,8 +486,7 @@ impl HeadHandle { /// Run one frame of this head now, on the calling thread, as the refresh /// thread does at a retrace: capture, compose, present, and serve the /// frame and screenshot requests. For tests of a head that is not - /// started. - #[cfg(test)] + /// started, and a counting refresh's requested frame. pub(crate) fn frame_now(&self) { if let Some(head) = self.board() { self.frame_now_as(&*head); @@ -496,7 +495,6 @@ impl HeadHandle { /// As [`frame_now`](Self::frame_now), with `head` standing in for the /// board (a test that composes with its own display object). - #[cfg(test)] pub(crate) fn frame_now_as(&self, head: &dyn Head) { let Some(shared) = self.refresh.upgrade() else { return }; let mut slots = shared.slots.lock(); @@ -510,6 +508,10 @@ impl HeadHandle { pub fn request_frame(&self) { self.frame_request.request(); self.kick(); + // A counting refresh has no retrace while the CPU is stopped: compose the frame here. + if crate::clock::COUNTING && self.refresh.upgrade().is_some_and(|s| s.spawn.is_some() && !s.threaded()) { + self.frame_now(); + } } pub fn frame_pending(&self) -> bool { @@ -637,8 +639,18 @@ impl Refresh { /// Deliver line events ([`Head::line`]) from the machine's timer /// thread, each one's timer scheduling the next, so they keep their /// times while this thread composes. Without it the thread delivers - /// them itself between its other deadlines. + /// them itself between its other deadlines. A counting clock starts no thread: a one-shot + /// steps the schedule from the CPU, every millisecond while no head runs. pub fn set_timers(&self, timers: Arc) { + if timers.clock().is_counting() { + let shared = Arc::downgrade(&self.shared); + timers.add_one_shot(Duration::ZERO, move || { + use crate::hptimer::TimerReturn; + let Some(shared) = shared.upgrade() else { return TimerReturn::Delete }; + let wait = shared.step().map_or(Duration::from_millis(1), |next| Duration::from_nanos(next.saturating_sub(shared.now()))); + TimerReturn::RescheduleOneShot(wait) + }); + } let _ = self.shared.timers.set(timers); } @@ -741,7 +753,20 @@ impl Shared { }) } + /// The refresh's time: the machine clock when it counts instructions, else `clock`. + #[inline(always)] + fn now(&self) -> u64 { + if let Some(t) = self.timers.get().filter(|t| t.clock().is_counting()) { + return t.clock().now(); + } + (self.clock)() + } + fn threaded(&self) -> bool { + // On a counting clock the timers run the schedule, from the CPU. + if self.timers.get().is_some_and(|t| t.clock().is_counting()) { + return false; + } self.spawn.is_some() } @@ -752,6 +777,9 @@ impl Shared { } fn ensure_thread(self: &Arc) { + if !self.threaded() { + return; + } let Some(spawn) = self.spawn else { return }; let mut thread = self.thread.lock(); if thread.is_none() { @@ -769,7 +797,7 @@ impl Shared { while !shared.shutdown.load(Ordering::Acquire) { match shared.step() { Some(next) => { - let now = (shared.clock)(); + let now = shared.now(); if next > now { std::thread::park_timeout(Duration::from_nanos(next - now)); } @@ -840,7 +868,7 @@ impl Slot { (chain.field, chain.start_ns, chain.done) = (field, start_ns, 0); (chain.h_total, chain.pixel_clock_hz) = (self.timing.h_total, self.timing.pixel_clock_hz); let Some(timers) = shared.timers.get() else { return }; - let now = (shared.clock)(); + let now = shared.now(); let Some(at) = chain.run(head, now) else { return }; let (handle, generation) = (Arc::downgrade(handle), chain.generation); chain.timer = Some(timers.add_one_shot(Duration::from_nanos(at - now), move || { @@ -851,7 +879,7 @@ impl Slot { if chain.generation != generation { return TimerReturn::Delete; } - let now = (shared.clock)(); + let now = shared.now(); match chain.run(&*head, now) { Some(at) => TimerReturn::RescheduleOneShot(Duration::from_nanos(at - now)), None => { @@ -912,7 +940,7 @@ impl Slot { self.release(handle); return None; }; - let now = (shared.clock)(); + let now = shared.now(); if !self.armed { self.armed = true; self.in_blank = false; @@ -923,7 +951,7 @@ impl Slot { } loop { - let now = (shared.clock)(); + let now = shared.now(); let fields = self.timing.fields as u64; let field = (self.field % fields) as u32; if !self.in_blank { @@ -957,14 +985,14 @@ impl Slot { head.vblank_start(field, start); // A field that begins late (the last frame overran) has // its lines as late: they keep their place in it. - self.begin_lines(shared, handle, &*head, field, (shared.clock)().max(start)); + self.begin_lines(shared, handle, &*head, field, shared.now().max(start)); handle.retraces.fetch_add(1, Ordering::Relaxed); self.in_blank = true; // The blank lasts its length from when it really began: a // retrace delivered late (the last frame overran) still // gives the guest the whole blank to service it before the // frame is captured. - self.blank_end_ns = (shared.clock)().max(start) + self.timing.blank_ns(); + self.blank_end_ns = shared.now().max(start) + self.timing.blank_ns(); } let end = self.blank_end_ns; if now < end { @@ -981,7 +1009,7 @@ impl Slot { self.frame(shared, handle, &*head); // Back to the thread after a frame, so a head that is slow // to compose does not hold up the others' retraces. - return Some(self.field_time(self.field).min((shared.clock)())); + return Some(self.field_time(self.field).min(shared.now())); } } } @@ -991,7 +1019,7 @@ impl Slot { } fn frame(&mut self, shared: &Shared, h: &HeadHandle, head: &dyn Head) { - let now = (shared.clock)(); + let now = shared.now(); // The requests this frame serves: those made before it began. let (shot, frame_ticket) = (h.screenshot.taken(), h.frame_request.taken()); let readback = Self::readback_wanted(h); diff --git a/src/display/tests.rs b/src/display/tests.rs index 764c9e514..09b59530a 100644 --- a/src/display/tests.rs +++ b/src/display/tests.rs @@ -209,6 +209,51 @@ fn with_timers_a_line_does_not_wait_for_the_thread() { assert!(said("a start0") < said("a line100.0") && said("a line100.0") < said("a line300.0"), "{:?}", log.lock()); } +/// On a clock that counts instructions the schedule has no thread: a retrace and a line come at +/// the machine times the timing gives, when the timers run, and a stop waits for no thread. +#[cfg(feature = "ci_clock")] +#[test] +fn ci_clock_a_counting_refresh_runs_from_the_machine_clock_without_a_thread() { + let (tm, step) = crate::test_board::counting(); + let refresh = Refresh::new(); + refresh.set_timers(tm); + let log = Log::default(); + let head = TestHead::new("a", &log); + let as_head: Arc = head.clone(); + let handle = refresh.add_head(Arc::downgrade(&as_head), MachineStatus::detached()); + // Line 100 of 1066 is 1.6 ms into the field. + handle.set_line_events(&[100]); + handle.start(); + assert!(refresh.shared.thread.lock().is_none(), "no refresh thread"); + step(0); + step(HZ60_NS - MS); + assert!(log.lock().is_empty(), "nothing before the first retrace: {:?}", log.lock()); + step(2 * MS); + assert_eq!(log.lock()[0], "a start0"); + assert!(!log.lock().iter().any(|l| l == "a line100.0")); + step(2 * MS); + assert!(log.lock().iter().any(|l| l == "a line100.0"), "{:?}", log.lock()); + handle.stop(); +} + +/// With the machine clock held, a requested frame is composed at once and no retrace is raised. +#[cfg(feature = "ci_clock")] +#[test] +fn ci_clock_a_counting_refresh_composes_a_requested_frame_with_the_clock_held() { + let (tm, _step) = crate::test_board::counting(); + let refresh = Refresh::new(); + refresh.set_timers(tm); + let log = Log::default(); + let head = TestHead::new("a", &log); + let as_head: Arc = head.clone(); + let handle = refresh.add_head(Arc::downgrade(&as_head), MachineStatus::detached()); + handle.start(); + handle.request_frame(); + assert!(!handle.frame_pending(), "{:?}", log.lock()); + assert_eq!(head.composes.load(Ordering::SeqCst), 1); + assert!(!log.lock().iter().any(|l| l.contains("start")), "no retrace: {:?}", log.lock()); +} + #[test] fn the_blank_lasts_its_lines() { let rig = Rig::new(); diff --git a/src/hptimer.rs b/src/hptimer.rs index 0f525ca8b..ede7779b7 100644 --- a/src/hptimer.rs +++ b/src/hptimer.rs @@ -52,6 +52,10 @@ struct TimerManagerInner { stop: bool, /// Wakes the worker out of its wait (`Waiter`), once the worker has made one. waker: Option, + /// A counting manager's CPU interrupt word, where an armed timer asks that CPU to run it. + /// Read and cleared under this lock, so it is never used after the CPU is gone. + #[cfg(feature = "ci_clock")] + interrupts: Option, } impl TimerManagerInner { @@ -120,6 +124,8 @@ impl TimerManager { fifo: VecDeque::new(), stop: false, waker: None, + #[cfg(feature = "ci_clock")] + interrupts: None, })); let new_timer_added = Arc::new(AtomicBool::new(false)); @@ -127,18 +133,19 @@ impl TimerManager { let thread_inner = inner.clone(); let thread_added = new_timer_added.clone(); - let thread_handle = thread::Builder::new().name("hptimer".into()).spawn(move || { + // A counting clock's timers run on its CPU (`run_expired`), so it needs no thread. + let thread_handle = (!clock.is_counting()).then(|| thread::Builder::new().name("hptimer".into()).spawn(move || { let waiter = Waiter::new(); { let mut guard = thread_inner.lock(); guard.waker = Some(waiter.waker()); } - timer_thread_loop(thread_inner, thread_added, &waiter); - }).expect("spawn hptimer thread"); + timer_thread_loop(&thread_inner, &thread_added, Some(&waiter), Instant::now); + }).expect("spawn hptimer thread")); Self { inner, - thread_handle: Some(thread_handle), + thread_handle, new_timer_added, clock, #[cfg(test)] @@ -148,6 +155,34 @@ impl TimerManager { } } + /// Where deadlines count from: now in host time, or in machine time on a counting manager. + fn deadline_base(&self) -> Instant { + if self.clock.is_counting() { + return epoch() + Duration::from_nanos(self.clock.now()); + } + Instant::now() + } + + /// Where a counting manager's CPU asks to have its timers run: `word` is that CPU's interrupt + /// word, or null when the CPU goes. + pub fn set_interrupts(&self, word: *const AtomicU64) { + #[cfg(feature = "ci_clock")] + { + self.inner.lock().interrupts = (self.clock.is_counting() && !word.is_null()) + .then(|| crate::cpu::mips_core::TimerIrqPtr(word)); + } + #[cfg(not(feature = "ci_clock"))] + let _ = word; + } + + /// One pass of the timer thread's loop, on this thread: run every timer the clock has reached, + /// then return the next deadline in machine nanoseconds. For a counting manager's CPU. + #[cfg_attr(not(feature = "ci_clock"), allow(dead_code))] + pub(crate) fn run_expired(&self) -> Option { + timer_thread_loop(&self.inner, &self.new_timer_added, None, || self.deadline_base()) + .map(|t| t.saturating_duration_since(epoch()).as_nanos() as u64) + } + /// Run the callback of every started timer the clock has reached, oldest deadline first and /// on this thread, until none is left: what the host timer does, without waiting for it. #[cfg(test)] @@ -192,7 +227,7 @@ impl TimerManager { { let mut inner = self.inner.lock(); let id = inner.allocate(TimerEntry { - next_expiration: Instant::now() + expire_in, + next_expiration: self.deadline_base() + expire_in, period: None, in_fifo: false, callback: Some(Box::new(cb)), @@ -202,14 +237,14 @@ impl TimerManager { id } - /// Add a recurring timer to the manager. - pub fn add_recurring(&self, expire_at: Instant, period: Duration, cb: F) -> TimerId + /// Add a recurring timer to the manager, first due `expire_in` from now. + pub fn add_recurring(&self, expire_in: Duration, period: Duration, cb: F) -> TimerId where F: FnMut() -> TimerReturn + Send + 'static, { let mut inner = self.inner.lock(); let id = inner.allocate(TimerEntry { - next_expiration: expire_at, + next_expiration: self.deadline_base() + expire_in, period: Some(period), in_fifo: false, callback: Some(Box::new(cb)), @@ -228,6 +263,13 @@ impl TimerManager { fn wake_up(&self) { self.new_timer_added.store(true, Ordering::Release); let inner = self.inner.lock(); + // No thread to wake: ask the CPU to leave its batch and run the timers. + #[cfg(feature = "ci_clock")] + if let Some(word) = &inner.interrupts { + // SAFETY: the CPU clears the pointer, under this lock, before its word goes. + unsafe { &*word.0 }.fetch_or(crate::cpu::smp::TIMERS_BIT, Ordering::SeqCst); + return; + } if let Some(w) = &inner.waker { w.wake(); } @@ -414,10 +456,22 @@ impl Drop for TimerInner { } } -/// The core loop tracking timeouts precisely. -fn timer_thread_loop(inner: Arc>, new_timer_added: Arc, waiter: &Waiter) { +/// Where machine time 0 falls on the `Instant` line: a counting manager keeps its deadlines there. +fn epoch() -> Instant { + static EPOCH: std::sync::OnceLock = std::sync::OnceLock::new(); + *EPOCH.get_or_init(Instant::now) +} + +/// The core loop tracking timeouts precisely, in the time `time` reads. With no `waiter` it runs +/// what is due and returns the next deadline instead of waiting for it. +fn timer_thread_loop( + inner: &Mutex, + new_timer_added: &AtomicBool, + waiter: Option<&Waiter>, + time: impl Fn() -> Instant, +) -> Option { loop { - let now = Instant::now(); + let now = time(); let mut next_wakeup = None; let mut to_call = None; @@ -497,7 +551,7 @@ fn timer_thread_loop(inner: Arc>, new_timer_added: Arc< TimerReturn::Continue => { if let Some(period) = period { t.next_expiration += period; - let now = Instant::now(); + let now = time(); if catch_up + 1 < MAX_CATCHUP && t.next_expiration <= now { @@ -515,7 +569,7 @@ fn timer_thread_loop(inner: Arc>, new_timer_added: Arc< guard.deallocate(((generation as u64) << 32) | (idx as u64)); } TimerReturn::RescheduleOneShot(new_delay) => { - t.next_expiration = Instant::now() + new_delay; + t.next_expiration = time() + new_delay; t.period = None; } } @@ -526,6 +580,7 @@ fn timer_thread_loop(inner: Arc>, new_timer_added: Arc< continue; // Re-evaluate time continuously } + let Some(waiter) = waiter else { return next_wakeup }; // 5. Spin or park depending on how long we have to wait if let Some(target) = next_wakeup { loop { @@ -569,6 +624,7 @@ fn timer_thread_loop(inner: Arc>, new_timer_added: Arc< } } } + None } /// The longest the worker spins to land a deadline that falls between two diff --git a/src/hptimer_tests.rs b/src/hptimer_tests.rs index 328048a2b..6f7e5a470 100644 --- a/src/hptimer_tests.rs +++ b/src/hptimer_tests.rs @@ -28,7 +28,7 @@ fn test_precision_one_shot_and_recurring() { let r_count = recurring_count.clone(); manager.add_recurring( - start + Duration::from_millis(20), + Duration::from_millis(20), Duration::from_millis(20), move || { let c = r_count.fetch_add(1, Ordering::SeqCst) + 1; @@ -94,7 +94,7 @@ fn test_extended_callback_recovery() { // A fast recurring timer every 10ms let str = short_timer_runs.clone(); manager.add_recurring( - start + Duration::from_millis(10), + Duration::from_millis(10), Duration::from_millis(10), move || { str.fetch_add(1, Ordering::SeqCst); @@ -223,7 +223,7 @@ fn recurring_timer_at_1khz_keeps_its_rate() { let period = Duration::from_millis(1); let (f, l) = (fired.clone(), late_ns.clone()); let mut n = 0u32; - manager.add_recurring(start + period, period, move || { + manager.add_recurring(period, period, move || { n += 1; f.fetch_add(1, Ordering::SeqCst); let due = start + period * n; diff --git a/src/ip32_machine.rs b/src/ip32_machine.rs index 04fa261e3..bcd1c6c35 100644 --- a/src/ip32_machine.rs +++ b/src/ip32_machine.rs @@ -42,6 +42,8 @@ use crate::traits::{BusDevice, Device, MachineEvent, Signal}; use crate::workstation::{MachineRef, MachineSlot, Workstation}; const PROM_VA: std::ops::Range = 0xbfc0_0000..0xbfc8_0000; +/// How often the service thread, or on a counting clock a timer, looks after the devices while CRIME is interrupting. +const SERVICE_POLL: Duration = Duration::from_micros(100); /// Whether `pc` is in the firmware the PROM copies into RAM, at its KSEG0 /// address or its KSEG1 alias (0xa100_0000, uncached): it runs from both. @@ -201,8 +203,19 @@ impl O2Machine { rtc_file: Some(format!("{}.rtc", cfg.nvram).into()), rtc_offset: cfg.rtc_offset, }; - let timer_manager = Arc::new(TimerManager::new()); + let timer_manager = Arc::new(TimerManager::with_clock(crate::clock::Clock::cpu_or_host())); let bus = Ip32Bus::with_options(mem, prom, opts, &timer_manager); + // On a counting clock the service pass runs from the timers, on the CPU's instructions. + if timer_manager.clock().is_counting() { + use crate::hptimer::TimerReturn; + let bus = Arc::downgrade(&bus); + timer_manager.add_recurring(SERVICE_POLL, SERVICE_POLL, move || { + bus.upgrade().map_or(TimerReturn::Delete, |b| { + b.service(); + TimerReturn::Continue + }) + }); + } // MACE audio plays through the host unless audio is off. if !cfg.no_audio { bus.mace.audio.enable_output(cfg.audio()); @@ -297,6 +310,8 @@ impl O2Machine { let status = crate::status::MachineStatus::new(bus.mace.id.heartbeat.clone(), cpu.fasttick_count()); status.set_scsi_wide(true); status.set_cpu_cycles(cpu.cycles_ptr()); + timer_manager.clock().set_cpu_cycles(cpu.cycles_ptr()); + timer_manager.set_interrupts(cpu.interrupts_ptr()); status.set_count_hz(cpu.count_hz_atomic()); // The O2's clock is CP0 Compare: publish the rate it programs. cpu.publish_tick_rate(status.cpu(0).tick_rate()); @@ -478,7 +493,6 @@ impl O2Machine { // asynchronous input (a typed key, a frame from the network) — // and while any of that is flowing, its interrupts keep the poll // at 100 µs anyway. - const SERVICE_POLL: Duration = Duration::from_micros(100); const SERVICE_POLL_IDLE: Duration = Duration::from_millis(2); let mut poll = SERVICE_POLL; while running.load(Ordering::Relaxed) { @@ -495,8 +509,9 @@ impl O2Machine { } } // Frames from the network, and any line that changed without a - // register access (a disk finishing, a key from the window). - let interrupting = bus.service(); + // register access (a disk finishing, a key from the window). A timer does this + // pass on a counting clock. + let interrupting = !crate::clock::COUNTING && bus.service(); poll = if interrupting { SERVICE_POLL } else { (poll * 2).min(SERVICE_POLL_IDLE) }; @@ -639,6 +654,8 @@ impl Drop for O2Machine { self.cpu.clone().as_device().stop(); #[cfg(feature = "jitv2")] crate::cpu::jitv2::Jitv2::stop_for_drop(&self.cpu.jitv2(), || self.cpu.clone().as_device().stop()); + // The clock reads the CPU's cycle counter, which goes with the core. + self.timer_manager.clock().stop(); // The refresh thread lets go of the renderer here (`DisplayStop`). self.display.head.stop(); self.running.store(false, Ordering::SeqCst); diff --git a/src/machine.rs b/src/machine.rs index 248cc1660..d22b086a2 100644 --- a/src/machine.rs +++ b/src/machine.rs @@ -274,10 +274,7 @@ impl Machine { eeprom_mc.lock().set_cachsz(0); } - #[cfg(feature = "ci_clock")] - let timer_manager = Arc::new(TimerManager::with_clock(crate::clock::Clock::counting())); - #[cfg(not(feature = "ci_clock"))] - let timer_manager = Arc::new(TimerManager::new()); + let timer_manager = Arc::new(TimerManager::with_clock(crate::clock::Clock::cpu_or_host())); // 1. Create all devices first // Memory Controller let mc_banks: [u32; 4] = cfg.banks[..4].try_into().expect("the MC has four banks"); @@ -323,6 +320,10 @@ impl Machine { // What every graphics board's status bar reads; the CPU feeds its // fetch counters and the cycle counter is wired in below. let status = crate::status::MachineStatus::new(heartbeat.clone(), fasttick_count.clone()); + // On a counting clock the refresh runs on the machine's instructions, not on its own thread. + if timer_manager.clock().is_counting() { + status.refresh().set_timers(timer_manager.clone()); + } let [decoded_count, l1i_hit_count, l1i_fetch_count, uncached_fetch_count] = status.fetch_counters(); let (fatal_tx, fatal_rx) = mpsc::channel::(); @@ -770,6 +771,7 @@ impl Machine { let cpu_device: Arc = cpu.clone().as_device(); mc.set_cpu(Arc::downgrade(&cpu_device)); ioc.set_interrupts(cpu.interrupts_ptr()); + timer_manager.set_interrupts(cpu.interrupts_ptr()); // ppmem: the CPU's cache and the JIT read RAM through a cached view of // the window that is the CPU's own, so what the cache holds stays out @@ -817,7 +819,6 @@ impl Machine { } } hpc3.scsi().set_cpu_cycles(cpu.cycles_ptr()); - #[cfg(feature = "ci_clock")] timer_manager.clock().set_cpu_cycles(cpu.cycles_ptr()); // Inject the CPU/self handles jitv2's compile-thread worker needs to diff --git a/src/test_board.rs b/src/test_board.rs index 54e20d45b..36f0fd664 100644 --- a/src/test_board.rs +++ b/src/test_board.rs @@ -66,6 +66,22 @@ impl Stepped { } } +/// A timer manager on a clock that counts instructions, and a step that moves the count on +/// `ns` and runs the due timers, as the CPU does between batches. +#[cfg(feature = "ci_clock")] +pub(crate) fn counting() -> (Arc, impl Fn(u64)) { + // The step closure owns the counter, so keep it for as long as the manager is read. + let cycles = Arc::new(std::sync::atomic::AtomicU64::default()); + let clock = Clock::counting(); + clock.set_cpu_cycles(crate::cpu::mips_core::CyclesPtr::new(cycles.as_ptr())); + let tm = Arc::new(TimerManager::with_clock(clock)); + let t = tm.clone(); + (tm, move |ns| { + cycles.fetch_add(ns / crate::cpu::mips_core::NS_PER_GUEST_CYCLE, std::sync::atomic::Ordering::SeqCst); + t.run_expired(); + }) +} + impl Deref for Stepped { type Target = Clock; fn deref(&self) -> &Clock { diff --git a/src/ui.rs b/src/ui.rs index 6bb99a4b7..63138dadb 100644 --- a/src/ui.rs +++ b/src/ui.rs @@ -1303,7 +1303,7 @@ impl Ui { let ps2 = ps2.clone(); let delta = mouse_delta.clone(); timer_manager.add_recurring( - Instant::now() + Duration::from_millis(10), + Duration::from_millis(10), Duration::from_millis(10), move || { Self::flush_mouse_delta(&ps2, &delta, true); From d46c99c818b8f6e5eea0338ade43dda1643ceadb Mon Sep 17 00:00:00 2001 From: James Braid Date: Mon, 30 Nov 2026 04:44:52 -0700 Subject: [PATCH 3/5] hpc3: time the read-ahead window on the machine clock A SCSI channel caps how far the disk may read ahead of the CPU's last look at CBP, and forgets the look after 50 ms. That window was host time, so it kept running while the machine was stopped in the monitor or a debugger, and a guest that polled CBP just before a stop found the cap gone on resume. It now reads the machine clock, which holds still while the machine is stopped, and the window is exactly 50 ms of what the guest saw. It also removes a host-time read from the path a counting clock must keep out of, which the instruction-driven clock needs. A CBP poll now calls Clock::now() where it called Instant::now(); both are a few atomic loads and a clock read, and neither is per instruction. Each channel takes the clock at construction. Production lines: +9 -9 --- src/dev/hpc3.rs | 36 +++++++++++++++++++++++++----------- 1 file changed, 25 insertions(+), 11 deletions(-) diff --git a/src/dev/hpc3.rs b/src/dev/hpc3.rs index c7c0102ad..c1514c682 100644 --- a/src/dev/hpc3.rs +++ b/src/dev/hpc3.rs @@ -391,7 +391,8 @@ struct PdmaChannel { cbp_log_t0: Option, /// Device reads when the guest last read CBP, and when. reads_at_poll: u64, - last_poll: Option, + last_poll: Option, + clock: crate::clock::Clock, cbp: u32, nbdp: u32, bc: u32, @@ -435,7 +436,7 @@ struct PdmaChannel { } impl PdmaChannel { - fn new(id: usize, dump_enabled: Arc) -> Self { + fn new(id: usize, dump_enabled: Arc, clock: crate::clock::Clock) -> Self { Self { id, armed: Arc::new(ArmSignal::default()), @@ -461,6 +462,7 @@ impl PdmaChannel { cbp_log_t0: None, reads_at_poll: 0, last_poll: None, + clock, width_16: false, crbdp: 0, cpfxbdp: 0, ppfxbdp: 0, tx_new_packet: true, rx_filled: std::collections::VecDeque::new(), last_rx_ctrl: 0xFFFFFFFF, } @@ -890,11 +892,9 @@ impl DmaClient for PdmaClientImpl { fn read_ahead_of_poll(&self) -> Option { let c = self.channel.lock(); // A guest that has not read CBP for a while is not steering by it. - match c.last_poll { - Some(t) if t.elapsed() < std::time::Duration::from_millis(50) => - Some(c.dev_reads.saturating_sub(c.reads_at_poll)), - _ => None, - } + const WINDOW_NS: u64 = 50_000_000; + let recent = c.last_poll.is_some_and(|t| c.clock.now().saturating_sub(t) < WINDOW_NS); + recent.then(|| c.dev_reads.saturating_sub(c.reads_at_poll)) } fn write(&self, val: u32, eop: bool) -> DmaStatus { self.channel.lock().dma_write(val, eop) @@ -945,7 +945,7 @@ impl PdmaChannelOps for PbusDmaOps { HPC3_PDMA_CBP => { chan.cbp_polls += 1; chan.reads_at_poll = chan.dev_reads; - chan.last_poll = Some(std::time::Instant::now()); + chan.last_poll = Some(chan.clock.now()); let t0 = *chan.cbp_log_t0.get_or_insert_with(std::time::Instant::now); if chan.cbp_log.len() == 64 { chan.cbp_log.pop_front(); } let entry = (t0.elapsed().as_micros() as u64, chan.cbp, chan.dev_reads * 4); @@ -1329,7 +1329,7 @@ impl Hpc3 { let mut pdma_ops: Vec> = Vec::new(); let mut dma_clients: Vec> = Vec::new(); for i in 0..12 { - let mut chan = PdmaChannel::new(i, pdma_dump.clone()); + let mut chan = PdmaChannel::new(i, pdma_dump.clone(), tm.clock().clone()); if i == HPC3_PDMA_CHAN_SCSI0 as usize || i == HPC3_PDMA_CHAN_SCSI1 as usize { chan.active_mask = SCSI_CTRL_ACTIVE; // 0x10 for SCSI } else if i == HPC3_PDMA_CHAN_ENET_RX as usize || i == HPC3_PDMA_CHAN_ENET_TX as usize { @@ -2490,6 +2490,20 @@ impl Saveable for Hpc3 { mod tests { use super::*; + /// The read-ahead cap's 50 ms window is machine time: host time neither ends it nor keeps it open. + #[test] + fn the_dma_read_ahead_window_is_machine_time() { + let clock = crate::clock::Clock::stepped(); + let channel = Arc::new(Mutex::new(PdmaChannel::new(0, Arc::new(AtomicU32::new(0)), clock.clone()))); + let client = PdmaClientImpl::new(channel.clone()); + assert_eq!(client.read_ahead_of_poll(), None, "never polled"); + channel.lock().last_poll = Some(clock.now()); + std::thread::sleep(std::time::Duration::from_millis(60)); + assert!(client.read_ahead_of_poll().is_some(), "host time does not end the window"); + clock.step(51_000_000); + assert_eq!(client.read_ahead_of_poll(), None); + } + /// INTSTAT as a controller: each SCSI channel's chip and DMA bits are /// ORed onto its IOC line; a chip-INT ack also settles the paired PDMA /// half; the SEEQ's level goes to Ethernet as it is. @@ -2501,8 +2515,8 @@ mod tests { let (en, en_line) = LevelProbe::line(); let dump = Arc::new(AtomicU32::new(0)); let chans = [ - Arc::new(Mutex::new(PdmaChannel::new(8, dump.clone()))), - Arc::new(Mutex::new(PdmaChannel::new(9, dump))), + Arc::new(Mutex::new(PdmaChannel::new(8, dump.clone(), crate::clock::Clock::new()))), + Arc::new(Mutex::new(PdmaChannel::new(9, dump, crate::clock::Clock::new()))), ]; let state = Arc::new(Mutex::new(Hpc3State { intstat: 0, gio_misc: 0, eeprom_reg: 0, pbus_pio: [0; 0x1000] })); let irqs = Arc::new(Hpc3Interrupts { From 0c84f6982bc0862c6c81239d6c75f5cca4784ff6 Mon Sep 17 00:00:00 2001 From: James Braid Date: Mon, 30 Nov 2026 04:45:06 -0700 Subject: [PATCH 4/5] rex3: time BACKBUSY on the display head's clock A DCB address-12 command holds STATUS.BACKBUSY up for 1 ms, which was 1 ms of host time. A machine stopped in the monitor, or a guest that ran slower than the host, then saw BACKBUSY end at a different point of its own execution each time. It now lasts 1 ms of the head's clock, which is machine time, so a run reads the same STATUS however long the host took. The instruction-driven clock needs this for repeatable runs. BACKBUSY was never cleared when it ran out, so once any DCB command had set it every later STATUS read compared against it. That read is now a weak upgrade and a boxed clock call, not an Instant::now(), so the read drops the deadline as soon as it has passed and the cost is paid only inside the 1 ms window after a command. Production lines: +10 -6 --- src/dev/ng1/rex3.rs | 16 +++++++++------ src/dev/ng1/rex3_tests.rs | 41 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 51 insertions(+), 6 deletions(-) diff --git a/src/dev/ng1/rex3.rs b/src/dev/ng1/rex3.rs index 75b1c5629..4d0ccd4d4 100644 --- a/src/dev/ng1/rex3.rs +++ b/src/dev/ng1/rex3.rs @@ -1278,13 +1278,17 @@ impl Default for Rex3Config { } } +/// How long a DCB command holds BACKBUSY up, in nanoseconds of the head's clock. +const BACKBUSY_NS: u64 = 1_000_000; + #[derive(Debug)] pub struct Rex3DcbState { pub dcbmode: u32, pub dcbdata0: u32, pub dcbdata1: u32, - /// Set by DCB addr=12 write/read. Read during STATUS read (CPU thread only — same thread as DCB). - pub backbusy_until: Option, + /// Set by DCB addr=12 write/read, as `head.now_ns()` plus `BACKBUSY_NS`; a STATUS read clears + /// it once passed (CPU thread only — same thread as DCB). + pub backbusy_until: Option, } impl Rex3DcbState { @@ -2858,7 +2862,7 @@ impl Rex3 { } } 12 => { - dcb.backbusy_until = Some(std::time::Instant::now() + std::time::Duration::from_millis(1)); + dcb.backbusy_until = Some(self.head.now_ns() + BACKBUSY_NS); drop(dcb); self.diag.fetch_and(!Self::DIAG_LOCK_DCB, Ordering::Relaxed); return; @@ -2933,7 +2937,7 @@ impl Rex3 { } } 12 => { - dcb.backbusy_until = Some(std::time::Instant::now() + std::time::Duration::from_millis(1)); + dcb.backbusy_until = Some(self.head.now_ns() + BACKBUSY_NS); drop(dcb); self.diag.fetch_and(!Self::DIAG_LOCK_DCB, Ordering::Relaxed); return 0; @@ -4973,9 +4977,9 @@ impl Rex3 { let irq = self.fifo_full_cb.lock().clone(); if let Some(irq) = irq { irq.set(false); } } - let dcb = self.dcb.lock(); + let mut dcb = self.dcb.lock(); if let Some(until) = dcb.backbusy_until { - if std::time::Instant::now() < until { val |= STATUS_BACKBUSY; } + if self.head.now_ns() < until { val |= STATUS_BACKBUSY; } else { dcb.backbusy_until = None; } } } BusRead32::ok(val & 0xFFFFF) diff --git a/src/dev/ng1/rex3_tests.rs b/src/dev/ng1/rex3_tests.rs index d71e02cad..5927b65d7 100644 --- a/src/dev/ng1/rex3_tests.rs +++ b/src/dev/ng1/rex3_tests.rs @@ -9830,6 +9830,47 @@ fn legacy_gfifo_register_traffic_marks_framebuffer_dirty() { assert!(rex.fb_dirty.swap(false, Ordering::Acquire)); } +/// Once the 1 ms has passed a STATUS read drops the deadline, so later reads never ask the head +/// for the time. +#[test] +fn a_status_read_after_backbusy_ends_drops_the_deadline() { + let rex = &make_rex3_reset(); + w32(rex, set_addr(REX3_DCBMODE), 12 << DCBMODE_DCBADDR_SHIFT); + w32(rex, set_addr(REX3_DCBDATA0), 0); + assert!(rex.dcb.lock().backbusy_until.is_some(), "the command armed BACKBUSY"); + std::thread::sleep(std::time::Duration::from_millis(20)); + let status = rex.read32(set_addr(REX3_STATUS)).data; + assert_eq!(status & STATUS_BACKBUSY, 0); + assert!(rex.dcb.lock().backbusy_until.is_none()); +} + +/// A DCB command raises BACKBUSY for 1 ms of machine time, not host time: a run reads the same +/// STATUS however long the host took. +#[cfg(feature = "ci_clock")] +#[test] +fn ci_clock_backbusy_lasts_a_millisecond_of_machine_time() { + let (tm, step) = crate::test_board::counting(); + let status = crate::status::MachineStatus::detached(); + status.refresh().set_timers(tm); + let rex = &with_big_stack(move || { + let rex = TestBoard::new(Arc::new(Rex3::new(status))); + rex.power_on(); + rex + }); + // DCB address 12 raises BACKBUSY. + w32(rex, set_addr(REX3_DCBMODE), 12 << DCBMODE_DCBADDR_SHIFT); + w32(rex, set_addr(REX3_DCBDATA0), 0); + assert!(rex.dcb.lock().backbusy_until.is_some(), "the command armed BACKBUSY"); + let busy = |rex: &Rex3| rex.read32(set_addr(REX3_STATUS)).data & STATUS_BACKBUSY != 0; + assert!(busy(rex)); + std::thread::sleep(std::time::Duration::from_millis(5)); + assert!(busy(rex), "host time does not end it"); + step(999_000); + assert!(busy(rex)); + step(2_000); + assert!(!busy(rex), "a millisecond of machine time ended it"); +} + /// The emulated GFIFO is 65536 entries deep (65535 live), not the hardware's /// 32, and STATUS reports only the last 32 slots of it. /// From d50bc691e4d38588092618d70e5e3e4a4d10984d Mon Sep 17 00:00:00 2001 From: James Braid Date: Mon, 30 Nov 2026 05:11:53 -0700 Subject: [PATCH 5/5] dev: run the device engines inline when the clock counts The MC's DMA engine, REX3's GFIFO processor, CRIME's rendering engine, the AIC-7880 and the WD33C93A each ran on a thread of their own. When such a thread finishes a transfer, or what a status read sees of it, depends on the host's scheduler, so two runs of one PROM diverged even with the timers already on CPU 0's instructions. Where the build counts instructions the five now run in the access that wakes them: no worker, and a kick runs the loop until nothing is left, as the AIC-7880 already does when it has no worker. REX3 and CRIME do so once started, and queue as before until then. They read clock::COUNTING, which is a constant false in a default build. The MC leaves RUN latched for one read after a trigger, because the Indy PROM wants it set on its first look and clear on its second. The machine constructors assert that a counting build gives these engines a counting manager. The WD33C93A cannot wait for its HPC3 channel inline. A driver that writes TRANSFER_INFO before it arms the channel used to be waited for up to 100 ms of host time, but inline the waiter is the CPU that would arm it. A counting chip skips the wait and takes the pause path it already has, which keeps the data and raises the unexpected-phase interrupt at once. A one-byte transfer pauses the same way instead of retrying. IRIX and the PROM arm first, so neither is affected. The chip's deferred status interrupt, which the worker raised after spinning 10000 cycles, is raised with the command, as --no-scsi-deferred-int does. The status reads of REX3 and CRIME report an engine that has finished, which an inline engine always has. A test runs the Indy's built-in PROM for 40 ms of machine time twice and compares the registers, Count, console log and NVRAM. It sets the JIT's compile mode to sync, as any run that compares runs must: compiled code sees a deadline only at its cycle flushes, so which regions are compiled by when decides where a timer lands. The Ethernet is not covered. The SEEQ's thread and the host network backend run on host time, so a run whose guest sends or receives packets can still differ; the PROM sends none in this window. In a default build this changes nothing but dead COUNTING branches. Production lines: +83 -12 --- .cargo/config.toml | 3 +- CHANGELOG.md | 19 ++++++++++ FEATURES.md | 2 +- src/dev/aic7880.rs | 6 +++- src/dev/mc.rs | 13 ++++++- src/dev/mc_vdma.rs | 34 ++++++++++++++++++ src/dev/ng1/rex3.rs | 24 ++++++++++--- src/dev/ng1/rex3_tests.rs | 13 +++++++ src/dev/o2gfx.rs | 38 ++++++++++++++++++-- src/dev/wd33c93a.rs | 74 +++++++++++++++++++++++++++++++++++++-- src/display_stop_tests.rs | 2 ++ src/ip32_machine.rs | 2 ++ src/machine.rs | 55 +++++++++++++++++++++++++++++ 13 files changed, 271 insertions(+), 14 deletions(-) diff --git a/.cargo/config.toml b/.cargo/config.toml index 2c4e44a33..b1592ba2f 100644 --- a/.cargo/config.toml +++ b/.cargo/config.toml @@ -7,7 +7,8 @@ ci-test = "ci-nextest --profile ci" # The default features alone: the only run of the real-cache path that tcache # (implied by jitv2) compiles out. ci-test-default = "nextest run --workspace --profile ci" -# The nightly instruction-driven clock tests, which need their own build. +# The nightly instruction-driven clock tests, which need their own build. It also builds jitv2, +# whose compiles are async by default: a test that compares runs sets `jitv2.compile` to Sync. ci-clock = "ci-nextest --profile ci-clock --features ci_clock,idle-pause" # The loom concurrency models, built under --cfg loom. A flag, not RUSTFLAGS, so # no environment is needed; cargo keeps the loom build beside the normal one in diff --git a/CHANGELOG.md b/CHANGELOG.md index b6265829d..a52635916 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,25 @@ hashes are given where a change is easiest to understand by reading the commit. ## November 2026 +### Repeatable runs with `ci_clock` + +- On the Indy and the O2, a `ci_clock` build now runs the timers, the display + refresh and the device engines (MC DMA, REX3, CRIME's engine, both SCSI + controllers) on CPU 0's instructions, so two runs of one PROM that use no + network give the same registers, Count, serial output and NVRAM. Every + battery clock starts at 2026-01-01. +- The Ethernet is not covered: its thread and the host network backend still + run on host time, so a run whose guest sends or receives packets can differ. +- A build with the CPU JIT needs `--jitv2-compile sync` for this; compiles + that finish at host-chosen moments move where a timer lands. +- Sound follows machine time there, so a chime takes about ten times the + guest instructions it does on host time: `chime_tests` is slow under + `ci_clock` (about 110 s for the O2's in a dev build, against 9 s). +- A driver that starts an HPC3 SCSI transfer before it arms the channel (the + BSD manual flow) is paused at once under `ci_clock`, not after 100 ms. +- In every build, HAL2's read-ahead window and REX3's BACKBUSY count machine + time, so they hold still while the machine is stopped. + ### Front ends - A native Windows front end, `iris-win32`, over the same controllers as the diff --git a/FEATURES.md b/FEATURES.md index f38925e52..aa1d3b78f 100644 --- a/FEATURES.md +++ b/FEATURES.md @@ -22,7 +22,7 @@ Select with `cargo build --release --features `; add | `perfetto` | Perfetto trace recording (`--perfetto FILE`, monitor `perfetto`); see [docs/perfetto.md](docs/perfetto.md). Lightning-compatible. | — | | `rexdiag` | REX3 per-GO activity and dispatch counters. Default on; removable in a core build. | — | | `fetchverify` | Compare executed instruction bytes with memory in interpreter/JIT; expensive stale-code detector. | — | -| `ci_clock` | Synthetic deterministic Count clock for CI/snapshot validation; replaces real-time Count timing. Also times the Indy's DS1386 and 8254 on the cycle count, starts every battery clock at 2026-01-01T00:00:00Z, and on the Indy and the O2 runs the timers and the display's retrace on CPU 0's instructions: two runs of one PROM are byte-identical. Not repeatable with `idle-pause` (which it turns off on those machines), after a CPU hard reset, which sets the clock back, or on the O2's CRIME cold reset and power-off, which the service thread still performs at a host-chosen instruction. | — | +| `ci_clock` | Synthetic deterministic Count clock for CI/snapshot validation; replaces real-time Count timing. Also times the Indy's DS1386 and 8254 on the cycle count, starts every battery clock at 2026-01-01T00:00:00Z, and on the Indy and the O2 runs the timers, the device engines and the display's retrace on CPU 0's instructions: two runs of one PROM that use no network agree on registers, Count, serial output and NVRAM (with `--jitv2-compile sync` when the CPU JIT is built). The Ethernet's thread and the host network backend still run on host time. A driver that arms an HPC3 SCSI channel only after it has started a transfer sees the chip's pause interrupt at once instead of after a 100 ms wait. Not repeatable with `idle-pause` (which it turns off on those machines), after a CPU hard reset, which sets the clock back, or on the O2's CRIME cold reset and power-off, which the service thread still performs at a host-chosen instruction. | — | | `opcodefusion` | Interpreter instruction fusion; breakpoints on a fused second instruction cannot fire. | — | | `lightning` | Strip breakpoints/traceback for speed; hides GUI Debug controls. | `opcodefusion` | | `tlbvmap` | O(1) TLB fast path (the vmap); without it lookups use the MRU scan. On by default. | — | diff --git a/src/dev/aic7880.rs b/src/dev/aic7880.rs index ae4d0144f..36ea711c7 100644 --- a/src/dev/aic7880.rs +++ b/src/dev/aic7880.rs @@ -714,6 +714,10 @@ impl crate::traits::Device for Aic7880 { if self.running.swap(true, Ordering::AcqRel) { return; } + // A counting clock has no worker: `kick` does the work in the access that raised it. + if crate::clock::COUNTING { + return; + } let me = self.me.clone(); *worker = Some( std::thread::Builder::new() @@ -1339,7 +1343,7 @@ impl Aic7880 { /// Tell the sequencer there may be work: wake the worker, or, with no /// worker running (unit tests, the harness), do the work here. fn kick(&self) { - if self.running.load(Ordering::Acquire) { + if self.running.load(Ordering::Acquire) && !crate::clock::COUNTING { if let Some(w) = self.worker.lock().unwrap().as_ref() { w.thread().unpark(); } diff --git a/src/dev/mc.rs b/src/dev/mc.rs index 6df347b1d..c0e68629b 100644 --- a/src/dev/mc.rs +++ b/src/dev/mc.rs @@ -775,7 +775,7 @@ impl BusDevice for MemoryController { let mut state = self.state.lock(); state.update_timers(); - match offset as u32 { + let result = match offset as u32 { REG_CPUCTRL0 => { if (val & (1 << 9)) != 0 { // SIN: System INitialization — full power-cycle reset @@ -1028,7 +1028,14 @@ impl BusDevice for MemoryController { BUS_OK } + }; + // On a counting clock a trigger runs its transfer before the access returns, with the MC + // unlocked for what it reaches. RUN stays latched for one read, as the PROM expects. + if crate::clock::COUNTING && self.giodma.state.lock().run_real { + drop(state); + self.dma_worker(); } + result } // MC is a 32-bit device - 8/16-bit accesses not supported @@ -1090,6 +1097,10 @@ impl Device for MemoryController { if self.running.swap(true, Ordering::SeqCst) { return; } // Don't bill the guest for the time since construction. { let mut st = self.state.lock(); st.last_ns = st.clock.now(); } + // A counting clock has no thread: a trigger runs `dma_worker` itself. + if crate::clock::COUNTING { + return; + } let mc = self.clone(); self.threads.lock().push(thread::Builder::new().name("MC-DMA".to_string()).spawn(move || { mc.dma_worker(); diff --git a/src/dev/mc_vdma.rs b/src/dev/mc_vdma.rs index 59188e6a0..5645ee8bc 100644 --- a/src/dev/mc_vdma.rs +++ b/src/dev/mc_vdma.rs @@ -1221,6 +1221,10 @@ impl MemoryController { // before the worker first waits (right after `start`) would // otherwise be lost, and the guest would poll RUNNING forever. while !state.run_real && self.dma_running() { + // Called by the trigger on a counting clock: it returns once the transfer is done. + if crate::clock::COUNTING { + return; + } cvar.wait(&mut state); } @@ -1943,6 +1947,34 @@ mod line_bulk_tests_support { mc } + /// Under `ci_clock` a trigger write runs its transfer before it returns: the next read of + /// DMA_RUN finds the engine idle with the transfer done. + #[cfg(feature = "ci_clock")] + #[test] + fn ci_clock_dma_run_latches_busy_for_one_read_with_the_transfer_done() { + use crate::dev::mc::*; + use crate::traits::{BusDevice, Device}; + let sink = Arc::new(GioSink::new(true)); + for i in 0..8u32 { + sink.mem.write8((0x2000 + i) as u64, pattern(i)); + } + let mc = mc_with(sink.clone()); + mc.start(); + let reg = |r: u32| (MC_BASE + r) as u64; + mc.write32(reg(REG_DMA_MEMADR), 0x2000); + mc.write32(reg(REG_DMA_SIZE), (1 << 16) | 8); + mc.write32(reg(REG_DMA_STRIDE), 1 << 16); + mc.write32(reg(REG_DMA_GIO_ADR), 0x1f0f_0a30); + mc.write32(reg(REG_DMA_MODE), DMA_MODE_DIR); + mc.write32(reg(REG_DMA_STDMA), 1); + assert_eq!(mc.giodma().state.lock().memadr, 0x2008, "the 8 bytes were moved"); + let run = mc.read32(reg(REG_DMA_RUN)).data; + assert_ne!(run & DMA_RUN_RUN, 0, "RUN latched for the first read: {run:#x}"); + assert_ne!(run & DMA_CAUSE_COMPLETE, 0, "complete"); + assert_eq!(mc.read32(reg(REG_DMA_RUN)).data & DMA_RUN_RUN, 0, "idle on the second read"); + mc.stop(); + } + /// Distinct, non-zero byte per address so a skew or a dropped line shows as /// a wrong value rather than a coincidentally-equal one. pub(super) fn pattern(i: u32) -> u8 { ((i.wrapping_mul(31) ^ (i >> 5)) % 251 + 1) as u8 } @@ -2414,6 +2446,8 @@ mod gio32_tests { /// The trigger lands before the worker thread exists, so the worker has /// nobody to notify it: it must see the pending run flag on its own /// instead of sleeping until a second trigger that never comes. + // The worker thread's wake-up: a ci_clock transfer runs inline and has no worker. + #[cfg(not(feature = "ci_clock"))] #[test] fn a_trigger_written_before_the_worker_starts_still_runs() { polled_vdma(true); diff --git a/src/dev/ng1/rex3.rs b/src/dev/ng1/rex3.rs index 4d0ccd4d4..d768f9f47 100644 --- a/src/dev/ng1/rex3.rs +++ b/src/dev/ng1/rex3.rs @@ -3021,6 +3021,14 @@ impl Rex3 { // get subtly wrong. fn wake_gfifo_processor(&self) { + // A started REX3 on a counting clock has no processor thread: the write runs its loop + // until the GFIFO is empty. + if crate::clock::COUNTING { + if self.running.load(Ordering::Relaxed) { + self.register_processor(); + } + return; + } if !self.processor_parked.load(Ordering::Acquire) { return; } @@ -3383,7 +3391,7 @@ impl Rex3 { self.flush_resident_if_due(); } } - } else if !lingered { + } else if !lingered && !crate::clock::COUNTING { // Linger before going idle. A consumer that keeps pace with // the producer reads the tail and each slot just after the // producer writes them, so every push pays a cache-line @@ -3416,6 +3424,9 @@ impl Rex3 { //self.update_gfifo_irqs(); } self.gfifo.flush_head(); + if crate::clock::COUNTING { + return; + } // Nothing in the ring — back off. Spin-hint/yield while a burst // might still be in flight; once emptiness is *sustained* // (crossbeam's backoff completes), stop burning a host core on @@ -4438,10 +4449,13 @@ impl Device for Rex3 { // arguments the compiled shader does instead of a `&Rex3`. unsafe { (*self.context.get()).host = rex3 as *const Rex3; } - *self.processor_thread.lock() = Some(thread::Builder::new().name(self.tag("REX3-Processor")).spawn(move || { - crate::thread_affinity::pin_current(crate::thread_affinity::PerfRole::Rex3Processor); - rex3.register_processor() - }).unwrap()); + // A counting clock has no processor thread: a push runs `register_processor` itself. + if !crate::clock::COUNTING { + *self.processor_thread.lock() = Some(thread::Builder::new().name(self.tag("REX3-Processor")).spawn(move || { + crate::thread_affinity::pin_current(crate::thread_affinity::PerfRole::Rex3Processor); + rex3.register_processor() + }).unwrap()); + } let shim = self.head_shim.get_or_init(|| Arc::new(Rex3Head(rex3))); let head: Arc = shim.clone(); diff --git a/src/dev/ng1/rex3_tests.rs b/src/dev/ng1/rex3_tests.rs index 5927b65d7..13b180eb4 100644 --- a/src/dev/ng1/rex3_tests.rs +++ b/src/dev/ng1/rex3_tests.rs @@ -9830,6 +9830,19 @@ fn legacy_gfifo_register_traffic_marks_framebuffer_dirty() { assert!(rex.fb_dirty.swap(false, Ordering::Acquire)); } +/// Under `ci_clock` the GFIFO is carried out as it is written: STATUS reads idle with nothing +/// queued after a draw. +#[cfg(feature = "ci_clock")] +#[test] +fn ci_clock_status_reads_idle_after_a_draw() { + let rex = &make_rex3_reset(); + assert!(rex.processor_thread.lock().is_none(), "no processor thread"); + reg(rex, REX3_COLORRED, 0x0012_3400); + reg(rex, REX3_COLORRED, 0x0056_7800); + let status = rex.read32(set_addr(REX3_STATUS)).data; + assert_eq!(status & (STATUS_GFXBUSY | STATUS_GFIFOLEVEL_MASK), 0, "idle at once, nothing queued"); +} + /// Once the 1 ms has passed a STATUS read drops the deadline, so later reads never ask the head /// for the time. #[test] diff --git a/src/dev/o2gfx.rs b/src/dev/o2gfx.rs index 7ed3e6f12..47a7f8e8c 100644 --- a/src/dev/o2gfx.rs +++ b/src/dev/o2gfx.rs @@ -1791,6 +1791,11 @@ impl CrimeRe { if self.started.swap(true, std::sync::atomic::Ordering::AcqRel) { return; } + // A counting clock has no thread: `cpu_write` runs the engine until the buffer is empty, + // and what was queued before the start runs now. + if crate::clock::COUNTING { + return self.run(); + } let worker = std::thread::Builder::new() .name("CRIME-RE".into()) .spawn(move || { @@ -1835,7 +1840,7 @@ impl CrimeRe { } // Stays set across sleeps, so an idle engine wakes only for // the park backstop and goes straight back to sleep. - if self.quit.load(Relaxed) { + if self.quit.load(Relaxed) || crate::clock::COUNTING { return; } let since = *idle_since.get_or_insert_with(std::time::Instant::now); @@ -2033,7 +2038,11 @@ impl CrimeRe { self.transfers_queued.fetch_add(1, std::sync::atomic::Ordering::Release); } self.polled_busy.store(false, std::sync::atomic::Ordering::Relaxed); - self.wake(); + if crate::clock::COUNTING && self.started.load(std::sync::atomic::Ordering::Acquire) { + self.run(); + } else { + self.wake(); + } BUS_OK } @@ -4485,6 +4494,8 @@ mod tests { /// than one poll's wait. The first read after a write still answers /// busy without waiting long, so a driver that only checks for room /// keeps drawing while the engine works. + // The engine thread's back-pressure: a ci_clock engine runs inline and never answers busy. + #[cfg(not(feature = "ci_clock"))] #[test] fn a_status_wait_loop_outlasts_an_engine_held_off_the_processor() { let re = Arc::new(CrimeRe::new(Arc::new(O2Memory::single(32 << 20)))); @@ -4551,6 +4562,29 @@ mod tests { assert_eq!(status, RE_STATUS_IDLE); } + /// Under `ci_clock` no thread draws: an MTE clear is done when the write that starts it + /// returns, so the status read that follows answers idle with the memory clear. + #[cfg(feature = "ci_clock")] + #[test] + fn ci_clock_an_mte_clear_is_done_before_the_status_read() { + let ram = Arc::new(O2Memory::single(32 << 20)); + let addr = 0x0011_4000u32; + ram.write(addr as usize, &[0x55; 0x2000]); + let re = Arc::new(CrimeRe::new(ram.clone())); + re.start(re.clone(), |r| r); + assert!(re.worker.lock().unwrap().is_none(), "no engine thread"); + let reg = |off: u32| (0x1500_0000 + off) as u64; + let page = addr >> 12; + let pair = ((1u64 << 31 | page as u64) << 32) | (1u64 << 31 | (page + 1) as u64); + assert_eq!(re.write64(reg(TLB_LINEAR_A + 8 * ((page & 31) >> 1)), pair), BUS_OK); + for (off, val) in [(MTE_DST0, addr), (MTE_DST1, addr + 0x1fff), (MTE_FG, 0), (MTE_BYTEMASK, 0xffff_ffff), (MTE_MODE | 0x800, 0x11)] { + assert_eq!(re.write32(reg(off), val), BUS_OK); + } + assert!(ram.bytes(addr as usize, 0x2000).iter().all(|&b| b == 0), "the clear is done"); + let status = re.read32(reg(STATUS)); + assert_eq!((status.status, status.data), (BUS_OK, RE_STATUS_IDLE), "read at once, answered idle"); + } + /// A full interface buffer holds the CPU's write back (BUS_BUSY) with /// nothing lost, and the status word shows the level as CRIME's 64 /// entries would: what is queued below that, one entry past it. diff --git a/src/dev/wd33c93a.rs b/src/dev/wd33c93a.rs index a9f2f5024..f7aa73fe5 100644 --- a/src/dev/wd33c93a.rs +++ b/src/dev/wd33c93a.rs @@ -446,6 +446,18 @@ impl Wd33c93a { } } + /// On a counting clock there is no worker: run the command just written and raise what it + /// queued in that access, a deferred interrupt at once (as `--no-scsi-deferred-int`). + fn run_pending(&self, st: &mut Wd33c93aState) { + if let Some(cmd_reg) = st.pending_command.take() { + st.process_wd_command(cmd_reg, self.dma.as_deref()); + crate::status::scsi_blink(&self.heartbeat, st.target_id as u32); + } + if !st.irq_fifo.is_empty() { + st.update_irq(); + } + } + /// Wire up the CPU cycle counter — called from `Machine::new` once /// `MipsCpu` exists (this device is constructed before it does, so this /// can't be a constructor parameter; see `MipsCpu::cycles_ptr`). Must be @@ -682,6 +694,9 @@ impl Wd33c93a { dlog!(state.log_module(), "WD33C93A({}): PIO xfer complete phase=0x{:02x}, waking worker ({} bytes)", state.id, cmd_phase, state.fifo.len()); state.update_asr(asr::DBR, 0); state.pending_command = Some(state.regs[regs::COMMAND as usize]); + if crate::clock::COUNTING { + self.run_pending(&mut state); + } drop(state); self.cond.notify_one(); return BUS_OK; @@ -755,6 +770,9 @@ impl Wd33c93a { } state.pending_command = Some(val); + if crate::clock::COUNTING { + self.run_pending(&mut state); + } self.cond.notify_one(); // COMMAND register does not auto-increment } else if ar != regs::AUX_STATUS_DIRECT { @@ -797,6 +815,10 @@ impl Device for Wd33c93a { // Re-arm any DaynaPort backend a previous stop() shut down. No-op on // first boot — add_daynaport() already started them. self.bus.for_each(|_, dev| dev.start()); + // A counting clock has no worker: `run_pending` does its work in the access. + if crate::clock::COUNTING { + return; + } let state = self.state.clone(); let cond = self.cond.clone(); let running = self.running.clone(); @@ -1766,7 +1788,8 @@ impl Wd33c93aState { while i < total { let is_last = i == last_idx; let mut st = dma_dev.write(data[i] as u32, is_last); - if i == 0 && st.not_active() { + // A counting clock cannot wait: inline, the CPU that would arm the channel is this one. + if i == 0 && st.not_active() && !crate::clock::COUNTING { // Driver calls wdsc_dmago *after* writing TRANSFER_INFO, so the channel // may not be active yet. Wait up to 100ms for the CPU thread to arm it. // `wait_active` blocks until the arming write wakes us (HPC3), with no @@ -1796,7 +1819,7 @@ impl Wd33c93aState { // EOX mid-transfer: chain exhausted early (device sent less than allocated). // Pause so IRIX can re-arm via SELECT_ATN_XFER for the next chunk. // XIE (irq without eox): descriptor boundary, chain continues — keep writing. - let pause = (st.eox() || st.refused()) && !is_last; + let pause = (st.eox() || st.refused()) && (!is_last || crate::clock::COUNTING && st.not_active()); if pause { dlog!(self.log_module(), "WD33C93A({}): EOX={} XIE={} refused={} at offset=0x{:x}, remaining=0x{:x} — pausing", self.id, st.eox(), st.irq(), st.refused(), i, total - i); @@ -1847,7 +1870,7 @@ impl Wd33c93aState { None => { let remaining = total - data.len(); if remaining > 0 { - if data.is_empty() { + if data.is_empty() && !crate::clock::COUNTING { // Channel not yet active — driver issues TRANSFER_INFO before dmago // (NetBSD: SET_SBIC_cmd then sc_dmago on same CPU thread). // Wait up to 100ms for the CPU thread to call dmago, woken @@ -1990,11 +2013,34 @@ mod tests { Wd33c93a::new(None, None, Arc::new(AtomicU64::new(0))) } + /// On a counting clock no worker runs: a command is carried out by the write that gives it, and + /// a deferred interrupt is raised with it. + #[cfg(feature = "ci_clock")] + #[test] + fn ci_clock_a_command_completes_when_written() { + let wd = make_scsi(); + wd.start(); + wd.write(0, regs::COMMAND); + wd.write(1, cmd::RESET); + assert!(wd.state.lock().pending_command.is_none(), "taken at once, by no worker"); + assert_eq!(wd.read(0).data & asr::INT, asr::INT, "the reset interrupt is up when the write returns"); + { + let mut st = wd.state.lock(); + st.irq_fifo.push_back((scsi_status::RESET, None, true)); + st.set_asr(asr::CIP | asr::DBR); + wd.run_pending(&mut st); + assert_eq!(st.asr & asr::INT, asr::INT, "a deferred interrupt is not held back"); + } + wd.stop(); + } + /// A command written before the worker first waits is still run. The /// worker takes the state lock when it starts; a COMMAND write and its /// notify that land first used to be lost, because the worker then waited /// without looking at `pending_command` and slept until some later write. /// Hold the lock across `start()` so the write is guaranteed to come first. + // The worker thread's wait: a counting controller runs each command inline and has no worker. + #[cfg(not(feature = "ci_clock"))] #[test] fn a_command_written_before_the_worker_waits_is_not_lost() { let wd = make_scsi(); @@ -2264,6 +2310,7 @@ mod data_out_phase_tests { /// Data in before the driver arms the channel: the chip waits for the /// arming, is woken by it rather than polling, and takes every byte. + #[cfg(not(feature = "ci_clock"))] #[test] fn data_in_waits_for_a_late_arming_and_is_woken_by_it() { let dma = LateDma::new(&[1, 2, 3, 4]); @@ -2274,6 +2321,7 @@ mod data_out_phase_tests { } /// The same for data out. + #[cfg(not(feature = "ci_clock"))] #[test] fn data_out_waits_for_a_late_arming_and_is_woken_by_it() { let dma = LateDma::new(&[]); @@ -2283,4 +2331,24 @@ mod data_out_phase_tests { assert_eq!(*dma.taken.lock(), vec![5, 6, 7, 8]); assert_eq!(dma.waits.load(Ordering::Relaxed), 1, "the chip polled instead of waiting for the arming"); } + + /// On a counting clock the CPU that would arm the channel runs the chip, so an unarmed data + /// phase pauses at once with the interrupt, never waits; a one-byte transfer pauses too. + #[cfg(feature = "ci_clock")] + #[test] + fn ci_clock_data_on_an_unarmed_channel_pauses_without_waiting() { + for data in [vec![5, 6, 7, 8], vec![5]] { + let dma = LateDma::new(&[]); + let dev = Wd33c93a::new(None, None, Arc::new(AtomicU64::new(0))); + let mut s = dev.state.lock(); + assert!(!s.send_data_chunked(data.clone(), 0, Some(&*dma as &dyn DmaClient))); + assert_eq!(s.xfer_data, data, "kept for the resume"); + assert_eq!(s.irq_fifo.len(), 1, "the driver is told"); + assert_eq!(dma.waits.load(Ordering::Relaxed), 0, "no wait on the CPU thread"); + } + let dma = LateDma::new(&[1, 2, 3, 4]); + let dev = Wd33c93a::new(None, None, Arc::new(AtomicU64::new(0))); + assert_eq!(dev.state.lock().receive_data_chunked(4, Some(&*dma as &dyn DmaClient)), None); + assert_eq!(dma.waits.load(Ordering::Relaxed), 0); + } } diff --git a/src/display_stop_tests.rs b/src/display_stop_tests.rs index 3b9359f48..c785870dd 100644 --- a/src/display_stop_tests.rs +++ b/src/display_stop_tests.rs @@ -119,6 +119,8 @@ fn stop_as(name: &str, mut machine: Box, last: bool) -> Option< finished.recv_timeout(BOUND).ok() } +// A ci_clock machine's CPU draws the frames, so one that never started presents none. +#[cfg(not(feature = "ci_clock"))] #[test] fn stopping_from_the_main_thread_never_waits_on_the_renderer() { let dir = scratch("main-thread"); diff --git a/src/ip32_machine.rs b/src/ip32_machine.rs index bcd1c6c35..101f6d4e3 100644 --- a/src/ip32_machine.rs +++ b/src/ip32_machine.rs @@ -204,6 +204,8 @@ impl O2Machine { rtc_offset: cfg.rtc_offset, }; let timer_manager = Arc::new(TimerManager::with_clock(crate::clock::Clock::cpu_or_host())); + // CRIME's engine and the AIC-7880 run inline where the build counts, which needs a counting manager. + assert!(!crate::clock::COUNTING || timer_manager.clock().is_counting()); let bus = Ip32Bus::with_options(mem, prom, opts, &timer_manager); // On a counting clock the service pass runs from the timers, on the CPU's instructions. if timer_manager.clock().is_counting() { diff --git a/src/machine.rs b/src/machine.rs index d22b086a2..dac7961ea 100644 --- a/src/machine.rs +++ b/src/machine.rs @@ -275,6 +275,8 @@ impl Machine { } let timer_manager = Arc::new(TimerManager::with_clock(crate::clock::Clock::cpu_or_host())); + // The MC, REX3 and WD33C93A run inline where the build counts, which needs a counting manager. + assert!(!crate::clock::COUNTING || timer_manager.clock().is_counting()); // 1. Create all devices first // Memory Controller let mc_banks: [u32; 4] = cfg.banks[..4].try_into().expect("the MC has four banks"); @@ -2655,3 +2657,56 @@ mod virtio_tests { assert_eq!(places(both).unwrap(), ["xio15/pci0/7", "xio15/pci0/5"]); } } + +/// Two runs of the Indy's built-in PROM on a counting clock agree on everything the guest can see. +#[cfg(all(test, feature = "ci_clock"))] +mod repeatable_run_tests { + use super::*; + use crate::hptimer::TimerReturn; + use crate::test_temp::{nvram_in, TempPath}; + + /// Machine time the PROM runs for before the CPU is held. + const RUN: std::time::Duration = std::time::Duration::from_millis(40); + + /// Run the PROM for `RUN` of machine time, hold the CPU from a timer on its own instructions, + /// and return what a guest could have seen: registers, Count, the console log and the NVRAM + /// the stop writes. + fn run_prom() -> (crate::cpu::mips_exec::CpuStateDigest, u32, Vec, Vec) { + let dir = TempPath::dir("ci-clock-two-runs"); + let d = dir.to_path_buf(); + std::thread::Builder::new().stack_size(64 * 1024 * 1024).spawn(move || { + let mut cfg = crate::bench_runner::bench_config([128, 128, 0, 0], &parts::R4400_150); + nvram_in(&mut cfg, &d); + cfg.serial_log = Some(d.join("console.log").to_string_lossy().into_owned()); + // Compiled code reaches a deadline only at its flushes, so which regions are compiled by + // when would decide where the timers land. + cfg.jitv2.compile = crate::config::JitCompile::Sync; + crate::dev::serial_host::tests::free_ports(&mut cfg); + let mut machine = Box::new(Machine::new(cfg)); + let slot = machine.cpu.park_slot(); + let hold = slot.clone(); + machine.get_timer_manager().add_one_shot(RUN, move || { + hold.hold(crate::cpu::smp::HOLD_RENDEZVOUS); + TimerReturn::Delete + }); + machine.start(); + machine.cpu_start(); + slot.wait_parked(); + let digest = machine.cpu_state_digest().unwrap(); + // SAFETY: the machine owns the CPU, which is parked. + let count = unsafe { &*machine.cpu.core_ptr() }.count_peek(); + machine.stop(); + let read = |name: &str| std::fs::read(d.join(name)).unwrap_or_default(); + (digest, count, read("console.log"), read("nvram")) + }).unwrap().join().unwrap() + } + + #[test] + fn ci_clock_two_runs_of_the_indy_prom_end_in_the_same_state() { + let (a, b) = (run_prom(), run_prom()); + assert!(a.1 > 0, "the clock moved"); + assert_eq!((a.0.gpr, a.0.pc, a.1), (b.0.gpr, b.0.pc, b.1), "registers and Count"); + assert_eq!(a.2, b.2, "console log"); + assert!(!a.3.is_empty() && a.3 == b.3, "NVRAM"); + } +}