run_6400_td.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432
  1. #!/usr/bin/env python3
  2. """Run clean, source-bound TD synthesis, place/route, and bit generation."""
  3. from __future__ import annotations
  4. import argparse
  5. from datetime import datetime, timezone
  6. import hashlib
  7. import json
  8. import os
  9. from pathlib import Path
  10. import re
  11. import shutil
  12. import subprocess
  13. import sys
  14. import time
  15. ROOT = Path(__file__).resolve().parents[1]
  16. DEFAULT_PROFILE = "6400-control"
  17. HARDWARE_PROFILES = {
  18. "6400-control": {
  19. "project": "products/6400-control/project.json",
  20. "closure": "products/6400-control/source-closure.json",
  21. "td_project": "td/prod2u_6400_front_back.prj",
  22. "td_files": (
  23. "td/syn/prod2u_6400_front_back.tcl",
  24. "td/phy/prod2u_6400_front_back.tcl",
  25. "td/bitgen/prod2u_6400_front_back.tcl",
  26. ),
  27. "artifact_basename": "prod2u_6400_front_back",
  28. "production": True,
  29. "stimulus": False,
  30. },
  31. "6400-identification": {
  32. "project": "products/6400-identification/project.json",
  33. "closure": "products/6400-identification/source-closure.json",
  34. "td_project": "td/prod2u_6400_identification.prj",
  35. "td_files": (
  36. "td/syn/prod2u_6400_identification.tcl",
  37. "td/phy/prod2u_6400_identification.tcl",
  38. "td/bitgen/prod2u_6400_identification.tcl",
  39. ),
  40. "artifact_basename": "prod2u_6400_identification",
  41. "production": False,
  42. "stimulus": True,
  43. },
  44. }
  45. # Backward-compatible aliases for callers importing the production defaults.
  46. PROJECT = ROOT / str(HARDWARE_PROFILES[DEFAULT_PROFILE]["project"])
  47. CLOSURE = ROOT / str(HARDWARE_PROFILES[DEFAULT_PROFILE]["closure"])
  48. TD_PROJECT = str(HARDWARE_PROFILES[DEFAULT_PROFILE]["td_project"])
  49. TD_FILES = tuple(HARDWARE_PROFILES[DEFAULT_PROFILE]["td_files"])
  50. CONSTRAINT_FILES = (
  51. "constraints/prod2u_6400_front_back.adc",
  52. "constraints/prod2u_6400_front_back.sdc",
  53. )
  54. EXPECTED_UNBOUND_PORTS = ("host_ttl_rx", "host_ttl_tx")
  55. def sha256(path: Path) -> str:
  56. digest = hashlib.sha256()
  57. with path.open("rb") as stream:
  58. for chunk in iter(lambda: stream.read(1024 * 1024), b""):
  59. digest.update(chunk)
  60. return digest.hexdigest()
  61. def git(*args: str) -> str:
  62. return subprocess.check_output(["git", *args], cwd=ROOT, text=True).strip()
  63. def _load_inherited_json(path: Path, list_key: str, additional_key: str) -> tuple[list[str], list[str]]:
  64. payload = json.loads(path.read_text(encoding="utf-8"))
  65. inputs = [str(path.relative_to(ROOT))]
  66. values: list[str] = []
  67. inherited = payload.get("inherits")
  68. if inherited:
  69. parent_values, parent_inputs = _load_inherited_json(
  70. ROOT / inherited, list_key, additional_key
  71. )
  72. values.extend(parent_values)
  73. inputs.extend(parent_inputs)
  74. values.extend(payload.get(list_key, payload.get(additional_key, [])))
  75. return values, inputs
  76. def source_closure(profile_name: str) -> tuple[list[str], list[str]]:
  77. profile = HARDWARE_PROFILES[profile_name]
  78. return _load_inherited_json(ROOT / str(profile["closure"]), "sources", "additional_sources")
  79. def project_inputs(path: Path) -> list[str]:
  80. payload = json.loads(path.read_text(encoding="utf-8"))
  81. paths = [str(path.relative_to(ROOT))]
  82. if payload.get("inherits"):
  83. paths.extend(project_inputs(ROOT / payload["inherits"]))
  84. return paths
  85. def profile_receipt_fields(profile_name: str) -> dict[str, object]:
  86. profile = HARDWARE_PROFILES[profile_name]
  87. return {
  88. "profile": profile_name,
  89. "firmware_role": "production" if profile["production"] else "identification",
  90. "production": bool(profile["production"]),
  91. "stimulus": bool(profile["stimulus"]),
  92. "simulation_only": False,
  93. "artifact_basename": str(profile["artifact_basename"]),
  94. }
  95. def input_manifest(profile_name: str = DEFAULT_PROFILE) -> dict[str, str]:
  96. profile = HARDWARE_PROFILES[profile_name]
  97. sources, closure_inputs = source_closure(profile_name)
  98. project_path = ROOT / str(profile["project"])
  99. paths = [
  100. *sources,
  101. *CONSTRAINT_FILES,
  102. str(profile["td_project"]),
  103. *profile["td_files"],
  104. *project_inputs(project_path),
  105. *closure_inputs,
  106. ]
  107. paths = list(dict.fromkeys(paths))
  108. missing = [item for item in paths if not (ROOT / item).is_file()]
  109. if missing:
  110. raise RuntimeError(f"source closure contains missing inputs: {missing}")
  111. return {item: sha256(ROOT / item) for item in paths}
  112. def run_stage(name: str, command: list[str], cwd: Path, env: dict[str, str]) -> dict[str, object]:
  113. log_path = cwd / f"{name}.log"
  114. started = time.monotonic()
  115. with log_path.open("wb") as log:
  116. completed = subprocess.run(command, cwd=cwd, env=env, stdout=log, stderr=subprocess.STDOUT, check=False)
  117. duration = round(time.monotonic() - started, 3)
  118. return {
  119. "command": command,
  120. "cwd": str(cwd),
  121. "exit_code": completed.returncode,
  122. "duration_seconds": duration,
  123. "log": str(log_path),
  124. "log_sha256": sha256(log_path),
  125. }
  126. def first_int(text: str, patterns: tuple[str, ...]) -> int | None:
  127. for pattern in patterns:
  128. match = re.search(pattern, text, re.IGNORECASE | re.MULTILINE)
  129. if match:
  130. return int(match.group(1))
  131. return None
  132. def first_float(text: str, patterns: tuple[str, ...]) -> float | None:
  133. for pattern in patterns:
  134. match = re.search(pattern, text, re.IGNORECASE | re.MULTILINE)
  135. if match:
  136. return float(match.group(1))
  137. return None
  138. def parse_metrics(
  139. run_root: Path, artifact_basename: str = "prod2u_6400_front_back"
  140. ) -> dict[str, object]:
  141. area_paths = [
  142. run_root / f"phy/{artifact_basename}_phy.area",
  143. run_root / f"syn/{artifact_basename}_gate.area",
  144. ]
  145. area = "\n".join(path.read_text(encoding="utf-8", errors="replace") for path in area_paths if path.is_file())
  146. timing_path = run_root / f"phy/{artifact_basename}_pr.timing"
  147. timing = timing_path.read_text(encoding="utf-8", errors="replace") if timing_path.is_file() else ""
  148. logs = "\n".join(
  149. path.read_text(encoding="utf-8", errors="replace")
  150. for path in (run_root / "syn/syn.log", run_root / "phy/phy.log", run_root / "bitgen/bitgen.log")
  151. if path.is_file()
  152. )
  153. reported_total_luts = first_int(area, (r"^#Total_luts\s+(\d+)",))
  154. lut = first_int(area, (r"^#lut\s+(\d+)",))
  155. slice_matches = re.findall(r"(\d+)\s+mslices,\s+(\d+)\s+lslices", logs, re.IGNORECASE)
  156. mslice = int(slice_matches[-1][0]) if slice_matches else None
  157. lslice = int(slice_matches[-1][1]) if slice_matches else None
  158. violation_endpoint_counts = [
  159. int(value)
  160. for value in re.findall(r"(\d+)\s+Viol Endpoints", timing, re.IGNORECASE)
  161. ]
  162. return {
  163. "total_luts": reported_total_luts if reported_total_luts is not None else lut,
  164. "total_luts_source": "#Total_luts" if reported_total_luts is not None else "#lut_fallback",
  165. "lut": lut,
  166. "registers": first_int(area, (r"^#reg\s+(\d+)",)),
  167. "dsp": first_int(area, (r"^#dsp\s+(\d+)",)),
  168. "eram_bram": first_int(area, (r"^#(?:eram|bram)\s+(\d+)",)),
  169. "bram": first_int(area, (r"^#bram\s+(\d+)",)),
  170. "mslice": mslice,
  171. "lslice": lslice,
  172. "packed_slices": mslice + lslice if mslice is not None and lslice is not None else None,
  173. "packed_slices_derivation": "mslice_plus_lslice",
  174. "fmax_mhz": first_float(timing, (r"Fmax[^\n]*?([0-9]+(?:\.[0-9]+)?)\s*MHz", r"([0-9]+(?:\.[0-9]+)?)\s*MHz")),
  175. "setup_slack_ns": first_float(
  176. timing,
  177. (r"^\s*SWNS\s*:\s*(-?[0-9]+(?:\.[0-9]+)?)\s*ns",),
  178. ),
  179. "hold_slack_ns": first_float(
  180. timing,
  181. (r"^\s*HWNS\s*:\s*(-?[0-9]+(?:\.[0-9]+)?)\s*ns",),
  182. ),
  183. "setup_total_negative_slack_ns": first_float(
  184. timing,
  185. (r"^\s*SWNS\s*:\s*-?[0-9]+(?:\.[0-9]+)?\s*ns,\s*STNS\s*:\s*(-?[0-9]+(?:\.[0-9]+)?)\s*ns",),
  186. ),
  187. "hold_total_negative_slack_ns": first_float(
  188. timing,
  189. (r"^\s*HWNS\s*:\s*-?[0-9]+(?:\.[0-9]+)?\s*ns,\s*HTNS\s*:\s*(-?[0-9]+(?:\.[0-9]+)?)\s*ns",),
  190. ),
  191. "violation_endpoint_counts": violation_endpoint_counts,
  192. "all_violation_endpoint_counts_zero": all(
  193. value == 0 for value in violation_endpoint_counts
  194. ),
  195. "area_reports": [str(path) for path in area_paths if path.is_file()],
  196. "timing_report": str(timing_path) if timing_path.is_file() else None,
  197. }
  198. def warning_audit(stage_records: dict[str, dict[str, object]]) -> dict[str, object]:
  199. lines: list[str] = []
  200. blocking: list[str] = []
  201. unbound_ports: set[str] = set()
  202. severity = re.compile(
  203. r"^\s*(?:(?:[A-Z][A-Z0-9_-]*-\d+)\s+)?"
  204. r"(?:CRITICAL-WARNING|WARNING|ERROR|FATAL)\s*:",
  205. re.IGNORECASE,
  206. )
  207. noteworthy = re.compile(
  208. r"Bitgen will abort|No ADC ports:|\bunrouted\b|\bviolations?\b|"
  209. r"\bunconstrained\b|\bunassigned\b|\blatch\b|\bloop\b",
  210. re.IGNORECASE,
  211. )
  212. blocker_patterns = (
  213. re.compile(
  214. r"^\s*(?:(?:[A-Z][A-Z0-9_-]*-\d+)\s+)?(?:ERROR|FATAL)\s*:",
  215. re.IGNORECASE,
  216. ),
  217. re.compile(r"^\s*\[(?:ERROR|FATAL)\]", re.IGNORECASE),
  218. re.compile(
  219. r"\b(?:synthesis|placement|place\s*&\s*route|routing|route|fit|bitgen)"
  220. r"\s+(?:failed|failure)\b",
  221. re.IGNORECASE,
  222. ),
  223. re.compile(r"\b(?:setup|hold|timing)\s+(?:check\s+)?(?:failed|failure)\b", re.IGNORECASE),
  224. re.compile(r"(?:\b[1-9]\d*\s+unrouted\b|\bunrouted\s*[:=]\s*[1-9]\d*)", re.IGNORECASE),
  225. )
  226. for record in stage_records.values():
  227. log = Path(str(record["log"]))
  228. for line in log.read_text(encoding="utf-8", errors="replace").splitlines():
  229. if "No ADC ports:" in line:
  230. suffix = line.split("No ADC ports:", 1)[1]
  231. unbound_ports.update(
  232. re.findall(r"[A-Za-z_][A-Za-z0-9_]*(?:\[\d+(?::\d+)?\])?", suffix)
  233. )
  234. if severity.search(line) or noteworthy.search(line):
  235. compact = line.strip()
  236. if compact and compact not in lines:
  237. lines.append(compact)
  238. if any(pattern.search(compact) for pattern in blocker_patterns):
  239. blocking.append(compact)
  240. expected = set(EXPECTED_UNBOUND_PORTS)
  241. unexpected_unbound = sorted(unbound_ports - expected)
  242. missing_expected_unbound = sorted(expected - unbound_ports)
  243. if unexpected_unbound:
  244. blocking.append("unexpected unbound ports: " + ", ".join(unexpected_unbound))
  245. if missing_expected_unbound:
  246. blocking.append("expected unbound ports not reported: " + ", ".join(missing_expected_unbound))
  247. return {
  248. "status": "FAIL" if blocking else "PASS",
  249. "noteworthy_count": len(lines),
  250. "blocking_count": len(blocking),
  251. "expected_unbound_ports": sorted(expected),
  252. "observed_unbound_ports": sorted(unbound_ports),
  253. "unexpected_unbound_ports": unexpected_unbound,
  254. "missing_expected_unbound_ports": missing_expected_unbound,
  255. "blocking": blocking[:100],
  256. "noteworthy": lines[:300],
  257. }
  258. def main(argv: list[str] | None = None) -> int:
  259. parser = argparse.ArgumentParser()
  260. parser.add_argument(
  261. "--profile", choices=tuple(HARDWARE_PROFILES), default=DEFAULT_PROFILE
  262. )
  263. parser.add_argument("--run-root", type=Path)
  264. args = parser.parse_args(argv)
  265. profile_name = args.profile
  266. profile = HARDWARE_PROFILES[profile_name]
  267. project_path = ROOT / str(profile["project"])
  268. closure_path = ROOT / str(profile["closure"])
  269. artifact_basename = str(profile["artifact_basename"])
  270. td_files = tuple(profile["td_files"])
  271. td = shutil.which("td2026")
  272. local_td = ROOT / "tools/td2026"
  273. if td is None and local_td.is_file():
  274. td = str(local_td)
  275. if td is None:
  276. print("TD_MISSING: td2026 is not on PATH", file=sys.stderr)
  277. return 4
  278. dirty_before = git("status", "--porcelain")
  279. if dirty_before:
  280. print("TD_BLOCKED: source worktree must be clean", file=sys.stderr)
  281. print(dirty_before, file=sys.stderr)
  282. return 3
  283. commit = git("rev-parse", "HEAD")
  284. tree = git("rev-parse", "HEAD^{tree}")
  285. stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
  286. run_kind = "6400-td" if profile_name == DEFAULT_PROFILE else "6400-identification-td"
  287. run_id = f"{run_kind}-{stamp}-{commit[:8]}"
  288. run_root = args.run_root or Path(os.environ.get("PROD2U_TD_RUN_ROOT", "/data/prod2u/cpld-runs")) / run_id
  289. for stage in ("syn", "phy", "bitgen"):
  290. (run_root / stage).mkdir(parents=True, exist_ok=False)
  291. inputs = input_manifest(profile_name)
  292. manifest_bytes = json.dumps(inputs, sort_keys=True, separators=(",", ":")).encode()
  293. version_probe = subprocess.run([td, "-version"], capture_output=True, text=True, check=False)
  294. version_text = (version_probe.stdout + version_probe.stderr).strip()
  295. env = os.environ.copy()
  296. env["PROD2U_SOURCE_ROOT"] = str(ROOT)
  297. env["PATH"] = str(ROOT / "tools") + os.pathsep + env.get("PATH", "")
  298. stages: dict[str, dict[str, object]] = {}
  299. tcl = {
  300. "syn": ROOT / td_files[0],
  301. "phy": ROOT / td_files[1],
  302. "bitgen": ROOT / td_files[2],
  303. }
  304. status = "PASS"
  305. for name in ("syn", "phy", "bitgen"):
  306. stages[name] = run_stage(name, [td, str(tcl[name])], run_root / name, env)
  307. print(f"{name}: exit={stages[name]['exit_code']} duration_s={stages[name]['duration_seconds']}", flush=True)
  308. if stages[name]["exit_code"] != 0:
  309. status = "FAIL"
  310. break
  311. expected = {
  312. "syn": run_root / f"syn/{artifact_basename}_gate.db",
  313. "phy": run_root / f"phy/{artifact_basename}_pr.db",
  314. "bitgen": run_root / f"bitgen/{artifact_basename}.bit",
  315. }
  316. missing = [name for name, path in expected.items() if name in stages and stages[name]["exit_code"] == 0 and not path.is_file()]
  317. if missing:
  318. status = "FAIL"
  319. audit = warning_audit(stages)
  320. if audit["status"] != "PASS":
  321. status = "FAIL"
  322. bitstream = expected["bitgen"]
  323. metrics = parse_metrics(run_root, artifact_basename)
  324. required_metrics = (
  325. "total_luts", "lut", "registers", "dsp", "eram_bram", "mslice",
  326. "lslice", "packed_slices", "fmax_mhz", "setup_slack_ns", "hold_slack_ns",
  327. "setup_total_negative_slack_ns", "hold_total_negative_slack_ns",
  328. )
  329. missing_metrics = [name for name in required_metrics if metrics[name] is None]
  330. timing_pass = bool(
  331. not missing_metrics
  332. and metrics["violation_endpoint_counts"]
  333. and metrics["all_violation_endpoint_counts_zero"]
  334. and metrics["fmax_mhz"] >= 25.0
  335. and metrics["setup_slack_ns"] >= 0.0
  336. and metrics["hold_slack_ns"] >= 0.0
  337. and metrics["setup_total_negative_slack_ns"] == 0.0
  338. and metrics["hold_total_negative_slack_ns"] == 0.0
  339. )
  340. if not timing_pass:
  341. status = "FAIL"
  342. receipt = {
  343. "schema": "prod2u-6400-td-receipt-v1",
  344. "run_id": run_id,
  345. "status": status,
  346. "generated_at": datetime.now(timezone.utc).isoformat(),
  347. "commit": commit,
  348. "tree": tree,
  349. "branch": git("branch", "--show-current"),
  350. "clean_before": not bool(dirty_before),
  351. "clean_after": not bool(git("status", "--porcelain")),
  352. **profile_receipt_fields(profile_name),
  353. "project": str(project_path.relative_to(ROOT)),
  354. "project_sha256": sha256(project_path),
  355. "source_closure": str(closure_path.relative_to(ROOT)),
  356. "source_closure_sha256": sha256(closure_path),
  357. "source_manifest_sha256": hashlib.sha256(manifest_bytes).hexdigest(),
  358. "inputs": inputs,
  359. "tool": {
  360. "command": "td2026",
  361. "resolved": td,
  362. "version_probe_exit": version_probe.returncode,
  363. "version": version_text,
  364. "container_image_id": os.environ.get("PROD2U_CONTAINER_IMAGE_ID"),
  365. "container_digest": os.environ.get("PROD2U_CONTAINER_DIGEST"),
  366. },
  367. "safety": {"opens_serial": False, "programs_hardware": False, "jtag": False},
  368. "stages": stages,
  369. "missing_outputs": missing,
  370. "missing_metrics": missing_metrics,
  371. "warning_audit": audit,
  372. "metrics": metrics,
  373. "timing_pass_25mhz": timing_pass,
  374. "bitstream": str(bitstream) if bitstream.is_file() else None,
  375. "bitstream_sha256": sha256(bitstream) if bitstream.is_file() else None,
  376. "deployment_status": (
  377. "UNSAFE_UNTIL_HOST_TTL_PINS_ARE_FROZEN_AND_HARDWARE_VALIDATED"
  378. if profile["production"]
  379. else "IDENTIFICATION_ONLY_NOT_FOR_PRODUCTION_OR_DEPLOYMENT"
  380. ),
  381. "known_unbound_ports": list(EXPECTED_UNBOUND_PORTS),
  382. }
  383. receipt_path = run_root / "td-receipt.json"
  384. receipt_path.write_text(json.dumps(receipt, indent=2, sort_keys=True) + "\n", encoding="utf-8")
  385. print(receipt_path)
  386. if status != "PASS":
  387. for name, record in stages.items():
  388. if record["exit_code"] != 0:
  389. log = Path(str(record["log"]))
  390. print(f"--- {name} log tail ---", file=sys.stderr)
  391. print("\n".join(log.read_text(encoding="utf-8", errors="replace").splitlines()[-120:]), file=sys.stderr)
  392. return 1
  393. print(f"TD_PASS bitstream_sha256={receipt['bitstream_sha256']}")
  394. return 0
  395. if __name__ == "__main__":
  396. raise SystemExit(main())