singe-cuda 0.1.0

Safe Rust wrappers for the CUDA driver and runtime APIs, including runtime compilation of CUDA C++ and NVTX annotations.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
//! Shared CUDA contexts, primary-context retention, and code loading.

use std::{
    any::Any,
    ffi::CString,
    fmt::{self, Display, Formatter},
    hash::{Hash, Hasher},
    mem, ptr,
    result::Result as StdResult,
    sync::{Arc, Mutex},
};

use bitflags::parser;
use singe_core::report_cleanup_failure;
use singe_cuda_sys::{driver, runtime};

use crate::{
    device::{Device, Limit},
    error::{Error, Result},
    graph::Graph,
    jit::JitOptions,
    library::{Library, RawLibrary},
    memory::PinnedPool,
    module::{Module, ModuleImage, artifact::ArtifactMetadata},
    submission::{Access, AccessGuard, AccessMode, AccessTracker, lock_access},
    try_ffi,
    utility::{to_u32, to_usize},
    view::DeviceRegion,
};

bitflags::bitflags! {
    /// Context creation flags.
    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
    pub struct ContextFlags: u32 {
        /// Automatic scheduling.
        const SCHEDULE_AUTO = driver::CUctx_flags::CU_CTX_SCHED_AUTO.0;
        /// Set spin as default scheduling.
        const SCHEDULE_SPIN = driver::CUctx_flags::CU_CTX_SCHED_SPIN.0;
        /// Set yield as default scheduling.
        const SCHEDULE_YIELD = driver::CUctx_flags::CU_CTX_SCHED_YIELD.0;
        /// Set blocking synchronization as default scheduling.
        const SCHEDULE_BLOCKING_SYNC = driver::CUctx_flags::CU_CTX_SCHED_BLOCKING_SYNC.0;
        /// Deprecated: This flag was deprecated as of CUDA 11.0 and it no longer has any effect.
        /// All contexts as of CUDA 3.2 behave as though the flag is enabled.
        const MAP_HOST = driver::CUctx_flags::CU_CTX_MAP_HOST.0;
        /// Keep local memory allocation after launch.
        const LOCAL_MEMORY_RESIZE_TO_MAX = driver::CUctx_flags::CU_CTX_LMEM_RESIZE_TO_MAX.0;
        /// Trigger coredumps from exceptions in this context.
        const COREDUMP_ENABLE = driver::CUctx_flags::CU_CTX_COREDUMP_ENABLE.0;
        /// Enable user pipe to trigger coredumps in this context.
        const USER_COREDUMP_ENABLE = driver::CUctx_flags::CU_CTX_USER_COREDUMP_ENABLE.0;
        /// Ensure synchronous memory operations on this context will synchronize.
        const SYNC_MEMORY_OPERATIONS = driver::CUctx_flags::CU_CTX_SYNC_MEMOPS.0;
    }
}

impl Display for ContextFlags {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        parser::to_writer(self, f)
    }
}

bitflags::bitflags! {
    /// Flags for [`Context::enable_peer_access`].
    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
    pub struct PeerAccessFlags: u32 {
        /// Default peer-access behavior.
        const DEFAULT = 0;
    }
}

impl Display for PeerAccessFlags {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        parser::to_writer(self, f)
    }
}

/// A shared CUDA driver context.
///
/// Unlike cuBLAS, cuDNN, cuFFT, and similar library handles, a CUDA context is the underlying execution environment for a device.
/// It is intended to be shared by streams, modules, libraries, events, allocations, and higher-level library wrappers.
///
/// This type is therefore reference-counted by returning [`Arc<Self>`] from the constructors, and it remains `Send + Sync`.
/// 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.
///
/// Prefer one long-lived context per device and share it across dependent CUDA objects instead of creating many short-lived contexts.
#[derive(Debug)]
pub struct Context {
    handle: driver::CUcontext,
    device: Device,
    ownership: RawContextOwnership,
    pub(crate) access_tracker: Arc<Mutex<AccessTracker>>,
    pub(crate) pinned: PinnedPool,
}

