Files
nvdriver/tools/gpu_error_policy_table.py

147 lines
5.9 KiB
Python

#!/usr/bin/env python3
"""Recover the exact original status-table row used by error-init group10."""
import argparse
import hashlib
import json
import os
from pathlib import Path
import struct
ROOT = Path(__file__).resolve().parent.parent
EXPECTED_SHA256 = '5269a23ffba19a17fe16f076463e7ad4151254659441d1711bee6c6221ff6f4b'
DEFAULT_ANALYSIS_ROOT = Path('/home/geodd/nvidia-driver/analysis-580.178.04')
def find_rm_object() -> Path:
candidates = []
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 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('--check', action='store_true', help='fail if report differs')
args = parser.parse_args(argv)
source = find_rm_object()
raw_elf = source.read_bytes()
sha = hashlib.sha256(raw_elf).hexdigest()
if sha != EXPECTED_SHA256:
raise SystemExit(f'{source}: sha256 mismatch ({sha} != {EXPECTED_SHA256})')
sections, by_name = parse_elf64(raw_elf)
syms = load_symbols(raw_elf, sections, by_name['.symtab'])
function = next((s for s in syms if s[0] == '_nv031134rm'), None)
if function is None:
raise SystemExit('symbol _nv031134rm not found')
rel_h = sections[by_name['.rela.text']][1]
rel_entsize = rel_h[9] or 24
target_rel = None
want_off = function[2] + 0x5A
for i in range(rel_h[5] // rel_entsize):
r_offset, r_info, r_addend = struct.unpack_from('<QQq', raw_elf, rel_h[4] + i * rel_entsize)
if r_offset == want_off:
target_rel = (r_info >> 32, r_addend)
break
if target_rel is None:
raise SystemExit(f'missing relocation at _nv031134rm+0x5a (0x{want_off:x})')
r_sym, r_addend = target_rel
target = syms[r_sym]
sec_name, sec_h = sections[target[1]]
if sec_name != '.data':
raise SystemExit(f'unexpected target section {sec_name!r} != .data')
sec_data = raw_elf[sec_h[4]:sec_h[4] + sec_h[5]]
offset = target[2] + r_addend
rows = [struct.unpack_from('<6I', sec_data, offset + i * 24) for i in range(32)]
matches = [(i, row) for i, row in enumerate(rows) if row[0] == 10]
if matches != [(10, (10, 0, 8, 3, 0, 0))]:
raise SystemExit(f'unexpected group10 error policy row: {matches}')
report = {
'source_sha256': sha,
'source_function': '_nv031134rm',
'original_text_relocation_offset': hex(want_off),
'relative_function_relocation_offset': '0x5a',
'section': '.data',
'table_offset': hex(offset),
'record_bytes': 24,
'rows': [list(row) for row in rows],
'selected_group': 10,
'selected_row': list(matches[0][1]),
'gpu_word_offset': '0x6d90',
'rust_update': '(old & !0x300) | 0x100',
'limits': 'Only the exact group10 / sentinelb33b1500 / value1 call is implemented; other groups still require their actual state owners.',
}
out = ROOT / 'reports/gpu-gv100-error-policy-table.json'
payload = json.dumps(report, indent=2) + '\n'
if args.check:
if not out.is_file() or out.read_text(encoding='utf-8') != payload:
raise SystemExit('Stale ' + str(out))
else:
out.parent.mkdir(parents=True, exist_ok=True)
out.write_text(payload, encoding='utf-8')
print('Original relocation-backed group10 row verified:', matches[0])
if __name__ == '__main__':
main()