#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """Run Nick Mikstas's schematic-derived POKEY (VHDL) under GHDL and ask it questions. The model (reference/src/atari_pokey, pinned, no licence stated) is a CLOSED BOX: fetched, built and run locally, never opened, searched or quoted (docs/restart.md rules 1 and 5). Its author says he wrote it from ijor's reconstruction of the POKEY die. This script globs its *.vhd names for GHDL, links it to ``validation/pokey_tb.vhd`` (a testbench of this repository that only drives and prints pins) and runs small experiments whose answers are known from real hardware. It is the proof of the recipe for the core's judge (docs/validation.md, "The judge"), not a test of any core: there is no core yet. python -I scripts/run_vhdl.py --oss /path/to/oss-cad-suite # build, run all python -I scripts/run_vhdl.py --oss DIR timer init clocks python -I scripts/run_vhdl.py --oss DIR speed --cycles 200000 OSS_CAD_SUITE=DIR python -I scripts/run_vhdl.py GHDL comes from the YosysHQ oss-cad-suite bundle (pinned as a ``tool`` in scripts/pinned_files.json; any unpacked copy will do, it is only read). Experiments (each prints what the model does beside what hardware does): - ``timer``: channel 1 on the 1.79 MHz clock, AUDF1 = 0, 1, 5: the cycle after a STIMER write at which IRQST bit 0 first reads 0, and the output's half period. Hardware: 8 + AUDF1 and AUDF1 + 4 (Altirra manual 5.3 and Figure 8). - ``init``: RANDOM after initialisation mode is released. Hardware: $1F four cycles after the write in 9-bit mode (Altirra manual 5.5); 114 cycles after, $95 in 9-bit mode and $08 in 17-bit mode (Acid800 pokey_noise.s). - ``clocks``: timer 1 with AUDF1 = 0 on the 64 kHz and the 15 kHz clock: the cycle after the write releasing initialisation mode at which IRQST bit 0 first reads 0. Hardware: 24 and 83 (Altirra manual 5.2). - ``speed``: model cycles per second on this machine. The stimulus language is described at the top of validation/pokey_tb.vhd. A model signal that is undefined prints as -1: the model has no power-on reset, so every experiment first writes every register. """ from __future__ import annotations import argparse import os import subprocess import sys import time from pathlib import Path ROOT = Path(__file__).resolve().parents[1] MODEL = ROOT / "reference" / "src" / "atari_pokey" / "HDL" / "VHDL" / "POKEY_top" / "source" BENCH = ROOT / "validation" / "pokey_tb.vhd" WORK = ROOT / "reference" / "build" / "mikstas-ghdl" AUDF1, AUDC1, AUDCTL, STIMER, SKRES, POTGO, SEROUT, IRQEN, SKCTL = 0, 1, 8, 9, 10, 11, 13, 14, 15 RANDOM, IRQST = 10, 14 def environment(oss: Path | None) -> dict[str, str]: env = dict(os.environ) suite = oss or (Path(env["OSS_CAD_SUITE"]) if env.get("OSS_CAD_SUITE") else None) if suite: env["PATH"] = f"{suite / 'bin'}:{env['PATH']}" return env def build(env: dict[str, str]) -> Path: executable = WORK / "pokey_tb" if executable.exists() and executable.stat().st_mtime > BENCH.stat().st_mtime: return executable if not MODEL.is_dir(): raise SystemExit(f"{MODEL} is missing: run scripts/fetch_references.py") WORK.mkdir(parents=True, exist_ok=True) flags = ["--std=08", f"--workdir={WORK}"] sources = sorted(str(p) for p in MODEL.glob("*.vhd")) for step in ( ["ghdl", "-i", *flags, *sources], ["nice", "-n", "19", "ghdl", "-m", *flags, "pokey_top"], ["nice", "-n", "19", "ghdl", "-a", *flags, str(BENCH)], ["nice", "-n", "19", "ghdl", "-e", *flags, "pokey_tb"], ): subprocess.run(step, cwd=WORK, env=env, check=True, capture_output=True) return executable def run(executable: Path, commands: list[str], name: str) -> list[tuple]: """One row per cycle: (cycle, kind, address, data, audio, irq, sod, oclk, bclko, dump, k).""" stimulus = WORK / f"{name}.stim" stimulus.write_text("\n".join(commands) + "\n", encoding="ascii") out = subprocess.run( ["nice", "-n", "19", str(executable), f"-gSTIM={stimulus}"], cwd=WORK, check=True, capture_output=True, text=True, ).stdout # fmt: skip rows = [] for line in out.splitlines(): parts = line.split() if len(parts) == 11: rows.append((int(parts[0]), parts[1], *(int(x) for x in parts[2:]))) return rows def preamble(audctl: int, audf1: int = 0, audc1: int = 0, hold: int = 300) -> list[str]: """Every register written, initialisation mode held for ``hold`` cycles.""" commands = [f"W {SKCTL} 0"] for register in range(8): commands.append(f"W {register} 0") commands += [ f"W {AUDF1} {audf1}", f"W {AUDC1} {audc1}", f"W {AUDCTL} {audctl}", f"W {SEROUT} 0", f"W {IRQEN} 0", f"W {POTGO} 0", f"N {hold}", ] # fmt: skip return commands def cycle_of(rows: list[tuple], kind: str, address: int, data: int | None = None) -> int: """The cycle of the LAST such access.""" hits = [r[0] for r in rows if r[1] == kind and r[2] == address and data in (None, r[3])] return hits[-1] def timer(executable: Path) -> list[str]: lines = [] for period in (0, 1, 5): commands = [ *preamble(0x40, 200, 0xAF), f"W {SKCTL} 3", f"W {SKRES} 0", "N 8", f"W {STIMER} 0", f"W {IRQEN} 0", f"W {IRQEN} 1", f"W {AUDF1} {period}", f"W {STIMER} 0", *[f"R {IRQST}"] * 24, "N 60", ] # fmt: skip rows = run(executable, commands, f"timer{period}") start = cycle_of(rows, "W", STIMER) first = next(r[0] - start for r in rows if r[0] > start and r[1] == "R" and not r[3] & 1) pin = next(r[0] - start for r in rows if r[0] > start and r[5] == 1) edges = [r[0] for a, r in zip(rows, rows[1:]) if r[0] > start + 30 and a[4] != r[4]] half = sorted({b - a for a, b in zip(edges, edges[1:])}) lines.append( f"timer: AUDF1={period}: IRQST bit 0 first reads 0 at +{first}" f" (hardware +{8 + period}); /IRQ pin asserted from the end of +{pin};" f" output half period {half} (hardware {period + 4})" ) return lines def init(executable: Path) -> list[str]: lines = [] for name, audctl, expected in (("9-bit", 0x80, 0x95), ("17-bit", 0x00, 0x08)): rows = run( executable, [*preamble(audctl), f"W {SKCTL} 3", *[f"R {RANDOM}"] * 120], f"init{name}" ) start = cycle_of(rows, "W", SKCTL, 3) seen = {r[0] - start: r[3] for r in rows if r[1] == "R"} first = " ".join(f"{seen[d]:02X}" for d in range(1, 13)) lines.append(f"init: {name}: RANDOM at +1..+12: {first}") if name == "9-bit": lines.append(f"init: 9-bit: RANDOM at +4 = ${seen[4]:02X} (hardware $1F)") lines.append(f"init: {name}: RANDOM at +114 = ${seen[114]:02X} (hardware ${expected:02X})") return lines def clocks(executable: Path) -> list[str]: lines = [] for name, audctl, expected in (("64 kHz", 0x00, 24), ("15 kHz", 0x01, 83)): commands = [ *preamble(audctl), f"W {STIMER} 0", f"W {IRQEN} 1", "N 20", f"W {SKCTL} 3", *[f"R {IRQST}"] * 100, ] # fmt: skip rows = run(executable, commands, f"clocks{audctl}") start = cycle_of(rows, "W", SKCTL, 3) first = next( (r[0] - start for r in rows if r[0] > start and r[1] == "R" and not r[3] & 1), None ) lines.append( f"clocks: {name}, AUDF1=0: IRQST bit 0 first reads 0 at +{first}" f" after the SKCTL write (hardware +{expected})" ) return lines def speed(executable: Path, cycles: int) -> list[str]: commands = [*preamble(0x40, 37, 0xAF, hold=8), f"W {SKCTL} 3", f"N {cycles}"] began = time.monotonic() rows = run(executable, commands, "speed") wall = time.monotonic() - began return [f"speed: {len(rows):,} cycles in {wall:.1f} s = {len(rows) / wall:,.0f} cycles/s"] def main() -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument( "experiments", nargs="*", help="timer, init, clocks, speed (default: first three)" ) parser.add_argument("--oss", type=Path, help="an unpacked oss-cad-suite (read only)") parser.add_argument("--cycles", type=int, default=100_000, help="for speed") args = parser.parse_args() executable = build(environment(args.oss)) table = {"timer": timer, "init": init, "clocks": clocks} for name in args.experiments or list(table): if name == "speed": report = speed(executable, args.cycles) elif name in table: report = table[name](executable) else: parser.error(f"unknown experiment {name}") print("\n".join(report)) return 0 if __name__ == "__main__": sys.exit(main())