[PATCH] kthread: kthread_should_stop() checks if we're a kthread

From: Kent Overstreet
Date: Mon Nov 20 2023 - 17:17:42 EST


bcachefs has a fair amount of code that may or may not be running from a
kthread (it may instead be called by a userspace ioctl); having
kthread_should_stop() check if we're a kthread enables a fair bit of
cleanup and makes it safer to use.

Cc: Nicholas Piggin <npiggin@xxxxxxxxx>
Cc: Mike Christie <michael.christie@xxxxxxxxxx>
Cc: Zqiang <qiang1.zhang@xxxxxxxxx>
Cc: Petr Mladek <pmladek@xxxxxxxx>
Signed-off-by: Kent Overstreet <kent.overstreet@xxxxxxxxx>
---
kernel/kthread.c | 3 ++-
1 file changed, 2 insertions(+), 1 deletion(-)

diff --git a/kernel/kthread.c b/kernel/kthread.c
index 1eea53050bab..fe6090ddf414 100644
--- a/kernel/kthread.c
+++ b/kernel/kthread.c
@@ -155,7 +155,8 @@ void free_kthread_struct(struct task_struct *k)
*/
bool kthread_should_stop(void)
{
- return test_bit(KTHREAD_SHOULD_STOP, &to_kthread(current)->flags);
+ return (current->flags & PF_KTHREAD) &&
+ test_bit(KTHREAD_SHOULD_STOP, &to_kthread(current)->flags);
}
EXPORT_SYMBOL(kthread_should_stop);

--
2.42.0