use std::{
ffi::c_void,
fmt::{self, Display, Formatter},
mem::{ManuallyDrop, MaybeUninit, align_of, size_of},
os::fd::RawFd,
ptr,
result::Result as StdResult,
sync::Arc,
};
use bitflags::parser;
use num_enum::{IntoPrimitive, TryFromPrimitive};
use singe_core::{impl_enum_display, report_cleanup_failure};
use singe_cuda_sys::driver;
use crate::{
context::Context,
error::{Error, Result},
module::{KernelParameters, PushKernelArg},
try_ffi,
utility::{checked_bytes, to_u64, to_usize},
view::{
AllocationId, AnyBitPatternDeviceRepr, DeviceOutput, DeviceOutputView, DeviceRange,
DeviceRegion, DeviceRegionProvider, DeviceRepr, DeviceSlice, DeviceSliceMut, DeviceView,
DeviceViewMut, NoUninitDeviceRepr,
},
};
singe_core::native_enum! {
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, TryFromPrimitive, IntoPrimitive)]
#[repr(u32)]
#[non_exhaustive]
pub enum ExternalMemoryHandleType: driver::CUexternalMemoryHandleType {
OpaqueFileDescriptor = CU_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD,
OpaqueWin32 = CU_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_WIN32,
OpaqueWin32Kmt = CU_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_WIN32_KMT,
DmaBufferFileDescriptor = CU_EXTERNAL_MEMORY_HANDLE_TYPE_DMABUF_FD,
}
}
bitflags::bitflags! {
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct ExternalMemoryFlags: u32 {
const DEDICATED = driver::CUDA_EXTERNAL_MEMORY_DEDICATED;
}
}
impl Display for ExternalMemoryFlags {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
parser::to_writer(self, f)
}
}
#[derive(Debug)]
pub struct RawExternalMemory {
pub handle: driver::CUexternalMemory,
pub size: usize,
pub context: Arc<Context>,
}
#[derive(Debug)]
pub struct ExternalMemory {
handle: driver::CUexternalMemory,
size: usize,
context: Arc<Context>,
}
#[derive(Debug)]
pub struct MappedAllocation {
memory: ManuallyDrop<ExternalMemory>,
ptr: *mut u8,
bytes: usize,
offset: usize,
id: AllocationId,
}
#[derive(Debug)]
pub struct MappedBuffer<T: DeviceRepr> {
allocation: Arc<MappedAllocation>,
ptr: *mut T,
length: usize,
}
impl ExternalMemory {
#[cfg(unix)]
pub unsafe fn import_opaque_file_descriptor(
context: &Arc<Context>,
fd: RawFd,
size: usize,
flags: ExternalMemoryFlags,
) -> Result<Self> {
let mut desc = handle_desc(ExternalMemoryHandleType::OpaqueFileDescriptor, size, flags)?;
desc.handle.fd = fd;
unsafe { Self::import(context, &desc, size) }
}
pub unsafe fn import_opaque_win32_handle(
context: &Arc<Context>,
handle: *mut c_void,
size: usize,
flags: ExternalMemoryFlags,
) -> Result<Self> {
if handle.is_null() {
return Err(Error::NullHandle);
}
let mut desc = handle_desc(ExternalMemoryHandleType::OpaqueWin32, size, flags)?;
desc.handle.win32.handle = handle;
desc.handle.win32.name = ptr::null();
unsafe { Self::import(context, &desc, size) }
}
pub unsafe fn import_opaque_win32_name(
context: &Arc<Context>,
name: *const c_void,
size: usize,
flags: ExternalMemoryFlags,
) -> Result<Self> {
if name.is_null() {
return Err(Error::NullHandle);
}
let mut desc = handle_desc(ExternalMemoryHandleType::OpaqueWin32, size, flags)?;
desc.handle.win32.handle = ptr::null_mut();
desc.handle.win32.name = name;
unsafe { Self::import(context, &desc, size) }
}
unsafe fn import(
context: &Arc<Context>,
desc: &driver::CUDA_EXTERNAL_MEMORY_HANDLE_DESC,
size: usize,
) -> Result<Self> {
context.bind()?;
let mut handle = ptr::null_mut();
unsafe {
try_ffi!(driver::cuImportExternalMemory(&raw mut handle, desc))?;
}
unsafe {
Self::from_raw(RawExternalMemory {
handle,
size,
context: Arc::clone(context),
})
}
}
pub fn map_buffer<T: DeviceRepr>(
self,
offset_bytes: usize,
length: usize,
) -> Result<MappedBuffer<MaybeUninit<T>>> {
let () = T::LAYOUT;
let bytes = checked_bytes::<T>(length, "mapped buffer byte size")?;
let end = offset_bytes
.checked_add(bytes)
.ok_or_else(|| Error::out_of_range("mapped buffer end"))?;
if end > self.size {
return Err(Error::buffer_too_small("external memory", end, self.size));
}
self.context.bind()?;
let mut pointer = 0;
if bytes != 0 {
let desc = driver::CUDA_EXTERNAL_MEMORY_BUFFER_DESC {
offset: to_u64(offset_bytes, "mapped buffer offset")?,
size: to_u64(bytes, "mapped buffer byte size")?,
flags: 0,
reserved: [0; 16],
};
unsafe {
try_ffi!(driver::cuExternalMemoryGetMappedBuffer(
&raw mut pointer,
self.handle,
&raw const desc
))?;
}
if pointer == 0 {
return Err(Error::NullHandle);
}
}
let address = to_usize(pointer, "mapped buffer address")?;
let allocation = Arc::new(MappedAllocation {
memory: ManuallyDrop::new(self),
ptr: ptr::without_provenance_mut(address),
bytes,
offset: offset_bytes,
id: AllocationId::create(),
});
unsafe {
DeviceRegion::from_raw_parts(
allocation.context(),
allocation.id,
allocation.ptr,
bytes,
)?
};
if bytes != 0
&& !pointer.is_multiple_of(
u64::try_from(align_of::<T>()).expect("alignment fits a device address"),
)
{
return Err(Error::misaligned("mapped buffer address", align_of::<T>()));
}
Ok(MappedBuffer {
allocation,
ptr: ptr::without_provenance_mut(address),
length,
})
}
#[must_use]
pub const fn byte_len(&self) -> usize {
self.size
}
#[must_use]
pub const fn as_raw(&self) -> driver::CUexternalMemory {
self.handle
}
#[must_use]
pub fn context(&self) -> &Arc<Context> {
&self.context
}
pub unsafe fn from_raw(raw: RawExternalMemory) -> Result<Self> {
if raw.handle.is_null() {
return Err(Error::NullHandle);
}
if raw.size == 0 {
return Err(Error::not_positive("external memory size"));
}
Ok(Self {
handle: raw.handle,
size: raw.size,
context: raw.context,
})
}
#[must_use]
pub fn into_raw(self) -> RawExternalMemory {
let memory = ManuallyDrop::new(self);
RawExternalMemory {
handle: memory.handle,
size: memory.size,
context: unsafe { ptr::read(&raw const memory.context) },
}
}
}
impl Drop for ExternalMemory {
fn drop(&mut self) {
if let Err(error) = self.context.bind() {
report_cleanup_failure(
"bind the cuda context to destroy",
"cuda external memory",
&error,
);
return;
}
if let Err(error) = unsafe { try_ffi!(driver::cuDestroyExternalMemory(self.handle)) } {
report_cleanup_failure("destroy", "cuda external memory", &error);
}
}
}
unsafe impl Send for ExternalMemory {}
unsafe impl Sync for ExternalMemory {}
unsafe impl Send for MappedAllocation {}
unsafe impl Sync for MappedAllocation {}
impl MappedAllocation {
#[must_use]
pub const fn id(&self) -> AllocationId {
self.id
}
#[must_use]
pub fn context(&self) -> &Arc<Context> {
self.memory.context()
}
#[must_use]
pub const fn as_ptr(&self) -> *mut u8 {
self.ptr
}
#[must_use]
pub const fn byte_len(&self) -> usize {
self.bytes
}
#[must_use]
pub const fn external_offset_bytes(&self) -> usize {
self.offset
}
#[must_use]
pub fn external_memory(&self) -> &ExternalMemory {
&self.memory
}
}
unsafe impl DeviceRegionProvider for MappedAllocation {
fn region(&self) -> DeviceRegion<'_> {
unsafe { DeviceRegion::from_raw_parts(self.context(), self.id, self.ptr, self.bytes) }
.expect("native mapping bounds validated during construction")
}
}
impl Drop for MappedAllocation {
fn drop(&mut self) {
if !self.ptr.is_null() {
if let Err(error) = self.context().bind() {
report_cleanup_failure(
"bind the cuda context to free",
"cuda mapped external memory buffer",
&error,
);
return;
}
let address = self.ptr.addr() as driver::CUdeviceptr;
let result = unsafe { try_ffi!(driver::cuMemFree_v2(address)) };
if let Err(error) = result {
report_cleanup_failure("free", "cuda mapped external memory buffer", &error);
return;
}
}
unsafe { ManuallyDrop::drop(&mut self.memory) };
}
}
impl<T: DeviceRepr> MappedBuffer<T> {
#[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 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, "mapped buffer byte size")
.expect("mapped byte length validated during construction")
}
#[must_use]
pub fn context(&self) -> &Arc<Context> {
self.allocation.context()
}
#[must_use]
pub fn allocation(&self) -> &Arc<MappedAllocation> {
&self.allocation
}
#[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 cast<U: AnyBitPatternDeviceRepr>(self) -> StdResult<MappedBuffer<U>, Self>
where
T: NoUninitDeviceRepr,
{
let () = T::LAYOUT;
let () = U::LAYOUT;
let bytes = self.byte_len();
if size_of::<U>() == 0
|| !bytes.is_multiple_of(size_of::<U>())
|| (bytes != 0 && !self.ptr.addr().is_multiple_of(align_of::<U>()))
{
return Err(self);
}
Ok(MappedBuffer {
allocation: self.allocation,
ptr: self.ptr.cast(),
length: bytes / size_of::<U>(),
})
}
#[must_use]
pub fn into_uninit(self) -> MappedBuffer<MaybeUninit<T>> {
MappedBuffer {
allocation: self.allocation,
ptr: self.ptr.cast(),
length: self.length,
}
}
}
impl<T: DeviceRepr> MappedBuffer<MaybeUninit<T>> {
pub fn output(&mut self) -> DeviceOutputView<'_, T> {
DeviceOutputView::from_output(self)
}
pub fn cast_uninit<U: DeviceRepr>(self) -> StdResult<MappedBuffer<MaybeUninit<U>>, Self> {
let () = U::LAYOUT;
let bytes = self.byte_len();
if size_of::<U>() == 0
|| !bytes.is_multiple_of(size_of::<U>())
|| (bytes != 0 && !self.ptr.addr().is_multiple_of(align_of::<U>()))
{
return Err(self);
}
Ok(MappedBuffer {
allocation: self.allocation,
ptr: self.ptr.cast(),
length: bytes / size_of::<U>(),
})
}
#[must_use]
pub unsafe fn assume_init(self) -> MappedBuffer<T> {
let () = T::LAYOUT;
MappedBuffer {
allocation: self.allocation,
ptr: self.ptr.cast(),
length: self.length,
}
}
pub unsafe fn assume_init_prefix(mut self, length: usize) -> Result<MappedBuffer<T>> {
if length > self.length {
return Err(Error::buffer_too_small(
"mapped buffer",
length,
self.length,
));
}
self.length = length;
unsafe { Ok(self.assume_init()) }
}
}
unsafe impl<T: DeviceRepr + Send> Send for MappedBuffer<T> {}
unsafe impl<T: DeviceRepr + Sync> Sync for MappedBuffer<T> {}
unsafe impl<T: DeviceRepr> DeviceRegionProvider for MappedBuffer<T> {
fn region(&self) -> DeviceRegion<'_> {
self.allocation
.region()
.slice(..self.byte_len())
.expect("mapped range validated during construction")
}
}
unsafe impl<T: DeviceRepr> DeviceRange<T> for MappedBuffer<T> {
fn as_device_ptr(&self) -> *const T {
self.ptr
}
fn len(&self) -> usize {
self.length
}
}
unsafe impl<T: DeviceRepr> DeviceSlice<T> for MappedBuffer<T> {}
unsafe impl<T: DeviceRepr> DeviceSliceMut<T> for MappedBuffer<T> {}
unsafe impl<T: DeviceRepr> DeviceOutput<T> for MappedBuffer<T> {
fn as_mut_ptr(&mut self) -> *mut T {
self.ptr
}
}
unsafe impl<T: DeviceRepr> DeviceRange<T> for MappedBuffer<MaybeUninit<T>> {
fn len(&self) -> usize {
self.length
}
}
unsafe impl<T: DeviceRepr> DeviceOutput<T> for MappedBuffer<MaybeUninit<T>> {
fn as_mut_ptr(&mut self) -> *mut T {
self.ptr.cast()
}
}
impl<T: DeviceRepr> PushKernelArg for &MappedBuffer<T> {
fn push_to(self, params: &mut KernelParameters<'_>) {
params.device_input(self);
}
}
impl<T: DeviceRepr> PushKernelArg for &mut MappedBuffer<T> {
fn push_to(self, params: &mut KernelParameters<'_>) {
params.device_slice_mut(self);
}
}
fn handle_desc(
handle_type: ExternalMemoryHandleType,
size: usize,
flags: ExternalMemoryFlags,
) -> Result<driver::CUDA_EXTERNAL_MEMORY_HANDLE_DESC> {
if size == 0 {
return Err(Error::not_positive("external memory size"));
}
Ok(driver::CUDA_EXTERNAL_MEMORY_HANDLE_DESC {
type_: handle_type.into(),
handle: driver::CUDA_EXTERNAL_MEMORY_HANDLE_DESC_st__bindgen_ty_1::default(),
size: to_u64(size, "external memory size")?,
flags: flags.bits(),
reserved: [0; 16],
})
}
impl_enum_display!(ExternalMemoryHandleType, {
ExternalMemoryHandleType::OpaqueFileDescriptor => "CU_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD",
ExternalMemoryHandleType::OpaqueWin32 => "CU_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_WIN32",
ExternalMemoryHandleType::OpaqueWin32Kmt => "CU_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_WIN32_KMT",
ExternalMemoryHandleType::DmaBufferFileDescriptor => "CU_EXTERNAL_MEMORY_HANDLE_TYPE_DMABUF_FD",
});