singe_cuda/memory/
allocation.rs1use 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#[derive(Debug)]
27pub(crate) struct DeferredFree {
28 pointer: *mut u8,
29 context: Arc<Context>,
30 _pool: Option<MemoryPool>,
31}
32
33unsafe impl Send for DeferredFree {}
35
36unsafe impl Sync for DeferredFree {}
38
39impl DeferredFree {
40 pub(crate) fn enqueue(&self, stream: runtime::cudaStream_t) -> Result<()> {
41 self.context.bind()?;
42 unsafe { try_ffi!(runtime::cudaFreeAsync(self.pointer.cast(), stream)) }
44 }
45}
46
47#[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
60unsafe impl Send for DeviceAllocation {}
62
63unsafe 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 #[must_use]
84 pub const fn id(&self) -> AllocationId {
85 self.id
86 }
87
88 #[must_use]
90 pub fn context(&self) -> &Arc<Context> {
91 &self.context
92 }
93
94 #[must_use]
96 pub fn as_device_ptr(&self) -> DevicePtr {
97 unsafe { DevicePtr::from_raw(self.ptr.cast()) }
99 }
100
101 #[must_use]
103 pub const fn byte_len(&self) -> usize {
104 self.bytes
105 }
106
107 #[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 #[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 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 stream.defer_free(free)
148 }
149 }
150 }
151}
152
153unsafe impl DeviceRegionProvider for DeviceAllocation {
155 fn region(&self) -> DeviceRegion<'_> {
156 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 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}