sh2

package
v0.3.4 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 29, 2026 License: GPL-3.0 Imports: 4 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

SH-2 CPU Core

Clean room implementation of the Hitachi SH-2 (SH7604) processor core for use in Sega Saturn emulation.

Instruction Set

All SH-2 instructions are implemented:

  • Arithmetic (33): ADD, ADDI, ADDC, ADDV, SUB, SUBC, SUBV, NEG, NEGC, CMP/EQ, CMP/GE, CMP/GT, CMP/HI, CMP/HS, CMP/PL, CMP/PZ, CMP/STR, CMP/EQ #imm, DIV0U, DIV0S, DIV1, MUL.L, MULS.W, MULU.W, DMULS.L, DMULU.L, MAC.L, MAC.W, DT, EXTS.B, EXTS.W, EXTU.B, EXTU.W
  • Logic (13): AND, OR, XOR, TST, NOT, AND/OR/XOR/TST #imm, AND.B/OR.B/XOR.B/TST.B @(R0,GBR)
  • Shift/Rotate (14): SHLL, SHLR, SHAL, SHAR, SHLL2/8/16, SHLR2/8/16, ROTL, ROTR, ROTCL, ROTCR
  • Branch (12): BRA, BRAF, BSR, BSRF, BT, BF, BT/S, BF/S, JMP, JSR, RTS, RTE
  • Data Transfer (39): MOV variants (direct, indexed, post-increment, pre-decrement, GBR-relative, PC-relative, 4-bit displacement), MOVA, MOVT, SWAP.B, SWAP.W, XTRCT
  • System Control (30): CLRT, SETT, CLRMAC, NOP, SLEEP, LDC/STC for SR/GBR/VBR (direct and memory), LDS/STS for MACH/MACL/PR (direct and memory), TRAPA
  • Bit (1): TAS.B

Group 0xF opcodes are unused on SH-2 (no FPU).

Illegal Instructions

General illegal instructions (undefined opcodes) are dispatched to vector 4 through the synchronous serviceException path: SR and PC are pushed to the stack and PC is loaded from VBR + 4 * 4. The stacked PC value is the PC after the illegal opcode because the fetch advance is not rolled back. HM Sec 4.5.4 specifies the stacked PC should be the start address of the undefined code; that divergence is not modeled because an illegal instruction is typically a terminal fault and the resulting stack frame is not used for recovery.

Slot illegal exception (vector 6, HM Sec 4.5.3) is not detected. Undefined code placed in a delay slot is dispatched through the same general-illegal path (vector 4) rather than the slot-illegal path. Instructions that rewrite the PC (JMP, JSR, BRA, BSR, RTS, RTE, BT, BF, TRAPA, BF.S, BT.S, BSRF, BRAF) placed in a delay slot are also not detected as slot illegal; they execute normally.

Pipeline

The SH-2 has a 5-stage pipeline. This implementation does not model the full pipeline but does implement:

  • Delayed branch execution (branch delay slots)
  • Load-use hazard detection with 1-cycle stall insertion
  • Store data forwarding (stores to the same register as a prior load do not stall)
  • Multi-cycle instruction decomposition via the pending operation system
  • Per-cycle bus activity tracking (BusNone, BusRead, BusWrite, BusHeld)
Multi-Cycle Instructions

Complex instructions are decomposed into per-cycle micro-ops using the pending operation system. Each Clock() call advances exactly one cycle. Decomposed instructions include:

  • STC.L @-Rn (2 cycles)
  • LDC.L @Rm+,CR (3 cycles)
  • AND.B/OR.B/XOR.B @(R0,GBR) (3 cycles: read, logic, write)
  • TST.B @(R0,GBR) (3 cycles: read+test, 2 stall)
  • TAS.B @Rn (4 cycles: EX, read, modify, write - bus held)
  • RTE (3 cycles: EX, read PC, read SR + delay branch)
  • TRAPA (8 cycles: EX, write SR, write PC, vector calc, read vector, 3 pipeline refill)
  • Interrupt exception (5 cycles: internal, write SR, write PC, read vector, pipeline refill)
  • MAC.W/MAC.L (2 cycles: read @Rn, read @Rm + accumulate)
Multiplier Contention

When the MA of a multiplier-type instruction (MUL/MAC) coincides with the background multiplier stages ("mm") of a preceding multiplier-type instruction, the second instruction's MA is extended until mm ends. Per Programming Manual Section 7.2.3 and Table 7.1:

  • MULS.W / MULU.W: mm runs 2 cycles after MA
  • MUL.L / DMULS.L / DMULU.L: mm runs 4 cycles after MA
  • MAC.W: mm runs 2 cycles after the second MA
  • MAC.L: mm runs 4 cycles after the second MA

Only multiplier-type instructions stall on outstanding mm:

  • MUL.L, MULS.W, MULU.W, DMULS.L, DMULU.L, MAC.W, MAC.L

MAC-register access instructions (LDS/STS/LDS.L/STS.L to MACH or MACL, and CLRMAC) are listed in Table 7.1 as flat 1-cycle ops with no contention range. They cause mm contention for a subsequent multiplier-type instruction, but do not themselves stall on a preceding mm.

The stall is implemented by tracking a per-CPU cycle timestamp at which mm completes and by folding stall cycles into the follower's pending-op count when its EX stage begins before that timestamp. The stall value is clamped to each follower's Table 7.1 maximum extra-cycle count, so total cycle counts match the documented ranges exactly in all pairings (non-contending cases hit the Table 7.1 minimum; contending cases hit the Table 7.1 maximum).

IF/MA Bus Contention (not modeled)

Per Programming Manual Section 7.2.1, the instruction-fetch (IF) and memory-access (MA) pipeline stages share the memory bus. When a load/store's MA coincides with the next instruction's IF, the slot splits into two bus cycles. On SH-2 there is an optimization: longword-aligned code in on-chip memory has a single IF fetch two instructions in one bus cycle; subsequent fetches consume no bus and do not contend.

This contention is not modeled. Each Clock() call charges exactly one cycle. Cycle counts are therefore understated for code with a high memory-access density. System-level timing is largely unaffected because peripheral schedulers (VDP1/VDP2/SCU/SCSP) tick on scanline or sample boundaries rather than exact SH-2 cycles, so the internal timing stays consistent even though absolute wall-clock speed runs slightly fast.

If a game exhibits timing issues that correlate with memory-access- heavy code paths (such as polling hardware registers in tight loops), a bus-access cycle model can be added. The existing Bus.AccessCycles interface can be extended to cost instruction fetches as well as data accesses.

Interrupts

  • External interrupts via RequestInterrupt(level, vector)
  • NMI via NMI() (level 16, always accepted)
  • Interrupts accepted when level > IMASK
  • IMASK set to interrupt level after servicing
  • Higher priority pending interrupt replaces lower priority pending
  • Interrupt clears SLEEP/halt state
  • Synchronous exceptions (address error, TRAPA) handled separately
Address error during instruction execution (not modeled correctly)

Hardware manual Sec 4.3.2 specifies that when an address error occurs during an instruction's data access, exception handling begins after the failing bus cycle ends and the executing instruction completes. Sec 4.7 Table 4.11 specifies the stacked PC value as "address of instruction after executed instruction." Sec 4.8.3 covers the nested case (misaligned SP at exception entry) and requires hardware to suppress recursive address errors so the handler can run.

