Rust VFIO PCI support and NVIDIA vGPU driver
Subsystems (10)
v3 cover Rust VFIO PCI support and NVIDIA vGPU driver
This is v3 of the Rust VFIO PCI abstractions and the NVIDIA VFIO variant driver [1]. The driver uses nova-core's typed SR-IOV PF interface to create, reset and release vGPU instances while VFIO provides userspace access to the PCI device.
Patches 1-5 add the PCI helpers and callbacks the VFIO abstractions need. Patch 6 adds the VFIO device handling common to all buses, and patch 7 the VFIO PCI abstractions on top of it. Patch 8 publishes the typed Nova PF interface, and patch 9 adds the NVIDIA VFIO variant driver.
This series is based on drm-rust-next with the Rust PCI SR-IOV series
[2] applied. Patches 1-7 need nothing else. Patches 8 and 9 also depend on Alok's vGPU manager series [3] and can follow once it has landed.
Runtime PM is not part of this series anymore. As Danilo suggested, it will follow as a separate series based on Beata's generic Rust runtime PM work [4], so that the rest can land independently. Until then, vfio::pci::Registration keeps the device runtime active while it is registered, so a VF bound to the driver is not runtime suspended.
Changes since v2:
- Drop runtime PM from this series (v2 patch 08 and the runtime PM parts of v2 patches 04, 09 and 12), see above.
- Put the common VFIO device handling first (v2 patch 10, now patch 6) and squash v2 patches 04 and 09 into one patch (patch 7) (Danilo).
- Drop the bind callback (v2 patch 06). A driver registers its VFIO device with vfio::pci::Registration::new(), for example from probe, and unregisters it by dropping the Registration (Danilo).
- Patch 1: say first what the function does in its documentation (Gary).
- Patch 2: return Result<u16> from vf_id(), and add a C helper so that it builds without CONFIG_PCI_IOV (Danilo).
- Patch 3: make DRIVER_MANAGED_DMA an unsafe marker, until the DMA setup tokens exist (Danilo).
- Patches 4 and 5: use Device::drvdata_borrow() and #[optional]; add the pci::ChannelState and pci::ErsResult types (Danilo).
- Patch 6: add vfio::DeviceBase and RawDevice; use GATs instead of ForLt/CovariantForLt and drop the covariance requirement on the registration data (Danilo).
- Patch 8: drop the CONFIG_PCI_IOV guards, use a pin-init self-reference for the GPU, simplify the SAFETY comment and use enable_all() (Danilo).
- Patch 9: rename the driver to nova-vgpu (Danilo), and adapt it to the changes above.
v2 patches 01, 02, 03, 05, 07, 10, 04+09, 11 and 12 are now patches 1 to 9.
[1] https://lore.kernel.org/nova-gpu/[email protected]/
[2] https://lore.kernel.org/all/[email protected]/
[3] https://lore.kernel.org/all/[email protected]/
[4] https://lore.kernel.org/all/[email protected]/
Danilo Krummrich (5):
rust: pci: add VFIO override device IDs
rust: pci: expose the VF index within its PF
rust: pci: allow drivers to manage DMA ownership
rust: vfio: add PCI variant driver abstractions vfio/nova-vgpu: add the Rust VFIO variant driver
Simon Song (2):
rust: pci: add reset callbacks
rust: pci: add an error_detected callback
Zhi Wang (2):
rust: vfio: add common VFIO device handling
gpu: nova-core: publish typed SR-IOV PF APIs
drivers/gpu/Makefile | 15 +- 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 | 178 ++++-- 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 | 375 ++++++++++++ rust/bindings/bindings_helper.h | 4 + rust/helpers/pci.c | 5 + rust/kernel/lib.rs | 2 + rust/kernel/pci.rs | 194 ++++++ rust/kernel/pci/iov.rs | 11 + rust/kernel/vfio.rs | 433 +++++++++++++ rust/kernel/vfio/pci.rs | 777 ++++++++++++++++++++++++ 17 files changed, 2011 insertions(+), 48 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 create mode 100644 rust/kernel/vfio.rs create mode 100644 rust/kernel/vfio/pci.rs
Signature · 1 line
2.43.7
PATCH v3 1/9 rust: pci: add VFIO override device IDs
From: Danilo Krummrich <[email protected]>
VFIO variant drivers need override-only IDs and VFIO-specific module aliases so userspace can select them for PCI assignment.
Add a DeviceId constructor equivalent to PCI_DRIVER_OVERRIDE_DEVICE_VFIO, matching a vendor and device without restricting the PCI class.
--- rust/kernel/pci.rs | 15 +++++++++++++++ 1 file changed, 15 insertions(+)
rust/kernel/pci.rs +15 -0
@@ -209,6 +209,21 @@ macro_rules! module_pci_driver {impl DeviceId {const PCI_ANY_ID :u32 = !0 ; +/// Create a new `pci::DeviceId` for a VFIO driver from a vendor and device ID. +/// +/// The ID matches every device with this vendor and device ID, whatever its class, but only +/// once userspace has selected the driver for the device through `driver_override`. The +/// driver is never bound to a matching device automatically. The module alias generated for +/// the ID has the `vfio_pci:` prefix, which lets userspace find the VFIO driver for a device. +/// +/// Equivalent to C's `PCI_DRIVER_OVERRIDE_DEVICE_VFIO` macro. +#[inline] +pub const fn from_id_vfio_override (vendor:Vendor , device:u32 ) ->Self { +let mut id =Self ::from_id (vendor, device); + id.0 .override_only = bindings::PCI_ID_F_VFIO_DRIVER_OVERRIDE ; + id + } +/// Equivalent to C's `PCI_DEVICE` macro. /// /// Create a new `pci::DeviceId` from a vendor and device ID.
Signature · 1 line
2.43.7
PATCH v3 2/9 rust: pci: expose the VF index within its PF
In reply to Simon SongFrom: Danilo Krummrich <[email protected]>
Nova identifies a vGPU instance by the VF's index within its PF. Expose pci_iov_vf_id() through Device::vf_id() so a Rust VF driver can obtain that index, with an error for devices that are not VFs.
Because enabling or disabling SR-IOV can update the PF's VF offset and stride, from which the index is computed, restrict vf_id() to bound devices, Device<device::Bound>.
--- rust/helpers/pci.c | 5 +++++ rust/kernel/pci/iov.rs | 11 +++++++++++ 2 files changed, 16 insertions(+)
rust/helpers/pci.c +5 -0
@@ -41,6 +41,11 @@ __rust_helper u32 rust_helper_pci_ext_cap_next(u32 header) }#ifndef CONFIG_PCI_IOV +__rust_helper int rust_helper_pci_iov_vf_id(struct pci_dev *pdev) +{ +return pci_iov_vf_id (pdev); +} + __rust_helper int rust_helper_pci_enable_sriov(struct pci_dev *pdev,int nr_virtfn) {
rust/kernel/pci/iov.rs +11 -0
@@ -379,6 +379,17 @@ unsafe impl<F: ForLt> Send for VfRegistration<'_, F> where for<'a> F::Of<'a>: Seunsafe impl <F :ForLt >Sync for VfRegistration <'_,F >where for <'a>F ::Of <'a>:Send +Sync {}impl Device <device::Bound > { +/// Return the zero-based VF index within its PF, or an error for a non-VF device. +/// +/// Returns [`ENOSYS`] when `CONFIG_PCI_IOV` is disabled. +#[inline] +pub fn vf_id (&self) ->Result <u16 > { +// SAFETY: `self.as_raw()` points to a live PCI device; the helper checks VF membership. +let id =unsafe { bindings::pci_iov_vf_id (self.as_raw ()) }; +to_result (id)?; +Ok (id.try_into ()?) + } +/// Internal helper: reads the `vf_registration_data_rust` pointer from the /// PF, checks the `TypeId`, and returns a pinned reference. ///
Signature · 1 line
2.43.7
PATCH v3 3/9 rust: pci: allow drivers to manage DMA ownership
In reply to Simon SongFrom: Danilo Krummrich <[email protected]>
VFIO manages DMA ownership through the userspace IOMMU interface. Its PCI variant drivers must opt out of the driver's default DMA domain.
Add Driver::DRIVER_MANAGED_DMA and pass it to the PCI core. Make it an unsafe marker as suggested, until the DMA setup tokens exist.
--- rust/kernel/pci.rs | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+)
rust/kernel/pci.rs +23 -0
@@ -105,6 +105,7 @@ unsafe fn register( (*pdrv.get ()).probe =Some (Self ::probe_callback); (*pdrv.get ()).remove =Some (Self ::remove_callback); (*pdrv.get ()).id_table =T ::ID_TABLE .as_ptr (); + (*pdrv.get ()).driver_managed_dma =T ::DRIVER_MANAGED_DMA .is_some ();if T ::HAS_SRIOV_ENABLE { (*pdrv.get ()).sriov_configure =Some (Self ::sriov_configure_callback); }
@@ -293,6 +294,24 @@ unsafe impl RawDeviceIdIndex for DeviceId {const DRIVER_DATA_OFFSET :usize = core::mem::offset_of!(bindings::pci_device_id, driver_data); } +/// Marker for a driver that manages DMA ownership of its devices by itself. +/// +/// The driver core does not claim the default DMA domain for the devices of such a driver. See +/// [`Driver::DRIVER_MANAGED_DMA`]. +pub struct DriverManagedDma <D : ?Sized >(PhantomData <fn () -> *mut D >); + +impl <D : ?Sized >DriverManagedDma <D > { +/// Declares that driver `D` manages DMA ownership of its devices by itself. +/// +/// # Safety +/// +/// The caller must ensure that devices bound to `D` are not used for DMA allocations or +/// mappings through the kernel DMA API, directly or through helpers. +pub const unsafe fn new () ->Self { +Self (PhantomData ) + } +} +/// `IdTable` type for PCI. pub type IdTable <T > = &'staticdyn kernel::device_id::IdTable <DeviceId ,T >;
@@ -356,6 +375,10 @@ pub trait Driver {/// The table of device ids supported by the driver. const ID_TABLE :IdTable <Self ::IdInfo >; +/// Set if the driver manages DMA ownership of its devices by itself, instead of using the +/// default DMA domain. Construct with [`DriverManagedDma::new`]. +const DRIVER_MANAGED_DMA :Option <DriverManagedDma <Self >> =None ; +/// PCI driver probe. /// /// Called when a new pci device is added or discovered. Implementers should
Signature · 1 line
2.43.7
PATCH v3 4/9 rust: pci: add reset callbacks
In reply to Simon SongBecause a VFIO PCI variant driver may need to update its state when its device is reset, it needs notifications before and after the reset. The NVIDIA VFIO variant driver resets a VF's active vGPU instance.
Add reset_prepare() and reset_done() as optional callbacks to pci::Driver.
--- rust/kernel/pci.rs | 59 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+)
rust/kernel/pci.rs +59 -0
@@ -106,6 +106,9 @@ unsafe fn register( (*pdrv.get ()).remove =Some (Self ::remove_callback); (*pdrv.get ()).id_table =T ::ID_TABLE .as_ptr (); (*pdrv.get ()).driver_managed_dma =T ::DRIVER_MANAGED_DMA .is_some (); +if T ::HAS_RESET_PREPARE ||T ::HAS_RESET_DONE { + (*pdrv.get ()).err_handler = &Self ::ERROR_HANDLERS ; + }if T ::HAS_SRIOV_ENABLE { (*pdrv.get ()).sriov_configure =Some (Self ::sriov_configure_callback); }
@@ -178,6 +181,54 @@ extern "C" fn remove_callback(pdev: *mut bindings::pci_dev) {// before `devres_release_all()` in `device_unbind_cleanup()` is sufficient. drop (data); } + +extern "C" fn reset_prepare_callback (pdev: *mut bindings::pci_dev ) { +// SAFETY: The PCI core only ever calls the reset_prepare callback with a valid pointer to +// a `struct pci_dev`, while holding the device lock. +// +// INVARIANT: `pdev` is valid for the duration of `reset_prepare_callback()`. +let pdev =unsafe { &*pdev.cast ::<Device <device::CoreInternal <'_>>>() }; + +// SAFETY: The PCI core only calls this callback for a device bound to this driver. The +// device lock excludes `probe_callback()` and `remove_callback()`, so the stored pointer +// has type `T::Data<'_>` and remains valid throughout this callback. +let data =unsafe { pdev.as_ref ().drvdata_borrow ::<T ::Data <'_>>() }; + +T ::reset_prepare (pdev, data); + } + +extern "C" fn reset_done_callback (pdev: *mut bindings::pci_dev ) { +// SAFETY: The PCI core only ever calls the reset_done callback with a valid pointer to a +// `struct pci_dev`, while holding the device lock. +// +// INVARIANT: `pdev` is valid for the duration of `reset_done_callback()`. +let pdev =unsafe { &*pdev.cast ::<Device <device::CoreInternal <'_>>>() }; + +// SAFETY: The PCI core only calls this callback for a device bound to this driver. The +// device lock excludes `probe_callback()` and `remove_callback()`, so the stored pointer +// has type `T::Data<'_>` and remains valid throughout this callback. +let data =unsafe { pdev.as_ref ().drvdata_borrow ::<T ::Data <'_>>() }; + +T ::reset_done (pdev, data); + } + +const ERROR_HANDLERS : bindings::pci_error_handlers = bindings::pci_error_handlers { + error_detected:None , + mmio_enabled:None , + slot_reset:None , + reset_prepare:if T ::HAS_RESET_PREPARE { +Some (Self ::reset_prepare_callback) + }else { +None + }, + reset_done:if T ::HAS_RESET_DONE { +Some (Self ::reset_done_callback) + }else { +None + }, + resume:None , + cor_error_detected:None , + }; }/// Declares a kernel module that exposes a single PCI driver.
@@ -402,6 +453,14 @@ fn unbind<'bound>(dev: &'bound Device<device::Core<'_>>, this: Pin<&Self::Data<'let _ = (dev, this); } +/// Called before a PCI function reset, with the device lock held. +#[optional] +fn reset_prepare <'bound>(_dev: &Device <device::Core <'_>>, _this:Pin <&Self ::Data <'bound>>); + +/// Called after a PCI function reset, with the device lock held. +#[optional] +fn reset_done <'bound>(_dev: &Device <device::Core <'_>>, _this:Pin <&Self ::Data <'bound>>); +/// Enables Single Root I/O Virtualization (SR-IOV) for a PF. /// /// This callback is only invoked when `CONFIG_PCI_IOV` is enabled.
Signature · 1 line
2.43.7
PATCH v3 5/9 rust: pci: add an error_detected callback
In reply to Simon SongVFIO PCI variant drivers will use error_detected() to notify userspace of PCI errors through vfio-pci-core.
Adding error_detected() to pci::Driver lets VFIO variants reuse the PCI adapter's error callback dispatch.
--- rust/kernel/pci.rs | 89 ++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 87 insertions(+), 2 deletions(-)
rust/kernel/pci.rs +87 -2
@@ -106,7 +106,7 @@ unsafe fn register( (*pdrv.get ()).remove =Some (Self ::remove_callback); (*pdrv.get ()).id_table =T ::ID_TABLE .as_ptr (); (*pdrv.get ()).driver_managed_dma =T ::DRIVER_MANAGED_DMA .is_some (); -if T ::HAS_RESET_PREPARE ||T ::HAS_RESET_DONE { +if T ::HAS_ERROR_DETECTED ||T ::HAS_RESET_PREPARE ||T ::HAS_RESET_DONE { (*pdrv.get ()).err_handler = &Self ::ERROR_HANDLERS ; }if T ::HAS_SRIOV_ENABLE {
@@ -212,8 +212,36 @@ extern "C" fn reset_done_callback(pdev: *mut bindings::pci_dev) {T ::reset_done (pdev, data); } +extern "C" fn error_detected_callback ( + pdev: *mut bindings::pci_dev , + state: bindings::pci_channel_state_t , + ) -> bindings::pci_ers_result_t { +// SAFETY: PCI error recovery only ever calls the error_detected callback with a valid +// pointer to a `struct pci_dev`. AER (`report_error_detected()`) and EEH hold the device +// lock while calling it. +// +// INVARIANT: `pdev` is valid for the duration of `error_detected_callback()`. +let pdev =unsafe { &*pdev.cast ::<Device <device::CoreInternal <'_>>>() }; + +// SAFETY: PCI error recovery only calls this callback for a device bound to this driver. +// The device lock excludes `probe_callback()` and `remove_callback()`, so the stored +// pointer has type `T::Data<'_>` and remains valid throughout this callback. +let data =unsafe { pdev.as_ref ().drvdata_borrow ::<T ::Data <'_>>() }; + +let Some (state) =ChannelState ::from_raw (state)else { +// PCI error recovery only reports the states `ChannelState` represents. +return ErsResult ::None .as_raw (); + }; + +T ::error_detected (pdev, data, state).as_raw () + } +const ERROR_HANDLERS : bindings::pci_error_handlers = bindings::pci_error_handlers { - error_detected:None , + error_detected:if T ::HAS_ERROR_DETECTED { +Some (Self ::error_detected_callback) + }else { +None + }, mmio_enabled:None , slot_reset:None , reset_prepare:if T ::HAS_RESET_PREPARE {
@@ -363,6 +391,55 @@ impl<D: ?Sized> DriverManagedDma<D> { } } +/// The state of the I/O channel to a device, as reported by PCI error recovery. +#[derive( Clone , Copy , Debug , PartialEq , Eq )] +pub enum ChannelState { +/// The I/O channel remains operational. +Normal , +/// I/O to the device is blocked. +Frozen , +/// The device has permanently failed. +PermanentFailure , +} + +impl ChannelState { +fn from_raw (state: bindings::pci_channel_state_t ) ->Option <Self > { +match state { + bindings::pci_channel_io_normal =>Some (Self ::Normal ), + bindings::pci_channel_io_frozen =>Some (Self ::Frozen ), + bindings::pci_channel_io_perm_failure =>Some (Self ::PermanentFailure ), + _ =>None , + } + } +} + +/// The result a driver reports to PCI error recovery. +#[derive( Clone , Copy , Debug , PartialEq , Eq )] +pub enum ErsResult { +/// The driver has no result to report. +None , +/// The driver can recover without a slot reset. +CanRecover , +/// The driver needs the slot to be reset. +NeedReset , +/// The device has failed completely and cannot be recovered. +Disconnect , +/// The driver has fully recovered and the device is operational. +Recovered , +} + +impl ErsResult { +fn as_raw (self) -> bindings::pci_ers_result_t { +match self { +Self ::None => bindings::pci_ers_result_PCI_ERS_RESULT_NONE, +Self ::CanRecover => bindings::pci_ers_result_PCI_ERS_RESULT_CAN_RECOVER, +Self ::NeedReset => bindings::pci_ers_result_PCI_ERS_RESULT_NEED_RESET, +Self ::Disconnect => bindings::pci_ers_result_PCI_ERS_RESULT_DISCONNECT, +Self ::Recovered => bindings::pci_ers_result_PCI_ERS_RESULT_RECOVERED, + } + } +} +/// `IdTable` type for PCI. pub type IdTable <T > = &'staticdyn kernel::device_id::IdTable <DeviceId ,T >;
@@ -461,6 +538,14 @@ fn unbind<'bound>(dev: &'bound Device<device::Core<'_>>, this: Pin<&Self::Data<'#[optional] fn reset_done <'bound>(_dev: &Device <device::Core <'_>>, _this:Pin <&Self ::Data <'bound>>); +/// Handle a PCI error and return the PCI recovery result, with the device lock held. +#[optional] +fn error_detected <'bound>( + _dev: &Device <device::Core <'_>>, + _this:Pin <&Self ::Data <'bound>>, + _state:ChannelState , + ) ->ErsResult ; +/// Enables Single Root I/O Virtualization (SR-IOV) for a PF. /// /// This callback is only invoked when `CONFIG_PCI_IOV` is enabled.
Signature · 1 line
2.43.7
PATCH v3 6/9 rust: vfio: add common VFIO device handling
In reply to Simon SongFrom: Zhi Wang <[email protected]>
A VFIO PCI device contains a VFIO device. Expose that relationship in Rust so common device handling is independent of PCI resources.
Add vfio::DeviceBase, a C VFIO device structure followed by pointers to callback data, and vfio::Device, its alias for struct vfio_device. The data is registration data and data kept from the first successful open until the last close, which can borrow the former. Share reference counting and callback-data lifetime handling in vfio.
The helpers are unused until the next patch adds the PCI abstraction.
--- rust/bindings/bindings_helper.h | 2 + rust/kernel/lib.rs | 2 + rust/kernel/vfio.rs | 430 ++++++++++++++++++++++++++++++++ 3 files changed, 434 insertions(+) create mode 100644 rust/kernel/vfio.rs
rust/bindings/bindings_helper.h +2 -0
@@ -93,6 +93,7 @@#include <linux/task_work.h> #include <linux/tracepoint.h> #include <linux/usb.h> +#include <linux/vfio.h> #include <linux/wait.h> #include <linux/workqueue.h> #include <linux/xarray.h>
@@ -115,6 +116,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 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 ;
rust/kernel/lib.rs +2 -0
@@ -147,6 +147,8 @@pub mod uaccess;#[cfg( CONFIG_USB = "y" )] pub mod usb; +#[cfg( CONFIG_VFIO )] +pub mod vfio;pub mod workqueue;pub mod xarray;
rust/kernel/vfio.rs new file +430 -0
430 lines not on this page · raw message
Signature · 1 line
2.43.7
PATCH v3 7/9 rust: vfio: add PCI variant driver abstractions
In reply to Simon SongFrom: Danilo Krummrich <[email protected]>
Add Rust abstractions for PCI drivers that extend vfio-pci-core with device-specific operations.
Provide Operations, Device and Registration with separate registration and first-open/last-close data. Allow open data to borrow registration data, undo PCI enablement if open fails, and drop open data before closing the core device.
Let a driver register its VFIO device with Registration::new(), for example from its PCI probe callback, and unregister it by dropping the Registration. Let drivers forward PCI reset and error callbacks through the Registration. Let vfio-pci-core select its VGA arbitration callbacks. Because runtime PM support follows in a separate patch series, keep the device active while it is registered.
Restrict core I/O helpers to their corresponding callback contexts. Add region mapping helpers, and wire up VFIO core support for device features, matching, IOMMUFD and PASID. Allow passthrough devices to export physical BARs as DMA buffers.
Add pci::ErsResult::from_raw() for the result of the VFIO PCI core's error handler.
--- rust/bindings/bindings_helper.h | 2 + rust/kernel/pci.rs | 12 + rust/kernel/vfio.rs | 21 +- rust/kernel/vfio/pci.rs | 777 ++++++++++++++++++++++++++++++++ 4 files changed, 803 insertions(+), 9 deletions(-) create mode 100644 rust/kernel/vfio/pci.rs
rust/bindings/bindings_helper.h +2 -0
@@ -94,6 +94,7 @@#include <linux/tracepoint.h> #include <linux/usb.h> #include <linux/vfio.h> +#include <linux/vfio_pci_core.h> #include <linux/wait.h> #include <linux/workqueue.h> #include <linux/xarray.h>
@@ -117,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_PCI_HOT_RESET =VFIO_DEVICE_PCI_HOT_RESET ;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 ;
rust/kernel/pci.rs +12 -0
@@ -429,6 +429,18 @@ pub enum ErsResult { }impl ErsResult { +#[cfg_attr(not( CONFIG_VFIO_PCI_CORE ), expect(dead_code))] +pub (crate )fn from_raw (result: bindings::pci_ers_result_t ) ->Option <Self > { +match result { + bindings::pci_ers_result_PCI_ERS_RESULT_NONE =>Some (Self ::None ), + bindings::pci_ers_result_PCI_ERS_RESULT_CAN_RECOVER =>Some (Self ::CanRecover ), + bindings::pci_ers_result_PCI_ERS_RESULT_NEED_RESET =>Some (Self ::NeedReset ), + bindings::pci_ers_result_PCI_ERS_RESULT_DISCONNECT =>Some (Self ::Disconnect ), + bindings::pci_ers_result_PCI_ERS_RESULT_RECOVERED =>Some (Self ::Recovered ), + _ =>None , + } + } +fn as_raw (self) -> bindings::pci_ers_result_t {match self {Self ::None => bindings::pci_ers_result_PCI_ERS_RESULT_NONE,
rust/kernel/vfio.rs +12 -9
@@ -3,7 +3,7 @@//! Virtual Function I/O (VFIO) devices and callback data. //! //! [`DeviceBase`] combines a C VFIO device structure with the data its callbacks use. -//! [`Device`] is an alias of it for `struct vfio_device`. +//! [`Device`] and the bus-specific devices, such as `pci::Device`, are aliases of it. //! //! C header: [`include/linux/vfio.h`](srctree/include/linux/vfio.h)
@@ -26,6 +26,9 @@ ptr::NonNull, // }; +#[cfg( CONFIG_VFIO_PCI_CORE )] +pub mod pci; +/// Reset the VFIO device. pub const DEVICE_RESET :u32 = bindings::VFIO_DEVICE_RESET ;
@@ -89,7 +92,7 @@ impl IoContext for GetRegionInfo {}/// The data the driver of a [`Device`] shares with its callbacks. /// -/// Bus-specific devices take the data types from their own trait. +/// Bus-specific devices take the data types from their own trait, such as `pci::Operations`. pub trait Operations :Sized +Send +Sync + 'static {/// Data owned by the registration and passed to VFIO callbacks. ///
@@ -148,8 +151,8 @@ struct CallbackData<R, O> {/// beginning of `Self`, as `vfio_alloc_device()` requires. /// /// `R` and `O` are the types of the registration data and the open data of `T`, written with -/// the placeholder lifetime `'static`. Use the alias [`Device`], which takes both from the -/// operations trait of `T`. +/// the placeholder lifetime `'static`. Use the aliases [`Device`] and `pci::Device`, which +/// take both from the operations trait of `T`. /// /// # Invariants ///
@@ -176,7 +179,7 @@ pub struct DeviceBase<Raw, R, O, T, Ctx: DeviceContext = Normal> { Ctx, >; -#[expect(dead_code)] +#[cfg_attr(not( CONFIG_VFIO_PCI_CORE ), expect(dead_code))] impl <Raw :RawDevice ,R ,O ,T ,Ctx :DeviceContext >DeviceBase <Raw ,R ,O ,T ,Ctx > {/// Initializes the Rust fields of a newly allocated device. ///
@@ -217,7 +220,7 @@ fn as_raw_vfio(&self) -> *mut bindings::vfio_device { } } -#[expect(dead_code)] +#[cfg_attr(not( CONFIG_VFIO_PCI_CORE ), expect(dead_code))] impl <Raw :RawDevice ,R ,O ,T >DeviceBase <Raw ,R ,O ,T > {/// Publishes the registration data passed to callbacks. ///
@@ -258,7 +261,7 @@ unsafe fn close(&self) { } } -#[expect(dead_code)] +#[cfg_attr(not( CONFIG_VFIO_PCI_CORE ), expect(dead_code))] impl <Raw :RawDevice ,R ,O ,T >DeviceBase <Raw ,R ,O ,T ,Open > {/// Creates the open data from the registration data. ///
@@ -301,7 +304,7 @@ unsafe fn open<'a, OD, I>(&'a self, init: impl FnOnce(&'a R) -> I) -> Result } } -#[expect(dead_code)] +#[cfg_attr(not( CONFIG_VFIO_PCI_CORE ), expect(dead_code))] impl <Raw :RawDevice ,R ,O ,T ,Ctx :IoContext >DeviceBase <Raw ,R ,O ,T ,Ctx > {/// Returns the registration data and the open data, for an I/O callback. ///
@@ -352,7 +355,7 @@ unsafe impl<Raw: RawDevice, R: Send + Sync, O: Send + Sync, T> Sync for DeviceBa/// Capability buffer supplied by VFIO for a region-info callback. pub struct InfoCap <'a> { -#[expect(dead_code)] +#[cfg_attr(not( CONFIG_VFIO_PCI_CORE ), expect(dead_code))] raw: &'amut bindings::vfio_info_cap , }
rust/kernel/vfio/pci.rs new file +777 -0
777 lines not on this page · raw message
Signature · 1 line
2.43.7
PATCH v3 8/9 gpu: nova-core: publish typed SR-IOV PF APIs
In reply to Simon SongFrom: Zhi Wang <[email protected]>
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.
--- 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 | 178 +++++++++++++++++++------ 4 files changed, 171 insertions(+), 45 deletions(-)
drivers/gpu/nova-core/driver.rs +33 -1
@@ -29,7 +29,8 @@ NovaCoreFwCtl, NovaCoreFwCtlData, // }, - gpu::Gpu, // + gpu::Gpu, + vgpu::vgpu_api::NovaCoreVfApi, // };/// Counter for generating unique auxiliary device IDs.
@@ -41,6 +42,10 @@ pub(crate) struct NovaCore<'bound> { _reg: auxiliary::Registration<'bound, ForLt!(NovaCoreApi<'_>)>, /// Unregisters fwctl and drains its callbacks before GPU resources are dropped. _fwctl: fwctl::Registration<'bound, NovaCoreFwCtl>, +#[allow(clippy::type_complexity)] +#[pin] +#[uses('gpu: invariant)] + _vf_registration: pci::VfRegistration<'gpu, ForLt!(NovaCoreVfApi<'_>)>,#[pin] pub(crate) gpu: Gpu<'bound>, bar: pci::Bar<'bound, BAR0_SIZE>,
@@ -112,6 +117,10 @@ fn probe<'bound>(try_pin_init! (NovaCore { _: { +if pdev.is_virtfn () { +return Err (ENODEV ); + } + pdev.enable_device_mem ()?; pdev.set_master (); },
@@ -150,6 +159,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)) + }, + _reg: {// TODO: Use `&gpu` self-referential pin-init syntax once available. //
@@ -198,4 +213,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 (()) + } }
drivers/gpu/nova-core/nova_core.rs +2 -1
@@ -31,9 +31,10 @@mod vbios;mod vgpu; -#[cfg( CONFIG_PCI_IOV )] pub use vgpu::vgpu_api::{NovaCoreVfApi , +NovaCoreVfApiHandle , +VgpuInstance ,VgpuTypeInfo ,// };
drivers/gpu/nova-core/vgpu.rs +0 -1
@@ -42,7 +42,6 @@mod instance;mod log;mod scrubber; -#[cfg_attr(not( CONFIG_PCI_IOV ), expect(dead_code, unreachable_pub))] pub (crate )mod vgpu_api;mod vram;
drivers/gpu/nova-core/vgpu/vgpu_api.rs +136 -42
234 lines not on this page · raw message
Signature · 1 line
2.43.7
PATCH v3 9/9 vfio/nova-vgpu: add the Rust VFIO variant driver
In reply to Simon SongFrom: Danilo Krummrich <[email protected]>
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.
Match NVIDIA devices through a VFIO override-only entry. 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.
--- 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 | 375 ++++++++++++++++++++++++ 6 files changed, 414 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
drivers/gpu/Makefile +12 -3
@@ -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
drivers/vfio/pci/Kconfig +2 -0
@@ -74,4 +74,6 @@ source "drivers/vfio/pci/qat/Kconfig" source "drivers/vfio/pci/xe/Kconfig" +source "drivers/vfio/pci/nova-vgpu/Kconfig" + endmenu
drivers/vfio/pci/Makefile +2 -0
@@ -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.
drivers/vfio/pci/nova-vgpu/Kconfig new file +20 -0
@@ -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 + select VFIO_PCI_CORE + 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.
drivers/vfio/pci/nova-vgpu/Makefile new file +3 -0
@@ -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).
drivers/vfio/pci/nova-vgpu/nova_vgpu.rs new file +375 -0
375 lines not on this page · raw message
Signature · 1 line
2.43.7