[PATCH] kthread: Annotate lockless to_kthread() flags access

Kunwu Chan posted 1 patch 4 days, 12 hours ago
kernel/kthread.c | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
[PATCH] kthread: Annotate lockless to_kthread() flags access
Posted by Kunwu Chan 4 days, 12 hours ago
do_exit() calls synchronize_group_exit(), which modifies task->flags
under sighand->siglock:

	tsk->flags |= PF_POSTCOREDUMP;

The sanity check in to_kthread() reads the same flags word without
holding that lock:

	WARN_ON(!(k->flags & PF_KTHREAD));

PF_KTHREAD is set once when the task becomes a kthread and is never
cleared for the lifetime of the task.  Since PF_KTHREAD is immutable,
the check does not depend on synchronization with updates to other
bits in task->flags.

Use READ_ONCE() to annotate the intentional lockless access.

Signed-off-by: Kunwu Chan <kunwu.chan@gmail.com>
---
 kernel/kthread.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/kernel/kthread.c b/kernel/kthread.c
index a3f95c90456b..cc8cb5d3eab7 100644
--- a/kernel/kthread.c
+++ b/kernel/kthread.c
@@ -81,7 +81,7 @@ enum KTHREAD_BITS {
 
 static inline struct kthread *to_kthread(struct task_struct *k)
 {
-	WARN_ON(!(k->flags & PF_KTHREAD));
+	WARN_ON(!(READ_ONCE(k->flags) & PF_KTHREAD));
 	return k->worker_private;
 }
 
-- 
2.43.0
Re: [PATCH] kthread: Annotate lockless to_kthread() flags access
Posted by Bradley Morgan 4 days, 6 hours ago
On 20 September 2026 08:07:50 BST, Kunwu Chan <kunwu.chan@gmail.com> wrote:
>do_exit() calls synchronize_group_exit(), which modifies task->flags
>under sighand->siglock:
>
>	tsk->flags |= PF_POSTCOREDUMP;
>
>The sanity check in to_kthread() reads the same flags word without
>holding that lock:
>
>	WARN_ON(!(k->flags & PF_KTHREAD));
>
>PF_KTHREAD is set once when the task becomes a kthread and is never
>cleared for the lifetime of the task.  Since PF_KTHREAD is immutable,
>the check does not depend on synchronization with updates to other
>bits in task->flags.
>
>Use READ_ONCE() to annotate the intentional lockless access.
>
>Signed-off-by: Kunwu Chan <kunwu.chan@gmail.com>
>---
> kernel/kthread.c | 2 +-
> 1 file changed, 1 insertion(+), 1 deletion(-)
>
>diff --git a/kernel/kthread.c b/kernel/kthread.c
>index a3f95c90456b..cc8cb5d3eab7 100644
>--- a/kernel/kthread.c
>+++ b/kernel/kthread.c
>@@ -81,7 +81,7 @@ enum KTHREAD_BITS {
> 
> static inline struct kthread *to_kthread(struct task_struct *k)
> {
>-	WARN_ON(!(k->flags & PF_KTHREAD));
>+	WARN_ON(!(READ_ONCE(k->flags) & PF_KTHREAD));


Nice! Thanks for the fix!

Reviewed-by: Bradley Morgan <brads@mainlining.org>

> 	return k->worker_private;
> }
> 
>


--- Thanks!
"I'm not a very positive person" - Linus torvalds