The emulator does not implement any of that sequence. cpu.write32, cpu.write16, cpu.read32, cpu.read16, and cpu.fetchPC all call addressError() (cpu.go) which calls serviceException(vecCPUAddr) synchronously from inside the failing bus access. Three things go wrong as a result:

  1. The currently-executing instruction is not allowed to complete. serviceException redirects PC to the address-error vector handler immediately. The HM-required final state of the instruction (R[m] post-increments for LDC.L / LDS.L / RTE / MAC.W / MAC.L, the WB write to GBR/VBR/SR/MACH/MACL/PR for LDC.L / LDS.L, the delay branch setup for RTE) is partly done and partly not, depending on which step inside the multi-cycle pending op the failure occurred.
  2. Stacked PC is wrong. serviceException saves the live PC at the moment of the failing access. For most pending ops PC was already advanced past the failing instruction during fetch, so the stacked value resembles HM's "next instruction" but is not derived from a defined snapshot point and may differ for delayed branches.
  3. Misaligned SP at exception entry recurses incorrectly. When SR or PC is pushed to a misaligned R15 the nested bus.Write32 writes garbage at the misaligned bus address (testBus and the production buses do not enforce alignment), and the dispatch then continues normally. For multi-cycle pending exceptions (popException, popTRAPA) the pending state machine then runs its remaining steps, including the vector fetch, which overwrites the address-error PC redirect with the original exception's vector. The Sec 4.8.3 suppression is not implemented; in practice no loop occurs because the bus does not re-trigger an alignment check.

This divergence is intentionally left unmodeled. Reaching any of the above paths requires the guest program to have already corrupted its own state (misaligned SP, wild pointer dereference, garbage register loaded into a control register and later used as an address). The hardware's Sec 4.3.2 / 4.8.3 sequence is a crash-containment feature, not a recovery feature: even on real hardware the resulting stack frame is undefined and RTE-based recovery is impossible. No Saturn BIOS or commercial title is observed to reach this path during normal execution, so the emulator's incorrect behavior is not externally visible during actual gameplay.

