Skip to main content

singe_cuda/
error.rs

1//! Typed CUDA errors, native status values, and FFI status conversion.
2
3#![expect(
4    deprecated,
5    reason = "wraps deprecated upstream API values that remain part of the supported surface"
6)]
7
8use std::{borrow::Cow, error, ffi::NulError, io, result::Result as StdResult, sync::Arc};
9
10use oxide_artifacts::ArtifactError;
11use singe_cuda_sys::runtime;
12use thiserror::Error;
13
14use crate::kernel::launch::LaunchContractError;
15#[cfg(feature = "nvjitlink_13_4")]
16use crate::nvjitlink::Status as NvJitLinkStatus;
17#[cfg(feature = "nvrtc_13_4")]
18use crate::nvrtc::Status as NvrtcStatus;
19#[cfg(feature = "nvvm_13_4")]
20use crate::nvvm::Status as NvvmStatus;
21
22singe_core::wrapper_status! {
23    library = "cuda",
24    error = Error::Cuda,
25    raw = runtime::cudaError_t,
26    success = CUDA_SUCCESS,
27    absence = singe_cuda_sys::take_absence,
28    unknown = "UNKNOWN_CUDA_STATUS",
29    description = runtime::cudaGetErrorString,
30    /// CUDA driver and runtime status code.
31    pub enum Status: u32 {
32        /// The API call returned with no errors.
33        ///
34        /// For a query such as [`Event::query`](crate::event::Event::query) or [`Stream::query`](crate::stream::Stream::query), it also means the queried work is complete.
35        Success = CUDA_SUCCESS,
36        /// This indicates that one or more of the parameters passed to the API call is not within an acceptable range of values.
37        InvalidValue = CUDA_ERROR_INVALID_VALUE,
38        /// The API call failed because it was unable to allocate enough memory or other resources to perform the requested operation.
39        OutOfMemory = CUDA_ERROR_OUT_OF_MEMORY,
40        /// This indicates that the CUDA driver has not been initialized or that initialization has failed.
41        NotInitialized = CUDA_ERROR_NOT_INITIALIZED,
42        /// This indicates that the CUDA driver is in the process of shutting down.
43        Deinitialized = CUDA_ERROR_DEINITIALIZED,
44        /// This indicates profiler is not initialized for this run.
45        ///
46        /// This can happen when the application is running with external profiling tools like visual profiler.
47        ProfilerDisabled = CUDA_ERROR_PROFILER_DISABLED,
48        /// Deprecated: This error return is deprecated as of CUDA 5.0.
49        /// Starting or stopping the profiler without initialization is no longer an error.
50        #[deprecated]
51        ProfilerNotInitialized = CUDA_ERROR_PROFILER_NOT_INITIALIZED,
52        /// Deprecated: This error return is deprecated as of CUDA 5.0.
53        /// Starting the profiler when profiling is already enabled is no longer an error.
54        #[deprecated]
55        ProfilerAlreadyStarted = CUDA_ERROR_PROFILER_ALREADY_STARTED,
56        /// Deprecated: This error return is deprecated as of CUDA 5.0.
57        /// Stopping the profiler when profiling is already disabled is no longer an error.
58        #[deprecated]
59        ProfilerAlreadyStopped = CUDA_ERROR_PROFILER_ALREADY_STOPPED,
60        /// This indicates that the CUDA driver that the application has loaded is a stub library.
61        ///
62        /// Applications that run with the stub rather than a real driver loaded will result in CUDA API returning this error.
63        StubLibrary = CUDA_ERROR_STUB_LIBRARY,
64        /// This indicates that the API call requires a newer CUDA driver than the one currently installed.
65        ///
66        /// Users should install an updated NVIDIA CUDA driver to allow the API call to succeed.
67        CallRequiresNewerDriver = CUDA_ERROR_CALL_REQUIRES_NEWER_DRIVER,
68        /// This indicates that requested CUDA device is unavailable at the current time.
69        ///
70        /// Devices are often unavailable because their compute mode is [`ComputeMode::ExclusiveProcess`](crate::device::ComputeMode::ExclusiveProcess) or [`ComputeMode::Prohibited`](crate::device::ComputeMode::Prohibited).
71        DeviceUnavailable = CUDA_ERROR_DEVICE_UNAVAILABLE,
72        /// This indicates that no CUDA-capable devices were detected by the installed CUDA driver.
73        NoDevice = CUDA_ERROR_NO_DEVICE,
74        /// This indicates that the device ordinal supplied by the user does not correspond to a valid CUDA device or that the action requested is invalid for the specified device.
75        InvalidDevice = CUDA_ERROR_INVALID_DEVICE,
76        /// This error indicates that the Grid license is not applied.
77        DeviceNotLicensed = CUDA_ERROR_DEVICE_NOT_LICENSED,
78        /// This indicates that the device kernel image is invalid.
79        ///
80        /// This can also indicate an invalid CUDA module.
81        InvalidImage = CUDA_ERROR_INVALID_IMAGE,
82        /// This most frequently indicates that there is no context bound to the current thread.
83        ///
84        /// This can also be returned if a context passed to an API call is not a valid handle, such as a destroyed context.
85        /// This can also be returned if a context and an API call come from different driver API versions.
86        /// This can also be returned if a green context passed to an API call was not converted to an ordinary context first.
87        InvalidContext = CUDA_ERROR_INVALID_CONTEXT,
88        /// This indicated that the context being supplied as a parameter to the API call was already the active context.
89        #[deprecated]
90        ContextAlreadyCurrent = CUDA_ERROR_CONTEXT_ALREADY_CURRENT,
91        /// This indicates that a map or register operation has failed.
92        MapFailed = CUDA_ERROR_MAP_FAILED,
93        /// This indicates that an unmap or unregister operation has failed.
94        UnmapFailed = CUDA_ERROR_UNMAP_FAILED,
95        /// This indicates that the specified array is currently mapped and thus cannot be destroyed.
96        ArrayIsMapped = CUDA_ERROR_ARRAY_IS_MAPPED,
97        /// This indicates that the resource is already mapped.
98        AlreadyMapped = CUDA_ERROR_ALREADY_MAPPED,
99        /// This indicates that there is no kernel image available that is suitable for the device.
100        ///
101        /// This can occur when a user specifies code generation options for a particular CUDA source file that do not include the corresponding device configuration.
102        NoBinaryForGpu = CUDA_ERROR_NO_BINARY_FOR_GPU,
103        /// This indicates that a resource has already been acquired.
104        AlreadyAcquired = CUDA_ERROR_ALREADY_ACQUIRED,
105        /// This indicates that a resource is not mapped.
106        NotMapped = CUDA_ERROR_NOT_MAPPED,
107        /// This indicates that a mapped resource is not available for access as an array.
108        NotMappedAsArray = CUDA_ERROR_NOT_MAPPED_AS_ARRAY,
109        /// This indicates that a mapped resource is not available for access as a pointer.
110        NotMappedAsPointer = CUDA_ERROR_NOT_MAPPED_AS_POINTER,
111        /// This indicates that an uncorrectable ECC error was detected during execution.
112        EccUncorrectable = CUDA_ERROR_ECC_UNCORRECTABLE,
113        /// This indicates that the context limit passed to the API call is not supported by the active device.
114        UnsupportedLimit = CUDA_ERROR_UNSUPPORTED_LIMIT,
115        /// This indicates that the `CUcontext` passed to the API call can only be bound to a single CPU thread at a time but is already bound to a CPU thread.
116        ContextAlreadyInUse = CUDA_ERROR_CONTEXT_ALREADY_IN_USE,
117        /// This indicates that peer access is not supported across the given devices.
118        PeerAccessUnsupported = CUDA_ERROR_PEER_ACCESS_UNSUPPORTED,
119        /// This indicates that a PTX JIT compilation failed.
120        InvalidPtx = CUDA_ERROR_INVALID_PTX,
121        /// This indicates an error with OpenGL or DirectX context.
122        InvalidGraphicsContext = CUDA_ERROR_INVALID_GRAPHICS_CONTEXT,
123        /// This indicates that an uncorrectable NVLink error was detected during the execution.
124        NvlinkUncorrectable = CUDA_ERROR_NVLINK_UNCORRECTABLE,
125        /// This indicates that the PTX JIT compiler library was not found.
126        JitCompilerNotFound = CUDA_ERROR_JIT_COMPILER_NOT_FOUND,
127        /// This indicates that the provided PTX was compiled with an unsupported toolchain.
128        UnsupportedPtxVersion = CUDA_ERROR_UNSUPPORTED_PTX_VERSION,
129        /// This indicates that the PTX JIT compilation was disabled.
130        JitCompilationDisabled = CUDA_ERROR_JIT_COMPILATION_DISABLED,
131        /// This indicates that the execution affinity type passed to the API call is not supported by the active device.
132        UnsupportedExecAffinity = CUDA_ERROR_UNSUPPORTED_EXEC_AFFINITY,
133        /// This indicates that the code to be compiled by the PTX JIT calls device-side `cudaDeviceSynchronize`, which is unsupported.
134        UnsupportedDevsideSync = CUDA_ERROR_UNSUPPORTED_DEVSIDE_SYNC,
135        /// This indicates that an exception occurred on the device that is now contained by the GPU's error containment capability.
136        ///
137        /// Common causes are certain invalid accesses of peer GPU memory over NVLink and certain classes of hardware errors.
138        /// This leaves the process in an inconsistent state and any further CUDA work will return the same error.
139        /// To continue using CUDA, the process must be terminated and relaunched.
140        Contained = CUDA_ERROR_CONTAINED,
141        /// This indicates that the device kernel source is invalid.
142        ///
143        /// This includes compilation/linker errors encountered in device code or user error.
144        InvalidSource = CUDA_ERROR_INVALID_SOURCE,
145        /// This indicates that the file specified was not found.
146        FileNotFound = CUDA_ERROR_FILE_NOT_FOUND,
147        /// This indicates that initialization of a shared object failed.
148        SharedObjectInitFailed = CUDA_ERROR_SHARED_OBJECT_INIT_FAILED,
149        /// This indicates that an OS call failed.
150        OperatingSystem = CUDA_ERROR_OPERATING_SYSTEM,
151        /// This indicates that a resource handle passed to the API call was not valid.
152        ///
153        /// Resource handles are opaque native handles such as those of streams and events.
154        InvalidHandle = CUDA_ERROR_INVALID_HANDLE,
155        /// This indicates that a resource required by the API call is not in a valid state to perform the requested operation.
156        IllegalState = CUDA_ERROR_ILLEGAL_STATE,
157        /// This indicates an attempt was made to introspect an object in a way that would discard semantically important information.
158        ///
159        /// This is either due to the object using functionality newer than the API version used to introspect it or omission of optional return arguments.
160        LossyQuery = CUDA_ERROR_LOSSY_QUERY,
161        /// This indicates that a named symbol was not found.
162        ///
163        /// Examples of symbols are global/constant variable names, driver function names, texture names, and surface names.
164        NotFound = CUDA_ERROR_NOT_FOUND,
165        /// This indicates that asynchronous operations issued previously have not completed yet.
166        ///
167        /// This result is not an error, but differs from [`Status::Success`], which indicates completion.
168        NotReady = CUDA_ERROR_NOT_READY,
169        /// While executing a kernel, the device encountered a load or store instruction on an invalid memory address.
170        ///
171        /// This leaves the process in an inconsistent state and any further CUDA work will return the same error.
172        /// To continue using CUDA, the process must be terminated and relaunched.
173        IllegalAddress = CUDA_ERROR_ILLEGAL_ADDRESS,
174        /// This indicates that a launch did not occur because it did not have appropriate resources.
175        ///
176        /// This error usually indicates that the user has attempted to pass too many arguments to the device kernel, or the kernel launch specifies too many threads for the kernel's register count.
177        /// Passing arguments of the wrong size, such as a 64-bit pointer where a 32-bit integer is expected, is equivalent to passing too many arguments and can also result in this error.
178        LaunchOutOfResources = CUDA_ERROR_LAUNCH_OUT_OF_RESOURCES,
179        /// This indicates that the device kernel took too long to execute.
180        ///
181        /// This can only occur if the device enables timeouts, as [`DeviceAttribute::KernelExecTimeout`](crate::device::DeviceAttribute::KernelExecTimeout) reports.
182        /// This leaves the process in an inconsistent state and any further CUDA work will return the same error.
183        /// To continue using CUDA, the process must be terminated and relaunched.
184        LaunchTimeout = CUDA_ERROR_LAUNCH_TIMEOUT,
185        /// This error indicates an attempt to enable peer access to a context that already has it enabled.
186        PeerAccessAlreadyEnabled = CUDA_ERROR_PEER_ACCESS_ALREADY_ENABLED,
187        /// This error indicates an attempt to disable peer access that has not been enabled.
188        PeerAccessNotEnabled = CUDA_ERROR_PEER_ACCESS_NOT_ENABLED,
189        /// This error indicates that the primary context for the specified device has already been initialized.
190        PrimaryContextActive = CUDA_ERROR_PRIMARY_CONTEXT_ACTIVE,
191        /// This error indicates that the context current to the calling thread has been destroyed, or is a primary context which has not yet been initialized.
192        ContextIsDestroyed = CUDA_ERROR_CONTEXT_IS_DESTROYED,
193        /// A device-side assert triggered during kernel execution.
194        ///
195        /// The context cannot be used anymore, and must be destroyed.
196        /// All existing device memory allocations from this context are invalid and must be reconstructed if the program is to continue using CUDA.
197        Assert = CUDA_ERROR_ASSERT,
198        /// This error indicates that the hardware resources required to enable peer access have been exhausted for one or more of the devices involved.
199        TooManyPeers = CUDA_ERROR_TOO_MANY_PEERS,
200        /// This error indicates that a host pointer being unregistered does not correspond to any currently registered memory region.
201        HostMemoryNotRegistered = CUDA_ERROR_HOST_MEMORY_NOT_REGISTERED,
202        /// While executing a kernel, the device encountered a stack error.
203        ///
204        /// This can be due to stack corruption or exceeding the stack size limit.
205        /// This leaves the process in an inconsistent state and any further CUDA work will return the same error.
206        /// To continue using CUDA, the process must be terminated and relaunched.
207        HardwareStackError = CUDA_ERROR_HARDWARE_STACK_ERROR,
208        /// While executing a kernel, the device encountered an illegal instruction.
209        ///
210        /// This leaves the process in an inconsistent state and any further CUDA work will return the same error.
211        /// To continue using CUDA, the process must be terminated and relaunched.
212        IllegalInstruction = CUDA_ERROR_ILLEGAL_INSTRUCTION,
213        /// While executing a kernel, the device encountered a load or store instruction on a memory address which is not aligned.
214        ///
215        /// This leaves the process in an inconsistent state and any further CUDA work will return the same error.
216        /// To continue using CUDA, the process must be terminated and relaunched.
217        MisalignedAddress = CUDA_ERROR_MISALIGNED_ADDRESS,
218        /// While executing a kernel, the device encountered an instruction which can only operate on memory locations in certain address spaces (global, shared, or local), but was supplied a memory address not belonging to an allowed address space.
219        ///
220        /// This leaves the process in an inconsistent state and any further CUDA work will return the same error.
221        /// To continue using CUDA, the process must be terminated and relaunched.
222        InvalidAddressSpace = CUDA_ERROR_INVALID_ADDRESS_SPACE,
223        /// While executing a kernel, the device program counter wrapped its address space.
224        ///
225        /// This leaves the process in an inconsistent state and any further CUDA work will return the same error.
226        /// To continue using CUDA, the process must be terminated and relaunched.
227        InvalidPc = CUDA_ERROR_INVALID_PC,
228        /// An exception occurred on the device while executing a kernel.
229        ///
230        /// Common causes include dereferencing an invalid device pointer and accessing out of bounds shared memory.
231        /// Less common cases can be system specific - more information about these cases can be found in the system specific user guide.
232        /// This leaves the process in an inconsistent state and any further CUDA work will return the same error.
233        /// To continue using CUDA, the process must be terminated and relaunched.
234        LaunchFailed = CUDA_ERROR_LAUNCH_FAILED,
235        /// This error indicates that a cooperative launch requested more blocks per grid than the kernel's maximum active blocks per multiprocessor times [`DeviceAttribute::MultiprocessorCount`](crate::device::DeviceAttribute::MultiprocessorCount).
236        CooperativeLaunchTooLarge = CUDA_ERROR_COOPERATIVE_LAUNCH_TOO_LARGE,
237        /// An exception occurred on the device while exiting a kernel using tensor memory: the tensor memory was not completely deallocated.
238        ///
239        /// This leaves the process in an inconsistent state and any further CUDA work will return the same error.
240        /// To continue using CUDA, the process must be terminated and relaunched.
241        TensorMemoryLeak = CUDA_ERROR_TENSOR_MEMORY_LEAK,
242        /// This error indicates that the attempted operation is not permitted.
243        NotPermitted = CUDA_ERROR_NOT_PERMITTED,
244        /// This error indicates that the attempted operation is not supported on the current system or device.
245        NotSupported = CUDA_ERROR_NOT_SUPPORTED,
246        /// This error indicates that the system is not yet ready to start any CUDA work.
247        ///
248        /// To continue using CUDA, verify the system configuration is in a valid state and all required driver daemons are actively running.
249        /// More information about this error can be found in the system specific user guide.
250        SystemNotReady = CUDA_ERROR_SYSTEM_NOT_READY,
251        /// This error indicates that there is a mismatch between the versions of the display driver and the CUDA driver.
252        ///
253        /// Refer to the compatibility documentation for supported versions.
254        SystemDriverMismatch = CUDA_ERROR_SYSTEM_DRIVER_MISMATCH,
255        /// This error indicates that the MPS client failed to connect to the MPS control daemon or the MPS server.
256        MpsConnectionFailed = CUDA_ERROR_MPS_CONNECTION_FAILED,
257        /// This error indicates that the remote procedural call between the MPS server and the MPS client failed.
258        MpsRpcFailure = CUDA_ERROR_MPS_RPC_FAILURE,
259        /// This error indicates that the MPS server is not ready to accept new MPS client requests.
260        ///
261        /// This error can be returned when the MPS server is in the process of recovering from a fatal failure.
262        MpsServerNotReady = CUDA_ERROR_MPS_SERVER_NOT_READY,
263        /// This error indicates that the hardware resources required to create MPS client have been exhausted.
264        MpsMaxClientsReached = CUDA_ERROR_MPS_MAX_CLIENTS_REACHED,
265        /// This error indicates the hardware resources required to support device connections have been exhausted.
266        MpsMaxConnectionsReached = CUDA_ERROR_MPS_MAX_CONNECTIONS_REACHED,
267        /// This error indicates that the MPS client has been terminated by the server.
268        ///
269        /// To continue using CUDA, the process must be terminated and relaunched.
270        MpsClientTerminated = CUDA_ERROR_MPS_CLIENT_TERMINATED,
271        /// This error indicates that the module is using CUDA Dynamic Parallelism, but the current configuration, like MPS, does not support it.
272        CdpNotSupported = CUDA_ERROR_CDP_NOT_SUPPORTED,
273        /// This error indicates that a module contains an unsupported interaction between different versions of CUDA Dynamic Parallelism.
274        CdpVersionMismatch = CUDA_ERROR_CDP_VERSION_MISMATCH,
275        /// This error indicates that the operation is not permitted when the stream is capturing.
276        StreamCaptureUnsupported = CUDA_ERROR_STREAM_CAPTURE_UNSUPPORTED,
277        /// This error indicates that the current capture sequence on the stream has been invalidated due to a previous error.
278        StreamCaptureInvalidated = CUDA_ERROR_STREAM_CAPTURE_INVALIDATED,
279        /// This error indicates that the operation would have resulted in a merge of two independent capture sequences.
280        StreamCaptureMerge = CUDA_ERROR_STREAM_CAPTURE_MERGE,
281        /// This error indicates that the capture was not initiated in this stream.
282        StreamCaptureUnmatched = CUDA_ERROR_STREAM_CAPTURE_UNMATCHED,
283        /// This error indicates that the capture sequence contains a fork that was not joined to the primary stream.
284        StreamCaptureUnjoined = CUDA_ERROR_STREAM_CAPTURE_UNJOINED,
285        /// This error indicates that a dependency would have been created which crosses the capture sequence boundary.
286        ///
287        /// Only implicit in-stream ordering dependencies are allowed to cross the boundary.
288        StreamCaptureIsolation = CUDA_ERROR_STREAM_CAPTURE_ISOLATION,
289        /// This error indicates a disallowed implicit dependency on a current capture sequence from the legacy default stream.
290        StreamCaptureImplicit = CUDA_ERROR_STREAM_CAPTURE_IMPLICIT,
291        /// This error indicates that the operation is not permitted on an event which was last recorded in a capturing stream.
292        CapturedEvent = CUDA_ERROR_CAPTURED_EVENT,
293        /// A stream capture that did not begin in [`StreamCaptureMode::Relaxed`](crate::stream::StreamCaptureMode::Relaxed) was ended from a different thread.
294        StreamCaptureWrongThread = CUDA_ERROR_STREAM_CAPTURE_WRONG_THREAD,
295        /// This error indicates that the timeout specified for the wait operation has lapsed.
296        Timeout = CUDA_ERROR_TIMEOUT,
297        /// This error indicates that the graph update was not performed because it included changes which violated constraints specific to instantiated graph update.
298        GraphExecUpdateFailure = CUDA_ERROR_GRAPH_EXEC_UPDATE_FAILURE,
299        /// This indicates that an error has occurred in a device outside of GPU.
300        ///
301        /// It can be a synchronous error with respect to CUDA API or an asynchronous error from the external device.
302        /// In case of asynchronous error, it means that if CUDA was waiting for an external device's signal before consuming shared data, the external device signaled an error indicating that the data is not valid for consumption.
303        /// This leaves the process in an inconsistent state and any further CUDA work will return the same error.
304        /// To continue using CUDA, the process must be terminated and relaunched.
305        /// In case of synchronous error, it means that one or more external devices have encountered an error and cannot complete the operation.
306        ExternalDevice = CUDA_ERROR_EXTERNAL_DEVICE,
307        /// Indicates a kernel launch error due to cluster misconfiguration.
308        InvalidClusterSize = CUDA_ERROR_INVALID_CLUSTER_SIZE,
309        /// Indicates a function handle is not loaded when calling an API that requires a loaded function.
310        FunctionNotLoaded = CUDA_ERROR_FUNCTION_NOT_LOADED,
311        /// This error indicates one or more resources passed in are not valid resource types for the operation.
312        InvalidResourceType = CUDA_ERROR_INVALID_RESOURCE_TYPE,
313        /// This error indicates that an error happened during the key rotation sequence.
314        KeyRotation = CUDA_ERROR_KEY_ROTATION,
315        /// This error indicates that the requested operation is not permitted because the stream is in a detached state.
316        ///
317        /// This can occur if the green context associated with the stream has been destroyed, limiting the stream's operational capabilities.
318        StreamDetached = CUDA_ERROR_STREAM_DETACHED,
319        /// The API call failed because of a hardware resource required to bind memory to a multicast object is unavailable.
320        MulticastResourceFull = CUDA_ERROR_MULTICAST_RESOURCE_FULL,
321        /// This indicates that the Loader version is insufficient for fatbin.
322        InsufficientLoaderVersion = CUDA_ERROR_INSUFFICIENT_LOADER_VERSION,
323        /// The GPU fabric is not ready within the bounded wait while the fabric manager probe is still in progress (or not converging in time).
324        ///
325        /// Applications may retry after a delay; environment variables such as `CUDA_FABRIC_INIT_TIMEOUT_MS` set the initialization wait budget.
326        FabricNotReady = CUDA_ERROR_FABRIC_NOT_READY,
327        /// This indicates that an unknown internal error has occurred.
328        UnknownError = CUDA_ERROR_UNKNOWN,
329    }
330}
331
332/// CUDA wrapper failures, including native status codes, compiler diagnostics, resource ownership, and submission tracking.
333#[derive(Error, Debug)]
334#[non_exhaustive]
335pub enum Error {
336    /// A library or symbol would not load.
337    #[error(transparent)]
338    Load(#[from] singe_cuda_sys::LoadError),
339
340    /// The requested GPU architecture cannot be represented or supported by this operation.
341    #[error("unsupported gpu architecture `{target}`")]
342    UnsupportedArchitecture {
343        /// Requested GPU architecture name.
344        target: String,
345    },
346
347    /// No embedded artifact with the requested name matches the target compute capability.
348    #[error(
349        "no compatible embedded artifact named `{name}` for compute capability {major}.{minor}"
350    )]
351    NoCompatibleArtifact {
352        /// Requested embedded artifact name.
353        name: Cow<'static, str>,
354        /// Target compute capability major component.
355        major: u32,
356        /// Target compute capability minor component.
357        minor: u32,
358    },
359
360    /// Embedded artifact selection, decoding, or loading failed.
361    #[error(transparent)]
362    Artifact(
363        /// Underlying artifact error.
364        #[from]
365        ArtifactError,
366    ),
367
368    /// A per-thread default stream cannot be retained as a stream shared across threads.
369    #[error("per-thread default streams cannot be retained as shared streams")]
370    ThreadLocalStreamUnsupported,
371
372    /// The foreign readiness stream and Singe stream refer to different native CUDA streams.
373    #[error("the singe and foreign readiness streams must refer to the same native stream")]
374    ForeignStreamMismatch,
375
376    /// The submitted native operation returned an error.
377    #[error("native operation failed")]
378    Operation(
379        /// Underlying native operation error.
380        #[source]
381        Box<dyn error::Error + Send + Sync>,
382    ),
383
384    /// An error was retained while waiting for submission completion.
385    #[error("submission completion failed")]
386    Completion(
387        /// Shared error retained by the submission completion state.
388        #[source]
389        Arc<Self>,
390    ),
391
392    /// The worker responsible for tracking CUDA completion stopped.
393    #[error("cuda completion worker stopped")]
394    CompletionWorkerStopped,
395
396    /// Destroying a retained submission resource panicked.
397    #[error("submission resource destruction panicked")]
398    ResourceDestructionPanicked,
399
400    /// Retiring completed submission state panicked.
401    #[error("completion retirement panicked")]
402    CompletionPanicked,
403
404    /// The device cannot provide the concurrent managed access required for managed host access.
405    #[error("managed host access requires concurrent managed access support")]
406    ManagedHostAccessUnsupported,
407
408    /// CUDA access was requested while the calling thread already held a host or enqueue access guard.
409    #[error("nested cuda access while a host or enqueue access guard is held")]
410    ReentrantAccess,
411
412    /// A lock was poisoned by an earlier panic.
413    #[error("`{name}` lock is poisoned")]
414    LockPoisoned {
415        /// Name of the locked resource.
416        name: Cow<'static, str>,
417    },
418
419    /// Kernel argument, launch, or memory-access validation failed.
420    #[error(transparent)]
421    LaunchContract(
422        /// Kernel launch contract violation.
423        #[from]
424        LaunchContractError,
425    ),
426
427    /// A compiler operation failed with a diagnostic message.
428    #[error("compiler error: {message}")]
429    Compiler {
430        /// Diagnostic text returned by the compiler integration.
431        message: String,
432    },
433
434    /// nvJitLink returned a failure status, with the linker's error log.
435    #[cfg(feature = "nvjitlink_13_4")]
436    #[error("nvjitlink error ({code}): {}{}", code.description(), log_suffix(diagnostic))]
437    NvJitLink {
438        /// Native device-linker status.
439        code: NvJitLinkStatus,
440        /// The linker's error log, empty when none was read.
441        diagnostic: String,
442    },
443
444    /// A CUDA driver or runtime call returned a failure status.
445    #[error("cuda error ({code}): {}", code.description())]
446    Cuda {
447        /// Native CUDA status.
448        code: Status,
449    },
450
451    /// An NVRTC call returned a failure status.
452    #[cfg(feature = "nvrtc_13_4")]
453    #[error("nvrtc error ({code}): {}", code.description())]
454    Nvrtc {
455        /// Native NVRTC status.
456        code: NvrtcStatus,
457    },
458
459    /// An NVVM call returned a failure status.
460    #[cfg(feature = "nvvm_13_4")]
461    #[error("nvvm error ({code}): {}", code.description())]
462    Nvvm {
463        /// Native NVVM status.
464        code: NvvmStatus,
465    },
466
467    /// A string intended for a native NUL-terminated interface contains an interior NUL byte.
468    #[error("string contains interior nul byte")]
469    InteriorNul,
470
471    /// An operating-system I/O operation failed.
472    #[error(transparent)]
473    Io(
474        /// Underlying I/O error.
475        #[from]
476        io::Error,
477    ),
478
479    /// The requested CUDA device could not be found.
480    #[error("device not found")]
481    DeviceNotFound,
482
483    /// A pinned host allocation needs an alignment above 4096 bytes, or CUDA returned a chunk that is not page-aligned.
484    #[error("pinned host memory cannot align to {align} bytes")]
485    UnsupportedPinnedAlignment {
486        /// Alignment in bytes that the pool cannot give.
487        align: usize,
488    },
489
490    /// An owner cannot be consumed or released while other owners share it.
491    #[error("`{name}` is still shared")]
492    OwnershipShared {
493        /// Name of the shared owner.
494        name: Cow<'static, str>,
495    },
496
497    /// The memory allocation belongs to another CUDA context.
498    #[error("memory belongs to a different cuda context")]
499    MemoryContextMismatch,
500
501    /// A native call returned a null handle where a live resource was required.
502    #[error("unexpected null handle")]
503    NullHandle,
504
505    /// A pointer argument or native result is null where a valid address is required.
506    #[error("`{name}` is null")]
507    NullPointer {
508        /// Name of the pointer.
509        name: Cow<'static, str>,
510    },
511
512    /// A value must be greater than zero.
513    #[error("`{name}` must be positive")]
514    NotPositive {
515        /// Name of the value.
516        name: Cow<'static, str>,
517    },
518
519    /// A value or collection is empty where content is required.
520    #[error("`{name}` is empty")]
521    Empty {
522        /// Name of the value.
523        name: Cow<'static, str>,
524    },
525
526    /// A native enum value has no typed variant in this crate.
527    #[error("unknown `{name}` value {value}")]
528    UnknownEnumValue {
529        /// Name of the typed enum.
530        name: Cow<'static, str>,
531        /// Unrecognized native value.
532        value: i64,
533    },
534
535    /// A named argument or computed extent exceeds the supported range.
536    #[error("`{name}` is out of range")]
537    OutOfRange {
538        /// Name of the argument or computed extent that exceeded its range.
539        name: Cow<'static, str>,
540    },
541
542    /// Two lengths that must be equal differ.
543    #[error("`{name}` length mismatch (expected {expected}, got {actual})")]
544    LengthMismatch {
545        /// Name of the value whose length is checked.
546        name: Cow<'static, str>,
547        /// Required length.
548        expected: usize,
549        /// Supplied length.
550        actual: usize,
551    },
552
553    /// A buffer cannot hold what the operation reads from or writes to it.
554    #[error("`{name}` is too small (requires {required}, got {actual})")]
555    BufferTooSmall {
556        /// Name of the buffer.
557        name: Cow<'static, str>,
558        /// Required length.
559        required: usize,
560        /// Supplied length.
561        actual: usize,
562    },
563
564    /// Two byte sizes that must be equal differ.
565    #[error("`{name}` size mismatch (expected {expected} bytes, got {actual})")]
566    SizeMismatch {
567        /// Name of the value whose size is checked.
568        name: Cow<'static, str>,
569        /// Required size in bytes.
570        expected: usize,
571        /// Supplied size in bytes.
572        actual: usize,
573    },
574
575    /// An address, offset, or size is not a multiple of the required alignment.
576    #[error("`{name}` is not aligned to {alignment} bytes")]
577    Misaligned {
578        /// Name of the address, offset, or size.
579        name: Cow<'static, str>,
580        /// Required alignment in bytes.
581        alignment: usize,
582    },
583
584    /// Graph dependency relationships do not match the required graph state.
585    #[error("graph dependency mismatch")]
586    GraphDependencyMismatch,
587
588    /// A graph node belongs to a different graph.
589    #[error("graph node belongs to a different graph")]
590    GraphNodeMismatch,
591
592    /// A CUDA object other than memory or a stream belongs to a different CUDA context.
593    #[error("`{name}` belongs to a different cuda context")]
594    ContextMismatch {
595        /// Name of the object.
596        name: Cow<'static, str>,
597    },
598
599    /// The stream belongs to a different CUDA context.
600    #[error("stream belongs to a different cuda context")]
601    StreamContextMismatch,
602
603    /// A checkpoint region was copied against its operation's direction: to the host during a restore, or from the host during a checkpoint.
604    #[error("checkpoint region of a {operation} cannot be copied in this direction")]
605    CheckpointDirectionMismatch {
606        /// The region's operation, `checkpoint` or `restore`.
607        operation: &'static str,
608    },
609}
610
611/// Result of a CUDA wrapper operation, using the crate's typed `Error`.
612pub type Result<T> = StdResult<T, Error>;
613
614impl Error {
615    pub(crate) fn out_of_range(name: impl Into<Cow<'static, str>>) -> Self {
616        Self::OutOfRange { name: name.into() }
617    }
618
619    pub(crate) fn null_pointer(name: impl Into<Cow<'static, str>>) -> Self {
620        Self::NullPointer { name: name.into() }
621    }
622
623    pub(crate) fn not_positive(name: impl Into<Cow<'static, str>>) -> Self {
624        Self::NotPositive { name: name.into() }
625    }
626
627    pub(crate) fn empty(name: impl Into<Cow<'static, str>>) -> Self {
628        Self::Empty { name: name.into() }
629    }
630
631    pub(crate) fn lock_poisoned(name: impl Into<Cow<'static, str>>) -> Self {
632        Self::LockPoisoned { name: name.into() }
633    }
634
635    pub(crate) fn ownership_shared(name: impl Into<Cow<'static, str>>) -> Self {
636        Self::OwnershipShared { name: name.into() }
637    }
638
639    pub(crate) fn context_mismatch(name: impl Into<Cow<'static, str>>) -> Self {
640        Self::ContextMismatch { name: name.into() }
641    }
642
643    pub(crate) fn length_mismatch(
644        name: impl Into<Cow<'static, str>>,
645        expected: usize,
646        actual: usize,
647    ) -> Self {
648        Self::LengthMismatch {
649            name: name.into(),
650            expected,
651            actual,
652        }
653    }
654
655    pub(crate) fn buffer_too_small(
656        name: impl Into<Cow<'static, str>>,
657        required: usize,
658        actual: usize,
659    ) -> Self {
660        Self::BufferTooSmall {
661            name: name.into(),
662            required,
663            actual,
664        }
665    }
666
667    pub(crate) fn size_mismatch(
668        name: impl Into<Cow<'static, str>>,
669        expected: usize,
670        actual: usize,
671    ) -> Self {
672        Self::SizeMismatch {
673            name: name.into(),
674            expected,
675            actual,
676        }
677    }
678
679    pub(crate) fn misaligned(name: impl Into<Cow<'static, str>>, alignment: usize) -> Self {
680        Self::Misaligned {
681            name: name.into(),
682            alignment,
683        }
684    }
685}
686
687#[cfg(feature = "nvjitlink_13_4")]
688fn log_suffix(log: &str) -> String {
689    if log.is_empty() {
690        String::new()
691    } else {
692        format!(": {log}")
693    }
694}
695
696impl From<singe_core::UnknownEnumValue> for Error {
697    fn from(error: singe_core::UnknownEnumValue) -> Self {
698        Self::UnknownEnumValue {
699            name: error.name.into(),
700            value: error.value,
701        }
702    }
703}
704
705impl From<NulError> for Error {
706    fn from(_: NulError) -> Self {
707        Self::InteriorNul
708    }
709}
710
711// Converts a raw CUDA status into this crate's `Result`.
712macro_rules! try_ffi {
713    ($expr:expr) => {
714        $crate::error::Error::check($expr)
715    };
716}
717
718pub(crate) use try_ffi;
719
720// Converts a raw NVRTC status into this crate's `Result`.
721#[cfg(feature = "nvrtc_13_4")]
722macro_rules! try_nvrtc {
723    ($expr:expr) => {
724        $crate::error::Error::check_nvrtc($expr)
725    };
726}
727
728#[cfg(feature = "nvrtc_13_4")]
729pub(crate) use try_nvrtc;
730
731// Converts a raw NVVM status into this crate's `Result`.
732#[cfg(feature = "nvvm_13_4")]
733macro_rules! try_nvvm {
734    ($expr:expr) => {
735        $crate::error::Error::check_nvvm($expr)
736    };
737}
738
739#[cfg(feature = "nvvm_13_4")]
740pub(crate) use try_nvvm;