// SPDX-License-Identifier: MIT //! The 32X's SH-2 side: two SH7604s from sh2-rust, their bus, SDRAM and interrupts //! (milestone 2, docs/handoff-brief.md). //! //! **The chips.** Two `sh2::Sh7604`, `mode="master"` and `"slave"` (the MD5 pin; HM //! 7.10), each with its own boot ROM at $00000000 (Manual 3.1: master 2 KB, slave 1 KB; //! the user's own, decision 3) and everything else in common. Each sees the board through //! two callbacks, one external bus cycle per call (sh2-python `bus.py`); cache hits and //! on-chip modules never reach the board. //! //! **The clock.** SH-2 = MCLK x 3/7 exactly (Manual 3.3; the PLL on the slot's VCLK, service //! manual `A406a`), so the board's time in SH-2 states is `mclk * 3 // 7`. Each chip //! keeps its own `clock`; `skew` is what it lost outside its own steps (held while RV //! is 1, below), so its place on the board's time line is `clock + skew`. `catch_up` //! steps whichever chip is furthest behind until both reach the target -- called from //! every 68000 access to 32X space and after every 68000 instruction (sockets 4 and 5). A //! chip overshoots by at most one instruction (an exception sequence included). //! //! **When they run.** The SH-2s are held while ADEN = 0 ("CPU clock runs only when the //! software selectable MARS bit is set", service manual block diagram, `A406a`) and while //! RES = 0 ($A15100 bit 1, "0: Reset", Manual 3.2.1); the step that releases both resets //! them (a power-on reset: PC and SP from the boot ROM's vectors 0 and 1). notaz's comment //! in testpico `x32x_disable` ("sh2s should see no ADEN and sleep") suggests they run //! with ADEN = 0; `Quirks.sh2_clock_needs_aden` keeps both records. //! //! **Interrupts** (Manual 3.2.2): per CPU, VRES 14 (no mask), V 12, H 10, CMD 8, PWM 6, //! masked by that CPU's bits of $20004000; the level reaches /IRL3-/IRL1, and FTOA drives //! /IRL0 directly (32XDK wiki "FRT Bumping", from the schematic), so the level the core //! sees is `level | (1 - FTOA)` (`Quirks.ftoa_to_irl0`). //! //! **The bus** (milestone 5b, docs/timing.md "Bus waits"). Each callback is one cycle; the //! board decides when it may start (`Quirks.sh2_bus_arbitration`: one bus, the slave asking //! for it each access, an access's port cycles and a line fill held together; the cartridge //! against the 68000, `Quirks.cartridge_contention`; the frame buffer's write FIFO, //! `Quirks.sh2_framebuffer_fifo`) and how many WAIT states the device adds beyond the BSC's //! programmed ones (`Quirks.sh2_waits`, `Quirks.sh2_wait_overlap`). The SDRAM's cycles are //! the core's alone: WAIT does not reach them (`Quirks.sh2_sdram`). A cycle's end, which the //! core computes after the callback returns, is its start + the BSC's states + `chip.wait`. //! //! Everything chosen here that a source does not fix is a `Quirk` with its documents, //! hardware and implemented records kept apart. //! //! The reference's `sh2side.py`. What Rust forced: //! - The reference's callbacks are closures over the side and its device. Here each chip //! owns a [`Port`] (sh2-rust's `Bus`), which reaches the device and the board through //! pointers set for the length of a call into the chip (`Sega32X::sh2_with_chip`), and //! the chip is taken out of the side while it runs: its clock, wait, BSC lists and pins //! are then the callback's `BusContext` (sh2-rust's form of `chip.clock`, `chip.wait`, //! `chip.bsc.*`, `chip.irl`), reached through [`Own`]; the other chip is in place. //! - What the reference's side does through its device (the registers, the VDP, the PWM, //! RV, the cartridge) is a method of the device, `Sega32X::sh2_*`, in this file; what it //! does on its own state alone stays a method of [`SH2Side`]. //! - `on_step` (a debugger hook) is not transcribed. use megadrive_rust::board::Devices; use sh2::{BusContext, Mode, Options, Pins, Sh7604, FILL, FIRST}; use crate::machine::{Quirks, Sh2Waits}; use crate::slot::Sega32X; pub const SDRAM_SIZE: usize = 0x40000; // 2 Mbit (Manual 2.1) /// Interrupt sources, as bits of `pending` and the level each asserts (Manual 3.2.2). pub const VRES: u32 = 16; pub const VINT: u32 = 8; pub const HINT: u32 = 4; pub const CMD: u32 = 2; pub const PWM: u32 = 1; pub const LEVELS: [(u32, u32); 5] = [(VRES, 14), (VINT, 12), (HINT, 10), (CMD, 8), (PWM, 6)]; /// A chip's bus (sh2-rust's `Bus`): its index and, for the length of a call into the chip, /// the device and the board (null otherwise: a cycle then is the reference's /// `_unwired_read`). pub struct Port { pub index: usize, pub device: *mut Sega32X, pub board: *mut Devices, } // SAFETY: the pointers are set only for the length of a call into the chip, made by the // thread that holds the device (`Sega32X::sh2_with_chip`), and are null otherwise. unsafe impl Send for Port {} impl Port { fn wired(&mut self) -> (&mut Sega32X, &mut Devices) { assert!(!self.device.is_null(), "an SH-2 bus cycle before the board wired its callbacks"); // SAFETY: set by `sh2_with_chip` from the device and the board it was lent, for the // length of the chip's call; the chip itself is out of the device meanwhile, so the // device reached here holds no reference to it. unsafe { (&mut *self.device, &mut *self.board) } } } impl sh2::Bus for Port { fn read(&mut self, address: u32, width: u32, kind: u32, cx: &mut BusContext) -> u32 { let index = self.index; let (device, board) = self.wired(); device.sh2_read(index, address, width, kind, cx, board) } fn write(&mut self, address: u32, width: u32, value: u32, kind: u32, cx: &mut BusContext) { let index = self.index; let (device, board) = self.wired(); device.sh2_write(index, address, width, value, kind, cx, board); } fn on_ftoa(&mut self, level: u32, _clock: i64, pins: &mut Pins) { let index = self.index; let (device, _) = self.wired(); let sh2 = device.sh2.as_mut().expect("the SH-2 side"); sh2.with_own(index, pins, std::ptr::null_mut(), |sh2| { sh2.ftoa[index] = level; sh2.update_irl(index); }); } /// The two SCIs are crossed: one's TxD is the other's RxD (Manual 5.3), a byte at a /// time with no frame time (`Quirks.sci_link`). fn on_txd(&mut self, byte: u32, _clock: i64, _pins: &mut Pins) { let index = self.index; let (device, _) = self.wired(); device.sh2.as_mut().expect("the SH-2 side").chip(index ^ 1).sci_receive(byte); } } /// The chip running now and its callback's view of itself: `pins` (the callback's, or a /// pin-out's), and `cx` within a bus cycle (null otherwise). #[derive(Clone, Copy)] pub struct Own { pub index: usize, pub pins: *mut Pins, pub cx: *mut BusContext, } // SAFETY: set only for the length of a callback, on the thread making it (`with_own`). unsafe impl Send for Own {} /// Both SH-2s and what only they reach: SDRAM, the boot ROMs, the interrupt lines. pub struct SH2Side { pub roms: [Vec; 2], pub sdram: Vec, pub chips: [Option>>; 2], pub skew: [i64; 2], /// The board's time in SH-2 states the chips have been run to. pub time: i64, pub running: bool, /// Per CPU: the interrupt sources asserted (VRES, VINT, HINT, CMD, PWM bits), the /// mask bits of $20004000 (V 8, H 4, CMD 2, PWM 1: the same positions), FTOA. pub pending: [u32; 2], pub masks: [u32; 2], pub ftoa: [u32; 2], /// Blocked on the cartridge while RV = 1 (Manual 3.2.1: "Waits until value becomes /// 0 (RV = 0) before accessing"). pub rv_blocked: [bool; 2], pub instructions: [u64; 2], pub unmapped: Vec<(usize, u32, u32)>, pub waits: Sh2Waits, pub slave_request: i64, pub master_return: i64, /// The shared bus (Manual 2.2: the master owns it, the slave asks): who used it /// last, and that access's start and end, in board states /// (`Quirks.sh2_bus_arbitration`). pub bus_owner: usize, pub bus_start: i64, pub bus_until: i64, /// Per chip, its last cycle (end, address, width, write) for telling an access's /// second port cycle from a new access. pub last: [(i64, u32, u32, bool); 2], pub access_start: [i64; 2], /// The frame buffer's write FIFO (`Quirks.sh2_framebuffer_fifo`): the board /// state at which each queued word has left it, oldest first. pub fifo_depth: usize, pub fifo_drain: i64, pub fb_fifo: Vec, /// The cartridge (`Quirks.cartridge_contention`): the last SH-2 cartridge cycle /// and the 68000's last cartridge access, each (start, end) in board states. pub cart_sh2: (i64, i64), pub cart_m68k: (i64, i64), /// The chip running now (Rust's form of reaching `self.chips[index]` from inside a /// callback). pub own: Option, /// The lockstep's per-chip CRC of every external bus cycle (None: not traced). pub bus_crc: Option<[u32; 2]>, } impl SH2Side { pub fn new(q: &Quirks, master_rom: Vec, slave_rom: Vec) -> SH2Side { let width = q.sh2_area0_width.value as u32; let chip = |index: usize, mode: Mode| { Box::new(Sh7604::new( Port { index, device: std::ptr::null_mut(), board: std::ptr::null_mut() }, Options { mode, area0_width: width, ..Options::default() }, )) }; let arbitration = q.sh2_bus_arbitration.value; let fifo = q.sh2_framebuffer_fifo.value; SH2Side { roms: [master_rom, slave_rom], sdram: vec![0; SDRAM_SIZE], chips: [Some(chip(0, Mode::Master)), Some(chip(1, Mode::Slave))], skew: [0, 0], time: 0, running: false, pending: [0, 0], masks: [0, 0], ftoa: [0, 0], rv_blocked: [false, false], instructions: [0, 0], unmapped: Vec::new(), waits: q.sh2_waits.value, slave_request: arbitration.slave_request, master_return: arbitration.master_return, bus_owner: 0, bus_start: 0, bus_until: 0, last: [(-1, 0, 0, false), (-1, 0, 0, false)], access_start: [0, 0], fifo_depth: fifo.depth as usize, fifo_drain: fifo.drain, fb_fifo: Vec::new(), cart_sh2: (0, 0), cart_m68k: (0, 0), own: None, bus_crc: None, } } /// Chip `index`, in place (not the one running a callback: its state is the /// callback's). pub fn chip(&mut self, index: usize) -> &mut Sh7604 { self.chips[index].as_deref_mut().expect("this chip is running: reach it through Own") } pub fn chip_ref(&self, index: usize) -> &Sh7604 { self.chips[index].as_deref().expect("this chip is running") } fn own_index(&self, index: usize) -> Option { self.own.filter(|own| own.index == index) } /// Run `f` with chip `index`'s callback view set (`pins`, and `cx` within a cycle). pub fn with_own( &mut self, index: usize, pins: *mut Pins, cx: *mut BusContext, f: impl FnOnce(&mut Self) -> R, ) -> R { let before = self.own.replace(Own { index, pins, cx }); let out = f(self); self.own = before; out } // -- the chip's fields, wherever the chip is --------------------------------------- /// `chip.clock`. pub fn clock(&self, index: usize) -> i64 { match self.own_index(index) { // SAFETY: `cx` is the running callback's, alive for its length. Some(own) if !own.cx.is_null() => unsafe { (*own.cx).clock }, Some(_) => panic!("chip.clock outside a bus cycle of the running chip"), None => self.chip_ref(index).clock, } } /// `chip.wait`. pub fn wait(&self, index: usize) -> i64 { match self.own_index(index) { // SAFETY: as in `clock`. Some(own) if !own.cx.is_null() => unsafe { (*own.cx).wait }, Some(_) => panic!("chip.wait outside a bus cycle of the running chip"), None => self.chip_ref(index).wait, } } /// `chip.wait += states`. pub fn add_wait(&mut self, index: usize, states: i64) { match self.own_index(index) { // SAFETY: as in `clock`. Some(own) if !own.cx.is_null() => unsafe { (*own.cx).wait += states }, Some(_) => panic!("chip.wait outside a bus cycle of the running chip"), None => self.chip(index).wait += states, } } /// The BSC's lists of the running chip: `cycle_states`, `waits`, `wait_pin`. fn cx(&self, index: usize) -> &BusContext { let own = self.own_index(index).expect("the BSC's lists inside the chip's own cycle"); assert!(!own.cx.is_null(), "the BSC's lists inside the chip's own cycle"); // SAFETY: as in `clock`. unsafe { &*own.cx } } fn set_pin(&mut self, index: usize, f: impl Fn(&mut Pins)) { match self.own_index(index) { Some(own) => { // SAFETY: `pins` is the running callback's or pin-out's, alive for its length. unsafe { f(&mut *own.pins) } } None => { let chip = self.chip(index); let mut pins = chip.pins(); f(&mut pins); chip.set_pins(pins); } } } // -- interrupts ---------------------------------------------------------------------- pub fn update_irl(&mut self, index: usize) { let mut level = 0; let active = self.pending[index] & (self.masks[index] | VRES); for (source, source_level) in LEVELS { if active & source != 0 { level = source_level; break; } } // /IRL0 is FTOA itself: a low FTOA asserts it (Quirks.ftoa_to_irl0). let irl = level | (self.ftoa[index] ^ 1); self.set_pin(index, |pins| pins.irl = irl); } pub fn assert_source(&mut self, index: usize, source: u32) { self.pending[index] |= source; self.update_irl(index); } pub fn clear_source(&mut self, index: usize, source: u32) { self.pending[index] &= !source; self.update_irl(index); } pub fn set_mask(&mut self, index: usize, mask: u32) { self.masks[index] = mask & 0x0F; self.update_irl(index); } /// An interrupt source fires: latched on the CPUs whose mask enables it (HINT, /// PWM; `Quirks.vint_latch`). fn raise(&mut self, source: u32) { for index in 0..2 { if self.masks[index] & source != 0 { self.assert_source(index, source); } } } /// The PWM timer (`pwm.rs`), latched as HINT is. pub fn raise_pwm(&mut self) { self.raise(PWM); } /// HINT from the 32X VDP's HBLANK (`vdp.rs`; `Quirks.hint_counter`). pub fn raise_hint(&mut self) { self.raise(HINT); } /// VBLANK's edges from the 32X VDP (`Quirks.vint_latch`, `Quirks.vint_at`): VINT /// asserts on both CPUs whatever their masks and stays for the rest of VBlank or until /// cleared; VBLANK's end takes it away. pub fn raise_vint(&mut self, on: bool) { for index in 0..2 { if on { self.assert_source(index, VINT); } else if self.pending[index] & VINT != 0 { self.clear_source(index, VINT); } } } // -- the channels' SH-2 ends (docs/domains.md) ----------------------------------------- // // What the rest of the 32X (slot.rs, pwm.rs) may do to the SH-2 pair, by name, so no // other module reaches into a chip. Each is a line or a time the pair shares with the // 68000's side, the VDP or the PWM; none changes what it carries. /// DREQ0 to both chips' DMAC channel 0: the 68000's FIFO holds a word /// (`Quirks.dreq_fifo`). pub fn set_dreq0(&mut self, level: u32) { for index in 0..2 { self.set_pin(index, |pins| pins.dreq0 = level); } } /// DREQ1 to both chips' DMAC channel 1: the PWM timer with RTP (`Quirks.pwm_dreq1`); /// `catch_up` drops it after each chip's next step. pub fn set_dreq1(&mut self, level: u32) { for index in 0..2 { self.set_pin(index, |pins| pins.dreq1 = level); } } /// Chip `index`'s bus cycle under way lasts `states` more (a WAIT the device /// drives: the palette's PEN hold, `Quirks.palette_wait`). pub fn hold(&mut self, index: usize, states: i64) { self.add_wait(index, states); } /// Chip `index`'s place on the board's time line, in SH-2 states. pub fn state(&self, index: usize) -> i64 { self.clock(index) + self.skew[index] } /// Where chip `index`'s bus cycle under way stands with the waits added so far. pub fn cycle_end(&self, index: usize) -> i64 { self.clock(index) + self.skew[index] + self.wait(index) } /// The earlier of the two chips' places on the time line. pub fn oldest(&self) -> i64 { (0..2).map(|i| self.chip_ref(i).clock + self.skew[i]).min().expect("two chips") } /// Whether `source` is asserted on chip `index`. pub fn has_source(&self, index: usize, source: u32) -> bool { self.pending[index] & source != 0 } // -- the bus ------------------------------------------------------------------------- /// The device's WAIT for a cycle that the Manual gives `waits` waits (a cycle of /// 2 + `waits` states): what the BSC's programmed waits for the area do not already /// cover, and nothing if WCR does not sample WAIT there (`Quirks.sh2_wait_overlap`; /// HM 7.2.3, 7.4.2). fn drive(&mut self, index: usize, area: usize, waits: i64) { let cx = self.cx(index); let extra = waits - cx.waits[area]; if extra > 0 && cx.wait_pin[area] { self.add_wait(index, extra); } } /// When the cycle that wants to start at `now` may start, with the delay added to /// `chip.wait` (`Quirks.sh2_bus_arbitration`). An access's second port cycle and a /// line fill's later cycles follow on the bus their first took (HM 7.10: no release /// within them). Otherwise the slave asks for the bus (`slave_request` states), a /// cycle waits for the other chip's access under way, and the master taking the bus /// back from a slave access that has just ended waits `master_return`. fn arbitrate(&mut self, index: usize, now: i64, address: u32, width: u32, kind: u32, write: bool) -> i64 { let (end, last_address, last_width, last_write) = self.last[index]; if now == end && ((kind & FILL != 0 && (address & 2 != 0 || kind & FIRST == 0)) || (address == last_address.wrapping_add(2) && last_address & 3 == 0 && width == 16 && last_width == 16 && write == last_write)) { return now; // the same access, still on the bus } let mut start = now; if self.bus_owner != index && self.bus_start <= now { if index == 0 { if now < self.bus_until + self.master_return { start = self.bus_until + self.master_return; } } else if now < self.bus_until { start = self.bus_until; } } if index == 1 { start = start.max(now + self.slave_request); } if start != now { self.add_wait(index, start - now); } self.access_start[index] = start; start } /// The cycle ends at `end`: the bus is this chip's, from its access's start, until /// then. fn release(&mut self, index: usize, end: i64, address: u32, width: u32, write: bool) { self.bus_start = self.access_start[index]; self.bus_owner = index; self.bus_until = end; self.last[index] = (end, address, width, write); } // -- the frame buffer's write FIFO ------------------------------------------------- /// The FIFO at `now`: the words that have left are dropped. fn fifo_drained(&mut self, now: i64) { let fifo = &mut self.fb_fifo; let gone = fifo.iter().take_while(|&&leaves| leaves <= now).count(); fifo.drain(..gone); } /// (FULL, EMPTY) of the frame buffer's write FIFO at board state `now` /// ($20004006 bits 15 and 14; `Quirks.sh2_framebuffer_fifo`). pub fn fifo_status(&mut self, now: i64) -> (bool, bool) { self.fifo_drained(now); (self.fb_fifo.len() >= self.fifo_depth, self.fb_fifo.is_empty()) } /// A frame-buffer write cycle from `start`: room in the FIFO at once (the BSC's /// cycle and the Manual's minimum, 3 clocks) or a wait for its oldest word to leave; /// the word is queued to leave `drain` states after the one before it, or after the /// cycle ends. Returns the cycle's end. fn framebuffer_write_wait(&mut self, index: usize, start: i64) -> i64 { self.drive(index, 2, self.waits.framebuffer_write); self.fifo_drained(start); if self.fb_fifo.len() >= self.fifo_depth { let room = self.fb_fifo.remove(0); self.add_wait(index, room - start); } let end = self.clock(index) + self.skew[index] + self.cx(index).cycle_states[2] + self.wait(index); let last = self.fb_fifo.last().copied().unwrap_or(0); self.fb_fifo.push(end.max(last) + self.fifo_drain); end } /// A frame-buffer read waits for the word leaving the FIFO now, then takes the /// Manual's 5 waits (`Quirks.sh2_framebuffer_fifo`). fn framebuffer_read_wait(&mut self, index: usize, start: i64) { self.fifo_drained(start); if !self.fb_fifo.is_empty() { let leaving = self.fb_fifo.remove(0); self.add_wait(index, leaving - start); } self.drive(index, 2, self.waits.framebuffer_read); } /// The FIFO's next word leaves after the read has had the DRAM. fn fifo_after_read(&mut self, end: i64) { let mut previous = end; for leaves in self.fb_fifo.iter_mut() { let value = (*leaves).max(previous + self.fifo_drain); *leaves = value; previous = value; } } /// Manual 4.1: system registers 1, VDP registers 5, the palette 5 (and its PEN /// hold, `Quirks.palette_wait`, added by the device). fn register_waits(&self, address: u32) -> i64 { let region = address & 0x700; if region == 0 { return self.waits.system_register; } if region >= 0x200 { return self.waits.palette; } self.waits.vdp } /// A 68000 cartridge access at `mclk` taking `length` master clocks: the master /// clocks it is held for an SH-2 cartridge cycle under way, and its time on the /// cartridge noted for the SH-2s (`Quirks.cartridge_contention`). pub fn m68k_cartridge(&mut self, mclk: i64, length: i64) -> i64 { let now = mclk * 3 / 7; let (start, end) = self.cart_sh2; let mut held = 0; if start <= now && now < end { held = end * 7 / 3 + i64::from(end * 7 % 3 != 0) - mclk; } self.cart_m68k = (now, (mclk + held + length) * 3 / 7); held } fn trace_cycle(&mut self, index: usize, address: u32, width: u32, value: u32, kind: u32, write: bool, start: i64) { if let Some(crcs) = self.bus_crc.as_mut() { let mut data = Vec::with_capacity(32); data.extend_from_slice(&address.to_le_bytes()); data.extend_from_slice(&width.to_le_bytes()); data.extend_from_slice(&value.to_le_bytes()); data.extend_from_slice(&kind.to_le_bytes()); data.push(u8::from(write)); data.extend_from_slice(&start.to_le_bytes()); crcs[index] = crate::trace::crc32_update(crcs[index], &data); } } } // -- what the side does through its device --------------------------------------------- impl Sega32X { fn side(&mut self) -> &mut SH2Side { self.sh2.as_mut().expect("the SH-2 side") } /// Call into chip `index` (a step, a reset): the chip is taken out of the side for /// the call, and its bus is given the device and `board` (the reference's callbacks /// keep both). pub fn sh2_with_chip(&mut self, index: usize, board: &mut Devices, f: impl FnOnce(&mut Sh7604) -> R) -> R { let mut chip = self.side().chips[index].take().expect("the chip in place"); chip.bus.device = self as *mut Sega32X; chip.bus.board = board as *mut Devices; let out = f(&mut chip); chip.bus.device = std::ptr::null_mut(); chip.bus.board = std::ptr::null_mut(); self.side().chips[index] = Some(chip); out } // -- running ------------------------------------------------------------------------ /// ADEN and RES decide whether the SH-2s run; the step that releases them resets /// both (power-on reset through their boot ROMs). pub fn sh2_set_run(&mut self, run: bool, mclk: i64, board: Option<&mut Devices>) { let sh2 = self.side(); if run == sh2.running { return; } sh2.running = run; let now = mclk * 3 / 7; sh2.time = now; if run { // Released from reset: nothing pending but CMD, which follows INTM/INTS. let board = board.expect("the board, to reset the SH-2s"); sh2.pending = [0, 0]; sh2.rv_blocked = [false, false]; for index in 0..2 { self.sh2_with_chip(index, board, |chip| chip.reset(true)); let sh2 = self.side(); sh2.skew[index] = now - sh2.chip(index).clock; sh2.update_irl(index); } self.cmd_lines(); } } pub fn sh2_catch_up(&mut self, mclk: i64, board: &mut Devices) { if !self.side().running { return; } let target = mclk * 3 / 7; if target <= self.side().time { return; } self.video_lines_to(mclk); // socket 6: lines up to now are published first let rv = self.rv(); let sh2 = self.side(); for index in 0..2 { if sh2.rv_blocked[index] { if rv { // Still held on the cartridge: the chip waits out the interval. let behind = target - (sh2.chip(index).clock + sh2.skew[index]); if behind > 0 { sh2.skew[index] += behind; } } else { sh2.rv_blocked[index] = false; } } } sh2.time = target; loop { let sh2 = self.side(); let t0 = sh2.chip(0).clock + sh2.skew[0]; let t1 = sh2.chip(1).clock + sh2.skew[1]; let (index, now) = if t0 <= t1 { (0, t0) } else { (1, t1) }; if now >= target { break; } if now >= self.vdp.next_state { // The 32X VDP's events (HINT, VINT, latch, a row drawn) due by this state. let (vdp, mut links) = self.vdp_links(); vdp.advance(now * 7 / 3, &mut links); } if now >= self.pwm.next { // A PWM period's end: the FIFOs, the timer interrupt, DREQ1. let (pwm, mut links) = self.pwm_links(); pwm.run(now, &mut links); } if self.side().chip(index).dreq1 != 0 { // DREQ1 is seen by the DMAC at this step's start and dropped after it // (Quirks.pwm_dreq1). self.sh2_with_chip(index, board, |chip| chip.step()); self.side().chip(index).dreq1 = 0; } else { self.sh2_with_chip(index, board, |chip| chip.step()); } self.side().instructions[index] += 1; } let (pwm, mut links) = self.pwm_links(); pwm.run(target, &mut links); } // -- the bus ------------------------------------------------------------------------- /// One read cycle of chip `index` (the reference's `_reader` closure). #[allow(clippy::too_many_arguments)] pub fn sh2_read( &mut self, index: usize, address: u32, width: u32, kind: u32, cx: &mut BusContext, board: &mut Devices, ) -> u32 { let pins: *mut Pins = &mut cx.pins; let cx_ptr: *mut BusContext = cx; let before = self.side().own.replace(Own { index, pins, cx: cx_ptr }); let start_clock = self.side().clock(index); let value = self.sh2_read_cycle(index, address, width, kind, board); let sh2 = self.side(); sh2.trace_cycle(index, address, width, value, kind, false, start_clock); sh2.own = before; value } fn sh2_read_cycle(&mut self, index: usize, address: u32, width: u32, kind: u32, board: &mut Devices) -> u32 { let sh2 = self.side(); let now = sh2.clock(index) + sh2.skew[index]; let start = sh2.arbitrate(index, now, address, width, kind, false); let region = address >> 24; if region == 6 { // SDRAM: the core's cycle alone (Quirks.sh2_sdram) let offset = (address & 0x3FFFF) as usize; let sdram = &sh2.sdram; let value = match width { 32 => u32::from_be_bytes([sdram[offset], sdram[offset + 1], sdram[offset + 2], sdram[offset + 3]]), 16 => u32::from(sdram[offset]) << 8 | u32::from(sdram[offset + 1]), _ => u32::from(sdram[offset]), }; let end = now + sh2.cx(index).cycle_states[3] + sh2.wait(index); sh2.release(index, end, address, width, false); return value; } let mut value = 0; if region == 0 { if address < 0x4000 { let waits = sh2.waits.boot_rom; sh2.drive(index, 0, waits); let rom = &sh2.roms[index]; let offset = (address as usize) & (rom.len() - 1); value = match width { 32 => u32::from_be_bytes([rom[offset], rom[offset + 1], rom[offset + 2], rom[offset + 3]]), 16 => u32::from(rom[offset]) << 8 | u32::from(rom[offset + 1]), _ => u32::from(rom[offset]), }; } else if address < 0x4400 { value = self.sh2_split_read(index, address, width, board); } else { sh2.unmapped.push((index, address, width)); } } else if region == 2 { value = self.sh2_cartridge_read(index, start, address, width, board); } else if region == 4 { self.side().framebuffer_read_wait(index, start); value = self.sh2_framebuffer_read(address, width); } else { sh2.unmapped.push((index, address, width)); } let sh2 = self.side(); let end = now + sh2.cx(index).cycle_states[((region >> 1) & 3) as usize] + sh2.wait(index); if region == 4 { sh2.fifo_after_read(end); } sh2.release(index, end, address, width, false); value } /// One write cycle of chip `index` (the reference's `_writer` closure). #[allow(clippy::too_many_arguments)] pub fn sh2_write( &mut self, index: usize, address: u32, width: u32, value: u32, kind: u32, cx: &mut BusContext, board: &mut Devices, ) { let pins: *mut Pins = &mut cx.pins; let cx_ptr: *mut BusContext = cx; let before = self.side().own.replace(Own { index, pins, cx: cx_ptr }); let start_clock = self.side().clock(index); self.sh2_write_cycle(index, address, width, value, kind, board); let sh2 = self.side(); sh2.trace_cycle(index, address, width, value, kind, true, start_clock); sh2.own = before; } fn sh2_write_cycle(&mut self, index: usize, address: u32, width: u32, value: u32, kind: u32, board: &mut Devices) { let sh2 = self.side(); let now = sh2.clock(index) + sh2.skew[index]; let start = sh2.arbitrate(index, now, address, width, kind, true); let region = address >> 24; if region == 6 { let offset = (address & 0x3FFFF) as usize; let sdram = &mut sh2.sdram; match width { 32 => sdram[offset..offset + 4].copy_from_slice(&value.to_be_bytes()), 16 => { sdram[offset] = (value >> 8) as u8; sdram[offset + 1] = value as u8; } _ => sdram[offset] = value as u8, } let end = now + sh2.cx(index).cycle_states[3] + sh2.wait(index); sh2.release(index, end, address, width, true); return; } if region == 0 { if address < 0x4000 { let waits = sh2.waits.boot_rom; sh2.drive(index, 0, waits); // the boot ROM: no effect } else if address < 0x4400 { self.sh2_split_write(index, address, width, value, board); } else { sh2.unmapped.push((index, address, width | 0x100)); } } else if region == 2 { self.sh2_cartridge_wait(index, start); let cartridge = self.shared_cartridge(board); let offset = address & 0x3FFFFF; if width == 8 { cartridge.write_byte(offset, value as u8); } else { cartridge.write_word(offset, value as u16); } } else if region == 4 { let end = self.side().framebuffer_write_wait(index, start); self.sh2_framebuffer_write(address, width, value); self.side().release(index, end, address, width, true); return; } else { sh2.unmapped.push((index, address, width | 0x100)); } let sh2 = self.side(); let end = now + sh2.cx(index).cycle_states[((region >> 1) & 3) as usize] + sh2.wait(index); if region == 2 { sh2.cart_sh2 = (start, end); } sh2.release(index, end, address, width, true); } // -- the registers ----------------------------------------------------------------- /// $4000-$43FF, the registers: word-wide; a longword is two words (with CS0 16 bits /// wide, `Quirks.sh2_area0_width`, the core already splits it). fn sh2_split_read(&mut self, index: usize, address: u32, width: u32, board: &mut Devices) -> u32 { let sh2 = self.side(); let waits = sh2.register_waits(address); sh2.drive(index, 0, waits); if width == 32 { let high = u32::from(self.sh2_register_read(index, address & !1, board)); let low = u32::from(self.sh2_register_read(index, (address + 2) & !1, board)); return (high << 16) | low; } let word = u32::from(self.sh2_register_read(index, address & !1, board)); if width == 16 { return word; } if address & 1 != 0 { word & 0xFF } else { word >> 8 } } fn sh2_split_write(&mut self, index: usize, address: u32, width: u32, value: u32, board: &mut Devices) { let sh2 = self.side(); let waits = sh2.register_waits(address); sh2.drive(index, 0, waits); if width == 32 { self.sh2_register_write(index, address, (value >> 16) as u16, 0xFFFF, board); self.sh2_register_write(index, address + 2, value as u16, 0xFFFF, board); } else if width == 16 { self.sh2_register_write(index, address, value as u16, 0xFFFF, board); } else if address & 1 != 0 { self.sh2_register_write(index, address & !1, value as u16, 0x00FF, board); } else { self.sh2_register_write(index, address, (value << 8) as u16, 0xFF00, board); } } // -- the cartridge ------------------------------------------------------------------- /// The cartridge from an SH-2: its waits; a 68000 cartridge access under way first /// (`Quirks.cartridge_contention`); and while RV = 1 the chip waits for the 68000 to /// clear it (Manual 3.2.1). The board can only hold the chip to the time it has been /// asked to run to; `catch_up` holds it on while RV stays 1 (`skew`). The access /// itself is made now (`Quirks.rv_stall`). fn sh2_cartridge_wait(&mut self, index: usize, start: i64) { let rv = self.rv(); let sh2 = self.side(); let (m68k_start, m68k_end) = sh2.cart_m68k; if m68k_start <= start && start < m68k_end { sh2.add_wait(index, m68k_end - start); } let waits = sh2.waits.cartridge; sh2.drive(index, 1, waits); if rv { let behind = sh2.time - (sh2.clock(index) + sh2.skew[index]); if behind > 0 { sh2.add_wait(index, behind); } sh2.rv_blocked[index] = true; } } fn sh2_cartridge_read(&mut self, index: usize, start: i64, address: u32, width: u32, board: &mut Devices) -> u32 { self.sh2_cartridge_wait(index, start); let sh2 = self.side(); let end = sh2.clock(index) + sh2.skew[index] + sh2.cx(index).cycle_states[1] + sh2.wait(index); sh2.cart_sh2 = (start, end); let cartridge = self.shared_cartridge(board); let offset = address & 0x3FFFFF; match width { 32 => (u32::from(cartridge.read_word(offset)) << 16) | u32::from(cartridge.read_word(offset + 2)), 16 => u32::from(cartridge.read_word(offset)), _ => u32::from(cartridge.read_byte(offset)), } } }