Skip to main content

singe_cuda/memory/
stream_ordered.rs

1use std::{marker::PhantomData, mem::MaybeUninit, ptr, sync::Arc};
2
3use singe_cuda_sys::runtime;
4
5use crate::{
6    error::{Error, Result},
7    memory::{DeviceAllocation, DeviceDeallocation, DeviceMemory, MemoryPool},
8    stream::Stream,
9    try_ffi,
10    utility::checked_bytes,
11    view::{DeviceRepr, ZeroableDeviceRepr},
12};
13
14impl<T> DeviceMemory<T> {
15    /// Allocates stream-ordered device memory on `stream` for a raw producer to initialize.
16    ///
17    /// The last owner enqueues `cudaFreeAsync` on `stream` when it drops.
18    ///
19    /// # Safety
20    ///
21    /// Every element must be initialized to a valid `T` before it is read.
22    /// Consumers on other streams must wait for allocation and producer work.
23    ///
24    /// # Errors
25    ///
26    /// Returns an error if the requested byte size overflows, the stream's context cannot be bound, CUDA cannot enqueue the allocation, or `length` is non-zero for a zero-sized `T`.
27    pub unsafe fn create_stream_ordered_unchecked(length: usize, stream: &Stream) -> Result<Self> {
28        let _lifecycle = stream.allocation_guard()?;
29        stream.context().bind()?;
30        let bytes = checked_bytes::<T>(length, "byte length")?;
31        let ptr = if bytes == 0 {
32            ptr::null_mut()
33        } else {
34            // SAFETY: the allocation is owned below and freed on `stream`, and this function's caller initializes it before reads.
35            unsafe { Self::alloc_async(length, stream)? }
36        };
37        Ok(Self {
38            allocation: DeviceAllocation::from_parts(
39                stream.context(),
40                ptr.cast(),
41                bytes,
42                DeviceDeallocation::StreamOrdered {
43                    stream: stream.clone(),
44                    pool: None,
45                },
46            ),
47            ptr,
48            length,
49            _phantom: PhantomData,
50        })
51    }
52
53    /// Allocates stream-ordered device memory from `pool` on `stream` for a raw producer to initialize.
54    ///
55    /// The last owner enqueues `cudaFreeAsync` on `stream` when it drops, and retains `pool` until then.
56    ///
57    /// # Safety
58    ///
59    /// Every element must be initialized to a valid `T` before it is read.
60    /// Consumers on other streams must wait for allocation and producer work.
61    ///
62    /// # Errors
63    ///
64    /// Returns an error if the requested byte size overflows, the stream's context cannot be bound, CUDA cannot enqueue the pool allocation, CUDA returns a null pointer for a non-empty request, or `length` is non-zero for a zero-sized `T`.
65    pub unsafe fn create_in_pool_unchecked(
66        length: usize,
67        pool: &MemoryPool,
68        stream: &Stream,
69    ) -> Result<Self> {
70        let _lifecycle = stream.allocation_guard()?;
71        stream.context().bind()?;
72        let bytes = checked_bytes::<T>(length, "byte length")?;
73        let mut ptr = ptr::null_mut();
74        if bytes != 0 {
75            // SAFETY: `ptr` is a local output, `bytes` is a checked nonzero size, and `pool` and `stream` are borrowed live in the bound context.
76            unsafe {
77                try_ffi!(runtime::cudaMallocFromPoolAsync(
78                    &raw mut ptr,
79                    bytes as _,
80                    pool.as_raw(),
81                    stream.as_raw()
82                ))?;
83            }
84
85            if ptr.is_null() {
86                return Err(Error::NullHandle);
87            }
88        }
89
90        Ok(Self {
91            allocation: DeviceAllocation::from_parts(
92                stream.context(),
93                ptr.cast(),
94                bytes,
95                DeviceDeallocation::StreamOrdered {
96                    stream: stream.clone(),
97                    pool: Some(pool.clone()),
98                },
99            ),
100            ptr: ptr.cast(),
101            length,
102            _phantom: PhantomData,
103        })
104    }
105
106    /// Enqueues an uninitialized allocation on `stream` from CUDA's current pool.
107    ///
108    /// Access on other streams must be ordered after the allocation stream.
109    ///
110    /// # Errors
111    ///
112    /// Returns an error if the byte count overflows, a nonempty zero-sized allocation is requested, stream or context setup fails, or CUDA cannot enqueue the allocation.
113    pub fn create_uninit_stream_ordered(
114        length: usize,
115        stream: &Stream,
116    ) -> Result<DeviceMemory<MaybeUninit<T>>>
117    where
118        T: DeviceRepr,
119    {
120        let () = T::LAYOUT;
121        // SAFETY: `MaybeUninit<T>` elements need no initialization.
122        unsafe { DeviceMemory::<MaybeUninit<T>>::create_stream_ordered_unchecked(length, stream) }
123    }
124
125    /// Enqueues an uninitialized allocation from `pool` on `stream`.
126    ///
127    /// The allocation retains both the pool and the stream until it is freed.
128    ///
129    /// # Errors
130    ///
131    /// Returns an error if the byte count overflows, a nonempty zero-sized allocation is requested, or stream or context setup fails.
132    /// Also propagates CUDA errors for the requested pool allocation and rejects a null handle for a nonempty allocation.
133    pub fn create_uninit_in_pool(
134        length: usize,
135        pool: &MemoryPool,
136        stream: &Stream,
137    ) -> Result<DeviceMemory<MaybeUninit<T>>>
138    where
139        T: DeviceRepr,
140    {
141        let () = T::LAYOUT;
142        // SAFETY: `MaybeUninit<T>` elements need no initialization.
143        unsafe { DeviceMemory::<MaybeUninit<T>>::create_in_pool_unchecked(length, pool, stream) }
144    }
145
146    /// Returns the stream a stream-ordered allocation was made on and is freed on, or `None` for an allocation freed with `cudaFree`.
147    #[must_use]
148    pub fn stream(&self) -> Option<&Stream> {
149        self.allocation.stream()
150    }
151
152    /// Returns the pool a stream-ordered allocation came from, if one was selected.
153    #[must_use]
154    pub fn pool(&self) -> Option<&MemoryPool> {
155        self.allocation.pool()
156    }
157
158    /// Releases the allocation now when this is its final owner.
159    ///
160    /// Memory freed with `cudaFree` is freed before this returns; a stream-ordered allocation enqueues `cudaFreeAsync` on its stream.
161    /// Calling this surfaces the errors that dropping the owner can only report.
162    ///
163    /// # Errors
164    ///
165    /// Returns [`Error::OwnershipShared`] if a view, submission, graph, or interop user retains the allocation, which then stays live until its final owner drops.
166    /// Otherwise returns an error if the context cannot be bound or CUDA cannot free or enqueue the free.
167    pub fn release(self) -> Result<()> {
168        let mut allocation = Arc::try_unwrap(self.allocation)
169            .map_err(|_| Error::ownership_shared("device allocation"))?;
170        allocation.release()
171    }
172}
173
174impl<T: ZeroableDeviceRepr> DeviceMemory<T> {
175    /// Allocates stream-ordered device memory on `stream` and enqueues a fill with zero bytes.
176    ///
177    /// # Errors
178    ///
179    /// Returns an error if allocation fails or CUDA cannot enqueue the memset.
180    pub fn zeroed_stream_ordered(length: usize, stream: &Stream) -> Result<Self> {
181        let () = T::LAYOUT;
182        // SAFETY: the fill below initializes every element on the allocation stream before any later consumer.
183        let memory = unsafe { Self::create_stream_ordered_unchecked(length, stream)? };
184        // SAFETY: the fill covers the `memory.length` owned elements on the allocation's own stream, which orders it before the free, and `T: ZeroableDeviceRepr` makes zero bytes valid.
185        unsafe {
186            Self::set_async(memory.ptr, 0, memory.length, stream)?;
187        }
188        Ok(memory)
189    }
190
191    /// Allocates stream-ordered device memory from `pool` on `stream` and enqueues a fill with zero bytes.
192    ///
193    /// # Errors
194    ///
195    /// Returns an error if allocation from the pool fails or CUDA cannot enqueue the memset.
196    pub fn zeroed_in_pool(length: usize, pool: &MemoryPool, stream: &Stream) -> Result<Self> {
197        let () = T::LAYOUT;
198        // SAFETY: the fill below initializes every element on the allocation stream before any later consumer.
199        let memory = unsafe { Self::create_in_pool_unchecked(length, pool, stream)? };
200        // SAFETY: the fill covers the `memory.length` owned elements on the allocation's own stream, which orders it before the free, and `T: ZeroableDeviceRepr` makes zero bytes valid.
201        unsafe {
202            Self::set_async(memory.ptr, 0, memory.length, stream)?;
203        }
204        Ok(memory)
205    }
206}
207
208/// The stream that frees a stream-ordered allocation, and the pool it came from.
209#[derive(Debug)]
210pub struct StreamOrderedFree {
211    /// Stream the allocation was made on and is freed on.
212    pub stream: Stream,
213    /// Pool the allocation came from, if any.
214    pub pool: Option<MemoryPool>,
215}