singe-cuda 0.1.0

Safe Rust wrappers for the CUDA driver and runtime APIs, including runtime compilation of CUDA C++ and NVTX annotations.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
//! Safe ownership wrappers for CUDA external memory imports.

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! {
    /// Kind of operating-system handle an external memory import receives.
    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, TryFromPrimitive, IntoPrimitive)]
    #[repr(u32)]
    #[non_exhaustive]
    pub enum ExternalMemoryHandleType: driver::CUexternalMemoryHandleType {
        /// Handle is an opaque file descriptor.
        OpaqueFileDescriptor = CU_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD,
        /// Handle is an opaque shared NT handle.
        OpaqueWin32 = CU_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_WIN32,
        /// Handle is an opaque, globally shared handle.
        OpaqueWin32Kmt = CU_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_WIN32_KMT,
        /// Handle is a `dma_buf` file descriptor.
        DmaBufferFileDescriptor = CU_EXTERNAL_MEMORY_HANDLE_TYPE_DMABUF_FD,
    }
}

bitflags::bitflags! {
    /// Flags describing the external allocation imported into CUDA.
    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
    pub struct ExternalMemoryFlags: u32 {
        /// The external resource has a dedicated memory allocation.
        const DEDICATED = driver::CUDA_EXTERNAL_MEMORY_DEDICATED;
    }
}

impl Display for ExternalMemoryFlags {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        parser::to_writer(self, f)
    }
}

/// Raw ownership of an unmapped external-memory import and its context.
///
/// Destroy `handle` while `context` is alive, or re-adopt the value with [`ExternalMemory::from_raw`].
#[derive(Debug)]
pub struct RawExternalMemory {
    /// Native external-memory handle.
    pub handle: driver::CUexternalMemory,
    /// Imported size in bytes.
    pub size: usize,
    /// Context the memory was imported into.
    pub context: Arc<Context>,
}

/// Owns an imported external-memory object in an explicit CUDA context.
#[derive(Debug)]
pub struct ExternalMemory {
    handle: driver::CUexternalMemory,
    size: usize,
    context: Arc<Context>,
}

/// Retains a native mapping, its imported memory object, and the actual CUDA context.
///
/// Raw addresses and regions grant neither initialized access nor permission to enqueue conflicting work.
#[derive(Debug)]
pub struct MappedAllocation {
    memory: ManuallyDrop<ExternalMemory>,
    ptr: *mut u8,
    bytes: usize,
    offset: usize,
    id: AllocationId,
}

/// Typed storage in one native external-memory mapping.
///
/// Casts and initialized prefixes retain the original mapping and import independently of typed access.
#[derive(Debug)]
pub struct MappedBuffer<T: DeviceRepr> {
    allocation: Arc<MappedAllocation>,
    ptr: *mut T,
    length: usize,
}

