Skip to main content

singe_cuda/module/
function.rs

1use std::{
2    fmt::{self, Display, Formatter},
3    ptr,
4};
5
6use bitflags::parser;
7use singe_cuda_sys::driver;
8
9use super::{
10    KernelLaunchArgs, LaunchConfig, LaunchGeometry, Module,
11    config::validate_dynamic_shared_memory_bytes,
12};
13use crate::{
14    error::{Error, Result},
15    graph::{ExecutableGraph, Graph, GraphNode},
16    green::GreenStream,
17    kernel::{self, ModuleKernelHandle},
18    stream::Stream,
19    try_ffi,
20    types::{DeviceFunction, FunctionAttribute, SharedMemoryCarveout, SharedMemoryMode},
21    utility::{to_i32, to_usize},
22};
23
24bitflags::bitflags! {
25    /// Occupancy calculator flag
26    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
27    pub struct OccupancyFlags: u32 {
28        /// Default behavior.
29        const DEFAULT = driver::CUoccupancy_flags::CU_OCCUPANCY_DEFAULT.0;
30        /// Assume global caching is enabled and cannot be automatically turned off.
31        const DISABLE_CACHING_OVERRIDE = driver::CUoccupancy_flags::CU_OCCUPANCY_DISABLE_CACHING_OVERRIDE.0;
32    }
33}
34
35impl Display for OccupancyFlags {
36    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
37        parser::to_writer(self, f)
38    }
39}
40
41/// Function resource usage, compilation versions, and launch constraints queried from CUDA.
42///
43/// These values describe the function in its module context; device and compiler choices can affect them.
44#[derive(Debug, Clone, Copy, PartialEq, Eq)]
45pub struct FunctionAttributes {
46    /// Statically allocated shared memory per block in bytes, excluding dynamic launch-time shared memory.
47    pub shared_size_bytes: usize,
48    /// User-allocated constant memory required by the function in bytes.
49    pub const_size_bytes: usize,
50    /// Local memory used per thread in bytes.
51    pub local_size_bytes: usize,
52    /// Maximum number of threads per block permitted for this function on the device.
53    pub max_threads_per_block: i32,
54    /// Number of registers used per thread.
55    pub num_regs: i32,
56    /// PTX virtual architecture version, encoded as `major * 10 + minor`.
57    /// May be zero for cubins compiled before CUDA 3.0.
58    pub ptx_version: i32,
59    /// Binary architecture version, encoded as `major * 10 + minor`.
60    /// Legacy cubins without an encoded version report 10.
61    pub binary_version: i32,
62    /// Whether the function was compiled with the `-Xptxas --dlcm=ca` cache setting.
63    pub cache_mode_ca: bool,
64    /// Maximum dynamic shared memory permitted per block for this function, in bytes.
65    pub max_dynamic_shared_size_bytes: i32,
66    /// Preferred percentage of shared L1/shared-memory resources assigned to shared memory.
67    /// This is a hint; CUDA may choose another ratio.
68    pub preferred_shared_memory_carveout: i32,
69    /// Whether launches must specify a valid cluster size.
70    pub cluster_dim_must_be_set: bool,
71    /// Required cluster width in blocks; zero means no required width is set.
72    pub required_cluster_width: i32,
73    /// Required cluster height in blocks; zero means no required height is set.
74    pub required_cluster_height: i32,
75    /// Required cluster depth in blocks; zero means no required depth is set.
76    pub required_cluster_depth: i32,
77    /// Native cluster scheduling policy preference value.
78    pub cluster_scheduling_policy_preference: i32,
79    /// Whether the function permits cluster sizes beyond the portable limit.
80    pub non_portable_cluster_size_allowed: bool,
81}
82
83/// A block size selected to maximize potential occupancy and the minimum grid size needed to achieve it.
84#[derive(Debug, Clone, Copy, PartialEq, Eq)]
85pub struct OccupancyMaxPotentialBlockSize {
86    /// Minimum number of blocks in the grid needed to achieve the calculated maximum occupancy.
87    pub min_grid_size: i32,
88    /// Number of threads per block selected by the occupancy calculator.
89    pub block_size: i32,
90}
91
92/// A context-specific CUDA kernel function that retains its module and loading context.
93#[derive(Debug, Clone)]
94pub struct KernelFunction {
95    pub(crate) handle: DeviceFunction,
96    pub(crate) module: Module,
97}
98
99// SAFETY: a CUDA function handle is usable from any thread while its module is loaded, which the retained `module` guarantees.
100unsafe impl Send for KernelFunction {}
101
102// SAFETY: `&self` methods only pass the immutable function handle to the driver, whose attribute and launch calls are thread-safe.
103unsafe impl Sync for KernelFunction {}
104
105impl KernelFunction {
106    /// Adopts a function handle while retaining its module.
107    ///
108    /// # Safety
109    ///
110    /// `handle` must identify a live function in `module` and its actual context.
111    #[must_use]
112    pub unsafe fn from_raw(handle: DeviceFunction, module: &Module) -> Self {
113        Self {
114            handle,
115            module: module.clone(),
116        }
117    }
118
119    fn check_graph_context(&self, graph: &Graph) -> Result<()> {
120        if graph.context() != &self.module.inner.context {
121            return Err(Error::context_mismatch("graph"));
122        }
123        Ok(())
124    }
125
126    fn check_executable_graph_context(&self, executable: &ExecutableGraph) -> Result<()> {
127        if executable.context() != &self.module.inner.context {
128            return Err(Error::context_mismatch("executable graph"));
129        }
130        Ok(())
131    }
132
133    /// Invokes this kernel function on a grid of blocks using the given stream.
134    /// Each block contains the threads specified by [`LaunchConfig::block_dim`].
135    ///
136    /// [`LaunchConfig::shared_memory_bytes`] sets the amount of dynamic shared memory available to each thread block.
137    ///
138    /// Kernel parameters are passed with [`KernelParameters`](super::KernelParameters) or tuples of shared or mutable references.
139    ///
140    /// Launching the kernel invalidates the persistent function state set through the following deprecated APIs: [`sys::cuFuncSetBlockShape`](singe_cuda_sys::driver::cuFuncSetBlockShape), [`sys::cuFuncSetSharedSize`](singe_cuda_sys::driver::cuFuncSetSharedSize), [`sys::cuParamSetSize`](singe_cuda_sys::driver::cuParamSetSize), [`sys::cuParamSeti`](singe_cuda_sys::driver::cuParamSeti), [`sys::cuParamSetf`](singe_cuda_sys::driver::cuParamSetf), [`sys::cuParamSetv`](singe_cuda_sys::driver::cuParamSetv).
141    ///
142    /// The kernel must either have been compiled with toolchain version 3.2 or later so that it contains kernel parameter information, or have no kernel parameters.
143    /// If either of these conditions is not met, the launch returns [`crate::error::Status::InvalidImage`].
144    ///
145    /// # Safety
146    ///
147    /// Arguments must match the kernel ABI and satisfy its access and value requirements.
148    /// Keep the function and all pointed-to storage alive until execution completes.
149    /// Order conflicting accesses and preserve exclusive writable access during execution.
150    /// Successful submission does not establish output initialization or completion.
151    ///
152    /// # Errors
153    ///
154    /// Returns [`crate::error::Status::InvalidImage`] if the kernel parameter metadata requirements above are not met.
155    /// Also returns an error if `stream` belongs to a different context, the module context cannot be bound, CUDA rejects the launch, or a previous asynchronous launch reports an error.
156    pub unsafe fn launch_async<'a, P>(
157        &self,
158        config: &LaunchConfig,
159        params: P,
160        stream: &Stream,
161    ) -> Result<()>
162    where
163        P: KernelLaunchArgs<'a>,
164    {
165        if stream.context() != &self.module.inner.context {
166            return Err(Error::StreamContextMismatch);
167        }
168
169        self.module.inner.context.bind()?;
170        // SAFETY: the function and stream share the context bound above, the encoded arguments live through the call, and the caller guarantees their ABI, storage lifetime, and access ordering.
171        params.with_encoded_arguments(|mut arguments| unsafe {
172            config.launch_raw(
173                self.handle.as_raw(),
174                stream.as_raw(),
175                arguments.as_mut_ptr().cast(),
176            )?;
177            Ok(())
178        })
179    }
180
181    /// Adds this kernel to `graph` as a kernel node.
182    ///
183    /// # Safety
184    ///
185    /// CUDA copies each kernel argument value during this call.
186    /// Non-pointer argument values may be borrowed from stack or temporary storage that outlives this call.
187    /// If an argument value is a pointer, CUDA stores only the pointer address.
188    /// The caller must ensure every copied pointer value remains valid for every graph instantiation, update, and launch that can execute the created node.
189    /// Mutable pointer arguments must remain exclusive for the work ordered by those launches.
190    /// Arguments must match the function ABI and satisfy its value and access requirements.
191    /// Keep the graph, executable or another code owner alive until queued executions complete.
192    ///
193    /// # Errors
194    ///
195    /// Returns `Error::ContextMismatch` if the graph is associated with another context.
196    /// Also propagates context binding errors, dependency ownership errors, and CUDA failures when creating the kernel node or setting its launch attributes.
197    pub unsafe fn add_to_graph<'a, P>(
198        &self,
199        graph: &mut Graph,
200        dependencies: &[GraphNode],
201        config: &LaunchConfig,
202        params: P,
203    ) -> Result<GraphNode>
204    where
205        P: KernelLaunchArgs<'a>,
206    {
207        self.check_graph_context(graph)?;
208        self.module.inner.context.bind()?;
209        // SAFETY: `self.handle` is a live function of the module retained below, and the caller guarantees the argument ABI, pointer validity, and exclusivity that `add_kernel_node` requires.
210        let node = unsafe { graph.add_kernel_node(dependencies, self.handle, config, params) }?;
211        graph.retain_module(&self.module)?;
212        Ok(node)
213    }
214
215    /// Updates this kernel's parameters in an executable graph node.
216    ///
217    /// # Safety
218    ///
219    /// CUDA copies each kernel argument value during this call.
220    /// Non-pointer argument values may be borrowed from stack or temporary storage that outlives this call.
221    /// If an argument value is a pointer, CUDA stores only the pointer address.
222    /// The caller must ensure every copied pointer value remains valid for every future launch that can execute `node`.
223    /// Mutable pointer arguments must remain exclusive for the work ordered by those launches.
224    /// Arguments must match the function ABI and satisfy its value and access requirements.
225    /// Keep the graph, executable or another code owner alive until queued executions complete.
226    /// Launch attributes are preserved; they must remain compatible with this kernel and geometry.
227    ///
228    /// # Errors
229    ///
230    /// Returns `Error::ContextMismatch` if the executable is associated with another context.
231    /// Also propagates context binding errors, node ownership errors, and CUDA failures when updating the node.
232    pub unsafe fn set_graph_node_params<'a, P>(
233        &self,
234        executable: &mut ExecutableGraph,
235        node: &GraphNode,
236        geometry: &LaunchGeometry,
237        params: P,
238    ) -> Result<()>
239    where
240        P: KernelLaunchArgs<'a>,
241    {
242        self.check_executable_graph_context(executable)?;
243        self.module.inner.context.bind()?;
244        // SAFETY: `self.handle` is a live function of the module retained below, and the caller guarantees the argument ABI, pointer validity, exclusivity, and attribute compatibility that `set_kernel_node_params` requires.
245        unsafe { executable.set_kernel_node_params(node, self.handle, geometry, params) }?;
246        executable.retain_module(&self.module);
247        Ok(())
248    }
249
250    /// Returns the module retained by this function.
251    #[must_use]
252    pub const fn module(&self) -> &Module {
253        &self.module
254    }
255
256    /// Returns the native function name, replacing invalid UTF-8 sequences.
257    ///
258    /// # Errors
259    ///
260    /// Returns an error if the module context cannot be bound, CUDA cannot query the name, or CUDA returns a null name pointer.
261    pub fn name(&self) -> Result<String> {
262        // SAFETY: the kernel handle belongs to the module or library retained by `self`.
263        unsafe {
264            kernel::name::<ModuleKernelHandle>(
265                self.module.inner.context.as_ref(),
266                self.handle.as_raw(),
267            )
268        }
269    }
270
271    /// Returns one function attribute for this module context.
272    ///
273    /// # Errors
274    ///
275    /// Returns an error if the module context cannot be bound or CUDA rejects the requested function attribute.
276    pub fn attribute(&self, attribute: FunctionAttribute) -> Result<i32> {
277        // SAFETY: the kernel handle belongs to the module or library retained by `self`.
278        unsafe {
279            kernel::attribute::<ModuleKernelHandle>(
280                self.module.inner.context.as_ref(),
281                self.handle.as_raw(),
282                attribute,
283            )
284        }
285    }
286
287    /// Sets a mutable function attribute.
288    ///
289    /// See [`FunctionAttribute`] for the supported attributes and their value constraints.
290    ///
291    /// # Errors
292    ///
293    /// Returns an error if the module context cannot be bound or CUDA rejects the selected attribute or value.
294    pub fn set_attribute(&self, attribute: FunctionAttribute, value: i32) -> Result<()> {
295        // SAFETY: the kernel handle belongs to the module or library retained by `self`.
296        unsafe {
297            kernel::set_attribute::<ModuleKernelHandle>(
298                self.module.inner.context.as_ref(),
299                self.handle.as_raw(),
300                attribute,
301                value,
302            )
303        }
304    }
305
306    /// Sets the maximum dynamic shared memory permitted per block, in bytes.
307    ///
308    /// The requested size plus static shared memory must fit the device's opt-in per-block limit.
309    /// This attribute does not enable oversized shared memory; use [`Self::set_shared_memory_mode`] for that.
310    ///
311    /// # Errors
312    ///
313    /// Returns an error if the module context cannot be bound or CUDA rejects the selected attribute or value.
314    pub fn set_max_dynamic_shared_memory_bytes(&self, bytes: i32) -> Result<()> {
315        self.set_attribute(FunctionAttribute::MaxDynamicSharedSizeBytes, bytes)
316    }
317
318    /// Sets the preferred shared-memory carveout for this function.
319    ///
320    /// On devices sharing hardware resources between L1 cache and shared memory, the driver treats this as a hint and may choose another ratio.
321    ///
322    /// # Errors
323    ///
324    /// Returns an error if the module context cannot be bound or CUDA rejects the selected attribute or value.
325    pub fn set_preferred_shared_memory_carveout(
326        &self,
327        carveout: SharedMemoryCarveout,
328    ) -> Result<()> {
329        self.set_attribute(
330            FunctionAttribute::PreferredSharedMemoryCarveout,
331            i32::from(carveout),
332        )
333    }
334
335    /// Queries the function's resource usage, compilation versions, and launch constraints.
336    ///
337    /// Each field is queried separately; the result is not an atomic snapshot of concurrent attribute changes.
338    ///
339    /// # Errors
340    ///
341    /// Returns an error if the module context cannot be bound or any constituent attribute query fails.
342    /// No partial result is returned.
343    pub fn attributes(&self) -> Result<FunctionAttributes> {
344        Ok(FunctionAttributes {
345            shared_size_bytes: to_usize(
346                self.attribute(FunctionAttribute::SharedSizeBytes)?,
347                "shared size bytes",
348            )?,
349            const_size_bytes: to_usize(
350                self.attribute(FunctionAttribute::ConstSizeBytes)?,
351                "const size bytes",
352            )?,
353            local_size_bytes: to_usize(
354                self.attribute(FunctionAttribute::LocalSizeBytes)?,
355                "local size bytes",
356            )?,
357            max_threads_per_block: self.attribute(FunctionAttribute::MaxThreadsPerBlock)?,
358            num_regs: self.attribute(FunctionAttribute::NumRegs)?,
359            ptx_version: self.attribute(FunctionAttribute::PtxVersion)?,
360            binary_version: self.attribute(FunctionAttribute::BinaryVersion)?,
361            cache_mode_ca: self.attribute(FunctionAttribute::CacheModeCa)? != 0,
362            max_dynamic_shared_size_bytes: self
363                .attribute(FunctionAttribute::MaxDynamicSharedSizeBytes)?,
364            preferred_shared_memory_carveout: self
365                .attribute(FunctionAttribute::PreferredSharedMemoryCarveout)?,
366            cluster_dim_must_be_set: self.attribute(FunctionAttribute::ClusterSizeMustBeSet)? != 0,
367            required_cluster_width: self.attribute(FunctionAttribute::RequiredClusterWidth)?,
368            required_cluster_height: self.attribute(FunctionAttribute::RequiredClusterHeight)?,
369            required_cluster_depth: self.attribute(FunctionAttribute::RequiredClusterDepth)?,
370            cluster_scheduling_policy_preference: self
371                .attribute(FunctionAttribute::ClusterSchedulingPolicyPreference)?,
372            non_portable_cluster_size_allowed: self
373                .attribute(FunctionAttribute::NonPortableClusterSizeAllowed)?
374                != 0,
375        })
376    }
377
378    /// Returns the maximum number of active blocks per streaming multiprocessor for `block_size` threads and the specified dynamic shared-memory bytes per block.
379    ///
380    /// `flags` controls how special cases are handled.
381    /// The valid flags are:
382    ///
383    /// * [`OccupancyFlags::DEFAULT`], which maintains the default behavior as [`sys::cuOccupancyMaxActiveBlocksPerMultiprocessor`](singe_cuda_sys::driver::cuOccupancyMaxActiveBlocksPerMultiprocessor);
384    ///
385    /// * [`OccupancyFlags::DISABLE_CACHING_OVERRIDE`], which suppresses the default behavior on platforms where global caching affects occupancy.
386    ///   On such platforms, if caching is enabled, but per-block SM resource usage would result in zero occupancy, the occupancy calculator will calculate the occupancy as if caching is disabled.
387    ///   Setting [`OccupancyFlags::DISABLE_CACHING_OVERRIDE`] makes the occupancy calculator return 0 in such cases.
388    ///   More information can be found about this feature in the "Unified L1/Texture Cache" section of the Maxwell tuning guide.
389    ///
390    /// For context-less kernels queried via [`Library::kernel`](crate::library::Library::kernel).
391    /// Here, this wrapper uses the current context for calculations.
392    ///
393    /// # Errors
394    ///
395    /// Returns an error if the module context cannot be bound, CUDA rejects the occupancy query, or a previous asynchronous launch reports an error.
396    pub fn occupancy_max_active_blocks_per_multiprocessor(
397        &self,
398        block_size: i32,
399        dynamic_shared_memory_bytes: usize,
400        flags: OccupancyFlags,
401    ) -> Result<i32> {
402        self.module.inner.context.bind()?;
403        let dynamic_shared_memory_bytes =
404            validate_dynamic_shared_memory_bytes(dynamic_shared_memory_bytes)?;
405        let mut blocks = 0;
406        // SAFETY: `blocks` is a writable local, and `self.handle` is a live function of the module `self` retains, with its context bound above.
407        unsafe {
408            try_ffi!(
409                driver::cuOccupancyMaxActiveBlocksPerMultiprocessorWithFlags(
410                    &raw mut blocks,
411                    self.handle.as_raw(),
412                    block_size,
413                    dynamic_shared_memory_bytes,
414                    flags.bits(),
415                )
416            )?;
417        }
418        Ok(blocks)
419    }
420
421    /// Returns dynamic shared memory available per block when launching `num_blocks` blocks on a streaming multiprocessor.
422    ///
423    /// The returned value is the maximum size of dynamic shared memory that allows `num_blocks` blocks per streaming multiprocessor.
424    ///
425    /// For context-less kernels queried via [`Library::kernel`](crate::library::Library::kernel).
426    /// Here, this wrapper uses the current context for calculations.
427    ///
428    /// # Errors
429    ///
430    /// Returns an error if the module context cannot be bound, CUDA rejects the occupancy query, or a previous asynchronous launch reports an error.
431    pub fn occupancy_available_dynamic_shared_memory_per_block(
432        &self,
433        num_blocks: i32,
434        block_size: i32,
435    ) -> Result<usize> {
436        self.module.inner.context.bind()?;
437        let mut bytes = 0;
438        // SAFETY: `bytes` is a writable local, and `self.handle` is a live function of the module `self` retains, with its context bound above.
439        unsafe {
440            try_ffi!(driver::cuOccupancyAvailableDynamicSMemPerBlock(
441                &raw mut bytes,
442                self.handle.as_raw(),
443                num_blocks,
444                block_size,
445            ))?;
446        }
447        to_usize(bytes, "occupancy byte count")
448    }
449
450    /// Selects a block size with maximum potential occupancy for the supplied dynamic shared-memory bytes per block.
451    ///
452    /// `block_size_limit` restricts the block size; zero adds no limit.
453    ///
454    /// `flags` controls how special cases are handled.
455    /// The valid flags are:
456    ///
457    /// * [`OccupancyFlags::DEFAULT`], which maintains the default behavior as [`sys::cuOccupancyMaxPotentialBlockSize`](singe_cuda_sys::driver::cuOccupancyMaxPotentialBlockSize);
458    ///
459    /// * [`OccupancyFlags::DISABLE_CACHING_OVERRIDE`], which suppresses the default behavior on platforms where global caching affects occupancy.
460    ///   On such platforms, the launch configurations that produce maximal occupancy might not support global caching.
461    ///   Setting [`OccupancyFlags::DISABLE_CACHING_OVERRIDE`] guarantees that the produced launch configuration is global caching compatible at a potential cost of occupancy.
462    ///   More information can be found about this feature in the "Unified L1/Texture Cache" section of the Maxwell tuning guide.
463    ///
464    /// For context-less kernels queried via [`Library::kernel`](crate::library::Library::kernel).
465    /// Here, this wrapper uses the current context for calculations.
466    ///
467    /// # Errors
468    ///
469    /// Returns an error if the module context cannot be bound, CUDA rejects the occupancy query, or a previous asynchronous launch reports an error.
470    pub fn occupancy_max_potential_block_size(
471        &self,
472        dynamic_shared_memory_bytes: usize,
473        block_size_limit: i32,
474        flags: OccupancyFlags,
475    ) -> Result<OccupancyMaxPotentialBlockSize> {
476        self.module.inner.context.bind()?;
477        let dynamic_shared_memory_bytes =
478            validate_dynamic_shared_memory_bytes(dynamic_shared_memory_bytes)?;
479        let mut min_grid_size = 0;
480        let mut block_size = 0;
481        // SAFETY: the outputs are writable locals, `self.handle` is a live function of the module `self` retains, and no block-size callback is passed.
482        unsafe {
483            try_ffi!(driver::cuOccupancyMaxPotentialBlockSizeWithFlags(
484                &raw mut min_grid_size,
485                &raw mut block_size,
486                self.handle.as_raw(),
487                None,
488                dynamic_shared_memory_bytes,
489                block_size_limit,
490                flags.bits(),
491            ))?;
492        }
493        Ok(OccupancyMaxPotentialBlockSize {
494            min_grid_size,
495            block_size,
496        })
497    }
498
499    /// Given this kernel and launch configuration, returns the maximum cluster size.
500    ///
501    /// The cluster dimensions in `config` are ignored.
502    /// If the kernel has a required cluster size set, the returned value reflects the required cluster size.
503    ///
504    /// By default this returns a value that is portable on future hardware.
505    /// A higher value may be returned if the kernel function allows non-portable cluster sizes.
506    ///
507    /// Respects the compile-time launch bounds.
508    ///
509    /// For context-less kernels queried via [`Library::kernel`](crate::library::Library::kernel).
510    /// Here, this wrapper uses the current context for calculations.
511    ///
512    /// # Errors
513    ///
514    /// Returns an error if the module context cannot be bound, CUDA rejects the occupancy query, or a previous asynchronous launch reports an error.
515    pub fn occupancy_max_potential_cluster_size(&self, config: &LaunchConfig) -> Result<i32> {
516        self.module.inner.context.bind()?;
517        let mut cluster_size = 0;
518        // SAFETY: `cluster_size` is a writable local, `self.handle` is a live function of the module `self` retains, and `config` lives through the closure.
519        config.with_raw_config(ptr::null_mut(), |config| unsafe {
520            try_ffi!(driver::cuOccupancyMaxPotentialClusterSize(
521                &raw mut cluster_size,
522                self.handle.as_raw(),
523                config,
524            ))?;
525            Ok(cluster_size)
526        })
527    }
528
529    /// Given this kernel and launch configuration, returns the maximum number of clusters that could co-exist on the target device.
530    ///
531    /// If the kernel already has a required cluster size set, the cluster size from `config` must either be unspecified or match the required size.
532    /// Without required sizes, the cluster size must be specified in `config`; otherwise this method returns an error.
533    ///
534    /// Various kernel function attributes may affect occupancy calculation.
535    /// Runtime environment may affect how the hardware schedules the clusters, so the calculated occupancy is not guaranteed to be achievable.
536    ///
537    /// For context-less kernels queried via [`Library::kernel`](crate::library::Library::kernel).
538    /// Here, this wrapper uses the current context for calculations.
539    ///
540    /// # Errors
541    ///
542    /// Returns an error if the module context cannot be bound, `config` does not specify a valid cluster size for this kernel, CUDA rejects the occupancy query, or a previous asynchronous launch reports an error.
543    pub fn occupancy_max_active_clusters(&self, config: &LaunchConfig) -> Result<i32> {
544        self.module.inner.context.bind()?;
545        let mut clusters = 0;
546        // SAFETY: `clusters` is a writable local, `self.handle` is a live function of the module `self` retains, and `config` lives through the closure.
547        config.with_raw_config(ptr::null_mut(), |config| unsafe {
548            try_ffi!(driver::cuOccupancyMaxActiveClusters(
549                &raw mut clusters,
550                self.handle.as_raw(),
551                config,
552            ))?;
553            Ok(clusters)
554        })
555    }
556
557    /// Returns the borrowed device function handle without retaining another module owner.
558    #[must_use]
559    pub const fn as_raw(&self) -> DeviceFunction {
560        self.handle
561    }
562}
563
564impl KernelFunction {
565    /// Specifies whether the function may use oversized shared memory configurations.
566    ///
567    /// # Errors
568    ///
569    /// Returns an error if the module context cannot be bound or CUDA rejects the selected attribute or value.
570    pub fn set_shared_memory_mode(&self, mode: SharedMemoryMode) -> Result<()> {
571        self.set_attribute(
572            FunctionAttribute::SharedMemoryMode,
573            to_i32(u32::from(mode), "shared memory mode")?,
574        )
575    }
576
577    /// Returns the shared memory mode configured for this function.
578    ///
579    /// # Errors
580    ///
581    /// Returns an error if the module context cannot be bound or CUDA rejects the requested function attribute.
582    /// Returns `Error::UnknownEnumValue` if CUDA returns an unrecognized shared-memory mode.
583    pub fn shared_memory_mode(&self) -> Result<SharedMemoryMode> {
584        let value = self.attribute(FunctionAttribute::SharedMemoryMode)?;
585        u32::try_from(value)
586            .ok()
587            .and_then(|raw| SharedMemoryMode::try_from(raw).ok())
588            .ok_or_else(|| Error::UnknownEnumValue {
589                name: "shared memory mode".into(),
590                value: i64::from(value),
591            })
592    }
593
594    /// Invokes this kernel on a stream provisioned by a green context.
595    ///
596    /// # Safety
597    ///
598    /// Arguments must match the kernel ABI and satisfy its access and value requirements.
599    /// Keep the function and all pointed-to storage alive until execution completes.
600    /// Order conflicting accesses and preserve exclusive writable access during execution.
601    /// Successful submission does not establish output initialization or completion.
602    ///
603    /// # Errors
604    ///
605    /// Returns `Error::StreamContextMismatch` unless the function was loaded in the primary context of the green context's device.
606    /// Also returns an error if the module context cannot be bound, argument encoding fails, CUDA rejects the launch, or previous asynchronous work reports an error.
607    pub unsafe fn launch_green_async<'a, P: KernelLaunchArgs<'a>>(
608        &self,
609        config: &LaunchConfig,
610        params: P,
611        stream: &GreenStream,
612    ) -> Result<()> {
613        if !self
614            .module
615            .inner
616            .context
617            .is_primary_for(stream.context().device())?
618        {
619            return Err(Error::StreamContextMismatch);
620        }
621
622        self.module.inner.context.bind()?;
623        // SAFETY: the function's context is bound above, the encoded arguments live through the call, and the caller guarantees their ABI, storage lifetime, and access ordering.
624        params.with_encoded_arguments(|mut arguments| unsafe {
625            config.launch_raw(
626                self.handle.as_raw(),
627                stream.as_raw(),
628                arguments.as_mut_ptr().cast(),
629            )
630        })
631    }
632}