Skip to contentSkip to conversation

rust: Add drm::JobQueue

PATCH In review Philipp Stanner 3 participants 15 messages Nov 24

Subsystems (7)
DRM drivers Media (V4L/DVB) Rust RCU +3 more subsystems
lore
Share & tools
lore

Philipp Stanner

author maintainer
#0 lore raw

v2 cover rust: Add drm::JobQueue

Changes in v2:
- Fence:
- Use cond_synchronize_rcu() to speed up fence dropping. (Gary)
- status(): Don't lock anymore, since I fixed the misordering in C [1].
- JQ:
- In v1, jobs could be forgotten without being submitted, causing UAF. Fixed it by incrementing the atomic by 1, decremented then later in submit.
- Fix bug where I was holding the lock while dropping stuff. (Younes)
- Add support for park() and unpark() for Tyr.
- Do not check for parked (revoked) in DropWorker, so that a park()ed JQ can continue to drop. Is safe thx to drop order.
- Use our own workqueues, with MEM_RECLAIM flag set for the submit workqueue.
- Rename SubmitWorker consistently to RunWorker. Now, submit always means job.submit(), and run always means run_job().
- Add max_capacity, so you can never submit jobs that are too expensive.
- Dependency fences:
- Do not kill the JQ anymore if dependencies got signaled with an error. Just run these jobs anyways, like drm_sched. (Boris)
- Thus, remove the kill() callback.
- In a future extension, we can pass the error codes through a suitable data structure to the driver in run_job().
- Why was this done? To be discussed in detail, but implementing it like this allows us for centralizing dep error handling in run_job(), *if* drivers should care. As far as can be seen in the DRM drivers, they don't.
And if they do we would have to come to a common position about fences' errors' meaning.
So the proposal is to upstream it like this for now to unblock Tyr. Dependency error checking can then be added once our discussions reached a common ground.
- Fix CLIPPY warnings.
- Update the docu to reflect the points above.
- Update the doctest examples accordingly.

Changes since RFCv7:
- Write a bunch of documentation, mostly about the kill() backend_ops.
- Add creations of own work_queues (requires some work with the life times still; last relevant TODO AFAICS).

[1] https://lore.kernel.org/dri-devel/[email protected]/

Depends on the workqueue series:
https://lore.kernel.org/rust-for-linux/[email protected]/

Besides based on drm-rust-next

Daniel tested an earlier RFC (v6 I think) on Tyr and reports that it ran well. In v2 I want to have our own workqueues ready, perhaps after the workqueue has gone upstream.

But I thought it's time to present this as v1 since we settled on the design, it's mostly working already and we can now begin diving out the remaining problems.

So please review :)

Thx again to everyone who helped with moving this forward.

Last RFC:
https://lore.kernel.org/dri-devel/[email protected]/

Repo:
https://gitlab.freedesktop.org/pstanner/linux-drm-work/-/tree/jobqueue-jobqueue-v1-2?ref_type=heads

PS:
Note that this version now obtains a fence->error under lock, because I strongly suspect that this pattern

if (dma_fence_is_signaled(f))
pr_info("err: %i\n", f->error);

is UB since there is no memory ordering between the reads (which would proof that fences' locks are not "just for the cb_list", as was sometimes suggested). My discussions regarding fixing that in C can be found here:

https://lore.kernel.org/dri-devel/[email protected]/
https://lore.kernel.org/dri-devel/[email protected]/

Philipp Stanner (10):
rust: rcu: Add get_state_synchronize_rcu()
rust: rcu: Add cond_synchronize_rcu()
rust: DmaFence: Implement Deref for FenceContext
rust: DmaFence: Add ID accessor for FenceContext
rust: DmaFence: Don't drop on signal
rust: DmaFence: Replace call_rcu() with cond_synchronize_rcu()
rust: DmaFence: Replace is_signaled() with status()
rust: DmaFence: Pass result in callbacks
rust: drm: Add JobQueue
MAINTAINERS: Add drm::JobQueue to drm_sched's entry

 MAINTAINERS                      |   1 +
 rust/helpers/rcu.c               |   5 +
 rust/kernel/dma_buf/dma_fence.rs | 261 +++++-----
 rust/kernel/dma_buf/mod.rs       |   3 +-
 rust/kernel/drm/job_queue.rs     | 863 +++++++++++++++++++++++++++++++
 rust/kernel/drm/mod.rs           |   4 +
 rust/kernel/sync/rcu.rs          |  23 +
 7 files changed, 1038 insertions(+), 122 deletions(-)
 create mode 100644 rust/kernel/drm/job_queue.rs

base-commit: 4325f4aad9727a6e8e7f10c5d2ebf490470cf938
prerequisite-patch-id: f5e24f7b3717f2ab0445b5395c7f12b554861d78
prerequisite-patch-id: e4ebcb108207c2d06130382c59c12ffe09a7a6db
prerequisite-patch-id: e19d2e11fc6c6fc121d65c8502bfa557e1dfc5ec
prerequisite-patch-id: 47301119dc7bc6fdc83256002e92c781a872b142

Signature · 1 line
2.56.0
author maintainer
#1 lore raw

PATCH v2 1/10 rust: rcu: Add get_state_synchronize_rcu()

Some users don't want to perform a full call to synchronize_rcu() if it is avoidable.

Add abstractions for get_state_synchronize_rcu() to obtain a grace period identifier.

---
 rust/kernel/sync/rcu.rs | 10 ++++++++++
 1 file changed, 10 insertions(+)
rust/kernel/sync/rcu.rs +10 -0
index 0daa1ac87d81..7afc78b34759 100644
@@ -86,3 +86,13 @@ pub fn synchronize_rcu() {
     // SAFETY: `synchronize_rcu()` is always safe to be called from process context.
     unsafe { bindings::synchronize_rcu() };
 }
+
+/// Obtain a cookie identifying a grace period.
+///
+/// Returns an identifier that can be used by other functions to check whether
+/// a specific grace period has passed already.
+#[inline]
+pub fn get_state_synchronize_rcu() -> usize {
+    // SAFETY: `get_state_synchronize_rcu()` is always safe to be called.
+    unsafe { bindings::get_state_synchronize_rcu() }
+}
Signature · 1 line
2.56.0
author maintainer
#2 lore raw

PATCH v2 2/10 rust: rcu: Add cond_synchronize_rcu()

In reply to Philipp Stanner

cond_synchronize_rcu() can be useful for anyone who does not want to suffer the overhead of an avoidable call to synchronize_rcu().

Add an abstraction for cond_synchronize_rcu(). Add it as an unsafe function since passing the right grace period identifier is crucial for safety.

---
 rust/helpers/rcu.c      |  5 +++++
 rust/kernel/sync/rcu.rs | 13 +++++++++++++
 2 files changed, 18 insertions(+)
rust/helpers/rcu.c +5 -0
index 481274c05857..570ee76b7247 100644
@@ -11,3 +11,8 @@ __rust_helper void rust_helper_rcu_read_unlock(void)
 {
 	rcu_read_unlock();
 }
+
+__rust_helper void rust_helper_cond_synchronize_rcu(unsigned long cookie)
+{
+	cond_synchronize_rcu(cookie);
+}
rust/kernel/sync/rcu.rs +13 -0
index 7afc78b34759..c395a493746c 100644
@@ -96,3 +96,16 @@ pub fn get_state_synchronize_rcu() -> usize {
     // SAFETY: `get_state_synchronize_rcu()` is always safe to be called.
     unsafe { bindings::get_state_synchronize_rcu() }
 }
+
+/// Do a [`synchronize_rcu()`] if necessary.
+///
+/// # Safety
+///
+/// The `cookie` you provide must be one you obtained through
+/// [`get_state_synchronize_rcu()`].
+/// It must match the specific grace period you need to wait for.
+#[inline]
+pub unsafe fn cond_synchronize_rcu(cookie: usize) {
+    // SAFETY: Safe by the function's safety requirements.
+    unsafe { bindings::cond_synchronize_rcu(cookie) };
+}
Signature · 1 line
2.56.0
author maintainer
#3 lore raw

PATCH v2 3/10 rust: DmaFence: Implement Deref for FenceContext

In reply to Philipp Stanner

A FenceContext carries data, which the user should be able to access.

Implement Deref for FenceContext.

---
 rust/kernel/dma_buf/dma_fence.rs | 9 +++++++++
 1 file changed, 9 insertions(+)
rust/kernel/dma_buf/dma_fence.rs +9 -0
index a1d851656562..5300448882e7 100644
@@ -86,6 +86,15 @@ pub struct FenceContext<T: FenceContextOps + Send + Sync> {
     data: T,
 }
 
+impl<T: Send + Sync + FenceContextOps> Deref for FenceContext<T> {
+    type Target = T;
+
+    #[inline]
+    fn deref(&self) -> &Self::Target {
+        &self.data
+    }
+}
+
 impl<'a, T: Send + Sync + FenceContextOps> FenceContext<T> {
     // This can later be extended as a vtable in case other parties need support
     // for the more "exotic" callbacks.
Signature · 1 line
2.56.0
author maintainer
#4 lore raw

PATCH v2 4/10 rust: DmaFence: Add ID accessor for FenceContext

In reply to Philipp Stanner

A FenceContext has a fence context number, which can serve as an ID field. This number can be useful for owners of multiple contexts to identify them, store them in an XArray etc.

Add an accessor for fctx.nr.

---
 rust/kernel/dma_buf/dma_fence.rs | 6 ++++++
 1 file changed, 6 insertions(+)
rust/kernel/dma_buf/dma_fence.rs +6 -0
index 5300448882e7..897308f60dd3 100644
@@ -135,6 +135,12 @@ pub fn new<E>(
         })
     }
 
+    /// Obtain the FenceContext's ID number.
+    #[inline]
+    pub fn id(&self) -> u64 {
+        self.nr
+    }
+
     fn next_seqno(&self) -> u64 {
         self.seqno.fetch_add(1, Relaxed)
     }
Signature · 1 line
2.56.0
author maintainer
#5 lore raw

PATCH v2 5/10 rust: DmaFence: Don't drop on signal

In reply to Philipp Stanner

The original design for DmaFence intended to comply as strictly as possible with the "dma_fence contract", which, according to some, says that a fence must only be signaled once. Thus, the implementation was made so that a DriverFence drops on signal.

While extending JobQueue's capabilities, it was discovered that this characteristic causes - unnecessary - trouble: fence-data must be dropped in an RCU-deferred manner because the C backend demands that. However, fences are often signaled in atomic context (e.g., interrupt handler) where you don't want to drop, but signal as quickly as possible.

Actually, there is no real hard reason to enforce that a fence can only get signaled once, because the C backend is robust against multiple signal attempts.

What is decisive is that a) all fences signal and b) they only drop no earlier than 1 RCU grace period after signaling.

Don't drop a DriverFence on signal().

---
 rust/kernel/dma_buf/dma_fence.rs | 11 ++++++-----
 1 file changed, 6 insertions(+), 5 deletions(-)
rust/kernel/dma_buf/dma_fence.rs +6 -5
index 897308f60dd3..c04b68fe67fe 100644
@@ -820,7 +820,7 @@ pub fn as_fence(&self) -> &Fence {
     }
 
     /// Signal the fence. This will invoke all registered callbacks.
-    pub fn signal(self, res: Result) {
+    pub fn signal(&self, res: Result) {
         let fence = self.as_fence().lock();
 
         // SAFETY: `fence` is valid because `self` is valid. The lock must be
@@ -831,14 +831,15 @@ pub fn signal(self, res: Result) {
                 // must not have been signaled yet, which we check directly above.
                 unsafe { bindings::dma_fence_set_error(fence.as_raw(), err.to_errno()) };
             }
+
+            // SAFETY: `self.data` is valid because `self` is valid.
+            let fctx = unsafe { self.data.as_ref().fctx };
+            let _ = fctx.nr_of_unsignaled_fences.fetch_sub(1, Relaxed);
+
             // SAFETY: `fence` is valid because `self` is valid. The lock must
             // be held, which we acquired above.
             unsafe { bindings::dma_fence_signal_locked(fence.as_raw()) };
         }
-
-        // SAFETY: `self.data` is valid because `self` is valid.
-        let fctx = unsafe { self.data.as_ref().fctx };
-        let _ = fctx.nr_of_unsignaled_fences.fetch_sub(1, Relaxed);
     }
 }
 
