#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """Milestone 2, exits (a) and (b): DMA-timing probes on the board and on the detectors. ``probes/dmaprobe.s`` counts iterations of a 13-cycle loop between MSTAT edges and stores 32 frame counts at $2200 ([HF]'s method: a program measures the cycles it is left). Each variant below is assembled with ca65/ld65 from cc65 2.19 (``CC65_DIR``, default ``~/.local/opt/cc65-2.19/bin``) into ``tests/probe_builds/`` (ignored), given an A78 header by this repository's converter, and run: - on the board, NTSC, started directly (the probes are not signed, so the NTSC BIOS would start them in 2600 mode; labelled "BIOS skipped"); - on MAME 0.285 as ``a7800p`` (the PAL BIOS checks only the region byte, C8; 313 lines, 292 of DMA), reading the results through MAME's Lua; - on ProSystem (BIOS-less, NTSC) through ``scripts/prosystem_run.py --dump``. Cycles per frame = mean count x 13 (BIT zp 3, BMI 2, INC zp 5, BNE 3; + 7 per 256 for the carry pass) over frames 4-31; with ``TIALOOP`` the loop is 16.5 cycles by the documents (16 if a TIA access were fast). The program measures every other frame (it waits a frame between counts) and starts counting about 10 cycles after the edge, so an absolute frame figure is the count's cycles plus 10 to 23; differences between variants cancel that. The figures in brackets are the ones [HF]/[SG] measured. python scripts/probes.py # board only python scripts/probes.py --mame --prosystem """ from __future__ import annotations import argparse import os import statistics import subprocess import sys from pathlib import Path ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT / "src")) from a7800_python import romsets # noqa: E402 from a7800_python.cartridge import a78 # noqa: E402 from a7800_python.cartridge.connector import Linear # noqa: E402 from a7800_python.cartridge.description import CartDescription # noqa: E402 from a7800_python.machine import NTSC, PAL # noqa: E402 from a7800_python.system import System # noqa: E402 CC65 = Path(os.environ.get("CC65_DIR", Path.home() / ".local/opt/cc65-2.19/bin")) BUILD = ROOT / "tests" / "probe_builds" MAME = "/usr/games/mame" BIOS_DIR = str(romsets.mame_rompath()) # $MAME_ROMPATH: a7800.zip, a7800p.zip VARIANTS = { "off": {"DMA": 0, "WHOLE": 1}, "off-tia": {"DMA": 0, "WHOLE": 1, "TIALOOP": 1}, "null": {"DMA": 1, "WHOLE": 1, "ZONEH": 16}, "null-z8": {"DMA": 1, "WHOLE": 1, "ZONEH": 8}, "null-dli": {"DMA": 1, "WHOLE": 1, "ZONEH": 16, "DLI": 1}, "h4w1": {"DMA": 1, "WHOLE": 1, "NOBJ": 4, "KIND": 0, "WIDTH": 1}, "h4w2": {"DMA": 1, "WHOLE": 1, "NOBJ": 4, "KIND": 0, "WIDTH": 2}, "h5w1": {"DMA": 1, "WHOLE": 1, "NOBJ": 4, "KIND": 1, "WIDTH": 1}, "ind": {"DMA": 1, "WHOLE": 1, "NOBJ": 4, "KIND": 2, "WIDTH": 1}, "indw": {"DMA": 1, "WHOLE": 1, "NOBJ": 4, "KIND": 3, "WIDTH": 1}, } def build(name: str, defines: dict) -> tuple[bytes, Path]: BUILD.mkdir(parents=True, exist_ok=True) obj, binary = BUILD / f"{name}.o", BUILD / f"{name}.bin" flags = [f"-D{k}={v}" for k, v in defines.items()] subprocess.run([str(CC65 / "ca65"), *flags, "-o", str(obj), str(ROOT / "probes/dmaprobe.s")], check=True) # fmt: skip subprocess.run([str(CC65 / "ld65"), "-C", str(ROOT / "probes/probe.cfg"), "-o", str(binary), str(obj)], check=True) # fmt: skip rom = binary.read_bytes() headered = BUILD / f"{name}.a78" desc = CartDescription(payload=rom, title=f"dmaprobe {name}", region="ntsc") headered.write_bytes(a78.build(desc) + rom) return rom, headered def counts_from(raw: bytes) -> list[int]: return [raw[2 * i] | raw[2 * i + 1] << 8 for i in range(32)] def cycles(counts: list[int], loop: float) -> float: use = counts[4:] return statistics.fmean(c * loop + (c // 256) * 7 for c in use) def run_board(rom: bytes, machine=NTSC) -> list[int]: system = System(Linear(rom), machine, start="direct") ram = system.board.ram done = 0x2280 - 0x1800 system.run_until(lambda: ram[done] == 0xA5, max_clocks=machine.frame_clocks * 72) return counts_from(bytes(ram[0x2200 - 0x1800 : 0x2240 - 0x1800])) LUA = """ local cpu = manager.machine.devices[":maincpu"] local space = cpu.spaces["program"] emu.register_frame_done(function() if space:read_u8(0x2280) == 0xA5 then local out = {} for i = 0, 63 do out[#out + 1] = string.format("%02x", space:read_u8(0x2200 + i)) end local f = io.open("result.txt", "w"); f:write(table.concat(out)); f:close() manager.machine:exit() end end) """ def run_mame(headered: Path, name: str) -> list[int] | None: out = BUILD / f"mame-{name}" out.mkdir(exist_ok=True) (out / "probe.lua").write_text(LUA) result = out / "result.txt" result.unlink(missing_ok=True) subprocess.run([MAME, "a7800p", "-cart", str(headered), "-rompath", BIOS_DIR, "-homepath", str(out), "-video", "none", "-sound", "none", "-nothrottle", "-noreadconfig", "-skip_gameinfo", "-seconds_to_run", "12", "-autoboot_script", str(out / "probe.lua")], cwd=out, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) # fmt: skip if not result.exists(): return None return counts_from(bytes.fromhex(result.read_text())) def run_prosystem(headered: Path) -> list[int] | None: text = subprocess.run([sys.executable, str(ROOT / "scripts/prosystem_run.py"), str(headered), "--frames", "90", "--every", "1000", "--dump", "2200:40"], capture_output=True, text=True).stdout # fmt: skip for line in text.splitlines(): if line.startswith("RAM 2200:"): return counts_from(bytes.fromhex(line.split(": ")[1])) return None def report(label: str, c: dict[str, float], lines: int, dma_lines: int, zone_ends: dict) -> list[str]: off, null = c["off"], c["null"] out = [f"\n== {label}"] out.append(f"DMA off: {off:,.1f} cycles a frame ({lines} lines: {off / lines:.2f} a line) " f"[measured: 29,850.5 NTSC; 113.5 a line]") # fmt: skip if "off-tia" in c: # Count with a TIA read in the loop: the frame is the same length, so the # extra time per pass is what one TIA access costs beyond a fast cycle. n = c["off-tia"] / 16.5 extra = (off - n * 16) / n out.append(f"TIA access: {extra:+.2f} cycle beyond a fast cycle [measured +0.5]") lost = (off - null) * 4 ends = zone_ends[16] per_line = (lost - 8 - ends * 8) / dma_lines out.append(f"null lists: {lost:,.0f} MARIA clocks lost a frame = {dma_lines} lines x " f"{per_line:.2f} + {ends} zone ends x 8 + 8 [measured 16 a line, 24 on a zone's " f"last line, +8 a frame]") # fmt: skip if "null-z8" in c: extra = ((off - c["null-z8"]) * 4 - lost) / (zone_ends[8] - ends) out.append(f"last line of a zone: +{extra:.2f} clocks [measured +8]") frame_extra = lost - dma_lines * 16 - ends * 8 out.append(f"once a frame: +{frame_extra:.1f} clocks [measured +8]") if "null-dli" in c: dlis = ends + 1 dli_cost = ((null - c["null-dli"]) - 13 * dlis) * 4 / dlis out.append(f"DLI: {dli_cost:+.2f} MARIA clocks of DMA each ({dlis} a frame, the handler's " f"13 cycles taken out) [measured 0]") # fmt: skip per_obj = {k: (null - c[k]) * 4 / dma_lines / 4 for k in ("h4w1", "h4w2", "h5w1", "ind", "indw") if k in c} # fmt: skip if len(per_obj) == 5: gfx = per_obj["h4w2"] - per_obj["h4w1"] out.append(f"per object: 4-byte header {per_obj['h4w1'] - gfx:.2f} [8], 5-byte header " f"{per_obj['h5w1'] - gfx:.2f} [10], direct byte {gfx:.2f} [3], indirect " f"{per_obj['ind'] - per_obj['h5w1'] + gfx:.2f} [6], indirect wide " f"{per_obj['indw'] - per_obj['h5w1'] + gfx:.2f} [9]") # fmt: skip return out def main() -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("--mame", action="store_true") parser.add_argument("--prosystem", action="store_true") parser.add_argument("--only", nargs="*") parser.add_argument("--fault", action="append", default=[]) parser.add_argument("--pal", action="store_true", help="the board on its PAL row (milestone 8)") args = parser.parse_args() machine = PAL if args.pal else NTSC names = args.only or list(VARIANTS) board, mame, pro = {}, {}, {} for name in names: rom, headered = build(name, VARIANTS[name]) loop = 16.5 if VARIANTS[name].get("TIALOOP") else 13 if args.fault: system = System(Linear(rom), machine, start="direct") system.board.faults |= set(args.fault) ram = system.board.ram system.run_until(lambda ram=ram: ram[0xA80] == 0xA5, max_clocks=machine.frame_clocks * 72) counts = counts_from(bytes(ram[0xA00:0xA40])) else: counts = run_board(rom, machine) board[name] = cycles(counts, loop) line = f"{name:9} board {board[name]:10,.1f}" if args.mame: m = run_mame(headered, name) if m: mame[name] = cycles(m, loop) line += f" MAME(PAL) {mame[name]:10,.1f}" if args.prosystem: p = run_prosystem(headered) if p: pro[name] = cycles(p, loop) line += f" ProSystem {pro[name]:10,.1f}" print(line, flush=True) # Zone ends among the DMA lines: zones start on the first DMA line (17), so # the last line of zone k is line 17 + ZONEH*(k+1) - 1. ntsc_ends = {h: sum(1 for k in range(64) if 17 + h * (k + 1) - 1 <= 258) for h in (8, 16)} pal_ends = {h: sum(1 for k in range(64) if 17 + h * (k + 1) - 1 <= 308) for h in (8, 16)} if "off" in board and "null" in board: if args.pal: print("\n".join(report("board (PAL, direct start)", board, 313, 292, pal_ends))) else: print("\n".join(report("board (NTSC, direct start)", board, 263, 242, ntsc_ends))) if "off" in mame and "null" in mame: print("\n".join(report("MAME 0.285 a7800p (PAL BIOS)", mame, 313, 292, pal_ends))) if "off" in pro and "null" in pro: print("\n".join(report("ProSystem (NTSC, no BIOS)", pro, 263, 242, ntsc_ends))) return 0 if __name__ == "__main__": sys.exit(main())