Thank you for your contribution! Sashiko AI review found 4 potential
issues to consider:
- [High] rust: dma_fence: payload leak in DriverFence::drop() dropping
  NonNull wrapper
- [Medium] rust: dma_fence: unordered error read and dropped lock in
  Fence::status()
- [Low] rust: dma_fence: unused must_use Poll<()> from status? in
  DriverFence doctest
- [Low] rust: dma_fence: missing #[inline] on Fence::status() and
  Fence::__status()
--

commit f56e1b83c890ce88ce5d8586f8dbd63eb0c3c0e7
Author: Philipp Stanner <[email protected]>

rust: DmaFence: Replace is_signaled() with status()

This commit replaces Fence::is_signaled() with Fence::status() returning
Poll<Result> so callers also check whether a signaled fence completed with
an error, and updates the DriverFence documentation example accordingly.

> diff --git a/rust/kernel/dma_buf/dma_fence.rs 
> b/rust/kernel/dma_buf/dma_fence.rs
> index f3889994e69d3..931d3a084e452 100644
> --- a/rust/kernel/dma_buf/dma_fence.rs
> +++ b/rust/kernel/dma_buf/dma_fence.rs
[ ... ]
> @@ -503,39 +504,34 @@ unsafe impl Send for Fence {}
>  unsafe impl Sync for Fence {}
>  
>  impl Fence {
> -    /// Check whether the fence was signaled at the moment of the function 
> call.
> +    /// Query a fence's error code and turn it into a [`Result`].
>      ///
> -    /// Note that this can return `true` for a [`Fence`] whose 
> [`DriverFence`]
> -    /// has not yet been dropped. The reason is that the fence ops callbacks 
> can
> -    /// cause the fence to get signaled by the C backend.
> -    #[inline]
> -    pub fn is_signaled(&self) -> bool {
> -        // We should not use `dma_fence_is_signaled_locked()` here, because
> -        // according to the C backend's recommendations, that function is
> -        // problematic and we should avoid calling that function with a lock
> -        // held.
> -
> -        // SAFETY: Inner `fence` is valid because `self` is valid.
> -        let ret = unsafe { bindings::dma_fence_is_signaled(self.as_raw()) };
> -
> -        // To be as robust as possible for the future we guarantee that an 
> API
> -        // caller can 100% rely on the signaling being completed (i.e., all
> -        // fence callbacks ran), so we have to take the lock.
> -        //
> -        // The reason is that the C dma_fence backend currently does not
> -        // carefully synchronize the `dma_fence_is_signaled()` function with 
> the
> -        // proper spinlock. This can lead to the function returning `true` 
> while
> -        // fence callbacks are still being executed. This can be mitigated by
> -        // guarding the entire function with the spinlock.
> -        //
> -        // The fundamental reason is that the C backend currently does guard
> -        // setting of the fence's signaled-bit with the fence's spinlock, but
> -        // reading is done locklessly.
> -        //
> -        // See commit c8a5d5ea3ba6a.
> -        let _ = self.lock();
> +    /// # Safety
> +    ///
> +    /// The caller must only call this on fences that are already signaled. 
> It
> +    /// must be ensured that this is ordered properly against checking of the
> +    /// signaled status (fence->signaled bit).
> +    unsafe fn __status(&self) -> Result {
> +        // SAFETY: Safe by the function's safety requirements.
> +        let res = unsafe { (*self.as_raw()).error };
> +
> +        to_result(res)
> +    }
>  
> -        ret
> +    /// Query a fence's status at the moment of the function call.
> +    ///
> +    /// If it is signaled, return the fence's result, i.e., determine if it 
> was
> +    /// signaled with an error.
> +    pub fn status(&self) -> Poll<Result> {
> +        // SAFETY: `self` is valid.
> +        if unsafe { bindings::dma_fence_is_signaled(self.as_raw()) } {
> +            // SAFETY: The fence is signaled. The C backend ensures ordering.
> +            let status = unsafe { self.__status() };
> +
> +            return Poll::Ready(status);
> +        }
> +
> +        Poll::Pending
>      }

[Severity: Medium]
Does dma_fence_is_signaled() actually provide the memory ordering that
__status() requires before reading (*self.as_raw()).error?

On the fast path, dma_fence_is_signaled() calls
dma_fence_test_signaled_flag(), which is a plain test_bit() with no
acquire barrier or lock:

include/linux/dma-fence.h:dma_fence_test_signaled_flag() {
        return test_bit(DMA_FENCE_FLAG_SIGNALED_BIT, &fence->flags);
}

Because a branch on test_bit() only creates a control dependency, which
does not order load-to-load, a weakly-ordered CPU can reorder the
non-atomic read of fence->error in __status() ahead of the read of
fence->flags:

CPU0                              CPU1
DriverFence::signal(Err(...))     Fence::status()
  dma_fence_lock_irqsave()          (speculatively loads fence->error == 0)
  dma_fence_set_error()
    fence->error = err;
  dma_fence_signal_locked()
    test_and_set_bit(SIGNALED_BIT)
                                    dma_fence_is_signaled() -> true
                                    __status() -> Ok(())  <-- stale error / 
data race

C's dma_fence_get_status() takes dma_fence_lock_irqsave() around
dma_fence_get_status_locked().  Removing let _ = self.lock() here also
drops the guarantee documented in the old is_signaled() comment that all
registered fence callbacks have finished running before the fence is
observed as signaled.

[Severity: Low]
This isn't a bug, but Fence::is_signaled() was marked #[inline]; should
Fence::status() and Fence::__status() also carry #[inline] as small
kernel-crate abstraction wrappers?

[ ... ]

> @@ -714,9 +710,18 @@ struct DriverFenceData<'a, T: Send + Sync + 
> FenceContextOps> {
>  /// let cb_reg = KBox::pin_init(cb_reg, GFP_KERNEL)?;
>  ///
>  /// // TODO signalling guards
> -/// assert_eq!(waiting_fence.is_signaled(), false);
> +///
> +/// let status = waiting_fence.status();
> +/// if status.is_ready() {
> +///      return Err(ENOMSG);
> +/// }
>  /// fence.signal(Ok(()));
> -/// assert_eq!(waiting_fence.is_signaled(), true);
> +/// let status = waiting_fence.status();
> +/// if status.is_pending() {
> +///     return Err(ENOENT);
> +/// }
> +///
> +/// status?;
>  ///
>  /// Ok::<(), Error>(())
>  /// ```

[Severity: Low]
Does "status?;" fail to compile when CONFIG_RUST_KERNEL_DOCTESTS=y,
CONFIG_DMA_SHARED_BUFFER=y, and CONFIG_WERROR=y are enabled?

Applying ? to Poll<Result> yields a Poll<()>, which is annotated with
#[must_use] and triggers an unused_must_use warning when discarded.

[Severity: High]
Also, while this doctest constructs FenceData with a CString payload,
commit "rust: DmaFence: Replace call_rcu() with RcuState" earlier in this
series changed DriverFence::drop() to pass the outer NonNull field to
drop_in_place():

rust/kernel/dma_buf/dma_fence.rs:DriverFence::drop() {
    ...
        unsafe { drop_in_place(&raw mut self.data) };

        unsafe { bindings::dma_fence_put(self.as_raw()) };
}

Because self.data is a NonNull<DriverFenceData<'a, T>>, drop_in_place()
is a no-op and T::FenceDataType's destructor never runs, leaking the user
payload on every DriverFence drop.  Should this drop
&raw mut (*self.data.as_ptr()).data (after caching self.as_raw() so
as_raw() does not create a shared reference to DriverFenceData after its
data field is dropped)?

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

Reply via email to