On 12/2/2026 11:19 AM, Gary Guo wrote:
> On Fri Nov 27, 2026 at 10:49 PM GMT, Simon Song wrote:
>> From: 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 drivers to export physical
>> BARs as DMA buffers with per-region length limits.
>>
>> Add pci::ErsResult::from_raw() for the result of the VFIO PCI core's
>> error handler.
>>
>> Signed-off-by: Danilo Krummrich <[email protected]>
>> Signed-off-by: Zhi Wang <[email protected]>
>> Signed-off-by: Simon Song <[email protected]>
>> ---
>> rust/bindings/bindings_helper.h | 2 +
>> rust/kernel/pci.rs | 12 +
>> rust/kernel/vfio.rs | 24 +-
>> rust/kernel/vfio/pci.rs | 812 ++++++++++++++++++++++++++++++++
>> 4 files changed, 842 insertions(+), 8 deletions(-)
>> create mode 100644 rust/kernel/vfio/pci.rs
>>
>> diff --git a/rust/bindings/bindings_helper.h
>> b/rust/bindings/bindings_helper.h
>> index a5781bc1ea85f..b052f1e874e25 100644
>> --- a/rust/bindings/bindings_helper.h
>> +++ b/rust/bindings/bindings_helper.h
>> @@ -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;
>> diff --git a/rust/kernel/pci.rs b/rust/kernel/pci.rs
>> index 3fa6831fe34d8..d6f5b0a9dfc7f 100644
>> --- a/rust/kernel/pci.rs
>> +++ b/rust/kernel/pci.rs
>> @@ -428,6 +428,18 @@ pub enum ErsResult {
>> }
>>
>> impl ErsResult {
>> + #[cfg_attr(not(CONFIG_VFIO_PCI_CORE = "y"), 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,
>> diff --git a/rust/kernel/vfio.rs b/rust/kernel/vfio.rs
>> index f49ff5931df56..ff8b17819ca58 100644
>> --- a/rust/kernel/vfio.rs
>> +++ b/rust/kernel/vfio.rs
>> @@ -3,7 +3,12 @@
>> //! 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 are aliases of it, such as
>> +#."
>> +)]
>> +#![cfg_attr(not(CONFIG_VFIO_PCI_CORE = "y"), doc = "`vfio::pci::Device`.")]
>> //!
>> //! C header: [`include/linux/vfio.h`](srctree/include/linux/vfio.h)
>>
>> @@ -28,6 +33,9 @@
>> ptr::NonNull, //
>> };
>>
>> +#[cfg(CONFIG_VFIO_PCI_CORE = "y")]
>> +pub mod pci;
>> +
>> /// Reset the VFIO device.
>> pub const DEVICE_RESET: u32 = bindings::VFIO_DEVICE_RESET;
>>
>> @@ -91,7 +99,7 @@ impl IoContext for GetRegionInfo {}
>>
>> /// The data the driver of a [`Device`] shares with its callbacks.
>> ///
>> -/// Bus-specific operations traits extend this trait.
>> +/// Bus-specific operations traits, such as `vfio::pci::Operations`, extend
>> this trait.
>> pub trait Operations: Sized + Send + Sync + 'static {
>> /// Data owned by the registration and passed to VFIO callbacks.
>> ///
>> @@ -127,7 +135,7 @@ struct CallbackData<T: Operations> {
>> /// `raw` is the first field, so the `vfio_device` at the beginning of
>> `Raw` is also at the
>> /// beginning of `Self`, as `vfio_alloc_device()` requires.
>> ///
>> -/// Use the alias [`Device`].
>> +/// Use the aliases [`Device`] and `vfio::pci::Device`.
>> ///
>> /// # Invariants
>> ///
>> @@ -148,7 +156,7 @@ pub struct DeviceBase<Raw, T: Operations, Ctx:
>> DeviceContext = Normal> {
>> /// A VFIO device, wrapping `struct vfio_device`.
>> pub type Device<T, Ctx = Normal> = DeviceBase<bindings::vfio_device, T,
>> Ctx>;
>>
>> -#[expect(dead_code)]
>> +#[cfg_attr(not(CONFIG_VFIO_PCI_CORE = "y"), expect(dead_code))]
>
> There're so many of these attr.
>
> How about only enabling vfio abstraction if it's not going to be dead_code, or
> do a global `#![cfg_attr(not(CONFIG_VFIO_PCI_CORE = "y"), expect(dead_code)]`?
>
Thanks, i will use file-wide attributed as you suggested.
>> impl<Raw, T: Operations, Ctx: DeviceContext> DeviceBase<Raw, T, Ctx> {
>> /// Initializes the Rust fields of a newly allocated device.
>> ///
>> @@ -193,7 +201,7 @@ fn as_raw_vfio(&self) -> *mut bindings::vfio_device {
>> }
>> }
>>
>> -#[expect(dead_code)]
>> +#[cfg_attr(not(CONFIG_VFIO_PCI_CORE = "y"), expect(dead_code))]
>> impl<Raw, T: Operations> DeviceBase<Raw, T> {
>> /// Publishes the registration data passed to callbacks.
>> ///
>> @@ -240,7 +248,7 @@ unsafe fn close(&self) {
>> }
>> }
>>
>> -#[expect(dead_code)]
>> +#[cfg_attr(not(CONFIG_VFIO_PCI_CORE = "y"), expect(dead_code))]
>> impl<Raw, T: Operations> DeviceBase<Raw, T, Open> {
>> /// Creates the open data from the registration data.
>> ///
>> @@ -284,7 +292,7 @@ unsafe fn open<'a, 'reg: 'a, I>(
>> }
>> }
>>
>> -#[expect(dead_code)]
>> +#[cfg_attr(not(CONFIG_VFIO_PCI_CORE = "y"), expect(dead_code))]
>> impl<Raw, T: Operations, Ctx: IoContext> DeviceBase<Raw, T, Ctx> {
>> /// Returns the registration data and the open data, for an I/O
>> callback.
>> ///
>> @@ -345,7 +353,7 @@ unsafe impl<Raw, T: Operations> Sync for DeviceBase<Raw,
>> T> {}
>>
>> /// Capability buffer supplied by VFIO for a region-info callback.
>> pub struct InfoCap<'a> {
>> - #[expect(dead_code)]
>> + #[cfg_attr(not(CONFIG_VFIO_PCI_CORE = "y"), expect(dead_code))]
>> raw: &'a mut bindings::vfio_info_cap,
>> }
>>
>> diff --git a/rust/kernel/vfio/pci.rs b/rust/kernel/vfio/pci.rs
>> new file mode 100644
>> index 0000000000000..6805915414b55
>> --- /dev/null
>> +++ b/rust/kernel/vfio/pci.rs
>> @@ -0,0 +1,812 @@
>> +// SPDX-License-Identifier: GPL-2.0
>> +
>> +//! VFIO PCI variant driver abstractions.
>> +//!
>> +//! Provides Rust abstractions for writing VFIO PCI variant drivers (also
>> known
>> +//! as "VFIO PCI core" drivers). A [`Registration`] struct registers the
>> VFIO
>> +//! device and owns its registration data, tying resource lifetimes to the
>> PCI
>> +//! driver's binding scope.
>> +//!
>> +//! C header:
>> [`include/linux/vfio_pci_core.h`](srctree/include/linux/vfio_pci_core.h)
>> +
>> +use super::{
>> + DeviceBase,
>> + InfoCap,
>> + UserBuf, //
>> +};
>> +pub use super::{
>> + DeviceContext,
>> + GetRegionInfo,
>> + IoContext,
>> + Ioctl,
>> + Mmap,
>> + Normal,
>> + Open,
>> + Read,
>> + Write, //
>> +};
>> +
>> +use crate::{
>> + alloc::allocator::Kmalloc,
>> + bindings,
>> + device,
>> + error::{
>> + from_err_ptr,
>> + from_result,
>> + to_result, //
>> + },
>> + mm::virt::VmaNew,
>> + pci,
>> + prelude::*,
>> + sync::aref::ARef,
>> + types::NotThreadSafe,
>> + uaccess::UserPtr, //
>> +};
>> +use core::{
>> + alloc::Layout,
>> + ptr::NonNull, //
>> +};
>> +
>> +/// Reset the PCI slot or bus containing a VFIO device.
>> +pub const DEVICE_PCI_HOT_RESET: u32 = bindings::VFIO_DEVICE_PCI_HOT_RESET;
>> +
>> +/// Index of the PCI configuration-space region.
>> +pub const CONFIG_REGION_INDEX: u32 = bindings::VFIO_PCI_CONFIG_REGION_INDEX;
>
> Can these be new types?
>
ah, DEVICE_PCI_HOT_RESET should actually be removed since we no longer should
intercept HOT_RESET as previous v3 had reviewed
for CONFIG_REGION_INDEX a newtype feels a bit overkill for now, it would adding
conversion where index is used as a BAR number,
i would keep it for now.
>> +impl<T: Operations> Device<T> {
>> + /// Allocate a VFIO PCI device for subsequent registration.
>> + pub fn new(pdev: &pci::Device<device::Core<'_>>) -> Result<ARef<Self>> {
>> + let size = Kmalloc::aligned_layout(Layout::new::<Self>()).size();
>> +
>> + // SAFETY: The bound PCI device and static ops are valid. The
>> allocation
>> + // includes the full Rust wrapper with kmalloc-compatible size and
>> alignment.
>> + let raw = from_err_ptr(unsafe {
>> + bindings::_vfio_alloc_device(size, pdev.as_ref().as_raw(),
>> &Self::OPS)
>> + })?;
>
> This doesn't make sure alignment is correct.
>
The current wrapper's alignment is within a page; I've made that a compile-time
assertion and documented how both kvzalloc() paths satisfy it.
>> + let this = NonNull::new(raw.cast::<Self>()).ok_or(ENOMEM)?;
>> +
>> + // SAFETY: `vfio_pci_core_init_dev()` initialized the C device in
>> this new allocation,
>> + // which nothing else can access yet. `vfio_pci_core_device` begins
>> with its
>> + // `vfio_device`, as asserted above.
>> + // INVARIANT: The layout and the initialized `raw` are as just
>> described.
>> + unsafe { Self::init(this.as_ptr()) };
>> +
>> + // SAFETY: No registration or callbacks can observe this allocation
>> yet.
>> + unsafe { (*this.as_ref().as_raw()).pci_ops = &Self::PCI_OPS };
>> +
>> + // SAFETY: `this` owns the initial VFIO device reference.
>> + Ok(unsafe { ARef::from_raw(this) })
>> + }
>> +}
>>
>> [snip]
>>
>> +
>> +/// Build the `vfio_device_ops` vtable for a variant driver `T`.
>> +///
>> +/// The open callback and the implemented I/O callbacks dispatch to `T`;
>> unimplemented I/O
>> +/// callbacks are not installed. Other installed callbacks use VFIO core
>> functions or wrappers.
>> +macro_rules! build_ops {
>> + ($T:ty) => {
>> + bindings::vfio_device_ops {
>> + #[allow(clippy::disallowed_methods)]
>> + name: <$T>::NAME.as_ptr().cast_mut().cast(),
>> + init: Some(bindings::vfio_pci_core_init_dev),
>> + release: Some(bindings::vfio_pci_core_release_dev),
>> + open_device: Some(open_device_cb::<$T>),
>> + close_device: Some(close_device_cb::<$T>),
>> + ioctl: if <$T>::HAS_IOCTL {
>> + Some(ioctl_cb::<$T>)
>> + } else {
>> + None
>> + },
>
> None here (and below) means returning EINVAL instead of forwarding to core
> callbacks. Is this what's whated? Most existing vfio pci variant drivers
> forward
> un-implemented callbacks.
>
> Perhaps it's worth changing the C side to switch the meaning, but regardless
> we
> should consider what's actually the desired behaviour when people use Rust
> abstraction's trait "provided methods".
>
this is intended and follows the C API, as Danilo wrote in v3