Add is_user_thread() and is_kernel_thread() helper functions
Subsystems (40)
Steven Rostedt
maintainercover Add is_user_thread() and is_kernel_thread() helper functions
While working on the deferred stacktrace code, Peter Zijlstra told me to use task->flags & PF_KTHREAD instead of checking task->mm for NULL. This seemed reasonable, but while working on it, as there were several places that check if the task is a kernel thread and other places that check if the task is a user space thread I found it a bit confusing when looking at both:
if (task->flags & PF_KTHREAD) and if (!(task->flags & PF_KTHREAD))
Where I mixed them up sometimes, and checked for a user space thread when I really wanted to check for a kernel thread. I found these mistakes before sending out my patches, but going back and reviewing the code, I always had to stop and spend a few unnecessary seconds making sure the check was testing that flag correctly.
To make this a bit more obvious, I introduced two helper functions:
is_user_thread(task)
is_kernel_thread(task)
which simply test the flag for you. Thus, seeing:
if (is_user_thread(task))
or
if (is_kernel_thread(task))
it was very obvious to which test you wanted to make.
I then created a coccinelle script to change all the checks throughout the kernel to use one of these macros.
$ cat kthread.cocci
@@
identifier task;
@@
- !(task->flags & PF_KTHREAD)
+ is_user_thread(task)
@@
identifier task;
@@
- (task->flags & PF_KTHREAD) == 0
+ is_user_thread(task)
@@
identifier task;
@@
- (task->flags & PF_KTHREAD) != 0
+ is_kernel_thread(task)
@@
identifier task;
@@
- task->flags & PF_KTHREAD
+ is_kernel_thread(task) $ spatch --dir --include-headers kthread.cocci . > /tmp/t.patch
$ patch -p1 < /tmp/t.patchMake sure to undo the conversion of the helper functions themselves!
$ git show include/linux/sched.h | patch -p1 -R
It did modify the tools/sched_ext code, and I'm not sure if that's OK or not. Does it still use the sched.h header? If so, it should be fine. But if it is an issue, I can undo the changes to tools as well.
Steven Rostedt (2):
kthread: Add is_user_thread() and is_kernel_thread() helper functions
treewide: Have the task->flags & PF_KTHREAD check use the helper functions
----
arch/arm/mm/init.c | 2 +- arch/arm64/include/asm/uaccess.h | 2 +- arch/arm64/kernel/process.c | 2 +- arch/arm64/kernel/proton-pack.c | 2 +- arch/mips/kernel/process.c | 2 +- arch/powerpc/kernel/process.c | 2 +- arch/powerpc/kernel/stacktrace.c | 2 +- arch/x86/kernel/fpu/core.c | 2 +- arch/x86/kernel/process.c | 2 +- block/blk-cgroup.c | 2 +- drivers/gpu/drm/amd/amdgpu/amdgpu_amdkfd.h | 2 +- drivers/md/dm-vdo/logger.c | 2 +- drivers/tty/sysrq.c | 2 +- fs/bcachefs/clock.c | 2 +- fs/bcachefs/journal_reclaim.c | 2 +- fs/bcachefs/move.c | 6 +++--- fs/exec.c | 2 +- fs/file_table.c | 2 +- fs/namespace.c | 2 +- fs/proc/array.c | 4 ++-- fs/proc/base.c | 6 +++--- include/linux/sched.h | 10 ++++++++++ io_uring/io_uring.c | 2 +- kernel/cgroup/cgroup.c | 6 +++--- kernel/cgroup/freezer.c | 4 ++-- kernel/events/core.c | 2 +- kernel/exit.c | 2 +- kernel/fork.c | 6 +++--- kernel/freezer.c | 4 ++-- kernel/futex/pi.c | 2 +- kernel/kthread.c | 12 ++++++------ kernel/livepatch/transition.c | 2 +- kernel/power/process.c | 2 +- kernel/sched/core.c | 6 +++--- kernel/sched/idle.c | 2 +- kernel/sched/sched.h | 4 ++-- kernel/signal.c | 4 ++-- kernel/stacktrace.c | 2 +- lib/is_single_threaded.c | 2 +- mm/memcontrol.c | 2 +- mm/oom_kill.c | 4 ++-- mm/page_alloc.c | 2 +- mm/vmscan.c | 2 +- security/keys/request_key.c | 2 +- security/smack/smack_access.c | 2 +- security/smack/smack_lsm.c | 4 ++-- security/tomoyo/network.c | 2 +- security/yama/yama_lsm.c | 2 +- tools/sched_ext/scx_central.bpf.c | 2 +- tools/sched_ext/scx_flatcg.bpf.c | 2 +- tools/sched_ext/scx_qmap.bpf.c | 2 +- 51 files changed, 82 insertions(+), 72 deletions(-)
Steven Rostedt
maintainerRFC PATCH 1/2 kthread: Add is_user_thread() and is_kernel_thread() helper functions
From: Steven Rostedt <[email protected]>
In order to know if a task is a user thread or a kernel thread it is recommended to test the task flags for PF_KTHREAD. The old way was to check if the task mm pointer is NULL.
It is an easy mistake to not test the flag correctly, as:
if (!(task->flag & PF_KTHREAD))
Is not immediately obvious that it's testing for a user thread.
Add helper functions:
is_user_thread()
is_kernel_thread()
that can make seeing what is being tested for much more obvious:
if (is_user_thread(task))
--- include/linux/sched.h | 10 ++++++++++ 1 file changed, 10 insertions(+)
include/linux/sched.h +10 -0
@@ -1785,6 +1785,16 @@ static __always_inline bool is_percpu_thread(void)#endif } +static __always_inline bool is_user_thread(struct task_struct *task) +{ +return !(task->flags &PF_KTHREAD ); +} + +static __always_inline bool is_kernel_thread(struct task_struct *task) +{ +return task->flags &PF_KTHREAD ; +} +/* Per-process atomic flags. */ #define PFA_NO_NEW_PRIVS 0/* May not gain new privileges. */ #define PFA_SPREAD_PAGE 1/* Spread page cache over cpuset */
Signature · 1 line
2.47.2
Re: [RFC][PATCH 1/2] kthread: Add is_user_thread() and is_kernel_thread() helper functions
Quoted 34 lines · Steven Rostedt
From: Steven Rostedt <[email protected]>
In order to know if a task is a user thread or a kernel thread it is recommended to test the task flags for
PF_KTHREAD. The old way was to check if the task mm pointer is NULL.It is an easy mistake to not test the flag correctly, as:
if (!(task->flag & PF_KTHREAD))Is not immediately obvious that it's testing for a user thread.
Add helper functions:
is_user_thread()
is_kernel_thread()that can make seeing what is being tested for much more obvious:
if (
is_user_thread(task))Signed-off-by Steven Rostedt (Google) <[email protected]>--- include/linux/sched.h | 10 ++++++++++ 1 file changed, 10 insertions(+)include/linux/sched.h +0
-0@@ -1785,6 +1785,16 @@ static __always_inline bool is_percpu_thread(void)#endif
include/linux/sched.h static __always_inline bool is_percpu_thread(void) · line 1795
Quoted 10 lines
include/linux/sched.h +8
-0} +static __always_inline bool is_user_thread(struct task_struct *task) +{ +return !(task->flags &PF_KTHREAD ); +} + +static __always_inline bool is_kernel_thread(struct task_struct *task) +{ +return task->flags &PF_KTHREAD ;
nit: maybe do explicit type conversion:
return !!(task->flags & PF_KTHREAD);
but that's just a style issue, really.
Thank you for not using current->mm -- KUnit, live patching, etc, all use current->mm but are kthreads. :)
Signature · 1 line
Kees Cook
Steven Rostedt
maintainerRe: [RFC][PATCH 1/2] kthread: Add is_user_thread() and is_kernel_thread() helper functions
Quoted 9 lines · On Fri, 25 Apr 2025 16:03:16 -0700 Kees Cook <[email protected]> wrote:
include/linux/sched.h static __always_inline bool is_percpu_thread(void) · line 1795
Quoted 3 lines
include/linux/sched.h +3
-0+static __always_inline bool is_kernel_thread(struct task_struct *task) +{ +return task->flags &PF_KTHREAD ;nit: maybe do explicit type conversion:
return !!(task->flags & PF_KTHREAD);but that's just a style issue, really.
I may use Boris's suggestion (which I thought of doing originally too) and have this return:
return !is_user_thread(task);
Quoted 2 lines
Reviewed-by Kees Cook <[email protected]>
Thanks.
Quoted 3 lines
Thank you for not using
current->mm-- KUnit, live patching, etc, all usecurrent->mmbut are kthreads. :)
Yeah, Peter was stressing this.
-- Steve
Borislav Petkov
maintainerRe: [RFC][PATCH 1/2] kthread: Add is_user_thread() and is_kernel_thread() helper functions
In reply to Steven RostedtQuoted 34 lines · Steven Rostedt
From: Steven Rostedt <[email protected]>
In order to know if a task is a user thread or a kernel thread it is recommended to test the task flags for
PF_KTHREAD. The old way was to check if the task mm pointer is NULL.It is an easy mistake to not test the flag correctly, as:
if (!(task->flag & PF_KTHREAD))Is not immediately obvious that it's testing for a user thread.
Add helper functions:
is_user_thread()
is_kernel_thread()that can make seeing what is being tested for much more obvious:
if (
is_user_thread(task))Signed-off-by Steven Rostedt (Google) <[email protected]>---
include/linux/sched.h| 10 ++++++++++1 file changed, 10 insertions(+)include/linux/sched.h +0
-0@@ -1785,6 +1785,16 @@ static __always_inline bool is_percpu_thread(void)#endif
include/linux/sched.h static __always_inline bool is_percpu_thread(void) · line 1795
Quoted 10 lines
include/linux/sched.h +8
-0} +static __always_inline bool is_user_thread(struct task_struct *task) +{ +return !(task->flags &PF_KTHREAD ); +} + +static __always_inline bool is_kernel_thread(struct task_struct *task) +{ +return task->flags &PF_KTHREAD ;
return !is_user_thread(task);
or the other way around.
🙂
Signature · 1 line
Sent from a small device: formatting sucks and brevity is inevitable.
Steven Rostedt
maintainerRe: [RFC][PATCH 1/2] kthread: Add is_user_thread() and is_kernel_thread() helper functions
Quoted 7 lines · On Sat, 26 Apr 2025 14:08:46 +0300 Borislav Petkov <[email protected]> wrote:
include/linux/sched.h static __always_inline bool is_percpu_thread(void) · line 1795
Quoted 3 lines
include/linux/sched.h +3
-0+static __always_inline bool is_kernel_thread(struct task_struct *task) +{ +return task->flags &PF_KTHREAD ;return !is_user_thread(task);
or the other way around.
Yeah, I thought about doing that but decided against it.
As Kees mentioned to use !!, I think using the !is_user_thread() is a better approach.
-- Steve
Steven Rostedt
maintainerRFC PATCH 2/2 treewide: Have the task->flags & PF_KTHREAD check use the helper functions
In reply to Steven RostedtFrom: Steven Rostedt <[email protected]>
Getting the check if a task is a kernel thread or a user thread can be error prone as it's not easy to see the difference.
if (!(task->flags & PF_KTHREAD))
Is not immediately obvious that it's checking for a user thread.
if (is_user_thread(task))
Is much easier to review, as it is obvious that it is checking if the task is a user thread.
Using a coccinelle script, convert these checks over to using either is_user_thread() or is_kernel_thread().
$ cat kthread.cocci @@ identifier task; @@ - !(task->flags & PF_KTHREAD) + is_user_thread(task) @@ identifier task; @@ - (task->flags & PF_KTHREAD) == 0 + is_user_thread(task) @@ identifier task; @@ - (task->flags & PF_KTHREAD) != 0 + is_kernel_thread(task) @@ identifier task; @@ - task->flags & PF_KTHREAD + is_kernel_thread(task)
$ spatch --dir --include-headers kthread.cocci . > /tmp/t.patch $ patch -p1 < /tmp/t.patch
Make sure to undo the conversion of the helper functions themselves!
$ git show include/linux/sched.h | patch -p1 -R
--- arch/arm/mm/init.c | 2 +- arch/arm64/include/asm/uaccess.h | 2 +- arch/arm64/kernel/process.c | 2 +- arch/arm64/kernel/proton-pack.c | 2 +- arch/mips/kernel/process.c | 2 +- arch/powerpc/kernel/process.c | 2 +- arch/powerpc/kernel/stacktrace.c | 2 +- arch/x86/kernel/fpu/core.c | 2 +- arch/x86/kernel/process.c | 2 +- block/blk-cgroup.c | 2 +- drivers/gpu/drm/amd/amdgpu/amdgpu_amdkfd.h | 2 +- drivers/md/dm-vdo/logger.c | 2 +- drivers/tty/sysrq.c | 2 +- fs/bcachefs/clock.c | 2 +- fs/bcachefs/journal_reclaim.c | 2 +- fs/bcachefs/move.c | 6 +++--- fs/exec.c | 2 +- fs/file_table.c | 2 +- fs/namespace.c | 2 +- fs/proc/array.c | 4 ++-- fs/proc/base.c | 6 +++--- io_uring/io_uring.c | 2 +- kernel/cgroup/cgroup.c | 6 +++--- kernel/cgroup/freezer.c | 4 ++-- kernel/events/core.c | 2 +- kernel/exit.c | 2 +- kernel/fork.c | 6 +++--- kernel/freezer.c | 4 ++-- kernel/futex/pi.c | 2 +- kernel/kthread.c | 12 ++++++------ kernel/livepatch/transition.c | 2 +- kernel/power/process.c | 2 +- kernel/sched/core.c | 6 +++--- kernel/sched/idle.c | 2 +- kernel/sched/sched.h | 4 ++-- kernel/signal.c | 4 ++-- kernel/stacktrace.c | 2 +- lib/is_single_threaded.c | 2 +- mm/memcontrol.c | 2 +- mm/oom_kill.c | 4 ++-- mm/page_alloc.c | 2 +- mm/vmscan.c | 2 +- security/keys/request_key.c | 2 +- security/smack/smack_access.c | 2 +- security/smack/smack_lsm.c | 4 ++-- security/tomoyo/network.c | 2 +- security/yama/yama_lsm.c | 2 +- tools/sched_ext/scx_central.bpf.c | 2 +- tools/sched_ext/scx_flatcg.bpf.c | 2 +- tools/sched_ext/scx_qmap.bpf.c | 2 +- 50 files changed, 72 insertions(+), 72 deletions(-)
arch/arm/mm/init.c +1 -1
@@ -390,7 +390,7 @@ static void update_sections_early(struct section_perm perms[], int n)struct task_struct *t, *s;for_each_process (t) { -if (t->flags &PF_KTHREAD ) +if (is_kernel_thread (t))continue ;for_each_thread (t, s)if (s->mm)
arch/arm64/include/asm/uaccess.h +1 -1
@@ -43,7 +43,7 @@ static inline int access_ok(const void __user *addr, unsigned long size)* the user address before checking. */ if (IS_ENABLED (CONFIG_ARM64_TAGGED_ADDR_ABI ) && - (current->flags &PF_KTHREAD ||test_thread_flag (TIF_TAGGED_ADDR ))) + (is_kernel_thread (current) ||test_thread_flag (TIF_TAGGED_ADDR ))) addr =untagged_addr (addr);return likely (__access_ok (addr, size));
arch/arm64/kernel/process.c +1 -1
@@ -514,7 +514,7 @@ static void ssbs_thread_switch(struct task_struct *next)* Nothing to do for kernel threads, but 'regs' may be junk * (e.g. idle task) so check the flags and bail early. */ -if (unlikely (next->flags &PF_KTHREAD )) +if (unlikely (is_kernel_thread (next)))return ;/*
arch/arm64/kernel/proton-pack.c +1 -1
@@ -666,7 +666,7 @@ static void __update_pstate_ssbs(struct pt_regs *regs, bool state)void spectre_v4_enable_task_mitigation (struct task_struct *tsk) {struct pt_regs *regs =task_pt_regs (tsk); -bool ssbs = false, kthread = tsk->flags &PF_KTHREAD ; +bool ssbs = false, kthread =is_kernel_thread (tsk);if (spectre_v4_mitigations_off ()) ssbs = true;
arch/mips/kernel/process.c +1 -1
@@ -74,7 +74,7 @@ void exit_thread(struct task_struct *tsk)* User threads may have allocated a delay slot emulation frame. * If so, clean up that allocation. */ -if (!(current->flags &PF_KTHREAD )) +if (is_user_thread (current))dsemul_thread_cleanup (tsk); }
arch/powerpc/kernel/process.c +1 -1
@@ -1770,7 +1770,7 @@ int copy_thread(struct task_struct *p, const struct kernel_clone_args *args)klp_init_thread_info (p); -if (unlikely (p->flags &PF_KTHREAD )) { +if (unlikely (is_kernel_thread (p))) {/* kernel thread */ /* Create initial minimum stack frame. */
arch/powerpc/kernel/stacktrace.c +1 -1
@@ -76,7 +76,7 @@ int __no_sanitize_address arch_stack_walk_reliable(stack_trace_consume_fn consum stack_end = stack_page +THREAD_SIZE ;// See copy_thread() for details. -if (task->flags &PF_KTHREAD ) +if (is_kernel_thread (task)) stack_end -=STACK_FRAME_MIN_SIZE ;else stack_end -=STACK_USER_INT_FRAME_SIZE ;
arch/x86/kernel/fpu/core.c +1 -1
@@ -805,7 +805,7 @@ void fpregs_lock_and_load(void)* Warn about it. */ WARN_ON_ONCE (!irq_fpu_usable ()); -WARN_ON_ONCE (current->flags &PF_KTHREAD ); +WARN_ON_ONCE (is_kernel_thread (current));fpregs_lock ();
arch/x86/kernel/process.c +1 -1
@@ -220,7 +220,7 @@ int copy_thread(struct task_struct *p, const struct kernel_clone_args *args)fpu_clone (p, clone_flags, args->fn, new_ssp);/* Kernel thread ? */ -if (unlikely (p->flags &PF_KTHREAD )) { +if (unlikely (is_kernel_thread (p))) { p->thread.pkru =pkru_get_init_value ();memset (childregs,0 ,sizeof (struct pt_regs ));kthread_frame_init (frame, args->fn, args->fn_arg);
block/blk-cgroup.c +1 -1
@@ -2061,7 +2061,7 @@ void blkcg_maybe_throttle_current(void)*/ void blkcg_schedule_throttle (struct gendisk *disk,bool use_memdelay) { -if (unlikely (current->flags &PF_KTHREAD )) +if (unlikely (is_kernel_thread (current)))return ;if (current->throttle_disk != disk) {
drivers/gpu/drm/amd/amdgpu/amdgpu_amdkfd.h +1 -1
@@ -279,7 +279,7 @@ bool amdgpu_amdkfd_compute_active(struct amdgpu_device *adev, uint32_t node_id);pagefault_disable (); \if ((mmptr) == current->mm) { \ valid = !get_user ((dst), (wptr)); \ - }else if (current->flags &PF_KTHREAD ) { \ + }else if (is_kernel_thread (current)) { \kthread_use_mm (mmptr); \ valid = !get_user ((dst), (wptr)); \kthread_unuse_mm (mmptr); \
drivers/md/dm-vdo/logger.c +1 -1
@@ -137,7 +137,7 @@ static void emit_log_message(int priority, const char *module, const char *prefi* If it's a kernel thread and the module name is a prefix of its name, assume it is ours * and only identify the thread. */ -if (((current->flags &PF_KTHREAD ) !=0 ) && +if ((is_kernel_thread (current)) && (strncmp (module, current->comm,strlen (module)) ==0 )) {emit_log_message_to_kernel (priority,"%s: %s%pV%pV\n" , current->comm, prefix, vaf1, vaf2);
drivers/tty/sysrq.c +1 -1
@@ -360,7 +360,7 @@ static void send_sig_all(int sig)read_lock (&tasklist_lock);for_each_process (p) { -if (p->flags &PF_KTHREAD ) +if (is_kernel_thread (p))continue ;if (is_global_init (p))continue ;
fs/bcachefs/clock.c +1 -1
@@ -93,7 +93,7 @@ void bch2_io_clock_schedule_timeout(struct io_clock *clock, u64 until)void bch2_kthread_io_clock_wait (struct io_clock *clock,u64 io_until,unsigned long cpu_timeout) { -bool kthread = (current->flags &PF_KTHREAD ) !=0 ; +bool kthread =is_kernel_thread (current);struct io_clock_wait wait = { .io_timer.expire = io_until, .io_timer.fn = io_clock_wait_fn,
fs/bcachefs/journal_reclaim.c +1 -1
@@ -665,7 +665,7 @@ static int __bch2_journal_reclaim(struct journal *j, bool direct, bool kicked) { struct bch_fs *c = container_of(j, struct bch_fs, journal);struct btree_cache *bc = &c->btree_cache; -bool kthread = (current->flags &PF_KTHREAD ) !=0 ; +bool kthread =is_kernel_thread (current);u64 seq_to_flush;size_t min_nr, min_key_cache, nr_flushed;unsigned flags;
fs/bcachefs/move.c +3 -3
@@ -487,7 +487,7 @@ int bch2_move_get_io_opts_one(struct btree_trans *trans,int bch2_move_ratelimit (struct moving_context *ctxt) {struct bch_fs *c = ctxt->trans->c; -bool is_kthread = current->flags &PF_KTHREAD ; +bool is_kthread =is_kernel_thread (current);u64 delay;if (ctxt->wait_on_copygc && c->copygc_running) {
@@ -749,7 +749,7 @@ static int __bch2_move_data_phys(struct moving_context *ctxt, {struct btree_trans *trans = ctxt->trans;struct bch_fs *c = trans->c; -bool is_kthread = current->flags &PF_KTHREAD ; +bool is_kthread =is_kernel_thread (current);struct bch_io_opts io_opts =bch2_opts_to_inode_opts (c->opts);struct btree_iter iter = {}, bp_iter = {};struct bkey_buf sk;
@@ -961,7 +961,7 @@ static int bch2_move_btree(struct bch_fs *c, move_btree_pred pred, void *arg, struct bch_move_stats *stats) { - bool kthread = (current->flags & PF_KTHREAD) != 0; + bool kthread = is_kernel_thread(current);struct bch_io_opts io_opts =bch2_opts_to_inode_opts (c->opts);struct moving_context ctxt;struct btree_trans *trans;
fs/exec.c +1 -1
@@ -1983,7 +1983,7 @@ int kernel_execve(const char *kernel_filename,int retval;/* It is non-sense for kernel threads to call execve */ -if (WARN_ON_ONCE (current->flags &PF_KTHREAD )) +if (WARN_ON_ONCE (is_kernel_thread (current)))return -EINVAL ; filename =getname_kernel (kernel_filename);
fs/file_table.c +1 -1
@@ -521,7 +521,7 @@ static void __fput_deferred(struct file *file)return ; } -if (likely (!in_interrupt () && !(task->flags &PF_KTHREAD ))) { +if (likely (!in_interrupt () &&is_user_thread (task))) {init_task_work (&file->f_task_work, ____fput);if (!task_work_add (task, &file->f_task_work,TWA_RESUME ))return ;
fs/namespace.c +1 -1
@@ -1509,7 +1509,7 @@ static void mntput_no_expire(struct mount *mnt)if (likely (!(mnt->mnt.mnt_flags &MNT_INTERNAL ))) {struct task_struct *task = current; -if (likely (!(task->flags &PF_KTHREAD ))) { +if (likely (is_user_thread (task))) {init_task_work (&mnt->mnt_rcu, __cleanup_mnt);if (!task_work_add (task, &mnt->mnt_rcu,TWA_RESUME ))return ;
fs/proc/array.c +2 -2
@@ -106,7 +106,7 @@ void proc_task_name(struct seq_file *m, struct task_struct *p, bool escape)*/ if (p->flags &PF_WQ_WORKER )wq_worker_comm (tcomm,sizeof (tcomm), p); -else if (p->flags &PF_KTHREAD ) +else if (is_kernel_thread (p))get_kthread_comm (tcomm,sizeof (tcomm), p);else get_task_comm (tcomm, p);
@@ -221,7 +221,7 @@ static inline void task_state(struct seq_file *m, struct pid_namespace *ns,#endif seq_putc (m,'\n' ); -seq_printf (m,"Kthread:\t%c\n" , p->flags &PF_KTHREAD ?'1' :'0' ); +seq_printf (m,"Kthread:\t%c\n" ,is_kernel_thread (p) ?'1' :'0' ); } void render_sigset_t(struct seq_file *m, const char *header,
fs/proc/base.c +3 -3
@@ -1179,7 +1179,7 @@ static int __set_oom_adj(struct file *file, int oom_adj, bool legacy)continue ;/* do not touch kernel threads or the global init */ -if (p->flags &PF_KTHREAD ||is_global_init (p)) +if (is_kernel_thread (p) ||is_global_init (p))continue ;task_lock (p);
@@ -1330,7 +1330,7 @@ static ssize_t proc_loginuid_write(struct file * file, const char __user * buf,int rv;/* Don't let kthreads write their own loginuid */ -if (current->flags &PF_KTHREAD ) +if (is_kernel_thread (current))return -EPERM ;rcu_read_lock ();
@@ -1876,7 +1876,7 @@ void task_dump_owner(struct task_struct *task, umode_t mode,kuid_t uid;kgid_t gid; -if (unlikely (task->flags &PF_KTHREAD )) { +if (unlikely (is_kernel_thread (task))) { *ruid =GLOBAL_ROOT_UID ; *rgid =GLOBAL_ROOT_GID ;return ;
io_uring/io_uring.c +1 -1
@@ -523,7 +523,7 @@ static void io_queue_iowq(struct io_kiocb *req)BUG_ON (!tctx); -if ((current->flags &PF_KTHREAD ) || !tctx->io_wq) { +if (is_kernel_thread (current) || !tctx->io_wq) {io_req_task_queue_fail (req, -ECANCELED );return ; }
kernel/cgroup/cgroup.c +3 -3
@@ -4033,7 +4033,7 @@ static void __cgroup_kill(struct cgroup *cgrp)css_task_iter_start (&cgrp->self,CSS_TASK_ITER_PROCS |CSS_TASK_ITER_THREADED , &it);while ((task =css_task_iter_next (&it))) {/* Ignore kernel threads here. */ -if (task->flags &PF_KTHREAD ) +if (is_kernel_thread (task))continue ;/* Skip tasks that are already dying. */
@@ -6718,7 +6718,7 @@ void cgroup_post_fork(struct task_struct *child, cset =NULL ; } -if (!(child->flags &PF_KTHREAD )) { +if (is_user_thread (child)) {if (unlikely (test_bit (CGRP_FREEZE , &cgrp_flags))) {/* * If the cgroup has to be frozen, the new task has
@@ -6800,7 +6800,7 @@ void cgroup_exit(struct task_struct *tsk)dec_dl_tasks_cs (tsk);WARN_ON_ONCE (cgroup_task_frozen (tsk)); -if (unlikely (!(tsk->flags &PF_KTHREAD ) && +if (unlikely (is_user_thread (tsk) &&test_bit (CGRP_FREEZE , &task_dfl_cgroup (tsk)->flags)))cgroup_update_frozen (task_dfl_cgroup (tsk));
kernel/cgroup/freezer.c +2 -2
@@ -196,7 +196,7 @@ static void cgroup_do_freeze(struct cgroup *cgrp, bool freeze)* Ignore kernel threads here. Freezing cgroups containing * kthreads isn't supported. */ -if (task->flags &PF_KTHREAD ) +if (is_kernel_thread (task))continue ;cgroup_freeze_task (task, freeze); }
@@ -224,7 +224,7 @@ void cgroup_freezer_migrate_task(struct task_struct *task,/* * Kernel threads are not supposed to be frozen at all. */ -if (task->flags &PF_KTHREAD ) +if (is_kernel_thread (task))return ;/*
kernel/events/core.c +1 -1
@@ -7317,7 +7317,7 @@ static void perf_sample_regs_user(struct perf_regs *regs_user,if (user_mode (regs)) { regs_user->abi =perf_reg_abi (current); regs_user->regs = regs; - }else if (!(current->flags &PF_KTHREAD )) { + }else if (is_user_thread (current)) {perf_get_regs_user (regs_user, regs); }else { regs_user->abi =PERF_SAMPLE_REGS_ABI_NONE ;
kernel/exit.c +1 -1
@@ -533,7 +533,7 @@ void mm_update_next_owner(struct mm_struct *mm)for_each_process (g) {if (atomic_read (&mm->mm_users) <=1 )break ; -if (g->flags &PF_KTHREAD ) +if (is_kernel_thread (g))continue ;if (try_to_set_owner (g, mm)) goto ret;
kernel/fork.c +3 -3
@@ -586,7 +586,7 @@ void free_task(struct task_struct *tsk)rt_mutex_debug_task_free (tsk);ftrace_graph_exit_task (tsk);arch_release_task_struct (tsk); -if (tsk->flags &PF_KTHREAD ) +if (is_kernel_thread (tsk))free_kthread_struct (tsk);bpf_task_storage_free (tsk);free_task_struct (tsk);
@@ -1545,7 +1545,7 @@ struct file *get_task_exe_file(struct task_struct *task)struct file *exe_file =NULL ;struct mm_struct *mm; -if (task->flags &PF_KTHREAD ) +if (is_kernel_thread (task))return NULL ;task_lock (task);
@@ -1570,7 +1570,7 @@ struct mm_struct *get_task_mm(struct task_struct *task) {struct mm_struct *mm; -if (task->flags &PF_KTHREAD ) +if (is_kernel_thread (task))return NULL ;task_lock (task);
kernel/freezer.c +2 -2
@@ -46,7 +46,7 @@ bool freezing_slow_path(struct task_struct *p)if (pm_nosig_freezing ||cgroup_freezing (p))return true; -if (pm_freezing && !(p->flags &PF_KTHREAD )) +if (pm_freezing &&is_user_thread (p))return true;return false;
@@ -170,7 +170,7 @@ bool freeze_task(struct task_struct *p)return false; } -if (!(p->flags &PF_KTHREAD )) +if (is_user_thread (p))fake_signal_wake_up (p);else wake_up_state (p,TASK_NORMAL );
kernel/futex/pi.c +1 -1
@@ -428,7 +428,7 @@ static int attach_to_pi_owner(u32 __user *uaddr, u32 uval, union futex_key *key,if (!p)return handle_exit_race (uaddr, uval,NULL ); -if (unlikely (p->flags &PF_KTHREAD )) { +if (unlikely (is_kernel_thread (p))) {put_task_struct (p);return -EPERM ; }
kernel/kthread.c +6 -6
@@ -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 (is_user_thread (k));return k->worker_private; }
@@ -99,7 +99,7 @@ static inline struct kthread *to_kthread(struct task_struct *k)static inline struct kthread *__to_kthread (struct task_struct *p) {void *kthread = p->worker_private; -if (kthread && !(p->flags &PF_KTHREAD )) +if (kthread &&is_user_thread (p)) kthread =NULL ;return kthread; }
@@ -1601,7 +1601,7 @@ void kthread_use_mm(struct mm_struct *mm)struct mm_struct *active_mm;struct task_struct *tsk = current; -WARN_ON_ONCE (!(tsk->flags &PF_KTHREAD )); +WARN_ON_ONCE (is_user_thread (tsk));WARN_ON_ONCE (tsk->mm);/*
@@ -1646,7 +1646,7 @@ void kthread_unuse_mm(struct mm_struct *mm) {struct task_struct *tsk = current; -WARN_ON_ONCE (!(tsk->flags &PF_KTHREAD )); +WARN_ON_ONCE (is_user_thread (tsk));WARN_ON_ONCE (!tsk->mm);task_lock (tsk);
@@ -1686,7 +1686,7 @@ void kthread_associate_blkcg(struct cgroup_subsys_state *css) {struct kthread *kthread; -if (!(current->flags &PF_KTHREAD )) +if (is_user_thread (current))return ; kthread =to_kthread (current);if (!kthread)
@@ -1712,7 +1712,7 @@ struct cgroup_subsys_state *kthread_blkcg(void) {struct kthread *kthread; -if (current->flags &PF_KTHREAD ) { +if (is_kernel_thread (current)) { kthread =to_kthread (current);if (kthread)return kthread->blkcg_css;
kernel/livepatch/transition.c +1 -1
@@ -423,7 +423,7 @@ static void klp_send_signals(void)* Meanwhile the task could migrate itself and the action * would be meaningless. It is not serious though. */ -if (task->flags &PF_KTHREAD ) { +if (is_kernel_thread (task)) {/* * Wake up a kthread which sleeps interruptedly and * still has not been migrated.
kernel/power/process.c +1 -1
@@ -223,7 +223,7 @@ void thaw_kernel_threads(void)read_lock (&tasklist_lock);for_each_process_thread (g, p) { -if (p->flags &PF_KTHREAD ) +if (is_kernel_thread (p))__thaw_task (p); }read_unlock (&tasklist_lock);
kernel/sched/core.c +3 -3
@@ -2448,7 +2448,7 @@ static inline bool is_cpu_allowed(struct task_struct *p, int cpu)return cpu_online (cpu);/* Non kernel threads are not allowed during either online or offline. */ -if (!(p->flags &PF_KTHREAD )) +if (is_user_thread (p))return cpu_active (cpu);/* KTHREAD_IS_PER_CPU is always allowed. */
@@ -3074,7 +3074,7 @@ static int __set_cpus_allowed_ptr_locked(struct task_struct *p, {const struct cpumask *cpu_allowed_mask =task_cpu_possible_mask (p);const struct cpumask *cpu_valid_mask = cpu_active_mask; -bool kthread = p->flags &PF_KTHREAD ; +bool kthread =is_kernel_thread (p);unsigned int dest_cpu;int ret =0 ;
@@ -8895,7 +8895,7 @@ void normalize_rt_tasks(void)/* * Only normalize user tasks: */ -if (p->flags &PF_KTHREAD ) +if (is_kernel_thread (p))continue ; p->se.exec_start =0 ;
kernel/sched/idle.c +1 -1
@@ -387,7 +387,7 @@ void play_idle_precise(u64 duration_ns, u64 latency_ns)*/ WARN_ON_ONCE (current->policy !=SCHED_FIFO );WARN_ON_ONCE (current->nr_cpus_allowed !=1 ); -WARN_ON_ONCE (!(current->flags &PF_KTHREAD )); +WARN_ON_ONCE (is_user_thread (current));WARN_ON_ONCE (!(current->flags &PF_NO_SETAFFINITY ));WARN_ON_ONCE (!duration_ns);WARN_ON_ONCE (current->mm);
kernel/sched/sched.h +2 -2
@@ -2571,7 +2571,7 @@ static inline bool task_allowed_on_cpu(struct task_struct *p, int cpu)return false;/* Can @cpu run a user thread? */ -if (!(p->flags &PF_KTHREAD ) && !task_cpu_possible (cpu, p)) +if (is_user_thread (p) && !task_cpu_possible (cpu, p))return false;return true;
@@ -3556,7 +3556,7 @@ static inline void membarrier_switch_mm(struct rq *rq,#ifdef CONFIG_SMP static inline bool is_per_cpu_kthread (struct task_struct *p) { -if (!(p->flags &PF_KTHREAD )) +if (is_user_thread (p))return false;if (p->nr_cpus_allowed !=1 )
kernel/signal.c +2 -2
@@ -96,7 +96,7 @@ static bool sig_task_ignored(struct task_struct *t, int sig, bool force)return true;/* Only allow kernel generated signals to this kthread */ -if (unlikely ((t->flags &PF_KTHREAD ) && +if (unlikely (is_kernel_thread (t) && (handler ==SIG_KTHREAD_KERNEL ) && !force))return true;
@@ -1067,7 +1067,7 @@ static int __send_signal_locked(int sig, struct kernel_siginfo *info,/* * Skip useless siginfo allocation for SIGKILL and kernel threads. */ -if ((sig ==SIGKILL ) || (t->flags &PF_KTHREAD )) +if ((sig ==SIGKILL ) ||is_kernel_thread (t)) goto out_set;/*
kernel/stacktrace.c +1 -1
@@ -229,7 +229,7 @@ unsigned int stack_trace_save_user(unsigned long *store, unsigned int size) };/* Trace user stack if not a kernel thread */ -if (current->flags &PF_KTHREAD ) +if (is_kernel_thread (current))return 0 ;arch_stack_walk_user (consume_entry, &c,task_pt_regs (current));
lib/is_single_threaded.c +1 -1
@@ -28,7 +28,7 @@ bool current_is_single_threaded(void) ret = false;rcu_read_lock ();for_each_process (p) { -if (unlikely (p->flags &PF_KTHREAD )) +if (unlikely (is_kernel_thread (p)))continue ;if (unlikely (p == task->group_leader))continue ;
mm/memcontrol.c +1 -1
@@ -2555,7 +2555,7 @@ static struct obj_cgroup *current_objcg_update(void) }/* If new objcg is NULL, no reason for the second atomic update. */ -if (!current->mm || (current->flags &PF_KTHREAD )) +if (!current->mm ||is_kernel_thread (current))return NULL ;/*
mm/oom_kill.c +2 -2
@@ -164,7 +164,7 @@ static bool oom_unkillable_task(struct task_struct *p) {if (is_global_init (p))return true; -if (p->flags &PF_KTHREAD ) +if (is_kernel_thread (p))return true;return false; }
@@ -987,7 +987,7 @@ static void __oom_kill_process(struct task_struct *victim, const char *message)* No kthread_use_mm() user needs to read from the userspace so * we are ok to reap it. */ -if (unlikely (p->flags &PF_KTHREAD )) +if (unlikely (is_kernel_thread (p)))continue ;do_send_sig_info (SIGKILL ,SEND_SIG_PRIV , p,PIDTYPE_TGID ); }
mm/page_alloc.c +1 -1
@@ -590,7 +590,7 @@ static inline struct capture_control *task_capc(struct zone *zone)struct capture_control *capc = current->capture_control;return unlikely (capc) && - !(current->flags &PF_KTHREAD ) && +is_user_thread (current) && !capc->page && capc->cc->zone == zone ? capc :NULL ; }
mm/vmscan.c +1 -1
@@ -6478,7 +6478,7 @@ static bool throttle_direct_reclaim(gfp_t gfp_mask, struct zonelist *zonelist,* committing a transaction where throttling it could forcing other * processes to block on log_wait_commit(). */ -if (current->flags &PF_KTHREAD ) +if (is_kernel_thread (current)) goto out;/*
security/keys/request_key.c +1 -1
@@ -39,7 +39,7 @@ static void cache_requested_key(struct key *key)struct task_struct *t = current;/* Do not cache key if it is a kernel thread */ -if (!(t->flags &PF_KTHREAD )) { +if (is_user_thread (t)) {key_put (t->cached_requested_key); t->cached_requested_key =key_get (key);set_tsk_thread_flag (t,TIF_NOTIFY_RESUME );
security/smack/smack_access.c +1 -1
@@ -697,7 +697,7 @@ bool smack_privileged(int cap)/* * All kernel tasks are privileged */ -if (unlikely (current->flags &PF_KTHREAD )) +if (unlikely (is_kernel_thread (current)))return true;return smack_privileged_cred (cap,current_cred ());
security/smack/smack_lsm.c +2 -2
@@ -2408,7 +2408,7 @@ static int smack_sk_alloc_security(struct sock *sk, int family, gfp_t gfp_flags)/* * Sockets created by kernel threads receive web label. */ -if (unlikely (current->flags &PF_KTHREAD )) { +if (unlikely (is_kernel_thread (current))) { ssp->smk_in = &smack_known_web; ssp->smk_out = &smack_known_web; }else {
@@ -2950,7 +2950,7 @@ static int smack_socket_post_create(struct socket *sock, int family,/* * Sockets created by kernel threads receive web label. */ -if (unlikely (current->flags &PF_KTHREAD )) { +if (unlikely (is_kernel_thread (current))) { ssp =smack_sock (sock->sk); ssp->smk_in = &smack_known_web; ssp->smk_out = &smack_known_web;
security/tomoyo/network.c +1 -1
@@ -613,7 +613,7 @@ static int tomoyo_check_unix_address(struct sockaddr *addr,static bool tomoyo_kernel_service (void ) {/* Nothing to do if I am a kernel service. */ -return current->flags &PF_KTHREAD ; +return is_kernel_thread (current); }/**
security/yama/yama_lsm.c +1 -1
@@ -79,7 +79,7 @@ static void report_access(const char *access, struct task_struct *target,assert_spin_locked (&target->alloc_lock);/* for target->comm */ -if (current->flags &PF_KTHREAD ) { +if (is_kernel_thread (current)) {/* I don't think kthreads call task_work_run() before exiting. * Imagine angry ranting about procfs here. */
tools/sched_ext/scx_central.bpf.c +1 -1
@@ -111,7 +111,7 @@ void BPF_STRUCT_OPS(central_enqueue, struct task_struct *p, u64 enq_flags)* behind other threads which is necessary for forward progress * guarantee as we depend on the BPF timer which may run from ksoftirqd. */ -if ((p->flags &PF_KTHREAD ) && p->nr_cpus_allowed ==1 ) { +if (is_kernel_thread (p) && p->nr_cpus_allowed ==1 ) {__sync_fetch_and_add (&nr_locals,1 );scx_bpf_dsq_insert (p,SCX_DSQ_LOCAL ,SCX_SLICE_INF , enq_flags |SCX_ENQ_PREEMPT );
tools/sched_ext/scx_flatcg.bpf.c +1 -1
@@ -370,7 +370,7 @@ void BPF_STRUCT_OPS(fcg_enqueue, struct task_struct *p, u64 enq_flags)* implement per-cgroup fallback dq's instead so that we have * more control over when tasks with custom cpumask get issued. */ -if (p->nr_cpus_allowed ==1 && (p->flags &PF_KTHREAD )) { +if (p->nr_cpus_allowed ==1 &&is_kernel_thread (p)) {stat_inc (FCG_STAT_LOCAL );scx_bpf_dsq_insert (p,SCX_DSQ_LOCAL ,SCX_SLICE_DFL , enq_flags);
tools/sched_ext/scx_qmap.bpf.c +1 -1
@@ -200,7 +200,7 @@ void BPF_STRUCT_OPS(qmap_enqueue, struct task_struct *p, u64 enq_flags)void *ring;s32 cpu; -if (p->flags &PF_KTHREAD ) { +if (is_kernel_thread (p)) {if (stall_kernel_nth && !(++kernel_cnt % stall_kernel_nth))return ; }else {
Signature · 1 line
2.47.2
Re: [RFC][PATCH 2/2] treewide: Have the task->flags & PF_KTHREAD check use the helper functions
Quoted 39 lines · Steven Rostedt
From: Steven Rostedt <[email protected]>
Getting the check if a task is a kernel thread or a user thread can be error prone as it's not easy to see the difference.
if (!(task->flags & PF_KTHREAD))Is not immediately obvious that it's checking for a user thread.
if (
is_user_thread(task))Is much easier to review, as it is obvious that it is checking if the task is a user thread.
Using a coccinelle script, convert these checks over to using either
is_user_thread()oris_kernel_thread().$ cat kthread.cocci @@ identifier task; @@ - !(task->flags & PF_KTHREAD) + is_user_thread(task) @@ identifier task; @@ - (task->flags & PF_KTHREAD) == 0 + is_user_thread(task) @@ identifier task; @@ - (task->flags & PF_KTHREAD) != 0 + is_kernel_thread(task) @@ identifier task; @@ - task->flags & PF_KTHREAD + is_kernel_thread(task)
Quoted 6 lines
$ spatch --dir --include-headers kthread.cocci . > /tmp/t.patch $ patch -p1 < /tmp/t.patchMake sure to undo the conversion of the helper functions themselves!
$ git show include/linux/sched.h | patch -p1 -R
FYI, the "file in" test can be helpful. I use it to exclude tools and samples regularly, and *I think* it would work for excluding individual files too:
@name_of_rule depends !(file in "tools") && !(file in "samples")@
I've been collecting random notes like this here:
https://github.com/kees/kernel-tools/tree/trunk/coccinelle
Quoted 3 lines
tools/sched_ext/scx_central.bpf.c | 2 +- tools/sched_ext/scx_flatcg.bpf.c | 2 +- tools/sched_ext/scx_qmap.bpf.c | 2 +-
I think these are fine. The Makefile is pulling in standard kbuild Makefiles, so I think the correct include directories (outside of tools/) are being used.
But yeah, easy mechanical change and a readability improvement. :)
Signature · 1 line
Kees Cook
Re: [RFC][PATCH 2/2] treewide: Have the task->flags & PF_KTHREAD check use the helper functions
Quoted 58 lines · Kees Cook
Quoted 39 lines · Steven Rostedt
From: Steven Rostedt <[email protected]>
Getting the check if a task is a kernel thread or a user thread can be error prone as it's not easy to see the difference.
if (!(task->flags & PF_KTHREAD))Is not immediately obvious that it's checking for a user thread.
if (
is_user_thread(task))Is much easier to review, as it is obvious that it is checking if the task is a user thread.
Using a coccinelle script, convert these checks over to using either
is_user_thread()oris_kernel_thread().$ cat kthread.cocci @@ identifier task; @@ - !(task->flags & PF_KTHREAD) + is_user_thread(task) @@ identifier task; @@ - (task->flags & PF_KTHREAD) == 0 + is_user_thread(task) @@ identifier task; @@ - (task->flags & PF_KTHREAD) != 0 + is_kernel_thread(task) @@ identifier task; @@ - task->flags & PF_KTHREAD + is_kernel_thread(task)Quoted 6 lines
$ spatch --dir --include-headers kthread.cocci . > /tmp/t.patch $ patch -p1 < /tmp/t.patchMake sure to undo the conversion of the helper functions themselves!
$ git show include/linux/sched.h | patch -p1 -RFYI, the "file in" test can be helpful. I use it to exclude tools and samples regularly, and *I think* it would work for excluding individual files too:
@name_of_rule depends !(file in "tools") && !(file in "samples")@
I've been collecting random notes like this here:
Quoted 7 lines
Quoted 3 lines
tools/sched_ext/scx_central.bpf.c | 2 +- tools/sched_ext/scx_flatcg.bpf.c | 2 +- tools/sched_ext/scx_qmap.bpf.c | 2 +-I think these are fine. The
Makefileis pulling in standard kbuild Makefiles, so I think the correct include directories (outside oftools/) are being used.
I suspect they are not fine.
I don't think they #include linux/sched.h
I would drop them for now.
Tejun,
please double check.
Tejun Heo
maintainerRe: [RFC][PATCH 2/2] treewide: Have the task->flags & PF_KTHREAD check use the helper functions
Quoted 11 lines · Alexei Starovoitov
Quoted 7 lines
Quoted 3 lines
tools/sched_ext/scx_central.bpf.c | 2 +- tools/sched_ext/scx_flatcg.bpf.c | 2 +- tools/sched_ext/scx_qmap.bpf.c | 2 +-I think these are fine. The
Makefileis pulling in standard kbuild Makefiles, so I think the correct include directories (outside oftools/) are being used.I suspect they are not fine.
I don't think they #includelinux/sched.h
I would drop them for now.
Oh, this won't work. Those get all the kernel defs from the BTF generated vmlinux.h file which doesn't include any inline functions or macros, so please don't include them in this conversion.
Thanks.
Signature · 1 line
tejun
Andrew Morton
maintainerQuoted 22 lines · On Fri, 25 Apr 2025 16:41:20 -0400 Steven Rostedt <[email protected]> wrote:
While working on the deferred stacktrace code, Peter Zijlstra told me to use
task->flags&PF_KTHREADinstead of checkingtask->mmfor NULL. This seemed reasonable, but while working on it, as there were several places that check if the task is a kernel thread and other places that check if the task is a user space thread I found it a bit confusing when looking at both:if (task->flags & PF_KTHREAD) and if (!(task->flags & PF_KTHREAD))Where I mixed them up sometimes, and checked for a user space thread when I really wanted to check for a kernel thread. I found these mistakes before sending out my patches, but going back and reviewing the code, I always had to stop and spend a few unnecessary seconds making sure the check was testing that flag correctly.
To make this a bit more obvious, I introduced two helper functions:
is_user_thread(task)
is_kernel_thread(task)
Quoted 7 lines
which simply test the flag for you. Thus, seeing:
if (
is_user_thread(task))
or
if (is_kernel_thread(task))it was very obvious to which test you wanted to make.
Seems sensible. Please consider renaming PF_KTHREAD in order to break missed conversion sites.
Quoted 26 lines · Andrew Morton
Quoted 24 lines · On Fri, 25 Apr 2025 16:41:20 -0400 Steven Rostedt <[email protected]> wrote:
While working on the deferred stacktrace code, Peter Zijlstra told me to use
task->flags&PF_KTHREADinstead of checkingtask->mmfor NULL. This seemed reasonable, but while working on it, as there were several places that check if the task is a kernel thread and other places that check if the task is a user space thread I found it a bit confusing when looking at both:if (task->flags & PF_KTHREAD) and if (!(task->flags & PF_KTHREAD))Where I mixed them up sometimes, and checked for a user space thread when I really wanted to check for a kernel thread. I found these mistakes before sending out my patches, but going back and reviewing the code, I always had to stop and spend a few unnecessary seconds making sure the check was testing that flag correctly.
To make this a bit more obvious, I introduced two helper functions:
is_user_thread(task)
is_kernel_thread(task)which simply test the flag for you. Thus, seeing:
Quoted 8 lines
Quoted 5 lines
if (
is_user_thread(task))
or
if (is_kernel_thread(task))it was very obvious to which test you wanted to make.
Seems sensible. Please consider renaming
PF_KTHREADin order to break missed conversion sites.
Maybe:
@r depends on !(file in "include/linux/sched.h")@ // Kees's suggestion position p;
expression e;
@@
(
e = (PF_KTHREAD | ...)
|
e |= (PF_KTHREAD | ...)
|
PF_KTHREAD@p
)
@script:ocaml@ // change to python if desired
p << r.p;
@@
Printf.printf "%s:%d: Warning: remaining use of PF_KTHREAD\n" (List.hd p).file (List.hd p).line
julia
Steven Rostedt
maintainerQuoted 2 lines · On Fri, 25 Apr 2025 16:14:49 -0700 Andrew Morton <[email protected]>…
Seems sensible. Please consider renaming
PF_KTHREADin order to break missed conversion sites.
It's not wrong to use the thread. I just find using these helper functions a bit easier to review code. There's also some places that have special tests where it can't use the flag:
kernel/sched/core.c: if (!curr->mm || (curr->flags & (PF_EXITING | PF_KTHREAD)) || kernel/sched/fair.c: if (!curr->mm || (curr->flags & (PF_EXITING | PF_KTHREAD)) || work->next != work) kernel/trace/bpf_trace.c: current->flags & (PF_KTHREAD | PF_EXITING))) kernel/trace/bpf_trace.c: if (unlikely(task->flags & (PF_KTHREAD | PF_EXITING)))
Maybe we can have a: is_user_exiting_or_kthread() ?
Note, for coccinelle patches, I would wait till the end of the merge window, run the scripts on what's in Linus's tree, run my tests, and then submit. This way it catches most of the conversions with the least amount of conflicts.
-- Steve
PATCH 1/1 sched/core: Introduce task_*() helpers for PF_ flags
Quoted 10 lines · Steven Rostedt
Quoted 2 lines · On Fri, 25 Apr 2025 16:14:49 -0700 Andrew Morton <[email protected]>…
Seems sensible. Please consider renaming
PF_KTHREADin order to break missed conversion sites.It's not wrong to use the thread. I just find using these helper functions a bit easier to review code. There's also some places that have special tests where it can't use the flag:
Quoted 6 lines
kernel/sched/core.c: if (!curr->mm || (curr->flags & (PF_EXITING | PF_KTHREAD)) || kernel/sched/fair.c: if (!curr->mm || (curr->flags & (PF_EXITING | PF_KTHREAD)) || work->next != work) kernel/trace/bpf_trace.c: current->flags & (PF_KTHREAD | PF_EXITING))) kernel/trace/bpf_trace.c: if (unlikely(task->flags & (PF_KTHREAD | PF_EXITING)))Maybe we can have a:
is_user_exiting_or_kthread()?
No, we don't need is_user_exiting_or_kthread(). At all. Ever. In this universe. Or in any alternative universes. We don't even need is_user_exiting_or_kthread() in horror fiction novels written for kernel developers: there's really a limit to the level of horror that people are able to accept. Sheesh ...
This:
if (task_kthread(task) || task_exiting(task)) ...
is a perfectly fine and readable C expression.
There's also *zero* reason for the whole is_*() complication your methods introduce. There's no need for 'is_' if we put a proper noun as a prefix before these methods, such as task_*(), and it also nicely organizes the namespace!
Let's not complicate trivial use of C logical operators unnecessarily, and let's not suck at namespaces more than we need to, 'kay?
( What's next, are we going to redefine 'if (x)' statements???
... wait a minute ... ;-)
The attached patch does the sane thing and introduces the following helpers for PF_ flags:
/* * Helpers for PF_ flags: */ #define task_vcpu(task) ((task)->flags & PF_VCPU) #define task_idle(task) ((task)->flags & PF_IDLE) #define task_exiting(task) ((task)->flags & PF_EXITING) #define task_postcoredump(task) ((task)->flags & PF_POSTCOREDUMP) #define task_io_worker(task) ((task)->flags & PF_IO_WORKER) #define task_wq_worker(task) ((task)->flags & PF_WQ_WORKER) #define task_forknoexec(task) ((task)->flags & PF_FORKNOEXEC) #define task_mce_process(task) ((task)->flags & PF_MCE_PROCESS) #define task_superpriv(task) ((task)->flags & PF_SUPERPRIV) #define task_dumpcore(task) ((task)->flags & PF_DUMPCORE) #define task_signaled(task) ((task)->flags & PF_SIGNALED) #define task_memalloc(task) ((task)->flags & PF_MEMALLOC) #define task_nproc_exceeded(task) ((task)->flags & PF_NPROC_EXCEEDED) #define task_used_math(task) ((task)->flags & PF_USED_MATH) #define task_user_worker(task) ((task)->flags & PF_USER_WORKER) #define task_nofreeze(task) ((task)->flags & PF_NOFREEZE) #define task_kcompactd(task) ((task)->flags & PF_KCOMPACTD) #define task_kswapd(task) ((task)->flags & PF_KSWAPD) #define task_memalloc_nofs(task) ((task)->flags & PF_MEMALLOC_NOFS) #define task_memalloc_noio(task) ((task)->flags & PF_MEMALLOC_NOIO) #define task_local_throttle(task) ((task)->flags & PF_LOCAL_THROTTLE) #define task_kthread(task) ((task)->flags & PF_KTHREAD) #define task_randomize(task) ((task)->flags & PF_RANDOMIZE) #define task_no_setaffinity(task) ((task)->flags & PF_NO_SETAFFINITY) #define task_mce_early(task) ((task)->flags & PF_MCE_EARLY) #define task_memalloc_pin(task) ((task)->flags & PF_MEMALLOC_PIN) #define task_block_ts(task) ((task)->flags & PF_BLOCK_TS) #define task_suspend_task(task) ((task)->flags & PF_SUSPEND_TASK)
These are easy names, precise lower-case variants of the PF_ flag
names: if you know the PF flag's name, you know the helper's name as well.
And no, we don't need separate helpers for !task_kthread() et al: the C logical negation unary operator is perfectly readable when placed before a function call or a macro invocation, and a competent Linux kernel developer is expected to recognize it on sight:
if (!task_kthread(task)) ...
Let's not infantilize the kernel source...
You can find this patch in my tree at:
git://git.kernel.org/pub/scm/linux/kernel/git/mingo/tip.git WIP.sched/core
Note that I plan to add a few more patches as well, while we are touching this area:
- tsk_used_math() is now overlapping and should be consolidated a bit. And the used_math() indirection should go away as well.
- I'll add conversion patches as well, at minimum for the top 10 flags that cover 90%+ of the PF_ flag usage:
nr of uses | flag
-------------------------
7 | PF_USED_MATH
8 | PF_USER_WORKER
10 PF_NOFREEZE
15 PF_WQ_WORKER
18 PF_NO_SETAFFINITY
18 PF_VCPU
24 PF_RANDOMIZE
30 PF_MEMALLOC
73 PF_EXITING
92 PF_KTHREAD
[ Or maybe for all of them - see below wrt. set_task_*(). ]
- PF_ goes for 'per-process flag' and as such it is a total misnomer, proudly misrepresented in <linux/sched.h>:
/* * Per process flags */ #define PF_VCPU 0x00000001 /* I'm a virtual CPU */ #define PF_IDLE 0x00000002 /* I am an IDLE thread */
Yeah, no: the PF_ flags haven't been "per process" ever since we introduced threading 25 years ago...
Renaming just for that causes churn, but it becomes easier once we have the conversion patches for helpers for explicit uses of PF_ flags.
- We might want to add set_task_*() helpers as well, to totally encapsulate PF_ uses. Maybe. I dislike how close it is to the existing set_tsk*() methods that manipulate TIF_ flags. The dichotomy between the TIF_ and PF_ space isn't really sensible these days I think on a conceptual level - although merging them is probably not practical due to possibly running out of easy 64-bit word width.
I'll send out a full series if there's no better suggestions for the general approach.
Thanks,
Ingo
============================>
From: Ingo Molnar <[email protected]>
Date: Sat, 26 Apr 2025 20:00:22 +0200
Subject: [PATCH] sched/core: Introduce task_*() helpers for PF_ flags
Add straightforward PF_ task flag helpers:
if (!(task->flags & PF_KTHREAD))
...
|
\|/
V
if (!task_kthread(task))
...( Fortunately there's no namespace collision for any of the new
methods introduced. )
--- include/linux/sched.h | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+)
include/linux/sched.h +32 -0
@@ -1747,6 +1747,38 @@ extern struct pid *cad_pid;#define PF__HOLE__40000000 0x40000000#define PF_SUSPEND_TASK 0x80000000/* This thread called freeze_processes() and should not be frozen */ +/* +* Helpers for PF_ flags: +*/ +#define task_vcpu (task) ((task)->flags & PF_VCPU) +#define task_idle (task) ((task)->flags & PF_IDLE) +#define task_exiting (task) ((task)->flags & PF_EXITING) +#define task_postcoredump (task) ((task)->flags & PF_POSTCOREDUMP) +#define task_io_worker (task) ((task)->flags & PF_IO_WORKER) +#define task_wq_worker (task) ((task)->flags & PF_WQ_WORKER) +#define task_forknoexec (task) ((task)->flags & PF_FORKNOEXEC) +#define task_mce_process (task) ((task)->flags & PF_MCE_PROCESS) +#define task_superpriv (task) ((task)->flags & PF_SUPERPRIV) +#define task_dumpcore (task) ((task)->flags & PF_DUMPCORE) +#define task_signaled (task) ((task)->flags & PF_SIGNALED) +#define task_memalloc (task) ((task)->flags & PF_MEMALLOC) +#define task_nproc_exceeded (task) ((task)->flags & PF_NPROC_EXCEEDED) +#define task_used_math (task) ((task)->flags & PF_USED_MATH) +#define task_user_worker (task) ((task)->flags & PF_USER_WORKER) +#define task_nofreeze (task) ((task)->flags & PF_NOFREEZE) +#define task_kcompactd (task) ((task)->flags & PF_KCOMPACTD) +#define task_kswapd (task) ((task)->flags & PF_KSWAPD) +#define task_memalloc_nofs (task) ((task)->flags & PF_MEMALLOC_NOFS) +#define task_memalloc_noio (task) ((task)->flags & PF_MEMALLOC_NOIO) +#define task_local_throttle (task) ((task)->flags & PF_LOCAL_THROTTLE) +#define task_kthread (task) ((task)->flags & PF_KTHREAD) +#define task_randomize (task) ((task)->flags & PF_RANDOMIZE) +#define task_no_setaffinity (task) ((task)->flags & PF_NO_SETAFFINITY) +#define task_mce_early (task) ((task)->flags & PF_MCE_EARLY) +#define task_memalloc_pin (task) ((task)->flags & PF_MEMALLOC_PIN) +#define task_block_ts (task) ((task)->flags & PF_BLOCK_TS) +#define task_suspend_task (task) ((task)->flags & PF_SUSPEND_TASK) +/* * Only the _current_ task can read/write to tsk->flags, but other * tasks can access tsk->flags in readonly mode for example
Re: [PATCH] sched/core: Introduce task_*() helpers for PF_ flags
Quoted 7 lines · Ingo Molnar
- We might want to add set_task_*() helpers as well, to totally encapsulate
PF_uses. Maybe. I dislike how close it is to the existing set_tsk*() methods that manipulateTIF_flags. The dichotomy between theTIF_andPF_space isn't really sensible these days I think on a conceptual level - although merging them is probably not practical due to possibly running out of easy 64-bit word width.
And yeah, the TIF_ space is per arch to a substantial degree, and is accessed from assembly code, plus is often operated on atomically, while the PF_ space is nicely generic and non-atomic - but still we could do better to express that these two per task flag spaces are rather similar in purpose, instead of this historic 'task/process' distinction that isn't actually true.
Thanks,
Ingo
Steven Rostedt
maintainerRe: [PATCH] sched/core: Introduce task_*() helpers for PF_ flags
In reply to Ingo MolnarQuoted 5 lines · On Sat, 26 Apr 2025 20:42:21 +0200 Ingo Molnar <[email protected]> wrote:
Quoted 5 lines
kernel/sched/core.c: if (!curr->mm || (curr->flags & (PF_EXITING | PF_KTHREAD)) || kernel/sched/fair.c: if (!curr->mm || (curr->flags & (PF_EXITING | PF_KTHREAD)) || work->next != work) kernel/trace/bpf_trace.c: current->flags & (PF_KTHREAD | PF_EXITING))) kernel/trace/bpf_trace.c: if (unlikely(task->flags & (PF_KTHREAD | PF_EXITING)))
Quoted 7 lines
Quoted 1 line
Maybe we can have a:
is_user_exiting_or_kthread()?No, we don't need
is_user_exiting_or_kthread(). At all. Ever. In this universe. Or in any alternative universes. We don't even needis_user_exiting_or_kthread()in horror fiction novels written for kernel developers: there's really a limit to the level of horror that people are able to accept. Sheesh ...
Ingo,
A simple "No we do not need that" would suffice. This isn't 2005 anymore, where we come up with creative ways to insult each other. We're better now.
Quoted 7 lines
And no, we don't need separate helpers for !task_kthread() et al: the C logical negation unary operator is perfectly readable when placed before a function call or a macro invocation, and a competent Linux kernel developer is expected to recognize it on sight:
if (!task_kthread(task)) ...
Not really. I originally tried just having a single "is_kernel_thread()" where I would use the "!is_kernel_thread()" for user thread, but honestly, it wasn't much better than the "!(task->flags & PF_KTHREAD)".
And just because it's not a kernel thread, does it mean it will always be a user space thread? Could it one day also be a guest thread (if we decide to have such a thing)?
Wanting to know if something is a user space thread, "if (!task_kthread(task))" seems short sighted. As it assumes that we only have two types of threads. It may be true today, but may not be the case in the future.
if (!task_kthread(task))
Still takes a second more to understand that's a user space thread than:
if (task_user(task))
would.
-- Steve
Steven Rostedt
maintainerRe: [PATCH] sched/core: Introduce task_*() helpers for PF_ flags
In reply to Ingo MolnarQuoted 2 lines · On Sat, 26 Apr 2025 20:42:21 +0200 Ingo Molnar <[email protected]> wrote:
I'll send out a full series if there's no better suggestions for the general approach.
Fine, you can take over. I have other things to work on.
Unless you add a task_user() or something similar that makes it very easy to see that a task is a user thread other than testing if it's not a kernel thread, it doesn't solve the issue that was my original motivation for my patches. That is, there's places in the code that needs to only work on user threads, and it would be nice to quickly see that the if statement is checking if it is or not.
We have places that check if it's a kernel thread to exit out early:
if (task_kernel(task)) goto out;
And places that do something if it's a user thread:
if (task_user(task)) // do something special
By explicitly stating "user" in the test, makes that very easy to see, where as:
if (task_kernel(task)) goto out;
and
if (!task_kernel(task)) // do something special
makes you have to look a bit harder. The kernel is complex enough, I believe we should make it easier where there's low hanging fruit to do so.
-- Steve