Files
nvdriver/tools/check_gpu_memory_placement_binary.py
morebrackets 7bc8310fd7 Address CodeRabbit follow-up findings on #217
- tools/check_gpu_memory_placement_binary.py, tools/check_vram_size_binary.py,
  tools/gp106/bar2_setup.py (4778396367, 4778396379, 4778396382): pass
  verify=True to resolve_580_binary() so digest verification is enforced
  under python3 -O before ELF/emulation or output generation.
- tools/gp106/bar2_setup.py (4778396388): use a callable replacement in
  re.subn so literal backslashes in paths are never interpreted as escapes.
- tools/oracle_gsp_620.py (4778396392): prefer a candidate source tree whose
  version.mk matches 620.70.06 over an unversioned tree with another release,
  and replace hardcoded /home/geodd fallback with Path.home().
2026-12-02 17:07:02 -08:00

1384 lines
64 KiB
Python

#!/usr/bin/env python3
"""Run the original GV100 memory-placement producers and write an oracle.
Bring-up level 4 needs the BAR2 hidden range, the reserved-memory size and
base, and the framebuffer addresses of the first internal allocations. This
harness executes the original code that produces them on a GV100 (chip HAL
0x23, RM HAL 2). The whole object file is loaded and relocated; the function
tables of MemoryManager, MemorySystem, KernelMemorySystem, KernelBus,
KernelGmmu, KernelFifo, OBJFIFO, OBJCE, OBJUVM and OBJGMMU come from running
their original binders and property initializers.
Executed original code, in first-open order:
region table MemoryManager+120 _nv043995rm -> +340 _nv043988rm (LTC count
MemorySystem+b10 _nv044754rm, framebuffer size
KernelMemorySystem+110 _nv041622rm -> _nv041621rm -> +108
_nv041679rm), +330, +128 _nv044084rm, +1d0 _nv043993rm,
_nv044071rm.
comptag decode MemorySystem+ef0 _nv045239rm -> _nv045238rm -> +ee8
_nv045563rm (_nv045002rm).
BAR2 sizes _nv039557rm (aperture limits).
reserved size _nv044065rm (_nv044984rm, _nv043742rm) -> _nv044075rm ->
KernelBus+158 _nv039445rm -> +160 _nv039455rm -> +168
_nv039317rm -> +170 _nv039316rm -> OBJUVM+1b8 _nv059748rm,
KernelGmmu+368 _nv040937rm (twice), KernelFifo+218
_nv040202rm -> +220 _nv040312rm -> +118 _nv040413rm ->
_nv040275rm, OBJFIFO+1a8 _nv027729rm; +190 _nv040337rm;
GPU+488 _nv030432rm -> _nv018874rm -> OBJCE+378 _nv018898rm
-> +320 _nv018880rm; then KernelBus+150 _nv039447rm.
comptag size the steps of _nv045880rm (reached from MemorySystem+1c8
_nv045881rm) that size the store: +ef8 _nv044284rm (+ed8,
+f40, +b10) and +f28 _nv044460rm (_nv043683rm, descriptor
creation _nv043694rm, page size MemoryManager+358
_nv044111rm).
reserved base _nv043997rm (+320 _nv043823rm, _nv044000rm, _nv014086rm,
_nv044071rm, descriptor creation and _nv043698rm).
heap _nv035551rm (heapInit: _nv043892rm, _nv035541rm,
_nv035550rm, _nv044073rm -> _nv043817rm -> MemoryManager+300
_nv043815rm, _nv044072rm; region reservation _nv035555rm).
allocations MemorySystem+eb8 _nv044227rm (comptag store), OBJGMMU
InitLocked _nv029562rm (two dummy pages), KernelBus+1c0
_nv039577rm (flush page) and KernelBus+408 _nv039656rm up to
the return of its allocation (test page); each through
_nv043691rm or _nv043692rm -> _nv014072rm -> _nv043803rm
(page size _nv043861rm, alignment MemoryManager+1c8
_nv043790rm) -> _nv060574rm -> _nv035538rm (heapAlloc). The
test page is then released (_nv043704rm, _nv043700rm) and a
request of the size and alignment of the WPR image follows.
generic contiguous framebuffer descriptors of many sizes and
alignments, allocated and released in mixed order through
the same functions.
direct ACR the requests that follow the BAR2 test page when the shadow
copy needs no copy-engine channel, each through its original
requester (rows "direct", appended last): WPR primary and
shadow; the PMU instance block as _nv052270rm asks for it
(_nv052299rm, _nv052602rm, _nv052601rm); the PMU super
surface as _nv052522rm asks for it (_nv052179rm ->
_nv052177rm, _nv052602rm, _nv052601rm); the runlist buffers;
the HS image descriptor of _nv016741rm (size rounded to
0x100, alignment 0x100, tag 0x82); the Falcon instance block
_nv028536rm (Falcon+98); and the five page levels of the
Falcon address space through the walker's level callback
_nv013506rm (_nv040820rm, _nv046232rm, _nv029452rm). The
instance-location words GPU+5300..530f come from executing
the GPU property initializer _nv005825rm and _nv030827rm.
Fixture-supplied: register access (_nv053907rm, _nv053912rm) from the case's
register values, the register apertures of the first copy engine and of the
LTC broadcast block (a read of the base plus the offset), diagnostics, the
allocator, fill and copy, registry lookups, the multi-GPU and
calling-context helpers, the object-model ancestor lookup and cast
(_nv049086rm, _nv005245rm), the operating-system queries (page size, console
framebuffer _nv049691rm, memory onlining _nv049754rm, may-sleep), the OBJFUSE
feature query, timeout start, the framebuffer fill _nv043684rm of the dummy
pages, the BAR2 mapping of the flush page, and the cross-object sizes that
enter the internal heap size (MemoryManager+308, +310, +318, +1d8,
KernelGmmu+128), which are case inputs. Fields the engine constructors set
are written directly: MemoryManager+b68, +840, +440 (_nv043850rm), the
aperture kinds of KernelBus, the page-table format (as in
tools/check_gpu_bar2_setup_binary.py). For the direct ACR rows also: the
framebuffer fills _nv044030rm and _nv044036rm and the descriptor name
_nv043763rm; the surface objects (their creator _nv006748rm is not run, the
constructor _nv052602rm is), the PMU byte +429 (0), the Falcon object, the
walker context (address space flags 0, limit 0x20000fff), the image range
(0x1000 up) and the page-table apertures KernelGmmu+4c0..4dc, written as
the constructor _nv040666rm does. No hardware is involved.
The loader and fixture functions may be imported by the GP106 oracle. Importing
does not generate the GV100 cases; build_template defaults to the same GV100
boot words and additionally accepts an explicitly selected chip/boot identity.
"""
import bisect
from _binary_path import resolve_580_binary
import hashlib
import json
import os
from pathlib import Path
import struct
import sys
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_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(verify=True)
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 = 0x1000000, 0x200000
(GPU, BUS, MMU, MEMMGR, KMEMSYS, MEMSYS, FIFO, OFIFO, CE, UVM, GMMU, CHIP, RM, CONFIG, APERTURES,
HEAPOBJ, GRAPHICS, FUSE, PMUOBJ, FALCON, SPACE) = (OBJ + 0x10000 * index for index in range(21))
CONTINUE, ABORT, SERVICE = STOP + 0x100, STOP + 0x200, STOP + 0x400
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}
# Slots the chain dispatches through, checked against the bindings report where it has them.
EXPECTED = {
"KernelBus": {"0x150": "_nv039447rm", "0x158": "_nv039445rm", "0x160": "_nv039455rm",
"0x168": "_nv039317rm", "0x170": "_nv039316rm", "0x1c0": "_nv039577rm",
"0x408": "_nv039656rm"},
"KernelGmmu": {"0x368": "_nv040937rm"},
"KernelFifo": {"0x118": "_nv040413rm", "0x190": "_nv040337rm", "0x218": "_nv040202rm",
"0x220": "_nv040312rm"},
"OBJFIFO": {"0x1a8": "_nv027729rm"},
"OBJCE": {"0x320": "_nv018880rm", "0x378": "_nv018898rm"},
"OBJUVM": {"0x1b8": "_nv059748rm"},
"MemoryManager": {"0x120": "_nv043995rm", "0x300": "_nv043815rm", "0x320": "_nv043823rm",
"0x340": "_nv043988rm"},
"MemorySystem": {"0xeb8": "_nv044227rm", "0xed8": "_nv044826rm", "0xee8": "_nv045563rm",
"0xef0": "_nv045239rm", "0xef8": "_nv044284rm", "0xf28": "_nv044460rm",
"0xf40": "_nv045025rm"},
"KernelMemorySystem": {"0x108": "_nv041679rm", "0x110": "_nv041622rm"},
}
# Slots filled by the MemorySystem binder _nv005936rm, which the bindings report omits.
UNREPORTED = {"MemorySystem": {"0xb10": "_nv044754rm", "0x1c8": "_nv045881rm"}}
BINDERS = (("_nv005902rm", BUS), ("_nv005903rm", BUS), ("_nv005790rm", BUS),
("_nv005935rm", MEMMGR), ("_nv005806rm", MEMMGR),
("_nv005925rm", KMEMSYS), ("_nv005800rm", KMEMSYS),
("_nv005914rm", MMU), ("_nv005915rm", MMU), ("_nv005794rm", MMU),
("_nv005936rm", MEMSYS), ("_nv005937rm", MEMSYS), ("_nv005938rm", MEMSYS),
("_nv005939rm", MEMSYS), ("_nv005940rm", MEMSYS), ("_nv005807rm", MEMSYS),
("_nv005912rm", FIFO), ("_nv005792rm", FIFO),
("_nv005970rm", OFIFO), ("_nv005971rm", OFIFO), ("_nv005972rm", OFIFO),
("_nv005820rm", OFIFO),
("_nv005954rm", CE), ("_nv005955rm", CE), ("_nv005813rm", CE),
("_nv006017rm", UVM), ("_nv005845rm", UVM),
("_nv005975rm", GMMU), ("_nv005822rm", GMMU))
BASE_OF = {"KernelBus": BUS, "KernelGmmu": MMU, "KernelFifo": FIFO, "OBJFIFO": OFIFO, "OBJCE": CE,
"OBJUVM": UVM, "MemoryManager": MEMMGR, "MemorySystem": MEMSYS,
"KernelMemorySystem": KMEMSYS}
# Register values of the traced V100 with the transcript line of each read.
V100 = {0x100ce0: (0x20a, 37530), 0x100a0c: (0x1000, 37590), 0x100e34: (0x60002061, 37591),
0x100e48: (0x40001800, 37594), 0x2008: (0x1000, 37597), 0x104028: (0x1ff, 37598),
0x17e3f4: (0x401c0002, 37583), 0x12006c: (0x10, 37529)}
CE_APERTURE, LTC_APERTURE = 0x104000, 0x17e000
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)
assert bindings["gpu_object"]["hal_slots"]["0x488"]["function"] == "_nv030432rm"
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)):
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 text(address):
data = bytes(cpu.mem_read(address, 64))
return data[:data.index(0)].decode()
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))
class Aborted(Exception):
pass
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)
state["aborted"] = False
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)
raise AssertionError((str(error), hex(pc), function_at(pc), target)) from error
if state["aborted"]:
return None
assert cpu.reg_read(UC_X86_REG_RIP) == STOP, target
return cpu.reg_read(UC_X86_REG_RAX)
def emit(token):
state["events"].append(token)
def read_register(a):
assert (a[0], a[1] & 0xffffffff, a[2] & 0xffffffff) == (GPU + 0x4120, 0, 0)
offset = a[3] & 0xffffffff
value = state["case"]["registers"][offset]
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
# _nv040937rm writes the fault-buffer size registers back; the model keeps the value.
assert offset in (0x100e34, 0x100e48), hex(offset)
state["case"]["registers"][offset] = value
emit(f"w:{offset:x}:{value:x}")
return 0
def diagnostic(a):
emit(f"e:{a[1] >> 16 & 0xffff:x}")
return 0
def asserted(position):
"""The assertion reporters; their line argument is recorded."""
def handler(a):
emit(f"A:{a[position] & 0xffffffff:x}")
return 0
return handler
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 registry(a):
"""_nv049786rm(gpu, key, &value): the status; the value only on success."""
key = text(a[1])
emit("k:" + key)
if key in state["case"]["registry"]:
wd(a[2], state["case"]["registry"][key])
return 0
return 0x56
def context(a):
wd(a[1], 0)
return 0
def copy(a):
cpu.mem_write(a[0], bytes(cpu.mem_read(a[1], a[2] & 0xffffffff)))
return a[0]
def fill(a):
cpu.mem_write(a[0], bytes([a[1] & 0xff]) * (a[2] & 0xffffffff))
return a[0]
def framebuffer_fill(a):
"""_nv043684rm(gpu, descriptor, value): the PRAMIN fill of a dummy page."""
emit(f"z:{q(a[1] + 0x30):x}")
return 0
def map_descriptor(a):
"""_nv043739rm(gpu, descriptor, flags): the BAR2 mapping of the flush page."""
emit(f"v:{a[2] & 0xffffffff:x}")
return 0x1000
HANDLERS = {
"_nv053907rm": read_register, "_nv053912rm": write_register,
"_nv047869rm": diagnostic, "_nv047868rm": diagnostic, "_nv047867rm": diagnostic,
"_nv046745rm": asserted(0), "_nv046747rm": asserted(1), "_nv046751rm": asserted(1),
"_nv046752rm": asserted(2),
"_nv052687rm": lambda a: allocate(a[0], 0xcc), "_nv052701rm": lambda a: 0,
"_nv049786rm": registry,
"_nv049086rm": lambda a: GPU, "_nv005245rm": lambda a: a[0],
"_nv049754rm": lambda a: 0, "os_semaphore_may_sleep": lambda a: 1,
"_nv059509rm": lambda a: 0, "_nv031395rm": lambda a: 1, "_nv031424rm": next_gpu,
"_nv060459rm": context, "_nv031390rm": lambda a: 0, "_nv031426rm": lambda a: GPU,
"_nv031447rm": lambda a: 1, "_nv031478rm": lambda a: 0, "_nv031482rm": lambda a: 0,
"_nv043684rm": framebuffer_fill, "_nv043739rm": map_descriptor,
"os_mem_set": fill, "os_mem_copy": copy,
}
SERVICES = {}
INSTALLED = {}
def service(name):
def register(function):
address = SERVICE + 16 * len(SERVICES)
SERVICES[address] = (name, function)
return address
return register
def install(address, handler, *, replace=False):
if replace:
for previous in INSTALLED.pop(address, []):
cpu.hook_del(previous)
def run(emu, pc, size, unused):
value = handler([emu.reg_read(register) for register in ARGS])
if value is not None:
leave(value)
handle = cpu.hook_add(UC_HOOK_CODE, run, begin=address, end=address)
INSTALLED.setdefault(address, []).append(handle)
@service("register aperture: read32 at vtable +28")
def aperture_read(a):
base = q(a[0] + 8)
offset = base + (a[1] & 0xffffffff)
value = state["case"]["registers"][offset]
emit(f"r:{offset:x}:{value:x}")
return value
def sized(name):
def handler(a):
emit("s:" + name)
return state["case"]["sizes"][name]
return handler
@service("OBJFUSE+118: feature query")
def fuse_query(a):
assert (a[0], a[1], a[2] & 0xffffffff) == (GPU, FUSE, 0xff00003d), [hex(v) for v in a]
emit("q")
wd(a[3], state["case"]["console_feature"])
return 0
def console(a):
"""_nv049691rm(&base, &size): the operating system's console framebuffer."""
emit("c")
wq(a[0], state["case"]["console"][0])
wq(a[1], state["case"]["console"][1])
return 0
HANDLERS["_nv049691rm"] = console
# Direct ACR rows only: fills through BAR2 and the descriptor name.
HANDLERS["_nv044030rm"] = lambda a: (emit(f"z:{q(a[1] + 0x30):x}"), 0)[1]
HANDLERS["_nv044036rm"] = lambda a: (emit(f"z:{a[3]:x}"), 0)[1]
HANDLERS["_nv043763rm"] = lambda a: 0
ATTRIBUTE = service("MemoryManager+308")(sized("attribute"))
RUNLISTS = service("MemoryManager+310")(sized("runlists"))
USERD = service("MemoryManager+318")(sized("userd"))
CONTEXT = service("MemoryManager+1d8")(sized("context"))
FAULT_FB = service("KernelGmmu+128")(sized("fault"))
for name, handler in HANDLERS.items():
install(externals[name] if name in externals else by_name[name], handler)
for address, (name, handler) in SERVICES.items():
install(address, 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 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)
def aborted(emu, address, size, unused):
state["aborted"] = True
state["result"] = emu.reg_read(UC_X86_REG_RAX)
emu.emu_stop()
cpu.hook_add(UC_HOOK_CODE, unexpected, begin=EXT, end=EXT + 0x10000)
cpu.hook_add(UC_HOOK_CODE, aborted, begin=ABORT, end=ABORT)
PRISTINE = {name: bytes(sections[name]) for name in (".data", ".bss")}
(SYSTEM, MANAGER, FACTORY, CE_OBJECT, LTC_OBJECT, LTC_TABLE, GPU_1E60, CONFIDENTIAL) = (
APERTURES + 0x1000 * number for number in range(8))
BOOT0, BOOT42 = 0x140000a1, 0x140a1000
MASK = (1 << 64) - 1
def status(value):
return value & 0xffffffff
def build_template(chip=0x23, boot0=BOOT0, boot42=BOOT42):
"""Objects as the creators, binders and constructors leave them, once."""
cpu.mem_write(OBJ, bytes(OBJ_SIZE))
cpu.mem_write(CHIP + 0x10, struct.pack("<H", chip))
cpu.mem_write(RM + 0x10, struct.pack("<H", 2))
state.update(heap=HEAP, events=[], case=None, aborted=False, capture=False)
for binder, target in BINDERS:
call(binder, target, CHIP, RM)
if chip == 0x23:
for group in (EXPECTED, UNREPORTED):
for label, slots in group.items():
for slot, function in slots.items():
assert q(BASE_OF[label] + int(slot, 16)) == by_name[function], (label, slot)
# Chip identification and the GPU object's own table, as the GPU constructor does it.
wq(GPU + 0x80, CHIP)
wq(GPU + 0x88, RM)
wq(by_name["_nv029075rm"], SYSTEM)
wq(SYSTEM + 0x258, MANAGER)
wq(MANAGER + 0x48 + chip * 8, FACTORY)
assert call("_nv030179rm", GPU, boot0, boot42, 0) == 0
call("_nv030823rm", GPU)
assert (d(GPU + 0x9e8), d(GPU + 0xd00)) == (chip, boot42 >> 20 & 0x3f0)
call("_nv005980rm", GPU)
call("_nv005982rm", GPU)
assert q(GPU + 0x488) == by_name["_nv030432rm"]
for offset, target in ((0x1f80, BUS), (0x1f90, MMU), (0x1ed0, MEMMGR), (0x1ec8, KMEMSYS),
(0x1ec0, MEMSYS), (0x22d0, FIFO), (0x22d8, OFIFO), (0x2130, CE),
(0x22f0, UVM), (0x1f88, GMMU), (0x2018, GRAPHICS), (0x1e78, FUSE),
(0x1e60, GPU_1E60)):
wq(GPU + offset, target)
wd(GPU + 0xdf4, 1)
wq(FUSE + 0x118, fuse_query)
wq(KMEMSYS + 0x290, CONFIG)
wb(CONFIG + 0x10, 1)
wq(externals["os_page_size"], 0x1000)
# Register apertures: the first copy engine and the LTC broadcast block.
for holder, base in ((CE_OBJECT, CE_APERTURE), (LTC_OBJECT, LTC_APERTURE)):
wq(holder, holder + 0x100)
wq(holder + 8, base)
wq(holder + 0x100 + 0x28, aperture_read)
wq(CE + 0x578, CE_OBJECT)
wq(MEMSYS + 0x8d00, LTC_TABLE)
wd(MEMSYS + 0x8d08, 2)
wq(LTC_TABLE + 0x88 + 0x50, LTC_OBJECT)
# MemoryManager fields of the engine constructor _nv043850rm.
for offset in (0xb68, 0x840, 0x440):
wq(MEMMGR + offset, MASK)
# 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 in (0xace4, 0xacdc, 0xace8, 0xace0):
wd(BUS + offset, 2)
# Cross-object sizes of the internal heap are case inputs.
for slot, target in ((0x308, ATTRIBUTE), (0x310, RUNLISTS), (0x318, USERD), (0x1d8, CONTEXT)):
wq(MEMMGR + slot, target)
wq(MMU + 0x128, FAULT_FB)
wq(MEMMGR + 0x468, HEAPOBJ)
assert not state["events"], state["events"]
return (bytes(cpu.mem_read(OBJ, OBJ_SIZE)), state["heap"],
{name: bytes(cpu.mem_read(BASES[name], len(sections[name])))
for name in (".data", ".bss")})
def reset(case):
cpu.mem_write(OBJ, TEMPLATE[0])
for name, content in TEMPLATE[2].items():
cpu.mem_write(BASES[name], content)
state.update(heap=TEMPLATE[1], events=[], case=case, aborted=False, capture=False,
descriptor=0)
def watch_allocation(emu, address, size, unused):
"""In capture mode the caller of _nv043691rm is left when the allocation returns."""
if state["capture"]:
state["descriptor"] = emu.reg_read(UC_X86_REG_RDI)
wq(emu.reg_read(UC_X86_REG_RSP), ABORT)
cpu.hook_add(UC_HOOK_CODE, watch_allocation, begin=by_name["_nv043691rm"],
end=by_name["_nv043691rm"])
class Stop(Exception):
pass
def checked(name, value, mark):
"""A stage ends the case when it fails or when an assertion reporter ran in it."""
asserts = [token for token in state["events"][mark:] if token.startswith("A:")]
if status(value) or asserts:
raise Stop(f"fail:{name}:{status(value):x}:" + ",".join(asserts))
def physical(descriptor):
return call("_nv043721rm", descriptor, 1, 0)
def regions():
rows = []
for number in range(d(MEMMGR + 0x850)):
at = MEMMGR + 0x858 + 0x28 * number
rows.append((q(at), q(at + 8), q(at + 0x10), cpu.mem_read(at + 0x18, 1)[0], d(at + 0x1c),
*bytes(cpu.mem_read(at + 0x20, 4))))
return rows
def stage_regions(out):
mark = len(state["events"])
checked("regions", call(q(MEMMGR + 0x120), GPU, MEMMGR), mark)
out += [q(MEMMGR + 0x820), q(MEMMGR + 0x830), d(MEMMGR + 0x874)]
def stage_decode(out):
mark = len(state["events"])
call(q(MEMSYS + 0xef0), GPU, MEMSYS)
checked("decode", 0, mark)
def stage_reserved(out):
mark = len(state["events"])
checked("apertures", call("_nv039557rm", GPU, BUS, 0), mark)
checked("reserved", call("_nv044065rm", GPU, MEMMGR), mark)
out += [q(BUS + 0x45e0), q(BUS + 0x45e8), d(BUS + 0x4678), d(BUS + 0x4680), q(BUS + 0x4608),
q(BUS + 0x4618), q(MEMMGR + 0x490)]
def stage_comptag(out):
"""The steps of _nv045880rm (MemorySystem+1c8 through _nv045881rm) that size the store."""
mark = len(state["events"])
if d(MEMSYS + 0x13b8) == 0 and cpu.mem_read(MEMSYS + 0x8cef, 1)[0] == 0:
usable = q(MEMMGR + 0x820)
wq(MEMSYS + 0x4358, usable)
call(q(MEMSYS + 0xef8), GPU, MEMSYS, usable)
lines = d(MEMSYS + 0x13b4)
if d(MEMSYS + 0x13b8) != 0:
checked("comptag", call(q(MEMSYS + 0xf28), GPU, MEMSYS), mark)
checked("comptag", 0, mark)
descriptor = q(MEMSYS + 0x13c8)
# The last word: _nv044460rm set the descriptor's page size to 4 KiB (MemoryManager+358).
out += [lines, d(MEMSYS + 0x13b8), q(descriptor + 0x28) if descriptor else 0,
int(q(descriptor + 0x10) == 0x1000) if descriptor else 0]
def stage_base(out):
mark = len(state["events"])
checked("base", call("_nv043997rm", GPU, MEMMGR, q(MEMMGR + 0x830) << 20), mark)
out += [q(MEMMGR + 0x488), q(MEMMGR + 0x490), q(MEMMGR + 0x820)]
def stage_heap(out):
"""_nv043851rm's call of heapInit with its arguments; the object creation, the page
allocator and the later steps of that function are not executed."""
mark = len(state["events"])
top = call(q(MEMMGR + 0x1f8), GPU, MEMMGR)
call(q(MEMMGR + 0x1e0), GPU, MEMMGR)
whole = q(MEMMGR + 0x830) << 20
start = q(MEMMGR + 0x480)
checked("heap", call("_nv035551rm", GPU, HEAPOBJ, start, whole - min(top, whole) - start, 0,
0, stack=(0,)), mark)
internal = [row for row in regions() if row[8] and not row[3]]
assert len(internal) <= 1
out += [internal[0][0], internal[0][1] + 1] if internal else [0, 0]
def create(size, alignment, flags):
slot = allocate(8)
value = status(call("_nv043694rm", slot, GPU, size, alignment, 1, 2, stack=(1, flags)))
return value, q(slot)
def allocation(size, alignment, flags, small=0):
"""A contiguous framebuffer descriptor: creation, optionally the 4 KiB page size as
_nv044460rm sets it through MemoryManager+358, _nv043691rm, physical address."""
mark = len(state["events"])
value, descriptor = create(size, alignment, flags)
if value == 0 and small:
call(q(MEMMGR + 0x358), GPU, MEMMGR, descriptor, 1, 1)
if value == 0:
value = status(call("_nv043691rm", descriptor))
if value or any(token.startswith("A:") for token in state["events"][mark:]):
return None, f"x{value:x}"
return descriptor, f"{physical(descriptor):x}"
def release(descriptor):
call("_nv043704rm", descriptor)
call("_nv043700rm", descriptor)
def stage_allocations(out):
mark = len(state["events"])
if q(MEMSYS + 0x13c8):
checked("store", call(q(MEMSYS + 0xeb8), GPU, MEMSYS), mark)
out.append(q(MEMSYS + 0x13d0))
else:
out.append(0)
checked("dummy", call("_nv029562rm", GPU, GMMU), mark)
out += [physical(q(GMMU + 0x408)), physical(q(GMMU + 0x410))]
checked("flush", call(q(BUS + 0x1c0), GPU, BUS), mark)
out.append(physical(q(BUS + 0xacc8)))
state["capture"] = True
assert call(q(BUS + 0x408), GPU, BUS, 0, 0, 0, 0) is None
state["capture"] = False
checked("test", state["result"], mark)
page = state["descriptor"]
assert (q(page + 0x30), q(page + 0x28)) == (0x10, 0x1000)
out.append(physical(page))
# The test releases its page; a later request of the size and alignment of the WPR image.
release(page)
out.append(int(allocation(0xe0000, 0x20000, 0)[1].replace("x", "-"), 16))
checked("later", 0, mark)
STAGES = (stage_regions, stage_decode, stage_reserved, stage_comptag, stage_base, stage_heap)
CHAIN_KEYS = (0x100ce0, 0x100a0c, 0x100e34, 0x100e48, 0x2008, 0x104028, 0x17e3f4, 0x12006c)
SIZE_KEYS = ("attribute", "runlists", "userd", "context", "fault")
def run_chain(kind, registers, war=0, sizes=(0, 0, 0, 0, 0), operations=None, store=False):
case = dict(registers=dict(zip(CHAIN_KEYS, registers)), registry={},
sizes=dict(zip(SIZE_KEYS, sizes)), console_feature=1, console=(MASK, 0))
if war:
case["registry"]["RMBug1848110War"] = war
reset(case)
out, result = [], "ok"
try:
for stage in STAGES:
stage(out)
if operations is None:
stage_allocations(out)
elif store:
# As first open does: the comptag store is the first request.
mark = len(state["events"])
checked("store", call(q(MEMSYS + 0xeb8), GPU, MEMSYS), mark)
out.append(q(MEMSYS + 0x13d0))
except Stop as stop:
result = str(stop)
fields = [" ".join(f"{value:x}" for value in registers), f"{war:x}",
" ".join(f"{value:x}" for value in sizes)]
tail = ""
if operations is not None:
held, results = [], []
if result == "ok":
for operation in operations:
if operation[0] == "a":
descriptor, text_ = allocation(*operation[1:])
held.append(descriptor)
results.append(text_)
elif operation[1] < len(held) and held[operation[1]]:
release(held[operation[1]])
held[operation[1]] = None
results.append("f")
else:
results.append("n")
fields.append(" ".join("a:%x:%x:%x:%x" % operation[1:] if operation[0] == "a"
else "f:%x" % operation[1] for operation in operations))
tail = ";" + " ".join(results)
rows.append(f"{kind};" + ";".join(fields) + f";{result};"
+ " ".join(f"{value:x}" for value in out) + tail)
return result, out, list(state["events"])
def run_hidden(visible, base, limit, uvm, gmmu, override, ce, registers):
"""KernelBus+170 _nv039316rm and KernelBus+168 _nv039317rm on given aperture state."""
keys = (0x100a0c, 0x100e34, 0x100e48, 0x2008, 0x104028)
reset(dict(registers=dict(zip(keys, registers)), registry={}, sizes={}))
for offset, value in ((0x45d8, visible), (0x45e0, base), (0x45e8, limit)):
wq(BUS + offset, value)
if uvm is None:
wq(GPU + 0x22f0, 0)
else:
wd(UVM + 0x220, uvm)
if not gmmu:
wq(GPU + 0x1f90, 0)
if override is not None:
wb(FIFO + 0x456, 1)
wd(FIFO + 0x458, override)
if not ce:
wq(GPU + 0x2130, 0)
size = status(call(q(BUS + 0x170), GPU))
asserts = [token for token in state["events"] if token.startswith("A:")]
reset(dict(state["case"], registers=dict(zip(keys, registers))))
for offset, value in ((0x45d8, visible), (0x45e0, base), (0x45e8, limit)):
wq(BUS + offset, value)
if uvm is None:
wq(GPU + 0x22f0, 0)
else:
wd(UVM + 0x220, uvm)
if not gmmu:
wq(GPU + 0x1f90, 0)
if override is not None:
wb(FIFO + 0x456, 1)
wd(FIFO + 0x458, override)
if not ce:
wq(GPU + 0x2130, 0)
call(q(BUS + 0x168), GPU, BUS, 0)
rows.append("hidden;" + " ".join(f"{value:x}" for value in (
visible, base, limit, 0xff if uvm is None else uvm, int(gmmu),
MASK if override is None else override, int(ce), *registers))
+ ";" + ("fail:" + ",".join(asserts) if asserts else "ok")
+ f";{size:x} {q(BUS + 0x45e0):x} {q(BUS + 0x45e8):x}")
return size, q(BUS + 0x45e0), q(BUS + 0x45e8)
def run_base(table, megabytes, usable, reserved, extra, bottom, confidential):
"""_nv043997rm on a given region table."""
reset(dict(registers={}, registry={}, sizes={}))
wd(MEMMGR + 0x850, len(table))
for number, row in enumerate(table):
at = MEMMGR + 0x858 + 0x28 * number
wq(at, row[0])
wq(at + 8, row[1])
wq(at + 0x10, row[2])
wb(at + 0x18, row[3])
wd(at + 0x1c, row[4])
cpu.mem_write(at + 0x20, bytes(row[5:9]))
for offset, value in ((0x830, megabytes), (0x820, usable), (0x490, reserved)):
wq(MEMMGR + offset, value)
wq(MEMSYS + 0x1388, extra)
wb(MEMMGR + 0xcec, bottom)
if confidential:
wq(GPU + 0x23c0, CONFIDENTIAL)
wb(CONFIDENTIAL + 0x231, 1)
# The instance block offsets and kinds _nv044065rm leaves.
wq(BUS + 0x5f0, 0)
wq(BUS + 0x4620, 0x1000)
wq(BUS + 0xacec, 0x200000002)
value = status(call("_nv043997rm", GPU, MEMMGR, megabytes << 20))
asserts = [token for token in state["events"] if token.startswith("A:")]
after = regions()
rows.append("base;" + f"{megabytes:x} {usable:x} {reserved:x} {extra:x} {bottom:x} "
f"{confidential:x} " + " ".join(",".join(f"{field:x}" for field in row)
for row in table)
+ ";" + (f"fail:{value:x}:" + ",".join(asserts) if value or asserts else "ok")
+ f";{q(MEMMGR + 0x488):x} {q(MEMMGR + 0x490):x} {q(MEMMGR + 0x820):x} "
f"{q(BUS + 0x5f0):x} {q(BUS + 0x4620):x} "
+ " ".join(",".join(f"{field:x}" for field in row) for row in after))
return value, asserts
def run_comptag(geometry, count, usable, secure):
"""Decode, line count and store size for given register values and usable size."""
reset(dict(registers={0x17e3f4: geometry, 0x12006c: count}, registry={}, sizes={}))
wq(MEMMGR + 0x820, usable)
wb(KMEMSYS + 0x280, secure)
out, result = [], "ok"
try:
stage_decode(out)
stage_comptag(out)
except Stop as stop:
result = str(stop)
rows.append(f"comptag;{geometry:x} {count:x} {usable:x} {secure:x};{result};"
+ " ".join(f"{value:x}" for value in out))
return result, out
class Generator:
"""xorshift64*: the case list must not depend on the interpreter's generator."""
def __init__(self, seed):
self.state = seed
def next(self):
value = self.state
value ^= value >> 12
value ^= value << 25 & MASK
value ^= value >> 27
self.state = value
return value * 0x2545f4914f6cdd1d & MASK
def below(self, bound):
return self.next() % bound
def pick(self, values):
return values[self.below(len(values))]
if __name__ == "__main__":
rows = []
TEMPLATE = build_template()
V100_REGISTERS = tuple(V100[key][0] for key in CHAIN_KEYS)
hook = cpu.hook_add(UC_HOOK_CODE, record_function, begin=BASES[".text"],
end=BASES[".text"] + len(sections[".text"]))
result, v100, events = run_chain("chain", V100_REGISTERS)
cpu.hook_del(hook)
assert result == "ok", result
EXPECTED_V100 = dict(zip(
("usable", "megabytes", "ltc_count", "hidden_base", "hidden_limit", "directories", "tables",
"directory_offset", "table_offset", "reserved_before_rounding", "comptag_lines",
"comptag_bytes", "comptag_alignment", "comptag_small_pages", "reserved_base",
"reserved_size", "usable_after", "internal_base", "internal_end", "comptag_store",
"mmu_read_page", "mmu_write_page", "flush_page", "test_page", "later_e0000_request"),
(0x800000000, 0x8000, 0x10, 0x2000000, 0xa090fff, 4, 81, 0x2000, 0x6000, 0x57000, 0x3ffff,
0x2000000, 0x20000, 1, 0x7fffa0000, 0x60000, 0x7fffa0000, 0x7f99a0000, 0x7fffa0000,
0x7fdfa0000, 0x7fdf90000, 0x7fdf80000, 0x7fdf7f000, 0x7fdf7e000, 0x7fde80000)))
assert v100 == list(EXPECTED_V100.values()), [hex(value) for value in v100]
reads = [token for token in events if token[0] in "rw"]
transcript = None
if TRANSCRIPT.exists():
lines = TRANSCRIPT.read_text().split("\n")
def traced(first, last):
return [f"{fields[0].lower()}:{int(fields[1], 16):x}:{int(fields[2], 16):x}"
for fields in (line.split() for line in lines[first - 1:last])]
# Region table, hidden range (PreInit) and the fault-method size of the heap creation.
assert reads[:2] == traced(37529, 37530), reads[:2]
assert reads[2] == traced(37583, 37583)[0]
assert reads[3:12] == traced(37590, 37598), reads[3:12]
assert reads[-2:] == traced(74914, 74915), reads[-2:]
for key, (value, line) in V100.items():
fields = lines[line - 1].split()
assert (fields[0], int(fields[1], 16), int(fields[2], 16)) == ("R", key, value), line
transcript = {"lines_equal": "37529-37530 (region table), 37583 (comptag geometry), "
"37590-37598 (hidden range), 74914-74915 (heap creation)",
"register_inputs": {f"0x{key:x}": {"value": f"0x{value:x}", "line": line}
for key, (value, line) in V100.items()}}
print("V100 chain:", {key: hex(value) for key, value in EXPECTED_V100.items()}, file=sys.stderr)
# ---------------------------------------------------------------- cases
generator = Generator(0x580178042019)
FB = { # NV_PFB_PRI_MMU_LOCAL_MEMORY_RANGE values: magnitude in bits 9:4, scale in 3:0
"4G": 0x4a, "6G": 0x6a, "8G": 0x8a, "8G scale 9": 0x109, "11G": 0xba, "12G": 0xca,
"16G": 0x10a, "24G": 0x18a, "32G": 0x20a, "32G scale 11": 0x10b, "40G": 0x28a, "48G": 0x30a,
"2G": 0x2a, "1G": 0x1a, "3G scale 8": 0xc8}
ECC = 1 << 30
chains = []
# Framebuffer sizes with and without the ECC bit.
for raw in FB.values():
for ecc in (0, ECC):
chains.append(dict(registers=(raw | ecc,) + V100_REGISTERS[1:]))
def varied(position, value, base=V100_REGISTERS):
registers = list(base)
registers[CHAIN_KEYS.index(position)] = value
return tuple(registers)
# Fault buffer sizes, access counter entries, channel counts and copy-engine words.
for value in (0x60000001, 0x60000080, 0x60000800, 0x60002000, 0x60002061, 0x60007fff, 0x2800,
0x6000ffff, 0x60020000, 0xe00fffff):
chains.append(dict(registers=varied(0x100e34, value)))
for value in (0x40000000, 0x40000001, 0x40000800, 0x40001800, 0x40004000, 0x4000ffff, 0x1800,
0x40040000):
chains.append(dict(registers=varied(0x100e48, value)))
for value in (0, 1, 0x80, 0x800, 0x1000, 0x2000, 0x8000, 0x20000, 0x80000):
chains.append(dict(registers=varied(0x100a0c, value)))
for value in (0, 1, 0x200, 0x800, 0xfff, 0x1000, 0x1001, 0x2000, 0x4000):
chains.append(dict(registers=varied(0x2008, value)))
for value in (0, 1, 3, 0xff, 0x1ff, 0x3ff, 0xffff, 0xffff01ff, 0x10000):
chains.append(dict(registers=varied(0x104028, value)))
# LTC counts and comptag geometry words.
for value in (0, 1, 2, 4, 6, 8, 12, 16, 17, 24, 31, 0x30, 0xffffffe8):
chains.append(dict(registers=varied(0x12006c, value)))
for value in (0x401c0002, 0x401c0001, 0x401c0004, 0x101c0002, 0x201c0008, 0x411c0002, 0x421c0003,
0x801c0010, 0x401c0000, 0x1c0002, 0x4f1c0002, 0xf01cffff):
chains.append(dict(registers=varied(0x17e3f4, value)))
# Size combinations with the workaround key and with cross-object heap sizes.
for raw in (0x4a, 0x8a, 0xca, 0x10a, 0x18a, 0x20a, 0x30a):
for ecc in (0, ECC):
for round_ in range(6):
registers = list(V100_REGISTERS)
registers[0] = raw | ecc
registers[1] = generator.pick((0x400, 0x1000, 0x1800, 0x4000, 0x10000))
registers[2] = 0x60000000 | generator.pick((0x400, 0x2061, 0x2800, 0x4000, 0x8000))
registers[3] = 0x40000000 | generator.pick((0x800, 0x1800, 0x2000, 0x6000))
registers[4] = generator.pick((0x200, 0x400, 0x800, 0x1000, 0x1800))
registers[5] = generator.pick((0x1, 0xf, 0xff, 0x1ff, 0x3ff, 0x7fff))
registers[6] = generator.pick((0x401c0002, 0x401c0001, 0x201c0002, 0x411c0002,
0x401c0003))
registers[7] = generator.pick((4, 6, 8, 12, 16, 24))
sizes = tuple(generator.pick((0, 0x1000, 0x40000, 0x200000, 0x1000000, 0x8000000))
for unused in SIZE_KEYS)
chains.append(dict(registers=tuple(registers), war=generator.pick((0, 0, 1, 2)),
sizes=sizes))
for entry in chains:
run_chain("chain", **entry)
# Generic requests against the heap the chain builds: sizes, alignments, descriptor flags
# (priority, bit 2), the 4 KiB page size, releases, and requests that do not fit.
SIZES = (0x10, 0x800, 0x1000, 0x1001, 0x1234, 0x3000, 0x5000, 0x7fff, 0x8000, 0xf000, 0x10000,
0x10001, 0x1f000,
0x20000, 0x30000, 0x48000, 0xe0000, 0x100000, 0x1ff000, 0x200000, 0x200001, 0x300000,
0x800000, 0x2000000)
ALIGNMENTS = (0, 0x10, 0x800, 0x1000, 0x2000, 0x3000, 0x8000, 0x10000, 0x20000, 0x30000, 0x40000,
0x100000, 0x200000, 0x400000, 0x600000)
for round_ in range(600):
registers = list(V100_REGISTERS)
registers[0] = generator.pick((0x4a, 0x8a, 0xca, 0x10a, 0x20a, 0x30a, 0x4000020a, 0x400000ba))
registers[2] = 0x60000000 | generator.pick((0x2061, 0x2061, 0x4000, 0x800, 0x7000))
registers[7] = generator.pick((16, 16, 8, 6, 24))
operations, live = [], 0
for unused in range(4 + generator.below(9)):
if live and generator.below(4) == 0:
operations.append(("f", generator.below(live)))
else:
flags = generator.pick((0, 0, 0, 0x80000, 0x80004, 4, 0x100000))
operations.append(("a", generator.pick(SIZES), generator.pick(ALIGNMENTS), flags,
generator.pick((0, 0, 1))))
live += 1
store = round_ % 3 == 0
run_chain("heap-store" if store else "heap", tuple(registers),
sizes=tuple(generator.pick((0, 0, 0x100000, 0x4000000)) for unused in SIZE_KEYS),
operations=operations, store=store)
# Hidden range: _nv039316rm and _nv039317rm on their own.
hidden_cases = 0
for visible, base, limit in ((0x1ffffff, 0, 0), (0xffffff, 0, 0), (0x7fffff, 0, 0), (0, 0, 0),
(0x1ffffff, 0x4000000, 0), (0x1ffffff, 0x2000000, 0x20fffff),
(0x1ffffff, 0, 0x5000fff), (0x3fffff, 0x400000, 0)):
for uvm in (None, 0, 1, 2, 3):
for gmmu, override, ce in ((1, None, 1), (0, None, 1), (1, 0x800, 1), (1, 0x2000, 1),
(1, 0, 1), (1, None, 0)):
for round_ in range(6):
registers = (generator.pick((0, 0x1000, 0x80, 0x7ffffff, 0xffffffff, 0x333)),
generator.pick((0x60002061, 0x60000001, 0xe00fffff, 0x40000000,
0x7ff, 0x60002000)),
generator.pick((0x40001800, 0x40000000, 0x400fffff, 0x1, 0x3001)),
generator.pick((0x1000, 0x800, 1, 0, 0x10000, 0xffffffff, 0x1001)),
generator.pick((0x1ff, 0, 1, 0xffff, 0x1ffff, 0xaaaa5555, 0x7)))
run_hidden(visible, base, limit, uvm, gmmu, override, ce, registers)
hidden_cases += 1
# Reserved base: _nv043997rm on region tables.
MEGABYTE = 1 << 20
def region(base, limit, reserved=0, flag=0, performance=0x10, compressed=1, iso=1, protected=0,
internal=0):
return (base, limit, reserved, flag, performance, compressed, iso, protected, internal)
def tables_for(megabytes):
whole = megabytes * MEGABYTE
half, quarter = whole // 2, whole // 4
yield [region(0, whole - 1)]
yield [region(0, whole - 0x100001)]
yield [region(0, whole - 0x1235)]
yield [region(0, whole + 0xfffff)]
yield [region(0, half - 1), region(half, whole - 1)]
yield [region(0, half - 1), region(half, whole - 1, flag=1)]
yield [region(0, half - 1, flag=1), region(half, whole - 1)]
yield [region(0, half - 1, protected=1), region(half, whole - 1)]
yield [region(0, half - 1), region(half, whole - 1, protected=1)]
yield [region(0, quarter - 1), region(quarter, half - 1, flag=1),
region(half, whole - 0x40001), region(whole - 0x40000, whole - 1, flag=1)]
yield [region(0x100000, quarter - 1, protected=1), region(quarter, half - 1),
region(half, 3 * quarter - 1, protected=1), region(3 * quarter, whole - 1, flag=1)]
yield [region(0, whole - 1, flag=1)]
yield [region(0, whole - 1, protected=1)]
yield [region(0x200000, 0x2fffff)]
yield []
base_cases = 0
for megabytes in (0x1000, 0x2000, 0x2c00, 0x4000, 0x7800, 0x8000, 0xc000, 3):
for table in tables_for(megabytes):
for reserved in (0x57000, 0x60000, 0x1000, 0, 0xfffff, 0x100000, 0x3b000, 0xf0001):
for extra, bottom, confidential in ((0, 0, 0), (0x8000, 0, 0), (0x10000, 0, 0),
(0, 1, 0), (0, 0, 1), (0x2000, 1, 1)):
usable = max((row[1] + 1 - row[0] for row in table if not row[3]), default=0)
run_base(table, megabytes, usable, reserved, extra, bottom, confidential)
base_cases += 1
# Comptag store: decode, line count and size.
comptag_cases = 0
for geometry in (0x401c0002, 0x401c0001, 0x401c0003, 0x401c0004, 0x101c0002, 0x201c0008,
0x411c0002, 0x421c0003, 0x4f1c0002, 0x801c0010, 0xf01cffff, 0x401c0000, 0x1c0002,
0x401cffff, 0x7fff0200, 0x10000001):
for count in (16, 1, 2, 6, 8, 12, 24, 31, 0, 0x30):
for usable in (0x800000000, 0x7fffa0000, 0x100000000, 0xf0000000, 0x400000000,
0x3ffff0000, 0x3ffff0001, 0xc00000000, 0x10000, 0xffff, 1, 0,
0x294000000):
run_comptag(geometry, count, usable, comptag_cases % 5 == 0)
comptag_cases += 1
out = ROOT / "target/gpu-stage"
out.mkdir(parents=True, exist_ok=True)
# OBJFIFO InitLocked: the requests that follow the BAR2 test page on the same heap, appended
# after every earlier row. The two dummy pages, the flush page and the test page with its
# release are the requests of stage_allocations; then the WPR primary and shadow of OBJACR
# InitLocked (_nv016953rm; the shadow descriptor has flag 4), the PMU surface of the PMU
# InitLocked (_nv052601rm: descriptor flag 4 and the 4 KiB page size) and two buffers per
# runlist owner (_nv040400rm: tools/check_gpu_fifo_load_binary.py records the request).
FIRST_OPEN = [("a", 0x10000, 0x10000, 0, 0), ("a", 0x10000, 0x10000, 0, 0),
("a", 0x1000, 0x1000, 0, 0), ("a", 0x10, 0x1000, 0, 0), ("f", 3)]
def fifo_init(registers, wpr, surface, buffers, bytes_each):
operations = list(FIRST_OPEN)
if wpr:
operations += [("a", 0xe0000, 0x20000, 0, 0), ("a", 0xe0000, 0x20000, 4, 0)]
if surface:
operations.append(("a", surface[0], 0, 4, surface[1]))
operations += [("a", bytes_each, 0x1000, 0, 0)] * buffers
result, out_, events_ = run_chain("heap-store", tuple(registers), operations=operations,
store=True)
assert result == "ok", result
return rows[-1].rsplit(";", 1)[1].split()[len(FIRST_OPEN):]
# The traced V100: 0x2008 reads 0x1000 channels (buffers of 0x20000 bytes), 13 runlists, and
# the PMU argument word of transcript line 147444 gives a surface of 0x207a00 bytes.
traced_fifo = fifo_init(V100_REGISTERS, True, (0x207a00, 1), 26, 0x20000)
assert traced_fifo[:3] == ["7fde80000", "7fdda0000", "7fdb98000"], traced_fifo[:3]
assert [int(word, 16) for word in traced_fifo[3:]] == [0x7fdb70000 - 0x20000 * number
for number in range(26)]
fifo_init_rows = 1
for registers in (V100_REGISTERS, (0x10a,) + V100_REGISTERS[1:],
V100_REGISTERS[:7] + (24,), (0x4a,) + V100_REGISTERS[1:7] + (6,)):
for wpr in (True, False):
for surface in (None, (0x207a00, 1), (0x207a00, 0), (0x1f0000, 1), (0x200000, 1),
(0x1000, 1), (0x9000, 0)):
for bytes_each in (0x20000, 0x10000, 0x4000, 0x20020, 0x40000):
fifo_init(registers, wpr, surface, 26, bytes_each)
fifo_init_rows += 1
# Direct ACR path: the requests after the BAR2 test page in the original order, each made by
# its original requester, appended after every earlier row.
EARLIER_ROWS = len(rows)
QUIET = dict(registers=dict(zip(CHAIN_KEYS, V100_REGISTERS)), registry={},
sizes=dict(zip(SIZE_KEYS, (0,) * 5)), console_feature=1, console=(MASK, 0))
reset(dict(QUIET))
call("_nv005825rm", GPU)
assert cpu.mem_read(GPU + 0x5310, 1)[0] == 1
assert status(call("_nv030827rm", GPU)) == 0
LOCATION_WORDS = bytes(cpu.mem_read(GPU + 0x5300, 16))
assert struct.unpack("<4I", LOCATION_WORDS) == (0x30033030, 0, 0xc00000, 0), LOCATION_WORDS.hex()
assert cpu.mem_read(GPU + 0x914, 1)[0] == 0
direct_executed = set()
def record_direct(emu, address, size, unused):
name = function_at(address)
if name and address == by_name.get(name):
direct_executed.add(name)
def granted(value, descriptor, mark):
assert status(value) == 0, hex(status(value))
assert not any(token.startswith("A:") for token in state["events"][mark:])
return physical(descriptor)
def surface_request(prepare):
"""A surface object as its constructor _nv052602rm leaves it, then _nv052601rm."""
surface = allocate(0x88)
assert status(call("_nv052602rm", surface, GPU, PMUOBJ)) == 0
assert (q(surface + 0x48), cpu.mem_read(surface + 0x79, 1)[0]) == (PMUOBJ, 0)
prepare(surface)
mark = len(state["events"])
value = call("_nv052601rm", GPU, surface)
descriptor = q(surface + 0x58)
assert (d(descriptor + 0xa0), q(descriptor + 0x10)) == (0xe, 0x1000)
return granted(value, descriptor, mark), descriptor
def pmu_instance(surface):
# _nv052270rm: contiguous, the three sizes of _nv052299rm, framebuffer for +84 == 0.
wb(surface + 0x79, 1)
assert status(call("_nv052299rm", PMUOBJ + 0xc20, surface + 0x50, surface + 0x68,
surface + 0x6c)) == 0
assert d(PMUOBJ + 0xc20 + 0x84) == 0
wq(surface + 0x60, 0x100000002)
def super_surface(chip):
def prepare(surface):
# _nv052522rm: framebuffer while GPU+914 and GPU+52fc are clear; the size of
# _nv052179rm for the chip word.
assert cpu.mem_read(GPU + 0x914, 1)[0] == 0 and cpu.mem_read(GPU + 0x52fc, 1)[0] == 0
wq(surface + 0x60, 0x100000002)
sizes = allocate(16)
cpu.mem_write(CHIP + 0x10, struct.pack("<H", chip))
assert status(call("_nv052179rm", GPU, sizes, sizes + 8)) == 0
cpu.mem_write(CHIP + 0x10, struct.pack("<H", 0x23))
wq(surface + 0x50, q(sizes))
return prepare
def falcon_levels():
"""The levels from the root to the 4 KiB page table of the version 2 format."""
fmt = q(q(MMU + 0x4b0) + 0x520)
assert d(fmt) == 2
level, levels = q(fmt + 8), []
while True:
low, high, entry, table, sublevels = cpu.mem_read(level, 5)
levels.append((level, low, high, entry))
if not sublevels:
return fmt, levels
level = q(level + 0x10) + 0x18 * (sublevels - 1)
def run_direct(registers, wpr, pmu, chip, buffers, bytes_each, image_bytes, traced=False):
reset(dict(QUIET, registers=dict(zip(CHAIN_KEYS, registers))))
cpu.mem_write(GPU + 0x5300, LOCATION_WORDS)
# KernelGmmu constructor _nv040666rm: framebuffer unless a location word overrides it.
word = d(GPU + 0x5300)
for selector, offset in ((word >> 24 & 3, 0x4c0), (word >> 26 & 3, 0x4c8), (word & 3, 0x4d0),
(word >> 2 & 3, 0x4d8)):
wq(MMU + offset, 0x200000002)
call("_nv043742rm", selector, 0, MMU + offset, MMU + offset + 4)
out = []
for stage in STAGES:
stage(out)
mark = len(state["events"])
checked("store", call(q(MEMSYS + 0xeb8), GPU, MEMSYS), mark)
out.append(q(MEMSYS + 0x13d0))
held = []
for operation in FIRST_OPEN:
if operation[0] == "a":
descriptor, text_ = allocation(*operation[1:])
assert descriptor, text_
held.append(descriptor)
else:
release(held[operation[1]])
hook = cpu.hook_add(UC_HOOK_CODE, record_direct, begin=BASES[".text"],
end=BASES[".text"] + len(sections[".text"])) if traced else None
words = []
if wpr:
for flags in (0, 4):
descriptor, text_ = allocation(0xe0000, 0x20000, flags)
assert descriptor, text_
words.append(int(text_, 16))
if pmu:
words.append(surface_request(pmu_instance)[0])
if chip:
words.append(surface_request(super_surface(chip))[0])
for number in range(buffers):
descriptor, text_ = allocation(bytes_each, 0x1000, 0, 0)
assert descriptor, text_
words.append(int(text_, 16))
# _nv016741rm: the HS image descriptor.
slot = allocate(8)
rounded = (image_bytes + 0xff) & 0xffffff00
def image_request():
assert status(call("_nv043694rm", slot, GPU, rounded, 0x100, 1, 2, stack=(1, 0))) == 0
wd(q(slot) + 0xa0, 0x82)
mark = len(state["events"])
return granted(call("_nv043691rm", q(slot)), q(slot), mark), q(slot)
address, image = image_request()
words.append(address)
# Falcon+98 _nv028536rm: the instance block.
mark = len(state["events"])
value = call("_nv028536rm", GPU, FALCON)
holder = q(FALCON + 0x618)
instance = q(holder + 8)
assert (q(holder), d(holder + 0x10), d(holder + 0x14), d(instance + 0xa0)) == (0x1000, 2, 2,
0x7b)
words.append(granted(value, instance, mark))
assert "z:1000" in state["events"][mark:]
# The walker's level callback for the root and then each level below it.
fmt, levels = falcon_levels()
assert [(low, high, entry) for level, low, high, entry in levels] == [
(47, 48, 8), (38, 46, 8), (29, 37, 8), (21, 28, 16), (12, 20, 8)]
wq(SPACE + 0x140, 0x20000fff)
wd(SPACE + 0xb8, 0)
wq(SPACE + 0x1000, fmt)
for number, value in enumerate((SPACE, GPU, SPACE + 0x1000, 0)):
wq(SPACE + 0x2000 + 8 * number, value)
tables = []
for number, (level, low, high, entry) in enumerate(levels):
result = SPACE + 0x3000 + 0x20 * number
cpu.mem_write(result, bytes(0x20))
mark = len(state["events"])
value = call("_nv013506rm", SPACE + 0x2000, level, 0x1000, 0x1000 + rounded - 1, 1, result,
stack=(result + 8, result + 0x10))
descriptor = q(result)
assert (d(descriptor + 0xa0), d(descriptor + 0x70), q(descriptor + 0x28),
q(descriptor + 0x10), q(descriptor + 0x30)) == (0xb0, 2, 0x1000, 0x1000, 0x1000)
assert d(result + 8) == entry << high - low + 1 and cpu.mem_read(result + 0x10, 1)[0] == 1
words.append(granted(value, descriptor, mark))
tables.append(descriptor)
if hook is not None:
cpu.hook_del(hook)
# Released, the same image request is granted the same address again.
for descriptor in reversed(tables):
release(descriptor)
release(instance)
release(image)
again, image = image_request()
assert again == address, (hex(again), hex(address))
fields = [" ".join(f"{value:x}" for value in registers), "0", "0 0 0 0 0",
f"{wpr:x} {pmu:x} {chip:x} {buffers:x} {bytes_each:x} {image_bytes:x}", "ok",
" ".join(f"{value:x}" for value in out), " ".join(f"{value:x}" for value in words)]
rows.append("direct;" + ";".join(fields))
return out, words
# The traced V100 on the path without a copy-engine channel: image, instance block and root
# at the addresses of transcript lines 141133-141146; the PMU instance block at the address
# line 147346 binds (0x10a480 = 0x407fdf7e).
direct_out, direct = run_direct(V100_REGISTERS, 1, 1, 0x23, 26, 0x20000, 0x4700, traced=True)
assert direct_out[:19] == v100[:19]
assert direct[:4] == [0x7fde80000, 0x7fdda0000, 0x7fdf7e000, 0x7fdb98000], direct[:4]
assert direct[4:30] == [0x7fdb70000 - 0x20000 * number for number in range(26)]
assert direct[30:] == [0x7fdf79000, 0x7fdf78000, 0x7fdf77000, 0x7fdf76000, 0x7fdf75000,
0x7fdf74000, 0x7fdf73000], [hex(value) for value in direct[30:]]
direct_rows = 1
for registers in (V100_REGISTERS, (0x10a,) + V100_REGISTERS[1:],
V100_REGISTERS[:7] + (24,), (0x4a,) + V100_REGISTERS[1:7] + (6,)):
for wpr, pmu, chip in ((1, 1, 0x23), (1, 1, 0), (1, 0, 0x23), (0, 1, 0x23), (0, 0, 0),
(1, 0, 0), (0, 1, 0), (1, 1, 0x18), (1, 1, 0x25), (0, 1, 0x2a)):
for buffers, bytes_each in ((26, 0x20000), (0, 0x20000), (4, 0x4000)):
for image_bytes in (0x4700, 0x4701, 0x100, 1, 0x1000, 0x7f01, 0x8000, 0x12345,
0x1ff001):
run_direct(registers, wpr, pmu, chip, buffers, bytes_each, image_bytes)
direct_rows += 1
oracle = "\n".join(rows) + "\n"
(out / "original-memory-placement.txt").write_text(oracle)
kinds, failed = {}, {}
for row in rows:
kind = row.split(";", 1)[0]
result = next(field for field in row.split(";") if field.startswith(("ok", "fail")))
kinds[kind] = kinds.get(kind, 0) + 1
if not result.startswith("ok"):
failed[kind] = failed.get(kind, 0) + 1
HOOKED = sorted(HANDLERS) + sorted(name for name, handler in SERVICES.values())
report = {
"original_sha256": DIGEST, "chip_hal": "0x23", "rm_hal": 2,
"executed_on_the_v100_chain": sorted(executed - set(HANDLERS)),
"executed_count": len(executed - set(HANDLERS)),
"fixture_supplied": HOOKED,
"slots_checked_against_bindings_report": EXPECTED,
"slots_checked_missing_from_bindings_report": UNREPORTED,
"cases": len(rows), "cases_by_kind": kinds,
"cases_where_the_original_fails_or_asserts": failed,
"v100_chain": {key: f"0x{value:x}" for key, value in EXPECTED_V100.items()},
"v100_register_reads": reads,
"transcript_comparison": transcript,
"fifo_init_rows": {
"count": fifo_init_rows, "kind": "heap-store, the last rows of the oracle",
"traced_v100": {"wpr_primary": "0x" + traced_fifo[0], "wpr_shadow": "0x" + traced_fifo[1],
"pmu_surface": "0x" + traced_fifo[2],
"runlist_buffers": ["0x" + word for word in traced_fifo[3:]]},
"runlist_buffers_equal_the_transcript": "0x2270 values of transcript lines "
"140727-140870 (first buffer of each pair) are the even entries above >> 12"},
"direct_acr_rows": {
"count": direct_rows, "kind": "direct, the last rows of the oracle",
"earlier_rows": EARLIER_ROWS,
"earlier_rows_sha256": hashlib.sha256(
("\n".join(rows[:EARLIER_ROWS]) + "\n").encode()).hexdigest(),
"instance_location_words": LOCATION_WORDS.hex(),
"executed_after_the_test_page": sorted(direct_executed - set(HANDLERS)),
"traced_v100": {
"wpr_primary": f"0x{direct[0]:x}", "wpr_shadow": f"0x{direct[1]:x}",
"pmu_instance_block": f"0x{direct[2]:x}", "pmu_super_surface": f"0x{direct[3]:x}",
"hs_image": f"0x{direct[30]:x}", "falcon_instance_block": f"0x{direct[31]:x}",
"falcon_levels_root_first": [f"0x{value:x}" for value in direct[32:]]}},
"oracle": "target/gpu-stage/original-memory-placement.txt",
"oracle_sha256": hashlib.sha256(oracle.encode()).hexdigest(),
"scope": "Original GV100 placement producers with binder-selected tables: region table, "
"BAR2 hidden range, reserved size and base, comptag store size, internal heap "
"region and the first framebuffer allocations through the original heap. Register "
"values and cross-object sizes are case inputs; no hardware executed."}
(ROOT / "reports/gpu-memory-placement-original.json").write_text(json.dumps(report, indent=2) + "\n")
print(f"{len(rows)} original memory placement cases {kinds}; original failures {failed}; "
f"executed {len(executed - set(HANDLERS))} original functions; oracle "
f"{report['oracle_sha256']}")