run_6400_td.py 17 KB

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