Modeling it correctly would require:

  • A deferred-dispatch flag (e.g. pendingAddrError bool) instead of the synchronous serviceException call inside addressError.
  • All step* handlers and execute() to drain to a clean boundary before the deferred dispatch fires.
  • Delay-slot suppression per Sec 4.6.1 (defer one more instruction if the failing instruction was a delayed branch's delay slot).
  • Sec 4.8.3 recursion suppression for the address-error handler's own stacking.

If a future Saturn title is found that depends on this path, that's the design sketch.

On-Chip Peripherals

FRT (Free-Running Timer)

16-bit free-running counter with output compare and input capture.

  • Configurable clock divider (fc/8, fc/32, fc/128, external)
  • Output compare A/B with interrupt generation
  • Counter clear on compare A match (CCLRA)
  • Overflow detection with interrupt
  • Input capture for inter-CPU communication (MINIT/SINIT)
  • Byte-pair register access with temp register
  • Registers: TIER, FTCSR, FRC, OCRA/B, TCR, TOCR, ICR (0xFFFFFE10-0xFFFFFE19)
FRT Simplifications
  • FTCSR flag clear protocol (manual Sec 11.2.5). Hardware requires the flag be read while set to 1 before a write of 0 can clear it. This implementation clears on any write of 0 regardless of whether the flag was read first. Ordinary polling sequences (read-to-check, then write 0-to-clear) behave identically; only software that violates the two- step protocol sees divergent behavior.
  • TCR.IEDGA input-edge select (Sec 11.2.6). The FRT has no external input capture pin on the Saturn; input capture is driven by MINIT/SINIT inter-CPU writes via FRTInputCapture. The IEDGA bit is storage only and does not affect capture behavior.
  • TOCR.OLVLA / OLVLB output levels (Sec 11.2.7). No FTOA/FTOB output pin is modeled. The corresponding TOCR bits are currently stored as 0 regardless of the written value; software that reads back the bits does not observe the write.
  • FTI pin signal phasing (Sec 11.4.4 Fig 11.9). Hardware delays the input-capture signal by one timer-clock cycle when it coincides with an ICR upper-byte read. The Saturn has no FTI pin; capture is driven by MINIT/SINIT writes via FRTInputCapture. Latching is synchronous with the call and independent of any concurrent ICR read.
INTC (Interrupt Controller)

Routes on-chip interrupt sources to the CPU with configurable priority and vector numbers.

  • Priority registers:
    • IPRA bits 15-12: DIVU overflow
    • IPRA bits 11-8: DMAC channel 0/1 transfer-end (channel 0 wins ties)
    • IPRA bits 7-4: WDT interval interrupt
    • IPRB bits 11-8: FRT (ICI/OCIA/OCIB/OVI sub-priority)
  • Vector registers:
    • VCRC: FRT ICI (bits 14-8) and OCI (bits 6-0)
    • VCRD: FRT OVI (bits 14-8)
    • VCRWDT: WDT ITI (bits 14-8)
    • VCRDIV (DIVU, 0xFFFFFF0C), VCRDMA0/1 (DMAC, 0xFFFFFFA0/A8)
  • ICR: NMIL (bit 15) tracks the NMI pin via SetNMIL; NMIE (bit 8) and VECMD (bit 0) are storage-only (see INTC Simplifications).
  • Registers: 0xFFFFFE60-0xFFFFFE68, 0xFFFFFEE0-0xFFFFFEE4
INTC Simplifications

The following documented INTC behaviors are not exercised by the Saturn hardware we emulate and are not modeled here. Register bits that exist for them are preserved as read/write storage only unless otherwise noted.

  • SCI interrupts (IPRB bits 15-12, VCRA, VCRB). The serial communication interface is not modeled; the priority and vector fields are storage only. Hardware manual Sec 5.2.4 / 5.3.2 / 5.3.4 / 5.3.5.
  • BSC refresh compare-match interrupt (VCRWDT bits 6-0). The refresh control unit inside the bus state controller does not raise CMI in this emulator; the vector field is storage only. IPRA bits 7-4 are used exclusively for WDT here (the manual shares them with BSC REF CMI). Hardware manual Sec 5.3.1 / 5.3.3.
  • UBC interrupts. isrcUBC is reserved in the interrupt-source enum but no code asserts it. Hardware manual Sec 5.2.2 / Sec 6.
  • SBYCR / STBY power-down (0xFFFFFE91). Stub storage with reserved-bit masking; STBY/SLEEP power semantics are not modeled. Hardware manual Sec 14.2.1.
  • IRL auto-vector mode (ICR.VECMD=0, Table 5.3). The Saturn SCU synthesizes the vector itself and delivers it via SetIRL(level, vec), so the INTC's internal auto-vector generator is never used. VECMD is storage only. Hardware manual Sec 5.2.3 / 5.3.8.
  • NMI edge select (ICR.NMIE). CPU.NMI() unconditionally latches the request; the SMPC drives a single falling-edge NMI on reset-button press and that is the only mode used by Saturn software. NMIE is storage only. Hardware manual Sec 5.2.1 / 5.3.8.
  • On-chip peripheral 2-cycle interrupt-recognition delay. The manual's usage note (Sec 5.7) requires two cycles between an on-chip source assertion and acceptance so software can clear a just-raised latch before RTE. Acceptance is immediate here; no Saturn game observed so far depends on the delay.
  • External vector fetch bus cycle (Sec 5.2.3, Fig 5.4). The IVECF / D7-D0 external-vector-read path is never driven; vectors arrive on the SetIRL call directly from the SCU.
DIVU (Division Unit)

Hardware division unit performing signed integer division.

  • 32-bit / 32-bit division (write DVDNT to trigger)
  • 64-bit / 32-bit division (write DVDNTL to trigger)
  • Division by zero detection (overflow)
  • Quotient overflow detection with saturation
  • Optional overflow interrupt (OVFIE)
  • Registers: DVSR, DVDNT, DVCR, VCRDIV, DVDNTH, DVDNTL (0xFFFFFF00-0xFFFFFF14)
DIVU Simplifications
  • Division timing (manual Sec 10.1.1 / 10.3.3). Hardware takes 39 cycles for a normal division and 6 cycles when overflow aborts the operation. This implementation completes the division instantly at register-write time. Software that intentionally interleaves non-DIVU work with a running division does not stall, but the final result appears in the result registers the same way.
  • DVDNTL intermediate result on overflow with OVFIE=1 (Table 10.2). The manual says hardware leaves the operation result captured at the 6th overflow-detection cycle in DVDNTL. This implementation does not compute an intermediate result; the DVDNT write path unconditionally copies the dividend into DVDNTL before detecting overflow, and the OVFIE=1 branch returns without updating DVDNTL further, so the register reads back as the dividend. DVDNTH still holds the sign-extended dividend high half per table. With OVFIE=0 the saturating clamp behavior matches hardware.
WDT (Watchdog Timer)

8-bit counter with selectable prescaler, usable as either a watchdog or an interval timer.

  • Interval timer mode (WTCSR.WT/IT=0): overflow sets WTCSR.OVF and raises an interval interrupt (ITI) through the INTC.
  • Watchdog timer mode (WTCSR.WT/IT=1): overflow sets RSTCSR.WOVF.
  • Eight prescaler selections via WTCSR.CKS (manual Table 12.3).
  • A5/5A word-write protection (Sec 12.2.4) for WTCSR, WTCNT, and RSTCSR.
  • Clearing WTCSR.TME resets WTCNT to 0 per Sec 12.2.2.
  • Registers: WTCSR, WTCNT, RSTCSR (0xFFFFFE80-0xFFFFFE83)
WDT Simplifications
  • Watchdog-mode external reset output (Sec 12.3.1). Hardware asserts the WDTOVF pin for 128 system clocks and, if RSTCSR.RSTE=1, drives an internal reset for 512 clocks on watchdog-mode overflow. This implementation latches RSTCSR.WOVF and emits a log line; no pin output or chip reset is generated. No Saturn title reaches watchdog-mode overflow in normal operation.
DMAC (Direct Memory Access Controller)

Two-channel DMA controller used by the Saturn BIOS and games for memory-to-memory transfers.

  • Per-channel SAR, DAR, TCR (24-bit), CHCR, VCRDMA.
  • Shared DMAOR with DME, PR (fixed vs round-robin), AE, NMIF flags.
  • Transfer sizes: byte, word, longword, 16-byte burst (CHCR.TS).
  • Source/destination addressing modes: fixed, increment, decrement.
  • Transfers move data atomically on register write; the CPU is stalled for a region-aware bus-occupation cost accumulated across each unit access via Bus.AccessCycles. Transfer-end interrupt is gated by CHCR.IE and routed via VCRDMAn.
  • NMI sets DMAOR.NMIF, blocking new transfer starts until software clears it.
  • Registers: SAR0/1, DAR0/1, TCR0/1, CHCR0/1, VCRDMA0/1, DMAOR, DRCR0/1 (0xFFFFFF80-0xFFFFFFB0, DRCR at 0xFFFFFE71-0xFFFFFE72).
DMAC Simplifications
  • External DREQ / DACK pin signaling, single-address mode (CHCR.TA=1), acknowledge mode/level (AM, AL), DREQ edge/level detection (DS, DL), and the DRCR resource-select field (Sec 9.2.4, 9.2.6). The Saturn does not route any external DMA peripherals to the SH-2 DMAC; only auto-request and dual-address mode are used. The corresponding CHCR and DRCR bits are stored but not consulted.
  • Cycle-steal vs burst-mode selection (CHCR.TB). Transfers move data atomically on trigger rather than interleaving with CPU access at the bus level. The post-transfer stall window prevents observable CPU activity during the transfer, so visible ordering matches burst-mode semantics; cycle-steal-style interleaving is not available. One consequence is that an NMI mid-stall (Sec 9.3.8 "Conditions for Both Channels Ending Simultaneously") cannot abort a partially-transferred block: the data has already moved by the time the stall starts, and CHCR.TE is latched when the stall drains. Hardware would only set TE if the NMI-coincident unit was the final one. The NMIF gate on future transfer starts is modeled correctly.
  • DMA address-error generation (vector 10, Sec 9.3.2). No code path asserts a DMAC address error, so the exception is never taken.

Cache

The SH-2's 4 KB on-chip cache is fully modeled per SH7604 hardware manual Section 8: 4-way set associative, 64 entries, 16-byte lines, mixed instruction/data, write-through with no write allocation. Each CPU has its own private cache (cache.go); both instruction fetches and data accesses go through it when CE is set.

  • Partition routing (Sec 8.3, Table 8.2): A31-A29 select cache area (000), cache-through (001), associative purge (010), address array (011), data array (110), or I/O (111). Reads and writes in read8/16/32 / write8/16/32 dispatch on the partition.
  • Reads (Sec 8.4.1): a hit is served from the data array with no external access and no wait states. A miss selects a way by pseudo-LRU, writes the tag and valid bit, and fills the 16-byte line with four longword bus reads; the stall charged is the full four-access external cost.
  • Writes (Sec 8.4.2): write-through - memory is always written (and always pays the external cost; the CPU waits for the internal bus write), the data array is updated only on a tag hit, and a write miss does not allocate.
  • Pseudo-LRU (Sec 8.4.5, Tables 8.3/8.4): 6 bits per entry, updated on read hit, write hit, and replacement. After a purge the fill order is way 3 -> 2 -> 1 -> 0. OD/ID suppress replacement for data/instruction misses; two-way mode (TW) replaces only ways 2-3, picked by LRU bit 0 (the way2<->way3 order bit), leaving ways 0-1 as RAM.
  • CCR (Sec 8.2): CE/ID/OD/TW/W1-W0 modeled; CP purges all valid bits and LRU information, self-clears, and always reads 0 (Sec 8.4.6). A reset clears CCR but not the cache contents (Sec 8.5.1).
  • Associative purge (Sec 8.4.7): a write to 0x40000000+addr invalidates a line matching addr's tag in any way.
  • Address array (Sec 8.4.9): longword read returns tag/LRU/valid for the way selected by CCR W1-W0; a write sets the tag and valid bit from the address and the LRU from the data.
  • Data array (Sec 8.4.8): 0xC0000000+ reads and writes the 4 KB cache storage directly, way-major (way 0 at +0x000, way 3 at +0xC00), shared with cached lines - the same bytes hardware exposes. Code can execute from it. With the cache disabled or in two-way mode, games use it as on-chip RAM.
  • TAS.B (Sec 8.4.4): the read is cache-through even in the cache area (no tag compare, no fill); the write updates the data array on a tag hit before the memory write.
  • No snoop (Sec 8.5.3): writes by the other CPU, the SCU, or the DMAC do not update or invalidate this CPU's cache. Stale data after external writes is real hardware behavior; software maintains coherency with cache-through addresses, associative purges, and CP. The on-chip DMAC also bypasses the cache (Sec 7.11.2).
Bus-access wait states

External accesses - cache misses (line fills), cache-through and uncached accesses, and every write - are charged a wait-state penalty so memory-heavy code runs at hardware rate; cache hits cost nothing:

  • The CPU's instruction-execution accesses go through the Bus interface's SH2* methods (SH2Read8/16/32, SH2Write8/16/32, SH2FillLine, SH2RMWRead/SH2RMWWrite), each passing the CPU's frame cycle (SetFrameCyc) and master/slave flag. The Bus implementation computes the whole access stall and returns it; the CPU adds it to busStall. This package defines the interface and applies the returned stall - it holds no cost tables of its own.
  • The frame cycle and master/slave flag are passed precisely so the Bus implementation can model the wait state it owns: per-region access cost, the slave SH-2's per-access bus-arbitration penalty, and inter-CPU bus contention (one CPU waiting on the other's in-flight shared-bus access).
  • busStall debt is drained one cycle per Clock() before the next instruction executes (the same deferred-cycle pattern as load-use stall), so each access extends its instruction by its cost.
  • On-chip registers and data-array accesses are internal and never charged. The plain Read*/Write* interface methods (used by callers with no instruction-execution timing) are untimed.

