#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """Instruction-order lockstep of this board against a MAME 0.285 trace (milestone 1, exit a). MAME is a detector ([docs/validation.md]): a difference is a question, not a verdict. The trace is ``scripts/mame_trace.py``'s ``error.log`` (one line per instruction: PC A X Y P SP totalcycles beamx beamy frame; R/W lines for the watched addresses). The board runs the same cartridge from the same BIOS. What is compared, per docs/mame-oracle.md: - **Instruction order and registers**: PC, A, X, Y, P & $CF, S (with its page). Spin loops are compared as loops: a run of instructions whose whole register state repeats exactly (``BIT MSTAT / BPL``, ``LDA $F0 / BMI``) is one iteration, however many times it repeats, because the two machines' clocks differ (trap 3) and a wait loop's count follows the clock. The number of iterations dropped on each side is reported. - **Cycles** (trap 3): MAME runs every cycle at 1.79 MHz; the board stretches TIA and 6532 cycles, and every cycle while MEN = 0, to 6 MARIA clocks. So between two consecutive aligned instructions with no collapsed loop between them, ``board clocks - 4 x MAME cycles`` must equal ``2 x the board's slow cycles`` (plus, once DMA is on, the halted periods: milestone 2). Every such segment is checked; the report counts those that are exact. - **INPTCTRL**: the sequence of values written while unlocked, on both sides. python scripts/lockstep_mame.py tests/mame_traces/a7800-asteroid/error.log \\ ".../Atari - Atari 7800 (BIN)/Asteroids (USA).zip" --until dma-on """ from __future__ import annotations import argparse import sys import time from pathlib import Path ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT / "src")) sys.path.insert(0, str(ROOT / "scripts")) import harness # noqa: E402 from a7800_python.system import System # noqa: E402 # Inexact cycle segments that are understood as MAME's departures from the # documents, by the PC of the segment's first instruction. Each must cite why. KNOWN_DETECTOR_ARTIFACTS = { # The BIOS clears the TIA with STA $00,X for X = 1..$2C while INPTCTRL = 0. # MEN = 0 selects the 2600 decoder, so $20-$2C are TIA registers ([MT84] # Figure 2, "2600 mode": TIA at $00-$7F); MAME 0.285 has no MEN decoder and # sends them to MARIA, where $24 is WSYNC: its CPU waits for the line's end # (C16). The board's TIA takes $24 (HMBL) and runs on. 0xFB1D: "C16: MAME's WSYNC at $24 under MEN = 0", } # The NTSC BIOS's last instruction, JMP (CartResetVector), run from RAM at $26BE # (the wiki's commented disassembly: Enter7800Mode at ROM $F7B9, RAM offset $D100). BIOS_HANDOFF = 0x26BE # MAME's reads of the 6532 timer (INTIM, TIMINT), in order. The timer counts # Φ2 periods on the board and CPU cycles on MAME, and the two machines' cycles # differ by every slow access (C11, C12): the value a program reads differs and # so does everything after. With --force-timer the board's k-th timer read # returns MAME's k-th value (the board's RIOT keeps its own state); the count # of forced reads is reported. TIMER_READS: list[int] = [] # MAME's TIA reads ($00-$1F), in order. MAME 0.285 drives all eight bits of a # TIA read (0 in D5-D0 for INPT4/5, $FF for addresses it calls undefined); the # board drives D7/D6 and leaves the rest to the floating bus, as the documents # and the wiki's M.I.A. note say (C17). With --force-tia the board's k-th TIA # read returns MAME's k-th value; how many differed is reported. TIA_READS: list[int] = [] # MAME's reads of SWCHB ($282, the console switches), in order. With # --force-switches the board's k-th SWCHB read returns MAME's k-th value: a # scripted Reset or Select (mame_trace.py --script) then reaches the program # at the same read on both machines, whatever frame each side's script # counted (a setting for following a trace through scripted input). SWCHB_READS: list[int] = [] def mame_records(log: Path, until: str, limit: int): """MAME's instructions up to the stop, and its INPTCTRL writes. Each record is [state, totalcycles, accesses]: ``accesses`` counts the instruction's logged accesses to the slow rows of [MT84] Figure 2 that the trace watches (TIA $00-$1F, 6532 ports $280-$29F): the independent count of slow cycles the cycle check uses (not the board's own counter).""" records, inptctrl = [], [] locked = in_cart = False with log.open("rb") as handle: for raw in handle: parts = raw.split() if len(parts) == 10: pc, a, x, y, p, sp = (int(v, 16) for v in parts[:6]) records.append([(pc, a, x, y, p & 0xCF, sp), int(parts[6]), 0, int(parts[9])]) if pc == BIOS_HANDOFF: in_cart = True if len(records) >= limit: break elif len(parts) == 4 and parts[0] in (b"R", b"W"): address, value = int(parts[1], 16), int(parts[2], 16) if records and (address < 0x20 or 0x280 <= address < 0x2A0): records[-1][2] += 1 if parts[0] == b"R": if 0x280 <= address < 0x2A0 and address & 0x04: TIMER_READS.append(value) if address == 0x282: SWCHB_READS.append(value) if address < 0x20: TIA_READS.append(value) continue if address < 0x20 and not locked: inptctrl.append(value) locked = bool(value & 1) dma_on = address == 0x3C and (value >> 5) & 3 == 2 if dma_on and (until == "dma-on" or (until == "cart-dma-on" and in_cart)): break return records, inptctrl FORCED: list[dict] = [] FORCED_TIA: list[dict] = [] MASKED: list[dict] = [] OPEN_BUS: list[dict] = [] FORCED_SWITCHES: list[dict] = [] def board_records(system: System, until: str, limit: int, faults: set[str], force_timer: bool, force_tia: bool, mask_tia: bool = False, mame_switches: bool = False, mask_open_bus: bool = False): # fmt: skip board, cpu = system.board, system.cpu board.faults |= faults stop = {"hit": False, "in_cart": False} def watch(kind, address, value, clock): dma_on = kind == "W" and address & 0xFF3F == 0x3C and board.inptctrl & 2 dma_on = dma_on and (value >> 5) & 3 == 2 if dma_on and (until == "dma-on" or (until == "cart-dma-on" and stop["in_cart"])): stop["hit"] = True board.bus_observers.append(watch) if force_timer: FORCED.append(harness.force_timer(board, TIMER_READS)) if force_tia: tia_read = board.tia.read forced_tia = {"n": 0, "differed": 0} def read_tia(address): value = tia_read(address) if forced_tia["n"] < len(TIA_READS) and (address & 0xFFFF) < 0x20: mame_value = TIA_READS[forced_tia["n"]] forced_tia["n"] += 1 forced_tia["differed"] += (value | (board.data_bus & 0x3F)) != mame_value # The board ORs the floating bus into a TIA read right after this # call: put MAME's byte on the bus so the OR yields it unchanged. board.data_bus = mame_value return mame_value return value board.tia.read = read_tia FORCED_TIA.append(forced_tia) if mame_switches: harness.mame_switches(board) # difficulty A on both, MAME's default: a setting if mask_tia: MASKED.append(harness.mask_tia_undriven(board)) # C17, a named, counted exclusion if mask_open_bus: OPEN_BUS.append(harness.mask_open_bus(board)) # C18, a named, counted exclusion system.step() # the reset sequence records = [] while len(records) < limit and not stop["hit"]: if cpu.pc == BIOS_HANDOFF: stop["in_cart"] = True state = (cpu.pc, cpu.a, cpu.x, cpu.y, cpu.p & 0xCF, 0x100 | cpu.s) records.append((state, board.clocks, bool(board.inptctrl & 2), board.halted_periods, board.stalled_periods)) # fmt: skip system.step() inptctrl = [value for _, value in system.mode_log] return records, inptctrl def interrupts_excised(states: list) -> tuple[list[int], int]: """Indices of the main-line records: every interrupt handler run is cut out. An interrupt entry is a step where S falls by 3 (BRK, NMI, IRQ push PC and P) and the handler ends at the first later record whose S is back to its value before the entry (the RTI's return). MAME takes a DLI at an instruction boundary as soon as its per-line DMA lump starts; the console takes it one cycle after HALT is released, mid-line, after finishing the instruction DMA stopped (C1, C4, docs/timing.md "The DLI"): the handler lands between different main-line instructions on the two machines while the main line, which the handler preserves, is the same. The handler bodies are compared as a count.""" kept, handlers = [], 0 i, n = 0, len(states) while i < n: kept.append(i) if i + 1 < n and states[i + 1][5] == states[i][5] - 3: base = states[i][5] j = i + 2 while j < n and states[j][5] != base: j += 1 handlers += 1 i = j continue i += 1 return kept, handlers def canonical(all_states: list) -> tuple[list[int], int, int]: """Indices kept after excising interrupt handlers, then collapsing exact repeats of loops of 1-8 instructions; with the loops and handlers dropped.""" main, handlers = interrupts_excised(all_states) states = [all_states[i] for i in main] kept: list[int] = [] dropped = 0 i, n = 0, len(states) while i < n: for length in range(1, 9): if len(kept) >= length and i + length <= n and all( states[i + k] == states[kept[-length + k]] for k in range(length) ): i += length dropped += 1 break else: kept.append(i) i += 1 return [main[k] for k in kept], dropped, handlers def main() -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("log", type=Path) parser.add_argument("cart", type=Path) parser.add_argument("--until", choices=("dma-on", "cart-dma-on", "count"), default="dma-on") parser.add_argument("--limit", type=int, default=2_000_000) parser.add_argument("--fault", action="append", default=[], help="seed a board fault") parser.add_argument("--force-timer", action="store_true", help="take MAME's 6532 timer reads") parser.add_argument("--force-tia", action="store_true", help="take MAME's TIA reads (C17). Tried on Centipede and Ms. Pac-Man: " "the two machines' TIA read counts differ (MAME logs reads the " "board's collapsed polling loops repeat differently), so the queue " "misaligns; kept for the record, not used for the exit") # fmt: skip parser.add_argument("--mask-tia-undriven", action="store_true", help="C17 exclusion: the board's TIA reads in 7800 mode take MAME's " "driven-low undriven bits (by rule, counted); the board's D7 is kept") parser.add_argument("--mame-switches", action="store_true", help="set the console switches as MAME 0.285 defaults them " "(difficulty A on both)") parser.add_argument("--mask-open-bus", action="store_true", help="C18 exclusion: reads nothing drives return MAME's $00 (counted)") parser.add_argument("--force-switches", action="store_true", help="the board's SWCHB reads take MAME's logged values in order " "(follow a trace recorded with a scripted Reset or Select)") parser.add_argument("--script", nargs="*", default=[], metavar="FRAME:ACTION", help="the scripted input the trace was recorded with (mame_trace.py " "--script), applied as MARIA's frame count reaches FRAME") parser.add_argument("--board-factor", type=float, default=1.3, help="with --until count: board instructions per MAME instruction run") args = parser.parse_args() began = time.monotonic() mame, mame_inptctrl = mame_records(args.log, args.until, args.limit) system = System.from_rom(args.cart) board_limit = int(len(mame) * args.board_factor) if args.until == "count" else max( args.limit, len(mame) * 3) if args.force_switches: riot_read, forced = system.board.riot.read, {"n": 0, "differed": 0} def read_switches(address, cycle): value = riot_read(address, cycle) if address & 0x207 == 0x202 and forced["n"] < len(SWCHB_READS): forced["differed"] += value != SWCHB_READS[forced["n"]] value = SWCHB_READS[forced["n"]] forced["n"] += 1 return value system.board.riot.read = read_switches FORCED_SWITCHES.append(forced) if args.script: import frames_mame script = frames_mame.parse_script(args.script) maria, step = system.board.maria, system.step def scripted_step(): actions = script.pop(maria.frame + 1, None) if actions: frames_mame.apply_board(system, actions) return step() system.step = scripted_step mine, my_inptctrl = board_records(system, args.until, board_limit, set(args.fault), args.force_timer, args.force_tia, args.mask_tia_undriven, args.mame_switches, args.mask_open_bus) # fmt: skip if OPEN_BUS: m = OPEN_BUS[0] print(f"C18 exclusion (--mask-open-bus): {m['reads']:,} undriven reads took MAME's $00, " f"{m['differed']:,} of them differing from the board's floating byte") if MASKED: m = MASKED[0] print(f"C17 exclusion (--mask-tia-undriven): {m['reads']:,} TIA reads in 7800 mode took " f"MAME's undriven bits, {m['differed']:,} of them differing from the board's byte") if FORCED_SWITCHES: f = FORCED_SWITCHES[0] print(f"SWCHB reads forced to MAME's values: {f['n']} of MAME's {len(SWCHB_READS)}, " f"{f['differed']} of them differing from the board's own") if FORCED: print(f"timer reads forced to MAME's values: {FORCED[0]['n']} of MAME's {len(TIMER_READS)}") if FORCED_TIA: f = FORCED_TIA[0] print(f"TIA reads forced to MAME's values: {f['n']} of MAME's {len(TIA_READS)}, " f"{f['differed']} of them differing from the board's own byte (C17)") m_kept, m_dropped, m_handlers = canonical([r[0] for r in mame]) b_kept, b_dropped, b_handlers = canonical([r[0] for r in mine]) print(f"interrupt handler runs excised: MAME {m_handlers}, board {b_handlers}") # Walk both streams together. A mismatch inside a spin loop whose iteration # an interrupt split differently on the two sides (the handler came after # the load on one machine and after the branch on the other) is resolved by # leaving the loop on both sides: each stream skips to its first record # whose PC is outside the loop's PCs, and the walk goes on from there. m_aligned, b_aligned = [], [] i = j = 0 first = None resyncs = 0 while i < len(m_kept) and j < len(b_kept): ms, bs = mame[m_kept[i]][0], mine[b_kept[j]][0] if ms == bs: m_aligned.append(m_kept[i]) b_aligned.append(b_kept[j]) i += 1 j += 1 continue loop = {mame[m_kept[k]][0][0] for k in range(max(0, i - 8), i)} if ms[0] in loop and bs[0] in loop: while i < len(m_kept) and mame[m_kept[i]][0][0] in loop: i += 1 while j < len(b_kept) and mine[b_kept[j]][0][0] in loop: j += 1 resyncs += 1 continue first = len(m_aligned) print(f" at the mismatch: MAME {len(m_kept) - i} records left, board {len(b_kept) - j}: " f"{ms} vs {bs}; MAME frame {mame[m_kept[i]][3]}") break print(f"spin loops left at different iterations and re-aligned on exit: {resyncs}") tail_m, tail_b = m_kept[i : i + 4], b_kept[j : j + 4] m_kept, b_kept = m_aligned + tail_m, b_aligned + tail_b n = len(m_aligned) exact = checked = dma_segments = 0 worst: list = [] explained_artifacts: list = [] for k in range(1, first if first is not None else n): mi0, mi1, bi0, bi1 = m_kept[k - 1], m_kept[k], b_kept[k - 1], b_kept[k] if mi1 - mi0 != 1 or bi1 - bi0 != 1: continue # a collapsed loop in between: its length follows each machine's clock checked += 1 _, c0, men, h0, w0 = mine[bi0] _, c1, _, h1, w1 = mine[bi1] mame_cycles = mame[mi1][1] - mame[mi0][1] # Slow cycles by the documents, counted outside the board: every cycle # under the 2600 decoder (MEN = 0), else MAME's logged TIA/6532 accesses. slow = mame[mi0][2] if men else mame_cycles explained = 2 * slow + 4 * (h1 - h0) + 4 * (w1 - w0) residue = (c1 - c0) - 4 * mame_cycles - explained if residue == 0: exact += 1 elif h1 != h0 or mame_cycles > 8: # DMA on either side: the board holds the CPU in whole periods where # MAME suspends it in one lump per line at an instruction boundary # (trap 4); such segments are compared per frame, not per segment. dma_segments += 1 elif mine[bi0][0][0] in KNOWN_DETECTOR_ARTIFACTS: explained_artifacts.append((k, hex(mine[bi0][0][0]), residue)) elif len(worst) < 8: worst.append((k, hex(mine[bi0][0][0]), residue)) def fmt(state): pc, a, x, y, p, s = state return f"PC={pc:04X} A={a:02X} X={x:02X} Y={y:02X} P={p:02X} S={s:03X}" print(f"MAME: {len(mame):,} instructions -> {len(m_kept):,} after collapsing {m_dropped:,} loop iterations") print(f"board: {len(mine):,} instructions -> {len(b_kept):,} after collapsing {b_dropped:,} loop iterations") if first is None and len(m_kept) == len(b_kept): print(f"instruction order and registers: identical over {n:,} aligned instructions") elif first is None: print(f"identical over {n:,}; lengths differ ({len(m_kept):,} vs {len(b_kept):,})") else: print(f"FIRST DIVERGENCE at aligned instruction {first:,}:") for k in range(max(0, first - 4), min(n, first + 3)): print(f" {k:8} MAME {fmt(mame[m_kept[k]][0])} board {fmt(mine[b_kept[k]][0])}") print(f"cycles: {exact:,} of {checked:,} segments exact (board clocks - 4 x MAME cycles " f"= 2 x slow cycles + 4 x held or stalled periods); {dma_segments:,} segments " f"with DMA on either side (trap 4, not compared)") # fmt: skip for k, pc, residue in explained_artifacts: print(f" segment {k:,} at {pc}: residue {residue}, {KNOWN_DETECTOR_ARTIFACTS[int(pc, 16)]}") if worst: print(" first inexact segments (aligned index, PC, residue in MARIA clocks):", worst) same = mame_inptctrl == my_inptctrl print(f"INPTCTRL writes while unlocked: MAME {' '.join(f'{v:02X}' for v in mame_inptctrl[:40])}") print(f" board {' '.join(f'{v:02X}' for v in my_inptctrl[:40])}" f" -> {'identical' if same else 'DIFFERENT'}") # fmt: skip print(f"board: {system.board.slow_cycles:,} slow cycles; wall {time.monotonic() - began:.1f} s") compared = checked - dma_segments ok = (first is None and len(m_kept) == len(b_kept) and exact + len(explained_artifacts) == compared and same) # fmt: skip print("PASS" if ok else "FAIL") return 0 if ok else 1 if __name__ == "__main__": sys.exit(main())