/// Raw ownership of a CUDA context.
///
/// Release `handle` according to `ownership`, or re-adopt the value with [`Context::from_raw`].
#[derive(Debug)]
pub struct RawContext {
    /// Native context handle.
    pub handle: driver::CUcontext,
    /// Device the context belongs to.
    pub device: Device,
    /// Release responsibility for `handle`.
    pub ownership: RawContextOwnership,
}

/// Native release responsibility, including a retained external ownership token.
#[derive(Clone)]
#[non_exhaustive]
pub enum RawContextOwnership {
    /// Destroys the context when the last wrapper is dropped.
    Created,
    /// Releases one retained primary-context reference when the last wrapper is dropped.
    Primary,
    /// Keeps an external owner alive without destroying or releasing the native context.
    Borrowed(
        /// External ownership token retained for the lifetime of this wrapper.
        Arc<dyn Any + Send + Sync>,
    ),
}

impl fmt::Debug for RawContextOwnership {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            Self::Created => "Created",
            Self::Primary => "Primary",
            Self::Borrowed(_) => "Borrowed",
        })
    }
}

impl Context {
    /// Holds submitted accesses out of the supplied ranges while host code runs.
    /// Nested tracked access returns an error instead of waiting on its own host access guard.
    ///
    /// # Errors
    ///
    /// 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.
    /// Also propagates CUDA synchronization or event-query errors and errors returned by `access`.
    /// The callback runs only after all required waits succeed.
    pub fn with_host_access<T>(
        &self,
        regions: &[DeviceRegion<'_>],
        access: impl FnOnce() -> Result<T>,
    ) -> Result<T> {
        let _guard = self.acquire_host_access(regions)?;
        access()
    }

    /// Waits for conflicting submitted uses and declared readiness streams, then holds these access declarations against concurrent tracked submissions while `access` runs.
    /// The declarations retain context and ordering metadata, not allocation owners.
    ///
    /// # Safety
    ///
    /// Keep the declared storage live and obey each declaration's access mode.
    /// Any asynchronous work using these ranges must complete before the callback returns or unwinds.
    /// Nested tracked access is rejected rather than waiting on its own guard.
    ///
    /// # Errors
    ///
    /// 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.
    /// Also converts errors from synchronizing conflicting uses or readiness streams and querying completion events.
    /// Errors returned by `access` pass through unchanged; the callback runs only after all required waits succeed.
    pub unsafe fn with_synchronized_accesses<T, E>(
        &self,
        accesses: &[Access],
        access: impl FnOnce() -> StdResult<T, E>,
    ) -> StdResult<T, E>
    where
        E: From<Error>,
    {
        let _guard = self.acquire_accesses(accesses)?;
        access()
    }

    pub(crate) fn acquire_host_access(
        &self,
        regions: &[DeviceRegion<'_>],
    ) -> Result<AccessGuard<'_>> {
        let accesses: Vec<_> = regions
            .iter()
            .map(|&region| Access::new(region, AccessMode::ReadWrite))
            .collect();
        self.acquire_accesses(&accesses)
    }

    pub(crate) fn acquire_accesses(&self, accesses: &[Access]) -> Result<AccessGuard<'_>> {
        for access in accesses {
            access.validate_context(self)?;
        }

        let mut tracker = lock_access(&self.access_tracker, accesses)?;
        for access in accesses {
            tracker.synchronize_access(access)?;
            if let Some(stream) = &access.readiness {
                stream.synchronize()?;
            }
        }
        Ok(tracker)
    }

    /// Enables this actual context to directly access `peer` allocations.
    /// Already-enabled access succeeds.
    /// The permission is unidirectional and persists until explicitly disabled or either context is destroyed.
    /// Pool allocations additionally follow their pool's access descriptors.
    ///
    /// # Errors
    ///
    /// Returns `Error::OutOfRange` for nondefault flags.
    /// 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.
    /// Already-enabled access succeeds.
    pub fn enable_peer_access(&self, peer: &Self, flags: PeerAccessFlags) -> Result<()> {
        if flags != PeerAccessFlags::DEFAULT {
            return Err(Error::out_of_range("peer access flags"));
        }

        self.bind()?;
        // SAFETY: `self` is bound above, and `peer` keeps its context handle live for the call.
        let status = unsafe { driver::cuCtxEnablePeerAccess(peer.as_raw(), flags.bits()) };
        if status == driver::CUresult::CUDA_ERROR_PEER_ACCESS_ALREADY_ENABLED {
            return Ok(());
        }
        try_ffi!(status)
    }

