Skip to main content

singe_cuda/memory/
allocation.rs

1use std::{mem::replace, ptr, sync::Arc};
2
3use singe_core::report_cleanup_failure;
4use singe_cuda_sys::runtime;
5
6use crate::{
7    context::Context,
8    error::Result,
9    memory::{DeviceMemory, MemoryPool},
10    stream::Stream,
11    try_ffi,
12    types::DevicePtr,
13    view::{AllocationId, DeviceRegion, DeviceRegionProvider},
14};
15
16#[derive(Debug)]
17pub(crate) enum DeviceDeallocation {
18    Immediate,
19    StreamOrdered {
20        stream: Stream,
21        pool: Option<MemoryPool>,
22    },
23}
24
25/// A queued free owns its deallocation resources without retaining its stream.
26#[derive(Debug)]
27pub(crate) struct DeferredFree {
28    pointer: *mut u8,
29    context: Arc<Context>,
30    _pool: Option<MemoryPool>,
31}
32
33// SAFETY: the host never dereferences `pointer`, and `enqueue` binds the retained context on whichever thread calls it.
34unsafe impl Send for DeferredFree {}
35
36// SAFETY: `&DeferredFree` only passes the address to `cudaFreeAsync`; the stream's cleanup lock runs each free once.
37unsafe impl Sync for DeferredFree {}
38
39impl DeferredFree {
40    pub(crate) fn enqueue(&self, stream: runtime::cudaStream_t) -> Result<()> {
41        self.context.bind()?;
42        // SAFETY: `pointer` came from a stream-ordered allocation whose final owner released it to this free, and the context is bound.
43        unsafe { try_ffi!(runtime::cudaFreeAsync(self.pointer.cast(), stream)) }
44    }
45}
46
47/// Owns a CUDA allocation independently of its typed buffers and views.
48///
49/// Retaining this owner keeps the allocation, context, and deallocation resources alive.
50/// Raw CUDA work must still satisfy the lifetime and ordering contract of its launch.
51#[derive(Debug)]
52pub struct DeviceAllocation {
53    pub(crate) id: AllocationId,
54    pub(crate) context: Arc<Context>,
55    pub(crate) ptr: *mut u8,
56    pub(crate) bytes: usize,
57    pub(crate) deallocation: DeviceDeallocation,
58}
59
60// SAFETY: the host never dereferences `ptr`, the retained context and stream are `Send`, and release binds the context on the dropping thread.
61unsafe impl Send for DeviceAllocation {}
62
63// SAFETY: `&DeviceAllocation` exposes only immutable metadata; access to the bytes goes through borrows or unsafe raw APIs.
64unsafe impl Sync for DeviceAllocation {}
65
66impl DeviceAllocation {
67    pub(crate) fn from_parts(
68        context: &Arc<Context>,
69        ptr: *mut u8,
70        bytes: usize,
71        deallocation: DeviceDeallocation,
72    ) -> Arc<Self> {
73        Arc::new(Self {
74            id: AllocationId::create(),
75            context: Arc::clone(context),
76            ptr,
77            bytes,
78            deallocation,
79        })
80    }
81
82    /// Returns the identity shared by every buffer and view of this allocation.
83    #[must_use]
84    pub const fn id(&self) -> AllocationId {
85        self.id
86    }
87
88    /// Returns the context that owns this allocation.
89    #[must_use]
90    pub fn context(&self) -> &Arc<Context> {
91        &self.context
92    }
93
94    /// Returns the allocation's base device address.
95    #[must_use]
96    pub fn as_device_ptr(&self) -> DevicePtr {
97        // SAFETY: `ptr` is this live allocation's base or null, and `DevicePtr` only records the address.
98        unsafe { DevicePtr::from_raw(self.ptr.cast()) }
99    }
100
101    /// Returns the full allocation size, independent of typed views.
102    #[must_use]
103    pub const fn byte_len(&self) -> usize {
104        self.bytes
105    }
106
107    /// Returns the allocation and deallocation stream for stream-ordered memory.
108    #[must_use]
109    pub fn stream(&self) -> Option<&Stream> {
110        match &self.deallocation {
111            DeviceDeallocation::Immediate => None,
112            DeviceDeallocation::StreamOrdered { stream, .. } => Some(stream),
113        }
114    }
115
116    /// Returns the explicitly selected pool retained by this allocation.
117    #[must_use]
118    pub fn pool(&self) -> Option<&MemoryPool> {
119        match &self.deallocation {
120            DeviceDeallocation::Immediate => None,
121            DeviceDeallocation::StreamOrdered { pool, .. } => pool.as_ref(),
122        }
123    }
124
125    pub(crate) fn release(&mut self) -> Result<()> {
126        if self.ptr.is_null() {
127            return Ok(());
128        }
129        match &self.deallocation {
130            DeviceDeallocation::Immediate => {
131                self.context.bind()?;
132                // SAFETY: `release` runs once, from `Drop` of the last `Arc` owner, so no view or submission still uses `ptr`.
133                unsafe {
134                    DeviceMemory::<u8>::free(&self.context, self.ptr)?;
135                }
136
137                self.ptr = ptr::null_mut();
138                Ok(())
139            }
140            DeviceDeallocation::StreamOrdered { stream, pool } => {
141                let free = DeferredFree {
142                    pointer: replace(&mut self.ptr, ptr::null_mut()),
143                    context: Arc::clone(&self.context),
144                    _pool: pool.clone(),
145                };
146                // The stream keeps failed frees and captured frees until they can be enqueued.
147                stream.defer_free(free)
148            }
149        }
150    }
151}
152
153// SAFETY: the owner retains `bytes` bytes at `ptr` and its context for its lifetime, under one allocation identity.
154unsafe impl DeviceRegionProvider for DeviceAllocation {
155    fn region(&self) -> DeviceRegion<'_> {
156        // SAFETY: this owner retains the complete allocation and its context.
157        let region =
158            unsafe { DeviceRegion::from_raw_parts(&self.context, self.id, self.ptr, self.bytes) }
159                .expect("invalid device allocation metadata");
160        self.stream().map_or(region, |stream| {
161            // SAFETY: a stream-ordered allocation is allocated on this stream, so it orders the allocation.
162            unsafe { region.with_stream(stream) }.expect("allocation stream context mismatch")
163        })
164    }
165}
166
167impl Drop for DeviceAllocation {
168    fn drop(&mut self) {
169        if let Err(error) = self.release() {
170            report_cleanup_failure("release", "cuda device allocation", &error);
171        }
172    }
173}