소스 검색

test(protocol): fuzz 6400 Host UART framing

root 3 달 전
부모
커밋
e90033ebd4

+ 6 - 3
src/top/prod2u_6400_v1_top.v

@@ -3,7 +3,9 @@
 
 module prod2u_6400_v1_top #(
     parameter integer ENABLE_STIMULUS = 0,
-    parameter integer CT_SCAN_PERIOD_CLKS = 2500000
+    parameter integer CT_SCAN_PERIOD_CLKS = 2500000,
+    parameter integer HOST_INTER_BYTE_TIMEOUT_CLKS = 250000,
+    parameter integer HOST_IDLE_UNLOCK_CLKS = 1250000
 ) (
     input  wire        sys_clk,
     input  wire        host_rs232_rx,
@@ -147,7 +149,7 @@ module prod2u_6400_v1_top #(
         .clk(sys_clk), .rst_n(rst_n), .tick(tick_1s)
     );
 
-    host_port_selector u_host_select (
+    host_port_selector #(.IDLE_UNLOCK_CLKS(HOST_IDLE_UNLOCK_CLKS)) u_host_select (
         .clk(sys_clk), .rst_n(rst_n), .rs232_rx_async(host_rs232_rx),
         .ttl_rx_async(host_ttl_rx), .shared_tx(shared_host_tx),
         .transaction_done(host_transaction_done), .selected_rx(selected_host_rx),
@@ -159,7 +161,8 @@ module prod2u_6400_v1_top #(
         .clk(sys_clk), .rst_n(rst_n), .rx_i(selected_host_rx), .byte_valid(host_rx_valid),
         .byte_data(host_rx_data), .framing_error(host_rx_error)
     );
