NVIDIA GPU driver infrastructure
 help / color / mirror / Atom feed
* [PATCH v5 0/4] Rust VFIO PCI support
@ 2026-12-04  4:17 Simon Song
  2026-12-04  4:17 ` [PATCH v5 1/4] rust: uaccess: support bounded forward buffer traversal Simon Song
                   ` (3 more replies)
  0 siblings, 4 replies; 7+ messages in thread
From: Simon Song @ 2026-12-04  4:17 UTC (permalink / raw)
  To: dakr, acourbot, kvm, rust-for-linux, nova-gpu, linux-pci
  Cc: Simon Song, 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, Liam R. Howlett,
	linux-mm, Lorenzo Stoakes

This is v5 of the Rust VFIO PCI abstractions. v4 was posted as "Rust
VFIO PCI support and NVIDIA vGPU driver" [1].

Up to v4 this series also carried the nova-core SR-IOV PF interface and
the NVIDIA VFIO variant driver. Those two patches depend on Alok's vGPU
manager series [2], so the series did not apply to a public tree and
Sashiko could not review it. They will now be posted as a separate
series on top of this one. The four patches here have no external
dependencies and are based on drm-rust-next.

Patch 1 adds UserSlice helpers for bounded forward traversal. Patch 2
adds the VFIO device handling common to all buses. Patch 3 adds two
VmaRef accessors for patch 4, the VFIO PCI abstractions.

Runtime PM is still not part of this series. It will follow once the
generic Rust runtime PM support [3] and the PCI bus handling for it are
available. Until then, vfio::pci::Registration keeps the device runtime
active while it is registered.

Changes since v4 [1]:
- Move the nova-core and nova-vgpu patches (v4 patches 4 and 5) to a
  separate series (Gary, Danilo).
- New patch 1: add UserSlice helpers for bounded forward traversal
  (Danilo).
- Patch 2 (v4 patch 1):
  - Remove UserBuf. The callbacks use UserSlice (Gary, Danilo).
  - Make InfoCap a transparent wrapper of struct vfio_info_cap (Gary).
  - Use 'res for the resource lifetime and 'reg for the registration
    lifetime (Gary, Danilo).
  - Do not name the hidden DeviceBase in the public documentation
    (Gary).
  - Use one module-level dead_code expectation (Gary).
  - Add #[inline] to the small DeviceBase accessors.
- Patch 3 (v4 patch 2): add Alice's Acked-by.
- Patch 4 (v4 patch 3):
  - Let Registration::new() allocate the VFIO device, and remove the
    public allocator (Gary, Danilo).
  - Give the Open context of open_device() its own lifetime, so that
    the open data cannot retain it (Gary).
  - Pass a UserSlice to read() and write() (Gary, Danilo).
  - Wrap struct vfio_region_info in RegionInfo (Gary).
  - Remove the unused DEVICE_PCI_HOT_RESET (Gary).
  - Assert that the device alignment fits the vmalloc fallback of
    kvzalloc() (Gary).
  - Check the bound driver at runtime in Registration::new() instead
    of the const assertions on the driver type, and add
    pci::Device::driver_has_managed_dma() and
    pci::Device::driver_has_sriov_configure() for that (Gary, Danilo).
  - Add #[inline] to the small Position, Mapping and Device helpers.

v4 patches 1, 2 and 3 are now patches 2, 3 and 4.

[1] https://lore.kernel.org/r/20261127224928.1511382-1-xinmengs@nvidia.com
[2] https://lore.kernel.org/all/cover.1796191007.git.alkumar@nvidia.com/
[3] https://lore.kernel.org/r/20261124113555.2480381-1-beata.michalska@arm.com

Danilo Krummrich (1):
  rust: vfio: add PCI variant driver abstractions

Simon Song (2):
  rust: uaccess: support bounded forward buffer traversal
  rust: mm: add VmaRef::size() and VmaRef::pgoff()

Zhi Wang (1):
  rust: vfio: add common VFIO device handling

 rust/bindings/bindings_helper.h |   3 +
 rust/kernel/lib.rs              |   2 +
 rust/kernel/mm/virt.rs          |  14 +
 rust/kernel/pci.rs              |  39 ++
 rust/kernel/uaccess.rs          |  44 +-
 rust/kernel/vfio.rs             | 366 +++++++++++++
 rust/kernel/vfio/pci.rs         | 880 ++++++++++++++++++++++++++++++++
 7 files changed, 1346 insertions(+), 2 deletions(-)
 create mode 100644 rust/kernel/vfio.rs
 create mode 100644 rust/kernel/vfio/pci.rs


base-commit: d9da44362d77bcbf1f5bfd2ba1c514e776fdb07c
-- 
2.43.7


^ permalink raw reply	[flat|nested] 7+ messages in thread

* [PATCH v5 1/4] rust: uaccess: support bounded forward buffer traversal
  2026-12-04  4:17 [PATCH v5 0/4] Rust VFIO PCI support Simon Song
@ 2026-12-04  4:17 ` Simon Song
  2026-12-04  4:17 ` [PATCH v5 2/4] rust: vfio: add common VFIO device handling Simon Song
                   ` (2 subsequent siblings)
  3 siblings, 0 replies; 7+ messages in thread
From: Simon Song @ 2026-12-04  4:17 UTC (permalink / raw)
  To: dakr, acourbot, kvm, rust-for-linux, nova-gpu, linux-pci
  Cc: Simon Song, 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, Liam R. Howlett,
	linux-mm, Lorenzo Stoakes

VFIO PCI drivers need to bound user-buffer transfers delegated to C
and traverse device-specific fields without fetching preceding bytes.
UserSlice should cover that use without a separate VFIO buffer type.

Suggested-by: Danilo Krummrich <dakr@kernel.org>
Signed-off-by: Simon Song <xinmengs@nvidia.com>
---
 rust/kernel/uaccess.rs | 44 ++++++++++++++++++++++++++++++++++++++++--
 1 file changed, 42 insertions(+), 2 deletions(-)

diff --git a/rust/kernel/uaccess.rs b/rust/kernel/uaccess.rs
index ab6b34a0fc97..d002769f21e9 100644
--- a/rust/kernel/uaccess.rs
+++ b/rust/kernel/uaccess.rs
@@ -15,7 +15,13 @@
     ptr::KnownSize,
     transmute::{AsBytes, FromBytes},
 };
-use core::mem::{size_of, MaybeUninit};
+use core::{
+    cmp,
+    mem::{
+        size_of,
+        MaybeUninit, //
+    }, //
+};
 
 /// A pointer into userspace.
 ///
@@ -226,13 +232,25 @@ pub struct UserSliceReader {
 }
 
 impl UserSliceReader {
+    /// Returns the current userspace pointer.
+    #[inline]
+    pub(crate) fn as_ptr(&self) -> UserPtr {
+        self.ptr
+    }
+
+    /// Limits the remaining buffer to at most `length` bytes, keeping its current address.
+    #[inline]
+    pub fn truncate(&mut self, length: usize) {
+        self.length = cmp::min(self.length, length);
+    }
+
     /// Skip the provided number of bytes.
     ///
     /// Returns an error if skipping more than the length of the buffer.
     pub fn skip(&mut self, num_skip: usize) -> Result {
         // Update `self.length` first since that's the fallible part of this operation.
         self.length = self.length.checked_sub(num_skip).ok_or(EFAULT)?;
-        self.ptr = self.ptr.wrapping_byte_add(num_skip);
+        self.ptr = self.as_ptr().wrapping_byte_add(num_skip);
         Ok(())
     }
 
@@ -458,6 +476,28 @@ pub struct UserSliceWriter {
 }
 
 impl UserSliceWriter {
+    /// Returns the current userspace pointer.
+    #[inline]
+    pub(crate) fn as_ptr(&self) -> UserPtr {
+        self.ptr
+    }
+
+    /// Limits the remaining buffer to at most `length` bytes, keeping its current address.
+    #[inline]
+    pub fn truncate(&mut self, length: usize) {
+        self.length = cmp::min(self.length, length);
+    }
+
+    /// Skips the provided number of bytes without writing to them.
+    ///
+    /// Returns an error if skipping more than the length of the buffer.
+    #[inline]
+    pub fn skip(&mut self, num_skip: usize) -> Result {
+        self.length = self.length.checked_sub(num_skip).ok_or(EFAULT)?;
+        self.ptr = self.as_ptr().wrapping_byte_add(num_skip);
+        Ok(())
+    }
+
     /// Returns the amount of space remaining in this buffer.
     ///
     /// Note that even writing less than this number of bytes may fail.
-- 
2.43.7


^ permalink raw reply related	[flat|nested] 7+ messages in thread

* [PATCH v5 2/4] rust: vfio: add common VFIO device handling
  2026-12-04  4:17 [PATCH v5 0/4] Rust VFIO PCI support Simon Song
  2026-12-04  4:17 ` [PATCH v5 1/4] rust: uaccess: support bounded forward buffer traversal Simon Song
@ 2026-12-04  4:17 ` Simon Song
  2026-12-05  4:19   ` sashiko-bot
  2026-12-04  4:17 ` [PATCH v5 3/4] rust: mm: add VmaRef::size() and VmaRef::pgoff() Simon Song
  2026-12-04  4:17 ` [PATCH v5 4/4] rust: vfio: add PCI variant driver abstractions Simon Song
  3 siblings, 1 reply; 7+ messages in thread
From: Simon Song @ 2026-12-04  4:17 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>

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.

Signed-off-by: Zhi Wang <zhiw@nvidia.com>
Signed-off-by: Simon Song <xinmengs@nvidia.com>
---
 rust/bindings/bindings_helper.h |   2 +
 rust/kernel/lib.rs              |   2 +
 rust/kernel/vfio.rs             | 357 ++++++++++++++++++++++++++++++++
 3 files changed, 361 insertions(+)
 create mode 100644 rust/kernel/vfio.rs

