| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340 |
- """L7 bit-exact differential checks against the thermal-control-lab model."""
- from __future__ import annotations
- from pathlib import Path
- import sys
- import cocotb
- from cocotb.triggers import FallingEdge, ReadOnly, RisingEdge, Timer, with_timeout
- ROOT = Path(__file__).resolve().parents[2]
- LAB_ROOT = ROOT.parent / "thermal-control-lab"
- if not LAB_ROOT.is_dir():
- raise RuntimeError(f"thermal-control-lab sibling is required for L7: {LAB_ROOT}")
- sys.path.insert(0, str(LAB_ROOT))
- from thermal_control_lab.fixed_point import ControllerBank, PIConfig # noqa: E402
- FULL_VALID = (1 << 24) - 1
- def raw_from_centi(value: int) -> int:
- if not 0 <= value <= 25_499:
- raise ValueError(f"BMC test temperature out of range: {value}")
- integer, fraction = divmod(value, 100)
- return (integer << 8) | fraction
- def errors_for(target_c: int, temperatures: list[int]) -> list[int]:
- return [target_c * 100 - value for value in temperatures]
- async def clock_cycles(dut, count: int) -> None:
- for _ in range(count):
- await RisingEdge(dut.sys_clk)
- async def wait_for(dut, predicate, *, cycles: int, label: str) -> None:
- for _ in range(cycles):
- await RisingEdge(dut.sys_clk)
- await ReadOnly()
- if predicate():
- return
- raise AssertionError(f"timeout waiting for {label}")
- async def load_temperatures(dut, temperatures: list[int]) -> None:
- assert len(temperatures) == 24
- await FallingEdge(dut.sys_clk)
- dut.bmc_wr_en.value = 1
- for index, value in enumerate(temperatures):
- dut.bmc_wr_index.value = index
- dut.bmc_wr_raw.value = raw_from_centi(value)
- await FallingEdge(dut.sys_clk)
- dut.bmc_wr_en.value = 0
- async def set_epoch(
- dut,
- epoch: int,
- temperatures: list[int],
- *,
- valid_mask: int = FULL_VALID,
- ) -> None:
- await load_temperatures(dut, temperatures)
- await FallingEdge(dut.sys_clk)
- dut.bmc_valid_mask_test.value = valid_mask
- dut.bmc_epoch_test.value = epoch & 0xFFFF
- async def wait_commit(dut, previous_count: int, label: str) -> None:
- await wait_for(
- dut,
- lambda: int(dut.commit_count_mon.value) > previous_count,
- cycles=500,
- label=label,
- )
- async def read_outputs(dut) -> tuple[list[int], list[int], list[int], list[int]]:
- requested: list[int] = []
- applied: list[int] = []
- previous_error: list[int] = []
- previous_output: list[int] = []
- for index in range(32):
- await FallingEdge(dut.sys_clk)
- dut.rd_index.value = index
- await RisingEdge(dut.sys_clk)
- await ReadOnly()
- requested.append(int(dut.requested_data.value))
- applied.append(int(dut.applied_data.value))
- if index < 24:
- error = int(dut.previous_error_data.value)
- previous_error.append(error - 0x10000 if error & 0x8000 else error)
- previous_output.append(int(dut.previous_output_data.value))
- return requested, applied, previous_error, previous_output
- async def compare_epoch(
- dut,
- model: ControllerBank,
- epoch: int,
- temperatures: list[int],
- *,
- target_c: int = 70,
- valid_mask: int = FULL_VALID,
- override: list[bool] | None = None,
- expected_fans: list[int] | None = None,
- label: str,
- ) -> tuple[list[int], list[int]]:
- before = int(dut.commit_count_mon.value)
- await set_epoch(dut, epoch, temperatures, valid_mask=valid_mask)
- await wait_commit(dut, before, label)
- valid = [bool(valid_mask & (1 << index)) for index in range(24)]
- expected = model.update(
- epoch,
- errors_for(target_c, temperatures),
- valid,
- safety_override=override,
- )
- requested, applied, previous_error, previous_output = await read_outputs(dut)
- assert applied[:24] == expected, f"{label}: applied RTL/Python mismatch"
- assert all(0 <= value <= 100 for value in requested + applied)
- if override is None and valid_mask == FULL_VALID:
- assert requested[:24] == expected, f"{label}: requested RTL/Python mismatch"
- expected_state_error = [state.previous_error_centi for state in model.states]
- expected_state_output = [state.previous_output_q8_8 for state in model.states]
- assert previous_error == expected_state_error, f"{label}: error-state mismatch"
- assert previous_output == expected_state_output, f"{label}: output-state mismatch"
- fans = expected_fans or [30] * 8
- assert applied[24:] == fans, f"{label}: fan safety mismatch"
- return requested, applied
- async def bootstrap_auto(dut, temperatures: list[int], start_epoch: int = 1) -> int:
- await wait_for(
- dut,
- lambda: int(dut.control_state.value) == 2,
- cycles=50,
- label="PREHEAT_CT",
- )
- await set_epoch(dut, start_epoch, temperatures)
- await wait_for(
- dut,
- lambda: int(dut.control_state.value) == 3,
- cycles=50,
- label="WAIT_BMC_STABLE",
- )
- for epoch in (start_epoch + 1, start_epoch + 2):
- await set_epoch(dut, epoch, temperatures)
- await clock_cycles(dut, 8)
- return start_epoch + 3
- @cocotb.test()
- async def test_pi_python_rtl_differential_safety_epoch_target_and_recovery(dut):
- dut.tick_1s_test.value = 0
- dut.target_commit_test.value = 0
- dut.target_celsius_test.value = 70
- dut.bmc_epoch_test.value = 0
- dut.bmc_stale_test.value = 0
- dut.bmc_valid_mask_test.value = FULL_VALID
- dut.bmc_wr_en.value = 0
- dut.bmc_wr_index.value = 0
- dut.bmc_wr_raw.value = 0
- dut.ct_epoch_test.value = 1
- dut.ct_stale_test.value = 0
- dut.ct_valid_mask_test.value = (1 << 27) - 1
- dut.rd_index.value = 0
- await with_timeout(RisingEdge(dut.rst_n_mon), 1, "ms")
- model = ControllerBank(PIConfig(32, 4), PIConfig(24, 3))
- temperatures = [6500 + ((index * 37) % 400) for index in range(24)]
- epoch = await bootstrap_auto(dut, temperatures)
- await compare_epoch(dut, model, epoch, temperatures, label="initial mixed edge/center pass")
- # The same BMC epoch is a strict hold: no reintegration and no new bank flip.
- held_commit = int(dut.commit_count_mon.value)
- held_outputs = (await read_outputs(dut))[1]
- assert model.update(epoch, errors_for(70, temperatures), [True] * 24) == held_outputs[:24]
- await clock_cycles(dut, 300)
- assert int(dut.commit_count_mon.value) == held_commit
- assert (await read_outputs(dut))[1] == held_outputs
- # Mixed fractional errors cover both coefficient classes and half-away
- # rounding. Repeated cold epochs then hit slew and upper anti-windup.
- epoch += 1
- temperatures = [6999 - ((index * 7) % 180) for index in range(24)]
- await compare_epoch(dut, model, epoch, temperatures, label="fractional rounding")
- for iteration in range(24):
- epoch += 1
- temperatures = [2000 + ((index * 11 + iteration) % 90) for index in range(24)]
- await compare_epoch(dut, model, epoch, temperatures, label=f"positive slew {iteration}")
- assert max(model.outputs_q8_8) == 25_600
- # Hold at saturation, then prove the negative slew path is equally exact.
- for iteration in range(2):
- epoch += 1
- await compare_epoch(dut, model, epoch, temperatures, label=f"anti-windup hold {iteration}")
- for iteration in range(5):
- epoch += 1
- temperatures = [7399 - (index % 5) for index in range(24)]
- await compare_epoch(dut, model, epoch, temperatures, label=f"negative slew {iteration}")
- # A single invalid channel is off while its PI state freezes. When the
- # channel becomes valid, the Python and RTL paths resume from that state.
- invalid_mask = FULL_VALID ^ 1
- frozen_state = model.states[0]
- epoch += 1
- await compare_epoch(
- dut,
- model,
- epoch,
- temperatures,
- valid_mask=invalid_mask,
- label="single invalid freeze",
- )
- assert model.states[0] == frozen_state
- temperatures = [7100] * 24
- for iteration in range(3):
- epoch += 1
- await compare_epoch(dut, model, epoch, temperatures, label=f"invalid recovery {iteration}")
- assert int(dut.control_state.value) == 4
- # Pretrip clears one production controller, forces its PTC off, and raises
- # both lane fans. The reference is explicitly rebased for safe recovery.
- epoch += 1
- temperatures = [6900] * 24
- temperatures[6] = 7600
- override = [index == 6 for index in range(24)]
- await compare_epoch(
- dut,
- model,
- epoch,
- temperatures,
- override=override,
- expected_fans=[30, 80, 30, 30, 30, 80, 30, 30],
- label="76 C pretrip",
- )
- model.clear_channels([6])
- temperatures = [6900] * 24
- for iteration in range(3):
- epoch += 1
- await compare_epoch(dut, model, epoch, temperatures, label=f"pretrip recovery {iteration}")
- # A 77 C sample clamps and clears the complete six-channel lane. Three
- # safe epochs retain zero duty; the next epoch ramps from the cleared state.
- epoch += 1
- temperatures[12] = 7700
- lane_override = [12 <= index < 18 for index in range(24)]
- await compare_epoch(
- dut,
- model,
- epoch,
- temperatures,
- override=lane_override,
- expected_fans=[30, 30, 100, 30, 30, 30, 100, 30],
- label="77 C lane hard clamp",
- )
- assert int(dut.lane_fault_mask.value) & (1 << 2)
- model.clear_channels(range(12, 18))
- temperatures[12] = 6900
- for iteration in range(3):
- epoch += 1
- recovery_fans = (
- [30, 30, 100, 30, 30, 30, 100, 30]
- if iteration < 2
- else [30] * 8
- )
- await compare_epoch(
- dut,
- model,
- epoch,
- temperatures,
- override=lane_override,
- expected_fans=recovery_fans,
- label=f"hard-clamp recovery hold {iteration}",
- )
- assert int(dut.lane_fault_mask.value) == 0
- epoch += 1
- await compare_epoch(dut, model, epoch, temperatures, label="hard-clamp limited restart")
- # Runtime stale preempts without a new epoch, atomically fills 0/100 safe
- # outputs, and requires three fresh recovery epochs before limited restart.
- before = int(dut.commit_count_mon.value)
- await FallingEdge(dut.sys_clk)
- dut.bmc_stale_test.value = 1
- await wait_commit(dut, before, "global stale safe fill")
- _, stale_applied, _, _ = await read_outputs(dut)
- assert stale_applied == [0] * 24 + [100] * 8
- assert model.update(epoch, errors_for(70, temperatures), [True] * 24, stale=True) == [0] * 24
- model.stop()
- await FallingEdge(dut.sys_clk)
- dut.bmc_stale_test.value = 0
- all_override = [True] * 24
- for iteration in range(3):
- epoch += 1
- recovery_fans = [100] * 8 if iteration < 2 else [30] * 8
- await compare_epoch(
- dut,
- model,
- epoch,
- temperatures,
- override=all_override,
- expected_fans=recovery_fans,
- label=f"stale recovery hold {iteration}",
- )
- assert int(dut.global_fault.value) == 0
- epoch += 1
- await compare_epoch(dut, model, epoch, temperatures, label="stale limited restart")
- # Target changes clear the PI path, commit a safe image, and require the
- # CT/BMC qualification sequence before the new-target Python path runs.
- before = int(dut.commit_count_mon.value)
- await FallingEdge(dut.sys_clk)
- dut.target_celsius_test.value = 60
- dut.target_commit_test.value = 1
- await FallingEdge(dut.sys_clk)
- dut.target_commit_test.value = 0
- await wait_commit(dut, before, "target-change safe fill")
- assert (await read_outputs(dut))[1][:24] == [0] * 24
- model.stop()
- await FallingEdge(dut.sys_clk)
- dut.ct_epoch_test.value = 2
- temperatures = [5500 + (index % 20) for index in range(24)]
- next_epoch = await bootstrap_auto(dut, temperatures, start_epoch=epoch + 1)
- await compare_epoch(
- dut,
- model,
- next_epoch,
- temperatures,
- target_c=60,
- label="new-target qualified restart",
- )
- assert int(dut.current_target_celsius.value) == 60
- assert int(dut.control_state.value) == 4
- assert int(dut.work_state_mon.value) == 0
|