Signature · 1 line
2.56.0
author maintainer
#6 lore raw

PATCH v2 6/10 rust: DmaFence: Replace call_rcu() with cond_synchronize_rcu()

In reply to Philipp Stanner

The C dma_fence contract demands that a fence's data disappears no earlier than 1 RCU grace period after the DriverFence was signaled. So far, we achieved this with dropping the DriverFence's data in a deferred manner with a manual, raw binding call to call_rcu().

However, this call_rcu() does not solve one problem: It is conceivable that some driver data must not drop in atomic context; but call_rcu()'s payload *can* be executed in atomic context.

Moreover, the current developments in drm::JobQueue, where a DriverFence is always coupled 1:1 with a Job, allows for dropping job and fence through a work item.

We can satisfy the grace period requirement in a safe yet performant manner by using cond_synchronize_rcu(), which only waits for a grace period if the specified grace period has not yet passed.

We can exactly identify the right grace period by setting a cookie in DriverFence::signal().

Replace DriverFence::drop()'s call_rcu() with cond_synchronize_rcu().

An implication of this is that fences must for now drop in process context until someone finds a more elegant solution. Document this requirement.

---
 rust/kernel/dma_buf/dma_fence.rs | 133 +++++++++++++------------------
 1 file changed, 56 insertions(+), 77 deletions(-)
rust/kernel/dma_buf/dma_fence.rs +56 -77
index c04b68fe67fe..20dadbde4eb9 100644
@@ -21,6 +21,7 @@
 };
 
 use core::{
+    cell::UnsafeCell,
     marker::PhantomData,
     mem::ManuallyDrop,
     ops::Deref,
@@ -42,7 +43,11 @@
             Atomic,
             Relaxed, //
         },
-        rcu::rcu_barrier, //
+        rcu::{
+            cond_synchronize_rcu,
+            get_state_synchronize_rcu,
+            synchronize_rcu, //
+        },
     }, //
 };
 
@@ -58,6 +63,8 @@ pub trait FenceContextOps {
 /// A dma-fence context. A fence context takes care of associating related fences
 /// with each other, providing each with raising sequence numbers and a common
 /// identifier.
+///
+/// A FenceContext must drop in non-atomic context.
 #[pin_data(PinnedDrop)]
 pub struct FenceContext<T: FenceContextOps + Send + Sync> {
     /// The fence context number.
@@ -65,7 +72,7 @@ pub struct FenceContext<T: FenceContextOps + Send + Sync> {
     /// The sequence number for the next fence created.
     seqno: Atomic<u64>,
     // The name parameters can be accessed by the dma_fence backend_ops. UAF
-    // errors are prevented by the `call_rcu()` in `drop_driver_fence_data()`.
+    // errors are prevented by `synchronize_rcu()`.
     /// The name of the driver this FenceContext's fences belong to.
     driver_name: CString,
     /// The name of the timeline this FenceContext's fences belong to.
@@ -149,20 +156,17 @@ fn next_seqno(&self) -> u64 {
     ///
     /// This is needed because many times, creation of a [`DriverFence`] must not
     /// fail, and allocating might deadlock in some situations.
-    ///
-    /// The `data` you pass here must not perform any operations that are illegal
-    /// in atomic context in its [`Drop`] implementation.
     pub fn new_fence_allocation(
         &self,
         data: T::FenceDataType,
     ) -> Result<DriverFenceAllocation<'_, T>> {
         let fence_data = DriverFenceData {
-            rcu_head: Default::default(),
             // `inner` remains uninitialized until a `DriverFence` takes over.
             inner: Fence {
                 inner: Opaque::uninit(),
             },
             fctx: self,
+            synchronize_rcu_cookie: UnsafeCell::new(0),
             data,
         };
 
@@ -243,15 +247,10 @@ fn drop(self: Pin<&mut Self>) {
             panic!("Forgotten fences in FenceContext.");
         }
 
-        // Ensure that the driver cannot unload while there are still dma_fence
-        // callbacks running. At the same time, the RCU barrier addresses the
-        // problem inherited by the C backend, in which backend ops callbacks
-        // might be accessing the fence while it is being signaled (or shortly
-        // after). This could cause UAF access on the fence context's
-        // `fctx.driver_name` and `fctx.timeline_name`.
-        //
-        // Wait for the RCU callbacks in `DriverFence::drop`.
-        rcu_barrier();
+        // If a DriverFence signals without doing a synchronize_rcu(), and a
+        // fctx drops immediately afterwards, then backend_ops still accessing
+        // the fctx might run into UAF if we don't wait for them here.
+        synchronize_rcu();
     }
 }
 
@@ -615,12 +614,14 @@ struct DriverFenceData<'a, T: Send + Sync + FenceContextOps> {
     // necessary so that the C backend can free the allocation (coming from our
     // Rust code) with kfree_rcu().
     inner: Fence,
-    /// Callback head for dropping this in a deferred manner through RCU.
-    rcu_head: bindings::callback_head,
     /// Reference to access the FenceContext.
     fctx: &'a FenceContext<T>,
-    /// The API user's data. It is essential that the data only performs
-    /// operations legal in atomic context in its [`Drop`] implementation.
+    /// A cookie that helps with reducing the number of costly calls to
+    /// `synchronize_rcu()` in [`DriverFence::drop()`].
+    ///
+    /// This [`UnsafeCell`] is protected by `inner`'s spinlock.
+    synchronize_rcu_cookie: UnsafeCell<usize>,
+    /// The API user's data.
     #[pin]
     data: T::FenceDataType,
 }
@@ -659,6 +660,8 @@ struct DriverFenceData<'a, T: Send + Sync + FenceContextOps> {
 ///
 /// In the unlikely case of such violations, a panic is thrown.
 ///
+/// A DriverFence must drop in non-atomic context.
+///
 /// # Examples
 ///
 /// ```
@@ -831,7 +834,6 @@ pub fn signal(&self, res: Result) {
                 // must not have been signaled yet, which we check directly above.
                 unsafe { bindings::dma_fence_set_error(fence.as_raw(), err.to_errno()) };
             }
-
             // SAFETY: `self.data` is valid because `self` is valid.
             let fctx = unsafe { self.data.as_ref().fctx };
             let _ = fctx.nr_of_unsignaled_fences.fetch_sub(1, Relaxed);
@@ -839,6 +841,11 @@ pub fn signal(&self, res: Result) {
             // SAFETY: `fence` is valid because `self` is valid. The lock must
             // be held, which we acquired above.
             unsafe { bindings::dma_fence_signal_locked(fence.as_raw()) };
+
+            // SAFETY: `self.data` is valid because `self` is valid.
+            // The lock guarantees exclusivity.
+            let rcu_cookie = unsafe { &mut *self.data.as_ref().synchronize_rcu_cookie.get() };
+            *rcu_cookie = get_state_synchronize_rcu();
         }
     }
 }
@@ -955,15 +962,15 @@ fn drop(&mut self) {
         // dma_fence_is_signaled_locked() because the C backend wants to get rid
         // of the latter.
 
-        // SAFETY: `guard` is valid until the `call_rcu()` below.
+        // SAFETY: `guard` is valid.
         let signaled: bool = unsafe { bindings::dma_fence_test_signaled_flag(guard.as_raw()) };
         if !signaled {
             pr_err!("DriverFence drops unsignaled. Danger of memory corruption!\n");
-            // SAFETY: `guard` is valid until the `call_rcu()` below. The fence
-            // must not have been signaled yet, which we check directly above.
+            // SAFETY: `guard` is valid. The fence must not have been signaled
+            // yet, which we check directly above.
             unsafe { bindings::dma_fence_set_error(guard.as_raw(), ECANCELED.to_errno()) };
-            // SAFETY: `guard` is valid until the `call_rcu()` below. The lock
-            // must be held, which we acquired above.
+            // SAFETY: `guard` is valid. The lock must be held, which we
+            // acquired above.
             unsafe { bindings::dma_fence_signal_locked(guard.as_raw()) };
 
             // SAFETY: `self.data` is valid because `self` is valid.
@@ -988,59 +995,31 @@ fn drop(&mut self) {
             return;
         }
 
-        // SAFETY: Valid because `self` is valid.
-        let rcu_head_ptr = unsafe { &raw mut (*self.data.as_ptr()).rcu_head };
+        // SAFETY: `self` is valid. No one can access the cookie anymore because
+        // we are dropping.
+        let rcu_cookie = unsafe { *self.data.as_ref().synchronize_rcu_cookie.get() };
 
-        // SAFETY: `call_rcu()` is always safe to be called. `rcu_head_ptr` was
-        // created validly above. The module must perform a `synchronize_rcu()`
-        // or `rcu_barrier()` call to guard against module unload.
-        unsafe { bindings::call_rcu(rcu_head_ptr, Some(drop_driver_fence_data::<T>)) };
-    }
-}
+        // Make sure none of the fence backend_ops can access fence-data anymore.
+        //
+        // TODO:
+        // This would not be necessary if the C dma_fence backend were using a
+        // spinlock to properly synchronize its signaled state. Fix it in C and
+        // then remove synchronize_rcu().
+        if rcu_cookie != 0 {
+            // SAFETY: The if-else checks whether the cookie was validly
+            // initialized when this fence signaled.
+            unsafe { cond_synchronize_rcu(rcu_cookie) };
+        } else {
+            // The user never signaled this fence. We don't know the grace period.
+            synchronize_rcu();
+        }
 
-// TODO:
-// The entire call_rcu() mechanism in the drop above and the code below would be
-// unnecessary if C's dma_fence_signal() could be reworked in a way that after it
-// ran, the caller knows that no fence_ops callbacks can be running anymore.
-// In other words, if the dma_fence backend would use its spinlock for full
-// synchronization.
-//
-// Then we could move the drop_in_place() and dma_fence_put() upwards into the
-// drop() implementation and call it a day.
+        // SAFETY: Valid because `self` is valid. RCU above ensures that all
+        // accessors are gone.
+        unsafe { drop_in_place(&raw mut self.data) };
 
-/// Finally really drop this `DriverFence<T>`
-///
-/// # Safety
-///
-/// `head` references the `rcu_head` field of an `DriverFenceData<T>`. All
-/// accessors to that `DriverFenceData<T>` must be gone by now. This must be
-/// ensured by signalling the associated `DriverFence<T>` and then waiting
-/// for a grace period until calling this function here.
-unsafe extern "C" fn drop_driver_fence_data<T: Send + Sync + FenceContextOps>(
-    head: *mut bindings::callback_head,
-) {
-    // SAFETY: Caller provides a pointer to the `rcu_head` field of a `DriverFenceData<C>`.
-    let fence_data = unsafe { container_of!(head, DriverFenceData<'_, T>, rcu_head) };
-
-    // SAFETY: `fence_data` was created validly above. All the fence's data will
-    // only drop below, but the raw pointer to the raw C `dma_fence` remains
-    // valid because the reference count is only decremented at the end of the
-    // function.
-    let fence = unsafe { (*fence_data).inner.inner.get() };
-
-    // SAFETY: `fence_data` was created validly above. The user has already
-    // dropped the only conventional accessor to the user data, the `DriverFence`,
-    // one grace period ago. All accessors are gone now.
-    unsafe { drop_in_place(&raw mut (*fence_data).data) };
-
-    // The inner `Fence` explicitly does not get dropped because there may be
-    // many more users / consumers, each holding their own reference.
-
-    // SAFETY: Once a `DriverFence` is initialized, the inner `fence` is valid
-    // and initialized. It is valid until the refcount drops to 0, which can
-    // earliest happen once we drop the `DriverFence`'s reference here.
-    unsafe { bindings::dma_fence_put(fence) };
-
-    // The actual memory the data associated with a `DriverFence` lives in
-    // gets freed by the C dma_fence backend once the fence's refcount reaches 0.
+        // SAFETY: Valid because `self` is valid. This is the initial reference
+        // from when this `DriverFence` was created.
+        unsafe { bindings::dma_fence_put(self.as_raw()) };
+    }
 }
Signature · 1 line
2.56.0
author maintainer
#8 lore raw

PATCH v2 7/10 rust: DmaFence: Replace is_signaled() with status()

In reply to Philipp Stanner

As it turns out, our dma_fence abstractions lack an essential feature; a problem which is partially inherited from the C backend:

Despite it being a common pattern in the kernel, you actually should not just check whether a fence was signaled and call it a day - it is important that you also check whether a fence was signaled *with an error*.

To make things more complicated, an error can get modified at any point in time before a fence gets signaled. Thus, it must be ensured that the signaled state is always evaluated before the error code.

Since the fence status is essential information that must not be ignored, replace Fence::is_signaled() with Fence::status(), making it impossible to ignore the error code.

---
 rust/kernel/dma_buf/dma_fence.rs | 77 ++++++++++++++++++--------------
 rust/kernel/dma_buf/mod.rs       |  3 +-
 2 files changed, 46 insertions(+), 34 deletions(-)
rust/kernel/dma_buf/dma_fence.rs +44 -33
index 20dadbde4eb9..09bebf9c1e4e 100644
@@ -510,40 +510,44 @@ unsafe impl Send for Fence {}
 // SAFETY: Fences are literally designed to be shared between threads.
 unsafe impl Sync for Fence {}
 
+/// Fence-Status queried through [`Fence::status()`].
+#[derive(Debug)]
+pub enum FenceStatus {
+    /// The fence is not yet signaled.
+    Unsignaled,
+    /// The fence is signaled. Might have been signaled with an error.
+    Signaled(Result),
+}
+
 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)
