Skip to main content

singe_cuda/
external_memory.rs

1//! Safe ownership wrappers for CUDA external memory imports.
2
3use std::{
4    ffi::c_void,
5    fmt::{self, Display, Formatter},
6    mem::{ManuallyDrop, MaybeUninit, align_of, size_of},
7    os::fd::RawFd,
8    ptr,
9    result::Result as StdResult,
10    sync::Arc,
11};
12
13use bitflags::parser;
14use num_enum::{IntoPrimitive, TryFromPrimitive};
15use singe_core::{impl_enum_display, report_cleanup_failure};
16use singe_cuda_sys::driver;
17
18use crate::{
19    context::Context,
20    error::{Error, Result},
21    module::{KernelParameters, PushKernelArg},
22    try_ffi,
23    utility::{checked_bytes, to_u64, to_usize},
24    view::{
25        AllocationId, AnyBitPatternDeviceRepr, DeviceOutput, DeviceOutputView, DeviceRange,
26        DeviceRegion, DeviceRegionProvider, DeviceRepr, DeviceSlice, DeviceSliceMut, DeviceView,
27        DeviceViewMut, NoUninitDeviceRepr,
28    },
29};
30
31singe_core::native_enum! {
32    /// Kind of operating-system handle an external memory import receives.
33    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, TryFromPrimitive, IntoPrimitive)]
34    #[repr(u32)]
35    #[non_exhaustive]
36    pub enum ExternalMemoryHandleType: driver::CUexternalMemoryHandleType {
37        /// Handle is an opaque file descriptor.
38        OpaqueFileDescriptor = CU_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD,
39        /// Handle is an opaque shared NT handle.
40        OpaqueWin32 = CU_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_WIN32,
41        /// Handle is an opaque, globally shared handle.
42        OpaqueWin32Kmt = CU_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_WIN32_KMT,
43        /// Handle is a `dma_buf` file descriptor.
44        DmaBufferFileDescriptor = CU_EXTERNAL_MEMORY_HANDLE_TYPE_DMABUF_FD,
45    }
46}
47
48bitflags::bitflags! {
49    /// Flags describing the external allocation imported into CUDA.
50    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
51    pub struct ExternalMemoryFlags: u32 {
52        /// The external resource has a dedicated memory allocation.
53        const DEDICATED = driver::CUDA_EXTERNAL_MEMORY_DEDICATED;
54    }
55}
56
57impl Display for ExternalMemoryFlags {
58    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
59        parser::to_writer(self, f)
60    }
61}
62
63/// Raw ownership of an unmapped external-memory import and its context.
64///
65/// Destroy `handle` while `context` is alive, or re-adopt the value with [`ExternalMemory::from_raw`].
66#[derive(Debug)]
67pub struct RawExternalMemory {
68    /// Native external-memory handle.
69    pub handle: driver::CUexternalMemory,
70    /// Imported size in bytes.
71    pub size: usize,
72    /// Context the memory was imported into.
73    pub context: Arc<Context>,
74}
75
76/// Owns an imported external-memory object in an explicit CUDA context.
77#[derive(Debug)]
78pub struct ExternalMemory {
79    handle: driver::CUexternalMemory,
80    size: usize,
81    context: Arc<Context>,
82}
83
84/// Retains a native mapping, its imported memory object, and the actual CUDA context.
85///
86/// Raw addresses and regions grant neither initialized access nor permission to enqueue conflicting work.
87#[derive(Debug)]
88pub struct MappedAllocation {
89    memory: ManuallyDrop<ExternalMemory>,
90    ptr: *mut u8,
91    bytes: usize,
92    offset: usize,
93    id: AllocationId,
94}
95
96/// Typed storage in one native external-memory mapping.
97///
98/// Casts and initialized prefixes retain the original mapping and import independently of typed access.
99#[derive(Debug)]
100pub struct MappedBuffer<T: DeviceRepr> {
101    allocation: Arc<MappedAllocation>,
102    ptr: *mut T,
103    length: usize,
104}
105
106impl ExternalMemory {
107    /// Imports an opaque file descriptor in `context`.
108    ///
109    /// # Safety
110    ///
111    /// `fd` must reference a compatible memory object of `size` bytes on this context's device.
112    /// CUDA takes descriptor ownership on success.
113    /// Do not use it afterward.
114    /// Keep external backing resources alive and coordinate foreign accesses with all CUDA accesses.
115    /// Do not create independently mutable imports of overlapping external storage.
116    ///
117    /// # Errors
118    ///
119    /// Returns an error if `size` is zero, the context cannot be bound, CUDA rejects the import, or CUDA returns a null handle.
120    /// Descriptor ownership remains with the caller if the native import fails.
121    #[cfg(unix)]
122    pub unsafe fn import_opaque_file_descriptor(
123        context: &Arc<Context>,
124        fd: RawFd,
125        size: usize,
126        flags: ExternalMemoryFlags,
127    ) -> Result<Self> {
128        let mut desc = handle_desc(ExternalMemoryHandleType::OpaqueFileDescriptor, size, flags)?;
129        desc.handle.fd = fd;
130        // SAFETY: the caller guarantees `fd` references a compatible object of `size` bytes and hands its ownership to CUDA.
131        unsafe { Self::import(context, &desc, size) }
132    }
133
134    /// Imports an opaque Win32 shared handle in `context`.
135    ///
136    /// # Safety
137    ///
138    /// The handle must reference a compatible live external allocation of the stated size on this device.
139    /// Ownership of the Win32 handle remains with the caller.
140    /// Retain foreign backing resources, coordinate every foreign access, and prevent independently mutable aliases.
141    ///
142    /// # Errors
143    ///
144    /// Returns an error if `handle` is null, `size` is zero, the context cannot be bound, CUDA rejects the import, or CUDA returns a null handle.
145    pub unsafe fn import_opaque_win32_handle(
146        context: &Arc<Context>,
147        handle: *mut c_void,
148        size: usize,
149        flags: ExternalMemoryFlags,
150    ) -> Result<Self> {
151        if handle.is_null() {
152            return Err(Error::NullHandle);
153        }
154
155        let mut desc = handle_desc(ExternalMemoryHandleType::OpaqueWin32, size, flags)?;
156        desc.handle.win32.handle = handle;
157        desc.handle.win32.name = ptr::null();
158        // SAFETY: `handle` is non-null, and the caller guarantees it references a compatible live allocation of `size` bytes.
159        unsafe { Self::import(context, &desc, size) }
160    }
161
162    /// Imports a named Win32 external memory object in `context`.
163    ///
164    /// # Safety
165    ///
166    /// `name` must reference a valid null-terminated UTF-16 object name throughout import.
167    /// The object must be compatible with this device and have the stated size.
168    /// Retain foreign backing resources, coordinate every foreign access, and prevent independently mutable aliases.
169    ///
170    /// # Errors
171    ///
172    /// Returns an error if `name` is null, `size` is zero, the context cannot be bound, CUDA rejects the import, or CUDA returns a null handle.
173    pub unsafe fn import_opaque_win32_name(
174        context: &Arc<Context>,
175        name: *const c_void,
176        size: usize,
177        flags: ExternalMemoryFlags,
178    ) -> Result<Self> {
179        if name.is_null() {
180            return Err(Error::NullHandle);
181        }
182
183        let mut desc = handle_desc(ExternalMemoryHandleType::OpaqueWin32, size, flags)?;
184        desc.handle.win32.handle = ptr::null_mut();
185        desc.handle.win32.name = name;
186        // SAFETY: `name` is non-null, and the caller guarantees it is a NUL-terminated UTF-16 name of a compatible object of `size` bytes.
187        unsafe { Self::import(context, &desc, size) }
188    }
189
190    unsafe fn import(
191        context: &Arc<Context>,
192        desc: &driver::CUDA_EXTERNAL_MEMORY_HANDLE_DESC,
193        size: usize,
194    ) -> Result<Self> {
195        context.bind()?;
196        let mut handle = ptr::null_mut();
197        // SAFETY: `handle` is a local output, `desc` comes from `handle_desc` with a nonzero size, and the importing function's caller guarantees the external handle is valid.
198        unsafe {
199            try_ffi!(driver::cuImportExternalMemory(&raw mut handle, desc))?;
200        }
201        // SAFETY: CUDA returned a new import of `size` bytes in `context`, which was bound for the call, and nothing else owns it; `from_raw` rejects a null handle.
202        unsafe {
203            Self::from_raw(RawExternalMemory {
204                handle,
205                size,
206                context: Arc::clone(context),
207            })
208        }
209    }
210
211    /// Consumes this import and maps uninitialized typed storage.
212    ///
213    /// One import owns one native mapping.
214    /// Use borrowed views and splits for subranges.
215    /// This avoids overlapping native mappings with distinct virtual aliases and coherence requirements.
216    /// Mapping establishes no claim about externally produced values or completion.
217    /// Offset and size must also satisfy the originating API's alignment requirements.
218    ///
219    /// # Errors
220    ///
221    /// Returns an error if the typed byte count or range end overflows, the range exceeds the imported object, the context cannot be bound, or CUDA rejects the mapping.
222    /// Also rejects a null nonempty mapping, a mapping address not aligned for `T`, or an invalid mapped address range.
223    /// The consumed import is released on failure unless a native mapping cannot be safely freed.
224    ///
225    /// # Panics
226    ///
227    /// Panics if `T`'s alignment cannot be represented by a 64-bit device address.
228    pub fn map_buffer<T: DeviceRepr>(
229        self,
230        offset_bytes: usize,
231        length: usize,
232    ) -> Result<MappedBuffer<MaybeUninit<T>>> {
233        let () = T::LAYOUT;
234        let bytes = checked_bytes::<T>(length, "mapped buffer byte size")?;
235        let end = offset_bytes
236            .checked_add(bytes)
237            .ok_or_else(|| Error::out_of_range("mapped buffer end"))?;
238        if end > self.size {
239            return Err(Error::buffer_too_small("external memory", end, self.size));
240        }
241
242        self.context.bind()?;
243        let mut pointer = 0;
244        if bytes != 0 {
245            let desc = driver::CUDA_EXTERNAL_MEMORY_BUFFER_DESC {
246                offset: to_u64(offset_bytes, "mapped buffer offset")?,
247                size: to_u64(bytes, "mapped buffer byte size")?,
248                flags: 0,
249                reserved: [0; 16],
250            };
251            // SAFETY: `self` owns the live import, `offset_bytes + bytes` was checked against its size above, and `pointer` is a local output.
252            unsafe {
253                try_ffi!(driver::cuExternalMemoryGetMappedBuffer(
254                    &raw mut pointer,
255                    self.handle,
256                    &raw const desc
257                ))?;
258            }
259            if pointer == 0 {
260                return Err(Error::NullHandle);
261            }
262        }
263
264        let address = to_usize(pointer, "mapped buffer address")?;
265        let allocation = Arc::new(MappedAllocation {
266            memory: ManuallyDrop::new(self),
267            ptr: ptr::without_provenance_mut(address),
268            bytes,
269            offset: offset_bytes,
270            id: AllocationId::create(),
271        });
272        // SAFETY: `allocation.ptr` is the mapping CUDA just returned for `bytes` bytes in the import's context, and `from_raw_parts` validates the address range.
273        unsafe {
274            DeviceRegion::from_raw_parts(
275                allocation.context(),
276                allocation.id,
277                allocation.ptr,
278                bytes,
279            )?
280        };
281
282        if bytes != 0
283            && !pointer.is_multiple_of(
284                u64::try_from(align_of::<T>()).expect("alignment fits a device address"),
285            )
286        {
287            return Err(Error::misaligned("mapped buffer address", align_of::<T>()));
288        }
289        Ok(MappedBuffer {
290            allocation,
291            ptr: ptr::without_provenance_mut(address),
292            length,
293        })
294    }
295
296    /// Returns the byte size declared for the imported external-memory object.
297    #[must_use]
298    pub const fn byte_len(&self) -> usize {
299        self.size
300    }
301
302    /// Returns the borrowed native import handle without transferring ownership.
303    #[must_use]
304    pub const fn as_raw(&self) -> driver::CUexternalMemory {
305        self.handle
306    }
307
308    /// Returns the actual CUDA import context.
309    #[must_use]
310    pub fn context(&self) -> &Arc<Context> {
311        &self.context
312    }
313
314    /// Takes ownership of an unmapped native external-memory import.
315    ///
316    /// # Safety
317    ///
318    /// `raw.handle` must be live in `raw.context`, have the stated size, and have no other destroying owner or mapped buffers.
319    /// Retain external backing resources, coordinate foreign accesses, and prevent independently mutable aliases.
320    ///
321    /// # Errors
322    ///
323    /// Returns an error if `raw.handle` is null or `raw.size` is zero.
324    pub unsafe fn from_raw(raw: RawExternalMemory) -> Result<Self> {
325        if raw.handle.is_null() {
326            return Err(Error::NullHandle);
327        }
328
329        if raw.size == 0 {
330            return Err(Error::not_positive("external memory size"));
331        }
332        Ok(Self {
333            handle: raw.handle,
334            size: raw.size,
335            context: raw.context,
336        })
337    }
338
339    /// Transfers the unmapped native handle, byte size, and context to its next owner.
340    ///
341    /// Bind the returned context before use and retain it through native destruction.
342    #[must_use]
343    pub fn into_raw(self) -> RawExternalMemory {
344        let memory = ManuallyDrop::new(self);
345        RawExternalMemory {
346            handle: memory.handle,
347            size: memory.size,
348            // SAFETY: ManuallyDrop prevents destruction, and the context owner is transferred exactly once.
349            context: unsafe { ptr::read(&raw const memory.context) },
350        }
351    }
352}
353
354impl Drop for ExternalMemory {
355    fn drop(&mut self) {
356        if let Err(error) = self.context.bind() {
357            report_cleanup_failure(
358                "bind the cuda context to destroy",
359                "cuda external memory",
360                &error,
361            );
362            return;
363        }
364
365        // SAFETY: this wrapper owns the live unmapped import in the bound context.
366        if let Err(error) = unsafe { try_ffi!(driver::cuDestroyExternalMemory(self.handle)) } {
367            report_cleanup_failure("destroy", "cuda external memory", &error);
368        }
369    }
370}
371
372// SAFETY: a `CUexternalMemory` may be used and destroyed from any thread, since driver calls are thread-safe and the owner binds its retained context before each call.
373unsafe impl Send for ExternalMemory {}
374
375// SAFETY: shared references only read the handle and immutable metadata; mapping consumes the owner and destruction needs `&mut`.
376unsafe impl Sync for ExternalMemory {}
377
378// SAFETY: the mapping is a device address with no host-thread affinity, and its import owner is `Send`; drop binds the retained context before freeing it.
379unsafe impl Send for MappedAllocation {}
380
381// SAFETY: shared references expose only the immutable address, size, and identity; access to the device bytes goes through typed borrows or unsafe contracts.
382unsafe impl Sync for MappedAllocation {}
383
384impl MappedAllocation {
385    /// Returns the stable allocation identity shared by views and casts of this mapping.
386    #[must_use]
387    pub const fn id(&self) -> AllocationId {
388        self.id
389    }
390
391    /// Returns the CUDA context retained by the imported-memory owner.
392    #[must_use]
393    pub fn context(&self) -> &Arc<Context> {
394        self.memory.context()
395    }
396
397    /// Returns the device mapping's raw byte address without granting initialized access or host accessibility.
398    #[must_use]
399    pub const fn as_ptr(&self) -> *mut u8 {
400        self.ptr
401    }
402
403    /// Returns the byte size of this native mapping.
404    #[must_use]
405    pub const fn byte_len(&self) -> usize {
406        self.bytes
407    }
408
409    /// Returns the offset of this native mapping in the original external object.
410    #[must_use]
411    pub const fn external_offset_bytes(&self) -> usize {
412        self.offset
413    }
414
415    /// Borrows the imported-memory owner retained until after the native mapping is freed.
416    #[must_use]
417    pub fn external_memory(&self) -> &ExternalMemory {
418        &self.memory
419    }
420}
421
422// SAFETY: this owner retains the complete native mapping, actual context, and stable allocation identity.
423unsafe impl DeviceRegionProvider for MappedAllocation {
424    fn region(&self) -> DeviceRegion<'_> {
425        // SAFETY: all bytes belong to this live native mapping and its retained import context.
426        unsafe { DeviceRegion::from_raw_parts(self.context(), self.id, self.ptr, self.bytes) }
427            .expect("native mapping bounds validated during construction")
428    }
429}
430
431impl Drop for MappedAllocation {
432    fn drop(&mut self) {
433        // Preserve the imported memory and its context if the native mapping could still be live.
434        if !self.ptr.is_null() {
435            if let Err(error) = self.context().bind() {
436                report_cleanup_failure(
437                    "bind the cuda context to free",
438                    "cuda mapped external memory buffer",
439                    &error,
440                );
441                return;
442            }
443
444            let address = self.ptr.addr() as driver::CUdeviceptr;
445            // SAFETY: this is the last owner of the mapping CUDA returned for this import, and its context was bound above.
446            let result = unsafe { try_ffi!(driver::cuMemFree_v2(address)) };
447            if let Err(error) = result {
448                report_cleanup_failure("free", "cuda mapped external memory buffer", &error);
449                return;
450            }
451        }
452
453        // SAFETY: native mapping destruction completed before destroying its sole imported-memory owner.
454        unsafe { ManuallyDrop::drop(&mut self.memory) };
455    }
456}
457
458impl<T: DeviceRepr> MappedBuffer<T> {
459    /// Returns a device pointer to the buffer's typed storage without granting host accessibility.
460    #[must_use]
461    pub const fn as_ptr(&self) -> *const T {
462        self.ptr
463    }
464
465    /// Returns a mutable device pointer without extending the allocation lifetime or granting access after this borrow.
466    pub const fn as_mut_ptr(&mut self) -> *mut T {
467        self.ptr
468    }
469
470    /// Returns the number of typed storage elements exposed by this buffer.
471    #[must_use]
472    pub const fn len(&self) -> usize {
473        self.length
474    }
475
476    /// Returns whether this buffer exposes zero typed elements.
477    #[must_use]
478    pub const fn is_empty(&self) -> bool {
479        self.length == 0
480    }
481
482    /// Returns the byte size of the exposed typed range, which can be shorter than the retained native mapping.
483    ///
484    /// # Panics
485    ///
486    /// Panics if the stored length violates the byte-size invariant checked during construction and casts.
487    #[must_use]
488    pub fn byte_len(&self) -> usize {
489        checked_bytes::<T>(self.length, "mapped buffer byte size")
490            .expect("mapped byte length validated during construction")
491    }
492
493    /// Returns the CUDA context owning the retained external-memory mapping.
494    #[must_use]
495    pub fn context(&self) -> &Arc<Context> {
496        self.allocation.context()
497    }
498
499    /// Borrows the complete native mapping owner retained by this typed buffer.
500    #[must_use]
501    pub fn allocation(&self) -> &Arc<MappedAllocation> {
502        &self.allocation
503    }
504
505    /// Borrows this buffer as a typed device view.
506    #[must_use]
507    pub fn view(&self) -> DeviceView<'_, T> {
508        DeviceView::from_buffer(self)
509    }
510
511    /// Exclusively borrows this buffer as a mutable typed device view.
512    pub fn view_mut(&mut self) -> DeviceViewMut<'_, T> {
513        DeviceViewMut::from_buffer(self)
514    }
515
516    /// Reinterprets initialized bytes while preserving the complete native mapping and imported owner.
517    ///
518    /// # Errors
519    ///
520    /// Returns an error holding `self` if the target type has zero size, the byte count is not a multiple of its size, or a nonempty mapping address is not aligned for it.
521    pub fn cast<U: AnyBitPatternDeviceRepr>(self) -> StdResult<MappedBuffer<U>, Self>
522    where
523        T: NoUninitDeviceRepr,
524    {
525        let () = T::LAYOUT;
526        let () = U::LAYOUT;
527        let bytes = self.byte_len();
528        if size_of::<U>() == 0
529            || !bytes.is_multiple_of(size_of::<U>())
530            || (bytes != 0 && !self.ptr.addr().is_multiple_of(align_of::<U>()))
531        {
532            return Err(self);
533        }
534        Ok(MappedBuffer {
535            allocation: self.allocation,
536            ptr: self.ptr.cast(),
537            length: bytes / size_of::<U>(),
538        })
539    }
540
541    /// Preserves the mapping and element count while discarding the initialized-value claim.
542    #[must_use]
543    pub fn into_uninit(self) -> MappedBuffer<MaybeUninit<T>> {
544        MappedBuffer {
545            allocation: self.allocation,
546            ptr: self.ptr.cast(),
547            length: self.length,
548        }
549    }
550}
551
552impl<T: DeviceRepr> MappedBuffer<MaybeUninit<T>> {
553    /// Exclusively borrows uninitialized storage as an output view without exposing initialized `T` values.
554    pub fn output(&mut self) -> DeviceOutputView<'_, T> {
555        DeviceOutputView::from_output(self)
556    }
557
558    /// Reinterprets uninitialized storage without claiming initialized bytes.
559    ///
560    /// # Errors
561    ///
562    /// Returns an error holding `self` if the target type has zero size, the byte count is not a multiple of its size, or a nonempty mapping address is not aligned for it.
563    pub fn cast_uninit<U: DeviceRepr>(self) -> StdResult<MappedBuffer<MaybeUninit<U>>, Self> {
564        let () = U::LAYOUT;
565        let bytes = self.byte_len();
566        if size_of::<U>() == 0
567            || !bytes.is_multiple_of(size_of::<U>())
568            || (bytes != 0 && !self.ptr.addr().is_multiple_of(align_of::<U>()))
569        {
570            return Err(self);
571        }
572        Ok(MappedBuffer {
573            allocation: self.allocation,
574            ptr: self.ptr.cast(),
575            length: bytes / size_of::<U>(),
576        })
577    }
578
579    /// Marks every element initialized after external or CUDA production.
580    ///
581    /// # Safety
582    ///
583    /// All elements must contain valid T values and all producers must complete or be ordered before every consumer.
584    /// Synchronize foreign runtime accesses and retain exclusive access until production completes.
585    #[must_use]
586    pub unsafe fn assume_init(self) -> MappedBuffer<T> {
587        let () = T::LAYOUT;
588        MappedBuffer {
589            allocation: self.allocation,
590            ptr: self.ptr.cast(),
591            length: self.length,
592        }
593    }
594
595    /// Exposes only a produced prefix, retaining the complete native mapping for deallocation.
596    ///
597    /// # Safety
598    ///
599    /// Prefix values must be valid and producer completion and foreign access must satisfy `assume_init`.
600    ///
601    /// # Errors
602    ///
603    /// Returns an error if `length` exceeds the buffer's element count.
604    pub unsafe fn assume_init_prefix(mut self, length: usize) -> Result<MappedBuffer<T>> {
605        if length > self.length {
606            return Err(Error::buffer_too_small(
607                "mapped buffer",
608                length,
609                self.length,
610            ));
611        }
612
613        self.length = length;
614        // SAFETY: the caller guarantees the first `length` elements, now the whole buffer, are valid and their producers are ordered before consumers.
615        unsafe { Ok(self.assume_init()) }
616    }
617}
618
619// SAFETY: the buffer holds a device pointer and an `Arc` of a `Send + Sync` mapping owner, so moving it is as safe as moving `T`.
620unsafe impl<T: DeviceRepr + Send> Send for MappedBuffer<T> {}
621
622// SAFETY: shared references expose only the pointer and length; writes need `&mut self`, so sharing is as safe as sharing `T`.
623unsafe impl<T: DeviceRepr + Sync> Sync for MappedBuffer<T> {}
624
625// SAFETY: typed handles preserve the owner's identity and expose only their validated leading byte range.
626unsafe impl<T: DeviceRepr> DeviceRegionProvider for MappedBuffer<T> {
627    fn region(&self) -> DeviceRegion<'_> {
628        self.allocation
629            .region()
630            .slice(..self.byte_len())
631            .expect("mapped range validated during construction")
632    }
633}
634
635// SAFETY: `ptr` and `length` describe the typed range validated by `map_buffer` or a checked cast, inside the retained mapping.
636unsafe impl<T: DeviceRepr> DeviceRange<T> for MappedBuffer<T> {
637    fn as_device_ptr(&self) -> *const T {
638        self.ptr
639    }
640
641    fn len(&self) -> usize {
642        self.length
643    }
644}
645
646// SAFETY: the typed owner or view preserves initialized values for its borrow.
647unsafe impl<T: DeviceRepr> DeviceSlice<T> for MappedBuffer<T> {}
648
649// SAFETY: `&mut self` gives exclusive access to the owned range, and writes keep `T` values valid.
650unsafe impl<T: DeviceRepr> DeviceSliceMut<T> for MappedBuffer<T> {}
651
652// SAFETY: the owned range is writable device storage for `length` elements of `T`, borrowed exclusively through `&mut self`.
653unsafe impl<T: DeviceRepr> DeviceOutput<T> for MappedBuffer<T> {
654    fn as_mut_ptr(&mut self) -> *mut T {
655        self.ptr
656    }
657}
658
659// SAFETY: output metadata describes the same live typed range without initialized reads.
660unsafe impl<T: DeviceRepr> DeviceRange<T> for MappedBuffer<MaybeUninit<T>> {
661    fn len(&self) -> usize {
662        self.length
663    }
664}
665
666// SAFETY: `MaybeUninit<T>` has the layout of `T`, so the owned range is writable storage for `length` elements of `T`, borrowed exclusively through `&mut self`.
667unsafe impl<T: DeviceRepr> DeviceOutput<T> for MappedBuffer<MaybeUninit<T>> {
668    fn as_mut_ptr(&mut self) -> *mut T {
669        self.ptr.cast()
670    }
671}
672
673impl<T: DeviceRepr> PushKernelArg for &MappedBuffer<T> {
674    fn push_to(self, params: &mut KernelParameters<'_>) {
675        params.device_input(self);
676    }
677}
678
679impl<T: DeviceRepr> PushKernelArg for &mut MappedBuffer<T> {
680    fn push_to(self, params: &mut KernelParameters<'_>) {
681        params.device_slice_mut(self);
682    }
683}
684
685fn handle_desc(
686    handle_type: ExternalMemoryHandleType,
687    size: usize,
688    flags: ExternalMemoryFlags,
689) -> Result<driver::CUDA_EXTERNAL_MEMORY_HANDLE_DESC> {
690    if size == 0 {
691        return Err(Error::not_positive("external memory size"));
692    }
693
694    Ok(driver::CUDA_EXTERNAL_MEMORY_HANDLE_DESC {
695        type_: handle_type.into(),
696        handle: driver::CUDA_EXTERNAL_MEMORY_HANDLE_DESC_st__bindgen_ty_1::default(),
697        size: to_u64(size, "external memory size")?,
698        flags: flags.bits(),
699        reserved: [0; 16],
700    })
701}
702
703impl_enum_display!(ExternalMemoryHandleType, {
704    ExternalMemoryHandleType::OpaqueFileDescriptor => "CU_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD",
705    ExternalMemoryHandleType::OpaqueWin32 => "CU_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_WIN32",
706    ExternalMemoryHandleType::OpaqueWin32Kmt => "CU_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_WIN32_KMT",
707    ExternalMemoryHandleType::DmaBufferFileDescriptor => "CU_EXTERNAL_MEMORY_HANDLE_TYPE_DMABUF_FD",
708});