use std::{
env,
fmt::Write as _,
fs::{File, OpenOptions},
path::PathBuf,
sync::Arc,
};
use singe_cuda_sys::driver;
use crate::{
context::Context,
device::{Device, Uuid},
error::{Error, Result, Status},
try_ffi,
};
#[derive(Debug)]
pub struct DeviceLock {
_file: File,
}
impl DeviceLock {
fn acquire(device_id: i32) -> Result<Self> {
let uuid = device_uuid(device_id)?;
let name = uuid
.bytes
.iter()
.fold(String::from("singe-cuda-device-"), |mut name, byte| {
let _ = write!(name, "{byte:02x}");
name
});
let path = env::var_os("SINGE_CUDA_TEST_LOCK_DIR")
.map_or_else(env::temp_dir, PathBuf::from)
.join(format!("{name}.lock"));
let file = OpenOptions::new()
.read(true)
.write(true)
.create(true)
.truncate(false)
.open(&path)?;
file.lock()?;
Ok(Self { _file: file })
}
}
pub fn device_lock(device: Device) -> Result<DeviceLock> {
DeviceLock::acquire(device.id())
}
#[derive(Debug)]
pub struct TestDevice {
context: Arc<Context>,
_lock: DeviceLock,
}
impl TestDevice {
#[must_use]
pub fn context(&self) -> &Arc<Context> {
&self.context
}
}
pub fn bootstrap() -> Result<TestDevice> {
bootstrap_for_device(Device::new(0))
}
pub fn bootstrap_for_device(device: Device) -> Result<TestDevice> {
let lock = device_lock(device)?;
let context = Context::create_for_device(device)?;
Ok(TestDevice {
context,
_lock: lock,
})
}
#[must_use]
pub fn is_unavailable(error: &Error) -> bool {
matches!(
error,
Error::Cuda { code, .. } if *code == Status::StubLibrary
) || matches!(error, Error::Load(_))
}
fn device_uuid(device_id: i32) -> Result<Uuid> {
let mut device: driver::CUdevice = 0;
let mut uuid = driver::CUuuid::default();
unsafe {
try_ffi!(driver::cuInit(0))?;
try_ffi!(driver::cuDeviceGet(&raw mut device, device_id))?;
try_ffi!(driver::cuDeviceGetUuid_v2(&raw mut uuid, device))?;
}
Ok(uuid.into())
}