    /// Disables this actual context's direct access to `peer` allocations.
    ///
    /// # Safety
    ///
    /// Complete every access that relies on this permission, including graph replays, before disabling it.
    /// Do not use retained peer-copy objects or peer pointers again until access is re-enabled.
    /// Exclude concurrent uses.
    ///
    /// # Errors
    ///
    /// Returns an error if this context cannot be bound or CUDA cannot disable the permission, including when peer access is not enabled.
    pub unsafe fn disable_peer_access(&self, peer: &Self) -> Result<()> {
        self.bind()?;
        // SAFETY: `self` is bound above and `peer` keeps its context live; the caller guarantees no access still relies on the permission.
        unsafe { try_ffi!(driver::cuCtxDisablePeerAccess(peer.as_raw())) }
    }

    /// Retains the primary context of the calling thread's current runtime device and makes it current.
    ///
    /// The primary context is shared with the CUDA runtime and other libraries on the same device.
    /// Use [`Self::create_dedicated`] for a separate execution environment.
    ///
    /// # Errors
    ///
    /// Propagates errors from querying the current runtime device or from [`Self::create_for_device`].
    pub fn create() -> Result<Arc<Self>> {
        Self::create_for_device(Device::current()?)
    }

    /// Creates a new context for `device` with `flags` and makes it current on the calling thread.
    ///
    /// The last owning wrapper destroys this context.
    /// It is a separate execution environment from the device's primary context and from other created contexts.
    ///
    /// # Errors
    ///
    /// Returns an error if CUDA initialization or context creation fails, including invalid creation flags, an unavailable device, or insufficient resources.
    /// Returns `Error::NullHandle` if CUDA reports success with a null context handle.
    pub fn create_dedicated(device: Device, flags: ContextFlags) -> Result<Arc<Self>> {
        // SAFETY: `handle` is a writable local, the null creation parameters select the defaults, and `cuInit` runs first.
        unsafe {
            try_ffi!(driver::cuInit(0))?;

            let mut handle = ptr::null_mut();
            try_ffi!(driver::cuCtxCreate_v4(
                &raw mut handle,
                ptr::null_mut(),
                flags.bits(),
                device.id(),
            ))?;

            if handle.is_null() {
                return Err(Error::NullHandle);
            }

            // The context was just created and nothing else refers to it, so a failed lookup destroys it.
            let access_tracker = AccessTracker::for_context(handle.addr()).inspect_err(|_| {
                if let Err(error) = try_ffi!(driver::cuCtxDestroy_v2(handle)) {
                    report_cleanup_failure("destroy", "cuda context", &error);
                }
            })?;
            Ok(Arc::new(Self {
                handle,
                device,
                ownership: RawContextOwnership::Created,
                access_tracker,
                pinned: PinnedPool::default(),
            }))
        }
    }

    /// Retains the primary context for `device` and makes it current on the calling thread.
    ///
    /// The device's primary context is shared with the CUDA runtime.
    /// Dropping the last owning wrapper releases this retain; other native retainers may keep the context alive.
    ///
    /// # Errors
    ///
    /// Returns an error if CUDA initialization, retaining the primary context, or setting it current fails.
    /// Returns `Error::NullHandle` if CUDA reports success with a null context handle.
    pub fn create_for_device(device: Device) -> Result<Arc<Self>> {
        let mut handle = ptr::null_mut();
        // SAFETY: `handle` is a writable local, and `cuInit` runs first.
        unsafe {
            try_ffi!(driver::cuInit(0))?;
            try_ffi!(driver::cuDevicePrimaryCtxRetain(
                &raw mut handle,
                device.id(),
            ))?;
        }

        let access_tracker = if handle.is_null() {
            Err(Error::NullHandle)
        } else {
            AccessTracker::for_context(handle.addr())
        }
        .inspect_err(|_| {
            // SAFETY: releases only the primary-context retain taken above.
            let result = unsafe { try_ffi!(driver::cuDevicePrimaryCtxRelease_v2(device.id())) };
            if let Err(error) = result {
                report_cleanup_failure("release", "cuda primary context", &error);
            }
        })?;

        // From here on, dropping the wrapper releases the retain.
        let context = Arc::new(Self {
            handle,
            device,
            ownership: RawContextOwnership::Primary,
            access_tracker,
            pinned: PinnedPool::default(),
        });

        context.bind()?;
        Ok(context)
    }

