singe-cuda-sys 0.1.0

Low-level FFI bindings for the CUDA driver and runtime APIs and the CUDA libraries that ship with them, such as NVRTC.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
//! 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.
//! Each API has its own module: [`driver`], [`runtime`], [`nvrtc`], [`nvjitlink`], [`nvvm`], [`nvtx`], [`profiler`], and [`library_types`].
//! 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.
//! Most users want the safe crate, `singe-cuda`.
#![allow(
    deprecated,
    non_camel_case_types,
    non_snake_case,
    unnecessary_transmutes,
    unused_imports,
    unused_qualifications,
    non_upper_case_globals,
    unsafe_op_in_unsafe_fn,
    unpredictable_function_pointer_comparisons,
    missing_debug_implementations,
    unnameable_types,
    unreachable_pub,
    clippy::correctness,
    clippy::suspicious,
    clippy::complexity,
    clippy::perf,
    clippy::style,
    clippy::absolute_paths,
    clippy::pedantic,
    clippy::nursery,
    clippy::undocumented_unsafe_blocks,
    reason = "generated bindings preserve upstream ABI conventions and documentation"
)]

#[cfg(not(any(
    feature = "driver_13_4",
    feature = "runtime_13_4",
    feature = "nvrtc_13_4",
    feature = "nvvm_13_4",
    feature = "nvtx_3",
    feature = "nvjitlink_13_4"
)))]
compile_error!("singe-cuda-sys requires a version feature, such as `driver_13_4`");

#[cfg(feature = "driver")]
/// CUDA Driver API declarations for contexts, memory, kernels, and graphs.
pub mod driver {

    #[cfg(feature = "driver_13_4")]
    include!("driver_sys_13040.rs");