diff --git a/rust/bindings/bindings_helper.h b/rust/bindings/bindings_helper.h
index 3791af0aadc7..a5781bc1ea85 100644
--- a/rust/bindings/bindings_helper.h
+++ b/rust/bindings/bindings_helper.h
@@ -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;
diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs
index 1ab41129d557..061e22fb09cf 100644
--- a/rust/kernel/lib.rs
+++ b/rust/kernel/lib.rs
@@ -147,6 +147,8 @@
 pub mod uaccess;
 #[cfg(CONFIG_USB = "y")]
 pub mod usb;
+#[cfg(CONFIG_VFIO = "y")]
+pub mod vfio;
 pub mod workqueue;
 pub mod xarray;
 
diff --git a/rust/kernel/vfio.rs b/rust/kernel/vfio.rs
new file mode 100644
index 000000000000..30a593634a72
--- /dev/null
+++ b/rust/kernel/vfio.rs
@@ -0,0 +1,357 @@
+// SPDX-License-Identifier: GPL-2.0
+
+//! Virtual Function I/O (VFIO) devices and callback data.
+//!
+//! A [`Device`] wraps a C `struct vfio_device` together with the data its driver's callbacks
+//! use.
+//!
+//! C header: [`include/linux/vfio.h`](srctree/include/linux/vfio.h)
+
+// The PCI abstraction is currently the only user of these helpers.
+#![expect(dead_code)]
+
+use crate::{
+    bindings,
+    prelude::*,
+    sync::aref::AlwaysRefCounted,
+    types::{
+        ForeignOwnable,
+        NotThreadSafe,
+        Opaque, //
+    }, //
+};
+use core::{
+    cell::UnsafeCell,
+    marker::PhantomData,
+    ptr::NonNull, //
+};
+
+/// Reset the VFIO device.
+pub const DEVICE_RESET: u32 = bindings::VFIO_DEVICE_RESET;
+
+/// The context in which a VFIO device reference is valid.
+///
+/// Callback views can only be borrowed from the corresponding VFIO trampoline.
+/// They cannot be refcounted or shared across threads.
+pub trait DeviceContext: private::Sealed {}
+
+/// A callback context in which VFIO keeps the device open.
+///
+/// Registration data and open data are available throughout such a callback.
+pub trait IoContext: DeviceContext {}
+
+/// An ordinary device reference, without callback-specific operations.
+pub struct Normal;
+
+/// The device is undergoing its exclusive first-open callback.
+pub struct Open;
+
+/// The device is borrowed for a VFIO ioctl callback on the current thread.
+pub struct Ioctl;
+
+/// The device is borrowed for a VFIO read callback on the current thread.
+pub struct Read;
+
+/// The device is borrowed for a VFIO write callback on the current thread.
+pub struct Write;
+
+/// The device is borrowed for a VFIO mmap callback on the current thread.
+pub struct Mmap;
+
+/// The device is borrowed for a VFIO region-info callback on the current thread.
+pub struct GetRegionInfo;
+
+mod private {
+    pub trait Sealed {}
+
+    impl Sealed for super::Normal {}
+    impl Sealed for super::Open {}
+    impl Sealed for super::Write {}
+    impl Sealed for super::Mmap {}
+    impl Sealed for super::Ioctl {}
+    impl Sealed for super::Read {}
+    impl Sealed for super::GetRegionInfo {}
+}
+
+impl DeviceContext for Normal {}
+impl DeviceContext for Open {}
+impl DeviceContext for Write {}
+impl DeviceContext for Mmap {}
+impl DeviceContext for Ioctl {}
+impl DeviceContext for Read {}
+impl DeviceContext for GetRegionInfo {}
+
+impl IoContext for Write {}
+impl IoContext for Mmap {}
+impl IoContext for Ioctl {}
+impl IoContext for Read {}
+impl IoContext for GetRegionInfo {}
+
+/// The data the driver of a [`Device`] shares with its callbacks.
+///
+/// Bus-specific operations traits extend this trait.
+pub trait Operations: Sized + Send + Sync + 'static {
+    /// Data owned by the registration and passed to VFIO callbacks.
+    ///
+    /// It can borrow resources of the driver's binding for `'res`. Per-device state lives here.
+    type RegistrationData<'res>: Send + Sync + 'res;
+
+    /// Data shared by callbacks from the first successful open until the last close.
+    ///
+    /// It can borrow the registration data for `'reg`.
+    type OpenData<'reg, 'res: 'reg>: Send + Sync + 'reg;
+}
+
+/// Callback data stored after the C device structure.
+///
+/// The registration data and the open data of `T` are both written with the placeholder
+/// lifetime `'static`, because the device has no lifetime to name.
+///
+/// # Invariants
+///
+/// `reg_data` is `None` until a registration publishes its data, and is not changed again. The
+/// data is pinned and remains valid while the device is registered. After unregistration or a
+/// failed registration attempt, the pointer may dangle; its pointee must never again be
+/// accessed through this device.
+/// `open_data` is `None` outside a successful first open, otherwise it owns a pinned allocation
+/// until the last close. The bus-specific layer drains callbacks before either is released.
+struct CallbackData<T: Operations> {
+    reg_data: UnsafeCell<Option<NonNull<T::RegistrationData<'static>>>>,
+    open_data: UnsafeCell<Option<NonNull<T::OpenData<'static, 'static>>>>,
+}
+
+/// A C VFIO device structure `Raw`, followed by the callback data of the driver `T`.
+///
+/// `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`].
+///
+/// # Invariants
+///
+/// - `Raw` is a C structure that begins with its `struct vfio_device`.
+/// - The data stored is only valid as described for `CallbackData`.
+/// - `raw` is initialized and remains alive while borrowed. The reference count of its embedded
+///   `vfio_device` owns the allocation.
+/// - For [`Open`] and [`IoContext`] references, registration data is published and remains
+///   valid for the reference's lifetime.
+#[doc(hidden)]
+#[repr(C)]
+pub struct DeviceBase<Raw, T: Operations, Ctx: DeviceContext = Normal> {
+    raw: Opaque<Raw>,
+    data: CallbackData<T>,
+    _context: PhantomData<(T, Ctx, NotThreadSafe)>,
+}
+
+/// A VFIO device, wrapping `struct vfio_device`.
+pub type Device<T, Ctx = Normal> = DeviceBase<bindings::vfio_device, T, Ctx>;
+
+impl<Raw, T: Operations, Ctx: DeviceContext> DeviceBase<Raw, T, Ctx> {
+    /// Initializes the Rust fields of a newly allocated device.
+    ///
+    /// # Safety
+    ///
+    /// `this` must point to an allocation with the size and alignment of `Self`, whose `raw`
+    /// has been initialized. `Raw` must be a C structure that begins with its
+    /// `struct vfio_device`. Nothing else may access the allocation during this call.
+    unsafe fn init(this: *mut Self) {
+        // SAFETY: The caller provides exclusive access to a suitable allocation.
+        // INVARIANT: No data is published, and no open data exists.
+        unsafe {
+            (&raw mut (*this).data).write(CallbackData {
+                reg_data: UnsafeCell::new(None),
+                open_data: UnsafeCell::new(None),
+            })
+        };
+        // SAFETY: By the same reasoning above, `_context` can be written.
+        unsafe { (&raw mut (*this)._context).write(PhantomData) };
+    }
+
+    /// Recovers `&Self` from the `vfio_device` VFIO passes to a callback.
+    ///
+    /// # Safety
+    ///
+    /// `vdev` must point to the `vfio_device` at the beginning of a `Self` that remains alive
+    /// for `'a`. The caller must provide the guarantees of `Ctx` throughout the borrow.
+    #[inline]
+    unsafe fn from_raw_vfio<'a>(vdev: *mut bindings::vfio_device) -> &'a Self {
+        // SAFETY: By the type invariants, `Raw` begins with its `vfio_device`, and `raw` is the
+        // first field of `Self`. The caller guarantees validity.
+        // INVARIANT: The caller provides the guarantees of `Ctx`.
+        unsafe { &*vdev.cast() }
+    }
+
+    #[inline]
+    fn as_raw(&self) -> *mut Raw {
+        self.raw.get()
+    }
+
+    #[inline]
+    fn as_raw_vfio(&self) -> *mut bindings::vfio_device {
+        // By the type invariants, `Raw` begins with its `vfio_device`.
+        self.as_raw().cast()
+    }
+}
+
+impl<Raw, T: Operations> DeviceBase<Raw, T> {
+    /// Publishes the registration data passed to callbacks.
+    ///
+    /// # Safety
+    ///
+    /// The device must not have been registered, and this must be the only call for it.
+    /// `data` must point to pinned data that remains valid until the device has been
+    /// unregistered or, if registration fails, is not accessed through this device.
+    unsafe fn publish_registration_data<'res>(&self, data: NonNull<T::RegistrationData<'res>>) {
+        // SAFETY: The device has not been registered, so no callback can read the slot, and
+        // this is the only call that writes it.
+        // INVARIANT: The slot is written once; the caller keeps `data` valid.
+        unsafe { *self.data.reg_data.get() = Some(data.cast()) };
+    }
+
+    /// Destroys the open data.
+    ///
+    /// # Safety
+    ///
+    /// Call once after a successful [`DeviceBase::open`], with all I/O callbacks drained and
+    /// the next first open excluded. Registration data and the resources the open data borrows
+    /// must remain alive.
+    unsafe fn close(&self) {
+        // SAFETY: The last close exclusively takes the allocation published by `open()`.
+        let raw = unsafe { &mut *self.data.open_data.get() }
+            .take()
+            .expect("VFIO OpenData is expected to be populated.");
+        // SAFETY: `raw` came from `into_foreign()` in `open()` and is not used again. The
+        // allocation is destroyed without moving it.
+        drop(unsafe {
+            <Pin<KBox<T::OpenData<'static, 'static>>>>::from_foreign(raw.as_ptr().cast())
+        });
+    }
+}
+
+impl<Raw, T: Operations> DeviceBase<Raw, T, Open> {
+    /// Creates the open data from the registration data.
+    ///
+    /// The [`Open`] context guarantees an exclusive first open of a registered device, whose
+    /// registration data remains valid until the last close.
+    ///
+    /// # Safety
+    ///
+    /// - No open data may exist.
+    /// - The caller chooses `'a` and `'res`; this function cannot tie either to the time the
+    ///   data is valid. `init` must therefore use the registration data parametrically, as a
+    ///   function generic over its lifetimes does: nothing borrowed from it may escape, other
+    ///   than into the returned open data.
+    /// - `init` must not capture references that are only valid for the callback and store
+    ///   them in the open data, which outlives the callback.
+    /// - The open data must be destroyed with [`DeviceBase::close`] at the last close.
+    unsafe fn open<'a, 'res: 'a, I>(
+        &'a self,
+        init: impl FnOnce(&'a T::RegistrationData<'res>) -> I,
+    ) -> Result
+    where
+        I: PinInit<T::OpenData<'a, 'res>, Error>,
+    {
+        // SAFETY: By the type invariants, an `Open` reference only exists for a registered
+        // device, which has published registration data that nothing changes anymore. The
+        // data remains valid until the last close.
+        let reg_data = unsafe { *self.data.reg_data.get() }
+            .expect("VFIO registration data is expected to be published.");
+        // SAFETY: By the same reasoning above, the registration data is valid; only its
+        // lifetime is named here.
+        let reg_data = unsafe { reg_data.cast::<T::RegistrationData<'res>>().as_ref() };
+
+        // Allocate before calling the driver so allocation failure cannot follow open.
+        let data = KBox::pin_init(pin_init::pin_init_scope(|| Ok(init(reg_data))), GFP_KERNEL)?;
+        // The stored type only differs in lifetimes, which do not affect the layout.
+        let raw = data.into_foreign().cast::<T::OpenData<'static, 'static>>();
+        // SAFETY: The first open is exclusive, and no I/O callback runs before it returns.
+        // INVARIANT: The allocation is pinned and owned by the slot until `close()`.
+        unsafe { *self.data.open_data.get() = NonNull::new(raw) };
+        Ok(())
+    }
+}
+
+impl<Raw, T: Operations, Ctx: IoContext> DeviceBase<Raw, T, Ctx> {
+    /// Returns the registration data and the open data, for an I/O callback.
+    ///
+    /// # Safety
+    ///
+    /// The data is named with the placeholder lifetime `'static`, which is not the time the
+    /// data is valid. The caller must use both parametrically, as a function generic over
+    /// their lifetimes does: nothing borrowed from them may outlive the callback, and nothing
+    /// borrowed for the callback may be stored in them.
+    unsafe fn callback_data(
+        &self,
+    ) -> (
+        &T::RegistrationData<'static>,
+        Pin<&T::OpenData<'static, 'static>>,
+    ) {
+        // SAFETY: By the type invariants, an `IoContext` reference only exists during an I/O
+        // callback on an open, registered device. VFIO excludes the last close and
+        // unregistration for its duration, so by the type invariants of `CallbackData` both
+        // slots hold valid data that nothing changes, and the open data is pinned.
+        let reg_data = unsafe { *self.data.reg_data.get() }
+            .expect("VFIO registration data is expected to be published.");
+        // SAFETY: By the same reasoning above, nothing changes the open data slot.
+        let open_data = unsafe { *self.data.open_data.get() }
+            .expect("VFIO OpenData is expected to be populated.");
+        // SAFETY: By the same reasoning above, the registration data is valid for this callback.
+        let reg_data = unsafe { reg_data.as_ref() };
+        // SAFETY: By the same reasoning above, the open data is valid for this callback.
+        let open_data = unsafe { open_data.as_ref() };
+        // SAFETY: By the same reasoning above, the open data is pinned until the last close.
+        (reg_data, unsafe { Pin::new_unchecked(open_data) })
+    }
+}
+
+// SAFETY: VFIO uses the embedded class device's refcount to own the full allocation.
+unsafe impl<Raw, T: Operations> AlwaysRefCounted for DeviceBase<Raw, T> {
+    #[inline]
+    fn inc_ref(&self) {
+        // SAFETY: A shared reference keeps the initialized VFIO device alive.
+        unsafe { bindings::get_device(&raw mut (*self.as_raw_vfio()).device) };
+    }
+
+    #[inline]
+    unsafe fn dec_ref(obj: NonNull<Self>) {
+        // By the type invariants, `Raw` begins with its `vfio_device`, and `raw` is the first
+        // field of `Self`.
+        let vdev = obj.as_ptr().cast::<bindings::vfio_device>();
+        // SAFETY: The caller owns the VFIO reference being released.
+        unsafe { bindings::put_device(&raw mut (*vdev).device) };
+    }
+}
+
+// SAFETY: VFIO serializes open/close transitions, and callback data is `Send + Sync`.
+unsafe impl<Raw, T: Operations> Send for DeviceBase<Raw, T> {}
+
+// SAFETY: Shared access only changes the embedded class device's reference count. I/O callbacks
+// share `Sync` data; VFIO excludes them from mutations of `open_data` during first open and
+// last close, and registration data follows the registration lifetime. Mutable C state is
+// managed by the VFIO core.
+unsafe impl<Raw, T: Operations> Sync for DeviceBase<Raw, T> {}
+
+/// Capability buffer supplied by VFIO for a region-info callback.
+#[repr(transparent)]
+pub struct InfoCap(Opaque<bindings::vfio_info_cap>);
+
+impl InfoCap {
+    /// Creates a reference to an [`InfoCap`] from a raw pointer.
+    ///
+    /// # Safety
+    ///
+    /// `ptr` must point to a `struct vfio_info_cap` that satisfies the VFIO core's invariants,
+    /// remains valid for `'a` and is not accessed in any other way for the duration of `'a`.
+    #[inline]
+    pub(crate) unsafe fn from_raw<'a>(ptr: *mut bindings::vfio_info_cap) -> &'a mut Self {
+        // SAFETY: `Self` is a transparent wrapper around `struct vfio_info_cap`. The caller
+        // guarantees that `ptr` is valid and exclusively accessible for `'a`.
+        unsafe { &mut *ptr.cast() }
+    }
+
+    /// Returns a raw pointer to the `struct vfio_info_cap`.
+    #[inline]
+    pub(crate) fn as_raw(&self) -> *mut bindings::vfio_info_cap {
+        self.0.get()
+    }
+}
-- 
2.43.7


