Skip to main content

baracuda_driver/
init.rs

1//! Driver initialization helpers.
2//!
3//! CUDA requires `cuInit(0)` before any other driver call. `baracuda-driver`
4//! will call it automatically on first use of [`crate::Device::get`] and
5//! friends, but you may also call [`init`] yourself (e.g. at process
6//! start-up) to fail fast when CUDA is unavailable.
7
8use core::sync::atomic::{AtomicBool, Ordering};
9
10use baracuda_cuda_sys::driver;
11
12use crate::error::{check, Result};
13
14static INITIALIZED: AtomicBool = AtomicBool::new(false);
15
16/// Ensure `cuInit(0)` has been called. Idempotent and thread-safe.
17pub fn init() -> Result<()> {
18    if INITIALIZED.load(Ordering::Acquire) {
19        return Ok(());
20    }
21    let d = driver()?;
22    let cu = d.cu_init()?;
23    // SAFETY: `cuInit` takes a flags word; NVIDIA reserves all bits (pass 0).
24    check(unsafe { cu(0) })?;
25    INITIALIZED.store(true, Ordering::Release);
26    Ok(())
27}
28
29/// Driver version exposed by the installed `libcuda`, e.g. `CudaVersion::CUDA_12_6`.
30pub fn version() -> Result<baracuda_types::CudaVersion> {
31    init()?;
32    let d = driver()?;
33    let cu = d.cu_driver_get_version()?;
34    let mut raw: core::ffi::c_int = 0;
35    check(unsafe { cu(&mut raw) })?;
36    Ok(baracuda_types::CudaVersion::from_raw(raw as u32))
37}