pin_inventory.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592
  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. }
  242. if profile not in supported_profiles:
  243. return {
  244. "schema": "cpld-diagnostic-pin-profile-v1",
  245. "generated_at": utc_now(),
  246. "board_id": inventory.get("board_id"),
  247. "profile": profile,
  248. "status": "fail_unknown_profile",
  249. "assignments": {},
  250. "errors": [f"unknown_profile:{profile}"],
  251. }
  252. assignments = real_fan_ptc_assignments(inventory)
  253. bmc_source = "live_bmc_j6_uart"
  254. live_bmc_link_status = "used"
  255. hardware_access_status = "not_run"
  256. reserved_uart_use_policy = "reserved_unused"
  257. uart_aliases: dict[str, str] = {}
  258. allowed_reserved_balls: set[str] = set()
  259. if profile in {"temp-uart-ptc-remap", "debug-photo-uart-bmc-replay", "debug-photo-bmc-replay-binary921"}:
  260. uart_assignments = dict(LOCKED_DEBUG_UART_ASSIGNMENTS)
  261. for item in TEMP_UART_PTC_REMAP_SUBSTITUTIONS.values():
  262. assignments[item["signal"]] = item["substitute_ball"]
  263. substitution_reason = (
  264. "photo_visible_uart_overlap_remap"
  265. if profile in {"debug-photo-uart-bmc-replay", "debug-photo-bmc-replay-binary921"}
  266. else "temporary_uart_overlap_remap"
  267. )
  268. ptc_substitutions = _ptc_substitution_rows(inventory, assignments, reason=substitution_reason)
  269. hardware_status = "not_run"
  270. if profile in {"debug-photo-uart-bmc-replay", "debug-photo-bmc-replay-binary921"}:
  271. bmc_source = "pc_replay_from_real_bmc_capture"
  272. live_bmc_link_status = "not_used"
  273. hardware_access_status = "photo_visible_header"
  274. uart_aliases = {
  275. "bmc_replay_uart_tx": "bmc_uart_tx",
  276. "bmc_replay_uart_rx": "bmc_uart_rx",
  277. }
  278. if profile == "debug-photo-bmc-replay-binary921":
  279. boundary = (
  280. "BMC-replay debug-photo binary921 profile: photo-visible/current J6/COM7/COM8 UART wiring is kept, "
  281. "the CPLD BMC UART talks to a PC poll-response replay emulator instead of a live BMC, "
  282. "HostPort and DebugPort use binary921 machine frames, and six overlapping HEAT/PTC channels are moved to verified spare GPIO. "
  283. "It is debug-only and does not claim full real HEAT pinout pass."
  284. )
  285. else:
  286. boundary = (
  287. "BMC-replay debug-photo profile: photo-visible/current J6/COM7/COM8 UART wiring is kept, "
  288. "the CPLD BMC UART talks to a PC poll-response replay emulator instead of a live BMC, "
  289. "and six overlapping HEAT/PTC channels are moved to verified spare GPIO. "
  290. "It is debug-only and does not claim full real HEAT pinout pass."
  291. )
  292. else:
  293. boundary = (
  294. "Temporary debug pin profile: current J6/COM7/COM8 UART wiring is kept, "
  295. "and six overlapping HEAT/PTC channels are moved to verified spare GPIO for signal-level diagnostic use."
  296. )
  297. elif profile == "formal-uart":
  298. uart_assignments = dict(FORMAL_UART_ASSIGNMENTS)
  299. ptc_substitutions = {}
  300. hardware_status = "not_run"
  301. boundary = (
  302. "Formal debug pin profile: all HEAT/PTC/FAN/FG/INSTALL pins use the schematic mapping, "
  303. "and all three diagnostic UARTs move to verified spare GPIO; schematic UART1/2 are reserved unused."
  304. )
  305. else:
  306. if profile == "production-two-uart-bmc-replay-binary921":
  307. uart_assignments = dict(PRODUCTION_TWO_UART_BMC_REPLAY_BINARY921_ASSIGNMENTS)
  308. elif profile == "formal-uart1-bmc-replay-binary921":
  309. uart_assignments = dict(FORMAL_UART1_BMC_REPLAY_BINARY921_ASSIGNMENTS)
  310. else:
  311. uart_assignments = dict(FORMAL_UART1_BMC_REPLAY_ASSIGNMENTS)
  312. ptc_substitutions = {}
  313. hardware_status = "not_run"
  314. bmc_source = "pc_replay_from_real_bmc_capture"
  315. live_bmc_link_status = "not_used"
  316. hardware_access_status = (
  317. "production_uart1_uart2_access_confirmed_by_user"
  318. if profile == "production-two-uart-bmc-replay-binary921"
  319. else "blocked_waiting_for_uart1_uart2_access"
  320. )
  321. reserved_uart_use_policy = "intentional_uart1_uart2_bmc_replay_host"
  322. uart_aliases = {
  323. "bmc_replay_uart_tx": "bmc_uart_tx",
  324. "bmc_replay_uart_rx": "bmc_uart_rx",
  325. }
  326. if profile == "production-two-uart-bmc-replay-binary921":
  327. uart_aliases.update(
  328. {
  329. "combined_debug_host_uart_tx": "host_uart_tx",
  330. "combined_debug_host_uart_rx": "host_uart_rx",
  331. }
  332. )
  333. allowed_reserved_balls = {"L10", "M9", "M10", "N11"}
  334. if profile == "production-two-uart-bmc-replay-binary921":
  335. boundary = (
  336. "Production two-UART BMC-replay binary921 profile for J3 SRAM-only bring-up: HEAT/FAN/FG/INSTALL stay on PDF/inventory pins, "
  337. "BMC replay uses UART1 L10/M9 at 115200, and a combined Host+Debug binary921 port uses UART2 M10/N11 at 921600. "
  338. "The board is programmed through J3 with target board power present and PROGRAM_SRAM only; VREF is a reference, not board power. "
  339. "It does not claim live BMC, flash, thermal performance, PID closed-loop, or real PTC/FAN load pass."
  340. )
  341. elif profile == "formal-uart1-bmc-replay-binary921":
  342. boundary = (
  343. "BMC-replay formal-uart1 binary921 profile: HEAT/FAN/FG/INSTALL stay on the schematic pins, "
  344. "BMC replay uses UART1 L10/M9, HostPort uses UART2 M10/N11, DebugPort uses M14/M15 spare GPIO, "
  345. "and HostPort/DebugPort use binary921 machine frames. "
  346. "Photo evidence did not prove UART1/2 are physically accessible, so hardware access remains blocked until continuity/header access is verified."
  347. )
  348. else:
  349. boundary = (
  350. "BMC-replay formal-uart1 profile: HEAT/FAN/FG/INSTALL stay on the schematic pins, "
  351. "BMC replay uses UART1 L10/M9, HostPort uses UART2 M10/N11, and DebugPort uses SPARE_GPIO44/45 "
  352. "as TX=N14/RX=P15. "
  353. "Photo evidence did not prove UART1/2 are physically accessible, so hardware access remains blocked until continuity/header access is verified."
  354. )
  355. assignments.update(uart_assignments)
  356. conflict = check_pin_conflicts(inventory, assignments, allowed_reserved_balls=allowed_reserved_balls)
  357. reserved_future_uart = _reserved_future_uart(inventory)
  358. used_balls = {str(ball) for ball in assignments.values()}
  359. reserved_balls = {
  360. str(item.get("fpga_ball"))
  361. for item in reserved_future_uart.values()
  362. if item.get("fpga_ball")
  363. }
  364. uses_reserved_future_uart = bool(used_balls & reserved_balls)
  365. errors = list(conflict.get("errors") or [])
  366. if uses_reserved_future_uart and reserved_uart_use_policy != "intentional_uart1_uart2_bmc_replay_host":
  367. errors.append("uses_reserved_future_uart")
  368. status = "pass" if conflict["status"] == "pass" and not errors else "fail"
  369. return {
  370. "schema": "cpld-diagnostic-pin-profile-v1",
  371. "generated_at": utc_now(),
  372. "board_id": inventory.get("board_id"),
  373. "profile": profile,
  374. "status": status,
  375. "assignments": dict(sorted(assignments.items())),
  376. "uart_assignments": _uart_assignment_rows(inventory, uart_assignments, aliases=uart_aliases),
  377. "ptc_substitutions": ptc_substitutions,
  378. "reserved_future_uart": reserved_future_uart,
  379. "uses_reserved_future_uart": uses_reserved_future_uart,
  380. "reserved_uart_use_policy": reserved_uart_use_policy,
  381. "bmc_source": bmc_source,
  382. "live_bmc_link_status": live_bmc_link_status,
  383. "transport": "combined_host_debug_uart" if profile == "production-two-uart-bmc-replay-binary921" else "separate_host_debug_uart",
  384. "hardware_access_status": hardware_access_status,
  385. "real_fan_ptc_hardware_status": hardware_status,
  386. "conflict_check": conflict,
  387. "errors": sorted(set(errors)),
  388. "authority_boundary": boundary,
  389. }
  390. def check_pin_conflicts(
  391. inventory: dict[str, Any],
  392. assignments: dict[str, str],
  393. *,
  394. allowed_reserved_balls: set[str] | None = None,
  395. ) -> dict[str, Any]:
  396. pins = _pin_by_ball(inventory)
  397. allowed_reserved_balls = allowed_reserved_balls or set()
  398. seen: dict[str, str] = {}
  399. errors: list[str] = []
  400. warnings: list[str] = []
  401. assignment_rows: list[dict[str, Any]] = []
  402. for signal, ball in assignments.items():
  403. ball_text = str(ball)
  404. pin = pins.get(ball_text)
  405. if ball_text in seen:
  406. errors.append(f"duplicate_ball:{ball_text}")
  407. seen[ball_text] = signal
  408. if pin is None:
  409. errors.append(f"unknown_ball:{ball_text}")
  410. assignment_rows.append({"signal": signal, "fpga_ball": ball_text, "status": "unknown_ball"})
  411. continue
  412. capabilities = set(pin.get("capability") or [])
  413. if (
  414. (pin.get("reserved") and ball_text not in allowed_reserved_balls)
  415. or pin.get("role") not in {"user_io", "HEAT", "FAN_PWM", "FAN_FG", "FAN_INSTALL"}
  416. or "gpio" not in capabilities
  417. ):
  418. errors.append(f"reserved_or_not_gpio:{ball_text}")
  419. if pin.get("manually_verified") is not True:
  420. warnings.append(f"unverified_pin:{ball_text}")
  421. assignment_rows.append(
  422. {
  423. "signal": signal,
  424. "fpga_ball": ball_text,
  425. "connector": pin.get("connector"),
  426. "connector_pin": pin.get("connector_pin"),
  427. "io_standard": pin.get("io_standard"),
  428. "manually_verified": pin.get("manually_verified") is True,
  429. }
  430. )
  431. return {
  432. "schema": "cpld-pin-conflict-check-v1",
  433. "generated_at": utc_now(),
  434. "board_id": inventory.get("board_id"),
  435. "status": "fail" if errors else "pass",
  436. "assignments": assignment_rows,
  437. "errors": sorted(set(errors)),
  438. "warnings": sorted(set(warnings)),
  439. }
  440. def generate_adc(
  441. inventory: dict[str, Any],
  442. *,
  443. assignments: dict[str, str],
  444. output: Path | str,
  445. allow_unverified: bool = False,
  446. ) -> dict[str, Any]:
  447. conflict = check_pin_conflicts(inventory, assignments)
  448. if conflict["errors"]:
  449. return {"schema": "cpld-adc-generation-v1", "status": "fail_pin_conflict", "conflict": conflict}
  450. if conflict["warnings"] and not allow_unverified:
  451. return {"schema": "cpld-adc-generation-v1", "status": "blocked_unverified_pin_map", "conflict": conflict}
  452. pins = _pin_by_ball(inventory)
  453. lines = [
  454. "# Generated by tools/pin_inventory.py",
  455. f"# Board: {inventory.get('board_id')}",
  456. ]
  457. if conflict["warnings"]:
  458. lines.append("# LAB_SMOKE_UNVERIFIED_PIN_MAP: connector orientation and schematic cross-check are still required.")
  459. for signal, ball in assignments.items():
  460. pin = pins[str(ball)]
  461. io_standard = pin.get("io_standard") or "LVCMOS33"
  462. lines.append(f"set_pin_assignment {{ {signal} }} {{ LOCATION = {ball}; IOSTANDARD = {io_standard}; PULLTYPE = NONE; }}")
  463. output_path = Path(output)
  464. output_path.parent.mkdir(parents=True, exist_ok=True)
  465. output_path.write_text("\n".join(lines) + "\n", encoding="utf-8")
  466. return {
  467. "schema": "cpld-adc-generation-v1",
  468. "status": "pass",
  469. "path": str(output_path),
  470. "conflict": conflict,
  471. "allow_unverified": allow_unverified,
  472. "authority_boundary": "Generated ADC is a candidate lab-smoke constraint only unless all pins are manually verified and product gate is explicitly enabled.",
  473. }
  474. def _parse_assignments(items: list[str]) -> dict[str, str]:
  475. assignments: dict[str, str] = {}
  476. for item in items:
  477. if "=" not in item:
  478. raise ValueError(f"assignment must be signal=BALL: {item}")
  479. signal, ball = item.split("=", 1)
  480. assignments[signal.strip()] = ball.strip()
  481. return assignments
  482. def build_parser() -> argparse.ArgumentParser:
  483. parser = argparse.ArgumentParser(description=__doc__)
  484. sub = parser.add_subparsers(dest="command", required=True)
  485. budget = sub.add_parser("budget")
  486. budget.add_argument("--inventory", type=Path, default=ROOT / "config" / "pin_inventory.mini.json")
  487. budget.add_argument("--json", action="store_true")
  488. budget.set_defaults(func=cmd_budget)
  489. conflict = sub.add_parser("conflict")
  490. conflict.add_argument("--inventory", type=Path, default=ROOT / "config" / "pin_inventory.mini.json")
  491. conflict.add_argument("--assign", action="append", default=[])
  492. conflict.add_argument("--json", action="store_true")
  493. conflict.set_defaults(func=cmd_conflict)
  494. adc = sub.add_parser("generate-adc")
  495. adc.add_argument("--inventory", type=Path, default=ROOT / "config" / "pin_inventory.mini.json")
  496. adc.add_argument("--assign", action="append", default=[])
  497. adc.add_argument("--output", type=Path, required=True)
  498. adc.add_argument("--allow-unverified", action="store_true")
  499. adc.add_argument("--json", action="store_true")
  500. adc.set_defaults(func=cmd_generate_adc)
  501. return parser
  502. def cmd_budget(args: argparse.Namespace) -> int:
  503. payload = build_io_budget(load_pin_inventory(args.inventory))
  504. print(json.dumps(payload, indent=2) if args.json else f"pin-budget: {payload['status']}")
  505. return 0 if payload["status"] == "pass" else 1
  506. def cmd_conflict(args: argparse.Namespace) -> int:
  507. payload = check_pin_conflicts(load_pin_inventory(args.inventory), _parse_assignments(args.assign))
  508. print(json.dumps(payload, indent=2) if args.json else f"pin-conflict: {payload['status']}")
  509. return 0 if payload["status"] == "pass" else 1
  510. def cmd_generate_adc(args: argparse.Namespace) -> int:
  511. payload = generate_adc(
  512. load_pin_inventory(args.inventory),
  513. assignments=_parse_assignments(args.assign),
  514. output=args.output,
  515. allow_unverified=args.allow_unverified,
  516. )
  517. print(json.dumps(payload, indent=2) if args.json else f"generate-adc: {payload['status']}")
  518. return 0 if payload["status"] == "pass" else 1
  519. def main(argv: list[str] | None = None) -> int:
  520. return build_parser().parse_args(argv).func(build_parser().parse_args(argv))
  521. if __name__ == "__main__":
  522. parser = build_parser()
  523. parsed = parser.parse_args()
  524. raise SystemExit(parsed.func(parsed))