Files
nvdriver/tools/check_uvm_gpu_ops2_binary.py
morebrackets 0ba3d54d06 Replace all elidable asserts across RMAPI/UVM binary oracles and test all five main() branches
- Replace all assert statements across check_rmapi_binary.py (34),
  check_rmapi_channel_binary.py (122), check_rmapi_memory_binary.py (33),
  check_uvm_gpu_ops_binary.py (15), and check_uvm_gpu_ops2_binary.py (53)
  with _require() so required calls survive python3 -O.
- Extend test_rmapi_and_uvm_binary_check_mode.py to enforce zero asserts
  across entire files and exercise all five main() entry points for --check
  missing/match/drift, normal write, and --only read-only modes.
2026-12-02 16:29:36 -08:00

1412 lines
66 KiB
Python

#!/usr/bin/env python3
"""Run the original RM side of the UVM interface for the workload's per-context path
(UVM slice 2) and write an oracle for the Rust `uvm::gpu_ops` module.
Executed original code (580.178.04 nv-kernel.o_binary, whole object relocated; loader and
fixtures of tools/check_rmapi_binary.py and tools/rmapi_binary_emulator.py, imported and not
modified). Unlike slice 1 the RM underneath is the original's own: the GPU object is the one
the original constructs for the traced V100 (check_rmapi_binary.gpu_world: core init, probe,
attach, the base PreInit sweep and KernelMemorySystem PreInitLocked), and the client, device,
subdevice and VA space objects are allocated through the original resource server.
The RM API table the entry points obtain from rmapiGetInterface (_nv054239rm) is replaced by
a recording table per interface type. Each slot records the request and then either
* answers from the case ("canned": controls and classes whose handlers need engine state
this fixture cannot produce, named per case), or
* enters the original slot function of the same interface with the same arguments
("real") and records what it returned.
See the functions `*_cases` for what each case constructs, and
analysis/closed-driver-580/uvm.md (section "Slice 2") for the findings.
"""
import hashlib
import json
import struct
import sys
def _require(condition, message=None):
if not condition:
raise AssertionError(message if message is not None else 'check failed')
from unicorn import UC_HOOK_CODE
from unicorn.x86_const import UC_X86_REG_RAX, UC_X86_REG_RSP
import check_rmapi_binary as R
import check_uvm_gpu_ops_binary as S1
from rmapi_binary_emulator import BASES, DIGEST, HEAP, ROOT, STOP
E = R.E
OUT = ROOT / "target/uvm"
SLOT = STOP + 0x200 # 0x40 slots of 8 bytes: one stub address per slot
SLOT_NAMES = {0: "alloc", 3: "free", 7: "control", 10: "dup", 12: "share", 14: "map",
17: "unmap"}
# Stack arguments (beyond the six register arguments) of each slot function.
SLOT_STACK = {0: 1, 3: 0, 7: 0, 10: 1, 12: 0, 14: 2, 17: 1}
CANNED_HANDLE = 0xcc000000
CANNED_MAPPING = 0x7100000000
def sparse(data):
"""`len:off=hex,off=hex` with the zero bytes left out."""
runs, start = [], None
for offset, byte in enumerate(data):
if byte and start is None:
start = offset
if not byte and start is not None:
runs.append((start, offset))
start = None
if start is not None:
runs.append((start, len(data)))
merged = []
for begin, end in runs:
if merged and begin - merged[-1][1] < 4:
merged[-1] = (merged[-1][0], end)
else:
merged.append((begin, end))
return f"{len(data):x}:" + ",".join(f"{begin:x}={data[begin:end].hex()}"
for begin, end in merged)
class Api:
"""The recording RM API. `canned`: {("alloc", class) | command | "map": reply}; a reply
is bytes (status 0), (status, bytes), a status, or a callable of the request bytes.
Requests without an entry run the original slot function."""
def __init__(self):
self.real = {} # interface type -> original table
self.fake = {} # fake table address -> interface type
self.active = False
self.depth = 0
self.lines, self.canned, self.fail, self.count = [], {}, None, 0
self.canned_handles = set()
self.next_canned = 0
self.pointers = {} # kernel pointers seen in parameter blocks -> token
def begin(self, canned=None, fail=None):
self.lines, self.canned, self.fail, self.count = [], dict(canned or {}), fail, 0
def interface(self, a):
"""Fixture of _nv054239rm (rmapiGetInterface): the recording table of that type."""
if not self.active or self.depth:
# Requests of the original's own handlers below a "real" slot are not recorded.
return None
kind = a[0] & 0xffffffff
for table, known in self.fake.items():
if known == kind:
return table
raise AssertionError(f"RM API interface {kind} has no recording table")
def tables(self, kinds):
"""Called once per world, with the recording switched off: learn the original
tables and build the recording ones."""
self.real, self.fake = {}, {}
for kind in kinds:
self.real[kind] = E.call("_nv054239rm", kind)
table = E.allocate(0x200)
for index in range(0x40):
E.wq(table + 8 * index, SLOT + 8 * index)
self.fake[table] = kind
def injected(self):
index = self.count
self.count += 1
if self.fail is not None and self.fail[0] == index:
return self.fail[1]
return None
def enter(self, index, a, after):
"""Run the original slot function with the caller's arguments and resume the caller
with what `after(status)` returns."""
kind = self.fake[a[0]]
target = E.q(self.real[kind] + 8 * index)
rsp = E.cpu.reg_read(UC_X86_REG_RSP)
count = SLOT_STACK[index]
stack = [E.q(rsp + 8 + 8 * number) for number in range(count)]
new = rsp - 8 * count - (8 if count % 2 == 0 else 0) - 0x40
new &= ~0xf
for number, value in enumerate(stack):
E.wq(new + 8 * number, value)
E.cpu.reg_write(UC_X86_REG_RSP, new)
self.depth += 1
def resume(status):
self.depth -= 1
E.cpu.reg_write(UC_X86_REG_RSP, rsp)
return after(status & 0xffffffff)
E.nested(target, [self.real[kind]] + list(a[1:]), resume)
def reply(self, key, request):
reply = self.canned.get(key)
if callable(reply):
reply = reply(request)
return reply
def kind(self, a):
return self.fake[a[0]]
def alloc(self, a):
client, parent, klass = a[1] & 0xffffffff, a[2] & 0xffffffff, a[4] & 0xffffffff
size = E.stack_argument(0) & 0xffffffff
handle_in = E.d(a[3])
params = E.read(a[5], size) if a[5] and size else None
head = (f"call alloc {self.kind(a)} {client:x} {parent:x} {handle_in:x} {klass:x}"
f" {self.block(klass, params) if params is not None else '-'}")
def finish(status, how):
handle_out = E.d(a[3])
out = E.read(a[5], size) if params is not None else None
self.lines.append(f"{head} -> {status:x} {handle_out:x}"
f" {self.block(klass, out) if out is not None else '-'} {how}")
return status
status = self.injected()
if status is not None:
return finish(status, "injected")
reply = self.reply(("alloc", klass), params)
if reply is None:
self.enter(0, a, lambda status: finish(status, "real"))
return None
status, data = reply if isinstance(reply, tuple) else (
(reply, None) if isinstance(reply, int) else (0, reply))
if status == 0:
if handle_in == 0:
self.next_canned += 1
E.wd(a[3], CANNED_HANDLE + self.next_canned)
self.canned_handles.add(E.d(a[3]))
if data is not None:
E.write(a[5], data)
return finish(status, "canned")
def block(self, key, data):
"""Parameter bytes with kernel pointers of the fixture replaced by a token."""
edit = POINTER_FIELDS.get(key)
if edit is None or data is None:
return sparse(data)
data = bytearray(data)
for offset in edit:
value = struct.unpack_from("<Q", data, offset)[0]
struct.pack_into("<Q", data, offset, 0x1000 if value else 0)
return sparse(bytes(data))
def free(self, a):
client, handle = a[1] & 0xffffffff, a[2] & 0xffffffff
head = f"call free {self.kind(a)} {client:x} {handle:x}"
status = self.injected()
if status is not None:
# A failing Free is not modelled: the original ignores the status everywhere
# on these paths, and the object would stay allocated.
status = None
if handle in self.canned_handles:
self.canned_handles.discard(handle)
self.lines.append(f"{head} -> 0 canned")
return 0
def finish(status):
self.lines.append(f"{head} -> {status:x} real")
return status
self.enter(3, a, finish)
return None
def control(self, a):
client, obj, command = a[1] & 0xffffffff, a[2] & 0xffffffff, a[3] & 0xffffffff
size = a[5] & 0xffffffff
params = E.read(a[4], size) if a[4] and size else b""
if command == 0x800201:
return self.class_list(a, client, obj, params)
head = (f"call control {self.kind(a)} {client:x} {obj:x} {command:x}"
f" {self.block(command, params)}")
def finish(status, how):
out = E.read(a[4], size) if size else b""
self.lines.append(f"{head} -> {status:x} {self.block(command, out)} {how}")
return status
status = self.injected()
if status is not None:
return finish(status, "injected")
reply = self.reply(command, params)
if reply is None:
self.enter(7, a, lambda status: finish(status, "real"))
return None
status, data = reply if isinstance(reply, tuple) else (
(reply, None) if isinstance(reply, int) else (0, reply))
if data is not None:
_require(len(data) == size, (hex(command), len(data), size))
E.write(a[4], data)
return finish(status, "canned")
def class_list(self, a, client, obj, params):
"""NV0080_CTRL_CMD_GPU_GET_CLASSLIST: {numClasses, pad, classList pointer}."""
count_in, pointer = struct.unpack("<I4xQ", params)
status = self.injected()
classes = self.canned.get(0x800201, [])
if status is None:
status = 0
E.wd(a[4], len(classes))
if pointer:
E.write(pointer, b"".join(struct.pack("<I", klass) for klass in classes))
listed = ",".join(f"{klass:x}" for klass in classes) if (
pointer and status == 0 and classes) else "-"
self.lines.append(f"call classlist {self.kind(a)} {client:x} {obj:x} {count_in:x}"
f" {1 if pointer else 0} -> {status:x} {E.d(a[4]):x} {listed}")
return status
def dup(self, a):
client, parent = a[1] & 0xffffffff, a[2] & 0xffffffff
source_client, source = a[4] & 0xffffffff, a[5] & 0xffffffff
flags = E.stack_argument(0) & 0xffffffff
handle_in = E.d(a[3])
head = (f"call dup {self.kind(a)} {client:x} {parent:x} {handle_in:x}"
f" {source_client:x} {source:x} {flags:x}")
def finish(status, how):
self.lines.append(f"{head} -> {status:x} {E.d(a[3]):x} {how}")
return status
status = self.injected()
if status is not None:
return finish(status, "injected")
reply = self.reply("dup", (source_client, source))
if reply is None:
self.enter(10, a, lambda status: finish(status, "real"))
return None
if reply == 0:
if handle_in == 0:
self.next_canned += 1
E.wd(a[3], CANNED_HANDLE + self.next_canned)
self.canned_handles.add(E.d(a[3]))
return finish(reply, "canned")
def share(self, a):
head = (f"call share {self.kind(a)} {a[1] & 0xffffffff:x} {a[2] & 0xffffffff:x}"
f" {E.read(a[3], 12).hex()}")
status = self.injected()
if status is not None:
self.lines.append(f"{head} -> {status:x} injected")
return status
def finish(status):
self.lines.append(f"{head} -> {status:x} real")
return status
self.enter(12, a, finish)
return None
def map(self, a):
"""MapToCpu(api, client, device, memory, offset, length, &pointer, flags)."""
client, device, memory = (value & 0xffffffff for value in a[1:4])
offset, length = a[4], a[5]
out, flags = E.stack_argument(0), E.stack_argument(1) & 0xffffffff
head = (f"call map {self.kind(a)} {client:x} {device:x} {memory:x} {offset:x}"
f" {length:x} {flags:x}")
status = self.injected()
how = "injected"
if status is None:
reply = self.reply("map", memory)
_require(reply is not None, "MapToCpu is always answered by the case")
status, how = reply, "canned"
if status == 0:
# A distinct token per mapped object; the original only stores it.
E.wq(out, CANNED_MAPPING + (memory & 0xffff) * 0x100000)
self.lines.append(f"{head} -> {status:x} {1 if status == 0 else 0} {how}")
return status
def unmap(self, a):
"""UnmapFromCpu(api, client, device, memory, pointer, flags, process)."""
client, device, memory = (value & 0xffffffff for value in a[1:4])
self.injected()
self.lines.append(f"call unmap {self.kind(a)} {client:x} {device:x} {memory:x}"
f" {1 if a[4] else 0} {a[5] & 0xffffffff:x} -> 0 canned")
return 0
def other(self, index):
def run(a):
raise AssertionError(f"RM API slot {index:#x} is not part of these paths")
return run
# Parameter-block fields that hold kernel pointers of the fixture: {class or command:
# offsets}. NV0005_ALLOC_PARAMETERS (class 0x7e, 0x18 bytes) carries the callback at +0x10.
POINTER_FIELDS = {0x7e: (0x10,)}
API = Api()
PAGES = {"registered": [], "fail": None}
def register_phys_pages(a):
"""nv_register_phys_pages(nv, addresses, count, cache type, &private)."""
count = a[2]
_require(count < 0x10000, hex(count))
PAGES["registered"].append(("register", [E.q(a[1] + 8 * index) for index in range(count)],
a[3] & 0xffffffff))
if PAGES["fail"] is not None:
return PAGES["fail"]
E.wq(a[4], 0x5150000 + 0x100 * len(PAGES["registered"]))
return 0
def unregister_phys_pages(a):
PAGES["registered"].append(("unregister", a[1]))
return 0
LOCKS = {"fail": None, "count": 0}
def lock_all(a):
"""_nvGpuOpsLocksAcquireWithClientLockFlags(API lock flags, client lock flags, client,
&pClient, number of GPU locks, instance 1, instance 2, &lock set)."""
if not API.active or API.depth:
return None
index = LOCKS["count"]
LOCKS["count"] += 1
head = (f"call lock {a[0] & 0xffffffff:x} {a[1] & 0xffffffff:x} {a[2] & 0xffffffff:x}"
f" {a[4] & 0xffffffff:x}")
if LOCKS["fail"] is not None and LOCKS["fail"][0] == index:
API.lines.append(f"{head} -> {LOCKS['fail'][1]:x} injected")
return LOCKS["fail"][1]
API.lines.append(f"{head} -> 0 real")
return None
def unlock_all(a):
if API.active and not API.depth:
API.lines.append("call unlock -> 0 real")
return None
FAKE_MEMORY = {}
def memory_lookup(a):
"""memGetByHandle (_nv043666rm): the fixture Memory object of a handle the case made,
whichever client asks (the duplicate keeps the handle of the original here)."""
handle = a[1] & 0xffffffff
if handle in FAKE_MEMORY:
E.wq(a[2], FAKE_MEMORY[handle])
return 0
return None
GID = {"status": 0, "uuid": bytes(range(0xc0, 0xd0))}
def gid_info(a):
"""gpuGetGidInfo (_nv030562rm): the GPU's SHA-1 UUID in binary form. The original
derives it from identity data this fixture does not hold, so the case supplies it."""
if not API.active:
return None
if GID["status"] == 0:
buffer = E.allocate(16)
E.write(buffer, GID["uuid"])
E.wq(a[1], buffer)
E.wd(a[2], 16)
return GID["status"]
def install():
"""Install every replacement before any original instruction runs (hooks added to
already translated code do not fire); `API.active` switches the RM API table."""
handlers = {0: API.alloc, 3: API.free, 7: API.control, 10: API.dup, 12: API.share,
14: API.map, 17: API.unmap}
for index in range(0x40):
E.install(SLOT + 8 * index, handlers.get(index, API.other(index)))
E.install("_nv054239rm", API.interface)
E.handlers.pop("_nv054239rm")
E.install("nv_register_phys_pages", register_phys_pages)
E.install("nv_unregister_phys_pages", unregister_phys_pages)
# _nvGpuOpsLocksAcquire (_nv014211rm) and _nvGpuOpsLocksRelease (_nv014212rm): observed,
# and the acquisition can be made to fail by the case.
E.install("_nv014211rm", lock_all)
E.handlers.pop("_nv014211rm")
E.install("_nv014212rm", unlock_all)
E.handlers.pop("_nv014212rm")
E.install("_nv043666rm", memory_lookup)
E.handlers.pop("_nv043666rm")
E.install("_nv030562rm", gid_info)
E.handlers.pop("_nv030562rm")
def runtime_stack():
"""nvidia_stack_t as the thunks use it: the RM stack top at +8."""
stack = E.allocate(0x100)
area = E.allocate(0x20000)
E.wq(stack + 8, area + 0x18000)
return stack
class World:
"""One constructed GPU with a user client (device of VA mode 2 as libcuda makes it,
subdevice) and a UVM session, all made by the original. `snapshot` and `restore` let
many cases start from the same state."""
USER = 0xc1d00001
def __init__(self, name):
API.active = False
self.case = R.GpuSequence(name)
case = self.case
self.gpu = case.gpu
_require(case.alloc(0, 0, 0, 0)[1] == self.USER)
case.initialized(1)
good = R.device_params(share=self.USER, mode=2)
result, self.device = case.alloc(self.USER, self.USER, 0, 0x80, params=good)
_require(result == 0)
result, self.subdevice = case.alloc(self.USER, self.device, 0, 0x2080, params=bytes(4))
_require(result == 0)
_require(case.sweep() == 0)
case.stage("kms-preinit")
# Data symbols of the open layer (os-interface.c): 4 KiB pages.
E.wq(E.externals["os_page_size"], 0x1000)
E.wq(E.externals["os_page_shift"], 12)
E.wq(E.externals["os_page_mask"], 0xfffffffffffff000)
API.tables((1, 2, 3, 4, 5))
self.stack = runtime_stack()
out = E.allocate(16)
_require(self.call("rm_gpu_ops_create_session", out) == 0)
self.session = E.q(out)
self.session_client = E.d(self.session)
self.saved = None
UUID = bytes(range(0xc0, 0xd0))
def describe(self):
"""What the Rust model of this world needs: the GPU properties the entry points
read (architecture GPU+0xd00, implementation +0xd04, id +0xca4, zero-FB property
+0x92b, virtual +0xe00, SR-IOV +0x4de7 and heavy +0x52f9, MIG manager +0x1fc8),
the session client and the user's client, device and subdevice."""
gpu = self.gpu
return (f"world {E.d(gpu + 0xd00):x} {E.d(gpu + 0xd04):x} {E.d(gpu + 0xca4):x}"
f" {E.b(gpu + 0x92b)} {E.b(gpu + 0xe00)} {E.b(gpu + 0x4de7)}"
f" {E.b(gpu + 0x52f9)} {1 if E.q(gpu + 0x1fc8) else 0}"
f" {self.session_client:x} {self.USER:x} {self.device:x} {self.subdevice:x}")
def snapshot(self):
self.saved = dict(
sections={name: E.read(BASES[name], len(E.pristine[name]))
for name in (".data", ".bss")},
heap=E.read(HEAP, E.heap - HEAP), top=E.heap,
state={key: (list(value) if isinstance(value, list) else
dict(value) if isinstance(value, dict) else value)
for key, value in R.state.items()},
gpu_state={key: (list(value) if isinstance(value, list) else
dict(value) if isinstance(value, dict) else value)
for key, value in R.gpu_state.items()},
api=(set(API.canned_handles), API.next_canned),
externals=E.read(E.externals["os_page_size"] & ~0xfff, 0x1000))
def restore(self):
saved = self.saved
for name, content in saved["sections"].items():
E.write(BASES[name], content)
E.write(HEAP, saved["heap"])
E.heap = saved["top"]
for target, source in ((R.state, saved["state"]), (R.gpu_state, saved["gpu_state"])):
for key, value in source.items():
target[key] = (list(value) if isinstance(value, list) else
dict(value) if isinstance(value, dict) else value)
API.canned_handles, API.next_canned = set(saved["api"][0]), saved["api"][1]
PAGES["registered"], PAGES["fail"] = [], None
LOCKS["fail"] = None
FAKE_MEMORY.clear()
GID["status"] = 0
def user_alloc(self, parent, klass, params):
return self.case.alloc(self.USER, parent, 0, klass, params=params)
def vaspace(self, flags=0x48, base=0x1000, parent=None, **fields):
result, handle = self.user_alloc(parent or self.device, 0x90f1,
R.vaspace_params(flags=flags, base=base, **fields))
_require(result == 0, hex(result))
return handle
def call(self, name, *arguments, canned=None, fail=None, lock_fail=None):
API.begin(canned, fail)
LOCKS["fail"], LOCKS["count"] = lock_fail, 0
R.state["diag"].clear()
R.gpu_state["read"].clear()
R.gpu_state["written"].clear()
API.active, API.depth = True, 0
# A register an entry point reads enters the case with its first value in the
# physical transcript of the traced V100; writes are recorded, not applied.
# The flush registers (0x70004..0x70010) are not in the transcript: they read as
# idle (0).
R.gpu_state["source"] = dict(R.first_reads())
R.gpu_state["source"].update({0x70004: 0, 0x70008: 0, 0x7000c: 0, 0x70010: 0})
for offset in (0x70004, 0x70008, 0x7000c, 0x70010):
R.gpu_state["registers"].pop(offset, None)
try:
full = (self.stack,) + arguments
return E.call(name, *full[:6], stack=full[6:]) & 0xffffffff
finally:
API.active = False
R.gpu_state["source"] = None
def footer(self):
"""Register accesses and assertion records of the last call."""
reads = ",".join(f"{offset:x}={R.gpu_state['registers'][offset]:x}"
for offset in R.gpu_state["read"]) or "-"
writes = ",".join(f"{offset:x}={value:x}" for offset, value in
R.gpu_state["written"]) or "-"
return [f"registers {reads} {writes}", "asserts " + (",".join(R.state["diag"]) or "-")]
# ---------------------------------------------------------------------------------------
# rm_gpu_ops_device_create -> _nv046795rm (nvGpuOpsDeviceCreate) and
# rm_gpu_ops_device_destroy -> _nv046796rm.
def fb_info_reply(heap_size, reserved, broken, heap_start):
def run(params):
reply = bytearray(params)
for index, value in enumerate((heap_size, reserved, broken, heap_start)):
struct.pack_into("<I", reply, 8 + 8 * index, value)
return bytes(reply)
return run
def fb_regions(limits):
"""NV2080_CTRL_CMD_FB_GET_FB_REGION_INFO reply (0x388 bytes): count, then 0x38-byte
regions from +8 with the limit at +8 of each."""
reply = bytearray(0x388)
struct.pack_into("<I", reply, 0, len(limits))
for index, limit in enumerate(limits):
struct.pack_into("<QQ", reply, 8 + 0x38 * index, 0x1000 * index, limit)
return bytes(reply)
def ecc_status(units):
"""NV2080_CTRL_CMD_GPU_QUERY_ECC_STATUS reply (0x5b8 bytes): 36 units of 0x28 bytes,
`enabled` at +0 and `supported` at +2 of each. `units`: index -> (enabled, supported)."""
reply = bytearray(0x5b8)
for index, (enabled, supported) in units.items():
reply[0x28 * index] = enabled
reply[0x28 * index + 2] = supported
return bytes(reply)
def device_canned(ecc=None, nvlink=bytes(0x30), classes=None):
canned = {
0x274: S1.uuid_info(0, 0),
("alloc", 0xc361): 0, "map": lambda memory: 0,
0x2080012f: 0x56 if ecc is None else ecc,
0x20803001: nvlink,
("alloc", 0x90e6): 0,
0x90e60101: struct.pack("<IIII", 0x100, 0x40000000, 0, 0x00400000),
("alloc", 0x7e): 0,
0x20800301: 0,
0x20801303: fb_info_reply(0x7f7c00, 0x200, 0, 0x40),
0x20801320: fb_regions((0x7fbffffff, 0x7ffffffff, 0x1fffffff)),
0x20800188: struct.pack("<Q", 0x200000),
0x20801354: struct.pack("<BB6xQQ", 0, 0, 0, 0),
0x800201: list(S1.V100_CLASSES if classes is None else classes),
}
return canned
V100_ECC = ecc_status({0: (1, 1), 1: (1, 1), 5: (0, 0)})
def device_summary(device):
"""The fields of struct gpuDevice (0x1a0 bytes), its deviceDesc (0x60) and
subDeviceDesc (0xd8) that later entry points read."""
words = lambda base, layout: " ".join(
f"{int.from_bytes(E.read(base + offset, size), 'little'):x}" for offset, size in layout)
rm_device, rm_subdevice = E.q(device), E.q(device + 8)
text = words(device, ((0x10, 4), (0x14, 4), (0x18, 4), (0x1c, 4), (0x20, 4), (0x24, 4),
(0x28, 4), (0x2c, 4), (0x30, 4), (0x34, 4), (0x38, 4), (0x3c, 1),
(0x3d, 1), (0x3e, 1), (0x48, 8), (0x50, 4), (0x54, 4), (0x58, 1),
(0x60, 8), (0x68, 1), (0x69, 1), (0x70, 8), (0x78, 8), (0x80, 4)))
text += f" {1 if E.q(device + 0x198) else 0} | "
text += words(rm_device, ((0x40, 4), (0x50, 4), (0x54, 4), (0x58, 4), (0x5c, 4)))
mapped = lambda offset: 1 if E.q(rm_subdevice + offset) else 0
text += " | " + words(rm_subdevice, ((0x38, 4), (0x40, 8), (0x58, 4), (0x5c, 4)))
text += f" {mapped(0x60)} " + words(rm_subdevice, ((0x68, 4), (0x6c, 4), (0x70, 1),
(0x71, 1), (0x88, 4), (0x8c, 4)))
text += f" {mapped(0x90)} " + words(rm_subdevice, ((0x98, 4), (0x9c, 4), (0xa0, 1),
(0xa1, 1), (0xb8, 4)))
text += f" {mapped(0xc0)}"
return text
def gpu_info_block(smc_enabled=0, swizz=0, user_client=(0, 0), fill=0):
"""UvmGpuInfo as the caller passes it to device_create: only smcEnabled (+0x88),
smcSwizzId (+0x8c) and smcUserClientInfo (+0x90, +0x94) are read; the whole block is
copied into the device."""
block = bytearray([fill]) * H_INFO_SIZE
block[0x88] = smc_enabled
struct.pack_into("<I", block, 0x8c, swizz)
struct.pack_into("<II", block, 0x90, *user_client)
return bytes(block)
H_INFO_SIZE = 0xf0
class Runner:
"""Collects the record lines of the cases run on one world."""
def __init__(self, world):
self.world = world
self.lines = []
self.cases = 0
self.calls = 0
def begin(self, name, *extra):
self.world.restore()
self.lines.append(f"case {name}")
self.lines.append(self.world.describe())
self.lines.extend(extra)
self.cases += 1
self.devices, self.spaces = [], []
def note(self, text):
self.lines.append(text)
def user_vaspace(self, flags=0x48, base=0x1000, parent=None, **fields):
"""A VA space of the user's client, allocated by the original (0x48 = externally
owned + page faulting, what libcuda asks for its channel address space), and the
line the Rust model reads: client, handle, class, parent, parent class, device
instance of the parent, externally owned, ATS."""
world = self.world
handle = world.vaspace(flags=flags, base=base, parent=parent, **fields)
self.note(f"object {world.USER:x} {handle:x} vaspace {parent or world.device:x}"
f" {'subdevice' if parent == world.subdevice else 'device'} 0"
f" {1 if flags & 8 else 0} 0")
return handle
def standard_device(self, **keywords):
status, device, _ = self.device_create(device_canned(ecc=V100_ECC), **keywords)
_require(status == 0)
return device
def space_result(self, status, out, info):
space = E.q(out)
block = E.read(info, 0x30).hex()
if status != 0:
_require(space == 0, hex(space))
return f"- - - {block}"
self.spaces.append(space)
return f"{E.d(space):x} {E.q(space + 0x40):x} {E.q(space + 0x48):x} {block}"
def dup_address_space(self, device, client, handle, fail=None, fifo=64):
out, info = E.allocate(16, 0xa5), E.allocate(0x30, 0xa5)
status = self.world.call("rm_gpu_ops_dup_address_space", device, client, handle, out,
info, canned={0x20801109: fifo_info(fifo)}, fail=fail)
self.op(f"dup_address_space {self.devices.index(device)} {client:x} {handle:x}",
status, self.space_result(status, out, info))
return status
def address_space_create(self, device, base, size, ats, fail=None):
out, info = E.allocate(16, 0xa5), E.allocate(0x30, 0xa5)
status = self.world.call("rm_gpu_ops_address_space_create", device, base, size, ats,
out, info, canned={0x20801109: fifo_info(64)}, fail=fail)
if status != 0 and E.q(out) == 0xa5a5a5a5a5a5a5a5:
# The enable-ATS argument check returns before the outputs are cleared.
E.wq(out, 0)
self.op(f"address_space_create {self.devices.index(device)} {base:x} {size:x} {ats}",
status, self.space_result(status, out, info))
return status
def address_space_destroy(self, space):
index = self.spaces.index(space)
status = self.world.call("rm_gpu_ops_address_space_destroy", space, canned={})
self.op(f"address_space_destroy {index}", status)
def set_page_directory(self, space, address, entries, video, pasid=0xffffffff, fail=None,
lock_fail=None, pages_fail=None):
dma = E.allocate(8, 0xa5)
PAGES["registered"], PAGES["fail"] = [], pages_fail
status = self.world.call("rm_gpu_ops_set_page_directory", space, address, entries,
video, pasid, dma, canned={}, fail=fail, lock_fail=lock_fail)
registered = ";".join(
f"{entry[0]}:" + ",".join(f"{page:x}" for page in entry[1]) if entry[0] == "register"
else "unregister" for entry in PAGES["registered"]) or "-"
self.op(f"set_page_directory {self.spaces.index(space)} {address:x} {entries:x} {video}"
f" {pasid:x}", status, f"{E.q(dma):x} {registered}")
return status
def unset_page_directory(self, space, fail=None, lock_fail=None):
PAGES["registered"] = []
status = self.world.call("rm_gpu_ops_unset_page_directory", space, canned={},
fail=fail, lock_fail=lock_fail)
registered = ";".join(entry[0] for entry in PAGES["registered"]) or "-"
self.op(f"unset_page_directory {self.spaces.index(space)}", status, registered)
return status
def op(self, text, status, result=""):
self.lines.append(f"op {text}")
self.lines.extend(API.lines)
self.calls += len(API.lines)
self.lines.append(f"ret {status:x} {result}".rstrip())
self.lines.extend(self.world.footer())
def device_create(self, canned, fail=None, info=None, smc=0, uuid=None):
world = self.world
info = gpu_info_block() if info is None else info
uuid = uuid or bytes(range(0x10, 0x20))
block, pointer, out = E.allocate(H_INFO_SIZE), E.allocate(16), E.allocate(16, 0xa5)
E.write(block, info)
E.write(pointer, uuid)
status = world.call("rm_gpu_ops_device_create", world.session, block, pointer, out, smc,
canned=canned, fail=fail)
device = E.q(out)
if status == 0:
summary = device_summary(device)
self.devices.append(device)
else:
_require(device == 0xa5a5a5a5a5a5a5a5, hex(device))
summary, device = "-", None
failing = "-" if fail is None else f"{fail[0]:x}:{fail[1]:x}"
self.op(f"device_create {uuid.hex()} {smc} {sparse(info)} {failing}", status, summary)
return status, device, len(API.lines)
def device_destroy(self, device, canned):
status = self.world.call("rm_gpu_ops_device_destroy", device, canned=canned)
self.op("device_destroy", status)
return status
def device_cases(world):
run = Runner(world)
default = device_canned(ecc=V100_ECC)
# The V100 path: ECC enabled on every supported unit, NVLink without the uncontained
# error recovery capability.
run.begin("device-v100")
status, device, calls = run.device_create(default)
_require(status == 0)
run.device_destroy(device, default)
# Every RM API call of that path failing in turn (0x56 has a rule of its own for the ECC
# status query).
for index in range(calls):
for failure in (0x65, 0x56):
run.begin(f"device-fail-{index}-{failure:x}")
status, device, _ = run.device_create(default, fail=(index, failure))
if status == 0:
run.device_destroy(device, default)
# ECC variants.
for label, ecc in (("not-supported", 0x56), ("error", (0x65, bytes(0x5b8))),
("no-unit", ecc_status({})),
("unit-disabled", ecc_status({0: (1, 1), 7: (0, 1)})),
("unsupported-enabled", ecc_status({3: (1, 0)})),
("last-unit", ecc_status({35: (1, 1)})),
("last-unit-off", ecc_status({0: (1, 1), 35: (0, 1)}))):
run.begin(f"device-ecc-{label}")
canned = device_canned(ecc=ecc)
status, device, _ = run.device_create(canned)
if status == 0:
run.device_destroy(device, canned)
# NVLink capability bytes: SUPPORTED is bit 0 of byte 0, UNCONTAINED_ERROR_RECOVERY
# bit 5 of byte 1. With recovery the interrupt-tree object of ECC is reused, or one is
# allocated when ECC is off.
recovery = bytes([1, 0x20]) + bytes(0x2e)
for label, caps, ecc in (("unsupported", bytes([0, 0x20]) + bytes(0x2e), V100_ECC),
("no-recovery", bytes([0xff, 0xdf]) + bytes([0xff]) * 0x2e, V100_ECC),
("error", (0x56, bytes(0x30)), V100_ECC),
("recovery", recovery, V100_ECC),
("recovery-no-ecc", recovery, None)):
run.begin(f"device-nvlink-{label}")
canned = device_canned(ecc=ecc, nvlink=caps)
status, device, calls = run.device_create(canned)
if status == 0:
run.device_destroy(device, canned)
for ecc in (V100_ECC, None):
canned = device_canned(ecc=ecc, nvlink=recovery)
probe = Runner(world)
probe.begin("probe")
_, _, calls = probe.device_create(canned)
for index in range(calls):
run.begin(f"device-nvlink-fail-{1 if ecc else 0}-{index}")
status, device, _ = run.device_create(canned, fail=(index, 0x65))
if status == 0:
run.device_destroy(device, canned)
# Framebuffer information: the largest region limit, the zero-FB property.
for label, edit in (("no-region", {0x20801320: fb_regions(())}),
("one-region", {0x20801320: fb_regions((0x123456789abc,))}),
("descending", {0x20801320: fb_regions((9, 8, 7, 6))}),
("values", {0x20801303: fb_info_reply(0xffffffff, 0x12345678, 0x101, 7),
0x20800188: struct.pack("<Q", 0x123456789abcdef0),
0x20801354: struct.pack("<BB6xQQ", 1, 1, 0x1000, 0x2000)}),
("bar1-flags", {0x20801354: struct.pack("<BB6xQQ", 0, 2, 1, 2)})):
run.begin(f"device-fb-{label}")
canned = device_canned(ecc=V100_ECC)
canned.update(edit)
status, device, _ = run.device_create(canned)
_require(status == 0)
run.device_destroy(device, canned)
run.begin("device-zero-fb", "poke gpu 92b 1")
E.wb(world.gpu + 0x92b, 1)
status, device, _ = run.device_create(default)
_require(status == 0)
run.device_destroy(device, default)
# Class lists reach the device through findDeviceClasses.
for label, classes in (("none", []), ("pascal", [0xc06f, 0xc0b5, 0xc0c0, 0xb069]),
("all", sorted(set(S1.PUBLIC_CLASSES) | set(S1.V100_CLASSES)))):
run.begin(f"device-classes-{label}")
canned = device_canned(ecc=V100_ECC, classes=classes)
status, device, _ = run.device_create(canned)
if status == 0:
run.device_destroy(device, canned)
# A second device of the same GPU shares the RM device and subdevice; each create maps
# the usermode region and initializes ECC and NVLink again.
for order in ((0, 1), (1, 0)):
run.begin(f"device-twice-{order[0]}{order[1]}")
devices = []
for _ in range(2):
status, device, _ = run.device_create(default)
_require(status == 0)
devices.append(device)
for index in order:
run.device_destroy(devices[index], default)
run.begin("device-twice-second-fails")
status, first, _ = run.device_create(default)
status, second, _ = run.device_create(default, fail=(3, 0x65))
_require(status != 0)
run.device_destroy(first, default)
# SMC: a GPU reported with SMC enabled gets no usermode region; a partition request on
# a GPU without MIG is refused after the device exists.
run.begin("device-smc-enabled-info")
status, device, _ = run.device_create(default, info=gpu_info_block(smc_enabled=1, swizz=5))
_require(status == 0)
run.device_destroy(device, default)
for label, info in (("no-smc", gpu_info_block()),
("no-mig", gpu_info_block(smc_enabled=1, swizz=3, user_client=(1, 2)))):
run.begin(f"device-partition-{label}")
status, device, _ = run.device_create(default, info=info, smc=1)
_require(status != 0)
run.begin("device-info-copied")
status, device, _ = run.device_create(default, info=gpu_info_block(fill=0x5a)[:0x88]
+ bytes(0x10) + bytes([0x5a]) * 0x58,
uuid=bytes(range(0xf0, 0x100)))
_require(status == 0)
run.device_destroy(device, default)
return run
# ---------------------------------------------------------------------------------------
# Address spaces: rm_gpu_ops_dup_address_space -> _nv046800rm, address_space_create ->
# _nv046771rm (both with getAddressSpaceInfo _nv029315rm), address_space_destroy ->
# _nv046772rm, set_page_directory -> _nv046861rm, unset_page_directory -> _nv046867rm.
# The VA space objects, DupObject and the controls 0x801806, 0x801813 and 0x801814 are the
# original's; only NV2080_CTRL_CMD_FIFO_GET_INFO (0x20801109) is answered by the case.
def fifo_info(count):
def run(params):
return params[:8] + struct.pack("<I", count) + params[12:]
return run
def address_space_cases(world):
run = Runner(world)
user = world.USER
def start(name, *extra, **keywords):
run.begin(name, *extra)
external = run.user_vaspace()
device = run.standard_device(**keywords)
return device, external
# The workload's sequence: duplicate the channel address space, commit a directory
# (video memory as stock UVM, system memory as option B), revoke, destroy.
for video in (1, 0):
device, external = start(f"as-workload-{'video' if video else 'system'}")
_require(run.dup_address_space(device, user, external) == 0)
space = run.spaces[0]
_require(run.set_page_directory(space, 0x7fe345000, 4, video) == 0)
_require(run.set_page_directory(space, 0x7fe346000, 4, video) == 0x56)
_require(run.unset_page_directory(space) == 0)
_require(run.set_page_directory(space, 0x7fe346000, 4, video) == 0)
_require(run.unset_page_directory(space) == 0)
run.unset_page_directory(space)
run.address_space_destroy(space)
run.device_destroy(device, device_canned(ecc=V100_ECC))
# Every RM API call of the duplication failing in turn; the sub-context count is
# stored whatever the status of its query.
for index in range(3):
for failure in (0x65, 0x56):
device, external = start(f"as-dup-fail-{index}-{failure:x}")
run.dup_address_space(device, user, external, fail=(index, failure))
device, external = start("as-dup-fifo-values")
for count in (0, 1, 0xffffffff):
_require(run.dup_address_space(device, user, external, fifo=count) == 0)
# What is refused: a space RM manages itself, a handle of another class, unknown
# handles and clients, a space of another device.
device, external = start("as-dup-managed")
managed = run.user_vaspace(flags=0, base=0x5000000)
fault_capable = run.user_vaspace(flags=0x40 | 8, base=0x200000)
_require(run.dup_address_space(device, user, managed) == 0x29)
_require(run.dup_address_space(device, user, fault_capable) == 0)
device, external = start("as-dup-not-a-space")
run.note(f"object {user:x} {world.device:x} device {user:x} client - 0 0")
run.note(f"object {user:x} {world.subdevice:x} subdevice {world.device:x} device 0 0 0")
run.note(f"object {user:x} {user:x} client 0 client - 0 0")
for handle in (world.device, world.subdevice, user, 0x777, 0):
run.dup_address_space(device, user, handle)
run.dup_address_space(device, 0xc1d00077, external)
run.dup_address_space(device, world.session_client, external)
device, external = start("as-dup-other-device", "poke device 0 18 1")
E.wd(device + 0x18, 1)
_require(run.dup_address_space(device, user, external) == 0x5a)
# Without a usermode region (a GPU reported with SMC enabled) the timer words are
# offsets from a null mapping.
device, external = start("as-dup-no-usermode", info=gpu_info_block(smc_enabled=1))
_require(run.dup_address_space(device, user, external) == 0)
# Two duplicates of one space share its directory; two spaces do not.
device, external = start("as-dup-twice")
other = run.user_vaspace(base=0x2000)
for handle in (external, external, other):
_require(run.dup_address_space(device, user, handle) == 0)
first, second, third = run.spaces
_require(run.set_page_directory(first, 0x1000000, 4, 1) == 0)
_require(run.set_page_directory(second, 0x2000000, 4, 1) == 0x56)
_require(run.set_page_directory(third, 0x2000000, 4, 0) == 0)
_require(run.unset_page_directory(second) == 0)
_require(run.set_page_directory(second, 0x3000000, 4, 1) == 0)
for space in (first, second, third):
run.address_space_destroy(space)
# Directory arguments. The entry point refuses a zero entry count itself; everything
# else is the control's answer (root format: 4 entries of 8 bytes covering 2^47 each).
for video in (1, 0):
label = "video" if video else "system"
for entries in (0, 1, 2, 3, 4, 5, 8, 0x200, 0xffffffff):
device, external = start(f"as-set-entries-{label}-{entries:x}")
run.dup_address_space(device, user, external)
if run.set_page_directory(run.spaces[0], 0x7fe345000, entries, video) == 0:
run.unset_page_directory(run.spaces[0])
for address in (0, 0xfff, 0x7fe345678, 0x7fe345800, 1 << 40, (1 << 64) - 0x1000):
device, external = start(f"as-set-address-{label}-{address:x}")
run.dup_address_space(device, user, external)
if run.set_page_directory(run.spaces[0], address, 4, video) == 0:
run.unset_page_directory(run.spaces[0])
for pasid in (0, 5, 0xfffff):
device, external = start(f"as-set-pasid-{label}-{pasid:x}")
run.dup_address_space(device, user, external)
run.set_page_directory(run.spaces[0], 0x7fe345000, 4, video, pasid=pasid)
for video in (1, 2, 0x100, 0xff):
device, external = start(f"as-set-aperture-flag-{video:x}")
run.dup_address_space(device, user, external)
run.set_page_directory(run.spaces[0], 0x7fe345000, 4, video)
# Failures: the control, the locks, the registration of the system-memory page.
for failure in (0x65, 0x56):
device, external = start(f"as-set-fail-{failure:x}")
run.dup_address_space(device, user, external)
space = run.spaces[0]
_require(run.set_page_directory(space, 0x7fe345000, 4, 1, fail=(0, failure)) == failure)
_require(run.set_page_directory(space, 0x7fe345000, 4, 1) == 0)
_require(run.unset_page_directory(space, fail=(0, failure)) == failure)
_require(run.unset_page_directory(space) == 0)
device, external = start("as-set-lock-fails")
run.dup_address_space(device, user, external)
space = run.spaces[0]
_require(run.set_page_directory(space, 0x7fe345000, 4, 1, lock_fail=(0, 0x2f)) == 0x2f)
_require(run.set_page_directory(space, 0x7fe345000, 4, 1) == 0)
_require(run.unset_page_directory(space, lock_fail=(0, 0x2f)) == 0x2f)
_require(run.unset_page_directory(space) == 0)
device, external = start("as-set-system-registration-fails")
run.dup_address_space(device, user, external)
run.set_page_directory(run.spaces[0], 0x7fe345000, 4, 0, pages_fail=0x51)
run.set_page_directory(run.spaces[0], 0x7fe345000, 4, 0)
# A space that is destroyed with its directory still committed.
device, external = start("as-destroy-committed")
run.dup_address_space(device, user, external)
run.set_page_directory(run.spaces[0], 0x7fe345000, 4, 1)
run.address_space_destroy(run.spaces[0])
run.dup_address_space(device, user, external)
run.set_page_directory(run.spaces[1], 0x7fe345000, 4, 1)
# Address spaces UVM creates for itself. Without a size RM manages the space and the
# directory controls refuse it; with a size it is under shared management, whose
# directory commit needs page-table memory this fixture does not have (recorded as
# the original answered here, not a statement about a running GPU).
for label, base, size, ats in (("default", 0, 0, 0), ("128tb", 0, 1 << 47, 0),
("base", 0x200000, 1 << 40, 0), ("ats", 0, 1 << 47, 1),
("ats-no-size", 0, 0, 1), ("too-large", 0, 1 << 50, 0)):
device, external = start(f"as-create-{label}")
if run.address_space_create(device, base, size, ats) == 0:
space = run.spaces[0]
run.note("fixture-limited")
run.set_page_directory(space, 0x7fe345000, 4, 1)
run.unset_page_directory(space)
run.address_space_destroy(space)
for index in range(3):
device, external = start(f"as-create-fail-{index}")
run.address_space_create(device, 0, 1 << 47, 0, fail=(index, 0x65))
return run
# ---------------------------------------------------------------------------------------
# Memory: rm_gpu_ops_dup_memory -> _nv046802rm -> _nv026760rm (dupMemory),
# free_duped_handle -> _nv046808rm, get_external_alloc_ptes -> _nv046815rm -> _nv046816rm
# -> _nv046777rm (nvGpuOpsBuildExternalAllocPtes).
#
# No memory class can be allocated in this fixture (no heap, no page allocator), so the
# Memory object behind a handle is fixture memory: the lookup memGetByHandle (_nv043666rm)
# returns it, and DupObject is answered by the case. Its memory descriptor is the
# original's: memdescCreate (_nv043694rm), memdescDescribe (_nv043698rm) or a page array
# written into the descriptor, memdescSetPageSize (_nv043765rm), memdescSetPteKindForGpu
# (_nv043768rm), with the GPU cache attribute poked at +0x74. Everything the entry points
# compute from it (page size, addresses, PTE bytes, cache flush) is original code.
MEMDESC_READ_ONLY = 1 << 33
MEMDESC_ENCRYPTED = 1 << 11
MEMDESC_PRIVILEGED = 1 << 13
MEMDESC_SYSCOH_OVER_BAR1 = 1 << 39
def no_class():
"""An NVOC run-time type that casts to nothing: {class definition, destructor, offset}
with an empty cast list."""
rtti, definition, casts = E.allocate(0x20), E.allocate(0x40), E.allocate(0x10)
E.wq(rtti, definition)
E.wd(definition + 4, 0x7e57c1a5)
E.wq(definition + 0x18, casts)
return rtti
_pte_array = {}
def pte_array_offset(world):
if "offset" not in _pte_array:
out, marker = E.allocate(8), 0x5a17e5a17000
_require(E.call("_nv043694rm", out, world.gpu, 0x1000, 0, 1, 2,
stack=(0, 0)) & 0xffffffff == 0)
E.call("_nv043698rm", E.q(out), 2, marker, 0x1000)
_pte_array["offset"] = E.read(E.q(out), 0x200).index(struct.pack("<Q", marker))
return _pte_array["offset"]
def fixture_memory(run, handle, space, base, size, page=0x1000, contiguous=True, cached=True,
flags=0, kind=0, parent="device", pages=None, gpu=True):
"""A Memory object for `handle` and its `memory` line: handle, address space (1 system,
2 video), base or page list, size, GPU page size (0 = not set), contiguous, GPU cache
attribute cached, descriptor flags, PTE kind, parent class, owned by the GPU."""
world = run.world
out = E.allocate(8)
# memdescCreate(&descriptor, gpu, size, alignment, contiguous, address space, CPU cache
# attribute, flags): the last two arguments are on the stack.
status = E.call("_nv043694rm", out, world.gpu if gpu else 0, size, 0, 1 if contiguous else 0,
space, stack=(0, flags)) & 0xffffffff
_require(status == 0, hex(status))
descriptor = E.q(out)
if contiguous:
E.call("_nv043698rm", descriptor, space, base, size)
pages = [base]
else:
# The page array at the end of the descriptor (its offset is found by describing a
# contiguous descriptor and looking for the base).
E.write(descriptor + pte_array_offset(world),
b"".join(struct.pack("<Q", page_address) for page_address in pages))
if page:
E.call("_nv043765rm", descriptor, 1, page)
if kind:
E.call("_nv043768rm", descriptor, world.gpu, kind)
E.wd(descriptor + 0x74, 0 if cached else 1)
reference = E.allocate(16)
target = {"device": world.device, "subdevice": world.subdevice, "client": world.USER}[parent]
_require(E.call("_nv056387rm", world.USER, target, reference) & 0xffffffff == 0)
memory, first, second = E.allocate(0x400), E.allocate(0x100), E.allocate(0x100)
E.wq(memory, no_class())
E.wq(memory + 0xb8, first)
E.wq(first + 0x48, second)
E.wq(second + 0x18, E.q(reference))
E.wq(memory + 0x118, descriptor)
FAKE_MEMORY[handle] = memory
run.note(f"memory {handle:x} {space} {','.join(f'{address:x}' for address in pages)}"
f" {size:x} {page:x} {1 if contiguous else 0} {1 if cached else 0} {flags:x}"
f" {kind:x} {parent} {1 if gpu else 0}")
return descriptor
def mapping_info(caching=0, mapping=0, buffer_size=0x200, page_size=0, format_type=0,
element_bits=0, compression=0):
"""UvmGpuExternalMappingInfo (0x48 bytes) with a PTE buffer of `buffer_size` bytes."""
info, buffer = E.allocate(0x48), E.allocate(buffer_size + 16, 0xa5)
E.write(info, struct.pack("<IIIII4xQQQQQI", caching, mapping, format_type, element_bits,
compression, buffer_size, page_size, buffer, 0xa5a5a5a5a5a5a5a5,
0xa5a5a5a5a5a5a5a5, 0xa5a5a5a5) + b"\xa5\xa5\xa5\xa5")
return info, buffer
def pte_result(info, buffer, buffer_size):
written, remaining, pte_size, flush = struct.unpack_from("<QQIB", E.read(info, 0x48), 0x30)
return (f"{written:x} {remaining:x} {pte_size:x} {flush:x}"
f" {E.read(buffer, buffer_size + 16).hex()}")
def memory_cases(world):
run = Runner(world)
user = world.USER
hooks = {symbol: E.install(symbol, handler) for symbol, handler in R.STAGE_FIXTURES.items()}
def start(name):
run.begin(name)
external = run.user_vaspace()
device = run.standard_device()
_require(run.dup_address_space(device, user, external) == 0)
return device, run.spaces[0]
def ptes(space, handle, offset, size, buffer_size=0x200, **fields):
info, buffer = mapping_info(buffer_size=buffer_size, **fields)
status = world.call("rm_gpu_ops_get_external_alloc_ptes", space, handle, offset, size,
info, canned={})
text = " ".join(f"{fields.get(key, 0):x}" for key in (
"caching", "mapping", "page_size", "format_type", "element_bits", "compression"))
run.op(f"get_external_alloc_ptes 0 {handle:x} {offset:x} {size:x} {buffer_size:x} {text}",
status, pte_result(info, buffer, buffer_size))
return status
def dup(device, handle, canned=0, fail=None, lock_fail=None, info=True):
out, block = E.allocate(8, 0xa5), E.allocate(0x38, 0xa5)
status = world.call("rm_gpu_ops_dup_memory", device, user, handle, out,
block if info else 0, canned={"dup": lambda source: canned},
fail=fail, lock_fail=lock_fail)
run.op(f"dup_memory 0 {user:x} {handle:x} {1 if info else 0}", status,
f"{E.d(out):x} {E.read(block, 0x38).hex()}")
return status, E.d(out)
def free(device, handle, lock_fail=None):
# The duplicate of a fixture object is the same object under the new handle.
status = world.call("rm_gpu_ops_free_duped_handle", device, handle, canned={},
lock_fail=lock_fail)
run.op(f"free_duped_handle 0 {handle:x}", status)
return status
# The mappings of the workload: video memory in 2 MiB pages (GPU cached), duplicated,
# described and freed; system memory in 4 KiB pages.
device, space = start("mem-workload")
fixture_memory(run, 0x5001, 2, 0x7f0000000, 0x400000, page=0x200000)
fixture_memory(run, 0x5002, 1, 0x123456000, 0x8000, cached=False)
for handle, size in ((0x5001, 0x400000), (0x5002, 0x8000)):
status, duplicate = dup(device, handle)
_require(status == 0)
FAKE_MEMORY[duplicate] = FAKE_MEMORY[handle]
run.note(f"same {duplicate:x} {handle:x}")
_require(ptes(space, duplicate, 0, size, mapping=1) == 0)
_require(free(device, duplicate) == 0)
# PTE fields: every mapping type and caching type on video and system memory of each
# page size, cached and uncached descriptors.
for label, space_kind, base, size, page in (
("video-4k", 2, 0x7e0000000, 0x4000, 0x1000),
("video-64k", 2, 0x7d0000000, 0x40000, 0x10000),
("video-2m", 2, 0x7c0000000, 0x400000, 0x200000),
("system-4k", 1, 0x1234567000, 0x4000, 0x1000),
("system-64k", 1, 0x1234560000, 0x40000, 0x10000),
("system-2m", 1, 0x1234400000, 0x400000, 0x200000)):
for cached in (True, False):
device, space = start(f"mem-pte-{label}-{'cached' if cached else 'uncached'}")
fixture_memory(run, 0x5001, space_kind, base, size, page=page, cached=cached)
for caching in range(3):
for mapping in range(4):
ptes(space, 0x5001, 0, size, caching=caching, mapping=mapping)
# Descriptor flags and PTE kinds.
for label, flags, kind in (("read-only", MEMDESC_READ_ONLY, 0),
("encrypted", MEMDESC_ENCRYPTED, 0),
("privileged", MEMDESC_PRIVILEGED, 0),
("all", MEMDESC_READ_ONLY | MEMDESC_ENCRYPTED
| MEMDESC_PRIVILEGED, 0),
("kind-ca", 0, 0xca), ("kind-ff", 0, 0xff)):
for space_kind, base in ((2, 0x7e0000000), (1, 0x1234567000)):
device, space = start(f"mem-pte-{label}-{space_kind}")
fixture_memory(run, 0x5001, space_kind, base, 0x2000, flags=flags, kind=kind)
for mapping in range(4):
ptes(space, 0x5001, 0, 0x2000, mapping=mapping)
# Ranges, buffer sizes and the mapping page size.
device, space = start("mem-pte-ranges")
fixture_memory(run, 0x5001, 2, 0x7e0000000, 0x40000, page=0x10000)
fixture_memory(run, 0x5002, 1, 0x1234567000, 0x5800, page=0x1000)
for handle, offset, size, fields in (
(0x5001, 0, 0, {}), (0x5001, 0x10000, 0x20000, {}), (0x5001, 0x40000, 0x10000, {}),
(0x5001, 0x30000, 0x20000, {}), (0x5001, 0x8000, 0x10000, {}),
(0x5001, 0, 0x18000, {}), (0x5001, 0, 0x40000, dict(buffer_size=0x10)),
(0x5001, 0, 0x40000, dict(buffer_size=0xf)), (0x5001, 0, 0x40000, dict(buffer_size=0)),
(0x5001, 0, 0x40000, dict(page_size=0x1000, buffer_size=0x200)),
(0x5001, 0x3000, 0x2000, dict(page_size=0x1000)),
(0x5001, 0, 0x40000, dict(page_size=0x10000)),
(0x5001, 0, 0x40000, dict(page_size=0x200000)),
(0x5001, 0, 0x40000, dict(page_size=0x3000)),
# A mapping page size that divides the page size but has no page-table level
# (0x8000) is not generated: the original dereferences a null level format.
(0x5002, 0, 0, {}), (0x5002, 0x5000, 0x1000, {}), (0x5002, 0x6000, 0x1000, {}),
(0x5002, 0x4000, 0x3000, {}), (0x5002, 0x800, 0x1000, {}),
(0x5002, 0, 0x6000, dict(buffer_size=0x18)), (0, 0, 0x1000, {}),
(0x5999, 0, 0x1000, {})):
ptes(space, handle, offset, size, **fields)
# A discontiguous descriptor and one whose page size was never set.
device, space = start("mem-pte-pages")
pages = [0x7e0005000, 0x7e0001000, 0x7e0009000, 0x7e0002000]
fixture_memory(run, 0x5001, 2, 0, 0x4000, contiguous=False, pages=pages)
fixture_memory(run, 0x5002, 1, 0, 0x4000, contiguous=False, cached=False,
pages=[page_address + 0x1200000000 for page_address in pages])
fixture_memory(run, 0x5003, 2, 0x7e0000000, 0x4000, page=0)
fixture_memory(run, 0x5004, 2, 0x7f0000000, 0x200000, page=0)
for handle in (0x5001, 0x5002):
ptes(space, handle, 0, 0x4000)
ptes(space, handle, 0x1000, 0x2000)
ptes(space, 0x5003, 0, 0x4000)
ptes(space, 0x5004, 0, 0x200000)
# Compression and format requests (not issued by the workload) read attributes of the
# Memory object the fixture object does not carry: not generated; the Rust code refuses
# them.
# A cached mapping of system memory flushes the framebuffer L2 cache; the registers of
# the flush are the case's (first values of the transcript).
device, space = start("mem-pte-l2")
fixture_memory(run, 0x5001, 1, 0x1234567000, 0x2000, cached=True)
fixture_memory(run, 0x5002, 2, 0x7e0000000, 0x2000, cached=True)
for handle in (0x5001, 0x5002):
for caching in range(3):
ptes(space, handle, 0, 0x2000, caching=caching)
# dupMemory: the descriptor facts it reports, the parent of the duplicate, failures.
for label, keywords in (("video", dict(space=2, base=0x7f0000000, size=0x400000,
page=0x200000)),
("video-kind", dict(space=2, base=0x7e0000000, size=0x3000,
kind=0xdb)),
("system", dict(space=1, base=0x123456000, size=0x8000)),
("subdevice", dict(space=2, base=0x7e0000000, size=0x1000,
parent="subdevice")),
("no-page-size", dict(space=2, base=0x7e0000000, size=0x210000,
page=0)),
("bar1", dict(space=1, base=0x123456000, size=0x1000,
flags=MEMDESC_SYSCOH_OVER_BAR1))):
device, space = start(f"mem-dup-{label}")
fixture_memory(run, 0x5001, keywords.pop("space"), keywords.pop("base"),
keywords.pop("size"), **keywords)
status, duplicate = dup(device, 0x5001)
if status == 0:
FAKE_MEMORY[duplicate] = FAKE_MEMORY[0x5001]
run.note(f"same {duplicate:x} 5001")
free(device, duplicate)
device, space = start("mem-dup-pages")
fixture_memory(run, 0x5001, 2, 0, 0x3000, contiguous=False,
pages=[0x7e0005000, 0x7e0001000, 0x7e0009000])
dup(device, 0x5001)
dup(device, 0x5001, info=False)
device, space = start("mem-dup-failures")
fixture_memory(run, 0x5001, 2, 0x7e0000000, 0x1000)
GID["status"] = 0x31
run.note("gid 31")
dup(device, 0x5001)
GID["status"] = 0
run.note("gid 0")
dup(device, 0x5001, canned=0x1b)
dup(device, 0x5001, fail=(0, 0x65))
dup(device, 0x5001, lock_fail=(0, 0x2f))
dup(device, 0x5999)
dup(device, 0)
free(device, 0x5999)
free(device, 0x5001, lock_fail=(0, 0x2f))
for symbol, hook in hooks.items():
E.cpu.hook_del(hook)
E.handlers.pop(symbol)
return run
# ---------------------------------------------------------------------------------------
# Channels, the two entry points that need no kernel channel object:
# rm_gpu_ops_get_channel_resource_ptes -> _nv046811rm (the PTE builder on a context-buffer
# descriptor, no Memory object) and rm_gpu_ops_release_channel -> _nv046853rm ->
# _nv014215rm (_nvGpuOpsReleaseChannel). The retained-channel structure (0xb8 bytes:
# device +0, session +0x18, resource descriptors from +0x30, their count +0x9c, the TSG
# duplicate +0xac, the context-share duplicate +0xb0, the retainer +0xb4) is fixture memory
# here, as is every descriptor; the handles are answered by the case.
def channel_cases(world):
run = Runner(world)
user = world.USER
hooks = {symbol: E.install(symbol, handler) for symbol, handler in R.STAGE_FIXTURES.items()}
def start(name):
run.begin(name)
external = run.user_vaspace()
device = run.standard_device()
_require(run.dup_address_space(device, user, external) == 0)
return device, run.spaces[0]
def ptes(space, handle, descriptor, offset, size, buffer_size=0x100, lock_fail=None,
**fields):
info, buffer = mapping_info(buffer_size=buffer_size, **fields)
status = world.call("rm_gpu_ops_get_channel_resource_ptes", space, descriptor, offset,
size, info, canned={}, lock_fail=lock_fail)
text = " ".join(f"{fields.get(key, 0):x}" for key in ("caching", "mapping", "page_size"))
run.op(f"get_channel_resource_ptes 0 {handle:x} {offset:x} {size:x} {buffer_size:x}"
f" {text}", status, pte_result(info, buffer, buffer_size))
return status
# Context buffers as RM allocates them: video memory in 4 KiB pages, contiguous or
# not, GPU cached; and system memory.
device, space = start("chan-ptes")
pages = [0x7e0005000, 0x7e0001000, 0x7e0009000, 0x7e0002000]
buffers = {
0x6001: fixture_memory(run, 0x6001, 2, 0x7e1000000, 0x5000),
0x6002: fixture_memory(run, 0x6002, 2, 0, 0x4000, contiguous=False, pages=pages),
0x6003: fixture_memory(run, 0x6003, 1, 0x1234567000, 0x3000, cached=False),
0x6004: fixture_memory(run, 0x6004, 2, 0x7e2000000, 0x1000, gpu=False),
0x6005: fixture_memory(run, 0x6005, 2, 0x7e3000000, 0x20000, page=0x10000,
flags=MEMDESC_PRIVILEGED),
}
for handle, size in ((0x6001, 0x5000), (0x6002, 0x4000), (0x6003, 0x3000), (0x6004, 0x1000),
(0x6005, 0x20000)):
ptes(space, handle, buffers[handle], 0, size)
ptes(space, 0x6001, buffers[0x6001], 0x2000, 0x2000, mapping=3, caching=1)
ptes(space, 0x6001, buffers[0x6001], 0, 0x5000, page_size=0x1000)
ptes(space, 0x6001, buffers[0x6001], 0, 0x5000, buffer_size=0x10)
ptes(space, 0x6001, buffers[0x6001], 0x5000, 0x1000)
ptes(space, 0x6001, buffers[0x6001], 0, 0x5000, lock_fail=(0, 0x2f))
ptes(space, 0, 0, 0, 0x1000)
def release(device, count, tsg, share, retainer, lock_fail=None):
retained = E.allocate(0xb8)
E.wq(retained, device)
E.wq(retained + 0x18, world.session)
descriptors = []
for index in range(count):
descriptor = fixture_memory(run, 0x6100 + index, 2, 0x7e4000000 + 0x10000 * index,
0x1000)
E.wq(retained + 0x30 + 8 * index, descriptor)
descriptors.append(0x6100 + index)
E.wd(retained + 0x9c, count)
for offset, handle in ((0xac, tsg), (0xb0, share), (0xb4, retainer)):
E.wd(retained + offset, handle)
if handle:
API.canned_handles.add(handle)
status = world.call("rm_gpu_ops_release_channel", retained, canned={},
lock_fail=lock_fail)
run.op(f"release_channel 0 {count:x} {tsg:x} {share:x} {retainer:x}", 0)
device, space = start("chan-release")
release(device, 0, 0xcc000101, 0xcc000102, 0xcc000103)
release(device, 3, 0xcc000111, 0xcc000112, 0xcc000113)
release(device, 0, 0xcc000121, 0, 0xcc000123)
release(device, 0, 0, 0, 0xcc000133)
release(device, 1, 0, 0, 0)
release(device, 2, 0xcc000151, 0xcc000152, 0xcc000153, lock_fail=(0, 0x2f))
for symbol, hook in hooks.items():
E.cpu.hook_del(hook)
E.handlers.pop(symbol)
return run
def main():
install()
lines = ["# Original RM side of the UVM interface (per-context path) under instruction "
"emulation; see tools/check_uvm_gpu_ops2_binary.py", f"# original sha256 {DIGEST}"]
world = World("uvm-slice2")
world.snapshot()
runs = [device_cases(world), address_space_cases(world), memory_cases(world),
channel_cases(world)]
for run in runs:
lines += run.lines
text = "\n".join(lines) + "\n"
target = OUT / "original-gpu-ops2.txt"
if "--check" in sys.argv:
if not target.is_file():
raise SystemExit(f"oracle missing: {target}")
if target.read_text() != text:
raise SystemExit(f"oracle differs from the checked copy: {target}")
else:
OUT.mkdir(parents=True, exist_ok=True)
target.write_text(text)
print(json.dumps(dict(
original_sha256=DIGEST, oracle=str(target.relative_to(ROOT)),
oracle_sha256=hashlib.sha256(text.encode()).hexdigest(),
cases=sum(run.cases for run in runs), rm_api_calls=sum(run.calls for run in runs))))
if __name__ == "__main__":
main()