#!/usr/bin/env python3 """Run the original RM API escape path and write an oracle for the Rust `rmapi` module. Executed original code (580.178.04 nv-kernel.o_binary, whole object relocated): dispatcher _nv000800rm (RmIoctl) for every escape number, with the request sizes around each accepted size, on the control node and on a device node. Callees are replaced by recorders here, so only the size rule, the node rule, the class rewrite of NV_ESC_RM_ALLOC and the selected thunk are observed. sequences _nv000800rm with nothing replaced below it except the operating-system boundary: NV_ESC_RM_ALLOC -> _nv000646rm/_nv000647rm -> _nv054202rm -> _nv054201rm -> _nv056297rm (serverAllocResource) -> the RmClient factory and _nv056299rm; NV_ESC_RM_FREE -> _nv000641rm -> _nv054235rm -> _nv054234rm -> _nv056325rm (serverFreeResourceTree); NV_ESC_RM_CONTROL -> _nv000653rm -> _nv014199rm -> _nv054220rm -> _nv015942rm -> _nv056303rm and the exported RmClientResource handlers. The resource server is the one the original initializer _nv054244rm constructs (handle base 0xc1d00000). Fixture-supplied (everything else is original instructions): * the open-layer symbols the path reaches: allocator, fill, copy, compare, user copies, lock primitives, thread and process identity, time, os_check_access; * the RM API lock and the GPUs lock (_nv054246rm, _nv054250rm, _nv054248rm, _nv054249rm, _nv054240rm, _nv054115rm, _nv054117rm, _nv054116rm): acquire succeeds, owner queries answer "held"; * diagnostics (_nv047867rm.._nv047869rm, _nv04674xrm), recorded per operation; * the registry lookup _nv049786rm (no key present) and the administrator query _nv049723rm (a case input); * the purge of a client's OS events _nv054153rm (recorded); * the system object behind _nv029075rm: a zeroed block with the two client-validation properties at +0x70 and +0x71 set (their generated defaults in the matching public source, g_system_nvoc.c), the GPU manager at +0x1e0 and the boost manager at +0x248, both filled per case: the probed-GPU table, the attached-GPU table and GPU objects carrying only the fields the client control handlers read; * the GPU property services of _nv031410rm (_nv049700rm, _nv030934rm, _nv031447rm, _nv030277rm, _nv030607rm, _nv030593rm): case inputs. No class constructor is replaced. Classes that need a GPU therefore fail in their own constructor, and trees deeper than client -> child cannot be built here; the free-order rule for such trees is not covered by this oracle (see the implementation notes). """ 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_RDI, UC_X86_REG_RDX, UC_X86_REG_RSI from rmapi_binary_emulator import DIGEST, ROOT, STOP, Emulator LOCK = STOP + 0x800 OUT = ROOT / "target/rmapi" E = Emulator() if "DEBUG" in sys.argv: E.trace_calls() state = {"admin": 0, "diag": [], "purge": 0, "gpu_flags": {}, "called": None, "freed": [], "generator": None} def fill(a): E.write(a[0], bytes([a[1] & 0xff]) * (a[2] & 0xffffffff)) return a[0] def copy(a): E.write(a[0], E.read(a[1], a[2] & 0xffffffff)) return a[0] def user_copy(a): copy(a) return 0 def compare(a): left, right = E.read(a[0], a[2] & 0xffffffff), E.read(a[1], a[2] & 0xffffffff) return 0 if left == right else (1 if left > right else 0xffffffff) def allocate(a): E.wq(a[0], E.allocate(a[1] & 0xffffffff, 0xcc)) return 0 def pointer_out(value): def run(a): E.wq(a[0], value) return 0 return run def diagnostic(kind): def run(a): state["diag"].append(f"{kind}{a[0] & 0xffffffff:x}" if kind == "A" else f"{kind}{a[0] & 0xffffffff:x}.{a[1] & 0xffffffff:x}") return 0 return run def purge_events(): state["purge"] += 1 if state["called"] is not None: state["called"].append("_nv054153rm") return 0 FIXTURES = { "os_alloc_mem": allocate, "os_free_mem": lambda a: 0, "os_mem_set": fill, "os_mem_copy": copy, "os_mem_cmp": compare, "os_memcpy_from_user": user_copy, "os_memcpy_to_user": user_copy, "os_alloc_rwlock": lambda a: LOCK, "os_free_rwlock": lambda a: 0, "os_acquire_rwlock_read": lambda a: 0, "os_acquire_rwlock_write": lambda a: 0, "os_release_rwlock_read": lambda a: 0, "os_release_rwlock_write": lambda a: 0, "os_cond_acquire_rwlock_read": lambda a: 0, "os_cond_acquire_rwlock_write": lambda a: 0, "os_alloc_spinlock": pointer_out(LOCK), "os_free_spinlock": lambda a: 0, "os_acquire_spinlock": lambda a: 0, "os_release_spinlock": lambda a: 0, "os_alloc_mutex": pointer_out(LOCK), "os_free_mutex": lambda a: 0, "os_acquire_mutex": lambda a: 0, "os_release_mutex": lambda a: 0, "os_cond_acquire_mutex": lambda a: 0, "os_alloc_semaphore": lambda a: LOCK, "os_free_semaphore": lambda a: 0, "os_acquire_semaphore": lambda a: 0, "os_release_semaphore": lambda a: 0, "os_cond_acquire_semaphore": lambda a: 0, "os_semaphore_may_sleep": lambda a: 1, "os_is_isr": lambda a: 0, "nv_printf": lambda a: 0, "os_dbg_breakpoint": lambda a: 0, "os_get_current_thread": pointer_out(0x1234), "os_get_current_process": lambda a: 4242, "os_get_pid_info": lambda a: 0x5000, "os_put_pid_info": lambda a: 0, "os_find_ns_pid": lambda a: (E.wd(a[1], 4242), 0)[1], "os_get_current_process_name": lambda a: E.write(a[0], b"oracle\0") or 0, "os_get_euid": lambda a: (E.wd(a[0], 1000), 0)[1], "os_is_init_ns": lambda a: 1, "os_get_current_process_flags": lambda a: 0, "os_is_administrator": lambda a: state["admin"], "os_is_vgx_hyper": lambda a: 0, "os_is_grid_supported": lambda a: 0, # Linux answers NV_ERR_INSUFFICIENT_PERMISSIONS for an unprivileged caller. "os_check_access": lambda a: 0 if state["admin"] else 0x1b, "os_get_system_time": lambda a: (E.wd(a[0], 1), E.wd(a[1], 2), 0)[2], "os_get_cpu_count": lambda a: 4, "os_get_cpu_number": lambda a: 0, "os_get_monotonic_time_ns": lambda a: 0, "os_get_monotonic_time_ns_hr": lambda a: 0, "os_get_version_info": lambda a: 0x56, # RM API lock, GPUs lock. "_nv054246rm": lambda a: 0, "_nv054250rm": lambda a: 0, "_nv054248rm": lambda a: 1, "_nv054249rm": lambda a: 1, "_nv054240rm": lambda a: 1, "_nv054115rm": lambda a: 0, "_nv054117rm": lambda a: 0, "_nv054116rm": lambda a: 1, "_nv047869rm": lambda a: 0, "_nv047868rm": lambda a: 0, "_nv047867rm": lambda a: 0, "_nv046745rm": diagnostic("A"), "_nv046744rm": diagnostic("A"), "_nv046747rm": diagnostic("S"), "_nv046752rm": lambda a: 0, "_nv049786rm": lambda a: 0x57, "_nv049723rm": lambda a: state["admin"], "_nv054153rm": lambda a: purge_events(), # GPU manager mutexes (objects are fixture memory). "_nv052721rm": lambda a: 0, "_nv052725rm": lambda a: 0, "_nv052727rm": lambda a: 0, "_nv052734rm": lambda a: 0, # GPU property services read by _nv031410rm. "_nv049700rm": lambda a: state["gpu_flags"].get(a[0], {}).get("numa", 0), "_nv030934rm": lambda a: state["gpu_flags"].get(a[0], {}).get("in_use", 0), "_nv031447rm": lambda a: state["gpu_flags"].get(a[0], {}).get("sli_count", 1), "_nv030277rm": lambda a: state["gpu_flags"].get(a[0], {}).get("kind", 0), "_nv030607rm": lambda a: 1, "_nv030593rm": lambda a: 0, } HOOKS = {name: E.install(name, handler) for name, handler in FIXTURES.items()} def observe_free(emu, address, size, unused): """Entry of _nv019537rm (clientFreeResource_IMPL): one call per destroyed resource.""" state["freed"].append(E.d(emu.reg_read(UC_X86_REG_RDX) + 4)) def observe_generator(emu, address, size, unused): """Entry of _nv019538rm (clientGenResourceHandle): the client's handle ranges.""" client = emu.reg_read(UC_X86_REG_RDI) state["generator"] = (E.d(client + 0xa0), E.d(client + 0xa4), E.q(client + 0xa8), E.q(client + 0xb0)) E.cpu.hook_add(UC_HOOK_CODE, observe_free, begin=E.by_name["_nv019537rm"], end=E.by_name["_nv019537rm"]) E.cpu.hook_add(UC_HOOK_CODE, observe_generator, begin=E.by_name["_nv019538rm"], end=E.by_name["_nv019538rm"]) SERVER = E.by_name["_nv029076rm"] SYSTEM_SLOT = E.by_name["_nv029075rm"] def setup(probed=(), attached=()): """A freshly initialized RM API. `probed`: (gpu_id, extra, excluded); `attached`: dicts.""" E.reset() state.update(admin=0, diag=[], purge=0, gpu_flags={}) _require(E.call("_nv059519rm") & 0xffffffff == 0) # TLS and port layer system = E.allocate(0x2000) manager = E.allocate(0x40000) boost = E.allocate(0x1000) E.wq(SYSTEM_SLOT, system) E.wb(system + 0x70, 1) E.wb(system + 0x71, 1) E.wq(system + 0x1e0, manager) E.wq(system + 0x248, boost) for index in range(32): E.wd(manager + 0x48 + 0x48 * index, 0xffffffff) for index, (gpu_id, extra, excluded) in enumerate(probed): entry = manager + 0x48 + 0x48 * index E.wd(entry, gpu_id) E.wd(entry + 4, extra) E.wb(entry + 0x13, excluded) mask = 0 for index, gpu in enumerate(attached): obj = E.allocate(0x6000) instance = gpu["instance"] mask |= 1 << instance E.wq(manager + 0x3f230 + 16 * index, obj) E.wd(manager + 0x3f238 + 16 * index, instance) E.wb(obj + 0x90d, 1) E.wd(obj + 0xca4, gpu["gpu_id"]) E.wd(obj + 0xc9c, instance) E.wd(obj + 0xca8, gpu["board_id"]) E.wd(obj + 0xcac, gpu["device_instance"]) E.wd(obj + 0xcb0, gpu["subdevice_instance"]) E.wd(obj + 0xcb4, gpu["numa_id"]) E.wd(obj + 0x1e50, gpu["sli_status"]) for offset in gpu.get("bytes", ()): E.wb(obj + offset, 1) if offset == 0x978: E.wq(obj + 0x1f58, obj) state["gpu_flags"][obj] = gpu.get("services", {}) E.wd(manager + 0x3f430, len(attached)) E.wd(manager + 0x95c, mask) _require(E.call("_nv054244rm") & 0xffffffff == 0) # rmapiInitialize _require(not state["diag"], state["diag"]) files = [E.allocate(0x100) for _ in range(4)] control = E.allocate(0x400) E.wd(control + 0x10, 4) # NV_FLAG_CONTROL device = E.allocate(0x400) return dict(files=files, nodes={"ctl": control, "dev": device}) def escape(context, node, file, command, data): block = E.allocate(len(data) + 16) E.write(block, data) state["diag"].clear() status = E.call("_nv000800rm", context["nodes"][node], context["files"][file], command, block, len(data)) & 0xffffffff return status, E.read(block, len(data)) def user(data): if data is None: return 0 address = E.allocate(len(data) + 16) E.write(address, data) return address class Sequence: """Operations of one case; every line carries the request and the original's reply.""" def __init__(self, name, **system): self.lines = [f"case {name}"] self.context = setup(**system) self.system = system def describe_system(self): for gpu_id, extra, excluded in self.system.get("probed", ()): self.lines.append(f"probed {gpu_id:x} {extra:x} {excluded}") for gpu in self.system.get("attached", ()): services = gpu.get("services", {}) offsets = ",".join(f"{offset:x}" for offset in gpu.get("bytes", ())) or "-" self.lines.append( f"attached {gpu['gpu_id']:x} {gpu['instance']:x} {gpu['device_instance']:x}" f" {gpu['subdevice_instance']:x} {gpu['board_id']:x} {gpu['numa_id']:x}" f" {gpu['sli_status']:x} {services.get('numa', 0)} {services.get('in_use', 0)}" f" {services.get('sli_count', 1)} {services.get('kind', 0)} {offsets}") def admin(self, value): state["admin"] = value self.lines.append(f"admin {value}") def emit(self, kind, node, file, request, params, status, reply, params_out): diagnostics = ",".join(state["diag"]) or "-" self.lines.append( f"{kind} {node} {file} {request.hex()} {params.hex() if params is not None else '-'}" f" -> {status:x} {reply.hex()}" f" {params_out.hex() if params_out is not None else '-'} {diagnostics}") def alloc(self, root, parent, new, klass, params=None, size=0, flags=0, file=0, node="ctl", legacy=False): address = user(params) if legacy: request = struct.pack(" {status:x} {rewritten:x} {','.join(called) or '-'}") E.heap = block for hook in hooks: E.cpu.hook_del(hook) for name in targets: E.handlers.pop(name, None) state["called"] = None return lines PRIVILEGE_PROBES = {} for record in json.loads((ROOT / "analysis/closed-driver-580/rmapi-userspace.json") .read_text())["classes"]: if record["flags"] & 0x680 and len(PRIVILEGE_PROBES) < 400: PRIVILEGE_PROBES[record["ext"]] = record["param_size"] V100 = dict(board_id=0x1a00, device_instance=0, subdevice_instance=0, numa_id=0xffffffff, sli_status=0) def client_sequences(): cases = [] case = Sequence("client-handles") client = 0xc1d00000 case.alloc(0, 0, 0, 0) case.alloc(0, 0, 0, 1) case.alloc(0, 0, 0, 0x41, params=bytes(4), size=4) case.alloc(0, 0, 0, 0x41, params=bytes(8), size=8) case.alloc(0, 0, 0x999, 0x41) case.alloc(0, 0x55, 0x777, 0x41) case.alloc(0x1234, 0, 0, 0x41) case.alloc(0x1234, 0, 0x999, 0x41) case.alloc(0xc1d00005, 0, 0, 0x41) case.alloc(0xc1d00407, 0, 0, 0x41) for _ in range(4): case.alloc(0, 0, 0, 0x41) case.alloc(0, 0, 0, 0x41, flags=1) case.alloc(0, 0, 0, 0x41, flags=2) case.alloc(0, 0, 0, 0x41, legacy=True) case.alloc(0, 0, 0, 0x41, params=bytes(4), legacy=True) case.alloc(0, 0, 0, 0, node="dev") case.free(client, 0, client) case.free(client, 0, client) case.alloc(0, 0, 0, 0x41) case.alloc(client, 0, 0, 0x41) case.free(0x1234, 0xdeadbeef, 0x1234) case.free(0xc1d00001, 0, 0xc1d00001, file=1) case.free(0xc1d00001, 0, 0x999) case.free(0xbad, 0, 0x999) case.free(0, 0, 0) cases.append(case) # A requested handle equal to the next generated one: the generator moves on by the # bucket count (0x400) inside the same bucket. case = Sequence("client-handle-collision") case.alloc(0xc1d00000, 0, 0, 0x41) case.alloc(0, 0, 0, 0x41) case.alloc(0xc1d00001, 0, 0, 0x41) case.alloc(0xc1d00401, 0, 0, 0x41) case.alloc(0, 0, 0, 0x41) case.alloc(0, 0, 0, 0x41) case.free(0xc1d00400, 0, 0xc1d00400) case.alloc(0xc1d00400, 0, 0, 0x41) case.alloc(0xc1e00000, 0, 0, 0x41) case.alloc(0xffffffff, 0, 0, 0x41) case.alloc(1, 0, 0, 0x41) case.alloc(0, 0, 0, 0x41, file=1) case.free(0xffffffff, 0, 0xffffffff) cases.append(case) case = Sequence("resource-handles") case.alloc(0, 0, 0, 0) case.alloc(client, client, 0, 0x900e) case.alloc(client, 0, 0, 0x20, params=bytes(4)) case.alloc(client, client, 0, 0x20) case.alloc(client, client, 0, 0x20) case.alloc(client, client, 0x5000, 0x20) case.alloc(client, client, 0x5000, 0xcb33, params=bytes(4)) case.alloc(client, client, 0x5000, 0xcb33) case.alloc(client, client, client, 0xcb33) case.alloc(client, client, client, 0x12345) case.alloc(client, 0xdead, client, 0xcb33) case.alloc(client, client, 0xcaf00004, 0xcb33) for _ in range(4): case.alloc(client, client, 0, 0xcb33) case.alloc(client, client, 0xc9f00000, 0xcb33) case.alloc(client, client, 0xc9f7ffff, 0xcb33) case.alloc(client, client, 0xc9f80000, 0xcb33) case.alloc(client, client, 0xc9efffff, 0xcb33) case.alloc(client, client, 0xcaf7ffff, 0xcb33) case.alloc(client, client, 0xffffffff, 0xcb33) case.alloc(client, client, 1, 0xcb33) case.alloc(client, 0x5000, 0, 0xcb33) case.alloc(client, 0xdead, 0, 0xcb33) case.alloc(client, 0xdead, 0, 0x20) case.alloc(client, 0x5000, 0, 0x20) case.alloc(client, client, 0, 0x2080) case.alloc(client, client, 0x5000, 0x2080) case.alloc(client, client, 0, 0x12345) case.alloc(0xbad, 0, 0, 0x12345) case.alloc(client, client, 0, 0xcb33, params=bytes(4), size=4) case.alloc(client, client, 0, 0xcb33, params=bytes(8), size=8) case.alloc(client, client, 0, 0xcb33, params=bytes(4), size=0) case.alloc(client, client, 0, 0x90cd) case.alloc(0xbad, 0, 0, 0x90cd) case.alloc(client, client, 0, 0xcb33, flags=1) case.alloc(client, client, 0, 0xcb33, flags=2) case.alloc(client, client, 0, 0xcb33, legacy=True) case.alloc(client, client, 0, 0xcb33, params=bytes(4), legacy=True) case.alloc(0xbad, 0, 0, 0xcb33) case.alloc(client, client, 0, 0xcb33, file=1) case.alloc(client, client, 0, 0xcb33, node="dev") case.alloc(client, client, 0, 0x80, params=bytes(56)) case.alloc(client, client, 0, 0x80) # Privilege flags of the class record (0x200 privileged, 0x400 kernel) and the # internal-only flag (0x80), as an unprivileged and as an administrator caller. for admin in (0, 1): case.admin(admin) for klass in PRIVILEGE_PROBES: size = PRIVILEGE_PROBES[klass] case.alloc(client, client, 0, klass, params=bytes(size) if size else None) case.alloc(client, 0xdead, 0, klass, params=bytes(size) if size else None) case.alloc(client, client, client, klass, params=bytes(size) if size else None) case.admin(0) case.free(client, 0, 0x999) case.free(client, 0, 0x5000, file=1) case.free(client, 0xdead, 0x5000) case.free(client, 0, 0x5000) case.alloc(client, client, 0x5000, 0xcb33) case.free(client, 0, 0xcaf00001) case.alloc(client, client, 0, 0x20) case.alloc(client, client, 0, 0xcb33) case.free(client, 0, 0, node="dev") case.free(client, client, client) case.free(client, client, client) case.alloc(client, client, 0, 0xcb33) cases.append(case) # Destruction order of a client's children: one _nv019537rm call per resource. case = Sequence("free-order") case.alloc(0, 0, 0, 0) for handle in (0x30, 0x10, 0x20): case.alloc(client, client, handle, 0xcb33) case.alloc(client, client, 0x8, 0x900e) case.alloc(client, client, 0xffff0000, 0x20) case.alloc(client, client, 0, 0xcb33) case.free(client, 0, 0x10) case.alloc(client, client, 0x10, 0xcb33) case.free(client, 0, client) start, size, low, high = state["generator"] case.lines.append(f"generator {start:x} {size:x} {low:x} {high:x}") cases.append(case) # Attached GPUs covering every input of the id-info flag word (_nv031410rm). variants = [ {}, dict(bytes=[0x94c, 0x90f]), dict(services={"in_use": 1, "sli_count": 2, "kind": 1}, bytes=[0xc98]), dict(services={"kind": 2, "numa": 1}, numa_id=3), dict(services={"kind": 3}, bytes=[0x92b]), dict(bytes=[0x921]), dict(bytes=[0xc98, 0x921], sli_status=0x20000000), dict(bytes=[0x978]), dict(bytes=[0x92b, 0x978], services={"kind": 1}), dict(bytes=[0x92b, 0x921, 0x978]), dict(device_instance=32), ] gpus = [] for index, variant in enumerate(variants): gpu = dict(V100, gpu_id=0x1a00 + 0x100 * index, instance=index, device_instance=index, board_id=0x1a00 + 0x100 * index) gpu.update(variant) gpus.append(gpu) probed = [(gpu["gpu_id"], index, 0) for index, gpu in enumerate(gpus)] probed.insert(3, (0x3d00, 0x77, 1)) probed.append((0x3e00, 4, 0)) for label, system in (("controls-empty", {}), ("controls-one-probed", dict(probed=[(0xb300, 0, 0)])), ("controls-attached", dict(probed=probed, attached=gpus))): case = Sequence(label, **system) case.describe_system() case.alloc(0, 0, 0, 0) ids = [entry[0] for entry in system.get("probed", ())] or [0x1a00] # NULL commands and argument checks of the control entry. case.control(client, client, 0) case.control(0xbad, 0xbad, 0x20800000, params=bytes(4)) case.control(0xbad, client, 0x214, params=bytes(384)) case.control(client, 0xbad, 0x214, params=bytes(384)) case.control(client, client, 0x214, params=bytes(380)) case.control(client, client, 0x214, params=bytes(384), null_pointer=True) case.control(client, client, 0x214, size=0, null_pointer=True) case.control(client, client, 0x214, params=bytes(384), file=1) case.control(client, client, 0x214, params=bytes(384), node="dev") case.control(client, client, 0x214, params=bytes(384), flags=1) case.control(client, client, 0x214, params=bytes(384), flags=4) case.control(client, client, 0x2ff, params=bytes(4)) case.control(client, client, 0x20800102, params=bytes(564)) case.control(client, client, 0x801402, params=bytes(3)) case.control(client, client, 0x20800102, params=bytes(560)) case.control(0xbad, client, 0x214, params=bytes(380)) case.control(0xbad, client, 0x2ff, params=bytes(4)) case.control(client, 0xbad, 0x214, params=bytes(380)) case.control(client, 0xbad, 0x2ff, params=bytes(4)) case.control(client, client, 0x214, params=bytes(380), flags=4) case.control(client, client, 0x214, params=bytes(384), flags=2) case.control(client, client, 0x214, params=bytes(384), flags=8) case.control(client, client, 0x4000, params=bytes(4)) case.control(0xbad, client, 0x214, params=bytes(384), flags=1) case.control(0xbad, client, 0x214, params=bytes(384), flags=4) case.control(client, 0xbad, 0x214, params=bytes(384), flags=1) case.control(client, 0xbad, 0x214, params=bytes(384), flags=4) case.control(client, client, 0x2ff, params=bytes(4), flags=1) case.control(client, client, 0x2ff, params=bytes(4), flags=4) case.control(client, client, 0x214, params=bytes(384), flags=5) case.control(client, client, 0x214, params=bytes(384), flags=0xc) case.control(client, client, 0x214, params=bytes(384), flags=0x10) case.control(client, client, 0x214, params=bytes(384), flags=0xfffffff8) case.control(0xbad, 0xbad, 0x20804000, params=bytes(4), flags=7) case.control(client, client, 0x101, params=bytes(36)) case.control(client, client, 0x13e, params=bytes(4)) case.control(client, client, 0x13e, params=bytes([0xa5]) * 1032) case.control(0xbad, 0xbad, 0x101, params=bytes(40)) case.control(client, 0xbad, 0x101, params=bytes(40)) case.control(client, client, 0x101, params=bytes(40), file=1) case.control(client, client, 0x101, params=bytes(40), flags=1) case.control(client, client, 0x101, params=bytes(40), flags=4) case.control(client, client, 0x101, size=40, null_pointer=True) case.control(client, client, 0x101, size=0, null_pointer=True) case.control(client, client, 0x2ff, size=0, null_pointer=True) # The client-object commands the workload issues before its first device. pattern = bytes([0xa5]) * 4096 case.control(client, client, 0xd04, params=struct.pack(" (child array offset in the GPU object, instances, body, further arguments). # The bodies are the class-vtable or HAL bodies the stage wrappers of the first open # dispatch to (reports/gpu-stage-engine-worklist.json, reports/gv100-engine-hal-bindings.json). STAGE_BODIES = { "objce-preinit": (0x2130, 20, "_nv019109rm", ()), # OBJCE StatePreInitLocked "kce-init": (0x21d0, 20, "_nv039835rm", ()), # KernelCE StateInitLocked "objce-init": (0x2130, 20, "_nv019107rm", ()), # OBJCE StateInitUnlocked "objce-preload": (0x2130, 20, "_nv019113rm", (0,)), # OBJCE StatePreLoad "kce-load": (0x21d0, 20, "_nv039837rm", (0,)), # KernelCE StateLoad (HAL +0x120) "kms-preinit": (0x1ec8, 1, "_nv041691rm", ()), # KernelMemorySystem PreInitLocked } CE_STAGES = ("objce-preinit", "kce-init", "objce-init", "objce-preload", "kce-load") # Operating-system boundary the stage bodies reach beyond GPU_FIXTURES: delays, the tick # resolution of the timeout helper, and the page size (data symbol os_page_size). STAGE_FIXTURES = {"os_delay_us": lambda a: 0, "os_get_monotonic_tick_resolution_ns": lambda a: 1000000} BAR0 = 0x7000000000 TRANSCRIPT = ROOT / "target/trace/b3-bar0.txt" # Registers the attach reads, by reader (see the implementation notes, slice 2). ATTACH_REGISTERS = (0x0, 0x4, 0xa00, 0x88000, 0x88008, 0x8802c, 0x88084, 0x1373a0, 0x21c04, 0x21434, 0x10ac08, 0x15f8, 0x140) # Read at attach but absent from the transcript (lost events at its head): case inputs. UNTRACED_REGISTERS = {0x1070: 0, 0x8: 0, 0x1078: 0} V100_PCI = dict(domain=0, bus=0xb3, slot=0, function=0, vendor=0x10de, device=0x1db5, subsystem_vendor=0x10de, subsystem=0x1249, irq=0xd3, bars=((0xa9000000, 0x1000000), (0x387000000000, 0x400000000), (0x387400000000, 0x2000000))) gpu_state = {"registers": {}, "accessible": 1, "read": [], "written": [], "files": {}, "cache": 0, "source": None} # Registers the base PreInit pass _nv031220rm reads when every engine's PreInit callback is # replaced (GpuSequence.sweep): branding and chip information, the device-information table # 0x22700.., the engine presence checks of the missing-engine sweep (display fuse 0x21c04 after # the Jtag register 0x1373a0, the KernelNvlink discovery words 0xa00000.., the copy-engine # words 0x2390..) and PMC_ENABLE. SWEEP_REGISTERS = (0x200, 0x1074, 0x1100, 0x2004, *range(0x2390, 0x23c8, 4), 0x2634, 0x2133c, 0x214f8, 0x21510, 0x21580, 0x21c04, 0x21ed4, 0x22400, *range(0x22700, 0x22800, 4), 0x1373a0, *range(0xa00000, 0xa000dc, 4)) _first_reads = {} def first_reads(): """First read of every register in the physical transcript of 0000:b3:00.0.""" if not _first_reads: for line in TRANSCRIPT.read_text().splitlines(): parts = line.split() if parts[0] == "R": _first_reads.setdefault(int(parts[1], 16), int(parts[2], 16)) return _first_reads def transcript_registers(overrides=None): values = first_reads() table = {offset: values[offset] for offset in ATTACH_REGISTERS} table.update(UNTRACED_REGISTERS) table.update(overrides or {}) return table def register_read(a): offset = a[2] & 0xffffffff source = gpu_state.get("source") if offset not in gpu_state["registers"] and source is not None: # A stage body (GpuSequence.stage): the register enters the case with the value # the case names for it, else with its first read in the physical transcript. _require(offset in source, f"register {offset:#x} has no value for this stage") gpu_state["registers"][offset] = source[offset] _require(offset in gpu_state["registers"], f"register {offset:#x} is not in the case") gpu_state["read"].append(offset) return gpu_state["registers"][offset] def file_private(a): """nv_get_file_private(fd, ctl, &os_private): the file of that kind, or NULL.""" entry = gpu_state["files"].get(a[0] & 0xffffffff) if entry is None or entry[1] != (a[1] & 0xff): return 0 E.wq(a[2], entry[0]) return entry[0] def register_write(a): gpu_state["written"].append((a[2] & 0xffffffff, a[3] & 0xffffffff)) return 0 GPU_FIXTURES = { "_nv049612rm": register_read, "_nv049615rm": register_write, "os_map_kernel_space": lambda a: BAR0, "os_unmap_kernel_space": lambda a: 0, "nv_is_gpu_accessible": lambda a: gpu_state["accessible"], "nv_get_file_private": file_private, "nv_put_file_private": lambda a: 0, "nv_requires_dma_remap": lambda a: 0, "nv_set_dma_address_size": lambda a: 0, "nv_get_dev_minor": lambda a: 0, "os_get_grid_csp_support": lambda a: 0, "nv_is_chassis_notebook": lambda a: 0, "nv_acpi_is_battery_present": lambda a: 0, "os_is_efi_enabled": lambda a: 0, "nv_platform_supports_s0ix": lambda a: 0, "os_is_nvswitch_present": lambda a: 0, "os_get_cpu_frequency": lambda a: 0, "os_registry_init": lambda a: 0, "os_dbg_init": lambda a: 0, "os_add_record_for_crashLog": lambda a: 0, "os_delete_record_for_crashLog": lambda a: 0, } def cache_mode_address(): """Address of the mode word: `cmp dword [rip+disp], 2` at the head of _nv054210rm.""" start = E.by_name["_nv054210rm"] code = E.read(start, 0x40) position = code.index(b"\x83\x3d") _require(code[position + 6] == 2) return start + position + 7 + struct.unpack_from("map (RmSetupRegisters) slot = E.allocate(16) _require(E.call("_nv031506rm") & 0xffffffff == 0) _require(E.call("_nv031359rm", slot) & 0xffffffff == 0) instance = E.d(slot) _require(E.call("_nv054107rm", instance) & 0xffffffff == 0) _require(E.call("_nv031377rm", slot + 8, 1 << instance, 0) & 0xffffffff == 0) # GPUATTACHARG as osInitNvMapping fills it (public osinit.c). argument = E.allocate(0x12d0) E.wq(argument, BAR0) for index, source in ((3, 0x90), (4, 0xb8), (5, 0xe0), (8, 0x98), (9, 0xc0), (10, 0xe8)): E.wq(argument + 8 * index, E.q(nv + source)) E.wq(argument + 0x38, E.q(manager + 0x50 + 0x48 * instance)) # nv_encode_pci_info E.wd(argument + 0xf74, 0xffffffff) # no IO VA space E.wd(argument + 0xf7c, 0xffffffff) # no NUMA node E.wq(argument + 0x58, nv) status = E.call("_nv031364rm", instance, argument) & 0xffffffff _require(status == 0, hex(status)) E.call("_nv031505rm") _require(not state["diag"], state["diag"]) gpu = E.q(manager + 0x3f230 + 16 * instance) files = [E.allocate(0x100) for _ in range(6)] control = E.allocate(0x400) E.wd(control + 0x10, 4) # Descriptors 10..12 are control files 0..2, 20..22 device files 3..5. gpu_state["files"] = {10 + index: (files[index], 1) for index in range(3)} gpu_state["files"].update({20 + index: (files[3 + index], 0) for index in range(3)}) return dict(files=files, nodes={"ctl": control, "dev": nv}), gpu, nv, system class GpuSequence(Sequence): def __init__(self, name, registers=None): self.lines = [f"case {name}"] self.context, self.gpu, self.nv, self.sys = gpu_world(registers) self.system = {} pci = V100_PCI self.lines.append( f"gpu {pci['domain']:x} {pci['bus']:x} {pci['slot']:x} {pci['function']:x}" f" {pci['vendor']:x} {pci['device']:x} {pci['subsystem_vendor']:x}" f" {pci['subsystem']:x} {pci['irq']:x} " + " ".join(f"{address:x}:{size:x}" for address, size in pci["bars"])) self.lines.append("registers " + " ".join( f"{offset:x}={value:x}" for offset, value in sorted(gpu_state["registers"].items()))) self.lines.append("attach-reads " + " ".join( f"{offset:x}" for offset in dict.fromkeys(gpu_state["read"]))) self.lines.append("attach-writes " + (" ".join( f"{offset:x}={value:x}" for offset, value in gpu_state["written"]) or "-")) self.initialized(0) def initialized(self, value): """PDB_PROP_GPU_STATE_INITIALIZED (GPU+0x90d): what gpumgrGetGpu requires.""" E.wb(self.gpu + 0x90d, value) self.lines.append(f"initialized {value}") def accessible(self, value): gpu_state["accessible"] = value self.lines.append(f"accessible {value}") def cache(self, mode): """Mode word of the control cache: 1 enabled (default), 2 verify only, 0 disabled.""" E.wd(gpu_state["cache_word"], mode) self.lines.append(f"cache {mode}") def flush(self): """rmapiControlCacheFreeAllCacheForGpu for GPU instance 0 and the system-wide key.""" for instance in (0, 0x20): E.call("_nv054205rm", instance) self.lines.append("flush") def child(self, name): if name[:3] in ("oce", "kce"): # OBJCE (GPU+0x2130) and KernelCE (GPU+0x21d0) instance name[3:]. return E.q(self.gpu + (0x2130 if name[0] == "o" else 0x21d0) + 8 * int(name[3:])) return {"cl": E.q(self.sys + 0x208), "bif": E.q(self.gpu + 0x1e88), "krc": E.q(self.gpu + 0x20f8)}[name] def stage(self, name, registers=None): """Original stage bodies of one engine class on this GPU, called the way the stage wrappers call them (GPU not yet initialized, expanded visibility, GPUs lock held), one call per constructed instance in instance order. Registers a body reads that the case does not hold yet come from `registers`, else from the first read in the transcript; writes are recorded, not applied. Every status must be 0.""" offset, count, body, extra = STAGE_BODIES[name] gpu_state["source"] = dict(first_reads()) gpu_state["source"].update(registers or {}) hooks = {symbol: E.install(symbol, handler) for symbol, handler in STAGE_FIXTURES.items()} E.wq(E.externals["os_page_size"], 0x1000) gpu_state["read"].clear() gpu_state["written"].clear() state["diag"].clear() initialized = E.b(self.gpu + 0x90d) E.wb(self.gpu + 0x90d, 0) for index in range(count): instance = E.q(self.gpu + offset + 8 * index) if not instance: continue _require(E.call("_nv031506rm") & 0xffffffff == 0) _require(E.call("_nv054115rm", 0, 1) & 0xffffffff == 0) status = E.call(body, self.gpu, instance, *extra) & 0xffffffff _require(E.call("_nv054117rm", 0, 0) & 0xffffffff == 0) E.call("_nv031505rm") _require(status == 0, (name, index, hex(status), state["diag"])) E.wb(self.gpu + 0x90d, initialized) for symbol, hook in hooks.items(): E.cpu.hook_del(hook) E.handlers.pop(symbol) gpu_state["source"] = None reads = " ".join(f"{offset:x}={gpu_state['registers'][offset]:x}" for offset in dict.fromkeys(gpu_state["read"])) or "-" writes = " ".join(f"{offset:x}={value:x}" for offset, value in gpu_state["written"]) or "-" self.lines.append(f"stage {name} {body} {','.join(state['diag']) or '-'}") self.lines.append(f"stage-reads {name} {reads}") self.lines.append(f"stage-writes {name} {writes}") def peek(self, target, offset, size): base = {"gpu": self.gpu, "sys": self.sys}.get(target) or self.child(target) value = int.from_bytes(E.read(base + offset, size), "little") self.lines.append(f"peek {target} {offset:x} {size} -> {value:x}") return value def poke(self, target, offset, size, value): base = {"gpu": self.gpu, "sys": self.sys}.get(target) or self.child(target) E.write(base + offset, value.to_bytes(size, "little")) self.lines.append(f"poke {target} {offset:x} {size} {value:x}") def class_table(self): """The class descriptor list the original's engine-table constructor built for this GPU (GPU+0xd90, count GPU+0xd98: generic classes, engine-less classes of the chip and the chip's class-to-engine list) and the class database gpuBuildClassDB made of it (GPU+0xdc8, count GPU+0xdd8).""" for label, pointer, count in (("descriptors", 0xd90, 0xd98), ("classdb", 0xdc8, 0xdd8)): base, number = E.q(self.gpu + pointer), E.d(self.gpu + count) records = [struct.unpack(" {status:x} {reply.hex()}") return status def device_params(device=0, share=0, target_client=0, target_device=0, flags=0, size=0, start=0, limit=0, mode=0): """NV0080_ALLOC_PARAMETERS (56 bytes).""" return struct.pack(" vmmCreateVaspace _nv060601rm -> gvaspaceConstruct_ _nv034563rm), the VA capabilities control 0x801806 (_nv022155rm) and NV50_THIRD_PARTY_P2P (0x503c, _nv059452rm) with its VA-space registration (0x503c0102 _nv059454rm, 0x503c0103 _nv059457rm). The constructor reads the memory-system static configuration, so KernelMemorySystem PreInitLocked runs first.""" case = GpuSequence("gpu-vaspace") case.alloc(0, 0, 0, 0) case.initialized(1) _, device = case.alloc(client, client, 0, 0x80, params=good) _, subdevice = case.alloc(client, device, 0, 0x2080, params=bytes(4)) case.sweep() case.stage("kms-preinit") space = vaspace_params def probe(parent, params, keep=False, **keywords): gpu_state["read"].clear() gpu_state["written"].clear() result, handle = case.alloc(client, parent, 0, 0x90f1, params=params, **keywords) # The constructor is CPU-side only: no register access. _require(not gpu_state["read"] and not gpu_state["written"]) if result == 0 and not keep: case.free(client, 0, handle) return handle # The two allocations of the workload: the channel address space (externally owned, # page faulting) and the RM-managed one. probe(device, space(flags=0x48, base=0x1000)) probe(device, space(base=0x5000000)) probe(subdevice, space(flags=0x48, base=0x1000)) probe(client, space(flags=0x48, base=0x1000)) probe(device, None) probe(device, pattern[:56]) for admin in (0, 1): case.admin(admin) for index in range(7): probe(device, space(index=index)) probe(device, space(index=0xffffffff)) for bit in range(32): probe(device, space(flags=1 << bit)) for flags in (0x48, 0x28, 0x68, 0x148, 0x88, 0xc8, 0x4c, 0x49, 0x60, 0x3fff, 0xffffffff): probe(device, space(flags=flags)) probe(device, space(flags=flags, base=0x1000)) case.admin(0) for base in (0x1000, 0x2000, 0xfff, 0x1234, 0x10000, 0xfffff, 0x100000, 0x100001, 0x200000, 0x5000000, 1 << 32, 1 << 48, (1 << 49) - 0x1000, (1 << 49) - 1, 1 << 49, 1 << 63, 0xffffffffffffffff): probe(device, space(base=base)) probe(device, space(flags=0x48, base=base)) probe(device, space(flags=0x100, base=base)) probe(device, space(flags=0x100)) probe(device, space(flags=0x148)) for size in (1, 0x1000, 0xfffff, 0x100000, 0x100001, 0x200000, 1 << 32, 1 << 48, (1 << 49) - 1, 1 << 49, (1 << 49) + 1, 1 << 50, 0xffffffffffffffff): probe(device, space(size=size)) probe(device, space(flags=0x48, size=size, base=0x1000)) probe(device, space(flags=0x100, size=size)) probe(device, space(size=size, base=0x200000)) probe(device, space(size=0xffffffffffffffff, base=2)) probe(device, space(size=(1 << 49) - 0x1000, base=0x1000)) probe(device, space(size=(1 << 49) - 0xfff, base=0x1000)) for big in (0x1000, 0x10000, 0x20000, 0x40000, 0x200000, 0x10001, 0xffffffff): probe(device, space(big=big)) probe(device, space(flags=0x48, big=big, base=0x1000)) for flags in (0, 0x80): for start, limit in ((0x1000, 0xffff), (0, 0xffffffff), (0x100000, 0xfffff), (1 << 32, (1 << 33) - 1), (0x200000, 1 << 49), (5, 4)): probe(device, space(flags=flags, start=start, limit=limit)) probe(device, space(tail=0xa5a5a5a5a5a5a5a5)) # Devices of the other VA modes. for mode in (0, 1): result, other = case.alloc(client, client, 0, 0x80, params=device_params(share=client, mode=mode)) if result == 0: caps = bytearray(pattern[:192]) struct.pack_into(" _nv013913rm -> _nv039407rm # (kbusGetDeviceCaps). Inputs: the chipset object (system+0x208) and GPU+0x93f. run(device, 0x801402, 3) for pokes in ((("cl", 0x6a, 1, 0),), (("cl", 0xaa, 2, 0x10de),), (("cl", 0xaa, 2, 0x10de), ("cl", 0xa8, 2, 0x800)), (("cl", 0xaa, 2, 0x10de), ("cl", 0xa8, 2, 0x807)), (("cl", 0xaa, 2, 0x10de), ("cl", 0xa8, 2, 0x808)), (("cl", 0xaa, 2, 0x10de), ("cl", 0xa8, 2, 0x7ff)), (("cl", 0xaa, 2, 0x10de), ("gpu", 0x93f, 1, 1)), (("cl", 0xaa, 2, 0x8086), ("cl", 0xa8, 2, 0x800), ("gpu", 0x93f, 1, 1)), (("cl", 0x6a, 1, 0), ("cl", 0xaa, 2, 0x10de), ("cl", 0xa8, 2, 0x803))): saved = [case.peek(*poke[:3]) for poke in pokes] for poke in pokes: case.poke(*poke) run(device, 0x801402, 3) for poke, value in zip(pokes, saved): case.poke(*poke[:3], value) run(subdevice, 0x801402, 3) run(device, 0x801402, 4) # 0x2080182a NV2080_CTRL_CMD_BUS_GET_PCIE_SUPPORTED_GPU_ATOMICS: _nv057446rm -> # _nv057447rm. Thirteen (byte, word) pairs of the OBJBIF object (GPU+0x1e88) at +0xbf0. run(subdevice, 0x2080182a, 112) run(subdevice, 0x2080182a, 112, block=bytes(112)) for first in (1, 0x1a00, 0xb300, 0xffffffff): run(subdevice, 0x2080182a, 112, block=struct.pack(" _nv042163rm (krcWatchdogChangeState). KernelRc (GPU+0x20f8) # +0x220 enable, +0x224 disable, +0x228 soft-disable request counts, +0x148 flags. release, soft = 0x2080220c, 0x20802210 def counters(): for offset in (0x220, 0x224, 0x228, 0x148): case.peek("krc", offset, 4) counters() for obj, command, who in ((subdevice, release, client), (subdevice, soft, client), (subdevice, soft, client), (subdevice1, soft, client), (subdevice2, soft, other), (subdevice, release, client), (subdevice, release, client), (subdevice1, release, client), (subdevice2, release, other), (subdevice2, soft, other), (subdevice, soft, client)): run(obj, command, 0, who=who) counters() run(device, soft, 0) run(subdevice, soft, 1) run(subdevice, release, 0, flags=4) # Counts and flags another kind of request would have left (enable and disable are not # issued by the workload; their handlers are not executed here). for offset, value in ((0x220, 1), (0x224, 1), (0x148, 2), (0x148, 0xffffffff)): saved = case.peek("krc", offset, 4) case.poke("krc", offset, 4, value) run(subdevice, release, 0) counters() run(subdevice, soft, 0) counters() run(subdevice1, soft, 0) counters() run(subdevice1, release, 0) run(subdevice, release, 0) counters() case.poke("krc", offset, 4, saved) # A subdevice that goes away releases its request (operation RM_CLIENT_DESTRUCTION). run(subdevice1, soft, 0) run(subdevice2, soft, 0, who=other) counters() case.free(client, 0, subdevice1) counters() case.free(other, 0, other) counters() run(subdevice, soft, 0) counters() # 0x800292 NV0080_CTRL_CMD_GPU_GET_CLASSLIST_V2: _nv022202rm -> _nv030463rm. run(device, 0x800292, 804) run(device, 0x800292, 804, block=bytes(804)) run(subdevice, 0x800292, 804) run(device, 0x800292, 800) case.sweep() case.class_table() run(device, 0x800292, 804) run(device, 0x801402, 3) run(subdevice, 0x2080182a, 112, block=bytes(112)) run(subdevice, soft, 0) counters() _require(case.alloc(0, 0, 0, 0)[1] == client + 3) case.free(client, 0, client) counters() cases.append(case) # Not covered: a GPU whose display fuse (0x21c04 bit 0) is clear. Its attach reads # display registers (0x610018 first) that the transcript of this board does not hold. return cases def _verify_or_write_oracle(path, text, check, label): if check: if not path.is_file(): raise SystemExit(f"{label} missing: {path}") if path.read_text() != text: raise SystemExit(f"{label} differs from the checked copy: {path}") else: path.parent.mkdir(parents=True, exist_ok=True) path.write_text(text) def main(): check = "--check" in sys.argv lines = ["# Original RM API escape path under instruction emulation; see " "tools/check_rmapi_binary.py", f"# original sha256 {DIGEST}"] dispatcher = dispatcher_table() lines += dispatcher cases = client_sequences() for case in cases: lines += case.lines text = "\n".join(lines) + "\n" target = OUT / "original-rmapi.txt" _verify_or_write_oracle(target, text, check, "oracle") operations = sum(1 for line in text.splitlines() if line[:2] in ("A ", "L ", "F ", "C ")) # The GPU-backed cases run last: they replace the fabricated system by the original's. gpu_cases = gpu_sequences() gpu_text = "\n".join(lines[:2] + [line for case in gpu_cases for line in case.lines]) + "\n" gpu_target = OUT / "original-rmapi-gpu.txt" _verify_or_write_oracle(gpu_target, gpu_text, check, "GPU oracle") gpu_operations = sum(1 for line in gpu_text.splitlines() if line[:2] in ("A ", "L ", "F ", "C ", "R ")) report = dict(original_sha256=DIGEST, oracle=str(target.relative_to(ROOT)), dispatcher_cases=len(dispatcher) - 1, sequence_cases=len(cases), sequence_operations=operations, gpu_oracle=str(gpu_target.relative_to(ROOT)), gpu_cases=len(gpu_cases), gpu_operations=gpu_operations) print(json.dumps(report)) if __name__ == "__main__": main()