# SPDX-License-Identifier: MIT """Re-establish a board rule at the referee's pins by ablation. Some of the board's rules were first worked out from signals inside Nuked-MD, or from its source, which the family's rules no longer allow (docs/provenance.md). This puts each such rule back on the pins alone: a cartridge built here runs on the referee (Nuked-MD @ 594ca2a, a closed box; its 68000 bus stream only, ``NMD_TRACE_MASK`` 1: /AS, /DTACK, the address and data buses), and the board runs it with the rule as it stands and with each alternative. Every 68000 bus cycle is compared, address, kind, the stall charged and the gap to the one before (``run_nuked_md.compare_rom``, which takes the refresh phases from the referee's own stalls). A rule is re-established when the board as it stands agrees on every cycle and each alternative does not. Cases: - ``refresh-pause``: the work-RAM refresh timer stops while the VDP holds the bus for a 68000-to-VDP transfer (``vdp.RAM_REFRESH_PAUSES``) and counts 112 68000 clocks (``board.RAM_REFRESH_COUNT_MCLK``). Dense work-RAM reads, a walk of 0-15 idle passes (70 MCLK each, so the timer stands at a different count each time), a transfer of 64 or 600 words from the cartridge to VRAM, and dense reads again. - ``dma-trigger``: ``vdp.DMA_TRIGGER_HOLD_MCLK`` and the unarmed trigger's extra CPU cycle, on ``run_dma_trigger.py``'s three cartridges. python scripts/pin_ablation.py refresh-pause [--jobs 8] python scripts/pin_ablation.py dma-trigger """ from __future__ import annotations import argparse import sys from concurrent.futures import ProcessPoolExecutor from pathlib import Path ROOT = Path(__file__).resolve().parents[1] sys.path[:0] = [str(ROOT / "src"), str(ROOT / "scripts")] import nuked_md as nmd # noqa: E402 import run_nuked_md as rn # noqa: E402 from run_ram_refresh import STOP, control, dense # noqa: E402 def refresh_rom(words: int, walk: int) -> bytes: body = rn.UNLOCK + bytes.fromhex("41f900ff0000") # lea $FF0000,a0 source = 0x8000 >> 1 for reg, value in ((0x00, 0x04), (0x01, 0x14), (0x0C, 0x81), (0x0F, 0x02), (0x13, words & 0xFF), (0x14, words >> 8 & 0xFF), (0x15, source & 0xFF), (0x16, source >> 8 & 0xFF), (0x17, source >> 16 & 0x7F)): # fmt: skip body += control(0x8000 | reg << 8 | value) body += control(0x4000) + dense(40) if walk: body += bytes.fromhex("343c") + (walk - 1).to_bytes(2, "big") + bytes.fromhex("51cafffe") body += control(0x0080) + dense(10) # and a second transfer from wherever the timer now stands body += control(0x4000) + bytes.fromhex("4e71") * (walk % 7) + control(0x0080) + dense(10) return rn.cartridge(body + STOP, size=0x20000) def _variant(spec: str): """'module.NAME=value' pairs, comma-separated; '' is the board as it stands.""" import importlib out = [] for item in filter(None, spec.split(",")): name, value = item.split("=") module, attr = name.rsplit(".", 1) out.append((importlib.import_module(f"megadrive_python.{module}"), attr, eval(value))) return out _board_trace = nmd.board_trace def _cpu_only(*args, **kwargs): """The board's 68000 bus log without the transfer's own reads: the referee's side is ``m68k(dma=False)``.""" system, log = _board_trace(*args, **kwargs) return system, [a for a in log if a.kind != "rd"] nmd.board_trace = _cpu_only def score(job: tuple) -> tuple[str, str, int, int]: name, rom, window, variants = job run = nmd.run(rom, stop=rn.REFEREE_RESET + window + 5000, trace=(rn.REFEREE_RESET, rn.REFEREE_RESET + window), trace_mask=1) # fmt: skip reference = run.m68k(dma=False) rows = [] for spec in variants: saved = [] for module, attr, value in _variant(spec): saved.append((module, attr, getattr(module, attr))) setattr(module, attr, value) try: n, diffs, *_ = rn.compare_rom(reference, rom, machine="nuked-md", version=rn.REFEREE_VERSION) finally: for module, attr, value in saved: setattr(module, attr, value) # The work-RAM accesses' own stalls: the refresh, apart from what else moved. ram = sum(1 for e in reference if e.address >= 0xE00000) ram_bad = sum(1 for d in diffs if d.what == "stall" and int(d.detail[:6], 16) >= 0xE00000) rows.append((name, spec or "as it stands", n - len(diffs), n, ram - ram_bad, ram)) return rows CASES = { "refresh-pause": ( [(f"{w} words, walk {k}", refresh_rom(w, k), 150_000 + 80 * w) for w in (64, 600) for k in range(16)], # fmt: skip ["", "vdp.RAM_REFRESH_PAUSES=False", "board.RAM_REFRESH_COUNT_MCLK=105*7", "board.RAM_REFRESH_COUNT_MCLK=119*7", "board.RAM_REFRESH_COUNT_MCLK=126*7"], ), } def dma_trigger_case(): import run_dma_trigger as dt return ( [(f"pattern {p}", dt.cartridge(p), 400_000) for p in dt.PATTERNS], ["", "vdp.DMA_TRIGGER_HOLD_MCLK=0", "vdp.DMA_TRIGGER_HOLD_MCLK=14", "vdp.DMA_TRIGGER_HOLD_MCLK=28", "vdp.DMA_UNARMED_EXTRA_CYCLE=False"], ) def main() -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("case", choices=[*CASES, "dma-trigger"]) parser.add_argument("--jobs", type=int, default=8) parser.add_argument("--variant", action="append", help="add a variant spec") args = parser.parse_args() carts, variants = dma_trigger_case() if args.case == "dma-trigger" else CASES[args.case] variants = variants + (args.variant or []) totals: dict[str, list[int]] = {v or "as it stands": [0, 0, 0, 0, 0] for v in variants} with ProcessPoolExecutor(args.jobs) as pool: for rows in pool.map(score, [(n, r, w, variants) for n, r, w in carts]): for name, spec, agree, n, ram_ok, ram in rows: print(f"{name:24} {spec:40} {agree:6d} of {n:6d} cycles agree; work-RAM " f"stalls {ram_ok} of {ram}", flush=True) # fmt: skip t = totals[spec] t[0] += agree t[1] += n t[2] += agree == n t[3] += ram_ok t[4] += ram print("\ntotals:") for spec, (agree, n, whole, ram_ok, ram) in totals.items(): print(f" {spec:40} {agree} of {n} cycles ({whole} of {len(carts)} cartridges whole); " f"work-RAM stalls {ram_ok} of {ram}") # fmt: skip return 0 if __name__ == "__main__": raise SystemExit(main())