Linux PCI subsystem development
 help / color / mirror / Atom feed
From: "Danilo Krummrich" <dakr@kernel.org>
To: "Gary Guo" <gary@garyguo.net>
Cc: "Simon Song" <xinmengs@nvidia.com>, <acourbot@nvidia.com>,
	<kvm@vger.kernel.org>, <rust-for-linux@vger.kernel.org>,
	<nova-gpu@lists.linux.dev>, <linux-pci@vger.kernel.org>,
	<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>,
	<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>, <zhiw@nvidia.com>, <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>, "Liam R. Howlett" <liam@infradead.org>,
	<linux-mm@kvack.org>, "Lorenzo Stoakes" <ljs@kernel.org>
Subject: Re: [PATCH v4 3/5] rust: vfio: add PCI variant driver abstractions
Date: Wed, 02 Dec 2026 22:35:35 +0100	[thread overview]
Message-ID: <DNAKJDWJ4JHK.JRY1IDO00NSZ@kernel.org> (raw)
In-Reply-To: <DNADTLFKJ1RK.3926JZRGLFCG3@garyguo.net>

On Wed Dec 2, 2026 at 5:19 PM CET, Gary Guo wrote:
> On Fri Nov 27, 2026 at 10:49 PM GMT, Simon Song wrote:
>> +    /// 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<'reg>(
>> +        _dev: &Device<Self, Ioctl>,
>> +        _reg_data: &Self::RegistrationData<'reg>,
>> +        _open_data: Pin<&Self::OpenData<'_, 'reg>>,
>
> If the API is from-scratch Rust design I'd actually make this two traits, with
> these ioctls implemented on `OpenData` as a trait, and the `open_device` and
> other non-open-data methods only on `RegistrationData`.

I think we'd still need an Operations trait carrying the type families,
otherwise we'd probably have to fall back to ForLt if I understand correctly.

Either way, I feel like that'd be an additional complication with not much
benefit.

> That said, this isn't too bad either so I guess it's okay.

Yeah, I think it's pretty straightforward as is.

