Skip to main content

singe_cuda_sys/
lib.rs

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