// SPDX-License-Identifier: MIT //! The expansion sockets: what a 32X or a Sega CD board plugs into (the reference's //! `sockets.py`, megadrive-python `efd80fc`; its docs/expansion-sockets.md). //! //! The add-ons are boards of their own, in their own repositories, which pin this one. //! This module is the whole of the contract between them and this board: nine narrow //! traits (the reference's `typing.Protocol`s) and the plain records two of them hand //! over. Nothing here does any work; the board ([`crate::board`]), the system //! ([`crate::system`]), the VDP, the renderer and the audio path call these at the //! points the design names. //! //! **With nothing attached the board is byte-for-byte what it was before the sockets** //! (the design's gate). Every hook is either reached only on a path that had nothing to //! do before -- open bus, the 32X area's lock-up, the $A1 page's unused registers -- or //! guarded by one `None` test or one empty-list test; the 68000's hot paths (cartridge //! ROM, work RAM, the VDP's ports) are untouched, because a claim on $000000-$3FFFFF //! changes which object answers there ([`crate::board::Devices::remap`]) rather than //! testing anything per access. //! //! The sockets, by the design's numbers: //! //! 1. **Cartridge slot** -- the cartridge itself (this crate's [`Cartridge`] and //! `BootRom`, with `grounds_cart`), and a [`SlotDevice`] that *holds* one (the 32X). //! An empty slot is a real state: `Devices::slot_cartridge` is false and /CART reads //! high (`Devices::cartridge_present`). //! 2. **Expansion port** -- a [`PortDevice`] (the Sega CD), which reads /CART from the //! board when it is attached and claims $000000-$3FFFFF or $400000-$7FFFFF //! accordingly, plus $A12000-$A120FF. It clears $A10001 bit 5 (/DISK), and the TMSS //! boot ROM, when switched in, sits above it. //! 3. **One decode for every bus master** -- the 68000, the Z80's bank window (and the //! side-effect-free peek the scheduler's probe uses) and the VDP's 68000-to-VDP DMA //! all reach a device through the same claims ([`BusDevice::claims`]). DMA has its own //! entry ([`BusDevice::dma_read_word`]) and a start notice with the bus's value then //! ([`BusDevice::dma_start`]), for word RAM's one-word-late rule. //! 4. **Bus timing** -- every device access carries its master clock, and the device may //! hold the master that made it (`Devices::hold`). The device can run itself up to //! that clock *inside* the access, before it answers. //! 5. **Clock domains** -- `System::clocked`: each is run up to the 68000's clock after //! every 68000 instruction, after the Z80 ([`Clocked::catch_up`]). //! 6. **Video timing** -- a [`VideoTiming`] gets one [`VideoLine`] per line as the VDP //! starts it (and again when an H32/H40 change re-anchors it), every edge in master //! clocks. //! 7. **Picture** -- a [`Picture`] gets each finished line as a [`PictureLine`] (finished //! RGB, YS, shadow/highlight) and returns the line that leaves the console. //! 8. **Sound** -- `System::audio_sources`: further [`AudioSource`]s, each at its own and //! changeable rate with its own gain, mixed with the FM and the PSG. //! 9. **Reset** -- three events, [`Reset`]: power-on, the reset button, and the 68000's //! RESET instruction ([`BusDevice::reset`]). //! //! What Rust forces (the shape of the rest of the crate, docs/handoff-brief.md): //! //! - A device cannot keep the board it is attached to, as the reference's do from //! `attach`: every call that may need it is handed the board (`board: &mut Devices`, //! everything but the VDP, which Rust cannot lend from inside its own DMA). So a //! device cannot run the VDP itself (`board.vdp.sync(mclk)` in the reference's //! [`VideoTiming`] notes). //! - The board owns its devices and lends each out for the length of a call //! (`Devices::with_device`); a device's `update_claims` from inside its own call takes //! effect as that call returns, before the next access, rather than at once. Nothing //! reaches the board's decode in between, so no access can tell. //! - A slot device hands the board the cartridge it holds at attach //! ([`SlotDevice::take_cartridge`]): the board's bus owns it, and the device reaches it //! through `board.cartridge` (the reference's `Board.game_cartridge`). //! - The picture a device returns is a shared row ([`PictureRow`]), the reference's //! list, so the device can still fill it in place until the frame is read. //! - A claim the reference refuses with `ValueError` (not whole pages, not on a socket's //! bus, a second device in a socket) is a bug in the device: here it panics. //! //! What the design calls for and this does not do is listed in the reference's //! docs/expansion-sockets.md, "What is built". use std::sync::{Arc, Mutex}; use crate::board::Devices; use crate::cartridge::Cartridge; use crate::vdp::HName; /// Which bus master made a byte access ([`BusDevice::read_byte`]). A word access is /// always the 68000's: the Z80's bus is eight bits wide, and the VDP's DMA has its own /// entry, [`BusDevice::dma_read_word`]. pub const M68K: u8 = 0; pub const Z80: u8 = 1; /// The granularity of a claim: 256 bytes, so that $A12000-$A120FF (the Sega CD's gate /// array) and $A15100-$A153FF (the 32X's registers) are claims of their own without /// taking the I/O chip's page, the Z80's bus and reset registers or TMSS's with them. pub const CLAIM_PAGE: u32 = 0x100; /// What a device may claim, as [start, end) 68000 addresses: the cartridge and /// expansion ranges, the 32X area, and the $A1 page -- less the pages the board's own /// registers decode: the I/O chip ($A10000-$A1001F), the Z80's bus request and reset /// ($A111xx, $A112xx) and TMSS ($A140xx, $A141xx). Work RAM, the VDP and the Z80's space /// are not on either socket's bus. pub const CLAIMABLE: [(u32, u32); 4] = [ (0x000000, 0xA00000), (0xA10100, 0xA11100), (0xA11300, 0xA14000), (0xA14200, 0xA20000), ]; /// The three reset events (socket 9), which the add-ons may treat differently: the /// reset button interrupts the 32X's SH-2s (VRES; testpico `t_32x_reset_btn`), and what /// each event does to a Sega CD is the device's to decide (no hardware source here says /// whether its reset follows the button: provisional, segacd-python's question). Whether /// the 68000's RESET instruction reaches either socket's reset line is not established /// by any source here either: every event is delivered, and the device decides. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Reset { PowerOn = 0, Button = 1, Instruction = 2, } /// Socket 5: a device with its own clock, run up to `mclk` (master clocks from power-on) /// after every 68000 instruction. A device in the 68000's clock domain (the 32X: SH-2 = /// MCLK x 3/7) converts exactly; one with its own crystal (the Sega CD's 50 MHz) keeps /// its own ratio and remainder. It may also be called from inside a bus access (socket /// 4), by the device itself, at the access's clock; when nothing is due it should cost a /// comparison. Overshoot is the device's: it may run whole instructions past `mclk` (the /// Sega CD's sub-CPU: up to a DIVS, about 680 MCLK). pub trait Clocked { fn catch_up(&mut self, board: &mut Devices, mclk: i64); /// What Rust forces of a device that runs the Mega Drive's VDP itself /// (sega32x-python's `Sega32X.video_lines_to`, `board.vdp.sync(mclk)` from inside its /// own access or catch-up: socket 6's line records up to `mclk` before its SH-2s and /// its own VDP run). A device here is lent the board without the VDP, so the board /// asks first: before every call it makes with a clock -- an access by the 68000 or /// the Z80, a catch-up (socket 5), a reset (`reset` is then the event) -- it asks /// whether the VDP should first be brought to `mclk`, and if so syncs it, then makes /// the call. The device does here, in the reference's order, whatever comes before /// the VDP's sync in its own call (the 32X notes the clock as its own), and the rest /// when the call comes. Not asked on a DMA read: the VDP is the caller then, already /// at `mclk`, where the reference's sync does nothing. Asking for nothing (the /// default) leaves every device and the board as they were. fn video_first(&mut self, _board: &mut Devices, _mclk: i64, _reset: Option) -> bool { false } } /// What both sockets' devices answer (sockets 1-5 and 9). /// /// `attach`: the board, once, when the device is plugged in; the device reads the /// open-bus value (`Devices::open_bus`), /CART (`Devices::cartridge_present`), the /// cartridge it may pass accesses through to (`Devices::cartridge`), its own wait states /// (`Devices::hold`) and re-reads its claims when they change (`Devices::update_claims`: /// the 32X's ADEN, the Sega CD's mode) from the board each call is handed. /// /// `claims`: [start, end) ranges of 68000 addresses the device answers, each a multiple /// of [`CLAIM_PAGE`] and inside [`CLAIMABLE`]. Read at attach and at every /// `update_claims`. A range nobody claims behaves as it does without a device: the /// cartridge at $000000-$3FFFFF, open bus at $400000-$7FFFFF, a lock-up at /// $800000-$9FFFFF. Where both sockets claim a page the port wins (TMSS > port > slot, /// the order segacd-python's `docs/sockets.md` 2 gives for $000000; for the Sega CD with /// a 32X it is provisional, a question for that milestone). /// /// The accesses: `mclk` is the master clock the access starts at -- the 68000's own /// clock inside its instruction (`Devices::m68k_access_clock`), or the Z80's /// (`Devices::z80_access_time`) -- so the device can catch itself up to it before it /// answers (socket 4). The cartridge refresh has already stretched the 68000's cycle /// when the device is called. `peek_byte` must have no side effects on the console: the /// scheduler's probe and the Z80's code peeks use it. /// /// `dma_start`: a 68000-to-VDP DMA has started at `mclk`, with `bus` the value on the /// 68000's data bus then (its prefetch, `Devices::open_bus`), so a device that delays its /// words by one read has the first one to give (whether word RAM does, and what comes /// first, is the device's question: segacd-python `docs/sockets.md` 9); the device /// latches as it decides. Every device is told, whether or not the transfer's source is /// its own. `dma_read_word`: a word of such a transfer from a claimed page, at the VDP's /// clock for that read. /// /// `reset`: one of the three [`Reset`] events, at master clock `mclk`. /// /// `name`: what the header of a save state names the device by (the reference's /// qualified class name), so a state loads only into a console wired the same. pub trait BusDevice: Clocked { fn attach(&mut self, board: &mut Devices); fn claims(&self) -> Vec<(u32, u32)>; fn read_word(&mut self, board: &mut Devices, address: u32, mclk: i64) -> u16; fn write_word(&mut self, board: &mut Devices, address: u32, value: u16, mclk: i64); fn read_byte(&mut self, board: &mut Devices, address: u32, mclk: i64, master: u8) -> u8; fn write_byte(&mut self, board: &mut Devices, address: u32, value: u8, mclk: i64, master: u8); /// `board` is lent for reading (the 32X peeks its windows into the cartridge the board /// holds, and the open bus): what the reference's devices reach through the board they /// keep. Nothing may be changed through it. fn peek_byte(&mut self, board: &mut Devices, address: u32) -> u8; fn dma_start(&mut self, board: &mut Devices, mclk: i64, bus: u16); fn dma_read_word(&mut self, board: &mut Devices, address: u32, mclk: i64) -> u16; fn reset(&mut self, board: &mut Devices, kind: Reset, mclk: i64); fn name(&self) -> &'static str { std::any::type_name::() } } /// Socket 1's device: a board in the cartridge slot that holds a cartridge (the 32X). /// /// `take_cartridge`: the cartridge in *its* slot, or None, handed to the board at attach /// (the reference's `cartridge` attribute, which the board and the device share). The /// board puts it on the bus wherever the device does not claim -- the 32X with ADEN = 0 /// claims nothing at $000000 and the held cartridge answers as if it were in the /// console's own slot -- and /CART is its: the 32X answers for its own slot /// (sega32x-python's handoff brief, finding 2). pub trait SlotDevice: BusDevice { fn take_cartridge(&mut self) -> Option; } /// Socket 2's device: a board on the expansion port (the Sega CD). It reads /CART from /// the board at attach (`Devices::cartridge_present`) and claims by it: $000000-$3FFFFF /// with no cartridge (its BIOS, PRG RAM window and word RAM), else $400000-$7FFFFF, and /// $A12000-$A120FF either way. A cartridge that does not ground /CART answering at /// $400000-$7FFFFF (the RAM cartridge) is the device's to route: it claims the range and /// passes the access to `Devices::cartridge`, so the Sega CD's swap lives in its own /// repository. Hot-plugging is not modelled. pub trait PortDevice: BusDevice {} /// One line of the Mega Drive VDP's timing, every time in master clocks from power-on /// (socket 6). What the 32X takes off the slot -- HSYNC, VSYNC, EDCLK, NTSC/PAL -- and /// needs at master-clock precision for its HBLK/VBLK/PEN bits, its HINT and VINT and its /// register latch (sega32x-python's handoff brief, finding 6c). /// /// `start`/`length`: the line, from the V counter's increment point (the board's line /// boundary, `VdpState::line_start`). `v`: the V counter on it. `hmode`: H32 or H40. /// `hblank_set`/`hblank_clear`: when the HBlank flag sets ($166 in H40, $126 in H32) and /// clears ($00B, $00A) in this line. `vblank`: the vertical border is on for the line. /// `vsync`: the line VSYNC is asserted on. `pixels`: each pixel's start from `start`, in /// order of the H counter from the increment point (`HMode::starts`): the dot clock, /// EDCLK's slow pixels around HSYNC included. `published`: when this record was made -- /// `start`, or later for a mode change that re-anchors the line at its HBlank /// (`Vdp::latch_hmode`). #[derive(Clone, Debug, PartialEq, Eq)] pub struct VideoLine { pub start: i64, pub length: i64, pub v: i64, pub hmode: HName, pub hblank_set: i64, pub hblank_clear: i64, pub vblank: bool, pub vsync: bool, pub interlace: bool, pub odd: bool, pub pal: bool, pub pixels: &'static [i64], pub published: i64, } /// Socket 6: told of each line as the VDP starts it. The VDP is lazy (it runs when read, /// written, or at the start of a 68000 step), so a line is published when the VDP /// reaches it, which may be after the device's own clock. pub trait VideoTiming { fn video_line(&mut self, line: VideoLine); } /// A line of RGB888 a [`Picture`] device returns: shared, so the device may fill it in /// place until the frame is read (the reference's list). pub type PictureRow = Arc>>; /// One finished display line of the Mega Drive's picture, handed to the device before it /// leaves the console (socket 7; sega32x-python's handoff brief, findings 6a-6b). /// /// `row`: the picture row (with double interlace, both fields' rows). `start`: the /// line's start in master clocks (`VdpState::line_start`). `hmode`, `width` (256 or /// 320) and `pixel_mclk` (10 or 8: the active display's dot clock) describe the line; /// `display_at` is the master clock the H counter names pixel 0 at, and the output runs /// `output_delay` pixels behind it (`render::output_delay`). That is where a CRAM write /// shows (the die's CRAM-dot offset), **not** when pixel 0 leaves the RGB pins: against /// Nuked-MD the pins are 40 master clocks later in H40 and 20 in H32, so a device that /// times its own picture against the Mega Drive's must not take /// `display_at + output_delay * pixel_mclk` as the pins' time (sega32x-python /// docs/worklog.md, Session 9: its first composite was 40 MCLK out from this). `rgb`: /// the finished colour of each pixel, RGB888 -- the DAC's levels, after /// shadow/highlight, CRAM dots and register 0's blanking, as `Renderer::frame_rgb` gives /// it. `ys`: 1 where no plane or sprite pixel shows (the backdrop: YS, per TmEE), 0 /// elsewhere. `shade`: 0 normal, 1 shadow, 2 highlight. #[derive(Clone, Debug, PartialEq, Eq)] pub struct PictureLine { pub row: usize, pub start: i64, pub hmode: HName, pub width: usize, pub pixel_mclk: i64, pub display_at: i64, pub output_delay: i64, pub rgb: Vec, pub ys: Vec, pub shade: Vec, } /// Socket 7: each finished line in, the line that leaves the console out -- RGB888 of /// any width (the 32X draws its own 320 even in H32), or None for the Mega Drive's own. /// /// The returned row is read only when the frame is (`Renderer::frame_rgb`), not when /// `picture_line` returns, so a device may hand back a row and fill it in place until /// then -- what a device with its own CPUs to run first needs of a VDP that renders /// lazily. A device must not reuse a returned row for another line before the frame is /// read. pub trait Picture { fn picture_line(&mut self, line: PictureLine) -> Option; } /// Socket 8: a further sound source beside the FM and the PSG. /// /// `rate`: its sample rate in Hz, which may change between calls (the 32X's PWM follows /// its cycle register). `gain`: what each sample is multiplied by, in the FM's /// summed-DAC units (full scale about +/-6,100) -- a labelled assumption for either /// add-on, since no recording of either mix exists. `take_samples`: run up to master /// clock `mclk` and return the stereo samples finished since the last call, the device's /// own filters already applied. The list covers the whole stretch since the last call: a /// source that starts within it leads with silence back to that call (the board takes a /// source's first non-empty list to start where the stretch does). `rate` describes the /// list just returned, one rate per call; a source whose rate changes within a call /// converts its samples to one rate itself. pub trait AudioSource { fn rate(&self) -> f64; fn gain(&self) -> f64; fn take_samples(&mut self, mclk: i64) -> Vec<(f64, f64)>; }