#!/usr/bin/env python3 """Run the original RM side of the UVM interface for the workload's per-context path (UVM slice 2) and write an oracle for the Rust `uvm::gpu_ops` module. Executed original code (580.178.04 nv-kernel.o_binary, whole object relocated; loader and fixtures of tools/check_rmapi_binary.py and tools/rmapi_binary_emulator.py, imported and not modified). Unlike slice 1 the RM underneath is the original's own: the GPU object is the one the original constructs for the traced V100 (check_rmapi_binary.gpu_world: core init, probe, attach, the base PreInit sweep and KernelMemorySystem PreInitLocked), and the client, device, subdevice and VA space objects are allocated through the original resource server. The RM API table the entry points obtain from rmapiGetInterface (_nv054239rm) is replaced by a recording table per interface type. Each slot records the request and then either * answers from the case ("canned": controls and classes whose handlers need engine state this fixture cannot produce, named per case), or * enters the original slot function of the same interface with the same arguments ("real") and records what it returned. See the functions `*_cases` for what each case constructs, and analysis/closed-driver-580/uvm.md (section "Slice 2") for the findings. """ import hashlib import json import struct import sys def _require(condition, message=None): if not condition: raise AssertionError(message if message is not None else 'check failed') from unicorn import UC_HOOK_CODE from unicorn.x86_const import UC_X86_REG_RAX, UC_X86_REG_RSP import check_rmapi_binary as R import check_uvm_gpu_ops_binary as S1 from rmapi_binary_emulator import BASES, DIGEST, HEAP, ROOT, STOP E = R.E OUT = ROOT / "target/uvm" SLOT = STOP + 0x200 # 0x40 slots of 8 bytes: one stub address per slot SLOT_NAMES = {0: "alloc", 3: "free", 7: "control", 10: "dup", 12: "share", 14: "map", 17: "unmap"} # Stack arguments (beyond the six register arguments) of each slot function. SLOT_STACK = {0: 1, 3: 0, 7: 0, 10: 1, 12: 0, 14: 2, 17: 1} CANNED_HANDLE = 0xcc000000 CANNED_MAPPING = 0x7100000000 def sparse(data): """`len:off=hex,off=hex` with the zero bytes left out.""" runs, start = [], None for offset, byte in enumerate(data): if byte and start is None: start = offset if not byte and start is not None: runs.append((start, offset)) start = None if start is not None: runs.append((start, len(data))) merged = [] for begin, end in runs: if merged and begin - merged[-1][1] < 4: merged[-1] = (merged[-1][0], end) else: merged.append((begin, end)) return f"{len(data):x}:" + ",".join(f"{begin:x}={data[begin:end].hex()}" for begin, end in merged) class Api: """The recording RM API. `canned`: {("alloc", class) | command | "map": reply}; a reply is bytes (status 0), (status, bytes), a status, or a callable of the request bytes. Requests without an entry run the original slot function.""" def __init__(self): self.real = {} # interface type -> original table self.fake = {} # fake table address -> interface type self.active = False self.depth = 0 self.lines, self.canned, self.fail, self.count = [], {}, None, 0 self.canned_handles = set() self.next_canned = 0 self.pointers = {} # kernel pointers seen in parameter blocks -> token def begin(self, canned=None, fail=None): self.lines, self.canned, self.fail, self.count = [], dict(canned or {}), fail, 0 def interface(self, a): """Fixture of _nv054239rm (rmapiGetInterface): the recording table of that type.""" if not self.active or self.depth: # Requests of the original's own handlers below a "real" slot are not recorded. return None kind = a[0] & 0xffffffff for table, known in self.fake.items(): if known == kind: return table raise AssertionError(f"RM API interface {kind} has no recording table") def tables(self, kinds): """Called once per world, with the recording switched off: learn the original tables and build the recording ones.""" self.real, self.fake = {}, {} for kind in kinds: self.real[kind] = E.call("_nv054239rm", kind) table = E.allocate(0x200) for index in range(0x40): E.wq(table + 8 * index, SLOT + 8 * index) self.fake[table] = kind def injected(self): index = self.count self.count += 1 if self.fail is not None and self.fail[0] == index: return self.fail[1] return None def enter(self, index, a, after): """Run the original slot function with the caller's arguments and resume the caller with what `after(status)` returns.""" kind = self.fake[a[0]] target = E.q(self.real[kind] + 8 * index) rsp = E.cpu.reg_read(UC_X86_REG_RSP) count = SLOT_STACK[index] stack = [E.q(rsp + 8 + 8 * number) for number in range(count)] new = rsp - 8 * count - (8 if count % 2 == 0 else 0) - 0x40 new &= ~0xf for number, value in enumerate(stack): E.wq(new + 8 * number, value) E.cpu.reg_write(UC_X86_REG_RSP, new) self.depth += 1 def resume(status): self.depth -= 1 E.cpu.reg_write(UC_X86_REG_RSP, rsp) return after(status & 0xffffffff) E.nested(target, [self.real[kind]] + list(a[1:]), resume) def reply(self, key, request): reply = self.canned.get(key) if callable(reply): reply = reply(request) return reply def kind(self, a): return self.fake[a[0]] def alloc(self, a): client, parent, klass = a[1] & 0xffffffff, a[2] & 0xffffffff, a[4] & 0xffffffff size = E.stack_argument(0) & 0xffffffff handle_in = E.d(a[3]) params = E.read(a[5], size) if a[5] and size else None head = (f"call alloc {self.kind(a)} {client:x} {parent:x} {handle_in:x} {klass:x}" f" {self.block(klass, params) if params is not None else '-'}") def finish(status, how): handle_out = E.d(a[3]) out = E.read(a[5], size) if params is not None else None self.lines.append(f"{head} -> {status:x} {handle_out:x}" f" {self.block(klass, out) if out is not None else '-'} {how}") return status status = self.injected() if status is not None: return finish(status, "injected") reply = self.reply(("alloc", klass), params) if reply is None: self.enter(0, a, lambda status: finish(status, "real")) return None status, data = reply if isinstance(reply, tuple) else ( (reply, None) if isinstance(reply, int) else (0, reply)) if status == 0: if handle_in == 0: self.next_canned += 1 E.wd(a[3], CANNED_HANDLE + self.next_canned) self.canned_handles.add(E.d(a[3])) if data is not None: E.write(a[5], data) return finish(status, "canned") def block(self, key, data): """Parameter bytes with kernel pointers of the fixture replaced by a token.""" edit = POINTER_FIELDS.get(key) if edit is None or data is None: return sparse(data) data = bytearray(data) for offset in edit: value = struct.unpack_from(" 0 canned") return 0 def finish(status): self.lines.append(f"{head} -> {status:x} real") return status self.enter(3, a, finish) return None def control(self, a): client, obj, command = a[1] & 0xffffffff, a[2] & 0xffffffff, a[3] & 0xffffffff size = a[5] & 0xffffffff params = E.read(a[4], size) if a[4] and size else b"" if command == 0x800201: return self.class_list(a, client, obj, params) head = (f"call control {self.kind(a)} {client:x} {obj:x} {command:x}" f" {self.block(command, params)}") def finish(status, how): out = E.read(a[4], size) if size else b"" self.lines.append(f"{head} -> {status:x} {self.block(command, out)} {how}") return status status = self.injected() if status is not None: return finish(status, "injected") reply = self.reply(command, params) if reply is None: self.enter(7, a, lambda status: finish(status, "real")) return None status, data = reply if isinstance(reply, tuple) else ( (reply, None) if isinstance(reply, int) else (0, reply)) if data is not None: _require(len(data) == size, (hex(command), len(data), size)) E.write(a[4], data) return finish(status, "canned") def class_list(self, a, client, obj, params): """NV0080_CTRL_CMD_GPU_GET_CLASSLIST: {numClasses, pad, classList pointer}.""" count_in, pointer = struct.unpack(" {status:x} {E.d(a[4]):x} {listed}") return status def dup(self, a): client, parent = a[1] & 0xffffffff, a[2] & 0xffffffff source_client, source = a[4] & 0xffffffff, a[5] & 0xffffffff flags = E.stack_argument(0) & 0xffffffff handle_in = E.d(a[3]) head = (f"call dup {self.kind(a)} {client:x} {parent:x} {handle_in:x}" f" {source_client:x} {source:x} {flags:x}") def finish(status, how): self.lines.append(f"{head} -> {status:x} {E.d(a[3]):x} {how}") return status status = self.injected() if status is not None: return finish(status, "injected") reply = self.reply("dup", (source_client, source)) if reply is None: self.enter(10, a, lambda status: finish(status, "real")) return None if reply == 0: if handle_in == 0: self.next_canned += 1 E.wd(a[3], CANNED_HANDLE + self.next_canned) self.canned_handles.add(E.d(a[3])) return finish(reply, "canned") def share(self, a): head = (f"call share {self.kind(a)} {a[1] & 0xffffffff:x} {a[2] & 0xffffffff:x}" f" {E.read(a[3], 12).hex()}") status = self.injected() if status is not None: self.lines.append(f"{head} -> {status:x} injected") return status def finish(status): self.lines.append(f"{head} -> {status:x} real") return status self.enter(12, a, finish) return None def map(self, a): """MapToCpu(api, client, device, memory, offset, length, &pointer, flags).""" client, device, memory = (value & 0xffffffff for value in a[1:4]) offset, length = a[4], a[5] out, flags = E.stack_argument(0), E.stack_argument(1) & 0xffffffff head = (f"call map {self.kind(a)} {client:x} {device:x} {memory:x} {offset:x}" f" {length:x} {flags:x}") status = self.injected() how = "injected" if status is None: reply = self.reply("map", memory) _require(reply is not None, "MapToCpu is always answered by the case") status, how = reply, "canned" if status == 0: # A distinct token per mapped object; the original only stores it. E.wq(out, CANNED_MAPPING + (memory & 0xffff) * 0x100000) self.lines.append(f"{head} -> {status:x} {1 if status == 0 else 0} {how}") return status def unmap(self, a): """UnmapFromCpu(api, client, device, memory, pointer, flags, process).""" client, device, memory = (value & 0xffffffff for value in a[1:4]) self.injected() self.lines.append(f"call unmap {self.kind(a)} {client:x} {device:x} {memory:x}" f" {1 if a[4] else 0} {a[5] & 0xffffffff:x} -> 0 canned") return 0 def other(self, index): def run(a): raise AssertionError(f"RM API slot {index:#x} is not part of these paths") return run # Parameter-block fields that hold kernel pointers of the fixture: {class or command: # offsets}. NV0005_ALLOC_PARAMETERS (class 0x7e, 0x18 bytes) carries the callback at +0x10. POINTER_FIELDS = {0x7e: (0x10,)} API = Api() PAGES = {"registered": [], "fail": None} def register_phys_pages(a): """nv_register_phys_pages(nv, addresses, count, cache type, &private).""" count = a[2] _require(count < 0x10000, hex(count)) PAGES["registered"].append(("register", [E.q(a[1] + 8 * index) for index in range(count)], a[3] & 0xffffffff)) if PAGES["fail"] is not None: return PAGES["fail"] E.wq(a[4], 0x5150000 + 0x100 * len(PAGES["registered"])) return 0 def unregister_phys_pages(a): PAGES["registered"].append(("unregister", a[1])) return 0 LOCKS = {"fail": None, "count": 0} def lock_all(a): """_nvGpuOpsLocksAcquireWithClientLockFlags(API lock flags, client lock flags, client, &pClient, number of GPU locks, instance 1, instance 2, &lock set).""" if not API.active or API.depth: return None index = LOCKS["count"] LOCKS["count"] += 1 head = (f"call lock {a[0] & 0xffffffff:x} {a[1] & 0xffffffff:x} {a[2] & 0xffffffff:x}" f" {a[4] & 0xffffffff:x}") if LOCKS["fail"] is not None and LOCKS["fail"][0] == index: API.lines.append(f"{head} -> {LOCKS['fail'][1]:x} injected") return LOCKS["fail"][1] API.lines.append(f"{head} -> 0 real") return None def unlock_all(a): if API.active and not API.depth: API.lines.append("call unlock -> 0 real") return None FAKE_MEMORY = {} def memory_lookup(a): """memGetByHandle (_nv043666rm): the fixture Memory object of a handle the case made, whichever client asks (the duplicate keeps the handle of the original here).""" handle = a[1] & 0xffffffff if handle in FAKE_MEMORY: E.wq(a[2], FAKE_MEMORY[handle]) return 0 return None GID = {"status": 0, "uuid": bytes(range(0xc0, 0xd0))} def gid_info(a): """gpuGetGidInfo (_nv030562rm): the GPU's SHA-1 UUID in binary form. The original derives it from identity data this fixture does not hold, so the case supplies it.""" if not API.active: return None if GID["status"] == 0: buffer = E.allocate(16) E.write(buffer, GID["uuid"]) E.wq(a[1], buffer) E.wd(a[2], 16) return GID["status"] def install(): """Install every replacement before any original instruction runs (hooks added to already translated code do not fire); `API.active` switches the RM API table.""" handlers = {0: API.alloc, 3: API.free, 7: API.control, 10: API.dup, 12: API.share, 14: API.map, 17: API.unmap} for index in range(0x40): E.install(SLOT + 8 * index, handlers.get(index, API.other(index))) E.install("_nv054239rm", API.interface) E.handlers.pop("_nv054239rm") E.install("nv_register_phys_pages", register_phys_pages) E.install("nv_unregister_phys_pages", unregister_phys_pages) # _nvGpuOpsLocksAcquire (_nv014211rm) and _nvGpuOpsLocksRelease (_nv014212rm): observed, # and the acquisition can be made to fail by the case. E.install("_nv014211rm", lock_all) E.handlers.pop("_nv014211rm") E.install("_nv014212rm", unlock_all) E.handlers.pop("_nv014212rm") E.install("_nv043666rm", memory_lookup) E.handlers.pop("_nv043666rm") E.install("_nv030562rm", gid_info) E.handlers.pop("_nv030562rm") def runtime_stack(): """nvidia_stack_t as the thunks use it: the RM stack top at +8.""" stack = E.allocate(0x100) area = E.allocate(0x20000) E.wq(stack + 8, area + 0x18000) return stack class World: """One constructed GPU with a user client (device of VA mode 2 as libcuda makes it, subdevice) and a UVM session, all made by the original. `snapshot` and `restore` let many cases start from the same state.""" USER = 0xc1d00001 def __init__(self, name): API.active = False self.case = R.GpuSequence(name) case = self.case self.gpu = case.gpu _require(case.alloc(0, 0, 0, 0)[1] == self.USER) case.initialized(1) good = R.device_params(share=self.USER, mode=2) result, self.device = case.alloc(self.USER, self.USER, 0, 0x80, params=good) _require(result == 0) result, self.subdevice = case.alloc(self.USER, self.device, 0, 0x2080, params=bytes(4)) _require(result == 0) _require(case.sweep() == 0) case.stage("kms-preinit") # Data symbols of the open layer (os-interface.c): 4 KiB pages. E.wq(E.externals["os_page_size"], 0x1000) E.wq(E.externals["os_page_shift"], 12) E.wq(E.externals["os_page_mask"], 0xfffffffffffff000) API.tables((1, 2, 3, 4, 5)) self.stack = runtime_stack() out = E.allocate(16) _require(self.call("rm_gpu_ops_create_session", out) == 0) self.session = E.q(out) self.session_client = E.d(self.session) self.saved = None UUID = bytes(range(0xc0, 0xd0)) def describe(self): """What the Rust model of this world needs: the GPU properties the entry points read (architecture GPU+0xd00, implementation +0xd04, id +0xca4, zero-FB property +0x92b, virtual +0xe00, SR-IOV +0x4de7 and heavy +0x52f9, MIG manager +0x1fc8), the session client and the user's client, device and subdevice.""" gpu = self.gpu return (f"world {E.d(gpu + 0xd00):x} {E.d(gpu + 0xd04):x} {E.d(gpu + 0xca4):x}" f" {E.b(gpu + 0x92b)} {E.b(gpu + 0xe00)} {E.b(gpu + 0x4de7)}" f" {E.b(gpu + 0x52f9)} {1 if E.q(gpu + 0x1fc8) else 0}" f" {self.session_client:x} {self.USER:x} {self.device:x} {self.subdevice:x}") def snapshot(self): self.saved = dict( sections={name: E.read(BASES[name], len(E.pristine[name])) for name in (".data", ".bss")}, heap=E.read(HEAP, E.heap - HEAP), top=E.heap, state={key: (list(value) if isinstance(value, list) else dict(value) if isinstance(value, dict) else value) for key, value in R.state.items()}, gpu_state={key: (list(value) if isinstance(value, list) else dict(value) if isinstance(value, dict) else value) for key, value in R.gpu_state.items()}, api=(set(API.canned_handles), API.next_canned), externals=E.read(E.externals["os_page_size"] & ~0xfff, 0x1000)) def restore(self): saved = self.saved for name, content in saved["sections"].items(): E.write(BASES[name], content) E.write(HEAP, saved["heap"]) E.heap = saved["top"] for target, source in ((R.state, saved["state"]), (R.gpu_state, saved["gpu_state"])): for key, value in source.items(): target[key] = (list(value) if isinstance(value, list) else dict(value) if isinstance(value, dict) else value) API.canned_handles, API.next_canned = set(saved["api"][0]), saved["api"][1] PAGES["registered"], PAGES["fail"] = [], None LOCKS["fail"] = None FAKE_MEMORY.clear() GID["status"] = 0 def user_alloc(self, parent, klass, params): return self.case.alloc(self.USER, parent, 0, klass, params=params) def vaspace(self, flags=0x48, base=0x1000, parent=None, **fields): result, handle = self.user_alloc(parent or self.device, 0x90f1, R.vaspace_params(flags=flags, base=base, **fields)) _require(result == 0, hex(result)) return handle def call(self, name, *arguments, canned=None, fail=None, lock_fail=None): API.begin(canned, fail) LOCKS["fail"], LOCKS["count"] = lock_fail, 0 R.state["diag"].clear() R.gpu_state["read"].clear() R.gpu_state["written"].clear() API.active, API.depth = True, 0 # A register an entry point reads enters the case with its first value in the # physical transcript of the traced V100; writes are recorded, not applied. # The flush registers (0x70004..0x70010) are not in the transcript: they read as # idle (0). R.gpu_state["source"] = dict(R.first_reads()) R.gpu_state["source"].update({0x70004: 0, 0x70008: 0, 0x7000c: 0, 0x70010: 0}) for offset in (0x70004, 0x70008, 0x7000c, 0x70010): R.gpu_state["registers"].pop(offset, None) try: full = (self.stack,) + arguments return E.call(name, *full[:6], stack=full[6:]) & 0xffffffff finally: API.active = False R.gpu_state["source"] = None def footer(self): """Register accesses and assertion records of the last call.""" reads = ",".join(f"{offset:x}={R.gpu_state['registers'][offset]:x}" for offset in R.gpu_state["read"]) or "-" writes = ",".join(f"{offset:x}={value:x}" for offset, value in R.gpu_state["written"]) or "-" return [f"registers {reads} {writes}", "asserts " + (",".join(R.state["diag"]) or "-")] # --------------------------------------------------------------------------------------- # rm_gpu_ops_device_create -> _nv046795rm (nvGpuOpsDeviceCreate) and # rm_gpu_ops_device_destroy -> _nv046796rm. def fb_info_reply(heap_size, reserved, broken, heap_start): def run(params): reply = bytearray(params) for index, value in enumerate((heap_size, reserved, broken, heap_start)): struct.pack_into(" (enabled, supported).""" reply = bytearray(0x5b8) for index, (enabled, supported) in units.items(): reply[0x28 * index] = enabled reply[0x28 * index + 2] = supported return bytes(reply) def device_canned(ecc=None, nvlink=bytes(0x30), classes=None): canned = { 0x274: S1.uuid_info(0, 0), ("alloc", 0xc361): 0, "map": lambda memory: 0, 0x2080012f: 0x56 if ecc is None else ecc, 0x20803001: nvlink, ("alloc", 0x90e6): 0, 0x90e60101: struct.pack(" _nv046800rm, address_space_create -> # _nv046771rm (both with getAddressSpaceInfo _nv029315rm), address_space_destroy -> # _nv046772rm, set_page_directory -> _nv046861rm, unset_page_directory -> _nv046867rm. # The VA space objects, DupObject and the controls 0x801806, 0x801813 and 0x801814 are the # original's; only NV2080_CTRL_CMD_FIFO_GET_INFO (0x20801109) is answered by the case. def fifo_info(count): def run(params): return params[:8] + struct.pack(" _nv046802rm -> _nv026760rm (dupMemory), # free_duped_handle -> _nv046808rm, get_external_alloc_ptes -> _nv046815rm -> _nv046816rm # -> _nv046777rm (nvGpuOpsBuildExternalAllocPtes). # # No memory class can be allocated in this fixture (no heap, no page allocator), so the # Memory object behind a handle is fixture memory: the lookup memGetByHandle (_nv043666rm) # returns it, and DupObject is answered by the case. Its memory descriptor is the # original's: memdescCreate (_nv043694rm), memdescDescribe (_nv043698rm) or a page array # written into the descriptor, memdescSetPageSize (_nv043765rm), memdescSetPteKindForGpu # (_nv043768rm), with the GPU cache attribute poked at +0x74. Everything the entry points # compute from it (page size, addresses, PTE bytes, cache flush) is original code. MEMDESC_READ_ONLY = 1 << 33 MEMDESC_ENCRYPTED = 1 << 11 MEMDESC_PRIVILEGED = 1 << 13 MEMDESC_SYSCOH_OVER_BAR1 = 1 << 39 def no_class(): """An NVOC run-time type that casts to nothing: {class definition, destructor, offset} with an empty cast list.""" rtti, definition, casts = E.allocate(0x20), E.allocate(0x40), E.allocate(0x10) E.wq(rtti, definition) E.wd(definition + 4, 0x7e57c1a5) E.wq(definition + 0x18, casts) return rtti _pte_array = {} def pte_array_offset(world): if "offset" not in _pte_array: out, marker = E.allocate(8), 0x5a17e5a17000 _require(E.call("_nv043694rm", out, world.gpu, 0x1000, 0, 1, 2, stack=(0, 0)) & 0xffffffff == 0) E.call("_nv043698rm", E.q(out), 2, marker, 0x1000) _pte_array["offset"] = E.read(E.q(out), 0x200).index(struct.pack(" _nv046811rm (the PTE builder on a context-buffer # descriptor, no Memory object) and rm_gpu_ops_release_channel -> _nv046853rm -> # _nv014215rm (_nvGpuOpsReleaseChannel). The retained-channel structure (0xb8 bytes: # device +0, session +0x18, resource descriptors from +0x30, their count +0x9c, the TSG # duplicate +0xac, the context-share duplicate +0xb0, the retainer +0xb4) is fixture memory # here, as is every descriptor; the handles are answered by the case. def channel_cases(world): run = Runner(world) user = world.USER hooks = {symbol: E.install(symbol, handler) for symbol, handler in R.STAGE_FIXTURES.items()} def start(name): run.begin(name) external = run.user_vaspace() device = run.standard_device() _require(run.dup_address_space(device, user, external) == 0) return device, run.spaces[0] def ptes(space, handle, descriptor, offset, size, buffer_size=0x100, lock_fail=None, **fields): info, buffer = mapping_info(buffer_size=buffer_size, **fields) status = world.call("rm_gpu_ops_get_channel_resource_ptes", space, descriptor, offset, size, info, canned={}, lock_fail=lock_fail) text = " ".join(f"{fields.get(key, 0):x}" for key in ("caching", "mapping", "page_size")) run.op(f"get_channel_resource_ptes 0 {handle:x} {offset:x} {size:x} {buffer_size:x}" f" {text}", status, pte_result(info, buffer, buffer_size)) return status # Context buffers as RM allocates them: video memory in 4 KiB pages, contiguous or # not, GPU cached; and system memory. device, space = start("chan-ptes") pages = [0x7e0005000, 0x7e0001000, 0x7e0009000, 0x7e0002000] buffers = { 0x6001: fixture_memory(run, 0x6001, 2, 0x7e1000000, 0x5000), 0x6002: fixture_memory(run, 0x6002, 2, 0, 0x4000, contiguous=False, pages=pages), 0x6003: fixture_memory(run, 0x6003, 1, 0x1234567000, 0x3000, cached=False), 0x6004: fixture_memory(run, 0x6004, 2, 0x7e2000000, 0x1000, gpu=False), 0x6005: fixture_memory(run, 0x6005, 2, 0x7e3000000, 0x20000, page=0x10000, flags=MEMDESC_PRIVILEGED), } for handle, size in ((0x6001, 0x5000), (0x6002, 0x4000), (0x6003, 0x3000), (0x6004, 0x1000), (0x6005, 0x20000)): ptes(space, handle, buffers[handle], 0, size) ptes(space, 0x6001, buffers[0x6001], 0x2000, 0x2000, mapping=3, caching=1) ptes(space, 0x6001, buffers[0x6001], 0, 0x5000, page_size=0x1000) ptes(space, 0x6001, buffers[0x6001], 0, 0x5000, buffer_size=0x10) ptes(space, 0x6001, buffers[0x6001], 0x5000, 0x1000) ptes(space, 0x6001, buffers[0x6001], 0, 0x5000, lock_fail=(0, 0x2f)) ptes(space, 0, 0, 0, 0x1000) def release(device, count, tsg, share, retainer, lock_fail=None): retained = E.allocate(0xb8) E.wq(retained, device) E.wq(retained + 0x18, world.session) descriptors = [] for index in range(count): descriptor = fixture_memory(run, 0x6100 + index, 2, 0x7e4000000 + 0x10000 * index, 0x1000) E.wq(retained + 0x30 + 8 * index, descriptor) descriptors.append(0x6100 + index) E.wd(retained + 0x9c, count) for offset, handle in ((0xac, tsg), (0xb0, share), (0xb4, retainer)): E.wd(retained + offset, handle) if handle: API.canned_handles.add(handle) status = world.call("rm_gpu_ops_release_channel", retained, canned={}, lock_fail=lock_fail) run.op(f"release_channel 0 {count:x} {tsg:x} {share:x} {retainer:x}", 0) device, space = start("chan-release") release(device, 0, 0xcc000101, 0xcc000102, 0xcc000103) release(device, 3, 0xcc000111, 0xcc000112, 0xcc000113) release(device, 0, 0xcc000121, 0, 0xcc000123) release(device, 0, 0, 0, 0xcc000133) release(device, 1, 0, 0, 0) release(device, 2, 0xcc000151, 0xcc000152, 0xcc000153, lock_fail=(0, 0x2f)) for symbol, hook in hooks.items(): E.cpu.hook_del(hook) E.handlers.pop(symbol) return run def main(): install() lines = ["# Original RM side of the UVM interface (per-context path) under instruction " "emulation; see tools/check_uvm_gpu_ops2_binary.py", f"# original sha256 {DIGEST}"] world = World("uvm-slice2") world.snapshot() runs = [device_cases(world), address_space_cases(world), memory_cases(world), channel_cases(world)] for run in runs: lines += run.lines text = "\n".join(lines) + "\n" target = OUT / "original-gpu-ops2.txt" if "--check" in sys.argv: if not target.is_file(): raise SystemExit(f"oracle missing: {target}") if target.read_text() != text: raise SystemExit(f"oracle differs from the checked copy: {target}") else: OUT.mkdir(parents=True, exist_ok=True) target.write_text(text) print(json.dumps(dict( original_sha256=DIGEST, oracle=str(target.relative_to(ROOT)), oracle_sha256=hashlib.sha256(text.encode()).hexdigest(), cases=sum(run.cases for run in runs), rm_api_calls=sum(run.calls for run in runs)))) if __name__ == "__main__": main()