Skip to main content

singe_nvml/
compute_instance.rs

1#[allow(unused_imports)]
2use crate::error::Status;
3
4use std::{mem::ManuallyDrop, ops::Deref, ptr::read as ptr_read};
5
6use singe_nvml_sys as sys;
7
8use crate::{
9    device::Device,
10    error::Result,
11    gpu_instance::GpuInstance,
12    try_ffi,
13    types::{ComputeInstanceInfo, ComputeInstancePlacement},
14};
15
16#[derive(Debug, Clone, PartialEq, Eq, Hash)]
17#[repr(transparent)]
18pub struct ComputeInstance(sys::nvmlComputeInstance_t);
19
20#[derive(Debug)]
21pub struct OwnedComputeInstance(ComputeInstance);
22
23impl ComputeInstance {
24    pub const unsafe fn from_raw(handle: sys::nvmlComputeInstance_t) -> Self {
25        Self(handle)
26    }
27
28    pub const fn as_raw(&self) -> sys::nvmlComputeInstance_t {
29        self.0
30    }
31
32    pub const fn is_null(&self) -> bool {
33        self.0.is_null()
34    }
35
36    /// Returns compute instance information.
37    ///
38    /// For Ampere or newer fully supported devices.
39    /// Supported on Linux only.
40    ///
41    /// # Errors
42    ///
43    /// Returns an error if the handle or output arguments are rejected by NVML, if
44    /// the current process does not have permission to query the instance, or if
45    /// NVML has not been initialized.
46    pub fn info(&self) -> Result<ComputeInstanceInfo> {
47        let mut info = sys::nvmlComputeInstanceInfo_t::default();
48        unsafe {
49            try_ffi!(sys::nvmlComputeInstanceGetInfo_v2(self.0, &raw mut info))?;
50        }
51        Ok(info.into())
52    }
53
54    pub fn parent_device(&self) -> Result<Device> {
55        Ok(self.info()?.device)
56    }
57
58    pub fn parent_gpu_instance(&self) -> Result<GpuInstance> {
59        Ok(self.info()?.gpu_instance)
60    }
61
62    pub fn id(&self) -> Result<u32> {
63        Ok(self.info()?.id)
64    }
65
66    pub fn profile_id(&self) -> Result<u32> {
67        Ok(self.info()?.profile_id)
68    }
69
70    pub fn placement(&self) -> Result<ComputeInstancePlacement> {
71        Ok(self.info()?.placement)
72    }
73}
74
75impl OwnedComputeInstance {
76    pub const unsafe fn from_raw(handle: sys::nvmlComputeInstance_t) -> Self {
77        Self(ComputeInstance(handle))
78    }
79
80    pub const fn as_compute_instance(&self) -> &ComputeInstance {
81        &self.0
82    }
83
84    pub fn into_inner(self) -> ComputeInstance {
85        let this = ManuallyDrop::new(self);
86        unsafe { ptr_read(&this.0) }
87    }
88}
89
90impl Deref for OwnedComputeInstance {
91    type Target = ComputeInstance;
92
93    fn deref(&self) -> &Self::Target {
94        &self.0
95    }
96}
97
98impl Drop for OwnedComputeInstance {
99    fn drop(&mut self) {
100        unsafe {
101            let _ = sys::nvmlComputeInstanceDestroy(self.0.0);
102        }
103    }
104}