mirror of
https://github.com/QuixiAI/nvdriver.git
synced 2026-12-06 06:28:39 +00:00
tools: harden PT decoder, UVM 620 export check, and MMU/compat/alarm oracle checks
- tools/decode_original_pt_bounded.py: validate --max-lines/--max-errors >= 1, guard perf child teardown in try/finally, report missing perf cleanly, propagate non-zero perf exit codes when not stopped by a limit, and wrap in main(). - tools/check_uvm_620_exports.py: fail cleanly on missing module files or empty undefined nvUvmInterface* symbol set (preventing false green on stripped/wrong binaries), parse CLI via argparse, and wrap in main(). - tools/check_mmu_oracle.py and tools/timer-alarm-vectors.py: replace -O-elidable assert checks with explicit SystemExit errors and wrap in main(). - tools/check_compat_layout.py: resolve NVIDIA 580.178.04 include dirs via NV_RS_ANALYSIS_ROOT / NV_RS_KERNEL_SRC / OPEN_GPU_ROOT / /usr/src/nvidia-580.178.04 instead of hardcoding /home/geodd, replace -O-elidable asserts, and wrap in main(). - tools/check_original_live_init.py: close timestamped-record-dump.txt with a context manager and wrap in main(). - tests/offline/test_oracle_check_and_pt_decoder_tools.py: offline unit tests verified under python3 -O.
This commit is contained in:
83
tests/offline/test_oracle_check_and_pt_decoder_tools.py
Normal file
83
tests/offline/test_oracle_check_and_pt_decoder_tools.py
Normal file
@ -0,0 +1,83 @@
|
||||
"""Offline tests for PT bounded decoder, UVM 620 export check, MMU/compat oracles, and alarm vectors."""
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib.util
|
||||
import os
|
||||
from pathlib import Path
|
||||
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 TestOracleCheckAndPtDecoderTools(unittest.TestCase):
|
||||
def test_decode_original_pt_bounded_rejects_non_positive_limits(self):
|
||||
mod = _load("tools/decode_original_pt_bounded.py", "decode_original_pt_bounded")
|
||||
parser = mod.build_parser()
|
||||
for bad in ("0", "-5"):
|
||||
with self.assertRaises(SystemExit) as ctx:
|
||||
parser.parse_args(["--input", "a", "--kallsyms", "b", "--output", "c", "--max-lines", bad])
|
||||
self.assertEqual(ctx.exception.code, 2)
|
||||
with self.assertRaises(SystemExit) as ctx:
|
||||
parser.parse_args(["--input", "a", "--kallsyms", "b", "--output", "c", "--max-errors", bad])
|
||||
self.assertEqual(ctx.exception.code, 2)
|
||||
|
||||
def test_check_uvm_620_exports_rejects_empty_needed_set(self):
|
||||
mod = _load("tools/check_uvm_620_exports.py", "check_uvm_620_exports")
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
stock = Path(td) / "stock.ko"
|
||||
bridge = Path(td) / "bridge.ko"
|
||||
stock.write_bytes(b"")
|
||||
bridge.write_bytes(b"")
|
||||
with mock.patch.object(mod.subprocess, "check_output", return_value="00000000 T unrelated\n"):
|
||||
with self.assertRaises(SystemExit) as ctx:
|
||||
mod.main([str(stock), str(bridge)])
|
||||
self.assertIn("no undefined nvUvmInterface* symbols", str(ctx.exception))
|
||||
|
||||
def test_check_compat_layout_resolves_env_overrides(self):
|
||||
mod = _load("tools/check_compat_layout.py", "check_compat_layout")
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
ksrc = Path(td) / "kernel"
|
||||
ogpu = Path(td) / "open-gpu"
|
||||
(ksrc / "common/inc").mkdir(parents=True)
|
||||
(ogpu / "src/common/sdk/nvidia/inc").mkdir(parents=True)
|
||||
(ksrc / "common/inc/nv-ioctl.h").write_text("")
|
||||
(ksrc / "common/inc/nvtypes.h").write_text("")
|
||||
(ogpu / "src/common/sdk/nvidia/inc/nvos.h").write_text("")
|
||||
with mock.patch.dict(
|
||||
os.environ,
|
||||
{"NV_RS_KERNEL_SRC": str(ksrc), "OPEN_GPU_ROOT": str(ogpu)},
|
||||
clear=False,
|
||||
):
|
||||
incs = mod.resolve_include_dirs()
|
||||
self.assertEqual(incs, [ksrc / "common/inc", ogpu / "src/common/sdk/nvidia/inc"])
|
||||
|
||||
def test_check_mmu_oracle_rejects_corrupt_provenance_even_under_O(self):
|
||||
mod = _load("tools/check_mmu_oracle.py", "check_mmu_oracle")
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
d = Path(td)
|
||||
(d / "sample.c").write_text("hello")
|
||||
(d / "provenance.json").write_text('[{"copy": "sample.c", "sha256": "00"}]')
|
||||
with self.assertRaises(SystemExit) as ctx:
|
||||
mod.verify_provenance(d)
|
||||
self.assertIn("provenance SHA-256 mismatch", str(ctx.exception))
|
||||
|
||||
def test_timer_alarm_vectors_and_live_init_import_cleanly(self):
|
||||
vectors = _load("tools/timer-alarm-vectors.py", "timer_alarm_vectors")
|
||||
live_init = _load("tools/check_original_live_init.py", "check_original_live_init")
|
||||
self.assertTrue(callable(vectors.main))
|
||||
self.assertTrue(callable(live_init.main))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@ -1,16 +1,79 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Compile-only i386/x86_64 exact-header wire layout check."""
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import json,hashlib,subprocess,tempfile,struct
|
||||
R=Path(__file__).resolve().parent.parent
|
||||
P=Path('/home/geodd/nvidia-driver/analysis-580.178.04')
|
||||
incs=[P/'extracted/kernel/common/inc',P/'reference/open-gpu-kernel-modules-580.178.04/src/common/sdk/nvidia/inc']
|
||||
results={}
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
for bits in [32,64]:
|
||||
obj=Path(d)/f'layout{bits}.o';raw=Path(d)/f'layout{bits}.bin'
|
||||
subprocess.run(['cc',f'-m{bits}','-std=c11','-Wall','-Werror','-ffreestanding','-fno-pic','-c',*[f'-I{i}' for i in incs],str(R/'tests/oracles/compat-layout.c'),'-o',str(obj)],check=True)
|
||||
subprocess.run(['objcopy','--dump-section',f'.rodata={raw}',str(obj)],check=True)
|
||||
data=raw.read_bytes();results[str(bits)]=list(struct.unpack('<'+'I'*(len(data)//4),data))
|
||||
assert results['32'][0]==4 and results['64'][0]==8
|
||||
assert results['32'][1:]==results['64'][1:]
|
||||
report={'passed':True,'scope':'Compile-only i386/x86_64 exact-header layout proof; not a 32-bit process runtime test.','layouts':results,'all_wire_sizes_offsets_alignment_equal':True,'files':{str(p):hashlib.sha256(p.read_bytes()).hexdigest() for p in [R/'tests/oracles/compat-layout.c',incs[0]/'nv-ioctl.h',incs[0]/'nvtypes.h',incs[1]/'nvos.h']}}
|
||||
(R/'reports/compat-layout-validation.json').write_text(json.dumps(report,indent=2)+'\n');print('i386 and x86_64 layouts match except pointer width')
|
||||
import struct
|
||||
import subprocess
|
||||
import tempfile
|
||||
|
||||
R = Path(__file__).resolve().parent.parent
|
||||
DEFAULT_ANALYSIS = Path("/home/geodd/nvidia-driver/analysis-580.178.04")
|
||||
|
||||
|
||||
def resolve_include_dirs():
|
||||
analysis = Path(os.environ.get("NV_RS_ANALYSIS_ROOT") or DEFAULT_ANALYSIS)
|
||||
common_candidates = []
|
||||
if os.environ.get("NV_RS_KERNEL_SRC"):
|
||||
common_candidates.append(Path(os.environ["NV_RS_KERNEL_SRC"]) / "common/inc")
|
||||
common_candidates.extend([
|
||||
analysis / "extracted/kernel/common/inc",
|
||||
Path("/usr/src/nvidia-580.178.04/common/inc"),
|
||||
Path("/usr/src/nvidia-srv-580.178.04/common/inc"),
|
||||
])
|
||||
sdk_candidates = []
|
||||
if os.environ.get("OPEN_GPU_ROOT"):
|
||||
sdk_candidates.append(Path(os.environ["OPEN_GPU_ROOT"]) / "src/common/sdk/nvidia/inc")
|
||||
sdk_candidates.append(analysis / "reference/open-gpu-kernel-modules-580.178.04/src/common/sdk/nvidia/inc")
|
||||
|
||||
common_inc = next((p for p in common_candidates if (p / "nv-ioctl.h").is_file() and (p / "nvtypes.h").is_file()), None)
|
||||
sdk_inc = next((p for p in sdk_candidates if (p / "nvos.h").is_file()), None)
|
||||
if common_inc is None or sdk_inc is None:
|
||||
raise SystemExit(
|
||||
"Unable to locate NVIDIA 580.178.04 headers (nv-ioctl.h, nvtypes.h, nvos.h); "
|
||||
"set NV_RS_ANALYSIS_ROOT or NV_RS_KERNEL_SRC + OPEN_GPU_ROOT."
|
||||
)
|
||||
return [common_inc, sdk_inc]
|
||||
|
||||
|
||||
def main():
|
||||
incs = resolve_include_dirs()
|
||||
results = {}
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
for bits in (32, 64):
|
||||
obj = Path(d) / f"layout{bits}.o"
|
||||
raw = Path(d) / f"layout{bits}.bin"
|
||||
subprocess.run(
|
||||
[
|
||||
"cc", f"-m{bits}", "-std=c11", "-Wall", "-Werror", "-ffreestanding", "-fno-pic",
|
||||
"-c", *[f"-I{i}" for i in incs], str(R / "tests/oracles/compat-layout.c"),
|
||||
"-o", str(obj),
|
||||
],
|
||||
check=True,
|
||||
)
|
||||
subprocess.run(["objcopy", "--dump-section", f".rodata={raw}", str(obj)], check=True)
|
||||
data = raw.read_bytes()
|
||||
results[str(bits)] = list(struct.unpack("<" + "I" * (len(data) // 4), data))
|
||||
if not (results["32"] and results["64"] and results["32"][0] == 4 and results["64"][0] == 8):
|
||||
raise SystemExit(f"unexpected pointer widths: 32-bit={results['32'][:1]}, 64-bit={results['64'][:1]}")
|
||||
if results["32"][1:] != results["64"][1:]:
|
||||
raise SystemExit("i386 and x86_64 wire layouts differ beyond pointer width")
|
||||
report = {
|
||||
"passed": True,
|
||||
"scope": "Compile-only i386/x86_64 exact-header layout proof; not a 32-bit process runtime test.",
|
||||
"layouts": results,
|
||||
"all_wire_sizes_offsets_alignment_equal": True,
|
||||
"files": {
|
||||
str(p): hashlib.sha256(p.read_bytes()).hexdigest()
|
||||
for p in [R / "tests/oracles/compat-layout.c", incs[0] / "nv-ioctl.h", incs[0] / "nvtypes.h", incs[1] / "nvos.h"]
|
||||
},
|
||||
}
|
||||
report_path = R / "reports/compat-layout-validation.json"
|
||||
report_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
report_path.write_text(json.dumps(report, indent=2) + "\n")
|
||||
print("i386 and x86_64 layouts match except pointer width")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
||||
@ -1,15 +1,36 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Compile the actual shipped C encoders against shipped hwref headers; emit differential vectors."""
|
||||
import hashlib,json,subprocess,tempfile
|
||||
import hashlib
|
||||
import json
|
||||
import subprocess
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
R=Path(__file__).resolve().parents[1];D=R/'abi/mmu';vectors=[]
|
||||
for rec in json.loads((D/'provenance.json').read_text()):assert hashlib.sha256((D/rec['copy']).read_bytes()).hexdigest()==rec['sha256']
|
||||
def function(text,name):
|
||||
start=text.rfind('static ',0,text.index(name+'('));pos=text.index('{',start);level=1;end=pos+1
|
||||
while level:
|
||||
level+= (text[end]=='{')-(text[end]=='}');end+=1
|
||||
return text[start:end]
|
||||
prefix=r'''
|
||||
|
||||
R = Path(__file__).resolve().parents[1]
|
||||
D = R / "abi/mmu"
|
||||
|
||||
|
||||
def verify_provenance(mmu_dir=D):
|
||||
for rec in json.loads((mmu_dir / "provenance.json").read_text()):
|
||||
actual = hashlib.sha256((mmu_dir / rec["copy"]).read_bytes()).hexdigest()
|
||||
if actual != rec["sha256"]:
|
||||
raise SystemExit(
|
||||
f"provenance SHA-256 mismatch for {rec['copy']}: {actual} != {rec['sha256']}"
|
||||
)
|
||||
|
||||
|
||||
def function(text, name):
|
||||
start = text.rfind("static ", 0, text.index(name + "("))
|
||||
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 <stdbool.h>
|
||||
@ -42,27 +63,106 @@ typedef uint64_t NvU64;typedef uint8_t NvU8;typedef int uvm_aperture_t;typedef i
|
||||
#define HWVALUE64(p,t,f,v) (((uint64_t)(v)&HWMASK64(p,t,f))<<((0?FIELD(p,t,f))%64))
|
||||
#define HWCONST64(p,t,f,c) HWVALUE64(p,t,f,NV##p##_##t##_##f##_##c)
|
||||
'''
|
||||
for idx,arch in enumerate(['maxwell','pascal','volta','turing','hopper']):
|
||||
source=(D/f'{arch}_mmu.c').read_text();body=function(source,'make_pte_'+arch)
|
||||
unmapped_arch='pascal' if arch in ['volta','turing'] else arch
|
||||
unmapped_source=(D/f'{unmapped_arch}_mmu.c').read_text();body+='\n'+function(unmapped_source,'unmapped_pte_'+unmapped_arch)
|
||||
if arch=='hopper':body='\n'.join(l for l in source.splitlines() if l.startswith('#define NV_MMU_VER3_PTE_ADDRESS_'))+'\n'+function(source,'pte_pcf')+'\n'+body
|
||||
main='''int main(void){uint64_t addrs[]={0,0x12345000ULL,0x1bad000000ULL,0x400000000000ULL};for(int a=0;a<%d;a++)for(int p=1;p<=3;p++)for(int flags=0;flags<%d;flags++)for(int n=0;n<3;n++)printf("%%d %%d %%d %%llu %%llu\\n",a,p,flags,(unsigned long long)addrs[n],(unsigned long long)make_pte_%s(a,addrs[n],p,flags));}'''%(11 if arch=='hopper' else 10,4 if arch=='hopper' else 2,arch)
|
||||
if arch in ['volta','turing','hopper']:
|
||||
main=main.replace('n<3','n<4')
|
||||
if arch=='hopper':main=main.replace('printf(', 'if(!(a==0 && n==3))printf(',1)
|
||||
main=main[:-1]+f'for(int n=0;n<2;n++)printf("255 0 0 %llu %llu\\n",n?65536ULL:4096ULL,(unsigned long long)unmapped_pte_{unmapped_arch}(n?65536:4096));}}'
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
p=Path(tmp);(p/'oracle.c').write_text(prefix+f'\n#include "{D}/{arch}_dev_mmu.h"\n'+body+'\n'+main);subprocess.run(['cc','-std=c11','-Wall','-Werror','-O2',str(p/'oracle.c'),'-o',str(p/'oracle')],check=True);out=subprocess.check_output([str(p/'oracle')],text=True)
|
||||
for line in out.splitlines():
|
||||
ap,prot,flags,addr,bits=map(int,line.split());vectors.append((idx,ap,prot,flags,addr,bits))
|
||||
lines=['// Actual shipped C encoder outputs; tools/check_mmu_oracle.py','pub const VECTORS:&[(u8,u8,u8,u8,u64,u64)]=&[']+[str(v).replace(' ','')+',' for v in vectors]+['];']
|
||||
(R/'src/nvidia/src/mmu/oracle_vectors.rs').write_text('\n'.join(lines)+'\n');(R/'reports/mmu-oracle.json').write_text(json.dumps({'passed':True,'actual_C_vectors':len(vectors),'source_hashes_verified':True,'compiler':'cc -std=c11 -Wall -Werror -O2','execution':'Own extracted pure C encoder functions only; no target driver code executed'},indent=2)+'\n');print(len(vectors),'actual C vectors')
|
||||
# Compile actual Volta PDE helpers as well, including the depth2 ATS condition.
|
||||
source=(D/'volta_mmu.c').read_text();body='\n'.join(function(source,n) for n in ['single_pde_volta','big_half_pde_volta','small_half_pde_volta'])
|
||||
pde_prefix='''\ntypedef uint32_t NvU32;typedef struct {struct{uint64_t address;int aperture;} addr;} uvm_mmu_page_table_alloc_t;static struct {struct{bool enabled;} ats;} g_uvm_global;\n'''
|
||||
main='''int main(void){for(int a=0;a<2;a++)for(int d=0;d<3;d++)for(int ats=0;ats<2;ats++){uvm_mmu_page_table_alloc_t alloc={{0x12345000,a}};g_uvm_global.ats.enabled=ats;printf("0 %d %d %d %llu\\n",a,d,ats,(unsigned long long)single_pde_volta(&alloc,d));}for(int a=0;a<2;a++){uvm_mmu_page_table_alloc_t alloc={{0x12345000,a}};printf("1 %d 0 0 %llu\\n",a,(unsigned long long)big_half_pde_volta(&alloc));printf("2 %d 0 0 %llu\\n",a,(unsigned long long)small_half_pde_volta(&alloc));}}'''
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
p=Path(tmp);(p/'pde.c').write_text(prefix+f'\n#include "{D}/volta_dev_mmu.h"\n'+pde_prefix+body+main);subprocess.run(['cc','-std=c11','-Wall','-Werror','-O2',str(p/'pde.c'),'-o',str(p/'pde')],check=True);out=subprocess.check_output([str(p/'pde')],text=True)
|
||||
pdes=[tuple(map(int,l.split())) for l in out.splitlines()];(R/'src/nvidia/src/mmu/pde_oracle_vectors.rs').write_text('// Actual shipped Volta C PDE helpers\npub const PDE_VECTORS:&[(u8,u8,u8,u8,u64)]=&[\n'+'\n'.join(str(v).replace(' ','')+',' for v in pdes)+'\n];\n');print(len(pdes),'actual C PDE vectors')
|
||||
report=json.loads((R/'reports/mmu-oracle.json').read_text());report['actual_C_PDE_vectors']=len(pdes);(R/'reports/mmu-oracle.json').write_text(json.dumps(report,indent=2)+'\n')
|
||||
|
||||
|
||||
def main():
|
||||
verify_provenance(D)
|
||||
vectors = []
|
||||
for idx, arch in enumerate(["maxwell", "pascal", "volta", "turing", "hopper"]):
|
||||
source = (D / f"{arch}_mmu.c").read_text()
|
||||
body = function(source, "make_pte_" + arch)
|
||||
unmapped_arch = "pascal" if arch in ("volta", "turing") else arch
|
||||
unmapped_source = (D / f"{unmapped_arch}_mmu.c").read_text()
|
||||
body += "\n" + function(unmapped_source, "unmapped_pte_" + unmapped_arch)
|
||||
if arch == "hopper":
|
||||
body = (
|
||||
"\n".join(line for line in source.splitlines() if line.startswith("#define NV_MMU_VER3_PTE_ADDRESS_"))
|
||||
+ "\n"
|
||||
+ function(source, "pte_pcf")
|
||||
+ "\n"
|
||||
+ body
|
||||
)
|
||||
main_src = (
|
||||
'int main(void){uint64_t addrs[]={0,0x12345000ULL,0x1bad000000ULL,0x400000000000ULL};'
|
||||
'for(int a=0;a<%d;a++)for(int p=1;p<=3;p++)for(int flags=0;flags<%d;flags++)'
|
||||
'for(int n=0;n<3;n++)printf("%%d %%d %%d %%llu %%llu\\n",a,p,flags,'
|
||||
'(unsigned long long)addrs[n],(unsigned long long)make_pte_%s(a,addrs[n],p,flags));}'
|
||||
% (11 if arch == "hopper" else 10, 4 if arch == "hopper" else 2, arch)
|
||||
)
|
||||
if arch in ("volta", "turing", "hopper"):
|
||||
main_src = main_src.replace("n<3", "n<4")
|
||||
if arch == "hopper":
|
||||
main_src = main_src.replace("printf(", "if(!(a==0 && n==3))printf(", 1)
|
||||
main_src = (
|
||||
main_src[:-1]
|
||||
+ f'for(int n=0;n<2;n++)printf("255 0 0 %llu %llu\\n",n?65536ULL:4096ULL,'
|
||||
+ f'(unsigned long long)unmapped_pte_{unmapped_arch}(n?65536:4096));}}'
|
||||
)
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
p = Path(tmp)
|
||||
(p / "oracle.c").write_text(PREFIX + f'\n#include "{D}/{arch}_dev_mmu.h"\n' + body + "\n" + main_src)
|
||||
subprocess.run(
|
||||
["cc", "-std=c11", "-Wall", "-Werror", "-O2", str(p / "oracle.c"), "-o", str(p / "oracle")],
|
||||
check=True,
|
||||
)
|
||||
out = subprocess.check_output([str(p / "oracle")], text=True)
|
||||
for line in out.splitlines():
|
||||
ap, prot, flags, addr, bits = map(int, line.split())
|
||||
vectors.append((idx, ap, prot, flags, addr, bits))
|
||||
|
||||
lines = [
|
||||
"// Actual shipped C encoder outputs; tools/check_mmu_oracle.py",
|
||||
"pub const VECTORS:&[(u8,u8,u8,u8,u64,u64)]=&[",
|
||||
] + [str(v).replace(" ", "") + "," for v in vectors] + ["];"]
|
||||
(R / "src/nvidia/src/mmu/oracle_vectors.rs").write_text("\n".join(lines) + "\n")
|
||||
report_path = R / "reports/mmu-oracle.json"
|
||||
report_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
report = {
|
||||
"passed": True,
|
||||
"actual_C_vectors": len(vectors),
|
||||
"source_hashes_verified": True,
|
||||
"compiler": "cc -std=c11 -Wall -Werror -O2",
|
||||
"execution": "Own extracted pure C encoder functions only; no target driver code executed",
|
||||
}
|
||||
report_path.write_text(json.dumps(report, indent=2) + "\n")
|
||||
print(len(vectors), "actual C vectors")
|
||||
|
||||
# Compile actual Volta PDE helpers as well, including the depth2 ATS condition.
|
||||
source = (D / "volta_mmu.c").read_text()
|
||||
body = "\n".join(
|
||||
function(source, n) for n in ["single_pde_volta", "big_half_pde_volta", "small_half_pde_volta"]
|
||||
)
|
||||
pde_prefix = (
|
||||
"\ntypedef uint32_t NvU32;"
|
||||
"typedef struct {struct{uint64_t address;int aperture;} addr;} uvm_mmu_page_table_alloc_t;"
|
||||
"static struct {struct{bool enabled;} ats;} g_uvm_global;\n"
|
||||
)
|
||||
pde_main = (
|
||||
'int main(void){for(int a=0;a<2;a++)for(int d=0;d<3;d++)for(int ats=0;ats<2;ats++)'
|
||||
'{uvm_mmu_page_table_alloc_t alloc={{0x12345000,a}};g_uvm_global.ats.enabled=ats;'
|
||||
'printf("0 %d %d %d %llu\\n",a,d,ats,(unsigned long long)single_pde_volta(&alloc,d));}'
|
||||
'for(int a=0;a<2;a++){uvm_mmu_page_table_alloc_t alloc={{0x12345000,a}};'
|
||||
'printf("1 %d 0 0 %llu\\n",a,(unsigned long long)big_half_pde_volta(&alloc));'
|
||||
'printf("2 %d 0 0 %llu\\n",a,(unsigned long long)small_half_pde_volta(&alloc));}}'
|
||||
)
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
p = Path(tmp)
|
||||
(p / "pde.c").write_text(PREFIX + f'\n#include "{D}/volta_dev_mmu.h"\n' + pde_prefix + body + pde_main)
|
||||
subprocess.run(
|
||||
["cc", "-std=c11", "-Wall", "-Werror", "-O2", str(p / "pde.c"), "-o", str(p / "pde")],
|
||||
check=True,
|
||||
)
|
||||
out = subprocess.check_output([str(p / "pde")], text=True)
|
||||
pdes = [tuple(map(int, line.split())) for line in out.splitlines()]
|
||||
(R / "src/nvidia/src/mmu/pde_oracle_vectors.rs").write_text(
|
||||
"// Actual shipped Volta C PDE helpers\npub const PDE_VECTORS:&[(u8,u8,u8,u8,u64)]=&[\n"
|
||||
+ "\n".join(str(v).replace(" ", "") + "," for v in pdes)
|
||||
+ "\n];\n"
|
||||
)
|
||||
print(len(pdes), "actual C PDE vectors")
|
||||
report["actual_C_PDE_vectors"] = len(pdes)
|
||||
report_path.write_text(json.dumps(report, indent=2) + "\n")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
||||
@ -1,29 +1,105 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Check two finite original-driver captures; this is not a Rust parity test."""
|
||||
import argparse,json,hashlib
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
p=argparse.ArgumentParser();p.add_argument('report_directory',type=Path);p.add_argument('--labels',type=Path,required=True);a=p.parse_args();root=a.report_directory
|
||||
left=json.loads((root/'standalone-dispatch.json').read_text())
|
||||
dispatch_path = root / 'timestamped-dispatch.json'
|
||||
dispatch_bytes = dispatch_path.read_bytes()
|
||||
right = json.loads(dispatch_bytes)
|
||||
|
||||
|
||||
def signature(d):
|
||||
return[(e['gpu_ordinal'],e['engine_ordinal'],e['stage'],e['callback']['name'],e['callback']['offset'],e['load_flags'])for e in d['events']]
|
||||
checks={'both_runs_2056_samples':left['samples']==right['samples']==2056,'both_runs_eight_gpu_owners':left['gpu_count']==right['gpu_count']==8,'no_unparsed_samples':not left['rejected']and not right['rejected'],'same_per_gpu_sequences':left['all_gpu_sequences_identical']and right['all_gpu_sequences_identical'],'same_order_across_repeated_runs':signature(left)==signature(right),'all_timestamped_groups_ordered':all(g['timestamp_ordered']for g in right['gpu_groups']),'all_same_engine_sets':all(g['same_engine_set_across_locked_preload_load']for g in right['gpu_groups']),'all_preload_before_load':all(g['all_preload_before_load']for g in right['gpu_groups']),'all_optional_unlocked_before_locked':all(g['unlocked_before_matching_locked']for g in right['gpu_groups'])}
|
||||
counts={k:sum(k in line for line in (root/'timestamped-record-dump.txt').open())for k in ['PERF_RECORD_LOST','PERF_RECORD_THROTTLE','PERF_RECORD_UNTHROTTLE']};checks['no_reported_lost_or_throttled_records']=not any(counts.values())
|
||||
labels=json.loads(a.labels.read_text())
|
||||
# The generator records a source path relative to its checkout. Verify the
|
||||
# uniquely identified artifact by content even when the bundle has moved.
|
||||
recorded_hashes = [
|
||||
digest for name, digest in labels['inputs'].items()
|
||||
if Path(name).name == dispatch_path.name
|
||||
]
|
||||
checks['label_input_hash_matches'] = (
|
||||
len(recorded_hashes) == 1
|
||||
and recorded_hashes[0] == hashlib.sha256(dispatch_bytes).hexdigest()
|
||||
)
|
||||
checks['all_labeled_callbacks_match_samples']=all((e:=right['events'][c['sample']])['callback']['name']==c['symbol']and e['callback_address']==c['callback_address']and e['engine_ordinal']==obj['engine_ordinal0']and e['engine_owner']==obj['engine_owner']and e['gpu_owner']==obj['gpu_owner']and e['stage']==stage for obj in labels['engines']for stage,c in obj['callbacks'].items())
|
||||
bundle=json.loads((root/'final-rea-evidence-bundle.json').read_text());ids=['ev_b1b9a9279aa151b6f51c93b6bee10b9949d4c6e0f4afcc14d61579d213210443','ev_1b2d3b2a0781ff192ac6f67dc3e065dafe95bcb8960d5a122583f4e3cbff8e46'];records={e['evidence_id']:e for e in bundle['records']}
|
||||
for i in ids:
|
||||
n=records[i]['normalized_result'];out=''.join(f['data']for f in n['frames']);checks['successful_cuda_workload_'+i]=n['exit']['code']==0 and '"passed":true'in out and '"verified_words":64'in out and '"context_destroyed":true'in out
|
||||
report={'passed':all(checks.values()),'scope':'Finite original-driver observations and decoding only; not Rust parity. Hardware breakpoint timings are not a performance baseline. REA process-tree sampling limitations remain in retained Evidence.','checks':checks,'record_loss_diagnostics':counts,'rea_capture_evidence':ids};(root/'validation.json').write_text(json.dumps(report,indent=2)+'\n');print(json.dumps(report,indent=2));raise SystemExit(0 if report['passed']else 1)
|
||||
return [
|
||||
(
|
||||
e["gpu_ordinal"],
|
||||
e["engine_ordinal"],
|
||||
e["stage"],
|
||||
e["callback"]["name"],
|
||||
e["callback"]["offset"],
|
||||
e["load_flags"],
|
||||
)
|
||||
for e in d["events"]
|
||||
]
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
p = argparse.ArgumentParser(description=__doc__)
|
||||
p.add_argument("report_directory", type=Path)
|
||||
p.add_argument("--labels", type=Path, required=True)
|
||||
a = p.parse_args(argv)
|
||||
root = a.report_directory
|
||||
left = json.loads((root / "standalone-dispatch.json").read_text())
|
||||
dispatch_path = root / "timestamped-dispatch.json"
|
||||
dispatch_bytes = dispatch_path.read_bytes()
|
||||
right = json.loads(dispatch_bytes)
|
||||
checks = {
|
||||
"both_runs_2056_samples": left["samples"] == right["samples"] == 2056,
|
||||
"both_runs_eight_gpu_owners": left["gpu_count"] == right["gpu_count"] == 8,
|
||||
"no_unparsed_samples": not left["rejected"] and not right["rejected"],
|
||||
"same_per_gpu_sequences": left["all_gpu_sequences_identical"] and right["all_gpu_sequences_identical"],
|
||||
"same_order_across_repeated_runs": signature(left) == signature(right),
|
||||
"all_timestamped_groups_ordered": all(g["timestamp_ordered"] for g in right["gpu_groups"]),
|
||||
"all_same_engine_sets": all(g["same_engine_set_across_locked_preload_load"] for g in right["gpu_groups"]),
|
||||
"all_preload_before_load": all(g["all_preload_before_load"] for g in right["gpu_groups"]),
|
||||
"all_optional_unlocked_before_locked": all(g["unlocked_before_matching_locked"] for g in right["gpu_groups"]),
|
||||
}
|
||||
record_keys = ("PERF_RECORD_LOST", "PERF_RECORD_THROTTLE", "PERF_RECORD_UNTHROTTLE")
|
||||
counts = {k: 0 for k in record_keys}
|
||||
with (root / "timestamped-record-dump.txt").open() as dump:
|
||||
for line in dump:
|
||||
for k in record_keys:
|
||||
if k in line:
|
||||
counts[k] += 1
|
||||
checks["no_reported_lost_or_throttled_records"] = not any(counts.values())
|
||||
labels = json.loads(a.labels.read_text())
|
||||
# The generator records a source path relative to its checkout. Verify the
|
||||
# uniquely identified artifact by content even when the bundle has moved.
|
||||
recorded_hashes = [
|
||||
digest for name, digest in labels["inputs"].items()
|
||||
if Path(name).name == dispatch_path.name
|
||||
]
|
||||
checks["label_input_hash_matches"] = (
|
||||
len(recorded_hashes) == 1
|
||||
and recorded_hashes[0] == hashlib.sha256(dispatch_bytes).hexdigest()
|
||||
)
|
||||
checks["all_labeled_callbacks_match_samples"] = all(
|
||||
(e := right["events"][c["sample"]])["callback"]["name"] == c["symbol"]
|
||||
and e["callback_address"] == c["callback_address"]
|
||||
and e["engine_ordinal"] == obj["engine_ordinal0"]
|
||||
and e["engine_owner"] == obj["engine_owner"]
|
||||
and e["gpu_owner"] == obj["gpu_owner"]
|
||||
and e["stage"] == stage
|
||||
for obj in labels["engines"]
|
||||
for stage, c in obj["callbacks"].items()
|
||||
)
|
||||
bundle = json.loads((root / "final-rea-evidence-bundle.json").read_text())
|
||||
ids = [
|
||||
"ev_b1b9a9279aa151b6f51c93b6bee10b9949d4c6e0f4afcc14d61579d213210443",
|
||||
"ev_1b2d3b2a0781ff192ac6f67dc3e065dafe95bcb8960d5a122583f4e3cbff8e46",
|
||||
]
|
||||
records = {e["evidence_id"]: e for e in bundle["records"]}
|
||||
for i in ids:
|
||||
n = records[i]["normalized_result"]
|
||||
out = "".join(f["data"] for f in n["frames"])
|
||||
checks["successful_cuda_workload_" + i] = (
|
||||
n["exit"]["code"] == 0
|
||||
and '"passed":true' in out
|
||||
and '"verified_words":64' in out
|
||||
and '"context_destroyed":true' in out
|
||||
)
|
||||
report = {
|
||||
"passed": all(checks.values()),
|
||||
"scope": (
|
||||
"Finite original-driver observations and decoding only; not Rust parity. "
|
||||
"Hardware breakpoint timings are not a performance baseline. "
|
||||
"REA process-tree sampling limitations remain in retained Evidence."
|
||||
),
|
||||
"checks": checks,
|
||||
"record_loss_diagnostics": counts,
|
||||
"rea_capture_evidence": ids,
|
||||
}
|
||||
(root / "validation.json").write_text(json.dumps(report, indent=2) + "\n")
|
||||
print(json.dumps(report, indent=2))
|
||||
raise SystemExit(0 if report["passed"] else 1)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
||||
@ -4,16 +4,19 @@ is exported by our nvidia_rs_uvm_bridge.ko. Needs no GPU and no module loading.
|
||||
|
||||
usage: check_uvm_620_exports.py [stock-nvidia-uvm.ko] [bridge.ko]
|
||||
"""
|
||||
import argparse
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
stock = Path(sys.argv[1] if len(sys.argv) > 1 else ROOT / "../nvidia-open-620.73.04/kernel-open/nvidia-uvm.ko")
|
||||
bridge = Path(sys.argv[2] if len(sys.argv) > 2 else ROOT / "kernel-open/uvm_bridge/nvidia_rs_uvm_bridge.ko")
|
||||
DEFAULT_STOCK = ROOT / "../nvidia-open-620.73.04/kernel-open/nvidia-uvm.ko"
|
||||
DEFAULT_BRIDGE = ROOT / "kernel-open/uvm_bridge/nvidia_rs_uvm_bridge.ko"
|
||||
|
||||
|
||||
def syms(path, kind):
|
||||
if not path.is_file():
|
||||
raise SystemExit(f"module not found: {path}")
|
||||
out = set()
|
||||
for line in subprocess.check_output(["nm", str(path)], text=True).splitlines():
|
||||
p = line.split()
|
||||
@ -24,15 +27,27 @@ def syms(path, kind):
|
||||
# an export is a __ksymtab_ entry, not just a defined function
|
||||
if name.startswith("__ksymtab_nvUvmInterface"):
|
||||
out.add(name[len("__ksymtab_"):])
|
||||
elif name.startswith("nvUvmInterface") and p[-2] == "U":
|
||||
elif len(p) >= 2 and name.startswith("nvUvmInterface") and p[-2] == "U":
|
||||
out.add(name)
|
||||
return out
|
||||
|
||||
|
||||
need = syms(stock, "U")
|
||||
have = syms(bridge, "T")
|
||||
missing = sorted(need - have)
|
||||
print(f"stock needs {len(need)} nvUvmInterface* symbols; bridge exports {len(have)}; missing {len(missing)}")
|
||||
for m in missing:
|
||||
print(" MISSING", m)
|
||||
sys.exit(1 if missing else 0)
|
||||
def main(argv=None):
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("stock", nargs="?", type=Path, default=DEFAULT_STOCK)
|
||||
parser.add_argument("bridge", nargs="?", type=Path, default=DEFAULT_BRIDGE)
|
||||
args = parser.parse_args(argv)
|
||||
|
||||
need = syms(args.stock, "U")
|
||||
have = syms(args.bridge, "T")
|
||||
if not need:
|
||||
raise SystemExit(f"no undefined nvUvmInterface* symbols found in {args.stock}")
|
||||
missing = sorted(need - have)
|
||||
print(f"stock needs {len(need)} nvUvmInterface* symbols; bridge exports {len(have)}; missing {len(missing)}")
|
||||
for m in missing:
|
||||
print(" MISSING", m)
|
||||
return 1 if missing else 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
|
||||
@ -1,22 +1,115 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Bound PT decode output/errors; preserve raw data and declare incomplete decode."""
|
||||
import argparse
|
||||
import collections
|
||||
import json
|
||||
from pathlib import Path
|
||||
import argparse,json,subprocess,signal,time,os,re,collections
|
||||
p=argparse.ArgumentParser();p.add_argument('--input',required=True);p.add_argument('--kallsyms',required=True);p.add_argument('--output',type=Path,required=True);p.add_argument('--time');p.add_argument('--max-lines',type=int,default=20000);p.add_argument('--max-errors',type=int,default=100);p.add_argument('--all-symbols',action='store_true');p.add_argument('--itrace',choices=['ce','be'],default='ce');a=p.parse_args();a.output.parent.mkdir(parents=True,exist_ok=True)
|
||||
symbols=['_nv000790rm','_nv030241rm','_nv033663rm','_nv033665rm','_nv016741rm','_nv016753rm','_nv028470rm','_nv043236rm','_nv043182rm','_nv027605rm','_nv029864rm','_nv033231rm','_nv033300rm','_nv055403rm','_nv028309rm','_nv028308rm','_nv043609rm']
|
||||
command=['perf','script','-i',a.input,'--itrace='+a.itrace,'--ns','-F','comm,pid,tid,time,ip,sym,symoff,addr,dso,flags','--kallsyms',a.kallsyms]
|
||||
if not a.all_symbols:command+=['-S',','.join(symbols)]
|
||||
if a.time:command+=['--time',a.time]
|
||||
lines=0;errors=0;error_codes=collections.Counter();stop=None;start=time.monotonic();errpath=a.output.with_suffix('.stderr');reportpath=a.output.with_suffix('.json')
|
||||
with a.output.open('w')as f,errpath.open('w')as err:
|
||||
child=subprocess.Popen(command,stdout=subprocess.PIPE,stderr=err,text=True,start_new_session=True)
|
||||
for line in child.stdout:
|
||||
f.write(line);lines+=1
|
||||
if 'instruction trace error'in line:
|
||||
errors+=1;match=re.search(r'code (\d+):',line);error_codes[match.group(1)if match else'unknown']+=1
|
||||
if errors>=a.max_errors or lines>=a.max_lines:
|
||||
stop='error_limit'if errors>=a.max_errors else'line_limit';child.send_signal(signal.SIGINT);break
|
||||
child.stdout.close()
|
||||
try:status=child.wait(timeout=10)
|
||||
except subprocess.TimeoutExpired:child.kill();status=child.wait();stop=stop or'decoder_shutdown_timeout'
|
||||
report={'command':command,'exit_code':status,'stop':stop,'output_lines':lines,'trace_errors':errors,'error_codes':dict(error_codes),'instruction_mismatch_errors':error_codes.get('6',0),'elapsed_seconds':time.monotonic()-start,'scope':'Bounded decoder observation only. A size-limited source capture, interrupted/error decode or limited requested time cannot establish absent events.'};reportpath.write_text(json.dumps(report,indent=2)+'\n');print(json.dumps(report))
|
||||
import re
|
||||
import signal
|
||||
import subprocess
|
||||
import time
|
||||
|
||||
SYMBOLS = [
|
||||
"_nv000790rm", "_nv030241rm", "_nv033663rm", "_nv033665rm",
|
||||
"_nv016741rm", "_nv016753rm", "_nv028470rm", "_nv043236rm",
|
||||
"_nv043182rm", "_nv027605rm", "_nv029864rm", "_nv033231rm",
|
||||
"_nv033300rm", "_nv055403rm", "_nv028309rm", "_nv028308rm",
|
||||
"_nv043609rm",
|
||||
]
|
||||
|
||||
|
||||
def _positive_int(value):
|
||||
parsed = int(value)
|
||||
if parsed < 1:
|
||||
raise argparse.ArgumentTypeError("must be >= 1")
|
||||
return parsed
|
||||
|
||||
|
||||
def build_parser():
|
||||
p = argparse.ArgumentParser(description=__doc__)
|
||||
p.add_argument("--input", required=True)
|
||||
p.add_argument("--kallsyms", required=True)
|
||||
p.add_argument("--output", type=Path, required=True)
|
||||
p.add_argument("--time")
|
||||
p.add_argument("--max-lines", type=_positive_int, default=20000)
|
||||
p.add_argument("--max-errors", type=_positive_int, default=100)
|
||||
p.add_argument("--all-symbols", action="store_true")
|
||||
p.add_argument("--itrace", choices=["ce", "be"], default="ce")
|
||||
return p
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
a = build_parser().parse_args(argv)
|
||||
a.output.parent.mkdir(parents=True, exist_ok=True)
|
||||
command = [
|
||||
"perf", "script", "-i", a.input, "--itrace=" + a.itrace, "--ns",
|
||||
"-F", "comm,pid,tid,time,ip,sym,symoff,addr,dso,flags",
|
||||
"--kallsyms", a.kallsyms,
|
||||
]
|
||||
if not a.all_symbols:
|
||||
command += ["-S", ",".join(SYMBOLS)]
|
||||
if a.time:
|
||||
command += ["--time", a.time]
|
||||
|
||||
lines = 0
|
||||
errors = 0
|
||||
error_codes = collections.Counter()
|
||||
stop = None
|
||||
status = -1
|
||||
start = time.monotonic()
|
||||
errpath = a.output.with_suffix(".stderr")
|
||||
reportpath = a.output.with_suffix(".json")
|
||||
|
||||
with a.output.open("w") as f, errpath.open("w") as err:
|
||||
try:
|
||||
child = subprocess.Popen(
|
||||
command, stdout=subprocess.PIPE, stderr=err, text=True, start_new_session=True
|
||||
)
|
||||
except OSError as exc:
|
||||
raise SystemExit(f"failed to launch perf: {exc}") from exc
|
||||
try:
|
||||
if child.stdout is None:
|
||||
raise RuntimeError("perf subprocess stdout pipe unavailable")
|
||||
for line in child.stdout:
|
||||
f.write(line)
|
||||
lines += 1
|
||||
if "instruction trace error" in line:
|
||||
errors += 1
|
||||
match = re.search(r"code (\d+):", line)
|
||||
error_codes[match.group(1) if match else "unknown"] += 1
|
||||
if errors >= a.max_errors or lines >= a.max_lines:
|
||||
stop = "error_limit" if errors >= a.max_errors else "line_limit"
|
||||
child.send_signal(signal.SIGINT)
|
||||
break
|
||||
finally:
|
||||
if child.stdout is not None:
|
||||
child.stdout.close()
|
||||
try:
|
||||
status = child.wait(timeout=10)
|
||||
except subprocess.TimeoutExpired:
|
||||
child.kill()
|
||||
status = child.wait()
|
||||
stop = stop or "decoder_shutdown_timeout"
|
||||
|
||||
report = {
|
||||
"command": command,
|
||||
"exit_code": status,
|
||||
"stop": stop,
|
||||
"output_lines": lines,
|
||||
"trace_errors": errors,
|
||||
"error_codes": dict(error_codes),
|
||||
"instruction_mismatch_errors": error_codes.get("6", 0),
|
||||
"elapsed_seconds": time.monotonic() - start,
|
||||
"scope": (
|
||||
"Bounded decoder observation only. A size-limited source capture, "
|
||||
"interrupted/error decode or limited requested time cannot establish absent events."
|
||||
),
|
||||
}
|
||||
reportpath.write_text(json.dumps(report, indent=2) + "\n")
|
||||
print(json.dumps(report))
|
||||
if stop is None and status != 0:
|
||||
raise SystemExit(status if status > 0 else 1)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
||||
@ -1,10 +1,66 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Generate or verify Rust timer-alarm test vectors from reports/timer-alarm-original.json."""
|
||||
import argparse
|
||||
import json
|
||||
from pathlib import Path
|
||||
import json,argparse
|
||||
p=argparse.ArgumentParser();p.add_argument('--check',action='store_true');a=p.parse_args();R=Path(__file__).resolve().parents[1];data=json.loads((R/'reports/timer-alarm-original.json').read_text());tags={'flag':0,'access':1,'write':2,'time':3,'pending':4,'diagnostic':5};s='use super::Vector;\n// Actual original016384/059642/059655 instruction outputs; not Rust-generated expectations.\n#[rustfmt::skip]\npub(super) const VECTORS: &[Vector] = &[\n'
|
||||
for row in data['cases']:
|
||||
c=row['input'];events=','.join('&['+','.join(map(str,[tags[e[0]],*e[1:]]))+']'for e in row['events']);values=','.join(map(str,c['times']));pending=','.join(map(str,c['pending']));status='None'if row['status']is None else'Some('+str(row['status'])+')';s+='Vector {kind:%d,deadline:%d,flags:%d,gpu908:%d,disabled:%d,countdown:%d,policy:%d,times:&[%s],pending:&[%s],events:&[%s],status:%s},\n'%({'alarm':0,'schedule':1,'countdown':2}[c['kind']],c['deadline'],c['flags'],c['gpu908'],c['disabled'],c['countdown'],{'valid':0,'not_loaded':1,'inaccessible':2}[c['policy']],values,pending,events,status)
|
||||
s+='];\n';dest=R/'tests/timer-alarm/vectors.rs'
|
||||
if a.check:assert dest.read_text()==s,'Original alarm Rust vectors drift'
|
||||
else:dest.write_text(s)
|
||||
print(len(data['cases']),'independent original vectors retained')
|
||||
|
||||
R = Path(__file__).resolve().parents[1]
|
||||
TAGS = {"flag": 0, "access": 1, "write": 2, "time": 3, "pending": 4, "diagnostic": 5}
|
||||
KINDS = {"alarm": 0, "schedule": 1, "countdown": 2}
|
||||
POLICIES = {"valid": 0, "not_loaded": 1, "inaccessible": 2}
|
||||
|
||||
|
||||
def render_vectors(data):
|
||||
lines = [
|
||||
"use super::Vector;",
|
||||
"// Actual original016384/059642/059655 instruction outputs; not Rust-generated expectations.",
|
||||
"#[rustfmt::skip]",
|
||||
"pub(super) const VECTORS: &[Vector] = &[",
|
||||
]
|
||||
for row in data["cases"]:
|
||||
c = row["input"]
|
||||
events = ",".join(
|
||||
"&[" + ",".join(map(str, [TAGS[e[0]], *e[1:]])) + "]" for e in row["events"]
|
||||
)
|
||||
values = ",".join(map(str, c["times"]))
|
||||
pending = ",".join(map(str, c["pending"]))
|
||||
status = "None" if row["status"] is None else f"Some({row['status']})"
|
||||
lines.append(
|
||||
"Vector {kind:%d,deadline:%d,flags:%d,gpu908:%d,disabled:%d,countdown:%d,policy:%d,"
|
||||
"times:&[%s],pending:&[%s],events:&[%s],status:%s},"
|
||||
% (
|
||||
KINDS[c["kind"]],
|
||||
c["deadline"],
|
||||
c["flags"],
|
||||
c["gpu908"],
|
||||
c["disabled"],
|
||||
c["countdown"],
|
||||
POLICIES[c["policy"]],
|
||||
values,
|
||||
pending,
|
||||
events,
|
||||
status,
|
||||
)
|
||||
)
|
||||
lines.append("];")
|
||||
return "\n".join(lines) + "\n"
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
p = argparse.ArgumentParser(description=__doc__)
|
||||
p.add_argument("--check", action="store_true")
|
||||
a = p.parse_args(argv)
|
||||
data = json.loads((R / "reports/timer-alarm-original.json").read_text())
|
||||
rendered = render_vectors(data)
|
||||
dest = R / "tests/timer-alarm/vectors.rs"
|
||||
if a.check:
|
||||
if not dest.is_file() or dest.read_text() != rendered:
|
||||
raise SystemExit("Original alarm Rust vectors drift")
|
||||
else:
|
||||
dest.parent.mkdir(parents=True, exist_ok=True)
|
||||
dest.write_text(rendered)
|
||||
print(len(data["cases"]), "independent original vectors retained")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
||||
Reference in New Issue
Block a user