mirror of
https://github.com/QuixiAI/nvdriver.git
synced 2026-12-06 06:28:39 +00:00
183 lines
6.5 KiB
Python
183 lines
6.5 KiB
Python
#!/usr/bin/env python3
|
|
"""Compile unchanged exact installer Linux delay/schedule source with recorder primitives."""
|
|
import argparse
|
|
import hashlib
|
|
import json
|
|
import os
|
|
import subprocess
|
|
import tempfile
|
|
from pathlib import Path
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
|
|
|
|
def _discover_kernel_source(explicit=None) -> Path:
|
|
if explicit is not None:
|
|
return Path(explicit).expanduser().resolve()
|
|
candidates = []
|
|
env_kernel = os.environ.get("NV_RS_KERNEL_SRC")
|
|
if env_kernel:
|
|
candidates.append(Path(env_kernel).expanduser())
|
|
env_analysis = os.environ.get("NV_RS_ANALYSIS_ROOT")
|
|
if env_analysis:
|
|
candidates.append(Path(env_analysis).expanduser() / "extracted/kernel")
|
|
candidates.extend(
|
|
[
|
|
Path.home() / "nvidia-driver/analysis-580.178.04/extracted/kernel",
|
|
Path("/usr/src/nvidia-580.178.04"),
|
|
Path("/usr/src/nvidia-srv-580.178.04"),
|
|
]
|
|
)
|
|
for cand in candidates:
|
|
if (cand / "common/inc/nv-time.h").is_file() and (
|
|
cand / "nvidia/os-interface.c"
|
|
).is_file():
|
|
return cand.resolve()
|
|
return candidates[0].resolve()
|
|
|
|
|
|
def _extract_body(text: str, signature: str) -> str:
|
|
start = text.index(signature)
|
|
pos = text.index("{", start)
|
|
depth = 0
|
|
for end in range(pos, len(text)):
|
|
depth += (text[end] == "{") - (text[end] == "}")
|
|
if depth == 0:
|
|
return text[start : end + 1]
|
|
raise ValueError(signature)
|
|
|
|
|
|
PROLOGUE = """#include <stdint.h>
|
|
#include <stdio.h>
|
|
typedef uint32_t NV_STATUS;
|
|
#define NV_API_CALL
|
|
#define NV_OK 0
|
|
#define NV_ERR_GENERIC 65535
|
|
#define NV_ERR_ILLEGAL_ACTION 22
|
|
#define NV_MAX_ISR_DELAY_US 20000
|
|
#define NV_DBG_ERRORS 0
|
|
#define TASK_INTERRUPTIBLE 1
|
|
static unsigned context,ms_value,us_value,schedules,diagnostics;
|
|
#define nv_in_hardirq() (!!(context&1))
|
|
#define NV_MAY_SLEEP() (!(context&14))
|
|
#define mdelay(x) (ms_value=(x))
|
|
#define udelay(x) (us_value=(x))
|
|
#define set_current_state(x) ((void)(x))
|
|
#define schedule_timeout(x) ((void)(x),++schedules)
|
|
#define nv_printf(level,format) ((void)(level),(void)(format),++diagnostics)
|
|
"""
|
|
|
|
EPILOGUE = """
|
|
int main(void) {
|
|
uint32_t durations[]={0,1,999,1000,1001,19999,20000,20001,1000000,50000000,UINT32_MAX-1,UINT32_MAX};
|
|
for(context=0;context<16;context++) {
|
|
for(unsigned operation=0;operation<3;operation++) {
|
|
unsigned count=operation==1?1:sizeof(durations)/sizeof(durations[0]);
|
|
for(unsigned i=0;i<count;i++) {
|
|
unsigned duration=durations[i],status;ms_value=us_value=schedules=diagnostics=0;
|
|
if(operation==1)status=os_schedule();
|
|
else if(operation==2)status=nv_sleep_us(duration<1000?1:duration/1000);
|
|
else status=nv_sleep_us(duration);
|
|
printf("%u,%u,%u,%u,%u,%u,%u,%u\\n",operation,context,duration,status,ms_value,us_value,schedules,diagnostics);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
"""
|
|
|
|
|
|
def main(argv=None) -> int:
|
|
parser = argparse.ArgumentParser(
|
|
description="Generate or verify host-time delay/schedule C-oracle vectors."
|
|
)
|
|
parser.add_argument(
|
|
"--source",
|
|
type=Path,
|
|
default=None,
|
|
help="Path to 580.178.04 extracted/installed kernel source tree",
|
|
)
|
|
parser.add_argument("--check", action="store_true")
|
|
options = parser.parse_args(argv)
|
|
|
|
base = _discover_kernel_source(options.source)
|
|
header = base / "common/inc/nv-time.h"
|
|
source = base / "nvidia/os-interface.c"
|
|
for req in (header, source):
|
|
if not req.is_file():
|
|
raise SystemExit(
|
|
f"Missing 580.178.04 kernel source file: {req} "
|
|
"(set NV_RS_KERNEL_SRC, NV_RS_ANALYSIS_ROOT, or --source)"
|
|
)
|
|
|
|
functions = (
|
|
_extract_body(header.read_text(), "static inline NV_STATUS nv_sleep_us(")
|
|
+ "\n"
|
|
+ _extract_body(source.read_text(), "NV_STATUS NV_API_CALL os_schedule(void)")
|
|
)
|
|
|
|
with tempfile.TemporaryDirectory(prefix="nv-rs-host-time-oracle-") as tmp:
|
|
c_path = Path(tmp) / "original.c"
|
|
exe = Path(tmp) / "original"
|
|
c_path.write_text(PROLOGUE + functions + EPILOGUE)
|
|
subprocess.run(
|
|
["cc", "-std=c11", "-Wall", "-Wextra", "-Werror", str(c_path), "-o", str(exe)],
|
|
check=True,
|
|
)
|
|
rows = [
|
|
tuple(map(int, line.split(",")))
|
|
for line in subprocess.check_output([str(exe)], text=True).splitlines()
|
|
]
|
|
|
|
if len(rows) != 400:
|
|
raise SystemExit(f"Expected 400 host-time oracle vectors, got {len(rows)}")
|
|
code = (
|
|
"// Unchanged installer nv_sleep_us/os_schedule with controlled Linux primitives.\n"
|
|
"type Vector = (u8, u32, u32, u32, u32, u32, u32, u32);\n"
|
|
"#[rustfmt::skip]\n"
|
|
"const VECTORS:&[Vector]=&[\n"
|
|
+ "".join("(" + ",".join(map(str, row)) + "),\n" for row in rows)
|
|
+ "];\n"
|
|
)
|
|
out_path = ROOT / "src/nvidia/src/gpu/host_time_oracle_vectors.rs"
|
|
report_path = ROOT / "reports/host-time-oracle.json"
|
|
report = {
|
|
"passed": True,
|
|
"vectors": len(rows),
|
|
"source_sha256": {
|
|
str(p): hashlib.sha256(p.read_bytes()).hexdigest()
|
|
for p in (header, source)
|
|
},
|
|
"functions": [
|
|
"unchanged nv_sleep_us",
|
|
"unchanged os_schedule",
|
|
"RM nanosecond argument conversion modeled from _nv049597 instructions",
|
|
],
|
|
"scope": "Compiled shipped Linux source with context, busy-delay, scheduler and diagnostic recorder mocks. No actual delay/sleep or GPU execution.",
|
|
}
|
|
if options.check:
|
|
if not out_path.is_file() or out_path.read_text() != code:
|
|
raise SystemExit(f"OS service vectors changed: {out_path}")
|
|
if not report_path.is_file():
|
|
raise SystemExit(f"Missing host-time oracle report: {report_path}")
|
|
existing = json.loads(report_path.read_text())
|
|
for key in ("passed", "vectors", "functions", "scope"):
|
|
if existing.get(key) != report[key]:
|
|
raise SystemExit(f"Host-time oracle report differs for {key!r}")
|
|
existing_hashes = {
|
|
Path(k).name: v for k, v in existing.get("source_sha256", {}).items()
|
|
}
|
|
expected_hashes = {
|
|
Path(k).name: v for k, v in report["source_sha256"].items()
|
|
}
|
|
if existing_hashes != expected_hashes:
|
|
raise SystemExit("Host-time oracle report source_sha256 differs")
|
|
else:
|
|
out_path.write_text(code)
|
|
report_path.write_text(json.dumps(report, indent=2) + "\n")
|
|
print(len(rows), "original Linux OS delay/schedule vectors")
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
raise SystemExit(main())
|