mirror of
https://github.com/QuixiAI/nvdriver.git
synced 2026-12-06 14:38:47 +00:00
725 lines
30 KiB
Python
725 lines
30 KiB
Python
#!/usr/bin/env python3
|
|
"""Run the original RM side of the UVM interface (rm_gpu_ops_*) 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, which this script imports and does not modify):
|
|
|
|
thunks every exported rm_gpu_ops_* symbol: the first call target of the thunk is read
|
|
from the relocated instructions (73 thunks).
|
|
classes _nv028356rm (findDeviceClasses) once per class id of the original's class table
|
|
and of the public class predicates, to obtain the host / copy / compute / fault
|
|
buffer / access counter / SEC2 classification.
|
|
session rm_gpu_ops_create_session -> _nv046789rm (nvGpuOpsCreateSession) ->
|
|
_nv046788rm (nvGpuOpsCreateClient), and rm_gpu_ops_destroy_session ->
|
|
_nv046793rm, (a) against a recording RM API and (b) with nothing replaced
|
|
below them, down to the original resource server ("deep" lines).
|
|
gpu-info rm_gpu_ops_get_gpu_info's inner function _nv046818rm (nvGpuOpsGetGpuInfo) with
|
|
every helper it calls (_nv028356rm, _nv017016rm, _nv029342rm, _nv029343rm,
|
|
_nv018690rm, _nv021659rm, _nv017901rm, _nv054095rm, _nv041838rm, _nv041025rm).
|
|
|
|
Fixture-supplied for the recording runs (everything else is original instructions):
|
|
* rmapiGetInterface (_nv054239rm) returns a table whose slots record the request and
|
|
answer from the case: Alloc (+0x00), Free (+0x18), Control (+0x38), DupObject (+0x50),
|
|
Share (+0x60). The slot offsets are the ones the original instructions call through.
|
|
* gpumgrGetGpuFromUuid (_nv031406rm) returns the case's GPU object or NULL, and
|
|
nv_is_gpu_accessible answers from the case.
|
|
* the GPU object is fixture memory holding only the fields _nv046818rm reads: the
|
|
KernelMIGManager (+0x1fc8), KernelGraphicsManager (+0x1fd0), KernelGraphics[0]
|
|
(+0x2018), KernelMemorySystem (+0x1ec8), MemoryManager (+0x1ed0), KernelNvlink
|
|
(+0x2320) pointers and the property bytes +0x922 and +0x92d.
|
|
|
|
MIG (IS_MIG_IN_USE) cases are not generated: the Rust module refuses that branch.
|
|
"""
|
|
import json
|
|
import random
|
|
import struct
|
|
import sys
|
|
|
|
from unicorn.x86_const import UC_X86_REG_RAX, UC_X86_REG_RIP, UC_X86_REG_RSP
|
|
|
|
import check_rmapi_binary as R
|
|
from rmapi_binary_emulator import BASES, DIGEST, ROOT, STOP
|
|
|
|
E = R.E
|
|
OUT = ROOT / "target/uvm"
|
|
SLOT = STOP + 0x200
|
|
SLOTS = {0: "alloc", 3: "free", 7: "control", 10: "dup", 12: "share"}
|
|
INFO_SIZE = 0xf0
|
|
NVLINK_SIZE = 0x3420
|
|
|
|
|
|
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)
|
|
|
|
|
|
def thunk_table():
|
|
"""First call target of each rm_gpu_ops_* thunk, from the relocated instructions."""
|
|
lines = []
|
|
by_address = {address: name for address, _size, name in E.functions}
|
|
for address, size, name in E.functions:
|
|
if not name.startswith("rm_gpu_ops_"):
|
|
continue
|
|
code = E.read(address, size)
|
|
targets = []
|
|
position = 0
|
|
while position < len(code) - 4:
|
|
if code[position] == 0xe8:
|
|
target = address + position + 5 + struct.unpack_from("<i", code, position + 1)[0]
|
|
if target in by_address:
|
|
targets.append(by_address[target])
|
|
position += 5
|
|
continue
|
|
position += 1
|
|
inner = [target for target in targets if target.startswith("_nv") and
|
|
target not in ("_nv059482rm", "_nv059473rm", "_nv046744rm")]
|
|
assert inner, name
|
|
lines.append(f"thunk {name} {inner[0]}")
|
|
assert len(lines) == 73, len(lines)
|
|
return sorted(lines)
|
|
|
|
|
|
class Api:
|
|
"""The recording RM API of one case."""
|
|
|
|
def __init__(self):
|
|
self.table = E.allocate(0x200)
|
|
for index in range(0x40):
|
|
E.wq(self.table + 8 * index, SLOT + 8 * index)
|
|
self.lines = []
|
|
self.replies = None
|
|
self.next_handle = 0
|
|
self.fail = None
|
|
self.count = 0
|
|
|
|
def begin(self, replies, first_handle, fail=None):
|
|
self.lines, self.replies, self.next_handle = [], replies, first_handle
|
|
self.fail, self.count = fail, 0
|
|
|
|
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 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
|
|
status = self.injected()
|
|
if status is None:
|
|
status = self.replies.get(("alloc", klass), 0)
|
|
handle_out = handle_in
|
|
if status == 0 and handle_in == 0:
|
|
self.next_handle += 1
|
|
handle_out = self.next_handle
|
|
E.wd(a[3], handle_out)
|
|
out = E.read(a[5], size) if params is not None else None
|
|
self.lines.append(
|
|
f"call alloc {client:x} {parent:x} {handle_in:x} {klass:x}"
|
|
f" {sparse(params) if params is not None else '-'} -> {status:x} {handle_out:x}"
|
|
f" {sparse(out) if out is not None else '-'}")
|
|
return status
|
|
|
|
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)
|
|
status = self.injected()
|
|
reply = self.replies.get(command)
|
|
if callable(reply):
|
|
reply = reply(params)
|
|
if command == 0x800201:
|
|
# NV0080_CTRL_CMD_GPU_GET_CLASSLIST: {numClasses, pad, classList pointer}.
|
|
count_in, pointer = struct.unpack("<I4xQ", params)
|
|
classes = reply if reply is not None else []
|
|
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 {client:x} {obj:x} {count_in:x} {1 if pointer else 0}"
|
|
f" -> {status:x} {E.d(a[4]):x} {listed}")
|
|
return status
|
|
if status is None:
|
|
status = 0
|
|
if isinstance(reply, tuple):
|
|
status, reply = reply
|
|
if reply is not None:
|
|
assert len(reply) == size, (hex(command), len(reply), size)
|
|
E.write(a[4], reply)
|
|
self.lines.append(f"call control {client:x} {obj:x} {command:x} {sparse(params)}"
|
|
f" -> {status:x} {sparse(E.read(a[4], size))}")
|
|
return status
|
|
|
|
def free(self, a):
|
|
self.injected()
|
|
self.lines.append(f"call free {a[1] & 0xffffffff:x} {a[2] & 0xffffffff:x} -> 0")
|
|
return 0
|
|
|
|
def share(self, a):
|
|
status = self.injected()
|
|
if status is None:
|
|
status = self.replies.get("share", 0)
|
|
self.lines.append(f"call share {a[1] & 0xffffffff:x} {a[2] & 0xffffffff:x}"
|
|
f" {E.read(a[3], 12).hex()} -> {status:x}")
|
|
return status
|
|
|
|
def other(self, index):
|
|
def run(a):
|
|
raise AssertionError(f"RM API slot {index:#x} is not part of these paths")
|
|
return run
|
|
|
|
|
|
API = None
|
|
|
|
|
|
def install_recording():
|
|
"""Replace the RM API table, the GPU lookup and the access check. The replacements are
|
|
installed before any original instruction runs (hooks added to already translated code
|
|
do not fire) and are switched by `world["recording"]`."""
|
|
global API
|
|
API = Api.__new__(Api)
|
|
API.lines, API.replies, API.next_handle, API.fail, API.count = [], {}, 0, None, 0
|
|
API.table = 0
|
|
for index in range(0x40):
|
|
handler = {0: API.alloc, 3: API.free, 7: API.control, 12: API.share}.get(
|
|
index, API.other(index))
|
|
E.install(SLOT + 8 * index, handler)
|
|
world = {"gpu": 0, "accessible": 1, "recording": False}
|
|
E.install("_nv054239rm", lambda a: API.table if world["recording"] else None)
|
|
E.handlers.pop("_nv054239rm")
|
|
E.install("_nv031406rm", lambda a: world["gpu"] if world["recording"] else None)
|
|
E.handlers.pop("_nv031406rm")
|
|
assert "nv_is_gpu_accessible" not in R.HOOKS
|
|
E.install("nv_is_gpu_accessible", lambda a: world["accessible"])
|
|
return world
|
|
|
|
|
|
def quick_setup():
|
|
"""What the recording cases need of the RM: the port layer (allocator, TLS). The RM API
|
|
itself is replaced, so the resource server is not initialized."""
|
|
E.reset()
|
|
R.state.update(admin=0, diag=[], purge=0, gpu_flags={})
|
|
assert E.call("_nv059519rm") & 0xffffffff == 0
|
|
|
|
|
|
def fresh_table():
|
|
"""E.reset() empties the fixture heap, so the API table is rebuilt per case."""
|
|
API.table = E.allocate(0x200)
|
|
for index in range(0x40):
|
|
E.wq(API.table + 8 * index, SLOT + 8 * index)
|
|
|
|
|
|
# ---------------------------------------------------------------------------------------
|
|
# Sessions.
|
|
|
|
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
|
|
|
|
|
|
def session_cases():
|
|
lines = []
|
|
# (a) recording RM API: every failure position of nvGpuOpsCreateClient.
|
|
for name, fail in (("ok", None), ("alloc-fails", (0, 0x51)), ("alloc-fails-1a", (0, 0x1a)),
|
|
("share-fails", (1, 0x65)), ("share-fails-1b", (1, 0x1b))):
|
|
quick_setup()
|
|
fresh_table()
|
|
API.begin({}, 0xc1d00041, fail)
|
|
stack, out = runtime_stack(), E.allocate(16, 0xa5)
|
|
status = E.call("rm_gpu_ops_create_session", stack, out) & 0xffffffff
|
|
lines.append(f"case session-{name}")
|
|
lines += API.lines
|
|
session = E.q(out)
|
|
if status == 0:
|
|
blob = E.read(session, 0x28)
|
|
handle, devices, lock1, p2p, lock2 = struct.unpack("<I4xQQQQ", blob)
|
|
assert lock1 and lock2
|
|
lines.append(f"ret {status:x} {handle:x} {devices:x} {p2p:x}")
|
|
API.begin({}, 0)
|
|
assert E.call("rm_gpu_ops_destroy_session", stack, session) & 0xffffffff == 0
|
|
lines.append("destroy")
|
|
lines += API.lines
|
|
lines.append("ret 0")
|
|
else:
|
|
assert session == 0xa5a5a5a5a5a5a5a5, hex(session)
|
|
lines.append(f"ret {status:x} - - -")
|
|
assert not R.state["diag"], R.state["diag"]
|
|
# A NULL session is accepted and touches nothing.
|
|
quick_setup()
|
|
fresh_table()
|
|
API.begin({}, 0)
|
|
assert E.call("rm_gpu_ops_destroy_session", runtime_stack(), 0) & 0xffffffff == 0
|
|
assert not API.lines
|
|
lines += ["case session-destroy-null", "ret 0"]
|
|
return lines
|
|
|
|
|
|
def deep_session_cases():
|
|
"""Nothing replaced below the thunks: the original resource server allocates the
|
|
session's client. Three sessions, destroyed out of order, then one more."""
|
|
lines = ["case session-deep"]
|
|
R.setup()
|
|
stack = runtime_stack()
|
|
sessions = []
|
|
for _ in range(3):
|
|
out = E.allocate(16)
|
|
status = E.call("rm_gpu_ops_create_session", stack, out) & 0xffffffff
|
|
handle = E.d(E.q(out))
|
|
sessions.append(E.q(out))
|
|
lines.append(f"deep create -> {status:x} {handle:x}")
|
|
for index in (1, 0):
|
|
R.state["freed"].clear()
|
|
handle = E.d(sessions[index])
|
|
status = E.call("rm_gpu_ops_destroy_session", stack, sessions[index]) & 0xffffffff
|
|
lines.append(f"deep destroy {handle:x} -> {status:x} freed "
|
|
+ ",".join(f"{freed:x}" for freed in R.state["freed"]))
|
|
out = E.allocate(16)
|
|
status = E.call("rm_gpu_ops_create_session", stack, out) & 0xffffffff
|
|
lines.append(f"deep create -> {status:x} {E.d(E.q(out)):x}")
|
|
assert not R.state["diag"], R.state["diag"]
|
|
return lines
|
|
|
|
|
|
# ---------------------------------------------------------------------------------------
|
|
# Class predicates.
|
|
|
|
PUBLIC_CLASSES = (
|
|
0x506f, 0x906f, 0xa06f, 0xa16f, 0xb06f, 0xc06f, 0xc36f, 0xc46f, 0xc56f, 0xc86f, 0xc96f,
|
|
0xca6f, 0xb0b5, 0xc0b5, 0xc1b5, 0xc3b5, 0xc5b5, 0xc6b5, 0xc7b5, 0xc8b5, 0xc9b5, 0xcab5,
|
|
0xb0c0, 0xb1c0, 0xc0c0, 0xc1c0, 0xc3c0, 0xc4c0, 0xc5c0, 0xc6c0, 0xc7c0, 0xcbc0, 0xcdc0,
|
|
0xb069, 0xc369, 0xc365, 0x95a1, 0xcba2, 0xc572, 0xc361, 0xa06c, 0x9067, 0x90f1, 0x2080)
|
|
|
|
|
|
def class_table(world):
|
|
# The original's class table: 279 records of 56 bytes at .data+0xb620, external id first.
|
|
records = E.read(BASES[".data"] + 0xb620, 279 * 56)
|
|
table = [struct.unpack_from("<I", records, 56 * index)[0] for index in range(279)]
|
|
assert table[0] == 0 and 0xc36f in table and 0x2080 in table
|
|
ids = sorted((set(table) | set(PUBLIC_CLASSES)) - {0})
|
|
quick_setup()
|
|
fresh_table()
|
|
outputs = [E.allocate(8) for _ in range(6)]
|
|
lines = []
|
|
for klass in ids:
|
|
API.begin({0x800201: [klass]}, 0)
|
|
for pointer in outputs:
|
|
E.wd(pointer, 0)
|
|
status = E.call("_nv028356rm", 1, 2, outputs[0], outputs[1], outputs[2], outputs[3],
|
|
stack=(outputs[4], outputs[5])) & 0xffffffff
|
|
assert status == 0, (hex(status), hex(klass), API.lines)
|
|
hit = [name for name, pointer in zip("hcmfas", outputs) if E.d(pointer) == klass]
|
|
assert len(hit) <= 1 and all(E.d(pointer) in (0, klass) for pointer in outputs), (
|
|
hex(klass), [hex(E.d(pointer)) for pointer in outputs])
|
|
if hit:
|
|
lines.append(f"class {klass:x} {hit[0]}")
|
|
lines.append("classes-tested " + " ".join(f"{klass:x}" for klass in ids))
|
|
return lines
|
|
|
|
|
|
# ---------------------------------------------------------------------------------------
|
|
# nvGpuOpsGetGpuInfo.
|
|
|
|
V100_CLASSES = (0x2, 0x4, 0x5, 0x30, 0x3d, 0x3e, 0x3f, 0x40, 0x41, 0x70, 0x71, 0x73, 0x7d,
|
|
0x80, 0x2080, 0x208f, 0x402c, 0x503b, 0x503c, 0x5070, 0x5080, 0x50a0, 0x9010,
|
|
0x9067, 0x9072, 0x9074, 0x90cd, 0x90cc, 0x90e0, 0x90e1, 0x90e6, 0x90e7, 0x90f1,
|
|
0xa06c, 0xa081, 0xb0b6, 0xc361, 0xc365, 0xc369, 0xc36f, 0xc397, 0xc3b0,
|
|
0xc3b5, 0xc3b7, 0xc3c0, 0xc3e0, 0xc3fa, 0xc3fd)
|
|
|
|
|
|
def gpu_object(view):
|
|
"""Fixture GPU holding the fields _nv046818rm reads."""
|
|
gpu = E.allocate(0x6000)
|
|
E.wb(gpu + 0x922, view["ats"])
|
|
E.wb(gpu + 0x92d, view["mig_supported"])
|
|
if view["mig_manager"]:
|
|
mig = E.allocate(0x4000)
|
|
E.wq(gpu + 0x1fc8, mig)
|
|
manager = E.allocate(0x400)
|
|
E.wq(gpu + 0x1fd0, manager)
|
|
E.wb(manager + 0x298, view["gr_initialized"])
|
|
if view["gr_info"] is not None:
|
|
info = E.allocate(0x200)
|
|
E.wq(manager + 0x290, info)
|
|
E.wd(info + 0xbc, view["gr_info"][0])
|
|
E.wd(info + 0xa4, view["gr_info"][1])
|
|
E.wd(manager + 0x110, view["gpc_mask"])
|
|
graphics = E.allocate(0x600)
|
|
E.wq(gpu + 0x2018, graphics)
|
|
if view["kgr_static"] is not None:
|
|
static = E.allocate(0x40)
|
|
E.wq(graphics + 0x1c0, static)
|
|
E.wb(static, view["kgr_static"][0])
|
|
table = E.allocate(0x200)
|
|
E.wq(static + 8, table)
|
|
E.wd(table + 0x4c, view["kgr_static"][1])
|
|
if view["memory_system"] is not None:
|
|
system = E.allocate(0x600)
|
|
E.wq(gpu + 0x1ec8, system)
|
|
E.wq(system + 0x458, view["memory_system"][0])
|
|
E.wq(system + 0x460, view["memory_system"][1])
|
|
memory = E.allocate(0xd10)
|
|
E.wq(gpu + 0x1ed0, memory)
|
|
E.wq(memory + 0x448, view["egm_base"])
|
|
if view["nvlink"] is not None:
|
|
nvlink = E.allocate(0x16b8)
|
|
E.wq(gpu + 0x2320, nvlink)
|
|
for offset, value in zip((0x1648, 0x1650, 0x1658), view["nvlink"]):
|
|
E.wq(nvlink + offset, value)
|
|
return gpu
|
|
|
|
|
|
def default_view():
|
|
return dict(found=1, accessible=1, ats=0, mig_supported=0, mig_manager=1, gr_initialized=1,
|
|
gr_info=(5, 6), gpc_mask=0x3f, kgr_static=(1, 80), memory_system=(0, 0),
|
|
egm_base=0, nvlink=(0xffffffffffffffff,) * 3)
|
|
|
|
|
|
def view_line(view):
|
|
def pair(value):
|
|
return "-" if value is None else ",".join(f"{item:x}" for item in value)
|
|
return (f"gpu {view['found']} {view['accessible']} {view['ats']} {view['mig_supported']}"
|
|
f" {view['mig_manager']} {view['gr_initialized']} {pair(view['gr_info'])}"
|
|
f" {view['gpc_mask']:x} {pair(view['kgr_static'])} {pair(view['memory_system'])}"
|
|
f" {view['egm_base']:x} {pair(view['nvlink'])}")
|
|
|
|
|
|
def info_v2(data):
|
|
"""NV2080_CTRL_GPU_GET_INFO_V2 reply: the request with the first entry's data set."""
|
|
def run(params):
|
|
reply = bytearray(params)
|
|
struct.pack_into("<I", reply, 8, data[struct.unpack_from("<I", params, 4)[0]])
|
|
return bytes(reply)
|
|
return run
|
|
|
|
|
|
def bus_info(data, statuses=None):
|
|
def run(params):
|
|
index = struct.unpack_from("<I", params, 4)[0]
|
|
reply = bytearray(params)
|
|
struct.pack_into("<I", reply, 8, data.get(index, 0))
|
|
if statuses and index in statuses:
|
|
return statuses[index], bytes(reply)
|
|
return bytes(reply)
|
|
return run
|
|
|
|
|
|
def fb_info(count):
|
|
def run(params):
|
|
reply = bytearray(params)
|
|
struct.pack_into("<I", reply, 8, count)
|
|
return bytes(reply)
|
|
return run
|
|
|
|
|
|
def nvlink_status(links, mask=0, vector=0, junk=None):
|
|
"""NV2080_CTRL_CMD_NVLINK_GET_NVLINK_STATUS reply (0x3420 bytes). `links`: index ->
|
|
(connected, loop, remote type, version, line rate, caps)."""
|
|
reply = bytearray(junk.randbytes(NVLINK_SIZE) if junk else NVLINK_SIZE)
|
|
struct.pack_into("<I4xQQ", reply, 0, mask, junk.getrandbits(64) if junk else 0, vector)
|
|
for index in range(64):
|
|
base = 0x20 + 0xd0 * index
|
|
connected, loop, remote, version, rate, caps = links.get(index, (0, 0, 0, 0, 0, 0))
|
|
reply[base] = caps
|
|
reply[base + 0xf] = version
|
|
struct.pack_into("<I", reply, base + 0x24, rate)
|
|
reply[base + 0x38] = connected
|
|
reply[base + 0x39] = loop
|
|
struct.pack_into("<Q", reply, base + 0x78, remote)
|
|
return bytes(reply)
|
|
|
|
|
|
def uuid_info(device, subdevice, gpu_id=0xb300):
|
|
def run(params):
|
|
reply = bytearray(params)
|
|
struct.pack_into("<III", reply, 0x104, gpu_id, device, subdevice)
|
|
return bytes(reply)
|
|
return run
|
|
|
|
|
|
def default_replies():
|
|
name = bytearray(0x84)
|
|
name[4:4 + 10] = b"Tesla V100"
|
|
return {
|
|
0x274: uuid_info(0, 0),
|
|
0x20801701: struct.pack("<IIII", 0x140, 0, 0xa1, 0),
|
|
0x20800110: bytes(name),
|
|
0x800289: struct.pack("<II", 0, 0),
|
|
0x800201: list(V100_CLASSES),
|
|
0x800280: struct.pack("<I", 1),
|
|
0x20801303: fb_info(1),
|
|
0x20800119: struct.pack("<I", 0),
|
|
0xcb330101: bytes(6),
|
|
0x20801823: bus_info({0x33: 0, 0x3: 3 | 16 << 4}),
|
|
0x20803002: (0x56, bytes(NVLINK_SIZE)),
|
|
0x20800102: info_v2({0x3a: 0, 0x30: 0, 0x42: 0, 0x44: 0}),
|
|
}
|
|
|
|
|
|
def gpu_info_case(name, view, replies, fail=None, uuid=None, client=(0, 0)):
|
|
quick_setup()
|
|
fresh_table()
|
|
WORLD["gpu"] = gpu_object(view) if view["found"] else 0
|
|
WORLD["accessible"] = view["accessible"]
|
|
uuid = uuid or bytes(range(0x10, 0x20))
|
|
pointer, info, client_info = E.allocate(16), E.allocate(INFO_SIZE, 0xa5), E.allocate(8)
|
|
E.write(pointer, uuid)
|
|
E.write(client_info, struct.pack("<II", *client))
|
|
API.begin(replies, 0xc1d00041, fail)
|
|
status = E.call("rm_gpu_ops_get_gpu_info", runtime_stack(), pointer, client_info,
|
|
info) & 0xffffffff
|
|
lines = [f"case gpu-info-{name}", view_line(view),
|
|
f"args {uuid.hex()} {client[0]:x} {client[1]:x}"]
|
|
lines += API.lines
|
|
lines.append(f"ret {status:x} {E.read(info, INFO_SIZE).hex()}")
|
|
lines.append("asserts " + (",".join(R.state["diag"]) or "-"))
|
|
R.state["diag"].clear()
|
|
return lines, len(API.lines)
|
|
|
|
|
|
def gpu_info_cases():
|
|
rng = random.Random(0x5701)
|
|
lines = []
|
|
|
|
def add(name, view=None, replies=None, **keywords):
|
|
case, calls = gpu_info_case(name, view or default_view(), replies or default_replies(),
|
|
**keywords)
|
|
lines.extend(case)
|
|
return calls
|
|
|
|
calls = add("v100")
|
|
# Every RM API call of the default path fails in turn (0x56 has a rule of its own for
|
|
# the NVLINK status query, so both a plain error and NOT_SUPPORTED are injected).
|
|
for index in range(calls):
|
|
for status in (0x65, 0x56):
|
|
add(f"fail-{index}-{status:x}", fail=(index, status))
|
|
view = default_view()
|
|
view["found"] = 0
|
|
add("uuid-not-found", view)
|
|
view = default_view()
|
|
view["accessible"] = 0
|
|
add("not-accessible", view)
|
|
# Instances and identity come back from the UUID query.
|
|
replies = default_replies()
|
|
replies[0x274] = uuid_info(3, 1)
|
|
replies[0x20801701] = struct.pack("<IIII", 0x150, 4, 0xb1, 7)
|
|
replies[0x800280] = struct.pack("<I", 2)
|
|
replies[0x20801303] = fb_info(0)
|
|
replies[0x20800119] = struct.pack("<I", 1)
|
|
name = bytearray(rng.randbytes(0x84))
|
|
replies[0x20800110] = bytes(name) # unterminated name
|
|
add("identity", replies=replies, uuid=rng.randbytes(16), client=(0xc1d00002, 0x5c000007))
|
|
for length in (0, 1, 0x3e, 0x3f, 0x40, 0x41):
|
|
replies = default_replies()
|
|
name = bytearray(0x84)
|
|
name[4:4 + length] = bytes([0x41 + index % 26 for index in range(length)])
|
|
replies[0x20800110] = bytes(name)
|
|
add(f"name-{length:x}", replies=replies)
|
|
# Class lists.
|
|
for label, classes in (("none", []), ("only-skipped", [0xc572]),
|
|
("all", sorted(set(PUBLIC_CLASSES) | set(V100_CLASSES))),
|
|
("reversed", sorted(PUBLIC_CLASSES, reverse=True)),
|
|
("no-host", [0xc3b5, 0xc3c0]), ("pascal", [0xc06f, 0xc0b5, 0xc0c0])):
|
|
replies = default_replies()
|
|
replies[0x800201] = classes
|
|
add(f"classes-{label}", replies=replies)
|
|
# Virtualization mode: only VGX (2) asks the vGPU device for its capability bits.
|
|
for mode in (1, 3, 4, 0xffffffff):
|
|
replies = default_replies()
|
|
replies[0x800289] = struct.pack("<II", mode, 0)
|
|
add(f"virt-{mode:x}", replies=replies)
|
|
for bits in (0, 0x800, 0x80000, 0x80800, 0xfff7f7ff, 0xffffffff):
|
|
replies = default_replies()
|
|
replies[0x800289] = struct.pack("<II", 2, 0)
|
|
config = bytearray(rng.randbytes(0x48))
|
|
struct.pack_into("<I", config, 0x34, bits)
|
|
replies[0xa0800301] = bytes(config)
|
|
calls = add(f"vgx-{bits:x}", replies=replies)
|
|
for index in range(calls):
|
|
replies = default_replies()
|
|
replies[0x800289] = struct.pack("<II", 2, 0)
|
|
replies[0xa0800301] = bytes(0x48)
|
|
add(f"vgx-fail-{index}", replies=replies, fail=(index, 0x65))
|
|
# Confidential computing capabilities and the key rotation state.
|
|
for feature in range(4):
|
|
for multi in range(3):
|
|
for rotation in range(5):
|
|
if feature in (0, 3) and multi != 1 and rotation:
|
|
continue
|
|
if feature == 1 and (multi or rotation):
|
|
continue
|
|
replies = default_replies()
|
|
caps = bytearray(6)
|
|
caps[3], caps[5] = feature, multi
|
|
caps[0], caps[1], caps[2], caps[4] = rng.randbytes(4)
|
|
replies[0xcb330101] = bytes(caps)
|
|
replies[0xcb33010c] = lambda params, rotation=rotation: params[:4] + struct.pack(
|
|
"<I", rotation)
|
|
calls = add(f"cc-{feature}-{multi}-{rotation}", replies=replies)
|
|
replies = default_replies()
|
|
replies[0xcb330101] = bytes([0, 0, 0, 2, 0, 0])
|
|
replies[0xcb33010c] = lambda params: params[:4] + struct.pack("<I", 1)
|
|
calls = add("cc-enabled", replies=replies)
|
|
for index in range(calls):
|
|
add(f"cc-fail-{index}", replies=dict(replies), fail=(index, 0x65))
|
|
# System memory link: PCIe capabilities.
|
|
for speed in range(16):
|
|
for width in (0, 1, 8, 16, 32, 63):
|
|
replies = default_replies()
|
|
replies[0x20801823] = bus_info({0x33: 0, 0x3: speed | width << 4 | rng.getrandbits(
|
|
22) << 10})
|
|
add(f"pcie-{speed:x}-{width:x}", replies=replies)
|
|
for kind in (3, 4, 0xffffffff):
|
|
replies = default_replies()
|
|
replies[0x20801823] = bus_info({0x33: kind})
|
|
add(f"sysmem-kind-{kind:x}", replies=replies)
|
|
# C2C.
|
|
for up, remote, links, rate in ((1, 1, 2, 5000), (0, 1, 2, 5000), (1, 2, 2, 5000),
|
|
(1, 1, 0xffff, 0x10001), (2, 1, 1, 1)):
|
|
replies = default_replies()
|
|
replies[0x20801823] = bus_info({0x33: 2})
|
|
c2c = bytearray(rng.randbytes(0x1c))
|
|
c2c[0] = up
|
|
struct.pack_into("<I", c2c, 4, links)
|
|
struct.pack_into("<I", c2c, 0x10, rate)
|
|
struct.pack_into("<I", c2c, 0x18, remote)
|
|
replies[0x2080182b] = bytes(c2c)
|
|
calls = add(f"c2c-{up}-{remote}-{links:x}", replies=replies)
|
|
for index in range(calls):
|
|
replies = default_replies()
|
|
replies[0x20801823] = bus_info({0x33: 2})
|
|
c2c = bytearray(0x1c)
|
|
c2c[0] = 1
|
|
struct.pack_into("<III", c2c, 4, 1, 0, 0)
|
|
struct.pack_into("<I", c2c, 0x18, 1)
|
|
replies[0x2080182b] = bytes(c2c)
|
|
add(f"c2c-fail-{index}", replies=replies, fail=(index, 0x65))
|
|
# NVLINK status: the three scans (NPU for system memory, switch, GPU peers).
|
|
def links(kind):
|
|
table = {}
|
|
for index in rng.sample(range(64), rng.randrange(1, 12)):
|
|
table[index] = (rng.choice((0, 1, 1, 1)), rng.choice((0, 0, 0, 1)),
|
|
kind if rng.random() < 0.7 else rng.randrange(0, 5),
|
|
rng.choice((0xff, 1, 2, 3, 4, 5, 6, 7, 8)),
|
|
rng.randrange(0, 200000), rng.getrandbits(8))
|
|
return table
|
|
|
|
for number in range(48):
|
|
kind = (1, 2, 3)[number % 3]
|
|
table = links(kind)
|
|
if number % 4 == 0:
|
|
# One version on every matching link, as real hardware reports.
|
|
version = rng.choice((1, 2, 3, 4, 5, 6, 7, 8))
|
|
table = {index: (c, l, r, version, rate, caps)
|
|
for index, (c, l, r, _v, rate, caps) in table.items()}
|
|
mask = 0
|
|
vector = 0
|
|
for index in table:
|
|
if index < 32 and rng.random() < 0.6:
|
|
mask |= 1 << index
|
|
elif rng.random() < 0.8:
|
|
vector |= 1 << index
|
|
replies = default_replies()
|
|
replies[0x20803002] = nvlink_status(table, mask, vector, rng if number % 2 else None)
|
|
replies[0x20801823] = bus_info({0x33: 1 if kind == 1 else 0, 0x3: 3 | 16 << 4})
|
|
view = default_view()
|
|
view["nvlink"] = None if number % 5 == 0 else tuple(
|
|
rng.choice((0xffffffffffffffff, rng.getrandbits(47))) for _ in range(3))
|
|
calls = add(f"nvlink-{number}", view, replies)
|
|
replies = default_replies()
|
|
replies[0x20803002] = nvlink_status({3: (1, 0, 1, 2, 25781, 0x10)}, 8, 0)
|
|
replies[0x20801823] = bus_info({0x33: 1})
|
|
calls = add("nvlink-npu", replies=replies)
|
|
for index in range(calls):
|
|
for status in (0x65, 0x56):
|
|
add(f"nvlink-npu-fail-{index}-{status:x}", replies=dict(replies), fail=(index, status))
|
|
# GPU object state.
|
|
for label, edit in (
|
|
("ats", dict(ats=1, memory_system=(0x8000000000, 0x9000000000))),
|
|
("ats-wrap", dict(ats=1, memory_system=(0x9000000000, 0x10))),
|
|
("ats-off-window", dict(ats=0, memory_system=(0x1000, 0x2000))),
|
|
("no-memory-system", dict(memory_system=None)),
|
|
("gr-uninitialized", dict(gr_initialized=0)),
|
|
("gr-no-info", dict(gr_info=None)),
|
|
("gr-masks", dict(gr_info=(0x12345678, 0x9abcdef0), gpc_mask=0xf0f0f0f1,
|
|
kgr_static=(1, 0xdeadbeef))),
|
|
("gr-static-flag-clear", dict(kgr_static=(0, 77))),
|
|
("gr-static-absent", dict(kgr_static=None)),
|
|
("no-mig-manager", dict(mig_manager=0, mig_supported=1)),
|
|
("mig-supported-idle", dict(mig_manager=1, mig_supported=1)),
|
|
("egm-base", dict(egm_base=0x123456789abc))):
|
|
view = default_view()
|
|
view.update(edit)
|
|
add(f"state-{label}", view)
|
|
# GPU_GET_INFO_V2 answers.
|
|
for egm, ats, non_pasid, cdmm in ((1, 1, 1, 1), (0x301, 2, 2, 2), (0xffffffff, 0, 3, 0),
|
|
(0x1f00, 1, 0, 3), (2, 0xffffffff, 1, 2)):
|
|
replies = default_replies()
|
|
replies[0x20800102] = info_v2({0x3a: egm, 0x30: ats, 0x42: non_pasid, 0x44: cdmm})
|
|
add(f"info-{egm:x}-{ats:x}-{non_pasid:x}-{cdmm:x}", replies=replies)
|
|
return lines
|
|
|
|
|
|
WORLD = None
|
|
|
|
|
|
def main():
|
|
global WORLD
|
|
lines = ["# Original RM side of the UVM interface under instruction emulation; see "
|
|
"tools/check_uvm_gpu_ops_binary.py", f"# original sha256 {DIGEST}"]
|
|
WORLD = install_recording()
|
|
lines += thunk_table()
|
|
lines += deep_session_cases()
|
|
WORLD["recording"] = True
|
|
lines += class_table(WORLD)
|
|
lines += session_cases()
|
|
lines += gpu_info_cases()
|
|
text = "\n".join(lines) + "\n"
|
|
target = OUT / "original-gpu-ops.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)
|
|
import hashlib
|
|
print(json.dumps(dict(
|
|
original_sha256=DIGEST, oracle=str(target.relative_to(ROOT)),
|
|
oracle_sha256=hashlib.sha256(text.encode()).hexdigest(),
|
|
thunks=sum(line.startswith("thunk ") for line in lines),
|
|
classified_classes=sum(line.startswith("class ") for line in lines),
|
|
cases=sum(line.startswith("case ") for line in lines),
|
|
rm_api_calls=sum(line.startswith("call ") for line in lines))))
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|