dut_and_hood_sim.py 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024
  1. #!/usr/bin/env python3
  2. """
  3. dut_and_hood_sim.py — Multi-Station Protocol-Authentic DUT Firmware & 6400 Hood HIL Simulator
  4. Pairs with `bmc_ssh_hil_sim` (C RMCP+ UDP :623 + SSHv2 TCP :2200 daemon) to emulate:
  5. 1. 4x Dual-Socket Intel GNR DDR5 Servers (`108_VD012` Hovsee & `101_VD013` CxmtDdrTest):
  6. - Full 7-stage boot & memory test pipeline:
  7. BIOS POST -> ICT Stage 1 -> DDR5 MRC Training (24 DIMMs) -> RMT -> Dual-CPU AMT ->
  8. ICT Stage 2 -> UEFI Interactive Shell -> 118.efi (MemTest86) + real UDP TFTP WRQ HTML upload
  9. - Hardware power event tracking from `bmc_ssh_hil_sim` (`\x01PWR:OFF|ON|RESET|CYCLE`)
  10. - Deterministic fault injection:
  11. * Silent hard hang at any stage (`training`, `rmt`, `amt`, `mt`, `uip1`, `uefi`) while
  12. TCP :2200 & BMC :623 remain 100% online (`hang_stage`, `hang_remaining_boots`)
  13. * Non-silent MemTest86 ANSI clock-redraw infinite loop (`mt_clock_loop`)
  14. * Stage memory/training errors (`inject_error_stage`)
  15. * Silent prompt hold across serial reconnect (`hold_prompt_echo_until_cr`) to test `\r` re-probe
  16. 2. 8x `os.openpty()` (`/dev/pts/*`) 6400 High-Temperature Hood v1.1 Controllers (4 backend + 4 Qt):
  17. - Strictly `/dev/pts/*` (NEVER touches `/dev/ttyUSB*`)
  18. - Full STM32 binary protocol (`AA 55 | CMD | LEN | Payload | CRC8-ATM`) + 1 Hz `0xF0` + `[SNAP]`
  19. - Tracks `0x01` target temp heating, `0x02` 24-ch temps, `0x0D` 8-ch CT7428 temps,
  20. and `0x08 00` cooling purge vs `0x08 01` keep-warm in an exact `cmd_history` audit ledger
  21. - Syncs 24-ch thermal physics back into `bmc_ssh_hil_sim` SDR sensors (`SET_TEMPS`)
  22. 3. HTTP JSON Control & Inspection API (`--http-port`, default `19198`).
  23. """
  24. import argparse
  25. import asyncio
  26. import json
  27. import os
  28. import socket
  29. import struct
  30. import sys
  31. import termios
  32. import time
  33. import tty
  34. from typing import Any, Dict, List, Optional, Tuple
  35. from aiohttp import web
  36. def now_ms() -> int:
  37. return int(time.time() * 1000)
  38. def crc8_atm(data: bytes) -> int:
  39. crc = 0
  40. for b in data:
  41. crc ^= b
  42. for _ in range(8):
  43. if crc & 0x80:
  44. crc = ((crc << 1) ^ 0x07) & 0xFF
  45. else:
  46. crc = (crc << 1) & 0xFF
  47. return crc
  48. def build_mcu_frame(cmd: int, payload: bytes = b"") -> bytes:
  49. head = bytes([0xAA, 0x55, cmd & 0xFF, len(payload) & 0xFF]) + payload
  50. return head + bytes([crc8_atm(head)])
  51. def send_bmc_ctrl_cmd(ctrl_host: str, ctrl_port: int, line: str) -> Dict[str, Any]:
  52. with socket.create_connection((ctrl_host, ctrl_port), timeout=2.0) as s:
  53. s.sendall((line.strip() + "\n").encode("utf-8"))
  54. chunks = []
  55. while True:
  56. data = s.recv(4096)
  57. if not data:
  58. break
  59. chunks.append(data)
  60. if b"\n" in data:
  61. break
  62. raw = b"".join(chunks).decode("utf-8", errors="replace").strip()
  63. return json.loads(raw) if raw else {}
  64. def tftp_wrq_upload_sync(host: str, port: int, filename: str, content: bytes, timeout_s: float = 2.5) -> bool:
  65. """Standard RFC 1350 / RFC 2348 UDP TFTP WRQ client for MemTest86 HTML report upload."""
  66. if port <= 0:
  67. return False
  68. sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  69. sock.settimeout(timeout_s)
  70. try:
  71. wrq = (
  72. struct.pack("!H", 2)
  73. + filename.encode("ascii")
  74. + b"\x00octet\x00blksize\x001024\x00"
  75. )
  76. sock.sendto(wrq, (host, port))
  77. pkt, server_tid_addr = sock.recvfrom(2048)
  78. if len(pkt) < 2:
  79. return False
  80. op = struct.unpack("!H", pkt[:2])[0]
  81. blksize = 512
  82. if op == 6: # OACK
  83. blksize = 1024
  84. elif op == 4: # ACK 0
  85. blksize = 512
  86. else:
  87. return False
  88. block = 1
  89. offset = 0
  90. while True:
  91. chunk = content[offset : offset + blksize]
  92. dpkt = struct.pack("!HH", 3, block & 0xFFFF) + chunk
  93. acked = False
  94. for _ in range(4):
  95. sock.sendto(dpkt, server_tid_addr)
  96. try:
  97. apkt, _ = sock.recvfrom(512)
  98. if len(apkt) >= 4:
  99. aop, ablk = struct.unpack("!HH", apkt[:4])
  100. if aop == 4 and ablk == (block & 0xFFFF):
  101. acked = True
  102. break
  103. except socket.timeout:
  104. continue
  105. if not acked:
  106. return False
  107. if len(chunk) < blksize:
  108. break
  109. offset += len(chunk)
  110. block += 1
  111. return True
  112. except Exception:
  113. return False
  114. finally:
  115. sock.close()
  116. class HoodPtsSim:
  117. """Protocol-authentic STM32 6400 High-Temperature Hood v1.1 on `/dev/pts/*`."""
  118. def __init__(self, hood_id: str, station_idx: int, bmc_ctrl: Tuple[str, int], sync_bmc: bool = True):
  119. self.hood_id = hood_id
  120. self.station_idx = station_idx
  121. self.bmc_ctrl = bmc_ctrl
  122. self.sync_bmc = sync_bmc
  123. master_fd, slave_fd = os.openpty()
  124. pts_name = os.ttyname(slave_fd)
  125. if "ttyUSB" in pts_name:
  126. os.close(master_fd)
  127. os.close(slave_fd)
  128. raise RuntimeError(f"Refusing unsafe serial path: {pts_name}")
  129. tty.setraw(master_fd)
  130. tty.setraw(slave_fd)
  131. attrs = termios.tcgetattr(slave_fd)
  132. attrs[4] = termios.B115200
  133. attrs[5] = termios.B115200
  134. termios.tcsetattr(slave_fd, termios.TCSANOW, attrs)
  135. os.set_blocking(master_fd, False)
  136. self.master_fd = master_fd
  137. self.slave_fd = slave_fd # Keep slave open so master never gets EIO before client opens it
  138. self.pts_path = pts_name
  139. self.rx_buf = bytearray()
  140. self.flags = 0x00 # bit1=preheat, bit2=pid, bit6=manual
  141. self.target_c = 0xFF
  142. self.f0_seq = 0
  143. self.cooling_purge = False
  144. self.ptc_pct = 0
  145. self.fan_pct = 20
  146. self.ssr_pct = 0
  147. self.ambient_c = 28.0
  148. self.chamber_c = [30.0] * 8
  149. self.dimm_c = [42.0 + (i % 4) for i in range(24)]
  150. self.preheat_started_s = 0.0
  151. self.preheat_done_notified = False
  152. self.cmd_history: List[Dict[str, Any]] = []
  153. self.running = True
  154. def close(self) -> None:
  155. self.running = False
  156. for fd_attr in ("master_fd", "slave_fd"):
  157. fd = getattr(self, fd_attr, -1)
  158. if fd >= 0:
  159. try:
  160. os.close(fd)
  161. except OSError:
  162. pass
  163. setattr(self, fd_attr, -1)
  164. def clear_history(self) -> None:
  165. self.cmd_history.clear()
  166. def _write_bytes(self, data: bytes) -> None:
  167. if self.master_fd < 0:
  168. return
  169. try:
  170. os.write(self.master_fd, data)
  171. except BlockingIOError:
  172. pass
  173. except OSError:
  174. pass
  175. def _on_readable(self) -> None:
  176. if self.master_fd < 0:
  177. return
  178. try:
  179. chunk = os.read(self.master_fd, 4096)
  180. except BlockingIOError:
  181. return
  182. except OSError:
  183. return
  184. if not chunk:
  185. return
  186. self.rx_buf.extend(chunk)
  187. self._drain_frames()
  188. def _drain_frames(self) -> None:
  189. while len(self.rx_buf) >= 5:
  190. head = -1
  191. for i in range(len(self.rx_buf) - 1):
  192. if self.rx_buf[i] == 0xAA and self.rx_buf[i + 1] == 0x55:
  193. head = i
  194. break
  195. if head < 0:
  196. del self.rx_buf[:-1]
  197. break
  198. if head > 0:
  199. del self.rx_buf[:head]
  200. if len(self.rx_buf) < 5:
  201. break
  202. plen = self.rx_buf[3]
  203. total = 5 + plen
  204. if len(self.rx_buf) < total:
  205. break
  206. frame = bytes(self.rx_buf[:total])
  207. del self.rx_buf[:total]
  208. if crc8_atm(frame[:-1]) == frame[-1]:
  209. self._handle_cmd(frame[2], frame[4:-1])
  210. def _handle_cmd(self, cmd: int, payload: bytes) -> None:
  211. ts = now_ms()
  212. if cmd == 0x01 and len(payload) >= 1:
  213. tgt = payload[0]
  214. self.target_c = tgt
  215. self.cooling_purge = False
  216. self.flags = 0x02 # preheating
  217. self.ptc_pct = 85
  218. self.fan_pct = 45
  219. self.ssr_pct = 80
  220. self.preheat_started_s = time.monotonic()
  221. self.preheat_done_notified = False
  222. self.cmd_history.append({"cmd": "0x01", "target_c": tgt, "ts_ms": ts})
  223. self._write_bytes(build_mcu_frame(0x81, bytes([0x01])))
  224. elif cmd == 0x02:
  225. vals = bytes([max(0, min(254, int(round(v)))) for v in self.dimm_c])
  226. self._write_bytes(build_mcu_frame(0x82, vals))
  227. elif cmd == 0x0D:
  228. vals = bytes([max(0, min(254, int(round(v)))) for v in self.chamber_c])
  229. self._write_bytes(build_mcu_frame(0x8D, vals))
  230. elif cmd == 0x08:
  231. mode_byte = payload[0] if len(payload) >= 1 else 0x00
  232. dissipate = (mode_byte == 0x00)
  233. self.flags = 0x00
  234. self.ptc_pct = 0
  235. self.ssr_pct = 0
  236. if dissipate:
  237. self.cooling_purge = True
  238. self.fan_pct = 100
  239. self.target_c = 0xFF
  240. else:
  241. self.cooling_purge = False
  242. self.fan_pct = 25
  243. self.cmd_history.append({
  244. "cmd": "0x08",
  245. "mode_byte": mode_byte,
  246. "dissipate": dissipate,
  247. "mode": "purge_cool" if dissipate else "keep_warm",
  248. "ts_ms": ts,
  249. })
  250. self._write_bytes(build_mcu_frame(0x88, bytes([0x01])))
  251. elif cmd == 0x04:
  252. # Bootloader / App version info (v1.1.0, product 0x6400)
  253. binfo = bytes([1, 1, 0, 12, 0x00, 0x64, 2, 0, 1, 0, 3, 0])
  254. self._write_bytes(build_mcu_frame(0x84, binfo))
  255. elif cmd == 0x09:
  256. uid = struct.pack("<III", 0x0034001E, 0x55485011, 0x20383400 + self.station_idx)
  257. self._write_bytes(build_mcu_frame(0x89, uid))
  258. elif cmd in (0x05, 0x06, 0x07, 0x0A, 0x0B):
  259. if cmd in (0x06, 0x07):
  260. self.flags = 0x04 # PID active
  261. self.cooling_purge = False
  262. elif cmd in (0x05, 0x0A):
  263. self.flags = 0x00
  264. self.ptc_pct = 0
  265. self.ssr_pct = 0
  266. self.cmd_history.append({"cmd": f"0x{cmd:02X}", "payload_hex": payload.hex(), "ts_ms": ts})
  267. self._write_bytes(build_mcu_frame(cmd | 0x80, bytes([0x01])))
  268. elif cmd == 0x0C:
  269. self.cmd_history.append({"cmd": "0x0C", "ts_ms": ts})
  270. self._write_bytes(build_mcu_frame(0x8C, b"OK P=2.6 I=0.125 D=0.04"))
  271. elif cmd == 0x46:
  272. self.flags = 0x40
  273. self.cmd_history.append({"cmd": "0x46", "ts_ms": ts})
  274. self._write_bytes(build_mcu_frame(0xC6, bytes([0x01])))
  275. async def physics_and_heartbeat_loop(self) -> None:
  276. loop = asyncio.get_running_loop()
  277. loop.add_reader(self.master_fd, self._on_readable)
  278. try:
  279. tick = 0
  280. while self.running:
  281. await asyncio.sleep(0.5)
  282. tick += 1
  283. # Auto-handoff preheat -> PID after 1.5s in simulation
  284. if (self.flags & 0x02) != 0 and (time.monotonic() - self.preheat_started_s) >= 1.5:
  285. self.flags = 0x04
  286. self.ptc_pct = 52
  287. self.ssr_pct = 45
  288. if not self.preheat_done_notified:
  289. self.preheat_done_notified = True
  290. self._write_bytes(build_mcu_frame(0x81, bytes([0x02])))
  291. if (self.flags & 0x06) != 0 and self.target_c != 0xFF:
  292. goal = float(self.target_c)
  293. for i in range(24):
  294. self.dimm_c[i] += (goal - self.dimm_c[i]) * 0.28 + ((i % 3) - 1) * 0.1
  295. for j in range(8):
  296. self.chamber_c[j] += ((goal - 4.0) - self.chamber_c[j]) * 0.25
  297. elif self.cooling_purge:
  298. for i in range(24):
  299. self.dimm_c[i] = max(self.ambient_c, self.dimm_c[i] - 3.5)
  300. for j in range(8):
  301. self.chamber_c[j] = max(self.ambient_c, self.chamber_c[j] - 4.0)
  302. else:
  303. for i in range(24):
  304. self.dimm_c[i] += (38.0 - self.dimm_c[i]) * 0.08
  305. # 1 Hz 0xF0 heartbeat + [SNAP] line
  306. if tick % 2 == 0:
  307. hb = build_mcu_frame(0xF0, bytes([self.flags, self.target_c, self.f0_seq & 0xFF]))
  308. self.f0_seq = (self.f0_seq + 1) & 0xFF
  309. snap = f"\r\n[SNAP] ptc={self.ptc_pct}% fan={self.fan_pct}% ssr={self.ssr_pct}%\r\n".encode("ascii")
  310. self._write_bytes(hb + snap)
  311. if self.sync_bmc:
  312. csv_temps = ",".join(str(max(20, min(115, int(round(x))))) for x in self.dimm_c)
  313. try:
  314. await asyncio.to_thread(
  315. send_bmc_ctrl_cmd,
  316. self.bmc_ctrl[0],
  317. self.bmc_ctrl[1],
  318. f"SET_TEMPS {self.station_idx} {csv_temps}",
  319. )
  320. except Exception:
  321. pass
  322. finally:
  323. if self.master_fd >= 0:
  324. try:
  325. loop.remove_reader(self.master_fd)
  326. except Exception:
  327. pass
  328. def snapshot(self) -> Dict[str, Any]:
  329. purge_events = [e for e in self.cmd_history if e.get("cmd") == "0x08" and e.get("dissipate") is True]
  330. heat_events = [e for e in self.cmd_history if e.get("cmd") == "0x01"]
  331. return {
  332. "hood_id": self.hood_id,
  333. "station_idx": self.station_idx,
  334. "pts_path": self.pts_path,
  335. "flags": self.flags,
  336. "target_c": None if self.target_c == 0xFF else self.target_c,
  337. "cooling_purge": self.cooling_purge,
  338. "fan_pct": self.fan_pct,
  339. "ptc_pct": self.ptc_pct,
  340. "avg_dimm_c": round(sum(self.dimm_c) / len(self.dimm_c), 1),
  341. "heat_cmd_count": len(heat_events),
  342. "purge_cool_count": len(purge_events),
  343. "cmd_history": list(self.cmd_history),
  344. }
  345. class DutStationSim:
  346. """Protocol-authentic GNR Dual-Socket BIOS / ICT / MRC / RMT / AMT / UEFI / 118.efi State Machine."""
  347. def __init__(
  348. self,
  349. idx: int,
  350. station_id: str,
  351. uart_port: int,
  352. tftp_host: str,
  353. tftp_port: int,
  354. fw_family: str = "hovsee",
  355. ):
  356. self.idx = idx
  357. self.station_id = station_id
  358. self.uart_port = uart_port
  359. self.tftp_host = tftp_host
  360. self.tftp_port = tftp_port
  361. self.fw_family = fw_family # "hovsee" (108_VD012) or "cxmt" (101_VD013)
  362. self.speed_scale = 1.0
  363. self.hang_stage = "" # "", "training", "rmt", "amt", "mt", "mt_clock_loop"
  364. self.hang_remaining_boots = 0
  365. self.inject_error_stage = "" # "", "training", "rmt", "amt", "mt"
  366. self.mt_tftp_report_enabled = True
  367. self.power_on = True
  368. self.stage = "uip1"
  369. self.hung_now = False
  370. self.hw_boot_count = 0
  371. self.prompt_str = ""
  372. self.uefi_cwd = "Shell> "
  373. self.amt_cpu = 0
  374. self.reader: Optional[asyncio.StreamReader] = None
  375. self.writer: Optional[asyncio.StreamWriter] = None
  376. self.boot_task: Optional[asyncio.Task] = None
  377. self.cmd_queue: asyncio.Queue[str] = asyncio.Queue()
  378. self.rx_line_buf = ""
  379. self.running = True
  380. self.tx_bytes_total = 0
  381. self.rx_commands: List[str] = []
  382. def _tag(self) -> str:
  383. return "Hovsee" if self.fw_family == "hovsee" else "CxmtDdrTest"
  384. def _amt_tag(self) -> str:
  385. return "AMT" if self.fw_family == "hovsee" else "AMEMDIAG"
  386. async def _tx(self, text: str) -> None:
  387. if not self.power_on or self.writer is None:
  388. return
  389. data = text.encode("utf-8", errors="replace")
  390. try:
  391. self.writer.write(data)
  392. await self.writer.drain()
  393. self.tx_bytes_total += len(data)
  394. except Exception:
  395. pass
  396. def _cancel_boot_task(self) -> None:
  397. if self.boot_task and not self.boot_task.done():
  398. self.boot_task.cancel()
  399. self.boot_task = None
  400. while not self.cmd_queue.empty():
  401. try:
  402. self.cmd_queue.get_nowait()
  403. except asyncio.QueueEmpty:
  404. break
  405. def trigger_power_boot(self, reason: str = "power_on") -> None:
  406. self._cancel_boot_task()
  407. self.power_on = True
  408. self.hung_now = False
  409. self.hw_boot_count += 1
  410. self.boot_task = asyncio.create_task(self._run_boot_pipeline(reason))
  411. def trigger_power_off(self) -> None:
  412. self._cancel_boot_task()
  413. self.power_on = False
  414. self.hung_now = False
  415. self.stage = "power_off"
  416. self.prompt_str = ""
  417. def _consume_hang_for_stage(self, stg: str) -> bool:
  418. if self.hang_stage == stg and self.hang_remaining_boots > 0:
  419. self.hang_remaining_boots -= 1
  420. self.hung_now = True
  421. return True
  422. return False
  423. async def _sleep_scaled(self, sec: float) -> None:
  424. await asyncio.sleep(max(0.01, sec * self.speed_scale))
  425. async def _wait_interactive_prompt(self, prompt: str) -> str:
  426. """Emit prompt (without trailing LF, matching real BIOS) and process commands until exit/launch."""
  427. self.prompt_str = prompt
  428. await self._tx(prompt)
  429. while self.running and self.power_on:
  430. cmd = await self.cmd_queue.get()
  431. stripped = cmd.strip()
  432. self.rx_commands.append(stripped)
  433. if len(self.rx_commands) > 100:
  434. self.rx_commands = self.rx_commands[-100:]
  435. # Empty Enter (`\r` prompt re-probe after serial reconnect or user Enter): re-echo prompt!
  436. if stripped == "":
  437. await self._tx("\r\n" + self.prompt_str)
  438. continue
  439. return stripped
  440. return ""
  441. async def _run_boot_pipeline(self, reason: str) -> None:
  442. try:
  443. tag = self._tag()
  444. atag = self._amt_tag()
  445. pfx = "HS" if self.fw_family == "hovsee" else "HD"
  446. # 1. Realistic hardware PSU + SEC POST delay (1.35s) after IPMI power-on/reset so
  447. # BMC `chassis power status == on` verification (~900ms) completes before BIOS UART output!
  448. self.stage = "boot"
  449. self.prompt_str = ""
  450. if reason in ("on", "reset", "cycle", "ac_restore"):
  451. await asyncio.sleep(1.35)
  452. else:
  453. await self._sleep_scaled(0.15)
  454. ver = "108_VD012" if self.fw_family == "hovsee" else "101_VD013"
  455. bios_tag = "HS_BIOS" if self.fw_family == "hovsee" else "SYS_BIOS"
  456. await self._tx(
  457. f"\r\n[{bios_tag}]Version: {ver}\r\n"
  458. f"Welcome to {tag}\r\n"
  459. f"[{tag}]Current stage is 1\r\n"
  460. f"[{tag}]Start UIP\r\n"
  461. )
  462. self.stage = "uip1"
  463. rmt_enabled = True
  464. uip1_prompt = f"[0][{tag}]Please input your command:"
  465. await self._tx(uip1_prompt)
  466. self.prompt_str = uip1_prompt
  467. while self.running and self.power_on:
  468. cmd = (await self.cmd_queue.get()).strip()
  469. self.rx_commands.append(cmd)
  470. if cmd == "":
  471. await self._tx("\r\n" + uip1_prompt)
  472. continue
  473. low = cmd.lower()
  474. if low in ("exit", "boot", "q", "quit"):
  475. await self._tx(f"{cmd}\r\n[{tag}]Exit UIP\r\n")
  476. self.prompt_str = ""
  477. break
  478. if "rmt disable" in low or "maskmain 48" in low:
  479. rmt_enabled = False
  480. elif "rmt enable" in low or "unmaskmain 48" in low:
  481. rmt_enabled = True
  482. await self._tx(f"{cmd}\r\n[0][{tag}] Set OK: {cmd}\r\n{uip1_prompt}")
  483. # 2. DDR5 MRC Training + 24-DIMM Inventory
  484. self.stage = "training"
  485. await self._tx(f"[{pfx}_StartMemTrain]\r\n")
  486. for cpu in range(2):
  487. for ch in range(12):
  488. await self._tx(f"[{pfx}_DRAM] N{cpu}.C{ch}.D0 DDR5 Present Size:65536\r\n")
  489. await self._sleep_scaled(0.06)
  490. if self._consume_hang_for_stage("training"):
  491. await self._tx(f"[{pfx}_BIOS][Training][ScktId: 0] Executing RxPerBitDeskew...\r\n")
  492. while self.running and self.power_on:
  493. await asyncio.sleep(1.0)
  494. return
  495. if self.inject_error_stage == "training":
  496. await self._tx("N0.C3.D0.R0 : Training Fail - No eye found\r\n")
  497. await self._tx(f"[{pfx}_EndMemTrain]\r\nMRC Done\r\n")
  498. await self._sleep_scaled(0.10)
  499. # 3. Rank Margin Tool (RMT)
  500. if not rmt_enabled:
  501. # Authentic 108_VD012 0-row wrapper output when RMT is disabled/masked
  502. await self._tx(f"[{pfx}_BIOS] Rank Margin Tool -- SUCCEEDED,Time=18 ms\r\n")
  503. await self._sleep_scaled(0.05)
  504. else:
  505. self.stage = "rmt"
  506. for cpu in range(2):
  507. await self._tx(f"START_RMT_N{cpu}\r\n")
  508. for ch in range(12):
  509. await self._tx(f"[{pfx}_RMTSensor] N{cpu}.C{ch}.D0 : {66 + (ch % 4)}.5\r\n")
  510. if cpu == 0 and ch == 5 and self._consume_hang_for_stage("rmt"):
  511. # Hard hang mid-RMT: TCP :2200 & BMC :623 stay alive, UART completely silent!
  512. while self.running and self.power_on:
  513. await asyncio.sleep(1.0)
  514. return
  515. if self.inject_error_stage == "rmt" and cpu == 0 and ch == 2:
  516. await self._tx("N0.C2.D0.R0 : 0 0 0 0 Critical Margin Error\r\n")
  517. else:
  518. await self._tx(f"N{cpu}.C{ch}.D0.R0 : -18 19 -17 18\r\n")
  519. await self._sleep_scaled(0.08)
  520. await self._tx(f"STOP_RMT_N{cpu}\r\n")
  521. # 4. Dual-Socket Advanced Memory Test (AMT / AMEMDIAG)
  522. self.stage = "amt"
  523. algo_tot = 24 if self.fw_family == "hovsee" else 19
  524. ver_banner = "AMT Version GNR-4.3.3" if self.fw_family == "hovsee" else "AMEMDIAG Version GNR-4.3.0"
  525. await self._tx(f"\r\n{ver_banner}\r\n{atag} Test Algo Count: {algo_tot}\r\n")
  526. for cpu in range(2):
  527. self.amt_cpu = cpu
  528. amt_prompt = f"[{cpu}][{atag} #]"
  529. self.prompt_str = amt_prompt
  530. await self._tx(amt_prompt)
  531. cpu_ran = False
  532. while self.running and self.power_on:
  533. cmd = (await self.cmd_queue.get()).strip()
  534. self.rx_commands.append(cmd)
  535. if cmd == "":
  536. await self._tx("\r\n" + amt_prompt)
  537. continue
  538. low = cmd.lower()
  539. if low in ("exit", "quit", "q"):
  540. await self._tx(f"{cmd}\r\n")
  541. self.prompt_str = ""
  542. break
  543. if low.startswith("amemdiag") or low.startswith("amt") or "start" in low:
  544. self.prompt_str = ""
  545. await self._tx(f"{cmd}\r\n{atag} Test Start\r\n")
  546. for aid in range(1, algo_tot + 1):
  547. await self._tx(f"[{cpu}][{atag} 1/1 1/1 {aid}/{algo_tot}] Algo #{aid} PASS\r\n")
  548. if cpu == 0 and aid == 6 and self._consume_hang_for_stage("amt"):
  549. while self.running and self.power_on:
  550. await asyncio.sleep(1.0)
  551. return
  552. if aid % 8 == 0:
  553. await self._sleep_scaled(0.05)
  554. if self.inject_error_stage == "amt" and cpu == 1:
  555. await self._tx(
  556. f"N1.C4.D0.R0.B11 : Data Compare Error\r\n"
  557. f"Error Address : 0x123456780\r\n"
  558. f"[{cpu}] Total Error Count: 1\r\n"
  559. f"[{cpu}] {atag} Test Result Summary: FAIL\r\n"
  560. )
  561. else:
  562. res_lbl = "Summary" if cpu == 1 else ""
  563. sep = " " if res_lbl else ""
  564. await self._tx(
  565. f"[{cpu}] Total Error Count: 0\r\n"
  566. f"[{cpu}] {atag} Test Result{sep}{res_lbl}: PASS\r\n"
  567. )
  568. cpu_ran = True
  569. self.prompt_str = amt_prompt
  570. await self._tx(amt_prompt)
  571. else:
  572. await self._tx(f"{cmd}\r\nOK\r\n{amt_prompt}")
  573. if cpu_ran:
  574. pass
  575. # 5. ICT Stage 2
  576. self.stage = "uip2"
  577. uip2_prompt = f"[0][{tag}]Please input your command:"
  578. await self._tx(f"\r\n[{tag}]Current stage is 2\r\n[{tag}]Stage2 UIP\r\n{uip2_prompt}")
  579. self.prompt_str = uip2_prompt
  580. while self.running and self.power_on:
  581. cmd = (await self.cmd_queue.get()).strip()
  582. self.rx_commands.append(cmd)
  583. if cmd == "":
  584. await self._tx("\r\n" + uip2_prompt)
  585. continue
  586. if cmd.lower() in ("exit", "boot", "q", "quit"):
  587. await self._tx(f"{cmd}\r\n[{tag}]Exit UIP\r\n0x90 : BDS Started\r\n")
  588. self.prompt_str = ""
  589. break
  590. await self._tx(f"{cmd}\r\n[0][{tag}] Stage2 OK\r\n{uip2_prompt}")
  591. # 6. UEFI Interactive Shell -> 7. MemTest86 (118.efi)
  592. self.stage = "uefi"
  593. self.uefi_cwd = "Shell> "
  594. await self._sleep_scaled(0.08)
  595. await self._tx(
  596. "\r\nUEFI Interactive Shell v2.2\r\n"
  597. "EDK II\r\n"
  598. "Mapping table\r\n"
  599. " FS0: Alias(s):HD0a0b:;BLK1:\r\n"
  600. " PciRoot(0x0)/Pci(0x14,0x0)/USB(0x0,0x0)\r\n"
  601. "Press ESC in 1 seconds to skip startup.nsh or any other key to continue.\r\n"
  602. "Shell> "
  603. )
  604. self.prompt_str = self.uefi_cwd
  605. while self.running and self.power_on:
  606. cmd = (await self.cmd_queue.get()).strip()
  607. self.rx_commands.append(cmd)
  608. if cmd == "":
  609. await self._tx("\r\n" + self.uefi_cwd)
  610. continue
  611. low = cmd.lower()
  612. if low.startswith("map"):
  613. await self._tx(
  614. f"{cmd}\r\nMapping table\r\n"
  615. f" FS0: Alias(s):HD0a0b:;BLK1:\r\n"
  616. f" PciRoot(0x0)/Pci(0x14,0x0)/USB(0x0,0x0)\r\n"
  617. f"{self.uefi_cwd}"
  618. )
  619. elif low in ("fs0:", "fs0:\\"):
  620. self.uefi_cwd = "FS0:\\> "
  621. self.prompt_str = self.uefi_cwd
  622. await self._tx(f"{cmd}\r\n{self.uefi_cwd}")
  623. elif low.startswith("cd ") and "efi" in low:
  624. self.uefi_cwd = "FS0:\\EFI\\> "
  625. self.prompt_str = self.uefi_cwd
  626. await self._tx(f"{cmd}\r\n{self.uefi_cwd}")
  627. elif low.startswith("ls ") and "118.efi" in low:
  628. if "fs0:" in low:
  629. await self._tx(
  630. f"{cmd}\r\nDirectory of: FS0:\\EFI\\\r\n"
  631. f"06/01/2026 12:00 1,245,184 118.efi\r\n"
  632. f" 1 File(s) 1,245,184 bytes\r\n"
  633. f" 0 Dir(s)\r\n"
  634. f"{self.uefi_cwd}"
  635. )
  636. else:
  637. await self._tx(f"{cmd}\r\nls: File Not Found\r\n{self.uefi_cwd}")
  638. elif low.startswith("ls "):
  639. await self._tx(f"{cmd}\r\nls: File Not Found\r\n{self.uefi_cwd}")
  640. elif low.startswith("echo ") or low.startswith("cp "):
  641. await self._tx(f"{cmd}\r\n{self.uefi_cwd}")
  642. elif "118.efi" in low or low.endswith(".efi"):
  643. await self._run_memtest86(cmd)
  644. if not self.power_on or self.hung_now:
  645. return
  646. self.stage = "uefi"
  647. self.prompt_str = self.uefi_cwd
  648. await self._tx(self.uefi_cwd)
  649. else:
  650. await self._tx(f"{cmd}\r\n{self.uefi_cwd}")
  651. except asyncio.CancelledError:
  652. return
  653. async def _run_memtest86(self, launch_cmd: str) -> None:
  654. self.stage = "mt"
  655. self.prompt_str = ""
  656. await self._tx(
  657. f"{launch_cmd}\r\n"
  658. f"Launching 118.efi\r\n"
  659. f"PassMark MemTest86 V11.1 Pro (64-bit)\r\n"
  660. f"Found configuration file: mt86.cfg\r\n"
  661. f"*** TEST SESSION - START ***\r\n"
  662. )
  663. if self._consume_hang_for_stage("mt_clock_loop"):
  664. # Infinite ANSI clock redraw loop: keeps updating last_rx_unix_ms without progressing!
  665. sec_counter = 0
  666. while self.running and self.power_on:
  667. sec_counter += 1
  668. mm, ss = divmod(sec_counter, 60)
  669. await self._tx(f"\x1b[2;60HElapsed: 00:{mm:02d}:{ss:02d}")
  670. await asyncio.sleep(0.25)
  671. return
  672. for tid in range(26):
  673. await self._tx(f"Running test #{tid} (Test: {tid}/26 {(tid * 100) // 26}%)\r\n")
  674. if tid == 3 and self._consume_hang_for_stage("mt"):
  675. while self.running and self.power_on:
  676. await asyncio.sleep(1.0)
  677. return
  678. if tid % 6 == 0:
  679. await self._sleep_scaled(0.05)
  680. is_fail = (self.inject_error_stage == "mt")
  681. rpt_name = f"MT86-{self.station_id}-{now_ms()}.html"
  682. if is_fail:
  683. await self._tx(
  684. "[Data Error] Test: 13 Addr: 0x2468ACE00 Expected: 0xFFFFFFFF Actual: 0xFFFFFFFE CPU0_DIMM_D0\r\n"
  685. "(Chan,Slot,Rank,Bank,Row,Col): (3,0,0,7,1024,64)\r\n"
  686. )
  687. if self.mt_tftp_report_enabled and self.tftp_port > 0:
  688. verdict_txt = "FAIL" if is_fail else "PASS"
  689. errs_cnt = 1 if is_fail else 0
  690. err_row = (
  691. "<tr><td>13</td><td>0x2468ACE00</td><td>CPU0_DIMM_D0</td><td>Rank 0 Bank 7</td></tr>"
  692. if is_fail
  693. else ""
  694. )
  695. html = (
  696. f"<html><head><title>MemTest86 Report {self.station_id}</title></head><body>"
  697. f"<h1>PassMark MemTest86 Report</h1>"
  698. f"<table><tr><td>Test Result</td><td>{verdict_txt}</td></tr>"
  699. f"<tr><td>Tests Passed</td><td>{25 if is_fail else 26}/26</td></tr>"
  700. f"<tr><td>Errors</td><td>{errs_cnt}</td></tr></table>"
  701. f"{err_row}</body></html>"
  702. ).encode("utf-8")
  703. await asyncio.to_thread(
  704. tftp_wrq_upload_sync, self.tftp_host, self.tftp_port, rpt_name, html
  705. )
  706. if is_fail:
  707. await self._tx(
  708. "Finished pass #1 (of 1) (total errors: 1)\r\n"
  709. "Test Result: FAIL\r\n"
  710. )
  711. else:
  712. await self._tx(
  713. "Tests Passed: 26/26\r\n"
  714. "Pass complete, no errors\r\n"
  715. "Test Result: PASS\r\n"
  716. )
  717. async def uart_client_loop(self) -> None:
  718. while self.running:
  719. try:
  720. reader, writer = await asyncio.open_connection("127.0.0.1", self.uart_port)
  721. self.reader = reader
  722. self.writer = writer
  723. if self.power_on and self.boot_task is None:
  724. self.trigger_power_boot("initial")
  725. while self.running:
  726. chunk = await reader.read(1024)
  727. if not chunk:
  728. break
  729. text = chunk.decode("utf-8", errors="replace")
  730. self._process_incoming_uart(text)
  731. except Exception:
  732. await asyncio.sleep(0.1)
  733. finally:
  734. if self.writer is not None:
  735. try:
  736. self.writer.close()
  737. except Exception:
  738. pass
  739. self.reader = None
  740. self.writer = None
  741. def _process_incoming_uart(self, text: str) -> None:
  742. # Handle embedded `\x01PWR:<EVENT>\n` control notifications from `bmc_ssh_hil_sim`
  743. idx = 0
  744. n = len(text)
  745. while idx < n:
  746. if text[idx] == "\x01" and text.startswith("\x01PWR:", idx):
  747. nl = text.find("\n", idx)
  748. if nl < 0:
  749. nl = n
  750. ev = text[idx + 5 : nl].strip()
  751. if ev == "OFF":
  752. self.trigger_power_off()
  753. elif ev in ("ON", "RESET", "CYCLE"):
  754. self.trigger_power_boot(ev.lower())
  755. idx = nl + 1
  756. continue
  757. ch = text[idx]
  758. idx += 1
  759. if ch in ("\r", "\n"):
  760. # Avoid double-triggering on CRLF pairs: only emit empty Enter if standalone `\r` or `\n`
  761. cmd = self.rx_line_buf
  762. self.rx_line_buf = ""
  763. if ch == "\n" and getattr(self, "_last_was_cr", False) and cmd == "":
  764. self._last_was_cr = False
  765. continue
  766. self._last_was_cr = (ch == "\r")
  767. if not self.hung_now:
  768. self.cmd_queue.put_nowait(cmd)
  769. else:
  770. self._last_was_cr = False
  771. self.rx_line_buf += ch
  772. def snapshot(self) -> Dict[str, Any]:
  773. return {
  774. "idx": self.idx,
  775. "station_id": self.station_id,
  776. "fw_family": self.fw_family,
  777. "power_on": self.power_on,
  778. "stage": self.stage,
  779. "hung_now": self.hung_now,
  780. "hw_boot_count": self.hw_boot_count,
  781. "hang_stage": self.hang_stage,
  782. "hang_remaining_boots": self.hang_remaining_boots,
  783. "inject_error_stage": self.inject_error_stage,
  784. "prompt_str": self.prompt_str,
  785. "tx_bytes_total": self.tx_bytes_total,
  786. "recent_rx_commands": self.rx_commands[-12:],
  787. }
  788. class HilClusterRuntime:
  789. def __init__(self, args: argparse.Namespace):
  790. self.args = args
  791. self.bmc_ctrl = (args.bmc_ctrl_host, args.bmc_ctrl_port)
  792. families = ["hovsee", "cxmt", "hovsee", "hovsee"]
  793. self.duts: List[DutStationSim] = [
  794. DutStationSim(
  795. idx=i,
  796. station_id=f"S{i + 1}",
  797. uart_port=args.uart_base + i,
  798. tftp_host=args.tftp_host,
  799. tftp_port=args.tftp_port,
  800. fw_family=families[i % len(families)],
  801. )
  802. for i in range(args.num_stations)
  803. ]
  804. # 4 backend ThermalMcuHub hoods + 4 Qt ComManager hoods (all /dev/pts/*)
  805. self.backend_hoods: List[HoodPtsSim] = [
  806. HoodPtsSim(f"backend-S{i + 1}", i, self.bmc_ctrl, sync_bmc=True)
  807. for i in range(args.num_stations)
  808. ]
  809. self.tasks: List[asyncio.Task] = []
  810. async def start(self) -> None:
  811. for d in self.duts:
  812. d.speed_scale = self.args.speed_scale
  813. self.tasks.append(asyncio.create_task(d.uart_client_loop()))
  814. for h in self.backend_hoods:
  815. self.tasks.append(asyncio.create_task(h.physics_and_heartbeat_loop()))
  816. async def stop(self) -> None:
  817. for d in self.duts:
  818. d.running = False
  819. d._cancel_boot_task()
  820. for h in self.backend_hoods:
  821. h.close()
  822. for t in self.tasks:
  823. t.cancel()
  824. async def handle_status(self, _req: web.Request) -> web.Response:
  825. bmc_st = await asyncio.to_thread(send_bmc_ctrl_cmd, self.bmc_ctrl[0], self.bmc_ctrl[1], "STATUS")
  826. return web.json_response({
  827. "ok": True,
  828. "bmc": bmc_st.get("stations", []),
  829. "duts": [d.snapshot() for d in self.duts],
  830. "backend_hoods": [h.snapshot() for h in self.backend_hoods],
  831. })
  832. async def handle_bmc_set_link(self, req: web.Request) -> web.Response:
  833. body = await req.json()
  834. idx = int(body["idx"])
  835. bmc_up = 1 if body.get("bmc_up", True) else 0
  836. serial_up = 1 if body.get("serial_up", True) else 0
  837. res = await asyncio.to_thread(
  838. send_bmc_ctrl_cmd, self.bmc_ctrl[0], self.bmc_ctrl[1], f"SET_LINK {idx} {bmc_up} {serial_up}"
  839. )
  840. return web.json_response(res)
  841. async def handle_bmc_set_power(self, req: web.Request) -> web.Response:
  842. body = await req.json()
  843. idx = int(body["idx"])
  844. pwr = 1 if body.get("power_on", True) else 0
  845. res = await asyncio.to_thread(
  846. send_bmc_ctrl_cmd, self.bmc_ctrl[0], self.bmc_ctrl[1], f"SET_POWER {idx} {pwr}"
  847. )
  848. if 0 <= idx < len(self.duts):
  849. if pwr == 0:
  850. self.duts[idx].trigger_power_off()
  851. elif not self.duts[idx].power_on:
  852. self.duts[idx].trigger_power_boot("ac_restore")
  853. return web.json_response(res)
  854. async def handle_dut_configure(self, req: web.Request) -> web.Response:
  855. body = await req.json()
  856. idx = int(body["idx"])
  857. dut = self.duts[idx]
  858. if "fw_family" in body:
  859. dut.fw_family = str(body["fw_family"])
  860. if "speed_scale" in body:
  861. dut.speed_scale = float(body["speed_scale"])
  862. if "hang_stage" in body:
  863. dut.hang_stage = str(body["hang_stage"])
  864. if "hang_remaining_boots" in body:
  865. dut.hang_remaining_boots = int(body["hang_remaining_boots"])
  866. if "inject_error_stage" in body:
  867. dut.inject_error_stage = str(body["inject_error_stage"])
  868. if "mt_tftp_report_enabled" in body:
  869. dut.mt_tftp_report_enabled = bool(body["mt_tftp_report_enabled"])
  870. return web.json_response({"ok": True, "dut": dut.snapshot()})
  871. async def handle_dut_trigger_boot(self, req: web.Request) -> web.Response:
  872. body = await req.json()
  873. idx = int(body["idx"])
  874. await asyncio.to_thread(send_bmc_ctrl_cmd, self.bmc_ctrl[0], self.bmc_ctrl[1], f"SET_POWER {idx} 1")
  875. self.duts[idx].trigger_power_boot(str(body.get("reason", "api_trigger")))
  876. return web.json_response({"ok": True, "dut": self.duts[idx].snapshot()})
  877. async def handle_hood_clear_history(self, req: web.Request) -> web.Response:
  878. body = await req.json()
  879. idx = body.get("idx")
  880. for i, h in enumerate(self.backend_hoods):
  881. if idx is None or int(idx) == i:
  882. h.clear_history()
  883. return web.json_response({"ok": True})
  884. async def async_main(args: argparse.Namespace) -> None:
  885. rt = HilClusterRuntime(args)
  886. await rt.start()
  887. app = web.Application()
  888. app.router.add_get("/api/status", rt.handle_status)
  889. app.router.add_post("/api/bmc/set_link", rt.handle_bmc_set_link)
  890. app.router.add_post("/api/bmc/set_power", rt.handle_bmc_set_power)
  891. app.router.add_post("/api/dut/configure", rt.handle_dut_configure)
  892. app.router.add_post("/api/dut/trigger_boot", rt.handle_dut_trigger_boot)
  893. app.router.add_post("/api/hood/clear_history", rt.handle_hood_clear_history)
  894. runner = web.AppRunner(app)
  895. await runner.setup()
  896. site = web.TCPSite(runner, "127.0.0.1", args.http_port)
  897. await site.start()
  898. manifest = {
  899. "http_ctrl": f"http://127.0.0.1:{args.http_port}",
  900. "backend_hood_pts": [h.pts_path for h in rt.backend_hoods],
  901. }
  902. if args.manifest_out:
  903. with open(args.manifest_out, "w", encoding="utf-8") as f:
  904. json.dump(manifest, f, indent=2)
  905. print("READY " + json.dumps(manifest), flush=True)
  906. stop_ev = asyncio.Event()
  907. try:
  908. await stop_ev.wait()
  909. except asyncio.CancelledError:
  910. pass
  911. finally:
  912. await rt.stop()
  913. await runner.cleanup()
  914. def main() -> None:
  915. p = argparse.ArgumentParser()
  916. p.add_argument("--http-port", type=int, default=19198)
  917. p.add_argument("--bmc-ctrl-host", default="127.0.0.1")
  918. p.add_argument("--bmc-ctrl-port", type=int, default=19199)
  919. p.add_argument("--uart-base", type=int, default=19200)
  920. p.add_argument("--num-stations", type=int, default=4)
  921. p.add_argument("--tftp-host", default="127.0.0.1")
  922. p.add_argument("--tftp-port", type=int, default=19069)
  923. p.add_argument("--speed-scale", type=float, default=0.3)
  924. p.add_argument("--manifest-out", default="")
  925. args = p.parse_args()
  926. try:
  927. asyncio.run(async_main(args))
  928. except KeyboardInterrupt:
  929. sys.exit(0)
  930. if __name__ == "__main__":
  931. main()