Skip to contentSkip to conversation

Add Rust PCI SR-IOV support

PATCH Applied Simon Song 3 participants 25 messages Nov 11 – Nov 17

Subsystems (11)
DRM drivers KVM PCI Driver core +7 more subsystems
lore
Share & tools
lore

Simon Song

author
#0 lore raw

v6 cover Add Rust PCI SR-IOV support

Rust PCI drivers need to configure SR-IOV and let VF drivers borrow selected PF-owned data. This series provides those operations and a registration that keeps the shared data available until VF removal completes.

This builds on Peter Colberg's Rust PCI SR-IOV series [1] and Danilo Krummrich's typed PF registration design [2]. The PF/VF sample demonstrates the interface using QEMU's 82576 emulation.

Drivers implement separate sriov_enable() and sriov_disable() callbacks, each receiving pinned driver data and a token for the requested operation. Enabling VFs returns a guard that disables them if later setup fails. Returning the guard successfully leaves the VFs enabled, with VfRegistration owning their final teardown. Drivers that do not share data with VFs can register ().

Changes since v5 [3]:
- Stub the SR-IOV API when CONFIG_PCI_IOV is disabled instead of cfg-gating it, so drivers need no configuration guards, following Danilo's suggested diff [4].
- Add SriovEnable::enable_all() (patch 9), following Danilo's suggestion [4].
- Split the drvdata_borrow() safety documentation fix into its own patch (patch 5), and explain why driver data is dropped before remove() returns, following Danilo's and Alexandre's review.
- Use NonZero<u16> for the requested VF count, const_assert!() and #[optional] for the paired SR-IOV callbacks, and document the errors returned by SriovEnable::enable(), following Alexandre's review.
- Build the sample as a single module with the PF and VF drivers in separate files, and simplify it, following Danilo's and Alexandre's review.
- Collect Alexandre's Reviewed-by (patches 1-4, 8 and 10) and Bjorn's Acked-by for include/linux/pci.h (patch 7).
- Dropped Alexandre's Reviewed-by from patch 7 after adding CONFIG_PCI_IOV=n support; the revised patch needs renewed review.

[1]
https://lore.kernel.org/rust-for-linux/[email protected]/
[2]
https://lore.kernel.org/nova-gpu/[email protected]/
[3]
https://lore.kernel.org/all/[email protected]/T/
[4]
https://lore.kernel.org/nova-gpu/[email protected]/

John Hubbard (1):
rust: pci: add is_virtfn(), to check for VFs

Peter Colberg (5):
rust: pci: add internal SR-IOV enable and disable helpers
rust: pci: add vtable attribute to pci::Driver trait
rust: pci: add num_vf(), to return number of VFs
rust: pci: add SR-IOV enable and disable callbacks
samples: rust: add a Rust SR-IOV PF and VF driver sample

Simon Song (1):
rust: pci: add SriovEnable::enable_all(), to enable all requested VFs

Zhi Wang (4):
rust: device: clarify the drvdata_borrow() safety requirement
rust: pci: drop driver data before remove returns
rust: pci: add typed SR-IOV PF registration data
rust: pci: add SR-IOV enable and disable tokens

 MAINTAINERS                           |   1 +
 drivers/gpu/nova-core/driver.rs       |   1 +
 include/linux/pci.h                   |   7 +
 rust/helpers/pci.c                    |  16 +
 rust/kernel/device.rs                 |   4 +-
 rust/kernel/pci.rs                    | 116 +++++++
 rust/kernel/pci/iov.rs                | 468 ++++++++++++++++++++++++++
 samples/rust/Kconfig                  |  11 +
 samples/rust/Makefile                 |   1 +
 samples/rust/rust_dma.rs              |   1 +
 samples/rust/rust_driver_auxiliary.rs |   1 +
 samples/rust/rust_driver_pci.rs       |   1 +
 samples/rust/rust_driver_sriov.rs     | 178 ++++++++++
 samples/rust/rust_driver_sriov_vf.rs  |  49 +++
 14 files changed, 853 insertions(+), 2 deletions(-)
 create mode 100644 rust/kernel/pci/iov.rs
 create mode 100644 samples/rust/rust_driver_sriov.rs
 create mode 100644 samples/rust/rust_driver_sriov_vf.rs

base-commit: 6e557330b874b0e1fdd03e8fe4c438f36c93eefa

Signature · 1 line
2.43.7
author
#1 lore raw

PATCH v6 1/11 rust: pci: add internal SR-IOV enable and disable helpers

From: Peter Colberg <[email protected]>

Wrap pci_enable_sriov() and pci_disable_sriov() on Device<CoreInternal> for use by the SR-IOV callback tokens and their rollback guard. Keep these operations internal so drivers can only enable or disable VFs through the callback-scoped API introduced later in this series.

Stub both helpers when CONFIG_PCI_IOV is disabled, so the SR-IOV API builds regardless and drivers need no configuration guards.

---
 rust/helpers/pci.c     | 11 ++++++++++
 rust/kernel/pci.rs     |  1 +
 rust/kernel/pci/iov.rs | 48 ++++++++++++++++++++++++++++++++++++++++++
 3 files changed, 60 insertions(+)
 create mode 100644 rust/kernel/pci/iov.rs
