mirror of
https://github.com/QuixiAI/nvdriver.git
synced 2026-12-06 06:28:39 +00:00
- Updated tools/post_reboot.sh to check kernel oops taint bit and stuck driver tasks instead of <86400s uptime - Level 7 hardware regression passed on 0000:b3:00.0 (module 37e6fa430835eee2b426019db3ad70eeb7a9e9070c09c84bd9b973cf56cbe529, 107 inventory words, 0 static mismatches, CUDA baseline verified before and after) - Updated .gitignore to exclude build archives (*.a, *.rlib), __pycache__, and raw trace dumps
730 lines
33 KiB
Python
730 lines
33 KiB
Python
#!/usr/bin/env python3
|
|
"""Run the original GV100 KernelBus InitLocked BAR2 bring-up and write an oracle.
|
|
|
|
Executed original code: the kernel half of KernelBus InitLocked, _nv039592rm
|
|
(called by the class body _nv039595rm before KernelBus+110 _nv039594rm), with
|
|
everything it calls directly or through the function tables the original
|
|
binders fill in: the default PRAMIN window (KernelBus+3e0 _nv039556rm), BAR2
|
|
initialization _nv039463rm (+1d0 CPU aperture _nv039563rm, +140 GPU VA space
|
|
_nv039566rm, +178 commit _nv039325rm), the page-level walker (_nv046237rm
|
|
create, _nv046252rm reserve, _nv046260rm sparsify, _nv046247rm map) with the
|
|
BAR2 walker callbacks of table _nv029065rm (_nv012114rm level allocation,
|
|
_nv012116rm root update, _nv012117rm directory entry, _nv012113rm fill), the
|
|
instance block writer (+428 _nv039472rm), the PRAMIN accessor _nv039504rm, the
|
|
bind _nv039307rm, the aperture update _nv039638rm with its entry callback
|
|
_nv013924rm, the flush _nv039553rm/_nv018613rm and _nv039391rm/_nv039387rm, the
|
|
invalidate _nv040843rm with _nv040639rm, _nv040663rm and _nv040941rm, the flush
|
|
pointer setup _nv039577rm and the BAR2 test _nv039656rm. The reserved-memory
|
|
placement of the page levels, _nv044075rm, runs first and supplies the
|
|
relative directory and table offsets. The whole object file is loaded and
|
|
relocated, so no callee is selected by hand; the KernelBus, KernelGmmu,
|
|
MemoryManager, KernelMemorySystem and OBJBUS tables come from running their
|
|
original binders with chip HAL 0x23 and RM HAL 2, and the page-table format
|
|
from the original constructor steps (_nv040763rm, _nv040773rm, the KernelGmmu
|
|
functions at +1c0, +1a8, +1a0, +188, _nv040782rm and +1c8).
|
|
|
|
Fixture-supplied: register access (_nv053907rm, _nv053912rm) backed by a
|
|
model of the PRAMIN window and of framebuffer words, the BAR2 CPU mapping
|
|
(translated through the page tables the original just wrote), allocation,
|
|
memory fill and copy, diagnostics, the timeout functions (_nv059509rm start,
|
|
_nv059505rm check, _nv059492rm thread reset), the multi-GPU loop helpers
|
|
(_nv031390rm, _nv031395rm, _nv031424rm, _nv031426rm, _nv031478rm,
|
|
_nv031482rm), the calling-context query _nv060459rm, the device ownership
|
|
helper _nv014074rm, the PCI mapping _nv049745rm, framebuffer allocation
|
|
_nv043691rm (the address is a case input), descriptor release, the level-2
|
|
cache service _nv041683rm, and the places that enter the BAR2 mapping cache:
|
|
_nv044028rm and _nv043739rm (map) become a call of the original aperture
|
|
update _nv039638rm with the address the public mapping code would pick
|
|
(persistent mappings top down below the last page of the RM aperture, others
|
|
bottom up); _nv043773rm (unmap) becomes a write-combine flush and the original
|
|
flush of KernelBus+4a8; _nv043699rm (descriptor destruction) releases the
|
|
cached test mapping with the original aperture update in sparsify mode. The
|
|
order of these BAR2 accesses equals the full physical trace of the V100.
|
|
The teardown register tail is taken from
|
|
_nv039604rm separately. No hardware is involved.
|
|
"""
|
|
import bisect
|
|
import hashlib
|
|
import json
|
|
from pathlib import Path
|
|
import struct
|
|
import warnings
|
|
|
|
warnings.filterwarnings("ignore", category=UserWarning)
|
|
from elftools.elf.elffile import ELFFile # noqa: E402
|
|
from unicorn import (UC_ARCH_X86, UC_HOOK_CODE, UC_HOOK_MEM_READ, UC_HOOK_MEM_WRITE, # noqa: E402
|
|
UC_MEM_WRITE, UC_MODE_64, Uc)
|
|
from unicorn.x86_const import (UC_X86_REG_R8, UC_X86_REG_R9, UC_X86_REG_R10, # noqa: E402
|
|
UC_X86_REG_R11, UC_X86_REG_R12, UC_X86_REG_R13, UC_X86_REG_R14,
|
|
UC_X86_REG_R15, UC_X86_REG_RAX, UC_X86_REG_RBP, UC_X86_REG_RBX,
|
|
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 = Path("/home/geodd/nvidia-driver/analysis-580.178.04/extracted/kernel/nvidia/nv-kernel.o_binary")
|
|
DIGEST = "5269a23ffba19a17fe16f076463e7ad4151254659441d1711bee6c6221ff6f4b"
|
|
TRANSCRIPT = ROOT / "target/trace/b3-bar0.txt"
|
|
BASES = {".text": 0x10000000, ".data": 0x20000000, ".rodata": 0x30000000, ".bss": 0x38000000}
|
|
EXT, HEAP, OBJ, STACK, STOP, BAR2 = (0x08000000, 0x40000000, 0x48000000, 0x4c000000, 0x4d000000,
|
|
0x60000000)
|
|
HEAP_SIZE, OBJ_SIZE, BAR2_SIZE = 0x4000000, 0x100000, 0x2000000
|
|
(GPU, BUS, MMU, MEMMGR, KMEMSYS, CHIP, RM, OBUS, DMA, CONFIG) = (
|
|
OBJ, OBJ + 0x10000, OBJ + 0x20000, OBJ + 0x30000, OBJ + 0x40000, OBJ + 0x50000, OBJ + 0x51000,
|
|
OBJ + 0x60000, OBJ + 0x70000, OBJ + 0x80000)
|
|
CONTINUE, GPU_1A0 = STOP + 0x100, STOP + 0x200
|
|
ARGS = (UC_X86_REG_RDI, UC_X86_REG_RSI, UC_X86_REG_RDX, UC_X86_REG_RCX, UC_X86_REG_R8, UC_X86_REG_R9)
|
|
THUNKS = {"rax": UC_X86_REG_RAX, "rbx": UC_X86_REG_RBX, "rcx": UC_X86_REG_RCX,
|
|
"rdx": UC_X86_REG_RDX, "rsi": UC_X86_REG_RSI, "r8": UC_X86_REG_R8, "r9": UC_X86_REG_R9,
|
|
"r10": UC_X86_REG_R10, "r11": UC_X86_REG_R11, "r12": UC_X86_REG_R12,
|
|
"r13": UC_X86_REG_R13, "r14": UC_X86_REG_R14, "r15": UC_X86_REG_R15}
|
|
# Functions the fixture replaces; everything else that runs is original code.
|
|
HOOKED = ("_nv053907rm", "_nv053912rm", "_nv047869rm", "_nv046745rm", "_nv046747rm", "_nv047868rm",
|
|
"_nv047867rm", "_nv046764rm", "_nv052687rm", "_nv052701rm", "_nv060459rm", "_nv060458rm", "_nv014074rm",
|
|
"_nv059509rm", "_nv059505rm", "_nv059492rm", "_nv031390rm", "_nv031395rm", "_nv031424rm",
|
|
"_nv031426rm", "_nv031478rm", "_nv031482rm", "_nv049745rm", "_nv043691rm", "_nv043704rm",
|
|
"_nv043699rm", "_nv041683rm", "_nv044028rm", "_nv043739rm", "_nv043773rm", "_nv039358rm")
|
|
# Slots the bring-up dispatches through, checked against the bindings report.
|
|
EXPECTED = {"KernelBus": {"0x110": "_nv039594rm", "0x138": "_nv039638rm", "0x140": "_nv039566rm",
|
|
"0x150": "_nv039447rm", "0x158": "_nv039445rm", "0x160": "_nv039455rm",
|
|
"0x178": "_nv039325rm", "0x1c0": "_nv039577rm", "0x1d0": "_nv039563rm",
|
|
"0x1d8": "_nv039604rm", "0x3e0": "_nv039556rm", "0x3e8": "_nv039394rm",
|
|
"0x3f0": "_nv039562rm", "0x3f8": "_nv039541rm", "0x400": "_nv039463rm",
|
|
"0x408": "_nv039656rm", "0x418": "_nv039307rm", "0x428": "_nv039472rm"},
|
|
"KernelGmmu": {"0x160": "_nv040639rm", "0x168": "_nv040663rm", "0x170": "_nv040941rm"},
|
|
"OBJBUS": {"0x268": "_nv018613rm"}}
|
|
|
|
raw = ORIGINAL.read_bytes()
|
|
assert hashlib.sha256(raw).hexdigest() == DIGEST
|
|
bindings = json.loads((ROOT / "reports/gv100-engine-hal-bindings.json").read_text())
|
|
assert bindings["original_sha256"] == DIGEST
|
|
tables = {entry["class_label"]: entry["hal_slots"] for entry in bindings["classes"]}
|
|
for label, slots in EXPECTED.items():
|
|
for slot, function in slots.items():
|
|
assert tables[label][slot]["function"] == function, (label, slot)
|
|
|
|
with ORIGINAL.open("rb") as stream:
|
|
elf = ELFFile(stream)
|
|
index = {section.name: number for number, section in enumerate(elf.iter_sections())}
|
|
sections = {name: bytearray(elf.get_section_by_name(name).data()) if name != ".bss"
|
|
else bytearray(elf.get_section_by_name(name)["sh_size"]) for name in BASES}
|
|
symbol_bytes = elf.get_section_by_name(".symtab").data()
|
|
strings = elf.get_section_by_name(".strtab").data()
|
|
relocations = {name: elf.get_section_by_name(".rela" + name).data()
|
|
for name in (".text", ".data", ".rodata")}
|
|
section_base = {index[name]: base for name, base in BASES.items()}
|
|
symbols, by_name, externals, functions = [], {}, {}, []
|
|
for name_offset, info, other, section, value, size in struct.iter_unpack("<IBBHQQ", symbol_bytes):
|
|
name = strings[name_offset:strings.index(b"\0", name_offset)].decode()
|
|
address = None
|
|
if section == 0 and name:
|
|
address = externals.setdefault(name, EXT + 0x100 + 16 * len(externals))
|
|
elif section in section_base:
|
|
address = section_base[section] + value
|
|
if name:
|
|
by_name[name] = address
|
|
if info & 15 == 2 and section == index[".text"]:
|
|
functions.append((address, size, name))
|
|
symbols.append(address)
|
|
functions.sort()
|
|
starts = [entry[0] for entry in functions]
|
|
for name, blob in relocations.items():
|
|
data, base = sections[name], BASES[name]
|
|
for offset, info, addend in struct.iter_unpack("<QQq", blob):
|
|
kind, target = info & 0xffffffff, symbols[info >> 32]
|
|
if target is None:
|
|
continue
|
|
if kind == 1:
|
|
struct.pack_into("<Q", data, offset, (target + addend) & (1 << 64) - 1)
|
|
elif kind in (2, 4):
|
|
struct.pack_into("<i", data, offset, target + addend - (base + offset))
|
|
elif kind == 10:
|
|
struct.pack_into("<I", data, offset, target + addend)
|
|
else:
|
|
assert kind == 11, kind
|
|
struct.pack_into("<i", data, offset, target + addend)
|
|
|
|
|
|
def function_at(address):
|
|
position = bisect.bisect_right(starts, address) - 1
|
|
if position >= 0:
|
|
start, size, name = functions[position]
|
|
if start <= address < start + max(size, 1):
|
|
return name
|
|
return None
|
|
|
|
|
|
cpu = Uc(UC_ARCH_X86, UC_MODE_64)
|
|
for name, base in BASES.items():
|
|
cpu.mem_map(base, (len(sections[name]) + 0xfff) & ~0xfff)
|
|
cpu.mem_write(base, bytes(sections[name]))
|
|
for base, size in ((EXT, 0x10000), (HEAP, HEAP_SIZE), (OBJ, OBJ_SIZE), (STACK, 0x100000),
|
|
(STOP, 0x1000), (BAR2, BAR2_SIZE)):
|
|
cpu.mem_map(base, size)
|
|
executed = set()
|
|
state = {}
|
|
|
|
|
|
def q(address):
|
|
return struct.unpack("<Q", cpu.mem_read(address, 8))[0]
|
|
|
|
|
|
def d(address):
|
|
return struct.unpack("<I", cpu.mem_read(address, 4))[0]
|
|
|
|
|
|
def wq(address, value):
|
|
cpu.mem_write(address, struct.pack("<Q", value & (1 << 64) - 1))
|
|
|
|
|
|
def wd(address, value):
|
|
cpu.mem_write(address, struct.pack("<I", value & 0xffffffff))
|
|
|
|
|
|
def wb(address, value):
|
|
cpu.mem_write(address, bytes([value]))
|
|
|
|
|
|
def allocate(size, fill=0):
|
|
address = state["heap"]
|
|
state["heap"] += (size + 0x1f) & ~0xf
|
|
assert state["heap"] < HEAP + HEAP_SIZE
|
|
cpu.mem_write(address, bytes([fill]) * size)
|
|
return address
|
|
|
|
|
|
def leave(value=0):
|
|
rsp = cpu.reg_read(UC_X86_REG_RSP)
|
|
cpu.reg_write(UC_X86_REG_RSP, rsp + 8)
|
|
cpu.reg_write(UC_X86_REG_RAX, value & (1 << 64) - 1)
|
|
cpu.reg_write(UC_X86_REG_RIP, q(rsp))
|
|
|
|
|
|
def call(target, *arguments, stack=()):
|
|
for register, argument in zip(ARGS, arguments):
|
|
cpu.reg_write(register, argument & (1 << 64) - 1)
|
|
rsp = (STACK + 0xf0000 - 8 * len(stack)) & ~0xf
|
|
rsp -= 8
|
|
cpu.reg_write(UC_X86_REG_RSP, rsp)
|
|
# The object code keeps locals on a second stack addressed through RBP.
|
|
cpu.reg_write(UC_X86_REG_RBP, STACK + 0x80000)
|
|
wq(rsp, STOP)
|
|
for number, value in enumerate(stack):
|
|
wq(rsp + 8 + 8 * number, value)
|
|
cpu.emu_start(target if isinstance(target, int) else by_name[target], STOP)
|
|
assert cpu.reg_read(UC_X86_REG_RIP) == STOP, target
|
|
return cpu.reg_read(UC_X86_REG_RAX)
|
|
|
|
|
|
def nested(target, arguments, after):
|
|
"""Enter an original function from a fixture hook and resume the caller afterwards."""
|
|
rsp = cpu.reg_read(UC_X86_REG_RSP) - 8
|
|
cpu.reg_write(UC_X86_REG_RSP, rsp)
|
|
wq(rsp, CONTINUE)
|
|
for register, argument in zip(ARGS, arguments):
|
|
cpu.reg_write(register, argument)
|
|
cpu.reg_write(UC_X86_REG_RIP, target if isinstance(target, int) else by_name[target])
|
|
state["continuations"].append(after)
|
|
|
|
|
|
def emit(token):
|
|
state["events"].append(token)
|
|
|
|
|
|
def translate(offset):
|
|
"""BAR2 offset to framebuffer address through the tables in the framebuffer model."""
|
|
entry = state["fb"].get(q(BUS + 0x4618) + (offset >> 12) * 8, 0)
|
|
assert entry & 1, hex(offset)
|
|
return ((entry >> 8) << 12) + (offset & 0xfff)
|
|
|
|
|
|
def pop(name, default):
|
|
values = state["case"][name]
|
|
return values.pop(0) if values else default
|
|
|
|
|
|
def read_register(a):
|
|
assert (a[0], a[1] & 0xffffffff, a[2] & 0xffffffff) == (GPU + 0x4120, 0, 0)
|
|
offset = a[3] & 0xffffffff
|
|
if offset == 0x1700:
|
|
value = state["window"]
|
|
elif offset == 0x1714:
|
|
value = state["bar2_block"]
|
|
elif offset == 0x1710:
|
|
value = pop("bind", 0)
|
|
elif offset == 0x70000:
|
|
value = pop("flush", 0)
|
|
elif offset == 0x100c80:
|
|
value = pop("mmu", 0x208001)
|
|
else:
|
|
assert 0x700000 <= offset < 0x800000, hex(offset)
|
|
value = state["fb"].get(((state["window"] & 0xffffff) << 16) + offset - 0x700000, 0)
|
|
state["pramin_reads"] += 1
|
|
if state["pramin_reads"] == state["case"]["corrupt_pramin"]:
|
|
value ^= 0x100
|
|
emit(f"r:{offset:x}:{value:x}")
|
|
return value
|
|
|
|
|
|
def write_register(a):
|
|
assert (a[0], a[1] & 0xffffffff, a[2] & 0xffffffff) == (GPU + 0x4120, 0, 0)
|
|
offset, value = a[3] & 0xffffffff, a[4] & 0xffffffff
|
|
if offset == 0x1700:
|
|
state["window"] = value
|
|
elif offset == 0x1714:
|
|
state["bar2_block"] = value
|
|
elif 0x700000 <= offset < 0x800000:
|
|
state["fb"][((state["window"] & 0xffffff) << 16) + offset - 0x700000] = value
|
|
else:
|
|
assert offset in (0x70000, 0x100cb8, 0x100cec, 0x100cbc), hex(offset)
|
|
emit(f"w:{offset:x}:{value:x}")
|
|
return 0
|
|
|
|
|
|
def bar2_access(emu, access, address, size, value, unused):
|
|
offset = address - BAR2
|
|
assert size == 4, (hex(offset), size)
|
|
if access == UC_MEM_WRITE:
|
|
state["fb"][translate(offset)] = value & 0xffffffff
|
|
emit(f"W:{offset:x}:{value & 0xffffffff:x}")
|
|
else:
|
|
value = state["fb"].get(translate(offset), 0)
|
|
state["bar2_reads"] += 1
|
|
if state["bar2_reads"] == state["case"]["corrupt_bar2"]:
|
|
value ^= 0x100
|
|
cpu.mem_write(address, struct.pack("<I", value))
|
|
emit(f"R:{offset:x}:{value:x}")
|
|
|
|
|
|
def copy(a):
|
|
destination, source, size = a[0], a[1], a[2] & 0xffffffff
|
|
data = bytes(cpu.mem_read(source, size))
|
|
assert not BAR2 <= source < BAR2 + BAR2_SIZE
|
|
if BAR2 <= destination < BAR2 + BAR2_SIZE:
|
|
# The original copies page-table entries bytewise; record 32-bit words.
|
|
assert size % 4 == 0
|
|
for position in range(0, size, 4):
|
|
word = struct.unpack_from("<I", data, position)[0]
|
|
offset = destination - BAR2 + position
|
|
state["fb"][translate(offset)] = word
|
|
emit(f"W:{offset:x}:{word:x}")
|
|
cpu.mem_write(destination, data)
|
|
return destination
|
|
|
|
|
|
def fill(a):
|
|
assert not BAR2 <= a[0] < BAR2 + BAR2_SIZE
|
|
cpu.mem_write(a[0], bytes([a[1] & 0xff]) * (a[2] & 0xffffffff))
|
|
return a[0]
|
|
|
|
|
|
def diagnostic(a):
|
|
emit(f"e:{a[1] >> 16 & 0xffff:x}")
|
|
return 0
|
|
|
|
|
|
def context(a):
|
|
wd(a[1], 0)
|
|
return 0
|
|
|
|
|
|
def next_gpu(a):
|
|
position = d(a[1])
|
|
while position < 32 and not (a[0] & 0xffffffff) >> position & 1:
|
|
position += 1
|
|
if position >= 32:
|
|
return 0
|
|
wd(a[1], position + 1)
|
|
return GPU
|
|
|
|
|
|
def timeout_start(a):
|
|
assert a[0] == GPU + 0x1e08
|
|
emit(f"ts:{a[3] & 0xffffffff:x}")
|
|
return 0
|
|
|
|
|
|
def timeout_check(a):
|
|
assert a[0] == GPU + 0x1e08
|
|
status = pop("check", 0)
|
|
emit(f"tc:{a[2] & 0xffffffff:x}:{status:x}")
|
|
return status
|
|
|
|
|
|
def thread_reset(a):
|
|
emit("tr")
|
|
return 0
|
|
|
|
|
|
def map_pci(a):
|
|
assert (a[0], a[4]) == (GPU, BUS + 0x7c48)
|
|
emit(f"m:{a[1]:x}:{a[2]:x}")
|
|
wq(a[4], BAR2)
|
|
return 0
|
|
|
|
|
|
def descriptor_size(descriptor):
|
|
return (q(descriptor + 0x30) + 0xfff) & ~0xfff
|
|
|
|
|
|
def framebuffer_allocate(a):
|
|
address = state["case"]["pages"].pop(0)
|
|
emit(f"a:{address:x}")
|
|
nested("_nv043698rm", [a[0], 2, address, q(a[0] + 0x30)], lambda unused: 0)
|
|
|
|
|
|
def map_descriptor(descriptor, flags):
|
|
size = descriptor_size(descriptor)
|
|
if flags & 8:
|
|
state["top"] -= size
|
|
address = state["top"]
|
|
else:
|
|
address = state["bottom"]
|
|
state["bottom"] += size
|
|
state["mapped"][descriptor] = (address, size)
|
|
emit(f"v:{address:x}:{size:x}")
|
|
nested(q(BUS + 0x138), [GPU, BUS, descriptor, address, size, 1],
|
|
lambda status: BAR2 + address if status & 0xffffffff == 0 else 0)
|
|
|
|
|
|
def unmap_descriptor(a):
|
|
"""_nv043773rm with flags 0: write-combine flush, the mapping stays cached, then the
|
|
original flush of KernelBus+4a8 with the aperture flag of _nv039418rm."""
|
|
assert a[2] & 0xffffffff == 0
|
|
emit("f")
|
|
state["cached"].add(a[1])
|
|
nested("_nv039418rm", [BUS, 2], lambda flag: nested(
|
|
q(BUS + 0x4a8), [GPU, BUS, flag & 0xffffffff], lambda unused: 0))
|
|
|
|
|
|
def destroy_descriptor(a):
|
|
"""Releasing a cached mapping when its descriptor goes away: sparse entry and invalidate."""
|
|
if a[0] not in state["cached"]:
|
|
return 0
|
|
state["cached"].remove(a[0])
|
|
address, size = state["mapped"].pop(a[0])
|
|
nested(q(BUS + 0x138), [GPU, BUS, a[0], address, size, 5], lambda unused: 0)
|
|
return None
|
|
|
|
|
|
def cache_service(a):
|
|
emit(f"L:{a[2] & 0xffffffff:x}")
|
|
return 0
|
|
|
|
|
|
def destroy(a):
|
|
emit("D")
|
|
return 0
|
|
|
|
|
|
HANDLERS = {
|
|
"_nv053907rm": read_register, "_nv053912rm": write_register,
|
|
"_nv047869rm": diagnostic, "_nv046745rm": lambda a: 0, "_nv046747rm": lambda a: 0,
|
|
"_nv047868rm": diagnostic, "_nv047867rm": diagnostic,
|
|
"_nv046764rm": lambda a: emit(f"e:x{a[1] & 0xffffffff:x}") or 0,
|
|
"_nv052687rm": lambda a: allocate(a[0], 0xcc), "_nv052701rm": lambda a: 0,
|
|
"_nv060459rm": context, "_nv060458rm": lambda a: 0, "_nv014074rm": lambda a: 0,
|
|
"_nv059509rm": timeout_start, "_nv059505rm": timeout_check, "_nv059492rm": thread_reset,
|
|
"_nv031390rm": lambda a: 0, "_nv031395rm": lambda a: 1, "_nv031424rm": next_gpu,
|
|
"_nv031426rm": lambda a: GPU, "_nv031478rm": lambda a: 0, "_nv031482rm": lambda a: 0,
|
|
"_nv049745rm": map_pci, "_nv043691rm": framebuffer_allocate,
|
|
"_nv043704rm": lambda a: 0, "_nv043699rm": destroy_descriptor,
|
|
"_nv041683rm": cache_service,
|
|
"_nv044028rm": lambda a: map_descriptor(a[1], a[2]),
|
|
"_nv043739rm": lambda a: map_descriptor(a[1], a[2]),
|
|
"_nv043773rm": unmap_descriptor, "_nv039358rm": destroy,
|
|
"os_mem_set": fill, "os_mem_copy": copy,
|
|
"os_flush_cpu_write_combine_buffer": lambda a: emit("f") or 0,
|
|
}
|
|
assert set(HOOKED) <= set(HANDLERS)
|
|
|
|
|
|
def install(address, handler):
|
|
def run(emu, pc, size, unused):
|
|
value = handler([emu.reg_read(register) for register in ARGS])
|
|
if value is not None:
|
|
leave(value)
|
|
cpu.hook_add(UC_HOOK_CODE, run, begin=address, end=address)
|
|
|
|
|
|
for name, handler in HANDLERS.items():
|
|
install(externals[name] if name in externals else by_name[name], handler)
|
|
for name, address in externals.items():
|
|
if name.startswith("__x86_indirect_thunk_"):
|
|
register = THUNKS[name.rsplit("_", 1)[1]]
|
|
cpu.hook_add(UC_HOOK_CODE, lambda emu, pc, size, register: emu.reg_write(
|
|
UC_X86_REG_RIP, emu.reg_read(register)), register, begin=address, end=address)
|
|
def resume(emu, pc, size, unused):
|
|
# A continuation either returns the hooked function's result or chains another call.
|
|
value = state["continuations"].pop()(emu.reg_read(UC_X86_REG_RAX))
|
|
if value is not None:
|
|
leave(value)
|
|
|
|
|
|
cpu.hook_add(UC_HOOK_CODE, resume, begin=CONTINUE, end=CONTINUE)
|
|
install(GPU_1A0, lambda a: emit("g") or 0)
|
|
cpu.hook_add(UC_HOOK_MEM_READ | UC_HOOK_MEM_WRITE, bar2_access, begin=BAR2,
|
|
end=BAR2 + BAR2_SIZE - 1)
|
|
|
|
|
|
def record_function(emu, address, size, unused):
|
|
name = function_at(address)
|
|
if name and address == by_name.get(name):
|
|
executed.add(name)
|
|
|
|
|
|
def unexpected(emu, address, size, unused):
|
|
for name, target in externals.items():
|
|
if target == address and name not in HANDLERS and not name.startswith("__x86"):
|
|
raise AssertionError("unexpected external " + name)
|
|
|
|
|
|
cpu.hook_add(UC_HOOK_CODE, unexpected, begin=EXT, end=EXT + 0x10000)
|
|
cpu.mem_write(CHIP + 0x10, struct.pack("<H", 0x23))
|
|
cpu.mem_write(RM + 0x10, struct.pack("<H", 2))
|
|
PRISTINE = {name: bytes(sections[name]) for name in (".data", ".bss")}
|
|
|
|
|
|
def prepare(case):
|
|
"""Objects as the engine constructors and the memory manager leave them."""
|
|
cpu.mem_write(OBJ, bytes(OBJ_SIZE))
|
|
for name, content in PRISTINE.items():
|
|
cpu.mem_write(BASES[name], content)
|
|
cpu.mem_write(CHIP + 0x10, struct.pack("<H", 0x23))
|
|
cpu.mem_write(RM + 0x10, struct.pack("<H", 2))
|
|
state.update(heap=HEAP, events=[], fb={}, continuations=[], mapped={}, cached=set(),
|
|
case=case,
|
|
window=case["window_register"], bar2_block=0, pramin_reads=0, bar2_reads=0,
|
|
top=case["rm_limit"] + 1 - 0x1000, bottom=0)
|
|
for binder, target in (("_nv005902rm", BUS), ("_nv005903rm", BUS), ("_nv005790rm", BUS),
|
|
("_nv005935rm", MEMMGR), ("_nv005806rm", MEMMGR),
|
|
("_nv005925rm", KMEMSYS), ("_nv005800rm", KMEMSYS),
|
|
("_nv005914rm", MMU), ("_nv005915rm", MMU), ("_nv005794rm", MMU),
|
|
("_nv005953rm", OBUS),
|
|
# The parent-class binder receives the sub-object OBJBUS+e8
|
|
# (_nv005726rm, called by the creator _nv006625rm).
|
|
("_nv005997rm", OBUS + 0xe8)):
|
|
call(binder, target, CHIP, RM)
|
|
for label, base in (("KernelBus", BUS), ("KernelGmmu", MMU), ("OBJBUS", OBUS)):
|
|
for slot, function in EXPECTED[label].items():
|
|
assert q(base + int(slot, 16)) == by_name[function], (label, slot)
|
|
# Page-table format: the steps of the KernelGmmu constructor _nv040666rm for version 2.
|
|
family = allocate(0x530)
|
|
wq(MMU + 0x4b0, family)
|
|
wq(MMU + 0x498, 0x10000)
|
|
call("_nv040763rm", MMU, MMU + 0x4f8)
|
|
call("_nv040773rm", MMU, MMU + 0x502)
|
|
call(q(MMU + 0x1c0), MMU, family, 2, MMU + 0x4f8)
|
|
call(q(MMU + 0x1a8), MMU, family + 0x210, 2, MMU + 0x4f8)
|
|
call(q(MMU + 0x1a0), MMU, family + 0x310, 2, MMU + 0x502, 0)
|
|
call(q(MMU + 0x188), MMU, family + 0x310, 2)
|
|
assert call("_nv040782rm", MMU) == 0
|
|
call(q(MMU + 0x1c8), GPU, MMU)
|
|
for offset, target in ((0x1f80, BUS), (0x1f90, MMU), (0x1ed0, MEMMGR), (0x1ec8, KMEMSYS),
|
|
(0x1f78, OBUS), (0x1fb0, DMA)):
|
|
wq(GPU + offset, target)
|
|
wq(GPU + 0x1a0, GPU_1A0)
|
|
wb(GPU + 0x915, 1)
|
|
wq(GPU + 0xe30, 0x7000000000)
|
|
wq(KMEMSYS + 0x290, CONFIG)
|
|
wb(CONFIG + 0x10, 1)
|
|
wq(MEMMGR + 0x488, case["reserved_base"])
|
|
wq(MEMMGR + 0x830, case["fb_megabytes"])
|
|
for offset, value in ((0x45c0, 0x39a800000000), (0x45d0, 0),
|
|
(0x45d8, case["visible_limit"]), (0x45e0, case["hidden_base"]),
|
|
(0x45e8, case["hidden_limit"]), (0x45f0, 0),
|
|
(0x45f8, case["rm_limit"]),
|
|
(0x598, case["window_cache"])):
|
|
wq(BUS + offset, value)
|
|
for offset in (0xace4, 0xacdc, 0xacec, 0xace8, 0xace0, 0xacf0):
|
|
wd(BUS + offset, 2)
|
|
wd(BUS + 0x7c54, 0x101)
|
|
# _nv044065rm puts the BAR1 and BAR2 instance blocks first in reserved memory, then the
|
|
# original placement function lays out the page levels behind them.
|
|
cursor = allocate(8)
|
|
wq(cursor, 0x2000)
|
|
call("_nv044075rm", GPU, MEMMGR, cursor)
|
|
relative = (q(BUS + 0x4608), q(BUS + 0x4618), q(cursor))
|
|
# _nv043997rm relocates the instance block and creates its descriptor.
|
|
slot = allocate(8)
|
|
assert call("_nv043694rm", slot, GPU, 0x1000, 0x1000, 1, 2, stack=(2, 0)) & 0xffffffff == 0
|
|
call("_nv043698rm", q(slot), 2, case["reserved_base"] + 0x1000, 0x1000)
|
|
wq(BUS + 0x4628, q(slot))
|
|
wq(BUS + 0x4620, case["reserved_base"] + 0x1000)
|
|
return relative
|
|
|
|
|
|
def run(name, **changes):
|
|
case = dict(reserved_base=0x7fffa0000, fb_megabytes=0x8000, visible_limit=0x3fffff,
|
|
hidden_base=0x400000, hidden_limit=0x500fff, rm_limit=0x3fffff,
|
|
window_register=0x7fff0, window_cache=0x7fff00000,
|
|
pages=[0x7fdf7f000, 0x7fdf7e000], bind=[], flush=[], mmu=[], check=[],
|
|
corrupt_pramin=0, corrupt_bar2=0)
|
|
case.update(changes)
|
|
inputs = [case[key] for key in ("reserved_base", "fb_megabytes", "visible_limit", "hidden_base",
|
|
"hidden_limit", "rm_limit", "window_register", "window_cache")]
|
|
inputs += case["pages"]
|
|
case = {key: list(value) if isinstance(value, list) else value for key, value in case.items()}
|
|
relative = prepare(case)
|
|
status = call("_nv039592rm", GPU, BUS) & 0xffffffff
|
|
assert not state["continuations"]
|
|
layout = (*relative, q(BUS + 0x4620), q(BUS + 0x4608), q(BUS + 0x4618), q(BUS + 0x4600),
|
|
d(BUS + 0x4678), d(BUS + 0x4680))
|
|
events = list(state["events"])
|
|
rows.append(f"{name};" + " ".join(f"{value:x}" for value in inputs) + f";{status:x};"
|
|
+ " ".join(f"{value:x}" for value in layout) + ";" + " ".join(events))
|
|
return status, events, layout
|
|
|
|
|
|
rows = []
|
|
hook = cpu.hook_add(UC_HOOK_CODE, record_function, begin=BASES[".text"],
|
|
end=BASES[".text"] + len(sections[".text"]))
|
|
# Coverage of original functions is recorded on one small case; the hook is then removed.
|
|
status, events, layout = run("small")
|
|
cpu.hook_del(hook)
|
|
assert status == 0 and not any(token.startswith("e:") for token in events)
|
|
rows.clear()
|
|
|
|
# The physical V100 inputs of 0000:b3:00.0 (see the transcript comparison below).
|
|
status, physical, layout = run("v100", visible_limit=0x1ffffff, rm_limit=0xffffff,
|
|
hidden_base=0x2000000, hidden_limit=0xa090fff)
|
|
assert status == 0 and not any(token.startswith("e:") for token in physical)
|
|
assert layout == (0x2000, 0x6000, 0x57000, 0x7fffa1000, 0x7fffa2000, 0x7fffa6000, 0xa090fff, 4,
|
|
81), [hex(value) for value in layout]
|
|
# BAR2 accesses of the same interval in the full trace of all mappings
|
|
# (reports/original-mmiotrace-b3-first/mmiotrace.txt lines 30853165-30853348, BAR2 at
|
|
# 0x39a800000000). The three entry stores are byte copies the tracer logged without values.
|
|
PHYSICAL_BAR2 = ["W:fb5d48", "W:fb5d4c", "W:fae000", "W:fae004", "R:fa9000:0", "W:0:abcdabcd",
|
|
"W:4:abcdabcd", "W:8:abcdabcd", "W:c:abcdabcd", "R:fa9000:0", "R:0:abcdabdd",
|
|
"R:4:abcdabdd", "R:8:abcdabdd", "R:c:abcdabdd", "R:fa9000:0", "W:fae000",
|
|
"W:fae004", "R:fa9000:0"]
|
|
through_bar2 = [token for token in physical if token[0] in "RW"]
|
|
assert len(through_bar2) == len(PHYSICAL_BAR2)
|
|
assert all(token == seen or token.startswith(seen + ":")
|
|
for token, seen in zip(through_bar2, PHYSICAL_BAR2)), through_bar2
|
|
transcript = None
|
|
if TRANSCRIPT.exists():
|
|
expected = [token for token in physical if token[0] in "rw"]
|
|
position, matched, gaps, service = 0, 0, [], 0
|
|
lines = TRANSCRIPT.read_text().split("\n")[107727:138655]
|
|
pending, number = None, 0
|
|
while number < len(lines):
|
|
fields = lines[number].split()
|
|
number += 1
|
|
if fields[0] == "MARK":
|
|
pending = int(fields[3])
|
|
continue
|
|
if fields[1] == "12006c":
|
|
# The level-2 cache service: 35 accesses the fixture does not perform.
|
|
number += 34
|
|
service += 35
|
|
continue
|
|
token = f"{fields[0].lower()}:{int(fields[1], 16):x}:{int(fields[2], 16):x}"
|
|
if expected[position] != token:
|
|
skipped = expected.index(token, position) - position
|
|
assert pending == skipped, (107727 + number, pending, skipped)
|
|
gaps.append(skipped)
|
|
position += skipped
|
|
pending = None
|
|
position += 1
|
|
matched += 1
|
|
assert position == len(expected) and gaps == [52164, 828], (position, len(expected), gaps)
|
|
transcript = {"lines": "107728-138655", "register_accesses_matched": matched,
|
|
"level2_cache_service_accesses_not_executed": service,
|
|
"events_skipped_at_the_two_loss_markers": gaps,
|
|
"oracle_register_accesses": len(expected)}
|
|
|
|
# Layout: reserved base, aperture limits, hidden range, window state.
|
|
for number, base in enumerate((0x7fffa0000, 0x3ffe0e000, 0x1f0000, 0xfffff0000, 0x7ffeef000)):
|
|
for hidden in ((0x400000, 0x400fff), (0x400000, 0x7fffff), (0x400000, 0xa00fff),
|
|
(0x600000, 0x601fff)):
|
|
for window, cache in ((0x7fff0, 0x7fff00000), (0x7fff0, 0), (0x0307ffe0, 0),
|
|
(0xa0000020, 0x200000)):
|
|
megabytes = (0x8000, 0x4000, 0x8000, 0x3)[(number + hidden[1]) % 4]
|
|
run("layout", reserved_base=base, hidden_base=hidden[0], hidden_limit=hidden[1],
|
|
window_register=window, window_cache=cache, fb_megabytes=megabytes)
|
|
# The default 32 MiB visible range with the 16 MiB RM aperture.
|
|
for base, hidden_limit in ((0x7fffa0000, 0x2000fff), (0x3ffe0e000, 0x2345fff), (0x1f0000, 0x2200fff)):
|
|
run("default", reserved_base=base, visible_limit=0x1ffffff, rm_limit=0xffffff,
|
|
hidden_base=0x2000000, hidden_limit=hidden_limit)
|
|
# Aperture sizes set by the registry override (both limits equal) and odd sizes.
|
|
for megabytes, hidden_limit in ((1, 0x1ff000 - 1), (2, 0x7fffff), (3, 0x9fffff), (4, 0x4010fff),
|
|
(8, 0xffffff), (16, 0x10fffff)):
|
|
limit = (megabytes << 20) - 1
|
|
run("aperture", visible_limit=limit, rm_limit=limit,
|
|
hidden_base=limit + 1, hidden_limit=hidden_limit)
|
|
# The largest supported space: 256 page tables, which leave the 1 MiB PRAMIN window and
|
|
# put the page-level mapping across two page tables.
|
|
run("large", visible_limit=0x2fffff, rm_limit=0x2fffff, hidden_base=0x300000,
|
|
hidden_limit=0x1fffffff, reserved_base=0x7f0000000)
|
|
# Polling: bind status, flush status, invalidate queue and acknowledge, timeout checks.
|
|
for bind in ([], [4], [8, 0xc, 0], [0xfffffff3], [4, 4, 4]):
|
|
for check in ([], [0], [0x65], [0, 0x65], [0x10, 0], [0x65, 0x65, 0x65]):
|
|
if len(check) < len(bind):
|
|
continue
|
|
run("bind", bind=bind, check=check[:len(bind)])
|
|
for flush in ([1], [2, 3, 0], [0xfffffffc], [1, 1]):
|
|
for check in ([0, 0, 0], [0x65, 0, 0], [0, 0x65, 0], [0x10, 0, 0]):
|
|
run("flush", flush=flush, check=check[:len(flush)])
|
|
for mmu in ([0x8000, 0x208001], [0, 0x10000, 0x8000], [0xff0000, 0, 0x8000],
|
|
[0x208001, 0x200001, 0x200001, 0x8000], [0, 0, 0x208001]):
|
|
for check in ([0] * 4, [0x65] * 4, [0, 0x65, 0, 0], [0x10, 0, 0, 0], [0, 0, 0x65, 0]):
|
|
run("mmu", mmu=mmu, check=check)
|
|
# Pattern test failures at each comparison.
|
|
for position in range(1, 8):
|
|
run("verify", corrupt_pramin=position)
|
|
for position in range(1, 11):
|
|
run("verify", corrupt_bar2=position)
|
|
# Flush page and test page placement.
|
|
for pages in ([0x1000, 0x2000], [0xffffff000, 0x7fdf7e000], [0x7fdf7f000, 0x12345000]):
|
|
run("pages", pages=pages)
|
|
|
|
# Teardown register tail of _nv039604rm with no mapping left.
|
|
teardown = []
|
|
for block in (0xc07fffa1, 0x40000000, 0xffffffff, 0x80000000, 0):
|
|
prepare(dict(reserved_base=0x7fffa0000, fb_megabytes=0x8000, visible_limit=0x1ffffff,
|
|
hidden_base=0x2000000, hidden_limit=0x2000fff, rm_limit=0xffffff,
|
|
window_register=0x7fff0,
|
|
window_cache=0x7fff00000, pages=[], bind=[], flush=[], mmu=[], check=[],
|
|
corrupt_pramin=0, corrupt_bar2=0))
|
|
state["bar2_block"] = block
|
|
assert call("_nv039604rm", GPU, BUS, 0) & 0xffffffff == 0
|
|
teardown.append(f"teardown;{block:x};0;;" + " ".join(state["events"]))
|
|
rows += teardown
|
|
|
|
out = ROOT / "target/gpu-stage"
|
|
out.mkdir(parents=True, exist_ok=True)
|
|
oracle = "\n".join(rows) + "\n"
|
|
(out / "original-bar2-setup.txt").write_text(oracle)
|
|
kinds = {}
|
|
for row in rows:
|
|
kinds[row.split(";", 1)[0]] = kinds.get(row.split(";", 1)[0], 0) + 1
|
|
failed = sum(1 for row in rows if row.split(";")[2] != "0")
|
|
report = {
|
|
"original_sha256": DIGEST, "chip_hal": "0x23", "rm_hal": 2,
|
|
"entry": "_nv039592rm (KernelBus InitLocked, kernel half), _nv044075rm, _nv039604rm",
|
|
"executed_on_the_small_case": sorted(executed - set(HOOKED)),
|
|
"executed_count": len(executed - set(HOOKED)),
|
|
"fixture_supplied": sorted(HANDLERS),
|
|
"slots_checked_against_bindings_report": EXPECTED,
|
|
"cases": len(rows), "cases_by_kind": kinds, "cases_with_nonzero_status": failed,
|
|
"v100_layout": {"directory_offset": "0x2000", "table_offset": "0x6000",
|
|
"reserved_end_offset": "0x57000", "instance_block": "0x7fffa1000",
|
|
"page_directory": "0x7fffa2000", "page_tables": "0x7fffa6000",
|
|
"va_limit": "0xa090fff", "page_directories": 4, "page_tables_count": 81},
|
|
"v100_events": len(physical),
|
|
"v100_bar2_accesses": through_bar2,
|
|
"v100_bar2_accesses_equal_full_trace": True,
|
|
"transcript_comparison": transcript,
|
|
"oracle": "target/gpu-stage/original-bar2-setup.txt",
|
|
"oracle_sha256": hashlib.sha256(oracle.encode()).hexdigest(),
|
|
"scope": "Original GV100 KernelBus InitLocked kernel half with binder-selected tables, from "
|
|
"the default PRAMIN window to the end of the BAR2 pattern test. Register values, "
|
|
"the framebuffer and BAR2 memory model, allocation addresses, timeouts, the BAR2 "
|
|
"mapping cache and the level-2 cache service are fixture-supplied; no hardware "
|
|
"executed."}
|
|
(ROOT / "reports/gpu-bar2-setup-original.json").write_text(json.dumps(report, indent=2) + "\n")
|
|
print(f"{len(rows)} original BAR2 setup cases ({failed} with a nonzero status); executed "
|
|
f"{len(executed - set(HOOKED))} original functions"
|
|
+ (f"; transcript: {transcript['register_accesses_matched']} accesses matched"
|
|
if transcript else "; transcript absent"))
|