mirror of
https://github.com/QuixiAI/nvdriver.git
synced 2026-12-06 06:28:39 +00:00
Merge pull request #281 from morebrackets/fix/tools-oracle-portability-and-capture-safety
tools: make UVM/TLB/time C oracles portable and harden control compare/capture
This commit is contained in:
110
tests/offline/test_oracle_portability_and_capture.py
Normal file
110
tests/offline/test_oracle_portability_and_capture.py
Normal file
@ -0,0 +1,110 @@
|
||||
"""Offline unit tests for oracle portability and capture/comparison tools."""
|
||||
from __future__ import annotations
|
||||
|
||||
import ctypes
|
||||
import importlib.util
|
||||
import os
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
from unittest import mock
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
|
||||
|
||||
def _load(rel_path: str, module_name: str):
|
||||
path = ROOT / rel_path
|
||||
spec = importlib.util.spec_from_file_location(module_name, path)
|
||||
assert spec is not None and spec.loader is not None
|
||||
mod = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(mod)
|
||||
return mod
|
||||
|
||||
|
||||
class TestOraclePortabilityAndCapture(unittest.TestCase):
|
||||
def test_uvm_ioctl_layout_resolves_env_and_rejects_bad_flag(self):
|
||||
mod = _load("tools/check_uvm_ioctl_layout.py", "check_uvm_ioctl_layout")
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
tree = Path(td)
|
||||
(tree / "nvidia-uvm").mkdir(parents=True)
|
||||
(tree / "common/inc").mkdir(parents=True)
|
||||
(tree / "nvidia-uvm/uvm.c").write_text("// stub\n")
|
||||
with mock.patch.dict(os.environ, {"NV_RS_KERNEL_SRC": str(tree)}, clear=False):
|
||||
trees = mod.resolve_source_trees()
|
||||
self.assertEqual(trees[0][0], "env")
|
||||
self.assertEqual(trees[0][1], tree)
|
||||
with self.assertRaises(SystemExit) as ctx:
|
||||
mod.main(["--unknown-flag"])
|
||||
self.assertEqual(ctx.exception.code, 2)
|
||||
|
||||
def test_tlb_and_system_time_oracles_honor_env_override(self):
|
||||
tlb = _load("tools/check_gv100_tlb_oracle.py", "check_gv100_tlb_oracle")
|
||||
systime = _load("tools/check_system_time_source.py", "check_system_time_source")
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
tree = Path(td)
|
||||
(tree / "nvidia-uvm").mkdir(parents=True)
|
||||
(tree / "nvidia").mkdir(parents=True)
|
||||
(tree / "nvidia-uvm/uvm_pascal_host.c").write_text("")
|
||||
(tree / "nvidia/os-interface.c").write_text("")
|
||||
with mock.patch.dict(os.environ, {"NV_RS_KERNEL_SRC": str(tree)}, clear=False):
|
||||
self.assertEqual(tlb.resolve_uvm_source_dir(), tree / "nvidia-uvm")
|
||||
self.assertEqual(
|
||||
systime.resolve_original_os_interface(),
|
||||
tree / "nvidia/os-interface.c",
|
||||
)
|
||||
|
||||
def test_compare_software_controls_label_normalization_is_single_pass(self):
|
||||
mod = _load("tools/compare_software_controls.py", "compare_software_controls")
|
||||
mapping = {0xC1: 0xC2, 0xC2: 0xC3}
|
||||
# Single-pass boundary-aware replacement must not chain 0xc1->0xc2->0xc3
|
||||
# and must not corrupt longer hex tokens like 0xc10.
|
||||
self.assertEqual(
|
||||
mod.normalize_label("alloc 0xc1 next 0xc2 keep 0xc10", mapping),
|
||||
"alloc 0xc2 next 0xc3 keep 0xc10",
|
||||
)
|
||||
# Unknown ioctl kind reports an issue instead of crashing with KeyError.
|
||||
rec = {
|
||||
"request": "0xc01046ff",
|
||||
"input_top": "00" * 16,
|
||||
"response": "00" * 16,
|
||||
"linux_errno": 0,
|
||||
"status": 0,
|
||||
"label": "unknown",
|
||||
}
|
||||
cases = mod.compare_records({"records": [rec]}, {"records": [rec]})
|
||||
self.assertEqual(len(cases), 1)
|
||||
self.assertFalse(cases[0]["passed"])
|
||||
self.assertTrue(any("unsupported ioctl kind" in issue for issue in cases[0]["issues"]))
|
||||
|
||||
def test_cuda_basic_binds_64bit_argtypes(self):
|
||||
mod = _load("tools/ioctl_capture/cuda_basic.py", "ioctl_capture_cuda_basic")
|
||||
|
||||
class FakeFn:
|
||||
argtypes = None
|
||||
restype = None
|
||||
|
||||
class FakeCuda:
|
||||
def __init__(self):
|
||||
for name in (
|
||||
"cuInit",
|
||||
"cuDeviceGet",
|
||||
"cuCtxCreate_v2",
|
||||
"cuMemAlloc_v2",
|
||||
"cuMemcpyHtoD_v2",
|
||||
"cuMemcpyDtoH_v2",
|
||||
"cuCtxSynchronize",
|
||||
"cuMemFree_v2",
|
||||
"cuCtxDestroy_v2",
|
||||
):
|
||||
setattr(self, name, FakeFn())
|
||||
|
||||
fake = mod._bind_cuda(FakeCuda())
|
||||
self.assertEqual(fake.cuMemAlloc_v2.argtypes[1], ctypes.c_size_t)
|
||||
self.assertEqual(fake.cuMemcpyHtoD_v2.argtypes, [ctypes.c_uint64, ctypes.c_void_p, ctypes.c_size_t])
|
||||
self.assertEqual(fake.cuMemcpyDtoH_v2.argtypes, [ctypes.c_void_p, ctypes.c_uint64, ctypes.c_size_t])
|
||||
self.assertEqual(fake.cuMemFree_v2.argtypes, [ctypes.c_uint64])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@ -1,18 +1,46 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Differential vectors from exact580 shipped Pascal host functions (GV100 HAL inheritance)."""
|
||||
import hashlib,json,subprocess,tempfile
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
R=Path(__file__).resolve().parents[1]
|
||||
S=Path('/home/geodd/nvidia-driver/analysis-580.178.04/extracted/kernel/nvidia-uvm')
|
||||
def function(text,name):
|
||||
start=text.rfind('\nvoid ',0,text.index(name+'('))+1
|
||||
pos=text.index('{',start);level=1;end=pos+1
|
||||
while level:
|
||||
level+=(text[end]=='{')-(text[end]=='}');end+=1
|
||||
return text[start:end]
|
||||
source=(S/'uvm_pascal_host.c').read_text()
|
||||
body='\n'.join(function(source,n) for n in ['uvm_hal_pascal_host_membar_sys','uvm_hal_pascal_host_membar_gpu','uvm_hal_pascal_host_tlb_invalidate_all'])
|
||||
prefix=r'''
|
||||
|
||||
R = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def resolve_uvm_source_dir():
|
||||
candidates = []
|
||||
if os.environ.get("NV_RS_KERNEL_SRC"):
|
||||
candidates.append(Path(os.environ["NV_RS_KERNEL_SRC"]) / "nvidia-uvm")
|
||||
if os.environ.get("NV_RS_ANALYSIS_ROOT"):
|
||||
candidates.append(Path(os.environ["NV_RS_ANALYSIS_ROOT"]) / "extracted/kernel/nvidia-uvm")
|
||||
candidates.extend([
|
||||
Path("/home/geodd/nvidia-driver/analysis-580.178.04/extracted/kernel/nvidia-uvm"),
|
||||
Path("/usr/src/nvidia-580.178.04/nvidia-uvm"),
|
||||
Path("/usr/src/nvidia-srv-580.178.04/nvidia-uvm"),
|
||||
])
|
||||
for candidate in candidates:
|
||||
if (candidate / "uvm_pascal_host.c").is_file():
|
||||
return candidate
|
||||
raise SystemExit(
|
||||
"Unable to locate uvm_pascal_host.c; set NV_RS_KERNEL_SRC or NV_RS_ANALYSIS_ROOT."
|
||||
)
|
||||
|
||||
|
||||
def function(text, name):
|
||||
start = text.rfind("\nvoid ", 0, text.index(name + "(")) + 1
|
||||
pos = text.index("{", start)
|
||||
level = 1
|
||||
end = pos + 1
|
||||
while level:
|
||||
level += (text[end] == "{") - (text[end] == "}")
|
||||
end += 1
|
||||
return text[start:end]
|
||||
|
||||
|
||||
PREFIX = r'''
|
||||
#include <stdint.h>
|
||||
#include <stdio.h>
|
||||
#include <assert.h>
|
||||
@ -36,21 +64,73 @@ typedef struct {uint32_t words[64];unsigned n,hshub;} uvm_push_t;
|
||||
#define NV_PUSH_4U(p,a,x,b,y,c,z,d,w) do{push->words[push->n++]=HWCONST(B06F,DMA,SEC_OP,INC_METHOD)|HWVALUE(B06F,DMA,INCR_ADDRESS,NV##p##_##a>>2)|HWVALUE(B06F,DMA,INCR_SUBCHANNEL,0)|HWVALUE(B06F,DMA,INCR_COUNT,4);push->words[push->n++]=(x);push->words[push->n++]=(y);push->words[push->n++]=(z);push->words[push->n++]=(w);}while(0)
|
||||
static void uvm_hal_tlb_invalidate_membar(uvm_push_t*,uvm_membar_t);
|
||||
'''
|
||||
|
||||
# The original helper dispatches hshub GPU barriers then the requested barrier.
|
||||
# Callback plumbing is replaced; the called encoding functions remain original C.
|
||||
tail=r'''
|
||||
TAIL = r'''
|
||||
static void uvm_hal_tlb_invalidate_membar(uvm_push_t*p,uvm_membar_t m){if(m==0)return;for(unsigned i=0;i<p->hshub;i++)uvm_hal_pascal_host_membar_gpu(p);if(m==1)uvm_hal_pascal_host_membar_gpu(p);else uvm_hal_pascal_host_membar_sys(p);}
|
||||
int main(void){uint64_t addresses[]={0,4096,0x12345000ULL,0x12345678000ULL,0x7fffffffffff000ULL};for(unsigned a=0;a<5;a++)for(unsigned ap=0;ap<2;ap++)for(unsigned d=0;d<5;d++)for(unsigned m=0;m<3;m++)for(unsigned h=0;h<3;h++){uvm_push_t p={.hshub=h};uvm_gpu_phys_address_t pdb={addresses[a],ap};uvm_hal_pascal_host_tlb_invalidate_all(&p,pdb,d,m);printf("%llu %u %u %u %u",(unsigned long long)addresses[a],ap,d,m,h);for(unsigned n=0;n<p.n;n++)printf(" %u",p.words[n]);puts("");}}
|
||||
'''
|
||||
with tempfile.TemporaryDirectory() as t:
|
||||
p=Path(t);(p/'oracle.c').write_text(prefix+body+tail)
|
||||
subprocess.run(['cc','-std=c11','-Wall','-Werror','-O2','-I',str(S),'-I',str(S.parent/'common/inc'),str(p/'oracle.c'),'-o',str(p/'oracle')],check=True)
|
||||
lines=subprocess.check_output([str(p/'oracle')],text=True).splitlines()
|
||||
rows=[list(map(int,l.split())) for l in lines]
|
||||
output=['// Generated by tools/check_gv100_tlb_oracle.py from exact shipped C host functions.',"pub type Vector = (u64, u8, u8, u8, u32, &'static [u32]);", '#[rustfmt::skip]', 'pub const VECTORS: &[Vector] = &[']
|
||||
for a,ap,d,m,h,*words in rows:output.append(f'({a},{ap},{d},{m},{h},&{words}),')
|
||||
output.append('];')
|
||||
(R/'src/nvidia/src/mmu/tlb_oracle_vectors.rs').write_text('\n'.join(output)+'\n')
|
||||
report={'passed':True,'vectors':len(rows),'execution':'Pure original C host method encoders only; no driver or GPU execution','callback_plumbing':'Original membar helper dispatch represented by finite callback shim; original GPU/SYS encoders unchanged','source_hashes':{str(S/n):hashlib.sha256((S/n).read_bytes()).hexdigest() for n in ['uvm_pascal_host.c','uvm_hal.c','uvm_push_macros.h','clc06f.h','clb06f.h']}}
|
||||
(R/'reports/gv100-tlb-oracle.json').write_text(json.dumps(report,indent=2)+'\n')
|
||||
print(len(rows),'actual C TLB method vectors')
|
||||
|
||||
|
||||
def main():
|
||||
uvm_dir = resolve_uvm_source_dir()
|
||||
source = (uvm_dir / "uvm_pascal_host.c").read_text()
|
||||
body = "\n".join(
|
||||
function(source, n)
|
||||
for n in [
|
||||
"uvm_hal_pascal_host_membar_sys",
|
||||
"uvm_hal_pascal_host_membar_gpu",
|
||||
"uvm_hal_pascal_host_tlb_invalidate_all",
|
||||
]
|
||||
)
|
||||
with tempfile.TemporaryDirectory() as t:
|
||||
p = Path(t)
|
||||
(p / "oracle.c").write_text(PREFIX + body + TAIL)
|
||||
subprocess.run(
|
||||
[
|
||||
"cc",
|
||||
"-std=c11",
|
||||
"-Wall",
|
||||
"-Werror",
|
||||
"-O2",
|
||||
"-I",
|
||||
str(uvm_dir),
|
||||
"-I",
|
||||
str(uvm_dir.parent / "common/inc"),
|
||||
str(p / "oracle.c"),
|
||||
"-o",
|
||||
str(p / "oracle"),
|
||||
],
|
||||
check=True,
|
||||
)
|
||||
lines = subprocess.check_output([str(p / "oracle")], text=True).splitlines()
|
||||
rows = [list(map(int, line.split())) for line in lines]
|
||||
output = [
|
||||
"// Generated by tools/check_gv100_tlb_oracle.py from exact shipped C host functions.",
|
||||
"pub type Vector = (u64, u8, u8, u8, u32, &'static [u32]);",
|
||||
"#[rustfmt::skip]",
|
||||
"pub const VECTORS: &[Vector] = &[",
|
||||
]
|
||||
for a, ap, d, m, h, *words in rows:
|
||||
output.append(f"({a},{ap},{d},{m},{h},&{words}),")
|
||||
output.append("];")
|
||||
(R / "src/nvidia/src/mmu/tlb_oracle_vectors.rs").write_text("\n".join(output) + "\n")
|
||||
report = {
|
||||
"passed": True,
|
||||
"vectors": len(rows),
|
||||
"execution": "Pure original C host method encoders only; no driver or GPU execution",
|
||||
"callback_plumbing": "Original membar helper dispatch represented by finite callback shim; original GPU/SYS encoders unchanged",
|
||||
"source_hashes": {
|
||||
str(uvm_dir / n): hashlib.sha256((uvm_dir / n).read_bytes()).hexdigest()
|
||||
for n in ["uvm_pascal_host.c", "uvm_hal.c", "uvm_push_macros.h", "clc06f.h", "clb06f.h"]
|
||||
},
|
||||
}
|
||||
report_path = R / "reports/gv100-tlb-oracle.json"
|
||||
report_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
report_path.write_text(json.dumps(report, indent=2) + "\n")
|
||||
print(len(rows), "actual C TLB method vectors")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
||||
@ -1,17 +1,48 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Compare unchanged shipped OS time conversion with the Linux adapter body."""
|
||||
import hashlib,json,subprocess
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
R=Path(__file__).resolve().parents[1]
|
||||
original=Path('/home/geodd/nvidia-driver/analysis-580.178.04/extracted/kernel/nvidia/os-interface.c')
|
||||
replacement=R/'kernel-open/nvidia/clock_adapter.c'
|
||||
def body(text,signature):
|
||||
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]
|
||||
|
||||
R = Path(__file__).resolve().parents[1]
|
||||
REPLACEMENT = R / "kernel-open/nvidia/clock_adapter.c"
|
||||
|
||||
|
||||
def resolve_original_os_interface():
|
||||
candidates = []
|
||||
if os.environ.get("NV_RS_KERNEL_SRC"):
|
||||
candidates.append(Path(os.environ["NV_RS_KERNEL_SRC"]) / "nvidia/os-interface.c")
|
||||
if os.environ.get("NV_RS_ANALYSIS_ROOT"):
|
||||
candidates.append(
|
||||
Path(os.environ["NV_RS_ANALYSIS_ROOT"]) / "extracted/kernel/nvidia/os-interface.c"
|
||||
)
|
||||
candidates.extend([
|
||||
Path("/home/geodd/nvidia-driver/analysis-580.178.04/extracted/kernel/nvidia/os-interface.c"),
|
||||
Path("/usr/src/nvidia-580.178.04/nvidia/os-interface.c"),
|
||||
Path("/usr/src/nvidia-srv-580.178.04/nvidia/os-interface.c"),
|
||||
])
|
||||
for candidate in candidates:
|
||||
if candidate.is_file():
|
||||
return candidate
|
||||
raise SystemExit(
|
||||
"Unable to locate nvidia/os-interface.c; set NV_RS_KERNEL_SRC or NV_RS_ANALYSIS_ROOT."
|
||||
)
|
||||
|
||||
|
||||
def body(text, signature):
|
||||
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>
|
||||
|
||||
|
||||
PROLOGUE = '''#include <stdint.h>
|
||||
#include <stdio.h>
|
||||
#include <assert.h>
|
||||
typedef uint32_t u32;
|
||||
@ -24,7 +55,8 @@ struct timespec64 { int64_t tv_sec; long tv_nsec; };
|
||||
static struct timespec64 clock_value;
|
||||
static void ktime_get_real_ts64(struct timespec64 *out) { *out=clock_value; }
|
||||
'''
|
||||
epilogue='''
|
||||
|
||||
EPILOGUE = '''
|
||||
int main(void) {
|
||||
int64_t seconds[]={0,1,-1,INT32_MAX,UINT32_MAX,INT64_C(4294967296),INT64_MAX};
|
||||
long nanoseconds[]={0,1,999,1000,999999999};
|
||||
@ -42,10 +74,42 @@ int main(void) {
|
||||
printf("%u\\n",count);
|
||||
}
|
||||
'''
|
||||
out=R/'target/system-time-source';out.mkdir(parents=True,exist_ok=True)
|
||||
c=out/'original-and-replacement.c';exe=out/'comparison'
|
||||
c.write_text(prologue+body(original.read_text(),'NV_STATUS NV_API_CALL os_get_system_time(')+'\n'+body(replacement.read_text(),'void nv_rs_clock_system_time(')+epilogue)
|
||||
subprocess.run(['cc','-std=c11','-Wall','-Wextra','-Werror',str(c),'-o',str(exe)],check=True)
|
||||
cases=int(subprocess.check_output([str(exe)],text=True));assert cases==35
|
||||
report={'passed':True,'cases':cases,'source_sha256':{str(p):hashlib.sha256(p.read_bytes()).hexdigest() for p in [original,replacement]},'scope':'Unchanged original and adapter conversion bodies compiled with the same scripted ktime_get_real_ts64. Includes negative/wrapping seconds and microsecond truncation. Does not compare simultaneous live wall-clock samples.'}
|
||||
(R/'reports/system-time-source.json').write_text(json.dumps(report,indent=2)+'\n');print(cases,'original/adapter system-time conversion cases')
|
||||
|
||||
|
||||
def main():
|
||||
original = resolve_original_os_interface()
|
||||
out = R / "target/system-time-source"
|
||||
out.mkdir(parents=True, exist_ok=True)
|
||||
c = out / "original-and-replacement.c"
|
||||
exe = out / "comparison"
|
||||
c.write_text(
|
||||
PROLOGUE
|
||||
+ body(original.read_text(), "NV_STATUS NV_API_CALL os_get_system_time(")
|
||||
+ "\n"
|
||||
+ body(REPLACEMENT.read_text(), "void nv_rs_clock_system_time(")
|
||||
+ EPILOGUE
|
||||
)
|
||||
subprocess.run(["cc", "-std=c11", "-Wall", "-Wextra", "-Werror", str(c), "-o", str(exe)], check=True)
|
||||
cases = int(subprocess.check_output([str(exe)], text=True))
|
||||
if cases != 35:
|
||||
raise SystemExit(f"expected 35 system-time comparison cases, got {cases}")
|
||||
report = {
|
||||
"passed": True,
|
||||
"cases": cases,
|
||||
"source_sha256": {
|
||||
str(p): hashlib.sha256(p.read_bytes()).hexdigest() for p in [original, REPLACEMENT]
|
||||
},
|
||||
"scope": (
|
||||
"Unchanged original and adapter conversion bodies compiled with the same scripted "
|
||||
"ktime_get_real_ts64. Includes negative/wrapping seconds and microsecond truncation. "
|
||||
"Does not compare simultaneous live wall-clock samples."
|
||||
),
|
||||
}
|
||||
report_path = R / "reports/system-time-source.json"
|
||||
report_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
report_path.write_text(json.dumps(report, indent=2) + "\n")
|
||||
print(cases, "original/adapter system-time conversion cases")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
||||
@ -10,8 +10,10 @@ Writes target/uvm/ioctl-layout.txt, which `uvm::ioctl` is tested against.
|
||||
Two source trees are compiled and must agree: the reference tree of the analysis and, when
|
||||
present, the tree the loaded module was built from (/usr/src/nvidia-srv-580.178.04).
|
||||
"""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import subprocess
|
||||
@ -22,6 +24,38 @@ ROOT = Path(__file__).resolve().parents[1]
|
||||
REFERENCE = Path("/home/geodd/nvidia-driver/analysis-580.178.04/reference/"
|
||||
"open-gpu-kernel-modules-580.178.04/kernel-open")
|
||||
INSTALLED = Path("/usr/src/nvidia-srv-580.178.04")
|
||||
INSTALLED_FALLBACK = Path("/usr/src/nvidia-580.178.04")
|
||||
|
||||
|
||||
def resolve_source_trees():
|
||||
"""Return available `(label, kernel_open_root)` source trees in priority order."""
|
||||
candidates = []
|
||||
env_kernel = os.environ.get("NV_RS_KERNEL_SRC")
|
||||
if env_kernel:
|
||||
candidates.append(("env", Path(env_kernel)))
|
||||
env_analysis = os.environ.get("NV_RS_ANALYSIS_ROOT")
|
||||
if env_analysis:
|
||||
candidates.append((
|
||||
"analysis",
|
||||
Path(env_analysis) / "reference/open-gpu-kernel-modules-580.178.04/kernel-open",
|
||||
))
|
||||
candidates.append(("analysis_extracted", Path(env_analysis) / "extracted/kernel"))
|
||||
candidates.extend([
|
||||
("reference", REFERENCE),
|
||||
("installed", INSTALLED),
|
||||
("installed", INSTALLED_FALLBACK),
|
||||
])
|
||||
found = []
|
||||
seen = set()
|
||||
for label, tree in candidates:
|
||||
if not (tree / "nvidia-uvm/uvm.c").is_file() or not (tree / "common/inc").is_dir():
|
||||
continue
|
||||
key = tree.resolve()
|
||||
if key in seen:
|
||||
continue
|
||||
seen.add(key)
|
||||
found.append((label, tree))
|
||||
return found
|
||||
FIELDS = {
|
||||
"UVM_INITIALIZE": ("flags", "rmStatus"),
|
||||
"UVM_MM_INITIALIZE": ("uvmFd", "rmStatus"),
|
||||
@ -77,7 +111,8 @@ def routes(uvm_c):
|
||||
|
||||
def layout(uvm, include):
|
||||
table = routes((uvm / "uvm.c").read_text())
|
||||
assert len(table) == 45, len(table)
|
||||
if len(table) != 45:
|
||||
raise RuntimeError(f"expected 45 UVM ioctl routes in {uvm / 'uvm.c'}, found {len(table)}")
|
||||
program = ['#include <stdio.h>', '#include <stddef.h>', '#include "uvm_linux_ioctl.h"',
|
||||
'int main(void) {']
|
||||
for name, check, heap in table:
|
||||
@ -107,19 +142,35 @@ def layout(uvm, include):
|
||||
return subprocess.run([str(binary)], check=True, capture_output=True, text=True).stdout
|
||||
|
||||
|
||||
def main():
|
||||
text = layout(REFERENCE / "nvidia-uvm", REFERENCE / "common/inc")
|
||||
trees = ["reference"]
|
||||
if INSTALLED.exists():
|
||||
assert layout(INSTALLED / "nvidia-uvm", INSTALLED / "common/inc") == text, \
|
||||
"the installed and the reference source disagree"
|
||||
trees.append("installed")
|
||||
def main(argv=None):
|
||||
parser = argparse.ArgumentParser(description="Compute /dev/nvidia-uvm ioctl struct layouts.")
|
||||
parser.add_argument("--check", action="store_true",
|
||||
help="Verify target/uvm/ioctl-layout.txt matches the computed layout.")
|
||||
args = parser.parse_args(argv)
|
||||
|
||||
source_trees = resolve_source_trees()
|
||||
if not source_trees:
|
||||
raise SystemExit(
|
||||
"Unable to locate NVIDIA 580.178.04 nvidia-uvm sources; "
|
||||
"set NV_RS_KERNEL_SRC or NV_RS_ANALYSIS_ROOT."
|
||||
)
|
||||
|
||||
first_label, first_tree = source_trees[0]
|
||||
text = layout(first_tree / "nvidia-uvm", first_tree / "common/inc")
|
||||
trees = [first_label]
|
||||
for label, tree in source_trees[1:]:
|
||||
other = layout(tree / "nvidia-uvm", tree / "common/inc")
|
||||
if other != text:
|
||||
raise SystemExit(f"the {label} ({tree}) and {first_label} ({first_tree}) sources disagree")
|
||||
trees.append(label)
|
||||
|
||||
text = ("# /dev/nvidia-uvm ioctl layouts from the public source; see "
|
||||
"tools/check_uvm_ioctl_layout.py\n" + text)
|
||||
target = ROOT / "target/uvm/ioctl-layout.txt"
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
if "--check" in sys.argv:
|
||||
assert target.read_text() == text, "layout record differs from the checked copy"
|
||||
if args.check:
|
||||
if not target.is_file() or target.read_text() != text:
|
||||
raise SystemExit("layout record differs from the checked copy")
|
||||
else:
|
||||
target.write_text(text)
|
||||
print(json.dumps(dict(record=str(target.relative_to(ROOT)), trees=trees,
|
||||
|
||||
@ -1,54 +1,180 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Actual original-vs-loaded Rust parity; normalize only opaque handles/pointers."""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import argparse,json,hashlib
|
||||
R=Path(__file__).resolve().parent.parent
|
||||
p=argparse.ArgumentParser();p.add_argument('--original',type=Path,default=R/'reports/software-controls-replay-original.json');p.add_argument('--rust',type=Path,default=R/'reports/software-controls-rust-live.json');p.add_argument('--out',type=Path,default=R/'reports/software-controls-live-comparison.json');a=p.parse_args()
|
||||
original=json.loads(a.original.read_text());rust=json.loads(a.rust.read_text());mapping={};cases=[]
|
||||
def word(b,offset):return int.from_bytes(b[offset:offset+4],'little')
|
||||
def mapped(b,offset):
|
||||
key=word(b,offset)
|
||||
if key in mapping:b[offset:offset+4]=mapping[key].to_bytes(4,'little')
|
||||
def normalize_top(data,kind):
|
||||
data=bytearray.fromhex(data)
|
||||
for offset in ({0x2b:[0,4,8],0x2a:[0,4],0x29:[0,4,8]}[kind]):mapped(data,offset)
|
||||
return data
|
||||
def normalize_payload(data,kind):
|
||||
data=bytearray.fromhex(data or '')
|
||||
if kind==0x2a and len(data)>=4:mapped(data,0)
|
||||
return data
|
||||
if len(original['records'])!=len(rust['records']):raise SystemExit('Request sequence lengths differ')
|
||||
if not original['records']:
|
||||
raise SystemExit('No records to compare')
|
||||
for i,(old,new) in enumerate(zip(original['records'],rust['records'])):
|
||||
issues=[];req=int(old['request'],16);kind=req&255
|
||||
if req!=int(new['request'],16):issues.append('request ioctl differs')
|
||||
inp=normalize_top(old['input_top'],kind);actual_input=bytearray.fromhex(new['input_top']);ptr_offset=16 if kind in [0x2a,0x2b] else None
|
||||
# Only known Python-backed non-null parameter pointers are normalized. NULL and
|
||||
# sentinel/non-backed addresses would remain exact and expose validation gaps.
|
||||
pointer_pair=None
|
||||
if ptr_offset is not None and old.get('input_payload') is not None and new.get('input_payload') is not None:
|
||||
oldptr=int.from_bytes(inp[ptr_offset:ptr_offset+8],'little');newptr=int.from_bytes(actual_input[ptr_offset:ptr_offset+8],'little')
|
||||
if oldptr and newptr:pointer_pair=(oldptr,newptr);inp[ptr_offset:ptr_offset+8]=newptr.to_bytes(8,'little')
|
||||
if inp!=actual_input:issues.append('normalized request wrapper differs')
|
||||
if normalize_payload(old.get('input_payload'),kind)!=bytearray.fromhex(new.get('input_payload') or ''):issues.append('normalized input payload differs')
|
||||
if old['linux_errno']!=new['linux_errno']:issues.append('Linux errno differs')
|
||||
if old['status']!=new['status']:issues.append('NV status differs')
|
||||
if kind==0x2b:
|
||||
expected_obj=word(bytes.fromhex(old['response']),8);actual_obj=word(bytes.fromhex(new['response']),8)
|
||||
if word(bytes.fromhex(old['input_top']),0)==0 and expected_obj and (old['status']==0 or expected_obj!=word(bytes.fromhex(old['input_top']),8)):
|
||||
if expected_obj in mapping and mapping[expected_obj]!=actual_obj:issues.append('client handle mapping changed')
|
||||
if actual_obj==0:issues.append('generated client became NULL')
|
||||
if any(k!=expected_obj and v==actual_obj for k,v in mapping.items()):issues.append('opaque client mapping collapsed distinct handles')
|
||||
mapping[expected_obj]=actual_obj
|
||||
out=normalize_top(old['response'],kind);actual_out=bytearray.fromhex(new['response'])
|
||||
if pointer_pair is not None:
|
||||
oldptr,newptr=pointer_pair
|
||||
if int.from_bytes(out[ptr_offset:ptr_offset+8],'little')==oldptr:out[ptr_offset:ptr_offset+8]=newptr.to_bytes(8,'little')
|
||||
if out!=actual_out:issues.append('normalized response wrapper differs')
|
||||
if normalize_payload(old.get('payload'),kind)!=bytearray.fromhex(new.get('payload') or ''):issues.append('normalized output payload differs')
|
||||
label=old['label']
|
||||
for before,after in mapping.items():label=label.replace(hex(before),hex(after))
|
||||
if label!=new['label']:issues.append('case identity/order differs after handle normalization')
|
||||
cases.append({'original_label':old['label'],'rust_label':new['label'],'passed':not issues,'issues':issues})
|
||||
report={'passed':all(c['passed'] for c in cases),'scope':'Actual loaded Rust software-only controls vs original responses. Not CUDA or physical GPU parity.','cases':cases,'case_count':len(cases),'source_sha256':{str(f):hashlib.sha256(f.read_bytes()).hexdigest() for f in [a.original,a.rust]},'rust_module_identity':rust.get('module_identity'),'normalization':['Generated client handles mapped consistently/injectively at root allocation responses.','Only known non-null Python-backed nested parameter pointer fields are normalized.','No NV status, Linux errno, padding, method values or output payload data are excluded.'],'limits':['Runs occur at different times; identical deterministic control inputs and normalized opaque identifiers are compared.','This finite software-client suite does not establish GPU/backend/security/concurrency parity.']};a.out.write_text(json.dumps(report,indent=2)+'\n');print(json.dumps({'passed':report['passed'],'cases':len(cases),'failures':[c for c in cases if not c['passed']]},indent=2));raise SystemExit(0 if report['passed'] else 1)
|
||||
import re
|
||||
|
||||
R = Path(__file__).resolve().parent.parent
|
||||
HANDLE_OFFSETS = {0x2b: (0, 4, 8), 0x2a: (0, 4), 0x29: (0, 4, 8)}
|
||||
|
||||
|
||||
def word(b, offset):
|
||||
return int.from_bytes(b[offset:offset + 4], "little")
|
||||
|
||||
|
||||
def _mapped(b, offset, mapping):
|
||||
if offset + 4 > len(b):
|
||||
return
|
||||
key = word(b, offset)
|
||||
if key in mapping:
|
||||
b[offset:offset + 4] = mapping[key].to_bytes(4, "little")
|
||||
|
||||
|
||||
def normalize_top(data, kind, mapping):
|
||||
buf = bytearray.fromhex(data)
|
||||
for offset in HANDLE_OFFSETS.get(kind, ()):
|
||||
_mapped(buf, offset, mapping)
|
||||
return buf
|
||||
|
||||
|
||||
def normalize_payload(data, kind, mapping):
|
||||
buf = bytearray.fromhex(data or "")
|
||||
if kind == 0x2a and len(buf) >= 4:
|
||||
_mapped(buf, 0, mapping)
|
||||
return buf
|
||||
|
||||
|
||||
def normalize_label(label, mapping):
|
||||
if not mapping:
|
||||
return label
|
||||
replacements = {hex(before): hex(after) for before, after in mapping.items()}
|
||||
pattern = re.compile(
|
||||
r"(?<![0-9a-fA-FxX])(?:"
|
||||
+ "|".join(re.escape(k) for k in sorted(replacements, key=len, reverse=True))
|
||||
+ r")(?![0-9a-fA-F])"
|
||||
)
|
||||
return pattern.sub(lambda m: replacements[m.group(0)], label)
|
||||
|
||||
|
||||
def compare_records(original, rust):
|
||||
orig_records = original.get("records")
|
||||
rust_records = rust.get("records")
|
||||
if not isinstance(orig_records, list) or not isinstance(rust_records, list):
|
||||
raise SystemExit("Both comparison files must contain a 'records' list")
|
||||
if len(orig_records) != len(rust_records):
|
||||
raise SystemExit("Request sequence lengths differ")
|
||||
if not orig_records:
|
||||
raise SystemExit("No records to compare")
|
||||
|
||||
mapping = {}
|
||||
cases = []
|
||||
for old, new in zip(orig_records, rust_records):
|
||||
issues = []
|
||||
req = int(old["request"], 16)
|
||||
kind = req & 255
|
||||
if kind not in HANDLE_OFFSETS:
|
||||
issues.append(f"unsupported ioctl kind 0x{kind:02x}")
|
||||
if req != int(new["request"], 16):
|
||||
issues.append("request ioctl differs")
|
||||
inp = normalize_top(old["input_top"], kind, mapping)
|
||||
actual_input = bytearray.fromhex(new["input_top"])
|
||||
ptr_offset = 16 if kind in (0x2a, 0x2b) else None
|
||||
# Only known Python-backed non-null parameter pointers are normalized. NULL and
|
||||
# sentinel/non-backed addresses would remain exact and expose validation gaps.
|
||||
pointer_pair = None
|
||||
if (
|
||||
ptr_offset is not None
|
||||
and ptr_offset + 8 <= len(inp)
|
||||
and ptr_offset + 8 <= len(actual_input)
|
||||
and old.get("input_payload") is not None
|
||||
and new.get("input_payload") is not None
|
||||
):
|
||||
oldptr = int.from_bytes(inp[ptr_offset:ptr_offset + 8], "little")
|
||||
newptr = int.from_bytes(actual_input[ptr_offset:ptr_offset + 8], "little")
|
||||
if oldptr and newptr:
|
||||
pointer_pair = (oldptr, newptr)
|
||||
inp[ptr_offset:ptr_offset + 8] = newptr.to_bytes(8, "little")
|
||||
if inp != actual_input:
|
||||
issues.append("normalized request wrapper differs")
|
||||
if normalize_payload(old.get("input_payload"), kind, mapping) != bytearray.fromhex(
|
||||
new.get("input_payload") or ""
|
||||
):
|
||||
issues.append("normalized input payload differs")
|
||||
if old["linux_errno"] != new["linux_errno"]:
|
||||
issues.append("Linux errno differs")
|
||||
if old["status"] != new["status"]:
|
||||
issues.append("NV status differs")
|
||||
if kind == 0x2b:
|
||||
old_resp = bytes.fromhex(old["response"])
|
||||
new_resp = bytes.fromhex(new["response"])
|
||||
old_in = bytes.fromhex(old["input_top"])
|
||||
expected_obj = word(old_resp, 8)
|
||||
actual_obj = word(new_resp, 8)
|
||||
if (
|
||||
word(old_in, 0) == 0
|
||||
and expected_obj
|
||||
and (old["status"] == 0 or expected_obj != word(old_in, 8))
|
||||
):
|
||||
if expected_obj in mapping and mapping[expected_obj] != actual_obj:
|
||||
issues.append("client handle mapping changed")
|
||||
if actual_obj == 0:
|
||||
issues.append("generated client became NULL")
|
||||
if any(k != expected_obj and v == actual_obj for k, v in mapping.items()):
|
||||
issues.append("opaque client mapping collapsed distinct handles")
|
||||
mapping[expected_obj] = actual_obj
|
||||
out = normalize_top(old["response"], kind, mapping)
|
||||
actual_out = bytearray.fromhex(new["response"])
|
||||
if pointer_pair is not None and ptr_offset + 8 <= len(out):
|
||||
oldptr, newptr = pointer_pair
|
||||
if int.from_bytes(out[ptr_offset:ptr_offset + 8], "little") == oldptr:
|
||||
out[ptr_offset:ptr_offset + 8] = newptr.to_bytes(8, "little")
|
||||
if out != actual_out:
|
||||
issues.append("normalized response wrapper differs")
|
||||
if normalize_payload(old.get("payload"), kind, mapping) != bytearray.fromhex(
|
||||
new.get("payload") or ""
|
||||
):
|
||||
issues.append("normalized output payload differs")
|
||||
label = normalize_label(old["label"], mapping)
|
||||
if label != new["label"]:
|
||||
issues.append("case identity/order differs after handle normalization")
|
||||
cases.append({
|
||||
"original_label": old["label"],
|
||||
"rust_label": new["label"],
|
||||
"passed": not issues,
|
||||
"issues": issues,
|
||||
})
|
||||
return cases
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
p = argparse.ArgumentParser()
|
||||
p.add_argument("--original", type=Path, default=R / "reports/software-controls-replay-original.json")
|
||||
p.add_argument("--rust", type=Path, default=R / "reports/software-controls-rust-live.json")
|
||||
p.add_argument("--out", type=Path, default=R / "reports/software-controls-live-comparison.json")
|
||||
a = p.parse_args(argv)
|
||||
original = json.loads(a.original.read_text())
|
||||
rust = json.loads(a.rust.read_text())
|
||||
cases = compare_records(original, rust)
|
||||
report = {
|
||||
"passed": all(c["passed"] for c in cases),
|
||||
"scope": "Actual loaded Rust software-only controls vs original responses. Not CUDA or physical GPU parity.",
|
||||
"cases": cases,
|
||||
"case_count": len(cases),
|
||||
"source_sha256": {
|
||||
str(f): hashlib.sha256(f.read_bytes()).hexdigest() for f in (a.original, a.rust)
|
||||
},
|
||||
"rust_module_identity": rust.get("module_identity"),
|
||||
"normalization": [
|
||||
"Generated client handles mapped consistently/injectively at root allocation responses.",
|
||||
"Only known non-null Python-backed nested parameter pointer fields are normalized.",
|
||||
"No NV status, Linux errno, padding, method values or output payload data are excluded.",
|
||||
],
|
||||
"limits": [
|
||||
"Runs occur at different times; identical deterministic control inputs and normalized opaque identifiers are compared.",
|
||||
"This finite software-client suite does not establish GPU/backend/security/concurrency parity.",
|
||||
],
|
||||
}
|
||||
a.out.parent.mkdir(parents=True, exist_ok=True)
|
||||
a.out.write_text(json.dumps(report, indent=2) + "\n")
|
||||
print(json.dumps({
|
||||
"passed": report["passed"],
|
||||
"cases": len(cases),
|
||||
"failures": [c for c in cases if not c["passed"]],
|
||||
}, indent=2))
|
||||
raise SystemExit(0 if report["passed"] else 1)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
||||
@ -6,7 +6,24 @@ Run under tools/ioctl_capture/capture_stock.sh so the ioctl sequence is recorded
|
||||
import ctypes
|
||||
import sys
|
||||
|
||||
cuda = ctypes.CDLL("libcuda.so.1")
|
||||
|
||||
def _bind_cuda(cuda):
|
||||
signatures = {
|
||||
"cuInit": ([ctypes.c_uint], ctypes.c_int),
|
||||
"cuDeviceGet": ([ctypes.POINTER(ctypes.c_int), ctypes.c_int], ctypes.c_int),
|
||||
"cuCtxCreate_v2": ([ctypes.POINTER(ctypes.c_void_p), ctypes.c_uint, ctypes.c_int], ctypes.c_int),
|
||||
"cuMemAlloc_v2": ([ctypes.POINTER(ctypes.c_uint64), ctypes.c_size_t], ctypes.c_int),
|
||||
"cuMemcpyHtoD_v2": ([ctypes.c_uint64, ctypes.c_void_p, ctypes.c_size_t], ctypes.c_int),
|
||||
"cuMemcpyDtoH_v2": ([ctypes.c_void_p, ctypes.c_uint64, ctypes.c_size_t], ctypes.c_int),
|
||||
"cuCtxSynchronize": ([], ctypes.c_int),
|
||||
"cuMemFree_v2": ([ctypes.c_uint64], ctypes.c_int),
|
||||
"cuCtxDestroy_v2": ([ctypes.c_void_p], ctypes.c_int),
|
||||
}
|
||||
for name, (argtypes, restype) in signatures.items():
|
||||
fn = getattr(cuda, name)
|
||||
fn.argtypes = argtypes
|
||||
fn.restype = restype
|
||||
return cuda
|
||||
|
||||
|
||||
def ok(name, rc):
|
||||
@ -15,18 +32,33 @@ def ok(name, rc):
|
||||
sys.exit(f"{name} failed with {rc}")
|
||||
|
||||
|
||||
ok("cuInit", cuda.cuInit(0))
|
||||
dev = ctypes.c_int()
|
||||
ok("cuDeviceGet", cuda.cuDeviceGet(ctypes.byref(dev), 0))
|
||||
ctx = ctypes.c_void_p()
|
||||
ok("cuCtxCreate_v2", cuda.cuCtxCreate_v2(ctypes.byref(ctx), 0, dev))
|
||||
ptr = ctypes.c_uint64()
|
||||
ok("cuMemAlloc_v2", cuda.cuMemAlloc_v2(ctypes.byref(ptr), 1 << 20))
|
||||
src = (ctypes.c_ubyte * 4096)(*[i & 0xFF for i in range(4096)])
|
||||
dst = (ctypes.c_ubyte * 4096)()
|
||||
ok("cuMemcpyHtoD_v2", cuda.cuMemcpyHtoD_v2(ptr, src, 4096))
|
||||
ok("cuMemcpyDtoH_v2", cuda.cuMemcpyDtoH_v2(dst, ptr, 4096))
|
||||
ok("cuCtxSynchronize", cuda.cuCtxSynchronize())
|
||||
print("roundtrip_match", bytes(src) == bytes(dst), flush=True)
|
||||
ok("cuMemFree_v2", cuda.cuMemFree_v2(ptr))
|
||||
ok("cuCtxDestroy_v2", cuda.cuCtxDestroy_v2(ctx))
|
||||
def main():
|
||||
cuda = _bind_cuda(ctypes.CDLL("libcuda.so.1"))
|
||||
ok("cuInit", cuda.cuInit(0))
|
||||
dev = ctypes.c_int()
|
||||
ok("cuDeviceGet", cuda.cuDeviceGet(ctypes.byref(dev), 0))
|
||||
ctx = ctypes.c_void_p()
|
||||
ok("cuCtxCreate_v2", cuda.cuCtxCreate_v2(ctypes.byref(ctx), 0, dev.value))
|
||||
ptr = ctypes.c_uint64()
|
||||
try:
|
||||
try:
|
||||
ok("cuMemAlloc_v2", cuda.cuMemAlloc_v2(ctypes.byref(ptr), 1 << 20))
|
||||
src = (ctypes.c_ubyte * 4096)(*[i & 0xFF for i in range(4096)])
|
||||
dst = (ctypes.c_ubyte * 4096)()
|
||||
ok("cuMemcpyHtoD_v2", cuda.cuMemcpyHtoD_v2(ptr.value, src, 4096))
|
||||
ok("cuMemcpyDtoH_v2", cuda.cuMemcpyDtoH_v2(dst, ptr.value, 4096))
|
||||
ok("cuCtxSynchronize", cuda.cuCtxSynchronize())
|
||||
matched = bytes(src) == bytes(dst)
|
||||
print("roundtrip_match", matched, flush=True)
|
||||
if not matched:
|
||||
sys.exit("roundtrip mismatch between H2D and D2H buffers")
|
||||
finally:
|
||||
if ptr.value:
|
||||
ok("cuMemFree_v2", cuda.cuMemFree_v2(ptr.value))
|
||||
finally:
|
||||
if ctx.value:
|
||||
ok("cuCtxDestroy_v2", cuda.cuCtxDestroy_v2(ctx))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
||||
Reference in New Issue
Block a user