thermal_6400_uart.py 11 KB

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