xref: /openbmc/linux/kernel/fork.c (revision 16d51a590a8ce3befb1308e0e7ab77f3b661af33)
1457c8996SThomas Gleixner // SPDX-License-Identifier: GPL-2.0-only
21da177e4SLinus Torvalds /*
31da177e4SLinus Torvalds  *  linux/kernel/fork.c
41da177e4SLinus Torvalds  *
51da177e4SLinus Torvalds  *  Copyright (C) 1991, 1992  Linus Torvalds
61da177e4SLinus Torvalds  */
71da177e4SLinus Torvalds 
81da177e4SLinus Torvalds /*
91da177e4SLinus Torvalds  *  'fork.c' contains the help-routines for the 'fork' system call
101da177e4SLinus Torvalds  * (see also entry.S and others).
111da177e4SLinus Torvalds  * Fork is rather simple, once you get the hang of it, but the memory
121da177e4SLinus Torvalds  * management can be a bitch. See 'mm/memory.c': 'copy_page_range()'
131da177e4SLinus Torvalds  */
141da177e4SLinus Torvalds 
15b3e58382SChristian Brauner #include <linux/anon_inodes.h>
161da177e4SLinus Torvalds #include <linux/slab.h>
174eb5aaa3SIngo Molnar #include <linux/sched/autogroup.h>
186e84f315SIngo Molnar #include <linux/sched/mm.h>
19f7ccbae4SIngo Molnar #include <linux/sched/coredump.h>
208703e8a4SIngo Molnar #include <linux/sched/user.h>
216a3827d7SIngo Molnar #include <linux/sched/numa_balancing.h>
2203441a34SIngo Molnar #include <linux/sched/stat.h>
2329930025SIngo Molnar #include <linux/sched/task.h>
2468db0cf1SIngo Molnar #include <linux/sched/task_stack.h>
2532ef5517SIngo Molnar #include <linux/sched/cputime.h>
26b3e58382SChristian Brauner #include <linux/seq_file.h>
27037741a6SIngo Molnar #include <linux/rtmutex.h>
281da177e4SLinus Torvalds #include <linux/init.h>
291da177e4SLinus Torvalds #include <linux/unistd.h>
301da177e4SLinus Torvalds #include <linux/module.h>
311da177e4SLinus Torvalds #include <linux/vmalloc.h>
321da177e4SLinus Torvalds #include <linux/completion.h>
331da177e4SLinus Torvalds #include <linux/personality.h>
341da177e4SLinus Torvalds #include <linux/mempolicy.h>
351da177e4SLinus Torvalds #include <linux/sem.h>
361da177e4SLinus Torvalds #include <linux/file.h>
379f3acc31SAl Viro #include <linux/fdtable.h>
38da9cbc87SJens Axboe #include <linux/iocontext.h>
391da177e4SLinus Torvalds #include <linux/key.h>
401da177e4SLinus Torvalds #include <linux/binfmts.h>
411da177e4SLinus Torvalds #include <linux/mman.h>
42cddb8a5cSAndrea Arcangeli #include <linux/mmu_notifier.h>
43133ff0eaSJérôme Glisse #include <linux/hmm.h>
441da177e4SLinus Torvalds #include <linux/fs.h>
45615d6e87SDavidlohr Bueso #include <linux/mm.h>
46615d6e87SDavidlohr Bueso #include <linux/vmacache.h>
47ab516013SSerge E. Hallyn #include <linux/nsproxy.h>
48c59ede7bSRandy.Dunlap #include <linux/capability.h>
491da177e4SLinus Torvalds #include <linux/cpu.h>
50b4f48b63SPaul Menage #include <linux/cgroup.h>
511da177e4SLinus Torvalds #include <linux/security.h>
52a1e78772SMel Gorman #include <linux/hugetlb.h>
53e2cfabdfSWill Drewry #include <linux/seccomp.h>
541da177e4SLinus Torvalds #include <linux/swap.h>
551da177e4SLinus Torvalds #include <linux/syscalls.h>
561da177e4SLinus Torvalds #include <linux/jiffies.h>
571da177e4SLinus Torvalds #include <linux/futex.h>
588141c7f3SLinus Torvalds #include <linux/compat.h>
59207205a2SEric Dumazet #include <linux/kthread.h>
607c3ab738SAndrew Morton #include <linux/task_io_accounting_ops.h>
61ab2af1f5SDipankar Sarma #include <linux/rcupdate.h>
621da177e4SLinus Torvalds #include <linux/ptrace.h>
631da177e4SLinus Torvalds #include <linux/mount.h>
641da177e4SLinus Torvalds #include <linux/audit.h>
6578fb7466SPavel Emelianov #include <linux/memcontrol.h>
66f201ae23SFrederic Weisbecker #include <linux/ftrace.h>
675e2bf014SMike Galbraith #include <linux/proc_fs.h>
681da177e4SLinus Torvalds #include <linux/profile.h>
691da177e4SLinus Torvalds #include <linux/rmap.h>
70f8af4da3SHugh Dickins #include <linux/ksm.h>
711da177e4SLinus Torvalds #include <linux/acct.h>
72893e26e6SPavel Emelyanov #include <linux/userfaultfd_k.h>
738f0ab514SJay Lan #include <linux/tsacct_kern.h>
749f46080cSMatt Helsley #include <linux/cn_proc.h>
75ba96a0c8SRafael J. Wysocki #include <linux/freezer.h>
76ca74e92bSShailabh Nagar #include <linux/delayacct.h>
77ad4ecbcbSShailabh Nagar #include <linux/taskstats_kern.h>
780a425405SArjan van de Ven #include <linux/random.h>
79522ed776SMiloslav Trmac #include <linux/tty.h>
80fd0928dfSJens Axboe #include <linux/blkdev.h>
815ad4e53bSAl Viro #include <linux/fs_struct.h>
827c9f8861SEric Sandeen #include <linux/magic.h>
83cdd6c482SIngo Molnar #include <linux/perf_event.h>
8442c4ab41SStanislaw Gruszka #include <linux/posix-timers.h>
858e7cac79SAvi Kivity #include <linux/user-return-notifier.h>
863d5992d2SYing Han #include <linux/oom.h>
87ba76149fSAndrea Arcangeli #include <linux/khugepaged.h>
88d80e731eSOleg Nesterov #include <linux/signalfd.h>
890326f5a9SSrikar Dronamraju #include <linux/uprobes.h>
90a27bb332SKent Overstreet #include <linux/aio.h>
9152f5684cSGideon Israel Dsouza #include <linux/compiler.h>
9216db3d3fSHeinrich Schuchardt #include <linux/sysctl.h>
935c9a8750SDmitry Vyukov #include <linux/kcov.h>
94d83a7cb3SJosh Poimboeuf #include <linux/livepatch.h>
9548ac3c18SMark Rutland #include <linux/thread_info.h>
96afaef01cSAlexander Popov #include <linux/stackleak.h>
971da177e4SLinus Torvalds 
981da177e4SLinus Torvalds #include <asm/pgtable.h>
991da177e4SLinus Torvalds #include <asm/pgalloc.h>
1007c0f6ba6SLinus Torvalds #include <linux/uaccess.h>
1011da177e4SLinus Torvalds #include <asm/mmu_context.h>
1021da177e4SLinus Torvalds #include <asm/cacheflush.h>
1031da177e4SLinus Torvalds #include <asm/tlbflush.h>
1041da177e4SLinus Torvalds 
105ad8d75ffSSteven Rostedt #include <trace/events/sched.h>
106ad8d75ffSSteven Rostedt 
10743d2b113SKAMEZAWA Hiroyuki #define CREATE_TRACE_POINTS
10843d2b113SKAMEZAWA Hiroyuki #include <trace/events/task.h>
10943d2b113SKAMEZAWA Hiroyuki 
1101da177e4SLinus Torvalds /*
111ac1b398dSHeinrich Schuchardt  * Minimum number of threads to boot the kernel
112ac1b398dSHeinrich Schuchardt  */
113ac1b398dSHeinrich Schuchardt #define MIN_THREADS 20
114ac1b398dSHeinrich Schuchardt 
115ac1b398dSHeinrich Schuchardt /*
116ac1b398dSHeinrich Schuchardt  * Maximum number of threads
117ac1b398dSHeinrich Schuchardt  */
118ac1b398dSHeinrich Schuchardt #define MAX_THREADS FUTEX_TID_MASK
119ac1b398dSHeinrich Schuchardt 
120ac1b398dSHeinrich Schuchardt /*
1211da177e4SLinus Torvalds  * Protected counters by write_lock_irq(&tasklist_lock)
1221da177e4SLinus Torvalds  */
1231da177e4SLinus Torvalds unsigned long total_forks;	/* Handle normal Linux uptimes. */
1241da177e4SLinus Torvalds int nr_threads;			/* The idle threads do not count.. */
1251da177e4SLinus Torvalds 
1268856ae4dSKefeng Wang static int max_threads;		/* tunable limit on nr_threads */
1271da177e4SLinus Torvalds 
1281da177e4SLinus Torvalds DEFINE_PER_CPU(unsigned long, process_counts) = 0;
1291da177e4SLinus Torvalds 
1301da177e4SLinus Torvalds __cacheline_aligned DEFINE_RWLOCK(tasklist_lock);  /* outer */
131db1466b3SPaul E. McKenney 
132db1466b3SPaul E. McKenney #ifdef CONFIG_PROVE_RCU
133db1466b3SPaul E. McKenney int lockdep_tasklist_lock_is_held(void)
134db1466b3SPaul E. McKenney {
135db1466b3SPaul E. McKenney 	return lockdep_is_held(&tasklist_lock);
136db1466b3SPaul E. McKenney }
137db1466b3SPaul E. McKenney EXPORT_SYMBOL_GPL(lockdep_tasklist_lock_is_held);
138db1466b3SPaul E. McKenney #endif /* #ifdef CONFIG_PROVE_RCU */
1391da177e4SLinus Torvalds 
1401da177e4SLinus Torvalds int nr_processes(void)
1411da177e4SLinus Torvalds {
1421da177e4SLinus Torvalds 	int cpu;
1431da177e4SLinus Torvalds 	int total = 0;
1441da177e4SLinus Torvalds 
1451d510750SIan Campbell 	for_each_possible_cpu(cpu)
1461da177e4SLinus Torvalds 		total += per_cpu(process_counts, cpu);
1471da177e4SLinus Torvalds 
1481da177e4SLinus Torvalds 	return total;
1491da177e4SLinus Torvalds }
1501da177e4SLinus Torvalds 
151f19b9f74SAkinobu Mita void __weak arch_release_task_struct(struct task_struct *tsk)
152f19b9f74SAkinobu Mita {
153f19b9f74SAkinobu Mita }
154f19b9f74SAkinobu Mita 
155f5e10287SThomas Gleixner #ifndef CONFIG_ARCH_TASK_STRUCT_ALLOCATOR
156e18b890bSChristoph Lameter static struct kmem_cache *task_struct_cachep;
15741101809SThomas Gleixner 
15841101809SThomas Gleixner static inline struct task_struct *alloc_task_struct_node(int node)
15941101809SThomas Gleixner {
16041101809SThomas Gleixner 	return kmem_cache_alloc_node(task_struct_cachep, GFP_KERNEL, node);
16141101809SThomas Gleixner }
16241101809SThomas Gleixner 
16341101809SThomas Gleixner static inline void free_task_struct(struct task_struct *tsk)
16441101809SThomas Gleixner {
16541101809SThomas Gleixner 	kmem_cache_free(task_struct_cachep, tsk);
16641101809SThomas Gleixner }
1671da177e4SLinus Torvalds #endif
1681da177e4SLinus Torvalds 
169b235beeaSLinus Torvalds #ifndef CONFIG_ARCH_THREAD_STACK_ALLOCATOR
17041101809SThomas Gleixner 
1710d15d74aSThomas Gleixner /*
1720d15d74aSThomas Gleixner  * Allocate pages if THREAD_SIZE is >= PAGE_SIZE, otherwise use a
1730d15d74aSThomas Gleixner  * kmemcache based allocator.
1740d15d74aSThomas Gleixner  */
175ba14a194SAndy Lutomirski # if THREAD_SIZE >= PAGE_SIZE || defined(CONFIG_VMAP_STACK)
176ac496bf4SAndy Lutomirski 
177ac496bf4SAndy Lutomirski #ifdef CONFIG_VMAP_STACK
178ac496bf4SAndy Lutomirski /*
179ac496bf4SAndy Lutomirski  * vmalloc() is a bit slow, and calling vfree() enough times will force a TLB
180ac496bf4SAndy Lutomirski  * flush.  Try to minimize the number of calls by caching stacks.
181ac496bf4SAndy Lutomirski  */
182ac496bf4SAndy Lutomirski #define NR_CACHED_STACKS 2
183ac496bf4SAndy Lutomirski static DEFINE_PER_CPU(struct vm_struct *, cached_stacks[NR_CACHED_STACKS]);
18419659c59SHoeun Ryu 
18519659c59SHoeun Ryu static int free_vm_stack_cache(unsigned int cpu)
18619659c59SHoeun Ryu {
18719659c59SHoeun Ryu 	struct vm_struct **cached_vm_stacks = per_cpu_ptr(cached_stacks, cpu);
18819659c59SHoeun Ryu 	int i;
18919659c59SHoeun Ryu 
19019659c59SHoeun Ryu 	for (i = 0; i < NR_CACHED_STACKS; i++) {
19119659c59SHoeun Ryu 		struct vm_struct *vm_stack = cached_vm_stacks[i];
19219659c59SHoeun Ryu 
19319659c59SHoeun Ryu 		if (!vm_stack)
19419659c59SHoeun Ryu 			continue;
19519659c59SHoeun Ryu 
19619659c59SHoeun Ryu 		vfree(vm_stack->addr);
19719659c59SHoeun Ryu 		cached_vm_stacks[i] = NULL;
19819659c59SHoeun Ryu 	}
19919659c59SHoeun Ryu 
20019659c59SHoeun Ryu 	return 0;
20119659c59SHoeun Ryu }
202ac496bf4SAndy Lutomirski #endif
203ac496bf4SAndy Lutomirski 
204ba14a194SAndy Lutomirski static unsigned long *alloc_thread_stack_node(struct task_struct *tsk, int node)
205b69c49b7SFUJITA Tomonori {
206ba14a194SAndy Lutomirski #ifdef CONFIG_VMAP_STACK
207ac496bf4SAndy Lutomirski 	void *stack;
208ac496bf4SAndy Lutomirski 	int i;
209ac496bf4SAndy Lutomirski 
210ac496bf4SAndy Lutomirski 	for (i = 0; i < NR_CACHED_STACKS; i++) {
211112166f8SChristoph Lameter 		struct vm_struct *s;
212112166f8SChristoph Lameter 
213112166f8SChristoph Lameter 		s = this_cpu_xchg(cached_stacks[i], NULL);
214ac496bf4SAndy Lutomirski 
215ac496bf4SAndy Lutomirski 		if (!s)
216ac496bf4SAndy Lutomirski 			continue;
217ac496bf4SAndy Lutomirski 
218ca182551SKonstantin Khlebnikov 		/* Clear stale pointers from reused stack. */
219ca182551SKonstantin Khlebnikov 		memset(s->addr, 0, THREAD_SIZE);
220e01e8063SKees Cook 
221ac496bf4SAndy Lutomirski 		tsk->stack_vm_area = s;
222ba4a4574SShakeel Butt 		tsk->stack = s->addr;
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 	 */
2425eed6f1dSRik van Riel 	if (stack) {
243ba14a194SAndy Lutomirski 		tsk->stack_vm_area = find_vm_area(stack);
2445eed6f1dSRik van Riel 		tsk->stack = stack;
2455eed6f1dSRik van Riel 	}
246ba14a194SAndy Lutomirski 	return stack;
247ba14a194SAndy Lutomirski #else
2484949148aSVladimir Davydov 	struct page *page = alloc_pages_node(node, THREADINFO_GFP,
2492889f608SThomas Gleixner 					     THREAD_SIZE_ORDER);
250b6a84016SEric Dumazet 
2511bf4580eSAndrea Arcangeli 	if (likely(page)) {
2521bf4580eSAndrea Arcangeli 		tsk->stack = page_address(page);
2531bf4580eSAndrea Arcangeli 		return tsk->stack;
2541bf4580eSAndrea Arcangeli 	}
2551bf4580eSAndrea Arcangeli 	return NULL;
256ba14a194SAndy Lutomirski #endif
257b69c49b7SFUJITA Tomonori }
258b69c49b7SFUJITA Tomonori 
259ba14a194SAndy Lutomirski static inline void free_thread_stack(struct task_struct *tsk)
260b69c49b7SFUJITA Tomonori {
261ac496bf4SAndy Lutomirski #ifdef CONFIG_VMAP_STACK
2629b6f7e16SRoman Gushchin 	struct vm_struct *vm = task_stack_vm_area(tsk);
2639b6f7e16SRoman Gushchin 
2649b6f7e16SRoman Gushchin 	if (vm) {
265ac496bf4SAndy Lutomirski 		int i;
266ac496bf4SAndy Lutomirski 
2679b6f7e16SRoman Gushchin 		for (i = 0; i < THREAD_SIZE / PAGE_SIZE; i++) {
2689b6f7e16SRoman Gushchin 			mod_memcg_page_state(vm->pages[i],
2699b6f7e16SRoman Gushchin 					     MEMCG_KERNEL_STACK_KB,
2709b6f7e16SRoman Gushchin 					     -(int)(PAGE_SIZE / 1024));
2719b6f7e16SRoman Gushchin 
2729b6f7e16SRoman Gushchin 			memcg_kmem_uncharge(vm->pages[i], 0);
2739b6f7e16SRoman Gushchin 		}
2749b6f7e16SRoman Gushchin 
275ac496bf4SAndy Lutomirski 		for (i = 0; i < NR_CACHED_STACKS; i++) {
276112166f8SChristoph Lameter 			if (this_cpu_cmpxchg(cached_stacks[i],
277112166f8SChristoph Lameter 					NULL, tsk->stack_vm_area) != NULL)
278ac496bf4SAndy Lutomirski 				continue;
279ac496bf4SAndy Lutomirski 
280ac496bf4SAndy Lutomirski 			return;
281ac496bf4SAndy Lutomirski 		}
282ac496bf4SAndy Lutomirski 
2830f110a9bSAndrey Ryabinin 		vfree_atomic(tsk->stack);
284ac496bf4SAndy Lutomirski 		return;
285ac496bf4SAndy Lutomirski 	}
286ac496bf4SAndy Lutomirski #endif
287ac496bf4SAndy Lutomirski 
288ba14a194SAndy Lutomirski 	__free_pages(virt_to_page(tsk->stack), THREAD_SIZE_ORDER);
289b69c49b7SFUJITA Tomonori }
2900d15d74aSThomas Gleixner # else
291b235beeaSLinus Torvalds static struct kmem_cache *thread_stack_cache;
2920d15d74aSThomas Gleixner 
2939521d399SMichael Ellerman static unsigned long *alloc_thread_stack_node(struct task_struct *tsk,
2940d15d74aSThomas Gleixner 						  int node)
2950d15d74aSThomas Gleixner {
2965eed6f1dSRik van Riel 	unsigned long *stack;
2975eed6f1dSRik van Riel 	stack = kmem_cache_alloc_node(thread_stack_cache, THREADINFO_GFP, node);
2985eed6f1dSRik van Riel 	tsk->stack = stack;
2995eed6f1dSRik van Riel 	return stack;
3000d15d74aSThomas Gleixner }
3010d15d74aSThomas Gleixner 
302ba14a194SAndy Lutomirski static void free_thread_stack(struct task_struct *tsk)
3030d15d74aSThomas Gleixner {
304ba14a194SAndy Lutomirski 	kmem_cache_free(thread_stack_cache, tsk->stack);
3050d15d74aSThomas Gleixner }
3060d15d74aSThomas Gleixner 
307b235beeaSLinus Torvalds void thread_stack_cache_init(void)
3080d15d74aSThomas Gleixner {
309f9d29946SDavid Windsor 	thread_stack_cache = kmem_cache_create_usercopy("thread_stack",
310f9d29946SDavid Windsor 					THREAD_SIZE, THREAD_SIZE, 0, 0,
311f9d29946SDavid Windsor 					THREAD_SIZE, NULL);
312b235beeaSLinus Torvalds 	BUG_ON(thread_stack_cache == NULL);
3130d15d74aSThomas Gleixner }
3140d15d74aSThomas Gleixner # endif
315b69c49b7SFUJITA Tomonori #endif
316b69c49b7SFUJITA Tomonori 
3171da177e4SLinus Torvalds /* SLAB cache for signal_struct structures (tsk->signal) */
318e18b890bSChristoph Lameter static struct kmem_cache *signal_cachep;
3191da177e4SLinus Torvalds 
3201da177e4SLinus Torvalds /* SLAB cache for sighand_struct structures (tsk->sighand) */
321e18b890bSChristoph Lameter struct kmem_cache *sighand_cachep;
3221da177e4SLinus Torvalds 
3231da177e4SLinus Torvalds /* SLAB cache for files_struct structures (tsk->files) */
324e18b890bSChristoph Lameter struct kmem_cache *files_cachep;
3251da177e4SLinus Torvalds 
3261da177e4SLinus Torvalds /* SLAB cache for fs_struct structures (tsk->fs) */
327e18b890bSChristoph Lameter struct kmem_cache *fs_cachep;
3281da177e4SLinus Torvalds 
3291da177e4SLinus Torvalds /* SLAB cache for vm_area_struct structures */
3303928d4f5SLinus Torvalds static struct kmem_cache *vm_area_cachep;
3311da177e4SLinus Torvalds 
3321da177e4SLinus Torvalds /* SLAB cache for mm_struct structures (tsk->mm) */
333e18b890bSChristoph Lameter static struct kmem_cache *mm_cachep;
3341da177e4SLinus Torvalds 
335490fc053SLinus Torvalds struct vm_area_struct *vm_area_alloc(struct mm_struct *mm)
3363928d4f5SLinus Torvalds {
337a670468fSAndrew Morton 	struct vm_area_struct *vma;
338490fc053SLinus Torvalds 
339a670468fSAndrew Morton 	vma = kmem_cache_alloc(vm_area_cachep, GFP_KERNEL);
340027232daSKirill A. Shutemov 	if (vma)
341027232daSKirill A. Shutemov 		vma_init(vma, mm);
342490fc053SLinus Torvalds 	return vma;
3433928d4f5SLinus Torvalds }
3443928d4f5SLinus Torvalds 
3453928d4f5SLinus Torvalds struct vm_area_struct *vm_area_dup(struct vm_area_struct *orig)
3463928d4f5SLinus Torvalds {
34795faf699SLinus Torvalds 	struct vm_area_struct *new = kmem_cache_alloc(vm_area_cachep, GFP_KERNEL);
34895faf699SLinus Torvalds 
34995faf699SLinus Torvalds 	if (new) {
35095faf699SLinus Torvalds 		*new = *orig;
35195faf699SLinus Torvalds 		INIT_LIST_HEAD(&new->anon_vma_chain);
35295faf699SLinus Torvalds 	}
35395faf699SLinus Torvalds 	return new;
3543928d4f5SLinus Torvalds }
3553928d4f5SLinus Torvalds 
3563928d4f5SLinus Torvalds void vm_area_free(struct vm_area_struct *vma)
3573928d4f5SLinus Torvalds {
3583928d4f5SLinus Torvalds 	kmem_cache_free(vm_area_cachep, vma);
3593928d4f5SLinus Torvalds }
3603928d4f5SLinus Torvalds 
361ba14a194SAndy Lutomirski static void account_kernel_stack(struct task_struct *tsk, int account)
362c6a7f572SKOSAKI Motohiro {
363ba14a194SAndy Lutomirski 	void *stack = task_stack_page(tsk);
364ba14a194SAndy Lutomirski 	struct vm_struct *vm = task_stack_vm_area(tsk);
365ba14a194SAndy Lutomirski 
366ba14a194SAndy Lutomirski 	BUILD_BUG_ON(IS_ENABLED(CONFIG_VMAP_STACK) && PAGE_SIZE % 1024 != 0);
367ba14a194SAndy Lutomirski 
368ba14a194SAndy Lutomirski 	if (vm) {
369ba14a194SAndy Lutomirski 		int i;
370ba14a194SAndy Lutomirski 
371ba14a194SAndy Lutomirski 		BUG_ON(vm->nr_pages != THREAD_SIZE / PAGE_SIZE);
372ba14a194SAndy Lutomirski 
373ba14a194SAndy Lutomirski 		for (i = 0; i < THREAD_SIZE / PAGE_SIZE; i++) {
374ba14a194SAndy Lutomirski 			mod_zone_page_state(page_zone(vm->pages[i]),
375ba14a194SAndy Lutomirski 					    NR_KERNEL_STACK_KB,
376ba14a194SAndy Lutomirski 					    PAGE_SIZE / 1024 * account);
377ba14a194SAndy Lutomirski 		}
378ba14a194SAndy Lutomirski 	} else {
379ba14a194SAndy Lutomirski 		/*
380ba14a194SAndy Lutomirski 		 * All stack pages are in the same zone and belong to the
381ba14a194SAndy Lutomirski 		 * same memcg.
382ba14a194SAndy Lutomirski 		 */
383efdc9490SAndy Lutomirski 		struct page *first_page = virt_to_page(stack);
384c6a7f572SKOSAKI Motohiro 
385efdc9490SAndy Lutomirski 		mod_zone_page_state(page_zone(first_page), NR_KERNEL_STACK_KB,
386d30dd8beSAndy Lutomirski 				    THREAD_SIZE / 1024 * account);
387efdc9490SAndy Lutomirski 
388ed52be7bSJohannes Weiner 		mod_memcg_page_state(first_page, MEMCG_KERNEL_STACK_KB,
389efdc9490SAndy Lutomirski 				     account * (THREAD_SIZE / 1024));
390c6a7f572SKOSAKI Motohiro 	}
391ba14a194SAndy Lutomirski }
392c6a7f572SKOSAKI Motohiro 
3939b6f7e16SRoman Gushchin static int memcg_charge_kernel_stack(struct task_struct *tsk)
3949b6f7e16SRoman Gushchin {
3959b6f7e16SRoman Gushchin #ifdef CONFIG_VMAP_STACK
3969b6f7e16SRoman Gushchin 	struct vm_struct *vm = task_stack_vm_area(tsk);
3979b6f7e16SRoman Gushchin 	int ret;
3989b6f7e16SRoman Gushchin 
3999b6f7e16SRoman Gushchin 	if (vm) {
4009b6f7e16SRoman Gushchin 		int i;
4019b6f7e16SRoman Gushchin 
4029b6f7e16SRoman Gushchin 		for (i = 0; i < THREAD_SIZE / PAGE_SIZE; i++) {
4039b6f7e16SRoman Gushchin 			/*
4049b6f7e16SRoman Gushchin 			 * If memcg_kmem_charge() fails, page->mem_cgroup
4059b6f7e16SRoman Gushchin 			 * pointer is NULL, and both memcg_kmem_uncharge()
4069b6f7e16SRoman Gushchin 			 * and mod_memcg_page_state() in free_thread_stack()
4079b6f7e16SRoman Gushchin 			 * will ignore this page. So it's safe.
4089b6f7e16SRoman Gushchin 			 */
4099b6f7e16SRoman Gushchin 			ret = memcg_kmem_charge(vm->pages[i], GFP_KERNEL, 0);
4109b6f7e16SRoman Gushchin 			if (ret)
4119b6f7e16SRoman Gushchin 				return ret;
4129b6f7e16SRoman Gushchin 
4139b6f7e16SRoman Gushchin 			mod_memcg_page_state(vm->pages[i],
4149b6f7e16SRoman Gushchin 					     MEMCG_KERNEL_STACK_KB,
4159b6f7e16SRoman Gushchin 					     PAGE_SIZE / 1024);
4169b6f7e16SRoman Gushchin 		}
4179b6f7e16SRoman Gushchin 	}
4189b6f7e16SRoman Gushchin #endif
4199b6f7e16SRoman Gushchin 	return 0;
4209b6f7e16SRoman Gushchin }
4219b6f7e16SRoman Gushchin 
42268f24b08SAndy Lutomirski static void release_task_stack(struct task_struct *tsk)
4231da177e4SLinus Torvalds {
424405c0759SAndy Lutomirski 	if (WARN_ON(tsk->state != TASK_DEAD))
425405c0759SAndy Lutomirski 		return;  /* Better to leak the stack than to free prematurely */
426405c0759SAndy Lutomirski 
427ba14a194SAndy Lutomirski 	account_kernel_stack(tsk, -1);
428ba14a194SAndy Lutomirski 	free_thread_stack(tsk);
42968f24b08SAndy Lutomirski 	tsk->stack = NULL;
43068f24b08SAndy Lutomirski #ifdef CONFIG_VMAP_STACK
43168f24b08SAndy Lutomirski 	tsk->stack_vm_area = NULL;
43268f24b08SAndy Lutomirski #endif
43368f24b08SAndy Lutomirski }
43468f24b08SAndy Lutomirski 
43568f24b08SAndy Lutomirski #ifdef CONFIG_THREAD_INFO_IN_TASK
43668f24b08SAndy Lutomirski void put_task_stack(struct task_struct *tsk)
43768f24b08SAndy Lutomirski {
438f0b89d39SElena Reshetova 	if (refcount_dec_and_test(&tsk->stack_refcount))
43968f24b08SAndy Lutomirski 		release_task_stack(tsk);
44068f24b08SAndy Lutomirski }
44168f24b08SAndy Lutomirski #endif
44268f24b08SAndy Lutomirski 
44368f24b08SAndy Lutomirski void free_task(struct task_struct *tsk)
44468f24b08SAndy Lutomirski {
44568f24b08SAndy Lutomirski #ifndef CONFIG_THREAD_INFO_IN_TASK
44668f24b08SAndy Lutomirski 	/*
44768f24b08SAndy Lutomirski 	 * The task is finally done with both the stack and thread_info,
44868f24b08SAndy Lutomirski 	 * so free both.
44968f24b08SAndy Lutomirski 	 */
45068f24b08SAndy Lutomirski 	release_task_stack(tsk);
45168f24b08SAndy Lutomirski #else
45268f24b08SAndy Lutomirski 	/*
45368f24b08SAndy Lutomirski 	 * If the task had a separate stack allocation, it should be gone
45468f24b08SAndy Lutomirski 	 * by now.
45568f24b08SAndy Lutomirski 	 */
456f0b89d39SElena Reshetova 	WARN_ON_ONCE(refcount_read(&tsk->stack_refcount) != 0);
45768f24b08SAndy Lutomirski #endif
45823f78d4aSIngo Molnar 	rt_mutex_debug_task_free(tsk);
459fb52607aSFrederic Weisbecker 	ftrace_graph_exit_task(tsk);
460e2cfabdfSWill Drewry 	put_seccomp_filter(tsk);
461f19b9f74SAkinobu Mita 	arch_release_task_struct(tsk);
4621da5c46fSOleg Nesterov 	if (tsk->flags & PF_KTHREAD)
4631da5c46fSOleg Nesterov 		free_kthread_struct(tsk);
4641da177e4SLinus Torvalds 	free_task_struct(tsk);
4651da177e4SLinus Torvalds }
4661da177e4SLinus Torvalds EXPORT_SYMBOL(free_task);
4671da177e4SLinus Torvalds 
4681da177e4SLinus Torvalds #ifdef CONFIG_MMU
4690766f788SEmese Revfy static __latent_entropy int dup_mmap(struct mm_struct *mm,
4700766f788SEmese Revfy 					struct mm_struct *oldmm)
4711da177e4SLinus Torvalds {
472297c5eeeSLinus Torvalds 	struct vm_area_struct *mpnt, *tmp, *prev, **pprev;
4731da177e4SLinus Torvalds 	struct rb_node **rb_link, *rb_parent;
4741da177e4SLinus Torvalds 	int retval;
4751da177e4SLinus Torvalds 	unsigned long charge;
476893e26e6SPavel Emelyanov 	LIST_HEAD(uf);
4771da177e4SLinus Torvalds 
47832cdba1eSOleg Nesterov 	uprobe_start_dup_mmap();
4797c051267SMichal Hocko 	if (down_write_killable(&oldmm->mmap_sem)) {
4807c051267SMichal Hocko 		retval = -EINTR;
4817c051267SMichal Hocko 		goto fail_uprobe_end;
4827c051267SMichal Hocko 	}
483ec8c0446SRalf Baechle 	flush_cache_dup_mm(oldmm);
484f8ac4ec9SOleg Nesterov 	uprobe_dup_mmap(oldmm, mm);
485ad339451SIngo Molnar 	/*
486ad339451SIngo Molnar 	 * Not linked in yet - no deadlock potential:
487ad339451SIngo Molnar 	 */
488ad339451SIngo Molnar 	down_write_nested(&mm->mmap_sem, SINGLE_DEPTH_NESTING);
4897ee78232SHugh Dickins 
49090f31d0eSKonstantin Khlebnikov 	/* No ordering required: file already has been exposed. */
49190f31d0eSKonstantin Khlebnikov 	RCU_INIT_POINTER(mm->exe_file, get_mm_exe_file(oldmm));
49290f31d0eSKonstantin Khlebnikov 
4934f7d4614SVladimir Davydov 	mm->total_vm = oldmm->total_vm;
49484638335SKonstantin Khlebnikov 	mm->data_vm = oldmm->data_vm;
4954f7d4614SVladimir Davydov 	mm->exec_vm = oldmm->exec_vm;
4964f7d4614SVladimir Davydov 	mm->stack_vm = oldmm->stack_vm;
4974f7d4614SVladimir Davydov 
4981da177e4SLinus Torvalds 	rb_link = &mm->mm_rb.rb_node;
4991da177e4SLinus Torvalds 	rb_parent = NULL;
5001da177e4SLinus Torvalds 	pprev = &mm->mmap;
501f8af4da3SHugh Dickins 	retval = ksm_fork(mm, oldmm);
502f8af4da3SHugh Dickins 	if (retval)
503f8af4da3SHugh Dickins 		goto out;
504ba76149fSAndrea Arcangeli 	retval = khugepaged_fork(mm, oldmm);
505ba76149fSAndrea Arcangeli 	if (retval)
506ba76149fSAndrea Arcangeli 		goto out;
5071da177e4SLinus Torvalds 
508297c5eeeSLinus Torvalds 	prev = NULL;
509fd3e42fcSHugh Dickins 	for (mpnt = oldmm->mmap; mpnt; mpnt = mpnt->vm_next) {
5101da177e4SLinus Torvalds 		struct file *file;
5111da177e4SLinus Torvalds 
5121da177e4SLinus Torvalds 		if (mpnt->vm_flags & VM_DONTCOPY) {
51384638335SKonstantin Khlebnikov 			vm_stat_account(mm, mpnt->vm_flags, -vma_pages(mpnt));
5141da177e4SLinus Torvalds 			continue;
5151da177e4SLinus Torvalds 		}
5161da177e4SLinus Torvalds 		charge = 0;
517655c79bbSTetsuo Handa 		/*
518655c79bbSTetsuo Handa 		 * Don't duplicate many vmas if we've been oom-killed (for
519655c79bbSTetsuo Handa 		 * example)
520655c79bbSTetsuo Handa 		 */
521655c79bbSTetsuo Handa 		if (fatal_signal_pending(current)) {
522655c79bbSTetsuo Handa 			retval = -EINTR;
523655c79bbSTetsuo Handa 			goto out;
524655c79bbSTetsuo Handa 		}
5251da177e4SLinus Torvalds 		if (mpnt->vm_flags & VM_ACCOUNT) {
526b2412b7fSHuang Shijie 			unsigned long len = vma_pages(mpnt);
527b2412b7fSHuang Shijie 
528191c5424SAl Viro 			if (security_vm_enough_memory_mm(oldmm, len)) /* sic */
5291da177e4SLinus Torvalds 				goto fail_nomem;
5301da177e4SLinus Torvalds 			charge = len;
5311da177e4SLinus Torvalds 		}
5323928d4f5SLinus Torvalds 		tmp = vm_area_dup(mpnt);
5331da177e4SLinus Torvalds 		if (!tmp)
5341da177e4SLinus Torvalds 			goto fail_nomem;
535ef0855d3SOleg Nesterov 		retval = vma_dup_policy(mpnt, tmp);
536ef0855d3SOleg Nesterov 		if (retval)
5371da177e4SLinus Torvalds 			goto fail_nomem_policy;
538a247c3a9SAndrea Arcangeli 		tmp->vm_mm = mm;
539893e26e6SPavel Emelyanov 		retval = dup_userfaultfd(tmp, &uf);
540893e26e6SPavel Emelyanov 		if (retval)
541893e26e6SPavel Emelyanov 			goto fail_nomem_anon_vma_fork;
542d2cd9edeSRik van Riel 		if (tmp->vm_flags & VM_WIPEONFORK) {
543d2cd9edeSRik van Riel 			/* VM_WIPEONFORK gets a clean slate in the child. */
544d2cd9edeSRik van Riel 			tmp->anon_vma = NULL;
545d2cd9edeSRik van Riel 			if (anon_vma_prepare(tmp))
546d2cd9edeSRik van Riel 				goto fail_nomem_anon_vma_fork;
547d2cd9edeSRik van Riel 		} else if (anon_vma_fork(tmp, mpnt))
5485beb4930SRik van Riel 			goto fail_nomem_anon_vma_fork;
549893e26e6SPavel Emelyanov 		tmp->vm_flags &= ~(VM_LOCKED | VM_LOCKONFAULT);
550297c5eeeSLinus Torvalds 		tmp->vm_next = tmp->vm_prev = NULL;
5511da177e4SLinus Torvalds 		file = tmp->vm_file;
5521da177e4SLinus Torvalds 		if (file) {
553496ad9aaSAl Viro 			struct inode *inode = file_inode(file);
554b88ed205SHugh Dickins 			struct address_space *mapping = file->f_mapping;
555b88ed205SHugh Dickins 
5561da177e4SLinus Torvalds 			get_file(file);
5571da177e4SLinus Torvalds 			if (tmp->vm_flags & VM_DENYWRITE)
5581da177e4SLinus Torvalds 				atomic_dec(&inode->i_writecount);
55983cde9e8SDavidlohr Bueso 			i_mmap_lock_write(mapping);
560b88ed205SHugh Dickins 			if (tmp->vm_flags & VM_SHARED)
5614bb5f5d9SDavid Herrmann 				atomic_inc(&mapping->i_mmap_writable);
562b88ed205SHugh Dickins 			flush_dcache_mmap_lock(mapping);
563b88ed205SHugh Dickins 			/* insert tmp into the share list, just after mpnt */
5649826a516SMichel Lespinasse 			vma_interval_tree_insert_after(tmp, mpnt,
5659826a516SMichel Lespinasse 					&mapping->i_mmap);
566b88ed205SHugh Dickins 			flush_dcache_mmap_unlock(mapping);
56783cde9e8SDavidlohr Bueso 			i_mmap_unlock_write(mapping);
5681da177e4SLinus Torvalds 		}
5691da177e4SLinus Torvalds 
5701da177e4SLinus Torvalds 		/*
571a1e78772SMel Gorman 		 * Clear hugetlb-related page reserves for children. This only
572a1e78772SMel Gorman 		 * affects MAP_PRIVATE mappings. Faults generated by the child
573a1e78772SMel Gorman 		 * are not guaranteed to succeed, even if read-only
574a1e78772SMel Gorman 		 */
575a1e78772SMel Gorman 		if (is_vm_hugetlb_page(tmp))
576a1e78772SMel Gorman 			reset_vma_resv_huge_pages(tmp);
577a1e78772SMel Gorman 
578a1e78772SMel Gorman 		/*
5797ee78232SHugh Dickins 		 * Link in the new vma and copy the page table entries.
5801da177e4SLinus Torvalds 		 */
5811da177e4SLinus Torvalds 		*pprev = tmp;
5821da177e4SLinus Torvalds 		pprev = &tmp->vm_next;
583297c5eeeSLinus Torvalds 		tmp->vm_prev = prev;
584297c5eeeSLinus Torvalds 		prev = tmp;
5851da177e4SLinus Torvalds 
5861da177e4SLinus Torvalds 		__vma_link_rb(mm, tmp, rb_link, rb_parent);
5871da177e4SLinus Torvalds 		rb_link = &tmp->vm_rb.rb_right;
5881da177e4SLinus Torvalds 		rb_parent = &tmp->vm_rb;
5891da177e4SLinus Torvalds 
5901da177e4SLinus Torvalds 		mm->map_count++;
591d2cd9edeSRik van Riel 		if (!(tmp->vm_flags & VM_WIPEONFORK))
5920b0db14cSHugh Dickins 			retval = copy_page_range(mm, oldmm, mpnt);
5931da177e4SLinus Torvalds 
5941da177e4SLinus Torvalds 		if (tmp->vm_ops && tmp->vm_ops->open)
5951da177e4SLinus Torvalds 			tmp->vm_ops->open(tmp);
5961da177e4SLinus Torvalds 
5971da177e4SLinus Torvalds 		if (retval)
5981da177e4SLinus Torvalds 			goto out;
5991da177e4SLinus Torvalds 	}
600d6dd61c8SJeremy Fitzhardinge 	/* a new mm has just been created */
6011ed0cc5aSNadav Amit 	retval = arch_dup_mmap(oldmm, mm);
6021da177e4SLinus Torvalds out:
6037ee78232SHugh Dickins 	up_write(&mm->mmap_sem);
604fd3e42fcSHugh Dickins 	flush_tlb_mm(oldmm);
6051da177e4SLinus Torvalds 	up_write(&oldmm->mmap_sem);
606893e26e6SPavel Emelyanov 	dup_userfaultfd_complete(&uf);
6077c051267SMichal Hocko fail_uprobe_end:
60832cdba1eSOleg Nesterov 	uprobe_end_dup_mmap();
6091da177e4SLinus Torvalds 	return retval;
6105beb4930SRik van Riel fail_nomem_anon_vma_fork:
611ef0855d3SOleg Nesterov 	mpol_put(vma_policy(tmp));
6121da177e4SLinus Torvalds fail_nomem_policy:
6133928d4f5SLinus Torvalds 	vm_area_free(tmp);
6141da177e4SLinus Torvalds fail_nomem:
6151da177e4SLinus Torvalds 	retval = -ENOMEM;
6161da177e4SLinus Torvalds 	vm_unacct_memory(charge);
6171da177e4SLinus Torvalds 	goto out;
6181da177e4SLinus Torvalds }
6191da177e4SLinus Torvalds 
6201da177e4SLinus Torvalds static inline int mm_alloc_pgd(struct mm_struct *mm)
6211da177e4SLinus Torvalds {
6221da177e4SLinus Torvalds 	mm->pgd = pgd_alloc(mm);
6231da177e4SLinus Torvalds 	if (unlikely(!mm->pgd))
6241da177e4SLinus Torvalds 		return -ENOMEM;
6251da177e4SLinus Torvalds 	return 0;
6261da177e4SLinus Torvalds }
6271da177e4SLinus Torvalds 
6281da177e4SLinus Torvalds static inline void mm_free_pgd(struct mm_struct *mm)
6291da177e4SLinus Torvalds {
6305e541973SBenjamin Herrenschmidt 	pgd_free(mm, mm->pgd);
6311da177e4SLinus Torvalds }
6321da177e4SLinus Torvalds #else
63390f31d0eSKonstantin Khlebnikov static int dup_mmap(struct mm_struct *mm, struct mm_struct *oldmm)
63490f31d0eSKonstantin Khlebnikov {
63590f31d0eSKonstantin Khlebnikov 	down_write(&oldmm->mmap_sem);
63690f31d0eSKonstantin Khlebnikov 	RCU_INIT_POINTER(mm->exe_file, get_mm_exe_file(oldmm));
63790f31d0eSKonstantin Khlebnikov 	up_write(&oldmm->mmap_sem);
63890f31d0eSKonstantin Khlebnikov 	return 0;
63990f31d0eSKonstantin Khlebnikov }
6401da177e4SLinus Torvalds #define mm_alloc_pgd(mm)	(0)
6411da177e4SLinus Torvalds #define mm_free_pgd(mm)
6421da177e4SLinus Torvalds #endif /* CONFIG_MMU */
6431da177e4SLinus Torvalds 
644d70f2a14SAndrew Morton static void check_mm(struct mm_struct *mm)
645d70f2a14SAndrew Morton {
646d70f2a14SAndrew Morton 	int i;
647d70f2a14SAndrew Morton 
648d70f2a14SAndrew Morton 	for (i = 0; i < NR_MM_COUNTERS; i++) {
649d70f2a14SAndrew Morton 		long x = atomic_long_read(&mm->rss_stat.count[i]);
650d70f2a14SAndrew Morton 
651d70f2a14SAndrew Morton 		if (unlikely(x))
652d70f2a14SAndrew Morton 			printk(KERN_ALERT "BUG: Bad rss-counter state "
653d70f2a14SAndrew Morton 					  "mm:%p idx:%d val:%ld\n", mm, i, x);
654d70f2a14SAndrew Morton 	}
655d70f2a14SAndrew Morton 
656d70f2a14SAndrew Morton 	if (mm_pgtables_bytes(mm))
657d70f2a14SAndrew Morton 		pr_alert("BUG: non-zero pgtables_bytes on freeing mm: %ld\n",
658d70f2a14SAndrew Morton 				mm_pgtables_bytes(mm));
659d70f2a14SAndrew Morton 
660d70f2a14SAndrew Morton #if defined(CONFIG_TRANSPARENT_HUGEPAGE) && !USE_SPLIT_PMD_PTLOCKS
661d70f2a14SAndrew Morton 	VM_BUG_ON_MM(mm->pmd_huge_pte, mm);
662d70f2a14SAndrew Morton #endif
663d70f2a14SAndrew Morton }
6641da177e4SLinus Torvalds 
665e94b1766SChristoph Lameter #define allocate_mm()	(kmem_cache_alloc(mm_cachep, GFP_KERNEL))
6661da177e4SLinus Torvalds #define free_mm(mm)	(kmem_cache_free(mm_cachep, (mm)))
6671da177e4SLinus Torvalds 
668d70f2a14SAndrew Morton /*
669d70f2a14SAndrew Morton  * Called when the last reference to the mm
670d70f2a14SAndrew Morton  * is dropped: either by a lazy thread or by
671d70f2a14SAndrew Morton  * mmput. Free the page directory and the mm.
672d70f2a14SAndrew Morton  */
673d34bc48fSAndrew Morton void __mmdrop(struct mm_struct *mm)
674d70f2a14SAndrew Morton {
675d70f2a14SAndrew Morton 	BUG_ON(mm == &init_mm);
6763eda69c9SMark Rutland 	WARN_ON_ONCE(mm == current->mm);
6773eda69c9SMark Rutland 	WARN_ON_ONCE(mm == current->active_mm);
678d70f2a14SAndrew Morton 	mm_free_pgd(mm);
679d70f2a14SAndrew Morton 	destroy_context(mm);
680d70f2a14SAndrew Morton 	mmu_notifier_mm_destroy(mm);
681d70f2a14SAndrew Morton 	check_mm(mm);
682d70f2a14SAndrew Morton 	put_user_ns(mm->user_ns);
683d70f2a14SAndrew Morton 	free_mm(mm);
684d70f2a14SAndrew Morton }
685d34bc48fSAndrew Morton EXPORT_SYMBOL_GPL(__mmdrop);
686d70f2a14SAndrew Morton 
687d70f2a14SAndrew Morton static void mmdrop_async_fn(struct work_struct *work)
688d70f2a14SAndrew Morton {
689d70f2a14SAndrew Morton 	struct mm_struct *mm;
690d70f2a14SAndrew Morton 
691d70f2a14SAndrew Morton 	mm = container_of(work, struct mm_struct, async_put_work);
692d70f2a14SAndrew Morton 	__mmdrop(mm);
693d70f2a14SAndrew Morton }
694d70f2a14SAndrew Morton 
695d70f2a14SAndrew Morton static void mmdrop_async(struct mm_struct *mm)
696d70f2a14SAndrew Morton {
697d70f2a14SAndrew Morton 	if (unlikely(atomic_dec_and_test(&mm->mm_count))) {
698d70f2a14SAndrew Morton 		INIT_WORK(&mm->async_put_work, mmdrop_async_fn);
699d70f2a14SAndrew Morton 		schedule_work(&mm->async_put_work);
700d70f2a14SAndrew Morton 	}
701d70f2a14SAndrew Morton }
702d70f2a14SAndrew Morton 
7031da177e4SLinus Torvalds static inline void free_signal_struct(struct signal_struct *sig)
7041da177e4SLinus Torvalds {
7051da177e4SLinus Torvalds 	taskstats_tgid_free(sig);
7061da177e4SLinus Torvalds 	sched_autogroup_exit(sig);
7071da177e4SLinus Torvalds 	/*
7081da177e4SLinus Torvalds 	 * __mmdrop is not safe to call from softirq context on x86 due to
7091da177e4SLinus Torvalds 	 * pgd_dtor so postpone it to the async context
7101da177e4SLinus Torvalds 	 */
7111da177e4SLinus Torvalds 	if (sig->oom_mm)
7121da177e4SLinus Torvalds 		mmdrop_async(sig->oom_mm);
7131da177e4SLinus Torvalds 	kmem_cache_free(signal_cachep, sig);
7141da177e4SLinus Torvalds }
7151da177e4SLinus Torvalds 
7161da177e4SLinus Torvalds static inline void put_signal_struct(struct signal_struct *sig)
7171da177e4SLinus Torvalds {
71860d4de3fSElena Reshetova 	if (refcount_dec_and_test(&sig->sigcnt))
7191da177e4SLinus Torvalds 		free_signal_struct(sig);
7201da177e4SLinus Torvalds }
7211da177e4SLinus Torvalds 
7221da177e4SLinus Torvalds void __put_task_struct(struct task_struct *tsk)
7231da177e4SLinus Torvalds {
7241da177e4SLinus Torvalds 	WARN_ON(!tsk->exit_state);
725ec1d2819SElena Reshetova 	WARN_ON(refcount_read(&tsk->usage));
7261da177e4SLinus Torvalds 	WARN_ON(tsk == current);
7271da177e4SLinus Torvalds 
7281da177e4SLinus Torvalds 	cgroup_free(tsk);
729*16d51a59SJann Horn 	task_numa_free(tsk, true);
7301da177e4SLinus Torvalds 	security_task_free(tsk);
7311da177e4SLinus Torvalds 	exit_creds(tsk);
7321da177e4SLinus Torvalds 	delayacct_tsk_free(tsk);
7331da177e4SLinus Torvalds 	put_signal_struct(tsk->signal);
7341da177e4SLinus Torvalds 
7351da177e4SLinus Torvalds 	if (!profile_handoff_task(tsk))
7361da177e4SLinus Torvalds 		free_task(tsk);
7371da177e4SLinus Torvalds }
7381da177e4SLinus Torvalds EXPORT_SYMBOL_GPL(__put_task_struct);
7391da177e4SLinus Torvalds 
7401da177e4SLinus Torvalds void __init __weak arch_task_cache_init(void) { }
7411da177e4SLinus Torvalds 
7421da177e4SLinus Torvalds /*
7431da177e4SLinus Torvalds  * set_max_threads
7441da177e4SLinus Torvalds  */
7451da177e4SLinus Torvalds static void set_max_threads(unsigned int max_threads_suggested)
7461da177e4SLinus Torvalds {
7471da177e4SLinus Torvalds 	u64 threads;
748ca79b0c2SArun KS 	unsigned long nr_pages = totalram_pages();
7491da177e4SLinus Torvalds 
7501da177e4SLinus Torvalds 	/*
7511da177e4SLinus Torvalds 	 * The number of threads shall be limited such that the thread
7521da177e4SLinus Torvalds 	 * structures may only consume a small part of the available memory.
7531da177e4SLinus Torvalds 	 */
7543d6357deSArun KS 	if (fls64(nr_pages) + fls64(PAGE_SIZE) > 64)
7551da177e4SLinus Torvalds 		threads = MAX_THREADS;
7561da177e4SLinus Torvalds 	else
7573d6357deSArun KS 		threads = div64_u64((u64) nr_pages * (u64) PAGE_SIZE,
7581da177e4SLinus Torvalds 				    (u64) THREAD_SIZE * 8UL);
7591da177e4SLinus Torvalds 
7601da177e4SLinus Torvalds 	if (threads > max_threads_suggested)
7611da177e4SLinus Torvalds 		threads = max_threads_suggested;
7621da177e4SLinus Torvalds 
7631da177e4SLinus Torvalds 	max_threads = clamp_t(u64, threads, MIN_THREADS, MAX_THREADS);
7641da177e4SLinus Torvalds }
7651da177e4SLinus Torvalds 
7661da177e4SLinus Torvalds #ifdef CONFIG_ARCH_WANTS_DYNAMIC_TASK_STRUCT
7671da177e4SLinus Torvalds /* Initialized by the architecture: */
7681da177e4SLinus Torvalds int arch_task_struct_size __read_mostly;
7691da177e4SLinus Torvalds #endif
7701da177e4SLinus Torvalds 
7715905429aSKees Cook static void task_struct_whitelist(unsigned long *offset, unsigned long *size)
7725905429aSKees Cook {
7735905429aSKees Cook 	/* Fetch thread_struct whitelist for the architecture. */
7745905429aSKees Cook 	arch_thread_struct_whitelist(offset, size);
7755905429aSKees Cook 
7765905429aSKees Cook 	/*
7775905429aSKees Cook 	 * Handle zero-sized whitelist or empty thread_struct, otherwise
7785905429aSKees Cook 	 * adjust offset to position of thread_struct in task_struct.
7795905429aSKees Cook 	 */
7805905429aSKees Cook 	if (unlikely(*size == 0))
7815905429aSKees Cook 		*offset = 0;
7825905429aSKees Cook 	else
7835905429aSKees Cook 		*offset += offsetof(struct task_struct, thread);
7845905429aSKees Cook }
7855905429aSKees Cook 
7861da177e4SLinus Torvalds void __init fork_init(void)
7871da177e4SLinus Torvalds {
7881da177e4SLinus Torvalds 	int i;
7891da177e4SLinus Torvalds #ifndef CONFIG_ARCH_TASK_STRUCT_ALLOCATOR
7901da177e4SLinus Torvalds #ifndef ARCH_MIN_TASKALIGN
7911da177e4SLinus Torvalds #define ARCH_MIN_TASKALIGN	0
7921da177e4SLinus Torvalds #endif
7931da177e4SLinus Torvalds 	int align = max_t(int, L1_CACHE_BYTES, ARCH_MIN_TASKALIGN);
7945905429aSKees Cook 	unsigned long useroffset, usersize;
7951da177e4SLinus Torvalds 
7961da177e4SLinus Torvalds 	/* create a slab on which task_structs can be allocated */
7975905429aSKees Cook 	task_struct_whitelist(&useroffset, &usersize);
7985905429aSKees Cook 	task_struct_cachep = kmem_cache_create_usercopy("task_struct",
7991da177e4SLinus Torvalds 			arch_task_struct_size, align,
8005905429aSKees Cook 			SLAB_PANIC|SLAB_ACCOUNT,
8015905429aSKees Cook 			useroffset, usersize, NULL);
8021da177e4SLinus Torvalds #endif
8031da177e4SLinus Torvalds 
8041da177e4SLinus Torvalds 	/* do the arch specific task caches init */
8051da177e4SLinus Torvalds 	arch_task_cache_init();
8061da177e4SLinus Torvalds 
8071da177e4SLinus Torvalds 	set_max_threads(MAX_THREADS);
8081da177e4SLinus Torvalds 
8091da177e4SLinus Torvalds 	init_task.signal->rlim[RLIMIT_NPROC].rlim_cur = max_threads/2;
8101da177e4SLinus Torvalds 	init_task.signal->rlim[RLIMIT_NPROC].rlim_max = max_threads/2;
8111da177e4SLinus Torvalds 	init_task.signal->rlim[RLIMIT_SIGPENDING] =
8121da177e4SLinus Torvalds 		init_task.signal->rlim[RLIMIT_NPROC];
8131da177e4SLinus Torvalds 
8141da177e4SLinus Torvalds 	for (i = 0; i < UCOUNT_COUNTS; i++) {
8151da177e4SLinus Torvalds 		init_user_ns.ucount_max[i] = max_threads/2;
8161da177e4SLinus Torvalds 	}
8171da177e4SLinus Torvalds 
8181da177e4SLinus Torvalds #ifdef CONFIG_VMAP_STACK
8191da177e4SLinus Torvalds 	cpuhp_setup_state(CPUHP_BP_PREPARE_DYN, "fork:vm_stack_cache",
8201da177e4SLinus Torvalds 			  NULL, free_vm_stack_cache);
8211da177e4SLinus Torvalds #endif
8221da177e4SLinus Torvalds 
8231da177e4SLinus Torvalds 	lockdep_init_task(&init_task);
824aad42dd4SNadav Amit 	uprobes_init();
8251da177e4SLinus Torvalds }
8261da177e4SLinus Torvalds 
8271da177e4SLinus Torvalds int __weak arch_dup_task_struct(struct task_struct *dst,
8281da177e4SLinus Torvalds 					       struct task_struct *src)
8291da177e4SLinus Torvalds {
8301da177e4SLinus Torvalds 	*dst = *src;
8311da177e4SLinus Torvalds 	return 0;
8321da177e4SLinus Torvalds }
8331da177e4SLinus Torvalds 
8341da177e4SLinus Torvalds void set_task_stack_end_magic(struct task_struct *tsk)
8351da177e4SLinus Torvalds {
8361da177e4SLinus Torvalds 	unsigned long *stackend;
8371da177e4SLinus Torvalds 
8381da177e4SLinus Torvalds 	stackend = end_of_stack(tsk);
8391da177e4SLinus Torvalds 	*stackend = STACK_END_MAGIC;	/* for overflow detection */
8401da177e4SLinus Torvalds }
8411da177e4SLinus Torvalds 
8421da177e4SLinus Torvalds static struct task_struct *dup_task_struct(struct task_struct *orig, int node)
8431da177e4SLinus Torvalds {
8441da177e4SLinus Torvalds 	struct task_struct *tsk;
8451da177e4SLinus Torvalds 	unsigned long *stack;
8460f4991e8SYueHaibing 	struct vm_struct *stack_vm_area __maybe_unused;
8471da177e4SLinus Torvalds 	int err;
8481da177e4SLinus Torvalds 
8491da177e4SLinus Torvalds 	if (node == NUMA_NO_NODE)
8501da177e4SLinus Torvalds 		node = tsk_fork_get_node(orig);
8511da177e4SLinus Torvalds 	tsk = alloc_task_struct_node(node);
8521da177e4SLinus Torvalds 	if (!tsk)
8531da177e4SLinus Torvalds 		return NULL;
8541da177e4SLinus Torvalds 
8551da177e4SLinus Torvalds 	stack = alloc_thread_stack_node(tsk, node);
8561da177e4SLinus Torvalds 	if (!stack)
8571da177e4SLinus Torvalds 		goto free_tsk;
8581da177e4SLinus Torvalds 
8599b6f7e16SRoman Gushchin 	if (memcg_charge_kernel_stack(tsk))
8609b6f7e16SRoman Gushchin 		goto free_stack;
8619b6f7e16SRoman Gushchin 
8621da177e4SLinus Torvalds 	stack_vm_area = task_stack_vm_area(tsk);
8631da177e4SLinus Torvalds 
8641da177e4SLinus Torvalds 	err = arch_dup_task_struct(tsk, orig);
8651da177e4SLinus Torvalds 
8661da177e4SLinus Torvalds 	/*
8671da177e4SLinus Torvalds 	 * arch_dup_task_struct() clobbers the stack-related fields.  Make
8681da177e4SLinus Torvalds 	 * sure they're properly initialized before using any stack-related
8691da177e4SLinus Torvalds 	 * functions again.
8701da177e4SLinus Torvalds 	 */
8711da177e4SLinus Torvalds 	tsk->stack = stack;
8721da177e4SLinus Torvalds #ifdef CONFIG_VMAP_STACK
8731da177e4SLinus Torvalds 	tsk->stack_vm_area = stack_vm_area;
8741da177e4SLinus Torvalds #endif
8751da177e4SLinus Torvalds #ifdef CONFIG_THREAD_INFO_IN_TASK
876f0b89d39SElena Reshetova 	refcount_set(&tsk->stack_refcount, 1);
8771da177e4SLinus Torvalds #endif
8781da177e4SLinus Torvalds 
8791da177e4SLinus Torvalds 	if (err)
8801da177e4SLinus Torvalds 		goto free_stack;
8811da177e4SLinus Torvalds 
8821da177e4SLinus Torvalds #ifdef CONFIG_SECCOMP
8831da177e4SLinus Torvalds 	/*
8841da177e4SLinus Torvalds 	 * We must handle setting up seccomp filters once we're under
8851da177e4SLinus Torvalds 	 * the sighand lock in case orig has changed between now and
8861da177e4SLinus Torvalds 	 * then. Until then, filter must be NULL to avoid messing up
8871da177e4SLinus Torvalds 	 * the usage counts on the error path calling free_task.
8881da177e4SLinus Torvalds 	 */
8891da177e4SLinus Torvalds 	tsk->seccomp.filter = NULL;
8901da177e4SLinus Torvalds #endif
8911da177e4SLinus Torvalds 
8921da177e4SLinus Torvalds 	setup_thread_stack(tsk, orig);
8931da177e4SLinus Torvalds 	clear_user_return_notifier(tsk);
8941da177e4SLinus Torvalds 	clear_tsk_need_resched(tsk);
8951da177e4SLinus Torvalds 	set_task_stack_end_magic(tsk);
8961da177e4SLinus Torvalds 
897050e9baaSLinus Torvalds #ifdef CONFIG_STACKPROTECTOR
8981da177e4SLinus Torvalds 	tsk->stack_canary = get_random_canary();
8991da177e4SLinus Torvalds #endif
9003bd37062SSebastian Andrzej Siewior 	if (orig->cpus_ptr == &orig->cpus_mask)
9013bd37062SSebastian Andrzej Siewior 		tsk->cpus_ptr = &tsk->cpus_mask;
9021da177e4SLinus Torvalds 
9031da177e4SLinus Torvalds 	/*
9041da177e4SLinus Torvalds 	 * One for us, one for whoever does the "release_task()" (usually
9051da177e4SLinus Torvalds 	 * parent)
9061da177e4SLinus Torvalds 	 */
907ec1d2819SElena Reshetova 	refcount_set(&tsk->usage, 2);
9081da177e4SLinus Torvalds #ifdef CONFIG_BLK_DEV_IO_TRACE
9091da177e4SLinus Torvalds 	tsk->btrace_seq = 0;
9101da177e4SLinus Torvalds #endif
9111da177e4SLinus Torvalds 	tsk->splice_pipe = NULL;
9121da177e4SLinus Torvalds 	tsk->task_frag.page = NULL;
9131da177e4SLinus Torvalds 	tsk->wake_q.next = NULL;
9141da177e4SLinus Torvalds 
9151da177e4SLinus Torvalds 	account_kernel_stack(tsk, 1);
9161da177e4SLinus Torvalds 
9171da177e4SLinus Torvalds 	kcov_task_init(tsk);
9181da177e4SLinus Torvalds 
9191da177e4SLinus Torvalds #ifdef CONFIG_FAULT_INJECTION
9201da177e4SLinus Torvalds 	tsk->fail_nth = 0;
9211da177e4SLinus Torvalds #endif
9221da177e4SLinus Torvalds 
9232c323017SJosef Bacik #ifdef CONFIG_BLK_CGROUP
9242c323017SJosef Bacik 	tsk->throttle_queue = NULL;
9252c323017SJosef Bacik 	tsk->use_memdelay = 0;
9262c323017SJosef Bacik #endif
9272c323017SJosef Bacik 
928d46eb14bSShakeel Butt #ifdef CONFIG_MEMCG
929d46eb14bSShakeel Butt 	tsk->active_memcg = NULL;
930d46eb14bSShakeel Butt #endif
9311da177e4SLinus Torvalds 	return tsk;
9321da177e4SLinus Torvalds 
9331da177e4SLinus Torvalds free_stack:
9341da177e4SLinus Torvalds 	free_thread_stack(tsk);
9351da177e4SLinus Torvalds free_tsk:
9361da177e4SLinus Torvalds 	free_task_struct(tsk);
9371da177e4SLinus Torvalds 	return NULL;
9381da177e4SLinus Torvalds }
9391da177e4SLinus Torvalds 
9401da177e4SLinus Torvalds __cacheline_aligned_in_smp DEFINE_SPINLOCK(mmlist_lock);
9411da177e4SLinus Torvalds 
9424cb0e11bSHidehiro Kawai static unsigned long default_dump_filter = MMF_DUMP_FILTER_DEFAULT;
9434cb0e11bSHidehiro Kawai 
9444cb0e11bSHidehiro Kawai static int __init coredump_filter_setup(char *s)
9454cb0e11bSHidehiro Kawai {
9464cb0e11bSHidehiro Kawai 	default_dump_filter =
9474cb0e11bSHidehiro Kawai 		(simple_strtoul(s, NULL, 0) << MMF_DUMP_FILTER_SHIFT) &
9484cb0e11bSHidehiro Kawai 		MMF_DUMP_FILTER_MASK;
9494cb0e11bSHidehiro Kawai 	return 1;
9504cb0e11bSHidehiro Kawai }
9514cb0e11bSHidehiro Kawai 
9524cb0e11bSHidehiro Kawai __setup("coredump_filter=", coredump_filter_setup);
9534cb0e11bSHidehiro Kawai 
9541da177e4SLinus Torvalds #include <linux/init_task.h>
9551da177e4SLinus Torvalds 
956858f0993SAlexey Dobriyan static void mm_init_aio(struct mm_struct *mm)
957858f0993SAlexey Dobriyan {
958858f0993SAlexey Dobriyan #ifdef CONFIG_AIO
959858f0993SAlexey Dobriyan 	spin_lock_init(&mm->ioctx_lock);
960db446a08SBenjamin LaHaise 	mm->ioctx_table = NULL;
961858f0993SAlexey Dobriyan #endif
962858f0993SAlexey Dobriyan }
963858f0993SAlexey Dobriyan 
964c3f3ce04SAndrea Arcangeli static __always_inline void mm_clear_owner(struct mm_struct *mm,
965c3f3ce04SAndrea Arcangeli 					   struct task_struct *p)
966c3f3ce04SAndrea Arcangeli {
967c3f3ce04SAndrea Arcangeli #ifdef CONFIG_MEMCG
968c3f3ce04SAndrea Arcangeli 	if (mm->owner == p)
969c3f3ce04SAndrea Arcangeli 		WRITE_ONCE(mm->owner, NULL);
970c3f3ce04SAndrea Arcangeli #endif
971c3f3ce04SAndrea Arcangeli }
972c3f3ce04SAndrea Arcangeli 
97333144e84SVladimir Davydov static void mm_init_owner(struct mm_struct *mm, struct task_struct *p)
97433144e84SVladimir Davydov {
97533144e84SVladimir Davydov #ifdef CONFIG_MEMCG
97633144e84SVladimir Davydov 	mm->owner = p;
97733144e84SVladimir Davydov #endif
97833144e84SVladimir Davydov }
97933144e84SVladimir Davydov 
980355627f5SEric Biggers static void mm_init_uprobes_state(struct mm_struct *mm)
981355627f5SEric Biggers {
982355627f5SEric Biggers #ifdef CONFIG_UPROBES
983355627f5SEric Biggers 	mm->uprobes_state.xol_area = NULL;
984355627f5SEric Biggers #endif
985355627f5SEric Biggers }
986355627f5SEric Biggers 
987bfedb589SEric W. Biederman static struct mm_struct *mm_init(struct mm_struct *mm, struct task_struct *p,
988bfedb589SEric W. Biederman 	struct user_namespace *user_ns)
9891da177e4SLinus Torvalds {
99041f727fdSVladimir Davydov 	mm->mmap = NULL;
99141f727fdSVladimir Davydov 	mm->mm_rb = RB_ROOT;
99241f727fdSVladimir Davydov 	mm->vmacache_seqnum = 0;
9931da177e4SLinus Torvalds 	atomic_set(&mm->mm_users, 1);
9941da177e4SLinus Torvalds 	atomic_set(&mm->mm_count, 1);
9951da177e4SLinus Torvalds 	init_rwsem(&mm->mmap_sem);
9961da177e4SLinus Torvalds 	INIT_LIST_HEAD(&mm->mmlist);
997999d9fc1SOleg Nesterov 	mm->core_state = NULL;
998af5b0f6aSKirill A. Shutemov 	mm_pgtables_bytes_init(mm);
99941f727fdSVladimir Davydov 	mm->map_count = 0;
100041f727fdSVladimir Davydov 	mm->locked_vm = 0;
100170f8a3caSDavidlohr Bueso 	atomic64_set(&mm->pinned_vm, 0);
1002d559db08SKAMEZAWA Hiroyuki 	memset(&mm->rss_stat, 0, sizeof(mm->rss_stat));
10031da177e4SLinus Torvalds 	spin_lock_init(&mm->page_table_lock);
100488aa7cc6SYang Shi 	spin_lock_init(&mm->arg_lock);
100541f727fdSVladimir Davydov 	mm_init_cpumask(mm);
1006858f0993SAlexey Dobriyan 	mm_init_aio(mm);
1007cf475ad2SBalbir Singh 	mm_init_owner(mm, p);
10082b7e8665SEric Biggers 	RCU_INIT_POINTER(mm->exe_file, NULL);
100941f727fdSVladimir Davydov 	mmu_notifier_mm_init(mm);
1010133ff0eaSJérôme Glisse 	hmm_mm_init(mm);
101116af97dcSNadav Amit 	init_tlb_flush_pending(mm);
101241f727fdSVladimir Davydov #if defined(CONFIG_TRANSPARENT_HUGEPAGE) && !USE_SPLIT_PMD_PTLOCKS
101341f727fdSVladimir Davydov 	mm->pmd_huge_pte = NULL;
101441f727fdSVladimir Davydov #endif
1015355627f5SEric Biggers 	mm_init_uprobes_state(mm);
10161da177e4SLinus Torvalds 
1017a0715cc2SAlex Thorlton 	if (current->mm) {
1018a0715cc2SAlex Thorlton 		mm->flags = current->mm->flags & MMF_INIT_MASK;
1019a0715cc2SAlex Thorlton 		mm->def_flags = current->mm->def_flags & VM_INIT_DEF_MASK;
1020a0715cc2SAlex Thorlton 	} else {
1021a0715cc2SAlex Thorlton 		mm->flags = default_dump_filter;
10221da177e4SLinus Torvalds 		mm->def_flags = 0;
1023a0715cc2SAlex Thorlton 	}
1024a0715cc2SAlex Thorlton 
102541f727fdSVladimir Davydov 	if (mm_alloc_pgd(mm))
102641f727fdSVladimir Davydov 		goto fail_nopgd;
102778fb7466SPavel Emelianov 
102841f727fdSVladimir Davydov 	if (init_new_context(p, mm))
102941f727fdSVladimir Davydov 		goto fail_nocontext;
103041f727fdSVladimir Davydov 
1031bfedb589SEric W. Biederman 	mm->user_ns = get_user_ns(user_ns);
103241f727fdSVladimir Davydov 	return mm;
103341f727fdSVladimir Davydov 
103441f727fdSVladimir Davydov fail_nocontext:
103541f727fdSVladimir Davydov 	mm_free_pgd(mm);
103641f727fdSVladimir Davydov fail_nopgd:
10371da177e4SLinus Torvalds 	free_mm(mm);
10381da177e4SLinus Torvalds 	return NULL;
10391da177e4SLinus Torvalds }
10401da177e4SLinus Torvalds 
10411da177e4SLinus Torvalds /*
10421da177e4SLinus Torvalds  * Allocate and initialize an mm_struct.
10431da177e4SLinus Torvalds  */
10441da177e4SLinus Torvalds struct mm_struct *mm_alloc(void)
10451da177e4SLinus Torvalds {
10461da177e4SLinus Torvalds 	struct mm_struct *mm;
10471da177e4SLinus Torvalds 
10481da177e4SLinus Torvalds 	mm = allocate_mm();
1049de03c72cSKOSAKI Motohiro 	if (!mm)
1050de03c72cSKOSAKI Motohiro 		return NULL;
1051de03c72cSKOSAKI Motohiro 
10521da177e4SLinus Torvalds 	memset(mm, 0, sizeof(*mm));
1053bfedb589SEric W. Biederman 	return mm_init(mm, current, current_user_ns());
10541da177e4SLinus Torvalds }
10551da177e4SLinus Torvalds 
1056ec8d7c14SMichal Hocko static inline void __mmput(struct mm_struct *mm)
10571da177e4SLinus Torvalds {
1058ec8d7c14SMichal Hocko 	VM_BUG_ON(atomic_read(&mm->mm_users));
10590ae26f1bSAndrew Morton 
1060d4b3b638SSrikar Dronamraju 	uprobe_clear_state(mm);
10611da177e4SLinus Torvalds 	exit_aio(mm);
10621c2fb7a4SAndrea Arcangeli 	ksm_exit(mm);
1063ba76149fSAndrea Arcangeli 	khugepaged_exit(mm); /* must run before exit_mmap */
10641da177e4SLinus Torvalds 	exit_mmap(mm);
10656fcb52a5SAaron Lu 	mm_put_huge_zero_page(mm);
1066925d1c40SMatt Helsley 	set_mm_exe_file(mm, NULL);
10671da177e4SLinus Torvalds 	if (!list_empty(&mm->mmlist)) {
10681da177e4SLinus Torvalds 		spin_lock(&mmlist_lock);
10691da177e4SLinus Torvalds 		list_del(&mm->mmlist);
10701da177e4SLinus Torvalds 		spin_unlock(&mmlist_lock);
10711da177e4SLinus Torvalds 	}
1072801460d0SHiroshi Shimamoto 	if (mm->binfmt)
1073801460d0SHiroshi Shimamoto 		module_put(mm->binfmt->module);
10741da177e4SLinus Torvalds 	mmdrop(mm);
10751da177e4SLinus Torvalds }
1076ec8d7c14SMichal Hocko 
1077ec8d7c14SMichal Hocko /*
1078ec8d7c14SMichal Hocko  * Decrement the use count and release all resources for an mm.
1079ec8d7c14SMichal Hocko  */
1080ec8d7c14SMichal Hocko void mmput(struct mm_struct *mm)
1081ec8d7c14SMichal Hocko {
1082ec8d7c14SMichal Hocko 	might_sleep();
1083ec8d7c14SMichal Hocko 
1084ec8d7c14SMichal Hocko 	if (atomic_dec_and_test(&mm->mm_users))
1085ec8d7c14SMichal Hocko 		__mmput(mm);
10861da177e4SLinus Torvalds }
10871da177e4SLinus Torvalds EXPORT_SYMBOL_GPL(mmput);
10881da177e4SLinus Torvalds 
1089a1b2289cSSherry Yang #ifdef CONFIG_MMU
1090a1b2289cSSherry Yang static void mmput_async_fn(struct work_struct *work)
1091a1b2289cSSherry Yang {
1092a1b2289cSSherry Yang 	struct mm_struct *mm = container_of(work, struct mm_struct,
1093a1b2289cSSherry Yang 					    async_put_work);
1094a1b2289cSSherry Yang 
1095a1b2289cSSherry Yang 	__mmput(mm);
1096a1b2289cSSherry Yang }
1097a1b2289cSSherry Yang 
1098a1b2289cSSherry Yang void mmput_async(struct mm_struct *mm)
1099a1b2289cSSherry Yang {
1100a1b2289cSSherry Yang 	if (atomic_dec_and_test(&mm->mm_users)) {
1101a1b2289cSSherry Yang 		INIT_WORK(&mm->async_put_work, mmput_async_fn);
1102a1b2289cSSherry Yang 		schedule_work(&mm->async_put_work);
1103a1b2289cSSherry Yang 	}
1104a1b2289cSSherry Yang }
1105a1b2289cSSherry Yang #endif
1106a1b2289cSSherry Yang 
110790f31d0eSKonstantin Khlebnikov /**
110890f31d0eSKonstantin Khlebnikov  * set_mm_exe_file - change a reference to the mm's executable file
110990f31d0eSKonstantin Khlebnikov  *
111090f31d0eSKonstantin Khlebnikov  * This changes mm's executable file (shown as symlink /proc/[pid]/exe).
111190f31d0eSKonstantin Khlebnikov  *
11126e399cd1SDavidlohr Bueso  * Main users are mmput() and sys_execve(). Callers prevent concurrent
11136e399cd1SDavidlohr Bueso  * invocations: in mmput() nobody alive left, in execve task is single
11146e399cd1SDavidlohr Bueso  * threaded. sys_prctl(PR_SET_MM_MAP/EXE_FILE) also needs to set the
11156e399cd1SDavidlohr Bueso  * mm->exe_file, but does so without using set_mm_exe_file() in order
11166e399cd1SDavidlohr Bueso  * to do avoid the need for any locks.
111790f31d0eSKonstantin Khlebnikov  */
111838646013SJiri Slaby void set_mm_exe_file(struct mm_struct *mm, struct file *new_exe_file)
111938646013SJiri Slaby {
11206e399cd1SDavidlohr Bueso 	struct file *old_exe_file;
11216e399cd1SDavidlohr Bueso 
11226e399cd1SDavidlohr Bueso 	/*
11236e399cd1SDavidlohr Bueso 	 * It is safe to dereference the exe_file without RCU as
11246e399cd1SDavidlohr Bueso 	 * this function is only called if nobody else can access
11256e399cd1SDavidlohr Bueso 	 * this mm -- see comment above for justification.
11266e399cd1SDavidlohr Bueso 	 */
11276e399cd1SDavidlohr Bueso 	old_exe_file = rcu_dereference_raw(mm->exe_file);
112890f31d0eSKonstantin Khlebnikov 
112938646013SJiri Slaby 	if (new_exe_file)
113038646013SJiri Slaby 		get_file(new_exe_file);
113190f31d0eSKonstantin Khlebnikov 	rcu_assign_pointer(mm->exe_file, new_exe_file);
113290f31d0eSKonstantin Khlebnikov 	if (old_exe_file)
113390f31d0eSKonstantin Khlebnikov 		fput(old_exe_file);
113438646013SJiri Slaby }
113538646013SJiri Slaby 
113690f31d0eSKonstantin Khlebnikov /**
113790f31d0eSKonstantin Khlebnikov  * get_mm_exe_file - acquire a reference to the mm's executable file
113890f31d0eSKonstantin Khlebnikov  *
113990f31d0eSKonstantin Khlebnikov  * Returns %NULL if mm has no associated executable file.
114090f31d0eSKonstantin Khlebnikov  * User must release file via fput().
114190f31d0eSKonstantin Khlebnikov  */
114238646013SJiri Slaby struct file *get_mm_exe_file(struct mm_struct *mm)
114338646013SJiri Slaby {
114438646013SJiri Slaby 	struct file *exe_file;
114538646013SJiri Slaby 
114690f31d0eSKonstantin Khlebnikov 	rcu_read_lock();
114790f31d0eSKonstantin Khlebnikov 	exe_file = rcu_dereference(mm->exe_file);
114890f31d0eSKonstantin Khlebnikov 	if (exe_file && !get_file_rcu(exe_file))
114990f31d0eSKonstantin Khlebnikov 		exe_file = NULL;
115090f31d0eSKonstantin Khlebnikov 	rcu_read_unlock();
115138646013SJiri Slaby 	return exe_file;
115238646013SJiri Slaby }
115311163348SDavidlohr Bueso EXPORT_SYMBOL(get_mm_exe_file);
115438646013SJiri Slaby 
11551da177e4SLinus Torvalds /**
1156cd81a917SMateusz Guzik  * get_task_exe_file - acquire a reference to the task's executable file
1157cd81a917SMateusz Guzik  *
1158cd81a917SMateusz Guzik  * Returns %NULL if task's mm (if any) has no associated executable file or
1159cd81a917SMateusz Guzik  * this is a kernel thread with borrowed mm (see the comment above get_task_mm).
1160cd81a917SMateusz Guzik  * User must release file via fput().
1161cd81a917SMateusz Guzik  */
1162cd81a917SMateusz Guzik struct file *get_task_exe_file(struct task_struct *task)
1163cd81a917SMateusz Guzik {
1164cd81a917SMateusz Guzik 	struct file *exe_file = NULL;
1165cd81a917SMateusz Guzik 	struct mm_struct *mm;
1166cd81a917SMateusz Guzik 
1167cd81a917SMateusz Guzik 	task_lock(task);
1168cd81a917SMateusz Guzik 	mm = task->mm;
1169cd81a917SMateusz Guzik 	if (mm) {
1170cd81a917SMateusz Guzik 		if (!(task->flags & PF_KTHREAD))
1171cd81a917SMateusz Guzik 			exe_file = get_mm_exe_file(mm);
1172cd81a917SMateusz Guzik 	}
1173cd81a917SMateusz Guzik 	task_unlock(task);
1174cd81a917SMateusz Guzik 	return exe_file;
1175cd81a917SMateusz Guzik }
1176cd81a917SMateusz Guzik EXPORT_SYMBOL(get_task_exe_file);
1177cd81a917SMateusz Guzik 
1178cd81a917SMateusz Guzik /**
11791da177e4SLinus Torvalds  * get_task_mm - acquire a reference to the task's mm
11801da177e4SLinus Torvalds  *
1181246bb0b1SOleg Nesterov  * Returns %NULL if the task has no mm.  Checks PF_KTHREAD (meaning
11821da177e4SLinus Torvalds  * this kernel workthread has transiently adopted a user mm with use_mm,
11831da177e4SLinus Torvalds  * to do its AIO) is not set and if so returns a reference to it, after
11841da177e4SLinus Torvalds  * bumping up the use count.  User must release the mm via mmput()
11851da177e4SLinus Torvalds  * after use.  Typically used by /proc and ptrace.
11861da177e4SLinus Torvalds  */
11871da177e4SLinus Torvalds struct mm_struct *get_task_mm(struct task_struct *task)
11881da177e4SLinus Torvalds {
11891da177e4SLinus Torvalds 	struct mm_struct *mm;
11901da177e4SLinus Torvalds 
11911da177e4SLinus Torvalds 	task_lock(task);
11921da177e4SLinus Torvalds 	mm = task->mm;
11931da177e4SLinus Torvalds 	if (mm) {
1194246bb0b1SOleg Nesterov 		if (task->flags & PF_KTHREAD)
11951da177e4SLinus Torvalds 			mm = NULL;
11961da177e4SLinus Torvalds 		else
11973fce371bSVegard Nossum 			mmget(mm);
11981da177e4SLinus Torvalds 	}
11991da177e4SLinus Torvalds 	task_unlock(task);
12001da177e4SLinus Torvalds 	return mm;
12011da177e4SLinus Torvalds }
12021da177e4SLinus Torvalds EXPORT_SYMBOL_GPL(get_task_mm);
12031da177e4SLinus Torvalds 
12048cdb878dSChristopher Yeoh struct mm_struct *mm_access(struct task_struct *task, unsigned int mode)
12058cdb878dSChristopher Yeoh {
12068cdb878dSChristopher Yeoh 	struct mm_struct *mm;
12078cdb878dSChristopher Yeoh 	int err;
12088cdb878dSChristopher Yeoh 
12098cdb878dSChristopher Yeoh 	err =  mutex_lock_killable(&task->signal->cred_guard_mutex);
12108cdb878dSChristopher Yeoh 	if (err)
12118cdb878dSChristopher Yeoh 		return ERR_PTR(err);
12128cdb878dSChristopher Yeoh 
12138cdb878dSChristopher Yeoh 	mm = get_task_mm(task);
12148cdb878dSChristopher Yeoh 	if (mm && mm != current->mm &&
12158cdb878dSChristopher Yeoh 			!ptrace_may_access(task, mode)) {
12168cdb878dSChristopher Yeoh 		mmput(mm);
12178cdb878dSChristopher Yeoh 		mm = ERR_PTR(-EACCES);
12188cdb878dSChristopher Yeoh 	}
12198cdb878dSChristopher Yeoh 	mutex_unlock(&task->signal->cred_guard_mutex);
12208cdb878dSChristopher Yeoh 
12218cdb878dSChristopher Yeoh 	return mm;
12228cdb878dSChristopher Yeoh }
12238cdb878dSChristopher Yeoh 
122457b59c4aSOleg Nesterov static void complete_vfork_done(struct task_struct *tsk)
1225c415c3b4SOleg Nesterov {
1226d68b46feSOleg Nesterov 	struct completion *vfork;
1227c415c3b4SOleg Nesterov 
1228d68b46feSOleg Nesterov 	task_lock(tsk);
1229d68b46feSOleg Nesterov 	vfork = tsk->vfork_done;
1230d68b46feSOleg Nesterov 	if (likely(vfork)) {
1231c415c3b4SOleg Nesterov 		tsk->vfork_done = NULL;
1232d68b46feSOleg Nesterov 		complete(vfork);
1233d68b46feSOleg Nesterov 	}
1234d68b46feSOleg Nesterov 	task_unlock(tsk);
1235d68b46feSOleg Nesterov }
1236d68b46feSOleg Nesterov 
1237d68b46feSOleg Nesterov static int wait_for_vfork_done(struct task_struct *child,
1238d68b46feSOleg Nesterov 				struct completion *vfork)
1239d68b46feSOleg Nesterov {
1240d68b46feSOleg Nesterov 	int killed;
1241d68b46feSOleg Nesterov 
1242d68b46feSOleg Nesterov 	freezer_do_not_count();
124376f969e8SRoman Gushchin 	cgroup_enter_frozen();
1244d68b46feSOleg Nesterov 	killed = wait_for_completion_killable(vfork);
124576f969e8SRoman Gushchin 	cgroup_leave_frozen(false);
1246d68b46feSOleg Nesterov 	freezer_count();
1247d68b46feSOleg Nesterov 
1248d68b46feSOleg Nesterov 	if (killed) {
1249d68b46feSOleg Nesterov 		task_lock(child);
1250d68b46feSOleg Nesterov 		child->vfork_done = NULL;
1251d68b46feSOleg Nesterov 		task_unlock(child);
1252d68b46feSOleg Nesterov 	}
1253d68b46feSOleg Nesterov 
1254d68b46feSOleg Nesterov 	put_task_struct(child);
1255d68b46feSOleg Nesterov 	return killed;
1256c415c3b4SOleg Nesterov }
1257c415c3b4SOleg Nesterov 
12581da177e4SLinus Torvalds /* Please note the differences between mmput and mm_release.
12591da177e4SLinus Torvalds  * mmput is called whenever we stop holding onto a mm_struct,
12601da177e4SLinus Torvalds  * error success whatever.
12611da177e4SLinus Torvalds  *
12621da177e4SLinus Torvalds  * mm_release is called after a mm_struct has been removed
12631da177e4SLinus Torvalds  * from the current process.
12641da177e4SLinus Torvalds  *
12651da177e4SLinus Torvalds  * This difference is important for error handling, when we
12661da177e4SLinus Torvalds  * only half set up a mm_struct for a new process and need to restore
12671da177e4SLinus Torvalds  * the old one.  Because we mmput the new mm_struct before
12681da177e4SLinus Torvalds  * restoring the old one. . .
12691da177e4SLinus Torvalds  * Eric Biederman 10 January 1998
12701da177e4SLinus Torvalds  */
12711da177e4SLinus Torvalds void mm_release(struct task_struct *tsk, struct mm_struct *mm)
12721da177e4SLinus Torvalds {
12738141c7f3SLinus Torvalds 	/* Get rid of any futexes when releasing the mm */
12748141c7f3SLinus Torvalds #ifdef CONFIG_FUTEX
1275fc6b177dSPeter Zijlstra 	if (unlikely(tsk->robust_list)) {
12768141c7f3SLinus Torvalds 		exit_robust_list(tsk);
1277fc6b177dSPeter Zijlstra 		tsk->robust_list = NULL;
1278fc6b177dSPeter Zijlstra 	}
12798141c7f3SLinus Torvalds #ifdef CONFIG_COMPAT
1280fc6b177dSPeter Zijlstra 	if (unlikely(tsk->compat_robust_list)) {
12818141c7f3SLinus Torvalds 		compat_exit_robust_list(tsk);
1282fc6b177dSPeter Zijlstra 		tsk->compat_robust_list = NULL;
1283fc6b177dSPeter Zijlstra 	}
12848141c7f3SLinus Torvalds #endif
1285322a2c10SThomas Gleixner 	if (unlikely(!list_empty(&tsk->pi_state_list)))
1286322a2c10SThomas Gleixner 		exit_pi_state_list(tsk);
12878141c7f3SLinus Torvalds #endif
12888141c7f3SLinus Torvalds 
12890326f5a9SSrikar Dronamraju 	uprobe_free_utask(tsk);
12900326f5a9SSrikar Dronamraju 
12911da177e4SLinus Torvalds 	/* Get rid of any cached register state */
12921da177e4SLinus Torvalds 	deactivate_mm(tsk, mm);
12931da177e4SLinus Torvalds 
1294fec1d011SRoland McGrath 	/*
1295735f2770SMichal Hocko 	 * Signal userspace if we're not exiting with a core dump
1296735f2770SMichal Hocko 	 * because we want to leave the value intact for debugging
1297735f2770SMichal Hocko 	 * purposes.
1298fec1d011SRoland McGrath 	 */
12999c8a8228SEric Dumazet 	if (tsk->clear_child_tid) {
1300735f2770SMichal Hocko 		if (!(tsk->signal->flags & SIGNAL_GROUP_COREDUMP) &&
13019c8a8228SEric Dumazet 		    atomic_read(&mm->mm_users) > 1) {
13021da177e4SLinus Torvalds 			/*
13031da177e4SLinus Torvalds 			 * We don't check the error code - if userspace has
13041da177e4SLinus Torvalds 			 * not set up a proper pointer then tough luck.
13051da177e4SLinus Torvalds 			 */
13069c8a8228SEric Dumazet 			put_user(0, tsk->clear_child_tid);
13072de0db99SDominik Brodowski 			do_futex(tsk->clear_child_tid, FUTEX_WAKE,
13082de0db99SDominik Brodowski 					1, NULL, NULL, 0, 0);
13099c8a8228SEric Dumazet 		}
13109c8a8228SEric Dumazet 		tsk->clear_child_tid = NULL;
13111da177e4SLinus Torvalds 	}
1312f7505d64SKonstantin Khlebnikov 
1313f7505d64SKonstantin Khlebnikov 	/*
1314f7505d64SKonstantin Khlebnikov 	 * All done, finally we can wake up parent and return this mm to him.
1315f7505d64SKonstantin Khlebnikov 	 * Also kthread_stop() uses this completion for synchronization.
1316f7505d64SKonstantin Khlebnikov 	 */
1317f7505d64SKonstantin Khlebnikov 	if (tsk->vfork_done)
1318f7505d64SKonstantin Khlebnikov 		complete_vfork_done(tsk);
13191da177e4SLinus Torvalds }
13201da177e4SLinus Torvalds 
132113585fa0SNadav Amit /**
132213585fa0SNadav Amit  * dup_mm() - duplicates an existing mm structure
132313585fa0SNadav Amit  * @tsk: the task_struct with which the new mm will be associated.
132413585fa0SNadav Amit  * @oldmm: the mm to duplicate.
132513585fa0SNadav Amit  *
132613585fa0SNadav Amit  * Allocates a new mm structure and duplicates the provided @oldmm structure
132713585fa0SNadav Amit  * content into it.
132813585fa0SNadav Amit  *
132913585fa0SNadav Amit  * Return: the duplicated mm or NULL on failure.
1330a0a7ec30SJANAK DESAI  */
133113585fa0SNadav Amit static struct mm_struct *dup_mm(struct task_struct *tsk,
133213585fa0SNadav Amit 				struct mm_struct *oldmm)
1333a0a7ec30SJANAK DESAI {
133413585fa0SNadav Amit 	struct mm_struct *mm;
1335a0a7ec30SJANAK DESAI 	int err;
1336a0a7ec30SJANAK DESAI 
1337a0a7ec30SJANAK DESAI 	mm = allocate_mm();
1338a0a7ec30SJANAK DESAI 	if (!mm)
1339a0a7ec30SJANAK DESAI 		goto fail_nomem;
1340a0a7ec30SJANAK DESAI 
1341a0a7ec30SJANAK DESAI 	memcpy(mm, oldmm, sizeof(*mm));
1342a0a7ec30SJANAK DESAI 
1343bfedb589SEric W. Biederman 	if (!mm_init(mm, tsk, mm->user_ns))
1344a0a7ec30SJANAK DESAI 		goto fail_nomem;
1345a0a7ec30SJANAK DESAI 
1346a0a7ec30SJANAK DESAI 	err = dup_mmap(mm, oldmm);
1347a0a7ec30SJANAK DESAI 	if (err)
1348a0a7ec30SJANAK DESAI 		goto free_pt;
1349a0a7ec30SJANAK DESAI 
1350a0a7ec30SJANAK DESAI 	mm->hiwater_rss = get_mm_rss(mm);
1351a0a7ec30SJANAK DESAI 	mm->hiwater_vm = mm->total_vm;
1352a0a7ec30SJANAK DESAI 
1353801460d0SHiroshi Shimamoto 	if (mm->binfmt && !try_module_get(mm->binfmt->module))
1354801460d0SHiroshi Shimamoto 		goto free_pt;
1355801460d0SHiroshi Shimamoto 
1356a0a7ec30SJANAK DESAI 	return mm;
1357a0a7ec30SJANAK DESAI 
1358a0a7ec30SJANAK DESAI free_pt:
1359801460d0SHiroshi Shimamoto 	/* don't put binfmt in mmput, we haven't got module yet */
1360801460d0SHiroshi Shimamoto 	mm->binfmt = NULL;
1361c3f3ce04SAndrea Arcangeli 	mm_init_owner(mm, NULL);
1362a0a7ec30SJANAK DESAI 	mmput(mm);
1363a0a7ec30SJANAK DESAI 
1364a0a7ec30SJANAK DESAI fail_nomem:
1365a0a7ec30SJANAK DESAI 	return NULL;
1366a0a7ec30SJANAK DESAI }
1367a0a7ec30SJANAK DESAI 
13681da177e4SLinus Torvalds static int copy_mm(unsigned long clone_flags, struct task_struct *tsk)
13691da177e4SLinus Torvalds {
13701da177e4SLinus Torvalds 	struct mm_struct *mm, *oldmm;
13711da177e4SLinus Torvalds 	int retval;
13721da177e4SLinus Torvalds 
13731da177e4SLinus Torvalds 	tsk->min_flt = tsk->maj_flt = 0;
13741da177e4SLinus Torvalds 	tsk->nvcsw = tsk->nivcsw = 0;
137517406b82SMandeep Singh Baines #ifdef CONFIG_DETECT_HUNG_TASK
137617406b82SMandeep Singh Baines 	tsk->last_switch_count = tsk->nvcsw + tsk->nivcsw;
1377a2e51445SDmitry Vyukov 	tsk->last_switch_time = 0;
137817406b82SMandeep Singh Baines #endif
13791da177e4SLinus Torvalds 
13801da177e4SLinus Torvalds 	tsk->mm = NULL;
13811da177e4SLinus Torvalds 	tsk->active_mm = NULL;
13821da177e4SLinus Torvalds 
13831da177e4SLinus Torvalds 	/*
13841da177e4SLinus Torvalds 	 * Are we cloning a kernel thread?
13851da177e4SLinus Torvalds 	 *
13861da177e4SLinus Torvalds 	 * We need to steal a active VM for that..
13871da177e4SLinus Torvalds 	 */
13881da177e4SLinus Torvalds 	oldmm = current->mm;
13891da177e4SLinus Torvalds 	if (!oldmm)
13901da177e4SLinus Torvalds 		return 0;
13911da177e4SLinus Torvalds 
1392615d6e87SDavidlohr Bueso 	/* initialize the new vmacache entries */
1393615d6e87SDavidlohr Bueso 	vmacache_flush(tsk);
1394615d6e87SDavidlohr Bueso 
13951da177e4SLinus Torvalds 	if (clone_flags & CLONE_VM) {
13963fce371bSVegard Nossum 		mmget(oldmm);
13971da177e4SLinus Torvalds 		mm = oldmm;
13981da177e4SLinus Torvalds 		goto good_mm;
13991da177e4SLinus Torvalds 	}
14001da177e4SLinus Torvalds 
14011da177e4SLinus Torvalds 	retval = -ENOMEM;
140213585fa0SNadav Amit 	mm = dup_mm(tsk, current->mm);
14031da177e4SLinus Torvalds 	if (!mm)
14041da177e4SLinus Torvalds 		goto fail_nomem;
14051da177e4SLinus Torvalds 
14061da177e4SLinus Torvalds good_mm:
14071da177e4SLinus Torvalds 	tsk->mm = mm;
14081da177e4SLinus Torvalds 	tsk->active_mm = mm;
14091da177e4SLinus Torvalds 	return 0;
14101da177e4SLinus Torvalds 
14111da177e4SLinus Torvalds fail_nomem:
14121da177e4SLinus Torvalds 	return retval;
14131da177e4SLinus Torvalds }
14141da177e4SLinus Torvalds 
1415a39bc516SAlexey Dobriyan static int copy_fs(unsigned long clone_flags, struct task_struct *tsk)
14161da177e4SLinus Torvalds {
1417498052bbSAl Viro 	struct fs_struct *fs = current->fs;
14181da177e4SLinus Torvalds 	if (clone_flags & CLONE_FS) {
1419498052bbSAl Viro 		/* tsk->fs is already what we want */
14202a4419b5SNick Piggin 		spin_lock(&fs->lock);
1421498052bbSAl Viro 		if (fs->in_exec) {
14222a4419b5SNick Piggin 			spin_unlock(&fs->lock);
1423498052bbSAl Viro 			return -EAGAIN;
1424498052bbSAl Viro 		}
1425498052bbSAl Viro 		fs->users++;
14262a4419b5SNick Piggin 		spin_unlock(&fs->lock);
14271da177e4SLinus Torvalds 		return 0;
14281da177e4SLinus Torvalds 	}
1429498052bbSAl Viro 	tsk->fs = copy_fs_struct(fs);
14301da177e4SLinus Torvalds 	if (!tsk->fs)
14311da177e4SLinus Torvalds 		return -ENOMEM;
14321da177e4SLinus Torvalds 	return 0;
14331da177e4SLinus Torvalds }
14341da177e4SLinus Torvalds 
1435a016f338SJANAK DESAI static int copy_files(unsigned long clone_flags, struct task_struct *tsk)
1436a016f338SJANAK DESAI {
1437a016f338SJANAK DESAI 	struct files_struct *oldf, *newf;
1438a016f338SJANAK DESAI 	int error = 0;
1439a016f338SJANAK DESAI 
1440a016f338SJANAK DESAI 	/*
1441a016f338SJANAK DESAI 	 * A background process may not have any files ...
1442a016f338SJANAK DESAI 	 */
1443a016f338SJANAK DESAI 	oldf = current->files;
1444a016f338SJANAK DESAI 	if (!oldf)
1445a016f338SJANAK DESAI 		goto out;
1446a016f338SJANAK DESAI 
1447a016f338SJANAK DESAI 	if (clone_flags & CLONE_FILES) {
1448a016f338SJANAK DESAI 		atomic_inc(&oldf->count);
1449a016f338SJANAK DESAI 		goto out;
1450a016f338SJANAK DESAI 	}
1451a016f338SJANAK DESAI 
1452a016f338SJANAK DESAI 	newf = dup_fd(oldf, &error);
1453a016f338SJANAK DESAI 	if (!newf)
1454a016f338SJANAK DESAI 		goto out;
1455a016f338SJANAK DESAI 
1456a016f338SJANAK DESAI 	tsk->files = newf;
1457a016f338SJANAK DESAI 	error = 0;
1458a016f338SJANAK DESAI out:
1459a016f338SJANAK DESAI 	return error;
1460a016f338SJANAK DESAI }
1461a016f338SJANAK DESAI 
1462fadad878SJens Axboe static int copy_io(unsigned long clone_flags, struct task_struct *tsk)
1463fd0928dfSJens Axboe {
1464fd0928dfSJens Axboe #ifdef CONFIG_BLOCK
1465fd0928dfSJens Axboe 	struct io_context *ioc = current->io_context;
14666e736be7STejun Heo 	struct io_context *new_ioc;
1467fd0928dfSJens Axboe 
1468fd0928dfSJens Axboe 	if (!ioc)
1469fd0928dfSJens Axboe 		return 0;
1470fadad878SJens Axboe 	/*
1471fadad878SJens Axboe 	 * Share io context with parent, if CLONE_IO is set
1472fadad878SJens Axboe 	 */
1473fadad878SJens Axboe 	if (clone_flags & CLONE_IO) {
14743d48749dSTejun Heo 		ioc_task_link(ioc);
14753d48749dSTejun Heo 		tsk->io_context = ioc;
1476fadad878SJens Axboe 	} else if (ioprio_valid(ioc->ioprio)) {
14776e736be7STejun Heo 		new_ioc = get_task_io_context(tsk, GFP_KERNEL, NUMA_NO_NODE);
14786e736be7STejun Heo 		if (unlikely(!new_ioc))
1479fd0928dfSJens Axboe 			return -ENOMEM;
1480fd0928dfSJens Axboe 
14816e736be7STejun Heo 		new_ioc->ioprio = ioc->ioprio;
148211a3122fSTejun Heo 		put_io_context(new_ioc);
1483fd0928dfSJens Axboe 	}
1484fd0928dfSJens Axboe #endif
1485fd0928dfSJens Axboe 	return 0;
1486fd0928dfSJens Axboe }
1487fd0928dfSJens Axboe 
1488a39bc516SAlexey Dobriyan static int copy_sighand(unsigned long clone_flags, struct task_struct *tsk)
14891da177e4SLinus Torvalds {
14901da177e4SLinus Torvalds 	struct sighand_struct *sig;
14911da177e4SLinus Torvalds 
149260348802SZhaolei 	if (clone_flags & CLONE_SIGHAND) {
1493d036bda7SElena Reshetova 		refcount_inc(&current->sighand->count);
14941da177e4SLinus Torvalds 		return 0;
14951da177e4SLinus Torvalds 	}
14961da177e4SLinus Torvalds 	sig = kmem_cache_alloc(sighand_cachep, GFP_KERNEL);
1497e56d0903SIngo Molnar 	rcu_assign_pointer(tsk->sighand, sig);
14981da177e4SLinus Torvalds 	if (!sig)
14991da177e4SLinus Torvalds 		return -ENOMEM;
15009d7fb042SPeter Zijlstra 
1501d036bda7SElena Reshetova 	refcount_set(&sig->count, 1);
150206e62a46SJann Horn 	spin_lock_irq(&current->sighand->siglock);
15031da177e4SLinus Torvalds 	memcpy(sig->action, current->sighand->action, sizeof(sig->action));
150406e62a46SJann Horn 	spin_unlock_irq(&current->sighand->siglock);
15051da177e4SLinus Torvalds 	return 0;
15061da177e4SLinus Torvalds }
15071da177e4SLinus Torvalds 
1508a7e5328aSOleg Nesterov void __cleanup_sighand(struct sighand_struct *sighand)
1509c81addc9SOleg Nesterov {
1510d036bda7SElena Reshetova 	if (refcount_dec_and_test(&sighand->count)) {
1511d80e731eSOleg Nesterov 		signalfd_cleanup(sighand);
1512392809b2SOleg Nesterov 		/*
15135f0d5a3aSPaul E. McKenney 		 * sighand_cachep is SLAB_TYPESAFE_BY_RCU so we can free it
1514392809b2SOleg Nesterov 		 * without an RCU grace period, see __lock_task_sighand().
1515392809b2SOleg Nesterov 		 */
1516c81addc9SOleg Nesterov 		kmem_cache_free(sighand_cachep, sighand);
1517c81addc9SOleg Nesterov 	}
1518d80e731eSOleg Nesterov }
1519c81addc9SOleg Nesterov 
1520b18b6a9cSNicolas Pitre #ifdef CONFIG_POSIX_TIMERS
1521f06febc9SFrank Mayhar /*
1522f06febc9SFrank Mayhar  * Initialize POSIX timer handling for a thread group.
1523f06febc9SFrank Mayhar  */
1524f06febc9SFrank Mayhar static void posix_cpu_timers_init_group(struct signal_struct *sig)
1525f06febc9SFrank Mayhar {
152678d7d407SJiri Slaby 	unsigned long cpu_limit;
152778d7d407SJiri Slaby 
1528316c1608SJason Low 	cpu_limit = READ_ONCE(sig->rlim[RLIMIT_CPU].rlim_cur);
152978d7d407SJiri Slaby 	if (cpu_limit != RLIM_INFINITY) {
1530ebd7e7fcSFrederic Weisbecker 		sig->cputime_expires.prof_exp = cpu_limit * NSEC_PER_SEC;
1531d5c373ebSJason Low 		sig->cputimer.running = true;
15326279a751SOleg Nesterov 	}
15336279a751SOleg Nesterov 
1534f06febc9SFrank Mayhar 	/* The timer lists. */
1535f06febc9SFrank Mayhar 	INIT_LIST_HEAD(&sig->cpu_timers[0]);
1536f06febc9SFrank Mayhar 	INIT_LIST_HEAD(&sig->cpu_timers[1]);
1537f06febc9SFrank Mayhar 	INIT_LIST_HEAD(&sig->cpu_timers[2]);
1538f06febc9SFrank Mayhar }
1539b18b6a9cSNicolas Pitre #else
1540b18b6a9cSNicolas Pitre static inline void posix_cpu_timers_init_group(struct signal_struct *sig) { }
1541b18b6a9cSNicolas Pitre #endif
1542f06febc9SFrank Mayhar 
1543a39bc516SAlexey Dobriyan static int copy_signal(unsigned long clone_flags, struct task_struct *tsk)
15441da177e4SLinus Torvalds {
15451da177e4SLinus Torvalds 	struct signal_struct *sig;
15461da177e4SLinus Torvalds 
15474ab6c083SOleg Nesterov 	if (clone_flags & CLONE_THREAD)
1548490dea45SPeter Zijlstra 		return 0;
15496279a751SOleg Nesterov 
1550a56704efSVeaceslav Falico 	sig = kmem_cache_zalloc(signal_cachep, GFP_KERNEL);
15511da177e4SLinus Torvalds 	tsk->signal = sig;
15521da177e4SLinus Torvalds 	if (!sig)
15531da177e4SLinus Torvalds 		return -ENOMEM;
15541da177e4SLinus Torvalds 
1555b3ac022cSOleg Nesterov 	sig->nr_threads = 1;
15561da177e4SLinus Torvalds 	atomic_set(&sig->live, 1);
155760d4de3fSElena Reshetova 	refcount_set(&sig->sigcnt, 1);
15580c740d0aSOleg Nesterov 
15590c740d0aSOleg Nesterov 	/* list_add(thread_node, thread_head) without INIT_LIST_HEAD() */
15600c740d0aSOleg Nesterov 	sig->thread_head = (struct list_head)LIST_HEAD_INIT(tsk->thread_node);
15610c740d0aSOleg Nesterov 	tsk->thread_node = (struct list_head)LIST_HEAD_INIT(sig->thread_head);
15620c740d0aSOleg Nesterov 
15631da177e4SLinus Torvalds 	init_waitqueue_head(&sig->wait_chldexit);
1564db51aeccSOleg Nesterov 	sig->curr_target = tsk;
15651da177e4SLinus Torvalds 	init_sigpending(&sig->shared_pending);
1566c3ad2c3bSEric W. Biederman 	INIT_HLIST_HEAD(&sig->multiprocess);
1567e78c3496SRik van Riel 	seqlock_init(&sig->stats_lock);
15689d7fb042SPeter Zijlstra 	prev_cputime_init(&sig->prev_cputime);
15691da177e4SLinus Torvalds 
1570baa73d9eSNicolas Pitre #ifdef CONFIG_POSIX_TIMERS
1571b18b6a9cSNicolas Pitre 	INIT_LIST_HEAD(&sig->posix_timers);
1572c9cb2e3dSThomas Gleixner 	hrtimer_init(&sig->real_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
15731da177e4SLinus Torvalds 	sig->real_timer.function = it_real_fn;
1574baa73d9eSNicolas Pitre #endif
15751da177e4SLinus Torvalds 
15761da177e4SLinus Torvalds 	task_lock(current->group_leader);
15771da177e4SLinus Torvalds 	memcpy(sig->rlim, current->signal->rlim, sizeof sig->rlim);
15781da177e4SLinus Torvalds 	task_unlock(current->group_leader);
15791da177e4SLinus Torvalds 
15806279a751SOleg Nesterov 	posix_cpu_timers_init_group(sig);
15816279a751SOleg Nesterov 
1582522ed776SMiloslav Trmac 	tty_audit_fork(sig);
15835091faa4SMike Galbraith 	sched_autogroup_fork(sig);
1584522ed776SMiloslav Trmac 
1585a63d83f4SDavid Rientjes 	sig->oom_score_adj = current->signal->oom_score_adj;
1586dabb16f6SMandeep Singh Baines 	sig->oom_score_adj_min = current->signal->oom_score_adj_min;
158728b83c51SKOSAKI Motohiro 
15889b1bf12dSKOSAKI Motohiro 	mutex_init(&sig->cred_guard_mutex);
15899b1bf12dSKOSAKI Motohiro 
15901da177e4SLinus Torvalds 	return 0;
15911da177e4SLinus Torvalds }
15921da177e4SLinus Torvalds 
1593dbd95212SKees Cook static void copy_seccomp(struct task_struct *p)
1594dbd95212SKees Cook {
1595dbd95212SKees Cook #ifdef CONFIG_SECCOMP
1596dbd95212SKees Cook 	/*
1597dbd95212SKees Cook 	 * Must be called with sighand->lock held, which is common to
1598dbd95212SKees Cook 	 * all threads in the group. Holding cred_guard_mutex is not
1599dbd95212SKees Cook 	 * needed because this new task is not yet running and cannot
1600dbd95212SKees Cook 	 * be racing exec.
1601dbd95212SKees Cook 	 */
160269f6a34bSGuenter Roeck 	assert_spin_locked(&current->sighand->siglock);
1603dbd95212SKees Cook 
1604dbd95212SKees Cook 	/* Ref-count the new filter user, and assign it. */
1605dbd95212SKees Cook 	get_seccomp_filter(current);
1606dbd95212SKees Cook 	p->seccomp = current->seccomp;
1607dbd95212SKees Cook 
1608dbd95212SKees Cook 	/*
1609dbd95212SKees Cook 	 * Explicitly enable no_new_privs here in case it got set
1610dbd95212SKees Cook 	 * between the task_struct being duplicated and holding the
1611dbd95212SKees Cook 	 * sighand lock. The seccomp state and nnp must be in sync.
1612dbd95212SKees Cook 	 */
1613dbd95212SKees Cook 	if (task_no_new_privs(current))
1614dbd95212SKees Cook 		task_set_no_new_privs(p);
1615dbd95212SKees Cook 
1616dbd95212SKees Cook 	/*
1617dbd95212SKees Cook 	 * If the parent gained a seccomp mode after copying thread
1618dbd95212SKees Cook 	 * flags and between before we held the sighand lock, we have
1619dbd95212SKees Cook 	 * to manually enable the seccomp thread flag here.
1620dbd95212SKees Cook 	 */
1621dbd95212SKees Cook 	if (p->seccomp.mode != SECCOMP_MODE_DISABLED)
1622dbd95212SKees Cook 		set_tsk_thread_flag(p, TIF_SECCOMP);
1623dbd95212SKees Cook #endif
1624dbd95212SKees Cook }
1625dbd95212SKees Cook 
162617da2bd9SHeiko Carstens SYSCALL_DEFINE1(set_tid_address, int __user *, tidptr)
16271da177e4SLinus Torvalds {
16281da177e4SLinus Torvalds 	current->clear_child_tid = tidptr;
16291da177e4SLinus Torvalds 
1630b488893aSPavel Emelyanov 	return task_pid_vnr(current);
16311da177e4SLinus Torvalds }
16321da177e4SLinus Torvalds 
1633a39bc516SAlexey Dobriyan static void rt_mutex_init_task(struct task_struct *p)
163423f78d4aSIngo Molnar {
16351d615482SThomas Gleixner 	raw_spin_lock_init(&p->pi_lock);
1636e29e175bSZilvinas Valinskas #ifdef CONFIG_RT_MUTEXES
1637a23ba907SDavidlohr Bueso 	p->pi_waiters = RB_ROOT_CACHED;
1638e96a7705SXunlei Pang 	p->pi_top_task = NULL;
163923f78d4aSIngo Molnar 	p->pi_blocked_on = NULL;
164023f78d4aSIngo Molnar #endif
164123f78d4aSIngo Molnar }
164223f78d4aSIngo Molnar 
1643b18b6a9cSNicolas Pitre #ifdef CONFIG_POSIX_TIMERS
16441da177e4SLinus Torvalds /*
1645f06febc9SFrank Mayhar  * Initialize POSIX timer handling for a single task.
1646f06febc9SFrank Mayhar  */
1647f06febc9SFrank Mayhar static void posix_cpu_timers_init(struct task_struct *tsk)
1648f06febc9SFrank Mayhar {
164964861634SMartin Schwidefsky 	tsk->cputime_expires.prof_exp = 0;
165064861634SMartin Schwidefsky 	tsk->cputime_expires.virt_exp = 0;
1651f06febc9SFrank Mayhar 	tsk->cputime_expires.sched_exp = 0;
1652f06febc9SFrank Mayhar 	INIT_LIST_HEAD(&tsk->cpu_timers[0]);
1653f06febc9SFrank Mayhar 	INIT_LIST_HEAD(&tsk->cpu_timers[1]);
1654f06febc9SFrank Mayhar 	INIT_LIST_HEAD(&tsk->cpu_timers[2]);
1655f06febc9SFrank Mayhar }
1656b18b6a9cSNicolas Pitre #else
1657b18b6a9cSNicolas Pitre static inline void posix_cpu_timers_init(struct task_struct *tsk) { }
1658b18b6a9cSNicolas Pitre #endif
1659f06febc9SFrank Mayhar 
16602c470475SEric W. Biederman static inline void init_task_pid_links(struct task_struct *task)
16612c470475SEric W. Biederman {
16622c470475SEric W. Biederman 	enum pid_type type;
16632c470475SEric W. Biederman 
16642c470475SEric W. Biederman 	for (type = PIDTYPE_PID; type < PIDTYPE_MAX; ++type) {
16652c470475SEric W. Biederman 		INIT_HLIST_NODE(&task->pid_links[type]);
16662c470475SEric W. Biederman 	}
16672c470475SEric W. Biederman }
16682c470475SEric W. Biederman 
166981907739SOleg Nesterov static inline void
167081907739SOleg Nesterov init_task_pid(struct task_struct *task, enum pid_type type, struct pid *pid)
167181907739SOleg Nesterov {
16722c470475SEric W. Biederman 	if (type == PIDTYPE_PID)
16732c470475SEric W. Biederman 		task->thread_pid = pid;
16742c470475SEric W. Biederman 	else
16752c470475SEric W. Biederman 		task->signal->pids[type] = pid;
167681907739SOleg Nesterov }
167781907739SOleg Nesterov 
16786bfbaa51SIngo Molnar static inline void rcu_copy_process(struct task_struct *p)
16796bfbaa51SIngo Molnar {
16806bfbaa51SIngo Molnar #ifdef CONFIG_PREEMPT_RCU
16816bfbaa51SIngo Molnar 	p->rcu_read_lock_nesting = 0;
16826bfbaa51SIngo Molnar 	p->rcu_read_unlock_special.s = 0;
16836bfbaa51SIngo Molnar 	p->rcu_blocked_node = NULL;
16846bfbaa51SIngo Molnar 	INIT_LIST_HEAD(&p->rcu_node_entry);
16856bfbaa51SIngo Molnar #endif /* #ifdef CONFIG_PREEMPT_RCU */
16866bfbaa51SIngo Molnar #ifdef CONFIG_TASKS_RCU
16876bfbaa51SIngo Molnar 	p->rcu_tasks_holdout = false;
16886bfbaa51SIngo Molnar 	INIT_LIST_HEAD(&p->rcu_tasks_holdout_list);
16896bfbaa51SIngo Molnar 	p->rcu_tasks_idle_cpu = -1;
16906bfbaa51SIngo Molnar #endif /* #ifdef CONFIG_TASKS_RCU */
16916bfbaa51SIngo Molnar }
16926bfbaa51SIngo Molnar 
1693b3e58382SChristian Brauner static int pidfd_release(struct inode *inode, struct file *file)
1694b3e58382SChristian Brauner {
1695b3e58382SChristian Brauner 	struct pid *pid = file->private_data;
1696b3e58382SChristian Brauner 
1697b3e58382SChristian Brauner 	file->private_data = NULL;
1698b3e58382SChristian Brauner 	put_pid(pid);
1699b3e58382SChristian Brauner 	return 0;
1700b3e58382SChristian Brauner }
1701b3e58382SChristian Brauner 
1702b3e58382SChristian Brauner #ifdef CONFIG_PROC_FS
1703b3e58382SChristian Brauner static void pidfd_show_fdinfo(struct seq_file *m, struct file *f)
1704b3e58382SChristian Brauner {
1705b3e58382SChristian Brauner 	struct pid_namespace *ns = proc_pid_ns(file_inode(m->file));
1706b3e58382SChristian Brauner 	struct pid *pid = f->private_data;
1707b3e58382SChristian Brauner 
1708b3e58382SChristian Brauner 	seq_put_decimal_ull(m, "Pid:\t", pid_nr_ns(pid, ns));
1709b3e58382SChristian Brauner 	seq_putc(m, '\n');
1710b3e58382SChristian Brauner }
1711b3e58382SChristian Brauner #endif
1712b3e58382SChristian Brauner 
1713b53b0b9dSJoel Fernandes (Google) /*
1714b53b0b9dSJoel Fernandes (Google)  * Poll support for process exit notification.
1715b53b0b9dSJoel Fernandes (Google)  */
1716b53b0b9dSJoel Fernandes (Google) static unsigned int pidfd_poll(struct file *file, struct poll_table_struct *pts)
1717b53b0b9dSJoel Fernandes (Google) {
1718b53b0b9dSJoel Fernandes (Google) 	struct task_struct *task;
1719b53b0b9dSJoel Fernandes (Google) 	struct pid *pid = file->private_data;
1720b53b0b9dSJoel Fernandes (Google) 	int poll_flags = 0;
1721b53b0b9dSJoel Fernandes (Google) 
1722b53b0b9dSJoel Fernandes (Google) 	poll_wait(file, &pid->wait_pidfd, pts);
1723b53b0b9dSJoel Fernandes (Google) 
1724b53b0b9dSJoel Fernandes (Google) 	rcu_read_lock();
1725b53b0b9dSJoel Fernandes (Google) 	task = pid_task(pid, PIDTYPE_PID);
1726b53b0b9dSJoel Fernandes (Google) 	/*
1727b53b0b9dSJoel Fernandes (Google) 	 * Inform pollers only when the whole thread group exits.
1728b53b0b9dSJoel Fernandes (Google) 	 * If the thread group leader exits before all other threads in the
1729b53b0b9dSJoel Fernandes (Google) 	 * group, then poll(2) should block, similar to the wait(2) family.
1730b53b0b9dSJoel Fernandes (Google) 	 */
1731b53b0b9dSJoel Fernandes (Google) 	if (!task || (task->exit_state && thread_group_empty(task)))
1732b53b0b9dSJoel Fernandes (Google) 		poll_flags = POLLIN | POLLRDNORM;
1733b53b0b9dSJoel Fernandes (Google) 	rcu_read_unlock();
1734b53b0b9dSJoel Fernandes (Google) 
1735b53b0b9dSJoel Fernandes (Google) 	return poll_flags;
1736b53b0b9dSJoel Fernandes (Google) }
1737b53b0b9dSJoel Fernandes (Google) 
1738b3e58382SChristian Brauner const struct file_operations pidfd_fops = {
1739b3e58382SChristian Brauner 	.release = pidfd_release,
1740b53b0b9dSJoel Fernandes (Google) 	.poll = pidfd_poll,
1741b3e58382SChristian Brauner #ifdef CONFIG_PROC_FS
1742b3e58382SChristian Brauner 	.show_fdinfo = pidfd_show_fdinfo,
1743b3e58382SChristian Brauner #endif
1744b3e58382SChristian Brauner };
1745b3e58382SChristian Brauner 
1746c3f3ce04SAndrea Arcangeli static void __delayed_free_task(struct rcu_head *rhp)
1747c3f3ce04SAndrea Arcangeli {
1748c3f3ce04SAndrea Arcangeli 	struct task_struct *tsk = container_of(rhp, struct task_struct, rcu);
1749c3f3ce04SAndrea Arcangeli 
1750c3f3ce04SAndrea Arcangeli 	free_task(tsk);
1751c3f3ce04SAndrea Arcangeli }
1752c3f3ce04SAndrea Arcangeli 
1753c3f3ce04SAndrea Arcangeli static __always_inline void delayed_free_task(struct task_struct *tsk)
1754c3f3ce04SAndrea Arcangeli {
1755c3f3ce04SAndrea Arcangeli 	if (IS_ENABLED(CONFIG_MEMCG))
1756c3f3ce04SAndrea Arcangeli 		call_rcu(&tsk->rcu, __delayed_free_task);
1757c3f3ce04SAndrea Arcangeli 	else
1758c3f3ce04SAndrea Arcangeli 		free_task(tsk);
1759c3f3ce04SAndrea Arcangeli }
1760c3f3ce04SAndrea Arcangeli 
1761f06febc9SFrank Mayhar /*
17621da177e4SLinus Torvalds  * This creates a new process as a copy of the old one,
17631da177e4SLinus Torvalds  * but does not actually start it yet.
17641da177e4SLinus Torvalds  *
17651da177e4SLinus Torvalds  * It copies the registers, and all the appropriate
17661da177e4SLinus Torvalds  * parts of the process environment (as per the clone
17671da177e4SLinus Torvalds  * flags). The actual kick-off is left to the caller.
17681da177e4SLinus Torvalds  */
17690766f788SEmese Revfy static __latent_entropy struct task_struct *copy_process(
177009a05394SRoland McGrath 					struct pid *pid,
17713033f14aSJosh Triplett 					int trace,
17727f192e3cSChristian Brauner 					int node,
17737f192e3cSChristian Brauner 					struct kernel_clone_args *args)
17741da177e4SLinus Torvalds {
1775b3e58382SChristian Brauner 	int pidfd = -1, retval;
1776a24efe62SMariusz Kozlowski 	struct task_struct *p;
1777c3ad2c3bSEric W. Biederman 	struct multiprocess_signals delayed;
17786fd2fe49SAl Viro 	struct file *pidfile = NULL;
17797f192e3cSChristian Brauner 	u64 clone_flags = args->flags;
17801da177e4SLinus Torvalds 
1781667b6094SMarcos Paulo de Souza 	/*
1782667b6094SMarcos Paulo de Souza 	 * Don't allow sharing the root directory with processes in a different
1783667b6094SMarcos Paulo de Souza 	 * namespace
1784667b6094SMarcos Paulo de Souza 	 */
17851da177e4SLinus Torvalds 	if ((clone_flags & (CLONE_NEWNS|CLONE_FS)) == (CLONE_NEWNS|CLONE_FS))
17861da177e4SLinus Torvalds 		return ERR_PTR(-EINVAL);
17871da177e4SLinus Torvalds 
1788e66eded8SEric W. Biederman 	if ((clone_flags & (CLONE_NEWUSER|CLONE_FS)) == (CLONE_NEWUSER|CLONE_FS))
1789e66eded8SEric W. Biederman 		return ERR_PTR(-EINVAL);
1790e66eded8SEric W. Biederman 
17911da177e4SLinus Torvalds 	/*
17921da177e4SLinus Torvalds 	 * Thread groups must share signals as well, and detached threads
17931da177e4SLinus Torvalds 	 * can only be started up within the thread group.
17941da177e4SLinus Torvalds 	 */
17951da177e4SLinus Torvalds 	if ((clone_flags & CLONE_THREAD) && !(clone_flags & CLONE_SIGHAND))
17961da177e4SLinus Torvalds 		return ERR_PTR(-EINVAL);
17971da177e4SLinus Torvalds 
17981da177e4SLinus Torvalds 	/*
17991da177e4SLinus Torvalds 	 * Shared signal handlers imply shared VM. By way of the above,
18001da177e4SLinus Torvalds 	 * thread groups also imply shared VM. Blocking this case allows
18011da177e4SLinus Torvalds 	 * for various simplifications in other code.
18021da177e4SLinus Torvalds 	 */
18031da177e4SLinus Torvalds 	if ((clone_flags & CLONE_SIGHAND) && !(clone_flags & CLONE_VM))
18041da177e4SLinus Torvalds 		return ERR_PTR(-EINVAL);
18051da177e4SLinus Torvalds 
1806123be07bSSukadev Bhattiprolu 	/*
1807123be07bSSukadev Bhattiprolu 	 * Siblings of global init remain as zombies on exit since they are
1808123be07bSSukadev Bhattiprolu 	 * not reaped by their parent (swapper). To solve this and to avoid
1809123be07bSSukadev Bhattiprolu 	 * multi-rooted process trees, prevent global and container-inits
1810123be07bSSukadev Bhattiprolu 	 * from creating siblings.
1811123be07bSSukadev Bhattiprolu 	 */
1812123be07bSSukadev Bhattiprolu 	if ((clone_flags & CLONE_PARENT) &&
1813123be07bSSukadev Bhattiprolu 				current->signal->flags & SIGNAL_UNKILLABLE)
1814123be07bSSukadev Bhattiprolu 		return ERR_PTR(-EINVAL);
1815123be07bSSukadev Bhattiprolu 
18168382fcacSEric W. Biederman 	/*
181740a0d32dSOleg Nesterov 	 * If the new process will be in a different pid or user namespace
1818faf00da5SEric W. Biederman 	 * do not allow it to share a thread group with the forking task.
18198382fcacSEric W. Biederman 	 */
1820faf00da5SEric W. Biederman 	if (clone_flags & CLONE_THREAD) {
182140a0d32dSOleg Nesterov 		if ((clone_flags & (CLONE_NEWUSER | CLONE_NEWPID)) ||
182240a0d32dSOleg Nesterov 		    (task_active_pid_ns(current) !=
1823c2b1df2eSAndy Lutomirski 				current->nsproxy->pid_ns_for_children))
18248382fcacSEric W. Biederman 			return ERR_PTR(-EINVAL);
182540a0d32dSOleg Nesterov 	}
18268382fcacSEric W. Biederman 
1827b3e58382SChristian Brauner 	if (clone_flags & CLONE_PIDFD) {
1828b3e58382SChristian Brauner 		/*
1829b3e58382SChristian Brauner 		 * - CLONE_DETACHED is blocked so that we can potentially
1830b3e58382SChristian Brauner 		 *   reuse it later for CLONE_PIDFD.
1831b3e58382SChristian Brauner 		 * - CLONE_THREAD is blocked until someone really needs it.
1832b3e58382SChristian Brauner 		 */
18337f192e3cSChristian Brauner 		if (clone_flags & (CLONE_DETACHED | CLONE_THREAD))
1834b3e58382SChristian Brauner 			return ERR_PTR(-EINVAL);
1835b3e58382SChristian Brauner 	}
1836b3e58382SChristian Brauner 
1837c3ad2c3bSEric W. Biederman 	/*
1838c3ad2c3bSEric W. Biederman 	 * Force any signals received before this point to be delivered
1839c3ad2c3bSEric W. Biederman 	 * before the fork happens.  Collect up signals sent to multiple
1840c3ad2c3bSEric W. Biederman 	 * processes that happen during the fork and delay them so that
1841c3ad2c3bSEric W. Biederman 	 * they appear to happen after the fork.
1842c3ad2c3bSEric W. Biederman 	 */
1843c3ad2c3bSEric W. Biederman 	sigemptyset(&delayed.signal);
1844c3ad2c3bSEric W. Biederman 	INIT_HLIST_NODE(&delayed.node);
1845c3ad2c3bSEric W. Biederman 
1846c3ad2c3bSEric W. Biederman 	spin_lock_irq(&current->sighand->siglock);
1847c3ad2c3bSEric W. Biederman 	if (!(clone_flags & CLONE_THREAD))
1848c3ad2c3bSEric W. Biederman 		hlist_add_head(&delayed.node, &current->signal->multiprocess);
1849c3ad2c3bSEric W. Biederman 	recalc_sigpending();
1850c3ad2c3bSEric W. Biederman 	spin_unlock_irq(&current->sighand->siglock);
1851c3ad2c3bSEric W. Biederman 	retval = -ERESTARTNOINTR;
1852c3ad2c3bSEric W. Biederman 	if (signal_pending(current))
1853c3ad2c3bSEric W. Biederman 		goto fork_out;
1854c3ad2c3bSEric W. Biederman 
18551da177e4SLinus Torvalds 	retval = -ENOMEM;
1856725fc629SAndi Kleen 	p = dup_task_struct(current, node);
18571da177e4SLinus Torvalds 	if (!p)
18581da177e4SLinus Torvalds 		goto fork_out;
18591da177e4SLinus Torvalds 
18604d6501dcSVegard Nossum 	/*
18614d6501dcSVegard Nossum 	 * This _must_ happen before we call free_task(), i.e. before we jump
18624d6501dcSVegard Nossum 	 * to any of the bad_fork_* labels. This is to avoid freeing
18634d6501dcSVegard Nossum 	 * p->set_child_tid which is (ab)used as a kthread's data pointer for
18644d6501dcSVegard Nossum 	 * kernel threads (PF_KTHREAD).
18654d6501dcSVegard Nossum 	 */
18667f192e3cSChristian Brauner 	p->set_child_tid = (clone_flags & CLONE_CHILD_SETTID) ? args->child_tid : NULL;
18674d6501dcSVegard Nossum 	/*
18684d6501dcSVegard Nossum 	 * Clear TID on mm_release()?
18694d6501dcSVegard Nossum 	 */
18707f192e3cSChristian Brauner 	p->clear_child_tid = (clone_flags & CLONE_CHILD_CLEARTID) ? args->child_tid : NULL;
18714d6501dcSVegard Nossum 
1872f7e8b616SSteven Rostedt 	ftrace_graph_init_task(p);
1873f7e8b616SSteven Rostedt 
1874bea493a0SPeter Zijlstra 	rt_mutex_init_task(p);
1875bea493a0SPeter Zijlstra 
1876d12c1a37SIngo Molnar #ifdef CONFIG_PROVE_LOCKING
1877de30a2b3SIngo Molnar 	DEBUG_LOCKS_WARN_ON(!p->hardirqs_enabled);
1878de30a2b3SIngo Molnar 	DEBUG_LOCKS_WARN_ON(!p->softirqs_enabled);
1879de30a2b3SIngo Molnar #endif
18801da177e4SLinus Torvalds 	retval = -EAGAIN;
18813b11a1deSDavid Howells 	if (atomic_read(&p->real_cred->user->processes) >=
188278d7d407SJiri Slaby 			task_rlimit(p, RLIMIT_NPROC)) {
1883b57922b6SEric Paris 		if (p->real_cred->user != INIT_USER &&
1884b57922b6SEric Paris 		    !capable(CAP_SYS_RESOURCE) && !capable(CAP_SYS_ADMIN))
18851da177e4SLinus Torvalds 			goto bad_fork_free;
18861da177e4SLinus Torvalds 	}
188772fa5997SVasiliy Kulikov 	current->flags &= ~PF_NPROC_EXCEEDED;
18881da177e4SLinus Torvalds 
1889f1752eecSDavid Howells 	retval = copy_creds(p, clone_flags);
1890f1752eecSDavid Howells 	if (retval < 0)
1891f1752eecSDavid Howells 		goto bad_fork_free;
18921da177e4SLinus Torvalds 
18931da177e4SLinus Torvalds 	/*
18941da177e4SLinus Torvalds 	 * If multiple threads are within copy_process(), then this check
18951da177e4SLinus Torvalds 	 * triggers too late. This doesn't hurt, the check is only there
18961da177e4SLinus Torvalds 	 * to stop root fork bombs.
18971da177e4SLinus Torvalds 	 */
189804ec93feSLi Zefan 	retval = -EAGAIN;
18991da177e4SLinus Torvalds 	if (nr_threads >= max_threads)
19001da177e4SLinus Torvalds 		goto bad_fork_cleanup_count;
19011da177e4SLinus Torvalds 
1902ca74e92bSShailabh Nagar 	delayacct_tsk_init(p);	/* Must remain after dup_task_struct() */
1903c1de45caSPeter Zijlstra 	p->flags &= ~(PF_SUPERPRIV | PF_WQ_WORKER | PF_IDLE);
1904514ddb44SDavid Rientjes 	p->flags |= PF_FORKNOEXEC;
19051da177e4SLinus Torvalds 	INIT_LIST_HEAD(&p->children);
19061da177e4SLinus Torvalds 	INIT_LIST_HEAD(&p->sibling);
1907f41d911fSPaul E. McKenney 	rcu_copy_process(p);
19081da177e4SLinus Torvalds 	p->vfork_done = NULL;
19091da177e4SLinus Torvalds 	spin_lock_init(&p->alloc_lock);
19101da177e4SLinus Torvalds 
19111da177e4SLinus Torvalds 	init_sigpending(&p->pending);
19121da177e4SLinus Torvalds 
191364861634SMartin Schwidefsky 	p->utime = p->stime = p->gtime = 0;
191440565b5aSStanislaw Gruszka #ifdef CONFIG_ARCH_HAS_SCALED_CPUTIME
191564861634SMartin Schwidefsky 	p->utimescaled = p->stimescaled = 0;
191640565b5aSStanislaw Gruszka #endif
19179d7fb042SPeter Zijlstra 	prev_cputime_init(&p->prev_cputime);
19189d7fb042SPeter Zijlstra 
19196a61671bSFrederic Weisbecker #ifdef CONFIG_VIRT_CPU_ACCOUNTING_GEN
1920bac5b6b6SFrederic Weisbecker 	seqcount_init(&p->vtime.seqcount);
1921bac5b6b6SFrederic Weisbecker 	p->vtime.starttime = 0;
1922bac5b6b6SFrederic Weisbecker 	p->vtime.state = VTIME_INACTIVE;
19236a61671bSFrederic Weisbecker #endif
19246a61671bSFrederic Weisbecker 
1925a3a2e76cSKAMEZAWA Hiroyuki #if defined(SPLIT_RSS_COUNTING)
1926a3a2e76cSKAMEZAWA Hiroyuki 	memset(&p->rss_stat, 0, sizeof(p->rss_stat));
1927a3a2e76cSKAMEZAWA Hiroyuki #endif
1928172ba844SBalbir Singh 
19296976675dSArjan van de Ven 	p->default_timer_slack_ns = current->timer_slack_ns;
19306976675dSArjan van de Ven 
1931eb414681SJohannes Weiner #ifdef CONFIG_PSI
1932eb414681SJohannes Weiner 	p->psi_flags = 0;
1933eb414681SJohannes Weiner #endif
1934eb414681SJohannes Weiner 
19355995477aSAndrea Righi 	task_io_accounting_init(&p->ioac);
19361da177e4SLinus Torvalds 	acct_clear_integrals(p);
19371da177e4SLinus Torvalds 
1938f06febc9SFrank Mayhar 	posix_cpu_timers_init(p);
19391da177e4SLinus Torvalds 
19401da177e4SLinus Torvalds 	p->io_context = NULL;
1941c0b0ae8aSRichard Guy Briggs 	audit_set_context(p, NULL);
1942b4f48b63SPaul Menage 	cgroup_fork(p);
19431da177e4SLinus Torvalds #ifdef CONFIG_NUMA
1944846a16bfSLee Schermerhorn 	p->mempolicy = mpol_dup(p->mempolicy);
19451da177e4SLinus Torvalds 	if (IS_ERR(p->mempolicy)) {
19461da177e4SLinus Torvalds 		retval = PTR_ERR(p->mempolicy);
19471da177e4SLinus Torvalds 		p->mempolicy = NULL;
1948e8604cb4SLi Zefan 		goto bad_fork_cleanup_threadgroup_lock;
19491da177e4SLinus Torvalds 	}
19501da177e4SLinus Torvalds #endif
1951778d3b0fSMichal Hocko #ifdef CONFIG_CPUSETS
1952778d3b0fSMichal Hocko 	p->cpuset_mem_spread_rotor = NUMA_NO_NODE;
1953778d3b0fSMichal Hocko 	p->cpuset_slab_spread_rotor = NUMA_NO_NODE;
1954cc9a6c87SMel Gorman 	seqcount_init(&p->mems_allowed_seq);
1955778d3b0fSMichal Hocko #endif
1956de30a2b3SIngo Molnar #ifdef CONFIG_TRACE_IRQFLAGS
1957de30a2b3SIngo Molnar 	p->irq_events = 0;
1958de30a2b3SIngo Molnar 	p->hardirqs_enabled = 0;
1959de30a2b3SIngo Molnar 	p->hardirq_enable_ip = 0;
1960de30a2b3SIngo Molnar 	p->hardirq_enable_event = 0;
1961de30a2b3SIngo Molnar 	p->hardirq_disable_ip = _THIS_IP_;
1962de30a2b3SIngo Molnar 	p->hardirq_disable_event = 0;
1963de30a2b3SIngo Molnar 	p->softirqs_enabled = 1;
1964de30a2b3SIngo Molnar 	p->softirq_enable_ip = _THIS_IP_;
1965de30a2b3SIngo Molnar 	p->softirq_enable_event = 0;
1966de30a2b3SIngo Molnar 	p->softirq_disable_ip = 0;
1967de30a2b3SIngo Molnar 	p->softirq_disable_event = 0;
1968de30a2b3SIngo Molnar 	p->hardirq_context = 0;
1969de30a2b3SIngo Molnar 	p->softirq_context = 0;
1970de30a2b3SIngo Molnar #endif
19718bcbde54SDavid Hildenbrand 
19728bcbde54SDavid Hildenbrand 	p->pagefault_disabled = 0;
19738bcbde54SDavid Hildenbrand 
1974fbb9ce95SIngo Molnar #ifdef CONFIG_LOCKDEP
1975b09be676SByungchul Park 	lockdep_init_task(p);
1976fbb9ce95SIngo Molnar #endif
19771da177e4SLinus Torvalds 
1978408894eeSIngo Molnar #ifdef CONFIG_DEBUG_MUTEXES
1979408894eeSIngo Molnar 	p->blocked_on = NULL; /* not blocked yet */
1980408894eeSIngo Molnar #endif
1981cafe5635SKent Overstreet #ifdef CONFIG_BCACHE
1982cafe5635SKent Overstreet 	p->sequential_io	= 0;
1983cafe5635SKent Overstreet 	p->sequential_io_avg	= 0;
1984cafe5635SKent Overstreet #endif
19850f481406SMarkus Metzger 
19863c90e6e9SSrivatsa Vaddagiri 	/* Perform scheduler related setup. Assign this task to a CPU. */
1987aab03e05SDario Faggioli 	retval = sched_fork(clone_flags, p);
1988aab03e05SDario Faggioli 	if (retval)
1989aab03e05SDario Faggioli 		goto bad_fork_cleanup_policy;
19906ab423e0SPeter Zijlstra 
1991cdd6c482SIngo Molnar 	retval = perf_event_init_task(p);
19926ab423e0SPeter Zijlstra 	if (retval)
19936ab423e0SPeter Zijlstra 		goto bad_fork_cleanup_policy;
1994fb0a685cSDaniel Rebelo de Oliveira 	retval = audit_alloc(p);
1995fb0a685cSDaniel Rebelo de Oliveira 	if (retval)
19966c72e350SPeter Zijlstra 		goto bad_fork_cleanup_perf;
19971da177e4SLinus Torvalds 	/* copy all the process information */
1998ab602f79SJack Miller 	shm_init_task(p);
1999e4e55b47STetsuo Handa 	retval = security_task_alloc(p, clone_flags);
2000fb0a685cSDaniel Rebelo de Oliveira 	if (retval)
20011da177e4SLinus Torvalds 		goto bad_fork_cleanup_audit;
2002e4e55b47STetsuo Handa 	retval = copy_semundo(clone_flags, p);
2003e4e55b47STetsuo Handa 	if (retval)
2004e4e55b47STetsuo Handa 		goto bad_fork_cleanup_security;
2005fb0a685cSDaniel Rebelo de Oliveira 	retval = copy_files(clone_flags, p);
2006fb0a685cSDaniel Rebelo de Oliveira 	if (retval)
20071da177e4SLinus Torvalds 		goto bad_fork_cleanup_semundo;
2008fb0a685cSDaniel Rebelo de Oliveira 	retval = copy_fs(clone_flags, p);
2009fb0a685cSDaniel Rebelo de Oliveira 	if (retval)
20101da177e4SLinus Torvalds 		goto bad_fork_cleanup_files;
2011fb0a685cSDaniel Rebelo de Oliveira 	retval = copy_sighand(clone_flags, p);
2012fb0a685cSDaniel Rebelo de Oliveira 	if (retval)
20131da177e4SLinus Torvalds 		goto bad_fork_cleanup_fs;
2014fb0a685cSDaniel Rebelo de Oliveira 	retval = copy_signal(clone_flags, p);
2015fb0a685cSDaniel Rebelo de Oliveira 	if (retval)
20161da177e4SLinus Torvalds 		goto bad_fork_cleanup_sighand;
2017fb0a685cSDaniel Rebelo de Oliveira 	retval = copy_mm(clone_flags, p);
2018fb0a685cSDaniel Rebelo de Oliveira 	if (retval)
20191da177e4SLinus Torvalds 		goto bad_fork_cleanup_signal;
2020fb0a685cSDaniel Rebelo de Oliveira 	retval = copy_namespaces(clone_flags, p);
2021fb0a685cSDaniel Rebelo de Oliveira 	if (retval)
2022d84f4f99SDavid Howells 		goto bad_fork_cleanup_mm;
2023fb0a685cSDaniel Rebelo de Oliveira 	retval = copy_io(clone_flags, p);
2024fb0a685cSDaniel Rebelo de Oliveira 	if (retval)
2025fd0928dfSJens Axboe 		goto bad_fork_cleanup_namespaces;
20267f192e3cSChristian Brauner 	retval = copy_thread_tls(clone_flags, args->stack, args->stack_size, p,
20277f192e3cSChristian Brauner 				 args->tls);
20281da177e4SLinus Torvalds 	if (retval)
2029fd0928dfSJens Axboe 		goto bad_fork_cleanup_io;
20301da177e4SLinus Torvalds 
2031afaef01cSAlexander Popov 	stackleak_task_init(p);
2032afaef01cSAlexander Popov 
2033425fb2b4SPavel Emelyanov 	if (pid != &init_struct_pid) {
2034c2b1df2eSAndy Lutomirski 		pid = alloc_pid(p->nsproxy->pid_ns_for_children);
203535f71bc0SMichal Hocko 		if (IS_ERR(pid)) {
203635f71bc0SMichal Hocko 			retval = PTR_ERR(pid);
20370740aa5fSJiri Slaby 			goto bad_fork_cleanup_thread;
2038425fb2b4SPavel Emelyanov 		}
203935f71bc0SMichal Hocko 	}
2040425fb2b4SPavel Emelyanov 
2041b3e58382SChristian Brauner 	/*
2042b3e58382SChristian Brauner 	 * This has to happen after we've potentially unshared the file
2043b3e58382SChristian Brauner 	 * descriptor table (so that the pidfd doesn't leak into the child
2044b3e58382SChristian Brauner 	 * if the fd table isn't shared).
2045b3e58382SChristian Brauner 	 */
2046b3e58382SChristian Brauner 	if (clone_flags & CLONE_PIDFD) {
20476fd2fe49SAl Viro 		retval = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
2048b3e58382SChristian Brauner 		if (retval < 0)
2049b3e58382SChristian Brauner 			goto bad_fork_free_pid;
2050b3e58382SChristian Brauner 
2051b3e58382SChristian Brauner 		pidfd = retval;
20526fd2fe49SAl Viro 
20536fd2fe49SAl Viro 		pidfile = anon_inode_getfile("[pidfd]", &pidfd_fops, pid,
20546fd2fe49SAl Viro 					      O_RDWR | O_CLOEXEC);
20556fd2fe49SAl Viro 		if (IS_ERR(pidfile)) {
20566fd2fe49SAl Viro 			put_unused_fd(pidfd);
205728dd29c0SChristian Brauner 			retval = PTR_ERR(pidfile);
20586fd2fe49SAl Viro 			goto bad_fork_free_pid;
20596fd2fe49SAl Viro 		}
20606fd2fe49SAl Viro 		get_pid(pid);	/* held by pidfile now */
20616fd2fe49SAl Viro 
20627f192e3cSChristian Brauner 		retval = put_user(pidfd, args->pidfd);
2063b3e58382SChristian Brauner 		if (retval)
2064b3e58382SChristian Brauner 			goto bad_fork_put_pidfd;
2065b3e58382SChristian Brauner 	}
2066b3e58382SChristian Brauner 
206773c10101SJens Axboe #ifdef CONFIG_BLOCK
206873c10101SJens Axboe 	p->plug = NULL;
206973c10101SJens Axboe #endif
207042b2dd0aSAlexey Dobriyan #ifdef CONFIG_FUTEX
20718f17d3a5SIngo Molnar 	p->robust_list = NULL;
20728f17d3a5SIngo Molnar #ifdef CONFIG_COMPAT
20738f17d3a5SIngo Molnar 	p->compat_robust_list = NULL;
20748f17d3a5SIngo Molnar #endif
2075c87e2837SIngo Molnar 	INIT_LIST_HEAD(&p->pi_state_list);
2076c87e2837SIngo Molnar 	p->pi_state_cache = NULL;
207742b2dd0aSAlexey Dobriyan #endif
20781da177e4SLinus Torvalds 	/*
2079f9a3879aSGOTO Masanori 	 * sigaltstack should be cleared when sharing the same VM
2080f9a3879aSGOTO Masanori 	 */
2081f9a3879aSGOTO Masanori 	if ((clone_flags & (CLONE_VM|CLONE_VFORK)) == CLONE_VM)
20822a742138SStas Sergeev 		sas_ss_reset(p);
2083f9a3879aSGOTO Masanori 
2084f9a3879aSGOTO Masanori 	/*
20856580807dSOleg Nesterov 	 * Syscall tracing and stepping should be turned off in the
20866580807dSOleg Nesterov 	 * child regardless of CLONE_PTRACE.
20871da177e4SLinus Torvalds 	 */
20886580807dSOleg Nesterov 	user_disable_single_step(p);
20891da177e4SLinus Torvalds 	clear_tsk_thread_flag(p, TIF_SYSCALL_TRACE);
2090ed75e8d5SLaurent Vivier #ifdef TIF_SYSCALL_EMU
2091ed75e8d5SLaurent Vivier 	clear_tsk_thread_flag(p, TIF_SYSCALL_EMU);
2092ed75e8d5SLaurent Vivier #endif
2093e02c9b0dSLin Feng 	clear_tsk_latency_tracing(p);
20941da177e4SLinus Torvalds 
20951da177e4SLinus Torvalds 	/* ok, now we should be set up.. */
209618c830dfSOleg Nesterov 	p->pid = pid_nr(pid);
209718c830dfSOleg Nesterov 	if (clone_flags & CLONE_THREAD) {
20985f8aadd8SOleg Nesterov 		p->exit_signal = -1;
209918c830dfSOleg Nesterov 		p->group_leader = current->group_leader;
210018c830dfSOleg Nesterov 		p->tgid = current->tgid;
210118c830dfSOleg Nesterov 	} else {
210218c830dfSOleg Nesterov 		if (clone_flags & CLONE_PARENT)
21035f8aadd8SOleg Nesterov 			p->exit_signal = current->group_leader->exit_signal;
21045f8aadd8SOleg Nesterov 		else
21057f192e3cSChristian Brauner 			p->exit_signal = args->exit_signal;
210618c830dfSOleg Nesterov 		p->group_leader = p;
210718c830dfSOleg Nesterov 		p->tgid = p->pid;
210818c830dfSOleg Nesterov 	}
21095f8aadd8SOleg Nesterov 
21109d823e8fSWu Fengguang 	p->nr_dirtied = 0;
21119d823e8fSWu Fengguang 	p->nr_dirtied_pause = 128 >> (PAGE_SHIFT - 10);
211283712358SWu Fengguang 	p->dirty_paused_when = 0;
21139d823e8fSWu Fengguang 
2114bb8cbbfeSOleg Nesterov 	p->pdeath_signal = 0;
211547e65328SOleg Nesterov 	INIT_LIST_HEAD(&p->thread_group);
2116158e1645SAl Viro 	p->task_works = NULL;
21171da177e4SLinus Torvalds 
2118780de9ddSIngo Molnar 	cgroup_threadgroup_change_begin(current);
211918c830dfSOleg Nesterov 	/*
21207e47682eSAleksa Sarai 	 * Ensure that the cgroup subsystem policies allow the new process to be
21217e47682eSAleksa Sarai 	 * forked. It should be noted the the new process's css_set can be changed
21227e47682eSAleksa Sarai 	 * between here and cgroup_post_fork() if an organisation operation is in
21237e47682eSAleksa Sarai 	 * progress.
21247e47682eSAleksa Sarai 	 */
2125b53202e6SOleg Nesterov 	retval = cgroup_can_fork(p);
21267e47682eSAleksa Sarai 	if (retval)
2127c3b7112dSChristian Brauner 		goto bad_fork_cgroup_threadgroup_change_end;
21287e47682eSAleksa Sarai 
21297e47682eSAleksa Sarai 	/*
21307b558513SDavid Herrmann 	 * From this point on we must avoid any synchronous user-space
21317b558513SDavid Herrmann 	 * communication until we take the tasklist-lock. In particular, we do
21327b558513SDavid Herrmann 	 * not want user-space to be able to predict the process start-time by
21337b558513SDavid Herrmann 	 * stalling fork(2) after we recorded the start_time but before it is
21347b558513SDavid Herrmann 	 * visible to the system.
21357b558513SDavid Herrmann 	 */
21367b558513SDavid Herrmann 
21377b558513SDavid Herrmann 	p->start_time = ktime_get_ns();
21389285ec4cSJason A. Donenfeld 	p->real_start_time = ktime_get_boottime_ns();
21397b558513SDavid Herrmann 
21407b558513SDavid Herrmann 	/*
214118c830dfSOleg Nesterov 	 * Make it visible to the rest of the system, but dont wake it up yet.
214218c830dfSOleg Nesterov 	 * Need tasklist lock for parent etc handling!
214318c830dfSOleg Nesterov 	 */
21441da177e4SLinus Torvalds 	write_lock_irq(&tasklist_lock);
21451da177e4SLinus Torvalds 
21461da177e4SLinus Torvalds 	/* CLONE_PARENT re-uses the old parent */
21472d5516cbSOleg Nesterov 	if (clone_flags & (CLONE_PARENT|CLONE_THREAD)) {
21481da177e4SLinus Torvalds 		p->real_parent = current->real_parent;
21492d5516cbSOleg Nesterov 		p->parent_exec_id = current->parent_exec_id;
21502d5516cbSOleg Nesterov 	} else {
21511da177e4SLinus Torvalds 		p->real_parent = current;
21522d5516cbSOleg Nesterov 		p->parent_exec_id = current->self_exec_id;
21532d5516cbSOleg Nesterov 	}
21541da177e4SLinus Torvalds 
2155d83a7cb3SJosh Poimboeuf 	klp_copy_process(p);
2156d83a7cb3SJosh Poimboeuf 
21571da177e4SLinus Torvalds 	spin_lock(&current->sighand->siglock);
21584a2c7a78SOleg Nesterov 
21594a2c7a78SOleg Nesterov 	/*
2160dbd95212SKees Cook 	 * Copy seccomp details explicitly here, in case they were changed
2161dbd95212SKees Cook 	 * before holding sighand lock.
2162dbd95212SKees Cook 	 */
2163dbd95212SKees Cook 	copy_seccomp(p);
2164dbd95212SKees Cook 
2165d7822b1eSMathieu Desnoyers 	rseq_fork(p, clone_flags);
2166d7822b1eSMathieu Desnoyers 
21674ca1d3eeSEric W. Biederman 	/* Don't start children in a dying pid namespace */
2168e8cfbc24SGargi Sharma 	if (unlikely(!(ns_of_pid(pid)->pid_allocated & PIDNS_ADDING))) {
21693fd37226SKirill Tkhai 		retval = -ENOMEM;
21703fd37226SKirill Tkhai 		goto bad_fork_cancel_cgroup;
21713fd37226SKirill Tkhai 	}
21724a2c7a78SOleg Nesterov 
21737673bf55SEric W. Biederman 	/* Let kill terminate clone/fork in the middle */
21747673bf55SEric W. Biederman 	if (fatal_signal_pending(current)) {
21757673bf55SEric W. Biederman 		retval = -EINTR;
21767673bf55SEric W. Biederman 		goto bad_fork_cancel_cgroup;
21777673bf55SEric W. Biederman 	}
21787673bf55SEric W. Biederman 
21796fd2fe49SAl Viro 	/* past the last point of failure */
21806fd2fe49SAl Viro 	if (pidfile)
21816fd2fe49SAl Viro 		fd_install(pidfd, pidfile);
21821da177e4SLinus Torvalds 
21832c470475SEric W. Biederman 	init_task_pid_links(p);
218473b9ebfeSOleg Nesterov 	if (likely(p->pid)) {
21854b9d33e6STejun Heo 		ptrace_init_task(p, (clone_flags & CLONE_PTRACE) || trace);
21861da177e4SLinus Torvalds 
218781907739SOleg Nesterov 		init_task_pid(p, PIDTYPE_PID, pid);
21881da177e4SLinus Torvalds 		if (thread_group_leader(p)) {
21896883f81aSEric W. Biederman 			init_task_pid(p, PIDTYPE_TGID, pid);
219081907739SOleg Nesterov 			init_task_pid(p, PIDTYPE_PGID, task_pgrp(current));
219181907739SOleg Nesterov 			init_task_pid(p, PIDTYPE_SID, task_session(current));
219281907739SOleg Nesterov 
21931c4042c2SEric W. Biederman 			if (is_child_reaper(pid)) {
219417cf22c3SEric W. Biederman 				ns_of_pid(pid)->child_reaper = p;
21951c4042c2SEric W. Biederman 				p->signal->flags |= SIGNAL_UNKILLABLE;
21961c4042c2SEric W. Biederman 			}
2197c3ad2c3bSEric W. Biederman 			p->signal->shared_pending.signal = delayed.signal;
21989c9f4dedSAlan Cox 			p->signal->tty = tty_kref_get(current->signal->tty);
2199749860ceSPavel Tikhomirov 			/*
2200749860ceSPavel Tikhomirov 			 * Inherit has_child_subreaper flag under the same
2201749860ceSPavel Tikhomirov 			 * tasklist_lock with adding child to the process tree
2202749860ceSPavel Tikhomirov 			 * for propagate_has_child_subreaper optimization.
2203749860ceSPavel Tikhomirov 			 */
2204749860ceSPavel Tikhomirov 			p->signal->has_child_subreaper = p->real_parent->signal->has_child_subreaper ||
2205749860ceSPavel Tikhomirov 							 p->real_parent->signal->is_child_subreaper;
22069cd80bbbSOleg Nesterov 			list_add_tail(&p->sibling, &p->real_parent->children);
22075e85d4abSEric W. Biederman 			list_add_tail_rcu(&p->tasks, &init_task.tasks);
22086883f81aSEric W. Biederman 			attach_pid(p, PIDTYPE_TGID);
220981907739SOleg Nesterov 			attach_pid(p, PIDTYPE_PGID);
221081907739SOleg Nesterov 			attach_pid(p, PIDTYPE_SID);
2211909ea964SChristoph Lameter 			__this_cpu_inc(process_counts);
221280628ca0SOleg Nesterov 		} else {
221380628ca0SOleg Nesterov 			current->signal->nr_threads++;
221480628ca0SOleg Nesterov 			atomic_inc(&current->signal->live);
221560d4de3fSElena Reshetova 			refcount_inc(&current->signal->sigcnt);
2216924de3b8SEric W. Biederman 			task_join_group_stop(p);
221780628ca0SOleg Nesterov 			list_add_tail_rcu(&p->thread_group,
221880628ca0SOleg Nesterov 					  &p->group_leader->thread_group);
22190c740d0aSOleg Nesterov 			list_add_tail_rcu(&p->thread_node,
22200c740d0aSOleg Nesterov 					  &p->signal->thread_head);
22211da177e4SLinus Torvalds 		}
222281907739SOleg Nesterov 		attach_pid(p, PIDTYPE_PID);
22231da177e4SLinus Torvalds 		nr_threads++;
222473b9ebfeSOleg Nesterov 	}
22251da177e4SLinus Torvalds 	total_forks++;
2226c3ad2c3bSEric W. Biederman 	hlist_del_init(&delayed.node);
22273f17da69SOleg Nesterov 	spin_unlock(&current->sighand->siglock);
22284af4206bSOleg Nesterov 	syscall_tracepoint_update(p);
22291da177e4SLinus Torvalds 	write_unlock_irq(&tasklist_lock);
22304af4206bSOleg Nesterov 
2231c13cf856SAndrew Morton 	proc_fork_connector(p);
2232b53202e6SOleg Nesterov 	cgroup_post_fork(p);
2233780de9ddSIngo Molnar 	cgroup_threadgroup_change_end(current);
2234cdd6c482SIngo Molnar 	perf_event_fork(p);
223543d2b113SKAMEZAWA Hiroyuki 
223643d2b113SKAMEZAWA Hiroyuki 	trace_task_newtask(p, clone_flags);
22373ab67966SOleg Nesterov 	uprobe_copy_process(p, clone_flags);
223843d2b113SKAMEZAWA Hiroyuki 
22391da177e4SLinus Torvalds 	return p;
22401da177e4SLinus Torvalds 
22417e47682eSAleksa Sarai bad_fork_cancel_cgroup:
22423fd37226SKirill Tkhai 	spin_unlock(&current->sighand->siglock);
22433fd37226SKirill Tkhai 	write_unlock_irq(&tasklist_lock);
2244b53202e6SOleg Nesterov 	cgroup_cancel_fork(p);
2245c3b7112dSChristian Brauner bad_fork_cgroup_threadgroup_change_end:
2246c3b7112dSChristian Brauner 	cgroup_threadgroup_change_end(current);
2247b3e58382SChristian Brauner bad_fork_put_pidfd:
22486fd2fe49SAl Viro 	if (clone_flags & CLONE_PIDFD) {
22496fd2fe49SAl Viro 		fput(pidfile);
22506fd2fe49SAl Viro 		put_unused_fd(pidfd);
22516fd2fe49SAl Viro 	}
2252425fb2b4SPavel Emelyanov bad_fork_free_pid:
2253425fb2b4SPavel Emelyanov 	if (pid != &init_struct_pid)
2254425fb2b4SPavel Emelyanov 		free_pid(pid);
22550740aa5fSJiri Slaby bad_fork_cleanup_thread:
22560740aa5fSJiri Slaby 	exit_thread(p);
2257fd0928dfSJens Axboe bad_fork_cleanup_io:
2258b69f2292SLouis Rilling 	if (p->io_context)
2259b69f2292SLouis Rilling 		exit_io_context(p);
2260ab516013SSerge E. Hallyn bad_fork_cleanup_namespaces:
2261444f378bSLinus Torvalds 	exit_task_namespaces(p);
22621da177e4SLinus Torvalds bad_fork_cleanup_mm:
2263c3f3ce04SAndrea Arcangeli 	if (p->mm) {
2264c3f3ce04SAndrea Arcangeli 		mm_clear_owner(p->mm, p);
22651da177e4SLinus Torvalds 		mmput(p->mm);
2266c3f3ce04SAndrea Arcangeli 	}
22671da177e4SLinus Torvalds bad_fork_cleanup_signal:
22684ab6c083SOleg Nesterov 	if (!(clone_flags & CLONE_THREAD))
22691c5354deSMike Galbraith 		free_signal_struct(p->signal);
22701da177e4SLinus Torvalds bad_fork_cleanup_sighand:
2271a7e5328aSOleg Nesterov 	__cleanup_sighand(p->sighand);
22721da177e4SLinus Torvalds bad_fork_cleanup_fs:
22731da177e4SLinus Torvalds 	exit_fs(p); /* blocking */
22741da177e4SLinus Torvalds bad_fork_cleanup_files:
22751da177e4SLinus Torvalds 	exit_files(p); /* blocking */
22761da177e4SLinus Torvalds bad_fork_cleanup_semundo:
22771da177e4SLinus Torvalds 	exit_sem(p);
2278e4e55b47STetsuo Handa bad_fork_cleanup_security:
2279e4e55b47STetsuo Handa 	security_task_free(p);
22801da177e4SLinus Torvalds bad_fork_cleanup_audit:
22811da177e4SLinus Torvalds 	audit_free(p);
22826c72e350SPeter Zijlstra bad_fork_cleanup_perf:
2283cdd6c482SIngo Molnar 	perf_event_free_task(p);
22846c72e350SPeter Zijlstra bad_fork_cleanup_policy:
2285b09be676SByungchul Park 	lockdep_free_task(p);
22861da177e4SLinus Torvalds #ifdef CONFIG_NUMA
2287f0be3d32SLee Schermerhorn 	mpol_put(p->mempolicy);
2288e8604cb4SLi Zefan bad_fork_cleanup_threadgroup_lock:
22891da177e4SLinus Torvalds #endif
229035df17c5SShailabh Nagar 	delayacct_tsk_free(p);
22911da177e4SLinus Torvalds bad_fork_cleanup_count:
2292d84f4f99SDavid Howells 	atomic_dec(&p->cred->user->processes);
2293e0e81739SDavid Howells 	exit_creds(p);
22941da177e4SLinus Torvalds bad_fork_free:
2295405c0759SAndy Lutomirski 	p->state = TASK_DEAD;
229668f24b08SAndy Lutomirski 	put_task_stack(p);
2297c3f3ce04SAndrea Arcangeli 	delayed_free_task(p);
2298fe7d37d1SOleg Nesterov fork_out:
2299c3ad2c3bSEric W. Biederman 	spin_lock_irq(&current->sighand->siglock);
2300c3ad2c3bSEric W. Biederman 	hlist_del_init(&delayed.node);
2301c3ad2c3bSEric W. Biederman 	spin_unlock_irq(&current->sighand->siglock);
2302fe7d37d1SOleg Nesterov 	return ERR_PTR(retval);
23031da177e4SLinus Torvalds }
23041da177e4SLinus Torvalds 
23052c470475SEric W. Biederman static inline void init_idle_pids(struct task_struct *idle)
2306f106eee1SOleg Nesterov {
2307f106eee1SOleg Nesterov 	enum pid_type type;
2308f106eee1SOleg Nesterov 
2309f106eee1SOleg Nesterov 	for (type = PIDTYPE_PID; type < PIDTYPE_MAX; ++type) {
23102c470475SEric W. Biederman 		INIT_HLIST_NODE(&idle->pid_links[type]); /* not really needed */
23112c470475SEric W. Biederman 		init_task_pid(idle, type, &init_struct_pid);
2312f106eee1SOleg Nesterov 	}
2313f106eee1SOleg Nesterov }
2314f106eee1SOleg Nesterov 
23150db0628dSPaul Gortmaker struct task_struct *fork_idle(int cpu)
23161da177e4SLinus Torvalds {
231736c8b586SIngo Molnar 	struct task_struct *task;
23187f192e3cSChristian Brauner 	struct kernel_clone_args args = {
23197f192e3cSChristian Brauner 		.flags = CLONE_VM,
23207f192e3cSChristian Brauner 	};
23217f192e3cSChristian Brauner 
23227f192e3cSChristian Brauner 	task = copy_process(&init_struct_pid, 0, cpu_to_node(cpu), &args);
2323f106eee1SOleg Nesterov 	if (!IS_ERR(task)) {
23242c470475SEric W. Biederman 		init_idle_pids(task);
23251da177e4SLinus Torvalds 		init_idle(task, cpu);
2326f106eee1SOleg Nesterov 	}
232773b9ebfeSOleg Nesterov 
23281da177e4SLinus Torvalds 	return task;
23291da177e4SLinus Torvalds }
23301da177e4SLinus Torvalds 
233113585fa0SNadav Amit struct mm_struct *copy_init_mm(void)
233213585fa0SNadav Amit {
233313585fa0SNadav Amit 	return dup_mm(NULL, &init_mm);
233413585fa0SNadav Amit }
233513585fa0SNadav Amit 
23361da177e4SLinus Torvalds /*
23371da177e4SLinus Torvalds  *  Ok, this is the main fork-routine.
23381da177e4SLinus Torvalds  *
23391da177e4SLinus Torvalds  * It copies the process, and if successful kick-starts
23401da177e4SLinus Torvalds  * it and waits for it to finish using the VM if required.
23411da177e4SLinus Torvalds  */
23427f192e3cSChristian Brauner long _do_fork(struct kernel_clone_args *args)
23431da177e4SLinus Torvalds {
23447f192e3cSChristian Brauner 	u64 clone_flags = args->flags;
23459f5325aaSMarcos Paulo de Souza 	struct completion vfork;
23469f5325aaSMarcos Paulo de Souza 	struct pid *pid;
23471da177e4SLinus Torvalds 	struct task_struct *p;
23481da177e4SLinus Torvalds 	int trace = 0;
234992476d7fSEric W. Biederman 	long nr;
23501da177e4SLinus Torvalds 
2351bdff746aSAndrew Morton 	/*
23524b9d33e6STejun Heo 	 * Determine whether and which event to report to ptracer.  When
23534b9d33e6STejun Heo 	 * called from kernel_thread or CLONE_UNTRACED is explicitly
23544b9d33e6STejun Heo 	 * requested, no event is reported; otherwise, report if the event
23554b9d33e6STejun Heo 	 * for the type of forking is enabled.
235609a05394SRoland McGrath 	 */
2357e80d6661SAl Viro 	if (!(clone_flags & CLONE_UNTRACED)) {
23584b9d33e6STejun Heo 		if (clone_flags & CLONE_VFORK)
23594b9d33e6STejun Heo 			trace = PTRACE_EVENT_VFORK;
23607f192e3cSChristian Brauner 		else if (args->exit_signal != SIGCHLD)
23614b9d33e6STejun Heo 			trace = PTRACE_EVENT_CLONE;
23624b9d33e6STejun Heo 		else
23634b9d33e6STejun Heo 			trace = PTRACE_EVENT_FORK;
23644b9d33e6STejun Heo 
23654b9d33e6STejun Heo 		if (likely(!ptrace_event_enabled(current, trace)))
23664b9d33e6STejun Heo 			trace = 0;
23674b9d33e6STejun Heo 	}
23681da177e4SLinus Torvalds 
23697f192e3cSChristian Brauner 	p = copy_process(NULL, trace, NUMA_NO_NODE, args);
237038addce8SEmese Revfy 	add_latent_entropy();
23719f5325aaSMarcos Paulo de Souza 
23729f5325aaSMarcos Paulo de Souza 	if (IS_ERR(p))
23739f5325aaSMarcos Paulo de Souza 		return PTR_ERR(p);
23749f5325aaSMarcos Paulo de Souza 
23751da177e4SLinus Torvalds 	/*
23761da177e4SLinus Torvalds 	 * Do this prior waking up the new thread - the thread pointer
23771da177e4SLinus Torvalds 	 * might get invalid after that point, if the thread exits quickly.
23781da177e4SLinus Torvalds 	 */
23790a16b607SMathieu Desnoyers 	trace_sched_process_fork(current, p);
23800a16b607SMathieu Desnoyers 
23814e52365fSMatthew Dempsky 	pid = get_task_pid(p, PIDTYPE_PID);
23824e52365fSMatthew Dempsky 	nr = pid_vnr(pid);
238330e49c26SPavel Emelyanov 
238430e49c26SPavel Emelyanov 	if (clone_flags & CLONE_PARENT_SETTID)
23857f192e3cSChristian Brauner 		put_user(nr, args->parent_tid);
2386a6f5e063SSukadev Bhattiprolu 
23871da177e4SLinus Torvalds 	if (clone_flags & CLONE_VFORK) {
23881da177e4SLinus Torvalds 		p->vfork_done = &vfork;
23891da177e4SLinus Torvalds 		init_completion(&vfork);
2390d68b46feSOleg Nesterov 		get_task_struct(p);
23911da177e4SLinus Torvalds 	}
23921da177e4SLinus Torvalds 
23933e51e3edSSamir Bellabes 	wake_up_new_task(p);
23941da177e4SLinus Torvalds 
23954b9d33e6STejun Heo 	/* forking complete and child started to run, tell ptracer */
23964b9d33e6STejun Heo 	if (unlikely(trace))
23974e52365fSMatthew Dempsky 		ptrace_event_pid(trace, pid);
239809a05394SRoland McGrath 
23991da177e4SLinus Torvalds 	if (clone_flags & CLONE_VFORK) {
2400d68b46feSOleg Nesterov 		if (!wait_for_vfork_done(p, &vfork))
24014e52365fSMatthew Dempsky 			ptrace_event_pid(PTRACE_EVENT_VFORK_DONE, pid);
24029f59ce5dSChuck Ebbert 	}
24034e52365fSMatthew Dempsky 
24044e52365fSMatthew Dempsky 	put_pid(pid);
240592476d7fSEric W. Biederman 	return nr;
24061da177e4SLinus Torvalds }
24071da177e4SLinus Torvalds 
2408028b6e8aSDmitry V. Levin bool legacy_clone_args_valid(const struct kernel_clone_args *kargs)
2409028b6e8aSDmitry V. Levin {
2410028b6e8aSDmitry V. Levin 	/* clone(CLONE_PIDFD) uses parent_tidptr to return a pidfd */
2411028b6e8aSDmitry V. Levin 	if ((kargs->flags & CLONE_PIDFD) &&
2412028b6e8aSDmitry V. Levin 	    (kargs->flags & CLONE_PARENT_SETTID))
2413028b6e8aSDmitry V. Levin 		return false;
2414028b6e8aSDmitry V. Levin 
2415028b6e8aSDmitry V. Levin 	return true;
2416028b6e8aSDmitry V. Levin }
2417028b6e8aSDmitry V. Levin 
24183033f14aSJosh Triplett #ifndef CONFIG_HAVE_COPY_THREAD_TLS
24193033f14aSJosh Triplett /* For compatibility with architectures that call do_fork directly rather than
24203033f14aSJosh Triplett  * using the syscall entry points below. */
24213033f14aSJosh Triplett long do_fork(unsigned long clone_flags,
24223033f14aSJosh Triplett 	      unsigned long stack_start,
24233033f14aSJosh Triplett 	      unsigned long stack_size,
24243033f14aSJosh Triplett 	      int __user *parent_tidptr,
24253033f14aSJosh Triplett 	      int __user *child_tidptr)
24263033f14aSJosh Triplett {
24277f192e3cSChristian Brauner 	struct kernel_clone_args args = {
24287f192e3cSChristian Brauner 		.flags		= (clone_flags & ~CSIGNAL),
2429028b6e8aSDmitry V. Levin 		.pidfd		= parent_tidptr,
24307f192e3cSChristian Brauner 		.child_tid	= child_tidptr,
24317f192e3cSChristian Brauner 		.parent_tid	= parent_tidptr,
24327f192e3cSChristian Brauner 		.exit_signal	= (clone_flags & CSIGNAL),
24337f192e3cSChristian Brauner 		.stack		= stack_start,
24347f192e3cSChristian Brauner 		.stack_size	= stack_size,
24357f192e3cSChristian Brauner 	};
24367f192e3cSChristian Brauner 
2437028b6e8aSDmitry V. Levin 	if (!legacy_clone_args_valid(&args))
2438028b6e8aSDmitry V. Levin 		return -EINVAL;
2439028b6e8aSDmitry V. Levin 
24407f192e3cSChristian Brauner 	return _do_fork(&args);
24413033f14aSJosh Triplett }
24423033f14aSJosh Triplett #endif
24433033f14aSJosh Triplett 
24442aa3a7f8SAl Viro /*
24452aa3a7f8SAl Viro  * Create a kernel thread.
24462aa3a7f8SAl Viro  */
24472aa3a7f8SAl Viro pid_t kernel_thread(int (*fn)(void *), void *arg, unsigned long flags)
24482aa3a7f8SAl Viro {
24497f192e3cSChristian Brauner 	struct kernel_clone_args args = {
24507f192e3cSChristian Brauner 		.flags		= ((flags | CLONE_VM | CLONE_UNTRACED) & ~CSIGNAL),
24517f192e3cSChristian Brauner 		.exit_signal	= (flags & CSIGNAL),
24527f192e3cSChristian Brauner 		.stack		= (unsigned long)fn,
24537f192e3cSChristian Brauner 		.stack_size	= (unsigned long)arg,
24547f192e3cSChristian Brauner 	};
24557f192e3cSChristian Brauner 
24567f192e3cSChristian Brauner 	return _do_fork(&args);
24572aa3a7f8SAl Viro }
24582aa3a7f8SAl Viro 
2459d2125043SAl Viro #ifdef __ARCH_WANT_SYS_FORK
2460d2125043SAl Viro SYSCALL_DEFINE0(fork)
2461d2125043SAl Viro {
2462d2125043SAl Viro #ifdef CONFIG_MMU
24637f192e3cSChristian Brauner 	struct kernel_clone_args args = {
24647f192e3cSChristian Brauner 		.exit_signal = SIGCHLD,
24657f192e3cSChristian Brauner 	};
24667f192e3cSChristian Brauner 
24677f192e3cSChristian Brauner 	return _do_fork(&args);
2468d2125043SAl Viro #else
2469d2125043SAl Viro 	/* can not support in nommu mode */
24705d59e182SDaeseok Youn 	return -EINVAL;
2471d2125043SAl Viro #endif
2472d2125043SAl Viro }
2473d2125043SAl Viro #endif
2474d2125043SAl Viro 
2475d2125043SAl Viro #ifdef __ARCH_WANT_SYS_VFORK
2476d2125043SAl Viro SYSCALL_DEFINE0(vfork)
2477d2125043SAl Viro {
24787f192e3cSChristian Brauner 	struct kernel_clone_args args = {
24797f192e3cSChristian Brauner 		.flags		= CLONE_VFORK | CLONE_VM,
24807f192e3cSChristian Brauner 		.exit_signal	= SIGCHLD,
24817f192e3cSChristian Brauner 	};
24827f192e3cSChristian Brauner 
24837f192e3cSChristian Brauner 	return _do_fork(&args);
2484d2125043SAl Viro }
2485d2125043SAl Viro #endif
2486d2125043SAl Viro 
2487d2125043SAl Viro #ifdef __ARCH_WANT_SYS_CLONE
2488d2125043SAl Viro #ifdef CONFIG_CLONE_BACKWARDS
2489d2125043SAl Viro SYSCALL_DEFINE5(clone, unsigned long, clone_flags, unsigned long, newsp,
2490d2125043SAl Viro 		 int __user *, parent_tidptr,
24913033f14aSJosh Triplett 		 unsigned long, tls,
2492d2125043SAl Viro 		 int __user *, child_tidptr)
2493d2125043SAl Viro #elif defined(CONFIG_CLONE_BACKWARDS2)
2494d2125043SAl Viro SYSCALL_DEFINE5(clone, unsigned long, newsp, unsigned long, clone_flags,
2495d2125043SAl Viro 		 int __user *, parent_tidptr,
2496d2125043SAl Viro 		 int __user *, child_tidptr,
24973033f14aSJosh Triplett 		 unsigned long, tls)
2498dfa9771aSMichal Simek #elif defined(CONFIG_CLONE_BACKWARDS3)
2499dfa9771aSMichal Simek SYSCALL_DEFINE6(clone, unsigned long, clone_flags, unsigned long, newsp,
2500dfa9771aSMichal Simek 		int, stack_size,
2501dfa9771aSMichal Simek 		int __user *, parent_tidptr,
2502dfa9771aSMichal Simek 		int __user *, child_tidptr,
25033033f14aSJosh Triplett 		unsigned long, tls)
2504d2125043SAl Viro #else
2505d2125043SAl Viro SYSCALL_DEFINE5(clone, unsigned long, clone_flags, unsigned long, newsp,
2506d2125043SAl Viro 		 int __user *, parent_tidptr,
2507d2125043SAl Viro 		 int __user *, child_tidptr,
25083033f14aSJosh Triplett 		 unsigned long, tls)
2509d2125043SAl Viro #endif
2510d2125043SAl Viro {
25117f192e3cSChristian Brauner 	struct kernel_clone_args args = {
25127f192e3cSChristian Brauner 		.flags		= (clone_flags & ~CSIGNAL),
25137f192e3cSChristian Brauner 		.pidfd		= parent_tidptr,
25147f192e3cSChristian Brauner 		.child_tid	= child_tidptr,
25157f192e3cSChristian Brauner 		.parent_tid	= parent_tidptr,
25167f192e3cSChristian Brauner 		.exit_signal	= (clone_flags & CSIGNAL),
25177f192e3cSChristian Brauner 		.stack		= newsp,
25187f192e3cSChristian Brauner 		.tls		= tls,
25197f192e3cSChristian Brauner 	};
25207f192e3cSChristian Brauner 
2521028b6e8aSDmitry V. Levin 	if (!legacy_clone_args_valid(&args))
25227f192e3cSChristian Brauner 		return -EINVAL;
25237f192e3cSChristian Brauner 
25247f192e3cSChristian Brauner 	return _do_fork(&args);
25257f192e3cSChristian Brauner }
2526d68dbb0cSChristian Brauner #endif
25277f192e3cSChristian Brauner 
2528d68dbb0cSChristian Brauner #ifdef __ARCH_WANT_SYS_CLONE3
25297f192e3cSChristian Brauner noinline static int copy_clone_args_from_user(struct kernel_clone_args *kargs,
25307f192e3cSChristian Brauner 					      struct clone_args __user *uargs,
25317f192e3cSChristian Brauner 					      size_t size)
25327f192e3cSChristian Brauner {
25337f192e3cSChristian Brauner 	struct clone_args args;
25347f192e3cSChristian Brauner 
25357f192e3cSChristian Brauner 	if (unlikely(size > PAGE_SIZE))
25367f192e3cSChristian Brauner 		return -E2BIG;
25377f192e3cSChristian Brauner 
25387f192e3cSChristian Brauner 	if (unlikely(size < sizeof(struct clone_args)))
25397f192e3cSChristian Brauner 		return -EINVAL;
25407f192e3cSChristian Brauner 
25417f192e3cSChristian Brauner 	if (unlikely(!access_ok(uargs, size)))
25427f192e3cSChristian Brauner 		return -EFAULT;
25437f192e3cSChristian Brauner 
25447f192e3cSChristian Brauner 	if (size > sizeof(struct clone_args)) {
25457f192e3cSChristian Brauner 		unsigned char __user *addr;
25467f192e3cSChristian Brauner 		unsigned char __user *end;
25477f192e3cSChristian Brauner 		unsigned char val;
25487f192e3cSChristian Brauner 
25497f192e3cSChristian Brauner 		addr = (void __user *)uargs + sizeof(struct clone_args);
25507f192e3cSChristian Brauner 		end = (void __user *)uargs + size;
25517f192e3cSChristian Brauner 
25527f192e3cSChristian Brauner 		for (; addr < end; addr++) {
25537f192e3cSChristian Brauner 			if (get_user(val, addr))
25547f192e3cSChristian Brauner 				return -EFAULT;
25557f192e3cSChristian Brauner 			if (val)
25567f192e3cSChristian Brauner 				return -E2BIG;
25577f192e3cSChristian Brauner 		}
25587f192e3cSChristian Brauner 
25597f192e3cSChristian Brauner 		size = sizeof(struct clone_args);
25607f192e3cSChristian Brauner 	}
25617f192e3cSChristian Brauner 
25627f192e3cSChristian Brauner 	if (copy_from_user(&args, uargs, size))
25637f192e3cSChristian Brauner 		return -EFAULT;
25647f192e3cSChristian Brauner 
25657f192e3cSChristian Brauner 	*kargs = (struct kernel_clone_args){
25667f192e3cSChristian Brauner 		.flags		= args.flags,
25677f192e3cSChristian Brauner 		.pidfd		= u64_to_user_ptr(args.pidfd),
25687f192e3cSChristian Brauner 		.child_tid	= u64_to_user_ptr(args.child_tid),
25697f192e3cSChristian Brauner 		.parent_tid	= u64_to_user_ptr(args.parent_tid),
25707f192e3cSChristian Brauner 		.exit_signal	= args.exit_signal,
25717f192e3cSChristian Brauner 		.stack		= args.stack,
25727f192e3cSChristian Brauner 		.stack_size	= args.stack_size,
25737f192e3cSChristian Brauner 		.tls		= args.tls,
25747f192e3cSChristian Brauner 	};
25757f192e3cSChristian Brauner 
25767f192e3cSChristian Brauner 	return 0;
25777f192e3cSChristian Brauner }
25787f192e3cSChristian Brauner 
25797f192e3cSChristian Brauner static bool clone3_args_valid(const struct kernel_clone_args *kargs)
25807f192e3cSChristian Brauner {
25817f192e3cSChristian Brauner 	/*
25827f192e3cSChristian Brauner 	 * All lower bits of the flag word are taken.
25837f192e3cSChristian Brauner 	 * Verify that no other unknown flags are passed along.
25847f192e3cSChristian Brauner 	 */
25857f192e3cSChristian Brauner 	if (kargs->flags & ~CLONE_LEGACY_FLAGS)
25867f192e3cSChristian Brauner 		return false;
25877f192e3cSChristian Brauner 
25887f192e3cSChristian Brauner 	/*
25897f192e3cSChristian Brauner 	 * - make the CLONE_DETACHED bit reuseable for clone3
25907f192e3cSChristian Brauner 	 * - make the CSIGNAL bits reuseable for clone3
25917f192e3cSChristian Brauner 	 */
25927f192e3cSChristian Brauner 	if (kargs->flags & (CLONE_DETACHED | CSIGNAL))
25937f192e3cSChristian Brauner 		return false;
25947f192e3cSChristian Brauner 
25957f192e3cSChristian Brauner 	if ((kargs->flags & (CLONE_THREAD | CLONE_PARENT)) &&
25967f192e3cSChristian Brauner 	    kargs->exit_signal)
25977f192e3cSChristian Brauner 		return false;
25987f192e3cSChristian Brauner 
25997f192e3cSChristian Brauner 	return true;
26007f192e3cSChristian Brauner }
26017f192e3cSChristian Brauner 
26027f192e3cSChristian Brauner SYSCALL_DEFINE2(clone3, struct clone_args __user *, uargs, size_t, size)
26037f192e3cSChristian Brauner {
26047f192e3cSChristian Brauner 	int err;
26057f192e3cSChristian Brauner 
26067f192e3cSChristian Brauner 	struct kernel_clone_args kargs;
26077f192e3cSChristian Brauner 
26087f192e3cSChristian Brauner 	err = copy_clone_args_from_user(&kargs, uargs, size);
26097f192e3cSChristian Brauner 	if (err)
26107f192e3cSChristian Brauner 		return err;
26117f192e3cSChristian Brauner 
26127f192e3cSChristian Brauner 	if (!clone3_args_valid(&kargs))
26137f192e3cSChristian Brauner 		return -EINVAL;
26147f192e3cSChristian Brauner 
26157f192e3cSChristian Brauner 	return _do_fork(&kargs);
2616d2125043SAl Viro }
2617d2125043SAl Viro #endif
2618d2125043SAl Viro 
26190f1b92cbSOleg Nesterov void walk_process_tree(struct task_struct *top, proc_visitor visitor, void *data)
26200f1b92cbSOleg Nesterov {
26210f1b92cbSOleg Nesterov 	struct task_struct *leader, *parent, *child;
26220f1b92cbSOleg Nesterov 	int res;
26230f1b92cbSOleg Nesterov 
26240f1b92cbSOleg Nesterov 	read_lock(&tasklist_lock);
26250f1b92cbSOleg Nesterov 	leader = top = top->group_leader;
26260f1b92cbSOleg Nesterov down:
26270f1b92cbSOleg Nesterov 	for_each_thread(leader, parent) {
26280f1b92cbSOleg Nesterov 		list_for_each_entry(child, &parent->children, sibling) {
26290f1b92cbSOleg Nesterov 			res = visitor(child, data);
26300f1b92cbSOleg Nesterov 			if (res) {
26310f1b92cbSOleg Nesterov 				if (res < 0)
26320f1b92cbSOleg Nesterov 					goto out;
26330f1b92cbSOleg Nesterov 				leader = child;
26340f1b92cbSOleg Nesterov 				goto down;
26350f1b92cbSOleg Nesterov 			}
26360f1b92cbSOleg Nesterov up:
26370f1b92cbSOleg Nesterov 			;
26380f1b92cbSOleg Nesterov 		}
26390f1b92cbSOleg Nesterov 	}
26400f1b92cbSOleg Nesterov 
26410f1b92cbSOleg Nesterov 	if (leader != top) {
26420f1b92cbSOleg Nesterov 		child = leader;
26430f1b92cbSOleg Nesterov 		parent = child->real_parent;
26440f1b92cbSOleg Nesterov 		leader = parent->group_leader;
26450f1b92cbSOleg Nesterov 		goto up;
26460f1b92cbSOleg Nesterov 	}
26470f1b92cbSOleg Nesterov out:
26480f1b92cbSOleg Nesterov 	read_unlock(&tasklist_lock);
26490f1b92cbSOleg Nesterov }
26500f1b92cbSOleg Nesterov 
26515fd63b30SRavikiran G Thirumalai #ifndef ARCH_MIN_MMSTRUCT_ALIGN
26525fd63b30SRavikiran G Thirumalai #define ARCH_MIN_MMSTRUCT_ALIGN 0
26535fd63b30SRavikiran G Thirumalai #endif
26545fd63b30SRavikiran G Thirumalai 
265551cc5068SAlexey Dobriyan static void sighand_ctor(void *data)
2656aa1757f9SOleg Nesterov {
2657aa1757f9SOleg Nesterov 	struct sighand_struct *sighand = data;
2658aa1757f9SOleg Nesterov 
2659aa1757f9SOleg Nesterov 	spin_lock_init(&sighand->siglock);
2660b8fceee1SDavide Libenzi 	init_waitqueue_head(&sighand->signalfd_wqh);
2661fba2afaaSDavide Libenzi }
2662aa1757f9SOleg Nesterov 
26631da177e4SLinus Torvalds void __init proc_caches_init(void)
26641da177e4SLinus Torvalds {
2665c1a2f7f0SRik van Riel 	unsigned int mm_size;
2666c1a2f7f0SRik van Riel 
26671da177e4SLinus Torvalds 	sighand_cachep = kmem_cache_create("sighand_cache",
26681da177e4SLinus Torvalds 			sizeof(struct sighand_struct), 0,
26695f0d5a3aSPaul E. McKenney 			SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_TYPESAFE_BY_RCU|
267075f296d9SLevin, Alexander (Sasha Levin) 			SLAB_ACCOUNT, sighand_ctor);
26711da177e4SLinus Torvalds 	signal_cachep = kmem_cache_create("signal_cache",
26721da177e4SLinus Torvalds 			sizeof(struct signal_struct), 0,
267375f296d9SLevin, Alexander (Sasha Levin) 			SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_ACCOUNT,
26745d097056SVladimir Davydov 			NULL);
26751da177e4SLinus Torvalds 	files_cachep = kmem_cache_create("files_cache",
26761da177e4SLinus Torvalds 			sizeof(struct files_struct), 0,
267775f296d9SLevin, Alexander (Sasha Levin) 			SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_ACCOUNT,
26785d097056SVladimir Davydov 			NULL);
26791da177e4SLinus Torvalds 	fs_cachep = kmem_cache_create("fs_cache",
26801da177e4SLinus Torvalds 			sizeof(struct fs_struct), 0,
268175f296d9SLevin, Alexander (Sasha Levin) 			SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_ACCOUNT,
26825d097056SVladimir Davydov 			NULL);
2683c1a2f7f0SRik van Riel 
26846345d24dSLinus Torvalds 	/*
2685c1a2f7f0SRik van Riel 	 * The mm_cpumask is located at the end of mm_struct, and is
2686c1a2f7f0SRik van Riel 	 * dynamically sized based on the maximum CPU number this system
2687c1a2f7f0SRik van Riel 	 * can have, taking hotplug into account (nr_cpu_ids).
26886345d24dSLinus Torvalds 	 */
2689c1a2f7f0SRik van Riel 	mm_size = sizeof(struct mm_struct) + cpumask_size();
2690c1a2f7f0SRik van Riel 
269107dcd7feSDavid Windsor 	mm_cachep = kmem_cache_create_usercopy("mm_struct",
2692c1a2f7f0SRik van Riel 			mm_size, ARCH_MIN_MMSTRUCT_ALIGN,
269375f296d9SLevin, Alexander (Sasha Levin) 			SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_ACCOUNT,
269407dcd7feSDavid Windsor 			offsetof(struct mm_struct, saved_auxv),
269507dcd7feSDavid Windsor 			sizeof_field(struct mm_struct, saved_auxv),
26965d097056SVladimir Davydov 			NULL);
26975d097056SVladimir Davydov 	vm_area_cachep = KMEM_CACHE(vm_area_struct, SLAB_PANIC|SLAB_ACCOUNT);
26988feae131SDavid Howells 	mmap_init();
269966577193SAl Viro 	nsproxy_cache_init();
27001da177e4SLinus Torvalds }
2701cf2e340fSJANAK DESAI 
2702cf2e340fSJANAK DESAI /*
27039bfb23fcSOleg Nesterov  * Check constraints on flags passed to the unshare system call.
2704cf2e340fSJANAK DESAI  */
27059bfb23fcSOleg Nesterov static int check_unshare_flags(unsigned long unshare_flags)
2706cf2e340fSJANAK DESAI {
27079bfb23fcSOleg Nesterov 	if (unshare_flags & ~(CLONE_THREAD|CLONE_FS|CLONE_NEWNS|CLONE_SIGHAND|
27089bfb23fcSOleg Nesterov 				CLONE_VM|CLONE_FILES|CLONE_SYSVSEM|
270950804fe3SEric W. Biederman 				CLONE_NEWUTS|CLONE_NEWIPC|CLONE_NEWNET|
2710a79a908fSAditya Kali 				CLONE_NEWUSER|CLONE_NEWPID|CLONE_NEWCGROUP))
2711cf2e340fSJANAK DESAI 		return -EINVAL;
27129bfb23fcSOleg Nesterov 	/*
271312c641abSEric W. Biederman 	 * Not implemented, but pretend it works if there is nothing
271412c641abSEric W. Biederman 	 * to unshare.  Note that unsharing the address space or the
271512c641abSEric W. Biederman 	 * signal handlers also need to unshare the signal queues (aka
271612c641abSEric W. Biederman 	 * CLONE_THREAD).
27179bfb23fcSOleg Nesterov 	 */
27189bfb23fcSOleg Nesterov 	if (unshare_flags & (CLONE_THREAD | CLONE_SIGHAND | CLONE_VM)) {
271912c641abSEric W. Biederman 		if (!thread_group_empty(current))
272012c641abSEric W. Biederman 			return -EINVAL;
272112c641abSEric W. Biederman 	}
272212c641abSEric W. Biederman 	if (unshare_flags & (CLONE_SIGHAND | CLONE_VM)) {
2723d036bda7SElena Reshetova 		if (refcount_read(&current->sighand->count) > 1)
272412c641abSEric W. Biederman 			return -EINVAL;
272512c641abSEric W. Biederman 	}
272612c641abSEric W. Biederman 	if (unshare_flags & CLONE_VM) {
272712c641abSEric W. Biederman 		if (!current_is_single_threaded())
27289bfb23fcSOleg Nesterov 			return -EINVAL;
27299bfb23fcSOleg Nesterov 	}
2730cf2e340fSJANAK DESAI 
2731cf2e340fSJANAK DESAI 	return 0;
2732cf2e340fSJANAK DESAI }
2733cf2e340fSJANAK DESAI 
2734cf2e340fSJANAK DESAI /*
273599d1419dSJANAK DESAI  * Unshare the filesystem structure if it is being shared
2736cf2e340fSJANAK DESAI  */
2737cf2e340fSJANAK DESAI static int unshare_fs(unsigned long unshare_flags, struct fs_struct **new_fsp)
2738cf2e340fSJANAK DESAI {
2739cf2e340fSJANAK DESAI 	struct fs_struct *fs = current->fs;
2740cf2e340fSJANAK DESAI 
2741498052bbSAl Viro 	if (!(unshare_flags & CLONE_FS) || !fs)
2742498052bbSAl Viro 		return 0;
2743498052bbSAl Viro 
2744498052bbSAl Viro 	/* don't need lock here; in the worst case we'll do useless copy */
2745498052bbSAl Viro 	if (fs->users == 1)
2746498052bbSAl Viro 		return 0;
2747498052bbSAl Viro 
2748498052bbSAl Viro 	*new_fsp = copy_fs_struct(fs);
274999d1419dSJANAK DESAI 	if (!*new_fsp)
275099d1419dSJANAK DESAI 		return -ENOMEM;
2751cf2e340fSJANAK DESAI 
2752cf2e340fSJANAK DESAI 	return 0;
2753cf2e340fSJANAK DESAI }
2754cf2e340fSJANAK DESAI 
2755cf2e340fSJANAK DESAI /*
2756a016f338SJANAK DESAI  * Unshare file descriptor table if it is being shared
2757cf2e340fSJANAK DESAI  */
2758cf2e340fSJANAK DESAI static int unshare_fd(unsigned long unshare_flags, struct files_struct **new_fdp)
2759cf2e340fSJANAK DESAI {
2760cf2e340fSJANAK DESAI 	struct files_struct *fd = current->files;
2761a016f338SJANAK DESAI 	int error = 0;
2762cf2e340fSJANAK DESAI 
2763cf2e340fSJANAK DESAI 	if ((unshare_flags & CLONE_FILES) &&
2764a016f338SJANAK DESAI 	    (fd && atomic_read(&fd->count) > 1)) {
2765a016f338SJANAK DESAI 		*new_fdp = dup_fd(fd, &error);
2766a016f338SJANAK DESAI 		if (!*new_fdp)
2767a016f338SJANAK DESAI 			return error;
2768a016f338SJANAK DESAI 	}
2769cf2e340fSJANAK DESAI 
2770cf2e340fSJANAK DESAI 	return 0;
2771cf2e340fSJANAK DESAI }
2772cf2e340fSJANAK DESAI 
2773cf2e340fSJANAK DESAI /*
2774cf2e340fSJANAK DESAI  * unshare allows a process to 'unshare' part of the process
2775cf2e340fSJANAK DESAI  * context which was originally shared using clone.  copy_*
2776cf2e340fSJANAK DESAI  * functions used by do_fork() cannot be used here directly
2777cf2e340fSJANAK DESAI  * because they modify an inactive task_struct that is being
2778cf2e340fSJANAK DESAI  * constructed. Here we are modifying the current, active,
2779cf2e340fSJANAK DESAI  * task_struct.
2780cf2e340fSJANAK DESAI  */
27819b32105eSDominik Brodowski int ksys_unshare(unsigned long unshare_flags)
2782cf2e340fSJANAK DESAI {
2783cf2e340fSJANAK DESAI 	struct fs_struct *fs, *new_fs = NULL;
2784cf2e340fSJANAK DESAI 	struct files_struct *fd, *new_fd = NULL;
2785b2e0d987SEric W. Biederman 	struct cred *new_cred = NULL;
2786cf7b708cSPavel Emelyanov 	struct nsproxy *new_nsproxy = NULL;
27879edff4abSManfred Spraul 	int do_sysvsem = 0;
27889bfb23fcSOleg Nesterov 	int err;
2789cf2e340fSJANAK DESAI 
279050804fe3SEric W. Biederman 	/*
2791faf00da5SEric W. Biederman 	 * If unsharing a user namespace must also unshare the thread group
2792faf00da5SEric W. Biederman 	 * and unshare the filesystem root and working directories.
2793b2e0d987SEric W. Biederman 	 */
2794b2e0d987SEric W. Biederman 	if (unshare_flags & CLONE_NEWUSER)
2795e66eded8SEric W. Biederman 		unshare_flags |= CLONE_THREAD | CLONE_FS;
2796b2e0d987SEric W. Biederman 	/*
279750804fe3SEric W. Biederman 	 * If unsharing vm, must also unshare signal handlers.
279850804fe3SEric W. Biederman 	 */
279950804fe3SEric W. Biederman 	if (unshare_flags & CLONE_VM)
280050804fe3SEric W. Biederman 		unshare_flags |= CLONE_SIGHAND;
28016013f67fSManfred Spraul 	/*
280212c641abSEric W. Biederman 	 * If unsharing a signal handlers, must also unshare the signal queues.
280312c641abSEric W. Biederman 	 */
280412c641abSEric W. Biederman 	if (unshare_flags & CLONE_SIGHAND)
280512c641abSEric W. Biederman 		unshare_flags |= CLONE_THREAD;
280612c641abSEric W. Biederman 	/*
28079bfb23fcSOleg Nesterov 	 * If unsharing namespace, must also unshare filesystem information.
28089bfb23fcSOleg Nesterov 	 */
28099bfb23fcSOleg Nesterov 	if (unshare_flags & CLONE_NEWNS)
28109bfb23fcSOleg Nesterov 		unshare_flags |= CLONE_FS;
281150804fe3SEric W. Biederman 
281250804fe3SEric W. Biederman 	err = check_unshare_flags(unshare_flags);
281350804fe3SEric W. Biederman 	if (err)
281450804fe3SEric W. Biederman 		goto bad_unshare_out;
28159bfb23fcSOleg Nesterov 	/*
28166013f67fSManfred Spraul 	 * CLONE_NEWIPC must also detach from the undolist: after switching
28176013f67fSManfred Spraul 	 * to a new ipc namespace, the semaphore arrays from the old
28186013f67fSManfred Spraul 	 * namespace are unreachable.
28196013f67fSManfred Spraul 	 */
28206013f67fSManfred Spraul 	if (unshare_flags & (CLONE_NEWIPC|CLONE_SYSVSEM))
28219edff4abSManfred Spraul 		do_sysvsem = 1;
2822fb0a685cSDaniel Rebelo de Oliveira 	err = unshare_fs(unshare_flags, &new_fs);
2823fb0a685cSDaniel Rebelo de Oliveira 	if (err)
28249bfb23fcSOleg Nesterov 		goto bad_unshare_out;
2825fb0a685cSDaniel Rebelo de Oliveira 	err = unshare_fd(unshare_flags, &new_fd);
2826fb0a685cSDaniel Rebelo de Oliveira 	if (err)
28279bfb23fcSOleg Nesterov 		goto bad_unshare_cleanup_fs;
2828b2e0d987SEric W. Biederman 	err = unshare_userns(unshare_flags, &new_cred);
2829fb0a685cSDaniel Rebelo de Oliveira 	if (err)
28309edff4abSManfred Spraul 		goto bad_unshare_cleanup_fd;
2831b2e0d987SEric W. Biederman 	err = unshare_nsproxy_namespaces(unshare_flags, &new_nsproxy,
2832b2e0d987SEric W. Biederman 					 new_cred, new_fs);
2833b2e0d987SEric W. Biederman 	if (err)
2834b2e0d987SEric W. Biederman 		goto bad_unshare_cleanup_cred;
2835cf2e340fSJANAK DESAI 
2836b2e0d987SEric W. Biederman 	if (new_fs || new_fd || do_sysvsem || new_cred || new_nsproxy) {
28379edff4abSManfred Spraul 		if (do_sysvsem) {
28389edff4abSManfred Spraul 			/*
28399edff4abSManfred Spraul 			 * CLONE_SYSVSEM is equivalent to sys_exit().
28409edff4abSManfred Spraul 			 */
28419edff4abSManfred Spraul 			exit_sem(current);
28429edff4abSManfred Spraul 		}
2843ab602f79SJack Miller 		if (unshare_flags & CLONE_NEWIPC) {
2844ab602f79SJack Miller 			/* Orphan segments in old ns (see sem above). */
2845ab602f79SJack Miller 			exit_shm(current);
2846ab602f79SJack Miller 			shm_init_task(current);
2847ab602f79SJack Miller 		}
2848ab516013SSerge E. Hallyn 
28496f977e6bSAlan Cox 		if (new_nsproxy)
2850cf7b708cSPavel Emelyanov 			switch_task_namespaces(current, new_nsproxy);
2851cf2e340fSJANAK DESAI 
2852cf7b708cSPavel Emelyanov 		task_lock(current);
2853cf7b708cSPavel Emelyanov 
2854cf2e340fSJANAK DESAI 		if (new_fs) {
2855cf2e340fSJANAK DESAI 			fs = current->fs;
28562a4419b5SNick Piggin 			spin_lock(&fs->lock);
2857cf2e340fSJANAK DESAI 			current->fs = new_fs;
2858498052bbSAl Viro 			if (--fs->users)
2859498052bbSAl Viro 				new_fs = NULL;
2860498052bbSAl Viro 			else
2861cf2e340fSJANAK DESAI 				new_fs = fs;
28622a4419b5SNick Piggin 			spin_unlock(&fs->lock);
2863cf2e340fSJANAK DESAI 		}
2864cf2e340fSJANAK DESAI 
2865cf2e340fSJANAK DESAI 		if (new_fd) {
2866cf2e340fSJANAK DESAI 			fd = current->files;
2867cf2e340fSJANAK DESAI 			current->files = new_fd;
2868cf2e340fSJANAK DESAI 			new_fd = fd;
2869cf2e340fSJANAK DESAI 		}
2870cf2e340fSJANAK DESAI 
2871cf2e340fSJANAK DESAI 		task_unlock(current);
2872b2e0d987SEric W. Biederman 
2873b2e0d987SEric W. Biederman 		if (new_cred) {
2874b2e0d987SEric W. Biederman 			/* Install the new user namespace */
2875b2e0d987SEric W. Biederman 			commit_creds(new_cred);
2876b2e0d987SEric W. Biederman 			new_cred = NULL;
2877b2e0d987SEric W. Biederman 		}
2878cf2e340fSJANAK DESAI 	}
2879cf2e340fSJANAK DESAI 
2880e4222673SHari Bathini 	perf_event_namespaces(current);
2881e4222673SHari Bathini 
2882b2e0d987SEric W. Biederman bad_unshare_cleanup_cred:
2883b2e0d987SEric W. Biederman 	if (new_cred)
2884b2e0d987SEric W. Biederman 		put_cred(new_cred);
2885cf2e340fSJANAK DESAI bad_unshare_cleanup_fd:
2886cf2e340fSJANAK DESAI 	if (new_fd)
2887cf2e340fSJANAK DESAI 		put_files_struct(new_fd);
2888cf2e340fSJANAK DESAI 
2889cf2e340fSJANAK DESAI bad_unshare_cleanup_fs:
2890cf2e340fSJANAK DESAI 	if (new_fs)
2891498052bbSAl Viro 		free_fs_struct(new_fs);
2892cf2e340fSJANAK DESAI 
2893cf2e340fSJANAK DESAI bad_unshare_out:
2894cf2e340fSJANAK DESAI 	return err;
2895cf2e340fSJANAK DESAI }
28963b125388SAl Viro 
28979b32105eSDominik Brodowski SYSCALL_DEFINE1(unshare, unsigned long, unshare_flags)
28989b32105eSDominik Brodowski {
28999b32105eSDominik Brodowski 	return ksys_unshare(unshare_flags);
29009b32105eSDominik Brodowski }
29019b32105eSDominik Brodowski 
29023b125388SAl Viro /*
29033b125388SAl Viro  *	Helper to unshare the files of the current task.
29043b125388SAl Viro  *	We don't want to expose copy_files internals to
29053b125388SAl Viro  *	the exec layer of the kernel.
29063b125388SAl Viro  */
29073b125388SAl Viro 
29083b125388SAl Viro int unshare_files(struct files_struct **displaced)
29093b125388SAl Viro {
29103b125388SAl Viro 	struct task_struct *task = current;
291150704516SAl Viro 	struct files_struct *copy = NULL;
29123b125388SAl Viro 	int error;
29133b125388SAl Viro 
29143b125388SAl Viro 	error = unshare_fd(CLONE_FILES, &copy);
29153b125388SAl Viro 	if (error || !copy) {
29163b125388SAl Viro 		*displaced = NULL;
29173b125388SAl Viro 		return error;
29183b125388SAl Viro 	}
29193b125388SAl Viro 	*displaced = task->files;
29203b125388SAl Viro 	task_lock(task);
29213b125388SAl Viro 	task->files = copy;
29223b125388SAl Viro 	task_unlock(task);
29233b125388SAl Viro 	return 0;
29243b125388SAl Viro }
292516db3d3fSHeinrich Schuchardt 
292616db3d3fSHeinrich Schuchardt int sysctl_max_threads(struct ctl_table *table, int write,
292716db3d3fSHeinrich Schuchardt 		       void __user *buffer, size_t *lenp, loff_t *ppos)
292816db3d3fSHeinrich Schuchardt {
292916db3d3fSHeinrich Schuchardt 	struct ctl_table t;
293016db3d3fSHeinrich Schuchardt 	int ret;
293116db3d3fSHeinrich Schuchardt 	int threads = max_threads;
293216db3d3fSHeinrich Schuchardt 	int min = MIN_THREADS;
293316db3d3fSHeinrich Schuchardt 	int max = MAX_THREADS;
293416db3d3fSHeinrich Schuchardt 
293516db3d3fSHeinrich Schuchardt 	t = *table;
293616db3d3fSHeinrich Schuchardt 	t.data = &threads;
293716db3d3fSHeinrich Schuchardt 	t.extra1 = &min;
293816db3d3fSHeinrich Schuchardt 	t.extra2 = &max;
293916db3d3fSHeinrich Schuchardt 
294016db3d3fSHeinrich Schuchardt 	ret = proc_dointvec_minmax(&t, write, buffer, lenp, ppos);
294116db3d3fSHeinrich Schuchardt 	if (ret || !write)
294216db3d3fSHeinrich Schuchardt 		return ret;
294316db3d3fSHeinrich Schuchardt 
294416db3d3fSHeinrich Schuchardt 	set_max_threads(threads);
294516db3d3fSHeinrich Schuchardt 
294616db3d3fSHeinrich Schuchardt 	return 0;
294716db3d3fSHeinrich Schuchardt }
2948