Skip to contentSkip to conversation

workqueue OwnedQueue, ScopedQueue and ScopedWork

PATCH Superseded Danilo Krummrich 3 participants 13 messages Aug 4 – Aug 7

Subsystems (5)

v1 of 2 Superseded Latest is v2 →

lore
Share & tools
lore

Danilo Krummrich

author maintainer
#0 lore raw

cover workqueue OwnedQueue, ScopedQueue and ScopedWork

This series extends the Rust workqueue bindings with the ability to create custom workqueues, enqueue non-'static work items on scoped queues, and introduces ScopedWork, a work item type that cancels synchronously on drop, allowing drivers to use workqueues with lifetime-bound data.

This picks up and extends prior work from Alice [1] and Onur [2]; changes I subsequently applied, if any, are documented in the corresponding patch.

I also added a patch to replace the deprecated system_wq with system_{percpu,dfl}_wq, which I originally sent with the WaitQueue series [3], as it makes a bit more sense in this context.

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

Alice Ryhl (3):
rust: workqueue: restrict delayed work to global wqs
rust: workqueue: create workqueue subdirectory
rust: workqueue: add creation of workqueues

Danilo Krummrich (3):
rust: workqueue: replace deprecated system_wq with
system_{percpu,dfl}_wq
rust: workqueue: add Work::cancel_work_sync()
rust: workqueue: add ScopedWork for non-'static work items

Onur Özkan (1):
rust: workqueue: add ScopedQueue for lifetime bound items

 MAINTAINERS                                   |   1 +
 drivers/android/binder/process.rs             |   4 +-
 rust/helpers/workqueue.c                      |   7 +
 rust/kernel/sync/completion.rs                |   2 +-
 rust/kernel/workqueue/builder.rs              | 389 ++++++++++++++++++
 .../kernel/{workqueue.rs => workqueue/mod.rs} | 147 +++++--
 rust/kernel/workqueue/scoped_queue.rs         | 202 +++++++++
 rust/kernel/workqueue/scoped_work.rs          | 290 +++++++++++++
 8 files changed, 1009 insertions(+), 33 deletions(-)
 create mode 100644 rust/kernel/workqueue/builder.rs
 rename rust/kernel/{workqueue.rs => workqueue/mod.rs} (90%)
 create mode 100644 rust/kernel/workqueue/scoped_queue.rs
 create mode 100644 rust/kernel/workqueue/scoped_work.rs

base-commit: f2687db25dd52319cb06ef4aa8cc2a13fa0203fa

Signature · 1 line
2.55.0
author maintainer
#1 lore raw

PATCH 1/7 rust: workqueue: replace deprecated system_wq with system_{percpu,dfl}_wq

system_wq is deprecated and triggers a runtime warning:

	[    0.857414] workqueue: work func ...WorkItemPointerKy0_E3runB7_ enqueued on deprecated workqueue. Use system_{percpu|dfl}_wq instead.

Replace system() with system_percpu() and system_dfl(), to match the previous behavior of the deprecated system() and convert doc examples and tests to system_dfl().

---
 drivers/android/binder/process.rs |  4 ++--
 rust/kernel/sync/completion.rs    |  2 +-
 rust/kernel/workqueue.rs          | 40 +++++++++++++++++++------------
 3 files changed, 28 insertions(+), 18 deletions(-)
