mirror of
https://github.com/QuixiAI/nvdriver.git
synced 2026-12-06 06:28:39 +00:00
- 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.
362 lines
17 KiB
Python
362 lines
17 KiB
Python
#!/usr/bin/env python3
|
|
"""Label observed immediate EngState callbacks through original NVOC metadata.
|
|
Read-only inputs; generates evidence, never samples or edits driver production.
|
|
"""
|
|
import argparse
|
|
from collections import Counter, defaultdict
|
|
import hashlib
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import re
|
|
import struct
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
EXPECTED_SHA256 = '5269a23ffba19a17fe16f076463e7ad4151254659441d1711bee6c6221ff6f4b'
|
|
EXPECTED_RELEASE = '580.178.04'
|
|
DEFAULT_ANALYSIS_ROOT = Path.home() / 'nvidia-driver/analysis-580.178.04'
|
|
SLOTS = {'InitLocked': 0x50, 'InitUnlocked': 0x58, 'PreLoad': 0x60, 'Load': 0x68}
|
|
NOOPS = {'_nv026842rm', '_nv026845rm', '_nv026851rm'}
|
|
|
|
|
|
def find_rm_object(explicit: Path | None = None) -> Path:
|
|
candidates = []
|
|
if explicit is not None:
|
|
candidates.append(explicit)
|
|
if os.environ.get('NV_RS_RM_OBJECT'):
|
|
candidates.append(Path(os.environ['NV_RS_RM_OBJECT']))
|
|
if os.environ.get('NV_RS_KERNEL_SRC'):
|
|
base = Path(os.environ['NV_RS_KERNEL_SRC'])
|
|
candidates.extend([base / 'nvidia/nv-kernel.o_binary', base])
|
|
analysis = Path(os.environ.get('NV_RS_ANALYSIS_ROOT', str(DEFAULT_ANALYSIS_ROOT)))
|
|
candidates.append(analysis / 'extracted/kernel/nvidia/nv-kernel.o_binary')
|
|
candidates.extend([
|
|
Path('/usr/src/nvidia-580.178.04/nvidia/nv-kernel.o_binary'),
|
|
Path('/usr/src/nvidia-srv-580.178.04/nvidia/nv-kernel.o_binary'),
|
|
])
|
|
for candidate in candidates:
|
|
if candidate.is_file():
|
|
return candidate
|
|
raise SystemExit('Cannot find 580.178.04 nv-kernel.o_binary; set NV_RS_RM_OBJECT or NV_RS_KERNEL_SRC')
|
|
|
|
|
|
def detect_open_gpu_release(gen_dir: Path) -> str | None:
|
|
"""Inspect parent directories of a generated/ dir for NVIDIA open-gpu-kernel-modules release metadata."""
|
|
cur = gen_dir.resolve()
|
|
for _ in range(5):
|
|
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_generated_dir(explicit: Path | None = None, expected_release: str = EXPECTED_RELEASE) -> Path | None:
|
|
if explicit is not None:
|
|
if not explicit.is_dir():
|
|
raise SystemExit(f'generated directory not found: {explicit}')
|
|
detected = detect_open_gpu_release(explicit)
|
|
if detected != expected_release:
|
|
raise SystemExit(
|
|
f'generated source tree release mismatch at {explicit}: expected {expected_release!r}, detected {detected!r}'
|
|
)
|
|
return explicit
|
|
candidates = []
|
|
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/nvidia/generated', base / 'nvidia/generated', 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/nvidia/generated')
|
|
for candidate in candidates:
|
|
if candidate.is_dir() and detect_open_gpu_release(candidate) == expected_release:
|
|
return candidate
|
|
return None
|
|
|
|
|
|
def _parse_elf64(raw: bytes):
|
|
if len(raw) < 64 or raw[:4] != b'\x7fELF' or raw[4] != 2 or raw[5] != 1:
|
|
raise SystemExit('nv-kernel.o_binary 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.append((name, st_shndx, st_value, st_size, st_info & 0xF))
|
|
return syms
|
|
|
|
|
|
def main(argv=None) -> None:
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument('--rm-object', type=Path, default=None)
|
|
parser.add_argument('--generated-dir', type=Path, default=None)
|
|
args = parser.parse_args(argv)
|
|
|
|
rm_obj = find_rm_object(args.rm_object)
|
|
raw_elf = rm_obj.read_bytes()
|
|
sha = hashlib.sha256(raw_elf).hexdigest()
|
|
if sha != EXPECTED_SHA256:
|
|
raise SystemExit(f'{rm_obj}: sha256 mismatch ({sha} != {EXPECTED_SHA256})')
|
|
|
|
dispatch_path = ROOT / 'reports/original-live-init-bp-4/timestamped-dispatch.json'
|
|
cap = json.loads(dispatch_path.read_text(encoding='utf-8'))
|
|
events = [x for x in cap['events'] if x['gpu_ordinal'] == 0]
|
|
if len(events) != 257:
|
|
raise SystemExit(f'expected 257 gpu_ordinal==0 events, found {len(events)}')
|
|
|
|
labels = defaultdict(list)
|
|
gen_dir = find_generated_dir(args.generated_dir)
|
|
if gen_dir is not None:
|
|
for p in sorted(gen_dir.glob('*_nvoc.h')):
|
|
for line, s in enumerate(p.read_text(encoding='utf-8', errors='replace').splitlines(), 1):
|
|
m = re.match(r'#define __nvoc_class_id_(\w+) (0x[0-9a-fA-F]+)', s)
|
|
if m:
|
|
labels[int(m[2], 16)].append({'class_name': m[1], 'source_file': str(p), 'line': line})
|
|
|
|
def choose_label(cid):
|
|
choices = labels[cid]
|
|
canonical = [x for x in choices if Path(x['source_file']).name == 'g_eng_desc_nvoc.h']
|
|
return canonical or choices[:1]
|
|
|
|
sections, by_name = _parse_elf64(raw_elf)
|
|
ss = _load_symbols(raw_elf, sections, by_name['.symtab'])
|
|
byname = {s[0]: (i, s) for i, s in enumerate(ss)}
|
|
roidx = by_name['.rodata']
|
|
ro_h = sections[roidx][1]
|
|
ro = raw_elf[ro_h[4]:ro_h[4] + ro_h[5]]
|
|
|
|
rel_h = sections[by_name['.rela.rodata']][1]
|
|
rel_entsize = rel_h[9] or 24
|
|
rels = {}
|
|
refs = defaultdict(list)
|
|
for i in range(rel_h[5] // rel_entsize):
|
|
off, r_info, r_addend = struct.unpack_from('<QQq', raw_elf, rel_h[4] + i * rel_entsize)
|
|
r_sym = r_info >> 32
|
|
rels[off] = (r_sym, r_addend)
|
|
refs[r_sym].append(off)
|
|
|
|
def target(off):
|
|
rel = rels.get(off)
|
|
return ss[rel[0]] if rel is not None else None
|
|
|
|
def ro_target(off):
|
|
rel = rels.get(off)
|
|
if rel is None:
|
|
return None
|
|
s = ss[rel[0]]
|
|
return s[2] + rel[1] if s[1] == roidx else None
|
|
|
|
owners = defaultdict(list)
|
|
for owner in ss:
|
|
if owner[1] != roidx or owner[4] != 1 or owner[3] != 40: # STT_OBJECT == 1
|
|
continue
|
|
cast = ro_target(owner[2] + 0x18)
|
|
if cast is None or cast + 8 > len(ro):
|
|
continue
|
|
count = struct.unpack_from('<I', ro, cast)[0]
|
|
if not (0 < count < 32):
|
|
continue
|
|
relatives = [ro_target(cast + 8 + i * 8) for i in range(count)]
|
|
if any(x is None for x in relatives):
|
|
continue
|
|
roots = [
|
|
x for x in relatives
|
|
if (t := target(x)) is not None and t[0] == owner[0] and struct.unpack_from('<I', ro, x + 16)[0] == 0
|
|
]
|
|
if len(roots) != 1:
|
|
continue
|
|
for base in relatives:
|
|
ancestor = target(base)
|
|
if ancestor is not None and ancestor[0] == '_nv003100rm':
|
|
owners[base].append((owner, roots[0], cast, relatives))
|
|
|
|
methods = {}
|
|
class_catalog = {}
|
|
|
|
def candidates(name, slot):
|
|
answer = []
|
|
for off in refs[byname[name][0]]:
|
|
base = off - slot
|
|
for owner, root, cast, relatives in owners[base]:
|
|
cid = struct.unpack_from('<I', ro, owner[2] + 4)[0]
|
|
key = hex(cid)
|
|
ancestor_ids = []
|
|
for relative in relatives:
|
|
ancestor = target(relative)
|
|
if ancestor is not None and ancestor[4] == 1:
|
|
ancestor_ids.append(hex(struct.unpack_from('<I', ro, ancestor[2] + 4)[0]))
|
|
class_catalog[key] = {
|
|
'class_id': key,
|
|
'binary_class_definition': owner[0],
|
|
'class_definition_rodata_offset': hex(owner[2]),
|
|
'class_id_field_offset': 4,
|
|
'source_labels': choose_label(cid),
|
|
'ancestor_class_ids': ancestor_ids,
|
|
}
|
|
answer.append({
|
|
'class_id': key,
|
|
'metadata_engstate_rodata_offset': hex(base),
|
|
'callback_relocation_rodata_offset': hex(off),
|
|
'root_rtti_rodata_offset': hex(root),
|
|
'castinfo_rodata_offset': hex(cast),
|
|
'castinfo_num_relatives': len(relatives),
|
|
'engstate_subobject_offset': struct.unpack_from('<I', ro, base + 16)[0],
|
|
})
|
|
return answer
|
|
|
|
for ev in events:
|
|
name = ev['callback']['name']
|
|
stage = ev['stage']
|
|
key = name + ':' + stage
|
|
if key in methods:
|
|
continue
|
|
if ev['callback']['offset'] != '0x0':
|
|
raise SystemExit(f'unexpected non-zero callback offset {ev["callback"]["offset"]!r} for {key}')
|
|
methods[key] = {
|
|
'symbol': name,
|
|
'stage': stage,
|
|
'vtable_slot': hex(SLOTS[stage]),
|
|
'shared_default_noop': name in NOOPS,
|
|
'candidates': candidates(name, SLOTS[stage]),
|
|
}
|
|
|
|
engines = []
|
|
for ordinal in range(78):
|
|
selected = [ev for ev in events if ev['engine_ordinal'] == ordinal]
|
|
engine_owners = {x['engine_owner'] for x in selected}
|
|
if len(engine_owners) != 1:
|
|
raise SystemExit(f'engine ordinal {ordinal} has {len(engine_owners)} distinct owners')
|
|
matching = None
|
|
for ev in selected:
|
|
keys = {x['class_id'] for x in methods[ev['callback']['name'] + ':' + ev['stage']]['candidates']}
|
|
matching = keys if matching is None else matching & keys
|
|
matching = sorted(matching or [])
|
|
declarations = [d for cid in matching for d in class_catalog[cid]['source_labels']]
|
|
name = declarations[0]['class_name'] if len(matching) == 1 and len({d['class_name'] for d in declarations}) == 1 else None
|
|
engines.append({
|
|
'engine_ordinal0': ordinal,
|
|
'gpu_owner': selected[0]['gpu_owner'],
|
|
'engine_owner': next(iter(engine_owners)),
|
|
'class_label': name,
|
|
'phase_positions0': {phase: order.index(ordinal) for phase, order in cap['gpu_groups'][0]['engine_orders'].items() if ordinal in order},
|
|
'class_candidate_ids': matching,
|
|
'class_label_evidence': 'intersection of actual callback-slot original metadata classes whose ClassDef CastInfo owns SAME EngStateRTTI; capturedSI matches across phases; no live classID read',
|
|
'callbacks': {
|
|
ev['stage']: {
|
|
'symbol': ev['callback']['name'],
|
|
'callback_address': ev['callback_address'],
|
|
'sample': ev['sample'],
|
|
'source_line': ev['source_line'],
|
|
'method_evidence': ev['callback']['name'] + ':' + ev['stage'],
|
|
'shared_default_noop': ev['callback']['name'] in NOOPS,
|
|
}
|
|
for ev in selected
|
|
},
|
|
})
|
|
|
|
# Compare capture1 actual AX sequences/owner grouping without comparing heap addresses.
|
|
raw_path = ROOT / 'reports/original-live-init-bp-4/standalone-dispatch-registers.txt'
|
|
raw_rows = []
|
|
for line in raw_path.read_text(encoding='utf-8').splitlines():
|
|
m = re.search(r'mem:(0x[0-9a-f]+):x:.*AX:(0x[0-9a-f]+).*DX:(0x[0-9a-f]+).*SI:(0x[0-9a-f]+).*DI:(0x[0-9a-f]+)', line)
|
|
if m:
|
|
raw_rows.append(m.groups())
|
|
if not raw_rows:
|
|
raise SystemExit(f'no register rows parsed from {raw_path}')
|
|
first_gpu = raw_rows[0][-1]
|
|
first = [x for x in raw_rows if x[-1] == first_gpu]
|
|
if len(first) != 257:
|
|
raise SystemExit(f'expected 257 capture1 rows for first GPU, found {len(first)}')
|
|
repeat = [(x[0], x[1]) for x in first] == [(ev['site'], ev['callback_address']) for ev in events]
|
|
|
|
used_sources = {d['source_file'] for c in class_catalog.values() for d in c['source_labels']}
|
|
source_hashes = {p: hashlib.sha256(Path(p).read_bytes()).hexdigest() for p in sorted(used_sources)}
|
|
report = {
|
|
'schema': 1,
|
|
'scope': 'Observed immediate callback attempts for first GPU group. Exact580 generated-source names label original binary classIDs only; no final HAL body/completion claim.',
|
|
'inputs': {
|
|
str(dispatch_path.relative_to(ROOT)): hashlib.sha256(dispatch_path.read_bytes()).hexdigest(),
|
|
str(raw_path.relative_to(ROOT)): hashlib.sha256(raw_path.read_bytes()).hexdigest(),
|
|
'original_rm_sha256': sha,
|
|
},
|
|
'ordinal_convention': 'engine_ordinal0 isZEROBASED and matches timestamped-dispatch.json engine_ordinal; not1-based position',
|
|
'sample_clock': cap['sample_clock'],
|
|
'input_revision': json.loads((ROOT / 'reports/gpu-live-engine-labels-revision.json').read_text(encoding='utf-8')),
|
|
'first_gpu_owner': events[0]['gpu_owner'],
|
|
'first_gpu_samples': 257,
|
|
'stage_counts': dict(Counter(x['stage'] for x in events)),
|
|
'capture1_callback_order_repeats_capture2': repeat,
|
|
'engine_count': 78,
|
|
'source_named_engines': sum(x['class_label'] is not None for x in engines),
|
|
'ambiguous_or_undeclared_engines': [x['engine_ordinal0'] for x in engines if x['class_label'] is None],
|
|
'engines': engines,
|
|
'phase_orders': cap['gpu_groups'][0]['engine_orders'],
|
|
'ordered_attempts': [
|
|
{'sample': x['sample'], 'perf_time_ns': x['perf_time_ns'], 'stage': x['stage'], 'engine_ordinal0': x['engine_ordinal'], 'callback': x['callback']['name']}
|
|
for x in events
|
|
],
|
|
'method_catalog': methods,
|
|
'class_catalog': class_catalog,
|
|
'label_source_hashes': source_hashes,
|
|
'limitations': [
|
|
'No live classID/object memory dereference. Shared callback/noop mappings remain ambiguous unless other captured methods for SAME SI narrow the class.',
|
|
'Unknown binary classIDs without exact generated-source declaration remain numeric, unnamed. In particular ordinal38 class5dfed5 has Pmu ancestor but must not be labeled the base Pmu class.',
|
|
'Labels are classes consistent with the observed original metadata; no class name inferred from ordinal, method number or neighboring class.',
|
|
'CapturedRAX is the immediate wrapper/default method, not proof of final HAL target, completion, result status, authentication or hardware readiness.',
|
|
'Capture1 has no printed timestamps; primaryorder uses capture2 timestamped events and compares capture1 actual site+AX sequence.',
|
|
],
|
|
'read_only': True,
|
|
'tracing_changed': False,
|
|
'production_changed': False,
|
|
}
|
|
out = ROOT / 'reports/gpu-live-engine-labels.json'
|
|
out.parent.mkdir(parents=True, exist_ok=True)
|
|
out.write_text(json.dumps(report, indent=2) + '\n', encoding='utf-8')
|
|
print('Named', report['source_named_engines'], 'of78; unresolved', report['ambiguous_or_undeclared_engines'], 'repeat', repeat)
|
|
|
|
|
|
if __name__ == '__main__':
|
|
main()
|