Re: [PATCH v4 5/5] rust: workqueue: add ScopedWork for non-'static work items
From: Gary Guo
Date: Wed Nov 25 2026 - 12:10:08 EST
On Thu Nov 19, 2026 at 2:12 PM GMT, Alice Ryhl wrote:
> From: Danilo Krummrich <dakr@xxxxxxxxxx>
>
> Add ScopedWork<'wq, T>, a work item wrapper bound to a specific
> &'wq Queue 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.
>
> Each ScopedWork<'wq, T> is bound to a single Queue at construction and
> enqueued via ScopedWork::enqueue() to uphold the non-reentrance
> conditions documented in Documentation/core-api/workqueue.rst: queuing
> an in-flight work item onto a different workqueue violates those
> conditions, in which case cancel_work_sync() only waits for execution on
> the last queued workqueue and may return while an earlier execution is
> still running.
>
> Because the cancellation guarantee only holds if the destructor runs
> before the bound Queue or any lifetime in T expires, ScopedWork::new()
> (and thus new_scoped_work!) is unsafe and requires that the resulting
> value is never forgotten and is dropped before 'wq or T's lifetimes end.
> In return, ScopedWork::enqueue() is a safe method.
>
> 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, queue pointer, and 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>.
>
> Signed-off-by: Danilo Krummrich <dakr@xxxxxxxxxx>
> Co-developed-by: Alice Ryhl <aliceryhl@xxxxxxxxxx>
> Signed-off-by: Alice Ryhl <aliceryhl@xxxxxxxxxx>
Reviewed-by: Gary Guo <gary@xxxxxxxxxxx>
> ---
> rust/kernel/workqueue/mod.rs | 13 ++
> rust/kernel/workqueue/scoped.rs | 410 ++++++++++++++++++++++++++++++++++++++++
> 2 files changed, 423 insertions(+)