-    frame_rx #(.MAX_PAYLOAD(33), .INTER_BYTE_TIMEOUT_CYCLES(250000)) u_frame_rx (
+    frame_rx #(.MAX_PAYLOAD(33),
+        .INTER_BYTE_TIMEOUT_CYCLES(HOST_INTER_BYTE_TIMEOUT_CLKS)) u_frame_rx (
         .clk(sys_clk), .rst_n(rst_n), .byte_valid(host_rx_valid), .byte_data(host_rx_data),
         .accept_enable(frame_accept_enable), .frame_valid(frame_valid), .frame_ready(frame_ready),
         .frame_type(frame_type), .frame_length(frame_length), .payload_read_addr(payload_rd_addr),

+ 23 - 1
tests/cocotb/prod2u_6400_v1_cocotb_top.v

@@ -28,6 +28,11 @@ module prod2u_6400_v1_cocotb_top #(
     output wire [3:0]  lane_fault_mask_mon,
     output wire        global_fault_mon,
     output wire        stimulus_active_mon,
+    output wire [7:0]  current_target_mon,
+    output wire        host_locked_mon,
+    output wire        host_port_sel_mon,
+    output reg  [15:0] target_commit_count_mon,
+    output reg  [15:0] host_response_count_mon,
     output wire        pwm_boundary_mon,
     output wire [6:0]  pwm_phase_mon,
     output wire        pwm_deadline_miss_mon
@@ -41,7 +46,9 @@ module prod2u_6400_v1_cocotb_top #(
 
     prod2u_6400_v1_top #(
         .ENABLE_STIMULUS(ENABLE_STIMULUS),
-        .CT_SCAN_PERIOD_CLKS(64)
+        .CT_SCAN_PERIOD_CLKS(64),
+        .HOST_INTER_BYTE_TIMEOUT_CLKS(512),
+        .HOST_IDLE_UNLOCK_CLKS(1024)
     ) u_dut (
         .sys_clk(clk),
         .host_rs232_rx(host_rs232_rx),
@@ -79,7 +86,22 @@ module prod2u_6400_v1_cocotb_top #(
     assign lane_fault_mask_mon = u_dut.lane_fault_mask;
     assign global_fault_mon = u_dut.global_fault;
     assign stimulus_active_mon = u_dut.stimulus_active;
+    assign current_target_mon = u_dut.current_target;
+    assign host_locked_mon = u_dut.host_locked;
+    assign host_port_sel_mon = u_dut.host_port_sel;
     assign pwm_boundary_mon = u_dut.pwm_boundary;
     assign pwm_phase_mon = u_dut.pwm_phase;
     assign pwm_deadline_miss_mon = u_dut.pwm_deadline_miss;
+
+    always @(posedge clk or negedge u_dut.rst_n) begin
+        if (!u_dut.rst_n) begin
+            target_commit_count_mon <= 0;
+            host_response_count_mon <= 0;
+        end else begin
+            if (u_dut.target_commit)
+                target_commit_count_mon <= target_commit_count_mon + 1'b1;
+            if (u_dut.tx_start)
+                host_response_count_mon <= host_response_count_mon + 1'b1;
+        end
+    end
 endmodule

+ 16 - 4
tests/cocotb/run_6400_v1_integration.py

@@ -3,7 +3,9 @@
 
 from __future__ import annotations
 
+import argparse
 import json
+import os
 from pathlib import Path
 import tempfile
 import xml.etree.ElementTree as ET
@@ -26,6 +28,7 @@ def rtl_sources() -> list[Path]:
 
 
 def run_profile(name: str, enable_stimulus: int, build_dir: Path) -> None:
+    os.environ["HYPOTHESIS_STORAGE_DIRECTORY"] = str(build_dir / "hypothesis")
     runner = get_runner("icarus")
     runner.build(
         sources=[*rtl_sources(), WRAPPER],
@@ -55,12 +58,21 @@ def run_profile(name: str, enable_stimulus: int, build_dir: Path) -> None:
         )
 
 
-def main() -> int:
+def main(argv: list[str] | None = None) -> int:
+    parser = argparse.ArgumentParser()
+    parser.add_argument(
+        "profiles",
+        nargs="*",
+        choices=("control", "identification", "host_protocol"),
+        default=("control", "identification", "host_protocol"),
+    )
+    args = parser.parse_args(argv)
+    stimulus = {"control": 0, "identification": 1, "host_protocol": 0}
     with tempfile.TemporaryDirectory(prefix="prod2u-6400-cocotb-") as directory:
         root = Path(directory)
-        run_profile("control", 0, root / "control")
-        run_profile("identification", 1, root / "identification")
-    print("PASS: 6400 control and identification cocotb integration")
+        for profile in args.profiles:
+            run_profile(profile, stimulus[profile], root / profile)
+    print(f"PASS: 6400 cocotb integration profiles: {', '.join(args.profiles)}")
     return 0
 
 

+ 239 - 0
tests/cocotb/test_6400_v1_host_protocol_integration.py

@@ -0,0 +1,239 @@
+"""Randomized full-UART Host framing and resynchronization coverage."""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+import warnings
+
+import cocotb
+from cocotb.triggers import RisingEdge, Timer, with_timeout
+from hypothesis import HealthCheck, given, settings, strategies as st
+from hypothesis.errors import HypothesisSideeffectWarning
+
+from thermal_6400_uart import (
+    CLOCK_NS,
+    HOST_CLKS_PER_BIT,
+    SET_TARGET,
+    SET_TARGET_ACK,
+    clock_cycles,
+    crc16,
+    encode_frame,
+    receive_frame,
+    send_uart,
+    wait_for,
+)
+
+
+@dataclass(frozen=True)
+class FrameCase:
+    frame_type: int
+    declared_length: int
+    payload: bytes
+    good_crc: bool
+
+    @property
+    def accepted_target(self) -> int | None:
+        if not self.good_crc or self.frame_type != SET_TARGET or self.declared_length != 1:
+            return None
+        target = self.payload[0]
+        return target if target == 0 or 20 <= target <= 70 else None
+
+    def encode(self) -> bytes:
+        body = bytes((self.frame_type, self.declared_length)) + self.payload
+        checksum = crc16(body)
+        if not self.good_crc:
+            checksum ^= 0x0001
+        return b"\xA5\x5A" + body + checksum.to_bytes(2, "little")
+
+
+@st.composite
+def frame_cases(draw) -> FrameCase:
+    frame_type = draw(st.sampled_from((0x00, 0x01, 0x04, 0x7F, 0x80, 0x81, 0xFF)))
+    declared_length = draw(st.integers(min_value=0, max_value=255))
+    if declared_length <= 33:
+        payload = draw(st.binary(min_size=declared_length, max_size=declared_length))
+    else:
+        # RTL rejects the oversized declaration before consuming payload.  A
+        # bounded tail exercises recovery without letting an embedded header
+        # become a separate, accidental test case.
+        tail = draw(st.binary(min_size=0, max_size=12))
+        payload = tail.replace(b"\xA5", b"\xA4")
+    return FrameCase(frame_type, declared_length, payload, draw(st.booleans()))
+
+
+def generated_cases() -> list[FrameCase]:
+    values: list[FrameCase] = []
+
+    @settings(
+        max_examples=96,
+        derandomize=True,
+        database=None,
+        deadline=None,
+        suppress_health_check=(HealthCheck.too_slow,),
+    )
+    @given(frame_cases())
+    def collect(value: FrameCase) -> None:
+        values.append(value)
+
+    # Cocotb imports tests through its pytest plugin, then invokes this
+    # collector deliberately from the running coroutine.  Hypothesis warns
+    # about any strategy evaluation in plugin-owned code even though this is
+    # the test body and the database/storage are both isolated.
+    with warnings.catch_warnings():
+        warnings.simplefilter("ignore", HypothesisSideeffectWarning)
+        collect()
+    return values
+
+
+async def send_uart_with_period(signal, data: bytes, clocks_per_bit: int) -> None:
+    for value in data:
+        signal.value = 0
+        await Timer(clocks_per_bit * CLOCK_NS, units="ns")
+        for bit in range(8):
+            signal.value = (value >> bit) & 1
+            await Timer(clocks_per_bit * CLOCK_NS, units="ns")
+        signal.value = 1
+        await Timer(clocks_per_bit * CLOCK_NS, units="ns")
+
+
+async def send_uart_jittered(signal, data: bytes) -> None:
+    periods = (27, 26, 28, 27, 28, 26, 27, 26, 28, 27)
+    for value in data:
+        bits = (0, *((value >> bit) & 1 for bit in range(8)), 1)
+        for level, clocks in zip(bits, periods, strict=True):
+            signal.value = level
+            await Timer(clocks * CLOCK_NS, units="ns")
+
+
+async def wait_unlocked(dut) -> None:
+    await wait_for(
+        dut,
+        lambda: int(dut.host_locked_mon.value) == 0,
+        cycles=1800,
+        label="Host selector unlock",
+    )
+
+
+async def target_transaction(dut, target: int, sender=send_uart) -> None:
+    response = cocotb.start_soon(receive_frame(dut.host_rs232_tx))
+    frame = encode_frame(SET_TARGET, bytes((target,)))
+    if sender is send_uart:
+        await sender(dut.host_rs232_rx, frame, HOST_CLKS_PER_BIT)
+    else:
+        await sender(dut.host_rs232_rx, frame)
+    kind, payload = await with_timeout(response, 20, "ms")
+    assert (kind, payload) == (SET_TARGET_ACK, b"")
+    await Timer(HOST_CLKS_PER_BIT * CLOCK_NS * 2, units="ns")
+    await wait_unlocked(dut)
+    assert int(dut.current_target_mon.value) == target
+
+
+@cocotb.test()
+async def test_host_random_frames_timeout_resync_and_port_lock(dut):
+    dut.host_rs232_rx.value = 1
+    dut.host_ttl_rx.value = 1
+    dut.bmc_rs232_rx.value = 1
+    dut.tick_1s_test.value = 0
+    await with_timeout(RisingEdge(dut.rst_n_mon), 1, "ms")
+    await clock_cycles(dut, 8)
+
+    # Hypothesis supplies arbitrary declared lengths, payloads, CRC validity,
+    # legal targets, illegal targets, and unknown types.  Every invalid case
+    # is a silent drop and must leave both the target and response counters
+    # unchanged; valid target frames commit exactly once and ACK exactly once.
+    for case in generated_cases():
+        commits_before = int(dut.target_commit_count_mon.value)
+        responses_before = int(dut.host_response_count_mon.value)
+        target_before = int(dut.current_target_mon.value)
+        accepted = case.accepted_target
+        if accepted is not None:
+            response = cocotb.start_soon(receive_frame(dut.host_rs232_tx))
+            await send_uart(dut.host_rs232_rx, case.encode(), HOST_CLKS_PER_BIT)
+            assert await with_timeout(response, 20, "ms") == (SET_TARGET_ACK, b"")
+            await Timer(HOST_CLKS_PER_BIT * CLOCK_NS * 2, units="ns")
+        else:
+            await send_uart(dut.host_rs232_rx, case.encode(), HOST_CLKS_PER_BIT)
+        await wait_unlocked(dut)
+        if accepted is None:
+            assert int(dut.target_commit_count_mon.value) == commits_before
+            assert int(dut.host_response_count_mon.value) == responses_before
+            assert int(dut.current_target_mon.value) == target_before
+        else:
+            assert int(dut.target_commit_count_mon.value) == commits_before + 1
+            assert int(dut.host_response_count_mon.value) == responses_before + 1
+            assert int(dut.current_target_mon.value) == accepted
+        assert int(dut.host_rs232_tx.value) == 1
+        assert int(dut.host_ttl_tx.value) == 1
+
+    # Noise and overlapping A5 candidates must resynchronize to the next full
+    # header without resetting the UART or parser.
+    response = cocotb.start_soon(receive_frame(dut.host_rs232_tx))
+    noisy = b"\x00\xFF\xA5\xA5\x00\xA5" + encode_frame(SET_TARGET, b"\x3E")
+    await send_uart(dut.host_rs232_rx, noisy, HOST_CLKS_PER_BIT)
+    assert await with_timeout(response, 20, "ms") == (SET_TARGET_ACK, b"")
+    await Timer(HOST_CLKS_PER_BIT * CLOCK_NS * 2, units="ns")
+    await wait_unlocked(dut)
+    assert int(dut.current_target_mon.value) == 62
+
+    # A half-frame is discarded after the accelerated test timeout; the next
+    # valid frame must not inherit its type, length, payload, or CRC state.
+    commits_before = int(dut.target_commit_count_mon.value)
+    responses_before = int(dut.host_response_count_mon.value)
+    await send_uart(dut.host_rs232_rx, b"\xA5\x5A\x01\x01", HOST_CLKS_PER_BIT)
+    await clock_cycles(dut, 1200)
+    await wait_unlocked(dut)
+    assert int(dut.target_commit_count_mon.value) == commits_before
+    assert int(dut.host_response_count_mon.value) == responses_before
+    await target_transaction(dut, 61)
+
+    # There is no command queue: a second complete frame arriving while the
+    # first physical ACK is active is dropped, and a later retransmission is
+    # accepted after the response boundary retires.
+    commits_before = int(dut.target_commit_count_mon.value)
+    responses_before = int(dut.host_response_count_mon.value)
+    response = cocotb.start_soon(receive_frame(dut.host_rs232_tx))
+    await send_uart(dut.host_rs232_rx, encode_frame(SET_TARGET, b"\x14"), HOST_CLKS_PER_BIT)
+    await send_uart(dut.host_rs232_rx, encode_frame(SET_TARGET, b"\x46"), HOST_CLKS_PER_BIT)
+    assert await with_timeout(response, 20, "ms") == (SET_TARGET_ACK, b"")
+    await Timer(HOST_CLKS_PER_BIT * CLOCK_NS * 2, units="ns")
+    await wait_unlocked(dut)
+    assert int(dut.target_commit_count_mon.value) == commits_before + 1
+    assert int(dut.host_response_count_mon.value) == responses_before + 1
+    assert int(dut.current_target_mon.value) == 20
+    await target_transaction(dut, 70)
+
+    # Simultaneous start bits deterministically select RS-232 for the entire
+    # request/response lock.  TTL traffic cannot splice payload or steal TX.
+    commits_before = int(dut.target_commit_count_mon.value)
+    response = cocotb.start_soon(receive_frame(dut.host_rs232_tx))
+    rs232 = cocotb.start_soon(
+        send_uart(dut.host_rs232_rx, encode_frame(SET_TARGET, b"\x3C"), HOST_CLKS_PER_BIT)
+    )
+    ttl = cocotb.start_soon(
+        send_uart(dut.host_ttl_rx, encode_frame(SET_TARGET, b"\x46"), HOST_CLKS_PER_BIT)
+    )
+    await rs232
+    await ttl
+    assert await with_timeout(response, 20, "ms") == (SET_TARGET_ACK, b"")
+    assert int(dut.host_ttl_tx.value) == 1
+    await Timer(HOST_CLKS_PER_BIT * CLOCK_NS * 2, units="ns")
+    await wait_unlocked(dut)
+    assert int(dut.target_commit_count_mon.value) == commits_before + 1
+    assert int(dut.current_target_mon.value) == 60
+
+    # Integrate the raw UART tolerance proof with a legal frame: fixed -1/+1
+    # clock baud error and balanced per-bit jitter must preserve framing/CRC.
+    await target_transaction(dut, 64, lambda signal, data: send_uart_with_period(signal, data, 26))
+    await target_transaction(dut, 63, lambda signal, data: send_uart_with_period(signal, data, 28))
+    await target_transaction(dut, 65, send_uart_jittered)
+
+    # A declared 255-byte unknown frame plus a long zero tail is discarded
+    # without a response, state mutation, or loss of the next valid command.
+    commits_before = int(dut.target_commit_count_mon.value)
+    responses_before = int(dut.host_response_count_mon.value)
+    long_invalid = b"\xA5\x5A\x7F\xFF" + bytes(260)
+    await send_uart(dut.host_rs232_rx, long_invalid, HOST_CLKS_PER_BIT)
+    await wait_unlocked(dut)
+    assert int(dut.target_commit_count_mon.value) == commits_before
+    assert int(dut.host_response_count_mon.value) == responses_before
+    await target_transaction(dut, 66)