Files
nvdriver/tools/generate_timeout_oracle.py

189 lines
6.8 KiB
Python

#!/usr/bin/env python3
"""Run unchanged exact-version public C functions against explicit test services."""
import argparse
import hashlib
import json
import os
import subprocess
import tempfile
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
REL_SOURCE = Path("src/nvidia/src/kernel/gpu/gpu_timeout.c")
def _discover_timeout_source(explicit=None) -> Path:
if explicit is not None:
p = Path(explicit).expanduser()
return (p / REL_SOURCE if p.is_dir() else p).resolve()
candidates = []
for env_var in ("NV_RS_OPEN_GPU_SRC", "OPEN_GPU_ROOT"):
val = os.environ.get(env_var)
if val:
candidates.append(Path(val).expanduser() / REL_SOURCE)
env_analysis = os.environ.get("NV_RS_ANALYSIS_ROOT")
if env_analysis:
candidates.append(
Path(env_analysis).expanduser()
/ "reference/open-gpu-kernel-modules-580.178.04"
/ REL_SOURCE
)
candidates.append(
Path.home()
/ "nvidia-driver/analysis-580.178.04/reference/open-gpu-kernel-modules-580.178.04"
/ REL_SOURCE
)
for cand in candidates:
if cand.is_file():
return cand.resolve()
return candidates[0].resolve()
HARNESS = r"""
int main(void){
OBJGPU own={0},parent={0};own.parent=&parent;parent.parent=&parent;
own.attached=parent.attached=true;own.full_power=parent.full_power=true;
own.getProperty=parent.getProperty=property;own.timer.now=parent.timer.now=1000;
TIMEOUT_DATA data={0};data.defaultus=17;data.pGpu=&own;
unsigned modes[]={0,8,16,32,128,24,40,160};
for(unsigned m=0;m<8;m++)for(unsigned extra=0;extra<32;extra++)
for(unsigned duration=0;duration<3;duration++)for(unsigned ts=0;ts<3;ts++){
unsigned requested=duration==0?0:(duration==1?1:200);
unsigned flags=modes[m]|((extra&1)?1:0)|((extra&2)?2:0)|((extra&4)?4:0)|((extra&8)?64:0)|((extra&16)?256:0);
data.defaultFlags=8;cpu_now=1000;tick_resolution=100;
thread_status=ts==0?0:(ts==1?0x40:0x65);
RMTIMEOUT timeout;timeoutSet(&data,&timeout,requested,flags);
NvU64 initial=timeout.timeout;unsigned initial_flags=timeout.flags;
unsigned selected=timeout.pTmrGpu==&parent?2:(timeout.pTmrGpu==&own?1:0);
cpu_now=2000;parent.timer.now=own.timer.now=2000;
unsigned status=timeoutCheck(&data,&timeout,0x2a3);
printf("(%u,%u,%u,%llu,%u,%u,%u,%llu,%u),\n",requested,flags,thread_status,(unsigned long long)initial,initial_flags,selected,status,(unsigned long long)timeout.timeout,timeout.flags);
parent.timer.now=own.timer.now=1000;
}
}
"""
_INVARIANT_REPORT_KEYS = (
"cases",
"source_sha256",
"header_sha256",
"functions_sha256",
"vectors_sha256",
"test_service_sha256",
"compile_flags",
"limitations",
)
def main(argv=None) -> int:
parser = argparse.ArgumentParser(
description="Generate or verify GPU timeout C-oracle vectors."
)
parser.add_argument(
"--source",
type=Path,
default=None,
help="Path to open-gpu-kernel-modules-580.178.04 root or gpu_timeout.c",
)
parser.add_argument("--check", action="store_true")
args = parser.parse_args(argv)
source = _discover_timeout_source(args.source)
if not source.is_file():
raise SystemExit(
f"Missing open-gpu-kernel-modules source file: {source} "
"(set NV_RS_OPEN_GPU_SRC, OPEN_GPU_ROOT, NV_RS_ANALYSIS_ROOT, or --source)"
)
if len(source.parents) <= 3:
raise SystemExit(
f"Cannot locate inc/kernel/gpu/gpu_timeout.h relative to {source}"
)
header = source.parents[3] / "inc/kernel/gpu/gpu_timeout.h"
if not header.is_file():
raise SystemExit(
f"Missing open-gpu-kernel-modules source file: {header} "
"(set NV_RS_OPEN_GPU_SRC, OPEN_GPU_ROOT, NV_RS_ANALYSIS_ROOT, or --source)"
)
text = source.read_text()
h = header.read_text()
functions = "void\n" + text[
text.index("timeoutSet\n") : text.index("/*!\n * @brief Wait for a condition")
]
defines = "\n".join(
line for line in h.splitlines() if line.startswith("#define GPU_TIMEOUT_")
)
types = h[h.index("typedef struct\n") : h.index("/*!\n * @brief A prototype")]
with tempfile.TemporaryDirectory(prefix="nv-rs-timeout-") as tmp:
p = Path(tmp)
c = p / "oracle.c"
binary = p / "oracle"
c.write_text(
'#include "'
+ str(ROOT / "tests/oracles/timeout-shim.h")
+ '"\n'
+ defines
+ "\n"
+ types
+ "\n"
+ functions
+ "\n"
+ HARNESS
)
subprocess.run(
["cc", "-std=c11", "-Werror", "-Wno-error=cpp", str(c), "-o", str(binary)],
check=True,
)
output = subprocess.check_output([str(binary)], text=True)
rows = output.splitlines()
destination = ROOT / "tests/oracles/timeout-vectors.rs"
generated = (
"// Unchanged exact-version public C policy, mocked service inputs.\n[\n"
+ output
+ "]\n"
)
if args.check:
if not destination.is_file() or destination.read_text() != generated:
raise SystemExit(
"Timeout C oracle vectors differ; regenerate and investigate"
)
else:
destination.write_text(generated)
report = {
"cases": len(rows),
"original_source": str(source),
"source_sha256": hashlib.sha256(source.read_bytes()).hexdigest(),
"header_sha256": hashlib.sha256(header.read_bytes()).hexdigest(),
"functions_sha256": hashlib.sha256(functions.encode()).hexdigest(),
"vectors_sha256": hashlib.sha256(generated.encode()).hexdigest(),
"test_service_sha256": hashlib.sha256(
(ROOT / "tests/oracles/timeout-shim.h").read_bytes()
).hexdigest(),
"compiler_version": subprocess.check_output(["cc", "--version"], text=True),
"compile_flags": ["-std=c11", "-Werror", "-Wno-error=cpp"],
"limitations": [
"Clock/thread services are test inputs, not original RM execution.",
"Applicable original binary paths were independently inspected through REA.",
"This oracle compares status/state, not logging or physical GPU timing.",
],
}
report_path = ROOT / "reports/gpu-timeout-oracle.json"
if args.check:
if not report_path.is_file():
raise SystemExit(f"Missing timeout oracle report: {report_path}")
existing = json.loads(report_path.read_text())
for key in _INVARIANT_REPORT_KEYS:
if existing.get(key) != report[key]:
raise SystemExit(f"Timeout oracle provenance differs for {key!r}")
else:
report_path.write_text(json.dumps(report, indent=2) + "\n")
print(json.dumps(report, indent=2))
return 0
if __name__ == "__main__":
raise SystemExit(main())