^ permalink raw reply related	[flat|nested] 7+ messages in thread

* [PATCH v5 3/4] rust: mm: add VmaRef::size() and VmaRef::pgoff()
  2026-12-04  4:17 [PATCH v5 0/4] Rust VFIO PCI support Simon Song
  2026-12-04  4:17 ` [PATCH v5 1/4] rust: uaccess: support bounded forward buffer traversal Simon Song
  2026-12-04  4:17 ` [PATCH v5 2/4] rust: vfio: add common VFIO device handling Simon Song
@ 2026-12-04  4:17 ` Simon Song
  2026-12-04  4:17 ` [PATCH v5 4/4] rust: vfio: add PCI variant driver abstractions Simon Song
  3 siblings, 0 replies; 7+ messages in thread
From: Simon Song @ 2026-12-04  4:17 UTC (permalink / raw)
  To: dakr, acourbot, kvm, rust-for-linux, nova-gpu, linux-pci
  Cc: Simon Song, 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, Liam R. Howlett,
	linux-mm, Lorenzo Stoakes

The forthcoming VFIO PCI abstraction needs VMA page offsets and byte
lengths for mapping bounds checks. Keeping these queries on VmaRef
confines unsafe field access to the MM abstraction and avoids repeated
length calculations in callers.

Suggested-by: Danilo Krummrich <dakr@kernel.org>
Acked-by: Alice Ryhl <aliceryhl@google.com>
Signed-off-by: Simon Song <xinmengs@nvidia.com>
---
 rust/kernel/mm/virt.rs | 14 ++++++++++++++
 1 file changed, 14 insertions(+)

diff --git a/rust/kernel/mm/virt.rs b/rust/kernel/mm/virt.rs
index 63eb730b0b05..b0210869b757 100644
--- a/rust/kernel/mm/virt.rs
+++ b/rust/kernel/mm/virt.rs
@@ -92,6 +92,20 @@ pub fn end(&self) -> usize {
         unsafe { (*self.as_ptr()).__bindgen_anon_1.__bindgen_anon_1.vm_end }
     }
 
+    /// Returns the size of the virtual memory area in bytes.
+    #[inline]
+    pub fn size(&self) -> usize {
+        self.end() - self.start()
+    }
+
+    /// Returns the VMA's page offset (`vm_pgoff`).
+    #[inline]
+    pub fn pgoff(&self) -> usize {
+        // SAFETY: By `VmaRef`'s invariants, the VMA is valid and the mmap/VMA read lock prevents
+        // concurrent modification.
+        unsafe { (*self.as_ptr()).vm_pgoff }
+    }
+
     /// Zap pages in the given page range.
     ///
     /// This clears page table mappings for the range at the leaf level, leaving all other page
-- 
2.43.7


^ permalink raw reply related	[flat|nested] 7+ messages in thread

* [PATCH v5 4/4] rust: vfio: add PCI variant driver abstractions
  2026-12-04  4:17 [PATCH v5 0/4] Rust VFIO PCI support Simon Song
                   ` (2 preceding siblings ...)
  2026-12-04  4:17 ` [PATCH v5 3/4] rust: mm: add VmaRef::size() and VmaRef::pgoff() Simon Song
@ 2026-12-04  4:17 ` Simon Song
  2026-12-05  4:19   ` sashiko-bot
  3 siblings, 1 reply; 7+ messages in thread
From: Simon Song @ 2026-12-04  4:17 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>

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. Add pci::Device::driver_has_managed_dma() and
pci::Device::driver_has_sriov_configure(), so that Registration::new()
can check the driver bound to the device.