rust/helpers/pci.c +11 -0
index a8540f90b13c..a87b5a77efef 100644
@@ -41,6 +41,17 @@ __rust_helper u32 rust_helper_pci_ext_cap_next(u32 header)
 }
 
 #ifndef CONFIG_PCI_IOV
+__rust_helper int rust_helper_pci_enable_sriov(struct pci_dev *pdev,
+					       int nr_virtfn)
+{
+	return pci_enable_sriov(pdev, nr_virtfn);
+}
+
+__rust_helper void rust_helper_pci_disable_sriov(struct pci_dev *pdev)
+{
+	pci_disable_sriov(pdev);
+}
+
 __rust_helper unsigned int
 rust_helper_pci_sriov_get_totalvfs(struct pci_dev *pdev)
 {
rust/kernel/pci.rs +1 -0
index 769d01d23429..8a4af261d1d4 100644
@@ -36,6 +36,7 @@
 mod cap;
 mod id;
 mod io;
+mod iov;
 mod irq;
 
 pub use self::cap::{
rust/kernel/pci/iov.rs new file +48 -0

48 lines not on this page · raw message

Signature · 1 line
2.43.7
#2 lore raw

Re: [PATCH v6 01/11] rust: pci: add internal SR-IOV enable and disable helpers

Sashiko has reviewed this patch and found no issues.
Quoted 7 lines

From: Peter Colberg <[email protected]>

Wrap pci_enable_sriov() and pci_disable_sriov() on Device<CoreInternal> for use by the SR-IOV callback tokens and their rollback guard. Keep these operations internal so drivers can only enable or disable VFs through the callback-scoped API introduced later in this series.

Quoted 8 lines

Stub both helpers when CONFIG_PCI_IOV is disabled, so the SR-IOV API builds regardless and drivers need no configuration guards.

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=1
author
#3 lore raw

PATCH v6 2/11 rust: pci: add vtable attribute to pci::Driver trait

In reply to Simon Song

From: Peter Colberg <[email protected]>

Add the #[vtable] attribute to pci::Driver and its implementations to support the optional sriov_enable() and sriov_disable() callbacks introduced later in this series.

---
 drivers/gpu/nova-core/driver.rs       | 1 +
 rust/kernel/pci.rs                    | 2 ++
 samples/rust/rust_dma.rs              | 1 +
 samples/rust/rust_driver_auxiliary.rs | 1 +
 samples/rust/rust_driver_pci.rs       | 1 +
 5 files changed, 6 insertions(+)
drivers/gpu/nova-core/driver.rs +1 -0
index 560a70c4f5a7..65897c303e7f 100644
@@ -91,6 +91,7 @@ pub(crate) fn bar1_resource_index(pdev: &pci::Device<Bound>) -> Result<u32> {
     ]
 );
 
+#[vtable]
 impl pci::Driver for NovaCoreDriver {
     type IdInfo = ();
     type Data<'bound> = NovaCore<'bound>;
rust/kernel/pci.rs +2 -0
index 8a4af261d1d4..4d32b55779fd 100644
@@ -282,6 +282,7 @@ macro_rules! pci_device_table {
 ///     ]
 /// );
 ///
+/// #[vtable]
 /// impl pci::Driver for MyDriver {
 ///     type IdInfo = ();
 ///     type Data<'bound> = Self;
@@ -297,6 +298,7 @@ macro_rules! pci_device_table {
 ///```
 /// Drivers must implement this trait in order to get a PCI driver registered. Please refer to the
 /// `Adapter` documentation for an example.
+#[vtable]
 pub trait Driver {
     /// The type holding information about each device id supported by the driver.
     // TODO: Use `associated_type_defaults` once stabilized:
samples/rust/rust_dma.rs +1 -0
index ffb693544673..804d55a63005 100644
@@ -69,6 +69,7 @@ unsafe impl kernel::transmute::FromBytes for MyStruct {}
     [(pci::DeviceId::from_id(pci::Vendor::REDHAT, 0x5), ())]
 );
 
+#[vtable]
 impl pci::Driver for DmaSampleDriver {
     type IdInfo = ();
     type Data<'bound> = DmaSampleData<'bound>;
samples/rust/rust_driver_auxiliary.rs +1 -0
index 0bee16faecc6..6cff9bf8c80c 100644
@@ -90,6 +90,7 @@ struct ParentData<'bound> {
     [(pci::DeviceId::from_id(pci::Vendor::REDHAT, 0x5), ())]
 );
 
+#[vtable]
 impl pci::Driver for ParentDriver {
     type IdInfo = ();
     type Data<'bound> = ParentData<'bound>;
samples/rust/rust_driver_pci.rs +1 -0
index 13b035a95756..50c8709739c6 100644
@@ -139,6 +139,7 @@ fn config_space(pdev: &pci::Device<Bound>) {
     }
 }
 
+#[vtable]
 impl pci::Driver for SampleDriver {
     type IdInfo = TestIndex;
     type Data<'bound> = SampleDriverData<'bound>;
Signature · 1 line
2.43.7
#4 lore raw

Re: [PATCH v6 02/11] rust: pci: add vtable attribute to pci::Driver trait

Sashiko has reviewed this patch and found no issues.
Quoted 11 lines

From: Peter Colberg <[email protected]>

Add the #[vtable] attribute to pci::Driver and its implementations to support the optional sriov_enable() and sriov_disable() callbacks introduced later in this series.

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=2
author
#5 lore raw

PATCH v6 3/11 rust: pci: add is_virtfn(), to check for VFs

In reply to Simon Song

From: John Hubbard <[email protected]>

Add a method to check if a PCI device is a Virtual Function (VF) created through Single Root I/O Virtualization (SR-IOV).

---
 rust/kernel/pci.rs | 7 +++++++
 1 file changed, 7 insertions(+)
rust/kernel/pci.rs +7 -0
index 4d32b55779fd..9e31b9bb4d0d 100644
@@ -362,6 +362,13 @@ fn as_raw(&self) -> *mut bindings::pci_dev {
 }
 
 impl Device {
+    /// Returns `true` if this device is a Virtual Function (VF).
+    #[inline]
+    pub fn is_virtfn(&self) -> bool {
+        // SAFETY: `self.as_raw` is a valid pointer to a `struct pci_dev`.
+        unsafe { (*self.as_raw()).is_virtfn() != 0 }
+    }
+
     /// Returns the PCI vendor ID as [`Vendor`].
     ///
     /// # Examples
Signature · 1 line
2.43.7
#6 lore raw

Re: [PATCH v6 03/11] rust: pci: add is_virtfn(), to check for VFs

Sashiko has reviewed this patch and found no issues.
Quoted 5 lines

From: John Hubbard <[email protected]>

Add a method to check if a PCI device is a Virtual Function (VF) created through Single Root I/O Virtualization (SR-IOV).

Quoted 7 lines

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=3
author
#7 lore raw

PATCH v6 4/11 rust: pci: add num_vf(), to return number of VFs

In reply to Simon Song

From: Peter Colberg <[email protected]>

Add a method to return the number of Virtual Functions (VF) enabled for a Physical Function (PF).

Expose the query in the PCI core callback context and return u16, matching the type of the VF count stored by the PCI core.

---
 rust/helpers/pci.c     |  5 +++++
 rust/kernel/pci/iov.rs | 13 +++++++++++++
 2 files changed, 18 insertions(+)
rust/helpers/pci.c +5 -0
index a87b5a77efef..57c28ddeeb9b 100644
@@ -52,6 +52,11 @@ __rust_helper void rust_helper_pci_disable_sriov(struct pci_dev *pdev)
 	pci_disable_sriov(pdev);
 }
 
+__rust_helper int rust_helper_pci_num_vf(struct pci_dev *pdev)
+{
+	return pci_num_vf(pdev);
+}
+
 __rust_helper unsigned int
 rust_helper_pci_sriov_get_totalvfs(struct pci_dev *pdev)
 {
rust/kernel/pci/iov.rs +13 -0
index 18e42b2d3965..78e279169be1 100644
@@ -11,6 +11,19 @@
     prelude::*, //
 };
 
+impl Device<device::Core<'_>> {
+    /// Returns the number of Virtual Functions (VF) enabled for a Physical Function (PF).
+    ///
+    /// Returns zero when `CONFIG_PCI_IOV` is disabled.
+    #[inline]
+    pub fn num_vf(&self) -> u16 {
+        // SAFETY: `self.as_raw()` is valid and this call runs in the PCI core callback context.
+        unsafe { bindings::pci_num_vf(self.as_raw()) }
+            .try_into()
+            .expect("pdev->sriov->num_VFs is u16")
+    }
+}
+
 impl Device<device::CoreInternal<'_>> {
     /// Enable the Single Root I/O Virtualization (SR-IOV) capability for this device,
     /// where `nr_virtfn` is number of Virtual Functions (VF) to enable.
Signature · 1 line
2.43.7
#8 lore raw

Re: [PATCH v6 04/11] rust: pci: add num_vf(), to return number of VFs

Sashiko has reviewed this patch and found no issues.
Quoted 5 lines

From: Peter Colberg <[email protected]>

Add a method to return the number of Virtual Functions (VF) enabled for a Physical Function (PF).

Quoted 7 lines

Expose the query in the PCI core callback context and return u16, matching the type of the VF count stored by the PCI core.

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=4
author
#9 lore raw

PATCH v6 5/11 rust: device: clarify the drvdata_borrow() safety requirement

In reply to Simon Song

From: Zhi Wang <[email protected]>

The safety requirement of drvdata_borrow() says it must only be called after Device::set_drvdata() and before the device is fully unbound. This describes when the stored data is expected to be present, rather than the requirement itself.

State the requirement directly: the data stored by Device::set_drvdata() must still be installed and remain valid for the returned borrow.

---
 rust/kernel/device.rs | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
rust/kernel/device.rs +2 -2
index 2291d85b6849..1f6bb58396e2 100644
@@ -243,8 +243,8 @@ impl<Ctx: InternalBoundContext> Device<Ctx> {
     ///
     /// # Safety
     ///
-    /// - Must only be called after a preceding call to [`Device::set_drvdata`] and before the
-    ///   device is fully unbound.
+    /// - The data stored by [`Device::set_drvdata`] must still be installed and remain valid
+    ///   for the returned borrow.
     /// - The type `T` must match the type of the `ForeignOwnable` previously stored by
     ///   [`Device::set_drvdata`].
     pub unsafe fn drvdata_borrow<T>(&self) -> Pin<&T> {
Signature · 1 line
2.43.7
#10 lore raw

Re: [PATCH v6 05/11] rust: device: clarify the drvdata_borrow() safety requirement

Sashiko has reviewed this patch and found no issues.
Quoted 7 lines

From: Zhi Wang <[email protected]>

The safety requirement of drvdata_borrow() says it must only be called after Device::set_drvdata() and before the device is fully unbound. This describes when the stored data is expected to be present, rather than the requirement itself.

Quoted 6 lines

State the requirement directly: the data stored by Device::set_drvdata() must still be installed and remain valid for the returned borrow.

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=5
author
#11 lore raw

PATCH v6 6/11 rust: pci: drop driver data before remove returns

In reply to Simon Song

From: Zhi Wang <[email protected]>

A Rust PCI driver's private data is currently dropped by driver::Registration::post_unbind_callback(). The driver core calls it from device_unbind_cleanup(), after the PCI bus remove callback, pci_device_remove(), has returned.

VF drivers will store a vfio::pci::Registration in their private data, which calls vfio_pci_core_register_device() when created and vfio_pci_core_unregister_device() when destroyed.

vfio_pci_core_unregister_device() expects to be called from pci_device_remove(), and hence can't be deferred beyond it. This also makes it incompatible with devres, i.e. a devm_vfio_pci_core_register_device() helper wouldn't work either, since devres_release_all() also runs from device_unbind_cleanup().

Hence, drop the private data in pci::Adapter::remove_callback(), so it is dropped before pci_device_remove() returns.

This is a special case for VFIO-PCI. In general, a driver's private data must not rely on being dropped from the bus remove callback; any point after the driver's remove callback and before devres_release_all() in device_unbind_cleanup() is sufficient.

---
 rust/kernel/pci.rs | 13 +++++++++++++
 1 file changed, 13 insertions(+)
rust/kernel/pci.rs +13 -0
index 9e31b9bb4d0d..75d764975a4e 100644
@@ -149,6 +149,19 @@ extern "C" fn remove_callback(pdev: *mut bindings::pci_dev) {
         let data = unsafe { pdev.as_ref().drvdata_borrow::<T::Data<'_>>() };
 
         T::unbind(pdev, data);
+
+        // SAFETY: The driver's unbind callback has returned, and no callbacks retain a borrow.
+        let data = unsafe { pdev.as_ref().drvdata_obtain::<T::Data<'_>>() };
+
+        // Drop the private data here, ahead of `driver::Registration::post_unbind_callback()`,
+        // which would otherwise drop it after `pci_device_remove()` returns. `drvdata_obtain()`
+        // has cleared the driver data pointer, so that callback finds nothing left to drop.
+        //
+        // This is a special case for VFIO-PCI: `vfio_pci_core_unregister_device()` must be
+        // called from `pci_device_remove()`. In general, private data must not rely on being
+        // dropped from the bus remove callback; any point after the driver's remove callback and
+        // before `devres_release_all()` in `device_unbind_cleanup()` is sufficient.
+        drop(data);
     }
 }
 
Signature · 1 line
2.43.7
#12 lore raw

Re: [PATCH v6 06/11] rust: pci: drop driver data before remove returns

Sashiko has reviewed this patch and found no issues.
Quoted 20 lines

From: Zhi Wang <[email protected]>

A Rust PCI driver's private data is currently dropped by driver::Registration::post_unbind_callback(). The driver core calls it from device_unbind_cleanup(), after the PCI bus remove callback, pci_device_remove(), has returned.

VF drivers will store a vfio::pci::Registration in their private data, which calls vfio_pci_core_register_device() when created and vfio_pci_core_unregister_device() when destroyed.

vfio_pci_core_unregister_device() expects to be called from pci_device_remove(), and hence can't be deferred beyond it. This also makes it incompatible with devres, i.e. a devm_vfio_pci_core_register_device() helper wouldn't work either, since devres_release_all() also runs from device_unbind_cleanup().

Hence, drop the private data in pci::Adapter::remove_callback(), so it is dropped before pci_device_remove() returns.

Quoted 8 lines

This is a special case for VFIO-PCI. In general, a driver's private data must not rely on being dropped from the bus remove callback; any point after the driver's remove callback and before devres_release_all() in device_unbind_cleanup() is sufficient.

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=6
author
#13 lore raw

PATCH v6 7/11 rust: pci: add typed SR-IOV PF registration data

In reply to Simon Song

From: Zhi Wang <[email protected]>

Rust PF and VF drivers bind to separate PCI devices and may reside in different modules. A VF driver that calls PF operations needs typed access to the data exposed by the PF driver. This data must remain valid until VF driver removal completes.

Add VfRegistration to register a pinned object in the PF's private data. VF drivers can borrow it after checking the requested Rust type, using a higher-ranked closure or a covariant lifetime encoding.

Keep VfRegistration usable when CONFIG_PCI_IOV is disabled so PF drivers need no configuration guards around their registration field or its initialization.

Capture the core callback context in the initializer. Reject active VFs and an occupied registration slot before initializing the payload, then recheck the slot before publication in case the payload initializer created another registration. Publish only after all fallible work.

During registration teardown, disable SR-IOV and wait for VF remove callbacks to finish before clearing the pointer and dropping the object.

---
 include/linux/pci.h    |   7 ++
 rust/kernel/pci.rs     |   1 +
 rust/kernel/pci/iov.rs | 258 ++++++++++++++++++++++++++++++++++++++++-
 3 files changed, 265 insertions(+), 1 deletion(-)
include/linux/pci.h +7 -0
index aa3765a20a96..01b82f6561ce 100644
@@ -552,6 +552,13 @@ struct pci_dev {
 	u16		ats_cap;	/* ATS Capability offset */
 	u8		ats_stu;	/* ATS Smallest Translation Unit */
 #endif
+#if defined(CONFIG_PCI_IOV) && defined(CONFIG_RUST)
+	/*
+	 * Private data owned by the PF's Rust driver, readable by VF drivers
+	 * through the PCI VF registration data Rust abstraction.
+	 */
+	void		*vf_registration_data_rust;
+#endif
 #ifdef CONFIG_PCI_PRI
 	u16		pri_cap;	/* PRI Capability offset */
 	u32		pri_reqs_alloc; /* Number of PRI requests allocated */
rust/kernel/pci.rs +1 -0
index 75d764975a4e..033c49363d1e 100644
@@ -59,6 +59,7 @@
     Extended,
     Normal, //
 };
+pub use self::iov::VfRegistration;
 pub use self::irq::{
     IrqType,
     IrqTypes,
rust/kernel/pci/iov.rs +257 -1

268 lines not on this page · raw message

Signature · 1 line
2.43.7
#14 lore raw

Re: [PATCH v6 07/11] rust: pci: add typed SR-IOV PF registration data

Sashiko has reviewed this patch and found no issues.
Quoted 20 lines

From: Zhi Wang <[email protected]>

Rust PF and VF drivers bind to separate PCI devices and may reside in different modules. A VF driver that calls PF operations needs typed access to the data exposed by the PF driver. This data must remain valid until VF driver removal completes.

Add VfRegistration to register a pinned object in the PF's private data. VF drivers can borrow it after checking the requested Rust type, using a higher-ranked closure or a covariant lifetime encoding.

Keep VfRegistration usable when CONFIG_PCI_IOV is disabled so PF drivers need no configuration guards around their registration field or its initialization.

Capture the core callback context in the initializer. Reject active VFs and an occupied registration slot before initializing the payload, then recheck the slot before publication in case the payload initializer created another registration. Publish only after all fallible work.

Quoted 8 lines

During registration teardown, disable SR-IOV and wait for VF remove callbacks to finish before clearing the pointer and dropping the object.

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=7
author
#15 lore raw

PATCH v6 8/11 rust: pci: add SR-IOV enable and disable tokens

In reply to Simon Song

From: Zhi Wang <[email protected]>

Enabling VFs can succeed before the driver's remaining setup fails. Use a callback-scoped token to return an enabled guard that disables SR-IOV when dropped, rolling back those VFs on a later error.

Add SriovEnable, SriovEnabled and SriovDisable for the split callbacks introduced later in this series. Tie each token to its PF and callback lifetime, and limit the enabled count to the user's request. The PCI adapter disarms the guard when accepting a successful enable callback.

Require a VfRegistration to own final VF teardown after that handoff. Drivers that do not share data with VFs can register (). A disable token permits explicit shutdown without forcing it on a rejected request.

---
 rust/kernel/pci.rs     |   7 ++-
 rust/kernel/pci/iov.rs | 102 +++++++++++++++++++++++++++++++++++++++--
 2 files changed, 105 insertions(+), 4 deletions(-)
rust/kernel/pci.rs +6 -1
index 033c49363d1e..077fa80e7425 100644
@@ -59,7 +59,12 @@
     Extended,
     Normal, //
 };
-pub use self::iov::VfRegistration;
+pub use self::iov::{
+    SriovDisable,
+    SriovEnable,
+    SriovEnabled,
+    VfRegistration, //
+};
 pub use self::irq::{
     IrqType,
     IrqTypes,
rust/kernel/pci/iov.rs +99 -3

126 lines not on this page · raw message

Signature · 1 line
2.43.7
#16 lore raw

Re: [PATCH v6 08/11] rust: pci: add SR-IOV enable and disable tokens

Sashiko has reviewed this patch and found no issues.
Quoted 16 lines

From: Zhi Wang <[email protected]>

Enabling VFs can succeed before the driver's remaining setup fails. Use a callback-scoped token to return an enabled guard that disables SR-IOV when dropped, rolling back those VFs on a later error.

Add SriovEnable, SriovEnabled and SriovDisable for the split callbacks introduced later in this series. Tie each token to its PF and callback lifetime, and limit the enabled count to the user's request. The PCI adapter disarms the guard when accepting a successful enable callback.

Require a VfRegistration to own final VF teardown after that handoff. Drivers that do not share data with VFs can register (). A disable token permits explicit shutdown without forcing it on a rejected request.

Quoted 4 lines

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=8
author
#17 lore raw

PATCH v6 9/11 rust: pci: add SriovEnable::enable_all(), to enable all requested VFs

In reply to Simon Song

PF drivers typically enable all VFs that userspace requests through sriov_numvfs. With the SriovEnable token this takes two steps:
enable() consumes the token, so the requested count has to be read from it first:

	let num_vfs = token.num_vfs();
	token.enable(num_vfs)

Add enable_all() for this common case. It passes the requested number of VFs to enable(), so callers do not need to handle the count.

---
 rust/kernel/pci/iov.rs | 14 ++++++++++++++
 1 file changed, 14 insertions(+)
rust/kernel/pci/iov.rs +14 -0
index bda2bffffcda..a3d1c4c567f7 100644
@@ -158,6 +158,20 @@ pub fn enable(self, num_vfs: NonZero<u16>) -> Result<SriovEnabled<'a>> {
             num_vfs,
         })
     }
+
+    /// Enables all VFs requested for this callback.
+    ///
+    /// This is equivalent to calling [`Self::enable()`] with [`Self::num_vfs()`].
+    ///
+    /// # Errors
+    ///
+    /// - [`ENODEV`]: the PF driver has not registered a [`VfRegistration`].
+    /// - Any error returned by `pci_enable_sriov()`.
+    #[inline]
+    pub fn enable_all(self) -> Result<SriovEnabled<'a>> {
+        let num_vfs = self.num_vfs;
+        self.enable(num_vfs)
+    }
 }
 
 /// Enabled VFs awaiting successful completion of `sriov_enable()`.
Signature · 1 line
2.43.7
#18 lore raw

Re: [PATCH v6 09/11] rust: pci: add SriovEnable::enable_all(), to enable all requested VFs

Sashiko has reviewed this patch and found no issues.
Quoted 5 lines

PF drivers typically enable all VFs that userspace requests through sriov_numvfs. With the SriovEnable token this takes two steps:
enable() consumes the token, so the requested count has to be read from it first:

Quoted 8 lines
	let num_vfs = token.num_vfs();
	token.enable(num_vfs)

Add enable_all() for this common case. It passes the requested number of VFs to enable(), so callers do not need to handle the count.

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=9
author
#19 lore raw

PATCH v6 10/11 rust: pci: add SR-IOV enable and disable callbacks

In reply to Simon Song

From: Peter Colberg <[email protected]>

Allow Rust PCI drivers to configure SR-IOV through sriov_numvfs. Split the C configure callback into sriov_enable() and sriov_disable(), passing pinned driver data and a token for the requested operation. Require drivers to implement both callbacks together.

Return the enabled guard's VF count on success and disarm its rollback. On a disable request, verify that the driver has removed all VFs before reporting success. VfRegistration handles VF removal during PF teardown; these callbacks only handle explicit configuration requests.

The PCI core invokes sriov_configure only through the PF-only sriov_numvfs sysfs attribute, so no extra PF role check is needed.

---
 rust/kernel/pci.rs     | 87 ++++++++++++++++++++++++++++++++++++++++++
 rust/kernel/pci/iov.rs | 55 ++++++++++++++++++++++----
 2 files changed, 135 insertions(+), 7 deletions(-)
rust/kernel/pci.rs +87 -0
index 077fa80e7425..4887052d31b1 100644
@@ -94,12 +94,20 @@ unsafe fn register(
         name: &'static CStr,
         module: &'static ThisModule,
     ) -> Result {
+        const_assert!(
+            T::HAS_SRIOV_ENABLE == T::HAS_SRIOV_DISABLE,
+            "PCI drivers must implement both sriov_enable and sriov_disable"
+        );
+
         // SAFETY: It's safe to set the fields of `struct pci_driver` on initialization.
         unsafe {
             (*pdrv.get()).name = name.as_char_ptr();
             (*pdrv.get()).probe = Some(Self::probe_callback);
             (*pdrv.get()).remove = Some(Self::remove_callback);
             (*pdrv.get()).id_table = T::ID_TABLE.as_ptr();
+            if T::HAS_SRIOV_ENABLE {
+                (*pdrv.get()).sriov_configure = Some(Self::sriov_configure_callback);
+            }
         }
 
         // SAFETY: `pdrv` is guaranteed to be a valid `DriverType`.
@@ -355,6 +363,85 @@ fn probe<'bound>(
     fn unbind<'bound>(dev: &'bound Device<device::Core<'_>>, this: Pin<&Self::Data<'bound>>) {
         let _ = (dev, this);
     }
+
+    /// Enables Single Root I/O Virtualization (SR-IOV) for a PF.
+    ///
+    /// This callback is only invoked when `CONFIG_PCI_IOV` is enabled.
+    ///
+    /// Called when userspace writes a nonzero VF count to `sriov_numvfs`. The token carries the
+    /// requested count and permission to enable VFs on this PF. Return the guard obtained from
+    /// [`SriovEnable::enable()`] after completing setup; dropping it rolls back the enable.
+    ///
+    /// The PF must own a [`VfRegistration`] before enabling VFs. That registration disables
+    /// SR-IOV when the driver data is destroyed, while resources needed by VF drivers remain live.
+    /// Implement this callback and [`Self::sriov_disable()`] together, or implement neither.
+    ///
+    /// See [PCI Express I/O Virtualization].
+    ///
+    /// [PCI Express I/O Virtualization]: https://docs.kernel.org/PCI/pci-iov-howto.html
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// # use kernel::{
+    /// #     device::Core,
+    /// #     pci,
+    /// #     prelude::*, //
+    /// # };
+    /// # struct Data;
+    /// fn sriov_enable<'a>(
+    ///     _dev: &'a pci::Device<Core<'_>>,
+    ///     _data: Pin<&Data>,
+    ///     token: pci::SriovEnable<'a>,
+    /// ) -> Result<pci::SriovEnabled<'a>> {
+    ///     let num_vfs = token.num_vfs();
+    ///     let enabled = token.enable(num_vfs)?;
+    ///     // Complete any additional setup before returning the guard.
+    ///     Ok(enabled)
+    /// }
+    /// ```
+    #[optional]
+    fn sriov_enable<'a>(
+        _dev: &'a Device<device::Core<'_>>,
+        _data: Pin<&Self::Data<'a>>,
+        _token: SriovEnable<'a>,
+    ) -> Result<SriovEnabled<'a>>;
+
+    /// Disables all VFs of a PF in response to a userspace request.
+    ///
+    /// This callback is only invoked when `CONFIG_PCI_IOV` is enabled.
+    ///
+    /// Called when userspace writes zero to `sriov_numvfs`. Call [`SriovDisable::disable()`]
+    /// while resources used by VF drivers are still available. Returning an error before calling
+    /// it leaves the VFs enabled. Returning success requires that all VFs have been disabled.
+    ///
+    /// This callback is not invoked during PF unbind; [`VfRegistration`] owns that teardown.
+    /// Implement this callback and [`Self::sriov_enable()`] together, or implement neither.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// # use kernel::{
+    /// #     device::Core,
+    /// #     pci,
+    /// #     prelude::*, //
+    /// # };
+    /// # struct Data;
+    /// fn sriov_disable<'a>(
+    ///     _dev: &'a pci::Device<Core<'_>>,
+    ///     _data: Pin<&Data>,
+    ///     token: pci::SriovDisable<'a>,
+    /// ) -> Result {
+    ///     token.disable();
+    ///     Ok(())
+    /// }
+    /// ```
+    #[optional]
+    fn sriov_disable<'a>(
+        _dev: &'a Device<device::Core<'_>>,
+        _data: Pin<&Self::Data<'a>>,
+        _token: SriovDisable<'a>,
+    ) -> Result;
 }
 
 /// The PCI device representation.
