On Thu Nov 19, 2026 at 10:50 PM CET, Simon Song wrote:
> +/// Maps a C device structure to its embedded VFIO device.
> +///
> +/// # Safety
> +///
> +/// Implementations must return the address of the `vfio_device` at the 
> beginning of `Self`,

I think "at the beginning of `Self`" is not a safety requirement for this trait,
it's an implementation detail of the current implementation on the C side, that
could be a type invariant of DeviceBase.

Besides that, I think the abstraction we currently need with DeviceBase and
RawDevice (which I proposed to deal with the current implementation) could be
simplified if the C code would be more flexible regarding the layout of a struct
subclassing a struct vfio_device.

However, this could be a subsequent consideration and nothing that needs to be
tackled now; it is mostly an implementation detail of this abstraction.

> +/// preserving the input pointer's provenance.
> +pub unsafe trait RawDevice {
> +    /// Returns the `vfio_device` embedded in `raw`.
> +    ///
> +    /// # Safety
> +    ///
> +    /// `raw` must point to an initialized, live `Self`.
> +    unsafe fn raw_vfio_device(raw: *mut Self) -> *mut bindings::vfio_device;

I think this could be safe by taking &Opaque<Self>.

> +}
> +
> +// SAFETY: A `vfio_device` is its own VFIO device.
> +unsafe impl RawDevice for bindings::vfio_device {
> +    unsafe fn raw_vfio_device(raw: *mut Self) -> *mut bindings::vfio_device {
> +        raw
> +    }
> +}
> +
> +/// Callback data stored after the C device structure.
> +///
> +/// `R` is the type of the registration data and `O` the type of the open 
> data, 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 null 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<R, O> {
> +    reg_data: UnsafeCell<Option<NonNull<R>>>,
> +    open_data: UnsafeCell<*mut O>,

I think this should be Option<NonNull<O>> as well.

> +}
> +
> +/// 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.
> +///
> +/// `R` and `O` are the types of the registration data and the open data of 
> `T`, written with
> +/// the placeholder lifetime `'static`. Use the alias [`Device`], which 
> takes both from the
> +/// operations trait of `T`.
> +///
> +/// # Invariants
> +///
> +/// - `R` and `O` are the registration data and open data types of `T` with 
> all lifetimes
> +///   replaced by `'static`. 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.
> +/// - The device is registered with VFIO only after its registration data 
> has been published.

That's more of a description of the registration protocal than a type invariant.

Maybe something like:

"For [`Open`] and [`IoContext`] references, registration data is published and
remains valid for the reference's lifetime."

Also note that type invariants should be justified with an // INVARIANT comment
when the type is constructed, or re-created from a raw pointer.

> +/// - Callback contexts are borrowed only for the corresponding callback and 
> thread; only
> +///   [`Normal`] references can be reference-counted.

I'd remove this one.

I'd also keep the documentation private with #[doc(hidden)] as the type is not
supposed to be used outside of the Rust core code.

> +#[repr(C)]
> +pub struct DeviceBase<Raw, R, O, T, Ctx: DeviceContext = Normal> {
> +    raw: Opaque<Raw>,
> +    data: CallbackData<R, O>,
> +    _context: PhantomData<(T, Ctx, NotThreadSafe)>,
> +}

If we declare CallbackData as

        struct CallbackData<T: Operations> {
            reg_data: UnsafeCell<Option<NonNull<T::RegistrationData<'static>>>>,
            open_data: UnsafeCell<Option<NonNull<T::OpenData<'static, 
'static>>>>,
        }

we can get rid of R, O, right? Then DeviceBase could be simplified to:

        pub struct DeviceBase<Raw, T: Operations, Ctx: DeviceContext = Normal> {
            raw: Opaque<Raw>,
            data: CallbackData<T>,
            _context: PhantomData<(T, Ctx, NotThreadSafe)>,
        }

I think this also needs a change in the subsequent patch, so
vfio::pci::Operations extend vfio::Operations.

        pub trait Operations: super::Operations

> +/// A VFIO device, wrapping `struct vfio_device`.
> +pub type Device<T, Ctx = Normal> = DeviceBase<
> +    bindings::vfio_device,
> +    <T as Operations>::RegistrationData<'static>,
> +    <T as Operations>::OpenData<'static, 'static>,
> +    T,
> +    Ctx,
> +>;

...and this simplifies to:

        pub type Device<T, Ctx = Normal> = DeviceBase<bindings::vfio_device, T, 
Ctx>;

