use std::fmt;
use std::sync::Arc;
use cudarc::driver::{CudaContext, DriverError, PinnedHostSlice};
use oxidelake_core::{BackendKind, EngineError, HOST_ALIGN};
use crate::host::{HostAlloc, PinnedProvider};
fn driver_error(err: DriverError) -> EngineError {
EngineError::device(BackendKind::Cuda, err.to_string())
}
pub struct PinnedBuf {
slice: PinnedHostSlice<u8>,
len: usize,
ctx: Arc<CudaContext>,
}
impl PinnedBuf {
pub fn alloc(ctx: &Arc<CudaContext>, len: usize) -> Result<Self, EngineError> {
let mut slice = unsafe { ctx.alloc_pinned::<u8>(len.max(1)) }
.map_err(|e| EngineError::allocation(len, HOST_ALIGN, e.to_string()))?;
slice.as_mut_slice().map_err(driver_error)?.fill(0);
Ok(Self {
slice,
len,
ctx: Arc::clone(ctx),
})
}
pub const fn len(&self) -> usize {
self.len
}
pub const fn is_empty(&self) -> bool {
self.len == 0
}
pub fn as_slice(&self) -> Result<&[u8], EngineError> {
Ok(&self.slice.as_slice().map_err(driver_error)?[..self.len])
}
pub fn as_mut_slice(&mut self) -> Result<&mut [u8], EngineError> {
let len = self.len;
Ok(&mut self.slice.as_mut_slice().map_err(driver_error)?[..len])
}
pub const fn raw(&self) -> &PinnedHostSlice<u8> {
&self.slice
}
pub const fn raw_mut(&mut self) -> &mut PinnedHostSlice<u8> {
&mut self.slice
}
pub const fn context(&self) -> &Arc<CudaContext> {
&self.ctx
}
}
impl fmt::Debug for PinnedBuf {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("PinnedBuf")
.field("len", &self.len)
.field("device", &self.ctx.ordinal())
.finish()
}
}
#[derive(Debug)]
pub struct CudaPinnedProvider {
ctx: Arc<CudaContext>,
}
impl CudaPinnedProvider {
pub fn new(ctx: Arc<CudaContext>) -> Self {
Self { ctx }
}
}
impl PinnedProvider for CudaPinnedProvider {
fn alloc_pinned(&self, len: usize) -> Result<HostAlloc, EngineError> {
Ok(HostAlloc::from_pinned(PinnedBuf::alloc(&self.ctx, len)?))
}
}