Skip to content

Commit cc22198

Browse files
committed
refactor(vfio): generalize GPU passthrough sysfs handling
Signed-off-by: Patrick Riel <priel@nvidia.com>
1 parent b3f4e62 commit cc22198

7 files changed

Lines changed: 179 additions & 60 deletions

File tree

‎crates/openshell-vfio/src/bind.rs‎

Lines changed: 17 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,8 @@
22
// SPDX-License-Identifier: Apache-2.0
33

44
use crate::VfioError;
5-
use crate::sysfs::{SysfsRoot, read_sysfs_trimmed, write_sysfs};
5+
use crate::sysfs::{SysfsRoot, write_sysfs};
66
use std::collections::HashMap;
7-
use std::fs;
87
use std::sync::{LazyLock, Mutex};
98
use std::time::Duration;
109

@@ -19,20 +18,12 @@ static VFIO_ID_REFCOUNTS: LazyLock<Mutex<HashMap<String, usize>>> =
1918
LazyLock::new(|| Mutex::new(HashMap::new()));
2019

2120
pub(crate) fn current_driver_name(sysfs: &SysfsRoot, bdf: &str) -> Option<String> {
22-
let driver_link = sysfs.pci_device(bdf).join("driver");
23-
fs::read_link(&driver_link)
24-
.ok()
25-
.and_then(|p| p.file_name().map(|n| n.to_string_lossy().into_owned()))
21+
sysfs.pci_device_ref(bdf).driver_name()
2622
}
2723

2824
/// Read vendor and device IDs from sysfs and format as `"VVVV DDDD"` (no `0x` prefix).
2925
pub(crate) fn vfio_id_string(sysfs: &SysfsRoot, bdf: &str) -> Option<String> {
30-
let dev_dir = sysfs.pci_device(bdf);
31-
let vendor = read_sysfs_trimmed(&dev_dir.join("vendor")).ok()?;
32-
let device = read_sysfs_trimmed(&dev_dir.join("device")).ok()?;
33-
let vendor_hex = vendor.strip_prefix("0x").unwrap_or(&vendor);
34-
let device_hex = device.strip_prefix("0x").unwrap_or(&device);
35-
Some(format!("{vendor_hex} {device_hex}"))
26+
sysfs.pci_device_ref(bdf).vfio_id_string()
3627
}
3728

