Re: [PATCH v2 5/8] rust: workqueue: add helper for defining work_struct fields

Boqun Feng
2023-06-02T16:34:18Z

On Fri, Jun 02, 2023 at 08:38:56AM +0000, Alice Ryhl wrote:
> Boqun Feng <boqun.feng@gmail.com> writes:
> > On Thu, Jun 01, 2023 at 01:49:43PM +0000, Alice Ryhl wrote:
> >> diff --git a/rust/helpers.c b/rust/helpers.c
> >> index 81e80261d597..7f0c2fe2fbeb 100644
> >> --- a/rust/helpers.c
> >> +++ b/rust/helpers.c
> >> @@ -26,6 +26,7 @@
> >> #include <linux/spinlock.h>
> >> #include <linux/sched/signal.h>
> >> #include <linux/wait.h>
> >> +#include <linux/workqueue.h>
> >>
> >> __noreturn void rust_helper_BUG(void)
> >> {
> >> @@ -128,6 +129,13 @@ void rust_helper_put_task_struct(struct task_struct *t)
> >> }
> >> EXPORT_SYMBOL_GPL(rust_helper_put_task_struct);
> >>
> >> +void rust_helper___INIT_WORK(struct work_struct *work, work_func_t func,
> >> + bool on_stack)
> >> +{
> >> + __INIT_WORK(work, func, on_stack);
> >
> > Note here all the work items in Rust will share the same lockdep class.
> > That could be problematic: the lockdep classes for work are for
> > detecting deadlocks in the following scenario:
> >
> > step 1: queue a work "foo", whose work function is:
> >
> > mutex_lock(&bar);
> > do_something(...);
> > mutex_unlock(&bar);
> >
> > step 2: in another thread do:
> >
> > mutex_lock(&bar);
> > flush_work(foo); // wait until work "foo" is finished.
> >
> > if this case, if step 2 get the lock "bar" first, it's a deadlock.
> >
> > With the current implementation, all the work items share the same
> > lockdep class, so the following will be treated as deadlock:
> >
> > <in work "work1">
> > mutex_lock(&bar);
> > do_something(...);
> > mutex_unlock(&bar);
> >
> > <in another thread>
> > mutex_lock(&bar);
> > flush_work(work2); // flush work2 intead of work1.
> >
> > which is a false positive. We at least need some changes in C side to
> > make it work:
> >
> > https://lore.kernel.org/rust-for-linux/20220802015052.10452-7-ojeda@kernel.org/
> >
> > however, that still has the disadvantage that all Rust work items have
> > the same name for the lockdep classes.. maybe we should extend that for
> > an extra "name" parameter. And then it's not necessary to be a macro.
>
> Yeah, I did know about this issue, but I didn't know what the best way
> to fix it is. What solution would you like me to use?
>

Having a init_work_with_key() function in C side:

void init_work_with_key(struct work_struct *work, bool onstack,
const char *name, struct lock_class_key *key)
{
__init_work(work, onstack); \
work->data = (atomic_long_t) WORK_DATA_INIT(); \
lockdep_init_map(&work->lockdep_map, name, key, 0); \
INIT_LIST_HEAD(&work->entry); \
work->func = func; \
}

, and provide class key and name from Rust side.

Thoughts?

Regards,
Boqun

> Alice