28 Commits

Author SHA1 Message Date
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
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
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
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
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
63c8309915 Merge origin/master and address CodeRabbit finding in destroy_gpu_va_space
- Resolve conflicts in hwmon_adapter.c, src/nvidia/Makefile, gsp_route.rs,
  rmapi_node.rs, and uvm_node.rs (preserving both #350 security/UVM/hwmon
  checks and master's #266/#349/#360 additions).
- In uvm_node::destroy_gpu_va_space, retain the page tree on any failed
  set_vaspace_page_directory(..., None) across all builds (not only GA10x)
  and flush GPU TLB before tree.destroy() on success.
2026-12-03 04:23:44 +00:00
1d0e760c57 uvm_node: hold rmapi_node_lock around cleanup and cancel_work_sync after unlock 2026-12-02 23:13:34 +00:00
ab028d8835 uvm_node: schedule workqueue drain outside mmap_lock when vma_closed trylock contends 2026-12-02 22:59:35 +00:00
797cbcbf71 Merge origin/master into feat/rust-lifecycle-cleanup-142 2026-12-02 13:26:57 -08:00
b0ea314202 fix(gpu,uvm): harden RC/MIG/RDMA lifecycle, thermal/power math, ctxsw GPU-lost, and UVM node checks
- src/nvidia/src/gpu/rc_recovery.rs:
  - RowRemapperTable::mark_row_for_remap: detect duplicate pending (0x3f) / reserved (0x40) rows before checking table capacity, report accurate bank_used_rows, and clamp count/max_entries to entries.len().
  - PcieAerTracker::on_error_detected: do not increment correctable_count or mutate state when both uncorr_status and corr_status are 0.
  - KernelMigManager: reuse freed GI/CI slots, populate compute_instance_mask, enforce cumulative GPC budget across CIs within a GI, and add destroy_compute_instance() / destroy_gpu_instance() (rejecting busy GIs with NV_ERR_STATE_IN_USE 0x63 and reclaiming used_mem_slices and active_swizzle_mask so MIG mode can be cleanly disabled).
  - GpuDirectRdmaRegistry::dma_map_pages: use checked arithmetic for page offset/address calculation and roll back dma_mapped and partial dma_addrs on failure.
- src/nvidia/src/gpu/thermal_power.rs:
  - PowerCapGovernor::tick: widen (ndiv_span * avail_mw) / span_mw to u64 to avoid u32 overflow on high-TDP GPUs under overflow-checks=yes.
  - PowerPolicyState::apply_control_0x38 and FanPolicyState::{compute_pwm_hi, curve_pct}: guard min/max clamp ordering and widen temperature delta math to i64.
- src/nvidia/src/gpu/ctxsw_dump.rs:
  - Add is_gpu_lost() (0xffff_ffff readback detection) and exclude GPU-lost from is_pgraph_busy().
- kernel-open/nvidia/uvm_node.c:
  - Guard against NULL file->private_data with -EBADFD in nv_rs_uvm_ioctl (matching mmap/release/vma_close).
  - Add smp_wmb() before WRITE_ONCE in nv_rs_uvm_write64 (matching nv_rs_uvm_write32 for GPU PTE/PDE ordering).
2026-12-02 01:06:44 -08:00
3904da442d rmapi/uvm: drain UvmCpuDmaLedger per-device mappings in a single O(B+N) pass
Addresses follow-up CodeRabbit review on PR #201:
- Replace repeated bucket-0 rescans in `UvmCpuDmaLedger::pop_for_dev` with
  single-pass `detach_for_dev()` (which unlinks all matching device entries
  into a caller-owned intrusive chain in one O(UVM_DMA_BUCKETS + N) pass)
  plus O(1) `pop_detached()` slot recycling.
- Update `nv_rs_uvm_unmap_gpu_dev` to detach once under the lock and unmap/put
  each detached record outside the lock in O(1) per record.
2026-12-01 23:05:20 -08:00
4c30b692c4 rmapi/uvm: move sysmem page pool and UVM CPU-DMA table out of C into Rust (#142)
Continues #142 by removing the last manual Linux linked lists and hash tables from
kernel-open/nvidia/rmapi_node.c and kernel-open/nvidia/uvm_node.c:

1. Rust-owned system-memory page pool (SysmemPagePool in alloc_registry.rs):
   - Replaces LIST_HEAD(nv_rs_sysmem_pool), nv_rs_sysmem_pool_pages, LIST_HEAD(reclaim),
     list_add/list_del_init/list_move, and <linux/list.h> in rmapi_node.c.
   - O(1) ring-deque semantics preserving LIFO hot-cache pops (pop_hot) and FIFO oldest-page
     reclaim (pop_cold_for_trim), with lock-free AtomicU64 length snapshot for budget checks
     and OOM-safe fallback to __free_page(page).

2. Rust-owned UVM CPU-to-DMA mapping registry (UvmCpuDmaLedger in alloc_registry.rs):
   - Replaces DEFINE_HASHTABLE(nv_rs_uvm_cpu_dma_ht, 10), struct nv_rs_uvm_cpu_dma_entry,
     per-entry kmalloc/kfree, HLIST_HEAD(dead) teardown lists, and <linux/hashtable.h> in
     uvm_node.c.
   - Switches nv_rs_uvm_cpu_dma_lock to a leaf mutex (all callers are sleepable process
     context that already called kmalloc(GFP_KERNEL) / dma_map_page), allowing growable
     KernelVec storage while performing dma_unmap_page / put_page / put_device outside locks.

3. Unit tests & verification:
   - Host unit tests covering SysmemPagePool LIFO/FIFO ordering, wraparound repack, and
     UvmCpuDmaLedger concurrent insert races, page-free, hot-unplug, and exit drain (7/7 PASS).
   - cargo fmt --all -- --check, cargo clippy -- -D warnings, make modules,
     tools/check_kernel_module.py PASS.
   - QEMU EDU + QEMU EDU --iommu guest tests PASS.
   - Live GA107M (RTX 3050 Mobile) VFIO KVM guest: full CUDA/UVM/VMM/Graph/2x-multiproc
     smoke PASS + clean rmmod with zero slab/page leaks.

Refs #142
2026-12-01 22:20:34 -08:00
d5e0b9bb87 Wave 7A: Proactive P0 lock/UAF fixes and kernel build/compat hardening
Cluster 2 (RMAPI/UVM/Locking/Memory P0s):
- Convert runtime_start_users to atomic_t so wait_event() in
  nv_rs_rmapi_node_gpu_remove never calls mutex_lock while !TASK_RUNNING.
- Guard all 6 unlocked nv_rs_alloc_reg_find() call sites in rmapi_node.c with
  nv_rs_rmapi_alloc_lock.
- Run nv_rs_rmapi_rc_recover_fault while nv_rs_rmapi_lock is held from
  nv_rs_rmapi_node_trylock() in nv_rs_uvm_fault_work_fn (no blocking re-lock).
- Filter MANAGED_RANGES and PAGE_TREES by UvmFile owner in uvm_node.rs to
  prevent cross-process managed_unmap UAF; use flush_gpu_tlb_trylock() +
  TLB_FLUSH_PENDING deferral so .mmap/vm_ops->close never touch LIVE_ENGINES
  without nv_rs_rmapi_lock.
- Pin FD-exported memory backings in memory::Table::export_pins and check via
  shared backing_shares_resource() so export -> free original -> import never
  UAFs; release orphaned backings on FD owner close.
- Fix Backing::System map_protection(flags), deduplicate video_allocated_bytes,
  and unmap Backing::Register in drop_mappings.

Cluster 4 (Kernel Build Hygiene & Linux 5.15-7.3 Compat P0s):
- Factor shared kernel-open/compat_probes.mk for Kbuild + build_guest_test.sh
  (fixing Linux 5.15 char *date probe and Linux 7.0+ guest_build).
- Extend tools/prepare_kernel_archive.py to strip all kernel-exported
  compiler_builtins mem/string members (strlen/memcpy/memmove/memset/memcmp/bcmp)
  and wire it into tools/vm/build_guest_test.sh.
- Fix tools/check_kernel_module.py no_unhardened_sls_return to check per-ret
  int3 succession instead of file-wide has_int3.
- Set AR=llvm-ar / NM=llvm-nm under LLVM=1 in utils.mk, LC_ALL=C and non-rustup
  fallback in verify_rust_guest.py/check_native_codegen.py, and 1024 MiB guest RAM.

Validated: cargo fmt/clippy/test (958+2), test_gate_cases.py (24/24),
test_kernel_archive.py (5/5), NV_RS_KERNEL_IBT=0 & 1 make modules +
check_kernel_module.py (largest_stack=1000), QEMU EDU verify_rust_guest.py.
2026-12-02 01:34:46 +00:00
c65b7c440c uvm_node: take the RM API lock before the UVM lock
nv_rs_uvm_ioctl() and nv_rs_uvm_release() took nv_rs_uvm_lock and then
nv_rs_rmapi_lock. Two other orders already exist:

  rmapi -> mmap_lock   nv_rs_rmapi_os_lock_user_pages() calls
                       pin_user_pages_fast() with the RM API lock held
                       (NV01_MEMORY_SYSTEM_OS_DESCRIPTOR, cudaHostRegister)
  mmap_lock -> uvm     the kernel calls nv_rs_uvm_mmap() and
                       nv_rs_uvm_vma_close() with mmap_lock held

so uvm -> rmapi closes a cycle. lockdep reports it as soon as a CUDA
process pins host memory while another thread mmaps the UVM node, and a
multi-threaded process can really deadlock on it:

  WARNING: possible circular locking dependency detected
  cuda_dmabuf_exp/4377 is trying to acquire lock:
   (&mm->mmap_lock){++++}-{4:4}, at: gup_fast_fallback+0x51f/0x2bc0
  but task is already holding lock:
   (nv_rs_rmapi_lock){+.+.}-{4:4}, at: nv_rs_rmapi_ioctl+0x64c/0x2f50
  Chain exists of:
    &mm->mmap_lock --> nv_rs_uvm_lock --> nv_rs_rmapi_lock

Take the RM API lock first in both places. Nothing under the RM API lock
takes the UVM lock (only the UVM file operations and module init/exit
do), so the order is now rmapi -> mmap_lock -> uvm everywhere. The fault
worker only trylocks, so it could not deadlock, but it now tries the two
locks in the same order as well.

The other way out would be to pin the pages before taking the RM API
lock in the OS-descriptor path; this keeps the change local to the UVM
node.

Observed on an RTX 3050 Laptop (GA107) under a lockdep kernel
(7.4.0-rc2) running a CUDA dma-buf test.
2026-12-02 07:27:28 +08:00
c553930fd7 wave 1: kernel/ARM64/Clang/DKMS compat, IOMMU/PCI lifecycle, and RMAPI/UVM isolation
Proactive 100% parity Wave 1 (REA-grounded vs stock 580.178.04):
- Kernel/build compat: Kbuild header probes for timer_delete_sync, vm_flags_set,
  vma_flags_set_word; remove broken UTS_UBUNTU_RELEASE_ABI guard on
  pci_resize_resource; guard x86 set_memory_uc/wb under CONFIG_X86; remove
  illegal ARM64 dma_sync_single_* on coherent DMA; gate nvidia_rs_drm on
  CONFIG_DRM; default LD=ld.lld/OBJCOPY=llvm-objcopy under LLVM=1; fix dkms.conf
  (KDIR support, all 4 modules, 0.2.0) and install.sh (all 4 modules, non-0000
  PCI domains, KREL override).
- IOMMU & PCI lifecycle: switch gsp_route error notifier to per-device DMA
  (nv_rs_rmapi_os_page_dma); add PCI .shutdown (pci_clear_master + udelay(1))
  and AER .err_handler; keep freed rmapi_allocs on list until users==0 for
  hot-unplug DMA teardown; drain nv_rs_uvm_cpu_dma_ht on exit; lock BAR0 fill
  under p->access; raise MAX_BRIDGE_GPUS to 32.
- Security & isolation (REA _nv000655rm / _nv000663rm): enforce cross-process
  share policy on NV_ESC_RM_DUP_OBJECT & NV_ESC_RM_SHARE; refcount shared memory
  backings on release (eliminating dup UAF); scope UVM ManagedFaultMapper by
  faulting GPU & SysmemPageTree.owner; pass real task_tgid_vnr into Caller.pid.
2026-12-01 16:16:09 +00:00
61f6529bf6 GA102 (RTX 3090) on GSP-RM 580.178.04 in MIT Rust; split-RM routing; RM events
The C port (ga102_gsp.c, ga102_rm.c, ga102_glue.c) is replaced by Rust under src/nvidia/ with a thin MIT C adapter:

- src/nvidia/src/gpu/ga10x_gsp.rs (core, no unsafe): VBIOS / FWSEC / Booter parsing with every offset
  bounds-checked, signature choice from the fuse version, FWSEC DMEM patch (FRTS, SB), FB and WPR2 layout, radix3,
  LibOS arguments, queue headers, element framing and checksum, system info, registry, static info. Unit tests use
  the 3090's numbers.
- src/nvidia/src/gpu/gsp_ucode.rs: GA10x bootloader and Booter Load/Unload from NVIDIA's MIT bindata at 580.178.04
  (licenses/gsp-rm-boot-ga102-mit.txt).
- src/nvidia/kernel/ga10x_gsp.rs: the live boot (FWSEC-FRTS, Booter Load, RISC-V bootloader, LibOS, CPU sequencer,
  INIT_DONE), the RPC transport on GSP-RM's shared-memory queues, and the unload (UNLOADING_GUEST_DRIVER,
  FWSEC-SB, Booter Unload; falcons reset before any DMA memory is freed).
- src/nvidia/kernel/ga10x.rs: per-GPU state and RM RPCs. The slot table publishes a GPU with a release store only
  after every field is written (FREE -> BOOTING -> ACTIVE -> ENDING); readers acquire; a second boot of the same
  GPU backs off. This replaces install_external_session and its publication race.
- src/nvidia/kernel/ga10x_mem.rs, ga10x_objects.rs: the kernel side of split RM (heap split, BAR1 1:1, VA spaces,
  TSG, ctxshare, channel, golden context, work submit token, time correlation).
- src/nvidia/kernel/ga10x_events.rs: RM events through irq_adapter (GA10x MSI; GV100 chained around
  LIVE_IRQ_OPS), posted from the IRQ thread.
- src/nvidia/kernel/gsp_route.rs: routing of the client's RM calls, with NVIDIA's control flags enforced (INTERNAL
  refused, PRIVILEGED needs admin, kernel-only refused, parameter size, owner).
- kernel-open/nvidia/ga10x_adapter.c: log lines, sleep, PCI info and config, BAR0 fill, CPU clocks, credentials,
  three module parameters: ga10x_gsp (default 1; 0 leaves GA10x to gsp_bringup's own path), ga10x_events,
  gsp_route_trace.

rmapi/gpu.rs: the usermode window (0xc561) is allowed on GA10x too; c9c4706 allowed the class but not the window.

Tested on an RTX 3090 + V100: CUDA on both, P2P both ways, NCCL all_reduce over P2P, blocking sync through RM
events, NVIDIA's 580 back after every unload, 0 Xid.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 10:01:46 +01:00
5a02e03a79 Merge pull request #16 from morebrackets/fix/v100-16gb-iommu-irq-linux7
Fix 16GB V100 VRAM sizing, strict IOMMU DMA, IRQ deadlock, and Linux 7.0 build
2026-11-30 20:00:37 -05:00
33ff608a88 Add MIT LICENSE and unify repository SPDX/Cargo/module licensing
- Add root LICENSE (MIT License, Copyright (c) 2026 QuixiAI / Eric Hartford).
- Set license = "MIT" in workspace Cargo.toml and member crates (zero non-MIT dependencies).
- Update all kernel-open/ and tests/vm/ SPDX headers to MIT and EXPORT_SYMBOL_GPL -> EXPORT_SYMBOL.
- Use MODULE_LICENSE("Dual MIT/GPL") in Linux .ko modules so Linux modpost permits linking against the kernel's own EXPORT_SYMBOL_GPL symbols while keeping the repository source 100% MIT.

Closes #12.
2026-12-01 00:20:02 +00:00
caef37fa93 kernel: add RHEL 9.8+ (5.14) compat guards, firmware install, boot kit, and driver_version= param
Cherry-picked and adapted from PR #9 onto master:
- RHEL 9.8+ backport guards: #ifndef PCI_IRQ_INTX in irq_adapter.c, RHEL_RELEASE_CODE in vm_flags_set/clear (rmapi_node.c, uvm_node.c) and DMA_BUF namespace import (dmabuf_p2p.c). (nano_timer_adapter.c container_of() and rom_fw_adapter.c MAX_PAGE_ORDER were already landed on master.)
- install.sh: install extracted target/firmware/nvidia-rs/*/*.fw packs into /lib/firmware before depmod.
- contrib/rhel-5.14-boot/: boot persistence setup for RHEL 9 (modprobe/dracut/udev/systemd/nodes.sh), with empty-vs-wildcard pci_target guard in nodes.sh.
- driver_version= module parameter (default 580.178.04): overrides /proc/driver/nvidia/version, NV_ESC_CHECK_VERSION_STR, and RM 0x101/0x13e identity replies at load time so hosts running newer 580.x userspace (e.g. driver_version=580.196.07) work without breaking 580.178.04 parity.

Co-authored-by: Gaël STEPHAN <gstephan@wyplay.com>
2026-12-01 00:09:44 +00:00
6a1a63e8bc Close DMA publish/remove and UVM page-unmap teardown races
Recheck that the GPU device is still live under nv_rs_rmapi_alloc_lock before inserting a new DMA record in nv_rs_rmapi_os_page_dma(), and hold a struct page reference across each cached UVM CPU-to-DMA mapping until after dma_unmap_page() completes.
2026-11-30 11:25:52 -08:00
bf60e3a72e Harden raw BAR1 dmabuf export, unmap DMA on GPU removal, and fix 6.3/pipefail checks
Require CAP_SYS_ADMIN for NV_RS_ESC_EXPORT_TO_DMABUF_FD now that RMAPI nodes are 0666, unmap retained RMAPI and UVM DMA mappings in nv_rs_rmapi_node_gpu_remove() before PCI teardown, bump the nv_vma_start_write() guard to Linux 6.4+ (6.3 doesn't have vma_start_write), and switch bind_dev_nodes.sh from lsmod|grep to /sys/module checks so pipefail SIGPIPE can't bypass the stock-driver guard.
2026-11-30 11:15:49 -08:00
2c09a6b64b Address review feedback on DMA mask, fault mapping, and PMA cursor
Route the 47-bit DMA mask negotiation in rmapi_node.c and uvm_node.c through nv_rs_pci_negotiate_dma() under p->access so active DMA leases and dma_bits stay consistent. Also require the faulting GPU's own page tree to map before returning Mapped in ManagedFaultMapper, and keep set_gpu_pma_base() monotonic on re-registration.
2026-11-30 10:58:06 -08:00
87a26a2aee Support 0x2080a61d power limit query and non-root /dev/nvidia* access
btop queries nvmlDeviceGetPowerManagementLimit, which hits RM control 0x2080a61d and was falling through to NOT_SUPPORTED. Wire it up next to 0x2080a61f to return the 300W limit.

Also switch the RMAPI and UVM misc devices to mode 0666 (matching stock /dev/nvidia*) and add a small bind-mount helper (wired optionally via BIND_DEV_NODES=1 in install.sh) so tools like btop, nvidia-smi, and non-root services can use nvidia_rs directly without a mount namespace.
2026-11-30 10:53:36 -08:00
2d90287ede Fix 16GB V100 VRAM sizing, strict IOMMU DMA, IRQ top-half deadlock, and Linux 7.0 build
Tested on 4x Tesla V100-SXM2-16GB (Dell PowerEdge C4130) running Ubuntu
7.0.0-44-generic with Intel VT-d enabled (no iommu=pt).

Fixes #2 and a few other things that showed up once 16GB cards came up:

- Derive the GV100 runtime VRAM window, RMAPI VideoRegion ceiling, NVENC
  ucode staging address, and UVM descriptor/PMA base from the real FB size
  in placement::Placement::usable instead of hardcoding 32 GiB constants.
  Also pass the detected VRAM size through fb_info_v2_with_usable so
  cards with a smaller BAR1 still report the right total memory.

- Switch LiveEngine::irq_top_half, live_irq_mask, and live_irq_unmask to
  the lockless nv_rs_pci_{read,write}32_irq helpers. Using the normal
  nv_rs_pci_{read,write}32 path acquires p->access inside hardirq context
  and self-deadlocks when an IRQ lands on the same CPU running
  irq_thread_service.

- DMA-map sysmem pages per GPU instead of putting raw physical addresses
  in GPU page tables and rings: lazy per-GPU dma_map_page for RMAPI
  allocations and CPU-mapped UVM semaphore/managed pages, dma_alloc_coherent
  for SysmemPageTree and the replayable fault ring, and a live coherent
  flush page in 0x100c10 across ACR load/runtime/unload so SYS_MEMBAR does
  not hit stale unmapped IOVAs left behind by stock nvidia.ko.

- Add version-guarded compatibility wrappers for Linux 6.3-7.0 API changes
  (noop_llseek, vm_flags_set/clear, PCI_IRQ_INTX, timer_container_of,
  hrtimer_setup, MAX_PAGE_ORDER, MODULE_IMPORT_NS("DMA_BUF"), and
  drm_driver.date).

Verified with cargo fmt/clippy/test (918 passed), make modules +
check_kernel_module.py (10/10, largest_stack 1000), native-hello,
uvm-replayable-fault-test, 4-GPU cuda-multigpu-parity (matches stock
580.178.04), and llama-bench on 1 and 4 GPUs with zero DMAR faults and
clean unbind/rmmod.
2026-11-30 10:53:36 -08:00
4472b75ccd Follow-up to PR #10/#11: auto-gate IBT flags, fix RUSTC fallback & section-reloc gate, align stock 580.178.04 compat/FOLL_LONGTERM
- utils.mk: search ~/.cargo/bin in rustup lookup and fall back to ~/.cargo/bin/rustc; auto-gate -Z cf-protection=branch -C jump-tables=no on CONFIG_X86_KERNEL_IBT=y (overridable via NV_RS_KERNEL_IBT=0/1).
- rust-toolchain.toml: restore default stable 1.100.0 (IBT kernels build with RUSTUP_TOOLCHAIN=nightly-2026-11-29).
- tools/check_kernel_module.py: resolve section-symbol relocation targets against disassembled function-entry addresses (avoiding false mid-function failures on valid .text+<entry_off> relocs) and enforce the x86 endbr64 gate when IBT is configured or emitted.
- Stock 580.178.04 parity: omit .llseek across fops (matching nv.c/uvm.c), use container_of() in nano_timer_adapter.c (matching nv-timer.h), use #if defined(MAX_PAGE_ORDER) in rom_fw_adapter.c (matching nv-linux.h), and pass FOLL_LONGTERM in nv_rs_rmapi_os_lock_user_pages (matching os-mlock.c).
- Docs: remove scratch docs/HISTORY.md and update docs/KERNEL_COMPAT.md.
2026-11-30 17:19:30 +00:00
91ef1e1b6f vm_flags be const from 6.3 — five writes now use the helpers, ye blind bilge rats
- Boundary proven by fetching mm.h at the tags: vm_flags_set/vm_flags_clear absent at v6.2, present at v6.3, and the running 7.3.6 kernel has them. rmapi_node.c x4 and uvm_node.c x1 take the helpers on the >=6.3 side, plain |= / &= below.
- Reads be untouched: a const member is still readable, so vm_get_page_prot(vma->vm_flags) and the shared_rw test stand as they was.
2026-11-30 17:39:55 +01:00
c55ca81524 Guard the dead no_llseek for kernels >= 6.12 — the mangy symbol is two years six feet under
- The kernel took no_llseek out tree-wide in cb787f4ac0c2 (v6.12, 2024-09-27); the 7.3.6-gentoo build choked on the dead name, same as the in-tree drivers mechanically scrubbed.
- All 5 file_operations llseek initializers in kernel-open (diagnostic.c, gpu_owner.c, uvm_node.c, rmapi_node.c x2) now take no_llseek on kernels < 6.12 and noop_llseek on >= 6.12, with <linux/version.h> pulled in.
- Boundary proven from the kernel git itself + headers at the tags: 868941b14441 (v6.0) turned no_llseek into #define NULL, cb787f4ac0c2 (v6.12) took the name out. noop_llseek survived and is what in-tree DRM/accel use.
- Galley scroll docs/KERNEL_COMPAT.md + mast pointer line, per the chart law.
- The lseek behavior difference (noop_llseek returns f_pos, old side failed with -ESPIPE) is documented in the scroll — no silent semantics smuggled aboard.

Apply PR #7 review: UVM node keeps stock -ESPIPE, docs stop lying about seek mode

- uvm_node.c ≥6.12 branch: noop_llseek -> NULL. Verified stock 580.178.04 uvm.c uvm_fops carries NO llseek callback, so stock lseek() be -ESPIPE; noop_llseek returned f_pos — a bloody parity break against the exact-parity law. NULL keeps -ESPIPE because fs/open.c clears FMODE_LSEEK for nodes with NULL llseek (verified at the v6.12 tag and the running 7.3.6 kernel).
- docs/KERNEL_COMPAT.md: the behavior difference applies ONLY to nodes whose open path leaves seek mode enabled. The diagnostic node and both RMAPI nodes call nonseekable_open() in their open callbacks (diagnostic.c:78, rmapi_node.c:740,800), so they keep returning -ESPIPE on ≥6.12 — the old blanket claim was a lie. The GPU open node (open_gpu clears no seek mode) be the only node where lseek succeeds on ≥6.12.
- Other kernel branches unchanged, as the review asked.

GPU open node keeps stock -ESPIPE: kill the lie that stock used no_llseek

- gpu_owner.c >=6.12 branch: noop_llseek -> NULL. Stock ground truth at tag 580.178.04 (kernel-open/nvidia/nv.c:236 nvidia_fops) carries NO .llseek field at all -> NULL -> FMODE_LSEEK cleared at open -> lseek() = -ESPIPE, on every kernel version. Tags 470.256.02/535.104.05/550.144.03 show zero llseek references, so stock never had a llseek handler. Our noop_llseek there made lseek() SUCCEED (returns f_pos) — a real parity break, and CodeRabbit let it slide because it only looked at the handler name, not the open path. open_gpu clears no seek mode, so the handler actually runs.
- Retracted: 'U no_llseek' in reports/kernel-module-codegen-validation.json is OUR OWN module's undefined-symbol list, not stock evidence. No blob-level proof exists on this box: nv-kernel.o_binary is not shipped in the repo, no stock nvidia*.ko under /lib/modules/7.3.6-gentoo, and reports/original-live-init-pt-3/runtime-code/kcore covers only 2 PT_LOAD segments (0xffffffffaea00000+0x1003000, 0xffffffffc03a0000+0x25bc000) — nvidia_fops at 0xffffffffc7858ee0 falls outside, so the struct bytes can't be read. Only kallsyms proves the symbol exists in the live module.
- Docs seek-mode law rewritten: noop_llseek may only be used where seek mode is already disabled (the three nonseekable_open() nodes); nodes leaving FMODE_LSEEK set (uvm_node.c, gpu_owner.c) must take NULL. Verified mechanism: fs/open.c:969 clears FMODE_LSEEK for NULL llseek at v6.12; vfs_llseek returns -ESPIPE when the mode is clear and dereferences the handler only when set; on v5.15 no_llseek is the fallback for a NULL handler. no_llseek (NULL since v6.0) and NULL be behaviorally identical, so the pre-6.12 side be untouched as the review asked.
2026-11-30 17:39:55 +01:00
4b6a77d90f Clean-room Rust NVIDIA 580.178.04 driver: GV100 0-diff parity (8-GPU PyTorch/NCCL/llama.cpp, H.264+HEVC NVDEC/NVENC, 2,096/2,096 RM controls, stock UVM/modeset bridges, artificial restrictions unlocked) 2026-11-27 20:45:30 +00:00