# SPDX-License-Identifier: MIT """The minimal harness: the core plus a scripted host (validation.md "The minimal harness"). No S-CPU, no cartridge map, no clock ratio: the host waits for RQM by running the DSP, then moves one byte through :meth:`UPD7725.write_dr` or :meth:`UPD7725.read_dr`, exactly as a game's polling loop would, and counts the instructions the DSP spent. ``command`` sends a command and its parameters and reads its results; ``run_to_idle`` stops in the program's ``JRQM $`` wait. The ST010/ST011 data RAM is ``harness.dsp.ram`` (words) with the byte view the SNES sees in :meth:`read_ram_byte`/:meth:`write_ram_byte` (U21). """ from __future__ import annotations from collections.abc import Callable, Iterable from dataclasses import dataclass from upd7725_python._fields import JP, brch, kind, na from upd7725_python.cpu import UPD7725 from upd7725_python.images import load_image, model_for from upd7725_python.model import Model JRQM = 0x0BE SR_RQM = 0x8000 SR_DRC = 0x0400 DEFAULT_BUDGET = 2_000_000 # Instructions the DSP runs after each host access before the host can make another. A real # S-CPU needs at least one 8-clock cycle (about 3 DSP instructions at 7.6 MHz) between # accesses and a polling loop many more; the programs rely on it: the DSP-1 reads a command # in 8-bit mode and only then switches DR to 16 bits, so a host that answered RQM in zero # time would write the first parameter byte in the wrong mode. DEFAULT_HOST_DELAY = 16 class HostTimeout(RuntimeError): """The DSP did not raise RQM (or reach its idle loop) within the instruction budget.""" @dataclass(frozen=True, slots=True) class HostAccess: """One host access: ``"R"``/``"W"``, ``"DR"``/``"SR"``, the byte, and the number of instructions the DSP had executed when it happened.""" direction: str port: str value: int instructions: int class Harness: """A scripted host around one core. ``step`` lets a caller (the tracer) take over the instruction loop; it must execute exactly one instruction.""" def __init__( self, program: list[int], data_rom: list[int], model: Model | None = None, *, reset: bool = True, dsp: UPD7725 | None = None, host_delay: int = DEFAULT_HOST_DELAY, ) -> None: self.dsp = ( dsp if dsp is not None else UPD7725(program, data_rom, model=model or model_for(program)) ) if reset: self.dsp.reset() self.instructions = 0 self.host_delay = host_delay self.log: list[HostAccess] = [] self.step: Callable[[], int] = self.dsp.step @classmethod def from_image(cls, source, **kwargs) -> Harness: program, data_rom = load_image(source) return cls(program, data_rom, **kwargs) # ----- running --------------------------------------------------------------------------- def idle(self) -> bool: """Whether the DSP sits in a ``JRQM $`` wait with RQM = 1.""" dsp = self.dsp word = dsp.program[dsp.pc] return ( kind(word) == JP and brch(word) == JRQM and na(word) == dsp.pc & 0x7FF and bool(dsp.sr & SR_RQM) ) def run(self, count: int) -> None: step = self.step for _ in range(count): step() self.instructions += count def run_until(self, condition: Callable[[], bool], budget: int = DEFAULT_BUDGET) -> int: """Step until ``condition()`` holds (checked before each instruction); returns the instructions spent, or raises :class:`HostTimeout`.""" step = self.step for spent in range(budget + 1): if condition(): self.instructions += spent return spent if spent < budget: step() self.instructions += budget raise HostTimeout(f"no progress after {budget} instructions (pc {self.dsp.pc:04X})") def run_to_idle(self, budget: int = DEFAULT_BUDGET) -> int: return self.run_until(self.idle, budget) def wait_rqm(self, budget: int = DEFAULT_BUDGET) -> int: dsp = self.dsp return self.run_until(lambda: bool(dsp.sr & SR_RQM), budget) # ----- the host's side of the port ------------------------------------------------------- def read_sr(self) -> int: value = self.dsp.read_sr() self.log.append(HostAccess("R", "SR", value, self.instructions)) return value def write_byte(self, value: int, budget: int = DEFAULT_BUDGET) -> None: """Wait for RQM, then write one byte of DR.""" self.wait_rqm(budget) self.dsp.write_dr(value) self.log.append(HostAccess("W", "DR", value & 0xFF, self.instructions)) self.run(self.host_delay) def read_byte(self, budget: int = DEFAULT_BUDGET) -> int: """Wait for RQM, then read one byte of DR.""" self.wait_rqm(budget) value = self.dsp.read_dr() self.log.append(HostAccess("R", "DR", value, self.instructions)) self.run(self.host_delay) return value def write_word(self, value: int, budget: int = DEFAULT_BUDGET) -> None: """A 16-bit transfer: low byte, then high byte (16-bit mode, DRC = 0).""" self.write_byte(value & 0xFF, budget) self.write_byte(value >> 8 & 0xFF, budget) def read_word(self, budget: int = DEFAULT_BUDGET) -> int: low = self.read_byte(budget) return self.read_byte(budget) << 8 | low def command( self, code: int, parameters: Iterable[int] = (), results: int = 0, *, command_word: bool = False, budget: int = DEFAULT_BUDGET, ) -> list[int]: """Send a command (a byte, or a 16-bit word with ``command_word``, as the DSP-4 takes them), its 16-bit parameters, and read ``results`` 16-bit words.""" if command_word: self.write_word(code, budget) else: self.write_byte(code, budget) for value in parameters: self.write_word(value, budget) return [self.read_word(budget) for _ in range(results)] # ----- the uPD96050's data RAM as the SNES sees it (U21; the board's byte split) ------- def read_ram_byte(self, address: int) -> int: word = self.dsp.ram[address >> 1 & (len(self.dsp.ram) - 1)] return word >> 8 if address & 1 else word & 0xFF def write_ram_byte(self, address: int, value: int) -> None: index = address >> 1 & (len(self.dsp.ram) - 1) word = self.dsp.ram[index] if address & 1: self.dsp.ram[index] = (value & 0xFF) << 8 | (word & 0xFF) else: self.dsp.ram[index] = (word & 0xFF00) | (value & 0xFF) __all__ = ["DEFAULT_BUDGET", "DEFAULT_HOST_DELAY", "Harness", "HostAccess", "HostTimeout"]