    #[cfg(feature = "driver_13_4")]
    pub use self::{
        cuArray3DCreate_v2 as cuArray3DCreate, cuArray3DGetDescriptor_v2 as cuArray3DGetDescriptor,
        cuArrayCreate_v2 as cuArrayCreate, cuArrayGetDescriptor_v2 as cuArrayGetDescriptor,
        cuCtxCreate_v4 as cuCtxCreate, cuCtxDestroy_v2 as cuCtxDestroy,
        cuCtxPopCurrent_v2 as cuCtxPopCurrent, cuCtxPushCurrent_v2 as cuCtxPushCurrent,
        cuDeviceGetUuid_v2 as cuDeviceGetUuid,
        cuDevicePrimaryCtxRelease_v2 as cuDevicePrimaryCtxRelease,
        cuDevicePrimaryCtxReset_v2 as cuDevicePrimaryCtxReset,
        cuDevicePrimaryCtxSetFlags_v2 as cuDevicePrimaryCtxSetFlags,
        cuDeviceTotalMem_v2 as cuDeviceTotalMem, cuEventDestroy_v2 as cuEventDestroy,
        cuEventElapsedTime_v2 as cuEventElapsedTime, cuGetProcAddress_v2 as cuGetProcAddress,
        cuGraphAddDependencies_v2 as cuGraphAddDependencies,
        cuGraphAddKernelNode_v2 as cuGraphAddKernelNode, cuGraphAddNode_v2 as cuGraphAddNode,
        cuGraphExecKernelNodeSetParams_v2 as cuGraphExecKernelNodeSetParams,
        cuGraphExecUpdate_v2 as cuGraphExecUpdate, cuGraphGetEdges_v2 as cuGraphGetEdges,
        cuGraphKernelNodeGetParams_v2 as cuGraphKernelNodeGetParams,
        cuGraphKernelNodeSetParams_v2 as cuGraphKernelNodeSetParams,
        cuGraphNodeGetDependencies_v2 as cuGraphNodeGetDependencies,
        cuGraphNodeGetDependentNodes_v2 as cuGraphNodeGetDependentNodes,
        cuGraphRemoveDependencies_v2 as cuGraphRemoveDependencies,
        cuGraphicsResourceGetMappedPointer_v2 as cuGraphicsResourceGetMappedPointer,
        cuGraphicsResourceSetMapFlags_v2 as cuGraphicsResourceSetMapFlags,
        cuIpcOpenMemHandle_v2 as cuIpcOpenMemHandle, cuLinkAddData_v2 as cuLinkAddData,
        cuLinkAddFile_v2 as cuLinkAddFile, cuLinkCreate_v2 as cuLinkCreate,
        cuMemAdvise_v2 as cuMemAdvise, cuMemAlloc_v2 as cuMemAlloc,
        cuMemAllocHost_v2 as cuMemAllocHost, cuMemAllocPitch_v2 as cuMemAllocPitch,
        cuMemFree_v2 as cuMemFree, cuMemGetAddressRange_v2 as cuMemGetAddressRange,
        cuMemGetInfo_v2 as cuMemGetInfo, cuMemHostGetDevicePointer_v2 as cuMemHostGetDevicePointer,
        cuMemHostRegister_v2 as cuMemHostRegister, cuMemPrefetchAsync_v2 as cuMemPrefetchAsync,
        cuMemcpy2D_v2 as cuMemcpy2D, cuMemcpy2DAsync_v2 as cuMemcpy2DAsync,
        cuMemcpy2DUnaligned_v2 as cuMemcpy2DUnaligned, cuMemcpy3D_v2 as cuMemcpy3D,
        cuMemcpy3DAsync_v2 as cuMemcpy3DAsync, cuMemcpy3DBatchAsync_v2 as cuMemcpy3DBatchAsync,
        cuMemcpyAtoA_v2 as cuMemcpyAtoA, cuMemcpyAtoD_v2 as cuMemcpyAtoD,
        cuMemcpyAtoH_v2 as cuMemcpyAtoH, cuMemcpyAtoHAsync_v2 as cuMemcpyAtoHAsync,
        cuMemcpyBatchAsync_v2 as cuMemcpyBatchAsync, cuMemcpyDtoA_v2 as cuMemcpyDtoA,
        cuMemcpyDtoD_v2 as cuMemcpyDtoD, cuMemcpyDtoDAsync_v2 as cuMemcpyDtoDAsync,
        cuMemcpyDtoH_v2 as cuMemcpyDtoH, cuMemcpyDtoHAsync_v2 as cuMemcpyDtoHAsync,
        cuMemcpyHtoA_v2 as cuMemcpyHtoA, cuMemcpyHtoAAsync_v2 as cuMemcpyHtoAAsync,
        cuMemcpyHtoD_v2 as cuMemcpyHtoD, cuMemcpyHtoDAsync_v2 as cuMemcpyHtoDAsync,
        cuMemsetD2D8_v2 as cuMemsetD2D8, cuMemsetD2D16_v2 as cuMemsetD2D16,
        cuMemsetD2D32_v2 as cuMemsetD2D32, cuMemsetD8_v2 as cuMemsetD8,
        cuMemsetD16_v2 as cuMemsetD16, cuMemsetD32_v2 as cuMemsetD32,
        cuModuleGetGlobal_v2 as cuModuleGetGlobal, cuStreamBatchMemOp_v2 as cuStreamBatchMemOp,
        cuStreamBeginCapture_v2 as cuStreamBeginCapture, cuStreamDestroy_v2 as cuStreamDestroy,
        cuStreamGetCaptureInfo_v3 as cuStreamGetCaptureInfo,
        cuStreamUpdateCaptureDependencies_v2 as cuStreamUpdateCaptureDependencies,
        cuStreamWaitValue32_v2 as cuStreamWaitValue32,
        cuStreamWaitValue64_v2 as cuStreamWaitValue64,
        cuStreamWriteValue32_v2 as cuStreamWriteValue32,
        cuStreamWriteValue64_v2 as cuStreamWriteValue64,
        cuTexRefSetAddress2D_v3 as cuTexRefSetAddress2D,
    };
}

#[cfg(feature = "driver")]
/// CUDA profiler start and stop declarations.
pub mod profiler {
    #[cfg(feature = "driver_13_4")]
    include!("profiler_sys_13040.rs");
}

