//! The one bus all three Z80s share (`docs/memory-map.md`): video RAM, the //! three work RAMs, the DIP switches, the WSG registers, the two LS259 //! latches, the 06xx window, and the event log the oracle comparison reads. //! //! Each CPU owns a [`CpuBus`] holding its own program ROM (the only per-CPU //! region) and a shared handle to [`Shared`]; ROM fetches never touch the //! shared cell, everything else does. use std::cell::RefCell; use std::rc::Rc; use z80_rust::core::Bus; use super::n06xx::N06xx; use super::n51xx::N51xx; use super::profile::Profile; #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub enum Cpu { Main = 0, Sub = 1, Sub2 = 2, } impl Cpu { /// MAME's device tags, as the oracle's events name them. pub fn name(self) -> &'static str { match self { Cpu::Main => "maincpu", Cpu::Sub => "sub", Cpu::Sub2 => "sub2", } } pub fn from_name(name: &str) -> Option { match name { "maincpu" => Some(Cpu::Main), "sub" => Some(Cpu::Sub), "sub2" => Some(Cpu::Sub2), _ => None, } } } /// One tapped device access, exactly what `oracle/mame_dump.lua` records: /// the frame it happened in, the CPU, the window, the address and the byte /// on the bus. `read` marks the main CPU's reads of the 06xx window. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct Event { pub frame: u64, pub cpu: Cpu, pub kind: Kind, pub addr: u16, pub data: u8, pub read: bool, } #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub enum Kind { Wsg, Latch, Bus06, Ctl06, Star, } impl Kind { pub fn name(self) -> &'static str { match self { Kind::Wsg => "wsg", Kind::Latch => "latch", Kind::Bus06 => "bus06", Kind::Ctl06 => "ctl06", Kind::Star => "star", } } pub fn from_name(name: &str) -> Option { match name { "wsg" => Some(Kind::Wsg), "latch" => Some(Kind::Latch), "bus06" => Some(Kind::Bus06), "ctl06" => Some(Kind::Ctl06), "star" => Some(Kind::Star), _ => None, } } } /// Side effects of latch writes the scheduler must act on after the step /// that produced them (the bus cannot reach the CPUs). pub const EFFECT_CLEAR_MAIN_IRQ: u8 = 0b0001; pub const EFFECT_CLEAR_SUB_IRQ: u8 = 0b0010; pub const EFFECT_SUBS_RELEASED: u8 = 0b0100; pub const EFFECT_SUBS_HELD: u8 = 0b1000; pub struct Shared { pub video_ram: [u8; 0x800], pub ram1: [u8; 0x400], pub ram2: [u8; 0x400], pub ram3: [u8; 0x400], /// MAME's `DSWA` and `DSWB` port bytes (`bosco_dsw_r`: bit 0 of a read is /// DSWB's bit n, bit 1 is DSWA's). MAME's defaults are 0xf7 and 0x97. pub dsw_a: u8, pub dsw_b: u8, pub wsg: [u8; 0x20], /// LS259 3C outputs Q0-Q7 and 5K outputs Q0-Q7. pub misclatch: u8, pub videolatch: u8, pub main_irq_mask: bool, pub sub_irq_mask: bool, /// `nmion_w` stores the inverse of Q2 and starts false (MAME's constructor), /// so it is inconsistent with Q2 until the first write that changes Q2. pub sub2_nmi_on: bool, pub subs_running: bool, /// The vblank IRQ lines, level: asserted at vblank while the mask is set, /// cleared only by a write of 0 to the mask bit. pub main_irq_line: bool, pub sub_irq_line: bool, pub effects: u8, /// A write MAME synchronizes on (a 06xx data or control write, a latch /// change that moves a CPU's IRQ or reset line): MAME ends the writing /// CPU's slice after that instruction (`galaga::sched`). pub sync: bool, pub n06: N06xx, pub n51: N51xx, /// Bytes written to the 54xx (slot 3) with the T-state they arrived at; /// the sound model consumes them. pub n54_writes: Vec<(u64, u8)>, pub events: Vec, /// WSG register writes with the T-state they happened at, for the sound /// renderer: (absolute T-state of the writing CPU, offset, value). pub wsg_writes: Vec<(u64, u8, u8)>, pub frame: u64, /// The main CPU's T-state clock, the timeline the 06xx runs on. pub main_t: u64, /// The T-state clock of the CPU currently stepping (set by the scheduler). pub now: u64, /// Debug: every write to this address is logged to stderr with the CPU /// and clock (`EMU_GALAGA_WATCH=0x93e2` in the oracle tool). pub watch: Vec, /// Debug: log every RAM access in this address range during these /// frames (`EMU_GALAGA_WATCH_RANGE=8000-9fff`, `EMU_GALAGA_WATCH_FRAMES=2034-2035`). pub watch_range: Option<(u16, u16)>, pub watch_frames: (u64, u64), /// PC of the instruction the current CPU is executing (set by the /// scheduler before each step), for the access profile. pub pc: u16, /// Remix: who reads and writes which RAM byte, when switched on. pub profile: Option>, /// Remix: T-states spent at each instruction address, per CPU (index /// `cpu * 0x10000 + pc`), when switched on: where each CPU's time goes. pub time_by_pc: Option>, } impl Shared { pub fn new() -> Shared { Shared { video_ram: [0; 0x800], ram1: [0; 0x400], ram2: [0; 0x400], ram3: [0; 0x400], dsw_a: 0xf7, dsw_b: 0x97, wsg: [0; 0x20], misclatch: 0, videolatch: 0, main_irq_mask: false, sub_irq_mask: false, sub2_nmi_on: false, subs_running: false, main_irq_line: false, sub_irq_line: false, effects: 0, sync: false, n06: N06xx::new(), n51: N51xx::new(), n54_writes: Vec::new(), events: Vec::new(), wsg_writes: Vec::new(), frame: 0, main_t: 0, now: 0, watch: Vec::new(), watch_range: None, watch_frames: (0, u64::MAX), pc: 0, profile: None, time_by_pc: None, } } fn record(&mut self, cpu: Cpu, kind: Kind, addr: u16, data: u8, read: bool) { self.events.push(Event { frame: self.frame, cpu, kind, addr, data, read, }); } fn watching(&self, addr: u16) -> bool { matches!(self.watch_range, Some((lo, hi)) if addr >= lo && addr <= hi) && self.frame >= self.watch_frames.0 && self.frame <= self.watch_frames.1 } pub fn read(&mut self, cpu: Cpu, addr: u16) -> u8 { let value = self.read_inner(cpu, addr); if let Some(profile) = &mut self.profile { profile.access(cpu, self.pc, addr, value, false, self.frame); } if self.watching(addr) { eprintln!( "R {} {} pc {:04x} {addr:04x} {value:02x} +{} t={}", self.frame, cpu.name(), self.pc, self.now % 50_688, self.now ); } value } fn read_inner(&mut self, cpu: Cpu, addr: u16) -> u8 { match addr { 0x6800..=0x6807 => { let n = addr & 7; ((self.dsw_b >> n) & 1) | (((self.dsw_a >> n) & 1) << 1) } 0x7000..=0x70ff => { let value = if self.n06.read_mode() { let mut result = 0xff; if self.n06.selected(0) { result &= self.n51.read(); } result } else { 0x00 }; if cpu == Cpu::Main { self.record(cpu, Kind::Bus06, addr, value, true); } value } 0x7100 => self.n06.control, 0x8000..=0x87ff => self.video_ram[usize::from(addr - 0x8000)], 0x8800..=0x8bff => self.ram1[usize::from(addr - 0x8800)], 0x9000..=0x93ff => self.ram2[usize::from(addr - 0x9000)], 0x9800..=0x9bff => self.ram3[usize::from(addr - 0x9800)], _ => 0x00, } } pub fn write(&mut self, cpu: Cpu, addr: u16, value: u8) { if let Some(profile) = &mut self.profile { profile.access(cpu, self.pc, addr, value, true, self.frame); } if self.watching(addr) { eprintln!( "W {} {} pc {:04x} {addr:04x} {value:02x} +{} t={}", self.frame, cpu.name(), self.pc, self.now % 50_688, self.now ); } if !self.watch.is_empty() && self.watch.contains(&addr) { eprintln!( "watch f{} t={} (+{} in frame) {} 0x{addr:04x} <- 0x{value:02x}", self.frame, self.now, self.now % 50_688, cpu.name() ); } match addr { 0x6800..=0x681f => { self.wsg[usize::from(addr & 0x1f)] = value & 0x0f; self.wsg_writes.push((self.now, (addr & 0x1f) as u8, value)); self.record(cpu, Kind::Wsg, addr, value, false); } 0x6820..=0x6827 => { self.record(cpu, Kind::Latch, addr, value, false); self.write_misclatch((addr & 7) as u8, value & 1 != 0); } 0x7000..=0x70ff => { self.record(cpu, Kind::Bus06, addr, value, false); self.sync = true; if !self.n06.read_mode() { if self.n06.selected(0) { self.n51.write(value); } if self.n06.selected(3) { self.n54_writes.push((self.now, value)); } } } 0x7100 => { self.record(cpu, Kind::Ctl06, addr, value, false); self.sync = true; let now = u128::from(self.main_t) * super::sched::Z80.aps; if self.n06.control_write(value, now) { self.n51.begin_read(); } } 0x8000..=0x87ff => self.video_ram[usize::from(addr - 0x8000)] = value, 0x8800..=0x8bff => self.ram1[usize::from(addr - 0x8800)] = value, 0x9000..=0x93ff => self.ram2[usize::from(addr - 0x9000)] = value, 0x9800..=0x9bff => self.ram3[usize::from(addr - 0x9800)] = value, 0xa000..=0xa007 => { self.record(cpu, Kind::Star, addr, value, false); let bit = (addr & 7) as u8; if value & 1 != 0 { self.videolatch |= 1 << bit; } else { self.videolatch &= !(1 << bit); } } _ => {} } } /// `ls259_device::write_d0` with the driver's callbacks; callbacks only /// run when the bit changes (`update_bit`), which is why the power-on /// write of 0 to bit 3 does nothing. fn write_misclatch(&mut self, bit: u8, d: bool) { let was = self.misclatch & (1 << bit) != 0; if was == d { return; } if d { self.misclatch |= 1 << bit; } else { self.misclatch &= !(1 << bit); } match bit { 0 => { self.main_irq_mask = d; if !d { self.sync = true; self.main_irq_line = false; self.effects |= EFFECT_CLEAR_MAIN_IRQ; } } 1 => { self.sub_irq_mask = d; if !d { self.sync = true; self.sub_irq_line = false; self.effects |= EFFECT_CLEAR_SUB_IRQ; } } 2 => self.sub2_nmi_on = !d, 3 => { self.sync = true; self.subs_running = d; self.n51.reset(); self.effects |= if d { EFFECT_SUBS_RELEASED } else { EFFECT_SUBS_HELD }; } _ => {} } } } impl Default for Shared { fn default() -> Self { Shared::new() } } /// One CPU's view of the bus. pub struct CpuBus { pub cpu: Cpu, /// 16 KB for the main CPU; 4 KB for the subs followed by zeros, which is /// what MAME's zero-filled region returns at 0x1000-0x3fff. rom: Vec, pub shared: Rc>, } impl CpuBus { pub fn new(cpu: Cpu, rom: &[u8], shared: Rc>) -> CpuBus { let mut image = vec![0u8; 0x4000]; image[..rom.len()].copy_from_slice(rom); CpuBus { cpu, rom: image, shared, } } } impl CpuBus { /// Remix: lay `bytes` over this CPU's program space at `at` (below /// 0x4000). For the subs, 0x1000-0x3fff is unconnected on the real board /// and free for new code or data. pub fn patch(&mut self, at: u16, bytes: &[u8]) -> Result<(), String> { let start = usize::from(at); let end = start + bytes.len(); if end > self.rom.len() { return Err(format!( "patch 0x{start:04x}-0x{end:04x} runs past the program space" )); } self.rom[start..end].copy_from_slice(bytes); Ok(()) } /// The program space as this CPU sees it, patches included. pub fn program(&self) -> &[u8] { &self.rom } } impl Bus for CpuBus { #[inline] fn read_byte(&mut self, addr: u16) -> u8 { if addr < 0x4000 { self.rom[usize::from(addr)] } else { self.shared.borrow_mut().read(self.cpu, addr) } } #[inline] fn write_byte(&mut self, addr: u16, value: u8) { if addr >= 0x4000 { self.shared.borrow_mut().write(self.cpu, addr, value); } } #[inline] fn read_port(&mut self, _addr: u16) -> u8 { 0xff } #[inline] fn write_port(&mut self, _addr: u16, _value: u8) {} }