Files
nvdriver/tools/gpu_generate_aspm_oracle.py

115 lines
4.3 KiB
Python

#!/usr/bin/env python3
"""Compile literal original inferred policy bodies against a synthetic recorder."""
import argparse
import hashlib
import json
import subprocess
import tempfile
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
def _require_file_text(path: Path, expected: str, label: str) -> None:
if not path.is_file() or path.read_text() != expected:
raise SystemExit(f"Stale or missing {label}: {path}")
def _require_json_equal(path: Path, expected: dict, label: str) -> None:
if not path.is_file():
raise SystemExit(f"Missing {label}: {path}")
try:
actual = json.loads(path.read_text())
except ValueError as exc:
raise SystemExit(f"Invalid JSON in {label} ({path}): {exc}") from exc
if actual != expected:
raise SystemExit(f"Stale {label}: {path}")
def main(argv=None) -> int:
parser = argparse.ArgumentParser(
description="Generate or verify GV100 ASPM policy and alarm C-oracle vectors."
)
parser.add_argument("--check", action="store_true")
args = parser.parse_args(argv)
source = ROOT / "tools/gpu_aspm_policy_oracle.c"
if not source.is_file():
raise SystemExit(f"Missing ASPM oracle C source: {source}")
with tempfile.TemporaryDirectory(prefix="nv-rs-aspm-oracle-") as tmp:
exe = Path(tmp) / "oracle"
subprocess.run(
["cc", "-std=c11", "-Wall", "-Wextra", "-Werror", str(source), "-o", str(exe)],
check=True,
)
raw = subprocess.check_output([str(exe)], text=True)
alarm_raw = subprocess.check_output([str(exe), "--alarm"], text=True)
rows = [list(map(int, line.split(","))) for line in raw.splitlines()]
if len(rows) != 8192:
raise SystemExit(f"Expected 8192 ASPM policy vectors, got {len(rows)}")
code = (
"// Generated by tools/gpu_generate_aspm_oracle.py from literal original C bodies.\n"
"use super::Vector;\n"
"pub(super) static VECTORS:&[Vector]=&[\n"
+ "".join(
"Vector{flags:%d,saved_up:%d,saved_down:%d,first:%d,second:%d},\n" % tuple(row)
for row in rows
)
+ "];\n"
)
path = ROOT / "src/nvidia/src/gpu/gv100_aspm_vectors.rs"
if args.check:
_require_file_text(path, code, "ASPM policy vectors")
else:
path.write_text(code)
report = {
"source_sha256": hashlib.sha256(source.read_bytes()).hexdigest(),
"original_input_sha256": "5269a23ffba19a17fe16f076463e7ad4151254659441d1711bee6c6221ff6f4b",
"literal_functions": ["_nv012119rm", "_nv012121rm"],
"vector_count": len(rows),
"flags_range": [0, 511],
"saved_low2_each": [0, 3],
"generated_sha256": hashlib.sha256(code.encode()).hexdigest(),
"original_machine_code_executed": False,
"physical_access": False,
}
print("Original C policy oracle:", len(rows), "vectors verified")
alarm_rows = [list(map(int, line.split(","))) for line in alarm_raw.splitlines()]
if len(alarm_rows) != 1152:
raise SystemExit(f"Expected 1152 ASPM alarm vectors, got {len(alarm_rows)}")
alarm_code = (
"// Generated from literal original012120/012119/012121 C callbacks.\n"
"use super::AlarmVector;\n"
"pub(super) static VECTORS:&[AlarmVector]=&[\n"
+ "".join(
"AlarmVector{flags:%d,saved_up:%d,saved_down:%d,phase:%d,busy:%d,next_phase:%d,first:%d,second:%d,armed:%d},\n"
% tuple(row)
for row in alarm_rows
)
+ "];\n"
)
alarm_path = ROOT / "src/nvidia/src/gpu/gv100_aspm_alarm_vectors.rs"
if args.check:
_require_file_text(alarm_path, alarm_code, "ASPM alarm vectors")
else:
alarm_path.write_text(alarm_code)
report["alarm_vector_count"] = len(alarm_rows)
report["alarm_generated_sha256"] = hashlib.sha256(alarm_code.encode()).hexdigest()
report["literal_functions"].append("_nv012120rm")
report_path = ROOT / "reports/gpu-gv100-aspm-oracle.json"
if args.check:
_require_json_equal(report_path, report, "ASPM oracle report")
else:
report_path.write_text(json.dumps(report, indent=2) + "\n")
print("Original C alarm oracle:", len(alarm_rows), "vectors verified")
return 0
if __name__ == "__main__":
raise SystemExit(main())