/// Scalar data types and library property enums shared by NVIDIA libraries.
pub mod library_types {

    #[cfg(feature = "runtime_13_4")]
    include!("library_types_sys_13040.rs");
}

/// CUDA runtime linking library.
#[cfg(feature = "nvjitlink_13_4")]
pub mod nvjitlink {
    include!("nvjitlink_sys_13040.rs");
}

#[cfg(feature = "nvrtc")]
/// NVRTC runtime compilation declarations.
pub mod nvrtc {

    #[cfg(feature = "nvrtc_13_4")]
    include!("nvrtc_sys_13040.rs");
}

#[cfg(feature = "nvvm")]
/// NVVM IR compilation and version-query declarations.
pub mod nvvm {

    #[cfg(feature = "nvvm_13_4")]
    include!("nvvm_sys_13040.rs");
}

#[cfg(feature = "nvtx")]
/// NVTX event annotation declarations.
pub mod nvtx {

    #[cfg(feature = "nvtx_3")]
    include!("nvtx_sys_3.rs");
}

#[cfg(feature = "runtime")]
/// CUDA Runtime API declarations and driver-compatible handle aliases.
pub mod runtime {

    // These types have type definitions in `driver_types.h`.
    #[cfg(feature = "driver_13_4")]
    #[rustfmt::skip]
    pub use crate::driver::{
        // --- Core handles & pointers ---
        cudaError_enum as cudaError_t,
        CUevent as cudaEvent_t,
        CUfunction as cudaFunction_t,
        CUstream as cudaStream_t,
        CUuuid as cudaUUID_t,
        CUuserObject as cudaUserObject_t,

        // --- Array & memory Types ---
        CUarray as cudaArray_t,
        CUmipmappedArray as cudaMipmappedArray_t,
        CUmemoryPool as cudaMemPool_t,

        // --- Texture & surface types ---
        CUgraphicsResource as cudaGraphicsResource_t,

        // --- Memory/semaphore types ---
        CUexternalMemory as cudaExternalMemory_t,
        CUexternalSemaphore as cudaExternalSemaphore_t,

        // --- Graph types ---
        CUgraph as cudaGraph_t,
        CUgraphNode as cudaGraphNode_t,
        CUgraphExec as cudaGraphExec_t,

        CUkernel as cudaKernel_t,
        CUlibrary as cudaLibrary_t,
        CUgraphConditionalHandle as cudaGraphConditionalHandle,
        CUasyncCallbackHandle as cudaAsyncCallbackHandle_t,
    };