rust/kernel/pci/iov.rs +48 -7

101 lines not on this page · raw message

Signature · 1 line
2.43.7
#20 lore raw

Re: [PATCH v6 10/11] rust: pci: add SR-IOV enable and disable callbacks

Sashiko has reviewed this patch and found no issues.
Quoted 12 lines

From: Peter Colberg <[email protected]>

Allow Rust PCI drivers to configure SR-IOV through sriov_numvfs. Split the C configure callback into sriov_enable() and sriov_disable(), passing pinned driver data and a token for the requested operation. Require drivers to implement both callbacks together.

Return the enabled guard's VF count on success and disarm its rollback. On a disable request, verify that the driver has removed all VFs before reporting success. VfRegistration handles VF removal during PF teardown; these callbacks only handle explicit configuration requests.

Quoted 8 lines

The PCI core invokes sriov_configure only through the PF-only sriov_numvfs sysfs attribute, so no extra PF role check is needed.

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=10
author
#21 lore raw

PATCH v6 11/11 samples: rust: add a Rust SR-IOV PF and VF driver sample

In reply to Simon Song

From: Peter Colberg <[email protected]>

Add a sample module with a PF and a VF driver that demonstrates SR-IOV using QEMU's 82576 (igb) emulation.

The PF publishes a pinned API object in its private data and provides a submit_request() helper. The VF calls this helper with its Bound device borrow. The helper performs the typed registration lookup, so the VF driver does not use the API object or its lifetime encoding directly.

