From mboxrd@z Thu Jan 1 00:00:00 1970 Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.remote-ip=100.103.45.18 ARC-Seal: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; cv=none; t=1796247345; b=bjaXogQmKtk80NeKbS6UWM2dS4wnACw9zISOm+wdaF14wD9PFHYGAxzgbW2ztyRG1swg 8nVRgiiNiDm6n71P3YsyCtPYDNpfFSlyD3yu1/qKfOsdMQRPNzqCjf868f9wMmm+MyZfF bFozUU8bPmM3YiJHsjpX/Sot6H3ZerRB3IUuDyPbndkkqT2s4vLDYiCO/gwzHYP/4Lbf3 vVaf/jHwQnORoQyP+/n8EBaE/Io74tAs/RWDJ1bVaaglrAm9BukVOpZPp+rFTtsxSo/Ca lYoC3eFrd+nF+4zCZ1nrMfbq3MVwBH4OLdXxGz4m+TzWMbTN6mboYT2mabmps1iqbqg== ARC-Message-Signature: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; c=relaxed/relaxed; t=1796247345; h=Received:DKIM-Signature:Mime-Version:Content-Transfer-Encoding: Content-Type:Date:Message-Id:Subject:Cc:To:From:References: In-Reply-To; bh=DlEvsgcKqnHykQ1twZEs94JHYHv88w0guh1kIYGwWsM=; b=vHnYzX6KJT5dvkWqfZhkpHMm/x93+FpRcMyIQY5LWKvtX824T9+BzquI18UuxDe2J+UV AbgWa+hNY1i5iam+U7YVUD81rNE3NR26aAfN/4aFiNU1c5+5geVoSx6q13zM4Obv1PLSy R4aPLfjOcMBDGr1wA5ZS4PNOInSXUMsBrO3WcHo+15whpapzq2s5kSULF5ypTLN04oejE QZ5BmhOkDjW8XKyXITkSwjQDEKGJd0WwvPERt3PWA45/j6eAA1NI1Wxj1Rd3y+lm0a9nC 644tUIpjpjICcwF2+YQD1ZAFiHBOHzWGqeraQsKVqV1ljUoY1FPKke1wokeWyFRVlUA== ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass header.d=kernel.org header.i=@kernel.org header.a=rsa-sha256 header.s=k20260515 header.b=ghGWh67E; arc=none smtp.remote-ip=100.103.45.18 Received: from smtp.kernel.org (quasi.space.kernel.org [100.103.45.18]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature ECDSA (prime256v1)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id B6CFD606A322; Wed, 2 Dec 2026 21:35:45 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.a=rsa-sha256 header.s=k20260515 header.b=ghGWh67E Received: by smtp.kernel.org (Postfix) with ESMTPSA id 937031F000C1; Wed, 2 Dec 2026 21:35:36 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=kernel.org; s=k20260515; t=1796247345; bh=DlEvsgcKqnHykQ1twZEs94JHYHv88w0guh1kIYGwWsM=; h=Date:Subject:Cc:To:From:References:In-Reply-To; b=ghGWh67Eopp7Exehz8UEog6Uia06/YMc/gFHJV0ahq0tdAK0YoK1HndWYwQj8ftx8 V3Z4XF2dt90h7P0mOuwMdNrrE1jcU0t2R/cqmwOV5FRgqhKnRjrRm61rWZ8kMFHYK7 skXcAH48naoSwwhiWiNr+KWhPOsKW8/73bVnQ4NGyBfYNNHBKMaOFvV+6D5C8QCACH tr2MdYRXo5KR4H9wBl/zvmOCAHyQShAXEjjBs63RzcLvOIUVK4nlpJiXcNqL4GfyyW hE8bwyj69c4xO7Rn0lp+U8HhKNrnSAkYZHCUk/o3JSBqN7lH/aiwpVFj+prT0L1XET bpeIZR+9ogYTA== X-Mailing-List: rust-for-linux@vger.kernel.org List-Id: List-Post: List-Help: List-Subscribe: List-Unsubscribe: List-Owner: Precedence: list Mime-Version: 1.0 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset=UTF-8 Date: Wed, 02 Dec 2026 22:35:35 +0100 Message-Id: Subject: Re: [PATCH v4 3/5] rust: vfio: add PCI variant driver abstractions Cc: "Simon Song" , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , "Liam R. Howlett" , , "Lorenzo Stoakes" To: "Gary Guo" From: "Danilo Krummrich" References: <20261127224928.1511382-1-xinmengs@nvidia.com> <20261127224928.1511382-4-xinmengs@nvidia.com> In-Reply-To: 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, >> + _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 correctl= y. 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_c= ore_init_dev()`. >> +/// - The callback data follows the VFIO registration and first-open/la= st-close lifetimes. >> +/// Open data is destroyed before PCI core close, and registration da= ta is >> +/// released after PCI core unregistration has drained callbacks. >> +pub type Device =3D DeviceBase; >> + >> +static_assert!(core::mem::offset_of!(bindings::vfio_pci_core_device, vd= ev) =3D=3D 0); >> + >> +impl Device { >> + /// Allocate a VFIO PCI device for subsequent registration. >> + pub fn new(pdev: &pci::Device>) -> Result> { >> + let size =3D Kmalloc::aligned_layout(Layout::new::()).siz= e(); >> + >> + // SAFETY: The bound PCI device and static ops are valid. The a= llocation >> + // includes the full Rust wrapper with kmalloc-compatible size = and alignment. >> + let raw =3D 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 =3D NonNull::new(raw.cast::()).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` be= gins 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 alloca= tion yet. >> + unsafe { (*this.as_ref().as_raw()).pci_ops =3D &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 cor= e functions or wrappers. >> +macro_rules! build_ops { >> + ($T:ty) =3D> { >> + 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 cor= e > 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. I= f a driver wants to forward a callback to the core callback it does that explic= itly. > Perhaps it's worth changing the C side to switch the meaning, but regardl= ess we > should consider what's actually the desired behaviour when people use Rus= t > abstraction's trait "provided methods". I think returning EINVAL for these missing callbacks is intentional, i.e. t= he 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_io= as), >> + #[cfg(not(CONFIG_IOMMUFD))] >> + attach_ioas: None, >> + #[cfg(CONFIG_IOMMUFD)] >> + detach_ioas: Some(bindings::vfio_iommufd_physical_detach_io= as), >> + #[cfg(not(CONFIG_IOMMUFD))] >> + detach_ioas: None, >> + #[cfg(CONFIG_IOMMUFD)] >> + pasid_attach_ioas: Some(bindings::vfio_iommufd_physical_pas= id_attach_ioas), >> + #[cfg(not(CONFIG_IOMMUFD))] >> + pasid_attach_ioas: None, >> + #[cfg(CONFIG_IOMMUFD)] >> + pasid_detach_ioas: Some(bindings::vfio_iommufd_physical_pas= id_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, tyin= g >> +/// resource lifetimes to the PCI binding scope `'a`. The device is reg= istered >> +/// on construction and unregistered when the `Registration` is dropped= . >> +pub struct Registration<'a, T: Operations> { >> + dev: ARef>, >> + reg_data: Pin>>, >> +} >> + >> +impl Device { >> + const OPS: bindings::vfio_device_ops =3D build_ops!(T); >> + >> + const PCI_OPS: bindings::vfio_pci_device_ops =3D bindings::vfio_pci= _device_ops { >> + #[cfg(CONFIG_VFIO_PCI_DMABUF)] >> + get_dmabuf_phys: if T::HAS_DMABUF_LEN { >> + Some(get_dmabuf_phys_cb::) >> + } 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 callba= ck data. >> + /// >> + /// `dev` must have been allocated for `pdev`, and can be registere= d only once. `D` is the >> + /// PCI driver bound to `pdev`. >> + /// >> + /// # Safety >> + /// >> + /// The returned `Registration` must be stored in the bus device pr= ivate data of `D`, the >> + /// driver bound to `pdev`, and must not be leaked: it has to be dr= opped while that driver >> + /// is being unbound from `pdev`, or when its probe fails. >> + pub unsafe fn new( >> + pdev: &'a pci::Device>, >> + dev: &Device, >> + reg_data: impl PinInit, Error>, >> + ) -> Result { >> + 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 configurati= on" >> + ); > > D has no association with `pci::Device` at all so it can be completely ar= bitrary > 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 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 { } } =20 +impl Device { + /// 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 unchange= d. + let driver =3D unsafe { (*self.as_ref().as_raw()).driver }; + + // SAFETY: The driver of a PCI device is embedded in a `struct pci= _driver`. + let driver =3D 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 unchange= d. + let driver =3D unsafe { (*self.as_ref().as_raw()).driver }; + + // SAFETY: The driver of a PCI device is embedded in a `struct pci= _driver`. + let driver =3D unsafe { container_of!(driver, bindings::pci_driver= , driver) }; + + // SAFETY: `driver` is valid and `sriov_configure` is immutable wh= ile registered. + unsafe { (*driver).sriov_configure }.is_some() + } +} + impl<'a> Device> { /// Returns the total number of VFs, or [`None`] if SR-IOV is not avai= lable. #[inline] We could also have a new type pci::BoundDriver with Opaque having the corresponding methods, but that seems overkill for now.