xref: /linux/lib/is_single_threaded.c (revision 4cf421e55d69016989548e0fb8585e69f54bd283)
1 /* Function to determine if a thread group is single threaded or not
2  *
3  * Copyright (C) 2008 Red Hat, Inc. All Rights Reserved.
4  * Written by David Howells (dhowells@redhat.com)
5  * - Derived from security/selinux/hooks.c
6  *
7  * This program is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU General Public Licence
9  * as published by the Free Software Foundation; either version
10  * 2 of the Licence, or (at your option) any later version.
11  */
12 #include <linux/sched/signal.h>
13 
14 /*
15  * Returns true if the task does not share ->mm with another thread/process.
16  */
17 bool current_is_single_threaded(void)
18 {
19 	struct task_struct *task = current;
20 	struct mm_struct *mm = task->mm;
21 	struct task_struct *p, *t;
22 	bool ret;
23 
24 	if (atomic_read(&task->signal->live) != 1)
25 		return false;
26 
27 	if (atomic_read(&mm->mm_users) == 1)
28 		return true;
29 
30 	ret = false;
31 	rcu_read_lock();
32 	for_each_process(p) {
33 		if (unlikely(p->flags & PF_KTHREAD))
34 			continue;
35 		if (unlikely(p == task->group_leader))
36 			continue;
37 
38 		for_each_thread(p, t) {
39 			if (unlikely(t->mm == mm))
40 				goto found;
41 			if (likely(t->mm))
42 				break;
43 			/*
44 			 * t->mm == NULL. Make sure next_thread/next_task
45 			 * will see other CLONE_VM tasks which might be
46 			 * forked before exiting.
47 			 */
48 			smp_rmb();
49 		}
50 	}
51 	ret = true;
52 found:
53 	rcu_read_unlock();
54 
55 	return ret;
56 }
57