Signed-off-by: Danilo Krummrich <dakr@kernel.org>
Signed-off-by: Zhi Wang <zhiw@nvidia.com>
Signed-off-by: Simon Song <xinmengs@nvidia.com>
---
 rust/bindings/bindings_helper.h |   1 +
 rust/kernel/pci.rs              |  39 ++
 rust/kernel/vfio.rs             |  17 +-
 rust/kernel/vfio/pci.rs         | 880 ++++++++++++++++++++++++++++++++
 4 files changed, 933 insertions(+), 4 deletions(-)
 create mode 100644 rust/kernel/vfio/pci.rs

diff --git a/rust/bindings/bindings_helper.h b/rust/bindings/bindings_helper.h
index a5781bc1ea85..06bc8508064d 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>
diff --git a/rust/kernel/pci.rs b/rust/kernel/pci.rs
index 078da469d98a..ae701027b101 100644
--- a/rust/kernel/pci.rs
+++ b/rust/kernel/pci.rs
@@ -459,6 +459,19 @@ pub enum ErsResult {
 }
 
 impl ErsResult {
+    #[cfg_attr(not(CONFIG_VFIO_PCI_CORE = "y"), expect(dead_code))]
+    #[inline]
+    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,
@@ -813,6 +826,32 @@ pub fn domain_nr(&self) -> u32 {
         // handle.
         domain_nr as u32
     }
+
+    /// Returns whether the bound driver manages DMA ownership.
+    #[inline]
+    pub fn driver_has_managed_dma(&self) -> bool {
+        // SAFETY: The bound context keeps `dev.driver` valid and unchanged.
+        let driver = unsafe { (*self.as_ref().as_raw()).driver };
+
+        // SAFETY: The driver of a PCI device is embedded in a `struct pci_driver`.
+        let driver = unsafe { crate::container_of!(driver, bindings::pci_driver, driver) };
+
+        // SAFETY: `driver` is valid and `driver_managed_dma` is immutable while registered.
+        unsafe { (*driver).driver_managed_dma }
+    }
+
+    /// Returns whether the bound driver provides an SR-IOV configuration callback.
+    #[inline]
+    pub fn driver_has_sriov_configure(&self) -> bool {
+        // SAFETY: The bound context keeps `dev.driver` valid and unchanged.
+        let driver = unsafe { (*self.as_ref().as_raw()).driver };
+
+        // SAFETY: The driver of a PCI device is embedded in a `struct pci_driver`.
+        let driver = unsafe { crate::container_of!(driver, bindings::pci_driver, driver) };
+
+        // SAFETY: `driver` is valid and `sriov_configure` is immutable while registered.
+        unsafe { (*driver).sriov_configure }.is_some()
+    }
 }
 
 impl<'a> Device<device::Core<'a>> {
diff --git a/rust/kernel/vfio.rs b/rust/kernel/vfio.rs
index 30a593634a72..2aad900e6d97 100644
--- a/rust/kernel/vfio.rs
+++ b/rust/kernel/vfio.rs
@@ -3,12 +3,18 @@
 //! Virtual Function I/O (VFIO) devices and callback data.
 //!
 //! A [`Device`] wraps a C `struct vfio_device` together with the data its driver's callbacks
-//! use.
+//! use. Bus-specific devices, such as
+#![cfg_attr(
+    CONFIG_VFIO_PCI_CORE = "y",
+    doc = "[`vfio::pci::Device`](kernel::vfio::pci::Device),"
+)]
+#![cfg_attr(not(CONFIG_VFIO_PCI_CORE = "y"), doc = "`vfio::pci::Device`,")]
+//! wrap their bus's C device structure in the same way.
 //!
 //! C header: [`include/linux/vfio.h`](srctree/include/linux/vfio.h)
 
 // The PCI abstraction is currently the only user of these helpers.