Memory Access / Region Routing Simplifications

The SH-2 memory map (Hardware Manual Sec 7.1.5, Table 7.3) includes several address ranges that the Saturn does not exercise in normal operation. These ranges are modeled with reduced fidelity; each entry below describes the documented hardware behavior, what erings does, and why the simplification is safe for Saturn software.

  • D1 Cache data array mirroring (Sec 8.4.8, Table 7.3). Hardware maps the 4 KB data array at 0xC0000000-0xC0000FFF and reserves the remainder of 0xC0001000-0xDFFFFFFF. erings mirrors the 4 KB buffer throughout the full 512 MB range. Saturn software accesses the buffer through the documented base, so the mirror is never observed.
  • D2 Associative-purge reserved alias (Sec 8.4.7, Table 7.3). Hardware defines the associative purge region at 0x40000000-0x47FFFFFF and reserves 0x48000000-0x5FFFFFFF. erings treats the full partition as the purge region: any write purges by the address's tag/entry bits; reads return 0.
  • D3 Address-array reserved alias (Sec 8.4.9, Table 7.3). Hardware maps the address array at 0x60000000-0x600003FF; the rest of 0x60000000-0x7FFFFFFF is addressable via tag-address bit layout. erings serves the full partition through the same entry-bit decode (A9-A4), so the documented base behaves exactly and the remainder mirrors it.
  • D4 Reserved block 0x80000000-0xBFFFFFFF (Table 7.3). Hardware reserves this range. erings returns 0 on read and drops writes.
  • D5 SDRAM-mode setting area and reserved on-chip block (Table 7.3). Hardware maps 0xFFFF8000-0xFFFFBFFF to synchronous DRAM mode registers and reserves 0xFFFFC000-0xFFFFFDFF. The Saturn does not wire SDRAM to the SH-2, so neither range is exercised by software. erings routes these through readOnChip/writeOnChip where they are unhandled: reads return 0 and writes are dropped.
  • D6 FMR not modeled (Sec 3.4.2). Hardware provides the Frequency Modification Register at 0xFFFFFE90 for PLL multiplier selection. The Saturn drives the SH-2 clock from SMPC via CKCHG, so FMR is unused. erings does not map the register: reads return 0 and writes are dropped.
  • D7 BSC registers other than BCR1 (Sec 7.2). Hardware defines BCR2 (0xFFFFFFE4), WCR (0xFFFFFFE8), MCR (0xFFFFFFEC), RTCSR (0xFFFFFFF0), RTCNT (0xFFFFFFF4), and RTCOR (0xFFFFFFF8) for wait- state programming and DRAM refresh. The Saturn configures these through the SCU glue logic rather than the SH-2 BSC, and the values are not inspected by software. erings only models BCR1's MASTER bit; the remaining BSC registers return 0 on read and drop writes.
  • D8 Undefined access-size clobber on 32-bit-only on-chip registers (Table 9.2 Note 3, Table 10.1 Note 1). Manual declares DVSR / DVDNT / DVDNTH / DVDNTL and SAR / DAR / TCR / CHCR / VCRDMA / DMAOR as 32-bit access only; byte and word accesses are undefined. erings handles such accesses by routing through the 32-bit dispatch path with a zero-extended value, which clobbers the unaddressed bytes of the register. Reads return the low 16 bits (word) or the big-endian byte from the 32-bit value (byte). This is one valid undefined- behavior interpretation; Saturn software uses only longword access for these registers.
  • D9 Table 4.6 address-error source rows not detected (Sec 4.3.1). The odd-PC and misaligned-data rows are detected; the following rows are not. erings services the access normally instead of trapping to vector 9. Reaching any row requires prior memory or stack corruption and no observed Saturn title exercises these paths.
    • Instruction fetch from on-chip peripheral space ($FFFFFE00-$FFFFFFFF).
    • PC-relative MOV.W/MOV.L @(disp,PC) and MOVA targeting cache purge ($40000000-$5FFFFFFF), address array ($60000000-$7FFFFFFF), or on-chip I/O space.
    • TAS.B targeting cache purge, address array, data array ($C0000000-$DFFFFFFF), or on-chip I/O space.
    • Byte access in $FFFFFF00-$FFFFFFFF. Services the access through the D8 path; see D8.
    • Longword access in $FFFFFE00-$FFFFFEFF. Services the access against the underlying 16-bit register.

References

  • SH7604 Hardware Manual
    • Section 8: Cache (pages 213-230, Tables 8.3-8.4)
  • SH-1/SH-2 Programming Manual
    • Section 6: Instruction descriptions

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Disassemble

func Disassemble(pc uint32, op uint16) string

Disassemble decodes a 16-bit SH-2 instruction and returns a human-readable string. The pc parameter is the address of the instruction, used for PC-relative address calculation.

func IsDelayedBranch added in v0.2.0

func IsDelayedBranch(op uint16) bool

IsDelayedBranch reports whether op is an SH-2 delayed branch, i.e. the following instruction (the delay slot) executes before the branch takes effect. The decode patterns mirror those used by Disassemble above. This is a disassembly aid; the execution core handles delay slots via runtime state (CPU.inDelay/delayPC) rather than opcode classification.

Types

type Bus

