Files
nvdriver/tools/check_rmapi_binary.py

1923 lines
92 KiB
Python

#!/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
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={})
assert 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)
assert E.call("_nv054244rm") & 0xffffffff == 0 # rmapiInitialize
assert 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("<IIIIQII", root, parent, new, klass, address, size,
0xdddddddd)
else:
request = struct.pack("<IIIIQQIIII", root, parent, new, klass, address, 0, size,
flags, 0xdddddddd, 0xeeeeeeee)
status, reply = escape(self.context, node, file, 0x2b, request)
params_out = E.read(address, len(params)) if params is not None else None
# The user pointer is fixture memory: canonicalize it in the record.
canonical = bytearray(request)
canonical_reply = bytearray(reply)
marker = struct.pack("<Q", 0x1000 if params is not None else 0)
canonical[16:24] = marker
canonical_reply[16:24] = marker
self.emit("L" if legacy else "A", node, file, bytes(canonical), params, status,
bytes(canonical_reply), params_out)
fields = struct.unpack("<IIII", reply[:16])
result = struct.unpack_from("<I", reply, 28 if legacy else 40)[0]
return result, fields[2]
def free(self, root, parent, obj, file=0, node="ctl"):
request = struct.pack("<IIII", root, parent, obj, 0xdddddddd)
before = state["purge"]
state["freed"].clear()
status, reply = escape(self.context, node, file, 0x29, request)
self.emit("F", node, file, request, None, status, reply, None)
self.lines.append(f"purged {state['purge'] - before}")
self.lines.append("freed " + (",".join(f"{handle:x}" for handle in state["freed"])
or "-"))
return struct.unpack_from("<I", reply, 12)[0]
def control(self, client, obj, command, params=None, size=None, flags=0, file=0,
node="ctl", null_pointer=False):
address = 0 if null_pointer else user(params)
length = (len(params) if params is not None else 0) if size is None else size
request = struct.pack("<IIIIQII", client, obj, command, flags, address, length,
0xdddddddd)
status, reply = escape(self.context, node, file, 0x2a, request)
params_out = (E.read(address, len(params))
if params is not None and not null_pointer else None)
canonical = bytearray(request)
canonical_reply = bytearray(reply)
marker = struct.pack("<Q", 0x1000 if address else 0)
canonical[16:24] = marker
canonical_reply[16:24] = marker
self.emit("C", node, file, bytes(canonical),
params if not null_pointer else None, status, bytes(canonical_reply),
params_out)
return struct.unpack_from("<I", reply, 28)[0], params_out
def build_version(self, client, length, null=()):
"""NV0000_CTRL_CMD_SYSTEM_GET_BUILD_VERSION (deprecated command 0x101): three user
string buffers inside the 40-byte parameter block."""
buffers = [E.allocate(0x110, 0xa5) for _ in range(3)]
pointers = [0 if index in null else buffer for index, buffer in enumerate(buffers)]
params = struct.pack("<IIQQQII", length, 0, *pointers, 0xa5a5a5a5, 0xa5a5a5a5)
address = user(params)
request = struct.pack("<IIIIQII", client, client, 0x101, 0, address, 40, 0xdddddddd)
status, reply = escape(self.context, "ctl", 0, 0x2a, request)
out = bytearray(E.read(address, 40))
canonical, canonical_reply, sent = bytearray(request), bytearray(reply), bytearray(params)
canonical[16:24] = canonical_reply[16:24] = struct.pack("<Q", 0x1000)
for index in range(3):
marker = struct.pack("<Q", 0 if index in null else 0x2000 + 0x1000 * index)
sent[8 + 8 * index:16 + 8 * index] = marker
out[8 + 8 * index:16 + 8 * index] = marker
self.emit("C", "ctl", 0, bytes(canonical), bytes(sent), status, bytes(canonical_reply),
bytes(out))
for index, buffer in enumerate(buffers):
self.lines.append(f"string {index} {E.read(buffer, 0x110).hex()}")
Sequence.build_version = build_version
def dispatcher_table():
"""Size and node rules of _nv000800rm with every callee replaced by a recorder."""
context = setup()
called = []
hooks = []
state["called"] = called
targets = ["_nv000636rm", "_nv000637rm", "_nv000638rm", "_nv000639rm", "_nv000641rm",
"_nv000644rm", "_nv000646rm", "_nv000647rm", "_nv000649rm", "_nv000650rm",
"_nv000651rm", "_nv000653rm", "_nv000655rm", "_nv000656rm", "_nv000657rm",
"_nv000659rm", "_nv000661rm", "_nv000663rm", "_nv000665rm", "_nv000667rm",
"_nv000669rm", "_nv000732rm", "_nv054151rm", "_nv054155rm", "_nv054156rm",
"_nv054198rm", "_nv054260rm", "_nv054264rm", "_nv019661rm", "_nv019662rm",
"_nv019663rm", "nv_get_file_private", "nv_put_file_private",
"nv_get_adapter_state"]
for name in targets:
assert name in E.by_name or name in E.externals, name
hooks.append(E.install(name, lambda a, name=name: called.append(name) or 0))
lines = ["case dispatcher"]
sizes = sorted({0, 4, 8, 0xc, 0x10, 0x14, 0x18, 0x1c, 0x20, 0x28, 0x30, 0x38, 0x40, 0x48,
0xb8, 0x3c34} | {size + delta for size in (4, 0xc, 0x10, 0x14, 0x18, 0x1c,
0x20, 0x28, 0x30, 0x38, 0x40,
0x48, 0xb8)
for delta in (-4, 4)})
classes = (0, 1, 2, 5, 0x41, 0x42, 0x77, 0x78, 0x79, 0x7a, 0x7d, 0x7e, 0x7f, 0x80, 0x2080)
for command in range(0x100):
for node in ("ctl", "dev"):
for size in sizes:
variants = classes if command == 0x2b and size in (0x20, 0x30) else (None,)
for klass in variants:
data = bytearray(max(size, 0x40))
if klass is not None:
struct.pack_into("<I", data, 12, klass)
if command == 0x29:
# Root free with status 0 left by the recorder: the purge is reached.
struct.pack_into("<III", data, 0, 0x55, 0, 0x55)
called.clear()
block = E.allocate(len(data))
E.write(block, data)
status = E.call("_nv000800rm", context["nodes"][node], context["files"][0],
command, block, size) & 0xffffffff
rewritten = E.d(block + 12) if klass is not None else 0
lines.append(
f"D {command:x} {node} {size:x} {klass if klass is not None else -1:x}"
f" -> {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("<IIHH", 0, 0xffffffff, 3, 0))
case.control(client, client, 0xd04, params=struct.pack("<IIHH", 1, 0x3, 3, 0))
case.control(client, client, 0xd04, params=struct.pack("<IIHH", 0, 0xffffffff, 8, 0))
case.control(client, client, 0xd04, params=pattern[:12])
# The two requests of the workload (records 9 and 10), then variations.
case.control(client, client, 0xd04, params=struct.pack("<IIHBB", client, 1, 4, 0, 0))
case.control(client, client, 0xd04, params=struct.pack("<IIHBB", client, 4, 4, 4, 0))
for kind in range(9):
for action in (0, 1, 2, 4, 6, 8):
for target in (0, client):
case.control(client, client, 0xd04,
params=struct.pack("<IIHBB", target, 0x5, kind, action, 0xa5))
case.control(client, client, 0xd04, params=struct.pack("<IIHBB", client, 0, 4, 0, 0))
case.control(client, client, 0xd04,
params=struct.pack("<IIHBB", client, 0xffffffff, 4, 0, 0))
case.control(client, client, 0x1f0, params=pattern[:4])
case.control(client, client, 0x214, params=pattern[:384])
case.control(client, client, 0xa04, params=pattern[:2244])
attach = bytearray(pattern[:132])
struct.pack_into("<32I", attach, 0, *([ids[0]] + [0xffffffff] * 31))
case.control(client, client, 0x215, params=bytes(attach))
struct.pack_into("<I", attach, 0, 0xffff)
case.control(client, client, 0x215, params=bytes(attach))
struct.pack_into("<II", attach, 0, ids[0], 0x7777)
case.control(client, client, 0x215, params=bytes(attach))
struct.pack_into("<32I", attach, 0, *([ids[-1]] * 32))
case.control(client, client, 0x215, params=bytes(attach))
struct.pack_into("<32I", attach, 0, *([ids[0], 0x3d00] + [0xffffffff] * 30))
case.control(client, client, 0x215, params=bytes(attach))
struct.pack_into("<32I", attach, 0, *([0xffffffff] * 32))
case.control(client, client, 0x215, params=bytes(attach))
case.control(client, client, 0x288, params=pattern[:3076])
case.control(client, client, 0x201, params=pattern[:128])
for gpu_id in ids[:12] + [0x7777, 0xffffffff]:
block = bytearray(pattern[:32])
struct.pack_into("<I", block, 0, gpu_id)
case.control(client, client, 0x205, params=bytes(block))
block = bytearray(pattern[:40])
struct.pack_into("<I", block, 0, gpu_id)
case.control(client, client, 0x202, params=bytes(block))
for length in (0x100, 0x50, 53, 52, 29, 11, 4, 0):
case.build_version(client, length)
for null in ((0, 1, 2), (0,), (1,), (2,), (0, 1), (1, 2)):
case.build_version(client, 0x100, null=null)
case.build_version(client, 4, null=null)
cases.append(case)
return cases
# ---------------------------------------------------------------------------------------
# GPU-backed objects (slice 2). Nothing below is fabricated object memory: the system
# object comes from the original core initializer and the GPU object from the original
# probe and attach routines.
#
# _nv021662rm coreInitializeRm: OBJSYS, the GPU manager, the resource server and
# the RM API (the internal client takes handle 0xc1d00000)
# _nv000794rm(nv) RmInitPrivateState: PMC_BOOT_0/1/42, gpumgrRegisterGpuId
# _nv031506rm gpumgrThreadEnableExpandedGpuVisibility
# _nv031359rm, _nv054107rm, _nv031377rm
# gpumgrAllocGpuInstance, rmGpuLockAlloc, gpumgrCreateDevice
# _nv031364rm(inst, arg) gpumgrAttachGpu: objCreate(OBJGPU) with its four HAL binders, the
# property initializer, gpuPostConstruct with every engine child of a
# GV100 constructed (children table, engine lists, class database)
# _nv031505rm visibility off again
#
# These are the steps of RmInitAdapter (_nv000790rm) up to and including the attach. The
# state stages after it (RmInitNvDevice: PreInit, Init, Load) are NOT executed, so the GPU
# object is constructed but not initialized. The original only lets gpumgrGetGpu return a
# GPU whose byte +0x90d (PDB_PROP_GPU_STATE_INITIALIZED) is set; the cases set that byte
# where they say "initialized 1" to reach the class constructors and control handlers.
# Whatever a handler reads from state the stages would have produced is therefore the
# constructor's value, and the cases only keep handlers for which that is stated in the
# implementation notes.
#
# Fixture-supplied for these cases, beyond the list at the top:
# * register writes (_nv049615rm, osDevWriteReg032): recorded, not applied;
# * register reads (_nv049612rm, osDevReadReg032): the case's register table, taken from
# the physical transcript of 0000:b3:00.0 (first read of each register); a register
# outside the table raises. Of BAR0 only the first page is mapped (the probe-time read
# of PMC_BOOT_0, _1 and _42 by RmInitPrivateState), so any other direct access raises;
# * open-layer queries: nv_is_gpu_accessible (case input: the caller holds the GPU's
# device node open), nv_get_file_private/nv_put_file_private (descriptor numbers of the
# case's files), nv_requires_dma_remap (0), nv_set_dma_address_size, nv_get_dev_minor
# (0), os_map_kernel_space/os_unmap_kernel_space (probe-time page), platform queries
# answered "no" (notebook, battery, EFI, s0ix, NVSwitch, GRID CSP), crash-log records,
# os_registry_init, os_dbg_init, os_get_cpu_frequency (0);
# * the original's control cache runs in the mode its initializer _nv054213rm sets (1,
# enabled; slice 3). A cacheable command is therefore answered from the first reply of
# its GPU instance. Where a case wants the handler itself (rule and input variations) it
# says "flush": the original's own rmapiControlCacheFreeAllCacheForGpu (_nv054205rm) is
# called for GPU instance 0 and for the system-wide key 0x20, which is what the original
# does for a GPU at state destroy. The mode word (the global _nv054210rm compares with 2)
# is only written by the steps "cache": 2 is the original's verify-only mode (lookups
# miss, stores compare and leave the diagnostic A240 on a difference), 0 disables;
# * the RM API lock stays a fixture (always acquired, owner queries true); the GPUs lock
# is the original code here (_nv054115rm, _nv054117rm, _nv054116rm are not replaced),
# because the control handlers assert its owner state.
GPU_LOCKS = ("_nv054115rm", "_nv054117rm", "_nv054116rm")
# Stage bodies executed in front of control handlers and constructors (slices 3c and 4):
# name -> (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.
assert offset in source, f"register {offset:#x} has no value for this stage"
gpu_state["registers"][offset] = source[offset]
assert 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")
assert code[position + 6] == 2
return start + position + 7 + struct.unpack_from("<i", code, position + 2)[0]
def gpu_world(registers=None, pci=V100_PCI):
"""Core init, probe and attach of one GPU. Returns (context, gpu object, nv, system)."""
for name in GPU_LOCKS:
if name in HOOKS:
E.cpu.hook_del(HOOKS.pop(name))
E.handlers.pop(name)
for name, handler in GPU_FIXTURES.items():
if name not in HOOKS:
HOOKS[name] = E.install(name, handler)
E.reset()
E.wq(E.externals["os_page_size"], 0) # set by GpuSequence.stage
state.update(admin=0, diag=[], purge=0, gpu_flags={})
gpu_state.update(registers=dict(registers or transcript_registers()), accessible=1,
read=[], written=[], files={}, cache=0, source=None)
assert E.call("_nv021662rm") & 0xffffffff == 0 # coreInitializeRm
gpu_state["cache_word"] = cache_mode_address()
gpu_state["cache_default"] = E.d(gpu_state["cache_word"])
assert gpu_state["cache_default"] == 1
system = E.q(SYSTEM_SLOT)
manager = E.q(system + 0x1e0)
# nv_state_t of the public open layer (offsets from kernel-open/common/inc/nv.h).
nv = E.allocate(0x400)
E.wd(nv + 0x14, pci["domain"])
E.write(nv + 0x18, bytes([pci["bus"], pci["slot"], pci["function"], 0]))
E.write(nv + 0x1c, struct.pack("<HHHH", pci["vendor"], pci["device"], pci["subsystem"],
pci["subsystem_vendor"]))
for index, (address, size) in enumerate(pci["bars"]):
E.wq(nv + 0x90 + 0x28 * index, address)
E.wq(nv + 0x98 + 0x28 * index, size)
E.wq(nv + 0x108, nv + 0x90) # regs
E.wq(nv + 0x140, nv + 0xb8) # fb
E.wd(nv + 0x17c, pci["irq"])
# RmInitPrivateState reads PMC_BOOT_0, _1 and _42 through its own one-page mapping.
if not gpu_state.get("page"):
E.cpu.mem_map(BAR0, 0x1000)
gpu_state["page"] = True
E.write(BAR0, bytes(0x1000))
for offset in (0x0, 0x4, 0xa00):
E.wd(BAR0 + offset, gpu_state["registers"][offset])
assert E.call("_nv000794rm", nv) & 0xff == 1 # RmInitPrivateState
E.wq(nv + 0xa8, BAR0) # regs->map (RmSetupRegisters)
slot = E.allocate(16)
assert E.call("_nv031506rm") & 0xffffffff == 0
assert E.call("_nv031359rm", slot) & 0xffffffff == 0
instance = E.d(slot)
assert E.call("_nv054107rm", instance) & 0xffffffff == 0
assert 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
assert status == 0, hex(status)
E.call("_nv031505rm")
assert 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
assert E.call("_nv031506rm") & 0xffffffff == 0
assert E.call("_nv054115rm", 0, 1) & 0xffffffff == 0
status = E.call(body, self.gpu, instance, *extra) & 0xffffffff
assert E.call("_nv054117rm", 0, 0) & 0xffffffff == 0
E.call("_nv031505rm")
assert 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("<II", E.read(base + 8 * index, 8))
for index in range(number)]
self.lines.append(f"{label} " + " ".join(f"{klass:x}:{engine:x}"
for klass, engine in records))
def engine_table(self):
"""The static table gpuUpdateEngineTable (_nv031235rm) walks: 16-byte records of RM
engine type, engine class id, instance and a valid byte. Its bounds are the two
immediates of the loop (`mov rbx, first` at +0x40, `cmp rbx, end` at +0x9e)."""
start = E.by_name["_nv031235rm"]
code = E.read(start, 0xa8)
assert code[0x40:0x43] == b"\x48\xc7\xc3" and code[0x9e:0xa1] == b"\x48\x81\xfb"
first, end = (struct.unpack_from("<I", code, offset)[0] for offset in (0x43, 0xa1))
assert (end - first) % 16 == 0
records = [struct.unpack("<IIIB", E.read(address, 13))
for address in range(first, end, 16)]
# gpuGetNv2080EngineTypeList (_nv030671rm) gives the type the control reports.
source, target = E.allocate(4 * len(records)), E.allocate(4 * len(records))
E.write(source, b"".join(struct.pack("<I", record[0]) for record in records))
E.call("_nv030671rm", source, len(records), target)
self.lines.append("engine-table " + " ".join(
f"{kind:x}:{klass << 8 | instance:x}:{valid}:{E.d(target + 4 * index):x}"
for index, (kind, klass, instance, valid) in enumerate(records)))
def sweep(self):
"""The original's base PreInit pass _nv031220rm (gpuStatePreInit) on this GPU as the
first open runs it: GPU not yet initialized, expanded visibility, GPUs lock held.
The per-engine PreInit dispatcher _nv026850rm is replaced by "status 0", so what
executes is the prologue (branding, internal client, device and subdevice, chip
information) and the missing-engine sweep with the engines' own presence checks.
Register writes are recorded, not applied."""
values = first_reads()
for offset in SWEEP_REGISTERS:
gpu_state["registers"].setdefault(offset, values[offset])
hooks = [E.install("os_delay_us", lambda a: 0), E.install("_nv026850rm", lambda a: 0)]
deleted = []
watch = E.cpu.hook_add(
UC_HOOK_CODE, lambda emu, address, size, unused: deleted.append(
emu.reg_read(UC_X86_REG_RSI) & 0xffffffff),
begin=E.by_name["_nv030262rm"], end=E.by_name["_nv030262rm"])
gpu_state["read"].clear()
gpu_state["written"].clear()
state["diag"].clear()
initialized = E.b(self.gpu + 0x90d)
E.wb(self.gpu + 0x90d, 0)
assert E.call("_nv031506rm") & 0xffffffff == 0
assert E.call("_nv054115rm", 0, 1) & 0xffffffff == 0 # rmGpuLocksAcquire
status = E.call("_nv031220rm", self.gpu) & 0xffffffff
assert E.call("_nv054117rm", 0, 0) & 0xffffffff == 0 # rmGpuLocksRelease
E.call("_nv031505rm")
E.wb(self.gpu + 0x90d, initialized)
for hook in hooks + [watch]:
E.cpu.hook_del(hook)
for name in ("os_delay_us", "_nv026850rm"):
E.handlers.pop(name)
assert not state["diag"], state["diag"]
self.lines.append("sweep-registers " + " ".join(
f"{offset:x}={gpu_state['registers'][offset]:x}"
for offset in dict.fromkeys(gpu_state["read"])))
self.lines.append("sweep-writes " + (" ".join(
f"{offset:x}={value:x}" for offset, value in gpu_state["written"]) or "-"))
self.lines.append("sweep-removed " + " ".join(f"{engine:x}" for engine in deleted))
# The pass allocates the GPU's internal client (GPU+0x423c): one client index.
self.lines.append(f"sweep {status:x} {E.d(self.gpu + 0x423c):x}")
return status
def register_fd(self, file, descriptor, node="dev", size=4):
"""NV_ESC_REGISTER_FD on device file `file` naming control descriptor `descriptor`."""
status, reply = escape(self.context, node, file, 0xc9,
struct.pack("<i", descriptor)[:size] + bytes(max(0, size - 4)))
self.lines.append(f"R {node} {file} {descriptor:x} {size:x} -> {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("<IIIIIIQQQII", device, share, target_client, target_device, flags, 0,
size, start, limit, mode, 0)
def gpu_sequences():
cases = []
client = 0xc1d00001 # 0xc1d00000 is the RM's internal client
pattern = bytes([0xa5]) * 4096
case = GpuSequence("gpu-classes")
assert case.alloc(0, 0, 0, 0)[1] == client
good = device_params(share=client, mode=2) # the workload's parameters
# Before the GPU is initialized nothing can be allocated on it.
case.alloc(client, client, 0, 0x80, params=good)
case.alloc(client, client, 0, 0x80)
case.control(client, client, 0x201, params=pattern[:128])
info = bytearray(pattern[:40])
struct.pack_into("<I", info, 0, 0xb300)
case.control(client, client, 0x202, params=bytes(info))
case.initialized(1)
case.control(client, client, 0x201, params=pattern[:128])
case.control(client, client, 0x202, params=bytes(info))
case.control(client, client, 0x205, params=bytes(info[:32]))
# The caller must hold the GPU's device node open (nv_is_gpu_accessible).
case.accessible(0)
case.alloc(client, client, 0, 0x80, params=good)
case.admin(1)
case.alloc(client, client, 0, 0x80, params=good)
case.admin(0)
case.accessible(1)
# hClientShare naming another client: of the same file, of another file, and with the
# caller an administrator.
assert case.alloc(0, 0, 0, 0)[1] == client + 1
assert case.alloc(0, 0, 0, 0, file=1)[1] == client + 2
for admin in (0, 1):
case.admin(admin)
for share in (client + 1, client + 2):
result, handle = case.alloc(client, client, 0x6000, 0x80,
params=device_params(share=share, mode=2))
if result == 0:
case.free(client, 0, handle)
case.admin(0)
case.free(client + 1, 0, client + 1)
case.free(client + 2, 0, client + 2, file=1)
# Parameter rules of the device.
for params in (device_params(device=1, share=client, mode=2),
device_params(device=31, share=client, mode=2),
device_params(device=32, share=client, mode=2),
device_params(device=0xffffffff, share=client, mode=2),
device_params(share=0x12345, mode=2),
device_params(share=0xc1d00000, mode=2),
device_params(share=client, target_client=client, mode=2),
device_params(share=client, target_client=0x777, target_device=0x888, mode=2),
device_params(share=client, mode=3),
device_params(share=client, mode=4),
device_params(share=client, mode=0xffffffff),
device_params(share=client, flags=0xffffffff, mode=2),
device_params(share=client, size=0x1000, start=0x1000, limit=0xffff, mode=2),
device_params(share=client, flags=0x800, start=0x2000, limit=0x1000, mode=2),
device_params(share=client, flags=0x800, start=0x1000, limit=0x1000, mode=2),
device_params(share=client, flags=0x808, start=0x1000, limit=0x2000, mode=2),
device_params(share=client, flags=0x6000, mode=2),
device_params(share=0x12345, flags=0x800, mode=2),
device_params(device=1, share=0x12345, flags=0x800, mode=2),
device_params(share=0x12345, flags=0x4008, mode=2),
device_params(share=client, flags=0x4008, mode=2)):
result, handle = case.alloc(client, client, 0x6000, 0x80, params=params)
if result == 0:
case.free(client, 0, handle)
for flag in range(32):
result, handle = case.alloc(client, client, 0x6000, 0x80,
params=device_params(share=client, flags=1 << flag, mode=2))
if result == 0:
case.free(client, 0, handle)
# VASPACE_SIZE (flag 8) with explicit sizes and ranges.
for size, start, limit in ((0x1000, 0, 0), (0x100000000, 0, 0), (1 << 40, 0, 0),
(1 << 49, 0, 0), (1 << 50, 0, 0), (0xffffffffffffffff, 0, 0),
(0x100000000, 0x1000, 0xffffffff), (0, 0x1000, 0xffffffff)):
result, handle = case.alloc(client, client, 0x6000, 0x80, params=device_params(
share=client, flags=8, size=size, start=start, limit=limit, mode=2))
if result == 0:
case.free(client, 0, handle)
for mode in (0, 1):
result, handle = case.alloc(client, client, 0x6000, 0x80,
params=device_params(share=client, mode=mode))
if result == 0:
case.free(client, 0, handle)
result, handle = case.alloc(client, client, 0x6000, 0x80, params=device_params(mode=2))
if result == 0:
case.free(client, 0, handle)
result, handle = case.alloc(client, client, 0x6000, 0x80)
if result == 0:
case.free(client, 0, handle)
_, device = case.alloc(client, client, 0, 0x80, params=good)
case.alloc(client, client, 0, 0x80, params=good) # a second device on the GPU
case.alloc(client, client, device, 0x80, params=good)
case.control(client, client, 0x202, params=bytes(info))
# Subdevice: NV2080_ALLOC_PARAMETERS { subDeviceId }.
case.alloc(client, client, 0, 0x2080, params=bytes(4))
for number in (1, 2, 7, 8, 9, 0x80000000, 0xffffffff):
case.alloc(client, device, 0, 0x2080, params=struct.pack("<I", number))
case.alloc(client, device, 0, 0x2080, params=struct.pack("<I", 1))
_, subdevice = case.alloc(client, device, 0, 0x2080, params=bytes(4))
case.alloc(client, device, 0, 0x2080, params=bytes(4))
case.alloc(client, device, 0, 0x2080)
# BinaryApi and the confidential-compute object.
case.alloc(client, device, 0, 0x2081, params=bytes(4))
_, binary = case.alloc(client, subdevice, 0, 0x2081, params=pattern[:4])
case.alloc(client, subdevice, 0, 0x2081)
_, compute = case.alloc(client, client, 0, 0xcb33, params=pattern[:4])
case.alloc(client, client, 0, 0xcb33)
case.alloc(client, device, 0, 0xcb33)
# Controls. Every block is filled with 0xa5 so that untouched bytes are visible.
def run(obj, command, size, edit=None, **keywords):
block = bytearray(pattern[:size])
if edit:
edit(block)
case.flush()
return case.control(client, obj, command, params=bytes(block) if size else None,
size=size, null_pointer=not size, **keywords)
run(compute, 0xcb330101, 6)
for offsets in ((0xa4,), (0xa4, 0xa5), (0xa4, 0xa7), (0xa4, 0xa8), (0xa4, 0xa7, 0xa8),
(0xa5,)):
for offset in offsets:
case.poke("sys", offset, 1, 1)
run(compute, 0xcb330101, 6)
for offset in offsets:
case.poke("sys", offset, 1, 0)
run(client, 0x27b, 4)
case.poke("sys", 0x67, 1, 1)
run(client, 0x27b, 4)
case.poke("sys", 0x67, 1, 0)
run(client, 0x136, 4)
for offsets in ((0x6c,), (0x6c, 0x6e), (0x6c, 0x6d), (0x6c, 0x6d, 0x6e), (0x6d, 0x6e)):
for offset in offsets:
case.poke("sys", offset, 1, 1)
run(client, 0x136, 4)
for offset in offsets:
case.poke("sys", offset, 1, 0)
for ids in ((0xb300,), (0xffff,), (0x1a00,), (0xb300, 0x1a00), (0xb300, 0xb300), (),
(0xffffffff, 0xb300)):
words = list(ids) + [0xffffffff] * (32 - len(ids))
case.control(client, client, 0x216, params=struct.pack("<32I", *words))
run(device, 0x800280, 4)
run(device, 0x800289, 8)
for offsets in ((0xe00,), (0x4de6,), (0xe00, 0x4de6)):
for offset in offsets:
case.poke("gpu", offset, 1, 1)
run(device, 0x800289, 8)
for offset in offsets:
case.poke("gpu", offset, 1, 0)
run(subdevice, 0x20801701, 16)
case.poke("gpu", 0xd38, 1, 3)
run(subdevice, 0x20801701, 16)
case.poke("gpu", 0xd38, 1, 0)
run(subdevice, 0x20801801, 16)
run(subdevice, 0x20800119, 4)
for offsets in ((0x4de3,), (0x4de4,), (0x4de5,), (0x90e,), (0x4de2,), (0x4de4, 0x4de5),
(0x90e, 0x4de2), (0x4de3, 0x90e)):
for offset in offsets:
case.poke("gpu", offset, 1, 1)
run(subdevice, 0x20800119, 4)
for offset in offsets:
case.poke("gpu", offset, 1, 0)
run(subdevice, 0x20800131, 4)
for rules in (1, 2, 3, 0):
case.poke("gpu", 0x1e2c, 4, rules)
run(subdevice, 0x20800131, 4)
run(subdevice, 0x20808162, 1)
case.poke("gpu", 0x541f, 1, 1)
run(subdevice, 0x20808162, 1)
case.poke("gpu", 0x541f, 1, 0)
run(subdevice, 0x20803601, 72)
run(binary, 0x20810108, 992)
run(subdevice, 0x2080182b, 28)
def table(count, indexes):
def edit(block):
struct.pack_into("<I", block, 0, count)
for position, index in enumerate(indexes):
struct.pack_into("<I", block, 4 + 8 * position, index)
return edit
run(subdevice, 0x20808159, 332, table(1, [0]))
run(subdevice, 0x20808159, 332, table(0x29, range(0x29)))
run(subdevice, 0x20808159, 332, table(3, [0x28, 0x29, 5]))
run(subdevice, 0x20808159, 332, table(0, []))
run(subdevice, 0x20808159, 332, table(0x2a, range(0x29)))
case.poke("gpu", 0x6d66 + 7, 1, 0x5a)
run(subdevice, 0x20808159, 332, table(2, [7, 8]))
case.poke("gpu", 0x6d66 + 7, 1, 0)
# Compute-mode reservation (GPU+0x1e34 holds the owning client).
for rules in (0, 1, 2, 3):
case.poke("gpu", 0x1e2c, 4, rules)
run(subdevice, 0x20800146, 0)
run(subdevice, 0x20800145, 0)
run(subdevice, 0x20800145, 0)
run(subdevice, 0x20800146, 0)
run(subdevice, 0x20800146, 0)
case.poke("gpu", 0x1e34, 4, 0x777)
run(subdevice, 0x20800145, 0)
run(subdevice, 0x20800146, 0)
case.poke("gpu", 0x1e34, 4, 0)
case.poke("gpu", 0x1e2c, 4, 0)
# A subdevice whose instance number names no GPU of the device.
run(0xcaf00006, 0x20801701, 16)
run(0xcaf00006, 0x20801801, 16)
# Entry rules on GPU-bound objects.
run(device, 0x20801701, 16)
run(subdevice, 0x800280, 4)
run(binary, 0x20801701, 16)
run(subdevice, 0x20801701, 12)
run(subdevice, 0x20801701, 16, flags=4)
run(subdevice, 0x20801701, 16, file=1)
case.initialized(0)
run(subdevice, 0x20801701, 16)
run(device, 0x800280, 4)
case.initialized(1)
# Device-node escape: NV_ESC_REGISTER_FD.
case.register_fd(3, 10)
case.register_fd(3, 10)
case.register_fd(3, 11)
case.register_fd(4, 99)
case.register_fd(4, 20)
case.register_fd(4, 11)
case.register_fd(5, 10, size=8)
case.register_fd(0, 10, node="ctl")
case.register_fd(1, 10, node="ctl")
case.register_fd(1, 20, node="ctl")
# The reservation of a client that goes away.
case.poke("gpu", 0x1e2c, 4, 1)
run(subdevice, 0x20800145, 0)
case.peek("gpu", 0x1e34, 4)
# Destruction order with GPU-bound objects.
_, second = case.alloc(client, client, 0, 0x80, params=good)
case.alloc(client, second, 0, 0x2080, params=bytes(4))
case.free(client, 0, subdevice)
case.peek("gpu", 0x1e34, 4)
case.alloc(client, device, 0x7000, 0x2080, params=bytes(4))
run(0x7000, 0x20800145, 0)
case.peek("gpu", 0x1e34, 4)
case.alloc(client, 0x7000, 0x7001, 0x2081)
case.free(client, 0, device)
case.control(client, client, 0x202, params=bytes(info))
case.peek("gpu", 0x1e34, 4)
case.free(client, 0, client)
case.peek("gpu", 0x1e34, 4)
cases.append(case)
cases += slice3_sequences(client, good, pattern)
cases += slice3c_sequences(client, good, pattern)
cases += slice4_sequences(client, good, pattern)
return cases
# PCE-LCE registers of the first copy-engine shim (BAR0 0x104000): PCE2LCE_CONFIG(i) at
# 0x104040 + 4 i for the nine PCEs, GRCE_CONFIG(i) at 0x104034 + 4 i for the two GRCEs.
def ce_registers(pce, grce):
table = {0x104040 + 4 * index: value for index, value in enumerate(pce)}
table.update({0x104034 + 4 * index: value for index, value in enumerate(grce)})
return table
CE_VARIANTS = (
# The traced board: PCE 0..7 on LCE 2, 3, 4, 4, 5, 5, 6, 7, PCE 8 unassigned; both GRCEs
# shared (bit 30) with LCE 4 and 5.
("transcript", None),
("all-on-lce2", ce_registers([2] * 9, [0x40000002, 0x40000002])),
("one-each", ce_registers(list(range(9)), [0, 0])),
("grce-not-shared", ce_registers([2, 3, 4, 4, 5, 5, 6, 7, 8], [4, 5])),
("grce1-shared-only", ce_registers([0xf, 3, 3, 3, 0xf, 0xf, 0xf, 0xf, 0xf], [0, 0x40000003])),
("high-nibble", ce_registers([0x12, 0x23, 0xf4, 0x4, 0x5, 0x5, 0x6, 0x7, 0x1f],
[0x40000014, 0x80000005])),
)
def slice3c_sequences(client, good, pattern):
"""Slice 3c: the engine list (0x20800170) behind the original's copy-engine stage bodies.
OBJCE PreInitLocked, KernelCE InitLocked, OBJCE InitUnlocked, OBJCE PreLoad and KernelCE
Load run in the order of the first open; the Load of the shim owner (KernelCE 0) issues
the PCE-LCE mapping update, whose class-database pass _nv019120rm marks each LCE without
a PCE as stubbed (OBJCE+0x488) and deletes its classes."""
cases = []
for name, registers in CE_VARIANTS:
case = GpuSequence("gpu-slice3c-" + name)
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))
engines = lambda obj=subdevice, size=340, block=None, **keywords: case.control(
client, obj, 0x20800170, params=(pattern[:size] if block is None else block),
**keywords)
if registers is None:
case.engine_table()
engines() # constructed GPU
case.sweep()
if registers is None:
engines() # swept, before the CE stages
for stage in CE_STAGES:
case.stage(stage, registers if stage == "kce-load" else None)
for index in range(9):
case.peek(f"oce{index}", 0x488, 1)
case.class_table()
engines()
if registers is None:
engines(block=bytes(340))
engines(obj=device)
engines(size=336)
engines(flags=4)
case.initialized(0)
engines()
case.initialized(1)
engines()
cases.append(case)
return cases
def vaspace_params(index=0, flags=0, size=0, start=0, limit=0, big=0, base=0, tail=0):
"""NV_VASPACE_ALLOCATION_PARAMETERS (56 bytes)."""
return struct.pack("<IIQQQIIQQ", index, flags, size, start, limit, big, 0, base, tail)
def slice4_sequences(client, good, pattern):
"""Slice 4: VA spaces. FERMI_VASPACE_A (0x90f1, VaSpaceApi constructor _nv059869rm ->
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.
assert 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("<I", caps, 164, 0)
case.control(client, other, 0x801806, params=bytes(caps))
probe(other, space(flags=0x48, base=0x1000))
probe(other, space(index=3))
probe(other, space(index=3, flags=0x48, base=0x1000, size=0x1000, big=0x20000))
case.control(client, other, 0x801806, params=bytes(caps))
case.free(client, 0, other)
external = probe(device, space(flags=0x48, base=0x1000), keep=True)
managed = probe(device, space(base=0x5000000), keep=True)
probe(device, space(flags=0x48, base=0x1000), keep=True) # a second one of each kind
_, device2 = case.alloc(client, client, 0, 0x80, params=good)
foreign = probe(device2, space(), keep=True)
def run(obj, command, block, **keywords):
gpu_state["read"].clear()
gpu_state["written"].clear()
result = case.control(client, obj, command, params=bytes(block), **keywords)
assert not gpu_state["read"] and not gpu_state["written"]
return result
# 0x801806 NV0080_CTRL_CMD_DMA_ADV_SCHED_GET_VA_CAPS (192 bytes, hVASpace at 164).
for handle in (0, external, managed, foreign, subdevice, device, 0x777):
block = bytearray(pattern[:192])
struct.pack_into("<I", block, 164, handle)
run(device, 0x801806, block)
for big in (0x10000, 0x20000):
handle = probe(device, space(big=big, base=0x200000, size=0x400000), keep=True)
block = bytearray(pattern[:192])
struct.pack_into("<I", block, 164, handle)
run(device, 0x801806, block)
case.free(client, 0, handle)
block = bytearray(192)
struct.pack_into("<I", block, 164, managed)
run(device, 0x801806, block)
run(device2, 0x801806, block)
run(subdevice, 0x801806, block)
run(device, 0x801806, block[:188])
# NV50_THIRD_PARTY_P2P: NV503C_ALLOC_PARAMETERS { flags } with the type in bits 1:0.
for flags in (0, 2, 3, 4, 0xfffffffd):
result, handle = case.alloc(client, subdevice, 0, 0x503c, params=struct.pack("<I", flags))
if result == 0:
case.free(client, 0, handle)
result, handle = case.alloc(client, subdevice, 0, 0x503c)
if result == 0:
case.free(client, 0, handle)
case.alloc(client, device, 0, 0x503c, params=struct.pack("<I", 1))
_, p2p = case.alloc(client, subdevice, 0, 0x503c, params=struct.pack("<I", 1))
case.alloc(client, subdevice, 0, 0x503c, params=struct.pack("<I", 1))
register = lambda handle, obj=p2p: run(obj, 0x503c0102,
struct.pack("<I", handle) + pattern[:12])
unregister = lambda handle, obj=p2p: run(obj, 0x503c0103, struct.pack("<I", handle))
register(external) # the workload's request
register(external)
register(managed)
register(foreign)
register(0x999)
register(0)
register(subdevice)
register(0xfe00)
register(0xfe01)
register(0x1234)
unregister(0x999)
unregister(0x999)
unregister(0xfe00)
register(0x4321)
unregister(managed)
register(external, obj=subdevice)
run(p2p, 0x503c0102, bytes(12))
# A registered VA space that goes away takes the P2P object with it (dependant).
case.free(client, 0, external)
unregister(0x1234)
result, p2p = case.alloc(client, subdevice, 0, 0x503c, params=struct.pack("<I", 1))
register(managed, obj=p2p)
register(foreign, obj=p2p)
case.free(client, 0, p2p)
case.free(client, 0, managed)
result, p2p = case.alloc(client, subdevice, 0, 0x503c, params=struct.pack("<I", 1))
register(foreign, obj=p2p)
# Freeing the device of a registered VA space, then everything.
case.free(client, 0, device2)
unregister(foreign, obj=p2p)
probe(device, space(), keep=True)
case.free(client, 0, client)
return [case, vaspace_dependants(client, good, pattern)]
def vaspace_dependants(client, good, pattern):
"""What survives of a VA-space registration: is the P2P object still a dependant of a
VA space it has unregistered, and of a handle that named nothing when it was registered?"""
case = GpuSequence("gpu-vaspace-dependants")
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 = lambda handle=0: case.alloc(client, device, handle, 0x90f1,
params=vaspace_params(base=0x200000))[1]
p2p = lambda: case.alloc(client, subdevice, 0, 0x503c, params=struct.pack("<I", 1))[1]
register = lambda obj, handle: case.control(
client, obj, 0x503c0102, params=struct.pack("<I", handle) + pattern[:12])
unregister = lambda obj, handle: case.control(
client, obj, 0x503c0103, params=struct.pack("<I", handle))
first, second = space(), space()
peer = p2p()
register(peer, first)
unregister(peer, first)
case.free(client, 0, first) # unregistered before the free
register(peer, second)
case.free(client, 0, peer)
# A handle registered before the object of that name exists.
peer = p2p()
register(peer, 0x7000)
third = space(0x7000)
case.free(client, 0, third)
register(peer, second)
unregister(peer, 0x7000)
# Two registrations, the first one freed; then the P2P object itself and a new one.
fourth = space()
register(peer, fourth)
case.free(client, 0, second)
unregister(peer, fourth)
register(peer, fourth)
case.free(client, 0, peer)
peer = p2p()
register(peer, fourth)
# The subdevice as the registered handle: the P2P object is its child and its dependant.
register(peer, subdevice)
case.free(client, 0, subdevice)
register(peer, fourth)
case.free(client, 0, client)
return case
def slice3_sequences(client, good, pattern):
"""Slice 3: the control cache in its normal mode, and the controls whose state the
original's constructors build (host capabilities, PCIe atomics words, RC watchdog
requests, the class list before and after the PreInit missing-engine sweep)."""
cases = []
table = lambda count, indexes: struct.pack("<I", count) + b"".join(
struct.pack("<II", index, 0xa5a5a5a5) for index in indexes)
case = GpuSequence("gpu-control-cache")
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))
assert case.alloc(0, 0, 0, 0, file=1)[1] == client + 1
other = client + 1
_, device2 = case.alloc(other, other, 0, 0x80, params=device_params(share=other, mode=2),
file=1)
_, subdevice2 = case.alloc(other, device2, 0, 0x2080, params=bytes(4), file=1)
arch = lambda obj, who=client, **keywords: case.control(
who, obj, 0x20801701, params=pattern[:16], **keywords)
# Per-GPU key: the first reply answers every object of the GPU, of any client and file,
# and the serialization flag; objects without a GPU attribute reach the normal path.
for obj, keywords in ((subdevice, {}), (subdevice, {}), (device, {}), (client, {}),
(0xbad, {}), (subdevice, dict(flags=4)), (subdevice, dict(file=1)),
(subdevice, dict(flags=1)), (subdevice, dict(flags=2)),
(subdevice, dict(node="dev"))):
arch(obj, **keywords)
arch(subdevice2, who=other, file=1)
arch(subdevice2, who=other)
arch(subdevice, who=other, file=1)
arch(subdevice2)
arch(subdevice, who=0xbad)
case.control(client, subdevice, 0x20801701, params=pattern[:12])
case.control(client, subdevice, 0x20801701, params=pattern[:20])
case.control(client, subdevice, 0x20801701, params=pattern[:16], null_pointer=True)
case.control(client, subdevice, 0x20801701, size=0, null_pointer=True)
case.poke("gpu", 0xd38, 1, 3)
arch(subdevice)
arch(subdevice2, who=other, file=1)
case.flush()
arch(subdevice2, who=other, file=1)
arch(subdevice)
case.poke("gpu", 0xd38, 1, 0)
arch(device)
# The cache answers although the GPU is no longer returned by gpumgrGetGpu.
case.initialized(0)
arch(subdevice)
case.control(client, device, 0x800280, params=pattern[:4])
case.initialized(1)
case.control(client, device, 0x800280, params=pattern[:4])
case.control(client, subdevice, 0x800280, params=pattern[:4])
# A freed object loses its GPU attribute; the GPU's entries stay.
case.free(client, 0, subdevice)
arch(subdevice)
_, subdevice = case.alloc(client, device, 0, 0x2080, params=bytes(4))
arch(subdevice)
# System-wide key (commands of class 0): no client or object is looked at.
memop = lambda who, obj, **keywords: case.control(who, obj, 0x27b, params=pattern[:4],
**keywords)
memop(client, client)
case.poke("sys", 0x67, 1, 1)
memop(client, client)
memop(other, other, file=1)
memop(other, other)
memop(client, subdevice)
memop(0xbad, 0xbad)
memop(client, client, flags=4)
case.control(client, client, 0x27b, params=pattern[:8])
case.flush()
memop(0xbad, 0xbad)
memop(client, subdevice)
memop(client, client)
case.poke("sys", 0x67, 1, 0)
memop(other, other, file=1)
case.flush()
# Cacheable by input (0x20808159).
bytes159 = lambda indexes, count=None, obj=None, **keywords: case.control(
client, subdevice if obj is None else obj, 0x20808159,
params=(table(len(indexes) if count is None else count, indexes)
+ pattern)[:332], **keywords)
bytes159([7, 8])
case.poke("gpu", 0x6d66 + 7, 1, 0x5a)
bytes159([7, 8])
bytes159([8, 7])
bytes159([7])
bytes159([9, 7, 10])
bytes159([7], obj=device)
bytes159([7], file=1)
bytes159([7], flags=4)
bytes159([0x29])
bytes159([7], count=0)
bytes159([7] * 0x29)
bytes159([7], count=0x2a)
case.flush()
bytes159([7])
case.poke("gpu", 0x6d66 + 7, 1, 0)
bytes159([7, 8])
bytes159([8])
case.flush()
# Every index is cached on its own.
bytes159(list(range(0x29)))
for index in range(0x29):
case.poke("gpu", 0x6d66 + index, 1, index + 1)
bytes159(list(range(0x29)))
bytes159([0x28, 0])
case.flush()
bytes159([0x28, 0, 5])
bytes159([4])
for index in range(0x29):
case.poke("gpu", 0x6d66 + index, 1, 0)
bytes159([4, 5])
case.flush()
# Mode word: verify only (2) and disabled (0).
arch(subdevice)
case.poke("gpu", 0xd38, 1, 3)
case.cache(2)
arch(subdevice)
arch(device)
case.cache(0)
arch(subdevice)
arch(device)
case.cache(1)
arch(subdevice)
arch(device)
case.poke("gpu", 0xd38, 1, 0)
case.free(other, 0, other, file=1)
arch(subdevice2, who=other, file=1)
case.free(client, 0, client)
arch(subdevice)
memop(client, client)
cases.append(case)
case = GpuSequence("gpu-slice3b")
case.class_table()
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))
_, subdevice1 = case.alloc(client, device, 0, 0x2080, params=struct.pack("<I", 1))
assert case.alloc(0, 0, 0, 0)[1] == client + 1
other = client + 1
_, device2 = case.alloc(other, other, 0, 0x80, params=device_params(share=other, mode=2))
_, subdevice2 = case.alloc(other, device2, 0, 0x2080, params=bytes(4))
def run(obj, command, size, block=None, who=client, **keywords):
block = pattern[:size] if block is None else block
case.flush()
return case.control(who, obj, command, params=bytes(block) if size else None,
size=size, null_pointer=not size, **keywords)
# 0x801402 NV0080_CTRL_CMD_HOST_GET_CAPS_V2: _nv022229rm -> _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("<I", first) + bytes(108))
run(subdevice, 0x2080182a, 112, block=bytes(4) + pattern[:108])
for index in (0, 5, 12):
case.poke("bif", 0xbf0 + 8 * index, 1, 1)
case.poke("bif", 0xbf4 + 8 * index, 4, 0x11110000 + index)
run(subdevice, 0x2080182a, 112, block=bytes(4) + pattern[:108])
run(subdevice1, 0x2080182a, 112, block=bytes(112))
run(device, 0x2080182a, 112, block=bytes(112))
for index in (0, 5, 12):
case.poke("bif", 0xbf0 + 8 * index, 1, 0)
case.poke("bif", 0xbf4 + 8 * index, 4, 0)
# RC watchdog requests: 0x2080220c (release, operation 0xc) and 0x20802210 (soft
# disable, operation 0xe) -> _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()
assert 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()