+    }
+
+    /// 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) -> FenceStatus {
+        // 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 FenceStatus::Signaled(status);
+        }
 
-        ret
+        FenceStatus::Unsignaled
     }
 
     /// Lock the fence. A helper only to be used internally in this module.
@@ -672,6 +676,7 @@ struct DriverFenceData<'a, T: Send + Sync + FenceContextOps> {
 ///         FenceContextOps,
 ///         FenceCallback,
 ///         FenceCallbackRegistration,
+///         FenceStatus, //
 ///     },
 ///     str::CString,
 ///     sync::aref::ARef, //
@@ -723,9 +728,15 @@ 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);
+///
+/// // TODO: add support for `assert_matches!()`.
+/// if let FenceStatus::Signaled(_) = waiting_fence.status() {
+///      return Err(ENOMSG);
+/// }
 /// fence.signal(Ok(()));
-/// assert_eq!(waiting_fence.is_signaled(), true);
+/// if let FenceStatus::Unsignaled = waiting_fence.status() {
+///     return Err(ENOENT);
+/// }
 ///
 /// Ok::<(), Error>(())
 /// ```
rust/kernel/dma_buf/mod.rs +2 -1
index 4764a828642e..b5254144f69e 100644
@@ -10,5 +10,6 @@
     FenceCallback,
     FenceCallbackRegistration,
     FenceContext,
-    FenceContextOps, //
+    FenceContextOps,
+    FenceStatus, //
 };
Signature · 1 line
2.56.0
author maintainer
#10 lore raw

PATCH v2 8/10 rust: DmaFence: Pass result in callbacks

In reply to Philipp Stanner

A FenceCallbackRegistration invokes the on_signal() trait functions specified by the user. These callbacks always get executed, even if the fence was signaled with an error. The user must then be able to react accordingly.

Memory ordering is ensured by the C backend.

Change the on_signal() trait function so that the implementor always receives the fence's actual state.

---
 rust/kernel/dma_buf/dma_fence.rs | 27 ++++++++++++++++++++-------
 1 file changed, 20 insertions(+), 7 deletions(-)
rust/kernel/dma_buf/dma_fence.rs +20 -7
index 09bebf9c1e4e..e972b2e84b1d 100644
@@ -299,9 +299,12 @@ fn from(e: AllocError) -> Self {
 /// }
 ///
 /// impl FenceCallback for MyCallback {
-///     fn on_signal(&mut self) {
-///         pr_info!("Fence signaled!\n");
-///         // Handle fence completion
+///     fn on_signal(&mut self, status: Result) {
+///         if status.is_ok() {
+///             pr_info!("Fence signaled!\n");
+///         } else {
+///             pr_err!("Fence signaled with an error!\n");
+///         }
 ///     }
 /// }
 /// ```
@@ -316,7 +319,7 @@ pub trait FenceCallback: Send {
     /// An implementation likely wants to inform itself (e.g., through a work item)
     /// within this callback that the associated [`FenceCallbackRegistration`]
     /// can now be dropped.
-    fn on_signal(&mut self);
+    fn on_signal(&mut self, status: Result);
 }
 
 /// A callback registration on a fence.
@@ -403,11 +406,17 @@ pub unsafe fn new<'a>(
         // embedded into a `FenceCallbackRegistration`.
         let reg: *mut Self = unsafe { container_of!(ptr, Self, callback_foreign) };
 
+        // SAFETY: `reg` is a valid `Self` pointer. This here is literally an
+        // executing fence callback, hence the fence is signaled. Its signaled
+        // bit has been set with a strongly ordered atomic instruction on the
+        // same CPU.
+        let fence_result = unsafe { (*reg).fence.__status() };
+
         // SAFETY: `reg` is a valid `Self` pointer.
         //
         // The backend ensures synchronisation so whoever holds the registration object cannot drop
         // it while this code is running. See `FenceCallbackRegistration::drop`.
-        unsafe { (*reg).callback.on_signal() };
+        unsafe { (*reg).callback.on_signal(fence_result) };
     }
 
     /// Returns a reference to the fence this callback is registered on.
@@ -686,8 +695,12 @@ struct DriverFenceData<'a, T: Send + Sync + FenceContextOps> {
 /// struct CallbackData { }
 ///
 /// impl FenceCallback for CallbackData {
-///     fn on_signal(&mut self) {
-///         pr_info!("DmaFence callback executed.\n");
+///     fn on_signal(&mut self, status: Result) {
+///         if status.is_ok() {
+///             pr_info!("DmaFence callback executed.\n");
+///         } else {
+///             pr_err!("DmaFence callback executed, but fence has an error.\n");
+///         }
 ///     }
 /// }
 ///
Signature · 1 line
2.56.0
author maintainer
#11 lore raw

PATCH v2 9/10 rust: drm: Add JobQueue

In reply to Philipp Stanner

JobQueue is a pure Rust component that handles job submissions for GPUs with firmware scheduling, i.e., GPUs that support one exclusive ring per execution context.

JobQueue's primary task is dependency handling, where the user can set dependencies, each in the form of a dma_buf::Fence, on a job and then submit it to the queue.

Jobs are being executed in FIFO order. Only jobs whose dependencies are all fulfilled get executed, otherwise the JobQueue pauses.

A core design principle, just like with DmaFence, is to avoid all allocations in job submission paths, since this runs danger of deadlocking. For the same reason JobQueue's run_job workqueue is reclaim-safe.

Another design principle, new when compared to the older drafts, is the ownership relationship with fences:

1. The JobQueue owns the FenceContext exclusively.
2. Jobs are created on the JobQueue, ensuring correct fence sequence number ordering.
3. Jobs own the respective DriverFence.
4. Jobs are owned by the JobQueue.

Consequently, a driver can only interact with fences and FenceContext indirectly through the JobQueue, and can also only complete jobs (and, hence, signal fences) through the JobQueue.

Like drm_sched, JobQueue currently does not take errors set on job dependency fences into account. The reasons are that only all dependencies being signaled is decisive for memory safety, and that we would first have to establish what the semantic meaning of fence errors actually is. That's especially difficult when you consider that fences can be shared across drivers. Nevertheless, it would be doable to inform drivers through their run_job callback that this particular jobs has failed (but signaled) dependencies, and then allow the driver to make a decision on how to proceed (i.e., ignore or kill JQ).

When a job shall be run, both its JobQueue::data and Job::data get borrowed back to the driver, together with the sequence number of this job, so that it can perform the appropriate interaction with the hardware.

The RunWorker runs all ready jobs based on a credit count system, so that run_job() is infallible. A separate worker drops jobs (and their fences) that are already completed, but only if the user's payload data actually requires Drop. Otherwise, jobs are dropped by the RunWorker directly.

Data left over by the workers drops together with JobQueue. For this reason, and because a JobQueue owns a FenceContext, it must only ever be dropped in process context.

(^ waiting for Gary to sign-off)

---
 rust/kernel/drm/job_queue.rs | 863 +++++++++++++++++++++++++++++++++++
 rust/kernel/drm/mod.rs       |   4 +
 2 files changed, 867 insertions(+)
 create mode 100644 rust/kernel/drm/job_queue.rs