impl ExternalMemory {
    /// Imports an opaque file descriptor in `context`.
    ///
    /// # Safety
    ///
    /// `fd` must reference a compatible memory object of `size` bytes on this context's device.
    /// CUDA takes descriptor ownership on success.
    /// Do not use it afterward.
    /// Keep external backing resources alive and coordinate foreign accesses with all CUDA accesses.
    /// Do not create independently mutable imports of overlapping external storage.
    ///
    /// # Errors
    ///
    /// Returns an error if `size` is zero, the context cannot be bound, CUDA rejects the import, or CUDA returns a null handle.
    /// Descriptor ownership remains with the caller if the native import fails.
    #[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;
        // SAFETY: the caller guarantees `fd` references a compatible object of `size` bytes and hands its ownership to CUDA.
        unsafe { Self::import(context, &desc, size) }
    }

    /// Imports an opaque Win32 shared handle in `context`.
    ///
    /// # Safety
    ///
    /// The handle must reference a compatible live external allocation of the stated size on this device.
    /// Ownership of the Win32 handle remains with the caller.
    /// Retain foreign backing resources, coordinate every foreign access, and prevent independently mutable aliases.
    ///
    /// # Errors
    ///
    /// 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.
    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();
        // SAFETY: `handle` is non-null, and the caller guarantees it references a compatible live allocation of `size` bytes.
        unsafe { Self::import(context, &desc, size) }
    }

    /// Imports a named Win32 external memory object in `context`.
    ///
    /// # Safety
    ///
    /// `name` must reference a valid null-terminated UTF-16 object name throughout import.
    /// The object must be compatible with this device and have the stated size.
    /// Retain foreign backing resources, coordinate every foreign access, and prevent independently mutable aliases.
    ///
    /// # Errors
    ///
    /// 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.
    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;
        // SAFETY: `name` is non-null, and the caller guarantees it is a NUL-terminated UTF-16 name of a compatible object of `size` bytes.
        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();
        // 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.
        unsafe {
            try_ffi!(driver::cuImportExternalMemory(&raw mut handle, desc))?;
        }
        // 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.
        unsafe {
            Self::from_raw(RawExternalMemory {
                handle,
                size,
                context: Arc::clone(context),
            })
        }
    }

    /// Consumes this import and maps uninitialized typed storage.
    ///
    /// One import owns one native mapping.
    /// Use borrowed views and splits for subranges.
    /// This avoids overlapping native mappings with distinct virtual aliases and coherence requirements.
    /// Mapping establishes no claim about externally produced values or completion.
    /// Offset and size must also satisfy the originating API's alignment requirements.
    ///
    /// # Errors
    ///
    /// 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.
    /// Also rejects a null nonempty mapping, a mapping address not aligned for `T`, or an invalid mapped address range.
    /// The consumed import is released on failure unless a native mapping cannot be safely freed.
    ///
    /// # Panics
    ///
    /// Panics if `T`'s alignment cannot be represented by a 64-bit device address.
    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],
            };
            // SAFETY: `self` owns the live import, `offset_bytes + bytes` was checked against its size above, and `pointer` is a local output.
            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(),
        });
        // 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.
        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,
        })
    }

    /// Returns the byte size declared for the imported external-memory object.
    #[must_use]
    pub const fn byte_len(&self) -> usize {
        self.size
    }

    /// Returns the borrowed native import handle without transferring ownership.
    #[must_use]
    pub const fn as_raw(&self) -> driver::CUexternalMemory {
        self.handle
    }

    /// Returns the actual CUDA import context.
    #[must_use]
    pub fn context(&self) -> &Arc<Context> {
        &self.context
    }

    /// Takes ownership of an unmapped native external-memory import.
    ///
    /// # Safety
    ///
    /// `raw.handle` must be live in `raw.context`, have the stated size, and have no other destroying owner or mapped buffers.
    /// Retain external backing resources, coordinate foreign accesses, and prevent independently mutable aliases.
    ///
    /// # Errors
    ///
    /// Returns an error if `raw.handle` is null or `raw.size` is zero.
    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,
        })
    }

    /// Transfers the unmapped native handle, byte size, and context to its next owner.
    ///
    /// Bind the returned context before use and retain it through native destruction.
    #[must_use]
    pub fn into_raw(self) -> RawExternalMemory {
        let memory = ManuallyDrop::new(self);
        RawExternalMemory {
            handle: memory.handle,
            size: memory.size,
            // SAFETY: ManuallyDrop prevents destruction, and the context owner is transferred exactly once.
            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;
        }

        // SAFETY: this wrapper owns the live unmapped import in the bound context.
        if let Err(error) = unsafe { try_ffi!(driver::cuDestroyExternalMemory(self.handle)) } {
            report_cleanup_failure("destroy", "cuda external memory", &error);
        }
    }
}

// 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.
unsafe impl Send for ExternalMemory {}

// SAFETY: shared references only read the handle and immutable metadata; mapping consumes the owner and destruction needs `&mut`.
unsafe impl Sync for ExternalMemory {}

// 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.
unsafe impl Send for MappedAllocation {}

// SAFETY: shared references expose only the immutable address, size, and identity; access to the device bytes goes through typed borrows or unsafe contracts.
unsafe impl Sync for MappedAllocation {}

impl MappedAllocation {
    /// Returns the stable allocation identity shared by views and casts of this mapping.
    #[must_use]
    pub const fn id(&self) -> AllocationId {
        self.id
    }

    /// Returns the CUDA context retained by the imported-memory owner.
    #[must_use]
    pub fn context(&self) -> &Arc<Context> {
        self.memory.context()
    }

    /// Returns the device mapping's raw byte address without granting initialized access or host accessibility.
    #[must_use]
    pub const fn as_ptr(&self) -> *mut u8 {
        self.ptr
    }

    /// Returns the byte size of this native mapping.
    #[must_use]
    pub const fn byte_len(&self) -> usize {
        self.bytes
    }

    /// Returns the offset of this native mapping in the original external object.
    #[must_use]
    pub const fn external_offset_bytes(&self) -> usize {
        self.offset
    }

    /// Borrows the imported-memory owner retained until after the native mapping is freed.
    #[must_use]
    pub fn external_memory(&self) -> &ExternalMemory {
        &self.memory
    }
}

// SAFETY: this owner retains the complete native mapping, actual context, and stable allocation identity.
unsafe impl DeviceRegionProvider for MappedAllocation {
    fn region(&self) -> DeviceRegion<'_> {
        // SAFETY: all bytes belong to this live native mapping and its retained import context.
        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) {
        // Preserve the imported memory and its context if the native mapping could still be live.
        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;
            // SAFETY: this is the last owner of the mapping CUDA returned for this import, and its context was bound above.
            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;
            }
        }

        // SAFETY: native mapping destruction completed before destroying its sole imported-memory owner.
        unsafe { ManuallyDrop::drop(&mut self.memory) };
    }
}

impl<T: DeviceRepr> MappedBuffer<T> {
    /// Returns a device pointer to the buffer's typed storage without granting host accessibility.
    #[must_use]
    pub const fn as_ptr(&self) -> *const T {
        self.ptr
    }

