Files
nvdriver/tools/check_rmapi_channel_binary.py
nvidia-driver-rs 4526e6a816 Baseline: validated 30/30 tree with passing Level 7 hardware regression
- Updated tools/post_reboot.sh to check kernel oops taint bit and stuck driver tasks instead of <86400s uptime
- Level 7 hardware regression passed on 0000:b3:00.0 (module 37e6fa430835eee2b426019db3ad70eeb7a9e9070c09c84bd9b973cf56cbe529, 107 inventory words, 0 static mismatches, CUDA baseline verified before and after)
- Updated .gitignore to exclude build archives (*.a, *.rlib), __pycache__, and raw trace dumps
2026-11-23 23:48:38 +00:00

1731 lines
81 KiB
Python

#!/usr/bin/env python3
"""Run the original's channel-object paths and write an oracle for the Rust `rmapi` channel
slice (userspace interface slice 6).
This extends the memory fixture of tools/check_rmapi_memory_binary.py (same emulator, same
GPU object built by the original's own probe and attach, same heap and allocator) and uses
the UVM slice-2 fixture of tools/check_uvm_gpu_ops2_binary.py for the page directory. Both
are imported and not modified.
RECORD GRAMMAR (target/rmapi/original-rmapi-channel.txt). One line per item, fields separated
by single spaces, all numbers hexadecimal without prefix unless stated.
# ... comment
case <name> a new world (fresh emulator state); everything up to the
next `case` belongs to it
fixture <text> a fixture decision of this case (free text)
gpu/registers/attach-*/sweep*/initialized/stage*/regions/reserved/R ...
world construction lines of the earlier harnesses (formats in
tools/check_rmapi_binary.py and check_rmapi_memory_binary.py)
op/call/ret/registers/asserts lines of the UVM slice-2 harness (rm_gpu_ops entry points;
formats in tools/check_uvm_gpu_ops2_binary.py)
note <text> free text for the reader, not data
A|F|C <node> <file> <request> <params|-> -> <status> <reply> <params_out|-> <diag|->
one escape through `_nv000800rm` (NV_ESC_RM_ALLOC 0x2b,
NV_ESC_RM_FREE 0x29, NV_ESC_RM_CONTROL 0x2a) as in the earlier
records. For `F` two lines `purged <n>` and `freed <h,..|->`
follow first (resources destroyed, in destruction order).
Every line after a request line and before the next request/case/note line is an EVENT
of that request, in the order the original produced it:
r <offset> <value> BAR0 register read and the value the fixture answered
w <offset> <value> BAR0 register write (recorded, not applied unless the case
names a register model in a `fixture` line)
os <call> ... operating-system boundary call (formats of the memory record)
bar2 map <phys> <size> <flags> the original mapped a framebuffer descriptor through
KernelBus+0x120 (`_nv039492rm`, kbusMapRmAperture): physical
address of its first byte, descriptor size, caller flags
bar2 unmap <phys> <flags> KernelBus+0x130 (`_nv039620rm`)
bar2 remap <phys> KernelBus+0x128 (`_nv039648rm`)
bar2 pte <space> <phys> <va> <size> <flags>
KernelBus+0x138 (`_nv039638rm`, the BAR2 page-table update):
descriptor address space (1 system, 2 framebuffer), physical
address of the descriptor, BAR2 virtual address, size, flags
m <space> <base> <offset> <size> <value>
a store instruction of the original into mapped memory:
space `fb` (framebuffer physical addresses) or `sys` (system
memory, fabricated page addresses); base is the physical
address of the mapping the byte belongs to (the argument of the
last `bar2 map` / `os kernel-map` covering it), offset is
relative to base, size is 1, 2, 4 or 8, value the integer stored
fill <space> <base> <offset> <length> <byte>
os_mem_set into mapped memory
copy <space> <base> <offset> <hex bytes>
os_mem_copy / user copy into mapped memory
E <node> <file> <escape> <request> -> <status> <reply> <diag|->
NV_ESC_ALLOC_OS_EVENT / NV_ESC_FREE_OS_EVENT through the
original's rm_ioctl; followed by `events <records> <byte>`
(see `event_cases`)
workload-compare / workload-difference
comparison of the replayed capture with the captured replies
(see `workload_case`)
engine-table ... the static engine table (format of the GPU record)
process <pid> the calling process from here on (default 1092 = 4242)
list <handles> <chids> nested user buffers of 0x80170d (hex bytes, little-endian
u32 each): the handle list sent and the channel list written;
in the C line the two user pointers appear as 0x2000, 0x3000
State lines the harness reads from the original's objects after a request (not events):
tsg <handle> <grpID> <runlistId> <chanCount> <engineType field> <timeslice us>
<bLegacyMode> <bRunlistAssigned> <tsgUniqueId>
after a successful 0xa06c and wherever a case asks
chan <handle> <ChID> <runlistId> <VEID> <cid> <bIsContextBound> <instance block phys>
<USERD phys> <cid in the reply (params +0x84)>
after a successful 0xc36f
image <name> <phys> <sparse> final content of a mapped region after the request, in the
`len:off=hex,...` form of the UVM record (zero bytes omitted)
See the progress file analysis/closed-driver-580/rmapi-channel-slice-progress.md for the
findings. Fixture decisions that bound every claim of the record are the `fixture` lines of
each case and the list below.
FIXTURE DECISIONS (beyond the two imported harnesses)
1. Stage bodies run in front of every case, each to status 0 through `GpuSequence.stage`:
the seven memory bodies, then KernelFifo StateInitLocked `_nv040424rm` and OBJFIFO
StateInitLocked `_nv028307rm` (channel-id manager, engine table, one scheduler owner per
runlist with its two runlist buffers allocated on the original heap).
2. BAR2 is not set up (KernelBus StateInitLocked does not run). The three KernelBus
functions that map a framebuffer descriptor for the CPU and the BAR2 page-table update
are replaced by recorders (lines `bar2 ...`); a mapping returns a pointer into fixture
memory that stands for the framebuffer, so every store of the original is seen with its
physical address. Unwritten framebuffer bytes read 0.
3. System memory the original maps (nv_alloc_kernel_mapping) is fixture memory at a fixed
window, so stores into notifiers and method buffers are seen (space `sys`).
4. os_flush_cpu_write_combine_buffer and os_flush_cpu_cache_all return 0.
"""
import hashlib
import json
import struct
import sys
from unicorn import UC_HOOK_CODE, UC_HOOK_MEM_WRITE
from unicorn.x86_const import UC_X86_REG_RDI, UC_X86_REG_RSI
import check_rmapi_memory_binary as M
import check_uvm_gpu_ops2_binary as U
R, E = M.R, M.E
ROOT, OUT, DIGEST = M.ROOT, M.OUT, M.DIGEST
state, gpu_state, os_state = M.state, M.gpu_state, M.os_state
CLIENT, DEVICE, SUBDEVICE = M.CLIENT, M.DEVICE, M.SUBDEVICE
PAGE = 0x1000
TARGET = OUT / "original-rmapi-channel.txt"
R.STAGE_BODIES.update({
"kfifo-init": (0x22d0, 1, "_nv040424rm", ()), # KernelFifo StateInitLocked
"ofifo-init": (0x22d8, 1, "_nv028307rm", ()), # OBJFIFO StateInitLocked
})
FIFO_STAGES = ("kfifo-init", "ofifo-init")
TIMER = {0x9400: 0x89abcde0, 0x9410: 0x01234567}
# Fixture windows: emulator address = window + physical address.
FB_WINDOW, FB_SPAN = 0x100000000000, 0x800000000
SYS_WINDOW, SYS_SPAN = 0x200000000000, 0x4000000000
windows = {"fb": dict(base=FB_WINDOW, pages=set(), maps=[]),
"sys": dict(base=SYS_WINDOW, pages=set(), maps=[])}
def events():
return os_state["events"]
def window_map(space, physical, size):
"""Back [physical, physical + size) of a window with zeroed fixture memory."""
window = windows[space]
first, last = physical & ~(PAGE - 1), (physical + size + PAGE - 1) & ~(PAGE - 1)
for page in range(first, last, PAGE):
if page not in window["pages"]:
E.cpu.mem_map(window["base"] + page, PAGE)
window["pages"].add(page)
return window["base"] + physical
def window_reset():
for window in windows.values():
for page in window["pages"]:
E.cpu.mem_unmap(window["base"] + page, PAGE)
window["pages"].clear()
window["maps"].clear()
def window_of(address):
"""(space, physical, base of the covering mapping) of an emulator address, or None."""
for space, window in windows.items():
physical = address - window["base"]
if 0 <= physical < (FB_SPAN if space == "fb" else SYS_SPAN):
for base, size in reversed(window["maps"]):
if base <= physical < base + size:
return space, physical, base
return space, physical, physical & ~(PAGE - 1)
return None
def store(emu, access, address, size, value, unused):
space, physical, base = window_of(address)
events().append(f"m {space} {base:x} {physical - base:x} {size:x}"
f" {value & ((1 << 8 * size) - 1):x}")
E.cpu.hook_add(UC_HOOK_MEM_WRITE, store, begin=FB_WINDOW, end=FB_WINDOW + FB_SPAN - 1)
E.cpu.hook_add(UC_HOOK_MEM_WRITE, store, begin=SYS_WINDOW, end=SYS_WINDOW + SYS_SPAN - 1)
def replace(name, handler):
"""Replace a fixture of the imported harnesses (open-layer symbol) by another."""
if name in R.HOOKS:
E.cpu.hook_del(R.HOOKS[name])
R.HOOKS[name] = E.install(name, handler)
def fill(a):
where = window_of(a[0])
if where:
space, physical, base = where
events().append(f"fill {space} {base:x} {physical - base:x} {a[2] & 0xffffffff:x}"
f" {a[1] & 0xff:x}")
return R.fill(a)
def copy(a):
where = window_of(a[0])
if where:
space, physical, base = where
events().append(f"copy {space} {base:x} {physical - base:x}"
f" {E.read(a[1], a[2] & 0xffffffff).hex()}")
return R.copy(a)
def user_copy(a):
copy(a)
return 0
for _name, _handler in (("os_mem_set", fill), ("os_mem_copy", copy),
("os_memcpy_from_user", user_copy), ("os_memcpy_to_user", user_copy)):
replace(_name, _handler)
for _name in ("os_flush_cpu_write_combine_buffer", "os_flush_cpu_cache_all"):
E.install(_name, lambda a: 0)
class Pages(dict):
"""os_state["pages"] of the memory harness: an allocation of at most 1 MiB gets its
kernel-mapping backing in the system-memory window at its fabricated address."""
def __setitem__(self, cookie, record):
if record.get("backing") is None and record["bytes"] <= 0x100000:
record["backing"] = window_map("sys", record["base"], record["bytes"])
windows["sys"]["maps"].append((record["base"], record["bytes"]))
super().__setitem__(cookie, record)
# Memory descriptor fields (MEMORY_DESCRIPTOR of this build): +0x8 flags (0x400 contiguous),
# +0x30 size, +0x60 offset inside the parent, +0x70 address space, +0xd0 parent, +0x178
# first page address.
def descriptor(memdesc):
offset, root = 0, memdesc
while E.q(root + 0xd0):
offset += E.q(root + 0x60)
root = E.q(root + 0xd0)
own = E.q(memdesc + 0x178)
physical = E.q(root + 0x178) + offset
if root != memdesc:
# A sub-descriptor carries the address of its first page; the byte offset inside
# that page is the parent offset's low bits.
assert own == physical & ~(PAGE - 1), (hex(own), hex(physical))
return E.d(memdesc + 0x70), physical, E.q(memdesc + 0x30)
def bar2_map(a):
"""KernelBus+0x120 `_nv039492rm`(gpu, kbus, memdesc, flags): CPU pointer."""
space, physical, size = descriptor(a[2])
assert space == 2, space
windows["fb"]["maps"].append((physical, size))
events().append(f"bar2 map {physical:x} {size:x} {a[3] & 0xffffffff:x}")
return window_map("fb", physical, size)
def bar2_remap(a):
"""KernelBus+0x128 `_nv039648rm`(gpu, kbus, memdesc, pointer): the pointer."""
space, physical, size = descriptor(a[2])
events().append(f"bar2 remap {physical:x}")
return a[3]
def bar2_unmap(a):
"""KernelBus+0x130 `_nv039620rm`(gpu, kbus, memdesc, &pointer, flags)."""
space, physical, size = descriptor(a[2])
events().append(f"bar2 unmap {physical:x} {a[4] & 0xffffffff:x}")
return 0
def bar2_update(a):
"""KernelBus+0x138 `_nv039638rm`(gpu, kbus, memdesc, va, size, flags)."""
space, physical, size = descriptor(a[2])
events().append(f"bar2 pte {space:x} {physical:x} {a[3]:x} {a[4]:x} {a[5] & 0xffffffff:x}")
return 0
BAR2_SLOTS = {0x120: ("_nv039492rm", bar2_map), 0x128: ("_nv039648rm", bar2_remap),
0x130: ("_nv039620rm", bar2_unmap), 0x138: ("_nv039638rm", bar2_update)}
# Installed before any original instruction runs (a hook added to translated code does not
# fire); the world checks that these are the functions in the KernelBus object.
for _slot, (_name, _handler) in BAR2_SLOTS.items():
E.install(_name, _handler)
E.handlers.pop(_name)
# Object pointers of the constructors, by entry hook: `_nv039884rm` kchangrpapiConstruct,
# `_nv039920rm` kchannelConstruct, `_nv040060rm` kctxshareapiConstruct.
constructed = {"group": [], "channel": [], "share": []}
for _kind, _name in (("group", "_nv039884rm"), ("channel", "_nv039920rm"),
("share", "_nv040060rm")):
E.cpu.hook_add(UC_HOOK_CODE, lambda emu, address, size, kind: constructed[kind].append(
emu.reg_read(UC_X86_REG_RDI)), _kind, begin=E.by_name[_name], end=E.by_name[_name])
graphics = {"stub": False, "case": None}
def graphics_info(emu, address, size, unused):
"""Entry of `_nv041022rm`(gpu, KernelGraphics, index): returns KernelGraphics+0x1e0 +
0x60 * index, or NULL when that pointer is NULL. `_nv041157rm` (reached when a channel
whose runlist is the graphics runlist is freed) reads byte +0x50 of the result without a
NULL test. On this fixture the pointer is NULL because no KernelGraphics stage body ran.
A case that says so (`fixture graphics-info-stub`) gets a zeroed block of 8 records
there, so that the free path continues with "nothing to unmap"."""
kgraphics = emu.reg_read(UC_X86_REG_RSI)
if graphics["stub"] and E.q(kgraphics + 0x1e0) == 0:
E.wq(kgraphics + 0x1e0, E.allocate(0x60 * 8))
E.cpu.hook_add(UC_HOOK_CODE, graphics_info, begin=E.by_name["_nv041022rm"],
end=E.by_name["_nv041022rm"])
U.install()
class Accesses(list):
"""gpu_state["read"] / ["written"] during a request: every access becomes an event."""
def tsg_params(error=0, ecc=0, space=0, engine=1, plugin=0):
"""NV_CHANNEL_GROUP_ALLOCATION_PARAMETERS (20 bytes)."""
return struct.pack("<IIIII", error, ecc, space, engine, plugin)
def share_params(space, flags=1, subcontext=0):
"""NV_CTXSHARE_ALLOCATION_PARAMETERS (12 bytes)."""
return struct.pack("<III", space, flags, subcontext)
def channel_params(error=0, buffer=0, gpfifo=0x200400000, entries=0x400, flags=0, share=0,
space=0, userd=0, userd_offset=0x2000, engine=0, **extra):
"""NV_CHANNEL_ALLOC_PARAMS (0x170 bytes); `extra`: {offset name: (offset, format, value)}."""
block = bytearray(0x170)
struct.pack_into("<IIQIIII", block, 0, error, buffer, gpfifo, entries, flags, share, space)
struct.pack_into("<I", block, 0x20, userd)
struct.pack_into("<Q", block, 0x40, userd_offset)
struct.pack_into("<I", block, 0x80, engine)
for offset, layout, value in extra.values():
struct.pack_into(layout, block, offset, value)
return bytes(block)
class ChannelSequence(M.MemorySequence):
"""A case on a GPU with the memory state and the FIFO InitLocked state, a UVM session
and device, and (by `address_space`) the workload's externally owned VA space with a
registered page directory."""
USER = CLIENT
call = U.World.call
footer = U.World.footer
user_alloc = U.World.user_alloc
vaspace = U.World.vaspace
def __init__(self, name, registers=None):
window_reset()
for objects in constructed.values():
objects.clear()
self.ready = False
super().__init__(name, registers)
os_state["pages"] = Pages(os_state["pages"])
kbus = E.q(self.gpu + 0x1f80)
for slot, (symbol, _) in BAR2_SLOTS.items():
assert E.q(kbus + slot) == E.by_name[symbol], (hex(slot), symbol)
M.request_fixtures(False)
for stage in FIFO_STAGES:
self.stage(stage)
self.lines += os_state["events"]
os_state["events"].clear()
self.kfifo, self.ofifo = E.q(self.gpu + 0x22d0), E.q(self.gpu + 0x22d8)
self.dummy_page()
M.request_fixtures(True)
self.case, self.device, self.subdevice = self, DEVICE, SUBDEVICE
E.wq(E.externals["os_page_size"], 0x1000)
self.ready = True
self.groups, self.channels = {}, {}
graphics["stub"] = False
process["pid"] = 4242
# Case-named register values (not in the transcript's first reads, or fixed here so
# that the record is deterministic): the timer NV_PTIMER_TIME_1 (0x9410) and TIME_0
# (0x9400) read constants, so every notifier timestamp is the same value.
self.named = dict(TIMER)
self.fixture("bar2 not set up: the diagnostic A225 (`_nv039387rm`, the flush after a"
" BAR2 unmap, finds no BAR2 state) in a request's diagnostics is a"
" consequence of fixture decision 2, not behaviour of the original on"
" an initialized GPU")
self.fixture("registers " + " ".join(f"{offset:x}={value:x}"
for offset, value in sorted(TIMER.items())))
def locked(self, body):
"""Run `body` the way GpuSequence.stage runs a stage body: GPU not yet initialized,
expanded visibility, GPUs lock held."""
initialized = E.b(self.gpu + 0x90d)
E.wb(self.gpu + 0x90d, 0)
state["diag"].clear()
assert E.call("_nv031506rm") & 0xffffffff == 0
assert E.call("_nv054115rm", 0, 1) & 0xffffffff == 0
result = body()
assert E.call("_nv054117rm", 0, 0) & 0xffffffff == 0
E.call("_nv031505rm")
E.wb(self.gpu + 0x90d, initialized)
return result
def dummy_page(self):
"""The zombie-subcontext dummy page (KernelFifo+0x470). KernelFifo StatePostLoad
`_nv040427rm` allocates it after the preallocated USERD block, whose BAR1 mapping this
fixture cannot provide; so only the page is made here, with the calls and arguments
of that body: memdescCreate `_nv043694rm`(&KernelFifo+0x470, gpu, 0x1000, 0, 0, 0,
KernelFifo+0x460, broadcast state), tag 0x71, allocation `_nv043692rm` on the list
at KernelFifo+0x468. A subcontext slot in zombie state gets this page as its page
directory in every instance block."""
gpu, kfifo = self.gpu, self.kfifo
assert E.b(kfifo + 0x44e) == 1 and E.q(kfifo + 0x470) == 0
def body():
broadcast = E.call("_nv031390rm", gpu) & 0xff
E.call("_nv031482rm", gpu, 1)
flag = 1 if E.call("_nv031390rm", gpu) & 0xff else 0
status = E.call("_nv043694rm", kfifo + 0x470, gpu, 0x1000, 0, 0, 0,
stack=(E.d(kfifo + 0x460), flag)) & 0xffffffff
assert status == 0, hex(status)
E.wd(E.q(kfifo + 0x470) + 0xa0, 0x71)
status = E.call("_nv043692rm", E.q(kfifo + 0x470), E.q(kfifo + 0x468)) & 0xffffffff
assert status == 0, hex(status)
E.call("_nv031482rm", gpu, broadcast)
self.locked(body)
space, physical, size = descriptor(E.q(kfifo + 0x470))
self.fixture(f"dummy-page {space:x} {physical:x} {size:x} {','.join(state['diag']) or '-'}")
self.lines += os_state["events"]
os_state["events"].clear()
def fixture(self, text):
self.lines.append(f"fixture {text}")
def note(self, text):
self.lines.append(f"note {text}")
# Requests: every register access and memory store is an event line under the request.
def begin(self):
gpu_state["read"], gpu_state["written"] = Accesses(), Accesses()
gpu_state["source"] = dict(R.first_reads())
gpu_state["source"].update(M.UNTRACED)
gpu_state["source"].update(getattr(self, "named", {}))
def finish(self):
gpu_state["source"] = None
self.lines += os_state["events"]
os_state["events"].clear()
def quiet(self):
pass
def uvm(self):
"""The UVM side as tools/check_uvm_gpu_ops2_binary.py builds it: a session and a
device (its canned replies), on this world."""
U.API.tables((1, 2, 3, 4, 5))
self.stack = U.runtime_stack()
out = E.allocate(16)
assert self.call("rm_gpu_ops_create_session", out) == 0
self.session = E.q(out)
self.session_client = E.d(self.session)
self.run = U.Runner(self)
self.run.devices, self.run.spaces = [], []
self.uvm_device = self.run.standard_device()
self.flush_run()
def flush_run(self):
self.lines += self.run.lines
self.run.lines.clear()
self.lines += os_state["events"]
os_state["events"].clear()
def address_space(self, directory=0x123000, video=1, register=True, client=CLIENT,
device=DEVICE):
"""The workload's channel address space: 0x90f1 with flags 0x48 (externally owned,
page faulting) and base 0x1000; the page directory is registered the way UVM does it
(rm_gpu_ops_dup_address_space, rm_gpu_ops_set_page_directory -> control 0x801813)."""
result, handle = self.alloc(client, device, 0, 0x90f1,
params=R.vaspace_params(flags=0x48, base=0x1000))
assert result == 0
if register:
assert self.run.dup_address_space(self.uvm_device, client, handle) == 0
assert self.run.set_page_directory(self.run.spaces[-1], directory, 4, video) == 0
self.flush_run()
return handle
class Registers(dict):
"""gpu_state["registers"] of a case with the channel register model (a `fixture
ccsr-model` line): for channel `c` the word at 0x800000 + 8c reads back the last value
written (0 before), and the word at 0x800004 + 8c reads bit 0 (ENABLE) as last set by a
write with bit 10 (ENABLE_SET) or cleared by a write with bit 11 (ENABLE_CLR); every
other bit reads 0 (status idle, not busy, no fault). All other registers behave as in
the earlier harnesses (first read of the transcript, or a value the case names)."""
def __init__(self, values):
super().__init__(values)
self.channels = {}
@staticmethod
def modelled(offset):
return isinstance(offset, int) and 0x800000 <= offset < 0x808000
def __contains__(self, offset):
return self.modelled(offset) or super().__contains__(offset)
def __getitem__(self, offset):
if self.modelled(offset):
return self.channels.get(offset, 0)
return super().__getitem__(offset)
def written(self, offset, value):
if self.modelled(offset):
if offset & 4:
enabled = self.channels.get(offset, 0)
if value & 0x400:
enabled = 1
if value & 0x800:
enabled = 0
self.channels[offset] = enabled
else:
self.channels[offset] = value
def _append(self, item):
if isinstance(item, tuple):
events().append(f"w {item[0]:x} {item[1]:x}")
if isinstance(gpu_state["registers"], Registers):
gpu_state["registers"].written(*item)
else:
events().append(f"r {item:x} {gpu_state['registers'][item]:x}")
list.append(self, item)
Accesses.append = _append
process = {"pid": 4242}
replace("os_get_current_process", lambda a: process["pid"])
replace("os_find_ns_pid", lambda a: (E.wd(a[1], process["pid"]), 0)[1])
def new_object(kind, before):
objects = constructed[kind]
return objects[before] if len(objects) > before else 0
def _channel_methods():
def ccsr_model(self):
gpu_state["registers"] = Registers(gpu_state["registers"])
self.fixture("ccsr-model registers 800000..807fff: +0 reads the last value written,"
" +4 reads bit 0 as last set (write bit 10) or cleared (write bit 11)")
def graphics_stub(self):
graphics["stub"] = True
self.fixture("graphics-info-stub KernelGraphics+0x1e0 (NULL on this fixture: no"
" KernelGraphics stage body ran) is given a zeroed block of 8 records of"
" 0x60 bytes on first use by _nv041022rm; without it the original takes a"
" CPU exception in _nv041157rm when a channel on the graphics runlist is"
" freed. Every graphics-side effect of such a free is therefore absent"
" from this case")
def context_bound(self, channel):
"""Stands for rm_gpu_ops_bind_channel_resources, which sets bIsContextBound
(KernelChannel+0x28e) after promoting the context buffers; here only the byte."""
E.wb(self.channels[channel] + 0x28e, 1)
self.fixture(f"context-bound {channel:x} KernelChannel+0x28e set to 1 by the fixture"
" (no context buffer exists, nothing was promoted)")
def process_id(self, pid):
"""The calling process (os_get_current_process, os_find_ns_pid)."""
process["pid"] = pid
self.lines.append(f"process {pid:x}")
def group(self, engine=1, space=0, parent=DEVICE, client=CLIENT, new=0, **fields):
"""Class 0xa06c. State line on success:
tsg <handle> <grpID> <runlistId> <chanCount> <engineType field> <timeslice us>
<legacy mode> <runlist assigned> <tsgUniqueId>"""
before = len(constructed["group"])
result, handle = self.alloc(client, parent, new, 0xa06c,
params=tsg_params(space=space, engine=engine, **fields))
if result == 0:
self.groups[handle] = E.q(new_object("group", before) + 0x138)
self.describe_group(handle)
return result, handle
def describe_group(self, handle):
group = self.groups[handle]
self.lines.append(
f"tsg {handle:x} {E.d(group + 0x128):x} {E.d(group + 0x12c):x}"
f" {E.d(group + 0x130):x} {E.d(group + 0x134):x} {E.q(group + 0x180):x}"
f" {E.b(group + 0x191):x} {E.b(group + 0x1c0):x} {E.d(group + 0x23c):x}")
def share(self, group, space, flags=1, subcontext=0, client=CLIENT, new=0):
"""Class 0x9067: (status, handle, subctxId of the reply)."""
result, handle = self.alloc(client, group, new, 0x9067,
params=share_params(space, flags, subcontext))
reply = bytes.fromhex(self.request_line().split()[-2])
return result, handle, struct.unpack_from("<I", reply, 8)[0]
def request_line(self):
return next(line for line in reversed(self.lines) if line[:2] in ("A ", "C ", "F "))
def channel(self, group, index=0, client=CLIENT, new=0, images=True, **fields):
"""Class 0xc36f with the workload's layout for creation index `index`: GPFIFO at GPU
VA 0x200400000 + 0x3000 * index, 0x400 entries, USERD at offset 0x2000 + 0x3000 *
index of `userd`. State lines on success:
chan <handle> <ChID> <runlistId> <VEID> <cid> <bIsContextBound> <instance block
physical address> <USERD physical address> <cid of the reply>
image inst <phys> <sparse 0x1000 bytes>; image userd <phys> <sparse 0x200 bytes>"""
fields.setdefault("gpfifo", 0x200400000 + 0x3000 * index)
fields.setdefault("userd_offset", 0x2000 + 0x3000 * index)
before = len(constructed["channel"])
result, handle = self.alloc(client, group, new, 0xc36f, params=channel_params(**fields))
if result == 0:
self.channels[handle] = new_object("channel", before)
reply = bytes.fromhex(self.request_line().split()[-2])
self.describe_channel(handle, struct.unpack_from("<I", reply, 0x84)[0], images)
return result, handle
def describe_channel(self, handle, reply=0, images=True):
channel = self.channels[handle]
instance = descriptor(E.q(E.q(channel + 0x290)))[1]
userd = descriptor(E.q(channel + 0x310))[1] if E.q(channel + 0x310) else 0
self.lines.append(
f"chan {handle:x} {E.d(channel + 0x274):x} {E.d(channel + 0x270):x}"
f" {E.d(channel + 0x3a4):x} {E.d(channel + 0x3ac):x} {E.b(channel + 0x28e):x}"
f" {instance:x} {userd:x} {reply:x}")
if images:
self.image("inst", instance, 0x1000)
self.image("userd", userd, 0x200)
def image(self, name, physical, size):
mapped = all(page in windows["fb"]["pages"]
for page in range(physical & ~0xfff, physical + size, PAGE))
data = E.read(FB_WINDOW + physical, size) if mapped else b""
self.lines.append(f"image {name} {physical:x} {U.sparse(data) if mapped else '-'}")
def engine_object(self, channel, klass, params, client=CLIENT, new=0):
return self.alloc(client, channel, new, klass, params=params)
def copy_object(self, channel, index, version=0, **keywords):
"""Class 0xc3b5: NVB0B5_ALLOCATION_PARAMETERS {version, engineType}."""
return self.engine_object(channel, 0xc3b5, struct.pack("<II", version, index),
**keywords)
def engine_id(self, channel, handle, client=CLIENT):
"""0x906f0101 NV906F_CTRL_GET_CLASS_ENGINEID."""
return self.control(client, channel, 0x906f0101,
params=struct.pack("<IIII", handle, 0, 0, 0))
def token(self, channel, client=CLIENT):
"""0xc36f0108 NVC36F_CTRL_CMD_GPFIFO_GET_WORK_SUBMIT_TOKEN."""
result, reply = self.control(client, channel, 0xc36f0108, params=bytes(4))
return result, struct.unpack("<I", reply)[0]
def channel_list(self, handles, client=CLIENT, device=DEVICE, count=None):
"""0x80170d NV0080_CTRL_CMD_FIFO_GET_CHANNELLIST: {numChannels, pChannelHandleList,
pChannelList} with two nested user buffers. The record shows the pointers as 0x2000
and 0x3000 and adds a line `list <handles in> <channel list out>` (hex bytes)."""
count = len(handles) if count is None else count
source = E.allocate(4 * len(handles) + 16)
target = E.allocate(4 * len(handles) + 16, 0xa5)
E.write(source, b"".join(struct.pack("<I", handle) for handle in handles))
params = struct.pack("<IIQQ", count, 0, source, target)
address = R.user(params)
request = struct.pack("<IIIIQII", client, device, 0x80170d, 0, address, 24, 0xdddddddd)
self.begin()
status, reply = R.escape(self.context, "ctl", 0, 0x2a, request)
out = bytearray(E.read(address, 24))
sent, canonical, canonical_reply = bytearray(params), bytearray(request), bytearray(reply)
canonical[16:24] = canonical_reply[16:24] = struct.pack("<Q", 0x1000)
for block in (sent, out):
for offset, real, marker in ((8, source, 0x2000), (16, target, 0x3000)):
if struct.unpack_from("<Q", block, offset)[0] == real:
struct.pack_into("<Q", block, offset, marker)
self.emit("C", "ctl", 0, bytes(canonical), bytes(sent), status, bytes(canonical_reply),
bytes(out))
listed = E.read(target, 4 * len(handles))
self.lines.append(f"list {E.read(source, 4 * len(handles)).hex()} {listed.hex()}")
self.finish()
return struct.unpack_from("<I", reply, 28)[0], list(
struct.unpack(f"<{len(handles)}I", listed))
def notifier(self, client=CLIENT, device=DEVICE, size=0x1000):
"""A 4 KiB class 0x3e error notifier as libcuda allocates it (type 13, kernel
mapping)."""
result, handle = self.memory(0x3e, parent=device, size=size, kind=13, owner=device,
flags=0xc001, alignment=0, attr=0x3a000000) \
if client == CLIENT else self.alloc(
client, device, 0, 0x3e, params=M.memory_params(
size=size, kind=13, owner=device, flags=0xc001, alignment=0,
attr=0x3a000000))
assert result == 0, hex(result)
return handle
for name, function in list(locals().items()):
setattr(ChannelSequence, name, function)
_channel_methods()
def standard(name, holders=True):
"""A world with the UVM session and device, the two 2 MiB allocations that stand for
UVM's page-tree chunks (as in the memory record's workload case; the page directory
0x123000 lies in the first), the externally owned address space with its directory, and
the workload's 2 MiB GPFIFO/USERD block."""
case = ChannelSequence(name)
case.uvm()
if holders:
for holder in (0x5cff0001, 0x5cff0002):
assert case.memory(0x40, new=holder, size=0x200000) == (0, holder)
case.external = case.address_space()
result, case.block = case.memory(0x40, size=0x200000)
assert result == 0
case.ccsr_model()
return case
def group_cases():
"""C3: class 0xa06c (NV_CHANNEL_GROUP_ALLOCATION_PARAMETERS)."""
case = standard("chan-group")
external = case.external
# The workload's two requests: GR0 without an address space, a copy type with the
# external space; then every engine type and what each leaves in the group.
for engine, space in ((1, 0), (0xb, external)):
result, group = case.group(engine=engine, space=space)
assert result == 0
assert case.free(CLIENT, 0, group) == 0
live = []
for engine in list(range(0, 0x14)) + [0x1f, 0x29, 0x35, 0x3f, 0x40, 0x41, 0x100, 0xffffffff]:
for space in (0, external):
result, group = case.group(engine=engine, space=space)
if result == 0:
live.append(group)
for group in live[::3] + live[1::3] + live[2::3]:
assert case.free(CLIENT, 0, group) == 0
# Parents, address spaces, the other parameter fields, a chosen handle.
result, managed = case.alloc(CLIENT, DEVICE, 0, 0x90f1,
params=R.vaspace_params(flags=0, base=0x5000000))
assert result == 0
result, bare = case.alloc(CLIENT, DEVICE, 0, 0x90f1,
params=R.vaspace_params(flags=0x48, base=0x2000))
assert result == 0
for parent in (SUBDEVICE, CLIENT, external, case.block, 0x12345678, 0):
case.group(parent=parent)
for space in (managed, bare, 0x12345678, DEVICE, case.block, CLIENT):
for engine in (1, 0xb):
result, group = case.group(engine=engine, space=space)
if result == 0:
assert case.free(CLIENT, 0, group) == 0
notifier = case.notifier()
for fields in (dict(error=notifier), dict(ecc=notifier), dict(error=0x12345678),
dict(ecc=0x12345678), dict(plugin=1), dict(plugin=0x100),
dict(plugin=0xffffffff)):
result, group = case.group(**fields)
if result == 0:
assert case.free(CLIENT, 0, group) == 0
case.alloc(CLIENT, DEVICE, 0, 0xa06c)
case.alloc(CLIENT, DEVICE, 0, 0xa06c, params=bytes(16))
case.alloc(CLIENT, DEVICE, 0, 0xa06c, params=bytes(24))
assert case.group(new=0x5c000059)[0] == 0
case.group(new=0x5c000059)
# Group ids: allocated lowest-free, released on free.
held = [case.group()[1] for _ in range(4)]
assert case.free(CLIENT, 0, held[1]) == 0
held.append(case.group()[1])
held.append(case.group(engine=0xc, space=external)[1])
assert case.free(CLIENT, 0, CLIENT) == 0
return case
def group_mode_cases():
"""C3: 0xa06c under devices of the other address-space modes (vaMode 0 OPTIONAL_MULTIPLE,
1 SINGLE, 2 MULTIPLE): a second and a third client with their own device."""
case = ChannelSequence("chan-group-vamode")
clients = []
for mode in (0, 1):
result, client = case.alloc(0, 0, 0, 0)
assert result == 0
result, device = case.alloc(client, client, 0, 0x80,
params=R.device_params(share=client, mode=mode))
assert result == 0, hex(result)
case.note(f"client {client:x} device {device:x} vaMode {mode}")
result, space = case.alloc(client, device, 0, 0x90f1,
params=R.vaspace_params(flags=0, base=0x5000000))
for engine in (1, 0xb):
for chosen in (0, space, 0x12345678) if result == 0 else (0, 0x12345678):
result, group = case.group(engine=engine, space=chosen, parent=device,
client=client)
if result == 0:
assert case.free(client, 0, group) == 0
clients.append(client)
# A group of one client is not visible to another.
result, group = case.group()
assert result == 0
case.free(clients[0], 0, group)
for client in clients:
assert case.free(client, 0, client) == 0
return case
def share_cases():
"""C4: class 0x9067 (NV_CTXSHARE_ALLOCATION_PARAMETERS)."""
case = standard("chan-share")
external = case.external
result, group = case.group()
assert result == 0
# The workload's request (ASYNC in the external space), then the four flag values.
assert case.share(group, external)[::2] == (0, 0x3f)
for flags, subcontext in ((1, 0), (0, 0), (0, 0), (2, 5), (2, 5), (2, 0x3e), (2, 0x40),
(2, 0xffffffff), (3, 0), (3, 0), (1, 7), (4, 0), (0x80000001, 0),
(0xffffffff, 0)):
case.share(group, external, flags, subcontext)
# Address spaces: none, unknown, RM-managed, external without a page directory, objects
# of other classes.
result, managed = case.alloc(CLIENT, DEVICE, 0, 0x90f1,
params=R.vaspace_params(flags=0, base=0x5000000))
assert result == 0
bare = case.address_space(register=False)
shares = {}
for space in (0, 0x12345678, managed, bare, DEVICE, case.block, group):
result, handle, _ = case.share(group, space)
if result == 0:
shares[space] = handle
# Parents.
for parent in (DEVICE, SUBDEVICE, CLIENT, external, 0x12345678, 0):
case.share(parent, external)
case.alloc(CLIENT, group, 0, 0x9067)
case.alloc(CLIENT, group, 0, 0x9067, params=bytes(8))
case.alloc(CLIENT, group, 0, 0x9067, params=share_params(external) + bytes(4))
assert case.share(group, external, new=0x5c00005a)[0] == 0
case.share(group, external, new=0x5c00005a)
# Released ids are reused; a share freed and its id taken again.
assert case.free(CLIENT, 0, 0x5c00005a) == 0
case.share(group, external)
# A group that carries an address space (the copy groups): a share in it.
result, copy = case.group(engine=0xb, space=external)
assert result == 0
for space in (external, 0, managed):
case.share(copy, space)
# Every id of a group: 64 ASYNC requests on a fresh group, then one more.
result, full = case.group()
assert result == 0
for _ in range(65):
case.share(full, external)
# The address space goes while shares live in it; then the group; then the client.
assert case.free(CLIENT, 0, managed) == 0
assert case.free(CLIENT, 0, full) == 0
assert case.free(CLIENT, 0, external) == 0
assert case.free(CLIENT, 0, CLIENT) == 0
return case
def compute_group(case, shares=1):
"""The workload's compute group: TSG for GR0 without an address space and ASYNC
context shares in the external space."""
result, group = case.group()
assert result == 0
handles = []
for _ in range(shares):
result, share, _ = case.share(group, case.external)
assert result == 0
handles.append(share)
return group, handles
def channel_cases():
"""C5: class 0xc36f, the workload's two styles, with 0x80170d and 0xc36f0108."""
case = standard("chan-channel")
external, block = case.external, case.block
group, (share,) = compute_group(case)
channels = []
for index in range(3):
notifier = case.notifier()
result, channel = case.channel(group, index, error=notifier, buffer=block, share=share,
userd=block)
assert result == 0, hex(result)
case.describe_group(group)
case.channel_list([channel])
case.token(channel)
channels.append((channel, notifier))
result, copy = case.group(engine=0xb, space=external)
assert result == 0
for index in range(3, 5):
notifier = case.notifier()
result, channel = case.channel(copy, index, error=notifier, buffer=block, userd=block)
assert result == 0, hex(result)
case.describe_group(copy)
case.channel_list([channel])
case.token(channel)
channels.append((channel, notifier))
case.channel_list([channel for channel, _ in channels] + [group, 0x12345678, 0])
case.channel_list([], count=0)
for channel, notifier in channels:
assert case.free(CLIENT, 0, channel) == 0
assert case.free(CLIENT, 0, notifier) == 0
assert case.free(CLIENT, 0, share) == 0
assert case.free(CLIENT, 0, group) == 0
assert case.free(CLIENT, 0, copy) == 0
assert case.free(CLIENT, 0, CLIENT) == 0
return case
def channel_rule_cases():
"""C5: parameter and parent rules of 0xc36f around the workload's request."""
case = standard("chan-channel-rules")
external, block = case.external, case.block
group, (share, other_share) = compute_group(case, 2)
result, copy = case.group(engine=0xb, space=external)
assert result == 0
result, foreign = case.group()
assert result == 0
result, foreign_share, _ = case.share(foreign, external)
assert result == 0
notifier = case.notifier()
system = case.memory(0x3e, size=0x3000, flags=0xc001, alignment=0, attr=0x3a000000)[1]
small = case.memory(0x3e, size=0x1000, flags=0xc001, alignment=0, attr=0x3a000000)[1]
good = dict(error=notifier, buffer=block, share=share, userd=block)
index = [0]
def probe(parent=group, keep=False, **changes):
fields = dict(good)
fields.update(changes)
result, channel = case.channel(parent, index[0], images=False, **fields)
index[0] += 1
if result == 0 and not keep:
case.token(channel)
assert case.free(CLIENT, 0, channel) == 0
return result, channel
assert probe()[0] == 0
# hObjectBuffer is not looked at (requirements open question 10).
for buffer in (0, 0x12345678, notifier, DEVICE):
probe(buffer=buffer)
case.note("flags bit 2 is not executed: in this fixture the original takes a CPU exception"
" (unmapped read) in _nv039920rm near +0x1293")
for bit in range(32):
if bit != 2:
probe(flags=1 << bit)
for entries in (0, 1, 2, 3, 0x3ff, 0x401, 0x800, 0x10000, 0x80000000, 0xffffffff):
probe(entries=entries)
for gpfifo in (0, 0x1000, 0x200400004, 0xff00000000, 0x10000000000, 0x1ffffffffffff,
(1 << 64) - 0x1000):
probe(gpfifo=gpfifo)
# Error notifier: none, unknown, other classes, a notifier too small for record 1.
for error in (0, 0x12345678, block, DEVICE, system, small, external):
probe(error=error)
# USERD: none (the preallocated block, which this fixture does not have), unknown,
# system memory, other classes, offsets.
case.note("hUserdMemory 0 (the preallocated USERD block) is not executed: the block is made"
" by KernelFifo StatePostLoad, which this fixture cannot run (it needs BAR1); the"
" original takes a CPU exception here without it")
case.note("USERD in system memory (a class 0x3e handle) is not executed: the allocation"
" answers 0 with diagnostic S1a.359, then the original takes a CPU exception in"
" the following token or free request in this fixture")
for userd in (0x12345678, DEVICE, external):
probe(userd=userd)
case.note("USERD offsets whose 0x200 bytes do not lie inside the memory object (0x1fff00"
" and above for the 2 MiB block) are not executed: the original takes a CPU"
" exception in this fixture")
for offset in (0, 0x200, 0x1ff, 0x100, 0x1000, 0x1ffe00, 0x1ffe01):
probe(userd_offset=offset)
# Context share and address space.
for changes in (dict(share=0), dict(share=other_share), dict(share=foreign_share),
dict(share=0x12345678), dict(share=group), dict(share=external),
dict(space=external), dict(share=0, space=external),
dict(share=0, space=0x12345678)):
probe(**changes)
for engine in (1, 2, 0xb, 0x40, 0xffffffff):
probe(engine=engine)
for name, offset, layout in (("cid", 0x84, "<I"), ("subdevice", 0x88, "<I"),
("ecc", 0x8c, "<I"), ("instance", 0x90, "<Q"),
("userdmem", 0xa8, "<Q"), ("ramfc", 0xc0, "<Q"),
("mthdbuf", 0xd8, "<Q"), ("physgroup", 0xf0, "<I"),
("internal", 0xf4, "<I"), ("errormem", 0xf8, "<Q"),
("eccmem", 0x110, "<Q"), ("process", 0x128, "<I"),
("subprocess", 0x12c, "<I"), ("iv", 0x130, "<I"),
("tpc", 0x168, "<I")):
probe(**{name: (offset, layout, 0x1001)})
# Parents: the copy group (legacy mode), a device (RM allocates the group), others.
probe(parent=copy, share=0)
probe(parent=copy)
probe(parent=copy, share=0, space=external)
for parent in (DEVICE, SUBDEVICE, CLIENT, external, share, block, 0x12345678, 0):
probe(parent=parent, share=0, space=external)
probe(parent=parent, share=0)
# A group in sub-context mode refuses a channel without a share and the reverse.
assert probe(keep=True)[0] == 0
probe(share=0)
assert probe(parent=copy, share=0, keep=True)[0] == 0
probe(parent=copy)
case.alloc(CLIENT, group, 0, 0xc36f)
case.alloc(CLIENT, group, 0, 0xc36f, params=channel_params(**good)[:0x168])
case.alloc(CLIENT, group, 0, 0xc36f, params=channel_params(**good) + bytes(8))
assert case.channel(group, 60, new=0x5c000060, images=False, **good)[0] == 0
case.channel(group, 61, new=0x5c000060, images=False, **good)
case.admin(1)
probe()
case.admin(0)
assert case.free(CLIENT, 0, CLIENT) == 0
return case
def channel_id_cases():
"""C5: channel-id allocation across two clients of two processes (isolation in blocks
of 8 ids) and reuse of released ids."""
case = standard("chan-channel-ids")
block = case.block
worlds = {}
def member(pid):
case.process_id(pid)
if pid not in worlds:
if not worlds:
client, device, space, memory = CLIENT, DEVICE, case.external, block
else:
result, client = case.alloc(0, 0, 0, 0)
assert result == 0
result, device = case.alloc(client, client, 0, 0x80,
params=R.device_params(share=client, mode=2))
assert result == 0, hex(result)
space = case.address_space(directory=0x223000, client=client, device=device)
result, memory = case.alloc(client, device, 0, 0x40,
params=M.memory_params(owner=client, size=0x200000))
assert result == 0
result, group = case.group(engine=0xb, space=space, parent=device, client=client)
assert result == 0
worlds[pid] = dict(client=client, device=device, group=group, memory=memory,
count=0, channels=[])
return worlds[pid]
def add(pid):
world = member(pid)
notifier = case.notifier(client=world["client"], device=world["device"])
result, channel = case.channel(world["group"], world["count"], client=world["client"],
images=False, error=notifier, userd=world["memory"])
assert result == 0, hex(result)
world["count"] += 1
world["channels"].append(channel)
return channel
for pid in (4242,) * 3 + (5151,) * 2 + (4242,) * 6 + (5151,) * 7 + (4242,):
add(pid)
# Released ids: the lowest free id of a block the process owns is taken again; a block
# whose last channel went is free for the other process.
first, second = worlds[4242], worlds[5151]
case.process_id(4242)
for channel in (first["channels"][1], first["channels"][4]):
assert case.free(first["client"], 0, channel) == 0
add(4242)
add(4242)
case.process_id(5151)
for channel in second["channels"][:8]:
assert case.free(second["client"], 0, channel) == 0
add(4242)
add(5151)
# The same client from another process: the client's own process identity decides.
case.process_id(7777)
world = worlds[4242]
notifier = case.notifier()
case.channel(world["group"], 40, images=False, error=notifier, userd=block)
case.process_id(5151)
assert case.free(second["client"], 0, second["client"]) == 0
case.process_id(4242)
assert case.free(CLIENT, 0, CLIENT) == 0
return case
def channel_free_cases():
"""C5: destruction orders. The notifier first, the context share first, the group with
live channels, the address space first, the USERD/GPFIFO memory first (requirements
open question 12: the 2 MiB block's frames are observed through the offset the
allocator gives the next 2 MiB request)."""
case = standard("chan-channel-free")
external = case.external
def build(count=2, copies=1):
result, block = case.memory(0x40, size=0x200000)
assert result == 0
group, (share,) = compute_group(case)
made = []
for index in range(count):
notifier = case.notifier()
result, channel = case.channel(group, index, images=False, error=notifier,
buffer=block, share=share, userd=block)
assert result == 0
made.append((channel, notifier))
result, copy = case.group(engine=0xb, space=external)
assert result == 0
for index in range(copies):
notifier = case.notifier()
result, channel = case.channel(copy, count + index, images=False, error=notifier,
buffer=block, userd=block)
assert result == 0
made.append((channel, notifier))
return block, group, share, copy, made
def after(*handles):
"""What is left: a token request per channel, then free of whatever remains."""
for handle in handles:
case.free(CLIENT, 0, handle)
block, group, share, copy, made = build()
case.note("notifier first")
assert case.free(CLIENT, 0, made[0][1]) == 0
case.token(made[0][0])
case.token(made[1][0])
case.free(CLIENT, 0, made[0][0])
case.note("context share first")
assert case.free(CLIENT, 0, share) == 0
case.token(made[1][0])
case.note("group with live channels")
assert case.free(CLIENT, 0, copy) == 0
case.token(made[2][0])
after(made[1][0], made[1][1], made[2][0], made[2][1], group, block)
block, group, share, copy, made = build()
case.note("USERD/GPFIFO memory first")
assert case.free(CLIENT, 0, block) == 0
probe = case.memory(0x40, size=0x200000)[1]
for channel, _ in made:
case.token(channel)
assert case.free(CLIENT, 0, made[0][0]) == 0
second = case.memory(0x40, size=0x200000)[1]
assert case.free(CLIENT, 0, group) == 0
assert case.free(CLIENT, 0, copy) == 0
third = case.memory(0x40, size=0x200000)[1]
after(probe, second, third, *(notifier for _, notifier in made))
block, group, share, copy, made = build()
case.note("address space first")
assert case.free(CLIENT, 0, external) == 0
for channel, _ in made:
case.token(channel)
after(group, copy, block)
case.note("client with live objects")
case.external = case.address_space()
external = case.external
build()
assert case.free(CLIENT, 0, CLIENT) == 0
return case
def schedule(case, group, enable=1, skip_submit=0, skip_enable=0, client=CLIENT):
"""0xa06c0101 NVA06C_CTRL_CMD_GPFIFO_SCHEDULE {bEnable, bSkipSubmit, bSkipEnable}."""
result, _ = case.control(client, group, 0xa06c0101,
params=bytes([enable, skip_submit, skip_enable]))
case.describe_group(group)
return result
def copy_group(case, count, engine=0xb, index=2, first=0, objects=True):
"""A copy group as the workload builds it: TSG with the external space, `count`
channels without a context share, one 0xc3b5 object (CE index `index`) on each and the
0x906f0101 query."""
result, group = case.group(engine=engine, space=case.external)
assert result == 0
made = []
for number in range(count):
notifier = case.notifier()
result, channel = case.channel(group, first + number, error=notifier,
buffer=case.block, userd=case.block)
assert result == 0, hex(result)
engine_object = 0
if objects:
result, engine_object = case.copy_object(channel, index)
assert result == 0, hex(result)
case.describe_group(group)
case.describe_channel(channel, images=False)
case.engine_id(channel, engine_object)
case.token(channel)
made.append((channel, notifier, engine_object))
return group, made
def engine_object_cases():
"""C6: class 0xc3b5 (NVB0B5_ALLOCATION_PARAMETERS {version, engineType}) and
0x906f0101 on copy-group and compute-group channels; what the first engine object does
to the runlist of the channel and of the group; the runlist conflict."""
case = standard("chan-engine-objects")
case.graphics_stub()
case.engine_table()
external, block = case.external, case.block
count = [0]
def fresh(compute=False):
if compute:
group, (share,) = compute_group(case)
else:
result, group = case.group(engine=0xb, space=external)
assert result == 0
share = 0
notifier = case.notifier()
result, channel = case.channel(group, count[0], images=False, error=notifier,
buffer=block, share=share, userd=block)
assert result == 0
count[0] += 1
return group, channel
def attach(group, channel, index, version=0):
result, handle = case.copy_object(channel, index, version)
case.describe_group(group)
case.describe_channel(channel, images=False)
if result == 0:
case.engine_id(channel, handle)
return result, handle
# Version 0: the CE index. Each index on a channel of its own group.
for index in list(range(0, 10)) + [0xb, 0x40, 0xffffffff]:
group, channel = fresh()
attach(group, channel, index)
assert case.free(CLIENT, 0, group) == 0
# Version 1: the NV2080 engine type.
for kind in (0, 1, 9, 0xa, 0xb, 0x10, 0x11, 0x12, 0x13, 0x40):
group, channel = fresh()
attach(group, channel, kind, version=1)
assert case.free(CLIENT, 0, group) == 0
group, channel = fresh()
attach(group, channel, 2, version=2)
# Several objects on one channel: the same engine again, another engine of the same
# runlist, an engine of another runlist (0x40).
for index in (2, 2, 3, 0, 1):
attach(group, channel, index)
# A second channel of the group: the group's runlist is fixed.
notifier = case.notifier()
result, second = case.channel(group, count[0], images=False, error=notifier, buffer=block,
userd=block)
assert result == 0
for index in (3, 2):
attach(group, second, index)
# The compute group: COPY0/COPY1 share the GR runlist (the workload passes index 1).
group, channel = fresh(compute=True)
result, first = attach(group, channel, 1)
assert result == 0
for index in (0, 2):
attach(group, channel, index)
# 0x906f0101: argument rules.
for handle in (0, CLIENT, 0x12345678, channel, group, block, first):
case.engine_id(channel, handle)
case.engine_id(second, first)
case.control(CLIENT, channel, 0x906f0101, params=bytes(12))
# Parents and parameter sizes of the object.
for parent in (group, DEVICE, SUBDEVICE, CLIENT, 0x12345678):
case.copy_object(parent, 1)
case.alloc(CLIENT, channel, 0, 0xc3b5)
case.alloc(CLIENT, channel, 0, 0xc3b5, params=bytes(4))
case.alloc(CLIENT, channel, 0, 0xc3b5, params=struct.pack("<III", 0, 1, 0))
# The object goes; the channel keeps its runlist. Then the channel with its objects.
assert case.free(CLIENT, 0, first) == 0
case.describe_group(group)
case.describe_channel(channel, images=False)
attach(group, channel, 2)
assert case.free(CLIENT, 0, channel) == 0
assert case.free(CLIENT, 0, CLIENT) == 0
return case
def schedule_cases():
"""C7 on copy groups (no graphics state needed): 0xa06c0101, 0xa06c0103, 0xa06c0105,
then channel and group free, with every register access and runlist buffer store."""
case = standard("chan-schedule")
block = case.block
# The workload's order for one copy group of four channels.
group, made = copy_group(case, 4)
assert schedule(case, group) == 0
for channel, _, _ in made:
case.describe_channel(channel, images=False)
# A second schedule, the skip flags, disable and enable again.
schedule(case, group)
schedule(case, group, skip_submit=1)
schedule(case, group, skip_enable=1)
schedule(case, group, enable=0)
schedule(case, group, enable=0)
schedule(case, group, enable=1, skip_submit=1)
schedule(case, group)
# 0xa06c0103 NVA06C_CTRL_CMD_SET_TIMESLICE {timesliceUs u64}.
for value in (0x800, 0x800, 0x400, 0x3ff, 1, 0, 1000, 2000, 5000, 0x10000, 500000,
0x3fc00, 0x7f800, 0x1000000, 1 << 32, (1 << 64) - 1):
case.control(CLIENT, group, 0xa06c0103, params=struct.pack("<Q", value))
case.describe_group(group)
# 0xa06c0105 NVA06C_CTRL_CMD_PREEMPT {bWait, bManualTimeout, timeoutUs}.
for wait, manual, timeout in ((1, 0, 0), (0, 0, 0), (1, 1, 1000), (1, 1, 1000000),
(1, 1, 1000001), (0, 1, 0), (1, 1, 0)):
case.control(CLIENT, group, 0xa06c0105, params=struct.pack("<BBHI", wait, manual, 0,
timeout))
# A second group on the same runlist and one on another: runlist content with several
# groups; then a channel added to a scheduled group.
second, more = copy_group(case, 2, first=4)
assert schedule(case, second) == 0
third, other = copy_group(case, 1, engine=0xc, index=3, first=6)
assert schedule(case, third) == 0
notifier = case.notifier()
result, late = case.channel(group, 7, error=notifier, buffer=block, userd=block)
assert result == 0
case.describe_group(group)
case.copy_object(late, 2)
schedule(case, group)
# Teardown in the workload's order for one group: engine object, channel, notifier.
for channel, notifier, engine_object in made:
assert case.free(CLIENT, 0, engine_object) == 0
assert case.free(CLIENT, 0, channel) == 0
assert case.free(CLIENT, 0, notifier) == 0
assert case.free(CLIENT, 0, group) == 0
# A scheduled group freed with its channels; then the client.
assert case.free(CLIENT, 0, second) == 0
# Groups that cannot be scheduled as they are: no channel, a channel without an engine
# object, wrong objects.
result, empty = case.group(engine=0xd, space=case.external)
schedule(case, empty)
bare, _ = copy_group(case, 1, engine=0xd, first=8, objects=False)
schedule(case, bare)
for target in (DEVICE, block, 0x12345678):
case.control(CLIENT, target, 0xa06c0101, params=bytes([1, 0, 0]))
case.control(CLIENT, group, 0xa06c0101, params=bytes([1, 0, 0]))
case.control(CLIENT, third, 0xa06c0101, params=bytes([1, 0]))
assert case.free(CLIENT, 0, CLIENT) == 0
return case
def compute_channels(case, count, objects=True):
"""The workload's compute group: `count` channels with the context share, each with a
0xc3b5 object of CE index 1 (the engine COPY1 on the graphics runlist)."""
group, (share,) = compute_group(case)
made = []
for number in range(count):
notifier = case.notifier()
result, channel = case.channel(group, number, error=notifier, buffer=case.block,
share=share, userd=case.block)
assert result == 0, hex(result)
engine_object = 0
if objects:
result, engine_object = case.copy_object(channel, 1)
assert result == 0, hex(result)
case.describe_group(group)
case.describe_channel(channel, images=False)
case.engine_id(channel, engine_object)
case.token(channel)
made.append((channel, notifier, engine_object))
return group, share, made
def compute_object_cases():
"""C8 as far as this fixture goes, with nothing substituted on the graphics side: class
0xc3c0 on a compute channel, 0x20801218, and the schedule gate of a group on the
graphics runlist whose channels were not bound by UVM. The world is abandoned without
freeing the channels (see `fixture graphics-info-stub` in the next case for why)."""
case = standard("chan-compute-object")
group, share, made = compute_channels(case, 2, objects=False)
channel = made[0][0]
# NV_GR_ALLOCATION_PARAMETERS {version, flags, size, caps}: the workload's bytes.
workload = struct.pack("<IIII", 0, 0, 0x68d1c870, 0x7ffd)
case.engine_object(channel, 0xc3c0, workload)
case.engine_object(channel, 0xc3c0, bytes(16))
case.alloc(CLIENT, channel, 0, 0xc3c0)
for parent in (group, DEVICE, SUBDEVICE, 0x12345678):
case.engine_object(parent, 0xc3c0, workload)
case.describe_group(group)
case.describe_channel(channel, images=False)
case.note("0x20801218 on these channels is not executed here: the original takes a CPU"
" exception in _nv041111rm (KernelGraphics+0x1e0 is NULL); see the next case")
for handle in (group, 0x12345678, 0):
case.control(CLIENT, SUBDEVICE, 0x20801218, params=struct.pack("<IIQ", handle, 0, 0))
# The schedule gate: without an engine object the group is on no runlist yet; with the
# COPY1 object the channels sit on the graphics runlist and are not context-bound.
schedule(case, group)
for target, _, _ in made:
result, handle = case.copy_object(target, 1)
assert result == 0
case.describe_channel(target, images=False)
schedule(case, group)
schedule(case, group, enable=0)
case.control(CLIENT, group, 0xa06c0103, params=struct.pack("<Q", 0x800))
case.describe_group(group)
case.control(CLIENT, group, 0xa06c0105, params=struct.pack("<BBHI", 1, 0, 0, 0))
case.note("not executed: rm_gpu_ops_retain_channel / bind_channel_resources (no context"
" buffer exists, 0xc3c0 did not construct), and any free of these channels")
return case
def compute_group_cases():
"""The compute group's channel life on the graphics runlist with two named fixture
substitutions (graphics-info-stub, context-bound): schedule gate, schedule, timeslice,
preempt and teardown in the workload's order. No graphics object exists."""
case = standard("chan-compute-group")
case.graphics_stub()
group, share, made = compute_channels(case, 8)
assert schedule(case, group) == 0x40
for channel, _, _ in made[:7]:
case.context_bound(channel)
assert schedule(case, group) == 0x40
case.context_bound(made[7][0])
schedule(case, group)
for channel, _, _ in made:
case.describe_channel(channel, images=False)
case.engine_object(made[0][0], 0xc3c0, struct.pack("<IIII", 0, 0, 0x68d1c870, 0x7ffd))
case.control(CLIENT, SUBDEVICE, 0x20801218,
params=struct.pack("<IIQ", made[0][0], 0, 0))
case.control(CLIENT, group, 0xa06c0103, params=struct.pack("<Q", 0x800))
case.describe_group(group)
case.control(CLIENT, group, 0xa06c0105, params=struct.pack("<BBHI", 1, 0, 0, 0))
for channel, notifier, engine_object in made:
assert case.free(CLIENT, 0, engine_object) == 0
assert case.free(CLIENT, 0, channel) == 0
assert case.free(CLIENT, 0, notifier) == 0
assert case.free(CLIENT, 0, share) == 0
assert case.free(CLIENT, 0, group) == 0
assert case.free(CLIENT, 0, CLIENT) == 0
return case
CAPTURE = M.R.ROOT.parent / "nvidia-driver/analysis-580.178.04/reports" \
/ "cuda-compute-exact-allocation-ioctl-payloads.jsonl"
WORKLOAD_CLASSES = (0xa06c, 0x9067, 0xc36f, 0xc3c0, 0xc3b5)
WORKLOAD_CONTROLS = (0x80170d, 0x906f0101, 0xc36f0108, 0xa06c0101, 0xa06c0103, 0xa06c0105,
0x20801218)
def workload_case():
"""The channel-phase requests of the captured CUDA run (the ioctl capture named in
CAPTURE, read directly) for the device the context lives on, in the capture's order and
with libcuda's handles and parameter bytes: the external address space, the 2 MiB
GPFIFO/USERD block, every error notifier, the 7 groups, the context share, the 32
channels with their engine objects, the controls 0x80170d (nested buffers rebuilt: the
handle of the channel just allocated), 0x906f0101, 0xc36f0108, 0x20801218, 0xa06c0101,
0xa06c0103, 0xa06c0105, and the frees of all of these. Not replayed: memory mappings,
events, the debugger session, 0x20801210, every UVM ioctl. Inserted by the fixture: the
page directory after the address space is allocated, and `context-bound` for the
compute channels in front of the compute group's schedule (where the capture has
UVM_REGISTER_CHANNEL). The line `workload-compare` counts replies equal to the capture
(status and parameter bytes, with the cid word of a channel reply and the token and
channel-id values left out of the comparison because their bases differ: the capture's
first channel id is 0x10 and its cid counter starts at 0x63e)."""
import json
rows = [json.loads(line) for line in CAPTURE.read_text().splitlines()]
rows = [row for row in rows if "nvidia-uvm" not in row["device"]]
number = lambda row: int(row["request"], 16) & 0xff
def words(text):
data = bytes.fromhex(text or "")
return struct.unpack(f"<{len(data) // 4}I", data[:len(data) // 4 * 4])
devices = [(words(row["after"])[0], words(row["after"])[2]) for row in rows
if number(row) == 0x2b and words(row["after"])[3] == 0x80]
client, device = devices[-1]
subdevice = next(words(row["after"])[2] for row in rows
if number(row) == 0x2b and words(row["after"])[3] == 0x2080
and words(row["after"])[1] == device)
rename = {client: CLIENT, device: DEVICE, subdevice: SUBDEVICE}
def canonical(text):
data = bytearray(bytes.fromhex(text))
for offset in range(0, len(data) - 3, 4):
value = struct.unpack_from("<I", data, offset)[0]
if value in rename:
struct.pack_into("<I", data, offset, rename[value])
return bytes(data)
# First pass: the memory objects the channels name and the channel address space.
memory, spaces = set(), set()
for row in rows:
after = words(row["after"])
if number(row) == 0x2b and after[0] == client and row["params_before"]:
params = words(row["params_before"])
if after[3] == 0xc36f:
memory.update((params[0], params[8]))
elif after[3] in (0xa06c, 0x9067):
spaces.add(params[2] if after[3] == 0xa06c else params[0])
memory.discard(0)
spaces.discard(0)
case = ChannelSequence("chan-workload")
case.uvm()
for holder in (0x5cff0001, 0x5cff0002):
assert case.memory(0x40, new=holder, size=0x200000) == (0, holder)
case.ccsr_model()
case.graphics_stub()
objects = {DEVICE, SUBDEVICE}
compared, differences, last_channel, computes, bound = {}, [], [0], [], [False]
def compare(kind, same, index, detail):
entry = compared.setdefault(kind, [0, 0])
entry[0 if same else 1] += 1
if not same:
differences.append(f"{index}:{kind}:{detail}")
for index, row in enumerate(rows):
escape = number(row)
before, after = words(row["before"]), words(row["after"])
if not before or before[0] != client:
continue
if escape == 0x2b:
parent, new, klass = rename.get(before[1], before[1]), before[2], before[3]
wanted = klass in WORKLOAD_CLASSES or new in memory or new in spaces
if not wanted or parent not in objects:
continue
params = canonical(row["params_before"]) if row["params_before"] else None
size, flags = before[8], before[9]
count = len(constructed["channel"]), len(constructed["group"])
result, handle = case.alloc(CLIENT, parent, new, klass, params=params, size=size,
flags=flags)
reply = bytearray.fromhex(case.request_line().split()[-2]) if params else b""
expected = bytearray(canonical(row["params_after"])) if params else b""
if result == 0:
objects.add(handle)
if klass == 0xa06c:
case.groups[handle] = E.q(new_object("group", count[1]) + 0x138)
case.describe_group(handle)
elif klass == 0xc36f:
case.channels[handle] = new_object("channel", count[0])
case.describe_channel(handle, struct.unpack_from("<I", reply, 0x84)[0])
last_channel[0] = handle
if struct.unpack_from("<I", params, 0x18)[0]:
computes.append(handle)
elif klass == 0x90f1 and new in spaces:
assert case.run.dup_address_space(case.uvm_device, CLIENT, handle) == 0
assert case.run.set_page_directory(case.run.spaces[-1], 0x123000, 4,
1) == 0
case.flush_run()
if klass == 0xc36f and len(reply) == 0x170:
reply[0x84:0x88] = expected[0x84:0x88] = bytes(4)
compare(f"alloc-{klass:x}", (result, reply) == (after[10], expected), index,
f"{result:x}/{after[10]:x}")
elif escape == 0x2a and before[2] in WORKLOAD_CONTROLS:
target, command = rename.get(before[1], before[1]), before[2]
if target not in objects:
continue
if command == 0xa06c0101 and not bound[0] and target in case.groups and any(
E.q(case.channels[channel] + 0x278) and channel in computes
and E.q(E.q(case.channels[channel] + 0x278) + 0x138) == case.groups[target]
for channel in computes):
for channel in computes:
case.context_bound(channel)
bound[0] = True
if command == 0x80170d:
result, listed = case.channel_list([last_channel[0]])
compare("control-80170d", result == after[7], index, f"{result:x}")
continue
params = canonical(row["params_before"])
result, reply = case.control(CLIENT, target, command, params=params)
expected = canonical(row["params_after"])
if command == 0xc36f0108:
reply = expected = b""
if target in case.groups:
case.describe_group(target)
compare(f"control-{command:x}", (result, reply) == (after[7], expected), index,
f"{result:x}/{after[7]:x} {reply.hex()}/{expected.hex()}")
elif escape == 0x29 and before[2] in objects - {DEVICE, SUBDEVICE}:
result = case.free(CLIENT, 0, before[2])
objects.discard(before[2])
compare("free", result == after[3], index, f"{before[2]:x} {result:x}/{after[3]:x}")
case.lines.append("workload-compare " + " ".join(
f"{kind}={same}/{same + different}" for kind, (same, different) in
sorted(compared.items())))
for difference in differences:
case.lines.append(f"workload-difference {difference}")
return case
def event_cases():
"""C1: NV_ESC_ALLOC_OS_EVENT (0xce) and NV_ESC_FREE_OS_EVENT (0xcf), entered at the
original's `rm_ioctl` (they are handled in front of `_nv000800rm`), and class 0x79
(NV01_EVENT_OS_EVENT) through `_nv000800rm`. Lines:
E <node> <file> <escape> <request> -> <status of rm_ioctl> <reply> <diag|->
the 16-byte nv_ioctl_alloc_os_event_t {hClient, hDevice, fd, Status}
events <n> <byte> records in the control state's list (+0x298) after the request and
the "has events" byte of the calling file (nvfp+0x70)
The reply of a class 0x79 allocation carries, at params +0x10, the address of the event
record in fixture memory (the original returns a kernel pointer there): the harness
replaces a non-zero value that differs from the request by 0x1000 in the record."""
case = standard("chan-events")
control = case.context["nodes"]["ctl"]
lock = E.allocate(16)
E.wq(control + 0x2a0, lock)
case.fixture("event-lock the control state's event spinlock (+0x2a0, a 16-byte wrapper"
" the original's own initialization of the control node creates) is fixture"
" memory; the list head +0x298 starts NULL")
stack = U.runtime_stack()
def os_event(escape, file, descriptor, client=CLIENT, size=16, node="dev"):
request = struct.pack("<IIiI", client, SUBDEVICE, descriptor, 0xdddddddd)[:size]
block = E.allocate(len(request) + 16)
E.write(block, request)
state["diag"].clear()
case.begin()
status = E.call("rm_ioctl", stack, case.context["nodes"][node],
case.context["files"][file], escape, block, len(request)) & 0xffffffff
reply = E.read(block, len(request))
case.lines.append(f"E {node} {file} {escape:x} {request.hex()} -> {status:x}"
f" {reply.hex()} {','.join(state['diag']) or '-'}")
case.finish()
count, entry = 0, E.q(control + 0x298)
while entry and count < 64:
count, entry = count + 1, E.q(entry + 0x30)
case.lines.append(f"events {count:x} {E.b(case.context['files'][file] + 0x70):x}")
return status, (struct.unpack_from("<I", reply, 12)[0] if size >= 16 else 0)
def event(parent, new, index, data, file=3, node="dev", owner=CLIENT, klass=0x79,
source=0, named=0x79):
"""Class 0x79: NV0005_ALLOC_PARAMETERS {hParentClient, hSrcResource, hClass,
notifyIndex, data}."""
params = struct.pack("<IIIIQ", owner, source, named, index, data)
result, handle = case.alloc(CLIENT, parent, new, klass, params=params, node=node,
file=file)
line = case.request_line()
parts = line.split()
out = bytearray.fromhex(parts[-2]) if parts[-2] != "-" else None
if out is not None and struct.unpack_from("<Q", out, 16)[0] not in (0, data):
struct.pack_into("<Q", out, 16, 0x1000)
parts[-2] = out.hex()
case.lines[len(case.lines) - 1 - case.lines[::-1].index(line)] = " ".join(parts)
return result, handle
# Device files 3, 4, 5 are descriptors 20, 21, 22; control file 0 is descriptor 10.
assert os_event(0xce, 3, 20) == (0, 0)
os_event(0xce, 3, 20) # duplicate (client, fd)
os_event(0xce, 4, 20) # same key from another file
os_event(0xce, 4, 21)
os_event(0xce, 3, 22) # a second record on one file
os_event(0xce, 3, 23, client=0x12345678)
os_event(0xce, 3, 20, size=12)
os_event(0xce, 3, 20, size=20)
os_event(0xce, 0, 10, node="ctl")
# The workload's seven subdevice events (graphics, six copy engines) on descriptor 20.
handles = []
for number, index in enumerate((0x3800000c, 0x38000019, 0x3800001a, 0x3800001b,
0x3800001c, 0x3800001d, 0x3800001e)):
result, handle = event(SUBDEVICE, 0x5c000081 + number, index, 20)
handles.append(handle)
event(SUBDEVICE, 0x5c000081, 0x3800000c, 20) # handle in use
event(SUBDEVICE, 0, 0x3800000c, 30) # no record for the fd
event(SUBDEVICE, 0, 0x3800000c, 21) # another file's record
event(SUBDEVICE, 0, 0x3800000c, 20, file=4, node="dev")
event(SUBDEVICE, 0, 0x3800000c, 20, file=0, node="ctl")
# Flag and index variations on the subdevice; NONSTALL on other sources.
for index in (0x1000000c, 0x3000000c, 0x0800000c, 0x2800000c, 0x3800ffff, 0x38000000,
0x380000ff, 0x3801000c, 0xb800000c, 0x3c00000c, 0xc):
result, handle = event(SUBDEVICE, 0, index, 20)
if result == 0:
case.free(CLIENT, 0, handle)
group, made = copy_group(case, 1)
channel, notifier, engine_object = made[0]
for parent in (DEVICE, CLIENT, channel, engine_object, group, case.block, case.external,
0x12345678):
for index in (0x38000019, 0x30000001):
result, handle = event(parent, 0, index, 20)
if result == 0:
case.free(CLIENT, 0, handle)
event(SUBDEVICE, 0, 0x3800000c, 20, owner=0)
event(SUBDEVICE, 0, 0x3800000c, 20, owner=0x12345678)
event(SUBDEVICE, 0, 0x3800000c, 20, source=channel)
event(SUBDEVICE, 0, 0x3800000c, 20, klass=5)
event(SUBDEVICE, 0, 0x3800000c, 20, klass=5, named=0x78)
# Frees: the OS event while class 0x79 objects use it, the objects, then the records.
os_event(0xcf, 3, 20)
for handle in handles[:3]:
case.free(CLIENT, 0, handle, node="dev", file=3)
case.free(CLIENT, 0, handle)
os_event(0xcf, 3, 20)
os_event(0xcf, 3, 30)
os_event(0xcf, 4, 21)
os_event(0xcf, 3, 22, client=0x12345678)
os_event(0xcf, 3, 22, size=12)
os_event(0xce, 3, 20)
assert case.free(CLIENT, 0, CLIENT) == 0
os_event(0xcf, 3, 20)
return case
CASES = (group_cases, group_mode_cases, share_cases, channel_cases, channel_rule_cases,
channel_id_cases, channel_free_cases, engine_object_cases, schedule_cases,
compute_object_cases, compute_group_cases, workload_case, event_cases)
def sequences():
cases = []
for build in CASES:
if "--only" in sys.argv and build.__name__ not in sys.argv:
continue
try:
cases.append(build())
except BaseException:
# Development aid: the requests made before the failure.
sys.stderr.write("\n".join(summary(os_state["case"].lines)[-12:]) + "\n")
raise
return cases
def summary(lines):
"""Development view: one short line per request."""
out, count = [], 0
for line in lines:
if line[:2] in ("A ", "F ", "C "):
parts = line.split()
head = bytes.fromhex(parts[3])
words = struct.unpack_from("<IIII", head)
what = {"A": f"alloc {words[3]:x} parent {words[1]:x} new {words[2]:x}",
"F": f"free {words[2]:x}", "C": f"ctrl {words[2]:x} on {words[1]:x}"}[parts[0]]
reply = bytes.fromhex(parts[parts.index("->") + 2])
status = struct.unpack_from("<I", reply, {"A": 40, "F": 12, "C": 28}[parts[0]])[0]
if parts[0] == "A":
what += f" -> {struct.unpack_from('<I', reply, 8)[0]:x}"
out.append(f"{what} = {status:x} [{parts[-1]}] params {parts[4][:48]}")
elif line.split()[0] in ("r", "w", "m", "fill", "copy", "bar2", "os"):
count += 1
continue
else:
out.append(" " + line[:230])
continue
if count:
out.insert(-1, f" ({count} events)")
count = 0
return out
def main():
cases = sequences()
lines = ["# Original channel-object paths under instruction emulation; see "
"tools/check_rmapi_channel_binary.py", f"# original sha256 {DIGEST}"]
for case in cases:
lines += case.lines
text = "\n".join(lines) + "\n"
OUT.mkdir(parents=True, exist_ok=True)
if "--only" in sys.argv:
sys.stdout.write(text if "--print" in sys.argv else "")
if "--summary" in sys.argv:
print("\n".join(summary(lines)))
elif "--check" in sys.argv:
assert TARGET.read_text() == text, "channel oracle differs from the checked copy"
else:
TARGET.write_text(text)
kinds = {}
for line in text.splitlines():
if line[:2] in ("A ", "F ", "C ", "M ", "U "):
kinds[line[0]] = kinds.get(line[0], 0) + 1
print(json.dumps(dict(
original_sha256=DIGEST, oracle=str(TARGET.relative_to(ROOT)),
oracle_sha256=hashlib.sha256(text.encode()).hexdigest(), cases=len(cases),
operations=kinds,
events={kind: sum(1 for line in text.splitlines() if line.startswith(kind + " "))
for kind in ("r", "w", "m", "fill", "copy", "bar2", "os")})))
if __name__ == "__main__":
main()