Keep the PF and VF drivers in separate files, but build them into a single module that registers both drivers. Separate modules would need cross-crate Rust symbol exports, which can be added once the build system supports them.

Unbinding the PF disables SR-IOV and removes its VFs before releasing the registered data.

---
 MAINTAINERS                          |   1 +
 samples/rust/Kconfig                 |  11 ++
 samples/rust/Makefile                |   1 +
 samples/rust/rust_driver_sriov.rs    | 178 +++++++++++++++++++++++++++
 samples/rust/rust_driver_sriov_vf.rs |  49 ++++++++
 5 files changed, 240 insertions(+)
 create mode 100644 samples/rust/rust_driver_sriov.rs
 create mode 100644 samples/rust/rust_driver_sriov_vf.rs
MAINTAINERS +1 -0
index 93abbb315065..4ea281037109 100644
@@ -21634,6 +21634,7 @@ F:	rust/helpers/pci.c
 F:	rust/kernel/pci.rs
 F:	rust/kernel/pci/
 F:	samples/rust/rust_driver_pci.rs
+F:	samples/rust/rust_driver_sriov*
 
 PCIE BANDWIDTH CONTROLLER
 M:	Ilpo Järvinen <[email protected]>
samples/rust/Kconfig +11 -0
index 31d62533ef25..b88473558b9d 100644
@@ -128,6 +128,17 @@ config SAMPLE_RUST_DRIVER_PLATFORM
 
 	  If unsure, say N.
 