type Bus interface {
	Read8(addr uint32) uint8
	Read16(addr uint32) uint16
	Read32(addr uint32) uint32
	Write8(addr uint32, val uint8)
	Write16(addr uint32, val uint16)
	Write32(addr uint32, val uint32)

	// The SH2* methods are the instruction-execution access path: each
	// folds the full bus-access stall (region cost + slave arbitration +
	// inter-CPU contention) into the data access and returns the cycles to
	// add to the CPU's wait-state debt (reads also return the value). Width
	// is in the method name, matching the plain Read*/Write* above, which
	// are the non-timed path (on-chip DMAC, exceptions). frameCyc is the
	// accessing CPU's frame-relative cycle (the clock both SH-2s share);
	// slave selects the arbitration penalty.
	SH2Read8(addr uint32, frameCyc int64, slave bool) (uint8, uint32)
	SH2Read16(addr uint32, frameCyc int64, slave bool) (uint16, uint32)
	SH2Read32(addr uint32, frameCyc int64, slave bool) (uint32, uint32)
	SH2Write8(addr uint32, val uint8, frameCyc int64, slave bool) uint32
	SH2Write16(addr uint32, val uint16, frameCyc int64, slave bool) uint32
	SH2Write32(addr uint32, val uint32, frameCyc int64, slave bool) uint32

	// AccessCycles returns the CPU state count consumed by a single
	// read transaction of the given size (in bytes: 1, 2, 4, or 16)
	// at the given address; WriteAccessCycles the same for a write
	// (some devices cost differently per direction - SDRAM reads run
	// a full burst pipeline while writes are single). Used by the
	// DMAC to accumulate accurate bus-occupation stall duration.
	AccessCycles(addr uint32, size uint32) uint32
	WriteAccessCycles(addr uint32, size uint32) uint32

	// ReadCacheLine fills dst from the 16-byte-aligned line at base in
	// a single bus tenure, so another bus master cannot interleave a
	// write between the four longwords. Per SH7604 Sec 8.4.1 a cache
	// line fill reads four longwords consecutively, and for Work RAM-H
	// that is one SDRAM burst (Sec 7.5.3-7.5.4) - an indivisible
	// transaction the other CPU/DMAC cannot break into. base is the
	// big-endian line; dst[0] is base's high byte.
	ReadCacheLine(base uint32, dst *[16]byte)

	// SH2FillLine is the timed 16-byte line-fill variant (returns the
	// access stall). See SH2Read32 for frameCyc/slave.
	SH2FillLine(base uint32, dst *[16]byte, frameCyc int64, slave bool) uint32

	// ReadRMW8 begins a TAS.B read-modify-write: it claims the
	// address's bus area and returns with the claim held. WriteRMW8
	// completes the sequence and releases it. Per SH7604 Sec 7.10 the
	// bus is not released between the read and write cycles of TAS.
	ReadRMW8(addr uint32) uint8
	WriteRMW8(addr uint32, val uint8)

	// Timed TAS.B pair (return the access stall). The read half charges
	// cost+arbitration+contention and holds the bus; the write half extends
	// the busy window and charges only the write cost.
	SH2RMWRead(addr uint32, frameCyc int64, slave bool) (uint8, uint32)
	SH2RMWWrite(addr uint32, val uint8, frameCyc int64) uint32
}

Bus provides memory access for the SH-2 CPU. Addresses are 32-bit. The SH-2 uses big-endian byte ordering. Word and longword accesses must be naturally aligned; the CPU raises an address error before reaching the bus on misaligned access.

type BusActivity

type BusActivity uint8

BusActivity describes what bus operation the CPU performed on a clock cycle.

const (
	BusNone  BusActivity = iota // No bus access
	BusRead                     // Memory read
	BusWrite                    // Memory write
	BusHeld                     // Bus held for atomic operation (TAS.B)
)

type CPU

type CPU struct {

	// Trace callback: called with (pc, opcode) before each instruction
	TraceFunc func(pc uint32, op uint16)

	// HLEHook, if non-nil, is invoked from the execute loop when the
	// fetched PC falls within the HLE BIOS magic address range. The
	// hook is responsible for performing the emulated service in Go.
	// The bus returns RTS (+ NOP delay slot) at these addresses, so
	// the CPU unwinds to the caller normally after the hook returns.
	// Set by HLEBIOS.Boot when the emulator is started without a real
	// BIOS image; nil otherwise.
	HLEHook func(pc uint32)
	// contains filtered or unexported fields
}

CPU implements the Hitachi SH-2 processor core.

func New

func New(bus Bus, master bool) *CPU

New creates a CPU connected to the given bus in power-on state. master indicates whether this is the master (true) or slave (false) SH-2. SR has all interrupts masked. Call LoadResetVectors() once the bus has valid data to set the initial PC and SP.

func (*CPU) CachePurge added in v0.3.0

func (c *CPU) CachePurge()

CachePurge purges the cache on behalf of emulated BIOS code running in Go (HLE): on hardware that code executed on this CPU through the cache, so its memory writes were coherent and its footprint evicted resident lines. A full purge at the service boundary restores both properties. Must be called on the CPU's own thread, between instructions.

func (*CPU) ClearFRTInputCapture added in v0.3.0

func (c *CPU) ClearFRTInputCapture()

ClearFRTInputCapture clears the FRT input-capture latch and re-evaluates the on-chip interrupt line. Used on a system reset (CKCHG/SYSRES): the peer SH-2 that drives this CPU's cross-CPU input capture is turned off, so a SINIT/MINIT capture latched just before the reset must not leave ICF asserted (the request line is the AND of ICF and TIER.ICIE and is otherwise held until software clears ICF).

func (*CPU) ClearIRL

func (c *CPU) ClearIRL()

ClearIRL deasserts the external IRL interrupt request.

func (*CPU) Clock

func (c *CPU) Clock() ClockState

Clock advances the CPU by exactly one cycle and returns per-cycle state.

func (*CPU) Cycles

func (c *CPU) Cycles() uint64

Cycles returns the total number of cycles executed.

func (*CPU) FRT added in v0.2.0

func (c *CPU) FRT() *FRT

FRT returns the CPU's free-running timer module. Used by HLE BIOS services that need to configure FRT registers on a CPU whose own setup code we're replacing with Go (e.g., enabling slave FRT input-capture interrupts when the real-BIOS slave-init code that would normally configure them is being skipped).

func (*CPU) FRTInputCapture

func (c *CPU) FRTInputCapture()

FRTInputCapture triggers input capture on the FRT. Called by the coordinator when it detects a write to MINIT/SINIT addresses. Sync live FRT state before the capture so ICR latches the current FRC value (Section 11.4.5, Figure 11.10).

func (*CPU) Halted

func (c *CPU) Halted() bool

Halted returns true if the CPU is halted (via SLEEP instruction).

func (*CPU) INTC added in v0.2.0

func (c *CPU) INTC() *INTC

INTC returns the CPU's interrupt controller. Used by HLE BIOS services that need to set vector / priority registers on a CPU whose own setup code we're replacing with Go.

func (*CPU) IRL added in v0.3.0

func (c *CPU) IRL() uint32

IRL returns the raw external interrupt-request word currently driven by the SCU (level<<16 | vector). Counterpart to SetIRL/ClearIRL.

func (*CPU) InTAS added in v0.3.0

func (c *CPU) InTAS() bool

InTAS reports whether a TAS.B read-modify-write is in progress. TAS is the only operation that keeps a bus claim held across cycles (SH7604 Sec 7.10), so a scheduler running the two CPUs on separate threads must not park this CPU at a cross-thread sync point mid-TAS: the other CPU would stall on the held claim while this one waits, deadlocking. The scheduler lets the TAS finish (releasing the claim) before waiting.

func (*CPU) LoadResetVectors

func (c *CPU) LoadResetVectors()

LoadResetVectors reads the initial PC from address 0x00000000 and SP from address 0x00000004.

func (*CPU) NMI

func (c *CPU) NMI()

NMI requests a non-maskable interrupt and asserts the NMIL bit in the ICR register so that software can observe the NMI pin state. NMI always has priority level 16 and uses vector 11. Tracked independently of the IPR-level sources via a dedicated flag.

Per manual Sec 9.2.6, an NMI input also sets DMAOR.NMIF (bit 1). transferReady gates new transfers on dmaor&0x07 == 0x01, so setting NMIF here prevents any subsequent CHCR/DMAOR-triggered DMA start until software writes 0 to DMAOR bit 1 to clear NMIF.

func (*CPU) NMIRequest added in v0.3.0

func (c *CPU) NMIRequest()

