// SPDX-License-Identifier: MIT //! The Lynx board: one 16 MHz tick line, the CPU's bus callbacks, the memory map //! (`board.py`). //! //! Domains and channels (charter, "Domains and channels"): the whole machine is one //! clock domain, the 16 MHz crystal; the CPU, Mikey's timers and display, Suzy and //! the cart port all advance on the one tick counter here, in the order of record: //! a CPU bus cycle charges its ticks, then Mikey runs up to the cycle's end, then the //! access is made. The channels between the parts are the bus (this module), the //! interrupt line (Mikey -> CPU), the cart port (Mikey drives its address lines, //! Suzy strobes and reads it: `crate::cart::port`) and the bus grant //! (Mikey's CPUSLEEP <-> Suzy's sprite engine). Audio synthesis is a pure producer //! of Mikey's register state over time. //! //! Modelling levels: CPU cycle level (w65c02-rust, one callback per bus cycle); //! Mikey timers cycle level; tick costs per bus cycle from the documents and the //! hardware tests. //! //! Differences forced by Rust: the Python `Lynx` owns the CPU and the CPU calls back into //! `Lynx._read` / `Lynx._write`. A Rust CPU owns its bus, so the console is split: [`Hw`] //! is everything but the CPU (RAM, ROM, Mikey, Suzy, the cart port, the tick line) and //! implements `w65c02::Bus`; [`Lynx`] holds the CPU, which holds the `Hw`. The CPU state //! the Python board reads inside a callback (`cpu.sync`, `cpu.fetch`) arrives as the //! callback's `Signals`; its interrupt requests and `note_stall` go through the callback's //! `Frame`. Python ints become `i64` (ticks) or the register's width. `Hw` also carries an //! optional bus log for the lockstep trace (`trace`), which the Python trace script gets //! by wrapping the CPU's callbacks. use serde::{Deserialize, Serialize}; use w65c02::{Bus, Cmos65c02, Frame, Signals}; use crate::cart::port::CartPort; use crate::machine::{Machine, DEFAULT}; use crate::mikey::display::DMA_TICKS; use crate::mikey::Mikey; use crate::suzy::engine::EngineBus; use crate::suzy::{self, Suzy}; // -- CPU cycle costs in ticks (Spec §4 "CPU Cycle Tick Summary", DOC; LT page-mode) ------- // MEASURED below means: decoded from the Lynx II logic-analyser captures with the // reference's own scripts (scripts/la_trace.py, la_compare.py, la_registers.py, // la_refresh.py, la_dma.py); docs/validation.md "M2 (bus costs from the captures)". pub const PAGE_MODE_TICKS: i64 = 4; // DOC + MEASURED: a page-mode RAM/ROM read of the instruction stream pub const NORMAL_TICKS: i64 = 5; // DOC + MEASURED: normal RAM/ROM read or write; Mikey registers; Suzy write // MEASURED (la_registers.py, lynx2-mikey-refresh_rate-* captures, 879-1,387 reads each): // a read of Suzy's SCB/math register file ($FC00) takes 10 ticks, a read of her other // registers ($FC92 SPRSYS, $FCB0 JOYSTICK) 9. Other addresses are given the cost of the // group they belong to (HYPOTHESIS). DOC Spec §4: 9 to 15. pub const SUZY_FILE_READ_TICKS: i64 = 10; pub const SUZY_READ_TICKS: i64 = 9; pub const CART_READ_TICKS: i64 = 15; // DOC Spec §9: "The CPU cycle that performed the actual read uses 15 ticks" // The timer/audio dual-ported RAM ($FD00-$FD3F). MEASURED (la_compare.py on // lynx2-mikey-page_mode, la_registers.py on three refresh_rate captures): an access // ends on its timer's slot, which recurs every 16 ticks; timer n's slot (audio channel c // is timer 8 + c) ends 1 tick after timer n-1's (timers 0, 2, 6 and audio 0 measured); // lengths seen 5 to 20 ticks (DOC Spec §4: "5 to 20"), so an access takes 5 ticks plus // the wait for the slot: 5 + ((slot end - start - 5) mod 16). pub const DPRAM_CYCLE: i64 = 16; // The slot phase against the timer prescaler is not in the captures (no timer edge is // visible on the bus). FITTED: see docs/validation.md "M2 (bus costs from the captures)". pub const DPRAM_PHASE: i64 = 0; // DRAM refresh. MEASURED (la_refresh.py, la_dma.py): every display DMA half-burst is // followed by one refresh cycle (row = column, a counter); in lines without display // DMA a refresh cycle of 4 ticks takes the bus every 256 ticks (spacings 250-260, mean // 256), at the next CPU cycle boundary, and the CPU's next access opens a new row. The // refresh request's phase equals the timer 0 slot end modulo 16 in all four captures // measured (la_refresh.py + la_registers.py); its phase modulo 256 is unknown // (HYPOTHESIS: the slot phase). pub const REFRESH_PERIOD: i64 = 256; pub const REFRESH_TICKS: i64 = 4; // FITTED to the capture's alignment (scripts/la_phase.py on lynx2-mikey-page_mode: the // refresh cycles fall where the capture has them for this phase and no other of 21 tried). pub const REFRESH_PHASE: i64 = DPRAM_PHASE + 140; /// Everything of a Lynx console but its CPU: RAM, boot ROM, Mikey, Suzy, a cart. #[derive(Clone, Serialize, Deserialize)] pub struct Hw { pub frame_ticks: i64, pub frames: u64, pub irq_line: bool, pub last_page: bool, pub last_stream: i64, #[serde(skip, default = "default_machine")] pub machine: Machine, pub mapctl: u8, pub mikey: Mikey, pub next_refresh: i64, /// A test hook replacing the CPUSLEEP hold. #[serde(skip)] pub on_sleep: Option, pub port: CartPort, pub ram: Vec, #[serde(skip)] pub rom: Option>, pub row_open: bool, pub stream_open: bool, pub suzy: Suzy, pub tick: i64, /// The lockstep trace's bus log: per CPU bus cycle, the board time after it and /// `kind << 24 | address << 8 | value` (kind 0 read, 1 write). None when not tracing. #[serde(skip)] pub trace: Option>, } fn default_machine() -> Machine { DEFAULT } /// A Lynx console: the CPU on its bus ([`Hw`]). pub struct Lynx { pub cpu: Cmos65c02, } impl Lynx { pub fn new( bank0: &[u8], block0: usize, machine: Machine, boot_rom: Option<&[u8]>, bank1: &[u8], block1: usize, ) -> Lynx { let ram = vec![0u8; 0x10000]; // HYPOTHESIS (U15): power-on RAM contents are not documented; zeros. let port = CartPort::new(bank0, block0, bank1, block1); let mikey = Mikey::new(machine.stereo); // (mikey.ram is the board's RAM: the bus is the channel; passed to Mikey's calls) let suzy = Suzy::new(); let hw = Hw { machine, ram, rom: boot_rom.map(|r| r.to_vec()), port, mikey, suzy, tick: 0, mapctl: 0, // DOC Appx 2: MAPCTL reset = 0 (everything overlaid, page mode on) stream_open: false, row_open: false, last_stream: -2, // address of the last instruction-stream read last_page: false, // the last CPU cycle was a page-mode read irq_line: false, frames: 0, frame_ticks: 0, on_sleep: None, next_refresh: REFRESH_PHASE, trace: None, }; Lynx { cpu: Cmos65c02::new(machine.cpu, hw), } } /// The board around the CPU. pub fn hw(&self) -> &Hw { &self.cpu.bus } pub fn hw_mut(&mut self) -> &mut Hw { &mut self.cpu.bus } // -- running ------------------------------------------------------------------------- pub fn reset(&mut self) { self.cpu.frame.request_reset(); } pub fn step(&mut self) -> u32 { self.cpu.step() } pub fn run_ticks(&mut self, ticks: i64) { let end = self.cpu.bus.tick + ticks; while self.cpu.bus.tick < end { self.cpu.step(); } } pub fn tick(&self) -> i64 { self.cpu.bus.tick } /// What the CPU would read, without side effects or time (for traces and tools). pub fn peek(&self, address: u16) -> u8 { self.cpu.bus.peek(address) } } impl Hw { // -- the bus ----------------------------------------------------------------------- /// Ticks of a CPU read of RAM or the boot ROM. /// /// MEASURED (`scripts/la_compare.py` against `lynx2-mikey-page_mode`, and /// `la_trace.py` on the refresh_rate captures' interrupt routine), agreeing /// with TEST ROM + the LT page-mode guide where it states a rule: /// /// - A read of the instruction stream (an opcode or operand byte, the byte a /// one-byte instruction reads and drops, an RTS's second cycle, a taken /// branch's extra cycle: every read at the address after the last stream /// read) takes 4 ticks when page mode is on (MAPCTL bit 7 clear), the stream /// is open, the DRAM row is still open (no DMA or refresh in between), /// `address & $0F != 0` and the address is the last stream address or the /// one after it. Otherwise 5, and it opens the stream. So a branch, JSR or /// RTS target costs 5 (the captures: every one is a new row). /// - Any other read (data, stack, pointers) is 5 and closes the stream. So is /// the last cycle of an RTS (a read at the pulled address, not after the /// last stream byte): the captured opcode after it is a new row, 5 ticks. /// - While Mikey's interrupt line is asserted no page-mode read follows a /// page-mode read (MEASURED: the refresh_rate interrupt routine alternates /// new-row and page-mode reads throughout; why is unknown, U22). fn read_cost(&mut self, address: u16, cpu: Signals) -> i64 { let address = address as i64; if cpu.sync || ((cpu.fetch || self.stream_open) && address == (self.last_stream + 1) & 0xFFFF) { let difference = (address - self.last_stream) & 0xFFFF; let fast = self.stream_open && self.row_open && address & 0x0F != 0 && (0..=1).contains(&difference) && self.mapctl & 0x80 == 0 && !(self.irq_line && self.last_page); self.stream_open = true; self.last_stream = address; self.last_page = fast; return if fast { PAGE_MODE_TICKS } else { NORMAL_TICKS }; } self.stream_open = false; self.last_page = false; NORMAL_TICKS } /// Ticks of a CPU access to the timer/audio DPRAM (see `DPRAM_CYCLE`). fn dpram_cost(&self, address: u16) -> i64 { let reg = (address & 0xFF) as i64; let slot = if reg < 0x20 { reg >> 2 } else { 8 + ((reg - 0x20) >> 3) }; let end = DPRAM_PHASE + slot; NORMAL_TICKS + (end - self.tick - NORMAL_TICKS).rem_euclid(DPRAM_CYCLE) } fn advance(&mut self, ticks: i64, frame: &mut Frame) { self.tick += ticks; self.mikey.run_until(self.tick, &self.ram); // The interrupt line follows Mikey's pending bits as they change, not only on a // register access (a program waiting in RAM for its interrupt handler's flag). if (self.mikey.timers.pending != 0) != self.irq_line { self.irq(frame); } } /// Display DMA takes the bus before the next CPU or Suzy cycle. /// /// DOC (Spec Appx "bus interplay"): priority video, refresh, CPU, Suzy. The CPU /// cycle in progress completes first (HYPOTHESIS: the burst starts at the next /// cycle boundary; Spec appendix 7, the bus state machine, is lost: U5). The /// burst closes the CPU's DRAM row (LT page-mode: the next CPU access is 5 ticks). fn video(&mut self) { while let Some(&first) = self.mikey.display.dma_times.front() { if first > self.tick { break; } self.mikey.display.dma_times.pop_front(); self.tick += DMA_TICKS; self.row_open = false; self.mikey.run_until(self.tick, &self.ram); } } /// DRAM refresh takes the bus (DOC Spec Appx "bus interplay": priority video, /// refresh, CPU, Suzy; "video and refresh requests should occur together"). In a /// line with display DMA the refresh rides on the DMA bursts (inside /// `DMA_TICKS`); otherwise a 4-tick cycle every 256 ticks (MEASURED: see /// `REFRESH_PERIOD`). fn refresh(&mut self) { while self.next_refresh <= self.tick { self.next_refresh += REFRESH_PERIOD; if !self.mikey.display.fetching(self.mikey.dispctl) { self.tick += REFRESH_TICKS; self.row_open = false; self.mikey.run_until(self.tick, &self.ram); } } } fn irq(&mut self, frame: &mut Frame) { let line = self.mikey.irq_bits() != 0; if line != self.irq_line { self.irq_line = line; if line { frame.request_maskable_interrupt(); } else { frame.clear_maskable_interrupt(); } } } fn dma_due(&self) -> bool { matches!(self.mikey.display.dma_times.front(), Some(&t) if t <= self.tick) } fn read_byte(&mut self, address: u16, frame: &mut Frame, cpu: Signals) -> u8 { if self.dma_due() { self.video(); } if self.next_refresh <= self.tick { self.refresh(); } let mapctl = self.mapctl; if address < 0xFC00 || address == 0xFFF8 { return self.ram_read(address, frame, cpu); } if address < 0xFD00 { if mapctl & 0x01 != 0 { return self.ram_read(address, frame, cpu); } self.register_cycle(); let reg = address & 0xFF; let cost = if reg == 0xB2 || reg == 0xB3 { CART_READ_TICKS } else if reg < 0x80 { SUZY_FILE_READ_TICKS } else { SUZY_READ_TICKS }; self.advance(cost, frame); let value = self.suzy.read(address, self.tick, &mut self.port); self.irq(frame); return value; } if address < 0xFE00 { if mapctl & 0x02 != 0 { return self.ram_read(address, frame, cpu); } self.register_cycle(); let cost = if address < 0xFD40 { self.dpram_cost(address) } else { NORMAL_TICKS }; self.advance(cost, frame); let value = self.mikey.read(address, &self.port); self.irq(frame); return value; } if address == 0xFFF9 { self.register_cycle(); self.advance(NORMAL_TICKS, frame); // MEASURED + TEST ROM (LT page-mode): 5 ticks return (self.machine.mapctl_readback)(mapctl); } let rom_mapped = if address >= 0xFFFA { mapctl & 0x08 == 0 } else { mapctl & 0x04 == 0 }; if !rom_mapped || self.rom.is_none() { return self.ram_read(address, frame, cpu); } let cost = self.read_cost(address, cpu); self.advance(cost, frame); self.row_open = true; self.rom.as_ref().unwrap()[address as usize - 0xFE00] } /// A register access is a data cycle: it closes the stream and the DRAM row. fn register_cycle(&mut self) { self.stream_open = false; self.last_page = false; self.row_open = false; } fn ram_read(&mut self, address: u16, frame: &mut Frame, cpu: Signals) -> u8 { let cost = self.read_cost(address, cpu); self.advance(cost, frame); self.row_open = true; self.ram[address as usize] } fn write_byte(&mut self, address: u16, value: u8, frame: &mut Frame) { if self.dma_due() { self.video(); } if self.next_refresh <= self.tick { self.refresh(); } self.stream_open = false; self.last_page = false; let mapctl = self.mapctl; if address < 0xFC00 || address == 0xFFF8 { self.advance(NORMAL_TICKS, frame); self.row_open = true; self.ram[address as usize] = value; return; } if address < 0xFD00 && mapctl & 0x01 == 0 { self.advance(NORMAL_TICKS, frame); // DOC: Suzy writes are blind 5-tick cycles self.row_open = false; self.suzy.write(address, value, self.tick, &mut self.port); self.irq(frame); return; } if (0xFD00..0xFE00).contains(&address) && mapctl & 0x02 == 0 { let cost = if address < 0xFD40 { self.dpram_cost(address) } else { NORMAL_TICKS }; self.advance(cost, frame); self.row_open = false; let reg = address & 0xFF; if reg == 0x90 { self.mikey.sdone_pending = 0; // DOC SDONEACK: any value acknowledges (C4) } else if reg == 0x91 { self.sleep(frame); } else { self.mikey.write(address, value, &mut self.port, &self.ram); } self.irq(frame); return; } if address == 0xFFF9 { self.advance(NORMAL_TICKS, frame); self.row_open = false; // DOC Appx 2: Mikey and Suzy both accept the write; only bit 0 matters to Suzy. self.mapctl = value; return; } // RAM under the overlays, and the ROM space. HYPOTHESIS (U14): a write to the ROM // space with the overlay on reaches the RAM underneath. self.advance(NORMAL_TICKS, frame); self.row_open = true; self.ram[address as usize] = value; } /// A write to CPUSLEEP ($FD91): the CPU drops its bus request and Suzy runs. /// /// DOC Spec §4 "CPU Sleep" and §16: "the CPU will NOT remain asleep unless Suzy /// is using the bus"; §18: an unacknowledged Suzy completion, or any Mikey /// interrupt "regardless of the state of the CPU enable interrupt bit", keeps /// the CPU from sleeping (C4: TEST ROM sdoneack 1-10). LT timers: an enabled /// pending interrupt wakes it; Suzy then waits and software sleeps again. /// /// The CPU's next cycle happens after this callback returns: the hold is /// inside the write, as the core's contract allows (`note_stall`). fn sleep(&mut self, frame: &mut Frame) { if let Some(hook) = self.on_sleep { hook(self); return; } if !(self.suzy.sprite_busy != 0 && self.suzy.busen != 0) || self.mikey.sdone_pending != 0 { return; } frame.note_stall(); while self.mikey.irq_bits() == 0 { if suzy::run_engine(self) { self.suzy.sprite_busy = 0; self.suzy.sprgo &= !1; self.mikey.sdone_pending = 1; // DOC: Suzy's done, to be acknowledged by SDONEACK break; } } frame.note_stall(); } // -- inspection ---------------------------------------------------------------------- /// What the CPU would read, without side effects or time (for traces and tools). pub fn peek(&self, address: u16) -> u8 { if (0xFC00..0xFD00).contains(&address) && self.mapctl & 1 == 0 { return 0; } if (0xFD00..0xFE00).contains(&address) && self.mapctl & 2 == 0 { return 0; } let vectors = address >= 0xFFFA && self.mapctl & 8 == 0; let rom_space = (0xFE00..0xFFF8).contains(&address) && self.mapctl & 4 == 0; if let Some(rom) = &self.rom { if vectors || rom_space { return rom[address as usize - 0xFE00]; } } self.ram[address as usize] } } impl EngineBus for Hw { /// Suzy owns the bus for `ticks` (the sprite engine calls this per access). fn suzy_cycles(&mut self, ticks: i64) { if self.dma_due() { self.video(); // Suzy yields to video (DOC Spec §4: within 40 ticks) } if self.next_refresh <= self.tick { self.refresh(); // and to refresh (DOC Appx "bus interplay") } self.tick += ticks; self.row_open = false; self.mikey.run_until(self.tick, &self.ram); } fn ram(&mut self) -> &mut [u8] { &mut self.ram } fn suzy(&mut self) -> &mut Suzy { &mut self.suzy } } impl Bus for Hw { fn read(&mut self, address: u16, frame: &mut Frame, signals: Signals) -> u8 { let value = self.read_byte(address, frame, signals); if let Some(log) = self.trace.as_mut() { log.push([self.tick as u64, ((address as u64) << 8) | value as u64]); } value } fn write(&mut self, address: u16, value: u8, frame: &mut Frame, _signals: Signals) { self.write_byte(address, value, frame); if let Some(log) = self.trace.as_mut() { log.push([ self.tick as u64, (1 << 24) | ((address as u64) << 8) | value as u64, ]); } } }