#!/usr/bin/env python3 """Run the original construction, use and teardown of the GV100 PMU address space. The environment is the one tools/check_gpu_falcon_vaspace_binary.py builds on top of tools/check_gpu_bar2_setup_binary.py: the whole object relocated, KernelBus, KernelGmmu, MemoryManager, KernelMemorySystem and OBJBUS bound by their original binders (chip HAL 0x23, RM HAL 2), and for every case the complete original BAR2 bring-up of the physical V100 layout, so that BAR2 is bound and its page levels are the ones the original wrote. That file's source is executed here unchanged up to its first case. Executed original code, entered through the functions the PMU class calls in InitLocked (_nv051858rm), Load (_nv051860rm), Unload (_nv052517rm) and Destroy (_nv051856rm), in their order: space _nv052643rm (the GV100 body behind _nv052645rm): the start address from _nv040786rm, vmmCreateVaspace _nv060601rm with class 0x90f1, flags 0x4000810 and the object creator, constructor, heap and walker creation. memory _nv052601rm for each surface object (descriptor _nv043694rm, page size _nv043765rm, tag 0xe, allocation), the instance block's zero fill _nv044030rm, the super surface's sub-descriptor _nv052573rm and zero fill _nv044059rm. mapping _nv052610rm -> _nv052346rm -> _nv052341rm: MemoryManager+358 _nv044111rm, dmaAllocMapping _nv026096rm with the virtual address allocation of the space, the walker and its callbacks (level allocation _nv013506rm, root update _nv013511rm). The root update of this space (flag 0x800) enters _nv052399rm -> _nv052304rm: kgmmuInstBlkInit _nv040832rm, the space object's function at +78 (_nv052298rm on a GV100: one _nv040832rm call per subcontext, KernelFifo+170 of them, and the valid word), the bus flush KernelBus+4a8 and _nv039553rm. surface the CPU mapping _nv052575rm -> _nv018651rm and the two-word store of _nv052584rm (made here with the values _nv043721rm returns; the store itself is two fixture writes), its release _nv052580rm -> _nv018652rm. unmapping _nv052612rm -> _nv052348rm -> _nv052639rm (dmaFreeMapping _nv026107rm) for each mapping, in the Unload's order. release _nv052609rm for each surface object and vmmDestroyVaspace _nv060602rm (through the body of _nv052641rm). Fixture-supplied (everything the Falcon address-space harness lists, plus): * the PMU object: a zeroed block with +200 -> +18 -> a Falcon block whose +650 is 1, +b08 -> an object whose function at vtable +58 answers 0 (the kernel-side object: "not yet started"), +c20 the address-space object bound by its original binder _nv006033rm (asserted: +48 _nv052303rm, +78 _nv052298rm), +da8 the three words _nv052643rm fills. GPU+2120 points to it. * the surface objects: zeroed 0x80-byte blocks with the fields the original creator and its callers store, as read from the objects of tools/check_gpu_pmu_ls_start_binary.py after InitLocked: +48 the PMU, +50 bytes, +60 address space, +64 cache attribute, +68/+6c 0x1000, +79 contiguous, +7c 0. * KernelFifo: bound by its binders (KernelFifo+44d = 1 from the property initializer _nv005792rm) with +170 answering the case's subcontext count (64 on the traced V100: transcript, instance block writes 0x2a0..0x69c). * the PMU bind _nv052272rm (register accesses: core gpu::pmu_ls_start): recorded as "bind". * four fixtures of the Falcon harness are replaced before its handler table is built: os_mem_set and os_mem_copy into BAR2 may cross pages (the surface is filled through mappings of up to 1 MiB); the release of a descriptor of part of another one records nothing; _nv043773rm with flag bit 0 (its callers here are _nv052298rm and _nv018652rm) is the write-combine flush alone, because the original returns before its bus flush when that bit is set (pseudocode; the physical trace has one flush read after the subcontext words, not two). * allocation addresses: case inputs, in request order. For a system-memory descriptor the allocation is the page array the operating system would give: the case's first address and consecutive pages. No hardware is involved. Oracle row: name;inputs;statuses;events. Events as in the Falcon harness, plus P:, bind and sc: (subcontext count asked). """ import hashlib import json from pathlib import Path import sys HERE = Path(__file__).resolve() FALCON = HERE.with_name("check_gpu_falcon_vaspace_binary.py") _text = FALCON.read_text() _end = "# ------------------------------------------------- the traced V100 case" _update = "HANDLERS.update({ # noqa: F821" assert _text.count(_end) == 1 and _text.count(_update) == 1 __file__ = str(FALCON) exec(compile(_text[:_text.index(_update)], str(FALCON), "exec"), globals()) # noqa: S102 # The Falcon harness's fill and copy fixtures take one page; the PMU surface is # filled through mappings of up to 1 MiB and its page entries are copied in # runs. Its release fixture knows no descriptor of a part of another one. # Its unmap fixture flushes the bus whatever the flags. These four are replaced # before the handler table is built. _falcon_fill, _falcon_copy = fill, copy # noqa: F821 assert "framebuffer_free" in globals() def fill(a): if not falcon() or not in_bar2(a[0]): # noqa: F821 return _falcon_fill(a) offset, value, size = a[0] - BAR2, a[1] & 0xff, a[2] & 0xffffffff # noqa: F821 done = 0 while done < size: take = min(size - done, 0x1000 - (offset + done & 0xfff)) fb_store(translate(offset + done), bytes([value]) * take) # noqa: F821 done += take emit(f"Z:{offset:x}:{translate(offset):x}:{size:x}:{value:x}") # noqa: F821 return a[0] def copy(a): destination, size = a[0], a[2] & 0xffffffff if not falcon() or not in_bar2(destination): # noqa: F821 return _falcon_copy(a) assert not in_bar2(a[1]) # noqa: F821 data = bytes(cpu.mem_read(a[1], size)) # noqa: F821 offset, done = destination - BAR2, 0 # noqa: F821 while done < size: take = min(size - done, 0x1000 - (offset + done & 0xfff)) fb_store(translate(offset + done), data[done:done + take]) # noqa: F821 done += take emit(f"C:{offset:x}:{translate(offset):x}:{data.hex()}") # noqa: F821 return destination _falcon_unmap = unmap_descriptor # noqa: F821 def unmap_descriptor(a): """_nv043773rm with flag bit 0 (the callers here: _nv052298rm and _nv018652rm): the write-combine flush only; the function returns before its bus flush (test of bit 0 at its end). The Falcon harness's fixture has no such caller.""" flags = a[2] & 0xffffffff if not falcon() or flags & 0x10 or not flags & 1: # noqa: F821 return _falcon_unmap(a) assert a[1] in state["mapped"] and a[1] not in state["cached"] # noqa: F821 emit("f") # noqa: F821 state["cached"].add(a[1]) # noqa: F821 return 0 def framebuffer_free(a): """A descriptor of part of another one (_nv043696rm) owns no memory: no event.""" if falcon() and a[0] in state["address"]: # noqa: F821 emit(f"x:{state['address'].pop(a[0]):x}") # noqa: F821 return 0 exec(compile(_text[_text.index(_update):_text.index(_end)], str(FALCON), "exec"), # noqa: S102 globals()) __file__ = str(HERE) PMU_PHASES = {"_nv052643rm": "space", "_nv052601rm": "allocate", "_nv044030rm": "zero", "_nv044059rm": "fill", "_nv052610rm": "map", "_nv052399rm": "root", "_nv040832rm": "block", "_nv052298rm": "subcontexts", "_nv018651rm": "cpumap", "_nv018652rm": "cpuunmap", "_nv052612rm": "unmap", "_nv052609rm": "release", "_nv060602rm": "destroy"} def pmu_phase(name): def mark(a): if falcon(): # noqa: F821 emit(f"P:{PMU_PHASES[name]}") # noqa: F821 return mark for _name in PMU_PHASES: if _name not in PHASES: # noqa: F821 install(by_name[_name], pmu_phase(_name)) # noqa: F821 install(by_name["_nv052272rm"], lambda a: emit("bind") or 0) # noqa: F821 install(by_name["_nv052303rm"], lambda a: emit("unbind") or 0) # noqa: F821 rows = [] TRACED = dict(instance=0x7fdf7e000, surface=0x7fdb98000, surface_bytes=0x207a00, levels=[0x7fdf7d000, 0x7fdf7c000, 0x7fdf7b000, 0x7fdf7a000, 0x7fdf79000, 0x7fdf78000], buffers=[], subcontexts=64, bar2_base=0x1000, mmu=[]) def surface_object(pmu, size, space, cache, contiguous): """The fields of a surface object (class of _nv006748rm) the executed functions read.""" obj = allocate(0x80) # noqa: F821 wq(obj + 0x48, pmu) # noqa: F821 wq(obj + 0x50, size) # noqa: F821 wd(obj + 0x60, space) # noqa: F821 wd(obj + 0x64, cache) # noqa: F821 wd(obj + 0x68, 0x1000) # noqa: F821 wd(obj + 0x6c, 0x1000) # noqa: F821 wb(obj + 0x79, contiguous) # noqa: F821 return obj def pmu_case(name, record=False, **changes): # noqa: C901 case = dict(TRACED) case.update(changes) status, unused, unused = run("bar2", **V100) # noqa: F821 rows.pop() assert status == 0 hook = None if record: cpu.ctl_flush_tb() # noqa: F821 hook = cpu.hook_add(UC_HOOK_CODE, record_function, begin=BASES[".text"], # noqa: F821 end=BASES[".text"] + len(sections[".text"])) # noqa: F821 wq(externals["os_page_size"], 0x1000) # noqa: F821 wq(by_name["_nv029075rm"], SYSTEM) # noqa: F821 wq(GPU + 0x1e60, OBJ_1E60) # noqa: F821 assert call("_nv040666rm", GPU, MMU) & 0xffffffff == 0 # noqa: F821 fifo, object_22d8, slot = allocate(0x4000), allocate(0x1000), allocate(16) # noqa: F821 for binder in ("_nv005912rm", "_nv005792rm"): call(binder, fifo, CHIP, RM) # noqa: F821 # Subcontexts supported (property initializer), and the cached count of _nv040326rm. assert cpu.mem_read(fifo + 0x44d, 1)[0] == 1 # noqa: F821 assert q(fifo + 0x170) == by_name["_nv040326rm"] # noqa: F821 wd(fifo + 0x3c0, case["subcontexts"]) # noqa: F821 wq(GPU + 0x22d0, fifo) # noqa: F821 wq(GPU + 0x22d8, object_22d8) # noqa: F821 assert d(by_name["_nv003171rm"] + 4) == 0xa030ab # noqa: F821 assert call("_nv006057rm", slot, 0, by_name["_nv003171rm"], 0) & 0xffffffff == 0 # noqa: F821 vmm = q(slot) # noqa: F821 wq(SYSTEM + 0x230, vmm) # noqa: F821 wd(GPU + 0xc9c, 0) # noqa: F821 wd(GPU + 0x5308, 0xc00000) # noqa: F821 pmu, holder, flcn, kernel = (allocate(0x2000), allocate(0x40), allocate(0x800), # noqa: F821 allocate(0x80)) # noqa: F821 wq(pmu + 0x200, holder) # noqa: F821 wq(holder + 0x18, flcn) # noqa: F821 wd(flcn + 0x650, 1) # noqa: F821 wq(pmu + 0xb08, kernel) # noqa: F821 wq(kernel, kernel + 0x10) # noqa: F821 wq(kernel + 0x10 + 0x58, by_name["_nv052296rm"]) # noqa: F821 (answers 0) call("_nv006033rm", pmu + 0xc20, CHIP) # noqa: F821 assert q(pmu + 0xc20 + 0x48) == by_name["_nv052303rm"] # noqa: F821 assert q(pmu + 0xc20 + 0x78) == by_name["_nv052298rm"] # noqa: F821 wq(GPU + 0x2120, pmu) # noqa: F821 state["case"].update(pages=[], bar2_base=case["bar2_base"], mmu=list(case["mmu"])) # noqa: F821 state.update(falcon=True, events=[], phases=[], address={}, map_flags=None) # noqa: F821 kept = dict(state["mapped"]) # noqa: F821 statuses = [] def allocate_object(obj, address): rest = state["case"]["pages"] # noqa: F821 state["case"]["pages"] = [address] # noqa: F821 status = call("_nv052601rm", GPU, obj) & 0xffffffff # noqa: F821 assert not state["case"]["pages"] # noqa: F821 state["case"]["pages"] = rest # noqa: F821 return status # InitLocked: the space, the instance block, the super surface. statuses.append(call("_nv052643rm", GPU, pmu + 0xda8, vmm, MMU) & 0xffffffff) # noqa: F821 space, start, extent = q(pmu + 0xda8), q(pmu + 0xdb0), d(pmu + 0xdb8) # noqa: F821 instance = surface_object(pmu, 0x1000, 2, 1, 1) statuses.append(allocate_object(instance, case["instance"])) call("_nv044030rm", MEMMGR, q(instance + 0x58), 0, 0) # noqa: F821 wq(pmu + 0xc20 + 0x88, instance) # noqa: F821 surface = surface_object(pmu, case["surface_bytes"], 2, 1, 0) statuses.append(allocate_object(surface, case["surface"])) entry = allocate(0x80) # noqa: F821 wq(entry + 0x30, surface) # noqa: F821 statuses.append(call("_nv052573rm", entry + 0x38, q(surface + 0x58), 0, # noqa: F821 case["surface_bytes"], 0, 0) & 0xffffffff) statuses.append(call("_nv044059rm", MEMMGR, q(entry + 0x38), 0, 0, # noqa: F821 q(q(entry + 0x38) + 0x30), 0, 0) & 0xffffffff) # noqa: F821 # Load: the mapping of the surface (first use of the space), its CPU mapping and the # two-word store, then the system-memory mappings. emit("P:load") # noqa: F821 state["case"]["pages"] = list(case["levels"]) # noqa: F821 statuses.append(call("_nv052610rm", GPU, surface) & 0xffffffff) # noqa: F821 addresses = [q(surface + 0x70)] # noqa: F821 assert cpu.mem_read(surface + 0x78, 1)[0] == 1 # noqa: F821 out = allocate(16) # noqa: F821 statuses.append(call("_nv052575rm", GPU, entry + 0x38, out, 0) & 0xffffffff) # noqa: F821 mapping = q(out) - BAR2 # noqa: F821 address = call("_nv043721rm", q(surface + 0x58), 1, 0) # noqa: F821 if case["surface_bytes"] >= 0x10608: for position, word in ((0x10600, address & 0xffffffff), (0x10604, address >> 32)): physical = translate(mapping + position) # noqa: F821 fb_store(physical, word.to_bytes(4, "little")) # noqa: F821 emit(f"S4:{mapping + position:x}:{physical:x}:{word:x}") # noqa: F821 buffers = [] for size, where in case["buffers"]: emit("P:buffer") # noqa: F821 obj = surface_object(pmu, size, 1, 1, 0) statuses.append(allocate_object(obj, where)) # The allocation fixture describes framebuffer memory; describe the pages again as # system memory (memdescDescribe _nv043698rm, address space 1). call("_nv043698rm", q(obj + 0x58), 1, where, q(q(obj + 0x58) + 0x30)) # noqa: F821 statuses.append(call("_nv052610rm", GPU, obj) & 0xffffffff) # noqa: F821 addresses.append(q(obj + 0x70)) # noqa: F821 buffers.append(obj) # Unload, in its order: the surface's CPU mapping and its mapping in the space # (_nv052598rm -> _nv015302rm), the PMU+e88 surface (_nv052624rm), the logger buffer # (_nv052322rm). emit("P:unload") # noqa: F821 statuses.append(call("_nv052580rm", GPU, entry + 0x38, 0) & 0xffffffff) # noqa: F821 statuses.append(call("_nv052612rm", GPU, surface) & 0xffffffff) # noqa: F821 for obj in reversed(buffers): statuses.append(call("_nv052612rm", GPU, obj) & 0xffffffff) # noqa: F821 # Destroy. emit("P:release") # noqa: F821 for obj in buffers: call("_nv052609rm", obj) # noqa: F821 call("_nv043699rm", q(entry + 0x38)) # noqa: F821 call("_nv052609rm", surface) # noqa: F821 call("_nv052609rm", instance) # noqa: F821 call("_nv052641rm", GPU, pmu + 0xda8, vmm) # noqa: F821 assert not state["continuations"] and not state["case"]["pages"] # noqa: F821 assert not state["address"] and state["mapped"] == kept, state["mapped"] # noqa: F821 assert q(pmu + 0xda8) == 0 # noqa: F821 if hook is not None: cpu.hook_del(hook) # noqa: F821 state["falcon"] = False # noqa: F821 events = list(state["events"]) # noqa: F821 assert not any(token.startswith("e:") for token in events), events inputs = [case["instance"], case["surface"], case["surface_bytes"], case["subcontexts"], case["bar2_base"], len(case["levels"]), *case["levels"]] for size, where in case["buffers"]: inputs += [size, where] rows.append(f"{name};" + " ".join(f"{value:x}" for value in inputs) + ";" + " ".join(f"{value:x}" for value in statuses) + ";" + " ".join(f"{value:x}" for value in (start, extent, *addresses)) + ";" + " ".join(events)) return dict(statuses=statuses, start=start, extent=extent, addresses=addresses, events=events, space=space) def stores(events, page): """Copies, fills and stores into the framebuffer page at `page`, in order.""" out = [] for token in events: fields = token.split(":") if fields[0][0] in "CZS" and int(fields[2], 16) & ~0xfff == page: out.append(token) return out def levels(count, top=0x7fdf7d000): return [top - 0x1000 * index for index in range(count)] # ------------------------------------------------- the traced V100 case executed.clear() # noqa: F821 LOGGER, SHARED = (0x19d0, 0x12345000), (0x1f5b0, 0x23450000) traced = pmu_case("v100", record=True, buffers=[LOGGER, SHARED]) assert not any(traced["statuses"]), traced["statuses"] assert (traced["start"], traced["extent"]) == (0x4000000, 0x20000000) assert traced["addresses"] == [0x4000000, 0x4208000, 0x420a000], traced["addresses"] pmu_executed = sorted(executed - set(HOOKED) - set(ADDED)) # noqa: F821 entries = { "instance_block": stores(traced["events"], 0x7fdf7e000)[:8], "root_directory": stores(traced["events"], 0x7fdf7d000), "directory_1": stores(traced["events"], 0x7fdf7c000), "directory_2": stores(traced["events"], 0x7fdf7b000), "directory_3_dual": stores(traced["events"], 0x7fdf7a000), "page_table_0_first_and_last": [stores(traced["events"], 0x7fdf79000)[index] for index in (1, 512)], "page_table_1": stores(traced["events"], 0x7fdf78000)[1:43], } registers = [token for token in traced["events"] if token[:2] in ("r:", "w:")] if "--traced" in sys.argv: for label, tokens in entries.items(): print(f" {label}: " + " ".join(tokens)) sys.exit(0) # ------------------------------------------------- variations pmu_case("plain") pmu_case("logger", buffers=[LOGGER]) # Surface sizes: one page to three page tables. for size in (0x1000, 0x1001, 0x7a00, 0x10608, 0x100000, 0x100001, 0x1ff000, 0x200000, 0x200001, 0x3ff000, 0x400001): pmu_case("size", surface_bytes=size, levels=levels(4 + (size + 0x1fffff) // 0x200000)) for size in (0x1000, 0x1ff000, 0x200000): pmu_case("size", surface_bytes=size, levels=levels(4 + (size + 0xa000 + 0x1fffff) // 0x200000), buffers=[(0x1, 0xfffff000), (0x8001, 0x1_0000_0000)]) # Addresses: below and above 4 GiB, far apart. ADDRESSES = ( dict(instance=0x1000, surface=0x12345000, levels=[0x2000, 0xfffff000, 0x100000000, 0x355555000, 0x7ffffe000, 0x3000]), dict(instance=0x7fffef000, surface=0x7ffc00000, levels=[0x7fffee000, 0x7fffed000, 0x7fffec000, 0x7fffeb000, 0x7fffea000, 0x7fffe9000]), dict(instance=0xffffe000, surface=0xfff00000, levels=[0xfffff000, 0x100010000, 0xfffe0000, 0x100020000, 0xfffd0000, 0x100030000]), dict(instance=0x555555000, surface=0x0, levels=[0x400000000, 0x200000000, 0x100000000, 0x80000000, 0x40000000, 0x20000000]), ) for addresses in ADDRESSES: pmu_case("address", **addresses) pmu_case("address", buffers=[(0x19d0, 0x7_ffff_e000), (0x1f5b0, 0xabcd0000)], **addresses) for address in (0x1000, 0xfffff000, 0x1_0000_0000, 0xff_ffff_e000, 0xfff_ffff_e000, 0x7fff_ffff_e000): pmu_case("sysmem", surface_bytes=0x3000, levels=levels(5), buffers=[(0x19d0, address)]) # Subcontext counts KernelFifo+170 answers. for count in (1, 2, 16, 63): pmu_case("subcontexts", subcontexts=count, surface_bytes=0x3000, levels=levels(5)) # The lowest free BAR2 offset (fixture input of the mapping cache). for bar2_base in (0, 0x2000, 0x5000, 0x200000): pmu_case("base", bar2_base=bar2_base, surface_bytes=0x3000, levels=levels(5)) # Invalidate polling: queue full once, acknowledge late. pmu_case("poll", mmu=[0, 0x10000, 0, 0x8000] * 64, surface_bytes=0x3000, levels=levels(5), buffers=[LOGGER]) pmu_case("poll", mmu=[0x10000, 0x8000] * 64, surface_bytes=0x3000, levels=levels(5)) out = ROOT / "target/gpu-stage" # noqa: F821 out.mkdir(parents=True, exist_ok=True) oracle = "\n".join(rows) + "\n" (out / "original-pmu-vaspace.txt").write_text(oracle) digest = hashlib.sha256(oracle.encode()).hexdigest() kinds = {} for row in rows: kinds[row.split(";", 1)[0]] = kinds.get(row.split(";", 1)[0], 0) + 1 report = { "original_sha256": DIGEST, "chip_hal": "0x23", "rm_hal": 2, # noqa: F821 "entry": "_nv052643rm, _nv052601rm, _nv044030rm, _nv052573rm, _nv044059rm, _nv052610rm, " "_nv052575rm, _nv052580rm, _nv052612rm, _nv052609rm, _nv052641rm", "executed_after_the_bar2_bring_up_of_the_traced_case": pmu_executed, "executed_count": len(pmu_executed), "fixture_markers": {"bind": "_nv052272rm", "unbind": "_nv052303rm"}, "phase_markers_on_original_functions": PMU_PHASES, "cases": len(rows), "cases_by_kind": kinds, "traced_case": { "inputs": {key: (f"{value:#x}" if isinstance(value, int) else [f"{entry:#x}" if isinstance(entry, int) else [f"{item:#x}" for item in entry] for entry in value]) for key, value in dict(TRACED, buffers=[LOGGER, SHARED]).items()}, "space_start": f"{traced['start']:#x}", "space_extent": f"{traced['extent']:#x}", "virtual_addresses": [f"{value:#x}" for value in traced["addresses"]], "stores_by_page": entries, "register_accesses": registers, "events": len(traced["events"])}, "oracle": "target/gpu-stage/original-pmu-vaspace.txt", "oracle_sha256": digest, "scope": "Original construction, mappings and teardown of the PMU address space (class " "0x90f1, flags 0x4000810) on a GV100 whose BAR2 space the original bring-up bound " "in the same emulation, entered through the functions the PMU class calls. The " "PMU object, the surface objects, allocation addresses, the BAR2 mapping cache, " "the subcontext count, register values and the bind/unbind register sequences " "are fixture-supplied; no hardware executed. Not covered: allocation failures, " "an instance block outside the framebuffer, mappings made after an unmapping."} (ROOT / "reports/gpu-pmu-vaspace-original.json").write_text( # noqa: F821 json.dumps(report, indent=2) + "\n") print(f"{len(rows)} original PMU address-space cases {kinds}; executed {len(pmu_executed)} " f"original functions after the BAR2 bring-up; oracle SHA-256 {digest}")