Skip to main content

singe_cuda/
library.rs

1//! CUDA libraries, kernel lookup, and library-owned globals.
2
3use std::{ffi::CString, ptr, result::Result as StdResult, sync::Arc};
4
5use singe_core::report_cleanup_failure;
6use singe_cuda_sys::driver;
7
8use crate::{
9    context::Context,
10    error::{Error, Result},
11    graph::{ExecutableGraph, Graph, GraphNode},
12    kernel::{self, LibraryKernelHandle},
13    module::{KernelFunction, KernelLaunchArgs, LaunchConfig, LaunchGeometry, Module},
14    try_ffi,
15    types::{DeviceFunction, FunctionAttribute, FunctionCache, SharedMemoryMode},
16    utility::{to_i32, to_usize},
17};
18
19/// Raw ownership of a CUDA library and its lookup context.
20///
21/// Unload `handle` while `context` is alive, or re-adopt the value with [`Library::from_raw`].
22#[derive(Debug)]
23pub struct RawLibrary {
24    /// Native library handle.
25    pub handle: driver::CUlibrary,
26    /// Context used for lookups in the library.
27    pub context: Arc<Context>,
28}
29
30/// A shared CUDA library and its retained lookup context.
31///
32/// Clones, kernels, and modules share ownership.
33/// The native library is unloaded when its last owner is dropped, unless ownership has been transferred with [`Self::into_raw`].
34#[derive(Debug, Clone)]
35pub struct Library {
36    inner: Arc<LibraryInner>,
37}
38
39#[derive(Debug)]
40struct LibraryInner {
41    handle: driver::CUlibrary,
42    context: Arc<Context>,
43    owns_handle: bool,
44}
45
46/// The address and byte size of a global or managed variable in a CUDA library.
47///
48/// This view borrows the library to keep its code and variable storage loaded.
49/// It does not establish host accessibility, initialization, or exclusive access to the variable.
50#[derive(Debug, Clone, Copy)]
51pub struct LibraryGlobal<'a> {
52    ptr: *mut (),
53    size: usize,
54    _library: &'a Library,
55}
56
57/// A CUDA library kernel handle that keeps its library and lookup context alive.
58#[derive(Debug, Clone)]
59pub struct LibraryKernel {
60    handle: driver::CUkernel,
61    library: Library,
62}
63
64/// Byte layout of one kernel argument in the device-side parameter buffer.
65#[derive(Debug, Clone, Copy, PartialEq, Eq)]
66pub struct KernelParamInfo {
67    /// Byte offset of this argument in the parameter buffer.
68    pub offset: usize,
69    /// Size of this argument in bytes.
70    pub size: usize,
71}
72
73impl Library {
74    /// Takes ownership of a CUDA library, retaining its lookup context.
75    ///
76    /// # Safety
77    ///
78    /// `raw.handle` must be live and must not be unloaded elsewhere.
79    /// `raw.context` must support the library's device code.
80    ///
81    /// # Errors
82    ///
83    /// Returns `Error::NullHandle` if the handle is null.
84    pub unsafe fn from_raw(raw: RawLibrary) -> Result<Self> {
85        if raw.handle.is_null() {
86            return Err(Error::NullHandle);
87        }
88
89        Ok(Self {
90            inner: Arc::new(LibraryInner {
91                handle: raw.handle,
92                context: raw.context,
93                owns_handle: true,
94            }),
95        })
96    }
97
98    /// Returns the handle of the kernel with the given name located in this library.
99    /// If kernel handle is not found, the call returns [`crate::error::Status::NotFound`].
100    ///
101    /// # Errors
102    ///
103    /// Returns an error if `name` contains an interior NUL byte, if the CUDA context cannot be bound, if CUDA Driver cannot find the kernel, or if it returns a null handle.
104    pub fn kernel(&self, name: &str) -> Result<LibraryKernel> {
105        let c_name = CString::new(name)?;
106        let mut handle = ptr::null_mut();
107        self.inner.context.bind()?;
108        // SAFETY: `handle` is a writable local, `self.inner.handle` is the live library this owner retains, and `c_name` is NUL-terminated for the call.
109        unsafe {
110            try_ffi!(driver::cuLibraryGetKernel(
111                &raw mut handle,
112                self.inner.handle,
113                c_name.as_ptr(),
114            ))?;
115        }
116
117        if handle.is_null() {
118            return Err(Error::NullHandle);
119        }
120        Ok(LibraryKernel {
121            handle,
122            library: self.clone(),
123        })
124    }
125
126    /// Returns the number of kernels in this library.
127    ///
128    /// # Errors
129    ///
130    /// Returns an error if the CUDA context cannot be bound or if CUDA Driver cannot report the kernel count.
131    pub fn kernel_count(&self) -> Result<usize> {
132        let mut count = 0;
133        self.inner.context.bind()?;
134        // SAFETY: `count` is a writable local, and `self.inner.handle` is the live library this owner retains.
135        unsafe {
136            try_ffi!(driver::cuLibraryGetKernelCount(
137                &raw mut count,
138                self.inner.handle
139            ))?;
140        }
141        to_usize(count, "library kernel count")
142    }
143
144    /// Returns the module handle associated with the current context located in this library.
145    /// If module handle is not found, the call returns [`crate::error::Status::NotFound`].
146    ///
147    /// # Errors
148    ///
149    /// Returns an error if the CUDA context cannot be bound, if CUDA Driver cannot find the module, or if it returns a null handle.
150    pub fn module(&self) -> Result<Module> {
151        let mut handle = ptr::null_mut();
152        self.inner.context.bind()?;
153        // SAFETY: `handle` is a writable local, and `self.inner.handle` is the live library this owner retains.
154        unsafe {
155            try_ffi!(driver::cuLibraryGetModule(
156                &raw mut handle,
157                self.inner.handle
158            ))?;
159        }
160
161        if handle.is_null() {
162            return Err(Error::NullHandle);
163        }
164        Ok(Module::from_library(
165            handle,
166            Arc::clone(&self.inner.context),
167            self.clone(),
168        ))
169    }
170
171    /// Returns the base pointer and size of the global with the given name for the requested library and the current context.
172    /// If no global for the requested name exists, the call returns [`crate::error::Status::NotFound`].
173    ///
174    /// # Errors
175    ///
176    /// Returns an error if `name` contains an interior NUL byte, if the CUDA context cannot be bound, or if CUDA Driver cannot find the global.
177    pub fn global(&self, name: &str) -> Result<LibraryGlobal<'_>> {
178        let c_name = CString::new(name)?;
179        let mut ptr = 0;
180        let mut size = 0;
181        self.inner.context.bind()?;
182        // SAFETY: `ptr` and `size` are writable locals, `self.inner.handle` is the live library this owner retains, and `c_name` is NUL-terminated for the call.
183        unsafe {
184            try_ffi!(driver::cuLibraryGetGlobal(
185                &raw mut ptr,
186                &raw mut size,
187                self.inner.handle,
188                c_name.as_ptr(),
189            ))?;
190        }
191        Ok(LibraryGlobal {
192            ptr: ptr as *mut (),
193            size: to_usize(size, "library byte count")?,
194            _library: self,
195        })
196    }
197
198    /// Returns the base pointer and size of the managed memory with the given name for the requested library.
199    /// If no managed memory with the requested name exists, the call returns [`crate::error::Status::NotFound`].
200    /// Managed memory for the library is shared across devices and is registered when the library is loaded into at least one context.
201    ///
202    /// # Errors
203    ///
204    /// Returns an error if `name` contains an interior NUL byte, if the CUDA context cannot be bound, or if CUDA Driver cannot find the managed allocation.
205    pub fn managed(&self, name: &str) -> Result<LibraryGlobal<'_>> {
206        let c_name = CString::new(name)?;
207        let mut ptr = 0;
208        let mut size = 0;
209        self.inner.context.bind()?;
210        // SAFETY: `ptr` and `size` are writable locals, `self.inner.handle` is the live library this owner retains, and `c_name` is NUL-terminated for the call.
211        unsafe {
212            try_ffi!(driver::cuLibraryGetManaged(
213                &raw mut ptr,
214                &raw mut size,
215                self.inner.handle,
216                c_name.as_ptr(),
217            ))?;
218        }
219        Ok(LibraryGlobal {
220            ptr: ptr as *mut (),
221            size: to_usize(size, "library byte count")?,
222            _library: self,
223        })
224    }
225
226    /// Returns the borrowed native library handle without transferring ownership.
227    #[must_use]
228    pub fn as_raw(&self) -> driver::CUlibrary {
229        self.inner.handle
230    }
231
232    /// Consumes the library and returns the raw CUDA library handle without unloading it.
233    ///
234    /// The caller becomes responsible for eventually unloading the returned handle with CUDA while retaining the returned context.
235    /// Returns the unchanged wrapper while kernels, modules, graphs or other clones retain this library.
236    ///
237    /// # Errors
238    ///
239    /// Returns `Err(self)` if another library clone, kernel, module, or retained graph owner still shares the library.
240    /// The returned wrapper remains usable and retains ownership.
241    pub fn into_raw(self) -> StdResult<RawLibrary, Self> {
242        match Arc::try_unwrap(self.inner) {
243            Ok(mut inner) => {
244                inner.owns_handle = false;
245                Ok(RawLibrary {
246                    handle: inner.handle,
247                    context: Arc::clone(&inner.context),
248                })
249            }
250            Err(inner) => Err(Self { inner }),
251        }
252    }
253
254    pub(crate) fn code_owner_id(&self) -> usize {
255        Arc::as_ptr(&self.inner).addr()
256    }
257
258    /// Returns the context used for library lookups and device attributes.
259    #[must_use]
260    pub fn context(&self) -> &Arc<Context> {
261        &self.inner.context
262    }
263}
264
265impl Drop for LibraryInner {
266    fn drop(&mut self) {
267        if !self.owns_handle {
268            return;
269        }
270
271        if let Err(error) = self.context.bind() {
272            report_cleanup_failure("bind the cuda context to unload", "cuda library", &error);
273            return;
274        }
275
276        // SAFETY: the last owner of `self.handle` unloads it once, with its lookup context bound, and no kernel or module that uses it remains.
277        if let Err(error) = unsafe { try_ffi!(driver::cuLibraryUnload(self.handle)) } {
278            report_cleanup_failure("unload", "cuda library", &error);
279        }
280    }
281}
282
283// SAFETY: a CUDA library handle may be used and unloaded from any thread once its context is bound, and the retained context is `Send`.
284unsafe impl Send for LibraryInner {}
285
286// SAFETY: shared access only passes the immutable handle to thread-safe driver lookups; `owns_handle` changes only on an owned value.
287unsafe impl Sync for LibraryInner {}
288
289impl LibraryGlobal<'_> {
290    /// Returns the variable's raw address without changing its access permissions.
291    ///
292    /// The address may refer to device-only memory; obtaining it does not make it safe to dereference on the host.
293    #[must_use]
294    pub const fn as_ptr(&self) -> *mut () {
295        self.ptr
296    }
297
298    /// Returns the size of the variable in bytes.
299    #[must_use]
300    pub const fn byte_len(&self) -> usize {
301        self.size
302    }
303}
304
305// SAFETY: a CUDA kernel handle is usable from any thread while its library is loaded, which the retained `library` guarantees.
306unsafe impl Send for LibraryKernel {}
307
308// SAFETY: `&self` methods only pass the immutable kernel handle to thread-safe driver calls; attribute setters race only as CUDA documents for concurrent configuration.
309unsafe impl Sync for LibraryKernel {}
310
311impl LibraryKernel {
312    /// Returns the native kernel name, replacing invalid UTF-8 sequences.
313    ///
314    /// # Errors
315    ///
316    /// Returns an error if the lookup context cannot be bound, CUDA cannot query the name, or CUDA returns a null name pointer.
317    pub fn name(&self) -> Result<String> {
318        // SAFETY: the kernel handle belongs to the module or library retained by `self`.
319        unsafe {
320            kernel::name::<LibraryKernelHandle>(self.library.inner.context.as_ref(), self.handle)
321        }
322    }
323
324    /// Returns the device function handle for this kernel and the current context.
325    /// If the handle is not found, the call returns [`crate::error::Status::NotFound`].
326    ///
327    /// # Errors
328    ///
329    /// Returns an error if the CUDA context cannot be bound, if CUDA Driver cannot find the function, or if it returns a null handle.
330    pub fn function(&self) -> Result<KernelFunction> {
331        self.library.inner.context.bind()?;
332        let mut handle = ptr::null_mut();
333        // SAFETY: `handle` is a writable local, and `self.handle` is a live kernel of the library `self` retains, with its context bound above.
334        unsafe {
335            try_ffi!(driver::cuKernelGetFunction(&raw mut handle, self.handle))?;
336        }
337
338        if handle.is_null() {
339            return Err(Error::NullHandle);
340        }
341
342        let module = self.library.module()?;
343        // SAFETY: CUDA returned this function handle for the module retained by the kernel.
344        Ok(unsafe { KernelFunction::from_raw(DeviceFunction::from_raw(handle), &module) })
345    }
346
347    /// Adds this kernel to `graph` as a kernel node.
348    ///
349    /// # Safety
350    ///
351    /// The caller must ensure every pointer value passed through `params` remains valid for every graph instantiation, update, and launch that can execute the created node.
352    /// Mutable pointer arguments must remain exclusive for the work ordered by those launches.
353    /// Arguments must match the function ABI and satisfy its value and access requirements.
354    /// Keep the graph, executable or another code owner alive until queued executions complete.
355    ///
356    /// # Errors
357    ///
358    /// Propagates errors from resolving this kernel's function and module.
359    /// Also returns an error if the graph belongs to another context, a dependency belongs to another graph, the context cannot be bound, CUDA rejects the node or its launch attributes.
360    pub unsafe fn add_to_graph<'a, P>(
361        &self,
362        graph: &mut Graph,
363        dependencies: &[GraphNode],
364        config: &LaunchConfig,
365        params: P,
366    ) -> Result<GraphNode>
367    where
368        P: KernelLaunchArgs<'a>,
369    {
370        let function = self.function()?;
371        // SAFETY: `function` is this kernel's function, and the caller guarantees the argument validity, exclusivity, and code-owner lifetime that `KernelFunction::add_to_graph` requires.
372        unsafe { function.add_to_graph(graph, dependencies, config, params) }
373    }
374
375    /// Updates this kernel's parameters in an executable graph node.
376    ///
377    /// # Safety
378    ///
379    /// The caller must ensure every pointer value passed through `params` remains valid for every future launch that can execute `node`.
380    /// Mutable pointer arguments must remain exclusive for the work ordered by those launches.
381    /// Arguments must match the function ABI and satisfy its value and access requirements.
382    /// Keep the graph, executable or another code owner alive until queued executions complete.
383    /// Launch attributes are preserved; they must remain compatible with this kernel and geometry.
384    ///
385    /// # Errors
386    ///
387    /// Propagates errors from resolving this kernel's function and module.
388    /// Also returns an error if the executable belongs to another context, the node does not belong to its source graph, the context cannot be bound, CUDA rejects the parameter update.
389    pub unsafe fn set_graph_node_params<'a, P>(
390        &self,
391        executable: &mut ExecutableGraph,
392        node: &GraphNode,
393        geometry: &LaunchGeometry,
394        params: P,
395    ) -> Result<()>
396    where
397        P: KernelLaunchArgs<'a>,
398    {
399        let function = self.function()?;
400        // SAFETY: `function` is this kernel's function, and the caller guarantees the argument validity, exclusivity, code-owner lifetime, and attribute compatibility that `KernelFunction::set_graph_node_params` requires.
401        unsafe { function.set_graph_node_params(executable, node, geometry, params) }
402    }
403
404    /// Returns `attribute` for this kernel on the library's lookup device.
405    ///
406    /// # Errors
407    ///
408    /// Returns an error if the lookup context cannot be bound or CUDA rejects the attribute query for this kernel and device.
409    pub fn attribute(&self, attribute: FunctionAttribute) -> Result<i32> {
410        // SAFETY: the kernel handle belongs to the module or library retained by `self`.
411        unsafe {
412            kernel::attribute::<LibraryKernelHandle>(
413                self.library.inner.context.as_ref(),
414                self.handle,
415                attribute,
416            )
417        }
418    }
419
420    /// Specifies whether the kernel may use oversized shared memory configurations.
421    ///
422    /// # Errors
423    ///
424    /// Propagates errors from setting [`FunctionAttribute::SharedMemoryMode`], including a context binding failure or a mode unsupported by the kernel or device.
425    pub fn set_shared_memory_mode(&self, mode: SharedMemoryMode) -> Result<()> {
426        self.set_attribute(
427            FunctionAttribute::SharedMemoryMode,
428            to_i32(u32::from(mode), "shared memory mode")?,
429        )
430    }
431
432    /// Returns the shared memory mode configured for this kernel.
433    ///
434    /// # Errors
435    ///
436    /// Propagates errors from querying [`FunctionAttribute::SharedMemoryMode`].
437    /// Returns `Error::UnknownEnumValue` if the returned native value is not a recognized [`SharedMemoryMode`].
438    pub fn shared_memory_mode(&self) -> Result<SharedMemoryMode> {
439        let value = self.attribute(FunctionAttribute::SharedMemoryMode)?;
440        u32::try_from(value)
441            .ok()
442            .and_then(|raw| SharedMemoryMode::try_from(raw).ok())
443            .ok_or_else(|| Error::UnknownEnumValue {
444                name: "shared memory mode".into(),
445                value: i64::from(value),
446            })
447    }
448
449    /// Sets `attribute` to `value` for this kernel on the library's lookup device.
450    ///
451    /// Only attributes supported for mutation by CUDA can be set; see [`FunctionAttribute`] for attribute-specific constraints.
452    ///
453    /// # Errors
454    ///
455    /// Returns an error if the lookup context cannot be bound or CUDA rejects the selected attribute or value for this kernel and device.
456    pub fn set_attribute(&self, attribute: FunctionAttribute, value: i32) -> Result<()> {
457        // SAFETY: the kernel handle belongs to the module or library retained by `self`.
458        unsafe {
459            kernel::set_attribute::<LibraryKernelHandle>(
460                self.library.inner.context.as_ref(),
461                self.handle,
462                attribute,
463                value,
464            )
465        }
466    }
467
468    /// Sets the preferred cache configuration for this kernel on devices where L1 cache and shared memory use the same hardware resources.
469    /// This setting is only a preference.
470    /// The driver uses the requested configuration if possible, but it may choose a different configuration if required to execute the kernel.
471    /// This per-kernel setting overrides any context-wide preference set via [`sys::cuCtxSetCacheConfig`](singe_cuda_sys::driver::cuCtxSetCacheConfig).
472    ///
473    /// Attributes set using [`sys::cuFuncSetCacheConfig`](singe_cuda_sys::driver::cuFuncSetCacheConfig) override this preference regardless of call order.
474    ///
475    /// This setting does nothing on devices where the size of the L1 cache and shared memory are fixed.
476    ///
477    /// Launching a kernel with a different preference than the most recent preference setting may insert a device-side synchronization point.
478    ///
479    /// The supported cache configurations are:
480    ///
481    /// * [`FunctionCache::PreferNone`]: no preference for shared memory or L1 (default)
482    /// * [`FunctionCache::PreferShared`]: prefer larger shared memory and smaller L1 cache
483    /// * [`FunctionCache::PreferL1`]: prefer larger L1 cache and smaller shared memory
484    /// * [`FunctionCache::PreferEqual`]: prefer equal sized L1 cache and shared memory
485    ///
486    /// This has stricter locking requirements than its legacy counterpart [`sys::cuFuncSetCacheConfig`](singe_cuda_sys::driver::cuFuncSetCacheConfig) because the setting has device-wide semantics.
487    /// If multiple threads try to set a configuration on the same device simultaneously, the final cache configuration depends on OS scheduler interleaving and memory consistency.
488    ///
489    /// # Errors
490    ///
491    /// Returns an error if the CUDA context cannot be bound or if CUDA Driver rejects the cache configuration.
492    pub fn set_cache_config(&self, config: FunctionCache) -> Result<()> {
493        self.library.inner.context.bind()?;
494        // SAFETY: `self.handle` is a live kernel of the library `self` retains, with its context bound above.
495        unsafe {
496            try_ffi!(driver::cuKernelSetCacheConfig(
497                self.handle,
498                config.into(),
499                self.library.inner.context.device().id(),
500            ))?;
501        }
502        Ok(())
503    }
504
505    /// Queries the kernel parameter at the given index, returning the offset and size where the parameter resides in the device-side parameter layout.
506    /// Use this information to update kernel node parameters from the device.
507    /// The index must be less than the number of parameters that the kernel takes.
508    ///
509    /// # Errors
510    ///
511    /// Returns an error if the library context cannot be bound, `index` is not a valid kernel parameter index, CUDA cannot query the parameter layout, or a previous asynchronous launch reported an error.
512    pub fn param_info(&self, index: usize) -> Result<KernelParamInfo> {
513        self.library.inner.context.bind()?;
514        let mut offset = 0;
515        let mut size = 0;
516        let index = index
517            .try_into()
518            .map_err(|_| Error::out_of_range("kernel parameter index"))?;
519        // SAFETY: `offset` and `size` are writable locals, and `self.handle` is a live kernel of the library `self` retains.
520        unsafe {
521            try_ffi!(driver::cuKernelGetParamInfo(
522                self.handle,
523                index,
524                &raw mut offset,
525                &raw mut size,
526            ))?;
527        }
528        Ok(KernelParamInfo {
529            offset: to_usize(offset, "kernel parameter offset")?,
530            size: to_usize(size, "library byte count")?,
531        })
532    }
533
534    /// Returns the borrowed native kernel handle.
535    ///
536    /// The handle is kept live by this kernel's library owner; the returned pointer does not retain that owner.
537    #[must_use]
538    pub const fn as_raw(&self) -> driver::CUkernel {
539        self.handle
540    }
541}