>> +/// 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 of `DeviceBase`:
>> +///
>> +/// - 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 subsequent registration.
>> +    pub fn new(pdev: &pci::Device<device::Core<'_>>) -> Result<ARef<Self>> {
>> +        let size = Kmalloc::aligned_layout(Layout::new::<Self>()).size();
>> +
>> +        // SAFETY: The bound PCI device and static ops are valid. The allocation
>> +        // includes the full Rust wrapper with kmalloc-compatible size and alignment.
>> +        let raw = from_err_ptr(unsafe {
>> +            bindings::_vfio_alloc_device(size, pdev.as_ref().as_raw(), &Self::OPS)
>> +        })?;
>
> This doesn't make sure alignment is correct.

It looks correct to me, what do you think is incorrect?

(I think the justification could deal with the fact that _vfio_alloc_device()
uses kvzalloc(), but the code should be correct.)

>> +        let this = NonNull::new(raw.cast::<Self>()).ok_or(ENOMEM)?;
>> +
>> +        // SAFETY: `vfio_pci_core_init_dev()` initialized the C device in this new allocation,
>> +        // which nothing else can access yet. `vfio_pci_core_device` begins with its
>> +        // `vfio_device`, as asserted above.
>> +        // INVARIANT: The layout and the initialized `raw` are as just described.
>> +        unsafe { Self::init(this.as_ptr()) };
>> +
>> +        // SAFETY: No registration or callbacks can observe this allocation yet.
>> +        unsafe { (*this.as_ref().as_raw()).pci_ops = &Self::PCI_OPS };
>> +
>> +        // SAFETY: `this` owns the initial VFIO device reference.
>> +        Ok(unsafe { ARef::from_raw(this) })
>> +    }
>> +}
>>
>> [snip]
>>
>> +
>> +/// Build the `vfio_device_ops` vtable for a variant driver `T`.
>> +///
>> +/// The open callback and the implemented I/O callbacks dispatch to `T`; unimplemented I/O
>> +/// callbacks are not installed. Other installed callbacks use VFIO core functions or wrappers.
>> +macro_rules! build_ops {
>> +    ($T:ty) => {
>> +        bindings::vfio_device_ops {
>> +            #[allow(clippy::disallowed_methods)]
>> +            name: <$T>::NAME.as_ptr().cast_mut().cast(),
>> +            init: Some(bindings::vfio_pci_core_init_dev),
>> +            release: Some(bindings::vfio_pci_core_release_dev),
>> +            open_device: Some(open_device_cb::<$T>),
>> +            close_device: Some(close_device_cb::<$T>),
>> +            ioctl: if <$T>::HAS_IOCTL {
>> +                Some(ioctl_cb::<$T>)
>> +            } else {
>> +                None
>> +            },
>
> None here (and below) means returning EINVAL instead of forwarding to core
> callbacks. Is this what's whated? Most existing vfio pci variant drivers forward
> un-implemented callbacks.

I suggested this in the last version, as it is consistent with the C API. If a
driver wants to forward a callback to the core callback it does that explicitly.

> Perhaps it's worth changing the C side to switch the meaning, but regardless we
> should consider what's actually the desired behaviour when people use Rust
> abstraction's trait "provided methods".

I think returning EINVAL for these missing callbacks is intentional, i.e. the
core returning EINVAL is valid behavior.

>
>> +            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> {
>> +    /// Register a previously allocated VFIO PCI device with its callback data.
>> +    ///
>> +    /// `dev` must have been allocated for `pdev`, and can be registered only once. `D` is the
>> +    /// PCI driver bound to `pdev`.
>> +    ///
>> +    /// # Safety
>> +    ///
>> +    /// The returned `Registration` must be stored in the bus device private data of `D`, 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<D: pci::Driver>(
>> +        pdev: &'a pci::Device<device::Core<'_>>,
>> +        dev: &Device<T>,
>> +        reg_data: impl PinInit<T::RegistrationData<'a>, Error>,
>> +    ) -> Result<Self> {
>> +        const_assert!(
>> +            D::DRIVER_MANAGED_DMA.is_some(),
>> +            "VFIO drivers must manage DMA ownership"
>> +        );
>> +        const_assert!(
>> +            !D::HAS_SRIOV_ENABLE && !D::HAS_SRIOV_DISABLE,
>> +            "VFIO PCI variant drivers do not support SR-IOV configuration"
>> +        );
>
> D has no association with `pci::Device` at all so it can be completely arbitrary
> and the checks here don't really serve any soundness purpose.

The unsafe contract currently requires D to be the bound driver, but we can
avoid relying on that by checking the actual driver. I suggest adding the
following methods to pci::Device<Bound> instead.

diff --git a/rust/kernel/pci.rs b/rust/kernel/pci.rs
index 03b210a21cef..444a791ee534 100644
--- a/rust/kernel/pci.rs
+++ b/rust/kernel/pci.rs
@@ -795,6 +795,34 @@ pub fn pci_class(&self) -> Class {
     }
 }
 
+impl Device<device::Bound> {
+    /// 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 { 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 { 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>> {
     /// Returns the total number of VFs, or [`None`] if SR-IOV is not available.
     #[inline]

We could also have a new type pci::BoundDriver with Opaque<bindings::pci_driver>
having the corresponding methods, but that seems overkill for now.

  reply	other threads:[~2026-12-02 21:35 UTC|newest]

Thread overview: 17+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
2026-11-27 22:49 [PATCH v4 0/5] Rust VFIO PCI support and NVIDIA vGPU driver Simon Song
2026-11-27 22:49 ` [PATCH v4 1/5] rust: vfio: add common VFIO device handling Simon Song
2026-12-02 15:58   ` Gary Guo
2026-12-02 17:55     ` Danilo Krummrich
2026-12-02 18:43       ` Gary Guo
2026-12-02 19:43         ` Danilo Krummrich
2026-12-02 19:20     ` Danilo Krummrich
2026-11-27 22:49 ` [PATCH v4 2/5] rust: mm: add VmaRef::size() and VmaRef::pgoff() Simon Song
2026-12-02 22:22   ` Alice Ryhl
2026-11-27 22:49 ` [PATCH v4 3/5] rust: vfio: add PCI variant driver abstractions Simon Song
2026-12-02 16:19   ` Gary Guo
2026-12-02 21:35     ` Danilo Krummrich [this message]
2026-11-27 22:49 ` [PATCH v4 4/5] gpu: nova-core: publish typed SR-IOV PF APIs Simon Song
2026-11-27 22:49 ` [PATCH v4 5/5] vfio/nova-vgpu: add the Rust VFIO variant driver Simon Song
2026-12-02 14:01 ` [PATCH v4 0/5] Rust VFIO PCI support and NVIDIA vGPU driver Gary Guo
2026-12-02 14:14   ` Gary Guo
2026-12-02 19:52   ` Simon Song

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=DNAKJDWJ4JHK.JRY1IDO00NSZ@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=liam@infradead.org \
    --cc=linux-kernel@vger.kernel.org \
    --cc=linux-mm@kvack.org \
    --cc=linux-pci@vger.kernel.org \
    --cc=ljs@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