xref: /openbmc/linux/lib/is_single_threaded.c (revision 3f07c0144132e4f59d88055ac8ff3e691a5fa2b8)
16cc88bc4SDavid Howells /* Function to determine if a thread group is single threaded or not
26cc88bc4SDavid Howells  *
36cc88bc4SDavid Howells  * Copyright (C) 2008 Red Hat, Inc. All Rights Reserved.
46cc88bc4SDavid Howells  * Written by David Howells (dhowells@redhat.com)
56cc88bc4SDavid Howells  * - Derived from security/selinux/hooks.c
66cc88bc4SDavid Howells  *
76cc88bc4SDavid Howells  * This program is free software; you can redistribute it and/or
86cc88bc4SDavid Howells  * modify it under the terms of the GNU General Public Licence
96cc88bc4SDavid Howells  * as published by the Free Software Foundation; either version
106cc88bc4SDavid Howells  * 2 of the Licence, or (at your option) any later version.
116cc88bc4SDavid Howells  */
12*3f07c014SIngo Molnar #include <linux/sched/signal.h>
136cc88bc4SDavid Howells 
14d2e3ee9bSOleg Nesterov /*
15d2e3ee9bSOleg Nesterov  * Returns true if the task does not share ->mm with another thread/process.
166cc88bc4SDavid Howells  */
175bb459bbSOleg Nesterov bool current_is_single_threaded(void)
186cc88bc4SDavid Howells {
195bb459bbSOleg Nesterov 	struct task_struct *task = current;
20d2e3ee9bSOleg Nesterov 	struct mm_struct *mm = task->mm;
21d2e3ee9bSOleg Nesterov 	struct task_struct *p, *t;
22d2e3ee9bSOleg Nesterov 	bool ret;
236cc88bc4SDavid Howells 
24d2e3ee9bSOleg Nesterov 	if (atomic_read(&task->signal->live) != 1)
25d2e3ee9bSOleg Nesterov 		return false;
266cc88bc4SDavid Howells 
27d2e3ee9bSOleg Nesterov 	if (atomic_read(&mm->mm_users) == 1)
286cc88bc4SDavid Howells 		return true;
296cc88bc4SDavid Howells 
30d2e3ee9bSOleg Nesterov 	ret = false;
31d2e3ee9bSOleg Nesterov 	rcu_read_lock();
32d2e3ee9bSOleg Nesterov 	for_each_process(p) {
33d2e3ee9bSOleg Nesterov 		if (unlikely(p->flags & PF_KTHREAD))
34d2e3ee9bSOleg Nesterov 			continue;
35d2e3ee9bSOleg Nesterov 		if (unlikely(p == task->group_leader))
36d2e3ee9bSOleg Nesterov 			continue;
37d2e3ee9bSOleg Nesterov 
3890224350SOleg Nesterov 		for_each_thread(p, t) {
39d2e3ee9bSOleg Nesterov 			if (unlikely(t->mm == mm))
40d2e3ee9bSOleg Nesterov 				goto found;
41d2e3ee9bSOleg Nesterov 			if (likely(t->mm))
42d2e3ee9bSOleg Nesterov 				break;
43967cc537SOleg Nesterov 			/*
44967cc537SOleg Nesterov 			 * t->mm == NULL. Make sure next_thread/next_task
45967cc537SOleg Nesterov 			 * will see other CLONE_VM tasks which might be
46967cc537SOleg Nesterov 			 * forked before exiting.
47967cc537SOleg Nesterov 			 */
48967cc537SOleg Nesterov 			smp_rmb();
4990224350SOleg Nesterov 		}
50d2e3ee9bSOleg Nesterov 	}
51d2e3ee9bSOleg Nesterov 	ret = true;
52d2e3ee9bSOleg Nesterov found:
53d2e3ee9bSOleg Nesterov 	rcu_read_unlock();
54d2e3ee9bSOleg Nesterov 
55d2e3ee9bSOleg Nesterov 	return ret;
566cc88bc4SDavid Howells }
57