Skip to contentSkip to conversation

rust: workqueue: add cancel_sync support

PATCH Superseded Onur Özkan 3 participants 7 messages May 10 – May 23 Rust

v1 of 3 Superseded Latest is v3 →

lore
Share & tools
lore

Onur Özkan

author reviewer
#0 lore raw

PATCH 1/1 rust: workqueue: add cancel_sync support

Drivers can use this during teardown to cancel pending work and wait for running work to finish before dropping related resources.

This is not implemented for Pin<KBox<T>> because queuing a boxed work item transfers ownership of the box to the workqueue. There is therefore no separate safe owner that can cancel the boxed work while it is pending.

The immediate motivation is the Tyr reset infrastructure [1], which needs to cancel pending reset work and wait for any running reset work during teardown before dropping the resources used by that work.

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

---
 rust/kernel/workqueue.rs | 134 ++++++++++++++++++++++++++++++++-------
 1 file changed, 112 insertions(+), 22 deletions(-)
rust/kernel/workqueue.rs +112 -22
index 7e253b6f299c..a10daa2763ac 100644
@@ -442,23 +442,44 @@ pub unsafe trait RawDelayedWorkItem<const ID: u64>: RawWorkItem<ID> {}
 ///
 /// # Safety
 ///
-/// Implementers must ensure that [`__enqueue`] uses a `work_struct` initialized with the [`run`]
-/// method of this trait as the function pointer.
+/// Implementers must ensure that [`__enqueue`] uses a `work_struct` initialized with [`run`] as
+/// its function pointer, and that [`from_raw_work`] rebuilds the exact ownership transferred by
+/// a successful [`__enqueue`] call.
 ///
 /// [`__enqueue`]: RawWorkItem::__enqueue
+/// [`from_raw_work`]: WorkItemPointer::from_raw_work
 /// [`run`]: WorkItemPointer::run
-pub unsafe trait WorkItemPointer<const ID: u64>: RawWorkItem<ID> {
-    /// Run this work item.
+pub unsafe trait WorkItemPointer<const ID: u64>: RawWorkItem<ID> + Sized {
+    /// The work item type containing the embedded `work_struct`.
+    type Item: WorkItem<ID, Pointer = Self> + ?Sized;
+
+    /// Rebuild this work item's pointer from its embedded `work_struct`.
     ///
     /// # Safety
     ///
-    /// The provided `work_struct` pointer must originate from a previous call to [`__enqueue`]
-    /// where the `queue_work_on` closure returned true, and the pointer must still be valid.
+    /// The provided `work_struct` pointer must originate from a previous call to
+    /// [`RawWorkItem::__enqueue`] where the `queue_work_on` closure returned true
+    /// and the pointer must still be valid.
+    unsafe fn from_raw_work(ptr: *mut bindings::work_struct) -> Self;
+
+    /// Run this work item.
     ///
-    /// [`__enqueue`]: RawWorkItem::__enqueue
-    unsafe extern "C" fn run(ptr: *mut bindings::work_struct);
+    /// # Safety
+    ///
+    /// The provided `work_struct` pointer must satisfy the same requirements as
+    /// [`WorkItemPointer::from_raw_work`].
+    #[inline]
+    unsafe extern "C" fn run(ptr: *mut bindings::work_struct) {
+        <Self::Item as WorkItem<ID>>::run(
+            // SAFETY: The requirements for `run` are exactly those of `from_raw_work`.
+            unsafe { Self::from_raw_work(ptr) },
+        );
+    }
 }
 
+/// Marker for work item types that support cancellation.
+pub trait SupportsCancelling<const ID: u64>: WorkItemPointer<ID> {}
+
 /// Defines the method that should be called when this work item is executed.
 ///
 /// This trait is used when the `work_struct` field is defined using the [`Work`] helper.
@@ -523,6 +544,32 @@ pub fn new(name: &'static CStr, key: Pin<&'static LockClassKey>) -> impl PinInit
         })
     }
 
