# SPDX-License-Identifier: MIT """Seeded and directed register streams, run on the core and on the closed box. A stream is a list of testbench commands (scripts/referee.py). ``run_core`` plays it on ``POKEY`` with the same convention as the testbench: one command per cycle, the access first, then the tick (B0.1); it returns rows shaped like the closed box's (cycle, read value or None, levels after the tick, irq). python -I scripts/streams.py rung2 --streams 200 --cycles 50000 python -I scripts/streams.py rung2 --seed 7 --cycles 2000 --show The judge for each rung is in docs/validation.md; the alignment between the core and the closed box is fixed per path and written in docs/validation.md, "Closed-box differences" (it is never fitted per stream). """ from __future__ import annotations import argparse import os import random import sys import time from pathlib import Path ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, os.environ.get("POKEY_SRC") or str(ROOT / "src")) # seeded_faults.py sets it sys.path.insert(0, str(ROOT / "scripts")) from pokey_python import POKEY # noqa: E402 from validation_constants import ( # noqa: E402 BOX_CLOCK_LAG_15, BOX_CLOCK_LAG_64, RUNG2_FIRE_OFFSET, RUNG3_LEVEL_OFFSET, RUNG4_IRQ_OFFSET, ) AUDC_SQUARE = (0xA1, 0xA2, 0xA4, 0xA8) # pure tone, volumes 1, 2, 4, 8: the pin's sum decodes def _predecessor(state: int, steps: int, bits: int, step) -> int: """The counter state that reaches ``state`` after ``steps`` shifts.""" for _ in range(steps): state = next(s for s in range(1 << bits) if step(s) == state) return state def _step15(c: int) -> int: bit = 1 if c == 0b1001001 else (((c >> 6) ^ (c >> 5)) & 1) ^ 1 return ((c << 1) & 0x7F) | bit def _step64(c: int) -> int: bit = 1 if c == 0b00010 else ((c >> 4) ^ (c >> 2)) & 1 return ((c << 1) & 0x1F) | bit class BoxAligned(POKEY): """The core with the closed box's derived-clock phase (differences D1, D2). The box's first 64 kHz pulse after init mode comes 1 cycle later than the core's (B2.1b, from Acid800 pokey_inittiming.s); its 15 kHz pulse agrees (U1 rows 2 and 3; validation_constants). The referee holds the core's counters that many extra ticks so that streams can be compared; the shipped core keeps the hardware test's timing. """ hold15 = 0 hold64 = 0 box_clear = 0 # D12 (rung 6): the box reads Break on /KR2 at $10 and Shift at $30 SHIFT_CODE = 0x30 BREAK_CODE = 0x10 #: D9, D10 (rung 4): the box's acknowledge and its bit-3 pin term come one tick late box_irqen = True def tick(self) -> None: was_init = self.init_mode c15, c64 = self.c15, self.c64 reg, val, irqen, old = self.w_reg, self.w_val, self.irqen, self.latched clear, self.box_clear = self.box_clear, 0 clocks_held = self.clocks_init # B2.1b: the core's own one-tick lag, not counted below super().tick() if self.box_irqen: if clear: # D9: the bits an IRQEN write cleared were held one more tick self.latched &= ~clear if reg == 14: fired = self.fired new = ((fired[0] and 1) | (fired[1] and 2) | (fired[3] and 4)) & irqen cleared = (old | new) & ~val & 0xF7 self.latched |= cleared self.box_clear = cleared self.irq = bool(self.latched) or bool(irqen & 0x08) # D10: IRQEN as before this tick if self.hold15 and not clocks_held: # the 15 kHz counter still as in init mode (B2.1a) self.c15 = (c15 << 1) & 0x7F self.hold15 -= 1 if self.hold64 and not clocks_held: self.c64 = ((c64 << 1) & 0x1F) | 1 self.hold64 -= 1 if was_init and not self.init_mode: # released at the end of this tick self.hold15, self.hold64 = BOX_CLOCK_LAG_15, BOX_CLOCK_LAG_64 def run_core(commands: list[tuple], chip: POKEY | None = None) -> tuple[POKEY, list[tuple]]: """Rows: (cycle, value read or None, fired mask after the tick, levels, irq).""" chip = chip or BoxAligned() rows = [] cycle = 0 for command in commands: op = command[0] if op in ("K", "P", "S"): apply_pins(chip, op, command[1]) continue repeat = command[1] if op == "N" else 1 for _ in range(repeat): value = None if op == "W": chip.write(command[1], command[2]) elif op == "R": value = chip.read(command[1]) chip.tick() fired = chip.fired mask = (fired[0] and 1) | (fired[1] and 2) | (fired[2] and 4) | (fired[3] and 8) rows.append((cycle, value, mask, chip.levels(), chip.irq, chip.scan_code, chip.shift_latch, chip.key_held)) cycle += 1 return chip, rows def apply_pins(chip: POKEY, op: str, value: int) -> None: if op == "S": chip.sid = 1 if value else 0 elif op == "P": mask = value chip.pot_level = lambda n, mask=mask: bool(mask >> n & 1) elif op == "K": # testbench: v = KR2,KR1 pin levels (idle 3); the core's callable: bit set = asserted asserted = ~value & 3 chip.key_response = lambda _code, asserted=asserted: asserted def rung2_stream( seed: int, cycles: int, audctl_changes: bool = False, init_toggles: bool = True ) -> list[tuple]: """Random AUDF/AUDCTL (clock and join bits) writes, init-mode toggles, RANDOM read every cycle. STIMER only in the preamble, so every change of an output bit is a fire (the output stage is rung 3). High-pass bits stay off. """ rnd = random.Random(seed) audctl = rnd.choice([0x00, 0x01, 0x40, 0x20, 0x60, 0x50, 0x28, 0x78, 0x59]) | rnd.choice([0, 0x80]) commands: list[tuple] = [("W", 15, 0)] for ch in range(4): commands += [("W", 2 * ch, rnd.randrange(256)), ("W", 2 * ch + 1, AUDC_SQUARE[ch])] commands += [("W", 8, audctl), ("W", 13, 0), ("W", 14, 0), ("W", 10, 0), ("N", 30)] commands += [("W", 15, 3), ("W", 9, 0), ("R", 10)] used = sum(c[1] if c[0] == "N" else 1 for c in commands) while used < cycles: gap = rnd.choice((1, 2, 3, 5, 8, 13, 40, 100, 300)) commands += [("R", 10)] * gap used += gap kind = rnd.random() if kind < 0.75: ch = rnd.randrange(4) value = rnd.choice((rnd.randrange(8), rnd.randrange(32), rnd.randrange(256))) commands.append(("W", 2 * ch, value)) elif kind < 0.93 and not audctl_changes: ch = rnd.randrange(4) commands.append(("W", 2 * ch, rnd.randrange(256))) elif kind < 0.93: bits = rnd.choice((0x01, 0x08, 0x10, 0x20, 0x40)) # bit 7 fixed: difference D3 audctl ^= bits commands.append(("W", 8, audctl & ~0x06)) elif not init_toggles: commands.append(("W", 2 * rnd.randrange(4), rnd.randrange(16))) else: hold = rnd.choice((9, 20, 120)) # holds under 7 cycles: difference D5 commands += [("W", 15, 0), *[("R", 10)] * hold, ("W", 15, 3)] used += hold + 1 used += 1 return commands def box_commands(commands: list[tuple]) -> list[tuple]: """The stimulus as the closed box gets it: each STIMER moved one cycle later. validation_constants.BOX_STIMER_DELAY (the fixed alignment for U1 row 1). The cycle after a STIMER must be a read or an idle cycle. """ out: list[tuple] = [] pending = None for command in commands: if pending is not None: if command[0] == "R": out += [command, pending] pending = None continue if command[0] == "N": out += [("N", 1), pending] pending = None if command[1] > 1: out.append(("N", command[1] - 1)) continue raise ValueError("a STIMER must be followed by a read or an idle cycle") if command[0] == "W" and command[1] == 9: pending = command else: out.append(command) if pending is not None: out += [("N", 1), pending] return out def rung3_stream(seed: int, cycles: int, stimers: bool = False) -> list[tuple]: """Rung 2's streams with AUDC (distortion, volume-only) and the high-pass bits randomised. Volumes stay 1, 2, 4, 8 so that the audio pin decodes into four output bits. AUDCTL is fixed per stream (D3, D4) and init mode is not re-entered (D5). With ``stimers`` STIMER appears in the body too (difference D7). """ rnd = random.Random(seed) audctl = rnd.choice([0x00, 0x01, 0x40, 0x20, 0x60, 0x50, 0x28, 0x78, 0x59]) audctl |= rnd.choice([0, 0x80]) | rnd.choice([0, 0x02, 0x04, 0x06]) def audc(ch: int) -> int: top = rnd.choice((0x00, 0x20, 0x40, 0x60, 0x80, 0xA0, 0xC0, 0xE0, 0x10)) return top | (1 << ch) commands: list[tuple] = [("W", 15, 0)] for ch in range(4): commands += [("W", 2 * ch, rnd.randrange(256)), ("W", 2 * ch + 1, AUDC_SQUARE[ch])] # the high-pass bits stay off until STIMER has defined the flip-flops: the box has no # power-on state, and a high-pass flip-flop enabled from the start copies an undefined one commands += [("W", 8, audctl & ~0x06), ("W", 13, 0), ("W", 14, 0), ("W", 10, 0), ("N", 30)] # ungated in init mode (D6); the random AUDC values only from T+4 of the STIMER, so # that none coincides with its gate load in T+2 (D8) commands += [("W", 15, 3), ("W", 9, 0), ("N", 3)] for ch in range(4): commands += [("W", 2 * ch + 1, audc(ch))] commands += [("W", 8, audctl)] used = sum(c[1] if c[0] == "N" else 1 for c in commands) while used < cycles: gap = rnd.choice((1, 2, 3, 5, 8, 13, 40, 100, 300)) commands += [("N", gap)] used += gap + 1 kind = rnd.random() ch = rnd.randrange(4) if kind < 0.55: value = rnd.choice((rnd.randrange(8), rnd.randrange(32), rnd.randrange(256))) commands.append(("W", 2 * ch, value)) elif kind < 0.9 or not stimers: commands.append(("W", 2 * ch + 1, audc(ch))) else: commands += [("W", 9, 0), ("N", 1)] used += 1 return commands def rung4_stream(seed: int, cycles: int) -> list[tuple]: """Rung 2's streams (no init re-entry, AUDCTL fixed) with random IRQEN writes. IRQEN takes random values of bits 0-3 (timers 1, 2, 4 and the idle serial output); every write of 0 to a bit acknowledges it (B1.4). STIMER only in the preamble (D1 is the box's STIMER, aligned by box_commands). """ rnd = random.Random(seed) audctl = rnd.choice([0x40, 0x60, 0x50, 0x28, 0x78, 0x00, 0x01, 0x59]) commands: list[tuple] = [("W", 15, 0)] for ch in range(4): commands += [("W", 2 * ch, rnd.randrange(64)), ("W", 2 * ch + 1, AUDC_SQUARE[ch])] commands += [("W", 8, audctl), ("W", 13, 0), ("W", 14, 0), ("W", 10, 0), ("N", 30)] commands += [("W", 15, 3), ("W", 9, 0), ("N", 4)] used = sum(c[1] if c[0] == "N" else 1 for c in commands) while used < cycles: gap = rnd.choice((1, 2, 3, 5, 8, 13, 40, 100)) commands += [("R", 14)] * gap used += gap + 1 if rnd.random() < 0.6: commands.append(("W", 14, rnd.choice((rnd.randrange(16), rnd.randrange(8), 0x07, 0)))) else: commands.append(("W", 2 * rnd.randrange(4), rnd.randrange(64))) return commands def compare_irq(commands: list[tuple], box_rows: list, offset: int, settle: int = 8) -> dict: """The /IRQ line every cycle and IRQST bits 0-3 at every read: box row t against core row t - offset.""" _, core_rows = run_core(commands) start = release_row(commands) + settle result = {"cycles": 0, "irq_diff": 0, "irqst_reads": 0, "irqst_diff": 0} first = None for t in range(start + offset, min(len(box_rows), len(core_rows) + offset)): box, core = box_rows[t], core_rows[t - offset] if box.irq < 0: continue result["cycles"] += 1 if (box.irq == 1) != core[4]: result["irq_diff"] += 1 first = first or ("irq", t) # a read in row t sees the state after tick t - 1 on both sides (offset 0 for reads) read = core_rows[t][1] if t < len(core_rows) else None if box.kind == "R" and box.address == 14 and read is not None: result["irqst_reads"] += 1 if (box.data ^ read) & 0x0F: result["irqst_diff"] += 1 first = first or ("irqst", t) result["first_diff"] = first return result def rung6_stream(seed: int, cycles: int) -> list[tuple]: """Random /KR1 and /KR2 levels held for random spans, debounce on or off per stream. The pins are static levels on both sides (the key answers at every code while held). IRQEN enables the keyboard and Break interrupts and is rewritten (acknowledging them) at random; SKRES at random. Reads rotate over IRQST, SKSTAT and KBCODE. """ rnd = random.Random(seed) skctl = rnd.choice((0x03, 0x02)) commands: list[tuple] = [("W", 15, 0)] for ch in range(4): commands += [("W", 2 * ch, 0), ("W", 2 * ch + 1, 0xA0)] # IRQEN 0 first: it defines the box's interrupt latches (no power-on state) commands += [("W", 8, 0), ("W", 13, 0), ("W", 14, 0), ("W", 14, 0xC0), ("W", 10, 0), ("K", 3)] commands += [("N", 30)] commands += [("W", 15, skctl), ("W", 9, 0), ("N", 4)] used = sum(c[1] if c[0] == "N" else (0 if c[0] in "KPS" else 1) for c in commands) reads = (14, 15, 9) while used < cycles: span = rnd.choice((114, 300, 1000, 5000, 8000, 15000)) commands += [("R", reads[i % 3]) for i in range(span)] used += span kind = rnd.random() if kind < 0.6: commands.append(("K", rnd.choice((3, 2, 1, 0)))) elif kind < 0.85: commands += [("W", 14, 0x00), ("W", 14, 0xC0)] used += 2 else: commands.append(("W", 10, 0)) used += 1 return commands def compare_keyboard(commands: list[tuple], box_rows: list, settle: int = 8) -> dict: """K0-K5 every cycle (box row t+1 = core after tick t), /IRQ, and every IRQST/SKSTAT/KBCODE read.""" _, core_rows = run_core(commands) start = release_row(commands) + settle result = {"cycles": 0, "k_diff": 0, "irq_diff": 0, "reads": 0, "read_diff": 0, "kbcode_undefined": 0} first = None for t in range(start + 1, min(len(box_rows), len(core_rows) + 1)): box, core = box_rows[t], core_rows[t - 1] result["cycles"] += 1 if box.k != core[5]: # D11: the box's K pins ripple through 2-bit groups for a row or two after a carry new = core[5] ripple = set() for old in (core_rows[t - 2][5], core_rows[t - 3][5]): ripple |= {(new & 3) | (old & ~3 & 0x3F), (new & 0xF) | (old & ~0xF & 0x3F)} if box.k in ripple: result["k_ripple"] = result.get("k_ripple", 0) + 1 else: result["k_diff"] += 1 first = first or ("k", t) if box.irq >= 0 and (box.irq == 1) != core[4]: result["irq_diff"] += 1 first = first or ("irq", t) read = core_rows[t][1] if t < len(core_rows) else None if box.kind == "R" and read is not None: if box.address == 9 or box.data < 0: # D14: the box's KBCODE is not usable result["kbcode_undefined"] += 1 continue result["reads"] += 1 diff = (box.data ^ read) & (0xC0 if box.address == 14 else 0x40) if box.address == 15: # D13: the box's SKSTAT bits 3 (Shift) and 2 (held) show this cycle's tick diff |= (box.data >> 3 & 1) ^ (not core_rows[t][6]) diff |= (box.data >> 2 & 1) ^ (not core_rows[t][7]) if diff: result["read_diff"] += 1 first = first or (f"read {box.address}", t) result["first_diff"] = first return result def release_row(commands: list[tuple]) -> int: """The cycle of the first STIMER (the preamble's, written right after init mode is left).""" index = next(i for i, c in enumerate(commands) if c == ("W", 9, 0)) return sum(c[1] if c[0] == "N" else (0 if c[0] in "KPS" else 1) for c in commands[:index]) def compare_levels( commands: list[tuple], box_rows: list, chip: POKEY | None = None, settle: int = 8 ) -> dict: """Each channel's output bit every cycle: box row t against the core after tick t - offset. The comparison starts ``settle`` cycles after the preamble's STIMER has set the four flip-flops (B3.7): before it, the two sides' power-on states differ (the box has none; B1.8). """ from referee import channel_bits _, core_rows = run_core(commands, chip) offset = RUNG3_LEVEL_OFFSET diff = 0 first = None compared = 0 start = release_row(commands) + offset + settle undefined = 0 for t in range(start, min(len(box_rows), len(core_rows) + offset)): if box_rows[t].audio < 0: # the box's pin is undefined (no power-on state) undefined += 1 continue levels = core_rows[t - offset][3] core_bits = sum(1 << k for k in range(4) if levels[k]) box_bits = channel_bits(box_rows[t].audio) compared += 1 if core_bits != box_bits: diff += 1 if first is None: first = (t, core_bits, box_bits) return {"cycles": compared, "level_diff": diff, "undefined": undefined, "first_diff": first} def toggles(bits: list[int], channel: int) -> list[int]: out = [] for cycle in range(1, len(bits)): if (bits[cycle] ^ bits[cycle - 1]) >> channel & 1: out.append(cycle) return out def compare_rung2(commands: list[tuple], box_rows: list, offset: int) -> dict: """RANDOM every cycle (offset 0) and each channel's fires (box toggle = core fire + offset).""" from referee import channel_bits _, core_rows = run_core(commands) result = {"cycles": len(core_rows), "random_diff": 0, "random_reads": 0, "fire_diff": 0, "fires": 0} first_diff = None for core, box in zip(core_rows, box_rows): if core[1] is not None and box.kind == "R": result["random_reads"] += 1 if core[1] != box.data: result["random_diff"] += 1 first_diff = first_diff if first_diff is not None else ("random", core[0]) bits = [channel_bits(r.audio) for r in box_rows] start = next(i for i, c in enumerate(commands) if c == ("W", 9, 0)) start = sum(c[1] if c[0] == "N" else (0 if c[0] in "KPS" else 1) for c in commands[:start]) + 12 for ch in range(4): box_t = [t for t in toggles(bits, ch) if t > start + offset] core_t = [r[0] + offset for r in core_rows if r[2] >> ch & 1 and r[0] > start] core_t = [t for t in core_t if t < len(box_rows)] result["fires"] += len(core_t) if box_t != core_t: a, b = set(box_t), set(core_t) result["fire_diff"] += len(a ^ b) where = min(a ^ b) if first_diff is None or where < first_diff[1]: first_diff = (f"fire ch{ch + 1}", where) result["first_diff"] = first_diff return result def main() -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("rung", choices=["rung2", "rung3", "rung4", "rung6"]) parser.add_argument("--streams", type=int, default=1) parser.add_argument("--seed", type=int, default=1) parser.add_argument("--cycles", type=int, default=20000) parser.add_argument("--offset", type=int, default=None, help="box toggle = core fire + offset") parser.add_argument( "--audctl-changes", action="store_true", help="also switch AUDCTL clock/join bits while running (difference D4)", ) # fmt: skip parser.add_argument("--no-init-toggles", action="store_true", help="no init mode after the start") parser.add_argument( "--stimers", action="store_true", help="rung 3: STIMER in the body too (difference D7)" ) parser.add_argument( "--raw-irqen", action="store_true", help="rung 4: do not align the box's late acknowledge and bit-3 pin (differences D9, D10)", ) # fmt: skip args = parser.parse_args() BoxAligned.box_irqen = not args.raw_irqen import referee from validation_constants import RUNG2_FIRE_OFFSET offset = RUNG2_FIRE_OFFSET if args.offset is None else args.offset totals: dict = {} bad = 0 began = time.monotonic() for seed in range(args.seed, args.seed + args.streams): if args.rung == "rung3": commands = rung3_stream(seed, args.cycles, args.stimers) box = referee.run(box_commands(commands), timeout=3600) result = compare_levels(commands, box) elif args.rung == "rung6": commands = rung6_stream(seed, args.cycles) box = referee.run(box_commands(commands), timeout=3600) result = compare_keyboard(commands, box) elif args.rung == "rung4": commands = rung4_stream(seed, args.cycles) box = referee.run(box_commands(commands), timeout=3600) result = compare_irq(commands, box, RUNG4_IRQ_OFFSET if args.offset is None else args.offset) else: commands = rung2_stream(seed, args.cycles, args.audctl_changes, not args.no_init_toggles) box = referee.run(box_commands(commands), timeout=3600) result = compare_rung2(commands, box, offset) for key, value in result.items(): if isinstance(value, int): totals[key] = totals.get(key, 0) + value diffs = ("random_diff", "fire_diff", "level_diff", "irq_diff", "irqst_diff", "k_diff", "read_diff") if any(result.get(k) for k in diffs): bad += 1 print(f"seed {seed}: {result}") totals["streams"] = args.streams totals["streams_with_differences"] = bad totals["wall_s"] = round(time.monotonic() - began, 1) print(totals) return 1 if bad else 0 if __name__ == "__main__": sys.exit(main())