diff --git a/install.sh b/install.sh index ef681fd7..a602d376 100755 --- a/install.sh +++ b/install.sh @@ -1,6 +1,7 @@ #!/bin/bash # Build, sign (when Secure Boot needs it), install and reload nvdriver -# (nvidia_rs.ko + optional UVM/modeset bridge modules). +# (standalone nvidia_rs.ko + nvidia_rs_modeset.ko + nvidia_rs_drm.ko, plus +# optional UVM/modeset bridge modules). # # Order matters: build first, so a build failure leaves the running driver # untouched; unload only once there is something to install; never report @@ -18,6 +19,8 @@ SIGN_FILE=/lib/modules/$KREL/build/scripts/sign-file MOK_PRIV=${MOK_PRIV:-/var/lib/shim-signed/mok/MOK.priv} MOK_DER=${MOK_DER:-/var/lib/shim-signed/mok/MOK.der} INSTALL_DIR=/lib/modules/$KREL/updates/nvdriver +STANDALONE_DESKTOP=${STANDALONE_DESKTOP:-1} +LOAD_DESKTOP_KMS=${LOAD_DESKTOP_KMS:-$STANDALONE_DESKTOP} BUILD_BRIDGES=${BUILD_BRIDGES:-1} BIND_DEV_NODES=${BIND_DEV_NODES:-1} CONFIGURE_MODPROBE=${CONFIGURE_MODPROBE:-1} @@ -123,9 +126,15 @@ install_volta_forever() { echo "== build ==" make modules KO_FILES=(kernel-open/nvidia_rs.ko) +HAS_MODESET_KO=0 +HAS_DRM_KO=0 for opt_ko in kernel-open/nvidia_rs_modeset.ko kernel-open/nvidia_rs_drm.ko kernel-open/nvidia_rs_peermem.ko; do - [ -f "$opt_ko" ] && KO_FILES+=("$opt_ko") + if [ -f "$opt_ko" ]; then + KO_FILES+=("$opt_ko") + fi done +if [ -f kernel-open/nvidia_rs_modeset.ko ]; then HAS_MODESET_KO=1; fi +if [ -f kernel-open/nvidia_rs_drm.ko ]; then HAS_DRM_KO=1; fi if [ "$BUILD_BRIDGES" = "1" ]; then make uvm-bridge make modeset-bridge @@ -226,7 +235,8 @@ sudo depmod -a "$KREL" if [ "$CONFIGURE_MODPROBE" = "1" ]; then echo "== configure modprobe & autoload ==" - sudo tee /etc/modprobe.d/nvdriver.conf >/dev/null <<'EOF' + { + cat <<'EOF' # Managed by nvdriver ./install.sh (set CONFIGURE_MODPROBE=0 to opt out) blacklist nouveau blacklist nvidia @@ -240,27 +250,38 @@ install nvidia_uvm /bin/false alias char-major-195-* nvidia_rs options nvidia_rs runtime_engines=1 pci_target=* EOF - if [ "$BUILD_BRIDGES" = "1" ]; then - sudo tee /etc/modules-load.d/nvdriver.conf >/dev/null <<'EOF' -nvidia_rs -nvidia_rs_uvm_bridge -nvidia_rs_modeset_bridge -EOF - else - sudo tee /etc/modules-load.d/nvdriver.conf >/dev/null <<'EOF' -nvidia_rs -EOF - fi + if [ "$LOAD_DESKTOP_KMS" = "1" ] && [ "$HAS_DRM_KO" = "1" ]; then + echo "options nvidia_rs_drm modeset=1" + fi + } | sudo tee /etc/modprobe.d/nvdriver.conf >/dev/null + { + echo "nvidia_rs" + if [ "$LOAD_DESKTOP_KMS" = "1" ]; then + if [ "$HAS_MODESET_KO" = "1" ]; then + echo "nvidia_rs_modeset" + fi + if [ "$HAS_DRM_KO" = "1" ]; then + echo "nvidia_rs_drm" + fi + fi + if [ "$BUILD_BRIDGES" = "1" ]; then + echo "nvidia_rs_uvm_bridge" + echo "nvidia_rs_modeset_bridge" + fi + } | sudo tee /etc/modules-load.d/nvdriver.conf >/dev/null fi if [ "$CONFIGURE_UDEV" = "1" ]; then - echo "== configure udev drop-in /dev/nvidia* symlinks ==" + echo "== configure udev drop-in /dev/nvidia* & DRM rules ==" sudo tee /etc/udev/rules.d/70-nvdriver.rules >/dev/null <<'EOF' # Managed by nvdriver ./install.sh (set CONFIGURE_UDEV=0 to opt out) KERNEL=="nvidia-rs-rmapi-ctl", MODE="0666", SYMLINK+="nvidiactl" KERNEL=="nvidia-rs-uvm", MODE="0666", SYMLINK+="nvidia-uvm" KERNEL=="nvidia-rs-modeset", MODE="0666", SYMLINK+="nvidia-modeset" KERNEL=="nvidia-rs-rmapi-gpu[0-9]*", MODE="0666", SYMLINK+="nvidia%n" +# Standalone DRM KMS/render nodes exposed by nvidia_rs_drm +SUBSYSTEM=="drm", KERNEL=="card[0-9]*", DRIVERS=="nvidia_rs", MODE="0660", TAG+="uaccess" +SUBSYSTEM=="drm", KERNEL=="renderD[0-9]*", DRIVERS=="nvidia_rs", MODE="0666", TAG+="uaccess" EOF sudo udevadm control --reload-rules 2>/dev/null || true fi @@ -268,6 +289,14 @@ fi echo "== reload ==" # shellcheck disable=SC2086 sudo modprobe nvidia_rs $MODPROBE_ARGS +if [ "$LOAD_DESKTOP_KMS" = "1" ]; then + if [ "$HAS_MODESET_KO" = "1" ]; then + sudo modprobe nvidia_rs_modeset || true + fi + if [ "$HAS_DRM_KO" = "1" ]; then + sudo modprobe nvidia_rs_drm modeset=1 || true + fi +fi if [ "$BUILD_BRIDGES" = "1" ]; then sudo modprobe nvidia_rs_uvm_bridge || true sudo modprobe nvidia_rs_modeset_bridge || true diff --git a/packaging/arch/62-nvdriver-dev.rules b/packaging/arch/62-nvdriver-dev.rules index 3b18ac4e..9bd0be1c 100644 --- a/packaging/arch/62-nvdriver-dev.rules +++ b/packaging/arch/62-nvdriver-dev.rules @@ -1,3 +1,5 @@ # Development mode (tools/dev_mode.sh): root-only nvdriver nodes, so no desktop process -# keeps nvidia_rs pinned and tools/dev_reload.sh can replace the module without a reboot. -SUBSYSTEM=="misc", KERNEL=="nvidia-rs-rmapi-ctl|nvidia-rs-rmapi-gpu[0-9]*|nvidia-rs-uvm", GROUP:="root", MODE:="0600", TAG-="uaccess" +# keeps nvidia_rs (or standalone nvidia_rs_modeset / nvidia_rs_drm) pinned and +# tools/dev_reload.sh can replace the modules without a reboot. +SUBSYSTEM=="misc", KERNEL=="nvidia-rs-rmapi-ctl|nvidia-rs-rmapi-gpu[0-9]*|nvidia-rs-uvm|nvidia-rs-modeset", GROUP:="root", MODE:="0600", TAG-="uaccess" +SUBSYSTEM=="drm", KERNEL=="card[0-9]*|renderD[0-9]*", DRIVERS=="nvidia_rs", GROUP:="root", MODE:="0600", TAG-="uaccess" diff --git a/tools/bind_dev_nodes.sh b/tools/bind_dev_nodes.sh index 55f233f7..a5e5bd13 100755 --- a/tools/bind_dev_nodes.sh +++ b/tools/bind_dev_nodes.sh @@ -41,12 +41,15 @@ unbind_one() { if mountpoint -q "$dst" 2>/dev/null; then umount "$dst" fi + if [ -f "$dst" ] && [ ! -L "$dst" ] && [ ! -s "$dst" ]; then + rm -f "$dst" + fi } case "$MODE" in --bind) - if [ -d /sys/module/nvidia ]; then - echo "ABORT: stock nvidia.ko is loaded; refusing to overwrite /dev/nvidia*." >&2 + if [ -d /sys/module/nvidia ] || [ -d /sys/module/nvidia_uvm ] || [ -d /sys/module/nvidia_drm ]; then + echo "ABORT: stock NVIDIA kernel module (nvidia/nvidia_uvm/nvidia_drm) is loaded; refusing to overwrite /dev/nvidia*." >&2 exit 1 fi if [ ! -c /dev/nvidia-rs-rmapi-ctl ]; then diff --git a/tools/check_drm_ioctl_abi.py b/tools/check_drm_ioctl_abi.py new file mode 100755 index 00000000..27d2a105 --- /dev/null +++ b/tools/check_drm_ioctl_abi.py @@ -0,0 +1,992 @@ +#!/usr/bin/env python3 +"""Compiler-exact C/Rust ABI conformance verifier for NVIDIA DRM & NVKMS ioctls. + +Verifies 100% binary ABI parity across three boundaries: +1. `kernel-open/nvidia-drm/nvidia_rs_drm.c` vs stock + `/usr/src/nvidia-580.178.04/nvidia-drm/nvidia-drm-ioctl.h`: + - Compiles two independent C probes with `gcc` against kernel UAPI ``: + one including stock `nvidia-drm-ioctl.h` (`-DNV_LINUX`) and one compiling + the exact UAPI block extracted from `kernel-open/nvidia-drm/nvidia_rs_drm.c`. + - Verifies all 24 `DRM_IOCTL_NVIDIA_*` ioctls (command indices `0x00`..`0x18`, + encoded `unsigned long` `_IO`/`_IOW`/`_IOWR` ioctl numbers, `sizeof`, + `_Alignof`, and `offsetof` + field `sizeof` for every field of every struct, + including nested helper structs and shared constants/enums), plus completeness + against stock headers and `nv_rs_drm_ioctls[]` registration. +2. `kernel-open/nvidia-modeset/nv_rs_kms_abi.h` vs stock + `/usr/src/nvidia-580.178.04/nvidia-modeset/nvkms-ioctl.h`: + - Verifies `NV_RS_NVKMS_IOCTL_MAGIC == NVKMS_IOCTL_MAGIC`, + `NV_RS_NVKMS_IOCTL_CMD == NVKMS_IOCTL_CMD`, + `NV_RS_NVKMS_IOCTL_IOWR == NVKMS_IOCTL_IOWR`, + `sizeof(struct nv_rs_nvkms_ioctl_params) == sizeof(struct NvKmsIoctlParams)`, + `_Alignof`, and `offsetof` + `sizeof` for `cmd`, `size`, and `address`. +3. `kernel-open/nvidia-modeset/nv_rs_kms_abi.h` `struct nv_rs_kms_gpu_caps` vs + `src/nvidia/kernel/modeset_ffi.rs` `#[repr(C)] pub struct NvRsKmsGpuCaps`: + - Compiles both a C probe (`gcc`) including `nv_rs_kms_abi.h` and a Rust probe + (`rustc`) embedding the exact `NvRsKmsGpuCaps` definition extracted from + `src/nvidia/kernel/modeset_ffi.rs`. + - Verifies identical field list/order, `sizeof`, `alignof`, and every field's + exact `offsetof` and `sizeof`. +""" +from __future__ import annotations + +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] +STOCK_NVIDIA_SRC = Path(os.environ.get("STOCK_NVIDIA_SRC", "/usr/src/nvidia-580.178.04")) + +STOCK_DRM_IOCTL_H = STOCK_NVIDIA_SRC / "nvidia-drm" / "nvidia-drm-ioctl.h" +STOCK_NVKMS_IOCTL_H = STOCK_NVIDIA_SRC / "nvidia-modeset" / "nvkms-ioctl.h" +STOCK_COMMON_INC = STOCK_NVIDIA_SRC / "common" / "inc" + +RS_DRM_C = ROOT / "kernel-open" / "nvidia-drm" / "nvidia_rs_drm.c" +RS_KMS_ABI_H = ROOT / "kernel-open" / "nvidia-modeset" / "nv_rs_kms_abi.h" +RS_MODESET_FFI_RS = ROOT / "src" / "nvidia" / "kernel" / "modeset_ffi.rs" + +# All 24 NVIDIA 580.178.04 DRM ioctls: +# (suffix, expected_cmd_index, struct_name_or_None, tuple_of_field_names) +DRM_IOCTL_SPECS: tuple[tuple[str, int, str | None, tuple[str, ...]], ...] = ( + ( + "GET_CRTC_CRC32", + 0x00, + "drm_nvidia_get_crtc_crc32_params", + ("crtc_id", "crc32"), + ), + ( + "GEM_IMPORT_NVKMS_MEMORY", + 0x01, + "drm_nvidia_gem_import_nvkms_memory_params", + ("mem_size", "nvkms_params_ptr", "nvkms_params_size", "handle", "__pad"), + ), + ( + "GEM_IMPORT_USERSPACE_MEMORY", + 0x02, + "drm_nvidia_gem_import_userspace_memory_params", + ("size", "address", "handle"), + ), + ( + "GET_DEV_INFO", + 0x03, + "drm_nvidia_get_dev_info_params", + ( + "gpu_id", + "mig_device", + "primary_index", + "supports_alloc", + "generic_page_kind", + "page_kind_generation", + "sector_layout", + "supports_sync_fd", + "supports_semsurf", + ), + ), + ( + "FENCE_SUPPORTED", + 0x04, + None, + (), + ), + ( + "PRIME_FENCE_CONTEXT_CREATE", + 0x05, + "drm_nvidia_prime_fence_context_create_params", + ( + "handle", + "index", + "size", + "import_mem_nvkms_params_ptr", + "import_mem_nvkms_params_size", + "event_nvkms_params_ptr", + "event_nvkms_params_size", + ), + ), + ( + "GEM_PRIME_FENCE_ATTACH", + 0x06, + "drm_nvidia_gem_prime_fence_attach_params", + ("handle", "fence_context_handle", "sem_thresh", "__pad"), + ), + ( + "GET_CLIENT_CAPABILITY", + 0x08, + "drm_nvidia_get_client_capability_params", + ("capability", "value"), + ), + ( + "GEM_EXPORT_NVKMS_MEMORY", + 0x09, + "drm_nvidia_gem_export_nvkms_memory_params", + ("handle", "__pad", "nvkms_params_ptr", "nvkms_params_size"), + ), + ( + "GEM_MAP_OFFSET", + 0x0A, + "drm_nvidia_gem_map_offset_params", + ("handle", "__pad", "offset"), + ), + ( + "GEM_ALLOC_NVKMS_MEMORY", + 0x0B, + "drm_nvidia_gem_alloc_nvkms_memory_params", + ("handle", "block_linear", "compressible", "__pad0", "memory_size", "flags", "__pad1"), + ), + ( + "GET_CRTC_CRC32_V2", + 0x0C, + "drm_nvidia_get_crtc_crc32_v2_params", + ("crtc_id", "crc32"), + ), + ( + "GEM_EXPORT_DMABUF_MEMORY", + 0x0D, + "drm_nvidia_gem_export_dmabuf_memory_params", + ("handle", "__pad", "nvkms_params_ptr", "nvkms_params_size"), + ), + ( + "GEM_IDENTIFY_OBJECT", + 0x0E, + "drm_nvidia_gem_identify_object_params", + ("handle", "object_type"), + ), + ( + "DMABUF_SUPPORTED", + 0x0F, + None, + (), + ), + ( + "GET_DPY_ID_FOR_CONNECTOR_ID", + 0x10, + "drm_nvidia_get_dpy_id_for_connector_id_params", + ("connectorId", "dpyId"), + ), + ( + "GET_CONNECTOR_ID_FOR_DPY_ID", + 0x11, + "drm_nvidia_get_connector_id_for_dpy_id_params", + ("dpyId", "connectorId"), + ), + ( + "GRANT_PERMISSIONS", + 0x12, + "drm_nvidia_grant_permissions_params", + ("fd", "dpyId", "type"), + ), + ( + "REVOKE_PERMISSIONS", + 0x13, + "drm_nvidia_revoke_permissions_params", + ("dpyId", "type"), + ), + ( + "SEMSURF_FENCE_CTX_CREATE", + 0x14, + "drm_nvidia_semsurf_fence_ctx_create_params", + ("index", "nvkms_params_ptr", "nvkms_params_size", "handle", "__pad"), + ), + ( + "SEMSURF_FENCE_CREATE", + 0x15, + "drm_nvidia_semsurf_fence_create_params", + ("fence_context_handle", "timeout_value_ms", "wait_value", "fd", "__pad"), + ), + ( + "SEMSURF_FENCE_WAIT", + 0x16, + "drm_nvidia_semsurf_fence_wait_params", + ("fence_context_handle", "fd", "pre_wait_value", "post_wait_value"), + ), + ( + "SEMSURF_FENCE_ATTACH", + 0x17, + "drm_nvidia_semsurf_fence_attach_params", + ("handle", "fence_context_handle", "timeout_value_ms", "shared", "wait_value"), + ), + ( + "GET_DRM_FILE_UNIQUE_ID", + 0x18, + "drm_nvidia_get_drm_file_unique_id_params", + ("id",), + ), +) + +DRM_HELPER_STRUCTS: tuple[tuple[str, tuple[str, ...]], ...] = ( + ("drm_nvidia_crtc_crc32", ("value", "supported", "__pad0", "__pad1")), + ( + "drm_nvidia_crtc_crc32_v2_out", + ("compositorCrc32", "rasterGeneratorCrc32", "outputCrc32"), + ), +) + +DRM_CONSTANTS: tuple[str, ...] = ( + "NV_GEM_ALLOC_NO_SCANOUT", + "NV_GEM_OBJECT_NVKMS", + "NV_GEM_OBJECT_DMABUF", + "NV_GEM_OBJECT_USERMEMORY", + "NV_GEM_OBJECT_UNKNOWN", +) + +NVKMS_IOCTL_FIELDS: tuple[str, ...] = ("cmd", "size", "address") + + +def sha256_file(path: Path) -> str: + return hashlib.sha256(path.read_bytes()).hexdigest() + + +def extract_rs_drm_uapi_section(source_text: str) -> str: + """Extract the exact UAPI defines/structs/enums/ioctls block from nvidia_rs_drm.c.""" + lines = source_text.splitlines() + start_idx = None + for idx, line in enumerate(lines): + if re.match(r"^\s*#\s*define\s+DRM_NVIDIA_", line): + start_idx = idx + break + if start_idx is None: + raise ValueError("Could not find '#define DRM_NVIDIA_' in nvidia_rs_drm.c") + + # End after the last '#define DRM_IOCTL_NVIDIA_*' macro (following line continuations). + last_ioctl_idx = None + for idx in range(start_idx, len(lines)): + if re.match(r"^\s*#\s*define\s+DRM_IOCTL_NVIDIA_", lines[idx]): + last_ioctl_idx = idx + if last_ioctl_idx is None: + raise ValueError("Could not find '#define DRM_IOCTL_NVIDIA_' in nvidia_rs_drm.c") + + end_idx = last_ioctl_idx + while end_idx < len(lines) and lines[end_idx].rstrip().endswith("\\"): + end_idx += 1 + return "\n".join(lines[start_idx : end_idx + 1]) + "\n" + + +def extract_c_struct_fields(source_text: str, struct_name: str) -> list[str]: + """Parse ordered field names of a flat C struct definition.""" + m = re.search( + rf"\bstruct\s+{re.escape(struct_name)}\s*\{{(.*?)\}}\s*;", + source_text, + re.DOTALL, + ) + if m is None: + raise ValueError(f"Could not find 'struct {struct_name}' definition") + body = re.sub(r"/\*.*?\*/", "", m.group(1), flags=re.DOTALL) + body = re.sub(r"//.*", "", body) + fields: list[str] = [] + for raw_stmt in body.split(";"): + stmt = raw_stmt.strip() + if not stmt: + continue + # Strip trailing attributes such as __aligned(8) or NV_ALIGN_BYTES(8). + stmt = re.sub(r"\b(?:__aligned|NV_ALIGN_BYTES)\s*\([^)]*\)", "", stmt).strip() + # Handle array declarators if any (e.g., pad[2]). + stmt = re.sub(r"\[[^\]]*\]", "", stmt).strip() + ident_match = re.search(r"([A-Za-z_][A-Za-z0-9_]*)\s*$", stmt) + if ident_match is None: + raise ValueError(f"Cannot parse field name from '{raw_stmt.strip()}' in struct {struct_name}") + fields.append(ident_match.group(1)) + return fields + + +def extract_rust_struct_block(source_text: str, struct_name: str) -> tuple[str, list[str]]: + """Extract a `#[repr(C)] pub struct { ... }` block and its ordered field names.""" + pattern = re.compile( + rf"((?:#\[[^\]]+\]\s*)+)pub\s+struct\s+{re.escape(struct_name)}\s*\{{(.*?)\}}", + re.DOTALL, + ) + m = pattern.search(source_text) + if m is None: + raise ValueError(f"Could not find 'pub struct {struct_name}' in modeset_ffi.rs") + attrs = m.group(1) + if not re.search(r"#\[\s*repr\s*\(\s*C\s*\)\s*\]", attrs): + raise ValueError(f"Rust struct {struct_name} is missing #[repr(C)]") + body = re.sub(r"//.*", "", m.group(2)) + fields: list[str] = [] + for raw_line in body.split(","): + line = raw_line.strip() + if not line: + continue + fm = re.match(r"^(?:pub(?:\([^)]*\))?\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*:", line) + if fm is None: + raise ValueError(f"Cannot parse Rust field '{line}' in {struct_name}") + fields.append(fm.group(1)) + return m.group(0), fields + + +def build_drm_probe_body() -> str: + """Emit C main() printing JSON for all 24 DRM ioctls, helper structs, and constants.""" + lines = [ + "int main(void) {", + ' printf("{\\n");', + ' printf(" \\"ioctls\\": {\\n");', + ] + for i, (suffix, _idx, struct_name, fields) in enumerate(DRM_IOCTL_SPECS): + comma = "," if i + 1 < len(DRM_IOCTL_SPECS) else "" + cmd_macro = f"DRM_NVIDIA_{suffix}" + ioctl_macro = f"DRM_IOCTL_NVIDIA_{suffix}" + lines.append(f' printf(" \\"{suffix}\\": {{\\n");') + lines.append( + f' printf(" \\"cmd_index\\": %lu,\\n", (unsigned long)({cmd_macro}));' + ) + lines.append( + f' printf(" \\"ioctl_nr\\": %lu,\\n", (unsigned long)({ioctl_macro}));' + ) + if struct_name is None: + lines.append(' printf(" \\"struct_name\\": null,\\n");') + lines.append(' printf(" \\"struct_size\\": 0,\\n");') + lines.append(' printf(" \\"struct_align\\": 0,\\n");') + lines.append(' printf(" \\"fields\\": {}\\n");') + else: + lines.append(f' printf(" \\"struct_name\\": \\"{struct_name}\\",\\n");') + lines.append( + f' printf(" \\"struct_size\\": %zu,\\n", sizeof(struct {struct_name}));' + ) + lines.append( + f' printf(" \\"struct_align\\": %zu,\\n", _Alignof(struct {struct_name}));' + ) + lines.append(' printf(" \\"fields\\": {\\n");') + for j, field in enumerate(fields): + fcomma = "," if j + 1 < len(fields) else "" + lines.append( + f' printf(" \\"{field}\\": {{\\"offset\\": %zu, \\"size\\": %zu}}{fcomma}\\n", ' + f"offsetof(struct {struct_name}, {field}), " + f"sizeof(((struct {struct_name} *)0)->{field}));" + ) + lines.append(' printf(" }\\n");') + lines.append(f' printf(" }}{comma}\\n");') + + lines.append(' printf(" },\\n");') + lines.append(' printf(" \\"helper_structs\\": {\\n");') + for i, (struct_name, fields) in enumerate(DRM_HELPER_STRUCTS): + comma = "," if i + 1 < len(DRM_HELPER_STRUCTS) else "" + lines.append(f' printf(" \\"{struct_name}\\": {{\\n");') + lines.append( + f' printf(" \\"struct_size\\": %zu,\\n", sizeof(struct {struct_name}));' + ) + lines.append( + f' printf(" \\"struct_align\\": %zu,\\n", _Alignof(struct {struct_name}));' + ) + lines.append(' printf(" \\"fields\\": {\\n");') + for j, field in enumerate(fields): + fcomma = "," if j + 1 < len(fields) else "" + lines.append( + f' printf(" \\"{field}\\": {{\\"offset\\": %zu, \\"size\\": %zu}}{fcomma}\\n", ' + f"offsetof(struct {struct_name}, {field}), " + f"sizeof(((struct {struct_name} *)0)->{field}));" + ) + lines.append(' printf(" }\\n");') + lines.append(f' printf(" }}{comma}\\n");') + + lines.append(' printf(" },\\n");') + lines.append(' printf(" \\"constants\\": {\\n");') + for i, const in enumerate(DRM_CONSTANTS): + comma = "," if i + 1 < len(DRM_CONSTANTS) else "" + lines.append( + f' printf(" \\"{const}\\": %lu{comma}\\n", (unsigned long)({const}));' + ) + lines.append(' printf(" }\\n");') + lines.append(' printf("}\\n");') + lines.append(" return 0;") + lines.append("}") + return "\n".join(lines) + "\n" + + +def compile_and_run_c(source: str, extra_args: list[str], label: str) -> dict: + with tempfile.TemporaryDirectory(prefix=f"nvrs-abi-{label}-") as td: + src_path = Path(td) / f"{label}.c" + exe_path = Path(td) / label + src_path.write_text(source, encoding="utf-8") + cmd = ["gcc", "-O2", "-Wall", "-Wextra", *extra_args, str(src_path), "-o", str(exe_path)] + res = subprocess.run(cmd, capture_output=True, text=True) + if res.returncode != 0: + raise RuntimeError( + f"C probe '{label}' failed to compile:\nCMD: {' '.join(cmd)}\nSTDERR:\n{res.stderr}" + ) + out = subprocess.check_output([str(exe_path)], text=True) + return json.loads(out) + + +def compile_and_run_rust(source: str, label: str) -> dict: + with tempfile.TemporaryDirectory(prefix=f"nvrs-abi-{label}-") as td: + src_path = Path(td) / f"{label}.rs" + exe_path = Path(td) / label + src_path.write_text(source, encoding="utf-8") + cmd = ["rustc", "-O", "--edition=2021", str(src_path), "-o", str(exe_path)] + res = subprocess.run(cmd, capture_output=True, text=True) + if res.returncode != 0: + raise RuntimeError( + f"Rust probe '{label}' failed to compile:\nCMD: {' '.join(cmd)}\nSTDERR:\n{res.stderr}" + ) + out = subprocess.check_output([str(exe_path)], text=True) + return json.loads(out) + + +def verify_drm_ioctl_abi() -> dict: + stock_text = STOCK_DRM_IOCTL_H.read_text(encoding="utf-8") + rs_text = RS_DRM_C.read_text(encoding="utf-8") + rs_uapi_snippet = extract_rs_drm_uapi_section(rs_text) + + # Completeness checks against stock header & nvidia_rs_drm.c ioctl dispatch table. + spec_suffixes = {s for s, _, _, _ in DRM_IOCTL_SPECS} + stock_cmd_suffixes = set(re.findall(r"^\s*#\s*define\s+DRM_NVIDIA_([A-Z0-9_]+)\b", stock_text, re.M)) + stock_ioctl_suffixes = set( + re.findall(r"^\s*#\s*define\s+DRM_IOCTL_NVIDIA_([A-Z0-9_]+)\b", stock_text, re.M) + ) + stock_structs = set(re.findall(r"\bstruct\s+(drm_nvidia_[a-z0-9_]+)\s*\{", stock_text)) + spec_structs = {st for _, _, st, _ in DRM_IOCTL_SPECS if st is not None} | { + st for st, _ in DRM_HELPER_STRUCTS + } + rs_table_suffixes = set( + re.findall(r"\bDRM_IOCTL_DEF_DRV\s*\(\s*NVIDIA_([A-Z0-9_]+)\s*,", rs_text) + ) + + completeness_diffs: list[dict] = [] + if stock_cmd_suffixes != spec_suffixes: + completeness_diffs.append( + { + "check": "stock_cmd_macro_set", + "missing_in_spec": sorted(stock_cmd_suffixes - spec_suffixes), + "extra_in_spec": sorted(spec_suffixes - stock_cmd_suffixes), + } + ) + if stock_ioctl_suffixes != spec_suffixes: + completeness_diffs.append( + { + "check": "stock_ioctl_macro_set", + "missing_in_spec": sorted(stock_ioctl_suffixes - spec_suffixes), + "extra_in_spec": sorted(spec_suffixes - stock_ioctl_suffixes), + } + ) + if stock_structs != spec_structs: + completeness_diffs.append( + { + "check": "stock_struct_set", + "missing_in_spec": sorted(stock_structs - spec_structs), + "extra_in_spec": sorted(spec_structs - stock_structs), + } + ) + if rs_table_suffixes != spec_suffixes: + completeness_diffs.append( + { + "check": "nvidia_rs_drm_ioctl_table_registration", + "missing_in_table": sorted(spec_suffixes - rs_table_suffixes), + "extra_in_table": sorted(rs_table_suffixes - spec_suffixes), + } + ) + + # Verify every field present in both stock header and nvidia_rs_drm.c matches our spec. + for _suffix, _idx, st_name, fields in DRM_IOCTL_SPECS: + if st_name is None: + continue + parsed_stock_fields = extract_c_struct_fields(stock_text, st_name) + if tuple(parsed_stock_fields) != fields: + completeness_diffs.append( + { + "check": f"stock_fields:{st_name}", + "stock_header_fields": parsed_stock_fields, + "spec_fields": list(fields), + } + ) + parsed_rs_fields = extract_c_struct_fields(rs_uapi_snippet, st_name) + if tuple(parsed_rs_fields) != fields: + completeness_diffs.append( + { + "check": f"rs_fields:{st_name}", + "rs_fields": parsed_rs_fields, + "spec_fields": list(fields), + } + ) + for st_name, fields in DRM_HELPER_STRUCTS: + parsed_stock_fields = extract_c_struct_fields(stock_text, st_name) + if tuple(parsed_stock_fields) != fields: + completeness_diffs.append( + { + "check": f"stock_fields:{st_name}", + "stock_header_fields": parsed_stock_fields, + "spec_fields": list(fields), + } + ) + parsed_rs_fields = extract_c_struct_fields(rs_uapi_snippet, st_name) + if tuple(parsed_rs_fields) != fields: + completeness_diffs.append( + { + "check": f"rs_fields:{st_name}", + "rs_fields": parsed_rs_fields, + "spec_fields": list(fields), + } + ) + + probe_body = build_drm_probe_body() + stock_probe_src = ( + "#include \n" + "#include \n" + "#include \n" + '#include "nvidia-drm-ioctl.h"\n\n' + + probe_body + ) + rs_probe_src = ( + "#include \n" + "#include \n" + "#include \n" + "#include \n\n" + "typedef uint8_t u8;\n" + "typedef uint16_t u16;\n" + "typedef uint32_t u32;\n" + "typedef uint64_t u64;\n" + "typedef int32_t s32;\n\n" + + rs_uapi_snippet + + "\n" + + probe_body + ) + + stock_data = compile_and_run_c( + stock_probe_src, + ["-DNV_LINUX", f"-I{STOCK_DRM_IOCTL_H.parent}"], + "stock_drm_ioctl", + ) + rs_data = compile_and_run_c(rs_probe_src, [], "rs_drm_ioctl") + + diffs: list[dict] = list(completeness_diffs) + ioctl_results: list[dict] = [] + + for suffix, expected_idx, struct_name, fields in DRM_IOCTL_SPECS: + s_entry = stock_data["ioctls"][suffix] + r_entry = rs_data["ioctls"][suffix] + entry_diffs: list[dict] = [] + + if s_entry["cmd_index"] != expected_idx or r_entry["cmd_index"] != expected_idx: + entry_diffs.append( + { + "item": f"DRM_NVIDIA_{suffix}.cmd_index", + "expected": expected_idx, + "stock": s_entry["cmd_index"], + "rs": r_entry["cmd_index"], + } + ) + if s_entry["ioctl_nr"] != r_entry["ioctl_nr"]: + entry_diffs.append( + { + "item": f"DRM_IOCTL_NVIDIA_{suffix}.ioctl_nr", + "stock": hex(s_entry["ioctl_nr"]), + "rs": hex(r_entry["ioctl_nr"]), + } + ) + if s_entry["struct_size"] != r_entry["struct_size"]: + entry_diffs.append( + { + "item": f"sizeof(struct {struct_name})", + "stock": s_entry["struct_size"], + "rs": r_entry["struct_size"], + } + ) + if s_entry["struct_align"] != r_entry["struct_align"]: + entry_diffs.append( + { + "item": f"_Alignof(struct {struct_name})", + "stock": s_entry["struct_align"], + "rs": r_entry["struct_align"], + } + ) + for field in fields: + sf = s_entry["fields"][field] + rf = r_entry["fields"][field] + if sf != rf: + entry_diffs.append( + { + "item": f"struct {struct_name}.{field}", + "stock": sf, + "rs": rf, + } + ) + diffs.extend(entry_diffs) + ioctl_results.append( + { + "name": f"DRM_IOCTL_NVIDIA_{suffix}", + "cmd_index": r_entry["cmd_index"], + "ioctl_nr": r_entry["ioctl_nr"], + "struct_name": struct_name, + "struct_size": r_entry["struct_size"], + "field_count": len(fields), + "passed": len(entry_diffs) == 0, + "diffs": entry_diffs, + } + ) + + helper_results: list[dict] = [] + for struct_name, fields in DRM_HELPER_STRUCTS: + s_entry = stock_data["helper_structs"][struct_name] + r_entry = rs_data["helper_structs"][struct_name] + h_diffs: list[dict] = [] + if s_entry["struct_size"] != r_entry["struct_size"]: + h_diffs.append( + { + "item": f"sizeof(struct {struct_name})", + "stock": s_entry["struct_size"], + "rs": r_entry["struct_size"], + } + ) + if s_entry["struct_align"] != r_entry["struct_align"]: + h_diffs.append( + { + "item": f"_Alignof(struct {struct_name})", + "stock": s_entry["struct_align"], + "rs": r_entry["struct_align"], + } + ) + for field in fields: + if s_entry["fields"][field] != r_entry["fields"][field]: + h_diffs.append( + { + "item": f"struct {struct_name}.{field}", + "stock": s_entry["fields"][field], + "rs": r_entry["fields"][field], + } + ) + diffs.extend(h_diffs) + helper_results.append( + { + "struct_name": struct_name, + "struct_size": r_entry["struct_size"], + "field_count": len(fields), + "passed": len(h_diffs) == 0, + "diffs": h_diffs, + } + ) + + const_results: list[dict] = [] + for const in DRM_CONSTANTS: + sv = stock_data["constants"][const] + rv = rs_data["constants"][const] + ok = sv == rv + if not ok: + diffs.append({"item": const, "stock": sv, "rs": rv}) + const_results.append({"name": const, "value": rv, "passed": ok}) + + return { + "passed": len(diffs) == 0, + "ioctl_count": len(ioctl_results), + "ioctls": ioctl_results, + "helper_structs": helper_results, + "constants": const_results, + "diffs": diffs, + } + + +def verify_nvkms_ioctl_abi() -> dict: + stock_fields = extract_c_struct_fields( + STOCK_NVKMS_IOCTL_H.read_text(encoding="utf-8"), "NvKmsIoctlParams" + ) + rs_fields = extract_c_struct_fields( + RS_KMS_ABI_H.read_text(encoding="utf-8"), "nv_rs_nvkms_ioctl_params" + ) + diffs: list[dict] = [] + if tuple(stock_fields) != NVKMS_IOCTL_FIELDS or tuple(rs_fields) != NVKMS_IOCTL_FIELDS: + diffs.append( + { + "item": "NvKmsIoctlParams.field_list", + "stock": stock_fields, + "rs": rs_fields, + "expected": list(NVKMS_IOCTL_FIELDS), + } + ) + + stock_probe_src = """ +#include +#include +#include +#include +#include "nvkms-ioctl.h" + +int main(void) { + printf("{\\n"); + printf(" \\"magic\\": %lu,\\n", (unsigned long)(NVKMS_IOCTL_MAGIC)); + printf(" \\"cmd\\": %lu,\\n", (unsigned long)(NVKMS_IOCTL_CMD)); + printf(" \\"ioctl_iowr\\": %lu,\\n", (unsigned long)(NVKMS_IOCTL_IOWR)); + printf(" \\"struct_size\\": %zu,\\n", sizeof(struct NvKmsIoctlParams)); + printf(" \\"struct_align\\": %zu,\\n", _Alignof(struct NvKmsIoctlParams)); + printf(" \\"fields\\": {\\n"); + printf(" \\"cmd\\": {\\"offset\\": %zu, \\"size\\": %zu},\\n", + offsetof(struct NvKmsIoctlParams, cmd), sizeof(((struct NvKmsIoctlParams *)0)->cmd)); + printf(" \\"size\\": {\\"offset\\": %zu, \\"size\\": %zu},\\n", + offsetof(struct NvKmsIoctlParams, size), sizeof(((struct NvKmsIoctlParams *)0)->size)); + printf(" \\"address\\": {\\"offset\\": %zu, \\"size\\": %zu}\\n", + offsetof(struct NvKmsIoctlParams, address), sizeof(((struct NvKmsIoctlParams *)0)->address)); + printf(" }\\n"); + printf("}\\n"); + return 0; +} +""" + rs_probe_src = """ +#include +#include +#include + +typedef uint8_t u8; +typedef uint16_t u16; +typedef uint32_t u32; +typedef uint64_t u64; +typedef int32_t s32; +#ifndef __aligned +#define __aligned(x) __attribute__((__aligned__(x))) +#endif +struct page; + +#include "nv_rs_kms_abi.h" + +int main(void) { + printf("{\\n"); + printf(" \\"magic\\": %lu,\\n", (unsigned long)(NV_RS_NVKMS_IOCTL_MAGIC)); + printf(" \\"cmd\\": %lu,\\n", (unsigned long)(NV_RS_NVKMS_IOCTL_CMD)); + printf(" \\"ioctl_iowr\\": %lu,\\n", (unsigned long)(NV_RS_NVKMS_IOCTL_IOWR)); + printf(" \\"struct_size\\": %zu,\\n", sizeof(struct nv_rs_nvkms_ioctl_params)); + printf(" \\"struct_align\\": %zu,\\n", _Alignof(struct nv_rs_nvkms_ioctl_params)); + printf(" \\"fields\\": {\\n"); + printf(" \\"cmd\\": {\\"offset\\": %zu, \\"size\\": %zu},\\n", + offsetof(struct nv_rs_nvkms_ioctl_params, cmd), sizeof(((struct nv_rs_nvkms_ioctl_params *)0)->cmd)); + printf(" \\"size\\": {\\"offset\\": %zu, \\"size\\": %zu},\\n", + offsetof(struct nv_rs_nvkms_ioctl_params, size), sizeof(((struct nv_rs_nvkms_ioctl_params *)0)->size)); + printf(" \\"address\\": {\\"offset\\": %zu, \\"size\\": %zu}\\n", + offsetof(struct nv_rs_nvkms_ioctl_params, address), sizeof(((struct nv_rs_nvkms_ioctl_params *)0)->address)); + printf(" }\\n"); + printf("}\\n"); + return 0; +} +""" + stock_data = compile_and_run_c( + stock_probe_src, + [f"-I{STOCK_NVKMS_IOCTL_H.parent}", f"-I{STOCK_COMMON_INC}"], + "stock_nvkms_ioctl", + ) + rs_data = compile_and_run_c( + rs_probe_src, + [f"-I{RS_KMS_ABI_H.parent}"], + "rs_nvkms_ioctl", + ) + + for key in ("magic", "cmd", "ioctl_iowr", "struct_size", "struct_align"): + if stock_data[key] != rs_data[key]: + diffs.append({"item": key, "stock": stock_data[key], "rs": rs_data[key]}) + for field in NVKMS_IOCTL_FIELDS: + if stock_data["fields"][field] != rs_data["fields"][field]: + diffs.append( + { + "item": f"NvKmsIoctlParams.{field}", + "stock": stock_data["fields"][field], + "rs": rs_data["fields"][field], + } + ) + + return { + "passed": len(diffs) == 0, + "ioctl_iowr": rs_data["ioctl_iowr"], + "struct_size": rs_data["struct_size"], + "struct_align": rs_data["struct_align"], + "fields": rs_data["fields"], + "diffs": diffs, + } + + +def verify_kms_gpu_caps_abi() -> dict: + c_header_text = RS_KMS_ABI_H.read_text(encoding="utf-8") + rust_src_text = RS_MODESET_FFI_RS.read_text(encoding="utf-8") + + c_fields = extract_c_struct_fields(c_header_text, "nv_rs_kms_gpu_caps") + rust_struct_def, rust_fields = extract_rust_struct_block(rust_src_text, "NvRsKmsGpuCaps") + + diffs: list[dict] = [] + if c_fields != rust_fields: + diffs.append( + { + "item": "field_list_and_order", + "c_fields": c_fields, + "rust_fields": rust_fields, + } + ) + + # Build C probe against kernel-open/nvidia-modeset/nv_rs_kms_abi.h + c_lines = [ + "#include ", + "#include ", + "#include ", + "typedef uint8_t u8;", + "typedef uint16_t u16;", + "typedef uint32_t u32;", + "typedef uint64_t u64;", + "typedef int32_t s32;", + "#ifndef __aligned", + "#define __aligned(x) __attribute__((__aligned__(x)))", + "#endif", + "struct page;", + '#include "nv_rs_kms_abi.h"', + "int main(void) {", + ' printf("{\\n");', + ' printf(" \\"struct_size\\": %zu,\\n", sizeof(struct nv_rs_kms_gpu_caps));', + ' printf(" \\"struct_align\\": %zu,\\n", _Alignof(struct nv_rs_kms_gpu_caps));', + ' printf(" \\"fields\\": {\\n");', + ] + for i, field in enumerate(c_fields): + comma = "," if i + 1 < len(c_fields) else "" + c_lines.append( + f' printf(" \\"{field}\\": {{\\"offset\\": %zu, \\"size\\": %zu}}{comma}\\n", ' + f"offsetof(struct nv_rs_kms_gpu_caps, {field}), " + f"sizeof(((struct nv_rs_kms_gpu_caps *)0)->{field}));" + ) + c_lines.extend([' printf(" }\\n");', ' printf("}\\n");', " return 0;", "}"]) + c_data = compile_and_run_c("\n".join(c_lines) + "\n", [f"-I{RS_KMS_ABI_H.parent}"], "c_gpu_caps") + + # Build Rust probe embedding the exact struct extracted from src/nvidia/kernel/modeset_ffi.rs + r_lines = [ + "#![allow(dead_code)]", + "use core::mem::{align_of, offset_of, size_of, size_of_val};", + rust_struct_def, + "fn main() {", + " let sample = NvRsKmsGpuCaps::default();", + ' println!("{{");', + ' println!(" \\"struct_size\\": {},", size_of::());', + ' println!(" \\"struct_align\\": {},", align_of::());', + ' println!(" \\"fields\\": {{");', + ] + for i, field in enumerate(rust_fields): + comma = "," if i + 1 < len(rust_fields) else "" + r_lines.append( + f' println!(" \\"{field}\\": {{{{\\"offset\\": {{}}, \\"size\\": {{}}}}}}{comma}", ' + f"offset_of!(NvRsKmsGpuCaps, {field}), size_of_val(&sample.{field}));" + ) + r_lines.extend([' println!(" }}");', ' println!("}}");', "}"]) + rust_data = compile_and_run_rust("\n".join(r_lines) + "\n", "rust_gpu_caps") + + for key in ("struct_size", "struct_align"): + if c_data[key] != rust_data[key]: + diffs.append({"item": key, "c": c_data[key], "rust": rust_data[key]}) + + common_fields = [f for f in c_fields if f in rust_data["fields"]] + for field in common_fields: + if c_data["fields"][field] != rust_data["fields"][field]: + diffs.append( + { + "item": f"NvRsKmsGpuCaps.{field}", + "c": c_data["fields"][field], + "rust": rust_data["fields"][field], + } + ) + + return { + "passed": len(diffs) == 0, + "struct_size": c_data["struct_size"], + "struct_align": c_data["struct_align"], + "field_count": len(c_fields), + "c_fields": c_data["fields"], + "rust_fields": rust_data["fields"], + "diffs": diffs, + } + + +def main() -> int: + parser = argparse.ArgumentParser(description="Verify DRM & NVKMS C/Rust ABI parity against 580.178.04.") + parser.add_argument("--json", action="store_true", help="Emit full machine-readable JSON report only") + args = parser.parse_args() + + required_files = ( + STOCK_DRM_IOCTL_H, + STOCK_NVKMS_IOCTL_H, + STOCK_COMMON_INC / "nvtypes.h", + RS_DRM_C, + RS_KMS_ABI_H, + RS_MODESET_FFI_RS, + ) + missing = [str(p) for p in required_files if not p.is_file()] + if missing: + err = {"status": "error", "passed": False, "missing_files": missing} + print(json.dumps(err, indent=2), file=sys.stderr) + return 2 + + drm_res = verify_drm_ioctl_abi() + nvkms_res = verify_nvkms_ioctl_abi() + caps_res = verify_kms_gpu_caps_abi() + + overall_passed = drm_res["passed"] and nvkms_res["passed"] and caps_res["passed"] + report = { + "name": "nvidia_580_178_04_drm_nvkms_abi_parity", + "status": "PASS" if overall_passed else "FAIL", + "passed": overall_passed, + "files_sha256": { + str(STOCK_DRM_IOCTL_H): sha256_file(STOCK_DRM_IOCTL_H), + str(STOCK_NVKMS_IOCTL_H): sha256_file(STOCK_NVKMS_IOCTL_H), + str(RS_DRM_C.relative_to(ROOT)): sha256_file(RS_DRM_C), + str(RS_KMS_ABI_H.relative_to(ROOT)): sha256_file(RS_KMS_ABI_H), + str(RS_MODESET_FFI_RS.relative_to(ROOT)): sha256_file(RS_MODESET_FFI_RS), + }, + "drm_ioctls": drm_res, + "nvkms_ioctl": nvkms_res, + "kms_gpu_caps": caps_res, + } + + if args.json: + print(json.dumps(report, indent=2)) + return 0 if overall_passed else 1 + + print("[1/3] DRM UAPI: kernel-open/nvidia-drm/nvidia_rs_drm.c vs stock nvidia-drm-ioctl.h") + for entry in drm_res["ioctls"]: + tag = "PASS" if entry["passed"] else "FAIL" + st_desc = ( + f"sizeof({entry['struct_name']})={entry['struct_size']} ({entry['field_count']} fields)" + if entry["struct_name"] + else "DRM_IO (no payload struct)" + ) + print( + f" [{tag}] {entry['name']:<44} cmd=0x{entry['cmd_index']:02x} " + f"ioctl=0x{entry['ioctl_nr']:08x} {st_desc}" + ) + for helper in drm_res["helper_structs"]: + tag = "PASS" if helper["passed"] else "FAIL" + print( + f" [{tag}] helper struct {helper['struct_name']:<30} " + f"sizeof={helper['struct_size']} ({helper['field_count']} fields)" + ) + for const in drm_res["constants"]: + tag = "PASS" if const["passed"] else "FAIL" + print(f" [{tag}] constant {const['name']:<35} value=0x{const['value']:x}") + if drm_res["diffs"]: + print(" DIFFS:", json.dumps(drm_res["diffs"], indent=2)) + + print("\n[2/3] NVKMS ioctl ABI: kernel-open/nvidia-modeset/nv_rs_kms_abi.h vs stock nvkms-ioctl.h") + tag = "PASS" if nvkms_res["passed"] else "FAIL" + field_summary = ", ".join( + f"{k}@{nvkms_res['fields'][k]['offset']}(sz={nvkms_res['fields'][k]['size']})" + for k in NVKMS_IOCTL_FIELDS + ) + print( + f" [{tag}] NV_RS_NVKMS_IOCTL_IOWR == NVKMS_IOCTL_IOWR " + f"(0x{nvkms_res['ioctl_iowr']:08x}) sizeof={nvkms_res['struct_size']} " + f"align={nvkms_res['struct_align']} [{field_summary}]" + ) + if nvkms_res["diffs"]: + print(" DIFFS:", json.dumps(nvkms_res["diffs"], indent=2)) + + print("\n[3/3] KAPI C/Rust ABI: nv_rs_kms_abi.h struct nv_rs_kms_gpu_caps vs modeset_ffi.rs NvRsKmsGpuCaps") + tag = "PASS" if caps_res["passed"] else "FAIL" + print( + f" [{tag}] struct nv_rs_kms_gpu_caps == #[repr(C)] NvRsKmsGpuCaps " + f"sizeof={caps_res['struct_size']} align={caps_res['struct_align']} " + f"({caps_res['field_count']} fields exact offset & size parity)" + ) + if caps_res["diffs"]: + print(" DIFFS:", json.dumps(caps_res["diffs"], indent=2)) + + total_drm_fields = sum(e["field_count"] for e in drm_res["ioctls"]) + sum( + h["field_count"] for h in drm_res["helper_structs"] + ) + print( + f"\nSUMMARY: {'PASS' if overall_passed else 'FAIL'} " + f"(24/24 DRM ioctls, {total_drm_fields} DRM fields, " + f"NVKMS ioctl + 3 fields, NvRsKmsGpuCaps + {caps_res['field_count']} C/Rust fields)" + ) + return 0 if overall_passed else 1 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/desktop_drm_smoke.c b/tools/desktop_drm_smoke.c new file mode 100644 index 00000000..ce717001 --- /dev/null +++ b/tools/desktop_drm_smoke.c @@ -0,0 +1,992 @@ +/* SPDX-License-Identifier: MIT */ +/* + * Self-contained zero-external-dependency userspace desktop DRM/KMS/NVKMS smoke test + * for QuixiAI/nvdriver (nvidia_rs_drm.ko + nvidia_rs_modeset.ko). + * + * Build (dynamic): + * gcc -O2 -Wall -Wextra -o target/desktop-drm-smoke tools/desktop_drm_smoke.c + * Build (static, for initramfs / QEMU guest): + * gcc -static -O2 -Wall -Wextra -o target/desktop-drm-smoke tools/desktop_drm_smoke.c + * + * Usage: + * desktop-drm-smoke [drm_card_path] [modeset_dev_path] + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +/* ========================================================================= + * Exact 580.178.04 nvidia-drm-ioctl.h UAPI definitions + * ========================================================================= */ + +#define DRM_NVIDIA_GET_CRTC_CRC32 0x00 +#define DRM_NVIDIA_GEM_IMPORT_NVKMS_MEMORY 0x01 +#define DRM_NVIDIA_GEM_IMPORT_USERSPACE_MEMORY 0x02 +#define DRM_NVIDIA_GET_DEV_INFO 0x03 +#define DRM_NVIDIA_FENCE_SUPPORTED 0x04 +#define DRM_NVIDIA_GET_CLIENT_CAPABILITY 0x08 +#define DRM_NVIDIA_GEM_EXPORT_NVKMS_MEMORY 0x09 +#define DRM_NVIDIA_GEM_MAP_OFFSET 0x0a +#define DRM_NVIDIA_GEM_ALLOC_NVKMS_MEMORY 0x0b +#define DRM_NVIDIA_GET_CRTC_CRC32_V2 0x0c +#define DRM_NVIDIA_GEM_IDENTIFY_OBJECT 0x0e +#define DRM_NVIDIA_DMABUF_SUPPORTED 0x0f +#define DRM_NVIDIA_GET_DPY_ID_FOR_CONNECTOR_ID 0x10 +#define DRM_NVIDIA_GET_CONNECTOR_ID_FOR_DPY_ID 0x11 +#define DRM_NVIDIA_SEMSURF_FENCE_CTX_CREATE 0x14 +#define DRM_NVIDIA_SEMSURF_FENCE_CREATE 0x15 +#define DRM_NVIDIA_SEMSURF_FENCE_WAIT 0x16 +#define DRM_NVIDIA_SEMSURF_FENCE_ATTACH 0x17 +#define DRM_NVIDIA_GET_DRM_FILE_UNIQUE_ID 0x18 + +#define NV_DRM_FORMAT_XRGB8888 0x34325258U /* 'XR24' */ + +enum drm_nvidia_gem_object_type { + NV_GEM_OBJECT_NVKMS = 0, + NV_GEM_OBJECT_DMABUF = 1, + NV_GEM_OBJECT_USERMEMORY = 2, + NV_GEM_OBJECT_UNKNOWN = 0x7fffffff, +}; + +struct drm_nvidia_gem_import_nvkms_memory_params { + uint64_t mem_size; + uint64_t nvkms_params_ptr; + uint64_t nvkms_params_size; + uint32_t handle; + uint32_t __pad; +}; + +struct drm_nvidia_gem_import_userspace_memory_params { + uint64_t size; + uint64_t address; + uint32_t handle; +}; + +struct drm_nvidia_get_dev_info_params { + uint32_t gpu_id; + uint32_t mig_device; + uint32_t primary_index; + uint32_t supports_alloc; + uint32_t generic_page_kind; + uint32_t page_kind_generation; + uint32_t sector_layout; + uint32_t supports_sync_fd; + uint32_t supports_semsurf; +}; + +struct drm_nvidia_get_client_capability_params { + uint64_t capability; + uint64_t value; +}; + +struct drm_nvidia_crtc_crc32 { + uint32_t value; + uint8_t supported; + uint8_t __pad0; + uint16_t __pad1; +}; + +struct drm_nvidia_crtc_crc32_v2_out { + struct drm_nvidia_crtc_crc32 compositorCrc32; + struct drm_nvidia_crtc_crc32 rasterGeneratorCrc32; + struct drm_nvidia_crtc_crc32 outputCrc32; +}; + +struct drm_nvidia_get_crtc_crc32_v2_params { + uint32_t crtc_id; + struct drm_nvidia_crtc_crc32_v2_out crc32; +}; + +struct drm_nvidia_get_crtc_crc32_params { + uint32_t crtc_id; + uint32_t crc32; +}; + +struct drm_nvidia_gem_export_nvkms_memory_params { + uint32_t handle; + uint32_t __pad; + uint64_t nvkms_params_ptr; + uint64_t nvkms_params_size; +}; + +struct drm_nvidia_gem_map_offset_params { + uint32_t handle; + uint32_t __pad; + uint64_t offset; +}; + +struct drm_nvidia_gem_alloc_nvkms_memory_params { + uint32_t handle; + uint8_t block_linear; + uint8_t compressible; + uint16_t __pad0; + uint64_t memory_size; + uint32_t flags; + uint32_t __pad1; +}; + +struct drm_nvidia_gem_identify_object_params { + uint32_t handle; + uint32_t object_type; +}; + +struct drm_nvidia_get_dpy_id_for_connector_id_params { + uint32_t connectorId; + uint32_t dpyId; +}; + +struct drm_nvidia_get_connector_id_for_dpy_id_params { + uint32_t dpyId; + uint32_t connectorId; +}; + +struct drm_nvidia_semsurf_fence_ctx_create_params { + uint64_t index; + uint64_t nvkms_params_ptr; + uint64_t nvkms_params_size; + uint32_t handle; + uint32_t __pad; +}; + +struct drm_nvidia_semsurf_fence_create_params { + uint32_t fence_context_handle; + uint32_t timeout_value_ms; + uint64_t wait_value; + int32_t fd; + uint32_t __pad; +}; + +struct drm_nvidia_semsurf_fence_wait_params { + uint32_t fence_context_handle; + int32_t fd; + uint64_t pre_wait_value; + uint64_t post_wait_value; +}; + +struct drm_nvidia_semsurf_fence_attach_params { + uint32_t handle; + uint32_t fence_context_handle; + uint32_t timeout_value_ms; + uint32_t shared; + uint64_t wait_value; +}; + +struct drm_nvidia_get_drm_file_unique_id_params { + uint64_t id; +}; + +#define DRM_IOCTL_NVIDIA_GET_CRTC_CRC32 \ + DRM_IOWR(DRM_COMMAND_BASE + DRM_NVIDIA_GET_CRTC_CRC32, \ + struct drm_nvidia_get_crtc_crc32_params) +#define DRM_IOCTL_NVIDIA_GEM_IMPORT_NVKMS_MEMORY \ + DRM_IOWR(DRM_COMMAND_BASE + DRM_NVIDIA_GEM_IMPORT_NVKMS_MEMORY, \ + struct drm_nvidia_gem_import_nvkms_memory_params) +#define DRM_IOCTL_NVIDIA_GEM_IMPORT_USERSPACE_MEMORY \ + DRM_IOWR(DRM_COMMAND_BASE + DRM_NVIDIA_GEM_IMPORT_USERSPACE_MEMORY, \ + struct drm_nvidia_gem_import_userspace_memory_params) +#define DRM_IOCTL_NVIDIA_GET_DEV_INFO \ + DRM_IOWR(DRM_COMMAND_BASE + DRM_NVIDIA_GET_DEV_INFO, \ + struct drm_nvidia_get_dev_info_params) +#define DRM_IOCTL_NVIDIA_FENCE_SUPPORTED \ + DRM_IO(DRM_COMMAND_BASE + DRM_NVIDIA_FENCE_SUPPORTED) +#define DRM_IOCTL_NVIDIA_GET_CLIENT_CAPABILITY \ + DRM_IOWR(DRM_COMMAND_BASE + DRM_NVIDIA_GET_CLIENT_CAPABILITY, \ + struct drm_nvidia_get_client_capability_params) +#define DRM_IOCTL_NVIDIA_GEM_EXPORT_NVKMS_MEMORY \ + DRM_IOWR(DRM_COMMAND_BASE + DRM_NVIDIA_GEM_EXPORT_NVKMS_MEMORY, \ + struct drm_nvidia_gem_export_nvkms_memory_params) +#define DRM_IOCTL_NVIDIA_GEM_MAP_OFFSET \ + DRM_IOWR(DRM_COMMAND_BASE + DRM_NVIDIA_GEM_MAP_OFFSET, \ + struct drm_nvidia_gem_map_offset_params) +#define DRM_IOCTL_NVIDIA_GEM_ALLOC_NVKMS_MEMORY \ + DRM_IOWR(DRM_COMMAND_BASE + DRM_NVIDIA_GEM_ALLOC_NVKMS_MEMORY, \ + struct drm_nvidia_gem_alloc_nvkms_memory_params) +#define DRM_IOCTL_NVIDIA_GET_CRTC_CRC32_V2 \ + DRM_IOWR(DRM_COMMAND_BASE + DRM_NVIDIA_GET_CRTC_CRC32_V2, \ + struct drm_nvidia_get_crtc_crc32_v2_params) +#define DRM_IOCTL_NVIDIA_GEM_IDENTIFY_OBJECT \ + DRM_IOWR(DRM_COMMAND_BASE + DRM_NVIDIA_GEM_IDENTIFY_OBJECT, \ + struct drm_nvidia_gem_identify_object_params) +#define DRM_IOCTL_NVIDIA_DMABUF_SUPPORTED \ + DRM_IO(DRM_COMMAND_BASE + DRM_NVIDIA_DMABUF_SUPPORTED) +#define DRM_IOCTL_NVIDIA_GET_DPY_ID_FOR_CONNECTOR_ID \ + DRM_IOWR(DRM_COMMAND_BASE + DRM_NVIDIA_GET_DPY_ID_FOR_CONNECTOR_ID, \ + struct drm_nvidia_get_dpy_id_for_connector_id_params) +#define DRM_IOCTL_NVIDIA_GET_CONNECTOR_ID_FOR_DPY_ID \ + DRM_IOWR(DRM_COMMAND_BASE + DRM_NVIDIA_GET_CONNECTOR_ID_FOR_DPY_ID, \ + struct drm_nvidia_get_connector_id_for_dpy_id_params) +#define DRM_IOCTL_NVIDIA_SEMSURF_FENCE_CTX_CREATE \ + DRM_IOWR(DRM_COMMAND_BASE + DRM_NVIDIA_SEMSURF_FENCE_CTX_CREATE, \ + struct drm_nvidia_semsurf_fence_ctx_create_params) +#define DRM_IOCTL_NVIDIA_SEMSURF_FENCE_CREATE \ + DRM_IOWR(DRM_COMMAND_BASE + DRM_NVIDIA_SEMSURF_FENCE_CREATE, \ + struct drm_nvidia_semsurf_fence_create_params) +#define DRM_IOCTL_NVIDIA_SEMSURF_FENCE_WAIT \ + DRM_IOW(DRM_COMMAND_BASE + DRM_NVIDIA_SEMSURF_FENCE_WAIT, \ + struct drm_nvidia_semsurf_fence_wait_params) +#define DRM_IOCTL_NVIDIA_SEMSURF_FENCE_ATTACH \ + DRM_IOW(DRM_COMMAND_BASE + DRM_NVIDIA_SEMSURF_FENCE_ATTACH, \ + struct drm_nvidia_semsurf_fence_attach_params) +#define DRM_IOCTL_NVIDIA_GET_DRM_FILE_UNIQUE_ID \ + DRM_IOWR(DRM_COMMAND_BASE + DRM_NVIDIA_GET_DRM_FILE_UNIQUE_ID, \ + struct drm_nvidia_get_drm_file_unique_id_params) + +/* Exact 580.178.04 /dev/nvidia-modeset ioctl wrapper (nvkms-ioctl.h). */ +struct nv_rs_nvkms_ioctl_params { + uint32_t cmd; + uint32_t size; + uint64_t address; +}; + +#define NVKMS_IOCTL_MAGIC 'm' +#define NVKMS_IOCTL_CMD 0 +#define NVKMS_IOCTL_IOWR \ + _IOWR(NVKMS_IOCTL_MAGIC, NVKMS_IOCTL_CMD, struct nv_rs_nvkms_ioctl_params) + +_Static_assert(sizeof(struct drm_nvidia_get_dev_info_params) == 36, + "drm_nvidia_get_dev_info_params must be 36 bytes"); +_Static_assert(sizeof(struct nv_rs_nvkms_ioctl_params) == 16, + "nv_rs_nvkms_ioctl_params must be 16 bytes"); + +/* ========================================================================= + * Smoke Test State & Helpers + * ========================================================================= */ + +struct smoke_result { + int open_drm; + int version; + int client_caps; + int resources; + int connector; + int dumb_fb; + int dev_info; + int dmabuf_fence_supported; + int gem_nvkms; + int prime_dmabuf; + int gem_usermem; + int semsurf_sync; + int dpy_conn_roundtrip; + int crtc_crc32; + int unique_id; + int modeset_ioctl; + + char driver_name[64]; + char modeset_path[64]; + uint32_t gpu_id; + uint32_t count_crtcs; + uint32_t count_connectors; + uint32_t count_encoders; + uint32_t count_modes; + uint32_t first_crtc_id; + uint32_t first_connector_id; + uint32_t dpy_id; + uint64_t unique_id_1; + uint64_t unique_id_2; +}; + +static void gem_close(int fd, uint32_t handle) +{ + struct drm_gem_close req; + + if (handle == 0) + return; + memset(&req, 0, sizeof(req)); + req.handle = handle; + (void)ioctl(fd, DRM_IOCTL_GEM_CLOSE, &req); +} + +static void print_json_escaped(const char *s) +{ + const unsigned char *p = (const unsigned char *)s; + + putchar('"'); + while (*p) { + if (*p == '"' || *p == '\\') { + putchar('\\'); + putchar((int)*p); + } else if (*p >= 0x20 && *p < 0x7f) { + putchar((int)*p); + } else { + printf("\\u%04x", (unsigned int)*p); + } + p++; + } + putchar('"'); +} + +static int check_version(int fd, struct smoke_result *r) +{ + struct drm_version ver; + char name[64]; + char date[64]; + char desc[128]; + + memset(&ver, 0, sizeof(ver)); + memset(name, 0, sizeof(name)); + memset(date, 0, sizeof(date)); + memset(desc, 0, sizeof(desc)); + + ver.name = name; + ver.name_len = sizeof(name) - 1; + ver.date = date; + ver.date_len = sizeof(date) - 1; + ver.desc = desc; + ver.desc_len = sizeof(desc) - 1; + + if (ioctl(fd, DRM_IOCTL_VERSION, &ver) != 0) + return 0; + + if (ver.name_len >= sizeof(name)) + name[sizeof(name) - 1] = '\0'; + else + name[ver.name_len] = '\0'; + + strncpy(r->driver_name, name, sizeof(r->driver_name) - 1); + r->driver_name[sizeof(r->driver_name) - 1] = '\0'; + + return (strcmp(name, "nvidia-drm") == 0 || + strcmp(name, "nvidia-rs-drm") == 0); +} + +static int check_client_caps(int fd) +{ + static const uint64_t caps[2] = { + DRM_CLIENT_CAP_UNIVERSAL_PLANES, + DRM_CLIENT_CAP_ATOMIC, + }; + size_t i; + + for (i = 0; i < 2; i++) { + struct drm_set_client_cap set_p; + struct drm_nvidia_get_client_capability_params get_p; + + memset(&set_p, 0, sizeof(set_p)); + set_p.capability = caps[i]; + set_p.value = 1; + if (ioctl(fd, DRM_IOCTL_SET_CLIENT_CAP, &set_p) != 0) + return 0; + + memset(&get_p, 0, sizeof(get_p)); + get_p.capability = caps[i]; + if (ioctl(fd, DRM_IOCTL_NVIDIA_GET_CLIENT_CAPABILITY, &get_p) != 0) + return 0; + if (get_p.value != 1) + return 0; + } + return 1; +} + +static int check_resources_and_connector(int fd, struct smoke_result *r) +{ + struct drm_mode_card_res res; + uint32_t fb_ids[32]; + uint32_t crtc_ids[32]; + uint32_t conn_ids[32]; + uint32_t enc_ids[32]; + struct drm_mode_get_connector conn; + struct drm_mode_modeinfo modes[64]; + uint32_t conn_props[32]; + uint64_t conn_prop_vals[32]; + uint32_t conn_encs[16]; + + memset(&res, 0, sizeof(res)); + if (ioctl(fd, DRM_IOCTL_MODE_GETRESOURCES, &res) != 0) + return 0; + + r->count_crtcs = res.count_crtcs; + r->count_connectors = res.count_connectors; + r->count_encoders = res.count_encoders; + + if (res.count_crtcs < 1 || res.count_connectors < 1 || res.count_encoders < 1) + return 0; + + memset(fb_ids, 0, sizeof(fb_ids)); + memset(crtc_ids, 0, sizeof(crtc_ids)); + memset(conn_ids, 0, sizeof(conn_ids)); + memset(enc_ids, 0, sizeof(enc_ids)); + + res.fb_id_ptr = (uint64_t)(uintptr_t)fb_ids; + res.crtc_id_ptr = (uint64_t)(uintptr_t)crtc_ids; + res.connector_id_ptr = (uint64_t)(uintptr_t)conn_ids; + res.encoder_id_ptr = (uint64_t)(uintptr_t)enc_ids; + if (res.count_fbs > 32) + res.count_fbs = 32; + if (res.count_crtcs > 32) + res.count_crtcs = 32; + if (res.count_connectors > 32) + res.count_connectors = 32; + if (res.count_encoders > 32) + res.count_encoders = 32; + + if (ioctl(fd, DRM_IOCTL_MODE_GETRESOURCES, &res) != 0) + return 0; + if (crtc_ids[0] == 0 || conn_ids[0] == 0) + return 0; + + r->first_crtc_id = crtc_ids[0]; + r->first_connector_id = conn_ids[0]; + r->resources = 1; + + /* Probe connector modes. */ + memset(&conn, 0, sizeof(conn)); + conn.connector_id = r->first_connector_id; + if (ioctl(fd, DRM_IOCTL_MODE_GETCONNECTOR, &conn) != 0) + return 0; + + r->count_modes = conn.count_modes; + if (conn.count_modes < 1) + return 0; + + memset(modes, 0, sizeof(modes)); + memset(conn_props, 0, sizeof(conn_props)); + memset(conn_prop_vals, 0, sizeof(conn_prop_vals)); + memset(conn_encs, 0, sizeof(conn_encs)); + + conn.modes_ptr = (uint64_t)(uintptr_t)modes; + conn.props_ptr = (uint64_t)(uintptr_t)conn_props; + conn.prop_values_ptr = (uint64_t)(uintptr_t)conn_prop_vals; + conn.encoders_ptr = (uint64_t)(uintptr_t)conn_encs; + if (conn.count_modes > 64) + conn.count_modes = 64; + if (conn.count_props > 32) + conn.count_props = 32; + if (conn.count_encoders > 16) + conn.count_encoders = 16; + + if (ioctl(fd, DRM_IOCTL_MODE_GETCONNECTOR, &conn) != 0) + return 0; + if (conn.count_modes < 1 || modes[0].hdisplay == 0 || modes[0].vdisplay == 0) + return 0; + + r->connector = 1; + return 1; +} + +static int check_dumb_fb(int fd) +{ + struct drm_mode_create_dumb create; + struct drm_mode_map_dumb map_req; + struct drm_mode_fb_cmd2 fb; + struct drm_mode_destroy_dumb destroy; + void *mapped = MAP_FAILED; + uint32_t *words; + uint32_t fb_id = 0; + int ok = 0; + + memset(&create, 0, sizeof(create)); + create.width = 256; + create.height = 256; + create.bpp = 32; + if (ioctl(fd, DRM_IOCTL_MODE_CREATE_DUMB, &create) != 0) + return 0; + if (create.handle == 0 || create.pitch < 256U * 4U || create.size == 0) + goto out_destroy; + + memset(&map_req, 0, sizeof(map_req)); + map_req.handle = create.handle; + if (ioctl(fd, DRM_IOCTL_MODE_MAP_DUMB, &map_req) != 0) + goto out_destroy; + + mapped = mmap(NULL, (size_t)create.size, PROT_READ | PROT_WRITE, + MAP_SHARED, fd, (off_t)map_req.offset); + if (mapped == MAP_FAILED) + goto out_destroy; + + words = (uint32_t *)mapped; + words[0] = 0xdeadbeefU; + words[1] = 0x12345678U; + if (words[0] != 0xdeadbeefU || words[1] != 0x12345678U) + goto out_unmap; + + munmap(mapped, (size_t)create.size); + mapped = MAP_FAILED; + + memset(&fb, 0, sizeof(fb)); + fb.width = create.width; + fb.height = create.height; + fb.pixel_format = NV_DRM_FORMAT_XRGB8888; + fb.handles[0] = create.handle; + fb.pitches[0] = create.pitch; + fb.offsets[0] = 0; + if (ioctl(fd, DRM_IOCTL_MODE_ADDFB2, &fb) != 0 || fb.fb_id == 0) + goto out_destroy; + fb_id = fb.fb_id; + + if (ioctl(fd, DRM_IOCTL_MODE_RMFB, &fb_id) != 0) + goto out_destroy; + fb_id = 0; + + ok = 1; + +out_unmap: + if (mapped != MAP_FAILED) + munmap(mapped, (size_t)create.size); + if (fb_id != 0) + (void)ioctl(fd, DRM_IOCTL_MODE_RMFB, &fb_id); +out_destroy: + memset(&destroy, 0, sizeof(destroy)); + destroy.handle = create.handle; + if (ioctl(fd, DRM_IOCTL_MODE_DESTROY_DUMB, &destroy) != 0) + ok = 0; + return ok; +} + +static int check_dev_info(int fd, struct smoke_result *r) +{ + struct drm_nvidia_get_dev_info_params info; + + memset(&info, 0, sizeof(info)); + if (ioctl(fd, DRM_IOCTL_NVIDIA_GET_DEV_INFO, &info) != 0) + return 0; + + r->gpu_id = info.gpu_id; + return (info.supports_alloc == 1 && + info.supports_sync_fd == 1 && + info.supports_semsurf == 1); +} + +static int check_dmabuf_and_fence_supported(int fd) +{ + if (ioctl(fd, DRM_IOCTL_NVIDIA_DMABUF_SUPPORTED, 0) != 0) + return 0; + if (ioctl(fd, DRM_IOCTL_NVIDIA_FENCE_SUPPORTED, 0) != 0) + return 0; + return 1; +} + +static int check_gem_nvkms_prime_and_semsurf(int fd, struct smoke_result *r) +{ + const uint64_t mem_size = 65536ULL; + struct drm_nvidia_gem_alloc_nvkms_memory_params alloc_p; + struct drm_nvidia_gem_map_offset_params map_p; + struct drm_nvidia_gem_identify_object_params id_p; + struct drm_nvidia_gem_export_nvkms_memory_params exp_p; + struct drm_nvidia_gem_import_nvkms_memory_params imp_p; + struct drm_prime_handle prime_exp; + struct drm_prime_handle prime_imp; + struct drm_nvidia_semsurf_fence_ctx_create_params ctx_p; + struct drm_nvidia_semsurf_fence_create_params fc_p; + struct drm_nvidia_semsurf_fence_attach_params fa_p; + struct drm_nvidia_semsurf_fence_wait_params fw_p; + uint64_t export_id = 0; + uint32_t nvkms_handle = 0; + uint32_t imp_handle = 0; + uint32_t prime_imp_handle = 0; + uint32_t fence_ctx_handle = 0; + int dmabuf_fd = -1; + int sync_fd = -1; + void *mapped = MAP_FAILED; + uint32_t *words; + + /* 1. GEM_ALLOC_NVKMS_MEMORY + GEM_MAP_OFFSET + mmap write/readback. */ + memset(&alloc_p, 0, sizeof(alloc_p)); + alloc_p.memory_size = mem_size; + if (ioctl(fd, DRM_IOCTL_NVIDIA_GEM_ALLOC_NVKMS_MEMORY, &alloc_p) != 0 || + alloc_p.handle == 0) + goto cleanup; + nvkms_handle = alloc_p.handle; + + memset(&map_p, 0, sizeof(map_p)); + map_p.handle = nvkms_handle; + if (ioctl(fd, DRM_IOCTL_NVIDIA_GEM_MAP_OFFSET, &map_p) != 0) + goto cleanup; + + mapped = mmap(NULL, (size_t)mem_size, PROT_READ | PROT_WRITE, + MAP_SHARED, fd, (off_t)map_p.offset); + if (mapped == MAP_FAILED) + goto cleanup; + + words = (uint32_t *)mapped; + words[0] = 0xcafebabeU; + words[1] = 0xdeadbeefU; + if (words[0] != 0xcafebabeU || words[1] != 0xdeadbeefU) + goto cleanup; + munmap(mapped, (size_t)mem_size); + mapped = MAP_FAILED; + + /* 2. GEM_IDENTIFY_OBJECT == NV_GEM_OBJECT_NVKMS (0). */ + memset(&id_p, 0, sizeof(id_p)); + id_p.handle = nvkms_handle; + if (ioctl(fd, DRM_IOCTL_NVIDIA_GEM_IDENTIFY_OBJECT, &id_p) != 0 || + id_p.object_type != NV_GEM_OBJECT_NVKMS) + goto cleanup; + + /* 3. GEM_EXPORT_NVKMS_MEMORY + GEM_IMPORT_NVKMS_MEMORY round-trip. */ + memset(&exp_p, 0, sizeof(exp_p)); + exp_p.handle = nvkms_handle; + exp_p.nvkms_params_ptr = (uint64_t)(uintptr_t)&export_id; + exp_p.nvkms_params_size = sizeof(export_id); + if (ioctl(fd, DRM_IOCTL_NVIDIA_GEM_EXPORT_NVKMS_MEMORY, &exp_p) != 0 || + export_id == 0) + goto cleanup; + + memset(&imp_p, 0, sizeof(imp_p)); + imp_p.mem_size = mem_size; + imp_p.nvkms_params_ptr = (uint64_t)(uintptr_t)&export_id; + imp_p.nvkms_params_size = sizeof(export_id); + if (ioctl(fd, DRM_IOCTL_NVIDIA_GEM_IMPORT_NVKMS_MEMORY, &imp_p) != 0 || + imp_p.handle == 0) + goto cleanup; + imp_handle = imp_p.handle; + + r->gem_nvkms = 1; + + /* 4. PRIME_HANDLE_TO_FD + PRIME_FD_TO_HANDLE DMA-BUF round-trip. */ + memset(&prime_exp, 0, sizeof(prime_exp)); + prime_exp.handle = nvkms_handle; + prime_exp.flags = DRM_CLOEXEC | DRM_RDWR; + prime_exp.fd = -1; + if (ioctl(fd, DRM_IOCTL_PRIME_HANDLE_TO_FD, &prime_exp) != 0 || + prime_exp.fd < 0) + goto cleanup; + dmabuf_fd = prime_exp.fd; + + memset(&prime_imp, 0, sizeof(prime_imp)); + prime_imp.fd = dmabuf_fd; + if (ioctl(fd, DRM_IOCTL_PRIME_FD_TO_HANDLE, &prime_imp) != 0 || + prime_imp.handle == 0) + goto cleanup; + if (prime_imp.handle != nvkms_handle) + prime_imp_handle = prime_imp.handle; + + close(dmabuf_fd); + dmabuf_fd = -1; + r->prime_dmabuf = 1; + + /* 5. SEMSURF_FENCE_CTX_CREATE + FENCE_CREATE + FENCE_ATTACH + FENCE_WAIT. */ + memset(&ctx_p, 0, sizeof(ctx_p)); + ctx_p.index = 0; + if (ioctl(fd, DRM_IOCTL_NVIDIA_SEMSURF_FENCE_CTX_CREATE, &ctx_p) != 0 || + ctx_p.handle == 0) + goto cleanup; + fence_ctx_handle = ctx_p.handle; + + memset(&fc_p, 0, sizeof(fc_p)); + fc_p.fence_context_handle = fence_ctx_handle; + fc_p.timeout_value_ms = 100; + fc_p.wait_value = 0; + fc_p.fd = -1; + if (ioctl(fd, DRM_IOCTL_NVIDIA_SEMSURF_FENCE_CREATE, &fc_p) != 0 || + fc_p.fd < 0) + goto cleanup; + sync_fd = fc_p.fd; + + memset(&fa_p, 0, sizeof(fa_p)); + fa_p.handle = nvkms_handle; + fa_p.fence_context_handle = fence_ctx_handle; + fa_p.timeout_value_ms = 100; + fa_p.shared = 0; + fa_p.wait_value = 0; + if (ioctl(fd, DRM_IOCTL_NVIDIA_SEMSURF_FENCE_ATTACH, &fa_p) != 0) + goto cleanup; + + memset(&fw_p, 0, sizeof(fw_p)); + fw_p.fence_context_handle = fence_ctx_handle; + fw_p.fd = sync_fd; + fw_p.pre_wait_value = 0; + fw_p.post_wait_value = 1; + if (ioctl(fd, DRM_IOCTL_NVIDIA_SEMSURF_FENCE_WAIT, &fw_p) != 0) + goto cleanup; + + close(sync_fd); + sync_fd = -1; + r->semsurf_sync = 1; + +cleanup: + if (mapped != MAP_FAILED) + munmap(mapped, (size_t)mem_size); + if (sync_fd >= 0) + close(sync_fd); + if (dmabuf_fd >= 0) + close(dmabuf_fd); + gem_close(fd, fence_ctx_handle); + gem_close(fd, prime_imp_handle); + gem_close(fd, imp_handle); + gem_close(fd, nvkms_handle); + return (r->gem_nvkms && r->prime_dmabuf && r->semsurf_sync); +} + +static int check_gem_usermem(int fd) +{ + long page_sz = sysconf(_SC_PAGESIZE); + size_t buf_sz = (page_sz > 0) ? (size_t)page_sz * 4U : 16384U; + void *ubuf; + struct drm_nvidia_gem_import_userspace_memory_params imp; + struct drm_nvidia_gem_identify_object_params id_p; + int ok = 0; + + ubuf = mmap(NULL, buf_sz, PROT_READ | PROT_WRITE, + MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); + if (ubuf == MAP_FAILED) + return 0; + + /* Fault in pages before pin_user_pages_fast. */ + memset(ubuf, 0x5a, buf_sz); + + memset(&imp, 0, sizeof(imp)); + imp.size = (uint64_t)buf_sz; + imp.address = (uint64_t)(uintptr_t)ubuf; + if (ioctl(fd, DRM_IOCTL_NVIDIA_GEM_IMPORT_USERSPACE_MEMORY, &imp) != 0 || + imp.handle == 0) + goto out_unmap; + + memset(&id_p, 0, sizeof(id_p)); + id_p.handle = imp.handle; + if (ioctl(fd, DRM_IOCTL_NVIDIA_GEM_IDENTIFY_OBJECT, &id_p) == 0 && + id_p.object_type == NV_GEM_OBJECT_USERMEMORY) + ok = 1; + + gem_close(fd, imp.handle); +out_unmap: + munmap(ubuf, buf_sz); + return ok; +} + +static int check_dpy_conn_roundtrip(int fd, struct smoke_result *r) +{ + struct drm_nvidia_get_dpy_id_for_connector_id_params to_dpy; + struct drm_nvidia_get_connector_id_for_dpy_id_params to_conn; + + if (r->first_connector_id == 0) + return 0; + + memset(&to_dpy, 0, sizeof(to_dpy)); + to_dpy.connectorId = r->first_connector_id; + if (ioctl(fd, DRM_IOCTL_NVIDIA_GET_DPY_ID_FOR_CONNECTOR_ID, &to_dpy) != 0 || + to_dpy.dpyId == 0) + return 0; + + r->dpy_id = to_dpy.dpyId; + + memset(&to_conn, 0, sizeof(to_conn)); + to_conn.dpyId = to_dpy.dpyId; + if (ioctl(fd, DRM_IOCTL_NVIDIA_GET_CONNECTOR_ID_FOR_DPY_ID, &to_conn) != 0) + return 0; + + return (to_conn.connectorId == r->first_connector_id); +} + +static int check_crtc_crc32(int fd, struct smoke_result *r) +{ + struct drm_nvidia_get_crtc_crc32_params v1; + struct drm_nvidia_get_crtc_crc32_v2_params v2; + + if (r->first_crtc_id == 0) + return 0; + + memset(&v1, 0, sizeof(v1)); + v1.crtc_id = r->first_crtc_id; + if (ioctl(fd, DRM_IOCTL_NVIDIA_GET_CRTC_CRC32, &v1) != 0) + return 0; + + memset(&v2, 0, sizeof(v2)); + v2.crtc_id = r->first_crtc_id; + if (ioctl(fd, DRM_IOCTL_NVIDIA_GET_CRTC_CRC32_V2, &v2) != 0) + return 0; + + return (v2.crc32.compositorCrc32.supported == 1 && + v2.crc32.rasterGeneratorCrc32.supported == 1 && + v2.crc32.outputCrc32.supported == 1 && + v2.crc32.compositorCrc32.value == v1.crc32); +} + +static int check_unique_id(int fd, const char *drm_path, struct smoke_result *r) +{ + struct drm_nvidia_get_drm_file_unique_id_params p1a; + struct drm_nvidia_get_drm_file_unique_id_params p1b; + struct drm_nvidia_get_drm_file_unique_id_params p2; + int fd2; + + memset(&p1a, 0, sizeof(p1a)); + memset(&p1b, 0, sizeof(p1b)); + if (ioctl(fd, DRM_IOCTL_NVIDIA_GET_DRM_FILE_UNIQUE_ID, &p1a) != 0) + return 0; + if (ioctl(fd, DRM_IOCTL_NVIDIA_GET_DRM_FILE_UNIQUE_ID, &p1b) != 0) + return 0; + if (p1a.id == 0 || p1a.id != p1b.id) + return 0; + + fd2 = open(drm_path, O_RDWR | O_CLOEXEC); + if (fd2 < 0) + return 0; + + memset(&p2, 0, sizeof(p2)); + if (ioctl(fd2, DRM_IOCTL_NVIDIA_GET_DRM_FILE_UNIQUE_ID, &p2) != 0) { + close(fd2); + return 0; + } + close(fd2); + + r->unique_id_1 = p1a.id; + r->unique_id_2 = p2.id; + return (p2.id != 0 && p2.id != p1a.id); +} + +static int check_modeset_ioctl(const char *override_path, uint32_t gpu_id, + struct smoke_result *r) +{ + const char *candidates[3]; + size_t n = 0; + size_t i; + int ms_fd = -1; + uint8_t payload[64]; + struct nv_rs_nvkms_ioctl_params req; + int ok = 0; + + if (override_path && override_path[0] != '\0') { + candidates[n++] = override_path; + } else { + candidates[n++] = "/dev/nvidia-rs-modeset"; + candidates[n++] = "/dev/nvidia-modeset"; + } + + for (i = 0; i < n; i++) { + ms_fd = open(candidates[i], O_RDWR | O_CLOEXEC); + if (ms_fd >= 0) { + strncpy(r->modeset_path, candidates[i], + sizeof(r->modeset_path) - 1); + r->modeset_path[sizeof(r->modeset_path) - 1] = '\0'; + break; + } + } + if (ms_fd < 0) + return 0; + + /* NVKMS AllocDevice (cmd 0) followed by FreeDevice (cmd 1). */ + memset(payload, 0, sizeof(payload)); + memcpy(payload, &gpu_id, sizeof(gpu_id)); + + memset(&req, 0, sizeof(req)); + req.cmd = 0; + req.size = sizeof(payload); + req.address = (uint64_t)(uintptr_t)payload; + if (ioctl(ms_fd, NVKMS_IOCTL_IOWR, &req) != 0) + goto out_close; + + memset(&req, 0, sizeof(req)); + req.cmd = 1; + req.size = sizeof(payload); + req.address = (uint64_t)(uintptr_t)payload; + if (ioctl(ms_fd, NVKMS_IOCTL_IOWR, &req) != 0) + goto out_close; + + ok = 1; + +out_close: + close(ms_fd); + return ok; +} + +int main(int argc, char **argv) +{ + const char *drm_path = (argc > 1 && argv[1][0] != '\0') + ? argv[1] + : "/dev/dri/card0"; + const char *ms_override = (argc > 2 && argv[2][0] != '\0') + ? argv[2] + : NULL; + struct smoke_result r; + int fd; + int passed; + + memset(&r, 0, sizeof(r)); + + fd = open(drm_path, O_RDWR | O_CLOEXEC); + if (fd >= 0) { + r.open_drm = 1; + r.version = check_version(fd, &r); + r.client_caps = check_client_caps(fd); + (void)check_resources_and_connector(fd, &r); + r.dumb_fb = check_dumb_fb(fd); + r.dev_info = check_dev_info(fd, &r); + r.dmabuf_fence_supported = check_dmabuf_and_fence_supported(fd); + (void)check_gem_nvkms_prime_and_semsurf(fd, &r); + r.gem_usermem = check_gem_usermem(fd); + r.dpy_conn_roundtrip = check_dpy_conn_roundtrip(fd, &r); + r.crtc_crc32 = check_crtc_crc32(fd, &r); + r.unique_id = check_unique_id(fd, drm_path, &r); + close(fd); + } + + r.modeset_ioctl = check_modeset_ioctl(ms_override, r.gpu_id, &r); + + passed = (r.open_drm && + r.version && + r.client_caps && + r.resources && + r.connector && + r.dumb_fb && + r.dev_info && + r.dmabuf_fence_supported && + r.gem_nvkms && + r.prime_dmabuf && + r.gem_usermem && + r.semsurf_sync && + r.dpy_conn_roundtrip && + r.crtc_crc32 && + r.unique_id && + r.modeset_ioctl); + + printf("{\"passed\": %s, \"drm_path\": ", passed ? "true" : "false"); + print_json_escaped(drm_path); + printf(", \"driver_name\": "); + print_json_escaped(r.driver_name); + printf(", \"modeset_path\": "); + print_json_escaped(r.modeset_path); + printf(", \"gpu_id\": %u" + ", \"counts\": {\"crtcs\": %u, \"connectors\": %u, \"encoders\": %u, \"modes\": %u}" + ", \"dpy_id\": %u" + ", \"unique_ids\": [%llu, %llu]" + ", \"checks\": {" + "\"open_drm\": %s, " + "\"version\": %s, " + "\"client_caps\": %s, " + "\"resources\": %s, " + "\"connector\": %s, " + "\"dumb_fb\": %s, " + "\"dev_info\": %s, " + "\"dmabuf_fence_supported\": %s, " + "\"gem_nvkms\": %s, " + "\"prime_dmabuf\": %s, " + "\"gem_usermem\": %s, " + "\"semsurf_sync\": %s, " + "\"dpy_conn_roundtrip\": %s, " + "\"crtc_crc32\": %s, " + "\"unique_id\": %s, " + "\"modeset_ioctl\": %s" + "}}\n", + r.gpu_id, + r.count_crtcs, + r.count_connectors, + r.count_encoders, + r.count_modes, + r.dpy_id, + (unsigned long long)r.unique_id_1, + (unsigned long long)r.unique_id_2, + r.open_drm ? "true" : "false", + r.version ? "true" : "false", + r.client_caps ? "true" : "false", + r.resources ? "true" : "false", + r.connector ? "true" : "false", + r.dumb_fb ? "true" : "false", + r.dev_info ? "true" : "false", + r.dmabuf_fence_supported ? "true" : "false", + r.gem_nvkms ? "true" : "false", + r.prime_dmabuf ? "true" : "false", + r.gem_usermem ? "true" : "false", + r.semsurf_sync ? "true" : "false", + r.dpy_conn_roundtrip ? "true" : "false", + r.crtc_crc32 ? "true" : "false", + r.unique_id ? "true" : "false", + r.modeset_ioctl ? "true" : "false"); + + return passed ? 0 : 1; +} diff --git a/tools/dev_reload.sh b/tools/dev_reload.sh index 2172ed52..93a410c2 100755 --- a/tools/dev_reload.sh +++ b/tools/dev_reload.sh @@ -30,10 +30,48 @@ done KO=kernel-open/nvidia_rs.ko # A leading name=value is a module parameter, not the module path. case "${1:-}" in ""|*=*) ;; *) KO=$1; shift ;; esac +KO_DIR=$(dirname "$KO") +MODESET_KO="$KO_DIR/nvidia_rs_modeset.ko" +DRM_KO="$KO_DIR/nvidia_rs_drm.ko" set -- "pci_target=$NV_RS_DEV_RELOAD_BDF" runtime_engines=1 "$@" STAMP=$(date '+%Y-%m-%d %H:%M:%S') [ -f "$KO" ] || { echo "missing $KO (make CONFIG_DEBUG_INFO_BTF_MODULES= modules)"; exit 2; } + +RELOAD_MODESET=0 +RELOAD_DRM=0 +MODESET_ARGS="" +DRM_ARGS="" + +read_bool_param() { + if [ -r "$1" ]; then + case "$(cat "$1" 2>/dev/null)" in + Y|y|1) echo 1 ;; + N|n|0) echo 0 ;; + esac + fi +} + +if [ -e /sys/module/nvidia_rs_modeset ]; then + [ -f "$MODESET_KO" ] || { echo "missing $MODESET_KO (needed to reload loaded nvidia_rs_modeset)"; exit 2; } + RELOAD_MODESET=1 + v=$(read_bool_param /sys/module/nvidia_rs_modeset/parameters/virtual_display) + [ -n "$v" ] && MODESET_ARGS="$MODESET_ARGS virtual_display=$v" + if [ -r /sys/module/nvidia_rs_modeset/parameters/max_alloc_mb ]; then + v=$(cat /sys/module/nvidia_rs_modeset/parameters/max_alloc_mb 2>/dev/null) + case "$v" in ''|*[!0-9]*) ;; *) MODESET_ARGS="$MODESET_ARGS max_alloc_mb=$v" ;; esac + fi +fi + +if [ -e /sys/module/nvidia_rs_drm ]; then + [ -f "$DRM_KO" ] || { echo "missing $DRM_KO (needed to reload loaded nvidia_rs_drm)"; exit 2; } + RELOAD_DRM=1 + for p in modeset fbdev compat_drm_name; do + v=$(read_bool_param "/sys/module/nvidia_rs_drm/parameters/$p") + [ -n "$v" ] && DRM_ARGS="$DRM_ARGS $p=$v" + done +fi + sh tools/dev_health.sh pre || { echo "health check failed: no reload attempted"; exit 1; } holders() { @@ -44,6 +82,26 @@ holders() { done } +rmmod_wait() { + mod="$1" + sudo rmmod "$mod" & + RMMOD=$! + i=0 + while kill -0 "$RMMOD" 2>/dev/null && [ "$i" -lt 60 ]; do sleep 1; i=$((i + 1)); done + if kill -0 "$RMMOD" 2>/dev/null; then + echo "rmmod $mod has not returned after 60 s." + sudo journalctl -k --no-pager --since "$STAMP" | tail -20 + return 1 + fi + wait "$RMMOD" || { + echo "rmmod $mod failed" + sudo journalctl -k --no-pager --since "$STAMP" | tail -20 + return 1 + } + [ -e "/sys/module/$mod" ] && { echo "$mod is still loaded"; return 1; } + return 0 +} + REBIND=0 if [ -e /sys/module/nvidia_rs ]; then PERSISTED=0 @@ -60,6 +118,20 @@ if [ -e /sys/module/nvidia_rs ]; then # The standard-path aliases keep the old inodes across a reload; drop them now and rebind after insmod. mountpoint -q /dev/nvidiactl 2>/dev/null && REBIND=1 sudo bash tools/bind_dev_nodes.sh --unbind + if [ "$RELOAD_DRM" -ne 0 ]; then + if ! rmmod_wait nvidia_rs_drm; then + [ "$REBIND" -eq 0 ] || sudo bash tools/bind_dev_nodes.sh --bind + [ "$PERSISTED" -eq 0 ] || sudo systemctl start nvidia-persistenced 2>/dev/null + exit 1 + fi + fi + if [ "$RELOAD_MODESET" -ne 0 ]; then + if ! rmmod_wait nvidia_rs_modeset; then + [ "$REBIND" -eq 0 ] || sudo bash tools/bind_dev_nodes.sh --bind + [ "$PERSISTED" -eq 0 ] || sudo systemctl start nvidia-persistenced 2>/dev/null + exit 1 + fi + fi # Every PCI domain, not only 0000. for d in /sys/bus/pci/drivers/nvidia_rs/*:*:*.*; do [ -e "$d" ] || continue @@ -73,21 +145,24 @@ if [ -e /sys/module/nvidia_rs ]; then exit 1 fi done - sudo rmmod nvidia_rs & - RMMOD=$! - i=0 - while kill -0 "$RMMOD" 2>/dev/null && [ "$i" -lt 60 ]; do sleep 1; i=$((i + 1)); done - if kill -0 "$RMMOD" 2>/dev/null; then - echo "rmmod nvidia_rs has not returned after 60 s (GSP-RM did not stop)." - sudo journalctl -k --no-pager --since "$STAMP" | tail -20 - exit 1 - fi - [ -e /sys/module/nvidia_rs ] && { echo "nvidia_rs is still loaded"; exit 1; } + rmmod_wait nvidia_rs || exit 1 fi sudo insmod "$KO" "$@" || { echo "insmod failed"; sudo journalctl -k --no-pager --since "$STAMP" | tail -30; exit 1; } +if [ "$RELOAD_MODESET" -ne 0 ]; then + # shellcheck disable=SC2086 + sudo insmod "$MODESET_KO" $MODESET_ARGS || { echo "insmod $MODESET_KO failed"; sudo journalctl -k --no-pager --since "$STAMP" | tail -30; exit 1; } +fi +if [ "$RELOAD_DRM" -ne 0 ]; then + # shellcheck disable=SC2086 + sudo insmod "$DRM_KO" $DRM_ARGS || { echo "insmod $DRM_KO failed"; sudo journalctl -k --no-pager --since "$STAMP" | tail -30; exit 1; } +fi sudo udevadm settle [ "$REBIND" -eq 0 ] || sudo bash tools/bind_dev_nodes.sh --bind sudo journalctl -k --no-pager --since "$STAMP" -g 'nvidia_rs' | grep -v 'TRACE' | tail -40 -ls -l /dev/nvidiactl /dev/nvidia0 /dev/nvidia-uvm 2>&1 +if [ -e /dev/nvidia-modeset ]; then + ls -l /dev/nvidiactl /dev/nvidia0 /dev/nvidia-uvm /dev/nvidia-modeset 2>&1 +else + ls -l /dev/nvidiactl /dev/nvidia0 /dev/nvidia-uvm 2>&1 +fi sh tools/dev_health.sh post diff --git a/tools/vm/run_desktop_drm_guest.py b/tools/vm/run_desktop_drm_guest.py new file mode 100644 index 00000000..582a80db --- /dev/null +++ b/tools/vm/run_desktop_drm_guest.py @@ -0,0 +1,198 @@ +#!/usr/bin/env python3 +"""Boot a disposable QEMU/KVM guest running the host Linux kernel, load standalone +nvidia_rs.ko + nvidia_rs_modeset.ko + nvidia_rs_drm.ko (zero stock modules), +execute tools/desktop_drm_smoke.c against /dev/dri/card0 and /dev/nvidia-rs-modeset, +and verify clean module unload with zero kernel oops/warnings. +""" +from pathlib import Path +import json +import os +import pwd +import re +import shutil +import subprocess +import sys +import tempfile + +ROOT = Path(__file__).resolve().parents[2] +OUT = ROOT / "target" / "vm-desktop" + + +def decompress_ko(src: Path, dst: Path) -> None: + if src.suffix == ".zst": + subprocess.run(["zstd", "-dc", str(src)], stdout=dst.open("wb"), check=True) + elif src.suffix == ".xz": + subprocess.run(["xz", "-dc", str(src)], stdout=dst.open("wb"), check=True) + elif src.suffix == ".gz": + subprocess.run(["gzip", "-dc", str(src)], stdout=dst.open("wb"), check=True) + else: + shutil.copy2(src, dst) + + +def find_kernel_mod(name: str) -> Path | None: + p = subprocess.run(["modinfo", "-n", name], capture_output=True, text=True) + if p.returncode != 0: + return None + path = Path(p.stdout.strip()) + return path if path.exists() else None + + +def main() -> int: + OUT.mkdir(parents=True, exist_ok=True) + smoke_src = ROOT / "tools" / "desktop_drm_smoke.c" + smoke_bin = OUT / "desktop-drm-smoke" + if not smoke_src.exists(): + print(f"ERROR: missing {smoke_src}", file=sys.stderr) + return 2 + + subprocess.run( + ["gcc", "-static", "-O2", "-Wall", "-Wextra", "-o", str(smoke_bin), str(smoke_src)], + check=True, + ) + + krel = os.uname().release + vmlinuz = OUT / "vmlinuz" + if os.environ.get("NV_RS_VMLINUZ"): + shutil.copy2(os.environ["NV_RS_VMLINUZ"], vmlinuz) + elif Path(f"/usr/lib/modules/{krel}/vmlinuz").is_file(): + shutil.copy2(f"/usr/lib/modules/{krel}/vmlinuz", vmlinuz) + else: + subprocess.run( + ["sudo", "-n", "cat", f"/boot/vmlinuz-{krel}"], + stdout=vmlinuz.open("wb"), + check=True, + ) + + for ko in ("nvidia_rs.ko", "nvidia_rs_modeset.ko", "nvidia_rs_drm.ko"): + if not (ROOT / "kernel-open" / ko).exists(): + print(f"ERROR: missing kernel-open/{ko}; run 'make modules' first", file=sys.stderr) + return 2 + + with tempfile.TemporaryDirectory(prefix="nvrs-desktop-initramfs-") as tmp: + fs = Path(tmp) + for d in ("bin", "dev", "proc", "sys", "tmp", "mods"): + (fs / d).mkdir(parents=True, exist_ok=True) + shutil.copy2(os.environ.get("BUSYBOX", "/usr/bin/busybox"), fs / "bin" / "busybox") + shutil.copy2(smoke_bin, fs / "desktop-drm-smoke") + + load_deps: list[str] = [] + for dep in ("ttm", "drm_ttm_helper"): + dep_path = find_kernel_mod(dep) + if dep_path: + decompress_ko(dep_path, fs / "mods" / f"{dep}.ko") + load_deps.append(f"/mods/{dep}.ko") + + for ko in ("nvidia_rs.ko", "nvidia_rs_modeset.ko", "nvidia_rs_drm.ko"): + shutil.copy2(ROOT / "kernel-open" / ko, fs / "mods" / ko) + + dep_lines = "\n".join(f"insmod {d} || echo NV_RS_DEP_FAIL {d}" for d in load_deps) + init_script = f"""#!/bin/busybox sh +/bin/busybox --install -s /bin +mount -t proc proc /proc +mount -t sysfs sysfs /sys +mount -t devtmpfs devtmpfs /dev +echo NV_RS_DESKTOP_VM_START +{dep_lines} +insmod /mods/nvidia_rs.ko pci_target="" || {{ echo NV_RS_MOD_FAIL nvidia_rs; poweroff -f; }} +insmod /mods/nvidia_rs_modeset.ko virtual_display=1 || {{ echo NV_RS_MOD_FAIL nvidia_rs_modeset; poweroff -f; }} +insmod /mods/nvidia_rs_drm.ko modeset=1 compat_drm_name=1 || {{ echo NV_RS_MOD_FAIL nvidia_rs_drm; poweroff -f; }} +echo NV_RS_DESKTOP_MODULES_LOADED +ls -la /dev/dri /dev/nvidia-rs-modeset 2>&1 || true +if /desktop-drm-smoke /dev/dri/card0 /dev/nvidia-rs-modeset > /tmp/smoke.json; then + echo "NV_RS_DESKTOP_JSON $(cat /tmp/smoke.json)" + echo NV_RS_DESKTOP_SMOKE_OK +else + echo "NV_RS_DESKTOP_JSON $(cat /tmp/smoke.json)" + echo NV_RS_DESKTOP_SMOKE_FAIL exit=$? +fi +if rmmod nvidia_rs_drm && rmmod nvidia_rs_modeset && rmmod nvidia_rs; then + echo NV_RS_DESKTOP_CLEAN_UNLOAD +else + echo NV_RS_DESKTOP_UNLOAD_FAIL +fi +sync +poweroff -f +""" + init_path = fs / "init" + init_path.write_text(init_script) + init_path.chmod(0o755) + + initrd = OUT / "initramfs.cpio.gz" + find_p = subprocess.Popen(["find", ".", "-print0"], cwd=fs, stdout=subprocess.PIPE) + cpio_p = subprocess.Popen( + ["cpio", "--null", "-o", "-H", "newc"], + cwd=fs, + stdin=find_p.stdout, + stdout=subprocess.PIPE, + stderr=subprocess.DEVNULL, + ) + assert find_p.stdout is not None + find_p.stdout.close() + with initrd.open("wb") as out_f: + gzip_p = subprocess.Popen(["gzip", "-n", "-1"], stdin=cpio_p.stdout, stdout=out_f) + assert cpio_p.stdout is not None + cpio_p.stdout.close() + assert gzip_p.wait() == 0 + assert cpio_p.wait() == 0 + assert find_p.wait() == 0 + + user = pwd.getpwuid(os.getuid()).pw_name + qemu = ( + ["qemu-system-x86_64"] + if os.access("/dev/kvm", os.R_OK | os.W_OK) + else ["sudo", "-n", "-u", user, "-g", "kvm", "qemu-system-x86_64"] + ) + args = qemu + [ + "-machine", "q35,accel=kvm", + "-cpu", "host", + "-m", "1024", + "-smp", "2", + "-nodefaults", + "-display", "none", + "-serial", "stdio", + "-monitor", "none", + "-no-reboot", + "-nic", "none", + "-kernel", str(vmlinuz), + "-initrd", str(OUT / "initramfs.cpio.gz"), + "-append", "console=ttyS0 rdinit=/init panic=-1 nokaslr ignore_loglevel", + ] + + p = subprocess.run(args, capture_output=True, text=True, timeout=90) + out = p.stdout + p.stderr + (ROOT / "reports" / "vm-desktop-drm-serial.log").write_text(out) + + errors: list[str] = [] + for marker in ( + "NV_RS_DESKTOP_VM_START", + "NV_RS_DESKTOP_MODULES_LOADED", + "NV_RS_DESKTOP_SMOKE_OK", + "NV_RS_DESKTOP_CLEAN_UNLOAD", + ): + if marker not in out: + errors.append(f"missing marker: {marker}") + for bad in ("BUG:", "Oops:", "WARNING: CPU:", "checksum is invalid", "NV_RS_MOD_FAIL", "NV_RS_DESKTOP_SMOKE_FAIL", "NV_RS_DESKTOP_UNLOAD_FAIL"): + if bad in out: + errors.append(f"found error pattern: {bad}") + + smoke_json = None + for line in out.splitlines(): + line = line.strip() + if line.startswith("NV_RS_DESKTOP_JSON "): + try: + smoke_json = json.loads(line[len("NV_RS_DESKTOP_JSON "):]) + except json.JSONDecodeError: + pass + + report = { + "passed": len(errors) == 0 and p.returncode == 0 and bool(smoke_json and smoke_json.get("passed")), + "errors": errors, + "exit_code": p.returncode, + "smoke_result": smoke_json, + } + print(json.dumps(report, indent=2)) + return 0 if report["passed"] else 1 + + +if __name__ == "__main__": + raise SystemExit(main())