run_uart_resource_ab.py 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134
  1. #!/usr/bin/env python3
  2. """Run and record the fixed-27 versus fractional Host UART A/B trial."""
  3. from __future__ import annotations
  4. import argparse
  5. import hashlib
  6. import json
  7. from pathlib import Path
  8. import subprocess
  9. import tempfile
  10. ROOT = Path(__file__).resolve().parents[1]
  11. DEFAULT_OUTPUT = ROOT / "receipts" / "resource" / "uart-baud-ab.json"
  12. CANDIDATES = {
  13. "fixed_27": {
  14. "top": "uart_fixed_candidate_top",
  15. "sources": [
  16. "src/common/uart_rx_byte.v",
  17. "src/common/uart_tx_byte.v",
  18. "tests/resource/uart_fixed_candidate_top.v",
  19. ],
  20. "wire_behavior": "27 clocks per bit; 925925.926 baud; +0.469% nominal error",
  21. },
  22. "fractional_27_28": {
  23. "top": "uart_fractional_candidate_top",
  24. "sources": [
  25. "src/common/uart_rx_byte_fractional.v",
  26. "src/common/uart_tx_byte_fractional.v",
  27. "tests/resource/uart_fractional_candidate_top.v",
  28. ],
  29. "wire_behavior": "phase accumulator; 27/28 clocks per bit; zero long-term nominal error",
  30. },
  31. }
  32. def run(argv: list[str]) -> str:
  33. result = subprocess.run(argv, cwd=ROOT, check=True, text=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
  34. return result.stdout
  35. def sha256(path: Path) -> str:
  36. return hashlib.sha256(path.read_bytes()).hexdigest()
  37. def yosys_stats(top: str, sources: list[str]) -> tuple[dict[str, object], str]:
  38. script = (
  39. "read_verilog " + " ".join(sources) + "; "
  40. f"hierarchy -check -top {top}; synth -noabc -top {top}; abc -lut 4; stat -json"
  41. )
  42. output = run(["yosys", "-Q", "-T", "-p", script])
  43. marker = output.rfind('{\n "creator"')
  44. if marker < 0:
  45. raise RuntimeError("Yosys JSON statistics were not found")
  46. value, _ = json.JSONDecoder().raw_decode(output[marker:])
  47. design = value["design"]
  48. types = design["num_cells_by_type"]
  49. dff = sum(int(count) for name, count in types.items() if "DFF" in name)
  50. return {
  51. "lut4": int(types.get("$lut", 0)),
  52. "dff": dff,
  53. "total_cells": int(design["num_cells"]),
  54. "cell_types": types,
  55. }, script
  56. def main() -> int:
  57. parser = argparse.ArgumentParser()
  58. parser.add_argument("--output", type=Path, default=DEFAULT_OUTPUT)
  59. args = parser.parse_args()
  60. status = run(["git", "status", "--porcelain"])
  61. if status:
  62. raise RuntimeError("resource A/B receipts require a clean worktree")
  63. commit = run(["git", "rev-parse", "HEAD"]).strip()
  64. with tempfile.TemporaryDirectory(prefix="prod2u-uart-ab-") as directory:
  65. simulation = Path(directory) / "uart_baud_candidates_tb.vvp"
  66. simulation_sources = [
  67. "src/common/uart_rx_byte.v",
  68. "src/common/uart_tx_byte.v",
  69. "src/common/uart_rx_byte_fractional.v",
  70. "src/common/uart_tx_byte_fractional.v",
  71. "tests/sim/uart_baud_candidates_tb.v",
  72. ]
  73. run(["iverilog", "-g2012", "-Wall", "-s", "uart_baud_candidates_tb", "-o", str(simulation), *simulation_sources])
  74. simulation_output = run(["vvp", str(simulation)]).strip()
  75. results: dict[str, object] = {}
  76. for name, candidate in CANDIDATES.items():
  77. top = str(candidate["top"])
  78. sources = list(candidate["sources"])
  79. run(["verilator", "--lint-only", "--Wall", "--top-module", top, *sources])
  80. resources, yosys_script = yosys_stats(top, sources)
  81. results[name] = {
  82. "top": top,
  83. "sources": {source: sha256(ROOT / source) for source in sources},
  84. "wire_behavior": candidate["wire_behavior"],
  85. "yosys_lut4_mapping": resources,
  86. "yosys_script": yosys_script,
  87. "verilator_lint": "PASS",
  88. }
  89. fixed_lut = results["fixed_27"]["yosys_lut4_mapping"]["lut4"]
  90. fractional_lut = results["fractional_27_28"]["yosys_lut4_mapping"]["lut4"]
  91. if fixed_lut > fractional_lut:
  92. raise RuntimeError("selection rule changed: fractional candidate is now smaller")
  93. receipt = {
  94. "schema": "prod2u-6400-uart-resource-ab-v1",
  95. "run_id": f"uart-baud-ab-{commit[:12]}",
  96. "source_commit": commit,
  97. "project_sha256": sha256(ROOT / "products/6400-control/project.json"),
  98. "contract_sha256": (ROOT / "generated/6400/contract-sha256.txt").read_text(encoding="ascii").strip(),
  99. "tools": {
  100. "yosys": run(["yosys", "-V"]).strip(),
  101. "verilator": run(["verilator", "--version"]).strip(),
  102. "iverilog": run(["iverilog", "-V"]).splitlines()[0],
  103. },
  104. "bit_level_simulation": {
  105. "status": "PASS",
  106. "coverage": "peer 26/27/28 clocks, +/-1-clock per-bit jitter, arbitrary start phase, 64 continuous bytes, TX loopback",
  107. "output": simulation_output,
  108. },
  109. "candidates": results,
  110. "selected": "fixed_27",
  111. "selection_reason": "Both candidates passed bit-level simulation and lint; fixed-27 uses fewer mapped LUT4 and DFF resources.",
  112. "td_resource_comparison": "PENDING_L13_TD_RUN",
  113. "hardware_validation_state": "NOT RUN",
  114. }
  115. args.output.parent.mkdir(parents=True, exist_ok=True)
  116. args.output.write_text(json.dumps(receipt, indent=2, sort_keys=True) + "\n", encoding="utf-8")
  117. print(f"PASS: selected fixed_27 ({fixed_lut} LUT4 vs {fractional_lut} LUT4)")
  118. return 0
  119. if __name__ == "__main__":
  120. raise SystemExit(main())