# Handoff: build `sh4-python`, the Dreamcast's CPU core ## Context you are inheriting The family's shape (charter, emulator-lineage `docs/charter.md`): CPUs always get their own core; boards compose pinned cores; `x-python` is the specification and must not grow complicated for speed. This core's first user is [dreamcast-python](../../dreamcast-python) (Phase 0 beside it); NAOMI, NAOMI 2 and Atomiswave use the same CPU family (MAME's `naomi`, `awbios` sets) and would be later boards. The Dreamcast sits between era 3 and era 4 in the charter's table: a 200 MHz dual-issue CPU, thin hardware evidence, Python far too slow for long runs. Models to read first: **sh2-python** (generated decode from the manual's tables, one handler per row, the handler subset and its lint on branch `handler-subset`, a timing module from the manual's tables, a `ChipState` that round-trips) and **vr4300-python**'s Phase 0 (an era-3 RISC core brief: instruction-level semantics with stall rules, caches and TLB modelled, the subset from day one). Rules that bind the work: oracle tiers (validation.md); Python floor 3.11 and PyPy green; reference cores are correct, not fast; modern over compat; no `rm -rf`/`sed -i`/`ln -sfn`; never copy a file between repositories; no hardware probes; run anything that reads `reference/` with `python -I`; GPL emulators (Flycast, reicast, lxdream, WashingtonDC) are closed boxes, never read, never fetched into this repository; Sega's boot ROM and flash are never committed or copied. ### Read, in this order 1. `README.md`, [start-here.md](start-here.md). 2. [isa.md](isa.md), [fpu.md](fpu.md), [mmu-caches-sq.md](mmu-caches-sq.md), [timing.md](timing.md), [reuse-sh2.md](reuse-sh2.md). 3. [validation.md](validation.md), [mame-oracle.md](mame-oracle.md). 4. The manuals: SM sections 2, 5, 6, 7, 8, 9 in full; HM sections 2-8, then 13 (BSC), 14 (DMAC), 12 (TMU), 19 (INTC) as the board needs them. 5. sh2-python `docs/handler-subset.md` on branch `handler-subset`, and its `scripts/gen_decode.py`. Then `python -I scripts/fetch_references.py --verify`. ## Scope The whole SH7750-class chip as the Dreamcast uses it: little-endian (the Dreamcast's setting; the SH-4 supports both, HM 1), privileged and user modes, both register banks, the FPU in all three mode bits, the MMU (Windows CE titles use it), both caches with index and RAM modes, the store queues, exceptions and interrupts (IRL encoded levels, NMI), and the on-chip modules the Dreamcast uses (BSC, DMAC channel 2 for Holly's DMA, TMU, RTC, SCIF for the serial port, INTC, CPG, WDT; UBC and H-UDI as register maps). Out of scope: the SH7750R's extras, the SH7750S/R power-down variants beyond SLEEP and standby as the HM describes them for the SH7750, big-endian mode beyond a construction parameter. ## Proposed names - Repository `sh4-python`, package `sh4_python` (the family's naming rule), chip class `SH7091` (subclass or alias of `SH7750` once U1 is settled; the Dreamcast board constructs `SH7091`). - Modules: `_decode.py` (generated by `scripts/gen_decode.py` from a transcription of SM section 7 and table 8.3), `_transfer.py`, `_arith.py`, `_logic.py`, `_shift.py`, `_branch.py`, `_system.py`, `_fpu_ops.py` (handlers); `softfloat.py` (integer-only binary32/binary64 helpers, pure); `issue.py` (the dual-issue model); `mmu.py`, `cache.py`, `sq.py`; on-chip modules `bsc.py`, `dmac.py`, `tmu.py`, `rtc.py`, `scif.py`, `sci.py`, `intc.py`, `cpg.py`, `wdt.py`, `ubc.py`; `state.py`, `debug.py`, `trace.py`, `console.py`, `disasm.py`, `__main__.py`. ## The import boundary and the sockets - The core imports nothing from the board. The board gives it a bus object; the core gives the board `run(until)`, `step()`, pin setters (`set_irl(level)`, `nmi()`, `reset()`), and the DMAC's DREQ/DACK as callables. - The bus: `read(kind, paddr, size) -> (value, b_cycles)`, `write(kind, paddr, size, value) -> b_cycles`, `burst(kind, paddr, words)` for line fills, write-backs and SQ bursts (32 bytes). `kind` names fetch, data, line fill, write-back, SQ burst, DMAC. - Time: the core counts I-clock cycles as integers; the B:I and P:I ratios come from FRQCR (CPG module); the board answers in B-clocks. - Sync points (JIT proposal): every external transaction (a cache miss, an uncached access, an SQ burst, a write-back, every access to area 0's registers or area 4's TA FIFO) is a sync point; cache hits and on-chip work are not; interrupts are sampled at instruction boundaries (with the SH-4's rules for which instructions block them, SM 5). - Snapshots: every field, including cache lines and tags, both TLBs, URC, the SQs, the issue model's pending locks, so a state loads into a fresh chip and continues identically. ## Domains and speed **Domains and channels.** The SH-4 with its caches, TLBs, SQs and on-chip modules is one domain (dreamcast-python docs/domains-and-speed.md calls it C). Its channels to the rest: the bus transactions above (to Holly's registers, the TA FIFO and texture memory through SQ bursts and DMA, system RAM shared with Holly's and the G1/G2 DMA engines), IRL3-0 from Holly's interrupt controller, NMI, and DMAC channel 2's DREQ/DACK with Holly. **Instructions per second needed.** The SH-4 runs at 200 MHz and can issue two instructions a cycle (SM 8.2): a ceiling of 400 M instructions a second (Hitachi's figure, quoted by Comstedt, is 360 MIPS). Real code runs slower. The only figure we hold is a detector's: MAME charges 1.281 cycles an instruction in the boot ROM's menu, 2.61 M instructions a frame, **156 M instructions a second** (mame-oracle.md), and 90 % of those are a wait loop. For games, a working range of **0.5-1.0 instructions a cycle, 100-200 M instructions a second** (HYPOTHESIS: no game measured; to replace with the board's own counts once it runs games). Wait loops count unless skipped, and skipping is exact only where the loop provably changes nothing observable before its exit condition. **What each tier reaches**, with the family's measured SH-2 figures as the yardstick (the SH-4 interpreter will do more per instruction: dual-issue bookkeeping, a translation check on every access, FPU): - **sh4-python** (PyPy): sh2-python runs 0.09-0.11 M instructions a second with its stage scheduler (its docs/validation.md, "Speed", 2026-10/11). Expect 0.05-0.1 M for the SH-4: **1,000-4,000 times slower than real time**. The boot ROM's first 10 emulated seconds (its Set Date/Time dialog is up by frame 600 in MAME) are about 1.6 G instructions at MAME's count (2.6 M x 600 frames): 4.5-9 hours. The specification runs short targeted cases only (single-step cases, small test programs, short boot windows); long runs belong to the Rust tiers. - **sh4-rust** (transcription): sh2-rust gives 22-45 M a second native and 20-27 M as wasm (its docs/status.md). Expect the SH-4 at half to the same: about 11-45 M native. - **sh4-rust-fast**: sh2-rust-fast's quiet-machine figures (its docs/status.md, 2026-11-26) are 28-31 M a second on an E-core and 57-64 M unpinned on a P-core natively, 20-23 M (E-core) and 38-45 M (P-core) as wasm. For the SH-4: roughly 30-60 M native on a fast core, 20-45 M as wasm. **Against 100-200 M needed: 2-7 times short natively, 3-10 times short in the browser.** - **Cached interpreter** (turbo, no executable memory, allowed everywhere): decode once, replay handler sequences per block, invalidated by the writers mmu-caches-sq.md lists. The family has no measurement yet (the SH-2 pilot, sh2-rust-turbo, is the first); 1.5-3x over a plain interpreter is a HYPOTHESIS. That gives 45-180 M native on a fast desktop core and 30-135 M as wasm. - **Threads** do not help the SH-4 itself (one domain); they carry the PVR2 renderer, the AICA and the drive (dreamcast-python), so the SH-4 gets a whole core. **The honest no-JIT answer** (`recompile: none`): | Target | Need (SH-4) | No-JIT reach (cached interpreter, fast core) | Verdict | | --- | ---: | ---: | --- | | desktop, native | 100-200 M | 45-180 M | **real time for typical games on a fast core, not for heavy ones**; heavy scenes need a recompiler or exact wait-loop skipping | | phone, native (iPhone forbids JIT) | 100-200 M | about the desktop figure on the newest phone cores, half on mid-range ones (HYPOTHESIS, unmeasured) | **not real time in general**; at best light games on top phones | | browser (wasm, no runtime codegen) | 100-200 M | 30-135 M | **not real time** except light games on a fast desktop | | browser with recompile-to-wasm | 100-200 M | unknown | the plausible route for the web hosts; a measurement, not a promise | So the Dreamcast board states: meets real time with `recompile: none` on fast desktop cores for typical software; on phones and in browsers it needs `native` or `wasm` recompilation (where allowed) or named concessions (coarser timing in compiled blocks, inexact wait-loop skipping), each off by default. That is the charter's "say plainly on which targets it cannot". ## Unknowns (U) and contradictions (C) Unknowns, each with what would settle it: - U1. Which SH7750 revision the SH7091 matches (caches, errata, SQ behaviour); whether it differs anywhere visible. Settles: a hardware test program on a real Dreamcast; Sega's documents (set aside for now: dreamcast-python sources.md). - U2. The FRQCR, BSC and wait settings the boot ROM programs (the B and P clocks). Settles: the MAME trace's register writes (partly in mame-oracle.md), then the boot ROM itself. - U3. Behaviour of undefined mode combinations (PR=1 with SZ=1; FIPR/FTRV/FMAC with PR=1: SM's pseudo-code says `undefined_operation()`). Settles: hardware only. - U4. Whether the SH7091 decodes FSCA/FSRRA (SH-4A instructions). Default: illegal. - U5. **FIPR and FTRV bit-exact results.** HM 6.6.1 gives an error bound and says later parts may differ. Default: exact products, one rounding, tagged HYPOTHESIS, the bound asserted. Settles: hardware captures. - U6. URC's exact counting ("incremented each time the UTLB is accessed"): does an access that hits the ITLB count, a P1/P2 access, a failed one? Settles: hardware; Windows CE titles' behaviour as a weak detector. - U7. Pairing at fetch boundaries: branch targets at odd halfwords, I-cache misses, which pair is "fetched simultaneously". Settles: hardware timing loops. - U8. Memory penalties: I-cache and O-cache miss costs, SQ burst cost, uncached access cost to each Dreamcast area. Settles: hardware; until then FITTED, one table, owned by the board. - U9. NaN propagation and default NaN details beyond SM 6's text (to transcribe first). - U10. Interrupt acceptance latency in cycles (between IRL change and the vector fetch). Contradictions: - C1. SM table 7.10 names `1111nnn1mmmm0110` `FMOV @(R0,Rm),DRn`; HM and SM's section 9 say `XDn`. A typo in SM section 7: follow HM, cite both. - C2. Clock and MIPS: 360 MIPS (Hitachi via Comstedt) is 1.8 an instruction a cycle, while MAME charges 0.73-0.78 an instruction a cycle: neither is a measurement of game code. ## Milestones (rungs) As validation.md: rung 0 decode and lints; 1 integer ISA without MMU; 2 FPU; 3 MMU, caches, SQs; 4 timing; 5 the boot ROM with dreamcast-python. Rungs 0-2 need no board (single-step cases and unit tests); rung 3 needs a minimal harness with RAM; rung 5 needs dreamcast-python's milestone 1. A rung's report says which judges ran, with counts and tiers. ## Open decisions for Aubrey (each with my recommendation) 1. **Names.** `sh4-python` / `sh4_python`, class `SH7091` over an `SH7750` base. *Recommend* yes. 2. **Modelling level.** Instruction-level semantics; timing by the issue model of SM section 8 (pairing, latencies, locks as data); caches, TLBs and SQs modelled functionally with transaction-level penalties. *Recommend* this over a stage-by-stage pipeline (no judge sees inside a stage; it would make an already 1,000x-slow core slower). 3. **Reuse of sh2-python.** *Recommend* writing the SH-4 handlers anew from SM section 9 in the same style, with sh2-python as a pinned **differential detector** for the 142 shared encodings, rather than importing its mixins or extracting a shared ISA core (reuse-sh2.md). 4. **The handler subset from day one**, extended with integer-only soft-float helpers and mode-keyed rows, and its lint at rung 0. *Recommend* yes: the SH-4 is where a cached interpreter or a generated Rust interpreter matters most, and integer soft-float is also what FPU exactness needs. 5. **FIPR/FTRV (U5).** *Recommend* the exact-products-one-rounding default, tagged HYPOTHESIS, with the HM's error bound as a property test; revisit if a hardware capture appears. A switch for "fused" versus "MAME-like" results only if a game shows a difference. 6. **Merge sh2-python's `handler-subset` branch** before this core copies its structure (the lint and `_tas8` move are not on sh2-python `main` yet). *Recommend* yes, by whoever owns sh2-python, so the model this core follows is the merged one. 7. **MAME's BSD-licensed SH-4 files** (`cpu/sh/sh4*.cpp`, BSD-3-Clause by their headers): may they be read for facts, as other BSD MAME files are in sources.md? This batch's brief treats all of MAME as closed. *Recommend* keeping them closed for the CPU (the Renesas manuals are complete enough for semantics), and deciding the question once for the board's AICA DSP (dreamcast-python, where it matters more). 8. **Local until rung 2**, then public with minimal CI after a provenance check. *Recommend* yes. 9. **sources.md rows** (proposed in dreamcast-python `docs/sources.md`). *Recommend* adding them as written there. ## What was not verified in this phase (candour) - The SM was read for section 1, the FPU-error lines of section 6, section 7's tables, section 8 in full, and section 9's FADD, FIPR and FLDI0 pages; HM for 3.5, 4.3.7, 4.7, 5.3-5.4, 6.2.3, 6.4, 6.6-6.7. The rest (HM 2, 5 in full, 9-21) was not read in detail. - No SST case was run (there is no core). No KOS homebrew was built or run. - The SH7091 identity (U1) rests on MAME's device name and the HM's SH7750 parts list.