generate_6400_v1.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400
  1. #!/usr/bin/env python3
  2. """Generate every 6400 wire/layout mapping from the YAML contract set."""
  3. from __future__ import annotations
  4. import argparse
  5. import hashlib
  6. import json
  7. from pathlib import Path
  8. import sys
  9. from typing import Any
  10. import yaml
  11. ROOT = Path(__file__).resolve().parents[1]
  12. CONTRACT_DIR = ROOT / "contracts"
  13. DEFAULT_OUTPUT = ROOT / "generated" / "6400"
  14. INPUTS = (
  15. "channel-map.yaml",
  16. "6400-wire.yaml",
  17. "6400-snapshot.yaml",
  18. "6400-fixed-point.yaml",
  19. "controller-coefficients.yaml",
  20. "fan-control-parameters.yaml",
  21. )
  22. TYPE_BYTES = {"u8": 1, "u16": 2, "u32": 4, "bytes": 1}
  23. def load_yaml(name: str) -> dict[str, Any]:
  24. value = yaml.safe_load((CONTRACT_DIR / name).read_text(encoding="utf-8"))
  25. if not isinstance(value, dict):
  26. raise ValueError(f"{name}: root must be mapping")
  27. return value
  28. def source_hash() -> str:
  29. digest = hashlib.sha256()
  30. for name in INPUTS:
  31. digest.update(name.encode())
  32. digest.update(b"\0")
  33. digest.update((CONTRACT_DIR / name).read_bytes())
  34. digest.update(b"\0")
  35. return digest.hexdigest()
  36. def validate_channels(mapping: dict[str, Any]) -> None:
  37. rows = mapping.get("channels")
  38. if not isinstance(rows, list) or len(rows) != 24:
  39. raise ValueError("channel map must contain 24 rows")
  40. required = {
  41. "logical_dimm", "cpu", "cpu_slot", "air_lane", "thermal_zone",
  42. "ptc_channel", "bmc_temperature_index", "ct7428_channel",
  43. "front_fan_channel", "rear_fan_channel", "primary_cohort", "enabled",
  44. "physical_label", "evidence",
  45. }
  46. for row in rows:
  47. missing = required - set(row)
  48. if missing:
  49. raise ValueError(f"channel missing fields: {sorted(missing)}")
  50. for field in ("logical_dimm", "ptc_channel", "bmc_temperature_index"):
  51. values = [int(row[field]) for row in rows]
  52. if sorted(values) != list(range(24)):
  53. raise ValueError(f"{field} must be unique 0..23")
  54. for index, row in enumerate(rows):
  55. lane = index // 6
  56. expected_zone = 0 if lane == 0 else (1 if lane in (1, 2) else 2)
  57. if int(row["logical_dimm"]) != index:
  58. raise ValueError("channel rows must be logical order")
  59. if int(row["air_lane"]) != lane or int(row["thermal_zone"]) != expected_zone:
  60. raise ValueError(f"lane/zone mismatch at {index}")
  61. if int(row["front_fan_channel"]) != lane or int(row["rear_fan_channel"]) != lane:
  62. raise ValueError(f"fan mapping mismatch at {index}")
  63. if bool(row["primary_cohort"]) != (index < 18):
  64. raise ValueError(f"cohort mismatch at {index}")
  65. ct = row["ct7428_channel"]
  66. if ct != "unknown" and (not isinstance(ct, int) or not 0 <= ct < 27):
  67. raise ValueError(f"invalid CT mapping at {index}")
  68. def layout(snapshot: dict[str, Any]) -> tuple[list[dict[str, Any]], int]:
  69. offset = 0
  70. rows: list[dict[str, Any]] = []
  71. seen: set[str] = set()
  72. for field in snapshot.get("fields", []):
  73. name = field["name"]
  74. kind = field["type"]
  75. count = int(field.get("count", 1))
  76. if name in seen or kind not in TYPE_BYTES or count <= 0:
  77. raise ValueError(f"invalid snapshot field: {field}")
  78. seen.add(name)
  79. size = TYPE_BYTES[kind] * count
  80. row = dict(field)
  81. row.update({"offset": offset, "size": size})
  82. rows.append(row)
  83. offset += size
  84. if offset > int(snapshot["max_payload_bytes"]):
  85. raise ValueError(f"snapshot payload {offset} exceeds maximum")
  86. return rows, offset
  87. def validate_wire(wire: dict[str, Any], snapshot_size: int) -> None:
  88. if wire["clock_hz"] != 25_000_000 or wire["device"] != "EF2L45BG256B":
  89. raise ValueError("device/clock drift")
  90. if wire["host_uart"]["baud"] != 921_600 or wire["bmc_uart"]["baud"] != 115_200:
  91. raise ValueError("UART baud drift")
  92. if wire["commands"]["SET_TARGET"]["payload_length"] != 1:
  93. raise ValueError("SET_TARGET length drift")
  94. stimulus_fields = wire["commands"]["SET_STIMULUS"].get("payload_fields", [])
  95. expected_stimulus_fields = [
  96. {"name": "duration_seconds", "offset": 0, "count": 1, "minimum": 1, "maximum": 255, "unit": "seconds"},
  97. {"name": "ptc_duty_percent", "offset": 1, "count": 24, "minimum": 0, "maximum": 100, "unit": "percent"},
  98. {"name": "front_fan_duty_percent", "offset": 25, "count": 4, "minimum": 0, "maximum": 100, "unit": "percent"},
  99. {"name": "rear_fan_duty_percent", "offset": 29, "count": 4, "minimum": 0, "maximum": 100, "unit": "percent"},
  100. ]
  101. if stimulus_fields != expected_stimulus_fields:
  102. raise ValueError("SET_STIMULUS payload layout drift")
  103. if wire["responses"]["GET_SNAPSHOT_ACK"] != {"type": 0x82, "payload_length": 0}:
  104. raise ValueError("GET_SNAPSHOT independent ACK drift")
  105. if wire["responses"]["SNAPSHOT_DATA"].get("type") != 0x42:
  106. raise ValueError("SNAPSHOT_DATA must be request type OR 0x40")
  107. if wire["responses"]["SNAPSHOT_DATA"].get("payload_length", snapshot_size) != snapshot_size:
  108. raise ValueError("snapshot length drift")
  109. forbidden = set(wire.get("forbidden_fields", []))
  110. if not {"protocol_version", "project_id", "sequence", "nack"}.issubset(forbidden):
  111. raise ValueError("forbidden field list incomplete")
  112. def validate_fans(mapping: dict[str, Any], fan: dict[str, Any]) -> None:
  113. if mapping.get("board") != {
  114. "id": "fcb_fpga_mcu_v1_1_20260625",
  115. "evidence_source": "external:FCB_FPGA+MCU_V1.1_20260625.brd",
  116. "evidence_sha256": "db02938f7943b2ae532aa18208f61588364d32a70a0cc72f74b4a94aaab7e258",
  117. "independent_v1_1_schematic_pdf": "NOT_FOUND",
  118. "airflow_roles": "USER_CONFIRMED_SYSTEM_MAP",
  119. }:
  120. raise ValueError("V1.1 board identity/evidence drift")
  121. if mapping.get("fan_output_vector_order") != [
  122. "front0", "front1", "front2", "front3",
  123. "rear0", "rear1", "rear2", "rear3",
  124. ]:
  125. raise ValueError("fan physical vector order drift")
  126. expected_front = (
  127. (24, 0, "CON25", 7, "FAN_PWM3", "BANK5_IO1_8", "R652", "N10451185", "Q101", "B1", True),
  128. (25, 1, "CON8", 7, "FAN_PWM1", "BANK0_IO1_2", "R646", "N9745627", "Q99", "C4", True),
  129. (26, 2, "CON24", 7, "FAN_PWM2", "BANK0_IO1_5", "R649", "N10449541", "Q100", "B5", True),
  130. (27, 3, "CON26", 7, "FAN_PWM4", "BANK0_IO1_11", "R655", "N10452692", "Q102", "A14", True),
  131. )
  132. expected_rear = (
  133. (28, 0, "CON64", 4, "FAN_GPIO44", "BANK2_GPIO44", "R704", "FAN_GPIO44", "R704_0R_DESIGN_INTENT_POPULATION_UNVERIFIED", "P15", False),
  134. (29, 1, "CON66", 4, "FAN_GPIO46", "BANK2_GPIO46", "R706", "FAN_GPIO46", "R706_0R_DESIGN_INTENT_POPULATION_UNVERIFIED", "N15", False),
  135. (30, 2, "CON62", 4, "FAN_GPIO42", "BANK2_GPIO42", "R702", "FAN_GPIO42", "R702_0R_DESIGN_INTENT_POPULATION_UNVERIFIED", "M14", False),
  136. (31, 3, "CON60", 4, "FAN_GPIO40", "BANK2_GPIO40", "R700", "FAN_GPIO40", "R700_0R_DESIGN_INTENT_POPULATION_UNVERIFIED", "P5", False),
  137. )
  138. rows = mapping.get("fan_outputs", [])
  139. forbidden_connectors = {"CON31", "CON32", "CON33", "CON34", "CON35", "CON68"}
  140. if forbidden_connectors & {str(row.get("connector")) for row in rows}:
  141. raise ValueError("obsolete 8000/CON31-35/68 fan mapping is forbidden in 6400")
  142. for name, expected in (("front", expected_front), ("rear", expected_rear)):
  143. actual = tuple(
  144. (int(row["output_index"]), int(row["lane"]), row["connector"], int(row["pin"]),
  145. row["net"], row["fpga_net"], row["series_element"], row["connector_net"],
  146. row["board_stage"], row["fpga_ball"], bool(row["board_inverts"]))
  147. for row in rows if row.get("group") == name
  148. )
  149. if actual != expected:
  150. raise ValueError(f"{name} fan physical mapping drift")
  151. invert_mask = sum(1 << (int(row["output_index"]) - 24) for row in rows if row["board_inverts"])
  152. if invert_mask != 0x0F:
  153. raise ValueError("fan board invert mask must be 0x0F for grouped front/rear vector")
  154. pwm = fan.get("pwm", {})
  155. if pwm.get("ptc_hz") != 500 or pwm.get("fan_hz") != 500:
  156. raise ValueError("current PTC/FAN PWM frequencies must independently equal 500 Hz")
  157. if pwm.get("ptc_phase_clks") != 500 or pwm.get("fan_phase_clks") != 500:
  158. raise ValueError("current PTC/FAN phase clocks must independently equal 500")
  159. if pwm.get("carrier_backend") != "shared_equal_frequency_v1":
  160. raise ValueError("current equal-frequency carrier backend drift")
  161. if fan["duty"].get("reset") != 10 or fan["duty"].get("stopped") != 10:
  162. raise ValueError("reset and STOPPED fan standby duty must remain 10")
  163. def crc16(data: bytes) -> int:
  164. crc = 0xFFFF
  165. for value in data:
  166. crc ^= value << 8
  167. for _ in range(8):
  168. crc = ((crc << 1) ^ 0x1021) & 0xFFFF if crc & 0x8000 else (crc << 1) & 0xFFFF
  169. return crc
  170. def frame(frame_type: int, payload: bytes) -> str:
  171. body = bytes((frame_type, len(payload))) + payload
  172. crc = crc16(body)
  173. return (b"\xA5\x5A" + body + bytes((crc & 0xFF, crc >> 8))).hex().upper()
  174. def json_bytes(value: Any) -> bytes:
  175. return (json.dumps(value, indent=2, sort_keys=True, ensure_ascii=False) + "\n").encode()
  176. 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:
  177. command = wire["commands"]
  178. response = wire["responses"]
  179. limits = coeff["limits_centi_degC"]
  180. target = coeff["targets_centi_degC"]
  181. classes = coeff["classes"]
  182. fan_invert_mask = sum(
  183. 1 << (int(row["output_index"]) - 24)
  184. for row in mapping["fan_outputs"] if row["board_inverts"]
  185. )
  186. fan_rows = sorted(mapping["fan_outputs"], key=lambda row: int(row["output_index"]))
  187. front_rows = [row for row in fan_rows if row["group"] == "front"]
  188. rear_rows = [row for row in fan_rows if row["group"] == "rear"]
  189. def connector_map(rows: list[dict[str, Any]]) -> str:
  190. return ",".join(f"{row['connector']}.{int(row['pin'])}" for row in rows)
  191. def ball_map(rows: list[dict[str, Any]]) -> str:
  192. return ",".join(str(row["fpga_ball"]) for row in rows)
  193. lines = [
  194. "`ifndef PROD2U_6400_V1_PARAMS_VH",
  195. "`define PROD2U_6400_V1_PARAMS_VH",
  196. f"// Generated contract SHA-256: {contract_sha}",
  197. "`define FB_CLOCK_HZ 25000000",
  198. "`define FB_PTC_COUNT 24",
  199. "`define FB_FRONT_FAN_COUNT 4",
  200. "`define FB_REAR_FAN_COUNT 4",
  201. "`define FB_OUTPUT_COUNT 32",
  202. "`define FB_BMC_COUNT 24",
  203. "`define FB_CT_COUNT 27",
  204. "`define FB_PRIMARY_COUNT 18",
  205. "`define FB_HOLDOUT_COUNT 6",
  206. "`define FB_HOST_BAUD 921600",
  207. "`define FB_BMC_BAUD 115200",
  208. "`define FB_HOST_FIXED_CLKS_PER_BIT 27",
  209. "`define FB_BMC_CLKS_PER_BIT 217",
  210. f"`define FB_PWM_PHASES {int(fan['pwm']['phases'])}",
  211. f"`define FB_PTC_PWM_HZ {int(fan['pwm']['ptc_hz'])}",
  212. f"`define FB_FAN_PWM_HZ {int(fan['pwm']['fan_hz'])}",
  213. f"`define FB_PTC_PWM_PHASE_CLKS {int(fan['pwm']['ptc_phase_clks'])}",
  214. f"`define FB_FAN_PWM_PHASE_CLKS {int(fan['pwm']['fan_phase_clks'])}",
  215. f"`define FB_PTC_PWM_PERIOD_CLKS {int(fan['pwm']['ptc_phase_clks']) * int(fan['pwm']['phases'])}",
  216. f"`define FB_FAN_PWM_PERIOD_CLKS {int(fan['pwm']['fan_phase_clks']) * int(fan['pwm']['phases'])}",
  217. f"`define FAN_BOARD_INVERT_MASK 8'h{fan_invert_mask:02X}",
  218. f"`define FRONT_FAN_CONNECTOR_MAP \"{connector_map(front_rows)}\"",
  219. f"`define FRONT_FAN_FPGA_BALL_MAP \"{ball_map(front_rows)}\"",
  220. f"`define REAR_FAN_CONNECTOR_MAP \"{connector_map(rear_rows)}\"",
  221. f"`define REAR_FAN_FPGA_BALL_MAP \"{ball_map(rear_rows)}\"",
  222. f"`define FB_BOARD_ID \"{mapping['board']['id']}\"",
  223. f"`define FB_BOARD_EVIDENCE_SHA256 \"{mapping['board']['evidence_sha256']}\"",
  224. f"`define FB_CMD_SET_TARGET 8'h{int(command['SET_TARGET']['type']):02X}",
  225. f"`define FB_CMD_GET_SNAPSHOT 8'h{int(command['GET_SNAPSHOT']['type']):02X}",
  226. f"`define FB_CMD_SET_STIMULUS 8'h{int(command['SET_STIMULUS']['type']):02X}",
  227. f"`define FB_RSP_SET_TARGET_ACK 8'h{int(response['SET_TARGET_ACK']['type']):02X}",
  228. f"`define FB_RSP_GET_SNAPSHOT_ACK 8'h{int(response['GET_SNAPSHOT_ACK']['type']):02X}",
  229. f"`define FB_RSP_SNAPSHOT_DATA 8'h{int(response['SNAPSHOT_DATA']['type']):02X}",
  230. f"`define FB_RSP_STIMULUS_ACK 8'h{int(response['SET_STIMULUS_ACK']['type']):02X}",
  231. f"`define FB_SNAPSHOT_LENGTH {snapshot_size}",
  232. f"`define FB_TEMP_SOFT {int(limits['soft'])}",
  233. f"`define FB_TEMP_PRETRIP {int(limits['pretrip'])}",
  234. f"`define FB_TEMP_HARD {int(limits['hard'])}",
  235. f"`define FB_TEMP_DEFAULT_TARGET {int(target['default'])}",
  236. f"`define FB_EDGE_KP_Q4_12 {int(classes['EDGE']['kp_q4_12'])}",
  237. f"`define FB_EDGE_KI_Q4_12 {int(classes['EDGE']['ki_q4_12'])}",
  238. f"`define FB_CENTER_KP_Q4_12 {int(classes['CENTER']['kp_q4_12'])}",
  239. f"`define FB_CENTER_KI_Q4_12 {int(classes['CENTER']['ki_q4_12'])}",
  240. f"`define FAN_STANDBY_DUTY {int(fan['duty']['reset'])}",
  241. "`define FB_FAN_RESET `FAN_STANDBY_DUTY",
  242. f"`define FB_FAN_HARD {int(fan['duty']['hard'])}",
  243. ]
  244. for row in layout_rows:
  245. macro = row["name"].upper()
  246. lines.append(f"`define FB_SNAPSHOT_{macro}_OFFSET {row['offset']}")
  247. lines.extend(["`endif", ""])
  248. return "\n".join(lines).encode()
  249. def channel_markdown(mapping: dict[str, Any], contract_sha: str) -> bytes:
  250. lines = [
  251. "# Generated 6400 channel map",
  252. "",
  253. f"Contract SHA-256: `{contract_sha}`.",
  254. "",
  255. "| DIMM | CPU slot | Lane | Zone | PTC | BMC | CT | Cohort |",
  256. "| ---: | --- | ---: | ---: | ---: | ---: | --- | --- |",
  257. ]
  258. for row in mapping["channels"]:
  259. cohort = "primary" if row["primary_cohort"] else "holdout"
  260. lines.append(
  261. f"| {row['logical_dimm']} | CPU{row['cpu']}/{row['cpu_slot']} | {row['air_lane']} | "
  262. f"{row['thermal_zone']} | {row['ptc_channel']} | {row['bmc_temperature_index']} | "
  263. f"{row['ct7428_channel']} | {cohort} |"
  264. )
  265. lines.extend(["", "CT physical placement is explicitly unknown until board evidence closes it.", ""])
  266. return "\n".join(lines).encode()
  267. def generate(output: Path) -> dict[Path, bytes]:
  268. mapping = load_yaml("channel-map.yaml")
  269. wire = load_yaml("6400-wire.yaml")
  270. snapshot = load_yaml("6400-snapshot.yaml")
  271. fixed = load_yaml("6400-fixed-point.yaml")
  272. coeff = load_yaml("controller-coefficients.yaml")
  273. fan = load_yaml("fan-control-parameters.yaml")
  274. validate_channels(mapping)
  275. validate_fans(mapping, fan)
  276. layout_rows, snapshot_size = layout(snapshot)
  277. validate_wire(wire, snapshot_size)
  278. contract_sha = source_hash()
  279. snapshot_layout = {"schema": snapshot["schema"], "byte_order": "little", "payload_length": snapshot_size, "fields": layout_rows, "contract_sha256": contract_sha}
  280. golden = {
  281. "schema": "prod2u-6400-golden-vectors-v1",
  282. "contract_sha256": contract_sha,
  283. "frames": {
  284. "set_target_stop": frame(0x01, bytes((0,))),
  285. "set_target_20": frame(0x01, bytes((20,))),
  286. "set_target_70": frame(0x01, bytes((70,))),
  287. "get_snapshot": frame(0x02, b""),
  288. "set_target_ack": frame(0x81, b""),
  289. "get_snapshot_ack": frame(0x82, b""),
  290. "stimulus_all_zero_one_second": frame(0x03, bytes((1,)) + bytes(32)),
  291. "stimulus_ack": frame(0x83, b""),
  292. },
  293. }
  294. canonical_profiles = {
  295. "6400-control": {
  296. "allowed_commands": ["SET_TARGET", "GET_SNAPSHOT"],
  297. "production": True,
  298. "stimulus": False,
  299. "simulation_only": False,
  300. },
  301. "6400-identification": {
  302. "allowed_commands": ["SET_TARGET", "GET_SNAPSHOT", "SET_STIMULUS"],
  303. "production": False,
  304. "stimulus": True,
  305. "simulation_only": False,
  306. },
  307. "6400-sim-debug": {
  308. "allowed_commands": ["SET_TARGET", "GET_SNAPSHOT", "SET_STIMULUS"],
  309. "production": False,
  310. "stimulus": True,
  311. "simulation_only": True,
  312. },
  313. }
  314. host = {
  315. "schema": "prod2u-6400-host-contract-v2",
  316. "contract_sha256": contract_sha,
  317. "canonical_profiles": canonical_profiles,
  318. "wire": wire,
  319. "snapshot": snapshot_layout,
  320. "channel_map": mapping,
  321. "fixed_point": fixed,
  322. "controller_coefficients": coeff,
  323. "fan_control": fan,
  324. "golden_vectors": golden,
  325. }
  326. files = {
  327. output / "channel-map.json": json_bytes({**mapping, "contract_sha256": contract_sha}),
  328. output / "snapshot-layout.json": json_bytes(snapshot_layout),
  329. output / "fixed-point.json": json_bytes({**fixed, "contract_sha256": contract_sha}),
  330. output / "controller-coefficients.json": json_bytes({**coeff, "contract_sha256": contract_sha}),
  331. output / "fan-control-parameters.json": json_bytes({**fan, "contract_sha256": contract_sha}),
  332. output / "golden-vectors.json": json_bytes(golden),
  333. output / "host-contract.json": json_bytes(host),
  334. output / "prod2u_6400_v1_params.vh": verilog_header(layout_rows, snapshot_size, wire, coeff, fan, mapping, contract_sha),
  335. output / "contract-sha256.txt": (contract_sha + "\n").encode(),
  336. ROOT / "docs/generated/6400-channel-map.md": channel_markdown(mapping, contract_sha),
  337. }
  338. return files
  339. def main() -> int:
  340. parser = argparse.ArgumentParser()
  341. parser.add_argument("--output", type=Path, default=DEFAULT_OUTPUT)
  342. parser.add_argument("--check", action="store_true")
  343. args = parser.parse_args()
  344. expected = generate(args.output)
  345. drift: list[str] = []
  346. for path, content in expected.items():
  347. if args.check:
  348. if not path.exists() or path.read_bytes() != content:
  349. drift.append(str(path.relative_to(ROOT)))
  350. else:
  351. path.parent.mkdir(parents=True, exist_ok=True)
  352. if not path.exists() or path.read_bytes() != content:
  353. path.write_bytes(content)
  354. if drift:
  355. print("generated drift: " + ", ".join(drift), file=sys.stderr)
  356. return 1
  357. print(f"PASS: {len(expected)} generated files")
  358. return 0
  359. if __name__ == "__main__":
  360. try:
  361. sys.exit(main())
  362. except (KeyError, TypeError, ValueError, yaml.YAMLError) as exc:
  363. print(f"ERROR: {exc}", file=sys.stderr)
  364. sys.exit(2)