| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429 |
- #!/usr/bin/env python3
- """Run clean, source-bound TD synthesis, place/route, and bit generation."""
- from __future__ import annotations
- import argparse
- from datetime import datetime, timezone
- import hashlib
- import json
- import os
- from pathlib import Path
- import re
- import shutil
- import subprocess
- import sys
- import time
- ROOT = Path(__file__).resolve().parents[1]
- DEFAULT_PROFILE = "6400-front-rear"
- HARDWARE_PROFILES = {
- "6400-front-rear": {
- "project": "products/6400-front-rear/project.json",
- "closure": "products/6400-front-rear/source-closure.json",
- "td_project": "td/prod2u_6400_front_back.prj",
- "td_files": (
- "td/syn/prod2u_6400_front_back.tcl",
- "td/phy/prod2u_6400_front_back.tcl",
- "td/bitgen/prod2u_6400_front_back.tcl",
- ),
- "artifact_basename": "prod2u_6400_front_back",
- "production": True,
- "stimulus": False,
- "hardware_host_interfaces": ("host_rs232", "host_i2c_con36_logic_bound"),
- },
- }
- # Backward-compatible aliases for callers importing the production defaults.
- PROJECT = ROOT / str(HARDWARE_PROFILES[DEFAULT_PROFILE]["project"])
- CLOSURE = ROOT / str(HARDWARE_PROFILES[DEFAULT_PROFILE]["closure"])
- TD_PROJECT = str(HARDWARE_PROFILES[DEFAULT_PROFILE]["td_project"])
- TD_FILES = tuple(HARDWARE_PROFILES[DEFAULT_PROFILE]["td_files"])
- CONSTRAINT_FILES = (
- "constraints/prod2u_6400_front_back.adc",
- "constraints/prod2u_6400_front_back.sdc",
- )
- EXPECTED_UNBOUND_PORTS: tuple[str, ...] = ()
- def sha256(path: Path) -> str:
- digest = hashlib.sha256()
- with path.open("rb") as stream:
- for chunk in iter(lambda: stream.read(1024 * 1024), b""):
- digest.update(chunk)
- return digest.hexdigest()
- def git(*args: str) -> str:
- return subprocess.check_output(["git", *args], cwd=ROOT, text=True).strip()
- def _load_inherited_json(path: Path, list_key: str, additional_key: str) -> tuple[list[str], list[str]]:
- payload = json.loads(path.read_text(encoding="utf-8"))
- inputs = [str(path.relative_to(ROOT))]
- values: list[str] = []
- inherited = payload.get("inherits")
- if inherited:
- parent_values, parent_inputs = _load_inherited_json(
- ROOT / inherited, list_key, additional_key
- )
- values.extend(parent_values)
- inputs.extend(parent_inputs)
- values.extend(payload.get(list_key, payload.get(additional_key, [])))
- return values, inputs
- def source_closure(profile_name: str) -> tuple[list[str], list[str]]:
- profile = HARDWARE_PROFILES[profile_name]
- return _load_inherited_json(ROOT / str(profile["closure"]), "sources", "additional_sources")
- def project_inputs(path: Path) -> list[str]:
- payload = json.loads(path.read_text(encoding="utf-8"))
- paths = [str(path.relative_to(ROOT))]
- if payload.get("inherits"):
- paths.extend(project_inputs(ROOT / payload["inherits"]))
- return paths
- def profile_receipt_fields(profile_name: str) -> dict[str, object]:
- profile = HARDWARE_PROFILES[profile_name]
- return {
- "profile": profile_name,
- "firmware_role": "production" if profile["production"] else "identification",
- "production": bool(profile["production"]),
- "stimulus": bool(profile["stimulus"]),
- "simulation_only": False,
- "artifact_basename": str(profile["artifact_basename"]),
- "hardware_host_interfaces": list(profile["hardware_host_interfaces"]),
- }
- def input_manifest(profile_name: str = DEFAULT_PROFILE) -> dict[str, str]:
- profile = HARDWARE_PROFILES[profile_name]
- sources, closure_inputs = source_closure(profile_name)
- project_path = ROOT / str(profile["project"])
- paths = [
- *sources,
- *CONSTRAINT_FILES,
- str(profile["td_project"]),
- *profile["td_files"],
- *project_inputs(project_path),
- *closure_inputs,
- ]
- paths = list(dict.fromkeys(paths))
- missing = [item for item in paths if not (ROOT / item).is_file()]
- if missing:
- raise RuntimeError(f"source closure contains missing inputs: {missing}")
- return {item: sha256(ROOT / item) for item in paths}
- def run_stage(name: str, command: list[str], cwd: Path, env: dict[str, str]) -> dict[str, object]:
- log_path = cwd / f"{name}.log"
- started = time.monotonic()
- with log_path.open("wb") as log:
- completed = subprocess.run(command, cwd=cwd, env=env, stdout=log, stderr=subprocess.STDOUT, check=False)
- duration = round(time.monotonic() - started, 3)
- return {
- "command": command,
- "cwd": str(cwd),
- "exit_code": completed.returncode,
- "duration_seconds": duration,
- "log": str(log_path),
- "log_sha256": sha256(log_path),
- }
- def first_int(text: str, patterns: tuple[str, ...]) -> int | None:
- for pattern in patterns:
- match = re.search(pattern, text, re.IGNORECASE | re.MULTILINE)
- if match:
- return int(match.group(1))
- return None
- def first_float(text: str, patterns: tuple[str, ...]) -> float | None:
- for pattern in patterns:
- match = re.search(pattern, text, re.IGNORECASE | re.MULTILINE)
- if match:
- return float(match.group(1))
- return None
- def parse_metrics(
- run_root: Path, artifact_basename: str = "prod2u_6400_front_back"
- ) -> dict[str, object]:
- area_paths = [
- run_root / f"phy/{artifact_basename}_phy.area",
- run_root / f"syn/{artifact_basename}_gate.area",
- ]
- area = "\n".join(path.read_text(encoding="utf-8", errors="replace") for path in area_paths if path.is_file())
- timing_path = run_root / f"phy/{artifact_basename}_pr.timing"
- timing = timing_path.read_text(encoding="utf-8", errors="replace") if timing_path.is_file() else ""
- logs = "\n".join(
- path.read_text(encoding="utf-8", errors="replace")
- for path in (run_root / "syn/syn.log", run_root / "phy/phy.log", run_root / "bitgen/bitgen.log")
- if path.is_file()
- )
- reported_total_luts = first_int(area, (r"^#Total_luts\s+(\d+)",))
- lut = first_int(area, (r"^#lut\s+(\d+)",))
- slice_matches = re.findall(r"(\d+)\s+mslices,\s+(\d+)\s+lslices", logs, re.IGNORECASE)
- mslice = int(slice_matches[-1][0]) if slice_matches else None
- lslice = int(slice_matches[-1][1]) if slice_matches else None
- violation_endpoint_counts = [
- int(value)
- for value in re.findall(r"(\d+)\s+Viol Endpoints", timing, re.IGNORECASE)
- ]
- return {
- "total_luts": reported_total_luts if reported_total_luts is not None else lut,
- "total_luts_source": "#Total_luts" if reported_total_luts is not None else "#lut_fallback",
- "lut": lut,
- "registers": first_int(area, (r"^#reg\s+(\d+)",)),
- "dsp": first_int(area, (r"^#dsp\s+(\d+)",)),
- "eram_bram": first_int(area, (r"^#(?:eram|bram)\s+(\d+)",)),
- "bram": first_int(area, (r"^#bram\s+(\d+)",)),
- "mslice": mslice,
- "lslice": lslice,
- "packed_slices": mslice + lslice if mslice is not None and lslice is not None else None,
- "packed_slices_derivation": "mslice_plus_lslice",
- "fmax_mhz": first_float(timing, (r"Fmax[^\n]*?([0-9]+(?:\.[0-9]+)?)\s*MHz", r"([0-9]+(?:\.[0-9]+)?)\s*MHz")),
- "setup_slack_ns": first_float(
- timing,
- (r"^\s*SWNS\s*:\s*(-?[0-9]+(?:\.[0-9]+)?)\s*ns",),
- ),
- "hold_slack_ns": first_float(
- timing,
- (r"^\s*HWNS\s*:\s*(-?[0-9]+(?:\.[0-9]+)?)\s*ns",),
- ),
- "setup_total_negative_slack_ns": first_float(
- timing,
- (r"^\s*SWNS\s*:\s*-?[0-9]+(?:\.[0-9]+)?\s*ns,\s*STNS\s*:\s*(-?[0-9]+(?:\.[0-9]+)?)\s*ns",),
- ),
- "hold_total_negative_slack_ns": first_float(
- timing,
- (r"^\s*HWNS\s*:\s*-?[0-9]+(?:\.[0-9]+)?\s*ns,\s*HTNS\s*:\s*(-?[0-9]+(?:\.[0-9]+)?)\s*ns",),
- ),
- "violation_endpoint_counts": violation_endpoint_counts,
- "all_violation_endpoint_counts_zero": all(
- value == 0 for value in violation_endpoint_counts
- ),
- "area_reports": [str(path) for path in area_paths if path.is_file()],
- "timing_report": str(timing_path) if timing_path.is_file() else None,
- }
- def warning_audit(stage_records: dict[str, dict[str, object]]) -> dict[str, object]:
- lines: list[str] = []
- blocking: list[str] = []
- unbound_ports: set[str] = set()
- severity = re.compile(
- r"^\s*(?:(?:[A-Z][A-Z0-9_-]*-\d+)\s+)?"
- r"(?:CRITICAL-WARNING|WARNING|ERROR|FATAL)\s*:",
- re.IGNORECASE,
- )
- noteworthy = re.compile(
- r"Bitgen will abort|No ADC ports:|\bunrouted\b|\bviolations?\b|"
- r"\bunconstrained\b|\bunassigned\b|\blatch\b|\bloop\b",
- re.IGNORECASE,
- )
- blocker_patterns = (
- re.compile(
- r"^\s*(?:(?:[A-Z][A-Z0-9_-]*-\d+)\s+)?(?:ERROR|FATAL)\s*:",
- re.IGNORECASE,
- ),
- re.compile(r"^\s*\[(?:ERROR|FATAL)\]", re.IGNORECASE),
- re.compile(
- r"\b(?:synthesis|placement|place\s*&\s*route|routing|route|fit|bitgen)"
- r"\s+(?:failed|failure)\b",
- re.IGNORECASE,
- ),
- re.compile(r"\b(?:setup|hold|timing)\s+(?:check\s+)?(?:failed|failure)\b", re.IGNORECASE),
- re.compile(r"(?:\b[1-9]\d*\s+unrouted\b|\bunrouted\s*[:=]\s*[1-9]\d*)", re.IGNORECASE),
- )
- for record in stage_records.values():
- log = Path(str(record["log"]))
- for line in log.read_text(encoding="utf-8", errors="replace").splitlines():
- if "No ADC ports:" in line:
- suffix = line.split("No ADC ports:", 1)[1]
- unbound_ports.update(
- re.findall(r"[A-Za-z_][A-Za-z0-9_]*(?:\[\d+(?::\d+)?\])?", suffix)
- )
- if severity.search(line) or noteworthy.search(line):
- compact = line.strip()
- if compact and compact not in lines:
- lines.append(compact)
- if any(pattern.search(compact) for pattern in blocker_patterns):
- blocking.append(compact)
- expected = set(EXPECTED_UNBOUND_PORTS)
- unexpected_unbound = sorted(unbound_ports - expected)
- missing_expected_unbound = sorted(expected - unbound_ports)
- if unexpected_unbound:
- blocking.append("unexpected unbound ports: " + ", ".join(unexpected_unbound))
- if missing_expected_unbound:
- blocking.append("expected unbound ports not reported: " + ", ".join(missing_expected_unbound))
- return {
- "status": "FAIL" if blocking else "PASS",
- "noteworthy_count": len(lines),
- "blocking_count": len(blocking),
- "expected_unbound_ports": sorted(expected),
- "observed_unbound_ports": sorted(unbound_ports),
- "unexpected_unbound_ports": unexpected_unbound,
- "missing_expected_unbound_ports": missing_expected_unbound,
- "blocking": blocking[:100],
- "noteworthy": lines[:300],
- }
- def main(argv: list[str] | None = None) -> int:
- parser = argparse.ArgumentParser()
- parser.add_argument(
- "--profile", choices=tuple(HARDWARE_PROFILES), default=DEFAULT_PROFILE
- )
- parser.add_argument("--run-root", type=Path)
- args = parser.parse_args(argv)
- profile_name = args.profile
- profile = HARDWARE_PROFILES[profile_name]
- project_path = ROOT / str(profile["project"])
- closure_path = ROOT / str(profile["closure"])
- artifact_basename = str(profile["artifact_basename"])
- td_files = tuple(profile["td_files"])
- td = shutil.which("td2026")
- local_td = ROOT / "tools/td2026"
- if td is None and local_td.is_file():
- td = str(local_td)
- if td is None:
- print("TD_MISSING: td2026 is not on PATH", file=sys.stderr)
- return 4
- dirty_before = git("status", "--porcelain")
- if dirty_before:
- print("TD_BLOCKED: source worktree must be clean", file=sys.stderr)
- print(dirty_before, file=sys.stderr)
- return 3
- commit = git("rev-parse", "HEAD")
- tree = git("rev-parse", "HEAD^{tree}")
- stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
- run_kind = "6400-td"
- run_id = f"{run_kind}-{stamp}-{commit[:8]}"
- run_root = args.run_root or Path(os.environ.get("PROD2U_TD_RUN_ROOT", "/data/prod2u/cpld-runs")) / run_id
- for stage in ("syn", "phy", "bitgen"):
- (run_root / stage).mkdir(parents=True, exist_ok=False)
- inputs = input_manifest(profile_name)
- manifest_bytes = json.dumps(inputs, sort_keys=True, separators=(",", ":")).encode()
- version_probe = subprocess.run([td, "-version"], capture_output=True, text=True, check=False)
- version_text = (version_probe.stdout + version_probe.stderr).strip()
- if not version_text:
- td_binary = Path("/data/anlogic/TD_Release_2026.1_SP2_NL/bin/td")
- binary_identity = sha256(td_binary) if td_binary.is_file() else "unavailable"
- version_text = (
- "Anlogic TD 2026.1 SP2 Linux host-mounted toolchain; "
- f"td_binary_sha256={binary_identity}"
- )
- env = os.environ.copy()
- env["PROD2U_SOURCE_ROOT"] = str(ROOT)
- env["PATH"] = str(ROOT / "tools") + os.pathsep + env.get("PATH", "")
- stages: dict[str, dict[str, object]] = {}
- tcl = {
- "syn": ROOT / td_files[0],
- "phy": ROOT / td_files[1],
- "bitgen": ROOT / td_files[2],
- }
- status = "PASS"
- for name in ("syn", "phy", "bitgen"):
- stages[name] = run_stage(name, [td, str(tcl[name])], run_root / name, env)
- print(f"{name}: exit={stages[name]['exit_code']} duration_s={stages[name]['duration_seconds']}", flush=True)
- if stages[name]["exit_code"] != 0:
- status = "FAIL"
- break
- expected = {
- "syn": run_root / f"syn/{artifact_basename}_gate.db",
- "phy": run_root / f"phy/{artifact_basename}_pr.db",
- "bitgen": run_root / f"bitgen/{artifact_basename}.bit",
- }
- missing = [name for name, path in expected.items() if name in stages and stages[name]["exit_code"] == 0 and not path.is_file()]
- if missing:
- status = "FAIL"
- audit = warning_audit(stages)
- if audit["status"] != "PASS":
- status = "FAIL"
- bitstream = expected["bitgen"]
- metrics = parse_metrics(run_root, artifact_basename)
- required_metrics = (
- "total_luts", "lut", "registers", "dsp", "eram_bram", "mslice",
- "lslice", "packed_slices", "fmax_mhz", "setup_slack_ns", "hold_slack_ns",
- "setup_total_negative_slack_ns", "hold_total_negative_slack_ns",
- )
- missing_metrics = [name for name in required_metrics if metrics[name] is None]
- timing_pass = bool(
- not missing_metrics
- and metrics["violation_endpoint_counts"]
- and metrics["all_violation_endpoint_counts_zero"]
- and metrics["fmax_mhz"] >= 25.0
- and metrics["setup_slack_ns"] >= 0.0
- and metrics["hold_slack_ns"] >= 0.0
- and metrics["setup_total_negative_slack_ns"] == 0.0
- and metrics["hold_total_negative_slack_ns"] == 0.0
- )
- if not timing_pass:
- status = "FAIL"
- receipt = {
- "schema": "prod2u-6400-td-receipt-v1",
- "run_id": run_id,
- "status": status,
- "generated_at": datetime.now(timezone.utc).isoformat(),
- "commit": commit,
- "tree": tree,
- "branch": git("branch", "--show-current"),
- "clean_before": not bool(dirty_before),
- "clean_after": not bool(git("status", "--porcelain")),
- **profile_receipt_fields(profile_name),
- "project": str(project_path.relative_to(ROOT)),
- "project_sha256": sha256(project_path),
- "source_closure": str(closure_path.relative_to(ROOT)),
- "source_closure_sha256": sha256(closure_path),
- "source_manifest_sha256": hashlib.sha256(manifest_bytes).hexdigest(),
- "inputs": inputs,
- "tool": {
- "command": "td2026",
- "resolved": td,
- "version_probe_exit": version_probe.returncode,
- "version": version_text,
- "identity": "host-mounted toolchain /data/anlogic/TD_Release_2026.1_SP2_NL",
- "container_image_id": os.environ.get("PROD2U_CONTAINER_IMAGE_ID"),
- "container_digest": os.environ.get("PROD2U_CONTAINER_DIGEST"),
- },
- "safety": {"opens_serial": False, "programs_hardware": False, "jtag": False},
- "stages": stages,
- "missing_outputs": missing,
- "missing_metrics": missing_metrics,
- "warning_audit": audit,
- "metrics": metrics,
- "timing_pass_25mhz": timing_pass,
- "bitstream": str(bitstream) if bitstream.is_file() else None,
- "bitstream_sha256": sha256(bitstream) if bitstream.is_file() else None,
- "deployment_status": (
- "TD_QUALIFIED_UART_I2C_LOGIC_BOUND_HARDWARE_NOT_RUN"
- if profile["production"]
- else "IDENTIFICATION_ONLY_RS232_ONLY_HARDWARE_NOT_RUN"
- ),
- "known_unbound_ports": list(EXPECTED_UNBOUND_PORTS),
- }
- receipt_path = run_root / "td-receipt.json"
- receipt_path.write_text(json.dumps(receipt, indent=2, sort_keys=True) + "\n", encoding="utf-8")
- print(receipt_path)
- if status != "PASS":
- for name, record in stages.items():
- if record["exit_code"] != 0:
- log = Path(str(record["log"]))
- print(f"--- {name} log tail ---", file=sys.stderr)
- print("\n".join(log.read_text(encoding="utf-8", errors="replace").splitlines()[-120:]), file=sys.stderr)
- return 1
- print(f"TD_PASS bitstream_sha256={receipt['bitstream_sha256']}")
- return 0
- if __name__ == "__main__":
- raise SystemExit(main())
|