NMIRequest asserts an NMI from another goroutine. The CPU applies it on its own thread in Clock, so the register/INTC state NMI touches is only ever mutated by the owning thread.

func (*CPU) Read8 added in v0.3.0

func (c *CPU) Read8(addr uint32) uint8

read8 reads a byte, checking for on-chip peripheral addresses first. Partition routing per SH7604 manual Section 8.3 Table 8.2.

func (*CPU) Read16 added in v0.3.0

func (c *CPU) Read16(addr uint32) uint16

Read8/Read16/Read32 and Write8/Write16/Write32 perform a data access exactly as a MOV would: partition routing per SH7604 manual Section 8.3 Table 8.2, cache fill/update on the cache-area path, inter-CPU bus contention and stall charged to this CPU, and an address error raised on misalignment. They are side-effecting, not neutral peeks.

Read16 reads a 16-bit value with alignment check.

func (*CPU) Read32 added in v0.3.0

func (c *CPU) Read32(addr uint32) uint32

read32 reads a 32-bit value with alignment check. Partition routing per SH7604 manual Section 8.3 Table 8.2.

func (*CPU) RefreshOnChipInterrupts added in v0.2.0

func (c *CPU) RefreshOnChipInterrupts()

RefreshOnChipInterrupts re-evaluates the level-sensitive request line of every implemented on-chip interrupt source and marks the INTC pending bit for those currently asserting with a non-zero priority.

SH7604 on-chip interrupt requests are level-sensitive: each is the logical AND of a status flag and its enable bit (FRT Sec 11.5, WDT Sec 12.3.2, DIVU Sec 10, DMAC Sec 9), held until software clears the flag, and the INTC samples it continuously (Sec 5). A request can become active with no fresh flag-set edge: by enabling an already-set flag, by a mode change exposing a held flag, or by raising the module priority while a flag is pending. The peripherals' edge callbacks (route*Interrupt) only cover the flag-set edge, so this is called after any write to an interrupt control/enable/mode/ priority register to recover those level transitions. Over-marking is safe: processInterrupt lazily clears a pending bit whose source is no longer asserted.

func (*CPU) Registers

func (c *CPU) Registers() Registers

Registers returns a snapshot of the current register state.

func (*CPU) Reset

func (c *CPU) Reset()

Reset returns the CPU to its power-on state, clearing programmer-visible registers and on-chip peripherals, then reloading PC/SP from the reset vectors. This is what real hardware does when the slave receives SSHON (after SSHOFF) - the reset line is pulsed and the CPU re-enters its reset-vector boot sequence. Games rely on this to re-read their game-supplied slave entry pointer after updating it.

func (*CPU) SetCCR added in v0.3.0

func (c *CPU) SetCCR(v uint8)

SetCCR seeds the cache control register without going through an on-chip register write. Used by the HLE BIOS to reproduce the real BIOS handoff state (docs/bios/handoff_state.md: CCR = $01, cache enabled with all four ways purged). The CP semantics of a real CCR write apply: a set CP bit purges and self-clears (SH7604 manual Section 8.4.6).

func (*CPU) SetFrameCyc added in v0.3.0

func (c *CPU) SetFrameCyc(cyc int64)

SetFrameCyc sets this CPU's current frame-relative system cycle, used to time inter-CPU bus contention. The emulator calls it before each step so the clock advances with the CPU; callers that drive Clock() directly and care about bus timing must advance it too, or repeated Work-RAM accesses will appear to contend with themselves (a stuck clock never clears its busyUntil).

func (*CPU) SetGBR added in v0.2.0

func (c *CPU) SetGBR(v uint32)

SetGBR sets the global base register.

func (*CPU) SetIRL

func (c *CPU) SetIRL(level uint8, vec uint16)

SetIRL updates the external IRL interrupt level driven by the SCU. IRL interrupts are level-triggered: the level reflects the current state of the IRL pins and is sampled each cycle. When the SCU clears the interrupt source, it calls ClearIRL to deassert the request.

func (*CPU) SetIRLAck

func (c *CPU) SetIRLAck(f func(vec uint16))

SetIRLAck sets the callback invoked when the SH-2 accepts an IRL interrupt. The callback receives the vector the CPU dispatched.

func (*CPU) SetPC

func (c *CPU) SetPC(pc uint32)

SetPC sets the program counter.

func (*CPU) SetPR added in v0.2.0

func (c *CPU) SetPR(v uint32)

SetPR sets the procedure register. Used by HLE BIOS services that need a bus-served RTS at a magic address to land at a specific PC when the magic address was reached without a preceding JSR (which would have set PR for them).

func (*CPU) SetReg added in v0.2.0

func (c *CPU) SetReg(n int, v uint32)

SetReg sets general-purpose register Rn (n = 0..15). Used by external code (HLE BIOS, boot setup) to seed register state without going through an SH-2 instruction.

func (*CPU) SetSR added in v0.2.0

func (c *CPU) SetSR(v uint32)

SetSR sets the status register. Reserved bits are masked off so no LDC-equivalent invariant is broken.

func (*CPU) SetState added in v0.3.2

func (c *CPU) SetState(s *State)

SetState restores a snapshot taken by State. Pure field assignment: the snapshot is internally consistent by construction, so nothing is re-derived.

func (*CPU) SetVBR added in v0.2.0

func (c *CPU) SetVBR(v uint32)

SetVBR sets the vector base register.

func (*CPU) State added in v0.3.2

func (c *CPU) State() State

State returns a complete snapshot of the CPU's serializable state.

func (*CPU) Write8 added in v0.3.0

func (c *CPU) Write8(addr uint32, val uint8)

write8 writes a byte, checking for on-chip peripheral addresses first.

func (*CPU) Write16 added in v0.3.0

func (c *CPU) Write16(addr uint32, val uint16)

write16 writes a 16-bit value with alignment check. Partition routing per SH7604 manual Section 8.3 Table 8.2. Cache area writes are write-through (Section 8.4.2).

func (*CPU) Write32 added in v0.3.0

func (c *CPU) Write32(addr uint32, val uint32)

write32 writes a 32-bit value with alignment check. Partition routing per SH7604 manual Section 8.3 Table 8.2. Cache area writes are write-through (Section 8.4.2).

type CacheState added in v0.3.2

type CacheState struct {
	CCR   uint8
	Data  [4096]byte
	Tag   [4][64]uint32
	Valid [4][64]bool
	LRU   [64]uint8
}

CacheState holds the cache control register and all four cache arrays. The arrays are one unit: data restored without tags, valid bits, and LRU state is an incoherent cache.

type ClockState

type ClockState struct {
	Bus          BusActivity // Bus activity this clock cycle
	LoadUseStall bool        // Next instruction stalls on this load result
	BranchTaken  bool        // A branch was resolved (taken) this clock cycle
}

ClockState describes what the CPU did during a Clock() call.

type DIVU

type DIVU struct {
	// contains filtered or unexported fields
}

DIVU implements the SH-2 on-chip hardware division unit. It performs 32/32 -> 32 and 64/32 -> 32 signed division in hardware, triggered by writing the dividend register.

func (*DIVU) IRQAsserted

func (d *DIVU) IRQAsserted() bool

IRQAsserted returns true when the DIVU overflow interrupt line is currently driven to the INTC: OVF latch (bit 0) is set AND OVFIE enable (bit 1) is set. Latch remains asserted until software clears DVCR.OVF.

func (*DIVU) Read

func (d *DIVU) Read(addr uint32) uint32

