#!/usr/bin/env python3 """Generate every 6400 wire/layout mapping from the YAML contract set.""" from __future__ import annotations import argparse import hashlib import json from pathlib import Path import sys from typing import Any import yaml ROOT = Path(__file__).resolve().parents[1] CONTRACT_DIR = ROOT / "contracts" DEFAULT_OUTPUT = ROOT / "generated" / "6400" INPUTS = ( "channel-map.yaml", "6400-wire.yaml", "6400-snapshot.yaml", "6400-fixed-point.yaml", "controller-coefficients.yaml", "fan-control-parameters.yaml", ) TYPE_BYTES = {"u8": 1, "u16": 2, "u32": 4, "bytes": 1} def load_yaml(name: str) -> dict[str, Any]: value = yaml.safe_load((CONTRACT_DIR / name).read_text(encoding="utf-8")) if not isinstance(value, dict): raise ValueError(f"{name}: root must be mapping") return value def source_hash() -> str: digest = hashlib.sha256() for name in INPUTS: digest.update(name.encode()) digest.update(b"\0") digest.update((CONTRACT_DIR / name).read_bytes()) digest.update(b"\0") return digest.hexdigest() def validate_channels(mapping: dict[str, Any]) -> None: rows = mapping.get("channels") if not isinstance(rows, list) or len(rows) != 24: raise ValueError("channel map must contain 24 rows") required = { "logical_dimm", "cpu", "cpu_slot", "air_lane", "thermal_zone", "ptc_channel", "bmc_temperature_index", "ct7428_channel", "front_fan_channel", "rear_fan_channel", "primary_cohort", "enabled", "physical_label", "evidence", } for row in rows: missing = required - set(row) if missing: raise ValueError(f"channel missing fields: {sorted(missing)}") for field in ("logical_dimm", "ptc_channel", "bmc_temperature_index"): values = [int(row[field]) for row in rows] if sorted(values) != list(range(24)): raise ValueError(f"{field} must be unique 0..23") for index, row in enumerate(rows): lane = index // 6 expected_zone = 0 if lane == 0 else (1 if lane in (1, 2) else 2) if int(row["logical_dimm"]) != index: raise ValueError("channel rows must be logical order") if int(row["air_lane"]) != lane or int(row["thermal_zone"]) != expected_zone: raise ValueError(f"lane/zone mismatch at {index}") if int(row["front_fan_channel"]) != lane or int(row["rear_fan_channel"]) != lane: raise ValueError(f"fan mapping mismatch at {index}") if bool(row["primary_cohort"]) != (index < 18): raise ValueError(f"cohort mismatch at {index}") ct = row["ct7428_channel"] if ct != "unknown" and (not isinstance(ct, int) or not 0 <= ct < 27): raise ValueError(f"invalid CT mapping at {index}") def layout(snapshot: dict[str, Any]) -> tuple[list[dict[str, Any]], int]: offset = 0 rows: list[dict[str, Any]] = [] seen: set[str] = set() for field in snapshot.get("fields", []): name = field["name"] kind = field["type"] count = int(field.get("count", 1)) if name in seen or kind not in TYPE_BYTES or count <= 0: raise ValueError(f"invalid snapshot field: {field}") seen.add(name) size = TYPE_BYTES[kind] * count row = dict(field) row.update({"offset": offset, "size": size}) rows.append(row) offset += size if offset > int(snapshot["max_payload_bytes"]): raise ValueError(f"snapshot payload {offset} exceeds maximum") return rows, offset def validate_wire(wire: dict[str, Any], snapshot_size: int) -> None: if wire["clock_hz"] != 25_000_000 or wire["device"] != "EF2L45BG256B": raise ValueError("device/clock drift") if wire["host_uart"]["baud"] != 921_600 or wire["bmc_uart"]["baud"] != 115_200: raise ValueError("UART baud drift") expected_ids = {"SET_ALL": 0x01, "GET_SNAPSHOT": 0x02, "SET_STIMULUS": 0x03, "SET_PID_TARGET": 0x04} actual_ids = {name: int(value["type"]) for name, value in wire["commands"].items()} if actual_ids != expected_ids or len(set(actual_ids.values())) != len(actual_ids): raise ValueError("active command registry drift or duplicate command id") if wire["commands"]["SET_ALL"]["payload_length"] != 32: raise ValueError("SET_ALL length drift") stimulus_fields = wire["commands"]["SET_STIMULUS"].get("payload_fields", []) expected_stimulus_fields = [ {"name": "duration_seconds", "offset": 0, "count": 1, "minimum": 1, "maximum": 255, "unit": "seconds"}, {"name": "ptc_duty_percent", "offset": 1, "count": 24, "minimum": 0, "maximum": 100, "unit": "percent"}, {"name": "front_fan_duty_percent", "offset": 25, "count": 4, "minimum": 0, "maximum": 100, "unit": "percent"}, {"name": "rear_fan_duty_percent", "offset": 29, "count": 4, "minimum": 0, "maximum": 100, "unit": "percent"}, ] if stimulus_fields != expected_stimulus_fields: raise ValueError("SET_STIMULUS payload layout drift") ack = wire["responses"]["ACK_NACK"] if ack.get("type") != 0x06 or ack.get("payload_length") != 4: raise ValueError("unified ACK/NACK drift") if ack.get("payload") != ["ok", "request_type", "status", "detail"]: raise ValueError("ACK/NACK payload drift") if wire["responses"]["SNAPSHOT_DATA"].get("type") != 0x82: raise ValueError("SNAPSHOT_DATA type drift") if wire["responses"]["SNAPSHOT_DATA"].get("payload_length", snapshot_size) != snapshot_size: raise ValueError("snapshot length drift") pid = wire["commands"]["SET_PID_TARGET"] if (pid.get("payload_length"), pid.get("minimum"), pid.get("maximum"), pid.get("default")) != (1, 20, 70, 70): raise ValueError("PID target contract drift") def validate_fans(mapping: dict[str, Any], fan: dict[str, Any]) -> None: if mapping.get("board") != { "id": "fcb_fpga_mcu_v1_1_20260625", "evidence_source": "external:FCB_FPGA+MCU_V1.1_20260625.brd", "evidence_sha256": "db02938f7943b2ae532aa18208f61588364d32a70a0cc72f74b4a94aaab7e258", "independent_v1_1_schematic_pdf": "NOT_FOUND", "airflow_roles": "USER_CONFIRMED_SYSTEM_MAP", }: raise ValueError("V1.1 board identity/evidence drift") if mapping.get("fan_output_vector_order") != [ "front0", "front1", "front2", "front3", "rear0", "rear1", "rear2", "rear3", ]: raise ValueError("fan physical vector order drift") expected_front = ( (24, 0, "CON25", 7, "FAN_PWM3", "BANK5_IO1_8", "R652", "N10451185", "Q101", "B1", True), (25, 1, "CON8", 7, "FAN_PWM1", "BANK0_IO1_2", "R646", "N9745627", "Q99", "C4", True), (26, 2, "CON24", 7, "FAN_PWM2", "BANK0_IO1_5", "R649", "N10449541", "Q100", "B5", True), (27, 3, "CON26", 7, "FAN_PWM4", "BANK0_IO1_11", "R655", "N10452692", "Q102", "A14", True), ) expected_rear = ( (28, 0, "CON64", 4, "FAN_GPIO44", "BANK2_GPIO44", "R704", "FAN_GPIO44", "R704_0R_DESIGN_INTENT_POPULATION_UNVERIFIED", "P15", False), (29, 1, "CON66", 4, "FAN_GPIO46", "BANK2_GPIO46", "R706", "FAN_GPIO46", "R706_0R_DESIGN_INTENT_POPULATION_UNVERIFIED", "N15", False), (30, 2, "CON62", 4, "FAN_GPIO42", "BANK2_GPIO42", "R702", "FAN_GPIO42", "R702_0R_DESIGN_INTENT_POPULATION_UNVERIFIED", "M14", False), (31, 3, "CON60", 4, "FAN_GPIO40", "BANK2_GPIO40", "R700", "FAN_GPIO40", "R700_0R_DESIGN_INTENT_POPULATION_UNVERIFIED", "P5", False), ) rows = mapping.get("fan_outputs", []) forbidden_connectors = {"CON31", "CON32", "CON33", "CON34", "CON35", "CON68"} if forbidden_connectors & {str(row.get("connector")) for row in rows}: raise ValueError("obsolete 8000/CON31-35/68 fan mapping is forbidden in 6400") for name, expected in (("front", expected_front), ("rear", expected_rear)): actual = tuple( (int(row["output_index"]), int(row["lane"]), row["connector"], int(row["pin"]), row["net"], row["fpga_net"], row["series_element"], row["connector_net"], row["board_stage"], row["fpga_ball"], bool(row["board_inverts"])) for row in rows if row.get("group") == name ) if actual != expected: raise ValueError(f"{name} fan physical mapping drift") invert_mask = sum(1 << (int(row["output_index"]) - 24) for row in rows if row["board_inverts"]) if invert_mask != 0x0F: raise ValueError("fan board invert mask must be 0x0F for grouped front/rear vector") pwm = fan.get("pwm", {}) if pwm.get("ptc_hz") != 500 or pwm.get("fan_hz") != 500: raise ValueError("current PTC/FAN PWM frequencies must independently equal 500 Hz") if pwm.get("ptc_phase_clks") != 500 or pwm.get("fan_phase_clks") != 500: raise ValueError("current PTC/FAN phase clocks must independently equal 500") if pwm.get("carrier_backend") != "shared_equal_frequency_control_reset_independent_v2": raise ValueError("current equal-frequency carrier backend drift") safe_states = ("reset", "boot", "standby", "watchdog", "pid_wait_sensor", "ordinary_fault") if any(fan["duty"].get(name) != 20 for name in safe_states): raise ValueError("all non-hard-protect safe fan duties must remain 20") if fan.get("board_invert_mask") != 0x0F or fan.get("connector_duty_semantics") != "high_level_percent": raise ValueError("connector fan duty / board invert contract drift") def crc16(data: bytes) -> int: crc = 0xFFFF for value in data: crc ^= value << 8 for _ in range(8): crc = ((crc << 1) ^ 0x1021) & 0xFFFF if crc & 0x8000 else (crc << 1) & 0xFFFF return crc def frame(frame_type: int, payload: bytes) -> str: body = bytes((frame_type, len(payload))) + payload crc = crc16(body) return (b"\xA5\x5A" + body + bytes((crc & 0xFF, crc >> 8))).hex().upper() def json_bytes(value: Any) -> bytes: return (json.dumps(value, indent=2, sort_keys=True, ensure_ascii=False) + "\n").encode() def verilog_header(layout_rows: list[dict[str, Any]], snapshot_size: int, wire: dict[str, Any], coeff: dict[str, Any], fan: dict[str, Any], mapping: dict[str, Any], contract_sha: str) -> bytes: command = wire["commands"] response = wire["responses"] limits = coeff["limits_centi_degC"] target = coeff["targets_centi_degC"] classes = coeff["classes"] fan_invert_mask = sum( 1 << (int(row["output_index"]) - 24) for row in mapping["fan_outputs"] if row["board_inverts"] ) fan_rows = sorted(mapping["fan_outputs"], key=lambda row: int(row["output_index"])) front_rows = [row for row in fan_rows if row["group"] == "front"] rear_rows = [row for row in fan_rows if row["group"] == "rear"] def connector_map(rows: list[dict[str, Any]]) -> str: return ",".join(f"{row['connector']}.{int(row['pin'])}" for row in rows) def ball_map(rows: list[dict[str, Any]]) -> str: return ",".join(str(row["fpga_ball"]) for row in rows) lines = [ "`ifndef PROD2U_6400_V1_PARAMS_VH", "`define PROD2U_6400_V1_PARAMS_VH", f"// Generated contract SHA-256: {contract_sha}", "`define FB_CLOCK_HZ 25000000", "`define FB_PTC_COUNT 24", "`define FB_FRONT_FAN_COUNT 4", "`define FB_REAR_FAN_COUNT 4", "`define FB_OUTPUT_COUNT 32", "`define FB_BMC_COUNT 24", "`define FB_CT_COUNT 27", "`define FB_PRIMARY_COUNT 18", "`define FB_HOLDOUT_COUNT 6", "`define FB_HOST_BAUD 921600", "`define FB_BMC_BAUD 115200", "`define FB_HOST_FIXED_CLKS_PER_BIT 27", "`define FB_BMC_CLKS_PER_BIT 217", f"`define FB_PWM_PHASES {int(fan['pwm']['phases'])}", f"`define FB_PTC_PWM_HZ {int(fan['pwm']['ptc_hz'])}", f"`define FB_FAN_PWM_HZ {int(fan['pwm']['fan_hz'])}", f"`define FB_PTC_PWM_PHASE_CLKS {int(fan['pwm']['ptc_phase_clks'])}", f"`define FB_FAN_PWM_PHASE_CLKS {int(fan['pwm']['fan_phase_clks'])}", f"`define FB_PTC_PWM_PERIOD_CLKS {int(fan['pwm']['ptc_phase_clks']) * int(fan['pwm']['phases'])}", f"`define FB_FAN_PWM_PERIOD_CLKS {int(fan['pwm']['fan_phase_clks']) * int(fan['pwm']['phases'])}", f"`define FAN_BOARD_INVERT_MASK 8'h{fan_invert_mask:02X}", f"`define FRONT_FAN_CONNECTOR_MAP \"{connector_map(front_rows)}\"", f"`define FRONT_FAN_FPGA_BALL_MAP \"{ball_map(front_rows)}\"", f"`define REAR_FAN_CONNECTOR_MAP \"{connector_map(rear_rows)}\"", f"`define REAR_FAN_FPGA_BALL_MAP \"{ball_map(rear_rows)}\"", f"`define FB_BOARD_ID \"{mapping['board']['id']}\"", f"`define FB_BOARD_EVIDENCE_SHA256 \"{mapping['board']['evidence_sha256']}\"", f"`define FB_CMD_SET_ALL 8'h{int(command['SET_ALL']['type']):02X}", f"`define FB_CMD_GET_SNAPSHOT 8'h{int(command['GET_SNAPSHOT']['type']):02X}", f"`define FB_CMD_SET_STIMULUS 8'h{int(command['SET_STIMULUS']['type']):02X}", f"`define FB_CMD_SET_PID_TARGET 8'h{int(command['SET_PID_TARGET']['type']):02X}", f"`define FB_RSP_ACK_NACK 8'h{int(response['ACK_NACK']['type']):02X}", f"`define FB_RSP_SNAPSHOT_DATA 8'h{int(response['SNAPSHOT_DATA']['type']):02X}", "`define FB_STATUS_OK 8'd0", "`define FB_STATUS_UNSUPPORTED 8'd1", "`define FB_STATUS_BAD_LENGTH 8'd2", "`define FB_STATUS_BAD_VALUE 8'd3", "`define FB_STATUS_SAFETY_LOCKED 8'd4", f"`define FB_SNAPSHOT_LENGTH {snapshot_size}", f"`define FB_TEMP_CHANNEL_CLAMP {int(limits['channel_clamp'])}", f"`define FB_TEMP_LANE_HARD {int(limits['lane_hard'])}", f"`define FB_TEMP_LANE_RELEASE {int(limits['lane_release'])}", f"`define FB_TEMP_DEFAULT_TARGET {int(target['default'])}", f"`define FB_EDGE_KP_Q4_12 {int(classes['EDGE']['kp_q4_12'])}", f"`define FB_EDGE_KI_Q4_12 {int(classes['EDGE']['ki_q4_12'])}", f"`define FB_CENTER_KP_Q4_12 {int(classes['CENTER']['kp_q4_12'])}", f"`define FB_CENTER_KI_Q4_12 {int(classes['CENTER']['ki_q4_12'])}", f"`define FAN_SAFE_DUTY {int(fan['duty']['reset'])}", "`define FAN_STANDBY_DUTY `FAN_SAFE_DUTY", "`define FB_FAN_RESET `FAN_STANDBY_DUTY", f"`define FB_FAN_HARD {int(fan['duty']['hard'])}", "`define CONTROL_WATCHDOG_SECONDS 30", "`define SET_ALL_WATCHDOG_SECONDS `CONTROL_WATCHDOG_SECONDS", "`define DEFAULT_PID_TARGET_C 70", "`define FB_OWNER_SAFE 3'd0", "`define FB_OWNER_MANUAL 3'd1", "`define FB_OWNER_PID 3'd2", ] for row in layout_rows: macro = row["name"].upper() lines.append(f"`define FB_SNAPSHOT_{macro}_OFFSET {row['offset']}") lines.extend(["`endif", ""]) return "\n".join(lines).encode() def channel_markdown(mapping: dict[str, Any], contract_sha: str) -> bytes: lines = [ "# Generated 6400 channel map", "", f"Contract SHA-256: `{contract_sha}`.", "", "| DIMM | CPU slot | Lane | Zone | PTC | BMC | CT | Cohort |", "| ---: | --- | ---: | ---: | ---: | ---: | --- | --- |", ] for row in mapping["channels"]: cohort = "primary" if row["primary_cohort"] else "holdout" lines.append( f"| {row['logical_dimm']} | CPU{row['cpu']}/{row['cpu_slot']} | {row['air_lane']} | " f"{row['thermal_zone']} | {row['ptc_channel']} | {row['bmc_temperature_index']} | " f"{row['ct7428_channel']} | {cohort} |" ) lines.extend(["", "CT physical placement is explicitly unknown until board evidence closes it.", ""]) return "\n".join(lines).encode() def generate(output: Path) -> dict[Path, bytes]: mapping = load_yaml("channel-map.yaml") wire = load_yaml("6400-wire.yaml") snapshot = load_yaml("6400-snapshot.yaml") fixed = load_yaml("6400-fixed-point.yaml") coeff = load_yaml("controller-coefficients.yaml") fan = load_yaml("fan-control-parameters.yaml") validate_channels(mapping) validate_fans(mapping, fan) layout_rows, snapshot_size = layout(snapshot) validate_wire(wire, snapshot_size) contract_sha = source_hash() snapshot_layout = {"schema": snapshot["schema"], "byte_order": "little", "payload_length": snapshot_size, "fields": layout_rows, "contract_sha256": contract_sha} golden = { "schema": "prod2u-6400-golden-vectors-v1", "contract_sha256": contract_sha, "frames": { "set_all_safe": frame(0x01, bytes(24) + bytes((20,)) * 8), "set_all_0_20_50_100": frame(0x01, bytes(range(24)) + bytes((0, 20, 50, 100, 0, 20, 50, 100))), "get_snapshot": frame(0x02, b""), "set_pid_target_70": frame(0x04, bytes((70,))), "set_all_ack": frame(0x06, bytes((1, 0x01, 0, 0))), "get_snapshot_ack": frame(0x06, bytes((1, 0x02, 0, 0))), "set_pid_target_ack": frame(0x06, bytes((1, 0x04, 0, 0))), "unsupported_03_nack": frame(0x06, bytes((0, 0x03, 1, 0))), "bad_length_01_nack": frame(0x06, bytes((0, 0x01, 2, 32))), "bad_value_01_index_7_nack": frame(0x06, bytes((0, 0x01, 3, 7))), "safety_locked_01_nack": frame(0x06, bytes((0, 0x01, 4, 0))), "stimulus_all_zero_one_second": frame(0x03, bytes((1,)) + bytes(32)), "stimulus_ack": frame(0x06, bytes((1, 0x03, 0, 0))), }, } canonical_profiles = { "6400-front-rear": { "allowed_commands": ["SET_ALL", "GET_SNAPSHOT", "SET_PID_TARGET"], "production": True, "stimulus": False, "simulation_only": False, }, } host = { "schema": "prod2u-6400-host-contract-v3", "contract_sha256": contract_sha, "canonical_profiles": canonical_profiles, "wire": wire, "snapshot": snapshot_layout, "channel_map": mapping, "fixed_point": fixed, "controller_coefficients": coeff, "fan_control": fan, "golden_vectors": golden, } files = { output / "channel-map.json": json_bytes({**mapping, "contract_sha256": contract_sha}), output / "snapshot-layout.json": json_bytes(snapshot_layout), output / "fixed-point.json": json_bytes({**fixed, "contract_sha256": contract_sha}), output / "controller-coefficients.json": json_bytes({**coeff, "contract_sha256": contract_sha}), output / "fan-control-parameters.json": json_bytes({**fan, "contract_sha256": contract_sha}), output / "golden-vectors.json": json_bytes(golden), output / "host-contract.json": json_bytes(host), output / "prod2u_6400_v1_params.vh": verilog_header(layout_rows, snapshot_size, wire, coeff, fan, mapping, contract_sha), output / "contract-sha256.txt": (contract_sha + "\n").encode(), ROOT / "docs/generated/6400-channel-map.md": channel_markdown(mapping, contract_sha), } return files def main() -> int: parser = argparse.ArgumentParser() parser.add_argument("--output", type=Path, default=DEFAULT_OUTPUT) parser.add_argument("--check", action="store_true") args = parser.parse_args() expected = generate(args.output) drift: list[str] = [] for path, content in expected.items(): if args.check: if not path.exists() or path.read_bytes() != content: drift.append(str(path.relative_to(ROOT))) else: path.parent.mkdir(parents=True, exist_ok=True) if not path.exists() or path.read_bytes() != content: path.write_bytes(content) if drift: print("generated drift: " + ", ".join(drift), file=sys.stderr) return 1 print(f"PASS: {len(expected)} generated files") return 0 if __name__ == "__main__": try: sys.exit(main()) except (KeyError, TypeError, ValueError, yaml.YAMLError) as exc: print(f"ERROR: {exc}", file=sys.stderr) sys.exit(2)