3829
/// Best-effort registration of a device's vendor:device ID with `vfio-pci`.
@@ -159,9 +150,9 @@ pub(crate) fn clear_vfio_id_refcounts() {
159150
/// with `driver_override=vfio-pci` and would silently re-bind to vfio-pci on
160151
/// the next probe event.
161152
fn cleanup_partial_bind(sysfs: &SysfsRoot, bdf: &str) {
162-
let override_path = sysfs.pci_device(bdf).join("driver_override");
163-
if override_path.exists()
164-
&& let Err(err) = write_sysfs(&override_path, "\n")
153+
let device = sysfs.pci_device_ref(bdf);
154+
if device.driver_override_path().exists()
155+
&& let Err(err) = device.clear_driver_override()
165156
{
166157
tracing::warn!(bdf, %err, "failed to clear driver_override during bind rollback");
167158
}
@@ -179,7 +170,7 @@ pub(crate) fn bind_device_to_vfio(sysfs: &SysfsRoot, bdf: &str) -> Result<bool,
179170
if drv == "vfio-pci" {
180171
return Ok(false);
181172
}
182-
let unbind_path = sysfs.pci_device(bdf).join("driver/unbind");
173+
let unbind_path = sysfs.pci_device_ref(bdf).driver_unbind_path();
183174
write_sysfs(&unbind_path, bdf).map_err(|e| VfioError::BindFailed {
184175
bdf: bdf.to_string(),
185176
reason: format!("unbind from {drv}: {e}"),
@@ -189,7 +180,7 @@ pub(crate) fn bind_device_to_vfio(sysfs: &SysfsRoot, bdf: &str) -> Result<bool,
189180

190181
register_vfio_new_id(sysfs, bdf);
191182

192-
let override_path = sysfs.pci_device(bdf).join("driver_override");
183+
let override_path = sysfs.pci_device_ref(bdf).driver_override_path();
193184
if let Err(e) = write_sysfs(&override_path, "vfio-pci") {
194185
deregister_vfio_new_id(sysfs, bdf);
195186
return Err(VfioError::BindFailed {
@@ -251,7 +242,7 @@ pub(crate) fn restore_to_host_driver_ex(
251242
bdf: &str,
252243
skip_deregister: bool,
253244
) -> Result<(), VfioError> {
254-
let dev_dir = sysfs.pci_device(bdf);
245+
let device = sysfs.pci_device_ref(bdf);
255246

256247
if !skip_deregister {
257248
// Deregister the device ID from vfio-pci's match table before
@@ -260,20 +251,21 @@ pub(crate) fn restore_to_host_driver_ex(
260251
deregister_vfio_new_id(sysfs, bdf);
261252
}
262253

263-
let unbind_path = dev_dir.join("driver/unbind");
254+
let unbind_path = device.driver_unbind_path();
264255
if unbind_path.exists() {
265256
write_sysfs(&unbind_path, bdf).map_err(|e| VfioError::UnbindFailed {
266257
bdf: bdf.to_string(),
267258
reason: format!("unbind: {e}"),
268259
})?;
269260
}
270261

271-
let override_path = dev_dir.join("driver_override");
272-
if override_path.exists() {
273-
write_sysfs(&override_path, "\n").map_err(|e| VfioError::UnbindFailed {
274-
bdf: bdf.to_string(),
275-
reason: format!("clear driver_override: {e}"),
276-
})?;
262+
if device.driver_override_path().exists() {
263+
device
264+
.clear_driver_override()
265+
.map_err(|e| VfioError::UnbindFailed {
266+
bdf: bdf.to_string(),
267+
reason: format!("clear driver_override: {e}"),
268+
})?;
277269
}
278270

279271
let probe = sysfs.drivers_probe();

‎crates/openshell-vfio/src/error.rs‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,9 @@ pub enum VfioError {
1212
#[error("GPU {bdf} is not an NVIDIA device (vendor={vendor})")]
1313
NotNvidia { bdf: String, vendor: String },
1414

15+
#[error("PCI device {bdf} is not a GPU display controller (class={class})")]
16+
NotGpu { bdf: String, class: String },
17+
1518
#[error("PCI device {bdf} has no IOMMU group - is IOMMU enabled?")]
1619
NoIommuGroup { bdf: String },
1720

‎crates/openshell-vfio/src/gpu.rs‎

Lines changed: 64 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33

44
use crate::VfioError;
55
use crate::pci::{PciBindGuard, PciInfo};
6-
use crate::sysfs::{SysfsRoot, read_sysfs_trimmed, validate_bdf};
6+
use crate::sysfs::{SysfsRoot, validate_bdf};
77
use std::fs;
88

99
const NVIDIA_VENDOR_ID: &str = "0x10de";
@@ -38,26 +38,27 @@ pub fn probe_host_nvidia_vfio_readiness(sysfs: &SysfsRoot) -> Vec<PciInfo> {
3838

3939
for entry in entries.filter_map(Result::ok) {
4040
let bdf = entry.file_name().to_string_lossy().into_owned();
41-
let dev_dir = sysfs.pci_device(&bdf);
41+
let device = sysfs.pci_device_ref(&bdf);
4242

43-
let Ok(vendor) = read_sysfs_trimmed(&dev_dir.join("vendor")) else {
43+
let Ok(vendor) = device.vendor() else {
4444
continue;
4545
};
4646
if vendor != NVIDIA_VENDOR_ID {
4747
continue;
4848
}
4949

50-
let Ok(class) = read_sysfs_trimmed(&dev_dir.join("class")) else {
50+
let Ok(class) = device.class() else {
5151
continue;
5252
};
5353
if !is_gpu_class(&class) {
5454
continue;
5555
}
5656

57-
let device = read_sysfs_trimmed(&dev_dir.join("device")).unwrap_or_default();
57+
let device_id = device.device_id().unwrap_or_default();
5858

59-
let name = read_sysfs_trimmed(&dev_dir.join("label"))
60-
.unwrap_or_else(|_| format!("NVIDIA {device}"));
59+
let name = device
60+
.read_trimmed("label")
61+
.unwrap_or_else(|_| format!("NVIDIA {device_id}"));
6162

6263
let Ok(iommu_group) = sysfs.iommu_group(&bdf) else {
6364
continue;
@@ -67,7 +68,7 @@ pub fn probe_host_nvidia_vfio_readiness(sysfs: &SysfsRoot) -> Vec<PciInfo> {
6768
bdf,
6869
name,
6970
vendor,
70-
device,
71+
device: device_id,
7172
iommu_group,
7273
});
7374
}
@@ -86,28 +87,28 @@ pub fn prepare_gpu_for_passthrough(
8687
) -> Result<PciBindGuard, VfioError> {
8788
validate_bdf(bdf)?;
8889

89-
let dev_dir = sysfs.pci_device(bdf);
90-
if !dev_dir.exists() {
90+
let device = sysfs.pci_device_ref(bdf);
91+
if !device.exists() {
9192
return Err(VfioError::GpuNotFound {
9293
bdf: bdf.to_string(),
9394
});
9495
}
9596

96-
let vendor = read_sysfs_trimmed(&dev_dir.join("vendor"))?;
97-
if vendor != NVIDIA_VENDOR_ID {
98-
return Err(VfioError::NotNvidia {
97+
let class = device.class()?;
98+
if !is_gpu_class(&class) {
99+
return Err(VfioError::NotGpu {
99100
bdf: bdf.to_string(),
100-
vendor,
101+
class,
101102
});
102103
}
103104

104-
let iommu_group = sysfs.iommu_group(bdf)?;
105+
let iommu_group = device.iommu_group()?;
105106
let group_devices = sysfs.iommu_group_devices(iommu_group)?;
106107
let peers: Vec<String> = group_devices.into_iter().filter(|d| d != bdf).collect();
107108

108109
let mut bound_companions = Vec::new();
109110
for peer in &peers {
110-
if !sysfs.pci_device(peer).exists() {
111+
if !sysfs.pci_device_ref(peer).exists() {
111112
continue;
112113
}
113114
match crate::bind::bind_device_to_vfio(sysfs, peer) {
@@ -267,6 +268,53 @@ mod tests {
267268
assert_eq!(guard.bdf, "0000:2d:00.0");
268269
}
269270

271+
#[test]
272+
fn test_prepare_gpu_accepts_non_nvidia_gpu() {
273+
let _refcount_guard = test_refcounts::guard();
274+
test_refcounts::clear("8086 56a0");
275+
let (tmp, sysfs) = setup_mock_sysfs();
276+
create_pci_device(
277+
&sysfs,
278+
tmp.path(),
279+
"0000:03:00.0",
280+
"0x8086",
281+
"0x56a0",
282+
"0x030200",
283+
11,
284+
);
285+
create_probe_file(&sysfs);
286+
set_mock_driver(&sysfs, "0000:03:00.0", "vfio-pci");
287+
288+
let guard = prepare_gpu_for_passthrough(&sysfs, "0000:03:00.0").unwrap();
289+
290+
assert!(guard.companion_bdfs.is_empty());
291+
assert_eq!(guard.bdf, "0000:03:00.0");
292+
}
293+
294+
#[test]
295+
fn test_prepare_gpu_rejects_non_gpu_device() {
296+
let (tmp, sysfs) = setup_mock_sysfs();
297+
create_pci_device(
298+
&sysfs,
299+
tmp.path(),
300+
"0000:04:00.0",
301+
"0x8086",
302+
"0x1234",
303+
"0x020000",
304+
12,
305+
);
306+
307+
let err = prepare_gpu_for_passthrough(&sysfs, "0000:04:00.0").unwrap_err();
308+
309+
assert!(matches!(
310+
err,
311+
VfioError::NotGpu {
312+
bdf,
313+
class
314+
} if bdf == "0000:04:00.0" && class == "0x020000"
315+
));
316+
}
317+
270318
#[test]
271319
fn test_prepare_gpu_solo_iommu_group_no_companions() {
272320
let _refcount_guard = test_refcounts::guard();

‎crates/openshell-vfio/src/lib.rs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313
//! - [`bind`] - generic bind/unbind/probe mechanics
1414
//! - [`pci`] - generic device types and the public passthrough API
1515
//! - [`reconcile`] - crash-recovery for stale bindings
16-
//! - [`gpu`] - NVIDIA-specific helpers consumed by the VM driver's GPU inventory
16+
//! - [`gpu`] - GPU passthrough helpers plus NVIDIA-specific inventory probing
1717
1818
pub mod bind;
1919
pub mod error;

‎crates/openshell-vfio/src/pci.rs‎

Lines changed: 15 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
// SPDX-License-Identifier: Apache-2.0
33

44
use crate::VfioError;
5-
use crate::sysfs::{SysfsRoot, read_sysfs_trimmed, validate_bdf};
5+
use crate::sysfs::{SysfsRoot, validate_bdf};
66
use std::collections::BTreeSet;
77
use std::fs;
88
use std::path::Path;
@@ -234,9 +234,9 @@ pub fn probe_host_vfio_candidates(sysfs: &SysfsRoot, vendor_filter: Option<&str>
234234

235235
for entry in entries.filter_map(Result::ok) {
236236
let bdf = entry.file_name().to_string_lossy().into_owned();
237-
let dev_dir = sysfs.pci_device(&bdf);
237+
let device = sysfs.pci_device_ref(&bdf);
238238

239-
let Ok(vendor) = read_sysfs_trimmed(&dev_dir.join("vendor")) else {
239+
let Ok(vendor) = device.vendor() else {
240240
continue;
241241
};
242242
if let Some(filter) = vendor_filter
@@ -245,12 +245,13 @@ pub fn probe_host_vfio_candidates(sysfs: &SysfsRoot, vendor_filter: Option<&str>
245245
continue;
246246
}
247247

248-
let device = read_sysfs_trimmed(&dev_dir.join("device")).unwrap_or_default();
248+
let device_id = device.device_id().unwrap_or_default();
249249

250-
let name = read_sysfs_trimmed(&dev_dir.join("label"))
251-
.unwrap_or_else(|_| format!("{vendor} {device}"));
250+
let name = device
251+
.read_trimmed("label")
252+
.unwrap_or_else(|_| format!("{vendor} {device_id}"));
252253

253-
let Ok(iommu_group) = sysfs.iommu_group(&bdf) else {
254+
let Ok(iommu_group) = device.iommu_group() else {
254255
tracing::debug!(bdf, "skipping PCI device without IOMMU group");
255256
continue;
256257
};
@@ -259,7 +260,7 @@ pub fn probe_host_vfio_candidates(sysfs: &SysfsRoot, vendor_filter: Option<&str>
259260
bdf,
260261
name,
261262
vendor,
262-
device,
263+
device: device_id,
263264
iommu_group,
264265
});
265266
}
@@ -281,14 +282,14 @@ pub fn probe_host_vfio_candidates(sysfs: &SysfsRoot, vendor_filter: Option<&str>
281282
pub fn validate_pci_for_passthrough(sysfs: &SysfsRoot, bdf: &str) -> Result<(), VfioError> {
282283
validate_bdf(bdf)?;
283284

284-
let dev_dir = sysfs.pci_device(bdf);
285-
if !dev_dir.exists() {
285+
let device = sysfs.pci_device_ref(bdf);
286+
if !device.exists() {
286287
return Err(VfioError::DeviceNotFound {
287288
bdf: bdf.to_string(),
288289
});
289290
}
290291

291-
let iommu_group = sysfs.iommu_group(bdf)?;
292+
let iommu_group = device.iommu_group()?;
292293
let group_devices = sysfs.iommu_group_devices(iommu_group)?;
293294
let peers: Vec<String> = group_devices.into_iter().filter(|d| d != bdf).collect();
294295

@@ -374,7 +375,7 @@ pub fn validate_pci_group_for_passthrough(
374375

375376
for bdf in bdfs {
376377
validate_bdf(bdf)?;
377-
if !sysfs.pci_device(bdf).exists() {
378+
if !sysfs.pci_device_ref(bdf).exists() {
378379
return Err(VfioError::DeviceNotFound {
379380
bdf: (*bdf).to_string(),
380381
});
@@ -390,9 +391,9 @@ pub fn validate_pci_group_for_passthrough(
390391
});
391392
}
392393

393-
let expected_group = sysfs.iommu_group(primary)?;
394+
let expected_group = sysfs.pci_device_ref(primary).iommu_group()?;
394395
for bdf in companions {
395-
let g = sysfs.iommu_group(bdf)?;
396+
let g = sysfs.pci_device_ref(bdf).iommu_group()?;
396397
if g != expected_group {
397398
return Err(VfioError::GroupMismatch {
398399
bdf: (*bdf).to_string(),

‎crates/openshell-vfio/src/reconcile.rs‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
// SPDX-License-Identifier: Apache-2.0
33

44
use crate::pci::PciBindState;
5-
use crate::sysfs::{SysfsRoot, read_sysfs_trimmed, write_sysfs};
5+
use crate::sysfs::{SysfsRoot, write_sysfs};
66
use std::fs;
77
use std::path::Path;
88

@@ -45,8 +45,8 @@ pub fn reconcile_stale_bindings(sysfs: &SysfsRoot, state_path: &Path) -> Vec<Str
4545
restored.push(binding.bdf.clone());
4646
}
4747
_ => {
48-
let override_path = sysfs.pci_device(&binding.bdf).join("driver_override");
49-
if let Ok(val) = read_sysfs_trimmed(&override_path)
48+
let device = sysfs.pci_device_ref(&binding.bdf);
49+
if let Ok(val) = device.driver_override()
5050
&& val == "vfio-pci"
5151
{
5252
tracing::warn!(
@@ -55,7 +55,7 @@ pub fn reconcile_stale_bindings(sysfs: &SysfsRoot, state_path: &Path) -> Vec<Str
5555
"stale driver_override detected, clearing and re-probing"
5656
);
5757
crate::bind::deregister_vfio_new_id(sysfs, &binding.bdf);
58-
if let Err(err) = write_sysfs(&override_path, "\n") {
58+
if let Err(err) = device.clear_driver_override() {
5959
tracing::error!(bdf = %binding.bdf, %err, "failed to clear stale driver_override");
6060
failed_bindings.push(binding.clone());
6161
continue;

0 commit comments

Comments
 (0)