#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """The reference side of the lockstep: run scenarios on sh2-python, write their traces. reference_trace.py SH2_PYTHON OUT_DIR SCENARIO.json [...] Each scenario (``scripts/make_scenarios.py`` writes them) is a board, the chip's options and a list of operations; ``src/bin/sh2-trace.rs`` runs the same file on this crate and must write the same bytes. The trace has one line per event, in the order they happen: every bus callback (``r``/``w``: address, width, kind, the state it starts on, the BSC's states for its area, the board's wait, the value), every ``observe`` call, every pin-out callable, then after each step its states, clock and registers (and, at slice ends, the whole ``capture_state()``), the scheduler's ``pipeline_log`` events when the scenario turns the log on, and each operation's result. With a scenario's ``slice`` > 0 the lines are folded into one CRC-32 per slice of that many steps (the family's slice lines: methodology.md, "Gates"); 0 writes every line. Stdlib only; run it on the reference's interpreter (PyPy, ``PYPY_GC_NURSERY=1M``). """ from __future__ import annotations import json import sys import zlib from pathlib import Path def load_reference(root: Path): sys.path.insert(0, str(root / "src")) import sh2_python # noqa: F401 from sh2_python import SH7604 return SH7604 def xorshift_fill(size: int, seed: int) -> bytearray: """rung 1's fill (validation/rung1/corpus.py): xorshift32 (13, 17, 5), big-endian.""" x = seed or 0x12345678 out = bytearray(size) for i in range(0, size, 4): x ^= (x << 13) & 0xFFFFFFFF x ^= x >> 17 x ^= (x << 5) & 0xFFFFFFFF out[i : i + 4] = x.to_bytes(4, "big")[: min(4, size - i)] return out class Out: """The trace: lines straight out, or folded into one CRC-32 per slice.""" def __init__(self, stream, slice_steps: int) -> None: self.stream = stream self.slice = slice_steps self.crc = 0 self.lines = 0 self.number = 0 def line(self, text: str) -> None: if self.slice: self.crc = zlib.crc32(text.encode() + b"\n", self.crc) self.lines += 1 else: self.stream.write(text + "\n") def close_slice(self, chip) -> None: if self.slice: self.stream.write( f"slice {self.number} {self.lines} {self.crc:08x} {chip.clock} {chip.pc:x}\n" ) self.number += 1 self.crc = 0 self.lines = 0 class Region: __slots__ = ("base", "data", "size", "span") def __init__(self, spec: dict) -> None: self.base = spec["base"] self.size = spec["size"] self.span = spec.get("span", self.size) self.data = bytearray(self.size) if "xorshift" in spec: self.data[:] = xorshift_fill(self.size, spec["xorshift"]) for offset, text in spec.get("chunks", []): blob = bytes.fromhex(text) self.data[offset : offset + len(blob)] = blob class Board: """The scenario's board: regions, waits, and the trace of every callback.""" def __init__(self, spec: dict, out: Out) -> None: self.regions = [Region(r) for r in spec.get("regions", [])] self.area_waits = spec.get("area_waits", [0, 0, 0, 0]) self.address_waits = {int(a): w for a, w in spec.get("address_waits", {}).items()} self.pattern = spec.get("pattern", False) self.write_wait = spec.get("write_wait", 0) self.out = out self.chip = None def locate(self, address: int): for region in self.regions: if region.base <= address < region.base + region.span: return region, (address - region.base) % region.size return None, 0 def get(self, address: int, width: int) -> int: value = 0 for i in range(width >> 3): region, offset = self.locate(address + i) byte = region.data[offset] if region is not None else 0 value = (value << 8) | byte if self.pattern and self.locate(address)[0] is None: return (address * 0x01010101) & ((1 << width) - 1) return value def put(self, address: int, width: int, value: int) -> None: count = width >> 3 for i in range(count): region, offset = self.locate(address + i) if region is not None: region.data[offset] = (value >> (8 * (count - 1 - i))) & 0xFF def waits(self, address: int) -> int: return self.area_waits[(address >> 25) & 3] + self.address_waits.get(address, 0) def read(self, address: int, width: int, kind: int) -> int: chip = self.chip clock = chip.clock chip.wait += self.waits(address) value = self.get(address, width) cs = chip.bsc.cycle_states[(address >> 25) & 3] self.out.line(f"r {address:08x} {width} {kind} {clock} {cs} {chip.wait} {value:x}") return value def write(self, address: int, width: int, value: int, kind: int) -> None: chip = self.chip clock = chip.clock chip.wait += self.waits(address) + self.write_wait self.put(address, width, value) cs = chip.bsc.cycle_states[(address >> 25) & 3] self.out.line(f"w {address:08x} {width} {kind} {clock} {cs} {chip.wait} {value:x}") def observe(self, address: int, width: int, kind: int) -> None: self.out.line(f"o {address:08x} {width} {kind}") def on_ftoa(self, level: int, clock: int) -> None: self.out.line(f"ftoa {level} {clock}") def on_ftob(self, level: int, clock: int) -> None: self.out.line(f"ftob {level} {clock}") def on_dack(self, channel: int, clock: int) -> None: self.out.line(f"dack {channel} {clock}") def on_txd(self, byte: int, clock: int) -> None: self.out.line(f"txd {byte} {clock}") def on_wdtovf(self, clock: int) -> None: self.out.line(f"wdtovf {clock}") def state_text(state) -> str: modules = ";".join( name + ":" + ",".join(f"{k}={v}" for k, v in values.items()) for name, values in state.modules.items() ) r = ",".join(str(v) for v in state.r) pipeline = ",".join(str(v) for v in state.pipeline) flags = ( f"{int(state.sleeping)} {int(state.no_interrupt)} {int(state.address_error)} " f"{int(state.nmi_pending)}" ) return ( f"S r={r} sr={state.sr} gbr={state.gbr} vbr={state.vbr} mach={state.mach} " f"macl={state.macl} pr={state.pr} pc={state.pc} dt={state.delay_target} " f"flags={flags} clock={state.clock} pipeline={pipeline} modules={modules}" ) def step_text(chip, states: int) -> str: r = " ".join(f"{v:x}" for v in chip.R) return ( f"s {states} {chip.clock} {chip.pc:x} {chip.delay_target} {chip.sr:x} " f"{int(chip.sleeping)} {r} {chip.gbr:x} {chip.vbr:x} {chip.mach:x} {chip.macl:x} " f"{chip.pr:x}" ) BOOLEAN = {"sleeping", "replay_interrupts"} FIELDS = {"pc", "sr", "gbr", "vbr", "mach", "macl", "pr", "delay_target", "irl", "nmi", "dreq0", "dreq1", "ftci", "fti", "clock"} # fmt: skip class Runner: def __init__(self, sh7604, scenario: dict, stream) -> None: self.sh7604 = sh7604 self.scenario = scenario self.out = Out(stream, scenario.get("slice", 0)) self.board = Board(scenario.get("board", {}), self.out) self.options = scenario.get("options", {}) self.state_at_slice = scenario.get("state_at_slice", True) self.steps = 0 self.free_fetch = False self.chip = self.make_chip() def make_chip(self): board = self.board o = self.options chip = self.sh7604( board.read, board.write, mode=o.get("mode", "master"), area0_width=o.get("area0_width", 32), undefined=o.get("undefined", 0), observe=board.observe if o.get("observe") else None, on_ftoa=board.on_ftoa, on_ftob=board.on_ftob, on_dack=board.on_dack, on_txd=board.on_txd, on_wdtovf=board.on_wdtovf, ) board.chip = chip return chip def set_free_fetch(self, on: bool) -> None: """The reference's tests' ``place_free`` (tests/test_pipeline.py ``run``).""" chip = self.chip self.free_fetch = on if not on: chip.__dict__.pop("_place", None) return place = type(chip)._place.__get__(chip) from sh2_python.pipeline import RING_MASK def place_free(slot: int) -> None: place(slot) chip._p_if[slot & RING_MASK] = -2 chip._place = place_free def drain_log(self) -> None: log = self.chip.pipeline_log if log: for event in log: self.out.line(repr(event)) log.clear() def one_step(self) -> None: chip = self.chip states = chip.step() self.drain_log() self.out.line(step_text(chip, states)) self.steps += 1 if self.out.slice and self.steps % self.out.slice == 0: if self.state_at_slice: self.out.line(state_text(chip.capture_state())) self.out.close_slice(chip) def run(self) -> None: for op in self.scenario["ops"]: self.do(op) chip = self.chip self.drain_log() self.out.line(state_text(chip.capture_state())) self.out.close_slice(chip) self.out.stream.write(f"end {self.steps} {chip.clock}\n") def do(self, op: list) -> None: chip = self.chip name = op[0] if name == "reset": chip.reset(power_on=op[1]) elif name == "set": field, value = op[1], op[2] if field in BOOLEAN: setattr(chip, field, bool(value)) elif field in FIELDS: setattr(chip, field, value) elif field == "pipeline_log": chip.pipeline_log = [] if value else None elif field == "free_fetch": self.set_free_fetch(bool(value)) elif field == "dmac_run_disabled": if value: chip.dmac.run = lambda: None else: chip.dmac.__dict__.pop("run", None) else: raise ValueError(f"unknown field {field}") elif name == "r": chip.R[op[1]] = op[2] elif name == "cycle_states": chip.bsc.cycle_states[:] = op[1] elif name == "restart": chip._pipeline_restart() elif name == "drop_fetched": chip._drop_fetched() elif name == "step": for _ in range(op[1]): self.one_step() elif name == "run_until": stop, limit = op[1], op[2] count = 0 while (chip.pc != stop or chip.delay_target >= 0) and count < limit: self.one_step() count += 1 self.out.line(f"= {count} {chip.clock}") elif name == "read": value = chip._read(op[1], op[2]) self.drain_log() self.out.line(f"= {value:x} {chip.clock}") elif name == "write": chip._write(op[1], op[2], op[3]) self.drain_log() self.out.line(f"= w {chip.clock}") elif name == "module_read": module = chip._onchip[op[1] - 0xFFFFFE00] value = module.read(op[1], op[2]) if module is not None else 0 self.out.line(f"= {value:x} {chip.clock}") elif name == "module_write": module = chip._onchip[op[1] - 0xFFFFFE00] if module is not None: module.write(op[1], op[2], op[3]) self.out.line(f"= w {chip.clock}") elif name == "write_ccr": chip.cache.write_ccr(op[1]) elif name == "cache_put": chip.cache.put(op[1], op[2], op[3]) elif name == "sci_receive": chip.sci.receive(op[1]) elif name == "bus_released": chip.bsc.bus_released() elif name == "inject": chip.inject_interrupt(op[1], op[2]) elif name == "save_restore": chip.restore_state(chip.capture_state()) elif name == "fresh_restore": state = chip.capture_state() log = chip.pipeline_log self.chip = self.make_chip() self.chip.pipeline_log = log if self.free_fetch: self.set_free_fetch(True) self.chip.restore_state(state) elif name == "state": self.out.line(state_text(chip.capture_state())) elif name == "poke": blob = bytes.fromhex(op[2]) for i, byte in enumerate(blob): self.board.put(op[1] + i, 8, byte) else: raise ValueError(f"unknown operation {name}") def main() -> int: root, out_dir, *paths = sys.argv[1:] sh7604 = load_reference(Path(root)) out_dir = Path(out_dir) out_dir.mkdir(parents=True, exist_ok=True) for path in map(Path, paths): scenario = json.loads(path.read_text()) target = out_dir / (path.stem + ".trace") partial = target.with_suffix(".partial") with partial.open("w") as stream: Runner(sh7604, scenario, stream).run() partial.replace(target) return 0 if __name__ == "__main__": sys.exit(main())