Thank you for your contribution! Sashiko AI review found 2 potential
issues to consider:
- [Low] rust: dma: missing INVARIANT comments in Setup::new() and
  Handle::new_for_test()
- [Low] rust: dma: missing #[inline] on Setup and Handle methods in
  kernel abstraction
--

commit 24aab1a18402fe872441d89737705384f9f15bd1
Author: Matteo Kloiber <[email protected]>

rust: dma: require device configuration before DMA

This commit replaces the dma::Device trait with a dma::Setup token passed
via bus InitTokens, requiring drivers to configure DMA parameters and
obtain a dma::Handle before performing DMA allocations, scatterlist
mappings, or IOMMU page-table creation.

Link: https://lore.kernel.org/[email protected]
Link: https://lore.kernel.org/[email protected]

> diff --git a/rust/kernel/dma.rs b/rust/kernel/dma.rs
> index 580e1c3427bc5..03f48bd1f9406 100644
> --- a/rust/kernel/dma.rs
> +++ b/rust/kernel/dma.rs

[ ... ]

> @@ -48,83 +48,124 @@
> +/// Token for configuring a device's DMA parameters.
> +///
> +/// The bus passes it to the driver's `probe()` callback. The driver can 
> access the device, e.g. to
> +/// read its capabilities, before calling [`Setup::configure`], which 
> consumes the token. Drivers
> +/// that don't use DMA can drop it.
> +///
> +/// # Invariants
> +///
> +/// - The bus has initialized the device's DMA parameters.
> +/// - There is only one `Setup` per driver binding, and no [`Handle`] has 
> been created for it yet.
> +/// - No DMA allocation or mapping for this device can run concurrently with
> +///   [`Setup::configure`], and nothing else changes the DMA parameters 
> while the device is bound.
> +pub struct Setup<'bound> {
> +    dev: &'bound device::Device<Bound>,
> +}
> +
> +impl<'bound> Setup<'bound> {
> +    /// Creates the setup token passed to a driver's probe callback.
>      ///
>      /// # Safety
>      ///
> -    /// This method must not be called concurrently with any DMA allocation 
> or mapping primitives,
> -    /// such as [`Coherent::zeroed`].
> -    unsafe fn dma_set_mask(&self, mask: DmaMask) -> Result {
> -        // SAFETY:
> -        // - By the type invariant of `device::Device`, 
> `self.as_ref().as_raw()` is valid.
> -        // - The safety requirement of this function guarantees that there 
> are no concurrent calls
> -        //   to DMA allocation and mapping primitives using this mask.
> -        to_result(unsafe { bindings::dma_set_mask(self.as_ref().as_raw(), 
> mask.value()) })
> +    /// The caller must ensure the invariants of [`Self`], including 
> uniqueness of the token.
> +    pub(crate) unsafe fn new(dev: &'bound device::Device<Bound>) -> Self {
> +        Self { dev }
>      }
>
> -    /// Set up the device's DMA coherent addressing capabilities.
> -    ///
> -    /// This method is usually called once from `probe()` as soon as the 
> device capabilities are
> -    /// known.
> -    ///
> -    /// # Safety
> +    /// Applies `params` and returns a [`Handle`] for DMA allocations and 
> mappings.
>      ///
> -    /// This method must not be called concurrently with any DMA allocation 
> or mapping primitives,
> -    /// such as [`Coherent::zeroed`].
> -    unsafe fn dma_set_coherent_mask(&self, mask: DmaMask) -> Result {
> -        // SAFETY:
> -        // - By the type invariant of `device::Device`, 
> `self.as_ref().as_raw()` is valid.
> -        // - The safety requirement of this function guarantees that there 
> are no concurrent calls
> -        //   to DMA allocation and mapping primitives using this mask.
> -        to_result(unsafe { 
> bindings::dma_set_coherent_mask(self.as_ref().as_raw(), mask.value()) })
> +    /// If a setter fails, its error is returned and parameters applied 
> before it are not restored.
> +    pub fn configure(self, params: Params) -> Result<Handle<'bound>> {
> +        let dev = self.dev.as_raw();
> +
> +        if let Some(mask) = params.streaming_mask {
> +            // SAFETY: `dev` is valid. The `Setup` invariants exclude 
> concurrent DMA operations
> +            // and other parameter setters, and consuming the token prevents 
> reconfiguration.
> +            to_result(unsafe { bindings::dma_set_mask(dev, mask.value()) })?;
> +        }
> +        if let Some(mask) = params.coherent_mask {
> +            // SAFETY: `dev` is valid. The `Setup` invariants exclude 
> concurrent DMA operations
> +            // and other parameter setters, and consuming the token prevents 
> reconfiguration.
> +            to_result(unsafe { bindings::dma_set_coherent_mask(dev, 
> mask.value()) })?;
> +        }
> +        if let Some(size) = params.max_seg_size {
> +            // SAFETY: `dev` is valid and its DMA parameters are 
> initialized. The `Setup`
> +            // invariants exclude concurrent DMA operations and other 
> parameter setters,
> +            // and consuming the token prevents reconfiguration.
> +            unsafe { bindings::dma_set_max_seg_size(dev, size.get()) };
> +        }
> +
> +        // INVARIANT: All requested setters succeeded. The `Setup` 
> invariants prevent further
> +        // changes while the device is bound to the driver.
> +        Ok(Handle { dev: self.dev })
> +    }
> +}
> +
> +/// Handle for DMA allocations and mappings on a configured device.
> +///
> +/// Returned by [`Setup::configure`]. It can be copied freely, but cannot 
> change the DMA parameters.
> +///
> +/// # Invariants
> +///
> +/// The requested DMA parameters have been applied and do not change during 
> `'bound`.
> +#[derive(Clone, Copy)]
> +pub struct Handle<'bound> {
> +    dev: &'bound device::Device<Bound>,
> +}
> +
> +impl<'bound> Handle<'bound> {
> +    /// Returns the device associated with this DMA handle.
> +    pub fn device(self) -> &'bound device::Device<Bound> {
> +        self.dev
>      }
>
> -    /// Set up the device's DMA addressing capabilities.
> -    ///
> -    /// This is a combination of [`Device::dma_set_mask`] and 
> [`Device::dma_set_coherent_mask`].
> -    ///
> -    /// This method is usually called once from `probe()` as soon as the 
> device capabilities are
> -    /// known.
> -    ///
> -    /// # Safety
> -    ///
> -    /// This method must not be called concurrently with any DMA allocation 
> or mapping primitives,
> -    /// such as [`Coherent::zeroed`].
> -    unsafe fn dma_set_mask_and_coherent(&self, mask: DmaMask) -> Result {
> -        // SAFETY:
> -        // - By the type invariant of `device::Device`, 
> `self.as_ref().as_raw()` is valid.
> -        // - The safety requirement of this function guarantees that there 
> are no concurrent calls
> -        //   to DMA allocation and mapping primitives using this mask.
> -        to_result(unsafe {
> -            bindings::dma_set_mask_and_coherent(self.as_ref().as_raw(), 
> mask.value())
> -        })
> +    pub(crate) fn as_raw(self) -> *mut bindings::device {
> +        self.dev.as_raw()
>      }
>
> -    /// Set the maximum size of a single DMA segment the device may request.
> +    /// Creates a handle for `dev` without calling [`Setup::configure`].
>      ///
> -    /// This method is usually called once from `probe()` as soon as the 
> device capabilities are
> -    /// known.
> -    ///
> -    /// # Safety
> -    ///
> -    /// This method must not be called concurrently with any DMA allocation 
> or mapping primitives,
> -    /// such as [`Coherent::zeroed`].
> -    unsafe fn dma_set_max_seg_size(&self, size: u32) {
> -        // SAFETY:
> -        // - By the type invariant of `device::Device`, 
> `self.as_ref().as_raw()` is valid.
> -        // - The safety requirement of this function guarantees that there 
> are no concurrent calls
> -        //   to DMA allocation and mapping primitives using this parameter.
> -        unsafe { bindings::dma_set_max_seg_size(self.as_ref().as_raw(), 
> size) }
> +    /// For tests only.
> +    #[cfg(CONFIG_KUNIT = "y")]
> +    #[allow(dead_code)] // Only used by tests of other, optional 
> abstractions.
> +    pub(crate) fn new_for_test(dev: &'bound device::Device<Bound>) -> Self {
> +        Self { dev }
>      }
>  }

[Severity: Low]
Both Setup and Handle document an "# Invariants" section, and
Setup::configure() includes an "// INVARIANT:" comment when constructing
Handle, but Setup::new() and Handle::new_for_test() construct Self { dev }
without "// INVARIANT:" comments explaining why the type invariants hold.

[Severity: Low]
Should Setup::new(), Setup::configure(), Handle::device(),
Handle::as_raw(), and Handle::new_for_test() be marked #[inline], as they
are small accessors/constructors or forward directly to C bindings in the
kernel crate?

-- 
Sashiko AI review ยท 
https://sashiko.dev/#/patchset/[email protected]?part=3

Reply via email to