* [PATCH v5 1/2] gpu: nova-core: publish typed SR-IOV PF APIs
2026-12-04 14:48 [PATCH v5 0/2] vfio/nova-vgpu: add the NVIDIA VFIO variant driver Simon Song
@ 2026-12-04 14:48 ` Simon Song
2026-12-04 14:48 ` [PATCH v5 2/2] vfio/nova-vgpu: add the Rust VFIO variant driver Simon Song
1 sibling, 0 replies; 6+ messages in thread
From: Simon Song @ 2026-12-04 14:48 UTC (permalink / raw)
To: dakr, acourbot, kvm, rust-for-linux, nova-gpu, linux-pci
Cc: Zhi Wang, alex, jgg, yishaih, skolothumtho, kevin.tian, airlied,
simona, ojeda, alex.gaynor, boqun.feng, gary, bjorn3_gh, lossin,
a.hindborg, aliceryhl, tmgross, jhubbard, ecourtney, cjia, smitra,
kjaju, alkumar, ankita, aniketa, kwankhede, targupta,
linux-kernel, zhiwang, boqun, daniel.almeida, tamird, work, jgg,
bhelgaas, kwilczynski, dri-devel, peter, xinmengs,
Liam R. Howlett, linux-mm, Lorenzo Stoakes
From: Zhi Wang <zhiw@nvidia.com>
Register NovaCoreVfApi as typed SR-IOV PF data once the GPU is initialized.
Enable and disable VFs through the sriov_enable() and sriov_disable()
callbacks. The VF registration removes VFs before dropping its PF API
data. Declare the registration before the GPU so its borrowed services
remain valid through VF teardown.
Expose a VF-side handle that borrows these services for each operation.
Return an owned instance on open and close it on drop while the VF
remains bound.
Signed-off-by: Zhi Wang <zhiw@nvidia.com>
Signed-off-by: Simon Song <xinmengs@nvidia.com>
---
drivers/gpu/nova-core/driver.rs | 34 ++++-
drivers/gpu/nova-core/nova_core.rs | 3 +-
drivers/gpu/nova-core/vgpu.rs | 1 -
drivers/gpu/nova-core/vgpu/vgpu_api.rs | 171 +++++++++++++++++++------
4 files changed, 167 insertions(+), 42 deletions(-)
diff --git a/drivers/gpu/nova-core/driver.rs b/drivers/gpu/nova-core/driver.rs
index bea1b1b0844c9..34c35b5e648fc 100644
--- a/drivers/gpu/nova-core/driver.rs
+++ b/drivers/gpu/nova-core/driver.rs
@@ -24,7 +24,8 @@
use crate::{
api::NovaCoreApi,
- gpu::Gpu, //
+ gpu::Gpu,
+ vgpu::vgpu_api::NovaCoreVfApi, //
};
/// Counter for generating unique auxiliary device IDs.
@@ -35,6 +36,10 @@ pub(crate) struct NovaCore<'bound> {
#[allow(clippy::type_complexity)]
#[uses('gpu: invariant)]
_reg: auxiliary::Registration<'gpu, ForLt!(NovaCoreApi<'_>)>,
+ #[allow(clippy::type_complexity)]
+ #[pin]
+ #[uses('gpu: invariant)]
+ _vf_registration: pci::VfRegistration<'gpu, ForLt!(NovaCoreVfApi<'_>)>,
#[pin]
#[uses('bar1)]
pub(crate) gpu: Gpu<'bar>,
@@ -107,6 +112,10 @@ fn probe<'bound>(
try_pin_init!(NovaCore {
_: {
+ if pdev.is_virtfn() {
+ return Err(ENODEV);
+ }
+
pdev.enable_device_mem()?;
pdev.set_master();
},
@@ -138,6 +147,12 @@ fn probe<'bound>(
Ok(())
}),
+ // SAFETY: The registration is stored in `NovaCore`, this driver's bus device
+ // private data.
+ _vf_registration <- unsafe {
+ pci::VfRegistration::new(pdev, NovaCoreVfApi::new(pdev, gpu))
+ },
+
// SAFETY: `NovaCore` is dropped when the device is unbound; i.e. `mem::forget()` is
// never called on it.
_reg: unsafe {
@@ -154,4 +169,21 @@ fn probe<'bound>(
},
})
}
+
+ fn sriov_enable<'a>(
+ _dev: &'a pci::Device<Core<'_>>,
+ _this: Pin<&Self::Data<'a>>,
+ token: pci::SriovEnable<'a>,
+ ) -> Result<pci::SriovEnabled<'a>> {
+ token.enable_all()
+ }
+
+ fn sriov_disable<'a>(
+ _dev: &'a pci::Device<Core<'_>>,
+ _this: Pin<&Self::Data<'a>>,
+ token: pci::SriovDisable<'a>,
+ ) -> Result {
+ token.disable();
+ Ok(())
+ }
}
diff --git a/drivers/gpu/nova-core/nova_core.rs b/drivers/gpu/nova-core/nova_core.rs
index 4185717245438..fecd6341c997a 100644
--- a/drivers/gpu/nova-core/nova_core.rs
+++ b/drivers/gpu/nova-core/nova_core.rs
@@ -34,9 +34,10 @@
use debugfs::DebugfsData;
-#[cfg(CONFIG_PCI_IOV)]
pub use vgpu::vgpu_api::{
NovaCoreVfApi,
+ NovaCoreVfApiHandle,
+ VgpuInstance,
VgpuTypeInfo, //
};
diff --git a/drivers/gpu/nova-core/vgpu.rs b/drivers/gpu/nova-core/vgpu.rs
index f2dd5e73f8ee8..b792a446b2b66 100644
--- a/drivers/gpu/nova-core/vgpu.rs
+++ b/drivers/gpu/nova-core/vgpu.rs
@@ -42,7 +42,6 @@
mod hal;
mod instance;
mod scrubber;
-#[cfg_attr(not(CONFIG_PCI_IOV), expect(dead_code, unreachable_pub))]
pub(crate) mod vgpu_api;
mod vram;
diff --git a/drivers/gpu/nova-core/vgpu/vgpu_api.rs b/drivers/gpu/nova-core/vgpu/vgpu_api.rs
index b263e96098a80..1064e461cd269 100644
--- a/drivers/gpu/nova-core/vgpu/vgpu_api.rs
+++ b/drivers/gpu/nova-core/vgpu/vgpu_api.rs
@@ -8,7 +8,8 @@
use kernel::{
device,
pci,
- prelude::*, //
+ prelude::*,
+ types::ForLt, //
};
use crate::{
@@ -51,27 +52,38 @@ fn from(vgpu_properties: &VgpuProperties) -> Self {
}
/// PF-owned operations available while a VF driver is bound.
-pub struct NovaCoreVfApi<'gpu> {
+#[pin_data]
+pub struct NovaCoreVfApi<'gpu>
+where
+ // The GPU resources are invariant in their lifetime, which outlives this API borrow.
+ exists<'gpu_resources>: 'gpu,
+{
pdev: &'gpu pci::Device<device::Bound>,
- cmdq: &'gpu Cmdq<'gpu>,
- vgpu: Option<&'gpu VgpuManager<'gpu>>,
+ #[uses('gpu_resources: invariant)]
+ cmdq: &'gpu Cmdq<'gpu_resources>,
+ #[uses('gpu_resources: invariant)]
+ vgpu: Option<&'gpu VgpuManager<'gpu_resources>>,
total_vfs: Option<NonZero<u16>>,
}
impl<'gpu> NovaCoreVfApi<'gpu> {
- #[expect(dead_code)]
- pub(crate) fn new(gpu: &'gpu Gpu<'gpu>, pdev: &'gpu pci::Device<device::Bound>) -> Self {
- Self {
+ /// Creates the PF services that VF drivers access through the VF registration.
+ pub(crate) fn new<'res: 'gpu>(
+ pdev: &'gpu pci::Device<device::Bound>,
+ gpu: Pin<&'gpu Gpu<'res>>,
+ ) -> impl PinInit<Self, Error> + use<'gpu, 'res> {
+ let gpu = gpu.get_ref();
+ try_pin_init!(Self {
pdev,
cmdq: gpu.cmdq(),
vgpu: gpu.vgpu_manager(),
total_vfs: gpu.vgpu_total_vfs(),
- }
+ })
}
/// Returns whether the PF booted with vGPU support enabled.
pub fn is_available(&self) -> bool {
- self.vgpu.is_some()
+ self.with_vgpu(|vgpu| vgpu.is_some())
}
fn gfid(&self, gfid: u32) -> Result<Gfid> {
@@ -81,11 +93,29 @@ fn gfid(&self, gfid: u32) -> Result<Gfid> {
}
impl NovaCoreVfApi<'_> {
+ /// Obtains the enabled PF services for a bound VF.
+ pub fn handle(vf: &pci::Device<device::Bound>) -> Result<NovaCoreVfApiHandle<'_>> {
+ let handle = NovaCoreVfApiHandle { vf };
+ handle.with(|api| {
+ if api.is_available() {
+ Ok(())
+ } else {
+ Err(ENODEV)
+ }
+ })?;
+ Ok(handle)
+ }
+
/// Creates and boots an instance for a one-based VF ID.
///
/// `sbdf` encodes the VF address as `(segment << 16) | (bus << 8) | devfn`.
/// `vm_pid` identifies the VM process's thread group. This call may sleep.
- pub fn open_instance(&self, gfid: u32, sbdf: u32, vm_pid: u32) -> Result<VgpuTypeInfo> {
+ pub fn open_instance(
+ self: Pin<&Self>,
+ gfid: u32,
+ sbdf: u32,
+ vm_pid: u32,
+ ) -> Result<VgpuTypeInfo> {
let dev = self.pdev.as_ref();
let gfid = self.gfid(gfid)?;
let dbdf = Dbdf::from_raw(sbdf);
@@ -97,29 +127,31 @@ pub fn open_instance(&self, gfid: u32, sbdf: u32, vm_pid: u32) -> Result<VgpuTyp
dbdf.into_raw()
);
- let cmdq = self.cmdq;
- let vgpu = self.vgpu.ok_or(ENODEV)?;
-
- let type_id = query_assigned_vf_type(dev, cmdq, dbdf)?;
- dev_dbg!(
- dev,
- "vgpu_open: gfid={} assigned type_id={}\n",
- gfid.get(),
- type_id
- );
-
- let vgpu_properties = query_vgpu_properties(dev, cmdq, type_id)?;
- dev_dbg!(
- dev,
- "vgpu_open: gfid={} vgpu_type={} fb_length={:#x}\n",
- gfid.get(),
- vgpu_properties.type_id,
- vgpu_properties.fb_length
- );
-
- vgpu.create_instance(InstanceInfo::new(gfid, dbdf, &vgpu_properties, vm_pid))?;
-
- Ok(VgpuTypeInfo::from(&*vgpu_properties))
+ self.with_project_ref(|this| {
+ let cmdq = *this.cmdq;
+ let vgpu = this.vgpu.ok_or(ENODEV)?;
+
+ let type_id = query_assigned_vf_type(dev, cmdq, dbdf)?;
+ dev_dbg!(
+ dev,
+ "vgpu_open: gfid={} assigned type_id={}\n",
+ gfid.get(),
+ type_id
+ );
+
+ let vgpu_properties = query_vgpu_properties(dev, cmdq, type_id)?;
+ dev_dbg!(
+ dev,
+ "vgpu_open: gfid={} vgpu_type={} fb_length={:#x}\n",
+ gfid.get(),
+ vgpu_properties.type_id,
+ vgpu_properties.fb_length
+ );
+
+ vgpu.create_instance(InstanceInfo::new(gfid, dbdf, &vgpu_properties, vm_pid))?;
+
+ Ok(VgpuTypeInfo::from(&*vgpu_properties))
+ })
}
/// Tears down an instance, retaining resources if firmware cleanup fails.
@@ -131,11 +163,13 @@ pub fn close_instance(&self, gfid: u32) -> Result {
dev_dbg!(dev, "vgpu_close: gfid={}\n", gfid.get());
- let result = self.vgpu.ok_or(ENODEV)?.close_instance(gfid);
- if let Err(error) = result {
- dev_err!(dev, "vgpu_close: gfid={} failed: {:?}\n", gfid.get(), error);
- }
- result
+ self.with_vgpu(|vgpu| {
+ let result = vgpu.ok_or(ENODEV)?.close_instance(gfid);
+ if let Err(error) = result {
+ dev_err!(dev, "vgpu_close: gfid={} failed: {:?}\n", gfid.get(), error);
+ }
+ result
+ })
}
/// Resets an instance and scrubs its guest VRAM. This call may sleep.
@@ -145,9 +179,68 @@ pub fn reset_instance(&self, gfid: u32) -> Result {
dev_dbg!(dev, "vgpu_reset: gfid={}\n", gfid.get());
- self.vgpu.ok_or(ENODEV)?.reset_instance(gfid)?;
+ self.with_vgpu(|vgpu| vgpu.ok_or(ENODEV)?.reset_instance(gfid))?;
dev_dbg!(dev, "vgpu_reset: gfid={} done\n", gfid.get());
Ok(())
}
}
+
+/// Access to PF services for the lifetime of a VF driver binding.
+///
+/// The PF's registration keeps these services available until VF removal
+/// completes and is dropped before the GPU resources they borrow.
+pub struct NovaCoreVfApiHandle<'vf> {
+ vf: &'vf pci::Device<device::Bound>,
+}
+
+impl<'vf> NovaCoreVfApiHandle<'vf> {
+ /// Borrows the typed PF services for a single operation.
+ fn with<R>(
+ &self,
+ f: impl for<'borrow, 'data> FnOnce(Pin<&'borrow NovaCoreVfApi<'data>>) -> Result<R>,
+ ) -> Result<R> {
+ self.vf
+ .vf_registration_data_with::<ForLt!(NovaCoreVfApi<'_>), _>(f)?
+ }
+
+ /// Creates and boots an instance that closes when dropped.
+ ///
+ /// The arguments have the same meaning as in [`NovaCoreVfApi::open_instance`].
+ pub fn open(&self, gfid: u32, dbdf: u32, vm_pid: u32) -> Result<VgpuInstance<'vf>> {
+ let type_info = self.with(|api| api.open_instance(gfid, dbdf, vm_pid))?;
+ Ok(VgpuInstance {
+ api: Self { vf: self.vf },
+ gfid,
+ type_info,
+ })
+ }
+
+ /// Resets an active instance and scrubs its guest VRAM.
+ pub fn reset(&self, gfid: u32) -> Result {
+ self.with(|api| api.reset_instance(gfid))
+ }
+}
+
+/// An active instance whose teardown runs while its VF driver remains bound.
+///
+/// Dropping this guard may sleep while firmware teardown completes.
+pub struct VgpuInstance<'vf> {
+ api: NovaCoreVfApiHandle<'vf>,
+ gfid: u32,
+ type_info: VgpuTypeInfo,
+}
+
+impl VgpuInstance<'_> {
+ /// Returns the assigned PCI IDs and BAR1 aperture size.
+ #[inline]
+ pub fn type_info(&self) -> &VgpuTypeInfo {
+ &self.type_info
+ }
+}
+
+impl Drop for VgpuInstance<'_> {
+ fn drop(&mut self) {
+ let _ = self.api.with(|api| api.close_instance(self.gfid));
+ }
+}
--
2.43.7
^ permalink raw reply related [flat|nested] 6+ messages in thread* [PATCH v5 2/2] vfio/nova-vgpu: add the Rust VFIO variant driver
2026-12-04 14:48 [PATCH v5 0/2] vfio/nova-vgpu: add the NVIDIA VFIO variant driver Simon Song
2026-12-04 14:48 ` [PATCH v5 1/2] gpu: nova-core: publish typed SR-IOV PF APIs Simon Song
@ 2026-12-04 14:48 ` Simon Song
2026-12-04 23:12 ` Alex Williamson
1 sibling, 1 reply; 6+ messages in thread
From: Simon Song @ 2026-12-04 14:48 UTC (permalink / raw)
To: dakr, acourbot, kvm, rust-for-linux, nova-gpu, linux-pci
Cc: alex, jgg, yishaih, skolothumtho, kevin.tian, airlied, simona,
ojeda, alex.gaynor, boqun.feng, gary, bjorn3_gh, lossin,
a.hindborg, aliceryhl, tmgross, jhubbard, ecourtney, cjia, smitra,
kjaju, alkumar, ankita, aniketa, kwankhede, targupta,
linux-kernel, zhiwang, zhiw, boqun, daniel.almeida, tamird, work,
jgg, bhelgaas, kwilczynski, dri-devel, peter, xinmengs,
Liam R. Howlett, linux-mm, Lorenzo Stoakes
From: Danilo Krummrich <dakr@kernel.org>
NVIDIA vGPU VFs need nova-core to manage their instances when assigned
to userspace through VFIO.
Add a Rust VFIO PCI variant driver that uses the typed SR-IOV PF APIs
to create an instance on first open and close it on last close. Expose
the assigned device and subsystem IDs, enforce the assigned BAR1
aperture, and reset the active vGPU instance on PCI reset.
Refuse VFIO_DEVICE_IOEVENTFD for a vGPU, since the VFIO PCI core would
write to the BAR without the BAR1 limit, and add vfio::DEVICE_IOEVENTFD
for that.
Match the supported NVIDIA devices through VFIO override-only entries.
Devices without an available Nova vGPU interface use ordinary PCI
passthrough.
Register the VFIO device from probe and keep the Registration in the
PCI driver data, so that unbind unregisters it. Extend the GPU build
rules to make nova-core crate metadata available to the VFIO driver and
export the Rust symbols it references.
Signed-off-by: Danilo Krummrich <dakr@kernel.org>
Signed-off-by: Zhi Wang <zhiw@nvidia.com>
Signed-off-by: Simon Song <xinmengs@nvidia.com>
---
drivers/gpu/Makefile | 15 +-
drivers/vfio/pci/Kconfig | 2 +
drivers/vfio/pci/Makefile | 2 +
drivers/vfio/pci/nova-vgpu/Kconfig | 20 +
drivers/vfio/pci/nova-vgpu/Makefile | 3 +
drivers/vfio/pci/nova-vgpu/nova_vgpu.rs | 522 ++++++++++++++++++++++++
rust/bindings/bindings_helper.h | 1 +
rust/kernel/vfio.rs | 3 +
8 files changed, 565 insertions(+), 3 deletions(-)
create mode 100644 drivers/vfio/pci/nova-vgpu/Kconfig
create mode 100644 drivers/vfio/pci/nova-vgpu/Makefile
create mode 100644 drivers/vfio/pci/nova-vgpu/nova_vgpu.rs
diff --git a/drivers/gpu/Makefile b/drivers/gpu/Makefile
index e372fc02139fe..5fd610a172ad1 100644
--- a/drivers/gpu/Makefile
+++ b/drivers/gpu/Makefile
@@ -19,8 +19,9 @@ nova-core-y := nova-core/nova_core.o nova-core/nova_core_exports.o
obj-$(CONFIG_DRM_NOVA) += nova-drm.o
nova-drm-y := drm/nova/nova.o
-# Export Rust symbols from nova-core only if nova-drm actually references them.
-nova-core-export-deps := $(if $(CONFIG_DRM_NOVA),$(obj)/drm/nova/nova.o)
+# Export Rust symbols from nova-core only if dependent modules reference them.
+nova-core-export-deps := $(if $(CONFIG_DRM_NOVA),$(obj)/drm/nova/nova.o) \
+ $(if $(CONFIG_NOVA_VGPU_VFIO_PCI),$(obj)/../vfio/pci/nova-vgpu/nova_vgpu.o)
rust_needed_exports = \
{ $(if $(strip $(2)),$(NM) -u $(2);,) echo "__DEFINED_RUST_SYMBOLS__"; \
@@ -57,10 +58,18 @@ $(obj)/nova-core/nova_core_exports.o: private cmd_gensymtypes_c = \
$(obj)/nova-core/nova_core.o
endif
-# Output nova-core's crate metadata for use by nova-drm at compile time.
+# Output nova-core's crate metadata for its Rust consumers at compile time.
RUSTFLAGS_nova-core/nova_core.o += \
--emit=metadata=$(objtree)/$(obj)/nova-core/libnova_core.rmeta
# Allow nova-drm to import nova-core's types.
$(obj)/drm/nova/nova.o: $(obj)/nova-core/nova_core.o
RUSTFLAGS_drm/nova/nova.o := -L $(objtree)/$(obj)/nova-core --extern nova_core
+
+# Build the NVIDIA VFIO driver here so metadata and generated exports share
+# the same dependency graph as nova-drm.
+obj-$(CONFIG_NOVA_VGPU_VFIO_PCI) += nova-vgpu-vfio-pci.o
+nova-vgpu-vfio-pci-y := ../vfio/pci/nova-vgpu/nova_vgpu.o
+
+$(obj)/../vfio/pci/nova-vgpu/nova_vgpu.o: $(obj)/nova-core/nova_core.o
+RUSTFLAGS_../vfio/pci/nova-vgpu/nova_vgpu.o := -L $(objtree)/$(obj)/nova-core --extern nova_core
diff --git a/drivers/vfio/pci/Kconfig b/drivers/vfio/pci/Kconfig
index 296bf01e185ec..dd9b755262a4c 100644
--- a/drivers/vfio/pci/Kconfig
+++ b/drivers/vfio/pci/Kconfig
@@ -74,4 +74,6 @@ source "drivers/vfio/pci/qat/Kconfig"
source "drivers/vfio/pci/xe/Kconfig"
+source "drivers/vfio/pci/nova-vgpu/Kconfig"
+
endmenu
diff --git a/drivers/vfio/pci/Makefile b/drivers/vfio/pci/Makefile
index 6138f1bf241df..1d9fb11eb3c21 100644
--- a/drivers/vfio/pci/Makefile
+++ b/drivers/vfio/pci/Makefile
@@ -24,3 +24,5 @@ obj-$(CONFIG_NVGRACE_GPU_VFIO_PCI) += nvgrace-gpu/
obj-$(CONFIG_QAT_VFIO_PCI) += qat/
obj-$(CONFIG_XE_VFIO_PCI) += xe/
+
+# nova-vgpu is built from drivers/gpu/Makefile for nova-core crate linkage.
diff --git a/drivers/vfio/pci/nova-vgpu/Kconfig b/drivers/vfio/pci/nova-vgpu/Kconfig
new file mode 100644
index 0000000000000..29fad96340ce6
--- /dev/null
+++ b/drivers/vfio/pci/nova-vgpu/Kconfig
@@ -0,0 +1,20 @@
+# SPDX-License-Identifier: GPL-2.0-only
+config NOVA_VGPU_VFIO_PCI
+ tristate "VFIO support for the NVIDIA vGPU"
+ depends on NOVA_CORE && PCI_IOV && RUST
+ depends on VFIO_PCI_CORE=y
+ help
+ This option enables VFIO (Virtual Function I/O) support for
+ NVIDIA virtual GPUs (vGPU). It allows the assignment of a virtual
+ GPU instance to userspace applications via VFIO, typically used
+ with hypervisors such as KVM and device emulators like QEMU.
+
+ Devices without an available Nova vGPU interface use ordinary PCI
+ passthrough. Both paths use the VFIO PCI core defaults; vfio-pci
+ module options do not apply.
+
+ The NVIDIA vGPU allows a physical GPU to be partitioned into
+ multiple virtual GPUs, each of which can be passed to a virtual
+ machine as a PCI device using the standard VFIO infrastructure.
+
+ If you don't know what to do here, say N.
diff --git a/drivers/vfio/pci/nova-vgpu/Makefile b/drivers/vfio/pci/nova-vgpu/Makefile
new file mode 100644
index 0000000000000..0875c782602e4
--- /dev/null
+++ b/drivers/vfio/pci/nova-vgpu/Makefile
@@ -0,0 +1,3 @@
+# SPDX-License-Identifier: GPL-2.0
+# nova-vgpu is built from drivers/gpu/Makefile for nova-core crate linkage.
+# nova_vgpu.o (rust-analyzer marker - DO NOT REMOVE).
diff --git a/drivers/vfio/pci/nova-vgpu/nova_vgpu.rs b/drivers/vfio/pci/nova-vgpu/nova_vgpu.rs
new file mode 100644
index 0000000000000..21d3ad70c84ef
--- /dev/null
+++ b/drivers/vfio/pci/nova-vgpu/nova_vgpu.rs
@@ -0,0 +1,522 @@
+// SPDX-License-Identifier: GPL-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
+
+//! NVIDIA vGPU VFIO variant driver.
+//!
+//! Nova VFs own an instance between the first VFIO open and last close. Other
+//! matching devices use ordinary PCI passthrough.
+
+use core::ops::Range;
+use kernel::{
+ bindings,
+ device::{
+ Bound,
+ Core, //
+ },
+ io::resource::Flags,
+ pci,
+ prelude::*,
+ sync::{
+ CondVar,
+ Mutex,
+ MutexGuard, //
+ },
+ uaccess::{
+ UserSlice,
+ UserSliceReader,
+ UserSliceWriter, //
+ },
+ vfio::{
+ self,
+ pci::{
+ GetRegionInfo,
+ Ioctl,
+ Mapping,
+ Mmap,
+ Open,
+ Position,
+ Read,
+ RegionInfo,
+ Write, //
+ }, //
+ }, //
+};
+use nova_core::{
+ NovaCoreVfApi,
+ NovaCoreVfApiHandle,
+ VgpuInstance, //
+};
+
+struct NovaVgpuOps;
+
+struct VgpuRegistration<'a> {
+ api: NovaCoreVfApiHandle<'a>,
+ gfid: u32,
+}
+
+#[derive(Default)]
+struct InstanceState {
+ active: bool,
+ resetting: bool,
+ reset_error: Option<Error>,
+ fb_bar_reg: u64,
+}
+
+#[pin_data]
+struct NovaVgpuRegData<'a> {
+ pdev: &'a pci::Device<Bound>,
+ vgpu: Option<VgpuRegistration<'a>>,
+ fb_bar: Option<u32>,
+ #[pin]
+ state: Mutex<InstanceState>,
+ #[pin]
+ reset_done: CondVar,
+}
+
+impl NovaVgpuRegData<'_> {
+ fn lock_instance(&self) -> MutexGuard<'_, InstanceState> {
+ let mut state = self.state.lock();
+ while state.resetting {
+ self.reset_done.wait(&mut state);
+ }
+ state
+ }
+}
+
+struct NovaVgpuOpenData<'a, 'res> {
+ registration: &'a NovaVgpuRegData<'res>,
+ instance: Option<VgpuInstance<'res>>,
+}
+
+impl<'a, 'res> NovaVgpuOpenData<'a, 'res> {
+ fn new(
+ dev: &vfio::pci::Device<NovaVgpuOps, Open>,
+ rd: &'a NovaVgpuRegData<'res>,
+ ) -> Result<Self> {
+ let mut state = rd.lock_instance();
+ let instance = match &rd.vgpu {
+ Some(vgpu) => {
+ // The firmware DBDF format has a 16-bit PCI segment field.
+ let segment = u16::try_from(rd.pdev.domain_nr()).map_err(|_| EOVERFLOW)?;
+ let dbdf = (u32::from(segment) << 16) | u32::from(rd.pdev.dev_id().into_raw());
+ let vm_pid = kernel::current!().tgid().try_into()?;
+ let instance = vgpu.api.open(vgpu.gfid, dbdf, vm_pid)?;
+ let info = instance.type_info();
+ dev.set_device_id(info.pci_dev_id as u16);
+ state.active = true;
+ state.reset_error = None;
+ state.fb_bar_reg = 0;
+ Some(instance)
+ }
+ None => None,
+ };
+ Ok(Self {
+ registration: rd,
+ instance,
+ })
+ }
+
+ fn bar1_size(&self) -> Result<Option<u64>> {
+ let (Some(instance), Some(fb_bar)) = (&self.instance, self.registration.fb_bar) else {
+ return Ok(None);
+ };
+ let physical = self.registration.pdev.resource_len(fb_bar)?;
+ let size = instance
+ .type_info()
+ .bar1_length
+ .checked_mul(1 << 20)
+ .ok_or(EOVERFLOW)?;
+ if size != 0 && !size.is_power_of_two() {
+ return Err(EINVAL);
+ }
+ Ok(Some(size.min(physical)))
+ }
+
+ /// Returns the length to which a `len`-byte access at `position` has to be shortened to
+ /// stay within the vGPU's BAR1, or `None` if the access needs no limit.
+ fn bar1_limit(&self, len: usize, position: &Position<'_>) -> Result<Option<usize>> {
+ if len == 0 || Some(position.region_index()) != self.registration.fb_bar {
+ return Ok(None);
+ }
+ if let Some(size) = self.bar1_size()? {
+ let offset = position.region_offset();
+ if offset >= size {
+ return Err(EINVAL);
+ }
+ if size - offset < len as u64 {
+ return Ok(Some((size - offset) as usize));
+ }
+ }
+ Ok(None)
+ }
+}
+
+/// Overrides fields of a completed region read in the user buffer.
+///
+/// The fields must not overlap and have to be passed in ascending offset order, as the buffer
+/// is only walked forward.
+struct ReadOverride {
+ writer: UserSliceWriter,
+ /// Region offset of the writer's current position.
+ offset: u64,
+}
+
+impl ReadOverride {
+ /// `writer` starts at region offset `offset`, where a read returned `count` bytes.
+ fn new(mut writer: UserSliceWriter, offset: u64, count: usize) -> Self {
+ writer.truncate(count);
+ Self { writer, offset }
+ }
+
+ /// Replaces the bytes of the read that overlap `data`, located at `data_offset` in the
+ /// region.
+ fn apply(&mut self, data_offset: u64, data: &[u8]) -> Result {
+ let read_end = self
+ .offset
+ .checked_add(self.writer.len() as u64)
+ .ok_or(EOVERFLOW)?;
+ let data_end = data_offset
+ .checked_add(data.len() as u64)
+ .ok_or(EOVERFLOW)?;
+ let start = self.offset.max(data_offset);
+ let end = read_end.min(data_end);
+ if start >= end {
+ return Ok(());
+ }
+
+ // These differences are bounded by the writer's length and `data.len()`.
+ self.writer.skip((start - self.offset) as usize)?;
+ self.writer
+ .write_slice(&data[(start - data_offset) as usize..(end - data_offset) as usize])?;
+ self.offset = end;
+ Ok(())
+ }
+}
+
+/// Copies the bytes of a pending region write that overlap `data` into `data`.
+///
+/// `reader` holds the data of a write at region offset `write_offset`; it is not advanced.
+/// `data_offset` locates `data` within the same region. Returns the range of `data` that was
+/// filled.
+fn peek_write(
+ reader: &UserSliceReader,
+ write_offset: u64,
+ data_offset: u64,
+ data: &mut [u8],
+) -> Result<Range<usize>> {
+ let write_end = write_offset
+ .checked_add(reader.len() as u64)
+ .ok_or(EOVERFLOW)?;
+ let data_end = data_offset
+ .checked_add(data.len() as u64)
+ .ok_or(EOVERFLOW)?;
+ let start = write_offset.max(data_offset);
+ let end = write_end.min(data_end);
+ if start >= end {
+ return Ok(0..0);
+ }
+
+ // These differences are bounded by `reader.len()` and `data.len()`.
+ let range = (start - data_offset) as usize..(end - data_offset) as usize;
+ // The VFIO core fetches the write from user space again, so the copy made here may differ
+ // from what it stores. Use it for the driver's own bookkeeping only.
+ let mut peek = reader.clone_reader();
+ peek.skip((start - write_offset) as usize)?;
+ peek.read_slice(&mut data[range.clone()])?;
+ Ok(range)
+}
+
+impl Drop for NovaVgpuOpenData<'_, '_> {
+ fn drop(&mut self) {
+ let mut state = self.registration.lock_instance();
+ state.active = false;
+ drop(self.instance.take());
+ }
+}
+
+impl vfio::Operations for NovaVgpuOps {
+ type RegistrationData<'res> = NovaVgpuRegData<'res>;
+ type OpenData<'reg, 'res: 'reg> = NovaVgpuOpenData<'reg, 'res>;
+}
+
+#[vtable]
+impl vfio::pci::Operations for NovaVgpuOps {
+ const NAME: &'static CStr = c"nova-vgpu-vfio-pci";
+
+ fn open_device<'a, 'res: 'a>(
+ dev: &vfio::pci::Device<Self, Open>,
+ rd: &'a NovaVgpuRegData<'res>,
+ ) -> impl PinInit<Self::OpenData<'a, 'res>, Error> + 'a {
+ NovaVgpuOpenData::new(dev, rd)
+ }
+
+ fn ioctl<'res>(
+ dev: &vfio::pci::Device<Self, Ioctl>,
+ rd: &NovaVgpuRegData<'res>,
+ open_data: Pin<&Self::OpenData<'_, 'res>>,
+ cmd: u32,
+ arg: usize,
+ ) -> Result<isize> {
+ // The core checks ioeventfd bounds against the physical BAR and writes
+ // without calling write(), bypassing the vGPU's bar1_limit() check.
+ // Checking a copy here could race with the core's later copy from userspace.
+ // On rejection, QEMU falls back to its userspace eventfd handler, whose
+ // writes pass through write() and bar1_limit().
+ if cmd == vfio::DEVICE_IOEVENTFD && open_data.instance.is_some() {
+ return Err(ENOTTY);
+ }
+ let result = dev.core_ioctl(cmd, arg)?;
+ if cmd == vfio::DEVICE_RESET {
+ if let Some(error) = rd.state.lock().reset_error {
+ return Err(error);
+ }
+ }
+ Ok(result)
+ }
+
+ fn read<'res>(
+ dev: &vfio::pci::Device<Self, Read>,
+ rd: &NovaVgpuRegData<'res>,
+ open_data: Pin<&Self::OpenData<'_, 'res>>,
+ buf: UserSlice,
+ position: &mut Position<'_>,
+ ) -> Result<isize> {
+ let mut writer = buf.writer();
+ if let Some(instance) = &open_data.instance {
+ if position.region_index() == vfio::pci::CONFIG_REGION_INDEX {
+ let offset = position.region_offset();
+ return position.with_temporary(|next| {
+ let count = dev.core_read(&writer, next)?;
+ // The fields overridden below do not overlap and are in ascending config
+ // space offset order.
+ let mut overrides = ReadOverride::new(writer, offset, count.try_into()?);
+ if let (Some(size), Some(fb_bar)) = (open_data.bar1_size()?, rd.fb_bar) {
+ let reg = rd.state.lock().fb_bar_reg & !size.wrapping_sub(1);
+ // Byte 0 holds only the flag bits, which the core has filled in.
+ overrides.apply(
+ u64::from(bindings::PCI_BASE_ADDRESS_0) + 4 * u64::from(fb_bar) + 1,
+ ®.to_le_bytes()[1..],
+ )?;
+ }
+ // A VF has no device ID of its own, so the core keeps it in vconfig, where
+ // it is set once at open. The core reads the subsystem ID from the hardware,
+ // as a firmware update can change it there, so replace it on every read.
+ overrides.apply(
+ u64::from(bindings::PCI_SUBSYSTEM_ID),
+ &(instance.type_info().pci_subsys_id as u16).to_le_bytes(),
+ )?;
+ Ok(count)
+ });
+ }
+ }
+ if let Some(limit) = open_data.bar1_limit(writer.len(), position)? {
+ writer.truncate(limit);
+ }
+ dev.core_read(&writer, position)
+ }
+
+ fn write<'res>(
+ dev: &vfio::pci::Device<Self, Write>,
+ rd: &NovaVgpuRegData<'res>,
+ open_data: Pin<&Self::OpenData<'_, 'res>>,
+ buf: UserSlice,
+ position: &mut Position<'_>,
+ ) -> Result<isize> {
+ let mut reader = buf.reader();
+ if let Some(fb_bar) = rd.fb_bar {
+ if position.region_index() == vfio::pci::CONFIG_REGION_INDEX {
+ let mut written = [0; 8];
+ let range = peek_write(
+ &reader,
+ position.region_offset(),
+ u64::from(bindings::PCI_BASE_ADDRESS_0) + 4 * u64::from(fb_bar),
+ &mut written,
+ )?;
+ if !range.is_empty() {
+ let mut state = rd.state.lock();
+ let mut reg = state.fb_bar_reg.to_le_bytes();
+ reg[range.clone()].copy_from_slice(&written[range]);
+ state.fb_bar_reg = u64::from_le_bytes(reg);
+ }
+ }
+ }
+ if let Some(limit) = open_data.bar1_limit(reader.len(), position)? {
+ reader.truncate(limit);
+ }
+ dev.core_write(&reader, position)
+ }
+
+ fn mmap<'res>(
+ dev: &vfio::pci::Device<Self, Mmap>,
+ rd: &NovaVgpuRegData<'res>,
+ open_data: Pin<&Self::OpenData<'_, 'res>>,
+ mapping: &mut Mapping<'_>,
+ ) -> Result {
+ if Some(mapping.region_index()) == rd.fb_bar {
+ if let Some(size) = open_data.bar1_size()? {
+ if mapping.region_end()? > size {
+ return Err(EINVAL);
+ }
+ }
+ }
+ dev.core_mmap(mapping)
+ }
+
+ fn get_region_info<'res>(
+ dev: &vfio::pci::Device<Self, GetRegionInfo>,
+ rd: &NovaVgpuRegData<'res>,
+ open_data: Pin<&Self::OpenData<'_, 'res>>,
+ info: &mut RegionInfo,
+ caps: &mut vfio::InfoCap,
+ ) -> Result {
+ dev.core_get_region_info(info, caps)?;
+ if Some(info.index()) == rd.fb_bar && info.size() != 0 {
+ if let Some(size) = open_data.bar1_size()? {
+ info.set_size(info.size().min(size));
+ }
+ }
+ Ok(())
+ }
+
+ fn dmabuf_len<'res>(
+ rd: &NovaVgpuRegData<'res>,
+ open_data: Pin<&Self::OpenData<'_, 'res>>,
+ region_index: u32,
+ ) -> Result<Option<u64>> {
+ if Some(region_index) == rd.fb_bar {
+ return open_data.bar1_size();
+ }
+ Ok(None)
+ }
+
+ fn reset_prepare(rd: &NovaVgpuRegData<'_>) {
+ // PCI holds the device lock, and VFIO may hold its memory lock. Open and
+ // close release this mutex before entering the VFIO core.
+ let mut state = rd.state.lock();
+ state.resetting = true;
+ state.reset_error = None;
+ // A VF FLR is reported to the GSP firmware, but does not release all
+ // guest resources or scrub the framebuffer. That work can exceed the
+ // FLR time budget and delay other vGPUs if done in the FLR handler.
+ // Request it first through nova-core, which owns the PF's firmware
+ // interface, to quiesce the vGPU before its VF is reset.
+ //
+ // Using PCI's prepare callback also covers host sysfs function
+ // resets, in addition to VFIO ioctl and config-space resets.
+ // An error is recorded but cannot veto the PCI reset attempt.
+ if state.active {
+ if let Some(vgpu) = &rd.vgpu {
+ state.reset_error = vgpu.api.reset(vgpu.gfid).err();
+ }
+ }
+ }
+
+ fn reset_done(rd: &NovaVgpuRegData<'_>) -> Result {
+ let mut state = rd.state.lock();
+ let error = state.reset_error;
+ state.resetting = false;
+ rd.reset_done.notify_all();
+ error.map_or(Ok(()), Err)
+ }
+}
+
+struct NovaVgpuDriver;
+
+kernel::pci_device_table!(
+ PCI_TABLE,
+ <NovaVgpuDriver as pci::Driver>::IdInfo,
+ [
+ (
+ pci::DeviceId::from_id_vfio_override(pci::Vendor::NVIDIA, 0x2bb3),
+ (),
+ ),
+ (
+ pci::DeviceId::from_id_vfio_override(pci::Vendor::NVIDIA, 0x2bb5),
+ (),
+ ),
+ ]
+);
+
+#[pin_data]
+struct NovaVgpuData<'bound> {
+ reg: vfio::pci::Registration<'bound, NovaVgpuOps>,
+}
+
+#[vtable]
+impl pci::Driver for NovaVgpuDriver {
+ type IdInfo = ();
+ type Data<'bound> = NovaVgpuData<'bound>;
+ const ID_TABLE: pci::IdTable<Self::IdInfo> = &PCI_TABLE;
+ // SAFETY: VFIO hands the DMA ownership of the device to userspace. This driver never uses
+ // the kernel DMA API for its devices, directly or through helpers.
+ const DRIVER_MANAGED_DMA: Option<pci::DriverManagedDma<Self>> =
+ Some(unsafe { pci::DriverManagedDma::new() });
+
+ fn probe<'bound>(
+ pdev: &'bound pci::Device<Core<'_>>,
+ _info: Option<&'bound Self::IdInfo>,
+ ) -> impl PinInit<Self::Data<'bound>, Error> + 'bound {
+ try_pin_init!(NovaVgpuData {
+ reg: {
+ let vgpu = match NovaCoreVfApi::handle(pdev) {
+ Ok(api) => Some(VgpuRegistration {
+ api,
+ gfid: u32::from(pdev.vf_id()?) + 1,
+ }),
+ Err(_) => None,
+ };
+ let fb_bar = if vgpu.is_none() {
+ None
+ } else if pdev.resource_flags(0)?.contains(Flags::IORESOURCE_MEM_64) {
+ Some(2)
+ } else {
+ Some(1)
+ };
+ // SAFETY: The registration is stored in `NovaVgpuData`, this driver's bus
+ // device private data, which is never leaked.
+ unsafe {
+ vfio::pci::Registration::new(
+ pdev,
+ try_pin_init!(NovaVgpuRegData {
+ pdev,
+ vgpu,
+ fb_bar,
+ state <- kernel::new_mutex!(InstanceState::default()),
+ reset_done <- kernel::new_condvar!(),
+ }),
+ )?
+ }
+ },
+ })
+ }
+
+ fn reset_prepare<'bound>(_pdev: &pci::Device<Core<'_>>, data: Pin<&Self::Data<'bound>>) {
+ data.reg.reset_prepare();
+ }
+
+ fn reset_done<'bound>(pdev: &pci::Device<Core<'_>>, data: Pin<&Self::Data<'bound>>) {
+ if let Err(error) = data.reg.reset_done() {
+ dev_err!(pdev, "VFIO device reset failed: {:?}\n", error);
+ }
+ }
+
+ fn error_detected<'bound>(
+ _pdev: &pci::Device<Core<'_>>,
+ data: Pin<&Self::Data<'bound>>,
+ _state: pci::ChannelState,
+ ) -> pci::ErsResult {
+ data.reg.error_detected()
+ }
+}
+
+kernel::module_pci_driver! {
+ type: NovaVgpuDriver,
+ name: "nova-vgpu-vfio-pci",
+ authors: [
+ "Danilo Krummrich <dakr@kernel.org>",
+ "Zhi Wang <zhiw@nvidia.com>",
+ "Simon Song <xinmengs@nvidia.com>",
+ ],
+ description: "NVIDIA vGPU VFIO variant driver",
+ license: "GPL v2",
+}
diff --git a/rust/bindings/bindings_helper.h b/rust/bindings/bindings_helper.h
index 06bc8508064d8..6f958cceeec03 100644
--- a/rust/bindings/bindings_helper.h
+++ b/rust/bindings/bindings_helper.h
@@ -118,6 +118,7 @@ const size_t RUST_CONST_HELPER_ARCH_SLAB_MINALIGN = ARCH_SLAB_MINALIGN;
const size_t RUST_CONST_HELPER_ARCH_KMALLOC_MINALIGN = ARCH_KMALLOC_MINALIGN;
const size_t RUST_CONST_HELPER_PAGE_SIZE = PAGE_SIZE;
const unsigned int RUST_CONST_HELPER_VFIO_DEVICE_RESET = VFIO_DEVICE_RESET;
+const unsigned int RUST_CONST_HELPER_VFIO_DEVICE_IOEVENTFD = VFIO_DEVICE_IOEVENTFD;
const size_t RUST_CONST_HELPER_GENLMSG_DEFAULT_SIZE = GENLMSG_DEFAULT_SIZE;
const gfp_t RUST_CONST_HELPER_GFP_ATOMIC = GFP_ATOMIC;
const gfp_t RUST_CONST_HELPER_GFP_KERNEL = GFP_KERNEL;
diff --git a/rust/kernel/vfio.rs b/rust/kernel/vfio.rs
index 2aad900e6d971..7aeadad206542 100644
--- a/rust/kernel/vfio.rs
+++ b/rust/kernel/vfio.rs
@@ -38,6 +38,9 @@
/// Reset the VFIO device.
pub const DEVICE_RESET: u32 = bindings::VFIO_DEVICE_RESET;
+/// Write a value to a device region whenever an eventfd is signaled.
+pub const DEVICE_IOEVENTFD: u32 = bindings::VFIO_DEVICE_IOEVENTFD;
+
/// The context in which a VFIO device reference is valid.
///
/// Callback views can only be borrowed from the corresponding VFIO trampoline.
--
2.43.7
^ permalink raw reply related [flat|nested] 6+ messages in thread