| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434 |
- #!/usr/bin/env python3
- """Run device-backed TD resource/timing comparisons for 6400 A/B candidates."""
- 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 signal
- import subprocess
- import sys
- import time
- ROOT = Path(__file__).resolve().parents[1]
- CANDIDATE_SOURCE = ROOT / "tests/resource/architecture_ab_candidates.v"
- PIN_CONSTRAINTS = ROOT / "constraints/prod2u_6400_architecture_ab.adc"
- TIMING_CONSTRAINTS = ROOT / "constraints/prod2u_6400_architecture_ab.sdc"
- TD_SCRIPT = ROOT / "td/resource/prod2u_6400_architecture_ab.tcl"
- TRIALS = {
- "fsm_encoding": ("ab_fsm_binary", "ab_fsm_onehot"),
- "bmc_tx_serializer": ("ab_bmc_tx_dedicated", "ab_bmc_tx_shared"),
- "array_storage": ("ab_store_ff", "ab_store_eram"),
- "pi_form": ("ab_pi_positional", "ab_pi_incremental"),
- "safety_compare": ("ab_safety_parallel", "ab_safety_sequential"),
- "atomic_commit": ("ab_commit_copy", "ab_commit_bank"),
- "crc_datapath": ("ab_crc_independent", "ab_crc_shared"),
- "snapshot_materialization": ("ab_snapshot_copy", "ab_snapshot_stream"),
- }
- CANDIDATES = tuple(top for pair in TRIALS.values() for top in pair)
- TIMING_MEASURED = "MEASURED_REGISTER_TO_REGISTER_PATH"
- TIMING_NOT_APPLICABLE = "NOT_APPLICABLE_NO_REG_TO_REG_PATH"
- 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 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 run_bounded(
- command: list[str], *, cwd: Path, env: dict[str, str], log: Path, timeout: int
- ) -> dict[str, object]:
- started = time.monotonic()
- with log.open("wb") as stream:
- process = subprocess.Popen(
- command,
- cwd=cwd,
- env=env,
- stdout=stream,
- stderr=subprocess.STDOUT,
- start_new_session=(os.name == "posix"),
- )
- timed_out = False
- try:
- return_code = process.wait(timeout=timeout)
- except subprocess.TimeoutExpired:
- timed_out = True
- if os.name == "posix":
- try:
- os.killpg(process.pid, signal.SIGKILL)
- except ProcessLookupError:
- pass
- else:
- process.kill()
- return_code = process.wait()
- return {
- "command": command,
- "cwd": str(cwd),
- "exit_code": return_code,
- "timed_out": timed_out,
- "timeout_seconds": timeout,
- "duration_seconds": round(time.monotonic() - started, 3),
- "log": str(log),
- "log_sha256": sha256(log),
- }
- def parse_candidate(top: str, root: Path) -> dict[str, object]:
- area_paths = [root / f"{top}_gate.area", root / f"{top}_pr.area"]
- timing_path = root / f"{top}_pr.timing"
- log_path = root / "td.log"
- area = "\n".join(
- path.read_text(encoding="utf-8", errors="replace")
- for path in area_paths
- if path.is_file()
- )
- timing = timing_path.read_text(encoding="utf-8", errors="replace") if timing_path.is_file() else ""
- log_text = log_path.read_text(encoding="utf-8", errors="replace") if log_path.is_file() else ""
- slice_matches = re.findall(r"(\d+)\s+mslices,\s+(\d+)\s+lslices", log_text, re.IGNORECASE)
- mslice = int(slice_matches[-1][0]) if slice_matches else None
- lslice = int(slice_matches[-1][1]) if slice_matches else None
- reported_total_luts = first_int(area, (r"^#Total_luts\s+(\d+)",))
- lut = first_int(area, (r"^#lut\s+(\d+)",))
- fmax_mhz = first_float(
- timing,
- (r"Fmax[^\n]*?([0-9]+(?:\.[0-9]+)?)\s*MHz", r"([0-9]+(?:\.[0-9]+)?)\s*MHz"),
- )
- register_to_register_path = bool(
- re.search(r"^From Clock\s*:\s*\S+", timing, re.IGNORECASE | re.MULTILINE)
- and re.search(r"^To Clock\s*:\s*\S+", timing, re.IGNORECASE | re.MULTILINE)
- )
- violation_endpoint_counts = [
- int(value)
- for value in re.findall(r"(\d+)\s+Viol Endpoints", timing, re.IGNORECASE)
- ]
- metrics = {
- "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+)",)),
- "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": fmax_mhz,
- "timing_applicability": (
- TIMING_MEASURED if register_to_register_path else TIMING_NOT_APPLICABLE
- ),
- "register_to_register_path_present": register_to_register_path,
- "violation_endpoint_counts": violation_endpoint_counts,
- "all_violation_endpoint_counts_zero": all(
- value == 0 for value in violation_endpoint_counts
- ),
- "setup_slack_ns": first_float(
- timing,
- (
- r"^\s*SWNS\s*:\s*(-?[0-9]+(?:\.[0-9]+)?)\s*ns",
- r"(?:Setup|WNS)[^\n]*?(-?[0-9]+(?:\.[0-9]+)?)\s*ns",
- ),
- ),
- "hold_slack_ns": first_float(
- timing,
- (
- r"^\s*HWNS\s*:\s*(-?[0-9]+(?:\.[0-9]+)?)\s*ns",
- r"(?:Hold|HWNS)[^\n]*?(-?[0-9]+(?:\.[0-9]+)?)\s*ns",
- ),
- ),
- }
- return {
- "metrics": metrics,
- "area_reports": [
- {"path": str(path), "sha256": sha256(path)} for path in area_paths if path.is_file()
- ],
- "timing_report": (
- {"path": str(timing_path), "sha256": sha256(timing_path)}
- if timing_path.is_file()
- else None
- ),
- }
- def evaluate_timing(metrics: dict[str, object]) -> dict[str, object]:
- """Evaluate timing while distinguishing designs with no reg-to-reg path."""
- setup_slack = metrics["setup_slack_ns"]
- hold_slack = metrics["hold_slack_ns"]
- violation_counts = metrics["violation_endpoint_counts"]
- common_pass = bool(
- setup_slack is not None
- and hold_slack is not None
- and setup_slack >= 0.0
- and hold_slack >= 0.0
- and all(value == 0 for value in violation_counts)
- )
- applicability = metrics["timing_applicability"]
- if applicability == TIMING_NOT_APPLICABLE:
- passed = common_pass and metrics["fmax_mhz"] is None
- return {
- "status": "PASS" if passed else "FAIL",
- "classification": TIMING_NOT_APPLICABLE,
- "fmax_requirement": "NOT_APPLICABLE",
- "meets_25mhz": None,
- "reason": (
- "No register-to-register path; all reported setup/hold slacks and "
- "violation counts are non-negative/zero."
- if passed
- else "No register-to-register path, but timing status is incomplete or failing."
- ),
- }
- fmax_mhz = metrics["fmax_mhz"]
- passed = bool(
- common_pass
- and violation_counts
- and fmax_mhz is not None
- and fmax_mhz >= 25.0
- )
- return {
- "status": "PASS" if passed else "FAIL",
- "classification": TIMING_MEASURED,
- "fmax_requirement": "AT_LEAST_25_MHZ",
- "meets_25mhz": bool(fmax_mhz is not None and fmax_mhz >= 25.0),
- "reason": (
- "Register-to-register Fmax and all setup/hold checks pass."
- if passed
- else "Register-to-register timing is missing, below 25 MHz, or has violations."
- ),
- }
- def warning_audit(log_path: Path) -> dict[str, object]:
- lines = log_path.read_text(encoding="utf-8", errors="replace").splitlines()
- severity = re.compile(
- r"^\s*(?:(?:[A-Z][A-Z0-9_-]*-\d+)\s+)?"
- r"(?:CRITICAL-WARNING|WARNING|ERROR|FATAL)\s*:",
- re.IGNORECASE,
- )
- noteworthy = [
- line.strip()
- for line in lines
- if severity.search(line)
- or re.search(
- r"Bitgen will abort|No ADC ports:|\bunrouted\b|\bviolations?\b",
- line,
- re.IGNORECASE,
- )
- ]
- allowlisted = [
- line
- for line in noteworthy
- if re.search(r"\bSYN-6021\b|Bitgen will abort|No ADC ports:", line, re.IGNORECASE)
- ]
- blocking_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),
- )
- blocking = [
- line
- for line in noteworthy
- if any(pattern.search(line) for pattern in blocking_patterns)
- ]
- return {
- "status": "FAIL" if blocking else "PASS",
- "noteworthy_count": len(noteworthy),
- "blocking_count": len(blocking),
- "allowlisted_expected_count": len(allowlisted),
- "allowlisted_expected": allowlisted[:100],
- "noteworthy": noteworthy[:200],
- "blocking": blocking[:100],
- }
- def main(argv: list[str] | None = None) -> int:
- parser = argparse.ArgumentParser()
- parser.add_argument("--run-root", type=Path)
- parser.add_argument("--timeout-seconds", type=int, default=900)
- args = parser.parse_args(argv)
- 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_AB_MISSING: td2026 is not on PATH", file=sys.stderr)
- return 4
- dirty = git("status", "--porcelain")
- if dirty:
- print("TD_AB_BLOCKED: source worktree must be clean", file=sys.stderr)
- print(dirty, file=sys.stderr)
- return 3
- if args.timeout_seconds <= 0:
- raise SystemExit("--timeout-seconds must be positive")
- commit = git("rev-parse", "HEAD")
- tree = git("rev-parse", "HEAD^{tree}")
- stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
- run_id = f"6400-architecture-td-ab-{stamp}-{commit[:8]}"
- run_root = args.run_root or Path(
- os.environ.get("PROD2U_TD_AB_RUN_ROOT", "/data/prod2u/cpld-runs")
- ) / run_id
- run_root.mkdir(parents=True, exist_ok=False)
- version = subprocess.run([td, "-version"], capture_output=True, text=True, check=False)
- version_text = (version.stdout + version.stderr).strip()
- resolved_td = Path(td).resolve()
- vendor_td = Path(os.environ.get("PRODU2_TD_ROOT", "/data/anlogic/TD_Release_2026.1_SP2_NL")) / "bin/td"
- env_base = os.environ.copy()
- env_base["PROD2U_SOURCE_ROOT"] = str(ROOT)
- candidate_records: dict[str, dict[str, object]] = {}
- status = "PASS"
- for top in CANDIDATES:
- candidate_root = run_root / top
- candidate_root.mkdir()
- env = env_base.copy()
- env["PROD2U_AB_TOP"] = top
- run = run_bounded(
- [td, str(TD_SCRIPT)],
- cwd=candidate_root,
- env=env,
- log=candidate_root / "td.log",
- timeout=args.timeout_seconds,
- )
- outputs = {
- "gate_db": candidate_root / f"{top}_gate.db",
- "pr_db": candidate_root / f"{top}_pr.db",
- }
- missing = [name for name, path in outputs.items() if not path.is_file()]
- parsed = parse_candidate(top, candidate_root)
- audit = warning_audit(candidate_root / "td.log")
- metrics = parsed["metrics"]
- required_metrics = (
- "total_luts", "lut", "registers", "dsp", "eram_bram", "mslice",
- "lslice", "packed_slices", "setup_slack_ns", "hold_slack_ns",
- )
- missing_metrics = [name for name in required_metrics if metrics[name] is None]
- if (
- metrics["timing_applicability"] == TIMING_MEASURED
- and metrics["fmax_mhz"] is None
- ):
- missing_metrics.append("fmax_mhz")
- timing_evaluation = evaluate_timing(metrics)
- timing_pass = timing_evaluation["status"] == "PASS"
- candidate_status = "PASS" if (
- run["exit_code"] == 0
- and not run["timed_out"]
- and not missing
- and not missing_metrics
- and timing_pass
- and audit["status"] == "PASS"
- ) else "FAIL"
- if candidate_status != "PASS":
- status = "FAIL"
- candidate_records[top] = {
- "status": candidate_status,
- "run": run,
- "missing_outputs": missing,
- "missing_metrics": missing_metrics,
- "timing_pass_25mhz": timing_pass,
- "timing_evaluation": timing_evaluation,
- "warning_audit": audit,
- "outputs": {
- name: {"path": str(path), "sha256": sha256(path)}
- for name, path in outputs.items()
- if path.is_file()
- },
- **parsed,
- }
- print(
- f"{top}: {candidate_status} exit={run['exit_code']} "
- f"timeout={run['timed_out']} duration_s={run['duration_seconds']}",
- flush=True,
- )
- trial_records = {
- name: {
- "candidates": pair,
- "results": {top: candidate_records[top] for top in pair},
- }
- for name, pair in TRIALS.items()
- }
- clean_after = not bool(git("status", "--porcelain"))
- if not clean_after:
- status = "FAIL"
- receipt = {
- "schema": "prod2u-6400-architecture-td-ab-v1",
- "run_id": run_id,
- "generated_at": datetime.now(timezone.utc).isoformat(),
- "status": status,
- "commit": commit,
- "tree": tree,
- "branch": git("branch", "--show-current"),
- "clean_before": not bool(dirty),
- "clean_after": clean_after,
- "command": "python3 tools/run_6400_architecture_td_ab.py",
- "inputs": {
- str(path.relative_to(ROOT)): sha256(path)
- for path in (CANDIDATE_SOURCE, PIN_CONSTRAINTS, TIMING_CONSTRAINTS, TD_SCRIPT)
- },
- "tool": {
- "wrapper": str(resolved_td),
- "wrapper_sha256": sha256(resolved_td),
- "vendor_binary": str(vendor_td),
- "vendor_binary_sha256": sha256(vendor_td) if vendor_td.is_file() else None,
- "version_probe_exit": version.returncode,
- "version": version_text,
- "container_image_id": os.environ.get("PROD2U_CONTAINER_IMAGE_ID"),
- "container_digest": os.environ.get("PROD2U_CONTAINER_DIGEST"),
- },
- "trials": trial_records,
- "hardware": "NOT RUN",
- "jtag": "NOT RUN",
- "com": "NOT RUN",
- }
- receipt_path = run_root / "architecture-td-ab-receipt.json"
- receipt_path.write_text(json.dumps(receipt, indent=2, sort_keys=True) + "\n", encoding="utf-8")
- print(receipt_path)
- print(f"RESOURCE_ARCHITECTURE_TD_AB_{status} trials={len(TRIALS)} candidates={len(CANDIDATES)}")
- return 0 if status == "PASS" else 1
- if __name__ == "__main__":
- raise SystemExit(main())
|