rust: workqueue: add cancel_sync support
Onur Özkan
reviewerv2 cover rust: workqueue: add cancel_sync support
Changes since v1:
- Created SupportsCancelling trait for from_raw_work function.
- Removed from_raw_work from WorkItemPointer.
v1: https://lore.kernel.org/all/[email protected]
Onur Özkan (1):
rust: workqueue: add cancel_sync support
rust/kernel/workqueue.rs | 116 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 116 insertions(+)
Signature · 1 line
2.51.2
Onur Özkan
reviewerPATCH v2 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.
--- rust/kernel/workqueue.rs | 116 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 116 insertions(+)
rust/kernel/workqueue.rs +116 -0
@@ -471,6 +471,23 @@ pub trait WorkItem<const ID: u64 = 0> {fn run (this:Self ::Pointer ); } +/// Work item pointers that support cancellation. +/// +/// # Safety +/// +/// Implementers must ensure that `from_raw_work` rebuilds the exact ownership transferred +/// by a successful [`RawWorkItem::__enqueue`] call. +pub unsafe trait SupportsCancelling <const ID :u64 >:WorkItemPointer <ID > +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 +/// [`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 ; +} +/// Links for a work item. /// /// This struct contains a function pointer to the [`run`] function from the [`WorkItemPointer`]
@@ -537,6 +554,32 @@ pub unsafe fn raw_get(ptr: *const Self) -> *mut bindings::work_struct {// the compiler does not complain that the `work` field is unused. unsafe {Opaque ::cast_into (core::ptr::addr_of!((*ptr).work)) } } + +/// 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 + } + } }/// Declares that a type contains a [`Work<T, ID>`].
@@ -725,6 +768,34 @@ pub unsafe fn raw_as_work(ptr: *const Self) -> *mut Work<T, ID> {// CAST: Work and work_struct have compatible layouts. wrk.cast () } + +/// 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 + } + } }/// Declares that a type contains a [`DelayedWork<T, ID>`].
@@ -871,6 +942,24 @@ unsafe fn __enqueue<F>(self, queue_work_on: F) -> Self::EnqueueOutput } } +// SAFETY: `from_raw_work()` reconstructs exactly the `Arc<T>` ownership previously transferred by +// `Arc::into_raw()` in `RawWorkItem::__enqueue`, using the same `Work<T, ID>` field selected by +// `HasWork<T, ID>`. +unsafe impl <T ,const ID :u64 >SupportsCancelling <ID >for Arc <T > +where +T :WorkItem <ID ,Pointer =Self >, +T :HasWork <T ,ID >, +{ +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. +unsafe {Arc ::from_raw (ptr) } + } +} +// SAFETY: By the safety requirements of `HasDelayedWork`, the `work_struct` returned by methods in // `HasWork` provides a `work_struct` that is the `work` field of a `delayed_work`, and the rest of // the `delayed_work` has the same access rules as its `work` field.
@@ -1013,6 +1102,33 @@ unsafe fn __enqueue<F>(self, queue_work_on: F) -> Self::EnqueueOutput } } +// SAFETY: `from_raw_work()` reconstructs exactly the `ARef<T>` ownership previously transferred by +// `ARef::into_raw()` in `RawWorkItem::__enqueue`, using the same `Work<T, ID>` field selected by +// `HasWork<T, ID>`. +unsafe impl <T ,const ID :u64 >SupportsCancelling <ID >for ARef <T > +where +T :AlwaysRefCounted , +T :WorkItem <ID ,Pointer =Self >, +T :HasWork <T ,ID >, +{ +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 +// `ARef::into_raw`. +let ptr =unsafe {T ::work_container_of (ptr) }; + +// SAFETY: The safety contract of `work_container_of` ensures that it +// returns a valid non-null pointer. +let ptr =unsafe {NonNull ::new_unchecked (ptr) }; + +// SAFETY: This pointer comes from `ARef::into_raw` and we've been given +// back ownership. +unsafe {ARef ::from_raw (ptr) } + } +} +// SAFETY: By the safety requirements of `HasDelayedWork`, the `work_struct` returned by methods in // `HasWork` provides a `work_struct` that is the `work` field of a `delayed_work`, and the rest of // the `delayed_work` has the same access rules as its `work` field.
Signature · 1 line
2.51.2
Alice Ryhl
reviewerQuoted 8 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.
Signed-off-by Onur Özkan <[email protected]>
Overall looks reasonable to me, but some comments below.
Quoted 8 lines
rust/kernel/workqueue.rs | 116 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 116 insertions(+)rust/kernel/workqueue.rs +0
-0
rust/kernel/workqueue.rs pub trait WorkItem<const ID: u64 = 0> { · line 480
Quoted 10 lines
rust/kernel/workqueue.rs +7
-0@@ -471,6 +471,23 @@ pub trait WorkItem<const ID: u64 = 0> {fn run (this:Self ::Pointer ); } +/// Work item pointers that support cancellation. +/// +/// # Safety +/// +/// Implementers must ensure that `from_raw_work` rebuilds the exact ownership transferred +/// by a successful [`RawWorkItem::__enqueue`] call. +pub unsafe trait SupportsCancelling <const ID :u64 >:WorkItemPointer <ID > +Sized {
Nit; I think it reads nicer as SupportsCancel.
rust/kernel/workqueue.rs pub trait WorkItem<const ID: u64 = 0> { · line 488
Quoted 8 lines
rust/kernel/workqueue.rs +8
-0+/// Rebuild this work item's pointer from its embedded `work_struct`. +/// +/// # Safety +/// +/// 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 ;
I think you're missing some condition here about ownership having been transferred *out* from the workqueue by cancel_sync() or similar methods. Otherwise this currently says I can call the method even though the workqueue still owns the work item.
rust/kernel/workqueue.rs pub unsafe fn raw_get(ptr: *const Self) -> *mut bindings::work_struct { · line 566
Quoted 4 lines
rust/kernel/workqueue.rs +4
-0+/// # Note +/// +/// Should be called from a sleepable context if the work was last queued on a non-BH +/// workqueue.
Nit: I'd either reword "Note" to something more specific to what the note is about, or remove the heading.
rust/kernel/workqueue.rs pub unsafe fn raw_as_work(ptr: *const Self) -> *mut Work<T, ID> { · line 794
Quoted 13 lines
rust/kernel/workqueue.rs +13
-0+#[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)) })
Nit: The addr_of_mut! macro is no longer required. You can do: &raw mut (*ptr).work
Alice
Onur Özkan
reviewerQuoted 42 lines · On Mon, 15 Jun 2026 07:08:37 +0000 Alice Ryhl <[email protected]> wrote:
Quoted 8 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.
Signed-off-by Onur Özkan <[email protected]>Overall looks reasonable to me, but some comments below.
Quoted 8 lines
rust/kernel/workqueue.rs | 116 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 116 insertions(+)rust/kernel/workqueue.rs +0
-0rust/kernel/workqueue.rs pub trait WorkItem<const ID: u64 = 0> { · line 480
Quoted 10 lines
rust/kernel/workqueue.rs +7
-0@@ -471,6 +471,23 @@ pub trait WorkItem<const ID: u64 = 0> {fn run (this:Self ::Pointer ); } +/// Work item pointers that support cancellation. +/// +/// # Safety +/// +/// Implementers must ensure that `from_raw_work` rebuilds the exact ownership transferred +/// by a successful [`RawWorkItem::__enqueue`] call. +pub unsafe trait SupportsCancelling <const ID :u64 >:WorkItemPointer <ID > +Sized {Nit; I think it reads nicer as SupportsCancel.
rust/kernel/workqueue.rs pub trait WorkItem<const ID: u64 = 0> { · line 488
Quoted 8 lines
rust/kernel/workqueue.rs +8
-0+/// Rebuild this work item's pointer from its embedded `work_struct`. +/// +/// # Safety +/// +/// 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 ;
Quoted 5 lines
I think you're missing some condition here about ownership having been transferred *out* from the workqueue by
cancel_sync()or similar methods. Otherwise this currently says I can call the method even though the workqueue still owns the work item.
Very true, good point! I will improve this doc in the next version with the nits applied.
Onur
Quoted 25 lines
rust/kernel/workqueue.rs pub unsafe fn raw_get(ptr: *const Self) -> *mut bindings::work_struct { · line 566
Quoted 4 lines
rust/kernel/workqueue.rs +4
-0+/// # Note +/// +/// Should be called from a sleepable context if the work was last queued on a non-BH +/// workqueue. Nit: I'd either reword "Note" to something more specific to what the note is about, or remove the heading.
rust/kernel/workqueue.rs pub unsafe fn raw_as_work(ptr: *const Self) -> *mut Work<T, ID> { · line 794
Quoted 13 lines
rust/kernel/workqueue.rs +13
-0+#[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)) })Nit: The
addr_of_mut! macro is no longer required. You can do: &raw mut (*ptr).workAlice