xref: /openbmc/linux/kernel/fork.c (revision 4eb5aaa3af8a54e5e9bac90e2b42bbab1f1ee5a3)
11da177e4SLinus Torvalds /*
21da177e4SLinus Torvalds  *  linux/kernel/fork.c
31da177e4SLinus Torvalds  *
41da177e4SLinus Torvalds  *  Copyright (C) 1991, 1992  Linus Torvalds
51da177e4SLinus Torvalds  */
61da177e4SLinus Torvalds 
71da177e4SLinus Torvalds /*
81da177e4SLinus Torvalds  *  'fork.c' contains the help-routines for the 'fork' system call
91da177e4SLinus Torvalds  * (see also entry.S and others).
101da177e4SLinus Torvalds  * Fork is rather simple, once you get the hang of it, but the memory
111da177e4SLinus Torvalds  * management can be a bitch. See 'mm/memory.c': 'copy_page_range()'
121da177e4SLinus Torvalds  */
131da177e4SLinus Torvalds 
141da177e4SLinus Torvalds #include <linux/slab.h>
15*4eb5aaa3SIngo Molnar #include <linux/sched/autogroup.h>
161da177e4SLinus Torvalds #include <linux/init.h>
171da177e4SLinus Torvalds #include <linux/unistd.h>
181da177e4SLinus Torvalds #include <linux/module.h>
191da177e4SLinus Torvalds #include <linux/vmalloc.h>
201da177e4SLinus Torvalds #include <linux/completion.h>
211da177e4SLinus Torvalds #include <linux/personality.h>
221da177e4SLinus Torvalds #include <linux/mempolicy.h>
231da177e4SLinus Torvalds #include <linux/sem.h>
241da177e4SLinus Torvalds #include <linux/file.h>
259f3acc31SAl Viro #include <linux/fdtable.h>
26da9cbc87SJens Axboe #include <linux/iocontext.h>
271da177e4SLinus Torvalds #include <linux/key.h>
281da177e4SLinus Torvalds #include <linux/binfmts.h>
291da177e4SLinus Torvalds #include <linux/mman.h>
30cddb8a5cSAndrea Arcangeli #include <linux/mmu_notifier.h>
311da177e4SLinus Torvalds #include <linux/fs.h>
32615d6e87SDavidlohr Bueso #include <linux/mm.h>
33615d6e87SDavidlohr Bueso #include <linux/vmacache.h>
34ab516013SSerge E. Hallyn #include <linux/nsproxy.h>
35c59ede7bSRandy.Dunlap #include <linux/capability.h>
361da177e4SLinus Torvalds #include <linux/cpu.h>
37b4f48b63SPaul Menage #include <linux/cgroup.h>
381da177e4SLinus Torvalds #include <linux/security.h>
39a1e78772SMel Gorman #include <linux/hugetlb.h>
40e2cfabdfSWill Drewry #include <linux/seccomp.h>
411da177e4SLinus Torvalds #include <linux/swap.h>
421da177e4SLinus Torvalds #include <linux/syscalls.h>
431da177e4SLinus Torvalds #include <linux/jiffies.h>
441da177e4SLinus Torvalds #include <linux/futex.h>
458141c7f3SLinus Torvalds #include <linux/compat.h>
46207205a2SEric Dumazet #include <linux/kthread.h>
477c3ab738SAndrew Morton #include <linux/task_io_accounting_ops.h>
48ab2af1f5SDipankar Sarma #include <linux/rcupdate.h>
491da177e4SLinus Torvalds #include <linux/ptrace.h>
501da177e4SLinus Torvalds #include <linux/mount.h>
511da177e4SLinus Torvalds #include <linux/audit.h>
5278fb7466SPavel Emelianov #include <linux/memcontrol.h>
53f201ae23SFrederic Weisbecker #include <linux/ftrace.h>
545e2bf014SMike Galbraith #include <linux/proc_fs.h>
551da177e4SLinus Torvalds #include <linux/profile.h>
561da177e4SLinus Torvalds #include <linux/rmap.h>
57f8af4da3SHugh Dickins #include <linux/ksm.h>
581da177e4SLinus Torvalds #include <linux/acct.h>
59893e26e6SPavel Emelyanov #include <linux/userfaultfd_k.h>
608f0ab514SJay Lan #include <linux/tsacct_kern.h>
619f46080cSMatt Helsley #include <linux/cn_proc.h>
62ba96a0c8SRafael J. Wysocki #include <linux/freezer.h>
63ca74e92bSShailabh Nagar #include <linux/delayacct.h>
64ad4ecbcbSShailabh Nagar #include <linux/taskstats_kern.h>
650a425405SArjan van de Ven #include <linux/random.h>
66522ed776SMiloslav Trmac #include <linux/tty.h>
67fd0928dfSJens Axboe #include <linux/blkdev.h>
685ad4e53bSAl Viro #include <linux/fs_struct.h>
697c9f8861SEric Sandeen #include <linux/magic.h>
70cdd6c482SIngo Molnar #include <linux/perf_event.h>
7142c4ab41SStanislaw Gruszka #include <linux/posix-timers.h>
728e7cac79SAvi Kivity #include <linux/user-return-notifier.h>
733d5992d2SYing Han #include <linux/oom.h>
74ba76149fSAndrea Arcangeli #include <linux/khugepaged.h>
75d80e731eSOleg Nesterov #include <linux/signalfd.h>
760326f5a9SSrikar Dronamraju #include <linux/uprobes.h>
77a27bb332SKent Overstreet #include <linux/aio.h>
7852f5684cSGideon Israel Dsouza #include <linux/compiler.h>
7916db3d3fSHeinrich Schuchardt #include <linux/sysctl.h>
805c9a8750SDmitry Vyukov #include <linux/kcov.h>
811da177e4SLinus Torvalds 
821da177e4SLinus Torvalds #include <asm/pgtable.h>
831da177e4SLinus Torvalds #include <asm/pgalloc.h>
847c0f6ba6SLinus Torvalds #include <linux/uaccess.h>
851da177e4SLinus Torvalds #include <asm/mmu_context.h>
861da177e4SLinus Torvalds #include <asm/cacheflush.h>
871da177e4SLinus Torvalds #include <asm/tlbflush.h>
881da177e4SLinus Torvalds 
89ad8d75ffSSteven Rostedt #include <trace/events/sched.h>
90ad8d75ffSSteven Rostedt 
9143d2b113SKAMEZAWA Hiroyuki #define CREATE_TRACE_POINTS
9243d2b113SKAMEZAWA Hiroyuki #include <trace/events/task.h>
9343d2b113SKAMEZAWA Hiroyuki 
941da177e4SLinus Torvalds /*
95ac1b398dSHeinrich Schuchardt  * Minimum number of threads to boot the kernel
96ac1b398dSHeinrich Schuchardt  */
97ac1b398dSHeinrich Schuchardt #define MIN_THREADS 20
98ac1b398dSHeinrich Schuchardt 
99ac1b398dSHeinrich Schuchardt /*
100ac1b398dSHeinrich Schuchardt  * Maximum number of threads
101ac1b398dSHeinrich Schuchardt  */
102ac1b398dSHeinrich Schuchardt #define MAX_THREADS FUTEX_TID_MASK
103ac1b398dSHeinrich Schuchardt 
104ac1b398dSHeinrich Schuchardt /*
1051da177e4SLinus Torvalds  * Protected counters by write_lock_irq(&tasklist_lock)
1061da177e4SLinus Torvalds  */
1071da177e4SLinus Torvalds unsigned long total_forks;	/* Handle normal Linux uptimes. */
1081da177e4SLinus Torvalds int nr_threads;			/* The idle threads do not count.. */
1091da177e4SLinus Torvalds 
1101da177e4SLinus Torvalds int max_threads;		/* tunable limit on nr_threads */
1111da177e4SLinus Torvalds 
1121da177e4SLinus Torvalds DEFINE_PER_CPU(unsigned long, process_counts) = 0;
1131da177e4SLinus Torvalds 
1141da177e4SLinus Torvalds __cacheline_aligned DEFINE_RWLOCK(tasklist_lock);  /* outer */
115db1466b3SPaul E. McKenney 
116db1466b3SPaul E. McKenney #ifdef CONFIG_PROVE_RCU
117db1466b3SPaul E. McKenney int lockdep_tasklist_lock_is_held(void)
118db1466b3SPaul E. McKenney {
119db1466b3SPaul E. McKenney 	return lockdep_is_held(&tasklist_lock);
120db1466b3SPaul E. McKenney }
121db1466b3SPaul E. McKenney EXPORT_SYMBOL_GPL(lockdep_tasklist_lock_is_held);
122db1466b3SPaul E. McKenney #endif /* #ifdef CONFIG_PROVE_RCU */
1231da177e4SLinus Torvalds 
1241da177e4SLinus Torvalds int nr_processes(void)
1251da177e4SLinus Torvalds {
1261da177e4SLinus Torvalds 	int cpu;
1271da177e4SLinus Torvalds 	int total = 0;
1281da177e4SLinus Torvalds 
1291d510750SIan Campbell 	for_each_possible_cpu(cpu)
1301da177e4SLinus Torvalds 		total += per_cpu(process_counts, cpu);
1311da177e4SLinus Torvalds 
1321da177e4SLinus Torvalds 	return total;
1331da177e4SLinus Torvalds }
1341da177e4SLinus Torvalds 
135f19b9f74SAkinobu Mita void __weak arch_release_task_struct(struct task_struct *tsk)
136f19b9f74SAkinobu Mita {
137f19b9f74SAkinobu Mita }
138f19b9f74SAkinobu Mita 
139f5e10287SThomas Gleixner #ifndef CONFIG_ARCH_TASK_STRUCT_ALLOCATOR
140e18b890bSChristoph Lameter static struct kmem_cache *task_struct_cachep;
14141101809SThomas Gleixner 
14241101809SThomas Gleixner static inline struct task_struct *alloc_task_struct_node(int node)
14341101809SThomas Gleixner {
14441101809SThomas Gleixner 	return kmem_cache_alloc_node(task_struct_cachep, GFP_KERNEL, node);
14541101809SThomas Gleixner }
14641101809SThomas Gleixner 
14741101809SThomas Gleixner static inline void free_task_struct(struct task_struct *tsk)
14841101809SThomas Gleixner {
14941101809SThomas Gleixner 	kmem_cache_free(task_struct_cachep, tsk);
15041101809SThomas Gleixner }
1511da177e4SLinus Torvalds #endif
1521da177e4SLinus Torvalds 
153b235beeaSLinus Torvalds void __weak arch_release_thread_stack(unsigned long *stack)
154f19b9f74SAkinobu Mita {
155f19b9f74SAkinobu Mita }
156f19b9f74SAkinobu Mita 
157b235beeaSLinus Torvalds #ifndef CONFIG_ARCH_THREAD_STACK_ALLOCATOR
15841101809SThomas Gleixner 
1590d15d74aSThomas Gleixner /*
1600d15d74aSThomas Gleixner  * Allocate pages if THREAD_SIZE is >= PAGE_SIZE, otherwise use a
1610d15d74aSThomas Gleixner  * kmemcache based allocator.
1620d15d74aSThomas Gleixner  */
163ba14a194SAndy Lutomirski # if THREAD_SIZE >= PAGE_SIZE || defined(CONFIG_VMAP_STACK)
164ac496bf4SAndy Lutomirski 
165ac496bf4SAndy Lutomirski #ifdef CONFIG_VMAP_STACK
166ac496bf4SAndy Lutomirski /*
167ac496bf4SAndy Lutomirski  * vmalloc() is a bit slow, and calling vfree() enough times will force a TLB
168ac496bf4SAndy Lutomirski  * flush.  Try to minimize the number of calls by caching stacks.
169ac496bf4SAndy Lutomirski  */
170ac496bf4SAndy Lutomirski #define NR_CACHED_STACKS 2
171ac496bf4SAndy Lutomirski static DEFINE_PER_CPU(struct vm_struct *, cached_stacks[NR_CACHED_STACKS]);
172ac496bf4SAndy Lutomirski #endif
173ac496bf4SAndy Lutomirski 
174ba14a194SAndy Lutomirski static unsigned long *alloc_thread_stack_node(struct task_struct *tsk, int node)
175b69c49b7SFUJITA Tomonori {
176ba14a194SAndy Lutomirski #ifdef CONFIG_VMAP_STACK
177ac496bf4SAndy Lutomirski 	void *stack;
178ac496bf4SAndy Lutomirski 	int i;
179ac496bf4SAndy Lutomirski 
180ac496bf4SAndy Lutomirski 	local_irq_disable();
181ac496bf4SAndy Lutomirski 	for (i = 0; i < NR_CACHED_STACKS; i++) {
182ac496bf4SAndy Lutomirski 		struct vm_struct *s = this_cpu_read(cached_stacks[i]);
183ac496bf4SAndy Lutomirski 
184ac496bf4SAndy Lutomirski 		if (!s)
185ac496bf4SAndy Lutomirski 			continue;
186ac496bf4SAndy Lutomirski 		this_cpu_write(cached_stacks[i], NULL);
187ac496bf4SAndy Lutomirski 
188ac496bf4SAndy Lutomirski 		tsk->stack_vm_area = s;
189ac496bf4SAndy Lutomirski 		local_irq_enable();
190ac496bf4SAndy Lutomirski 		return s->addr;
191ac496bf4SAndy Lutomirski 	}
192ac496bf4SAndy Lutomirski 	local_irq_enable();
193ac496bf4SAndy Lutomirski 
194ac496bf4SAndy Lutomirski 	stack = __vmalloc_node_range(THREAD_SIZE, THREAD_SIZE,
195ba14a194SAndy Lutomirski 				     VMALLOC_START, VMALLOC_END,
196ba14a194SAndy Lutomirski 				     THREADINFO_GFP | __GFP_HIGHMEM,
197ba14a194SAndy Lutomirski 				     PAGE_KERNEL,
198ac496bf4SAndy Lutomirski 				     0, node, __builtin_return_address(0));
199ba14a194SAndy Lutomirski 
200ba14a194SAndy Lutomirski 	/*
201ba14a194SAndy Lutomirski 	 * We can't call find_vm_area() in interrupt context, and
202ba14a194SAndy Lutomirski 	 * free_thread_stack() can be called in interrupt context,
203ba14a194SAndy Lutomirski 	 * so cache the vm_struct.
204ba14a194SAndy Lutomirski 	 */
205ba14a194SAndy Lutomirski 	if (stack)
206ba14a194SAndy Lutomirski 		tsk->stack_vm_area = find_vm_area(stack);
207ba14a194SAndy Lutomirski 	return stack;
208ba14a194SAndy Lutomirski #else
2094949148aSVladimir Davydov 	struct page *page = alloc_pages_node(node, THREADINFO_GFP,
2102889f608SThomas Gleixner 					     THREAD_SIZE_ORDER);
211b6a84016SEric Dumazet 
212b6a84016SEric Dumazet 	return page ? page_address(page) : NULL;
213ba14a194SAndy Lutomirski #endif
214b69c49b7SFUJITA Tomonori }
215b69c49b7SFUJITA Tomonori 
216ba14a194SAndy Lutomirski static inline void free_thread_stack(struct task_struct *tsk)
217b69c49b7SFUJITA Tomonori {
218ac496bf4SAndy Lutomirski #ifdef CONFIG_VMAP_STACK
219ac496bf4SAndy Lutomirski 	if (task_stack_vm_area(tsk)) {
220ac496bf4SAndy Lutomirski 		unsigned long flags;
221ac496bf4SAndy Lutomirski 		int i;
222ac496bf4SAndy Lutomirski 
223ac496bf4SAndy Lutomirski 		local_irq_save(flags);
224ac496bf4SAndy Lutomirski 		for (i = 0; i < NR_CACHED_STACKS; i++) {
225ac496bf4SAndy Lutomirski 			if (this_cpu_read(cached_stacks[i]))
226ac496bf4SAndy Lutomirski 				continue;
227ac496bf4SAndy Lutomirski 
228ac496bf4SAndy Lutomirski 			this_cpu_write(cached_stacks[i], tsk->stack_vm_area);
229ac496bf4SAndy Lutomirski 			local_irq_restore(flags);
230ac496bf4SAndy Lutomirski 			return;
231ac496bf4SAndy Lutomirski 		}
232ac496bf4SAndy Lutomirski 		local_irq_restore(flags);
233ac496bf4SAndy Lutomirski 
2340f110a9bSAndrey Ryabinin 		vfree_atomic(tsk->stack);
235ac496bf4SAndy Lutomirski 		return;
236ac496bf4SAndy Lutomirski 	}
237ac496bf4SAndy Lutomirski #endif
238ac496bf4SAndy Lutomirski 
239ba14a194SAndy Lutomirski 	__free_pages(virt_to_page(tsk->stack), THREAD_SIZE_ORDER);
240b69c49b7SFUJITA Tomonori }
2410d15d74aSThomas Gleixner # else
242b235beeaSLinus Torvalds static struct kmem_cache *thread_stack_cache;
2430d15d74aSThomas Gleixner 
2449521d399SMichael Ellerman static unsigned long *alloc_thread_stack_node(struct task_struct *tsk,
2450d15d74aSThomas Gleixner 						  int node)
2460d15d74aSThomas Gleixner {
247b235beeaSLinus Torvalds 	return kmem_cache_alloc_node(thread_stack_cache, THREADINFO_GFP, node);
2480d15d74aSThomas Gleixner }
2490d15d74aSThomas Gleixner 
250ba14a194SAndy Lutomirski static void free_thread_stack(struct task_struct *tsk)
2510d15d74aSThomas Gleixner {
252ba14a194SAndy Lutomirski 	kmem_cache_free(thread_stack_cache, tsk->stack);
2530d15d74aSThomas Gleixner }
2540d15d74aSThomas Gleixner 
255b235beeaSLinus Torvalds void thread_stack_cache_init(void)
2560d15d74aSThomas Gleixner {
257b235beeaSLinus Torvalds 	thread_stack_cache = kmem_cache_create("thread_stack", THREAD_SIZE,
2580d15d74aSThomas Gleixner 					      THREAD_SIZE, 0, NULL);
259b235beeaSLinus Torvalds 	BUG_ON(thread_stack_cache == NULL);
2600d15d74aSThomas Gleixner }
2610d15d74aSThomas Gleixner # endif
262b69c49b7SFUJITA Tomonori #endif
263b69c49b7SFUJITA Tomonori 
2641da177e4SLinus Torvalds /* SLAB cache for signal_struct structures (tsk->signal) */
265e18b890bSChristoph Lameter static struct kmem_cache *signal_cachep;
2661da177e4SLinus Torvalds 
2671da177e4SLinus Torvalds /* SLAB cache for sighand_struct structures (tsk->sighand) */
268e18b890bSChristoph Lameter struct kmem_cache *sighand_cachep;
2691da177e4SLinus Torvalds 
2701da177e4SLinus Torvalds /* SLAB cache for files_struct structures (tsk->files) */
271e18b890bSChristoph Lameter struct kmem_cache *files_cachep;
2721da177e4SLinus Torvalds 
2731da177e4SLinus Torvalds /* SLAB cache for fs_struct structures (tsk->fs) */
274e18b890bSChristoph Lameter struct kmem_cache *fs_cachep;
2751da177e4SLinus Torvalds 
2761da177e4SLinus Torvalds /* SLAB cache for vm_area_struct structures */
277e18b890bSChristoph Lameter struct kmem_cache *vm_area_cachep;
2781da177e4SLinus Torvalds 
2791da177e4SLinus Torvalds /* SLAB cache for mm_struct structures (tsk->mm) */
280e18b890bSChristoph Lameter static struct kmem_cache *mm_cachep;
2811da177e4SLinus Torvalds 
282ba14a194SAndy Lutomirski static void account_kernel_stack(struct task_struct *tsk, int account)
283c6a7f572SKOSAKI Motohiro {
284ba14a194SAndy Lutomirski 	void *stack = task_stack_page(tsk);
285ba14a194SAndy Lutomirski 	struct vm_struct *vm = task_stack_vm_area(tsk);
286ba14a194SAndy Lutomirski 
287ba14a194SAndy Lutomirski 	BUILD_BUG_ON(IS_ENABLED(CONFIG_VMAP_STACK) && PAGE_SIZE % 1024 != 0);
288ba14a194SAndy Lutomirski 
289ba14a194SAndy Lutomirski 	if (vm) {
290ba14a194SAndy Lutomirski 		int i;
291ba14a194SAndy Lutomirski 
292ba14a194SAndy Lutomirski 		BUG_ON(vm->nr_pages != THREAD_SIZE / PAGE_SIZE);
293ba14a194SAndy Lutomirski 
294ba14a194SAndy Lutomirski 		for (i = 0; i < THREAD_SIZE / PAGE_SIZE; i++) {
295ba14a194SAndy Lutomirski 			mod_zone_page_state(page_zone(vm->pages[i]),
296ba14a194SAndy Lutomirski 					    NR_KERNEL_STACK_KB,
297ba14a194SAndy Lutomirski 					    PAGE_SIZE / 1024 * account);
298ba14a194SAndy Lutomirski 		}
299ba14a194SAndy Lutomirski 
300ba14a194SAndy Lutomirski 		/* All stack pages belong to the same memcg. */
301ba14a194SAndy Lutomirski 		memcg_kmem_update_page_stat(vm->pages[0], MEMCG_KERNEL_STACK_KB,
302ba14a194SAndy Lutomirski 					    account * (THREAD_SIZE / 1024));
303ba14a194SAndy Lutomirski 	} else {
304ba14a194SAndy Lutomirski 		/*
305ba14a194SAndy Lutomirski 		 * All stack pages are in the same zone and belong to the
306ba14a194SAndy Lutomirski 		 * same memcg.
307ba14a194SAndy Lutomirski 		 */
308efdc9490SAndy Lutomirski 		struct page *first_page = virt_to_page(stack);
309c6a7f572SKOSAKI Motohiro 
310efdc9490SAndy Lutomirski 		mod_zone_page_state(page_zone(first_page), NR_KERNEL_STACK_KB,
311d30dd8beSAndy Lutomirski 				    THREAD_SIZE / 1024 * account);
312efdc9490SAndy Lutomirski 
313ba14a194SAndy Lutomirski 		memcg_kmem_update_page_stat(first_page, MEMCG_KERNEL_STACK_KB,
314efdc9490SAndy Lutomirski 					    account * (THREAD_SIZE / 1024));
315c6a7f572SKOSAKI Motohiro 	}
316ba14a194SAndy Lutomirski }
317c6a7f572SKOSAKI Motohiro 
31868f24b08SAndy Lutomirski static void release_task_stack(struct task_struct *tsk)
3191da177e4SLinus Torvalds {
320405c0759SAndy Lutomirski 	if (WARN_ON(tsk->state != TASK_DEAD))
321405c0759SAndy Lutomirski 		return;  /* Better to leak the stack than to free prematurely */
322405c0759SAndy Lutomirski 
323ba14a194SAndy Lutomirski 	account_kernel_stack(tsk, -1);
324b235beeaSLinus Torvalds 	arch_release_thread_stack(tsk->stack);
325ba14a194SAndy Lutomirski 	free_thread_stack(tsk);
32668f24b08SAndy Lutomirski 	tsk->stack = NULL;
32768f24b08SAndy Lutomirski #ifdef CONFIG_VMAP_STACK
32868f24b08SAndy Lutomirski 	tsk->stack_vm_area = NULL;
32968f24b08SAndy Lutomirski #endif
33068f24b08SAndy Lutomirski }
33168f24b08SAndy Lutomirski 
33268f24b08SAndy Lutomirski #ifdef CONFIG_THREAD_INFO_IN_TASK
33368f24b08SAndy Lutomirski void put_task_stack(struct task_struct *tsk)
33468f24b08SAndy Lutomirski {
33568f24b08SAndy Lutomirski 	if (atomic_dec_and_test(&tsk->stack_refcount))
33668f24b08SAndy Lutomirski 		release_task_stack(tsk);
33768f24b08SAndy Lutomirski }
33868f24b08SAndy Lutomirski #endif
33968f24b08SAndy Lutomirski 
34068f24b08SAndy Lutomirski void free_task(struct task_struct *tsk)
34168f24b08SAndy Lutomirski {
34268f24b08SAndy Lutomirski #ifndef CONFIG_THREAD_INFO_IN_TASK
34368f24b08SAndy Lutomirski 	/*
34468f24b08SAndy Lutomirski 	 * The task is finally done with both the stack and thread_info,
34568f24b08SAndy Lutomirski 	 * so free both.
34668f24b08SAndy Lutomirski 	 */
34768f24b08SAndy Lutomirski 	release_task_stack(tsk);
34868f24b08SAndy Lutomirski #else
34968f24b08SAndy Lutomirski 	/*
35068f24b08SAndy Lutomirski 	 * If the task had a separate stack allocation, it should be gone
35168f24b08SAndy Lutomirski 	 * by now.
35268f24b08SAndy Lutomirski 	 */
35368f24b08SAndy Lutomirski 	WARN_ON_ONCE(atomic_read(&tsk->stack_refcount) != 0);
35468f24b08SAndy Lutomirski #endif
35523f78d4aSIngo Molnar 	rt_mutex_debug_task_free(tsk);
356fb52607aSFrederic Weisbecker 	ftrace_graph_exit_task(tsk);
357e2cfabdfSWill Drewry 	put_seccomp_filter(tsk);
358f19b9f74SAkinobu Mita 	arch_release_task_struct(tsk);
3591da5c46fSOleg Nesterov 	if (tsk->flags & PF_KTHREAD)
3601da5c46fSOleg Nesterov 		free_kthread_struct(tsk);
3611da177e4SLinus Torvalds 	free_task_struct(tsk);
3621da177e4SLinus Torvalds }
3631da177e4SLinus Torvalds EXPORT_SYMBOL(free_task);
3641da177e4SLinus Torvalds 
365ea6d290cSOleg Nesterov static inline void free_signal_struct(struct signal_struct *sig)
366ea6d290cSOleg Nesterov {
36797101eb4SOleg Nesterov 	taskstats_tgid_free(sig);
3681c5354deSMike Galbraith 	sched_autogroup_exit(sig);
3697283094eSMichal Hocko 	/*
3707283094eSMichal Hocko 	 * __mmdrop is not safe to call from softirq context on x86 due to
3717283094eSMichal Hocko 	 * pgd_dtor so postpone it to the async context
3727283094eSMichal Hocko 	 */
37326db62f1SMichal Hocko 	if (sig->oom_mm)
3747283094eSMichal Hocko 		mmdrop_async(sig->oom_mm);
375ea6d290cSOleg Nesterov 	kmem_cache_free(signal_cachep, sig);
376ea6d290cSOleg Nesterov }
377ea6d290cSOleg Nesterov 
378ea6d290cSOleg Nesterov static inline void put_signal_struct(struct signal_struct *sig)
379ea6d290cSOleg Nesterov {
3801c5354deSMike Galbraith 	if (atomic_dec_and_test(&sig->sigcnt))
381ea6d290cSOleg Nesterov 		free_signal_struct(sig);
382ea6d290cSOleg Nesterov }
383ea6d290cSOleg Nesterov 
384158d9ebdSAndrew Morton void __put_task_struct(struct task_struct *tsk)
3851da177e4SLinus Torvalds {
386270f722dSEugene Teo 	WARN_ON(!tsk->exit_state);
3871da177e4SLinus Torvalds 	WARN_ON(atomic_read(&tsk->usage));
3881da177e4SLinus Torvalds 	WARN_ON(tsk == current);
3891da177e4SLinus Torvalds 
3902e91fa7fSTejun Heo 	cgroup_free(tsk);
391156654f4SMike Galbraith 	task_numa_free(tsk);
3921a2a4d06SKees Cook 	security_task_free(tsk);
393e0e81739SDavid Howells 	exit_creds(tsk);
39435df17c5SShailabh Nagar 	delayacct_tsk_free(tsk);
395ea6d290cSOleg Nesterov 	put_signal_struct(tsk->signal);
3961da177e4SLinus Torvalds 
3971da177e4SLinus Torvalds 	if (!profile_handoff_task(tsk))
3981da177e4SLinus Torvalds 		free_task(tsk);
3991da177e4SLinus Torvalds }
40077c100c8SRik van Riel EXPORT_SYMBOL_GPL(__put_task_struct);
4011da177e4SLinus Torvalds 
4026c0a9fa6SThomas Gleixner void __init __weak arch_task_cache_init(void) { }
40361c4628bSSuresh Siddha 
404ff691f6eSHeinrich Schuchardt /*
405ff691f6eSHeinrich Schuchardt  * set_max_threads
406ff691f6eSHeinrich Schuchardt  */
40716db3d3fSHeinrich Schuchardt static void set_max_threads(unsigned int max_threads_suggested)
408ff691f6eSHeinrich Schuchardt {
409ac1b398dSHeinrich Schuchardt 	u64 threads;
410ff691f6eSHeinrich Schuchardt 
411ff691f6eSHeinrich Schuchardt 	/*
412ac1b398dSHeinrich Schuchardt 	 * The number of threads shall be limited such that the thread
413ac1b398dSHeinrich Schuchardt 	 * structures may only consume a small part of the available memory.
414ff691f6eSHeinrich Schuchardt 	 */
415ac1b398dSHeinrich Schuchardt 	if (fls64(totalram_pages) + fls64(PAGE_SIZE) > 64)
416ac1b398dSHeinrich Schuchardt 		threads = MAX_THREADS;
417ac1b398dSHeinrich Schuchardt 	else
418ac1b398dSHeinrich Schuchardt 		threads = div64_u64((u64) totalram_pages * (u64) PAGE_SIZE,
419ac1b398dSHeinrich Schuchardt 				    (u64) THREAD_SIZE * 8UL);
420ac1b398dSHeinrich Schuchardt 
42116db3d3fSHeinrich Schuchardt 	if (threads > max_threads_suggested)
42216db3d3fSHeinrich Schuchardt 		threads = max_threads_suggested;
42316db3d3fSHeinrich Schuchardt 
424ac1b398dSHeinrich Schuchardt 	max_threads = clamp_t(u64, threads, MIN_THREADS, MAX_THREADS);
425ff691f6eSHeinrich Schuchardt }
426ff691f6eSHeinrich Schuchardt 
4275aaeb5c0SIngo Molnar #ifdef CONFIG_ARCH_WANTS_DYNAMIC_TASK_STRUCT
4285aaeb5c0SIngo Molnar /* Initialized by the architecture: */
4295aaeb5c0SIngo Molnar int arch_task_struct_size __read_mostly;
4305aaeb5c0SIngo Molnar #endif
4310c8c0f03SDave Hansen 
432ff691f6eSHeinrich Schuchardt void __init fork_init(void)
4331da177e4SLinus Torvalds {
43425f9c081SEric W. Biederman 	int i;
435f5e10287SThomas Gleixner #ifndef CONFIG_ARCH_TASK_STRUCT_ALLOCATOR
4361da177e4SLinus Torvalds #ifndef ARCH_MIN_TASKALIGN
437e274795eSPeter Zijlstra #define ARCH_MIN_TASKALIGN	0
4381da177e4SLinus Torvalds #endif
43995cb64c1SPeter Zijlstra 	int align = max_t(int, L1_CACHE_BYTES, ARCH_MIN_TASKALIGN);
440e274795eSPeter Zijlstra 
4411da177e4SLinus Torvalds 	/* create a slab on which task_structs can be allocated */
4425d097056SVladimir Davydov 	task_struct_cachep = kmem_cache_create("task_struct",
443e274795eSPeter Zijlstra 			arch_task_struct_size, align,
4445d097056SVladimir Davydov 			SLAB_PANIC|SLAB_NOTRACK|SLAB_ACCOUNT, NULL);
4451da177e4SLinus Torvalds #endif
4461da177e4SLinus Torvalds 
44761c4628bSSuresh Siddha 	/* do the arch specific task caches init */
44861c4628bSSuresh Siddha 	arch_task_cache_init();
44961c4628bSSuresh Siddha 
45016db3d3fSHeinrich Schuchardt 	set_max_threads(MAX_THREADS);
4511da177e4SLinus Torvalds 
4521da177e4SLinus Torvalds 	init_task.signal->rlim[RLIMIT_NPROC].rlim_cur = max_threads/2;
4531da177e4SLinus Torvalds 	init_task.signal->rlim[RLIMIT_NPROC].rlim_max = max_threads/2;
4541da177e4SLinus Torvalds 	init_task.signal->rlim[RLIMIT_SIGPENDING] =
4551da177e4SLinus Torvalds 		init_task.signal->rlim[RLIMIT_NPROC];
456b376c3e1SEric W. Biederman 
45725f9c081SEric W. Biederman 	for (i = 0; i < UCOUNT_COUNTS; i++) {
45825f9c081SEric W. Biederman 		init_user_ns.ucount_max[i] = max_threads/2;
45925f9c081SEric W. Biederman 	}
4601da177e4SLinus Torvalds }
4611da177e4SLinus Torvalds 
46252f5684cSGideon Israel Dsouza int __weak arch_dup_task_struct(struct task_struct *dst,
46361c4628bSSuresh Siddha 					       struct task_struct *src)
46461c4628bSSuresh Siddha {
46561c4628bSSuresh Siddha 	*dst = *src;
46661c4628bSSuresh Siddha 	return 0;
46761c4628bSSuresh Siddha }
46861c4628bSSuresh Siddha 
469d4311ff1SAaron Tomlin void set_task_stack_end_magic(struct task_struct *tsk)
470d4311ff1SAaron Tomlin {
471d4311ff1SAaron Tomlin 	unsigned long *stackend;
472d4311ff1SAaron Tomlin 
473d4311ff1SAaron Tomlin 	stackend = end_of_stack(tsk);
474d4311ff1SAaron Tomlin 	*stackend = STACK_END_MAGIC;	/* for overflow detection */
475d4311ff1SAaron Tomlin }
476d4311ff1SAaron Tomlin 
477725fc629SAndi Kleen static struct task_struct *dup_task_struct(struct task_struct *orig, int node)
4781da177e4SLinus Torvalds {
4791da177e4SLinus Torvalds 	struct task_struct *tsk;
480b235beeaSLinus Torvalds 	unsigned long *stack;
481ba14a194SAndy Lutomirski 	struct vm_struct *stack_vm_area;
4823e26c149SPeter Zijlstra 	int err;
4831da177e4SLinus Torvalds 
484725fc629SAndi Kleen 	if (node == NUMA_NO_NODE)
485725fc629SAndi Kleen 		node = tsk_fork_get_node(orig);
486504f52b5SEric Dumazet 	tsk = alloc_task_struct_node(node);
4871da177e4SLinus Torvalds 	if (!tsk)
4881da177e4SLinus Torvalds 		return NULL;
4891da177e4SLinus Torvalds 
490b235beeaSLinus Torvalds 	stack = alloc_thread_stack_node(tsk, node);
491b235beeaSLinus Torvalds 	if (!stack)
492f19b9f74SAkinobu Mita 		goto free_tsk;
4931da177e4SLinus Torvalds 
494ba14a194SAndy Lutomirski 	stack_vm_area = task_stack_vm_area(tsk);
495ba14a194SAndy Lutomirski 
49661c4628bSSuresh Siddha 	err = arch_dup_task_struct(tsk, orig);
497ba14a194SAndy Lutomirski 
498ba14a194SAndy Lutomirski 	/*
499ba14a194SAndy Lutomirski 	 * arch_dup_task_struct() clobbers the stack-related fields.  Make
500ba14a194SAndy Lutomirski 	 * sure they're properly initialized before using any stack-related
501ba14a194SAndy Lutomirski 	 * functions again.
502ba14a194SAndy Lutomirski 	 */
503ba14a194SAndy Lutomirski 	tsk->stack = stack;
504ba14a194SAndy Lutomirski #ifdef CONFIG_VMAP_STACK
505ba14a194SAndy Lutomirski 	tsk->stack_vm_area = stack_vm_area;
506ba14a194SAndy Lutomirski #endif
50768f24b08SAndy Lutomirski #ifdef CONFIG_THREAD_INFO_IN_TASK
50868f24b08SAndy Lutomirski 	atomic_set(&tsk->stack_refcount, 1);
50968f24b08SAndy Lutomirski #endif
510ba14a194SAndy Lutomirski 
51161c4628bSSuresh Siddha 	if (err)
512b235beeaSLinus Torvalds 		goto free_stack;
51361c4628bSSuresh Siddha 
514dbd95212SKees Cook #ifdef CONFIG_SECCOMP
515dbd95212SKees Cook 	/*
516dbd95212SKees Cook 	 * We must handle setting up seccomp filters once we're under
517dbd95212SKees Cook 	 * the sighand lock in case orig has changed between now and
518dbd95212SKees Cook 	 * then. Until then, filter must be NULL to avoid messing up
519dbd95212SKees Cook 	 * the usage counts on the error path calling free_task.
520dbd95212SKees Cook 	 */
521dbd95212SKees Cook 	tsk->seccomp.filter = NULL;
522dbd95212SKees Cook #endif
52387bec58aSAndrew Morton 
52487bec58aSAndrew Morton 	setup_thread_stack(tsk, orig);
5258e7cac79SAvi Kivity 	clear_user_return_notifier(tsk);
526f26f9affSMike Galbraith 	clear_tsk_need_resched(tsk);
527d4311ff1SAaron Tomlin 	set_task_stack_end_magic(tsk);
5281da177e4SLinus Torvalds 
5290a425405SArjan van de Ven #ifdef CONFIG_CC_STACKPROTECTOR
5300a425405SArjan van de Ven 	tsk->stack_canary = get_random_int();
5310a425405SArjan van de Ven #endif
5320a425405SArjan van de Ven 
533fb0a685cSDaniel Rebelo de Oliveira 	/*
534fb0a685cSDaniel Rebelo de Oliveira 	 * One for us, one for whoever does the "release_task()" (usually
535fb0a685cSDaniel Rebelo de Oliveira 	 * parent)
536fb0a685cSDaniel Rebelo de Oliveira 	 */
5371da177e4SLinus Torvalds 	atomic_set(&tsk->usage, 2);
5386c5c9341SAlexey Dobriyan #ifdef CONFIG_BLK_DEV_IO_TRACE
5392056a782SJens Axboe 	tsk->btrace_seq = 0;
5406c5c9341SAlexey Dobriyan #endif
541a0aa7f68SJens Axboe 	tsk->splice_pipe = NULL;
5425640f768SEric Dumazet 	tsk->task_frag.page = NULL;
543093e5840SSebastian Andrzej Siewior 	tsk->wake_q.next = NULL;
544c6a7f572SKOSAKI Motohiro 
545ba14a194SAndy Lutomirski 	account_kernel_stack(tsk, 1);
546c6a7f572SKOSAKI Motohiro 
5475c9a8750SDmitry Vyukov 	kcov_task_init(tsk);
5485c9a8750SDmitry Vyukov 
5491da177e4SLinus Torvalds 	return tsk;
55061c4628bSSuresh Siddha 
551b235beeaSLinus Torvalds free_stack:
552ba14a194SAndy Lutomirski 	free_thread_stack(tsk);
553f19b9f74SAkinobu Mita free_tsk:
55461c4628bSSuresh Siddha 	free_task_struct(tsk);
55561c4628bSSuresh Siddha 	return NULL;
5561da177e4SLinus Torvalds }
5571da177e4SLinus Torvalds 
5581da177e4SLinus Torvalds #ifdef CONFIG_MMU
5590766f788SEmese Revfy static __latent_entropy int dup_mmap(struct mm_struct *mm,
5600766f788SEmese Revfy 					struct mm_struct *oldmm)
5611da177e4SLinus Torvalds {
562297c5eeeSLinus Torvalds 	struct vm_area_struct *mpnt, *tmp, *prev, **pprev;
5631da177e4SLinus Torvalds 	struct rb_node **rb_link, *rb_parent;
5641da177e4SLinus Torvalds 	int retval;
5651da177e4SLinus Torvalds 	unsigned long charge;
566893e26e6SPavel Emelyanov 	LIST_HEAD(uf);
5671da177e4SLinus Torvalds 
56832cdba1eSOleg Nesterov 	uprobe_start_dup_mmap();
5697c051267SMichal Hocko 	if (down_write_killable(&oldmm->mmap_sem)) {
5707c051267SMichal Hocko 		retval = -EINTR;
5717c051267SMichal Hocko 		goto fail_uprobe_end;
5727c051267SMichal Hocko 	}
573ec8c0446SRalf Baechle 	flush_cache_dup_mm(oldmm);
574f8ac4ec9SOleg Nesterov 	uprobe_dup_mmap(oldmm, mm);
575ad339451SIngo Molnar 	/*
576ad339451SIngo Molnar 	 * Not linked in yet - no deadlock potential:
577ad339451SIngo Molnar 	 */
578ad339451SIngo Molnar 	down_write_nested(&mm->mmap_sem, SINGLE_DEPTH_NESTING);
5797ee78232SHugh Dickins 
58090f31d0eSKonstantin Khlebnikov 	/* No ordering required: file already has been exposed. */
58190f31d0eSKonstantin Khlebnikov 	RCU_INIT_POINTER(mm->exe_file, get_mm_exe_file(oldmm));
58290f31d0eSKonstantin Khlebnikov 
5834f7d4614SVladimir Davydov 	mm->total_vm = oldmm->total_vm;
58484638335SKonstantin Khlebnikov 	mm->data_vm = oldmm->data_vm;
5854f7d4614SVladimir Davydov 	mm->exec_vm = oldmm->exec_vm;
5864f7d4614SVladimir Davydov 	mm->stack_vm = oldmm->stack_vm;
5874f7d4614SVladimir Davydov 
5881da177e4SLinus Torvalds 	rb_link = &mm->mm_rb.rb_node;
5891da177e4SLinus Torvalds 	rb_parent = NULL;
5901da177e4SLinus Torvalds 	pprev = &mm->mmap;
591f8af4da3SHugh Dickins 	retval = ksm_fork(mm, oldmm);
592f8af4da3SHugh Dickins 	if (retval)
593f8af4da3SHugh Dickins 		goto out;
594ba76149fSAndrea Arcangeli 	retval = khugepaged_fork(mm, oldmm);
595ba76149fSAndrea Arcangeli 	if (retval)
596ba76149fSAndrea Arcangeli 		goto out;
5971da177e4SLinus Torvalds 
598297c5eeeSLinus Torvalds 	prev = NULL;
599fd3e42fcSHugh Dickins 	for (mpnt = oldmm->mmap; mpnt; mpnt = mpnt->vm_next) {
6001da177e4SLinus Torvalds 		struct file *file;
6011da177e4SLinus Torvalds 
6021da177e4SLinus Torvalds 		if (mpnt->vm_flags & VM_DONTCOPY) {
60384638335SKonstantin Khlebnikov 			vm_stat_account(mm, mpnt->vm_flags, -vma_pages(mpnt));
6041da177e4SLinus Torvalds 			continue;
6051da177e4SLinus Torvalds 		}
6061da177e4SLinus Torvalds 		charge = 0;
6071da177e4SLinus Torvalds 		if (mpnt->vm_flags & VM_ACCOUNT) {
608b2412b7fSHuang Shijie 			unsigned long len = vma_pages(mpnt);
609b2412b7fSHuang Shijie 
610191c5424SAl Viro 			if (security_vm_enough_memory_mm(oldmm, len)) /* sic */
6111da177e4SLinus Torvalds 				goto fail_nomem;
6121da177e4SLinus Torvalds 			charge = len;
6131da177e4SLinus Torvalds 		}
614e94b1766SChristoph Lameter 		tmp = kmem_cache_alloc(vm_area_cachep, GFP_KERNEL);
6151da177e4SLinus Torvalds 		if (!tmp)
6161da177e4SLinus Torvalds 			goto fail_nomem;
6171da177e4SLinus Torvalds 		*tmp = *mpnt;
6185beb4930SRik van Riel 		INIT_LIST_HEAD(&tmp->anon_vma_chain);
619ef0855d3SOleg Nesterov 		retval = vma_dup_policy(mpnt, tmp);
620ef0855d3SOleg Nesterov 		if (retval)
6211da177e4SLinus Torvalds 			goto fail_nomem_policy;
622a247c3a9SAndrea Arcangeli 		tmp->vm_mm = mm;
623893e26e6SPavel Emelyanov 		retval = dup_userfaultfd(tmp, &uf);
624893e26e6SPavel Emelyanov 		if (retval)
625893e26e6SPavel Emelyanov 			goto fail_nomem_anon_vma_fork;
6265beb4930SRik van Riel 		if (anon_vma_fork(tmp, mpnt))
6275beb4930SRik van Riel 			goto fail_nomem_anon_vma_fork;
628893e26e6SPavel Emelyanov 		tmp->vm_flags &= ~(VM_LOCKED | VM_LOCKONFAULT);
629297c5eeeSLinus Torvalds 		tmp->vm_next = tmp->vm_prev = NULL;
6301da177e4SLinus Torvalds 		file = tmp->vm_file;
6311da177e4SLinus Torvalds 		if (file) {
632496ad9aaSAl Viro 			struct inode *inode = file_inode(file);
633b88ed205SHugh Dickins 			struct address_space *mapping = file->f_mapping;
634b88ed205SHugh Dickins 
6351da177e4SLinus Torvalds 			get_file(file);
6361da177e4SLinus Torvalds 			if (tmp->vm_flags & VM_DENYWRITE)
6371da177e4SLinus Torvalds 				atomic_dec(&inode->i_writecount);
63883cde9e8SDavidlohr Bueso 			i_mmap_lock_write(mapping);
639b88ed205SHugh Dickins 			if (tmp->vm_flags & VM_SHARED)
6404bb5f5d9SDavid Herrmann 				atomic_inc(&mapping->i_mmap_writable);
641b88ed205SHugh Dickins 			flush_dcache_mmap_lock(mapping);
642b88ed205SHugh Dickins 			/* insert tmp into the share list, just after mpnt */
6439826a516SMichel Lespinasse 			vma_interval_tree_insert_after(tmp, mpnt,
6449826a516SMichel Lespinasse 					&mapping->i_mmap);
645b88ed205SHugh Dickins 			flush_dcache_mmap_unlock(mapping);
64683cde9e8SDavidlohr Bueso 			i_mmap_unlock_write(mapping);
6471da177e4SLinus Torvalds 		}
6481da177e4SLinus Torvalds 
6491da177e4SLinus Torvalds 		/*
650a1e78772SMel Gorman 		 * Clear hugetlb-related page reserves for children. This only
651a1e78772SMel Gorman 		 * affects MAP_PRIVATE mappings. Faults generated by the child
652a1e78772SMel Gorman 		 * are not guaranteed to succeed, even if read-only
653a1e78772SMel Gorman 		 */
654a1e78772SMel Gorman 		if (is_vm_hugetlb_page(tmp))
655a1e78772SMel Gorman 			reset_vma_resv_huge_pages(tmp);
656a1e78772SMel Gorman 
657a1e78772SMel Gorman 		/*
6587ee78232SHugh Dickins 		 * Link in the new vma and copy the page table entries.
6591da177e4SLinus Torvalds 		 */
6601da177e4SLinus Torvalds 		*pprev = tmp;
6611da177e4SLinus Torvalds 		pprev = &tmp->vm_next;
662297c5eeeSLinus Torvalds 		tmp->vm_prev = prev;
663297c5eeeSLinus Torvalds 		prev = tmp;
6641da177e4SLinus Torvalds 
6651da177e4SLinus Torvalds 		__vma_link_rb(mm, tmp, rb_link, rb_parent);
6661da177e4SLinus Torvalds 		rb_link = &tmp->vm_rb.rb_right;
6671da177e4SLinus Torvalds 		rb_parent = &tmp->vm_rb;
6681da177e4SLinus Torvalds 
6691da177e4SLinus Torvalds 		mm->map_count++;
6700b0db14cSHugh Dickins 		retval = copy_page_range(mm, oldmm, mpnt);
6711da177e4SLinus Torvalds 
6721da177e4SLinus Torvalds 		if (tmp->vm_ops && tmp->vm_ops->open)
6731da177e4SLinus Torvalds 			tmp->vm_ops->open(tmp);
6741da177e4SLinus Torvalds 
6751da177e4SLinus Torvalds 		if (retval)
6761da177e4SLinus Torvalds 			goto out;
6771da177e4SLinus Torvalds 	}
678d6dd61c8SJeremy Fitzhardinge 	/* a new mm has just been created */
679d6dd61c8SJeremy Fitzhardinge 	arch_dup_mmap(oldmm, mm);
6801da177e4SLinus Torvalds 	retval = 0;
6811da177e4SLinus Torvalds out:
6827ee78232SHugh Dickins 	up_write(&mm->mmap_sem);
683fd3e42fcSHugh Dickins 	flush_tlb_mm(oldmm);
6841da177e4SLinus Torvalds 	up_write(&oldmm->mmap_sem);
685893e26e6SPavel Emelyanov 	dup_userfaultfd_complete(&uf);
6867c051267SMichal Hocko fail_uprobe_end:
68732cdba1eSOleg Nesterov 	uprobe_end_dup_mmap();
6881da177e4SLinus Torvalds 	return retval;
6895beb4930SRik van Riel fail_nomem_anon_vma_fork:
690ef0855d3SOleg Nesterov 	mpol_put(vma_policy(tmp));
6911da177e4SLinus Torvalds fail_nomem_policy:
6921da177e4SLinus Torvalds 	kmem_cache_free(vm_area_cachep, tmp);
6931da177e4SLinus Torvalds fail_nomem:
6941da177e4SLinus Torvalds 	retval = -ENOMEM;
6951da177e4SLinus Torvalds 	vm_unacct_memory(charge);
6961da177e4SLinus Torvalds 	goto out;
6971da177e4SLinus Torvalds }
6981da177e4SLinus Torvalds 
6991da177e4SLinus Torvalds static inline int mm_alloc_pgd(struct mm_struct *mm)
7001da177e4SLinus Torvalds {
7011da177e4SLinus Torvalds 	mm->pgd = pgd_alloc(mm);
7021da177e4SLinus Torvalds 	if (unlikely(!mm->pgd))
7031da177e4SLinus Torvalds 		return -ENOMEM;
7041da177e4SLinus Torvalds 	return 0;
7051da177e4SLinus Torvalds }
7061da177e4SLinus Torvalds 
7071da177e4SLinus Torvalds static inline void mm_free_pgd(struct mm_struct *mm)
7081da177e4SLinus Torvalds {
7095e541973SBenjamin Herrenschmidt 	pgd_free(mm, mm->pgd);
7101da177e4SLinus Torvalds }
7111da177e4SLinus Torvalds #else
71290f31d0eSKonstantin Khlebnikov static int dup_mmap(struct mm_struct *mm, struct mm_struct *oldmm)
71390f31d0eSKonstantin Khlebnikov {
71490f31d0eSKonstantin Khlebnikov 	down_write(&oldmm->mmap_sem);
71590f31d0eSKonstantin Khlebnikov 	RCU_INIT_POINTER(mm->exe_file, get_mm_exe_file(oldmm));
71690f31d0eSKonstantin Khlebnikov 	up_write(&oldmm->mmap_sem);
71790f31d0eSKonstantin Khlebnikov 	return 0;
71890f31d0eSKonstantin Khlebnikov }
7191da177e4SLinus Torvalds #define mm_alloc_pgd(mm)	(0)
7201da177e4SLinus Torvalds #define mm_free_pgd(mm)
7211da177e4SLinus Torvalds #endif /* CONFIG_MMU */
7221da177e4SLinus Torvalds 
7231da177e4SLinus Torvalds __cacheline_aligned_in_smp DEFINE_SPINLOCK(mmlist_lock);
7241da177e4SLinus Torvalds 
725e94b1766SChristoph Lameter #define allocate_mm()	(kmem_cache_alloc(mm_cachep, GFP_KERNEL))
7261da177e4SLinus Torvalds #define free_mm(mm)	(kmem_cache_free(mm_cachep, (mm)))
7271da177e4SLinus Torvalds 
7284cb0e11bSHidehiro Kawai static unsigned long default_dump_filter = MMF_DUMP_FILTER_DEFAULT;
7294cb0e11bSHidehiro Kawai 
7304cb0e11bSHidehiro Kawai static int __init coredump_filter_setup(char *s)
7314cb0e11bSHidehiro Kawai {
7324cb0e11bSHidehiro Kawai 	default_dump_filter =
7334cb0e11bSHidehiro Kawai 		(simple_strtoul(s, NULL, 0) << MMF_DUMP_FILTER_SHIFT) &
7344cb0e11bSHidehiro Kawai 		MMF_DUMP_FILTER_MASK;
7354cb0e11bSHidehiro Kawai 	return 1;
7364cb0e11bSHidehiro Kawai }
7374cb0e11bSHidehiro Kawai 
7384cb0e11bSHidehiro Kawai __setup("coredump_filter=", coredump_filter_setup);
7394cb0e11bSHidehiro Kawai 
7401da177e4SLinus Torvalds #include <linux/init_task.h>
7411da177e4SLinus Torvalds 
742858f0993SAlexey Dobriyan static void mm_init_aio(struct mm_struct *mm)
743858f0993SAlexey Dobriyan {
744858f0993SAlexey Dobriyan #ifdef CONFIG_AIO
745858f0993SAlexey Dobriyan 	spin_lock_init(&mm->ioctx_lock);
746db446a08SBenjamin LaHaise 	mm->ioctx_table = NULL;
747858f0993SAlexey Dobriyan #endif
748858f0993SAlexey Dobriyan }
749858f0993SAlexey Dobriyan 
75033144e84SVladimir Davydov static void mm_init_owner(struct mm_struct *mm, struct task_struct *p)
75133144e84SVladimir Davydov {
75233144e84SVladimir Davydov #ifdef CONFIG_MEMCG
75333144e84SVladimir Davydov 	mm->owner = p;
75433144e84SVladimir Davydov #endif
75533144e84SVladimir Davydov }
75633144e84SVladimir Davydov 
757bfedb589SEric W. Biederman static struct mm_struct *mm_init(struct mm_struct *mm, struct task_struct *p,
758bfedb589SEric W. Biederman 	struct user_namespace *user_ns)
7591da177e4SLinus Torvalds {
76041f727fdSVladimir Davydov 	mm->mmap = NULL;
76141f727fdSVladimir Davydov 	mm->mm_rb = RB_ROOT;
76241f727fdSVladimir Davydov 	mm->vmacache_seqnum = 0;
7631da177e4SLinus Torvalds 	atomic_set(&mm->mm_users, 1);
7641da177e4SLinus Torvalds 	atomic_set(&mm->mm_count, 1);
7651da177e4SLinus Torvalds 	init_rwsem(&mm->mmap_sem);
7661da177e4SLinus Torvalds 	INIT_LIST_HEAD(&mm->mmlist);
767999d9fc1SOleg Nesterov 	mm->core_state = NULL;
768e1f56c89SKirill A. Shutemov 	atomic_long_set(&mm->nr_ptes, 0);
7692d2f5119SKirill A. Shutemov 	mm_nr_pmds_init(mm);
77041f727fdSVladimir Davydov 	mm->map_count = 0;
77141f727fdSVladimir Davydov 	mm->locked_vm = 0;
772ce65cefaSVladimir Davydov 	mm->pinned_vm = 0;
773d559db08SKAMEZAWA Hiroyuki 	memset(&mm->rss_stat, 0, sizeof(mm->rss_stat));
7741da177e4SLinus Torvalds 	spin_lock_init(&mm->page_table_lock);
77541f727fdSVladimir Davydov 	mm_init_cpumask(mm);
776858f0993SAlexey Dobriyan 	mm_init_aio(mm);
777cf475ad2SBalbir Singh 	mm_init_owner(mm, p);
77841f727fdSVladimir Davydov 	mmu_notifier_mm_init(mm);
77920841405SRik van Riel 	clear_tlb_flush_pending(mm);
78041f727fdSVladimir Davydov #if defined(CONFIG_TRANSPARENT_HUGEPAGE) && !USE_SPLIT_PMD_PTLOCKS
78141f727fdSVladimir Davydov 	mm->pmd_huge_pte = NULL;
78241f727fdSVladimir Davydov #endif
7831da177e4SLinus Torvalds 
784a0715cc2SAlex Thorlton 	if (current->mm) {
785a0715cc2SAlex Thorlton 		mm->flags = current->mm->flags & MMF_INIT_MASK;
786a0715cc2SAlex Thorlton 		mm->def_flags = current->mm->def_flags & VM_INIT_DEF_MASK;
787a0715cc2SAlex Thorlton 	} else {
788a0715cc2SAlex Thorlton 		mm->flags = default_dump_filter;
7891da177e4SLinus Torvalds 		mm->def_flags = 0;
790a0715cc2SAlex Thorlton 	}
791a0715cc2SAlex Thorlton 
79241f727fdSVladimir Davydov 	if (mm_alloc_pgd(mm))
79341f727fdSVladimir Davydov 		goto fail_nopgd;
79478fb7466SPavel Emelianov 
79541f727fdSVladimir Davydov 	if (init_new_context(p, mm))
79641f727fdSVladimir Davydov 		goto fail_nocontext;
79741f727fdSVladimir Davydov 
798bfedb589SEric W. Biederman 	mm->user_ns = get_user_ns(user_ns);
79941f727fdSVladimir Davydov 	return mm;
80041f727fdSVladimir Davydov 
80141f727fdSVladimir Davydov fail_nocontext:
80241f727fdSVladimir Davydov 	mm_free_pgd(mm);
80341f727fdSVladimir Davydov fail_nopgd:
8041da177e4SLinus Torvalds 	free_mm(mm);
8051da177e4SLinus Torvalds 	return NULL;
8061da177e4SLinus Torvalds }
8071da177e4SLinus Torvalds 
808c3f0327fSKonstantin Khlebnikov static void check_mm(struct mm_struct *mm)
809c3f0327fSKonstantin Khlebnikov {
810c3f0327fSKonstantin Khlebnikov 	int i;
811c3f0327fSKonstantin Khlebnikov 
812c3f0327fSKonstantin Khlebnikov 	for (i = 0; i < NR_MM_COUNTERS; i++) {
813c3f0327fSKonstantin Khlebnikov 		long x = atomic_long_read(&mm->rss_stat.count[i]);
814c3f0327fSKonstantin Khlebnikov 
815c3f0327fSKonstantin Khlebnikov 		if (unlikely(x))
816c3f0327fSKonstantin Khlebnikov 			printk(KERN_ALERT "BUG: Bad rss-counter state "
817c3f0327fSKonstantin Khlebnikov 					  "mm:%p idx:%d val:%ld\n", mm, i, x);
818c3f0327fSKonstantin Khlebnikov 	}
819b30fe6c7SKirill A. Shutemov 
820b30fe6c7SKirill A. Shutemov 	if (atomic_long_read(&mm->nr_ptes))
821b30fe6c7SKirill A. Shutemov 		pr_alert("BUG: non-zero nr_ptes on freeing mm: %ld\n",
822b30fe6c7SKirill A. Shutemov 				atomic_long_read(&mm->nr_ptes));
823b30fe6c7SKirill A. Shutemov 	if (mm_nr_pmds(mm))
824b30fe6c7SKirill A. Shutemov 		pr_alert("BUG: non-zero nr_pmds on freeing mm: %ld\n",
825b30fe6c7SKirill A. Shutemov 				mm_nr_pmds(mm));
826b30fe6c7SKirill A. Shutemov 
827e009bb30SKirill A. Shutemov #if defined(CONFIG_TRANSPARENT_HUGEPAGE) && !USE_SPLIT_PMD_PTLOCKS
82896dad67fSSasha Levin 	VM_BUG_ON_MM(mm->pmd_huge_pte, mm);
829c3f0327fSKonstantin Khlebnikov #endif
830c3f0327fSKonstantin Khlebnikov }
831c3f0327fSKonstantin Khlebnikov 
8321da177e4SLinus Torvalds /*
8331da177e4SLinus Torvalds  * Allocate and initialize an mm_struct.
8341da177e4SLinus Torvalds  */
8351da177e4SLinus Torvalds struct mm_struct *mm_alloc(void)
8361da177e4SLinus Torvalds {
8371da177e4SLinus Torvalds 	struct mm_struct *mm;
8381da177e4SLinus Torvalds 
8391da177e4SLinus Torvalds 	mm = allocate_mm();
840de03c72cSKOSAKI Motohiro 	if (!mm)
841de03c72cSKOSAKI Motohiro 		return NULL;
842de03c72cSKOSAKI Motohiro 
8431da177e4SLinus Torvalds 	memset(mm, 0, sizeof(*mm));
844bfedb589SEric W. Biederman 	return mm_init(mm, current, current_user_ns());
8451da177e4SLinus Torvalds }
8461da177e4SLinus Torvalds 
8471da177e4SLinus Torvalds /*
8481da177e4SLinus Torvalds  * Called when the last reference to the mm
8491da177e4SLinus Torvalds  * is dropped: either by a lazy thread or by
8501da177e4SLinus Torvalds  * mmput. Free the page directory and the mm.
8511da177e4SLinus Torvalds  */
8527ad5b3a5SHarvey Harrison void __mmdrop(struct mm_struct *mm)
8531da177e4SLinus Torvalds {
8541da177e4SLinus Torvalds 	BUG_ON(mm == &init_mm);
8551da177e4SLinus Torvalds 	mm_free_pgd(mm);
8561da177e4SLinus Torvalds 	destroy_context(mm);
857cddb8a5cSAndrea Arcangeli 	mmu_notifier_mm_destroy(mm);
858c3f0327fSKonstantin Khlebnikov 	check_mm(mm);
859bfedb589SEric W. Biederman 	put_user_ns(mm->user_ns);
8601da177e4SLinus Torvalds 	free_mm(mm);
8611da177e4SLinus Torvalds }
8626d4e4c4fSAvi Kivity EXPORT_SYMBOL_GPL(__mmdrop);
8631da177e4SLinus Torvalds 
864ec8d7c14SMichal Hocko static inline void __mmput(struct mm_struct *mm)
8651da177e4SLinus Torvalds {
866ec8d7c14SMichal Hocko 	VM_BUG_ON(atomic_read(&mm->mm_users));
8670ae26f1bSAndrew Morton 
868d4b3b638SSrikar Dronamraju 	uprobe_clear_state(mm);
8691da177e4SLinus Torvalds 	exit_aio(mm);
8701c2fb7a4SAndrea Arcangeli 	ksm_exit(mm);
871ba76149fSAndrea Arcangeli 	khugepaged_exit(mm); /* must run before exit_mmap */
8721da177e4SLinus Torvalds 	exit_mmap(mm);
8736fcb52a5SAaron Lu 	mm_put_huge_zero_page(mm);
874925d1c40SMatt Helsley 	set_mm_exe_file(mm, NULL);
8751da177e4SLinus Torvalds 	if (!list_empty(&mm->mmlist)) {
8761da177e4SLinus Torvalds 		spin_lock(&mmlist_lock);
8771da177e4SLinus Torvalds 		list_del(&mm->mmlist);
8781da177e4SLinus Torvalds 		spin_unlock(&mmlist_lock);
8791da177e4SLinus Torvalds 	}
880801460d0SHiroshi Shimamoto 	if (mm->binfmt)
881801460d0SHiroshi Shimamoto 		module_put(mm->binfmt->module);
882862e3073SMichal Hocko 	set_bit(MMF_OOM_SKIP, &mm->flags);
8831da177e4SLinus Torvalds 	mmdrop(mm);
8841da177e4SLinus Torvalds }
885ec8d7c14SMichal Hocko 
886ec8d7c14SMichal Hocko /*
887ec8d7c14SMichal Hocko  * Decrement the use count and release all resources for an mm.
888ec8d7c14SMichal Hocko  */
889ec8d7c14SMichal Hocko void mmput(struct mm_struct *mm)
890ec8d7c14SMichal Hocko {
891ec8d7c14SMichal Hocko 	might_sleep();
892ec8d7c14SMichal Hocko 
893ec8d7c14SMichal Hocko 	if (atomic_dec_and_test(&mm->mm_users))
894ec8d7c14SMichal Hocko 		__mmput(mm);
8951da177e4SLinus Torvalds }
8961da177e4SLinus Torvalds EXPORT_SYMBOL_GPL(mmput);
8971da177e4SLinus Torvalds 
8987ef949d7SMichal Hocko #ifdef CONFIG_MMU
899ec8d7c14SMichal Hocko static void mmput_async_fn(struct work_struct *work)
900ec8d7c14SMichal Hocko {
901ec8d7c14SMichal Hocko 	struct mm_struct *mm = container_of(work, struct mm_struct, async_put_work);
902ec8d7c14SMichal Hocko 	__mmput(mm);
903ec8d7c14SMichal Hocko }
904ec8d7c14SMichal Hocko 
905ec8d7c14SMichal Hocko void mmput_async(struct mm_struct *mm)
906ec8d7c14SMichal Hocko {
907ec8d7c14SMichal Hocko 	if (atomic_dec_and_test(&mm->mm_users)) {
908ec8d7c14SMichal Hocko 		INIT_WORK(&mm->async_put_work, mmput_async_fn);
909ec8d7c14SMichal Hocko 		schedule_work(&mm->async_put_work);
910ec8d7c14SMichal Hocko 	}
911ec8d7c14SMichal Hocko }
9127ef949d7SMichal Hocko #endif
913ec8d7c14SMichal Hocko 
91490f31d0eSKonstantin Khlebnikov /**
91590f31d0eSKonstantin Khlebnikov  * set_mm_exe_file - change a reference to the mm's executable file
91690f31d0eSKonstantin Khlebnikov  *
91790f31d0eSKonstantin Khlebnikov  * This changes mm's executable file (shown as symlink /proc/[pid]/exe).
91890f31d0eSKonstantin Khlebnikov  *
9196e399cd1SDavidlohr Bueso  * Main users are mmput() and sys_execve(). Callers prevent concurrent
9206e399cd1SDavidlohr Bueso  * invocations: in mmput() nobody alive left, in execve task is single
9216e399cd1SDavidlohr Bueso  * threaded. sys_prctl(PR_SET_MM_MAP/EXE_FILE) also needs to set the
9226e399cd1SDavidlohr Bueso  * mm->exe_file, but does so without using set_mm_exe_file() in order
9236e399cd1SDavidlohr Bueso  * to do avoid the need for any locks.
92490f31d0eSKonstantin Khlebnikov  */
92538646013SJiri Slaby void set_mm_exe_file(struct mm_struct *mm, struct file *new_exe_file)
92638646013SJiri Slaby {
9276e399cd1SDavidlohr Bueso 	struct file *old_exe_file;
9286e399cd1SDavidlohr Bueso 
9296e399cd1SDavidlohr Bueso 	/*
9306e399cd1SDavidlohr Bueso 	 * It is safe to dereference the exe_file without RCU as
9316e399cd1SDavidlohr Bueso 	 * this function is only called if nobody else can access
9326e399cd1SDavidlohr Bueso 	 * this mm -- see comment above for justification.
9336e399cd1SDavidlohr Bueso 	 */
9346e399cd1SDavidlohr Bueso 	old_exe_file = rcu_dereference_raw(mm->exe_file);
93590f31d0eSKonstantin Khlebnikov 
93638646013SJiri Slaby 	if (new_exe_file)
93738646013SJiri Slaby 		get_file(new_exe_file);
93890f31d0eSKonstantin Khlebnikov 	rcu_assign_pointer(mm->exe_file, new_exe_file);
93990f31d0eSKonstantin Khlebnikov 	if (old_exe_file)
94090f31d0eSKonstantin Khlebnikov 		fput(old_exe_file);
94138646013SJiri Slaby }
94238646013SJiri Slaby 
94390f31d0eSKonstantin Khlebnikov /**
94490f31d0eSKonstantin Khlebnikov  * get_mm_exe_file - acquire a reference to the mm's executable file
94590f31d0eSKonstantin Khlebnikov  *
94690f31d0eSKonstantin Khlebnikov  * Returns %NULL if mm has no associated executable file.
94790f31d0eSKonstantin Khlebnikov  * User must release file via fput().
94890f31d0eSKonstantin Khlebnikov  */
94938646013SJiri Slaby struct file *get_mm_exe_file(struct mm_struct *mm)
95038646013SJiri Slaby {
95138646013SJiri Slaby 	struct file *exe_file;
95238646013SJiri Slaby 
95390f31d0eSKonstantin Khlebnikov 	rcu_read_lock();
95490f31d0eSKonstantin Khlebnikov 	exe_file = rcu_dereference(mm->exe_file);
95590f31d0eSKonstantin Khlebnikov 	if (exe_file && !get_file_rcu(exe_file))
95690f31d0eSKonstantin Khlebnikov 		exe_file = NULL;
95790f31d0eSKonstantin Khlebnikov 	rcu_read_unlock();
95838646013SJiri Slaby 	return exe_file;
95938646013SJiri Slaby }
96011163348SDavidlohr Bueso EXPORT_SYMBOL(get_mm_exe_file);
96138646013SJiri Slaby 
9621da177e4SLinus Torvalds /**
963cd81a917SMateusz Guzik  * get_task_exe_file - acquire a reference to the task's executable file
964cd81a917SMateusz Guzik  *
965cd81a917SMateusz Guzik  * Returns %NULL if task's mm (if any) has no associated executable file or
966cd81a917SMateusz Guzik  * this is a kernel thread with borrowed mm (see the comment above get_task_mm).
967cd81a917SMateusz Guzik  * User must release file via fput().
968cd81a917SMateusz Guzik  */
969cd81a917SMateusz Guzik struct file *get_task_exe_file(struct task_struct *task)
970cd81a917SMateusz Guzik {
971cd81a917SMateusz Guzik 	struct file *exe_file = NULL;
972cd81a917SMateusz Guzik 	struct mm_struct *mm;
973cd81a917SMateusz Guzik 
974cd81a917SMateusz Guzik 	task_lock(task);
975cd81a917SMateusz Guzik 	mm = task->mm;
976cd81a917SMateusz Guzik 	if (mm) {
977cd81a917SMateusz Guzik 		if (!(task->flags & PF_KTHREAD))
978cd81a917SMateusz Guzik 			exe_file = get_mm_exe_file(mm);
979cd81a917SMateusz Guzik 	}
980cd81a917SMateusz Guzik 	task_unlock(task);
981cd81a917SMateusz Guzik 	return exe_file;
982cd81a917SMateusz Guzik }
983cd81a917SMateusz Guzik EXPORT_SYMBOL(get_task_exe_file);
984cd81a917SMateusz Guzik 
985cd81a917SMateusz Guzik /**
9861da177e4SLinus Torvalds  * get_task_mm - acquire a reference to the task's mm
9871da177e4SLinus Torvalds  *
988246bb0b1SOleg Nesterov  * Returns %NULL if the task has no mm.  Checks PF_KTHREAD (meaning
9891da177e4SLinus Torvalds  * this kernel workthread has transiently adopted a user mm with use_mm,
9901da177e4SLinus Torvalds  * to do its AIO) is not set and if so returns a reference to it, after
9911da177e4SLinus Torvalds  * bumping up the use count.  User must release the mm via mmput()
9921da177e4SLinus Torvalds  * after use.  Typically used by /proc and ptrace.
9931da177e4SLinus Torvalds  */
9941da177e4SLinus Torvalds struct mm_struct *get_task_mm(struct task_struct *task)
9951da177e4SLinus Torvalds {
9961da177e4SLinus Torvalds 	struct mm_struct *mm;
9971da177e4SLinus Torvalds 
9981da177e4SLinus Torvalds 	task_lock(task);
9991da177e4SLinus Torvalds 	mm = task->mm;
10001da177e4SLinus Torvalds 	if (mm) {
1001246bb0b1SOleg Nesterov 		if (task->flags & PF_KTHREAD)
10021da177e4SLinus Torvalds 			mm = NULL;
10031da177e4SLinus Torvalds 		else
10043fce371bSVegard Nossum 			mmget(mm);
10051da177e4SLinus Torvalds 	}
10061da177e4SLinus Torvalds 	task_unlock(task);
10071da177e4SLinus Torvalds 	return mm;
10081da177e4SLinus Torvalds }
10091da177e4SLinus Torvalds EXPORT_SYMBOL_GPL(get_task_mm);
10101da177e4SLinus Torvalds 
10118cdb878dSChristopher Yeoh struct mm_struct *mm_access(struct task_struct *task, unsigned int mode)
10128cdb878dSChristopher Yeoh {
10138cdb878dSChristopher Yeoh 	struct mm_struct *mm;
10148cdb878dSChristopher Yeoh 	int err;
10158cdb878dSChristopher Yeoh 
10168cdb878dSChristopher Yeoh 	err =  mutex_lock_killable(&task->signal->cred_guard_mutex);
10178cdb878dSChristopher Yeoh 	if (err)
10188cdb878dSChristopher Yeoh 		return ERR_PTR(err);
10198cdb878dSChristopher Yeoh 
10208cdb878dSChristopher Yeoh 	mm = get_task_mm(task);
10218cdb878dSChristopher Yeoh 	if (mm && mm != current->mm &&
10228cdb878dSChristopher Yeoh 			!ptrace_may_access(task, mode)) {
10238cdb878dSChristopher Yeoh 		mmput(mm);
10248cdb878dSChristopher Yeoh 		mm = ERR_PTR(-EACCES);
10258cdb878dSChristopher Yeoh 	}
10268cdb878dSChristopher Yeoh 	mutex_unlock(&task->signal->cred_guard_mutex);
10278cdb878dSChristopher Yeoh 
10288cdb878dSChristopher Yeoh 	return mm;
10298cdb878dSChristopher Yeoh }
10308cdb878dSChristopher Yeoh 
103157b59c4aSOleg Nesterov static void complete_vfork_done(struct task_struct *tsk)
1032c415c3b4SOleg Nesterov {
1033d68b46feSOleg Nesterov 	struct completion *vfork;
1034c415c3b4SOleg Nesterov 
1035d68b46feSOleg Nesterov 	task_lock(tsk);
1036d68b46feSOleg Nesterov 	vfork = tsk->vfork_done;
1037d68b46feSOleg Nesterov 	if (likely(vfork)) {
1038c415c3b4SOleg Nesterov 		tsk->vfork_done = NULL;
1039d68b46feSOleg Nesterov 		complete(vfork);
1040d68b46feSOleg Nesterov 	}
1041d68b46feSOleg Nesterov 	task_unlock(tsk);
1042d68b46feSOleg Nesterov }
1043d68b46feSOleg Nesterov 
1044d68b46feSOleg Nesterov static int wait_for_vfork_done(struct task_struct *child,
1045d68b46feSOleg Nesterov 				struct completion *vfork)
1046d68b46feSOleg Nesterov {
1047d68b46feSOleg Nesterov 	int killed;
1048d68b46feSOleg Nesterov 
1049d68b46feSOleg Nesterov 	freezer_do_not_count();
1050d68b46feSOleg Nesterov 	killed = wait_for_completion_killable(vfork);
1051d68b46feSOleg Nesterov 	freezer_count();
1052d68b46feSOleg Nesterov 
1053d68b46feSOleg Nesterov 	if (killed) {
1054d68b46feSOleg Nesterov 		task_lock(child);
1055d68b46feSOleg Nesterov 		child->vfork_done = NULL;
1056d68b46feSOleg Nesterov 		task_unlock(child);
1057d68b46feSOleg Nesterov 	}
1058d68b46feSOleg Nesterov 
1059d68b46feSOleg Nesterov 	put_task_struct(child);
1060d68b46feSOleg Nesterov 	return killed;
1061c415c3b4SOleg Nesterov }
1062c415c3b4SOleg Nesterov 
10631da177e4SLinus Torvalds /* Please note the differences between mmput and mm_release.
10641da177e4SLinus Torvalds  * mmput is called whenever we stop holding onto a mm_struct,
10651da177e4SLinus Torvalds  * error success whatever.
10661da177e4SLinus Torvalds  *
10671da177e4SLinus Torvalds  * mm_release is called after a mm_struct has been removed
10681da177e4SLinus Torvalds  * from the current process.
10691da177e4SLinus Torvalds  *
10701da177e4SLinus Torvalds  * This difference is important for error handling, when we
10711da177e4SLinus Torvalds  * only half set up a mm_struct for a new process and need to restore
10721da177e4SLinus Torvalds  * the old one.  Because we mmput the new mm_struct before
10731da177e4SLinus Torvalds  * restoring the old one. . .
10741da177e4SLinus Torvalds  * Eric Biederman 10 January 1998
10751da177e4SLinus Torvalds  */
10761da177e4SLinus Torvalds void mm_release(struct task_struct *tsk, struct mm_struct *mm)
10771da177e4SLinus Torvalds {
10788141c7f3SLinus Torvalds 	/* Get rid of any futexes when releasing the mm */
10798141c7f3SLinus Torvalds #ifdef CONFIG_FUTEX
1080fc6b177dSPeter Zijlstra 	if (unlikely(tsk->robust_list)) {
10818141c7f3SLinus Torvalds 		exit_robust_list(tsk);
1082fc6b177dSPeter Zijlstra 		tsk->robust_list = NULL;
1083fc6b177dSPeter Zijlstra 	}
10848141c7f3SLinus Torvalds #ifdef CONFIG_COMPAT
1085fc6b177dSPeter Zijlstra 	if (unlikely(tsk->compat_robust_list)) {
10868141c7f3SLinus Torvalds 		compat_exit_robust_list(tsk);
1087fc6b177dSPeter Zijlstra 		tsk->compat_robust_list = NULL;
1088fc6b177dSPeter Zijlstra 	}
10898141c7f3SLinus Torvalds #endif
1090322a2c10SThomas Gleixner 	if (unlikely(!list_empty(&tsk->pi_state_list)))
1091322a2c10SThomas Gleixner 		exit_pi_state_list(tsk);
10928141c7f3SLinus Torvalds #endif
10938141c7f3SLinus Torvalds 
10940326f5a9SSrikar Dronamraju 	uprobe_free_utask(tsk);
10950326f5a9SSrikar Dronamraju 
10961da177e4SLinus Torvalds 	/* Get rid of any cached register state */
10971da177e4SLinus Torvalds 	deactivate_mm(tsk, mm);
10981da177e4SLinus Torvalds 
1099fec1d011SRoland McGrath 	/*
1100735f2770SMichal Hocko 	 * Signal userspace if we're not exiting with a core dump
1101735f2770SMichal Hocko 	 * because we want to leave the value intact for debugging
1102735f2770SMichal Hocko 	 * purposes.
1103fec1d011SRoland McGrath 	 */
11049c8a8228SEric Dumazet 	if (tsk->clear_child_tid) {
1105735f2770SMichal Hocko 		if (!(tsk->signal->flags & SIGNAL_GROUP_COREDUMP) &&
11069c8a8228SEric Dumazet 		    atomic_read(&mm->mm_users) > 1) {
11071da177e4SLinus Torvalds 			/*
11081da177e4SLinus Torvalds 			 * We don't check the error code - if userspace has
11091da177e4SLinus Torvalds 			 * not set up a proper pointer then tough luck.
11101da177e4SLinus Torvalds 			 */
11119c8a8228SEric Dumazet 			put_user(0, tsk->clear_child_tid);
11129c8a8228SEric Dumazet 			sys_futex(tsk->clear_child_tid, FUTEX_WAKE,
11139c8a8228SEric Dumazet 					1, NULL, NULL, 0);
11149c8a8228SEric Dumazet 		}
11159c8a8228SEric Dumazet 		tsk->clear_child_tid = NULL;
11161da177e4SLinus Torvalds 	}
1117f7505d64SKonstantin Khlebnikov 
1118f7505d64SKonstantin Khlebnikov 	/*
1119f7505d64SKonstantin Khlebnikov 	 * All done, finally we can wake up parent and return this mm to him.
1120f7505d64SKonstantin Khlebnikov 	 * Also kthread_stop() uses this completion for synchronization.
1121f7505d64SKonstantin Khlebnikov 	 */
1122f7505d64SKonstantin Khlebnikov 	if (tsk->vfork_done)
1123f7505d64SKonstantin Khlebnikov 		complete_vfork_done(tsk);
11241da177e4SLinus Torvalds }
11251da177e4SLinus Torvalds 
1126a0a7ec30SJANAK DESAI /*
1127a0a7ec30SJANAK DESAI  * Allocate a new mm structure and copy contents from the
1128a0a7ec30SJANAK DESAI  * mm structure of the passed in task structure.
1129a0a7ec30SJANAK DESAI  */
1130ff252c1fSDaeSeok Youn static struct mm_struct *dup_mm(struct task_struct *tsk)
1131a0a7ec30SJANAK DESAI {
1132a0a7ec30SJANAK DESAI 	struct mm_struct *mm, *oldmm = current->mm;
1133a0a7ec30SJANAK DESAI 	int err;
1134a0a7ec30SJANAK DESAI 
1135a0a7ec30SJANAK DESAI 	mm = allocate_mm();
1136a0a7ec30SJANAK DESAI 	if (!mm)
1137a0a7ec30SJANAK DESAI 		goto fail_nomem;
1138a0a7ec30SJANAK DESAI 
1139a0a7ec30SJANAK DESAI 	memcpy(mm, oldmm, sizeof(*mm));
1140a0a7ec30SJANAK DESAI 
1141bfedb589SEric W. Biederman 	if (!mm_init(mm, tsk, mm->user_ns))
1142a0a7ec30SJANAK DESAI 		goto fail_nomem;
1143a0a7ec30SJANAK DESAI 
1144a0a7ec30SJANAK DESAI 	err = dup_mmap(mm, oldmm);
1145a0a7ec30SJANAK DESAI 	if (err)
1146a0a7ec30SJANAK DESAI 		goto free_pt;
1147a0a7ec30SJANAK DESAI 
1148a0a7ec30SJANAK DESAI 	mm->hiwater_rss = get_mm_rss(mm);
1149a0a7ec30SJANAK DESAI 	mm->hiwater_vm = mm->total_vm;
1150a0a7ec30SJANAK DESAI 
1151801460d0SHiroshi Shimamoto 	if (mm->binfmt && !try_module_get(mm->binfmt->module))
1152801460d0SHiroshi Shimamoto 		goto free_pt;
1153801460d0SHiroshi Shimamoto 
1154a0a7ec30SJANAK DESAI 	return mm;
1155a0a7ec30SJANAK DESAI 
1156a0a7ec30SJANAK DESAI free_pt:
1157801460d0SHiroshi Shimamoto 	/* don't put binfmt in mmput, we haven't got module yet */
1158801460d0SHiroshi Shimamoto 	mm->binfmt = NULL;
1159a0a7ec30SJANAK DESAI 	mmput(mm);
1160a0a7ec30SJANAK DESAI 
1161a0a7ec30SJANAK DESAI fail_nomem:
1162a0a7ec30SJANAK DESAI 	return NULL;
1163a0a7ec30SJANAK DESAI }
1164a0a7ec30SJANAK DESAI 
11651da177e4SLinus Torvalds static int copy_mm(unsigned long clone_flags, struct task_struct *tsk)
11661da177e4SLinus Torvalds {
11671da177e4SLinus Torvalds 	struct mm_struct *mm, *oldmm;
11681da177e4SLinus Torvalds 	int retval;
11691da177e4SLinus Torvalds 
11701da177e4SLinus Torvalds 	tsk->min_flt = tsk->maj_flt = 0;
11711da177e4SLinus Torvalds 	tsk->nvcsw = tsk->nivcsw = 0;
117217406b82SMandeep Singh Baines #ifdef CONFIG_DETECT_HUNG_TASK
117317406b82SMandeep Singh Baines 	tsk->last_switch_count = tsk->nvcsw + tsk->nivcsw;
117417406b82SMandeep Singh Baines #endif
11751da177e4SLinus Torvalds 
11761da177e4SLinus Torvalds 	tsk->mm = NULL;
11771da177e4SLinus Torvalds 	tsk->active_mm = NULL;
11781da177e4SLinus Torvalds 
11791da177e4SLinus Torvalds 	/*
11801da177e4SLinus Torvalds 	 * Are we cloning a kernel thread?
11811da177e4SLinus Torvalds 	 *
11821da177e4SLinus Torvalds 	 * We need to steal a active VM for that..
11831da177e4SLinus Torvalds 	 */
11841da177e4SLinus Torvalds 	oldmm = current->mm;
11851da177e4SLinus Torvalds 	if (!oldmm)
11861da177e4SLinus Torvalds 		return 0;
11871da177e4SLinus Torvalds 
1188615d6e87SDavidlohr Bueso 	/* initialize the new vmacache entries */
1189615d6e87SDavidlohr Bueso 	vmacache_flush(tsk);
1190615d6e87SDavidlohr Bueso 
11911da177e4SLinus Torvalds 	if (clone_flags & CLONE_VM) {
11923fce371bSVegard Nossum 		mmget(oldmm);
11931da177e4SLinus Torvalds 		mm = oldmm;
11941da177e4SLinus Torvalds 		goto good_mm;
11951da177e4SLinus Torvalds 	}
11961da177e4SLinus Torvalds 
11971da177e4SLinus Torvalds 	retval = -ENOMEM;
1198a0a7ec30SJANAK DESAI 	mm = dup_mm(tsk);
11991da177e4SLinus Torvalds 	if (!mm)
12001da177e4SLinus Torvalds 		goto fail_nomem;
12011da177e4SLinus Torvalds 
12021da177e4SLinus Torvalds good_mm:
12031da177e4SLinus Torvalds 	tsk->mm = mm;
12041da177e4SLinus Torvalds 	tsk->active_mm = mm;
12051da177e4SLinus Torvalds 	return 0;
12061da177e4SLinus Torvalds 
12071da177e4SLinus Torvalds fail_nomem:
12081da177e4SLinus Torvalds 	return retval;
12091da177e4SLinus Torvalds }
12101da177e4SLinus Torvalds 
1211a39bc516SAlexey Dobriyan static int copy_fs(unsigned long clone_flags, struct task_struct *tsk)
12121da177e4SLinus Torvalds {
1213498052bbSAl Viro 	struct fs_struct *fs = current->fs;
12141da177e4SLinus Torvalds 	if (clone_flags & CLONE_FS) {
1215498052bbSAl Viro 		/* tsk->fs is already what we want */
12162a4419b5SNick Piggin 		spin_lock(&fs->lock);
1217498052bbSAl Viro 		if (fs->in_exec) {
12182a4419b5SNick Piggin 			spin_unlock(&fs->lock);
1219498052bbSAl Viro 			return -EAGAIN;
1220498052bbSAl Viro 		}
1221498052bbSAl Viro 		fs->users++;
12222a4419b5SNick Piggin 		spin_unlock(&fs->lock);
12231da177e4SLinus Torvalds 		return 0;
12241da177e4SLinus Torvalds 	}
1225498052bbSAl Viro 	tsk->fs = copy_fs_struct(fs);
12261da177e4SLinus Torvalds 	if (!tsk->fs)
12271da177e4SLinus Torvalds 		return -ENOMEM;
12281da177e4SLinus Torvalds 	return 0;
12291da177e4SLinus Torvalds }
12301da177e4SLinus Torvalds 
1231a016f338SJANAK DESAI static int copy_files(unsigned long clone_flags, struct task_struct *tsk)
1232a016f338SJANAK DESAI {
1233a016f338SJANAK DESAI 	struct files_struct *oldf, *newf;
1234a016f338SJANAK DESAI 	int error = 0;
1235a016f338SJANAK DESAI 
1236a016f338SJANAK DESAI 	/*
1237a016f338SJANAK DESAI 	 * A background process may not have any files ...
1238a016f338SJANAK DESAI 	 */
1239a016f338SJANAK DESAI 	oldf = current->files;
1240a016f338SJANAK DESAI 	if (!oldf)
1241a016f338SJANAK DESAI 		goto out;
1242a016f338SJANAK DESAI 
1243a016f338SJANAK DESAI 	if (clone_flags & CLONE_FILES) {
1244a016f338SJANAK DESAI 		atomic_inc(&oldf->count);
1245a016f338SJANAK DESAI 		goto out;
1246a016f338SJANAK DESAI 	}
1247a016f338SJANAK DESAI 
1248a016f338SJANAK DESAI 	newf = dup_fd(oldf, &error);
1249a016f338SJANAK DESAI 	if (!newf)
1250a016f338SJANAK DESAI 		goto out;
1251a016f338SJANAK DESAI 
1252a016f338SJANAK DESAI 	tsk->files = newf;
1253a016f338SJANAK DESAI 	error = 0;
1254a016f338SJANAK DESAI out:
1255a016f338SJANAK DESAI 	return error;
1256a016f338SJANAK DESAI }
1257a016f338SJANAK DESAI 
1258fadad878SJens Axboe static int copy_io(unsigned long clone_flags, struct task_struct *tsk)
1259fd0928dfSJens Axboe {
1260fd0928dfSJens Axboe #ifdef CONFIG_BLOCK
1261fd0928dfSJens Axboe 	struct io_context *ioc = current->io_context;
12626e736be7STejun Heo 	struct io_context *new_ioc;
1263fd0928dfSJens Axboe 
1264fd0928dfSJens Axboe 	if (!ioc)
1265fd0928dfSJens Axboe 		return 0;
1266fadad878SJens Axboe 	/*
1267fadad878SJens Axboe 	 * Share io context with parent, if CLONE_IO is set
1268fadad878SJens Axboe 	 */
1269fadad878SJens Axboe 	if (clone_flags & CLONE_IO) {
12703d48749dSTejun Heo 		ioc_task_link(ioc);
12713d48749dSTejun Heo 		tsk->io_context = ioc;
1272fadad878SJens Axboe 	} else if (ioprio_valid(ioc->ioprio)) {
12736e736be7STejun Heo 		new_ioc = get_task_io_context(tsk, GFP_KERNEL, NUMA_NO_NODE);
12746e736be7STejun Heo 		if (unlikely(!new_ioc))
1275fd0928dfSJens Axboe 			return -ENOMEM;
1276fd0928dfSJens Axboe 
12776e736be7STejun Heo 		new_ioc->ioprio = ioc->ioprio;
127811a3122fSTejun Heo 		put_io_context(new_ioc);
1279fd0928dfSJens Axboe 	}
1280fd0928dfSJens Axboe #endif
1281fd0928dfSJens Axboe 	return 0;
1282fd0928dfSJens Axboe }
1283fd0928dfSJens Axboe 
1284a39bc516SAlexey Dobriyan static int copy_sighand(unsigned long clone_flags, struct task_struct *tsk)
12851da177e4SLinus Torvalds {
12861da177e4SLinus Torvalds 	struct sighand_struct *sig;
12871da177e4SLinus Torvalds 
128860348802SZhaolei 	if (clone_flags & CLONE_SIGHAND) {
12891da177e4SLinus Torvalds 		atomic_inc(&current->sighand->count);
12901da177e4SLinus Torvalds 		return 0;
12911da177e4SLinus Torvalds 	}
12921da177e4SLinus Torvalds 	sig = kmem_cache_alloc(sighand_cachep, GFP_KERNEL);
1293e56d0903SIngo Molnar 	rcu_assign_pointer(tsk->sighand, sig);
12941da177e4SLinus Torvalds 	if (!sig)
12951da177e4SLinus Torvalds 		return -ENOMEM;
12969d7fb042SPeter Zijlstra 
12971da177e4SLinus Torvalds 	atomic_set(&sig->count, 1);
12981da177e4SLinus Torvalds 	memcpy(sig->action, current->sighand->action, sizeof(sig->action));
12991da177e4SLinus Torvalds 	return 0;
13001da177e4SLinus Torvalds }
13011da177e4SLinus Torvalds 
1302a7e5328aSOleg Nesterov void __cleanup_sighand(struct sighand_struct *sighand)
1303c81addc9SOleg Nesterov {
1304d80e731eSOleg Nesterov 	if (atomic_dec_and_test(&sighand->count)) {
1305d80e731eSOleg Nesterov 		signalfd_cleanup(sighand);
1306392809b2SOleg Nesterov 		/*
1307392809b2SOleg Nesterov 		 * sighand_cachep is SLAB_DESTROY_BY_RCU so we can free it
1308392809b2SOleg Nesterov 		 * without an RCU grace period, see __lock_task_sighand().
1309392809b2SOleg Nesterov 		 */
1310c81addc9SOleg Nesterov 		kmem_cache_free(sighand_cachep, sighand);
1311c81addc9SOleg Nesterov 	}
1312d80e731eSOleg Nesterov }
1313c81addc9SOleg Nesterov 
1314b18b6a9cSNicolas Pitre #ifdef CONFIG_POSIX_TIMERS
1315f06febc9SFrank Mayhar /*
1316f06febc9SFrank Mayhar  * Initialize POSIX timer handling for a thread group.
1317f06febc9SFrank Mayhar  */
1318f06febc9SFrank Mayhar static void posix_cpu_timers_init_group(struct signal_struct *sig)
1319f06febc9SFrank Mayhar {
132078d7d407SJiri Slaby 	unsigned long cpu_limit;
132178d7d407SJiri Slaby 
1322316c1608SJason Low 	cpu_limit = READ_ONCE(sig->rlim[RLIMIT_CPU].rlim_cur);
132378d7d407SJiri Slaby 	if (cpu_limit != RLIM_INFINITY) {
1324ebd7e7fcSFrederic Weisbecker 		sig->cputime_expires.prof_exp = cpu_limit * NSEC_PER_SEC;
1325d5c373ebSJason Low 		sig->cputimer.running = true;
13266279a751SOleg Nesterov 	}
13276279a751SOleg Nesterov 
1328f06febc9SFrank Mayhar 	/* The timer lists. */
1329f06febc9SFrank Mayhar 	INIT_LIST_HEAD(&sig->cpu_timers[0]);
1330f06febc9SFrank Mayhar 	INIT_LIST_HEAD(&sig->cpu_timers[1]);
1331f06febc9SFrank Mayhar 	INIT_LIST_HEAD(&sig->cpu_timers[2]);
1332f06febc9SFrank Mayhar }
1333b18b6a9cSNicolas Pitre #else
1334b18b6a9cSNicolas Pitre static inline void posix_cpu_timers_init_group(struct signal_struct *sig) { }
1335b18b6a9cSNicolas Pitre #endif
1336f06febc9SFrank Mayhar 
1337a39bc516SAlexey Dobriyan static int copy_signal(unsigned long clone_flags, struct task_struct *tsk)
13381da177e4SLinus Torvalds {
13391da177e4SLinus Torvalds 	struct signal_struct *sig;
13401da177e4SLinus Torvalds 
13414ab6c083SOleg Nesterov 	if (clone_flags & CLONE_THREAD)
1342490dea45SPeter Zijlstra 		return 0;
13436279a751SOleg Nesterov 
1344a56704efSVeaceslav Falico 	sig = kmem_cache_zalloc(signal_cachep, GFP_KERNEL);
13451da177e4SLinus Torvalds 	tsk->signal = sig;
13461da177e4SLinus Torvalds 	if (!sig)
13471da177e4SLinus Torvalds 		return -ENOMEM;
13481da177e4SLinus Torvalds 
1349b3ac022cSOleg Nesterov 	sig->nr_threads = 1;
13501da177e4SLinus Torvalds 	atomic_set(&sig->live, 1);
1351b3ac022cSOleg Nesterov 	atomic_set(&sig->sigcnt, 1);
13520c740d0aSOleg Nesterov 
13530c740d0aSOleg Nesterov 	/* list_add(thread_node, thread_head) without INIT_LIST_HEAD() */
13540c740d0aSOleg Nesterov 	sig->thread_head = (struct list_head)LIST_HEAD_INIT(tsk->thread_node);
13550c740d0aSOleg Nesterov 	tsk->thread_node = (struct list_head)LIST_HEAD_INIT(sig->thread_head);
13560c740d0aSOleg Nesterov 
13571da177e4SLinus Torvalds 	init_waitqueue_head(&sig->wait_chldexit);
1358db51aeccSOleg Nesterov 	sig->curr_target = tsk;
13591da177e4SLinus Torvalds 	init_sigpending(&sig->shared_pending);
1360e78c3496SRik van Riel 	seqlock_init(&sig->stats_lock);
13619d7fb042SPeter Zijlstra 	prev_cputime_init(&sig->prev_cputime);
13621da177e4SLinus Torvalds 
1363baa73d9eSNicolas Pitre #ifdef CONFIG_POSIX_TIMERS
1364b18b6a9cSNicolas Pitre 	INIT_LIST_HEAD(&sig->posix_timers);
1365c9cb2e3dSThomas Gleixner 	hrtimer_init(&sig->real_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
13661da177e4SLinus Torvalds 	sig->real_timer.function = it_real_fn;
1367baa73d9eSNicolas Pitre #endif
13681da177e4SLinus Torvalds 
13691da177e4SLinus Torvalds 	task_lock(current->group_leader);
13701da177e4SLinus Torvalds 	memcpy(sig->rlim, current->signal->rlim, sizeof sig->rlim);
13711da177e4SLinus Torvalds 	task_unlock(current->group_leader);
13721da177e4SLinus Torvalds 
13736279a751SOleg Nesterov 	posix_cpu_timers_init_group(sig);
13746279a751SOleg Nesterov 
1375522ed776SMiloslav Trmac 	tty_audit_fork(sig);
13765091faa4SMike Galbraith 	sched_autogroup_fork(sig);
1377522ed776SMiloslav Trmac 
1378a63d83f4SDavid Rientjes 	sig->oom_score_adj = current->signal->oom_score_adj;
1379dabb16f6SMandeep Singh Baines 	sig->oom_score_adj_min = current->signal->oom_score_adj_min;
138028b83c51SKOSAKI Motohiro 
13819b1bf12dSKOSAKI Motohiro 	mutex_init(&sig->cred_guard_mutex);
13829b1bf12dSKOSAKI Motohiro 
13831da177e4SLinus Torvalds 	return 0;
13841da177e4SLinus Torvalds }
13851da177e4SLinus Torvalds 
1386dbd95212SKees Cook static void copy_seccomp(struct task_struct *p)
1387dbd95212SKees Cook {
1388dbd95212SKees Cook #ifdef CONFIG_SECCOMP
1389dbd95212SKees Cook 	/*
1390dbd95212SKees Cook 	 * Must be called with sighand->lock held, which is common to
1391dbd95212SKees Cook 	 * all threads in the group. Holding cred_guard_mutex is not
1392dbd95212SKees Cook 	 * needed because this new task is not yet running and cannot
1393dbd95212SKees Cook 	 * be racing exec.
1394dbd95212SKees Cook 	 */
139569f6a34bSGuenter Roeck 	assert_spin_locked(&current->sighand->siglock);
1396dbd95212SKees Cook 
1397dbd95212SKees Cook 	/* Ref-count the new filter user, and assign it. */
1398dbd95212SKees Cook 	get_seccomp_filter(current);
1399dbd95212SKees Cook 	p->seccomp = current->seccomp;
1400dbd95212SKees Cook 
1401dbd95212SKees Cook 	/*
1402dbd95212SKees Cook 	 * Explicitly enable no_new_privs here in case it got set
1403dbd95212SKees Cook 	 * between the task_struct being duplicated and holding the
1404dbd95212SKees Cook 	 * sighand lock. The seccomp state and nnp must be in sync.
1405dbd95212SKees Cook 	 */
1406dbd95212SKees Cook 	if (task_no_new_privs(current))
1407dbd95212SKees Cook 		task_set_no_new_privs(p);
1408dbd95212SKees Cook 
1409dbd95212SKees Cook 	/*
1410dbd95212SKees Cook 	 * If the parent gained a seccomp mode after copying thread
1411dbd95212SKees Cook 	 * flags and between before we held the sighand lock, we have
1412dbd95212SKees Cook 	 * to manually enable the seccomp thread flag here.
1413dbd95212SKees Cook 	 */
1414dbd95212SKees Cook 	if (p->seccomp.mode != SECCOMP_MODE_DISABLED)
1415dbd95212SKees Cook 		set_tsk_thread_flag(p, TIF_SECCOMP);
1416dbd95212SKees Cook #endif
1417dbd95212SKees Cook }
1418dbd95212SKees Cook 
141917da2bd9SHeiko Carstens SYSCALL_DEFINE1(set_tid_address, int __user *, tidptr)
14201da177e4SLinus Torvalds {
14211da177e4SLinus Torvalds 	current->clear_child_tid = tidptr;
14221da177e4SLinus Torvalds 
1423b488893aSPavel Emelyanov 	return task_pid_vnr(current);
14241da177e4SLinus Torvalds }
14251da177e4SLinus Torvalds 
1426a39bc516SAlexey Dobriyan static void rt_mutex_init_task(struct task_struct *p)
142723f78d4aSIngo Molnar {
14281d615482SThomas Gleixner 	raw_spin_lock_init(&p->pi_lock);
1429e29e175bSZilvinas Valinskas #ifdef CONFIG_RT_MUTEXES
1430fb00aca4SPeter Zijlstra 	p->pi_waiters = RB_ROOT;
1431fb00aca4SPeter Zijlstra 	p->pi_waiters_leftmost = NULL;
143223f78d4aSIngo Molnar 	p->pi_blocked_on = NULL;
143323f78d4aSIngo Molnar #endif
143423f78d4aSIngo Molnar }
143523f78d4aSIngo Molnar 
1436b18b6a9cSNicolas Pitre #ifdef CONFIG_POSIX_TIMERS
14371da177e4SLinus Torvalds /*
1438f06febc9SFrank Mayhar  * Initialize POSIX timer handling for a single task.
1439f06febc9SFrank Mayhar  */
1440f06febc9SFrank Mayhar static void posix_cpu_timers_init(struct task_struct *tsk)
1441f06febc9SFrank Mayhar {
144264861634SMartin Schwidefsky 	tsk->cputime_expires.prof_exp = 0;
144364861634SMartin Schwidefsky 	tsk->cputime_expires.virt_exp = 0;
1444f06febc9SFrank Mayhar 	tsk->cputime_expires.sched_exp = 0;
1445f06febc9SFrank Mayhar 	INIT_LIST_HEAD(&tsk->cpu_timers[0]);
1446f06febc9SFrank Mayhar 	INIT_LIST_HEAD(&tsk->cpu_timers[1]);
1447f06febc9SFrank Mayhar 	INIT_LIST_HEAD(&tsk->cpu_timers[2]);
1448f06febc9SFrank Mayhar }
1449b18b6a9cSNicolas Pitre #else
1450b18b6a9cSNicolas Pitre static inline void posix_cpu_timers_init(struct task_struct *tsk) { }
1451b18b6a9cSNicolas Pitre #endif
1452f06febc9SFrank Mayhar 
145381907739SOleg Nesterov static inline void
145481907739SOleg Nesterov init_task_pid(struct task_struct *task, enum pid_type type, struct pid *pid)
145581907739SOleg Nesterov {
145681907739SOleg Nesterov 	 task->pids[type].pid = pid;
145781907739SOleg Nesterov }
145881907739SOleg Nesterov 
1459f06febc9SFrank Mayhar /*
14601da177e4SLinus Torvalds  * This creates a new process as a copy of the old one,
14611da177e4SLinus Torvalds  * but does not actually start it yet.
14621da177e4SLinus Torvalds  *
14631da177e4SLinus Torvalds  * It copies the registers, and all the appropriate
14641da177e4SLinus Torvalds  * parts of the process environment (as per the clone
14651da177e4SLinus Torvalds  * flags). The actual kick-off is left to the caller.
14661da177e4SLinus Torvalds  */
14670766f788SEmese Revfy static __latent_entropy struct task_struct *copy_process(
14680766f788SEmese Revfy 					unsigned long clone_flags,
14691da177e4SLinus Torvalds 					unsigned long stack_start,
14701da177e4SLinus Torvalds 					unsigned long stack_size,
14711da177e4SLinus Torvalds 					int __user *child_tidptr,
147209a05394SRoland McGrath 					struct pid *pid,
14733033f14aSJosh Triplett 					int trace,
1474725fc629SAndi Kleen 					unsigned long tls,
1475725fc629SAndi Kleen 					int node)
14761da177e4SLinus Torvalds {
14771da177e4SLinus Torvalds 	int retval;
1478a24efe62SMariusz Kozlowski 	struct task_struct *p;
14791da177e4SLinus Torvalds 
14801da177e4SLinus Torvalds 	if ((clone_flags & (CLONE_NEWNS|CLONE_FS)) == (CLONE_NEWNS|CLONE_FS))
14811da177e4SLinus Torvalds 		return ERR_PTR(-EINVAL);
14821da177e4SLinus Torvalds 
1483e66eded8SEric W. Biederman 	if ((clone_flags & (CLONE_NEWUSER|CLONE_FS)) == (CLONE_NEWUSER|CLONE_FS))
1484e66eded8SEric W. Biederman 		return ERR_PTR(-EINVAL);
1485e66eded8SEric W. Biederman 
14861da177e4SLinus Torvalds 	/*
14871da177e4SLinus Torvalds 	 * Thread groups must share signals as well, and detached threads
14881da177e4SLinus Torvalds 	 * can only be started up within the thread group.
14891da177e4SLinus Torvalds 	 */
14901da177e4SLinus Torvalds 	if ((clone_flags & CLONE_THREAD) && !(clone_flags & CLONE_SIGHAND))
14911da177e4SLinus Torvalds 		return ERR_PTR(-EINVAL);
14921da177e4SLinus Torvalds 
14931da177e4SLinus Torvalds 	/*
14941da177e4SLinus Torvalds 	 * Shared signal handlers imply shared VM. By way of the above,
14951da177e4SLinus Torvalds 	 * thread groups also imply shared VM. Blocking this case allows
14961da177e4SLinus Torvalds 	 * for various simplifications in other code.
14971da177e4SLinus Torvalds 	 */
14981da177e4SLinus Torvalds 	if ((clone_flags & CLONE_SIGHAND) && !(clone_flags & CLONE_VM))
14991da177e4SLinus Torvalds 		return ERR_PTR(-EINVAL);
15001da177e4SLinus Torvalds 
1501123be07bSSukadev Bhattiprolu 	/*
1502123be07bSSukadev Bhattiprolu 	 * Siblings of global init remain as zombies on exit since they are
1503123be07bSSukadev Bhattiprolu 	 * not reaped by their parent (swapper). To solve this and to avoid
1504123be07bSSukadev Bhattiprolu 	 * multi-rooted process trees, prevent global and container-inits
1505123be07bSSukadev Bhattiprolu 	 * from creating siblings.
1506123be07bSSukadev Bhattiprolu 	 */
1507123be07bSSukadev Bhattiprolu 	if ((clone_flags & CLONE_PARENT) &&
1508123be07bSSukadev Bhattiprolu 				current->signal->flags & SIGNAL_UNKILLABLE)
1509123be07bSSukadev Bhattiprolu 		return ERR_PTR(-EINVAL);
1510123be07bSSukadev Bhattiprolu 
15118382fcacSEric W. Biederman 	/*
151240a0d32dSOleg Nesterov 	 * If the new process will be in a different pid or user namespace
1513faf00da5SEric W. Biederman 	 * do not allow it to share a thread group with the forking task.
15148382fcacSEric W. Biederman 	 */
1515faf00da5SEric W. Biederman 	if (clone_flags & CLONE_THREAD) {
151640a0d32dSOleg Nesterov 		if ((clone_flags & (CLONE_NEWUSER | CLONE_NEWPID)) ||
151740a0d32dSOleg Nesterov 		    (task_active_pid_ns(current) !=
1518c2b1df2eSAndy Lutomirski 				current->nsproxy->pid_ns_for_children))
15198382fcacSEric W. Biederman 			return ERR_PTR(-EINVAL);
152040a0d32dSOleg Nesterov 	}
15218382fcacSEric W. Biederman 
15221da177e4SLinus Torvalds 	retval = security_task_create(clone_flags);
15231da177e4SLinus Torvalds 	if (retval)
15241da177e4SLinus Torvalds 		goto fork_out;
15251da177e4SLinus Torvalds 
15261da177e4SLinus Torvalds 	retval = -ENOMEM;
1527725fc629SAndi Kleen 	p = dup_task_struct(current, node);
15281da177e4SLinus Torvalds 	if (!p)
15291da177e4SLinus Torvalds 		goto fork_out;
15301da177e4SLinus Torvalds 
1531f7e8b616SSteven Rostedt 	ftrace_graph_init_task(p);
1532f7e8b616SSteven Rostedt 
1533bea493a0SPeter Zijlstra 	rt_mutex_init_task(p);
1534bea493a0SPeter Zijlstra 
1535d12c1a37SIngo Molnar #ifdef CONFIG_PROVE_LOCKING
1536de30a2b3SIngo Molnar 	DEBUG_LOCKS_WARN_ON(!p->hardirqs_enabled);
1537de30a2b3SIngo Molnar 	DEBUG_LOCKS_WARN_ON(!p->softirqs_enabled);
1538de30a2b3SIngo Molnar #endif
15391da177e4SLinus Torvalds 	retval = -EAGAIN;
15403b11a1deSDavid Howells 	if (atomic_read(&p->real_cred->user->processes) >=
154178d7d407SJiri Slaby 			task_rlimit(p, RLIMIT_NPROC)) {
1542b57922b6SEric Paris 		if (p->real_cred->user != INIT_USER &&
1543b57922b6SEric Paris 		    !capable(CAP_SYS_RESOURCE) && !capable(CAP_SYS_ADMIN))
15441da177e4SLinus Torvalds 			goto bad_fork_free;
15451da177e4SLinus Torvalds 	}
154672fa5997SVasiliy Kulikov 	current->flags &= ~PF_NPROC_EXCEEDED;
15471da177e4SLinus Torvalds 
1548f1752eecSDavid Howells 	retval = copy_creds(p, clone_flags);
1549f1752eecSDavid Howells 	if (retval < 0)
1550f1752eecSDavid Howells 		goto bad_fork_free;
15511da177e4SLinus Torvalds 
15521da177e4SLinus Torvalds 	/*
15531da177e4SLinus Torvalds 	 * If multiple threads are within copy_process(), then this check
15541da177e4SLinus Torvalds 	 * triggers too late. This doesn't hurt, the check is only there
15551da177e4SLinus Torvalds 	 * to stop root fork bombs.
15561da177e4SLinus Torvalds 	 */
155704ec93feSLi Zefan 	retval = -EAGAIN;
15581da177e4SLinus Torvalds 	if (nr_threads >= max_threads)
15591da177e4SLinus Torvalds 		goto bad_fork_cleanup_count;
15601da177e4SLinus Torvalds 
1561ca74e92bSShailabh Nagar 	delayacct_tsk_init(p);	/* Must remain after dup_task_struct() */
1562c1de45caSPeter Zijlstra 	p->flags &= ~(PF_SUPERPRIV | PF_WQ_WORKER | PF_IDLE);
1563514ddb44SDavid Rientjes 	p->flags |= PF_FORKNOEXEC;
15641da177e4SLinus Torvalds 	INIT_LIST_HEAD(&p->children);
15651da177e4SLinus Torvalds 	INIT_LIST_HEAD(&p->sibling);
1566f41d911fSPaul E. McKenney 	rcu_copy_process(p);
15671da177e4SLinus Torvalds 	p->vfork_done = NULL;
15681da177e4SLinus Torvalds 	spin_lock_init(&p->alloc_lock);
15691da177e4SLinus Torvalds 
15701da177e4SLinus Torvalds 	init_sigpending(&p->pending);
15711da177e4SLinus Torvalds 
157264861634SMartin Schwidefsky 	p->utime = p->stime = p->gtime = 0;
157340565b5aSStanislaw Gruszka #ifdef CONFIG_ARCH_HAS_SCALED_CPUTIME
157464861634SMartin Schwidefsky 	p->utimescaled = p->stimescaled = 0;
157540565b5aSStanislaw Gruszka #endif
15769d7fb042SPeter Zijlstra 	prev_cputime_init(&p->prev_cputime);
15779d7fb042SPeter Zijlstra 
15786a61671bSFrederic Weisbecker #ifdef CONFIG_VIRT_CPU_ACCOUNTING_GEN
1579b7ce2277SFrederic Weisbecker 	seqcount_init(&p->vtime_seqcount);
15806a61671bSFrederic Weisbecker 	p->vtime_snap = 0;
15817098c1eaSFrederic Weisbecker 	p->vtime_snap_whence = VTIME_INACTIVE;
15826a61671bSFrederic Weisbecker #endif
15836a61671bSFrederic Weisbecker 
1584a3a2e76cSKAMEZAWA Hiroyuki #if defined(SPLIT_RSS_COUNTING)
1585a3a2e76cSKAMEZAWA Hiroyuki 	memset(&p->rss_stat, 0, sizeof(p->rss_stat));
1586a3a2e76cSKAMEZAWA Hiroyuki #endif
1587172ba844SBalbir Singh 
15886976675dSArjan van de Ven 	p->default_timer_slack_ns = current->timer_slack_ns;
15896976675dSArjan van de Ven 
15905995477aSAndrea Righi 	task_io_accounting_init(&p->ioac);
15911da177e4SLinus Torvalds 	acct_clear_integrals(p);
15921da177e4SLinus Torvalds 
1593f06febc9SFrank Mayhar 	posix_cpu_timers_init(p);
15941da177e4SLinus Torvalds 
1595ccbf62d8SThomas Gleixner 	p->start_time = ktime_get_ns();
159657e0be04SThomas Gleixner 	p->real_start_time = ktime_get_boot_ns();
15971da177e4SLinus Torvalds 	p->io_context = NULL;
15981da177e4SLinus Torvalds 	p->audit_context = NULL;
1599b4f48b63SPaul Menage 	cgroup_fork(p);
16001da177e4SLinus Torvalds #ifdef CONFIG_NUMA
1601846a16bfSLee Schermerhorn 	p->mempolicy = mpol_dup(p->mempolicy);
16021da177e4SLinus Torvalds 	if (IS_ERR(p->mempolicy)) {
16031da177e4SLinus Torvalds 		retval = PTR_ERR(p->mempolicy);
16041da177e4SLinus Torvalds 		p->mempolicy = NULL;
1605e8604cb4SLi Zefan 		goto bad_fork_cleanup_threadgroup_lock;
16061da177e4SLinus Torvalds 	}
16071da177e4SLinus Torvalds #endif
1608778d3b0fSMichal Hocko #ifdef CONFIG_CPUSETS
1609778d3b0fSMichal Hocko 	p->cpuset_mem_spread_rotor = NUMA_NO_NODE;
1610778d3b0fSMichal Hocko 	p->cpuset_slab_spread_rotor = NUMA_NO_NODE;
1611cc9a6c87SMel Gorman 	seqcount_init(&p->mems_allowed_seq);
1612778d3b0fSMichal Hocko #endif
1613de30a2b3SIngo Molnar #ifdef CONFIG_TRACE_IRQFLAGS
1614de30a2b3SIngo Molnar 	p->irq_events = 0;
1615de30a2b3SIngo Molnar 	p->hardirqs_enabled = 0;
1616de30a2b3SIngo Molnar 	p->hardirq_enable_ip = 0;
1617de30a2b3SIngo Molnar 	p->hardirq_enable_event = 0;
1618de30a2b3SIngo Molnar 	p->hardirq_disable_ip = _THIS_IP_;
1619de30a2b3SIngo Molnar 	p->hardirq_disable_event = 0;
1620de30a2b3SIngo Molnar 	p->softirqs_enabled = 1;
1621de30a2b3SIngo Molnar 	p->softirq_enable_ip = _THIS_IP_;
1622de30a2b3SIngo Molnar 	p->softirq_enable_event = 0;
1623de30a2b3SIngo Molnar 	p->softirq_disable_ip = 0;
1624de30a2b3SIngo Molnar 	p->softirq_disable_event = 0;
1625de30a2b3SIngo Molnar 	p->hardirq_context = 0;
1626de30a2b3SIngo Molnar 	p->softirq_context = 0;
1627de30a2b3SIngo Molnar #endif
16288bcbde54SDavid Hildenbrand 
16298bcbde54SDavid Hildenbrand 	p->pagefault_disabled = 0;
16308bcbde54SDavid Hildenbrand 
1631fbb9ce95SIngo Molnar #ifdef CONFIG_LOCKDEP
1632fbb9ce95SIngo Molnar 	p->lockdep_depth = 0; /* no locks held yet */
1633fbb9ce95SIngo Molnar 	p->curr_chain_key = 0;
1634fbb9ce95SIngo Molnar 	p->lockdep_recursion = 0;
1635fbb9ce95SIngo Molnar #endif
16361da177e4SLinus Torvalds 
1637408894eeSIngo Molnar #ifdef CONFIG_DEBUG_MUTEXES
1638408894eeSIngo Molnar 	p->blocked_on = NULL; /* not blocked yet */
1639408894eeSIngo Molnar #endif
1640cafe5635SKent Overstreet #ifdef CONFIG_BCACHE
1641cafe5635SKent Overstreet 	p->sequential_io	= 0;
1642cafe5635SKent Overstreet 	p->sequential_io_avg	= 0;
1643cafe5635SKent Overstreet #endif
16440f481406SMarkus Metzger 
16453c90e6e9SSrivatsa Vaddagiri 	/* Perform scheduler related setup. Assign this task to a CPU. */
1646aab03e05SDario Faggioli 	retval = sched_fork(clone_flags, p);
1647aab03e05SDario Faggioli 	if (retval)
1648aab03e05SDario Faggioli 		goto bad_fork_cleanup_policy;
16496ab423e0SPeter Zijlstra 
1650cdd6c482SIngo Molnar 	retval = perf_event_init_task(p);
16516ab423e0SPeter Zijlstra 	if (retval)
16526ab423e0SPeter Zijlstra 		goto bad_fork_cleanup_policy;
1653fb0a685cSDaniel Rebelo de Oliveira 	retval = audit_alloc(p);
1654fb0a685cSDaniel Rebelo de Oliveira 	if (retval)
16556c72e350SPeter Zijlstra 		goto bad_fork_cleanup_perf;
16561da177e4SLinus Torvalds 	/* copy all the process information */
1657ab602f79SJack Miller 	shm_init_task(p);
1658fb0a685cSDaniel Rebelo de Oliveira 	retval = copy_semundo(clone_flags, p);
1659fb0a685cSDaniel Rebelo de Oliveira 	if (retval)
16601da177e4SLinus Torvalds 		goto bad_fork_cleanup_audit;
1661fb0a685cSDaniel Rebelo de Oliveira 	retval = copy_files(clone_flags, p);
1662fb0a685cSDaniel Rebelo de Oliveira 	if (retval)
16631da177e4SLinus Torvalds 		goto bad_fork_cleanup_semundo;
1664fb0a685cSDaniel Rebelo de Oliveira 	retval = copy_fs(clone_flags, p);
1665fb0a685cSDaniel Rebelo de Oliveira 	if (retval)
16661da177e4SLinus Torvalds 		goto bad_fork_cleanup_files;
1667fb0a685cSDaniel Rebelo de Oliveira 	retval = copy_sighand(clone_flags, p);
1668fb0a685cSDaniel Rebelo de Oliveira 	if (retval)
16691da177e4SLinus Torvalds 		goto bad_fork_cleanup_fs;
1670fb0a685cSDaniel Rebelo de Oliveira 	retval = copy_signal(clone_flags, p);
1671fb0a685cSDaniel Rebelo de Oliveira 	if (retval)
16721da177e4SLinus Torvalds 		goto bad_fork_cleanup_sighand;
1673fb0a685cSDaniel Rebelo de Oliveira 	retval = copy_mm(clone_flags, p);
1674fb0a685cSDaniel Rebelo de Oliveira 	if (retval)
16751da177e4SLinus Torvalds 		goto bad_fork_cleanup_signal;
1676fb0a685cSDaniel Rebelo de Oliveira 	retval = copy_namespaces(clone_flags, p);
1677fb0a685cSDaniel Rebelo de Oliveira 	if (retval)
1678d84f4f99SDavid Howells 		goto bad_fork_cleanup_mm;
1679fb0a685cSDaniel Rebelo de Oliveira 	retval = copy_io(clone_flags, p);
1680fb0a685cSDaniel Rebelo de Oliveira 	if (retval)
1681fd0928dfSJens Axboe 		goto bad_fork_cleanup_namespaces;
16823033f14aSJosh Triplett 	retval = copy_thread_tls(clone_flags, stack_start, stack_size, p, tls);
16831da177e4SLinus Torvalds 	if (retval)
1684fd0928dfSJens Axboe 		goto bad_fork_cleanup_io;
16851da177e4SLinus Torvalds 
1686425fb2b4SPavel Emelyanov 	if (pid != &init_struct_pid) {
1687c2b1df2eSAndy Lutomirski 		pid = alloc_pid(p->nsproxy->pid_ns_for_children);
168835f71bc0SMichal Hocko 		if (IS_ERR(pid)) {
168935f71bc0SMichal Hocko 			retval = PTR_ERR(pid);
16900740aa5fSJiri Slaby 			goto bad_fork_cleanup_thread;
1691425fb2b4SPavel Emelyanov 		}
169235f71bc0SMichal Hocko 	}
1693425fb2b4SPavel Emelyanov 
16941da177e4SLinus Torvalds 	p->set_child_tid = (clone_flags & CLONE_CHILD_SETTID) ? child_tidptr : NULL;
16951da177e4SLinus Torvalds 	/*
16961da177e4SLinus Torvalds 	 * Clear TID on mm_release()?
16971da177e4SLinus Torvalds 	 */
16981da177e4SLinus Torvalds 	p->clear_child_tid = (clone_flags & CLONE_CHILD_CLEARTID) ? child_tidptr : NULL;
169973c10101SJens Axboe #ifdef CONFIG_BLOCK
170073c10101SJens Axboe 	p->plug = NULL;
170173c10101SJens Axboe #endif
170242b2dd0aSAlexey Dobriyan #ifdef CONFIG_FUTEX
17038f17d3a5SIngo Molnar 	p->robust_list = NULL;
17048f17d3a5SIngo Molnar #ifdef CONFIG_COMPAT
17058f17d3a5SIngo Molnar 	p->compat_robust_list = NULL;
17068f17d3a5SIngo Molnar #endif
1707c87e2837SIngo Molnar 	INIT_LIST_HEAD(&p->pi_state_list);
1708c87e2837SIngo Molnar 	p->pi_state_cache = NULL;
170942b2dd0aSAlexey Dobriyan #endif
17101da177e4SLinus Torvalds 	/*
1711f9a3879aSGOTO Masanori 	 * sigaltstack should be cleared when sharing the same VM
1712f9a3879aSGOTO Masanori 	 */
1713f9a3879aSGOTO Masanori 	if ((clone_flags & (CLONE_VM|CLONE_VFORK)) == CLONE_VM)
17142a742138SStas Sergeev 		sas_ss_reset(p);
1715f9a3879aSGOTO Masanori 
1716f9a3879aSGOTO Masanori 	/*
17176580807dSOleg Nesterov 	 * Syscall tracing and stepping should be turned off in the
17186580807dSOleg Nesterov 	 * child regardless of CLONE_PTRACE.
17191da177e4SLinus Torvalds 	 */
17206580807dSOleg Nesterov 	user_disable_single_step(p);
17211da177e4SLinus Torvalds 	clear_tsk_thread_flag(p, TIF_SYSCALL_TRACE);
1722ed75e8d5SLaurent Vivier #ifdef TIF_SYSCALL_EMU
1723ed75e8d5SLaurent Vivier 	clear_tsk_thread_flag(p, TIF_SYSCALL_EMU);
1724ed75e8d5SLaurent Vivier #endif
17259745512cSArjan van de Ven 	clear_all_latency_tracing(p);
17261da177e4SLinus Torvalds 
17271da177e4SLinus Torvalds 	/* ok, now we should be set up.. */
172818c830dfSOleg Nesterov 	p->pid = pid_nr(pid);
172918c830dfSOleg Nesterov 	if (clone_flags & CLONE_THREAD) {
17305f8aadd8SOleg Nesterov 		p->exit_signal = -1;
173118c830dfSOleg Nesterov 		p->group_leader = current->group_leader;
173218c830dfSOleg Nesterov 		p->tgid = current->tgid;
173318c830dfSOleg Nesterov 	} else {
173418c830dfSOleg Nesterov 		if (clone_flags & CLONE_PARENT)
17355f8aadd8SOleg Nesterov 			p->exit_signal = current->group_leader->exit_signal;
17365f8aadd8SOleg Nesterov 		else
17375f8aadd8SOleg Nesterov 			p->exit_signal = (clone_flags & CSIGNAL);
173818c830dfSOleg Nesterov 		p->group_leader = p;
173918c830dfSOleg Nesterov 		p->tgid = p->pid;
174018c830dfSOleg Nesterov 	}
17415f8aadd8SOleg Nesterov 
17429d823e8fSWu Fengguang 	p->nr_dirtied = 0;
17439d823e8fSWu Fengguang 	p->nr_dirtied_pause = 128 >> (PAGE_SHIFT - 10);
174483712358SWu Fengguang 	p->dirty_paused_when = 0;
17459d823e8fSWu Fengguang 
1746bb8cbbfeSOleg Nesterov 	p->pdeath_signal = 0;
174747e65328SOleg Nesterov 	INIT_LIST_HEAD(&p->thread_group);
1748158e1645SAl Viro 	p->task_works = NULL;
17491da177e4SLinus Torvalds 
1750780de9ddSIngo Molnar 	cgroup_threadgroup_change_begin(current);
175118c830dfSOleg Nesterov 	/*
17527e47682eSAleksa Sarai 	 * Ensure that the cgroup subsystem policies allow the new process to be
17537e47682eSAleksa Sarai 	 * forked. It should be noted the the new process's css_set can be changed
17547e47682eSAleksa Sarai 	 * between here and cgroup_post_fork() if an organisation operation is in
17557e47682eSAleksa Sarai 	 * progress.
17567e47682eSAleksa Sarai 	 */
1757b53202e6SOleg Nesterov 	retval = cgroup_can_fork(p);
17587e47682eSAleksa Sarai 	if (retval)
17597e47682eSAleksa Sarai 		goto bad_fork_free_pid;
17607e47682eSAleksa Sarai 
17617e47682eSAleksa Sarai 	/*
176218c830dfSOleg Nesterov 	 * Make it visible to the rest of the system, but dont wake it up yet.
176318c830dfSOleg Nesterov 	 * Need tasklist lock for parent etc handling!
176418c830dfSOleg Nesterov 	 */
17651da177e4SLinus Torvalds 	write_lock_irq(&tasklist_lock);
17661da177e4SLinus Torvalds 
17671da177e4SLinus Torvalds 	/* CLONE_PARENT re-uses the old parent */
17682d5516cbSOleg Nesterov 	if (clone_flags & (CLONE_PARENT|CLONE_THREAD)) {
17691da177e4SLinus Torvalds 		p->real_parent = current->real_parent;
17702d5516cbSOleg Nesterov 		p->parent_exec_id = current->parent_exec_id;
17712d5516cbSOleg Nesterov 	} else {
17721da177e4SLinus Torvalds 		p->real_parent = current;
17732d5516cbSOleg Nesterov 		p->parent_exec_id = current->self_exec_id;
17742d5516cbSOleg Nesterov 	}
17751da177e4SLinus Torvalds 
17761da177e4SLinus Torvalds 	spin_lock(&current->sighand->siglock);
17774a2c7a78SOleg Nesterov 
17784a2c7a78SOleg Nesterov 	/*
1779dbd95212SKees Cook 	 * Copy seccomp details explicitly here, in case they were changed
1780dbd95212SKees Cook 	 * before holding sighand lock.
1781dbd95212SKees Cook 	 */
1782dbd95212SKees Cook 	copy_seccomp(p);
1783dbd95212SKees Cook 
1784dbd95212SKees Cook 	/*
17854a2c7a78SOleg Nesterov 	 * Process group and session signals need to be delivered to just the
17864a2c7a78SOleg Nesterov 	 * parent before the fork or both the parent and the child after the
17874a2c7a78SOleg Nesterov 	 * fork. Restart if a signal comes in before we add the new process to
17884a2c7a78SOleg Nesterov 	 * it's process group.
17894a2c7a78SOleg Nesterov 	 * A fatal signal pending means that current will exit, so the new
17904a2c7a78SOleg Nesterov 	 * thread can't slip out of an OOM kill (or normal SIGKILL).
17914a2c7a78SOleg Nesterov 	*/
17924a2c7a78SOleg Nesterov 	recalc_sigpending();
17934a2c7a78SOleg Nesterov 	if (signal_pending(current)) {
17944a2c7a78SOleg Nesterov 		spin_unlock(&current->sighand->siglock);
17954a2c7a78SOleg Nesterov 		write_unlock_irq(&tasklist_lock);
17964a2c7a78SOleg Nesterov 		retval = -ERESTARTNOINTR;
17977e47682eSAleksa Sarai 		goto bad_fork_cancel_cgroup;
17984a2c7a78SOleg Nesterov 	}
17994a2c7a78SOleg Nesterov 
180073b9ebfeSOleg Nesterov 	if (likely(p->pid)) {
18014b9d33e6STejun Heo 		ptrace_init_task(p, (clone_flags & CLONE_PTRACE) || trace);
18021da177e4SLinus Torvalds 
180381907739SOleg Nesterov 		init_task_pid(p, PIDTYPE_PID, pid);
18041da177e4SLinus Torvalds 		if (thread_group_leader(p)) {
180581907739SOleg Nesterov 			init_task_pid(p, PIDTYPE_PGID, task_pgrp(current));
180681907739SOleg Nesterov 			init_task_pid(p, PIDTYPE_SID, task_session(current));
180781907739SOleg Nesterov 
18081c4042c2SEric W. Biederman 			if (is_child_reaper(pid)) {
180917cf22c3SEric W. Biederman 				ns_of_pid(pid)->child_reaper = p;
18101c4042c2SEric W. Biederman 				p->signal->flags |= SIGNAL_UNKILLABLE;
18111c4042c2SEric W. Biederman 			}
18125cd17569SEric W. Biederman 
1813fea9d175SOleg Nesterov 			p->signal->leader_pid = pid;
18149c9f4dedSAlan Cox 			p->signal->tty = tty_kref_get(current->signal->tty);
1815749860ceSPavel Tikhomirov 			/*
1816749860ceSPavel Tikhomirov 			 * Inherit has_child_subreaper flag under the same
1817749860ceSPavel Tikhomirov 			 * tasklist_lock with adding child to the process tree
1818749860ceSPavel Tikhomirov 			 * for propagate_has_child_subreaper optimization.
1819749860ceSPavel Tikhomirov 			 */
1820749860ceSPavel Tikhomirov 			p->signal->has_child_subreaper = p->real_parent->signal->has_child_subreaper ||
1821749860ceSPavel Tikhomirov 							 p->real_parent->signal->is_child_subreaper;
18229cd80bbbSOleg Nesterov 			list_add_tail(&p->sibling, &p->real_parent->children);
18235e85d4abSEric W. Biederman 			list_add_tail_rcu(&p->tasks, &init_task.tasks);
182481907739SOleg Nesterov 			attach_pid(p, PIDTYPE_PGID);
182581907739SOleg Nesterov 			attach_pid(p, PIDTYPE_SID);
1826909ea964SChristoph Lameter 			__this_cpu_inc(process_counts);
182780628ca0SOleg Nesterov 		} else {
182880628ca0SOleg Nesterov 			current->signal->nr_threads++;
182980628ca0SOleg Nesterov 			atomic_inc(&current->signal->live);
183080628ca0SOleg Nesterov 			atomic_inc(&current->signal->sigcnt);
183180628ca0SOleg Nesterov 			list_add_tail_rcu(&p->thread_group,
183280628ca0SOleg Nesterov 					  &p->group_leader->thread_group);
18330c740d0aSOleg Nesterov 			list_add_tail_rcu(&p->thread_node,
18340c740d0aSOleg Nesterov 					  &p->signal->thread_head);
18351da177e4SLinus Torvalds 		}
183681907739SOleg Nesterov 		attach_pid(p, PIDTYPE_PID);
18371da177e4SLinus Torvalds 		nr_threads++;
183873b9ebfeSOleg Nesterov 	}
183973b9ebfeSOleg Nesterov 
18401da177e4SLinus Torvalds 	total_forks++;
18413f17da69SOleg Nesterov 	spin_unlock(&current->sighand->siglock);
18424af4206bSOleg Nesterov 	syscall_tracepoint_update(p);
18431da177e4SLinus Torvalds 	write_unlock_irq(&tasklist_lock);
18444af4206bSOleg Nesterov 
1845c13cf856SAndrew Morton 	proc_fork_connector(p);
1846b53202e6SOleg Nesterov 	cgroup_post_fork(p);
1847780de9ddSIngo Molnar 	cgroup_threadgroup_change_end(current);
1848cdd6c482SIngo Molnar 	perf_event_fork(p);
184943d2b113SKAMEZAWA Hiroyuki 
185043d2b113SKAMEZAWA Hiroyuki 	trace_task_newtask(p, clone_flags);
18513ab67966SOleg Nesterov 	uprobe_copy_process(p, clone_flags);
185243d2b113SKAMEZAWA Hiroyuki 
18531da177e4SLinus Torvalds 	return p;
18541da177e4SLinus Torvalds 
18557e47682eSAleksa Sarai bad_fork_cancel_cgroup:
1856b53202e6SOleg Nesterov 	cgroup_cancel_fork(p);
1857425fb2b4SPavel Emelyanov bad_fork_free_pid:
1858780de9ddSIngo Molnar 	cgroup_threadgroup_change_end(current);
1859425fb2b4SPavel Emelyanov 	if (pid != &init_struct_pid)
1860425fb2b4SPavel Emelyanov 		free_pid(pid);
18610740aa5fSJiri Slaby bad_fork_cleanup_thread:
18620740aa5fSJiri Slaby 	exit_thread(p);
1863fd0928dfSJens Axboe bad_fork_cleanup_io:
1864b69f2292SLouis Rilling 	if (p->io_context)
1865b69f2292SLouis Rilling 		exit_io_context(p);
1866ab516013SSerge E. Hallyn bad_fork_cleanup_namespaces:
1867444f378bSLinus Torvalds 	exit_task_namespaces(p);
18681da177e4SLinus Torvalds bad_fork_cleanup_mm:
1869c9f01245SDavid Rientjes 	if (p->mm)
18701da177e4SLinus Torvalds 		mmput(p->mm);
18711da177e4SLinus Torvalds bad_fork_cleanup_signal:
18724ab6c083SOleg Nesterov 	if (!(clone_flags & CLONE_THREAD))
18731c5354deSMike Galbraith 		free_signal_struct(p->signal);
18741da177e4SLinus Torvalds bad_fork_cleanup_sighand:
1875a7e5328aSOleg Nesterov 	__cleanup_sighand(p->sighand);
18761da177e4SLinus Torvalds bad_fork_cleanup_fs:
18771da177e4SLinus Torvalds 	exit_fs(p); /* blocking */
18781da177e4SLinus Torvalds bad_fork_cleanup_files:
18791da177e4SLinus Torvalds 	exit_files(p); /* blocking */
18801da177e4SLinus Torvalds bad_fork_cleanup_semundo:
18811da177e4SLinus Torvalds 	exit_sem(p);
18821da177e4SLinus Torvalds bad_fork_cleanup_audit:
18831da177e4SLinus Torvalds 	audit_free(p);
18846c72e350SPeter Zijlstra bad_fork_cleanup_perf:
1885cdd6c482SIngo Molnar 	perf_event_free_task(p);
18866c72e350SPeter Zijlstra bad_fork_cleanup_policy:
18871da177e4SLinus Torvalds #ifdef CONFIG_NUMA
1888f0be3d32SLee Schermerhorn 	mpol_put(p->mempolicy);
1889e8604cb4SLi Zefan bad_fork_cleanup_threadgroup_lock:
18901da177e4SLinus Torvalds #endif
189135df17c5SShailabh Nagar 	delayacct_tsk_free(p);
18921da177e4SLinus Torvalds bad_fork_cleanup_count:
1893d84f4f99SDavid Howells 	atomic_dec(&p->cred->user->processes);
1894e0e81739SDavid Howells 	exit_creds(p);
18951da177e4SLinus Torvalds bad_fork_free:
1896405c0759SAndy Lutomirski 	p->state = TASK_DEAD;
189768f24b08SAndy Lutomirski 	put_task_stack(p);
18981da177e4SLinus Torvalds 	free_task(p);
1899fe7d37d1SOleg Nesterov fork_out:
1900fe7d37d1SOleg Nesterov 	return ERR_PTR(retval);
19011da177e4SLinus Torvalds }
19021da177e4SLinus Torvalds 
1903f106eee1SOleg Nesterov static inline void init_idle_pids(struct pid_link *links)
1904f106eee1SOleg Nesterov {
1905f106eee1SOleg Nesterov 	enum pid_type type;
1906f106eee1SOleg Nesterov 
1907f106eee1SOleg Nesterov 	for (type = PIDTYPE_PID; type < PIDTYPE_MAX; ++type) {
1908f106eee1SOleg Nesterov 		INIT_HLIST_NODE(&links[type].node); /* not really needed */
1909f106eee1SOleg Nesterov 		links[type].pid = &init_struct_pid;
1910f106eee1SOleg Nesterov 	}
1911f106eee1SOleg Nesterov }
1912f106eee1SOleg Nesterov 
19130db0628dSPaul Gortmaker struct task_struct *fork_idle(int cpu)
19141da177e4SLinus Torvalds {
191536c8b586SIngo Molnar 	struct task_struct *task;
1916725fc629SAndi Kleen 	task = copy_process(CLONE_VM, 0, 0, NULL, &init_struct_pid, 0, 0,
1917725fc629SAndi Kleen 			    cpu_to_node(cpu));
1918f106eee1SOleg Nesterov 	if (!IS_ERR(task)) {
1919f106eee1SOleg Nesterov 		init_idle_pids(task->pids);
19201da177e4SLinus Torvalds 		init_idle(task, cpu);
1921f106eee1SOleg Nesterov 	}
192273b9ebfeSOleg Nesterov 
19231da177e4SLinus Torvalds 	return task;
19241da177e4SLinus Torvalds }
19251da177e4SLinus Torvalds 
19261da177e4SLinus Torvalds /*
19271da177e4SLinus Torvalds  *  Ok, this is the main fork-routine.
19281da177e4SLinus Torvalds  *
19291da177e4SLinus Torvalds  * It copies the process, and if successful kick-starts
19301da177e4SLinus Torvalds  * it and waits for it to finish using the VM if required.
19311da177e4SLinus Torvalds  */
19323033f14aSJosh Triplett long _do_fork(unsigned long clone_flags,
19331da177e4SLinus Torvalds 	      unsigned long stack_start,
19341da177e4SLinus Torvalds 	      unsigned long stack_size,
19351da177e4SLinus Torvalds 	      int __user *parent_tidptr,
19363033f14aSJosh Triplett 	      int __user *child_tidptr,
19373033f14aSJosh Triplett 	      unsigned long tls)
19381da177e4SLinus Torvalds {
19391da177e4SLinus Torvalds 	struct task_struct *p;
19401da177e4SLinus Torvalds 	int trace = 0;
194192476d7fSEric W. Biederman 	long nr;
19421da177e4SLinus Torvalds 
1943bdff746aSAndrew Morton 	/*
19444b9d33e6STejun Heo 	 * Determine whether and which event to report to ptracer.  When
19454b9d33e6STejun Heo 	 * called from kernel_thread or CLONE_UNTRACED is explicitly
19464b9d33e6STejun Heo 	 * requested, no event is reported; otherwise, report if the event
19474b9d33e6STejun Heo 	 * for the type of forking is enabled.
194809a05394SRoland McGrath 	 */
1949e80d6661SAl Viro 	if (!(clone_flags & CLONE_UNTRACED)) {
19504b9d33e6STejun Heo 		if (clone_flags & CLONE_VFORK)
19514b9d33e6STejun Heo 			trace = PTRACE_EVENT_VFORK;
19524b9d33e6STejun Heo 		else if ((clone_flags & CSIGNAL) != SIGCHLD)
19534b9d33e6STejun Heo 			trace = PTRACE_EVENT_CLONE;
19544b9d33e6STejun Heo 		else
19554b9d33e6STejun Heo 			trace = PTRACE_EVENT_FORK;
19564b9d33e6STejun Heo 
19574b9d33e6STejun Heo 		if (likely(!ptrace_event_enabled(current, trace)))
19584b9d33e6STejun Heo 			trace = 0;
19594b9d33e6STejun Heo 	}
19601da177e4SLinus Torvalds 
196162e791c1SAl Viro 	p = copy_process(clone_flags, stack_start, stack_size,
1962725fc629SAndi Kleen 			 child_tidptr, NULL, trace, tls, NUMA_NO_NODE);
196338addce8SEmese Revfy 	add_latent_entropy();
19641da177e4SLinus Torvalds 	/*
19651da177e4SLinus Torvalds 	 * Do this prior waking up the new thread - the thread pointer
19661da177e4SLinus Torvalds 	 * might get invalid after that point, if the thread exits quickly.
19671da177e4SLinus Torvalds 	 */
19681da177e4SLinus Torvalds 	if (!IS_ERR(p)) {
19691da177e4SLinus Torvalds 		struct completion vfork;
19704e52365fSMatthew Dempsky 		struct pid *pid;
19711da177e4SLinus Torvalds 
19720a16b607SMathieu Desnoyers 		trace_sched_process_fork(current, p);
19730a16b607SMathieu Desnoyers 
19744e52365fSMatthew Dempsky 		pid = get_task_pid(p, PIDTYPE_PID);
19754e52365fSMatthew Dempsky 		nr = pid_vnr(pid);
197630e49c26SPavel Emelyanov 
197730e49c26SPavel Emelyanov 		if (clone_flags & CLONE_PARENT_SETTID)
197830e49c26SPavel Emelyanov 			put_user(nr, parent_tidptr);
1979a6f5e063SSukadev Bhattiprolu 
19801da177e4SLinus Torvalds 		if (clone_flags & CLONE_VFORK) {
19811da177e4SLinus Torvalds 			p->vfork_done = &vfork;
19821da177e4SLinus Torvalds 			init_completion(&vfork);
1983d68b46feSOleg Nesterov 			get_task_struct(p);
19841da177e4SLinus Torvalds 		}
19851da177e4SLinus Torvalds 
19863e51e3edSSamir Bellabes 		wake_up_new_task(p);
19871da177e4SLinus Torvalds 
19884b9d33e6STejun Heo 		/* forking complete and child started to run, tell ptracer */
19894b9d33e6STejun Heo 		if (unlikely(trace))
19904e52365fSMatthew Dempsky 			ptrace_event_pid(trace, pid);
199109a05394SRoland McGrath 
19921da177e4SLinus Torvalds 		if (clone_flags & CLONE_VFORK) {
1993d68b46feSOleg Nesterov 			if (!wait_for_vfork_done(p, &vfork))
19944e52365fSMatthew Dempsky 				ptrace_event_pid(PTRACE_EVENT_VFORK_DONE, pid);
19959f59ce5dSChuck Ebbert 		}
19964e52365fSMatthew Dempsky 
19974e52365fSMatthew Dempsky 		put_pid(pid);
19981da177e4SLinus Torvalds 	} else {
199992476d7fSEric W. Biederman 		nr = PTR_ERR(p);
20001da177e4SLinus Torvalds 	}
200192476d7fSEric W. Biederman 	return nr;
20021da177e4SLinus Torvalds }
20031da177e4SLinus Torvalds 
20043033f14aSJosh Triplett #ifndef CONFIG_HAVE_COPY_THREAD_TLS
20053033f14aSJosh Triplett /* For compatibility with architectures that call do_fork directly rather than
20063033f14aSJosh Triplett  * using the syscall entry points below. */
20073033f14aSJosh Triplett long do_fork(unsigned long clone_flags,
20083033f14aSJosh Triplett 	      unsigned long stack_start,
20093033f14aSJosh Triplett 	      unsigned long stack_size,
20103033f14aSJosh Triplett 	      int __user *parent_tidptr,
20113033f14aSJosh Triplett 	      int __user *child_tidptr)
20123033f14aSJosh Triplett {
20133033f14aSJosh Triplett 	return _do_fork(clone_flags, stack_start, stack_size,
20143033f14aSJosh Triplett 			parent_tidptr, child_tidptr, 0);
20153033f14aSJosh Triplett }
20163033f14aSJosh Triplett #endif
20173033f14aSJosh Triplett 
20182aa3a7f8SAl Viro /*
20192aa3a7f8SAl Viro  * Create a kernel thread.
20202aa3a7f8SAl Viro  */
20212aa3a7f8SAl Viro pid_t kernel_thread(int (*fn)(void *), void *arg, unsigned long flags)
20222aa3a7f8SAl Viro {
20233033f14aSJosh Triplett 	return _do_fork(flags|CLONE_VM|CLONE_UNTRACED, (unsigned long)fn,
20243033f14aSJosh Triplett 		(unsigned long)arg, NULL, NULL, 0);
20252aa3a7f8SAl Viro }
20262aa3a7f8SAl Viro 
2027d2125043SAl Viro #ifdef __ARCH_WANT_SYS_FORK
2028d2125043SAl Viro SYSCALL_DEFINE0(fork)
2029d2125043SAl Viro {
2030d2125043SAl Viro #ifdef CONFIG_MMU
20313033f14aSJosh Triplett 	return _do_fork(SIGCHLD, 0, 0, NULL, NULL, 0);
2032d2125043SAl Viro #else
2033d2125043SAl Viro 	/* can not support in nommu mode */
20345d59e182SDaeseok Youn 	return -EINVAL;
2035d2125043SAl Viro #endif
2036d2125043SAl Viro }
2037d2125043SAl Viro #endif
2038d2125043SAl Viro 
2039d2125043SAl Viro #ifdef __ARCH_WANT_SYS_VFORK
2040d2125043SAl Viro SYSCALL_DEFINE0(vfork)
2041d2125043SAl Viro {
20423033f14aSJosh Triplett 	return _do_fork(CLONE_VFORK | CLONE_VM | SIGCHLD, 0,
20433033f14aSJosh Triplett 			0, NULL, NULL, 0);
2044d2125043SAl Viro }
2045d2125043SAl Viro #endif
2046d2125043SAl Viro 
2047d2125043SAl Viro #ifdef __ARCH_WANT_SYS_CLONE
2048d2125043SAl Viro #ifdef CONFIG_CLONE_BACKWARDS
2049d2125043SAl Viro SYSCALL_DEFINE5(clone, unsigned long, clone_flags, unsigned long, newsp,
2050d2125043SAl Viro 		 int __user *, parent_tidptr,
20513033f14aSJosh Triplett 		 unsigned long, tls,
2052d2125043SAl Viro 		 int __user *, child_tidptr)
2053d2125043SAl Viro #elif defined(CONFIG_CLONE_BACKWARDS2)
2054d2125043SAl Viro SYSCALL_DEFINE5(clone, unsigned long, newsp, unsigned long, clone_flags,
2055d2125043SAl Viro 		 int __user *, parent_tidptr,
2056d2125043SAl Viro 		 int __user *, child_tidptr,
20573033f14aSJosh Triplett 		 unsigned long, tls)
2058dfa9771aSMichal Simek #elif defined(CONFIG_CLONE_BACKWARDS3)
2059dfa9771aSMichal Simek SYSCALL_DEFINE6(clone, unsigned long, clone_flags, unsigned long, newsp,
2060dfa9771aSMichal Simek 		int, stack_size,
2061dfa9771aSMichal Simek 		int __user *, parent_tidptr,
2062dfa9771aSMichal Simek 		int __user *, child_tidptr,
20633033f14aSJosh Triplett 		unsigned long, tls)
2064d2125043SAl Viro #else
2065d2125043SAl Viro SYSCALL_DEFINE5(clone, unsigned long, clone_flags, unsigned long, newsp,
2066d2125043SAl Viro 		 int __user *, parent_tidptr,
2067d2125043SAl Viro 		 int __user *, child_tidptr,
20683033f14aSJosh Triplett 		 unsigned long, tls)
2069d2125043SAl Viro #endif
2070d2125043SAl Viro {
20713033f14aSJosh Triplett 	return _do_fork(clone_flags, newsp, 0, parent_tidptr, child_tidptr, tls);
2072d2125043SAl Viro }
2073d2125043SAl Viro #endif
2074d2125043SAl Viro 
20750f1b92cbSOleg Nesterov void walk_process_tree(struct task_struct *top, proc_visitor visitor, void *data)
20760f1b92cbSOleg Nesterov {
20770f1b92cbSOleg Nesterov 	struct task_struct *leader, *parent, *child;
20780f1b92cbSOleg Nesterov 	int res;
20790f1b92cbSOleg Nesterov 
20800f1b92cbSOleg Nesterov 	read_lock(&tasklist_lock);
20810f1b92cbSOleg Nesterov 	leader = top = top->group_leader;
20820f1b92cbSOleg Nesterov down:
20830f1b92cbSOleg Nesterov 	for_each_thread(leader, parent) {
20840f1b92cbSOleg Nesterov 		list_for_each_entry(child, &parent->children, sibling) {
20850f1b92cbSOleg Nesterov 			res = visitor(child, data);
20860f1b92cbSOleg Nesterov 			if (res) {
20870f1b92cbSOleg Nesterov 				if (res < 0)
20880f1b92cbSOleg Nesterov 					goto out;
20890f1b92cbSOleg Nesterov 				leader = child;
20900f1b92cbSOleg Nesterov 				goto down;
20910f1b92cbSOleg Nesterov 			}
20920f1b92cbSOleg Nesterov up:
20930f1b92cbSOleg Nesterov 			;
20940f1b92cbSOleg Nesterov 		}
20950f1b92cbSOleg Nesterov 	}
20960f1b92cbSOleg Nesterov 
20970f1b92cbSOleg Nesterov 	if (leader != top) {
20980f1b92cbSOleg Nesterov 		child = leader;
20990f1b92cbSOleg Nesterov 		parent = child->real_parent;
21000f1b92cbSOleg Nesterov 		leader = parent->group_leader;
21010f1b92cbSOleg Nesterov 		goto up;
21020f1b92cbSOleg Nesterov 	}
21030f1b92cbSOleg Nesterov out:
21040f1b92cbSOleg Nesterov 	read_unlock(&tasklist_lock);
21050f1b92cbSOleg Nesterov }
21060f1b92cbSOleg Nesterov 
21075fd63b30SRavikiran G Thirumalai #ifndef ARCH_MIN_MMSTRUCT_ALIGN
21085fd63b30SRavikiran G Thirumalai #define ARCH_MIN_MMSTRUCT_ALIGN 0
21095fd63b30SRavikiran G Thirumalai #endif
21105fd63b30SRavikiran G Thirumalai 
211151cc5068SAlexey Dobriyan static void sighand_ctor(void *data)
2112aa1757f9SOleg Nesterov {
2113aa1757f9SOleg Nesterov 	struct sighand_struct *sighand = data;
2114aa1757f9SOleg Nesterov 
2115aa1757f9SOleg Nesterov 	spin_lock_init(&sighand->siglock);
2116b8fceee1SDavide Libenzi 	init_waitqueue_head(&sighand->signalfd_wqh);
2117fba2afaaSDavide Libenzi }
2118aa1757f9SOleg Nesterov 
21191da177e4SLinus Torvalds void __init proc_caches_init(void)
21201da177e4SLinus Torvalds {
21211da177e4SLinus Torvalds 	sighand_cachep = kmem_cache_create("sighand_cache",
21221da177e4SLinus Torvalds 			sizeof(struct sighand_struct), 0,
21232dff4405SVegard Nossum 			SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_DESTROY_BY_RCU|
21245d097056SVladimir Davydov 			SLAB_NOTRACK|SLAB_ACCOUNT, sighand_ctor);
21251da177e4SLinus Torvalds 	signal_cachep = kmem_cache_create("signal_cache",
21261da177e4SLinus Torvalds 			sizeof(struct signal_struct), 0,
21275d097056SVladimir Davydov 			SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_NOTRACK|SLAB_ACCOUNT,
21285d097056SVladimir Davydov 			NULL);
21291da177e4SLinus Torvalds 	files_cachep = kmem_cache_create("files_cache",
21301da177e4SLinus Torvalds 			sizeof(struct files_struct), 0,
21315d097056SVladimir Davydov 			SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_NOTRACK|SLAB_ACCOUNT,
21325d097056SVladimir Davydov 			NULL);
21331da177e4SLinus Torvalds 	fs_cachep = kmem_cache_create("fs_cache",
21341da177e4SLinus Torvalds 			sizeof(struct fs_struct), 0,
21355d097056SVladimir Davydov 			SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_NOTRACK|SLAB_ACCOUNT,
21365d097056SVladimir Davydov 			NULL);
21376345d24dSLinus Torvalds 	/*
21386345d24dSLinus Torvalds 	 * FIXME! The "sizeof(struct mm_struct)" currently includes the
21396345d24dSLinus Torvalds 	 * whole struct cpumask for the OFFSTACK case. We could change
21406345d24dSLinus Torvalds 	 * this to *only* allocate as much of it as required by the
21416345d24dSLinus Torvalds 	 * maximum number of CPU's we can ever have.  The cpumask_allocation
21426345d24dSLinus Torvalds 	 * is at the end of the structure, exactly for that reason.
21436345d24dSLinus Torvalds 	 */
21441da177e4SLinus Torvalds 	mm_cachep = kmem_cache_create("mm_struct",
21455fd63b30SRavikiran G Thirumalai 			sizeof(struct mm_struct), ARCH_MIN_MMSTRUCT_ALIGN,
21465d097056SVladimir Davydov 			SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_NOTRACK|SLAB_ACCOUNT,
21475d097056SVladimir Davydov 			NULL);
21485d097056SVladimir Davydov 	vm_area_cachep = KMEM_CACHE(vm_area_struct, SLAB_PANIC|SLAB_ACCOUNT);
21498feae131SDavid Howells 	mmap_init();
215066577193SAl Viro 	nsproxy_cache_init();
21511da177e4SLinus Torvalds }
2152cf2e340fSJANAK DESAI 
2153cf2e340fSJANAK DESAI /*
21549bfb23fcSOleg Nesterov  * Check constraints on flags passed to the unshare system call.
2155cf2e340fSJANAK DESAI  */
21569bfb23fcSOleg Nesterov static int check_unshare_flags(unsigned long unshare_flags)
2157cf2e340fSJANAK DESAI {
21589bfb23fcSOleg Nesterov 	if (unshare_flags & ~(CLONE_THREAD|CLONE_FS|CLONE_NEWNS|CLONE_SIGHAND|
21599bfb23fcSOleg Nesterov 				CLONE_VM|CLONE_FILES|CLONE_SYSVSEM|
216050804fe3SEric W. Biederman 				CLONE_NEWUTS|CLONE_NEWIPC|CLONE_NEWNET|
2161a79a908fSAditya Kali 				CLONE_NEWUSER|CLONE_NEWPID|CLONE_NEWCGROUP))
2162cf2e340fSJANAK DESAI 		return -EINVAL;
21639bfb23fcSOleg Nesterov 	/*
216412c641abSEric W. Biederman 	 * Not implemented, but pretend it works if there is nothing
216512c641abSEric W. Biederman 	 * to unshare.  Note that unsharing the address space or the
216612c641abSEric W. Biederman 	 * signal handlers also need to unshare the signal queues (aka
216712c641abSEric W. Biederman 	 * CLONE_THREAD).
21689bfb23fcSOleg Nesterov 	 */
21699bfb23fcSOleg Nesterov 	if (unshare_flags & (CLONE_THREAD | CLONE_SIGHAND | CLONE_VM)) {
217012c641abSEric W. Biederman 		if (!thread_group_empty(current))
217112c641abSEric W. Biederman 			return -EINVAL;
217212c641abSEric W. Biederman 	}
217312c641abSEric W. Biederman 	if (unshare_flags & (CLONE_SIGHAND | CLONE_VM)) {
217412c641abSEric W. Biederman 		if (atomic_read(&current->sighand->count) > 1)
217512c641abSEric W. Biederman 			return -EINVAL;
217612c641abSEric W. Biederman 	}
217712c641abSEric W. Biederman 	if (unshare_flags & CLONE_VM) {
217812c641abSEric W. Biederman 		if (!current_is_single_threaded())
21799bfb23fcSOleg Nesterov 			return -EINVAL;
21809bfb23fcSOleg Nesterov 	}
2181cf2e340fSJANAK DESAI 
2182cf2e340fSJANAK DESAI 	return 0;
2183cf2e340fSJANAK DESAI }
2184cf2e340fSJANAK DESAI 
2185cf2e340fSJANAK DESAI /*
218699d1419dSJANAK DESAI  * Unshare the filesystem structure if it is being shared
2187cf2e340fSJANAK DESAI  */
2188cf2e340fSJANAK DESAI static int unshare_fs(unsigned long unshare_flags, struct fs_struct **new_fsp)
2189cf2e340fSJANAK DESAI {
2190cf2e340fSJANAK DESAI 	struct fs_struct *fs = current->fs;
2191cf2e340fSJANAK DESAI 
2192498052bbSAl Viro 	if (!(unshare_flags & CLONE_FS) || !fs)
2193498052bbSAl Viro 		return 0;
2194498052bbSAl Viro 
2195498052bbSAl Viro 	/* don't need lock here; in the worst case we'll do useless copy */
2196498052bbSAl Viro 	if (fs->users == 1)
2197498052bbSAl Viro 		return 0;
2198498052bbSAl Viro 
2199498052bbSAl Viro 	*new_fsp = copy_fs_struct(fs);
220099d1419dSJANAK DESAI 	if (!*new_fsp)
220199d1419dSJANAK DESAI 		return -ENOMEM;
2202cf2e340fSJANAK DESAI 
2203cf2e340fSJANAK DESAI 	return 0;
2204cf2e340fSJANAK DESAI }
2205cf2e340fSJANAK DESAI 
2206cf2e340fSJANAK DESAI /*
2207a016f338SJANAK DESAI  * Unshare file descriptor table if it is being shared
2208cf2e340fSJANAK DESAI  */
2209cf2e340fSJANAK DESAI static int unshare_fd(unsigned long unshare_flags, struct files_struct **new_fdp)
2210cf2e340fSJANAK DESAI {
2211cf2e340fSJANAK DESAI 	struct files_struct *fd = current->files;
2212a016f338SJANAK DESAI 	int error = 0;
2213cf2e340fSJANAK DESAI 
2214cf2e340fSJANAK DESAI 	if ((unshare_flags & CLONE_FILES) &&
2215a016f338SJANAK DESAI 	    (fd && atomic_read(&fd->count) > 1)) {
2216a016f338SJANAK DESAI 		*new_fdp = dup_fd(fd, &error);
2217a016f338SJANAK DESAI 		if (!*new_fdp)
2218a016f338SJANAK DESAI 			return error;
2219a016f338SJANAK DESAI 	}
2220cf2e340fSJANAK DESAI 
2221cf2e340fSJANAK DESAI 	return 0;
2222cf2e340fSJANAK DESAI }
2223cf2e340fSJANAK DESAI 
2224cf2e340fSJANAK DESAI /*
2225cf2e340fSJANAK DESAI  * unshare allows a process to 'unshare' part of the process
2226cf2e340fSJANAK DESAI  * context which was originally shared using clone.  copy_*
2227cf2e340fSJANAK DESAI  * functions used by do_fork() cannot be used here directly
2228cf2e340fSJANAK DESAI  * because they modify an inactive task_struct that is being
2229cf2e340fSJANAK DESAI  * constructed. Here we are modifying the current, active,
2230cf2e340fSJANAK DESAI  * task_struct.
2231cf2e340fSJANAK DESAI  */
22326559eed8SHeiko Carstens SYSCALL_DEFINE1(unshare, unsigned long, unshare_flags)
2233cf2e340fSJANAK DESAI {
2234cf2e340fSJANAK DESAI 	struct fs_struct *fs, *new_fs = NULL;
2235cf2e340fSJANAK DESAI 	struct files_struct *fd, *new_fd = NULL;
2236b2e0d987SEric W. Biederman 	struct cred *new_cred = NULL;
2237cf7b708cSPavel Emelyanov 	struct nsproxy *new_nsproxy = NULL;
22389edff4abSManfred Spraul 	int do_sysvsem = 0;
22399bfb23fcSOleg Nesterov 	int err;
2240cf2e340fSJANAK DESAI 
224150804fe3SEric W. Biederman 	/*
2242faf00da5SEric W. Biederman 	 * If unsharing a user namespace must also unshare the thread group
2243faf00da5SEric W. Biederman 	 * and unshare the filesystem root and working directories.
2244b2e0d987SEric W. Biederman 	 */
2245b2e0d987SEric W. Biederman 	if (unshare_flags & CLONE_NEWUSER)
2246e66eded8SEric W. Biederman 		unshare_flags |= CLONE_THREAD | CLONE_FS;
2247b2e0d987SEric W. Biederman 	/*
224850804fe3SEric W. Biederman 	 * If unsharing vm, must also unshare signal handlers.
224950804fe3SEric W. Biederman 	 */
225050804fe3SEric W. Biederman 	if (unshare_flags & CLONE_VM)
225150804fe3SEric W. Biederman 		unshare_flags |= CLONE_SIGHAND;
22526013f67fSManfred Spraul 	/*
225312c641abSEric W. Biederman 	 * If unsharing a signal handlers, must also unshare the signal queues.
225412c641abSEric W. Biederman 	 */
225512c641abSEric W. Biederman 	if (unshare_flags & CLONE_SIGHAND)
225612c641abSEric W. Biederman 		unshare_flags |= CLONE_THREAD;
225712c641abSEric W. Biederman 	/*
22589bfb23fcSOleg Nesterov 	 * If unsharing namespace, must also unshare filesystem information.
22599bfb23fcSOleg Nesterov 	 */
22609bfb23fcSOleg Nesterov 	if (unshare_flags & CLONE_NEWNS)
22619bfb23fcSOleg Nesterov 		unshare_flags |= CLONE_FS;
226250804fe3SEric W. Biederman 
226350804fe3SEric W. Biederman 	err = check_unshare_flags(unshare_flags);
226450804fe3SEric W. Biederman 	if (err)
226550804fe3SEric W. Biederman 		goto bad_unshare_out;
22669bfb23fcSOleg Nesterov 	/*
22676013f67fSManfred Spraul 	 * CLONE_NEWIPC must also detach from the undolist: after switching
22686013f67fSManfred Spraul 	 * to a new ipc namespace, the semaphore arrays from the old
22696013f67fSManfred Spraul 	 * namespace are unreachable.
22706013f67fSManfred Spraul 	 */
22716013f67fSManfred Spraul 	if (unshare_flags & (CLONE_NEWIPC|CLONE_SYSVSEM))
22729edff4abSManfred Spraul 		do_sysvsem = 1;
2273fb0a685cSDaniel Rebelo de Oliveira 	err = unshare_fs(unshare_flags, &new_fs);
2274fb0a685cSDaniel Rebelo de Oliveira 	if (err)
22759bfb23fcSOleg Nesterov 		goto bad_unshare_out;
2276fb0a685cSDaniel Rebelo de Oliveira 	err = unshare_fd(unshare_flags, &new_fd);
2277fb0a685cSDaniel Rebelo de Oliveira 	if (err)
22789bfb23fcSOleg Nesterov 		goto bad_unshare_cleanup_fs;
2279b2e0d987SEric W. Biederman 	err = unshare_userns(unshare_flags, &new_cred);
2280fb0a685cSDaniel Rebelo de Oliveira 	if (err)
22819edff4abSManfred Spraul 		goto bad_unshare_cleanup_fd;
2282b2e0d987SEric W. Biederman 	err = unshare_nsproxy_namespaces(unshare_flags, &new_nsproxy,
2283b2e0d987SEric W. Biederman 					 new_cred, new_fs);
2284b2e0d987SEric W. Biederman 	if (err)
2285b2e0d987SEric W. Biederman 		goto bad_unshare_cleanup_cred;
2286cf2e340fSJANAK DESAI 
2287b2e0d987SEric W. Biederman 	if (new_fs || new_fd || do_sysvsem || new_cred || new_nsproxy) {
22889edff4abSManfred Spraul 		if (do_sysvsem) {
22899edff4abSManfred Spraul 			/*
22909edff4abSManfred Spraul 			 * CLONE_SYSVSEM is equivalent to sys_exit().
22919edff4abSManfred Spraul 			 */
22929edff4abSManfred Spraul 			exit_sem(current);
22939edff4abSManfred Spraul 		}
2294ab602f79SJack Miller 		if (unshare_flags & CLONE_NEWIPC) {
2295ab602f79SJack Miller 			/* Orphan segments in old ns (see sem above). */
2296ab602f79SJack Miller 			exit_shm(current);
2297ab602f79SJack Miller 			shm_init_task(current);
2298ab602f79SJack Miller 		}
2299ab516013SSerge E. Hallyn 
23006f977e6bSAlan Cox 		if (new_nsproxy)
2301cf7b708cSPavel Emelyanov 			switch_task_namespaces(current, new_nsproxy);
2302cf2e340fSJANAK DESAI 
2303cf7b708cSPavel Emelyanov 		task_lock(current);
2304cf7b708cSPavel Emelyanov 
2305cf2e340fSJANAK DESAI 		if (new_fs) {
2306cf2e340fSJANAK DESAI 			fs = current->fs;
23072a4419b5SNick Piggin 			spin_lock(&fs->lock);
2308cf2e340fSJANAK DESAI 			current->fs = new_fs;
2309498052bbSAl Viro 			if (--fs->users)
2310498052bbSAl Viro 				new_fs = NULL;
2311498052bbSAl Viro 			else
2312cf2e340fSJANAK DESAI 				new_fs = fs;
23132a4419b5SNick Piggin 			spin_unlock(&fs->lock);
2314cf2e340fSJANAK DESAI 		}
2315cf2e340fSJANAK DESAI 
2316cf2e340fSJANAK DESAI 		if (new_fd) {
2317cf2e340fSJANAK DESAI 			fd = current->files;
2318cf2e340fSJANAK DESAI 			current->files = new_fd;
2319cf2e340fSJANAK DESAI 			new_fd = fd;
2320cf2e340fSJANAK DESAI 		}
2321cf2e340fSJANAK DESAI 
2322cf2e340fSJANAK DESAI 		task_unlock(current);
2323b2e0d987SEric W. Biederman 
2324b2e0d987SEric W. Biederman 		if (new_cred) {
2325b2e0d987SEric W. Biederman 			/* Install the new user namespace */
2326b2e0d987SEric W. Biederman 			commit_creds(new_cred);
2327b2e0d987SEric W. Biederman 			new_cred = NULL;
2328b2e0d987SEric W. Biederman 		}
2329cf2e340fSJANAK DESAI 	}
2330cf2e340fSJANAK DESAI 
2331b2e0d987SEric W. Biederman bad_unshare_cleanup_cred:
2332b2e0d987SEric W. Biederman 	if (new_cred)
2333b2e0d987SEric W. Biederman 		put_cred(new_cred);
2334cf2e340fSJANAK DESAI bad_unshare_cleanup_fd:
2335cf2e340fSJANAK DESAI 	if (new_fd)
2336cf2e340fSJANAK DESAI 		put_files_struct(new_fd);
2337cf2e340fSJANAK DESAI 
2338cf2e340fSJANAK DESAI bad_unshare_cleanup_fs:
2339cf2e340fSJANAK DESAI 	if (new_fs)
2340498052bbSAl Viro 		free_fs_struct(new_fs);
2341cf2e340fSJANAK DESAI 
2342cf2e340fSJANAK DESAI bad_unshare_out:
2343cf2e340fSJANAK DESAI 	return err;
2344cf2e340fSJANAK DESAI }
23453b125388SAl Viro 
23463b125388SAl Viro /*
23473b125388SAl Viro  *	Helper to unshare the files of the current task.
23483b125388SAl Viro  *	We don't want to expose copy_files internals to
23493b125388SAl Viro  *	the exec layer of the kernel.
23503b125388SAl Viro  */
23513b125388SAl Viro 
23523b125388SAl Viro int unshare_files(struct files_struct **displaced)
23533b125388SAl Viro {
23543b125388SAl Viro 	struct task_struct *task = current;
235550704516SAl Viro 	struct files_struct *copy = NULL;
23563b125388SAl Viro 	int error;
23573b125388SAl Viro 
23583b125388SAl Viro 	error = unshare_fd(CLONE_FILES, &copy);
23593b125388SAl Viro 	if (error || !copy) {
23603b125388SAl Viro 		*displaced = NULL;
23613b125388SAl Viro 		return error;
23623b125388SAl Viro 	}
23633b125388SAl Viro 	*displaced = task->files;
23643b125388SAl Viro 	task_lock(task);
23653b125388SAl Viro 	task->files = copy;
23663b125388SAl Viro 	task_unlock(task);
23673b125388SAl Viro 	return 0;
23683b125388SAl Viro }
236916db3d3fSHeinrich Schuchardt 
237016db3d3fSHeinrich Schuchardt int sysctl_max_threads(struct ctl_table *table, int write,
237116db3d3fSHeinrich Schuchardt 		       void __user *buffer, size_t *lenp, loff_t *ppos)
237216db3d3fSHeinrich Schuchardt {
237316db3d3fSHeinrich Schuchardt 	struct ctl_table t;
237416db3d3fSHeinrich Schuchardt 	int ret;
237516db3d3fSHeinrich Schuchardt 	int threads = max_threads;
237616db3d3fSHeinrich Schuchardt 	int min = MIN_THREADS;
237716db3d3fSHeinrich Schuchardt 	int max = MAX_THREADS;
237816db3d3fSHeinrich Schuchardt 
237916db3d3fSHeinrich Schuchardt 	t = *table;
238016db3d3fSHeinrich Schuchardt 	t.data = &threads;
238116db3d3fSHeinrich Schuchardt 	t.extra1 = &min;
238216db3d3fSHeinrich Schuchardt 	t.extra2 = &max;
238316db3d3fSHeinrich Schuchardt 
238416db3d3fSHeinrich Schuchardt 	ret = proc_dointvec_minmax(&t, write, buffer, lenp, ppos);
238516db3d3fSHeinrich Schuchardt 	if (ret || !write)
238616db3d3fSHeinrich Schuchardt 		return ret;
238716db3d3fSHeinrich Schuchardt 
238816db3d3fSHeinrich Schuchardt 	set_max_threads(threads);
238916db3d3fSHeinrich Schuchardt 
239016db3d3fSHeinrich Schuchardt 	return 0;
239116db3d3fSHeinrich Schuchardt }
2392