    // Green contexts belong to their device's primary context, so code loaded there is the only code they may launch.
    pub(crate) fn is_primary_for(&self, device: Device) -> Result<bool> {
        if self.device != device {
            return Ok(false);
        }

        match self.ownership {
            RawContextOwnership::Primary => Ok(true),
            RawContextOwnership::Created => Ok(false),
            RawContextOwnership::Borrowed(_) => {
                let mut primary = ptr::null_mut();
                // SAFETY: `primary` is a writable local, and the retain taken here is released right below.
                unsafe {
                    try_ffi!(driver::cuDevicePrimaryCtxRetain(
                        &raw mut primary,
                        device.id(),
                    ))?;
                }

                // SAFETY: releases only the primary-context retain taken above.
                unsafe {
                    try_ffi!(driver::cuDevicePrimaryCtxRelease_v2(device.id()))?;
                }

                Ok(primary == self.handle)
            }
        }
    }

    /// Binds this CUDA context to the calling CPU thread.
    ///
    /// The "current context" is thread-local driver state.
    /// 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.
    ///
    /// # Errors
    ///
    /// Returns an error if CUDA Driver cannot query or set the current context.
    pub fn bind(&self) -> Result<()> {
        // SAFETY: `current_context` is a writable local, and `self.handle` is the live context this wrapper owns or borrows.
        unsafe {
            let mut current_context = ptr::null_mut();
            try_ffi!(driver::cuCtxGetCurrent(&raw mut current_context))?;
            if current_context == self.as_raw() {
                return Ok(());
            }

            try_ffi!(driver::cuCtxSetCurrent(self.as_raw()))?;
        }
        Ok(())
    }

    /// Loads the corresponding module from the given image into this context with `jit_options`.
    /// 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.
    ///
    /// # Errors
    ///
    /// 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.
    pub fn load_module(
        self: &Arc<Self>,
        image: &ModuleImage<'_>,
        jit_options: JitOptions<'_>,
    ) -> Result<Module> {
        self.load_module_with_metadata(image, jit_options, None)
    }

    pub(crate) fn load_module_with_metadata(
        self: &Arc<Self>,
        image: &ModuleImage<'_>,
        mut jit_options: JitOptions<'_>,
        metadata: Option<Arc<ArtifactMetadata>>,
    ) -> Result<Module> {
        self.bind()?;

        let mut jit_options = jit_options.build();
        // 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.
        unsafe {
            let mut module_handle = ptr::null_mut();
            try_ffi!(driver::cuModuleLoadDataEx(
                &raw mut module_handle,
                image.as_ptr().cast(),
                to_u32(jit_options.names.len(), "JIT option count")?,
                jit_options.names.as_mut_ptr().cast(),
                jit_options.values.as_mut_ptr().cast(),
            ))?;
            Module::from_raw_with_metadata(module_handle, Arc::clone(self), metadata)
        }
    }

    /// Creates an empty CUDA graph associated with this context.
    ///
    /// Prefer this over [`UnboundGraph::create`](crate::graph::UnboundGraph::create) for ordinary Singe code.
    /// The returned graph carries its context association into instantiated executable graphs, allowing launches and uploads to reject streams from another context before calling CUDA.
    ///
    /// # Errors
    ///
    /// Returns an error if the context cannot be bound or CUDA cannot create the graph.
    pub fn create_graph(self: &Arc<Self>) -> Result<Graph> {
        Graph::create_in_context(Arc::clone(self))
    }

