1use std::path::{Path, PathBuf};
4
5use crate::Error;
6
7#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
17#[non_exhaustive]
18pub enum Device {
19 #[default]
21 Auto,
22 Render(PathBuf),
25 Video(PathBuf),
27}
28
29impl Device {
30 #[cfg_attr(
32 not(all(target_os = "linux", any(feature = "vaapi", feature = "nvidia"))),
33 allow(dead_code, reason = "only the VA-API and NVIDIA backends open one")
34 )]
35 pub(crate) fn render(&self) -> Option<&Path> {
36 match self {
37 Self::Render(path) => Some(path),
38 _ => None,
39 }
40 }
41
42 #[cfg_attr(
44 not(all(target_os = "linux", feature = "v4l2")),
45 allow(dead_code, reason = "only the V4L2 backends open one")
46 )]
47 pub(crate) fn video(&self) -> Option<&Path> {
48 match self {
49 Self::Video(path) => Some(path),
50 _ => None,
51 }
52 }
53
54 pub(crate) fn takes(&self, drives: Drives) -> Result<bool, Error> {
59 match (self, drives) {
60 (Self::Auto, _) | (_, Drives::Own) => Ok(true),
61 (Self::Render(_), Drives::Render) | (Self::Video(_), Drives::Video) => Ok(true),
62 (Self::Render(path), Drives::Nvidia) => nvidia(path),
63 _ => Ok(false),
64 }
65 }
66}
67
68impl std::fmt::Display for Device {
69 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
70 match self {
71 Self::Auto => f.write_str("any device"),
72 Self::Render(path) => write!(f, "render node {}", path.display()),
73 Self::Video(path) => write!(f, "codec node {}", path.display()),
74 }
75 }
76}
77
78#[derive(Clone, Copy, Debug, PartialEq, Eq)]
80#[allow(dead_code, reason = "a build without a backend of some kind never names that kind")]
81pub(crate) enum Drives {
82 Own,
84 Render,
86 Nvidia,
88 Video,
90}
91
92#[cfg(target_os = "linux")]
94fn nvidia(path: &Path) -> Result<bool, Error> {
95 Ok(field(&uevent(path)?, "DRIVER") == Some("nvidia"))
96}
97
98#[cfg(not(target_os = "linux"))]
99fn nvidia(_path: &Path) -> Result<bool, Error> {
100 Ok(false)
101}
102
103#[cfg(target_os = "linux")]
105fn uevent(path: &Path) -> Result<String, Error> {
106 use std::os::unix::fs::{FileTypeExt, MetadataExt};
107
108 let failed = |err: &dyn std::fmt::Display| Error::codec(anyhow::anyhow!("{}: {err}", path.display()));
109 let meta = std::fs::metadata(path).map_err(|err| failed(&err))?;
110 if !meta.file_type().is_char_device() {
111 return Err(failed(&"not a device node"));
112 }
113 let rdev = meta.rdev();
114 let sysfs = format!(
115 "/sys/dev/char/{}:{}/device/uevent",
116 libc::major(rdev),
117 libc::minor(rdev)
118 );
119 std::fs::read_to_string(&sysfs).map_err(|err| failed(&format_args!("{sysfs}: {err}")))
120}
121
122#[cfg(target_os = "linux")]
124fn field<'a>(uevent: &'a str, key: &str) -> Option<&'a str> {
125 uevent
126 .lines()
127 .find_map(|line| line.strip_prefix(key)?.strip_prefix('='))
128}
129
130#[cfg(all(target_os = "linux", feature = "nvidia"))]
132#[derive(Clone, Copy, Debug, PartialEq, Eq)]
133pub(crate) struct Pci {
134 pub domain: u32,
135 pub bus: u32,
136 pub device: u32,
137}
138
139#[cfg(all(target_os = "linux", feature = "nvidia"))]
140impl Pci {
141 pub(crate) fn of(path: &Path) -> Result<Self, Error> {
143 let uevent = uevent(path)?;
144 let slot = field(&uevent, "PCI_SLOT_NAME")
145 .ok_or_else(|| Error::codec(anyhow::anyhow!("{} is not a PCI device", path.display())))?;
146 Self::parse(slot)
147 .ok_or_else(|| Error::codec(anyhow::anyhow!("{}: malformed PCI address {slot}", path.display())))
148 }
149
150 fn parse(slot: &str) -> Option<Self> {
152 let (domain, rest) = slot.split_once(':')?;
153 let (bus, rest) = rest.split_once(':')?;
154 let (device, _function) = rest.split_once('.')?;
155 let hex = |s: &str| u32::from_str_radix(s, 16).ok();
156 Some(Self {
157 domain: hex(domain)?,
158 bus: hex(bus)?,
159 device: hex(device)?,
160 })
161 }
162
163 pub(crate) fn find(self, devices: impl IntoIterator<Item = (usize, Self)>) -> Option<usize> {
165 devices
166 .into_iter()
167 .find_map(|(ordinal, pci)| (pci == self).then_some(ordinal))
168 }
169}
170
171#[cfg(test)]
172mod tests {
173 use super::*;
174
175 #[test]
176 fn a_named_node_steers_to_the_backends_that_drive_its_kind() {
177 let render = Device::Render("/dev/dri/renderD129".into());
178 let video = Device::Video("/dev/video11".into());
179 for drives in [Drives::Own, Drives::Render, Drives::Nvidia, Drives::Video] {
180 assert!(Device::Auto.takes(drives).unwrap(), "{drives:?} refused Auto");
181 }
182 assert!(render.takes(Drives::Own).unwrap());
183 assert!(render.takes(Drives::Render).unwrap());
184 assert!(!render.takes(Drives::Video).unwrap());
185 assert!(video.takes(Drives::Own).unwrap());
186 assert!(video.takes(Drives::Video).unwrap());
187 assert!(!video.takes(Drives::Render).unwrap());
188 assert!(!video.takes(Drives::Nvidia).unwrap());
189 }
190
191 #[cfg(target_os = "linux")]
194 #[test]
195 fn a_missing_render_node_fails_the_nvidia_check() {
196 let missing = Device::Render("/dev/dri/renderD999-missing".into());
197 assert!(missing.takes(Drives::Nvidia).is_err());
198 let file = Device::Render("/proc/self/status".into());
199 assert!(file.takes(Drives::Nvidia).is_err());
200 }
201
202 #[cfg(target_os = "linux")]
203 #[test]
204 fn uevent_fields_are_read_by_exact_key() {
205 let uevent = "DRIVER=nvidia\nPCI_CLASS=30000\nPCI_SLOT_NAME=0000:01:00.0\n";
206 assert_eq!(field(uevent, "DRIVER"), Some("nvidia"));
207 assert_eq!(field(uevent, "PCI_SLOT_NAME"), Some("0000:01:00.0"));
208 assert_eq!(field(uevent, "PCI"), None);
209 }
210
211 #[cfg(all(target_os = "linux", feature = "nvidia"))]
212 #[test]
213 fn a_render_node_maps_to_the_cuda_device_at_its_pci_address() {
214 let first = Pci::parse("0000:01:00.0").unwrap();
215 let second = Pci::parse("0001:a1:1f.0").unwrap();
216 assert_eq!(
217 second,
218 Pci {
219 domain: 1,
220 bus: 0xa1,
221 device: 0x1f
222 }
223 );
224 let devices = [(0, first), (1, second)];
225 assert_eq!(first.find(devices), Some(0));
226 assert_eq!(second.find(devices), Some(1));
227 assert_eq!(Pci::parse("0000:02:00.0").unwrap().find(devices), None);
228 assert_eq!(Pci::parse("0000:01:00"), None);
229 }
230}