Re: [PATCH v4 1/5] rust: vfio: add common VFIO device handling
From: Simon Song
Date: Thu Dec 03 2026 - 10:55:41 EST
On 12/2/2026 10:58 AM, Gary Guo wrote:
...
>> +//! 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`.
>
> `DeviceBase` is mentioned here in public-facing documentation while the type
> itself is hidden.
>
Good catch, I will describe Device directly and no longer names DeviceBase
>> +//!
>> +//! C header: [`include/linux/vfio.h`](srctree/include/linux/vfio.h)
>> +
>> +use crate::{
>> + bindings,
>> + prelude::*,
>> + sync::aref::AlwaysRefCounted,
>> + types::{
>> + ForeignOwnable,
>> + NotThreadSafe,
>> + Opaque, //
>> + },
>> + uaccess::{
>> + UserPtr,
>> + UserSlice, //
>> + }, //
>> +};
>> +use core::{
>> + cell::UnsafeCell,
>> + marker::PhantomData,
>> + ops::Range,
>> + 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;
>
> That's a lot of type states. It looks like all of these are only used to ensure
> only corresponding vfio_pci_core callbacks can be delegated to. Are these really
> needed for soundness? I can understand that the `Open` one might be needed, but
> the rest might be mergeable?
>
As Danilo wrote, they're not needed for soundness, but to limit a callback to its own core function:
for example, core_write() cannot be called from read()
...
>> +#[expect(dead_code)]
>> +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 `'reg`; 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, 'reg: 'a, I>(
>> + &'a self,
>> + init: impl FnOnce(&'a T::RegistrationData<'reg>) -> I,
>> + ) -> Result
>> + where
>> + I: PinInit<T::OpenData<'a, 'reg>, Error>,
>
> `Device<Open>` can escape into `T::OpenData` and break the invariants. You need
> to change `pci::Operations::open_device` to give `dev` an anonymous lifetime.
>
will make this change as your suggestion in patch 3
>> + {
>> + // 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<'reg>>().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(())
>> + }
>> +}
>> +
>> +#[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.
>> + ///
>> + /// # 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> {
>> + 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) };
>> + }
>> +
>> + 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.
>> +pub struct InfoCap<'a> {
>> + #[expect(dead_code)]
>> + raw: &'a mut bindings::vfio_info_cap,
>> +}
>
> Any reason that this isn't
>
> #[repr(transparent)
> pub struct InfoCap {
> raw: Opaque<bindings::vfio_info_cap>,
> }
>
> ?
>
good catch, will include in next respin