Files
nvdriver/tools/check_uvm_ioctl_layout.py
morebrackets b7ed8c5c2c Merge pull request #281 from morebrackets/fix/tools-oracle-portability-and-capture-safety
tools: make UVM/TLB/time C oracles portable and harden control compare/capture
2026-12-02 15:28:58 -08:00

183 lines
8.8 KiB
Python

#!/usr/bin/env python3
"""Structure layouts of the /dev/nvidia-uvm ioctl interface, computed by the C compiler
from the open-source nvidia-uvm headers of 580.178.04 (evidence class [S]).
Reads the routing table of uvm.c (UVM_ROUTE_CMD_* lines of uvm_ioctl), compiles a
program that prints the size of every parameter structure, the offset of its rmStatus
and, for the commands the libcuda workload issues, the offset and size of every field.
Writes target/uvm/ioctl-layout.txt, which `uvm::ioctl` is tested against.
Two source trees are compiled and must agree: the reference tree of the analysis and, when
present, the tree the loaded module was built from (/usr/src/nvidia-srv-580.178.04).
"""
import argparse
import hashlib
import json
import os
from pathlib import Path
import re
import subprocess
import sys
import tempfile
ROOT = Path(__file__).resolve().parents[1]
REFERENCE = Path("/home/geodd/nvidia-driver/analysis-580.178.04/reference/"
"open-gpu-kernel-modules-580.178.04/kernel-open")
INSTALLED = Path("/usr/src/nvidia-srv-580.178.04")
INSTALLED_FALLBACK = Path("/usr/src/nvidia-580.178.04")
def resolve_source_trees():
"""Return available `(label, kernel_open_root)` source trees in priority order."""
candidates = []
env_kernel = os.environ.get("NV_RS_KERNEL_SRC")
if env_kernel:
candidates.append(("env", Path(env_kernel)))
env_analysis = os.environ.get("NV_RS_ANALYSIS_ROOT")
if env_analysis:
candidates.append((
"analysis",
Path(env_analysis) / "reference/open-gpu-kernel-modules-580.178.04/kernel-open",
))
candidates.append(("analysis_extracted", Path(env_analysis) / "extracted/kernel"))
candidates.extend([
("reference", REFERENCE),
("installed", INSTALLED),
("installed", INSTALLED_FALLBACK),
])
found = []
seen = set()
for label, tree in candidates:
if not (tree / "nvidia-uvm/uvm.c").is_file() or not (tree / "common/inc").is_dir():
continue
key = tree.resolve()
if key in seen:
continue
seen.add(key)
found.append((label, tree))
return found
FIELDS = {
"UVM_INITIALIZE": ("flags", "rmStatus"),
"UVM_MM_INITIALIZE": ("uvmFd", "rmStatus"),
"UVM_PAGEABLE_MEM_ACCESS": ("pageableMemAccess", "rmStatus"),
"UVM_REGISTER_GPU": ("gpu_uuid", "numaEnabled", "numaNodeId", "rmCtrlFd", "hClient",
"hSmcPartRef", "rmStatus"),
"UVM_UNREGISTER_GPU": ("gpu_uuid", "rmStatus"),
"UVM_CREATE_RANGE_GROUP": ("rangeGroupId", "rmStatus"),
"UVM_DESTROY_RANGE_GROUP": ("rangeGroupId", "rmStatus"),
"UVM_SET_RANGE_GROUP": ("rangeGroupId", "requestedBase", "length", "rmStatus"),
"UVM_PREVENT_MIGRATION_RANGE_GROUPS": ("rangeGroupIds", "numGroupIds", "rmStatus"),
"UVM_ALLOW_MIGRATION_RANGE_GROUPS": ("rangeGroupIds", "numGroupIds", "rmStatus"),
"UVM_MIGRATE_RANGE_GROUP": ("rangeGroupId", "destinationUuid", "rmStatus"),
"UVM_SET_PREFERRED_LOCATION": ("requestedBase", "length", "preferredLocation",
"preferredCpuNumaNode", "rmStatus"),
"UVM_UNSET_PREFERRED_LOCATION": ("requestedBase", "length", "rmStatus"),
"UVM_SET_ACCESSED_BY": ("requestedBase", "length", "accessedByUuid", "rmStatus"),
"UVM_UNSET_ACCESSED_BY": ("requestedBase", "length", "accessedByUuid", "rmStatus"),
"UVM_ENABLE_READ_DUPLICATION": ("requestedBase", "length", "rmStatus"),
"UVM_DISABLE_READ_DUPLICATION": ("requestedBase", "length", "rmStatus"),
"UVM_MIGRATE": ("base", "length", "destinationUuid", "flags", "semaphoreAddress",
"semaphorePayload", "cpuNumaNode", "userSpaceStart", "userSpaceLength",
"rmStatus"),
"UVM_DISCARD": ("base", "length", "flags", "rmStatus"),
"UVM_PAGEABLE_MEM_ACCESS_ON_GPU": ("gpu_uuid", "pageableMemAccess", "rmStatus"),
"UVM_ENABLE_PEER_ACCESS": ("gpuUuidA", "gpuUuidB", "rmStatus"),
"UVM_DISABLE_PEER_ACCESS": ("gpuUuidA", "gpuUuidB", "rmStatus"),
"UVM_REGISTER_GPU_VASPACE": ("gpuUuid", "rmCtrlFd", "hClient", "hVaSpace", "rmStatus"),
"UVM_UNREGISTER_GPU_VASPACE": ("gpuUuid", "rmStatus"),
"UVM_REGISTER_CHANNEL": ("gpuUuid", "rmCtrlFd", "hClient", "hChannel", "base", "length",
"rmStatus"),
"UVM_UNREGISTER_CHANNEL": ("gpuUuid", "hClient", "hChannel", "rmStatus"),
"UVM_CREATE_EXTERNAL_RANGE": ("base", "length", "rmStatus"),
"UVM_MAP_EXTERNAL_ALLOCATION": ("base", "length", "offset", "perGpuAttributes",
"gpuAttributesCount", "rmCtrlFd", "hClient", "hMemory",
"rmStatus"),
"UVM_FREE": ("base", "length", "rmStatus"),
"UVM_MAP_DYNAMIC_PARALLELISM_REGION": ("base", "length", "gpuUuid", "rmStatus"),
"UVM_ALLOC_SEMAPHORE_POOL": ("base", "length", "perGpuAttributes", "gpuAttributesCount",
"rmStatus"),
"UVM_VALIDATE_VA_RANGE": ("base", "length", "rmStatus"),
}
ATTRIBUTES = ("gpuUuid", "gpuMappingType", "gpuCachingType", "gpuFormatType", "gpuElementBits",
"gpuCompressionType")
def routes(uvm_c):
"""(name, init check, heap-allocated block) in the order of uvm_ioctl."""
found = re.findall(r"UVM_ROUTE_CMD_(STACK|ALLOC)_(NO_INIT|INIT)_CHECK\((UVM_[A-Z0-9_]+),",
uvm_c)
return [(name, check == "INIT", storage == "ALLOC") for storage, check, name in found]
def layout(uvm, include):
table = routes((uvm / "uvm.c").read_text())
if len(table) != 45:
raise RuntimeError(f"expected 45 UVM ioctl routes in {uvm / 'uvm.c'}, found {len(table)}")
program = ['#include <stdio.h>', '#include <stddef.h>', '#include "uvm_linux_ioctl.h"',
'int main(void) {']
for name, check, heap in table:
program.append(
f'printf("ioctl %x {name} %zx %zx {int(check)} {int(heap)}\\n", (unsigned){name}, '
f'sizeof({name}_PARAMS), offsetof({name}_PARAMS, rmStatus));')
for field in FIELDS.get(name, ()):
program.append(
f'printf("field {name} {field} %zx %zx\\n", offsetof({name}_PARAMS, {field}), '
f'sizeof((({name}_PARAMS *)0)->{field}));')
program.append('printf("attributes %zx\\n", sizeof(UvmGpuMappingAttributes));')
for field in ATTRIBUTES:
program.append(
f'printf("attribute {field} %zx %zx\\n", offsetof(UvmGpuMappingAttributes, {field}), '
f'sizeof(((UvmGpuMappingAttributes *)0)->{field}));')
program += ['printf("constant UVM_DEINITIALIZE %x\\n", (unsigned)UVM_DEINITIALIZE);',
'printf("constant UVM_MAX_GPUS %x\\n", (unsigned)UVM_MAX_GPUS);',
'printf("constant UVM_INIT_FLAGS_MASK %llx\\n", '
'(unsigned long long)UVM_INIT_FLAGS_MASK);',
'return 0; }']
with tempfile.TemporaryDirectory() as directory:
source = Path(directory) / "layout.c"
source.write_text("\n".join(program))
binary = Path(directory) / "layout"
subprocess.run(["gcc", f"-I{uvm}", f"-I{include}", str(source), "-o", str(binary)],
check=True)
return subprocess.run([str(binary)], check=True, capture_output=True, text=True).stdout
def main(argv=None):
parser = argparse.ArgumentParser(description="Compute /dev/nvidia-uvm ioctl struct layouts.")
parser.add_argument("--check", action="store_true",
help="Verify target/uvm/ioctl-layout.txt matches the computed layout.")
args = parser.parse_args(argv)
source_trees = resolve_source_trees()
if not source_trees:
raise SystemExit(
"Unable to locate NVIDIA 580.178.04 nvidia-uvm sources; "
"set NV_RS_KERNEL_SRC or NV_RS_ANALYSIS_ROOT."
)
first_label, first_tree = source_trees[0]
text = layout(first_tree / "nvidia-uvm", first_tree / "common/inc")
trees = [first_label]
for label, tree in source_trees[1:]:
other = layout(tree / "nvidia-uvm", tree / "common/inc")
if other != text:
raise SystemExit(f"the {label} ({tree}) and {first_label} ({first_tree}) sources disagree")
trees.append(label)
text = ("# /dev/nvidia-uvm ioctl layouts from the public source; see "
"tools/check_uvm_ioctl_layout.py\n" + text)
target = ROOT / "target/uvm/ioctl-layout.txt"
target.parent.mkdir(parents=True, exist_ok=True)
if args.check:
if not target.is_file() or target.read_text() != text:
raise SystemExit("layout record differs from the checked copy")
else:
target.write_text(text)
print(json.dumps(dict(record=str(target.relative_to(ROOT)), trees=trees,
sha256=hashlib.sha256(text.encode()).hexdigest(),
ioctls=text.count("\nioctl "), fields=text.count("\nfield "))))
if __name__ == "__main__":
main()