singe_cuda/context.rs
1//! Shared CUDA contexts, primary-context retention, and code loading.
2
3use std::{
4 any::Any,
5 ffi::CString,
6 fmt::{self, Display, Formatter},
7 hash::{Hash, Hasher},
8 mem, ptr,
9 result::Result as StdResult,
10 sync::{Arc, Mutex},
11};
12
13use bitflags::parser;
14use singe_core::report_cleanup_failure;
15use singe_cuda_sys::{driver, runtime};
16
17use crate::{
18 device::{Device, Limit},
19 error::{Error, Result},
20 graph::Graph,
21 jit::JitOptions,
22 library::{Library, RawLibrary},
23 memory::PinnedPool,
24 module::{Module, ModuleImage, artifact::ArtifactMetadata},
25 submission::{Access, AccessGuard, AccessMode, AccessTracker, lock_access},
26 try_ffi,
27 utility::{to_u32, to_usize},
28 view::DeviceRegion,
29};
30
31bitflags::bitflags! {
32 /// Context creation flags.
33 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
34 pub struct ContextFlags: u32 {
35 /// Automatic scheduling.
36 const SCHEDULE_AUTO = driver::CUctx_flags::CU_CTX_SCHED_AUTO.0;
37 /// Set spin as default scheduling.
38 const SCHEDULE_SPIN = driver::CUctx_flags::CU_CTX_SCHED_SPIN.0;
39 /// Set yield as default scheduling.
40 const SCHEDULE_YIELD = driver::CUctx_flags::CU_CTX_SCHED_YIELD.0;
41 /// Set blocking synchronization as default scheduling.
42 const SCHEDULE_BLOCKING_SYNC = driver::CUctx_flags::CU_CTX_SCHED_BLOCKING_SYNC.0;
43 /// Deprecated: This flag was deprecated as of CUDA 11.0 and it no longer has any effect.
44 /// All contexts as of CUDA 3.2 behave as though the flag is enabled.
45 const MAP_HOST = driver::CUctx_flags::CU_CTX_MAP_HOST.0;
46 /// Keep local memory allocation after launch.
47 const LOCAL_MEMORY_RESIZE_TO_MAX = driver::CUctx_flags::CU_CTX_LMEM_RESIZE_TO_MAX.0;
48 /// Trigger coredumps from exceptions in this context.
49 const COREDUMP_ENABLE = driver::CUctx_flags::CU_CTX_COREDUMP_ENABLE.0;
50 /// Enable user pipe to trigger coredumps in this context.
51 const USER_COREDUMP_ENABLE = driver::CUctx_flags::CU_CTX_USER_COREDUMP_ENABLE.0;
52 /// Ensure synchronous memory operations on this context will synchronize.
53 const SYNC_MEMORY_OPERATIONS = driver::CUctx_flags::CU_CTX_SYNC_MEMOPS.0;
54 }
55}
56
57impl Display for ContextFlags {
58 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
59 parser::to_writer(self, f)
60 }
61}
62
63bitflags::bitflags! {
64 /// Flags for [`Context::enable_peer_access`].
65 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
66 pub struct PeerAccessFlags: u32 {
67 /// Default peer-access behavior.
68 const DEFAULT = 0;
69 }
70}
71
72impl Display for PeerAccessFlags {
73 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
74 parser::to_writer(self, f)
75 }
76}
77
78/// A shared CUDA driver context.
79///
80/// Unlike cuBLAS, cuDNN, cuFFT, and similar library handles, a CUDA context is the underlying execution environment for a device.
81/// It is intended to be shared by streams, modules, libraries, events, allocations, and higher-level library wrappers.
82///
83/// This type is therefore reference-counted by returning [`Arc<Self>`] from the constructors, and it remains `Send + Sync`.
84/// Shared references do not mutate Rust-visible state on the [`Context`] object itself; methods such as `bind` update the calling thread's current CUDA context in the driver.
85///
86/// Prefer one long-lived context per device and share it across dependent CUDA objects instead of creating many short-lived contexts.
87#[derive(Debug)]
88pub struct Context {
89 handle: driver::CUcontext,
90 device: Device,
91 ownership: RawContextOwnership,
92 pub(crate) access_tracker: Arc<Mutex<AccessTracker>>,
93 pub(crate) pinned: PinnedPool,
94}
95
96/// Raw ownership of a CUDA context.
97///
98/// Release `handle` according to `ownership`, or re-adopt the value with [`Context::from_raw`].
99#[derive(Debug)]
100pub struct RawContext {
101 /// Native context handle.
102 pub handle: driver::CUcontext,
103 /// Device the context belongs to.
104 pub device: Device,
105 /// Release responsibility for `handle`.
106 pub ownership: RawContextOwnership,
107}
108
109/// Native release responsibility, including a retained external ownership token.
110#[derive(Clone)]
111#[non_exhaustive]
112pub enum RawContextOwnership {
113 /// Destroys the context when the last wrapper is dropped.
114 Created,
115 /// Releases one retained primary-context reference when the last wrapper is dropped.
116 Primary,
117 /// Keeps an external owner alive without destroying or releasing the native context.
118 Borrowed(
119 /// External ownership token retained for the lifetime of this wrapper.
120 Arc<dyn Any + Send + Sync>,
121 ),
122}
123
124impl fmt::Debug for RawContextOwnership {
125 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
126 f.write_str(match self {
127 Self::Created => "Created",
128 Self::Primary => "Primary",
129 Self::Borrowed(_) => "Borrowed",
130 })
131 }
132}
133
134impl Context {
135 /// Holds submitted accesses out of the supplied ranges while host code runs.
136 /// Nested tracked access returns an error instead of waiting on its own host access guard.
137 ///
138 /// # Errors
139 ///
140 /// Returns `Error::MemoryContextMismatch` for a range belonging to another context, `Error::ReentrantAccess` for nested tracked access, or `Error::LockPoisoned` if tracking has failed or a tracking lock is poisoned.
141 /// Also propagates CUDA synchronization or event-query errors and errors returned by `access`.
142 /// The callback runs only after all required waits succeed.
143 pub fn with_host_access<T>(
144 &self,
145 regions: &[DeviceRegion<'_>],
146 access: impl FnOnce() -> Result<T>,
147 ) -> Result<T> {
148 let _guard = self.acquire_host_access(regions)?;
149 access()
150 }
151
152 /// Waits for conflicting submitted uses and declared readiness streams, then holds these access declarations against concurrent tracked submissions while `access` runs.
153 /// The declarations retain context and ordering metadata, not allocation owners.
154 ///
155 /// # Safety
156 ///
157 /// Keep the declared storage live and obey each declaration's access mode.
158 /// Any asynchronous work using these ranges must complete before the callback returns or unwinds.
159 /// Nested tracked access is rejected rather than waiting on its own guard.
160 ///
161 /// # Errors
162 ///
163 /// Converts tracking errors into `E` if a nonportable access belongs to another context, access is reentrant, tracking has failed, or a tracking lock is poisoned.
164 /// Also converts errors from synchronizing conflicting uses or readiness streams and querying completion events.
165 /// Errors returned by `access` pass through unchanged; the callback runs only after all required waits succeed.
166 pub unsafe fn with_synchronized_accesses<T, E>(
167 &self,
168 accesses: &[Access],
169 access: impl FnOnce() -> StdResult<T, E>,
170 ) -> StdResult<T, E>
171 where
172 E: From<Error>,
173 {
174 let _guard = self.acquire_accesses(accesses)?;
175 access()
176 }
177
178 pub(crate) fn acquire_host_access(
179 &self,
180 regions: &[DeviceRegion<'_>],
181 ) -> Result<AccessGuard<'_>> {
182 let accesses: Vec<_> = regions
183 .iter()
184 .map(|®ion| Access::new(region, AccessMode::ReadWrite))
185 .collect();
186 self.acquire_accesses(&accesses)
187 }
188
189 pub(crate) fn acquire_accesses(&self, accesses: &[Access]) -> Result<AccessGuard<'_>> {
190 for access in accesses {
191 access.validate_context(self)?;
192 }
193
194 let mut tracker = lock_access(&self.access_tracker, accesses)?;
195 for access in accesses {
196 tracker.synchronize_access(access)?;
197 if let Some(stream) = &access.readiness {
198 stream.synchronize()?;
199 }
200 }
201 Ok(tracker)
202 }
203
204 /// Enables this actual context to directly access `peer` allocations.
205 /// Already-enabled access succeeds.
206 /// The permission is unidirectional and persists until explicitly disabled or either context is destroyed.
207 /// Pool allocations additionally follow their pool's access descriptors.
208 ///
209 /// # Errors
210 ///
211 /// Returns `Error::OutOfRange` for nondefault flags.
212 /// Also returns an error if this context cannot be bound or CUDA rejects peer access, for example because the device pair does not support it or the peer-access limit is reached.
213 /// Already-enabled access succeeds.
214 pub fn enable_peer_access(&self, peer: &Self, flags: PeerAccessFlags) -> Result<()> {
215 if flags != PeerAccessFlags::DEFAULT {
216 return Err(Error::out_of_range("peer access flags"));
217 }
218
219 self.bind()?;
220 // SAFETY: `self` is bound above, and `peer` keeps its context handle live for the call.
221 let status = unsafe { driver::cuCtxEnablePeerAccess(peer.as_raw(), flags.bits()) };
222 if status == driver::CUresult::CUDA_ERROR_PEER_ACCESS_ALREADY_ENABLED {
223 return Ok(());
224 }
225 try_ffi!(status)
226 }
227
228 /// Disables this actual context's direct access to `peer` allocations.
229 ///
230 /// # Safety
231 ///
232 /// Complete every access that relies on this permission, including graph replays, before disabling it.
233 /// Do not use retained peer-copy objects or peer pointers again until access is re-enabled.
234 /// Exclude concurrent uses.
235 ///
236 /// # Errors
237 ///
238 /// Returns an error if this context cannot be bound or CUDA cannot disable the permission, including when peer access is not enabled.
239 pub unsafe fn disable_peer_access(&self, peer: &Self) -> Result<()> {
240 self.bind()?;
241 // SAFETY: `self` is bound above and `peer` keeps its context live; the caller guarantees no access still relies on the permission.
242 unsafe { try_ffi!(driver::cuCtxDisablePeerAccess(peer.as_raw())) }
243 }
244
245 /// Retains the primary context of the calling thread's current runtime device and makes it current.
246 ///
247 /// The primary context is shared with the CUDA runtime and other libraries on the same device.
248 /// Use [`Self::create_dedicated`] for a separate execution environment.
249 ///
250 /// # Errors
251 ///
252 /// Propagates errors from querying the current runtime device or from [`Self::create_for_device`].
253 pub fn create() -> Result<Arc<Self>> {
254 Self::create_for_device(Device::current()?)
255 }
256
257 /// Creates a new context for `device` with `flags` and makes it current on the calling thread.
258 ///
259 /// The last owning wrapper destroys this context.
260 /// It is a separate execution environment from the device's primary context and from other created contexts.
261 ///
262 /// # Errors
263 ///
264 /// Returns an error if CUDA initialization or context creation fails, including invalid creation flags, an unavailable device, or insufficient resources.
265 /// Returns `Error::NullHandle` if CUDA reports success with a null context handle.
266 pub fn create_dedicated(device: Device, flags: ContextFlags) -> Result<Arc<Self>> {
267 // SAFETY: `handle` is a writable local, the null creation parameters select the defaults, and `cuInit` runs first.
268 unsafe {
269 try_ffi!(driver::cuInit(0))?;
270
271 let mut handle = ptr::null_mut();
272 try_ffi!(driver::cuCtxCreate_v4(
273 &raw mut handle,
274 ptr::null_mut(),
275 flags.bits(),
276 device.id(),
277 ))?;
278
279 if handle.is_null() {
280 return Err(Error::NullHandle);
281 }
282
283 // The context was just created and nothing else refers to it, so a failed lookup destroys it.
284 let access_tracker = AccessTracker::for_context(handle.addr()).inspect_err(|_| {
285 if let Err(error) = try_ffi!(driver::cuCtxDestroy_v2(handle)) {
286 report_cleanup_failure("destroy", "cuda context", &error);
287 }
288 })?;
289 Ok(Arc::new(Self {
290 handle,
291 device,
292 ownership: RawContextOwnership::Created,
293 access_tracker,
294 pinned: PinnedPool::default(),
295 }))
296 }
297 }
298
299 /// Retains the primary context for `device` and makes it current on the calling thread.
300 ///
301 /// The device's primary context is shared with the CUDA runtime.
302 /// Dropping the last owning wrapper releases this retain; other native retainers may keep the context alive.
303 ///
304 /// # Errors
305 ///
306 /// Returns an error if CUDA initialization, retaining the primary context, or setting it current fails.
307 /// Returns `Error::NullHandle` if CUDA reports success with a null context handle.
308 pub fn create_for_device(device: Device) -> Result<Arc<Self>> {
309 let mut handle = ptr::null_mut();
310 // SAFETY: `handle` is a writable local, and `cuInit` runs first.
311 unsafe {
312 try_ffi!(driver::cuInit(0))?;
313 try_ffi!(driver::cuDevicePrimaryCtxRetain(
314 &raw mut handle,
315 device.id(),
316 ))?;
317 }
318
319 let access_tracker = if handle.is_null() {
320 Err(Error::NullHandle)
321 } else {
322 AccessTracker::for_context(handle.addr())
323 }
324 .inspect_err(|_| {
325 // SAFETY: releases only the primary-context retain taken above.
326 let result = unsafe { try_ffi!(driver::cuDevicePrimaryCtxRelease_v2(device.id())) };
327 if let Err(error) = result {
328 report_cleanup_failure("release", "cuda primary context", &error);
329 }
330 })?;
331
332 // From here on, dropping the wrapper releases the retain.
333 let context = Arc::new(Self {
334 handle,
335 device,
336 ownership: RawContextOwnership::Primary,
337 access_tracker,
338 pinned: PinnedPool::default(),
339 });
340
341 context.bind()?;
342 Ok(context)
343 }
344
345 // Green contexts belong to their device's primary context, so code loaded there is the only code they may launch.
346 pub(crate) fn is_primary_for(&self, device: Device) -> Result<bool> {
347 if self.device != device {
348 return Ok(false);
349 }
350
351 match self.ownership {
352 RawContextOwnership::Primary => Ok(true),
353 RawContextOwnership::Created => Ok(false),
354 RawContextOwnership::Borrowed(_) => {
355 let mut primary = ptr::null_mut();
356 // SAFETY: `primary` is a writable local, and the retain taken here is released right below.
357 unsafe {
358 try_ffi!(driver::cuDevicePrimaryCtxRetain(
359 &raw mut primary,
360 device.id(),
361 ))?;
362 }
363
364 // SAFETY: releases only the primary-context retain taken above.
365 unsafe {
366 try_ffi!(driver::cuDevicePrimaryCtxRelease_v2(device.id()))?;
367 }
368
369 Ok(primary == self.handle)
370 }
371 }
372 }
373
374 /// Binds this CUDA context to the calling CPU thread.
375 ///
376 /// The "current context" is thread-local driver state.
377 /// Calling this method does not mutate the Rust [`Context`] value itself; it makes this context current for subsequent CUDA driver and interoperating runtime calls on the current host thread.
378 ///
379 /// # Errors
380 ///
381 /// Returns an error if CUDA Driver cannot query or set the current context.
382 pub fn bind(&self) -> Result<()> {
383 // SAFETY: `current_context` is a writable local, and `self.handle` is the live context this wrapper owns or borrows.
384 unsafe {
385 let mut current_context = ptr::null_mut();
386 try_ffi!(driver::cuCtxGetCurrent(&raw mut current_context))?;
387 if current_context == self.as_raw() {
388 return Ok(());
389 }
390
391 try_ffi!(driver::cuCtxSetCurrent(self.as_raw()))?;
392 }
393 Ok(())
394 }
395
396 /// Loads the corresponding module from the given image into this context with `jit_options`.
397 /// The image may be a cubin or fatbin as output by **nvcc**, or a NUL-terminated PTX string, either as output by **nvcc** or hand-written, or Tile IR data.
398 ///
399 /// # Errors
400 ///
401 /// Returns an error if the context cannot be bound, the JIT option count exceeds `u32`, CUDA rejects the image or JIT options, or a previous asynchronous launch reported an error.
402 pub fn load_module(
403 self: &Arc<Self>,
404 image: &ModuleImage<'_>,
405 jit_options: JitOptions<'_>,
406 ) -> Result<Module> {
407 self.load_module_with_metadata(image, jit_options, None)
408 }
409
410 pub(crate) fn load_module_with_metadata(
411 self: &Arc<Self>,
412 image: &ModuleImage<'_>,
413 mut jit_options: JitOptions<'_>,
414 metadata: Option<Arc<ArtifactMetadata>>,
415 ) -> Result<Module> {
416 self.bind()?;
417
418 let mut jit_options = jit_options.build();
419 // SAFETY: every `ModuleImage` is nonempty NUL-terminated PTX or a self-describing binary, so the length-less loader stays in bounds, and the options arrays have matching lengths.
420 unsafe {
421 let mut module_handle = ptr::null_mut();
422 try_ffi!(driver::cuModuleLoadDataEx(
423 &raw mut module_handle,
424 image.as_ptr().cast(),
425 to_u32(jit_options.names.len(), "JIT option count")?,
426 jit_options.names.as_mut_ptr().cast(),
427 jit_options.values.as_mut_ptr().cast(),
428 ))?;
429 Module::from_raw_with_metadata(module_handle, Arc::clone(self), metadata)
430 }
431 }
432
433 /// Creates an empty CUDA graph associated with this context.
434 ///
435 /// Prefer this over [`UnboundGraph::create`](crate::graph::UnboundGraph::create) for ordinary Singe code.
436 /// The returned graph carries its context association into instantiated executable graphs, allowing launches and uploads to reject streams from another context before calling CUDA.
437 ///
438 /// # Errors
439 ///
440 /// Returns an error if the context cannot be bound or CUDA cannot create the graph.
441 pub fn create_graph(self: &Arc<Self>) -> Result<Graph> {
442 Graph::create_in_context(Arc::clone(self))
443 }
444
445 /// Loads the corresponding library from the given image with `jit_options`, based on the application defined library loading mode:
446 ///
447 /// * If module loading is set to EAGER by the environment variables described in "Module loading", the library is loaded eagerly into all contexts at the time of the call and future contexts at the time of creation until the library is unloaded with [`sys::cuLibraryUnload`](singe_cuda_sys::driver::cuLibraryUnload).
448 /// * If the environment variables are set to LAZY, the library is not immediately loaded into existing contexts and is loaded only when a function is needed for that context, such as a kernel launch.
449 ///
450 /// These environment variables are described in the CUDA programming guide under the "CUDA environment variables" section.
451 ///
452 /// The code may be a cubin or fatbin emitted by **nvcc**, a NUL-terminated PTX string emitted by **nvcc** or written by hand, or Tile IR data.
453 /// A fatbin must also contain relocatable code when doing separate compilation.
454 ///
455 /// If the library contains managed variables and no device in the system supports them, this call returns [`crate::error::Status::NotSupported`].
456 ///
457 /// # Errors
458 ///
459 /// Returns an error if the context cannot be bound, the JIT option count exceeds `u32`, or CUDA rejects the image, options, or required device features.
460 /// Returns `Error::NullHandle` if CUDA reports success with a null library handle.
461 /// CUDA may also report errors from previous asynchronous work.
462 pub fn load_library(
463 self: &Arc<Self>,
464 image: &ModuleImage<'_>,
465 mut jit_options: JitOptions<'_>,
466 ) -> Result<Library> {
467 self.bind()?;
468
469 let mut jit_options = jit_options.build();
470 let mut handle = ptr::null_mut();
471 // SAFETY: every `ModuleImage` is nonempty NUL-terminated PTX or a self-describing binary, so the length-less loader stays in bounds, and the options arrays have matching lengths.
472 unsafe {
473 try_ffi!(driver::cuLibraryLoadData(
474 &raw mut handle,
475 image.as_ptr().cast(),
476 jit_options.names.as_mut_ptr().cast(),
477 jit_options.values.as_mut_ptr().cast(),
478 to_u32(jit_options.names.len(), "JIT option count")?,
479 ptr::null_mut(),
480 ptr::null_mut(),
481 0,
482 ))?;
483 }
484
485 if handle.is_null() {
486 return Err(Error::NullHandle);
487 }
488 // SAFETY: CUDA just created this handle in this context, and nothing else owns it.
489 unsafe {
490 Library::from_raw(RawLibrary {
491 handle,
492 context: Arc::clone(self),
493 })
494 }
495 }
496
497 /// Loads the corresponding library from the given file based on the application defined library loading mode:
498 ///
499 /// * If module loading is set to EAGER by the environment variables described in "Module loading", the library is loaded eagerly into all contexts at the time of the call and future contexts at the time of creation until the library is unloaded with [`sys::cuLibraryUnload`](singe_cuda_sys::driver::cuLibraryUnload).
500 /// * If the environment variables are set to LAZY, the library is not immediately loaded into existing contexts and is loaded only when a function is needed for that context, such as a kernel launch.
501 ///
502 /// These environment variables are described in the CUDA programming guide under the "CUDA environment variables" section.
503 ///
504 /// The file must be a cubin emitted by **nvcc**, a PTX file emitted by **nvcc** or written by hand, a fatbin emitted by **nvcc** or written by hand, or a Tile IR file.
505 /// A fatbin must also contain relocatable code when doing separate compilation.
506 ///
507 /// If the library contains managed variables and no device in the system supports them, this call returns [`crate::error::Status::NotSupported`].
508 ///
509 /// # Errors
510 ///
511 /// Returns an error if this context cannot be bound, if `path` contains an interior NUL byte, or if CUDA Driver cannot load the library.
512 pub fn load_library_from_file(self: &Arc<Self>, path: &str) -> Result<Library> {
513 self.bind()?;
514 let path = CString::new(path)?;
515 let mut handle = ptr::null_mut();
516 // SAFETY: `handle` is a writable local, `path` is a NUL-terminated string live for the call, and every option array is null with a zero count.
517 unsafe {
518 try_ffi!(driver::cuLibraryLoadFromFile(
519 &raw mut handle,
520 path.as_ptr(),
521 ptr::null_mut(),
522 ptr::null_mut(),
523 0,
524 ptr::null_mut(),
525 ptr::null_mut(),
526 0,
527 ))?;
528 }
529
530 if handle.is_null() {
531 return Err(Error::NullHandle);
532 }
533 // SAFETY: CUDA just created this handle in this context, and nothing else owns it.
534 unsafe {
535 Library::from_raw(RawLibrary {
536 handle,
537 context: Arc::clone(self),
538 })
539 }
540 }
541
542 /// Blocks until the current context has completed all preceding requested tasks.
543 /// If the current context is the primary context, child contexts that have been created are also synchronized.
544 /// [`Context::synchronize`] returns an error if one of the preceding tasks failed.
545 /// If the context was created with [`ContextFlags::SCHEDULE_BLOCKING_SYNC`], the CPU thread blocks until the GPU context has finished its work.
546 ///
547 /// # Errors
548 ///
549 /// Returns an error if the context cannot be bound, a preceding task failed, or a previous asynchronous launch reported an error.
550 pub fn synchronize(&self) -> Result<()> {
551 self.bind()?;
552 // SAFETY: `cuCtxSynchronize` takes no arguments and waits on the context bound above.
553 unsafe {
554 try_ffi!(driver::cuCtxSynchronize())?;
555 }
556 Ok(())
557 }
558
559 /// Returns the flags of the current context.
560 /// See [`ContextFlags`] for flag values.
561 ///
562 /// # Errors
563 ///
564 /// Returns an error if the context cannot be bound, CUDA cannot query the flags, or a previous asynchronous launch reported an error.
565 pub fn flags(&self) -> Result<ContextFlags> {
566 self.bind()?;
567 // SAFETY: `flags` is a local that `cuCtxGetFlags` writes through an exclusive pointer.
568 unsafe {
569 let mut flags = 0;
570 try_ffi!(driver::cuCtxGetFlags(&raw mut flags))?;
571 Ok(ContextFlags::from_bits_truncate(flags))
572 }
573 }
574
575 /// Returns the current size of limit.
576 /// The supported [`Limit`] values are:
577 ///
578 /// * [`Limit::StackSize`]: stack size in bytes of each GPU thread.
579 /// * [`Limit::PrintfFifoSize`]: size in bytes of the FIFO used by the `printf()` device system call.
580 /// * [`Limit::MallocHeapSize`]: size in bytes of the heap used by the `malloc()` and `free()` device system calls.
581 /// * [`Limit::DevRuntimeSyncDepth`]: maximum grid depth at which a thread can issue the device runtime call [`Device::synchronize`] to wait on child grid launches to complete.
582 /// * [`Limit::DevRuntimePendingLaunchCount`]: maximum number of outstanding device runtime launches that can be made from this context.
583 /// * [`Limit::MaxL2FetchGranularity`]: L2 cache fetch granularity.
584 /// * [`Limit::PersistingL2CacheSize`]: persisting L2 cache size in bytes.
585 ///
586 /// # Errors
587 ///
588 /// Returns an error if the context cannot be bound, `limit` is unsupported, CUDA cannot query the limit, or a previous asynchronous launch reported an error.
589 pub fn limit(&self, limit: Limit) -> Result<usize> {
590 self.bind()?;
591 // SAFETY: `value` is a local that `cuCtxGetLimit` writes through an exclusive pointer.
592 unsafe {
593 let mut value = 0;
594 try_ffi!(driver::cuCtxGetLimit(&raw mut value, driver_limit(limit)))?;
595 to_usize(value, "context limit")
596 }
597 }
598
599 /// Setting limit to value is a request by the application to update the current limit maintained by the context.
600 /// The driver may modify the requested value to meet hardware requirements, such as clamping to minimum or maximum values or rounding up to the nearest element size.
601 /// Use [`Context::limit`] to query the effective value.
602 ///
603 /// Setting each [`Limit`] has its own restrictions.
604 ///
605 /// * [`Limit::StackSize`] controls the stack size in bytes of each GPU thread.
606 /// The driver automatically increases the per-thread stack size for each kernel launch as needed.
607 /// This size is not reset back to the original value after each launch.
608 /// Setting this value will take effect immediately, and if necessary, the device will block until all preceding requested tasks are complete.
609 ///
610 /// * [`Limit::PrintfFifoSize`] controls the size in bytes of the FIFO used by the `printf()` device system call.
611 /// Configure [`Limit::PrintfFifoSize`] before launching any kernel that uses the `printf()` device system call; otherwise [`crate::error::Status::InvalidValue`] is returned.
612 ///
613 /// * [`Limit::MallocHeapSize`] controls the size in bytes of the heap used by the `malloc()` and `free()` device system calls.
614 /// Configure [`Limit::MallocHeapSize`] before launching any kernel that uses the `malloc()` or `free()` device system calls; otherwise [`crate::error::Status::InvalidValue`] is returned.
615 ///
616 /// * [`Limit::DevRuntimeSyncDepth`] controls the maximum nesting depth of a grid at which a thread can safely call [`Device::synchronize`].
617 /// Setting this limit must be performed before any launch of a kernel that uses the device runtime and calls [`Device::synchronize`] above the default sync depth, two levels of grids.
618 /// Calls to [`Device::synchronize`] fail if this limit is violated.
619 /// This limit can be set smaller than the default or up to the maximum launch depth of 24.
620 /// Additional sync-depth levels require the driver to reserve large amounts of device memory that can no longer be used for application allocations.
621 /// If these reservations of device memory fail, [`Context::set_limit`] returns [`crate::error::Status::OutOfMemory`], and the limit can be reset to a lower value.
622 /// This limit is only applicable to devices of compute capability < 9.0.
623 /// Setting this limit on devices of other compute capability versions returns [`crate::error::Status::UnsupportedLimit`].
624 ///
625 /// * [`Limit::DevRuntimePendingLaunchCount`] controls the maximum number of outstanding device runtime launches that can be made from the current context.
626 /// A grid is outstanding from launch until it is known to have completed.
627 /// Device runtime launches that violate this limit fail.
628 /// If a module using the device runtime needs more pending launches than the default 2048 launches, this limit can be increased.
629 /// Sustaining additional pending launches requires the driver to reserve larger amounts of device memory up front, which can no longer be used for allocations.
630 /// If these reservations fail, [`Context::set_limit`] returns [`crate::error::Status::OutOfMemory`], and the limit can be reset to a lower value.
631 /// This limit is only applicable to devices of compute capability 3.5 and higher.
632 /// Attempting to set this limit on devices of compute capability less than 3.5 returns [`crate::error::Status::UnsupportedLimit`].
633 ///
634 /// * [`Limit::MaxL2FetchGranularity`] controls the L2 cache fetch granularity.
635 /// Values can range from 0B to 128B.
636 /// Performance hint that may be ignored or clamped depending on the platform.
637 ///
638 /// * [`Limit::PersistingL2CacheSize`] controls size in bytes available for persisting L2 cache.
639 /// Performance hint that may be ignored or clamped depending on the platform.
640 ///
641 /// # Errors
642 ///
643 /// Returns an error if the context cannot be bound, `limit` is unsupported, CUDA rejects the requested value, or a previous asynchronous launch reported an error.
644 pub fn set_limit(&self, limit: Limit, value: usize) -> Result<()> {
645 self.bind()?;
646 let value = value
647 .try_into()
648 .map_err(|_| Error::out_of_range("context limit value"))?;
649 // SAFETY: `cuCtxSetLimit` receives only values, and applies them to the context bound above.
650 unsafe {
651 try_ffi!(driver::cuCtxSetLimit(driver_limit(limit), value))?;
652 }
653 Ok(())
654 }
655
656 /// Returns the device associated with this context.
657 #[must_use]
658 pub const fn device(&self) -> Device {
659 self.device
660 }
661
662 /// Returns the borrowed native context handle.
663 ///
664 /// The handle remains owned according to this wrapper's [`RawContextOwnership`].
665 /// Returning it does not retain the context or transfer release responsibility.
666 #[must_use]
667 pub const fn as_raw(&self) -> driver::CUcontext {
668 self.handle
669 }
670
671 /// Takes ownership of a raw CUDA context.
672 ///
673 /// # Safety
674 ///
675 /// `raw.handle` must be a valid CUDA context for `raw.device`, and no other Rust wrapper may own the same release responsibility.
676 /// `raw.ownership` must match how the context should be released: a created context is destroyed, while a primary context has one retain released.
677 /// Borrowed contexts retain an external owner instead of acquiring release responsibility.
678 ///
679 /// # Errors
680 ///
681 /// Returns `Error::NullHandle` if `raw.handle` is null.
682 pub unsafe fn from_raw(raw: RawContext) -> Result<Arc<Self>> {
683 if raw.handle.is_null() {
684 return Err(Error::NullHandle);
685 }
686
687 Ok(Arc::new(Self {
688 handle: raw.handle,
689 device: raw.device,
690 ownership: raw.ownership,
691 access_tracker: AccessTracker::for_context(raw.handle.addr())?,
692 pinned: PinnedPool::default(),
693 }))
694 }
695
696 /// Transfers ownership of the raw CUDA context to the caller.
697 ///
698 /// The caller becomes responsible for releasing the returned context according to the returned ownership mode.
699 /// For borrowed contexts, keep the returned external token live while using the raw handle.
700 ///
701 /// # Errors
702 ///
703 /// Returns the context unchanged as `Err` if another clone still retains it.
704 pub fn into_raw(this: Arc<Self>) -> StdResult<RawContext, Arc<Self>> {
705 let mut context = Arc::try_unwrap(this)?;
706 context.release_pinned();
707 let handle = mem::replace(&mut context.handle, ptr::null_mut());
708 Ok(RawContext {
709 handle,
710 device: context.device,
711 ownership: context.ownership.clone(),
712 })
713 }
714}
715
716// SAFETY: a CUDA context is a process-wide driver object that any thread may make current, use, and destroy; the other fields are `Send`.
717unsafe impl Send for Context {}
718
719// SAFETY: `&self` methods only bind the immutable handle on the calling thread, which the driver keeps as thread-local state, and the mutable state sits behind mutexes.
720unsafe impl Sync for Context {}
721
722impl Context {
723 fn release_pinned(&self) {
724 if let Err(error) = self.pinned.release_all(self) {
725 report_cleanup_failure("free", "cuda pinned host memory", &error);
726 }
727 }
728}
729
730impl Drop for Context {
731 fn drop(&mut self) {
732 if self.handle.is_null() {
733 return;
734 }
735
736 // Fields drop after this body, and pinned chunks must go before the native context.
737 self.release_pinned();
738 // SAFETY: the last owner releases `self.handle` exactly as `self.ownership` records, after freeing its pinned chunks; a borrowed context is not released.
739 unsafe {
740 let result = match &self.ownership {
741 RawContextOwnership::Created => try_ffi!(driver::cuCtxDestroy_v2(self.handle)),
742 RawContextOwnership::Primary => {
743 try_ffi!(driver::cuDevicePrimaryCtxRelease_v2(self.device.id()))
744 }
745 RawContextOwnership::Borrowed(_) => Ok(()),
746 };
747
748 if let Err(error) = result {
749 report_cleanup_failure("destroy", "cuda context", &error);
750 }
751 }
752 }
753}
754
755impl PartialEq for Context {
756 fn eq(&self, other: &Self) -> bool {
757 self.as_raw() == other.as_raw()
758 }
759}
760
761impl Eq for Context {}
762
763impl Hash for Context {
764 fn hash<H: Hasher>(&self, state: &mut H) {
765 self.as_raw().hash(state);
766 }
767}
768
769// The runtime and driver limit enumerations share their values.
770fn driver_limit(limit: Limit) -> driver::CUlimit {
771 driver::CUlimit(runtime::cudaLimit::from(limit).0)
772}