Skip to main content

singe_cuda_sys/
lib.rs

1//! Low-level FFI bindings for the CUDA driver and runtime APIs, NVRTC, nvJitLink, NVVM, NVTX 3, and the shared CUDA library types, generated with bindgen from their headers.
2//! Each API has its own module: [`driver`], [`runtime`], [`nvrtc`], [`nvjitlink`], [`nvvm`], [`nvtx`], [`profiler`], and [`library_types`].
3//! Every library loads at run time through [`singe-loader`](singe_loader), on the first call of one of its functions or up front with [`load_driver`] and the other `load_*` functions, so nothing links at build time.
4//! Most users want the safe crate, `singe-cuda`.
5#![allow(
6    deprecated,
7    non_camel_case_types,
8    non_snake_case,
9    unnecessary_transmutes,
10    unused_imports,
11    unused_qualifications,
12    non_upper_case_globals,
13    unsafe_op_in_unsafe_fn,
14    unpredictable_function_pointer_comparisons,
15    missing_debug_implementations,
16    unnameable_types,
17    unreachable_pub,
18    clippy::correctness,
19    clippy::suspicious,
20    clippy::complexity,
21    clippy::perf,
22    clippy::style,
23    clippy::absolute_paths,
24    clippy::pedantic,
25    clippy::nursery,
26    clippy::undocumented_unsafe_blocks,
27    reason = "generated bindings preserve upstream ABI conventions and documentation"
28)]
29
30#[cfg(not(any(
31    feature = "driver_13_4",
32    feature = "runtime_13_4",
33    feature = "nvrtc_13_4",
34    feature = "nvvm_13_4",
35    feature = "nvtx_3",
36    feature = "nvjitlink_13_4"
37)))]
38compile_error!("singe-cuda-sys requires a version feature, such as `driver_13_4`");
39
40#[cfg(feature = "driver")]
41/// CUDA Driver API declarations for contexts, memory, kernels, and graphs.
42pub mod driver {
43
44    #[cfg(feature = "driver_13_4")]
45    include!("driver_sys_13040.rs");
46
47    #[cfg(feature = "driver_13_4")]
48    pub use self::{
49        cuArray3DCreate_v2 as cuArray3DCreate, cuArray3DGetDescriptor_v2 as cuArray3DGetDescriptor,
50        cuArrayCreate_v2 as cuArrayCreate, cuArrayGetDescriptor_v2 as cuArrayGetDescriptor,
51        cuCtxCreate_v4 as cuCtxCreate, cuCtxDestroy_v2 as cuCtxDestroy,
52        cuCtxPopCurrent_v2 as cuCtxPopCurrent, cuCtxPushCurrent_v2 as cuCtxPushCurrent,
53        cuDeviceGetUuid_v2 as cuDeviceGetUuid,
54        cuDevicePrimaryCtxRelease_v2 as cuDevicePrimaryCtxRelease,
55        cuDevicePrimaryCtxReset_v2 as cuDevicePrimaryCtxReset,
56        cuDevicePrimaryCtxSetFlags_v2 as cuDevicePrimaryCtxSetFlags,
57        cuDeviceTotalMem_v2 as cuDeviceTotalMem, cuEventDestroy_v2 as cuEventDestroy,
58        cuEventElapsedTime_v2 as cuEventElapsedTime, cuGetProcAddress_v2 as cuGetProcAddress,
59        cuGraphAddDependencies_v2 as cuGraphAddDependencies,
60        cuGraphAddKernelNode_v2 as cuGraphAddKernelNode, cuGraphAddNode_v2 as cuGraphAddNode,
61        cuGraphExecKernelNodeSetParams_v2 as cuGraphExecKernelNodeSetParams,
62        cuGraphExecUpdate_v2 as cuGraphExecUpdate, cuGraphGetEdges_v2 as cuGraphGetEdges,
63        cuGraphKernelNodeGetParams_v2 as cuGraphKernelNodeGetParams,
64        cuGraphKernelNodeSetParams_v2 as cuGraphKernelNodeSetParams,
65        cuGraphNodeGetDependencies_v2 as cuGraphNodeGetDependencies,
66        cuGraphNodeGetDependentNodes_v2 as cuGraphNodeGetDependentNodes,
67        cuGraphRemoveDependencies_v2 as cuGraphRemoveDependencies,
68        cuGraphicsResourceGetMappedPointer_v2 as cuGraphicsResourceGetMappedPointer,
69        cuGraphicsResourceSetMapFlags_v2 as cuGraphicsResourceSetMapFlags,
70        cuIpcOpenMemHandle_v2 as cuIpcOpenMemHandle, cuLinkAddData_v2 as cuLinkAddData,
71        cuLinkAddFile_v2 as cuLinkAddFile, cuLinkCreate_v2 as cuLinkCreate,
72        cuMemAdvise_v2 as cuMemAdvise, cuMemAlloc_v2 as cuMemAlloc,
73        cuMemAllocHost_v2 as cuMemAllocHost, cuMemAllocPitch_v2 as cuMemAllocPitch,
74        cuMemFree_v2 as cuMemFree, cuMemGetAddressRange_v2 as cuMemGetAddressRange,
75        cuMemGetInfo_v2 as cuMemGetInfo, cuMemHostGetDevicePointer_v2 as cuMemHostGetDevicePointer,
76        cuMemHostRegister_v2 as cuMemHostRegister, cuMemPrefetchAsync_v2 as cuMemPrefetchAsync,
77        cuMemcpy2D_v2 as cuMemcpy2D, cuMemcpy2DAsync_v2 as cuMemcpy2DAsync,
78        cuMemcpy2DUnaligned_v2 as cuMemcpy2DUnaligned, cuMemcpy3D_v2 as cuMemcpy3D,
79        cuMemcpy3DAsync_v2 as cuMemcpy3DAsync, cuMemcpy3DBatchAsync_v2 as cuMemcpy3DBatchAsync,
80        cuMemcpyAtoA_v2 as cuMemcpyAtoA, cuMemcpyAtoD_v2 as cuMemcpyAtoD,
81        cuMemcpyAtoH_v2 as cuMemcpyAtoH, cuMemcpyAtoHAsync_v2 as cuMemcpyAtoHAsync,
82        cuMemcpyBatchAsync_v2 as cuMemcpyBatchAsync, cuMemcpyDtoA_v2 as cuMemcpyDtoA,
83        cuMemcpyDtoD_v2 as cuMemcpyDtoD, cuMemcpyDtoDAsync_v2 as cuMemcpyDtoDAsync,
84        cuMemcpyDtoH_v2 as cuMemcpyDtoH, cuMemcpyDtoHAsync_v2 as cuMemcpyDtoHAsync,
85        cuMemcpyHtoA_v2 as cuMemcpyHtoA, cuMemcpyHtoAAsync_v2 as cuMemcpyHtoAAsync,
86        cuMemcpyHtoD_v2 as cuMemcpyHtoD, cuMemcpyHtoDAsync_v2 as cuMemcpyHtoDAsync,
87        cuMemsetD2D8_v2 as cuMemsetD2D8, cuMemsetD2D16_v2 as cuMemsetD2D16,
88        cuMemsetD2D32_v2 as cuMemsetD2D32, cuMemsetD8_v2 as cuMemsetD8,
89        cuMemsetD16_v2 as cuMemsetD16, cuMemsetD32_v2 as cuMemsetD32,
90        cuModuleGetGlobal_v2 as cuModuleGetGlobal, cuStreamBatchMemOp_v2 as cuStreamBatchMemOp,
91        cuStreamBeginCapture_v2 as cuStreamBeginCapture, cuStreamDestroy_v2 as cuStreamDestroy,
92        cuStreamGetCaptureInfo_v3 as cuStreamGetCaptureInfo,
93        cuStreamUpdateCaptureDependencies_v2 as cuStreamUpdateCaptureDependencies,
94        cuStreamWaitValue32_v2 as cuStreamWaitValue32,
95        cuStreamWaitValue64_v2 as cuStreamWaitValue64,
96        cuStreamWriteValue32_v2 as cuStreamWriteValue32,
97        cuStreamWriteValue64_v2 as cuStreamWriteValue64,
98        cuTexRefSetAddress2D_v3 as cuTexRefSetAddress2D,
99    };
100}
101
102#[cfg(feature = "driver")]
103/// CUDA profiler start and stop declarations.
104pub mod profiler {
105    #[cfg(feature = "driver_13_4")]
106    include!("profiler_sys_13040.rs");
107}
108
109/// Scalar data types and library property enums shared by NVIDIA libraries.
110pub mod library_types {
111
112    #[cfg(feature = "runtime_13_4")]
113    include!("library_types_sys_13040.rs");
114}
115
116/// CUDA runtime linking library.
117#[cfg(feature = "nvjitlink_13_4")]
118pub mod nvjitlink {
119    include!("nvjitlink_sys_13040.rs");
120}
121
122#[cfg(feature = "nvrtc")]
123/// NVRTC runtime compilation declarations.
124pub mod nvrtc {
125
126    #[cfg(feature = "nvrtc_13_4")]
127    include!("nvrtc_sys_13040.rs");
128}
129
130#[cfg(feature = "nvvm")]
131/// NVVM IR compilation and version-query declarations.
132pub mod nvvm {
133
134    #[cfg(feature = "nvvm_13_4")]
135    include!("nvvm_sys_13040.rs");
136}
137
138#[cfg(feature = "nvtx")]
139/// NVTX event annotation declarations.
140pub mod nvtx {
141
142    #[cfg(feature = "nvtx_3")]
143    include!("nvtx_sys_3.rs");
144}
145
146#[cfg(feature = "runtime")]
147/// CUDA Runtime API declarations and driver-compatible handle aliases.
148pub mod runtime {
149
150    // These types have type definitions in `driver_types.h`.
151    #[cfg(feature = "driver_13_4")]
152    #[rustfmt::skip]
153    pub use crate::driver::{
154        // --- Core handles & pointers ---
155        cudaError_enum as cudaError_t,
156        CUevent as cudaEvent_t,
157        CUfunction as cudaFunction_t,
158        CUstream as cudaStream_t,
159        CUuuid as cudaUUID_t,
160        CUuserObject as cudaUserObject_t,
161
162        // --- Array & memory Types ---
163        CUarray as cudaArray_t,
164        CUmipmappedArray as cudaMipmappedArray_t,
165        CUmemoryPool as cudaMemPool_t,
166
167        // --- Texture & surface types ---
168        CUgraphicsResource as cudaGraphicsResource_t,
169
170        // --- Memory/semaphore types ---
171        CUexternalMemory as cudaExternalMemory_t,
172        CUexternalSemaphore as cudaExternalSemaphore_t,
173
174        // --- Graph types ---
175        CUgraph as cudaGraph_t,
176        CUgraphNode as cudaGraphNode_t,
177        CUgraphExec as cudaGraphExec_t,
178
179        CUkernel as cudaKernel_t,
180        CUlibrary as cudaLibrary_t,
181        CUgraphConditionalHandle as cudaGraphConditionalHandle,
182        CUasyncCallbackHandle as cudaAsyncCallbackHandle_t,
183    };
184
185    // These types are defined both in `driver_types.h` and `cuda.h` and might not be interchangeable.
186    // Types of different layouts should not be imported here.
187    #[cfg(feature = "driver_13_4")]
188    #[rustfmt::skip]
189    pub use crate::driver::{
190        // --- Core Handles & Pointers ---
191        CUflushGPUDirectRDMAWritesScope as cudaFlushGPUDirectRDMAWritesScope,
192        CUflushGPUDirectRDMAWritesTarget as cudaFlushGPUDirectRDMAWritesTarget,
193
194        // --- Array & memory Types ---
195        CUDA_MEMSET_NODE_PARAMS as cudaMemsetParams,
196        CUDA_HOST_NODE_PARAMS as cudaHostNodeParams,
197        CUDA_EXT_SEM_SIGNAL_NODE_PARAMS as cudaExternalSemaphoreSignalNodeParams,
198        CUDA_EXT_SEM_WAIT_NODE_PARAMS as cudaExternalSemaphoreWaitNodeParams,
199        CUDA_MEM_ALLOC_NODE_PARAMS as cudaMemAllocNodeParams,
200        CUDA_ARRAY_MEMORY_REQUIREMENTS as cudaArrayMemoryRequirements,
201        CUDA_ARRAY_SPARSE_PROPERTIES as cudaArraySparseProperties,
202        CUDA_MEMCPY3D_BATCH_OP as cudaMemcpy3DBatchOp,
203
204        CUmemcpyAttributes as cudaMemcpyAttributes,
205        CUmemPoolProps as cudaMemPoolProps,
206        CUmemPoolPtrExportData as cudaMemPoolPtrExportData,
207        CUmemAllocationHandleType as cudaMemAllocationHandleType,
208        CUmemPool_attribute as cudaMemPoolAttr,
209        CUsharedconfig as cudaSharedMemConfig,
210        CUmemLocation as cudaMemLocation,
211        CUmemAccessDesc as cudaMemAccessDesc,
212        CUmem_range_attribute as cudaMemRangeAttribute,
213        CUmem_advise as cudaMemoryAdvise,
214        CUmemAccess_flags as cudaMemAccessFlags,
215
216        // --- IPC Types ---
217        CUipcEventHandle as cudaIpcEventHandle_t,
218        CUipcMemHandle as cudaIpcMemHandle_t,
219
220        // --- Graph Types ---
221        CUgraphExecUpdateResult as cudaGraphExecUpdateResult,
222        CUgraphMem_attribute as cudaGraphMemAttributeType,
223        CUgraphNodeType as cudaGraphNodeType,
224        CUgraphEdgeData as cudaGraphEdgeData,
225
226        CUgraphNodeParams as cudaGraphNodeParams,
227        CUgraphExecUpdateResultInfo as cudaGraphExecUpdateResultInfo,
228        CUDA_GRAPH_INSTANTIATE_PARAMS as cudaGraphInstantiateParams,
229
230        // --- Function Pointer Types ---
231        CUhostFn as cudaHostFn_t,
232        CUasyncCallback as cudaAsyncCallback,
233
234        // --- Enums ---
235        CUdevice_attribute as cudaDeviceAttr,
236        CUfunction_attribute as cudaFuncAttribute,
237        CUjit_option as cudaJitOption,
238        CUdevice_P2PAttribute as cudaDeviceP2PAttr,
239        CUlibraryOption as cudaLibraryOption,
240        CUdriverProcAddressQueryResult as cudaDriverEntryPointQueryResult,
241
242        // --- Other types ---
243        CUfunc_cache as cudaFuncCache,
244        CUstreamCaptureMode as cudaStreamCaptureMode,
245        CUstreamCaptureStatus as cudaStreamCaptureStatus,
246        // CUextent3D as cudaExtent,
247    };
248
249    /// Pointer to a CUDA array handle in this runtime binding.
250    pub type cudaArray_const_t = *const crate::driver::CUarray;
251
252    /// Pointer to an immutable native CUDA mipmapped-array object.
253    pub type cudaMipmappedArray_const_t = *const crate::driver::CUmipmappedArray_st;
254
255    /// Stream capture status used by graph recapture operations.
256    pub type cudaGraphRecaptureStatus = cudaStreamCaptureStatus;
257
258    #[cfg(feature = "runtime_13_4")]
259    include!("driver_types_sys_13040.rs");
260
261    #[cfg(feature = "runtime_13_4")]
262    include!("runtime_sys_13040.rs");
263}
264
265pub use singe_loader::{Absence, LoadError, take_absence};
266
267static DRIVER: singe_loader::Library = singe_loader::Library::cuda_driver();
268
269/// Loads the CUDA driver now, instead of on the first call of one of its functions.
270///
271/// # Errors
272///
273/// Returns an error if the library has no files on this platform or one of its files would not load.
274pub fn load_driver() -> Result<(), LoadError> {
275    DRIVER.load()
276}
277
278static RUNTIME: singe_loader::Library = singe_loader::Library::cuda_runtime();
279
280/// Loads the CUDA runtime now, instead of on the first call of one of its functions.
281///
282/// # Errors
283///
284/// Returns an error if the library has no files on this platform or one of its files would not load.
285pub fn load_runtime() -> Result<(), LoadError> {
286    RUNTIME.load()
287}
288
289static NVRTC: singe_loader::Library = singe_loader::Library::nvrtc();
290
291/// Loads NVRTC now, instead of on the first call of one of its functions.
292///
293/// # Errors
294///
295/// Returns an error if the library has no files on this platform or one of its files would not load.
296pub fn load_nvrtc() -> Result<(), LoadError> {
297    NVRTC.load()
298}
299
300/// Returns the path of each NVRTC file, loading NVRTC first if it is not loaded yet.
301///
302/// # Errors
303///
304/// Returns an error if the library has no files on this platform or one of its files would not load.
305pub fn nvrtc_paths() -> Result<Vec<std::path::PathBuf>, LoadError> {
306    NVRTC.paths()
307}
308
309static NVJITLINK: singe_loader::Library = singe_loader::Library::nvjitlink();
310
311/// Loads nvJitLink now, instead of on the first call of one of its functions.
312///
313/// # Errors
314///
315/// Returns an error if the library has no files on this platform or one of its files would not load.
316pub fn load_nvjitlink() -> Result<(), LoadError> {
317    NVJITLINK.load()
318}
319
320static NVVM: singe_loader::Library = singe_loader::Library::nvvm();
321
322/// Loads NVVM now, instead of on the first call of one of its functions.
323///
324/// # Errors
325///
326/// Returns an error if the library has no files on this platform or one of its files would not load.
327pub fn load_nvvm() -> Result<(), LoadError> {
328    NVVM.load()
329}
330
331static NVTX: singe_loader::Library = singe_loader::Library::nvtx();
332
333/// Loads NVTX now, instead of on the first call of one of its functions.
334///
335/// # Errors
336///
337/// Returns an error if the library has no files on this platform or one of its files would not load.
338pub fn load_nvtx() -> Result<(), LoadError> {
339    NVTX.load()
340}
341
342#[cfg(feature = "driver_13_4")]
343singe_loader::missing_status!(
344    driver::CUresult,
345    library: driver::CUresult::CUDA_ERROR_SHARED_OBJECT_INIT_FAILED,
346    symbol: driver::CUresult::CUDA_ERROR_SHARED_OBJECT_SYMBOL_NOT_FOUND,
347);
348
349#[cfg(feature = "runtime_13_4")]
350impl singe_loader::Missing for runtime::cudaChannelFormatDesc {
351    fn missing(_: singe_loader::Absence) -> Self {
352        Self {
353            x: 0,
354            y: 0,
355            z: 0,
356            w: 0,
357            f: runtime::cudaChannelFormatKind::cudaChannelFormatKindSigned,
358        }
359    }
360}
361
362#[cfg(feature = "nvrtc_13_4")]
363singe_loader::missing_status!(
364    nvrtc::nvrtcResult,
365    library: nvrtc::nvrtcResult::NVRTC_ERROR_INTERNAL_ERROR,
366    symbol: nvrtc::nvrtcResult::NVRTC_ERROR_INTERNAL_ERROR,
367);
368
369#[cfg(feature = "nvjitlink_13_4")]
370singe_loader::missing_status!(
371    nvjitlink::nvJitLinkResult,
372    library: nvjitlink::nvJitLinkResult::NVJITLINK_ERROR_INTERNAL,
373    symbol: nvjitlink::nvJitLinkResult::NVJITLINK_ERROR_OUTDATED_LIBRARY,
374);
375
376#[cfg(feature = "nvvm_13_4")]
377singe_loader::missing_status!(
378    nvvm::nvvmResult,
379    library: nvvm::nvvmResult::NVVM_ERROR_PROGRAM_CREATION_FAILURE,
380    symbol: nvvm::nvvmResult::NVVM_ERROR_PROGRAM_CREATION_FAILURE,
381);
382
383#[cfg(test)]
384mod tests {
385    use super::*;
386
387    #[test]
388    fn test_it_works() {
389        #[cfg(feature = "driver")]
390        {
391            let mut version = 0;
392            // SAFETY: the version query writes only into the local output locations.
393            unsafe {
394                driver::cuDriverGetVersion(&mut version);
395            }
396            assert_ne!(version, 0);
397            println!("CUDA driver version: {}", version);
398        }
399
400        #[cfg(feature = "runtime")]
401        {
402            let mut version = 0;
403            // SAFETY: the version query writes only into the local output locations.
404            unsafe {
405                runtime::cudaRuntimeGetVersion(&mut version);
406            }
407            assert_ne!(version, 0);
408            println!("CUDA runtime version: {}", version);
409        }
410
411        #[cfg(feature = "nvrtc")]
412        {
413            let mut major = 0;
414            let mut minor = 0;
415            // SAFETY: the version query writes only into the local output locations.
416            unsafe {
417                nvrtc::nvrtcVersion(&mut major, &mut minor);
418            }
419            assert_ne!(major, 0);
420            println!("NVRTC version: {}.{}", major, minor);
421        }
422
423        #[cfg(feature = "nvtx")]
424        {
425            assert_eq!(nvtx::NVTX_VERSION, 3);
426            println!("NVTX version: {}", nvtx::NVTX_VERSION);
427        }
428    }
429}