use std::ffi::c_void;
use std::marker::PhantomData;
use std::mem::size_of;
use oxicuda_driver::error::CudaResult;
use oxicuda_driver::ffi::CUdeviceptr;
use oxicuda_driver::loader::try_driver;
pub struct MappedBuffer<T: Copy> {
host_ptr: *mut T,
device_ptr: CUdeviceptr,
len: usize,
_phantom: PhantomData<T>,
}
unsafe impl<T: Copy + Send> Send for MappedBuffer<T> {}
unsafe impl<T: Copy + Sync> Sync for MappedBuffer<T> {}
impl<T: Copy> MappedBuffer<T> {
pub fn alloc(n: usize) -> CudaResult<Self> {
let api = try_driver()?;
let byte_size = n.saturating_mul(size_of::<T>());
let mut raw_ptr: *mut c_void = std::ptr::null_mut();
oxicuda_driver::error::check(unsafe {
(api.cu_mem_alloc_host_v2)(&mut raw_ptr, byte_size)
})?;
let host_ptr = raw_ptr.cast::<T>();
let mut device_ptr: CUdeviceptr = 0;
let result = oxicuda_driver::error::check(unsafe {
(api.cu_mem_host_get_device_pointer_v2)(&mut device_ptr, raw_ptr, 0)
});
if let Err(e) = result {
unsafe { (api.cu_mem_free_host)(raw_ptr) };
return Err(e);
}
if byte_size > 0 {
unsafe {
std::ptr::write_bytes(raw_ptr.cast::<u8>(), 0, byte_size);
}
}
Ok(Self {
host_ptr,
device_ptr,
len: n,
_phantom: PhantomData,
})
}
#[inline]
pub fn len(&self) -> usize {
self.len
}
#[inline]
pub fn is_empty(&self) -> bool {
self.len == 0
}
#[inline]
pub fn byte_size(&self) -> usize {
self.len * size_of::<T>()
}
#[inline]
pub fn as_device_ptr(&self) -> CUdeviceptr {
self.device_ptr
}
#[inline]
pub fn as_host_ptr(&self) -> *const T {
self.host_ptr
}
#[inline]
pub fn as_host_ptr_mut(&mut self) -> *mut T {
self.host_ptr
}
pub fn as_host_slice(&self) -> &[T] {
unsafe { std::slice::from_raw_parts(self.host_ptr, self.len) }
}
pub fn as_host_slice_mut(&mut self) -> &mut [T] {
unsafe { std::slice::from_raw_parts_mut(self.host_ptr, self.len) }
}
}
impl<T: Copy> Drop for MappedBuffer<T> {
fn drop(&mut self) {
if self.host_ptr.is_null() {
return;
}
if let Ok(api) = try_driver() {
unsafe { (api.cu_mem_free_host)(self.host_ptr.cast::<c_void>()) };
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn alloc_signature_compiles() {
let _: fn(usize) -> CudaResult<MappedBuffer<f32>> = MappedBuffer::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) = MappedBuffer::<u8>::alloc(4096) else {
eprintln!("skipping: alloc failed");
return;
};
assert_eq!(buf.len(), 4096);
assert!(buf.as_host_slice().iter().all(|&b| b == 0));
}
#[test]
fn device_ptr_is_nonzero_and_host_writes_visible() {
let Some(_ctx) = real_context() else {
eprintln!("skipping: no CUDA driver/device");
return;
};
let Ok(mut buf) = MappedBuffer::<f32>::alloc(64) else {
eprintln!("skipping: alloc failed");
return;
};
assert_ne!(buf.as_device_ptr(), 0);
for (i, v) in buf.as_host_slice_mut().iter_mut().enumerate() {
*v = i as f32;
}
let expected: Vec<f32> = (0..64).map(|i| i as f32).collect();
assert_eq!(buf.as_host_slice(), expected.as_slice());
}
}
}