+config SAMPLE_RUST_DRIVER_SRIOV
+	tristate "SR-IOV PF and VF Drivers"
+	depends on PCI_IOV
+	help
+	  This option builds the Rust SR-IOV PF and VF driver sample.
+
+	  To compile this as a module, choose M here:
+	  the module will be called rust_driver_sriov.
+
+	  If unsure, say N.
+
 config SAMPLE_RUST_DRIVER_USB
 	tristate "USB Driver"
 	depends on USB = y
samples/rust/Makefile +1 -0
index b986b681cde5..238a11d5ec39 100644
@@ -11,6 +11,7 @@ obj-$(CONFIG_SAMPLE_RUST_DRIVER_I2C)		+= rust_driver_i2c.o
 obj-$(CONFIG_SAMPLE_RUST_I2C_CLIENT)		+= rust_i2c_client.o
 obj-$(CONFIG_SAMPLE_RUST_DRIVER_PCI)		+= rust_driver_pci.o
 obj-$(CONFIG_SAMPLE_RUST_DRIVER_PLATFORM)	+= rust_driver_platform.o
+obj-$(CONFIG_SAMPLE_RUST_DRIVER_SRIOV)		+= rust_driver_sriov.o
 obj-$(CONFIG_SAMPLE_RUST_DRIVER_USB)		+= rust_driver_usb.o
 obj-$(CONFIG_SAMPLE_RUST_DRIVER_FAUX)		+= rust_driver_faux.o
 obj-$(CONFIG_SAMPLE_RUST_DRIVER_AUXILIARY)	+= rust_driver_auxiliary.o
