Skip to main content

singe_cuda/kernel/
launch.rs

1//! Typed kernel signatures and context-bound launch preparation.
2
3use std::{
4    fmt,
5    marker::PhantomData,
6    mem::{align_of, size_of},
7    sync::Arc,
8};
9
10use singe_cuda_sys::driver;
11use thiserror::Error;
12
13use crate::{
14    context::Context,
15    device::DeviceAttribute,
16    dim::Dim3,
17    error::{Error as CudaError, Result, Status},
18    graph::{
19        ExecutableGraph, Graph, GraphNode,
20        owned::{Recordable, Recording},
21    },
22    green::SmResource,
23    module::{
24        KernelFunction, KernelParameters, LaunchAttribute, LaunchConfig, LaunchGeometry,
25        OccupancyFlags,
26    },
27    stream::{Stream, StreamCaptureScope},
28    submission::{DeviceOperation, Execution, Operation, Resources},
29    try_ffi,
30    types::{FunctionAttribute, SharedMemoryMode},
31    utility::{to_i32, to_u32, to_usize},
32    view::NoUninitDeviceRepr,
33};
34
35/// Access to the storage addressed by a kernel parameter.
36#[derive(Debug, Clone, Copy, PartialEq, Eq)]
37pub enum ParameterAccess {
38    /// A copied value, with no implied device memory access.
39    Value,
40    /// Reads initialized elements.
41    Read,
42    /// Writes elements without reading their previous values.
43    Write,
44    /// Reads and writes initialized elements.
45    ReadWrite,
46    /// A pointer whose access contract is supplied by the caller.
47    OpaquePointer,
48}
49
50/// Host representation of one CUDA parameter, in declaration order.
51#[derive(Debug, Clone, Copy, PartialEq, Eq)]
52pub struct ParameterLayout {
53    size: usize,
54    alignment: usize,
55    access: ParameterAccess,
56}
57
58impl ParameterLayout {
59    /// Describes a by-value parameter with initialized representation bytes.
60    #[must_use]
61    pub const fn value<T: NoUninitDeviceRepr>() -> Self {
62        let () = T::LAYOUT;
63        Self {
64            size: size_of::<T>(),
65            alignment: align_of::<T>(),
66            access: ParameterAccess::Value,
67        }
68    }
69
70    /// Describes a CUDA device pointer and its declared memory access.
71    #[must_use]
72    pub const fn pointer(access: ParameterAccess) -> Self {
73        Self {
74            size: size_of::<*const ()>(),
75            alignment: align_of::<*const ()>(),
76            access,
77        }
78    }
79
80    /// Returns the parameter representation size in bytes.
81    #[must_use]
82    pub const fn size(self) -> usize {
83        self.size
84    }
85
86    /// Returns the parameter representation alignment in bytes.
87    #[must_use]
88    pub const fn alignment(self) -> usize {
89        self.alignment
90    }
91
92    /// Returns the declared access to storage addressed by this parameter.
93    #[must_use]
94    pub const fn access(self) -> ParameterAccess {
95        self.access
96    }
97}
98
99/// Number of dimensions used by the kernel's indexing scheme.
100#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
101pub enum LaunchRank {
102    /// Uses only the x axis; grid and block y and z dimensions must all be one.
103    One,
104    /// Uses the x and y axes; grid and block z dimensions must be one.
105    Two,
106    /// Permits all three grid and block axes.
107    #[default]
108    Three,
109}
110
111/// Integer representation used for thread coordinates.
112#[derive(Debug, Clone, Copy, PartialEq, Eq)]
113pub enum CoordinateWidth {
114    /// Nonnegative coordinates representable by a unsigned 32-bit integer.
115    U32,
116    /// Nonnegative coordinates representable by a signed 32-bit integer.
117    I32,
118    /// Nonnegative coordinates representable by a unsigned 64-bit integer.
119    U64,
120    /// Nonnegative coordinates representable by a signed 64-bit integer.
121    I64,
122}
123
124impl CoordinateWidth {
125    const fn max(self) -> u128 {
126        match self {
127            Self::U32 => u32::MAX as u128,
128            Self::I32 => i32::MAX as u128,
129            Self::U64 => u64::MAX as u128,
130            Self::I64 => i64::MAX as u128,
131        }
132    }
133}
134
135/// Block dimensions accepted by the kernel.
136#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
137pub enum BlockRequirement {
138    /// Adds no block-shape restriction beyond CUDA function and device limits.
139    #[default]
140    Any,
141    /// Requires these exact thread dimensions for each block.
142    Exact(Dim3),
143    /// The total number of threads must be a nonzero multiple of this value.
144    MultipleOf(u32),
145    /// Maximum total number of threads in a block.
146    MaxThreads(u32),
147}
148
149/// Dynamic shared memory required by each block.
150#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
151pub enum SharedMemoryRequirement {
152    /// Adds no dynamic shared-memory requirement beyond CUDA function and device limits.
153    #[default]
154    Any,
155    /// Requires exactly this many dynamic shared-memory bytes per block.
156    Exact(usize),
157    /// Requires at least this many dynamic shared-memory bytes per block.
158    AtLeast(usize),
159    /// Inclusive kernel-specific bounds on dynamic shared memory.
160    Range {
161        /// Minimum permitted dynamic shared-memory bytes per block, inclusive.
162        min: usize,
163        /// Maximum permitted dynamic shared-memory bytes per block, inclusive.
164        max: usize,
165    },
166}
167
168/// Kernel requirements checked against a configuration and its actual context.
169///
170/// Coordinate requirements check the launched extent, including padded threads.
171/// Leave them unspecified only when the kernel has no corresponding restriction.
172#[derive(Debug, Clone, Copy, PartialEq, Eq)]
173pub struct LaunchRequirements {
174    /// Axes used by the kernel's indexing scheme.
175    /// Unused grid and block axes must equal one.
176    pub rank: LaunchRank,
177    /// Optional integer width bounding the largest launched coordinate on every axis, including padded threads.
178    pub axis_coordinates: Option<CoordinateWidth>,
179    /// Optional integer width bounding the largest flattened coordinate across the complete launched grid, including padded threads.
180    pub linear_coordinates: Option<CoordinateWidth>,
181    /// Kernel-specific constraints on the block shape or thread count.
182    pub block: BlockRequirement,
183    /// Kernel-specific dynamic shared-memory byte requirements per block.
184    pub shared_memory: SharedMemoryRequirement,
185    /// Minimum device compute capability as `(major, minor)`, or `None` for no additional minimum.
186    pub min_compute_capability: Option<(u32, u32)>,
187    /// Required cluster dimensions in blocks, or `None` for no signature-specific cluster shape.
188    /// Native kernel requirements still apply.
189    pub cluster: Option<Dim3>,
190    /// Whether the launch must explicitly enable cooperative execution.
191    /// A false value also permits cooperative launches when the device supports them.
192    pub cooperative: bool,
193}
194
195impl Default for LaunchRequirements {
196    fn default() -> Self {
197        Self::DEFAULT
198    }
199}
200
201impl LaunchRequirements {
202    /// No restrictions beyond the CUDA function and device limits.
203    pub const DEFAULT: Self = Self {
204        rank: LaunchRank::Three,
205        axis_coordinates: None,
206        linear_coordinates: None,
207        block: BlockRequirement::Any,
208        shared_memory: SharedMemoryRequirement::Any,
209        min_compute_capability: None,
210        cluster: None,
211        cooperative: false,
212    };
213}
214
215/// A kernel ABI and its launch requirements.
216///
217/// # Safety
218///
219/// `encode` must encode exactly `PARAMETERS`, in order, using the declared CUDA representation and access modes.
220/// `raw_arguments` must preserve that order and check every typed view's actual context.
221/// By-value representations must contain no uninitialized bytes.
222/// The requirements must describe the kernel being bound.
223/// This contract does not certify argument-dependent memory bounds or output coverage.
224pub unsafe trait KernelSignature: 'static {
225    /// Typed values and borrowed device views in declaration order.
226    type Arguments<'a>;
227
228    /// CUDA parameter values, including raw device addresses, in declaration order.
229    type RawArguments: Copy + 'static;
230
231    /// Host ABI layouts of the CUDA parameters, in declaration order.
232    const PARAMETERS: &'static [ParameterLayout];
233
234    /// Indexing and execution requirements checked when binding a launch configuration.
235    const REQUIREMENTS: LaunchRequirements;
236
237    /// Checks device-view contexts and converts typed arguments into CUDA parameter values.
238    ///
239    /// # Errors
240    ///
241    /// Returns an error if a typed device view belongs to another context or the implementation cannot convert the supplied values to its raw argument representation.
242    /// Implementations may impose additional argument-specific checks.
243    fn raw_arguments(
244        arguments: Self::Arguments<'_>,
245        context: &Arc<Context>,
246    ) -> Result<Self::RawArguments>;
247
248    /// Copies raw argument values into storage valid for the duration of `f`.
249    fn encode<R>(arguments: Self::RawArguments, f: impl FnOnce(KernelParameters<'_>) -> R) -> R;
250}
251
252/// Failure to match a kernel's ABI, indexing or execution requirements.
253#[derive(Debug, Clone, PartialEq, Eq, Error)]
254#[non_exhaustive]
255pub enum LaunchContractError {
256    /// The native function parameter count differs from the signature.
257    #[error("kernel parameter count mismatch (expected {expected}, got {actual})")]
258    ParameterCount {
259        /// Number of parameters declared by the signature.
260        expected: usize,
261        /// Number of parameters reported by CUDA.
262        actual: usize,
263    },
264    /// A native parameter offset or size differs from the signature's host ABI layout.
265    #[error(
266        "kernel parameter {index} layout mismatch (expected offset {expected_offset}, size {expected_size}; got offset {actual_offset}, size {actual_size})"
267    )]
268    ParameterLayout {
269        /// Zero-based parameter index.
270        index: usize,
271        /// Byte offset computed from the signature's preceding parameter sizes and alignments.
272        expected_offset: usize,
273        /// Parameter size in bytes declared by the signature.
274        expected_size: usize,
275        /// Parameter byte offset reported by CUDA.
276        actual_offset: usize,
277        /// Parameter size in bytes reported by CUDA.
278        actual_size: usize,
279    },
280    /// Nonunit dimensions occur on axes outside the kernel's indexing rank.
281    #[error("launch dimensions exceed the kernel's {rank:?} dimensional indexing")]
282    Rank {
283        /// Indexing rank required by the kernel.
284        rank: LaunchRank,
285    },
286    /// The configured block violates a kernel-specific block requirement.
287    #[error("block dimensions {actual:?} do not satisfy {required:?}")]
288    Block {
289        /// Kernel-specific block requirement.
290        required: BlockRequirement,
291        /// Configured block dimensions in threads.
292        actual: Dim3,
293    },
294    /// A requested launch quantity exceeds its device, function, or coordinate limit.
295    #[error("`{name}` exceeds its limit (requested {requested}, limit {limit})")]
296    Limit {
297        /// Name of the checked launch quantity.
298        name: &'static str,
299        /// Requested quantity in the units identified by `name`.
300        requested: u128,
301        /// Maximum permitted quantity in the same units as `requested`.
302        limit: u128,
303    },
304    /// Dynamic shared memory violates the kernel's byte requirement.
305    #[error("dynamic shared memory {actual} does not satisfy {required:?}")]
306    SharedMemory {
307        /// Kernel-specific dynamic shared-memory requirement.
308        required: SharedMemoryRequirement,
309        /// Configured dynamic shared-memory bytes per block.
310        actual: usize,
311    },
312    /// The device's compute capability is below the kernel's required minimum.
313    #[error("compute capability {actual:?} is below {required:?}")]
314    Architecture {
315        /// Minimum compute capability as `(major, minor)`.
316        required: (u32, u32),
317        /// Device compute capability as `(major, minor)`.
318        actual: (u32, u32),
319    },
320    /// Configured cluster dimensions disagree with the signature or native kernel requirement.
321    #[error("cluster dimensions {actual:?} do not satisfy {required:?}")]
322    Cluster {
323        /// Required cluster dimensions in blocks, when present.
324        required: Option<Dim3>,
325        /// Effective launch cluster dimensions in blocks, when present.
326        actual: Option<Dim3>,
327    },
328    /// The native function requires an explicit cluster size, but none is available.
329    #[error("kernel requires explicit cluster dimensions")]
330    ClusterRequired,
331    /// A cluster launch was requested on a device without cluster-launch support.
332    #[error("device does not support cluster launches")]
333    ClusterUnsupported,
334    /// The cluster dimensions are zero or do not divide the grid dimensions.
335    #[error("grid dimensions {grid:?} are incompatible with cluster dimensions {cluster:?}")]
336    ClusterGrid {
337        /// Configured grid dimensions in blocks.
338        grid: Dim3,
339        /// Effective cluster dimensions in blocks.
340        cluster: Dim3,
341    },
342    /// A required cooperative attribute is absent, or the device does not support the requested cooperative launch.
343    #[error("cooperative launch is required or unsupported on this device")]
344    Cooperative,
345    /// An explicit shared-memory mode was requested on a driver that cannot query or support shared-memory modes.
346    #[error("shared-memory mode {mode:?} is unsupported by the current driver")]
347    SharedMemoryModeUnsupported {
348        /// Requested per-launch shared-memory mode.
349        mode: SharedMemoryMode,
350    },
351    /// The product of grid and block volumes cannot be represented in 128 bits.
352    #[error("linear launch coordinates exceed 128 bits")]
353    CoordinateOverflow,
354    /// Computing a parameter offset or end overflows the host address space.
355    #[error("kernel parameter layout overflows the host address space")]
356    ParameterLayoutOverflow,
357}
358
359/// A typed kernel and checked configuration retaining the native code owner.
360///
361/// Preparation checks the signature and launch requirements.
362/// It does not launch work, initialize output storage, or prove argument-dependent accesses valid.
363/// Immediate submissions, capture and graph-node creation share this configuration.
364/// Executable-node updates reuse its geometry and preserve the executable's existing attributes.
365pub struct PreparedLaunch<K: KernelSignature> {
366    function: KernelFunction,
367    config: LaunchConfig,
368    _signature: PhantomData<fn() -> K>,
369}
370
371impl<K: KernelSignature> fmt::Debug for PreparedLaunch<K> {
372    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
373        f.debug_struct("PreparedLaunch")
374            .field("function", &self.function)
375            .field("config", &self.config)
376            .finish()
377    }
378}
379
380impl<K: KernelSignature> Clone for PreparedLaunch<K> {
381    fn clone(&self) -> Self {
382        Self {
383            function: self.function.clone(),
384            config: self.config.clone(),
385            _signature: PhantomData,
386        }
387    }
388}
389
390impl<K: KernelSignature> PreparedLaunch<K> {
391    /// Binds this signature to a kernel and checks its ABI and launch requirements.
392    ///
393    /// # Safety
394    ///
395    /// `K`'s access modes and launch requirements must describe this function.
396    /// Parameter count and representation mismatches are rejected.
397    /// CUDA metadata does not verify struct field layouts or semantic identity.
398    /// Explicit struct mappings must match the device field layout.
399    ///
400    /// # Errors
401    ///
402    /// Returns a [`LaunchContractError`] for parameter count or layout mismatches, layout overflow, incompatible launch requirements, or exceeded function or device limits.
403    /// Also propagates context binding, native parameter or attribute query, occupancy, resource query, and integer conversion errors.
404    /// No work is launched on success.
405    pub unsafe fn create(function: &KernelFunction, config: LaunchConfig) -> Result<Self> {
406        validate_parameters::<K>(function)?;
407        validate_requirements(function, &config, K::REQUIREMENTS)?;
408        Ok(Self {
409            function: function.clone(),
410            config,
411            _signature: PhantomData,
412        })
413    }
414
415    /// Returns the retained context-specific kernel function.
416    #[must_use]
417    pub fn function(&self) -> &KernelFunction {
418        &self.function
419    }
420
421    /// Returns the checked launch configuration.
422    #[must_use]
423    pub fn config(&self) -> &LaunchConfig {
424        &self.config
425    }
426
427    /// Returns the context in which the function's module was loaded.
428    #[must_use]
429    pub fn context(&self) -> &Arc<Context> {
430        self.function.module().context()
431    }
432
433    /// Checks that `stream` belongs to the prepared kernel's context.
434    ///
435    /// # Errors
436    ///
437    /// Returns `CudaError::StreamContextMismatch` if `stream` belongs to a different context.
438    pub fn validate_stream(&self, stream: &Stream) -> Result<()> {
439        if stream.context() != self.context() {
440            return Err(CudaError::StreamContextMismatch);
441        }
442        Ok(())
443    }
444
445    /// Submits a launch on an explicit stream in this kernel's context.
446    ///
447    /// # Safety
448    ///
449    /// Values and views must satisfy the kernel's bounds, initialization and semantic requirements.
450    /// Preserve storage lifetimes and exclusive writable access until execution completes, including every graph replay when `stream` is capturing.
451    /// Keep this prepared launch or another owner of its kernel code alive through completion.
452    ///
453    /// # Errors
454    ///
455    /// Propagates typed argument conversion and view-context errors from [`KernelSignature::raw_arguments`].
456    /// Returns `CudaError::StreamContextMismatch` if `stream` belongs to another context, and propagates context binding and native launch errors from [`KernelFunction::launch_async`].
457    pub unsafe fn launch_async(&self, arguments: K::Arguments<'_>, stream: &Stream) -> Result<()> {
458        let arguments = K::raw_arguments(arguments, self.context())?;
459        // SAFETY: `raw_arguments` checked the views' context, and the caller's guarantees on values, storage lifetimes, and code ownership are those `launch_encoded` requires.
460        unsafe { self.launch_encoded(arguments, stream) }
461    }
462
463    /// Records a launch in the active capture and retains the kernel's code for replay.
464    ///
465    /// # Safety
466    ///
467    /// Values and views must satisfy the kernel's bounds, initialization and semantic requirements for every replay.
468    /// Preserve storage lifetimes and exclusive writable access until all graph executions complete.
469    /// Keep a graph, executable or another code owner alive until queued executions complete.
470    ///
471    /// # Errors
472    ///
473    /// Propagates typed argument conversion and view-context errors from [`KernelSignature::raw_arguments`].
474    /// Returns `CudaError::StreamContextMismatch` if the capture stream belongs to another context, and propagates context binding and native launch errors.
475    pub unsafe fn record(
476        &self,
477        arguments: K::Arguments<'_>,
478        scope: &StreamCaptureScope<'_>,
479    ) -> Result<()> {
480        let arguments = K::raw_arguments(arguments, self.context())?;
481        self.validate_stream(scope.stream())?;
482        scope.retain_module(self.function.module());
483        // SAFETY: `raw_arguments` checked the views' context, the capture retains the module above, and the caller's guarantees for every replay cover what `launch_encoded` requires.
484        unsafe { self.launch_encoded(arguments, scope.stream()) }
485    }
486
487    /// Adds a graph node with this launch's configuration and retains the kernel's code.
488    ///
489    /// # Safety
490    ///
491    /// Values and views must satisfy the kernel's bounds, initialization and semantic requirements for every replay.
492    /// Preserve storage lifetimes and exclusive writable access until all graph executions complete.
493    /// Keep a graph, executable or another code owner alive until queued executions complete.
494    ///
495    /// # Errors
496    ///
497    /// Propagates typed argument conversion and view-context errors from [`KernelSignature::raw_arguments`].
498    /// Also propagates graph-context, dependency ownership, context binding, and native node creation or launch-attribute errors from [`KernelFunction::add_to_graph`].
499    pub unsafe fn add_to_graph(
500        &self,
501        arguments: K::Arguments<'_>,
502        graph: &mut Graph,
503        dependencies: &[GraphNode],
504    ) -> Result<GraphNode> {
505        let arguments = K::raw_arguments(arguments, self.context())?;
506        // SAFETY: `self.function` and `self.config` were checked against `K` when this launch was prepared, `raw_arguments` checked the views' context, and the caller's guarantees are those `KernelFunction::add_to_graph` requires.
507        K::encode(arguments, |params| unsafe {
508            self.function
509                .add_to_graph(graph, dependencies, &self.config, params)
510        })
511    }
512
513    /// Updates an executable node with this launch's geometry and arguments, retaining the kernel's code.
514    ///
515    /// # Safety
516    ///
517    /// Values and views must satisfy the kernel's bounds, initialization and semantic requirements for all future executions.
518    /// Preserve storage lifetimes and exclusive writable access until all executions using them complete.
519    /// Keep the executable or another code owner alive until queued executions complete.
520    /// Only this launch's geometry is applied; executable attributes remain unchanged and must satisfy `K`.
521    ///
522    /// # Errors
523    ///
524    /// Propagates typed argument conversion and view-context errors from [`KernelSignature::raw_arguments`].
525    /// Also propagates executable-context, node ownership, context binding, and native update errors from [`KernelFunction::set_graph_node_params`].
526    pub unsafe fn set_graph_node_params(
527        &self,
528        arguments: K::Arguments<'_>,
529        executable: &mut ExecutableGraph,
530        node: &GraphNode,
531    ) -> Result<()> {
532        let arguments = K::raw_arguments(arguments, self.context())?;
533        // SAFETY: `self.function` and `self.config` were checked against `K` when this launch was prepared, `raw_arguments` checked the views' context, and the caller's guarantees are those `KernelFunction::set_graph_node_params` requires.
534        K::encode(arguments, |params| unsafe {
535            self.function
536                .set_graph_node_params(executable, node, self.config.geometry(), params)
537        })
538    }
539
540    // Launches converted arguments on `stream`.
541    // The caller guarantees the arguments satisfy the kernel's requirements and keeps their storage and the kernel's code alive until completion.
542    unsafe fn launch_encoded(&self, arguments: K::RawArguments, stream: &Stream) -> Result<()> {
543        self.validate_stream(stream)?;
544        // SAFETY: `self.function` and `self.config` were checked against `K` when this launch was prepared, the stream's context is checked above, and the caller's argument guarantees are those `KernelFunction::launch_async` requires.
545        K::encode(arguments, |params| unsafe {
546            self.function.launch_async(&self.config, params, stream)
547        })
548    }
549}
550
551impl KernelFunction {
552    /// Updates an executable node's geometry and arguments, retaining this kernel's code.
553    ///
554    /// Launch attributes remain unchanged.
555    ///
556    /// # Safety
557    ///
558    /// `K` must describe this function and the executable's existing attributes must satisfy it.
559    /// Arguments must satisfy the kernel's bounds, initialization and aliasing requirements for every execution.
560    /// Keep storage and the executable or another code owner alive until queued executions complete.
561    ///
562    /// # Errors
563    ///
564    /// Returns an error for ABI, view-context or geometry mismatches, or if CUDA rejects the update.
565    pub unsafe fn set_typed_graph_node_params<K: KernelSignature>(
566        &self,
567        executable: &mut ExecutableGraph,
568        node: &GraphNode,
569        geometry: &LaunchGeometry,
570        arguments: K::Arguments<'_>,
571    ) -> Result<()> {
572        let arguments = K::raw_arguments(arguments, self.module().context())?;
573        validate_parameters::<K>(self)?;
574        validate_kernel_geometry(self, geometry, K::REQUIREMENTS)?;
575        // SAFETY: `raw_arguments` checked the views' context, the parameter layout and geometry are checked against `K` above, and the caller's guarantees are those `set_graph_node_params` requires.
576        K::encode(arguments, |params| unsafe {
577            self.set_graph_node_params(executable, node, geometry, params)
578        })
579    }
580}
581
582fn validate_parameters<K: KernelSignature>(function: &KernelFunction) -> Result<()> {
583    function.module().context().bind()?;
584    let mut count = 0;
585    // SAFETY: `count` is a writable local, and `function` retains its module, whose context is bound above.
586    unsafe {
587        try_ffi!(driver::cuFuncGetParamCount(
588            function.as_raw().as_raw(),
589            &raw mut count
590        ))?;
591    }
592
593    if to_usize(count, "kernel parameter count")? != K::PARAMETERS.len() {
594        return Err(LaunchContractError::ParameterCount {
595            expected: K::PARAMETERS.len(),
596            actual: to_usize(count, "kernel parameter count")?,
597        }
598        .into());
599    }
600
601    let mut expected_offset = 0_usize;
602    for (index, parameter) in K::PARAMETERS.iter().enumerate() {
603        let padding = expected_offset.wrapping_neg() & (parameter.alignment - 1);
604        expected_offset = expected_offset
605            .checked_add(padding)
606            .ok_or(LaunchContractError::ParameterLayoutOverflow)?;
607        let mut offset = 0;
608        let mut size = 0;
609        let native_index = index
610            .try_into()
611            .map_err(|_| CudaError::out_of_range("kernel parameter index"))?;
612        // SAFETY: `offset` and `size` are writable locals, and `function` retains its module, whose context is bound above.
613        unsafe {
614            try_ffi!(driver::cuFuncGetParamInfo(
615                function.as_raw().as_raw(),
616                native_index,
617                &raw mut offset,
618                &raw mut size
619            ))?;
620        }
621
622        if to_usize(offset, "kernel parameter offset")? != expected_offset
623            || to_usize(size, "kernel parameter size")? != parameter.size
624        {
625            return Err(LaunchContractError::ParameterLayout {
626                index,
627                expected_offset,
628                expected_size: parameter.size,
629                actual_offset: to_usize(offset, "kernel parameter offset")?,
630                actual_size: to_usize(size, "kernel parameter size")?,
631            }
632            .into());
633        }
634
635        expected_offset = expected_offset
636            .checked_add(parameter.size)
637            .ok_or(LaunchContractError::ParameterLayoutOverflow)?;
638    }
639    Ok(())
640}
641
642// Widens a native attribute or occupancy count, which CUDA reports as a non-negative `i32`, for the limit checks.
643fn native_limit(value: i32) -> Result<u128> {
644    u128::try_from(value).map_err(|_| CudaError::out_of_range("native launch limit"))
645}
646
647fn check_limit(name: &'static str, requested: u128, limit: u128) -> Result<()> {
648    if requested > limit {
649        return Err(LaunchContractError::Limit {
650            name,
651            requested,
652            limit,
653        }
654        .into());
655    }
656    Ok(())
657}
658
659fn volume(dim: Dim3) -> u128 {
660    u128::from(dim.x) * u128::from(dim.y) * u128::from(dim.z)
661}
662
663fn validate_geometry(
664    function: &KernelFunction,
665    geometry: &LaunchGeometry,
666    required: LaunchRequirements,
667) -> Result<()> {
668    let grid = geometry.grid_dim();
669    let block = geometry.block_dim();
670    match required.rank {
671        LaunchRank::One if grid.y != 1 || grid.z != 1 || block.y != 1 || block.z != 1 => {
672            return Err(LaunchContractError::Rank {
673                rank: required.rank,
674            }
675            .into());
676        }
677        LaunchRank::Two if grid.z != 1 || block.z != 1 => {
678            return Err(LaunchContractError::Rank {
679                rank: required.rank,
680            }
681            .into());
682        }
683        _ => {}
684    }
685
686    match required.block {
687        BlockRequirement::MaxThreads(n) if volume(block) > u128::from(n) => {
688            return Err(LaunchContractError::Block {
689                required: required.block,
690                actual: block,
691            }
692            .into());
693        }
694        BlockRequirement::Exact(dim) if dim != block => {
695            return Err(LaunchContractError::Block {
696                required: required.block,
697                actual: block,
698            }
699            .into());
700        }
701        BlockRequirement::MultipleOf(n)
702            if n == 0 || !volume(block).is_multiple_of(u128::from(n)) =>
703        {
704            return Err(LaunchContractError::Block {
705                required: required.block,
706                actual: block,
707            }
708            .into());
709        }
710        _ => {}
711    }
712
713    let context = function.module().context();
714    let device = context.device();
715    for (g, b, grid_attr, block_attr) in [
716        (
717            grid.x,
718            block.x,
719            DeviceAttribute::MaxGridDimX,
720            DeviceAttribute::MaxBlockDimX,
721        ),
722        (
723            grid.y,
724            block.y,
725            DeviceAttribute::MaxGridDimY,
726            DeviceAttribute::MaxBlockDimY,
727        ),
728        (
729            grid.z,
730            block.z,
731            DeviceAttribute::MaxGridDimZ,
732            DeviceAttribute::MaxBlockDimZ,
733        ),
734    ] {
735        check_limit(
736            "grid dimension",
737            u128::from(g),
738            native_limit(device.attribute(grid_attr)?)?,
739        )?;
740        check_limit(
741            "block dimension",
742            u128::from(b),
743            native_limit(device.attribute(block_attr)?)?,
744        )?;
745        if let Some(width) = required.axis_coordinates {
746            check_limit(
747                "axis coordinate",
748                u128::from(g) * u128::from(b) - 1,
749                width.max(),
750            )?;
751        }
752    }
753
754    if let Some(width) = required.linear_coordinates {
755        check_limit(
756            "linear coordinate",
757            volume(grid)
758                .checked_mul(volume(block))
759                .ok_or(LaunchContractError::CoordinateOverflow)?
760                - 1,
761            width.max(),
762        )?;
763    }
764
765    let threads = volume(block);
766    check_limit(
767        "threads per block",
768        threads,
769        native_limit(device.attribute(DeviceAttribute::MaxThreadsPerBlock)?)?,
770    )?;
771    check_limit(
772        "kernel threads per block",
773        threads,
774        native_limit(function.attribute(FunctionAttribute::MaxThreadsPerBlock)?)?,
775    )?;
776    Ok(())
777}
778
779fn validate_kernel_geometry(
780    function: &KernelFunction,
781    geometry: &LaunchGeometry,
782    required: LaunchRequirements,
783) -> Result<()> {
784    validate_geometry(function, geometry, required)?;
785    let device = function.module().context().device();
786    let shared = geometry.shared_memory_bytes();
787    match required.shared_memory {
788        SharedMemoryRequirement::Range { min, max } if shared < min || shared > max => {
789            return Err(LaunchContractError::SharedMemory {
790                required: required.shared_memory,
791                actual: shared,
792            }
793            .into());
794        }
795        SharedMemoryRequirement::Exact(n) if shared != n => {
796            return Err(LaunchContractError::SharedMemory {
797                required: required.shared_memory,
798                actual: shared,
799            }
800            .into());
801        }
802        SharedMemoryRequirement::AtLeast(n) if shared < n => {
803            return Err(LaunchContractError::SharedMemory {
804                required: required.shared_memory,
805                actual: shared,
806            }
807            .into());
808        }
809        _ => {}
810    }
811
812    if let Some(minimum) = required.min_compute_capability {
813        let actual = (
814            to_u32(
815                device.attribute(DeviceAttribute::ComputeCapabilityMajor)?,
816                "native attribute",
817            )?,
818            to_u32(
819                device.attribute(DeviceAttribute::ComputeCapabilityMinor)?,
820                "native attribute",
821            )?,
822        );
823        if actual < minimum {
824            return Err(LaunchContractError::Architecture {
825                required: minimum,
826                actual,
827            }
828            .into());
829        }
830    }
831    Ok(())
832}
833
834fn validate_requirements(
835    function: &KernelFunction,
836    config: &LaunchConfig,
837    required: LaunchRequirements,
838) -> Result<()> {
839    validate_kernel_geometry(function, config.geometry(), required)?;
840    let context = function.module().context();
841    let device = context.device();
842    let grid = config.grid_dim();
843    let threads = volume(config.block_dim());
844    let shared = config.shared_memory_bytes();
845    check_limit(
846        "dynamic shared memory",
847        shared as u128,
848        dynamic_shared_memory_limit(function, config)?,
849    )?;
850    let mut cluster = None;
851    let mut cooperative = false;
852    for attribute in config.attributes() {
853        match attribute {
854            LaunchAttribute::ClusterDimension(dim) => cluster = Some(*dim),
855            LaunchAttribute::Cooperative(value) => cooperative = *value,
856            _ => {}
857        }
858    }
859
860    let native_cluster = Dim3::new(
861        to_u32(
862            function.attribute(FunctionAttribute::RequiredClusterWidth)?,
863            "native attribute",
864        )?,
865        to_u32(
866            function.attribute(FunctionAttribute::RequiredClusterHeight)?,
867            "native attribute",
868        )?,
869        to_u32(
870            function.attribute(FunctionAttribute::RequiredClusterDepth)?,
871            "native attribute",
872        )?,
873    );
874    let native_cluster = (native_cluster.x != 0 || native_cluster.y != 0 || native_cluster.z != 0)
875        .then_some(native_cluster);
876    if let (Some(actual), Some(native)) = (cluster, native_cluster)
877        && actual != native
878    {
879        return Err(LaunchContractError::Cluster {
880            required: Some(native),
881            actual: Some(actual),
882        }
883        .into());
884    }
885
886    let cluster = cluster.or(native_cluster);
887    if required.cluster.is_some() && cluster != required.cluster {
888        return Err(LaunchContractError::Cluster {
889            required: required.cluster,
890            actual: cluster,
891        }
892        .into());
893    }
894
895    if function.attribute(FunctionAttribute::ClusterSizeMustBeSet)? != 0 && cluster.is_none() {
896        return Err(LaunchContractError::ClusterRequired.into());
897    }
898
899    if let Some(dim) = cluster {
900        if device.attribute(DeviceAttribute::ClusterLaunch)? == 0 {
901            return Err(LaunchContractError::ClusterUnsupported.into());
902        }
903
904        if dim.x == 0
905            || dim.y == 0
906            || dim.z == 0
907            || !grid.x.is_multiple_of(dim.x)
908            || !grid.y.is_multiple_of(dim.y)
909            || !grid.z.is_multiple_of(dim.z)
910        {
911            return Err(LaunchContractError::ClusterGrid { grid, cluster: dim }.into());
912        }
913
914        let limit = function.occupancy_max_potential_cluster_size(config)?;
915        check_limit("cluster blocks", volume(dim), native_limit(limit)?)?;
916    }
917
918    if required.cooperative && !cooperative
919        || cooperative && device.attribute(DeviceAttribute::CooperativeLaunch)? == 0
920    {
921        return Err(LaunchContractError::Cooperative.into());
922    }
923
924    if let (true, Some(cluster)) = (cooperative, cluster) {
925        let active = function.occupancy_max_active_clusters(config)?;
926        check_limit(
927            "cooperative grid clusters",
928            volume(grid) / volume(cluster),
929            native_limit(active)?,
930        )?;
931    } else if cooperative {
932        let active = function.occupancy_max_active_blocks_per_multiprocessor(
933            to_i32(threads, "block thread count")?,
934            shared,
935            OccupancyFlags::DEFAULT,
936        )?;
937        let sms = SmResource::for_context(context)?.sm_count();
938        check_limit(
939            "cooperative grid blocks",
940            volume(grid),
941            native_limit(active)? * u128::from(sms),
942        )?;
943    }
944    Ok(())
945}
946
947fn dynamic_shared_memory_limit(function: &KernelFunction, config: &LaunchConfig) -> Result<u128> {
948    let requested = config.attributes().iter().find_map(|attribute| {
949        if let LaunchAttribute::SharedMemoryMode(mode) = attribute {
950            Some(*mode)
951        } else {
952            None
953        }
954    });
955    let function_mode = match function.shared_memory_mode() {
956        Ok(mode) => mode,
957        // A live function on a driver without shared-memory modes rejects this attribute.
958        // Ordinary launches still use the function's dynamic-memory limit.
959        Err(CudaError::Cuda {
960            code: Status::InvalidValue | Status::NotSupported,
961            ..
962        }) => match requested {
963            None => SharedMemoryMode::Default,
964            Some(mode) => {
965                return Err(LaunchContractError::SharedMemoryModeUnsupported { mode }.into());
966            }
967        },
968        Err(error) => return Err(error),
969    };
970    let mode = requested.unwrap_or(function_mode);
971    let device = function.module().context().device();
972    let capacity = match mode {
973        SharedMemoryMode::Default => {
974            return native_limit(function.attribute(FunctionAttribute::MaxDynamicSharedSizeBytes)?);
975        }
976        SharedMemoryMode::RequirePortable => {
977            native_limit(device.attribute(DeviceAttribute::MaxSharedMemoryPerBlock)?)?
978        }
979        SharedMemoryMode::AllowNonPortable => {
980            native_limit(device.attribute(DeviceAttribute::MaxSharedMemoryPerBlockOptin)?)?
981        }
982        SharedMemoryMode::AllowOversizedSharedMemory
983        | SharedMemoryMode::PreferOversizedSharedMemory => {
984            let optin = device.attribute(DeviceAttribute::MaxSharedMemoryPerBlockOptin)?;
985            let oversized = device.attribute(DeviceAttribute::MaxOversizedSharedMemoryPerBlock)?;
986            native_limit(optin.max(oversized))?
987        }
988    };
989    let static_bytes = native_limit(function.attribute(FunctionAttribute::SharedSizeBytes)?)?;
990    check_limit("static shared memory", static_bytes, capacity)?;
991    Ok(capacity - static_bytes)
992}
993
994/// Prepared owned kernel work with an explicit resource and access contract.
995#[derive(Debug)]
996pub struct KernelOperation<K: KernelSignature, T> {
997    launch: PreparedLaunch<K>,
998    arguments: K::RawArguments,
999    resources: Resources,
1000    output: T,
1001}
1002
1003impl<K: KernelSignature> PreparedLaunch<K> {
1004    /// Binds owned resources to this prepared launch without enqueueing work.
1005    ///
1006    /// # Safety
1007    ///
1008    /// Arguments must satisfy the kernel's bounds, value, aliasing and output coverage contracts.
1009    /// Retain every pointed-to allocation and declare all accesses in `resources`.
1010    /// `output` must preserve pending initialization until successful completion, including capture.
1011    ///
1012    /// # Errors
1013    ///
1014    /// Propagates typed argument conversion and view-context errors from [`KernelSignature::raw_arguments`].
1015    pub unsafe fn into_operation<T: 'static>(
1016        self,
1017        arguments: K::Arguments<'_>,
1018        mut resources: Resources,
1019        output: T,
1020    ) -> Result<KernelOperation<K, T>> {
1021        let arguments = K::raw_arguments(arguments, self.context())?;
1022        resources.retain(Arc::new(self.function.module().clone()));
1023        Ok(KernelOperation {
1024            launch: self,
1025            arguments,
1026            resources,
1027            output,
1028        })
1029    }
1030}
1031
1032// SAFETY: `into_operation`'s caller declared every owner and access in `resources` and supplied a pending `output`, and `enqueue` registers them through `Execution::enqueue` before launching.
1033unsafe impl<K: KernelSignature, T: 'static> Operation for KernelOperation<K, T> {
1034    type Pending = Self::Output;
1035
1036    type Output = T;
1037
1038    fn enqueue(self, execution: &mut Execution) -> Result<T> {
1039        // SAFETY: `resources` retain every buffer the arguments address, as `into_operation` requires, and `launch_encoded` runs on the stream that orders those accesses.
1040        unsafe {
1041            execution.enqueue(self.resources, |stream| {
1042                self.launch.launch_encoded(self.arguments, stream)
1043            })?;
1044        }
1045        Ok(self.output)
1046    }
1047
1048    unsafe fn resolve(pending: Self::Pending) -> Result<Self::Output> {
1049        Ok(pending)
1050    }
1051}
1052
1053// SAFETY: `resolve` returns its input unchanged, and `enqueue` schedules the launch without host resolution.
1054unsafe impl<K: KernelSignature, T: 'static> DeviceOperation for KernelOperation<K, T> {}
1055
1056// SAFETY: `record` registers the declared owners and accesses with `Recording` before the launch, the module is among the retained resources, and `output` stays pending as `into_operation` requires.
1057unsafe impl<K: KernelSignature, T: 'static> Recordable for KernelOperation<K, T> {
1058    type Output = T;
1059
1060    fn record(self, recording: &mut Recording) -> Result<T> {
1061        // SAFETY: `resources` retain every buffer the arguments address for every replay, as `into_operation` requires, and the launch records on the capturing stream.
1062        unsafe {
1063            recording.enqueue(self.resources, |stream| {
1064                self.launch.launch_encoded(self.arguments, stream)
1065            })?;
1066        }
1067        Ok(self.output)
1068    }
1069}