Skip to main content

singe_cuda/stream/
raw.rs

1use std::{
2    any::Any,
3    fmt::{self, Formatter},
4    mem, ptr,
5    result::Result as StdResult,
6    sync::Arc,
7};
8
9use singe_cuda_sys::runtime;
10
11use super::{CaptureCleanup, PER_THREAD_STREAM, Stream, StreamIdentity, StreamInner};
12use crate::{
13    context::Context,
14    error::{Error, Result},
15    try_ffi,
16};
17
18/// Release responsibility returned with a raw native stream.
19pub enum RawStreamOwnership {
20    /// The caller must eventually destroy the returned native handle.
21    Owned,
22    /// The external owner token must remain live through every use of the native handle.
23    Borrowed(Arc<dyn Any + Send + Sync>),
24}
25
26impl fmt::Debug for RawStreamOwnership {
27    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
28        f.write_str(match self {
29            Self::Owned => "Owned",
30            Self::Borrowed(_) => "Borrowed",
31        })
32    }
33}
34
35/// Raw ownership of a CUDA stream, its context, and any external owner.
36///
37/// Destroy owned handles explicitly, keep borrowed tokens alive through every use, or re-adopt the value with [`Stream::from_raw`].
38#[derive(Debug)]
39pub struct RawStream {
40    /// Native stream handle whose release responsibility is described by `ownership`.
41    pub handle: runtime::cudaStream_t,
42    /// Actual CUDA context retained for native stream operations.
43    pub context: Arc<Context>,
44    /// Native destruction responsibility or external owner token.
45    pub ownership: RawStreamOwnership,
46}
47
48pub(crate) struct ForeignOwner(Arc<dyn Any + Send + Sync>);
49
50impl fmt::Debug for ForeignOwner {
51    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
52        f.debug_struct("ForeignOwner")
53            .field("references", &Arc::strong_count(&self.0))
54            .finish_non_exhaustive()
55    }
56}
57
58impl Stream {
59    /// Adopts a raw stream with the release responsibility recorded in `raw.ownership`.
60    ///
61    /// An owned handle is synchronized and destroyed when the last clone drops; a borrowed handle keeps its owner token instead.
62    /// Use [`Stream::shutdown`] to surface synchronization or destruction errors explicitly.
63    ///
64    /// # Safety
65    ///
66    /// `raw.handle` must be a valid CUDA stream of `raw.context`.
67    /// An owned handle must not be destroyed elsewhere; a borrowed handle must stay valid while its owner token lives.
68    ///
69    /// # Errors
70    ///
71    /// Returns `Error::NullHandle` if `raw.handle` is null.
72    pub unsafe fn from_raw(raw: RawStream) -> Result<Self> {
73        if raw.handle.is_null() {
74            return Err(Error::NullHandle);
75        }
76
77        let foreign_owner = match raw.ownership {
78            RawStreamOwnership::Owned => None,
79            RawStreamOwnership::Borrowed(owner) => Some(ForeignOwner(owner)),
80        };
81        Ok(Self {
82            inner: Arc::new(StreamInner {
83                handle: raw.handle,
84                capture_cleanup: CaptureCleanup::for_stream(StreamIdentity::new(
85                    &raw.context,
86                    raw.handle,
87                ))?,
88                context: raw.context,
89                foreign_owner,
90            }),
91        })
92    }
93
94    /// Borrows a stream while retaining the library object that owns its native handle.
95    /// Default legacy streams are accepted; per-thread default streams cannot be shared across threads.
96    ///
97    /// # Safety
98    ///
99    /// The handle must belong to `context` and remain valid while `owner` is retained.
100    /// External work must obey this wrapper's access ordering and capture lifecycle.
101    ///
102    /// # Errors
103    ///
104    /// Returns `Error::ThreadLocalStreamUnsupported` for the per-thread default-stream sentinel.
105    /// Also propagates context binding errors.
106    /// Other handle validity and external ownership requirements remain the caller's responsibility.
107    pub unsafe fn borrow_with_owner(
108        handle: runtime::cudaStream_t,
109        context: Arc<Context>,
110        owner: Arc<dyn Any + Send + Sync>,
111    ) -> Result<Self> {
112        if handle.addr() == PER_THREAD_STREAM {
113            return Err(Error::ThreadLocalStreamUnsupported);
114        }
115
116        context.bind()?;
117        Ok(Self {
118            inner: Arc::new(StreamInner {
119                handle,
120                capture_cleanup: CaptureCleanup::for_stream(StreamIdentity::new(&context, handle))?,
121                context,
122                foreign_owner: Some(ForeignOwner(owner)),
123            }),
124        })
125    }
126
127    #[cfg(feature = "interop_cudarc")]
128    pub(crate) fn release_foreign_owner<T: Any + Send + Sync>(&self, owner: Arc<T>) -> Result<()> {
129        use super::StreamCaptureStatus;
130        use crate::utility::lock_for_cleanup;
131
132        let mut cleanup = lock_for_cleanup(&self.inner.capture_cleanup);
133        cleanup.foreign.push(ForeignOwner(owner));
134        if self.capture_status()? == StreamCaptureStatus::None {
135            cleanup.flush_frees(self.as_raw())?;
136        }
137
138        drop(cleanup);
139        Ok(())
140    }
141}
142
143impl Stream {
144    /// Transfers the native handle, context and destruction responsibility to the caller.
145    /// Destroy owned handles explicitly; retain borrowed ownership tokens through every use.
146    /// Returns the unchanged stream if another clone or pending capture cleanup still retains it.
147    ///
148    /// # Errors
149    ///
150    /// Returns `Err(self)` if another stream clone retains the wrapper or shared capture cleanup still holds deferred owners, frees, or foreign tokens.
151    /// The returned wrapper remains usable and retains its release responsibility.
152    pub fn into_raw(self) -> StdResult<RawStream, Self> {
153        let mut inner = match Arc::try_unwrap(self.inner) {
154            Ok(inner) => inner,
155            Err(inner) => return Err(Self { inner }),
156        };
157        // A poisoned lifecycle may hold deferred work, so its stream stays owned.
158        if !inner
159            .capture_cleanup
160            .lock()
161            .is_ok_and(|cleanup| cleanup.is_empty())
162        {
163            return Err(Self {
164                inner: Arc::new(inner),
165            });
166        }
167
168        let handle = mem::replace(&mut inner.handle, ptr::null_mut());
169        let ownership = match inner.foreign_owner.take() {
170            Some(ForeignOwner(owner)) => RawStreamOwnership::Borrowed(owner),
171            None => RawStreamOwnership::Owned,
172        };
173        Ok(RawStream {
174            handle,
175            context: Arc::clone(&inner.context),
176            ownership,
177        })
178    }
179
180    pub(crate) fn destroy_handle(context: &Context, handle: runtime::cudaStream_t) -> Result<()> {
181        context.bind()?;
182        // SAFETY: the caller passes the owned stream it is destroying, live in `context`, which is bound above.
183        let sync_result = unsafe { try_ffi!(runtime::cudaStreamSynchronize(handle)) };
184        // SAFETY: the stream is owned here, nothing else destroys it, and the synchronization above drained its work.
185        let destroy_result = unsafe { try_ffi!(runtime::cudaStreamDestroy(handle)) };
186
187        match (sync_result, destroy_result) {
188            (Ok(()), Ok(())) => Ok(()),
189            (Err(error), _) | (Ok(()), Err(error)) => Err(error),
190        }
191    }
192}