rust/kernel/drm/job_queue.rs new file +863 -0
new file mode 100644
index 000000000000..3d3d78fda551
@@ -0,0 +1,863 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * Copyright (C) 2026 Red Hat Inc.
+ * Author: Philipp Stanner <[email protected]>
+ */
+
+//! DRM's job dependency manager and load balancer for GPUs with firmware
+//! scheduling, i.e., GPUs that can spawn one ring exclusive per user context.
+//!
+//! JobQueue abstracts the entire handling of [`dma_buf::FenceContext`] and its
+//! associated [`dma_buf::DriverFence`]s for the user.
+//!
+//! In this design, a JobQueue is always the owner of a [`dma_buf::FenceContext`]
+//! which represents the timeline on the associated GPU ring. Jobs created on
+//! this JobQueue always contain a [`dma_buf::DriverFence`] from this JobQueue,
+//! where the fence sequence number corresponds with the job sequence number,
+//! and the fence's generic payload data is also the job's payload data. This
+//! allows for the dma_fence backend_ops callbacks interacting with the driver
+//! through JobQueue. The trait [`JobQueueOps`] is the interface between driver
+//! and fence backend_ops.
+//!
+//! [`Job`]s created on the [`JobQueue`] take over ownership of the user's data
+//! and prepare all memory allocations. A later job submission through
+//! [`Job::submit()`] sets up the fence and performs no fallible operations.
+//!
+//! Before jobs are submitted to a queue, dependencies in the form of
+//! [`dma_buf::Fence`] can be set on them. Jobs are run by the JobQueue in
+//! process context through a work item in FIFO order. Only jobs whose
+//! dependency fences have all been signaled are run. If the front job's
+//! dependency is not yet fulfilled, the JobQueue pauses until that's the case.
+//!
+//! If a dependency fence gets signaled with an error, JobQueue currently runs
+//! it nevertheless, like drm_sched does, since drivers do not seem to desire
+//! their queues to be killed in such cases.
+//!
+//! JobQueue implements a credit count system, where the queue itself gets
+//! assigned a capacity by the user, and jobs get assigned individual cost. Jobs
+//! are only run if there is enough capacity; if not, running stops until that
+//! is the case. These credits must accurately represent the capacity on the GPU
+//! ring the queue was created for.
+//!
+//! The driver tells the JobQueue which jobs are finished through
+//! [`JobQueue::complete_jobs_up_to_seqno()`]. This function is typically
+//! invoked through the driver's GPU interrupt handler.
+//!
+//! Since jobs might contain data that must not drop in atomic context, and
+//! since jobs' [`dma_buf::DriverFence`]s perform a call to
+//! [`rcu::synchronize_rcu()`], they are dropped through a work item if [`Drop`]
+//! is implemented for the job's payload data.
+//!
+//! From JobQueue's perspective, it is not necessary to call any of its API
+//! functions with a driver lock held; this is actually discouraged to reduce
+//! the probability of deadlocks. All JobQueue API functions are properly
+//! ordered using the internal lock.
+//!
+//! JobQueue tells drivers to run jobs through [`JobQueueOps::run_job`], which
+//! is called without the JobQueue's spinlock being held, i.e., the driver is
+//! permitted to perform sleeping operations in the callback - except for
+//! sleeping allocations, of course, since this is the fence signaling path.
+//! JobQueue handles races between `run_job` and
+//! [`JobQueue::complete_jobs_up_to_seqno()`].
+//!
+//! This is pure Rust code that does not directly abstract C.
+
+#![allow(clippy::multiple_bound_locations)] // Clippy false positive, to be addressed by pin-init.
+
+use core::{
+    convert::Infallible,
+    ops::Deref, //
+};
+
+use kernel::{
+    dma_buf::dma_fence::{
+        DriverFence,
+        DriverFenceAllocation,
+        Fence,
+        FenceCallback,
+        FenceCallbackRegistration,
+        FenceContext,
+        FenceContextOps, //
+    },
+    list::{
+        impl_list_arc_safe,
+        impl_list_item,
+        List,
+        ListItem,
+        ListLinks, //
+    },
+    new_srcu,
+    prelude::*,
+    str::CString,
+    sync::{
+        aref::ARef,
+        atomic::{
+            Atomic,
+            Relaxed, //
+        },
+        new_spinlock_irq,
+        SpinLockIrq, //
+    }, //
+    sync::{
+        atomic::AtomicFlag,
+        Srcu, //
+    },
+    sync::{Arc, UniqueArc},
+    workqueue::{
+        new_scoped_work,
+        OwnedQueue,
+        Queue,
+        ScopedWork,
+        ScopedWorkItem, //
+    }, //
+};
+
+/// A linked list where all elements are owned.
+///
+/// This is a thin wrapper of `List` with all elements are `UniqueArc`.
+struct UniqueList<T: ListItem>(List<T>);
+
+impl<T: ListItem> Default for UniqueList<T> {
+    fn default() -> Self {
+        Self::new()
+    }
+}
+
+impl<T: ListItem> UniqueList<T> {
+    fn new() -> Self {
+        Self(List::new())
+    }
+
+    fn push_front(&mut self, item: Pin<UniqueArc<T>>) {
+        self.0.push_front(item.into())
+    }
+
+    fn push_back(&mut self, item: Pin<UniqueArc<T>>) {
+        self.0.push_back(item.into())
+    }
+
+    fn pop_front(&mut self) -> Option<Pin<UniqueArc<T>>> {
+        Some(
+            Arc::into_unique_or_drop(self.0.pop_front()?.into_arc())
+                .expect("UniqueList should only contain UniqueArc"),
+        )
+    }
+}
+
+struct DependencyWaker<'b, 'nr_of_deps, T: JobQueueOps + Send + Sync> {
+    nr_of_deps: &'nr_of_deps Atomic<u32>,
+    jq: &'b JobQueue<T>,
+}
+
+impl<'b, T: JobQueueOps + Send + Sync> FenceCallback for DependencyWaker<'b, '_, T> {
+    fn on_signal(&mut self, _res: Result) {
+        // Last dependency kicks the worker. This cannot cause UAF on JQ if the
+        // associated job was forgotten because only submitted jobs can reach 0.
+        if self.nr_of_deps.fetch_sub(1, Relaxed) == 1 {
+            // The drop-order of JobQueue ensures that all DependencyWakers are
+            // cancelled before the JobQueue itself is dropped.
+            self.jq.check_start_run_worker();
+        }
+    }
+}
+
+/// A JobQueue job before it has been submitted.
+///
+/// This is only useful for registering dependencies on and for submitting it.
+pub struct Job<'a, T: JobQueueOps + Send + Sync> {
+    inner: Pin<UniqueArc<JobInternal<'a, T>>>,
+    fence_allocation: DriverFenceAllocation<'a, DriverDataWrapper<T>>,
+}
+
+impl<'a, T: JobQueueOps + Send + Sync> Job<'a, T> {
+    /// Add a dependency for the job.
+    ///
+    /// A JobQueue will only run a job once `fence` has been signaled.
+    ///
+    /// This action can race with the fence being signaled. An already signaled
+    /// dependency fence is treated as success, even if the fence was signaled
+    /// with an error. JobQueue will nevertheless try to run the job in the
+    /// latter case.
+    pub fn add_dependency(&mut self, fence: &Fence) -> Result {
+        self.inner.as_mut().with_project(|job| {
+            // If the registration below gets registered successfully, a signaling
+            // fence will decrement the atomic. That could race. Thus, increment in
+            // advance. Ordering is ensured thanks to the dma_fence backend.
+            job.nr_of_deps.fetch_add(1, Relaxed);
+
+            let dependency = try_pin_init!(Dependency {
+                links <- ListLinks::new(),
+                // SAFETY:
+                // We do not satisfy the *precise* safety requirement of not
+                // leaking the registration - because the job (`self`) could
+                // indeed leak.
+                //
+                // However, it is still safe because the registration lives as
+                // long as the job, whose atomic nr_of_deps can only reach 0
+                // after the job was submitted, thus, preventing UAF on the
+                // JobQueue.
+                registration <- unsafe {
+                    FenceCallbackRegistration::new(
+                        fence,
+                        DependencyWaker {
+                            nr_of_deps: job.nr_of_deps,
+                            jq: job.jq,
+                        },
+                    )
+                }
+            });
+            match UniqueArc::pin_init(dependency, GFP_KERNEL) {
+                Err(e) => {
+                    let _ = job.nr_of_deps.fetch_sub(1, Relaxed);
+                    if e == ENOENT {
+                        // Was already signaled.
+                        return Ok(());
+                    }
+                    return Err(e);
+                }
+                Ok(dep) => {
+                    job.dependencies.push_back(dep);
+                }
+            }
+
+            Ok(())
+        })
+    }
+
+    /// Submit the job.
+    ///
+    /// Returns a [`dma_buf::Fence`] on which the user can register callbacks.
+    /// The fence will be signaled once the job is completed through
+    /// [`JobQueue::complete_jobs_up_to_seqno`], which can happen immediately
+    /// after the job has been submitted.
+    ///
+    /// This function does all fence initialization under the JobQueue lock in
+    /// one go, including setting of the fence sequence number. Thus, it is
+    /// typically unnecessary (and advised against) to call this function with
+    /// a driver lock held.
+    pub fn submit(self) -> ARef<Fence> {
+        let jq = self.inner.jq;
+        jq.with_inner(|inner| {
+            // SAFETY: this is a lifetime transmute from `Job<'queue, T>` to
+            // `Job<'fctx, T>`.
+            //
+            // `job` internally holds a reference to `JobQueue`, while we are
+            // now moving `job` into `inner`, which may borrow from `fctx` but
+            // not the full `JobQueue`. So on surface this would be incorrect.
+            // However, as we drain `inner` inside `JobQueue::drop`, the
+            // reference is gone before any field is destructed.
+            let mut job = unsafe { core::mem::transmute::<Job<'_, T>, Job<'_, T>>(self) };
+
+            // The lock orders setting of the sequence number, so no driver lock is needed.
+            let mut inner = inner.lock();
+            let fence = job.fence_allocation.new_fence();
+            let ret_fence = ARef::from(fence.as_fence());
+
+            *job.inner.as_mut().project().fence = Some(fence);
+
+            // Job is submitted now. Signaling dependencies are now allowed to
+            // kick the worker.
+            let _ = job.inner.nr_of_deps.fetch_sub(1, Relaxed);
+
+            inner.waiting_jobs.push_back(job.inner);
+            drop(inner);
+            jq.check_start_run_worker();
+
+            ret_fence
+        })
+    }
+}
+
+#[pin_data]
+struct Dependency<'b, 'nr_of_deps, T: JobQueueOps + Send + Sync> {
+    #[pin]
+    links: ListLinks,
+    #[pin]
+    registration: FenceCallbackRegistration<DependencyWaker<'b, 'nr_of_deps, T>>,
+}
+
+impl_list_arc_safe! {
+    impl{'b, T: JobQueueOps + Send + Sync} ListArcSafe<0> for Dependency<'b, '_, T> { untracked; }
+}
+impl_list_item! {
+    impl{'b, T: JobQueueOps + Send + Sync} ListItem<0> for Dependency<'b, '_, T> {
+        using ListLinks { self.links }; }
+}
+
+#[pin_data]
+#[repr(C)]
+struct JobInternal<'b, T: JobQueueOps + Send + Sync> {
+    #[pin]
+    links: ListLinks,
+    cost: u32,
+    fence: Option<DriverFence<'b, DriverDataWrapper<T>>>,
+    dependencies: UniqueList<Dependency<'b, 'nr_of_deps, T>>,
+    nr_of_deps: Atomic<u32>,
+    jq: &'b JobQueue<T>,
+}
+
+impl_list_arc_safe! {
+    impl{'b, T: JobQueueOps + Send + Sync} ListArcSafe<0> for JobInternal<'b, T> { untracked; }
+}
+impl_list_item! {
+    impl{'b, T: JobQueueOps + Send + Sync} ListItem<0> for JobInternal<'b, T> {
+        using ListLinks { self.links }; }
+}
+
+struct RunWorker<'a, 'fctx, T: JobQueueOps + Send + Sync> {
+    srcu: &'a Srcu,
+    parked: &'a AtomicFlag,
+    inner: &'a SpinLockIrq<JobQueueInner<'fctx, T>>,
+    fctx: &'fctx FenceContext<DriverDataWrapper<T>>,
+}
+
+impl<T: JobQueueOps + Send + Sync> ScopedWorkItem for RunWorker<'_, '_, T> {
+    fn run(work: &ScopedWork<Self>) {
+        // Synchronize against revocation in `JobQueue::drop`.
+        let _lock_guard = work.srcu.read_lock();
+        if work.parked.load(Relaxed) {
+            return;
+        }
+
+        let mut jq = work.inner.lock();
+
+        while let Some(job) = jq.waiting_jobs.pop_front() {
+            // While we didn't hold the lock below for `run_job()`, it could be
+            // that a new job entered the waiting list which has an unfulfilled
+            // dependency.
+            if job.nr_of_deps.load(Relaxed) > 0 {
+                jq.waiting_jobs.push_front(job);
+                break;
+            }
+            let new_capacity = jq.capacity as i64 - i64::from(job.cost);
+            if new_capacity < 0 {
+                jq.waiting_jobs.push_front(job);
+                break;
+            }
+            *jq.as_mut().project().capacity = new_capacity as u64;
+
+            let fence = job.fence.as_ref().expect("fence not present");
+            let seqno = fence.as_fence().seqno();
+            let runnable_job = JobRunnable {
+                seqno,
+                data: fence.deref(),
+            };
+
+            drop(jq); // Release lock.
+            T::run_job(work.fctx, runnable_job);
+            jq = work.inner.lock(); // Retake lock.
+
+            // run_job() above needs to be called without lock protection. Thus,
+            // it is possible that the driver instructed completion right before
+            // we could re-take the lock.
+            if jq.last_completed >= seqno {
+                *jq.as_mut().project().capacity += u64::from(job.cost);
+                fence.signal(Ok(()));
+
+                // Drop here directly if possible. Otherwise, let the DropWorker
+                // take care of it.
+                if core::mem::needs_drop::<T::JobDataType>() {
+                    jq.drop_list.push_back(job);
+                }
+            } else {
+                jq.running_jobs.push_back(job);
+            }
+        }
+    }
+}
+
+struct DropWorker<'a, 'fctx, T: JobQueueOps + Send + Sync> {
+    inner: &'a SpinLockIrq<JobQueueInner<'fctx, T>>,
+}
+
+impl<T: JobQueueOps + Send + Sync> ScopedWorkItem for DropWorker<'_, '_, T> {
+    fn run(work: &ScopedWork<Self>) {
+        let mut jq_locked = work.inner.lock();
+
+        while let Some(job) = jq_locked.drop_list.pop_front() {
+            drop(jq_locked);
+            drop(job);
+            jq_locked = work.inner.lock();
+        }
+    }
+}
+
+#[pin_data]
+struct JobQueueInner<'a, T: JobQueueOps + Send + Sync> {
+    #[pin]
+    /// List of jobs waiting to be run on the hardware.
+    waiting_jobs: UniqueList<JobInternal<'a, T>>,
+    #[pin]
+    /// List of jobs that are currently executing on the hardware.
+    running_jobs: UniqueList<JobInternal<'a, T>>,
+    /// The queue's current capacity.
+    capacity: u64,
+    /// The sequence number of the last completed job.
+    last_completed: u64,
+    #[pin]
+    /// Jobs that have finished executing and whose payload data `T` implements
+    /// `Drop`. These jobs are dropped in process context, which also allows for
+    /// their [`dma_buf::DriverFence`]s to implement the necessary RCU grace
+    /// period delay.
+    ///
+    /// If `Drop` is not implemented, this list is unused and the elements drop
+    /// directly in [`JobQueue::complete_jobs_up_to_seqno`].
+    ///
+    /// Should the JobQueue drop and the [`DropWorker`] not yet have dropped all
+    /// jobs, that is no problem because the JobQueue itself drops in process
+    /// context.
+    drop_list: UniqueList<JobInternal<'a, T>>,
+}
+
+/// A JobQueue.
+///
+/// When you drop your JobQueue, it might still attempt for one RCU grace period
+/// to submit more jobs via the [`JobQueueOps::run_job`] callback into your driver.
+///
+/// Dropping a JobQueue results in all remaining waiting jobs'
+/// fences being signaled with ECANCELED. All remaining running jobs' fences get
+/// signaled with the error you provided in [`JobQueue::set_error()`], or
+/// ECANCELED otherwise.
+///
+/// A JobQueue must only ever drop in non-atomic / process context.
+///
+/// # Examples
+///
+/// ```
+/// use core::ops::Deref;
+///
+/// use kernel::{
+///     dma_buf::*,
+///     drm::{
+///         JobQueue,
+///         JobQueueOps,
+///         JobRunnable, //
+///     },
+///     str::CString,
+///     time::{
+///         delay::fsleep,
+///         Delta, //
+///     }, //
+/// };
+///
+/// let driver_name = CString::try_from_fmt(fmt!("dummy_driver"))?;
+/// let timeline_name = CString::try_from_fmt(fmt!("dummy_timeline"))?;
+///
+/// #[pin_data]
+/// struct FenceContextData {}
+///
+/// impl FenceContextData {
+///     fn new() -> impl PinInit<Self> {
+///         pin_init!(Self {})
+///     }
+/// }
+///
+/// impl FenceContextOps for FenceContextData {
+///     type FenceDataType = ();
+/// }
+///
+/// let fctx_data = FenceContextData::new();
+///
+/// let fctx = KBox::pin_init(
+///     FenceContext::new(0, c"dependency_driver", c"dependency_timeline", fctx_data),
+///     GFP_KERNEL
+/// )?;
+///
+/// let dependency1 = fctx.new_fence_allocation(())?.new_fence();
+/// let dependency2 = fctx.new_fence_allocation(())?.new_fence();
+///
+/// #[pin_data]
+/// struct JqData {}
+///
+/// impl JqData {
+///     fn new() -> impl PinInit<Self> {
+///         pin_init!(Self {})
+///     }
+/// }
+///
+/// struct Payload { }
+///
+/// impl JobQueueOps for JqData {
+///     type JobDataType = Payload;
+///
+///     fn run_job<'a>(&self, job: JobRunnable<'a, Payload>) {
+///         pr_info!("Job Nr. {} gets run now.\n", job.seqno);
+///     }
+/// }
+///
+/// let jq_data = JqData::new();
+/// let jq = KBox::pin_init(
+///     JobQueue::new(driver_name, timeline_name, 1000, jq_data),
+///     GFP_KERNEL
+/// )?;
+///
+///
+/// let mut job1 = jq.new_job(1, Payload { })?;
+/// let mut job2 = jq.new_job(1, Payload { })?;
+///
+/// job1.add_dependency(dependency1.as_fence())?;
+/// job1.add_dependency(dependency2.as_fence())?;
+///
+/// job2.add_dependency(dependency2.as_fence())?;
+///
+/// struct Callback {
+///     seqno: u64,
+/// }
+///
+/// impl FenceCallback for Callback {
+///     fn on_signal(&mut self, res: Result) {
+///         pr_info!("Job Nr. {} got completed with status: {:?}.\n", self.seqno, res);
+///     }
+/// }
+///
+/// let done_fence1 = job1.submit();
+/// let done_fence2 = job2.submit();
+///
+/// let cb = Callback { seqno: done_fence2.seqno() };
+/// // SAFETY: The registration is not leaked.
+/// let reg = unsafe { FenceCallbackRegistration::new(&done_fence2, cb) };
+/// let reg = KBox::new(reg, GFP_KERNEL)?;
+///
+/// dependency1.signal(Ok(()));
+/// dependency2.signal(Ok(()));
+///
+/// // Give the RunWorker some time to run the jobs.
+/// fsleep(Delta::from_millis(100));
+/// jq.complete_jobs_up_to_seqno(done_fence2.seqno());
+///
+/// match done_fence2.status() {
+///     FenceStatus::Signaled(status) => return status,
+///     FenceStatus::Unsignaled => return Err(EAGAIN),
+/// }
+///
+/// Ok::<(), Error>(())
+/// ```
+#[pin_data(PinnedDrop)]
+pub struct JobQueue<T: JobQueueOps + Send + Sync> {
+    /// The queue's maximum available capacity.
+    max_capacity: u64,
+    /// The work queue on which the JobQueue drops the user's payload data.
+    drop_queue: OwnedQueue,
+    #[pin]
+    #[uses('_: invariant, 'parked: invariant, 'srcu: invariant)]
+    /// A worker for dropping the queue's jobs.
+    drop_worker: ScopedWork<DropWorker<'inner, 'fctx, T>>,
+    /// The work queue on which the JobQueue runs jobs ([`JobQueueOps::run_job`]).
+    run_queue: OwnedQueue,
+    #[pin]
+    #[uses('_: invariant)]
+    /// The worker submitting the queue's ready jobs.
+    run_worker: ScopedWork<RunWorker<'inner, 'fctx, T>>,
+    #[pin]
+    #[uses('fctx: invariant)]
+    /// The inner queue.
+    inner: SpinLockIrq<JobQueueInner<'fctx, T>>,
+    #[pin]
+    /// The [`dma_buf::FenceContext`] on which the queue creates
+    /// [`dma_buf::DriverFence`]s for the jobs.
+    fctx: FenceContext<DriverDataWrapper<T>>,
+    /// Needed for the park() and unpark() features.
+    parked: AtomicFlag,
+    #[pin]
+    /// Needed for the `parked` mechanism, since [`JobQueueOps::run_job`] might
+    /// sleep.
+    srcu: Srcu,
+    /// The error with which the JobQueue will signal still running jobs when it
+    /// drops.
+    err: Error,
+}
+
+// SAFETY: The JobQueue is locked and pinned.
+unsafe impl<T: JobQueueOps + Send + Sync> Sync for JobQueue<T> {}
+// SAFETY: The JobQueue is locked and pinned.
+unsafe impl<T: JobQueueOps + Send + Sync> Send for JobQueue<T> {}
+
+/// Object passed to the driver to run a job.
+pub struct JobRunnable<'a, T> {
+    /// The job's sequence number.
+    pub seqno: u64,
+    /// The associated job data.
+    pub data: &'a T,
+    // TODO: Pass the driver the failed dependency fences or their error codes here.
+}
+
+/// Ops for the JobQueue.
+pub trait JobQueueOps {
+    /// The type of the data passed over in [`JobQueue::new_job`].
+    type JobDataType: Send + Sync;
+
+    /// Instructs the driver to run this job.
+    ///
+    /// JobQueue calls this callback from process context without any locks
+    /// held, thus, the driver is permitted to sleep in its implementation.
+    /// However, `run_job()` is, of course, in the dma_fence critical path,
+    /// which is why you must not perform sleeping allocations here.
+    ///
+    /// The driver must be aware that JobQueue trusts on its credit count system
+    /// for this operation to be infallible.
+    ///
+    /// This callback might be called while the driver is in the process of
+    /// dropping the JobQueue, but will never be called afterwards.
+    fn run_job<'a>(&self, job: JobRunnable<'a, Self::JobDataType>);
+}
+
+#[pin_data]
+struct DriverDataWrapper<T: JobQueueOps + Send + Sync> {
+    #[pin]
+    data: T,
+}
+
+impl<T: JobQueueOps + Send + Sync> Deref for DriverDataWrapper<T> {
+    type Target = T;
+
+    fn deref(&self) -> &Self::Target {
+        &self.data
+    }
+}
+
+impl<T: JobQueueOps + Send + Sync> DriverDataWrapper<T> {
+    fn new<E>(data: impl PinInit<T, E>) -> impl PinInit<Self, E>
+    where
+        Error: From<E>,
+        E: From<Infallible>,
+    {
+        try_pin_init!(Self {
+            data <- data,
+        }? E)
+    }
+}
+
+impl<T: JobQueueOps + Send + Sync> FenceContextOps for DriverDataWrapper<T> {
+    type FenceDataType = T::JobDataType;
+}
+
+impl<T: JobQueueOps + Send + Sync> Deref for JobQueue<T> {
+    type Target = T;
+
+    fn deref(&self) -> &Self::Target {
+        self.fctx.deref()
+    }
+}
+
+impl<T: JobQueueOps + Send + Sync> JobQueue<T> {
+    /// Create a new JobQueue.
+    pub fn new<E>(
+        // TODO: pass these as &CStr. Figure out how to get the lifetimes for PinInit right.
+        driver_name: CString,
+        timeline_name: CString,
+        capacity_param: u64,
+        data: impl PinInit<T, E>,
+    ) -> impl PinInit<Self, Error>
+    where
+        Error: From<E>,
+        E: From<Infallible>,
+    {
+        try_pin_init!(Self {
+            srcu <- new_srcu!(),
+            parked: AtomicFlag::new(false),
+            max_capacity: capacity_param,
+            err: ECANCELED,
+            // The initial sequence number always starts at 1, since hardware is
+            // initialized to 0. Also makes internal logic easier.
+            fctx <- FenceContext::new(1, &driver_name, &timeline_name,
+                                      DriverDataWrapper::new(data)),
+            inner <- new_spinlock_irq!(try_pin_init!(JobQueueInner {
+                capacity: capacity_param,
+                last_completed: 0,
+                waiting_jobs: UniqueList::new(),
+                running_jobs: UniqueList::new(),
+                drop_list: UniqueList::new(),
+            })),
+            run_queue: Queue::new_unbound().mem_reclaim().build(c"JobQueueRunQueue")?,
+            // SAFETY: The worker does not get leaked. It drops together with JobQueue.
+            run_worker <- unsafe { new_scoped_work!("JobQueueRunWorker", Ok(RunWorker {
+                srcu: Pin::get_ref(srcu),
+                parked,
+                inner: Pin::get_ref(inner),
+                fctx: Pin::get_ref(fctx),
+            })) },
+            drop_queue: Queue::new_unbound().build(c"JobQueueDropQueue")?,
+            // SAFETY: The worker does not get leaked. It drops together with JobQueue.
+            drop_worker <- unsafe { new_scoped_work!("JobQueueDropWorker", Ok(DropWorker {
+                inner: Pin::get_ref(inner)
+            })) },
+        })
+    }
+
+    /// Give the unique identifier for this JobQueue.
+    ///
+    /// This corresponds to the JobQueue's underlying [`dma_buf::FenceContext`].
+    /// It is unique for all JobQueues in the entire system.
+    pub fn id(&self) -> u64 {
+        self.fctx.id()
+    }
+
+    /// Create a new job.
+    ///
+    /// The `cost` specified here is what JobQueue subtracts from its capacity
+    /// to determine whether a job is runnable, i.e., has space on the GPU ring.
+    ///
+    /// The `data` contained by a job will be borrowed back to the driver once
+    /// the job shall be run through [`JobQueueOps::run_job`].
+    pub fn new_job<'a>(&'a self, cost: u32, data: T::JobDataType) -> Result<Job<'a, T>> {
+        if u64::from(cost) > self.max_capacity {
+            return Err(EINVAL);
+        }
+
+        let fence_allocation = self.fctx.new_fence_allocation(data)?;
+        let job = try_pin_init!(JobInternal {
+            links <- ListLinks::new(),
+            cost,
+            fence: None,
+            // Initialize to 1 to prevent UAF for forgotten jobs. See
+            // [`Job::add_dependency()`].
+            nr_of_deps: Atomic::new(1),
+            dependencies: UniqueList::new(),
+            jq: &self,
+        });
+
+        let inner = UniqueArc::pin_init(job, GFP_KERNEL)?;
+
+        Ok(Job {
+            inner,
+            fence_allocation,
+        })
+    }
+
+    fn check_start_run_worker(&self) {
+        // SAFETY: `self` is valid.
+        let this = unsafe { Pin::new_unchecked(self) };
+        this.with_project_ref(|project| {
+            project
+                .run_queue
+                .enqueue_scoped(Pin::get_ref(project.run_worker));
+        })
+    }
+
+    fn check_start_drop_worker(&self) {
+        // SAFETY: `self` is valid.
+        let this = unsafe { Pin::new_unchecked(self) };
+        this.with_project_ref(|project| {
+            project
+                .drop_queue
+                .enqueue_scoped(Pin::get_ref(project.drop_worker));
+        })
+    }
+
+    /// Prevent the JobQueue from further calling [`JobQueueOps::run_job()`].
+    ///
+    /// The JobQueue will not call [`JobQueueOps::run_job()`] anymore after this
+    /// function returned, until you call [`JobQueue:unpark()`].
+    ///
+    /// Note that you should not use this function unless you have a very good
+    /// reason to.
+    ///
+    /// This must be called in non-atomic context.
+    pub fn park(&self) {
+        self.parked.store(true, Relaxed);
+        self.srcu.synchronize();
+    }
+
+    /// Unpark the JobQueue again.
+    ///
+    /// Note that you should not use this function unless you have a very good
+    /// reason to.
+    ///
+    /// This is the counterpart to [`JobQueue::park()`].
+    pub fn unpark(&self) {
+        self.parked.store(false, Relaxed);
+        // The workqueue barriers ensure ordering.
+        self.check_start_run_worker();
+    }
+
+    /// Complete all the jobs in the queue's running_list, up to `seqno`.
+    ///
+    /// This signals the jobs' fences and schedules dropping of both the [`Job`]
+    /// and its [`DriverFence`].
+    ///
+    /// This signals the associated fences with the `Ok(())` status.
+    ///
+    /// This function tells the implementation that there is now more capacity
+    /// for more jobs to be run.
+    pub fn complete_jobs_up_to_seqno(&self, seqno: u64) {
+        self.with_inner(|inner| {
+            let needs_drop = core::mem::needs_drop::<T::JobDataType>();
+            let mut jq_locked = inner.lock();
+            let mut jq = jq_locked.as_mut().project();
+
+            if seqno < *jq.last_completed {
+                return;
+            }
+
+            while let Some(mut job) = jq.running_jobs.pop_front() {
+                if job
+                    .as_mut()
+                    .project()
+                    .fence
+                    .as_mut()
+                    .expect("fence not present")
+                    .as_fence()
+                    .seqno()
+                    > seqno
+                {
+                    jq.running_jobs.push_front(job);
+                    break;
+                }
+
+                *jq.capacity += u64::from(job.cost);
+
+                let fence = job.fence.as_ref().expect("fence not present");
+                fence.signal(Ok(()));
+
+                if needs_drop {
+                    jq.drop_list.push_back(job);
+                }
+                // Otherwise, job is dropped here directly. Its fence won't perform
+                // an RCU grace period wait.
+            }
+
+            // This enables the RunWorker to complete a job that is not yet
+            // in 'running_jobs', in case of a race against the lock.
+            *jq.last_completed = seqno;
+            drop(jq_locked);
+
+            self.check_start_run_worker();
+            if needs_drop {
+                self.check_start_drop_worker();
+            }
+        })
+    }
+
+    /// Set the error with which this JobQueue will signal all running jobs'
+    /// fences. (The jobs on the waiting_list will all complete with ECANCELED
+    /// as their error)
+    pub fn set_error(mut self: Pin<&mut Self>, error: Error) {
+        *self.as_mut().project().err = error;
+    }
+}
+
+#[pinned_drop]
+impl<T: JobQueueOps + Send + Sync> PinnedDrop for JobQueue<T> {
+    fn drop(self: Pin<&mut Self>) {
+        // Prevent the RunWorker from moving more jobs to `running_jobs`.
+        self.parked.store(true, Relaxed);
+        self.srcu.synchronize();
+        self.with_inner(|inner| {
+            let mut inner_locked = inner.lock();
+            let drop_list = core::mem::take(&mut inner_locked.drop_list);
+            let waiting_jobs = core::mem::take(&mut inner_locked.waiting_jobs);
+            let mut running_jobs = core::mem::take(&mut inner_locked.running_jobs);
+
+            drop(inner_locked);
+
+            while let Some(job) = running_jobs.pop_front() {
+                let fence = job.fence.as_ref().expect("fence not present");
+                fence.signal(Err(self.err));
+            }
+
+            drop(drop_list);
+            drop(waiting_jobs);
+            drop(running_jobs);
+        })
+    }
+}
rust/kernel/drm/mod.rs +4 -0
index 7fcf2465a82e..8a29c8d6805f 100644
@@ -8,6 +8,7 @@
 pub mod gem;
 pub mod gpuvm;
 pub mod ioctl;
