Files
nvdriver/tools/check_rmapi_memory_binary.py

950 lines
47 KiB
Python

#!/usr/bin/env python3
"""Run the original's memory-object paths and write an oracle for the Rust `rmapi::memory`.
This extends the RM API fixture of tools/check_rmapi_binary.py (same emulator, same
constructed GPU): the GPU object is the one the original's own probe and attach build for a
GV100, and here the original's memory stage bodies run on it as well, so that the constructed
MemoryManager carries the framebuffer region table, the reserved region, the heap and the
physical memory allocator (PMA) the original creates in its first open.
Executed original code in front of every case (after the sweep and KernelMemorySystem
PreInitLocked of the earlier slices), each as the stage wrappers call it and each to status 0:
MemorySystem StatePreInitLocked HAL body _nv045895rm (region table through
MemoryManager+0x120, comptag geometry)
MemoryManager StatePreInitLocked _nv044123rm (reserved size, BAR2 hidden range)
KernelBus StatePreInitLocked _nv039599rm (aperture sizes)
MemorySystem StateInitUnlocked _nv045883rm
MemorySystem StateInitLocked _nv045882rm (comptag store size)
KernelMemorySystem StateInitLocked _nv041688rm (system-memory flush page)
MemoryManager StateInitLocked _nv044120rm: reserved base _nv043997rm, PMA
initialization _nv044062rm, heap creation _nv043851rm
with heapInit, PMA region registration and
kmemsysPostHeapCreate (the comptag store allocation)
Then, through the unmodified escape path `_nv000800rm`:
NV_ESC_RM_ALLOC classes 0x40 (VideoMemory, _nv060578rm -> pmaAllocatePages _nv051433rm
-> _nv043803rm -> _nv060574rm), 0x3e (SystemMemory, _nv058782rm), 0x50a0
(VirtualMemory, _nv060585rm) and their frees
NV_ESC_RM_ALLOC_MEMORY (0x27) class 0x71 (OsDescMemory)
NV_ESC_RM_MAP_MEMORY (0x4e), NV_ESC_RM_UNMAP_MEMORY (0x4f),
NV_ESC_RM_UPDATE_DEVICE_MAPPING_INFO (0x5e), and the controls 0xd01, 0x503c0104, 0x503c0105
Fixture-supplied beyond tools/check_rmapi_binary.py (the operating-system side of memory;
every call is written to the record as an `os` line under the request that made it):
nv_alloc_pages / nv_free_pages page allocations get fabricated physical addresses
0x100000000 + 0x10000000 * n for allocation n
nv_alloc_kernel_mapping / nv_free_... backed by fixture memory
nv_alloc_user_mapping / nv_free_... the public body: first page address plus offset
nv_add_mapping_context_to_file recorded (arguments and the access parameters)
os_lock_user_pages / os_unlock_... recorded; pages get fabricated addresses
nv_register_user_pages / nv_unregister recorded
os_lookup_user_io_memory INVALID_ADDRESS (the range is not an I/O mapping)
os_page_mask, os_page_shift data symbols of the open layer: ~0xfff and 12, set
after the attach (the attach runs as in the earlier
slices' fixture, where they are zero)
nv_get_ctl_state the control node's state
os_match_mmap_offset the public body over the fabricated addresses
nv_get_device_memory_config NOT_SUPPORTED (no NUMA onlining of device memory)
PMA scrub-on-free (pPma+0x298) cleared after heap creation. In the original the
allocator refuses requests (INVALID_STATE) until the
copy-engine scrubber registers, which needs a running
FIFO; with the byte clear, freed frames are reusable
at once and no scrub is submitted.
Limits: as tools/check_rmapi_binary.py (GPU constructed, not initialized, except for the
bodies above; one GPU; no concurrency). KernelBus StateInitLocked and PostLoad do not run, so
no BAR1 address space exists: a CPU mapping of video memory is executed only as far as the
original gets without one.
"""
import json
import struct
import sys
import check_rmapi_binary as R
E = R.E
ROOT, OUT, DIGEST = R.ROOT, R.OUT, R.DIGEST
state, gpu_state = R.state, R.gpu_state
WORKLOAD = ROOT / "tools/rmapi_memory_workload.json"
R.STAGE_BODIES.update({
"ms-preinit": (0x1ec0, 1, "_nv045895rm", ()),
"mm-preinit": (0x1ed0, 1, "_nv044123rm", ()),
"kbus-preinit": (0x1f80, 1, "_nv039599rm", ()),
"ms-init-unlocked": (0x1ec0, 1, "_nv045883rm", ()),
"ms-init": (0x1ec0, 1, "_nv045882rm", ()),
"kms-init": (0x1ec8, 1, "_nv041688rm", ()),
"mm-init": (0x1ed0, 1, "_nv044120rm", ()),
})
MEMORY_STAGES = ("ms-preinit", "mm-preinit", "kbus-preinit", "ms-init-unlocked", "ms-init",
"kms-init", "mm-init")
# Assertions the original logs in these bodies on the constructed GPU (recorded in the
# `stage` lines): A5a4 and A905 in the two MemorySystem bodies, Aa53 in MemoryManager
# InitLocked.
PAGE = 0x1000
# Registers a request reads that the transcript never shows: case inputs. 0x70010 is polled
# and 0x70004 are polled after they are written when video memory is released (cache
# operations that read back idle).
UNTRACED = {0x70010: 0, 0x70004: 0}
os_state = {"pages": {}, "events": [], "next": 0, "locked": {}, "lock_status": 0}
def event(text):
os_state["events"].append("os " + text)
def alloc_pages(a):
"""nv_alloc_pages(nv, page_count, page_size, contiguous, cache_type, zeroed,
unencrypted, node_id, pte_array, priv_data)."""
count, size, contiguous = a[1] & 0xffffffff, a[2], a[3] & 0xff
cache, zeroed = a[4] & 0xffffffff, a[5] & 0xff
unencrypted, node = E.stack_argument(0) & 0xff, E.stack_argument(1) & 0xffffffff
table, private = E.stack_argument(2), E.stack_argument(3)
index = os_state["next"]
os_state["next"] += 1
base = 0x100000000 + 0x10000000 * index
for entry in range(1 if contiguous else count):
E.wq(table + 8 * entry, base + entry * size)
cookie = E.allocate(16)
E.wq(cookie, index)
E.wq(private, cookie)
os_state["pages"][cookie] = dict(index=index, base=base, bytes=count * size, backing=None)
event(f"alloc-pages {count:x} {size:x} {contiguous} {cache:x} {zeroed} {unencrypted}"
f" {node:x} = {index:x}")
return 0
def free_pages(a):
"""nv_free_pages(nv, page_count, contiguous, cache_type, priv_data)."""
record = os_state["pages"].pop(a[4])
event(f"free-pages {record['index']:x} {a[1] & 0xffffffff:x} {a[2] & 0xff}"
f" {a[3] & 0xffffffff:x}")
return 0
def kernel_mapping(a):
"""nv_alloc_kernel_mapping(nv, priv, pageIndex, pageOffset, size, &priv): the address."""
record = os_state["pages"][a[1]]
if record["backing"] is None:
assert record["bytes"] <= 0x100000, "kernel mapping of a large allocation"
record["backing"] = E.allocate(record["bytes"])
event(f"kernel-map {record['index']:x} {a[2]:x} {a[3] & 0xffffffff:x} {a[4]:x}")
return record["backing"] + a[2] * PAGE + (a[3] & 0xffffffff)
def kernel_unmapping(a):
event("kernel-unmap")
return 0
def user_mapping(a):
"""nv_alloc_user_mapping(nv, priv, pageIndex, pageOffset, size, protect, &address,
&priv): the public body returns the physical address of the page plus the offset."""
record = os_state["pages"][a[1]]
address = record["base"] + a[2] * PAGE + (a[3] & 0xffffffff)
E.wq(E.stack_argument(0), address)
event(f"user-map {record['index']:x} {a[2]:x} {a[3] & 0xffffffff:x} {a[4]:x}"
f" {a[5] & 0xffffffff:x} = {address:x}")
return 0
def user_unmapping(a):
"""nv_free_user_mapping(nv, priv, userAddress, mapPriv)."""
record = os_state["pages"].get(a[1])
event(f"user-unmap {record['index'] if record else 0xffff:x} {a[2]:x}")
return 0
def mapping_context(a):
"""nv_add_mapping_context_to_file(nv, access params, prot, alloc private, page index,
fd). The access parameters (nv_usermap_access_params_t of the public nv.h): addr, size,
offset, page_array, num_pages, memory area (ranges, count), access_start, access_size,
contig, caching."""
block = a[1]
addr, size, offset, array, pages, ranges, count, start, length = struct.unpack(
"<9Q", E.read(block, 0x48))
contig, caching = E.b(block + 0x48), E.d(block + 0x4c)
record = os_state["pages"].get(a[3])
listed = [E.q(array + 8 * entry) for entry in range(min(pages, 4))] if array else []
areas = [struct.unpack("<QQ", E.read(ranges + 16 * entry, 16))
for entry in range(min(count, 4))] if ranges else []
node = "ctl" if E.d(a[0] + 0x10) & 4 else "dev"
event(f"context {node} {a[5] & 0xffffffff:x} {a[2] & 0xffffffff:x}"
f" {record['index'] if record else 0xffff:x} {a[4]:x} {addr:x} {size:x} {offset:x}"
f" {pages:x} {start:x} {length:x} {contig} {caching:x}"
f" {','.join(f'{value:x}' for value in listed) or '-'}"
f" {','.join(f'{base:x}:{span:x}' for base, span in areas) or '-'}")
return os_state.get("context_status", 0)
def lock_user_pages(a):
"""os_lock_user_pages(address, page_count, &page_array, flags)."""
index = os_state["next"]
os_state["next"] += 1
count = a[1]
event(f"lock-user-pages {a[0]:x} {count:x} {a[3] & 0xffffffff:x} = {index:x}")
if os_state["lock_status"]:
return os_state["lock_status"]
cookie = E.allocate(16)
E.wq(cookie, index)
E.wq(a[2], cookie)
os_state["locked"][cookie] = dict(index=index, count=count)
return 0
def unlock_user_pages(a):
"""os_unlock_user_pages(page_count, page_array, flags)."""
record = os_state["locked"].pop(a[1], None)
event(f"unlock-user-pages {record['index'] if record else 0xffff:x} {a[0]:x}"
f" {a[2] & 0xffffffff:x}")
return 0
def register_user_pages(a):
"""nv_register_user_pages(nv, page_count, phys_addr, import_priv, &priv_data,
unencrypted). As in the public body, the page array of the lock comes in through
*priv_data and the allocation goes out through it; the fixture fills the address table."""
locked = E.q(a[4])
record = os_state["locked"].get(locked)
index = record["index"] if record else 0xffff
base = 0x100000000 + 0x10000000 * index
for entry in range(a[1]):
E.wq(a[2] + 8 * entry, base + entry * PAGE)
cookie = E.allocate(16)
E.wq(cookie, index)
E.wq(a[4], cookie)
os_state["pages"][cookie] = dict(index=index, base=base, bytes=a[1] * PAGE, backing=None,
locked=locked)
event(f"register-user-pages {index:x} {a[1]:x} {a[3]:x} {a[5] & 0xff}")
return 0
def unregister_user_pages(a):
"""nv_unregister_user_pages(nv, page_count, &import_priv, &priv_data): the page array
of the lock goes back out through *priv_data."""
record = os_state["pages"].pop(E.q(a[3]), None)
if record:
E.wq(a[3], record["locked"])
if a[2]:
E.wq(a[2], 0)
event(f"unregister-user-pages {record['index'] if record else 0xffff:x} {a[1]:x}")
return 0
def match_offset(a):
"""os_match_mmap_offset(alloc private, offset, &page index): the public body looks the
address up in the allocation's page table."""
record = os_state["pages"].get(a[0])
if record is None or not record["base"] <= a[1] < record["base"] + record["bytes"] \
or (a[1] - record["base"]) % PAGE:
event(f"match-offset {a[1]:x} = -")
return 0x57
E.wq(a[2], (a[1] - record["base"]) // PAGE)
event(f"match-offset {a[1]:x} = {(a[1] - record['base']) // PAGE:x}")
return 0
def named(name, value):
def run(a):
event(name)
return value
return run
MEMORY_FIXTURES = {
"nv_alloc_pages": alloc_pages, "nv_free_pages": free_pages,
"nv_alloc_kernel_mapping": kernel_mapping, "nv_free_kernel_mapping": kernel_unmapping,
"nv_alloc_user_mapping": user_mapping, "nv_free_user_mapping": user_unmapping,
"nv_add_mapping_context_to_file": mapping_context,
"os_lock_user_pages": lock_user_pages, "os_unlock_user_pages": unlock_user_pages,
"nv_register_user_pages": register_user_pages,
"nv_unregister_user_pages": unregister_user_pages,
"os_lookup_user_io_memory": named("lookup-user-io", 0x1e),
"nv_get_device_memory_config": lambda a: 0x56,
"nv_get_ctl_state": lambda a: os_state["control"],
"os_match_mmap_offset": match_offset,
}
for _name, _handler in MEMORY_FIXTURES.items():
if _name in E.externals:
E.install(_name, _handler)
CLIENT, DEVICE, SUBDEVICE = 0xc1d00001, 0xcaf00000, 0xcaf00001
# The delay and tick-resolution fixtures of the stage runner stay installed for the requests
# of a case (a timeout is started on the mapping path); the stage runner installs and
# removes its own, so these are removed before the next case builds its world.
request_hooks = {}
def request_fixtures(enable):
for name, handler in R.STAGE_FIXTURES.items():
if enable and name not in request_hooks:
request_hooks[name] = E.install(name, handler)
elif not enable and name in request_hooks:
E.cpu.hook_del(request_hooks.pop(name))
E.handlers.pop(name)
def memory_params(owner=CLIENT, kind=0, flags=0x1c101, attr=0x18000000, attr2=0, size=0x200000,
alignment=0x200000, offset=0, space=0, fmt=0, low=0, high=0, limit=0,
width=0, height=0, pitch=0, compression=0, zcull=0, address=0, ctag=0,
internal=0, tag=0, node=0, fill=0):
"""NV_MEMORY_ALLOCATION_PARAMS (128 bytes)."""
block = struct.pack("<IIIIIiIIIIII", owner, kind, flags, width, height, pitch, attr, attr2,
fmt, compression, zcull, fill)
block += struct.pack("<QQQQQQQ", low, high, size, alignment, offset, limit, address)
block += struct.pack("<IIIIII", ctag, space, internal, tag, node, fill)
assert len(block) == 128
return block
class MemorySequence(R.GpuSequence):
"""A case on a GPU whose MemoryManager holds the original's heap and PMA."""
def __init__(self, name, registers=None):
os_state.update(pages={}, events=[], next=0, locked={}, lock_status=0,
context_status=0)
request_fixtures(False)
os_state["case"] = self
for symbol in ("os_page_mask", "os_page_shift"):
E.wq(E.externals[symbol], 0)
super().__init__(name, registers)
E.wq(E.externals["os_page_mask"], 0xfffffffffffff000)
E.wq(E.externals["os_page_shift"], 12)
os_state["control"] = self.context["nodes"]["ctl"]
assert self.alloc(0, 0, 0, 0)[1] == CLIENT
self.initialized(1)
assert self.alloc(CLIENT, CLIENT, 0, 0x80,
params=R.device_params(share=CLIENT, mode=2)) == (0, DEVICE)
assert self.alloc(CLIENT, DEVICE, 0, 0x2080, params=bytes(4)) == (0, SUBDEVICE)
# Device file 3 registers control file 0 (descriptor 10), as libcuda does for the
# device descriptor it issues NV_ESC_RM_ALLOC_MEMORY on.
assert self.register_fd(3, 10) == 0
self.sweep()
self.stage("kms-preinit")
for stage in MEMORY_STAGES:
self.stage(stage)
self.lines += os_state["events"]
os_state["events"].clear()
manager = E.q(self.gpu + 0x1ed0)
assert E.b(manager + 0x41c) == 1, "PMA is not initialized"
heap = E.q(manager + 0x468)
self.pma = E.q(heap + 0x128)
assert self.pma and E.b(self.pma + 0x298) == 1 and E.b(self.pma + 0x2b0) == 0
E.wb(self.pma + 0x298, 0)
# FB_REGION_DESCRIPTOR table: base, limit, reserved size, bRsvdRegion, performance,
# six flag bytes (compressed, ISO, protected, internal heap, lost and preserved on
# suspend).
regions = []
for index in range(E.d(manager + 0x850)):
entry = E.read(manager + 0x858 + 0x28 * index, 0x28)
base, limit, reserved, flag, performance = struct.unpack_from("<QQQII", entry)
regions.append(f"{base:x}:{limit:x}:{reserved:x}:{flag:x}:{performance:x}:"
f"{entry[0x20:0x26].hex()}")
self.lines.append("regions " + " ".join(regions))
self.lines.append(f"reserved {E.q(manager + 0x488):x} {E.q(manager + 0x490):x}")
gpu_state["source"] = None
request_fixtures(True)
def begin(self):
gpu_state["read"].clear()
gpu_state["written"].clear()
# A request that reaches hardware gets its register values from the transcript
# (first read of each register); its accesses are recorded in a `touched` line.
gpu_state["source"] = dict(R.first_reads())
gpu_state["source"].update(UNTRACED)
def finish(self):
gpu_state["source"] = None
if gpu_state["read"] or gpu_state["written"]:
self.lines.append("touched " + " ".join(
[f"r{offset:x}" for offset in dict.fromkeys(gpu_state["read"])] +
[f"w{offset:x}={value:x}" for offset, value in gpu_state["written"]]))
self.lines += os_state["events"]
os_state["events"].clear()
def quiet(self):
"""The request touched no register."""
assert not gpu_state["read"] and not gpu_state["written"], (
gpu_state["read"], gpu_state["written"])
def alloc(self, *arguments, **keywords):
self.begin()
result = super().alloc(*arguments, **keywords)
self.finish()
return result
def free(self, *arguments, **keywords):
self.begin()
result = super().free(*arguments, **keywords)
self.finish()
return result
def control(self, *arguments, **keywords):
self.begin()
result = super().control(*arguments, **keywords)
self.finish()
return result
def memory(self, klass, parent=DEVICE, new=0, **fields):
result, handle = self.alloc(CLIENT, parent, new, klass, params=memory_params(**fields))
self.quiet()
return result, handle
def raw(self, kind, number, request, node="ctl", file=0):
"""An escape whose block has no parameter pointer."""
self.begin()
status, reply = R.escape(self.context, node, file, number, request)
diagnostics = ",".join(state["diag"]) or "-"
self.lines.append(f"{kind} {node} {file} {request.hex()} -> {status:x} {reply.hex()}"
f" {diagnostics}")
self.finish()
return status, reply
def map(self, memory, offset, length, flags, descriptor, device=DEVICE, node="ctl",
file=0, size=0x38):
"""NV_ESC_RM_MAP_MEMORY: NVOS33 (hClient, hDevice, hMemory, offset, length,
pLinearAddress, status, flags) and the descriptor of the file to map through."""
request = struct.pack("<IIIIQQQIIiI", CLIENT, device, memory, 0, offset, length, 0,
0xdddddddd, flags, descriptor, 0)[:size]
status, reply = self.raw("M", 0x4e, request, node, file)
if status or len(reply) < 0x38:
return status, 0, 0
return struct.unpack_from("<I", reply, 40)[0], struct.unpack_from("<Q", reply, 32)[0], \
struct.unpack_from("<I", reply, 44)[0]
def unmap(self, memory, address, flags=0, device=DEVICE, node="ctl", file=0):
"""NV_ESC_RM_UNMAP_MEMORY: NVOS34 (hClient, hDevice, hMemory, pLinearAddress, status,
flags)."""
request = struct.pack("<IIIIQII", CLIENT, device, memory, 0, address, 0xdddddddd, flags)
status, reply = self.raw("U", 0x4f, request, node, file)
return status or struct.unpack_from("<I", reply, 24)[0]
def update(self, memory, old, new, device=SUBDEVICE):
"""NV_ESC_RM_UPDATE_DEVICE_MAPPING_INFO: NVOS56 (hClient, hDevice, hMemory,
pOldCpuAddress, pNewCpuAddress, status)."""
request = struct.pack("<IIIIQQII", CLIENT, device, memory, 0, old, new, 0xdddddddd, 0)
status, reply = self.raw("D", 0x5e, request)
return status or struct.unpack_from("<I", reply, 32)[0]
def descriptor(self, new, flags, address, limit, parent=DEVICE, klass=0x71, descriptor=-1,
node="dev", file=3):
"""NV_ESC_RM_ALLOC_MEMORY: NVOS02 (hRoot, hObjectParent, hObjectNew, hClass, flags,
pMemory, limit, status) and a descriptor."""
request = struct.pack("<IIIIIIQQIIiI", CLIENT, parent, new, klass, flags, 0, address,
limit, 0xdddddddd, 0, descriptor, 0)
status, reply = self.raw("G", 0x27, request, node, file)
return status or struct.unpack_from("<I", reply, 40)[0]
def address_space(self, handle, flags=0):
"""0xd01 NV0000_CTRL_CMD_CLIENT_GET_ADDR_SPACE_TYPE."""
result, reply = self.control(CLIENT, CLIENT, 0xd01,
params=struct.pack("<III", handle, flags, 0xaaaaaaaa))
self.quiet()
return result, struct.unpack_from("<I", reply, 8)[0]
class Generator:
"""Deterministic request variation (xorshift64)."""
def __init__(self, seed):
self.value = seed
def next(self):
value = self.value
value ^= (value << 13) & ((1 << 64) - 1)
value ^= value >> 7
value ^= (value << 17) & ((1 << 64) - 1)
self.value = value
return value
def below(self, bound):
return self.next() % bound
def pick(self, values):
return values[self.below(len(values))]
def workload_case():
"""The memory requests of the captured CUDA run for the device the context lives on, in
their order and with libcuda's own handles and parameters. Two 2 MiB video memory
objects are allocated first: in the capture the allocator's first 4 MiB were already
held when libcuda made its first request (UVM's page-tree chunks), and with the same
amount held here the placement of every later request can be compared with the capture.
Returns the case and the comparison with the capture's replies."""
workload = json.loads(WORKLOAD.read_text())
case = MemorySequence("mem-workload")
for holder in (0x5cff0001, 0x5cff0002):
assert case.memory(0x40, new=holder, size=0x200000) == (0, holder)
# Descriptors of the capture: every mapping uses a fresh file of the node kind the
# object needs; here descriptor 10 is a control file and 20 a device file.
compared = dict(alloc=0, osdesc=0, map=0, unmap=0, update=0, control=0, free=0)
differences = []
addresses = {}
for operation in workload["operations"]:
kind = operation["kind"]
request = bytes.fromhex(operation["request"])
expected = bytes.fromhex(operation["reply"])
if kind == "alloc":
root, parent, new, klass = struct.unpack_from("<IIII", request)
size, flags = struct.unpack_from("<II", request, 32)
params = bytes.fromhex(operation["params"])
result, _ = case.alloc(root, parent, new, klass, params=params, size=size,
flags=flags)
line = next(line for line in reversed(case.lines) if line.startswith("A "))
reply = bytes.fromhex(line.split()[-2])
wanted = bytes.fromhex(operation["params_reply"])
if (result, reply) != (struct.unpack_from("<I", expected, 40)[0], wanted):
differences.append((operation["index"], kind, f"{klass:x}", reply.hex(),
wanted.hex()))
elif kind == "control":
client, target, command = struct.unpack_from("<III", request)
params = bytes.fromhex(operation["params"])
result, reply = case.control(client, target, command, params=params)
wanted = bytes.fromhex(operation["params_reply"])
if (result, reply) != (struct.unpack_from("<I", expected, 28)[0], wanted):
differences.append((operation["index"], kind, f"{command:x}", reply.hex(),
wanted.hex()))
elif kind == "free":
root, parent, target = struct.unpack_from("<III", request)
result = case.free(root, parent, target)
if result != struct.unpack_from("<I", expected, 12)[0]:
differences.append((operation["index"], kind, f"{result:x}"))
elif kind == "osdesc":
fields = struct.unpack_from("<IIIIIIQQ", request)
result = case.descriptor(fields[2], fields[4], fields[6], fields[7],
parent=fields[1], klass=fields[3])
if result != struct.unpack_from("<I", expected, 40)[0]:
differences.append((operation["index"], kind, f"{result:x}"))
elif kind == "map":
fields = struct.unpack_from("<IIIIQQQII", request)
video = fields[1] == SUBDEVICE
result, address, flags = case.map(fields[2], fields[4], fields[5], fields[8],
20 if video else 10, device=fields[1])
addresses[struct.unpack_from("<Q", expected, 32)[0]] = address
wanted = struct.unpack_from("<II", expected, 40)
if (result, flags) != wanted:
differences.append((operation["index"], kind, f"{result:x}", f"{flags:x}",
f"{wanted[1]:x}"))
elif kind == "unmap":
fields = struct.unpack_from("<IIIIQII", request)
result = case.unmap(fields[2], addresses.get(fields[4], fields[4]), fields[6],
device=fields[1])
if result != struct.unpack_from("<I", expected, 24)[0]:
differences.append((operation["index"], kind, f"{result:x}"))
elif kind == "update":
fields = struct.unpack_from("<IIIIQQ", request)
result = case.update(fields[2], addresses.get(fields[4], fields[4]), fields[5],
device=fields[1])
if result != struct.unpack_from("<I", expected, 32)[0]:
differences.append((operation["index"], kind, f"{result:x}"))
compared[kind] += 1
return case, compared, differences
def probe(case, klass, keep=False, parent=DEVICE, **fields):
"""One allocation; released again unless `keep`."""
result, handle = case.memory(klass, parent=parent, **fields)
if result == 0 and not keep:
assert case.free(CLIENT, 0, handle) == 0
return result, handle
def video_rules():
"""NV01_MEMORY_LOCAL_USER (0x40): one request field varied at a time around the
workload's request and around an all-default request. Explicitly non-contiguous
requests (PHYSICALITY 1) are not part of this case: their page lists are not visible
in a reply."""
case = MemorySequence("mem-video-rules")
for flags, alignment in ((0x1c101, 0x200000), (0, 0)):
for size in (0, 1, 0xfff, 0x1000, 0x7fff, 0x8000, 0xffff, 0x10000, 0x10001, 0x1fffff,
0x200000, 0x200001, 0x3fffff, 0x400000, 0x7ef000000, 0x7ef600000,
0x800000000, 1 << 40, (1 << 64) - 1):
probe(case, 0x40, flags=flags, alignment=alignment, size=size)
for flags in (0x100, 0x80, 0):
for size in (0x10000, 0x200000):
for alignment in (0, 1, 0x800, 0x1000, 0x3000, 0x10000, 0x30000, 0x100000,
0x200000, 0x400000, 0x600000, 0x1000000, 1 << 32, 1 << 63):
probe(case, 0x40, flags=flags, alignment=alignment, size=size)
for page in range(4):
for huge in range(4):
for size in (0x1000, 0x10000, 0x200000, 0x300000, 0x20000000):
probe(case, 0x40, flags=0, alignment=0, size=size,
attr=0x10000000 | page << 23, attr2=huge << 20)
for physicality in (0, 2, 3):
for location in range(4):
probe(case, 0x40, flags=0, alignment=0, attr=physicality << 27 | location << 25)
for coherency in range(8):
probe(case, 0x40, flags=0, alignment=0, attr=0x10000000 | coherency << 29)
for bit in range(32):
probe(case, 0x40, flags=1 << bit, alignment=0, attr=0x10000000)
probe(case, 0x40, flags=1 << bit | 0x1c101, attr=0x18000000)
for bit in range(23):
probe(case, 0x40, flags=0, alignment=0, attr=0x10000000 | 1 << bit)
for bit in range(32):
probe(case, 0x40, flags=0, alignment=0, attr=0x10000000, attr2=1 << bit)
for kind in range(20):
probe(case, 0x40, kind=kind)
for owner in (0, 0xffffffff, 0xdeaf0000, 0xdeaf0003, 0xdeaf0004, DEVICE, 0x12345678):
probe(case, 0x40, owner=owner)
for field in ("fmt", "compression", "zcull", "width", "height", "pitch", "low", "high",
"offset", "limit", "address", "ctag", "space", "internal", "tag", "node"):
probe(case, 0x40, **{field: 0x1000})
probe(case, 0x40, flags=0x1c101 | 0x20000, low=0x1000000, high=0x1ffffff)
probe(case, 0x40, flags=0x1c101 | 0x20000, low=0x1000000, high=0x11fffff)
probe(case, 0x40, flags=0x1c101 | 0x20000, low=0x1100000, high=0x14fffff)
probe(case, 0x40, flags=0x1c101 | 0x20000, low=0x2000000, high=0x1000000)
probe(case, 0x40, flags=0x1c101 | 0x10, offset=0x1000000)
probe(case, 0x40, flags=0x1c101 | 0x10, offset=0x1010000)
probe(case, 0x40, parent=SUBDEVICE)
probe(case, 0x40, parent=CLIENT)
result, space = case.alloc(CLIENT, DEVICE, 0, 0x90f1,
params=R.vaspace_params(flags=0, base=0x5000000))
assert result == 0
probe(case, 0x40, parent=space)
probe(case, 0x40, space=space)
# A parameter block is required, and a handle the caller chooses is taken.
case.alloc(CLIENT, DEVICE, 0, 0x40)
assert probe(case, 0x40, keep=True)[0] == 0
return case
def video_placement():
"""Placement in the allocator: requests of mixed sizes and page sizes allocated and
released in a deterministic pseudo-random order, then the boundaries of the region."""
case = MemorySequence("mem-video-placement")
generator = Generator(0x9e3779b97f4a7c15)
live = []
sizes = (0x10000, 0x10000, 0x20000, 0x50000, 0x100000, 0x1f0000, 0x200000, 0x200000,
0x400000, 0x600000, 0xa00000, 0x1e00000, 0x4000000)
for step in range(420):
if live and (generator.below(100) < 42 or len(live) > 40):
handle = live.pop(generator.below(len(live)))
assert case.free(CLIENT, 0, handle) == 0
continue
size = generator.pick(sizes)
choice = generator.below(10)
if choice < 5:
fields = dict(flags=0x1c101, alignment=0x200000, attr=0x18000000)
elif choice < 8:
fields = dict(flags=0, alignment=0, attr=0x10000000)
elif choice < 9:
fields = dict(flags=0x100, alignment=generator.pick((0x10000, 0x200000, 0x400000,
0x800000)),
attr=0x10000000 | 2 << 23)
else:
fields = dict(flags=0, alignment=0, attr=0x10000000 | 3 << 23)
result, handle = case.memory(0x40, size=size, **fields)
if result == 0:
live.append(handle)
for handle in live:
assert case.free(CLIENT, 0, handle) == 0
# The whole region and its neighbours, with 64 KiB and with 2 MiB pages.
for size in (0x7eef60000, 0x7eef50000, 0x7eef70000, 0x7eee00000, 0x7ef000000):
for page in (2, 3):
probe(case, 0x40, flags=0, alignment=0, size=size, attr=0x10000000 | page << 23)
held = [case.memory(0x40, flags=0, alignment=0, size=0x7eec00000, attr=0x10000000)[1]]
for size in (0x200000, 0x200000, 0x200000, 0x10000, 0x150000, 0x10000):
held.append(case.memory(0x40, flags=0, alignment=0, size=size, attr=0x10000000)[1])
assert case.free(CLIENT, 0, CLIENT) == 0
return case
def system_rules():
"""NV01_MEMORY_SYSTEM (0x3e)."""
case = MemorySequence("mem-system-rules")
# Sizes whose page array the fixture's allocator cannot hold (from about 64 GiB) are not
# explored: what the original answers then depends on the kernel's allocator.
for size in (0, 1, 0xfff, 0x1000, 0x1001, 0x368d10, 0x200000, 0x5000000):
probe(case, 0x3e, flags=0xc001, attr=0x3a000000, alignment=0, size=size)
for location in range(4):
for physicality in range(4):
probe(case, 0x3e, flags=0xc001, alignment=0, size=0x3000,
attr=location << 25 | physicality << 27 | 1 << 29)
for coherency in range(8):
probe(case, 0x3e, flags=0xc001, alignment=0, size=0x3000,
attr=0x1a000000 | coherency << 29)
for page in range(4):
for size in (0x3000, 0x10000, 0x200000, 0x400000):
probe(case, 0x3e, flags=0xc001, alignment=0, size=size,
attr=0x3a000000 | page << 23)
for bit in range(32):
probe(case, 0x3e, flags=1 << bit, alignment=0, size=0x3000, attr=0x3a000000)
for bit in range(23):
probe(case, 0x3e, flags=0xc001, alignment=0, size=0x3000, attr=0x3a000000 | 1 << bit)
for bit in range(32):
probe(case, 0x3e, flags=0xc001, alignment=0, size=0x3000, attr=0x3a000000,
attr2=1 << bit)
for kind in range(20):
probe(case, 0x3e, flags=0xc001, alignment=0, size=0x3000, attr=0x3a000000, kind=kind)
for owner in (0, 0xffffffff, 0xdeaf0000, DEVICE, 0x12345678):
probe(case, 0x3e, flags=0xc001, alignment=0, size=0x3000, attr=0x3a000000,
owner=owner)
for alignment in (1, 0x1000, 0x3000, 0x10000, 0x200000):
for flags in (0xc001, 0xc101, 0xc081):
probe(case, 0x3e, flags=flags, alignment=alignment, size=0x3000, attr=0x3a000000)
for field in ("fmt", "compression", "zcull", "width", "height", "pitch", "low", "high",
"offset", "limit", "address", "ctag", "space", "internal", "tag", "node"):
probe(case, 0x3e, flags=0xc001, alignment=0, size=0x3000, attr=0x3a000000,
**{field: 0x1000})
probe(case, 0x3e, flags=0xc001, alignment=0, size=0x3000, attr=0x3a000000,
parent=SUBDEVICE)
probe(case, 0x3e, flags=0xc001, alignment=0, size=0x3000, attr=0x3a000000, parent=CLIENT)
# The client goes with live objects: a notifier (kernel mapping) and a buffer.
assert probe(case, 0x3e, keep=True, flags=0xc001, alignment=0, size=0x1000,
attr=0x3a000000, kind=13, owner=DEVICE)[0] == 0
assert probe(case, 0x3e, keep=True, flags=0xc001, alignment=0, size=0x200000,
attr=0x5a000000)[0] == 0
assert case.free(CLIENT, 0, CLIENT) == 0
return case
def virtual_rules():
"""NV50_MEMORY_VIRTUAL (0x50a0) in an RM-managed address space, with the workload's
fixed-offset request and the address heap around it."""
case = MemorySequence("mem-virtual-rules")
spaces = {}
for name, fields in (("managed", dict(flags=0, base=0x5000000)),
("external", dict(flags=0x48, base=0x1000)),
("small", dict(flags=0, base=0x100000, size=0x40000000)),
("high", dict(flags=0, base=0x200000000))):
result, spaces[name] = case.alloc(CLIENT, DEVICE, 0, 0x90f1,
params=R.vaspace_params(**fields))
assert result == 0
managed = spaces["managed"]
workload = dict(flags=0x8c415, attr=0, alignment=0, size=0xfb000000, offset=0x5000000)
for space in (0, 0x12345678, DEVICE, spaces["external"], managed, managed):
probe(case, 0x50a0, keep=True, space=space, **workload)
probe(case, 0x50a0, space=managed, parent=SUBDEVICE, **workload)
# Fixed offsets around the reservation, then released and taken again.
fixed = dict(flags=0x8c415, attr=0, alignment=0, space=managed)
for offset, size in ((0x4000000, 0x1000000), (0x4000000, 0x1000001), (0xffe00000, 0x200000),
(0x100000000, 0x200000), (0x100000000, 0x1000), (0x100200000, 0x1000),
(0x100200000, 0x1), (0x100201000, 0x10000), (0x100000000, 0x400000),
(0x0, 0x1000), (0x1000, 0x1000), (0x1ffffffe00000, 0x200000),
(0x1ffffffe00000, 0x200001), (0x2000000000000, 0x1000)):
probe(case, 0x50a0, keep=True, offset=offset, size=size, **fixed)
for size in (0, 1, 0x1000, 0x10000, 0x200000, 0x200001, 1 << 40, 1 << 49, (1 << 64) - 1):
probe(case, 0x50a0, offset=0x200000000, size=size, **fixed)
# Not fixed: the heap chooses, growing down (flag 4), growing up (flag 2) or by default.
for flags in (0x8c405, 0x8c403, 0x8c401, 0x80000, 0x8c505, 0x8c485):
for size, alignment in ((0x200000, 0), (0x1000, 0), (0x10000, 0), (0x1000000, 0x1000000),
(0x300000, 0x400000), (0x1000, 0x3000), (0x1000, 0x800)):
probe(case, 0x50a0, keep=True, flags=flags, attr=0, alignment=alignment, size=size,
space=managed)
for page in range(4):
for size in (0x1000, 0x10000, 0x200000):
probe(case, 0x50a0, flags=0x8c405, attr=page << 23, alignment=0, size=size,
space=managed)
# One bit at a time, on a lazy request (flag 0x400: no page-table memory is reserved at
# allocation, as in the workload). Without that flag the original reserves page-table
# memory from its page-level pools, which this fixture does not build: those requests
# (the six flag values above without 0x400, and the first of each pair below) show the
# original's answer when the reservation fails.
for bit in range(32):
probe(case, 0x50a0, flags=1 << bit | 0x80000, attr=0, alignment=0, size=0x200000,
space=managed)
probe(case, 0x50a0, flags=1 << bit | 0x80400, attr=0, alignment=0, size=0x200000,
space=managed)
probe(case, 0x50a0, flags=0x80400, attr=1 << bit, alignment=0, size=0x200000,
space=managed)
probe(case, 0x50a0, flags=0x80400, attr=0, attr2=1 << bit, alignment=0, size=0x200000,
space=managed)
for field in ("fmt", "compression", "zcull", "width", "height", "pitch", "low", "high",
"limit", "address", "ctag", "internal", "tag", "node", "kind"):
probe(case, 0x50a0, flags=0x8c405, attr=0, alignment=0, size=0x200000, space=managed,
**{field: 0x1000})
probe(case, 0x50a0, flags=0x8c405 | 0x20000, attr=0, alignment=0, size=0x200000,
space=managed, low=0x300000000, high=0x3ffffffff)
probe(case, 0x50a0, flags=0x8c405 | 0x20000, attr=0, alignment=0, size=0x200000,
space=managed, low=0x300000000, high=0x3000fffff)
# A bounded space, filled; and a space above 4 GiB.
for size in (0x20000000, 0x20000000, 0x200000, 0x1fc00000, 0x200000, 0x100000):
probe(case, 0x50a0, keep=True, flags=0x8c405, attr=0, alignment=0, size=size,
space=spaces["small"])
for flags in (0x8c405, 0x8c403):
probe(case, 0x50a0, keep=True, flags=flags, attr=0, alignment=0, size=0x200000,
space=spaces["high"])
# The space goes while reservations live in it; then everything.
assert case.free(CLIENT, 0, spaces["small"]) == 0
assert case.free(CLIENT, 0, CLIENT) == 0
return case
def mapping_rules():
"""NV_ESC_RM_MAP_MEMORY, NV_ESC_RM_UNMAP_MEMORY, NV_ESC_RM_UPDATE_DEVICE_MAPPING_INFO
and 0xd01 on memory objects. Descriptors 10..12 are control files, 20..22 device files.
A video memory mapping needs the BAR1 address space, which this fixture lacks: those
requests show how far the original gets without it."""
case = MemorySequence("mem-mapping-rules")
system = dict(flags=0xc001, alignment=0, attr=0x3a000000)
_, buffer = case.memory(0x3e, size=0x5000, **system)
_, combined = case.memory(0x3e, size=0x5000, flags=0xc001, alignment=0, attr=0x5a000000)
_, contiguous = case.memory(0x3e, size=0x5000, flags=0xc001, alignment=0, attr=0x32000000)
_, notifier = case.memory(0x3e, size=0x1000, kind=13, owner=DEVICE, **system)
_, video = case.memory(0x40, size=0x200000)
result, space = case.alloc(CLIENT, DEVICE, 0, 0x90f1,
params=R.vaspace_params(flags=0, base=0x5000000))
_, virtual = case.memory(0x50a0, flags=0x8c415, attr=0, alignment=0, size=0x1000000,
offset=0x5000000, space=space)
assert case.descriptor(0x5c000071, 0x40001010, 0x7f0000200000, 0x1fffff) == 0
for handle in (buffer, combined, contiguous, notifier, video, virtual, space, DEVICE,
SUBDEVICE, CLIENT, 0x5c000071, 0x12345678, 0):
for flags in (0, 0xc0000):
case.address_space(handle, flags)
# Offsets and lengths.
for offset, length in ((0, 0x5000), (0, 0x1000), (0x1000, 0x4000), (0x1000, 0x4001),
(0x4000, 0x1000), (0x5000, 0), (0x5000, 0x1000), (0, 0), (0x10, 0x20),
(0xfff, 2), (0, 0x5001), (0, 1 << 40), ((1 << 64) - 0x1000, 0x2000),
(0x800, 0x4800)):
result, address, _ = case.map(buffer, offset, length, 0, 10)
if result == 0:
assert case.unmap(buffer, address) == 0
# Flags, one bit at a time and the workload's values.
for flags in [1 << bit for bit in range(32)] + [0xc0000, 0xc8000, 3, 2, 0x6000, 0x18000]:
result, address, _ = case.map(buffer, 0, 0x5000, flags, 10)
if result == 0:
assert case.unmap(buffer, address) == 0
# The object kinds, through a control file and through a device file.
for handle in (combined, contiguous, notifier, 0x5c000071, virtual, space, video, DEVICE,
0x12345678):
for descriptor in (10, 20):
result, address, _ = case.map(handle, 0, 0x1000, 0, descriptor)
if result == 0:
assert case.unmap(handle, address) == 0
# The device handle of the request, the descriptor, the calling node and the size.
for device in (SUBDEVICE, CLIENT, buffer, 0, 0x12345678):
result, address, _ = case.map(buffer, 0, 0x5000, 0, 10, device=device)
if result == 0:
assert case.unmap(buffer, address, device=device) == 0
for descriptor in (-1, 0, 99, 11, 20):
result, address, _ = case.map(buffer, 0, 0x5000, 0, descriptor)
if result == 0:
assert case.unmap(buffer, address) == 0
case.map(buffer, 0, 0x5000, 0, 10, node="dev", file=3)
case.map(buffer, 0, 0x5000, 0, 10, size=0x30)
case.map(buffer, 0, 0x5000, 0, 10, file=1)
# The open layer refuses the context (a file that already has one answers 0x63).
os_state["context_status"] = 0x63
case.lines.append("context-status 63")
case.map(buffer, 0, 0x5000, 0, 10)
os_state["context_status"] = 0
case.lines.append("context-status 0")
# Several mappings of one object; unmapping by address.
first = case.map(buffer, 0, 0x5000, 0, 10)[1]
second = case.map(buffer, 0x1000, 0x1000, 0, 11)[1]
third = case.map(buffer, 0, 0x5000, 0, 12)[1]
other = case.map(combined, 0, 0x5000, 0, 10)[1]
# NV_ESC_RM_UPDATE_DEVICE_MAPPING_INFO: the address a mapping is known by.
case.update(buffer, second, 0x7f0000000000)
case.update(buffer, second, 0x7f0000000000, device=DEVICE)
case.update(buffer, 0x7f0000000000, 0x7f0000001000, device=DEVICE)
case.update(buffer, 0x1234000, 0x7f0000002000, device=DEVICE)
case.update(combined, 0x7f0000001000, 0x7f0000002000, device=DEVICE)
case.update(buffer, 0x7f0000001000, first, device=DEVICE)
case.update(buffer, first, second, device=DEVICE)
case.update(buffer, second, second, device=CLIENT)
case.update(0x12345678, second, first, device=DEVICE)
case.unmap(buffer, second + 0x1000)
case.unmap(buffer, other)
case.unmap(combined, first)
case.unmap(buffer, second, flags=0xffffffff)
case.unmap(buffer, second)
case.unmap(buffer, first, device=SUBDEVICE)
case.unmap(buffer, first, file=1)
case.unmap(buffer, first)
case.unmap(buffer, first)
case.unmap(0x12345678, first)
case.update(video, 0, 0x200400000)
case.unmap(buffer, third)
case.unmap(buffer, 0x7f0000001000)
case.unmap(buffer, 0x7f0000000000)
# Objects released while mapped: the object, then the client.
case.map(buffer, 0, 0x5000, 0, 10)
case.map(buffer, 0, 0x2000, 0, 11)
assert case.free(CLIENT, 0, buffer) == 0
case.map(notifier, 0, 0x1000, 0, 10)
assert case.free(CLIENT, 0, CLIENT) == 0
return case
def descriptor_rules():
"""NV_ESC_RM_ALLOC_MEMORY with class 0x71 (NV01_MEMORY_SYSTEM_OS_DESCRIPTOR): user
pages, as the workload registers them."""
case = MemorySequence("mem-descriptor-rules")
address, limit = 0x7f0000200000, 0x1fffff
for flags in (0x40001010, 0x40041010):
assert case.descriptor(0, flags, address, limit) == 0
for bit in range(32):
case.descriptor(0, 0x40001010 ^ 1 << bit, address, limit)
for coherency in range(8):
for physicality in (0, 1):
case.descriptor(0, 0x40000000 | coherency << 12 | physicality << 4, address, limit)
for pointer, last in ((address, 0), (address, 0xfff), (address, 0x1000), (address, 0xffe),
(address + 1, limit), (address + 0x800, limit), (0, limit),
(address, (1 << 64) - 1)):
case.descriptor(0, 0x40001010, pointer, last)
case.descriptor(0x5c000071, 0x40001010, address, limit)
case.descriptor(0x5c000071, 0x40001010, address, limit)
case.descriptor(0, 0x40001010, address, limit, parent=SUBDEVICE)
case.descriptor(0, 0x40001010, address, limit, parent=CLIENT)
case.descriptor(0, 0x40001010, address, limit, parent=0x12345678)
case.descriptor(0, 0x40001010, address, limit, descriptor=10)
case.descriptor(0, 0x40001010, address, limit, node="ctl", file=0)
case.descriptor(0, 0x40001010, address, limit, file=4)
# The operating system refuses to pin the pages.
os_state["lock_status"] = 0x1e
case.lines.append("lock-status 1e")
case.descriptor(0, 0x40001010, address, limit)
os_state["lock_status"] = 0
case.lines.append("lock-status 0")
assert case.free(CLIENT, 0, 0x5c000071) == 0
assert case.free(CLIENT, 0, CLIENT) == 0
return case
def sequences():
cases = []
case, compared, differences = workload_case()
cases.append(case)
for build in (video_rules, video_placement, system_rules, virtual_rules, mapping_rules,
descriptor_rules):
if "--only" in sys.argv and build.__name__ not in sys.argv:
continue
cases.append(build())
return cases, dict(compared=compared, differences=differences)
def main():
cases, workload = sequences()
lines = ["# Original memory-object paths under instruction emulation; see "
"tools/check_rmapi_memory_binary.py", f"# original sha256 {DIGEST}"]
for case in cases:
lines += case.lines
text = "\n".join(lines) + "\n"
target = OUT / "original-rmapi-memory.txt"
if "--check" in sys.argv:
if not target.is_file():
raise SystemExit(f"memory oracle missing: {target}")
if target.read_text() != text:
raise SystemExit(f"memory oracle differs from the checked copy: {target}")
else:
OUT.mkdir(parents=True, exist_ok=True)
target.write_text(text)
kinds = {}
for line in text.splitlines():
if line[:2] in ("A ", "F ", "C ", "M ", "U ", "D ", "G "):
kinds[line[0]] = kinds.get(line[0], 0) + 1
print(json.dumps(dict(original_sha256=DIGEST, oracle=str(target.relative_to(ROOT)),
cases=len(cases), operations=kinds,
os_calls=sum(1 for line in text.splitlines()
if line.startswith("os ")),
workload_against_capture=workload)))
if __name__ == "__main__":
main()