| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284 |
- #!/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")
- if wire["commands"]["SET_TARGET"]["payload_length"] != 1:
- raise ValueError("SET_TARGET length drift")
- if wire["responses"]["SNAPSHOT_DATA"].get("payload_length", snapshot_size) != snapshot_size:
- raise ValueError("snapshot length drift")
- forbidden = set(wire.get("forbidden_fields", []))
- if not {"protocol_version", "project_id", "sequence", "nack"}.issubset(forbidden):
- raise ValueError("forbidden field list incomplete")
- 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], contract_sha: str) -> bytes:
- command = wire["commands"]
- response = wire["responses"]
- limits = coeff["limits_centi_degC"]
- target = coeff["targets_centi_degC"]
- classes = coeff["classes"]
- 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",
- "`define FB_PWM_PHASES 100",
- "`define FB_PWM_PHASE_CLKS 500",
- "`define FB_PWM_PERIOD_CLKS 50000",
- f"`define FB_CMD_SET_TARGET 8'h{int(command['SET_TARGET']['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_RSP_SET_TARGET_ACK 8'h{int(response['SET_TARGET_ACK']['type']):02X}",
- f"`define FB_RSP_SNAPSHOT 8'h{int(response['SNAPSHOT_DATA']['type']):02X}",
- f"`define FB_RSP_STIMULUS_ACK 8'h{int(response['SET_STIMULUS_ACK']['type']):02X}",
- f"`define FB_SNAPSHOT_LENGTH {snapshot_size}",
- f"`define FB_TEMP_SOFT {int(limits['soft'])}",
- f"`define FB_TEMP_PRETRIP {int(limits['pretrip'])}",
- f"`define FB_TEMP_HARD {int(limits['hard'])}",
- 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 FB_FAN_RESET {int(fan['duty']['reset'])}",
- f"`define FB_FAN_HARD {int(fan['duty']['hard'])}",
- ]
- 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)
- 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_target_stop": frame(0x01, bytes((0,))),
- "set_target_20": frame(0x01, bytes((20,))),
- "set_target_70": frame(0x01, bytes((70,))),
- "get_snapshot": frame(0x02, b""),
- "set_target_ack": frame(0x81, b""),
- "stimulus_all_zero_one_second": frame(0x03, bytes((1,)) + bytes(32)),
- "stimulus_ack": frame(0x83, b""),
- },
- }
- host = {
- "schema": "prod2u-6400-host-contract-v1",
- "contract_sha256": contract_sha,
- "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, 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)
|