Files
nvdriver/tools/check_gpu_intr_init_binary.py

370 lines
17 KiB
Python

#!/usr/bin/env python3
"""Run the original GV100 Intr stage bodies and write a comparison oracle.
Executed original code: ConstructEngine _nv037522rm, StatePreInitLocked
_nv037777rm, StateInitLocked _nv037772rm and StateInitUnlocked _nv037773rm,
the binders _nv005896rm, _nv005897rm and _nv005787rm that populate the object,
and the bound functions PreInit reaches through the object: the table
initialiser _nv037667rm (slot 0x320), its entry count _nv037608rm (slot 0x108)
and the vector emptiness test, plus the bit-vector helpers of InitLocked.
The registry, containers, allocation, the GPU child and GPU instance
iterators, other objects' methods, the host table builder _nv037657rm (slot
0x310) and diagnostics are fixture-supplied. No hardware is involved.
"""
import bisect
from _binary_path import resolve_580_binary
import hashlib
import itertools
import json
from pathlib import Path
import struct
from elftools.elf.elffile import ELFFile
from unicorn import UC_ARCH_X86, UC_HOOK_CODE, UC_MODE_64, Uc
from unicorn.x86_const import (UC_X86_REG_RAX, UC_X86_REG_RBP, UC_X86_REG_RCX, UC_X86_REG_RDI,
UC_X86_REG_RDX, UC_X86_REG_RIP, UC_X86_REG_RSI, UC_X86_REG_RSP)
ROOT = Path(__file__).resolve().parents[1]
ORIGINAL = resolve_580_binary()
DIGEST = "5269a23ffba19a17fe16f076463e7ad4151254659441d1711bee6c6221ff6f4b"
TEXT, RODATA, DATA, STACK, STOP = 0x10000000, 0x20000000, 0x30000000, 0x40000000, 0x50000000
GPU, INTR, GMMU, CHILDREN, VTABLE = DATA, DATA + 0x10000, DATA + 0x13000, DATA + 0x14000, DATA + 0x15000
PEERS, PEER_INTRS, CHIP, RM = DATA + 0x20000, DATA + 0x38000, DATA + 0x3c000, DATA + 0x3d000
INDIRECT, REGISTER, GPU_160, ALLOCATOR, HEAP = STOP + 0x100, STOP + 0x200, STOP + 0x300, STOP + 0x400, 0x70000000
TABLE, TABLE_BYTES, CLASS_ID = INTR + 0x450, 0x10c8, 0x2271cc
BODIES = {"C": "_nv037522rm", "P": "_nv037777rm", "I": "_nv037772rm", "U": "_nv037773rm"}
# The binders only store pointers, so the functions they select are listed.
ROOTS = tuple(BODIES.values()) + ("_nv005896rm", "_nv005897rm", "_nv005787rm", "_nv037667rm",
"_nv037608rm")
HOOKED = ("_nv052691rm", "_nv060222rm", "_nv042695rm", "_nv042691rm", "_nv052687rm",
"_nv052701rm", "_nv030645rm", "_nv037657rm", "_nv049786rm", "_nv031415rm",
"_nv031424rm", "_nv047869rm", "_nv046747rm", "_nv046745rm", "_nv052705rm",
"_nv052695rm")
EXPECTED_SLOTS = {0x108: "_nv037608rm", 0x2f8: "_nv037775rm", 0x310: "_nv037657rm",
0x320: "_nv037667rm"}
REGISTRY = ("RMIntrDetailedLogs", "RMDisablePerIntrDPCQueueing", "RMIntrLockingMode", "RM654663")
# State fields in oracle order: (object, offset, bytes).
FIELDS = ([(INTR, 0x3f0, 1), (INTR, 0x3f5, 1), (INTR, 0x3f6, 1), (INTR, 0x448, 4)]
+ [(INTR, 0x1518 + 8 * index, 8) for index in range(5)]
+ [(INTR, 0x1540 + 8 * index, 8) for index in range(5)]
+ [(INTR, 0x1608 + 8 * index, 8) for index in range(7)]
+ [(INTR, 0x1640, 1), (INTR, 0x1668, 8), (INTR, 0x1670, 8), (INTR, 0x1678, 4),
(INTR, 0x1684, 4)]
+ [(INTR, 0x1688 + 8 * index, 8) for index in range(3)]
+ [(INTR, 0x16b8, 4), (INTR, 0x16c8, 4), (INTR, 0x16cc, 1), (GPU, 0xdec, 4),
(GMMU, 0x4a0, 4)])
assert hashlib.sha256(ORIGINAL.read_bytes()).hexdigest() == DIGEST
with ORIGINAL.open("rb") as stream:
elf = ELFFile(stream)
symbols = list(elf.get_section_by_name(".symtab").iter_symbols())
by_name = {symbol.name: symbol for symbol in symbols}
text = bytearray(elf.get_section_by_name(".text").data())
rodata = elf.get_section_by_name(".rodata").data()
text_section, rodata_section = (elf.get_section_index(name) for name in (".text", ".rodata"))
starts = sorted((symbol["st_value"], symbol["st_size"], symbol.name) for symbol in symbols
if symbol["st_shndx"] == text_section and symbol["st_size"])
relocations = sorted((relocation["r_offset"], relocation["r_info_type"],
relocation["r_info_sym"], relocation["r_addend"])
for relocation in elf.get_section_by_name(".rela.text").iter_relocations())
offsets = [entry[0] for entry in relocations]
names = {symbol[0]: symbol[2] for symbol in starts}
executed, pending = [], list(ROOTS)
while pending:
name = pending.pop()
if name in executed or name in HOOKED:
continue
executed.append(name)
start, size = by_name[name]["st_value"], by_name[name]["st_size"]
for offset, kind, index, addend in relocations[bisect.bisect_left(offsets, start):
bisect.bisect_left(offsets, start + size)]:
target = symbols[index]
if target.name == "__x86_indirect_thunk_rax":
address = INDIRECT
elif target["st_shndx"] == rodata_section:
address = RODATA + target["st_value"]
else:
assert target["st_shndx"] == text_section, (name, target.name)
address = TEXT + target["st_value"]
# Follow direct calls and tail calls only, not stored pointers.
if kind in (2, 4) and text[offset - 1] in (0xe8, 0xe9):
callee = names.get(target["st_value"] + addend + 4)
if callee and callee not in HOOKED:
pending.append(callee)
value = address + addend
if kind in (2, 4):
value -= TEXT + offset
else:
assert kind == 11, kind
struct.pack_into("<i", text, offset, value)
cpu = Uc(UC_ARCH_X86, UC_MODE_64)
for address, data in ((TEXT, bytes(text)), (RODATA, bytes(rodata))):
cpu.mem_map(address, (len(data) + 4095) & ~4095)
cpu.mem_write(address, data)
for address, size in ((DATA, 0x40000), (STACK, 0x10000), (STOP, 0x1000)):
cpu.mem_map(address, size)
case, trace = {}, []
def leave(emu, value=0):
rsp = emu.reg_read(UC_X86_REG_RSP)
emu.reg_write(UC_X86_REG_RSP, rsp + 8)
emu.reg_write(UC_X86_REG_RAX, value)
emu.reg_write(UC_X86_REG_RIP, struct.unpack("<Q", emu.mem_read(rsp, 8))[0])
def u32(emu, address):
return struct.unpack("<I", emu.mem_read(address, 4))[0]
def leaf(name):
def run(emu, address, size, unused):
a, b, c, d = (emu.reg_read(register) for register in (
UC_X86_REG_RDI, UC_X86_REG_RSI, UC_X86_REG_RDX, UC_X86_REG_RCX))
low_b, low_c, low_d = b & 0xffffffff, c & 0xffffffff, d & 0xffffffff
value = 0
if name == "_nv052691rm":
value = ALLOCATOR
elif name == "_nv060222rm":
assert b == ALLOCATOR
trace.append(f"vi:{a - INTR:x}:{low_c:x}:{low_d:x}")
value = case["vector"].pop(0)
elif name == "_nv042695rm":
assert b == ALLOCATOR
trace.append(f"li:{a - INTR:x}:{low_c:x}")
elif name == "_nv042691rm":
trace.append(f"lc:{a - INTR:x}")
elif name == "_nv052701rm":
trace.append(f"f:{a - HEAP if a else 0:x}")
elif name == "_nv030645rm":
assert (a, low_c) == (GPU, CLASS_ID)
cursor = u32(emu, b)
trace.append(f"n:{cursor:x}")
slot = next((slot for slot in case["children"] if slot >= cursor), None)
emu.mem_write(b, struct.pack("<I", 0xbb if slot is None else slot + 1))
value = 0 if slot is None else CHILDREN + slot * 0x10
elif name == "_nv037657rm":
assert (a, b, c) == (GPU, INTR, INTR + 0x430)
trace.append(f"t310:{low_d:x}")
value = case["table"]
elif name == "_nv049786rm":
assert a == GPU
key = bytes(emu.mem_read(b, 32)).split(b"\0")[0].decode()
ok, word = case["registry"][key]
trace.append(f"reg:{key}")
if ok:
emu.mem_write(c, struct.pack("<I", word))
value = 0 if ok else 0x57
elif name == "_nv031415rm":
assert a == GPU
trace.append("mask")
value = case["mask"]
elif name == "_nv031424rm":
mask, cursor = a & 0xffffffff, u32(emu, b)
trace.append(f"ng:{mask:x}:{cursor:x}")
bit = next((bit for bit in range(cursor, 32) if mask >> bit & 1), None)
emu.mem_write(b, struct.pack("<I", 0x20 if bit is None else bit + 1))
value = 0 if bit is None else PEERS + bit * 0x3000
elif name == "_nv047869rm":
trace.append(f"p:{low_b >> 16:x}:{low_c:x}")
elif name == "_nv046747rm":
trace.append(f"a:{low_b:x}:{a & 0xffffffff:x}")
elif name == "_nv052705rm":
emu.mem_write(a, bytes([b & 0xff]) * low_c)
value = a
elif name == "_nv052695rm":
emu.mem_write(a, bytes(emu.mem_read(c, low_d)))
value = a
else:
raise AssertionError(f"{name} must not be reached")
leave(emu, value)
return run
def thunk(emu, address, size, unused):
target = emu.reg_read(UC_X86_REG_RAX)
a, b, c = (emu.reg_read(r) for r in (UC_X86_REG_RDI, UC_X86_REG_RSI, UC_X86_REG_RDX))
if target == REGISTER:
assert (a, c) == (GPU, TABLE)
slot = (b - CHILDREN) // 0x10
trace.append(f"r:{slot:x}")
emu.mem_write(TABLE + slot, bytes([slot + 1]))
leave(emu)
elif target == GPU_160:
assert (a, b) == (GPU, TABLE)
trace.append("g160")
emu.mem_write(TABLE + TABLE_BYTES - 1, b"\xee")
leave(emu)
else:
assert TEXT <= target < TEXT + len(text), hex(target)
emu.reg_write(UC_X86_REG_RIP, target)
cpu.hook_add(UC_HOOK_CODE, thunk, begin=INDIRECT, end=INDIRECT)
for hooked in HOOKED:
entry = TEXT + by_name[hooked]["st_value"]
cpu.hook_add(UC_HOOK_CODE, leaf(hooked), begin=entry, end=entry)
def call(name, *arguments):
for register, argument in zip((UC_X86_REG_RDI, UC_X86_REG_RSI, UC_X86_REG_RDX), arguments):
cpu.reg_write(register, argument)
rsp = STACK + 0xffc8
cpu.reg_write(UC_X86_REG_RSP, rsp)
cpu.reg_write(UC_X86_REG_RBP, STACK + 0x8000)
cpu.mem_write(rsp, struct.pack("<Q", STOP))
cpu.emu_start(TEXT + by_name[name]["st_value"], STOP, count=200000)
assert cpu.reg_read(UC_X86_REG_RIP) == STOP, name
return cpu.reg_read(UC_X86_REG_RAX) & 0xffffffff
cpu.mem_write(CHIP + 0x10, struct.pack("<H", 0x23))
cpu.mem_write(RM + 0x10, struct.pack("<H", 2))
call("_nv005896rm", INTR, CHIP, RM)
call("_nv005897rm", INTR, CHIP, RM)
call("_nv005787rm", INTR, CHIP)
bound = {f"{slot:#x}": names[struct.unpack("<Q", cpu.mem_read(INTR + slot, 8))[0] - TEXT]
for slot in EXPECTED_SLOTS}
assert bound == {f"{slot:#x}": name for slot, name in EXPECTED_SLOTS.items()}, bound
property_3f7 = cpu.mem_read(INTR + 0x3f7, 1)[0]
assert property_3f7 == 1
# StateLoad is the constant-zero body bound at slot 0x2f8.
assert call("_nv037775rm", GPU, INTR) == 0
# Every byte past the function table starts as 0x77 so untouched fields show.
cpu.mem_write(INTR + 0x3f0, b"\x77" * (0x2000 - 0x3f0))
bound_object = bytes(cpu.mem_read(INTR, 0x2000))
branches = {}
def seen(key):
branches[key] = branches.get(key, 0) + 1
def run(kind, inputs, gmmu=True, children=(), extra=lambda: ()):
trace.clear()
cpu.mem_write(DATA, bytes(0x10000))
cpu.mem_write(INTR, bound_object)
cpu.mem_write(GMMU, b"\x77" * 0x1000)
cpu.mem_write(PEER_INTRS, b"\x77" * 0x4000)
cpu.mem_write(GPU + 0xdec, b"\x77" * 4)
cpu.mem_write(GPU + 0x160, struct.pack("<Q", GPU_160))
cpu.mem_write(GPU + 0x1f90, struct.pack("<Q", GMMU if gmmu else 0))
cpu.mem_write(VTABLE + 0x18, struct.pack("<Q", REGISTER))
for slot in range(0xbb):
cpu.mem_write(CHILDREN + slot * 0x10, struct.pack("<Q", VTABLE))
for bit in range(8):
cpu.mem_write(PEERS + bit * 0x3000 + 0x2110, struct.pack("<Q", PEER_INTRS + bit * 0x400))
case["children"] = children
yield
status = call(BODIES[kind], GPU, INTR)
state = [int.from_bytes(cpu.mem_read(base + offset, size), "little")
for base, offset, size in FIELDS]
rows.append(kind + " " + " ".join(f"{value:x}" for value in inputs) + ";"
+ " ".join(f"{value:x}" for value in [status] + state) + ";"
+ " ".join(f"{value:x}" for value in extra()) + ";" + " ".join(trace))
yield status
def finish(steps):
return next(steps)
rows = []
for first, second in ((0, 0), (0, 0x51), (0, 0x1f), (0x51, 0), (0x1f, 0)):
steps = run("C", (first, second))
next(steps)
case["vector"] = [first, second]
status = finish(steps)
seen("construct: first vector init failed" if first else
"construct: second vector init failed" if second else "construct: success")
assert status == (first or second)
CHILD_SETS = ((), (5,), (0, 0x21, 0xba))
MASKS = (0, 1, 4, 0x10, 0x1f)
for pointers, counts, length, table, children in itertools.product(
MASKS, MASKS, (0, 3), (0, 0x40, 0x65), CHILD_SETS):
steps = run("P", (pointers, counts, length, table) + children, children=children,
extra=lambda: (sum(1 for byte in cpu.mem_read(TABLE, TABLE_BYTES) if byte),
sum(cpu.mem_read(TABLE, TABLE_BYTES))))
next(steps)
case["table"] = table
for index in range(5):
cpu.mem_write(INTR + 0x1518 + 8 * index, struct.pack(
"<Q", HEAP + 0xa0 + index if pointers >> index & 1 else 0))
cpu.mem_write(INTR + 0x1540 + 8 * index, struct.pack(
"<Q", 9 + index if counts >> index & 1 else 0))
cpu.mem_write(INTR + 0x448, struct.pack("<I", length))
status = finish(steps)
if pointers or counts:
seen("pre-init: stale subtree array or count")
assert status == 0x40
elif length:
seen("pre-init: interrupt table not empty")
assert status == 0x40
elif table:
seen("pre-init: slot 0x310 failed")
assert status == table
else:
seen(f"pre-init: success with {len(children)} interrupt services")
assert status == 0
for byte_3f6, gmmu in itertools.product((0, 1, 0x77), (0, 1)):
steps = run("I", (byte_3f6, gmmu), gmmu=bool(gmmu))
next(steps)
cpu.mem_write(INTR + 0x3f6, bytes([byte_3f6]))
assert finish(steps) == 0
seen("init-locked: mask locking " + ("on" if byte_3f6 else "off")
+ (", GMMU present" if gmmu else ", GMMU absent"))
READS = {
REGISTRY[0]: ((0, 0), (1, 0), (1, 1), (1, 2)),
REGISTRY[1]: ((0, 0, 0), (1, 0, 0), (1, 1, 0), (1, 1, 1), (1, 1, 9), (1, 0x80000000, 9)),
REGISTRY[2]: ((0, 0), (1, 0), (1, 1), (1, 2)),
REGISTRY[3]: ((0, 0), (1, 0), (1, 0x1234)),
}
for detailed, queueing, locking, stuck, byte_3f7, byte_e00 in itertools.product(
READS[REGISTRY[0]], READS[REGISTRY[1]], READS[REGISTRY[2]], READS[REGISTRY[3]],
(0, 1), (0, 1)):
mask = queueing[2]
steps = run("U", detailed + queueing[:2] + locking + stuck + (byte_3f7, byte_e00, mask),
extra=lambda: (sum(1 << bit for bit in range(8)
if cpu.mem_read(PEER_INTRS + bit * 0x400 + 0x3f5, 1)[0] == 1),))
next(steps)
case["registry"] = dict(zip(REGISTRY, (detailed, queueing[:2], locking, stuck)))
case["mask"] = mask
cpu.mem_write(INTR + 0x3f7, bytes([byte_3f7]))
cpu.mem_write(GPU + 0xe00, bytes([byte_e00]))
assert finish(steps) == 0
seen("init-unlocked: detailed logs " + ("set" if detailed == (1, 1) else "left"))
seen("init-unlocked: per-interrupt queueing "
+ (f"disabled on {bin(mask).count('1')} GPUs" if queueing[0] and queueing[1] else "left"))
seen("init-unlocked: default mask locking " + ("on" if byte_3f7 and not byte_e00 else "off"))
seen("init-unlocked: locking mode " + ("absent" if not locking[0] else
"1, supported" if locking[1] == 1 and byte_3f7 else
"1, unsupported" if locking[1] == 1 else "other"))
seen("init-unlocked: stuck threshold " + ("registry" if stuck[0] else "default"))
out = ROOT / "target/gpu-stage"
out.mkdir(parents=True, exist_ok=True)
oracle = "\n".join(rows) + "\n"
(out / "original-intr-init.txt").write_text(oracle)
report = {"original_sha256": DIGEST, "chip_hal": "0x23", "rm_hal": 2,
"executed": sorted(executed),
"fixture_supplied": list(HOOKED) + ["GPU+0x160", "IntrService vtable+0x18",
"memory copy and fill are performed as such"],
"bindings": bound, "hal_property_0x3f7": property_3f7,
"state_load_0x2f8_returns": 0, "cases": len(rows),
"cases_per_body": {BODIES[kind]: sum(1 for row in rows if row[0] == kind)
for kind in BODIES},
"branches": dict(sorted(branches.items())),
"oracle": "target/gpu-stage/original-intr-init.txt",
"oracle_sha256": hashlib.sha256(oracle.encode()).hexdigest(),
"scope": "Original GV100 Intr ConstructEngine, StatePreInitLocked (through the "
"binder-selected table initialiser), StateInitLocked and StateInitUnlocked. "
"The registry, containers, allocation, iterators, other objects' methods, "
"the host table builder and diagnostics are fixture-supplied; no hardware "
"executed."}
(ROOT / "reports/gpu-intr-init-original.json").write_text(json.dumps(report, indent=2) + "\n")
print(f"{len(rows)} original Intr init cases; executed {len(executed)} functions")