    /// Loads the corresponding library from the given image with `jit_options`, based on the application defined library loading mode:
    ///
    /// * 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).
    /// * 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.
    ///
    /// These environment variables are described in the CUDA programming guide under the "CUDA environment variables" section.
    ///
    /// 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.
    /// A fatbin must also contain relocatable code when doing separate compilation.
    ///
    /// If the library contains managed variables and no device in the system supports them, this call returns [`crate::error::Status::NotSupported`].
    ///
    /// # Errors
    ///
    /// 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.
    /// Returns `Error::NullHandle` if CUDA reports success with a null library handle.
    /// CUDA may also report errors from previous asynchronous work.
    pub fn load_library(
        self: &Arc<Self>,
        image: &ModuleImage<'_>,
        mut jit_options: JitOptions<'_>,
    ) -> Result<Library> {
        self.bind()?;

        let mut jit_options = jit_options.build();
        let mut handle = ptr::null_mut();
        // 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.
        unsafe {
            try_ffi!(driver::cuLibraryLoadData(
                &raw mut handle,
                image.as_ptr().cast(),
                jit_options.names.as_mut_ptr().cast(),
                jit_options.values.as_mut_ptr().cast(),
                to_u32(jit_options.names.len(), "JIT option count")?,
                ptr::null_mut(),
                ptr::null_mut(),
                0,
            ))?;
        }

        if handle.is_null() {
            return Err(Error::NullHandle);
        }
        // SAFETY: CUDA just created this handle in this context, and nothing else owns it.
        unsafe {
            Library::from_raw(RawLibrary {
                handle,
                context: Arc::clone(self),
            })
        }
    }

    /// Loads the corresponding library from the given file based on the application defined library loading mode:
    ///
    /// * 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).
    /// * 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.
    ///
    /// These environment variables are described in the CUDA programming guide under the "CUDA environment variables" section.
    ///
    /// 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.
    /// A fatbin must also contain relocatable code when doing separate compilation.
    ///
    /// If the library contains managed variables and no device in the system supports them, this call returns [`crate::error::Status::NotSupported`].
    ///
    /// # Errors
    ///
    /// Returns an error if this context cannot be bound, if `path` contains an interior NUL byte, or if CUDA Driver cannot load the library.
    pub fn load_library_from_file(self: &Arc<Self>, path: &str) -> Result<Library> {
        self.bind()?;
        let path = CString::new(path)?;
        let mut handle = ptr::null_mut();
        // 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.
        unsafe {
            try_ffi!(driver::cuLibraryLoadFromFile(
                &raw mut handle,
                path.as_ptr(),
                ptr::null_mut(),
                ptr::null_mut(),
                0,
                ptr::null_mut(),
                ptr::null_mut(),
                0,
            ))?;
        }

        if handle.is_null() {
            return Err(Error::NullHandle);
        }
        // SAFETY: CUDA just created this handle in this context, and nothing else owns it.
        unsafe {
            Library::from_raw(RawLibrary {
                handle,
                context: Arc::clone(self),
            })
        }
    }

    /// Blocks until the current context has completed all preceding requested tasks.
    /// If the current context is the primary context, child contexts that have been created are also synchronized.
    /// [`Context::synchronize`] returns an error if one of the preceding tasks failed.
    /// If the context was created with [`ContextFlags::SCHEDULE_BLOCKING_SYNC`], the CPU thread blocks until the GPU context has finished its work.
    ///
    /// # Errors
    ///
    /// Returns an error if the context cannot be bound, a preceding task failed, or a previous asynchronous launch reported an error.
    pub fn synchronize(&self) -> Result<()> {
        self.bind()?;
        // SAFETY: `cuCtxSynchronize` takes no arguments and waits on the context bound above.
        unsafe {
            try_ffi!(driver::cuCtxSynchronize())?;
        }
        Ok(())
    }

    /// Returns the flags of the current context.
    /// See [`ContextFlags`] for flag values.
    ///
    /// # Errors
    ///
    /// Returns an error if the context cannot be bound, CUDA cannot query the flags, or a previous asynchronous launch reported an error.
    pub fn flags(&self) -> Result<ContextFlags> {
        self.bind()?;
        // SAFETY: `flags` is a local that `cuCtxGetFlags` writes through an exclusive pointer.
        unsafe {
            let mut flags = 0;
            try_ffi!(driver::cuCtxGetFlags(&raw mut flags))?;
            Ok(ContextFlags::from_bits_truncate(flags))
        }
    }