+    /// Cancels this work item if it is pending and waits for any running execution to finish.
+    ///
+    /// On return, the work item is guaranteed to not be pending or executing as long as there are
+    /// no racing re-enqueues.
+    ///
+    /// # Note
+    ///
+    /// Should be called from a sleepable context if the work was last queued on a non-BH
+    /// workqueue.
+    #[inline]
+    pub fn cancel_sync(&self) -> Option<T::Pointer>
+    where
+        T: WorkItem<ID>,
+        T::Pointer: SupportsCancelling<ID>,
+    {
+        let ptr = self.work.get();
+        // SAFETY: `ptr` is a valid embedded `work_struct`.
+        if unsafe { bindings::cancel_work_sync(ptr) } {
+            // SAFETY: A `true` return means the work was pending and got canceled, so the queued
+            // ownership transfer performed by `__enqueue` is reclaimed here.
+            Some(unsafe { T::Pointer::from_raw_work(ptr) })
+        } else {
+            None
+        }
+    }
+
     /// Get a pointer to the inner `work_struct`.
     ///
     /// # Safety
@@ -709,6 +756,34 @@ pub fn new(
         })
     }
 
+    /// Cancels this delayed work item if it is pending and waits for any running execution to
+    /// finish.
+    ///
+    /// On return, the work item is guaranteed to not be pending or executing as long as there are
+    /// no racing re-enqueues.
+    ///
+    /// # Note
+    ///
+    /// Should be called from a sleepable context if the work was last queued on a non-BH
+    /// workqueue.
+    #[inline]
+    pub fn cancel_sync(&self) -> Option<T::Pointer>
+    where
+        T: WorkItem<ID>,
+        T::Pointer: SupportsCancelling<ID>,
+    {
+        let ptr = self.dwork.get();
+
+        // SAFETY: `ptr` is a valid embedded `delayed_work`.
+        if unsafe { bindings::cancel_delayed_work_sync(ptr) } {
+            // SAFETY: A `true` return means the work was pending and got canceled, so the queued
+            // ownership transfer performed by `__enqueue` is reclaimed here.
+            Some(unsafe { T::Pointer::from_raw_work(core::ptr::addr_of_mut!((*ptr).work)) })
+        } else {
+            None
+        }
+    }
+
     /// Get a pointer to the inner `delayed_work`.
     ///
     /// # Safety
