pin_inventory.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621
  1. #!/usr/bin/env python3
  2. """Pin inventory, IO budget, and ADC guardrails for UART/RS232 migration."""
  3. from __future__ import annotations
  4. import argparse
  5. import json
  6. import sys
  7. from datetime import datetime, timezone
  8. from pathlib import Path
  9. from typing import Any
  10. ROOT = Path(__file__).resolve().parents[1]
  11. LOCKED_DEBUG_UART_ASSIGNMENTS = {
  12. "bmc_uart_tx": "T4",
  13. "bmc_uart_rx": "R5",
  14. "host_uart_tx": "P7",
  15. "host_uart_rx": "P8",
  16. "debug_uart_rx": "P10",
  17. "debug_uart_tx": "R10",
  18. }
  19. TEMP_UART_PTC_REMAP_SUBSTITUTIONS = {
  20. "PTC03": {"signal": "ptc_pwm_out[2]", "substitute_ball": "P5", "bank_io_net": "BANK2_GPIO40"},
  21. "PTC04": {"signal": "ptc_pwm_out[3]", "substitute_ball": "T8", "bank_io_net": "BANK2_GPIO41"},
  22. "PTC17": {"signal": "ptc_pwm_out[16]", "substitute_ball": "M14", "bank_io_net": "BANK2_GPIO42"},
  23. "PTC18": {"signal": "ptc_pwm_out[17]", "substitute_ball": "M15", "bank_io_net": "BANK2_GPIO43"},
  24. "PTC21": {"signal": "ptc_pwm_out[20]", "substitute_ball": "P15", "bank_io_net": "BANK2_GPIO44"},
  25. "PTC22": {"signal": "ptc_pwm_out[21]", "substitute_ball": "N14", "bank_io_net": "BANK2_GPIO45"},
  26. }
  27. FORMAL_UART_ASSIGNMENTS = {
  28. "bmc_uart_tx": "P5",
  29. "bmc_uart_rx": "T8",
  30. "host_uart_tx": "M14",
  31. "host_uart_rx": "M15",
  32. "debug_uart_rx": "P15",
  33. "debug_uart_tx": "N14",
  34. }
  35. FORMAL_UART1_BMC_REPLAY_ASSIGNMENTS = {
  36. "bmc_uart_tx": "L10",
  37. "bmc_uart_rx": "M9",
  38. "host_uart_tx": "M10",
  39. "host_uart_rx": "N11",
  40. "debug_uart_rx": "P15",
  41. "debug_uart_tx": "N14",
  42. }
  43. FORMAL_UART1_BMC_REPLAY_BINARY921_ASSIGNMENTS = {
  44. "bmc_uart_tx": "L10",
  45. "bmc_uart_rx": "M9",
  46. "host_uart_tx": "M10",
  47. "host_uart_rx": "N11",
  48. "debug_uart_rx": "M14",
  49. "debug_uart_tx": "M15",
  50. }
  51. PRODUCTION_TWO_UART_BMC_REPLAY_BINARY921_ASSIGNMENTS = {
  52. "bmc_uart_tx": "L10",
  53. "bmc_uart_rx": "M9",
  54. "host_uart_tx": "M10",
  55. "host_uart_rx": "N11",
  56. }
  57. RESERVED_FUTURE_UART_SIGNALS = ["UART1_TX", "UART1_RX", "UART2_TX", "UART2_RX"]
  58. REQUIRED_IO_GROUPS = [
  59. {"name": "ptc_pwm[23:0]", "count": 24, "reason": "24 HEAT/PTC PWM outputs"},
  60. {"name": "fan_pwm[3:0]", "count": 4, "reason": "4 FAN_PWM drive outputs"},
  61. {"name": "fan_fg[7:0]", "count": 8, "reason": "8 FAN_FG tachometer inputs"},
  62. {"name": "fan_install[3:0]", "count": 4, "reason": "4 FAN_INSTALL presence inputs"},
  63. {"name": "bmc_uart(rx,tx)", "count": 2, "reason": "temporary J6 BMC UART debug wiring"},
  64. {"name": "debug_uart(rx,tx)", "count": 2, "reason": "temporary COM7 P10/R10 debug UART"},
  65. {"name": "host_uart(rx,tx)", "count": 2, "reason": "temporary COM8 P7/P8 host-control UART"},
  66. ]
  67. def utc_now() -> str:
  68. return datetime.now(timezone.utc).isoformat(timespec="seconds").replace("+00:00", "Z")
  69. def load_pin_inventory(path: Path | str) -> dict[str, Any]:
  70. inventory_path = Path(path)
  71. return json.loads(inventory_path.read_text(encoding="utf-8"))
  72. def _available_gpio_pins(inventory: dict[str, Any]) -> list[dict[str, Any]]:
  73. pins = []
  74. for pin in inventory.get("pins", []):
  75. capabilities = set(pin.get("capability") or [])
  76. role = pin.get("role")
  77. if pin.get("reserved"):
  78. continue
  79. if role not in {"user_io", "HEAT", "FAN_PWM", "FAN_FG", "FAN_INSTALL"}:
  80. continue
  81. if "gpio" not in capabilities:
  82. continue
  83. pins.append(pin)
  84. return pins
  85. def build_io_budget(inventory: dict[str, Any]) -> dict[str, Any]:
  86. required_total = sum(int(item["count"]) for item in REQUIRED_IO_GROUPS)
  87. available_gpio = _available_gpio_pins(inventory)
  88. verified_gpio = [pin for pin in available_gpio if pin.get("manually_verified") is True]
  89. required_groups = {item["name"]: {"count": item["count"], "reason": item["reason"]} for item in REQUIRED_IO_GROUPS}
  90. locked_conflicts = check_locked_uart_conflicts(inventory)
  91. if inventory.get("status") == "product_pin_map_missing":
  92. status = "blocked_product_pin_map_missing"
  93. elif locked_conflicts["status"] != "pass":
  94. status = locked_conflicts["status"]
  95. elif len(verified_gpio) < required_total:
  96. status = "blocked_unverified_or_insufficient_io"
  97. else:
  98. status = "pass"
  99. return {
  100. "schema": "cpld-io-budget-v1",
  101. "generated_at": utc_now(),
  102. "board_id": inventory.get("board_id"),
  103. "status": status,
  104. "required_groups": required_groups,
  105. "required_signals_total": required_total,
  106. "available_gpio_count": len(available_gpio),
  107. "verified_gpio_count": len(verified_gpio),
  108. "product_thermal_gate_allowed": bool(inventory.get("product_thermal_gate_allowed")),
  109. "locked_uart_conflicts": locked_conflicts["conflicts"],
  110. "authority_boundary": "Budget proves only signal count feasibility. It does not prove connector orientation, voltage, current drive, or product thermal safety.",
  111. }
  112. def real_fan_ptc_assignments(inventory: dict[str, Any]) -> dict[str, str]:
  113. assignments: dict[str, str] = {}
  114. for pin in inventory.get("pins", []):
  115. signal = str(pin.get("signal") or "")
  116. ball = str(pin.get("fpga_ball") or "")
  117. if not signal or not ball:
  118. continue
  119. role = str(pin.get("role") or "")
  120. channel = int(pin.get("channel") or 0)
  121. if role == "HEAT" and 1 <= channel <= 24:
  122. assignments[f"ptc_pwm_out[{channel - 1}]"] = ball
  123. elif role == "FAN_PWM" and 1 <= channel <= 4:
  124. assignments[f"fan_pwm_out[{channel - 1}]"] = ball
  125. elif role == "FAN_FG" and 1 <= channel <= 8:
  126. assignments[f"fan_fg_in[{channel - 1}]"] = ball
  127. elif role == "FAN_INSTALL" and 1 <= channel <= 4:
  128. assignments[f"fan_install_in[{channel - 1}]"] = ball
  129. return dict(sorted(assignments.items()))
  130. def check_locked_uart_conflicts(inventory: dict[str, Any]) -> dict[str, Any]:
  131. locked_by_ball = {ball: signal for signal, ball in LOCKED_DEBUG_UART_ASSIGNMENTS.items()}
  132. conflicts: list[dict[str, Any]] = []
  133. for pin in inventory.get("pins", []):
  134. ball = str(pin.get("fpga_ball") or "")
  135. if ball not in locked_by_ball:
  136. continue
  137. role = str(pin.get("role") or "")
  138. if role not in {"HEAT", "FAN_PWM", "FAN_FG", "FAN_INSTALL"}:
  139. continue
  140. conflicts.append(
  141. {
  142. "function_net": pin.get("function_net") or pin.get("signal"),
  143. "signal": pin.get("signal"),
  144. "role": role,
  145. "channel": pin.get("channel"),
  146. "fpga_ball": ball,
  147. "locked_signal": locked_by_ball[ball],
  148. "bank_io_net": pin.get("bank_io_net"),
  149. "source_pages": pin.get("source_pages"),
  150. }
  151. )
  152. return {
  153. "schema": "cpld-locked-uart-conflict-check-v1",
  154. "generated_at": utc_now(),
  155. "board_id": inventory.get("board_id"),
  156. "locked_uart_assignments": LOCKED_DEBUG_UART_ASSIGNMENTS,
  157. "status": "blocked_pin_conflict_with_locked_debug_uart" if conflicts else "pass",
  158. "conflicts": conflicts,
  159. "authority_boundary": "A real FAN/PTC bitstream cannot bind a schematic function and a locked temporary UART to the same FPGA ball.",
  160. }
  161. def _pin_by_ball(inventory: dict[str, Any]) -> dict[str, dict[str, Any]]:
  162. return {str(pin.get("fpga_ball")): pin for pin in inventory.get("pins", []) if pin.get("fpga_ball")}
  163. def _pin_by_signal(inventory: dict[str, Any]) -> dict[str, dict[str, Any]]:
  164. return {str(pin.get("signal")): pin for pin in inventory.get("pins", []) if pin.get("signal")}
  165. def _pin_ref(pin: dict[str, Any] | None, *, role: str | None = None) -> dict[str, Any]:
  166. if pin is None:
  167. return {"status": "missing"}
  168. payload: dict[str, Any] = {
  169. "signal": pin.get("signal"),
  170. "function_net": pin.get("function_net"),
  171. "bank_io_net": pin.get("bank_io_net"),
  172. "fpga_ball": pin.get("fpga_ball"),
  173. "role": role or pin.get("role"),
  174. "direction": pin.get("direction"),
  175. "io_standard": pin.get("io_standard"),
  176. "source_pages": pin.get("source_pages"),
  177. "manually_verified": pin.get("manually_verified") is True,
  178. "reserved": pin.get("reserved") is True,
  179. }
  180. if pin.get("capability") is not None:
  181. payload["capability"] = pin.get("capability")
  182. return payload
  183. def _reserved_future_uart(inventory: dict[str, Any]) -> dict[str, dict[str, Any]]:
  184. pins_by_signal = _pin_by_signal(inventory)
  185. return {name: _pin_ref(pins_by_signal.get(name), role="reserved_future_uart") for name in RESERVED_FUTURE_UART_SIGNALS}
  186. def _uart_assignment_rows(
  187. inventory: dict[str, Any],
  188. assignments: dict[str, str],
  189. *,
  190. aliases: dict[str, str] | None = None,
  191. ) -> dict[str, dict[str, Any]]:
  192. pins_by_ball = _pin_by_ball(inventory)
  193. rows: dict[str, dict[str, Any]] = {}
  194. for signal, ball in assignments.items():
  195. pin = pins_by_ball.get(ball)
  196. rows[signal] = _pin_ref(pin, role="uart")
  197. rows[signal]["fpga_ball"] = ball
  198. for alias, signal in (aliases or {}).items():
  199. if signal not in assignments:
  200. continue
  201. ball = assignments[signal]
  202. pin = pins_by_ball.get(ball)
  203. rows[alias] = _pin_ref(pin, role="uart")
  204. rows[alias]["fpga_ball"] = ball
  205. rows[alias]["hdl_signal"] = signal
  206. return rows
  207. def _ptc_substitution_rows(
  208. inventory: dict[str, Any],
  209. assignments: dict[str, str],
  210. *,
  211. reason: str = "temporary_uart_overlap_remap",
  212. ) -> dict[str, dict[str, Any]]:
  213. real_assignments = real_fan_ptc_assignments(inventory)
  214. pins_by_ball = _pin_by_ball(inventory)
  215. rows: dict[str, dict[str, Any]] = {}
  216. for label, subst in TEMP_UART_PTC_REMAP_SUBSTITUTIONS.items():
  217. signal = subst["signal"]
  218. original_ball = real_assignments.get(signal)
  219. substitute_ball = subst["substitute_ball"]
  220. rows[label] = {
  221. "signal": signal,
  222. "function_net": f"HEAT{int(label[3:])}",
  223. "original_ball": original_ball,
  224. "substitute_ball": substitute_ball,
  225. "substitute_bank_io_net": subst["bank_io_net"],
  226. "active_ball": assignments.get(signal),
  227. "substitute_pin": _pin_ref(pins_by_ball.get(substitute_ball), role="HEAT_substitute"),
  228. "reason": reason,
  229. }
  230. return rows
  231. def diagnostic_profile_assignments(inventory: dict[str, Any], profile: str) -> dict[str, Any]:
  232. """Return complete board assignments for the active diagnostic profiles."""
  233. supported_profiles = {
  234. "temp-uart-ptc-remap",
  235. "formal-uart",
  236. "debug-photo-uart-bmc-replay",
  237. "formal-uart1-bmc-replay",
  238. "debug-photo-bmc-replay-binary921",
  239. "formal-uart1-bmc-replay-binary921",
  240. "production-two-uart-bmc-replay-binary921",
  241. "prod2u-bmc-replay-binary921",
  242. "prod2u-fan-tach-binary921-v2",
  243. }
  244. if profile not in supported_profiles:
  245. return {
  246. "schema": "cpld-diagnostic-pin-profile-v1",
  247. "generated_at": utc_now(),
  248. "board_id": inventory.get("board_id"),
  249. "profile": profile,
  250. "status": "fail_unknown_profile",
  251. "assignments": {},
  252. "errors": [f"unknown_profile:{profile}"],
  253. }
  254. assignments = real_fan_ptc_assignments(inventory)
  255. bmc_source = "live_bmc_j6_uart"
  256. live_bmc_link_status = "used"
  257. hardware_access_status = "not_run"
  258. reserved_uart_use_policy = "reserved_unused"
  259. uart_aliases: dict[str, str] = {}
  260. allowed_reserved_balls: set[str] = set()
  261. profile4_fan_tach = profile == "prod2u-fan-tach-binary921-v2"
  262. production_profile = profile in {
  263. "production-two-uart-bmc-replay-binary921",
  264. "prod2u-bmc-replay-binary921",
  265. "prod2u-fan-tach-binary921-v2",
  266. }
  267. if profile in {"temp-uart-ptc-remap", "debug-photo-uart-bmc-replay", "debug-photo-bmc-replay-binary921"}:
  268. uart_assignments = dict(LOCKED_DEBUG_UART_ASSIGNMENTS)
  269. for item in TEMP_UART_PTC_REMAP_SUBSTITUTIONS.values():
  270. assignments[item["signal"]] = item["substitute_ball"]
  271. substitution_reason = (
  272. "photo_visible_uart_overlap_remap"
  273. if profile in {"debug-photo-uart-bmc-replay", "debug-photo-bmc-replay-binary921"}
  274. else "temporary_uart_overlap_remap"
  275. )
  276. ptc_substitutions = _ptc_substitution_rows(inventory, assignments, reason=substitution_reason)
  277. hardware_status = "not_run"
  278. if profile in {"debug-photo-uart-bmc-replay", "debug-photo-bmc-replay-binary921"}:
  279. bmc_source = "pc_replay_from_real_bmc_capture"
  280. live_bmc_link_status = "not_used"
  281. hardware_access_status = "photo_visible_header"
  282. uart_aliases = {
  283. "bmc_replay_uart_tx": "bmc_uart_tx",
  284. "bmc_replay_uart_rx": "bmc_uart_rx",
  285. }
  286. if profile == "debug-photo-bmc-replay-binary921":
  287. boundary = (
  288. "BMC-replay debug-photo binary921 profile: photo-visible/current J6/COM7/COM8 UART wiring is kept, "
  289. "the CPLD BMC UART talks to a PC poll-response replay emulator instead of a live BMC, "
  290. "HostPort and DebugPort use binary921 machine frames, and six overlapping HEAT/PTC channels are moved to verified spare GPIO. "
  291. "It is debug-only and does not claim full real HEAT pinout pass."
  292. )
  293. else:
  294. boundary = (
  295. "BMC-replay debug-photo profile: photo-visible/current J6/COM7/COM8 UART wiring is kept, "
  296. "the CPLD BMC UART talks to a PC poll-response replay emulator instead of a live BMC, "
  297. "and six overlapping HEAT/PTC channels are moved to verified spare GPIO. "
  298. "It is debug-only and does not claim full real HEAT pinout pass."
  299. )
  300. else:
  301. boundary = (
  302. "Temporary debug pin profile: current J6/COM7/COM8 UART wiring is kept, "
  303. "and six overlapping HEAT/PTC channels are moved to verified spare GPIO for signal-level diagnostic use."
  304. )
  305. elif profile == "formal-uart":
  306. uart_assignments = dict(FORMAL_UART_ASSIGNMENTS)
  307. ptc_substitutions = {}
  308. hardware_status = "not_run"
  309. boundary = (
  310. "Formal debug pin profile: all HEAT/PTC/FAN/FG/INSTALL pins use the schematic mapping, "
  311. "and all three diagnostic UARTs move to verified spare GPIO; schematic UART1/2 are reserved unused."
  312. )
  313. else:
  314. if production_profile:
  315. uart_assignments = dict(PRODUCTION_TWO_UART_BMC_REPLAY_BINARY921_ASSIGNMENTS)
  316. elif profile == "formal-uart1-bmc-replay-binary921":
  317. uart_assignments = dict(FORMAL_UART1_BMC_REPLAY_BINARY921_ASSIGNMENTS)
  318. else:
  319. uart_assignments = dict(FORMAL_UART1_BMC_REPLAY_ASSIGNMENTS)
  320. ptc_substitutions = {}
  321. hardware_status = "not_run"
  322. bmc_source = "pc_replay_from_real_bmc_capture"
  323. live_bmc_link_status = "not_used"
  324. hardware_access_status = (
  325. "production_uart1_uart2_access_confirmed_by_user"
  326. if production_profile
  327. else "blocked_waiting_for_uart1_uart2_access"
  328. )
  329. reserved_uart_use_policy = "intentional_uart1_uart2_bmc_replay_host"
  330. uart_aliases = {
  331. "bmc_replay_uart_tx": "bmc_uart_tx",
  332. "bmc_replay_uart_rx": "bmc_uart_rx",
  333. }
  334. if production_profile:
  335. uart_aliases.update(
  336. {
  337. "combined_debug_host_uart_tx": "host_uart_tx",
  338. "combined_debug_host_uart_rx": "host_uart_rx",
  339. }
  340. )
  341. if profile4_fan_tach:
  342. bmc_source = "out_of_scope"
  343. live_bmc_link_status = "out_of_scope"
  344. reserved_uart_use_policy = "intentional_uart1_idle_uart2_host"
  345. uart_aliases = {
  346. "idle_uart1_tx": "bmc_uart_tx",
  347. "ignored_uart1_rx": "bmc_uart_rx",
  348. "combined_debug_host_uart_tx": "host_uart_tx",
  349. "combined_debug_host_uart_rx": "host_uart_rx",
  350. }
  351. allowed_reserved_balls = {"L10", "M9", "M10", "N11"}
  352. if profile4_fan_tach:
  353. boundary = (
  354. "Prod2U Profile 4 production pin profile: HEAT/FAN/FG/INSTALL stay on the PDF/inventory pins, "
  355. "UART2 M10/N11 is the combined Host+Debug binary921-v2 port, and UART1 L10/M9 is retained only "
  356. "as an idle TX and ignored RX electrical boundary. BMC is out of scope. J3 is PROGRAM_SRAM-only. "
  357. "It does not qualify RPM calibration, PWM electrical accuracy, PTC thermal performance, PID, flash, or nonvolatile programming."
  358. )
  359. elif production_profile:
  360. boundary = (
  361. "Production two-UART BMC-replay binary921 profile for J3 SRAM-only bring-up: HEAT/FAN/FG/INSTALL stay on PDF/inventory pins, "
  362. "BMC replay uses UART1 L10/M9 at 115200, and a combined Host+Debug binary921 port uses UART2 M10/N11 at 921600. "
  363. "The board is programmed through J3 with target board power present and PROGRAM_SRAM only; VREF is a reference, not board power. "
  364. "It does not claim live BMC, flash, thermal performance, PID closed-loop, or real PTC/FAN load pass."
  365. )
  366. elif profile == "formal-uart1-bmc-replay-binary921":
  367. boundary = (
  368. "BMC-replay formal-uart1 binary921 profile: HEAT/FAN/FG/INSTALL stay on the schematic pins, "
  369. "BMC replay uses UART1 L10/M9, HostPort uses UART2 M10/N11, DebugPort uses M14/M15 spare GPIO, "
  370. "and HostPort/DebugPort use binary921 machine frames. "
  371. "Photo evidence did not prove UART1/2 are physically accessible, so hardware access remains blocked until continuity/header access is verified."
  372. )
  373. else:
  374. boundary = (
  375. "BMC-replay formal-uart1 profile: HEAT/FAN/FG/INSTALL stay on the schematic pins, "
  376. "BMC replay uses UART1 L10/M9, HostPort uses UART2 M10/N11, and DebugPort uses SPARE_GPIO44/45 "
  377. "as TX=N14/RX=P15. "
  378. "Photo evidence did not prove UART1/2 are physically accessible, so hardware access remains blocked until continuity/header access is verified."
  379. )
  380. assignments.update(uart_assignments)
  381. conflict = check_pin_conflicts(inventory, assignments, allowed_reserved_balls=allowed_reserved_balls)
  382. reserved_future_uart = _reserved_future_uart(inventory)
  383. used_balls = {str(ball) for ball in assignments.values()}
  384. reserved_balls = {
  385. str(item.get("fpga_ball"))
  386. for item in reserved_future_uart.values()
  387. if item.get("fpga_ball")
  388. }
  389. uses_reserved_future_uart = bool(used_balls & reserved_balls)
  390. errors = list(conflict.get("errors") or [])
  391. allowed_reserved_policies = {
  392. "intentional_uart1_uart2_bmc_replay_host",
  393. "intentional_uart1_idle_uart2_host",
  394. }
  395. if uses_reserved_future_uart and reserved_uart_use_policy not in allowed_reserved_policies:
  396. errors.append("uses_reserved_future_uart")
  397. status = "pass" if conflict["status"] == "pass" and not errors else "fail"
  398. return {
  399. "schema": "cpld-diagnostic-pin-profile-v1",
  400. "generated_at": utc_now(),
  401. "board_id": inventory.get("board_id"),
  402. "profile": profile,
  403. "status": status,
  404. "assignments": dict(sorted(assignments.items())),
  405. "uart_assignments": _uart_assignment_rows(inventory, uart_assignments, aliases=uart_aliases),
  406. "ptc_substitutions": ptc_substitutions,
  407. "reserved_future_uart": reserved_future_uart,
  408. "uses_reserved_future_uart": uses_reserved_future_uart,
  409. "reserved_uart_use_policy": reserved_uart_use_policy,
  410. "bmc_source": bmc_source,
  411. "live_bmc_link_status": live_bmc_link_status,
  412. "transport": "combined_host_debug_uart" if production_profile else "separate_host_debug_uart",
  413. "hardware_access_status": hardware_access_status,
  414. "real_fan_ptc_hardware_status": hardware_status,
  415. "conflict_check": conflict,
  416. "errors": sorted(set(errors)),
  417. "authority_boundary": boundary,
  418. }
  419. def check_pin_conflicts(
  420. inventory: dict[str, Any],
  421. assignments: dict[str, str],
  422. *,
  423. allowed_reserved_balls: set[str] | None = None,
  424. ) -> dict[str, Any]:
  425. pins = _pin_by_ball(inventory)
  426. allowed_reserved_balls = allowed_reserved_balls or set()
  427. seen: dict[str, str] = {}
  428. errors: list[str] = []
  429. warnings: list[str] = []
  430. assignment_rows: list[dict[str, Any]] = []
  431. for signal, ball in assignments.items():
  432. ball_text = str(ball)
  433. pin = pins.get(ball_text)
  434. if ball_text in seen:
  435. errors.append(f"duplicate_ball:{ball_text}")
  436. seen[ball_text] = signal
  437. if pin is None:
  438. errors.append(f"unknown_ball:{ball_text}")
  439. assignment_rows.append({"signal": signal, "fpga_ball": ball_text, "status": "unknown_ball"})
  440. continue
  441. capabilities = set(pin.get("capability") or [])
  442. if (
  443. (pin.get("reserved") and ball_text not in allowed_reserved_balls)
  444. or pin.get("role") not in {"user_io", "HEAT", "FAN_PWM", "FAN_FG", "FAN_INSTALL"}
  445. or "gpio" not in capabilities
  446. ):
  447. errors.append(f"reserved_or_not_gpio:{ball_text}")
  448. if pin.get("manually_verified") is not True:
  449. warnings.append(f"unverified_pin:{ball_text}")
  450. assignment_rows.append(
  451. {
  452. "signal": signal,
  453. "fpga_ball": ball_text,
  454. "connector": pin.get("connector"),
  455. "connector_pin": pin.get("connector_pin"),
  456. "io_standard": pin.get("io_standard"),
  457. "manually_verified": pin.get("manually_verified") is True,
  458. }
  459. )
  460. return {
  461. "schema": "cpld-pin-conflict-check-v1",
  462. "generated_at": utc_now(),
  463. "board_id": inventory.get("board_id"),
  464. "status": "fail" if errors else "pass",
  465. "assignments": assignment_rows,
  466. "errors": sorted(set(errors)),
  467. "warnings": sorted(set(warnings)),
  468. }
  469. def generate_adc(
  470. inventory: dict[str, Any],
  471. *,
  472. assignments: dict[str, str],
  473. output: Path | str,
  474. allow_unverified: bool = False,
  475. ) -> dict[str, Any]:
  476. conflict = check_pin_conflicts(inventory, assignments)
  477. if conflict["errors"]:
  478. return {"schema": "cpld-adc-generation-v1", "status": "fail_pin_conflict", "conflict": conflict}
  479. if conflict["warnings"] and not allow_unverified:
  480. return {"schema": "cpld-adc-generation-v1", "status": "blocked_unverified_pin_map", "conflict": conflict}
  481. pins = _pin_by_ball(inventory)
  482. lines = [
  483. "# Generated by tools/pin_inventory.py",
  484. f"# Board: {inventory.get('board_id')}",
  485. ]
  486. if conflict["warnings"]:
  487. lines.append("# LAB_SMOKE_UNVERIFIED_PIN_MAP: connector orientation and schematic cross-check are still required.")
  488. for signal, ball in assignments.items():
  489. pin = pins[str(ball)]
  490. io_standard = pin.get("io_standard") or "LVCMOS33"
  491. lines.append(f"set_pin_assignment {{ {signal} }} {{ LOCATION = {ball}; IOSTANDARD = {io_standard}; PULLTYPE = NONE; }}")
  492. output_path = Path(output)
  493. output_path.parent.mkdir(parents=True, exist_ok=True)
  494. output_path.write_text("\n".join(lines) + "\n", encoding="utf-8")
  495. return {
  496. "schema": "cpld-adc-generation-v1",
  497. "status": "pass",
  498. "path": str(output_path),
  499. "conflict": conflict,
  500. "allow_unverified": allow_unverified,
  501. "authority_boundary": "Generated ADC is a candidate lab-smoke constraint only unless all pins are manually verified and product gate is explicitly enabled.",
  502. }
  503. def _parse_assignments(items: list[str]) -> dict[str, str]:
  504. assignments: dict[str, str] = {}
  505. for item in items:
  506. if "=" not in item:
  507. raise ValueError(f"assignment must be signal=BALL: {item}")
  508. signal, ball = item.split("=", 1)
  509. assignments[signal.strip()] = ball.strip()
  510. return assignments
  511. def build_parser() -> argparse.ArgumentParser:
  512. parser = argparse.ArgumentParser(description=__doc__)
  513. sub = parser.add_subparsers(dest="command", required=True)
  514. budget = sub.add_parser("budget")
  515. budget.add_argument("--inventory", type=Path, default=ROOT / "config" / "pin_inventory.mini.json")
  516. budget.add_argument("--json", action="store_true")
  517. budget.set_defaults(func=cmd_budget)
  518. conflict = sub.add_parser("conflict")
  519. conflict.add_argument("--inventory", type=Path, default=ROOT / "config" / "pin_inventory.mini.json")
  520. conflict.add_argument("--assign", action="append", default=[])
  521. conflict.add_argument("--json", action="store_true")
  522. conflict.set_defaults(func=cmd_conflict)
  523. adc = sub.add_parser("generate-adc")
  524. adc.add_argument("--inventory", type=Path, default=ROOT / "config" / "pin_inventory.mini.json")
  525. adc.add_argument("--assign", action="append", default=[])
  526. adc.add_argument("--output", type=Path, required=True)
  527. adc.add_argument("--allow-unverified", action="store_true")
  528. adc.add_argument("--json", action="store_true")
  529. adc.set_defaults(func=cmd_generate_adc)
  530. return parser
  531. def cmd_budget(args: argparse.Namespace) -> int:
  532. payload = build_io_budget(load_pin_inventory(args.inventory))
  533. print(json.dumps(payload, indent=2) if args.json else f"pin-budget: {payload['status']}")
  534. return 0 if payload["status"] == "pass" else 1
  535. def cmd_conflict(args: argparse.Namespace) -> int:
  536. payload = check_pin_conflicts(load_pin_inventory(args.inventory), _parse_assignments(args.assign))
  537. print(json.dumps(payload, indent=2) if args.json else f"pin-conflict: {payload['status']}")
  538. return 0 if payload["status"] == "pass" else 1
  539. def cmd_generate_adc(args: argparse.Namespace) -> int:
  540. payload = generate_adc(
  541. load_pin_inventory(args.inventory),
  542. assignments=_parse_assignments(args.assign),
  543. output=args.output,
  544. allow_unverified=args.allow_unverified,
  545. )
  546. print(json.dumps(payload, indent=2) if args.json else f"generate-adc: {payload['status']}")
  547. return 0 if payload["status"] == "pass" else 1
  548. def main(argv: list[str] | None = None) -> int:
  549. return build_parser().parse_args(argv).func(build_parser().parse_args(argv))
  550. if __name__ == "__main__":
  551. parser = build_parser()
  552. parsed = parser.parse_args()
  553. raise SystemExit(parsed.func(parsed))