Files
nvdriver/tools/gpu_engine_dispatch_sites.py
morebrackets a5cde383de Address Greptile review findings on #301
- tools/check_original_live_timer_init.py (4777572276): record incomplete
  default (_nv059507rm) and config (_nv059487rm) register samples in rejected
  so missing registers cannot pass all_28_samples_parsed.
- tools/gpu_engine_dispatch_sites.py (4777572295): verify nvidia.ko .modinfo
  version (580.178.04) and relative symbol offsets match the kallsyms capture
  snapshot before generating breakpoint sites.
- tools/gpu_label_live_engines.py (4777572314): verify open-gpu-kernel-modules
  release metadata (version.mk / nvUnixVersion.h == 580.178.04) before
  accepting a generated/ directory from OPEN_GPU_ROOT/NV_RS_OPEN_GPU_SRC or
  --generated-dir, and replace hardcoded /home/geodd default with Path.home().
- tests/offline/test_build_product_and_live_timer_tools.py: add unit tests
  covering all three guards.
2026-12-02 16:52:59 -08:00

239 lines
10 KiB
Python

#!/usr/bin/env python3
"""Read-only verification of exact original engine dispatcher HW-breakpoint sites."""
import argparse
import json
import os
from pathlib import Path
import platform
import struct
import subprocess
ROOT = Path(__file__).resolve().parents[1]
DEFAULT_KCORE_DIR = Path('/root/.debug/[kernel.kcore]/a3aac8f0306fd819566d868c7c422dbdcf1e7d42/2026111719514581')
PT_LOAD = 1
SITES = [
('InitUnlocked', '_nv026844rm', 0x3E, 0x58, True),
('InitLocked', '_nv026844rm', 0x80, 0x50, False),
('PreLoad', '_nv031217rm', 0x184, 0x60, False),
('Load', '_nv031217rm', 0x31F, 0x68, False),
]
EXPECTED_DRIVER_VERSION = '580.178.04'
def extract_modinfo_version(raw: bytes, sections, by_name: dict[str, int]) -> str | None:
idx = by_name.get('.modinfo')
if idx is None:
return None
_, h = sections[idx]
blob = raw[h[4]:h[4] + h[5]]
for entry in blob.split(b'\x00'):
if entry.startswith(b'version='):
return entry.split(b'=', 1)[1].decode('utf-8', errors='replace').strip()
return None
def verify_module_matches_capture(
raw: bytes,
sections,
by_name: dict[str, int],
symbols: dict,
lookup: dict[str, int],
target_fns: tuple[str, ...],
expected_version: str = EXPECTED_DRIVER_VERSION,
) -> None:
mod_ver = extract_modinfo_version(raw, sections, by_name)
if mod_ver != expected_version:
raise SystemExit(
f'nvidia.ko version mismatch: expected {expected_version!r} to match capture, got {mod_ver!r}'
)
base_fn = target_fns[0]
if base_fn not in lookup:
raise SystemExit(f'kallsyms snapshot missing {base_fn!r}')
base_disk = symbols[base_fn][1]
base_live = lookup[base_fn]
for name in target_fns[1:]:
if name not in lookup:
raise SystemExit(f'kallsyms snapshot missing {name!r}')
disk_delta = symbols[name][1] - base_disk
live_delta = lookup[name] - base_live
if disk_delta != live_delta:
raise SystemExit(
f'nvidia.ko symbol layout mismatch for {name}: module delta {hex(disk_delta)} != capture delta {hex(live_delta)}'
)
def find_nvidia_ko(explicit: Path | None = None) -> Path:
candidates = []
if explicit is not None:
candidates.append(explicit)
if os.environ.get('NV_RS_NVIDIA_KO'):
candidates.append(Path(os.environ['NV_RS_NVIDIA_KO']))
release = platform.release()
candidates.extend([
Path(f'/lib/modules/{release}/updates/dkms/nvidia.ko'),
Path('/lib/modules/5.15.0-202-generic/updates/dkms/nvidia.ko'),
])
for candidate in candidates:
if candidate.is_file():
return candidate
raise SystemExit('Cannot find installed nvidia.ko; set NV_RS_NVIDIA_KO or pass --nvidia-ko')
def _parse_elf64_sections(raw: bytes):
if len(raw) < 64 or raw[:4] != b'\x7fELF' or raw[4] != 2 or raw[5] != 1:
raise SystemExit('module file is not a valid 64-bit little-endian ELF file')
e_shoff, = struct.unpack_from('<Q', raw, 40)
e_shentsize, e_shnum, e_shstrndx = struct.unpack_from('<HHH', raw, 58)
sh0 = struct.unpack_from('<IIQQQQIIQQ', raw, e_shoff)
if e_shnum == 0:
e_shnum = sh0[5]
if e_shstrndx == 0xFFFF:
e_shstrndx = sh0[6]
hdrs = [struct.unpack_from('<IIQQQQIIQQ', raw, e_shoff + i * e_shentsize) for i in range(e_shnum)]
str_off, str_size = hdrs[e_shstrndx][4], hdrs[e_shstrndx][5]
shstr = raw[str_off:str_off + str_size]
sections = []
by_name = {}
for idx, h in enumerate(hdrs):
nul = shstr.find(b'\x00', h[0])
name = shstr[h[0]:nul if nul != -1 else len(shstr)].decode('utf-8', errors='replace')
sections.append((name, h))
by_name[name] = idx
return sections, by_name
def _load_symbols(raw: bytes, sections, sym_idx: int):
_, h = sections[sym_idx]
entsize = h[9] or 24
str_h = sections[h[6]][1]
strtab = raw[str_h[4]:str_h[4] + str_h[5]]
ext = None
for _, sh in sections:
if sh[1] == 18 and sh[6] == sym_idx:
ext = struct.unpack_from(f'<{sh[5] // 4}I', raw, sh[4])
break
syms = {}
for i in range(h[5] // entsize):
st_name, st_info, _st_other, st_shndx, st_value, st_size = struct.unpack_from('<IBBHQQ', raw, h[4] + i * entsize)
if st_shndx == 0xFFFF and ext is not None and i < len(ext):
st_shndx = ext[i]
nul = strtab.find(b'\x00', st_name)
name = strtab[st_name:nul if nul != -1 else len(strtab)].decode('utf-8', errors='replace')
syms[name] = (st_shndx, st_value, st_size, st_info & 0xF)
return syms
def _load_pt_load_segments(stream) -> list[tuple[int, int, int]]:
ehdr = stream.read(64)
if len(ehdr) < 64 or ehdr[:4] != b'\x7fELF' or ehdr[4] != 2 or ehdr[5] != 1:
raise SystemExit('kcore is not a valid 64-bit little-endian ELF file')
e_phoff, = struct.unpack_from('<Q', ehdr, 32)
e_phentsize, e_phnum = struct.unpack_from('<HH', ehdr, 54)
if e_phoff == 0 or e_phentsize < 56 or e_phnum == 0:
raise SystemExit('kcore has no program headers')
segments = []
stream.seek(e_phoff)
for _ in range(e_phnum):
ph = stream.read(e_phentsize)
if len(ph) < 56:
break
p_type, _p_flags, p_offset, p_vaddr, _p_paddr, p_filesz, _p_memsz, _p_align = struct.unpack_from('<IIQQQQQQ', ph, 0)
if p_type == PT_LOAD:
segments.append((p_vaddr, p_offset, p_filesz))
return segments
def main(argv=None) -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--nvidia-ko', type=Path, default=None)
parser.add_argument('--kcore-dir', type=Path, default=DEFAULT_KCORE_DIR)
args = parser.parse_args(argv)
module_path = find_nvidia_ko(args.nvidia_ko)
kcore_path = args.kcore_dir / 'kcore'
if not kcore_path.is_file():
raise SystemExit(f'cached kcore not found: {kcore_path}')
kallsyms = ROOT / 'reports/original-live-init-pt-3/kallsyms.txt'
lookup = {}
for line in kallsyms.read_text(encoding='utf-8').splitlines():
fields = line.split()
if len(fields) >= 3:
lookup[fields[2]] = int(fields[0], 16)
raw_mod = module_path.read_bytes()
sections, by_name = _parse_elf64_sections(raw_mod)
symbols = _load_symbols(raw_mod, sections, by_name['.symtab'])
text_idx = by_name['.text']
text_h = sections[text_idx][1]
text = raw_mod[text_h[4]:text_h[4] + text_h[5]]
target_fns = ('_nv026844rm', '_nv031217rm', '_nv031215rm')
disk = {}
for name in target_fns:
if name not in symbols or symbols[name][0] != text_idx:
raise SystemExit(f'symbol {name!r} not found in .text of {module_path}')
_, st_value, st_size, _ = symbols[name]
disk[name] = text[st_value:st_value + st_size]
verify_module_matches_capture(raw_mod, sections, by_name, symbols, lookup, target_fns)
assembly = {name: subprocess.check_output(['objdump', '-d', '--disassemble=' + name, str(module_path)], text=True) for name in disk}
with kcore_path.open('rb') as f:
segments = _load_pt_load_segments(f)
rows = []
for stage, name, off, slot, optional in SITES:
ip = lookup[name] + off
ph = next((seg for seg in segments if seg[0] <= ip - 16 and ip + 16 <= seg[0] + seg[2]), None)
if ph is None:
raise SystemExit(f'no PT_LOAD segment covering {stage} ip {hex(ip)}')
p_vaddr, p_offset, _p_filesz = ph
f.seek(p_offset + ip - 16 - p_vaddr)
live = f.read(32)
instruction = live[16:21]
target = ip + 5 + struct.unpack('<i', instruction[1:5])[0] if instruction[0] in (0xE8, 0xE9) else None
rows.append({
'stage': stage, 'symbol': name, 'symbol_offset': hex(off), 'runtime_ip': hex(ip),
'original_rm_text_offset': hex(symbols[name][1] - 0x200D0 + off),
'installed_module_text_offset': hex(symbols[name][1] + off),
'installed_instruction5_hex': disk[name][off:off + 5].hex(),
'cached_runtime_instruction5_hex': instruction.hex(),
'cached_runtime_context32_hex': live.hex(),
'branch_target': hex(target) if target else None,
'target_is_actual_kernel_rax_thunk': target == lookup.get('__x86_indirect_thunk_rax'),
'vtable_slot': hex(slot),
'intr_registers': {
'AX': 'actual immediate method address (RAX)',
'DI': 'GPU owner pointer (RDI)',
'SI': 'actual EngState subobject pointer (RSI)',
'DX': 'load flags for PreLoad/Load; unspecified for Init sites',
},
'optional_callback_route': optional,
'claim': 'A sample at this exact before-dispatch instruction proves attempted immediate method dispatch, not callback completion/status or final HAL body.',
})
report = {
'read_only': True, 'source_module': str(module_path), 'cached_runtime_code': str(kcore_path),
'kallsyms_snapshot': str(kallsyms), 'sites': rows,
'ranges': [{'symbol': n, 'runtime_start': hex(lookup[n]), 'bytes': symbols[n][2]} for n in target_fns],
'functions_assembly': assembly, 'needed_debug_slots': 4,
'three_site_minimum': ['InitLocked', 'PreLoad', 'Load'],
'three_site_omission': 'InitUnlocked is conditionally executed before InitLocked andmustnotbeclaimedcoveredbythree-sitecapture.',
'interpretation': [
'Capture actualAX/DI/SI/DX with exactinstruction-address identities, timestamp,TID,CPU andsampleloss counters.',
'Resolve AX againstmatchingloadedmodule symbols; it maynameanEngState wrapper, notfinalselectedengineHALbody.',
'GPU/engine identities areactualpointervaluesforassociation, notcopy/dereferencecapabilities.',
'Successfulsamplingorder isdispatchattemptorder only. Returnstatus/bodycompletionisnotrecorded.',
'Function-only PT ranges maymisscallee reachedthrough outsidefilter kernelretpolinethunk.',
],
'tracing_changed': False,
}
out = ROOT / 'reports/gpu-engine-dispatch-sites.json'
out.parent.mkdir(parents=True, exist_ok=True)
out.write_text(json.dumps(report, indent=2) + '\n', encoding='utf-8')
print(json.dumps(rows, indent=2))
if __name__ == '__main__':
main()