run_hthd_pty_rtl.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768
  1. #!/usr/bin/env python3
  2. """L3: real hthd + PTY + UART-bit bridge + current Prod2U top (Icarus/cocotb).
  3. Exit 0 on PASS, 1 on fail, 2 if tools/RTL/cocotb are missing (NOT RUN).
  4. """
  5. from __future__ import annotations
  6. import os
  7. import pty
  8. import select
  9. import socket
  10. import subprocess
  11. import sys
  12. import tempfile
  13. import termios
  14. import threading
  15. import time
  16. from pathlib import Path
  17. HERE = Path(__file__).resolve().parent
  18. HOST = HERE.parents[1]
  19. REPO = HOST.parent
  20. sys.path.insert(0, str(REPO))
  21. OSS_CAD_POISON = ("PYTHONEXECUTABLE", "PYTHONHOME", "PYTHONNOUSERSITE")
  22. UART_FAST = HERE / "prod2u_hthd_fast_uart_top.v"
  23. UART_PROD = HERE / "prod2u_hthd_prod_uart_top.v"
  24. def _uart_choice() -> tuple[Path, str, str]:
  25. if os.environ.get("HTH_PRODUCTION_UART") == "1":
  26. return UART_PROD, "prod2u_hthd_prod_uart_top", "217"
  27. return UART_FAST, "prod2u_hthd_fast_uart_top", "8"
  28. def _cad_root() -> Path | None:
  29. for root in (Path("/data/prod2u/oss-cad-suite/latest"), Path("/data/prod2u/oss-cad-suite")):
  30. if (root / "libexec" / "iverilog").is_file() and (root / "libexec" / "vvp").is_file():
  31. return root
  32. return None
  33. def _python_libdir(python: Path) -> str:
  34. r = subprocess.run(
  35. [str(python), "-c", "import sysconfig; print(sysconfig.get_config_var('LIBDIR') or '')"],
  36. stdout=subprocess.PIPE,
  37. stderr=subprocess.DEVNULL,
  38. text=True,
  39. timeout=10,
  40. env={k: v for k, v in os.environ.items() if k not in OSS_CAD_POISON},
  41. )
  42. return (r.stdout or "").strip()
  43. def _write_clean_cad_shims(shim: Path, cad: Path, extra_libs: list[str] | None = None) -> None:
  44. """Call libexec iverilog/vvp without the OSS CAD vvp wrapper's PYTHONEXECUTABLE poison."""
  45. shim.mkdir(parents=True, exist_ok=True)
  46. ld = cad / "lib" / "ld-linux-x86-64.so.2"
  47. lib = cad / "lib"
  48. iver = cad / "libexec" / "iverilog"
  49. vvp = cad / "libexec" / "vvp"
  50. lib_parts = [p for p in (extra_libs or []) if p]
  51. lib_parts.append(str(lib))
  52. libpath = ":".join(lib_parts)
  53. vvp_shim = shim / "vvp"
  54. vvp_shim.write_text(
  55. f"#!/bin/bash\nexec {ld} --inhibit-cache --inhibit-rpath '' --library-path {libpath} {vvp} \"$@\"\n",
  56. encoding="utf-8",
  57. )
  58. vvp_shim.chmod(0o755)
  59. iver_shim = shim / "iverilog"
  60. iver_shim.write_text(
  61. f"#!/bin/bash\nexec {ld} --inhibit-cache --inhibit-rpath '' --library-path {lib} {iver} -p VVP_EXECUTABLE={vvp_shim} \"$@\"\n",
  62. encoding="utf-8",
  63. )
  64. iver_shim.chmod(0o755)
  65. def _select_cocotb_python() -> Path | None:
  66. candidates = [
  67. Path(os.environ.get("PROD2U_P4_COCOTB_PYTHON", "")),
  68. Path("/opt/hth-cocotb312/bin/python"),
  69. Path("/opt/hth-cocotb/bin/python"),
  70. Path("/root/.cache/prod2u/venvs/verify/bin/python"),
  71. Path(sys.executable),
  72. ]
  73. for cand in candidates:
  74. if not cand.is_file():
  75. continue
  76. r = subprocess.run(
  77. [str(cand), "-B", "-c", "import cocotb, cocotb_tools"],
  78. stdout=subprocess.DEVNULL,
  79. stderr=subprocess.DEVNULL,
  80. timeout=20,
  81. env={k: v for k, v in os.environ.items() if k not in OSS_CAD_POISON},
  82. )
  83. if r.returncode == 0:
  84. return cand
  85. return None
  86. def _sdk_python() -> Path:
  87. cands = [
  88. Path(os.environ.get("HTH_SDK_PYTHON", "")),
  89. HOST / ".venv-sdk" / "bin" / "python3",
  90. HOST / ".venv-sdk" / "bin" / "python",
  91. Path("/opt/python-3.12/bin/python3.12"),
  92. Path("/usr/bin/python3.13"),
  93. Path(sys.executable),
  94. ]
  95. for cand in cands:
  96. if not cand.is_file():
  97. continue
  98. r = subprocess.run(
  99. [str(cand), "-c", "import grpc"],
  100. stdout=subprocess.DEVNULL,
  101. stderr=subprocess.DEVNULL,
  102. )
  103. if r.returncode == 0:
  104. return cand
  105. return Path(sys.executable)
  106. def _shim_dir(build: Path, python: Path, cad: Path) -> Path:
  107. shim = build / "path-shim"
  108. extra = []
  109. pydir = _python_libdir(python)
  110. if pydir:
  111. extra.append(pydir)
  112. extra.append("/opt/python-3.12/lib")
  113. _write_clean_cad_shims(shim, cad, extra)
  114. for name in ("python", "python3"):
  115. path = shim / name
  116. if path.exists() or path.is_symlink():
  117. path.unlink()
  118. path.symlink_to(python)
  119. return shim
  120. def _rtl_sources() -> list[Path]:
  121. from tools.prod2u_p4_normal_v3_build import PRODUCTION_RTL_SOURCES
  122. return [REPO / rel for rel in PRODUCTION_RTL_SOURCES]
  123. def _write_hthd_yaml(path: Path, slave: str, obs: str, ctl: str, runtime_root: str) -> None:
  124. path.write_text(
  125. f"""api_version: hth.api.v1
  126. device_id: prod2u-0
  127. backend: serial
  128. profile: {HOST / "profiles" / "prod2u-door-temp" / "profile.json"}
  129. runtime_root: {runtime_root}
  130. serial:
  131. path: {slave}
  132. io_timeout_ms: 28000
  133. inter_byte_timeout_ms: 2000
  134. response_timeout_ms: 28000
  135. get_temp_timeout_ms: 28000
  136. get_motor_timeout_ms: 28000
  137. probe_timeout_ms: 28000
  138. set_all_timeout_ms: 2000
  139. open_timeout_ms: 5000
  140. sockets:
  141. observe: {obs}
  142. control: {ctl}
  143. poll:
  144. temperature_ms: 12000
  145. motor_status_ms: 1500
  146. watchdog:
  147. heartbeat_period_ms: 8000
  148. lease:
  149. min_ttl_ms: 50
  150. max_ttl_ms: 30000
  151. safety:
  152. fan: 10
  153. ptc: 0
  154. door_close_percent: 0
  155. ring_buffer_size: 32
  156. subscriber_buffer_size: 64
  157. grpc:
  158. reflection: false
  159. """,
  160. encoding="utf-8",
  161. )
  162. def _set_raw_clocal(fd: int) -> None:
  163. """Binary 8N1-like PTY: no ICANON (or SET_ALL never leaves the line buffer)."""
  164. attrs = termios.tcgetattr(fd)
  165. attrs[0] &= ~(
  166. termios.IGNBRK | termios.BRKINT | termios.PARMRK | termios.ISTRIP
  167. | termios.INLCR | termios.IGNCR | termios.ICRNL | termios.IXON
  168. )
  169. attrs[1] &= ~termios.OPOST
  170. attrs[2] |= termios.CS8 | termios.CLOCAL | termios.CREAD
  171. attrs[2] &= ~(termios.PARENB | termios.CSTOPB | termios.HUPCL)
  172. attrs[3] &= ~(termios.ECHO | termios.ECHONL | termios.ICANON | termios.ISIG | termios.IEXTEN)
  173. attrs[6][termios.VMIN] = 0
  174. attrs[6][termios.VTIME] = 0
  175. termios.tcsetattr(fd, termios.TCSANOW, attrs)
  176. def _crc16_ccitt_false(data: bytes) -> int:
  177. crc = 0xFFFF
  178. for b in data:
  179. crc ^= b << 8
  180. for _ in range(8):
  181. if crc & 0x8000:
  182. crc = ((crc << 1) & 0xFFFF) ^ 0x1021
  183. else:
  184. crc = (crc << 1) & 0xFFFF
  185. return crc
  186. def _extract_frames(buf: bytearray) -> list[bytes]:
  187. out: list[bytes] = []
  188. while len(buf) >= 6:
  189. if buf[0] != 0xA5:
  190. del buf[0]
  191. continue
  192. if buf[1] != 0x5A:
  193. del buf[0]
  194. continue
  195. plen = buf[3]
  196. need = 6 + plen
  197. if len(buf) < need:
  198. break
  199. out.append(bytes(buf[:need]))
  200. del buf[:need]
  201. return out
  202. def _clear_startup_complete(frame: bytes) -> bytes:
  203. if len(frame) < 7 or frame[2] != 0x83 or frame[3] != 31:
  204. return frame
  205. payload = bytearray(frame[4:-2])
  206. payload[0] &= 0xBF
  207. body = bytes([frame[2], frame[3]]) + bytes(payload)
  208. crc = _crc16_ccitt_false(body)
  209. return bytes([0xA5, 0x5A]) + body + bytes((crc & 0xFF, crc >> 8))
  210. class UartTap:
  211. """Hold MOTOR_STATUS startup_complete=0 for wall-clock delayed-startup tests.
  212. Production UART (217 clocks/bit through Icarus) needs ~13s for the first
  213. MOTOR_STATUS round-trip. A 10s hold expires first, leaks startup_complete,
  214. and hthd immediately sends GET_TEMPERATURE which then times out.
  215. Keep holding until hold_s elapses AND at least one MOTOR_STATUS has been
  216. rewritten, capped at max_hold_s.
  217. """
  218. def __init__(self, hold_s: float = 10.0, max_hold_s: float | None = None) -> None:
  219. self.hold_s = hold_s
  220. self.max_hold_s = hold_s if max_hold_s is None else max_hold_s
  221. self._start = 0.0
  222. self._started = threading.Event()
  223. self._cleared_motors = 0
  224. self.up_buf = bytearray()
  225. self.dn_buf = bytearray()
  226. self.get_temp_during_hold = 0
  227. self.get_temp_after = 0
  228. self.motor_req_during_hold = 0
  229. self.motor_req_after = 0
  230. self.lock = threading.Lock()
  231. def mark_hthd_start(self) -> None:
  232. self._start = time.monotonic()
  233. self._started.set()
  234. def holding(self) -> bool:
  235. if not self._started.is_set():
  236. return False
  237. elapsed = time.monotonic() - self._start
  238. if elapsed >= self.max_hold_s:
  239. return False
  240. if elapsed < self.hold_s:
  241. return True
  242. return self._cleared_motors == 0
  243. def on_pty_to_rtl(self, data: bytes) -> None:
  244. self.up_buf.extend(data)
  245. for frame in _extract_frames(self.up_buf):
  246. if len(frame) < 3:
  247. continue
  248. typ = frame[2]
  249. with self.lock:
  250. hold = self.holding()
  251. if typ == 0x02:
  252. if hold:
  253. self.get_temp_during_hold += 1
  254. else:
  255. self.get_temp_after += 1
  256. elif typ == 0x03:
  257. if hold:
  258. self.motor_req_during_hold += 1
  259. else:
  260. self.motor_req_after += 1
  261. def rewrite_rtl_to_pty(self, data: bytes) -> bytes:
  262. self.dn_buf.extend(data)
  263. frames = _extract_frames(self.dn_buf)
  264. if not frames:
  265. return b""
  266. out = bytearray()
  267. hold = self.holding()
  268. for frame in frames:
  269. if hold and len(frame) >= 3 and frame[2] == 0x83:
  270. frame = _clear_startup_complete(frame)
  271. self._cleared_motors += 1
  272. out.extend(frame)
  273. return bytes(out)
  274. def _shuttle(master_fd: int, conn: socket.socket, stop: threading.Event, tap: UartTap | None = None) -> None:
  275. log_path = Path(os.environ.get("HTH_UART_LOG", "/tmp/hth-uart-bridge.log"))
  276. n_up = n_dn = 0
  277. while not stop.is_set():
  278. try:
  279. ready, _, _ = select.select([master_fd, conn], [], [], 0.05)
  280. except (OSError, ValueError):
  281. break
  282. if master_fd in ready:
  283. try:
  284. data = os.read(master_fd, 256)
  285. except OSError:
  286. time.sleep(0.01)
  287. continue
  288. if data:
  289. n_up += len(data)
  290. line = f"pty->rtl {data.hex()}\n"
  291. if n_up <= 256:
  292. print(line, end="", flush=True)
  293. try:
  294. with log_path.open("a", encoding="utf-8") as f:
  295. if n_up <= 256:
  296. f.write(line)
  297. except OSError:
  298. pass
  299. if tap is not None:
  300. tap.on_pty_to_rtl(data)
  301. try:
  302. conn.sendall(data)
  303. except OSError:
  304. time.sleep(0.01)
  305. continue
  306. if conn in ready:
  307. try:
  308. data = conn.recv(256)
  309. except OSError:
  310. time.sleep(0.01)
  311. continue
  312. if data:
  313. if tap is not None:
  314. data = tap.rewrite_rtl_to_pty(data)
  315. if not data:
  316. continue
  317. n_dn += len(data)
  318. line = f"rtl->pty {data.hex()}\n"
  319. if n_dn <= 256:
  320. print(line, end="", flush=True)
  321. try:
  322. with log_path.open("a", encoding="utf-8") as f:
  323. if n_dn <= 256:
  324. f.write(line)
  325. except OSError:
  326. pass
  327. try:
  328. os.write(master_fd, data)
  329. except OSError:
  330. time.sleep(0.01)
  331. continue
  332. try:
  333. with log_path.open("a", encoding="utf-8") as f:
  334. f.write(f"totals pty_to_rtl={n_up} rtl_to_pty={n_dn}\n")
  335. except OSError:
  336. pass
  337. def _sdk_apply(obs: str, ctl: str) -> None:
  338. script = r"""
  339. import asyncio, os, sys
  340. from datetime import timedelta
  341. from pathlib import Path
  342. sys.path.insert(0, os.environ["HTH_SDK_SRC"])
  343. from hth_sdk.client import connect
  344. from hth_sdk.types import ActionBatch
  345. async def main():
  346. obs, ctl = os.environ["HTH_OBS"], os.environ["HTH_CTL"]
  347. async with await connect(observe=obs, control=ctl, role="control") as client:
  348. for _ in range(400):
  349. snap = await client.get_snapshot("prod2u-0")
  350. if snap.lifecycle == "READY":
  351. break
  352. await asyncio.sleep(0.5)
  353. else:
  354. raise SystemExit("hthd never reached READY against RTL")
  355. caps = await client.get_capabilities("prod2u-0")
  356. async with await client.acquire_lease("prod2u-0", "rtl-l3", timedelta(seconds=30), auto_renew=True) as lease:
  357. snap = await client.get_snapshot("prod2u-0")
  358. b = ActionBatch.builder("prod2u-0", capabilities=caps).based_on(snap.snapshot_seq, snap.control_revision)
  359. b.valid_for(timedelta(seconds=180))
  360. for act in caps.actuators:
  361. if "door" in act.id and "close_percent" in act.id:
  362. b.set(act.id, 50)
  363. elif act.id.startswith("fan."):
  364. b.set(act.id, 10)
  365. elif act.id.startswith("ptc."):
  366. b.set(act.id, 0)
  367. else:
  368. b.set(act.id, act.safety_default)
  369. res = await lease.apply(b.build())
  370. if not res.accepted:
  371. raise SystemExit(f"ApplyAction rejected: {res}")
  372. print("APPLY_ACCEPTED")
  373. asyncio.run(main())
  374. """
  375. env = os.environ.copy()
  376. env["HTH_OBS"] = obs
  377. env["HTH_CTL"] = ctl
  378. env["HTH_SDK_SRC"] = str(HOST / "sdk" / "python")
  379. r = subprocess.run([str(_sdk_python()), "-B", "-c", script], env=env, capture_output=True, text=True)
  380. sys.stdout.write(r.stdout)
  381. sys.stderr.write(r.stderr)
  382. if r.returncode != 0:
  383. raise RuntimeError("sdk apply failed")
  384. def _sdk_safe_resume(obs: str, ctl: str) -> None:
  385. script = r"""
  386. import asyncio, os, sys
  387. from datetime import timedelta
  388. sys.path.insert(0, os.environ["HTH_SDK_SRC"])
  389. from hth_sdk.client import connect
  390. from hth_sdk.types import ActionBatch
  391. async def main():
  392. obs, ctl = os.environ["HTH_OBS"], os.environ["HTH_CTL"]
  393. async with await connect(observe=obs, control=ctl, role="control") as client:
  394. snap = await client.get_snapshot("prod2u-0")
  395. temps = [m for m in snap.measurements if m.id.startswith("temperature.channel.")]
  396. if len(temps) < 27:
  397. raise SystemExit(f"expected 27 temperature channels after GET_TEMP, got {len(temps)}")
  398. print("TEMP_CHANNELS", len(temps), "EVENT_ID", snap.event_id, "QUALITY", sorted({m.quality for m in temps}))
  399. caps = await client.get_capabilities("prod2u-0")
  400. async with await client.acquire_lease("prod2u-0", "rtl-safe", timedelta(seconds=30), auto_renew=True) as lease:
  401. safe = await lease.enter_safe_mode("rtl-safe")
  402. print("SAFE_ACCEPTED", safe.accepted, safe.dispatch_state, safe.confirmation)
  403. snap = await client.get_snapshot("prod2u-0")
  404. rb = ActionBatch.builder("prod2u-0", capabilities=caps).based_on(snap.snapshot_seq, snap.control_revision)
  405. rb.valid_for(timedelta(seconds=180))
  406. for act in caps.actuators:
  407. if act.id.startswith("fan."):
  408. rb.set(act.id, 10)
  409. elif act.id.startswith("ptc."):
  410. rb.set(act.id, 0)
  411. elif "door" in act.id and "close_percent" in act.id:
  412. rb.set(act.id, 0)
  413. else:
  414. rb.set(act.id, act.safety_default)
  415. resumed = await lease.resume_from_safe(rb.build())
  416. print("RESUME_ACCEPTED", resumed.accepted, resumed.dispatch_state, resumed.confirmation)
  417. snap2 = await client.get_snapshot("prod2u-0")
  418. if snap2.event_id < snap.event_id:
  419. raise SystemExit(f"event_id went backwards {snap.event_id} -> {snap2.event_id}")
  420. print("EVENT_ID_MONOTONIC", snap.event_id, snap2.event_id)
  421. hb_ok = False
  422. for _ in range(40):
  423. s = await client.get_snapshot("prod2u-0")
  424. if s.last_successful_hardware_heartbeat is not None:
  425. hb_ok = True
  426. print("HEARTBEAT_SEEN", s.last_successful_hardware_heartbeat, "REV", s.control_revision)
  427. break
  428. await asyncio.sleep(0.5)
  429. if not hb_ok:
  430. raise SystemExit("no hardware heartbeat after resume")
  431. print("RTL_SAFE_RESUME_HEARTBEAT_PATH_OK")
  432. asyncio.run(main())
  433. """
  434. env = os.environ.copy()
  435. env["HTH_OBS"] = obs
  436. env["HTH_CTL"] = ctl
  437. env["HTH_SDK_SRC"] = str(HOST / "sdk" / "python")
  438. r = subprocess.run([str(_sdk_python()), "-B", "-c", script], env=env, capture_output=True, text=True)
  439. sys.stdout.write(r.stdout)
  440. sys.stderr.write(r.stderr)
  441. if r.returncode != 0:
  442. raise RuntimeError("sdk safe/resume failed")
  443. def _run_sim_child() -> int:
  444. py = Path(os.environ["PYGPI_PYTHON_BIN"])
  445. from cocotb_tools.runner import get_runner
  446. uart_top, hdl_top, clks = _uart_choice()
  447. runner = get_runner("icarus")
  448. sources = _rtl_sources()
  449. runner.build(
  450. sources=[*sources, uart_top],
  451. hdl_toplevel=hdl_top,
  452. build_dir=os.environ["HTH_SIM_DIR"],
  453. build_args=["-I", str(REPO)],
  454. always=True,
  455. verbose=False,
  456. )
  457. runner.test(
  458. hdl_toplevel=hdl_top,
  459. test_module="test_hthd_pty_bridge",
  460. build_dir=os.environ["HTH_SIM_DIR"],
  461. test_dir=str(HERE),
  462. results_xml=os.environ["HTH_RESULTS_XML"],
  463. extra_env={
  464. "HTH_UART_BRIDGE": os.environ["HTH_UART_BRIDGE"],
  465. "HTH_RTL_RESULT": os.environ["HTH_RTL_RESULT"],
  466. "HTH_BRIDGE_READY": os.environ["HTH_BRIDGE_READY"],
  467. "HTH_STARTUP_FILE": os.environ["HTH_STARTUP_FILE"],
  468. "HTH_SIM_STOP": os.environ.get("HTH_SIM_STOP", ""),
  469. "HTH_EXPECT_PERCENT": "50",
  470. "HTH_CLKS_PER_BIT": clks,
  471. "PYTHONPATH": str(HERE),
  472. "PYGPI_PYTHON_BIN": str(py),
  473. "PATH": os.environ["PATH"],
  474. "LIBPYTHON_LOC": os.environ.get(
  475. "LIBPYTHON_LOC", "/opt/python-3.12/lib/libpython3.12.so.1.0"
  476. ),
  477. },
  478. )
  479. return 0
  480. def main() -> int:
  481. if "--production-uart" in sys.argv:
  482. os.environ["HTH_PRODUCTION_UART"] = "1"
  483. os.environ["HTH_CLKS_PER_BIT"] = "217"
  484. if "--sim" in sys.argv:
  485. return _run_sim_child()
  486. skip = "--skip-missing" in sys.argv
  487. cad = _cad_root()
  488. py = _select_cocotb_python()
  489. uart_top, hdl_top, clks = _uart_choice()
  490. try:
  491. sources = _rtl_sources()
  492. missing_rtl = [str(p) for p in sources if not p.is_file()]
  493. except Exception as exc:
  494. print("RTL-in-the-loop hthd+PTY+UART-bit: NOT RUN")
  495. print("source_manifest:", exc)
  496. return 2 if skip else 1
  497. if not uart_top.is_file():
  498. missing_rtl.append(str(uart_top))
  499. if cad is None or py is None or missing_rtl:
  500. print("RTL-in-the-loop hthd+PTY+UART-bit: NOT RUN")
  501. print("cad_root:", cad)
  502. print("cocotb_python:", py)
  503. print("missing_rtl:", ",".join(missing_rtl) or "none")
  504. return 2 if skip else 1
  505. if Path(sys.executable).resolve() != py.resolve():
  506. env = os.environ.copy()
  507. env["PROD2U_P4_COCOTB_PYTHON"] = str(py)
  508. env.setdefault("LIBPYTHON_LOC", "/opt/python-3.12/lib/libpython3.12.so.1.0")
  509. os.execve(str(py), [str(py), "-B", str(Path(__file__).resolve()), *sys.argv[1:]], env)
  510. work_root = REPO / "tmp"
  511. work_root.mkdir(parents=True, exist_ok=True)
  512. build = Path(tempfile.mkdtemp(prefix="hth-hthd-rtl-", dir=str(work_root)))
  513. shim = _shim_dir(build, py, cad)
  514. result = build / "result.txt"
  515. ready = build / "bridge.ready"
  516. startup = build / "startup.txt"
  517. sock_dir = Path(f"/tmp/hth-rtl-{os.getpid()}")
  518. sock_dir.mkdir(parents=True, exist_ok=True)
  519. (sock_dir / "observe").mkdir(exist_ok=True)
  520. (sock_dir / "control").mkdir(exist_ok=True)
  521. bridge = str(sock_dir / "uart.bridge")
  522. obs = str(sock_dir / "observe" / "observe.sock")
  523. ctl = str(sock_dir / "control" / "control.sock")
  524. cfg = build / "hthd.yaml"
  525. sim_dir = build / "sim"
  526. results_xml = build / "results.xml"
  527. master, slave = pty.openpty()
  528. _set_raw_clocal(master)
  529. try:
  530. _set_raw_clocal(slave)
  531. except termios.error:
  532. pass
  533. slave_name = os.ttyname(slave)
  534. _write_hthd_yaml(cfg, slave_name, obs, ctl, str(sock_dir))
  535. hthd_bin = build / "hthd"
  536. subprocess.check_call(
  537. ["go", "build", "-o", str(hthd_bin), "./cmd/hthd"],
  538. cwd=str(HOST),
  539. env={**os.environ, "CGO_ENABLED": "0", "GOTOOLCHAIN": os.environ.get("GOTOOLCHAIN", "local")},
  540. )
  541. env = {k: v for k, v in os.environ.items() if k not in OSS_CAD_POISON}
  542. libpython = os.environ.get("LIBPYTHON_LOC", "/opt/python-3.12/lib/libpython3.12.so.1.0")
  543. env["PATH"] = os.pathsep.join([str(py.parent), str(shim), "/usr/bin", "/bin"])
  544. env["LD_LIBRARY_PATH"] = "/opt/python-3.12/lib" + os.pathsep + env.get("LD_LIBRARY_PATH", "")
  545. env["PYTHONPATH"] = str(HERE) + os.pathsep + str(REPO)
  546. env["PYGPI_PYTHON_BIN"] = str(py)
  547. env["LIBPYTHON_LOC"] = libpython
  548. env["VIRTUAL_ENV"] = str(py.parent.parent)
  549. env["TEMP"] = str(build)
  550. env["TMP"] = str(build)
  551. env["TMPDIR"] = str(build)
  552. env["HTH_UART_BRIDGE"] = bridge
  553. env["HTH_RTL_RESULT"] = str(result)
  554. env["HTH_BRIDGE_READY"] = str(ready)
  555. env["HTH_STARTUP_FILE"] = str(startup)
  556. env["HTH_SIM_DIR"] = str(sim_dir)
  557. env["HTH_RESULTS_XML"] = str(results_xml)
  558. env["HTH_UART_LOG"] = os.environ.get("HTH_UART_LOG", str(build / "uart-bridge.log"))
  559. env["HTH_CLKS_PER_BIT"] = clks
  560. env["HTH_PRODUCTION_UART"] = os.environ.get("HTH_PRODUCTION_UART", "0")
  561. env["HTH_SIM_STOP"] = str(build / "sim.stop")
  562. env["PYTHONPATH"] = str(HERE) + os.pathsep + str(REPO)
  563. os.environ["PATH"] = env["PATH"]
  564. os.environ["PYGPI_PYTHON_BIN"] = str(py)
  565. os.environ["LIBPYTHON_LOC"] = env["LIBPYTHON_LOC"]
  566. os.environ["HTH_UART_LOG"] = env["HTH_UART_LOG"]
  567. Path(env["HTH_UART_LOG"]).write_text("", encoding="utf-8")
  568. srv = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
  569. srv.bind(bridge)
  570. srv.listen(1)
  571. srv.settimeout(300)
  572. sim = subprocess.Popen([str(py), "-B", str(HERE / "run_hthd_pty_rtl.py"), "--sim"], cwd=str(HERE), env=env)
  573. try:
  574. conn, _ = srv.accept()
  575. except socket.timeout:
  576. print("cocotb did not connect UART bridge", file=sys.stderr)
  577. sim.kill()
  578. return 1
  579. stop = threading.Event()
  580. if clks == "217":
  581. tap = UartTap(hold_s=45.0, max_hold_s=90.0)
  582. else:
  583. tap = UartTap(hold_s=10.0, max_hold_s=20.0)
  584. print(f"DELAYED_STARTUP_HOLD_S={tap.hold_s} MAX={tap.max_hold_s}", flush=True)
  585. threading.Thread(target=_shuttle, args=(master, conn, stop, tap), daemon=True).start()
  586. for _ in range(900):
  587. if ready.is_file():
  588. break
  589. if sim.poll() is not None:
  590. print("simulator exited before bridge ready", file=sys.stderr)
  591. return 1
  592. time.sleep(0.1)
  593. else:
  594. print("bridge ready file missing", file=sys.stderr)
  595. return 1
  596. hthd = None
  597. try:
  598. for _ in range(600 if clks == "217" else 240):
  599. if startup.is_file():
  600. break
  601. time.sleep(0.5)
  602. else:
  603. print("RTL startup_complete file missing", file=sys.stderr)
  604. return 1
  605. time.sleep(1.0)
  606. # Start hthd only after RTL calibration. Overlapping host UART with
  607. # Icarus bit-banging 5000-step seek makes MOTOR_STATUS miss the 28s
  608. # timeout and look like a reconnect loop. After hthd starts, the UART
  609. # tap holds MOTOR_STATUS.startup_complete=0 until hold_s (45s on 217
  610. # baud) and at least one MOTOR_STATUS rewrite, so production UART
  611. # proves no GET_TEMPERATURE during delayed startup.
  612. tap.mark_hthd_start()
  613. hthd = subprocess.Popen([str(hthd_bin), "--config", str(cfg)], cwd=str(HOST), env={**os.environ})
  614. for _ in range(200):
  615. if Path(obs).exists() and Path(ctl).exists():
  616. break
  617. time.sleep(0.1)
  618. else:
  619. print("hthd sockets not ready", file=sys.stderr)
  620. return 1
  621. try:
  622. _sdk_apply(obs, ctl)
  623. except Exception as exc:
  624. print("sdk apply failed:", exc, file=sys.stderr)
  625. deadline = time.time() + (300 if clks == "217" else 180)
  626. while time.time() < deadline:
  627. if result.is_file():
  628. text = result.read_text(encoding="utf-8")
  629. if text.startswith("PASS"):
  630. print(
  631. "DELAYED_STARTUP_HOLD_S",
  632. tap.hold_s,
  633. "GET_TEMP_DURING_HOLD",
  634. tap.get_temp_during_hold,
  635. "MOTOR_DURING_HOLD",
  636. tap.motor_req_during_hold,
  637. "GET_TEMP_AFTER",
  638. tap.get_temp_after,
  639. )
  640. if tap.get_temp_during_hold:
  641. print("GET_TEMPERATURE sent during delayed-startup hold", file=sys.stderr)
  642. return 1
  643. if tap.get_temp_after < 1:
  644. time.sleep(0.5)
  645. continue
  646. if tap.motor_req_during_hold == 0:
  647. print("no GET_MOTOR_STATUS during delayed-startup hold", file=sys.stderr)
  648. return 1
  649. try:
  650. _sdk_safe_resume(obs, ctl)
  651. except Exception as exc:
  652. print("sdk safe/resume failed:", exc, file=sys.stderr)
  653. return 1
  654. tag = "RTL_HTHD_PTY_PRODUCTION_UART_PASS" if clks == "217" else "RTL_HTHD_PTY_UART_BIT_PASS"
  655. print(tag)
  656. print("clks_per_bit", clks)
  657. print("hdl_top", hdl_top)
  658. print("RTL_DELAYED_STARTUP_PASS")
  659. print(text.strip())
  660. return 0
  661. if text.startswith("FAIL"):
  662. print(text, file=sys.stderr)
  663. return 1
  664. if sim.poll() is not None and (not result.is_file() or not result.read_text(encoding="utf-8").startswith("PASS")):
  665. print("simulator exited without PASS", file=sys.stderr)
  666. return 1
  667. time.sleep(0.5)
  668. print("timeout waiting for RTL PASS", file=sys.stderr)
  669. if result.is_file():
  670. print(result.read_text(encoding="utf-8"), file=sys.stderr)
  671. return 1
  672. finally:
  673. stop.set()
  674. try:
  675. Path(env["HTH_SIM_STOP"]).write_text("stop\n", encoding="utf-8")
  676. except Exception:
  677. pass
  678. if hthd is not None:
  679. hthd.send_signal(15)
  680. try:
  681. hthd.wait(timeout=8)
  682. except subprocess.TimeoutExpired:
  683. hthd.kill()
  684. sim.send_signal(15)
  685. try:
  686. sim.wait(timeout=5)
  687. except subprocess.TimeoutExpired:
  688. sim.kill()
  689. try:
  690. conn.close()
  691. except Exception:
  692. pass
  693. srv.close()
  694. os.close(master)
  695. os.close(slave)
  696. if __name__ == "__main__":
  697. raise SystemExit(main())