# Handoff: build `allegrex-python`, the PSP's CPU core ## Context you are inheriting The family's shape (charter): CPUs always get their own core; boards compose pinned cores; `x-python` is the specification. This core's first user is `psp-python` (`../psp-python`, Phase 0 beside it), which instantiates it twice (the main CPU with the VFPU, the Media Engine's CPU without). The PSP is an **era 3-4** machine (charter): transaction-level buses, instruction-level CPU timing, a CPU clock (333 MHz) far beyond what Python can run for long, and an operating system that games call. Read psp-python's handoff brief ("HLE versus LLE") before planning any rung that runs a game, and `../emulator-lineage/docs/proposals/2026-11-late-era-method.md` (slices, the shared state format) and `../n64-python/docs/execution-architecture.md` (time-keeping, not decode, is an exact interpreter's cost). Models: `r3000a-python` (MIPS I, little-endian, a COP2 vector unit as a module of the core, a scratchpad) and `vr4300-python` (MIPS III with caches, timing as data, decode generated from a cited table) are the closest; `sh2-python` for the handler subset (the JIT proposal's restricted semantics) and the measured lesson about time-keeping; `z80-python` for readability. Copy their **shape**, never their code. Rules: oracle tiers (validation.md); Python floor 3.11, PyPy green; reference cores are correct, not fast; modern over compat; no dangerous-looking one-liners; never copy a chip file between repositories; no hardware probes; run anything that reads `reference/` with `python -I`; PPSSPP, JPCSP, binutils/gcc's Allegrex patches and kotcrab/mist are GPL closed boxes, never read; vfpu-docs is GPL-3.0 documentation, read for facts and never transcribed; uOFW (a firmware transcription) is not read; Sony's firmware, boot ROM and KIRK keys are never committed, copied or read. ### Read, in this order 1. `README.md`, `docs/start-here.md` (the chip, the ISA contradiction, the boundary, the family's MIPS cores). 2. `docs/isa.md`, `docs/cop0-and-caches.md`, `docs/fpu.md`, `docs/vfpu.md`. 3. `docs/validation.md`, `docs/mame-oracle.md`, `docs/provenance.md`. 4. `reference/docs/vfpu-docs.pdf` (its introduction and the Allegrex chapter in full; the instruction pages as needed), YAPSPD chapters 4, 7 and 9, MD00086 rev 2.50 for each shared instruction. 5. Every `reference/src/pspautotests/tests/cpu/**/*.expected` beside its `.c`/`.S` source (read for what it tests; no licence, so cite, never copy). Then `python -I scripts/fetch_references.py --verify`. ## Scope The Allegrex as the PSP uses it: little-endian, 32-bit, kernel/supervisor/user modes, the segment map (no TLB), CP0 including Sony's control-register space and the debug registers' existence (not their function), MFIC/MTIC and HALT, CP1 single precision, the VFPU as a module, 16 KB I- and D-caches with tags and CACHE operations, interlocks as stall rules, a transaction bus interface, interrupt and NMI inputs, and the PSP-1000 errata as a model-row switch. Out of scope: the protection registers at 0xBC000000 and every other I/O block (psp-python), the ME's control and reset block (psp-python), the PS Vita's PSP mode. ## Proposed names - Repository `allegrex-python`, package `allegrex_python`. - `Allegrex` (the chip; `Allegrex(vfpu=True, model="psp-1000")`), `ChipState` (snapshot), `Cop0`, `Fpu`, `Vfpu` (module `vfpu.py`, its own `VfpuState`), `ICache`, `DCache`, `Bus` (`read(kind, paddr, size) -> (data, cycles)`, `write(...) -> cycles`, `read_line(paddr) -> (data, cycles)`, `write_line(...)`; `size` up to 16 bytes for LV.Q/SV.Q). - Modules: `_decode.py` (generated by `scripts/gen_decode.py` from a committed, cited table `tables/encodings.toml` that we write from the documents: never generated from the Sleigh), `_alu.py`, `_bits.py` (EXT/INS/BSHFL/ROTR/CLZ/MIN/MAX), `_muldiv.py`, `_loadstore.py`, `_branch.py`, `cop0.py`, `fpu.py`, `vfpu/` (`registers.py`, `prefixes.py`, `ops.py`, `transcendental.py`, `convert.py`), `cache.py`, `timing.py` (the cost tables, as data), `bus.py`. ## The import boundary and the sockets - The core imports nothing from the board. The board gives it one `Bus` and pin callables; the core gives `run(until_cycle)`, `step()`, `set_interrupt(level)`, `nmi()`, `reset()`, and the `CPUId` value at construction (0 main, 1 ME). - Time: integer CPU cycles. Bus responses are durations in CPU cycles, computed by the board from its bus clock (the ratio is the board's: the 222/333 MHz settings change it). - Sync points (JIT proposal, accepted 2026-11-25): every uncached transaction and every transaction to a non-RAM physical address; cache refills and write-backs to RAM only when the board says another master (GE, DMA, the ME) is touching that range in the window; interrupts sampled at instruction boundaries; HALT is a wait until the next interrupt, and the board may jump time to it exactly. - Snapshots: every field, including cache lines and tags, the VFPU's registers and prefix state, the multiply/divide and FPU/VFPU busy times, Sony's 32 control registers. ## Unknowns (U) and contradictions (C) - U1. MFIC/MTIC's register: its width and relation to Status.IE (YAPSPD 4.8.2; Sleigh note). Judge: a test (none held). - U2. Which MIPS32 rows the part lacks (MUL, DI/EI, WAIT, RDHWR, SYNCI, SDBBP, DERET, RDPGPR/WRPGPR): RI or something else. Judge: a test like `allegrex_encodings` for each. - U3. The trap instructions (TEQ..TNEI): present or RI. - U4. DIV/DIVU by zero and overflow results (values are in `cpu_div.expected`; derive the rule at rung 1). - U5. MADD/MSUB's exact HI/LO behaviour and timing. - U6. What clears LLbit (exceptions, ERET, another master's write). - U7. Whether the scratchpad is decoded in the core or on the bus (recommend the bus). - U8. Cache associativity, replacement and refill order. - U9. CP0 registers 7, 17-19, 23, 24, 26, 27, 31 and the control space's hardware meaning. - U10. Which interrupt line Count = Compare raises. - U11. Whether the ME's CPU lacks the VFPU in silicon or only in use; what a VFPU opcode does there. - U12. PRId and Config values (main and ME). - U13. The CPU-to-bus clock ratio at each power setting, and the miss cost in CPU cycles. - U14. The debug unit's behaviour (out of scope until a game needs it). - U15. `icache/icache`'s hardware status (pspautotests' 2012 `not_working_on_real_psp.txt` names `icache` and `vfpu`; the VFPU tests were re-recorded in 2026, the icache test is from 2011). - U16. The full CACHE operation table. - U17. Critical-word-first refills (suggested by mem_cycles.txt). - U18. CP1's exact instruction list and condition-bit count. - U19. FPU exceptions: whether any trap. - U20. **The VFPU's transcendental and reciprocal algorithms.** `vfpu/exact` gives bit patterns for sample inputs; a complete bit-exact model needs either the method or tables FITTED to many more hardware samples than we hold. - U21. How many instructions per second games really execute (CPU load under the kernel): needed for psp-python's speed answer. - C1. The ISA's family: "MIPS32 R2-based" (the task brief), "MIPS32 4K licence" (Copetti, presumably), "based on the MIPS II architecture" (vfpu-docs). The instruction set is a MIPS II base with selected MIPS32/R2 instructions, two of them re-encoded, plus Sony's (isa.md). The documents state lineage; only the encodings are evidence. - C2. Pipeline depth: 7 stages (Copetti, unofficial source) vs no other source; nothing in our model depends on it. - C3. BSHFL function 0x18: the Sleigh decodes it as an alias of 0x20; the hardware leaves the destination unchanged (`allegrex_encodings.expected`). The test wins. - C4. "Rounding hardwired to nearest, denormals flushed" is said in vfpu-docs' VFPU chapter about "the FPU"; pspautotests has CP1 `roundmode` and `denormal` tests whose outputs decide CP1 separately. - C5. CACHE operation numbers: the PSP's 0x19/0x1A/0x1B (D-cache hit invalidate / writeback / writeback-invalidate, `cacheop`) do not follow MIPS32's field layout (0x19 would be MIPS32's D-cache Hit Writeback). The PSP's numbering is the part's. ## Milestones (rungs) As validation.md: 0 decode, 1 integer, 2 CP0/exceptions, 3 CP1, 4 caches, 5 VFPU, 6 VFPU transcendentals, 7 timing, 8 seeded faults. Rungs 1-7 need psp-python's M1 (RAM, a PRX loader, an HLE `Kprintf` and enough of the kernel to start a test), built alongside, as sh2-python and sega32x-python were. A rung's report names the judges run, with counts, and their tier. ## Domains and speed **Domains.** The core is inside one domain on the board: the main CPU with its caches and VFPU. The ME's instance is a second domain (its own clock, its own 2 MB eDRAM; it meets the main CPU only at shared DDR, the ME control block and an interrupt: psp-python domains-and-speed). The core itself declares no channels beyond its bus and its interrupt pins. **The need, with its arithmetic (HYPOTHESIS until measured).** - Clock: 222 MHz (most games) or 333 MHz (games that ask, from firmware 3.50 on: DOC, pspsdk `psppower.h` exposes `scePowerSetClockFrequency`; the per-firmware limit is community knowledge, HYPOTHESIS). - Effective IPC 0.5-0.8: single issue, 1-cycle ALU ops, 3-cycle load use, 3-4-cycle taken branches, ~72-cycle DDR misses (cop0-and-caches.md, MEASURED by a third party). - Instructions per second at full load: 222 MHz -> 111-178 M; 333 MHz -> 167-266 M. - Games idle part of every frame in the kernel's idle thread (HALT). Under the HLE kernel that time is skipped exactly (no instruction runs while halted). How much it saves is U21; a busy 3D game is the worst case and is what the table uses. - Python specification for scale: sh2-python runs 0.1-0.2 M instructions/s (MEASURED, sh2-rust docs/status.md); expect the same order here, so **1/550 to 1/2,700 of real time**: an emulated second costs 9-45 minutes. Python rungs are test programs and slices. **Budget per instruction** (desktop-equivalent host cycles on one core; desktop 5.0e9, phone app 4.0e9, phone browser 2.4e9 cycles/s, as n64-python execution-architecture.md): | Rate | Desktop | Phone app | Phone browser | | --- | ---: | ---: | ---: | | 111 M/s (222 MHz, IPC 0.5) | 45 | 36 | 22 | | 178 M/s (222 MHz, IPC 0.8) | 28 | 22 | 13 | | 167 M/s (333 MHz, IPC 0.5) | 30 | 24 | 14 | | 266 M/s (333 MHz, IPC 0.8) | 19 | 15 | 9 | An exact interpreter costs 25-60 host cycles an instruction with cheap time-keeping (n64-python's estimate, HYPOTHESIS) and 89-145 with an SH-2-style scheduler (MEASURED, sh2-rust-fast). VFPU instructions cost more: up to 16 lanes, with flush-to-zero and exact-NaN handling around host floats; native SIMD with flush-to-zero flags (SSE, NEON) helps; WebAssembly SIMD128 has no FTZ mode, so the browser pays a software flush. **Verdict, no-JIT path (Rust -fast, then a cached interpreter, then threads):** - **Desktop:** real time for 222 MHz games if the -fast interpreter reaches 25-45 cycles an instruction; **not** for busy 333 MHz games (19-30 needed). The cached interpreter (exact for cached code: the I-cache sees no stores, as on the R3000A and the VR4300) and memoized block timing are the levers; threads do not help this domain. - **Phone app (no JIT allowed):** not real time at 333 MHz; at the edge at 222 MHz. - **Phone browser:** not real time by this estimate at either clock: it needs `recompile: wasm` (turbo), and probably a named concession for the heaviest games. - The industry's answer is recompilation (PPSSPP ships JIT backends and, where JIT is forbidden, an IR interpreter: OBSERVED from its public builds' options, not measured by us). Ours is turbo's `recompile: native | wasm`, with the exact interpreter as the fallback. The capability record will say plainly: `recompile: none` reaches real time on desktop at 222 MHz, and not at 333 MHz on any target. What to measure first: allegrex-rust's instructions/s on pspautotests' `cpu_alu` loop and its profile split (time-keeping, fetch, handlers, decode), compared with sh2-rust-fast's. ## Open decisions for Aubrey (each with my recommendation) - **A1. A new core repository**, not a variant of r3000a-python, vr4300-python or ee-python. *Recommend* yes: the ISA is a mixture none of them is (start-here.md), and the shared MIPS semantics are too small to be worth a shared library's pins. - **A2. The VFPU in the core**, as `allegrex_python.vfpu`, switched on per instance. *Recommend* yes (vfpu.md: it lives in the CPU's decoder, LSU, branch unit and CP1's errata; it has no second user). The ME instance is `vfpu=False`. - **A3. Modelling level:** instruction-level semantics, transaction-level bus, interlocks and measured latencies as stall rules and cost tables, caches modelled. *Recommend* yes; no judge sees inside a stage. - **A4. vfpu-docs as a facts source only.** It is GPL-3.0 (documentation included). *Recommend* reading its PDF and measured outputs for facts, never its YAML, pseudo-C or tests' source; building its tests in emu-tools-gpl if we want them as programs; and asking its author (its README invites it) whether the instruction descriptions may be used under a permissive licence. Asking is an outside post: Aubrey's call. - **A5. The transcendentals:** FITTED tables from `vfpu/exact` and any further hardware samples, marked FITTED, until the method is known. *Recommend* yes, with a named concession in turbo only if a table is found to differ. - **A6. Provisional defaults** (2026-11-12 rule): every MIPS32 row the part may lack (U2, U3) raises Reserved Instruction; MFIC/MTIC as one interrupt-enable word ANDed with Status.IE (U1); scratchpad on the bus (U7). Each marked HYPOTHESIS in code. - **A7. PSP-1000 errata as a model row** (`model="psp-1000"` enables the LVL.Q/LVR.Q CP1 corruption; later models do not). *Recommend* yes, with **no default**: the board's machine row (psp-1000, psp-2000, psp-3000, psp-go) passes the model, so a test result always names the unit it claims to match. Which unit recorded each pspautotests file is not stated in the files (a new unknown for the board, P-U7). - **A8. Local until rung 3,** then public with minimal CI after a provenance check. *Recommend* yes. - **A9. sources.md rows** as proposed in psp-python's docs/provenance.md. *Recommend* adding them as written there. ## What was not verified in this phase (candour) - No test program was run: there is no detector built (MAME has no PSP; PPSSPP would be a GPL build in emu-tools-gpl, not done tonight). - vfpu-docs was read for its introduction, the Allegrex chapter, the errata and a handful of instruction pages; YAPSPD chapters 4, 5, 7, 8.1 and 9.1 were read; the MIPS32 2.50 manual only for its Release 2 markers. - pspautotests' `.expected` files were read for `allegrex_encodings`, `delayslot/branch` (head), `cacheop`, `eret`, `icache`; the rest only listed. - Every number in "Domains and speed" is an estimate whose inputs are named.