+pub mod job_queue;
 
 pub use self::device::Device;
 pub use self::device::DeviceContext;
@@ -20,6 +21,9 @@
 pub use self::driver::DriverInfo;
 pub use self::driver::Registration;
 pub use self::file::File;
+pub use self::job_queue::JobQueue;
+pub use self::job_queue::JobQueueOps;
+pub use self::job_queue::JobRunnable;
 
 pub(crate) mod private {
     pub trait Sealed {}
Signature · 1 line
2.56.0
author maintainer
#13 lore raw

PATCH v2 10/10 MAINTAINERS: Add drm::JobQueue to drm_sched's entry

In reply to Philipp Stanner

The DRM subsystem now provides drm::JobQueue, a Rust dependency manager and load balancer for GPUs with firmware scheduling. Since it resides in the same problem space as drm_sched, it is reasonable to maintain it through a common entry.

---
 MAINTAINERS | 1 +
 1 file changed, 1 insertion(+)
MAINTAINERS +1 -0
index 19818be10616..5cb896c4e0eb 100644
@@ -9267,6 +9267,7 @@ T:	git https://gitlab.freedesktop.org/drm/misc/kernel.git
 F:	drivers/gpu/drm/scheduler/
 F:	include/drm/gpu_scheduler.h
 F:	include/drm/spsc_queue.h
+F:	rust/kernel/drm/job_queue.rs
 
 DRM GPUVM
 M:	Danilo Krummrich <[email protected]>
Signature · 1 line
2.56.0
#7 lore raw

Re: [PATCH v2 06/10] rust: DmaFence: Replace call_rcu() with cond_synchronize_rcu()

In reply to Philipp Stanner
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [High] rust: dma_fence: T::FenceDataType leak in DriverFence::drop() --

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [High] rust: dma_fence: T::FenceDataType leak in DriverFence::drop() --

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

rust: DmaFence: Replace call_rcu() with cond_synchronize_rcu()

This commit replaces deferred call_rcu() destruction of DriverFence data with an inline cond_synchronize_rcu() wait in DriverFence::drop() so that fence payloads are dropped in process context.

Quoted 4 lines
rust/kernel/dma_buf/dma_fence.rs +0 -0
index c04b68fe67fe3..20dadbde4eb9d 100644

[ ... ]

Quoted 74 lines
rust/kernel/dma_buf/dma_fence.rs +20 -47
@@ -988,59 +995,31 @@ fn drop(&mut self) {
             return;
         }
 
-        // SAFETY: Valid because `self` is valid.
-        let rcu_head_ptr = unsafe { &raw mut (*self.data.as_ptr()).rcu_head };
+        // SAFETY: `self` is valid. No one can access the cookie anymore because
+        // we are dropping.
+        let rcu_cookie = unsafe { *self.data.as_ref().synchronize_rcu_cookie.get() };
 
-        // SAFETY: `call_rcu()` is always safe to be called. `rcu_head_ptr` was
-        // created validly above. The module must perform a `synchronize_rcu()`
-        // or `rcu_barrier()` call to guard against module unload.
-        unsafe { bindings::call_rcu(rcu_head_ptr, Some(drop_driver_fence_data::<T>)) };
-    }
-}
+        // Make sure none of the fence backend_ops can access fence-data anymore.
+        //
+        // TODO:
+        // This would not be necessary if the C dma_fence backend were using a
+        // spinlock to properly synchronize its signaled state. Fix it in C and
+        // then remove synchronize_rcu().
+        if rcu_cookie != 0 {
+            // SAFETY: The if-else checks whether the cookie was validly
+            // initialized when this fence signaled.
+            unsafe { cond_synchronize_rcu(rcu_cookie) };
+        } else {
+            // The user never signaled this fence. We don't know the grace period.
+            synchronize_rcu();
+        }
 
