#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """Write the lockstep scenarios of rungs 1 and 4. Every program here is hand-assembled from the bytes below, so nothing third-party is committed. Scenarios that name a fetched program by path, and the large random-memory ones, are written to the gitignored ``external/scenarios/``; the hand-assembled ones to ``conformance/scenarios/``. make_scenarios.py [--programs DORMANN_BUILT FUNCTIONAL_BIN] Rung 1 (``--programs``): Dormann's 65C02 extended test (the image built for the row), his NMOS functional test and Clark's decimal test, the first 300,000 boundaries of each on every row, every bus access recorded; and the workout below with no interrupts, on every row. Rung 4: the interrupt workout (CLI, SEI, PHP/PLP, BRK, WAI, one-cycle NOPs, taken branches with and without a page crossing, BRA, decimal ADC, IRQ and NMI handlers) under seeded random requests between steps and during bus accesses, RDY stalls of reads and of writes (``note_stall``), and resets, on every row; WAI and STP scenarios; one-cycle NOPs before a pending IRQ; and random memory run as a program with random requests and resets, on every row. """ from __future__ import annotations import argparse import json import random from pathlib import Path ROOT = Path(__file__).resolve().parents[1] COMMITTED = ROOT / "conformance" / "scenarios" EXTERNAL = ROOT / "external" / "scenarios" ROWS = ("w65c02s", "r65c02", "g65sc02", "lynx2cell") #: row -> the extended test's image (the reference's tests/programs.py, EXTENDED) EXTENDED = {"w65c02s": "wdc", "r65c02": "rockwell", "g65sc02": "sc", "lynx2cell": "rockwell"} def workout() -> list[dict]: """The interrupt workout's memory: main loop at $02F0, handlers, vectors.""" main = bytes.fromhex( "58" # 02F0 CLI "a9 00" # 02F1 LDA #$00 "18" # 02F3 CLC "90 10" # 02F4 BCC +$10 -> $0306 (taken, crosses into page 3) "ea ea ea ea ea ea ea ea ea ea ea ea ea ea ea ea" # 02F6..0305 (skipped) "e6 10" # 0306 INC $10 "78" # 0308 SEI "03" # 0309 NOP (one byte, one cycle: does not poll, U7) "58" # 030A CLI "08" # 030B PHP "78" # 030C SEI "28" # 030D PLP (restores I clear, one boundary late) "69 01" # 030E ADC #$01 "d0 02" # 0310 BNE +2 -> $0314 (taken, same page, unless A wrapped) "ea ea" # 0312 "f0 00" # 0314 BEQ +0 (not taken unless zero) "08" # 0316 PHP "58" # 0317 CLI "28" # 0318 PLP "00 ff" # 0319 BRK #$FF -> IRQ/BRK handler "cb" # 031B WAI on the W65C02S; a one-cycle NOP on the other rows "13" # 031C NOP (one cycle) "a5 10" # 031D LDA $10 "c9 08" # 031F CMP #$08 (every eighth pass takes the decimal tail) "b0 03" # 0321 BCS +3 -> $0326 "4c f0 02" # 0323 JMP $02F0 "f8" # 0326 SED "69 19" # 0327 ADC #$19 (decimal: the extra cycle) "d8" # 0329 CLD "64 10" # 032A STZ $10 "9d 00 06" # 032C STA $0600,X (an indexed store within a page) "7c 34 03" # 032F JMP ($0334,X) (X is 0 or 2 here) "f0 02" # 0332 BEQ +2 "f0 02 f0 02" # 0334 the jump table: $02F0, $02F0 "80 b6" # 0338 BRA -> $02F0 (never reached; the table jumps) ) irq = bytes.fromhex( "48" # 0400 PHA "da" # 0401 PHX "e6 20" # 0402 INC $20 "a5 20" # 0404 LDA $20 "29 07" # 0406 AND #$07 "d0 01" # 0408 BNE +1 "58" # 040A CLI (nested interrupts now and then) "fa" # 040B PLX "68" # 040C PLA "40" # 040D RTI ) nmi = bytes.fromhex( "e6 21" # 0500 INC $21 "6c 06 05" # 0502 JMP ($0506) "ea" # 0505 "08 05" # 0506 -> $0508 "40" # 0508 RTI ) vectors = bytes.fromhex("0005" "f002" "0004") # NMI $0500, RESET $02F0, IRQ $0400 return [ {"address": 0x02F0, "hex": main.hex()}, {"address": 0x0400, "hex": irq.hex()}, {"address": 0x0500, "hex": nmi.hex()}, {"address": 0xFFFA, "hex": vectors.hex()}, ] def random_events(rng: random.Random, steps: int, accesses_per_step: float = 3.5) -> tuple[list, list]: """Seeded random requests (between steps and inside accesses) and RDY stalls.""" span = int(steps * accesses_per_step) events: list[dict] = [] # IRQ is a level the programs never acknowledge, so it is raised rarely and # dropped often, and NMIs are rare: the main loop must run between handlers. for access in range(span): roll = rng.random() if roll < 0.004: events.append({"access": access, "action": "irq"}) elif roll < 0.020: events.append({"access": access, "action": "irq_clear"}) elif roll < 0.0215: events.append({"access": access, "action": "nmi"}) elif roll < 0.0218: events.append({"access": access, "action": "nmi_clear"}) elif roll < 0.0258: # Two changes in one cycle: the poll keeps the requests from # before the first (Frame.request), so a pulse is invisible. first, second = rng.choice((("irq", "irq_clear"), ("irq_clear", "irq"), ("nmi", "nmi_clear"))) events.append({"access": access, "action": first}) events.append({"access": access, "action": second}) for step in range(steps): roll = rng.random() if roll < 0.01: events.append({"step": step, "action": "irq"}) elif roll < 0.02: events.append({"step": step, "action": "irq_clear"}) elif roll < 0.024: events.append({"step": step, "action": "nmi"}) elif roll < 0.0245: events.append({"step": step, "action": "reset"}) stalls = [] for access in range(span): if rng.random() < 0.02: halted = rng.randint(1, 4) during = [ {"cycle": rng.randint(1, halted), "action": rng.choice(("irq", "irq_clear", "nmi"))} for _ in range(rng.randint(0, 2)) ] stalls.append({"access": access, "halted": halted, "during": during}) return events, stalls def fuzz(row: str, seed: int, steps: int) -> dict: """The workout under seeded random requests, stalls (reads and writes) and resets.""" events, stalls = random_events(random.Random(seed), steps) return {"row": row, "memory": workout(), "reset": True, "steps": steps, "events": events, "stalls": stalls} def wai_stp(row: str) -> dict: """WAI woken by IRQ with I clear and set, WAI with IRQ already low, WAI woken by NMI (requested inside a waiting cycle), STP, then reset; on rows without WAI and STP the same bytes are one-cycle NOPs.""" program = bytes.fromhex( "58" # 0200 CLI "cb" # 0201 WAI (IRQ at step 6 wakes it: the entry) "e8" # 0202 INX "78" # 0203 SEI "cb" # 0204 WAI (IRQ at step 22 wakes it: no vectoring, I set) "e8" # 0205 INX "cb" # 0206 WAI (IRQ still low: a plain three-cycle instruction) "e8" # 0207 INX "cb" # 0208 WAI (IRQ cleared at step 26; NMI inside an access wakes it) "e8" # 0209 INX "db" # 020A STP (until the reset at step 70) "e8" # 020B INX "4c 0b 02" # 020C JMP $020B ) irq = bytes.fromhex("e6 20 40") # 0400 INC $20; RTI nmi = bytes.fromhex("e6 21 40") # 0500 INC $21; RTI return { "row": row, "memory": [ {"address": 0x0200, "hex": program.hex()}, {"address": 0x0400, "hex": irq.hex()}, {"address": 0x0500, "hex": nmi.hex()}, {"address": 0xFFFA, "hex": "0005" "0002" "0004"}, ], "reset": True, "steps": 100, "events": [ {"step": 6, "action": "irq"}, {"step": 9, "action": "irq_clear"}, {"step": 22, "action": "irq"}, {"step": 26, "action": "irq_clear"}, {"access": 120, "action": "nmi"}, {"step": 70, "action": "reset"}, {"step": 72, "action": "irq"}, ], } def one_cycle_nops(row: str) -> dict: """A pending IRQ meets a block of one-cycle NOPs (U7: it is taken only after the block, the LT `cpu` test 8 shape), with requests inside the NOPs' only cycle.""" block = bytes.fromhex("03 0b 13 1b 23 2b 33 3b 43 4b 53 5b 63 6b 73 7b 83 8b 93 9b a3 ab b3 bb c3 d3 e3 eb f3 fb") program = bytes.fromhex("58") + block + bytes.fromhex("e8 4c 00 02") # CLI, NOPs, INX, JMP $0200 return { "row": row, "memory": [ {"address": 0x0200, "hex": program.hex()}, {"address": 0x0400, "hex": "e6 20 40".replace(" ", "")}, {"address": 0xFFFA, "hex": "0004" "0002" "0004"}, ], "reset": True, "steps": 400, "events": [ {"step": 3, "action": "irq"}, {"step": 4, "action": "irq_clear"}, {"access": 40, "action": "irq"}, {"access": 41, "action": "irq_clear"}, {"access": 90, "action": "nmi"}, {"step": 150, "action": "irq"}, {"step": 151, "action": "irq_clear"}, {"access": 300, "action": "irq"}, {"access": 302, "action": "irq_clear"}, ], } def random_memory(row: str, seed: int, steps: int) -> dict: """64 KB of seeded random bytes run as a program: the row's opcodes, decimal mode, BRK, WAI and STP, with random requests, stalls and resets (a reset every 500 steps brings a stopped or lost CPU back through the random reset vector). Each seed is one path, so there are many seeds of a few thousand steps.""" rng = random.Random(seed) memory = bytes(rng.randrange(256) for _ in range(0x10000)) events, stalls = random_events(rng, steps) events += [{"step": step, "action": "reset"} for step in range(500, steps, 500)] return { "row": row, "memory": [{"address": 0, "hex": memory.hex()}], "reset": True, "steps": steps, "events": events, "stalls": stalls, } def programs(built: Path, functional: Path) -> dict[str, dict]: decimal = built / "65C02_decimal_test.bin" scenarios = {} for row in ROWS: images = { "extended": built / f"65C02_extended_opcodes_test_{EXTENDED[row]}.bin", "functional": functional, "decimal": decimal, } for name, path in images.items(): scenarios[f"program-{name}-{row}"] = { "row": row, "memory": [{"address": 0, "file": str(path.resolve())}], "registers": {"pc": 0x0400}, "steps": 300_000, } return scenarios def main() -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("--programs", nargs=2, type=Path, metavar=("DORMANN_BUILT", "FUNCTIONAL_BIN")) args = parser.parse_args() COMMITTED.mkdir(parents=True, exist_ok=True) EXTERNAL.mkdir(parents=True, exist_ok=True) committed: dict[str, dict] = {} external: dict[str, dict] = {} for index, row in enumerate(ROWS): # An NMI every 60 steps wakes the W65C02S's WAI; the other rows run it as a NOP. nmis = [{"step": step, "action": "nmi"} for step in range(60, 3_000, 60)] committed[f"tour-{row}"] = {"row": row, "memory": workout(), "reset": True, "steps": 3_000, "events": nmis} for seed in (1, 2): committed[f"interrupts-{row}-{seed}"] = fuzz(row, 10 * index + seed, 20_000) committed[f"wai-stp-{row}"] = wai_stp(row) committed[f"one-cycle-nops-{row}"] = one_cycle_nops(row) for seed in range(16): external[f"random-memory-{row}-{seed:02d}"] = random_memory(row, 1000 * (index + 1) + seed, 4_000) if args.programs: external.update(programs(*args.programs)) for name, scenario in committed.items(): (COMMITTED / f"{name}.json").write_text(json.dumps(scenario, separators=(",", ":")) + "\n") for name, scenario in external.items(): (EXTERNAL / f"{name}.json").write_text(json.dumps(scenario, separators=(",", ":")) + "\n") print(f"wrote {len(committed)} scenarios to {COMMITTED} and {len(external)} to {EXTERNAL}") return 0 if __name__ == "__main__": raise SystemExit(main())