# SPDX-License-Identifier: MIT """The public core: registers, reset, step/run, and the host (parallel) port. The chip has no memory bus: its program ROM, data ROM and data RAM are inside it, so the only interface is the host port (DR/SR through A0, /RD, /WR) and, on the uPD96050, the data RAM the SNES cartridge also maps. The board runs the DSP up to the time of a host access and then calls :meth:`UPD7725.read_sr`, :meth:`UPD7725.read_dr` or :meth:`UPD7725.write_dr`: an access always falls between two instructions (handoff-brief decision 3; C13). One ``step()`` is one instruction is one input clock (DS p.1: "All instructions execute in one instruction cycle"; timing.md). """ from __future__ import annotations from collections.abc import Sequence from upd7725_python._alu import ALUMixin from upd7725_python._jump import JumpMixin from upd7725_python._op import SR_DRC, SR_DRS, SR_RQM, OpMixin from upd7725_python.model import UPD7725_MODEL, UPD96050_MODEL, Model from upd7725_python.state import REGISTER_NAMES, CPUState def _words(name: str, values: Sequence[int], size: int, maximum: int) -> list[int]: if len(values) > size: raise ValueError(f"{name} has {len(values)} words; the chip holds {size}") words = [int(value) for value in values] for value in words: if not 0 <= value <= maximum: raise ValueError(f"{name} words must be in range 0..0x{maximum:X}") # A short image leaves the rest of the ROM zero (a NOP word). return words + [0] * (size - len(words)) class UPD7725(OpMixin, JumpMixin, ALUMixin): """An NEC uPD7725 (or, with ``model=UPD96050_MODEL``, a uPD96050). ``program`` is the instruction ROM as 24-bit words, ``data_rom`` the data ROM as 16-bit words (``images.load_image`` reads the three image formats). A new core holds the power-on state the DS leaves undefined (U18): every register and the RAM zero; call :meth:`reset` as the hardware requires before running. Contested behaviours are class attributes (C1 ``CARRY_BY_COMPARISON``, C2 ``S1_OV1_RULE``, C3 ``ALU_NOP_WHEN_MOVE_TO_ACC``, C4 ``SERIAL_BIT_REVERSE``, C6 ``RESET_SETS_RP``, C11 ``DRS_READS_ZERO_IN_8BIT_MODE``, C16 ``DPL_CLEARS_DP_BITS_10_8``); C5 and C9 are the model's stack depth and widths. Set one on a subclass or an instance to compare. """ #: C6. True (default): reset sets RP = 3FFh (DS (25); fullsnes "Reset"). False: no #: emulator does (ares zeroes everything, MAME leaves RP). RESET_SETS_RP = True #: C11. True (default): SR reads DRS as 0 while DRC = 1 (8-bit mode), as ares does #: (``upd96050.hpp`` l.63); MAME reports the stored bit. The DS defines DRS for 16-bit #: mode only. DRS_READS_ZERO_IN_8BIT_MODE = True def __init__( self, program: Sequence[int], data_rom: Sequence[int] = (), *, model: Model = UPD7725_MODEL, ) -> None: if not isinstance(model, Model): raise TypeError("model must be a Model") self.model = model self.program = _words("program", program, model.program_words, 0xFFFFFF) self.data_rom = _words("data_rom", data_rom, model.data_rom_words, 0xFFFF) self.ram = [0] * model.ram_words self._pc_mask = model.pc_mask self._rp_mask = model.rp_mask self._dp_mask = model.dp_mask self._stack_mask = model.stack_depth - 1 # The serial acknowledge latches (JSIAK/JSOAK, C12). No SNES cartridge clocks the # serial port (U16), so nothing sets them; reset clears them (DS (25)). self.siack = 0 self.soack = 0 self.stack = [0] * model.stack_depth self.restore_state(CPUState(stack=tuple(self.stack))) # ----- execution ------------------------------------------------------------------------ def reset(self) -> None: """The RST input (DS (25)): PC, FLAG A, FLAG B and SR = 0 (with them the P0/P1 pins), the serial acknowledges = 0, RP = 3FFh. "The other registers and contents of DATA RAM are not changed." C6: ``RESET_SETS_RP = False`` keeps RP as the emulators do.""" self.pc = 0 self.flaga = 0 self.flagb = 0 self.sr = 0 self.siack = 0 self.soack = 0 if self.RESET_SETS_RP: self.rp = 0x3FF & self._rp_mask # 3FFh on both chips (uPD96050: fullsnes) def step(self) -> int: """Execute one instruction (U1's order) and return 1, its length in input clocks.""" word = self.program[self.pc] self.pc = (self.pc + 1) & self._pc_mask kind = word >> 22 if kind == 0: # OP self._op(word) elif kind == 1: # RT: the OP, then the return, last (DB p.9) self._op(word) self._return() elif kind == 2: # JP self._jump(word) else: # LD: DST <- the 16-bit immediate (DS p.24); no pointer changes self._move(word & 0xF, word >> 6 & 0xFFFF) # The multiplier runs in every instruction from the K and L it ends with; M and N # show the product from the next instruction (DS (9)-(10), p.26; U3). M = sign and # upper 15 bits of the 31-bit product, N = the lower 15 bits shifted left once. k, l = self.k, self.l product = (k - ((k & 0x8000) << 1)) * (l - ((l & 0x8000) << 1)) self.m = product >> 15 & 0xFFFF self.n = product << 1 & 0xFFFF return 1 def run(self, count: int) -> int: """Execute ``count`` instructions, one ``step`` each (no wait-loop skipping: handoff-brief decision 8). Returns ``count``.""" step = self.step for _ in range(count): step() return count # ----- the host port (DS (17), (19), (20); U7, U20; fullsnes "RQM") --------------------- def read_sr(self) -> int: """A0 = 1, /RD: SR bits 15-8 (RQM USF1 USF0 DRS DMA DRC SOC SIC). No side effect.""" sr = self.sr if self.DRS_READS_ZERO_IN_8BIT_MODE and sr & SR_DRC: sr &= ~SR_DRS # C11 return sr >> 8 def read_dr(self) -> int: """A0 = 0, /RD: one byte of DR. 16-bit mode (DRC = 0): low byte (DRS -> 1), then high byte (DRS -> 0, RQM -> 0). 8-bit mode: DR bits 7-0, RQM -> 0, DRS untouched.""" sr = self.sr if sr & SR_DRC: self.sr = sr & ~SR_RQM return self.dr & 0xFF if not sr & SR_DRS: self.sr = sr | SR_DRS return self.dr & 0xFF self.sr = sr & ~(SR_DRS | SR_RQM) return self.dr >> 8 def peek_dr(self) -> int: """The byte :meth:`read_dr` would return, with no side effect (for debuggers).""" if self.sr & SR_DRC or not self.sr & SR_DRS: return self.dr & 0xFF return self.dr >> 8 def write_dr(self, value: int) -> None: """A0 = 0, /WR: one byte into DR, low byte first in 16-bit mode, with the same DRS/RQM sequence as :meth:`read_dr`. (A0 = 1 writes are "Inhibit", DS (20): the board ignores them; there is no ``write_sr``.)""" value &= 0xFF sr = self.sr if sr & SR_DRC: self.sr = sr & ~SR_RQM self.dr = (self.dr & 0xFF00) | value elif not sr & SR_DRS: self.sr = sr | SR_DRS self.dr = (self.dr & 0xFF00) | value else: self.sr = sr & ~(SR_DRS | SR_RQM) self.dr = value << 8 | (self.dr & 0x00FF) @property def p0(self) -> int: """The P0 output pin: SR bit 0 (DS (17)(a), (18); U17).""" return self.sr & 1 @property def p1(self) -> int: """The P1 output pin: SR bit 1.""" return self.sr >> 1 & 1 # ----- state ---------------------------------------------------------------------------- def capture_state(self, *, ram: bool = True) -> CPUState: """Every register, and the data RAM unless ``ram=False``.""" return CPUState( pc=self.pc, rp=self.rp, dp=self.dp, sp=self.sp, stack=tuple(self.stack), k=self.k, l=self.l, m=self.m, n=self.n, a=self.a, b=self.b, flaga=self.flaga, flagb=self.flagb, tr=self.tr, trb=self.trb, sr=self.sr, dr=self.dr, si=self.si, so=self.so, ram=tuple(self.ram) if ram else None, ) def restore_state(self, state: CPUState) -> None: """Replace the registers (and the RAM, when the state carries it).""" if type(state) is not CPUState: raise TypeError("state must be a CPUState") if len(state.stack) != self.model.stack_depth: raise ValueError(f"stack must have {self.model.stack_depth} entries") if state.ram is not None and len(state.ram) != self.model.ram_words: raise ValueError(f"ram must have {self.model.ram_words} words") for name in REGISTER_NAMES: setattr(self, name, getattr(state, name)) self.pc &= self._pc_mask self.rp &= self._rp_mask self.dp &= self._dp_mask self.stack = list(state.stack) if state.ram is not None: self.ram[:] = state.ram __all__ = ["UPD7725", "UPD7725_MODEL", "UPD96050_MODEL"]