Blob Blame History Raw
From a7c01fa93aeb03ab76cd3cb2107990dd160498e6 Mon Sep 17 00:00:00 2001
From: "Jason A. Donenfeld" <Jason@zx2c4.com>
Date: Tue, 12 Jul 2022 01:21:23 +0200
Subject: [PATCH] signal: break out of wait loops on kthread_stop()
Git-commit: a7c01fa93aeb03ab76cd3cb2107990dd160498e6
Patch-mainline: v6.1-rc1
References: bsc#1204926

I was recently surprised to learn that msleep_interruptible(),
wait_for_completion_interruptible_timeout(), and related functions
simply hung when I called kthread_stop() on kthreads using them. The
solution to fixing the case with msleep_interruptible() was more simply
to move to schedule_timeout_interruptible(). Why?

The reason is that msleep_interruptible(), and many functions just like
it, has a loop like this:

        while (timeout && !signal_pending(current))
                timeout = schedule_timeout_interruptible(timeout);

The call to kthread_stop() woke up the thread, so schedule_timeout_
interruptible() returned early, but because signal_pending() returned
true, it went back into another timeout, which was never woken up.

This wait loop pattern is common to various pieces of code, and I
suspect that the subtle misuse in a kthread that caused a deadlock in
the code I looked at last week is also found elsewhere.

So this commit causes signal_pending() to return true when
kthread_stop() is called, by setting TIF_NOTIFY_SIGNAL.

The same also probably applies to the similar kthread_park()
functionality, but that can be addressed later, as its semantics are
slightly different.

Cc: Eric W. Biederman <ebiederm@xmission.com>
Signed-off-by: Jason A. Donenfeld <Jason@zx2c4.com>
V1: https://lkml.kernel.org/r/20220627120020.608117-1-Jason@zx2c4.com
V2: https://lkml.kernel.org/r/20220627145716.641185-1-Jason@zx2c4.com
V3: https://lkml.kernel.org/r/20220628161441.892925-1-Jason@zx2c4.com
V4: https://lkml.kernel.org/r/20220711202136.64458-1-Jason@zx2c4.com
V5: https://lkml.kernel.org/r/20220711232123.136330-1-Jason@zx2c4.com
Signed-off-by: Eric W. Biederman <ebiederm@xmission.com>
Acked-by: Petr Mladek <pmladek@suse.com>

---
 kernel/kthread.c |    1 +
 1 file changed, 1 insertion(+)

--- a/kernel/kthread.c
+++ b/kernel/kthread.c
@@ -644,6 +644,7 @@ int kthread_stop(struct task_struct *k)
 	kthread = to_kthread(k);
 	set_bit(KTHREAD_SHOULD_STOP, &kthread->flags);
 	kthread_unpark(k);
+	set_tsk_thread_flag(k, TIF_NOTIFY_SIGNAL);
 	wake_up_process(k);
 	wait_for_completion(&kthread->exited);
 	ret = k->exit_code;