use std::{mem::replace, ptr, sync::Arc};
use singe_core::report_cleanup_failure;
use singe_cuda_sys::runtime;
use crate::{
context::Context,
error::Result,
memory::{DeviceMemory, MemoryPool},
stream::Stream,
try_ffi,
types::DevicePtr,
view::{AllocationId, DeviceRegion, DeviceRegionProvider},
};
#[derive(Debug)]
pub(crate) enum DeviceDeallocation {
Immediate,
StreamOrdered {
stream: Stream,
pool: Option<MemoryPool>,
},
}
#[derive(Debug)]
pub(crate) struct DeferredFree {
pointer: *mut u8,
context: Arc<Context>,
_pool: Option<MemoryPool>,
}
unsafe impl Send for DeferredFree {}
unsafe impl Sync for DeferredFree {}
impl DeferredFree {
pub(crate) fn enqueue(&self, stream: runtime::cudaStream_t) -> Result<()> {
self.context.bind()?;
unsafe { try_ffi!(runtime::cudaFreeAsync(self.pointer.cast(), stream)) }
}
}
#[derive(Debug)]
pub struct DeviceAllocation {
pub(crate) id: AllocationId,
pub(crate) context: Arc<Context>,
pub(crate) ptr: *mut u8,
pub(crate) bytes: usize,
pub(crate) deallocation: DeviceDeallocation,
}
unsafe impl Send for DeviceAllocation {}
unsafe impl Sync for DeviceAllocation {}
impl DeviceAllocation {
pub(crate) fn from_parts(
context: &Arc<Context>,
ptr: *mut u8,
bytes: usize,
deallocation: DeviceDeallocation,
) -> Arc<Self> {
Arc::new(Self {
id: AllocationId::create(),
context: Arc::clone(context),
ptr,
bytes,
deallocation,
})
}
#[must_use]
pub const fn id(&self) -> AllocationId {
self.id
}
#[must_use]
pub fn context(&self) -> &Arc<Context> {
&self.context
}
#[must_use]
pub fn as_device_ptr(&self) -> DevicePtr {
unsafe { DevicePtr::from_raw(self.ptr.cast()) }
}
#[must_use]
pub const fn byte_len(&self) -> usize {
self.bytes
}
#[must_use]
pub fn stream(&self) -> Option<&Stream> {
match &self.deallocation {
DeviceDeallocation::Immediate => None,
DeviceDeallocation::StreamOrdered { stream, .. } => Some(stream),
}
}
#[must_use]
pub fn pool(&self) -> Option<&MemoryPool> {
match &self.deallocation {
DeviceDeallocation::Immediate => None,
DeviceDeallocation::StreamOrdered { pool, .. } => pool.as_ref(),
}
}
pub(crate) fn release(&mut self) -> Result<()> {
if self.ptr.is_null() {
return Ok(());
}
match &self.deallocation {
DeviceDeallocation::Immediate => {
self.context.bind()?;
unsafe {
DeviceMemory::<u8>::free(&self.context, self.ptr)?;
}
self.ptr = ptr::null_mut();
Ok(())
}
DeviceDeallocation::StreamOrdered { stream, pool } => {
let free = DeferredFree {
pointer: replace(&mut self.ptr, ptr::null_mut()),
context: Arc::clone(&self.context),
_pool: pool.clone(),
};
stream.defer_free(free)
}
}
}
}
unsafe impl DeviceRegionProvider for DeviceAllocation {
fn region(&self) -> DeviceRegion<'_> {
let region =
unsafe { DeviceRegion::from_raw_parts(&self.context, self.id, self.ptr, self.bytes) }
.expect("invalid device allocation metadata");
self.stream().map_or(region, |stream| {
unsafe { region.with_stream(stream) }.expect("allocation stream context mismatch")
})
}
}
impl Drop for DeviceAllocation {
fn drop(&mut self) {
if let Err(error) = self.release() {
report_cleanup_failure("release", "cuda device allocation", &error);
}
}
}