mirror of
https://github.com/QuixiAI/nvdriver.git
synced 2026-12-06 06:28:39 +00:00
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>
409 lines
14 KiB
Rust
409 lines
14 KiB
Rust
//! Linux coherent DMA backend for core::dma::Manager. Context creation requires
|
|
//! a valid owned PCI lease or, for platform GPUs (Tegra194 GV11B), a live
|
|
//! driver-bound `struct device`; no adapter is constructed from a userspace
|
|
//! address.
|
|
use core::{ffi::c_void, ptr::NonNull};
|
|
use nv_rs_core::dma::{Backend, BackendError, Backing, DeviceMapping};
|
|
#[repr(C)]
|
|
#[derive(Clone, Copy, Default)]
|
|
struct RawBacking {
|
|
token: u64,
|
|
cpu_token: u64,
|
|
bytes: u64,
|
|
alignment: u64,
|
|
coherent: u32,
|
|
reserved: u32,
|
|
}
|
|
#[repr(C)]
|
|
#[derive(Clone, Copy, Default)]
|
|
struct RawMapping {
|
|
token: u64,
|
|
address: u64,
|
|
bytes: u64,
|
|
}
|
|
unsafe extern "C" {
|
|
fn nv_rs_dma_read_word(
|
|
ctx: *mut c_void,
|
|
b: *const RawBacking,
|
|
m: *const RawMapping,
|
|
offset: u64,
|
|
value: *mut u32,
|
|
) -> i32;
|
|
fn nv_rs_dma_write_word(
|
|
ctx: *mut c_void,
|
|
b: *const RawBacking,
|
|
m: *const RawMapping,
|
|
offset: u64,
|
|
value: u32,
|
|
) -> i32;
|
|
fn nv_rs_dma_cpu_ptr(
|
|
ctx: *mut c_void,
|
|
b: *const RawBacking,
|
|
m: *const RawMapping,
|
|
cpu_out: *mut *mut c_void,
|
|
bytes_out: *mut u64,
|
|
) -> i32;
|
|
fn nv_rs_dma_flush_sysmem(context: *mut c_void, backing: *const RawBacking) -> i32;
|
|
|
|
fn nv_rs_dma_context_create(pci: *mut c_void, bits: u32, result: *mut *mut c_void) -> i32;
|
|
fn nv_rs_dma_context_create_dev(dev: *mut c_void, bits: u32, result: *mut *mut c_void) -> i32;
|
|
fn nv_rs_dma_read(
|
|
ctx: *mut c_void,
|
|
backing: *const RawBacking,
|
|
offset: u64,
|
|
destination: *mut u8,
|
|
bytes: u64,
|
|
) -> i32;
|
|
fn nv_rs_dma_write(
|
|
ctx: *mut c_void,
|
|
backing: *const RawBacking,
|
|
offset: u64,
|
|
source: *const u8,
|
|
bytes: u64,
|
|
) -> i32;
|
|
fn nv_rs_dma_context_close(ctx: *mut c_void) -> i32;
|
|
fn nv_rs_dma_context_force_close(ctx: *mut c_void, freed: *mut u32) -> i32;
|
|
fn nv_rs_dma_context_leaked(ctx: *mut c_void);
|
|
fn nv_rs_dma_allocate(
|
|
ctx: *mut c_void,
|
|
bytes: u64,
|
|
alignment: u64,
|
|
result: *mut RawBacking,
|
|
) -> i32;
|
|
fn nv_rs_dma_map(ctx: *mut c_void, backing: *const RawBacking, result: *mut RawMapping) -> i32;
|
|
fn nv_rs_dma_unmap(
|
|
ctx: *mut c_void,
|
|
backing: *const RawBacking,
|
|
mapping: *const RawMapping,
|
|
) -> i32;
|
|
fn nv_rs_dma_release(ctx: *mut c_void, backing: *const RawBacking) -> i32;
|
|
fn nv_rs_dma_sync_device(
|
|
ctx: *mut c_void,
|
|
backing: *const RawBacking,
|
|
mapping: *const RawMapping,
|
|
offset: u64,
|
|
bytes: u64,
|
|
) -> i32;
|
|
fn nv_rs_dma_sync_cpu(
|
|
ctx: *mut c_void,
|
|
backing: *const RawBacking,
|
|
mapping: *const RawMapping,
|
|
offset: u64,
|
|
bytes: u64,
|
|
) -> i32;
|
|
}
|
|
fn status(code: i32) -> Result<(), BackendError> {
|
|
if code == 0 {
|
|
Ok(())
|
|
} else {
|
|
Err(BackendError(code))
|
|
}
|
|
}
|
|
fn backing(b: &Backing) -> RawBacking {
|
|
RawBacking {
|
|
token: b.token,
|
|
cpu_token: b.cpu_token,
|
|
bytes: b.bytes,
|
|
alignment: b.alignment,
|
|
coherent: u32::from(b.coherent),
|
|
reserved: 0,
|
|
}
|
|
}
|
|
fn mapping(m: &DeviceMapping) -> RawMapping {
|
|
RawMapping {
|
|
token: m.token,
|
|
address: m.address,
|
|
bytes: m.bytes,
|
|
}
|
|
}
|
|
const EINVAL: i32 = -22;
|
|
const ENODEV: i32 = -19;
|
|
const EIO: i32 = -5;
|
|
/// Owns a C context holding its PCI lease or device reference. Use
|
|
/// Manager::shutdown, then close. Dropping it open frees nothing: outstanding
|
|
/// mappings must not be freed implicitly, because the device may still reach
|
|
/// them. The drop reports the leak (allocations and the PCI lease or device
|
|
/// reference stay) in the kernel log.
|
|
pub struct LinuxDma {
|
|
context: Option<NonNull<c_void>>,
|
|
}
|
|
impl Drop for LinuxDma {
|
|
fn drop(&mut self) {
|
|
if let Some(context) = self.context.take() {
|
|
unsafe { nv_rs_dma_context_leaked(context.as_ptr()) };
|
|
}
|
|
}
|
|
}
|
|
pub struct CloseFailure {
|
|
pub error: BackendError,
|
|
pub backend: LinuxDma,
|
|
}
|
|
impl LinuxDma {
|
|
/// # Safety
|
|
/// `pci` must be a live driver-owned nv_rs_pci lease, with negotiated DMA mask,
|
|
/// serialized against concurrent removal/configuration. It is never a GPU
|
|
/// currently bound to another driver. C acquires its own lease reference.
|
|
/// The caller separately keeps this module's code alive until close (GPU
|
|
/// lease, active driver callback, or exit-joined owner); PCI krefs do not.
|
|
pub unsafe fn from_owned_pci(pci: *mut c_void, bits: u32) -> Result<Self, BackendError> {
|
|
unsafe {
|
|
if pci.is_null() {
|
|
return Err(BackendError(EINVAL));
|
|
}
|
|
let mut raw = core::ptr::null_mut();
|
|
status(nv_rs_dma_context_create(pci, bits, &mut raw))?;
|
|
Self::from_raw(raw)
|
|
}
|
|
}
|
|
/// # Safety
|
|
/// `dev` must be a live `struct device` of a platform GPU bound to this
|
|
/// driver, with its DMA masks already negotiated and wide enough for
|
|
/// `bits`. C takes its own `get_device` reference, dropped on close. There
|
|
/// is no removal tracking: the owner closes the context before unbinding.
|
|
/// The caller keeps this module's code alive until close.
|
|
pub unsafe fn from_device(dev: *mut c_void, bits: u32) -> Result<Self, BackendError> {
|
|
unsafe {
|
|
if dev.is_null() {
|
|
return Err(BackendError(ENODEV));
|
|
}
|
|
let mut raw = core::ptr::null_mut();
|
|
status(nv_rs_dma_context_create_dev(dev, bits, &mut raw))?;
|
|
Self::from_raw(raw)
|
|
}
|
|
}
|
|
fn from_raw(raw: *mut c_void) -> Result<Self, BackendError> {
|
|
Ok(Self {
|
|
context: Some(NonNull::new(raw).ok_or(BackendError(EIO))?),
|
|
})
|
|
}
|
|
/// # Safety
|
|
/// Caller must establish exclusive CPU ownership of the range or a verified
|
|
/// GPU-coherent protocol. No concurrent device writes may race this copy;
|
|
/// CPU/device barriers alone do not drain in-flight work.
|
|
pub unsafe fn read_backing(
|
|
&mut self,
|
|
b: &Backing,
|
|
offset: u64,
|
|
destination: &mut [u8],
|
|
) -> Result<(), BackendError> {
|
|
unsafe {
|
|
status(nv_rs_dma_read(
|
|
self.context()?,
|
|
&backing(b),
|
|
offset,
|
|
destination.as_mut_ptr(),
|
|
destination.len() as u64,
|
|
))
|
|
}
|
|
}
|
|
/// # Safety
|
|
/// No GPU walker/engine may read or write the range concurrently unless an
|
|
/// architecture-specific publication protocol proves the transition safe.
|
|
/// Keep backing pinned throughout and complete required TLB work afterward.
|
|
pub unsafe fn write_backing(
|
|
&mut self,
|
|
b: &Backing,
|
|
offset: u64,
|
|
source: &[u8],
|
|
) -> Result<(), BackendError> {
|
|
unsafe {
|
|
status(nv_rs_dma_write(
|
|
self.context()?,
|
|
&backing(b),
|
|
offset,
|
|
source.as_ptr(),
|
|
source.len() as u64,
|
|
))
|
|
}
|
|
}
|
|
/// Single aligned device-shared coherent word access, without a DMA barrier.
|
|
/// # Safety
|
|
/// Caller retains the mapping and establishes a device-specific ownership
|
|
/// protocol. It must issue an acquire barrier after a valid header and a
|
|
/// release barrier before publishing consumption; the mutex is not DMA sync.
|
|
/// These operations sleep and are not usable in hardirq context.
|
|
pub unsafe fn read_shared_word(
|
|
&self,
|
|
b: &Backing,
|
|
m: &DeviceMapping,
|
|
offset: u64,
|
|
) -> Result<u32, BackendError> {
|
|
unsafe {
|
|
let mut value = 0;
|
|
status(nv_rs_dma_read_word(
|
|
self.context()?,
|
|
&backing(b),
|
|
&mapping(m),
|
|
offset,
|
|
&mut value,
|
|
))?;
|
|
Ok(value)
|
|
}
|
|
}
|
|
/// # Safety
|
|
/// Same device protocol and retained mapping requirements as read_shared_word.
|
|
/// The producer must no longer access this word until consumer publication.
|
|
pub unsafe fn write_shared_word(
|
|
&self,
|
|
b: &Backing,
|
|
m: &DeviceMapping,
|
|
offset: u64,
|
|
value: u32,
|
|
) -> Result<(), BackendError> {
|
|
unsafe {
|
|
status(nv_rs_dma_write_word(
|
|
self.context()?,
|
|
&backing(b),
|
|
&mapping(m),
|
|
offset,
|
|
value,
|
|
))
|
|
}
|
|
}
|
|
/// Returns the direct kernel virtual address and byte size of a mapped coherent backing
|
|
/// so hot ring-buffer polling can use volatile loads/stores without locking the DMA context.
|
|
///
|
|
/// # Safety
|
|
/// Caller must clear the returned pointer before unmapping or releasing `b`, and must supply
|
|
/// appropriate acquire/release fences around device-shared ring pointers.
|
|
pub unsafe fn shared_cpu_ptr(
|
|
&self,
|
|
b: &Backing,
|
|
m: &DeviceMapping,
|
|
) -> Result<(*mut u8, usize), BackendError> {
|
|
unsafe {
|
|
let mut cpu = core::ptr::null_mut();
|
|
let mut bytes = 0u64;
|
|
status(nv_rs_dma_cpu_ptr(
|
|
self.context()?,
|
|
&backing(b),
|
|
&mapping(m),
|
|
&mut cpu,
|
|
&mut bytes,
|
|
))?;
|
|
if cpu.is_null() {
|
|
return Err(BackendError(EIO));
|
|
}
|
|
Ok((cpu.cast::<u8>(), bytes as usize))
|
|
}
|
|
}
|
|
/// Actual CPU full publication fence on a retained coherent mapping. This
|
|
/// does not touch payload bytes, invalidate GPU caches or complete GPU work.
|
|
pub fn flush_backing(&self, b: &Backing) -> Result<(), BackendError> {
|
|
status(unsafe { nv_rs_dma_flush_sysmem(self.context()?, &backing(b)) })
|
|
}
|
|
fn context(&self) -> Result<*mut c_void, BackendError> {
|
|
self.context
|
|
.map(NonNull::as_ptr)
|
|
.ok_or(BackendError(ENODEV))
|
|
}
|
|
pub fn close_in_place(&mut self) -> Result<(), BackendError> {
|
|
let context = self.context()?;
|
|
status(unsafe { nv_rs_dma_context_close(context) })?;
|
|
self.context = None;
|
|
Ok(())
|
|
}
|
|
/// Frees every allocation the context still holds and closes it; returns
|
|
/// how many were freed. For a context whose `close` failed.
|
|
/// # Safety
|
|
/// The device must no longer be able to reach system memory: bus
|
|
/// mastering is off (and was confirmed off) or the device is gone. A
|
|
/// device that can still write through an address of this context
|
|
/// writes into freed pages afterwards.
|
|
pub unsafe fn force_close(&mut self) -> Result<u32, BackendError> {
|
|
unsafe {
|
|
let context = self.context()?;
|
|
let mut freed = 0;
|
|
status(nv_rs_dma_context_force_close(context, &mut freed))?;
|
|
self.context = None;
|
|
Ok(freed)
|
|
}
|
|
}
|
|
pub fn close(mut self) -> Result<(), CloseFailure> {
|
|
match self.close_in_place() {
|
|
Ok(()) => Ok(()),
|
|
Err(error) => Err(CloseFailure {
|
|
error,
|
|
backend: self,
|
|
}),
|
|
}
|
|
}
|
|
}
|
|
impl Backend for LinuxDma {
|
|
fn allocate(&mut self, bytes: u64, alignment: u64) -> Result<Backing, BackendError> {
|
|
let mut raw = RawBacking::default();
|
|
status(unsafe { nv_rs_dma_allocate(self.context()?, bytes, alignment, &mut raw) })?;
|
|
Ok(Backing {
|
|
token: raw.token,
|
|
cpu_token: raw.cpu_token,
|
|
bytes: raw.bytes,
|
|
alignment: raw.alignment,
|
|
coherent: raw.coherent == 1,
|
|
})
|
|
}
|
|
fn map(&mut self, b: &Backing) -> Result<DeviceMapping, BackendError> {
|
|
let mut raw = RawMapping::default();
|
|
status(unsafe { nv_rs_dma_map(self.context()?, &backing(b), &mut raw) })?;
|
|
Ok(DeviceMapping {
|
|
token: raw.token,
|
|
address: raw.address,
|
|
bytes: raw.bytes,
|
|
})
|
|
}
|
|
fn sync_for_device(
|
|
&mut self,
|
|
b: &Backing,
|
|
m: &DeviceMapping,
|
|
o: u64,
|
|
n: u64,
|
|
) -> Result<(), BackendError> {
|
|
status(unsafe { nv_rs_dma_sync_device(self.context()?, &backing(b), &mapping(m), o, n) })
|
|
}
|
|
fn sync_for_cpu(
|
|
&mut self,
|
|
b: &Backing,
|
|
m: &DeviceMapping,
|
|
o: u64,
|
|
n: u64,
|
|
) -> Result<(), BackendError> {
|
|
status(unsafe { nv_rs_dma_sync_cpu(self.context()?, &backing(b), &mapping(m), o, n) })
|
|
}
|
|
fn unmap(&mut self, b: &Backing, m: &DeviceMapping) -> Result<(), BackendError> {
|
|
status(unsafe { nv_rs_dma_unmap(self.context()?, &backing(b), &mapping(m)) })
|
|
}
|
|
fn release(&mut self, b: &Backing) -> Result<(), BackendError> {
|
|
status(unsafe { nv_rs_dma_release(self.context()?, &backing(b)) })
|
|
}
|
|
}
|
|
const _: () = assert!(core::mem::size_of::<RawBacking>() == 40);
|
|
const _: () = assert!(core::mem::size_of::<RawMapping>() == 24);
|
|
|
|
impl nv_rs_core::dma::CpuAccessBackend for LinuxDma {
|
|
fn read_cpu(
|
|
&mut self,
|
|
access: nv_rs_core::dma::CpuAccess<'_>,
|
|
offset: u64,
|
|
destination: &mut [u8],
|
|
) -> Result<(), BackendError> {
|
|
// Manager alone constructs this permit after checking both pin counts.
|
|
unsafe { self.read_backing(access.backing(), offset, destination) }
|
|
}
|
|
fn write_cpu(
|
|
&mut self,
|
|
access: nv_rs_core::dma::CpuAccess<'_>,
|
|
offset: u64,
|
|
source: &[u8],
|
|
) -> Result<(), BackendError> {
|
|
unsafe { self.write_backing(access.backing(), offset, source) }
|
|
}
|
|
}
|
|
|
|
impl nv_rs_core::dma::SystemMemoryBackend for LinuxDma {
|
|
fn flush_system_memory(
|
|
&mut self,
|
|
access: nv_rs_core::dma::CpuAccess<'_>,
|
|
) -> Result<(), BackendError> {
|
|
status(unsafe { nv_rs_dma_flush_sysmem(self.context()?, &backing(access.backing())) })
|
|
}
|
|
}
|