    // These types are defined both in `driver_types.h` and `cuda.h` and might not be interchangeable.
    // Types of different layouts should not be imported here.
    #[cfg(feature = "driver_13_4")]
    #[rustfmt::skip]
    pub use crate::driver::{
        // --- Core Handles & Pointers ---
        CUflushGPUDirectRDMAWritesScope as cudaFlushGPUDirectRDMAWritesScope,
        CUflushGPUDirectRDMAWritesTarget as cudaFlushGPUDirectRDMAWritesTarget,

        // --- Array & memory Types ---
        CUDA_MEMSET_NODE_PARAMS as cudaMemsetParams,
        CUDA_HOST_NODE_PARAMS as cudaHostNodeParams,
        CUDA_EXT_SEM_SIGNAL_NODE_PARAMS as cudaExternalSemaphoreSignalNodeParams,
        CUDA_EXT_SEM_WAIT_NODE_PARAMS as cudaExternalSemaphoreWaitNodeParams,
        CUDA_MEM_ALLOC_NODE_PARAMS as cudaMemAllocNodeParams,
        CUDA_ARRAY_MEMORY_REQUIREMENTS as cudaArrayMemoryRequirements,
        CUDA_ARRAY_SPARSE_PROPERTIES as cudaArraySparseProperties,
        CUDA_MEMCPY3D_BATCH_OP as cudaMemcpy3DBatchOp,

        CUmemcpyAttributes as cudaMemcpyAttributes,
        CUmemPoolProps as cudaMemPoolProps,
        CUmemPoolPtrExportData as cudaMemPoolPtrExportData,
        CUmemAllocationHandleType as cudaMemAllocationHandleType,
        CUmemPool_attribute as cudaMemPoolAttr,
        CUsharedconfig as cudaSharedMemConfig,
        CUmemLocation as cudaMemLocation,
        CUmemAccessDesc as cudaMemAccessDesc,
        CUmem_range_attribute as cudaMemRangeAttribute,
        CUmem_advise as cudaMemoryAdvise,
        CUmemAccess_flags as cudaMemAccessFlags,

        // --- IPC Types ---
        CUipcEventHandle as cudaIpcEventHandle_t,
        CUipcMemHandle as cudaIpcMemHandle_t,

        // --- Graph Types ---
        CUgraphExecUpdateResult as cudaGraphExecUpdateResult,
        CUgraphMem_attribute as cudaGraphMemAttributeType,
        CUgraphNodeType as cudaGraphNodeType,
        CUgraphEdgeData as cudaGraphEdgeData,

        CUgraphNodeParams as cudaGraphNodeParams,
        CUgraphExecUpdateResultInfo as cudaGraphExecUpdateResultInfo,
        CUDA_GRAPH_INSTANTIATE_PARAMS as cudaGraphInstantiateParams,

        // --- Function Pointer Types ---
        CUhostFn as cudaHostFn_t,
        CUasyncCallback as cudaAsyncCallback,

        // --- Enums ---
        CUdevice_attribute as cudaDeviceAttr,
        CUfunction_attribute as cudaFuncAttribute,
        CUjit_option as cudaJitOption,
        CUdevice_P2PAttribute as cudaDeviceP2PAttr,
        CUlibraryOption as cudaLibraryOption,
        CUdriverProcAddressQueryResult as cudaDriverEntryPointQueryResult,

        // --- Other types ---
        CUfunc_cache as cudaFuncCache,
        CUstreamCaptureMode as cudaStreamCaptureMode,
        CUstreamCaptureStatus as cudaStreamCaptureStatus,
        // CUextent3D as cudaExtent,
    };

    /// Pointer to a CUDA array handle in this runtime binding.
    pub type cudaArray_const_t = *const crate::driver::CUarray;

    /// Pointer to an immutable native CUDA mipmapped-array object.
    pub type cudaMipmappedArray_const_t = *const crate::driver::CUmipmappedArray_st;

    /// Stream capture status used by graph recapture operations.
    pub type cudaGraphRecaptureStatus = cudaStreamCaptureStatus;

    #[cfg(feature = "runtime_13_4")]
    include!("driver_types_sys_13040.rs");

    #[cfg(feature = "runtime_13_4")]
    include!("runtime_sys_13040.rs");
}

pub use singe_loader::{Absence, LoadError, take_absence};

static DRIVER: singe_loader::Library = singe_loader::Library::cuda_driver();

/// Loads the CUDA driver now, instead of on the first call of one of its functions.
///
/// # Errors
///
/// Returns an error if the library has no files on this platform or one of its files would not load.
pub fn load_driver() -> Result<(), LoadError> {
    DRIVER.load()
}

static RUNTIME: singe_loader::Library = singe_loader::Library::cuda_runtime();

/// Loads the CUDA runtime now, instead of on the first call of one of its functions.
///
/// # Errors
///
/// Returns an error if the library has no files on this platform or one of its files would not load.
pub fn load_runtime() -> Result<(), LoadError> {
    RUNTIME.load()
}

static NVRTC: singe_loader::Library = singe_loader::Library::nvrtc();

/// Loads NVRTC now, instead of on the first call of one of its functions.
///
/// # Errors
///
/// Returns an error if the library has no files on this platform or one of its files would not load.
pub fn load_nvrtc() -> Result<(), LoadError> {
    NVRTC.load()
}

/// Returns the path of each NVRTC file, loading NVRTC first if it is not loaded yet.
///
/// # Errors
///
/// Returns an error if the library has no files on this platform or one of its files would not load.
pub fn nvrtc_paths() -> Result<Vec<std::path::PathBuf>, LoadError> {
    NVRTC.paths()
}