drivers/android/binder/process.rs +2 -2
index 96b8440ceac6..c0266fdaa598 100644
@@ -1632,7 +1632,7 @@ pub(crate) fn release(this: Arc<Process>, _file: &File) {
         if should_schedule {
             // Ignore failures to schedule to the workqueue. Those just mean that we're already
             // scheduled for execution.
-            let _ = workqueue::system().enqueue(this);
+            let _ = workqueue::system_percpu().enqueue(this);
         }
 
         drop(binderfs_file);
@@ -1649,7 +1649,7 @@ pub(crate) fn flush(this: ArcBorrow<'_, Process>) -> Result {
         if should_schedule {
             // Ignore failures to schedule to the workqueue. Those just mean that we're already
             // scheduled for execution.
-            let _ = workqueue::system().enqueue(Arc::from(this));
+            let _ = workqueue::system_percpu().enqueue(Arc::from(this));
         }
         Ok(())
     }
rust/kernel/sync/completion.rs +1 -1
index 35ff049ff078..1771bfc0ade2 100644
@@ -38,7 +38,7 @@
 ///             done <- Completion::new(),
 ///         }), GFP_KERNEL)?;
 ///
-///         let _ = workqueue::system().enqueue(this.clone());
+///         let _ = workqueue::system_dfl().enqueue(this.clone());
 ///
 ///         Ok(this)
 ///     }
rust/kernel/workqueue.rs +25 -15
index 7e253b6f299c..3194b9c441aa 100644
@@ -67,7 +67,7 @@
 //! /// This method will enqueue the struct for execution on the system workqueue, where its value
 //! /// will be printed.
 //! fn print_later(val: Arc<MyStruct>) {
-//!     let _ = workqueue::system().enqueue(val);
+//!     let _ = workqueue::system_dfl().enqueue(val);
 //! }
 //! # print_later(MyStruct::new(42).unwrap());
 //! ```
@@ -121,11 +121,11 @@
 //! }
 //!
 //! fn print_1_later(val: Arc<MyStruct>) {
-//!     let _ = workqueue::system().enqueue::<Arc<MyStruct>, 1>(val);
+//!     let _ = workqueue::system_dfl().enqueue::<Arc<MyStruct>, 1>(val);
 //! }
 //!
 //! fn print_2_later(val: Arc<MyStruct>) {
-//!     let _ = workqueue::system().enqueue::<Arc<MyStruct>, 2>(val);
+//!     let _ = workqueue::system_dfl().enqueue::<Arc<MyStruct>, 2>(val);
 //! }
 //! # print_1_later(MyStruct::new(24, 25).unwrap());
 //! # print_2_later(MyStruct::new(41, 42).unwrap());
@@ -171,13 +171,13 @@
 //! /// This method will enqueue the struct for execution on the system workqueue, where its value
 //! /// will be printed 12 jiffies later.
 //! fn print_later(val: Arc<MyStruct>) {
-//!     let _ = workqueue::system().enqueue_delayed(val, 12);
+//!     let _ = workqueue::system_dfl().enqueue_delayed(val, 12);
 //! }
 //!
 //! /// It is also possible to use the ordinary `enqueue` method together with `DelayedWork`. This
 //! /// is equivalent to calling `enqueue_delayed` with a delay of zero.
 //! fn print_now(val: Arc<MyStruct>) {
-//!     let _ = workqueue::system().enqueue(val);
+//!     let _ = workqueue::system_dfl().enqueue(val);
 //! }
 //! # print_later(MyStruct::new(42).unwrap());
 //! # print_now(MyStruct::new(42).unwrap());
@@ -1024,20 +1024,30 @@ unsafe impl<T, const ID: u64> RawDelayedWorkItem<ID> for ARef<T>
 {
 }
 
-/// Returns the system work queue (`system_wq`).
+/// Returns the system per-cpu work queue (`system_percpu_wq`).
 ///
 /// It is the one used by `schedule[_delayed]_work[_on]()`. Multi-CPU multi-threaded. There are
 /// users which expect relatively short queue flush time.
 ///
 /// Callers shouldn't queue work items which can run for too long.
-pub fn system() -> &'static Queue {
-    // SAFETY: `system_wq` is a C global, always available.
-    unsafe { Queue::from_raw(bindings::system_wq) }
+pub fn system_percpu() -> &'static Queue {
+    // SAFETY: `system_percpu_wq` is a C global, always available.
+    unsafe { Queue::from_raw(bindings::system_percpu_wq) }
+}
+
+/// Returns the system default (unbound) work queue (`system_dfl_wq`).
+///
+/// Workers are not bound to any specific CPU, not concurrency managed, and all queued work items
+/// are executed immediately as long as `max_active` limit is not reached and resources are
+/// available.
+pub fn system_dfl() -> &'static Queue {
+    // SAFETY: `system_dfl_wq` is a C global, always available.
+    unsafe { Queue::from_raw(bindings::system_dfl_wq) }
 }
 
 /// Returns the system high-priority work queue (`system_highpri_wq`).
 ///
