On 12/2/2026 4:35 PM, Danilo Krummrich wrote:
...
>> 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.
I will add this in next patch, then dropped D from Registration::new and check
the bound driver at runtime:
- pub unsafe fn new<D: pci::Driver>(
+ pub unsafe fn new(
pdev: &'a pci::Device<device::Core<'_>>,
reg_data: impl PinInit<T::RegistrationData<'a>, Error>,
) -> Result<Self> {
- const_assert!(D::DRIVER_MANAGED_DMA.is_some(), ...);
- const_assert!(!D::HAS_SRIOV_ENABLE && !D::HAS_SRIOV_DISABLE, ...);
+ if !pdev.driver_has_managed_dma() || pdev.driver_has_sriov_configure()
{
+ return Err(EINVAL);
+ }