static NVJITLINK: singe_loader::Library = singe_loader::Library::nvjitlink();

/// Loads nvJitLink now, instead of on the first call of one of its functions.
///
/// # Errors
///
/// Returns an error if the library has no files on this platform or one of its files would not load.
pub fn load_nvjitlink() -> Result<(), LoadError> {
    NVJITLINK.load()
}

static NVVM: singe_loader::Library = singe_loader::Library::nvvm();

/// Loads NVVM now, instead of on the first call of one of its functions.
///
/// # Errors
///
/// Returns an error if the library has no files on this platform or one of its files would not load.
pub fn load_nvvm() -> Result<(), LoadError> {
    NVVM.load()
}

static NVTX: singe_loader::Library = singe_loader::Library::nvtx();

/// Loads NVTX now, instead of on the first call of one of its functions.
///
/// # Errors
///
/// Returns an error if the library has no files on this platform or one of its files would not load.
pub fn load_nvtx() -> Result<(), LoadError> {
    NVTX.load()
}

#[cfg(feature = "driver_13_4")]
singe_loader::missing_status!(
    driver::CUresult,
    library: driver::CUresult::CUDA_ERROR_SHARED_OBJECT_INIT_FAILED,
    symbol: driver::CUresult::CUDA_ERROR_SHARED_OBJECT_SYMBOL_NOT_FOUND,
);

#[cfg(feature = "runtime_13_4")]
impl singe_loader::Missing for runtime::cudaChannelFormatDesc {
    fn missing(_: singe_loader::Absence) -> Self {
        Self {
            x: 0,
            y: 0,
            z: 0,
            w: 0,
            f: runtime::cudaChannelFormatKind::cudaChannelFormatKindSigned,
        }
    }
}

#[cfg(feature = "nvrtc_13_4")]
singe_loader::missing_status!(
    nvrtc::nvrtcResult,
    library: nvrtc::nvrtcResult::NVRTC_ERROR_INTERNAL_ERROR,
    symbol: nvrtc::nvrtcResult::NVRTC_ERROR_INTERNAL_ERROR,
);

#[cfg(feature = "nvjitlink_13_4")]
singe_loader::missing_status!(
    nvjitlink::nvJitLinkResult,
    library: nvjitlink::nvJitLinkResult::NVJITLINK_ERROR_INTERNAL,
    symbol: nvjitlink::nvJitLinkResult::NVJITLINK_ERROR_OUTDATED_LIBRARY,
);

#[cfg(feature = "nvvm_13_4")]
singe_loader::missing_status!(
    nvvm::nvvmResult,
    library: nvvm::nvvmResult::NVVM_ERROR_PROGRAM_CREATION_FAILURE,
    symbol: nvvm::nvvmResult::NVVM_ERROR_PROGRAM_CREATION_FAILURE,
);

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_it_works() {
        #[cfg(feature = "driver")]
        {
            let mut version = 0;
            // SAFETY: the version query writes only into the local output locations.
            unsafe {
                driver::cuDriverGetVersion(&mut version);
            }
            assert_ne!(version, 0);
            println!("CUDA driver version: {}", version);
        }

        #[cfg(feature = "runtime")]
        {
            let mut version = 0;
            // SAFETY: the version query writes only into the local output locations.
            unsafe {
                runtime::cudaRuntimeGetVersion(&mut version);
            }
            assert_ne!(version, 0);
            println!("CUDA runtime version: {}", version);
        }

        #[cfg(feature = "nvrtc")]
        {
            let mut major = 0;
            let mut minor = 0;
            // SAFETY: the version query writes only into the local output locations.
            unsafe {
                nvrtc::nvrtcVersion(&mut major, &mut minor);
            }
            assert_ne!(major, 0);
            println!("NVRTC version: {}.{}", major, minor);
        }

        #[cfg(feature = "nvtx")]
        {
            assert_eq!(nvtx::NVTX_VERSION, 3);
            println!("NVTX version: {}", nvtx::NVTX_VERSION);
        }
    }
}