// SPDX-License-Identifier: MIT //! The 32X as megadrive-rust's cartridge-slot device: the 68000's side (milestone 1) //! and, with the user's boot ROMs, the two SH-2s behind it (milestone 2; `sh2side.rs`). //! //! The 32X sits in the Mega Drive's cartridge slot and holds the game (Manual 1.1); on //! megadrive-rust that is a `sockets::SlotDevice` that hands the board the held //! `Cartridge`. The board puts the held cartridge on the bus wherever the device claims //! nothing, so this module answers only the ranges the 32X decodes, and changes them with //! ADEN and RV through `Devices::update_claims`: //! //! ```text //! ======================== ========================================================= //! State Claims (256-byte pages, ``sockets.CLAIM_PAGE``) //! ======================== ========================================================= //! always $A13000-$A130FF (``"MARS"`` at $A130EC-$A130EF; the rest of //! /TIME passed to the cartridge as the board would) and //! $A15100-$A153FF (system registers, VDP, palette) //! ADEN = 1 also $000000-$0000FF (vector ROM, HINT vector register) and //! $840000-$9FFFFF (frame buffer, overwrite image, windows) //! ADEN = 1, RV = 0 also $000100-$3FFFFF (the cartridge is not there, Manual 3.1) //! ======================== ========================================================= //! ``` //! //! With ADEN = 0 nothing at $000000-$3FFFFF is claimed, so megadrive-rust's ROM hot path //! is untouched (`Devices::remap` leaves the cartridge itself on the bus) and a Mega //! Drive game runs as if the 32X were not there (Manual 3.5: "After the power is turned on, //! address space of 68000 is mapped the same as the MEGA Drive unit"); the reference's //! docs/worklog.md, Session 1, has the gate that shows it. //! //! With `BootROMs` the device owns an `SH2Side`: every 68000 or Z80 access to 32X space //! first runs the SH-2s up to the access's master clock (socket 4), and `catch_up` runs //! them after every 68000 instruction (socket 5). The registers both sides share live //! here; the SH-2 side reaches them through `sh2_register_read`/`sh2_register_write`. The //! 32X VDP (`vdp.rs`, milestone 3) keeps its own line timing from socket 6 and draws the //! 32X's own picture, which `composite.rs` lays over the Mega Drive's (milestone 4, socket //! 7); `pwm.rs` is the PWM (milestone 5) and socket 8's sound source. The 68000's waits on //! 32X space are the Manual's (4.1) first model, through `Devices::hold` //! (`Quirks.m68k_waits`). Every behaviour chosen here is a field of `Quirks`. //! //! The reference's `slot.py`. What Rust forced: //! - The reference's device keeps the board from `attach`; here every call that needs it //! is lent the board (`board: &mut Devices`, megadrive-rust's sockets), and passes it //! down. The board owns the held cartridge (`Devices::cartridge`, the reference's //! `board.game_cartridge`); the device keeps whether there is one (`has_cartridge`). //! - The reference's `video_lines_to` runs the Mega Drive's VDP from inside the device's //! call. A device here is lent the board without the VDP, so the board does it first: //! [`Sega32X::video_first`] (megadrive-rust's `Clocked::video_first`) does what comes //! before the sync in the reference's `catch_up` (the clock taken, ADEN looked at) and //! asks for it, and the call that follows finishes the catch-up (`pending`). //! `video_lines_to` itself does nothing here. //! - The reference's exceptions (`Lockup`, `ResetLanding`, `BootROMError`) are a //! `Result`'s [`Stop`] inside the device; at the socket a stop is the board's lock-up //! (`Devices::lock_up`) and the access reads 0, and a peek reads $FF. //! - The device is shared by its four socket objects (`console.rs`): the slot, the video //! timing, the picture and the PWM's sound. use megadrive_rust::board::{Devices, Low}; use megadrive_rust::cartridge::Cartridge; use megadrive_rust::sockets::{PictureLine, PictureRow, Reset, VideoLine, M68K}; use crate::bootrom::BootROMs; use crate::composite::Composite; use crate::machine::{machine, M68kWaits, Machine}; use crate::pwm::PWM; use crate::sh2side::{SH2Side, CMD, HINT, PWM as PWM_INTERRUPT, VINT, VRES}; use crate::vdp::VDP32X; /// A 68000 bus cycle without waits: 4 of its clocks, in master clocks. pub const M68K_CYCLE: i64 = 28; /// Why an access stopped the run (the reference's exceptions). #[derive(Clone, Debug, PartialEq, Eq)] pub enum Stop { /// `megadrive_python.board.Lockup` (and `ResetLanding`, the placeholder for open item /// 10 (`Quirks.reset_with_rv`): the reset button pressed with ADEN = 1 and RV = 1. Not /// a hardware claim -- testpico shows the 68000 landing somewhere in its cartridge's /// $2C8-$304 -- but a stop that says what it is). Lockup(String), /// `BootROMError`: ADEN = 1 with no 68000 boot ROM. BootROM(String), } /// The pages claimed in every state: /TIME and the 32X's registers. pub const ALWAYS: [(u32, u32); 2] = [(0xA13000, 0xA13100), (0xA15100, 0xA15400)]; /// Frame buffer DRAM: two 1-Mbit chips, one displayed while the other is drawn (Manual 2.1). pub const FRAMEBUFFER_SIZE: usize = 0x20000; /// The DREQ FIFO's depth in words: two 4-word FIFOs (Manual figure 3.28). pub const FIFO_WORDS: usize = 8; /// The 32X in the cartridge slot, holding a cartridge (or none for an empty 32X slot). /// `vector_rom`: the 256-byte 68000 boot ROM mapped at $000000 when ADEN is set -- the /// user's `32X_G_BIOS.BIN` through `BootROMs` (checked by SHA-1 there), or any 256-byte /// image a test makes; None is allowed until a program sets ADEN. pub struct Sega32X { pub has_cartridge: bool, pub machine: Machine, pub vector_rom: Option>, /// The board's master clock in Hz (the reference's PWM reads `board.machine.mclk`), /// from `attach`. pub mclk_hz: i64, /// The master clock the device has run to (socket 4/5). pub clock: i64, /// A catch-up begun by `video_first` that the next call finishes. pub pending: Option, /// The claims changed (ADEN, RV): the reference's `board.update_claims()`, which the /// socket object makes once the device is unlocked ([`Sega32X::take_claims_changed`]; /// the board defers a device's own update to the end of its call in any case). pub claims_changed: bool, pub adapter_writable: u16, pub dreq_writable: u16, pub source_mask: u32, pub destination_mask: u32, pub length_mask: u16, pub sega_tv_writable: u16, pub int_writable: u16, pub bank_writable: u16, pub reads_zero: &'static [u32], pub mars: [u8; 4], pub waits: M68kWaits, /// The bus master of the access being answered, and whether it is a peek. pub master: u8, pub peeking: bool, /// The VDP's 68000-to-VDP DMA is reading (`dma_read_word`): not held on the /// cartridge (`Quirks.cartridge_contention`). pub dma: bool, /// The SH-2 side, when the user's boot ROMs were given (decision 3). pub sh2: Option, /// PWM: registers, FIFOs, the counter and socket 8's sound (`pwm.rs`); one object /// for the device's life, since `System::audio_sources` holds it. pub pwm: PWM, /// $A15100 as written (FM, RES, ADEN); REN always reads 1 (adapter_writable). pub adapter: u16, pub interrupt_control: u16, pub bank: u16, /// $A15106: RV (bit 0), bit 1, 68S (bit 2). pub dreq_control: u16, pub dreq_source: u32, pub dreq_destination: u32, pub dreq_length: u16, /// The last word written to the FIFO ($A15112). pub fifo_last: u16, pub sega_tv: u16, pub comm: [u16; 8], pub hint_vector: u32, pub framebuffers: [Vec; 2], /// The 32X VDP: registers, palette, FS, auto fill, its line timing and picture /// (`vdp.rs`; the CPUs reach the frame buffer FS does not display: Manual 3.1). pub vdp: VDP32X, /// Socket 7's composite (`composite.rs`), once `console::build` attaches it. pub composite: Option, /// The DREQ FIFO from the 68000 to SH-2 DMA channel 0 (`Quirks.dreq_fifo`). pub fifo: Vec, /// The SH-2 side's own: standby changer ($20004002), H count ($20004004), HEN. pub standby: u16, pub hcount: u16, pub hen: bool, /// The reset button was pressed with ADEN = 1 and RV = 1 and the 68000 has not /// yet reached the windows (`Quirks.reset_with_rv`). pub button_with_rv: bool, } impl Sega32X { pub fn new( has_cartridge: bool, machine_: Option, vector_rom: Option>, boot_roms: Option<&BootROMs>, ) -> Result { let vector_rom = match boot_roms { Some(roms) => Some(roms.m68k.clone()), None => vector_rom, }; if let Some(rom) = &vector_rom { if rom.len() != 256 { return Err(format!("the 68000 boot ROM is 256 bytes, not {}", rom.len())); } } let machine_ = machine_.unwrap_or_else(|| machine("genesis-32x").expect("the default model")); let q = machine_.quirks; let mclk_hz = megadrive_rust::machine::MCLK_NTSC; let mut device = Sega32X { has_cartridge, machine: machine_, vector_rom, mclk_hz, clock: 0, pending: None, claims_changed: false, adapter_writable: q.adapter_writable.value as u16, dreq_writable: q.dreq_control_writable.value as u16, source_mask: q.dreq_source_mask.value as u32, destination_mask: q.dreq_destination_mask.value as u32, length_mask: q.dreq_length_mask.value as u16, sega_tv_writable: q.sega_tv_writable.value as u16, int_writable: q.interrupt_control_writable.value as u16, bank_writable: q.bank_writable.value as u16, reads_zero: q.reads_zero.value, mars: q.mars_id.value, waits: q.m68k_waits.value, master: M68K, peeking: false, dma: false, sh2: boot_roms.map(|roms| SH2Side::new(&q, roms.master.clone(), roms.slave.clone())), pwm: PWM::new(&q, mclk_hz), adapter: 0, interrupt_control: 0, bank: 0, dreq_control: 0, dreq_source: 0, dreq_destination: 0, dreq_length: 0, fifo_last: 0, sega_tv: 0, comm: [0; 8], hint_vector: 0, framebuffers: [vec![0; FRAMEBUFFER_SIZE], vec![0; FRAMEBUFFER_SIZE]], vdp: VDP32X::new(&q), composite: None, fifo: Vec::new(), standby: 0, hcount: 0, hen: false, button_with_rv: false, }; device.power_on(None); Ok(device) } // -- state --------------------------------------------------------------------- /// Every register to its power-on value (`Quirks`: adapter_power_on, /// dreq_length_power_on, dreq_address_power_on, hint_vector_power_on). The frame /// buffers' power-on contents are unknown; they start at 0. pub fn power_on(&mut self, board: Option<&mut Devices>) { let q = self.machine.quirks; self.adapter = q.adapter_power_on.value as u16 & self.adapter_writable; self.interrupt_control = 0; self.bank = 0; self.dreq_control = 0; self.dreq_source = q.dreq_address_power_on.value as u32 & self.source_mask; self.dreq_destination = q.dreq_address_power_on.value as u32 & self.destination_mask; self.dreq_length = q.dreq_length_power_on.value as u16; self.fifo_last = 0; self.sega_tv = 0; self.comm = [0; 8]; self.hint_vector = q.hint_vector_power_on.value as u32; self.framebuffers = [vec![0; FRAMEBUFFER_SIZE], vec![0; FRAMEBUFFER_SIZE]]; self.vdp = VDP32X::new(&q); self.composite = None; self.fifo = Vec::new(); self.pwm.power_on(); self.standby = 0; self.hcount = 0; self.hen = false; if self.sh2.is_some() { let clock = self.clock; self.sh2_set_run(false, clock, board); } self.button_with_rv = false; } /// Whether the claims changed since the last call (then cleared). pub fn take_claims_changed(&mut self) -> bool { std::mem::take(&mut self.claims_changed) } pub fn aden(&self) -> bool { self.adapter & 1 != 0 } pub fn fm(&self) -> bool { self.adapter & 0x8000 != 0 } pub fn rv(&self) -> bool { self.dreq_control & 1 != 0 } /// The VDP and what it reaches of the device ([`crate::vdp::Links`]). pub fn vdp_links(&mut self) -> (&mut VDP32X, crate::vdp::Links<'_>) { let links = crate::vdp::Links { hen: self.hen, hcount: self.hcount, sh2: self.sh2.as_mut(), composite: self.composite.as_mut(), framebuffers: &self.framebuffers, }; (&mut self.vdp, links) } /// The PWM and what it reaches of the device ([`crate::pwm::Links`]). pub fn pwm_links(&mut self) -> (&mut PWM, crate::pwm::Links<'_>) { let links = crate::pwm::Links { aden: self.adapter & 1 != 0, sh2: self.sh2.as_mut() }; (&mut self.pwm, links) } // -- the socket ------------------------------------------------------------------ pub fn attach(&mut self, board: &mut Devices) { self.mclk_hz = board.machine.mclk(); } pub fn claims(&self) -> Vec<(u32, u32)> { let mut ranges = ALWAYS.to_vec(); if self.adapter & 1 != 0 { ranges.push((0x000000, 0x000100)); if self.dreq_control & 1 == 0 { ranges.push((0x000100, 0x400000)); } ranges.push((0x840000, 0xA00000)); } ranges } /// Rust's part of the reference's `catch_up` before its `video_lines_to`: the clock /// taken, ADEN looked at (megadrive-rust's `Clocked::video_first`). True when the board /// should bring the Mega Drive's VDP to `mclk` before the call that follows, which /// then finishes the catch-up. For the reset button, what `reset` does before its /// SH-2 catch-up would sync. pub fn video_first(&mut self, mclk: i64, reset: Option) -> bool { match reset { None => { if mclk > self.clock { self.clock = mclk; if self.adapter & 1 != 0 { self.pending = Some(mclk); return true; } } false } Some(Reset::Button) => { self.button_with_rv = self.adapter & 1 != 0 && self.dreq_control & 1 != 0; match &self.sh2 { Some(sh2) => sh2.running && mclk * 3 / 7 > sh2.time, None => false, } } Some(_) => false, } } /// The call `video_first` began a catch-up for: finish it first. fn finish_pending(&mut self, board: &mut Devices, mclk: i64) { if let Some(at) = self.pending.take() { assert_eq!(at, mclk, "a catch-up begun for another clock"); self.catch_up_after_video(board, at); } } /// Sockets 4 and 5: with ADEN = 1, the Mega Drive's VDP is brought to `mclk` (its /// line records are the 32X VDP's time base, socket 6), then the SH-2s and the 32X /// VDP's events run to it, in order. With ADEN = 0 nothing runs (the SH-2s are held, /// and nothing can reach the 32X VDP). pub fn catch_up(&mut self, board: &mut Devices, mclk: i64) { if self.pending.is_some() { self.finish_pending(board, mclk); return; } if mclk > self.clock { self.clock = mclk; if self.adapter & 1 == 0 { return; } self.video_lines_to(mclk); self.catch_up_after_video(board, mclk); } } fn catch_up_after_video(&mut self, board: &mut Devices, mclk: i64) { let running = self.sh2.as_ref().is_some_and(|sh2| sh2.running); if running { self.sh2_catch_up(mclk, board); let oldest = self.sh2.as_ref().expect("the SH-2 side").oldest(); let (vdp, mut links) = self.vdp_links(); vdp.advance(mclk, &mut links); vdp.prune(oldest * 7 / 3); } else { let (vdp, mut links) = self.vdp_links(); vdp.advance(mclk, &mut links); vdp.prune(mclk); let (pwm, mut links) = self.pwm_links(); pwm.run(mclk * 3 / 7, &mut links); } } /// The cartridge as the SH-2s reach it at $02000000 (Manual 3.1): memory both sides /// share, its contention between them modelled in `sh2side.rs` /// (`Quirks.cartridge_contention`); the board's game cartridge. pub fn shared_cartridge<'a>(&self, board: &'a mut Devices) -> &'a mut Cartridge { &mut board.cartridge } /// Socket 6's channel from the Mega Drive side: the Mega Drive's VDP publishes its /// line records (`video_line`) up to `mclk` before anything on the 32X side that /// reads them runs (docs/domains.md). Here the board does it before the call /// (`video_first`), so nothing is left to do. pub fn video_lines_to(&mut self, _mclk: i64) {} /// Socket 6 (`System::attach_video_timing`): the 32X VDP's time base -- its status /// bits, HINT and VINT, register latch, FS swap and rows (`vdp.rs`). pub fn video_line(&mut self, line: &VideoLine) { let running = self.adapter & 1 != 0; self.vdp.video_line(line, running); } /// Socket 7 (`System::attach_picture`): the line that leaves the console, the /// 32X's row laid over the Mega Drive's (`composite.rs`). Made on first use, so a /// device nobody attached as a Picture keeps `composite` None. pub fn picture_line(&mut self, line: PictureLine) -> Option { let aden = self.adapter & 1 != 0; let q = self.machine.quirks; self.composite.get_or_insert_with(|| Composite::new(&q)).picture_line(line, aden) } /// The Manual's 68000 waits for an access to 32X space (4.1; `Quirks.m68k_waits`), /// in 68000 clocks, through `Devices::hold`. fn hold(&self, board: &mut Devices, kind: &str, master: u8) { let w = self.waits; let waits = match kind { "framebuffer_read" => w.framebuffer_read, "vdp_read" => w.vdp_read, "vdp_write" => w.vdp_write, "palette_read" => w.palette_read, "palette_write" => w.palette_write, _ => unreachable!("a kind of wait"), }; if waits != 0 { board.hold(master, waits * 7); } } /// Power-on resets every register; the reset button and the 68000's RESET leave /// them (`Quirks.registers_survive_button`). The button's VRES to the SH-2s is /// milestone 2's. pub fn reset(&mut self, board: &mut Devices, kind: Reset, mclk: i64) { if kind == Reset::PowerOn { self.power_on(Some(board)); self.claims_changed = true; } else if kind == Reset::Button { // The 68000 will fetch its reset vector from the vector ROM ($880200) and run // there; with RV = 1 that is the open item `reset_landing` stands in for. self.button_with_rv = self.adapter & 1 != 0 && self.dreq_control & 1 != 0; // VRES: level 14 on both SH-2s, no mask (Manual 3.2.2; testpico // t_32x_reset_btn sees it taken on the master and held by SR on the slave). if self.sh2.as_ref().is_some_and(|sh2| sh2.running) { self.sh2_catch_up(mclk, board); let sh2 = self.sh2.as_mut().expect("the SH-2 side"); sh2.assert_source(0, VRES); sh2.assert_source(1, VRES); } } } /// The VDP's 68000-to-VDP DMA reads what the 68000 would read: the VDP becomes /// the 68000 bus's master, and nothing in the Manual says the 32X tells the two /// apart. What it reads from the frame buffer and the windows is open item 3 of /// docs/undocumented-behavior.md; the board gives the 68000's answer. pub fn dma_read_word(&mut self, board: &mut Devices, address: u32, mclk: i64) -> Result { self.dma = true; let out = self.read_word_inner(board, address, mclk); self.dma = false; out } // -- 68000 and Z80 accesses ------------------------------------------------------- pub fn read_word(&mut self, board: &mut Devices, address: u32, mclk: i64) -> Result { self.finish_pending(board, mclk); self.read_word_inner(board, address, mclk) } fn read_word_inner(&mut self, board: &mut Devices, address: u32, mclk: i64) -> Result { if mclk > self.clock { self.catch_up(board, mclk); } self.master = M68K; let top = address >> 16; if top < 0x40 { return self.low_read_word(board, address); } if top < 0xA0 { return self.high_read_word(board, address); } let page = (address >> 8) & 0xFF; if page == 0x30 { return Ok(self.time_read_word(board, address)); } self.register_read(board, address) } pub fn read_byte(&mut self, board: &mut Devices, address: u32, mclk: i64, master: u8) -> Result { self.finish_pending(board, mclk); if mclk > self.clock { self.catch_up(board, mclk); } self.master = master; self.read_byte_inner(board, address, master) } /// A side-effect-free byte for the Z80's code peeks and the scheduler's probe: /// what a Z80 read would give, and $FF where that read would lock up or is not /// modelled (`Devices::z80_peek` reads $FF for anything it cannot see). pub fn peek_byte(&mut self, board: &mut Devices, address: u32) -> u8 { self.peeking = true; let out = self.read_byte_inner(board, address, 1); self.peeking = false; match out { Ok(value) => value, Err(Stop::Lockup(_)) => 0xFF, Err(Stop::BootROM(message)) => panic!("{message}"), } } pub fn write_word(&mut self, board: &mut Devices, address: u32, value: u16, mclk: i64) -> Result<(), Stop> { self.finish_pending(board, mclk); if mclk > self.clock { self.catch_up(board, mclk); } self.master = M68K; self.write(board, address, value, 0xFFFF) } pub fn write_byte( &mut self, board: &mut Devices, address: u32, value: u8, mclk: i64, master: u8, ) -> Result<(), Stop> { self.finish_pending(board, mclk); if mclk > self.clock { self.catch_up(board, mclk); } self.master = master; if (address >> 8) & 0xFFFF == 0xA130 { // /TIME: a byte write drives the byte on both halves of the bus, as the board's // own byte path does (`Md::system_write`). Self::time_write(board, address, value, value, false); return Ok(()); } if address & 1 != 0 { self.write(board, address & !1, u16::from(value), 0x00FF) } else { self.write(board, address, u16::from(value) << 8, 0xFF00) } } /// A write to /TIME passed to the cartridge as the board's own write path passes it /// (`Devices::cart_write_time`): to a board with its own /TIME registers with the byte /// lanes the 68000 drove, else its low byte (`Cartridge::write_time_lanes` does both). /// Who answers is the cartridge the 32X holds (the board's), unless the TMSS boot ROM /// is switched in, which decodes nothing there (the reference's `_time_cartridge`). fn time_write(board: &mut Devices, address: u32, high: u8, low: u8, word: bool) { if board.low != Low::Boot { board.cartridge.write_time_lanes(address, high, low, word); } } fn read_byte_inner(&mut self, board: &mut Devices, address: u32, master: u8) -> Result { if (address >> 8) & 0xFFFF == 0xA130 { let low = address & 0xFF; if (0xEC..=0xEF).contains(&low) { return Ok(self.mars[(low - 0xEC) as usize]); } if master != M68K { // The board reads $FF for a Z80 bank read of $A1xxxx past the I/O chip // (`Board::z80_bank_read`); /TIME's reads stay as they were. return Ok(0xFF); } } let top = address >> 16; let word = if top < 0x40 { if address >= 0x100 { // Claimed only with RV = 0 (Quirks.low_map_without_rv). Open bus by bytes // is the board's own rule for undecoded space (`Md::read_byte`: the // next opcode's MSB at an even address, 0 at an odd one). return Ok(if address & 1 != 0 { 0 } else { (board.open_bus() >> 8) as u8 }); } self.low_read_word(board, address & !1)? } else if top < 0xA0 { self.high_read_word(board, address & !1)? } else if (address >> 8) & 0xFF == 0x30 { self.time_read_word(board, address & !1) } else { self.register_read(board, address & !1)? }; Ok(if address & 1 != 0 { word as u8 } else { (word >> 8) as u8 }) } /// A write of `value` on the byte lanes `lanes` ($FF00 even byte, $00FF odd /// byte, $FFFF word), `address` even. fn write(&mut self, board: &mut Devices, address: u32, value: u16, lanes: u16) -> Result<(), Stop> { let top = address >> 16; if top < 0x40 { if address & 0xFC == 0x70 && address < 0x100 { let shift = if address & 2 == 0 { 16 } else { 0 }; let keep = !(u32::from(lanes) << shift); self.hint_vector = (self.hint_vector & keep) | (u32::from(value & lanes) << shift); } // The rest of the vector ROM is ROM; $000100-$3FFFFF with RV = 0 is // undriven (Quirks.low_map_without_rv): both ignore writes. } else if top < 0x88 { self.framebuffer_write(address, value, lanes); } else if top < 0xA0 { let offset = self.window(board, address)?; let cartridge = &mut board.cartridge; if lanes == 0xFFFF { cartridge.write_word(offset, value); } else if lanes == 0xFF00 { cartridge.write_byte(offset, (value >> 8) as u8); } else { cartridge.write_byte(offset | 1, value as u8); } } else if (address >> 8) & 0xFF == 0x30 { // Only a word write gets here (`write_byte` takes /TIME's bytes first). Self::time_write(board, address, (value >> 8) as u8, value as u8, true); } else { self.register_write(board, address, value, lanes)?; } Ok(()) } // -- $000000-$3FFFFF ------------------------------------------------------------- fn low_read_word(&mut self, board: &mut Devices, address: u32) -> Result { if address < 0x100 { if address & 0xFC == 0x70 { return Ok((if address & 2 == 0 { self.hint_vector >> 16 } else { self.hint_vector }) as u16); } let Some(rom) = &self.vector_rom else { return Err(Stop::BootROM("ADEN = 1 maps the 32X's 68000 boot ROM; none was given".into())); }; let a = address as usize; return Ok(u16::from(rom[a]) << 8 | u16::from(rom[a + 1])); } // $000100-$3FFFFF with ADEN = 1 and RV = 0 (claimed only then). Ok(board.open_bus_msb()) } /// Where the 68000 goes after the reset button with ADEN = 1 and RV = 1: open item /// 10, a placeholder stop (`Quirks.reset_with_rv`). Replace this method, and only /// this, when a test shows the landing. (The pending flag is left alone here so a /// side-effect-free peek can pass through.) fn reset_landing(&self, address: u32) -> Stop { Stop::Lockup(format!( "68000 fetch at ${address:06X} after the reset button with ADEN = 1 and RV = 1: \ where hardware lands is open (docs/undocumented-behavior.md, item 10); this \ stop is a placeholder, not a hardware claim" )) } // -- $840000-$9FFFFF ------------------------------------------------------------- fn high_read_word(&mut self, board: &mut Devices, address: u32) -> Result { if address < 0x880000 { // $840000-$87FFFF: claimed from $840000 up if self.adapter & 0x8000 != 0 { // Quirks.vdp_side_with_fm: undefined (Manual 3.1); the board's open bus. return Ok(board.open_bus_msb()); } if !self.peeking { self.hold(board, "framebuffer_read", self.master); } let buffer = &self.framebuffers[self.vdp.fs ^ 1]; let offset = (address & 0x1FFFE) as usize; return Ok(u16::from(buffer[offset]) << 8 | u16::from(buffer[offset + 1])); } let offset = self.window(board, address)?; Ok(board.cartridge.read_word(offset)) } /// $880000-$8FFFFF is the cartridge's first 512 KB; $900000-$9FFFFF the 1 MB bank /// `BK1:BK0` (Manual 3.1, 3.5). With RV = 1 both hang (`Quirks.windows_with_rv`). /// The offset in the board's game cartridge. fn window(&mut self, board: &mut Devices, address: u32) -> Result { if self.dreq_control & 1 != 0 { if self.button_with_rv { return Err(self.reset_landing(address)); } return Err(Stop::Lockup(format!("68000 access to ${address:06X} with RV = 1"))); } let (peeking, dma, clock, master) = (self.peeking, self.dma, self.clock, self.master); if let Some(sh2) = self.sh2.as_mut() { if sh2.running && !peeking && !dma { // An SH-2 cartridge cycle under way holds the 68000 to its end; the 68000's // 4 clocks are noted for the SH-2s (Quirks.cartridge_contention). let held = sh2.m68k_cartridge(clock, M68K_CYCLE); if held != 0 { board.hold(master, held); } } } if address < 0x900000 { return Ok(address & 0x7FFFF); } Ok((u32::from(self.bank) << 20) | (address & 0xFFFFF)) } /// $840000: a $00 *byte* is dropped, a $0000 word is written; $860000 (the /// overwrite image of the same DRAM): every $00 byte is dropped /// (`Quirks.framebuffer_zero_bytes`). fn framebuffer_write(&mut self, address: u32, value: u16, lanes: u16) { if self.adapter & 0x8000 != 0 { return; // Quirks.vdp_side_with_fm: "writes are ignored" (Manual 3.1) } let buffer = &mut self.framebuffers[self.vdp.fs ^ 1]; let offset = (address & 0x1FFFE) as usize; let (high, low) = ((value >> 8) as u8, value as u8); let overwrite = address & 0x20000 != 0; if lanes == 0xFFFF && !overwrite { buffer[offset] = high; buffer[offset + 1] = low; return; } if lanes & 0xFF00 != 0 && high != 0 { buffer[offset] = high; } if lanes & 0x00FF != 0 && low != 0 { buffer[offset + 1] = low; } } // -- $A130xx: /TIME -------------------------------------------------------------- fn time_read_word(&mut self, board: &mut Devices, address: u32) -> u16 { let low = address & 0xFF; if (0xEC..=0xEF).contains(&low) { let index = (low & 2) as usize; return u16::from(self.mars[index]) << 8 | u16::from(self.mars[index + 1]); } // The rest is the cartridge's, exactly as the board reads /TIME without a device // (`Md::system_read_word`): a board's own word, else its byte on both halves // (`Cartridge::read_time_word` does both), or the open bus's MSB. The TMSS boot // ROM, switched in, decodes nothing there. let value = if board.low == Low::Boot { None } else { board.cartridge.read_time_word(address) }; value.unwrap_or_else(|| board.open_bus_msb()) } // -- $A15100-$A153FF: registers --------------------------------------------------- fn register_read(&mut self, board: &mut Devices, address: u32) -> Result { let offset = address & 0x3FF; if offset >= 0x180 { return self.vdp_access(board, address, false, 0, 0); } let offset = offset - 0x100; if offset >= 0x40 { // Quirks.unused_registers: as the board reads an undecoded $A1 address. return Ok(board.open_bus_msb()); } if offset >= 0x30 { let clock = self.clock; let (pwm, mut links) = self.pwm_links(); pwm.run(clock * 3 / 7, &mut links); return Ok(self.pwm.read(offset, false)); } if offset >= 0x20 { return Ok(self.comm[((offset - 0x20) >> 1) as usize]); } Ok(match offset { 0x00 => (self.adapter & self.adapter_writable) | 0x0080, 0x02 => self.interrupt_control, 0x04 => self.bank, 0x06 => { let full = if self.fifo.len() >= FIFO_WORDS { 0x80 } else { 0 }; self.dreq_control | full } 0x08 => (self.dreq_source >> 16) as u16, 0x0A => self.dreq_source as u16, 0x0C => (self.dreq_destination >> 16) as u16, 0x0E => self.dreq_destination as u16, 0x10 => self.dreq_length, 0x12 => self.machine.quirks.fifo_read.value as u16, 0x1A => self.sega_tv, _ => 0, // $14-$18, $1C, $1E (Quirks.reads_zero) }) } fn register_write(&mut self, board: &mut Devices, address: u32, value: u16, lanes: u16) -> Result<(), Stop> { let offset = address & 0x3FF; if offset >= 0x180 { self.vdp_access(board, address, true, value, lanes)?; return Ok(()); } let offset = offset - 0x100; if offset >= 0x40 { return Ok(()); } if offset >= 0x30 { let clock = self.clock; let (pwm, mut links) = self.pwm_links(); pwm.run(clock * 3 / 7, &mut links); pwm.write(offset, value, lanes, false, &mut links); return Ok(()); } let keep = !lanes; let value = value & lanes; if offset >= 0x20 { let index = ((offset - 0x20) >> 1) as usize; self.comm[index] = (self.comm[index] & keep) | value; } else if offset == 0x00 { let before = self.adapter; self.adapter = ((before & keep) | value) & self.adapter_writable; if (before ^ self.adapter) & 1 != 0 { if self.adapter & 1 != 0 && self.vector_rom.is_none() { return Err(Stop::BootROM("ADEN = 1 maps the 32X's 68000 boot ROM; none was given".into())); } self.claims_changed = true; } self.sh2_run(board); } else if offset == 0x02 { // INTM/INTS: what is written is what reads back and what requests CMD on the // master/slave; an SH-2's CMD clear clears its bit (`Quirks.cmd_interrupt`). let merged = (self.interrupt_control & keep) | value; self.interrupt_control = merged & self.int_writable; self.cmd_lines(); } else if offset == 0x04 { self.bank = ((self.bank & keep) | value) & self.bank_writable; } else if offset == 0x06 { let before = self.dreq_control; self.dreq_control = ((before & keep) | value) & self.dreq_writable; self.button_with_rv = false; if (before ^ self.dreq_control) & 1 != 0 && self.adapter & 1 != 0 { self.claims_changed = true; } if self.dreq_control & 4 == 0 { self.fifo.clear(); // "Writing 0 force-ends the operation" (Manual 3.2.1) self.dreq_update(); } } else if offset == 0x08 || offset == 0x0A { let shift = if offset == 0x08 { 16 } else { 0 }; let word = ((self.dreq_source >> shift) & 0xFFFF) as u16; let word = (word & keep) | value; let other = self.dreq_source & !(0xFFFF << shift); self.dreq_source = (other | (u32::from(word) << shift)) & self.source_mask; } else if offset == 0x0C || offset == 0x0E { let shift = if offset == 0x0C { 16 } else { 0 }; let word = ((self.dreq_destination >> shift) & 0xFFFF) as u16; let word = (word & keep) | value; let other = self.dreq_destination & !(0xFFFF << shift); self.dreq_destination = (other | (u32::from(word) << shift)) & self.destination_mask; } else if offset == 0x10 { self.dreq_length = ((self.dreq_length & keep) | value) & self.length_mask; } else if offset == 0x12 { self.fifo_last = (self.fifo_last & keep) | value; if self.dreq_control & 4 != 0 && self.fifo.len() < FIFO_WORDS { self.fifo.push(self.fifo_last); self.dreq_update(); } } else if offset == 0x1A { self.sega_tv = ((self.sega_tv & keep) | value) & self.sega_tv_writable; } // $14-$18, $1C, $1E: nothing holds a write (Quirks.reads_zero). Ok(()) } /// $A15180-$A153FF: the VDP registers and the palette. With ADEN = 0 the hardware /// hangs (`Quirks.vdp_without_aden`); with FM = 1 a read is undefined and a write /// ignored (`Quirks.vdp_side_with_fm`); otherwise the VDP's registers (`vdp.rs`), /// and a palette access while PEN = 0 waits for it (`Quirks.palette_wait`). fn vdp_access( &mut self, board: &mut Devices, address: u32, write: bool, value: u16, lanes: u16, ) -> Result { if self.adapter & 1 == 0 { return Err(Stop::Lockup(format!("68000 access to ${address:06X} (32X VDP) with ADEN = 0"))); } if self.adapter & 0x8000 != 0 { return Ok(if write { 0 } else { board.open_bus_msb() }); } let offset = address & 0x3FF; if offset < 0x200 { if offset >= 0x190 { return Ok(if !write { board.open_bus_msb() } else { 0 }); } if !self.peeking { self.hold(board, if write { "vdp_write" } else { "vdp_read" }, self.master); } if write { self.vdp.write(offset & 0xE, value, lanes, self.clock, &mut self.framebuffers); return Ok(0); } return Ok(self.vdp.read(offset & 0xE, self.clock)); } let index = ((offset - 0x200) >> 1) as usize; if !self.peeking { self.hold(board, if write { "palette_write" } else { "palette_read" }, self.master); // PEN = 0: held until it is 1 (Manual 3.3; Quirks.palette_wait). let wait = self.vdp.palette_wait(self.clock); if wait != 0 { board.hold(self.master, wait); } } if write { // Word access only (Manual 3.1); a byte write's lane is taken as it comes. let palette = &mut self.vdp.palette; palette[index] = (palette[index] & !lanes) | (value & lanes); return Ok(0); } Ok(self.vdp.palette[index]) } // -- the SH-2 side's view (sh2side.rs calls these) --------------------------------- /// CMD to each SH-2 follows INTM (master) and INTS (slave). pub fn cmd_lines(&mut self) { let interrupt_control = self.interrupt_control; let Some(sh2) = self.sh2.as_mut() else { return; }; for index in 0..2 { if (interrupt_control >> index) & 1 != 0 { sh2.assert_source(index, CMD); } else if sh2.has_source(index, CMD) { sh2.clear_source(index, CMD); } } } fn sh2_run(&mut self, board: &mut Devices) { if self.sh2.is_some() { let run = self.adapter & 1 != 0 && self.adapter & 2 != 0; let clock = self.clock; self.sh2_set_run(run, clock, Some(board)); } } /// DREQ0 to both SH-2s' DMAC channel 0 while the FIFO holds a word /// (`Quirks.dreq_fifo`). fn dreq_update(&mut self) { let level = u32::from(!self.fifo.is_empty()); if let Some(sh2) = self.sh2.as_mut() { sh2.set_dreq0(level); } } /// A word of $20004000-$200043FF from SH-2 `index` (0 master, 1 slave). pub fn sh2_register_read(&mut self, index: usize, address: u32, _board: &mut Devices) -> u16 { let offset = address & 0x3FF; if offset >= 0x100 { if self.adapter & 0x8000 == 0 { return 0; // FM = 0: "read is undefined" (Manual 3.1; Quirks.sh2_vdp_without_fm) } if offset >= 0x200 { self.sh2_palette_wait(index); return self.vdp.palette[((offset - 0x200) >> 1) as usize]; } if offset >= 0x110 { return 0; } let mclk = self.sh2_mclk(index); return self.vdp.read(offset & 0xE, mclk); } if offset >= 0x40 { return 0; } if offset >= 0x30 { let mclk = self.sh2_mclk(index); let (pwm, mut links) = self.pwm_links(); pwm.run(mclk * 3 / 7, &mut links); return self.pwm.read(offset, true); } if offset >= 0x20 { return self.comm[((offset - 0x20) >> 1) as usize]; } match offset { 0x00 => { let cart = if self.has_cartridge { 0 } else { 0x100 }; (self.adapter & 0x8000) | ((self.adapter & 1) << 9) | cart | (if self.hen { 0x80 } else { 0 }) | self.sh2.as_ref().expect("the SH-2 side").masks[index] as u16 } 0x02 => self.standby, 0x04 => self.hcount, 0x06 => { // FULL/EMPTY of the frame buffer's write FIFO at this access's time // (`Quirks.sh2_dreq_view`, `Quirks.sh2_framebuffer_fifo`); 68S, bit 1 and // RV as the 68000 set them. let sh2 = self.sh2.as_mut().expect("the SH-2 side"); let end = sh2.cycle_end(index); let (full, empty) = sh2.fifo_status(end); (if full { 0x8000 } else { 0 }) | (if empty { 0x4000 } else { 0 }) | self.dreq_control } 0x08 => (self.dreq_source >> 16) as u16, 0x0A => self.dreq_source as u16, 0x0C => (self.dreq_destination >> 16) as u16, 0x0E => self.dreq_destination as u16, 0x10 => self.dreq_length, 0x12 => self.fifo_pop(), _ => 0, } } /// The SH-2 side reads the FIFO (DMA channel 0, or a CPU): the oldest word; the /// length counts down and 68S clears at 0 (Manual 3.2.1). fn fifo_pop(&mut self) -> u16 { if self.fifo.is_empty() { return self.fifo_last; } let word = self.fifo.remove(0); self.dreq_length = self.dreq_length.wrapping_sub(1); if self.dreq_length == 0 { self.dreq_control &= !4; } self.dreq_update(); word } pub fn sh2_register_write(&mut self, index: usize, address: u32, value: u16, lanes: u16, _board: &mut Devices) { let offset = address & 0x3FF; let keep = !lanes; if offset >= 0x100 { if self.adapter & 0x8000 == 0 { return; // FM = 0: "write is ignored" (Manual 3.1) } if offset >= 0x200 { self.sh2_palette_wait(index); let palette = &mut self.vdp.palette; let i = ((offset - 0x200) >> 1) as usize; palette[i] = (palette[i] & keep) | (value & lanes); } else if offset < 0x110 { let mclk = self.sh2_mclk(index); self.vdp.write(offset & 0xE, value, lanes, mclk, &mut self.framebuffers); } return; } if offset >= 0x40 { return; } if offset >= 0x30 { let mclk = self.sh2_mclk(index); let (pwm, mut links) = self.pwm_links(); pwm.run(mclk * 3 / 7, &mut links); pwm.write(offset, value, lanes, true, &mut links); return; } let value = value & lanes; if offset >= 0x20 { let i = ((offset - 0x20) >> 1) as usize; self.comm[i] = (self.comm[i] & keep) | value; } else if offset == 0x00 { if lanes & 0xFF00 != 0 { // FM: "If a 1 is written to the FM bit, access authorization is forced to // switch to the SH2 side" (Manual 3.2.2); ADEN and CART read only. self.adapter = (self.adapter & !0x8000) | (value & 0x8000); } if lanes & 0x00FF != 0 { self.hen = value & 0x80 != 0; self.sh2.as_mut().expect("the SH-2 side").set_mask(index, u32::from(value & 0x0F)); } } else if offset == 0x02 { self.standby = (self.standby & keep) | value; } else if offset == 0x04 { if lanes & 0x00FF != 0 { self.hcount = value & 0xFF; } } else if matches!(offset, 0x14 | 0x16 | 0x18 | 0x1A | 0x1C) { let source = match offset { 0x14 => VRES, 0x16 => VINT, 0x18 => HINT, 0x1A => CMD, _ => PWM_INTERRUPT, }; self.sh2.as_mut().expect("the SH-2 side").clear_source(index, source); if source == CMD { self.interrupt_control &= !(1 << index); } } // $06-$12: the DREQ registers are the 68000's; read only here (testpico // t_32x_reg_w: an SH-2 write to $20004006 leaves RV as it was). } /// An SH-2 at the palette while PEN = 0 waits for it (Manual 3.3; Quirks. /// palette_wait), in its own states. fn sh2_palette_wait(&mut self, index: usize) { let mclk = self.sh2_mclk(index); let wait = self.vdp.palette_wait(mclk); if wait != 0 { self.sh2.as_mut().expect("the SH-2 side").hold(index, (wait * 3 + 6) / 7); } } /// The master clock an SH-2 access happens at (its place on the time line). pub fn sh2_mclk(&self, index: usize) -> i64 { self.sh2.as_ref().expect("the SH-2 side").state(index) * 7 / 3 } /// $04000000-$0403FFFF from an SH-2 (FM = 1); the frame buffer and its overwrite /// image are the same DRAM, and the range repeats above ($24040000: the 32XDK wiki's /// mirror; `Quirks.framebuffer_mirror`). pub fn sh2_framebuffer_read(&self, address: u32, width: u32) -> u32 { if self.adapter & 0x8000 == 0 { return 0; } let buffer = &self.framebuffers[self.vdp.fs ^ 1]; let offset = (address & 0x1FFFF) as usize; match width { // A longword at the buffer's end runs short, as the reference's slice does. 32 => buffer[offset..(offset + 4).min(buffer.len())].iter().fold(0, |v, &b| (v << 8) | u32::from(b)), 16 => u32::from(buffer[offset]) << 8 | u32::from(buffer[offset + 1]), _ => u32::from(buffer[offset]), } } pub fn sh2_framebuffer_write(&mut self, address: u32, width: u32, value: u32) { if self.adapter & 0x8000 == 0 { return; } let buffer = &mut self.framebuffers[self.vdp.fs ^ 1]; let offset = (address & 0x1FFFF) as usize; let overwrite = address & 0x20000 != 0; if width == 8 { if value != 0 { buffer[offset] = value as u8; } return; } let bytes = value.to_be_bytes(); let data = &bytes[(4 - (width >> 3) as usize)..]; for (i, &byte) in data.iter().enumerate() { // A frame-buffer word or longword is written whole; the overwrite image drops // every $00 byte (Manual 3.3, 3.6; testpico t_32x_sh_fb). if byte != 0 || !overwrite { buffer[offset + i] = byte; } } } }