-// TODO:
-// The entire call_rcu() mechanism in the drop above and the code below would be
-// unnecessary if C's dma_fence_signal() could be reworked in a way that after it
-// ran, the caller knows that no fence_ops callbacks can be running anymore.
-// In other words, if the dma_fence backend would use its spinlock for full
-// synchronization.
-//
-// Then we could move the drop_in_place() and dma_fence_put() upwards into the
-// drop() implementation and call it a day.
+        // SAFETY: Valid because `self` is valid. RCU above ensures that all
+        // accessors are gone.
+        unsafe { drop_in_place(&raw mut self.data) };
 
-/// Finally really drop this `DriverFence<T>`
-///
-/// # Safety
-///
-/// `head` references the `rcu_head` field of an `DriverFenceData<T>`. All
-/// accessors to that `DriverFenceData<T>` must be gone by now. This must be
-/// ensured by signalling the associated `DriverFence<T>` and then waiting
-/// for a grace period until calling this function here.
-unsafe extern "C" fn drop_driver_fence_data<T: Send + Sync + FenceContextOps>(
-    head: *mut bindings::callback_head,
-) {
-    // SAFETY: Caller provides a pointer to the `rcu_head` field of a `DriverFenceData<C>`.
-    let fence_data = unsafe { container_of!(head, DriverFenceData<'_, T>, rcu_head) };
-
-    // SAFETY: `fence_data` was created validly above. All the fence's data will
-    // only drop below, but the raw pointer to the raw C `dma_fence` remains
-    // valid because the reference count is only decremented at the end of the
-    // function.
-    let fence = unsafe { (*fence_data).inner.inner.get() };
-
-    // SAFETY: `fence_data` was created validly above. The user has already
-    // dropped the only conventional accessor to the user data, the `DriverFence`,
-    // one grace period ago. All accessors are gone now.
-    unsafe { drop_in_place(&raw mut (*fence_data).data) };
-
-    // The inner `Fence` explicitly does not get dropped because there may be
-    // many more users / consumers, each holding their own reference.
-
-    // SAFETY: Once a `DriverFence` is initialized, the inner `fence` is valid
-    // and initialized. It is valid until the refcount drops to 0, which can

rust/kernel/dma_buf/dma_fence.rs fn drop(&mut self) { · line 1025

Quoted 10 lines
rust/kernel/dma_buf/dma_fence.rs +4 -5
-    // earliest happen once we drop the `DriverFence`'s reference here.
-    unsafe { bindings::dma_fence_put(fence) };
-
-    // The actual memory the data associated with a `DriverFence` lives in
-    // gets freed by the C dma_fence backend once the fence's refcount reaches 0.
+        // SAFETY: Valid because `self` is valid. This is the initial reference
+        // from when this `DriverFence` was created.
+        unsafe { bindings::dma_fence_put(self.as_raw()) };
+    }
 }

[Severity: High]
Does drop_in_place(&raw mut self.data) leak the inner T::FenceDataType payload?

self.data on DriverFence is a NonNull<DriverFenceData<'a, T>>, which has no Drop implementation, so drop_in_place(&raw mut self.data) is a no-op and (*self.data.as_ptr()).data is never dropped before dma_fence_put() releases the allocation. Note also that self.as_raw() creates a shared reference &DriverFenceData<'a, T>, so the raw dma_fence pointer should be obtained before dropping (*self.data.as_ptr()).data in place.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=6
#9 lore raw

Re: [PATCH v2 07/10] rust: DmaFence: Replace is_signaled() with status()

In reply to Philipp Stanner
Thank you for your contribution! Sashiko AI review found 2 potential issues to consider: - [Medium] rust: dma_fence: unordered error read and dropped lock in Fence::status() - [Low] rust: dma_fence…

Thank you for your contribution! Sashiko AI review found 2 potential issues to consider:
- [Medium] rust: dma_fence: unordered error read and dropped lock in Fence::status()
- [Low] rust: dma_fence: missing #[inline] on Fence::status() and Fence::__status()
--

commit 26df0fcba82116d2e43f022188ec8d892405d6cd
Author: Philipp Stanner <[email protected]>

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

This commit replaces Fence::is_signaled() with Fence::status() and introduces FenceStatus so callers check the fence error code when querying whether a fence has been signaled.

Quoted 68 lines
rust/kernel/dma_buf/dma_fence.rs +28 -30
index 20dadbde4eb9d..09bebf9c1e4ee 100644
@@ -510,40 +510,44 @@ unsafe impl Send for Fence {}
 // SAFETY: Fences are literally designed to be shared between threads.
 unsafe impl Sync for Fence {}
 
+/// Fence-Status queried through [`Fence::status()`].
+#[derive(Debug)]
+pub enum FenceStatus {
+    /// The fence is not yet signaled.
+    Unsignaled,
+    /// The fence is signaled. Might have been signaled with an error.
+    Signaled(Result),
+}
+
 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)
+    }
+
+    /// 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) -> FenceStatus {
+        // SAFETY: `self` is valid.

