use std::{marker::PhantomData, ptr, ptr::NonNull, slice, sync::Arc};
use singe_core::report_cleanup_failure;
use singe_cuda_sys::runtime;
use crate::{
context::Context,
error::{Error, Result},
memory::{
HostRegisterFlags, PinnedHostSlice, PinnedHostSliceMut, register_host_raw,
unregister_host_raw,
},
submission::{Access, AccessMode},
try_ffi,
types::DevicePtr,
utility::{checked_bytes, dangling_or_non_null},
view::{
AllocationId, DeviceRegion, DeviceRepr, DeviceView, DeviceViewMut, HostRegion, HostSlice,
HostSliceMut,
},
};
impl<'a, T: DeviceRepr> RegisteredHostMemory<'a, T> {
pub fn with_host_slice<R>(&self, read: impl FnOnce(&[T]) -> R) -> Result<R> {
let context = self.context();
let _guard =
context.acquire_accesses(&[Access::host(self.host_region(), AccessMode::Read)])?;
Ok(read(self.as_slice()))
}
pub fn with_host_slice_mut<R>(&mut self, write: impl FnOnce(&mut [T]) -> R) -> Result<R> {
let context = Arc::clone(self.context());
let _guard =
context.acquire_accesses(&[Access::host(self.host_region(), AccessMode::ReadWrite)])?;
Ok(write(self.as_slice_mut()))
}
pub fn create(
context: &Arc<Context>,
slice: &'a mut [T],
flags: HostRegisterFlags,
) -> Result<Self> {
if flags.contains(HostRegisterFlags::READ_ONLY)
|| flags.contains(HostRegisterFlags::IO_MEMORY)
{
return Err(Error::out_of_range("host register flags"));
}
unsafe { Self::register_slice(context, slice.as_mut_ptr(), slice.len(), flags) }
}
pub unsafe fn create_io_memory(context: &Arc<Context>, slice: &'a mut [T]) -> Result<Self> {
unsafe {
Self::register_slice(
context,
slice.as_mut_ptr(),
slice.len(),
HostRegisterFlags::IO_MEMORY,
)
}
}
unsafe fn register_slice(
context: &Arc<Context>,
ptr: *mut T,
length: usize,
flags: HostRegisterFlags,
) -> Result<Self> {
let () = T::LAYOUT;
let bytes = checked_bytes::<T>(length, "byte length")?;
let typed_ptr = dangling_or_non_null(ptr, length)?;
let registration =
unsafe { HostRegistration::create(context, typed_ptr.cast(), bytes, flags)? };
Ok(Self {
ptr: typed_ptr,
length,
registration,
_borrow: PhantomData,
})
}
#[must_use]
pub fn as_slice(&self) -> &[T] {
if self.is_empty() {
return &[];
}
unsafe { slice::from_raw_parts(self.ptr.as_ptr(), self.length) }
}
pub fn as_slice_mut(&mut self) -> &mut [T] {
if self.is_empty() {
return &mut [];
}
unsafe { slice::from_raw_parts_mut(self.ptr.as_ptr(), self.length) }
}
#[must_use]
pub const fn as_ptr(&self) -> *const T {
self.ptr.as_ptr().cast_const()
}
pub const fn as_mut_ptr(&mut self) -> *mut T {
self.ptr.as_ptr()
}
#[must_use]
pub const fn len(&self) -> usize {
self.length
}
#[must_use]
pub const fn is_empty(&self) -> bool {
self.length == 0
}
pub fn byte_len(&self) -> Result<usize> {
checked_bytes::<T>(self.length, "byte length")
}
#[must_use]
pub const fn flags(&self) -> HostRegisterFlags {
self.registration.flags
}
pub fn mapped_device_ptr(&self) -> Result<DevicePtr> {
self.registration.mapped_device_ptr()
}
#[must_use]
pub fn context(&self) -> &Arc<Context> {
&self.registration.context
}
pub fn mapped_device_view(&self) -> Result<DeviceView<'_, T>> {
unsafe { DeviceView::from_raw_parts(self.registration.mapped_device_region()?, self.len()) }
}
pub fn mapped_device_view_mut(&mut self) -> Result<DeviceViewMut<'_, T>> {
unsafe {
DeviceViewMut::from_raw_parts(self.registration.mapped_device_region()?, self.len())
}
}
}
impl<'a, T: DeviceRepr> RegisteredHostSlice<'a, T> {
pub fn with_host_slice<R>(&self, read: impl FnOnce(&[T]) -> R) -> Result<R> {
let context = self.context();
let _guard =
context.acquire_accesses(&[Access::host(self.host_region(), AccessMode::Read)])?;
Ok(read(self.as_slice()))
}
pub fn create(
context: &Arc<Context>,
slice: &'a [T],
flags: HostRegisterFlags,
) -> Result<Self> {
if flags.contains(HostRegisterFlags::IO_MEMORY) {
return Err(Error::out_of_range("host register flags"));
}
unsafe { Self::register_slice(context, slice.as_ptr(), slice.len(), flags) }
}
unsafe fn register_slice(
context: &Arc<Context>,
ptr: *const T,
length: usize,
flags: HostRegisterFlags,
) -> Result<Self> {
let () = T::LAYOUT;
let bytes = checked_bytes::<T>(length, "byte length")?;
let typed_ptr = dangling_or_non_null(ptr.cast_mut(), length)?;
let registration =
unsafe { HostRegistration::create(context, typed_ptr.cast(), bytes, flags)? };
Ok(Self {
ptr: typed_ptr,
length,
registration,
_borrow: PhantomData,
})
}
#[must_use]
pub fn as_slice(&self) -> &[T] {
if self.is_empty() {
return &[];
}
unsafe { slice::from_raw_parts(self.ptr.as_ptr(), self.length) }
}
#[must_use]
pub const fn as_ptr(&self) -> *const T {
self.ptr.as_ptr().cast_const()
}
#[must_use]
pub const fn len(&self) -> usize {
self.length
}
#[must_use]
pub const fn is_empty(&self) -> bool {
self.length == 0
}
pub fn byte_len(&self) -> Result<usize> {
checked_bytes::<T>(self.length, "byte length")
}
#[must_use]
pub const fn flags(&self) -> HostRegisterFlags {
self.registration.flags
}
pub fn mapped_device_ptr(&self) -> Result<DevicePtr> {
self.registration.mapped_device_ptr()
}
#[must_use]
pub fn context(&self) -> &Arc<Context> {
&self.registration.context
}
pub fn mapped_device_view(&self) -> Result<DeviceView<'_, T>> {
unsafe { DeviceView::from_raw_parts(self.registration.mapped_device_region()?, self.len()) }
}
}
#[derive(Debug)]
pub(crate) struct HostRegistration {
flags: HostRegisterFlags,
context: Arc<Context>,
id: AllocationId,
ptr: NonNull<()>,
bytes: usize,
}
impl HostRegistration {
unsafe fn create(
context: &Arc<Context>,
ptr: NonNull<()>,
bytes: usize,
flags: HostRegisterFlags,
) -> Result<Self> {
context.bind()?;
if bytes != 0 {
unsafe {
register_host_raw(ptr.as_ptr(), bytes, flags)?;
}
}
Ok(Self {
flags,
context: Arc::clone(context),
id: AllocationId::create(),
ptr,
bytes,
})
}
fn host_region(&self) -> HostRegion<'_> {
unsafe {
HostRegion::from_raw_parts(
&self.context,
self.id,
self.bytes,
self.flags.contains(HostRegisterFlags::PORTABLE),
)
}
}
fn mapped_device_ptr(&self) -> Result<DevicePtr> {
self.context.bind()?;
if self.bytes == 0 {
return Ok(DevicePtr::null());
}
mapped_host_device_ptr(self.ptr.as_ptr())
}
fn mapped_device_region(&self) -> Result<DeviceRegion<'_>> {
let pointer = self.mapped_device_ptr()?;
unsafe { DeviceRegion::from_raw_parts(&self.context, self.id, pointer.cast(), self.bytes) }
}
fn unregister(&mut self) -> Result<()> {
if self.bytes != 0 {
self.context.bind()?;
unsafe { unregister_host_raw(self.ptr.as_ptr())? };
self.bytes = 0;
}
Ok(())
}
}
impl Drop for HostRegistration {
fn drop(&mut self) {
if let Err(error) = self.unregister() {
report_cleanup_failure("unregister", "cuda host memory", &error);
}
}
}
#[derive(Debug)]
pub struct RegisteredHostMemory<'a, T: DeviceRepr> {
ptr: NonNull<T>,
length: usize,
registration: HostRegistration,
_borrow: PhantomData<&'a mut [T]>,
}
#[derive(Debug)]
pub struct RegisteredHostSlice<'a, T: DeviceRepr> {
ptr: NonNull<T>,
length: usize,
registration: HostRegistration,
_borrow: PhantomData<&'a [T]>,
}
#[expect(
clippy::non_send_fields_in_send_ty,
reason = "raw host pointers follow the owned or borrowed storage bounds explained above"
)]
unsafe impl<T: DeviceRepr + Send> Send for RegisteredHostMemory<'_, T> {}
unsafe impl<T: DeviceRepr + Sync> Sync for RegisteredHostMemory<'_, T> {}
#[expect(
clippy::non_send_fields_in_send_ty,
reason = "raw host pointers follow the owned or borrowed storage bounds explained above"
)]
unsafe impl<T: DeviceRepr + Sync> Send for RegisteredHostSlice<'_, T> {}
unsafe impl<T: DeviceRepr + Sync> Sync for RegisteredHostSlice<'_, T> {}
unsafe impl<T: DeviceRepr> HostSlice<T> for RegisteredHostMemory<'_, T> {
fn as_host_ptr(&self) -> *const T {
self.as_ptr()
}
fn len(&self) -> usize {
self.len()
}
}
unsafe impl<T: DeviceRepr> HostSliceMut<T> for RegisteredHostMemory<'_, T> {
fn as_host_mut_ptr(&mut self) -> *mut T {
self.as_mut_ptr()
}
}
unsafe impl<T: DeviceRepr> HostSlice<T> for RegisteredHostSlice<'_, T> {
fn as_host_ptr(&self) -> *const T {
self.as_ptr()
}
fn len(&self) -> usize {
self.len()
}
}
unsafe impl<T: DeviceRepr> PinnedHostSlice<T> for RegisteredHostMemory<'_, T> {
fn host_region(&self) -> HostRegion<'_> {
self.registration
.host_region()
.slice(..self.byte_len().expect("valid host slice length"))
.expect("host slice fits its allocation")
}
}
unsafe impl<T: DeviceRepr> PinnedHostSliceMut<T> for RegisteredHostMemory<'_, T> {}
unsafe impl<T: DeviceRepr> PinnedHostSlice<T> for RegisteredHostSlice<'_, T> {
fn host_region(&self) -> HostRegion<'_> {
self.registration
.host_region()
.slice(..self.byte_len().expect("valid host slice length"))
.expect("host slice fits its allocation")
}
}
pub(crate) fn mapped_host_device_ptr(ptr: *mut ()) -> Result<DevicePtr> {
if ptr.is_null() {
return Ok(DevicePtr::null());
}
let mut device_ptr = ptr::null_mut();
unsafe {
try_ffi!(runtime::cudaHostGetDevicePointer(
&raw mut device_ptr,
ptr.cast(),
0,
))?;
}
Ok(unsafe { DevicePtr::from_raw(device_ptr.cast()) })
}