Skip to main content

tilo_presentation/
device.rs

1//! The identity of a DRM device node.
2//!
3//! A GPU is named to the kernel by the numbers of its device node
4//! (`/dev/dri/renderD128`); that is the identity a compositor and a process
5//! handing it frames agree on.
6
7use std::path::Path;
8
9/// The (major, minor) of the device node at `path`, as the filesystem
10/// reports it; `None` where the path is no device node.
11#[cfg(target_os = "linux")]
12#[must_use]
13pub fn device_numbers(path: &Path) -> Option<(u32, u32)> {
14    use std::os::unix::fs::MetadataExt as _;
15    let device = std::fs::metadata(path).ok()?.rdev();
16    // A file that is not a device node reports 0, which names no GPU.
17    if 0 == device {
18        return None;
19    }
20    Some((libc::major(device), libc::minor(device)))
21}
22
23#[cfg(not(target_os = "linux"))]
24#[must_use]
25pub fn device_numbers(_path: &Path) -> Option<(u32, u32)> {
26    None
27}
28
29#[cfg(all(test, target_os = "linux"))]
30mod tests {
31    use super::*;
32
33    /// `device_numbers` of a path: `(row, path, numbers)`. Each row was a test of its own, the
34    /// second with two paths, and a failure names its row and path.
35    #[test]
36    fn a_path_names_its_devices_numbers_or_no_gpu() {
37        let file = std::env::current_exe().expect("this test's own binary");
38        let rows = [
39            (
40                "a_device_node_is_named_by_its_numbers",
41                Path::new("/dev/null"),
42                Some((1, 3)),
43            ),
44            (
45                "a_file_with_no_device_behind_it_names_no_gpu",
46                file.as_path(),
47                None,
48            ),
49            (
50                "a_file_with_no_device_behind_it_names_no_gpu",
51                Path::new("/nonexistent/renderD128"),
52                None,
53            ),
54        ];
55        for (row, path, numbers) in rows {
56            assert_eq!(device_numbers(path), numbers, "{row}: {}", path.display());
57        }
58    }
59}