Skip to main content

singe_cuda/interop/
cudarc.rs

1//! Zero-copy cudarc storage with explicit cross-runtime access and ordering contracts.
2
3use std::{marker::PhantomData, ptr, sync::Arc};
4
5use ::cudarc::driver::{
6    CudaContext, CudaSlice, CudaStream, CudaView, CudaViewMut, DevicePtr as ForeignDevicePtr,
7    DevicePtrMut as ForeignDevicePtrMut, DeviceSlice as ForeignDeviceSlice, DriverError,
8    sys::CUdeviceptr,
9};
10use singe_core::report_cleanup_failure;
11
12use crate::{
13    context::{Context, RawContext, RawContextOwnership},
14    device::Device,
15    error::{Error, Result},
16    stream::{Stream, StreamIdentity},
17    utility::{checked_bytes, to_usize},
18    view::{
19        AllocationId, DeviceOutput, DeviceRange, DeviceRegion, DeviceRegionProvider, DeviceRepr,
20        DeviceSlice, DeviceSliceMut, DeviceView, DeviceViewMut, OwnedDeviceRegion,
21    },
22};
23
24fn foreign_error(error: DriverError) -> Error {
25    Error::Operation(Box::new(error))
26}
27
28impl Context {
29    /// Retains cudarc's actual context, including independently created non-primary contexts.
30    ///
31    /// # Errors
32    ///
33    /// Returns an error if cudarc's context handle is null.
34    pub fn from_cudarc(owner: Arc<CudaContext>) -> Result<Arc<Self>> {
35        let handle = owner.cu_ctx().cast();
36        let device = Device::new(owner.cu_device());
37        // SAFETY: `owner` keeps cudarc's live context, which belongs to `device`, alive for as long as the returned context.
38        unsafe {
39            Self::from_raw(RawContext {
40                handle,
41                device,
42                ownership: RawContextOwnership::Borrowed(owner),
43            })
44        }
45    }
46}
47
48impl Stream {
49    /// Borrows a cudarc stream and retains its native stream and context owners.
50    ///
51    /// # Safety
52    ///
53    /// Coordinate external submissions with Singe access tracking and capture lifecycle.
54    ///
55    /// # Errors
56    ///
57    /// Returns an error if the stream is a per-thread default stream or its context cannot be retained or bound.
58    pub unsafe fn from_cudarc(owner: Arc<CudaStream>) -> Result<Self> {
59        let context = Context::from_cudarc(Arc::clone(owner.context()))?;
60        // SAFETY: the stream belongs to cudarc's context, which `context` retains, `owner` keeps the stream alive, and the caller coordinates external submissions.
61        unsafe { Self::borrow_with_owner(owner.cu_stream().cast(), context, owner) }
62    }
63
64    /// Exposes this stream to cudarc without transferring destruction responsibility.
65    ///
66    /// # Safety
67    ///
68    /// Retain this Singe stream while any returned cudarc clone or allocation uses it.
69    /// Cudarc submissions must participate in explicit ordering and exclude conflicting Singe accesses.
70    ///
71    /// # Errors
72    ///
73    /// Returns an error if `context` is not this stream's context.
74    pub unsafe fn to_cudarc(&self, context: &Arc<CudaContext>) -> Result<Arc<CudaStream>> {
75        if self.context().as_raw().cast::<()>() != context.cu_ctx().cast::<()>() {
76            return Err(Error::StreamContextMismatch);
77        }
78        // SAFETY: the stream belongs to `context`, as checked above, and the caller keeps it alive and orders cudarc work with Singe work.
79        Ok(unsafe { context.wrap_borrowed_stream(self.as_raw().cast()) })
80    }
81}
82
83/// Retains the original cudarc allocation and the actual stream establishing its readiness.
84#[derive(Debug)]
85pub struct CudarcAllocation<T: DeviceRepr> {
86    owner: Option<Arc<CudaSlice<T>>>,
87    stream: Stream,
88    retirement_stream: Stream,
89    id: AllocationId,
90    pointer: *mut T,
91    bytes: usize,
92}
93
94// SAFETY: the device pointer is never dereferenced on the host, and the cudarc owner and the streams may move between threads; values move as `T` does.
95unsafe impl<T: DeviceRepr + Send> Send for CudarcAllocation<T> {}
96
97// SAFETY: shared references expose only the pointer, metadata, and `&` access to thread-safe owners; values are shared as `T` is.
98unsafe impl<T: DeviceRepr + Sync> Sync for CudarcAllocation<T> {}
99
100impl<T: DeviceRepr> CudarcAllocation<T> {
101    /// Returns the context of the allocation's readiness stream.
102    #[must_use]
103    pub fn context(&self) -> &Arc<Context> {
104        self.stream.context()
105    }
106
107    /// Returns the stream that establishes the allocation's readiness.
108    #[must_use]
109    pub fn stream(&self) -> &Stream {
110        &self.stream
111    }
112
113    /// Returns the allocation identity shared by every view of this allocation.
114    #[must_use]
115    pub fn id(&self) -> AllocationId {
116        self.id
117    }
118
119    /// Returns the allocation's size in bytes.
120    #[must_use]
121    pub fn byte_len(&self) -> usize {
122        self.bytes
123    }
124
125    /// Returns the allocation's device address without granting access to its values.
126    #[must_use]
127    pub fn as_ptr(&self) -> *mut T {
128        self.pointer
129    }
130
131    /// Returns the retained cudarc allocation.
132    ///
133    /// # Safety
134    ///
135    /// Foreign accesses must exclude conflicting Singe operations and establish event ordering in both directions.
136    #[must_use]
137    pub unsafe fn cudarc_owner(&self) -> &Arc<CudaSlice<T>> {
138        self.owner.as_ref().expect("live cudarc allocation owner")
139    }
140}
141
142// SAFETY: the retained cudarc owner keeps the storage live, and `id`, `pointer`, and `bytes` describe it in the retained stream's context.
143unsafe impl<T: DeviceRepr> DeviceRegionProvider for CudarcAllocation<T> {
144    fn region(&self) -> DeviceRegion<'_> {
145        // SAFETY: the retained cudarc owner keeps these `bytes` bytes live in this context, `id` is unique to the allocation, and its pending writes are ordered on `self.stream`.
146        unsafe {
147            DeviceRegion::from_raw_parts(self.context(), self.id, self.pointer.cast(), self.bytes)
148                .and_then(|region| region.with_stream(&self.stream))
149        }
150        .expect("checked cudarc allocation metadata")
151    }
152}
153
154impl<T: DeviceRepr> Drop for CudarcAllocation<T> {
155    fn drop(&mut self) {
156        if let Some(owner) = self.owner.take()
157            && let Err(error) = self.retirement_stream.release_foreign_owner(owner)
158        {
159            report_cleanup_failure("retire", "cudarc allocation", &error);
160        }
161    }
162}
163
164/// Typed cudarc allocation handle exposing Singe views while retaining the foreign owner.
165#[derive(Debug)]
166pub struct CudarcMemory<T: DeviceRepr> {
167    allocation: Arc<CudarcAllocation<T>>,
168    length: usize,
169}
170
171impl<T: DeviceRepr> CudarcMemory<T> {
172    /// Adopts an exclusive cudarc allocation, ordering its prior reads and writes before Singe consumers.
173    ///
174    /// # Safety
175    ///
176    /// Every element must be valid for `T` and externally retained aliases must exclude conflicting accesses.
177    /// External raw CUDA work and capture must obey the same resource and stream contracts as Singe.
178    ///
179    /// # Errors
180    ///
181    /// Returns an error if [`Self::from_shared`] fails for the allocation and its own stream.
182    pub unsafe fn from_owned(mut owner: CudaSlice<T>) -> Result<Self> {
183        let ready = Arc::clone(owner.stream());
184        let (_, order) = owner.device_ptr_mut(&ready);
185        drop(order);
186        // SAFETY: the mutable access above ordered prior cudarc work on `ready`, and the caller guarantees valid values and excluded aliases.
187        unsafe { Self::from_shared(Arc::new(owner), ready) }
188    }
189
190    /// Retains a shared cudarc owner and an explicit readiness stream.
191    ///
192    /// # Safety
193    ///
194    /// `ready` must order all prior accesses that conflict with the intended Singe uses.
195    /// Values must be valid for `T`; exclude conflicting accesses through foreign or separately imported aliases.
196    /// Use this bridge's views to preserve allocation identity across Singe accesses.
197    /// Foreign and Singe tracking are independent, so order both directions explicitly with events or completion.
198    /// Coordinate external capture on both the readiness stream and the allocation's original stream.
199    ///
200    /// # Errors
201    ///
202    /// Returns an error if `owner` and `ready` belong to different contexts, the byte size overflows, cudarc reports an error, or a stream cannot be retained.
203    pub unsafe fn from_shared(owner: Arc<CudaSlice<T>>, ready: Arc<CudaStream>) -> Result<Self> {
204        if owner.context().cu_ctx() != ready.context().cu_ctx() {
205            return Err(Error::MemoryContextMismatch);
206        }
207
208        let () = T::LAYOUT;
209        let length = owner.len();
210        let bytes = checked_bytes::<T>(length, "cudarc slice bytes")?;
211
212        let (pointer, order) = owner.device_ptr(&ready);
213        drop(order);
214        ready.context().check_err().map_err(foreign_error)?;
215        // SAFETY: the caller coordinates external submissions on `ready` with Singe tracking and capture.
216        let stream = unsafe { Stream::from_cudarc(ready)? };
217        // Cudarc frees on the allocation's original stream, independently of its readiness stream.
218        let retirement_stream =
219            if StreamIdentity::new(stream.context(), owner.stream().cu_stream().cast())
220                == stream.identity()
221            {
222                stream.clone()
223            } else {
224                // SAFETY: the caller coordinates external capture and submissions on the allocation's original stream.
225                unsafe { Stream::from_cudarc(Arc::clone(owner.stream()))? }
226            };
227        Ok(Self {
228            allocation: Arc::new(CudarcAllocation {
229                owner: Some(owner),
230                stream,
231                retirement_stream,
232                id: AllocationId::create(),
233                pointer: ptr::without_provenance_mut(to_usize(pointer, "cudarc device pointer")?),
234                bytes,
235            }),
236            length,
237        })
238    }
239
240    /// Returns the shared allocation owner.
241    #[must_use]
242    pub fn allocation(&self) -> &Arc<CudarcAllocation<T>> {
243        &self.allocation
244    }
245
246    /// Returns the number of elements.
247    #[must_use]
248    pub fn len(&self) -> usize {
249        self.length
250    }
251
252    /// Returns whether the memory holds no elements.
253    #[must_use]
254    pub fn is_empty(&self) -> bool {
255        self.length == 0
256    }
257
258    /// Borrows the elements as a typed device view.
259    #[must_use]
260    pub fn view(&self) -> DeviceView<'_, T> {
261        // SAFETY: the region covers the `length` elements `from_shared`'s caller guaranteed valid, and the view lives no longer than `&self`.
262        unsafe { DeviceView::from_raw_parts(self.region(), self.length) }
263            .expect("checked cudarc allocation view")
264    }
265
266    /// Exclusively borrows the elements as a mutable typed device view.
267    pub fn view_mut(&mut self) -> DeviceViewMut<'_, T> {
268        // SAFETY: the region covers the `length` valid elements, and `&mut self` excludes other Singe aliases for the view's lifetime.
269        unsafe { DeviceViewMut::from_raw_parts(self.region(), self.length) }
270            .expect("exclusive cudarc allocation view")
271    }
272
273    /// Returns a region that retains the allocation owner.
274    ///
275    /// # Errors
276    ///
277    /// Returns an error if the allocation's byte range cannot be described as an owned region.
278    pub fn retained_region(&self) -> Result<OwnedDeviceRegion<CudarcAllocation<T>>> {
279        OwnedDeviceRegion::from_owner(Arc::clone(&self.allocation), 0..self.allocation.bytes)
280    }
281}
282
283// SAFETY: the region comes from the retained allocation owner, which keeps its identity and bounds for the borrow.
284unsafe impl<T: DeviceRepr> DeviceRegionProvider for CudarcMemory<T> {
285    fn region(&self) -> DeviceRegion<'_> {
286        self.allocation.region()
287    }
288}
289
290// SAFETY: `length` elements of `T` span exactly the allocation's checked byte size.
291unsafe impl<T: DeviceRepr> DeviceRange<T> for CudarcMemory<T> {
292    fn len(&self) -> usize {
293        self.length
294    }
295}
296
297// SAFETY: `from_shared`'s caller guarantees every element is a valid `T`.
298unsafe impl<T: DeviceRepr> DeviceSlice<T> for CudarcMemory<T> {}
299
300// SAFETY: the allocation is writable device storage for `length` elements, borrowed exclusively through `&mut self`.
301unsafe impl<T: DeviceRepr> DeviceOutput<T> for CudarcMemory<T> {
302    fn as_mut_ptr(&mut self) -> *mut T {
303        self.allocation.pointer
304    }
305}
306
307// SAFETY: `&mut self` excludes other Singe aliases, and `from_shared`'s caller excludes conflicting foreign aliases.
308unsafe impl<T: DeviceRepr> DeviceSliceMut<T> for CudarcMemory<T> {}
309
310/// Read-only borrowed foreign view tied to a checked root allocation identity.
311#[derive(Debug)]
312pub struct CudarcView<'a, T: DeviceRepr> {
313    view: DeviceView<'a, T>,
314    foreign: PhantomData<&'a CudaSlice<T>>,
315}
316
317impl<'a, T: DeviceRepr> CudarcView<'a, T> {
318    /// Borrows a cudarc subview using an existing Singe bridge's root identity and bounds.
319    ///
320    /// # Safety
321    ///
322    /// The foreign view must alias this root and remain valid and unmodified through the borrow.
323    /// Order prior foreign producers on `ready` and order Singe consumers after that stream.
324    ///
325    /// # Errors
326    ///
327    /// Returns an error if `root`, `ready`, and the view's stream disagree on context or stream, cudarc reports an error, or the view lies outside `root`.
328    pub unsafe fn create(
329        view: &CudaView<'a, T>,
330        root: DeviceRegion<'a>,
331        ready: &'a Stream,
332    ) -> Result<Self> {
333        let foreign = Arc::clone(ForeignDeviceSlice::stream(view));
334        check_ready(root, ready, &foreign)?;
335        let length = view.len();
336        let (pointer, order) = view.device_ptr(&foreign);
337        drop(order);
338        foreign.context().check_err().map_err(foreign_error)?;
339        let region = subregion::<T>(root, pointer, length)?;
340        // SAFETY: the caller orders prior foreign producers on `ready`, which `check_ready` matched to the view's stream.
341        let region = unsafe { region.with_stream(ready)? };
342        Ok(Self {
343            // SAFETY: the caller guarantees the aliased values stay valid and unmodified for `'a`.
344            view: unsafe { DeviceView::from_raw_parts(region, length)? },
345            foreign: PhantomData,
346        })
347    }
348
349    /// Returns the Singe view of the borrowed elements.
350    #[must_use]
351    pub fn view(&self) -> DeviceView<'_, T> {
352        self.view
353    }
354}
355
356// SAFETY: the region is the checked subregion of the borrowed root, which stays live for the view's lifetime.
357unsafe impl<T: DeviceRepr> DeviceRegionProvider for CudarcView<'_, T> {
358    fn region(&self) -> DeviceRegion<'_> {
359        self.view.region()
360    }
361}
362
363// SAFETY: the length is the inner view's, which `DeviceView::from_raw_parts` matched to the region's byte length.
364unsafe impl<T: DeviceRepr> DeviceRange<T> for CudarcView<'_, T> {
365    fn len(&self) -> usize {
366        self.view.len()
367    }
368}
369
370// SAFETY: `create`'s caller guarantees the values are valid and unmodified for the borrow.
371unsafe impl<T: DeviceRepr> DeviceSlice<T> for CudarcView<'_, T> {}
372
373/// Exclusive borrowed foreign view retaining the native slice borrow and shared allocation identity.
374#[derive(Debug)]
375pub struct CudarcViewMut<'a, T: DeviceRepr> {
376    view: DeviceViewMut<'a, T>,
377    foreign: PhantomData<&'a mut CudaSlice<T>>,
378}
379
380impl<'a, T: DeviceRepr> CudarcViewMut<'a, T> {
381    /// Borrows a mutable cudarc subview using its original allocation's identity and exact stream.
382    ///
383    /// # Safety
384    ///
385    /// Values must be valid for `T`, and `root` must describe this view's actual backing allocation.
386    /// Exclude foreign aliases until this borrow ends and all Singe work using it completes.
387    ///
388    /// # Errors
389    ///
390    /// Returns an error if `root`, `ready`, and the view's stream disagree on context or stream, cudarc reports an error, or the view lies outside `root`.
391    pub unsafe fn create(
392        mut view: CudaViewMut<'a, T>,
393        root: DeviceRegion<'a>,
394        ready: &'a Stream,
395    ) -> Result<Self> {
396        let foreign = Arc::clone(ForeignDeviceSlice::stream(&view));
397        check_ready(root, ready, &foreign)?;
398        let length = view.len();
399        let (pointer, order) = view.device_ptr_mut(&foreign);
400        drop(order);
401        foreign.context().check_err().map_err(foreign_error)?;
402        let region = subregion::<T>(root, pointer, length)?;
403        // SAFETY: the mutable access above ordered prior cudarc work on the view's stream, which `check_ready` matched to `ready`.
404        let region = unsafe { region.with_stream(ready)? };
405        Ok(Self {
406            // SAFETY: the caller guarantees valid values and excludes foreign aliases until the borrow and its Singe work end.
407            view: unsafe { DeviceViewMut::from_raw_parts(region, length)? },
408            foreign: PhantomData,
409        })
410    }
411
412    /// Borrows the elements as a read-only Singe view.
413    #[must_use]
414    pub fn view(&self) -> DeviceView<'_, T> {
415        self.view.as_view()
416    }
417
418    /// Reborrows the elements as a mutable Singe view.
419    pub fn view_mut(&mut self) -> DeviceViewMut<'_, T> {
420        self.view.reborrow()
421    }
422}
423
424// SAFETY: the region is the checked subregion of the borrowed root, which stays live for the view's lifetime.
425unsafe impl<T: DeviceRepr> DeviceRegionProvider for CudarcViewMut<'_, T> {
426    fn region(&self) -> DeviceRegion<'_> {
427        self.view.region()
428    }
429}
430
431// SAFETY: the length is the inner view's, which `DeviceViewMut::from_raw_parts` matched to the region's byte length.
432unsafe impl<T: DeviceRepr> DeviceRange<T> for CudarcViewMut<'_, T> {
433    fn len(&self) -> usize {
434        self.view.len()
435    }
436}
437
438// SAFETY: `create`'s caller guarantees the values are valid for the borrow.
439unsafe impl<T: DeviceRepr> DeviceSlice<T> for CudarcViewMut<'_, T> {}
440
441// SAFETY: the inner exclusive view is writable storage for its elements, borrowed through `&mut self`.
442unsafe impl<T: DeviceRepr> DeviceOutput<T> for CudarcViewMut<'_, T> {
443    fn as_mut_ptr(&mut self) -> *mut T {
444        self.view.as_mut_ptr()
445    }
446}
447
448// SAFETY: the inner view is exclusive, and `create`'s caller excludes foreign aliases until the borrow ends.
449unsafe impl<T: DeviceRepr> DeviceSliceMut<T> for CudarcViewMut<'_, T> {}
450
451fn check_ready(root: DeviceRegion<'_>, ready: &Stream, foreign: &CudaStream) -> Result<()> {
452    let foreign_context = foreign.context().cu_ctx().cast::<()>();
453    if root.context() != ready.context() || root.context().as_raw().cast::<()>() != foreign_context
454    {
455        return Err(Error::MemoryContextMismatch);
456    }
457
458    if ready.identity() != StreamIdentity::new(ready.context(), foreign.cu_stream().cast()) {
459        return Err(Error::ForeignStreamMismatch);
460    }
461    Ok(())
462}
463
464fn subregion<T>(
465    root: DeviceRegion<'_>,
466    pointer: CUdeviceptr,
467    length: usize,
468) -> Result<DeviceRegion<'_>> {
469    let start = usize::try_from(pointer)
470        .map_err(|_| Error::out_of_range("cudarc view address"))?
471        .checked_sub(root.as_ptr().addr())
472        .ok_or_else(|| Error::out_of_range("cudarc view offset"))?;
473    let bytes = length
474        .checked_mul(size_of::<T>())
475        .ok_or_else(|| Error::out_of_range("cudarc view bytes"))?;
476    let end = start
477        .checked_add(bytes)
478        .ok_or_else(|| Error::out_of_range("cudarc view end"))?;
479    root.slice(start..end)
480}