    /// Returns a mutable device pointer without extending the allocation lifetime or granting access after this borrow.
    pub const fn as_mut_ptr(&mut self) -> *mut T {
        self.ptr
    }

    /// Returns the number of typed storage elements exposed by this buffer.
    #[must_use]
    pub const fn len(&self) -> usize {
        self.length
    }

    /// Returns whether this buffer exposes zero typed elements.
    #[must_use]
    pub const fn is_empty(&self) -> bool {
        self.length == 0
    }

    /// Returns the byte size of the exposed typed range, which can be shorter than the retained native mapping.
    ///
    /// # Panics
    ///
    /// Panics if the stored length violates the byte-size invariant checked during construction and casts.
    #[must_use]
    pub fn byte_len(&self) -> usize {
        checked_bytes::<T>(self.length, "mapped buffer byte size")
            .expect("mapped byte length validated during construction")
    }

    /// Returns the CUDA context owning the retained external-memory mapping.
    #[must_use]
    pub fn context(&self) -> &Arc<Context> {
        self.allocation.context()
    }

    /// Borrows the complete native mapping owner retained by this typed buffer.
    #[must_use]
    pub fn allocation(&self) -> &Arc<MappedAllocation> {
        &self.allocation
    }

    /// Borrows this buffer as a typed device view.
    #[must_use]
    pub fn view(&self) -> DeviceView<'_, T> {
        DeviceView::from_buffer(self)
    }

    /// Exclusively borrows this buffer as a mutable typed device view.
    pub fn view_mut(&mut self) -> DeviceViewMut<'_, T> {
        DeviceViewMut::from_buffer(self)
    }

    /// Reinterprets initialized bytes while preserving the complete native mapping and imported owner.
    ///
    /// # Errors
    ///
    /// 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.
    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>(),
        })
    }

    /// Preserves the mapping and element count while discarding the initialized-value claim.
    #[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>> {
    /// Exclusively borrows uninitialized storage as an output view without exposing initialized `T` values.
    pub fn output(&mut self) -> DeviceOutputView<'_, T> {
        DeviceOutputView::from_output(self)
    }

    /// Reinterprets uninitialized storage without claiming initialized bytes.
    ///
    /// # Errors
    ///
    /// 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.
    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>(),
        })
    }

    /// Marks every element initialized after external or CUDA production.
    ///
    /// # Safety
    ///
    /// All elements must contain valid T values and all producers must complete or be ordered before every consumer.
    /// Synchronize foreign runtime accesses and retain exclusive access until production completes.
    #[must_use]
    pub unsafe fn assume_init(self) -> MappedBuffer<T> {
        let () = T::LAYOUT;
        MappedBuffer {
            allocation: self.allocation,
            ptr: self.ptr.cast(),
            length: self.length,
        }
    }

    /// Exposes only a produced prefix, retaining the complete native mapping for deallocation.
    ///
    /// # Safety
    ///
    /// Prefix values must be valid and producer completion and foreign access must satisfy `assume_init`.
    ///
    /// # Errors
    ///
    /// Returns an error if `length` exceeds the buffer's element count.
    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;
        // SAFETY: the caller guarantees the first `length` elements, now the whole buffer, are valid and their producers are ordered before consumers.
        unsafe { Ok(self.assume_init()) }
    }
}

// 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`.
unsafe impl<T: DeviceRepr + Send> Send for MappedBuffer<T> {}

// SAFETY: shared references expose only the pointer and length; writes need `&mut self`, so sharing is as safe as sharing `T`.
unsafe impl<T: DeviceRepr + Sync> Sync for MappedBuffer<T> {}

// SAFETY: typed handles preserve the owner's identity and expose only their validated leading byte range.
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")
    }
}

// SAFETY: `ptr` and `length` describe the typed range validated by `map_buffer` or a checked cast, inside the retained mapping.
unsafe impl<T: DeviceRepr> DeviceRange<T> for MappedBuffer<T> {
    fn as_device_ptr(&self) -> *const T {
        self.ptr
    }

    fn len(&self) -> usize {
        self.length
    }
}

// SAFETY: the typed owner or view preserves initialized values for its borrow.
unsafe impl<T: DeviceRepr> DeviceSlice<T> for MappedBuffer<T> {}

// SAFETY: `&mut self` gives exclusive access to the owned range, and writes keep `T` values valid.
unsafe impl<T: DeviceRepr> DeviceSliceMut<T> for MappedBuffer<T> {}

// SAFETY: the owned range is writable device storage for `length` elements of `T`, borrowed exclusively through `&mut self`.
unsafe impl<T: DeviceRepr> DeviceOutput<T> for MappedBuffer<T> {
    fn as_mut_ptr(&mut self) -> *mut T {
        self.ptr
    }
}

// SAFETY: output metadata describes the same live typed range without initialized reads.
unsafe impl<T: DeviceRepr> DeviceRange<T> for MappedBuffer<MaybeUninit<T>> {
    fn len(&self) -> usize {
        self.length
    }
}

// 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`.
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",
});