// SPDX-License-Identifier: MIT //! Test-only devices for the expansion sockets: the reference's `tests/fake_devices.py`. //! //! Nothing here models a 32X or a Sega CD: each fake does the least that shows a socket //! reaching it -- it answers with values a test can recognise and logs every call, with //! the master clock and the bus master the board gave it. Each keeps its log behind a //! shared handle ([`Shared`]), since the board owns the device once it is plugged in and //! the test reads the log after (the reference's test holds the same object). Also built //! into `md-trace` (`--fake-slot`, `--fake-port`) for the lockstep's socket cases. #![allow(dead_code)] use std::collections::HashMap; use std::sync::{Arc, Mutex}; use megadrive_rust::board::Devices; use megadrive_rust::cartridge::Cartridge; use megadrive_rust::sockets::{ AudioSource, BusDevice, Clocked, Picture, PictureLine, PictureRow, PortDevice, Reset, SavedDevice, SlotDevice, VideoLine, VideoTiming, M68K, }; use megadrive_rust::system::System; /// One logged access: (kind, address, mclk, master, the board's step start, the device's /// clock after catching up). pub type Access = (&'static str, u32, i64, u8, i64, i64); /// What a [`FakeDevice`] keeps, shared with the test. #[derive(Default)] pub struct Log { pub ranges: Vec<(u32, u32)>, pub clock: i64, pub catch_ups: Vec, pub log: Vec, pub peeks: Vec, pub dma_starts: Vec<(i64, u16)>, pub dma_reads: Vec<(u32, i64)>, pub resets: Vec<(Reset, i64)>, pub written: HashMap, pub hold_mclk: i64, /// A port device's "BIOS" and where it is mapped (`FakePortDevice`). pub bios: Option>, pub base: u32, } pub type Shared = Arc>; impl Log { /// What a read of `address` gives: what was written there, or a recognisable word /// made from the address -- or, on a port device, its BIOS in its range. pub fn value(&self, address: u32) -> u16 { if let Some(bios) = &self.bios { if self.base <= address && address < self.base + 0x400000 && !self.written.contains_key(&(address & !1)) { let offset = ((address - self.base) & !1) as usize; if offset + 1 < bios.len() { return u16::from(bios[offset]) << 8 | u16::from(bios[offset + 1]); } return 0xFFFF; } } self.written .get(&(address & !1)) .copied() .unwrap_or((0xA500 | (address >> 1)) as u16) } } /// The calls every socket device answers (`sockets::BusDevice`), logged. /// /// Its clock runs whenever it is asked to catch up, and every access catches it up to the /// access's own clock before answering, as the add-ons must (socket 4); each log entry /// records the board's step start then, so a test can see the access fell *inside* the /// instruction. `hold_mclk`: wait states it puts on each access. In the slot it holds /// `cartridge` (`FakeSlotDevice`); on the port with a BIOS it maps by /CART /// (`FakePortDevice`). pub struct FakeDevice { pub s: Shared, pub cartridge: Option, } impl FakeDevice { pub fn new(ranges: Vec<(u32, u32)>) -> (Self, Shared) { let s: Shared = Arc::new(Mutex::new(Log { ranges, ..Log::default() })); ( FakeDevice { s: s.clone(), cartridge: None, }, s, ) } /// In the cartridge slot, holding a cartridge, claiming what the 32X claims that is /// not the cartridge's: its registers at $A15100-$A153FF and $800000-$9FFFFF. pub fn slot(cartridge: Option) -> (Self, Shared) { let (mut device, s) = FakeDevice::new(vec![(0xA15100, 0xA15400), (0x800000, 0xA00000)]); device.cartridge = cartridge; (device, s) } /// On the expansion port, mapped by /CART as the Sega CD is: its "BIOS" at $000000 /// with no cartridge, at $400000 with one, and $A12000-$A120FF either way. pub fn port(bios: Vec) -> (Self, Shared) { let (device, s) = FakeDevice::new(Vec::new()); s.lock().unwrap().bios = Some(bios); (device, s) } fn access( &mut self, board: &mut Devices, kind: &'static str, address: u32, mclk: i64, master: u8, ) { self.catch_up(board, mclk); let hold = { let mut s = self.s.lock().unwrap(); let clock = s.clock; s.log .push((kind, address, mclk, master, board.step_start, clock)); s.hold_mclk }; if hold != 0 { board.hold(master, hold); } } } impl Clocked for FakeDevice { fn catch_up(&mut self, _board: &mut Devices, mclk: i64) { let mut s = self.s.lock().unwrap(); s.catch_ups.push(mclk); s.clock = s.clock.max(mclk); } } impl BusDevice for FakeDevice { fn attach(&mut self, board: &mut Devices) { let mut s = self.s.lock().unwrap(); if s.bios.is_some() { s.base = if board.cartridge_present() { 0x400000 } else { 0 }; let base = s.base; s.ranges = vec![(base, base + 0x400000), (0xA12000, 0xA12100)]; } } fn claims(&self) -> Vec<(u32, u32)> { self.s.lock().unwrap().ranges.clone() } fn read_word(&mut self, board: &mut Devices, address: u32, mclk: i64) -> u16 { self.access(board, "rw", address, mclk, M68K); self.s.lock().unwrap().value(address) } fn write_word(&mut self, board: &mut Devices, address: u32, value: u16, mclk: i64) { self.access(board, "ww", address, mclk, M68K); self.s.lock().unwrap().written.insert(address & !1, value); } fn read_byte(&mut self, board: &mut Devices, address: u32, mclk: i64, master: u8) -> u8 { self.access(board, "rb", address, mclk, master); let word = self.s.lock().unwrap().value(address); if address & 1 != 0 { word as u8 } else { (word >> 8) as u8 } } fn write_byte(&mut self, board: &mut Devices, address: u32, value: u8, mclk: i64, master: u8) { self.access(board, "wb", address, mclk, master); self.s .lock() .unwrap() .written .insert(address & !1, u16::from(value)); } fn peek_byte(&mut self, address: u32) -> u8 { self.s.lock().unwrap().peeks.push(address); 0x5A } fn dma_start(&mut self, _board: &mut Devices, mclk: i64, bus: u16) { self.s.lock().unwrap().dma_starts.push((mclk, bus)); } fn dma_read_word(&mut self, _board: &mut Devices, address: u32, mclk: i64) -> u16 { let mut s = self.s.lock().unwrap(); s.dma_reads.push((address, mclk)); s.value(address) } fn reset(&mut self, _board: &mut Devices, kind: Reset, mclk: i64) { self.s.lock().unwrap().resets.push((kind, mclk)); } } impl SlotDevice for FakeDevice { fn take_cartridge(&mut self) -> Option { self.cartridge.take() } } impl PortDevice for FakeDevice {} /// A further sound source at a rate of its own: a constant level, so many samples a call, /// whatever the clock (`sockets::AudioSource`). pub struct FakeAudio { pub s: Arc>, } pub struct AudioLog { pub rate: f64, pub gain: f64, pub level: (f64, f64), pub calls: Vec, } impl FakeAudio { pub fn new(rate: f64, gain: f64, level: (f64, f64)) -> (Self, Arc>) { let s = Arc::new(Mutex::new(AudioLog { rate, gain, level, calls: Vec::new(), })); (FakeAudio { s: s.clone() }, s) } } impl AudioSource for FakeAudio { fn rate(&self) -> f64 { self.s.lock().unwrap().rate } fn gain(&self) -> f64 { self.s.lock().unwrap().gain } fn take_samples(&mut self, mclk: i64) -> Vec<(f64, f64)> { let mut s = self.s.lock().unwrap(); s.calls.push(mclk); vec![s.level; 600] } } /// Keeps every line the VDP publishes (`sockets::VideoTiming`). pub struct FakeVideo { pub lines: Arc>>, } impl VideoTiming for FakeVideo { fn video_line(&mut self, line: VideoLine) { self.lines.lock().unwrap().push(line); } } /// Keeps every line handed over and replaces the ones in `replace` with a line of its /// own colour, 320 wide (`sockets::Picture`). pub struct FakePicture { pub lines: Arc>>, pub replace: HashMap, } impl Picture for FakePicture { fn picture_line(&mut self, line: PictureLine) -> Option { let colour = self.replace.get(&line.row).copied(); self.lines.lock().unwrap().push(line); colour.map(|colour| Arc::new(Mutex::new(vec![colour; 320]))) } } // -- socket 10: a device's own state ---------------------------------------------------- /// What a [`FakeRamp`] keeps, shared with its device and the test. pub struct RampLog { pub rate: f64, pub gain: f64, pub n: i64, pub calls: Vec, } /// A further sound source whose level climbs one step a sample and wraps, so every /// sample differs from its neighbours (a lost leftover or a restarted position shows): /// the reference's `FakeRamp`. Its state is its device's ([`FakeSavedDevice`]). pub struct FakeRamp { pub s: Arc>, } impl AudioSource for FakeRamp { fn rate(&self) -> f64 { self.s.lock().unwrap().rate } fn gain(&self) -> f64 { self.s.lock().unwrap().gain } fn take_samples(&mut self, mclk: i64) -> Vec<(f64, f64)> { let mut s = self.s.lock().unwrap(); s.calls.push(mclk); let mut out = Vec::with_capacity(600); for _ in 0..600 { s.n = (s.n + 37) % 2000; out.push((s.n as f64, -(s.n as f64))); } out } fn held_by(&self) -> Option<&'static str> { Some(std::any::type_name::()) } } /// The test's own handles on a [`FakeSavedDevice`], left out of its state (the /// reference's `state_skip`): how many times it took a state back, and whether the next /// one is refused (once). #[derive(Default)] pub struct Loads { pub loads: u32, pub refuse: bool, } /// A slot device that saves its own side (socket 10, `sockets::SavedDevice`): the /// reference's `FakeSavedDevice`. Its bytes hold every field of its log and its sound /// source's ([`FakeRamp`], for `System::audio_sources`); the cartridge it held is the /// board's (`take_cartridge`), saved with the console. pub struct FakeSavedDevice { pub inner: FakeDevice, pub ramp: Arc>, pub version: u32, pub test: Arc>, } /// Everything a [`FakeSavedDevice`] saves. #[derive(serde::Serialize, serde::Deserialize)] struct FakeState { ranges: Vec<(u32, u32)>, clock: i64, catch_ups: Vec, log: Vec<(String, u32, i64, u8, i64, i64)>, peeks: Vec, dma_starts: Vec<(i64, u16)>, dma_reads: Vec<(u32, i64)>, resets: Vec<(u8, i64)>, written: Vec<(u32, u16)>, hold_mclk: i64, bios: Option>, base: u32, ramp: (f64, f64, i64, Vec), } impl FakeSavedDevice { pub fn new(cartridge: Option, rate: f64) -> (Self, Shared, Arc>) { let (inner, s) = FakeDevice::slot(cartridge); let ramp = Arc::new(Mutex::new(RampLog { rate, gain: 1.0, n: 0, calls: Vec::new(), })); let test = Arc::new(Mutex::new(Loads::default())); let device = FakeSavedDevice { inner, ramp, version: 1, test: test.clone(), }; (device, s, test) } /// Its sound source, for `System::audio_sources`. pub fn source(&self) -> FakeRamp { FakeRamp { s: self.ramp.clone(), } } } impl SavedDevice for FakeSavedDevice { fn state_version(&self) -> u32 { self.version } fn save_state(&self, _console: &System) -> Vec { let s = self.inner.s.lock().unwrap(); let r = self.ramp.lock().unwrap(); let mut written: Vec<(u32, u16)> = s.written.iter().map(|(&a, &v)| (a, v)).collect(); written.sort_unstable(); bincode::serialize(&FakeState { ranges: s.ranges.clone(), clock: s.clock, catch_ups: s.catch_ups.clone(), log: s .log .iter() .map(|&(kind, a, m, w, t, c)| (kind.to_string(), a, m, w, t, c)) .collect(), peeks: s.peeks.clone(), dma_starts: s.dma_starts.clone(), dma_reads: s.dma_reads.clone(), resets: s.resets.iter().map(|&(kind, m)| (kind as u8, m)).collect(), written, hold_mclk: s.hold_mclk, bios: s.bios.clone(), base: s.base, ramp: (r.rate, r.gain, r.n, r.calls.clone()), }) .unwrap() } fn load_state(&mut self, state: &[u8], _console: &System) -> Result<(), String> { let mut test = self.test.lock().unwrap(); if test.refuse { test.refuse = false; return Err("the fake device refuses this value".into()); } let f: FakeState = bincode::deserialize(state).map_err(|e| e.to_string())?; let mut log = Vec::with_capacity(f.log.len()); for (kind, a, m, w, t, c) in f.log { let kind = match kind.as_str() { "rw" => "rw", "ww" => "ww", "rb" => "rb", "wb" => "wb", other => return Err(format!("no access kind {other}")), }; log.push((kind, a, m, w, t, c)); } let mut resets = Vec::with_capacity(f.resets.len()); for (kind, m) in f.resets { resets.push(( match kind { 0 => Reset::PowerOn, 1 => Reset::Button, 2 => Reset::Instruction, other => return Err(format!("no reset {other}")), }, m, )); } let mut s = self.inner.s.lock().unwrap(); s.ranges = f.ranges; s.clock = f.clock; s.catch_ups = f.catch_ups; s.log = log; s.peeks = f.peeks; s.dma_starts = f.dma_starts; s.dma_reads = f.dma_reads; s.resets = resets; s.written = f.written.into_iter().collect(); s.hold_mclk = f.hold_mclk; s.bios = f.bios; s.base = f.base; let mut r = self.ramp.lock().unwrap(); (r.rate, r.gain, r.n, r.calls) = f.ramp; test.loads += 1; Ok(()) } } impl Clocked for FakeSavedDevice { fn catch_up(&mut self, board: &mut Devices, mclk: i64) { self.inner.catch_up(board, mclk); } } impl BusDevice for FakeSavedDevice { fn attach(&mut self, board: &mut Devices) { self.inner.attach(board); } fn claims(&self) -> Vec<(u32, u32)> { self.inner.claims() } fn read_word(&mut self, board: &mut Devices, address: u32, mclk: i64) -> u16 { self.inner.read_word(board, address, mclk) } fn write_word(&mut self, board: &mut Devices, address: u32, value: u16, mclk: i64) { self.inner.write_word(board, address, value, mclk); } fn read_byte(&mut self, board: &mut Devices, address: u32, mclk: i64, master: u8) -> u8 { self.inner.read_byte(board, address, mclk, master) } fn write_byte(&mut self, board: &mut Devices, address: u32, value: u8, mclk: i64, master: u8) { self.inner.write_byte(board, address, value, mclk, master); } fn peek_byte(&mut self, address: u32) -> u8 { self.inner.peek_byte(address) } fn dma_start(&mut self, board: &mut Devices, mclk: i64, bus: u16) { self.inner.dma_start(board, mclk, bus); } fn dma_read_word(&mut self, board: &mut Devices, address: u32, mclk: i64) -> u16 { self.inner.dma_read_word(board, address, mclk) } fn reset(&mut self, board: &mut Devices, kind: Reset, mclk: i64) { self.inner.reset(board, kind, mclk); } fn saved(&self) -> Option<&dyn SavedDevice> { Some(self) } fn saved_mut(&mut self) -> Option<&mut dyn SavedDevice> { Some(self) } } impl SlotDevice for FakeSavedDevice { fn take_cartridge(&mut self) -> Option { self.inner.take_cartridge() } }