Files
nvdriver/tools/generate_thread_timeout_oracle.py

203 lines
8.1 KiB
Python

#!/usr/bin/env python3
"""Run unchanged exact-version public thread timeout policy against mocked 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/core/thread_state.c")
def _discover_thread_state_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()
def _extract_function(text: str, name: str, prefix: str) -> str:
# Use function definitions rather than earlier explanatory comments/calls.
start = text.index(prefix + name)
brace = text.index("{", start)
depth = 1
i = brace + 1
while depth:
depth += (text[i] == "{") - (text[i] == "}")
i += 1
return text[start:i] + "\n"
HARNESS = r"""
int main(void){
threadStateDatabase.timeout.nonComputeTimeoutMsecs=1;
threadStateDatabase.timeout.computeTimeoutMsecs=2;
unsigned modes[]={0,8,16,24},nf[]={0,1,2,4,8,128,129};
NvU64 overrides[]={0,1,90000,UINT64_MAX},entries[]={0,99};
for(unsigned m=0;m<4;m++)for(unsigned f=0;f<7;f++)for(unsigned o=0;o<4;o++)for(unsigned e=0;e<2;e++){
THREAD_STATE_NODE n={0};n.flags=nf[f];n.timeout.enterTime=entries[e];n.timeout.overrideTimeoutMsecs=overrides[o];
threadStateDatabase.timeout.flags=modes[m];cpu_now=1000;
unsigned status=_threadNodeInitTime(&n);
printf("I %u,%u,%llu,%llu,%u,%llu,%llu,%llu,%llu\n",modes[m],nf[f],(unsigned long long)overrides[o],(unsigned long long)entries[e],status,(unsigned long long)n.timeout.enterTime,(unsigned long long)n.timeout.nonComputeTime,(unsigned long long)n.timeout.computeTime,(unsigned long long)n.timeout.nextCpuYieldTime);
}
unsigned setups[]={3,67,19},rem[]={0,100,10000000};
OBJGPU g={0};g.gpuInstance=0;
for(unsigned m=0;m<4;m++)for(unsigned s=0;s<3;s++)for(unsigned r=0;r<3;r++)for(unsigned mask=0;mask<2;mask++)for(unsigned attached=0;attached<2;attached++)for(unsigned present=0;present<2;present++){
THREAD_STATE_NODE n={0};n.flags=32;n.timeout.enterTime=1000;n.timeout.nonComputeTime=n.timeout.computeTime=rem[r];current_node=&n;
threadStateDatabase.timeout.flags=modes[m];threadStateDatabase.timeout.computeGpuMask=mask;threadStateDatabase.setupFlags=setups[s];
cpu_now=5000000;g.attached=attached;g.reset=false;NvU64 elapsed=0;
unsigned status=_threadNodeCheckTimeout(present?&g:NULL,&n,&elapsed);
printf("C %u,%u,%u,%u,%u,%u,%u,%llu,%u,%llu,%llu,%llu,%llu\n",modes[m],setups[s],rem[r],mask,attached,present,status,(unsigned long long)elapsed,n.flags,(unsigned long long)n.timeout.enterTime,(unsigned long long)n.timeout.nonComputeTime,(unsigned long long)n.timeout.computeTime,(unsigned long long)n.timeout.nextCpuYieldTime);
}
}
"""
_INVARIANT_REPORT_KEYS = (
"cases",
"source_sha256",
"extracted_functions_sha256",
"vectors_sha256",
"test_service_sha256",
"compile_flags",
"limitations",
)
def main(argv=None) -> int:
parser = argparse.ArgumentParser(
description="Generate or verify thread timeout C-oracle vectors."
)
parser.add_argument(
"--source",
type=Path,
default=None,
help="Path to open-gpu-kernel-modules-580.178.04 root or thread_state.c",
)
parser.add_argument("--check", action="store_true")
args = parser.parse_args(argv)
source = _discover_thread_state_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()
functions = "".join(
[
_extract_function(text, "_threadStateSetNextCpuYieldTime", "static void "),
_extract_function(text, "_threadNodeInitTime", "static NV_STATUS "),
_extract_function(text, "_getTimeoutDataFromGpuMode", "static void "),
_extract_function(text, "_threadNodeCheckTimeout", "static NV_STATUS "),
_extract_function(text, "threadStateResetTimeout", "NV_STATUS "),
]
)
defines = "\n".join(
line
for line in header.read_text().splitlines()
if line.startswith("#define GPU_TIMEOUT_")
)
with tempfile.TemporaryDirectory(prefix="nv-rs-thread-oracle-") as temp:
c = Path(temp) / "oracle.c"
binary = Path(temp) / "oracle"
c.write_text(
'#include "'
+ str(ROOT / "tests/oracles/thread-timeout-shim.h")
+ '"\n'
+ defines
+ "\n"
+ functions
+ "\n"
+ HARNESS
)
subprocess.run(
["cc", "-std=c11", "-Werror", str(c), "-o", str(binary)], check=True
)
rows = subprocess.check_output([str(binary)], text=True).splitlines()
generated = "// Unchanged original-public thread policy; service calls are mocked.\n"
for kind, name, width in (("I", "INIT", 9), ("C", "CHECK", 13)):
generated += (
f"pub const {name}: &[[u64; {width}]] = &[\n"
+ "".join("[" + r[2:] + "],\n" for r in rows if r.startswith(kind))
+ "];\n"
)
out = ROOT / "tests/oracles/thread-timeout-vectors.rs"
report_path = ROOT / "reports/gpu-thread-timeout-oracle.json"
report = {
"cases": len(rows),
"source": str(source),
"source_sha256": hashlib.sha256(source.read_bytes()).hexdigest(),
"extracted_functions_sha256": hashlib.sha256(functions.encode()).hexdigest(),
"vectors_sha256": hashlib.sha256(generated.encode()).hexdigest(),
"test_service_sha256": {
f: hashlib.sha256((ROOT / f).read_bytes()).hexdigest()
for f in (
"tests/oracles/thread-timeout-shim.h",
"tests/oracles/timeout-shim.h",
)
},
"compiler_version": subprocess.check_output(["cc", "--version"], text=True),
"compile_flags": ["-std=c11", "-Werror"],
"limitations": [
"Unchanged matching public policy functions with mocked clock/current-node/logging services.",
"No original RM code or physical GPU is executed.",
"Independent REA checks corroborate the proprietary node policy.",
],
}
if args.check:
if not out.is_file() or out.read_text() != generated:
raise SystemExit("Thread timeout oracle vectors differ")
if not report_path.is_file():
raise SystemExit(f"Missing thread 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"Thread timeout oracle provenance differs for {key!r}"
)
else:
out.write_text(generated)
report_path.write_text(json.dumps(report, indent=2) + "\n")
print(json.dumps(report, indent=2))
return 0
if __name__ == "__main__":
raise SystemExit(main())