#!/usr/bin/env python3 """Run the original construction, use and teardown of the SEC2 Falcon address space. The environment is the one tools/check_gpu_bar2_setup_binary.py builds: 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 in two pieces (up to its handler installation, and from there to its first case); between the pieces this file replaces seven of its fixture handlers with versions that behave as before until a case's Falcon phase starts. Executed original code, entered through the three Falcon functions that the launch _nv028470rm and its cleanup call (Falcon object bound by the original binder _nv005876rm): Falcon+260 _nv028420rm Falcon+98 _nv028536rm (instance block descriptor _nv043694rm, placement override _nv043742rm, zero fill _nv044030rm); vmmCreateVaspace _nv060601rm with the object creator _nv006057rm, the address space constructor (vtable +30) and its per-GPU state, heap and walker creation; the space's vtable +e0 _nv004253rm (pin the root directory: walker _nv046252rm, level allocation _nv013506rm, root update _nv013511rm with the channel walk _nv027751rm over an empty KernelFifo); the instance block writer _nv040832rm. Falcon+270 _nv028379rm MemoryManager+358 _nv044111rm; dmaAllocMapping _nv026096rm with the virtual address allocation of the space, the walker (_nv046245rm, _nv046252rm, _nv046247rm ...), the walker callbacks of the GPU address space (_nv013503rm, _nv013506rm level allocation, _nv013508rm, _nv013509rm, _nv013511rm root update, _nv013512rm), the page-table format code, the memory transfer functions _nv044028rm, _nv044025rm/_nv044031rm, _nv044036rm, _nv044058rm and the invalidate _nv040843rm with the bus flush. Falcon+268 _nv028781rm _nv028782rm (halt wait), Falcon+278 _nv028770rm with dmaFreeMapping _nv026107rm, the space's vtable +e8 _nv004257rm, vmmDestroyVaspace _nv060602rm with the destructor and the walker's level release (_nv013507rm), Falcon+a0 _nv028537rm. Also executed: the OBJVMM creator (class 0xa030ab through _nv006057rm), the KernelGmmu constructor _nv040666rm (once per case, after the BAR2 bring-up; it sets the directory and table aperture defaults the base harness leaves zero), the KernelFifo binders _nv005912rm and _nv005792rm, memdescCreate _nv043694rm for the image descriptor with the arguments of the HS runner _nv016741rm (size rounded to 0x100, alignment 0x100, contiguous, framebuffer, cache attribute 1, flags 0; [E] tools/check_gpu_acr_load_binary.py). Fixture-supplied (everything the base harness lists, plus): * os_page_size = 0x1000; the global system pointer _nv029075rm -> a zeroed block whose +230 is the OBJVMM the original creator returned. * _nv031394rm (default GPU of a mask) -> 0, _nv031398rm (GPU by instance) -> the GPU; _nv049086rm (ancestor of class 0x7ef3cb) -> the GPU and _nv005245rm for the GPU itself (the GPU block has no class header; for every other object the original cast runs). * the registry lookup _nv049786rm -> not found (0x56). * GPU+c9c (instance) = 0; GPU+5308 = 0xc00000 (instance block placement "framebuffer", as the traced 0x87054 = 0x407fdf78 shows); GPU+1e60 -> a zeroed block; GPU+22d0 -> KernelFifo bound by its binders and otherwise zero (no channel); GPU+22d8 -> a zeroed block (its byte +7c5 clear). * the framebuffer allocator _nv043691rm: the address is a case input (image, instance block, root directory, three directories, page table, in request order); memdescFree _nv043704rm records the address. * the BAR2 mapping cache behind memdescMapInternal _nv043739rm, memdescUnmapInternal _nv043773rm and descriptor destruction _nv043699rm: a new mapping gets the lowest free BAR2 offset from a case input (0x2000 on the traced V100) and its entries are written by the original aperture update _nv039638rm; an unmap without the destroy flag (0x10) is a write-combine flush and the original bus flush of KernelBus+4a8, with the mapping kept; an unmap with it, and the destruction of a descriptor whose mapping was kept, release the offset through the original aperture update (modes 5 and 3). _nv044028rm is NOT replaced in the Falcon phase (the original runs down to _nv043739rm). * BAR2 memory: every store, fill and copy the original makes through a BAR2 mapping is translated through the page tables the original wrote and recorded with offset, framebuffer address and bytes. * the Falcon register accessors of the cleanup, _nv028672rm (reads "halted") and _nv028674rm. No hardware is involved. Oracle row: name;inputs;statuses;events. Inputs: image address, image bytes, cache attribute, instance block, root, three directories, page table, BAR2 base offset. Statuses: Falcon+260, Falcon+270, virtual address, flags the original passed to _nv026096rm, Falcon+268. Events: P: phase (the original function entered), a::
allocation, x:
release, v/u/d:: BAR2 mapping placed/released/dropped (fixture), C::
: copy, Z::
:: fill, S/L::
: store/load of n bytes, r/w register access, f write-combine flush, ts/tc/tr timeout calls of the invalidate and the bus flush, T: any other timeout start, fr/fw Falcon register fixture. """ import hashlib import json from pathlib import Path HERE = Path(__file__).resolve() SOURCE = HERE.with_name("check_gpu_bar2_setup_binary.py") INSTALL = "for name, handler in HANDLERS.items():" CASES = "\nrows = []\n" source = SOURCE.read_text() assert source.count(INSTALL) == 1 and source.count(CASES) == 1 exec(compile(source[:source.index(INSTALL)], str(SOURCE), "exec"), globals()) # noqa: S102 # ------------------------------------------------------------ fixture replacements (base_fill, base_copy, base_bar2_access, base_map_descriptor, base_unmap_descriptor, base_destroy_descriptor, base_framebuffer_allocate, base_timeout_start) = ( fill, copy, bar2_access, map_descriptor, unmap_descriptor, # noqa: F821 destroy_descriptor, framebuffer_allocate, timeout_start) # noqa: F821 REPLACED = ("os_mem_set", "os_mem_copy", "_nv043739rm", "_nv044028rm", "_nv043773rm", "_nv043699rm", "_nv043691rm", "_nv043704rm", "_nv059509rm") # Callers whose timeout start belongs to the invalidate and the bus flush. TIMED = ("_nv040843rm", "_nv018613rm") def falcon(): return state.get("falcon", False) def caller(): return function_at(q(cpu.reg_read(UC_X86_REG_RSP)) - 1) def fb_store(address, data): for position, byte in enumerate(data): word, shift = address + position & ~3, (address + position & 3) * 8 state["fb"][word] = state["fb"].get(word, 0) & ~(0xff << shift) | byte << shift def fb_load(address, size): return bytes(state["fb"].get(address + position & ~3, 0) >> (address + position & 3) * 8 & 0xff for position in range(size)) def in_bar2(address): return BAR2 <= address < BAR2 + BAR2_SIZE def fill(a): if not falcon() or not in_bar2(a[0]): return base_fill(a) offset, value, size = a[0] - BAR2, a[1] & 0xff, a[2] & 0xffffffff assert (offset & 0xfff) + size <= 0x1000 physical = translate(offset) fb_store(physical, bytes([value]) * size) emit(f"Z:{offset:x}:{physical:x}:{size:x}:{value:x}") return a[0] def copy(a): if not falcon(): return base_copy(a) destination, source_address, size = a[0], a[1], a[2] & 0xffffffff assert not in_bar2(source_address) data = bytes(cpu.mem_read(source_address, size)) if in_bar2(destination): offset = destination - BAR2 assert (offset & 0xfff) + size <= 0x1000 physical = translate(offset) fb_store(physical, data) emit(f"C:{offset:x}:{physical:x}:{data.hex()}") else: cpu.mem_write(destination, data) return destination def bar2_access(emu, access, address, size, value, unused): if not falcon(): return base_bar2_access(emu, access, address, size, value, unused) offset = address - BAR2 physical = translate(offset) if access == UC_MEM_WRITE: value &= (1 << 8 * size) - 1 fb_store(physical, value.to_bytes(size, "little")) emit(f"S{size}:{offset:x}:{physical:x}:{value:x}") else: data = fb_load(physical, size) cpu.mem_write(address, data) emit(f"L{size}:{offset:x}:{physical:x}:{int.from_bytes(data, 'little'):x}") return None def map_descriptor(descriptor, flags): if not falcon(): return base_map_descriptor(descriptor, flags) if descriptor in state["mapped"]: state["cached"].discard(descriptor) return BAR2 + state["mapped"][descriptor][0] size = descriptor_size(descriptor) address = state["case"]["bar2_base"] while True: clash = [start + length for start, length in state["mapped"].values() if address < start + length and start < address + size] if not clash: break address = max(clash) state["mapped"][descriptor] = (address, size) emit(f"v:{address:x}:{size:x}") nested(q(BUS + 0x138), [GPU, BUS, descriptor, address, size, 1], lambda status: BAR2 + address if status & 0xffffffff == 0 else 0) return None def unmap_descriptor(a): if not falcon(): return base_unmap_descriptor(a) descriptor, flags = a[1], a[2] & 0xffffffff assert descriptor in state["mapped"] and descriptor not in state["cached"] if flags & 0x10: address, size = state["mapped"].pop(descriptor) emit(f"u:{address:x}:{size:x}") nested(q(BUS + 0x138), [GPU, BUS, descriptor, address, size, 5], lambda unused: 0) return None emit("f") state["cached"].add(descriptor) nested("_nv039418rm", [BUS, 2], lambda flag: nested( q(BUS + 0x4a8), [GPU, BUS, flag & 0xffffffff], lambda unused: 0)) return None def destroy_descriptor(a): if not falcon(): return base_destroy_descriptor(a) if a[0] not in state["mapped"]: return 0 assert a[0] in state["cached"], "descriptor destroyed while mapped" state["cached"].remove(a[0]) address, size = state["mapped"].pop(a[0]) emit(f"d:{address:x}:{size:x}") nested(q(BUS + 0x138), [GPU, BUS, a[0], address, size, 3], lambda unused: 0) return None def framebuffer_allocate(a): if not falcon(): return base_framebuffer_allocate(a) address = state["case"]["pages"].pop(0) state["address"][a[0]] = address emit(f"a:{d(a[0] + 0xa0):x}:{address:x}") nested("_nv043698rm", [a[0], 2, address, q(a[0] + 0x30)], lambda unused: 0) return None def framebuffer_free(a): if falcon(): emit(f"x:{state['address'].pop(a[0]):x}") return 0 def timeout_start(a): if not falcon() or caller() in TIMED: return base_timeout_start(a) emit(f"T:{caller()}") return 0 HANDLERS.update({ # noqa: F821 "os_mem_set": fill, "os_mem_copy": copy, "_nv043739rm": lambda a: map_descriptor(a[1], a[2]), # In the Falcon phase the original _nv044028rm runs (None: no return from the hook). "_nv044028rm": lambda a: None if falcon() else map_descriptor(a[1], a[2]), "_nv043773rm": unmap_descriptor, "_nv043699rm": destroy_descriptor, "_nv043691rm": framebuffer_allocate, "_nv043704rm": framebuffer_free, "_nv059509rm": timeout_start}) assert set(REPLACED) <= set(HANDLERS) # noqa: F821 exec(compile(source[source.index(INSTALL):source.index(CASES)], str(SOURCE), "exec"), # noqa: S102 globals()) # ------------------------------------------------------------ the Falcon environment SYSTEM, OBJ_1E60 = OBJ + 0x90000, OBJ + 0x91000 FALCON_SLOTS = {0x98: "_nv028536rm", 0xa0: "_nv028537rm", 0x260: "_nv028420rm", 0x268: "_nv028781rm", 0x270: "_nv028379rm", 0x278: "_nv028770rm"} SPACE_SLOTS = {0xe0: "_nv004253rm", 0xe8: "_nv004257rm"} # Phase markers: the original function is entered, the hook only records it. PHASES = {"_nv028536rm": "instance", "_nv060601rm": "create", "_nv004253rm": "pin", "_nv040832rm": "block", "_nv044111rm": "pagesize", "_nv026096rm": "map", "_nv026107rm": "unmap", "_nv004257rm": "unpin", "_nv060602rm": "destroy", "_nv028537rm": "release"} ADDED = { "_nv031394rm": lambda a: 0, "_nv031398rm": lambda a: GPU, "_nv049786rm": lambda a: 0x56, "_nv049086rm": lambda a: GPU if a[1] & 0xffffffff == 0x7ef3cb else 1 // 0, "_nv005245rm": lambda a: GPU if a[0] == GPU else None, "_nv028672rm": lambda a: emit(f"fr:{a[2] & 0xffffffff:x}") or 0x10, "_nv028674rm": lambda a: emit(f"fw:{a[2] & 0xffffffff:x}:{a[3] & 0xffffffff:x}") or 0, } for name, handler in ADDED.items(): install(by_name[name], handler) def phase(name): def mark(a): if falcon(): state["phases"].append(name) if name == "_nv026096rm": state["map_flags"] = a[5] emit(f"P:{PHASES[name]}") return mark for name in PHASES: install(by_name[name], phase(name)) rows = [] executed.clear() V100 = dict(visible_limit=0x1ffffff, rm_limit=0xffffff, hidden_base=0x2000000, hidden_limit=0xa090fff) TRACED = dict(image=0x7fdf79000, image_bytes=0x4700, cache=1, instance=0x7fdf78000, levels=[0x7fdf77000, 0x7fdf76000, 0x7fdf75000, 0x7fdf74000, 0x7fdf73000], bar2_base=0x2000) def falcon_case(name, record=False, mmu=(), **changes): case = dict(TRACED) case.update(changes) # The BAR2 bring-up of the physical layout; its own row is not part of this oracle. status, unused, unused = run("bar2", **V100) rows.pop() assert status == 0 hook = None if record: # Coverage from here on: the environment's creators, then the Falcon phase. cpu.ctl_flush_tb() hook = cpu.hook_add(UC_HOOK_CODE, record_function, begin=BASES[".text"], end=BASES[".text"] + len(sections[".text"])) wq(externals["os_page_size"], 0x1000) wq(by_name["_nv029075rm"], SYSTEM) wq(GPU + 0x1e60, OBJ_1E60) assert call("_nv040666rm", GPU, MMU) & 0xffffffff == 0 assert [d(MMU + offset) for offset in range(0x4c0, 0x4e0, 4)] == [2] * 8 fifo, object_22d8, falcon_object, slot = (allocate(0x4000), allocate(0x1000), allocate(0x1000), allocate(16)) for binder in ("_nv005912rm", "_nv005792rm"): call(binder, fifo, CHIP, RM) assert q(fifo + 0x1e0) == by_name["_nv040359rm"] wq(GPU + 0x22d0, fifo) wq(GPU + 0x22d8, object_22d8) # OBJVMM by its own class definition (class 0xa030ab, creator at +0x10). assert d(by_name["_nv003171rm"] + 4) == 0xa030ab assert call("_nv006057rm", slot, 0, by_name["_nv003171rm"], 0) & 0xffffffff == 0 wq(SYSTEM + 0x230, q(slot)) call("_nv005876rm", falcon_object, CHIP, RM) for offset, function in FALCON_SLOTS.items(): assert q(falcon_object + offset) == by_name[function], hex(offset) assert q(MEMMGR + 0x358) == by_name["_nv044111rm"] wd(GPU + 0xc9c, 0) wd(GPU + 0x5308, 0xc00000) state["case"].update(pages=[case["image"], case["instance"], *case["levels"]], bar2_base=case["bar2_base"], mmu=list(mmu)) state.update(falcon=True, events=[], phases=[], address={}, map_flags=None) kept = dict(state["mapped"]) # The image descriptor as the HS runner creates and allocates it. size = (case["image_bytes"] + 0xff) & ~0xff assert call("_nv043694rm", slot, GPU, size, 0x100, 1, 2, stack=(case["cache"], 0)) & 0xffffffff == 0 image = q(slot) wd(image + 0xa0, 0x82) call("_nv043691rm", image) create = call("_nv028420rm", GPU, falcon_object) & 0xffffffff space = q(falcon_object + 0x648) assert create == 0 and space for offset, function in SPACE_SLOTS.items(): assert q(q(space) + offset) == by_name[function], hex(offset) va = allocate(16) mapped = call("_nv028379rm", GPU, falcon_object, 0, image, va) & 0xffffffff address = q(va) flags = state["map_flags"] # What the launch stores before the cleanup runs: Falcon+3b1, +628, +630. wb(falcon_object + 0x3b1, 1) wb(falcon_object + 0x628, 1) wq(falcon_object + 0x630, address) teardown = call("_nv028781rm", GPU, falcon_object, image, 0) & 0xffffffff assert not state["continuations"] and not state["case"]["pages"] assert q(falcon_object + 0x648) == 0 and q(falcon_object + 0x618) == 0 # Only the image is left: every page of the space and the instance block were released. assert list(state["address"]) == [image] and state["mapped"] == kept if hook is not None: cpu.hook_del(hook) state["falcon"] = False events = list(state["events"]) assert not any(token.startswith("e:") for token in events), events inputs = [case["image"], case["image_bytes"], case["cache"], case["instance"], *case["levels"], case["bar2_base"]] rows.append(f"{name};" + " ".join(f"{value:x}" for value in inputs) + f";{create:x} {mapped:x} {address:x} {flags:x} {teardown:x};" + " ".join(events)) return dict(status=(create, mapped, teardown), va=address, flags=flags, events=events, phases=list(state["phases"])) 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 # ------------------------------------------------- the traced V100 case traced = falcon_case("v100", record=True) assert traced["status"] == (0, 0, 0) and traced["va"] == 0x1000, traced assert traced["phases"] == ["_nv028536rm", "_nv060601rm", "_nv004253rm", "_nv040832rm", "_nv044111rm", "_nv026096rm", "_nv026107rm", "_nv004257rm", "_nv060602rm", "_nv028537rm"], traced["phases"] # The image descriptor has cache attribute 1 at +0x7c, so _nv028379rm passes flags 0. assert traced["flags"] == 0 # _nv044028rm is replaced only outside the Falcon phase; _nv005245rm only for the GPU block. ORIGINAL_HERE = {"_nv044028rm", "_nv005245rm"} assert ORIGINAL_HERE <= executed falcon_executed = sorted(executed - set(HOOKED) - set(ADDED) | ORIGINAL_HERE) entries = { "instance_block": stores(traced["events"], 0x7fdf78000), "root_directory": stores(traced["events"], 0x7fdf77000), "directory_1": stores(traced["events"], 0x7fdf76000), "directory_2": stores(traced["events"], 0x7fdf75000), "directory_3_dual": stores(traced["events"], 0x7fdf74000), "page_table": stores(traced["events"], 0x7fdf73000), } registers = [token for token in traced["events"] if token[:2] in ("r:", "w:")] # ------------------------------------------------- variations # Image sizes: one page (also from a size below a page), five, sixteen, odd sizes. for image_bytes in (0x100, 0x1000, 0x1001, 0x4700, 0x5000, 0x8f01, 0x10000): falcon_case("size", image_bytes=image_bytes) # Addresses: below and above 4 GiB, far apart, near both ends of a 32 GiB framebuffer. ADDRESSES = ( dict(image=0x12345000, instance=0x1000, levels=[0x2000, 0xfffff000, 0x100000000, 0x355555000, 0x7ffffe000]), dict(image=0x7ffff0000, instance=0x7fffef000, levels=[0x7fffee000, 0x7fffed000, 0x7fffec000, 0x7fffeb000, 0x7fffea000]), dict(image=0x100000000, instance=0xffffe000, levels=[0xfffff000, 0x100010000, 0xfffe0000, 0x100020000, 0xfffd0000]), dict(image=0x0, instance=0x7fdf00000, levels=[0x400000000, 0x200000000, 0x100000000, 0x80000000, 0x40000000]), dict(image=0x7aaaaa000, instance=0x555555000, levels=[0x2aaaaa000, 0x155555000, 0xaaaaa000, 0x55555000, 0x2aaaa000]), ) for addresses in ADDRESSES: for image_bytes in (0x1000, 0x4700, 0x10000): falcon_case("address", image_bytes=image_bytes, **addresses) # The cache attribute of the image descriptor selects the mapping flags (0x10 for 0). for cache in (0, 1, 2): for image_bytes in (0x1000, 0x4700): falcon_case("cache", cache=cache, image_bytes=image_bytes) # The lowest free BAR2 offset (fixture input of the mapping cache). for bar2_base in (0, 0x1000, 0x5000, 0x1ff000, 0x200000): falcon_case("base", bar2_base=bar2_base) # Invalidate polling: queue full once, acknowledge late. falcon_case("poll", mmu=[0, 0x10000, 0, 0x8000] * 64) falcon_case("poll", mmu=[0x10000, 0x8000] * 64) out = ROOT / "target/gpu-stage" out.mkdir(parents=True, exist_ok=True) oracle = "\n".join(rows) + "\n" (out / "original-falcon-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, "entry": "Falcon+260 _nv028420rm, Falcon+270 _nv028379rm, Falcon+268 _nv028781rm", "phase_functions_in_call_order": traced["phases"], "executed_after_the_bar2_bring_up_of_the_traced_case": falcon_executed, "executed_count": len(falcon_executed), "fixture_supplied": sorted((set(HANDLERS) | set(ADDED)) - {"_nv044028rm"}), "fixture_only_for_the_gpu_block": ["_nv005245rm"], "fixture_replaced_from_the_bar2_harness": sorted(REPLACED), "phase_markers_on_original_functions": PHASES, "fixture_inputs": { "os_page_size": "0x1000", "GPU+0xc9c": 0, "GPU+0x5308": "0xc00000", "GPU+0x1e60": "zeroed block", "GPU+0x22d0": "KernelFifo, bound, no channel", "GPU+0x22d8": "zeroed block", "system+0x230": "OBJVMM from its creator", "bar2_layout": {key: f"{value:#x}" for key, value in V100.items()}, "image_descriptor": "size rounded to 0x100, alignment 0x100, contiguous, space 2, " "cache attribute (case input, 1 in the HS runner), flags 0"}, "cases": len(rows), "cases_by_kind": kinds, "traced_case": { "inputs": {key: (f"{value:#x}" if isinstance(value, int) else [f"{entry:#x}" for entry in value]) for key, value in TRACED.items()}, "statuses": [f"{value:#x}" for value in traced["status"]], "virtual_address": f"{traced['va']:#x}", "flags_passed_to_nv026096rm": f"{traced['flags']:#x}", "stores_by_page": entries, "register_accesses": registers, "events": len(traced["events"])}, "oracle": "target/gpu-stage/original-falcon-vaspace.txt", "oracle_sha256": digest, "scope": "Original construction, mapping and teardown of the SEC2 Falcon address space " "(class 0x90f1) on a GV100 whose BAR2 space the original bring-up bound in the " "same emulation. Allocation addresses, the BAR2 mapping cache, register values " "and the objects listed under fixture_inputs are fixture-supplied; no hardware " "executed. Not covered: allocation failures, an instance block outside the " "framebuffer, an image of more than 16 pages, a second mapping in the space."} (ROOT / "reports/gpu-falcon-vaspace-original.json").write_text(json.dumps(report, indent=2) + "\n") print(f"{len(rows)} original Falcon address-space cases; executed {len(falcon_executed)} " f"original functions after the BAR2 bring-up; oracle SHA-256 {digest}") for label, tokens in entries.items(): print(f" {label}: " + " ".join(tokens))