284 Commits

Author SHA1 Message Date
860fe11713 ga10x_gsp: populate bare-metal GspSystemInfo hypervisorType, FHB/chipset IDs, and upstream ASPM (#487, #548) (#660)
* ga10x_gsp: populate GspSystemInfo hypervisorType, FHB/chipset IDs, and upstream ASPM (#487, #548)

* ga10x_gsp: guard upstream ASPM on intervening bridges and keep chipsetIDInfo separate from FHBBusInfo

---------

Co-authored-by: Eric Hartford <eric@quixi.ai>
2026-12-05 19:24:28 -08:00
42ec794956 rmapi: probe pre-GSP FB/L2/bus-width geometry from BAR0 and keep VPSTATE MCLK above P8 (#631) (#633)
* rmapi: probe pre-GSP FB/L2/bus-width geometry from BAR0 and keep VPSTATE MCLK above P8 (#631)

* rmapi: reject PRI errors on NV_FUSE_STATUS_OPT_HALF_FBPA in FbGeometry::from_registers

---------

Co-authored-by: Eric Hartford <eric@quixi.ai>
2026-12-05 14:54:47 -08:00
3e1bf7b8c8 perf(rmapi/uvm/pcie): batch sysmem pool reuse & UVM DMA drain, roll back PCIe target on retrain failure (#516)
* fix(pcie): restore link target after retrain register failures

Reuse the existing best-effort timeout rollback for every failure after the endpoint target write succeeds, preserving the original error. Fault injection exposes three failing tests on master; all eight targeted tests, workspace tests, clippy and offline codegen checks pass with the correction. No changes to link policy, capability gates or success path.

* perf(uvm): batch DMA mapping cleanup at node exit

Drain up to 16 live records per leaf-mutex acquisition, preserving bucket order and leaving DMA unmap/page/device releases outside the lock. No changes to insert/lookup/device detach, per-page unmap or mapping permissions. Seven paired CPU-only samples from 1 to 262144 records show 1.30x to 20.85x faster ledger cleanup. Workspace 1409 passed, 150 ignored; clippy, formatting, native codegen and Rust kernel object build pass. Full kernel module and physical/guest testing pending.

* perf(rmapi): batch hot system-page pool reuse

Take up to 32 hot pages per pool mutex acquisition, publish the count once, and clear all reused pages outside the mutex. Preserve LIFO order, partial/empty fallback, admission and cache policy, and allocation failure cleanup. Seven paired host benchmarks show up to 4.72x faster bookkeeping and 4.92x p99 improvement for 16384 fully pooled pages, with single-page and empty-pool parity. 1409 workspace tests pass, 150 ignored; strict clippy, codegen audit, Rust kernel object and offline kernel gates pass. Full C module/guest/physical validation pending.

---------

Co-authored-by: Nick <your-email@example.com>
2026-12-05 14:19:17 -08:00
c777e5cc67 feat(display): standalone Stage 2 desktop video (nvidia_rs_modeset + nvidia_rs_drm) (#608)
* feat(desktop-video): Stage 2 standalone nvidia_rs_modeset + nvidia_rs_drm cutover

Complete Stage 2 standalone clean-room desktop video implementation
matching exact NVIDIA 580.178.04 DRM and NVKMS UAPI layouts (rebased
onto #587 GEM_EXPORT_DMABUF_MEMORY):

- DRM (24/24 PORTED):
  - Harden atomic KMS compositor paths in nvidia_rs_drm.c:
    atomic_disable vblank event delivery (prevents Wayland hangs /
    WARN_ON), crtc_atomic_check, cursor plane <=256x256 validation,
    and async_page_flip capability advertisement.
  - Add KAPI kms_grant_permissions / kms_revoke_permissions backing
    and end-to-end QEMU smoke coverage for GEM_EXPORT_DMABUF_MEMORY,
    atomic modeset + vblank flips, CRTC disable, and DRM permissions.
- NVKMS (62/66 PORTED, 4 Quadro Sync framelock honestly PARTIAL):
  - Connect /dev/nvidia-rs-modeset (/dev/nvidia-modeset) chardev to
    refcounted shared nv_rs_kms_device instances (real heads, disps,
    connectors, EDID, hardware commit & CRC32).
  - Add #![no_std] low-stack EDID 1.4 / CEA-861 mode enumerator and
    validator (src/nvidia/src/nvkms/modes.rs) and stateful NVKMS
    backends for permissions, deferred request FIFOs, swap groups,
    DPY/DISP attributes, vblank sync/sem controls, fliplock, mux,
    and 580 cmd 63/64 (src/nvidia/src/nvkms/state.rs).
  - Add per-file event ring buffer + wait_queue_head_t poll() wakeups
    and exact 580 grant/unicast-event fd roles.
- Verification (offline + disposable QEMU/KVM Linux 7.0 guest only):
  - make modules + check_kernel_module.py: PASS (0 GOT, 0 SIMD,
    0 memcpy/memset/memmove, largest_stack=1016).
  - cargo fmt --check, cargo clippy -D warnings, cargo test nvkms (76/76),
    NV_RS_KERNEL_IBT=1 kernel-module-gate (37/37): ALL PASS.
  - tools/vm/run_desktop_drm_guest.py: 19/19 checks PASS with clean unload.

* nvkms/drm: address CodeRabbit review findings for Stage 2 desktop video

- EDID/mode parsing (modes.rs): use exact 64-bit FNV-1a timing dedup key
  (preserving nearby refresh rates like 1080p60 vs 1080p62 with zero memset),
  decode CTA-861 Video Data Block Short Video Descriptors (VICs), normalize
  interlaced DTD vertical field counts to full frame lines, and reject
  htotal/vtotal > 0x7fff.
- Permissions & swap-group transactional safety (state.rs, mod.rs,
  modeset_ffi.rs, nvidia_rs_modeset.c, nvidia_rs_drm.c): align permission
  type enum to exact 580 values (1=FLIPPING, 2=MODESET, 3=SUB_OWNER),
  validate modeset fd role and share grant fd publication between DRM KAPI
  and NVKMS chardev, scope DRM grants to per-drm_file issuer_id with
  postclose cleanup, support explicit NvKmsPermissions revocation
  (typeMask==0), scope release_device() permission/swap-group cleanup to
  the released device handle, and roll back ACQUIRE_PERMISSIONS /
  ACQUIRE_SWAP_GROUP on copy_to_user -EFAULT.
- Concurrency, refcounting & vblank delivery (nvidia_rs_modeset.c,
  nvidia_rs_drm.c): serialize first-open per GPU with nv_rs_kms_open_lock,
  refcount direct kms_dev lookups via kms_dev_get(), deliver NOTIFY_VBLANK
  asynchronously on real vblank ticks (with fd >= 0 support and release
  cleanup), only consume atomic_disable page-flip events when !active, and
  remove unlatched async_page_flip shortcut.
- Honest -EOPNOTSUPP & parity ledger (nvidia_rs_modeset.c, nvidia_rs_drm.c,
  build_parity_ledger.py, desktop_drm_smoke.c): enforce connector membership
  and connector-specific DigitalSignal on DPY attributes, tighten CRC32 head
  check (< 4) and return -EOPNOTSUPP/supported=0 until HW CRC32 is wired,
  return -EOPNOTSUPP after validation/ownership checks on unimplemented
  chardev hardware-programming ioctls, and update parity ledger & 19/19
  QEMU desktop DRM smoke tests.

* nvkms/drm: resolve round-2 CodeRabbit findings and rebase onto master

- Preserve the full 128-byte 580 NvKmsPermissions union payload verbatim
  across GRANT_PERMISSIONS, ACQUIRE_PERMISSIONS, and explicit
  REVOKE_PERMISSIONS (using black_box copy to keep 0 memcpy/memset).
- Enforce issuer authority (owner or SUB_OWNER) under owner lock before
  publishing chardev permission grants; reject explicit SUB_OWNER
  revocation without mutating state; subtract explicit revocation bits
  rather than deleting partially matching rows; ignore explicit payload
  bytes on non-zero typeMask revocations.
- Reserve consumed permission and swap-group grant slots (pending_commit)
  across copy_to_user and release via commit_acquire / un-reserve via
  rollback_acquire (without resurrecting grants for freed swap groups).
- In NOTIFY_VBLANK, write the reply before mutating ev_f->fd_role or
  linking the waiter, revalidate the device handle under f->lock ->
  nv_rs_kms_lock, wake physical-display waiters from real HW vblank IRQs
  only (keeping synthetic timer as virtual-display fallback).
- Return honest -EOPNOTSUPP for IDLE_BASE_CHANNEL and SET_MODE (both
  commit=0 and commit=1) until full decode/HW wait is implemented; move
  disable completion event delivery back to atomic_flush so disable does
  not signal before scanout stops.

* nvkms/drm: fix stock 580 ABI layouts, transactional grants, vblank sync, and EOPNOTSUPP stubs

* desktop/nvkms: address remaining minor CodeRabbit findings on Stage 2

* desktop/nvkms: resolve round-4 CodeRabbit review findings on Stage 2

* desktop/nvkms: fix irq-safe vblank disable lock and connector probe init

* fix(nvkms): address CodeRabbit review on probe errors, vblank, CursorImm auth, pclk, and attrs

* fix(nvkms,drm): track connector probe validity, add vblank barriers, keep 64-bit refresh checks

---------

Co-authored-by: morebrackets <19673572+morebrackets@users.noreply.github.com>
2026-12-05 13:25:22 -08:00
1ed77198c8 feat(blackwell): adapt desktop video Stage 1 & Stage 2 for RTX 50 (GB202-GB207) (#621)
* feat(blackwell): adapt desktop video Stage 1 & Stage 2 for RTX 50 (GB202-GB207)

* fix(blackwell): address CodeRabbit review on DP 2.1 UHBR training and GB10 preflight

---------

Co-authored-by: morebrackets <19673572+morebrackets@users.noreply.github.com>
2026-12-05 13:05:22 -08:00
b95d30a698 ada/desktop: adapt Stage 1 & Stage 2 desktop video for RTX 40 series (AD102-AD107) (#620)
* ada/desktop: adapt Stage 1 & Stage 2 desktop video for RTX 40 series (AD102-AD107)

Stage 1 & Core Ada GSP-RM / RM fixes (verified against stock 580.196.07):
- ga10x_gsp.rs: stop downgrading Ada's configured 580.x release string when
  no bundled 580.178.04 Ada booter exists, add 580.196.07 -> 580.178.04
  gsprm_load fallback, read NV_FUSE_STATUS_OPT_DISPLAY at 0x820c04 on
  Ampere/Ada+ (_nv030373rm) and propagate display_fused_off into hw facts,
  and fail explicitly (instead of silently skipping) when cold-boot Ada
  scrubber-580.bin is missing.
- display.rs, display_channels.rs, gsp_boot.rs, ga10x.rs: fix Ada
  DispSfUser BAR0 offset (0x6f0000 for all NvDisplay v03_00+ per
  _nv005909rm/_nv040109rm), fix Ada copy_engine class (0xc7b5
  AMPERE_DMA_COPY_B), enable ce_class_db filtering for ArchFamily::Ada,
  and pass real boot0 to configure_live_display().
- gsp_route.rs, rmapi_node.rs, modeset_ffi.rs, modeset_bridge.c: intercept
  NV_ESC_RM_BIND_CONTEXT_DMA (0x59) in pre() for host-side 0x0002 ->
  NvDisplay channel binds, keep modeset_gsp_alloc_ctxdma 100% host-side
  with Node RM video memory lookup via nv_rs_modeset_query_rm_mem, prevent
  double GSP memory registration, purge MODESET_MEMS/MODESET_CTXS on
  NVOS00 free, validate Stage 1 nv_rs_modeset_get_rm_ops against the
  configured 580.x driver_version, and fix NVOS64 debug status trace.

Stage 2 Ada NvDisplay v4.1 (0xc77d/0xc67e) & DRM pipeline fixes:
- nvidia_rs_modeset.c:
  - Separate full Core modeset/link-training from fast Window-only page
    flips and cursor-only Core updates; program Core FIRST on full modeset.
  - Resolve imported compositor/Vulkan/EGL VRAM handles via
    nv_rs_modeset_query_rm_mem and bind host-side NV01_CONTEXT_DMA to Core
    and Window channels for scanout.
  - Enforce BAR1 window bounds on 0x0040 allocations (falling back to
    BAR1-constrained nv_rs_modeset_vram_alloc on non-ReBAR 256 MiB GPUs)
    and propagate block-linear pte_kind.
  - Query NV0073_CTRL_CMD_SPECIFIC_OR_GET_INFO (0x0073028b) for SOR
    sublink A/B (DP_A/DP_B, SINGLE_TMDS_A/B, DUAL_TMDS), promote HDMI
    >600 MHz to SOR_PROTOCOL_HDMI_FRL (0xc), bracket DP link training with
    NV5070_CTRL_CMD_SET_SOR_FLUSH_MODE (0x50700457), support DP 1.4a HBR3
    (0x1e) via DP_GET_CAPS (0x00731369), and retry with FALLBACK_CONFIG.
  - Honor HSYNC/VSYNC polarity and 10 bpc depth in HEAD_SET_CONTROL_OR,
    emit HEAD_SET_CONTROL / PCLK_CFG / USAGE_BOUNDS / STORAGE_CURSOR,
    fix WIN_SET_PLANAR_STRG0 13-bit mask (& 0x1fff), add XBGR16161616F,
    and back off synthetic vblank timer when real HW vblank IRQs arrive
    (removing the 4 ms floor for 240/360 Hz displays).
- nvidia_rs_drm.c: fix VRAM BAR1 mmap vma->vm_pgoff bounds/offset,
  validate explicit FB modifiers and reject compressible modifiers, add
  XBGR16161616F, remove unimplemented NV12, set preferred_depth=24 and
  <6.13 allow_fb_modifiers=true, and pair drm_kms_helper_poll_init/fini.
- install_desktop_boot.sh, reload_stage1.sh: add Ada (ad102) GSP boot &
  scrubber firmware preflight check with extract_gsp_boot_ucode.py hint.
- Add unit tests in display.rs, gsp_boot.rs, nvdisp_pushbuf.rs, and
  gpu_tests.rs covering Ada classes, fuse register, and pushbuffer encode.

* ada/desktop: resolve all CodeRabbit review findings for RTX 40 desktop video

* ada/desktop: address round-2 CodeRabbit review findings

* ada/desktop: address final CodeRabbit review findings

* ada/desktop: track explicit fb modifiers, order disable before vblank_off, reserve Window room up front

---------

Co-authored-by: morebrackets <19673572+morebrackets@users.noreply.github.com>
2026-12-05 12:26:38 -08:00
e0bcddcdbb gv100: fall back to PMU VBIOS power telemetry when baseboard INA3221 is absent (#484) (#623)
* gv100: fall back to PMU VBIOS power telemetry when baseboard INA3221 is absent (#484)

* gv100: gate automatic VBIOS capture on stopped/halted PMU CPUCTL

* gv100: log when PMU power fallback is skipped due to unavailable VBIOS capture

---------

Co-authored-by: Eric Hartford <eric@quixi.ai>
2026-12-05 09:53:12 -08:00
51d7d35c4a rmapi_node: bound external DMA-BUF sgt addresses by the GPU DMA width (#605)
nv_rs_rmapi_register_external_sgt() (GEM_EXPORT_DMABUF_MEMORY bridge,
#587) copied the importer's sg_dma_address() values verbatim into
external_dma_addrs[], which page_dma/page_dma_batch hand straight to
GPU sysmem PTEs. Nothing checked them against the GPU's addressing
width, so on GV11B (dma_bits = 40, platform_driver.c) a scatterlist
mapped for a different/wider device would be silently truncated by
the MMU. Refuse any segment ending past DMA_BIT_MASK(dma_bits) with
-EINVAL, before the RM object is created (caller keeps ownership).

Also derive page_dma_batch's renegotiation width from
nv_rs_rmapi_gpu_dma_bits() like page_dma does instead of a literal 47
(no behaviour change: negotiate already clamps to the node's width).

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 07:21:03 -08:00
dfda0a29a4 dma: device-owned coherent DMA contexts for GV11B platform GPUs (#606)
Add nv_rs_dma_context_create_dev(struct device *, bits, **) and
LinuxDma::from_device so Tegra194 GV11B platform GPUs, which have no
nv_rs_pci lease, can own a coherent DMA context.

ctx->pci is now optional. Creation, close and force_close share
context_init/context_destroy/context_release_owner: a PCI-owned context
releases its DMA user count and PCI reference exactly as before, a
device-owned context drops its get_device() reference with put_device().
Removal checks go through context_removed(), which consults
nv_rs_pci_is_removed only when ctx->pci is set. The PCI path keeps its
check order and errno values (-EINVAL, -ENODEV, -ERANGE, -ENOMEM).

The dma-mock fixture models get_device/put_device and covers the
device-owned lifecycle, every create failure path, force_close, and
independence from PCI removal state.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 07:20:57 -08:00
cb60725ce0 hwmon: close unregister drain race and add CONFIG_HWMON=n register_dev stubs (#598)
* hwmon: close unregister drain race and add CONFIG_HWMON=n register_dev stubs

* hwmon: preserve failure invalidation and return -ENODATA on removal
2026-12-05 07:20:51 -08:00
59190a5dc1 fix(gpu_owner): park nvidia_rs_rtN kthread in TASK_IDLE instead of D state (#614)
nv_rs_runtime_park_wait() currently sleeps with wait_event_timeout(), which puts each GPU's long-lived nvidia_rs_rtN worker into TASK_UNINTERRUPTIBLE (D state) for its entire parked lifetime. That permanently adds +1.00 per GPU to system load average and causes D-state hang checks (such as tools/gpu_binding.py) to flag an idle worker unless explicitly exempted.

Switch to wait_event_idle_timeout(), which sleeps in TASK_IDLE (TASK_UNINTERRUPTIBLE | TASK_NOLOAD):
- identical wake_up() and signal-ignoring semantics;
- displays as I (idle kthread) instead of D and adds 0 to load average;
- available in <linux/wait.h> since Linux 4.15 (well below the 5.15+ compat floor in docs/KERNEL_COMPAT.md).

Co-authored-by: Arsenova <arsenova@a7snv.com>
2026-12-05 07:20:34 -08:00
854741c986 fix(rmapi): answer NV2080_CTRL_CMD_BUS_GET_PCI_INFO_V2 (0x2080183c) on pre-GSP GPUs (#590)
* fix(rmapi): answer NV2080_CTRL_CMD_BUS_GET_PCI_INFO_V2 (0x2080183c) on pre-GSP GPUs (#564)

580.196.07 nvidia-smi / NVML asks for 0x2080183c when it reports
pci.bus_id. It is not in the 580.178.04 export table that control_table.rs
is generated from, so a pre-GSP GPU refused it with NV_ERR_NOT_SUPPORTED
(0x56) and `nvidia-smi --query-gpu=pci.bus_id` printed [N/A]. 580.178.04
userspace never sends it, which is why this went unseen.

The 28-byte layout is NV2080_CTRL_BUS_GET_PCI_INFO_V2_PARAMS from
NVIDIA/open-gpu-kernel-modules main (ctrl2080bus.h): the four words of
0x20801801 followed by pciProgrammingInterface, pciSubClass and
pciBaseClass. The class words come from the PCI class code, which the
PCI probe now passes down in RmapiGpu/nv_rs_rmapi_gpu (pdev->class).

Evidence: stock 580.196.07 replies captured with tools/ioctl_capture on an
EVGA GTX 1080 Ti (3842:6696, bus 01) and gdevenyi's ASUS capture on #564
(1043:85f1, bus 02) are reproduced byte for byte by new unit tests that
go through the RM_CONTROL escape path. The bus number is not part of this
reply; pci.bus_id keeps coming from 0x21b, which already matched stock.

0x2080012f is left alone: stock 580.196.07 also answers 0x56 on this
non-ECC GP102 (#371), and master already does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HgXrs8WswQymXpCe2YSiEM

* fix(gsp): keep NV2080_CTRL_CMD_BUS_GET_PCI_INFO_V2 (0x2080183c) host-only on the GSP route

The synthetic descriptor added for pre-GSP GPUs made control_info() know
0x2080183c, so the GSP route's validate() would now pass it and forward it
to GSP-RM for an owned mirrored object. Before this PR the command was
unknown to the tables and answered on the host Node. Add it to the existing
host-only list next to 0x00801401 and 0x20808165 so GSP-RM never sees it.

Reported by CodeRabbit on #590.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HgXrs8WswQymXpCe2YSiEM

---------

Co-authored-by: Dino Vitale <chaotikdino@gmail.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 06:30:58 -08:00
b295cd58e3 uvm: sorted range and external-map tables with binary search; UVM file capacity 4096 -> 16384 (#596)
* uvm: sorted range and external-map tables with binary search; capacity 4096 -> 16384

The UVM ranges and external-map tables were unordered fixed arrays of
MAX_RANGES = 4096 entries with linear scans. A full table returned
NV_ERR_NO_MEMORY at about 4,000 pinned allocations (#412), and a larger
constant alone made every map slower.

Both tables are now dense and sorted (ranges by start, maps by
(gpu, start)). Lookups use partition_point; insert and remove move the
tail with element loops (black_box on the index, so no memmove). Loops
over all ranges stop at range_count. FILE_RANGES is 16384.

Tests: logarithmic probe bound per create/map/free, sorted order through
a managed split and VMA close, full-table NO_MEMORY, last-byte lookup.

Fixes #412

* uvm: charge the per-open file state to the opener's memcg

nv_rs_uvm_open allocates the handle and the UVM file state (about 1.87 MB
at the 16384 capacity) with GFP_KERNEL. The device is mode 0666, so a
local user could open it many times and grow kernel memory that no cgroup
limit sees. Allocate both with GFP_KERNEL_ACCOUNT, as dmabuf_p2p.c does,
so the opener's memory cgroup pays for each open and its limit applies.

The idle cost per open does not change. Lazy table capacity is a
possible follow-up.

---------

Co-authored-by: GrowDev1 <growdev1@users.noreply.github.com>
2026-12-05 06:30:48 -08:00
Jo
cc6c5bae65 fix(hwmon): invalidate stale telemetry after acquisition failures (#567)
* hwmon: WIP temperature freshness correction with host-fixture tests

WIP contribution addressing #561 (temperature readings stay valid
after acquisition failures). Not ready for merge; submitted for
contributor review.

- Failed acquisitions invalidate the live channels they cover
  (provider bits on failure are untrusted); a failed poll no longer
  extends the freshness window and does not count as a successful
  poll; retries are rate-limited and unsupported providers are
  retried rather than latched.
- Per-channel acquisition stamps bound the served age (2 s cap) and
  per-channel publication sequences provide same-tick ordering
  between polls and mirror publications; reads take validity, stamp
  and value in one critical section.
- Mirror snapshots are incremental: they never invalidate channels
  they do not carry.
- Static limits (temp_max/temp_crit/power_cap) supplied by successful
  polls are applied and preserved across failures.

Regression coverage: host fixture tests/hwmon-mock/ compiles the real
hwmon_adapter.c against a kernel API mock - 71/71 assertions (17
registration + 54 behavioral). Kernel build on 7.0.0-44-generic
headers: module gate 18/18.

Feedback incorporated from dcr000 on #561 (sample timestamps,
failed-poll semantics; the GP100 self-poll provider is intentionally
left out of this patch). Independent review: Codex (2f67d67e) - GO
for these two corrections, with the legacy-provider compatibility
limitation (ENODEV from the GA10x-only provider can invalidate recent
legacy-mirror data) and physical qualification remaining outstanding.

Prepared with AI assistance; operator-reviewed.

* hwmon: retain bounded mirror data when no active acquisition is possible

Addresses CodeRabbit's finding on the draft PR and the legacy-provider
compatibility gap recorded by Codex (2f67d67e): an -ENODEV poll (no
GA10x/GSP owner - mirror-only GPUs such as GP100, or a runtime that
has not started yet) no longer invalidates recent mirror publications.
Such polls are not acquired-channel errors: the mirror samples are
retained and expire by their own per-channel age bound, the provider
is retried every window and is never latched, and a runtime that
appears later acquires normally.

Real acquisition failures (non-ENODEV) keep the immediate
per-channel invalidation, and all freshness, ordering, static-limit
and incremental-mirror semantics are unchanged. Fixture updated:
ENODEV retains recent mirror data within its age bound, expiry still
applies, retries happen per window, and recovery works once the
provider appears (72/72 PASS: 17 registration + 55 behavioral).

* hwmon: align accepted poll intervals with the served-age bound

Addresses the remaining trivial CodeRabbit finding: with poll
intervals above roughly 500 ms, a healthy active provider's reading
expired under the 2 s served-age cap before the next poll could run,
producing artificial -ENODATA periods (merge-base kept the value).
The freshness limit itself is unchanged; instead the accepted maximum
poll interval is now aligned with it: NV_RS_HWMON_POLL_MAX_MS is 500
(the largest interval whose uncapped active age formula, 2*poll+1000,
stays within the 2 s bound), larger configured values are clamped
rather than refused so polling keeps working, and the clamp is
documented in the module parameter description. A static_assert ties
the interval and age constants together at compile time. Regression
tests: oversized intervals are clamped and stay fresh; the default
interval never starves a healthy provider (no re-poll inside the
rate-limit window, exactly one poll in the next). 83/83 PASS.

* hwmon: revert the polling clamp; document long-interval -ENODATA behavior

Per independent review (cdaf3ee0), revert the v7 polling clamp: the
established minimum-interval contract is preserved and hwmon_poll_ms
is again honored up to 60000 ms. The 2 s served-age bound is
unchanged and is never extended to bridge a long polling interval:
with hwmon_poll_ms above the age bound, cached samples legitimately
expire and reads return -ENODATA between eligible acquisitions. This
is now documented in the served-age comment and in the module
parameter description.

Configuration regression tests updated: long intervals honor the
requested minimum (no clamp, no re-poll inside the window) and expose
-ENODATA once the cache expires, then refresh at the next eligible
poll; intermediate intervals (1000 ms) return -ENODATA after expiry
and recover on the next eligible read; the default interval keeps a
healthy provider fresh without extra polls. 92/92 PASS.

* hwmon: allow immediate cold-start acquisition; keep failures rate-limited

Addresses the second CodeRabbit minor finding (verified against
b6f657b4): the zero-initialized attempt timestamp was a sentinel, not
a real attempt, so a freshly registered slot could be throttled before
its first poll when the Linux tick counter was below the poll
interval. A separate 'attempted' flag now gates the retry deadline:
the first attempt always runs (cold start acquires immediately, as the
merge base did), while subsequent attempts - successes, failures and
unsupported providers alike - remain rate-limited by the configured
interval. mark_polled also marks an attempt so a Rust-side poll
completion keeps its throttling semantics. Regression test: cold
start with a small tick counter acquires on the first read with
exactly one poll, and the window still suppresses further polls.

The first CodeRabbit minor finding (transport-latency vs acquisition
age on a late-RPC timeout) is an existing upstream producer-contract
limitation, not a regression of this patch: the merge base served the
delayed value indefinitely; this patch bounds it to the 2 s served
age. Producer-side acquisition timestamps remain the documented
follow-up.

* hwmon: partial-poll retention, separate loop index, C89 declarations, stale-bit clear

One minimal revision addressing the latest CodeRabbit minor finding and
dcr000's review items at 60112a59:

- Partially available telemetry: a successful poll that did not
  acquire a channel no longer erases a still-fresh cached value for
  that channel (a partial batch must not invalidate an unrelated
  fresh mirror reading); the cached value is cleared only once it is
  already past its served age. Failed acquisitions still invalidate
  immediately.
- Separate loop index in nv_rs_hwmon_update_sample so the channel
  stamp loop no longer reuses the enclosing slot index.
- The sysfs show helpers declare their locals at function top,
  keeping kernels before 6.5 (-Wdeclaration-after-statement)
  buildable.
- Timestamp expiry and wraparound: the first stale read clears the
  channel's valid bit (publication-sequence guarded), so a jiffies
  wraparound cannot revive an ancient reading; a new publication
  restores it. Regression test added with a simulated 32-bit wrap.

Configurable freshness limits remain a separate design decision for
the maintainers (not changed here); the GP100 self-poll provider
stays with dcr000. Fixture 103/103 PASS; kernel-object gate 18/18.

* hwmon: conservative partial-poll semantics, in-lock expiry, wrap-safe age, strict-C89 helpers

Addresses Codex 36419308's four findings:

1. Partial-poll retention reverted: with the existing provider API an
   absent channel cannot be told apart from a failed acquisition, so
   successful polls conservatively invalidate channels they did not
   acquire (v9 error semantics restored); per-channel acquisition/
   error status from the provider remains the documented follow-up.
2. Read-side expiry evaluation and the stale-bit clear now happen
   inside the same sample_lock critical section as the snapshot, so a
   concurrently published sample (poll or mirror) is never discarded.
3. Age comparison uses the wrap-safe unsigned jiffies difference;
   on every supported target (x86_64, arm64) stamps are 64-bit and
   cannot compare young again. Fixture covers observed expiry, a huge
   dormant offset and recovery.
4. The five sysfs helpers now declare locals before any statement;
   verified with -Werror=declaration-after-statement on the guest.

Fixture 102/102 PASS (22 registration + 80 behavioral), also passing
under the strict declaration check; kernel-object gate 18/18.
2026-12-05 06:30:40 -08:00
f3862b6300 drm: implement GEM_EXPORT_DMABUF_MEMORY (24/24 DRM ioctls ported) (#587)
* drm: implement GEM_EXPORT_DMABUF_MEMORY via RM 0x71 external sgt bridge (24/24 DRM)

* rmapi: enforce external_gpu_id on DMA lookups and mirror forwarded GSP devices

* rmapi: keep locally registered memory RM_FREE on native execute_full path

* rmapi: scope local RM_FREE bypass to local UserPages (0x0071) backings only

* rmapi: mirror forwarded GSP peer device on import_slot and clean up local entries on forwarded FREE

* rmapi: recursively free native subtrees on GSP object free and keep UserPages MAP_MEMORY_DMA native

* rmapi: return NOT_SUPPORTED for UserPages MAP_MEMORY_DMA on legacy gsp_bringup sessions

* rmapi: verify client ownership before returning NOT_SUPPORTED on legacy GSP UserPages MAP_MEMORY_DMA

---------

Co-authored-by: Eric Hartford <eric@quixi.ai>
2026-12-05 04:20:19 -08:00
f3838d692d gv100/hbm: survey only the FBPAs the FBIO floorsweep fuse leaves enabled (#399) (#583)
* gv100/hbm: survey only the FBPAs the FBIO floorsweep fuse leaves enabled

survey_gv100_hbm() demanded all 16 FBPA PLLs readable, locked and equal.
A CMP 100-210 (10de:1df4, 12 GB, three HBM2 stacks) has FBPA 0..=3 fused
off: their PLL cfg/coeff registers answer 0xbadf2010 (PRI bus error)
while FBPA 4..=15 read cfg 0x29, coeff 0x14102 (877.5 MHz). The survey
refused the card (CfgUnreadable at FBPA 0), so the HBM2 session never got
a baseline and v100_hbm_ndiv was a no-op. program_coeff() made the same
assumption twice more: its post-write probe read FBPA 0, and its lock
wait polled all 16.

1. Survey mask. 580.178.04 does not probe for bus errors; it computes the
   enabled-FBPA mask from the fuse. _nv030402rm (GV100 GPU HAL slot
   +0x3a0) [D]:
     n    = RD32(0x2243c)                      NV_PTOP_SCAL_NUM_FBPAS
     fuse = OBJFUSE+0x118(0xff000033)          _nv029006rm
            -> OBJFUSE+0x110 _nv028950rm: fuse word 0xc14, shift 0,
               mask 0xffff, i.e. BAR0 0x21c14
     mask = zext64(~fuse); if n <= 64: mask &= ~0 >> (64 - n); n == 0: 0
   A stock mmiotrace of a Tesla V100 shows that pair once, 0x2243c = 0x10
   then 0x21c14 = 0 [O] (reports/original-mmiotrace-b3-first/b3-bar0.txt),
   which gives 0xffff. On the #399 card the reporter read 0x2243c = 0x10
   and 0x21c14 = 0xf [O], which gives 0xfff0 and matches the partitions
   that answer.
2. Post-write probe on the first enabled FBPA instead of FBPA 0.
3. Lock wait polls only the enabled FBPAs.
   Stock never retunes the HBM2 PLL, so 2 and 3 have no stock evidence;
   they follow from 1. On silicon [O]: the reporter ran 23db150 with the
   equivalent change (presence taken from the bus-error word rather than
   the fuse) on the #399 card and got a verified 877.5 -> 1107 MHz unlock
   (NDIV 65 -> 82) on FBPA 4..=15, D2D 618 -> 781 GB/s, then adaptive
   backoff on real ECC DBE/SBE and a clean return to NDIV 65
   (https://github.com/QuixiAI/nvdriver/issues/399#issuecomment-7386631509).
   This exact commit has not run on silicon.

fbio_enabled_mask() is the stock arithmetic and gv100_enabled_fbpa_mask()
the two reads, in stock order. An enabled partition must still be
readable, locked and in agreement (the reference coefficient is the first
enabled partition's), so a card whose fuse says 16 but whose FBPA 0 does
not answer is refused as before. The mask is resolved before the
multicast write; if 0x2243c is unreadable, 0 or above 16, or the fuse is
unreadable or enables nothing, the survey reports the new fault kinds
FbpaCountUnusable (6) / FbioFuseUnusable (7) and nothing is written. A
mask lost between the survey and the write is a refusal before the target
write, like the PMC_BOOT_0 canary: logged as SurveyFailed, not RolledBack.
gpu_owner.c logs kinds 6 and 7, and the CoeffMismatch text now says "the
first enabled FBPA" instead of "FBPA 0". A 16-partition card does two
more BAR0 reads per survey and per program_coeff and otherwise behaves as
before. The ECC poll and the backoff logic are unchanged.

Tests: fbio_enabled_mask_matches_nv030402rm_arithmetic,
gv100_hbm_survey_and_unlock_skip_fused_off_fbpas (mock with FBPA 0..=3
reading 0xbadf2010, fuse 0xf: survey, unlock 65 -> 82, backoff step,
restore; refusals with zero writes for unusable mask inputs), and
gv100_hbm_mask_lost_before_the_target_write_is_not_a_rollback. Without
the change the first survey assertion fails; reverting only the probe or
only the lock wait makes the unlock fail.

Refs #399

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* gv100/hbm: fall back to cached floorsweep mask on rollback/restore and log teardown failure

Addresses CodeRabbit review finding on PR #583:
- Cache the static silicon enabled-FBPA mask resolved during baseline survey
  (HbmSession::enabled_fbpa_mask and inside unlock/set rollback paths).
- If re-reading PTOP_SCAL_NUM_FBPAS (0x2243c) or FUSE_OPT_FBIO (0x21c14)
  glitches during a rollback or teardown restore, fall back to the cached
  mask so the baseline HBM2 coefficient write is not blocked while PMC_BOOT_0
  canary remains strictly enforced.
- Log failed HBM2 teardown restores in pmu_bringup.rs via log_hbm_outcome
  instead of discarding the result.
- Add unit test covering fuse-glitch teardown restore and canary refusal.

* gv100/hbm: use cached floorsweep mask for downward safety steps (ECC backoff / baseline return)

Addresses follow-up CodeRabbit finding on PR #583:
- In HbmSession::step_to, downward safety steps (target <= current clock:
  live ECC backoff via on_instability and sysfs return to baseline) fall
  back to the cached static silicon enabled-FBPA mask on a transient read
  failure of 0x2243c/0x21c14 so an elevated clock is never stranded while
  the GPU remains in service.
- Upward overclock steps continue to require a fresh fuse read and refuse
  before writing when unreadable.
- Extend unit test to cover on_instability and on_user_write(0) under a
  fuse-read glitch.

* gv100/hbm: skip rollback write on pre-write mask refusal

Addresses CodeRabbit trivial finding on PR #583:
- When program_coeff refuses before the target write due to an unreadable
  FBPA count (FbpaCountUnusable) or FBIO fuse (FbioFuseUnusable), skip the
  unnecessary rollback multicast write so the PLL stays completely untouched
  (writes == 0) and a clean refusal can never degrade into FailedUnverified.
- Preserve existing pre-write canary refusal behavior unchanged.

---------

Co-authored-by: Scottcjn <121303252+Scottcjn@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: morebrackets <19673572+morebrackets@users.noreply.github.com>
2026-12-05 00:18:44 -08:00
78f8530140 dma-buf export of VRAM: by RM handle (stock ABI) and by CUDA address (#148)
* dmabuf: export RM video memory by handle

NV_ESC_EXPORT_TO_DMABUF_FD (0xd9) only exported a raw BAR1 range, for
CAP_SYS_ADMIN, ignoring the RM handles in the request. Implement the
stock ABI (nv_ioctl_export_to_dma_buf_fd_t, 2608 bytes):

- resolve each (hClient, hMemory, offset, size) to its VRAM with
  nv_rs_rmapi_resolve_dmabuf_object(), authorized like the original:
  the client belongs to the caller's file or its control file
  (CAP_SYS_ADMIN may export any);
- a non-contiguous allocation (scatter_id != 0) is walked segment by
  segment, each piece of the requested range becoming its own BAR1
  extent, so an export never covers the VRAM between two segments;
- up to 128 objects per call, batched calls (index > 0) for larger
  VMM exports, contiguous extents coalesced, segments capped at 1 GiB,
  at most 2^20 extents per dma-buf; its kernel memory (pins, extents)
  grows with the objects appended, not the declared total, and is
  charged to the caller's memory cgroup;
- the dma-buf is BAR1-backed (the GA10x BAR1 maps VRAM 1:1), mapped for
  importers with dma_map_resource(); bAllowMmap allows a write-combined
  CPU mmap, shared only (a private, copy-on-write mapping of PFN-mapped
  memory is refused: vmf_insert_pfn() BUG()s on one). The raw BAR1
  export stays for h_client == 0 (admin only);
- only GSP-RM GPUs export: their BAR1 maps VRAM 1:1 for as long as the
  GPU is in the RM. A pre-GSP GPU's BAR1 window belongs to the runtime
  engines, which clear it when they stop (suspend, AER) while an export
  would keep its offsets, so those GPUs refuse (NV_ERR_NOT_SUPPORTED);
- the fd is reserved, and installed only once the reply carrying it has
  been copied to the caller: a reply that does not arrive leaves no fd,
  and no pin, behind (the raw BAR1 export included).

A dma-buf must not outlive its memory: once the VRAM is freed it can be
handed to another allocation, and a peer still DMAing into the old
range would write into it. The dma-buf therefore holds the memory, as
the stock driver's exports do. Each exported object's backing is pinned
in the RM memory table (Table::pin_export, the reference the FD exports
already take), and every route that frees memory honours it:
NV_ESC_RM_FREE, NVOS32_FUNCTION_FREE (NV_ESC_RM_VID_HEAP_CONTROL),
freeing a parent or the whole client, file release, and channel USERD
orphan cleanup drop the handle but leave the VRAM, and a non-contiguous
allocation's segment chain, allocated while a pin exists. (The orphan
cleanup released a segment chain without that check; it now has it.)
When the dma-buf is released, a work item drops its pins under the RM
API lock and frees whatever nothing else references; a dma-buf can be
released with that lock held, so its release callback does not take it.
Module unload flushes the work item. Exports resolve their handles and
take their pins under the same lock, so a concurrent free either runs
first, and the export fails, or finds the pin.

Only GPU removal still revokes, as the memory goes away regardless.
It first marks the device as going away: from then until the GPU has
left the RM no dma-buf is created over it (the check and the insertion
into the export list are under one lock hold, so an export is either
listed or refused). Before taking the RM API lock, so that RM calls do
not wait behind the importers, every dma-buf over the device is first
marked revoked (attach, map and mmap then fail with -ENODEV) and its
CPU mappings are zapped; then its importers' mappings are invalidated
(dma_buf_invalidate_mappings), those whose reservation object is free
first; only then are the two waits the kernel-doc asks for done for
each: until the fences on the reservation object retire, and until
every importer mapping has been unmapped. An importer slow to retire
its fences, or holding a reservation object, thus leaves no other
dma-buf readable. A dma-buf whose last reference is already going is
waited for until its release has queued its pins, which are then
flushed, so none is dropped after the GPU is gone. Then,
under the lock and before the GPU leaves the RM, the pins are dropped;
nothing waits there. The CPU zap is unmap_mapping_range(); CPU mappings
are filled in at fault time
(vmf_insert_pfn after checking `revoked` under the dma-buf's lock), not
in .mmap, because the kernel links a new VMA into the file's i_mmap
only after .mmap returns and pages inserted there could escape a racing
zap. After a revoke a CPU access gets SIGBUS.

Only importers that can honour a revoke may attach: peer-to-peer
capable (allow_peer2peer, the scatterlist has BAR1 bus addresses and no
struct pages) and revocable (dma_buf_attach_revocable(): they
invalidate and unmap in bounded time). The NVMe dma-buf I/O path is
both. Kernels without dma_buf_attach_revocable() have no such contract
(move_notify only asks importers to remap as soon as possible), so
there the dma-buf has no importers, only the CPU mmap. The exporter is
dynamic (pin/unpin, a no-op: BAR1 memory never moves), so that no
kernel caches an importer's mapping at attach time, where its unmap
would not reach the exporter.

Built against 7.4 only. dma_buf_attach_revocable(), the
invalidate_mappings rename and enum dma_resv_usage are probed in Kbuild
with fallbacks for older kernels, which have not been compiled.

Tested on an RTX 3050 Laptop (GA107), on a 7.4-rc2 kernel with KASAN
and lockdep, IOMMU in identity mode, with io_uring + NVMe dma-buf reads,
through the export by CUDA address added later in this series. That
shares the dma-buf creation, mapping, pinning and release code with
this ioctl but not its handle loop: libcuda does not issue
NV_ESC_EXPORT_TO_DMABUF_FD on this GPU, so multi-object and batched
exports have not run on hardware. NVMe -> VRAM reads were verified
byte for byte. With the memory freed (cuMemFree, cuMemRelease) while
128 reads were queued, or at points in the middle of a stream, every
read completed without error, and the freed VRAM was not reused: a new
allocation filled before the free stayed untouched. The VRAM stays
allocated while the dma-buf is open (free VRAM did not come back after
the RM free) and is returned when it is closed. A dma-buf whose
exporter exited keeps working, and killing a reader mid-I/O tears it
down. No KASAN or lockdep report. GPU removal (the remaining revoke)
is run on hardware by the test added in the third commit.

These runs used the gpu-prio `preempt 0` policy: on this GPU, master's
default CILP/GFXP preemption policy makes cuCtxCreate fail before any
export (the second channel's compute object allocation returns
NV_ERR_INSUFFICIENT_RESOURCES), with or without this series.

* gsp_route: answer GPU_GET_INFO DMABUF_CAPABILITY as kernel RM does

NV2080_CTRL_GPU_INFO_INDEX_DMABUF_CAPABILITY (0x3d) is answered by
NVIDIA's kernel-side RM, not by GSP-RM: subdevice_ctrl_gpu_kernel.c
returns YES when osDmabufIsSupported(). GSP-RM has no dma-buf and
answers NO, and the GA10x routing passed that through. nvdriver exports
dma-bufs itself (NV_ESC_EXPORT_TO_DMABUF_FD), so answer YES like the
kernel-side RM, on every path that answers the index: GSP-RM's V2
reply, the V2 reply a V1 GET_INFO is translated to, an R620-sized V2
query translated to 580 batches, and nvdriver's native GET_INFO_V2
table.

libcuda 580.178.04 queries this index, but on a GeForce laptop GPU it
still reports CU_DEVICE_ATTRIBUTE_DMA_BUF_SUPPORTED=0 afterwards and
never issues the export ioctl: its decision depends on more than this
answer. This only makes the answer correct.

* uvm: export a CUDA allocation as a dma-buf by GPU address

libcuda only exports a dma-buf through cuMemGetHandleForAddressRange,
and on GPUs it reports CU_DEVICE_ATTRIBUTE_DMA_BUF_SUPPORTED=0 for (a
GeForce RTX 3050 Laptop here) it refuses in user space with
CUDA_ERROR_NOT_SUPPORTED, before asking the kernel. The RM handles that
NV_ESC_EXPORT_TO_DMABUF_FD needs live inside libcuda, so an application
cannot call the ioctl itself.

The UVM node knows them: UVM_MAP_EXTERNAL_ALLOCATION maps (hClient,
hMemory, offset) at a GPU virtual address. Record them in each
ExternalMap (and carry them through uvm_ext_gpu_map_split, the piece
after a hole moving its offset along), and add an nvidia_rs ioctl on
the process's own /dev/nvidia-uvm VA-space fd:

  NV_RS_UVM_EXPORT_DMABUF (0x4e520001)
  { u64 va; u64 size; u32 flags; s32 fd; u32 status; s32 rm_fd; }

[va, va + size) must be page aligned and lie inside one external
mapping; flags bit 0 allows a (shared) CPU mmap. The range resolves to
its RM memory and goes through the same export as
NV_ESC_EXPORT_TO_DMABUF_FD (nv_rs_rmapi_export_dmabuf_object(), a single
extent), so it gets the same lifetime (the dma-buf pins the memory)
and the same authorization: the memory's client must belong to rm_fd,
an RM file the caller holds (or to its control file), the way UVM's
rmCtrlFd names it. The UVM mapping is
not enough on its own: UVM_MAP_EXTERNAL_ALLOCATION also accepts objects
shared through NV_ESC_RM_SHARE, which this export does not. If GPUs'
mappings of the range name different memory, the address is ambiguous
and refused. The lookup takes only the UVM lock (it reads this file's VA
space); the export then resolves the memory again under the RM API lock,
so a mapping changed in between exports memory the caller still owns, or
fails. As for NV_ESC_EXPORT_TO_DMABUF_FD, the fd is installed only once
the reply has been copied out.

tools/nv_rs_dmabuf.h wraps it (nv_rs_export_dmabuf(ptr, size, flags,
&status) finds the UVM and RM fds in /proc/self/fd); tools/
cuda_dmabuf_uvm_export_test.c checks that the dma-buf is the
allocation's VRAM (CPU mmap reads what cuMemcpyHtoD wrote and
cuMemcpyDtoH reads what it wrote, whole and for a sub-range), that bad
ranges and private mmaps are refused, that an export whose reply cannot
be copied back leaves no fd, and that the dma-buf keeps a
freed cuMemMap allocation: an existing CPU mapping still reads its
data, and writes through it never reach a new allocation.

On the RTX 3050 Laptop with io_uring + NVMe dma-buf reads (block layer
support from the io_uring dma-buf series in 7.4; ext4 needs out-of-tree
patches, device-mapper is refused), NVMe reads land in VRAM at the speed
they land in host memory on a Gen3 x4 drive (3.2 GB/s), and at ~75% of
it from a Gen4 x4 drive on another root port (5.1 vs 6.8 GB/s).

tools/dmabuf_unbind_race_test.py (run by tools/dmabuf_unbind_race_run.sh)
exercises the GPU-removal revoke from commit 1 through this export: it
unbinds nvidia_rs from the GPU while an io_uring reader keeps 32 NVMe
reads in flight into an exported buffer, another export carries an
unsignaled sw_sync write fence (signaled HOLD seconds into the unbind),
an RM-call loop runs, and an export loop runs. Its io_uring side is fastsafetensors' io_uring
dma-buf layer (IoUring); the export is its own, the ioctl of
tools/nv_rs_dmabuf.h. The reader exports after the
fenced buffer, so the revoke meets the fence first. On the RTX 3050
Laptop with a 5 s hold (three runs), exports were refused from 9-29 ms
into the unbind, every in-flight read completed with -ENODEV by
24-51 ms (the fenced buffer did not keep the reader's readable), RM
calls kept completing without a failure (slowest call 182 ms) while the revoke waited
for the fence, and the GPU teardown under the RM API lock started right
after the fence was signaled. Lockdep stayed on through the run, with no
KASAN or lockdep report.

---------

Co-authored-by: Arsenova <arsenova@a7snv.com>
2026-12-04 23:05:05 -08:00
7e80ce1b46 rmapi/gsp_route: translate R620 NV_CHANNEL_ALLOC_PARAMS so stock 620.x userspace can create CUDA contexts (#519)
* rmapi/gsp_route: translate R620 userspace RM controls to R580 GSP-RM layouts (#504)

* rmapi/gsp_route: translate R620 NV_CHANNEL_ALLOC_PARAMS (hHandleVASpace) for CUDA contexts

* rmapi: select channel alloc ABI from physical file_owner and hook into lockless prepare_alloc

* gsp_bringup: translate R620 channel alloc params on R580 GSP sessions
2026-12-04 21:47:24 -08:00
bbf609abf5 fix(kernel-open): shorten exported framelock symbol for CONFIG_MODVERSIONS and fix C90 warning (#572)
Co-authored-by: Eric Hartford <eric@quixi.ai>
2026-12-04 20:34:59 -08:00
6435d65112 fix(rmapi/modeset): rmmod refcnt leak (#491), modeset RM ops (#466), runtime logs/fw warning (#501) (#513)
* fix(ga10x/rmapi/modeset): R620 control translation, rmmod refcnt, modeset RM ops (#504, #491, #466, #501)

* chore(pr513): drop gsp_route R620 hunk in favor of live-verified #514

* fix(gpu_owner): balance get_task_struct with put_task_struct after kthread_stop

* fix(gpu_owner/irq): wait for runtime worker join & pin/teardown failed runtime IRQ close

Addresses CodeRabbit review findings on PR #513 (and #491/#528):
- gpu_owner.c: Wait for runtime_stopped in a 10s warning loop and always join
  via kthread_stop() + put_task_struct() so an unpinned runtime worker can
  never outlive module text during PCI removal / rmmod.
- irq_adapter.c: When nv_rs_irq_close() fails to quiesce an unpinned
  runtime-kthread IRQ owner, acquire THIS_MODULE before returning the error
  (or force-disable/synchronize/free handlers if the module is already
  unloading so no callback can outlive module text).
- ga10x_events.rs: Check nv_rs_irq_close() status in stop() and restore e.irq
  on failure instead of discarding the handle.
- tests/irq-mock: Cover both live-pin and unloading-force-teardown paths.

* fix(pci,irq): disable PCI INTx on forced IRQ close and bound AER/shutdown runtime stop

Address follow-up review findings on #513:
- In nv_rs_irq_close() forced teardown (unpinned runtime worker after mask
  failure), call pci_intx(owner->pdev, 0) for legacy INTx mode so the
  device stops asserting its level-triggered line without disabling a
  shared IRQ line for other devices, and add an irq-mock regression test.
- Add nv_rs_gpu_owner_runtime_stop_bounded(owner, timeout_ms) preserving
  runtime_task and runtime_stopping on timeout (preventing restart races
  and allowing a later nv_rs_remove() stop to complete the join).
- In nv_rs_shutdown() and nv_rs_aer_error_detected(), call pci_clear_master()
  first for immediate DMA containment, then use a bounded runtime stop so
  shutdown and PCIe AER callbacks never wedge indefinitely.

* fix(pci,pm): bound runtime_lock wait, reclaim retired worker on start/AER, and reassert BME clear

Address follow-up review findings on #513:
- Include runtime_lock acquisition inside nv_rs_gpu_owner_runtime_stop_bounded()'s
  deadline via bounded mutex_trylock() polling so shutdown/AER cannot hang when
  startup holds runtime_lock waiting for runtime_ready.
- Reclaim a retired worker in nv_rs_gpu_owner_runtime_start() via
  nv_rs_gpu_owner_runtime_reclaim_locked() and in nv_rs_aer_resume() so a
  timed-out bounded stop never strands runtime engines unavailable after recovery.
- Reassert pci_clear_master(pdev) after the serialized stop attempt in
  nv_rs_shutdown() and nv_rs_aer_error_detected() so in-flight GPU bring-up
  cannot leave Bus Master enabled.
- Use nv_rs_gpu_owner_runtime_stop_bounded() in PM suspend/runtime_suspend with
  full state rollback on timeout so suspend cannot wedge indefinitely while
  nv_rs_remove() keeps the unconditional join required before module unload.

* fix(pci): keep Bus Master enabled during bounded GSP unload on shutdown

Address final review comment on #513:
- In nv_rs_shutdown(), invoke nv_rs_gpu_owner_runtime_stop_bounded(owner, 10000)
  before pci_clear_master(pdev) so an active GSP session can complete its
  DMA unload RPC during clean shutdown, then clear Bus Master Enable once
  the stop finishes or hits its bounded deadline.

* fix(pci,pm): return DISCONNECT on AER stop timeout and keep full PM suspend stop

Address review findings on #513:
- In nv_rs_aer_error_detected(), return PCI_ERS_RESULT_DISCONNECT rather than
  PCI_ERS_RESULT_NEED_RESET if nv_rs_gpu_owner_runtime_stop_bounded() times
  out, preventing a PCIe slot reset while a live runtime worker could still
  issue MMIO or re-enable Bus Master.
- In nv_rs_pm_do_suspend() and nv_rs_pmops_runtime_suspend(), wait for worker
  retirement via nv_rs_gpu_owner_runtime_stop() before entering D3hot rather
  than half-aborting after modeset suspend and USERD VMA revocation.

---------

Co-authored-by: morebrackets <19673572+morebrackets@users.noreply.github.com>
2026-12-04 19:48:23 -08:00
ff0c7edbc0 feat(nvkms): add exact 580 ABI decoders, handle validation, and honest ledger audit (#517)
- Add exact 580.178.04 ABI Rust decoders/validators and unit tests (69/69)
  in src/nvidia/src/nvkms/mod.rs + kernel FFI exports in modeset_ffi.rs,
  modeset_iface_exports.c, and src/nvidia/Makefile for all remaining NVKMS
  ioctl commands.
- Wire per-command exact 580 ABI + handle validation in
  kernel-open/nvidia-modeset/nvidia_rs_modeset.c, returning honest -EINVAL
  (missing disp/head/framelock/swap-group) or -EOPNOTSUPP for unbacked
  display, framelock, permissions, deferred FIFO, swap-group join/leave/clip,
  and unicast-event handlers rather than fake success.
- Update tools/build_parity_ledger.py to inspect C handler function bodies
  and exclude -EOPNOTSUPP handlers from PORTED (keeping nvkms_ioctls honestly
  at 14 PORTED / 52 PARTIAL).

Co-authored-by: morebrackets <19673572+morebrackets@users.noreply.github.com>
2026-12-04 19:39:58 -08:00
0d9fa023f1 uvm: distinguish map slot exhaustion from host page mapping failures (#503)
Report the failing stage, minor, and completed bytes for external mappings without changing the RM result. Cover both mapping table paths and host DMA and PTE failures in CPU tests.
2026-12-04 18:59:27 -08:00
cb15715316 kernel-open: add opt-in Tegra194 GV11B platform_driver and bus-agnostic rmapi_node registration (#385)
* kernel-open: add opt-in Tegra194 GV11B platform_driver and bus-agnostic rmapi_node registration

* rmapi_node: support platform dev in nv_rs_rmapi_mmap

* platform(gv11b): skip reset_control when Tegra genpd pm_domain owns GPU reset

* kernel-open(gv11b): fault-map and revoke platform BAR IO VMAs on GPU removal

* kernel-open(gv11b): extract rmapi_plat_io.h and test platform BAR VMA revocation in host fixture

* kernel-open(gv11b): propagate and report actual platform DMA mask in proc gpu info

* kernel-open(gv11b): document plat_io pgoff/BDF assumptions and harden !live release

* kernel-open(gv11b): clean up orphaned plat_io mappings on file release

* kernel-open(gv11b): resolve duplicate boot0/dma_bits fields after rebase

* kernel-open(gv11b): gate file_ref_get() on Linux >= 6.13 or NV_RS_HAVE_FILE_REF
2026-12-04 17:03:17 -08:00
72543d1e2e fix(drm): harden DMABUF scanout/export guards and mark nvkms export PORTED (23/24 DRM) (#515)
- Harden nv_rs_fb_create() and nv_rs_crtc_atomic_flush() so imported
  NV_RS_GEM_DMABUF objects always validate single-segment contiguous sgt
  backing and scan out via import_sgt rather than kms_mem.
- Return -EOPNOTSUPP in nv_rs_ioctl_gem_export_nvkms_memory() if the
  export_memory_fd hook is unavailable instead of silently succeeding.
- Validate arguments and import_sgt in nv_rs_ioctl_gem_export_dmabuf_memory()
  and return -EOPNOTSUPP until an RM external DMA-BUF memory wrapper with
  independent attachment lifetime retention exists (avoiding a fake 0x003e
  sysmem allocation or premature drm_prime_gem_destroy on GEM close).
- Update tools/build_parity_ledger.py and docs/PARITY_LEDGER.md to mark
  nv_drm_gem_export_nvkms_memory_ioctl PORTED (backed by RM 0x00003d05)
  and keep nv_drm_gem_export_dmabuf_memory_ioctl honestly PARTIAL (23/24).

Co-authored-by: morebrackets <19673572+morebrackets@users.noreply.github.com>
2026-12-04 17:03:12 -08:00
4035bab737 perf(rmapi): cut nv_rs_rmapi_lock acquisitions in half & eliminate hot ioctl heap allocs (#518)
Co-authored-by: morebrackets <19673572+morebrackets@users.noreply.github.com>
2026-12-04 17:03:05 -08:00
Kev
034d12a8d6 gpu: run GP104 Devinit before framebuffer discovery (#547)
* Run GP104 VBIOS Devinit before framebuffer discovery

Run the stock-derived Devinit sequence on uninitialized Tesla P4 and GTX 1070 cards before the normal Pascal runtime reads VRAM. Extract the signed PMU boot loader from the stock 580.178.04 object and retain DMA if the PMU fails to quiesce.

* Reuse the Pascal firmware pack and recover incomplete GP104 bring-up

* Recover retained GP104 PCI owners and reconcile bus setup on rebind

* Preserve the next driver's bus mastering after a Devinit drain
2026-12-04 17:03:00 -08:00
1f6809b5cb GSP-RM: zero new video memory on GA10x (#555)
Master scrubs new video memory only on GV100. On a GPU that runs GSP-RM
(`ga10x::get`), a new allocation still holds what the last owner wrote.
On a desktop this shows as garbage around the mouse pointer, and one
process can read another one's data.

`Ga10xMem::zero` clears the allocation through the 1:1 BAR1 window, in
pieces of at most 16 MiB. Memory the window does not show (BAR1 shorter
than video memory) stays as it was: the BAR0 window would take too long.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-04 17:02:44 -08:00
c99236627f kernel-open: build with CONFIG_HWMON unset (#509)
hwmon_device_register_with_info() and hwmon_device_unregister() only
exist when CONFIG_HWMON is enabled. Several mainstream distribution
kernels ship it unset -- Debian's cloud-amd64 flavour for one -- and
modpost then fails to resolve both symbols:

  ERROR: modpost: "hwmon_device_register_with_info" undefined!
  ERROR: modpost: "hwmon_device_unregister" undefined!

Compile the hwmon block out when CONFIG_HWMON is unset. The telemetry
view is a convenience over RM data that still exists; losing the view
is preferable to refusing to build. The CONFIG_HWMON=y path is
unchanged, byte for byte.

Tested: builds on 6.12.118+deb13-cloud-amd64 (CONFIG_HWMON unset);
insmod and rmmod both return 0 on the same host, which has no GPU.
Not built against a CONFIG_HWMON=y kernel; that branch is the original
code verbatim under the #if.

Signed-off-by: Mara <Mara@K80.dev>
Co-authored-by: Mara <Mara@K80.dev>
2026-12-04 16:33:14 -08:00
e86d83cc64 fix(kernel-open): define DRM_PLANE_NO_SCALING on Linux <6.1 and fix C90 declaration warning in pci_adapter (#560)
Co-authored-by: Eric Hartford <eric@quixi.ai>
2026-12-04 16:23:47 -08:00
06e61c33fd uvm,tools(gv11b): add 40-bit DMA limit and dev:<idx> + NV_RS_CUDA_ARCH suite support (#439)
* uvm,tools(gv11b): add 40-bit DMA limit and dev:<idx> + NV_RS_CUDA_ARCH suite support

* tools(gv11b): reject empty dev: ordinal and handle integrated prefetch/IPC

* uvm,rmapi(gv11b): wire architecture DMA bit width into runtime negotiation

* tools(gv11b): guard cuMemAdvise on concurrent_managed and preserve non-801 IPC errors

* tools(gv11b): emit managed-access capability and skip flags in parity JSON

* kernel(gv11b): move nv_rs_uvm_dma_bits_for_boot0 to rmapi_node.rs and retain in guest VM build
2026-12-04 16:17:28 -08:00
7951e20683 pmu_bringup: log when the boot-voltage cap lowers a v100_p0_gpc_ndiv request (#447)
* pmu_bringup: log when the boot-voltage cap lowers a v100_p0_gpc_ndiv request

On GV100 (Tesla V100) a `v100_p0_gpc_ndiv` request above 172 is applied
as 172 (1290 MHz) whenever the LOGIC rail was not raised. Nothing said
so: with `v100_p0_gpc_ndiv=204` the only line was "GV100 P0 boost
active: GPC 555.0 -> 1290.0 MHz", which reads like the outcome of the
request, and the parameter still read back 204. The compiled-in default
(190) is capped the same way. Reported in #367.

The cap was two copies of an inline `if req > 172 && !volt_raised`, in
the bring-up path and in the governor tick that re-reads the parameter.
This commit only moves that existing condition; the value 172 and the
applied clock are unchanged. Both sites now go through nv_rs_core:

- `gv100_p0_boost::clamp_p0_gpc_ndiv_for_volt` returns
  `(effective_ndiv, was_clamped)`; the cap is `BOOT_VOLT_MAX_GPC_NDIV`.
- `P0GpcClampNotice::retune` takes the request, the NDIV in effect and
  a callback that performs the clock write, and decides whether to
  write and whether to report. A capped request is reported only once
  the capped clock is in effect: this pass wrote it successfully, or an
  active boost already sits at the cap. A write that fails
  (`P0BoostStatus::NafllNotReady` and the like) is not reported as
  applied and is not remembered, so the retry that succeeds reports it.
  Each capped request is reported once, not once per tick.

The line is printed before the boost line:

  nvidia_rs: GV100 P0 GPC NDIV request capped gpu=0x...: requested 204
  (1530.0 MHz), applied 172 (1290.0 MHz); LOGIC rail is at boot voltage
  (no PMU VOLT scaling)

It is pr_info, next to nv_rs_p0_boost_log and in the same style, because
the default request is capped too and a warning on every default load
would be noise.

The parameter keeps reading back the request. `v100_hbm_ndiv` does the
same across an adaptive backoff, `v100_p0_volt_uv` (read-only, 0444) is
range-limited only in its getter, and one global value cannot show a
per-GPU result when `v100_p0_gpc_ndiv_map` or the rail state differs
per GPU. README says so.

No stock 580.178.04 function is cited because no RM control, register
sequence, struct layout or status code changes.

Tests (host, the clock write is a mock callback):
p0_gpc_request_is_capped_at_boot_voltage_and_reported,
p0_gpc_initial_capped_boost_is_reported_once_and_ticks_do_not_repeat_it,
p0_gpc_failed_retune_is_not_reported_as_applied,
p0_gpc_clamp_is_not_reported_where_no_boost_took_effect.
The C side is one printk wrapper; its callers are compiled out of the
EDU guest build (`cfg(not(nv_rs_edu_guest))`). QEMU EDU guest tests
were not run. Not run on a GPU.

Refs #367

* pmu_bringup: report the live GPC clock in the skipped-retune notice

Review finding on #447. The capped-request notice named the retune
baseline (`applied_gpc_ndiv`) even when no write ran. The thermal guard
and the idle governor lower the hardware GPC clock and update only
`SavedP0State::cur_gpc_ndiv`, so the baseline can be stale: request 190
boosts to 172, a hot tick drops the clock to 160, the request changes
to 204, the write is skipped because the target still equals the
baseline, and the line said "applied 172 (1290.0 MHz)" while the clock
was at 1200 MHz.

`P0GpcRetune::notice_ndiv(live_ndiv)` now picks the NDIV the notice
names: after a successful write, the NDIV just written (unchanged);
when the write was skipped, the live clock from `cur_gpc_ndiv`. The
live value is used for the report only. The write decision still
compares the retune target with the baseline, so a hot tick is not
undone by raising the clock back to the cap.

Test: p0_gpc_skipped_retune_notice_names_the_live_clock (host). Not run
on a GPU; QEMU EDU guest tests not run.

Refs #367

* pmu_bringup: track idle-clock writes in the live GPC clock

Review finding on #447 (round 2). The skipped-retune notice names the
live clock `SavedP0State::cur_gpc_ndiv`, but the idle governor's writes
did not update it except on the transition back to Active. Request 190
boosts to 172, the governor enters LowPower and writes NDIV 74, the
request changes to 204 while still idle, the write is skipped because
the target equals the baseline, and the notice said 172 instead of 74.
The same held when `idle_pstate_gpc_khz` changed while already idle.

`IdlePstateGovernor::tick_tracking_live_ndiv` wraps `tick_with_clock`
and stores every NDIV the governor wrote successfully in the live state:
entering LowPower, re-applying a changed idle clock while in LowPower,
and waking to Active (which replaces the caller's Active-only update).
A failed write leaves it unchanged. The retune baseline
`applied_gpc_ndiv` and the write decision are untouched. The thermal
guard and power cap still read `cur_gpc_ndiv` only while Active, and
the wake to Active sets it to the active clock first, as before.

Test: p0_gpc_skipped_retune_notice_names_the_idle_clock (host) runs the
tick sequence with the real retune, idle governor and boost_gv100_p0
writes on MockGv100; with the live-state store removed it fails with
172 != 74. Not run on a GPU; QEMU EDU guest tests not run.

Refs #367

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* README: say when the capped-request line repeats

retune() logs once per distinct capped request per GPU and re-arms after an
uncapped request, so 'one line per GPU' overstated it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* gpu_owner: don't claim the LOGIC rail stayed at boot voltage in the cap notice

runtime_pmu_volt_init_and_scale returns volt_raised = false when any
VOLT SET step fails, even after earlier steps raised the rail, so the
capped-request line cannot say no scaling happened. Say the cap is active
and the raise was not confirmed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Scott <scottbphone12@gmail.com>
2026-12-04 16:17:22 -08:00
ae09b121df gv100/hbm: log every HBM2 session outcome, not only a verified unlock (#451)
* gv100/hbm: log every HBM2 session outcome, not only a verified unlock

On a CMP 100-210 (10de:1df4, 12 GB) FBPA 0..=3 answer with a PRI bus
error, so survey_gv100_hbm() refuses the card. HbmSession::begin() then
returns FailedRolledBack in state SurveyFailed, and pmu_bringup only
logged the Unlocked case: v100_hbm_ndiv=82 did nothing and dmesg said
nothing. The session is write-inhibited from then on, so a later sysfs
write to v100_hbm_ndiv was dropped without a line as well. A PLL that
would not take the new NDIV and was rolled back was equally silent, and
indistinguishable from the survey failure in HbmUnlockStatus.

Core (hbm_clock.rs):
- survey_gv100_hbm_checked() does the same reads in the same order as
  survey_gv100_hbm() and returns the first failed check as an
  HbmSurveyFault { kind, fbpa, value }: canary mismatch, cfg or coeff
  unreadable, PLL not locked, coeff mismatch. survey_gv100_hbm() is now
  its .ok(); HbmSession keeps the fault of the start survey.
- HbmSession::outcome() names what a start or live step did: Disabled,
  NonStockPll, AlreadyAtTarget, Unlocked, SurveyFailed, RolledBack,
  ClockUnknown, WriteInhibited.

Kernel glue (pmu_bringup.rs, gpu_owner.c): every start outcome other
than Unlocked, every live step that does not end in a verified new
clock, and a sysfs write dropped by a write-inhibited session now go to
nv_rs_hbm_clock_outcome_log(). The survey line carries the partition
and raw word, e.g. "survey failed (FBPA 0 PLL config unreadable
(0xbadf2010))". Requested-but-failed outcomes are pr_warn, an
unverified rollback is pr_err, the rest pr_info. The existing unlock
and backoff lines are unchanged. No register is read or written that
was not read or written before.

This reports the failure; it does not make the survey accept a card
with fused-off FBPAs. The GP100/GA100 MultiGenHbmSession path is not
touched.

Tests (host): hbm_survey_reports_the_first_failed_check and
hbm_session_outcome_names_every_start_and_step_result, the latter with
the #399 register values (FBPA 0..=3 = 0xbadf2010, 4..=15 cfg 0x29,
coeff 0x14102) and a PLL mock that drops or loses lock on a write. On
master they do not compile: HbmOutcome, HbmSurveyFault and
HbmSession::outcome do not exist.

Not run: QEMU EDU guest tests (need sudo here), any GPU.

Refs #399

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

* gv100/hbm: keep the failed phase in the logged HBM2 outcome

Review of #451 found three session results that were logged as something
else. A start or step whose target did not lock, whose rollback was
verified, and whose survey after the rollback then failed was reported as
"the rollback could not be verified". A survey that refused the card
before any PLL write was reported as "did not lock or read back; rolled
back" when the survey after it passed. And a start whose PMC_BOOT_0
canary read failed right after a good baseline survey was reported as
"PLL is not at a stock coefficient".

The unlock and step helpers now hand the session the read that stopped
them before a write, taken from the reads they already do, so the
register access order is unchanged. A refusal before any write puts the
session in SurveyFailed with that fault. A verified rollback followed by
a failed survey is the new outcome RolledBackSurveyLost (8): the clock
stays unknown and writes stay inhibited, and the log names the survey
fault. A failed canary is the new outcome CanaryFailed (9); NonStockPll
is left for a coefficient the unlock really rejected. The public
unlock_gv100_hbm and set_gv100_hbm_ndiv signatures and results are the
same as before.

Three host tests script the failing read with a mock and fail on the
previous commit.

Refs #399

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

* gv100/hbm: keep a canary refusal before the target write out of RolledBack

program_coeff checks the PMC_BOOT_0 canary before it writes the target
coefficient. When that check failed, the caller still ran the rollback
(which rewrites the unchanged baseline), and a verified rollback was then
logged as "did not lock or read back; rolled back", although the target
was never written.

program_coeff now returns the canary fault when it refuses before the
write. unlock_gv100_hbm_noted and set_gv100_hbm_ndiv_noted run the same
rollback as before and pass that fault on, so HbmSession reports the step
as SurveyFailed with the CanaryMismatch fault (the existing "refused
before the target write" path) instead of RolledBack. Register accesses
and their order are unchanged; the public functions keep their
signatures. A host test fails the canary once, just before the target
write, for both the initial unlock and a live step, and checks that the
rollback succeeds and the outcome is SurveyFailed, not RolledBack.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* gv100/hbm: say "target coefficient not written" for a survey refusal

The SurveyFailed log line said "clock not touched". Since a canary
refusal just before the target write is reported as SurveyFailed, and
the rollback in that path still rewrites the unchanged baseline
coefficient, that was true of the clock value but not of every PLL
register write. The line now says "target coefficient not written",
which holds in every SurveyFailed case, and the HbmOutcome::SurveyFailed
doc comment says the same.

Log text and a doc comment only; no change to register access, session
state or outcome mapping.

Refs #399

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* gv100/hbm: classify a refused baseline restoration by its skip reason

outcome() reported Disabled whenever the v100_hbm_ndiv value was 0, but
on_user_write(0) with a surveyed baseline steps to the baseline NDIV; a
non-stock coefficient refuses that with Skipped and no fault, and the log
then said "disabled" instead of the refusal. The session now records the
NDIV each start or step acted on (target_ndiv), and outcome() reserves
Disabled for a zero effective target; its requested_ndiv argument, which
only approximated that, is gone.

Test: start at MDIV 3 / NDIV 65, request 80 (rejected), then 0 (baseline
restore, rejected) -> NonStockPll. It fails if step_to stops recording
the target.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
Co-authored-by: Scott <scottbphone12@gmail.com>
2026-12-04 16:17:10 -08:00
f27e85efe5 ga10x: add gsp_passthru and gsp_primary module overrides (#492)
* ga10x: add gsp_passthru and gsp_primary module overrides

GspSystemInfo.bIsPassthru comes from X86_FEATURE_HYPERVISOR and bIsPrimary
from video_is_primary_device(). On a bare-metal RTX 5080 (GB203) GSP-RM never
sends GSP_INIT_DONE with bIsPassthru=0; forcing it to 1 boots (issue #487).
Both parameters default to -1, which keeps the detected value.

* ga10x: apply the gsp_passthru override on every architecture

The override sat inside #ifdef CONFIG_X86, so gsp_passthru=1 did nothing
on arm64 while the parameter description says 0 or 1 forces the value.
Detection still uses the x86 hypervisor flag. On other architectures the
field stays 0 unless the parameter forces it. The description now states
the detect default.
2026-12-04 16:16:40 -08:00
7f7dce5fa1 nvidia-drm: build against kernels that renamed drm_atomic_state to drm_atomic_commit (#541)
Linux 7.3 renamed the atomic state container to struct drm_atomic_commit,
and the plane and CRTC atomic helper callbacks take the renamed type, so
nvidia_rs_drm.c fails to compile there with eight incompatible-pointer
errors (reported in #533).

Probe the definition in <drm/drm_atomic.h> from compat_probes.mk, as the
other DRM guards do, and use a typedef in the five callbacks. No
behaviour change on either side of the rename.


Claude-Session: https://claude.ai/code/session_01W53iUSBQkEg9aqwF4AoBHi

Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
2026-12-04 16:15:30 -08:00
b8c7680284 kernel-open: probe class_create/devnode signatures (RHEL 9 5.14 build) (#552)
a2707a4 guards class_create(name) and the const-device class.devnode
callback in rmapi_node.c with LINUX_VERSION_CODE >= 6.4 / 6.2. RHEL 9
backports both to 5.14, so the #else branch is taken there and the
module fails to build (-Werror=incompatible-pointer-types, too many
arguments to class_create).

Probe include/linux/device/class.h in compat_probes.mk instead, keeping
the version check as the fallback for unprobed (host-fixture) builds,
and record the guard in docs/KERNEL_COMPAT.md.

Co-authored-by: TheWeakShall <22898767+TheWeakShall@users.noreply.github.com>
2026-12-04 16:15:23 -08:00
9f70f56020 chore: update repository references from QuixiAI/nvdriver to nvdriver/nvdriver (#520)
Co-authored-by: Eric Hartford <eric@quixi.ai>
2026-12-03 21:34:14 -08:00
366b416498 fix(pr383): address CodeRabbit Round-6 PRIME fence and mapper bounds findings
- nvidia_rs_drm.c:
  - Implement legacy 580.178.04 PRIME fence context memory-import path
    (NV_RS_GEM_PRIME_FENCE_CTX) via nv_kms.import_memory_fd (28-byte
    NvKmsKapiImportMemoryParams) / import_memory (8-byte import ID), kernel
    mapping, and 16-byte-stride GPU completion polling with clean teardown,
    keeping SEMSURF import separate.
- gsp_route.rs:
  - Enforce kernel-only permission check (owner == KERNEL_MODESET_OWNER) on
    the early 0x0002_0101 ContextDma update path.
  - Validate full physical backing range and page-rounded virtual span
    (including phys_off & 0xfff) in exec_mm_op MAP before writing PTEs.
  - Chunk unmaps > 4 GiB in unmap_dma_ga10x_no_flush() instead of silently
    capping at 1,048,576 pages.
  - Propagate ST_INVALID_STATE when write_semsurf_value() fails in
    exec_mm_op SEMAPHORE_SIGNAL.
- .coderabbit.yaml:
  - Update comment to match auto_incremental_review: true and
    auto_pause_after_reviewed_commits: 0.
2026-12-03 18:07:34 -08:00
d61030a3e6 fix(pr383): address CodeRabbit Round-5 DRM/GSP/RMAPI review findings
- nvidia_rs_drm.c:
  - Guard identifier-form MODULE_IMPORT_NS(DMA_BUF) with RHEL_RELEASE_CODE.
  - Hold a drm_dev_get/drm_dev_put reference per GEM object across all 6 GEM
    creation paths so nv_dev/kms_dev remain valid until pending SEMSURF fences
    release their GEM contexts.
  - Clear vma->vm_ops and vma->vm_private_data before dma_buf_mmap(), ensure
    VM_DONTEXPAND, and drop the drm_gem_mmap_obj() GEM ref on success.
  - Honor import_mem_nvkms_params_ptr/size in prime_fence_ctx_create via
    nv_kms.semsurf_import (rejecting mismatched/unsupported param sizes and
    out-of-bounds semaphore indices).
  - Separate NV_RS_HAVE_DMA_RESV_RESERVE_FENCES and NV_RS_HAVE_DMA_RESV_ADD_FENCE
    guards in a shared nv_rs_dma_resv_attach_fence() helper.
  - Reject non-contiguous (nents != 1) or undersized imported DMA-BUF scanout
    buffers in nv_rs_fb_create().
- gsp_route.rs:
  - Include page_off in pre_unmap_memory_dma() effective_sz so PTE clearing
    matches Node::unmap_memory_dma() without double-adding page_off.
  - Propagate nonzero set_disp_channel_pushbuf() errors (mapping 0xffff to
    ST_INVALID_STATE) before rm_alloc.
  - Re-export KERNEL_MODESET_OWNER from nv_rs_core and drop dead 0x00da /
    duplicate 0x0080_0201 code.
- gpu.rs:
  - Register userspace 0x05/0x79 OS events under GSP-RM BinaryApi parents via
    self.event() so GSP posted events deliver through events.events, falling
    back to a BinaryApi placeholder only when no host OS-event registration
    applies.
2026-12-03 17:09:42 -08:00
416c8eb9f1 Merge origin/master (a52af77e, PRs #438/#467/#473/#474/#475/#485) into feat/ga102-desktop-master 2026-12-03 16:47:17 -08:00
b52978f2a5 Address round-3 CodeRabbit PR #383 findings (all 12 remaining items) 2026-12-03 16:33:41 -08:00
a52af77e6c feat(drm): implement NVKMS dma-buf import and PRIME fence ioctls (22/24 DRM PORTED) (#485)
* feat(drm): implement remaining 5 DRM GEM/PRIME fence ioctls (24/24 DRM PORTED)

* fix(drm): back dma-buf NVKMS import with dma_buf_mmap, bound PRIME fences, and keep RM export ioctls honest PARTIAL

* fix(drm): clear DRM VMA callbacks before dma_buf_mmap and share imported dma_buf->resv

* fix(drm): pin THIS_MODULE across live PRIME and semsurf dma_fence lifetimes

---------

Co-authored-by: Eric Hartford <eric@quixi.ai>
2026-12-03 16:20:20 -08:00
c5a9dd147d Address round-2 CodeRabbit PR #383 findings across RMAPI, kernel glue, KMS/DRM, and tools 2026-12-03 16:13:36 -08:00
131c220f0b Merge origin/master (b764024f, DRM semsurf fence validators #472) into feat/ga102-desktop-master 2026-12-03 13:18:43 -08:00
b764024fd0 feat(drm): implement semaphore-surface timeline fence ioctls (19/24 DRM PORTED) (#472)
* feat(drm): implement semaphore-surface timeline fence ioctls via dma_fence, sync_file, and dma_resv

* fix(drm): per-fence lock, 64-bit seqno, timeout enforcement, pre_wait_value ordering, unpublished rollback, unload drain, and 5.19 dma_resv boundary

* fix(drm): separate done_link/on_ctx_list, bound pending waits with close() cleanup, and fix exit drain lock discipline

* fix(drm): hold ctx ref across drain_waits and init w->cb.node + sem_closing guard before callback arming

* fix(drm): reap disarmed waits during drain_waits when ctx->sem_closing is set

* fix(drm): probe dma_fence_init64 (6.17+), cap pending fences & timeout, and disarm all fence timers on close/unload

* fix(drm): track timed-out seqno watermark and tear down waits/timers before releasing DRM devices

* fix(drm): queue fence timeout work before releasing publication locks

---------

Co-authored-by: Eric Hartford <eric@quixi.ai>
2026-12-03 13:16:05 -08:00
5a1b9a659e Merge origin/master (ca3d44e3, NVKMS surface FFI #471 + DRM PAGE_SIZE #458) into feat/ga102-desktop-master 2026-12-03 13:10:52 -08:00
ca3d44e31b gv100: live board power from the PMU, groups built from the VBIOS (#136) (#405)
* gv100: live board power from the PMU, groups built from the VBIOS (#136)

On GV100 boards where nothing else reads the INA3221 (seen on SXM2-to-PCIe
adapter boards), nvidia_rs never populated the PMU's PERF/PMGR board-object
groups, so the PMU never sampled board power and `nvidia-smi` showed the
placeholder.

Stock 580.178.04, before its first power read, sends nine BOARDOBJ_GRP_CMD
SETs (PERF unit 0x13: pstates 0x1c, vpstates 0x1b, VFE variables 0x19, VFE
equations 0x1a; PMGR unit 0x18: I2C devices 0x2a, power equations 0x26,
sensors 0x27, devices 0x28, policies 0x29), each after writing its group
into the super-surface, then reads power with a PWR_DEVICE (0x28) copy-out.
No LOAD is involved.

New `gpu::gv100_pmu_tables` builds all nine groups, the twelve requests and
the copy-out region from the card's own VBIOS (BIT 'P' v2 tables and the DCB
I2C table). Every VBIOS read is bounds-checked; a table it does not understand
yields None, never a panic. The kernel side captures the VBIOS before the PMU
starts, sends the built sequence once after PMU bring-up, and the monitor tick
then reads device 0's power through the copy-out when no CPU-side INA3221 was
found, so the existing power governor (`nvidia-smi -pl`) has a real reading.

Opt-in: `v100_pmu_power=1` (default off), GV100 only (PMC_BOOT_0 chip 0x140).

Evidence: [O]. Every mapping was matched against one adapter-board
V100-SXM2-16GB's stock super-surface (read back through BAR2 after a stock
init in a VFIO VM) and its VBIOS: all nine groups byte-identical. Not yet
REA-derived; the fields that are observed constants are marked in the module.
Tests: request and copy-out layouts against the recorded stock requests, bounds
on hostile tables, and (with NV_RS_V100_VBIOS / NV_RS_V100_SURF set; stock
bytes are not in the repo) 0 differing bytes against the stock surface.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* gv100 PMU power: address review (per-GPU state, failure paths, VBIOS bounds)

Per-GPU state: the request buffer, the copy-out shape and the captured VBIOS
move from module statics into `Persist`, initialised in place like the RPC
scratch buffers. Two GPUs no longer share one buffer or one shape, and a
session publishes its shape only after its own sequence completed.

Lifetimes: `cleanup` drops a VBIOS image the bring-up never took (startup
ended early) and clears the shape.

Power read failure: a failed live read (including a reply timeout, after
which the transport refuses later commands as the original does) now turns
power polling off for the session and logs once (stage 8), instead of
issuing a command on every tick.

Boot sequence: a failed copy-out is checked before the 1 s wait and record
read; only completed commands are counted. PROM selection failure on a
GV100 gets its own code (7) so it is logged; a non-GV100 (2) stays silent.

Table builder:
- BIT 'P' pointer slots are read only within the token's declared data size.
- Sparse VFE variable/equation tables (a non-zero type after a type-0 one)
  are refused: the serializers index 0..count, and how stock lays out a
  sparse table is unknown.
- A pstate sub-entry count that would spill past one 0x420 record is refused.
Each has a test; each test fails with its guard removed. The reference
card's nine groups are still 0 bytes different from stock.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* gv100 PMU tables: one PWR_DEVICE reading, a bounds test that reaches the serializers

- pwr_devices() reads the PWR_DEVICE table once (mask, input mask, input
  count); the SET group and the copy-out shape both use it, so they cannot
  disagree. Output on the reference VBIOS is unchanged (0 bytes differ, all
  nine groups).
- writes_stay_inside_each_region now runs 4000 seeded junk VBIOS images whose
  BIT 'P' slots and DCB I2C table point at in-ROM tables, and asserts every
  serializer writes on some input. Dropping the PWR_DEVICE input bound panics
  it; a serializer that never writes fails it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* pmu_bringup: gate the #136 power-path imports outside the EDU guest

gv100_pmu_tables, rom, rom_bit, rom_descriptors and RuntimeVariant are only
used by #[cfg(not(nv_rs_edu_guest))] code, so the guest build
(tools/vm/build_guest_test.sh) warned five unused_imports. They now sit in
their own cfg-gated use; the main import list is back to master's.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Cool3reeze <193058586+Cool3reeze@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 21:33:30 +01:00
fe16cf34e2 feat(nvkms): implement surface lifecycle registry and FFI (14/66 NVKMS PORTED) (#471)
* feat(nvkms): implement surface lifecycle registry and FFI (REGISTER/UNREGISTER/GRANT/ACQUIRE/RELEASE)

* fix(nvkms): validate format, reject userspace skipSync, check plane extent, avoid ID/handle wraparound collisions, and preserve idempotent unregister/release

* fix(nvkms): retain backing dma-buf/RM fd ref until unregister, reject multi-plane formats, and validate format Bpp row pitch

* fix(nvkms): tie backing dma-buf/RM ref lifetime to SurfaceRegistry reap across orphan lifetimes

---------

Co-authored-by: Eric Hartford <eric@quixi.ai>
2026-12-03 12:06:55 -08:00
4e46f44f43 feat(drm): implement GEM_ALLOC_NVKMS_MEMORY, shmem GEM mmap, and host PAGE_SIZE FFI validation (15/24 DRM PORTED) (#458)
* feat(drm): implement GEM_ALLOC_NVKMS_MEMORY, shmem GEM mmap, and host PAGE_SIZE FFI validation

* fix(drm): use probed NV_RS_HAVE_VM_FLAGS_SET / RHEL_RELEASE_CODE / vma_flags_set_word helpers

---------

Co-authored-by: Eric Hartford <eric@quixi.ai>
2026-12-03 10:27:33 -08:00
d96fb792bc Fix test_pci_bridge host fixture and EDU guest_build linker exports 2026-12-03 09:42:18 -08:00
0f8299f438 feat(display,nvkms): VBIOS DCB 4.x board output enumeration (#189) + NVKMS QUERY_DISP/QUERY_FRAMELOCK FFI (11/66 PORTED) (#446)
* feat(display,nvkms): add VBIOS DCB 4.x board output enumeration (#189) + NVKMS QUERY_DISP/QUERY_FRAMELOCK FFI

- Add src/nvidia/src/gpu/display_outputs.rs (BoardOutputs::enumerate,
  validate_heads, connector-table pairing) using existing 580-parity
  rom_dcb decoders, with unit tests for 4-connector consumer boards,
  headless datacenter SKUs, bounds/signature errors, and excess heads
- Wire NVKMS_IOCTL_QUERY_DISP (cmd=2, 172 B) and NVKMS_IOCTL_QUERY_FRAMELOCK
  (cmd=28, 20 B) through live Rust FFI (nv_rs_nvkms_validate_query_disp,
  nv_rs_nvkms_validate_query_framelock) with dedicated per-command unit tests
- Update tools/build_parity_ledger.py and docs/PARITY_LEDGER.md:
  nvkms_ioctls 9 -> 11 PORTED (total 2,551 PORTED / 65 PARTIAL / 0 MISSING)

* fix(display): reject DCB overflow, ignore version-0 connectors, keep zero-count NVKMS queries PARTIAL

* fix(dcb): distinguish 0xe EOL from 0xf skip and match DCB 4.x connector bit layout

---------

Co-authored-by: Eric Hartford <eric@quixi.ai>
2026-12-03 09:33:23 -08:00