# SPDX-License-Identifier: MIT """The public core: registers, reset, the run loop, and the S-CPU's side of the chip. The board hands the core the cartridge ROM as ``bytes`` and the Game Pak RAM as the same ``bytearray`` it maps for the S-CPU (handoff-brief bus contract 5); the core decodes the GSU's own map itself. Before every S-CPU access to the cartridge the board runs the core up to that access's time (``run``), so an access always lands between two instructions; then it calls :meth:`GSU.read_io`/:meth:`GSU.write_io` for ``$3000-$34FF``, :meth:`GSU.cpu_rom_byte` for ROM, and checks :attr:`GSU.cpu_owns_ram` for RAM. Time is counted in **input clocks** (the 21.4 MHz unit; timing.py); ``clock`` is the core's own running total. Inside an instruction the core keeps its time exact: fetches, buffer waits, RAM accesses, the multiplier, the pixel write-back. Contested behaviours are class attributes (handoff-brief decision 5): C1 ``STOP_R15_PLUS_TWO``, C6 ``REGISTER_WRITE_LATCH``, C7 ``RESTRICT_ACCESS_WHILE_RUNNING``, C9 ``FMULT_R4_UNCHANGED``, C10 ``INCREMENTAL_CACHE_FILL``, C11 ``IRQ_FLAG_WHEN_MASKED``, C13 ``RAM_READS_CHARGED`` and ``WORD_WRITE_BUFFER``, C15 ``OVERLAPPED_PIXEL_WRITEBACK``, U9 ``CPU_R14_WRITE_PREFETCH``, U14 ``CACHE_WINDOW_BY_ADDRESS``, U20 ``TRANSPARENCY_BY_DEPTH``, the bus WAIT ``WAIT_ON_BUS``. Set one on a subclass or an instance to compare. """ from __future__ import annotations from gsu_python import _sfr from gsu_python._alu import ALUMixin from gsu_python._cache import CacheMixin from gsu_python._decode import TABLE from gsu_python._jump import JumpMixin from gsu_python._memory import MemoryMixin from gsu_python._multiply import MultiplyMixin from gsu_python._plot import PlotMixin from gsu_python._sfr import GO, IRQ, PREFIXES from gsu_python.model import GSU2, MIRRORS_MC1, Model from gsu_python.state import SCALAR_FIELDS, CPUState #: What the S-CPU reads in ROM space while GO = 1 and RON = 1, by address bits 3-0 (BK2 #: tables 2-5-1 and 2-5-2; fullsnes "GSU Interrupt Vectors"; U16): every vector reads 0100h #: but COP 0104h, NMI 0108h and IRQ 010Ch, so the game's handlers sit in WRAM at 00:0100. FIXED_VECTORS = bytes((0x00, 0x01, 0x00, 0x01, 0x04, 0x01, 0x00, 0x01, 0x00, 0x01, 0x08, 0x01, 0x00, 0x01, 0x0C, 0x01)) # fmt: skip _ROM_DATA = frozenset({"getb", "getbh", "getbl", "getbs", "getc", "romb"}) _RAM_DATA = frozenset({"ldw", "ldb", "lm", "lms", "stw", "stb", "sm", "sms", "sbk", "rpix", "ramb"}) class GSU(ALUMixin, MultiplyMixin, MemoryMixin, CacheMixin, PlotMixin, JumpMixin): """A Super FX chip over the cartridge's ROM and RAM. ``rom`` is the cartridge image (``bytes``, read in place, any length > 0); ``ram`` is the Game Pak RAM, a ``bytearray`` the board shares (the core never resizes it; its length is the mask). A new core holds the emulators' power-on state (U26): every register zero, the pipeline NOP, the cache zero; :meth:`reset` is the console's reset. """ #: C6. True (default): an S-CPU write of an even register address only latches the byte; #: the odd address writes ``latch | data << 8`` (fullsnes). False: each byte goes #: straight into the register (ares ``io.cpp`` l.61-67; MAME). REGISTER_WRITE_LATCH = True #: C7. True (default): while GO = 1 the S-CPU reaches only SFR, SCMR (writes) and VCR #: (BK2 chapter 4 preamble, plus SCMR for RON/RAN as fullsnes); other reads #: return ``None`` (the board's open bus) and other writes are ignored. False: everything #: (ares ``io.cpp``; MAME). RESTRICT_ACCESS_WHILE_RUNNING = True #: U9. True (default): an S-CPU write of R14 starts a ROM buffer read (ares ``io.cpp`` l.68). #: False: MAME 0.285. Nothing here decides it. CPU_R14_WRITE_PREFETCH = True #: U15. True (default): an S-CPU write of PBR invalidates the cache (ares ``io.cpp`` #: l.92-95; MAME). PBR_WRITE_FLUSHES_CACHE = True #: BK2 5.3: with RON (RAN) cleared by the S-CPU the GSU WAITs at its next ROM (RAM) #: access until the bit is set again. The core holds before the instruction that needs #: the bus and spends the clocks it is given at once. False: never wait (MAME 0.285). WAIT_ON_BUS = True def __init__(self, rom: bytes, ram: bytearray, *, model: Model = GSU2) -> None: if not isinstance(model, Model): raise TypeError("model must be a Model") if not isinstance(rom, (bytes, bytearray, memoryview)) or len(rom) == 0: raise TypeError("rom must be a non-empty bytes object") if not isinstance(ram, bytearray): raise TypeError("ram must be a bytearray (the board's own buffer)") self.model = model self.rom = rom self.ram = ram self._rom_size = len(rom) self._ram_size = len(ram) self._ms0_implemented = model.ms0_implemented self.cache = bytearray(512) self.cache_loaded = [0] * 32 self.pixel_primary = [-1, 0] + [0] * 8 self.pixel_secondary = [-1, 0] + [0] * 8 self.r = [0] * 16 self._r14_written = False self._r15_written = False self._previous_wrote_r15 = False #: Where the pipeline byte was fetched (PBR:address): the address of the next #: instruction's opcode, exact in a delay slot (MAME's ``pc`` is R15 - 1). self.pipeline_address = 0 # One bound handler per form: _dispatch[mode][opcode] = (handler, n, keeps_prefix). self._dispatch = tuple( tuple((getattr(self, "_op_" + f.key), f.n, f.keeps_prefix) for f in row) for row in TABLE ) self.restore_state(CPUState()) # ----- reset and state ------------------------------------------------------------------- def reset(self) -> None: """The console's reset (BK2 1.5.1: the GSU stops and the buses return to the S-CPU; chapter 4's initial values): R1 = R2 = R15 = 0, SFR = CBR = SCMR = BRAMR = CFGR = CLSR = 0, the cache lines invalid, the pipeline NOP. BK2 calls the other registers "invalid" or "undefined" after reset; the core leaves them as they were (U26).""" self.r[1] = self.r[2] = self.r[15] = 0 self.sfr = 0 self.cbr = 0 self.scmr = 0 self.bramr = 0 self.cfgr = 0 self.clsr = 0 self.sreg = self.dreg = 0 self.pipeline = 0x01 self._flush_cache() self.pixel_primary[1] = 0 def capture_state(self, *, cache: bool = True) -> CPUState: """Everything inside the chip (the cache contents unless ``cache=False``).""" values = {name: getattr(self, name) for name in SCALAR_FIELDS} return CPUState( r=tuple(self.r), cache_loaded=tuple(self.cache_loaded), pixel_primary=tuple(self.pixel_primary), pixel_secondary=tuple(self.pixel_secondary), previous_wrote_r15=self._previous_wrote_r15, cache=bytes(self.cache) if cache else None, **values, ) def restore_state(self, state: CPUState) -> None: """Replace the chip's state (and the cache contents when the state carries them).""" if type(state) is not CPUState: raise TypeError("state must be a CPUState") for name in SCALAR_FIELDS: setattr(self, name, getattr(state, name)) self.r[:] = state.r self.cache_loaded[:] = state.cache_loaded self.pixel_primary[:] = state.pixel_primary self.pixel_secondary[:] = state.pixel_secondary self._previous_wrote_r15 = state.previous_wrote_r15 if state.cache is not None: self.cache[:] = state.cache # ----- execution ------------------------------------------------------------------------- def _set(self, n: int, value: int) -> None: """Write register ``n``. An R14 write starts the ROM buffer at the end of the instruction (BK2 7.1); an R15 write is a jump (no increment after the instruction).""" self.r[n] = value if n >= 14: if n == 15: self._r15_written = True else: self._r14_written = True def step(self) -> int: """Execute one instruction and return its time in input clocks (0 when stopped). The instruction is the pipeline byte decoded in the current prefix state; the byte at R15 is fetched behind it first (U1). Every opcode but a prefix or a branch then clears the prefixes (U3). R15 advances past the fetched byte unless the instruction wrote it. """ if not self.sfr & GO: return 0 start = self.clock sfr = self.sfr handler, n, keeps_prefix = self._dispatch[sfr >> 8 & 3 | sfr >> 10 & 4][self.pipeline] self._r14_written = self._r15_written = False self.pipeline_address = self.pbr << 16 | self.r[15] self.pipeline = self._fetch(self.r[15]) handler(n) if not keeps_prefix: self.sfr &= ~PREFIXES self.sreg = self.dreg = 0 if self._r14_written: self._start_rom_buffer() if not self._r15_written: self.r[15] = (self.r[15] + 1) & 0xFFFF self._previous_wrote_r15 = self._r15_written return self.clock - start def run(self, clocks: int) -> int: """Spend ``clocks`` input clocks: whole instructions while GO = 1, so the time used may pass ``clocks`` by the rest of the last instruction; idle time (GO = 0) and a WAIT on RON/RAN are spent in one step. Returns the clocks used (the board keeps the overshoot as debt).""" if clocks <= 0: return 0 start = self.clock end = start + clocks step = self.step while self.clock < end: if not self.sfr & GO or (self.WAIT_ON_BUS and self.waiting): self.clock = end break step() return self.clock - start def peek_code(self, address: int, bank: int | None = None) -> int: """The opcode byte at ``bank:address`` (default PBR) as a fetch would see it (a valid cache line, else ROM/RAM), with no time and no cache fill: for disassemblers.""" bank = self.pbr if bank is None else bank address &= 0xFFFF if bank == self.pbr and (address - self.cbr) & 0xFFFF < 512: index = address & 0x1FF if self.cache_loaded[index >> 4] > (index & 15): return self.cache[index] return self._read(bank, address) @property def running(self) -> bool: """SFR.GO.""" return bool(self.sfr & GO) @property def waiting(self) -> bool: """True while the next instruction needs a bus the S-CPU has taken back (BK2 5.3).""" scmr = self.scmr if scmr & 0x18 == 0x18 or not self.sfr & GO: return False rom_ok = bool(scmr & 0x10) ram_ok = bool(scmr & 0x08) sfr = self.sfr form = TABLE[sfr >> 8 & 3 | sfr >> 10 & 4][self.pipeline] form_key = form.key for i in range(form.length): # the bytes this instruction fetches: R15, R15 + 1, ... address = (self.r[15] + i) & 0xFFFF index = address & 0x1FF if (address - self.cbr) & 0xFFFF < 512 and self.cache_loaded[index >> 4] > (index & 15): continue if not (rom_ok if self.pbr < 0x60 else ram_ok): return True if not rom_ok and form_key in _ROM_DATA and self.clock < self.rom_ready: return True if not ram_ok: if form_key in _RAM_DATA: return True if form_key == "plot": return self._plot_needs_ram() return False def _plot_needs_ram(self) -> bool: primary = self.pixel_primary if not primary[1]: return False x = self.r[1] & 0xFF offset = (self.r[2] & 0xFF) << 5 | x >> 3 return offset != primary[0] or primary[1] | 1 << ((x & 7) ^ 7) == 0xFF # ----- the S-CPU's side: the register file ($3000-$34FF) --------------------------------- def _fold(self, address: int) -> int | None: """The base register address ``$3000-$303F`` an address answers as (U12, fullsnes "Full I/O Map with Mirrors"), or ``None`` where the chip does not drive the bus.""" if self.model.mirrors == MIRRORS_MC1: # VCR 01h offset = address & 0xFF if offset >= 0x80 or 0x20 <= offset < 0x30: return None if offset < 0x20: return 0x3000 + offset if address < 0x3100 else None if offset < 0x40: return 0x3000 + offset if offset < 0x60: return 0x3000 + (offset & 0x1F) return 0x3030 + (offset & 0x0F) offset = address & 0x3F # VCR 04h: $3000-$303F repeats through $30FF and $3300-$34FF if 0x20 <= offset < 0x30: offset += 0x10 return 0x3000 + offset def read_io(self, address: int) -> int | None: """An S-CPU read of ``address`` (``$3000-$34FF``, bank already decoded). ``None`` where the chip does not drive the bus: the board answers open bus.""" address &= 0xFFFF if not 0x3000 <= address <= self.model.io_end: return None restricted = self.RESTRICT_ACCESS_WHILE_RUNNING and self.sfr & GO if 0x3100 <= address <= 0x32FF: return None if restricted else self.read_cache_window(address - 0x3100) base = self._fold(address) if base is None: return None if restricted and base not in (0x3030, 0x3031, 0x303B): return None if base < 0x3020: value = self.r[base >> 1 & 15] return value >> 8 if base & 1 else value & 0xFF if base == 0x303B: return self.model.vcr if self.model.mirrors == MIRRORS_MC1 and base not in (0x3030, 0x3031): base = 0x3030 | (base & 1) # MC1: $3032-$303F mirror the status register (U12) if base == 0x3030: return self.sfr_value() & 0xFF if base == 0x3031: value = self.sfr_value() >> 8 self.sfr &= ~IRQ # BK2 2-5-5; U11: the read releases /IRQ return value return { 0x3034: self.pbr, 0x3036: self.rombr, 0x303C: self.rambr, 0x303E: self.cbr & 0xFF, 0x303F: self.cbr >> 8, }.get(base, 0) # GSU-2: "unused or write-only ones return 00h" def peek_io(self, address: int) -> int | None: """What :meth:`read_io` would return, without clearing SFR.IRQ (for debuggers).""" sfr = self.sfr value = self.read_io(address) self.sfr = sfr return value def write_io(self, address: int, value: int) -> None: """An S-CPU write. ``$301F`` starts the GSU; SFR with GO = 0 stops it (U8, U10).""" address &= 0xFFFF value &= 0xFF if not 0x3000 <= address <= self.model.io_end: return restricted = self.RESTRICT_ACCESS_WHILE_RUNNING and self.sfr & GO if 0x3100 <= address <= 0x32FF: if not restricted: self.write_cache_window(address - 0x3100, value) return base = self._fold(address) if base is None or (restricted and base not in (0x3030, 0x3031, 0x303A)): return if base < 0x3020: self._write_register(base, value) elif base == 0x3030: # Bits 1-5 (Z, CY, S, OV, GO) are writable (fullsnes "SFR"; BK2 2-5-4). was_running = self.sfr & GO self.sfr = (self.sfr & ~0x3E) | (value & 0x3E) if not was_running and self.sfr & GO: self._start() # U10: GO = 1 restarts at R15 (Dirt Trax FX) if was_running and not self.sfr & GO: # BK2 2-6-11, U10: a forced stop sets CBR = 0 and invalidates the cache. self.cbr = 0 self._flush_cache() elif base == 0x3031: # The high byte as ares (``io.cpp`` l.84-86) and MAME write it: ALT1, ALT2, IL, IH, # B, IRQ. self.sfr = (self.sfr & 0x00FF) | (value << 8 & 0x9F00) elif base == 0x3033: self.bramr = value & 1 elif base == 0x3034: self.pbr = value & 0x7F if self.PBR_WRITE_FLUSHES_CACHE: self._flush_cache() elif base == 0x3037: self.cfgr = value & 0xA0 elif base == 0x3038: self.scbr = value elif base == 0x3039: self.clsr = value & 1 elif base == 0x303A: self.scmr = value & 0x3F # $3036 ROMBR, $303B VCR, $303C RAMBR, $303E-F CBR are read-only. def _write_register(self, base: int, value: int) -> None: n = base >> 1 & 15 if self.REGISTER_WRITE_LATCH: # C6: fullsnes if not base & 1: self.latch = value return self.r[n] = value << 8 | self.latch elif base & 1: # C6: ares, MAME self.r[n] = value << 8 | (self.r[n] & 0xFF) else: self.r[n] = (self.r[n] & 0xFF00) | value if n == 14 and self.CPU_R14_WRITE_PREFETCH: self._start_rom_buffer() # U9 if base == 0x301F: self._start() # U8: writing R15's high byte starts the GSU at R15 def _start(self) -> None: self.sfr |= GO # The pipeline byte (NOP after STOP or power-on) stands for the address before R15. self.pipeline_address = self.pbr << 16 | ((self.r[15] - 1) & 0xFFFF) def sfr_value(self) -> int: """SFR as the S-CPU reads it: the readable bits, with R from the ROM buffer's time.""" value = self.sfr & _sfr.READABLE if self.clock < self.rom_ready: value |= _sfr.R return value # ----- the S-CPU's side: ROM, RAM, /IRQ (U16) -------------------------------------------- def cpu_rom_byte(self, address: int) -> int | None: """The byte the S-CPU reads in ROM space while GO = 1 and RON = 1 (the fixed table, U16), else ``None``: the board reads the ROM.""" if self.sfr & GO and self.scmr & 0x10: return FIXED_VECTORS[address & 0xF] return None @property def cpu_owns_ram(self) -> bool: """False while GO = 1 and RAN = 1: S-CPU reads of Game Pak RAM are open bus and its writes are dropped (U16; handoff-brief decision 6).""" return not (self.sfr & GO and self.scmr & 0x08) @property def irq(self) -> bool: """The cartridge's /IRQ output: SFR.IRQ, unless CFGR bit 7 masks it (BK2 2-5-5).""" return bool(self.sfr & IRQ) and not self.cfgr & 0x80 __all__ = ["FIXED_VECTORS", "GSU"]