mod copy;
mod raw;
use std::{
marker::PhantomData,
mem::{MaybeUninit, replace},
ptr,
result::Result as StdResult,
sync::Arc,
};
use singe_cuda_sys::runtime;
use crate::{
context::Context,
error::{Error, Result},
ipc::IpcMemoryHandle,
memory::{DeviceAllocation, DeviceDeallocation, MemoryCopyKind, StreamOrderedFree, transfer},
stream::{AsStream, Stream, StreamBinding, StreamScope},
submission::{Access, AccessMode},
try_ffi,
types::DevicePtr,
utility::checked_bytes,
view::{
AllocationId, AnyBitPatternDeviceRepr, DeviceOutput, DeviceRange, DeviceRegion,
DeviceRegionProvider, DeviceRepr, NoUninitDeviceRepr, ZeroableDeviceRepr, cast_length,
},
};
impl<T> DeviceMemory<T> {
pub unsafe fn from_raw(raw: RawDeviceMemory<T>) -> Result<Self> {
let RawDeviceMemory {
ptr,
len,
context,
stream_ordered,
} = raw;
let bytes = checked_bytes::<T>(len, "byte length")?;
if bytes != 0 && ptr.is_null() {
return Err(Error::null_pointer("device memory"));
}
let deallocation = match stream_ordered {
None => DeviceDeallocation::Immediate,
Some(StreamOrderedFree { stream, pool }) => {
if stream.context() != &context {
return Err(Error::StreamContextMismatch);
}
DeviceDeallocation::StreamOrdered { stream, pool }
}
};
Ok(Self {
allocation: DeviceAllocation::from_parts(&context, ptr.cast(), bytes, deallocation),
ptr,
length: len,
_phantom: PhantomData,
})
}
pub fn into_raw(self) -> StdResult<RawDeviceMemory<T>, Self> {
let Self {
allocation,
ptr,
length,
..
} = self;
match Arc::try_unwrap(allocation) {
Ok(mut allocation) => {
let context = Arc::clone(allocation.context());
allocation.ptr = ptr::null_mut();
let stream_ordered =
match replace(&mut allocation.deallocation, DeviceDeallocation::Immediate) {
DeviceDeallocation::Immediate => None,
DeviceDeallocation::StreamOrdered { stream, pool } => {
Some(StreamOrderedFree { stream, pool })
}
};
Ok(RawDeviceMemory {
ptr,
len: length,
context,
stream_ordered,
})
}
Err(allocation) => Err(Self {
allocation,
ptr,
length,
_phantom: PhantomData,
}),
}
}
#[must_use]
pub fn into_uninit(self) -> DeviceMemory<MaybeUninit<T>> {
let Self {
allocation,
ptr,
length,
..
} = self;
DeviceMemory {
allocation,
ptr: ptr.cast(),
length,
_phantom: PhantomData,
}
}
pub fn create_uninit(
context: &Arc<Context>,
length: usize,
) -> Result<DeviceMemory<MaybeUninit<T>>>
where
T: DeviceRepr,
{
let () = T::LAYOUT;
DeviceMemory::<MaybeUninit<T>>::allocate(context, length)
}
pub fn zeroed(context: &Arc<Context>, length: usize) -> Result<Self>
where
T: ZeroableDeviceRepr,
{
let mut memory = Self::create_uninit(context, length)?;
memory.set_zeroes()?;
Ok(unsafe { memory.assume_init() })
}
pub fn filled(context: &Arc<Context>, length: usize, value: u8) -> Result<Self>
where
T: AnyBitPatternDeviceRepr,
{
let mut memory = Self::create_uninit(context, length)?;
memory.set_value(value)?;
Ok(unsafe { memory.assume_init() })
}
pub fn from_slice(context: &Arc<Context>, v: &[T]) -> Result<Self>
where
T: DeviceRepr,
{
let () = T::LAYOUT;
unsafe { Self::from_slice_unchecked(context, v) }
}
pub unsafe fn from_slice_unchecked(context: &Arc<Context>, v: &[T]) -> Result<Self> {
let memory = DeviceMemory::<MaybeUninit<T>>::allocate(context, v.len())?;
if !v.is_empty() {
unsafe {
transfer::copy_synchronous(
memory.ptr.cast::<T>(),
v.as_ptr(),
v.len(),
MemoryCopyKind::HostToDevice,
None,
)?;
}
}
Ok(unsafe { memory.assume_init() })
}
pub unsafe fn from_slice_async(v: &[T], stream: &Stream) -> Result<Self> {
let memory = DeviceMemory::<MaybeUninit<T>>::allocate(stream.context(), v.len())?;
let mut mem = unsafe { memory.assume_init() };
unsafe {
mem.copy_from_host_async(v, stream)?;
}
Ok(mem)
}
#[must_use]
pub const fn len(&self) -> usize {
self.length
}
#[must_use]
pub const fn is_empty(&self) -> bool {
self.length == 0
}
#[must_use]
pub fn byte_len(&self) -> usize {
checked_bytes::<T>(self.length, "byte length").expect("device memory byte length overflow")
}
#[must_use]
pub const fn as_ptr(&self) -> *const T {
self.ptr
}
#[must_use]
pub const fn as_mut_ptr(&self) -> *mut T {
self.ptr
}
#[must_use]
pub const fn as_device_ptr(&self) -> DevicePtr {
unsafe { DevicePtr::from_raw(self.ptr.cast()) }
}
#[must_use]
pub fn context(&self) -> &Arc<Context> {
self.allocation.context()
}
#[must_use]
pub fn allocation(&self) -> &Arc<DeviceAllocation> {
&self.allocation
}
#[must_use]
pub fn into_bytes(self) -> DeviceMemory<u8>
where
T: NoUninitDeviceRepr,
{
let () = T::LAYOUT;
let length = self.byte_len();
DeviceMemory {
allocation: self.allocation,
ptr: self.ptr.cast(),
length,
_phantom: PhantomData,
}
}
pub fn cast<U: AnyBitPatternDeviceRepr>(self) -> StdResult<DeviceMemory<U>, Self>
where
T: NoUninitDeviceRepr,
{
let () = T::LAYOUT;
let Ok(length) = cast_length::<U>(self.region()) else {
return Err(self);
};
Ok(DeviceMemory {
allocation: self.allocation,
ptr: self.ptr.cast(),
length,
_phantom: PhantomData,
})
}
fn bind(&self) -> Result<()> {
self.context().bind()
}
fn bind_stream(&self, stream: &Stream) -> Result<()> {
if self.context() != stream.context() {
return Err(Error::StreamContextMismatch);
}
self.bind()
}
pub fn set_zeroes(&mut self) -> Result<()>
where
T: ZeroableDeviceRepr,
{
let context = Arc::clone(self.context());
let _access = context.acquire_host_access(&[self.region()])?;
self.bind()?;
let () = T::LAYOUT;
if self.length == 0 {
return Ok(());
}
unsafe {
Self::set(self.context(), self.ptr, 0, self.length)?;
}
StreamBinding::Default(Arc::clone(self.context())).synchronize()
}
pub fn set_value(&mut self, value: u8) -> Result<()>
where
T: AnyBitPatternDeviceRepr,
{
let () = T::LAYOUT;
unsafe { self.set_value_unchecked(value) }
}
pub unsafe fn set_value_unchecked(&mut self, value: u8) -> Result<()> {
let context = Arc::clone(self.context());
let _access = context.acquire_host_access(&[self.region()])?;
self.bind()?;
if self.length == 0 {
return Ok(());
}
unsafe {
Self::set(self.context(), self.ptr, value, self.length)?;
}
StreamBinding::Default(Arc::clone(self.context())).synchronize()
}
pub fn set_value_scoped<'env>(
&'env mut self,
value: u8,
stream: &StreamScope<'_, 'env>,
) -> Result<()>
where
T: AnyBitPatternDeviceRepr,
{
let () = T::LAYOUT;
checked_bytes::<T>(self.len(), "byte length")?;
self.bind_stream(stream.stream())?;
if self.is_empty() {
return Ok(());
}
let accesses = [Access::new(self.region(), AccessMode::Write)];
unsafe {
stream.enqueue(&accesses, || {
Self::set_async(self.ptr, value, self.len(), stream.stream())
})
}
}
pub unsafe fn set_value_async(&mut self, value: u8, stream: &Stream) -> Result<()>
where
T: AnyBitPatternDeviceRepr,
{
let () = T::LAYOUT;
self.bind_stream(stream)?;
if self.is_empty() {
return Ok(());
}
stream.join_regions(&[self.region()])?;
unsafe { Self::set_async(self.as_mut_ptr(), value, self.len(), stream) }
}
pub fn ipc_handle(&self) -> Result<IpcMemoryHandle> {
self.bind()?;
if self.is_empty() {
return Err(Error::empty("device allocation"));
}
let mut handle = MaybeUninit::uninit();
unsafe {
try_ffi!(runtime::cudaIpcGetMemHandle(
handle.as_mut_ptr(),
self.as_ptr().cast_mut().cast(),
))?;
Ok(IpcMemoryHandle::from_raw(handle.assume_init()))
}
}
pub fn try_clone(&self) -> Result<Self> {
let new_mem = DeviceMemory::<MaybeUninit<T>>::allocate(self.context(), self.length)?;
if self.length == 0 || size_of::<T>() == 0 {
return Ok(unsafe { new_mem.assume_init() });
}
let source = self.region();
let _access = self.context().acquire_host_access(&[source])?;
self.context().bind()?;
unsafe {
transfer::copy_synchronous(
new_mem.as_mut_ptr().cast::<T>(),
self.as_ptr(),
self.length,
MemoryCopyKind::DeviceToDevice,
source.stream(),
)?;
}
Ok(unsafe { new_mem.assume_init() })
}
}
impl<T> DeviceMemory<MaybeUninit<T>> {
fn allocate(context: &Arc<Context>, length: usize) -> Result<Self> {
context.bind()?;
let bytes = checked_bytes::<T>(length, "byte length")?;
let device_ptr = if bytes == 0 {
ptr::null_mut()
} else {
unsafe { Self::alloc(context, length)? }
};
Ok(Self {
allocation: Arc::new(DeviceAllocation {
id: AllocationId::create(),
context: Arc::clone(context),
ptr: device_ptr.cast(),
bytes,
deallocation: DeviceDeallocation::Immediate,
}),
ptr: device_ptr,
length,
_phantom: PhantomData,
})
}
pub unsafe fn assume_init_prefix(mut self, length: usize) -> Result<DeviceMemory<T>> {
if length > self.length {
return Err(Error::buffer_too_small("allocation", length, self.length));
}
self.length = length;
Ok(unsafe { self.assume_init() })
}
#[must_use]
pub unsafe fn assume_init(self) -> DeviceMemory<T> {
let Self {
allocation,
ptr,
length,
..
} = self;
DeviceMemory {
allocation,
ptr: ptr.cast(),
length,
_phantom: PhantomData,
}
}
}
unsafe impl<T> DeviceRegionProvider for DeviceMemory<T> {
fn region(&self) -> DeviceRegion<'_> {
let offset = self.ptr.addr() - self.allocation.ptr.addr();
self.allocation
.region()
.slice(offset..offset + self.byte_len())
.expect("device buffer exceeds its allocation")
}
}
#[derive(Debug)]
pub struct RawDeviceMemory<T> {
pub ptr: *mut T,
pub len: usize,
pub context: Arc<Context>,
pub stream_ordered: Option<StreamOrderedFree>,
}
#[derive(Debug)]
pub struct DeviceMemory<T> {
pub(crate) allocation: Arc<DeviceAllocation>,
pub(crate) ptr: *mut T,
pub(crate) length: usize,
pub(crate) _phantom: PhantomData<T>,
}
impl<T> PartialEq for DeviceMemory<T> {
fn eq(&self, other: &Self) -> bool {
self.context() == other.context() && self.ptr == other.ptr && self.length == other.length
}
}
impl<T> Eq for DeviceMemory<T> {}
unsafe impl<T: Send> Send for DeviceMemory<T> {}
unsafe impl<T: Sync> Sync for DeviceMemory<T> {}
unsafe impl<T: DeviceRepr> DeviceOutput<T> for DeviceMemory<T> {
fn as_mut_ptr(&mut self) -> *mut T {
let () = T::LAYOUT;
self.ptr
}
}
unsafe impl<T: DeviceRepr> DeviceRange<T> for DeviceMemory<MaybeUninit<T>> {
fn len(&self) -> usize {
self.length
}
}
unsafe impl<T: DeviceRepr> DeviceOutput<T> for DeviceMemory<MaybeUninit<T>> {
fn as_mut_ptr(&mut self) -> *mut T {
let () = T::LAYOUT;
self.ptr.cast()
}
}