thermal_6400_uart.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  1. """Shared real-bit UART helpers for the 6400 cocotb integration tests."""
  2. from __future__ import annotations
  3. import json
  4. from pathlib import Path
  5. from typing import Callable, Iterable
  6. import cocotb
  7. from cocotb.triggers import FallingEdge, ReadOnly, RisingEdge, Timer, with_timeout
  8. ROOT = Path(__file__).resolve().parents[2]
  9. HOST_CLKS_PER_BIT = 27
  10. BMC_CLKS_PER_BIT = 217
  11. CLOCK_NS = 40
  12. SET_TARGET = 0x01
  13. GET_SNAPSHOT = 0x02
  14. SET_STIMULUS = 0x03
  15. SET_TARGET_ACK = 0x81
  16. GET_SNAPSHOT_ACK = 0x82
  17. SNAPSHOT_DATA = 0x42
  18. SET_STIMULUS_ACK = 0x83
  19. _LAYOUT = json.loads(
  20. (ROOT / "generated/6400/snapshot-layout.json").read_text(encoding="utf-8")
  21. )
  22. SNAPSHOT_LENGTH = _LAYOUT["payload_length"]
  23. FIELDS = {entry["name"]: entry for entry in _LAYOUT["fields"]}
  24. def crc16(data: bytes) -> int:
  25. value = 0xFFFF
  26. for octet in data:
  27. value ^= octet << 8
  28. for _ in range(8):
  29. value = ((value << 1) ^ 0x1021) & 0xFFFF if value & 0x8000 else (value << 1) & 0xFFFF
  30. return value
  31. def encode_frame(kind: int, payload: bytes = b"") -> bytes:
  32. body = bytes((kind, len(payload))) + payload
  33. return b"\xA5\x5A" + body + crc16(body).to_bytes(2, "little")
  34. async def clock_cycles(dut, count: int) -> None:
  35. for _ in range(count):
  36. await RisingEdge(dut.sys_clk)
  37. async def wait_for(
  38. dut,
  39. predicate: Callable[[], bool],
  40. *,
  41. cycles: int,
  42. label: str,
  43. ) -> None:
  44. for _ in range(cycles):
  45. if predicate():
  46. return
  47. await RisingEdge(dut.sys_clk)
  48. raise AssertionError(f"timeout waiting for {label}")
  49. async def send_uart_byte(signal, value: int, clocks_per_bit: int) -> None:
  50. signal.value = 0
  51. await Timer(clocks_per_bit * CLOCK_NS, units="ns")
  52. for bit in range(8):
  53. signal.value = (value >> bit) & 1
  54. await Timer(clocks_per_bit * CLOCK_NS, units="ns")
  55. signal.value = 1
  56. await Timer(clocks_per_bit * CLOCK_NS, units="ns")
  57. async def send_uart(signal, data: Iterable[int], clocks_per_bit: int) -> None:
  58. for value in data:
  59. await send_uart_byte(signal, value, clocks_per_bit)
  60. async def receive_uart_byte(signal, clocks_per_bit: int) -> int:
  61. if signal.value.is_resolvable and int(signal.value) == 0:
  62. await RisingEdge(signal)
  63. await FallingEdge(signal)
  64. await Timer(clocks_per_bit * 60, units="ns")
  65. value = 0
  66. for bit in range(8):
  67. value |= int(signal.value) << bit
  68. await Timer(clocks_per_bit * CLOCK_NS, units="ns")
  69. assert int(signal.value) == 1, f"UART stop-bit failure for 0x{value:02x}"
  70. return value
  71. async def receive_frame(signal, clocks_per_bit: int = HOST_CLKS_PER_BIT) -> tuple[int, bytes]:
  72. header = bytes([await receive_uart_byte(signal, clocks_per_bit) for _ in range(4)])
  73. assert header[:2] == b"\xA5\x5A", f"bad response header {header.hex()}"
  74. payload_and_crc = bytes(
  75. [await receive_uart_byte(signal, clocks_per_bit) for _ in range(header[3] + 2)]
  76. )
  77. packet = header + payload_and_crc
  78. assert packet[-2:] == crc16(packet[2:-2]).to_bytes(2, "little")
  79. return header[2], packet[4:-2]
  80. async def host_transaction(dut, port: str, kind: int, payload: bytes = b"") -> tuple[int, bytes]:
  81. rx = getattr(dut, f"host_{port}_rx")
  82. tx = getattr(dut, f"host_{port}_tx")
  83. response = cocotb.start_soon(receive_frame(tx))
  84. await send_uart(rx, encode_frame(kind, payload), HOST_CLKS_PER_BIT)
  85. result = await with_timeout(response, 20, "ms")
  86. # receive_frame returns at the center of the final stop bit; allow the
  87. # physical UART byte_done and port-selector unlock to retire.
  88. await Timer(HOST_CLKS_PER_BIT * CLOCK_NS * 2, units="ns")
  89. return result
  90. def bmc_payload(temperatures: Iterable[int | None]) -> bytes:
  91. values = list(temperatures)
  92. assert len(values) == 24
  93. raw = bytearray()
  94. for temperature in values:
  95. if temperature is None:
  96. raw.extend((0xFF, 0xFF))
  97. else:
  98. assert 0 <= temperature <= 254
  99. raw.extend((temperature, 0))
  100. return bytes(raw)
  101. async def send_bmc_snapshot(dut, temperatures: Iterable[int | None]) -> None:
  102. raw = bmc_payload(temperatures)
  103. line = ("".join(f"{value:02x}" for value in raw) + "\r").encode("ascii")
  104. old_epoch = int(dut.bmc_epoch_mon.value)
  105. await send_uart(dut.bmc_rs232_rx, line, BMC_CLKS_PER_BIT)
  106. await wait_for(
  107. dut,
  108. lambda: int(dut.bmc_epoch_mon.value) == ((old_epoch + 1) & 0xFFFF),
  109. cycles=200,
  110. label="BMC snapshot commit",
  111. )
  112. async def pulse_tick_1s(dut, count: int = 1) -> None:
  113. for _ in range(count):
  114. await FallingEdge(dut.sys_clk)
  115. dut.tick_1s_test.value = 1
  116. await RisingEdge(dut.sys_clk)
  117. await FallingEdge(dut.sys_clk)
  118. dut.tick_1s_test.value = 0
  119. def fan_connector_value(dut) -> int:
  120. front_ball = int(dut.front_fan_pwm_out.value)
  121. rear_ball = int(dut.rear_fan_pwm_out.value)
  122. return (rear_ball << 4) | ((~front_ball) & 0x0F)
  123. async def verify_boot_full_speed_then_standby(dut) -> None:
  124. # POR, both-RAM initialization, and the full-boundary handoff must expose
  125. # only the full-speed connector request. Capture the pre-edge advance
  126. # signal to prove the release itself occurs on the atomic PWM edge.
  127. saw_reset = False
  128. previous_release = 0
  129. for _ in range(4000):
  130. await FallingEdge(dut.sys_clk)
  131. pre_boundary = int(dut.u_dut.pwm_boundary_advance.value)
  132. await RisingEdge(dut.sys_clk)
  133. await ReadOnly()
  134. reset_n = int(dut.rst_n_mon.value)
  135. release = int(dut.u_dut.boot_fan_release.value)
  136. if not reset_n:
  137. saw_reset = True
  138. if not release:
  139. assert fan_connector_value(dut) == 0xFF
  140. assert int(dut.front_fan_pwm_out.value) == 0x0
  141. assert int(dut.rear_fan_pwm_out.value) == 0xF
  142. if release and not previous_release:
  143. assert pre_boundary == 1
  144. break
  145. previous_release = release
  146. else:
  147. raise AssertionError("boot fan release did not complete")
  148. assert saw_reset
  149. assert int(dut.u_dut.boot_init_complete.value) == 1
  150. # Reset-age BMC stale has higher safety priority than standby, so physical
  151. # output correctly remains 100% after the boot flag itself releases.
  152. assert fan_connector_value(dut) == 0xFF
  153. await FallingEdge(dut.sys_clk)
  154. await send_bmc_snapshot(dut, [60] * 24)
  155. await wait_for(
  156. dut,
  157. lambda: int(dut.u_dut.bmc_stale.value) == 0,
  158. cycles=200,
  159. label="fresh BMC before standby waveform",
  160. )
  161. # Once BMC is fresh, the initialized bank is FAN_STANDBY_DUTY=10 for all
  162. # eight outputs. Start at a later phase-zero boundary so the boundary-
  163. # latched stale override has already retired without a narrow pulse.
  164. while True:
  165. await RisingEdge(dut.sys_clk)
  166. await ReadOnly()
  167. if int(dut.pwm_boundary_mon.value) and int(dut.pwm_phase_mon.value) == 0:
  168. break
  169. high_counts = [0] * 8
  170. for sample in range(50000):
  171. connector = fan_connector_value(dut)
  172. for index in range(8):
  173. high_counts[index] += (connector >> index) & 1
  174. if sample != 49999:
  175. await RisingEdge(dut.sys_clk)
  176. await ReadOnly()
  177. assert high_counts == [5000] * 8
  178. async def initialize(dut, *, verify_boot: bool = False) -> None:
  179. dut.host_rs232_rx.value = 1
  180. dut.host_ttl_rx.value = 1
  181. dut.bmc_rs232_rx.value = 1
  182. dut.tick_1s_test.value = 0
  183. if verify_boot:
  184. await verify_boot_full_speed_then_standby(dut)
  185. else:
  186. await with_timeout(RisingEdge(dut.rst_n_mon), 1, "ms")
  187. await wait_for(
  188. dut,
  189. lambda: int(dut.ct_epoch_mon.value) >= 1,
  190. cycles=500,
  191. label="first 27-channel CT epoch",
  192. )
  193. assert int(dut.ct_valid_mask_mon.value) == (1 << 27) - 1
  194. await wait_for(
  195. dut,
  196. lambda: int(dut.control_state_mon.value) in (2, 3),
  197. cycles=1000,
  198. label="PREHEAT_CT or already-qualified WAIT_BMC_STABLE",
  199. )
  200. assert int(dut.global_fault_mon.value) == 0
  201. await FallingEdge(dut.sys_clk)
  202. async def bring_auto(dut, temperature: int = 60, *, verify_boot: bool = False) -> None:
  203. await initialize(dut, verify_boot=verify_boot)
  204. for _ in range(4):
  205. await send_bmc_snapshot(dut, [temperature] * 24)
  206. await wait_for(
  207. dut,
  208. lambda: int(dut.control_state_mon.value) == 4 and int(dut.control_epoch_mon.value) >= 1,
  209. cycles=1000,
  210. label="AUTO_BMC control commit",
  211. )
  212. assert int(dut.bmc_valid_mask_mon.value) == (1 << 24) - 1
  213. def decode_snapshot(payload: bytes) -> dict[str, object]:
  214. assert len(payload) == SNAPSHOT_LENGTH
  215. decoded: dict[str, object] = {}
  216. for name, field in FIELDS.items():
  217. start = field["offset"]
  218. data = payload[start : start + field["size"]]
  219. if field["type"] == "u8" and field.get("count", 1) == 1:
  220. decoded[name] = data[0]
  221. elif field["type"] == "u8":
  222. decoded[name] = list(data)
  223. elif field["type"] == "u16" and field.get("count", 1) == 1:
  224. decoded[name] = int.from_bytes(data, "little")
  225. elif field["type"] == "u16":
  226. decoded[name] = [
  227. int.from_bytes(data[index : index + 2], "little")
  228. for index in range(0, len(data), 2)
  229. ]
  230. elif field["type"] == "bytes":
  231. decoded[name] = int.from_bytes(data, "little")
  232. else:
  233. decoded[name] = list(data)
  234. return decoded
  235. async def get_snapshot(dut, port: str = "ttl") -> dict[str, object]:
  236. rx = getattr(dut, f"host_{port}_rx")
  237. tx = getattr(dut, f"host_{port}_tx")
  238. async def receive_ack_then_data() -> bytes:
  239. ack_kind, ack_payload = await receive_frame(tx)
  240. assert (ack_kind, ack_payload) == (GET_SNAPSHOT_ACK, b"")
  241. data_kind, data_payload = await receive_frame(tx)
  242. assert data_kind == SNAPSHOT_DATA
  243. return data_payload
  244. response = cocotb.start_soon(receive_ack_then_data())
  245. await send_uart(rx, encode_frame(GET_SNAPSHOT), HOST_CLKS_PER_BIT)
  246. payload = await with_timeout(response, 40, "ms")
  247. await Timer(HOST_CLKS_PER_BIT * CLOCK_NS * 2, units="ns")
  248. return decode_snapshot(payload)
  249. async def check_pwm_timing(dut) -> None:
  250. await RisingEdge(dut.pwm_boundary_mon)
  251. first_phase = int(dut.pwm_phase_mon.value)
  252. for offset in range(1, 101):
  253. clocks = 0
  254. while True:
  255. await RisingEdge(dut.sys_clk)
  256. await ReadOnly()
  257. clocks += 1
  258. if int(dut.pwm_boundary_mon.value):
  259. break
  260. assert clocks == 500
  261. assert int(dut.pwm_deadline_miss_mon.value) == 0
  262. if offset == 100:
  263. assert int(dut.pwm_phase_mon.value) == first_phase