Files
nvdriver/tools/check_gpu_engine_dispatch_binary.py

373 lines
18 KiB
Python

#!/usr/bin/env python3
"""Run the original stage passes over a constructed GV100 engine set and write an oracle of
the engine callback order.
The GPU object is the one the original's own core init, probe and gpumgrAttachGpu build
(`gpu_world` of tools/check_rmapi_binary.py, read-only use): children table, the four
engine lists and every engine object come from original code. On that object the original
base passes execute from their entries:
_nv031220rm gpuStatePreInit (missing-engine sweep, then _nv026850rm per engine)
_nv031215rm gpuStateInit (_nv026844rm per engine)
_nv031217rm gpuStateLoad (PreLoad, Load, then the PostLoad pass _nv031219rm)
Every non-default slot of every engine's stage table (OBJENGSTATE table +0x30..+0x98) for
PreInitLocked, PreInitUnlocked, InitLocked, InitUnlocked, PreLoad, Load and PostLoad is
replaced by a recorder that notes (engine descriptor, slot, wrapper, the function the
wrapper jumps to for that object, whether the GPUs lock is held) and returns the status the
case gives it. Non-default IsPresent and InitMissing bodies run as original code (their
register reads are answered from the physical transcript of 0000:b3:00.0, first read of each
register) and are recorded with their answer. Default slots stay in place, so the original's
own "is the Unlocked slot the default" comparisons decide the lock drops, and the default
IsPresent asks the GPU function at +0x128 as it does in the driver.
Oracle lines per case: `defaults` (default body of each slot and what it returns), `list`
(the four engine lists as constructed), `absent` (list entries without an object),
`missing` (engines with byte +0x48 set), `default-present` (GPU+0x128 answers), `class`
(per class: instances and every non-default slot as wrapper:body:c or :h<object slot>),
`answer` (the case's injected statuses), `unlocked-dispatch` (_nv026850rm and _nv026844rm
called without the GPUs lock), then the events in order: `pass`, `observe`, `delete`
(_nv030262rm), `destroy` (_nv030269rm), `callback`, `status`; `final` lists and the
assertion sites the fixtures saw.
What this proves: the order in which the original's passes reach the engine callbacks on
the GV100 engine set this emulation constructs, the lock state at each, and how a
callback status changes the rest of the walk. What it does not prove: anything about a
callback body; the non-engine steps of the passes (they run as original code on a
constructed, uninitialized GPU with the fixtures of tools/check_rmapi_binary.py); or that
the emulated construction equals a physical V100's. In the emulation KernelNvlink, OBJDISP
and OBJHDA have no object after the attach, whereas the live capture in
reports/gpu-stage-engine-worklist.json has KernelNvlink.
Depends on tools/check_rmapi_binary.py (`gpu_world`, `first_reads`, the fixture table) and
tools/rmapi_binary_emulator.py; both are only imported.
"""
import hashlib
import json
import re
import sys
from pathlib import Path
if str(Path(__file__).resolve().parent) not in sys.path:
sys.path.insert(0, str(Path(__file__).resolve().parent))
from _gpu_bar1_engine_oracle_check import require, write_or_check_text # noqa: E402
sys.path.insert(0, str(Path(__file__).resolve().parent))
import check_rmapi_binary as R # noqa: E402
from capstone import CS_ARCH_X86, CS_MODE_64, Cs # noqa: E402
from unicorn import UC_HOOK_CODE # noqa: E402
from unicorn.x86_const import UC_X86_REG_RSI # noqa: E402
from rmapi_binary_emulator import ARGS # noqa: E402
E = R.E
ROOT = R.ROOT
OUT = ROOT / "target/gpu-stage"
STUBS = 0x09000000
SLOT_NAMES = ("ConstructEngine", "InitMissing", "PreInitLocked", "PreInitUnlocked",
"InitLocked", "InitUnlocked", "PreLoad", "Load", "PostLoad", "PreUnload",
"Unload", "PostUnload", "StateDestroy", "IsPresent")
SLOT_OFFSET = {name: 0x30 + 8 * index for index, name in enumerate(SLOT_NAMES)}
RECORDED = ("PreInitLocked", "PreInitUnlocked", "InitLocked", "InitUnlocked", "PreLoad", "Load",
"PostLoad")
OBSERVED = ("InitMissing", "IsPresent")
LISTS = (("init", 0xda0), ("load", 0xdb0), ("unload", 0xdb8), ("destroy", 0xda8))
DISASSEMBLER = Cs(CS_ARCH_X86, CS_MODE_64)
E.cpu.mem_map(STUBS, 0x100000)
world = {}
def symbol(address):
return E.entry_names.get(address) or f"{address:#x}"
def number(name):
"""`_nv043631rm` -> 43631."""
require(name.startswith("_nv") and name.endswith("rm"), name)
return int(name[3:-2])
def class_body(engstate, wrapper):
"""The function a stage wrapper tail-jumps to for this object. Every wrapper is a thunk of
one of two shapes: through the class block (`mov rax,[rsi-K]; mov rax,[rax+slot]`) or
through a HAL slot of the object (`mov rax,[rsi+slot]`). Returns (address, "class" or
"hal", slot); any other instruction is a defect of this harness."""
registers = {"rsi": engstate}
kind = slot = None
for instruction in DISASSEMBLER.disasm(E.read(wrapper, 48), wrapper):
text = f"{instruction.mnemonic} {instruction.op_str}"
if instruction.mnemonic == "endbr64":
continue
if instruction.mnemonic == "jmp":
require(int(instruction.op_str, 16) == E.externals["__x86_indirect_thunk_rax"], text)
return registers["rax"], kind, slot
match = re.fullmatch(r"(mov|lea) (\w+), (?:qword ptr )?\[(\w+) ([+-]) (0x[0-9a-f]+|\d+)\]",
text)
if match:
operation, target, base, sign, amount = match.groups()
address = registers[base] + (-1 if sign == "-" else 1) * int(amount, 0)
if operation == "lea":
registers[target] = address
else:
require(target == "rax", text)
if base == "rsi":
# Through the object: a class block pointer below the engine state, or
# a HAL slot of the object (object offset = engine-state offset + 8).
kind, slot = ("class", None) if sign == "-" else ("hal", int(amount, 0) + 8)
else:
require(base == "rax" and kind == "class", text)
slot = int(amount, 0)
registers[target] = E.q(address)
continue
match = re.fullmatch(r"mov (\w+), (\w+)", text)
require(match, f"thunk shape of {symbol(wrapper)}: {text}")
registers[match.group(1)] = registers[match.group(2)]
raise AssertionError(f"thunk of {symbol(wrapper)} does not end")
def read_lists(gpu):
count = E.d(gpu + 0xdc0)
return {name: [E.d(E.q(gpu + offset) + 4 * index) for index in range(count)]
for name, offset in LISTS}
def stub_hook(emu, address, size, unused):
index = (address - STUBS) // 16
table, slot, target = world["stubs"][index]
engstate = emu.reg_read(UC_X86_REG_RSI)
descriptor = world["engstates"].get(engstate)
require(descriptor is not None, f"callback on an unknown object {engstate:#x}")
if slot in OBSERVED:
# Original code runs; the recorder notes its answer when it returns.
event = ["observe", descriptor, slot, symbol(target), None]
world["events"].append(event)
def after(value):
event[4] = value & 0xff
return value
E.nested(target, [emu.reg_read(register) for register in ARGS], after)
return
status = world["statuses"].get((descriptor, slot), 0)
body = class_body(engstate, target)[0]
world["events"].append(["callback", descriptor, slot, symbol(target), symbol(body),
int(world["locked"]), status])
E.leave(status)
E.cpu.hook_add(UC_HOOK_CODE, stub_hook, begin=STUBS, end=STUBS + 0xfffff)
def lock_event(owned):
def run(emu, address, size, unused):
world["locked"] = owned
return run
def removal(kind):
def run(emu, address, size, unused):
if kind == "delete":
world["events"].append(["delete", emu.reg_read(UC_X86_REG_RSI) & 0xffffffff])
else:
engstate = emu.reg_read(UC_X86_REG_RSI)
world["events"].append(["destroy", world["engstates"].get(engstate, 0)])
return run
# _nv054117rm releases the GPUs lock, _nv054115rm takes it (both run as original code).
E.cpu.hook_add(UC_HOOK_CODE, lock_event(False), begin=E.by_name["_nv054117rm"],
end=E.by_name["_nv054117rm"])
E.cpu.hook_add(UC_HOOK_CODE, lock_event(True), begin=E.by_name["_nv054115rm"],
end=E.by_name["_nv054115rm"])
# _nv030262rm(gpu, descriptor) removes an engine from the lists; _nv030269rm destroys it.
E.cpu.hook_add(UC_HOOK_CODE, removal("delete"), begin=E.by_name["_nv030262rm"],
end=E.by_name["_nv030262rm"])
E.cpu.hook_add(UC_HOOK_CODE, removal("destroy"), begin=E.by_name["_nv030269rm"],
end=E.by_name["_nv030269rm"])
def construct():
"""A constructed GPU with recorders in its stage tables. Returns the header lines."""
# The stage tables live in .rodata, which a new world does not restore.
for table, name, target in world.get("stubs", ()):
E.wq(table + SLOT_OFFSET[name], target)
context, gpu, nv, system = R.gpu_world()
values = R.first_reads()
world.update(gpu=gpu, events=[], statuses={}, locked=False, stubs=[], engstates={},
unknown_registers=[])
def register_read(a):
offset = a[2] & 0xffffffff
table = R.gpu_state["registers"]
if offset not in table:
# First value the physical transcript holds for the register; a register it
# never read is a case defect and stops the harness.
require(offset in values, f"register {offset:#x} has no transcript value")
table[offset] = values[offset]
R.gpu_state["read"].append(offset)
return table[offset]
for name in ("_nv049612rm", "os_delay_us"):
if name in R.HOOKS:
E.cpu.hook_del(R.HOOKS.pop(name))
E.handlers.pop(name, None)
R.HOOKS["_nv049612rm"] = E.install("_nv049612rm", register_read)
R.HOOKS["os_delay_us"] = E.install("os_delay_us", lambda a: 0)
lists = read_lists(gpu)
defaults, tables, lines = {}, {}, []
for descriptor in lists["init"]:
engstate = E.call("_nv030522rm", gpu, descriptor)
if engstate:
world["engstates"][engstate] = descriptor
tables.setdefault(E.q(engstate), []).append((descriptor, engstate))
# The default of a slot is the function most stage tables hold there.
for name, offset in SLOT_OFFSET.items():
counts = {}
for table in tables:
counts[E.q(table + offset)] = counts.get(E.q(table + offset), 0) + 1
defaults[name] = max(counts, key=counts.get)
require(symbol(defaults["PreInitUnlocked"]) == "_nv026849rm")
require(symbol(defaults["InitUnlocked"]) == "_nv026843rm")
world["defaults"] = defaults
sample = next(iter(world["engstates"]))
lines.append("defaults " + " ".join(
f"{name}={number(symbol(defaults[name]))}:"
f"{E.call(defaults[name], gpu, sample, 0) & 0xffffffff:x}"
for name in SLOT_NAMES if name not in ("ConstructEngine", "StateDestroy")))
for name, _offset in LISTS:
lines.append(f"list {name} " + " ".join(f"{value:x}" for value in lists[name]))
lines.append("absent " + (" ".join(
f"{descriptor:x}" for descriptor in lists["init"]
if descriptor not in world["engstates"].values()) or "-"))
# Byte +0x48 of the engine state: the pass destroys such an engine in its sweep without
# asking IsPresent.
lines.append("missing " + (" ".join(
f"{descriptor:x}" for engstate, descriptor in world["engstates"].items()
if E.b(engstate + 0x48)) or "-"))
# The default IsPresent _nv026838rm asks the GPU function at +0x128 with the engine's
# descriptor (engine state +0x4c). Its answers for the engines that use the default:
answers = []
for engstate, descriptor in world["engstates"].items():
require(E.d(engstate + 0x4c) == descriptor)
if E.q(E.q(engstate) + SLOT_OFFSET["IsPresent"]) == defaults["IsPresent"]:
answers.append(f"{descriptor:x}={E.call(E.q(gpu + 0x128), gpu, descriptor) & 0xff:x}")
lines.append(f"default-present {number(symbol(E.q(gpu + 0x128)))} " + " ".join(answers))
for table, users in tables.items():
descriptor, engstate = users[0]
slots = []
for name, offset in SLOT_OFFSET.items():
target = E.q(table + offset)
if target == defaults[name]:
continue
body, kind, slot = class_body(engstate, target)
slots.append(f"{name}={number(symbol(target))}:{number(symbol(body))}:"
+ ("c" if kind == "class" else f"h{slot:x}"))
if name in RECORDED or name in OBSERVED:
E.wq(table + offset, STUBS + 16 * len(world["stubs"]))
world["stubs"].append((table, name, target))
lines.append(f"class {descriptor >> 8:x} {len(users)} " + (" ".join(slots) or "-"))
return lines
def run_pass(name, *arguments):
gpu = world["gpu"]
require(E.call("_nv031506rm") & 0xffffffff == 0)
require(E.call("_nv054115rm", 0, 1) & 0xffffffff == 0)
world["locked"] = True
world["events"].append(["pass", name])
status = E.call(name, gpu, *arguments) & 0xffffffff
world["events"].append(["status", name, status, int(world["locked"])])
require(E.call("_nv054117rm", 0, 0) & 0xffffffff == 0)
E.call("_nv031505rm")
return status
def case(name, statuses, passes=("pre_init", "init", "load")):
lines = [f"case {name}"] + construct()
world["statuses"] = dict(statuses)
for (descriptor, slot), status in sorted(statuses.items()):
lines.append(f"answer {descriptor:x} {slot} {status:x}")
R.state["diag"].clear()
# The per-engine dispatchers called without the GPUs lock: _nv026850rm (PreInit) and
# _nv026844rm (Init) on OBJMC, whose Unlocked slots are not the default.
engstate = next(pointer for pointer, descriptor in world["engstates"].items()
if descriptor == 0x9aad0e00)
for entry in ("_nv026850rm", "_nv026844rm"):
before = len(world["events"])
status = E.call(entry, world["gpu"], engstate) & 0xffffffff
lines.append(f"unlocked-dispatch {number(entry)} {status:x} "
f"{len(world['events']) - before} " + " ".join(str(entry) for entry in R.state["diag"]))
del world["events"][before:]
R.state["diag"].clear()
ran = []
for stage, entry, arguments in (("pre_init", "_nv031220rm", ()),
("init", "_nv031215rm", ()),
("load", "_nv031217rm", (0,))):
if stage not in passes:
continue
status = run_pass(entry, *arguments)
ran.append(stage)
if status != 0:
break
for event in world["events"]:
kind = event[0]
if kind == "pass":
lines.append(f"pass {number(event[1])}")
elif kind == "status":
lines.append(f"status {number(event[1])} {event[2]:x} {event[3]}")
elif kind == "callback":
_, descriptor, slot, wrapper, body, locked, status = event
lines.append(f"callback {descriptor:x} {slot} {number(wrapper)} {number(body)} "
f"{locked} {status:x}")
elif kind == "observe":
lines.append(f"observe {event[1]:x} {event[2]} {number(event[3])} {event[4]:x}")
elif kind == "delete":
lines.append(f"delete {event[1]:x}")
elif kind == "destroy":
lines.append(f"destroy {event[1]:x}")
final = read_lists(world["gpu"])
count = E.d(world["gpu"] + 0xdc0)
for name, _offset in LISTS:
lines.append(f"final {name} " + " ".join(f"{value:x}" for value in final[name][:count]))
lines.append("diagnostics " + (" ".join(str(entry) for entry in R.state["diag"]) or "-"))
lines.append("end")
return lines, ran
def main():
graphics, cipher, memsys, bus, therm, clock, timer, kbus, gmmu, kgmmu, gcx, mc = (
0xd334df00, 0x8dd91100, 0x174e2100, 0xcc4c3100, 0x6c1e5600, 0xbcadd300, 0x9ddede00,
0xd2ac5700, 0xd7a41d00, 0x29362f00, 0x4507c400, 0x9aad0e00)
cases = [
("first-open", {}),
# NOT_SUPPORTED (0x56) from a PreInit callback removes the engine for good.
("pre-init-not-supported", {(graphics, "PreInitLocked"): 0x56,
(cipher, "PreInitUnlocked"): 0x56}),
("pre-init-unlocked-error", {(memsys, "PreInitUnlocked"): 0x51}),
("pre-init-locked-error", {(bus, "PreInitLocked"): 0x51}),
("init-not-supported", {(therm, "InitLocked"): 0x56, (clock, "InitUnlocked"): 0x56}),
("init-unlocked-error", {(timer, "InitUnlocked"): 0x51}),
("init-locked-error", {(kbus, "InitLocked"): 0x51}),
("pre-load-not-supported", {(gcx, "PreLoad"): 0x56}),
("pre-load-error", {(kbus, "PreLoad"): 0x51}),
("load-not-supported", {(therm, "Load"): 0x56}),
("load-error", {(gmmu, "Load"): 0x51}),
("post-load-not-supported", {(gcx, "PostLoad"): 0x56}),
("post-load-error", {(kgmmu, "PostLoad"): 0x51}),
]
del mc
lines = []
for name, statuses in cases:
produced, ran = case(name, statuses)
lines += produced
if "DEBUG" in sys.argv or "PRINT" in sys.argv:
print("\n".join(lines))
text = "\n".join(lines) + "\n"
write_or_check_text(OUT / "original-engine-dispatch.txt", text, check="--check" in sys.argv)
print(json.dumps({"oracle": "target/gpu-stage/original-engine-dispatch.txt",
"sha256": hashlib.sha256(text.encode()).hexdigest(),
"cases": len(cases), "lines": len(lines)}))
if __name__ == "__main__":
main()