Re: [PATCH v4 5/5] rust: workqueue: add ScopedWork for non-'static work items

From: Alice Ryhl

Date: Thu Nov 26 2026 - 07:43:25 EST


On Thu, Nov 26, 2026 at 12:22 PM Tejun Heo <tj@xxxxxxxxxx> wrote:
>
> Hello, Alice.
>
> On Wed, Nov 25, 2026 at 06:17:52PM +0000, Alice Ryhl wrote:
> > What I'd say is that this isn't the only way to spawn work on the
> > workqueue. This utility is intended for use-cases where it's convenient
> > to do it like that (e.g. because the queue is defined before the work
> > item in the same struct). We already have another way of spawning work
> > that uses different ownership rules (e.g. self-freeing work) and that
> > mechanism would not go through ScopedWork.
>
> This is your design and you know this area far better than I do, so please
> take this with a grain of salt. That said, I wonder whether the interface
> is more tortured and twisted than it needs to be.

Always happy to discuss! Thanks for the question.

> Workqueue lifetime seems to add a layer of ugliness, at least going by the
> restrictions on ScopedWork. Wouldn't that be relatively easy to solve by
> adding a percpu refcnt to the Rust wrapper of workqueue and tying work and
> delayed work items to it? Dropping the workqueue would wait until nothing
> is pending, and cancelling delayed work items before that would be up to
> the user. Work and delayed work items would then behave the same way and
> be usable on any workqueue.

I'll take a step back for one moment. The previous version of this
patchset did not have the lifetime in question. Adding a percpu
refcount doesn't resolve the issue that made me add it, unfortunately.

The problem is: if we drop a ScopedWork early, then once
cancel_work_sync() returns, we may free resources used by that work
item. Obviously if the work item is still executing on some workqueue
after cancel_work_sync() returns, that would be bad, as it would use
resources now freed.

Originally I did not think this was an issue. I assumed that if
cancel_work_sync() returns, and there was no concurrent resubmission,
then it would no longer be running. However, this is not true:
https://lore.kernel.org/all/20261118-ordered-wq-cancel-v1-2-916e01f9affe@xxxxxxxxxx/

My fix for this issue was to add a &Workqueue field to ScopedWork and
enforce that the scoped work item can only ever be scheduled to that
one workqueue. By only ever using it with one workqueue, I know the
non-reentrance conditions hold, and so I know that when
cancel_work_sync() returns, the work item is not running anywhere, and
hence it's safe to perform cleanup.

Of course, there may be other ways to enforce the non-reentrance
conditions hold, which could let me get rid of the lifetime. But the
lifetime is there to handle the cleanup before destroy_workqueue() is
called case, so a percpu refcount does not come into play.


Alice