@@ -824,25 +899,32 @@ unsafe impl<T, const ID: u64> WorkItemPointer<ID> for Arc<T>
     T: WorkItem<ID, Pointer = Self>,
     T: HasWork<T, ID>,
 {
-    unsafe extern "C" fn run(ptr: *mut bindings::work_struct) {
+    type Item = T;
+
+    unsafe fn from_raw_work(ptr: *mut bindings::work_struct) -> Self {
         // The `__enqueue` method always uses a `work_struct` stored in a `Work<T, ID>`.
         let ptr = ptr.cast::<Work<T, ID>>();
         // SAFETY: This computes the pointer that `__enqueue` got from `Arc::into_raw`.
         let ptr = unsafe { T::work_container_of(ptr) };
         // SAFETY: This pointer comes from `Arc::into_raw` and we've been given back ownership.
-        let arc = unsafe { Arc::from_raw(ptr) };
-
-        T::run(arc)
+        unsafe { Arc::from_raw(ptr) }
     }
 }
 
+impl<T, const ID: u64> SupportsCancelling<ID> for Arc<T>
+where
+    T: WorkItem<ID, Pointer = Self>,
+    T: HasWork<T, ID>,
+{
+}
+
 // SAFETY: The `work_struct` raw pointer is guaranteed to be valid for the duration of the call to
 // the closure because we get it from an `Arc`, which means that the ref count will be at least 1,
 // and we don't drop the `Arc` ourselves. If `queue_work_on` returns true, it is further guaranteed
 // to be valid until a call to the function pointer in `work_struct` because we leak the memory it
 // points to, and only reclaim it if the closure returns false, or in `WorkItemPointer::run`, which
 // is what the function pointer in the `work_struct` must be pointing to, according to the safety
-// requirements of `WorkItemPointer`.
+// requirements of `WorkItemPointer`, or after a successful cancellation.
 unsafe impl<T, const ID: u64> RawWorkItem<ID> for Arc<T>
 where
     T: WorkItem<ID, Pointer = Self>,
@@ -887,7 +969,9 @@ unsafe impl<T, const ID: u64> WorkItemPointer<ID> for Pin<KBox<T>>
     T: WorkItem<ID, Pointer = Self>,
     T: HasWork<T, ID>,
 {
-    unsafe extern "C" fn run(ptr: *mut bindings::work_struct) {
+    type Item = T;
+
+    unsafe fn from_raw_work(ptr: *mut bindings::work_struct) -> Self {
         // The `__enqueue` method always uses a `work_struct` stored in a `Work<T, ID>`.
         let ptr = ptr.cast::<Work<T, ID>>();
         // SAFETY: This computes the pointer that `__enqueue` got from `Arc::into_raw`.
@@ -895,9 +979,7 @@ unsafe impl<T, const ID: u64> WorkItemPointer<ID> for Pin<KBox<T>>
         // SAFETY: This pointer comes from `Arc::into_raw` and we've been given back ownership.
         let boxed = unsafe { KBox::from_raw(ptr) };
         // SAFETY: The box was already pinned when it was enqueued.
-        let pinned = unsafe { Pin::new_unchecked(boxed) };
-
-        T::run(pinned)
+        unsafe { Pin::new_unchecked(boxed) }
     }
 }
 
@@ -958,7 +1040,9 @@ unsafe impl<T, const ID: u64> WorkItemPointer<ID> for ARef<T>
     T: WorkItem<ID, Pointer = Self>,
     T: HasWork<T, ID>,
 {
-    unsafe extern "C" fn run(ptr: *mut bindings::work_struct) {
+    type Item = T;
+
+    unsafe fn from_raw_work(ptr: *mut bindings::work_struct) -> Self {
         // The `__enqueue` method always uses a `work_struct` stored in a `Work<T, ID>`.
         let ptr = ptr.cast::<Work<T, ID>>();
 
@@ -972,19 +1056,25 @@ unsafe impl<T, const ID: u64> WorkItemPointer<ID> for ARef<T>
 
         // SAFETY: This pointer comes from `ARef::into_raw` and we've been given
         // back ownership.
-        let aref = unsafe { ARef::from_raw(ptr) };
-
-        T::run(aref)
+        unsafe { ARef::from_raw(ptr) }
     }
 }
 
+impl<T, const ID: u64> SupportsCancelling<ID> for ARef<T>
+where
+    T: AlwaysRefCounted,
+    T: WorkItem<ID, Pointer = Self>,
+    T: HasWork<T, ID>,
+{
+}
+
 // SAFETY: The `work_struct` raw pointer is guaranteed to be valid for the duration of the call to
 // the closure because we get it from an `ARef`, which means that the ref count will be at least 1,
 // and we don't drop the `ARef` ourselves. If `queue_work_on` returns true, it is further guaranteed
 // to be valid until a call to the function pointer in `work_struct` because we leak the memory it
 // points to, and only reclaim it if the closure returns false, or in `WorkItemPointer::run`, which
 // is what the function pointer in the `work_struct` must be pointing to, according to the safety
-// requirements of `WorkItemPointer`.
+// requirements of `WorkItemPointer`, or after a successful cancellation.
 unsafe impl<T, const ID: u64> RawWorkItem<ID> for ARef<T>
 where
     T: AlwaysRefCounted,
Signature · 1 line
2.51.2
reviewer
#1 lore raw
Quoted 61 lines · Onur Özkan

Drivers can use this during teardown to cancel pending work and wait for running work to finish before dropping related resources.

This is not implemented for Pin<KBox<T>> because queuing a boxed work item transfers ownership of the box to the workqueue. There is therefore no separate safe owner that can cancel the boxed work while it is pending.

The immediate motivation is the Tyr reset infrastructure [1], which needs to cancel pending reset work and wait for any running reset work during teardown before dropping the resources used by that work.

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

---
 rust/kernel/workqueue.rs | 134 ++++++++++++++++++++++++++++++++-------
 1 file changed, 112 insertions(+), 22 deletions(-)
rust/kernel/workqueue.rs +20 -8
index 7e253b6f299c..a10daa2763ac 100644
@@ -442,23 +442,44 @@ pub unsafe trait RawDelayedWorkItem<const ID: u64>: RawWorkItem<ID> {}
 ///
 /// # Safety
 ///
-/// Implementers must ensure that [`__enqueue`] uses a `work_struct` initialized with the [`run`]
-/// method of this trait as the function pointer.
+/// Implementers must ensure that [`__enqueue`] uses a `work_struct` initialized with [`run`] as
+/// its function pointer, and that [`from_raw_work`] rebuilds the exact ownership transferred by
+/// a successful [`__enqueue`] call.
 ///
 /// [`__enqueue`]: RawWorkItem::__enqueue
+/// [`from_raw_work`]: WorkItemPointer::from_raw_work
 /// [`run`]: WorkItemPointer::run
-pub unsafe trait WorkItemPointer<const ID: u64>: RawWorkItem<ID> {
-    /// Run this work item.
+pub unsafe trait WorkItemPointer<const ID: u64>: RawWorkItem<ID> + Sized {
+    /// The work item type containing the embedded `work_struct`.
+    type Item: WorkItem<ID, Pointer = Self> + ?Sized;
+
+    /// Rebuild this work item's pointer from its embedded `work_struct`.
     ///
     /// # Safety
     ///
-    /// The provided `work_struct` pointer must originate from a previous call to [`__enqueue`]
-    /// where the `queue_work_on` closure returned true, and the pointer must still be valid.
+    /// The provided `work_struct` pointer must originate from a previous call to
+    /// [`RawWorkItem::__enqueue`] where the `queue_work_on` closure returned true
+    /// and the pointer must still be valid.
+    unsafe fn from_raw_work(ptr: *mut bindings::work_struct) -> Self;
+
+    /// Run this work item.
     ///
-    /// [`__enqueue`]: RawWorkItem::__enqueue
-    unsafe extern "C" fn run(ptr: *mut bindings::work_struct);
+    /// # Safety
+    ///
+    /// The provided `work_struct` pointer must satisfy the same requirements as
+    /// [`WorkItemPointer::from_raw_work`].
+    #[inline]

rust/kernel/workqueue.rs pub unsafe trait RawDelayedWorkItem<const ID: u64>: RawWorkItem<ID> {} · line 481

Quoted 10 lines
rust/kernel/workqueue.rs +8 -0
+    unsafe extern "C" fn run(ptr: *mut bindings::work_struct) {
+        <Self::Item as WorkItem<ID>>::run(
+            // SAFETY: The requirements for `run` are exactly those of `from_raw_work`.
+            unsafe { Self::from_raw_work(ptr) },
+        );
+    }
 }
 
+/// Marker for work item types that support cancellation.
+pub trait SupportsCancelling<const ID: u64>: WorkItemPointer<ID> {}

Shouldn't 'from_raw_work()' be a method on SupportsCancelling instead?

Alice

author reviewer
#2 lore raw
Quoted 70 lines · On Sun, 10 May 2026 13:43:59 +0000 Alice Ryhl <[email protected]> wrote:
Quoted 69 lines · Onur Özkan

Drivers can use this during teardown to cancel pending work and wait for running work to finish before dropping related resources.

This is not implemented for Pin<KBox<T>> because queuing a boxed work item transfers ownership of the box to the workqueue. There is therefore no separate safe owner that can cancel the boxed work while it is pending.

The immediate motivation is the Tyr reset infrastructure [1], which needs to cancel pending reset work and wait for any running reset work during teardown before dropping the resources used by that work.

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

---
 rust/kernel/workqueue.rs | 134 ++++++++++++++++++++++++++++++++-------
 1 file changed, 112 insertions(+), 22 deletions(-)
rust/kernel/workqueue.rs +26 -8
index 7e253b6f299c..a10daa2763ac 100644
@@ -442,23 +442,44 @@ pub unsafe trait RawDelayedWorkItem<const ID: u64>: RawWorkItem<ID> {}
 ///
 /// # Safety
 ///
-/// Implementers must ensure that [`__enqueue`] uses a `work_struct` initialized with the [`run`]
-/// method of this trait as the function pointer.
+/// Implementers must ensure that [`__enqueue`] uses a `work_struct` initialized with [`run`] as
+/// its function pointer, and that [`from_raw_work`] rebuilds the exact ownership transferred by
+/// a successful [`__enqueue`] call.
 ///
 /// [`__enqueue`]: RawWorkItem::__enqueue
+/// [`from_raw_work`]: WorkItemPointer::from_raw_work
 /// [`run`]: WorkItemPointer::run
-pub unsafe trait WorkItemPointer<const ID: u64>: RawWorkItem<ID> {
-    /// Run this work item.
+pub unsafe trait WorkItemPointer<const ID: u64>: RawWorkItem<ID> + Sized {
+    /// The work item type containing the embedded `work_struct`.
+    type Item: WorkItem<ID, Pointer = Self> + ?Sized;
+
+    /// Rebuild this work item's pointer from its embedded `work_struct`.
     ///
     /// # Safety
     ///
-    /// The provided `work_struct` pointer must originate from a previous call to [`__enqueue`]
-    /// where the `queue_work_on` closure returned true, and the pointer must still be valid.
+    /// The provided `work_struct` pointer must originate from a previous call to
+    /// [`RawWorkItem::__enqueue`] where the `queue_work_on` closure returned true
+    /// and the pointer must still be valid.
+    unsafe fn from_raw_work(ptr: *mut bindings::work_struct) -> Self;
+
+    /// Run this work item.
     ///
-    /// [`__enqueue`]: RawWorkItem::__enqueue
-    unsafe extern "C" fn run(ptr: *mut bindings::work_struct);
+    /// # Safety
+    ///
+    /// The provided `work_struct` pointer must satisfy the same requirements as
+    /// [`WorkItemPointer::from_raw_work`].
+    #[inline]
+    unsafe extern "C" fn run(ptr: *mut bindings::work_struct) {
+        <Self::Item as WorkItem<ID>>::run(
+            // SAFETY: The requirements for `run` are exactly those of `from_raw_work`.
+            unsafe { Self::from_raw_work(ptr) },
+        );
+    }
 }
 
Quoted 4 lines

rust/kernel/workqueue.rs pub unsafe trait RawDelayedWorkItem<const ID: u64>: RawWorkItem<ID> {} · line 481

Quoted 2 lines
rust/kernel/workqueue.rs +2 -0
+/// Marker for work item types that support cancellation.
+pub trait SupportsCancelling<const ID: u64>: WorkItemPointer<ID> {}

Shouldn't 'from_raw_work()' be a method on SupportsCancelling instead?

Not necessarily. I wanted to keep it like that because it removes a bit of duplication and makes run() simpler. It's also more extensible e.g. can be used for disable_sync too if needed in the future.

-Onur

Quoted 2 lines

Alice

reviewer
#3 lore raw
Quoted 73 lines · Onur Özkan
Quoted 70 lines · On Sun, 10 May 2026 13:43:59 +0000 Alice Ryhl <[email protected]> wrote:
Quoted 69 lines · Onur Özkan

Drivers can use this during teardown to cancel pending work and wait for running work to finish before dropping related resources.

This is not implemented for Pin<KBox<T>> because queuing a boxed work item transfers ownership of the box to the workqueue. There is therefore no separate safe owner that can cancel the boxed work while it is pending.

The immediate motivation is the Tyr reset infrastructure [1], which needs to cancel pending reset work and wait for any running reset work during teardown before dropping the resources used by that work.

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

---
 rust/kernel/workqueue.rs | 134 ++++++++++++++++++++++++++++++++-------
 1 file changed, 112 insertions(+), 22 deletions(-)
rust/kernel/workqueue.rs +26 -8
index 7e253b6f299c..a10daa2763ac 100644
@@ -442,23 +442,44 @@ pub unsafe trait RawDelayedWorkItem<const ID: u64>: RawWorkItem<ID> {}
 ///
 /// # Safety
 ///
-/// Implementers must ensure that [`__enqueue`] uses a `work_struct` initialized with the [`run`]
-/// method of this trait as the function pointer.
+/// Implementers must ensure that [`__enqueue`] uses a `work_struct` initialized with [`run`] as
+/// its function pointer, and that [`from_raw_work`] rebuilds the exact ownership transferred by
+/// a successful [`__enqueue`] call.
 ///
 /// [`__enqueue`]: RawWorkItem::__enqueue
+/// [`from_raw_work`]: WorkItemPointer::from_raw_work
 /// [`run`]: WorkItemPointer::run
-pub unsafe trait WorkItemPointer<const ID: u64>: RawWorkItem<ID> {
-    /// Run this work item.
+pub unsafe trait WorkItemPointer<const ID: u64>: RawWorkItem<ID> + Sized {
+    /// The work item type containing the embedded `work_struct`.
+    type Item: WorkItem<ID, Pointer = Self> + ?Sized;
+
+    /// Rebuild this work item's pointer from its embedded `work_struct`.
     ///
     /// # Safety
     ///
-    /// The provided `work_struct` pointer must originate from a previous call to [`__enqueue`]
-    /// where the `queue_work_on` closure returned true, and the pointer must still be valid.
+    /// The provided `work_struct` pointer must originate from a previous call to
+    /// [`RawWorkItem::__enqueue`] where the `queue_work_on` closure returned true
+    /// and the pointer must still be valid.
+    unsafe fn from_raw_work(ptr: *mut bindings::work_struct) -> Self;
+
+    /// Run this work item.
     ///
-    /// [`__enqueue`]: RawWorkItem::__enqueue
-    unsafe extern "C" fn run(ptr: *mut bindings::work_struct);
+    /// # Safety
+    ///
+    /// The provided `work_struct` pointer must satisfy the same requirements as
+    /// [`WorkItemPointer::from_raw_work`].
+    #[inline]
+    unsafe extern "C" fn run(ptr: *mut bindings::work_struct) {
+        <Self::Item as WorkItem<ID>>::run(
+            // SAFETY: The requirements for `run` are exactly those of `from_raw_work`.
+            unsafe { Self::from_raw_work(ptr) },
+        );
+    }
 }
 
Quoted 8 lines
Quoted 4 lines

rust/kernel/workqueue.rs pub unsafe trait RawDelayedWorkItem<const ID: u64>: RawWorkItem<ID> {} · line 481

Quoted 2 lines
rust/kernel/workqueue.rs +2 -0
+/// Marker for work item types that support cancellation.
+pub trait SupportsCancelling<const ID: u64>: WorkItemPointer<ID> {}

Shouldn't 'from_raw_work()' be a method on SupportsCancelling instead?

Not necessarily. I wanted to keep it like that because it removes a bit of duplication and makes run() simpler. It's also more extensible e.g. can be used for disable_sync too if needed in the future.

It still seems wrong to me because you are forcing all pointer types to provide from_raw_work() even though not all pointer types needs it.

As for disable_sync(), I think for that case we'd want three traits:

1. WorkItemPointer, defines run()
2. CancelableWorkItemPtr: WorkItemPointer, defines from_raw_work()
3. DisablableWorkItemPtr: CancelableWorkItemPtr, no methods

Alice

author reviewer
#4 lore raw
Quoted 79 lines · On Wed, 13 May 2026 07:33:46 +0000 Alice Ryhl <[email protected]> wrote:
Quoted 78 lines · Onur Özkan
Quoted 74 lines · On Sun, 10 May 2026 13:43:59 +0000 Alice Ryhl <[email protected]> wrote:
Quoted 61 lines · Onur Özkan

Drivers can use this during teardown to cancel pending work and wait for running work to finish before dropping related resources.

This is not implemented for Pin<KBox<T>> because queuing a boxed work item transfers ownership of the box to the workqueue. There is therefore no separate safe owner that can cancel the boxed work while it is pending.

The immediate motivation is the Tyr reset infrastructure [1], which needs to cancel pending reset work and wait for any running reset work during teardown before dropping the resources used by that work.

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

---
 rust/kernel/workqueue.rs | 134 ++++++++++++++++++++++++++++++++-------
 1 file changed, 112 insertions(+), 22 deletions(-)
rust/kernel/workqueue.rs +20 -8
index 7e253b6f299c..a10daa2763ac 100644
@@ -442,23 +442,44 @@ pub unsafe trait RawDelayedWorkItem<const ID: u64>: RawWorkItem<ID> {}
 ///
 /// # Safety
 ///
-/// Implementers must ensure that [`__enqueue`] uses a `work_struct` initialized with the [`run`]
-/// method of this trait as the function pointer.
+/// Implementers must ensure that [`__enqueue`] uses a `work_struct` initialized with [`run`] as
+/// its function pointer, and that [`from_raw_work`] rebuilds the exact ownership transferred by
+/// a successful [`__enqueue`] call.
 ///
 /// [`__enqueue`]: RawWorkItem::__enqueue
+/// [`from_raw_work`]: WorkItemPointer::from_raw_work
 /// [`run`]: WorkItemPointer::run
-pub unsafe trait WorkItemPointer<const ID: u64>: RawWorkItem<ID> {
-    /// Run this work item.
+pub unsafe trait WorkItemPointer<const ID: u64>: RawWorkItem<ID> + Sized {
+    /// The work item type containing the embedded `work_struct`.
+    type Item: WorkItem<ID, Pointer = Self> + ?Sized;
+
+    /// Rebuild this work item's pointer from its embedded `work_struct`.
     ///
     /// # Safety
     ///
-    /// The provided `work_struct` pointer must originate from a previous call to [`__enqueue`]
-    /// where the `queue_work_on` closure returned true, and the pointer must still be valid.
+    /// The provided `work_struct` pointer must originate from a previous call to
+    /// [`RawWorkItem::__enqueue`] where the `queue_work_on` closure returned true
+    /// and the pointer must still be valid.
+    unsafe fn from_raw_work(ptr: *mut bindings::work_struct) -> Self;
+
+    /// Run this work item.
     ///
-    /// [`__enqueue`]: RawWorkItem::__enqueue
-    unsafe extern "C" fn run(ptr: *mut bindings::work_struct);
+    /// # Safety
+    ///
+    /// The provided `work_struct` pointer must satisfy the same requirements as
+    /// [`WorkItemPointer::from_raw_work`].
+    #[inline]

rust/kernel/workqueue.rs pub unsafe trait RawDelayedWorkItem<const ID: u64>: RawWorkItem<ID> {} · line 481

Quoted 10 lines
rust/kernel/workqueue.rs +8 -0
+    unsafe extern "C" fn run(ptr: *mut bindings::work_struct) {
+        <Self::Item as WorkItem<ID>>::run(
+            // SAFETY: The requirements for `run` are exactly those of `from_raw_work`.
+            unsafe { Self::from_raw_work(ptr) },
+        );
+    }
 }
 
+/// Marker for work item types that support cancellation.
+pub trait SupportsCancelling<const ID: u64>: WorkItemPointer<ID> {}

Shouldn't 'from_raw_work()' be a method on SupportsCancelling instead?

Quoted 6 lines
Quoted 3 lines

Not necessarily. I wanted to keep it like that because it removes a bit of duplication and makes run() simpler. It's also more extensible e.g. can be used for disable_sync too if needed in the future.

It still seems wrong to me because you are forcing all pointer types to provide from_raw_work() even though not all pointer types needs it.

I know, that's the trade-off. I wanted to make run() simpler but I don't have strong feelings either way. IMO it's not even worth discussing this. I can change it and send a v2 right away, not a big deal.

Onur

Quoted 8 lines

As for disable_sync(), I think for that case we'd want three traits:

1. WorkItemPointer, defines run()
2. CancelableWorkItemPtr: WorkItemPointer, defines from_raw_work()
3. DisablableWorkItemPtr: CancelableWorkItemPtr, no methods

Alice

#5 lore raw
In reply to Onur Özkan
Quoted 2 lines · Onur Özkan

Drivers can use this during teardown to cancel pending work and wait for running work to finish before dropping related resources.

If you need this for driver teardown and the work uses device resources, you should rather create a new type of work that internally synchronizes with driver unbind.

This also allows you to provide a &Device<Bound> within the work function itself directly.

Instead you now have to fall back to unsafe code in your work callback implementation making it a driver responsibility to call cancel_sync() at the correct point of time:

	// SAFETY: `Controller` is part of driver-private data and only exists
	// while the platform device is bound.
	let pdev = unsafe { self.pdev.as_ref().as_bound() };

I already mentioned this a couple of times in the past that we want "managed" work for drivers for this exact reason.

More in general, please don't use Device::as_bound() from driver code; if it is needed it implies a design issue or that we're missing a proper solution.

author reviewer
#6 lore raw
Quoted 19 lines · On Fri, 22 May 2026 15:15:48 +0200 Danilo Krummrich <[email protected]> wrote:
Quoted 2 lines · Onur Özkan

Drivers can use this during teardown to cancel pending work and wait for running work to finish before dropping related resources.

If you need this for driver teardown and the work uses device resources, you should rather create a new type of work that internally synchronizes with driver unbind.

This also allows you to provide a &Device<Bound> within the work function itself directly.

Instead you now have to fall back to unsafe code in your work callback implementation making it a driver responsibility to call cancel_sync() at the correct point of time:

	// SAFETY: `Controller` is part of driver-private data and only exists
	// while the platform device is bound.
	let pdev = unsafe { self.pdev.as_ref().as_bound() };
Quoted 5 lines

I already mentioned this a couple of times in the past that we want "managed" work for drivers for this exact reason.

More in general, please don't use Device::as_bound() from driver code; if it is needed it implies a design issue or that we're missing a proper solution.

That makes sense a lot of sense. I will try to figure out a design for this.

- Onur