mirror of
https://github.com/QuixiAI/nvdriver.git
synced 2026-12-06 06:28:39 +00:00
1081 lines
49 KiB
Python
1081 lines
49 KiB
Python
#!/usr/bin/env python3
|
|
"""Run the original GV100 Graphics StateLoad and write an oracle.
|
|
|
|
Executed original code. The whole object file is loaded and relocated, so no
|
|
callee is selected by hand; the function tables come from the original binders
|
|
and property initializers with chip HAL 0x23 and RM HAL 2.
|
|
"""
|
|
import bisect
|
|
from _binary_path import resolve_580_binary
|
|
import hashlib
|
|
import json
|
|
from pathlib import Path
|
|
import struct
|
|
import sys
|
|
import warnings
|
|
from _gpu_graphics_oracle_check import require
|
|
|
|
warnings.filterwarnings("ignore", category=UserWarning)
|
|
from capstone import CS_ARCH_X86, CS_MODE_64, Cs # noqa: E402
|
|
from elftools.elf.elffile import ELFFile # noqa: E402
|
|
from unicorn import UC_ARCH_X86, UC_HOOK_CODE, UC_MODE_64, Uc, UcError # noqa: E402
|
|
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 = resolve_580_binary()
|
|
DIGEST = "5269a23ffba19a17fe16f076463e7ad4151254659441d1711bee6c6221ff6f4b"
|
|
TRANSCRIPT = ROOT / "target/trace/b3-bar0.txt"
|
|
BASES = {".text": 0x10000000, ".data": 0x20000000, ".rodata": 0x30000000, ".bss": 0x38000000}
|
|
EXT, HEAP, OBJ, STACK, STOP = 0x08000000, 0x40000000, 0x48000000, 0x4c000000, 0x4d000000
|
|
HEAP_SIZE, OBJ_SIZE = 0x2000000, 0x200000
|
|
(GPU, GR, KGR, GRMGR, MEMSYS, KGMMU, GMMU, CHIP, RM, KMIG, MEMMGR, BUS, INFO, PARENT, MAPPING,
|
|
THREAD, LPWR, CHILD, FUSE, PGCTRL, KFIFO, OFIFO) = (OBJ + 0x10000 * index for index in range(22))
|
|
CONTINUE, FUSE_118, FUSE_100, ZBC_FA8, LOCK = (STOP + 0x100, STOP + 0x200, STOP + 0x210, STOP + 0x220,
|
|
STOP + 0x800)
|
|
MC = OBJ + 0x10000 * 22
|
|
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, "rdi": UC_X86_REG_RDI,
|
|
"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}
|
|
GPU_BINDERS = ("_nv005978rm", "_nv005980rm", "_nv005982rm", "_nv005984rm", "_nv005825rm")
|
|
# Class-level routines the bindings report lacks. _nv005687rm(object, RM, chip) stores the
|
|
# Graphics base-class pointers and vtables (+188..+1b8, among them the object at +1a0) and
|
|
# calls _nv005883rm, which binds the slots below +8c0 and calls _nv005886rm.._nv005890rm;
|
|
# _nv005936rm(object, chip) binds MemorySystem.
|
|
TOP_BINDERS = {"Graphics": "_nv005687rm", "MemorySystem": "_nv005936rm"}
|
|
# Three-argument binders that take (object, RM selector, chip selector); every other one
|
|
# takes (object, chip selector, RM selector). Found by varying each selector over 0..95 and
|
|
# counting distinct results (--binder-order repeats it): the chip selector is the one with
|
|
# many. reports/gv100-engine-hal-bindings.json ran these three with the selectors swapped.
|
|
RM_FIRST = ("_nv005782rm", "_nv005822rm", "_nv005812rm")
|
|
# Where the parent-class binder _nv005997rm is applied (reports/gv100-engine-hal-bindings-
|
|
# correction.json): the real callers pass this sub-object, not the engine object.
|
|
PARENT_OFFSET = {"Graphics": 0x100, "MemorySystem": 0x100, "OBJGMMU": 0xe8, "OBJBUS": 0xe8}
|
|
CLASSES = (("Graphics", GR), ("KernelGraphics", KGR), ("GraphicsManager", GRMGR),
|
|
("MemorySystem", MEMSYS), ("KernelGmmu", KGMMU), ("OBJGMMU", GMMU), ("OBJBUS", BUS),
|
|
("MemoryManager", MEMMGR), ("KernelFifo", KFIFO), ("OBJFIFO", OFIFO))
|
|
|
|
raw = ORIGINAL.read_bytes()
|
|
require(hashlib.sha256(raw).hexdigest() == DIGEST)
|
|
# Binders and property initializers per class, as this harness was validated with them
|
|
# (reports/gv100-engine-hal-bindings.json of 2026-11-19 before its regeneration). They are
|
|
# pinned here because that report is regenerated with other contents: it now also lists
|
|
# _nv005883rm and _nv005936rm, which TOP_BINDERS below already runs with the right selectors.
|
|
classes = {
|
|
"Graphics": (("_nv005886rm", "_nv005887rm", "_nv005888rm", "_nv005889rm", "_nv005890rm",
|
|
"_nv005997rm"), ("_nv005782rm",)),
|
|
"KernelGraphics": (("_nv005919rm",), ("_nv005795rm",)),
|
|
"GraphicsManager": (("_nv005885rm",), ("_nv005783rm",)),
|
|
"MemorySystem": (("_nv005937rm", "_nv005938rm", "_nv005939rm", "_nv005940rm",
|
|
"_nv005997rm"), ("_nv005807rm",)),
|
|
"KernelGmmu": (("_nv005914rm", "_nv005915rm"), ("_nv005794rm",)),
|
|
"OBJGMMU": (("_nv005975rm", "_nv005997rm"), ("_nv005822rm",)),
|
|
"OBJBUS": (("_nv005953rm", "_nv005997rm"), ("_nv005812rm",)),
|
|
"MemoryManager": (("_nv005935rm",), ("_nv005806rm",)),
|
|
"KernelFifo": (("_nv005912rm",), ("_nv005792rm",)),
|
|
"OBJFIFO": (("_nv005970rm", "_nv005971rm", "_nv005972rm"), ("_nv005820rm",)),
|
|
}
|
|
classes = {label: {"binders": list(binders), "property_binders": list(properties)}
|
|
for label, (binders, properties) in classes.items()}
|
|
snapshot = json.loads((ROOT / "reports/hardware-inventory-original-b3.json").read_text())["inventory"]
|
|
DEVICE_INFO = {int(key, 16): int(value, 16) for key, value in snapshot.items()
|
|
if int(key, 16) == 0x2004 or 0x2390 <= int(key, 16) < 0x23d0
|
|
or 0x22700 <= int(key, 16) < 0x22800}
|
|
|
|
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]
|
|
sizes = {name: size for address, size, name 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:
|
|
require(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)):
|
|
cpu.mem_map(base, size)
|
|
executed, calls = set(), []
|
|
state = {"heap": HEAP, "events": [], "continuations": [], "case": {}, "keys": []}
|
|
disassembler = Cs(CS_ARCH_X86, CS_MODE_64)
|
|
|
|
|
|
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 b(address):
|
|
return cpu.mem_read(address, 1)[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 & 0xff]))
|
|
|
|
|
|
def text(address):
|
|
return bytes(cpu.mem_read(address, 96)).split(b"\0")[0].decode()
|
|
|
|
|
|
def allocate(size, fill=0):
|
|
address = state["heap"]
|
|
state["heap"] += (size + 0x1f) & ~0xf
|
|
require(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 listing(address, count=5):
|
|
out = []
|
|
try:
|
|
code = bytes(cpu.mem_read(address, 16 * count))
|
|
except UcError:
|
|
return "(unmapped)"
|
|
for instruction in disassembler.disasm(code, address):
|
|
out.append(f"{instruction.address:#x} {instruction.mnemonic} {instruction.op_str}")
|
|
if len(out) >= count:
|
|
break
|
|
return "\n".join(out)
|
|
|
|
|
|
def disassemble(name):
|
|
"""Listing of one original function with direct call targets named."""
|
|
start = by_name[name]
|
|
names = {address: external for external, address in externals.items()}
|
|
out = []
|
|
for instruction in disassembler.disasm(bytes(cpu.mem_read(start, sizes[name])), start):
|
|
note = ""
|
|
if instruction.mnemonic in ("call", "jmp") and instruction.op_str.startswith("0x"):
|
|
target = int(instruction.op_str, 16)
|
|
callee = function_at(target) or names.get(target)
|
|
if callee and (callee != name or instruction.mnemonic == "call"):
|
|
note = " ; " + callee
|
|
out.append(f"{instruction.address - start:5x} {instruction.mnemonic} "
|
|
f"{instruction.op_str}{note}")
|
|
return "\n".join(out)
|
|
|
|
|
|
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)
|
|
try:
|
|
cpu.emu_start(target if isinstance(target, int) else by_name[target], STOP)
|
|
except UcError as error:
|
|
pc = cpu.reg_read(UC_X86_REG_RIP)
|
|
registers = {name: hex(cpu.reg_read(register)) for name, register in THUNKS.items()}
|
|
raise RuntimeError(f"{error} at {pc:#x} {function_at(pc)}\ncalls {calls[-16:]}\n"
|
|
f"events {state['events'][-12:]}\n{registers}\n{listing(pc)}") from error
|
|
require(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 pop(name, default):
|
|
values = state["case"].get(name)
|
|
return values.pop(0) if values else default
|
|
|
|
|
|
def read_value(offset):
|
|
if state.get("phase") == "table" and offset in DEVICE_INFO:
|
|
return DEVICE_INFO[offset]
|
|
values = state["case"].get("reads", {}).get(offset)
|
|
if values:
|
|
value = values.pop(0) if len(values) > 1 else values[0]
|
|
else:
|
|
value = state["case"].get("default_read", lambda unused: 0)(offset)
|
|
emit(f"r:{offset:x}:{value:x}")
|
|
return value
|
|
|
|
|
|
def read_register(a):
|
|
require((a[0], a[1] & 0xffffffff, a[2] & 0xffffffff) == (GPU + 0x4120, 0, 0))
|
|
return read_value(a[3] & 0xffffffff)
|
|
|
|
|
|
def write_register(a):
|
|
require((a[0], a[1] & 0xffffffff, a[2] & 0xffffffff) == (GPU + 0x4120, 0, 0))
|
|
emit(f"w:{a[3] & 0xffffffff:x}:{a[4] & 0xffffffff:x}")
|
|
return 0
|
|
|
|
|
|
def mapped_read(a):
|
|
"""_nv049612rm(gpu, mapping, offset): the 32-bit read of a register object."""
|
|
require((a[0], a[1]) == (GPU, MAPPING))
|
|
return read_value(a[2] & 0xffffffff)
|
|
|
|
|
|
def mapped_write(a):
|
|
require((a[0], a[1]) == (GPU, MAPPING))
|
|
emit(f"w:{a[2] & 0xffffffff:x}:{a[3] & 0xffffffff:x}")
|
|
return 0
|
|
|
|
|
|
def diagnostic(a):
|
|
emit(f"e:{a[0] & 0xffffffff:x}:{a[1] & 0xffffffff:x}")
|
|
if "DEBUG" in sys.argv:
|
|
print("diagnostic", f"{a[0] & 0xffffffff:x}:{a[1] & 0xffffffff:x}", calls[-6:])
|
|
return 0
|
|
|
|
|
|
def registry(a):
|
|
key = text(a[1])
|
|
state["keys"].append(key)
|
|
value = state["case"].get("registry", {}).get(key)
|
|
if value is None:
|
|
return 0x57
|
|
wd(a[2], value)
|
|
return 0
|
|
|
|
|
|
def fuse_query(a):
|
|
"""The function at +118 of the GPU+1e78 object: (gpu, object, id, &value)."""
|
|
identifier = a[2] & 0xffffffff
|
|
status, value = state["case"].get("fuse_query", {}).get(identifier, (0, 0))
|
|
emit(f"fq:{identifier:x}:{status:x}:{value:x}")
|
|
wd(a[3], value)
|
|
return status
|
|
|
|
|
|
def fuse_read(a):
|
|
"""The function at +100 of the GPU+1e78 object: (gpu, object, offset, &value, 0)."""
|
|
offset = a[2] & 0xffffffff
|
|
value = state["case"].get("fuse", {}).get(offset, 0)
|
|
emit(f"fr:{offset:x}:{value:x}")
|
|
wd(a[3], value)
|
|
return 0
|
|
|
|
|
|
def in_objects(address):
|
|
return OBJ <= address < OBJ + OBJ_SIZE or HEAP <= address < HEAP + HEAP_SIZE
|
|
|
|
|
|
HANDLERS = {
|
|
"_nv053907rm": read_register, "_nv053912rm": write_register,
|
|
"_nv049612rm": mapped_read, "_nv049615rm": mapped_write,
|
|
"_nv047869rm": diagnostic, "_nv047868rm": diagnostic, "_nv047867rm": diagnostic,
|
|
"_nv046745rm": lambda a: emit(f"A:{a[0] & 0xffffffff:x}") or 0,
|
|
"_nv046747rm": lambda a: emit(f"S:{a[0] & 0xffffffff:x}:{a[1] & 0xffffffff:x}") or 0,
|
|
"_nv046752rm": lambda a: emit(f"S:{a[1] & 0xffffffff:x}:{a[2] & 0xffffffff:x}") or 0,
|
|
"_nv046751rm": lambda a: emit(f"A:{a[1] & 0xffffffff:x}") or 0,
|
|
"_nv049765rm": lambda a: 0,
|
|
"_nv052691rm": lambda a: LOCK, "_nv060222rm": lambda a: 0,
|
|
"_nv052687rm": lambda a: allocate(a[0], 0xcc), "_nv052701rm": lambda a: 0,
|
|
"_nv052705rm": lambda a: cpu.mem_write(a[0], bytes([a[1] & 0xff]) * (a[2] & 0xffffffff)) or a[0],
|
|
"_nv052695rm": lambda a: cpu.mem_write(a[0], bytes(cpu.mem_read(a[2], a[3] & 0xffffffff))) or a[0],
|
|
"_nv052744rm": lambda a: LOCK, "_nv052743rm": lambda a: 0, "_nv052747rm": lambda a: 0,
|
|
"_nv049786rm": registry, "_nv049788rm": registry, "_nv049789rm": registry,
|
|
"_nv049785rm": registry,
|
|
"_nv049086rm": lambda a: GPU,
|
|
"_nv005245rm": lambda a: a[0] if in_objects(a[0]) else None,
|
|
"_nv031426rm": lambda a: GPU, "_nv031395rm": lambda a: 1, "_nv031478rm": lambda a: 0,
|
|
"_nv031482rm": lambda a: 0,
|
|
"_nv059517rm": lambda a: 0, "_nv059516rm": lambda a: 0x7151,
|
|
# Below the register object's access: loop check, sanity check, thread, filters.
|
|
"_nv031391rm": lambda a: 0, "_nv031156rm": lambda a: 0, "_nv031155rm": lambda a: 0,
|
|
"_nv059477rm": lambda a: wq(a[0], THREAD) or 0,
|
|
"_nv013540rm": lambda a: wd(q(cpu.reg_read(UC_X86_REG_RSP) + 8), 0) or 0,
|
|
"_nv013539rm": lambda a: wd(a[5], 0) or 0,
|
|
# Cross-object services.
|
|
"_nv000260rm": lambda a: emit("vbios-260") or 0,
|
|
"_nv019166rm": lambda a: emit(f"lpwr-166:{a[2] & 0xffffffff:x}") or 0,
|
|
"_nv019141rm": lambda a: wb(a[3], 0) or 0, "_nv019282rm": lambda a: 0,
|
|
}
|
|
|
|
|
|
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)
|
|
|
|
|
|
def hook(name, handler):
|
|
HANDLERS[name] = handler
|
|
install(externals[name] if name in externals else by_name[name], handler)
|
|
|
|
|
|
for name, handler in list(HANDLERS.items()):
|
|
install(externals[name] if name in externals else by_name[name], handler)
|
|
install(FUSE_118, fuse_query)
|
|
install(FUSE_100, fuse_read)
|
|
# MemorySystem+fa8 (_nv045299rm), the ZBC table service: (gpu, memory system, argument).
|
|
def zbc_service(a):
|
|
require(b(GR + 0x1593) == 1)
|
|
emit(f"zbc:{a[2] & 0xffffffff:x}")
|
|
return 0
|
|
|
|
|
|
install(ZBC_FA8, zbc_service)
|
|
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):
|
|
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)
|
|
|
|
|
|
FRAMES = []
|
|
|
|
|
|
def record_function(emu, address, size, unused):
|
|
name = function_at(address)
|
|
if name and address == by_name.get(name):
|
|
executed.add(name)
|
|
calls.append(name)
|
|
del calls[:-64]
|
|
# Frames whose entry stack pointer is not above this one have returned.
|
|
rsp = emu.reg_read(UC_X86_REG_RSP)
|
|
while FRAMES and FRAMES[-1][1] <= rsp:
|
|
FRAMES.pop()
|
|
FRAMES.append((name, rsp))
|
|
|
|
|
|
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(f"unexpected external {name} after {calls[-8:]}")
|
|
|
|
|
|
cpu.hook_add(UC_HOOK_CODE, unexpected, begin=EXT, end=EXT + 0x10000)
|
|
TRACE_HOOK = [None]
|
|
|
|
|
|
def trace_functions(enable):
|
|
if enable and TRACE_HOOK[0] is None:
|
|
TRACE_HOOK[0] = cpu.hook_add(UC_HOOK_CODE, record_function, begin=BASES[".text"],
|
|
end=BASES[".text"] + len(sections[".text"]))
|
|
elif not enable and TRACE_HOOK[0] is not None:
|
|
cpu.hook_del(TRACE_HOOK[0])
|
|
TRACE_HOOK[0] = None
|
|
|
|
|
|
PRISTINE = {name: bytes(sections[name]) for name in (".data", ".bss")}
|
|
# Register words of the physical V100. Geometry words read by InitLocked are taken from the
|
|
# same reads KernelGraphics PostLoad repeats (transcript lines 166291-166353); the fuse words
|
|
# are the reads of register 0x21000 + offset there.
|
|
V100_GEOMETRY = {0x200: [0x1fecdff1]}
|
|
for gpc, word in enumerate((0x49, 0x49, 0x49, 9, 0x49, 9)):
|
|
V100_GEOMETRY[0x500c30 + 0x8000 * gpc] = [word]
|
|
V100_GEOMETRY[0x500c34 + 0x8000 * gpc] = [0x12]
|
|
V100_GEOMETRY[0x500c38 + 0x8000 * gpc] = [0x24]
|
|
# Not in the transcript (lost events of Init): both counts of the word, see the report.
|
|
V100_GEOMETRY[0x502608 + 0x8000 * gpc] = [0x40007 if word == 0x49 else 0x40006]
|
|
V100_FUSE = {0xc38 + 4 * 3: 1, 0xc38 + 4 * 5: 1}
|
|
V100_BUS = (6, 6, 7, 42) # _nv018541rm from 0x120078, 0x22430, 0x22434 (lines 37600-37603)
|
|
V100_BUFFERS = (0x7fdf80000, 0x7fdf90000, 0x10000) # KernelGmmu+410, +408 and their size
|
|
|
|
|
|
def memory_descriptor(address, size, space=2):
|
|
"""A descriptor made by the original _nv043694rm and described with _nv043698rm."""
|
|
slot = allocate(8)
|
|
require(call("_nv043694rm", slot, GPU, size, 0x1000, 1, space, stack=(2, 0)) & 0xffffffff == 0)
|
|
call("_nv043698rm", q(slot), space, address, size)
|
|
return q(slot)
|
|
|
|
|
|
def default_case():
|
|
return dict(reads={key: list(value) for key, value in V100_GEOMETRY.items()},
|
|
default_read=lambda offset: 0, registry={}, fuse=dict(V100_FUSE), fuse_query={},
|
|
bus=V100_BUS, buffers=V100_BUFFERS, gpu={0x911: 1}, flags=0)
|
|
|
|
|
|
def construct(case):
|
|
"""Objects as creation, the binders, the constructors, PreInit and InitLocked 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=[], continuations=[], case=case, keys=[], real=True)
|
|
wq(GPU + 0x80, CHIP)
|
|
wq(GPU + 0x88, RM)
|
|
for binder in GPU_BINDERS:
|
|
call(binder, GPU, CHIP, RM)
|
|
for label, base in CLASSES:
|
|
if label in TOP_BINDERS:
|
|
call(TOP_BINDERS[label], base, RM if label == "Graphics" else CHIP, CHIP)
|
|
for binder in classes[label]["binders"] + classes[label]["property_binders"]:
|
|
# The parent-class binder takes the parent sub-object, as its real callers pass it.
|
|
target = base + PARENT_OFFSET.get(label, 0) if binder == "_nv005997rm" else base
|
|
call(binder, target, *((RM, CHIP) if binder in RM_FIRST else (CHIP, RM)))
|
|
for offset, target in ((0x1fb8, GRMGR), (0x1fd8, GR), (0x2018, KGR), (0x1ec0, MEMSYS),
|
|
(0x1f88, KGMMU), (0x1f90, GMMU), (0x1f78, BUS), (0x1ed0, MEMMGR),
|
|
(0x1e78, FUSE), (0x1d30, PARENT), (0x22c8, LPWR), (0x22d0, KFIFO),
|
|
(0x22d8, OFIFO)):
|
|
wq(GPU + offset, target)
|
|
# The engine table from the device-info registers of the physical V100.
|
|
state["phase"] = "table"
|
|
require(call(q(KFIFO + 0x1a8), GPU, KFIFO) & 0xffffffff == 0)
|
|
state["phase"] = "init"
|
|
require(function_at(q(MEMSYS + 0xfa8)) == "_nv045299rm")
|
|
wq(MEMSYS + 0xfa8, ZBC_FA8)
|
|
wq(GPU + 0x1ea0, MC)
|
|
wq(FUSE + 0x118, FUSE_118)
|
|
wq(FUSE + 0x100, FUSE_100)
|
|
# The parent register aperture (GPU+1d30) the Graphics register objects are cut from.
|
|
wq(PARENT + 0x60, GPU)
|
|
wd(PARENT + 0x68, 0x11)
|
|
wd(PARENT + 0x6c, 0x22)
|
|
wq(PARENT + 0x70, MAPPING)
|
|
wd(PARENT + 0x80, 0x1000000)
|
|
# The Lpwr object as its property initializers leave it.
|
|
call("_nv005803rm", LPWR, CHIP, RM)
|
|
call("_nv005773rm", CHILD, CHIP, RM)
|
|
wq(LPWR + 0x11d8, CHILD)
|
|
wq(LPWR + 0x11c0, PGCTRL)
|
|
# The constructor of the base object at Graphics+100 (the +1a0 pointer): +38 = -1.
|
|
require(q(GR + 0x1a0) == GR + 0x100)
|
|
require(call("_nv037808rm", GR + 0x100) & 0xffffffff == 0)
|
|
stages = {}
|
|
for name, arguments in (("_nv033946rm", (GPU, GRMGR, 0)),):
|
|
stages[name] = call(name, *arguments) & 0xffffffff
|
|
call("_nv034073rm", GPU, GRMGR, *case["bus"])
|
|
for name, arguments in (("_nv031719rm", (GPU, GR, 0)), ("_nv033667rm", (GPU, GR)),
|
|
("_nv034082rm", (GPU, GRMGR)), ("_nv033663rm", (GPU, GR))):
|
|
state["events"].append(f"stage:{name}")
|
|
stages[name] = call(name, *arguments) & 0xffffffff
|
|
first, second, size = case["buffers"]
|
|
wq(KGMMU + 0x410, memory_descriptor(first, size))
|
|
wq(KGMMU + 0x408, memory_descriptor(second, size))
|
|
return stages
|
|
|
|
|
|
def transcript_range(first, last):
|
|
lines = TRANSCRIPT.read_text().split("\n")[first - 1:last]
|
|
reads, tokens = {}, []
|
|
for line in lines:
|
|
kind, offset, value = line.split()[:3]
|
|
offset, value = int(offset, 16), int(value, 16)
|
|
tokens.append(f"{kind.lower()}:{offset:x}:{value:x}")
|
|
if kind == "R":
|
|
reads.setdefault(offset, []).append(value)
|
|
return reads, tokens
|
|
|
|
|
|
def fixture(name, handler):
|
|
"""A service that is fixture-supplied in the oracle rows and original in the traced case."""
|
|
hook(name, lambda a: None if state.get("real") else handler(a))
|
|
|
|
|
|
def engine_busy(a):
|
|
"""_nv027871rm(gpu, fifo, engine, 0, &busy, 0): the FIFO engine status query."""
|
|
require(a[2] & 0xffffffff == 0xd334df00)
|
|
status, busy = pop("busy_status", 0), pop("busy", 0)
|
|
if status == 0:
|
|
# The original stores the answer only when its engine lookups succeed.
|
|
wb(a[4], busy)
|
|
emit(f"busy:{status:x}:{busy:x}")
|
|
return status
|
|
|
|
|
|
def overrides(a):
|
|
"""_nv000194rm(gpu, out): the VBIOS table of register overrides."""
|
|
status, version, count = state["case"]["vbios"]
|
|
if status == 0:
|
|
wd(a[1], version)
|
|
wd(a[1] + 4, count)
|
|
emit(f"vb:{status:x}:{version:x}:{count:x}")
|
|
return status
|
|
|
|
|
|
def timeout_check(a):
|
|
require(a[0] == GPU + 0x1e08)
|
|
status = pop("check", 0)
|
|
state["checks"] += 1
|
|
require(state["checks"] < 4000, "the case never ends its wait")
|
|
emit(f"tc:{a[2] & 0xffffffff:x}:{status:x}")
|
|
return status
|
|
|
|
|
|
fixture("_nv027871rm", engine_busy)
|
|
fixture("_nv033505rm", lambda a: emit("cg") or 0)
|
|
fixture("_nv027641rm", lambda a: emit("f641") or 0)
|
|
fixture("_nv029884rm", lambda a: emit("g80") or 0)
|
|
hook("_nv000194rm", overrides)
|
|
hook("_nv059509rm", lambda a: emit("ts") or 0)
|
|
hook("_nv059505rm", timeout_check)
|
|
hook("_nv049819rm", lambda a: emit("y") or 0)
|
|
hook("_nv033180rm", lambda a: emit("wt") or 0)
|
|
hook("_nv032687rm", lambda a: emit("dump") or 0)
|
|
hook("_nv042917rm", lambda a: emit(f"lp:{state['case']['lpwr_supported']:x}")
|
|
or state["case"]["lpwr_supported"])
|
|
HANDLERS["_nv045299rm (MemorySystem+fa8)"] = None
|
|
|
|
CACHE = {}
|
|
GPU_BYTES = (0x911, 0x52fc, 0x90e, 0xe00, 0x948, 0x915, 0x917, 0x918, 0x919, 0x926)
|
|
GR_BYTES = (0x160c, 0x15a2, 0x15c9, 0x15ca, 0x15e5, 0x18d4, 0x50)
|
|
PROPERTIES = tuple(range(0x28b, 0x295))
|
|
FLAGS = (0x20, 0x21, 0x22, 0x110, 0x111, 0x112, 0xe8, 0xe9, 0xea, 0x138, 0x139, 0x13a, 0x160, 0x161,
|
|
0x162)
|
|
|
|
|
|
def grinfo():
|
|
return call("_nv029329rm", q(GR + 0x15f8), 0x18)
|
|
|
|
|
|
def prepare(case):
|
|
key = (tuple(sorted((offset, tuple(values)) for offset, values in case["reads"].items()
|
|
if offset in V100_GEOMETRY and offset != 0x200)),
|
|
tuple(sorted(case["fuse"].items())), case["bus"], case["buffers"])
|
|
if key not in CACHE:
|
|
geometry = dict(case, reads={offset: list(values) for offset, values in
|
|
case["reads"].items() if offset in V100_GEOMETRY})
|
|
geometry["reads"][0x200] = list(V100_GEOMETRY[0x200])
|
|
stages = construct(geometry)
|
|
require(not any(stages.values()), stages)
|
|
CACHE[key] = (bytes(cpu.mem_read(OBJ, OBJ_SIZE)),
|
|
bytes(cpu.mem_read(HEAP, state["heap"] - HEAP)), state["heap"],
|
|
{name: bytes(cpu.mem_read(BASES[name], len(sections[name])))
|
|
for name in (".data", ".bss")}, list(state["events"]))
|
|
objects, heap, top, data, preparation = CACHE[key]
|
|
cpu.mem_write(OBJ, objects)
|
|
cpu.mem_write(HEAP, heap)
|
|
for name, content in data.items():
|
|
cpu.mem_write(BASES[name], content)
|
|
state.update(heap=top, events=[], continuations=[], case=case, keys=[], phase="load",
|
|
checks=0, preparation=preparation, real=case.get("real", False))
|
|
for offset, value in case["gpu"].items():
|
|
wb(GPU + offset, value)
|
|
for offset, value in case["gr"].items():
|
|
wb(GR + offset, value)
|
|
for offset, value in case["grmgr"].items():
|
|
wb(GRMGR + offset, value)
|
|
block = grinfo()
|
|
for offset, value in case["grinfo"].items():
|
|
wd(block + offset, value)
|
|
for (gpc, offset), value in case["records"].items():
|
|
wd(q(block + 0x570) + 0x1f0 * gpc + offset, value)
|
|
wd(GR + 0x138, case["base_38"])
|
|
wb(q(GR + 0x15e8) + 0x1f8, case["fecs_running"])
|
|
wd(q(GRMGR + 0x2b0) + 0x25c, case["done_mask"])
|
|
if not case["mc"]:
|
|
wq(GPU + 0x1ea0, 0)
|
|
if not case["lpwr"]:
|
|
wq(GPU + 0x22c8, 0)
|
|
case["reads"] = {offset: values for offset, values in case["reads"].items()
|
|
if offset not in V100_GEOMETRY or offset == 0x200}
|
|
return block
|
|
|
|
|
|
def inputs_of(case, block):
|
|
"""The state the load reads, as the preparation left it and the case changed it."""
|
|
records = q(block + 0x570)
|
|
count = call(q(GR + 0xc78), GPU, GR) & 0xffffffff
|
|
total = d(block + 0x554)
|
|
buffers = []
|
|
for slot in (0x410, 0x408):
|
|
descriptor = q(KGMMU + slot)
|
|
buffers.append("%x:%x:%x:%x" % (call("_nv043721rm", descriptor, 1, 0),
|
|
call("_nv040815rm", GMMU, descriptor) & 0xff,
|
|
call("_nv043734rm", descriptor) & 0xffffffff,
|
|
q(descriptor + 0x30)))
|
|
words = ((call(q(GPU + 0x420), GPU, 0x14) & 0xffffffff)
|
|
* (call(q(GPU + 0x420), GPU, 0x17) & 0xffffffff) + 7) >> 3
|
|
state["events"].clear()
|
|
return [f"{case['flags']:x}", " ".join(f"{b(GPU + offset):x}" for offset in GPU_BYTES),
|
|
" ".join(f"{b(GR + offset):x}" for offset in GR_BYTES),
|
|
"%x %x %x %x" % (d(GR + 0x138), d(GR + 0x188c), b(q(GR + 0x15e8) + 0x1f8),
|
|
d(q(GRMGR + 0x2b0) + 0x25c)),
|
|
" ".join(f"{d(block + offset):x}" for offset in (0x528, 0x544, 0x548, 0x554, 0x55c)),
|
|
" ".join("%x:%x:%x:%x" % tuple(d(records + 0x1f0 * gpc + offset)
|
|
for offset in (0, 4, 8, 0x1c)) for gpc in range(count)),
|
|
bytes(cpu.mem_read(q(block + 0x538), max(total, 1))).hex(), f"{words:x}",
|
|
" ".join(buffers), " ".join(f"{b(GRMGR + offset):x}" for offset in PROPERTIES),
|
|
"%x %x %x" % (int(case["mc"]), int(case["lpwr"]), b(LPWR + 0x272))]
|
|
|
|
|
|
rows = []
|
|
|
|
|
|
def listed(values):
|
|
return "/".join(f"{value:x}" for value in values) or "-"
|
|
|
|
|
|
def default_load():
|
|
case = default_case()
|
|
case.update(gr={}, grmgr={}, grinfo={}, records={}, base_38=0xffffffff, fecs_running=0,
|
|
done_mask=0, mc=True, lpwr=True, lpwr_supported=0, vbios=(0xffff, 0, 0),
|
|
check=[], busy=[], busy_status=[], entry="_nv033298rm")
|
|
return case
|
|
|
|
|
|
def run(kind, **changes):
|
|
case = default_load()
|
|
case.update(changes)
|
|
case["reads"] = {**default_load()["reads"], **changes.get("reads", {})}
|
|
case["gpu"] = {**default_load()["gpu"], **changes.get("gpu", {})}
|
|
block = prepare(case)
|
|
fields = inputs_of(case, block)
|
|
entry = case["entry"]
|
|
if entry == "_nv033298rm":
|
|
timeout = allocate(0x40)
|
|
status = call(entry, GPU, GR, timeout, 1) & 0xffffffff
|
|
else:
|
|
status = call(entry, GPU, GR, case["flags"]) & 0xffffffff
|
|
require(not state["continuations"])
|
|
events = list(state["events"])
|
|
info = q(GRMGR + 0x2b0)
|
|
outputs = ([f"{b(info + offset):x}" for offset in FLAGS]
|
|
+ [f"{b(KGR + 0x1a9):x}", f"{d(block + 0x608):x}", f"{b(block + 0x614):x}",
|
|
f"{b(GR + 0x1593):x}", f"{d(GR + 0x1620):x}", f"{b(GR + 0x1591):x}"])
|
|
kept = [event for event in events if event[0] not in "eAS" or event[1] != ":"]
|
|
rows.append(f"{kind};" + ";".join(fields) + f";{status:x};" + " ".join(outputs) + ";"
|
|
+ " ".join(kept))
|
|
return case, status, events
|
|
|
|
|
|
def transcript_case():
|
|
reads, tokens = transcript_range(FIRST_LINE, LAST_LINE)
|
|
return reads, tokens
|
|
|
|
|
|
FIRST_LINE, LAST_LINE = 156720, 158348
|
|
ZBC_LINES = (157715, 158241) # the MemorySystem+fa8 service of the traced run
|
|
|
|
|
|
class Random:
|
|
"""Deterministic values for the register words."""
|
|
|
|
def __init__(self, seed):
|
|
self.state = seed
|
|
|
|
def word(self):
|
|
self.state = (self.state * 6364136223846793005 + 1442695040888963407) & (1 << 64) - 1
|
|
return self.state >> 32
|
|
|
|
def pick(self, values):
|
|
return values[self.word() % len(values)]
|
|
|
|
|
|
def tracked_run(case_changes, hooks):
|
|
"""One run with unicorn memory hooks installed for its duration."""
|
|
handles = [cpu.hook_add(kind, callback, begin=low, end=high)
|
|
for kind, callback, low, high in hooks]
|
|
try:
|
|
return run("-", **case_changes)
|
|
finally:
|
|
rows.pop()
|
|
for handle in handles:
|
|
cpu.hook_del(handle)
|
|
|
|
|
|
def hashed(seed):
|
|
def value(offset):
|
|
word = (offset * 0x9e3779b1 ^ seed * 0x85ebca6b) & 0xffffffff
|
|
word ^= word >> 15
|
|
return (word * 0x2c1b3c6d) & 0xffffffff
|
|
return value
|
|
|
|
|
|
def geometry(words, fuse):
|
|
"""Register words of InitLocked for per-GPC TPC counts `words` and fuse words `fuse`."""
|
|
reads = {key: list(value) for key, value in V100_GEOMETRY.items()}
|
|
for gpc, word in enumerate(words):
|
|
reads[0x502608 + 0x8000 * gpc] = [word]
|
|
return dict(reads=reads, fuse=dict(fuse))
|
|
|
|
|
|
def main():
|
|
require(pop("check", 0) == 0)
|
|
# The traced V100: every body original except time, diagnostics, the VBIOS table, the
|
|
# LPWR query and the MemorySystem ZBC service.
|
|
reads, tokens = transcript_case()
|
|
trace_functions(True)
|
|
touched = {}
|
|
|
|
def note_read(emu, access, address, size, value, unused):
|
|
for label, base, length in regions:
|
|
if base <= address < base + length:
|
|
touched.setdefault(label, set()).add(address - base)
|
|
return
|
|
regions = []
|
|
case = default_load()
|
|
block = prepare(dict(case))
|
|
info, records = q(GRMGR + 0x2b0), q(block + 0x570)
|
|
regions[:] = [("GRinfo", block, 0x620), ("GRMgr record (+2b0)", info, 0x260),
|
|
("GPC records (GRinfo+570)", records, 6 * 0x1f0),
|
|
("FECS object (Graphics+15e8)", q(GR + 0x15e8), 0x200), ("GPU", GPU, 0x8000),
|
|
("Graphics", GR, 0x4600), ("KernelGraphics", KGR, 0x400),
|
|
("GraphicsManager", GRMGR, 0x700), ("MemorySystem", MEMSYS, 0x9000),
|
|
("KernelGmmu", KGMMU, 0x500), ("Lpwr (GPU+22c8)", LPWR, 0x1200)]
|
|
from unicorn import UC_HOOK_MEM_READ, UC_HOOK_MEM_WRITE
|
|
state["paths"] = None
|
|
v100 = dict(real=True, entry="_nv033665rm", reads={**default_case()["reads"], **reads})
|
|
paths = []
|
|
original_emit = globals()["emit"]
|
|
|
|
def emit_with_path(token):
|
|
original_emit(token)
|
|
rsp = cpu.reg_read(UC_X86_REG_RSP)
|
|
paths.append((token, tuple(name for name, entry in FRAMES if entry > rsp)))
|
|
globals()["emit"] = emit_with_path
|
|
del FRAMES[:]
|
|
case, status, physical = tracked_run(
|
|
v100, [(UC_HOOK_MEM_READ, note_read, OBJ, OBJ + OBJ_SIZE - 1),
|
|
(UC_HOOK_MEM_READ, note_read, HEAP, HEAP + HEAP_SIZE - 1)])
|
|
globals()["emit"] = original_emit
|
|
trace_functions(False)
|
|
load_executed = sorted(executed - {name for name in HANDLERS if name in by_name
|
|
and name not in ("_nv027871rm", "_nv033505rm",
|
|
"_nv027641rm", "_nv029884rm")})
|
|
paths = paths[-len(physical):]
|
|
require([token for token, path in paths] == physical)
|
|
registers = [event for event in physical if event[0] in "rw" and event[1] == ":"]
|
|
service = physical.index("zbc:0") if "zbc:0" in physical else None
|
|
require(status == 0 and service is not None)
|
|
before = sum(1 for event in physical[:service] if event[0] in "rw" and event[1] == ":")
|
|
zbc = ZBC_LINES[1] - ZBC_LINES[0] + 1
|
|
require(before == ZBC_LINES[0] - FIRST_LINE, before)
|
|
require(registers == tokens[:before] + tokens[before + zbc:], "transcript")
|
|
require(not any(event[0] in "eAS" and event[1] == ":" for event in physical))
|
|
# Attribution of every transcript line to the original call path that made it.
|
|
steps, line, previous, start = [], FIRST_LINE, None, FIRST_LINE
|
|
for token, path in paths:
|
|
if token == "zbc:0":
|
|
key, width = ("MemorySystem+fa8 service (_nv045299rm, fixture)",), zbc
|
|
elif token[0] in "rw" and token[1] == ":":
|
|
names = [name for name in path if name not in HANDLERS]
|
|
for anchor in ("_nv033298rm", "_nv033664rm"):
|
|
if anchor in names:
|
|
names = names[names.index(anchor):]
|
|
break
|
|
names = [name for name in names if name not in (
|
|
"_nv003744rm", "_nv003747rm", "_nv037843rm", "_nv037846rm", "_nv037850rm",
|
|
"_nv037851rm")]
|
|
key, width = tuple(names[:2]), 1
|
|
else:
|
|
continue
|
|
if key != previous:
|
|
if previous is not None:
|
|
steps.append([start, line - 1, " > ".join(previous)])
|
|
previous, start = key, line
|
|
line += width
|
|
steps.append([start, line - 1, " > ".join(previous)])
|
|
require(line - 1 == LAST_LINE)
|
|
merged = []
|
|
for first, last, path in steps:
|
|
# Collapse the per-TPC repetition of the GPC loop into one entry per run of paths.
|
|
if merged and merged[-1][2] == path:
|
|
merged[-1][1] = last
|
|
elif (len(merged) >= 3 and merged[-3][2] == path and "(repeats" in merged[-1][3]):
|
|
merged[-1][1] = last
|
|
else:
|
|
merged.append([first, last, path, ""])
|
|
transcript = {"lines": f"{FIRST_LINE}-{LAST_LINE}", "register_accesses": len(tokens),
|
|
"equal": True, "original_register_events": len(registers),
|
|
"zbc_service_lines": "%d-%d" % ZBC_LINES, "zbc_service_line_count": zbc}
|
|
rows.append("V;" + " ".join(physical))
|
|
fields_read = {label: sorted(offsets) for label, offsets in touched.items()}
|
|
|
|
# Which original instructions store the class-enable bytes Graphics+1608..160f.
|
|
stores = []
|
|
|
|
def note_store(emu, access, address, size, value, unused):
|
|
pc = emu.reg_read(UC_X86_REG_RIP)
|
|
stores.append([function_at(pc), f"+{address - GR:#x}", size, f"{value:#x}",
|
|
state.get("stage", "binders")])
|
|
handle = cpu.hook_add(UC_HOOK_MEM_WRITE, note_store, begin=GR + 0x1608, end=GR + 0x160f)
|
|
CACHE.clear()
|
|
prepare(default_load())
|
|
cpu.hook_del(handle)
|
|
class_enable_stores = [entry for entry in stores if entry[0]]
|
|
|
|
# The same traced inputs with the first class-enable byte (Graphics+160c) cleared by hand.
|
|
# No original GV100 path does that (see class_enable_stores); this shows what the byte gates.
|
|
case, status, compute = tracked_run(dict(v100, gr={0x160c: 0}), [])
|
|
require(status == 0 and "zbc:0" not in compute)
|
|
compute_registers = [event for event in compute if event[0] in "rw" and event[1] == ":"]
|
|
|
|
def written(events):
|
|
return {int(event.split(":")[1], 16) for event in events if event.startswith("w:")}
|
|
dropped = sorted(written(registers) - written(compute_registers))
|
|
require(not written(compute_registers) - written(registers))
|
|
position, skipped = 0, 0
|
|
for event in registers:
|
|
if position < len(compute_registers) and compute_registers[position] == event:
|
|
position += 1
|
|
else:
|
|
skipped += 1
|
|
require(position == len(compute_registers), "the reduced sequence is not a subsequence")
|
|
compute_only = {
|
|
"how": "Graphics+160c written 0 by the fixture before _nv033665rm; no original GV100 "
|
|
"path stores 0 there",
|
|
"register_events": len(compute_registers),
|
|
"traced_events_without_the_zbc_service": len(registers),
|
|
"is_a_subsequence_of_the_traced_events": True, "events_removed": skipped,
|
|
"zbc_service_called": False,
|
|
"registers_no_longer_written": [f"{offset:#x}" for offset in dropped]}
|
|
|
|
random = Random(0x33298)
|
|
# S: the whole StateLoad with its Falcon and clock-gating children as fixtures.
|
|
for flags in (0, 1, 2, 3, 0xfffffffb):
|
|
for done_mask in (0, 1, 2, 0xffffffff):
|
|
run("S", entry="_nv033665rm", flags=flags, done_mask=done_mask)
|
|
for changes in (dict(base_38=0), dict(gr={0x160c: 0}), dict(mc=False),
|
|
dict(gr={0x15e5: 0}, gpu={0x911: 0})):
|
|
run("S", entry="_nv033665rm", **changes)
|
|
# I: _nv033298rm(gpu, graphics, timeout, 1).
|
|
for three_d in (1, 0):
|
|
for gpu_911 in (1, 0):
|
|
for gpu_52fc in (0, 1):
|
|
run("I", gr={0x160c: three_d}, gpu={0x911: gpu_911, 0x52fc: gpu_52fc})
|
|
for changes in (dict(gr={0x15a2: 0}), dict(base_38=0), dict(base_38=5),
|
|
dict(base_38=0xfffffffe), dict(mc=False), dict(lpwr=False),
|
|
dict(mc=False, lpwr=False), dict(mc=False, gr={0x160c: 0}),
|
|
dict(grinfo={0x528: 0xffff00ff}, reads={0x400610: [0x12345678]}),
|
|
dict(grinfo={0x528: 1}, gr={0x160c: 0}),
|
|
dict(grinfo={0x544: 0xffffffff}), dict(grinfo={0x544: 0x12}),
|
|
dict(grmgr={0x294: 1})):
|
|
run("I", **changes)
|
|
for vbios in ((0, 0x10, 0), (0, 0x1f, 5), (0, 0x20, 0), (0, 0xffffffff, 0), (0x56, 0, 0),
|
|
(0x40, 0x20, 3)):
|
|
run("I", vbios=vbios)
|
|
# The two KernelGmmu buffers.
|
|
for first, second, size in ((0x7fdf80000, 0x7fdf90000, 0x1000), (0x1000, 0x7ffffff000, 0x20000),
|
|
(0x123456000, 0xfffff000, 0x4000), (0, 0, 0x10000)):
|
|
for three_d in (1, 0):
|
|
run("I", buffers=(first, second, size), gr={0x160c: three_d})
|
|
# Geometry: per-GPC TPC counts (fuse words) and the second count of the per-GPC word.
|
|
for words, fuse in (((0x40007,) * 6, {}), ((0x40006,) * 6, {0xc38 + 4 * gpc: 1 for gpc in range(6)}),
|
|
((0x40007, 0x40005, 0x40007, 0x40007, 0x40004, 0x40007),
|
|
{0xc3c: 3, 0xc48: 7}),
|
|
((0x70007, 0x70007, 0x70007, 0x60006, 0x70007, 0x60006), V100_FUSE),
|
|
((0x7,) * 6, {})):
|
|
for three_d in (1, 0):
|
|
run("I", gr={0x160c: three_d}, **geometry(words, fuse))
|
|
for gpc, value in ((0, 7), (0, 0), (3, 5), (5, 9), (2, 3), (1, 4)):
|
|
run("I", records={(gpc, 4): value})
|
|
run("I", records={(0, 4): 7, (4, 4): 3})
|
|
run("I", records={(gpc, 4): 0 for gpc in range(6)})
|
|
# The PPC count and the graphics TPC count of a GPC record, within the register units.
|
|
for gpc, value in ((0, 0), (2, 1), (5, 2)):
|
|
run("I", records={(gpc, 8): value})
|
|
run("I", records={(gpc, 0x1c): value})
|
|
# The four feature steps: property bytes, override bytes, the FECS word and the checks.
|
|
for word in (0, 0x1000, 0x2000, 0x4000, 0x20000, 0x3f100, 0xffffffff, 0xfffc8fff):
|
|
for grmgr in ({}, {0x28c: 0}, {0x28e: 0}, {0x290: 0}, {0x292: 0},
|
|
{0x28b: 1, 0x28d: 1, 0x28f: 1, 0x291: 1},
|
|
{0x28b: 1, 0x28c: 0, 0x28f: 1, 0x290: 0}):
|
|
run("I", grmgr=grmgr, reads={0x409660: [word]})
|
|
for offset, mask in ((0x354, 0xff), (0x368, 3), (0x620, 3)):
|
|
for tpc in (0x504000, 0x51d800, 0x52e800):
|
|
for values in ([1, 0], [0x100], [mask, mask, 0], [mask + 1, 0], [0xffffffff] * 3 + [0]):
|
|
for check in ([], [0, 0x65], [0x65], [5, 0, 0x65]):
|
|
if len(values) - 1 > len(check) or check and values[-1] and check[-1] != 0x65:
|
|
check = check + [0x65]
|
|
run("I", reads={tpc + offset: values}, check=list(check))
|
|
# Wait for idle.
|
|
for current in ([0], [0x80000000, 0], [0x80000000] * 3 + [0x7fffffff], [0xffffffff] * 2):
|
|
for enable in (0x1fecdff1, 0x1feccff1):
|
|
for pending, busy in (([0], []), ([1, 0], []), ([0], [1, 0]), ([1], [1]),
|
|
([0xfffffffe], [1, 1, 0])):
|
|
for check in ([], [0, 0x65], [0x65]):
|
|
run("I", reads={0x409b00: list(current), 0x200: [enable],
|
|
0x40060c: list(pending)}, busy=list(busy),
|
|
check=list(check) + [0x65] * 8)
|
|
for gpu in ({0x917: 1}, {0x918: 1}, {0x919: 1}, {0x926: 1}, {0x915: 0}):
|
|
run("I", reads={0x409b00: [0x80000000], 0x40060c: [1]}, gpu={0x911: 1, **gpu},
|
|
check=[0x65] * 8)
|
|
for busy_status in (0x40, 0xffff):
|
|
run("I", busy_status=[busy_status], reads={0x409b00: [0x80000000], 0x40060c: [0]})
|
|
# The LTC count and the other single words.
|
|
for count in (0, 1, 0x10, 0x1f, 0x3f, 0xffffffe0):
|
|
for three_d in (1, 0):
|
|
run("I", reads={0x12006c: [count]}, gr={0x160c: three_d})
|
|
for number in range(48):
|
|
seed = random.word()
|
|
run("I", default_read=hashed(seed), gr={0x160c: number & 1},
|
|
gpu={0x911: number >> 1 & 1}, check=[0x65] * 400,
|
|
reads={0x409660: [random.pick((0, 0x3f100, 0x7000, 0x21000))]})
|
|
|
|
out = ROOT / "target/gpu-stage"
|
|
out.mkdir(parents=True, exist_ok=True)
|
|
table = struct.unpack("<96I", cpu.mem_read(by_name["_nv053876rm"], 384))
|
|
require(all(table[index - 1] == -(-(1 << 23) // index) for index in range(1, 97)))
|
|
rows.insert(0, "T;" + " ".join(f"{value:x}" for value in table))
|
|
oracle = "\n".join(rows) + "\n"
|
|
(out / "original-graphics-load.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[0] == "I" and row.split(";")[12] != "0")
|
|
report = {
|
|
"original_sha256": DIGEST, "chip_hal": "0x23", "rm_hal": 2,
|
|
"entry": "_nv033665rm -> _nv033664rm -> _nv033298rm on objects prepared by "
|
|
"_nv005687rm, the binders, _nv033946rm, _nv034073rm, _nv031719rm, _nv033667rm, "
|
|
"_nv034082rm and _nv033663rm",
|
|
"executed_in_preparation_and_the_v100_case": load_executed,
|
|
"executed_count": len(load_executed),
|
|
"fixture_supplied": sorted(HANDLERS) + ["GPU+1e78 object +100 and +118 (fuse)"],
|
|
"fixture_in_rows_original_in_the_traced_case": [
|
|
"_nv027871rm", "_nv033505rm", "_nv027641rm", "_nv029884rm"],
|
|
"binder_argument_order": {"rm_then_chip": list(RM_FIRST),
|
|
"class_routines": TOP_BINDERS},
|
|
"v100_inputs": {
|
|
"from_transcript": {"0x500c30/c34/c38 per GPC": "lines 166336-166353",
|
|
"fuse 0x21c38+4*gpc": "lines 166291-166335",
|
|
"0x120078, 0x22430, 0x22434": "lines 37600-37603",
|
|
"KernelGmmu buffers": "lines 156736-156737"},
|
|
"not_in_transcript": {
|
|
"0x502608 + 0x8000*gpc": "0x40007 / 0x40006: the low five bits are the TPC "
|
|
"count the load writes to +914; bits 20:16 = 4 is the value +910 shows "
|
|
"(0x40028). Both fields are forced by transcript lines 157093-157110.",
|
|
"0x1070, 0x40960c, 0x500920": "read by InitLocked, value 0 used; no effect on "
|
|
"the load's register sequence was seen",
|
|
"_nv000194rm": "status or table of the VBIOS override service; the traced run "
|
|
"shows no override write"}},
|
|
"transcript_comparison": transcript, "step_attribution": merged,
|
|
"fields_read_by_the_load": {label: [f"{offset:#x}" for offset in offsets]
|
|
for label, offsets in sorted(fields_read.items())},
|
|
"class_enable_stores": class_enable_stores, "compute_only_experiment": compute_only,
|
|
"cases": len(rows), "cases_by_kind": kinds, "init_cases_with_nonzero_status": failed,
|
|
"kinds": {"T": "the 96 words at _nv053876rm (2^23 / n rounded up)",
|
|
"V": "the traced V100 StateLoad, every event",
|
|
"S": "_nv033665rm with fixture children", "I": "_nv033298rm"},
|
|
"oracle": "target/gpu-stage/original-graphics-load.txt",
|
|
"oracle_sha256": hashlib.sha256(oracle.encode()).hexdigest(),
|
|
"scope": "Original GV100 Graphics StateLoad on state produced by the original "
|
|
"constructors and InitLocked. Register values, time, the fuse object, the "
|
|
"VBIOS table, the LPWR query, the MemorySystem ZBC service and (in the rows) "
|
|
"the FIFO engine status, both Falcon objects and the clock-gating pass are "
|
|
"fixture-supplied; no hardware executed."}
|
|
(ROOT / "reports/gpu-graphics-load-original.json").write_text(json.dumps(report, indent=1) + "\n")
|
|
print(f"{len(rows)} original Graphics load rows {kinds}; executed {len(load_executed)} "
|
|
f"original functions; transcript lines {transcript['lines']} equal")
|
|
print(report["oracle_sha256"])
|
|
|
|
|
|
def binder_order():
|
|
"""Selector sensitivity of every binder the fixture runs: distinct results over 0..95."""
|
|
def result(binder, second, third):
|
|
cpu.mem_write(CHIP + 0x10, struct.pack("<H", second))
|
|
cpu.mem_write(RM + 0x10, struct.pack("<H", third))
|
|
cpu.mem_write(GR, bytes(0x8000))
|
|
call(binder, GR, CHIP, RM)
|
|
return bytes(cpu.mem_read(GR, 0x8000))
|
|
orders = {}
|
|
for binder in sorted({binder for label, base in CLASSES for binder in
|
|
classes[label]["binders"] + classes[label]["property_binders"]}
|
|
| {"_nv005803rm"}):
|
|
orders[binder] = tuple(max(len({result(binder, *((value, fixed) if position == 0
|
|
else (fixed, value)))
|
|
for value in range(96)}) for fixed in (2, 0x23))
|
|
for position in (0, 1))
|
|
return orders
|
|
|
|
|
|
if __name__ == "__main__":
|
|
if "--binder-order" in sys.argv:
|
|
for binder, (second, third) in binder_order().items():
|
|
# A two-argument binder shows 1 for the argument it does not take.
|
|
rm_first = third > second and second > 1
|
|
require(rm_first == (binder in RM_FIRST), binder)
|
|
print(binder, second, third, "(rm, chip)" if rm_first else "(chip, rm) or chip only")
|
|
elif "--disassemble" in sys.argv:
|
|
for name in sys.argv[sys.argv.index("--disassemble") + 1:]:
|
|
print(f"== {name}")
|
|
print(disassemble(name))
|
|
else:
|
|
main()
|