-#![expect(dead_code)]
+#![cfg_attr(not(CONFIG_VFIO_PCI_CORE = "y"), expect(dead_code))]
 
 use crate::{
     bindings,
@@ -26,6 +32,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;
 
@@ -89,7 +98,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.
     ///
@@ -125,7 +134,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
 ///
diff --git a/rust/kernel/vfio/pci.rs b/rust/kernel/vfio/pci.rs
new file mode 100644
index 000000000000..728baf0c1ce9
--- /dev/null
+++ b/rust/kernel/vfio/pci.rs
@@ -0,0 +1,880 @@
+// 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 allocates and 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, //
+};
+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,
+        Opaque, //
+    },
+    uaccess::{
+        UserPtr,
+        UserSlice,
+        UserSliceReader,
+        UserSliceWriter, //
+    }, //
+};
+use core::{
+    alloc::Layout,
+    ptr::NonNull, //
+};
+
+/// Index of the PCI configuration-space region.
+pub const CONFIG_REGION_INDEX: u32 = bindings::VFIO_PCI_CONFIG_REGION_INDEX;
+
+/// Information about a region of a VFIO PCI device, for a region-info callback.
+///
+/// # Invariants
+///
+/// The wrapped `struct vfio_region_info` is initialized.
+#[repr(transparent)]
+pub struct RegionInfo(Opaque<bindings::vfio_region_info>);
+
+impl RegionInfo {
+    /// Creates a reference to a [`RegionInfo`] from a raw pointer.
+    ///
+    /// # Safety
+    ///
+    /// `ptr` must point to an initialized `struct vfio_region_info` that remains valid for
+    /// `'a` and is not accessed in any other way for the duration of `'a`.
+    #[inline]
+    unsafe fn from_raw<'a>(ptr: *mut bindings::vfio_region_info) -> &'a mut Self {
+        // SAFETY: `Self` is a transparent wrapper around `struct vfio_region_info`. The caller
+        // guarantees that `ptr` is valid and exclusively accessible for `'a`.
+        // INVARIANT: The caller guarantees that the structure is initialized.
+        unsafe { &mut *ptr.cast() }
+    }
+
+    #[inline]
+    fn as_raw(&self) -> *mut bindings::vfio_region_info {
+        self.0.get()
+    }
+
+    /// Returns the index of the region.
+    #[inline]
+    pub fn index(&self) -> u32 {
+        // SAFETY: By the type invariants, the structure is initialized, and `self` is the only
+        // way to access it.
+        unsafe { (*self.as_raw()).index }
+    }
+
+    /// Returns the size of the region in bytes.
+    #[inline]
+    pub fn size(&self) -> u64 {
+        // SAFETY: By the type invariants, the structure is initialized, and `self` is the only
+        // way to access it.
+        unsafe { (*self.as_raw()).size }
+    }
+
+    /// Sets the size of the region in bytes.
+    #[inline]
+    pub fn set_size(&mut self, size: u64) {
+        // SAFETY: By the type invariants, the structure is initialized, and `self` is the only
+        // way to access it.
+        unsafe { (*self.as_raw()).size = size };
+    }
+}
+
+/// The trait for VFIO PCI variant driver implementations.
+///
+/// Unimplemented I/O callbacks leave their corresponding VFIO hooks unset. To get the
+/// behavior of the PCI core, implement the callback and call the corresponding core helper of
+/// [`Device`].
+///
+/// # Lifetime of the callback data
+///
+/// [`Registration`] owns the [`RegistrationData`](super::Operations::RegistrationData), which
+/// borrows from the PCI binding scope, and each callback borrows it. Callbacks are generic over
+/// the resource lifetime encoded in the registration data, so they cannot store callback-local
+/// references in it.
+#[vtable]
+pub trait Operations: super::Operations {
+    /// The name of the VFIO driver.
+    const NAME: &'static CStr;
+
+    /// Called when the first file descriptor is opened for this device.
+    ///
+    /// `vfio_pci_core_enable()` has already succeeded; if this returns an
+    /// error, `vfio_pci_core_disable()` is called automatically. The returned
+    /// open data is dropped before PCI core close on the last close.
+    ///
+    /// The [`Open`] context is valid only during the first-open callback;
+    /// the open data must not retain `dev`.
+    ///
+    /// Exported DMA buffers do not keep the open data alive; PCI core close
+    /// revokes them after the open data is dropped.
+    fn open_device<'a, 'res: 'a>(
+        dev: &Device<Self, Open>,
+        reg_data: &'a Self::RegistrationData<'res>,
+    ) -> impl PinInit<Self::OpenData<'a, 'res>, Error> + 'a;
+
+    /// Handle a VFIO ioctl.
+    ///
+    /// The default `vfio_pci_core_ioctl()` is available via
+    /// [`Device::core_ioctl()`] for delegation.
+    ///
+    /// [`Device::core_ioctl()`]: Device#method.core_ioctl
+    #[optional]
+    fn ioctl<'res>(
+        _dev: &Device<Self, Ioctl>,
+        _reg_data: &Self::RegistrationData<'res>,
+        _open_data: Pin<&Self::OpenData<'_, 'res>>,
+        _cmd: u32,
+        _arg: usize,
+    ) -> Result<isize>;
+
+    /// Read from the device.
+    ///
+    /// `buf` is the user-space buffer of the read. Use [`Device::core_read()`] to
+    /// delegate the default read; the bytes it has read can be overridden afterwards
+    /// through the same [`UserSliceWriter`].
+    ///
+    /// [`Device::core_read()`]: Device#method.core_read
+    #[optional]
+    fn read<'res>(
+        _dev: &Device<Self, Read>,
+        _reg_data: &Self::RegistrationData<'res>,
+        _open_data: Pin<&Self::OpenData<'_, 'res>>,
+        _buf: UserSlice,
+        _ppos: &mut Position<'_>,
+    ) -> Result<isize>;
+
+    /// Write to the device, delegating to [`Device::core_write()`] if appropriate.
+    ///
+    /// `buf` is the user-space buffer of the write.
+    ///
+    /// [`Device::core_write()`]: Device#method.core_write
+    #[optional]
+    fn write<'res>(
+        _dev: &Device<Self, Write>,
+        _reg_data: &Self::RegistrationData<'res>,
+        _open_data: Pin<&Self::OpenData<'_, 'res>>,
+        _buf: UserSlice,
+        _ppos: &mut Position<'_>,
+    ) -> Result<isize>;
+
+    /// Map a device region, delegating to [`Device::core_mmap()`] if appropriate.
+    ///
+    /// [`Device::core_mmap()`]: Device#method.core_mmap
+    #[optional]
+    fn mmap<'res>(
+        _dev: &Device<Self, Mmap>,
+        _reg_data: &Self::RegistrationData<'res>,
+        _open_data: Pin<&Self::OpenData<'_, 'res>>,
+        _mapping: &mut Mapping<'_>,
+    ) -> Result;
+
+    /// Prepare for PCI reset, including resets initiated during enable or close.
+    fn reset_prepare(_reg_data: &Self::RegistrationData<'_>) {}
+
+    /// Finish PCI reset.
+    fn reset_done(_reg_data: &Self::RegistrationData<'_>) -> Result {
+        Ok(())
+    }
+
+    /// Fill in region info capabilities.
+    ///
+    /// The default `vfio_pci_ioctl_get_region_info()` is available via
+    /// [`Device::core_get_region_info()`] for delegation.
+    ///
+    /// [`Device::core_get_region_info()`]: Device#method.core_get_region_info
+    #[optional]
+    fn get_region_info<'res>(
+        _dev: &Device<Self, GetRegionInfo>,
+        _reg_data: &Self::RegistrationData<'res>,
+        _open_data: Pin<&Self::OpenData<'_, 'res>>,
+        _info: &mut RegionInfo,
+        _caps: &mut InfoCap,
+    ) -> Result;
+
+    /// Returns a limit on the length of a region that may be exported as a DMA buffer.
+    ///
+    /// `None` selects the length of the PCI resource, which also caps a returned limit. A
+    /// device without this callback does not support DMA buffer export.
+    #[optional]
+    fn dmabuf_len<'res>(
+        _reg_data: &Self::RegistrationData<'res>,
+        _open_data: Pin<&Self::OpenData<'_, 'res>>,
+        _region_index: u32,
+    ) -> Result<Option<u64>>;
+}
+
+/// A VFIO PCI file position, encoding a region index and an offset within that region.
+pub struct Position<'a> {
+    raw: &'a mut i64,
+}
+
+impl Position<'_> {
+    /// Commit a temporary position only after the operation succeeds.
+    ///
+    /// This preserves the original position if a read succeeds but a subsequent
+    /// user copy fails.
+    pub fn with_temporary<R>(
+        &mut self,
+        operation: impl FnOnce(&mut Position<'_>) -> Result<R>,
+    ) -> Result<R> {
+        let mut next = *self.raw;
+        let result = operation(&mut Position { raw: &mut next })?;
+        *self.raw = next;
+        Ok(result)
+    }
+
+    /// Returns the PCI region index.
+    #[inline]
+    pub fn region_index(&self) -> u32 {
+        ((*self.raw as u64) >> bindings::VFIO_PCI_OFFSET_SHIFT) as u32
+    }
+
+    /// Returns the byte offset within the current region.
+    #[inline]
+    pub fn region_offset(&self) -> u64 {
+        (*self.raw as u64) & ((1u64 << bindings::VFIO_PCI_OFFSET_SHIFT) - 1)
+    }
+}
+
+/// Mapping metadata supplied by VFIO while the current thread holds the mmap lock.
+///
+/// The underlying VMA can only be passed back to the core mmap operation.
+pub struct Mapping<'a> {
+    vma: &'a VmaNew,
+    _not_thread_safe: NotThreadSafe,
+}
+
+impl Mapping<'_> {
+    #[inline]
+    fn page_offset(&self) -> u64 {
+        self.vma.pgoff() as u64
+    }
+
+    /// Returns the PCI region index encoded in the mapping offset.
+    #[inline]
+    pub fn region_index(&self) -> u32 {
+        (self.page_offset() >> (bindings::VFIO_PCI_OFFSET_SHIFT as usize - crate::page::PAGE_SHIFT))
+            as u32
+    }
+
+    /// Returns the byte offset within the PCI region.
+    #[inline]
+    fn region_offset(&self) -> u64 {
+        let mask = ((1u64 << bindings::VFIO_PCI_OFFSET_SHIFT) - 1) >> crate::page::PAGE_SHIFT;
+        (self.page_offset() & mask) << crate::page::PAGE_SHIFT
+    }
+
+    /// Returns the exclusive end of the requested mapping within the PCI region.
+    #[inline]
+    pub fn region_end(&self) -> Result<u64> {
+        self.region_offset()
+            .checked_add(self.vma.size() as u64)
+            .ok_or(EOVERFLOW)
+    }
+}
+
+/// A VFIO PCI variant device, wrapping `struct vfio_pci_core_device`.
+///
+/// Callback contexts expose only their matching core helper and cannot be
+/// refcounted or shared across threads.
+///
+/// # Invariants
+///
+/// In addition to the invariants common to all VFIO devices:
+///
+/// - The wrapped `vfio_pci_core_device` was initialized by `vfio_pci_core_init_dev()`.
+/// - The callback data follows the VFIO registration and first-open/last-close lifetimes.
+///   Open data is destroyed before PCI core close, and registration data is
+///   released after PCI core unregistration has drained callbacks.
+pub type Device<T, Ctx = Normal> = DeviceBase<bindings::vfio_pci_core_device, T, Ctx>;
+
+static_assert!(core::mem::offset_of!(bindings::vfio_pci_core_device, vdev) == 0);
+
+impl<T: Operations> Device<T> {
+    /// Allocate a VFIO PCI device for [`Registration::new()`] to register.
+    fn new(pdev: &pci::Device<device::Core<'_>>) -> Result<ARef<Self>> {
+        // `_vfio_alloc_device()` allocates with `kvzalloc()`, which may fall back to vmalloc
+        // memory, and that is only guaranteed to be page aligned.
+        const { assert!(core::mem::align_of::<Self>() <= crate::page::PAGE_SIZE) };
+        let size = Kmalloc::aligned_layout(Layout::new::<Self>()).size();
+
+        // SAFETY: The bound PCI device and static ops are valid. `size` covers the full Rust
+        // wrapper and is a multiple of its alignment, so kmalloc memory of that size is
+        // suitably aligned; vmalloc memory is page aligned, which suffices as asserted above.
+        let raw = from_err_ptr(unsafe {
+            bindings::_vfio_alloc_device(size, pdev.as_ref().as_raw(), &Self::OPS)
+        })?;
+        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) })
+    }
+}
+
+impl<T: Operations, Ctx: IoContext> Device<T, Ctx> {
+    /// Accesses the registration data and the open data from an I/O callback.
+    ///
+    /// The data lifetimes stay independent of the callback borrow, so that borrowed data
+    /// cannot be stored back into the registration data or the open data.
+    #[inline]
+    fn callback_data_with<V, F>(&self, f: F) -> V
+    where
+        F: for<'a, 'res> FnOnce(&T::RegistrationData<'res>, Pin<&T::OpenData<'a, 'res>>) -> V,
+    {
+        // SAFETY: `f` is generic over the lifetimes of the data, so it uses the data
+        // parametrically.
+        let (reg_data, open_data) = unsafe { self.callback_data() };
+        f(reg_data, open_data)
+    }
+}
+
+impl<T: Operations> Device<T, Open> {
+    /// Set the device ID exposed through VFIO's virtual PCI configuration space.
+    pub fn set_device_id(&self, device_id: u16) {
+        // SAFETY: core_enable allocated vconfig; the exclusive first-open callback
+        // runs before finish_enable publishes the configuration to userspace.
+        unsafe {
+            (*self.as_raw())
+                .vconfig
+                .add(bindings::PCI_DEVICE_ID as usize)
+                .cast::<u16>()
+                .write_unaligned(device_id.to_le());
+        }
+    }
+}
+
+impl<T: Operations> Device<T, Ioctl> {
+    /// Delegate to `vfio_pci_core_ioctl()`.
+    pub fn core_ioctl(&self, cmd: u32, arg: usize) -> Result<isize> {
+        // SAFETY: The Ioctl context keeps this device open on the callback thread.
+        let ret = unsafe { bindings::vfio_pci_core_ioctl(self.as_raw_vfio(), cmd, arg) };
+        if ret < 0 {
+            Err(Error::from_errno(ret as i32))
+        } else {
+            Ok(ret)
+        }
+    }
+}
+
+impl<T: Operations> Device<T, Read> {
+    /// Delegate to `vfio_pci_core_read()`.
+    ///
+    /// The VFIO core fills the remaining space of `buf` with the default PCI data
+    /// for the region identified by `ppos` and advances the position by the bytes read.
+    ///
+    /// `buf` itself is not advanced: it still starts at the first byte that was read, so
+    /// that the caller can override bytes of the result.
+    pub fn core_read(&self, buf: &UserSliceWriter, ppos: &mut Position<'_>) -> Result<isize> {
+        // SAFETY: The Read context keeps this device open on the callback thread;
+        // `buf` describes user-space memory, which the VFIO core accesses as such.
+        let ret = unsafe {
+            bindings::vfio_pci_core_read(
+                self.as_raw_vfio(),
+                buf.as_ptr().as_mut_ptr().cast(),
+                buf.len(),
+                ppos.raw,
+            )
+        };
+        if ret < 0 {
+            Err(Error::from_errno(ret as i32))
+        } else {
+            Ok(ret)
+        }
+    }
+}
+
+impl<T: Operations> Device<T, Write> {
+    /// Delegate to `vfio_pci_core_write()`.
+    ///
+    /// The VFIO core consumes the remaining data of `buf` for the region identified by
+    /// `ppos` and advances the position by the bytes written. `buf` itself is not advanced.
+    ///
+    /// The VFIO core fetches the data from user space itself. Data that the caller has read
+    /// through a clone of `buf` beforehand is fetched again and may have changed.
+    pub fn core_write(&self, buf: &UserSliceReader, ppos: &mut Position<'_>) -> Result<isize> {
+        // SAFETY: The Write context keeps the device open on the callback thread;
+        // `buf` describes user-space memory, which the VFIO core accesses as such.
+        let ret = unsafe {
+            bindings::vfio_pci_core_write(
+                self.as_raw_vfio(),
+                buf.as_ptr().as_const_ptr().cast(),
+                buf.len(),
+                ppos.raw,
+            )
+        };
+        if ret < 0 {
+            Err(Error::from_errno(ret as i32))
+        } else {
+            Ok(ret)
+        }
+    }
+}
+
+impl<T: Operations> Device<T, Mmap> {
+    /// Delegate to `vfio_pci_core_mmap()` for the current callback's VMA.
+    #[inline]
+    pub fn core_mmap(&self, mapping: &mut Mapping<'_>) -> Result {
+        // SAFETY: The Mmap context and Mapping keep the open device and locked VMA
+        // on the callback thread. The VMA cannot be replaced by driver code.
+        to_result(unsafe { bindings::vfio_pci_core_mmap(self.as_raw_vfio(), mapping.vma.as_ptr()) })
+    }
+}
+
+impl<T: Operations> Device<T, GetRegionInfo> {
+    /// Delegate to `vfio_pci_ioctl_get_region_info()`.
+    pub fn core_get_region_info(&self, info: &mut RegionInfo, caps: &mut InfoCap) -> Result {
+        // SAFETY: GetRegionInfo keeps the device open on the callback thread;
+        // `RegionInfo` and `InfoCap` preserve the validity of VFIO's region information and
+        // capability buffer.
+        to_result(unsafe {
+            bindings::vfio_pci_ioctl_get_region_info(
+                self.as_raw_vfio(),
+                info.as_raw(),
+                caps.as_raw(),
+            )
+        })
+    }
+}
+
+/// # Safety
+///
+/// `vdev` must belong to a registered `Device<T>` in VFIO's first-open context.
+/// VFIO must exclude other opens, closes and I/O callbacks for this call.
+unsafe extern "C" fn open_device_cb<T: Operations>(vdev: *mut bindings::vfio_device) -> c_int {
+    from_result(|| {
+        // SAFETY: `vdev` belongs to a live `Device<T>`; VFIO provides the first-open context.
+        let dev = unsafe { Device::<T, Open>::from_raw_vfio(vdev) };
+
+        // SAFETY: Enable the PCI-core side first.
+        to_result(unsafe { bindings::vfio_pci_core_enable(dev.as_raw()) })?;
+
+        // SAFETY: The previous last close destroyed any earlier open data. `T::open_device()`
+        // is generic over the data lifetimes and takes an independent `dev` borrow, so it
+        // cannot store that borrow in the open data. `close_device_cb()` destroys the open
+        // data at the last close.
+        unsafe { dev.open(|reg_data| T::open_device(dev, reg_data)) }.inspect_err(|_| {
+            // SAFETY: Undo the enable on failure.
+            unsafe { bindings::vfio_pci_core_disable(dev.as_raw()) };
+        })?;
+
+        // SAFETY: open succeeded.
+        unsafe { bindings::vfio_pci_core_finish_enable(dev.as_raw()) };
+        Ok(0)
+    })
+}
+
+/// # Safety
+///
+/// `vdev` must belong to a registered `Device<T>` whose first open succeeded.
+/// Call exactly once for the last close, after draining I/O callbacks and while
+/// excluding the next first open.
+unsafe extern "C" fn close_device_cb<T: Operations>(vdev: *mut bindings::vfio_device) {
+    // SAFETY: `vdev` belongs to a live `Device<T>`.
+    let dev = unsafe { Device::<T>::from_raw_vfio(vdev) };
+    // SAFETY: Last close drains I/O callbacks and excludes the next first open.
+    // Registration data and PCI resources remain valid while open data is destroyed.
+    unsafe { dev.close() };
+    // SAFETY: Matches the enable in open_device_cb.
+    unsafe { bindings::vfio_pci_core_close_device(vdev) };
+}
+
+/// # Safety
+///
+/// `vdev` must belong to a registered, open `Device<T>` in VFIO's ioctl callback
+/// context. Registration and open data must remain alive until the call returns.
+unsafe extern "C" fn ioctl_cb<T: Operations>(
+    vdev: *mut bindings::vfio_device,
+    cmd: core::ffi::c_uint,
+    arg: usize,
+) -> isize {
+    // SAFETY: `vdev` belongs to a live `Device<T>`; VFIO provides the ioctl context.
+    let dev = unsafe { Device::<T, Ioctl>::from_raw_vfio(vdev) };
+    from_result(|| dev.callback_data_with(|rd, od| T::ioctl(dev, rd, od, cmd, arg)))
+}
+
+/// # Safety
+///
+/// `vdev` must belong to a registered, open `Device<T>` in VFIO's read context.
+/// `buf` must be a userspace address and `ppos` must be exclusively accessible
+/// for this call. Registration and open data must remain alive until it returns.
+unsafe extern "C" fn read_cb<T: Operations>(
+    vdev: *mut bindings::vfio_device,
+    buf: *mut u8,
+    count: usize,
+    ppos: *mut i64,
+) -> isize {
+    // SAFETY: `vdev` belongs to a live `Device<T>`; VFIO provides the read context.
+    let dev = unsafe { Device::<T, Read>::from_raw_vfio(vdev) };
+    let ubuf = UserSlice::new(UserPtr::from_ptr(buf.cast()), count);
+    let mut pos = Position {
+        // SAFETY: `ppos` is a valid kernel pointer provided by the VFIO core.
+        raw: unsafe { &mut *ppos },
+    };
+    from_result(|| dev.callback_data_with(|rd, od| T::read(dev, rd, od, ubuf, &mut pos)))
+}
+
+/// # Safety
+///
+/// `vdev` must belong to a registered, open `Device<T>` in VFIO's region-info
+/// context. `info` and `caps` must be valid, disjoint, exclusively accessible
+/// objects; the capability buffer must satisfy the VFIO core's invariants.
+/// Registration and open data must remain alive until the call returns.
+unsafe extern "C" fn get_region_info_cb<T: Operations>(
+    vdev: *mut bindings::vfio_device,
+    info: *mut bindings::vfio_region_info,
+    caps: *mut bindings::vfio_info_cap,
+) -> c_int {
+    // SAFETY: `vdev` belongs to a live `Device<T>`; VFIO provides the region-info context.
+    let dev = unsafe { Device::<T, GetRegionInfo>::from_raw_vfio(vdev) };
+    // SAFETY: The VFIO caller lends its initialized `info` exclusively to this callback. All
+    // access until it returns goes through this borrowed view.
+    let info = unsafe { RegionInfo::from_raw(info) };
+    // SAFETY: The VFIO caller lends `caps` exclusively to this callback. All access until it
+    // returns goes through this borrowed view.
+    let caps = unsafe { InfoCap::from_raw(caps) };
+    from_result(|| {
+        dev.callback_data_with(|rd, od| T::get_region_info(dev, rd, od, info, caps))
+            .map(|()| 0)
+    })
+}
+
+/// # Safety
+///
+/// `vdev` must belong to a registered, open `Device<T>` in VFIO's write context.
+/// `buf` must be a userspace address and `ppos` must be exclusively accessible
+/// for this call. Registration and open data must remain alive until it returns.
+unsafe extern "C" fn write_cb<T: Operations>(
+    vdev: *mut bindings::vfio_device,
+    buf: *const u8,
+    count: usize,
+    ppos: *mut i64,
+) -> isize {
+    // SAFETY: `vdev` belongs to a live `Device<T>`; VFIO provides the write context.
+    let dev = unsafe { Device::<T, Write>::from_raw_vfio(vdev) };
+    let ubuf = UserSlice::new(UserPtr::from_ptr(buf.cast_mut().cast()), count);
+    let mut pos = Position {
+        // SAFETY: VFIO holds the file-position lock when required.
+        raw: unsafe { &mut *ppos },
+    };
+    from_result(|| dev.callback_data_with(|rd, od| T::write(dev, rd, od, ubuf, &mut pos)))
+}
+
+/// # Safety
+///
+/// `vdev` must belong to a registered, open `Device<T>` in VFIO's mmap context.
+/// `vma` must be the valid VMA being mapped, with the mmap write lock held on
+/// this thread. Registration and open data must remain alive until return.
+unsafe extern "C" fn mmap_cb<T: Operations>(
+    vdev: *mut bindings::vfio_device,
+    vma: *mut bindings::vm_area_struct,
+) -> c_int {
+    // SAFETY: `vdev` belongs to a live `Device<T>`; VFIO provides the mmap context.
+    let dev = unsafe { Device::<T, Mmap>::from_raw_vfio(vdev) };
+    let mut mapping = Mapping {
+        // SAFETY: VFIO calls this from its `f_ops->mmap()` hook, where the VMA is being set up.
+        vma: unsafe { VmaNew::from_raw(vma) },
+        _not_thread_safe: NotThreadSafe,
+    };
+    from_result(|| {
+        dev.callback_data_with(|rd, od| T::mmap(dev, rd, od, &mut mapping))
+            .map(|()| 0)
+    })
+}
+
+/// # Safety
+///
+/// `vdev` must belong to a registered, open `Device<T>` in VFIO's ioctl context, and the other
+/// pointers must be those `vfio_pci_core_feature_dma_buf()` passes to this callback.
+/// Registration and open data must remain alive until return.
+#[cfg(CONFIG_VFIO_PCI_DMABUF)]
+unsafe extern "C" fn get_dmabuf_phys_cb<T: Operations>(
+    vdev: *mut bindings::vfio_pci_core_device,
+    provider: *mut *mut bindings::p2pdma_provider,
+    region_index: c_uint,
+    phys_vec: *mut bindings::phys_vec,
+    dma_ranges: *mut bindings::vfio_region_dma_range,
+    nr_ranges: usize,
+) -> c_int {
+    // SAFETY: `vdev` begins with the `vfio_device` of a live `Device<T>`; the device feature
+    // ioctl provides the ioctl context.
+    let dev = unsafe { Device::<T, Ioctl>::from_raw_vfio(vdev.cast()) };
+    from_result(|| {
+        let len = dev.callback_data_with(|rd, od| T::dmabuf_len(rd, od, region_index))?;
+        let Some(len) = len else {
+            // SAFETY: The arguments are passed on unchanged from the PCI core.
+            let ret = unsafe {
+                bindings::vfio_pci_core_get_dmabuf_phys(
+                    vdev,
+                    provider,
+                    region_index,
+                    phys_vec,
+                    dma_ranges,
+                    nr_ranges,
+                )
+            };
+            return to_result(ret).map(|()| 0);
+        };
+        // SAFETY: `vdev` is a live `vfio_pci_core_device`.
+        let pdev = unsafe { (*vdev).pdev };
+        // SAFETY: `pdev` is the device bound to this driver, and the PCI core validated
+        // `region_index` as one of its BARs.
+        let p2pdma = unsafe { bindings::pcim_p2pdma_provider(pdev, region_index as c_int) };
+        if p2pdma.is_null() {
+            return Err(EINVAL);
+        }
+        // SAFETY: `provider` is the valid output pointer of the PCI core.
+        unsafe { provider.write(p2pdma) };
+        // SAFETY: By the same reasoning above, `pdev` and its BAR `region_index` are valid.
+        let start = unsafe { bindings::pci_resource_start(pdev, region_index as c_int) };
+        // SAFETY: By the same reasoning above, `pdev` and its BAR `region_index` are valid.
+        let bar_len = unsafe { bindings::pci_resource_len(pdev, region_index as c_int) };
+        let len = len.min(bar_len);
+        // SAFETY: `phys_vec` and `dma_ranges` hold `nr_ranges` entries, as passed by the PCI
+        // core, and `len` is within the BAR.
+        let ret = unsafe {
+            bindings::vfio_pci_core_fill_phys_vec(phys_vec, dma_ranges, nr_ranges, start, len)
+        };
+        to_result(ret).map(|()| 0)
+    })
+}
+
+/// 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
+            },
+            read: if <$T>::HAS_READ {
+                Some(read_cb::<$T>)
+            } else {
+                None
+            },
+            write: if <$T>::HAS_WRITE {
+                Some(write_cb::<$T>)
+            } else {
+                None
+            },
+            mmap: if <$T>::HAS_MMAP {
+                Some(mmap_cb::<$T>)
+            } else {
+                None
+            },
+            request: Some(bindings::vfio_pci_core_request),
+            get_region_info_caps: if <$T>::HAS_GET_REGION_INFO {
+                Some(get_region_info_cb::<$T>)
+            } else {
+                None
+            },
+            match_: Some(bindings::vfio_pci_core_match),
+            match_token_uuid: Some(bindings::vfio_pci_core_match_token_uuid),
+            device_feature: Some(bindings::vfio_pci_core_ioctl_feature),
+            #[cfg(CONFIG_IOMMUFD)]
+            bind_iommufd: Some(bindings::vfio_iommufd_physical_bind),
+            #[cfg(not(CONFIG_IOMMUFD))]
+            bind_iommufd: None,
+            #[cfg(CONFIG_IOMMUFD)]
+            unbind_iommufd: Some(bindings::vfio_iommufd_physical_unbind),
+            #[cfg(not(CONFIG_IOMMUFD))]
+            unbind_iommufd: None,
+            #[cfg(CONFIG_IOMMUFD)]
+            attach_ioas: Some(bindings::vfio_iommufd_physical_attach_ioas),
+            #[cfg(not(CONFIG_IOMMUFD))]
+            attach_ioas: None,
+            #[cfg(CONFIG_IOMMUFD)]
+            detach_ioas: Some(bindings::vfio_iommufd_physical_detach_ioas),
+            #[cfg(not(CONFIG_IOMMUFD))]
+            detach_ioas: None,
+            #[cfg(CONFIG_IOMMUFD)]
+            pasid_attach_ioas: Some(bindings::vfio_iommufd_physical_pasid_attach_ioas),
+            #[cfg(not(CONFIG_IOMMUFD))]
+            pasid_attach_ioas: None,
+            #[cfg(CONFIG_IOMMUFD)]
+            pasid_detach_ioas: Some(bindings::vfio_iommufd_physical_pasid_detach_ioas),
+            #[cfg(not(CONFIG_IOMMUFD))]
+            pasid_detach_ioas: None,
+            dma_unmap: None,
+        }
+    };
+}
+
+/// The registration of a VFIO PCI variant device.
+///
+/// Owns both the VFIO device reference and the registration data, tying
+/// resource lifetimes to the PCI binding scope `'a`. The device is registered
+/// on construction and unregistered when the `Registration` is dropped.
+pub struct Registration<'a, T: Operations> {
+    dev: ARef<Device<T>>,
+    reg_data: Pin<KBox<T::RegistrationData<'a>>>,
+}
+
+impl<T: Operations> Device<T> {
+    const OPS: bindings::vfio_device_ops = build_ops!(T);
+
+    const PCI_OPS: bindings::vfio_pci_device_ops = bindings::vfio_pci_device_ops {
+        #[cfg(CONFIG_VFIO_PCI_DMABUF)]
+        get_dmabuf_phys: if T::HAS_DMABUF_LEN {
+            Some(get_dmabuf_phys_cb::<T>)
+        } else {
+            None
+        },
+        #[cfg(not(CONFIG_VFIO_PCI_DMABUF))]
+        get_dmabuf_phys: None,
+    };
+}
+
+impl<'a, T: Operations> Registration<'a, T> {
+    /// Allocate a VFIO PCI device for `pdev` and register it with its callback data.
+    ///
+    /// Returns [`EINVAL`] if the PCI driver bound to `pdev` does not manage DMA ownership, or if
+    /// it provides an SR-IOV configuration callback, which this abstraction does not support.
+    ///
+    /// # Safety
+    ///
+    /// The returned `Registration` must be stored in the bus device private data of the driver
+    /// bound to `pdev`, and must not be leaked: it has to be dropped while that driver is being
+    /// unbound from `pdev`, or when its probe fails.
+    pub unsafe fn new(
+        pdev: &'a pci::Device<device::Core<'_>>,
+        reg_data: impl PinInit<T::RegistrationData<'a>, Error>,
+    ) -> Result<Self> {
+        if !pdev.driver_has_managed_dma() || pdev.driver_has_sriov_configure() {
+            return Err(EINVAL);
+        }
+
+        let dev = Device::<T>::new(pdev)?;
+
+        let reg_data: Pin<KBox<T::RegistrationData<'a>>> = KBox::pin_init(reg_data, GFP_KERNEL)?;
+        let ptr = NonNull::from(Pin::get_ref(reg_data.as_ref()));
+
+        // SAFETY: `dev` was allocated above and has not been registered, so nothing else can
+        // access it and no data has been published for it. The returned `Registration` keeps
+        // the pinned data alive until it has unregistered `dev`; if registration fails below,
+        // `dev` is released unregistered and never accesses the data.
+        unsafe { dev.publish_registration_data(ptr) };
+
+        // Registering `dev` allows runtime suspend of `pdev`. The VFIO PCI core expects the PCI
+        // driver's runtime PM callbacks to call into it, which these abstractions do not provide
+        // yet, so keep `pdev` runtime active while `dev` is registered.
+        // TODO: Replace this with the runtime PM handling of the PCI bus once it is available.
+        //
+        // SAFETY: `pdev` is a valid device. This is `pm_runtime_get_sync()`, which takes a usage
+        // reference even if it fails.
+        #[cfg(CONFIG_PM)]
+        let ret = unsafe {
+            bindings::__pm_runtime_resume(pdev.as_ref().as_raw(), bindings::RPM_GET_PUT as c_int)
+        };
+        #[cfg(not(CONFIG_PM))]
+        let ret = 0;
+
+        to_result(ret)
+            .and_then(|()| {
+                // SAFETY: `dev` is initialized, has published its registration data and has not
+                // been registered before. The caller holds the PCI device lock of its parent.
+                to_result(unsafe { bindings::vfio_pci_core_register_device(dev.as_raw()) })
+            })
+            .inspect_err(|_| {
+                // SAFETY: `pdev` is a valid device, and the usage reference taken above is
+                // dropped here. This is `pm_runtime_put()`.
+                #[cfg(CONFIG_PM)]
+                unsafe {
+                    bindings::__pm_runtime_idle(
+                        pdev.as_ref().as_raw(),
+                        (bindings::RPM_GET_PUT | bindings::RPM_ASYNC) as c_int,
+                    )
+                };
+            })?;
+
+        Ok(Self { dev, reg_data })
+    }
+
+    /// Prepare the variant driver's state for a PCI reset.
+    pub fn reset_prepare(&self) {
+        T::reset_prepare(&self.reg_data);
+    }
+
+    /// Complete the variant driver's state update after a PCI reset.
+    pub fn reset_done(&self) -> Result {
+        T::reset_done(&self.reg_data)
+    }
+
+    /// Signal the VFIO error interrupt and return the PCI recovery result.
+    pub fn error_detected(&self) -> pci::ErsResult {
+        // SAFETY: This owner keeps the initialized VFIO core device alive.
+        let result = unsafe { bindings::vfio_pci_core_aer_err_detected(self.dev.as_raw()) };
+        // The VFIO PCI core only returns results `pci::ErsResult` represents.
+        pci::ErsResult::from_raw(result).unwrap_or(pci::ErsResult::None)
+    }
+}
+
+impl<T: Operations> Drop for Registration<'_, T> {
+    fn drop(&mut self) {
+        // SAFETY: `new()` registered the device. By its safety requirements, this runs with the
+        // PCI device lock held, either from the PCI remove callback or while probe fails.
+        // Unregistration drains the VFIO callbacks, the only users of the registration data
+        // besides this owner, before the data is released.
+        unsafe { bindings::vfio_pci_core_unregister_device(self.dev.as_raw()) };
+
+        // SAFETY: `new()` took the usage reference dropped here on the parent device of `dev`.
+        // By the safety requirements of `new()`, that device is still bound, so the pointer is
+        // valid. This is `pm_runtime_put()`.
+        #[cfg(CONFIG_PM)]
+        unsafe {
+            bindings::__pm_runtime_idle(
+                (*self.dev.as_raw_vfio()).dev,
+                (bindings::RPM_GET_PUT | bindings::RPM_ASYNC) as c_int,
+            )
+        };
+    }
+}
-- 
2.43.7


