nvml_wrapper/
lib.rs

1/*!
2A safe and ergonomic Rust wrapper for the [NVIDIA Management Library][nvml] (NVML),
3a C-based programmatic interface for monitoring and managing various states within
4NVIDIA GPUs.
5
6```
7use nvml_wrapper::Nvml;
8# use nvml_wrapper::error::*;
9# fn test() -> Result<(), NvmlError> {
10
11let nvml = Nvml::init()?;
12// Get the first `Device` (GPU) in the system
13let device = nvml.device_by_index(0)?;
14
15let brand = device.brand()?; // GeForce on my system
16let fan_speed = device.fan_speed(0)?; // Currently 17% on my system
17let power_limit = device.enforced_power_limit()?; // 275k milliwatts on my system
18let encoder_util = device.encoder_utilization()?; // Currently 0 on my system; Not encoding anything
19let memory_info = device.memory_info()?; // Currently 1.63/6.37 GB used on my system
20
21// ... and there's a whole lot more you can do. Most everything in NVML is wrapped and ready to go
22# Ok(())
23# }
24```
25
26NVML is intended to be a platform for building 3rd-party applications, and is
27also the underlying library for NVIDIA's nvidia-smi tool.
28
29## Usage
30
31`nvml-wrapper` builds on top of generated bindings for NVML that make use of the
32[`libloading`][libloading] crate. This means the NVML library gets loaded upon
33calling `Nvml::init` and can return an error if NVML isn't present, making it
34possible to drop NVIDIA-related features in your code at runtime on systems that
35don't have relevant hardware.
36
37Successful execution of `Nvml::init` means:
38
39* The NVML library was present on the system and able to be opened
40* The function symbol to initialize NVML was loaded and called successfully
41* An attempt has been made to load all other NVML function symbols
42
43Every function you call thereafter will individually return an error if it couldn't
44be loaded from the NVML library during the `Nvml::init` call.
45
46Note that it's not advised to repeatedly call `Nvml::init` as the constructor
47has to perform all the work of loading the function symbols from the library
48each time it gets called. Instead, call `Nvml::init` once and store the resulting
49`Nvml` instance somewhere to be accessed throughout the lifetime of your program
50(perhaps in a [`once_cell`][once_cell]).
51
52## NVML Support
53
54This wrapper is being developed against and currently supports NVML version
5511. Each new version of NVML is guaranteed to be backwards-compatible according
56to NVIDIA, so this wrapper should continue to work without issue regardless of
57NVML version bumps.
58
59### Legacy Functions
60
61Sometimes there will be function-level API version bumps in new NVML releases.
62For example:
63
64```text
65nvmlDeviceGetComputeRunningProcesses
66nvmlDeviceGetComputeRunningProcesses_v2
67nvmlDeviceGetComputeRunningProcesses_v3
68```
69
70The older versions of the functions will generally continue to work with the
71newer NVML releases; however, the newer function versions will not work with
72older NVML installs.
73
74By default this wrapper only provides access to the newest function versions.
75Enable the `legacy-functions` feature if you require the ability to call older
76functions.
77
78## MSRV
79
80The Minimum Supported Rust Version is currently 1.51.0. I will not go out of my
81way to avoid bumping this.
82
83## Cargo Features
84
85The `serde` feature can be toggled on in order to `#[derive(Serialize, Deserialize)]`
86for every NVML data structure.
87
88[nvml]: https://developer.nvidia.com/nvidia-management-library-nvml
89[libloading]: https://github.com/nagisa/rust_libloading
90[once_cell]: https://docs.rs/once_cell/latest/once_cell/sync/struct.Lazy.html
91*/
92
93#![recursion_limit = "1024"]
94#![allow(non_upper_case_globals)]
95
96extern crate libloading;
97extern crate nvml_wrapper_sys as ffi;
98
99pub mod bitmasks;
100pub mod device;
101pub mod enum_wrappers;
102pub mod enums;
103pub mod error;
104pub mod event;
105pub mod high_level;
106pub mod nv_link;
107pub mod struct_wrappers;
108pub mod structs;
109#[cfg(test)]
110mod test_utils;
111pub mod unit;
112
113// Re-exports for convenience
114pub use crate::device::Device;
115pub use crate::event::EventSet;
116pub use crate::nv_link::NvLink;
117pub use crate::unit::Unit;
118
119/// Re-exports from `nvml-wrapper-sys` that are necessary for use of this wrapper.
120pub mod sys_exports {
121    /// Use these constants to populate the `structs::device::FieldId` newtype.
122    pub mod field_id {
123        pub use crate::ffi::bindings::field_id::*;
124    }
125}
126
127#[cfg(target_os = "linux")]
128use std::convert::TryInto;
129#[cfg(target_os = "linux")]
130use std::ptr;
131use std::{
132    convert::TryFrom,
133    ffi::{CStr, CString, OsStr},
134    mem::{self, ManuallyDrop},
135    os::raw::{c_int, c_uint},
136};
137
138use static_assertions::assert_impl_all;
139
140#[cfg(target_os = "linux")]
141use crate::enum_wrappers::device::TopologyLevel;
142
143use crate::error::{nvml_sym, nvml_try, NvmlError};
144use crate::ffi::bindings::*;
145
146use crate::struct_wrappers::ExcludedDeviceInfo;
147
148#[cfg(target_os = "linux")]
149use crate::struct_wrappers::device::PciInfo;
150use crate::struct_wrappers::unit::HwbcEntry;
151
152use crate::bitmasks::InitFlags;
153
154#[cfg(not(target_os = "linux"))]
155const LIB_PATH: &str = "nvml.dll";
156
157#[cfg(target_os = "linux")]
158const LIB_PATH: &str = "libnvidia-ml.so";
159
160/// Determines the major version of the CUDA driver given the full version.
161///
162/// Obtain the full version via `Nvml.sys_cuda_driver_version()`.
163pub fn cuda_driver_version_major(version: i32) -> i32 {
164    version / 1000
165}
166
167/// Determines the minor version of the CUDA driver given the full version.
168///
169/// Obtain the full version via `NVML.sys_cuda_driver_version()`.
170pub fn cuda_driver_version_minor(version: i32) -> i32 {
171    (version % 1000) / 10
172}
173
174/**
175The main struct that this library revolves around.
176
177According to NVIDIA's documentation, "It is the user's responsibility to call `nvmlInit()`
178before calling any other methods, and `nvmlShutdown()` once NVML is no longer being used."
179This struct is used to enforce those rules.
180
181Also according to NVIDIA's documentation, "NVML is thread-safe so it is safe to make
182simultaneous NVML calls from multiple threads." In the Rust world, this translates to `NVML`
183being `Send` + `Sync`. You can `.clone()` an `Arc` wrapped `NVML` and enjoy using it on any thread.
184
185NOTE: If you care about possible errors returned from `nvmlShutdown()`, use the `.shutdown()`
186method on this struct. **The `Drop` implementation ignores errors.**
187
188When reading documentation on this struct and its members, remember that a lot of it,
189especially in regards to errors returned, is copied from NVIDIA's docs. While they can be found
190online [here](http://docs.nvidia.com/deploy/nvml-api/index.html), the hosted docs sometimes outdated
191and may not accurately reflect the version of NVML that this library is written for; beware. You
192should ideally read the doc comments on an up-to-date NVML API header. Such a header can be
193downloaded as part of the [CUDA toolkit](https://developer.nvidia.com/cuda-downloads).
194*/
195pub struct Nvml {
196    lib: ManuallyDrop<NvmlLib>,
197}
198
199assert_impl_all!(Nvml: Send, Sync);
200
201impl std::fmt::Debug for Nvml {
202    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
203        f.write_str("NVML")
204    }
205}
206
207impl Nvml {
208    /**
209    Handles NVML initialization and must be called before doing anything else.
210
211    While it is possible to initialize `NVML` multiple times (NVIDIA's docs state
212    that reference counting is used internally), you should strive to initialize
213    `NVML` once at the start of your program's execution; the constructors handle
214    dynamically loading function symbols from the `NVML` lib and are therefore
215    somewhat expensive.
216
217    Note that this will initialize NVML but not any GPUs. This means that NVML can
218    communicate with a GPU even when other GPUs in a system are bad or unstable.
219
220    By default, initialization looks for "libnvidia-ml.so" on linux and "nvml.dll"
221    on Windows. These default names should work for default installs on those
222    platforms; if further specification is required, use `Nvml::builder`.
223
224    # Errors
225
226    * `DriverNotLoaded`, if the NVIDIA driver is not running
227    * `NoPermission`, if NVML does not have permission to talk to the driver
228    * `Unknown`, on any unexpected error
229    */
230    // Checked against local
231    #[doc(alias = "nvmlInit_v2")]
232    pub fn init() -> Result<Self, NvmlError> {
233        Self::init_internal(LIB_PATH)
234    }
235
236    fn init_internal(path: impl AsRef<std::ffi::OsStr>) -> Result<Self, NvmlError> {
237        let lib = unsafe {
238            let lib = NvmlLib::new(path)?;
239            let sym = nvml_sym(lib.nvmlInit_v2.as_ref())?;
240
241            nvml_try(sym())?;
242            ManuallyDrop::new(lib)
243        };
244
245        Ok(Self { lib })
246    }
247
248    /**
249    An initialization function that allows you to pass flags to control certain behaviors.
250
251    This is the same as `init()` except for the addition of flags.
252
253    # Errors
254
255    * `DriverNotLoaded`, if the NVIDIA driver is not running
256    * `NoPermission`, if NVML does not have permission to talk to the driver
257    * `Unknown`, on any unexpected error
258
259    # Examples
260
261    ```
262    # use nvml_wrapper::Nvml;
263    # use nvml_wrapper::error::*;
264    use nvml_wrapper::bitmasks::InitFlags;
265
266    # fn main() -> Result<(), NvmlError> {
267    // Don't fail if the system doesn't have any NVIDIA GPUs
268    //
269    // Also, don't attach any GPUs during initialization
270    Nvml::init_with_flags(InitFlags::NO_GPUS | InitFlags::NO_ATTACH)?;
271    # Ok(())
272    # }
273    ```
274    */
275    #[doc(alias = "nvmlInitWithFlags")]
276    pub fn init_with_flags(flags: InitFlags) -> Result<Self, NvmlError> {
277        Self::init_with_flags_internal(LIB_PATH, flags)
278    }
279
280    fn init_with_flags_internal(
281        path: impl AsRef<std::ffi::OsStr>,
282        flags: InitFlags,
283    ) -> Result<Self, NvmlError> {
284        let lib = unsafe {
285            let lib = NvmlLib::new(path)?;
286            let sym = nvml_sym(lib.nvmlInitWithFlags.as_ref())?;
287
288            nvml_try(sym(flags.bits()))?;
289            ManuallyDrop::new(lib)
290        };
291
292        Ok(Self { lib })
293    }
294
295    /// Create an `NvmlBuilder` for further flexibility in how NVML is initialized.
296    pub fn builder<'a>() -> NvmlBuilder<'a> {
297        NvmlBuilder::default()
298    }
299
300    /**
301    Use this to shutdown NVML and release allocated resources if you care about handling
302    potential errors (*the `Drop` implementation ignores errors!*).
303
304    # Errors
305
306    * `Uninitialized`, if the library has not been successfully initialized
307    * `Unknown`, on any unexpected error
308    */
309    // Thanks to `sorear` on IRC for suggesting this approach
310    // Checked against local
311    // Tested
312    #[doc(alias = "nvmlShutdown")]
313    pub fn shutdown(mut self) -> Result<(), NvmlError> {
314        let sym = nvml_sym(self.lib.nvmlShutdown.as_ref())?;
315
316        unsafe {
317            nvml_try(sym())?;
318        }
319
320        // SAFETY: we `mem::forget(self)` after this, so `self.lib` won't get
321        // touched by our `Drop` impl
322        let lib = unsafe { ManuallyDrop::take(&mut self.lib) };
323        mem::forget(self);
324
325        Ok(lib.__library.close()?)
326    }
327
328    /**
329    Get the number of compute devices in the system (compute device == one GPU).
330
331    Note that this count can include devices you do not have permission to access.
332
333    # Errors
334
335    * `Uninitialized`, if the library has not been successfully initialized
336    * `Unknown`, on any unexpected error
337    */
338    // Checked against local
339    // Tested
340    #[doc(alias = "nvmlDeviceGetCount_v2")]
341    pub fn device_count(&self) -> Result<u32, NvmlError> {
342        let sym = nvml_sym(self.lib.nvmlDeviceGetCount_v2.as_ref())?;
343
344        unsafe {
345            let mut count: c_uint = mem::zeroed();
346            nvml_try(sym(&mut count))?;
347
348            Ok(count)
349        }
350    }
351
352    /**
353    Gets the version of the system's graphics driver and returns it as an alphanumeric
354    string.
355
356    # Errors
357
358    * `Uninitialized`, if the library has not been successfully initialized
359    * `Utf8Error`, if the string obtained from the C function is not valid Utf8
360    */
361    // Checked against local
362    // Tested
363    #[doc(alias = "nvmlSystemGetDriverVersion")]
364    pub fn sys_driver_version(&self) -> Result<String, NvmlError> {
365        let sym = nvml_sym(self.lib.nvmlSystemGetDriverVersion.as_ref())?;
366
367        unsafe {
368            let mut version_vec = vec![0; NVML_SYSTEM_DRIVER_VERSION_BUFFER_SIZE as usize];
369
370            nvml_try(sym(
371                version_vec.as_mut_ptr(),
372                NVML_SYSTEM_DRIVER_VERSION_BUFFER_SIZE,
373            ))?;
374
375            let version_raw = CStr::from_ptr(version_vec.as_ptr());
376            Ok(version_raw.to_str()?.into())
377        }
378    }
379
380    /**
381    Gets the version of the system's NVML library and returns it as an alphanumeric
382    string.
383
384    # Errors
385
386    * `Utf8Error`, if the string obtained from the C function is not valid Utf8
387    */
388    // Checked against local
389    // Tested
390    #[doc(alias = "nvmlSystemGetNVMLVersion")]
391    pub fn sys_nvml_version(&self) -> Result<String, NvmlError> {
392        let sym = nvml_sym(self.lib.nvmlSystemGetNVMLVersion.as_ref())?;
393
394        unsafe {
395            let mut version_vec = vec![0; NVML_SYSTEM_NVML_VERSION_BUFFER_SIZE as usize];
396
397            nvml_try(sym(
398                version_vec.as_mut_ptr(),
399                NVML_SYSTEM_NVML_VERSION_BUFFER_SIZE,
400            ))?;
401
402            // Thanks to `Amaranth` on IRC for help with this
403            let version_raw = CStr::from_ptr(version_vec.as_ptr());
404            Ok(version_raw.to_str()?.into())
405        }
406    }
407
408    /**
409    Gets the version of the system's CUDA driver.
410
411    Calls into the CUDA library (cuDriverGetVersion()).
412
413    You can use `cuda_driver_version_major` and `cuda_driver_version_minor`
414    to get the major and minor driver versions from this number.
415
416    # Errors
417
418    * `FunctionNotFound`, if cuDriverGetVersion() is not found in the shared library
419    * `LibraryNotFound`, if libcuda.so.1 or libcuda.dll cannot be found
420    */
421    #[doc(alias = "nvmlSystemGetCudaDriverVersion_v2")]
422    pub fn sys_cuda_driver_version(&self) -> Result<i32, NvmlError> {
423        let sym = nvml_sym(self.lib.nvmlSystemGetCudaDriverVersion_v2.as_ref())?;
424
425        unsafe {
426            let mut version: c_int = mem::zeroed();
427            nvml_try(sym(&mut version))?;
428
429            Ok(version)
430        }
431    }
432
433    /**
434    Gets the name of the process for the given process ID, cropped to the provided length.
435
436    # Errors
437
438    * `Uninitialized`, if the library has not been successfully initialized
439    * `InvalidArg`, if the length is 0 (if this is returned without length being 0, file an issue)
440    * `NotFound`, if the process does not exist
441    * `NoPermission`, if the user doesn't have permission to perform the operation
442    * `Utf8Error`, if the string obtained from the C function is not valid UTF-8. NVIDIA's docs say
443    that the string encoding is ANSI, so this may very well happen.
444    * `Unknown`, on any unexpected error
445    */
446    // TODO: The docs say the string is ANSI-encoded. Not sure if I should try
447    // to do anything about that
448    // Checked against local
449    // Tested
450    #[doc(alias = "nvmlSystemGetProcessName")]
451    pub fn sys_process_name(&self, pid: u32, length: usize) -> Result<String, NvmlError> {
452        let sym = nvml_sym(self.lib.nvmlSystemGetProcessName.as_ref())?;
453
454        unsafe {
455            let mut name_vec = vec![0; length];
456
457            nvml_try(sym(pid, name_vec.as_mut_ptr(), length as c_uint))?;
458
459            let name_raw = CStr::from_ptr(name_vec.as_ptr());
460            Ok(name_raw.to_str()?.into())
461        }
462    }
463
464    /**
465    Acquire the handle for a particular device based on its index (starts at 0).
466
467    Usage of this function causes NVML to initialize the target GPU. Additional
468    GPUs may be initialized if the target GPU is an SLI slave.
469
470    You can determine valid indices by using `.device_count()`. This
471    function doesn't call that for you, but the actual C function to get
472    the device handle will return an error in the case of an invalid index.
473    This means that the `InvalidArg` error will be returned if you pass in
474    an invalid index.
475
476    NVIDIA's docs state that "The order in which NVML enumerates devices has
477    no guarantees of consistency between reboots. For that reason it is recommended
478    that devices be looked up by their PCI ids or UUID." In this library, that translates
479    into usage of `.device_by_uuid()` and `.device_by_pci_bus_id()`.
480
481    The NVML index may not correlate with other APIs such as the CUDA device index.
482
483    # Errors
484
485    * `Uninitialized`, if the library has not been successfully initialized
486    * `InvalidArg`, if index is invalid
487    * `InsufficientPower`, if any attached devices have improperly attached external power cables
488    * `NoPermission`, if the user doesn't have permission to talk to this device
489    * `IrqIssue`, if the NVIDIA kernel detected an interrupt issue with the attached GPUs
490    * `GpuLost`, if the target GPU has fallen off the bus or is otherwise inaccessible
491    * `Unknown`, on any unexpected error
492    */
493    // Checked against local
494    // Tested
495    #[doc(alias = "nvmlDeviceGetHandleByIndex_v2")]
496    pub fn device_by_index(&self, index: u32) -> Result<Device, NvmlError> {
497        let sym = nvml_sym(self.lib.nvmlDeviceGetHandleByIndex_v2.as_ref())?;
498
499        unsafe {
500            let mut device: nvmlDevice_t = mem::zeroed();
501            nvml_try(sym(index, &mut device))?;
502
503            Ok(Device::new(device, self))
504        }
505    }
506
507    /**
508    Acquire the handle for a particular device based on its PCI bus ID.
509
510    Usage of this function causes NVML to initialize the target GPU. Additional
511    GPUs may be initialized if the target GPU is an SLI slave.
512
513    The bus ID corresponds to the `bus_id` returned by `Device.pci_info()`.
514
515    # Errors
516
517    * `Uninitialized`, if the library has not been successfully initialized
518    * `InvalidArg`, if `pci_bus_id` is invalid
519    * `NotFound`, if `pci_bus_id` does not match a valid device on the system
520    * `InsufficientPower`, if any attached devices have improperly attached external power cables
521    * `NoPermission`, if the user doesn't have permission to talk to this device
522    * `IrqIssue`, if the NVIDIA kernel detected an interrupt issue with the attached GPUs
523    * `GpuLost`, if the target GPU has fallen off the bus or is otherwise inaccessible
524    * `NulError`, for which you can read the docs on `std::ffi::NulError`
525    * `Unknown`, on any unexpected error
526    */
527    // Checked against local
528    // Tested
529    #[doc(alias = "nvmlDeviceGetHandleByPciBusId_v2")]
530    pub fn device_by_pci_bus_id<S: AsRef<str>>(&self, pci_bus_id: S) -> Result<Device, NvmlError>
531    where
532        Vec<u8>: From<S>,
533    {
534        let sym = nvml_sym(self.lib.nvmlDeviceGetHandleByPciBusId_v2.as_ref())?;
535
536        unsafe {
537            let c_string = CString::new(pci_bus_id)?;
538            let mut device: nvmlDevice_t = mem::zeroed();
539
540            nvml_try(sym(c_string.as_ptr(), &mut device))?;
541
542            Ok(Device::new(device, self))
543        }
544    }
545
546    /// Not documenting this because it's deprecated and does not seem to work
547    /// anymore.
548    // Tested (for an error)
549    #[deprecated(note = "use `.device_by_uuid()`, this errors on dual GPU boards")]
550    #[doc(alias = "nvmlDeviceGetHandleBySerial")]
551    pub fn device_by_serial<S: AsRef<str>>(&self, board_serial: S) -> Result<Device, NvmlError>
552    where
553        Vec<u8>: From<S>,
554    {
555        let sym = nvml_sym(self.lib.nvmlDeviceGetHandleBySerial.as_ref())?;
556
557        unsafe {
558            let c_string = CString::new(board_serial)?;
559            let mut device: nvmlDevice_t = mem::zeroed();
560
561            nvml_try(sym(c_string.as_ptr(), &mut device))?;
562
563            Ok(Device::new(device, self))
564        }
565    }
566
567    /**
568    Acquire the handle for a particular device based on its globally unique immutable
569    UUID.
570
571    Usage of this function causes NVML to initialize the target GPU. Additional
572    GPUs may be initialized as the function called within searches for the target GPU.
573
574    # Errors
575
576    * `Uninitialized`, if the library has not been successfully initialized
577    * `InvalidArg`, if `uuid` is invalid
578    * `NotFound`, if `uuid` does not match a valid device on the system
579    * `InsufficientPower`, if any attached devices have improperly attached external power cables
580    * `IrqIssue`, if the NVIDIA kernel detected an interrupt issue with the attached GPUs
581    * `GpuLost`, if the target GPU has fallen off the bus or is otherwise inaccessible
582    * `NulError`, for which you can read the docs on `std::ffi::NulError`
583    * `Unknown`, on any unexpected error
584
585    NVIDIA doesn't mention `NoPermission` for this one. Strange!
586    */
587    // Checked against local
588    // Tested
589    #[doc(alias = "nvmlDeviceGetHandleByUUID")]
590    pub fn device_by_uuid<S: AsRef<str>>(&self, uuid: S) -> Result<Device, NvmlError>
591    where
592        Vec<u8>: From<S>,
593    {
594        let sym = nvml_sym(self.lib.nvmlDeviceGetHandleByUUID.as_ref())?;
595
596        unsafe {
597            let c_string = CString::new(uuid)?;
598            let mut device: nvmlDevice_t = mem::zeroed();
599
600            nvml_try(sym(c_string.as_ptr(), &mut device))?;
601
602            Ok(Device::new(device, self))
603        }
604    }
605
606    /**
607    Gets the common ancestor for two devices.
608
609    Note: this is the same as `Device.topology_common_ancestor()`.
610
611    # Errors
612
613    * `InvalidArg`, if the device is invalid
614    * `NotSupported`, if this `Device` or the OS does not support this feature
615    * `UnexpectedVariant`, for which you can read the docs for
616    * `Unknown`, on any unexpected error
617
618    # Platform Support
619
620    Only supports Linux.
621    */
622    // Checked against local
623    // Tested
624    #[cfg(target_os = "linux")]
625    #[doc(alias = "nvmlDeviceGetTopologyCommonAncestor")]
626    pub fn topology_common_ancestor(
627        &self,
628        device1: &Device,
629        device2: &Device,
630    ) -> Result<TopologyLevel, NvmlError> {
631        let sym = nvml_sym(self.lib.nvmlDeviceGetTopologyCommonAncestor.as_ref())?;
632
633        unsafe {
634            let mut level: nvmlGpuTopologyLevel_t = mem::zeroed();
635
636            nvml_try(sym(device1.handle(), device2.handle(), &mut level))?;
637
638            TopologyLevel::try_from(level)
639        }
640    }
641
642    /**
643    Acquire the handle for a particular `Unit` based on its index.
644
645    Valid indices are derived from the count returned by `.unit_count()`.
646    For example, if `unit_count` is 2 the valid indices are 0 and 1, corresponding
647    to UNIT 0 and UNIT 1.
648
649    Note that the order in which NVML enumerates units has no guarantees of
650    consistency between reboots.
651
652    # Errors
653
654    * `Uninitialized`, if the library has not been successfully initialized
655    * `InvalidArg`, if `index` is invalid
656    * `Unknown`, on any unexpected error
657
658    # Device Support
659
660    For S-class products.
661    */
662    // Checked against local
663    // Tested (for an error)
664    #[doc(alias = "nvmlUnitGetHandleByIndex")]
665    pub fn unit_by_index(&self, index: u32) -> Result<Unit, NvmlError> {
666        let sym = nvml_sym(self.lib.nvmlUnitGetHandleByIndex.as_ref())?;
667
668        unsafe {
669            let mut unit: nvmlUnit_t = mem::zeroed();
670            nvml_try(sym(index as c_uint, &mut unit))?;
671
672            Ok(Unit::new(unit, self))
673        }
674    }
675
676    /**
677    Checks if the passed-in `Device`s are on the same physical board.
678
679    Note: this is the same as `Device.is_on_same_board_as()`.
680
681    # Errors
682
683    * `Uninitialized`, if the library has not been successfully initialized
684    * `InvalidArg`, if either `Device` is invalid
685    * `NotSupported`, if this check is not supported by this `Device`
686    * `GpuLost`, if this `Device` has fallen off the bus or is otherwise inaccessible
687    * `Unknown`, on any unexpected error
688    */
689    // Checked against local
690    // Tested
691    #[doc(alias = "nvmlDeviceOnSameBoard")]
692    pub fn are_devices_on_same_board(
693        &self,
694        device1: &Device,
695        device2: &Device,
696    ) -> Result<bool, NvmlError> {
697        let sym = nvml_sym(self.lib.nvmlDeviceOnSameBoard.as_ref())?;
698
699        unsafe {
700            let mut bool_int: c_int = mem::zeroed();
701
702            nvml_try(sym(device1.handle(), device2.handle(), &mut bool_int))?;
703
704            match bool_int {
705                0 => Ok(false),
706                _ => Ok(true),
707            }
708        }
709    }
710
711    /**
712    Gets the set of GPUs that have a CPU affinity with the given CPU number.
713
714    # Errors
715
716    * `InvalidArg`, if `cpu_number` is invalid
717    * `NotSupported`, if this `Device` or the OS does not support this feature
718    * `Unknown`, an error has occurred in the underlying topology discovery
719
720    # Platform Support
721
722    Only supports Linux.
723    */
724    // Tested
725    #[cfg(target_os = "linux")]
726    #[doc(alias = "nvmlSystemGetTopologyGpuSet")]
727    pub fn topology_gpu_set(&self, cpu_number: u32) -> Result<Vec<Device>, NvmlError> {
728        let sym = nvml_sym(self.lib.nvmlSystemGetTopologyGpuSet.as_ref())?;
729
730        unsafe {
731            let mut count = match self.topology_gpu_set_count(cpu_number)? {
732                0 => return Ok(vec![]),
733                value => value,
734            };
735            let mut devices: Vec<nvmlDevice_t> = vec![mem::zeroed(); count as usize];
736
737            nvml_try(sym(cpu_number, &mut count, devices.as_mut_ptr()))?;
738
739            Ok(devices.into_iter().map(|d| Device::new(d, self)).collect())
740        }
741    }
742
743    // Helper function for the above.
744    #[cfg(target_os = "linux")]
745    fn topology_gpu_set_count(&self, cpu_number: u32) -> Result<c_uint, NvmlError> {
746        let sym = nvml_sym(self.lib.nvmlSystemGetTopologyGpuSet.as_ref())?;
747
748        unsafe {
749            // Indicates that we want the count
750            let mut count: c_uint = 0;
751
752            // Passing null doesn't indicate that we want the count, just allowed
753            nvml_try(sym(cpu_number, &mut count, ptr::null_mut()))?;
754
755            Ok(count)
756        }
757    }
758
759    /**
760    Gets the IDs and firmware versions for any Host Interface Cards in the system.
761
762    # Errors
763
764    * `Uninitialized`, if the library has not been successfully initialized
765
766    # Device Support
767
768    Supports S-class products.
769    */
770    // Checked against local
771    // Tested
772    #[doc(alias = "nvmlSystemGetHicVersion")]
773    pub fn hic_versions(&self) -> Result<Vec<HwbcEntry>, NvmlError> {
774        let sym = nvml_sym(self.lib.nvmlSystemGetHicVersion.as_ref())?;
775
776        unsafe {
777            let mut count: c_uint = match self.hic_count()? {
778                0 => return Ok(vec![]),
779                value => value,
780            };
781            let mut hics: Vec<nvmlHwbcEntry_t> = vec![mem::zeroed(); count as usize];
782
783            nvml_try(sym(&mut count, hics.as_mut_ptr()))?;
784
785            hics.into_iter().map(HwbcEntry::try_from).collect()
786        }
787    }
788
789    /**
790    Gets the count of Host Interface Cards in the system.
791
792    # Errors
793
794    * `Uninitialized`, if the library has not been successfully initialized
795
796    # Device Support
797
798    Supports S-class products.
799    */
800    // Tested as part of the above method
801    #[doc(alias = "nvmlSystemGetHicVersion")]
802    pub fn hic_count(&self) -> Result<u32, NvmlError> {
803        let sym = nvml_sym(self.lib.nvmlSystemGetHicVersion.as_ref())?;
804
805        unsafe {
806            /*
807            NVIDIA doesn't even say that `count` will be set to the count if
808            `InsufficientSize` is returned. But we can assume sanity, right?
809
810            The idea here is:
811            If there are 0 HICs, NVML_SUCCESS is returned, `count` is set
812              to 0. We return count, all good.
813            If there is 1 HIC, NVML_SUCCESS is returned, `count` is set to
814              1. We return count, all good.
815            If there are >= 2 HICs, NVML_INSUFFICIENT_SIZE is returned.
816             `count` is theoretically set to the actual count, and we
817              return it.
818            */
819            let mut count: c_uint = 1;
820            let mut hics: [nvmlHwbcEntry_t; 1] = [mem::zeroed()];
821
822            match sym(&mut count, hics.as_mut_ptr()) {
823                nvmlReturn_enum_NVML_SUCCESS | nvmlReturn_enum_NVML_ERROR_INSUFFICIENT_SIZE => {
824                    Ok(count)
825                }
826                // We know that this will be an error
827                other => nvml_try(other).map(|_| 0),
828            }
829        }
830    }
831
832    /**
833    Gets the number of units in the system.
834
835    # Errors
836
837    * `Uninitialized`, if the library has not been successfully initialized
838    * `Unknown`, on any unexpected error
839
840    # Device Support
841
842    Supports S-class products.
843    */
844    // Checked against local
845    // Tested
846    #[doc(alias = "nvmlUnitGetCount")]
847    pub fn unit_count(&self) -> Result<u32, NvmlError> {
848        let sym = nvml_sym(self.lib.nvmlUnitGetCount.as_ref())?;
849
850        unsafe {
851            let mut count: c_uint = mem::zeroed();
852            nvml_try(sym(&mut count))?;
853
854            Ok(count)
855        }
856    }
857
858    /**
859    Create an empty set of events.
860
861    # Errors
862
863    * `Uninitialized`, if the library has not been successfully initialized
864    * `Unknown`, on any unexpected error
865
866    # Device Support
867
868    Supports Fermi and newer fully supported devices.
869    */
870    // Checked against local
871    // Tested
872    #[doc(alias = "nvmlEventSetCreate")]
873    pub fn create_event_set(&self) -> Result<EventSet, NvmlError> {
874        let sym = nvml_sym(self.lib.nvmlEventSetCreate.as_ref())?;
875
876        unsafe {
877            let mut set: nvmlEventSet_t = mem::zeroed();
878            nvml_try(sym(&mut set))?;
879
880            Ok(EventSet::new(set, self))
881        }
882    }
883
884    /**
885    Request the OS and the NVIDIA kernel driver to rediscover a portion of the PCI
886    subsystem in search of GPUs that were previously removed.
887
888    The portion of the PCI tree can be narrowed by specifying a domain, bus, and
889    device in the passed-in `pci_info`. **If all of these fields are zeroes, the
890    entire PCI tree will be searched.** Note that for long-running NVML processes,
891    the enumeration of devices will change based on how many GPUs are discovered
892    and where they are inserted in bus order.
893
894    All newly discovered GPUs will be initialized and have their ECC scrubbed which
895    may take several seconds per GPU. **All device handles are no longer guaranteed
896    to be valid post discovery**. I am not sure if this means **all** device
897    handles, literally, or if NVIDIA is referring to handles that had previously
898    been obtained to devices that were then removed and have now been
899    re-discovered.
900
901    Must be run as administrator.
902
903    # Errors
904
905    * `Uninitialized`, if the library has not been successfully initialized
906    * `OperatingSystem`, if the operating system is denying this feature
907    * `NoPermission`, if the calling process has insufficient permissions to
908    perform this operation
909    * `NulError`, if an issue is encountered when trying to convert a Rust
910    `String` into a `CString`.
911    * `Unknown`, on any unexpected error
912
913    # Device Support
914
915    Supports Pascal and newer fully supported devices.
916
917    Some Kepler devices are also supported (that's all NVIDIA says, no specifics).
918
919    # Platform Support
920
921    Only supports Linux.
922    */
923    // TODO: constructor for default pci_infos ^
924    // Checked against local
925    // Tested
926    #[cfg(target_os = "linux")]
927    #[doc(alias = "nvmlDeviceDiscoverGpus")]
928    pub fn discover_gpus(&self, pci_info: PciInfo) -> Result<(), NvmlError> {
929        let sym = nvml_sym(self.lib.nvmlDeviceDiscoverGpus.as_ref())?;
930
931        unsafe { nvml_try(sym(&mut pci_info.try_into()?)) }
932    }
933
934    /**
935    Gets the number of excluded GPU devices in the system.
936
937    # Device Support
938
939    Supports all devices.
940    */
941    #[doc(alias = "nvmlGetExcludedDeviceCount")]
942    pub fn excluded_device_count(&self) -> Result<u32, NvmlError> {
943        let sym = nvml_sym(self.lib.nvmlGetExcludedDeviceCount.as_ref())?;
944
945        unsafe {
946            let mut count: c_uint = mem::zeroed();
947
948            nvml_try(sym(&mut count))?;
949            Ok(count)
950        }
951    }
952
953    /**
954    Gets information for the specified excluded device.
955
956    # Errors
957
958    * `InvalidArg`, if the given index is invalid
959    * `Utf8Error`, if strings obtained from the C function are not valid Utf8
960
961    # Device Support
962
963    Supports all devices.
964    */
965    #[doc(alias = "nvmlGetExcludedDeviceInfoByIndex")]
966    pub fn excluded_device_info(&self, index: u32) -> Result<ExcludedDeviceInfo, NvmlError> {
967        let sym = nvml_sym(self.lib.nvmlGetExcludedDeviceInfoByIndex.as_ref())?;
968
969        unsafe {
970            let mut info: nvmlExcludedDeviceInfo_t = mem::zeroed();
971
972            nvml_try(sym(index, &mut info))?;
973            ExcludedDeviceInfo::try_from(info)
974        }
975    }
976}
977
978/// This `Drop` implementation ignores errors! Use the `.shutdown()` method on
979/// the `Nvml` struct
980/// if you care about handling them.
981impl Drop for Nvml {
982    #[doc(alias = "nvmlShutdown")]
983    fn drop(&mut self) {
984        unsafe {
985            self.lib.nvmlShutdown();
986
987            // SAFETY: called after the last usage of `self.lib`
988            ManuallyDrop::drop(&mut self.lib);
989        }
990    }
991}
992
993/**
994A builder struct that provides further flexibility in how NVML is initialized.
995
996# Examples
997
998Initialize NVML with a non-default name for the shared object file:
999
1000```
1001use nvml_wrapper::Nvml;
1002use std::ffi::OsStr;
1003
1004let init_result = Nvml::builder().lib_path(OsStr::new("libnvidia-ml-other-name.so")).init();
1005```
1006
1007Initialize NVML with a non-default path to the shared object file:
1008
1009```
1010use nvml_wrapper::Nvml;
1011use std::ffi::OsStr;
1012
1013let init_result = Nvml::builder().lib_path(OsStr::new("/some/path/to/libnvidia-ml.so")).init();
1014```
1015*/
1016#[derive(Debug, Clone, Eq, PartialEq, Default)]
1017pub struct NvmlBuilder<'a> {
1018    lib_path: Option<&'a OsStr>,
1019    flags: InitFlags,
1020}
1021
1022impl<'a> NvmlBuilder<'a> {
1023    /**
1024    Set the path to the NVML lib file.
1025
1026    See [`libloading`'s docs][libloading] for details about how this lib path is
1027    handled.
1028
1029    [libloading]: https://docs.rs/libloading/0.6.6/libloading/struct.Library.html#method.new
1030    */
1031    pub fn lib_path(&mut self, path: &'a OsStr) -> &mut Self {
1032        self.lib_path = Some(path);
1033        self
1034    }
1035
1036    /// Set the `InitFlags` to initialize NVML with.
1037    pub fn flags(&mut self, flags: InitFlags) -> &mut Self {
1038        self.flags = flags;
1039        self
1040    }
1041
1042    /// Perform initialization.
1043    pub fn init(&self) -> Result<Nvml, NvmlError> {
1044        let lib_path = self.lib_path.unwrap_or_else(|| LIB_PATH.as_ref());
1045
1046        if self.flags.is_empty() {
1047            Nvml::init_internal(lib_path)
1048        } else {
1049            Nvml::init_with_flags_internal(lib_path, self.flags)
1050        }
1051    }
1052}
1053
1054#[cfg(test)]
1055mod test {
1056    use super::*;
1057    use crate::bitmasks::InitFlags;
1058    use crate::error::NvmlError;
1059    use crate::test_utils::*;
1060
1061    #[test]
1062    fn init_with_flags() {
1063        Nvml::init_with_flags(InitFlags::NO_GPUS).unwrap();
1064    }
1065
1066    #[test]
1067    fn shutdown() {
1068        test(3, || nvml().shutdown())
1069    }
1070
1071    #[test]
1072    fn device_count() {
1073        test(3, || nvml().device_count())
1074    }
1075
1076    #[test]
1077    fn sys_driver_version() {
1078        test(3, || nvml().sys_driver_version())
1079    }
1080
1081    #[test]
1082    fn sys_nvml_version() {
1083        test(3, || nvml().sys_nvml_version())
1084    }
1085
1086    #[test]
1087    fn sys_cuda_driver_version() {
1088        test(3, || nvml().sys_cuda_driver_version())
1089    }
1090
1091    #[test]
1092    fn sys_cuda_driver_version_major() {
1093        test(3, || {
1094            Ok(cuda_driver_version_major(nvml().sys_cuda_driver_version()?))
1095        })
1096    }
1097
1098    #[test]
1099    fn sys_cuda_driver_version_minor() {
1100        test(3, || {
1101            Ok(cuda_driver_version_minor(nvml().sys_cuda_driver_version()?))
1102        })
1103    }
1104
1105    #[test]
1106    fn sys_process_name() {
1107        let nvml = nvml();
1108        test_with_device(3, &nvml, |device| {
1109            let processes = device.running_graphics_processes()?;
1110            match nvml.sys_process_name(processes[0].pid, 64) {
1111                Err(NvmlError::NoPermission) => Ok("No permission error".into()),
1112                v => v,
1113            }
1114        })
1115    }
1116
1117    #[test]
1118    fn device_by_index() {
1119        let nvml = nvml();
1120        test(3, || nvml.device_by_index(0))
1121    }
1122
1123    #[test]
1124    fn device_by_pci_bus_id() {
1125        let nvml = nvml();
1126        test_with_device(3, &nvml, |device| {
1127            let id = device.pci_info()?.bus_id;
1128            nvml.device_by_pci_bus_id(id)
1129        })
1130    }
1131
1132    // Can't get serial on my machine
1133    #[ignore = "my machine does not support this call"]
1134    #[test]
1135    fn device_by_serial() {
1136        let nvml = nvml();
1137
1138        #[allow(deprecated)]
1139        test_with_device(3, &nvml, |device| {
1140            let serial = device.serial()?;
1141            nvml.device_by_serial(serial)
1142        })
1143    }
1144
1145    #[test]
1146    fn device_by_uuid() {
1147        let nvml = nvml();
1148        test_with_device(3, &nvml, |device| {
1149            let uuid = device.uuid()?;
1150            nvml.device_by_uuid(uuid)
1151        })
1152    }
1153
1154    // I don't have 2 devices
1155    #[ignore = "my machine does not support this call"]
1156    #[cfg(target_os = "linux")]
1157    #[test]
1158    fn topology_common_ancestor() {
1159        let nvml = nvml();
1160        let device1 = device(&nvml);
1161        let device2 = nvml.device_by_index(1).expect("device");
1162
1163        nvml.topology_common_ancestor(&device1, &device2)
1164            .expect("TopologyLevel");
1165    }
1166
1167    // Errors on my machine
1168
1169    #[test]
1170    #[ignore = "my machine does not support this call"]
1171    fn unit_by_index() {
1172        let nvml = nvml();
1173        test(3, || nvml.unit_by_index(0))
1174    }
1175
1176    // I don't have 2 devices
1177    #[ignore = "my machine does not support this call"]
1178    #[test]
1179    fn are_devices_on_same_board() {
1180        let nvml = nvml();
1181        let device1 = device(&nvml);
1182        let device2 = nvml.device_by_index(1).expect("device");
1183
1184        nvml.are_devices_on_same_board(&device1, &device2)
1185            .expect("bool");
1186    }
1187
1188    #[cfg(target_os = "linux")]
1189    #[test]
1190    fn topology_gpu_set() {
1191        let nvml = nvml();
1192        test(3, || nvml.topology_gpu_set(0))
1193    }
1194
1195    #[test]
1196    fn hic_version() {
1197        let nvml = nvml();
1198        test(3, || nvml.hic_versions())
1199    }
1200
1201    #[test]
1202    fn unit_count() {
1203        test(3, || nvml().unit_count())
1204    }
1205
1206    #[test]
1207    fn create_event_set() {
1208        let nvml = nvml();
1209        test(3, || nvml.create_event_set())
1210    }
1211
1212    #[cfg(target_os = "linux")]
1213    #[should_panic(expected = "OperatingSystem")]
1214    #[test]
1215    fn discover_gpus() {
1216        let nvml = nvml();
1217        test_with_device(3, &nvml, |device| {
1218            let pci_info = device.pci_info()?;
1219
1220            // We don't test with admin perms and therefore expect an error
1221            match nvml.discover_gpus(pci_info) {
1222                Err(NvmlError::NoPermission) => panic!("NoPermission"),
1223                other => other,
1224            }
1225        })
1226    }
1227
1228    #[test]
1229    fn excluded_device_count() {
1230        let nvml = nvml();
1231        test(3, || nvml.excluded_device_count())
1232    }
1233
1234    #[test]
1235    fn excluded_device_info() {
1236        let nvml = nvml();
1237
1238        if nvml.excluded_device_count().unwrap() > 0 {
1239            test(3, || nvml.excluded_device_info(0))
1240        }
1241    }
1242}