Skip to main content

singe_cuda/memory/
managed.rs

1use std::{
2    marker::PhantomData, mem::MaybeUninit, ptr, result::Result as StdResult, slice, sync::Arc,
3};
4
5use singe_cuda_sys::runtime;
6
7use crate::{
8    context::Context,
9    device::DeviceAttribute,
10    error::{Error, Result},
11    memory::{
12        DeviceAllocation, DeviceDeallocation, DeviceMemory, MemoryAttachFlags, MemoryLocation,
13        location_info,
14    },
15    stream::{AsStream, Stream, StreamBinding},
16    try_ffi,
17    types::{DevicePtr, MemoryAdvise},
18    utility::{checked_bytes, to_u64},
19    view::{
20        AnyBitPatternDeviceRepr, DeviceOutput, DeviceOutputView, DeviceRange, DeviceRegion,
21        DeviceRegionProvider, DeviceRepr, DeviceSlice, DeviceSliceMut, DeviceView, DeviceViewMut,
22        NoUninitDeviceRepr, ZeroableDeviceRepr, cast_length,
23    },
24};
25
26impl<T: DeviceRepr> ManagedMemory<T> {
27    /// Allocates CUDA managed memory and completes zero initialization.
28    ///
29    /// # Errors
30    ///
31    /// Returns an error if the byte size overflows, the context cannot be bound, CUDA cannot allocate the memory, access tracking fails, or CUDA cannot fill or synchronize.
32    pub fn zeroed(
33        context: &Arc<Context>,
34        length: usize,
35        attach_flags: MemoryAttachFlags,
36    ) -> Result<Self>
37    where
38        T: ZeroableDeviceRepr,
39    {
40        let mut memory = Self::create_uninit(context, length, attach_flags)?;
41        memory.set_zeroes()?;
42        // SAFETY: `set_zeroes` completed a zero fill of every element, and an all-zero `T` is valid.
43        Ok(unsafe { memory.assume_init() })
44    }
45
46    /// Allocates CUDA managed memory and completes its repeated byte fill.
47    ///
48    /// # Errors
49    ///
50    /// Returns an error if the byte size overflows, the context cannot be bound, CUDA cannot allocate the memory, access tracking fails, or CUDA cannot fill or synchronize.
51    pub fn filled(
52        context: &Arc<Context>,
53        length: usize,
54        attach_flags: MemoryAttachFlags,
55        value: u8,
56    ) -> Result<Self>
57    where
58        T: AnyBitPatternDeviceRepr,
59    {
60        let mut memory = Self::create_uninit(context, length, attach_flags)?;
61        memory.set_value(value)?;
62        // SAFETY: `set_value` completed a fill of every element, and every bit pattern is a valid `T`.
63        Ok(unsafe { memory.assume_init() })
64    }
65
66    /// Takes ownership of an existing managed allocation.
67    ///
68    /// # Safety
69    ///
70    /// `raw.ptr` must be null for an empty allocation or identify live managed storage for `raw.len` elements in `raw.context`, allocated with `cudaMallocManaged`.
71    /// The attachment flags must describe that allocation's policy.
72    /// No other owner may free it, and each element must be initialized before it is read.
73    ///
74    /// # Errors
75    ///
76    /// Returns an error if the byte length overflows or a nonempty allocation has a null pointer.
77    pub unsafe fn from_raw(raw: RawManagedMemory<T>) -> Result<Self> {
78        let RawManagedMemory {
79            ptr,
80            len,
81            attach_flags,
82            context,
83        } = raw;
84        let () = T::LAYOUT;
85        let bytes = checked_bytes::<T>(len, "byte length")?;
86        if bytes != 0 && ptr.is_null() {
87            return Err(Error::null_pointer("managed memory"));
88        }
89        Ok(Self {
90            allocation: DeviceAllocation::from_parts(
91                &context,
92                ptr.cast(),
93                bytes,
94                DeviceDeallocation::Immediate,
95            ),
96            ptr,
97            length: len,
98            attach_flags,
99            _phantom: PhantomData,
100        })
101    }
102
103    /// Transfers the allocation when no submission, graph, or foreign owner retains it.
104    ///
105    /// Returns the unchanged buffer if the allocation is shared.
106    /// On success the caller must free the pointer and keep its returned context alive until then.
107    ///
108    /// # Errors
109    ///
110    /// Returns the wrapper unchanged as the error if another owner, submission, graph, or foreign handle retains the allocation.
111    pub fn into_raw(self) -> StdResult<RawManagedMemory<T>, Self> {
112        let Self {
113            allocation,
114            ptr,
115            length,
116            attach_flags,
117            ..
118        } = self;
119        match Arc::try_unwrap(allocation) {
120            Ok(mut allocation) => {
121                let context = Arc::clone(allocation.context());
122                allocation.ptr = ptr::null_mut();
123                Ok(RawManagedMemory {
124                    ptr,
125                    len: length,
126                    attach_flags,
127                    context,
128                })
129            }
130            Err(allocation) => Err(Self {
131                allocation,
132                ptr,
133                length,
134                attach_flags,
135                _phantom: PhantomData,
136            }),
137        }
138    }
139
140    /// Returns the CUDA context retained by this allocation or pool.
141    #[must_use]
142    pub fn context(&self) -> &Arc<Context> {
143        self.allocation.context()
144    }
145
146    /// Returns the allocation owner retained by submissions, graphs, and interop users.
147    #[must_use]
148    pub fn allocation(&self) -> &Arc<DeviceAllocation> {
149        &self.allocation
150    }
151
152    /// Reinterprets initialized elements while preserving managed allocation ownership and attachment flags.
153    ///
154    /// # Errors
155    ///
156    /// Returns the allocation unchanged as the error if `U` is zero-sized, its size does not divide the exposed byte length, or a nonempty range is not aligned for `U`.
157    pub fn cast<U: AnyBitPatternDeviceRepr>(self) -> StdResult<ManagedMemory<U>, Self>
158    where
159        T: NoUninitDeviceRepr,
160    {
161        let () = T::LAYOUT;
162        let Ok(length) = cast_length::<U>(self.region()) else {
163            return Err(self);
164        };
165        Ok(ManagedMemory {
166            allocation: self.allocation,
167            ptr: self.ptr.cast(),
168            length,
169            attach_flags: self.attach_flags,
170            _phantom: PhantomData,
171        })
172    }
173
174    /// Erases initialization while retaining the managed allocation and its attachment flags.
175    #[must_use]
176    pub fn into_uninit(self) -> ManagedMemory<MaybeUninit<T>> {
177        ManagedMemory {
178            allocation: self.allocation,
179            ptr: self.ptr.cast(),
180            length: self.length,
181            attach_flags: self.attach_flags,
182            _phantom: PhantomData,
183        }
184    }
185
186    fn bind_stream(&self, stream: &Stream) -> Result<()> {
187        if stream.context() != self.context() {
188            return Err(Error::StreamContextMismatch);
189        }
190        self.context().bind()
191    }
192
193    /// Allocates CUDA managed memory without initializing its elements.
194    ///
195    /// # Errors
196    ///
197    /// Returns an error if the byte count overflows, a nonempty zero-sized allocation is requested, the attachment policy is unsupported, context binding fails, or CUDA cannot allocate managed memory.
198    pub fn create_uninit(
199        context: &Arc<Context>,
200        length: usize,
201        attach_flags: MemoryAttachFlags,
202    ) -> Result<ManagedMemory<MaybeUninit<T>>> {
203        let () = T::LAYOUT;
204        context.bind()?;
205        let bytes = checked_bytes::<T>(length, "byte length")?;
206        let ptr = if bytes == 0 {
207            ptr::null_mut()
208        } else {
209            // SAFETY: the `DeviceAllocation` below owns the pointer and frees it with a device free, its `MaybeUninit` elements need no initialization, and this wrapper orders host access through the access tracker.
210            unsafe { DeviceMemory::<MaybeUninit<T>>::alloc_managed(context, length, attach_flags)? }
211        };
212        Ok(ManagedMemory {
213            allocation: DeviceAllocation::from_parts(
214                context,
215                ptr.cast(),
216                bytes,
217                DeviceDeallocation::Immediate,
218            ),
219            ptr,
220            length,
221            attach_flags,
222            _phantom: PhantomData,
223        })
224    }
225
226    /// Returns the number of elements in the logical allocation range.
227    #[must_use]
228    pub const fn len(&self) -> usize {
229        self.length
230    }
231
232    /// Returns whether the logical allocation range contains no elements.
233    #[must_use]
234    pub const fn is_empty(&self) -> bool {
235        self.length == 0
236    }
237
238    /// Returns the size of the logical allocation range in bytes.
239    ///
240    /// # Panics
241    ///
242    /// Panics if the element count multiplied by the element size overflows `usize`.
243    /// Allocation construction validates this size, so this condition cannot occur for a valid allocation.
244    #[must_use]
245    pub fn byte_len(&self) -> usize {
246        checked_bytes::<T>(self.length, "byte length").expect("managed memory byte length overflow")
247    }
248
249    /// Returns the attachment policy recorded when the managed allocation was created.
250    #[must_use]
251    pub const fn attach_flags(&self) -> MemoryAttachFlags {
252        self.attach_flags
253    }
254
255    /// Returns the allocation’s CUDA-accessible element pointer without synchronizing pending work.
256    #[must_use]
257    pub const fn as_ptr(&self) -> *const T {
258        self.ptr
259    }
260
261    /// Returns the allocation’s CUDA-accessible mutable element pointer.
262    ///
263    /// The pointer does not establish execution ordering or permit conflicting accesses.
264    pub const fn as_mut_ptr(&mut self) -> *mut T {
265        self.ptr
266    }
267
268    /// Returns the allocation’s address as an untyped CUDA device pointer.
269    #[must_use]
270    pub const fn as_device_ptr(&self) -> DevicePtr {
271        // SAFETY: `ptr` is this live allocation's base or null, and `DevicePtr` only records the address.
272        unsafe { DevicePtr::from_raw(self.ptr.cast()) }
273    }
274
275    /// Borrows all initialized elements as a shared device view.
276    #[must_use]
277    pub fn view(&self) -> DeviceView<'_, T> {
278        DeviceView::from_buffer(self)
279    }
280
281    /// Borrows all initialized elements as an exclusive device view.
282    pub fn view_mut(&mut self) -> DeviceViewMut<'_, T> {
283        DeviceViewMut::from_buffer(self)
284    }
285
286    /// Completes submitted accesses and excludes tracked GPU work while reading managed values.
287    /// Requires [concurrent managed access](https://docs.nvidia.com/cuda/cuda-programming-guide/04-special-topics/unified-memory.html#unified-memory-on-windows-wsl-and-tegra) because unrelated streams may remain active.
288    ///
289    /// # Errors
290    ///
291    /// Returns [`Error::ManagedHostAccessUnsupported`] if the device lacks concurrent managed access.
292    /// Returns an error if the device attribute query, access tracking, or waiting for submitted work fails, before the callback runs.
293    pub fn with_host_slice<R>(&self, read: impl FnOnce(&[T]) -> R) -> Result<R> {
294        if self
295            .context()
296            .device()
297            .attribute(DeviceAttribute::ConcurrentManagedAccess)?
298            == 0
299        {
300            return Err(Error::ManagedHostAccessUnsupported);
301        }
302        self.context().with_host_access(&[self.region()], || {
303            // SAFETY: the host-access guard waited for and excludes tracked GPU work on this region, concurrent managed access was checked above, and `&self` excludes host writers.
304            Ok(read(unsafe { self.as_host_slice() }))
305        })
306    }
307
308    /// Completes submitted accesses and excludes tracked GPU work while modifying managed values.
309    /// Requires concurrent managed access support because unrelated streams may remain active.
310    ///
311    /// # Errors
312    ///
313    /// Returns [`Error::ManagedHostAccessUnsupported`] if the device lacks concurrent managed access.
314    /// Returns an error if the device attribute query, access tracking, or waiting for submitted work fails, before the callback runs.
315    pub fn with_host_slice_mut<R>(&mut self, write: impl FnOnce(&mut [T]) -> R) -> Result<R> {
316        if self
317            .context()
318            .device()
319            .attribute(DeviceAttribute::ConcurrentManagedAccess)?
320            == 0
321        {
322            return Err(Error::ManagedHostAccessUnsupported);
323        }
324
325        let context = Arc::clone(self.context());
326        let _guard = context.acquire_host_access(&[self.region()])?;
327        // SAFETY: the host-access guard waited for and excludes tracked GPU work on this region, concurrent managed access was checked above, and `&mut self` excludes other host references.
328        Ok(write(unsafe { self.as_host_slice_mut() }))
329    }
330
331    /// Returns a host slice over this managed allocation.
332    ///
333    /// # Safety
334    ///
335    /// The caller must ensure no GPU work or other CPU reference can concurrently mutate the same memory for the returned lifetime, and that the allocation is accessible from the host at the point of access.
336    #[must_use]
337    pub unsafe fn as_host_slice(&self) -> &[T] {
338        if self.is_empty() {
339            return &[];
340        }
341        // SAFETY: a nonempty allocation's `ptr` names `length` initialized values, and the caller guarantees the host can read them and nothing mutates them for the borrow.
342        unsafe { slice::from_raw_parts(self.ptr, self.length) }
343    }
344
345    /// Returns a mutable host slice over this managed allocation.
346    ///
347    /// # Safety
348    ///
349    /// The caller must ensure no GPU work or other CPU reference can concurrently access the same memory for the returned lifetime, and that the allocation is accessible from the host at the point of access.
350    pub unsafe fn as_host_slice_mut(&mut self) -> &mut [T] {
351        if self.is_empty() {
352            return &mut [];
353        }
354        // SAFETY: a nonempty allocation's `ptr` names `length` initialized values, and the caller guarantees the host can access them and nothing else does for the borrow.
355        unsafe { slice::from_raw_parts_mut(self.ptr, self.length) }
356    }
357
358    /// Fills every element with zero bytes and waits for completion.
359    ///
360    /// # Errors
361    ///
362    /// Returns an error if access tracking fails, the context cannot be bound, the byte size overflows, or CUDA cannot fill the memory or synchronize the default stream.
363    pub fn set_zeroes(&mut self) -> Result<()>
364    where
365        T: ZeroableDeviceRepr,
366    {
367        // SAFETY: `T: ZeroableDeviceRepr` makes the all-zero fill a valid `T`.
368        unsafe { self.fill_bytes(0) }
369    }
370
371    /// Fills every byte with `value` and waits for completion.
372    ///
373    /// # Errors
374    ///
375    /// Returns an error if access tracking fails, the context cannot be bound, the byte size overflows, or CUDA cannot fill the memory or synchronize the default stream.
376    pub fn set_value(&mut self, value: u8) -> Result<()>
377    where
378        T: AnyBitPatternDeviceRepr,
379    {
380        // SAFETY: `T: AnyBitPatternDeviceRepr` makes every repeated byte pattern a valid `T`.
381        unsafe { self.fill_bytes(value) }
382    }
383
384    // The caller guarantees that `value` repeated over each element is a valid `T`.
385    unsafe fn fill_bytes(&mut self, value: u8) -> Result<()> {
386        let context = Arc::clone(self.context());
387        let _access = context.acquire_host_access(&[self.region()])?;
388        self.context().bind()?;
389        let () = T::LAYOUT;
390        if self.is_empty() {
391            return Ok(());
392        }
393
394        // SAFETY: the allocation covers `length` elements, and the caller guarantees the repeated byte is a valid `T`.
395        unsafe {
396            DeviceMemory::<T>::set(self.context(), self.ptr, value, self.length)?;
397        }
398        StreamBinding::Default(Arc::clone(self.context())).synchronize()
399    }
400
401    /// Enqueues a residency prefetch of the entire managed range to `location`.
402    ///
403    /// The stream orders the request; completion is asynchronous.
404    ///
405    /// # Errors
406    ///
407    /// Returns an error if the stream belongs to another context, byte-size calculation overflows, context binding fails, or CUDA rejects the prefetch request or destination.
408    pub fn prefetch_to(&self, location: MemoryLocation, stream: &Stream) -> Result<()> {
409        self.bind_stream(stream)?;
410        DeviceMemory::<T>::prefetch(
411            // SAFETY: `self.ptr` is the base of the managed allocation that `self` owns, and `&self` keeps it allocated while CUDA enqueues the prefetch.
412            unsafe { DevicePtr::from_raw(self.ptr.cast::<()>()) },
413            checked_bytes::<T>(self.length, "byte length")?,
414            location,
415            stream,
416        )
417    }
418
419    /// Applies a managed-memory advice policy to this allocation.
420    ///
421    /// # Errors
422    ///
423    /// Returns an error if the context cannot be bound or CUDA rejects the advice or location.
424    pub fn advise(&self, advice: MemoryAdvise, location: MemoryLocation) -> Result<()> {
425        self.context().bind()?;
426        DeviceMemory::<T>::advise(
427            // SAFETY: `self.ptr` is the base of the managed allocation that `self` owns, and `&self` keeps it allocated for the call.
428            unsafe { DevicePtr::from_raw(self.ptr.cast::<()>()) },
429            checked_bytes::<T>(self.length, "byte length")?,
430            advice,
431            location,
432        )
433    }
434
435    /// Advises CUDA that this managed allocation is mostly read.
436    ///
437    /// CUDA may create read-only copies of pages on processors that read this range.
438    /// Writes remain coherent but can require additional migration or invalidation work.
439    ///
440    /// # Errors
441    ///
442    /// Returns an error if CUDA rejects the advice for this allocation.
443    pub fn set_read_mostly(&self) -> Result<()> {
444        self.advise(MemoryAdvise::SetReadMostly, Self::ignored_advice_location())
445    }
446
447    /// Removes explicit read-mostly advice from this managed allocation.
448    ///
449    /// # Errors
450    ///
451    /// Returns an error if CUDA rejects the advice for this allocation.
452    pub fn unset_read_mostly(&self) -> Result<()> {
453        self.advise(
454            MemoryAdvise::UnsetReadMostly,
455            Self::ignored_advice_location(),
456        )
457    }
458
459    /// Advises CUDA to prefer placing this managed allocation at `location`.
460    ///
461    /// This guides migration policy but does not immediately migrate pages.
462    /// Use [`ManagedMemory::prefetch_to`] when an explicit migration is desired.
463    ///
464    /// # Errors
465    ///
466    /// Returns an error if CUDA rejects the location or advice for this allocation.
467    pub fn set_preferred_location(&self, location: MemoryLocation) -> Result<()> {
468        self.advise(MemoryAdvise::SetPreferredLocation, location)
469    }
470
471    /// Clears the preferred-location advice for this managed allocation.
472    ///
473    /// # Errors
474    ///
475    /// Returns an error if CUDA rejects the advice for this allocation.
476    pub fn unset_preferred_location(&self) -> Result<()> {
477        self.advise(
478            MemoryAdvise::UnsetPreferredLocation,
479            Self::ignored_advice_location(),
480        )
481    }
482
483    /// Advises CUDA that `location` will access this managed allocation.
484    ///
485    /// This can establish or maintain mappings for the target processor without migrating the data there.
486    ///
487    /// # Errors
488    ///
489    /// Returns an error if CUDA rejects the location or advice for this allocation.
490    pub fn set_accessed_by(&self, location: MemoryLocation) -> Result<()> {
491        self.advise(MemoryAdvise::SetAccessedBy, location)
492    }
493
494    /// Clears accessed-by advice for `location`.
495    ///
496    /// # Errors
497    ///
498    /// Returns an error if CUDA rejects the location or advice for this allocation.
499    pub fn unset_accessed_by(&self, location: MemoryLocation) -> Result<()> {
500        self.advise(MemoryAdvise::UnsetAccessedBy, location)
501    }
502
503    const fn ignored_advice_location() -> MemoryLocation {
504        MemoryLocation::Host
505    }
506
507    /// Attaches this managed allocation to `stream` with the requested attach flags.
508    ///
509    /// This enqueues the attachment on `stream` and updates the stored attach flags after CUDA accepts the request.
510    ///
511    /// # Errors
512    ///
513    /// Returns an error if CUDA cannot attach the allocation to `stream`, the flags are invalid for the allocation, or a previous asynchronous launch reports an error.
514    pub fn attach_to_stream(&mut self, stream: &Stream, flags: MemoryAttachFlags) -> Result<()> {
515        self.bind_stream(stream)?;
516        let bytes = to_u64(
517            checked_bytes::<T>(self.length, "byte length")?,
518            "byte length",
519        )?;
520        // SAFETY: `stream` is live and belongs to this allocation's context, which is bound, and `self.ptr` with `bytes` names the managed allocation `self` owns.
521        unsafe {
522            try_ffi!(runtime::cudaStreamAttachMemAsync(
523                stream.as_raw(),
524                self.ptr.cast(),
525                bytes,
526                flags.bits(),
527            ))?;
528        }
529
530        self.attach_flags = flags;
531        Ok(())
532    }
533}
534
535// SAFETY: `ptr` names `length` aligned elements of the managed allocation that `allocation` keeps live, and `region` reports that same range in the owning context.
536unsafe impl<T: DeviceRepr> DeviceRange<T> for ManagedMemory<T> {
537    fn as_device_ptr(&self) -> *const T {
538        self.ptr
539    }
540
541    fn len(&self) -> usize {
542        self.length
543    }
544}
545
546// SAFETY: a `ManagedMemory<T>` is only built from initialized values, through `zeroed`, `filled`, `from_raw`, or `assume_init`, and its methods keep them valid.
547unsafe impl<T: DeviceRepr> DeviceSlice<T> for ManagedMemory<T> {}
548
549// SAFETY: `as_mut_ptr` returns the same `ptr` as `as_device_ptr`, and `&mut self` is the only way to reach it, so the mutable borrow is exclusive.
550unsafe impl<T: DeviceRepr> DeviceSliceMut<T> for ManagedMemory<T> {}
551
552// SAFETY: the region is a slice of the owning allocation's region at this buffer's offset and byte length, and `allocation` retains the context and memory while `self` lives.
553unsafe impl<T: DeviceRepr> DeviceRegionProvider for ManagedMemory<T> {
554    fn region(&self) -> DeviceRegion<'_> {
555        let offset = self.ptr.addr() - self.allocation.ptr.addr();
556        self.allocation
557            .region()
558            .slice(offset..offset + self.byte_len())
559            .expect("managed buffer exceeds its allocation")
560    }
561}
562
563impl<T: DeviceRepr> ManagedMemory<MaybeUninit<T>> {
564    /// Borrows this managed allocation as a write-only output of `T` values.
565    pub fn output(&mut self) -> DeviceOutputView<'_, T> {
566        DeviceOutputView::from_output(self)
567    }
568
569    /// Exposes an initialized prefix while retaining the full managed allocation.
570    ///
571    /// # Safety
572    ///
573    /// The prefix must contain valid initialized `T` values and all producing work must have completed.
574    ///
575    /// # Errors
576    ///
577    /// Returns an error if `length` exceeds the currently exposed element count.
578    pub unsafe fn assume_init_prefix(mut self, length: usize) -> Result<ManagedMemory<T>> {
579        if length > self.length {
580            return Err(Error::buffer_too_small("allocation", length, self.length));
581        }
582
583        self.length = length;
584        // SAFETY: the caller guarantees the first `length` elements hold valid `T` values written by completed work.
585        Ok(unsafe { self.assume_init() })
586    }
587
588    /// Marks every element initialized after its producer has completed.
589    ///
590    /// # Safety
591    ///
592    /// Every element must contain a valid `T` and all producer writes must have completed.
593    #[must_use]
594    pub unsafe fn assume_init(self) -> ManagedMemory<T> {
595        let () = T::LAYOUT;
596        ManagedMemory {
597            allocation: self.allocation,
598            ptr: self.ptr.cast(),
599            length: self.length,
600            attach_flags: self.attach_flags,
601            _phantom: PhantomData,
602        }
603    }
604}
605
606impl<T: DeviceRepr> ManagedMemory<T> {
607    /// Returns the residency of this memory range, one location per summary region.
608    ///
609    /// # Errors
610    ///
611    /// Returns an error if a granularity is invalid, the byte size overflows, the context cannot be bound, the driver entry point is unavailable, or CUDA rejects the location query.
612    pub fn location_info(
613        &self,
614        summary_granularity: usize,
615        sampling_granularity: usize,
616    ) -> Result<Vec<MemoryLocation>> {
617        self.context().bind()?;
618        // SAFETY: `self.ptr` is the base of the managed allocation that `self` owns, which stays allocated for the call.
619        unsafe {
620            location_info(
621                DevicePtr::from_raw(self.ptr.cast()),
622                checked_bytes::<T>(self.length, "byte length")?,
623                summary_granularity,
624                sampling_granularity,
625            )
626        }
627    }
628}
629
630/// Raw ownership of a managed allocation, its attachment policy, and its context.
631///
632/// Free `ptr` while `context` is alive, or re-adopt the value with [`ManagedMemory::from_raw`].
633#[derive(Debug)]
634pub struct RawManagedMemory<T> {
635    /// Base of the allocation, or null for an empty one.
636    pub ptr: *mut T,
637    /// Number of elements of `T`.
638    pub len: usize,
639    /// Attachment policy of the allocation.
640    pub attach_flags: MemoryAttachFlags,
641    /// Context the allocation belongs to.
642    pub context: Arc<Context>,
643}
644
645/// Owns a CUDA managed allocation and retains its context.
646///
647/// Host access through the guarded callback methods waits for tracked GPU work and excludes conflicting submissions for the duration of the callback.
648#[derive(Debug)]
649pub struct ManagedMemory<T: DeviceRepr> {
650    allocation: Arc<DeviceAllocation>,
651    ptr: *mut T,
652    length: usize,
653    // CUDA tracks the current visibility policy for managed memory separately
654    // from the pointer. Store the last policy requested through this wrapper so
655    // callers can reason about stream attachment without another FFI query.
656    attach_flags: MemoryAttachFlags,
657    _phantom: PhantomData<T>,
658}
659
660// SAFETY: the owner holds `T` values like a `Vec<T>`, and CUDA keeps managed memory coherent across host threads.
661unsafe impl<T: DeviceRepr + Send> Send for ManagedMemory<T> {}
662
663// SAFETY: shared host access goes through guarded callbacks or unsafe slices, and `T: Sync` covers shared reads.
664unsafe impl<T: DeviceRepr + Sync> Sync for ManagedMemory<T> {}
665
666// SAFETY: `&mut self` is exclusive over the `length` retained managed elements at `ptr`.
667unsafe impl<T: DeviceRepr> DeviceOutput<T> for ManagedMemory<T> {
668    fn as_mut_ptr(&mut self) -> *mut T {
669        let () = T::LAYOUT;
670        self.ptr
671    }
672}
673
674// SAFETY: `MaybeUninit<T>` has `T`'s layout, so the retained range holds `length` slots for `T`, and no initialized reads are claimed.
675unsafe impl<T: DeviceRepr> DeviceRange<T> for ManagedMemory<MaybeUninit<T>> {
676    fn len(&self) -> usize {
677        self.length
678    }
679}
680
681// SAFETY: `&mut self` is exclusive over `length` retained slots with `T`'s layout.
682unsafe impl<T: DeviceRepr> DeviceOutput<T> for ManagedMemory<MaybeUninit<T>> {
683    fn as_mut_ptr(&mut self) -> *mut T {
684        let () = T::LAYOUT;
685        self.ptr.cast()
686    }
687}