From: "Danilo Krummrich" <dakr@kernel.org>
To: "Simon Song" <xinmengs@nvidia.com>
Cc: <acourbot@nvidia.com>, <kvm@vger.kernel.org>,
<rust-for-linux@vger.kernel.org>, <nova-gpu@lists.linux.dev>,
<linux-pci@vger.kernel.org>, "Zhi Wang" <zhiw@nvidia.com>,
<alex@shazbot.org>, <jgg@nvidia.com>, <yishaih@nvidia.com>,
<skolothumtho@nvidia.com>, <kevin.tian@intel.com>,
<airlied@gmail.com>, <simona@ffwll.ch>, <ojeda@kernel.org>,
<alex.gaynor@gmail.com>, <boqun.feng@gmail.com>,
<gary@garyguo.net>, <bjorn3_gh@protonmail.com>,
<lossin@kernel.org>, <a.hindborg@kernel.org>,
<aliceryhl@google.com>, <tmgross@umich.edu>,
<jhubbard@nvidia.com>, <ecourtney@nvidia.com>, <cjia@nvidia.com>,
<smitra@nvidia.com>, <kjaju@nvidia.com>, <alkumar@nvidia.com>,
<ankita@nvidia.com>, <aniketa@nvidia.com>, <kwankhede@nvidia.com>,
<targupta@nvidia.com>, <linux-kernel@vger.kernel.org>,
<zhiwang@kernel.org>, <boqun@kernel.org>,
<daniel.almeida@collabora.com>, <tamird@kernel.org>,
<work@onurozkan.dev>, <jgg@ziepe.ca>, <bhelgaas@google.com>,
<kwilczynski@kernel.org>, <dri-devel@lists.freedesktop.org>,
<peter@colberg.org>
Subject: Re: [PATCH v3 6/9] rust: vfio: add common VFIO device handling
Date: Wed, 25 Nov 2026 18:57:40 +0100 [thread overview]
Message-ID: <DN4HIQ5VPWEI.FFVR53SNX54Y@kernel.org> (raw)
In-Reply-To: <20261119215046.2892839-7-xinmengs@nvidia.com>
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.
next prev parent reply other threads:[~2026-11-25 17:57 UTC|newest]
Thread overview: 13+ messages / expand[flat|nested] mbox.gz Atom feed top
2026-11-19 21:50 [PATCH v3 0/9] Rust VFIO PCI support and NVIDIA vGPU driver Simon Song
2026-11-19 21:50 ` [PATCH v3 1/9] rust: pci: add VFIO override device IDs Simon Song
2026-11-19 21:50 ` [PATCH v3 2/9] rust: pci: expose the VF index within its PF Simon Song
2026-11-19 21:50 ` [PATCH v3 3/9] rust: pci: allow drivers to manage DMA ownership Simon Song
2026-11-19 21:50 ` [PATCH v3 4/9] rust: pci: add reset callbacks Simon Song
2026-11-19 21:50 ` [PATCH v3 5/9] rust: pci: add an error_detected callback Simon Song
2026-11-19 21:50 ` [PATCH v3 6/9] rust: vfio: add common VFIO device handling Simon Song
2026-11-25 17:57 ` Danilo Krummrich [this message]
2026-11-19 21:50 ` [PATCH v3 7/9] rust: vfio: add PCI variant driver abstractions Simon Song
2026-11-19 21:50 ` [PATCH v3 8/9] gpu: nova-core: publish typed SR-IOV PF APIs Simon Song
2026-11-19 21:50 ` [PATCH v3 9/9] vfio/nova-vgpu: add the Rust VFIO variant driver Simon Song
2026-11-25 3:19 ` Alex Williamson
2026-11-24 22:21 ` (subset) [PATCH v3 0/9] Rust VFIO PCI support and NVIDIA vGPU driver Danilo Krummrich
Reply instructions:
You may reply publicly to this message via plain-text email
using any one of the following methods:
* Save the following mbox file, import it into your mail client,
and reply-to-all from there: mbox
Avoid top-posting and favor interleaved quoting:
https://en.wikipedia.org/wiki/Posting_style#Interleaved_style
* Reply using the --to, --cc, and --in-reply-to
switches of git-send-email(1):
git send-email \
--in-reply-to=DN4HIQ5VPWEI.FFVR53SNX54Y@kernel.org \
--to=dakr@kernel.org \
--cc=a.hindborg@kernel.org \
--cc=acourbot@nvidia.com \
--cc=airlied@gmail.com \
--cc=alex.gaynor@gmail.com \
--cc=alex@shazbot.org \
--cc=aliceryhl@google.com \
--cc=alkumar@nvidia.com \
--cc=aniketa@nvidia.com \
--cc=ankita@nvidia.com \
--cc=bhelgaas@google.com \
--cc=bjorn3_gh@protonmail.com \
--cc=boqun.feng@gmail.com \
--cc=boqun@kernel.org \
--cc=cjia@nvidia.com \
--cc=daniel.almeida@collabora.com \
--cc=dri-devel@lists.freedesktop.org \
--cc=ecourtney@nvidia.com \
--cc=gary@garyguo.net \
--cc=jgg@nvidia.com \
--cc=jgg@ziepe.ca \
--cc=jhubbard@nvidia.com \
--cc=kevin.tian@intel.com \
--cc=kjaju@nvidia.com \
--cc=kvm@vger.kernel.org \
--cc=kwankhede@nvidia.com \
--cc=kwilczynski@kernel.org \
--cc=linux-kernel@vger.kernel.org \
--cc=linux-pci@vger.kernel.org \
--cc=lossin@kernel.org \
--cc=nova-gpu@lists.linux.dev \
--cc=ojeda@kernel.org \
--cc=peter@colberg.org \
--cc=rust-for-linux@vger.kernel.org \
--cc=simona@ffwll.ch \
--cc=skolothumtho@nvidia.com \
--cc=smitra@nvidia.com \
--cc=tamird@kernel.org \
--cc=targupta@nvidia.com \
--cc=tmgross@umich.edu \
--cc=work@onurozkan.dev \
--cc=xinmengs@nvidia.com \
--cc=yishaih@nvidia.com \
--cc=zhiw@nvidia.com \
--cc=zhiwang@kernel.org \
/path/to/YOUR_REPLY
https://kernel.org/pub/software/scm/git/docs/git-send-email.html
* If your mail client supports setting the In-Reply-To header
via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line
before the message body.
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox
all inboxes | Powered by JetHome®