run_6400_td.py 17 KB

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