Read reads a DIVU register by full address (0xFFFFFF00-0xFFFFFF14). The SH-2 also exposes non-destructive aliases of DVDNTH and DVDNTL at 0xFFFFFF18 and 0xFFFFFF1C, returning the remainder and quotient of the last division without affecting DIVU state. The SH-7604 manual documents these addresses as reserved, but the real hardware mirrors DVDNTH/DVDNTL there and NiGHTS relies on reading the quotient from 0xFFFFFF1C in its vertex projection code.

func (*DIVU) Reset

func (d *DIVU) Reset()

Reset returns the division unit to power-on state.

func (*DIVU) Write

func (d *DIVU) Write(addr uint32, val uint32) bool

Write writes a DIVU register by full address (0xFFFFFF00-0xFFFFFF14). Writing DVDNT triggers 32/32 division. Writing DVDNTL triggers 64/32 division. Returns true if a division overflow interrupt should be generated.

type DIVUState added in v0.3.2

type DIVUState struct {
	DVSR   uint32
	DVDNT  uint32
	DVDNTH uint32
	DVDNTL uint32
	DVCR   uint32
	VCRDIV uint32
}

DIVUState holds the division unit registers.

type DMAC

type DMAC struct {
	// contains filtered or unexported fields
}

DMAC implements the SH-2 on-chip 2-channel DMA controller.

func (*DMAC) IRQAsserted

func (d *DMAC) IRQAsserted(ch int) bool

IRQAsserted returns true when the DMAC channel's transfer-end interrupt line is currently driven to the INTC: TE latch (bit 1) is set AND IE enable (bit 2) is set. Latch remains asserted until software clears CHCR.TE.

func (*DMAC) Read

func (d *DMAC) Read(addr uint32) uint32

Read reads a DMAC register by full address (0xFFFFFF80-0xFFFFFFB0).

func (*DMAC) ReadDRCR

func (d *DMAC) ReadDRCR(addr uint32) uint8

ReadDRCR reads a DRCR register (byte access at 0xFFFFFE71-0xFFFFFE72).

func (*DMAC) Reset

func (d *DMAC) Reset()

Reset returns the DMAC to power-on state.

func (*DMAC) Stalling

func (d *DMAC) Stalling() bool

Stalling returns true if the DMAC is occupying the bus.

func (*DMAC) Tick

func (d *DMAC) Tick() int

Tick decrements the stall countdown by one cycle. When the countdown reaches zero, TE is set on the completed channel. Returns the channel number that completed, or -1 if no completion occurred.

func (*DMAC) Write

func (d *DMAC) Write(addr uint32, val uint32) int

Write writes a DMAC register by full address (0xFFFFFF80-0xFFFFFFB0). Returns the channel number (0 or 1) if a transfer completed and interrupt should be checked, or -1 otherwise.

func (*DMAC) WriteDRCR

func (d *DMAC) WriteDRCR(addr uint32, val uint8)

WriteDRCR writes a DRCR register (byte access at 0xFFFFFE71-0xFFFFFE72).

type DMACChanState added in v0.3.2

type DMACChanState struct {
	SAR    uint32
	DAR    uint32
	TCR    uint32
	CHCR   uint32
	VCRDMA uint32
}

DMACChanState holds one DMA channel's registers.

type DMACState added in v0.3.2

type DMACState struct {
	Ch          [2]DMACChanState
	DMAOR       uint16
	DRCR        [2]uint8
	NextCh      int
	StallCycles int
	StallCh     int
}

DMACState holds the on-chip DMA controller state.

type ExecState added in v0.3.2

type ExecState struct {
	PrevPC     uint32
	DelayPC    uint32
	InDelay    bool
	NMIPending bool
	// NMIReq is the cross-goroutine NMI request not yet folded into
	// NMIPending; it can be set-but-unfolded at a frame boundary.
	NMIReq     bool
	IntInhibit bool

	PendingOp    uint8
	PendingStep  uint8
	PendingCount uint8
	PendingN     uint8
	PendingAddr  uint32
	PendingVal   uint32
	PendingVal2  uint32
	PendingImm   uint32

	LastLoadReg  uint8
	DeferredOp   uint16
	HasDeferred  bool
	LoadUseStall bool

	MultiplierBusyUntil uint64
	BusStall            uint32
	NextPeripheralEvent uint64

	// Fetch-line memo. Captured verbatim: it stays coherent because
	// the cache it resolves into is restored byte-for-byte.
	FetchLineAddr uint32
	FetchLineWay  int
	FetchLineOff  uint32

	SBYCR uint8
	BCR1  uint16
}

ExecState holds the pipeline and execution-engine state.

type FRT

type FRT struct {
	// contains filtered or unexported fields
}

FRT implements the SH-2 on-chip free-running timer. The FRT provides a 16-bit free-running counter, output compare, and input capture. Input capture is used for inter-CPU communication in the Saturn (MINIT/SINIT writes).

func (*FRT) ClearInputCapture added in v0.3.0

func (f *FRT) ClearInputCapture()

ClearInputCapture clears the input-capture flag (ICF) and its read latch. Used on a system reset (CKCHG/SYSRES), which turns off the peer SH-2 that drives cross-CPU input capture, so a capture latched just before the reset must not survive it.

func (*FRT) IRQFlags

func (f *FRT) IRQFlags() uint8

IRQFlags returns the currently asserted FRT interrupt flags masked by their enable bits. Bit positions match FTCSR/TIER: ICF=0x80, OCFA=0x08, OCFB=0x04, OVF=0x02. Non-zero means an interrupt is being asserted to the INTC. Flags remain asserted until software writes 0 to the corresponding FTCSR bit.

func (*FRT) InputCapture

func (f *FRT) InputCapture() bool

InputCapture latches the current FRC value into ICR and sets the input capture flag. Used by MINIT/SINIT writes. Returns true if the ICF interrupt is enabled.

func (*FRT) Read

func (f *FRT) Read(addr uint32) uint8

Read reads an FRT register by full address (0xFFFFFE10-0xFFFFFE19). FRT registers are byte-access only.

func (*FRT) Reset

func (f *FRT) Reset()

Reset returns the FRT to power-on state.

func (*FRT) Write

func (f *FRT) Write(addr uint32, val uint8)

Write writes an FRT register by full address (0xFFFFFE10-0xFFFFFE19). FRT registers are byte-access only.

type FRTState added in v0.3.2

type FRTState struct {
	FRC       uint16
	OCRA      uint16
	OCRB      uint16
	ICR       uint16
	TIER      uint8
	FTCSR     uint8
	ReadFlags uint8
	TCR       uint8
	TOCR      uint8
	Prescaler uint16
	Temp      uint8
	LastSync  uint64
	NextEvent uint64
}

FRTState holds the free-running timer state, including the TEMP register for the 8-bit byte-pair access protocol and the FTCSR read-then-write-0 clear tracking, both of which span instructions.

type INTC

type INTC struct {
	// contains filtered or unexported fields
}

INTC implements the SH-2 on-chip interrupt controller. It manages priority levels for internal interrupt sources (FRT, DIVU, etc.) and routes them to the CPU.

func (*INTC) AssertSource

func (i *INTC) AssertSource(s IntSource)

AssertSource marks an interrupt source as possibly asserted. Called by a peripheral's route function when the peripheral's status flag transitions high. processInterrupt reconciles stale-true bits lazily.

func (*INTC) Read

func (i *INTC) Read(addr uint32) uint16