    /// Returns the current size of limit.
    /// The supported [`Limit`] values are:
    ///
    /// * [`Limit::StackSize`]: stack size in bytes of each GPU thread.
    /// * [`Limit::PrintfFifoSize`]: size in bytes of the FIFO used by the `printf()` device system call.
    /// * [`Limit::MallocHeapSize`]: size in bytes of the heap used by the `malloc()` and `free()` device system calls.
    /// * [`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.
    /// * [`Limit::DevRuntimePendingLaunchCount`]: maximum number of outstanding device runtime launches that can be made from this context.
    /// * [`Limit::MaxL2FetchGranularity`]: L2 cache fetch granularity.
    /// * [`Limit::PersistingL2CacheSize`]: persisting L2 cache size in bytes.
    ///
    /// # Errors
    ///
    /// 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.
    pub fn limit(&self, limit: Limit) -> Result<usize> {
        self.bind()?;
        // SAFETY: `value` is a local that `cuCtxGetLimit` writes through an exclusive pointer.
        unsafe {
            let mut value = 0;
            try_ffi!(driver::cuCtxGetLimit(&raw mut value, driver_limit(limit)))?;
            to_usize(value, "context limit")
        }
    }

    /// Setting limit to value is a request by the application to update the current limit maintained by the context.
    /// 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.
    /// Use [`Context::limit`] to query the effective value.
    ///
    /// Setting each [`Limit`] has its own restrictions.
    ///
    /// * [`Limit::StackSize`] controls the stack size in bytes of each GPU thread.
    ///   The driver automatically increases the per-thread stack size for each kernel launch as needed.
    ///   This size is not reset back to the original value after each launch.
    ///   Setting this value will take effect immediately, and if necessary, the device will block until all preceding requested tasks are complete.
    ///
    /// * [`Limit::PrintfFifoSize`] controls the size in bytes of the FIFO used by the `printf()` device system call.
    ///   Configure [`Limit::PrintfFifoSize`] before launching any kernel that uses the `printf()` device system call; otherwise [`crate::error::Status::InvalidValue`] is returned.
    ///
    /// * [`Limit::MallocHeapSize`] controls the size in bytes of the heap used by the `malloc()` and `free()` device system calls.
    ///   Configure [`Limit::MallocHeapSize`] before launching any kernel that uses the `malloc()` or `free()` device system calls; otherwise [`crate::error::Status::InvalidValue`] is returned.
    ///
    /// * [`Limit::DevRuntimeSyncDepth`] controls the maximum nesting depth of a grid at which a thread can safely call [`Device::synchronize`].
    ///   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.
    ///   Calls to [`Device::synchronize`] fail if this limit is violated.
    ///   This limit can be set smaller than the default or up to the maximum launch depth of 24.
    ///   Additional sync-depth levels require the driver to reserve large amounts of device memory that can no longer be used for application allocations.
    ///   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.
    ///   This limit is only applicable to devices of compute capability &lt; 9.0.
    ///   Setting this limit on devices of other compute capability versions returns [`crate::error::Status::UnsupportedLimit`].
    ///
    /// * [`Limit::DevRuntimePendingLaunchCount`] controls the maximum number of outstanding device runtime launches that can be made from the current context.
    ///   A grid is outstanding from launch until it is known to have completed.
    ///   Device runtime launches that violate this limit fail.
    ///   If a module using the device runtime needs more pending launches than the default 2048 launches, this limit can be increased.
    ///   Sustaining additional pending launches requires the driver to reserve larger amounts of device memory up front, which can no longer be used for allocations.
    ///   If these reservations fail, [`Context::set_limit`] returns [`crate::error::Status::OutOfMemory`], and the limit can be reset to a lower value.
    ///   This limit is only applicable to devices of compute capability 3.5 and higher.
    ///   Attempting to set this limit on devices of compute capability less than 3.5 returns [`crate::error::Status::UnsupportedLimit`].
    ///
    /// * [`Limit::MaxL2FetchGranularity`] controls the L2 cache fetch granularity.
    ///   Values can range from 0B to 128B.
    ///   Performance hint that may be ignored or clamped depending on the platform.
    ///
    /// * [`Limit::PersistingL2CacheSize`] controls size in bytes available for persisting L2 cache.
    ///   Performance hint that may be ignored or clamped depending on the platform.
    ///
    /// # Errors
    ///
    /// 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.
    pub fn set_limit(&self, limit: Limit, value: usize) -> Result<()> {
        self.bind()?;
        let value = value
            .try_into()
            .map_err(|_| Error::out_of_range("context limit value"))?;
        // SAFETY: `cuCtxSetLimit` receives only values, and applies them to the context bound above.
        unsafe {
            try_ffi!(driver::cuCtxSetLimit(driver_limit(limit), value))?;
        }
        Ok(())
    }

