xref: /openbmc/linux/lib/is_single_threaded.c (revision 967cc5371113f9806b39a2ebb2174af2883d96fe)
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  */
126cc88bc4SDavid Howells 
136cc88bc4SDavid Howells #include <linux/sched.h>
146cc88bc4SDavid Howells 
15d2e3ee9bSOleg Nesterov /*
16d2e3ee9bSOleg Nesterov  * Returns true if the task does not share ->mm with another thread/process.
176cc88bc4SDavid Howells  */
185bb459bbSOleg Nesterov bool current_is_single_threaded(void)
196cc88bc4SDavid Howells {
205bb459bbSOleg Nesterov 	struct task_struct *task = current;
21d2e3ee9bSOleg Nesterov 	struct mm_struct *mm = task->mm;
22d2e3ee9bSOleg Nesterov 	struct task_struct *p, *t;
23d2e3ee9bSOleg Nesterov 	bool ret;
246cc88bc4SDavid Howells 
25d2e3ee9bSOleg Nesterov 	if (atomic_read(&task->signal->live) != 1)
26d2e3ee9bSOleg Nesterov 		return false;
276cc88bc4SDavid Howells 
28d2e3ee9bSOleg Nesterov 	if (atomic_read(&mm->mm_users) == 1)
296cc88bc4SDavid Howells 		return true;
306cc88bc4SDavid Howells 
31d2e3ee9bSOleg Nesterov 	ret = false;
32d2e3ee9bSOleg Nesterov 	rcu_read_lock();
33d2e3ee9bSOleg Nesterov 	for_each_process(p) {
34d2e3ee9bSOleg Nesterov 		if (unlikely(p->flags & PF_KTHREAD))
35d2e3ee9bSOleg Nesterov 			continue;
36d2e3ee9bSOleg Nesterov 		if (unlikely(p == task->group_leader))
37d2e3ee9bSOleg Nesterov 			continue;
38d2e3ee9bSOleg Nesterov 
39d2e3ee9bSOleg Nesterov 		t = p;
40d2e3ee9bSOleg Nesterov 		do {
41d2e3ee9bSOleg Nesterov 			if (unlikely(t->mm == mm))
42d2e3ee9bSOleg Nesterov 				goto found;
43d2e3ee9bSOleg Nesterov 			if (likely(t->mm))
44d2e3ee9bSOleg Nesterov 				break;
45*967cc537SOleg Nesterov 			/*
46*967cc537SOleg Nesterov 			 * t->mm == NULL. Make sure next_thread/next_task
47*967cc537SOleg Nesterov 			 * will see other CLONE_VM tasks which might be
48*967cc537SOleg Nesterov 			 * forked before exiting.
49*967cc537SOleg Nesterov 			 */
50*967cc537SOleg Nesterov 			smp_rmb();
51d2e3ee9bSOleg Nesterov 		} while_each_thread(p, t);
52d2e3ee9bSOleg Nesterov 	}
53d2e3ee9bSOleg Nesterov 	ret = true;
54d2e3ee9bSOleg Nesterov found:
55d2e3ee9bSOleg Nesterov 	rcu_read_unlock();
56d2e3ee9bSOleg Nesterov 
57d2e3ee9bSOleg Nesterov 	return ret;
586cc88bc4SDavid Howells }
59