| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024 |
- #!/usr/bin/env python3
- """
- dut_and_hood_sim.py — Multi-Station Protocol-Authentic DUT Firmware & 6400 Hood HIL Simulator
- Pairs with `bmc_ssh_hil_sim` (C RMCP+ UDP :623 + SSHv2 TCP :2200 daemon) to emulate:
- 1. 4x Dual-Socket Intel GNR DDR5 Servers (`108_VD012` Hovsee & `101_VD013` CxmtDdrTest):
- - Full 7-stage boot & memory test pipeline:
- BIOS POST -> ICT Stage 1 -> DDR5 MRC Training (24 DIMMs) -> RMT -> Dual-CPU AMT ->
- ICT Stage 2 -> UEFI Interactive Shell -> 118.efi (MemTest86) + real UDP TFTP WRQ HTML upload
- - Hardware power event tracking from `bmc_ssh_hil_sim` (`\x01PWR:OFF|ON|RESET|CYCLE`)
- - Deterministic fault injection:
- * Silent hard hang at any stage (`training`, `rmt`, `amt`, `mt`, `uip1`, `uefi`) while
- TCP :2200 & BMC :623 remain 100% online (`hang_stage`, `hang_remaining_boots`)
- * Non-silent MemTest86 ANSI clock-redraw infinite loop (`mt_clock_loop`)
- * Stage memory/training errors (`inject_error_stage`)
- * Silent prompt hold across serial reconnect (`hold_prompt_echo_until_cr`) to test `\r` re-probe
- 2. 8x `os.openpty()` (`/dev/pts/*`) 6400 High-Temperature Hood v1.1 Controllers (4 backend + 4 Qt):
- - Strictly `/dev/pts/*` (NEVER touches `/dev/ttyUSB*`)
- - Full STM32 binary protocol (`AA 55 | CMD | LEN | Payload | CRC8-ATM`) + 1 Hz `0xF0` + `[SNAP]`
- - Tracks `0x01` target temp heating, `0x02` 24-ch temps, `0x0D` 8-ch CT7428 temps,
- and `0x08 00` cooling purge vs `0x08 01` keep-warm in an exact `cmd_history` audit ledger
- - Syncs 24-ch thermal physics back into `bmc_ssh_hil_sim` SDR sensors (`SET_TEMPS`)
- 3. HTTP JSON Control & Inspection API (`--http-port`, default `19198`).
- """
- import argparse
- import asyncio
- import json
- import os
- import socket
- import struct
- import sys
- import termios
- import time
- import tty
- from typing import Any, Dict, List, Optional, Tuple
- from aiohttp import web
- def now_ms() -> int:
- return int(time.time() * 1000)
- def crc8_atm(data: bytes) -> int:
- crc = 0
- for b in data:
- crc ^= b
- for _ in range(8):
- if crc & 0x80:
- crc = ((crc << 1) ^ 0x07) & 0xFF
- else:
- crc = (crc << 1) & 0xFF
- return crc
- def build_mcu_frame(cmd: int, payload: bytes = b"") -> bytes:
- head = bytes([0xAA, 0x55, cmd & 0xFF, len(payload) & 0xFF]) + payload
- return head + bytes([crc8_atm(head)])
- def send_bmc_ctrl_cmd(ctrl_host: str, ctrl_port: int, line: str) -> Dict[str, Any]:
- with socket.create_connection((ctrl_host, ctrl_port), timeout=2.0) as s:
- s.sendall((line.strip() + "\n").encode("utf-8"))
- chunks = []
- while True:
- data = s.recv(4096)
- if not data:
- break
- chunks.append(data)
- if b"\n" in data:
- break
- raw = b"".join(chunks).decode("utf-8", errors="replace").strip()
- return json.loads(raw) if raw else {}
- def tftp_wrq_upload_sync(host: str, port: int, filename: str, content: bytes, timeout_s: float = 2.5) -> bool:
- """Standard RFC 1350 / RFC 2348 UDP TFTP WRQ client for MemTest86 HTML report upload."""
- if port <= 0:
- return False
- sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
- sock.settimeout(timeout_s)
- try:
- wrq = (
- struct.pack("!H", 2)
- + filename.encode("ascii")
- + b"\x00octet\x00blksize\x001024\x00"
- )
- sock.sendto(wrq, (host, port))
- pkt, server_tid_addr = sock.recvfrom(2048)
- if len(pkt) < 2:
- return False
- op = struct.unpack("!H", pkt[:2])[0]
- blksize = 512
- if op == 6: # OACK
- blksize = 1024
- elif op == 4: # ACK 0
- blksize = 512
- else:
- return False
- block = 1
- offset = 0
- while True:
- chunk = content[offset : offset + blksize]
- dpkt = struct.pack("!HH", 3, block & 0xFFFF) + chunk
- acked = False
- for _ in range(4):
- sock.sendto(dpkt, server_tid_addr)
- try:
- apkt, _ = sock.recvfrom(512)
- if len(apkt) >= 4:
- aop, ablk = struct.unpack("!HH", apkt[:4])
- if aop == 4 and ablk == (block & 0xFFFF):
- acked = True
- break
- except socket.timeout:
- continue
- if not acked:
- return False
- if len(chunk) < blksize:
- break
- offset += len(chunk)
- block += 1
- return True
- except Exception:
- return False
- finally:
- sock.close()
- class HoodPtsSim:
- """Protocol-authentic STM32 6400 High-Temperature Hood v1.1 on `/dev/pts/*`."""
- def __init__(self, hood_id: str, station_idx: int, bmc_ctrl: Tuple[str, int], sync_bmc: bool = True):
- self.hood_id = hood_id
- self.station_idx = station_idx
- self.bmc_ctrl = bmc_ctrl
- self.sync_bmc = sync_bmc
- master_fd, slave_fd = os.openpty()
- pts_name = os.ttyname(slave_fd)
- if "ttyUSB" in pts_name:
- os.close(master_fd)
- os.close(slave_fd)
- raise RuntimeError(f"Refusing unsafe serial path: {pts_name}")
- tty.setraw(master_fd)
- tty.setraw(slave_fd)
- attrs = termios.tcgetattr(slave_fd)
- attrs[4] = termios.B115200
- attrs[5] = termios.B115200
- termios.tcsetattr(slave_fd, termios.TCSANOW, attrs)
- os.set_blocking(master_fd, False)
- self.master_fd = master_fd
- self.slave_fd = slave_fd # Keep slave open so master never gets EIO before client opens it
- self.pts_path = pts_name
- self.rx_buf = bytearray()
- self.flags = 0x00 # bit1=preheat, bit2=pid, bit6=manual
- self.target_c = 0xFF
- self.f0_seq = 0
- self.cooling_purge = False
- self.ptc_pct = 0
- self.fan_pct = 20
- self.ssr_pct = 0
- self.ambient_c = 28.0
- self.chamber_c = [30.0] * 8
- self.dimm_c = [42.0 + (i % 4) for i in range(24)]
- self.preheat_started_s = 0.0
- self.preheat_done_notified = False
- self.cmd_history: List[Dict[str, Any]] = []
- self.running = True
- def close(self) -> None:
- self.running = False
- for fd_attr in ("master_fd", "slave_fd"):
- fd = getattr(self, fd_attr, -1)
- if fd >= 0:
- try:
- os.close(fd)
- except OSError:
- pass
- setattr(self, fd_attr, -1)
- def clear_history(self) -> None:
- self.cmd_history.clear()
- def _write_bytes(self, data: bytes) -> None:
- if self.master_fd < 0:
- return
- try:
- os.write(self.master_fd, data)
- except BlockingIOError:
- pass
- except OSError:
- pass
- def _on_readable(self) -> None:
- if self.master_fd < 0:
- return
- try:
- chunk = os.read(self.master_fd, 4096)
- except BlockingIOError:
- return
- except OSError:
- return
- if not chunk:
- return
- self.rx_buf.extend(chunk)
- self._drain_frames()
- def _drain_frames(self) -> None:
- while len(self.rx_buf) >= 5:
- head = -1
- for i in range(len(self.rx_buf) - 1):
- if self.rx_buf[i] == 0xAA and self.rx_buf[i + 1] == 0x55:
- head = i
- break
- if head < 0:
- del self.rx_buf[:-1]
- break
- if head > 0:
- del self.rx_buf[:head]
- if len(self.rx_buf) < 5:
- break
- plen = self.rx_buf[3]
- total = 5 + plen
- if len(self.rx_buf) < total:
- break
- frame = bytes(self.rx_buf[:total])
- del self.rx_buf[:total]
- if crc8_atm(frame[:-1]) == frame[-1]:
- self._handle_cmd(frame[2], frame[4:-1])
- def _handle_cmd(self, cmd: int, payload: bytes) -> None:
- ts = now_ms()
- if cmd == 0x01 and len(payload) >= 1:
- tgt = payload[0]
- self.target_c = tgt
- self.cooling_purge = False
- self.flags = 0x02 # preheating
- self.ptc_pct = 85
- self.fan_pct = 45
- self.ssr_pct = 80
- self.preheat_started_s = time.monotonic()
- self.preheat_done_notified = False
- self.cmd_history.append({"cmd": "0x01", "target_c": tgt, "ts_ms": ts})
- self._write_bytes(build_mcu_frame(0x81, bytes([0x01])))
- elif cmd == 0x02:
- vals = bytes([max(0, min(254, int(round(v)))) for v in self.dimm_c])
- self._write_bytes(build_mcu_frame(0x82, vals))
- elif cmd == 0x0D:
- vals = bytes([max(0, min(254, int(round(v)))) for v in self.chamber_c])
- self._write_bytes(build_mcu_frame(0x8D, vals))
- elif cmd == 0x08:
- mode_byte = payload[0] if len(payload) >= 1 else 0x00
- dissipate = (mode_byte == 0x00)
- self.flags = 0x00
- self.ptc_pct = 0
- self.ssr_pct = 0
- if dissipate:
- self.cooling_purge = True
- self.fan_pct = 100
- self.target_c = 0xFF
- else:
- self.cooling_purge = False
- self.fan_pct = 25
- self.cmd_history.append({
- "cmd": "0x08",
- "mode_byte": mode_byte,
- "dissipate": dissipate,
- "mode": "purge_cool" if dissipate else "keep_warm",
- "ts_ms": ts,
- })
- self._write_bytes(build_mcu_frame(0x88, bytes([0x01])))
- elif cmd == 0x04:
- # Bootloader / App version info (v1.1.0, product 0x6400)
- binfo = bytes([1, 1, 0, 12, 0x00, 0x64, 2, 0, 1, 0, 3, 0])
- self._write_bytes(build_mcu_frame(0x84, binfo))
- elif cmd == 0x09:
- uid = struct.pack("<III", 0x0034001E, 0x55485011, 0x20383400 + self.station_idx)
- self._write_bytes(build_mcu_frame(0x89, uid))
- elif cmd in (0x05, 0x06, 0x07, 0x0A, 0x0B):
- if cmd in (0x06, 0x07):
- self.flags = 0x04 # PID active
- self.cooling_purge = False
- elif cmd in (0x05, 0x0A):
- self.flags = 0x00
- self.ptc_pct = 0
- self.ssr_pct = 0
- self.cmd_history.append({"cmd": f"0x{cmd:02X}", "payload_hex": payload.hex(), "ts_ms": ts})
- self._write_bytes(build_mcu_frame(cmd | 0x80, bytes([0x01])))
- elif cmd == 0x0C:
- self.cmd_history.append({"cmd": "0x0C", "ts_ms": ts})
- self._write_bytes(build_mcu_frame(0x8C, b"OK P=2.6 I=0.125 D=0.04"))
- elif cmd == 0x46:
- self.flags = 0x40
- self.cmd_history.append({"cmd": "0x46", "ts_ms": ts})
- self._write_bytes(build_mcu_frame(0xC6, bytes([0x01])))
- async def physics_and_heartbeat_loop(self) -> None:
- loop = asyncio.get_running_loop()
- loop.add_reader(self.master_fd, self._on_readable)
- try:
- tick = 0
- while self.running:
- await asyncio.sleep(0.5)
- tick += 1
- # Auto-handoff preheat -> PID after 1.5s in simulation
- if (self.flags & 0x02) != 0 and (time.monotonic() - self.preheat_started_s) >= 1.5:
- self.flags = 0x04
- self.ptc_pct = 52
- self.ssr_pct = 45
- if not self.preheat_done_notified:
- self.preheat_done_notified = True
- self._write_bytes(build_mcu_frame(0x81, bytes([0x02])))
- if (self.flags & 0x06) != 0 and self.target_c != 0xFF:
- goal = float(self.target_c)
- for i in range(24):
- self.dimm_c[i] += (goal - self.dimm_c[i]) * 0.28 + ((i % 3) - 1) * 0.1
- for j in range(8):
- self.chamber_c[j] += ((goal - 4.0) - self.chamber_c[j]) * 0.25
- elif self.cooling_purge:
- for i in range(24):
- self.dimm_c[i] = max(self.ambient_c, self.dimm_c[i] - 3.5)
- for j in range(8):
- self.chamber_c[j] = max(self.ambient_c, self.chamber_c[j] - 4.0)
- else:
- for i in range(24):
- self.dimm_c[i] += (38.0 - self.dimm_c[i]) * 0.08
- # 1 Hz 0xF0 heartbeat + [SNAP] line
- if tick % 2 == 0:
- hb = build_mcu_frame(0xF0, bytes([self.flags, self.target_c, self.f0_seq & 0xFF]))
- self.f0_seq = (self.f0_seq + 1) & 0xFF
- snap = f"\r\n[SNAP] ptc={self.ptc_pct}% fan={self.fan_pct}% ssr={self.ssr_pct}%\r\n".encode("ascii")
- self._write_bytes(hb + snap)
- if self.sync_bmc:
- csv_temps = ",".join(str(max(20, min(115, int(round(x))))) for x in self.dimm_c)
- try:
- await asyncio.to_thread(
- send_bmc_ctrl_cmd,
- self.bmc_ctrl[0],
- self.bmc_ctrl[1],
- f"SET_TEMPS {self.station_idx} {csv_temps}",
- )
- except Exception:
- pass
- finally:
- if self.master_fd >= 0:
- try:
- loop.remove_reader(self.master_fd)
- except Exception:
- pass
- def snapshot(self) -> Dict[str, Any]:
- purge_events = [e for e in self.cmd_history if e.get("cmd") == "0x08" and e.get("dissipate") is True]
- heat_events = [e for e in self.cmd_history if e.get("cmd") == "0x01"]
- return {
- "hood_id": self.hood_id,
- "station_idx": self.station_idx,
- "pts_path": self.pts_path,
- "flags": self.flags,
- "target_c": None if self.target_c == 0xFF else self.target_c,
- "cooling_purge": self.cooling_purge,
- "fan_pct": self.fan_pct,
- "ptc_pct": self.ptc_pct,
- "avg_dimm_c": round(sum(self.dimm_c) / len(self.dimm_c), 1),
- "heat_cmd_count": len(heat_events),
- "purge_cool_count": len(purge_events),
- "cmd_history": list(self.cmd_history),
- }
- class DutStationSim:
- """Protocol-authentic GNR Dual-Socket BIOS / ICT / MRC / RMT / AMT / UEFI / 118.efi State Machine."""
- def __init__(
- self,
- idx: int,
- station_id: str,
- uart_port: int,
- tftp_host: str,
- tftp_port: int,
- fw_family: str = "hovsee",
- ):
- self.idx = idx
- self.station_id = station_id
- self.uart_port = uart_port
- self.tftp_host = tftp_host
- self.tftp_port = tftp_port
- self.fw_family = fw_family # "hovsee" (108_VD012) or "cxmt" (101_VD013)
- self.speed_scale = 1.0
- self.hang_stage = "" # "", "training", "rmt", "amt", "mt", "mt_clock_loop"
- self.hang_remaining_boots = 0
- self.inject_error_stage = "" # "", "training", "rmt", "amt", "mt"
- self.mt_tftp_report_enabled = True
- self.power_on = True
- self.stage = "uip1"
- self.hung_now = False
- self.hw_boot_count = 0
- self.prompt_str = ""
- self.uefi_cwd = "Shell> "
- self.amt_cpu = 0
- self.reader: Optional[asyncio.StreamReader] = None
- self.writer: Optional[asyncio.StreamWriter] = None
- self.boot_task: Optional[asyncio.Task] = None
- self.cmd_queue: asyncio.Queue[str] = asyncio.Queue()
- self.rx_line_buf = ""
- self.running = True
- self.tx_bytes_total = 0
- self.rx_commands: List[str] = []
- def _tag(self) -> str:
- return "Hovsee" if self.fw_family == "hovsee" else "CxmtDdrTest"
- def _amt_tag(self) -> str:
- return "AMT" if self.fw_family == "hovsee" else "AMEMDIAG"
- async def _tx(self, text: str) -> None:
- if not self.power_on or self.writer is None:
- return
- data = text.encode("utf-8", errors="replace")
- try:
- self.writer.write(data)
- await self.writer.drain()
- self.tx_bytes_total += len(data)
- except Exception:
- pass
- def _cancel_boot_task(self) -> None:
- if self.boot_task and not self.boot_task.done():
- self.boot_task.cancel()
- self.boot_task = None
- while not self.cmd_queue.empty():
- try:
- self.cmd_queue.get_nowait()
- except asyncio.QueueEmpty:
- break
- def trigger_power_boot(self, reason: str = "power_on") -> None:
- self._cancel_boot_task()
- self.power_on = True
- self.hung_now = False
- self.hw_boot_count += 1
- self.boot_task = asyncio.create_task(self._run_boot_pipeline(reason))
- def trigger_power_off(self) -> None:
- self._cancel_boot_task()
- self.power_on = False
- self.hung_now = False
- self.stage = "power_off"
- self.prompt_str = ""
- def _consume_hang_for_stage(self, stg: str) -> bool:
- if self.hang_stage == stg and self.hang_remaining_boots > 0:
- self.hang_remaining_boots -= 1
- self.hung_now = True
- return True
- return False
- async def _sleep_scaled(self, sec: float) -> None:
- await asyncio.sleep(max(0.01, sec * self.speed_scale))
- async def _wait_interactive_prompt(self, prompt: str) -> str:
- """Emit prompt (without trailing LF, matching real BIOS) and process commands until exit/launch."""
- self.prompt_str = prompt
- await self._tx(prompt)
- while self.running and self.power_on:
- cmd = await self.cmd_queue.get()
- stripped = cmd.strip()
- self.rx_commands.append(stripped)
- if len(self.rx_commands) > 100:
- self.rx_commands = self.rx_commands[-100:]
- # Empty Enter (`\r` prompt re-probe after serial reconnect or user Enter): re-echo prompt!
- if stripped == "":
- await self._tx("\r\n" + self.prompt_str)
- continue
- return stripped
- return ""
- async def _run_boot_pipeline(self, reason: str) -> None:
- try:
- tag = self._tag()
- atag = self._amt_tag()
- pfx = "HS" if self.fw_family == "hovsee" else "HD"
- # 1. Realistic hardware PSU + SEC POST delay (1.35s) after IPMI power-on/reset so
- # BMC `chassis power status == on` verification (~900ms) completes before BIOS UART output!
- self.stage = "boot"
- self.prompt_str = ""
- if reason in ("on", "reset", "cycle", "ac_restore"):
- await asyncio.sleep(1.35)
- else:
- await self._sleep_scaled(0.15)
- ver = "108_VD012" if self.fw_family == "hovsee" else "101_VD013"
- bios_tag = "HS_BIOS" if self.fw_family == "hovsee" else "SYS_BIOS"
- await self._tx(
- f"\r\n[{bios_tag}]Version: {ver}\r\n"
- f"Welcome to {tag}\r\n"
- f"[{tag}]Current stage is 1\r\n"
- f"[{tag}]Start UIP\r\n"
- )
- self.stage = "uip1"
- rmt_enabled = True
- uip1_prompt = f"[0][{tag}]Please input your command:"
- await self._tx(uip1_prompt)
- self.prompt_str = uip1_prompt
- while self.running and self.power_on:
- cmd = (await self.cmd_queue.get()).strip()
- self.rx_commands.append(cmd)
- if cmd == "":
- await self._tx("\r\n" + uip1_prompt)
- continue
- low = cmd.lower()
- if low in ("exit", "boot", "q", "quit"):
- await self._tx(f"{cmd}\r\n[{tag}]Exit UIP\r\n")
- self.prompt_str = ""
- break
- if "rmt disable" in low or "maskmain 48" in low:
- rmt_enabled = False
- elif "rmt enable" in low or "unmaskmain 48" in low:
- rmt_enabled = True
- await self._tx(f"{cmd}\r\n[0][{tag}] Set OK: {cmd}\r\n{uip1_prompt}")
- # 2. DDR5 MRC Training + 24-DIMM Inventory
- self.stage = "training"
- await self._tx(f"[{pfx}_StartMemTrain]\r\n")
- for cpu in range(2):
- for ch in range(12):
- await self._tx(f"[{pfx}_DRAM] N{cpu}.C{ch}.D0 DDR5 Present Size:65536\r\n")
- await self._sleep_scaled(0.06)
- if self._consume_hang_for_stage("training"):
- await self._tx(f"[{pfx}_BIOS][Training][ScktId: 0] Executing RxPerBitDeskew...\r\n")
- while self.running and self.power_on:
- await asyncio.sleep(1.0)
- return
- if self.inject_error_stage == "training":
- await self._tx("N0.C3.D0.R0 : Training Fail - No eye found\r\n")
- await self._tx(f"[{pfx}_EndMemTrain]\r\nMRC Done\r\n")
- await self._sleep_scaled(0.10)
- # 3. Rank Margin Tool (RMT)
- if not rmt_enabled:
- # Authentic 108_VD012 0-row wrapper output when RMT is disabled/masked
- await self._tx(f"[{pfx}_BIOS] Rank Margin Tool -- SUCCEEDED,Time=18 ms\r\n")
- await self._sleep_scaled(0.05)
- else:
- self.stage = "rmt"
- for cpu in range(2):
- await self._tx(f"START_RMT_N{cpu}\r\n")
- for ch in range(12):
- await self._tx(f"[{pfx}_RMTSensor] N{cpu}.C{ch}.D0 : {66 + (ch % 4)}.5\r\n")
- if cpu == 0 and ch == 5 and self._consume_hang_for_stage("rmt"):
- # Hard hang mid-RMT: TCP :2200 & BMC :623 stay alive, UART completely silent!
- while self.running and self.power_on:
- await asyncio.sleep(1.0)
- return
- if self.inject_error_stage == "rmt" and cpu == 0 and ch == 2:
- await self._tx("N0.C2.D0.R0 : 0 0 0 0 Critical Margin Error\r\n")
- else:
- await self._tx(f"N{cpu}.C{ch}.D0.R0 : -18 19 -17 18\r\n")
- await self._sleep_scaled(0.08)
- await self._tx(f"STOP_RMT_N{cpu}\r\n")
- # 4. Dual-Socket Advanced Memory Test (AMT / AMEMDIAG)
- self.stage = "amt"
- algo_tot = 24 if self.fw_family == "hovsee" else 19
- ver_banner = "AMT Version GNR-4.3.3" if self.fw_family == "hovsee" else "AMEMDIAG Version GNR-4.3.0"
- await self._tx(f"\r\n{ver_banner}\r\n{atag} Test Algo Count: {algo_tot}\r\n")
- for cpu in range(2):
- self.amt_cpu = cpu
- amt_prompt = f"[{cpu}][{atag} #]"
- self.prompt_str = amt_prompt
- await self._tx(amt_prompt)
- cpu_ran = False
- while self.running and self.power_on:
- cmd = (await self.cmd_queue.get()).strip()
- self.rx_commands.append(cmd)
- if cmd == "":
- await self._tx("\r\n" + amt_prompt)
- continue
- low = cmd.lower()
- if low in ("exit", "quit", "q"):
- await self._tx(f"{cmd}\r\n")
- self.prompt_str = ""
- break
- if low.startswith("amemdiag") or low.startswith("amt") or "start" in low:
- self.prompt_str = ""
- await self._tx(f"{cmd}\r\n{atag} Test Start\r\n")
- for aid in range(1, algo_tot + 1):
- await self._tx(f"[{cpu}][{atag} 1/1 1/1 {aid}/{algo_tot}] Algo #{aid} PASS\r\n")
- if cpu == 0 and aid == 6 and self._consume_hang_for_stage("amt"):
- while self.running and self.power_on:
- await asyncio.sleep(1.0)
- return
- if aid % 8 == 0:
- await self._sleep_scaled(0.05)
- if self.inject_error_stage == "amt" and cpu == 1:
- await self._tx(
- f"N1.C4.D0.R0.B11 : Data Compare Error\r\n"
- f"Error Address : 0x123456780\r\n"
- f"[{cpu}] Total Error Count: 1\r\n"
- f"[{cpu}] {atag} Test Result Summary: FAIL\r\n"
- )
- else:
- res_lbl = "Summary" if cpu == 1 else ""
- sep = " " if res_lbl else ""
- await self._tx(
- f"[{cpu}] Total Error Count: 0\r\n"
- f"[{cpu}] {atag} Test Result{sep}{res_lbl}: PASS\r\n"
- )
- cpu_ran = True
- self.prompt_str = amt_prompt
- await self._tx(amt_prompt)
- else:
- await self._tx(f"{cmd}\r\nOK\r\n{amt_prompt}")
- if cpu_ran:
- pass
- # 5. ICT Stage 2
- self.stage = "uip2"
- uip2_prompt = f"[0][{tag}]Please input your command:"
- await self._tx(f"\r\n[{tag}]Current stage is 2\r\n[{tag}]Stage2 UIP\r\n{uip2_prompt}")
- self.prompt_str = uip2_prompt
- while self.running and self.power_on:
- cmd = (await self.cmd_queue.get()).strip()
- self.rx_commands.append(cmd)
- if cmd == "":
- await self._tx("\r\n" + uip2_prompt)
- continue
- if cmd.lower() in ("exit", "boot", "q", "quit"):
- await self._tx(f"{cmd}\r\n[{tag}]Exit UIP\r\n0x90 : BDS Started\r\n")
- self.prompt_str = ""
- break
- await self._tx(f"{cmd}\r\n[0][{tag}] Stage2 OK\r\n{uip2_prompt}")
- # 6. UEFI Interactive Shell -> 7. MemTest86 (118.efi)
- self.stage = "uefi"
- self.uefi_cwd = "Shell> "
- await self._sleep_scaled(0.08)
- await self._tx(
- "\r\nUEFI Interactive Shell v2.2\r\n"
- "EDK II\r\n"
- "Mapping table\r\n"
- " FS0: Alias(s):HD0a0b:;BLK1:\r\n"
- " PciRoot(0x0)/Pci(0x14,0x0)/USB(0x0,0x0)\r\n"
- "Press ESC in 1 seconds to skip startup.nsh or any other key to continue.\r\n"
- "Shell> "
- )
- self.prompt_str = self.uefi_cwd
- while self.running and self.power_on:
- cmd = (await self.cmd_queue.get()).strip()
- self.rx_commands.append(cmd)
- if cmd == "":
- await self._tx("\r\n" + self.uefi_cwd)
- continue
- low = cmd.lower()
- if low.startswith("map"):
- await self._tx(
- f"{cmd}\r\nMapping table\r\n"
- f" FS0: Alias(s):HD0a0b:;BLK1:\r\n"
- f" PciRoot(0x0)/Pci(0x14,0x0)/USB(0x0,0x0)\r\n"
- f"{self.uefi_cwd}"
- )
- elif low in ("fs0:", "fs0:\\"):
- self.uefi_cwd = "FS0:\\> "
- self.prompt_str = self.uefi_cwd
- await self._tx(f"{cmd}\r\n{self.uefi_cwd}")
- elif low.startswith("cd ") and "efi" in low:
- self.uefi_cwd = "FS0:\\EFI\\> "
- self.prompt_str = self.uefi_cwd
- await self._tx(f"{cmd}\r\n{self.uefi_cwd}")
- elif low.startswith("ls ") and "118.efi" in low:
- if "fs0:" in low:
- await self._tx(
- f"{cmd}\r\nDirectory of: FS0:\\EFI\\\r\n"
- f"06/01/2026 12:00 1,245,184 118.efi\r\n"
- f" 1 File(s) 1,245,184 bytes\r\n"
- f" 0 Dir(s)\r\n"
- f"{self.uefi_cwd}"
- )
- else:
- await self._tx(f"{cmd}\r\nls: File Not Found\r\n{self.uefi_cwd}")
- elif low.startswith("ls "):
- await self._tx(f"{cmd}\r\nls: File Not Found\r\n{self.uefi_cwd}")
- elif low.startswith("echo ") or low.startswith("cp "):
- await self._tx(f"{cmd}\r\n{self.uefi_cwd}")
- elif "118.efi" in low or low.endswith(".efi"):
- await self._run_memtest86(cmd)
- if not self.power_on or self.hung_now:
- return
- self.stage = "uefi"
- self.prompt_str = self.uefi_cwd
- await self._tx(self.uefi_cwd)
- else:
- await self._tx(f"{cmd}\r\n{self.uefi_cwd}")
- except asyncio.CancelledError:
- return
- async def _run_memtest86(self, launch_cmd: str) -> None:
- self.stage = "mt"
- self.prompt_str = ""
- await self._tx(
- f"{launch_cmd}\r\n"
- f"Launching 118.efi\r\n"
- f"PassMark MemTest86 V11.1 Pro (64-bit)\r\n"
- f"Found configuration file: mt86.cfg\r\n"
- f"*** TEST SESSION - START ***\r\n"
- )
- if self._consume_hang_for_stage("mt_clock_loop"):
- # Infinite ANSI clock redraw loop: keeps updating last_rx_unix_ms without progressing!
- sec_counter = 0
- while self.running and self.power_on:
- sec_counter += 1
- mm, ss = divmod(sec_counter, 60)
- await self._tx(f"\x1b[2;60HElapsed: 00:{mm:02d}:{ss:02d}")
- await asyncio.sleep(0.25)
- return
- for tid in range(26):
- await self._tx(f"Running test #{tid} (Test: {tid}/26 {(tid * 100) // 26}%)\r\n")
- if tid == 3 and self._consume_hang_for_stage("mt"):
- while self.running and self.power_on:
- await asyncio.sleep(1.0)
- return
- if tid % 6 == 0:
- await self._sleep_scaled(0.05)
- is_fail = (self.inject_error_stage == "mt")
- rpt_name = f"MT86-{self.station_id}-{now_ms()}.html"
- if is_fail:
- await self._tx(
- "[Data Error] Test: 13 Addr: 0x2468ACE00 Expected: 0xFFFFFFFF Actual: 0xFFFFFFFE CPU0_DIMM_D0\r\n"
- "(Chan,Slot,Rank,Bank,Row,Col): (3,0,0,7,1024,64)\r\n"
- )
- if self.mt_tftp_report_enabled and self.tftp_port > 0:
- verdict_txt = "FAIL" if is_fail else "PASS"
- errs_cnt = 1 if is_fail else 0
- err_row = (
- "<tr><td>13</td><td>0x2468ACE00</td><td>CPU0_DIMM_D0</td><td>Rank 0 Bank 7</td></tr>"
- if is_fail
- else ""
- )
- html = (
- f"<html><head><title>MemTest86 Report {self.station_id}</title></head><body>"
- f"<h1>PassMark MemTest86 Report</h1>"
- f"<table><tr><td>Test Result</td><td>{verdict_txt}</td></tr>"
- f"<tr><td>Tests Passed</td><td>{25 if is_fail else 26}/26</td></tr>"
- f"<tr><td>Errors</td><td>{errs_cnt}</td></tr></table>"
- f"{err_row}</body></html>"
- ).encode("utf-8")
- await asyncio.to_thread(
- tftp_wrq_upload_sync, self.tftp_host, self.tftp_port, rpt_name, html
- )
- if is_fail:
- await self._tx(
- "Finished pass #1 (of 1) (total errors: 1)\r\n"
- "Test Result: FAIL\r\n"
- )
- else:
- await self._tx(
- "Tests Passed: 26/26\r\n"
- "Pass complete, no errors\r\n"
- "Test Result: PASS\r\n"
- )
- async def uart_client_loop(self) -> None:
- while self.running:
- try:
- reader, writer = await asyncio.open_connection("127.0.0.1", self.uart_port)
- self.reader = reader
- self.writer = writer
- if self.power_on and self.boot_task is None:
- self.trigger_power_boot("initial")
- while self.running:
- chunk = await reader.read(1024)
- if not chunk:
- break
- text = chunk.decode("utf-8", errors="replace")
- self._process_incoming_uart(text)
- except Exception:
- await asyncio.sleep(0.1)
- finally:
- if self.writer is not None:
- try:
- self.writer.close()
- except Exception:
- pass
- self.reader = None
- self.writer = None
- def _process_incoming_uart(self, text: str) -> None:
- # Handle embedded `\x01PWR:<EVENT>\n` control notifications from `bmc_ssh_hil_sim`
- idx = 0
- n = len(text)
- while idx < n:
- if text[idx] == "\x01" and text.startswith("\x01PWR:", idx):
- nl = text.find("\n", idx)
- if nl < 0:
- nl = n
- ev = text[idx + 5 : nl].strip()
- if ev == "OFF":
- self.trigger_power_off()
- elif ev in ("ON", "RESET", "CYCLE"):
- self.trigger_power_boot(ev.lower())
- idx = nl + 1
- continue
- ch = text[idx]
- idx += 1
- if ch in ("\r", "\n"):
- # Avoid double-triggering on CRLF pairs: only emit empty Enter if standalone `\r` or `\n`
- cmd = self.rx_line_buf
- self.rx_line_buf = ""
- if ch == "\n" and getattr(self, "_last_was_cr", False) and cmd == "":
- self._last_was_cr = False
- continue
- self._last_was_cr = (ch == "\r")
- if not self.hung_now:
- self.cmd_queue.put_nowait(cmd)
- else:
- self._last_was_cr = False
- self.rx_line_buf += ch
- def snapshot(self) -> Dict[str, Any]:
- return {
- "idx": self.idx,
- "station_id": self.station_id,
- "fw_family": self.fw_family,
- "power_on": self.power_on,
- "stage": self.stage,
- "hung_now": self.hung_now,
- "hw_boot_count": self.hw_boot_count,
- "hang_stage": self.hang_stage,
- "hang_remaining_boots": self.hang_remaining_boots,
- "inject_error_stage": self.inject_error_stage,
- "prompt_str": self.prompt_str,
- "tx_bytes_total": self.tx_bytes_total,
- "recent_rx_commands": self.rx_commands[-12:],
- }
- class HilClusterRuntime:
- def __init__(self, args: argparse.Namespace):
- self.args = args
- self.bmc_ctrl = (args.bmc_ctrl_host, args.bmc_ctrl_port)
- families = ["hovsee", "cxmt", "hovsee", "hovsee"]
- self.duts: List[DutStationSim] = [
- DutStationSim(
- idx=i,
- station_id=f"S{i + 1}",
- uart_port=args.uart_base + i,
- tftp_host=args.tftp_host,
- tftp_port=args.tftp_port,
- fw_family=families[i % len(families)],
- )
- for i in range(args.num_stations)
- ]
- # 4 backend ThermalMcuHub hoods + 4 Qt ComManager hoods (all /dev/pts/*)
- self.backend_hoods: List[HoodPtsSim] = [
- HoodPtsSim(f"backend-S{i + 1}", i, self.bmc_ctrl, sync_bmc=True)
- for i in range(args.num_stations)
- ]
- self.tasks: List[asyncio.Task] = []
- async def start(self) -> None:
- for d in self.duts:
- d.speed_scale = self.args.speed_scale
- self.tasks.append(asyncio.create_task(d.uart_client_loop()))
- for h in self.backend_hoods:
- self.tasks.append(asyncio.create_task(h.physics_and_heartbeat_loop()))
- async def stop(self) -> None:
- for d in self.duts:
- d.running = False
- d._cancel_boot_task()
- for h in self.backend_hoods:
- h.close()
- for t in self.tasks:
- t.cancel()
- async def handle_status(self, _req: web.Request) -> web.Response:
- bmc_st = await asyncio.to_thread(send_bmc_ctrl_cmd, self.bmc_ctrl[0], self.bmc_ctrl[1], "STATUS")
- return web.json_response({
- "ok": True,
- "bmc": bmc_st.get("stations", []),
- "duts": [d.snapshot() for d in self.duts],
- "backend_hoods": [h.snapshot() for h in self.backend_hoods],
- })
- async def handle_bmc_set_link(self, req: web.Request) -> web.Response:
- body = await req.json()
- idx = int(body["idx"])
- bmc_up = 1 if body.get("bmc_up", True) else 0
- serial_up = 1 if body.get("serial_up", True) else 0
- res = await asyncio.to_thread(
- send_bmc_ctrl_cmd, self.bmc_ctrl[0], self.bmc_ctrl[1], f"SET_LINK {idx} {bmc_up} {serial_up}"
- )
- return web.json_response(res)
- async def handle_bmc_set_power(self, req: web.Request) -> web.Response:
- body = await req.json()
- idx = int(body["idx"])
- pwr = 1 if body.get("power_on", True) else 0
- res = await asyncio.to_thread(
- send_bmc_ctrl_cmd, self.bmc_ctrl[0], self.bmc_ctrl[1], f"SET_POWER {idx} {pwr}"
- )
- if 0 <= idx < len(self.duts):
- if pwr == 0:
- self.duts[idx].trigger_power_off()
- elif not self.duts[idx].power_on:
- self.duts[idx].trigger_power_boot("ac_restore")
- return web.json_response(res)
- async def handle_dut_configure(self, req: web.Request) -> web.Response:
- body = await req.json()
- idx = int(body["idx"])
- dut = self.duts[idx]
- if "fw_family" in body:
- dut.fw_family = str(body["fw_family"])
- if "speed_scale" in body:
- dut.speed_scale = float(body["speed_scale"])
- if "hang_stage" in body:
- dut.hang_stage = str(body["hang_stage"])
- if "hang_remaining_boots" in body:
- dut.hang_remaining_boots = int(body["hang_remaining_boots"])
- if "inject_error_stage" in body:
- dut.inject_error_stage = str(body["inject_error_stage"])
- if "mt_tftp_report_enabled" in body:
- dut.mt_tftp_report_enabled = bool(body["mt_tftp_report_enabled"])
- return web.json_response({"ok": True, "dut": dut.snapshot()})
- async def handle_dut_trigger_boot(self, req: web.Request) -> web.Response:
- body = await req.json()
- idx = int(body["idx"])
- await asyncio.to_thread(send_bmc_ctrl_cmd, self.bmc_ctrl[0], self.bmc_ctrl[1], f"SET_POWER {idx} 1")
- self.duts[idx].trigger_power_boot(str(body.get("reason", "api_trigger")))
- return web.json_response({"ok": True, "dut": self.duts[idx].snapshot()})
- async def handle_hood_clear_history(self, req: web.Request) -> web.Response:
- body = await req.json()
- idx = body.get("idx")
- for i, h in enumerate(self.backend_hoods):
- if idx is None or int(idx) == i:
- h.clear_history()
- return web.json_response({"ok": True})
- async def async_main(args: argparse.Namespace) -> None:
- rt = HilClusterRuntime(args)
- await rt.start()
- app = web.Application()
- app.router.add_get("/api/status", rt.handle_status)
- app.router.add_post("/api/bmc/set_link", rt.handle_bmc_set_link)
- app.router.add_post("/api/bmc/set_power", rt.handle_bmc_set_power)
- app.router.add_post("/api/dut/configure", rt.handle_dut_configure)
- app.router.add_post("/api/dut/trigger_boot", rt.handle_dut_trigger_boot)
- app.router.add_post("/api/hood/clear_history", rt.handle_hood_clear_history)
- runner = web.AppRunner(app)
- await runner.setup()
- site = web.TCPSite(runner, "127.0.0.1", args.http_port)
- await site.start()
- manifest = {
- "http_ctrl": f"http://127.0.0.1:{args.http_port}",
- "backend_hood_pts": [h.pts_path for h in rt.backend_hoods],
- }
- if args.manifest_out:
- with open(args.manifest_out, "w", encoding="utf-8") as f:
- json.dump(manifest, f, indent=2)
- print("READY " + json.dumps(manifest), flush=True)
- stop_ev = asyncio.Event()
- try:
- await stop_ev.wait()
- except asyncio.CancelledError:
- pass
- finally:
- await rt.stop()
- await runner.cleanup()
- def main() -> None:
- p = argparse.ArgumentParser()
- p.add_argument("--http-port", type=int, default=19198)
- p.add_argument("--bmc-ctrl-host", default="127.0.0.1")
- p.add_argument("--bmc-ctrl-port", type=int, default=19199)
- p.add_argument("--uart-base", type=int, default=19200)
- p.add_argument("--num-stations", type=int, default=4)
- p.add_argument("--tftp-host", default="127.0.0.1")
- p.add_argument("--tftp-port", type=int, default=19069)
- p.add_argument("--speed-scale", type=float, default=0.3)
- p.add_argument("--manifest-out", default="")
- args = p.parse_args()
- try:
- asyncio.run(async_main(args))
- except KeyboardInterrupt:
- sys.exit(0)
- if __name__ == "__main__":
- main()
|