^ permalink raw reply related	[flat|nested] 7+ messages in thread

* Re: [PATCH v5 2/4] rust: vfio: add common VFIO device handling
  2026-12-04  4:17 ` [PATCH v5 2/4] rust: vfio: add common VFIO device handling Simon Song
@ 2026-12-05  4:19   ` sashiko-bot
  0 siblings, 0 replies; 7+ messages in thread
From: sashiko-bot @ 2026-12-05  4:19 UTC (permalink / raw)
  To: Simon Song, dakr, acourbot, kvm, 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, zhiwang,
	boqun, daniel.almeida, tamird, work, jgg, bhelgaas, kwilczynski,
	dri-devel, peter, Liam R. Howlett, linux-mm, Lorenzo Stoakes

Thank you for your contribution! Sashiko AI review found 3 potential
issues to consider:
- [Low] rust: vfio: missing #[inline] on small DeviceBase helpers
- [Low] rust: vfio: DeviceBase::callback_data() bypasses
  ForeignOwnable::borrow()
- [Low] rust: vfio: AlwaysRefCounted reaches into private
  vfio_device::device field
--

commit 00c5e0b75ff0082149fe02d0ba3c927a81f1b2c9
Author: Zhi Wang <zhiw@nvidia.com>

rust: vfio: add common VFIO device handling

