blob: 8c98b20bfc414a91dd9f00926358c2a425340855 [file] [log] [blame]
Thomas Gleixnerb4d0d232019-05-20 19:08:01 +02001// SPDX-License-Identifier: GPL-2.0-or-later
David Howells6cc88bc2008-11-14 10:39:21 +11002/* Function to determine if a thread group is single threaded or not
3 *
4 * Copyright (C) 2008 Red Hat, Inc. All Rights Reserved.
5 * Written by David Howells (dhowells@redhat.com)
6 * - Derived from security/selinux/hooks.c
David Howells6cc88bc2008-11-14 10:39:21 +11007 */
Ingo Molnar3f07c012017-02-08 18:51:30 +01008#include <linux/sched/signal.h>
Ingo Molnar9164bb42017-02-04 01:20:53 +01009#include <linux/sched/task.h>
Ingo Molnar589ee622017-02-04 00:16:44 +010010#include <linux/sched/mm.h>
David Howells6cc88bc2008-11-14 10:39:21 +110011
Oleg Nesterovd2e3ee92009-07-17 09:09:36 +100012/*
13 * Returns true if the task does not share ->mm with another thread/process.
David Howells6cc88bc2008-11-14 10:39:21 +110014 */
Oleg Nesterov5bb459b2009-07-10 03:48:23 +020015bool current_is_single_threaded(void)
David Howells6cc88bc2008-11-14 10:39:21 +110016{
Oleg Nesterov5bb459b2009-07-10 03:48:23 +020017 struct task_struct *task = current;
Oleg Nesterovd2e3ee92009-07-17 09:09:36 +100018 struct mm_struct *mm = task->mm;
19 struct task_struct *p, *t;
20 bool ret;
David Howells6cc88bc2008-11-14 10:39:21 +110021
Oleg Nesterovd2e3ee92009-07-17 09:09:36 +100022 if (atomic_read(&task->signal->live) != 1)
23 return false;
24
25 if (atomic_read(&mm->mm_users) == 1)
26 return true;
27
28 ret = false;
Oleg Nesterovd2e3ee92009-07-17 09:09:36 +100029 rcu_read_lock();
30 for_each_process(p) {
31 if (unlikely(p->flags & PF_KTHREAD))
32 continue;
33 if (unlikely(p == task->group_leader))
34 continue;
35
Oleg Nesterov90224352015-11-06 16:31:26 -080036 for_each_thread(p, t) {
Oleg Nesterovd2e3ee92009-07-17 09:09:36 +100037 if (unlikely(t->mm == mm))
38 goto found;
39 if (likely(t->mm))
40 break;
Oleg Nesterov967cc532009-07-09 23:28:49 +020041 /*
42 * t->mm == NULL. Make sure next_thread/next_task
43 * will see other CLONE_VM tasks which might be
44 * forked before exiting.
45 */
46 smp_rmb();
Oleg Nesterov90224352015-11-06 16:31:26 -080047 }
David Howells6cc88bc2008-11-14 10:39:21 +110048 }
Oleg Nesterovd2e3ee92009-07-17 09:09:36 +100049 ret = true;
50found:
51 rcu_read_unlock();
David Howells6cc88bc2008-11-14 10:39:21 +110052
Oleg Nesterovd2e3ee92009-07-17 09:09:36 +100053 return ret;
David Howells6cc88bc2008-11-14 10:39:21 +110054}