rust/kernel/dma_buf/dma_fence.rs unsafe impl Send for Fence {} · line 551

Quoted 10 lines
rust/kernel/dma_buf/dma_fence.rs +7 -1
+        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 FenceStatus::Signaled(status);
+        }
 
-        ret
+        FenceStatus::Unsignaled
     }

[Severity: Medium]
Can Fence::status() read (*self.as_raw()).error without load-to-load ordering against DMA_FENCE_FLAG_SIGNALED_BIT and observe FenceStatus::Signaled(Ok(())) on a fence signaled with an error?

On the fast path, dma_fence_is_signaled() checks dma_fence_test_signaled_flag(), which calls an unordered test_bit():

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

Because test_bit() has no acquire semantics and a control dependency does not order load-to-load, a weakly-ordered CPU can reorder the non-atomic read of fence->error in Fence::__status() before the read of fence->flags:

CPU0 CPU1
DriverFence::signal(Err(...)) Fence::status()
dma_fence_lock_irqsave() dma_fence_is_signaled()

                                      /* speculates fence->error == 0 */
  fence->error = err;
  dma_fence_signal_locked()
    test_and_set_bit(SIGNALED, ...)
                                      test_bit(SIGNALED, ...) == true
                                    self.__status()
                                      reads stale error == 0  <-- data race

Removing self.lock() (which C's dma_fence_get_status() takes around dma_fence_get_status_locked()) also drops the guarantee previously provided by Fence::is_signaled() that all registered fence callbacks have finished running before the fence is observed as signaled. Acquiring self.lock() before reading self.__status() would both order the error read and preserve callback completion synchronization.

[Severity: Low]
In kernel crate abstractions, small functions and functions that forward to C bindings should be marked with #[inline] (as the removed Fence::is_signaled() was). Fence::__status() and Fence::status() are missing #[inline].

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=7
#12 lore raw

Re: [PATCH v2 09/10] rust: drm: Add JobQueue

In reply to Philipp Stanner
Thank you for your contribution! Sashiko AI review found 12 potential issues to consider: - [High] rust: dma_fence: payload destructor skipped in DriverFence::drop() - [High] rust: drm: unsound…

Thank you for your contribution! Sashiko AI review found 12 potential issues to consider:
- [High] rust: dma_fence: payload destructor skipped in DriverFence::drop()
- [High] rust: drm: unsound lifetime transmute, aliasing, and teardown in JobQueue
- [High] rust: drm: fence signaling and job drop under SpinLockIrq in JobQueue
- [High] rust: drm: missing Signed-off-by trailer for Co-developed-by author
- [Medium] rust: drm: unscheduled DropWorker in RunWorker::run() on completion race
- [Medium] rust: drm: unsignaled waiting_jobs and serial RCU waits in JobQueue::drop()
- [Medium] rust: drm: RunWorker::run() does not re-check parked inside job loop
- [Medium] rust: drm: signed i64 cast of u64 capacity in RunWorker::run()
- [Medium] drm: rust: missing Release-Acquire ordering on nr_of_deps in job_queue
- [Low] rust: drm: spurious worker wakeups in complete_jobs_up_to_seqno()
- [Low] rust: drm: JobQueue doctest passes PinInit closure to KBox::new()
- [Low] rust: drm: non-vertical imports, broken doc links, and missing #[inline]
--

commit 1aa6ded0089a768fb2d0e487607dde049d292e4e
Author: Philipp Stanner <[email protected]>

rust: drm: Add JobQueue

This commit adds JobQueue, a Rust component for managing GPU job dependencies, credit accounting, and dma_fence lifetimes for GPUs with firmware scheduling.

Quoted 4 lines

(^ waiting for Gary to sign-off)

[Severity: High]
Per Documentation/process/submitting-patches.rst, a Co-developed-by trailer must be immediately followed by the co-author's Signed-off-by trailer, with the submitter's Signed-off-by last, and the draft note removed before merging.

Quoted 6 lines
rust/kernel/drm/job_queue.rs new file +0 -0
new file mode 100644
index 0000000000000..3d3d78fda5514
@@ -0,0 +1,863 @@

[ ... ]

Quoted 4 lines
rust/kernel/drm/job_queue.rs new file +4 -0
+//! Since jobs might contain data that must not drop in atomic context, and
+//! since jobs' [`dma_buf::DriverFence`]s perform a call to
+//! [`rcu::synchronize_rcu()`], they are dropped through a work item if [`Drop`]
+//! is implemented for the job's payload data.

[ ... ]

Quoted 32 lines
rust/kernel/drm/job_queue.rs new file +32 -0
+use kernel::{
+    dma_buf::dma_fence::{
+        DriverFence,
+        DriverFenceAllocation,
+        Fence,
+        FenceCallback,
+        FenceCallbackRegistration,
+        FenceContext,
+        FenceContextOps, //
+    },
+    list::{
+        impl_list_arc_safe,
+        impl_list_item,
+        List,
+        ListItem,
+        ListLinks, //
+    },
+    new_srcu,
+    prelude::*,
+    str::CString,
+    sync::{
+        aref::ARef,
+        atomic::{
+            Atomic,
+            Relaxed, //
+        },
+        new_spinlock_irq,
+        SpinLockIrq, //
+    }, //
+    sync::{
+        atomic::AtomicFlag,
+        Srcu, //

rust/kernel/drm/job_queue.rs line 113

Quoted 10 lines
rust/kernel/drm/job_queue.rs new file +10 -0
+    },
+    sync::{Arc, UniqueArc},
+    workqueue::{
+        new_scoped_work,
+        OwnedQueue,
+        Queue,
+        ScopedWork,
+        ScopedWorkItem, //
+    }, //
+};

[Severity: Low]
This isn't a bug, but the kernel::sync imports are split across three separate sync:: blocks with sync::{Arc, UniqueArc} on a single line rather than following the vertical import style in Documentation/rust/coding-guidelines.rst.

Also, the rustdoc intra-doc links to dma_buf::FenceContext, dma_buf::DriverFence, dma_buf::Fence, and rcu::synchronize_rcu() do not resolve because dma_buf and rcu are not in scope (and JobQueue::park()'s doc comment has a single-colon typo in [JobQueue:unpark()]). Finally, the small wrapper and accessor methods in this module (such as UniqueList's methods, DriverDataWrapper::deref, DriverDataWrapper::new, JobQueue::deref, JobQueue::id, and JobQueue::set_error) are missing #[inline].

[ ... ]

Quoted 11 lines
rust/kernel/drm/job_queue.rs new file +11 -0
+impl<'b, T: JobQueueOps + Send + Sync> FenceCallback for DependencyWaker<'b, '_, T> {
+    fn on_signal(&mut self, _res: Result) {
+        // Last dependency kicks the worker. This cannot cause UAF on JQ if the
+        // associated job was forgotten because only submitted jobs can reach 0.
+        if self.nr_of_deps.fetch_sub(1, Relaxed) == 1 {
+            // The drop-order of JobQueue ensures that all DependencyWakers are
+            // cancelled before the JobQueue itself is dropped.
+            self.jq.check_start_run_worker();
+        }
+    }
+}

[ ... ]

Quoted 22 lines
rust/kernel/drm/job_queue.rs new file +22 -0
+    pub fn submit(self) -> ARef<Fence> {
+        let jq = self.inner.jq;
+        jq.with_inner(|inner| {
+            // SAFETY: this is a lifetime transmute from `Job<'queue, T>` to
+            // `Job<'fctx, T>`.
+            //
+            // `job` internally holds a reference to `JobQueue`, while we are
+            // now moving `job` into `inner`, which may borrow from `fctx` but
+            // not the full `JobQueue`. So on surface this would be incorrect.
+            // However, as we drain `inner` inside `JobQueue::drop`, the
+            // reference is gone before any field is destructed.
+            let mut job = unsafe { core::mem::transmute::<Job<'_, T>, Job<'_, T>>(self) };
+
+            // The lock orders setting of the sequence number, so no driver lock is needed.
+            let mut inner = inner.lock();
+            let fence = job.fence_allocation.new_fence();
+            let ret_fence = ARef::from(fence.as_fence());
+
+            *job.inner.as_mut().project().fence = Some(fence);
+
+            // Job is submitted now. Signaling dependencies are now allowed to
+            // kick the worker.

rust/kernel/drm/job_queue.rs line 269

Quoted 10 lines
rust/kernel/drm/job_queue.rs new file +10 -0
+            let _ = job.inner.nr_of_deps.fetch_sub(1, Relaxed);
+
+            inner.waiting_jobs.push_back(job.inner);
+            drop(inner);
+            jq.check_start_run_worker();
+
+            ret_fence
+        })
+    }
+}

[Severity: High]
Is erasing the &JobQueue<T> borrow lifetime in Job::submit() sound while JobInternal and DependencyWaker still hold jq: &JobQueue<T>?

Because Job::submit() consumes Job<'queue, T>, the caller can obtain Pin<&mut JobQueue<T>> for JobQueue::set_error() or PinnedDrop::drop() while DependencyWaker callbacks in waiting_jobs are still active and can dereference self.jq (&JobQueue<T>) concurrently on another CPU, violating Rust's aliasing rules (and re-enqueuing run_worker during drop after srcu.synchronize() has already completed).

In addition, DropWorker::run() pops a job from drop_list and releases inner.lock() before calling drop(job), without taking srcu.read_lock() and without JobQueue::drop() flushing drop_worker:

CPU0 (DropWorker::run) CPU1 (JobQueue::drop)
---------------------- ---------------------
lock(inner)
job = drop_list.pop_front()
unlock(inner)

                                  parked.store(true)
                                  srcu.synchronize()
                                  drain inner lists
                                  // PinnedDrop::drop() returns;
                                  // JobQueue fields are dropped

drop(job) <-- job still holds &JobQueue and &FenceContext

Two other lifetime issues affect teardown: in struct JobQueue, drop_queue and run_queue (OwnedQueue) are declared before drop_worker and run_worker (ScopedWork), so Rust drops the queues before cancelling their ScopedWork items; and if an unsubmitted Job with a registered dependency is forgotten via core::mem::forget (as discussed in Job::add_dependency()) and the JobQueue is later dropped, a signal on that fence still invokes DependencyWaker::on_signal(&mut self) while self.jq is a dangling &JobQueue<T>.

[ ... ]

rust/kernel/drm/job_queue.rs line 324

