* 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>