# SPDX-License-Identifier: MIT AND ISC """The S-SMP around spc700-python: the I/O page $F0-$FF, the IPL ROM overlay, the timers, the four CPU ports, and the S-DSP clocked once per S-SMP clock. Sources (evidence tags as in the DSP module): fullsnes "SNES APU SPC700 I/O Ports", "SNES APU Memory and I/O Map" and "SNES APU Main CPU Communication Port" (DOC fullsnes); anomie's S-DSP document (DOC anomie: the timer ticks' steps); and ares ``ares/sfc/smp`` (pinned 9408cb43; ISC, notice below), from which the wait-state and timer-stage model, the TEST bit decode, the write-only registers' read value and the RAM-disable read value are taken (cited "ares"). blargg's ``notes.txt`` (his TEST-register cycle measurements) agrees with ares's cycle counts for TEST = $0A only as far as it can be read: it is a page of raw numbers. The bus contract is spc700-python's: one ``read_byte``/``write_byte``/``idle`` callback per SPC700 cycle. Inside each callback this module first clocks the S-DSP and the timers through the cycle, then performs the access, so an access in cycle *c* is seen by DSP step *c* + 1 on (HYPOTHESIS C14: no document orders the two; spc_dsp6's Timing tests through the board settle it). ares - Copyright (c) 2004-2025 ares team, Near et al Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. """ from __future__ import annotations import os from pathlib import Path from spc700_python import FLAG_P, SPC700, CPUState from snes_python.dsp import SDSP from snes_python.spc_file import SPCFile # ares timing.cpp: S-SMP cycle length and timer advance per TEST wait-state setting, in S-SMP # clocks at the normal rate (ares counts half-clocks: {2, 4, 10, 20} and {2, 4, 8, 16}). CYCLE_CLOCKS = (1, 2, 5, 10) TIMER_CLOCKS = (1, 2, 4, 8) IPL_SIZE = 64 def load_ipl(path: str | os.PathLike | None = None) -> bytes | None: """The 64-byte IPL ROM, bring-your-own: ``path``, else ``$SNES_IPL``, else None.""" chosen = path if path is not None else os.environ.get("SNES_IPL") if not chosen: return None data = Path(chosen).read_bytes() if len(data) != IPL_SIZE: raise ValueError(f"IPL ROM must be {IPL_SIZE} bytes, got {len(data)}") return data class Timer: """One timer (ares timing.cpp: stage 0 prescaler, stage 1 level, stage 2 divider, stage 3 the 4-bit TnOUT counter). DOC fullsnes: T0/T1 count at 8 kHz, T2 at 64 kHz; TnDIV 0 = 256.""" def __init__(self, half_period: int) -> None: self.half_period = half_period # S-SMP clocks per stage-1 toggle (64 or 8) # DOC anomie (sample loop, cycle 0 and 16): stage-1 ticks land on DSP step 0 (T0, T1 # every 4 samples) and steps 0 and 16 (T2). Starting one clock before a 1 -> 0 toggle # puts the first tick on step 0 after reset (HYPOTHESIS for power-on: U22). self.stage0 = half_period - 1 self.stage1 = 1 self.line = 1 self.stage2 = 0 self.stage3 = 0 self.enable = False self.target = 0 def advance(self, clocks: int, level_allowed: bool) -> None: self.stage0 += clocks while self.stage0 >= self.half_period: self.stage0 -= self.half_period self.stage1 ^= 1 self.synchronize(level_allowed) def synchronize(self, level_allowed: bool) -> None: level = self.stage1 if level_allowed else 0 falling = self.line and not level # ares: "only pulse on 1->0 transition" self.line = level if not falling or not self.enable: return self.stage2 = (self.stage2 + 1) & 0xFF if self.stage2 == self.target: self.stage2 = 0 self.stage3 = (self.stage3 + 1) & 0x0F class CPUPorts: """The one channel between the S-CPU's domain and the APU's (docs/domains.md): $2140-$2143 on the S-CPU's B bus, $F4-$F7 on the S-SMP's I/O page, two sets of four 8-bit latches (DOC fullsnes "SNES APU Main CPU Communication Port": "the ports are two separate sets of latches"). Every access from either side is a sync point. ``from_cpu`` is written by the S-CPU and read by the S-SMP; ``to_cpu`` the reverse. ``log`` holds (S-SMP clock, port, value before) for each S-SMP store, so an S-CPU read at an earlier time sees the earlier value (``cpu_read``). The other way, ``pending`` holds (S-SMP cycle, port, value) for each S-CPU store while the S-SMP is caught up to it, so the S-SMP's port reads and CONTROL clears see it from the S-SMP cycle that overlaps it (``smp_read``, ``smp_clear``), and ``cleared`` holds the S-SMP clock of the last clear of each port, so a store the S-SMP's clear came after in time is cleared even when the S-SMP had already run past it (``cpu_write``). The rule, both ways (DESIGN, as two chips sharing a latch, each side's access at its own time): an S-SMP access in cycle *c* is made at the cycle's end, S-SMP clock *c* + 1 (where ``SMP._advance`` leaves ``SMP.clock``); an S-CPU access at master clock *m* is made at S-SMP time *m* x ratio. A store is seen by every access of the other side made after it.""" __slots__ = ("cleared", "from_cpu", "log", "pending", "to_cpu") def __init__(self) -> None: self.from_cpu = [0, 0, 0, 0] self.to_cpu = [0, 0, 0, 0] self.log: list[tuple[int, int, int]] = [] self.pending: list[tuple[int, int, int]] = [] self.cleared = [0, 0, 0, 0] # -- the S-CPU's side -------------------------------------------------------------------- def cpu_write(self, port: int, value: int, at: int | None = None) -> None: """An S-CPU store to $2140 + port (DOC fullsnes "Main CPU Communication Port"). ``at`` is the S-SMP cycle the store falls in (the S-CPU's time in S-SMP clocks, rounded down). With ``at``, a CONTROL clear of the port made in cycle ``at`` or later (the S-SMP already past it, from an earlier catch-up's last instruction) came after the store and wins: the latch stays clear.""" port &= 3 if at is not None and at < self.cleared[port]: return self.from_cpu[port] = value & 0xFF def cpu_post(self, port: int, value: int, at: int) -> None: """An S-CPU store at S-SMP cycle ``at``, posted before the S-SMP is caught up to it: the S-SMP's accesses in cycle ``at`` and later see it (``smp_read``), the earlier ones do not. ``settle`` applies what the catch-up left.""" self.pending.append((at, port & 3, value & 0xFF)) def settle(self) -> None: """Apply the posted S-CPU stores (the S-SMP is now at or past each one's cycle).""" pending = self.pending for at, port, value in pending: self.cpu_write(port, value, at) pending.clear() def _apply_before(self, clock: int) -> None: """Apply the posted S-CPU stores of S-SMP cycles before ``clock`` (an S-SMP access made at ``clock``, the end of cycle ``clock`` - 1, sees them).""" pending = self.pending while pending and pending[0][0] < clock: at, port, value = pending.pop(0) self.cpu_write(port, value, at) def cpu_read(self, port: int, at: int | None = None) -> int: """An S-CPU load from $2140 + port: the last value the SPC700 stored at $F4 + port. ``at`` is the S-CPU's time in S-SMP clocks. The S-SMP runs whole instructions, so it can be up to one instruction past ``at``; a store made in a cycle after ``at`` is not seen yet (DESIGN: each store becomes visible at its own cycle, as on two chips sharing a latch). Rendering Ranger R2's upload handshake needs this: its S-CPU answers the S-SMP's $FF within a few S-SMP clocks, and the S-SMP reads port 0 three clocks after storing $FF; with stores visible from the instruction's start the S-SMP reads the S-CPU's next $00 instead of $FE and never leaves its loop (OBSERVED on the board, 2026-11-23; the SNESdev wiki's "Tricky-to-emulate games" lists the game's "infinite loop with SPC"). """ port &= 3 log = self.log if at is None or not log: return self.to_cpu[port] while log and log[0][0] <= at: log.pop(0) for _clock, logged_port, old in log: if logged_port == port: return old return self.to_cpu[port] def stub_echo(self, value: int) -> None: """No IPL ROM: nothing runs on the S-SMP side, and port 0 echoes the S-CPU's port-0 value as the IPL's transfer loop would (DESIGN, as ``apu.PortStub``).""" self.to_cpu[0] = value # -- the S-SMP's side -------------------------------------------------------------------- def smp_read(self, port: int, clock: int | None = None) -> int: """An SPC700 load from $F4 + port, made at S-SMP clock ``clock`` (the end of its cycle): S-CPU stores posted for earlier cycles are seen.""" if self.pending and clock is not None: self._apply_before(clock) return self.from_cpu[port] def smp_write(self, port: int, value: int, clock: int) -> None: """An SPC700 store to $F4 + port at S-SMP clock ``clock``.""" log = self.log if len(log) > 64: # unread for a long time: the S-CPU is past these del log[:32] log.append((clock, port, self.to_cpu[port])) self.to_cpu[port] = value def smp_clear(self, first: int, clock: int = 0) -> None: """CONTROL bit 4 (``first`` 0) or 5 (``first`` 2): the S-CPU-to-S-SMP latches of ports 0-1 or 2-3 read 0 (DOC fullsnes "00F1h - CONTROL"), made at S-SMP clock ``clock``: S-CPU stores of earlier cycles are cleared, later ones are not.""" if self.pending: self._apply_before(clock) self.from_cpu[first] = self.from_cpu[first + 1] = 0 self.cleared[first] = self.cleared[first + 1] = clock def load(self, values: bytes | list[int]) -> None: """Both sets of latches from an .spc snapshot's $F4-$F7, with no store pending.""" self.from_cpu[:] = values self.to_cpu[:] = values self.log.clear() self.pending.clear() self.cleared[:] = [0, 0, 0, 0] class SMP: """The S-SMP: an SPC700 core, 64 KiB ARAM shared with the S-DSP, and the I/O page. The board talks to it through ``cpu_write_port(n, value)`` (an S-CPU store to $2140+n), ``cpu_read_port(n)`` (an S-CPU load from $2140+n) and ``run(clocks)`` / ``step()``; the 32 kHz output is ``dsp.take_samples()``. """ def __init__( self, ipl: bytes | None = None, dsp_registers: bytes | None = None, aram: bytearray | None = None, ) -> None: if ipl is not None and len(ipl) != IPL_SIZE: raise ValueError("IPL ROM must be 64 bytes") self.ipl = ipl self.aram = aram if aram is not None else bytearray(0x10000) self.dsp = SDSP(self.aram, dsp_registers) self.cpu = SPC700(self._read, self._write, self._idle) self.clock = 0 # S-SMP clocks since power-on self.timers = [Timer(64), Timer(64), Timer(8)] #: The channel to the S-CPU (``CPUPorts``): the only state both domains touch. self.ports = CPUPorts() self.power_on() @property def input_ports(self) -> list[int]: """Written by the S-CPU, read at $F4-$F7 (``ports.from_cpu``).""" return self.ports.from_cpu @property def output_ports(self) -> list[int]: """Written at $F4-$F7, read by the S-CPU (``ports.to_cpu``).""" return self.ports.to_cpu # -- reset and loading ------------------------------------------------------------------- def power_on(self) -> None: """Power-on: TEST $0A (DOC fullsnes default), CONTROL $B0 (DOC fullsnes: "On power on or reset, it seems to be set to B0h": IPL ROM on, port latches cleared, timers off), DSP reset, then the SPC700 reset through the bus (reads the vector at $FFFE).""" self._write_test(0x0A) self._write_control(0xB0) self.dsp_address = 0 self.aux = [0, 0] self.dsp.reset() self.cpu.reset() def reset(self) -> None: """The /RESET line: CONTROL $B0 again and the DSP's reset (DOC fullsnes, anomie).""" self._write_control(0xB0) self.dsp.reset() self.cpu.reset() def skip_ipl(self, entry: int) -> None: """Start at ``entry`` with the registers the IPL ROM hands over ("in: A=0, X=0, Y=0, SP=EFh, PSW=02h", DOC fullsnes "Boot ROM Disassembly"), IPL ROM unmapped. For hosts with no IPL ROM; the S-CPU's upload protocol is not emulated here.""" self._write_control(0x00) self.cpu.restore_state(CPUState(a=0, x=0, y=0, sp=0xEF, psw=0x02, pc=entry & 0xFFFF)) def load_spc(self, spc: SPCFile) -> None: """Load an .spc snapshot (format: snesmusic.org "SPC File Format v0.30"). ARAM, the DSP registers and the SPC700 registers come from the file. The I/O page is rebuilt from the RAM image at $F0-$FF, since the file stores nothing else: CONTROL from $F1 (timer enables and the IPL bit), the DSP address from $F2, the ports from $F4-$F7 (input and output alike), the dividers from $FA-$FC and TnOUT from $FD-$FF. TEST is set to $0A, not to the byte at $F0 (HYPOTHESIS: rips hold 0 there, which would stop the timers and RAM writes). With the IPL bit set, the file's extra RAM is the RAM under the ROM. """ self.aram[:] = spc.ram ram = self.aram self._write_test(0x0A) control = ram[0xF1] for timer in self.timers: timer.enable = False self._write_control(control & 0x87) if control & 0x80 and self.ipl is not None: ram[0xFFC0:0x10000] = spc.extra_ram # with no IPL ROM, reads see the file's bytes self.dsp_address = ram[0xF2] self.ports.load(ram[0xF4:0xF8]) self.aux = [ram[0xF8], ram[0xF9]] for i, timer in enumerate(self.timers): timer.target = ram[0xFA + i] timer.stage3 = ram[0xFD + i] & 0x0F # A snapshot holds no prescaler or DSP-step state (C18). Start each timer one clock before # a stage-1 tick, the DSP at step 0 with the poll on the first sample: OBSERVED, the # alignment under which game .spc files agree longest with the referee # (docs/dsp/validation.md). for timer in self.timers: timer.stage0 = timer.half_period - 1 timer.stage1 = timer.line = 1 timer.stage2 = 0 self.dsp.reset() self.dsp.load_registers(spc.dsp_registers) self.dsp.phase = 0 self.dsp.every_other = 1 self.cpu.restore_state( CPUState(a=spc.a, x=spc.x, y=spc.y, sp=spc.sp, psw=spc.psw, pc=spc.pc) ) # -- the S-CPU side ---------------------------------------------------------------------- def cpu_write_port(self, port: int, value: int, at: int | None = None) -> None: """An S-CPU store to $2140 + port at S-SMP cycle ``at`` (``CPUPorts.cpu_write``).""" self.ports.cpu_write(port, value, at) def cpu_read_port(self, port: int, at: int | None = None) -> int: """An S-CPU load from $2140 + port at S-SMP clock ``at`` (``CPUPorts.cpu_read``).""" return self.ports.cpu_read(port, at) # -- running ----------------------------------------------------------------------------- def step(self) -> int: """One SPC700 instruction; returns its cycles (one bus callback each).""" return self.cpu.step() def run(self, clocks: int) -> None: """Run whole instructions until at least ``clocks`` S-SMP clocks have passed.""" end = self.clock + clocks while self.clock < end: self.cpu.step() def run_samples(self, count: int) -> list[tuple[int, int]]: """Run until the DSP has made ``count`` samples and return exactly that many (extra ones made by the last instruction are kept for the next call).""" dsp = self.dsp while len(dsp.samples) < count: self.cpu.step() out, dsp.samples = dsp.samples[:count], dsp.samples[count:] return out # -- the bus ----------------------------------------------------------------------------- def _advance(self, kind: int) -> None: """Clock the DSP and the timers through one SPC700 cycle (ares timing.cpp ``wait``).""" waits = self.internal_waits if kind else self.external_waits clocks = CYCLE_CLOCKS[waits] dsp_step = self.dsp.step for _ in range(clocks): dsp_step() self.clock += clocks allowed = self.timers_enable and not self.timers_disable timer_clocks = TIMER_CLOCKS[waits] for timer in self.timers: timer.advance(timer_clocks, allowed) def _idle(self) -> None: self._advance(1) # ares: idle cycles take the internal (I/O) wait states def _read(self, address: int) -> int: io = (address & 0xFFF0) == 0x00F0 ipl = address >= 0xFFC0 and self.ipl_enable and self.ipl is not None self._advance(1 if io or ipl else 0) if io: return self._read_io(address) if ipl: return self.ipl[address & 0x3F] if self.ram_disable: return 0x5A # ares memory.cpp ("0xff on mini-SNES") return self.aram[address] def _write(self, address: int, value: int) -> None: io = (address & 0xFFF0) == 0x00F0 ipl = address >= 0xFFC0 and self.ipl_enable and self.ipl is not None self._advance(1 if io or ipl else 0) # DOC fullsnes: "writes are also passed to RAM"; writes to $FFC0-$FFFF always go to RAM. if self.ram_writable and not self.ram_disable: self.aram[address] = value if io: self._write_io(address, value) def _read_io(self, address: int) -> int: register = address & 0x0F if register == 0x2: return self.dsp_address if register == 0x3: return self.dsp.read(self.dsp_address) # DOC fullsnes: $80-$FF read as mirrors if 0x4 <= register <= 0x7: return self.ports.smp_read(register - 4, self.clock) if register in (0x8, 0x9): return self.aux[register - 8] # DOC fullsnes: unconnected, RAM-like if register >= 0xD: timer = self.timers[register - 0xD] value = timer.stage3 timer.stage3 = 0 # DOC fullsnes: "reset to 0 after reading" return value return 0x00 # TEST, CONTROL, TnDIV are write-only: ares reads them as 0 def _write_io(self, address: int, value: int) -> None: register = address & 0x0F if register == 0x0: if not self.cpu.psw & FLAG_P: # ares io.cpp: TEST writes only with P clear self._write_test(value) elif register == 0x1: self._write_control(value) elif register == 0x2: self.dsp_address = value elif register == 0x3: if self.dsp_address < 0x80: # DOC fullsnes/anomie: $80-$FF are read-only mirrors self.dsp.write(self.dsp_address, value) elif 0x4 <= register <= 0x7: self.ports.smp_write(register - 4, value, self.clock) elif register in (0x8, 0x9): self.aux[register - 8] = value elif register <= 0xC: self.timers[register - 0xA].target = value def _write_test(self, value: int) -> None: """TEST $F0 (DOC fullsnes "00F0h - TEST"; field names and stage-1 resync from ares).""" self.timers_disable = bool(value & 0x01) self.ram_writable = bool(value & 0x02) self.ram_disable = bool(value & 0x04) # fullsnes: "Crash SPC700"; ares: RAM disable self.timers_enable = bool(value & 0x08) self.external_waits = (value >> 4) & 3 # RAM accesses self.internal_waits = (value >> 6) & 3 # I/O, IPL ROM and internal cycles self.dsp.ram_writable = self.ram_writable and not self.ram_disable allowed = self.timers_enable and not self.timers_disable for timer in getattr(self, "timers", ()): timer.synchronize(allowed) def _write_control(self, value: int) -> None: """CONTROL $F1 (DOC fullsnes "00F1h - CONTROL"): timer enables (a 0 -> 1 change clears the divider and TnOUT: ares io.cpp), port latch resets, the IPL ROM mapping.""" for i, timer in enumerate(self.timers): enable = bool(value >> i & 1) if enable and not timer.enable: timer.stage2 = 0 timer.stage3 = 0 timer.enable = enable if value & 0x10: self.ports.smp_clear(0, self.clock) if value & 0x20: self.ports.smp_clear(2, self.clock) self.ipl_enable = bool(value & 0x80)