use std::ffi::c_void;
use std::ops::{Deref, DerefMut};
use oxicuda_driver::error::{CudaError, CudaResult};
use oxicuda_driver::loader::try_driver;
pub struct PinnedBuffer<T: Copy> {
ptr: *mut T,
len: usize,
}
unsafe impl<T: Copy + Send> Send for PinnedBuffer<T> {}
unsafe impl<T: Copy + Sync> Sync for PinnedBuffer<T> {}
impl<T: Copy> PinnedBuffer<T> {
pub fn alloc(n: usize) -> CudaResult<Self> {
if n == 0 {
return Err(CudaError::InvalidValue);
}
let byte_size = n
.checked_mul(std::mem::size_of::<T>())
.ok_or(CudaError::InvalidValue)?;
let api = try_driver()?;
let mut raw_ptr: *mut c_void = std::ptr::null_mut();
let rc = unsafe { (api.cu_mem_alloc_host_v2)(&mut raw_ptr, byte_size) };
oxicuda_driver::check(rc)?;
if byte_size > 0 {
unsafe {
std::ptr::write_bytes(raw_ptr.cast::<u8>(), 0, byte_size);
}
}
Ok(Self {
ptr: raw_ptr.cast::<T>(),
len: n,
})
}
pub fn from_slice(data: &[T]) -> CudaResult<Self> {
let buf = Self::alloc(data.len())?;
unsafe {
std::ptr::copy_nonoverlapping(data.as_ptr(), buf.ptr, data.len());
}
Ok(buf)
}
#[inline]
pub fn len(&self) -> usize {
self.len
}
#[inline]
pub fn is_empty(&self) -> bool {
self.len == 0
}
#[inline]
pub fn as_ptr(&self) -> *const T {
self.ptr
}
#[inline]
pub fn as_mut_ptr(&mut self) -> *mut T {
self.ptr
}
#[inline]
pub fn as_slice(&self) -> &[T] {
unsafe { std::slice::from_raw_parts(self.ptr, self.len) }
}
#[inline]
pub fn as_mut_slice(&mut self) -> &mut [T] {
unsafe { std::slice::from_raw_parts_mut(self.ptr, self.len) }
}
}
impl<T: Copy> Deref for PinnedBuffer<T> {
type Target = [T];
#[inline]
fn deref(&self) -> &[T] {
self.as_slice()
}
}
impl<T: Copy> DerefMut for PinnedBuffer<T> {
#[inline]
fn deref_mut(&mut self) -> &mut [T] {
self.as_mut_slice()
}
}
impl<T: Copy> Drop for PinnedBuffer<T> {
fn drop(&mut self) {
if let Ok(api) = try_driver() {
let rc = unsafe { (api.cu_mem_free_host)(self.ptr.cast::<c_void>()) };
if rc != 0 {
tracing::warn!(
cuda_error = rc,
len = self.len,
"cuMemFreeHost failed during PinnedBuffer drop"
);
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn alloc_signature_compiles() {
let _: fn(usize) -> CudaResult<PinnedBuffer<f32>> = PinnedBuffer::alloc;
}
#[cfg(feature = "gpu-tests")]
mod gpu_tests {
use super::*;
fn real_context() -> Option<oxicuda_driver::context::Context> {
if oxicuda_driver::init().is_err()
|| oxicuda_driver::device::Device::count().unwrap_or(0) == 0
{
return None;
}
let dev = oxicuda_driver::device::Device::get(0).ok()?;
oxicuda_driver::context::Context::new(&dev).ok()
}
#[test]
fn alloc_is_zero_initialized() {
let Some(_ctx) = real_context() else {
eprintln!("skipping: no CUDA driver/device");
return;
};
let Ok(buf) = PinnedBuffer::<u8>::alloc(4096) else {
eprintln!("skipping: alloc failed");
return;
};
assert_eq!(buf.len(), 4096);
assert!(buf.as_slice().iter().all(|&b| b == 0));
}
#[test]
fn from_slice_round_trips() {
let Some(_ctx) = real_context() else {
eprintln!("skipping: no CUDA driver/device");
return;
};
let data: Vec<f32> = (0..64).map(|i| i as f32).collect();
let Ok(buf) = PinnedBuffer::from_slice(&data) else {
eprintln!("skipping: alloc failed");
return;
};
assert_eq!(&*buf, data.as_slice());
}
}
}