generate_6400_v1.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  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. if wire["responses"]["SNAPSHOT_DATA"].get("payload_length", snapshot_size) != snapshot_size:
  95. raise ValueError("snapshot length drift")
  96. forbidden = set(wire.get("forbidden_fields", []))
  97. if not {"protocol_version", "project_id", "sequence", "nack"}.issubset(forbidden):
  98. raise ValueError("forbidden field list incomplete")
  99. def crc16(data: bytes) -> int:
  100. crc = 0xFFFF
  101. for value in data:
  102. crc ^= value << 8
  103. for _ in range(8):
  104. crc = ((crc << 1) ^ 0x1021) & 0xFFFF if crc & 0x8000 else (crc << 1) & 0xFFFF
  105. return crc
  106. def frame(frame_type: int, payload: bytes) -> str:
  107. body = bytes((frame_type, len(payload))) + payload
  108. crc = crc16(body)
  109. return (b"\xA5\x5A" + body + bytes((crc & 0xFF, crc >> 8))).hex().upper()
  110. def json_bytes(value: Any) -> bytes:
  111. return (json.dumps(value, indent=2, sort_keys=True, ensure_ascii=False) + "\n").encode()
  112. 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:
  113. command = wire["commands"]
  114. response = wire["responses"]
  115. limits = coeff["limits_centi_degC"]
  116. target = coeff["targets_centi_degC"]
  117. classes = coeff["classes"]
  118. lines = [
  119. "`ifndef PROD2U_6400_V1_PARAMS_VH",
  120. "`define PROD2U_6400_V1_PARAMS_VH",
  121. f"// Generated contract SHA-256: {contract_sha}",
  122. "`define FB_CLOCK_HZ 25000000",
  123. "`define FB_PTC_COUNT 24",
  124. "`define FB_FRONT_FAN_COUNT 4",
  125. "`define FB_REAR_FAN_COUNT 4",
  126. "`define FB_OUTPUT_COUNT 32",
  127. "`define FB_BMC_COUNT 24",
  128. "`define FB_CT_COUNT 27",
  129. "`define FB_PRIMARY_COUNT 18",
  130. "`define FB_HOLDOUT_COUNT 6",
  131. "`define FB_HOST_BAUD 921600",
  132. "`define FB_BMC_BAUD 115200",
  133. "`define FB_HOST_FIXED_CLKS_PER_BIT 27",
  134. "`define FB_BMC_CLKS_PER_BIT 217",
  135. "`define FB_PWM_PHASES 100",
  136. "`define FB_PWM_PHASE_CLKS 500",
  137. "`define FB_PWM_PERIOD_CLKS 50000",
  138. f"`define FB_CMD_SET_TARGET 8'h{int(command['SET_TARGET']['type']):02X}",
  139. f"`define FB_CMD_GET_SNAPSHOT 8'h{int(command['GET_SNAPSHOT']['type']):02X}",
  140. f"`define FB_CMD_SET_STIMULUS 8'h{int(command['SET_STIMULUS']['type']):02X}",
  141. f"`define FB_RSP_SET_TARGET_ACK 8'h{int(response['SET_TARGET_ACK']['type']):02X}",
  142. f"`define FB_RSP_SNAPSHOT 8'h{int(response['SNAPSHOT_DATA']['type']):02X}",
  143. f"`define FB_RSP_STIMULUS_ACK 8'h{int(response['SET_STIMULUS_ACK']['type']):02X}",
  144. f"`define FB_SNAPSHOT_LENGTH {snapshot_size}",
  145. f"`define FB_TEMP_SOFT {int(limits['soft'])}",
  146. f"`define FB_TEMP_PRETRIP {int(limits['pretrip'])}",
  147. f"`define FB_TEMP_HARD {int(limits['hard'])}",
  148. f"`define FB_TEMP_DEFAULT_TARGET {int(target['default'])}",
  149. f"`define FB_EDGE_KP_Q4_12 {int(classes['EDGE']['kp_q4_12'])}",
  150. f"`define FB_EDGE_KI_Q4_12 {int(classes['EDGE']['ki_q4_12'])}",
  151. f"`define FB_CENTER_KP_Q4_12 {int(classes['CENTER']['kp_q4_12'])}",
  152. f"`define FB_CENTER_KI_Q4_12 {int(classes['CENTER']['ki_q4_12'])}",
  153. f"`define FB_FAN_RESET {int(fan['duty']['reset'])}",
  154. f"`define FB_FAN_HARD {int(fan['duty']['hard'])}",
  155. ]
  156. for row in layout_rows:
  157. macro = row["name"].upper()
  158. lines.append(f"`define FB_SNAPSHOT_{macro}_OFFSET {row['offset']}")
  159. lines.extend(["`endif", ""])
  160. return "\n".join(lines).encode()
  161. def channel_markdown(mapping: dict[str, Any], contract_sha: str) -> bytes:
  162. lines = [
  163. "# Generated 6400 channel map",
  164. "",
  165. f"Contract SHA-256: `{contract_sha}`.",
  166. "",
  167. "| DIMM | CPU slot | Lane | Zone | PTC | BMC | CT | Cohort |",
  168. "| ---: | --- | ---: | ---: | ---: | ---: | --- | --- |",
  169. ]
  170. for row in mapping["channels"]:
  171. cohort = "primary" if row["primary_cohort"] else "holdout"
  172. lines.append(
  173. f"| {row['logical_dimm']} | CPU{row['cpu']}/{row['cpu_slot']} | {row['air_lane']} | "
  174. f"{row['thermal_zone']} | {row['ptc_channel']} | {row['bmc_temperature_index']} | "
  175. f"{row['ct7428_channel']} | {cohort} |"
  176. )
  177. lines.extend(["", "CT physical placement is explicitly unknown until board evidence closes it.", ""])
  178. return "\n".join(lines).encode()
  179. def generate(output: Path) -> dict[Path, bytes]:
  180. mapping = load_yaml("channel-map.yaml")
  181. wire = load_yaml("6400-wire.yaml")
  182. snapshot = load_yaml("6400-snapshot.yaml")
  183. fixed = load_yaml("6400-fixed-point.yaml")
  184. coeff = load_yaml("controller-coefficients.yaml")
  185. fan = load_yaml("fan-control-parameters.yaml")
  186. validate_channels(mapping)
  187. layout_rows, snapshot_size = layout(snapshot)
  188. validate_wire(wire, snapshot_size)
  189. contract_sha = source_hash()
  190. snapshot_layout = {"schema": snapshot["schema"], "byte_order": "little", "payload_length": snapshot_size, "fields": layout_rows, "contract_sha256": contract_sha}
  191. golden = {
  192. "schema": "prod2u-6400-golden-vectors-v1",
  193. "contract_sha256": contract_sha,
  194. "frames": {
  195. "set_target_stop": frame(0x01, bytes((0,))),
  196. "set_target_20": frame(0x01, bytes((20,))),
  197. "set_target_70": frame(0x01, bytes((70,))),
  198. "get_snapshot": frame(0x02, b""),
  199. "set_target_ack": frame(0x81, b""),
  200. "stimulus_all_zero_one_second": frame(0x03, bytes((1,)) + bytes(32)),
  201. "stimulus_ack": frame(0x83, b""),
  202. },
  203. }
  204. host = {
  205. "schema": "prod2u-6400-host-contract-v1",
  206. "contract_sha256": contract_sha,
  207. "wire": wire,
  208. "snapshot": snapshot_layout,
  209. "channel_map": mapping,
  210. "fixed_point": fixed,
  211. "controller_coefficients": coeff,
  212. "fan_control": fan,
  213. "golden_vectors": golden,
  214. }
  215. files = {
  216. output / "channel-map.json": json_bytes({**mapping, "contract_sha256": contract_sha}),
  217. output / "snapshot-layout.json": json_bytes(snapshot_layout),
  218. output / "fixed-point.json": json_bytes({**fixed, "contract_sha256": contract_sha}),
  219. output / "controller-coefficients.json": json_bytes({**coeff, "contract_sha256": contract_sha}),
  220. output / "fan-control-parameters.json": json_bytes({**fan, "contract_sha256": contract_sha}),
  221. output / "golden-vectors.json": json_bytes(golden),
  222. output / "host-contract.json": json_bytes(host),
  223. output / "prod2u_6400_v1_params.vh": verilog_header(layout_rows, snapshot_size, wire, coeff, fan, contract_sha),
  224. output / "contract-sha256.txt": (contract_sha + "\n").encode(),
  225. ROOT / "docs/generated/6400-channel-map.md": channel_markdown(mapping, contract_sha),
  226. }
  227. return files
  228. def main() -> int:
  229. parser = argparse.ArgumentParser()
  230. parser.add_argument("--output", type=Path, default=DEFAULT_OUTPUT)
  231. parser.add_argument("--check", action="store_true")
  232. args = parser.parse_args()
  233. expected = generate(args.output)
  234. drift: list[str] = []
  235. for path, content in expected.items():
  236. if args.check:
  237. if not path.exists() or path.read_bytes() != content:
  238. drift.append(str(path.relative_to(ROOT)))
  239. else:
  240. path.parent.mkdir(parents=True, exist_ok=True)
  241. if not path.exists() or path.read_bytes() != content:
  242. path.write_bytes(content)
  243. if drift:
  244. print("generated drift: " + ", ".join(drift), file=sys.stderr)
  245. return 1
  246. print(f"PASS: {len(expected)} generated files")
  247. return 0
  248. if __name__ == "__main__":
  249. try:
  250. sys.exit(main())
  251. except (KeyError, TypeError, ValueError, yaml.YAMLError) as exc:
  252. print(f"ERROR: {exc}", file=sys.stderr)
  253. sys.exit(2)