test_6400_pi_differential.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  1. """L7 bit-exact differential checks against the thermal-control-lab model."""
  2. from __future__ import annotations
  3. from pathlib import Path
  4. import sys
  5. import cocotb
  6. from cocotb.triggers import FallingEdge, ReadOnly, RisingEdge, Timer, with_timeout
  7. ROOT = Path(__file__).resolve().parents[2]
  8. LAB_ROOT = ROOT.parent / "thermal-control-lab"
  9. if not LAB_ROOT.is_dir():
  10. raise RuntimeError(f"thermal-control-lab sibling is required for L7: {LAB_ROOT}")
  11. sys.path.insert(0, str(LAB_ROOT))
  12. from thermal_control_lab.fixed_point import ControllerBank, PIConfig # noqa: E402
  13. FULL_VALID = (1 << 24) - 1
  14. def raw_from_centi(value: int) -> int:
  15. if not 0 <= value <= 25_499:
  16. raise ValueError(f"BMC test temperature out of range: {value}")
  17. integer, fraction = divmod(value, 100)
  18. return (integer << 8) | fraction
  19. def errors_for(target_c: int, temperatures: list[int]) -> list[int]:
  20. return [target_c * 100 - value for value in temperatures]
  21. async def clock_cycles(dut, count: int) -> None:
  22. for _ in range(count):
  23. await RisingEdge(dut.sys_clk)
  24. async def wait_for(dut, predicate, *, cycles: int, label: str) -> None:
  25. for _ in range(cycles):
  26. await RisingEdge(dut.sys_clk)
  27. await ReadOnly()
  28. if predicate():
  29. return
  30. raise AssertionError(f"timeout waiting for {label}")
  31. async def load_temperatures(dut, temperatures: list[int]) -> None:
  32. assert len(temperatures) == 24
  33. await FallingEdge(dut.sys_clk)
  34. dut.bmc_wr_en.value = 1
  35. for index, value in enumerate(temperatures):
  36. dut.bmc_wr_index.value = index
  37. dut.bmc_wr_raw.value = raw_from_centi(value)
  38. await FallingEdge(dut.sys_clk)
  39. dut.bmc_wr_en.value = 0
  40. async def set_epoch(
  41. dut,
  42. epoch: int,
  43. temperatures: list[int],
  44. *,
  45. valid_mask: int = FULL_VALID,
  46. ) -> None:
  47. await load_temperatures(dut, temperatures)
  48. await FallingEdge(dut.sys_clk)
  49. dut.bmc_valid_mask_test.value = valid_mask
  50. dut.bmc_epoch_test.value = epoch & 0xFFFF
  51. async def wait_commit(dut, previous_count: int, label: str) -> None:
  52. await wait_for(
  53. dut,
  54. lambda: int(dut.commit_count_mon.value) > previous_count,
  55. cycles=500,
  56. label=label,
  57. )
  58. async def read_outputs(dut) -> tuple[list[int], list[int], list[int], list[int]]:
  59. requested: list[int] = []
  60. applied: list[int] = []
  61. previous_error: list[int] = []
  62. previous_output: list[int] = []
  63. await FallingEdge(dut.sys_clk)
  64. for index in range(32):
  65. dut.rd_index.value = index
  66. await Timer(1, units="ns")
  67. requested.append(int(dut.requested_data.value))
  68. applied.append(int(dut.applied_data.value))
  69. if index < 24:
  70. error = int(dut.previous_error_data.value)
  71. previous_error.append(error - 0x10000 if error & 0x8000 else error)
  72. previous_output.append(int(dut.previous_output_data.value))
  73. return requested, applied, previous_error, previous_output
  74. async def compare_epoch(
  75. dut,
  76. model: ControllerBank,
  77. epoch: int,
  78. temperatures: list[int],
  79. *,
  80. target_c: int = 70,
  81. valid_mask: int = FULL_VALID,
  82. override: list[bool] | None = None,
  83. expected_fans: list[int] | None = None,
  84. label: str,
  85. ) -> tuple[list[int], list[int]]:
  86. before = int(dut.commit_count_mon.value)
  87. await set_epoch(dut, epoch, temperatures, valid_mask=valid_mask)
  88. await wait_commit(dut, before, label)
  89. valid = [bool(valid_mask & (1 << index)) for index in range(24)]
  90. expected = model.update(
  91. epoch,
  92. errors_for(target_c, temperatures),
  93. valid,
  94. safety_override=override,
  95. )
  96. requested, applied, previous_error, previous_output = await read_outputs(dut)
  97. assert applied[:24] == expected, f"{label}: applied RTL/Python mismatch"
  98. assert all(0 <= value <= 100 for value in requested + applied)
  99. if override is None and valid_mask == FULL_VALID:
  100. assert requested[:24] == expected, f"{label}: requested RTL/Python mismatch"
  101. expected_state_error = [state.previous_error_centi for state in model.states]
  102. expected_state_output = [state.previous_output_q8_8 for state in model.states]
  103. assert previous_error == expected_state_error, f"{label}: error-state mismatch"
  104. assert previous_output == expected_state_output, f"{label}: output-state mismatch"
  105. fans = expected_fans or [30] * 8
  106. assert applied[24:] == fans, f"{label}: fan safety mismatch"
  107. return requested, applied
  108. async def bootstrap_auto(dut, temperatures: list[int], start_epoch: int = 1) -> int:
  109. await wait_for(
  110. dut,
  111. lambda: int(dut.control_state.value) == 2,
  112. cycles=50,
  113. label="PREHEAT_CT",
  114. )
  115. await set_epoch(dut, start_epoch, temperatures)
  116. await wait_for(
  117. dut,
  118. lambda: int(dut.control_state.value) == 3,
  119. cycles=50,
  120. label="WAIT_BMC_STABLE",
  121. )
  122. for epoch in (start_epoch + 1, start_epoch + 2):
  123. await set_epoch(dut, epoch, temperatures)
  124. await clock_cycles(dut, 8)
  125. return start_epoch + 3
  126. @cocotb.test()
  127. async def test_pi_python_rtl_differential_safety_epoch_target_and_recovery(dut):
  128. dut.tick_1s_test.value = 0
  129. dut.target_commit_test.value = 0
  130. dut.target_celsius_test.value = 70
  131. dut.bmc_epoch_test.value = 0
  132. dut.bmc_stale_test.value = 0
  133. dut.bmc_valid_mask_test.value = FULL_VALID
  134. dut.bmc_wr_en.value = 0
  135. dut.bmc_wr_index.value = 0
  136. dut.bmc_wr_raw.value = 0
  137. dut.ct_epoch_test.value = 1
  138. dut.ct_stale_test.value = 0
  139. dut.ct_valid_mask_test.value = (1 << 27) - 1
  140. dut.rd_index.value = 0
  141. await with_timeout(RisingEdge(dut.rst_n_mon), 1, "ms")
  142. model = ControllerBank(PIConfig(32, 4), PIConfig(24, 3))
  143. temperatures = [6500 + ((index * 37) % 400) for index in range(24)]
  144. epoch = await bootstrap_auto(dut, temperatures)
  145. await compare_epoch(dut, model, epoch, temperatures, label="initial mixed edge/center pass")
  146. # The same BMC epoch is a strict hold: no reintegration and no new bank flip.
  147. held_commit = int(dut.commit_count_mon.value)
  148. held_outputs = (await read_outputs(dut))[1]
  149. assert model.update(epoch, errors_for(70, temperatures), [True] * 24) == held_outputs[:24]
  150. await clock_cycles(dut, 300)
  151. assert int(dut.commit_count_mon.value) == held_commit
  152. assert (await read_outputs(dut))[1] == held_outputs
  153. # Mixed fractional errors cover both coefficient classes and half-away
  154. # rounding. Repeated cold epochs then hit slew and upper anti-windup.
  155. epoch += 1
  156. temperatures = [6999 - ((index * 7) % 180) for index in range(24)]
  157. await compare_epoch(dut, model, epoch, temperatures, label="fractional rounding")
  158. for iteration in range(24):
  159. epoch += 1
  160. temperatures = [2000 + ((index * 11 + iteration) % 90) for index in range(24)]
  161. await compare_epoch(dut, model, epoch, temperatures, label=f"positive slew {iteration}")
  162. assert max(model.outputs_q8_8) == 25_600
  163. # Hold at saturation, then prove the negative slew path is equally exact.
  164. for iteration in range(2):
  165. epoch += 1
  166. await compare_epoch(dut, model, epoch, temperatures, label=f"anti-windup hold {iteration}")
  167. for iteration in range(5):
  168. epoch += 1
  169. temperatures = [7399 - (index % 5) for index in range(24)]
  170. await compare_epoch(dut, model, epoch, temperatures, label=f"negative slew {iteration}")
  171. # A single invalid channel is off while its PI state freezes. When the
  172. # channel becomes valid, the Python and RTL paths resume from that state.
  173. invalid_mask = FULL_VALID ^ 1
  174. frozen_state = model.states[0]
  175. epoch += 1
  176. await compare_epoch(
  177. dut,
  178. model,
  179. epoch,
  180. temperatures,
  181. valid_mask=invalid_mask,
  182. label="single invalid freeze",
  183. )
  184. assert model.states[0] == frozen_state
  185. temperatures = [7100] * 24
  186. for iteration in range(3):
  187. epoch += 1
  188. await compare_epoch(dut, model, epoch, temperatures, label=f"invalid recovery {iteration}")
  189. assert int(dut.control_state.value) == 4
  190. # Pretrip clears one production controller, forces its PTC off, and raises
  191. # both lane fans. The reference is explicitly rebased for safe recovery.
  192. epoch += 1
  193. temperatures = [6900] * 24
  194. temperatures[6] = 7600
  195. override = [index == 6 for index in range(24)]
  196. await compare_epoch(
  197. dut,
  198. model,
  199. epoch,
  200. temperatures,
  201. override=override,
  202. expected_fans=[30, 80, 30, 30, 30, 80, 30, 30],
  203. label="76 C pretrip",
  204. )
  205. model.clear_channels([6])
  206. temperatures = [6900] * 24
  207. for iteration in range(3):
  208. epoch += 1
  209. await compare_epoch(dut, model, epoch, temperatures, label=f"pretrip recovery {iteration}")
  210. # A 77 C sample clamps and clears the complete six-channel lane. Three
  211. # safe epochs retain zero duty; the next epoch ramps from the cleared state.
  212. epoch += 1
  213. temperatures[12] = 7700
  214. lane_override = [12 <= index < 18 for index in range(24)]
  215. await compare_epoch(
  216. dut,
  217. model,
  218. epoch,
  219. temperatures,
  220. override=lane_override,
  221. expected_fans=[30, 30, 100, 30, 30, 30, 100, 30],
  222. label="77 C lane hard clamp",
  223. )
  224. assert int(dut.lane_fault_mask.value) & (1 << 2)
  225. model.clear_channels(range(12, 18))
  226. temperatures[12] = 6900
  227. for iteration in range(3):
  228. epoch += 1
  229. recovery_fans = (
  230. [30, 30, 100, 30, 30, 30, 100, 30]
  231. if iteration < 2
  232. else [30] * 8
  233. )
  234. await compare_epoch(
  235. dut,
  236. model,
  237. epoch,
  238. temperatures,
  239. override=lane_override,
  240. expected_fans=recovery_fans,
  241. label=f"hard-clamp recovery hold {iteration}",
  242. )
  243. assert int(dut.lane_fault_mask.value) == 0
  244. epoch += 1
  245. await compare_epoch(dut, model, epoch, temperatures, label="hard-clamp limited restart")
  246. # Runtime stale preempts without a new epoch, atomically fills 0/100 safe
  247. # outputs, and requires three fresh recovery epochs before limited restart.
  248. before = int(dut.commit_count_mon.value)
  249. await FallingEdge(dut.sys_clk)
  250. dut.bmc_stale_test.value = 1
  251. await wait_commit(dut, before, "global stale safe fill")
  252. _, stale_applied, _, _ = await read_outputs(dut)
  253. assert stale_applied == [0] * 24 + [100] * 8
  254. assert model.update(epoch, errors_for(70, temperatures), [True] * 24, stale=True) == [0] * 24
  255. model.stop()
  256. await FallingEdge(dut.sys_clk)
  257. dut.bmc_stale_test.value = 0
  258. all_override = [True] * 24
  259. for iteration in range(3):
  260. epoch += 1
  261. recovery_fans = [100] * 8 if iteration < 2 else [30] * 8
  262. await compare_epoch(
  263. dut,
  264. model,
  265. epoch,
  266. temperatures,
  267. override=all_override,
  268. expected_fans=recovery_fans,
  269. label=f"stale recovery hold {iteration}",
  270. )
  271. assert int(dut.global_fault.value) == 0
  272. epoch += 1
  273. await compare_epoch(dut, model, epoch, temperatures, label="stale limited restart")
  274. # Target changes clear the PI path, commit a safe image, and require the
  275. # CT/BMC qualification sequence before the new-target Python path runs.
  276. before = int(dut.commit_count_mon.value)
  277. await FallingEdge(dut.sys_clk)
  278. dut.target_celsius_test.value = 60
  279. dut.target_commit_test.value = 1
  280. await FallingEdge(dut.sys_clk)
  281. dut.target_commit_test.value = 0
  282. await wait_commit(dut, before, "target-change safe fill")
  283. assert (await read_outputs(dut))[1][:24] == [0] * 24
  284. model.stop()
  285. await FallingEdge(dut.sys_clk)
  286. dut.ct_epoch_test.value = 2
  287. temperatures = [5500 + (index % 20) for index in range(24)]
  288. next_epoch = await bootstrap_auto(dut, temperatures, start_epoch=epoch + 1)
  289. await compare_epoch(
  290. dut,
  291. model,
  292. next_epoch,
  293. temperatures,
  294. target_c=60,
  295. label="new-target qualified restart",
  296. )
  297. assert int(dut.current_target_celsius.value) == 60
  298. assert int(dut.control_state.value) == 4
  299. assert int(dut.work_state_mon.value) == 0