samples/rust/rust_driver_sriov.rs new file +178 -0

178 lines not on this page · raw message

samples/rust/rust_driver_sriov_vf.rs new file +49 -0

49 lines not on this page · raw message

Signature · 1 line
2.43.7
#22 lore raw

Re: [PATCH v6 11/11] samples: rust: add a Rust SR-IOV PF and VF driver sample

Sashiko has reviewed this patch and found no issues.
Quoted 18 lines

From: Peter Colberg <[email protected]>

Add a sample module with a PF and a VF driver that demonstrates SR-IOV using QEMU's 82576 (igb) emulation.

The PF publishes a pinned API object in its private data and provides a submit_request() helper. The VF calls this helper with its Bound device borrow. The helper performs the typed registration lookup, so the VF driver does not use the API object or its lifetime encoding directly.

Keep the PF and VF drivers in separate files, but build them into a single module that registers both drivers. Separate modules would need cross-crate Rust symbol exports, which can be added once the build system supports them.

Unbinding the PF disables SR-IOV and removes its VFs before releasing the registered data.

Quoted 6 lines

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=11
maintainer Applied
#23 lore raw

Re: (subset) [PATCH v6 00/11] Add Rust PCI SR-IOV support

In reply to Simon Song
Quoted 1 line · Simon Song

