# megadrive-rust-fast The ladder-gated speed fork of [megadrive-rust](https://github.com/alewman/megadrive-rust), as z80-rust-fast, m68000-rust-fast and ym2612-rust-fast are of their cores. **The rule: on every frame of every case it is the same board as upstream.** Every kept change is gated by `scripts/ladder.sh`: - **Rung 1:** `cargo test`, which covers: - the example cartridges against megadrive-python's committed traces; - the EEPROM vectors; - `frame_rgb_into` against `frame_rgb`; - with SDL2 installed, the window, headless, read back from the screen. - **Rung 2:** all 37 lockstep cases at full length (69,900 frames) against upstream's `md-trace` at `8c1f125`. Upstream is identical to megadrive-python on every one of them, so identical here is identical to the reference. **Seeded faults, 29 of 29 caught** (`scripts/seeded_faults.py --frames 300` at `b4f1f72`): - the 24 upstream's gate is held to; - five more, one in each of this fork's changes: the timing cache's tag, the memo's key, the probe's buffers, the next-edge table, the mixer's table. The thinnest catches are the mixer's table, the 6-button counter and the EEPROM page wrap, each seen by one check of 42. Speed comes only from doing the same work faster. Nothing in the board's model, its timings or its output changes. The package is `megadrive-rust-fast`; the crate keeps the name `megadrive_rust`. ## Speed so far `scripts/ab.sh`, 600 frames of each workload from power-on, best of 5 alternating runs on one efficiency core (cpu 31) of the shared i9-13900K, 2026-10-12. Sound and picture are included. Every row has the same checksums. | Workload | Fork point `fe8c769` | Now (`b4f1f72`) | Speed-up | With PGO | Speed-up | | --- | ---: | ---: | ---: | ---: | ---: | | Sonic the Hedgehog | 2.400 s (250 fps) | 1.626 s (369 fps) | ×1.476 | 1.440 s (417 fps) | ×1.667 | | Streets of Rage 2 | 1.897 s (316 fps) | 1.349 s (445 fps) | ×1.406 | 1.196 s (502 fps) | ×1.586 | | Gunstar Heroes | 2.406 s (249 fps) | 1.658 s (362 fps) | ×1.451 | 1.476 s (407 fps) | ×1.630 | | Overdrive 2 | 1.600 s (375 fps) | 1.306 s (459 fps) | ×1.225 | 1.144 s (524 fps) | ×1.399 | | **Total** | 8.303 s | 5.939 s | **×1.398** | 5.256 s | **×1.580** | - **"Now"** is the default build: `cargo build --release` on stable 1.90. - **"With PGO"** is `scripts/pgo.sh`: the same source built with profile-guided optimization on toolchain 1.93.1, the one here with llvm-profdata. That toolchain alone is 4% slower than stable 1.90; profile-guided, it is ×1.129 over the default build in a run of its own. The "With PGO" column is from that run; the other two are from one run together. - **PGO generalizes:** five cartridges outside its training set (Castlevania Bloodlines, Sonic 3, Phantasy Star IV, NBA Jam, Super Street Fighter II) gain ×1.08 to ×1.12. - **The PGO md-trace is gated too:** it is identical to upstream on all 37 cases. At 59.92 frames a second, Sonic now runs at 6.2 times real time on an efficiency core (7.0 with PGO). ## How it is measured - `md-bench` runs a cartridge as `md-play` does (pads, `run_frame`, the frame's sound mixed, the picture as RGB) and prints the time and a checksum of the sound and the last picture. - `scripts/bench.sh` times four cold boots with scripted play: Sonic, Streets of Rage 2, Gunstar Heroes, Overdrive 2. - `scripts/ab.sh BASE` builds a base revision and the working tree, and alternates them on one core cartridge by cartridge, keeping each one's best. The machine is shared, and A/A runs agree within 0.5% this way. It also fails if the two sides' checksums differ. - `md-profile` (feature `profile`) is a sampling profiler. It records SIGPROF samples up the frame-pointer chain, because `perf` is not allowed on the build machine. `scripts/profile.py` and `scripts/lines.py` turn the samples into functions and lines. - `scripts/seeded_faults.py` breaks the board one place at a time and must catch every break. Five of the faults aim at this fork's own changes. - `scripts/pgo.sh` makes an optional profile-guided build. ## Kept Each row is a ratio from `scripts/ab.sh` against the commit before it, with identical checksums, followed by a clean ladder. | Commit | Change | Speed-up | | --- | --- | ---: | | `7c23919` | The Z80's access offsets as a `Copy` array behind a direct-mapped cache. Before, they were a SipHash `HashMap` of `Arc` slices, looked up and cloned once per Z80 instruction: 17% of the time went to reference counts, clone/drop and hashing. | ×1.196 | | `409483d` | Release profile: fat LTO, one codegen unit. The hot paths cross four crates. | ×1.074 | | `409483d` | A last-lookup memo in front of that cache: the instruction waiting at the 68000's clock is looked up again after each 68000 step (4.3 lookups per Z80 instruction). | ×1.019 | | `a5dc15c` | The Z80 probe keeps its buffers from one probe to the next. Before, each probe built three `Vec`s and a `HashMap`, 1.1M times in 600 frames of Sonic. | ×1.017 | | `b98f14c` | HV-counter reads look up pixel position and next edge in per-line-offset tables instead of binary searches, which were 14% of Overdrive 2 (it polls the counter). The mixer's common case (no shadow/highlight, no debug register) picks the layer from a 64-entry table of the same rules. | ×1.058 | | `f16f126` | `frame_rgb_into`: the picture written row after row into one reused buffer, which md-play copies straight into an RGB888 texture. Neutral in the benchmark; it saves md-play an allocation per row and a repacking. | ×1.00 | ## Not kept | Change | Result | | --- | --- | | The offsets as 8 bytes of T-states instead of 72 bytes of master clocks | ×0.98 | | A 512-way timing cache instead of 4096 | ×0.995 | | Prearbitration's access list taken out and put back instead of cloned | ×0.93, three times | | The same list read by index | ×1.005, noise | | ym2612-rust-fast as the FM core (measured in a scratch worktree, not adopted) | ×1.021 | Measured, not changed: - The idle VDP syncs, one per 68000 step, cost 3 to 5%. - The zero-run Z80 catch-ups cost about 19%. In these, the instruction waiting at the 68000's clock is re-examined, and its accesses before that clock are settled, after every 68000 step: the model's lockstep itself, done cheaply already. ## Where the time goes now `md-profile` on Gunstar Heroes at `b98f14c`, 1,800 frames, inclusive: | Share | What | | ---: | --- | | 39% | Bringing the sound chips up to time (`Devices::sound_sync`). The YM2612 core is 30% of the total and the PSG core 7%. Both step every chip clock, as the die does. | | 30% | The Z80 kept in step with the 68000 (`Md::catch_up_z80`). The Z80 core itself is about 9%; the rest is timing: the access-offset lookups, prearbitration and the probe. | | 23% | The 68000's bus cycles (`Md::bus_cycle`) | | 11% | The VDP (`Vdp::sync`), the renderer's lines included | What is left in the board is spread thin, a few percent per site. The larger steps are in the cores: - **A sn76489-rust-fast:** the PSG is 7% of Gunstar and 14% of Overdrive 2, stepped every Z80 clock. - **The YM2612:** ym2612-rust-fast measures ×1.021 here. - **m68000-rust-fast:** it would first need the board's two hooks merged into it. Each would be a decision about this fork's dependencies; none has been taken. --- # megadrive-rust (upstream's README) A Rust **Sega Mega Drive / Genesis** board, transcribed from [megadrive-python](https://github.com/alewman/megadrive-python) at the frozen pin `megadrive-rust-pin-1` (`d7882e1`) and held in lockstep with it: on every case of the gate the two boards' traces are identical, frame for frame. A trace covers: - both CPUs' registers; - every memory; - every field of the VDP; - the picture; - both sound chips' samples; - the analogue mix. It runs on the family's Rust cores: | Chip | Core | Pin | | --- | --- | --- | | 68000 | [m68000-rust](https://github.com/alewman/m68000-rust) | `ce3b489` (main, with the board's two hooks, see below) | | Z80 | [z80-rust](https://github.com/alewman/z80-rust) | `3b15c1d` (= z80-python `b62891b`) | | YM2612 / YM3438 | [ym2612-rust](https://github.com/alewman/ym2612-rust) | `3061637` (= ym2612-python `2c2ab23`) | | SN76489 (the VDP's PSG) | [sn76489-rust](https://github.com/alewman/sn76489-rust) | `c5fc09e` (= sn76489-python `9ed3b85`, the chip of the board's `b0acbc8`) | Why it exists: the Python board is the readable reference and is slow by design. This board is the same machine at a speed that can be played, so cartridges can be tested on our own emulator. `src/` is the reference's `src/megadrive_python/` module for module: - `machine`, `arbiter`, `io`, `eeprom`, `cartridge`, `render`, `vdp`, `board`, `system`, `audio`, `wav` and `png`; - the command line as `md-run`. Each keeps its names, its order and its citations. Nothing is redesigned. Where Rust forced a difference, the module header says what it is ([docs/handoff-brief.md](docs/handoff-brief.md), "The shape Rust forces"). The reference's docs (`docs/start-here.md`, `docs/timing.md`, `docs/undocumented-behavior.md`, `docs/validation.md`) are the documentation of what is modelled and why. ## Running a cartridge ```text md-run CART [--machine genesis] [--frames 600] [--png frame.png] [--wav sound.wav] [--no-sound] [--press start --press-at 300] [--pad 6button] [--save game.srm] [--tmss-rom BOOT.zip] ``` The machines are the reference's: `genesis`, `genesis-tmss`, `genesis2`, `genesis3`, `megadrive`, `megadrive-tmss`, `megadrive2`, `megadrive-japan`, `megadrive2-japan`, and `nuked-md` (the die's DMA figures). The board comes from MAME's software list when `/usr/share/games/mame/hash/megadriv.xml` is installed, else from the header, as in the reference. ## Playing in a window ```text cargo build --release --features frontend # needs SDL2 (libsdl2-dev) target/release/md-play CART [--machine NAME] [--scale 3] [--no-audio] [--no-fm] [--skip N] [--pad 6button] [--pad2 none] [--save game.srm] [--tmss-rom BOOT.zip] [--fullscreen] ``` | Key | Does | Key | Does | | --- | --- | --- | --- | | Arrows | D-pad | Z X C, or J K L | A B C | | Enter | Start | A S D | X Y Z | | Q | Mode | Backspace | the reset button | | Tab (held) | fast forward | F3 | pause | | F5 | power cycle | F11 | fullscreen | | F12 | screenshot to `screenshots/` | Esc | quit | A game controller works too, on port 1 with the keyboard and the second on port 2: A, B, C are its X, A, B; the 6-button pad's X, Y, Z are left shoulder, Y and right shoulder; Start is Start and Mode is Back. Without `--machine` the machine comes from the header's country codes: the USA's Genesis first, then a PAL Mega Drive, then a Japanese one. `md-play` is the reference's `frontend.py` (`src/frontend.rs` and `src/play.rs`) on SDL2 itself instead of pygame-ce. The sound queue sets the pace, so the console runs at its own 59.92 Hz (49.70 Hz PAL). Unlike the reference on PyPy, this board has the speed for it with the YM2612 on. The title bar shows the frame, the emulated time and the speed. The window needs the `frontend` feature, so the gate and CI build without SDL. `cargo test --features frontend` also runs the window headless, under SDL's dummy drivers. ## Speed `md-run --frames 1800`, one core of a shared i9-13900K (load average about 30), 2026-10-11: | Cartridge | With the YM2612 | `--no-sound` | | --- | ---: | ---: | | Overdrive 2 | 376 fps, 6.3x real time | 522 fps | | Streets of Rage 2 | 281 fps, 4.7x | 384 fps | | Gunstar Heroes | 259 fps, 4.3x | 323 fps | | Sonic the Hedgehog | 246 fps, 4.1x | 348 fps | The reference runs these at 10-20 fps on PyPy with sound. Nothing has been optimized yet: this is the transcription, and speed is a `-fast` fork's job, as for the cores. ## The gate The reference is megadrive-python at `megadrive-rust-pin-1`, on PyPy 7.3.23 with exactly the four cores its `pyproject.toml` pins. Both boards run the same cartridge with the same inputs and write the same trace (`src/trace.rs`, `scripts/md_trace.py`). After every frame a trace records: - both CPUs' full state; - a CRC-32 of each memory (work RAM, Z80 RAM, VRAM, CRAM, VSRAM, the battery); - every field of the VDP (registers, command, FIFO with commit times, read buffer, DMA, interrupts, counters, slot position, line events, scroll latches); - the picture as CRAM indices and as RGB; - the FM's and PSG's samples, and the analogue mix's output; - the board's clocks (bank, bus request, both refreshes, the arbiter's grid). A case passes when the two traces are identical, byte for byte. `python3 scripts/lockstep.py`, 2026-10-11, at this repository's first commit: **37 of 37 cases identical**, 69,900 frames (about 19 emulated minutes). | Rung | Cases | Frames | | --- | --- | ---: | | The reference's test ROMs | VDPFIFOTesting on four machines; Nemesis's sprite masking ROM; MoD's `gen_test_z80_bus`; r57shell's VDP tests and `joy_speed` (6-button pad); Sega's MD Soft Checker; Nemesis's six YM2612 test ROMs; the 240p Test Suite | 12,600 | | Cold boots | Overdrive 2 for 9,000 frames, and Sonic the Hedgehog, Streets of Rage 2 and Gunstar Heroes for 3,600 each with play scripted on the pad, each on the default machine and on `nuked-md` (the die's DMA figures and FM lags) | 39,600 | | Boards | Sonic 3 (FRAM), NBA Jam and Brian Lara Cricket 96 (EEPROM, J-Cart), Phantasy Star IV (battery RAM), Super Street Fighter II (the Sega mapper), Castlevania Bloodlines, and the 5 MB Rickroll cartridge (the mapper found by its own code) | 11,700 | | Machines and buttons | The TMSS boot ROM handing off to Sonic; Sonic on a PAL Mega Drive and a Japanese Mega Drive 2 (the ASIC FM); the reset button, twice in one run and once after a TMSS boot; `--no-fm` with a 6-button pad and nothing on port 2 | 6,000 | Run 14 at a time on a shared machine, the reference took from 26 seconds to 55 minutes a case, and this board 2 to 73 seconds. **A gate that cannot fail proves nothing.** `scripts/seeded_faults.py` breaks the board in 24 places, one at a time, in a copy of the repository. Each breakage is a constant moved by one step or a rule bent, across every module. A broken board is checked against all 37 cases (at most 900 frames each) and against `cargo test`. **All 24 are caught.** Each is caught by 1 to 42 of the 42 checks; the record is in [docs/build-record.md](docs/build-record.md). `cargo test` (also CI) needs neither ROMs nor Python: - **The examples.** `tests/examples/` holds four runs of three cartridges of our own, assembled by `scripts/make_examples.py`. They cover DMA, fill and copy, both interrupts, raster writes to CRAM and VSRAM, a Z80 driving the FM and the PSG through every path to the 68000's side, sprites under shadow/highlight, the window, and 2-cell and full-screen scroll. Each run is replayed against the reference's committed trace. - **The EEPROM vectors.** Three files of bit-banged EEPROM transactions, update by update, one per addressing mode. ## Reproducing ```text scripts/fetch_megadrivepython.sh # the reference at the tag, PyPy venv, the four pinned cores cargo build --release python3 scripts/lockstep.py # every case of scripts/cases.tsv, both boards, compared python3 scripts/seeded_faults.py # after lockstep.py: each fault must be caught python3 scripts/make_examples.py # rewrite tests/examples/ from the reference ``` `scripts/md_trace.py` is the reference's half of the trace; `md-trace` is this board's. They take the same arguments, so one case can be rerun by hand. `--steps A:B` adds a line per 68000 step, to narrow a difference down. ROMs and traces are never committed: `$ROMS`, `$TEST_ROMS` and `$EXTRA_ROMS` say where the local ones are. ## What differs from the reference These paths the reference reaches only through reentrancy are not imitated: - **The Z80 writing $A11100 or $A11200 through its bank window.** The reference probes and resets the Z80 from inside its own step. Here the run stops with a message, as a lock-up does. - **A 68000-to-VDP DMA whose source is the Z80's space or $A1xxxx.** It reads what the reference's would, but without first running the Z80 up to the read. No case of the gate reaches either. m68000-rust needed two hooks for the board, added by its PR #1 (merged as `ce3b489`): - `Cycle::irc`: the reference's board reads the CPU's IRC inside a bus callable, for open bus. - `Bus::acknowledge_clock_credit`: it adds its holds to the CPU's clock inside the acknowledge, for the E clock. The default credit is 0, so every other host is unchanged. ## License MIT, like the reference. The emulators and die models the reference cites (Nuked-MD, Nuked-OPN2, Genesis Plus GX, BlastEm, MAME, Exodus) are cited through it and never read into this repository.