Quoted 11 lines
rust/kernel/drm/job_queue.rs new file +11 -0
+impl<T: JobQueueOps + Send + Sync> ScopedWorkItem for RunWorker<'_, '_, T> {
+    fn run(work: &ScopedWork<Self>) {
+        // Synchronize against revocation in `JobQueue::drop`.
+        let _lock_guard = work.srcu.read_lock();
+        if work.parked.load(Relaxed) {
+            return;
+        }
+
+        let mut jq = work.inner.lock();
+
+        while let Some(job) = jq.waiting_jobs.pop_front() {

[Severity: Medium]
Should RunWorker::run() also check work.parked inside the while loop?

work.parked is only checked once before entering the loop, and the lock is released around T::run_job(). If JobQueue::park() or JobQueue::drop() is called while T::run_job() is running, it sets self.parked to true and waits in self.srcu.synchronize(), but RunWorker::run() will continue popping and running all remaining ready jobs in waiting_jobs before exiting the loop and releasing the SRCU read lock.

rust/kernel/drm/job_queue.rs line 331

Quoted 7 lines
rust/kernel/drm/job_queue.rs new file +7 -0
+            // While we didn't hold the lock below for `run_job()`, it could be
+            // that a new job entered the waiting list which has an unfulfilled
+            // dependency.
+            if job.nr_of_deps.load(Relaxed) > 0 {
+                jq.waiting_jobs.push_front(job);
+                break;
+            }

[Severity: Medium]
Does Relaxed ordering on nr_of_deps guarantee that T::run_job() observes memory writes made before dependency fences were signaled?

If RunWorker::run() is already looping when the last dependency fence signals on another CPU (or if a dependency signals before Job::submit() performs the final decrement to 0), RunWorker::run() can observe job.nr_of_deps.load(Relaxed) == 0, unlock jq (a release operation), and call T::run_job() without any acquire barrier synchronizing with the dependency signal:

CPU0 (dependency signal) CPU1 (RunWorker::run)
------------------------ ---------------------
// writes before fence signal
nr_of_deps.fetch_sub(1, Relaxed)
// reaches 0
lock(inner) nr_of_deps.load(Relaxed) == 0 unlock(inner) T::run_job() <-- no acquire barrier

Using Release ordering on nr_of_deps.fetch_sub() in DependencyWaker::on_signal() and Job::submit() paired with Acquire ordering on job.nr_of_deps.load() in RunWorker::run() would establish a release-acquire chain before T::run_job() runs.

rust/kernel/drm/job_queue.rs line 337

Quoted 6 lines
rust/kernel/drm/job_queue.rs new file +6 -0
+            let new_capacity = jq.capacity as i64 - i64::from(job.cost);
+            if new_capacity < 0 {
+                jq.waiting_jobs.push_front(job);
+                break;
+            }
+            *jq.as_mut().project().capacity = new_capacity as u64;

[Severity: Medium]
Can casting jq.capacity (u64) to i64 wrap negative or underflow when capacity_param exceeds i64::MAX?

JobQueue::new() accepts any u64 for capacity_param, so if jq.capacity is greater than i64::MAX as u64, jq.capacity as i64 becomes negative and either permanently stalls the queue (new_capacity < 0) or underflows i64::MIN. Could this use jq.capacity.checked_sub(u64::from(job.cost)) instead?

Quoted 20 lines
rust/kernel/drm/job_queue.rs new file +20 -0
+
+            let fence = job.fence.as_ref().expect("fence not present");
+            let seqno = fence.as_fence().seqno();
+            let runnable_job = JobRunnable {
+                seqno,
+                data: fence.deref(),
+            };
+
+            drop(jq); // Release lock.
+            T::run_job(work.fctx, runnable_job);
+            jq = work.inner.lock(); // Retake lock.
+
+            // run_job() above needs to be called without lock protection. Thus,
+            // it is possible that the driver instructed completion right before
+            // we could re-take the lock.
+            if jq.last_completed >= seqno {
+                *jq.as_mut().project().capacity += u64::from(job.cost);
+                fence.signal(Ok(()));
+
+                // Drop here directly if possible. Otherwise, let the DropWorker

rust/kernel/drm/job_queue.rs line 367

Quoted 10 lines
rust/kernel/drm/job_queue.rs new file +10 -0
+                // take care of it.
+                if core::mem::needs_drop::<T::JobDataType>() {
+                    jq.drop_list.push_back(job);
+                }
+            } else {
+                jq.running_jobs.push_back(job);
+            }
+        }
+    }
+}

[Severity: Medium]
As reported by Younes Akhouayri on v1 [1], when a job completes before RunWorker::run() retakes work.inner.lock(), does pushing the job onto jq.drop_list here without scheduling drop_worker leave the job stranded?

In that race, complete_jobs_up_to_seqno() calls check_start_drop_worker() before the job is on drop_list, so DropWorker::run() can see an empty list and exit before RunWorker::run() pushes the job onto jq.drop_list. The job and its payload then remain unfreed in drop_list until a later job completes or the JobQueue is dropped.

Quoted 6 lines
rust/kernel/drm/job_queue.rs new file +6 -0
+
+struct DropWorker<'a, 'fctx, T: JobQueueOps + Send + Sync> {
+    inner: &'a SpinLockIrq<JobQueueInner<'fctx, T>>,
+}
+
+impl<T: JobQueueOps + Send + Sync> ScopedWorkItem for DropWorker<'_, '_, T> {

rust/kernel/drm/job_queue.rs line 383

Quoted 10 lines
rust/kernel/drm/job_queue.rs new file +10 -0
+    fn run(work: &ScopedWork<Self>) {
+        let mut jq_locked = work.inner.lock();
+
+        while let Some(job) = jq_locked.drop_list.pop_front() {
+            drop(jq_locked);
+            drop(job);
+            jq_locked = work.inner.lock();
+        }
+    }
+}

[Severity: High]
When DropWorker::run() (or JobQueue::drop()) drops a job whose T::JobDataType implements Drop, does DriverFence::drop() actually run the payload's destructor?

In DriverFence::drop() (updated earlier in this series by commit "rust:
DmaFence: Replace call_rcu() with cond_synchronize_rcu()"), drop_in_place is called on &raw mut self.data rather than on the inner payload field:

rust/kernel/dma_buf/dma_fence.rs:DriverFence::drop() {
    ...
        // SAFETY: Valid because `self` is valid. RCU above ensures that all
        // accessors are gone.
        unsafe { drop_in_place(&raw mut self.data) };

        // SAFETY: Valid because `self` is valid. This is the initial reference
        // from when this `DriverFence` was created.
        unsafe { bindings::dma_fence_put(self.as_raw()) };
}

Because DriverFence::data is a NonNull<DriverFenceData<'a, T>> pointer and the user payload lives at (*self.data.as_ptr()).data, drop_in_place(&raw mut self.data) is a no-op on a pointer wrapper and dma_fence_put() frees the allocation without running T::JobDataType's Drop implementation, leaking any resources owned by the job payload.

[ ... ]

rust/kernel/drm/job_queue.rs line 519

Quoted 4 lines
rust/kernel/drm/job_queue.rs new file +4 -0
+/// let cb = Callback { seqno: done_fence2.seqno() };
+/// // SAFETY: The registration is not leaked.
+/// let reg = unsafe { FenceCallbackRegistration::new(&done_fence2, cb) };
+/// let reg = KBox::new(reg, GFP_KERNEL)?;

[Severity: Low]
In this doctest example, FenceCallbackRegistration::new() returns an impl PinInit, so KBox::new(reg, GFP_KERNEL)? boxes the unexecuted initializer closure instead of registering the callback. Should this be KBox::pin_init(reg, GFP_KERNEL)?

[ ... ]

Quoted 26 lines
rust/kernel/drm/job_queue.rs new file +26 -0
+    pub fn complete_jobs_up_to_seqno(&self, seqno: u64) {
+        self.with_inner(|inner| {
+            let needs_drop = core::mem::needs_drop::<T::JobDataType>();
+            let mut jq_locked = inner.lock();
+            let mut jq = jq_locked.as_mut().project();
+
+            if seqno < *jq.last_completed {
+                return;
+            }
+
+            while let Some(mut job) = jq.running_jobs.pop_front() {
+                if job
+                    .as_mut()
+                    .project()
+                    .fence
+                    .as_mut()
+                    .expect("fence not present")
+                    .as_fence()
+                    .seqno()
+                    > seqno
+                {
+                    jq.running_jobs.push_front(job);
+                    break;
+                }
+
+                *jq.capacity += u64::from(job.cost);

rust/kernel/drm/job_queue.rs line 817

Quoted 10 lines
rust/kernel/drm/job_queue.rs new file +10 -0
+
+                let fence = job.fence.as_ref().expect("fence not present");
+                fence.signal(Ok(()));
+
+                if needs_drop {
+                    jq.drop_list.push_back(job);
+                }
+                // Otherwise, job is dropped here directly. Its fence won't perform
+                // an RCU grace period wait.
+            }

[Severity: High]
Can calling fence.signal(Ok(())) and dropping job while holding inner.lock() (SpinLockIrq) deadlock in complete_jobs_up_to_seqno() and RunWorker::run()?

DriverFence::signal() acquires the fence spinlock and synchronously runs registered FenceCallback::on_signal() callbacks while inner.lock() is held. If a completion callback submits another job via Job::submit() on the same JobQueue, it will try to acquire inner.lock() on the same CPU:

complete_jobs_up_to_seqno()
inner.lock()
fence.signal(Ok(()))

    dma_fence_signal_locked()
      on_signal()
        Job::submit()
          inner.lock()  <-- self-deadlock

Even across different fences, acquiring fence->lock inside inner.lock() (during both fence.signal() and, when !needs_drop, dropping job.dependencies -> FenceCallbackRegistration::drop() -> dma_fence_remove_callback()) inverts the fence->lock -> inner.lock() ordering taken whenever a fence callback calls into JobQueue, creating an ABBA deadlock.

rust/kernel/drm/job_queue.rs line 829

Quoted 12 lines
rust/kernel/drm/job_queue.rs new file +12 -0
+
+            // This enables the RunWorker to complete a job that is not yet
+            // in 'running_jobs', in case of a race against the lock.
+            *jq.last_completed = seqno;
+            drop(jq_locked);
+
+            self.check_start_run_worker();
+            if needs_drop {
+                self.check_start_drop_worker();
+            }
+        })
+    }

[Severity: Low]
If complete_jobs_up_to_seqno() is called with seqno == *jq.last_completed, or when no jobs in running_jobs had seqno <= the argument, this still wakes both run_worker and drop_worker (even when drop_list is empty). Checking seqno <= *jq.last_completed and only starting the workers when at least one job was completed (and clearing job.dependencies once a job is popped in RunWorker::run()) would avoid the extra workqueue wakeups and retain fewer allocations while jobs are running.

Quoted 24 lines
rust/kernel/drm/job_queue.rs new file +24 -0
+
+    /// Set the error with which this JobQueue will signal all running jobs'
+    /// fences. (The jobs on the waiting_list will all complete with ECANCELED
+    /// as their error)
+    pub fn set_error(mut self: Pin<&mut Self>, error: Error) {
+        *self.as_mut().project().err = error;
+    }
+}
+
+#[pinned_drop]
+impl<T: JobQueueOps + Send + Sync> PinnedDrop for JobQueue<T> {
+    fn drop(self: Pin<&mut Self>) {
+        // Prevent the RunWorker from moving more jobs to `running_jobs`.
+        self.parked.store(true, Relaxed);
+        self.srcu.synchronize();
+        self.with_inner(|inner| {
+            let mut inner_locked = inner.lock();
+            let drop_list = core::mem::take(&mut inner_locked.drop_list);
+            let waiting_jobs = core::mem::take(&mut inner_locked.waiting_jobs);
+            let mut running_jobs = core::mem::take(&mut inner_locked.running_jobs);
+
+            drop(inner_locked);
+
+            while let Some(job) = running_jobs.pop_front() {

rust/kernel/drm/job_queue.rs line 863

Quoted 10 lines
rust/kernel/drm/job_queue.rs new file +10 -0
+                let fence = job.fence.as_ref().expect("fence not present");
+                fence.signal(Err(self.err));
+            }
+
+            drop(drop_list);
+            drop(waiting_jobs);
+            drop(running_jobs);
+        })
+    }
+}

[Severity: Medium]
Does JobQueue::drop() leave waiting_jobs unsignaled and wait for a separate RCU grace period on every job?

Job::submit() already creates a DriverFence for each job in waiting_jobs, and the doc comments state that dropping a JobQueue signals waiting jobs' fences with ECANCELED. Because JobQueue::drop() drops waiting_jobs without calling fence.signal(Err(ECANCELED)), each waiting job hits DriverFence::drop()'s unsignaled error path, logging pr_err!("DriverFence drops unsignaled. Danger of memory corruption!\n") and calling an unconditional synchronize_rcu().

In addition, while let Some(job) = running_jobs.pop_front() drops each job at the end of the loop body right after fence.signal(Err(self.err)), which calls cond_synchronize_rcu() immediately per job instead of signaling all running and waiting fences first so they can share a single grace period.

[1] https://lore.kernel.org/r/[email protected]

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=9