[PATCH v6 00/11] Add Rust PCI SR-IOV support

Applied, thanks!

Branch: driver-core-testing
Tree: git://git.kernel.org/pub/scm/linux/kernel/git/driver-core/driver-core.git

[5/11] rust: device: clarify the drvdata_borrow() safety requirement

      commit: d66d8bbb0316

The patch will appear in the next linux-next integration (typically within 24 hours on weekdays).

The patch is in the driver-core-testing branch and will be promoted to driver-core-next after validation.

maintainer Applied
#24 lore raw

Re: (subset) [PATCH v6 00/11] Add Rust PCI SR-IOV support

In reply to Simon Song
Quoted 1 line · Simon Song

[PATCH v6 00/11] Add Rust PCI SR-IOV support

Applied, thanks!

Branch: topic/pci-sriov-7.5-rc1
Tree: git://git.kernel.org/pub/scm/linux/kernel/git/driver-core/driver-core.git

[1/11] rust: pci: add internal SR-IOV enable and disable helpers

      commit: 04d0402a3363
[2/11] rust: pci: add vtable attribute to pci::Driver trait
      commit: 95a327110699
[3/11] rust: pci: add is_virtfn(), to check for VFs
      commit: c2e223197829
[4/11] rust: pci: add num_vf(), to return number of VFs
      commit: 06a9b147241e
[6/11] rust: pci: drop driver data before remove returns
      commit: 5120ea00f3f7

[7/11] rust: pci: add typed SR-IOV PF registration data
commit: 5f0bc9be855a

[ Accept any initializer error E convertible into Error, drop
unnecessary initializer lifetime bounds, and adjust semicolon placement in set_vf_registration_data_ptr(). - Danilo ]

[8/11] rust: pci: add SR-IOV enable and disable tokens

      commit: 36051c35fdb2
[9/11] rust: pci: add SriovEnable::enable_all(), to enable all requested VFs
      commit: 666087381bc0
[10/11] rust: pci: add SR-IOV enable and disable callbacks
      commit: bcb6cb005449

[11/11] samples: rust: add a Rust SR-IOV PF and VF driver sample
commit: 73d3502c8172

[ Reorganize the sample into rust_driver_sriov/ with separate PF and VF
files and a local Makefile, and move the registration lookup into PfApi::submit(). - Danilo ]

The patches are in the topic/pci-sriov-7.5-rc1 topic branch and will be merged into the corresponding target branch soon.