Files
nvdriver/tools/check_ramin_oracle.py
morebrackets e763a670fa Address Greptile findings on #287
- tools/check_ramin_oracle.py, tools/check_system_memory_abi.py,
  tools/check_root_migration_oracle.py (4777570886): require matching 580.178.04
  release metadata (version.mk / nvUnixVersion.h) before accepting any source
  checkout or standalone file, and replace hardcoded /home/geodd defaults with
  Path.home().
- tests/offline/test_native_shader_and_abi_tools.py (4777570880): run the
  check_native_shader fallback ELF test inside a python3 -O child process with
  pyelftools explicitly blocked via sys.modules and verify _FallbackELFFile
  executes; also test rejection of unversioned and 620.70.06 source trees.
2026-12-02 17:20:40 -08:00

181 lines
7.7 KiB
Python

#!/usr/bin/env python3
"""Compile exact GP100/GV100 PDB HAL functions against their published RAMIN headers."""
import hashlib
import json
import os
from pathlib import Path
import re
import subprocess
import tempfile
R = Path(__file__).resolve().parents[1]
EXPECTED_RELEASE = '580.178.04'
DEFAULT_ANALYSIS_ROOT = Path.home() / 'nvidia-driver/analysis-580.178.04'
REQUIRED_REL = (
'nvidia/src/kernel/gpu/mmu/arch/pascal/kern_gmmu_gp100.c',
'nvidia/src/kernel/gpu/mmu/arch/volta/kern_gmmu_gv100.c',
'common/inc/swref/published/pascal/gp100/dev_ram.h',
'common/inc/swref/published/volta/gv100/dev_ram.h',
)
def _detect_release(path: Path) -> str | None:
cur = path.resolve()
if cur.is_file():
cur = cur.parent
for _ in range(6):
ver_mk = cur / 'version.mk'
if ver_mk.is_file():
m = re.search(r'^\s*NVIDIA_VERSION\s*[:?]?=\s*(\S+)', ver_mk.read_text(encoding='utf-8', errors='replace'), re.M)
if m:
return m.group(1).strip()
unix_ver = cur / 'src/common/sdk/nvidia/inc/nvUnixVersion.h'
if unix_ver.is_file():
m = re.search(r'#define\s+NV_VERSION_STRING\s+"([^"]+)"', unix_ver.read_text(encoding='utf-8', errors='replace'))
if m:
return m.group(1).strip()
if cur.parent == cur:
break
cur = cur.parent
return None
def find_open_gpu_src() -> Path:
candidates: list[Path] = []
for env_name in ('NV_RS_OPEN_GPU_SRC', 'OPEN_GPU_ROOT'):
val = os.environ.get(env_name)
if val:
base = Path(val)
candidates.extend([base / 'src', base])
analysis = Path(os.environ.get('NV_RS_ANALYSIS_ROOT', str(DEFAULT_ANALYSIS_ROOT)))
candidates.append(analysis / f'reference/open-gpu-kernel-modules-{EXPECTED_RELEASE}/src')
for candidate in candidates:
if all((candidate / rel).is_file() for rel in REQUIRED_REL) and _detect_release(candidate) == EXPECTED_RELEASE:
return candidate.resolve()
raise SystemExit(
f'Cannot find open-gpu-kernel-modules-{EXPECTED_RELEASE} RAMIN sources (matching release metadata required). '
'Set NV_RS_OPEN_GPU_SRC (or OPEN_GPU_ROOT / NV_RS_ANALYSIS_ROOT).'
)
def function(path: Path, name: str) -> str:
text = path.read_text(encoding='utf-8')
start = text.rfind('NV_STATUS', 0, text.index(name + '\n'))
pos = text.index('{', start)
level = 1
end = pos + 1
while level:
level += (text[end] == '{') - (text[end] == '}')
end += 1
return text[start:end]
PREFIX_TEMPLATE = r'''
#include <stdint.h>
#include <stdio.h>
#include <assert.h>
#include "GPHEADER"
#include "GVHEADER"
typedef uint32_t NvU32;typedef uint64_t NvU64;typedef uint64_t RmPhysAddr;typedef int NV_STATUS;
typedef struct {int unused;} OBJGPU,KernelGmmu,KernelFifo;
typedef struct {NvU64 address;NvU32 aperture,vol;} MEMORY_DESCRIPTOR;typedef MEMORY_DESCRIPTOR *PMEMORY_DESCRIPTOR;
typedef struct {NvU32 version;} GMMU_FMT;
typedef struct {MEMORY_DESCRIPTOR*root;GMMU_FMT*fmt;NvU64 big;} OBJVASPACE;typedef OBJVASPACE OBJGVASPACE;
typedef struct {int bIsClientAdmin,bIsFaultReplayable,bIsZombieSubctx;} INST_BLK_INIT_PARAMS;
#define NV_OK 0
#define NV_ERR_INVALID_STATE 0x40
#define NV_ERR_INVALID_PARAMETER 0x1f
#define FIFO_PDB_IDX_BASE UINT32_MAX
#define GMMU_FMT_VERSION_2 2
#define FERMI_BIG_PAGESIZE_64K 65536
#define AT_GPU 0
#define NV_ASSERT(x) assert(x)
#define NV_ASSERT_OR_RETURN(x,e) do{if(!(x))return(e);}while(0)
#define NV_PRINTF(...)
#define DBG_BREAKPOINT() assert(0)
#define dynamicCast(p,t) ((t*)(p))
#define GPU_GET_KERNEL_GMMU(p) ((KernelGmmu*)(p))
#define GPU_GET_KERNEL_FIFO(p) ((KernelFifo*)(p))
#define NvU64_LO32(v) ((uint32_t)(v))
#define NvU64_HI32(v) ((uint32_t)((v)>>32))
#define FIELD(p,f) NV##p##f
#define FIELDI(p,f,i) NV##p##f(i)
#define SF_OFFSET(f) (((0?f)/32)*4)
#define MASK(f) ((UINT64_C(1)<<((1?f)-(0?f)+1))-1)
#define NUM(f,v) (((uint32_t)((v)&MASK(f)))<<((0?f)%32))
#define SF_NUM(p,f,v) NUM(FIELD(p,f),v)
#define SF_DEF(p,f,c) SF_NUM(p,f,NV##p##f##c)
#define SF_IDX_NUM(p,f,v,i) NUM(FIELDI(p,f,i),v)
#define SF_IDX_DEF(p,f,c,i) SF_IDX_NUM(p,f,NV##p##f##c,i)
static const GMMU_FMT*gvaspaceGetGmmuFmt(OBJGVASPACE*v,OBJGPU*g){(void)g;return v->fmt;}
static MEMORY_DESCRIPTOR*vaspaceGetKernelPageDirBase(OBJVASPACE*v,OBJGPU*g){(void)g;return v->root;}
static MEMORY_DESCRIPTOR*vaspaceGetPageDirBase(OBJVASPACE*v,OBJGPU*g){(void)g;return v->root;}
static NvU64 vaspaceGetBigPageSize(OBJVASPACE*v){return v->big;}
static NvU64 memdescGetPhysAddr(MEMORY_DESCRIPTOR*m,int a,int b){(void)a;(void)b;return m->address;}
static NvU32 kgmmuGetHwPteApertureFromMemdesc(KernelGmmu*g,MEMORY_DESCRIPTOR*m){(void)g;return m->aperture;}
static NvU32 memdescGetVolatility(MEMORY_DESCRIPTOR*m){return m->vol;}
static MEMORY_DESCRIPTOR*kfifoGetDummyPageMemDesc(KernelFifo*f){(void)f;return 0;}
'''
MAIN_C = r'''
int main(void){NvU64 addresses[]={0,0x12345000ULL,0x12345678000ULL,0xfffffffffffff000ULL};NvU32 targets[]={UINT32_MAX,0,63};for(unsigned a=0;a<4;a++)for(unsigned ap=0;ap<4;ap++){if(ap==1)continue;for(unsigned vol=0;vol<2;vol++)for(unsigned replay=0;replay<2;replay++)for(unsigned ver=0;ver<2;ver++)for(unsigned big=0;big<2;big++)for(unsigned t=0;t<3;t++){MEMORY_DESCRIPTOR root={addresses[a],ap,vol};GMMU_FMT fmt={ver?2:1};OBJVASPACE v={&root,&fmt,big?65536:131072};OBJGPU gpu={0};KernelGmmu k={0};INST_BLK_INIT_PARAMS p={0,replay,0};NvU32 lo,lv,hi,hv;if(kgmmuInstBlkPageDirBaseGet_GV100(&gpu,&k,&v,&p,targets[t],&lo,&lv,&hi,&hv)!=0)return 1;printf("%llu %u %u %u %u %u %u %u %u %u %u\n",(unsigned long long)addresses[a],ap,vol,replay,ver,big,targets[t],lo,lv,hi,hv);}}return 0;}
'''
def main() -> None:
src = find_open_gpu_src()
gp = src / REQUIRED_REL[0]
gv = src / REQUIRED_REL[1]
hp = src / REQUIRED_REL[2]
hv = src / REQUIRED_REL[3]
prefix = PREFIX_TEMPLATE.replace('GPHEADER', str(hp)).replace('GVHEADER', str(hv))
with tempfile.TemporaryDirectory() as t:
p = Path(t)
(p / 'oracle.c').write_text(
prefix
+ function(gp, 'kgmmuInstBlkPageDirBaseGet_GP100')
+ function(gv, 'kgmmuInstBlkPageDirBaseGet_GV100')
+ MAIN_C,
encoding='utf-8',
)
subprocess.run(
['cc', '-std=c11', '-UNDEBUG', '-Wall', '-Werror', '-O2', str(p / 'oracle.c'), '-o', str(p / 'oracle')],
check=True,
)
rows = subprocess.check_output([str(p / 'oracle')], text=True).splitlines()
lines = [
'// Original exact580 GP100 base + GV100 subcontext HAL outputs.',
'pub type Vector = (u64,u8,bool,bool,bool,bool,u32,u32,u32,u32,u32);',
'#[rustfmt::skip]',
'pub const VECTORS: &[Vector] = &[',
]
for row in rows:
a, ap, vol, replay, ver, big, target, lo, lv, hi, hv_val = map(int, row.split())
lines.append(
f'({a},{ap},{str(bool(vol)).lower()},{str(bool(replay)).lower()},'
f'{str(bool(ver)).lower()},{str(bool(big)).lower()},{target},{lo},{lv},{hi},{hv_val}),'
)
lines.append('];')
(R / 'src/nvidia/src/mmu/ramin_oracle_vectors.rs').write_text('\n'.join(lines) + '\n', encoding='utf-8')
report = R / 'reports/ramin-oracle.json'
report.parent.mkdir(parents=True, exist_ok=True)
report.write_text(
json.dumps(
{
'passed': True,
'vectors': len(rows),
'source_hashes': {str(path): hashlib.sha256(path.read_bytes()).hexdigest() for path in [gp, gv, hp, hv]},
'executed': 'Original PDB HAL functions with descriptor/property lookup mocks; no driver/GPU execution',
},
indent=2,
)
+ '\n',
encoding='utf-8',
)
print(len(rows), 'original C RAMIN vectors')
if __name__ == '__main__':
main()