Skip to main content

singe_cuda/stream/
callback.rs

1use std::{ffi, panic};
2
3use singe_cuda_sys::runtime;
4
5use super::Stream;
6use crate::{error::Result, try_ffi};
7
8// Type alias for the trait object Box itself (inner box).
9type RustStreamCallbackDyn = Box<dyn FnOnce(Result<()>) + Send + 'static>;
10
11// Type alias for the pointer type stored in the outer box.
12type BoxedCallbackPtr = *mut RustStreamCallbackDyn;
13
14type RustHostFunctionDyn = Box<dyn FnOnce() + Send + 'static>;
15
16type BoxedHostFunctionPtr = *mut RustHostFunctionDyn;
17
18impl Stream {
19    /// This callback API is slated for eventual deprecation and removal.
20    /// If you do not require the callback to execute after a device error, consider using [`sys::cudaLaunchHostFunc`](singe_cuda_sys::runtime::cudaLaunchHostFunc).
21    /// Additionally, this callback mechanism is not supported with [`Stream::begin_capture`] and [`Stream::end_capture`], unlike [`sys::cudaLaunchHostFunc`](singe_cuda_sys::runtime::cudaLaunchHostFunc).
22    ///
23    /// Adds a callback to be called on the host after all currently enqueued items in the stream have completed.
24    /// For each [`Stream::add_callback`] call, a callback is executed exactly once.
25    /// A panic in the callback is caught and reported on standard error.
26    /// The callback blocks later work in the stream until it is finished.
27    ///
28    /// The callback may be passed a successful status or an error code.
29    /// In the event of a device error, all subsequently executed callbacks receive an appropriate [`Status`](crate::error::Status).
30    ///
31    /// Callbacks must not call CUDA functions.
32    /// Attempting to do so may result in [`crate::error::Status::NotPermitted`].
33    /// Callbacks must not perform any synchronization that may depend on outstanding device work or other callbacks that are not mandated to run earlier.
34    /// Callbacks without a mandated order (in independent streams) execute in undefined order and may be serialized.
35    ///
36    /// For the purposes of Unified Memory, callback execution makes a number of guarantees:
37    ///
38    /// * The callback stream is considered idle for the duration of the callback.
39    ///   Thus, for example, a callback may always use memory attached to the callback stream.
40    /// * The start of execution of a callback has the same effect as synchronizing an event recorded in the same stream immediately before the callback.
41    ///   It thus synchronizes streams which have been "joined" before the callback.
42    /// * Adding device work to any stream does not have the effect of making the stream active until all preceding callbacks have executed.
43    ///   Thus, for example, a callback might use global attached memory even if work has been added to another stream, if it has been properly ordered with an event.
44    /// * Completion of a callback does not cause a stream to become active except as described above.
45    ///   The callback stream will remain idle if no device work follows the callback, and will remain idle across consecutive callbacks without device work in between.
46    ///   Thus, for example, stream synchronization can be done by signaling from a callback at the end of the stream.
47    ///
48    /// # Errors
49    ///
50    /// Returns an error if the context cannot be bound, CUDA rejects the callback registration, a previous asynchronous launch reports an error, or CUDA reports runtime initialization diagnostics such as [`crate::error::Status::NotInitialized`], [`crate::error::Status::CallRequiresNewerDriver`], or [`crate::error::Status::NoDevice`].
51    pub fn add_callback<F>(&self, callback: F) -> Result<()>
52    where
53        F: FnOnce(Result<()>) + Send + 'static,
54    {
55        self.inner.context.bind()?;
56
57        let boxed_dyn_callback: RustStreamCallbackDyn = Box::new(callback);
58        let boxed_wrapper: Box<RustStreamCallbackDyn> = Box::new(boxed_dyn_callback);
59        let user_data_ptr: BoxedCallbackPtr = Box::into_raw(boxed_wrapper);
60        let final_user_data = user_data_ptr.cast();
61
62        let flags = 0u32;
63
64        // SAFETY: the boxed callback is leaked into CUDA and reclaimed exactly once by the trampoline.
65        unsafe {
66            let status = runtime::cudaStreamAddCallback(
67                self.as_raw(),
68                Some(stream_callback_trampoline),
69                final_user_data, // Pass the thin pointer
70                flags,
71            );
72
73            // If adding the callback fails, manually reconstruct and drop the *outer* Box to prevent leaking both boxes.
74            if status != runtime::cudaError_t::CUDA_SUCCESS {
75                // Reconstruct the outer box (Box<Box<dyn Trait>>)
76                let _leaked_box = Box::from_raw(user_data_ptr);
77                // Drop the reconstructed outer box.
78                try_ffi!(status)?;
79            }
80        }
81
82        Ok(())
83    }
84
85    /// Enqueues a host function to run after all currently enqueued work in this stream completes.
86    ///
87    /// Unlike [`Stream::add_callback`], CUDA does not call this function if the CUDA context is already in an error state, and then drops neither it nor its captures.
88    /// The host function must not call CUDA APIs or perform synchronization that depends on outstanding device work.
89    /// A panic in the host function is caught and reported on standard error.
90    ///
91    /// # Errors
92    ///
93    /// Returns an error if the stream is capturing, since a graph would run the `FnOnce` function on every replay.
94    /// Also returns an error if the context cannot be bound, CUDA rejects the host function registration, a previous asynchronous launch reports an error, or CUDA reports runtime initialization diagnostics.
95    pub fn launch_host_func<F>(&self, function: F) -> Result<()>
96    where
97        F: FnOnce() + Send + 'static,
98    {
99        self.ensure_not_capturing()?;
100
101        let boxed_dyn_function: RustHostFunctionDyn = Box::new(function);
102        let boxed_wrapper: Box<RustHostFunctionDyn> = Box::new(boxed_dyn_function);
103        let user_data_ptr: BoxedHostFunctionPtr = Box::into_raw(boxed_wrapper);
104        let final_user_data = user_data_ptr.cast();
105
106        // SAFETY: the boxed callback is leaked into CUDA and reclaimed exactly once by the trampoline.
107        unsafe {
108            let status = runtime::cudaLaunchHostFunc(
109                self.as_raw(),
110                Some(stream_host_function_trampoline),
111                final_user_data,
112            );
113
114            if status != runtime::cudaError_t::CUDA_SUCCESS {
115                let _leaked_box = Box::from_raw(user_data_ptr);
116                try_ffi!(status)?;
117            }
118        }
119
120        Ok(())
121    }
122}
123
124// Trampoline function to bridge C FFI callback to Rust closure
125extern "C" fn stream_callback_trampoline(
126    _stream: runtime::cudaStream_t,
127    status: runtime::cudaError_t,
128    user_data: *mut ffi::c_void,
129) {
130    if user_data.is_null() {
131        return;
132    }
133
134    let user_data_ptr = user_data as BoxedCallbackPtr;
135
136    // SAFETY: CUDA calls this trampoline once with the pointer leaked when the callback was enqueued.
137    let boxed_callback: Box<RustStreamCallbackDyn> = unsafe { Box::from_raw(user_data_ptr) };
138    let callback: RustStreamCallbackDyn = *boxed_callback;
139
140    let result = if status == runtime::cudaError_t::CUDA_SUCCESS {
141        Ok(())
142    } else {
143        Err(status.into())
144    };
145
146    // Unwinding must not cross into the CUDA driver.
147    if panic::catch_unwind(panic::AssertUnwindSafe(|| callback(result))).is_err() {
148        eprintln!("cuda stream callback panicked");
149    }
150}
151
152extern "C" fn stream_host_function_trampoline(user_data: *mut ffi::c_void) {
153    if user_data.is_null() {
154        return;
155    }
156
157    let user_data_ptr = user_data as BoxedHostFunctionPtr;
158    // SAFETY: CUDA calls this trampoline once with the pointer leaked when the callback was enqueued.
159    let boxed_function: Box<RustHostFunctionDyn> = unsafe { Box::from_raw(user_data_ptr) };
160    let function: RustHostFunctionDyn = *boxed_function;
161    // Unwinding must not cross into the CUDA driver.
162    if panic::catch_unwind(panic::AssertUnwindSafe(function)).is_err() {
163        eprintln!("cuda host function panicked");
164    }
165}