Read reads an INTC register. The addr parameter is the full 32-bit address (0xFFFFFE60-0xFFFFFEE4).

func (*INTC) Reset

func (i *INTC) Reset()

Reset returns the INTC to power-on state. Per manual Sec 5.3.8 the ICR's initial value is H'8000 when the NMI input pin is high and H'0000 when it is low. On the Saturn the NMI pin is pulled high at boot (SMPC asserts it briefly only on reset-button presses), so the NMIL bit (bit 15) is set.

func (*INTC) SetNMIL

func (i *INTC) SetNMIL(level bool)

SetNMIL sets or clears the NMIL bit (bit 15) of the ICR register. NMIL is a read-only bit that reflects the NMI input pin level.

func (*INTC) Write

func (i *INTC) Write(addr uint32, val uint16)

Write writes an INTC register. The addr parameter is the full 32-bit address (0xFFFFFE60-0xFFFFFEE4).

Reserved bits are masked to zero per manual Sec 5.3:

  • IPRA (0xFFFFFEE2): bits 3-0 reserved -> 0xFFF0
  • IPRB (0xFFFFFE60): bits 7-0 reserved -> 0xFF00
  • VCRA (0xFFFFFE62): bits 15, 7 reserved -> 0x7F7F
  • VCRB (0xFFFFFE64): bits 15, 7 reserved -> 0x7F7F
  • VCRC (0xFFFFFE66): bits 15, 7 reserved -> 0x7F7F
  • VCRD (0xFFFFFE68): bits 15, 7-0 reserved -> 0x7F00
  • VCRWDT(0xFFFFFEE4): bits 15, 7 reserved -> 0x7F7F
  • ICR (0xFFFFFEE0): bit 15 NMIL read-only, only bits 8 and 0 writable

type INTCState added in v0.3.2

type INTCState struct {
	IPRA    uint16
	IPRB    uint16
	VCRA    uint16
	VCRB    uint16
	VCRC    uint16
	VCRD    uint16
	ICR     uint16
	VCRWDT  uint16
	Pending uint16
}

INTCState holds the interrupt controller registers and the pending source bitmask.

type IntSource

type IntSource uint8

IntSource identifies an on-chip interrupt source. Values are ordered by manual Sec 5.2.5 Table 5.4 fixed tie-break priority (high -> low). Iterating the pending bitmask from LSB to MSB picks the higher priority source on equal IPR-level ties.

type Registers

type Registers struct {
	R    [16]uint32 // General purpose registers (R15 is stack pointer)
	PC   uint32     // Program counter
	PR   uint32     // Procedure register (return address for BSR/JSR)
	SR   uint32     // Status register
	GBR  uint32     // Global base register
	VBR  uint32     // Vector base register
	MACH uint32     // Multiply-accumulate high
	MACL uint32     // Multiply-accumulate low
}

Registers holds the programmer-visible state of the SH-2.

func (*Registers) ClearT

func (r *Registers) ClearT()

ClearT clears the T bit in SR.

func (*Registers) IMASK

func (r *Registers) IMASK() uint8

IMASK returns the interrupt mask level (0-15) from SR.

func (*Registers) S

func (r *Registers) S() bool

S returns the S bit from SR.

func (*Registers) SetIMASK

func (r *Registers) SetIMASK(level uint8)

SetIMASK sets the interrupt mask bits in SR.

func (*Registers) SetT

func (r *Registers) SetT()

SetT sets the T bit in SR.

func (*Registers) SetTVal

func (r *Registers) SetTVal(v bool)

SetTVal sets the T bit to 1 if v is true, 0 otherwise.

func (*Registers) T

func (r *Registers) T() uint32

T returns the T bit from SR.

type State added in v0.3.2

type State struct {
	Reg    Registers
	Cycles uint64
	Halted bool
	IRL    uint32 // packed level<<16 | vector, the SCU-driven line latch

	Exec  ExecState
	Cache CacheState
	INTC  INTCState
	FRT   FRTState
	DIVU  DIVUState
	DMAC  DMACState
	WDT   WDTState
}

State is a complete snapshot of the CPU's serializable state for save states. State() and SetState() are pure field copies: nothing is re-derived, invalidated, or recomputed on restore, so a round-trip covers every field with no carve-outs. Excluded are only per-cycle scratch set fresh before any read (ir, addrError, stepBus, branchTaken, frameCyc) and construction wiring (bus, callbacks, isMaster).

The consumer serializes these fields itself (the sh2 package exposes state, it does not serialize); field encodings and their stability rules live with the serializer.

type WDT

type WDT struct {
	// contains filtered or unexported fields
}

WDT implements the SH-2 on-chip Watchdog Timer (manual Sec 12). It consists of an 8-bit free-running counter (WTCNT) clocked from the CPU via a prescaler, a control/status register (WTCSR) for enable / mode / CKS / overflow flag, and a reset control register (RSTCSR). Two modes are selected by WTCSR.WT/IT:

  • Interval mode (WT/IT=0): overflow sets WTCSR.OVF and raises an interval-interrupt (ITI) through the INTC. The latch is sticky until software clears it via the A5-keyed word-write path.
  • Watchdog mode (WT/IT=1): overflow sets RSTCSR.WOVF and would trigger a CPU reset on hardware. Reset is NOT modeled here a log line surfaces the event.

All three registers share a word-write protection scheme (manual Sec 12.2.4): WTCSR/WTCNT live at 0xFFFFFE80 (word-aligned) with high-byte 0xA5 selecting WTCSR and 0x5A selecting WTCNT; RSTCSR at 0xFFFFFE82 accepts 0xA500 (clear WOVF) or 0x5A?? (update RSTE/RSTS). Any other high byte discards the write.

The CPU drives the WDT via deadline scheduling: nextEvent holds the absolute CPU cycle at which the next WTCNT wrap will occur, and tickPeripherals compares against that instead of calling into the WDT every cycle. syncTo reconciles lastSync->now on demand (register access, deadline hit, reset).

func (*WDT) IRQAsserted

func (w *WDT) IRQAsserted() bool

IRQAsserted returns true when the WDT is driving an interval interrupt request line: OVF latch set AND interval mode selected. Watchdog-mode overflow does not raise ITI.

func (*WDT) Read

func (w *WDT) Read(addr uint32) uint8

Read reads a WDT register byte. Read addresses per manual Sec 12.1.4 Table 12.2:

  • 0xFFFFFE80: WTCSR
  • 0xFFFFFE81: WTCNT
  • 0xFFFFFE82: undefined; returns 0.
  • 0xFFFFFE83: RSTCSR

RSTCSR's read address is offset +1 from its write address because its word-write places the register value in the low byte of the word (big-endian), so byte-wise the register lives at 0xFFFFFE83.

func (*WDT) Reset

func (w *WDT) Reset()

Reset returns the WDT to power-on state per manual Sec 12.2: WTCSR=0x18 (reserved bits 4-3 set), WTCNT=0x00, RSTCSR=0x1F (reserved bits 4-0 set).

func (*WDT) WriteWord

func (w *WDT) WriteWord(addr uint32, val uint16)

WriteWord handles a 16-bit write at the word-aligned address 0xFFFFFE80 or 0xFFFFFE82, applying the manual's high-byte key.

type WDTState added in v0.3.2

type WDTState struct {
	WTCSR     uint8
	WTCNT     uint8
	RSTCSR    uint8
	Prescaler uint32
	LastSync  uint64
	NextEvent uint64
}

WDTState holds the watchdog timer state.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL