singe_cuda/event.rs
1//! CUDA events, timing, and stream ordering.
2
3use std::{
4 cmp::Ordering,
5 fmt::{self, Display, Formatter},
6 mem::ManuallyDrop,
7 ptr,
8 sync::Arc,
9};
10
11use bitflags::parser;
12use singe_core::report_cleanup_failure;
13use singe_cuda_sys::{driver, runtime};
14
15use crate::{
16 context::Context,
17 error::{Error, Result},
18 stream::AsStream,
19 try_ffi,
20};
21
22bitflags::bitflags! {
23 /// Flags for CUDA event creation ([`Context::create_event`]).
24 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
25 pub struct EventFlags: u32 {
26 /// Default event flag.
27 const DEFAULT = driver::CUevent_flags::CU_EVENT_DEFAULT.0;
28 /// Event uses blocking synchronization.
29 const BLOCKING_SYNC = driver::CUevent_flags::CU_EVENT_BLOCKING_SYNC.0;
30 /// Event will not record timing data.
31 const DISABLE_TIMING = driver::CUevent_flags::CU_EVENT_DISABLE_TIMING.0;
32 /// Event is suitable for interprocess use.
33 ///
34 /// [`EventFlags::DISABLE_TIMING`] must also be set.
35 const INTERPROCESS = driver::CUevent_flags::CU_EVENT_INTERPROCESS.0;
36 }
37}
38
39impl Display for EventFlags {
40 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
41 parser::to_writer(self, f)
42 }
43}
44
45bitflags::bitflags! {
46 /// Flags controlling event recording and stream capture in [`Event::record`].
47 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
48 pub struct EventRecordFlags: u32 {
49 /// Record normally, using internal event dependencies during stream capture.
50 const DEFAULT = runtime::cudaEventRecordDefault;
51 /// Create an external event-record node during stream capture.
52 const EXTERNAL = runtime::cudaEventRecordExternal;
53 }
54}
55
56impl Display for EventRecordFlags {
57 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
58 parser::to_writer(self, f)
59 }
60}
61
62bitflags::bitflags! {
63 /// Flags controlling how a stream waits on an event, used by [`Stream::wait_event`](crate::stream::Stream::wait_event).
64 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
65 pub struct EventWaitFlags: u32 {
66 /// Wait normally, using internal event dependencies during stream capture.
67 const DEFAULT = driver::CUevent_wait_flags::CU_EVENT_WAIT_DEFAULT.0;
68 /// Create an external event-wait node during stream capture.
69 const EXTERNAL = driver::CUevent_wait_flags::CU_EVENT_WAIT_EXTERNAL.0;
70 }
71}
72
73impl Display for EventWaitFlags {
74 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
75 parser::to_writer(self, f)
76 }
77}
78
79/// A CUDA event and its retained context.
80///
81/// Recording captures preceding work on a stream; querying, waiting, and elapsed-time calculations refer to the event's most recent recording.
82/// Dropping the wrapper destroys its native event handle.
83#[derive(Debug)]
84pub struct Event {
85 handle: runtime::cudaEvent_t,
86 context: Arc<Context>,
87}
88
89/// Raw ownership of a CUDA event and the context it belongs to.
90///
91/// Destroy `handle` with CUDA while `context` is alive, or re-adopt the value with [`Event::from_raw`].
92#[derive(Debug)]
93pub struct RawEvent {
94 /// Native event handle.
95 pub handle: runtime::cudaEvent_t,
96 /// Context that owns the event.
97 pub context: Arc<Context>,
98}
99
100impl PartialEq for Event {
101 fn eq(&self, other: &Self) -> bool {
102 self.handle == other.handle && Arc::ptr_eq(&self.context, &other.context)
103 }
104}
105
106impl Eq for Event {}
107
108impl PartialOrd for Event {
109 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
110 Some(self.cmp(other))
111 }
112}
113
114impl Ord for Event {
115 fn cmp(&self, other: &Self) -> Ordering {
116 let lhs = (Arc::as_ptr(&self.context).addr(), self.handle.addr());
117 let rhs = (Arc::as_ptr(&other.context).addr(), other.handle.addr());
118 lhs.cmp(&rhs)
119 }
120}
121
122impl Event {
123 /// Takes ownership of a raw CUDA event.
124 ///
125 /// # Safety
126 ///
127 /// `raw.handle` must be a valid CUDA event created in `raw.context`, and ownership of the handle is transferred to the returned [`Event`].
128 /// The handle must not be destroyed elsewhere after calling this function.
129 ///
130 /// # Errors
131 ///
132 /// Returns `Error::NullHandle` if `raw.handle` is null.
133 pub unsafe fn from_raw(raw: RawEvent) -> Result<Self> {
134 if raw.handle.is_null() {
135 return Err(Error::NullHandle);
136 }
137
138 Ok(Self {
139 handle: raw.handle,
140 context: raw.context,
141 })
142 }
143
144 /// Records the work preceding this call on `stream`.
145 ///
146 /// Re-recording replaces the event's captured work.
147 /// `flags` controls whether capture treats this as an external event record.
148 ///
149 /// # Errors
150 ///
151 /// Returns `Error::StreamContextMismatch` if the stream and event belong to different contexts.
152 /// Also returns an error if the event context cannot be bound, CUDA rejects the recording or flags, or previous asynchronous work reports an error.
153 pub fn record(&self, stream: &(impl AsStream + ?Sized), flags: EventRecordFlags) -> Result<()> {
154 if stream.context() != self.context() {
155 return Err(Error::StreamContextMismatch);
156 }
157
158 self.context.bind()?;
159 // SAFETY: the event and stream are live handles of the bound context.
160 unsafe {
161 try_ffi!(runtime::cudaEventRecordWithFlags(
162 self.as_raw(),
163 stream.as_raw(),
164 flags.bits(),
165 ))?;
166 }
167 Ok(())
168 }
169
170 /// Queries the status of all work currently captured by event.
171 /// See [`Event::record`] for what an event captures.
172 ///
173 /// Returns `true` if all captured work has been completed, or `false` if any captured work is incomplete.
174 ///
175 /// For the purposes of Unified Memory, a return value of `true` is equivalent to having called [`Event::synchronize`].
176 ///
177 /// # Errors
178 ///
179 /// Returns an error if CUDA cannot query the event.
180 /// CUDA may also report errors from previous asynchronous launches, internal runtime initialization errors such as [`crate::error::Status::NotInitialized`], [`crate::error::Status::CallRequiresNewerDriver`], or [`crate::error::Status::NoDevice`], and callback diagnostics such as [`crate::error::Status::NotPermitted`].
181 pub fn query(&self) -> Result<bool> {
182 self.context.bind()?;
183 // SAFETY: `self` owns the live event, and its context is bound above.
184 let error = unsafe { runtime::cudaEventQuery(self.as_raw()) };
185 match error {
186 runtime::cudaError_t::CUDA_SUCCESS => Ok(true),
187 runtime::cudaError_t::CUDA_ERROR_NOT_READY => Ok(false),
188 _ => Err(error.into()),
189 }
190 }
191
192 /// Waits until the completion of all work currently captured in event.
193 /// See [`Event::record`] for what an event captures.
194 ///
195 /// Waiting for an event created with [`EventFlags::BLOCKING_SYNC`] causes the calling CPU thread to block until the event has been completed by the device.
196 /// Without [`EventFlags::BLOCKING_SYNC`], the CPU thread will busy-wait until the event has been completed by the device.
197 ///
198 /// # Errors
199 ///
200 /// Returns an error if CUDA cannot wait for the event.
201 /// CUDA may also report errors from previous asynchronous launches, internal runtime initialization errors such as [`crate::error::Status::NotInitialized`], [`crate::error::Status::CallRequiresNewerDriver`], or [`crate::error::Status::NoDevice`], and callback diagnostics such as [`crate::error::Status::NotPermitted`].
202 pub fn synchronize(&self) -> Result<()> {
203 self.context.bind()?;
204 // SAFETY: `self` owns the live event, and its context is bound above.
205 unsafe {
206 try_ffi!(runtime::cudaEventSynchronize(self.as_raw()))?;
207 }
208 Ok(())
209 }
210
211 /// Computes the elapsed time between two events (in milliseconds with a resolution of around 0.5 microseconds).
212 /// Note this call is not guaranteed to return the latest errors for pending work.
213 /// Use it only for elapsed-time calculation; poll for completion on the events to be compared with [`Event::query`] instead.
214 ///
215 /// If either event was last recorded in a non-default stream, the resulting time may be greater than expected, even if both used the same stream handle.
216 /// This happens because [`Event::record`] takes place asynchronously and there is no guarantee that the measured latency is actually just between the two events.
217 /// Any number of other different stream operations could execute in between the two measured events, thus altering the timing in a significant way.
218 ///
219 /// If either event has not been recorded with [`Event::record`], [`crate::error::Status::InvalidHandle`] is returned.
220 /// If both events have been recorded but one or both of them has not yet been completed (that is, [`Event::query`] returns `false` for at least one of them), [`crate::error::Status::NotReady`] is returned.
221 /// If either event was created with [`EventFlags::DISABLE_TIMING`], this returns [`crate::error::Status::InvalidHandle`].
222 ///
223 /// # Errors
224 ///
225 /// Returns an error if the events belong to different contexts, either event has not been recorded, either event is incomplete, timing was disabled on either event, or CUDA rejects the elapsed-time query.
226 /// CUDA may also report errors from previous asynchronous launches, internal runtime initialization errors such as [`crate::error::Status::NotInitialized`], [`crate::error::Status::CallRequiresNewerDriver`], or [`crate::error::Status::NoDevice`], and callback diagnostics such as [`crate::error::Status::NotPermitted`].
227 pub fn elapsed_time_since(&self, start: &Self) -> Result<f32> {
228 if self.context() != start.context() {
229 return Err(Error::context_mismatch("start event"));
230 }
231
232 self.context.bind()?;
233 let mut milliseconds = 0.0f32;
234 // SAFETY: both events are live, owned by their wrappers, and of the context bound above, and `milliseconds` is a local output.
235 unsafe {
236 try_ffi!(runtime::cudaEventElapsedTime(
237 &raw mut milliseconds,
238 start.as_raw(),
239 self.as_raw(),
240 ))?;
241 }
242 Ok(milliseconds)
243 }
244
245 /// Returns the context retained by this event.
246 #[must_use]
247 pub fn context(&self) -> &Arc<Context> {
248 &self.context
249 }
250
251 /// Returns the borrowed native event handle without transferring ownership.
252 #[must_use]
253 pub const fn as_raw(&self) -> runtime::cudaEvent_t {
254 self.handle
255 }
256
257 /// Consumes the event and returns its raw handle and context without destroying the handle.
258 ///
259 /// The caller becomes responsible for eventually destroying the returned handle with CUDA.
260 #[must_use]
261 pub fn into_raw(self) -> RawEvent {
262 let event = ManuallyDrop::new(self);
263 RawEvent {
264 handle: event.handle,
265 // SAFETY: `event` is never dropped or used again, so its context is moved out exactly once.
266 context: unsafe { ptr::read(&raw const event.context) },
267 }
268 }
269}
270
271// SAFETY: CUDA event handles may be recorded, queried, synchronized, and destroyed from any host thread once their context is bound, which every method and `Drop` do first.
272unsafe impl Send for Event {}
273
274// SAFETY: every `&self` method is a thread-safe driver call on the handle, and recording through `&self` only changes native state, never Rust-owned state.
275unsafe impl Sync for Event {}
276
277impl Drop for Event {
278 fn drop(&mut self) {
279 if let Err(error) = self.context.bind() {
280 report_cleanup_failure("bind the cuda context to destroy", "cuda event", &error);
281 return;
282 }
283
284 // SAFETY: `self` owns the live event, its context is bound above, and CUDA defers destruction until recorded work completes.
285 if let Err(error) = unsafe { try_ffi!(runtime::cudaEventDestroy(self.handle)) } {
286 report_cleanup_failure("destroy", "cuda event", &error);
287 }
288 }
289}
290
291impl Context {
292 /// Creates an event in this context with the specified flags.
293 /// Valid flags include:
294 ///
295 /// * [`EventFlags::DEFAULT`]: default event creation flag.
296 /// * [`EventFlags::BLOCKING_SYNC`]: the event uses blocking synchronization.
297 /// A host thread that uses [`Event::synchronize`] to wait on an event created with this flag will block until the event actually completes.
298 /// * [`EventFlags::DISABLE_TIMING`]: the created event does not record timing data.
299 /// Events created with this flag specified and [`EventFlags::BLOCKING_SYNC`] not specified will provide the best performance when used with [`Stream::wait_event`](crate::stream::Stream::wait_event) and [`Event::query`].
300 /// * [`EventFlags::INTERPROCESS`]: the created event may be shared with another process through an [`IpcEventHandle`](crate::ipc::IpcEventHandle).
301 /// [`EventFlags::INTERPROCESS`] must be specified along with [`EventFlags::DISABLE_TIMING`].
302 ///
303 /// # Errors
304 ///
305 /// Returns an error if the context cannot be bound, the flag combination is invalid, CUDA cannot create the event, or CUDA returns a null event handle.
306 /// CUDA may also report errors from previous asynchronous launches, internal runtime initialization errors such as [`crate::error::Status::NotInitialized`], [`crate::error::Status::CallRequiresNewerDriver`], or [`crate::error::Status::NoDevice`], and callback diagnostics such as [`crate::error::Status::NotPermitted`].
307 pub fn create_event(self: &Arc<Self>, flags: EventFlags) -> Result<Event> {
308 self.bind()?;
309 let mut handle = ptr::null_mut();
310 // SAFETY: `handle` is a local output, and this context is bound above.
311 unsafe {
312 try_ffi!(runtime::cudaEventCreateWithFlags(
313 &raw mut handle,
314 flags.bits()
315 ))?;
316 }
317
318 if handle.is_null() {
319 return Err(Error::NullHandle);
320 }
321 // SAFETY: CUDA just created this handle in this context, and nothing else owns it.
322 unsafe {
323 Event::from_raw(RawEvent {
324 handle,
325 context: Arc::clone(self),
326 })
327 }
328 }
329}