# SPDX-License-Identifier: MIT """The 32X's SH-2 side: two SH7604s from sh2-python, their bus, SDRAM and interrupts (milestone 2, docs/handoff-brief.md). **The chips.** Two :class:`sh2_python.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 :class:`~sega32x_python.machine. Quirk` with its documents, hardware and implemented records kept apart. """ from __future__ import annotations from collections.abc import Callable from typing import TYPE_CHECKING from sh2_python import SH7604 from sh2_python.bus import FILL, FIRST if TYPE_CHECKING: from .slot import Sega32X SDRAM_SIZE = 0x40000 # 2 Mbit (Manual 2.1) #: Interrupt sources, as bits of ``pending`` and the level each asserts (Manual 3.2.2). VRES, VINT, HINT, CMD, PWM = 16, 8, 4, 2, 1 LEVELS = ((VRES, 14), (VINT, 12), (HINT, 10), (CMD, 8), (PWM, 6)) def _unwired_read(address: int, width: int, kind: int) -> int: raise RuntimeError("an SH-2 bus cycle before the board wired its callbacks") def _unwired_write(address: int, width: int, value: int, kind: int) -> None: raise RuntimeError("an SH-2 bus cycle before the board wired its callbacks") class SH2Side: """Both SH-2s and what only they reach: SDRAM, the boot ROMs, the interrupt lines.""" def __init__(self, device: Sega32X, master_rom: bytes, slave_rom: bytes) -> None: self.device = device q = device.machine.quirks self.roms = (master_rom, slave_rom) self.sdram = bytearray(SDRAM_SIZE) width = q.sh2_area0_width.value self.chips = ( SH7604(_unwired_read, _unwired_write, mode="master", area0_width=width, on_ftoa=self._ftoa(0), on_txd=self._txd(0)), SH7604(_unwired_read, _unwired_write, mode="slave", area0_width=width, on_ftoa=self._ftoa(1), on_txd=self._txd(1)), ) # fmt: skip self.skew = [0, 0] #: The board's time in SH-2 states the chips have been run to. self.time = 0 self.running = False #: 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. self.pending = [0, 0] self.masks = [0, 0] self.ftoa = [0, 0] #: Blocked on the cartridge while RV = 1 (Manual 3.2.1: "Waits until value becomes #: 0 (RV = 0) before accessing"). self.rv_blocked = [False, False] self.instructions = [0, 0] self.unmapped: list[tuple[int, int, int]] = [] #: The debugger hook: called as ``on_step(index, chip)`` before each step of #: either chip (an instruction, an interrupt's acceptance, or a sleep's states), #: in the order the board runs them. For each access, sh2-python's own hooks: #: ``chip.observe`` sees every CPU access (cache hits too), and wrapping #: ``chip.read``/``chip.write`` sees the external bus cycles with their values #: (sh2-python ``debug.DebugSession`` shows how; :meth:`rewire` undoes it). self.on_step: Callable[[int, SH7604], None] | None = None self._waits = q.sh2_waits.value arbitration = q.sh2_bus_arbitration.value self._slave_request = arbitration["slave_request"] self._master_return = arbitration["master_return"] #: 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``). self.bus_owner = 0 self.bus_start = 0 self.bus_until = 0 #: Per chip, its last cycle (end, address, width, write) for telling an access's #: second port cycle from a new access. self._last = [(-1, 0, 0, False), (-1, 0, 0, False)] self._access_start = [0, 0] #: The frame buffer's write FIFO (``Quirks.sh2_framebuffer_fifo``): the board #: state at which each queued word has left it, oldest first. fifo = q.sh2_framebuffer_fifo.value self.fifo_depth = fifo["depth"] self.fifo_drain = fifo["drain"] self.fb_fifo: list[int] = [] #: The cartridge (``Quirks.cartridge_contention``): the last SH-2 cartridge cycle #: and the 68000's last cartridge access, each (start, end) in board states. self.cart_sh2 = (0, 0) self.cart_m68k = (0, 0) #: Each chip's BSC lists (updated in place by the core when BCR1/2, WCR change). self._cycle_states = [chip.bsc.cycle_states for chip in self.chips] self._bsc_waits = [chip.bsc.waits for chip in self.chips] self._wait_pin = [chip.bsc.wait_pin for chip in self.chips] self.rewire() def rewire(self) -> None: """Give each chip its bus and pin callbacks. They hold their chip and its BSC lists, so they are made once the chips exist (sh2-python: callables are plain attributes that may be replaced); a loaded save state (``savestate.py``) has its chips without them, being closures, and is rewired here.""" for index, chip in enumerate(self.chips): chip.read = self._reader(index) chip.write = self._writer(index) chip.on_ftoa = self._ftoa(index) chip.on_txd = self._txd(index) # -- running ------------------------------------------------------------------------ def set_run(self, run: bool, mclk: int) -> None: """ADEN and RES decide whether the SH-2s run; the step that releases them resets both (power-on reset through their boot ROMs).""" if run == self.running: return self.running = run now = mclk * 3 // 7 self.time = now if run: # Released from reset: nothing pending but CMD, which follows INTM/INTS. self.pending = [0, 0] self.rv_blocked = [False, False] for index, chip in enumerate(self.chips): chip.reset() self.skew[index] = now - chip.clock self._update_irl(index) self.device._cmd_lines() def catch_up(self, mclk: int) -> None: if not self.running: return target = mclk * 3 // 7 if target <= self.time: return self.device.video_lines_to(mclk) # socket 6: lines up to now are published first rv = self.device.rv for index in (0, 1): if self.rv_blocked[index]: if rv: # Still held on the cartridge: the chip waits out the interval. behind = target - (self.chips[index].clock + self.skew[index]) if behind > 0: self.skew[index] += behind else: self.rv_blocked[index] = False self.time = target chips, skew = self.chips, self.skew master, slave = chips vdp = self.device.vdp pwm = self.device.pwm on_step = self.on_step while True: t0 = master.clock + skew[0] t1 = slave.clock + skew[1] index, now = (0, t0) if t0 <= t1 else (1, t1) if now >= target: break if now >= vdp.next_state: # The 32X VDP's events (HINT, VINT, latch, a row drawn) due by this state. vdp.advance(now * 7 // 3) if now >= pwm.next: # A PWM period's end: the FIFOs, the timer interrupt, DREQ1. pwm.run(now) chip = chips[index] if on_step is not None: on_step(index, chip) if chip.dreq1: # DREQ1 is seen by the DMAC at this step's start and dropped after it # (Quirks.pwm_dreq1). chip.step() chip.dreq1 = 0 else: chip.step() self.instructions[index] += 1 pwm.run(target) # -- interrupts ---------------------------------------------------------------------- def _update_irl(self, index: int) -> None: level = 0 active = self.pending[index] & (self.masks[index] | VRES) for source, source_level in LEVELS: if active & source: level = source_level break # /IRL0 is FTOA itself: a low FTOA asserts it (Quirks.ftoa_to_irl0). self.chips[index].irl = level | (self.ftoa[index] ^ 1) def assert_source(self, index: int, source: int) -> None: self.pending[index] |= source self._update_irl(index) def clear_source(self, index: int, source: int) -> None: self.pending[index] &= ~source self._update_irl(index) def set_mask(self, index: int, mask: int) -> None: self.masks[index] = mask & 0x0F self._update_irl(index) def _raise(self, source: int) -> None: """An interrupt source fires: latched on the CPUs whose mask enables it (HINT, PWM; ``Quirks.vint_latch``).""" for index in (0, 1): if self.masks[index] & source: self.assert_source(index, source) def raise_pwm(self) -> None: """The PWM timer (``pwm.py``), latched as HINT is.""" self._raise(PWM) def raise_hint(self) -> None: """HINT from the 32X VDP's HBLANK (``vdp.py``; ``Quirks.hint_counter``).""" self._raise(HINT) def raise_vint(self, on: bool) -> None: """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.""" for index in (0, 1): if on: self.assert_source(index, VINT) elif self.pending[index] & VINT: self.clear_source(index, VINT) # -- the channels' SH-2 ends (docs/domains.md) ----------------------------------------- # # What the rest of the 32X (slot.py, pwm.py) 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. def set_dreq0(self, level: int) -> None: """DREQ0 to both chips' DMAC channel 0: the 68000's FIFO holds a word (``Quirks.dreq_fifo``).""" for chip in self.chips: chip.dreq0 = level def set_dreq1(self, level: int) -> None: """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.""" for chip in self.chips: chip.dreq1 = level def hold(self, index: int, states: int) -> None: """Chip ``index``'s bus cycle under way lasts ``states`` more (a WAIT the device drives: the palette's PEN hold, ``Quirks.palette_wait``).""" self.chips[index].wait += states def state(self, index: int) -> int: """Chip ``index``'s place on the board's time line, in SH-2 states.""" return self.chips[index].clock + self.skew[index] def cycle_end(self, index: int) -> int: """Where chip ``index``'s bus cycle under way stands with the waits added so far.""" chip = self.chips[index] return chip.clock + self.skew[index] + chip.wait def oldest(self) -> int: """The earlier of the two chips' places on the time line.""" return min(chip.clock + self.skew[i] for i, chip in enumerate(self.chips)) def has_source(self, index: int, source: int) -> bool: """Whether ``source`` is asserted on chip ``index``.""" return bool(self.pending[index] & source) # -- pins out ------------------------------------------------------------------------ def _ftoa(self, index: int): def on_ftoa(level: int, clock: int) -> None: self.ftoa[index] = level self._update_irl(index) return on_ftoa def _txd(self, index: int): """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``).""" def on_txd(byte: int, clock: int) -> None: self.chips[index ^ 1].sci.receive(byte) return on_txd # -- the bus ------------------------------------------------------------------------- def _reader(self, index: int): rom = None sdram = self.sdram device = self.device chip = self.chips[index] skew = self.skew cycle_states = self._cycle_states[index] def read(address: int, width: int, kind: int) -> int: nonlocal rom now = chip.clock + skew[index] start = self._arbitrate(index, now, address, width, kind, False) region = address >> 24 if region == 6: # SDRAM: the core's cycle alone (Quirks.sh2_sdram) offset = address & 0x3FFFF if width == 32: value = int.from_bytes(sdram[offset : offset + 4], "big") elif width == 16: value = (sdram[offset] << 8) | sdram[offset + 1] else: value = sdram[offset] self._release(index, now + cycle_states[3] + chip.wait, address, width, False) return value value = 0 if region == 0: if address < 0x4000: self._drive(index, 0, self._waits["boot_rom"]) if rom is None: rom = self.roms[index] offset = address & (len(rom) - 1) if width == 32: value = int.from_bytes(rom[offset : offset + 4], "big") elif width == 16: value = (rom[offset] << 8) | rom[offset + 1] else: value = rom[offset] elif address < 0x4400: value = self._split_read(index, address, width) else: self.unmapped.append((index, address, width)) elif region == 2: value = self._cartridge_read(index, start, address, width) elif region == 4: self._framebuffer_read_wait(index, start) value = device.sh2_framebuffer_read(address, width) else: self.unmapped.append((index, address, width)) end = now + cycle_states[(region >> 1) & 3] + chip.wait if region == 4: self._fifo_after_read(end) self._release(index, end, address, width, False) return value return read def _writer(self, index: int): sdram = self.sdram device = self.device chip = self.chips[index] skew = self.skew cycle_states = self._cycle_states[index] def write(address: int, width: int, value: int, kind: int) -> None: now = chip.clock + skew[index] start = self._arbitrate(index, now, address, width, kind, True) region = address >> 24 if region == 6: offset = address & 0x3FFFF if width == 32: sdram[offset : offset + 4] = value.to_bytes(4, "big") elif width == 16: sdram[offset] = value >> 8 sdram[offset + 1] = value & 0xFF else: sdram[offset] = value self._release(index, now + cycle_states[3] + chip.wait, address, width, True) return if region == 0: if address < 0x4000: self._drive(index, 0, self._waits["boot_rom"]) # the boot ROM: no effect elif address < 0x4400: self._split_write(index, address, width, value) else: self.unmapped.append((index, address, width | 0x100)) elif region == 2: self._cartridge_wait(index, start) cartridge = device.shared_cartridge() offset = address & 0x3FFFFF if width == 8: cartridge.write_byte(offset, value) else: cartridge.write_word(offset, value) elif region == 4: end = self._framebuffer_write_wait(index, start) device.sh2_framebuffer_write(address, width, value) self._release(index, end, address, width, True) return else: self.unmapped.append((index, address, width | 0x100)) end = now + cycle_states[(region >> 1) & 3] + chip.wait if region == 2: self.cart_sh2 = (start, end) self._release(index, end, address, width, True) return write def _drive(self, index: int, area: int, waits: int) -> None: """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).""" extra = waits - self._bsc_waits[index][area] if extra > 0 and self._wait_pin[index][area]: self.chips[index].wait += extra def _arbitrate( self, index: int, now: int, address: int, width: int, kind: int, write: bool ) -> int: """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``.""" end, last_address, last_width, last_write = self._last[index] if now == end and ( (kind & FILL and (address & 2 or not kind & FIRST)) or ( address == last_address + 2 and not last_address & 3 and width == 16 and last_width == 16 and write == last_write ) ): return now # the same access, still on the bus start = now if self.bus_owner != index and self.bus_start <= now: if index == 0: if now < self.bus_until + self._master_return: start = self.bus_until + self._master_return elif now < self.bus_until: start = self.bus_until if index == 1: start = max(start, now + self._slave_request) if start != now: self.chips[index].wait += start - now self._access_start[index] = start return start def _release(self, index: int, end: int, address: int, width: int, write: bool) -> None: """The cycle ends at ``end``: the bus is this chip's, from its access's start, until then.""" 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 ------------------------------------------------- def _fifo_drained(self, now: int) -> list[int]: """The FIFO at ``now``: the words that have left are dropped.""" fifo = self.fb_fifo while fifo and fifo[0] <= now: fifo.pop(0) return fifo def fifo_status(self, now: int) -> tuple[bool, bool]: """(FULL, EMPTY) of the frame buffer's write FIFO at board state ``now`` ($20004006 bits 15 and 14; ``Quirks.sh2_framebuffer_fifo``).""" fifo = self._fifo_drained(now) return len(fifo) >= self.fifo_depth, not fifo def _framebuffer_write_wait(self, index: int, start: int) -> int: """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.""" chip = self.chips[index] self._drive(index, 2, self._waits["framebuffer_write"]) fifo = self._fifo_drained(start) if len(fifo) >= self.fifo_depth: room = fifo.pop(0) chip.wait += room - start start = room end = chip.clock + self.skew[index] + self._cycle_states[index][2] + chip.wait last = fifo[-1] if fifo else 0 fifo.append(max(end, last) + self.fifo_drain) return end def _framebuffer_read_wait(self, index: int, start: int) -> None: """A frame-buffer read waits for the word leaving the FIFO now, then takes the Manual's 5 waits (``Quirks.sh2_framebuffer_fifo``).""" fifo = self._fifo_drained(start) if fifo: leaving = fifo.pop(0) self.chips[index].wait += leaving - start self._drive(index, 2, self._waits["framebuffer_read"]) def _fifo_after_read(self, end: int) -> None: """The FIFO's next word leaves after the read has had the DRAM.""" previous = end fifo = self.fb_fifo for i, leaves in enumerate(fifo): leaves = max(leaves, previous + self.fifo_drain) fifo[i] = previous = leaves # -- the registers ----------------------------------------------------------------- def _split_read(self, index: int, address: int, width: int) -> int: """$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).""" device = self.device self._drive(index, 0, self._register_waits(address)) if width == 32: return (device.sh2_register_read(index, address & ~1) << 16) | ( device.sh2_register_read(index, (address + 2) & ~1) ) word = device.sh2_register_read(index, address & ~1) if width == 16: return word return word & 0xFF if address & 1 else word >> 8 def _split_write(self, index: int, address: int, width: int, value: int) -> None: device = self.device self._drive(index, 0, self._register_waits(address)) if width == 32: device.sh2_register_write(index, address, value >> 16, 0xFFFF) device.sh2_register_write(index, address + 2, value & 0xFFFF, 0xFFFF) elif width == 16: device.sh2_register_write(index, address, value, 0xFFFF) elif address & 1: device.sh2_register_write(index, address & ~1, value, 0x00FF) else: device.sh2_register_write(index, address, value << 8, 0xFF00) def _register_waits(self, address: int) -> int: """Manual 4.1: system registers 1, VDP registers 5, the palette 5 (and its PEN hold, ``Quirks.palette_wait``, added by the device).""" region = address & 0x700 if region == 0: return self._waits["system_register"] if region >= 0x200: return self._waits["palette"] return self._waits["vdp"] # -- the cartridge ------------------------------------------------------------------- def _cartridge_wait(self, index: int, start: int) -> None: """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``).""" chip = self.chips[index] m68k_start, m68k_end = self.cart_m68k if m68k_start <= start < m68k_end: chip.wait += m68k_end - start self._drive(index, 1, self._waits["cartridge"]) if self.device.rv: behind = self.time - (chip.clock + self.skew[index]) if behind > 0: chip.wait += behind self.rv_blocked[index] = True def _cartridge_read(self, index: int, start: int, address: int, width: int) -> int: self._cartridge_wait(index, start) chip = self.chips[index] self.cart_sh2 = (start, chip.clock + self.skew[index] + self._cycle_states[index][1] + chip.wait) # fmt: skip cartridge = self.device.shared_cartridge() offset = address & 0x3FFFFF if width == 32: return (cartridge.read_word(offset) << 16) | cartridge.read_word(offset + 2) if width == 16: return cartridge.read_word(offset) return cartridge.read_byte(offset) def m68k_cartridge(self, mclk: int, length: int) -> int: """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``).""" now = mclk * 3 // 7 start, end = self.cart_sh2 held = 0 if start <= now < end: held = end * 7 // 3 + (1 if end * 7 % 3 else 0) - mclk self.cart_m68k = (now, (mclk + held + length) * 3 // 7) return held __all__ = ["CMD", "HINT", "PWM", "SDRAM_SIZE", "VINT", "VRES", "SH2Side"]