xref: /openbmc/linux/kernel/fork.c (revision eb414681d5a07d28d2ff90dc05f69ec6b232ebd2)
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>
154eb5aaa3SIngo Molnar #include <linux/sched/autogroup.h>
166e84f315SIngo Molnar #include <linux/sched/mm.h>
17f7ccbae4SIngo Molnar #include <linux/sched/coredump.h>
188703e8a4SIngo Molnar #include <linux/sched/user.h>
196a3827d7SIngo Molnar #include <linux/sched/numa_balancing.h>
2003441a34SIngo Molnar #include <linux/sched/stat.h>
2129930025SIngo Molnar #include <linux/sched/task.h>
2268db0cf1SIngo Molnar #include <linux/sched/task_stack.h>
2332ef5517SIngo Molnar #include <linux/sched/cputime.h>
24037741a6SIngo Molnar #include <linux/rtmutex.h>
251da177e4SLinus Torvalds #include <linux/init.h>
261da177e4SLinus Torvalds #include <linux/unistd.h>
271da177e4SLinus Torvalds #include <linux/module.h>
281da177e4SLinus Torvalds #include <linux/vmalloc.h>
291da177e4SLinus Torvalds #include <linux/completion.h>
301da177e4SLinus Torvalds #include <linux/personality.h>
311da177e4SLinus Torvalds #include <linux/mempolicy.h>
321da177e4SLinus Torvalds #include <linux/sem.h>
331da177e4SLinus Torvalds #include <linux/file.h>
349f3acc31SAl Viro #include <linux/fdtable.h>
35da9cbc87SJens Axboe #include <linux/iocontext.h>
361da177e4SLinus Torvalds #include <linux/key.h>
371da177e4SLinus Torvalds #include <linux/binfmts.h>
381da177e4SLinus Torvalds #include <linux/mman.h>
39cddb8a5cSAndrea Arcangeli #include <linux/mmu_notifier.h>
40133ff0eaSJérôme Glisse #include <linux/hmm.h>
411da177e4SLinus Torvalds #include <linux/fs.h>
42615d6e87SDavidlohr Bueso #include <linux/mm.h>
43615d6e87SDavidlohr Bueso #include <linux/vmacache.h>
44ab516013SSerge E. Hallyn #include <linux/nsproxy.h>
45c59ede7bSRandy.Dunlap #include <linux/capability.h>
461da177e4SLinus Torvalds #include <linux/cpu.h>
47b4f48b63SPaul Menage #include <linux/cgroup.h>
481da177e4SLinus Torvalds #include <linux/security.h>
49a1e78772SMel Gorman #include <linux/hugetlb.h>
50e2cfabdfSWill Drewry #include <linux/seccomp.h>
511da177e4SLinus Torvalds #include <linux/swap.h>
521da177e4SLinus Torvalds #include <linux/syscalls.h>
531da177e4SLinus Torvalds #include <linux/jiffies.h>
541da177e4SLinus Torvalds #include <linux/futex.h>
558141c7f3SLinus Torvalds #include <linux/compat.h>
56207205a2SEric Dumazet #include <linux/kthread.h>
577c3ab738SAndrew Morton #include <linux/task_io_accounting_ops.h>
58ab2af1f5SDipankar Sarma #include <linux/rcupdate.h>
591da177e4SLinus Torvalds #include <linux/ptrace.h>
601da177e4SLinus Torvalds #include <linux/mount.h>
611da177e4SLinus Torvalds #include <linux/audit.h>
6278fb7466SPavel Emelianov #include <linux/memcontrol.h>
63f201ae23SFrederic Weisbecker #include <linux/ftrace.h>
645e2bf014SMike Galbraith #include <linux/proc_fs.h>
651da177e4SLinus Torvalds #include <linux/profile.h>
661da177e4SLinus Torvalds #include <linux/rmap.h>
67f8af4da3SHugh Dickins #include <linux/ksm.h>
681da177e4SLinus Torvalds #include <linux/acct.h>
69893e26e6SPavel Emelyanov #include <linux/userfaultfd_k.h>
708f0ab514SJay Lan #include <linux/tsacct_kern.h>
719f46080cSMatt Helsley #include <linux/cn_proc.h>
72ba96a0c8SRafael J. Wysocki #include <linux/freezer.h>
73ca74e92bSShailabh Nagar #include <linux/delayacct.h>
74ad4ecbcbSShailabh Nagar #include <linux/taskstats_kern.h>
750a425405SArjan van de Ven #include <linux/random.h>
76522ed776SMiloslav Trmac #include <linux/tty.h>
77fd0928dfSJens Axboe #include <linux/blkdev.h>
785ad4e53bSAl Viro #include <linux/fs_struct.h>
797c9f8861SEric Sandeen #include <linux/magic.h>
80d70f2a14SAndrew Morton #include <linux/sched/mm.h>
81cdd6c482SIngo Molnar #include <linux/perf_event.h>
8242c4ab41SStanislaw Gruszka #include <linux/posix-timers.h>
838e7cac79SAvi Kivity #include <linux/user-return-notifier.h>
843d5992d2SYing Han #include <linux/oom.h>
85ba76149fSAndrea Arcangeli #include <linux/khugepaged.h>
86d80e731eSOleg Nesterov #include <linux/signalfd.h>
870326f5a9SSrikar Dronamraju #include <linux/uprobes.h>
88a27bb332SKent Overstreet #include <linux/aio.h>
8952f5684cSGideon Israel Dsouza #include <linux/compiler.h>
9016db3d3fSHeinrich Schuchardt #include <linux/sysctl.h>
915c9a8750SDmitry Vyukov #include <linux/kcov.h>
92d83a7cb3SJosh Poimboeuf #include <linux/livepatch.h>
9348ac3c18SMark Rutland #include <linux/thread_info.h>
941da177e4SLinus Torvalds 
951da177e4SLinus Torvalds #include <asm/pgtable.h>
961da177e4SLinus Torvalds #include <asm/pgalloc.h>
977c0f6ba6SLinus Torvalds #include <linux/uaccess.h>
981da177e4SLinus Torvalds #include <asm/mmu_context.h>
991da177e4SLinus Torvalds #include <asm/cacheflush.h>
1001da177e4SLinus Torvalds #include <asm/tlbflush.h>
1011da177e4SLinus Torvalds 
102ad8d75ffSSteven Rostedt #include <trace/events/sched.h>
103ad8d75ffSSteven Rostedt 
10443d2b113SKAMEZAWA Hiroyuki #define CREATE_TRACE_POINTS
10543d2b113SKAMEZAWA Hiroyuki #include <trace/events/task.h>
10643d2b113SKAMEZAWA Hiroyuki 
1071da177e4SLinus Torvalds /*
108ac1b398dSHeinrich Schuchardt  * Minimum number of threads to boot the kernel
109ac1b398dSHeinrich Schuchardt  */
110ac1b398dSHeinrich Schuchardt #define MIN_THREADS 20
111ac1b398dSHeinrich Schuchardt 
112ac1b398dSHeinrich Schuchardt /*
113ac1b398dSHeinrich Schuchardt  * Maximum number of threads
114ac1b398dSHeinrich Schuchardt  */
115ac1b398dSHeinrich Schuchardt #define MAX_THREADS FUTEX_TID_MASK
116ac1b398dSHeinrich Schuchardt 
117ac1b398dSHeinrich Schuchardt /*
1181da177e4SLinus Torvalds  * Protected counters by write_lock_irq(&tasklist_lock)
1191da177e4SLinus Torvalds  */
1201da177e4SLinus Torvalds unsigned long total_forks;	/* Handle normal Linux uptimes. */
1211da177e4SLinus Torvalds int nr_threads;			/* The idle threads do not count.. */
1221da177e4SLinus Torvalds 
1231da177e4SLinus Torvalds int max_threads;		/* tunable limit on nr_threads */
1241da177e4SLinus Torvalds 
1251da177e4SLinus Torvalds DEFINE_PER_CPU(unsigned long, process_counts) = 0;
1261da177e4SLinus Torvalds 
1271da177e4SLinus Torvalds __cacheline_aligned DEFINE_RWLOCK(tasklist_lock);  /* outer */
128db1466b3SPaul E. McKenney 
129db1466b3SPaul E. McKenney #ifdef CONFIG_PROVE_RCU
130db1466b3SPaul E. McKenney int lockdep_tasklist_lock_is_held(void)
131db1466b3SPaul E. McKenney {
132db1466b3SPaul E. McKenney 	return lockdep_is_held(&tasklist_lock);
133db1466b3SPaul E. McKenney }
134db1466b3SPaul E. McKenney EXPORT_SYMBOL_GPL(lockdep_tasklist_lock_is_held);
135db1466b3SPaul E. McKenney #endif /* #ifdef CONFIG_PROVE_RCU */
1361da177e4SLinus Torvalds 
1371da177e4SLinus Torvalds int nr_processes(void)
1381da177e4SLinus Torvalds {
1391da177e4SLinus Torvalds 	int cpu;
1401da177e4SLinus Torvalds 	int total = 0;
1411da177e4SLinus Torvalds 
1421d510750SIan Campbell 	for_each_possible_cpu(cpu)
1431da177e4SLinus Torvalds 		total += per_cpu(process_counts, cpu);
1441da177e4SLinus Torvalds 
1451da177e4SLinus Torvalds 	return total;
1461da177e4SLinus Torvalds }
1471da177e4SLinus Torvalds 
148f19b9f74SAkinobu Mita void __weak arch_release_task_struct(struct task_struct *tsk)
149f19b9f74SAkinobu Mita {
150f19b9f74SAkinobu Mita }
151f19b9f74SAkinobu Mita 
152f5e10287SThomas Gleixner #ifndef CONFIG_ARCH_TASK_STRUCT_ALLOCATOR
153e18b890bSChristoph Lameter static struct kmem_cache *task_struct_cachep;
15441101809SThomas Gleixner 
15541101809SThomas Gleixner static inline struct task_struct *alloc_task_struct_node(int node)
15641101809SThomas Gleixner {
15741101809SThomas Gleixner 	return kmem_cache_alloc_node(task_struct_cachep, GFP_KERNEL, node);
15841101809SThomas Gleixner }
15941101809SThomas Gleixner 
16041101809SThomas Gleixner static inline void free_task_struct(struct task_struct *tsk)
16141101809SThomas Gleixner {
16241101809SThomas Gleixner 	kmem_cache_free(task_struct_cachep, tsk);
16341101809SThomas Gleixner }
1641da177e4SLinus Torvalds #endif
1651da177e4SLinus Torvalds 
166b235beeaSLinus Torvalds void __weak arch_release_thread_stack(unsigned long *stack)
167f19b9f74SAkinobu Mita {
168f19b9f74SAkinobu Mita }
169f19b9f74SAkinobu Mita 
170b235beeaSLinus Torvalds #ifndef CONFIG_ARCH_THREAD_STACK_ALLOCATOR
17141101809SThomas Gleixner 
1720d15d74aSThomas Gleixner /*
1730d15d74aSThomas Gleixner  * Allocate pages if THREAD_SIZE is >= PAGE_SIZE, otherwise use a
1740d15d74aSThomas Gleixner  * kmemcache based allocator.
1750d15d74aSThomas Gleixner  */
176ba14a194SAndy Lutomirski # if THREAD_SIZE >= PAGE_SIZE || defined(CONFIG_VMAP_STACK)
177ac496bf4SAndy Lutomirski 
178ac496bf4SAndy Lutomirski #ifdef CONFIG_VMAP_STACK
179ac496bf4SAndy Lutomirski /*
180ac496bf4SAndy Lutomirski  * vmalloc() is a bit slow, and calling vfree() enough times will force a TLB
181ac496bf4SAndy Lutomirski  * flush.  Try to minimize the number of calls by caching stacks.
182ac496bf4SAndy Lutomirski  */
183ac496bf4SAndy Lutomirski #define NR_CACHED_STACKS 2
184ac496bf4SAndy Lutomirski static DEFINE_PER_CPU(struct vm_struct *, cached_stacks[NR_CACHED_STACKS]);
18519659c59SHoeun Ryu 
18619659c59SHoeun Ryu static int free_vm_stack_cache(unsigned int cpu)
18719659c59SHoeun Ryu {
18819659c59SHoeun Ryu 	struct vm_struct **cached_vm_stacks = per_cpu_ptr(cached_stacks, cpu);
18919659c59SHoeun Ryu 	int i;
19019659c59SHoeun Ryu 
19119659c59SHoeun Ryu 	for (i = 0; i < NR_CACHED_STACKS; i++) {
19219659c59SHoeun Ryu 		struct vm_struct *vm_stack = cached_vm_stacks[i];
19319659c59SHoeun Ryu 
19419659c59SHoeun Ryu 		if (!vm_stack)
19519659c59SHoeun Ryu 			continue;
19619659c59SHoeun Ryu 
19719659c59SHoeun Ryu 		vfree(vm_stack->addr);
19819659c59SHoeun Ryu 		cached_vm_stacks[i] = NULL;
19919659c59SHoeun Ryu 	}
20019659c59SHoeun Ryu 
20119659c59SHoeun Ryu 	return 0;
20219659c59SHoeun Ryu }
203ac496bf4SAndy Lutomirski #endif
204ac496bf4SAndy Lutomirski 
205ba14a194SAndy Lutomirski static unsigned long *alloc_thread_stack_node(struct task_struct *tsk, int node)
206b69c49b7SFUJITA Tomonori {
207ba14a194SAndy Lutomirski #ifdef CONFIG_VMAP_STACK
208ac496bf4SAndy Lutomirski 	void *stack;
209ac496bf4SAndy Lutomirski 	int i;
210ac496bf4SAndy Lutomirski 
211ac496bf4SAndy Lutomirski 	for (i = 0; i < NR_CACHED_STACKS; i++) {
212112166f8SChristoph Lameter 		struct vm_struct *s;
213112166f8SChristoph Lameter 
214112166f8SChristoph Lameter 		s = this_cpu_xchg(cached_stacks[i], NULL);
215ac496bf4SAndy Lutomirski 
216ac496bf4SAndy Lutomirski 		if (!s)
217ac496bf4SAndy Lutomirski 			continue;
218ac496bf4SAndy Lutomirski 
219ca182551SKonstantin Khlebnikov 		/* Clear stale pointers from reused stack. */
220ca182551SKonstantin Khlebnikov 		memset(s->addr, 0, THREAD_SIZE);
221e01e8063SKees Cook 
222ac496bf4SAndy Lutomirski 		tsk->stack_vm_area = s;
223ac496bf4SAndy Lutomirski 		return s->addr;
224ac496bf4SAndy Lutomirski 	}
225ac496bf4SAndy Lutomirski 
2269b6f7e16SRoman Gushchin 	/*
2279b6f7e16SRoman Gushchin 	 * Allocated stacks are cached and later reused by new threads,
2289b6f7e16SRoman Gushchin 	 * so memcg accounting is performed manually on assigning/releasing
2299b6f7e16SRoman Gushchin 	 * stacks to tasks. Drop __GFP_ACCOUNT.
2309b6f7e16SRoman Gushchin 	 */
23148ac3c18SMark Rutland 	stack = __vmalloc_node_range(THREAD_SIZE, THREAD_ALIGN,
232ba14a194SAndy Lutomirski 				     VMALLOC_START, VMALLOC_END,
2339b6f7e16SRoman Gushchin 				     THREADINFO_GFP & ~__GFP_ACCOUNT,
234ba14a194SAndy Lutomirski 				     PAGE_KERNEL,
235ac496bf4SAndy Lutomirski 				     0, node, __builtin_return_address(0));
236ba14a194SAndy Lutomirski 
237ba14a194SAndy Lutomirski 	/*
238ba14a194SAndy Lutomirski 	 * We can't call find_vm_area() in interrupt context, and
239ba14a194SAndy Lutomirski 	 * free_thread_stack() can be called in interrupt context,
240ba14a194SAndy Lutomirski 	 * so cache the vm_struct.
241ba14a194SAndy Lutomirski 	 */
242ba14a194SAndy Lutomirski 	if (stack)
243ba14a194SAndy Lutomirski 		tsk->stack_vm_area = find_vm_area(stack);
244ba14a194SAndy Lutomirski 	return stack;
245ba14a194SAndy Lutomirski #else
2464949148aSVladimir Davydov 	struct page *page = alloc_pages_node(node, THREADINFO_GFP,
2472889f608SThomas Gleixner 					     THREAD_SIZE_ORDER);
248b6a84016SEric Dumazet 
249b6a84016SEric Dumazet 	return page ? page_address(page) : NULL;
250ba14a194SAndy Lutomirski #endif
251b69c49b7SFUJITA Tomonori }
252b69c49b7SFUJITA Tomonori 
253ba14a194SAndy Lutomirski static inline void free_thread_stack(struct task_struct *tsk)
254b69c49b7SFUJITA Tomonori {
255ac496bf4SAndy Lutomirski #ifdef CONFIG_VMAP_STACK
2569b6f7e16SRoman Gushchin 	struct vm_struct *vm = task_stack_vm_area(tsk);
2579b6f7e16SRoman Gushchin 
2589b6f7e16SRoman Gushchin 	if (vm) {
259ac496bf4SAndy Lutomirski 		int i;
260ac496bf4SAndy Lutomirski 
2619b6f7e16SRoman Gushchin 		for (i = 0; i < THREAD_SIZE / PAGE_SIZE; i++) {
2629b6f7e16SRoman Gushchin 			mod_memcg_page_state(vm->pages[i],
2639b6f7e16SRoman Gushchin 					     MEMCG_KERNEL_STACK_KB,
2649b6f7e16SRoman Gushchin 					     -(int)(PAGE_SIZE / 1024));
2659b6f7e16SRoman Gushchin 
2669b6f7e16SRoman Gushchin 			memcg_kmem_uncharge(vm->pages[i], 0);
2679b6f7e16SRoman Gushchin 		}
2689b6f7e16SRoman Gushchin 
269ac496bf4SAndy Lutomirski 		for (i = 0; i < NR_CACHED_STACKS; i++) {
270112166f8SChristoph Lameter 			if (this_cpu_cmpxchg(cached_stacks[i],
271112166f8SChristoph Lameter 					NULL, tsk->stack_vm_area) != NULL)
272ac496bf4SAndy Lutomirski 				continue;
273ac496bf4SAndy Lutomirski 
274ac496bf4SAndy Lutomirski 			return;
275ac496bf4SAndy Lutomirski 		}
276ac496bf4SAndy Lutomirski 
2770f110a9bSAndrey Ryabinin 		vfree_atomic(tsk->stack);
278ac496bf4SAndy Lutomirski 		return;
279ac496bf4SAndy Lutomirski 	}
280ac496bf4SAndy Lutomirski #endif
281ac496bf4SAndy Lutomirski 
282ba14a194SAndy Lutomirski 	__free_pages(virt_to_page(tsk->stack), THREAD_SIZE_ORDER);
283b69c49b7SFUJITA Tomonori }
2840d15d74aSThomas Gleixner # else
285b235beeaSLinus Torvalds static struct kmem_cache *thread_stack_cache;
2860d15d74aSThomas Gleixner 
2879521d399SMichael Ellerman static unsigned long *alloc_thread_stack_node(struct task_struct *tsk,
2880d15d74aSThomas Gleixner 						  int node)
2890d15d74aSThomas Gleixner {
290b235beeaSLinus Torvalds 	return kmem_cache_alloc_node(thread_stack_cache, THREADINFO_GFP, node);
2910d15d74aSThomas Gleixner }
2920d15d74aSThomas Gleixner 
293ba14a194SAndy Lutomirski static void free_thread_stack(struct task_struct *tsk)
2940d15d74aSThomas Gleixner {
295ba14a194SAndy Lutomirski 	kmem_cache_free(thread_stack_cache, tsk->stack);
2960d15d74aSThomas Gleixner }
2970d15d74aSThomas Gleixner 
298b235beeaSLinus Torvalds void thread_stack_cache_init(void)
2990d15d74aSThomas Gleixner {
300f9d29946SDavid Windsor 	thread_stack_cache = kmem_cache_create_usercopy("thread_stack",
301f9d29946SDavid Windsor 					THREAD_SIZE, THREAD_SIZE, 0, 0,
302f9d29946SDavid Windsor 					THREAD_SIZE, NULL);
303b235beeaSLinus Torvalds 	BUG_ON(thread_stack_cache == NULL);
3040d15d74aSThomas Gleixner }
3050d15d74aSThomas Gleixner # endif
306b69c49b7SFUJITA Tomonori #endif
307b69c49b7SFUJITA Tomonori 
3081da177e4SLinus Torvalds /* SLAB cache for signal_struct structures (tsk->signal) */
309e18b890bSChristoph Lameter static struct kmem_cache *signal_cachep;
3101da177e4SLinus Torvalds 
3111da177e4SLinus Torvalds /* SLAB cache for sighand_struct structures (tsk->sighand) */
312e18b890bSChristoph Lameter struct kmem_cache *sighand_cachep;
3131da177e4SLinus Torvalds 
3141da177e4SLinus Torvalds /* SLAB cache for files_struct structures (tsk->files) */
315e18b890bSChristoph Lameter struct kmem_cache *files_cachep;
3161da177e4SLinus Torvalds 
3171da177e4SLinus Torvalds /* SLAB cache for fs_struct structures (tsk->fs) */
318e18b890bSChristoph Lameter struct kmem_cache *fs_cachep;
3191da177e4SLinus Torvalds 
3201da177e4SLinus Torvalds /* SLAB cache for vm_area_struct structures */
3213928d4f5SLinus Torvalds static struct kmem_cache *vm_area_cachep;
3221da177e4SLinus Torvalds 
3231da177e4SLinus Torvalds /* SLAB cache for mm_struct structures (tsk->mm) */
324e18b890bSChristoph Lameter static struct kmem_cache *mm_cachep;
3251da177e4SLinus Torvalds 
326490fc053SLinus Torvalds struct vm_area_struct *vm_area_alloc(struct mm_struct *mm)
3273928d4f5SLinus Torvalds {
328a670468fSAndrew Morton 	struct vm_area_struct *vma;
329490fc053SLinus Torvalds 
330a670468fSAndrew Morton 	vma = kmem_cache_alloc(vm_area_cachep, GFP_KERNEL);
331027232daSKirill A. Shutemov 	if (vma)
332027232daSKirill A. Shutemov 		vma_init(vma, mm);
333490fc053SLinus Torvalds 	return vma;
3343928d4f5SLinus Torvalds }
3353928d4f5SLinus Torvalds 
3363928d4f5SLinus Torvalds struct vm_area_struct *vm_area_dup(struct vm_area_struct *orig)
3373928d4f5SLinus Torvalds {
33895faf699SLinus Torvalds 	struct vm_area_struct *new = kmem_cache_alloc(vm_area_cachep, GFP_KERNEL);
33995faf699SLinus Torvalds 
34095faf699SLinus Torvalds 	if (new) {
34195faf699SLinus Torvalds 		*new = *orig;
34295faf699SLinus Torvalds 		INIT_LIST_HEAD(&new->anon_vma_chain);
34395faf699SLinus Torvalds 	}
34495faf699SLinus Torvalds 	return new;
3453928d4f5SLinus Torvalds }
3463928d4f5SLinus Torvalds 
3473928d4f5SLinus Torvalds void vm_area_free(struct vm_area_struct *vma)
3483928d4f5SLinus Torvalds {
3493928d4f5SLinus Torvalds 	kmem_cache_free(vm_area_cachep, vma);
3503928d4f5SLinus Torvalds }
3513928d4f5SLinus Torvalds 
352ba14a194SAndy Lutomirski static void account_kernel_stack(struct task_struct *tsk, int account)
353c6a7f572SKOSAKI Motohiro {
354ba14a194SAndy Lutomirski 	void *stack = task_stack_page(tsk);
355ba14a194SAndy Lutomirski 	struct vm_struct *vm = task_stack_vm_area(tsk);
356ba14a194SAndy Lutomirski 
357ba14a194SAndy Lutomirski 	BUILD_BUG_ON(IS_ENABLED(CONFIG_VMAP_STACK) && PAGE_SIZE % 1024 != 0);
358ba14a194SAndy Lutomirski 
359ba14a194SAndy Lutomirski 	if (vm) {
360ba14a194SAndy Lutomirski 		int i;
361ba14a194SAndy Lutomirski 
362ba14a194SAndy Lutomirski 		BUG_ON(vm->nr_pages != THREAD_SIZE / PAGE_SIZE);
363ba14a194SAndy Lutomirski 
364ba14a194SAndy Lutomirski 		for (i = 0; i < THREAD_SIZE / PAGE_SIZE; i++) {
365ba14a194SAndy Lutomirski 			mod_zone_page_state(page_zone(vm->pages[i]),
366ba14a194SAndy Lutomirski 					    NR_KERNEL_STACK_KB,
367ba14a194SAndy Lutomirski 					    PAGE_SIZE / 1024 * account);
368ba14a194SAndy Lutomirski 		}
369ba14a194SAndy Lutomirski 	} else {
370ba14a194SAndy Lutomirski 		/*
371ba14a194SAndy Lutomirski 		 * All stack pages are in the same zone and belong to the
372ba14a194SAndy Lutomirski 		 * same memcg.
373ba14a194SAndy Lutomirski 		 */
374efdc9490SAndy Lutomirski 		struct page *first_page = virt_to_page(stack);
375c6a7f572SKOSAKI Motohiro 
376efdc9490SAndy Lutomirski 		mod_zone_page_state(page_zone(first_page), NR_KERNEL_STACK_KB,
377d30dd8beSAndy Lutomirski 				    THREAD_SIZE / 1024 * account);
378efdc9490SAndy Lutomirski 
379ed52be7bSJohannes Weiner 		mod_memcg_page_state(first_page, MEMCG_KERNEL_STACK_KB,
380efdc9490SAndy Lutomirski 				     account * (THREAD_SIZE / 1024));
381c6a7f572SKOSAKI Motohiro 	}
382ba14a194SAndy Lutomirski }
383c6a7f572SKOSAKI Motohiro 
3849b6f7e16SRoman Gushchin static int memcg_charge_kernel_stack(struct task_struct *tsk)
3859b6f7e16SRoman Gushchin {
3869b6f7e16SRoman Gushchin #ifdef CONFIG_VMAP_STACK
3879b6f7e16SRoman Gushchin 	struct vm_struct *vm = task_stack_vm_area(tsk);
3889b6f7e16SRoman Gushchin 	int ret;
3899b6f7e16SRoman Gushchin 
3909b6f7e16SRoman Gushchin 	if (vm) {
3919b6f7e16SRoman Gushchin 		int i;
3929b6f7e16SRoman Gushchin 
3939b6f7e16SRoman Gushchin 		for (i = 0; i < THREAD_SIZE / PAGE_SIZE; i++) {
3949b6f7e16SRoman Gushchin 			/*
3959b6f7e16SRoman Gushchin 			 * If memcg_kmem_charge() fails, page->mem_cgroup
3969b6f7e16SRoman Gushchin 			 * pointer is NULL, and both memcg_kmem_uncharge()
3979b6f7e16SRoman Gushchin 			 * and mod_memcg_page_state() in free_thread_stack()
3989b6f7e16SRoman Gushchin 			 * will ignore this page. So it's safe.
3999b6f7e16SRoman Gushchin 			 */
4009b6f7e16SRoman Gushchin 			ret = memcg_kmem_charge(vm->pages[i], GFP_KERNEL, 0);
4019b6f7e16SRoman Gushchin 			if (ret)
4029b6f7e16SRoman Gushchin 				return ret;
4039b6f7e16SRoman Gushchin 
4049b6f7e16SRoman Gushchin 			mod_memcg_page_state(vm->pages[i],
4059b6f7e16SRoman Gushchin 					     MEMCG_KERNEL_STACK_KB,
4069b6f7e16SRoman Gushchin 					     PAGE_SIZE / 1024);
4079b6f7e16SRoman Gushchin 		}
4089b6f7e16SRoman Gushchin 	}
4099b6f7e16SRoman Gushchin #endif
4109b6f7e16SRoman Gushchin 	return 0;
4119b6f7e16SRoman Gushchin }
4129b6f7e16SRoman Gushchin 
41368f24b08SAndy Lutomirski static void release_task_stack(struct task_struct *tsk)
4141da177e4SLinus Torvalds {
415405c0759SAndy Lutomirski 	if (WARN_ON(tsk->state != TASK_DEAD))
416405c0759SAndy Lutomirski 		return;  /* Better to leak the stack than to free prematurely */
417405c0759SAndy Lutomirski 
418ba14a194SAndy Lutomirski 	account_kernel_stack(tsk, -1);
419b235beeaSLinus Torvalds 	arch_release_thread_stack(tsk->stack);
420ba14a194SAndy Lutomirski 	free_thread_stack(tsk);
42168f24b08SAndy Lutomirski 	tsk->stack = NULL;
42268f24b08SAndy Lutomirski #ifdef CONFIG_VMAP_STACK
42368f24b08SAndy Lutomirski 	tsk->stack_vm_area = NULL;
42468f24b08SAndy Lutomirski #endif
42568f24b08SAndy Lutomirski }
42668f24b08SAndy Lutomirski 
42768f24b08SAndy Lutomirski #ifdef CONFIG_THREAD_INFO_IN_TASK
42868f24b08SAndy Lutomirski void put_task_stack(struct task_struct *tsk)
42968f24b08SAndy Lutomirski {
43068f24b08SAndy Lutomirski 	if (atomic_dec_and_test(&tsk->stack_refcount))
43168f24b08SAndy Lutomirski 		release_task_stack(tsk);
43268f24b08SAndy Lutomirski }
43368f24b08SAndy Lutomirski #endif
43468f24b08SAndy Lutomirski 
43568f24b08SAndy Lutomirski void free_task(struct task_struct *tsk)
43668f24b08SAndy Lutomirski {
43768f24b08SAndy Lutomirski #ifndef CONFIG_THREAD_INFO_IN_TASK
43868f24b08SAndy Lutomirski 	/*
43968f24b08SAndy Lutomirski 	 * The task is finally done with both the stack and thread_info,
44068f24b08SAndy Lutomirski 	 * so free both.
44168f24b08SAndy Lutomirski 	 */
44268f24b08SAndy Lutomirski 	release_task_stack(tsk);
44368f24b08SAndy Lutomirski #else
44468f24b08SAndy Lutomirski 	/*
44568f24b08SAndy Lutomirski 	 * If the task had a separate stack allocation, it should be gone
44668f24b08SAndy Lutomirski 	 * by now.
44768f24b08SAndy Lutomirski 	 */
44868f24b08SAndy Lutomirski 	WARN_ON_ONCE(atomic_read(&tsk->stack_refcount) != 0);
44968f24b08SAndy Lutomirski #endif
45023f78d4aSIngo Molnar 	rt_mutex_debug_task_free(tsk);
451fb52607aSFrederic Weisbecker 	ftrace_graph_exit_task(tsk);
452e2cfabdfSWill Drewry 	put_seccomp_filter(tsk);
453f19b9f74SAkinobu Mita 	arch_release_task_struct(tsk);
4541da5c46fSOleg Nesterov 	if (tsk->flags & PF_KTHREAD)
4551da5c46fSOleg Nesterov 		free_kthread_struct(tsk);
4561da177e4SLinus Torvalds 	free_task_struct(tsk);
4571da177e4SLinus Torvalds }
4581da177e4SLinus Torvalds EXPORT_SYMBOL(free_task);
4591da177e4SLinus Torvalds 
4601da177e4SLinus Torvalds #ifdef CONFIG_MMU
4610766f788SEmese Revfy static __latent_entropy int dup_mmap(struct mm_struct *mm,
4620766f788SEmese Revfy 					struct mm_struct *oldmm)
4631da177e4SLinus Torvalds {
464297c5eeeSLinus Torvalds 	struct vm_area_struct *mpnt, *tmp, *prev, **pprev;
4651da177e4SLinus Torvalds 	struct rb_node **rb_link, *rb_parent;
4661da177e4SLinus Torvalds 	int retval;
4671da177e4SLinus Torvalds 	unsigned long charge;
468893e26e6SPavel Emelyanov 	LIST_HEAD(uf);
4691da177e4SLinus Torvalds 
47032cdba1eSOleg Nesterov 	uprobe_start_dup_mmap();
4717c051267SMichal Hocko 	if (down_write_killable(&oldmm->mmap_sem)) {
4727c051267SMichal Hocko 		retval = -EINTR;
4737c051267SMichal Hocko 		goto fail_uprobe_end;
4747c051267SMichal Hocko 	}
475ec8c0446SRalf Baechle 	flush_cache_dup_mm(oldmm);
476f8ac4ec9SOleg Nesterov 	uprobe_dup_mmap(oldmm, mm);
477ad339451SIngo Molnar 	/*
478ad339451SIngo Molnar 	 * Not linked in yet - no deadlock potential:
479ad339451SIngo Molnar 	 */
480ad339451SIngo Molnar 	down_write_nested(&mm->mmap_sem, SINGLE_DEPTH_NESTING);
4817ee78232SHugh Dickins 
48290f31d0eSKonstantin Khlebnikov 	/* No ordering required: file already has been exposed. */
48390f31d0eSKonstantin Khlebnikov 	RCU_INIT_POINTER(mm->exe_file, get_mm_exe_file(oldmm));
48490f31d0eSKonstantin Khlebnikov 
4854f7d4614SVladimir Davydov 	mm->total_vm = oldmm->total_vm;
48684638335SKonstantin Khlebnikov 	mm->data_vm = oldmm->data_vm;
4874f7d4614SVladimir Davydov 	mm->exec_vm = oldmm->exec_vm;
4884f7d4614SVladimir Davydov 	mm->stack_vm = oldmm->stack_vm;
4894f7d4614SVladimir Davydov 
4901da177e4SLinus Torvalds 	rb_link = &mm->mm_rb.rb_node;
4911da177e4SLinus Torvalds 	rb_parent = NULL;
4921da177e4SLinus Torvalds 	pprev = &mm->mmap;
493f8af4da3SHugh Dickins 	retval = ksm_fork(mm, oldmm);
494f8af4da3SHugh Dickins 	if (retval)
495f8af4da3SHugh Dickins 		goto out;
496ba76149fSAndrea Arcangeli 	retval = khugepaged_fork(mm, oldmm);
497ba76149fSAndrea Arcangeli 	if (retval)
498ba76149fSAndrea Arcangeli 		goto out;
4991da177e4SLinus Torvalds 
500297c5eeeSLinus Torvalds 	prev = NULL;
501fd3e42fcSHugh Dickins 	for (mpnt = oldmm->mmap; mpnt; mpnt = mpnt->vm_next) {
5021da177e4SLinus Torvalds 		struct file *file;
5031da177e4SLinus Torvalds 
5041da177e4SLinus Torvalds 		if (mpnt->vm_flags & VM_DONTCOPY) {
50584638335SKonstantin Khlebnikov 			vm_stat_account(mm, mpnt->vm_flags, -vma_pages(mpnt));
5061da177e4SLinus Torvalds 			continue;
5071da177e4SLinus Torvalds 		}
5081da177e4SLinus Torvalds 		charge = 0;
509655c79bbSTetsuo Handa 		/*
510655c79bbSTetsuo Handa 		 * Don't duplicate many vmas if we've been oom-killed (for
511655c79bbSTetsuo Handa 		 * example)
512655c79bbSTetsuo Handa 		 */
513655c79bbSTetsuo Handa 		if (fatal_signal_pending(current)) {
514655c79bbSTetsuo Handa 			retval = -EINTR;
515655c79bbSTetsuo Handa 			goto out;
516655c79bbSTetsuo Handa 		}
5171da177e4SLinus Torvalds 		if (mpnt->vm_flags & VM_ACCOUNT) {
518b2412b7fSHuang Shijie 			unsigned long len = vma_pages(mpnt);
519b2412b7fSHuang Shijie 
520191c5424SAl Viro 			if (security_vm_enough_memory_mm(oldmm, len)) /* sic */
5211da177e4SLinus Torvalds 				goto fail_nomem;
5221da177e4SLinus Torvalds 			charge = len;
5231da177e4SLinus Torvalds 		}
5243928d4f5SLinus Torvalds 		tmp = vm_area_dup(mpnt);
5251da177e4SLinus Torvalds 		if (!tmp)
5261da177e4SLinus Torvalds 			goto fail_nomem;
527ef0855d3SOleg Nesterov 		retval = vma_dup_policy(mpnt, tmp);
528ef0855d3SOleg Nesterov 		if (retval)
5291da177e4SLinus Torvalds 			goto fail_nomem_policy;
530a247c3a9SAndrea Arcangeli 		tmp->vm_mm = mm;
531893e26e6SPavel Emelyanov 		retval = dup_userfaultfd(tmp, &uf);
532893e26e6SPavel Emelyanov 		if (retval)
533893e26e6SPavel Emelyanov 			goto fail_nomem_anon_vma_fork;
534d2cd9edeSRik van Riel 		if (tmp->vm_flags & VM_WIPEONFORK) {
535d2cd9edeSRik van Riel 			/* VM_WIPEONFORK gets a clean slate in the child. */
536d2cd9edeSRik van Riel 			tmp->anon_vma = NULL;
537d2cd9edeSRik van Riel 			if (anon_vma_prepare(tmp))
538d2cd9edeSRik van Riel 				goto fail_nomem_anon_vma_fork;
539d2cd9edeSRik van Riel 		} else if (anon_vma_fork(tmp, mpnt))
5405beb4930SRik van Riel 			goto fail_nomem_anon_vma_fork;
541893e26e6SPavel Emelyanov 		tmp->vm_flags &= ~(VM_LOCKED | VM_LOCKONFAULT);
542297c5eeeSLinus Torvalds 		tmp->vm_next = tmp->vm_prev = NULL;
5431da177e4SLinus Torvalds 		file = tmp->vm_file;
5441da177e4SLinus Torvalds 		if (file) {
545496ad9aaSAl Viro 			struct inode *inode = file_inode(file);
546b88ed205SHugh Dickins 			struct address_space *mapping = file->f_mapping;
547b88ed205SHugh Dickins 
5481da177e4SLinus Torvalds 			get_file(file);
5491da177e4SLinus Torvalds 			if (tmp->vm_flags & VM_DENYWRITE)
5501da177e4SLinus Torvalds 				atomic_dec(&inode->i_writecount);
55183cde9e8SDavidlohr Bueso 			i_mmap_lock_write(mapping);
552b88ed205SHugh Dickins 			if (tmp->vm_flags & VM_SHARED)
5534bb5f5d9SDavid Herrmann 				atomic_inc(&mapping->i_mmap_writable);
554b88ed205SHugh Dickins 			flush_dcache_mmap_lock(mapping);
555b88ed205SHugh Dickins 			/* insert tmp into the share list, just after mpnt */
5569826a516SMichel Lespinasse 			vma_interval_tree_insert_after(tmp, mpnt,
5579826a516SMichel Lespinasse 					&mapping->i_mmap);
558b88ed205SHugh Dickins 			flush_dcache_mmap_unlock(mapping);
55983cde9e8SDavidlohr Bueso 			i_mmap_unlock_write(mapping);
5601da177e4SLinus Torvalds 		}
5611da177e4SLinus Torvalds 
5621da177e4SLinus Torvalds 		/*
563a1e78772SMel Gorman 		 * Clear hugetlb-related page reserves for children. This only
564a1e78772SMel Gorman 		 * affects MAP_PRIVATE mappings. Faults generated by the child
565a1e78772SMel Gorman 		 * are not guaranteed to succeed, even if read-only
566a1e78772SMel Gorman 		 */
567a1e78772SMel Gorman 		if (is_vm_hugetlb_page(tmp))
568a1e78772SMel Gorman 			reset_vma_resv_huge_pages(tmp);
569a1e78772SMel Gorman 
570a1e78772SMel Gorman 		/*
5717ee78232SHugh Dickins 		 * Link in the new vma and copy the page table entries.
5721da177e4SLinus Torvalds 		 */
5731da177e4SLinus Torvalds 		*pprev = tmp;
5741da177e4SLinus Torvalds 		pprev = &tmp->vm_next;
575297c5eeeSLinus Torvalds 		tmp->vm_prev = prev;
576297c5eeeSLinus Torvalds 		prev = tmp;
5771da177e4SLinus Torvalds 
5781da177e4SLinus Torvalds 		__vma_link_rb(mm, tmp, rb_link, rb_parent);
5791da177e4SLinus Torvalds 		rb_link = &tmp->vm_rb.rb_right;
5801da177e4SLinus Torvalds 		rb_parent = &tmp->vm_rb;
5811da177e4SLinus Torvalds 
5821da177e4SLinus Torvalds 		mm->map_count++;
583d2cd9edeSRik van Riel 		if (!(tmp->vm_flags & VM_WIPEONFORK))
5840b0db14cSHugh Dickins 			retval = copy_page_range(mm, oldmm, mpnt);
5851da177e4SLinus Torvalds 
5861da177e4SLinus Torvalds 		if (tmp->vm_ops && tmp->vm_ops->open)
5871da177e4SLinus Torvalds 			tmp->vm_ops->open(tmp);
5881da177e4SLinus Torvalds 
5891da177e4SLinus Torvalds 		if (retval)
5901da177e4SLinus Torvalds 			goto out;
5911da177e4SLinus Torvalds 	}
592d6dd61c8SJeremy Fitzhardinge 	/* a new mm has just been created */
5931ed0cc5aSNadav Amit 	retval = arch_dup_mmap(oldmm, mm);
5941da177e4SLinus Torvalds out:
5957ee78232SHugh Dickins 	up_write(&mm->mmap_sem);
596fd3e42fcSHugh Dickins 	flush_tlb_mm(oldmm);
5971da177e4SLinus Torvalds 	up_write(&oldmm->mmap_sem);
598893e26e6SPavel Emelyanov 	dup_userfaultfd_complete(&uf);
5997c051267SMichal Hocko fail_uprobe_end:
60032cdba1eSOleg Nesterov 	uprobe_end_dup_mmap();
6011da177e4SLinus Torvalds 	return retval;
6025beb4930SRik van Riel fail_nomem_anon_vma_fork:
603ef0855d3SOleg Nesterov 	mpol_put(vma_policy(tmp));
6041da177e4SLinus Torvalds fail_nomem_policy:
6053928d4f5SLinus Torvalds 	vm_area_free(tmp);
6061da177e4SLinus Torvalds fail_nomem:
6071da177e4SLinus Torvalds 	retval = -ENOMEM;
6081da177e4SLinus Torvalds 	vm_unacct_memory(charge);
6091da177e4SLinus Torvalds 	goto out;
6101da177e4SLinus Torvalds }
6111da177e4SLinus Torvalds 
6121da177e4SLinus Torvalds static inline int mm_alloc_pgd(struct mm_struct *mm)
6131da177e4SLinus Torvalds {
6141da177e4SLinus Torvalds 	mm->pgd = pgd_alloc(mm);
6151da177e4SLinus Torvalds 	if (unlikely(!mm->pgd))
6161da177e4SLinus Torvalds 		return -ENOMEM;
6171da177e4SLinus Torvalds 	return 0;
6181da177e4SLinus Torvalds }
6191da177e4SLinus Torvalds 
6201da177e4SLinus Torvalds static inline void mm_free_pgd(struct mm_struct *mm)
6211da177e4SLinus Torvalds {
6225e541973SBenjamin Herrenschmidt 	pgd_free(mm, mm->pgd);
6231da177e4SLinus Torvalds }
6241da177e4SLinus Torvalds #else
62590f31d0eSKonstantin Khlebnikov static int dup_mmap(struct mm_struct *mm, struct mm_struct *oldmm)
62690f31d0eSKonstantin Khlebnikov {
62790f31d0eSKonstantin Khlebnikov 	down_write(&oldmm->mmap_sem);
62890f31d0eSKonstantin Khlebnikov 	RCU_INIT_POINTER(mm->exe_file, get_mm_exe_file(oldmm));
62990f31d0eSKonstantin Khlebnikov 	up_write(&oldmm->mmap_sem);
63090f31d0eSKonstantin Khlebnikov 	return 0;
63190f31d0eSKonstantin Khlebnikov }
6321da177e4SLinus Torvalds #define mm_alloc_pgd(mm)	(0)
6331da177e4SLinus Torvalds #define mm_free_pgd(mm)
6341da177e4SLinus Torvalds #endif /* CONFIG_MMU */
6351da177e4SLinus Torvalds 
636d70f2a14SAndrew Morton static void check_mm(struct mm_struct *mm)
637d70f2a14SAndrew Morton {
638d70f2a14SAndrew Morton 	int i;
639d70f2a14SAndrew Morton 
640d70f2a14SAndrew Morton 	for (i = 0; i < NR_MM_COUNTERS; i++) {
641d70f2a14SAndrew Morton 		long x = atomic_long_read(&mm->rss_stat.count[i]);
642d70f2a14SAndrew Morton 
643d70f2a14SAndrew Morton 		if (unlikely(x))
644d70f2a14SAndrew Morton 			printk(KERN_ALERT "BUG: Bad rss-counter state "
645d70f2a14SAndrew Morton 					  "mm:%p idx:%d val:%ld\n", mm, i, x);
646d70f2a14SAndrew Morton 	}
647d70f2a14SAndrew Morton 
648d70f2a14SAndrew Morton 	if (mm_pgtables_bytes(mm))
649d70f2a14SAndrew Morton 		pr_alert("BUG: non-zero pgtables_bytes on freeing mm: %ld\n",
650d70f2a14SAndrew Morton 				mm_pgtables_bytes(mm));
651d70f2a14SAndrew Morton 
652d70f2a14SAndrew Morton #if defined(CONFIG_TRANSPARENT_HUGEPAGE) && !USE_SPLIT_PMD_PTLOCKS
653d70f2a14SAndrew Morton 	VM_BUG_ON_MM(mm->pmd_huge_pte, mm);
654d70f2a14SAndrew Morton #endif
655d70f2a14SAndrew Morton }
6561da177e4SLinus Torvalds 
657e94b1766SChristoph Lameter #define allocate_mm()	(kmem_cache_alloc(mm_cachep, GFP_KERNEL))
6581da177e4SLinus Torvalds #define free_mm(mm)	(kmem_cache_free(mm_cachep, (mm)))
6591da177e4SLinus Torvalds 
660d70f2a14SAndrew Morton /*
661d70f2a14SAndrew Morton  * Called when the last reference to the mm
662d70f2a14SAndrew Morton  * is dropped: either by a lazy thread or by
663d70f2a14SAndrew Morton  * mmput. Free the page directory and the mm.
664d70f2a14SAndrew Morton  */
665d34bc48fSAndrew Morton void __mmdrop(struct mm_struct *mm)
666d70f2a14SAndrew Morton {
667d70f2a14SAndrew Morton 	BUG_ON(mm == &init_mm);
6683eda69c9SMark Rutland 	WARN_ON_ONCE(mm == current->mm);
6693eda69c9SMark Rutland 	WARN_ON_ONCE(mm == current->active_mm);
670d70f2a14SAndrew Morton 	mm_free_pgd(mm);
671d70f2a14SAndrew Morton 	destroy_context(mm);
672d70f2a14SAndrew Morton 	hmm_mm_destroy(mm);
673d70f2a14SAndrew Morton 	mmu_notifier_mm_destroy(mm);
674d70f2a14SAndrew Morton 	check_mm(mm);
675d70f2a14SAndrew Morton 	put_user_ns(mm->user_ns);
676d70f2a14SAndrew Morton 	free_mm(mm);
677d70f2a14SAndrew Morton }
678d34bc48fSAndrew Morton EXPORT_SYMBOL_GPL(__mmdrop);
679d70f2a14SAndrew Morton 
680d70f2a14SAndrew Morton static void mmdrop_async_fn(struct work_struct *work)
681d70f2a14SAndrew Morton {
682d70f2a14SAndrew Morton 	struct mm_struct *mm;
683d70f2a14SAndrew Morton 
684d70f2a14SAndrew Morton 	mm = container_of(work, struct mm_struct, async_put_work);
685d70f2a14SAndrew Morton 	__mmdrop(mm);
686d70f2a14SAndrew Morton }
687d70f2a14SAndrew Morton 
688d70f2a14SAndrew Morton static void mmdrop_async(struct mm_struct *mm)
689d70f2a14SAndrew Morton {
690d70f2a14SAndrew Morton 	if (unlikely(atomic_dec_and_test(&mm->mm_count))) {
691d70f2a14SAndrew Morton 		INIT_WORK(&mm->async_put_work, mmdrop_async_fn);
692d70f2a14SAndrew Morton 		schedule_work(&mm->async_put_work);
693d70f2a14SAndrew Morton 	}
694d70f2a14SAndrew Morton }
695d70f2a14SAndrew Morton 
6961da177e4SLinus Torvalds static inline void free_signal_struct(struct signal_struct *sig)
6971da177e4SLinus Torvalds {
6981da177e4SLinus Torvalds 	taskstats_tgid_free(sig);
6991da177e4SLinus Torvalds 	sched_autogroup_exit(sig);
7001da177e4SLinus Torvalds 	/*
7011da177e4SLinus Torvalds 	 * __mmdrop is not safe to call from softirq context on x86 due to
7021da177e4SLinus Torvalds 	 * pgd_dtor so postpone it to the async context
7031da177e4SLinus Torvalds 	 */
7041da177e4SLinus Torvalds 	if (sig->oom_mm)
7051da177e4SLinus Torvalds 		mmdrop_async(sig->oom_mm);
7061da177e4SLinus Torvalds 	kmem_cache_free(signal_cachep, sig);
7071da177e4SLinus Torvalds }
7081da177e4SLinus Torvalds 
7091da177e4SLinus Torvalds static inline void put_signal_struct(struct signal_struct *sig)
7101da177e4SLinus Torvalds {
7111da177e4SLinus Torvalds 	if (atomic_dec_and_test(&sig->sigcnt))
7121da177e4SLinus Torvalds 		free_signal_struct(sig);
7131da177e4SLinus Torvalds }
7141da177e4SLinus Torvalds 
7151da177e4SLinus Torvalds void __put_task_struct(struct task_struct *tsk)
7161da177e4SLinus Torvalds {
7171da177e4SLinus Torvalds 	WARN_ON(!tsk->exit_state);
7181da177e4SLinus Torvalds 	WARN_ON(atomic_read(&tsk->usage));
7191da177e4SLinus Torvalds 	WARN_ON(tsk == current);
7201da177e4SLinus Torvalds 
7211da177e4SLinus Torvalds 	cgroup_free(tsk);
7221da177e4SLinus Torvalds 	task_numa_free(tsk);
7231da177e4SLinus Torvalds 	security_task_free(tsk);
7241da177e4SLinus Torvalds 	exit_creds(tsk);
7251da177e4SLinus Torvalds 	delayacct_tsk_free(tsk);
7261da177e4SLinus Torvalds 	put_signal_struct(tsk->signal);
7271da177e4SLinus Torvalds 
7281da177e4SLinus Torvalds 	if (!profile_handoff_task(tsk))
7291da177e4SLinus Torvalds 		free_task(tsk);
7301da177e4SLinus Torvalds }
7311da177e4SLinus Torvalds EXPORT_SYMBOL_GPL(__put_task_struct);
7321da177e4SLinus Torvalds 
7331da177e4SLinus Torvalds void __init __weak arch_task_cache_init(void) { }
7341da177e4SLinus Torvalds 
7351da177e4SLinus Torvalds /*
7361da177e4SLinus Torvalds  * set_max_threads
7371da177e4SLinus Torvalds  */
7381da177e4SLinus Torvalds static void set_max_threads(unsigned int max_threads_suggested)
7391da177e4SLinus Torvalds {
7401da177e4SLinus Torvalds 	u64 threads;
7411da177e4SLinus Torvalds 
7421da177e4SLinus Torvalds 	/*
7431da177e4SLinus Torvalds 	 * The number of threads shall be limited such that the thread
7441da177e4SLinus Torvalds 	 * structures may only consume a small part of the available memory.
7451da177e4SLinus Torvalds 	 */
7461da177e4SLinus Torvalds 	if (fls64(totalram_pages) + fls64(PAGE_SIZE) > 64)
7471da177e4SLinus Torvalds 		threads = MAX_THREADS;
7481da177e4SLinus Torvalds 	else
7491da177e4SLinus Torvalds 		threads = div64_u64((u64) totalram_pages * (u64) PAGE_SIZE,
7501da177e4SLinus Torvalds 				    (u64) THREAD_SIZE * 8UL);
7511da177e4SLinus Torvalds 
7521da177e4SLinus Torvalds 	if (threads > max_threads_suggested)
7531da177e4SLinus Torvalds 		threads = max_threads_suggested;
7541da177e4SLinus Torvalds 
7551da177e4SLinus Torvalds 	max_threads = clamp_t(u64, threads, MIN_THREADS, MAX_THREADS);
7561da177e4SLinus Torvalds }
7571da177e4SLinus Torvalds 
7581da177e4SLinus Torvalds #ifdef CONFIG_ARCH_WANTS_DYNAMIC_TASK_STRUCT
7591da177e4SLinus Torvalds /* Initialized by the architecture: */
7601da177e4SLinus Torvalds int arch_task_struct_size __read_mostly;
7611da177e4SLinus Torvalds #endif
7621da177e4SLinus Torvalds 
7635905429aSKees Cook static void task_struct_whitelist(unsigned long *offset, unsigned long *size)
7645905429aSKees Cook {
7655905429aSKees Cook 	/* Fetch thread_struct whitelist for the architecture. */
7665905429aSKees Cook 	arch_thread_struct_whitelist(offset, size);
7675905429aSKees Cook 
7685905429aSKees Cook 	/*
7695905429aSKees Cook 	 * Handle zero-sized whitelist or empty thread_struct, otherwise
7705905429aSKees Cook 	 * adjust offset to position of thread_struct in task_struct.
7715905429aSKees Cook 	 */
7725905429aSKees Cook 	if (unlikely(*size == 0))
7735905429aSKees Cook 		*offset = 0;
7745905429aSKees Cook 	else
7755905429aSKees Cook 		*offset += offsetof(struct task_struct, thread);
7765905429aSKees Cook }
7775905429aSKees Cook 
7781da177e4SLinus Torvalds void __init fork_init(void)
7791da177e4SLinus Torvalds {
7801da177e4SLinus Torvalds 	int i;
7811da177e4SLinus Torvalds #ifndef CONFIG_ARCH_TASK_STRUCT_ALLOCATOR
7821da177e4SLinus Torvalds #ifndef ARCH_MIN_TASKALIGN
7831da177e4SLinus Torvalds #define ARCH_MIN_TASKALIGN	0
7841da177e4SLinus Torvalds #endif
7851da177e4SLinus Torvalds 	int align = max_t(int, L1_CACHE_BYTES, ARCH_MIN_TASKALIGN);
7865905429aSKees Cook 	unsigned long useroffset, usersize;
7871da177e4SLinus Torvalds 
7881da177e4SLinus Torvalds 	/* create a slab on which task_structs can be allocated */
7895905429aSKees Cook 	task_struct_whitelist(&useroffset, &usersize);
7905905429aSKees Cook 	task_struct_cachep = kmem_cache_create_usercopy("task_struct",
7911da177e4SLinus Torvalds 			arch_task_struct_size, align,
7925905429aSKees Cook 			SLAB_PANIC|SLAB_ACCOUNT,
7935905429aSKees Cook 			useroffset, usersize, NULL);
7941da177e4SLinus Torvalds #endif
7951da177e4SLinus Torvalds 
7961da177e4SLinus Torvalds 	/* do the arch specific task caches init */
7971da177e4SLinus Torvalds 	arch_task_cache_init();
7981da177e4SLinus Torvalds 
7991da177e4SLinus Torvalds 	set_max_threads(MAX_THREADS);
8001da177e4SLinus Torvalds 
8011da177e4SLinus Torvalds 	init_task.signal->rlim[RLIMIT_NPROC].rlim_cur = max_threads/2;
8021da177e4SLinus Torvalds 	init_task.signal->rlim[RLIMIT_NPROC].rlim_max = max_threads/2;
8031da177e4SLinus Torvalds 	init_task.signal->rlim[RLIMIT_SIGPENDING] =
8041da177e4SLinus Torvalds 		init_task.signal->rlim[RLIMIT_NPROC];
8051da177e4SLinus Torvalds 
8061da177e4SLinus Torvalds 	for (i = 0; i < UCOUNT_COUNTS; i++) {
8071da177e4SLinus Torvalds 		init_user_ns.ucount_max[i] = max_threads/2;
8081da177e4SLinus Torvalds 	}
8091da177e4SLinus Torvalds 
8101da177e4SLinus Torvalds #ifdef CONFIG_VMAP_STACK
8111da177e4SLinus Torvalds 	cpuhp_setup_state(CPUHP_BP_PREPARE_DYN, "fork:vm_stack_cache",
8121da177e4SLinus Torvalds 			  NULL, free_vm_stack_cache);
8131da177e4SLinus Torvalds #endif
8141da177e4SLinus Torvalds 
8151da177e4SLinus Torvalds 	lockdep_init_task(&init_task);
8161da177e4SLinus Torvalds }
8171da177e4SLinus Torvalds 
8181da177e4SLinus Torvalds int __weak arch_dup_task_struct(struct task_struct *dst,
8191da177e4SLinus Torvalds 					       struct task_struct *src)
8201da177e4SLinus Torvalds {
8211da177e4SLinus Torvalds 	*dst = *src;
8221da177e4SLinus Torvalds 	return 0;
8231da177e4SLinus Torvalds }
8241da177e4SLinus Torvalds 
8251da177e4SLinus Torvalds void set_task_stack_end_magic(struct task_struct *tsk)
8261da177e4SLinus Torvalds {
8271da177e4SLinus Torvalds 	unsigned long *stackend;
8281da177e4SLinus Torvalds 
8291da177e4SLinus Torvalds 	stackend = end_of_stack(tsk);
8301da177e4SLinus Torvalds 	*stackend = STACK_END_MAGIC;	/* for overflow detection */
8311da177e4SLinus Torvalds }
8321da177e4SLinus Torvalds 
8331da177e4SLinus Torvalds static struct task_struct *dup_task_struct(struct task_struct *orig, int node)
8341da177e4SLinus Torvalds {
8351da177e4SLinus Torvalds 	struct task_struct *tsk;
8361da177e4SLinus Torvalds 	unsigned long *stack;
8371da177e4SLinus Torvalds 	struct vm_struct *stack_vm_area;
8381da177e4SLinus Torvalds 	int err;
8391da177e4SLinus Torvalds 
8401da177e4SLinus Torvalds 	if (node == NUMA_NO_NODE)
8411da177e4SLinus Torvalds 		node = tsk_fork_get_node(orig);
8421da177e4SLinus Torvalds 	tsk = alloc_task_struct_node(node);
8431da177e4SLinus Torvalds 	if (!tsk)
8441da177e4SLinus Torvalds 		return NULL;
8451da177e4SLinus Torvalds 
8461da177e4SLinus Torvalds 	stack = alloc_thread_stack_node(tsk, node);
8471da177e4SLinus Torvalds 	if (!stack)
8481da177e4SLinus Torvalds 		goto free_tsk;
8491da177e4SLinus Torvalds 
8509b6f7e16SRoman Gushchin 	if (memcg_charge_kernel_stack(tsk))
8519b6f7e16SRoman Gushchin 		goto free_stack;
8529b6f7e16SRoman Gushchin 
8531da177e4SLinus Torvalds 	stack_vm_area = task_stack_vm_area(tsk);
8541da177e4SLinus Torvalds 
8551da177e4SLinus Torvalds 	err = arch_dup_task_struct(tsk, orig);
8561da177e4SLinus Torvalds 
8571da177e4SLinus Torvalds 	/*
8581da177e4SLinus Torvalds 	 * arch_dup_task_struct() clobbers the stack-related fields.  Make
8591da177e4SLinus Torvalds 	 * sure they're properly initialized before using any stack-related
8601da177e4SLinus Torvalds 	 * functions again.
8611da177e4SLinus Torvalds 	 */
8621da177e4SLinus Torvalds 	tsk->stack = stack;
8631da177e4SLinus Torvalds #ifdef CONFIG_VMAP_STACK
8641da177e4SLinus Torvalds 	tsk->stack_vm_area = stack_vm_area;
8651da177e4SLinus Torvalds #endif
8661da177e4SLinus Torvalds #ifdef CONFIG_THREAD_INFO_IN_TASK
8671da177e4SLinus Torvalds 	atomic_set(&tsk->stack_refcount, 1);
8681da177e4SLinus Torvalds #endif
8691da177e4SLinus Torvalds 
8701da177e4SLinus Torvalds 	if (err)
8711da177e4SLinus Torvalds 		goto free_stack;
8721da177e4SLinus Torvalds 
8731da177e4SLinus Torvalds #ifdef CONFIG_SECCOMP
8741da177e4SLinus Torvalds 	/*
8751da177e4SLinus Torvalds 	 * We must handle setting up seccomp filters once we're under
8761da177e4SLinus Torvalds 	 * the sighand lock in case orig has changed between now and
8771da177e4SLinus Torvalds 	 * then. Until then, filter must be NULL to avoid messing up
8781da177e4SLinus Torvalds 	 * the usage counts on the error path calling free_task.
8791da177e4SLinus Torvalds 	 */
8801da177e4SLinus Torvalds 	tsk->seccomp.filter = NULL;
8811da177e4SLinus Torvalds #endif
8821da177e4SLinus Torvalds 
8831da177e4SLinus Torvalds 	setup_thread_stack(tsk, orig);
8841da177e4SLinus Torvalds 	clear_user_return_notifier(tsk);
8851da177e4SLinus Torvalds 	clear_tsk_need_resched(tsk);
8861da177e4SLinus Torvalds 	set_task_stack_end_magic(tsk);
8871da177e4SLinus Torvalds 
888050e9baaSLinus Torvalds #ifdef CONFIG_STACKPROTECTOR
8891da177e4SLinus Torvalds 	tsk->stack_canary = get_random_canary();
8901da177e4SLinus Torvalds #endif
8911da177e4SLinus Torvalds 
8921da177e4SLinus Torvalds 	/*
8931da177e4SLinus Torvalds 	 * One for us, one for whoever does the "release_task()" (usually
8941da177e4SLinus Torvalds 	 * parent)
8951da177e4SLinus Torvalds 	 */
8961da177e4SLinus Torvalds 	atomic_set(&tsk->usage, 2);
8971da177e4SLinus Torvalds #ifdef CONFIG_BLK_DEV_IO_TRACE
8981da177e4SLinus Torvalds 	tsk->btrace_seq = 0;
8991da177e4SLinus Torvalds #endif
9001da177e4SLinus Torvalds 	tsk->splice_pipe = NULL;
9011da177e4SLinus Torvalds 	tsk->task_frag.page = NULL;
9021da177e4SLinus Torvalds 	tsk->wake_q.next = NULL;
9031da177e4SLinus Torvalds 
9041da177e4SLinus Torvalds 	account_kernel_stack(tsk, 1);
9051da177e4SLinus Torvalds 
9061da177e4SLinus Torvalds 	kcov_task_init(tsk);
9071da177e4SLinus Torvalds 
9081da177e4SLinus Torvalds #ifdef CONFIG_FAULT_INJECTION
9091da177e4SLinus Torvalds 	tsk->fail_nth = 0;
9101da177e4SLinus Torvalds #endif
9111da177e4SLinus Torvalds 
9122c323017SJosef Bacik #ifdef CONFIG_BLK_CGROUP
9132c323017SJosef Bacik 	tsk->throttle_queue = NULL;
9142c323017SJosef Bacik 	tsk->use_memdelay = 0;
9152c323017SJosef Bacik #endif
9162c323017SJosef Bacik 
917d46eb14bSShakeel Butt #ifdef CONFIG_MEMCG
918d46eb14bSShakeel Butt 	tsk->active_memcg = NULL;
919d46eb14bSShakeel Butt #endif
9201da177e4SLinus Torvalds 	return tsk;
9211da177e4SLinus Torvalds 
9221da177e4SLinus Torvalds free_stack:
9231da177e4SLinus Torvalds 	free_thread_stack(tsk);
9241da177e4SLinus Torvalds free_tsk:
9251da177e4SLinus Torvalds 	free_task_struct(tsk);
9261da177e4SLinus Torvalds 	return NULL;
9271da177e4SLinus Torvalds }
9281da177e4SLinus Torvalds 
9291da177e4SLinus Torvalds __cacheline_aligned_in_smp DEFINE_SPINLOCK(mmlist_lock);
9301da177e4SLinus Torvalds 
9314cb0e11bSHidehiro Kawai static unsigned long default_dump_filter = MMF_DUMP_FILTER_DEFAULT;
9324cb0e11bSHidehiro Kawai 
9334cb0e11bSHidehiro Kawai static int __init coredump_filter_setup(char *s)
9344cb0e11bSHidehiro Kawai {
9354cb0e11bSHidehiro Kawai 	default_dump_filter =
9364cb0e11bSHidehiro Kawai 		(simple_strtoul(s, NULL, 0) << MMF_DUMP_FILTER_SHIFT) &
9374cb0e11bSHidehiro Kawai 		MMF_DUMP_FILTER_MASK;
9384cb0e11bSHidehiro Kawai 	return 1;
9394cb0e11bSHidehiro Kawai }
9404cb0e11bSHidehiro Kawai 
9414cb0e11bSHidehiro Kawai __setup("coredump_filter=", coredump_filter_setup);
9424cb0e11bSHidehiro Kawai 
9431da177e4SLinus Torvalds #include <linux/init_task.h>
9441da177e4SLinus Torvalds 
945858f0993SAlexey Dobriyan static void mm_init_aio(struct mm_struct *mm)
946858f0993SAlexey Dobriyan {
947858f0993SAlexey Dobriyan #ifdef CONFIG_AIO
948858f0993SAlexey Dobriyan 	spin_lock_init(&mm->ioctx_lock);
949db446a08SBenjamin LaHaise 	mm->ioctx_table = NULL;
950858f0993SAlexey Dobriyan #endif
951858f0993SAlexey Dobriyan }
952858f0993SAlexey Dobriyan 
95333144e84SVladimir Davydov static void mm_init_owner(struct mm_struct *mm, struct task_struct *p)
95433144e84SVladimir Davydov {
95533144e84SVladimir Davydov #ifdef CONFIG_MEMCG
95633144e84SVladimir Davydov 	mm->owner = p;
95733144e84SVladimir Davydov #endif
95833144e84SVladimir Davydov }
95933144e84SVladimir Davydov 
960355627f5SEric Biggers static void mm_init_uprobes_state(struct mm_struct *mm)
961355627f5SEric Biggers {
962355627f5SEric Biggers #ifdef CONFIG_UPROBES
963355627f5SEric Biggers 	mm->uprobes_state.xol_area = NULL;
964355627f5SEric Biggers #endif
965355627f5SEric Biggers }
966355627f5SEric Biggers 
967bfedb589SEric W. Biederman static struct mm_struct *mm_init(struct mm_struct *mm, struct task_struct *p,
968bfedb589SEric W. Biederman 	struct user_namespace *user_ns)
9691da177e4SLinus Torvalds {
97041f727fdSVladimir Davydov 	mm->mmap = NULL;
97141f727fdSVladimir Davydov 	mm->mm_rb = RB_ROOT;
97241f727fdSVladimir Davydov 	mm->vmacache_seqnum = 0;
9731da177e4SLinus Torvalds 	atomic_set(&mm->mm_users, 1);
9741da177e4SLinus Torvalds 	atomic_set(&mm->mm_count, 1);
9751da177e4SLinus Torvalds 	init_rwsem(&mm->mmap_sem);
9761da177e4SLinus Torvalds 	INIT_LIST_HEAD(&mm->mmlist);
977999d9fc1SOleg Nesterov 	mm->core_state = NULL;
978af5b0f6aSKirill A. Shutemov 	mm_pgtables_bytes_init(mm);
97941f727fdSVladimir Davydov 	mm->map_count = 0;
98041f727fdSVladimir Davydov 	mm->locked_vm = 0;
981ce65cefaSVladimir Davydov 	mm->pinned_vm = 0;
982d559db08SKAMEZAWA Hiroyuki 	memset(&mm->rss_stat, 0, sizeof(mm->rss_stat));
9831da177e4SLinus Torvalds 	spin_lock_init(&mm->page_table_lock);
98488aa7cc6SYang Shi 	spin_lock_init(&mm->arg_lock);
98541f727fdSVladimir Davydov 	mm_init_cpumask(mm);
986858f0993SAlexey Dobriyan 	mm_init_aio(mm);
987cf475ad2SBalbir Singh 	mm_init_owner(mm, p);
9882b7e8665SEric Biggers 	RCU_INIT_POINTER(mm->exe_file, NULL);
98941f727fdSVladimir Davydov 	mmu_notifier_mm_init(mm);
990133ff0eaSJérôme Glisse 	hmm_mm_init(mm);
99116af97dcSNadav Amit 	init_tlb_flush_pending(mm);
99241f727fdSVladimir Davydov #if defined(CONFIG_TRANSPARENT_HUGEPAGE) && !USE_SPLIT_PMD_PTLOCKS
99341f727fdSVladimir Davydov 	mm->pmd_huge_pte = NULL;
99441f727fdSVladimir Davydov #endif
995355627f5SEric Biggers 	mm_init_uprobes_state(mm);
9961da177e4SLinus Torvalds 
997a0715cc2SAlex Thorlton 	if (current->mm) {
998a0715cc2SAlex Thorlton 		mm->flags = current->mm->flags & MMF_INIT_MASK;
999a0715cc2SAlex Thorlton 		mm->def_flags = current->mm->def_flags & VM_INIT_DEF_MASK;
1000a0715cc2SAlex Thorlton 	} else {
1001a0715cc2SAlex Thorlton 		mm->flags = default_dump_filter;
10021da177e4SLinus Torvalds 		mm->def_flags = 0;
1003a0715cc2SAlex Thorlton 	}
1004a0715cc2SAlex Thorlton 
100541f727fdSVladimir Davydov 	if (mm_alloc_pgd(mm))
100641f727fdSVladimir Davydov 		goto fail_nopgd;
100778fb7466SPavel Emelianov 
100841f727fdSVladimir Davydov 	if (init_new_context(p, mm))
100941f727fdSVladimir Davydov 		goto fail_nocontext;
101041f727fdSVladimir Davydov 
1011bfedb589SEric W. Biederman 	mm->user_ns = get_user_ns(user_ns);
101241f727fdSVladimir Davydov 	return mm;
101341f727fdSVladimir Davydov 
101441f727fdSVladimir Davydov fail_nocontext:
101541f727fdSVladimir Davydov 	mm_free_pgd(mm);
101641f727fdSVladimir Davydov fail_nopgd:
10171da177e4SLinus Torvalds 	free_mm(mm);
10181da177e4SLinus Torvalds 	return NULL;
10191da177e4SLinus Torvalds }
10201da177e4SLinus Torvalds 
10211da177e4SLinus Torvalds /*
10221da177e4SLinus Torvalds  * Allocate and initialize an mm_struct.
10231da177e4SLinus Torvalds  */
10241da177e4SLinus Torvalds struct mm_struct *mm_alloc(void)
10251da177e4SLinus Torvalds {
10261da177e4SLinus Torvalds 	struct mm_struct *mm;
10271da177e4SLinus Torvalds 
10281da177e4SLinus Torvalds 	mm = allocate_mm();
1029de03c72cSKOSAKI Motohiro 	if (!mm)
1030de03c72cSKOSAKI Motohiro 		return NULL;
1031de03c72cSKOSAKI Motohiro 
10321da177e4SLinus Torvalds 	memset(mm, 0, sizeof(*mm));
1033bfedb589SEric W. Biederman 	return mm_init(mm, current, current_user_ns());
10341da177e4SLinus Torvalds }
10351da177e4SLinus Torvalds 
1036ec8d7c14SMichal Hocko static inline void __mmput(struct mm_struct *mm)
10371da177e4SLinus Torvalds {
1038ec8d7c14SMichal Hocko 	VM_BUG_ON(atomic_read(&mm->mm_users));
10390ae26f1bSAndrew Morton 
1040d4b3b638SSrikar Dronamraju 	uprobe_clear_state(mm);
10411da177e4SLinus Torvalds 	exit_aio(mm);
10421c2fb7a4SAndrea Arcangeli 	ksm_exit(mm);
1043ba76149fSAndrea Arcangeli 	khugepaged_exit(mm); /* must run before exit_mmap */
10441da177e4SLinus Torvalds 	exit_mmap(mm);
10456fcb52a5SAaron Lu 	mm_put_huge_zero_page(mm);
1046925d1c40SMatt Helsley 	set_mm_exe_file(mm, NULL);
10471da177e4SLinus Torvalds 	if (!list_empty(&mm->mmlist)) {
10481da177e4SLinus Torvalds 		spin_lock(&mmlist_lock);
10491da177e4SLinus Torvalds 		list_del(&mm->mmlist);
10501da177e4SLinus Torvalds 		spin_unlock(&mmlist_lock);
10511da177e4SLinus Torvalds 	}
1052801460d0SHiroshi Shimamoto 	if (mm->binfmt)
1053801460d0SHiroshi Shimamoto 		module_put(mm->binfmt->module);
10541da177e4SLinus Torvalds 	mmdrop(mm);
10551da177e4SLinus Torvalds }
1056ec8d7c14SMichal Hocko 
1057ec8d7c14SMichal Hocko /*
1058ec8d7c14SMichal Hocko  * Decrement the use count and release all resources for an mm.
1059ec8d7c14SMichal Hocko  */
1060ec8d7c14SMichal Hocko void mmput(struct mm_struct *mm)
1061ec8d7c14SMichal Hocko {
1062ec8d7c14SMichal Hocko 	might_sleep();
1063ec8d7c14SMichal Hocko 
1064ec8d7c14SMichal Hocko 	if (atomic_dec_and_test(&mm->mm_users))
1065ec8d7c14SMichal Hocko 		__mmput(mm);
10661da177e4SLinus Torvalds }
10671da177e4SLinus Torvalds EXPORT_SYMBOL_GPL(mmput);
10681da177e4SLinus Torvalds 
1069a1b2289cSSherry Yang #ifdef CONFIG_MMU
1070a1b2289cSSherry Yang static void mmput_async_fn(struct work_struct *work)
1071a1b2289cSSherry Yang {
1072a1b2289cSSherry Yang 	struct mm_struct *mm = container_of(work, struct mm_struct,
1073a1b2289cSSherry Yang 					    async_put_work);
1074a1b2289cSSherry Yang 
1075a1b2289cSSherry Yang 	__mmput(mm);
1076a1b2289cSSherry Yang }
1077a1b2289cSSherry Yang 
1078a1b2289cSSherry Yang void mmput_async(struct mm_struct *mm)
1079a1b2289cSSherry Yang {
1080a1b2289cSSherry Yang 	if (atomic_dec_and_test(&mm->mm_users)) {
1081a1b2289cSSherry Yang 		INIT_WORK(&mm->async_put_work, mmput_async_fn);
1082a1b2289cSSherry Yang 		schedule_work(&mm->async_put_work);
1083a1b2289cSSherry Yang 	}
1084a1b2289cSSherry Yang }
1085a1b2289cSSherry Yang #endif
1086a1b2289cSSherry Yang 
108790f31d0eSKonstantin Khlebnikov /**
108890f31d0eSKonstantin Khlebnikov  * set_mm_exe_file - change a reference to the mm's executable file
108990f31d0eSKonstantin Khlebnikov  *
109090f31d0eSKonstantin Khlebnikov  * This changes mm's executable file (shown as symlink /proc/[pid]/exe).
109190f31d0eSKonstantin Khlebnikov  *
10926e399cd1SDavidlohr Bueso  * Main users are mmput() and sys_execve(). Callers prevent concurrent
10936e399cd1SDavidlohr Bueso  * invocations: in mmput() nobody alive left, in execve task is single
10946e399cd1SDavidlohr Bueso  * threaded. sys_prctl(PR_SET_MM_MAP/EXE_FILE) also needs to set the
10956e399cd1SDavidlohr Bueso  * mm->exe_file, but does so without using set_mm_exe_file() in order
10966e399cd1SDavidlohr Bueso  * to do avoid the need for any locks.
109790f31d0eSKonstantin Khlebnikov  */
109838646013SJiri Slaby void set_mm_exe_file(struct mm_struct *mm, struct file *new_exe_file)
109938646013SJiri Slaby {
11006e399cd1SDavidlohr Bueso 	struct file *old_exe_file;
11016e399cd1SDavidlohr Bueso 
11026e399cd1SDavidlohr Bueso 	/*
11036e399cd1SDavidlohr Bueso 	 * It is safe to dereference the exe_file without RCU as
11046e399cd1SDavidlohr Bueso 	 * this function is only called if nobody else can access
11056e399cd1SDavidlohr Bueso 	 * this mm -- see comment above for justification.
11066e399cd1SDavidlohr Bueso 	 */
11076e399cd1SDavidlohr Bueso 	old_exe_file = rcu_dereference_raw(mm->exe_file);
110890f31d0eSKonstantin Khlebnikov 
110938646013SJiri Slaby 	if (new_exe_file)
111038646013SJiri Slaby 		get_file(new_exe_file);
111190f31d0eSKonstantin Khlebnikov 	rcu_assign_pointer(mm->exe_file, new_exe_file);
111290f31d0eSKonstantin Khlebnikov 	if (old_exe_file)
111390f31d0eSKonstantin Khlebnikov 		fput(old_exe_file);
111438646013SJiri Slaby }
111538646013SJiri Slaby 
111690f31d0eSKonstantin Khlebnikov /**
111790f31d0eSKonstantin Khlebnikov  * get_mm_exe_file - acquire a reference to the mm's executable file
111890f31d0eSKonstantin Khlebnikov  *
111990f31d0eSKonstantin Khlebnikov  * Returns %NULL if mm has no associated executable file.
112090f31d0eSKonstantin Khlebnikov  * User must release file via fput().
112190f31d0eSKonstantin Khlebnikov  */
112238646013SJiri Slaby struct file *get_mm_exe_file(struct mm_struct *mm)
112338646013SJiri Slaby {
112438646013SJiri Slaby 	struct file *exe_file;
112538646013SJiri Slaby 
112690f31d0eSKonstantin Khlebnikov 	rcu_read_lock();
112790f31d0eSKonstantin Khlebnikov 	exe_file = rcu_dereference(mm->exe_file);
112890f31d0eSKonstantin Khlebnikov 	if (exe_file && !get_file_rcu(exe_file))
112990f31d0eSKonstantin Khlebnikov 		exe_file = NULL;
113090f31d0eSKonstantin Khlebnikov 	rcu_read_unlock();
113138646013SJiri Slaby 	return exe_file;
113238646013SJiri Slaby }
113311163348SDavidlohr Bueso EXPORT_SYMBOL(get_mm_exe_file);
113438646013SJiri Slaby 
11351da177e4SLinus Torvalds /**
1136cd81a917SMateusz Guzik  * get_task_exe_file - acquire a reference to the task's executable file
1137cd81a917SMateusz Guzik  *
1138cd81a917SMateusz Guzik  * Returns %NULL if task's mm (if any) has no associated executable file or
1139cd81a917SMateusz Guzik  * this is a kernel thread with borrowed mm (see the comment above get_task_mm).
1140cd81a917SMateusz Guzik  * User must release file via fput().
1141cd81a917SMateusz Guzik  */
1142cd81a917SMateusz Guzik struct file *get_task_exe_file(struct task_struct *task)
1143cd81a917SMateusz Guzik {
1144cd81a917SMateusz Guzik 	struct file *exe_file = NULL;
1145cd81a917SMateusz Guzik 	struct mm_struct *mm;
1146cd81a917SMateusz Guzik 
1147cd81a917SMateusz Guzik 	task_lock(task);
1148cd81a917SMateusz Guzik 	mm = task->mm;
1149cd81a917SMateusz Guzik 	if (mm) {
1150cd81a917SMateusz Guzik 		if (!(task->flags & PF_KTHREAD))
1151cd81a917SMateusz Guzik 			exe_file = get_mm_exe_file(mm);
1152cd81a917SMateusz Guzik 	}
1153cd81a917SMateusz Guzik 	task_unlock(task);
1154cd81a917SMateusz Guzik 	return exe_file;
1155cd81a917SMateusz Guzik }
1156cd81a917SMateusz Guzik EXPORT_SYMBOL(get_task_exe_file);
1157cd81a917SMateusz Guzik 
1158cd81a917SMateusz Guzik /**
11591da177e4SLinus Torvalds  * get_task_mm - acquire a reference to the task's mm
11601da177e4SLinus Torvalds  *
1161246bb0b1SOleg Nesterov  * Returns %NULL if the task has no mm.  Checks PF_KTHREAD (meaning
11621da177e4SLinus Torvalds  * this kernel workthread has transiently adopted a user mm with use_mm,
11631da177e4SLinus Torvalds  * to do its AIO) is not set and if so returns a reference to it, after
11641da177e4SLinus Torvalds  * bumping up the use count.  User must release the mm via mmput()
11651da177e4SLinus Torvalds  * after use.  Typically used by /proc and ptrace.
11661da177e4SLinus Torvalds  */
11671da177e4SLinus Torvalds struct mm_struct *get_task_mm(struct task_struct *task)
11681da177e4SLinus Torvalds {
11691da177e4SLinus Torvalds 	struct mm_struct *mm;
11701da177e4SLinus Torvalds 
11711da177e4SLinus Torvalds 	task_lock(task);
11721da177e4SLinus Torvalds 	mm = task->mm;
11731da177e4SLinus Torvalds 	if (mm) {
1174246bb0b1SOleg Nesterov 		if (task->flags & PF_KTHREAD)
11751da177e4SLinus Torvalds 			mm = NULL;
11761da177e4SLinus Torvalds 		else
11773fce371bSVegard Nossum 			mmget(mm);
11781da177e4SLinus Torvalds 	}
11791da177e4SLinus Torvalds 	task_unlock(task);
11801da177e4SLinus Torvalds 	return mm;
11811da177e4SLinus Torvalds }
11821da177e4SLinus Torvalds EXPORT_SYMBOL_GPL(get_task_mm);
11831da177e4SLinus Torvalds 
11848cdb878dSChristopher Yeoh struct mm_struct *mm_access(struct task_struct *task, unsigned int mode)
11858cdb878dSChristopher Yeoh {
11868cdb878dSChristopher Yeoh 	struct mm_struct *mm;
11878cdb878dSChristopher Yeoh 	int err;
11888cdb878dSChristopher Yeoh 
11898cdb878dSChristopher Yeoh 	err =  mutex_lock_killable(&task->signal->cred_guard_mutex);
11908cdb878dSChristopher Yeoh 	if (err)
11918cdb878dSChristopher Yeoh 		return ERR_PTR(err);
11928cdb878dSChristopher Yeoh 
11938cdb878dSChristopher Yeoh 	mm = get_task_mm(task);
11948cdb878dSChristopher Yeoh 	if (mm && mm != current->mm &&
11958cdb878dSChristopher Yeoh 			!ptrace_may_access(task, mode)) {
11968cdb878dSChristopher Yeoh 		mmput(mm);
11978cdb878dSChristopher Yeoh 		mm = ERR_PTR(-EACCES);
11988cdb878dSChristopher Yeoh 	}
11998cdb878dSChristopher Yeoh 	mutex_unlock(&task->signal->cred_guard_mutex);
12008cdb878dSChristopher Yeoh 
12018cdb878dSChristopher Yeoh 	return mm;
12028cdb878dSChristopher Yeoh }
12038cdb878dSChristopher Yeoh 
120457b59c4aSOleg Nesterov static void complete_vfork_done(struct task_struct *tsk)
1205c415c3b4SOleg Nesterov {
1206d68b46feSOleg Nesterov 	struct completion *vfork;
1207c415c3b4SOleg Nesterov 
1208d68b46feSOleg Nesterov 	task_lock(tsk);
1209d68b46feSOleg Nesterov 	vfork = tsk->vfork_done;
1210d68b46feSOleg Nesterov 	if (likely(vfork)) {
1211c415c3b4SOleg Nesterov 		tsk->vfork_done = NULL;
1212d68b46feSOleg Nesterov 		complete(vfork);
1213d68b46feSOleg Nesterov 	}
1214d68b46feSOleg Nesterov 	task_unlock(tsk);
1215d68b46feSOleg Nesterov }
1216d68b46feSOleg Nesterov 
1217d68b46feSOleg Nesterov static int wait_for_vfork_done(struct task_struct *child,
1218d68b46feSOleg Nesterov 				struct completion *vfork)
1219d68b46feSOleg Nesterov {
1220d68b46feSOleg Nesterov 	int killed;
1221d68b46feSOleg Nesterov 
1222d68b46feSOleg Nesterov 	freezer_do_not_count();
1223d68b46feSOleg Nesterov 	killed = wait_for_completion_killable(vfork);
1224d68b46feSOleg Nesterov 	freezer_count();
1225d68b46feSOleg Nesterov 
1226d68b46feSOleg Nesterov 	if (killed) {
1227d68b46feSOleg Nesterov 		task_lock(child);
1228d68b46feSOleg Nesterov 		child->vfork_done = NULL;
1229d68b46feSOleg Nesterov 		task_unlock(child);
1230d68b46feSOleg Nesterov 	}
1231d68b46feSOleg Nesterov 
1232d68b46feSOleg Nesterov 	put_task_struct(child);
1233d68b46feSOleg Nesterov 	return killed;
1234c415c3b4SOleg Nesterov }
1235c415c3b4SOleg Nesterov 
12361da177e4SLinus Torvalds /* Please note the differences between mmput and mm_release.
12371da177e4SLinus Torvalds  * mmput is called whenever we stop holding onto a mm_struct,
12381da177e4SLinus Torvalds  * error success whatever.
12391da177e4SLinus Torvalds  *
12401da177e4SLinus Torvalds  * mm_release is called after a mm_struct has been removed
12411da177e4SLinus Torvalds  * from the current process.
12421da177e4SLinus Torvalds  *
12431da177e4SLinus Torvalds  * This difference is important for error handling, when we
12441da177e4SLinus Torvalds  * only half set up a mm_struct for a new process and need to restore
12451da177e4SLinus Torvalds  * the old one.  Because we mmput the new mm_struct before
12461da177e4SLinus Torvalds  * restoring the old one. . .
12471da177e4SLinus Torvalds  * Eric Biederman 10 January 1998
12481da177e4SLinus Torvalds  */
12491da177e4SLinus Torvalds void mm_release(struct task_struct *tsk, struct mm_struct *mm)
12501da177e4SLinus Torvalds {
12518141c7f3SLinus Torvalds 	/* Get rid of any futexes when releasing the mm */
12528141c7f3SLinus Torvalds #ifdef CONFIG_FUTEX
1253fc6b177dSPeter Zijlstra 	if (unlikely(tsk->robust_list)) {
12548141c7f3SLinus Torvalds 		exit_robust_list(tsk);
1255fc6b177dSPeter Zijlstra 		tsk->robust_list = NULL;
1256fc6b177dSPeter Zijlstra 	}
12578141c7f3SLinus Torvalds #ifdef CONFIG_COMPAT
1258fc6b177dSPeter Zijlstra 	if (unlikely(tsk->compat_robust_list)) {
12598141c7f3SLinus Torvalds 		compat_exit_robust_list(tsk);
1260fc6b177dSPeter Zijlstra 		tsk->compat_robust_list = NULL;
1261fc6b177dSPeter Zijlstra 	}
12628141c7f3SLinus Torvalds #endif
1263322a2c10SThomas Gleixner 	if (unlikely(!list_empty(&tsk->pi_state_list)))
1264322a2c10SThomas Gleixner 		exit_pi_state_list(tsk);
12658141c7f3SLinus Torvalds #endif
12668141c7f3SLinus Torvalds 
12670326f5a9SSrikar Dronamraju 	uprobe_free_utask(tsk);
12680326f5a9SSrikar Dronamraju 
12691da177e4SLinus Torvalds 	/* Get rid of any cached register state */
12701da177e4SLinus Torvalds 	deactivate_mm(tsk, mm);
12711da177e4SLinus Torvalds 
1272fec1d011SRoland McGrath 	/*
1273735f2770SMichal Hocko 	 * Signal userspace if we're not exiting with a core dump
1274735f2770SMichal Hocko 	 * because we want to leave the value intact for debugging
1275735f2770SMichal Hocko 	 * purposes.
1276fec1d011SRoland McGrath 	 */
12779c8a8228SEric Dumazet 	if (tsk->clear_child_tid) {
1278735f2770SMichal Hocko 		if (!(tsk->signal->flags & SIGNAL_GROUP_COREDUMP) &&
12799c8a8228SEric Dumazet 		    atomic_read(&mm->mm_users) > 1) {
12801da177e4SLinus Torvalds 			/*
12811da177e4SLinus Torvalds 			 * We don't check the error code - if userspace has
12821da177e4SLinus Torvalds 			 * not set up a proper pointer then tough luck.
12831da177e4SLinus Torvalds 			 */
12849c8a8228SEric Dumazet 			put_user(0, tsk->clear_child_tid);
12852de0db99SDominik Brodowski 			do_futex(tsk->clear_child_tid, FUTEX_WAKE,
12862de0db99SDominik Brodowski 					1, NULL, NULL, 0, 0);
12879c8a8228SEric Dumazet 		}
12889c8a8228SEric Dumazet 		tsk->clear_child_tid = NULL;
12891da177e4SLinus Torvalds 	}
1290f7505d64SKonstantin Khlebnikov 
1291f7505d64SKonstantin Khlebnikov 	/*
1292f7505d64SKonstantin Khlebnikov 	 * All done, finally we can wake up parent and return this mm to him.
1293f7505d64SKonstantin Khlebnikov 	 * Also kthread_stop() uses this completion for synchronization.
1294f7505d64SKonstantin Khlebnikov 	 */
1295f7505d64SKonstantin Khlebnikov 	if (tsk->vfork_done)
1296f7505d64SKonstantin Khlebnikov 		complete_vfork_done(tsk);
12971da177e4SLinus Torvalds }
12981da177e4SLinus Torvalds 
1299a0a7ec30SJANAK DESAI /*
1300a0a7ec30SJANAK DESAI  * Allocate a new mm structure and copy contents from the
1301a0a7ec30SJANAK DESAI  * mm structure of the passed in task structure.
1302a0a7ec30SJANAK DESAI  */
1303ff252c1fSDaeSeok Youn static struct mm_struct *dup_mm(struct task_struct *tsk)
1304a0a7ec30SJANAK DESAI {
1305a0a7ec30SJANAK DESAI 	struct mm_struct *mm, *oldmm = current->mm;
1306a0a7ec30SJANAK DESAI 	int err;
1307a0a7ec30SJANAK DESAI 
1308a0a7ec30SJANAK DESAI 	mm = allocate_mm();
1309a0a7ec30SJANAK DESAI 	if (!mm)
1310a0a7ec30SJANAK DESAI 		goto fail_nomem;
1311a0a7ec30SJANAK DESAI 
1312a0a7ec30SJANAK DESAI 	memcpy(mm, oldmm, sizeof(*mm));
1313a0a7ec30SJANAK DESAI 
1314bfedb589SEric W. Biederman 	if (!mm_init(mm, tsk, mm->user_ns))
1315a0a7ec30SJANAK DESAI 		goto fail_nomem;
1316a0a7ec30SJANAK DESAI 
1317a0a7ec30SJANAK DESAI 	err = dup_mmap(mm, oldmm);
1318a0a7ec30SJANAK DESAI 	if (err)
1319a0a7ec30SJANAK DESAI 		goto free_pt;
1320a0a7ec30SJANAK DESAI 
1321a0a7ec30SJANAK DESAI 	mm->hiwater_rss = get_mm_rss(mm);
1322a0a7ec30SJANAK DESAI 	mm->hiwater_vm = mm->total_vm;
1323a0a7ec30SJANAK DESAI 
1324801460d0SHiroshi Shimamoto 	if (mm->binfmt && !try_module_get(mm->binfmt->module))
1325801460d0SHiroshi Shimamoto 		goto free_pt;
1326801460d0SHiroshi Shimamoto 
1327a0a7ec30SJANAK DESAI 	return mm;
1328a0a7ec30SJANAK DESAI 
1329a0a7ec30SJANAK DESAI free_pt:
1330801460d0SHiroshi Shimamoto 	/* don't put binfmt in mmput, we haven't got module yet */
1331801460d0SHiroshi Shimamoto 	mm->binfmt = NULL;
1332a0a7ec30SJANAK DESAI 	mmput(mm);
1333a0a7ec30SJANAK DESAI 
1334a0a7ec30SJANAK DESAI fail_nomem:
1335a0a7ec30SJANAK DESAI 	return NULL;
1336a0a7ec30SJANAK DESAI }
1337a0a7ec30SJANAK DESAI 
13381da177e4SLinus Torvalds static int copy_mm(unsigned long clone_flags, struct task_struct *tsk)
13391da177e4SLinus Torvalds {
13401da177e4SLinus Torvalds 	struct mm_struct *mm, *oldmm;
13411da177e4SLinus Torvalds 	int retval;
13421da177e4SLinus Torvalds 
13431da177e4SLinus Torvalds 	tsk->min_flt = tsk->maj_flt = 0;
13441da177e4SLinus Torvalds 	tsk->nvcsw = tsk->nivcsw = 0;
134517406b82SMandeep Singh Baines #ifdef CONFIG_DETECT_HUNG_TASK
134617406b82SMandeep Singh Baines 	tsk->last_switch_count = tsk->nvcsw + tsk->nivcsw;
1347a2e51445SDmitry Vyukov 	tsk->last_switch_time = 0;
134817406b82SMandeep Singh Baines #endif
13491da177e4SLinus Torvalds 
13501da177e4SLinus Torvalds 	tsk->mm = NULL;
13511da177e4SLinus Torvalds 	tsk->active_mm = NULL;
13521da177e4SLinus Torvalds 
13531da177e4SLinus Torvalds 	/*
13541da177e4SLinus Torvalds 	 * Are we cloning a kernel thread?
13551da177e4SLinus Torvalds 	 *
13561da177e4SLinus Torvalds 	 * We need to steal a active VM for that..
13571da177e4SLinus Torvalds 	 */
13581da177e4SLinus Torvalds 	oldmm = current->mm;
13591da177e4SLinus Torvalds 	if (!oldmm)
13601da177e4SLinus Torvalds 		return 0;
13611da177e4SLinus Torvalds 
1362615d6e87SDavidlohr Bueso 	/* initialize the new vmacache entries */
1363615d6e87SDavidlohr Bueso 	vmacache_flush(tsk);
1364615d6e87SDavidlohr Bueso 
13651da177e4SLinus Torvalds 	if (clone_flags & CLONE_VM) {
13663fce371bSVegard Nossum 		mmget(oldmm);
13671da177e4SLinus Torvalds 		mm = oldmm;
13681da177e4SLinus Torvalds 		goto good_mm;
13691da177e4SLinus Torvalds 	}
13701da177e4SLinus Torvalds 
13711da177e4SLinus Torvalds 	retval = -ENOMEM;
1372a0a7ec30SJANAK DESAI 	mm = dup_mm(tsk);
13731da177e4SLinus Torvalds 	if (!mm)
13741da177e4SLinus Torvalds 		goto fail_nomem;
13751da177e4SLinus Torvalds 
13761da177e4SLinus Torvalds good_mm:
13771da177e4SLinus Torvalds 	tsk->mm = mm;
13781da177e4SLinus Torvalds 	tsk->active_mm = mm;
13791da177e4SLinus Torvalds 	return 0;
13801da177e4SLinus Torvalds 
13811da177e4SLinus Torvalds fail_nomem:
13821da177e4SLinus Torvalds 	return retval;
13831da177e4SLinus Torvalds }
13841da177e4SLinus Torvalds 
1385a39bc516SAlexey Dobriyan static int copy_fs(unsigned long clone_flags, struct task_struct *tsk)
13861da177e4SLinus Torvalds {
1387498052bbSAl Viro 	struct fs_struct *fs = current->fs;
13881da177e4SLinus Torvalds 	if (clone_flags & CLONE_FS) {
1389498052bbSAl Viro 		/* tsk->fs is already what we want */
13902a4419b5SNick Piggin 		spin_lock(&fs->lock);
1391498052bbSAl Viro 		if (fs->in_exec) {
13922a4419b5SNick Piggin 			spin_unlock(&fs->lock);
1393498052bbSAl Viro 			return -EAGAIN;
1394498052bbSAl Viro 		}
1395498052bbSAl Viro 		fs->users++;
13962a4419b5SNick Piggin 		spin_unlock(&fs->lock);
13971da177e4SLinus Torvalds 		return 0;
13981da177e4SLinus Torvalds 	}
1399498052bbSAl Viro 	tsk->fs = copy_fs_struct(fs);
14001da177e4SLinus Torvalds 	if (!tsk->fs)
14011da177e4SLinus Torvalds 		return -ENOMEM;
14021da177e4SLinus Torvalds 	return 0;
14031da177e4SLinus Torvalds }
14041da177e4SLinus Torvalds 
1405a016f338SJANAK DESAI static int copy_files(unsigned long clone_flags, struct task_struct *tsk)
1406a016f338SJANAK DESAI {
1407a016f338SJANAK DESAI 	struct files_struct *oldf, *newf;
1408a016f338SJANAK DESAI 	int error = 0;
1409a016f338SJANAK DESAI 
1410a016f338SJANAK DESAI 	/*
1411a016f338SJANAK DESAI 	 * A background process may not have any files ...
1412a016f338SJANAK DESAI 	 */
1413a016f338SJANAK DESAI 	oldf = current->files;
1414a016f338SJANAK DESAI 	if (!oldf)
1415a016f338SJANAK DESAI 		goto out;
1416a016f338SJANAK DESAI 
1417a016f338SJANAK DESAI 	if (clone_flags & CLONE_FILES) {
1418a016f338SJANAK DESAI 		atomic_inc(&oldf->count);
1419a016f338SJANAK DESAI 		goto out;
1420a016f338SJANAK DESAI 	}
1421a016f338SJANAK DESAI 
1422a016f338SJANAK DESAI 	newf = dup_fd(oldf, &error);
1423a016f338SJANAK DESAI 	if (!newf)
1424a016f338SJANAK DESAI 		goto out;
1425a016f338SJANAK DESAI 
1426a016f338SJANAK DESAI 	tsk->files = newf;
1427a016f338SJANAK DESAI 	error = 0;
1428a016f338SJANAK DESAI out:
1429a016f338SJANAK DESAI 	return error;
1430a016f338SJANAK DESAI }
1431a016f338SJANAK DESAI 
1432fadad878SJens Axboe static int copy_io(unsigned long clone_flags, struct task_struct *tsk)
1433fd0928dfSJens Axboe {
1434fd0928dfSJens Axboe #ifdef CONFIG_BLOCK
1435fd0928dfSJens Axboe 	struct io_context *ioc = current->io_context;
14366e736be7STejun Heo 	struct io_context *new_ioc;
1437fd0928dfSJens Axboe 
1438fd0928dfSJens Axboe 	if (!ioc)
1439fd0928dfSJens Axboe 		return 0;
1440fadad878SJens Axboe 	/*
1441fadad878SJens Axboe 	 * Share io context with parent, if CLONE_IO is set
1442fadad878SJens Axboe 	 */
1443fadad878SJens Axboe 	if (clone_flags & CLONE_IO) {
14443d48749dSTejun Heo 		ioc_task_link(ioc);
14453d48749dSTejun Heo 		tsk->io_context = ioc;
1446fadad878SJens Axboe 	} else if (ioprio_valid(ioc->ioprio)) {
14476e736be7STejun Heo 		new_ioc = get_task_io_context(tsk, GFP_KERNEL, NUMA_NO_NODE);
14486e736be7STejun Heo 		if (unlikely(!new_ioc))
1449fd0928dfSJens Axboe 			return -ENOMEM;
1450fd0928dfSJens Axboe 
14516e736be7STejun Heo 		new_ioc->ioprio = ioc->ioprio;
145211a3122fSTejun Heo 		put_io_context(new_ioc);
1453fd0928dfSJens Axboe 	}
1454fd0928dfSJens Axboe #endif
1455fd0928dfSJens Axboe 	return 0;
1456fd0928dfSJens Axboe }
1457fd0928dfSJens Axboe 
1458a39bc516SAlexey Dobriyan static int copy_sighand(unsigned long clone_flags, struct task_struct *tsk)
14591da177e4SLinus Torvalds {
14601da177e4SLinus Torvalds 	struct sighand_struct *sig;
14611da177e4SLinus Torvalds 
146260348802SZhaolei 	if (clone_flags & CLONE_SIGHAND) {
14631da177e4SLinus Torvalds 		atomic_inc(&current->sighand->count);
14641da177e4SLinus Torvalds 		return 0;
14651da177e4SLinus Torvalds 	}
14661da177e4SLinus Torvalds 	sig = kmem_cache_alloc(sighand_cachep, GFP_KERNEL);
1467e56d0903SIngo Molnar 	rcu_assign_pointer(tsk->sighand, sig);
14681da177e4SLinus Torvalds 	if (!sig)
14691da177e4SLinus Torvalds 		return -ENOMEM;
14709d7fb042SPeter Zijlstra 
14711da177e4SLinus Torvalds 	atomic_set(&sig->count, 1);
147206e62a46SJann Horn 	spin_lock_irq(&current->sighand->siglock);
14731da177e4SLinus Torvalds 	memcpy(sig->action, current->sighand->action, sizeof(sig->action));
147406e62a46SJann Horn 	spin_unlock_irq(&current->sighand->siglock);
14751da177e4SLinus Torvalds 	return 0;
14761da177e4SLinus Torvalds }
14771da177e4SLinus Torvalds 
1478a7e5328aSOleg Nesterov void __cleanup_sighand(struct sighand_struct *sighand)
1479c81addc9SOleg Nesterov {
1480d80e731eSOleg Nesterov 	if (atomic_dec_and_test(&sighand->count)) {
1481d80e731eSOleg Nesterov 		signalfd_cleanup(sighand);
1482392809b2SOleg Nesterov 		/*
14835f0d5a3aSPaul E. McKenney 		 * sighand_cachep is SLAB_TYPESAFE_BY_RCU so we can free it
1484392809b2SOleg Nesterov 		 * without an RCU grace period, see __lock_task_sighand().
1485392809b2SOleg Nesterov 		 */
1486c81addc9SOleg Nesterov 		kmem_cache_free(sighand_cachep, sighand);
1487c81addc9SOleg Nesterov 	}
1488d80e731eSOleg Nesterov }
1489c81addc9SOleg Nesterov 
1490b18b6a9cSNicolas Pitre #ifdef CONFIG_POSIX_TIMERS
1491f06febc9SFrank Mayhar /*
1492f06febc9SFrank Mayhar  * Initialize POSIX timer handling for a thread group.
1493f06febc9SFrank Mayhar  */
1494f06febc9SFrank Mayhar static void posix_cpu_timers_init_group(struct signal_struct *sig)
1495f06febc9SFrank Mayhar {
149678d7d407SJiri Slaby 	unsigned long cpu_limit;
149778d7d407SJiri Slaby 
1498316c1608SJason Low 	cpu_limit = READ_ONCE(sig->rlim[RLIMIT_CPU].rlim_cur);
149978d7d407SJiri Slaby 	if (cpu_limit != RLIM_INFINITY) {
1500ebd7e7fcSFrederic Weisbecker 		sig->cputime_expires.prof_exp = cpu_limit * NSEC_PER_SEC;
1501d5c373ebSJason Low 		sig->cputimer.running = true;
15026279a751SOleg Nesterov 	}
15036279a751SOleg Nesterov 
1504f06febc9SFrank Mayhar 	/* The timer lists. */
1505f06febc9SFrank Mayhar 	INIT_LIST_HEAD(&sig->cpu_timers[0]);
1506f06febc9SFrank Mayhar 	INIT_LIST_HEAD(&sig->cpu_timers[1]);
1507f06febc9SFrank Mayhar 	INIT_LIST_HEAD(&sig->cpu_timers[2]);
1508f06febc9SFrank Mayhar }
1509b18b6a9cSNicolas Pitre #else
1510b18b6a9cSNicolas Pitre static inline void posix_cpu_timers_init_group(struct signal_struct *sig) { }
1511b18b6a9cSNicolas Pitre #endif
1512f06febc9SFrank Mayhar 
1513a39bc516SAlexey Dobriyan static int copy_signal(unsigned long clone_flags, struct task_struct *tsk)
15141da177e4SLinus Torvalds {
15151da177e4SLinus Torvalds 	struct signal_struct *sig;
15161da177e4SLinus Torvalds 
15174ab6c083SOleg Nesterov 	if (clone_flags & CLONE_THREAD)
1518490dea45SPeter Zijlstra 		return 0;
15196279a751SOleg Nesterov 
1520a56704efSVeaceslav Falico 	sig = kmem_cache_zalloc(signal_cachep, GFP_KERNEL);
15211da177e4SLinus Torvalds 	tsk->signal = sig;
15221da177e4SLinus Torvalds 	if (!sig)
15231da177e4SLinus Torvalds 		return -ENOMEM;
15241da177e4SLinus Torvalds 
1525b3ac022cSOleg Nesterov 	sig->nr_threads = 1;
15261da177e4SLinus Torvalds 	atomic_set(&sig->live, 1);
1527b3ac022cSOleg Nesterov 	atomic_set(&sig->sigcnt, 1);
15280c740d0aSOleg Nesterov 
15290c740d0aSOleg Nesterov 	/* list_add(thread_node, thread_head) without INIT_LIST_HEAD() */
15300c740d0aSOleg Nesterov 	sig->thread_head = (struct list_head)LIST_HEAD_INIT(tsk->thread_node);
15310c740d0aSOleg Nesterov 	tsk->thread_node = (struct list_head)LIST_HEAD_INIT(sig->thread_head);
15320c740d0aSOleg Nesterov 
15331da177e4SLinus Torvalds 	init_waitqueue_head(&sig->wait_chldexit);
1534db51aeccSOleg Nesterov 	sig->curr_target = tsk;
15351da177e4SLinus Torvalds 	init_sigpending(&sig->shared_pending);
1536c3ad2c3bSEric W. Biederman 	INIT_HLIST_HEAD(&sig->multiprocess);
1537e78c3496SRik van Riel 	seqlock_init(&sig->stats_lock);
15389d7fb042SPeter Zijlstra 	prev_cputime_init(&sig->prev_cputime);
15391da177e4SLinus Torvalds 
1540baa73d9eSNicolas Pitre #ifdef CONFIG_POSIX_TIMERS
1541b18b6a9cSNicolas Pitre 	INIT_LIST_HEAD(&sig->posix_timers);
1542c9cb2e3dSThomas Gleixner 	hrtimer_init(&sig->real_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
15431da177e4SLinus Torvalds 	sig->real_timer.function = it_real_fn;
1544baa73d9eSNicolas Pitre #endif
15451da177e4SLinus Torvalds 
15461da177e4SLinus Torvalds 	task_lock(current->group_leader);
15471da177e4SLinus Torvalds 	memcpy(sig->rlim, current->signal->rlim, sizeof sig->rlim);
15481da177e4SLinus Torvalds 	task_unlock(current->group_leader);
15491da177e4SLinus Torvalds 
15506279a751SOleg Nesterov 	posix_cpu_timers_init_group(sig);
15516279a751SOleg Nesterov 
1552522ed776SMiloslav Trmac 	tty_audit_fork(sig);
15535091faa4SMike Galbraith 	sched_autogroup_fork(sig);
1554522ed776SMiloslav Trmac 
1555a63d83f4SDavid Rientjes 	sig->oom_score_adj = current->signal->oom_score_adj;
1556dabb16f6SMandeep Singh Baines 	sig->oom_score_adj_min = current->signal->oom_score_adj_min;
155728b83c51SKOSAKI Motohiro 
15589b1bf12dSKOSAKI Motohiro 	mutex_init(&sig->cred_guard_mutex);
15599b1bf12dSKOSAKI Motohiro 
15601da177e4SLinus Torvalds 	return 0;
15611da177e4SLinus Torvalds }
15621da177e4SLinus Torvalds 
1563dbd95212SKees Cook static void copy_seccomp(struct task_struct *p)
1564dbd95212SKees Cook {
1565dbd95212SKees Cook #ifdef CONFIG_SECCOMP
1566dbd95212SKees Cook 	/*
1567dbd95212SKees Cook 	 * Must be called with sighand->lock held, which is common to
1568dbd95212SKees Cook 	 * all threads in the group. Holding cred_guard_mutex is not
1569dbd95212SKees Cook 	 * needed because this new task is not yet running and cannot
1570dbd95212SKees Cook 	 * be racing exec.
1571dbd95212SKees Cook 	 */
157269f6a34bSGuenter Roeck 	assert_spin_locked(&current->sighand->siglock);
1573dbd95212SKees Cook 
1574dbd95212SKees Cook 	/* Ref-count the new filter user, and assign it. */
1575dbd95212SKees Cook 	get_seccomp_filter(current);
1576dbd95212SKees Cook 	p->seccomp = current->seccomp;
1577dbd95212SKees Cook 
1578dbd95212SKees Cook 	/*
1579dbd95212SKees Cook 	 * Explicitly enable no_new_privs here in case it got set
1580dbd95212SKees Cook 	 * between the task_struct being duplicated and holding the
1581dbd95212SKees Cook 	 * sighand lock. The seccomp state and nnp must be in sync.
1582dbd95212SKees Cook 	 */
1583dbd95212SKees Cook 	if (task_no_new_privs(current))
1584dbd95212SKees Cook 		task_set_no_new_privs(p);
1585dbd95212SKees Cook 
1586dbd95212SKees Cook 	/*
1587dbd95212SKees Cook 	 * If the parent gained a seccomp mode after copying thread
1588dbd95212SKees Cook 	 * flags and between before we held the sighand lock, we have
1589dbd95212SKees Cook 	 * to manually enable the seccomp thread flag here.
1590dbd95212SKees Cook 	 */
1591dbd95212SKees Cook 	if (p->seccomp.mode != SECCOMP_MODE_DISABLED)
1592dbd95212SKees Cook 		set_tsk_thread_flag(p, TIF_SECCOMP);
1593dbd95212SKees Cook #endif
1594dbd95212SKees Cook }
1595dbd95212SKees Cook 
159617da2bd9SHeiko Carstens SYSCALL_DEFINE1(set_tid_address, int __user *, tidptr)
15971da177e4SLinus Torvalds {
15981da177e4SLinus Torvalds 	current->clear_child_tid = tidptr;
15991da177e4SLinus Torvalds 
1600b488893aSPavel Emelyanov 	return task_pid_vnr(current);
16011da177e4SLinus Torvalds }
16021da177e4SLinus Torvalds 
1603a39bc516SAlexey Dobriyan static void rt_mutex_init_task(struct task_struct *p)
160423f78d4aSIngo Molnar {
16051d615482SThomas Gleixner 	raw_spin_lock_init(&p->pi_lock);
1606e29e175bSZilvinas Valinskas #ifdef CONFIG_RT_MUTEXES
1607a23ba907SDavidlohr Bueso 	p->pi_waiters = RB_ROOT_CACHED;
1608e96a7705SXunlei Pang 	p->pi_top_task = NULL;
160923f78d4aSIngo Molnar 	p->pi_blocked_on = NULL;
161023f78d4aSIngo Molnar #endif
161123f78d4aSIngo Molnar }
161223f78d4aSIngo Molnar 
1613b18b6a9cSNicolas Pitre #ifdef CONFIG_POSIX_TIMERS
16141da177e4SLinus Torvalds /*
1615f06febc9SFrank Mayhar  * Initialize POSIX timer handling for a single task.
1616f06febc9SFrank Mayhar  */
1617f06febc9SFrank Mayhar static void posix_cpu_timers_init(struct task_struct *tsk)
1618f06febc9SFrank Mayhar {
161964861634SMartin Schwidefsky 	tsk->cputime_expires.prof_exp = 0;
162064861634SMartin Schwidefsky 	tsk->cputime_expires.virt_exp = 0;
1621f06febc9SFrank Mayhar 	tsk->cputime_expires.sched_exp = 0;
1622f06febc9SFrank Mayhar 	INIT_LIST_HEAD(&tsk->cpu_timers[0]);
1623f06febc9SFrank Mayhar 	INIT_LIST_HEAD(&tsk->cpu_timers[1]);
1624f06febc9SFrank Mayhar 	INIT_LIST_HEAD(&tsk->cpu_timers[2]);
1625f06febc9SFrank Mayhar }
1626b18b6a9cSNicolas Pitre #else
1627b18b6a9cSNicolas Pitre static inline void posix_cpu_timers_init(struct task_struct *tsk) { }
1628b18b6a9cSNicolas Pitre #endif
1629f06febc9SFrank Mayhar 
16302c470475SEric W. Biederman static inline void init_task_pid_links(struct task_struct *task)
16312c470475SEric W. Biederman {
16322c470475SEric W. Biederman 	enum pid_type type;
16332c470475SEric W. Biederman 
16342c470475SEric W. Biederman 	for (type = PIDTYPE_PID; type < PIDTYPE_MAX; ++type) {
16352c470475SEric W. Biederman 		INIT_HLIST_NODE(&task->pid_links[type]);
16362c470475SEric W. Biederman 	}
16372c470475SEric W. Biederman }
16382c470475SEric W. Biederman 
163981907739SOleg Nesterov static inline void
164081907739SOleg Nesterov init_task_pid(struct task_struct *task, enum pid_type type, struct pid *pid)
164181907739SOleg Nesterov {
16422c470475SEric W. Biederman 	if (type == PIDTYPE_PID)
16432c470475SEric W. Biederman 		task->thread_pid = pid;
16442c470475SEric W. Biederman 	else
16452c470475SEric W. Biederman 		task->signal->pids[type] = pid;
164681907739SOleg Nesterov }
164781907739SOleg Nesterov 
16486bfbaa51SIngo Molnar static inline void rcu_copy_process(struct task_struct *p)
16496bfbaa51SIngo Molnar {
16506bfbaa51SIngo Molnar #ifdef CONFIG_PREEMPT_RCU
16516bfbaa51SIngo Molnar 	p->rcu_read_lock_nesting = 0;
16526bfbaa51SIngo Molnar 	p->rcu_read_unlock_special.s = 0;
16536bfbaa51SIngo Molnar 	p->rcu_blocked_node = NULL;
16546bfbaa51SIngo Molnar 	INIT_LIST_HEAD(&p->rcu_node_entry);
16556bfbaa51SIngo Molnar #endif /* #ifdef CONFIG_PREEMPT_RCU */
16566bfbaa51SIngo Molnar #ifdef CONFIG_TASKS_RCU
16576bfbaa51SIngo Molnar 	p->rcu_tasks_holdout = false;
16586bfbaa51SIngo Molnar 	INIT_LIST_HEAD(&p->rcu_tasks_holdout_list);
16596bfbaa51SIngo Molnar 	p->rcu_tasks_idle_cpu = -1;
16606bfbaa51SIngo Molnar #endif /* #ifdef CONFIG_TASKS_RCU */
16616bfbaa51SIngo Molnar }
16626bfbaa51SIngo Molnar 
1663f06febc9SFrank Mayhar /*
16641da177e4SLinus Torvalds  * This creates a new process as a copy of the old one,
16651da177e4SLinus Torvalds  * but does not actually start it yet.
16661da177e4SLinus Torvalds  *
16671da177e4SLinus Torvalds  * It copies the registers, and all the appropriate
16681da177e4SLinus Torvalds  * parts of the process environment (as per the clone
16691da177e4SLinus Torvalds  * flags). The actual kick-off is left to the caller.
16701da177e4SLinus Torvalds  */
16710766f788SEmese Revfy static __latent_entropy struct task_struct *copy_process(
16720766f788SEmese Revfy 					unsigned long clone_flags,
16731da177e4SLinus Torvalds 					unsigned long stack_start,
16741da177e4SLinus Torvalds 					unsigned long stack_size,
16751da177e4SLinus Torvalds 					int __user *child_tidptr,
167609a05394SRoland McGrath 					struct pid *pid,
16773033f14aSJosh Triplett 					int trace,
1678725fc629SAndi Kleen 					unsigned long tls,
1679725fc629SAndi Kleen 					int node)
16801da177e4SLinus Torvalds {
16811da177e4SLinus Torvalds 	int retval;
1682a24efe62SMariusz Kozlowski 	struct task_struct *p;
1683c3ad2c3bSEric W. Biederman 	struct multiprocess_signals delayed;
16841da177e4SLinus Torvalds 
1685667b6094SMarcos Paulo de Souza 	/*
1686667b6094SMarcos Paulo de Souza 	 * Don't allow sharing the root directory with processes in a different
1687667b6094SMarcos Paulo de Souza 	 * namespace
1688667b6094SMarcos Paulo de Souza 	 */
16891da177e4SLinus Torvalds 	if ((clone_flags & (CLONE_NEWNS|CLONE_FS)) == (CLONE_NEWNS|CLONE_FS))
16901da177e4SLinus Torvalds 		return ERR_PTR(-EINVAL);
16911da177e4SLinus Torvalds 
1692e66eded8SEric W. Biederman 	if ((clone_flags & (CLONE_NEWUSER|CLONE_FS)) == (CLONE_NEWUSER|CLONE_FS))
1693e66eded8SEric W. Biederman 		return ERR_PTR(-EINVAL);
1694e66eded8SEric W. Biederman 
16951da177e4SLinus Torvalds 	/*
16961da177e4SLinus Torvalds 	 * Thread groups must share signals as well, and detached threads
16971da177e4SLinus Torvalds 	 * can only be started up within the thread group.
16981da177e4SLinus Torvalds 	 */
16991da177e4SLinus Torvalds 	if ((clone_flags & CLONE_THREAD) && !(clone_flags & CLONE_SIGHAND))
17001da177e4SLinus Torvalds 		return ERR_PTR(-EINVAL);
17011da177e4SLinus Torvalds 
17021da177e4SLinus Torvalds 	/*
17031da177e4SLinus Torvalds 	 * Shared signal handlers imply shared VM. By way of the above,
17041da177e4SLinus Torvalds 	 * thread groups also imply shared VM. Blocking this case allows
17051da177e4SLinus Torvalds 	 * for various simplifications in other code.
17061da177e4SLinus Torvalds 	 */
17071da177e4SLinus Torvalds 	if ((clone_flags & CLONE_SIGHAND) && !(clone_flags & CLONE_VM))
17081da177e4SLinus Torvalds 		return ERR_PTR(-EINVAL);
17091da177e4SLinus Torvalds 
1710123be07bSSukadev Bhattiprolu 	/*
1711123be07bSSukadev Bhattiprolu 	 * Siblings of global init remain as zombies on exit since they are
1712123be07bSSukadev Bhattiprolu 	 * not reaped by their parent (swapper). To solve this and to avoid
1713123be07bSSukadev Bhattiprolu 	 * multi-rooted process trees, prevent global and container-inits
1714123be07bSSukadev Bhattiprolu 	 * from creating siblings.
1715123be07bSSukadev Bhattiprolu 	 */
1716123be07bSSukadev Bhattiprolu 	if ((clone_flags & CLONE_PARENT) &&
1717123be07bSSukadev Bhattiprolu 				current->signal->flags & SIGNAL_UNKILLABLE)
1718123be07bSSukadev Bhattiprolu 		return ERR_PTR(-EINVAL);
1719123be07bSSukadev Bhattiprolu 
17208382fcacSEric W. Biederman 	/*
172140a0d32dSOleg Nesterov 	 * If the new process will be in a different pid or user namespace
1722faf00da5SEric W. Biederman 	 * do not allow it to share a thread group with the forking task.
17238382fcacSEric W. Biederman 	 */
1724faf00da5SEric W. Biederman 	if (clone_flags & CLONE_THREAD) {
172540a0d32dSOleg Nesterov 		if ((clone_flags & (CLONE_NEWUSER | CLONE_NEWPID)) ||
172640a0d32dSOleg Nesterov 		    (task_active_pid_ns(current) !=
1727c2b1df2eSAndy Lutomirski 				current->nsproxy->pid_ns_for_children))
17288382fcacSEric W. Biederman 			return ERR_PTR(-EINVAL);
172940a0d32dSOleg Nesterov 	}
17308382fcacSEric W. Biederman 
1731c3ad2c3bSEric W. Biederman 	/*
1732c3ad2c3bSEric W. Biederman 	 * Force any signals received before this point to be delivered
1733c3ad2c3bSEric W. Biederman 	 * before the fork happens.  Collect up signals sent to multiple
1734c3ad2c3bSEric W. Biederman 	 * processes that happen during the fork and delay them so that
1735c3ad2c3bSEric W. Biederman 	 * they appear to happen after the fork.
1736c3ad2c3bSEric W. Biederman 	 */
1737c3ad2c3bSEric W. Biederman 	sigemptyset(&delayed.signal);
1738c3ad2c3bSEric W. Biederman 	INIT_HLIST_NODE(&delayed.node);
1739c3ad2c3bSEric W. Biederman 
1740c3ad2c3bSEric W. Biederman 	spin_lock_irq(&current->sighand->siglock);
1741c3ad2c3bSEric W. Biederman 	if (!(clone_flags & CLONE_THREAD))
1742c3ad2c3bSEric W. Biederman 		hlist_add_head(&delayed.node, &current->signal->multiprocess);
1743c3ad2c3bSEric W. Biederman 	recalc_sigpending();
1744c3ad2c3bSEric W. Biederman 	spin_unlock_irq(&current->sighand->siglock);
1745c3ad2c3bSEric W. Biederman 	retval = -ERESTARTNOINTR;
1746c3ad2c3bSEric W. Biederman 	if (signal_pending(current))
1747c3ad2c3bSEric W. Biederman 		goto fork_out;
1748c3ad2c3bSEric W. Biederman 
17491da177e4SLinus Torvalds 	retval = -ENOMEM;
1750725fc629SAndi Kleen 	p = dup_task_struct(current, node);
17511da177e4SLinus Torvalds 	if (!p)
17521da177e4SLinus Torvalds 		goto fork_out;
17531da177e4SLinus Torvalds 
17544d6501dcSVegard Nossum 	/*
17554d6501dcSVegard Nossum 	 * This _must_ happen before we call free_task(), i.e. before we jump
17564d6501dcSVegard Nossum 	 * to any of the bad_fork_* labels. This is to avoid freeing
17574d6501dcSVegard Nossum 	 * p->set_child_tid which is (ab)used as a kthread's data pointer for
17584d6501dcSVegard Nossum 	 * kernel threads (PF_KTHREAD).
17594d6501dcSVegard Nossum 	 */
17604d6501dcSVegard Nossum 	p->set_child_tid = (clone_flags & CLONE_CHILD_SETTID) ? child_tidptr : NULL;
17614d6501dcSVegard Nossum 	/*
17624d6501dcSVegard Nossum 	 * Clear TID on mm_release()?
17634d6501dcSVegard Nossum 	 */
17644d6501dcSVegard Nossum 	p->clear_child_tid = (clone_flags & CLONE_CHILD_CLEARTID) ? child_tidptr : NULL;
17654d6501dcSVegard Nossum 
1766f7e8b616SSteven Rostedt 	ftrace_graph_init_task(p);
1767f7e8b616SSteven Rostedt 
1768bea493a0SPeter Zijlstra 	rt_mutex_init_task(p);
1769bea493a0SPeter Zijlstra 
1770d12c1a37SIngo Molnar #ifdef CONFIG_PROVE_LOCKING
1771de30a2b3SIngo Molnar 	DEBUG_LOCKS_WARN_ON(!p->hardirqs_enabled);
1772de30a2b3SIngo Molnar 	DEBUG_LOCKS_WARN_ON(!p->softirqs_enabled);
1773de30a2b3SIngo Molnar #endif
17741da177e4SLinus Torvalds 	retval = -EAGAIN;
17753b11a1deSDavid Howells 	if (atomic_read(&p->real_cred->user->processes) >=
177678d7d407SJiri Slaby 			task_rlimit(p, RLIMIT_NPROC)) {
1777b57922b6SEric Paris 		if (p->real_cred->user != INIT_USER &&
1778b57922b6SEric Paris 		    !capable(CAP_SYS_RESOURCE) && !capable(CAP_SYS_ADMIN))
17791da177e4SLinus Torvalds 			goto bad_fork_free;
17801da177e4SLinus Torvalds 	}
178172fa5997SVasiliy Kulikov 	current->flags &= ~PF_NPROC_EXCEEDED;
17821da177e4SLinus Torvalds 
1783f1752eecSDavid Howells 	retval = copy_creds(p, clone_flags);
1784f1752eecSDavid Howells 	if (retval < 0)
1785f1752eecSDavid Howells 		goto bad_fork_free;
17861da177e4SLinus Torvalds 
17871da177e4SLinus Torvalds 	/*
17881da177e4SLinus Torvalds 	 * If multiple threads are within copy_process(), then this check
17891da177e4SLinus Torvalds 	 * triggers too late. This doesn't hurt, the check is only there
17901da177e4SLinus Torvalds 	 * to stop root fork bombs.
17911da177e4SLinus Torvalds 	 */
179204ec93feSLi Zefan 	retval = -EAGAIN;
17931da177e4SLinus Torvalds 	if (nr_threads >= max_threads)
17941da177e4SLinus Torvalds 		goto bad_fork_cleanup_count;
17951da177e4SLinus Torvalds 
1796ca74e92bSShailabh Nagar 	delayacct_tsk_init(p);	/* Must remain after dup_task_struct() */
1797c1de45caSPeter Zijlstra 	p->flags &= ~(PF_SUPERPRIV | PF_WQ_WORKER | PF_IDLE);
1798514ddb44SDavid Rientjes 	p->flags |= PF_FORKNOEXEC;
17991da177e4SLinus Torvalds 	INIT_LIST_HEAD(&p->children);
18001da177e4SLinus Torvalds 	INIT_LIST_HEAD(&p->sibling);
1801f41d911fSPaul E. McKenney 	rcu_copy_process(p);
18021da177e4SLinus Torvalds 	p->vfork_done = NULL;
18031da177e4SLinus Torvalds 	spin_lock_init(&p->alloc_lock);
18041da177e4SLinus Torvalds 
18051da177e4SLinus Torvalds 	init_sigpending(&p->pending);
18061da177e4SLinus Torvalds 
180764861634SMartin Schwidefsky 	p->utime = p->stime = p->gtime = 0;
180840565b5aSStanislaw Gruszka #ifdef CONFIG_ARCH_HAS_SCALED_CPUTIME
180964861634SMartin Schwidefsky 	p->utimescaled = p->stimescaled = 0;
181040565b5aSStanislaw Gruszka #endif
18119d7fb042SPeter Zijlstra 	prev_cputime_init(&p->prev_cputime);
18129d7fb042SPeter Zijlstra 
18136a61671bSFrederic Weisbecker #ifdef CONFIG_VIRT_CPU_ACCOUNTING_GEN
1814bac5b6b6SFrederic Weisbecker 	seqcount_init(&p->vtime.seqcount);
1815bac5b6b6SFrederic Weisbecker 	p->vtime.starttime = 0;
1816bac5b6b6SFrederic Weisbecker 	p->vtime.state = VTIME_INACTIVE;
18176a61671bSFrederic Weisbecker #endif
18186a61671bSFrederic Weisbecker 
1819a3a2e76cSKAMEZAWA Hiroyuki #if defined(SPLIT_RSS_COUNTING)
1820a3a2e76cSKAMEZAWA Hiroyuki 	memset(&p->rss_stat, 0, sizeof(p->rss_stat));
1821a3a2e76cSKAMEZAWA Hiroyuki #endif
1822172ba844SBalbir Singh 
18236976675dSArjan van de Ven 	p->default_timer_slack_ns = current->timer_slack_ns;
18246976675dSArjan van de Ven 
1825*eb414681SJohannes Weiner #ifdef CONFIG_PSI
1826*eb414681SJohannes Weiner 	p->psi_flags = 0;
1827*eb414681SJohannes Weiner #endif
1828*eb414681SJohannes Weiner 
18295995477aSAndrea Righi 	task_io_accounting_init(&p->ioac);
18301da177e4SLinus Torvalds 	acct_clear_integrals(p);
18311da177e4SLinus Torvalds 
1832f06febc9SFrank Mayhar 	posix_cpu_timers_init(p);
18331da177e4SLinus Torvalds 
1834ccbf62d8SThomas Gleixner 	p->start_time = ktime_get_ns();
183557e0be04SThomas Gleixner 	p->real_start_time = ktime_get_boot_ns();
18361da177e4SLinus Torvalds 	p->io_context = NULL;
1837c0b0ae8aSRichard Guy Briggs 	audit_set_context(p, NULL);
1838b4f48b63SPaul Menage 	cgroup_fork(p);
18391da177e4SLinus Torvalds #ifdef CONFIG_NUMA
1840846a16bfSLee Schermerhorn 	p->mempolicy = mpol_dup(p->mempolicy);
18411da177e4SLinus Torvalds 	if (IS_ERR(p->mempolicy)) {
18421da177e4SLinus Torvalds 		retval = PTR_ERR(p->mempolicy);
18431da177e4SLinus Torvalds 		p->mempolicy = NULL;
1844e8604cb4SLi Zefan 		goto bad_fork_cleanup_threadgroup_lock;
18451da177e4SLinus Torvalds 	}
18461da177e4SLinus Torvalds #endif
1847778d3b0fSMichal Hocko #ifdef CONFIG_CPUSETS
1848778d3b0fSMichal Hocko 	p->cpuset_mem_spread_rotor = NUMA_NO_NODE;
1849778d3b0fSMichal Hocko 	p->cpuset_slab_spread_rotor = NUMA_NO_NODE;
1850cc9a6c87SMel Gorman 	seqcount_init(&p->mems_allowed_seq);
1851778d3b0fSMichal Hocko #endif
1852de30a2b3SIngo Molnar #ifdef CONFIG_TRACE_IRQFLAGS
1853de30a2b3SIngo Molnar 	p->irq_events = 0;
1854de30a2b3SIngo Molnar 	p->hardirqs_enabled = 0;
1855de30a2b3SIngo Molnar 	p->hardirq_enable_ip = 0;
1856de30a2b3SIngo Molnar 	p->hardirq_enable_event = 0;
1857de30a2b3SIngo Molnar 	p->hardirq_disable_ip = _THIS_IP_;
1858de30a2b3SIngo Molnar 	p->hardirq_disable_event = 0;
1859de30a2b3SIngo Molnar 	p->softirqs_enabled = 1;
1860de30a2b3SIngo Molnar 	p->softirq_enable_ip = _THIS_IP_;
1861de30a2b3SIngo Molnar 	p->softirq_enable_event = 0;
1862de30a2b3SIngo Molnar 	p->softirq_disable_ip = 0;
1863de30a2b3SIngo Molnar 	p->softirq_disable_event = 0;
1864de30a2b3SIngo Molnar 	p->hardirq_context = 0;
1865de30a2b3SIngo Molnar 	p->softirq_context = 0;
1866de30a2b3SIngo Molnar #endif
18678bcbde54SDavid Hildenbrand 
18688bcbde54SDavid Hildenbrand 	p->pagefault_disabled = 0;
18698bcbde54SDavid Hildenbrand 
1870fbb9ce95SIngo Molnar #ifdef CONFIG_LOCKDEP
1871fbb9ce95SIngo Molnar 	p->lockdep_depth = 0; /* no locks held yet */
1872fbb9ce95SIngo Molnar 	p->curr_chain_key = 0;
1873fbb9ce95SIngo Molnar 	p->lockdep_recursion = 0;
1874b09be676SByungchul Park 	lockdep_init_task(p);
1875fbb9ce95SIngo Molnar #endif
18761da177e4SLinus Torvalds 
1877408894eeSIngo Molnar #ifdef CONFIG_DEBUG_MUTEXES
1878408894eeSIngo Molnar 	p->blocked_on = NULL; /* not blocked yet */
1879408894eeSIngo Molnar #endif
1880cafe5635SKent Overstreet #ifdef CONFIG_BCACHE
1881cafe5635SKent Overstreet 	p->sequential_io	= 0;
1882cafe5635SKent Overstreet 	p->sequential_io_avg	= 0;
1883cafe5635SKent Overstreet #endif
18840f481406SMarkus Metzger 
18853c90e6e9SSrivatsa Vaddagiri 	/* Perform scheduler related setup. Assign this task to a CPU. */
1886aab03e05SDario Faggioli 	retval = sched_fork(clone_flags, p);
1887aab03e05SDario Faggioli 	if (retval)
1888aab03e05SDario Faggioli 		goto bad_fork_cleanup_policy;
18896ab423e0SPeter Zijlstra 
1890cdd6c482SIngo Molnar 	retval = perf_event_init_task(p);
18916ab423e0SPeter Zijlstra 	if (retval)
18926ab423e0SPeter Zijlstra 		goto bad_fork_cleanup_policy;
1893fb0a685cSDaniel Rebelo de Oliveira 	retval = audit_alloc(p);
1894fb0a685cSDaniel Rebelo de Oliveira 	if (retval)
18956c72e350SPeter Zijlstra 		goto bad_fork_cleanup_perf;
18961da177e4SLinus Torvalds 	/* copy all the process information */
1897ab602f79SJack Miller 	shm_init_task(p);
1898e4e55b47STetsuo Handa 	retval = security_task_alloc(p, clone_flags);
1899fb0a685cSDaniel Rebelo de Oliveira 	if (retval)
19001da177e4SLinus Torvalds 		goto bad_fork_cleanup_audit;
1901e4e55b47STetsuo Handa 	retval = copy_semundo(clone_flags, p);
1902e4e55b47STetsuo Handa 	if (retval)
1903e4e55b47STetsuo Handa 		goto bad_fork_cleanup_security;
1904fb0a685cSDaniel Rebelo de Oliveira 	retval = copy_files(clone_flags, p);
1905fb0a685cSDaniel Rebelo de Oliveira 	if (retval)
19061da177e4SLinus Torvalds 		goto bad_fork_cleanup_semundo;
1907fb0a685cSDaniel Rebelo de Oliveira 	retval = copy_fs(clone_flags, p);
1908fb0a685cSDaniel Rebelo de Oliveira 	if (retval)
19091da177e4SLinus Torvalds 		goto bad_fork_cleanup_files;
1910fb0a685cSDaniel Rebelo de Oliveira 	retval = copy_sighand(clone_flags, p);
1911fb0a685cSDaniel Rebelo de Oliveira 	if (retval)
19121da177e4SLinus Torvalds 		goto bad_fork_cleanup_fs;
1913fb0a685cSDaniel Rebelo de Oliveira 	retval = copy_signal(clone_flags, p);
1914fb0a685cSDaniel Rebelo de Oliveira 	if (retval)
19151da177e4SLinus Torvalds 		goto bad_fork_cleanup_sighand;
1916fb0a685cSDaniel Rebelo de Oliveira 	retval = copy_mm(clone_flags, p);
1917fb0a685cSDaniel Rebelo de Oliveira 	if (retval)
19181da177e4SLinus Torvalds 		goto bad_fork_cleanup_signal;
1919fb0a685cSDaniel Rebelo de Oliveira 	retval = copy_namespaces(clone_flags, p);
1920fb0a685cSDaniel Rebelo de Oliveira 	if (retval)
1921d84f4f99SDavid Howells 		goto bad_fork_cleanup_mm;
1922fb0a685cSDaniel Rebelo de Oliveira 	retval = copy_io(clone_flags, p);
1923fb0a685cSDaniel Rebelo de Oliveira 	if (retval)
1924fd0928dfSJens Axboe 		goto bad_fork_cleanup_namespaces;
19253033f14aSJosh Triplett 	retval = copy_thread_tls(clone_flags, stack_start, stack_size, p, tls);
19261da177e4SLinus Torvalds 	if (retval)
1927fd0928dfSJens Axboe 		goto bad_fork_cleanup_io;
19281da177e4SLinus Torvalds 
1929425fb2b4SPavel Emelyanov 	if (pid != &init_struct_pid) {
1930c2b1df2eSAndy Lutomirski 		pid = alloc_pid(p->nsproxy->pid_ns_for_children);
193135f71bc0SMichal Hocko 		if (IS_ERR(pid)) {
193235f71bc0SMichal Hocko 			retval = PTR_ERR(pid);
19330740aa5fSJiri Slaby 			goto bad_fork_cleanup_thread;
1934425fb2b4SPavel Emelyanov 		}
193535f71bc0SMichal Hocko 	}
1936425fb2b4SPavel Emelyanov 
193773c10101SJens Axboe #ifdef CONFIG_BLOCK
193873c10101SJens Axboe 	p->plug = NULL;
193973c10101SJens Axboe #endif
194042b2dd0aSAlexey Dobriyan #ifdef CONFIG_FUTEX
19418f17d3a5SIngo Molnar 	p->robust_list = NULL;
19428f17d3a5SIngo Molnar #ifdef CONFIG_COMPAT
19438f17d3a5SIngo Molnar 	p->compat_robust_list = NULL;
19448f17d3a5SIngo Molnar #endif
1945c87e2837SIngo Molnar 	INIT_LIST_HEAD(&p->pi_state_list);
1946c87e2837SIngo Molnar 	p->pi_state_cache = NULL;
194742b2dd0aSAlexey Dobriyan #endif
19481da177e4SLinus Torvalds 	/*
1949f9a3879aSGOTO Masanori 	 * sigaltstack should be cleared when sharing the same VM
1950f9a3879aSGOTO Masanori 	 */
1951f9a3879aSGOTO Masanori 	if ((clone_flags & (CLONE_VM|CLONE_VFORK)) == CLONE_VM)
19522a742138SStas Sergeev 		sas_ss_reset(p);
1953f9a3879aSGOTO Masanori 
1954f9a3879aSGOTO Masanori 	/*
19556580807dSOleg Nesterov 	 * Syscall tracing and stepping should be turned off in the
19566580807dSOleg Nesterov 	 * child regardless of CLONE_PTRACE.
19571da177e4SLinus Torvalds 	 */
19586580807dSOleg Nesterov 	user_disable_single_step(p);
19591da177e4SLinus Torvalds 	clear_tsk_thread_flag(p, TIF_SYSCALL_TRACE);
1960ed75e8d5SLaurent Vivier #ifdef TIF_SYSCALL_EMU
1961ed75e8d5SLaurent Vivier 	clear_tsk_thread_flag(p, TIF_SYSCALL_EMU);
1962ed75e8d5SLaurent Vivier #endif
19639745512cSArjan van de Ven 	clear_all_latency_tracing(p);
19641da177e4SLinus Torvalds 
19651da177e4SLinus Torvalds 	/* ok, now we should be set up.. */
196618c830dfSOleg Nesterov 	p->pid = pid_nr(pid);
196718c830dfSOleg Nesterov 	if (clone_flags & CLONE_THREAD) {
19685f8aadd8SOleg Nesterov 		p->exit_signal = -1;
196918c830dfSOleg Nesterov 		p->group_leader = current->group_leader;
197018c830dfSOleg Nesterov 		p->tgid = current->tgid;
197118c830dfSOleg Nesterov 	} else {
197218c830dfSOleg Nesterov 		if (clone_flags & CLONE_PARENT)
19735f8aadd8SOleg Nesterov 			p->exit_signal = current->group_leader->exit_signal;
19745f8aadd8SOleg Nesterov 		else
19755f8aadd8SOleg Nesterov 			p->exit_signal = (clone_flags & CSIGNAL);
197618c830dfSOleg Nesterov 		p->group_leader = p;
197718c830dfSOleg Nesterov 		p->tgid = p->pid;
197818c830dfSOleg Nesterov 	}
19795f8aadd8SOleg Nesterov 
19809d823e8fSWu Fengguang 	p->nr_dirtied = 0;
19819d823e8fSWu Fengguang 	p->nr_dirtied_pause = 128 >> (PAGE_SHIFT - 10);
198283712358SWu Fengguang 	p->dirty_paused_when = 0;
19839d823e8fSWu Fengguang 
1984bb8cbbfeSOleg Nesterov 	p->pdeath_signal = 0;
198547e65328SOleg Nesterov 	INIT_LIST_HEAD(&p->thread_group);
1986158e1645SAl Viro 	p->task_works = NULL;
19871da177e4SLinus Torvalds 
1988780de9ddSIngo Molnar 	cgroup_threadgroup_change_begin(current);
198918c830dfSOleg Nesterov 	/*
19907e47682eSAleksa Sarai 	 * Ensure that the cgroup subsystem policies allow the new process to be
19917e47682eSAleksa Sarai 	 * forked. It should be noted the the new process's css_set can be changed
19927e47682eSAleksa Sarai 	 * between here and cgroup_post_fork() if an organisation operation is in
19937e47682eSAleksa Sarai 	 * progress.
19947e47682eSAleksa Sarai 	 */
1995b53202e6SOleg Nesterov 	retval = cgroup_can_fork(p);
19967e47682eSAleksa Sarai 	if (retval)
19977e47682eSAleksa Sarai 		goto bad_fork_free_pid;
19987e47682eSAleksa Sarai 
19997e47682eSAleksa Sarai 	/*
200018c830dfSOleg Nesterov 	 * Make it visible to the rest of the system, but dont wake it up yet.
200118c830dfSOleg Nesterov 	 * Need tasklist lock for parent etc handling!
200218c830dfSOleg Nesterov 	 */
20031da177e4SLinus Torvalds 	write_lock_irq(&tasklist_lock);
20041da177e4SLinus Torvalds 
20051da177e4SLinus Torvalds 	/* CLONE_PARENT re-uses the old parent */
20062d5516cbSOleg Nesterov 	if (clone_flags & (CLONE_PARENT|CLONE_THREAD)) {
20071da177e4SLinus Torvalds 		p->real_parent = current->real_parent;
20082d5516cbSOleg Nesterov 		p->parent_exec_id = current->parent_exec_id;
20092d5516cbSOleg Nesterov 	} else {
20101da177e4SLinus Torvalds 		p->real_parent = current;
20112d5516cbSOleg Nesterov 		p->parent_exec_id = current->self_exec_id;
20122d5516cbSOleg Nesterov 	}
20131da177e4SLinus Torvalds 
2014d83a7cb3SJosh Poimboeuf 	klp_copy_process(p);
2015d83a7cb3SJosh Poimboeuf 
20161da177e4SLinus Torvalds 	spin_lock(&current->sighand->siglock);
20174a2c7a78SOleg Nesterov 
20184a2c7a78SOleg Nesterov 	/*
2019dbd95212SKees Cook 	 * Copy seccomp details explicitly here, in case they were changed
2020dbd95212SKees Cook 	 * before holding sighand lock.
2021dbd95212SKees Cook 	 */
2022dbd95212SKees Cook 	copy_seccomp(p);
2023dbd95212SKees Cook 
2024d7822b1eSMathieu Desnoyers 	rseq_fork(p, clone_flags);
2025d7822b1eSMathieu Desnoyers 
20264ca1d3eeSEric W. Biederman 	/* Don't start children in a dying pid namespace */
2027e8cfbc24SGargi Sharma 	if (unlikely(!(ns_of_pid(pid)->pid_allocated & PIDNS_ADDING))) {
20283fd37226SKirill Tkhai 		retval = -ENOMEM;
20293fd37226SKirill Tkhai 		goto bad_fork_cancel_cgroup;
20303fd37226SKirill Tkhai 	}
20314a2c7a78SOleg Nesterov 
20327673bf55SEric W. Biederman 	/* Let kill terminate clone/fork in the middle */
20337673bf55SEric W. Biederman 	if (fatal_signal_pending(current)) {
20347673bf55SEric W. Biederman 		retval = -EINTR;
20357673bf55SEric W. Biederman 		goto bad_fork_cancel_cgroup;
20367673bf55SEric W. Biederman 	}
20377673bf55SEric W. Biederman 
20381da177e4SLinus Torvalds 
20392c470475SEric W. Biederman 	init_task_pid_links(p);
204073b9ebfeSOleg Nesterov 	if (likely(p->pid)) {
20414b9d33e6STejun Heo 		ptrace_init_task(p, (clone_flags & CLONE_PTRACE) || trace);
20421da177e4SLinus Torvalds 
204381907739SOleg Nesterov 		init_task_pid(p, PIDTYPE_PID, pid);
20441da177e4SLinus Torvalds 		if (thread_group_leader(p)) {
20456883f81aSEric W. Biederman 			init_task_pid(p, PIDTYPE_TGID, pid);
204681907739SOleg Nesterov 			init_task_pid(p, PIDTYPE_PGID, task_pgrp(current));
204781907739SOleg Nesterov 			init_task_pid(p, PIDTYPE_SID, task_session(current));
204881907739SOleg Nesterov 
20491c4042c2SEric W. Biederman 			if (is_child_reaper(pid)) {
205017cf22c3SEric W. Biederman 				ns_of_pid(pid)->child_reaper = p;
20511c4042c2SEric W. Biederman 				p->signal->flags |= SIGNAL_UNKILLABLE;
20521c4042c2SEric W. Biederman 			}
2053c3ad2c3bSEric W. Biederman 			p->signal->shared_pending.signal = delayed.signal;
20549c9f4dedSAlan Cox 			p->signal->tty = tty_kref_get(current->signal->tty);
2055749860ceSPavel Tikhomirov 			/*
2056749860ceSPavel Tikhomirov 			 * Inherit has_child_subreaper flag under the same
2057749860ceSPavel Tikhomirov 			 * tasklist_lock with adding child to the process tree
2058749860ceSPavel Tikhomirov 			 * for propagate_has_child_subreaper optimization.
2059749860ceSPavel Tikhomirov 			 */
2060749860ceSPavel Tikhomirov 			p->signal->has_child_subreaper = p->real_parent->signal->has_child_subreaper ||
2061749860ceSPavel Tikhomirov 							 p->real_parent->signal->is_child_subreaper;
20629cd80bbbSOleg Nesterov 			list_add_tail(&p->sibling, &p->real_parent->children);
20635e85d4abSEric W. Biederman 			list_add_tail_rcu(&p->tasks, &init_task.tasks);
20646883f81aSEric W. Biederman 			attach_pid(p, PIDTYPE_TGID);
206581907739SOleg Nesterov 			attach_pid(p, PIDTYPE_PGID);
206681907739SOleg Nesterov 			attach_pid(p, PIDTYPE_SID);
2067909ea964SChristoph Lameter 			__this_cpu_inc(process_counts);
206880628ca0SOleg Nesterov 		} else {
206980628ca0SOleg Nesterov 			current->signal->nr_threads++;
207080628ca0SOleg Nesterov 			atomic_inc(&current->signal->live);
207180628ca0SOleg Nesterov 			atomic_inc(&current->signal->sigcnt);
2072924de3b8SEric W. Biederman 			task_join_group_stop(p);
207380628ca0SOleg Nesterov 			list_add_tail_rcu(&p->thread_group,
207480628ca0SOleg Nesterov 					  &p->group_leader->thread_group);
20750c740d0aSOleg Nesterov 			list_add_tail_rcu(&p->thread_node,
20760c740d0aSOleg Nesterov 					  &p->signal->thread_head);
20771da177e4SLinus Torvalds 		}
207881907739SOleg Nesterov 		attach_pid(p, PIDTYPE_PID);
20791da177e4SLinus Torvalds 		nr_threads++;
208073b9ebfeSOleg Nesterov 	}
20811da177e4SLinus Torvalds 	total_forks++;
2082c3ad2c3bSEric W. Biederman 	hlist_del_init(&delayed.node);
20833f17da69SOleg Nesterov 	spin_unlock(&current->sighand->siglock);
20844af4206bSOleg Nesterov 	syscall_tracepoint_update(p);
20851da177e4SLinus Torvalds 	write_unlock_irq(&tasklist_lock);
20864af4206bSOleg Nesterov 
2087c13cf856SAndrew Morton 	proc_fork_connector(p);
2088b53202e6SOleg Nesterov 	cgroup_post_fork(p);
2089780de9ddSIngo Molnar 	cgroup_threadgroup_change_end(current);
2090cdd6c482SIngo Molnar 	perf_event_fork(p);
209143d2b113SKAMEZAWA Hiroyuki 
209243d2b113SKAMEZAWA Hiroyuki 	trace_task_newtask(p, clone_flags);
20933ab67966SOleg Nesterov 	uprobe_copy_process(p, clone_flags);
209443d2b113SKAMEZAWA Hiroyuki 
20951da177e4SLinus Torvalds 	return p;
20961da177e4SLinus Torvalds 
20977e47682eSAleksa Sarai bad_fork_cancel_cgroup:
20983fd37226SKirill Tkhai 	spin_unlock(&current->sighand->siglock);
20993fd37226SKirill Tkhai 	write_unlock_irq(&tasklist_lock);
2100b53202e6SOleg Nesterov 	cgroup_cancel_fork(p);
2101425fb2b4SPavel Emelyanov bad_fork_free_pid:
2102780de9ddSIngo Molnar 	cgroup_threadgroup_change_end(current);
2103425fb2b4SPavel Emelyanov 	if (pid != &init_struct_pid)
2104425fb2b4SPavel Emelyanov 		free_pid(pid);
21050740aa5fSJiri Slaby bad_fork_cleanup_thread:
21060740aa5fSJiri Slaby 	exit_thread(p);
2107fd0928dfSJens Axboe bad_fork_cleanup_io:
2108b69f2292SLouis Rilling 	if (p->io_context)
2109b69f2292SLouis Rilling 		exit_io_context(p);
2110ab516013SSerge E. Hallyn bad_fork_cleanup_namespaces:
2111444f378bSLinus Torvalds 	exit_task_namespaces(p);
21121da177e4SLinus Torvalds bad_fork_cleanup_mm:
2113c9f01245SDavid Rientjes 	if (p->mm)
21141da177e4SLinus Torvalds 		mmput(p->mm);
21151da177e4SLinus Torvalds bad_fork_cleanup_signal:
21164ab6c083SOleg Nesterov 	if (!(clone_flags & CLONE_THREAD))
21171c5354deSMike Galbraith 		free_signal_struct(p->signal);
21181da177e4SLinus Torvalds bad_fork_cleanup_sighand:
2119a7e5328aSOleg Nesterov 	__cleanup_sighand(p->sighand);
21201da177e4SLinus Torvalds bad_fork_cleanup_fs:
21211da177e4SLinus Torvalds 	exit_fs(p); /* blocking */
21221da177e4SLinus Torvalds bad_fork_cleanup_files:
21231da177e4SLinus Torvalds 	exit_files(p); /* blocking */
21241da177e4SLinus Torvalds bad_fork_cleanup_semundo:
21251da177e4SLinus Torvalds 	exit_sem(p);
2126e4e55b47STetsuo Handa bad_fork_cleanup_security:
2127e4e55b47STetsuo Handa 	security_task_free(p);
21281da177e4SLinus Torvalds bad_fork_cleanup_audit:
21291da177e4SLinus Torvalds 	audit_free(p);
21306c72e350SPeter Zijlstra bad_fork_cleanup_perf:
2131cdd6c482SIngo Molnar 	perf_event_free_task(p);
21326c72e350SPeter Zijlstra bad_fork_cleanup_policy:
2133b09be676SByungchul Park 	lockdep_free_task(p);
21341da177e4SLinus Torvalds #ifdef CONFIG_NUMA
2135f0be3d32SLee Schermerhorn 	mpol_put(p->mempolicy);
2136e8604cb4SLi Zefan bad_fork_cleanup_threadgroup_lock:
21371da177e4SLinus Torvalds #endif
213835df17c5SShailabh Nagar 	delayacct_tsk_free(p);
21391da177e4SLinus Torvalds bad_fork_cleanup_count:
2140d84f4f99SDavid Howells 	atomic_dec(&p->cred->user->processes);
2141e0e81739SDavid Howells 	exit_creds(p);
21421da177e4SLinus Torvalds bad_fork_free:
2143405c0759SAndy Lutomirski 	p->state = TASK_DEAD;
214468f24b08SAndy Lutomirski 	put_task_stack(p);
21451da177e4SLinus Torvalds 	free_task(p);
2146fe7d37d1SOleg Nesterov fork_out:
2147c3ad2c3bSEric W. Biederman 	spin_lock_irq(&current->sighand->siglock);
2148c3ad2c3bSEric W. Biederman 	hlist_del_init(&delayed.node);
2149c3ad2c3bSEric W. Biederman 	spin_unlock_irq(&current->sighand->siglock);
2150fe7d37d1SOleg Nesterov 	return ERR_PTR(retval);
21511da177e4SLinus Torvalds }
21521da177e4SLinus Torvalds 
21532c470475SEric W. Biederman static inline void init_idle_pids(struct task_struct *idle)
2154f106eee1SOleg Nesterov {
2155f106eee1SOleg Nesterov 	enum pid_type type;
2156f106eee1SOleg Nesterov 
2157f106eee1SOleg Nesterov 	for (type = PIDTYPE_PID; type < PIDTYPE_MAX; ++type) {
21582c470475SEric W. Biederman 		INIT_HLIST_NODE(&idle->pid_links[type]); /* not really needed */
21592c470475SEric W. Biederman 		init_task_pid(idle, type, &init_struct_pid);
2160f106eee1SOleg Nesterov 	}
2161f106eee1SOleg Nesterov }
2162f106eee1SOleg Nesterov 
21630db0628dSPaul Gortmaker struct task_struct *fork_idle(int cpu)
21641da177e4SLinus Torvalds {
216536c8b586SIngo Molnar 	struct task_struct *task;
2166725fc629SAndi Kleen 	task = copy_process(CLONE_VM, 0, 0, NULL, &init_struct_pid, 0, 0,
2167725fc629SAndi Kleen 			    cpu_to_node(cpu));
2168f106eee1SOleg Nesterov 	if (!IS_ERR(task)) {
21692c470475SEric W. Biederman 		init_idle_pids(task);
21701da177e4SLinus Torvalds 		init_idle(task, cpu);
2171f106eee1SOleg Nesterov 	}
217273b9ebfeSOleg Nesterov 
21731da177e4SLinus Torvalds 	return task;
21741da177e4SLinus Torvalds }
21751da177e4SLinus Torvalds 
21761da177e4SLinus Torvalds /*
21771da177e4SLinus Torvalds  *  Ok, this is the main fork-routine.
21781da177e4SLinus Torvalds  *
21791da177e4SLinus Torvalds  * It copies the process, and if successful kick-starts
21801da177e4SLinus Torvalds  * it and waits for it to finish using the VM if required.
21811da177e4SLinus Torvalds  */
21823033f14aSJosh Triplett long _do_fork(unsigned long clone_flags,
21831da177e4SLinus Torvalds 	      unsigned long stack_start,
21841da177e4SLinus Torvalds 	      unsigned long stack_size,
21851da177e4SLinus Torvalds 	      int __user *parent_tidptr,
21863033f14aSJosh Triplett 	      int __user *child_tidptr,
21873033f14aSJosh Triplett 	      unsigned long tls)
21881da177e4SLinus Torvalds {
21899f5325aaSMarcos Paulo de Souza 	struct completion vfork;
21909f5325aaSMarcos Paulo de Souza 	struct pid *pid;
21911da177e4SLinus Torvalds 	struct task_struct *p;
21921da177e4SLinus Torvalds 	int trace = 0;
219392476d7fSEric W. Biederman 	long nr;
21941da177e4SLinus Torvalds 
2195bdff746aSAndrew Morton 	/*
21964b9d33e6STejun Heo 	 * Determine whether and which event to report to ptracer.  When
21974b9d33e6STejun Heo 	 * called from kernel_thread or CLONE_UNTRACED is explicitly
21984b9d33e6STejun Heo 	 * requested, no event is reported; otherwise, report if the event
21994b9d33e6STejun Heo 	 * for the type of forking is enabled.
220009a05394SRoland McGrath 	 */
2201e80d6661SAl Viro 	if (!(clone_flags & CLONE_UNTRACED)) {
22024b9d33e6STejun Heo 		if (clone_flags & CLONE_VFORK)
22034b9d33e6STejun Heo 			trace = PTRACE_EVENT_VFORK;
22044b9d33e6STejun Heo 		else if ((clone_flags & CSIGNAL) != SIGCHLD)
22054b9d33e6STejun Heo 			trace = PTRACE_EVENT_CLONE;
22064b9d33e6STejun Heo 		else
22074b9d33e6STejun Heo 			trace = PTRACE_EVENT_FORK;
22084b9d33e6STejun Heo 
22094b9d33e6STejun Heo 		if (likely(!ptrace_event_enabled(current, trace)))
22104b9d33e6STejun Heo 			trace = 0;
22114b9d33e6STejun Heo 	}
22121da177e4SLinus Torvalds 
221362e791c1SAl Viro 	p = copy_process(clone_flags, stack_start, stack_size,
2214725fc629SAndi Kleen 			 child_tidptr, NULL, trace, tls, NUMA_NO_NODE);
221538addce8SEmese Revfy 	add_latent_entropy();
22169f5325aaSMarcos Paulo de Souza 
22179f5325aaSMarcos Paulo de Souza 	if (IS_ERR(p))
22189f5325aaSMarcos Paulo de Souza 		return PTR_ERR(p);
22199f5325aaSMarcos Paulo de Souza 
22201da177e4SLinus Torvalds 	/*
22211da177e4SLinus Torvalds 	 * Do this prior waking up the new thread - the thread pointer
22221da177e4SLinus Torvalds 	 * might get invalid after that point, if the thread exits quickly.
22231da177e4SLinus Torvalds 	 */
22240a16b607SMathieu Desnoyers 	trace_sched_process_fork(current, p);
22250a16b607SMathieu Desnoyers 
22264e52365fSMatthew Dempsky 	pid = get_task_pid(p, PIDTYPE_PID);
22274e52365fSMatthew Dempsky 	nr = pid_vnr(pid);
222830e49c26SPavel Emelyanov 
222930e49c26SPavel Emelyanov 	if (clone_flags & CLONE_PARENT_SETTID)
223030e49c26SPavel Emelyanov 		put_user(nr, parent_tidptr);
2231a6f5e063SSukadev Bhattiprolu 
22321da177e4SLinus Torvalds 	if (clone_flags & CLONE_VFORK) {
22331da177e4SLinus Torvalds 		p->vfork_done = &vfork;
22341da177e4SLinus Torvalds 		init_completion(&vfork);
2235d68b46feSOleg Nesterov 		get_task_struct(p);
22361da177e4SLinus Torvalds 	}
22371da177e4SLinus Torvalds 
22383e51e3edSSamir Bellabes 	wake_up_new_task(p);
22391da177e4SLinus Torvalds 
22404b9d33e6STejun Heo 	/* forking complete and child started to run, tell ptracer */
22414b9d33e6STejun Heo 	if (unlikely(trace))
22424e52365fSMatthew Dempsky 		ptrace_event_pid(trace, pid);
224309a05394SRoland McGrath 
22441da177e4SLinus Torvalds 	if (clone_flags & CLONE_VFORK) {
2245d68b46feSOleg Nesterov 		if (!wait_for_vfork_done(p, &vfork))
22464e52365fSMatthew Dempsky 			ptrace_event_pid(PTRACE_EVENT_VFORK_DONE, pid);
22479f59ce5dSChuck Ebbert 	}
22484e52365fSMatthew Dempsky 
22494e52365fSMatthew Dempsky 	put_pid(pid);
225092476d7fSEric W. Biederman 	return nr;
22511da177e4SLinus Torvalds }
22521da177e4SLinus Torvalds 
22533033f14aSJosh Triplett #ifndef CONFIG_HAVE_COPY_THREAD_TLS
22543033f14aSJosh Triplett /* For compatibility with architectures that call do_fork directly rather than
22553033f14aSJosh Triplett  * using the syscall entry points below. */
22563033f14aSJosh Triplett long do_fork(unsigned long clone_flags,
22573033f14aSJosh Triplett 	      unsigned long stack_start,
22583033f14aSJosh Triplett 	      unsigned long stack_size,
22593033f14aSJosh Triplett 	      int __user *parent_tidptr,
22603033f14aSJosh Triplett 	      int __user *child_tidptr)
22613033f14aSJosh Triplett {
22623033f14aSJosh Triplett 	return _do_fork(clone_flags, stack_start, stack_size,
22633033f14aSJosh Triplett 			parent_tidptr, child_tidptr, 0);
22643033f14aSJosh Triplett }
22653033f14aSJosh Triplett #endif
22663033f14aSJosh Triplett 
22672aa3a7f8SAl Viro /*
22682aa3a7f8SAl Viro  * Create a kernel thread.
22692aa3a7f8SAl Viro  */
22702aa3a7f8SAl Viro pid_t kernel_thread(int (*fn)(void *), void *arg, unsigned long flags)
22712aa3a7f8SAl Viro {
22723033f14aSJosh Triplett 	return _do_fork(flags|CLONE_VM|CLONE_UNTRACED, (unsigned long)fn,
22733033f14aSJosh Triplett 		(unsigned long)arg, NULL, NULL, 0);
22742aa3a7f8SAl Viro }
22752aa3a7f8SAl Viro 
2276d2125043SAl Viro #ifdef __ARCH_WANT_SYS_FORK
2277d2125043SAl Viro SYSCALL_DEFINE0(fork)
2278d2125043SAl Viro {
2279d2125043SAl Viro #ifdef CONFIG_MMU
22803033f14aSJosh Triplett 	return _do_fork(SIGCHLD, 0, 0, NULL, NULL, 0);
2281d2125043SAl Viro #else
2282d2125043SAl Viro 	/* can not support in nommu mode */
22835d59e182SDaeseok Youn 	return -EINVAL;
2284d2125043SAl Viro #endif
2285d2125043SAl Viro }
2286d2125043SAl Viro #endif
2287d2125043SAl Viro 
2288d2125043SAl Viro #ifdef __ARCH_WANT_SYS_VFORK
2289d2125043SAl Viro SYSCALL_DEFINE0(vfork)
2290d2125043SAl Viro {
22913033f14aSJosh Triplett 	return _do_fork(CLONE_VFORK | CLONE_VM | SIGCHLD, 0,
22923033f14aSJosh Triplett 			0, NULL, NULL, 0);
2293d2125043SAl Viro }
2294d2125043SAl Viro #endif
2295d2125043SAl Viro 
2296d2125043SAl Viro #ifdef __ARCH_WANT_SYS_CLONE
2297d2125043SAl Viro #ifdef CONFIG_CLONE_BACKWARDS
2298d2125043SAl Viro SYSCALL_DEFINE5(clone, unsigned long, clone_flags, unsigned long, newsp,
2299d2125043SAl Viro 		 int __user *, parent_tidptr,
23003033f14aSJosh Triplett 		 unsigned long, tls,
2301d2125043SAl Viro 		 int __user *, child_tidptr)
2302d2125043SAl Viro #elif defined(CONFIG_CLONE_BACKWARDS2)
2303d2125043SAl Viro SYSCALL_DEFINE5(clone, unsigned long, newsp, unsigned long, clone_flags,
2304d2125043SAl Viro 		 int __user *, parent_tidptr,
2305d2125043SAl Viro 		 int __user *, child_tidptr,
23063033f14aSJosh Triplett 		 unsigned long, tls)
2307dfa9771aSMichal Simek #elif defined(CONFIG_CLONE_BACKWARDS3)
2308dfa9771aSMichal Simek SYSCALL_DEFINE6(clone, unsigned long, clone_flags, unsigned long, newsp,
2309dfa9771aSMichal Simek 		int, stack_size,
2310dfa9771aSMichal Simek 		int __user *, parent_tidptr,
2311dfa9771aSMichal Simek 		int __user *, child_tidptr,
23123033f14aSJosh Triplett 		unsigned long, tls)
2313d2125043SAl Viro #else
2314d2125043SAl Viro SYSCALL_DEFINE5(clone, unsigned long, clone_flags, unsigned long, newsp,
2315d2125043SAl Viro 		 int __user *, parent_tidptr,
2316d2125043SAl Viro 		 int __user *, child_tidptr,
23173033f14aSJosh Triplett 		 unsigned long, tls)
2318d2125043SAl Viro #endif
2319d2125043SAl Viro {
23203033f14aSJosh Triplett 	return _do_fork(clone_flags, newsp, 0, parent_tidptr, child_tidptr, tls);
2321d2125043SAl Viro }
2322d2125043SAl Viro #endif
2323d2125043SAl Viro 
23240f1b92cbSOleg Nesterov void walk_process_tree(struct task_struct *top, proc_visitor visitor, void *data)
23250f1b92cbSOleg Nesterov {
23260f1b92cbSOleg Nesterov 	struct task_struct *leader, *parent, *child;
23270f1b92cbSOleg Nesterov 	int res;
23280f1b92cbSOleg Nesterov 
23290f1b92cbSOleg Nesterov 	read_lock(&tasklist_lock);
23300f1b92cbSOleg Nesterov 	leader = top = top->group_leader;
23310f1b92cbSOleg Nesterov down:
23320f1b92cbSOleg Nesterov 	for_each_thread(leader, parent) {
23330f1b92cbSOleg Nesterov 		list_for_each_entry(child, &parent->children, sibling) {
23340f1b92cbSOleg Nesterov 			res = visitor(child, data);
23350f1b92cbSOleg Nesterov 			if (res) {
23360f1b92cbSOleg Nesterov 				if (res < 0)
23370f1b92cbSOleg Nesterov 					goto out;
23380f1b92cbSOleg Nesterov 				leader = child;
23390f1b92cbSOleg Nesterov 				goto down;
23400f1b92cbSOleg Nesterov 			}
23410f1b92cbSOleg Nesterov up:
23420f1b92cbSOleg Nesterov 			;
23430f1b92cbSOleg Nesterov 		}
23440f1b92cbSOleg Nesterov 	}
23450f1b92cbSOleg Nesterov 
23460f1b92cbSOleg Nesterov 	if (leader != top) {
23470f1b92cbSOleg Nesterov 		child = leader;
23480f1b92cbSOleg Nesterov 		parent = child->real_parent;
23490f1b92cbSOleg Nesterov 		leader = parent->group_leader;
23500f1b92cbSOleg Nesterov 		goto up;
23510f1b92cbSOleg Nesterov 	}
23520f1b92cbSOleg Nesterov out:
23530f1b92cbSOleg Nesterov 	read_unlock(&tasklist_lock);
23540f1b92cbSOleg Nesterov }
23550f1b92cbSOleg Nesterov 
23565fd63b30SRavikiran G Thirumalai #ifndef ARCH_MIN_MMSTRUCT_ALIGN
23575fd63b30SRavikiran G Thirumalai #define ARCH_MIN_MMSTRUCT_ALIGN 0
23585fd63b30SRavikiran G Thirumalai #endif
23595fd63b30SRavikiran G Thirumalai 
236051cc5068SAlexey Dobriyan static void sighand_ctor(void *data)
2361aa1757f9SOleg Nesterov {
2362aa1757f9SOleg Nesterov 	struct sighand_struct *sighand = data;
2363aa1757f9SOleg Nesterov 
2364aa1757f9SOleg Nesterov 	spin_lock_init(&sighand->siglock);
2365b8fceee1SDavide Libenzi 	init_waitqueue_head(&sighand->signalfd_wqh);
2366fba2afaaSDavide Libenzi }
2367aa1757f9SOleg Nesterov 
23681da177e4SLinus Torvalds void __init proc_caches_init(void)
23691da177e4SLinus Torvalds {
2370c1a2f7f0SRik van Riel 	unsigned int mm_size;
2371c1a2f7f0SRik van Riel 
23721da177e4SLinus Torvalds 	sighand_cachep = kmem_cache_create("sighand_cache",
23731da177e4SLinus Torvalds 			sizeof(struct sighand_struct), 0,
23745f0d5a3aSPaul E. McKenney 			SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_TYPESAFE_BY_RCU|
237575f296d9SLevin, Alexander (Sasha Levin) 			SLAB_ACCOUNT, sighand_ctor);
23761da177e4SLinus Torvalds 	signal_cachep = kmem_cache_create("signal_cache",
23771da177e4SLinus Torvalds 			sizeof(struct signal_struct), 0,
237875f296d9SLevin, Alexander (Sasha Levin) 			SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_ACCOUNT,
23795d097056SVladimir Davydov 			NULL);
23801da177e4SLinus Torvalds 	files_cachep = kmem_cache_create("files_cache",
23811da177e4SLinus Torvalds 			sizeof(struct files_struct), 0,
238275f296d9SLevin, Alexander (Sasha Levin) 			SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_ACCOUNT,
23835d097056SVladimir Davydov 			NULL);
23841da177e4SLinus Torvalds 	fs_cachep = kmem_cache_create("fs_cache",
23851da177e4SLinus Torvalds 			sizeof(struct fs_struct), 0,
238675f296d9SLevin, Alexander (Sasha Levin) 			SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_ACCOUNT,
23875d097056SVladimir Davydov 			NULL);
2388c1a2f7f0SRik van Riel 
23896345d24dSLinus Torvalds 	/*
2390c1a2f7f0SRik van Riel 	 * The mm_cpumask is located at the end of mm_struct, and is
2391c1a2f7f0SRik van Riel 	 * dynamically sized based on the maximum CPU number this system
2392c1a2f7f0SRik van Riel 	 * can have, taking hotplug into account (nr_cpu_ids).
23936345d24dSLinus Torvalds 	 */
2394c1a2f7f0SRik van Riel 	mm_size = sizeof(struct mm_struct) + cpumask_size();
2395c1a2f7f0SRik van Riel 
239607dcd7feSDavid Windsor 	mm_cachep = kmem_cache_create_usercopy("mm_struct",
2397c1a2f7f0SRik van Riel 			mm_size, ARCH_MIN_MMSTRUCT_ALIGN,
239875f296d9SLevin, Alexander (Sasha Levin) 			SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_ACCOUNT,
239907dcd7feSDavid Windsor 			offsetof(struct mm_struct, saved_auxv),
240007dcd7feSDavid Windsor 			sizeof_field(struct mm_struct, saved_auxv),
24015d097056SVladimir Davydov 			NULL);
24025d097056SVladimir Davydov 	vm_area_cachep = KMEM_CACHE(vm_area_struct, SLAB_PANIC|SLAB_ACCOUNT);
24038feae131SDavid Howells 	mmap_init();
240466577193SAl Viro 	nsproxy_cache_init();
24051da177e4SLinus Torvalds }
2406cf2e340fSJANAK DESAI 
2407cf2e340fSJANAK DESAI /*
24089bfb23fcSOleg Nesterov  * Check constraints on flags passed to the unshare system call.
2409cf2e340fSJANAK DESAI  */
24109bfb23fcSOleg Nesterov static int check_unshare_flags(unsigned long unshare_flags)
2411cf2e340fSJANAK DESAI {
24129bfb23fcSOleg Nesterov 	if (unshare_flags & ~(CLONE_THREAD|CLONE_FS|CLONE_NEWNS|CLONE_SIGHAND|
24139bfb23fcSOleg Nesterov 				CLONE_VM|CLONE_FILES|CLONE_SYSVSEM|
241450804fe3SEric W. Biederman 				CLONE_NEWUTS|CLONE_NEWIPC|CLONE_NEWNET|
2415a79a908fSAditya Kali 				CLONE_NEWUSER|CLONE_NEWPID|CLONE_NEWCGROUP))
2416cf2e340fSJANAK DESAI 		return -EINVAL;
24179bfb23fcSOleg Nesterov 	/*
241812c641abSEric W. Biederman 	 * Not implemented, but pretend it works if there is nothing
241912c641abSEric W. Biederman 	 * to unshare.  Note that unsharing the address space or the
242012c641abSEric W. Biederman 	 * signal handlers also need to unshare the signal queues (aka
242112c641abSEric W. Biederman 	 * CLONE_THREAD).
24229bfb23fcSOleg Nesterov 	 */
24239bfb23fcSOleg Nesterov 	if (unshare_flags & (CLONE_THREAD | CLONE_SIGHAND | CLONE_VM)) {
242412c641abSEric W. Biederman 		if (!thread_group_empty(current))
242512c641abSEric W. Biederman 			return -EINVAL;
242612c641abSEric W. Biederman 	}
242712c641abSEric W. Biederman 	if (unshare_flags & (CLONE_SIGHAND | CLONE_VM)) {
242812c641abSEric W. Biederman 		if (atomic_read(&current->sighand->count) > 1)
242912c641abSEric W. Biederman 			return -EINVAL;
243012c641abSEric W. Biederman 	}
243112c641abSEric W. Biederman 	if (unshare_flags & CLONE_VM) {
243212c641abSEric W. Biederman 		if (!current_is_single_threaded())
24339bfb23fcSOleg Nesterov 			return -EINVAL;
24349bfb23fcSOleg Nesterov 	}
2435cf2e340fSJANAK DESAI 
2436cf2e340fSJANAK DESAI 	return 0;
2437cf2e340fSJANAK DESAI }
2438cf2e340fSJANAK DESAI 
2439cf2e340fSJANAK DESAI /*
244099d1419dSJANAK DESAI  * Unshare the filesystem structure if it is being shared
2441cf2e340fSJANAK DESAI  */
2442cf2e340fSJANAK DESAI static int unshare_fs(unsigned long unshare_flags, struct fs_struct **new_fsp)
2443cf2e340fSJANAK DESAI {
2444cf2e340fSJANAK DESAI 	struct fs_struct *fs = current->fs;
2445cf2e340fSJANAK DESAI 
2446498052bbSAl Viro 	if (!(unshare_flags & CLONE_FS) || !fs)
2447498052bbSAl Viro 		return 0;
2448498052bbSAl Viro 
2449498052bbSAl Viro 	/* don't need lock here; in the worst case we'll do useless copy */
2450498052bbSAl Viro 	if (fs->users == 1)
2451498052bbSAl Viro 		return 0;
2452498052bbSAl Viro 
2453498052bbSAl Viro 	*new_fsp = copy_fs_struct(fs);
245499d1419dSJANAK DESAI 	if (!*new_fsp)
245599d1419dSJANAK DESAI 		return -ENOMEM;
2456cf2e340fSJANAK DESAI 
2457cf2e340fSJANAK DESAI 	return 0;
2458cf2e340fSJANAK DESAI }
2459cf2e340fSJANAK DESAI 
2460cf2e340fSJANAK DESAI /*
2461a016f338SJANAK DESAI  * Unshare file descriptor table if it is being shared
2462cf2e340fSJANAK DESAI  */
2463cf2e340fSJANAK DESAI static int unshare_fd(unsigned long unshare_flags, struct files_struct **new_fdp)
2464cf2e340fSJANAK DESAI {
2465cf2e340fSJANAK DESAI 	struct files_struct *fd = current->files;
2466a016f338SJANAK DESAI 	int error = 0;
2467cf2e340fSJANAK DESAI 
2468cf2e340fSJANAK DESAI 	if ((unshare_flags & CLONE_FILES) &&
2469a016f338SJANAK DESAI 	    (fd && atomic_read(&fd->count) > 1)) {
2470a016f338SJANAK DESAI 		*new_fdp = dup_fd(fd, &error);
2471a016f338SJANAK DESAI 		if (!*new_fdp)
2472a016f338SJANAK DESAI 			return error;
2473a016f338SJANAK DESAI 	}
2474cf2e340fSJANAK DESAI 
2475cf2e340fSJANAK DESAI 	return 0;
2476cf2e340fSJANAK DESAI }
2477cf2e340fSJANAK DESAI 
2478cf2e340fSJANAK DESAI /*
2479cf2e340fSJANAK DESAI  * unshare allows a process to 'unshare' part of the process
2480cf2e340fSJANAK DESAI  * context which was originally shared using clone.  copy_*
2481cf2e340fSJANAK DESAI  * functions used by do_fork() cannot be used here directly
2482cf2e340fSJANAK DESAI  * because they modify an inactive task_struct that is being
2483cf2e340fSJANAK DESAI  * constructed. Here we are modifying the current, active,
2484cf2e340fSJANAK DESAI  * task_struct.
2485cf2e340fSJANAK DESAI  */
24869b32105eSDominik Brodowski int ksys_unshare(unsigned long unshare_flags)
2487cf2e340fSJANAK DESAI {
2488cf2e340fSJANAK DESAI 	struct fs_struct *fs, *new_fs = NULL;
2489cf2e340fSJANAK DESAI 	struct files_struct *fd, *new_fd = NULL;
2490b2e0d987SEric W. Biederman 	struct cred *new_cred = NULL;
2491cf7b708cSPavel Emelyanov 	struct nsproxy *new_nsproxy = NULL;
24929edff4abSManfred Spraul 	int do_sysvsem = 0;
24939bfb23fcSOleg Nesterov 	int err;
2494cf2e340fSJANAK DESAI 
249550804fe3SEric W. Biederman 	/*
2496faf00da5SEric W. Biederman 	 * If unsharing a user namespace must also unshare the thread group
2497faf00da5SEric W. Biederman 	 * and unshare the filesystem root and working directories.
2498b2e0d987SEric W. Biederman 	 */
2499b2e0d987SEric W. Biederman 	if (unshare_flags & CLONE_NEWUSER)
2500e66eded8SEric W. Biederman 		unshare_flags |= CLONE_THREAD | CLONE_FS;
2501b2e0d987SEric W. Biederman 	/*
250250804fe3SEric W. Biederman 	 * If unsharing vm, must also unshare signal handlers.
250350804fe3SEric W. Biederman 	 */
250450804fe3SEric W. Biederman 	if (unshare_flags & CLONE_VM)
250550804fe3SEric W. Biederman 		unshare_flags |= CLONE_SIGHAND;
25066013f67fSManfred Spraul 	/*
250712c641abSEric W. Biederman 	 * If unsharing a signal handlers, must also unshare the signal queues.
250812c641abSEric W. Biederman 	 */
250912c641abSEric W. Biederman 	if (unshare_flags & CLONE_SIGHAND)
251012c641abSEric W. Biederman 		unshare_flags |= CLONE_THREAD;
251112c641abSEric W. Biederman 	/*
25129bfb23fcSOleg Nesterov 	 * If unsharing namespace, must also unshare filesystem information.
25139bfb23fcSOleg Nesterov 	 */
25149bfb23fcSOleg Nesterov 	if (unshare_flags & CLONE_NEWNS)
25159bfb23fcSOleg Nesterov 		unshare_flags |= CLONE_FS;
251650804fe3SEric W. Biederman 
251750804fe3SEric W. Biederman 	err = check_unshare_flags(unshare_flags);
251850804fe3SEric W. Biederman 	if (err)
251950804fe3SEric W. Biederman 		goto bad_unshare_out;
25209bfb23fcSOleg Nesterov 	/*
25216013f67fSManfred Spraul 	 * CLONE_NEWIPC must also detach from the undolist: after switching
25226013f67fSManfred Spraul 	 * to a new ipc namespace, the semaphore arrays from the old
25236013f67fSManfred Spraul 	 * namespace are unreachable.
25246013f67fSManfred Spraul 	 */
25256013f67fSManfred Spraul 	if (unshare_flags & (CLONE_NEWIPC|CLONE_SYSVSEM))
25269edff4abSManfred Spraul 		do_sysvsem = 1;
2527fb0a685cSDaniel Rebelo de Oliveira 	err = unshare_fs(unshare_flags, &new_fs);
2528fb0a685cSDaniel Rebelo de Oliveira 	if (err)
25299bfb23fcSOleg Nesterov 		goto bad_unshare_out;
2530fb0a685cSDaniel Rebelo de Oliveira 	err = unshare_fd(unshare_flags, &new_fd);
2531fb0a685cSDaniel Rebelo de Oliveira 	if (err)
25329bfb23fcSOleg Nesterov 		goto bad_unshare_cleanup_fs;
2533b2e0d987SEric W. Biederman 	err = unshare_userns(unshare_flags, &new_cred);
2534fb0a685cSDaniel Rebelo de Oliveira 	if (err)
25359edff4abSManfred Spraul 		goto bad_unshare_cleanup_fd;
2536b2e0d987SEric W. Biederman 	err = unshare_nsproxy_namespaces(unshare_flags, &new_nsproxy,
2537b2e0d987SEric W. Biederman 					 new_cred, new_fs);
2538b2e0d987SEric W. Biederman 	if (err)
2539b2e0d987SEric W. Biederman 		goto bad_unshare_cleanup_cred;
2540cf2e340fSJANAK DESAI 
2541b2e0d987SEric W. Biederman 	if (new_fs || new_fd || do_sysvsem || new_cred || new_nsproxy) {
25429edff4abSManfred Spraul 		if (do_sysvsem) {
25439edff4abSManfred Spraul 			/*
25449edff4abSManfred Spraul 			 * CLONE_SYSVSEM is equivalent to sys_exit().
25459edff4abSManfred Spraul 			 */
25469edff4abSManfred Spraul 			exit_sem(current);
25479edff4abSManfred Spraul 		}
2548ab602f79SJack Miller 		if (unshare_flags & CLONE_NEWIPC) {
2549ab602f79SJack Miller 			/* Orphan segments in old ns (see sem above). */
2550ab602f79SJack Miller 			exit_shm(current);
2551ab602f79SJack Miller 			shm_init_task(current);
2552ab602f79SJack Miller 		}
2553ab516013SSerge E. Hallyn 
25546f977e6bSAlan Cox 		if (new_nsproxy)
2555cf7b708cSPavel Emelyanov 			switch_task_namespaces(current, new_nsproxy);
2556cf2e340fSJANAK DESAI 
2557cf7b708cSPavel Emelyanov 		task_lock(current);
2558cf7b708cSPavel Emelyanov 
2559cf2e340fSJANAK DESAI 		if (new_fs) {
2560cf2e340fSJANAK DESAI 			fs = current->fs;
25612a4419b5SNick Piggin 			spin_lock(&fs->lock);
2562cf2e340fSJANAK DESAI 			current->fs = new_fs;
2563498052bbSAl Viro 			if (--fs->users)
2564498052bbSAl Viro 				new_fs = NULL;
2565498052bbSAl Viro 			else
2566cf2e340fSJANAK DESAI 				new_fs = fs;
25672a4419b5SNick Piggin 			spin_unlock(&fs->lock);
2568cf2e340fSJANAK DESAI 		}
2569cf2e340fSJANAK DESAI 
2570cf2e340fSJANAK DESAI 		if (new_fd) {
2571cf2e340fSJANAK DESAI 			fd = current->files;
2572cf2e340fSJANAK DESAI 			current->files = new_fd;
2573cf2e340fSJANAK DESAI 			new_fd = fd;
2574cf2e340fSJANAK DESAI 		}
2575cf2e340fSJANAK DESAI 
2576cf2e340fSJANAK DESAI 		task_unlock(current);
2577b2e0d987SEric W. Biederman 
2578b2e0d987SEric W. Biederman 		if (new_cred) {
2579b2e0d987SEric W. Biederman 			/* Install the new user namespace */
2580b2e0d987SEric W. Biederman 			commit_creds(new_cred);
2581b2e0d987SEric W. Biederman 			new_cred = NULL;
2582b2e0d987SEric W. Biederman 		}
2583cf2e340fSJANAK DESAI 	}
2584cf2e340fSJANAK DESAI 
2585e4222673SHari Bathini 	perf_event_namespaces(current);
2586e4222673SHari Bathini 
2587b2e0d987SEric W. Biederman bad_unshare_cleanup_cred:
2588b2e0d987SEric W. Biederman 	if (new_cred)
2589b2e0d987SEric W. Biederman 		put_cred(new_cred);
2590cf2e340fSJANAK DESAI bad_unshare_cleanup_fd:
2591cf2e340fSJANAK DESAI 	if (new_fd)
2592cf2e340fSJANAK DESAI 		put_files_struct(new_fd);
2593cf2e340fSJANAK DESAI 
2594cf2e340fSJANAK DESAI bad_unshare_cleanup_fs:
2595cf2e340fSJANAK DESAI 	if (new_fs)
2596498052bbSAl Viro 		free_fs_struct(new_fs);
2597cf2e340fSJANAK DESAI 
2598cf2e340fSJANAK DESAI bad_unshare_out:
2599cf2e340fSJANAK DESAI 	return err;
2600cf2e340fSJANAK DESAI }
26013b125388SAl Viro 
26029b32105eSDominik Brodowski SYSCALL_DEFINE1(unshare, unsigned long, unshare_flags)
26039b32105eSDominik Brodowski {
26049b32105eSDominik Brodowski 	return ksys_unshare(unshare_flags);
26059b32105eSDominik Brodowski }
26069b32105eSDominik Brodowski 
26073b125388SAl Viro /*
26083b125388SAl Viro  *	Helper to unshare the files of the current task.
26093b125388SAl Viro  *	We don't want to expose copy_files internals to
26103b125388SAl Viro  *	the exec layer of the kernel.
26113b125388SAl Viro  */
26123b125388SAl Viro 
26133b125388SAl Viro int unshare_files(struct files_struct **displaced)
26143b125388SAl Viro {
26153b125388SAl Viro 	struct task_struct *task = current;
261650704516SAl Viro 	struct files_struct *copy = NULL;
26173b125388SAl Viro 	int error;
26183b125388SAl Viro 
26193b125388SAl Viro 	error = unshare_fd(CLONE_FILES, &copy);
26203b125388SAl Viro 	if (error || !copy) {
26213b125388SAl Viro 		*displaced = NULL;
26223b125388SAl Viro 		return error;
26233b125388SAl Viro 	}
26243b125388SAl Viro 	*displaced = task->files;
26253b125388SAl Viro 	task_lock(task);
26263b125388SAl Viro 	task->files = copy;
26273b125388SAl Viro 	task_unlock(task);
26283b125388SAl Viro 	return 0;
26293b125388SAl Viro }
263016db3d3fSHeinrich Schuchardt 
263116db3d3fSHeinrich Schuchardt int sysctl_max_threads(struct ctl_table *table, int write,
263216db3d3fSHeinrich Schuchardt 		       void __user *buffer, size_t *lenp, loff_t *ppos)
263316db3d3fSHeinrich Schuchardt {
263416db3d3fSHeinrich Schuchardt 	struct ctl_table t;
263516db3d3fSHeinrich Schuchardt 	int ret;
263616db3d3fSHeinrich Schuchardt 	int threads = max_threads;
263716db3d3fSHeinrich Schuchardt 	int min = MIN_THREADS;
263816db3d3fSHeinrich Schuchardt 	int max = MAX_THREADS;
263916db3d3fSHeinrich Schuchardt 
264016db3d3fSHeinrich Schuchardt 	t = *table;
264116db3d3fSHeinrich Schuchardt 	t.data = &threads;
264216db3d3fSHeinrich Schuchardt 	t.extra1 = &min;
264316db3d3fSHeinrich Schuchardt 	t.extra2 = &max;
264416db3d3fSHeinrich Schuchardt 
264516db3d3fSHeinrich Schuchardt 	ret = proc_dointvec_minmax(&t, write, buffer, lenp, ppos);
264616db3d3fSHeinrich Schuchardt 	if (ret || !write)
264716db3d3fSHeinrich Schuchardt 		return ret;
264816db3d3fSHeinrich Schuchardt 
264916db3d3fSHeinrich Schuchardt 	set_max_threads(threads);
265016db3d3fSHeinrich Schuchardt 
265116db3d3fSHeinrich Schuchardt 	return 0;
265216db3d3fSHeinrich Schuchardt }
2653