-/// It is similar to the one returned by [`system`] but for work items which require higher
+/// It is similar to the one returned by [`system_percpu`] but for work items which require higher
 /// scheduling priority.
 pub fn system_highpri() -> &'static Queue {
     // SAFETY: `system_highpri_wq` is a C global, always available.
@@ -1046,8 +1056,8 @@ pub fn system_highpri() -> &'static Queue {
 
 /// Returns the system work queue for potentially long-running work items (`system_long_wq`).
 ///
-/// It is similar to the one returned by [`system`] but may host long running work items. Queue
-/// flushing might take relatively long.
+/// It is similar to the one returned by [`system_percpu`] but may host long running work items.
+/// Queue flushing might take relatively long.
 pub fn system_long() -> &'static Queue {
     // SAFETY: `system_long_wq` is a C global, always available.
     unsafe { Queue::from_raw(bindings::system_long_wq) }
@@ -1065,7 +1075,7 @@ pub fn system_unbound() -> &'static Queue {
 
 /// Returns the system freezable work queue (`system_freezable_wq`).
 ///
-/// It is equivalent to the one returned by [`system`] except that it's freezable.
+/// It is equivalent to the one returned by [`system_percpu`] except that it's freezable.
 ///
 /// A freezable workqueue participates in the freeze phase of the system suspend operations. Work
 /// items on the workqueue are drained and no new work item starts execution until thawed.
@@ -1078,7 +1088,7 @@ pub fn system_freezable() -> &'static Queue {
 ///
 /// It is inclined towards saving power and is converted to "unbound" variants if the
 /// `workqueue.power_efficient` kernel parameter is specified; otherwise, it is similar to the one
-/// returned by [`system`].
+/// returned by [`system_percpu`].
 pub fn system_power_efficient() -> &'static Queue {
     // SAFETY: `system_power_efficient_wq` is a C global, always available.
     unsafe { Queue::from_raw(bindings::system_power_efficient_wq) }
@@ -1097,7 +1107,7 @@ pub fn system_freezable_power_efficient() -> &'static Queue {
 
 /// Returns the system bottom halves work queue (`system_bh_wq`).
 ///
-/// It is similar to the one returned by [`system`] but for work items which
+/// It is similar to the one returned by [`system_percpu`] but for work items which
 /// need to run from a softirq context.
 pub fn system_bh() -> &'static Queue {
     // SAFETY: `system_bh_wq` is a C global, always available.
Signature · 1 line
2.55.0
author maintainer
#2 lore raw

PATCH 2/7 rust: workqueue: restrict delayed work to global wqs

In reply to Danilo Krummrich

From: Alice Ryhl <[email protected]>

When a workqueue is shut down, delayed work that is pending but not scheduled does not get properly cleaned up, so it's not safe to use enqueue_delayed on a workqueue that might be destroyed. To fix this, restricted enqueue_delayed to static queues.

This may be fixed in the future by an approach along the lines of [1].

---
 rust/kernel/workqueue.rs | 9 ++++++++-
 1 file changed, 8 insertions(+), 1 deletion(-)
rust/kernel/workqueue.rs +8 -1
index 3194b9c441aa..b6e02ba427b3 100644
@@ -302,8 +302,15 @@ pub fn enqueue<W, const ID: u64>(&self, w: W) -> W::EnqueueOutput
     ///
     /// This may fail if the work item is already enqueued in a workqueue.
     ///
+    /// This is only valid for global workqueues (with static lifetimes) because those are the only
+    /// ones that outlive all possible delayed work items.
+    ///
     /// The work item will be submitted using `WORK_CPU_UNBOUND`.
-    pub fn enqueue_delayed<W, const ID: u64>(&self, w: W, delay: Jiffies) -> W::EnqueueOutput
+    pub fn enqueue_delayed<W, const ID: u64>(
+        &'static self,
+        w: W,
+        delay: Jiffies,
+    ) -> W::EnqueueOutput
     where
         W: RawDelayedWorkItem<ID> + Send + 'static,
     {
Signature · 1 line
2.55.0
author maintainer
#3 lore raw

PATCH 3/7 rust: workqueue: create workqueue subdirectory

In reply to Danilo Krummrich

From: Alice Ryhl <[email protected]>

The following patch will implement a workqueue builder in a separate file. To prepare for that, create a rust/kernel/workqueue subdirectory and move the existing file.

---
 MAINTAINERS                                    | 1 +
 rust/kernel/{workqueue.rs => workqueue/mod.rs} | 0
 2 files changed, 1 insertion(+)
 rename rust/kernel/{workqueue.rs => workqueue/mod.rs} (100%)
MAINTAINERS +1 -0
index f672858996f0..9cee804d840d 100644
@@ -29155,6 +29155,7 @@ F:	Documentation/core-api/workqueue.rst
 F:	include/linux/workqueue.h
 F:	kernel/workqueue.c
 F:	kernel/workqueue_internal.h
+F:	rust/kernel/workqueue/
 
 WWAN DRIVERS
 M:	Loic Poulain <[email protected]>
rust/kernel/workqueue/mod.rs renamed from rust/kernel/workqueue.rs +0 -0
similarity index 100%
rename from rust/kernel/workqueue.rs
rename to rust/kernel/workqueue/mod.rs
Signature · 1 line
2.55.0
author maintainer
#4 lore raw

PATCH 4/7 rust: workqueue: add creation of workqueues

In reply to Danilo Krummrich

From: Alice Ryhl <[email protected]>

Creating workqueues is needed by various GPU drivers. Not only does it give you better control over execution, it also allows devices to ensure that all tasks have exited before the device is unbound (or similar) by running the workqueue destructor.

[ * Fix import formatting of ptr::{self, NonNull},
* rename T to Kind,
* new_ordered(): set max_active: 1,
* new_power_efficient(): WQ_UNBOUND | WQ_POWER_EFFICIENT, add

    .percpu(),

* new_bh(): WQ_PERCPU | WQ_BH, removed .percpu(),
* various doc improvements: new_percpu, max_active, cpu_intensive, freezable.

- Danilo ]

---
 rust/helpers/workqueue.c         |   7 +
 rust/kernel/workqueue/builder.rs | 389 +++++++++++++++++++++++++++++++
 rust/kernel/workqueue/mod.rs     |  44 +++-
 3 files changed, 437 insertions(+), 3 deletions(-)
 create mode 100644 rust/kernel/workqueue/builder.rs
rust/helpers/workqueue.c +7 -0
index ce1c3a5b2150..e4b9d1b3d6bf 100644
@@ -14,3 +14,10 @@ __rust_helper void rust_helper_init_work_with_key(struct work_struct *work,
 	INIT_LIST_HEAD(&work->entry);
 	work->func = func;
 }
+
+__rust_helper
+struct workqueue_struct *rust_helper_alloc_workqueue(const char *fmt, unsigned int flags,
+						     int max_active, const void *data)
+{
+	return alloc_workqueue(fmt, flags, max_active, data);
+}
rust/kernel/workqueue/builder.rs new file +389 -0

389 lines not on this page · raw message

rust/kernel/workqueue/mod.rs +41 -3

68 lines not on this page · raw message

Signature · 1 line
2.55.0
author maintainer
#5 lore raw

PATCH 5/7 rust: workqueue: add ScopedQueue for lifetime bound items

In reply to Danilo Krummrich

From: Onur Özkan <[email protected]>

Add a workqueue wrapper for work items that are not 'static.

Tyr reset work is queued from a handle that owns a Controller<'bound> where the work item holds references tied to the lifetime of the bound device and its mapped IO state. The existing API only accepts 'static work items which cannot express that relationship.

Introduce ScopedQueue for this case. It owns the underlying workqueue and ties enqueued work to the queue lifetime so borrowed state cannot outlive the queue that may still run it.

Construction is unsafe because the queue must not be leaked.

compile_fail doc-tests are ignored for now as KUnit doesn't support that. Enabling those tests as regular code block would raise this error:

    ERROR:root:error[E0597]: `data` does not live long enough
	 --> rust/doctests_kernel_generated.rs:22029:44
	  |
    22027 |         let data = ();
	  |             ---- binding `data` declared here
    22028 |         // SAFETY: Queue is not leaked.
    22029 |         queue = unsafe { new_queue(&data)? };
	  |                                            ^^^^^ borrowed value does not live long enough
    22030 |     }
	  |     - `data` dropped here while still borrowed
    ...
    22034 | }
	  | - borrow might be used here, when `queue` is dropped and runs the `Drop` code for type `ScopedQueue`
	  |
	  = note: values in a scope are dropped in the opposite order they are defined

which is exactly the constraint ScopedQueue is meant to enforce.

---
 rust/kernel/workqueue/mod.rs          |   3 +
 rust/kernel/workqueue/scoped_queue.rs | 187 ++++++++++++++++++++++++++
 2 files changed, 190 insertions(+)
 create mode 100644 rust/kernel/workqueue/scoped_queue.rs
rust/kernel/workqueue/mod.rs +3 -0
index 747fea980aa2..5de88c59b2e5 100644
@@ -212,6 +212,9 @@
 mod builder;
 pub use self::builder::Builder;
 
+mod scoped_queue;
+pub use self::scoped_queue::ScopedQueue;
+
 /// Creates a [`Work`] initialiser with the given name and a newly-created lock class.
 #[macro_export]
 macro_rules! new_work {
rust/kernel/workqueue/scoped_queue.rs new file +187 -0

187 lines not on this page · raw message

Signature · 1 line
2.55.0
author maintainer
#6 lore raw

PATCH 6/7 rust: workqueue: add Work::cancel_work_sync()

In reply to Danilo Krummrich

Add a method to cancel a work item and wait for it to finish if it is currently running.

This will also be used by ScopedWork's destructor to synchronously cancel work before dropping borrowed data.

---
 rust/kernel/workqueue/mod.rs | 8 ++++++++
 1 file changed, 8 insertions(+)
rust/kernel/workqueue/mod.rs +8 -0
index 5de88c59b2e5..2b87f935712a 100644
@@ -585,6 +585,14 @@ 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 the work item and waits for it to finish if it is running.
+    ///
+    /// Returns `true` if the work was pending, `false` otherwise.
+    pub fn cancel_work_sync(&self) -> bool {
+        // SAFETY: We have a reference to a valid, initialized Work, so the pointer is valid.
+        unsafe { bindings::cancel_work_sync(Self::raw_get(self)) }
+    }
 }
 
 /// Declares that a type contains a [`Work<T, ID>`].
Signature · 1 line
2.55.0
#7 lore raw

Re: [PATCH 6/7] rust: workqueue: add Work::cancel_work_sync()

Quoted 17 lines · Danilo Krummrich

Add a method to cancel a work item and wait for it to finish if it is currently running.

This will also be used by ScopedWork's destructor to synchronously cancel work before dropping borrowed data.

---
 rust/kernel/workqueue/mod.rs | 8 ++++++++
 1 file changed, 8 insertions(+)
rust/kernel/workqueue/mod.rs +0 -0
index 5de88c59b2e5..2b87f935712a 100644
@@ -585,6 +585,14 @@ pub unsafe fn raw_get(ptr: *const Self) -> *mut bindings::work_struct {
         // the compiler does not complain that the `work` field is unused.

rust/kernel/workqueue/mod.rs pub unsafe fn raw_get(ptr: *const Self) -> *mut bindings::work_struct { · line 595

Quoted 10 lines
rust/kernel/workqueue/mod.rs +8 -0
         unsafe { Opaque::cast_into(core::ptr::addr_of!((*ptr).work)) }
     }
+
+    /// Cancels the work item and waits for it to finish if it is running.
+    ///
+    /// Returns `true` if the work was pending, `false` otherwise.
+    pub fn cancel_work_sync(&self) -> bool {
+        // SAFETY: We have a reference to a valid, initialized Work, so the pointer is valid.
+        unsafe { bindings::cancel_work_sync(Self::raw_get(self)) }
+    }

This seems to expose a way for driver writers to leak work items, doesn't it?

Previously, work items were either run, or failed to enqueue, and both of those paths restored the Arc via Arc::from_raw().

But now with this new cancel_work_sync(), Arc::from_raw() never gets called. So for example:

#[pin_data]

struct MyStruct {
    #[pin]
    work: Work<MyStruct>,
}
impl_has_work! {
    impl HasWork<Self> for MyStruct { self.work }
}
impl WorkItem for MyStruct {
    type Pointer = Arc<MyStruct>;

    fn run(_this: Arc<MyStruct>) {}
}

let obj = Arc::pin_init(

    pin_init!(MyStruct {
        work <- new_work!("MyStruct::work"),
    }),
    GFP_KERNEL,

)?;

// refcount 1 -> 2, and the workqueue owns the second one let _ = workqueue::system_dfl().enqueue(obj.clone());

// takes it off the worklist, so run() never reclaims that reference obj.work.cancel_work_sync();

// refcount 2 -> 1. MyStruct is never dropped.
drop(obj);

thanks,

Signature · 1 line
John Hubbard
author maintainer
#8 lore raw

Re: [PATCH 6/7] rust: workqueue: add Work::cancel_work_sync()

Quoted 2 lines · John Hubbard

This seems to expose a way for driver writers to leak work items, doesn't it?

Yes, I forgot about this for a second; this should be on ScopedWork only (at least without further effort to make it work properly for Work too).

Since you explicitly mention "driver writers", note that unbounded work shouldn't really have any (valid) use-cases within drivers. So drivers should either use ScopedQueue or ScopedWork.

It is of course possible to use Work with a ScopedQueue, but at this point it is unnecessary; the requirement is already that the Work must outlive the ScopedQueue. So using ScopedWork instead saves an otherwise unnecessary allocation and reference count.

(I also noticed that the run() callback of ScopedWork should pass &ScopedWork<Self> instead of just &Self, such that self-requeue is easily possible; I will add this in v2.)

#9 lore raw

Re: [PATCH 6/7] rust: workqueue: add Work::cancel_work_sync()

Quoted 10 lines · Danilo Krummrich
Quoted 2 lines · John Hubbard

This seems to expose a way for driver writers to leak work items, doesn't it?

Yes, I forgot about this for a second; this should be on ScopedWork only (at least without further effort to make it work properly for Work too).

Since you explicitly mention "driver writers", note that unbounded work shouldn't really have any (valid) use-cases within drivers. So drivers should either use ScopedQueue or ScopedWork.

Yes, agreed. Perhaps I shouldn't have used "drivers" as the example. I was just trying to show that this exposes an API that will leak refcounts.

thanks,

Signature · 1 line
John Hubbard
reviewer
#10 lore raw

Re: [PATCH 6/7] rust: workqueue: add Work::cancel_work_sync()

In reply to Danilo Krummrich
Quoted 18 lines · On Tue, 04 Aug 2026 21:52:08 +0200 Danilo Krummrich <[email protected]> wrote:

Add a method to cancel a work item and wait for it to finish if it is currently running.

This will also be used by ScopedWork's destructor to synchronously cancel work before dropping borrowed data.

---
 rust/kernel/workqueue/mod.rs | 8 ++++++++
 1 file changed, 8 insertions(+)
rust/kernel/workqueue/mod.rs +0 -0
index 5de88c59b2e5..2b87f935712a 100644
@@ -585,6 +585,14 @@ 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)) }

rust/kernel/workqueue/mod.rs pub unsafe fn raw_get(ptr: *const Self) -> *mut bindings::work_struct { · line 596

Quoted 10 lines
rust/kernel/workqueue/mod.rs +8 -0
     }
+
+    /// Cancels the work item and waits for it to finish if it is running.
+    ///
+    /// Returns `true` if the work was pending, `false` otherwise.
+    pub fn cancel_work_sync(&self) -> bool {
+        // SAFETY: We have a reference to a valid, initialized Work, so the pointer is valid.
+        unsafe { bindings::cancel_work_sync(Self::raw_get(self)) }
+    }
 }

We can't directly add cancel_sync support to every work items. Perhaps you could pull the exiting effort for cancel_sync support [1] which is also used by the tyr reset implementation [2]?

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

Quoted 5 lines
rust/kernel/workqueue/mod.rs +0 -0
 /// Declares that a type contains a [`Work<T, ID>`].
Signature · 1 line
2.55.0
author maintainer
#11 lore raw

Re: [PATCH 6/7] rust: workqueue: add Work::cancel_work_sync()

Quoted 2 lines · Onur Özkan

Perhaps you could pull the exiting effort for cancel_sync support [1] which is also used by the tyr reset implementation [2]?

Please also see my reply to John [3].

I think for your implementation in Tyr you should just use ScopedWork, which should simplify the implementation significantly.

cancel_sync() for Work could be useful regardless, but it seems to be an orthogonal effort that requires a separate use-case, so I rather not include it in this series.

Quoted 2 lines

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

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

author maintainer
#12 lore raw

PATCH 7/7 rust: workqueue: add ScopedWork for non-'static work items

In reply to Danilo Krummrich

Add ScopedWork<T>, a work item wrapper whose destructor calls cancel_work_sync(), allowing T to carry non-'static lifetimes. Ownership of the data is not transferred to the workqueue; instead, the synchronous cancellation on drop guarantees the work function is not running when the data is freed.

ScopedWork uses the existing Work/HasWork/WorkItem infrastructure with NonNull<Self> as WorkItem::Pointer for the callback path, and implements RawWorkItem for Pin<&ScopedWork<T>> for the enqueue path (requiring T:
Sync for cross-thread shared access safety).

Two enqueue paths are provided:
- Queue::enqueue_scoped() / ScopedQueue::enqueue_scoped() (unsafe):
the caller must ensure the work item is not forgotten.
- ScopedQueue::enqueue() (safe): when the work item's lifetime satisfies the queue's 'scope bound.

---
 rust/kernel/workqueue/mod.rs          |  43 +++-
 rust/kernel/workqueue/scoped_queue.rs |  37 +++-
 rust/kernel/workqueue/scoped_work.rs  | 290 ++++++++++++++++++++++++++
 3 files changed, 348 insertions(+), 22 deletions(-)
 create mode 100644 rust/kernel/workqueue/scoped_work.rs
rust/kernel/workqueue/mod.rs +32 -11
index 2b87f935712a..11477d42020b 100644
@@ -215,6 +215,13 @@
 mod scoped_queue;
 pub use self::scoped_queue::ScopedQueue;
 
+mod scoped_work;
+pub use self::scoped_work::{
+    new_scoped_work,
+    ScopedWork,
+    ScopedWorkItem, //
+};
+
 /// Creates a [`Work`] initialiser with the given name and a newly-created lock class.
 #[macro_export]
 macro_rules! new_work {
@@ -286,20 +293,34 @@ pub unsafe fn from_raw<'a>(ptr: *const bindings::workqueue_struct) -> &'a Queue
     pub fn enqueue<W, const ID: u64>(&self, w: W) -> W::EnqueueOutput
     where
         W: RawWorkItem<ID> + Send + 'static,
+    {
+        // SAFETY: `W: 'static` guarantees the work item remains valid indefinitely,
+        // so the `enqueue_scoped` requirement that the work item stays valid until
+        // the work function runs (or is cancelled) is trivially satisfied.
+        unsafe { self.enqueue_scoped(w) }
+    }
+
+    /// Enqueues a work item that may not be `'static`.
+    ///
+    /// Unlike [`Queue::enqueue`], this does not require the work item to be `'static`.
+    ///
+    /// The work item will be submitted using `WORK_CPU_UNBOUND`.
+    ///
+    /// # Safety
+    ///
+    /// The caller must ensure that the work item's destructor runs before any
+    /// lifetime it captures expires (i.e., the work item must not be forgotten).
+    pub unsafe fn enqueue_scoped<W, const ID: u64>(&self, w: W) -> W::EnqueueOutput
+    where
+        W: RawWorkItem<ID> + Send,
     {
         let queue_ptr = self.0.get();
 
-        // SAFETY: We only return `false` if the `work_struct` is already in a workqueue. The other
-        // `__enqueue` requirements are not relevant since `W` is `Send` and static.
-        //
-        // The call to `bindings::queue_work_on` will dereference the provided raw pointer, which
-        // is ok because `__enqueue` guarantees that the pointer is valid for the duration of this
-        // closure.
-        //
-        // Furthermore, if the C workqueue code accesses the pointer after this call to
-        // `__enqueue`, then the work item was successfully enqueued, and `bindings::queue_work_on`
-        // will have returned true. In this case, `__enqueue` promises that the raw pointer will
-        // stay valid until we call the function pointer in the `work_struct`, so the access is ok.
+        // SAFETY: We only return `false` if the `work_struct` is already in a workqueue. The
+        // caller guarantees the work item remains valid until the work function runs or the item
+        // is cancelled, satisfying the `__enqueue` requirement that the pointer stays valid until
+        // the function pointer in the `work_struct` is called. `W: Send` satisfies the
+        // cross-thread safety requirement.
         unsafe {
             w.__enqueue(move |work_ptr| {
                 bindings::queue_work_on(
rust/kernel/workqueue/scoped_queue.rs +26 -11
index d4b9a03fd93c..21928d60a63b 100644
@@ -152,20 +152,35 @@ pub unsafe fn new(name: &'static CStr) -> Result<Self> {
     pub fn enqueue<W, const ID: u64>(&self, work: W) -> W::EnqueueOutput
     where
         W: RawWorkItem<ID> + Send + 'scope,
+    {
+        // SAFETY: `W: 'scope` and dropck keep borrowed data alive until this queue
+        // is dropped. The constructor requires that the queue is not leaked and
+        // dropping `inner` drains pending and running work, so the function pointer
+        // is not called after any lifetime in `W` expires.
+        unsafe { self.enqueue_scoped(work) }
+    }
+
+    /// Enqueues a work item without the `'scope` lifetime bound.
+    ///
+    /// Unlike [`ScopedQueue::enqueue`], this does not require `W: 'scope`.
+    ///
+    /// Prefer [`ScopedQueue::enqueue`] when the work item's lifetime satisfies
+    /// `'scope`.
+    ///
+    /// # Safety
+    ///
+    /// The caller must ensure that the work item's destructor runs before any
+    /// lifetime it captures expires (i.e., the work item must not be forgotten).
+    pub unsafe fn enqueue_scoped<W, const ID: u64>(&self, work: W) -> W::EnqueueOutput
+    where
+        W: RawWorkItem<ID> + Send,
     {
         let queue_ptr = self.inner.0.get();
 
-        // SAFETY:
-        // - Closure returns `false` only if `queue_work_on` returns `false`
-        //   and that means `work_ptr` is already in a workqueue.
-        //
-        // - `W: 'scope` and dropck keep borrowed data alive until this queue is
-        //   dropped. The constructor requires that the queue is not leaked and
-        //   dropping `inner` drains pending and running work so the function
-        //   pointer is not called after any lifetime in `W` expires.
-        //
-        // - The last requirement of `__enqueue` is not relevant here because `W`
-        //   is `Send`.
+        // SAFETY: The caller guarantees the work item remains valid until the work
+        // function runs or the item is cancelled. `W: Send` satisfies the
+        // cross-thread safety requirement. The closure only returns `false` if the
+        // `work_struct` is already in a workqueue.
         unsafe {
             work.__enqueue(move |work_ptr| {
                 bindings::queue_work_on(
rust/kernel/workqueue/scoped_work.rs new file +290 -0

290 lines not on this page · raw message

Signature · 1 line
2.55.0