singe_cuda/module/mod.rs
1//! CUDA modules, device-code images, kernel arguments, and launch configuration.
2
3mod config;
4mod function;
5mod image;
6mod parameters;
7
8pub mod artifact;
9
10use std::{ffi::CString, ptr, result::Result as StdResult, sync::Arc};
11
12use singe_core::report_cleanup_failure;
13use singe_cuda_sys::driver;
14
15use crate::{
16 context::Context,
17 error::{Error, Result},
18 library::Library,
19 module::artifact::ArtifactMetadata,
20 try_ffi,
21 types::DeviceFunction,
22 utility::to_usize,
23};
24
25pub use self::{
26 config::{LaunchAttribute, LaunchConfig, LaunchGeometry},
27 function::{
28 FunctionAttributes, KernelFunction, OccupancyFlags, OccupancyMaxPotentialBlockSize,
29 },
30 image::ModuleImage,
31 parameters::{EncodedKernelArgs, KernelLaunchArgs, KernelParameters, PushKernelArg},
32};
33
34/// Raw ownership of a loaded CUDA module and its context.
35///
36/// Unload `handle` while `context` is alive, or re-adopt the value with [`Module::from_raw`].
37#[derive(Debug)]
38pub struct RawModule {
39 /// Native module handle.
40 pub handle: driver::CUmodule,
41 /// Context the module was loaded in.
42 pub context: Arc<Context>,
43}
44
45/// A shared CUDA module and its retained loading context.
46///
47/// Clones, functions, and retained graph owners keep the module alive.
48/// An owned native module is unloaded when its last owner is dropped.
49/// Library-backed modules instead retain their library; externally borrowed modules rely on the external owner.
50#[derive(Debug, Clone)]
51pub struct Module {
52 inner: Arc<ModuleInner>,
53}
54
55#[derive(Debug)]
56struct ModuleInner {
57 handle: driver::CUmodule,
58 context: Arc<Context>,
59 ownership: ModuleOwnership,
60 artifact_metadata: Option<Arc<ArtifactMetadata>>,
61}
62
63#[derive(Debug)]
64enum ModuleOwnership {
65 Owned,
66 External,
67 Library { owner: Library },
68}
69
70#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
71pub(crate) enum CodeOwnerId {
72 Module(usize),
73 Library(usize),
74}
75
76/// The address and byte size of a global variable in a CUDA module.
77///
78/// This view borrows the module to keep the variable loaded.
79/// It does not establish host accessibility, initialization, or exclusive access to the storage.
80#[derive(Debug, Clone, Copy)]
81pub struct Global<'a> {
82 ptr: *mut (),
83 size: usize,
84 _module: &'a Module,
85}
86
87/// A native texture reference borrowed from a module.
88///
89/// The module borrow keeps the reference loaded.
90#[derive(Debug, Clone, Copy)]
91pub struct TextureReference<'a> {
92 handle: driver::CUtexref,
93 _module: &'a Module,
94}
95
96/// A native surface reference borrowed from a module.
97///
98/// The module borrow keeps the reference loaded.
99#[derive(Debug, Clone, Copy)]
100pub struct SurfaceReference<'a> {
101 handle: driver::CUsurfref,
102 _module: &'a Module,
103}
104
105impl Module {
106 /// Takes ownership of a native module and its context association.
107 ///
108 /// # Safety
109 ///
110 /// `raw.handle` must be a live module loaded in `raw.context` and must not be unloaded elsewhere.
111 ///
112 /// # Errors
113 ///
114 /// Returns `Error::NullHandle` if the handle is null.
115 pub unsafe fn from_raw(raw: RawModule) -> Result<Self> {
116 // SAFETY: the caller guarantees `raw.handle` is a live module of `raw.context` that nothing else unloads, which `from_raw_with_metadata` requires.
117 unsafe { Self::from_raw_with_metadata(raw.handle, raw.context, None) }
118 }
119
120 pub(crate) unsafe fn from_raw_with_metadata(
121 handle: driver::CUmodule,
122 context: Arc<Context>,
123 artifact_metadata: Option<Arc<ArtifactMetadata>>,
124 ) -> Result<Self> {
125 if handle.is_null() {
126 return Err(Error::NullHandle);
127 }
128
129 Ok(Self {
130 inner: Arc::new(ModuleInner {
131 handle,
132 context,
133 ownership: ModuleOwnership::Owned,
134 artifact_metadata,
135 }),
136 })
137 }
138
139 /// Borrows an externally owned module.
140 ///
141 /// # Safety
142 ///
143 /// `handle` must belong to `context` and stay loaded until every clone, function, prepared launch and graph retaining this wrapper has been released.
144 pub unsafe fn from_borrowed_raw(handle: driver::CUmodule, context: Arc<Context>) -> Self {
145 Self {
146 inner: Arc::new(ModuleInner {
147 handle,
148 context,
149 ownership: ModuleOwnership::External,
150 artifact_metadata: None,
151 }),
152 }
153 }
154
155 /// Returns the kernel function with the given name from the module.
156 ///
157 /// # Errors
158 ///
159 /// Returns [`crate::error::Status::NotFound`] if the module has no kernel function named `name`.
160 /// Also returns an error if `name` contains an interior NUL byte, the module context cannot be bound, CUDA rejects the lookup, or a previous asynchronous launch reports an error.
161 pub fn function(&self, name: &str) -> Result<KernelFunction> {
162 self.inner.context.bind()?;
163 let c_name = CString::new(name)?;
164 let mut handle = ptr::null_mut();
165 // SAFETY: `handle` is a writable local, `self.inner.handle` is the live module this owner retains, and `c_name` is NUL-terminated for the call.
166 unsafe {
167 try_ffi!(driver::cuModuleGetFunction(
168 &raw mut handle,
169 self.inner.handle,
170 c_name.as_ptr()
171 ))?;
172 }
173
174 if handle.is_null() {
175 return Err(Error::NullHandle);
176 }
177 Ok(KernelFunction {
178 // SAFETY: CUDA returned this function handle for the module retained by `self`.
179 handle: unsafe { DeviceFunction::from_raw(handle) },
180 module: self.clone(),
181 })
182 }
183
184 /// Returns the number of functions in this module.
185 ///
186 /// # Errors
187 ///
188 /// Returns an error if CUDA Driver cannot report the function count.
189 pub fn function_count(&self) -> Result<usize> {
190 self.inner.context.bind()?;
191 let mut count = 0;
192 // SAFETY: `count` is a writable local, and `self.inner.handle` is the live module this owner retains.
193 unsafe {
194 try_ffi!(driver::cuModuleGetFunctionCount(
195 &raw mut count,
196 self.inner.handle
197 ))?;
198 }
199 to_usize(count, "module function count")
200 }
201
202 /// Returns the borrowed native module handle without transferring ownership.
203 #[must_use]
204 pub fn as_raw(&self) -> driver::CUmodule {
205 self.inner.handle
206 }
207
208 /// Consumes the module and returns the raw CUDA module handle without unloading it.
209 ///
210 /// The caller becomes responsible for eventually unloading the returned handle with CUDA while retaining the returned context.
211 /// Returns the unchanged wrapper if functions, graphs or other clones retain this module, or if its native handle is externally owned or owned by a library.
212 ///
213 /// # Errors
214 ///
215 /// Returns `Err(self)` if the module is externally owned, owned by a library, or still shared with another clone, function, or graph owner.
216 /// The returned wrapper remains usable and retains its ownership mode.
217 pub fn into_raw(self) -> StdResult<RawModule, Self> {
218 if !matches!(self.inner.ownership, ModuleOwnership::Owned) {
219 return Err(self);
220 }
221 match Arc::try_unwrap(self.inner) {
222 Ok(mut inner) => {
223 inner.ownership = ModuleOwnership::External;
224 Ok(RawModule {
225 handle: inner.handle,
226 context: Arc::clone(&inner.context),
227 })
228 }
229 Err(inner) => Err(Self { inner }),
230 }
231 }
232
233 /// Returns the CUDA context in which this module was loaded.
234 #[must_use]
235 pub fn context(&self) -> &Arc<Context> {
236 &self.inner.context
237 }
238
239 pub(crate) fn code_owner_id(&self) -> CodeOwnerId {
240 match &self.inner.ownership {
241 ModuleOwnership::Library { owner } => CodeOwnerId::Library(owner.code_owner_id()),
242 ModuleOwnership::Owned | ModuleOwnership::External => {
243 CodeOwnerId::Module(Arc::as_ptr(&self.inner).addr())
244 }
245 }
246 }
247
248 pub(crate) fn from_library(
249 handle: driver::CUmodule,
250 context: Arc<Context>,
251 library: Library,
252 ) -> Self {
253 Self {
254 inner: Arc::new(ModuleInner {
255 handle,
256 context,
257 ownership: ModuleOwnership::Library { owner: library },
258 artifact_metadata: None,
259 }),
260 }
261 }
262
263 /// Returns the base pointer and size of the global with the given name located in the module.
264 ///
265 /// The returned [`Global`] borrows this module, so the module remains loaded for at least as long as the global reference is usable.
266 ///
267 /// # Errors
268 ///
269 /// Returns [`crate::error::Status::NotFound`] if the module has no global variable named `name`.
270 /// Also returns an error if `name` contains an interior NUL byte, the module context cannot be bound, CUDA rejects the lookup, or a previous asynchronous launch reports an error.
271 pub fn global(&self, name: &str) -> Result<Global<'_>> {
272 let c_name = CString::new(name)?;
273 let mut ptr = 0;
274 let mut size = 0;
275 self.inner.context.bind()?;
276 // SAFETY: `ptr` and `size` are writable locals, `self.inner.handle` is the live module this owner retains, and `c_name` is NUL-terminated for the call.
277 unsafe {
278 try_ffi!(driver::cuModuleGetGlobal_v2(
279 &raw mut ptr,
280 &raw mut size,
281 self.inner.handle,
282 c_name.as_ptr(),
283 ))?;
284 }
285 Ok(Global {
286 ptr: ptr as _,
287 size: to_usize(size, "global byte count")?,
288 _module: self,
289 })
290 }
291}
292
293impl Drop for ModuleInner {
294 fn drop(&mut self) {
295 if !matches!(self.ownership, ModuleOwnership::Owned) {
296 return;
297 }
298
299 if let Err(error) = self.context.bind() {
300 report_cleanup_failure("bind the cuda context to unload", "cuda module", &error);
301 return;
302 }
303
304 // SAFETY: the last owner of an owned module unloads `self.handle` once, with its context bound, after every function and graph retaining it has dropped.
305 unsafe {
306 if let Err(error) = try_ffi!(driver::cuModuleUnload(self.handle)) {
307 report_cleanup_failure("unload", "cuda module", &error);
308 }
309 }
310 }
311}
312
313// SAFETY: a CUDA module handle may be used and unloaded from any thread once its context is bound, and the other fields are `Send`.
314unsafe impl Send for ModuleInner {}
315
316// SAFETY: shared access only passes the immutable handle to thread-safe driver lookups; `ownership` changes only on an owned value in `into_raw`.
317unsafe impl Sync for ModuleInner {}
318
319impl Global<'_> {
320 /// Returns the variable's raw address.
321 ///
322 /// Obtaining the pointer does not make device-only memory accessible to the host.
323 #[must_use]
324 pub const fn as_ptr(&self) -> *mut () {
325 self.ptr
326 }
327
328 /// Returns the variable's size in bytes.
329 #[must_use]
330 pub const fn byte_len(&self) -> usize {
331 self.size
332 }
333}
334
335impl TextureReference<'_> {
336 /// Returns the native texture reference borrowed from the module.
337 #[must_use]
338 pub const fn as_raw(&self) -> driver::CUtexref {
339 self.handle
340 }
341}
342
343impl SurfaceReference<'_> {
344 /// Returns the native surface reference borrowed from the module.
345 #[must_use]
346 pub const fn as_raw(&self) -> driver::CUsurfref {
347 self.handle
348 }
349}