#!/usr/bin/env python3 """Run the original GV100 BAR1 bring-up, mappings and teardown and write an oracle. 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 with chip HAL 0x23 and 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, as tools/check_gpu_falcon_vaspace_binary.py does; between the pieces this file replaces fixture handlers with versions that behave as before until a case's BAR1 phase starts. Executed original code (entered through the functions the stage bodies call): KernelBus InitLocked tail _nv044030rm(MemoryManager, BAR1 instance block descriptor, 0, 0): the zero fill of the block through a BAR2 mapping that stays. PreInit _nv039375rm (aperture length from the PCI size at KernelBus+558 and the registry). KernelBus PostLoad KernelBus+470 _nv039462rm (kbusInitBar1): vmmCreateVaspace _nv060601rm (class 0x90f1, flags 0x04080081) with the address-space constructor, its walker and the sparsify of the whole range; the reuse database and the two maps; the heap range; KernelBus+1f0 _nv039280rm (mailbox reservation); KernelBus+2c0/+2c8; KernelBus+498 _nv039293rm with kgmmuInstBlkInit _nv040832rm, KernelBus+4a8, _nv039553rm and the bind KernelBus+4e8 _nv039290rm; KernelBus+198. Mappings KernelBus+480 _nv039502rm (kbusMapFbAperture) through the single-range wrapper _nv039501rm, with the reuse database, _nv013915rm, _nv013917rm and dmaAllocMapping _nv026096rm; KernelBus+488 _nv039630rm through _nv039629rm with _nv013916rm and dmaFreeMapping _nv026107rm. KernelFifo PostLoad tail KernelFifo+208 _nv040417rm (register 0x2254). KernelBus PreUnload _nv039601rm: _nv039357rm (kbusDestroyBar1 with vmmDestroyVaspace _nv060602rm) and the unbind KernelBus+478 _nv039617rm. Fixture-supplied: everything tools/check_gpu_bar2_setup_binary.py lists, and what tools/check_gpu_falcon_vaspace_binary.py adds (os_page_size, the system pointer with the OBJVMM the original creator returned, the default-GPU helpers, the registry lookup answering "not found" unless a case supplies RMBar1ApertureSizeMB, GPU+c9c = 0, GPU+5308 = 0xc00000, GPU+1e60, a bound KernelFifo without channels at GPU+22d0, GPU+22d8, the framebuffer allocator _nv043691rm whose addresses are case inputs, the BAR2 mapping cache behind _nv043739rm / _nv043773rm / _nv043699rm, and BAR2 memory translated through the page tables the original wrote). Added here: a KernelBif block at GPU+1e90 whose bytes +331, +332 and word +350 are case inputs (GV100 properties 0, 0; 0 = not the BAR1 peer type), the PCI BAR sizes at KernelBus+550.., the GPU-lock ownership test _nv054098rm (owned), the descriptors of mapped memory (created by the original _nv043694rm and described at a case address by _nv043698rm, page size set by MemoryManager+358 _nv044111rm). Oracle rows: `name;inputs;statuses;events`, see `row` below. Events are those of the Falcon harness: P:, a:::::
allocation with the descriptor's request, 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, T: any other timeout start, V: a result address. No hardware is involved. """ import copy as copying import hashlib import json import random import sys from pathlib import Path if str(Path(__file__).resolve().parent) not in sys.path: sys.path.insert(0, str(Path(__file__).resolve().parent)) from _gpu_bar1_engine_oracle_check import require, write_or_check_json, write_or_check_text # noqa: E402 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() require(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, the bus flush and the bind. TIMED = ("_nv040843rm", "_nv018613rm", "_nv039290rm") def phase2(): return state.get("bar1", 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 phase2() or not in_bar2(a[0]): return base_fill(a) offset, value, size = a[0] - BAR2, a[1] & 0xff, a[2] & 0xffffffff require((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 phase2(): return base_copy(a) destination, source_address, size = a[0], a[1], a[2] & 0xffffffff require(not in_bar2(source_address)) data = bytes(cpu.mem_read(source_address, size)) if in_bar2(destination): offset = destination - BAR2 require((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 phase2(): 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 mapped_bytes(descriptor): """Pages a BAR2 mapping of the descriptor covers (its in-page offset included).""" return (d(descriptor + 0x68) + q(descriptor + 0x30) + 0xfff) & ~0xfff def map_descriptor(descriptor, flags): if not phase2(): return base_map_descriptor(descriptor, flags) adjust = d(descriptor + 0x68) if descriptor in state["mapped"]: state["cached"].discard(descriptor) return BAR2 + state["mapped"][descriptor][0] + adjust size = mapped_bytes(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 + adjust if status & 0xffffffff == 0 else 0) return None def unmap_descriptor(a): if not phase2(): return base_unmap_descriptor(a) descriptor, flags = a[1], a[2] & 0xffffffff require(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) if flags & 1: return 0 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 phase2(): return base_destroy_descriptor(a) if a[0] not in state["mapped"]: return 0 require(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 phase2(): return base_framebuffer_allocate(a) descriptor = a[0] pages = state["case"]["pages"] if not pages: emit("a:none") return 0x51 # The pool of T: gives its highest free page; the list of G: is taken in order. address = pages.pop(pages.index(max(pages)) if state["case"].get("pool") else 0) if address is None: emit("a:fail") return 0x51 state["address"][descriptor] = address emit(f"a:{d(descriptor + 0xa0):x}:{q(descriptor + 0x30):x}:{q(descriptor + 0x28):x}:" f"{q(descriptor + 0x10):x}:{address:x}") nested("_nv043698rm", [descriptor, 2, address, q(descriptor + 0x30)], lambda unused: 0) return None def framebuffer_free(a): # A sub-descriptor (_nv043696rm) was never allocated here; its release is not an event. if phase2() and a[0] in state["address"]: address = state["address"].pop(a[0]) emit(f"x:{address:x}") if state["case"].get("pool"): state["case"]["pages"].append(address) return 0 def timeout_start(a): if not phase2() or caller() in TIMED: return base_timeout_start(a) emit(f"T:{caller()}") return 0 base_read_register, base_write_register = read_register, write_register # noqa: F821 def read_register_bar1(a): offset = a[3] & 0xffffffff if phase2() and offset == 0x1704: value = state["bar1_block"] emit(f"r:{offset:x}:{value:x}") return value if phase2() and offset == 0x1710: value = pop("bind1", 0) emit(f"r:{offset:x}:{value:x}") return value return base_read_register(a) def write_register_bar1(a): offset, value = a[3] & 0xffffffff, a[4] & 0xffffffff if phase2() and offset in (0x1704, 0x2254): if offset == 0x1704: state["bar1_block"] = value emit(f"w:{offset:x}:{value:x}") return 0 return base_write_register(a) HANDLERS.update({ # noqa: F821 "os_mem_set": fill, "os_mem_copy": copy, "_nv043739rm": lambda a: map_descriptor(a[1], a[2]), # In the BAR1 phase the original _nv044028rm runs (None: no return from the hook). "_nv044028rm": lambda a: None if phase2() else map_descriptor(a[1], a[2]), "_nv043773rm": unmap_descriptor, "_nv043699rm": destroy_descriptor, "_nv043691rm": framebuffer_allocate, "_nv043704rm": framebuffer_free, "_nv059509rm": timeout_start, "_nv053907rm": read_register_bar1, "_nv053912rm": write_register_bar1}) require(set(REPLACED) <= set(HANDLERS)) # noqa: F821 exec(compile(source[source.index(INSTALL):source.index(CASES)], str(SOURCE), "exec"), # noqa: S102 globals()) # ------------------------------------------------------------ the BAR1 environment SYSTEM, OBJ_1E60, BIF = OBJ + 0x90000, OBJ + 0x91000, OBJ + 0x92000 # noqa: F821 BUS_SLOTS = {0x198: "_nv039512rm", 0x1f0: "_nv039280rm", 0x2c0: "_nv039488rm", 0x2c8: "_nv039382rm", 0x470: "_nv039462rm", 0x478: "_nv039617rm", 0x480: "_nv039502rm", 0x488: "_nv039630rm", 0x490: "_nv039402rm", 0x498: "_nv039293rm", 0x4a8: "_nv039391rm", 0x4e8: "_nv039290rm"} PHASES = {"_nv060601rm": "create", "_nv039280rm": "mailbox", "_nv040832rm": "block", "_nv039290rm": "bind", "_nv026096rm": "map", "_nv026107rm": "unmap", "_nv060602rm": "destroy", "_nv039617rm": "unbind"} def registry(a): """_nv049786rm(gpu, name, out): only RMBar1ApertureSizeMB can be present.""" name = bytes(cpu.mem_read(a[1], 32)).split(b"\0")[0].decode() # noqa: F821 megabytes = state["case"].get("registry_megabytes") if phase2() else None if name == "RMBar1ApertureSizeMB" and megabytes is not None: wd(a[2], megabytes) # noqa: F821 return 0 return 0x56 ADDED = { "_nv031394rm": lambda a: 0, "_nv031398rm": lambda a: GPU, # noqa: F821 "_nv049786rm": registry, "_nv049086rm": lambda a: GPU if a[1] & 0xffffffff == 0x7ef3cb else 1 // 0, # noqa: F821 "_nv005245rm": lambda a: GPU if a[0] == GPU else None, # noqa: F821 "_nv054098rm": lambda a: 1, # The global allocator object (.bss, filled at run time): allocate and release through it. "_nv015312rm": lambda a: allocate(a[1], 0xcc), # noqa: F821 "_nv015317rm": lambda a: 0, } for name, handler in ADDED.items(): install(by_name[name], handler) # noqa: F821 def phase(name): def mark(a): if phase2(): state["phases"].append(name) emit(f"P:{PHASES[name]}") return mark for name in PHASES: install(by_name[name], phase(name)) # noqa: F821 rows = [] executed.clear() # noqa: F821 V100 = dict(visible_limit=0x1ffffff, rm_limit=0xffffff, hidden_base=0x2000000, hidden_limit=0xa090fff) GIB = 1 << 30 TRACED = dict(bar1_bytes=32 * GIB, bar2_base=0, bif=(0, 0, 0), registry_megabytes=None) class Bar1: """One case: the environment, the BAR1 bring-up and the calls made afterwards.""" snapshot = None def __init__(self, record=False, mmu=(), bind1=(), check=(), flush=(), **changes): case = dict(TRACED) case.update(changes) self.case = case self.hook = None if Bar1.snapshot is None or record: self.environment(record) else: # The state after the BAR2 bring-up and the environment, saved by the first case. memory, saved = Bar1.snapshot for address, content in memory: cpu.mem_write(address, content) # noqa: F821 state.clear() # noqa: F821 state.update(copying.deepcopy(saved)) # noqa: F821 self.fifo, self.slot = state["fifo"], state["slot"] # noqa: F821 wq(GPU + 0x1e90, BIF) # noqa: F821 wb(BIF + 0x331, case["bif"][0]) # noqa: F821 wb(BIF + 0x332, case["bif"][1]) # noqa: F821 wd(BIF + 0x350, case["bif"][2]) # noqa: F821 # The mailbox address as the constructor step _nv039330rm leaves it. wq(BUS + 0xab70, 0xffffffffffffffff) # noqa: F821 wq(BUS + 0xab78, 0) # noqa: F821 # PCI sizes of the three memory BARs: 16 MiB, the case's BAR1, 32 MiB. wd(BUS + 0x50c, 3) # noqa: F821 for number, size in enumerate((0x1000000, case["bar1_bytes"], 0x2000000)): wq(BUS + 0x550 + 8 * number, size) # noqa: F821 state["case"].update(pages=[], bar2_base=case["bar2_base"], mmu=list(mmu), # noqa: F821 bind1=list(bind1), check=list(check), flush=list(flush), registry_megabytes=case["registry_megabytes"]) state.update(bar1=True, events=[], phases=[], address={}, bar1_block=0) # noqa: F821 self.kept = dict(state["mapped"]) # noqa: F821 slot = self.slot # _nv043997rm: the BAR1 instance block descriptor at the reserved base. base = state["case"]["reserved_base"] # noqa: F821 require(call("_nv043694rm", slot, GPU, 0x1000, 0x1000, 1, 2, # noqa: F821 stack=(2, 0)) & 0xffffffff == 0) self.block = q(slot) # noqa: F821 call("_nv043698rm", self.block, 2, base, 0x1000) # noqa: F821 wq(BUS + 0x5f8, self.block) # noqa: F821 wq(BUS + 0x5f0, base) # noqa: F821 self.statuses = [] def environment(self, record): status, unused, unused = run("bar2", **V100) # noqa: F821 rows.pop() require(status == 0) if record: cpu.ctl_flush_tb() # noqa: F821 self.hook = cpu.hook_add(UC_HOOK_CODE, record_function, # noqa: F821 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 require(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 wq(GPU + 0x22d0, fifo) # noqa: F821 wq(GPU + 0x22d8, object_22d8) # noqa: F821 require(d(by_name["_nv003171rm"] + 4) == 0xa030ab) # noqa: F821 require(call("_nv006057rm", slot, 0, by_name["_nv003171rm"], 0) & 0xffffffff == 0) # noqa: F821 wq(SYSTEM + 0x230, q(slot)) # noqa: F821 for offset, function in BUS_SLOTS.items(): require(q(BUS + offset) == by_name[function], hex(offset)) # noqa: F821 require(q(fifo + 0x208) == by_name["_nv040417rm"]) # noqa: F821 wd(GPU + 0xc9c, 0) # noqa: F821 wd(GPU + 0x5308, 0xc00000) # noqa: F821 state.update(fifo=fifo, slot=slot) # noqa: F821 if Bar1.snapshot is None and not record: memory = [(base, bytes(cpu.mem_read(base, size))) for base, size in ( # noqa: F821 (BASES[".data"], len(sections[".data"])), # noqa: F821 (BASES[".bss"], len(sections[".bss"])), # noqa: F821 (EXT, 0x10000), (OBJ, OBJ_SIZE), (HEAP, state["heap"] - HEAP + 0x1000))] # noqa: F821 Bar1.snapshot = (memory, copying.deepcopy(dict(state))) # noqa: F821 def step(self, target, *arguments, stack=()): status = call(target, *arguments, stack=stack) & 0xffffffff # noqa: F821 require(not state["continuations"]) # noqa: F821 self.statuses.append(status) return status def zero_block(self): emit("P:zero") # noqa: F821 return self.step("_nv044030rm", MEMMGR, self.block, 0, 0) # noqa: F821 def length(self): call("_nv039375rm", BUS, 0) # noqa: F821 return q(BUS + 0x5d0) # noqa: F821 def init(self): emit("P:init") # noqa: F821 return self.step("_nv039462rm", GPU, BUS, 0) # noqa: F821 def finish(self, name, inputs): if self.hook is not None: cpu.hook_del(self.hook) # noqa: F821 state["bar1"] = False # noqa: F821 events = list(state["events"]) # noqa: F821 rows.append(f"{name};" + " ".join(f"{value:x}" for value in inputs) + ";" + " ".join(f"{value:x}" for value in self.statuses) + ";" + " ".join(events)) return events def descriptor(self, address, size, attribute, alignment=0x1000): """A framebuffer descriptor at `address` with the page size of `attribute` (MemoryManager+358: 1 = 4 KiB, 2 = 64 KiB, 3 = 2 MiB, 0 = default).""" slot = allocate(16) # noqa: F821 require(call("_nv043694rm", slot, GPU, size, alignment, 1, 2, # noqa: F821 stack=(2, 0)) & 0xffffffff == 0) descriptor = q(slot) # noqa: F821 call("_nv043698rm", descriptor, 2, address, size) # noqa: F821 status = call(q(MEMMGR + 0x358), GPU, MEMMGR, descriptor, 1, attribute) & 0xffffffff # noqa: F821 require(status == 0, hex(status)) return descriptor def map_single(self, descriptor, flags, offset=0, length=None): """kbusMapFbApertureSingle _nv039501rm; returns (status, address, length).""" out = allocate(32) # noqa: F821 wq(out, 0) # noqa: F821 wq(out + 8, q(descriptor + 0x30) if length is None else length) # noqa: F821 emit(f"P:single:{flags:x}") # noqa: F821 status = self.step("_nv039501rm", GPU, BUS, descriptor, offset, out, out + 8, # noqa: F821 stack=(flags, 0)) emit(f"V:{q(out):x}:{q(out + 8):x}") # noqa: F821 return status, q(out), q(out + 8) # noqa: F821 def unmap_single(self, descriptor, address, length, flags=0): emit(f"P:unsingle:{flags:x}") # noqa: F821 return self.step("_nv039629rm", GPU, BUS, descriptor, address, length, flags) # noqa: F821 def map_managed(self, descriptor, flags, offset=0, length=None): """kbusMapFbAperture _nv039502rm with a memory area the reuse database fills.""" area = allocate(32) # noqa: F821 wq(area, 0) # noqa: F821 wq(area + 8, 0) # noqa: F821 emit(f"P:managed:{flags:x}") # noqa: F821 status = self.step("_nv039502rm", GPU, BUS, descriptor, offset, # noqa: F821 q(descriptor + 0x30) if length is None else length, area, # noqa: F821 stack=(flags, 0)) ranges = [(q(q(area) + 16 * n), q(q(area) + 16 * n + 8)) # noqa: F821 for n in range(q(area + 8))] if status == 0 else [] # noqa: F821 emit("V:" + ",".join(f"{start:x}:{size:x}" for start, size in ranges)) # noqa: F821 return status, area, ranges def unmap_managed(self, descriptor, area, flags=0): emit(f"P:unmanaged:{flags:x}") # noqa: F821 return self.step("_nv039630rm", GPU, BUS, descriptor, q(area), q(area + 8), flags) # noqa: F821 def userd_base(self, enable, offset): emit("P:userd") # noqa: F821 call(q(self.fifo + 0x208), GPU, self.fifo, enable, offset) # noqa: F821 def pre_unload(self, flags=0): emit("P:preunload") # noqa: F821 return self.step("_nv039601rm", GPU, BUS, flags) # noqa: F821 def descending(top, count=64): return [top - 0x1000 * n for n in range(count)] # ------------------------------------------------------------ scripts def script(name, text, record=False): """Runs one case. `text` is a list of space-separated steps: setup (before the first operation): L: PCI size of BAR1 (default 32 GiB) R: registry RMBar1ApertureSizeMB present with this value F::: KernelBif bytes and word pb: pc: pf: pm: values the bind status 0x1710, the timeout check, the flush register 0x70000 and 0x100c80 return, in order (then defaults) anywhere: T: framebuffer allocator: the highest free page at or below (256 pages; a released page is free again), from now on G:,,- framebuffer allocator: exactly these addresses, - fails (0x51) B: lowest BAR2 offset the mapping cache gives from now on E:: GPU byte at (a state byte of the stage bodies) operations (each adds one status): z zero fill of the instance block (_nv044030rm) i KernelBus+470 _nv039462rm m:
::::: descriptor and _nv039501rm; length 0 = the descriptor's size M:... the same through _nv039502rm (reuse database) r: _nv039501rm again for the descriptor of mapping n (flags as then) Q: _nv039502rm again for the descriptor of mapping n u: U: _nv039629rm / _nv039630rm for mapping n (in order of creation) b:: KernelFifo+208 (no status) x: KernelBus PreUnload _nv039601rm k the unbind alone, KernelBus+478 (no status) """ setup, steps = {}, text.split() polls = {"pb": "bind1", "pc": "check", "pf": "flush", "pm": "mmu"} for step in steps: key, unused, value = step.partition(":") if key == "L": setup["bar1_bytes"] = int(value, 16) elif key == "R": setup["registry_megabytes"] = int(value, 16) elif key == "F": setup["bif"] = tuple(int(part, 16) for part in value.split(":")) elif key in polls: setup[polls[key]] = [int(part, 16) for part in value.split(",")] case = Bar1(record=record, **setup) case.length() mappings = [] for step in steps: fields = step.split(":") key, arguments = fields[0], fields[1:] numbers = [int(part, 16) for part in arguments if part not in ("", "-") and "," not in part] if key in ("L", "R", "F") or key in polls: continue if key == "T": state["case"]["pages"] = descending(numbers[0], 256) # noqa: F821 state["case"]["pool"] = True # noqa: F821 elif key == "G": state["case"]["pages"] = [None if part == "-" else int(part, 16) # noqa: F821 for part in arguments[0].split(",") if part] state["case"]["pool"] = False # noqa: F821 elif key == "B": state["case"]["bar2_base"] = numbers[0] # noqa: F821 elif key == "E": wb(GPU + numbers[0], numbers[1]) # noqa: F821 elif key == "z": case.zero_block() elif key == "i": case.init() elif key in ("m", "M"): address, size, attribute, flags, offset, length = numbers descriptor = case.descriptor(address, size, attribute) if key == "m": status, start, unused = case.map_single(descriptor, flags, offset, length or None) mappings.append((descriptor, flags, start, length or size, None)) else: status, area, ranges = case.map_managed(descriptor, flags, offset, length or None) mappings.append((descriptor, flags, None, None, area)) elif key == "r": descriptor, flags = mappings[numbers[0]][:2] status, start, length = case.map_single(descriptor, flags) mappings.append((descriptor, flags, start, length, None)) elif key == "Q": descriptor, flags = mappings[numbers[0]][:2] status, area, ranges = case.map_managed(descriptor, flags) mappings.append((descriptor, flags, None, None, area)) elif key == "u": descriptor, flags, start, length, unused = mappings[numbers[0]] case.unmap_single(descriptor, start, length) elif key == "U": descriptor, flags, unused, unused, area = mappings[numbers[0]] case.unmap_managed(descriptor, area) elif key == "b": case.userd_base(numbers[0], numbers[1]) elif key == "x": case.pre_unload(numbers[0]) elif key == "k": emit("P:unbind") # noqa: F821 call(q(BUS + 0x478), GPU, BUS) # noqa: F821 else: raise AssertionError(step) leftover = [value for key in ("bind1", "check", "flush", "mmu") for value in state["case"][key]] # noqa: F821 events = case.finish(name, []) rows[-1] = f"{name};{text};" + rows[-1].split(";", 2)[2] require(not any(token.startswith("e:") for token in events) or name in LOGGING, (name, text)) return dict(statuses=list(case.statuses), events=events, leftover=leftover, phases=list(state["phases"])) # noqa: F821 # Kinds whose cases reach a diagnostic call of the original (failure branches). LOGGING = ("fail", "poll", "random", "probe") if __name__ == "__main__" and "--script" in sys.argv: result = script("probe", sys.argv[sys.argv.index("--script") + 1]) print([hex(value) for value in result["statuses"]], result["leftover"]) for token in result["events"]: print(token if len(token) < 200 else token[:200] + f"...({len(token)})") sys.exit(0) # ------------------------------------------------------------ cases START = "T:7fdf77000 z B:250000 i" # The traced first open: instance block zero fill (InitLocked), BAR1 bring-up (PostLoad), the # preallocated USERD (KernelFifo PostLoad; its framebuffer address is not in the transcript, # 0x7fd000000 is a fixture value) and the USERD base register; then a 64 KiB kernel USERD # object as the transcript maps one at 0x80000, the removals and the unload. traced = script("v100", START + " m:7fd000000:200000:1:4a4:0:0 b:1:7ffdf0000" " m:7eee20000:10000:2:20:0:0 u:1 b:0:0 u:0 x:0", record=True) require(traced["statuses"] == [0] * 7, traced["statuses"]) require(traced["phases"][:4] == ["_nv060601rm", "_nv039280rm", "_nv040832rm", "_nv039290rm"]) bar1_executed = sorted(executed - set(HOOKED) - set(ADDED) - set(PHASES) # noqa: F821 | {"_nv044028rm", "_nv005245rm"} | set(PHASES)) def results(events): return [token for token in events if token.startswith("V:")] require(results(traced["events"]) == ["V:7ffdf0000:200000", "V:80000:10000"], results( traced["events"])) # ---- transcript comparison of the traced case TRANSCRIPT_BAR12 = ROOT / "target/trace/b3-bar12-rle.txt" # noqa: F821 WINDOWS = (("instance block zero fill (KernelBus InitLocked)", "P:zero", "P:init", None, (217483.852627, 217483.860593)), ("BAR1 bring-up (KernelBus PostLoad)", "P:init", "P:single:4a4", (165442, 165465), (217520.543671, 217520.644153)), ("USERD preallocation and base register (KernelFifo PostLoad)", "P:single:4a4", "P:single:20", (167098, 167137), (217521.346866, 217521.431786))) def expected_extents(tokens): """BAR2 accesses of the oracle in the form of the run-length extract: byte copies that follow each other without another BAR2 access between them are one extent, as the extract merges them.""" out = [] for token in tokens: fields = token.split(":") kind = fields[0] if kind == "C": offset, size = int(fields[1], 16), len(fields[3]) // 2 if out and out[-1][0] == "U" and out[-1][1] + out[-1][2] == offset: out[-1] = ("U", out[-1][1], out[-1][2] + size) else: out.append(("U", offset, size)) continue if kind == "Z": out.append(("Z", int(fields[1], 16), int(fields[3], 16))) elif kind[0] in "SL" and kind[1:].isdigit(): out.append(("W" if kind[0] == "S" else "R", int(fields[1], 16), int(kind[1:]), int(fields[3], 16))) return out transcript = None if TRANSCRIPT.exists() and TRANSCRIPT_BAR12.exists(): # noqa: F821 bar0 = TRANSCRIPT.read_text().split("\n") # noqa: F821 extract = [] for line in TRANSCRIPT_BAR12.read_text().split("\n"): part = line.split() if not part or part[0] not in "EZU": continue if part[0] == "E" and part[4] == "2": extract.append((float(part[7]), (part[2], int(part[5], 16), int(part[3]), int(part[6], 16)))) elif part[0] in "ZU" and part[1] == "2": extract.append((float(part[6]), (part[0], int(part[2], 16), int(part[3])))) transcript = [] events = traced["events"] for label, first, last, lines, times in WINDOWS: window = events[events.index(first):events.index(last)] registers = [token for token in window if token[:2] in ("r:", "w:")] matched = None if lines: physical = [] for line in bar0[lines[0] - 1:lines[1]]: kind, offset, value = line.split()[:3] physical.append(f"{kind.lower()}:{int(offset, 16):x}:{int(value, 16):x}") require(physical == registers, (label, physical, registers)) matched = len(physical) else: # The zero fill's invalidate is transcript lines 138651-138655. physical = [f"{line.split()[0].lower()}:{int(line.split()[1], 16):x}:" f"{int(line.split()[2], 16):x}" for line in bar0[138650:138655]] require(physical == registers, (label, physical, registers)) matched, lines = len(physical), (138651, 138655) seen = [entry for time, entry in extract if times[0] <= time <= times[1]] wanted = expected_extents(window) require(seen == wanted, (label, [pair for pair in zip(seen, wanted) if pair[0] != pair[1]][:4], len(seen), len(wanted))) transcript.append({"window": label, "bar0_lines": f"{lines[0]}-{lines[1]}", "bar0_accesses_equal": matched, "bar2_extract_times": [f"{times[0]:.6f}", f"{times[1]:.6f}"], "bar2_extents_equal": len(seen), "bar2_bytes_copied_without_recorded_data": sum( entry[2] for entry in seen if entry[0] == "U")}) # ---- bring-up variations OBJECT = " m:7e0000000:10000:2:20:0:0 u:0 x:0" for size in (0x10000000, 0x20000000, 0x40000000, 0x100000000, 0x400000000, 0x1000000000): script("init", f"L:{size:x} " + START + OBJECT) for megabytes, size in ((0x100, 0x800000000), (0, 0x800000000), (0x10000, 0x800000000), (0x200, 0x40000000), (0x8000, 0x800000000), (0x1, 0x800000000)): script("init", f"L:{size:x} R:{megabytes:x} " + START + OBJECT) for bif in ("1:1:0", "1:0:0", "0:1:0", "0:0:1", "1:1:1"): script("init", f"F:{bif} " + START + OBJECT) for top in (0x12345000, 0x100002000, 0xfffff000, 0x7fffee000, 0x355555000): for base in (0x250000, 0x2000, 0x7ff000): script("init", f"T:{top:x} z B:{base:x} i" + OBJECT) script("init", "G:7fdf77000,12345000,400000000,5000,6000 z B:250000 i" + OBJECT) # Without the zero fill: the block is mapped at the bring-up. script("init", "T:7fdf77000 B:250000 i" + OBJECT) # A second call finds the address space and does nothing. script("second", START + " i" + OBJECT) # ---- polling: bind status, timeout checks, flush register, invalidate for bind in ("1", "2,3,0", "fffffffc", "1,1,1,1", "3,2,1"): for check in ("0", "65", "0,65", "10,0", "0,0,0,65", "65,65,65"): script("poll", f"pb:{bind} pc:{check} " + START + " x:0") for flush in ("1", "2,3,0", "1,1"): for check in ("0,0,0", "65,0,0", "0,65,0"): script("poll", f"pf:{flush} pc:{check} " + START + " x:0") for mmu in ("8000,208001", "0,10000,8000", "ff0000,0,8000", "0,0,208001"): for check in ("0,0,0,0", "65,65,65,65", "0,65,0,0"): script("poll", f"pm:{mmu} pc:{check} T:7fdf77000 B:250000 i x:0") # The bind does not wait while the GPU is marked lost or in reset (GPU+917, +918, +926). for offset in (0x917, 0x918, 0x919, 0x926): script("poll", f"pb:3,3 E:{offset:x}:1 " + START + " x:0") # ---- allocation failures of the bring-up and of a mapping for pages in ("-", "7fdf77000,-", "7fdf77000,7fdf76000,-"): script("fail", f"G:{pages} z B:250000 i x:0") # Not run: a failure of the page request that precedes the reuse of a free 0x100-byte piece # (G:7fdf74000,7fdf73000,- with attribute 1 or 2) ends in a read of unmapped memory in this # emulation; whether that is the fixture or the original was not examined. for pages in ("-", "7fdf74000,-"): for attribute in (1, 2, 3): script("fail", START + f" G:{pages} m:7e0000000:200000:{attribute}:20:0:0 x:0") # ---- mappings MAPS = ( # 4 KiB pages: one page, three pages in the next group, 17 pages. "m:7e0000000:1000:1:20:0:0 m:7e0010000:3000:1:20:0:0 u:0 u:1", "m:7e0000000:11000:1:20:0:0 u:0", # 64 KiB pages. "m:7e0000000:30000:2:20:0:0 m:7e0100000:10000:2:20:0:0 u:0 u:1", "m:7e0000000:200000:2:20:0:0 u:0", # 2 MiB pages. "m:7e0000000:400000:3:20:0:0 m:7e1000000:200000:3:20:0:0 u:0 u:1", # Mixed page sizes in one 2 MiB slot. "m:7e0000000:10000:1:20:0:0 m:7e0100000:10000:2:20:0:0 u:0 m:7e0200000:10000:2:20:0:0" " m:7e0300000:20000:1:20:0:0 u:2 u:1 u:3", # 2 MiB pages over a slot that held tables, then 4 KiB pages again. "m:7e0000000:200000:2:20:0:0 u:0 m:7e1000000:200000:3:20:0:0 u:1 m:7e2000000:200000:1:20:0:0" " u:2", "m:7e1000000:200000:3:20:0:0 u:0 m:7e2000000:10000:2:20:0:0 m:7e2100000:10000:1:20:0:0 u:1" " u:2 m:7e2000000:200000:1:20:0:0 u:3 m:7e1000000:200000:3:20:0:0 m:7e1000000:400000:1:20:0:0" " u:4 u:5", # Downward mappings (the USERD flags and the plain downward flag). "m:7e0000000:10000:2:24:0:0 m:7e0100000:10000:2:24:0:0 u:1 u:0", "m:7fd000000:200000:1:4a4:0:0 m:7e0000000:10000:2:24:0:0 m:7e0200000:200000:3:24:0:0 u:1 u:0" " u:2", # Page-size flags on the call (4 KiB, 64 KiB, 2 MiB) against the descriptor's page size. "m:7e0000000:200000:3:420:0:0 u:0 m:7e0000000:200000:3:820:0:0 u:1 m:7e0000000:200000:1:1020:0:0" " u:2 m:7e0000000:200000:0:20:0:0 u:3", # Read-only and write-only. "m:7e0000000:10000:2:28:0:0 m:7e0100000:10000:2:30:0:0 m:7e0200000:200000:3:28:0:0 u:0 u:1 u:2", # A part of a descriptor. "m:7e0000000:400000:2:20:10000:20000 m:7e0000000:400000:3:20:200000:200000 u:0 u:1", # The reuse database: the same range twice, then other descriptors. "M:7e0000000:200000:3:120:0:0 Q:0 U:0 U:1 M:7e1000000:10000:2:120:0:0 M:7e2000000:10000:2:20:0:0" " U:2 U:3", "M:7e0000000:10000:2:120:0:0 m:7e0100000:10000:2:20:0:0 U:0 u:1", ) for number, body in enumerate(MAPS): script("map", START + " " + body + " x:0") # The same without the mailbox reservation (the first mapping starts at 0). script("map", "F:1:1:0 " + START + " " + MAPS[0] + " " + MAPS[4].replace("u:0 u:1", "u:2 u:3") + " x:0") # ---- seeded random sequences of mappings and removals generator = random.Random(580178) for number in range(96): steps, live, made = [], [], 0 for unused in range(generator.randint(4, 9)): if live and generator.random() < 0.4: steps.append(f"u:{live.pop(generator.randrange(len(live)))}") continue attribute = generator.choice((1, 1, 2, 2, 2, 3)) size = {1: generator.choice((0x1000, 0x8000, 0x10000, 0x20000, 0x1f0000, 0x200000)), 2: generator.choice((0x10000, 0x20000, 0x50000, 0x200000, 0x210000)), 3: generator.choice((0x200000, 0x200000, 0x400000))}[attribute] flags = 0x24 if generator.random() < 0.2 else 0x20 steps.append(f"m:{0x700000000 + made * 0x1000000:x}:{size:x}:{attribute}:{flags:x}:0:0") live.append(made) made += 1 if generator.random() < 0.7: while live: steps.append(f"u:{live.pop(generator.randrange(len(live)))}") script("random", START + " " + " ".join(steps) + " x:0") # ---- unload script("unload", START + " x:1") script("unload", START + " E:69e4:1 x:0") script("unload", START + " b:1:7ffdf0000 b:1:0 b:0:7ffdf0000 b:1:fffffffff000 x:0") for block in (0xc07fffa0, 0xffffffff, 0x80000000, 0x307fffa0, 0): rows.append(None) Bar1() state["bar1_block"] = block # noqa: F821 emit("P:unbind") # noqa: F821 call(q(BUS + 0x478), GPU, BUS) # noqa: F821 rows[-1] = f"unbind;{block:x};;" + " ".join(state["events"]) # noqa: F821 state["bar1"] = False # noqa: F821 CHECK_MODE = "--check" in sys.argv out = ROOT / "target/gpu-stage" # noqa: F821 oracle = "\n".join(rows) + "\n" write_or_check_text(out / "original-bar1-setup.txt", oracle, check=CHECK_MODE) digest = hashlib.sha256(oracle.encode()).hexdigest() kinds, nonzero = {}, 0 for row in rows: fields = row.split(";") kinds[fields[0]] = kinds.get(fields[0], 0) + 1 nonzero += any(status != "0" for status in fields[2].split()) window = traced["events"] report = { "original_sha256": DIGEST, "chip_hal": "0x23", "rm_hal": 2, # noqa: F821 "entry": "_nv044030rm (instance block zero fill), _nv039375rm, KernelBus+470 _nv039462rm, " "_nv039501rm / KernelBus+480 _nv039502rm, _nv039629rm / KernelBus+488 _nv039630rm, " "KernelFifo+208 _nv040417rm, KernelBus PreUnload _nv039601rm (_nv039357rm, " "KernelBus+478 _nv039617rm)", "phase_functions_of_the_traced_case_in_call_order": traced["phases"], "executed_after_the_bar2_bring_up_of_the_traced_case": bar1_executed, "executed_count": len(bar1_executed), "fixture_supplied": sorted(set(HANDLERS) | set(ADDED)), # noqa: F821 "fixture_replaced_from_the_bar2_harness": sorted(REPLACED + ("_nv053907rm", "_nv053912rm")), "phase_markers_on_original_functions": PHASES, "slots_checked": {f"{offset:#x}": function for offset, function in BUS_SLOTS.items()}, "fixture_inputs": { "os_page_size": "0x1000", "GPU+0xc9c": 0, "GPU+0x5308": "0xc00000", "GPU+0x1e90": "KernelBif block: bytes +0x331, +0x332 and word +0x350 are case inputs", "KernelBus+0x50c, +0x550..": "3 BARs: 16 MiB, the case's BAR1 size, 32 MiB", "bar2_layout": {key: f"{value:#x}" for key, value in V100.items()}, "instance_block": "descriptor of _nv043694rm described at the reserved base " "(_nv043997rm does this in the original)", "mapped_descriptors": "_nv043694rm (size, alignment 0x1000, contiguous, framebuffer), " "_nv043698rm at the case address, MemoryManager+358 page size"}, "cases": len(rows), "cases_by_kind": kinds, "cases_with_a_nonzero_status": nonzero, "traced_case": { "script": rows[0].split(";")[1], "statuses": [f"{value:#x}" for value in traced["statuses"]], "result_addresses": results(window), "level_requests": [token for token in window if token.startswith("a:")][:3], "instance_block_stores": [token for token in window if token.startswith("S")], "register_accesses_of_the_bring_up": [ token for token in window[window.index("P:init"):window.index("P:single:4a4")] if token[:2] in ("r:", "w:")], "events": len(window)}, "transcript_comparison": transcript, "oracle": "target/gpu-stage/original-bar1-setup.txt", "oracle_sha256": digest, "scope": "Original GV100 BAR1 bring-up (kbusInitBar1), mappings and removals through the " "original entry points, the USERD base register and the unload, on a BAR2 space " "the original bring-up bound in the same emulation. Allocation addresses, the " "BAR2 mapping cache, register values, the KernelBif bytes and the mapped " "descriptors are fixture-supplied; no hardware executed. Not covered: the " "console mapping (KernelBus+acba), a virtual function, SLI, the static BAR1 " "path (stubs on GV100), system-memory mappings through BAR1, the PostLoad " "conditions of _nv039597rm around the call (read at instruction level only)."} write_or_check_json(ROOT / "reports/gpu-bar1-setup-original.json", report, check=CHECK_MODE) # noqa: F821 print(f"{len(rows)} original BAR1 cases ({nonzero} with a nonzero status); executed " f"{len(bar1_executed)} original functions after the BAR2 bring-up; oracle SHA-256 {digest}" + ("; transcript: " + ", ".join(f"{entry['bar0_accesses_equal']} BAR0 + " f"{entry['bar2_extents_equal']} BAR2" for entry in transcript) if transcript else "; transcript absent"))