|
|
@@ -0,0 +1,348 @@
|
|
|
+#!/usr/bin/env python3
|
|
|
+"""Run real hthd through a PTY into the exact bound 6400 Production RTL."""
|
|
|
+
|
|
|
+from __future__ import annotations
|
|
|
+
|
|
|
+import hashlib
|
|
|
+import json
|
|
|
+import os
|
|
|
+import pty
|
|
|
+import select
|
|
|
+import shutil
|
|
|
+import socket
|
|
|
+import subprocess
|
|
|
+import sys
|
|
|
+import tempfile
|
|
|
+import termios
|
|
|
+import threading
|
|
|
+import time
|
|
|
+from pathlib import Path
|
|
|
+
|
|
|
+
|
|
|
+HERE = Path(__file__).resolve().parent
|
|
|
+HOST = HERE.parents[1]
|
|
|
+CPLD = Path(os.environ.get("HTH_CPLD_ROOT", HOST.parent / "cpld-temperature-control"))
|
|
|
+IMPORT_META = HOST / "generated/6400/import-source.json"
|
|
|
+CLOSURE = CPLD / "products/6400-control/source-closure.json"
|
|
|
+WRAPPER = CPLD / "tests/cocotb/prod2u_6400_v1_cocotb_top.v"
|
|
|
+
|
|
|
+
|
|
|
+def _bound_sources() -> list[Path]:
|
|
|
+ imported = json.loads(IMPORT_META.read_text(encoding="utf-8"))
|
|
|
+ expected_commit = imported["source_commit"]
|
|
|
+ actual_commit = subprocess.run(
|
|
|
+ ["git", "-C", str(CPLD), "rev-parse", "HEAD"],
|
|
|
+ check=True,
|
|
|
+ capture_output=True,
|
|
|
+ text=True,
|
|
|
+ ).stdout.strip()
|
|
|
+ if actual_commit != expected_commit:
|
|
|
+ raise RuntimeError(
|
|
|
+ f"CPLD worktree HEAD {actual_commit} != imported Production source {expected_commit}"
|
|
|
+ )
|
|
|
+ contract = CPLD / "generated/6400/host-contract.json"
|
|
|
+ actual_sha = hashlib.sha256(contract.read_bytes()).hexdigest()
|
|
|
+ if actual_sha != imported["source_contract_file_sha256"]:
|
|
|
+ raise RuntimeError(
|
|
|
+ f"CPLD contract file SHA {actual_sha} != imported {imported['source_contract_file_sha256']}"
|
|
|
+ )
|
|
|
+ closure = json.loads(CLOSURE.read_text(encoding="utf-8"))
|
|
|
+ sources = [CPLD / item for item in closure["sources"] if item.endswith(".v")]
|
|
|
+ missing = [str(path) for path in [*sources, WRAPPER] if not path.is_file()]
|
|
|
+ if missing:
|
|
|
+ raise RuntimeError("missing 6400 Production RTL: " + ", ".join(missing))
|
|
|
+ return sources
|
|
|
+
|
|
|
+
|
|
|
+def _set_raw(fd: int) -> None:
|
|
|
+ attrs = termios.tcgetattr(fd)
|
|
|
+ attrs[0] &= ~(
|
|
|
+ termios.IGNBRK
|
|
|
+ | termios.BRKINT
|
|
|
+ | termios.PARMRK
|
|
|
+ | termios.ISTRIP
|
|
|
+ | termios.INLCR
|
|
|
+ | termios.IGNCR
|
|
|
+ | termios.ICRNL
|
|
|
+ | termios.IXON
|
|
|
+ )
|
|
|
+ attrs[1] &= ~termios.OPOST
|
|
|
+ attrs[2] |= termios.CS8 | termios.CLOCAL | termios.CREAD
|
|
|
+ attrs[2] &= ~(termios.PARENB | termios.CSTOPB | termios.HUPCL)
|
|
|
+ attrs[3] &= ~(
|
|
|
+ termios.ECHO
|
|
|
+ | termios.ECHONL
|
|
|
+ | termios.ICANON
|
|
|
+ | termios.ISIG
|
|
|
+ | termios.IEXTEN
|
|
|
+ )
|
|
|
+ attrs[6][termios.VMIN] = 0
|
|
|
+ attrs[6][termios.VTIME] = 0
|
|
|
+ termios.tcsetattr(fd, termios.TCSANOW, attrs)
|
|
|
+
|
|
|
+
|
|
|
+def _shuttle(master_fd: int, conn: socket.socket, stop: threading.Event, log: Path) -> None:
|
|
|
+ up = down = 0
|
|
|
+ rtl_frame = bytearray()
|
|
|
+ with log.open("a", encoding="utf-8") as output:
|
|
|
+ while not stop.is_set():
|
|
|
+ try:
|
|
|
+ ready, _, _ = select.select([master_fd, conn], [], [], 0.05)
|
|
|
+ except (OSError, ValueError):
|
|
|
+ break
|
|
|
+ if master_fd in ready:
|
|
|
+ try:
|
|
|
+ data = os.read(master_fd, 512)
|
|
|
+ except OSError:
|
|
|
+ continue
|
|
|
+ if data:
|
|
|
+ up += len(data)
|
|
|
+ output.write(f"pty->rtl {data.hex()}\n")
|
|
|
+ output.flush()
|
|
|
+ conn.sendall(data)
|
|
|
+ if conn in ready:
|
|
|
+ try:
|
|
|
+ data = conn.recv(512)
|
|
|
+ except OSError:
|
|
|
+ continue
|
|
|
+ if data:
|
|
|
+ down += len(data)
|
|
|
+ output.write(f"rtl->pty {data.hex()}\n")
|
|
|
+ output.flush()
|
|
|
+ rtl_frame.extend(data)
|
|
|
+ while True:
|
|
|
+ while rtl_frame and rtl_frame[0] != 0xA5:
|
|
|
+ del rtl_frame[0]
|
|
|
+ if len(rtl_frame) < 4:
|
|
|
+ break
|
|
|
+ if rtl_frame[1] != 0x5A:
|
|
|
+ del rtl_frame[0]
|
|
|
+ continue
|
|
|
+ frame_len = 6 + rtl_frame[3]
|
|
|
+ if len(rtl_frame) < frame_len:
|
|
|
+ break
|
|
|
+ frame = bytes(rtl_frame[:frame_len])
|
|
|
+ del rtl_frame[:frame_len]
|
|
|
+ # Icarus advances one UART byte much slower than wall
|
|
|
+ # time. Deliver each fully observed RTL frame in one
|
|
|
+ # PTY write so the production 10 ms inter-byte guard is
|
|
|
+ # not confused by simulator speed.
|
|
|
+ os.write(master_fd, frame)
|
|
|
+ output.write(f"totals pty_to_rtl={up} rtl_to_pty={down}\n")
|
|
|
+
|
|
|
+
|
|
|
+def _write_config(path: Path, serial: str, runtime: Path) -> tuple[Path, Path]:
|
|
|
+ observe = runtime / "observe.sock"
|
|
|
+ control = runtime / "control.sock"
|
|
|
+ path.write_text(
|
|
|
+ f"""api_version: hth.api.v1
|
|
|
+product: 6400-front-rear-v1
|
|
|
+device_id: prod2u-6400-0
|
|
|
+display_name: 6400 RTL cosim
|
|
|
+backend: serial
|
|
|
+runtime_root: {runtime}
|
|
|
+serial:
|
|
|
+ path: {serial}
|
|
|
+sockets:
|
|
|
+ observe: {observe}
|
|
|
+ control: {control}
|
|
|
+ observe_perm: "0660"
|
|
|
+ control_perm: "0660"
|
|
|
+thermal:
|
|
|
+ firmware_profile: 6400-control
|
|
|
+ transaction_timeout_ms: 15000
|
|
|
+ retries: 1
|
|
|
+grpc:
|
|
|
+ reflection: false
|
|
|
+""",
|
|
|
+ encoding="utf-8",
|
|
|
+ )
|
|
|
+ return observe, control
|
|
|
+
|
|
|
+
|
|
|
+def _run_sim() -> int:
|
|
|
+ try:
|
|
|
+ from cocotb_tools.runner import get_runner
|
|
|
+ except ModuleNotFoundError:
|
|
|
+ from cocotb.runner import get_runner
|
|
|
+
|
|
|
+ runner = get_runner("icarus")
|
|
|
+ runner.build(
|
|
|
+ sources=[*_bound_sources(), WRAPPER],
|
|
|
+ hdl_toplevel="prod2u_6400_v1_cocotb_top",
|
|
|
+ build_dir=os.environ["HTH_SIM_DIR"],
|
|
|
+ build_args=["-g2012", "-I", str(CPLD)],
|
|
|
+ parameters={"ENABLE_STIMULUS": 0},
|
|
|
+ always=True,
|
|
|
+ )
|
|
|
+ runner.test(
|
|
|
+ hdl_toplevel="prod2u_6400_v1_cocotb_top",
|
|
|
+ test_module="test_hthd_6400_pty_bridge",
|
|
|
+ test_dir=HERE,
|
|
|
+ build_dir=os.environ["HTH_SIM_DIR"],
|
|
|
+ results_xml=os.environ["HTH_RESULTS_XML"],
|
|
|
+ extra_env={
|
|
|
+ "HTH_UART_BRIDGE": os.environ["HTH_UART_BRIDGE"],
|
|
|
+ "HTH_RTL_RESULT": os.environ["HTH_RTL_RESULT"],
|
|
|
+ "HTH_BRIDGE_READY": os.environ["HTH_BRIDGE_READY"],
|
|
|
+ "HTH_SIM_DONE": os.environ["HTH_SIM_DONE"],
|
|
|
+ "PYTHONPATH": str(HERE),
|
|
|
+ },
|
|
|
+ )
|
|
|
+ return 0
|
|
|
+
|
|
|
+
|
|
|
+def _wait_path(path: Path, timeout: float) -> None:
|
|
|
+ deadline = time.monotonic() + timeout
|
|
|
+ while time.monotonic() < deadline:
|
|
|
+ if path.exists():
|
|
|
+ return
|
|
|
+ time.sleep(0.05)
|
|
|
+ raise TimeoutError(f"timed out waiting for {path}")
|
|
|
+
|
|
|
+
|
|
|
+def main() -> int:
|
|
|
+ if "--sim" in sys.argv:
|
|
|
+ return _run_sim()
|
|
|
+
|
|
|
+ if not shutil.which("iverilog") or not shutil.which("vvp"):
|
|
|
+ print("6400 hthd PTY RTL cosim: NOT RUN (Icarus missing)")
|
|
|
+ return 2
|
|
|
+ try:
|
|
|
+ import cocotb # noqa: F401
|
|
|
+ import grpc # noqa: F401
|
|
|
+ except ImportError as exc:
|
|
|
+ print(f"6400 hthd PTY RTL cosim: NOT RUN ({exc})")
|
|
|
+ return 2
|
|
|
+ try:
|
|
|
+ _bound_sources()
|
|
|
+ except Exception as exc:
|
|
|
+ print(f"6400 hthd PTY RTL cosim: NOT RUN ({exc})")
|
|
|
+ return 2
|
|
|
+
|
|
|
+ hthd_bin = Path(os.environ.get("HTH_HTHD_BIN", ""))
|
|
|
+ if not hthd_bin.is_file():
|
|
|
+ print("6400 hthd PTY RTL cosim: NOT RUN (set HTH_HTHD_BIN)")
|
|
|
+ return 2
|
|
|
+
|
|
|
+ requested = os.environ.get("HTH_COSIM_RUN_DIR")
|
|
|
+ if requested:
|
|
|
+ build = Path(requested)
|
|
|
+ build.mkdir(parents=True, exist_ok=False)
|
|
|
+ else:
|
|
|
+ build = Path(tempfile.mkdtemp(prefix="hth-6400-rtl-"))
|
|
|
+ runtime = build / "runtime"
|
|
|
+ runtime.mkdir()
|
|
|
+ sim_dir = build / "sim"
|
|
|
+ result = build / "result.txt"
|
|
|
+ ready = build / "bridge.ready"
|
|
|
+ done = build / "sim.done"
|
|
|
+ results_xml = build / "results.xml"
|
|
|
+ bridge = build / "uart.bridge"
|
|
|
+ config = build / "hthd.yaml"
|
|
|
+ uart_log = build / "uart.log"
|
|
|
+
|
|
|
+ master, slave = pty.openpty()
|
|
|
+ _set_raw(master)
|
|
|
+ _set_raw(slave)
|
|
|
+ observe, control = _write_config(config, os.ttyname(slave), runtime)
|
|
|
+
|
|
|
+ server = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
|
|
|
+ server.bind(str(bridge))
|
|
|
+ server.listen(1)
|
|
|
+ server.settimeout(90)
|
|
|
+ env = os.environ.copy()
|
|
|
+ env.update(
|
|
|
+ {
|
|
|
+ "HTH_UART_BRIDGE": str(bridge),
|
|
|
+ "HTH_RTL_RESULT": str(result),
|
|
|
+ "HTH_BRIDGE_READY": str(ready),
|
|
|
+ "HTH_SIM_DONE": str(done),
|
|
|
+ "HTH_SIM_DIR": str(sim_dir),
|
|
|
+ "HTH_RESULTS_XML": str(results_xml),
|
|
|
+ "PYTHONPATH": os.pathsep.join((str(HERE), str(CPLD), env.get("PYTHONPATH", ""))),
|
|
|
+ }
|
|
|
+ )
|
|
|
+
|
|
|
+ simulator = subprocess.Popen(
|
|
|
+ [sys.executable, "-B", str(Path(__file__).resolve()), "--sim"],
|
|
|
+ cwd=HERE,
|
|
|
+ env=env,
|
|
|
+ )
|
|
|
+ hthd: subprocess.Popen | None = None
|
|
|
+ conn: socket.socket | None = None
|
|
|
+ stop = threading.Event()
|
|
|
+ try:
|
|
|
+ conn, _ = server.accept()
|
|
|
+ threading.Thread(
|
|
|
+ target=_shuttle, args=(master, conn, stop, uart_log), daemon=True
|
|
|
+ ).start()
|
|
|
+ _wait_path(ready, 30)
|
|
|
+ hthd = subprocess.Popen(
|
|
|
+ [str(hthd_bin), "--config", str(config)],
|
|
|
+ cwd=HOST,
|
|
|
+ stdout=(build / "hthd.stdout").open("w", encoding="utf-8"),
|
|
|
+ stderr=(build / "hthd.stderr").open("w", encoding="utf-8"),
|
|
|
+ )
|
|
|
+ _wait_path(observe, 10)
|
|
|
+ _wait_path(control, 10)
|
|
|
+
|
|
|
+ sys.path.insert(0, str(HOST / "sdk/python"))
|
|
|
+ from hth_sdk.thermal import connect_thermal
|
|
|
+
|
|
|
+ with connect_thermal(
|
|
|
+ device_id="prod2u-6400-0",
|
|
|
+ observe_socket=str(observe),
|
|
|
+ control_socket=str(control),
|
|
|
+ firmware_profile="6400-control",
|
|
|
+ timeout=40.0,
|
|
|
+ ) as thermal:
|
|
|
+ thermal.set_target(60)
|
|
|
+ snapshot = thermal.get_snapshot()
|
|
|
+ if len(snapshot.payload) != 193:
|
|
|
+ raise AssertionError(f"snapshot length {len(snapshot.payload)} != 193")
|
|
|
+ if snapshot.decoded["current_target"] != 60:
|
|
|
+ raise AssertionError(f"target did not commit: {snapshot.decoded['current_target']}")
|
|
|
+ try:
|
|
|
+ thermal.run_stimulus(1, [0] * 24, [0] * 4, [0] * 4)
|
|
|
+ except NotImplementedError:
|
|
|
+ pass
|
|
|
+ else:
|
|
|
+ raise AssertionError("Production profile exposed stimulus")
|
|
|
+ thermal.stop()
|
|
|
+
|
|
|
+ result.write_text(
|
|
|
+ "PASS profile=6400-control set_ack=PASS get_ack=PASS "
|
|
|
+ "snapshot_data=193 stimulus=REJECTED\n",
|
|
|
+ encoding="utf-8",
|
|
|
+ )
|
|
|
+ done.write_text("done\n", encoding="utf-8")
|
|
|
+ if simulator.wait(timeout=60) != 0:
|
|
|
+ raise RuntimeError("cocotb simulator failed")
|
|
|
+ print("RTL_HTHD_6400_PTY_UART_PASS")
|
|
|
+ print(result.read_text(encoding="utf-8").strip())
|
|
|
+ print(f"artifacts={build}")
|
|
|
+ return 0
|
|
|
+ finally:
|
|
|
+ stop.set()
|
|
|
+ if hthd is not None:
|
|
|
+ hthd.terminate()
|
|
|
+ try:
|
|
|
+ hthd.wait(timeout=5)
|
|
|
+ except subprocess.TimeoutExpired:
|
|
|
+ hthd.kill()
|
|
|
+ if simulator.poll() is None:
|
|
|
+ simulator.terminate()
|
|
|
+ try:
|
|
|
+ simulator.wait(timeout=5)
|
|
|
+ except subprocess.TimeoutExpired:
|
|
|
+ simulator.kill()
|
|
|
+ if conn is not None:
|
|
|
+ conn.close()
|
|
|
+ server.close()
|
|
|
+ os.close(master)
|
|
|
+ os.close(slave)
|
|
|
+
|
|
|
+
|
|
|
+if __name__ == "__main__":
|
|
|
+ raise SystemExit(main())
|