// SPDX-License-Identifier: MIT //! A host that is not a SNES, for the rungs (`harness.py`). //! //! The core does not own the S-SMP's I/O page: this is a minimal copy of what //! the board's `smp` module does, enough to run test programs and sound drivers //! with no S-CPU and no S-DSP audio (the reference's docs/handoff-brief.md "The //! minimal harness"): 64 KiB RAM; $F0-$FF with RAM write-through (B4); the IPL //! ROM overlay; CONTROL; timers 0-2 at 128/16 cycles (B2); DSP ports as a //! 128-byte register file with no audio; $F4-$F7 as latches that a script //! drives; a `.spc` loader; and a stop on a branch to itself. TEST ($F0) is //! stored and otherwise ignored: wait states are the board's (B3). //! //! Rung 2's gilyon driver and rung 3's PeterLemon driver are at the end of this //! module. //! //! Differences forced by Rust: //! //! - The reference's `Harness` owns the CPU and is its bus; here the bus is //! [`Machine`] and [`Harness`] holds the CPU on it. //! - The reference's `on_port_write` is a callable a script sets, a closure //! over the script's report; the one script that uses it (spctest's) is //! [`Script::SpcTest`], whose state the machine holds and whose logic is //! [`Machine::spctest_on_write`], the closure's body. //! - `default_ipl()` (a file in the reference's checkout) is not transcribed: //! the rungs construct the harness without an IPL ROM, as the reference's do. use crate::core::{Bus, Signals, Spc700}; use crate::state::CpuState; pub const SPC_SIGNATURE: &[u8] = b"SNES-SPC700 Sound File Data v0.30"; pub const SPC_MINIMUM_SIZE: usize = 0x10180; // header, RAM and the DSP registers pub const IPL_SIZE: usize = 64; pub const IPL_BASE: u16 = (0x10000 - IPL_SIZE) as u16; /// The conditional branches, whose flags a branch to itself can never change, and BRA, JMP !a. pub const SELF_BRANCHES: [u8; 10] = [0x10, 0x30, 0x50, 0x70, 0x90, 0xB0, 0xD0, 0xF0, 0x2F, 0x5F]; /// One S-SMP timer: stage 2 counts stage-1 ticks up to the target, stage 3 is 4-bit (B2). #[derive(Clone, Copy, Debug, Default)] pub struct Timer { pub enabled: bool, pub target: u8, // 0 means 256 pub counter: u8, pub output: u8, } impl Timer { /// One stage-1 tick. pub fn tick(&mut self) { if self.enabled { self.counter = self.counter.wrapping_add(1); if self.counter == self.target { self.counter = 0; self.output = (self.output + 1) & 0x0F; } } } /// Stages 2 and 3 reset on a 0 to 1 edge of the enable bit (anomie, B2). pub fn enable(&mut self, on: bool) { if on && !self.enabled { self.counter = 0; self.output = 0; } self.enabled = on; } } /// How a bounded run ended. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct RunResult { pub reason: &'static str, // "self-branch", "stopped", "finished" (the script said so) or "max-cycles" pub cycles: u64, pub instructions: u64, } /// The scripted S-CPU behind the ports (the reference's `on_port_write`). #[derive(Clone, Debug, Default)] pub enum Script { #[default] None, /// gilyon's spctest: the tests started, and the PSW a failing test left. SpcTest { tests: Vec, failing: Vec }, } /// The harness's bus: 64 KiB RAM with a minimal S-SMP I/O page. pub struct Machine { pub ram: Vec, pub ipl: Option<[u8; IPL_SIZE]>, pub ipl_mapped: bool, pub cycles: u64, pub timers: [Timer; 3], pub dsp: [u8; 128], pub dsp_address: u8, pub ports_in: [u8; 4], // what the S-SMP reads at $F4-$F7: the S-CPU's last writes pub ports_out: [u8; 4], // what it wrote there: the S-CPU reads these pub port_log: Vec<(u64, u8, u8)>, // (cycle, port 0-3, value), every write pub script: Script, pub finished: bool, // a script sets this to end the run } impl Bus for Machine { fn read(&mut self, address: u16, _signals: Signals) -> u8 { self.tick(); if (0xF0..=0xFF).contains(&address) { return self.read_io(address); } if address >= IPL_BASE && self.ipl_mapped { return self.ipl.unwrap()[(address - IPL_BASE) as usize]; } self.ram[address as usize] } fn write(&mut self, address: u16, value: u8, _signals: Signals) { self.tick(); self.ram[address as usize] = value; // B4: even I/O writes reach the RAM beneath, and $FFC0+ is RAM if (0xF0..=0xFF).contains(&address) { self.write_io(address, value); } } fn idle(&mut self, _signals: Signals) { self.tick(); } } impl Machine { pub fn new(ipl: Option<[u8; IPL_SIZE]>) -> Self { Machine { ram: vec![0; 0x10000], ipl, ipl_mapped: ipl.is_some(), cycles: 0, timers: [Timer::default(); 3], dsp: [0; 128], dsp_address: 0, ports_in: [0; 4], ports_out: [0; 4], port_log: Vec::new(), script: Script::None, finished: false, } } // ----- the clock -------------------------------------------------------- /// One SPC700 cycle: stage 1 is 128 cycles for timers 0 and 1, 16 for timer 2 (B2). fn tick(&mut self) { self.cycles += 1; if self.cycles & 15 == 0 { self.timers[2].tick(); if self.cycles & 127 == 0 { self.timers[0].tick(); self.timers[1].tick(); } } } /// What a read would return, with no side effect and no cycle. pub fn peek(&self, address: u16) -> u8 { if address >= IPL_BASE && self.ipl_mapped { return self.ipl.unwrap()[(address - IPL_BASE) as usize]; } self.ram[address as usize] } fn read_io(&mut self, address: u16) -> u8 { match address { 0xF0 | 0xF1 | 0xFA | 0xFB | 0xFC => 0, // write-only 0xF2 => self.dsp_address, 0xF3 => self.dsp[(self.dsp_address & 0x7F) as usize], // B5: $80-$FF mirror $00-$7F 0xF4..=0xF7 => self.ports_in[(address - 0xF4) as usize], 0xF8 | 0xF9 => self.ram[address as usize], _ => { let timer = &mut self.timers[(address - 0xFD) as usize]; let value = timer.output; timer.output = 0; // B2: reading clears, a dummy read too value } } } fn write_io(&mut self, address: u16, value: u8) { match address { 0xF1 => self.write_control(value), 0xF2 => self.dsp_address = value, 0xF3 => { if self.dsp_address < 0x80 { // B5: writes to the mirror are ignored self.dsp[self.dsp_address as usize] = value; } } 0xF4..=0xF7 => { let port = (address - 0xF4) as u8; self.ports_out[port as usize] = value; self.port_log.push((self.cycles, port, value)); self.on_port_write(port, value); } 0xFA..=0xFC => self.timers[(address - 0xFA) as usize].target = value, _ => {} // TEST, AUXIO and the read-only counters: the RAM write is all there is } } fn on_port_write(&mut self, port: u8, value: u8) { if let Script::SpcTest { .. } = self.script { self.spctest_on_write(port, value); } } fn write_control(&mut self, value: u8) { for (bit, timer) in self.timers.iter_mut().enumerate() { timer.enable(value >> bit & 1 != 0); } if value & 0x10 != 0 { // every time a 1 is written, not on an edge (B1) self.ports_in[0] = 0; self.ports_in[1] = 0; } if value & 0x20 != 0 { self.ports_in[2] = 0; self.ports_in[3] = 0; } self.ipl_mapped = value & 0x80 != 0 && self.ipl.is_some(); } /// spctest's `on_write` (run_spctest's closure). fn spctest_on_write(&mut self, port: u8, value: u8) { let Script::SpcTest { tests, failing } = &mut self.script else { return; }; if port == 3 && failing.is_empty() { // MOVW $F6,YA writes the low byte, then the high one tests.push(self.ports_out[2] as u32 | (value as u32) << 8); } else if port == 0 && value == 1 { self.finished = true; } else if port == 0 && value == 2 { failing.push(self.ports_out[1]); self.ports_in[1] = 2; // the program waits for this before giving A, X and Y } else if port == 0 && value == 3 { self.finished = true; } } } /// The core on 64 KiB RAM with a minimal S-SMP I/O page, the host of rungs 2 to 4. pub struct Harness { pub cpu: Spc700, } impl Harness { pub fn new(ipl: Option<[u8; IPL_SIZE]>) -> Self { Harness { cpu: Spc700::new(Machine::new(ipl)), } } pub fn machine(&mut self) -> &mut Machine { &mut self.cpu.bus } // ----- loading ---------------------------------------------------------- /// Put a raw program at `org` and enter it as the IPL ROM would: A = X = Y = 0, /// PSW = $02, SP = $EF (U12), the IPL ROM still mapped. pub fn load_program(&mut self, data: &[u8], org: u16) { let org = org as usize; let length = data.len().min(0x10000 - org); self.cpu.bus.ram[org..org + length].copy_from_slice(&data[..length]); self.cpu.restore_state(&CpuState { pc: org as u16, ..CpuState::default() }); } /// Load a `.spc` snapshot: registers at $25-$2B, RAM at $100, DSP at $10100, /// the 64 bytes under the IPL ROM at $101C0 (the SPC file format document, /// "SNES-SPC700 Sound File Data v0.30"). pub fn load_spc(&mut self, data: &[u8]) -> Result<(), String> { if data.len() < 27 || data[..27] != SPC_SIGNATURE[..27] || data.len() < SPC_MINIMUM_SIZE { return Err("not a SNES-SPC700 sound file".into()); } let machine = &mut self.cpu.bus; machine.ram.copy_from_slice(&data[0x100..0x10100]); machine.dsp.copy_from_slice(&data[0x10100..0x10180]); machine.dsp_address = machine.ram[0xF2]; machine.ports_in.copy_from_slice(&machine.ram[0xF4..0xF8]); for index in 0..3 { let timer = &mut machine.timers[index]; timer.target = machine.ram[0xFA + index]; timer.output = machine.ram[0xFD + index] & 0x0F; timer.enabled = machine.ram[0xF1] >> index & 1 != 0; } machine.ipl_mapped = machine.ram[0xF1] & 0x80 != 0 && machine.ipl.is_some(); if machine.ram[0xF1] & 0x80 != 0 && data.len() >= 0x10200 { machine.ram[IPL_BASE as usize..].copy_from_slice(&data[0x101C0..0x10200]); } self.cpu.restore_state(&CpuState { a: data[0x27], x: data[0x28], y: data[0x29], sp: data[0x2B], pc: (data[0x26] as u16) << 8 | data[0x25] as u16, psw: data[0x2A], stopped: false, }); Ok(()) } /// A `.spc` snapshot if it has the signature, otherwise a raw program at `org`. /// (PeterLemon's per-test `ADC/SPC700ADC.spc` is a raw program for $0200 /// despite the extension; his top-level `SPC700ADC.spc` is a snapshot.) pub fn load_file(&mut self, data: &[u8], org: u16) -> Result<(), String> { if data.len() >= 27 && data[..27] == SPC_SIGNATURE[..27] { self.load_spc(data) } else { self.load_program(data, org); Ok(()) } } // ----- running ---------------------------------------------------------- /// Run until a branch to itself, a stopped CPU, a finished script, or /// `max_cycles` more cycles. pub fn run(&mut self, max_cycles: u64) -> RunResult { self.run_with(max_cycles, &mut |cpu| { cpu.step(); }) } /// [`Harness::run`] with `step` in place of `cpu.step` (a tracing session's). pub fn run_with( &mut self, max_cycles: u64, step: &mut dyn FnMut(&mut Spc700), ) -> RunResult { let end = self.cpu.bus.cycles + max_cycles; let start = self.cpu.bus.cycles; let mut instructions = 0; let mut reason = "max-cycles"; while self.cpu.bus.cycles < end { if self.cpu.bus.finished { reason = "finished"; break; } if self.cpu.stopped { reason = "stopped"; break; } let pc = self.cpu.pc; step(&mut self.cpu); instructions += 1; if self.cpu.pc == pc && SELF_BRANCHES.contains(&self.cpu.opcode) { reason = "self-branch"; break; } } RunResult { reason, cycles: self.cpu.bus.cycles - start, instructions, } } } // ----- rung 2: gilyon's spctest --------------------------------------------------------------- /// What the three programs of gilyon's spctest reported. #[derive(Clone, Debug, Default, PartialEq, Eq)] pub struct SpcTestReport { pub tests: Vec, // every test number, in the order it started pub failure: Option<(i64, i64, i64, i64, i64)>, // test, PSW, A, X, Y pub cycles: u64, pub instructions: u64, pub programs: u64, } impl SpcTestReport { pub fn passed(&self) -> bool { self.failure.is_none() && self.tests.iter().copied().eq(0..self.tests.len() as u32) } } /// Play the S-CPU side of spctest's port protocol (`spc_common.inc`, `spctest.asm`). /// /// Each program loads at $0300 and waits for port 1 = 1, with ports 2/3 = one /// less than the first test number. It writes each test's number to ports 2/3, /// and port 0 = 1 at the end, or 2 then 3 with the failing test's result on /// ports 1 to 3. Test numbers are checked to run from 0 with no gap, so a /// skipped test cannot pass unseen. pub fn run_spctest(programs: &[Vec], max_cycles: u64) -> SpcTestReport { let mut report = SpcTestReport::default(); let mut last_test: u32 = 0xFFFF; // one less than test 0 for program in programs { let mut harness = Harness::new(None); harness.load_program(program, 0x0300); let machine = harness.machine(); machine.ports_in[1] = 1; machine.ports_in[2] = (last_test & 0xFF) as u8; machine.ports_in[3] = (last_test >> 8) as u8; machine.script = Script::SpcTest { tests: Vec::new(), failing: Vec::new(), }; let result = harness.run(max_cycles); report.cycles += result.cycles; report.instructions += result.instructions; report.programs += 1; let machine = harness.machine(); let Script::SpcTest { tests, failing } = std::mem::take(&mut machine.script) else { unreachable!() }; report.tests.extend(tests); let last = report.tests.last().map_or(-1, |&t| t as i64); let final_port = machine.ports_out[0]; if final_port == 3 { let out = machine.ports_out; report.failure = Some(( last, failing[0] as i64, out[1] as i64, out[2] as i64, out[3] as i64, )); return report; } if result.reason != "finished" || final_port != 1 { report.failure = Some((last, -1, -1, -1, -1)); return report; } last_test = *report.tests.last().unwrap(); } report } // ----- rung 3: PeterLemon's CPU tests --------------------------------------------------------- /// One PeterLemon CPU test: the codes it wrote to $F4 and how it ended. #[derive(Clone, Debug, PartialEq, Eq)] pub struct CpuTestReport { pub codes: Vec, pub reason: &'static str, pub cycles: u64, pub instructions: u64, } impl CpuTestReport { pub fn passes(&self) -> Vec { self.codes .iter() .copied() .filter(|code| code & 0x80 == 0) .collect() } pub fn failures(&self) -> Vec { self.codes .iter() .copied() .filter(|code| code & 0x80 != 0) .collect() } } /// Run a PeterLemon program (raw, from its `SPCRAM` $0200, or a snapshot) until /// its final `jmp Loop`, or its `bra Fail` loop, and collect the $F4 writes: /// $0n pass, $8n fail. pub fn run_cpu_test(program: &[u8], max_cycles: u64) -> CpuTestReport { let mut harness = Harness::new(None); harness .load_file(program, 0x0200) .expect("a PeterLemon program"); let result = harness.run(max_cycles); let codes = harness .cpu .bus .port_log .iter() .filter(|(_, port, _)| *port == 0) .map(|&(_, _, value)| value) .collect(); CpuTestReport { codes, reason: result.reason, cycles: result.cycles, instructions: result.instructions, } }