This commit adds the core Rust VFIO device abstraction (DeviceBase and
Device), along with callback context types, registration and open data
storage, reference counting, and InfoCap.

> diff --git a/rust/kernel/vfio.rs b/rust/kernel/vfio.rs
> new file mode 100644
> index 0000000000000..30a593634a72b
> --- /dev/null
> +++ b/rust/kernel/vfio.rs
> @@ -0,0 +1,357 @@

[ ... ]

> +    unsafe fn init(this: *mut Self) {
> +        // SAFETY: The caller provides exclusive access to a suitable allocation.
> +        // INVARIANT: No data is published, and no open data exists.
> +        unsafe {
> +            (&raw mut (*this).data).write(CallbackData {
> +                reg_data: UnsafeCell::new(None),
> +                open_data: UnsafeCell::new(None),
> +            })
> +        };
> +        // SAFETY: By the same reasoning above, `_context` can be written.
> +        unsafe { (&raw mut (*this)._context).write(PhantomData) };
> +    }

[Severity: Low]
Should DeviceBase::init(), DeviceBase::publish_registration_data(), and
DeviceBase::callback_data() be marked #[inline]?  Kernel crate convention is
to mark small abstraction helpers #[inline], matching the other small
helpers in this module.

[ ... ]

> +        let open_data = unsafe { *self.data.open_data.get() }
> +            .expect("VFIO OpenData is expected to be populated.");
> +        // SAFETY: By the same reasoning above, the registration data is valid for this callback.
> +        let reg_data = unsafe { reg_data.as_ref() };
> +        // SAFETY: By the same reasoning above, the open data is valid for this callback.
> +        let open_data = unsafe { open_data.as_ref() };
> +        // SAFETY: By the same reasoning above, the open data is pinned until the last close.
> +        (reg_data, unsafe { Pin::new_unchecked(open_data) })

