use std::{
marker::PhantomData, mem::MaybeUninit, ptr, result::Result as StdResult, slice, sync::Arc,
};
use singe_cuda_sys::runtime;
use crate::{
context::Context,
device::DeviceAttribute,
error::{Error, Result},
memory::{
DeviceAllocation, DeviceDeallocation, DeviceMemory, MemoryAttachFlags, MemoryLocation,
location_info,
},
stream::{AsStream, Stream, StreamBinding},
try_ffi,
types::{DevicePtr, MemoryAdvise},
utility::{checked_bytes, to_u64},
view::{
AnyBitPatternDeviceRepr, DeviceOutput, DeviceOutputView, DeviceRange, DeviceRegion,
DeviceRegionProvider, DeviceRepr, DeviceSlice, DeviceSliceMut, DeviceView, DeviceViewMut,
NoUninitDeviceRepr, ZeroableDeviceRepr, cast_length,
},
};
impl<T: DeviceRepr> ManagedMemory<T> {
pub fn zeroed(
context: &Arc<Context>,
length: usize,
attach_flags: MemoryAttachFlags,
) -> Result<Self>
where
T: ZeroableDeviceRepr,
{
let mut memory = Self::create_uninit(context, length, attach_flags)?;
memory.set_zeroes()?;
Ok(unsafe { memory.assume_init() })
}
pub fn filled(
context: &Arc<Context>,
length: usize,
attach_flags: MemoryAttachFlags,
value: u8,
) -> Result<Self>
where
T: AnyBitPatternDeviceRepr,
{
let mut memory = Self::create_uninit(context, length, attach_flags)?;
memory.set_value(value)?;
Ok(unsafe { memory.assume_init() })
}
pub unsafe fn from_raw(raw: RawManagedMemory<T>) -> Result<Self> {
let RawManagedMemory {
ptr,
len,
attach_flags,
context,
} = raw;
let () = T::LAYOUT;
let bytes = checked_bytes::<T>(len, "byte length")?;
if bytes != 0 && ptr.is_null() {
return Err(Error::null_pointer("managed memory"));
}
Ok(Self {
allocation: DeviceAllocation::from_parts(
&context,
ptr.cast(),
bytes,
DeviceDeallocation::Immediate,
),
ptr,
length: len,
attach_flags,
_phantom: PhantomData,
})
}
pub fn into_raw(self) -> StdResult<RawManagedMemory<T>, Self> {
let Self {
allocation,
ptr,
length,
attach_flags,
..
} = self;
match Arc::try_unwrap(allocation) {
Ok(mut allocation) => {
let context = Arc::clone(allocation.context());
allocation.ptr = ptr::null_mut();
Ok(RawManagedMemory {
ptr,
len: length,
attach_flags,
context,
})
}
Err(allocation) => Err(Self {
allocation,
ptr,
length,
attach_flags,
_phantom: PhantomData,
}),
}
}
#[must_use]
pub fn context(&self) -> &Arc<Context> {
self.allocation.context()
}
#[must_use]
pub fn allocation(&self) -> &Arc<DeviceAllocation> {
&self.allocation
}
pub fn cast<U: AnyBitPatternDeviceRepr>(self) -> StdResult<ManagedMemory<U>, Self>
where
T: NoUninitDeviceRepr,
{
let () = T::LAYOUT;
let Ok(length) = cast_length::<U>(self.region()) else {
return Err(self);
};
Ok(ManagedMemory {
allocation: self.allocation,
ptr: self.ptr.cast(),
length,
attach_flags: self.attach_flags,
_phantom: PhantomData,
})
}
#[must_use]
pub fn into_uninit(self) -> ManagedMemory<MaybeUninit<T>> {
ManagedMemory {
allocation: self.allocation,
ptr: self.ptr.cast(),
length: self.length,
attach_flags: self.attach_flags,
_phantom: PhantomData,
}
}
fn bind_stream(&self, stream: &Stream) -> Result<()> {
if stream.context() != self.context() {
return Err(Error::StreamContextMismatch);
}
self.context().bind()
}
pub fn create_uninit(
context: &Arc<Context>,
length: usize,
attach_flags: MemoryAttachFlags,
) -> Result<ManagedMemory<MaybeUninit<T>>> {
let () = T::LAYOUT;
context.bind()?;
let bytes = checked_bytes::<T>(length, "byte length")?;
let ptr = if bytes == 0 {
ptr::null_mut()
} else {
unsafe { DeviceMemory::<MaybeUninit<T>>::alloc_managed(context, length, attach_flags)? }
};
Ok(ManagedMemory {
allocation: DeviceAllocation::from_parts(
context,
ptr.cast(),
bytes,
DeviceDeallocation::Immediate,
),
ptr,
length,
attach_flags,
_phantom: PhantomData,
})
}
#[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("managed memory byte length overflow")
}
#[must_use]
pub const fn attach_flags(&self) -> MemoryAttachFlags {
self.attach_flags
}
#[must_use]
pub const fn as_ptr(&self) -> *const T {
self.ptr
}
pub const fn as_mut_ptr(&mut 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 view(&self) -> DeviceView<'_, T> {
DeviceView::from_buffer(self)
}
pub fn view_mut(&mut self) -> DeviceViewMut<'_, T> {
DeviceViewMut::from_buffer(self)
}
pub fn with_host_slice<R>(&self, read: impl FnOnce(&[T]) -> R) -> Result<R> {
if self
.context()
.device()
.attribute(DeviceAttribute::ConcurrentManagedAccess)?
== 0
{
return Err(Error::ManagedHostAccessUnsupported);
}
self.context().with_host_access(&[self.region()], || {
Ok(read(unsafe { self.as_host_slice() }))
})
}
pub fn with_host_slice_mut<R>(&mut self, write: impl FnOnce(&mut [T]) -> R) -> Result<R> {
if self
.context()
.device()
.attribute(DeviceAttribute::ConcurrentManagedAccess)?
== 0
{
return Err(Error::ManagedHostAccessUnsupported);
}
let context = Arc::clone(self.context());
let _guard = context.acquire_host_access(&[self.region()])?;
Ok(write(unsafe { self.as_host_slice_mut() }))
}
#[must_use]
pub unsafe fn as_host_slice(&self) -> &[T] {
if self.is_empty() {
return &[];
}
unsafe { slice::from_raw_parts(self.ptr, self.length) }
}
pub unsafe fn as_host_slice_mut(&mut self) -> &mut [T] {
if self.is_empty() {
return &mut [];
}
unsafe { slice::from_raw_parts_mut(self.ptr, self.length) }
}
pub fn set_zeroes(&mut self) -> Result<()>
where
T: ZeroableDeviceRepr,
{
unsafe { self.fill_bytes(0) }
}
pub fn set_value(&mut self, value: u8) -> Result<()>
where
T: AnyBitPatternDeviceRepr,
{
unsafe { self.fill_bytes(value) }
}
unsafe fn fill_bytes(&mut self, value: u8) -> Result<()> {
let context = Arc::clone(self.context());
let _access = context.acquire_host_access(&[self.region()])?;
self.context().bind()?;
let () = T::LAYOUT;
if self.is_empty() {
return Ok(());
}
unsafe {
DeviceMemory::<T>::set(self.context(), self.ptr, value, self.length)?;
}
StreamBinding::Default(Arc::clone(self.context())).synchronize()
}
pub fn prefetch_to(&self, location: MemoryLocation, stream: &Stream) -> Result<()> {
self.bind_stream(stream)?;
DeviceMemory::<T>::prefetch(
unsafe { DevicePtr::from_raw(self.ptr.cast::<()>()) },
checked_bytes::<T>(self.length, "byte length")?,
location,
stream,
)
}
pub fn advise(&self, advice: MemoryAdvise, location: MemoryLocation) -> Result<()> {
self.context().bind()?;
DeviceMemory::<T>::advise(
unsafe { DevicePtr::from_raw(self.ptr.cast::<()>()) },
checked_bytes::<T>(self.length, "byte length")?,
advice,
location,
)
}
pub fn set_read_mostly(&self) -> Result<()> {
self.advise(MemoryAdvise::SetReadMostly, Self::ignored_advice_location())
}
pub fn unset_read_mostly(&self) -> Result<()> {
self.advise(
MemoryAdvise::UnsetReadMostly,
Self::ignored_advice_location(),
)
}
pub fn set_preferred_location(&self, location: MemoryLocation) -> Result<()> {
self.advise(MemoryAdvise::SetPreferredLocation, location)
}
pub fn unset_preferred_location(&self) -> Result<()> {
self.advise(
MemoryAdvise::UnsetPreferredLocation,
Self::ignored_advice_location(),
)
}
pub fn set_accessed_by(&self, location: MemoryLocation) -> Result<()> {
self.advise(MemoryAdvise::SetAccessedBy, location)
}
pub fn unset_accessed_by(&self, location: MemoryLocation) -> Result<()> {
self.advise(MemoryAdvise::UnsetAccessedBy, location)
}
const fn ignored_advice_location() -> MemoryLocation {
MemoryLocation::Host
}
pub fn attach_to_stream(&mut self, stream: &Stream, flags: MemoryAttachFlags) -> Result<()> {
self.bind_stream(stream)?;
let bytes = to_u64(
checked_bytes::<T>(self.length, "byte length")?,
"byte length",
)?;
unsafe {
try_ffi!(runtime::cudaStreamAttachMemAsync(
stream.as_raw(),
self.ptr.cast(),
bytes,
flags.bits(),
))?;
}
self.attach_flags = flags;
Ok(())
}
}
unsafe impl<T: DeviceRepr> DeviceRange<T> for ManagedMemory<T> {
fn as_device_ptr(&self) -> *const T {
self.ptr
}
fn len(&self) -> usize {
self.length
}
}
unsafe impl<T: DeviceRepr> DeviceSlice<T> for ManagedMemory<T> {}
unsafe impl<T: DeviceRepr> DeviceSliceMut<T> for ManagedMemory<T> {}
unsafe impl<T: DeviceRepr> DeviceRegionProvider for ManagedMemory<T> {
fn region(&self) -> DeviceRegion<'_> {
let offset = self.ptr.addr() - self.allocation.ptr.addr();
self.allocation
.region()
.slice(offset..offset + self.byte_len())
.expect("managed buffer exceeds its allocation")
}
}
impl<T: DeviceRepr> ManagedMemory<MaybeUninit<T>> {
pub fn output(&mut self) -> DeviceOutputView<'_, T> {
DeviceOutputView::from_output(self)
}
pub unsafe fn assume_init_prefix(mut self, length: usize) -> Result<ManagedMemory<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) -> ManagedMemory<T> {
let () = T::LAYOUT;
ManagedMemory {
allocation: self.allocation,
ptr: self.ptr.cast(),
length: self.length,
attach_flags: self.attach_flags,
_phantom: PhantomData,
}
}
}
impl<T: DeviceRepr> ManagedMemory<T> {
pub fn location_info(
&self,
summary_granularity: usize,
sampling_granularity: usize,
) -> Result<Vec<MemoryLocation>> {
self.context().bind()?;
unsafe {
location_info(
DevicePtr::from_raw(self.ptr.cast()),
checked_bytes::<T>(self.length, "byte length")?,
summary_granularity,
sampling_granularity,
)
}
}
}
#[derive(Debug)]
pub struct RawManagedMemory<T> {
pub ptr: *mut T,
pub len: usize,
pub attach_flags: MemoryAttachFlags,
pub context: Arc<Context>,
}
#[derive(Debug)]
pub struct ManagedMemory<T: DeviceRepr> {
allocation: Arc<DeviceAllocation>,
ptr: *mut T,
length: usize,
attach_flags: MemoryAttachFlags,
_phantom: PhantomData<T>,
}
unsafe impl<T: DeviceRepr + Send> Send for ManagedMemory<T> {}
unsafe impl<T: DeviceRepr + Sync> Sync for ManagedMemory<T> {}
unsafe impl<T: DeviceRepr> DeviceOutput<T> for ManagedMemory<T> {
fn as_mut_ptr(&mut self) -> *mut T {
let () = T::LAYOUT;
self.ptr
}
}
unsafe impl<T: DeviceRepr> DeviceRange<T> for ManagedMemory<MaybeUninit<T>> {
fn len(&self) -> usize {
self.length
}
}
unsafe impl<T: DeviceRepr> DeviceOutput<T> for ManagedMemory<MaybeUninit<T>> {
fn as_mut_ptr(&mut self) -> *mut T {
let () = T::LAYOUT;
self.ptr.cast()
}
}