> +#[expect(dead_code)]
> +impl<Raw: RawDevice, R, O, T, Ctx: DeviceContext> DeviceBase<Raw, R, O, T, 
> Ctx> {
> +    /// Initializes the Rust fields of a newly allocated device.
> +    ///
> +    /// # Safety
> +    ///
> +    /// `this` must point to an allocation with the size and alignment of 
> `Self`, whose `raw`
> +    /// has been initialized. 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.
> +        unsafe {
> +            (&raw mut (*this).data).write(CallbackData {
> +                reg_data: UnsafeCell::new(None),
> +                open_data: UnsafeCell::new(core::ptr::null_mut()),
> +            });
> +            (&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.
> +    unsafe fn from_raw_vfio<'a>(vdev: *mut bindings::vfio_device) -> &'a 
> Self {
> +        // SAFETY: `Raw` begins with its `vfio_device` and is the first 
> field of `Self`. The
> +        // caller guarantees validity and the context.
> +        unsafe { &*vdev.cast() }

If we rely on this layout guarantee here, there's no point to have the RawDevice
trait dealing with the layout.

Either we add from_raw_vfio() to RawDevice, or we just remove RawDevice and make
the layout guarantee a type invariant.

Either is fine with me, but maybe the RawDevice trait is a bit overengineered
and a type invaraint is sufficient.

> +    }
> +
> +    fn as_raw(&self) -> *mut Raw {
> +        self.raw.get()
> +    }
> +
> +    fn as_raw_vfio(&self) -> *mut bindings::vfio_device {
> +        // SAFETY: By the type invariants, `raw` is initialized and alive.
> +        unsafe { Raw::raw_vfio_device(self.as_raw()) }
> +    }
> +}
> +
> +#[expect(dead_code)]
> +impl<Raw: RawDevice, R, O, T> DeviceBase<Raw, R, O, T> {
> +    /// Publishes the registration data passed to callbacks.
> +    ///
> +    /// Returns [`EBUSY`] if registration data has been published before, so 
> that a device can
> +    /// be registered at most once.
> +    ///
> +    /// # Safety
> +    ///
> +    /// The caller must serialize calls for this device. `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(&self, data: NonNull<R>) -> Result {

I'd use:

        data: NonNull<T::RegistrationData<'a>>,

and erase the lifetime internally.

> +        // SAFETY: The caller serializes publication, and callbacks only 
> read the slot.
> +        if unsafe { (*self.data.reg_data.get()).is_some() } {
> +            return Err(EBUSY);
> +        }
> +        // SAFETY: The slot is unpublished, so the device has not been 
> registered and no
> +        // callback can read the slot.
> +        // INVARIANT: The slot is written once; the caller keeps `data` 
> valid.
> +        unsafe { *self.data.reg_data.get() = Some(data) };
> +        Ok(())
> +    }
> +
> +    /// 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 { core::mem::replace(&mut *self.data.open_data.get(), 
> core::ptr::null_mut()) };

With the type changed to Option<NonNull>> this becomes:

        let raw = unsafe { &mut *self.data.open_data.get() }
            .take()
            .expect("VFIO OpenData is expected to be populated.");

> +        // SAFETY: The allocation came from `KBox::into_raw()` and is 
> destroyed without moving
> +        // it. Lifetimes do not affect its layout.
> +        unsafe { drop(KBox::from_raw(raw)) };
> +    }
> +}
> +
> +#[expect(dead_code)]
> +impl<Raw: RawDevice, R, O, T> DeviceBase<Raw, R, O, 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.
> +    /// - `OD` must be `O`, except for lifetimes.
> +    /// - `R` names the registration data with the placeholder lifetime 
> `'static`, and the
> +    ///   caller chooses the lifetimes of `OD`; 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, OD, I>(&'a self, init: impl FnOnce(&'a R) -> I) -> 
> Result
> +    where
> +        I: PinInit<OD, Error>,
> +    {

I think this can just use the associated types of T:

        unsafe fn open<'a, 'data: 'a, I>(
            &'a self,
            init: impl FnOnce(&'a T::RegistrationData<'data>) -> I,
        ) -> Result
        where
            I: PinInit<T::OpenData<'a, 'data>, 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()).unwrap_unchecked().as_ref() };
> +
> +        // Allocate before calling the driver so allocation failure cannot 
> follow open.
> +        let data = KBox::<OD>::new_uninit(GFP_KERNEL)?;
> +        let data = data.write_pin_init(init(reg_data))?;
> +
> +        // SAFETY: Only the owning pointer moves; `close()` drops the 
> allocation in place.
> +        let raw = KBox::into_raw(unsafe { Pin::into_inner_unchecked(data) });

I think this can just be

        let data = KBox::pin_init(init(reg_data), GFP_KERNEL)?;
        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.
> +        // The caller guarantees that `OD` and `O` only differ in lifetimes, 
> which do not
> +        // affect the layout.
> +        // INVARIANT: The allocation is pinned and owned by the slot until 
> `close()`.
> +        unsafe { *self.data.open_data.get() = raw.cast::<O>() };
> +        Ok(())
> +    }
> +}
> +
> +#[expect(dead_code)]
> +impl<Raw: RawDevice, R, O, T, Ctx: IoContext> DeviceBase<Raw, R, O, T, Ctx> {
> +    /// Returns the registration data and the open data, for an I/O callback.
> +    ///
> +    /// # Safety
> +    ///
> +    /// `R` and `O` name the data 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) -> (&R, Pin<&O>) {

Same here, can we use the associated types of T?

> +        // 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.
> +        unsafe {
> +            let reg_data = (*self.data.reg_data.get()).unwrap_unchecked();

I'd use expect() instead.

> +            let open_data = *self.data.open_data.get();
> +            (reg_data.as_ref(), Pin::new_unchecked(&*open_data))
> +        }

Multiple unsafe operations should have their own unsafe block and justification.

Reply via email to