[Severity: Low]
Should callback_data() borrow open_data via
Pin::<KBox<T::OpenData<'static, 'static>>>::borrow() instead of
dereferencing the raw pointer directly?

DeviceBase::open() produces this pointer with
ForeignOwnable::into_foreign(), which documents that using the pointer
outside from_foreign(), try_from_foreign(), borrow(), or borrow_mut() can
cause undefined behavior.

Calling borrow(open_data.as_ptr().cast()) matches close()'s use of
from_foreign() and avoids relying on Pin<KBox<T>>'s internal pointer
representation.

[ ... ]

> +// SAFETY: VFIO uses the embedded class device's refcount to own the full allocation.
> +unsafe impl<Raw, T: Operations> AlwaysRefCounted for DeviceBase<Raw, T> {
> +    #[inline]
> +    fn inc_ref(&self) {
> +        // SAFETY: A shared reference keeps the initialized VFIO device alive.
> +        unsafe { bindings::get_device(&raw mut (*self.as_raw_vfio()).device) };
> +    }
> +
> +    #[inline]
> +    unsafe fn dec_ref(obj: NonNull<Self>) {
> +        // By the type invariants, `Raw` begins with its `vfio_device`, and `raw` is the first
> +        // field of `Self`.
> +        let vdev = obj.as_ptr().cast::<bindings::vfio_device>();
> +        // SAFETY: The caller owns the VFIO reference being released.
> +        unsafe { bindings::put_device(&raw mut (*vdev).device) };
> +    }
> +}

[Severity: Low]
Should AlwaysRefCounted avoid reaching into struct vfio_device::device
directly?

In include/linux/vfio.h, vfio_device::device is marked private and not for
driver use, and vfio_put_device() is already the public release helper.
Bypassing it risks silently diverging if VFIO changes its internal
refcounting or adds logic to vfio_put_device().

Adding a paired vfio_get_device() helper in include/linux/vfio.h and
wrapping both via rust/helpers/vfio.c would keep this within the public VFIO
API.

-- 
Sashiko AI review · https://sashiko.dev/#/patchset/20261204041727.4021092-1-xinmengs@nvidia.com?part=2

^ permalink raw reply	[flat|nested] 7+ messages in thread

* Re: [PATCH v5 4/4] rust: vfio: add PCI variant driver abstractions
  2026-12-04  4:17 ` [PATCH v5 4/4] rust: vfio: add PCI variant driver abstractions Simon Song
@ 2026-12-05  4:19   ` sashiko-bot
  0 siblings, 0 replies; 7+ messages in thread
From: sashiko-bot @ 2026-12-05  4:19 UTC (permalink / raw)
  To: Simon Song, dakr, acourbot, kvm, 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, zhiwang,
	zhiw, boqun, daniel.almeida, tamird, work, jgg, bhelgaas,
	kwilczynski, dri-devel, peter, Liam R. Howlett, linux-mm,
	Lorenzo Stoakes

Thank you for your contribution! Sashiko AI review found 2 potential
issues to consider:
- [Low] rust: vfio: missing #[inline] on small and forwarding methods in
  vfio::pci
- [Low] rust: vfio: build_ops!() duplicates
  as_char_ptr_in_const_context()
--

commit fc553fbc4c9de5d8211c3a1d37c9e87f322da8bb
Author: Danilo Krummrich <dakr@kernel.org>

rust: vfio: add PCI variant driver abstractions

This commit adds Rust abstractions for VFIO PCI variant drivers in
rust/kernel/vfio/pci.rs, along with PCI device and error-result helpers in
rust/kernel/pci.rs.

> diff --git a/rust/kernel/vfio/pci.rs b/rust/kernel/vfio/pci.rs
> new file mode 100644
> index 0000000000000..728baf0c1ce93
> --- /dev/null
> +++ b/rust/kernel/vfio/pci.rs
> @@ -0,0 +1,880 @@

[ ... ]

> +    pub fn with_temporary<R>(
> +        &mut self,
> +        operation: impl FnOnce(&mut Position<'_>) -> Result<R>,
> +    ) -> Result<R> {
> +        let mut next = *self.raw;
> +        let result = operation(&mut Position { raw: &mut next })?;
> +        *self.raw = next;
> +        Ok(result)
> +    }

[Severity: Low]
Should Position::with_temporary() and the other small or forwarding
methods in vfio::pci be marked #[inline]?

In the kernel crate, small helpers and thin wrappers around C bindings
normally carry #[inline] (as Position::region_index() and
Device::core_mmap() already do) so they can be inlined across crates into
variant drivers.

This also applies to Device::set_device_id(), Device::core_ioctl(),
Device::core_read(), Device::core_write(), Device::core_get_region_info(),
Registration::reset_prepare(), Registration::reset_done(), and
Registration::error_detected().

[ ... ]

> +macro_rules! build_ops {
> +    ($T:ty) => {
> +        bindings::vfio_device_ops {
> +            #[allow(clippy::disallowed_methods)]
> +            name: <$T>::NAME.as_ptr().cast_mut().cast(),

[Severity: Low]
Can this use crate::str::as_char_ptr_in_const_context(<$T>::NAME).cast_mut()
instead of duplicating the cast with #[allow(clippy::disallowed_methods)]?

rust/kernel/str.rs already provides as_char_ptr_in_const_context() for
const-context vtable initializers, as used by other subsystems in the
kernel crate.

-- 
Sashiko AI review · https://sashiko.dev/#/patchset/20261204041727.4021092-1-xinmengs@nvidia.com?part=4

^ permalink raw reply	[flat|nested] 7+ messages in thread

end of thread, other threads:[~2026-12-05  4:19 UTC | newest]

Thread overview: 7+ messages (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
2026-12-04  4:17 [PATCH v5 0/4] Rust VFIO PCI support Simon Song
2026-12-04  4:17 ` [PATCH v5 1/4] rust: uaccess: support bounded forward buffer traversal Simon Song
2026-12-04  4:17 ` [PATCH v5 2/4] rust: vfio: add common VFIO device handling Simon Song
2026-12-05  4:19   ` sashiko-bot
2026-12-04  4:17 ` [PATCH v5 3/4] rust: mm: add VmaRef::size() and VmaRef::pgoff() Simon Song
2026-12-04  4:17 ` [PATCH v5 4/4] rust: vfio: add PCI variant driver abstractions Simon Song
2026-12-05  4:19   ` sashiko-bot

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox