Skip to contentSkip to conversation

workqueue: OwnedQueue and ScopedWork

PATCH Superseded Alice Ryhl 2 participants 6 messages Oct 20 – Nov 9

Subsystems (3)

v3 of 4 Superseded Latest is v4 →

lore
Share & tools
lore

Alice Ryhl

author reviewer
#0 lore raw

v3 cover workqueue: OwnedQueue and ScopedWork

This series extends the Rust workqueue bindings with the ability to create custom workqueues (OwnedQueue), and introduces ScopedWork, a work item type that cancels synchronously on drop, allowing drivers to use workqueues with lifetime-bound data.

This is a continuation of Danilo's v2 [4], which picked up my earlier series [1] and Onur's ScopedQueue work [2].

Patch 1/6 of v2, "rust: workqueue: replace deprecated system_wq with system_{percpu,dfl}_wq", is a fix and has been sent separately [3]. This series no longer depends on it.

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

Changes in v3:
- Rebase on v7.3-rc7
- Split out the system_wq patch and send it separately as a fix [3]; this series no longer depends on it
- Drop ScopedQueue: with the ScopedWork changes below it is no longer needed to enqueue non-'static work items, and it has no other user
- ScopedWork: make ScopedWork::new() unsafe instead of Queue::enqueue_scoped(), which is now a safe method accepting &ScopedWork<T> on any queue
- ScopedWork: drop the WorkItem/WorkItemPointer/HasWork impls and the public ScopedWorkRef type; embed the work_struct directly with a dedicated callback, and keep the Opaque-wrapped payload private
- ScopedWork: drop T on drop (Opaque does not run destructors)
- ScopedWork: propagate the initializer's error type from new()
- Builder: new_power_efficient() uses WQ_PERCPU | WQ_POWER_EFFICIENT; remove the now pointless percpu() modifier
- Pick up Reviewed-by tags from Daniel
- Link to v2: https://lore.kernel.org/all/[email protected]

Changes in v2:
- Merge scoped_work.rs and scoped_queue.rs into scoped.rs
- Introduce ScopedWorkRef<T> and wrap it in Opaque inside ScopedWork to avoid &mut aliasing in drop
- Pass &ScopedWorkRef<Self> to ScopedWorkItem::run to enable self-re-enqueue
- Add Deref<Target = Queue> for ScopedQueue; remove duplicate enqueue_scoped()
- Add Send + Sync for OwnedQueue
- Fix stale workqueue::system() references in docs
- Drop Work::cancel_work_sync()
- Make sysfs() available on ordered workqueues
- Add #[inline] annotations throughout

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

Danilo Krummrich (1):
rust: workqueue: add ScopedWork for non-'static work items

 MAINTAINERS                                    |   1 +
 rust/helpers/workqueue.c                       |   7 +
 rust/kernel/workqueue/builder.rs               | 370 +++++++++++++++++++++++++
 rust/kernel/{workqueue.rs => workqueue/mod.rs} | 108 +++++++-
 rust/kernel/workqueue/scoped.rs                | 342 +++++++++++++++++++++++
 5 files changed, 823 insertions(+), 5 deletions(-)

---
base-commit: 24a19b953e2a3d0ea5a8c4951a0ab8f32720c907
change-id: 20261012-rust-workqueue-658cd0fbe770

Best regards,

Signature · 1 line
Alice Ryhl <[email protected]>
author reviewer
#1 lore raw

PATCH v3 1/4 rust: workqueue: restrict delayed work to global wqs

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 7e253b6f299c..aa8a472f4547 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.56.0.212.g129ede20d9-goog
author reviewer
#2 lore raw

PATCH v3 2/4 rust: workqueue: create workqueue subdirectory

In reply to Alice Ryhl

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(+)
MAINTAINERS +1 -0
index f53047aa8d3c..685ace2e27d1 100644
@@ -29515,6 +29515,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.56.0.212.g129ede20d9-goog
author reviewer
#4 lore raw

PATCH v3 3/4 rust: workqueue: add creation of workqueues

In reply to Alice Ryhl

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.

---
 rust/helpers/workqueue.c         |   7 +
 rust/kernel/workqueue/builder.rs | 370 +++++++++++++++++++++++++++++++++++++++
 rust/kernel/workqueue/mod.rs     |  51 +++++-
 3 files changed, 425 insertions(+), 3 deletions(-)
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 +370 -0

370 lines not on this page · raw message

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

75 lines not on this page · raw message

Signature · 1 line
2.56.0.212.g129ede20d9-goog
author reviewer
#5 lore raw

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

In reply to Alice Ryhl

From: Danilo Krummrich <[email protected]>

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.

Because that guarantee only holds if the destructor actually runs, ScopedWork::new() (and thus new_scoped_work!) is unsafe and requires that the resulting value is never forgotten. In return, Queue::enqueue_scoped() is a safe method that accepts a &ScopedWork<T> on any queue, including the system queues.

ScopedWork does not use the Work/WorkItem machinery: it embeds the work_struct directly and registers its own C callback, which recovers the &ScopedWork<T> via container_of!() and passes it to ScopedWorkItem::run(). The work_struct and the user data live in a private Inner<T> that is wrapped in Opaque as a whole, so that the &mut Self held by the destructor while cancel_work_sync() waits does not claim uniqueness over memory (including padding) that a worker thread may still be reading through &ScopedWork<T>.

---
 rust/kernel/workqueue/mod.rs    |  48 +++++-
 rust/kernel/workqueue/scoped.rs | 342 ++++++++++++++++++++++++++++++++++++++++
 2 files changed, 389 insertions(+), 1 deletion(-)
rust/kernel/workqueue/mod.rs +47 -1
index 78e6a7bb960a..73fa0bea4220 100644
@@ -212,6 +212,13 @@
 mod builder;
 pub use self::builder::Builder;
 
+mod scoped;
+pub use self::scoped::{
+    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 {
@@ -283,11 +290,50 @@ 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`, so everything borrowed by `W` remains valid forever.
+        unsafe { self.enqueue_raw(w) }
+    }
+
+    /// Enqueues a [`ScopedWork`] item.
+    ///
+    /// Unlike [`Queue::enqueue`], this does not require the work item to be `'static`. This is
+    /// sound because a [`ScopedWork`] cancels itself synchronously when it is dropped, and
+    /// [`ScopedWork::new`] requires that this destructor runs before any lifetime in `T` expires.
+    ///
+    /// This may fail if the work item is already enqueued in a workqueue.
+    ///
+    /// The work item will be submitted using `WORK_CPU_UNBOUND`.
+    #[inline]
+    pub fn enqueue_scoped<T>(&self, w: &ScopedWork<T>) -> bool
+    where
+        T: ScopedWorkItem + Sync,
+    {
+        // SAFETY: The `ScopedWork` destructor calls `cancel_work_sync()`, and `ScopedWork::new`
+        // guarantees that this destructor runs before any lifetime in `T` expires. Hence everything
+        // borrowed by `T` remains valid until the work item has run to completion or has been
+        // cancelled.
+        unsafe { self.enqueue_raw(w) }
+    }
+
+    /// Enqueues a work item without requiring it to be `'static`.
+    ///
+    /// # Safety
+    ///
+    /// Everything borrowed by `W` must remain valid until the work item has run to completion or
+    /// has been cancelled.
+    #[inline]
+    unsafe fn enqueue_raw<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.
+        // `__enqueue` requirements are not relevant since `W` is `Send` and the caller guarantees
+        // that everything borrowed by `W` remains valid until the work item has run to completion
+        // or has been cancelled, so the function pointer is never called after a lifetime in `W`
+        // expires.
         //
         // 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
rust/kernel/workqueue/scoped.rs new file +342 -0

342 lines not on this page · raw message

Signature · 1 line
2.56.0.212.g129ede20d9-goog