    /// Returns the device associated with this context.
    #[must_use]
    pub const fn device(&self) -> Device {
        self.device
    }

    /// Returns the borrowed native context handle.
    ///
    /// The handle remains owned according to this wrapper's [`RawContextOwnership`].
    /// Returning it does not retain the context or transfer release responsibility.
    #[must_use]
    pub const fn as_raw(&self) -> driver::CUcontext {
        self.handle
    }

    /// Takes ownership of a raw CUDA context.
    ///
    /// # Safety
    ///
    /// `raw.handle` must be a valid CUDA context for `raw.device`, and no other Rust wrapper may own the same release responsibility.
    /// `raw.ownership` must match how the context should be released: a created context is destroyed, while a primary context has one retain released.
    /// Borrowed contexts retain an external owner instead of acquiring release responsibility.
    ///
    /// # Errors
    ///
    /// Returns `Error::NullHandle` if `raw.handle` is null.
    pub unsafe fn from_raw(raw: RawContext) -> Result<Arc<Self>> {
        if raw.handle.is_null() {
            return Err(Error::NullHandle);
        }

        Ok(Arc::new(Self {
            handle: raw.handle,
            device: raw.device,
            ownership: raw.ownership,
            access_tracker: AccessTracker::for_context(raw.handle.addr())?,
            pinned: PinnedPool::default(),
        }))
    }

    /// Transfers ownership of the raw CUDA context to the caller.
    ///
    /// The caller becomes responsible for releasing the returned context according to the returned ownership mode.
    /// For borrowed contexts, keep the returned external token live while using the raw handle.
    ///
    /// # Errors
    ///
    /// Returns the context unchanged as `Err` if another clone still retains it.
    pub fn into_raw(this: Arc<Self>) -> StdResult<RawContext, Arc<Self>> {
        let mut context = Arc::try_unwrap(this)?;
        context.release_pinned();
        let handle = mem::replace(&mut context.handle, ptr::null_mut());
        Ok(RawContext {
            handle,
            device: context.device,
            ownership: context.ownership.clone(),
        })
    }
}

// SAFETY: a CUDA context is a process-wide driver object that any thread may make current, use, and destroy; the other fields are `Send`.
unsafe impl Send for Context {}

// 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.
unsafe impl Sync for Context {}

impl Context {
    fn release_pinned(&self) {
        if let Err(error) = self.pinned.release_all(self) {
            report_cleanup_failure("free", "cuda pinned host memory", &error);
        }
    }
}

impl Drop for Context {
    fn drop(&mut self) {
        if self.handle.is_null() {
            return;
        }

        // Fields drop after this body, and pinned chunks must go before the native context.
        self.release_pinned();
        // SAFETY: the last owner releases `self.handle` exactly as `self.ownership` records, after freeing its pinned chunks; a borrowed context is not released.
        unsafe {
            let result = match &self.ownership {
                RawContextOwnership::Created => try_ffi!(driver::cuCtxDestroy_v2(self.handle)),
                RawContextOwnership::Primary => {
                    try_ffi!(driver::cuDevicePrimaryCtxRelease_v2(self.device.id()))
                }
                RawContextOwnership::Borrowed(_) => Ok(()),
            };

            if let Err(error) = result {
                report_cleanup_failure("destroy", "cuda context", &error);
            }
        }
    }
}

impl PartialEq for Context {
    fn eq(&self, other: &Self) -> bool {
        self.as_raw() == other.as_raw()
    }
}

impl Eq for Context {}

impl Hash for Context {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.as_raw().hash(state);
    }
}

// The runtime and driver limit enumerations share their values.
fn driver_limit(limit: Limit) -> driver::CUlimit {
    driver::CUlimit(runtime::cudaLimit::from(limit).0)
}