#!/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. """ import bisect import hashlib import json 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 = Path("/home/geodd/nvidia-driver/analysis-580.178.04/extracted/kernel/nvidia/nv-kernel.o_binary") DIGEST = "5269a23ffba19a17fe16f076463e7ad4151254659441d1711bee6c6221ff6f4b" TRANSCRIPT = ROOT / "target/trace/b3-bar0.txt" BASES = {".text": 0x10000000, ".data": 0x20000000, ".rodata": 0x30000000, ".bss": 0x38000000} EXT, HEAP, OBJ, STACK, STOP = 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("> 32] if target is None: continue if kind == 1: struct.pack_into("= 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("> 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 = {} def service(name): def register(function): address = SERVICE + 16 * len(SERVICES) SERVICES[address] = (name, function) return address return register 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) @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(): """Objects as the creators, binders and constructors leave them, once.""" cpu.mem_write(OBJ, bytes(OBJ_SIZE)) cpu.mem_write(CHIP + 0x10, struct.pack("> 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))] 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("> 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']}")