xref: /openbmc/linux/kernel/fork.c (revision 4189ff23489e6688ef4c7f5109df0cebbad425b1)
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);
72916d51a59SJann 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 
771*4189ff23SChristoph Hellwig #ifndef CONFIG_ARCH_TASK_STRUCT_ALLOCATOR
7725905429aSKees Cook static void task_struct_whitelist(unsigned long *offset, unsigned long *size)
7735905429aSKees Cook {
7745905429aSKees Cook 	/* Fetch thread_struct whitelist for the architecture. */
7755905429aSKees Cook 	arch_thread_struct_whitelist(offset, size);
7765905429aSKees Cook 
7775905429aSKees Cook 	/*
7785905429aSKees Cook 	 * Handle zero-sized whitelist or empty thread_struct, otherwise
7795905429aSKees Cook 	 * adjust offset to position of thread_struct in task_struct.
7805905429aSKees Cook 	 */
7815905429aSKees Cook 	if (unlikely(*size == 0))
7825905429aSKees Cook 		*offset = 0;
7835905429aSKees Cook 	else
7845905429aSKees Cook 		*offset += offsetof(struct task_struct, thread);
7855905429aSKees Cook }
786*4189ff23SChristoph Hellwig #endif /* CONFIG_ARCH_TASK_STRUCT_ALLOCATOR */
7875905429aSKees Cook 
7881da177e4SLinus Torvalds void __init fork_init(void)
7891da177e4SLinus Torvalds {
7901da177e4SLinus Torvalds 	int i;
7911da177e4SLinus Torvalds #ifndef CONFIG_ARCH_TASK_STRUCT_ALLOCATOR
7921da177e4SLinus Torvalds #ifndef ARCH_MIN_TASKALIGN
7931da177e4SLinus Torvalds #define ARCH_MIN_TASKALIGN	0
7941da177e4SLinus Torvalds #endif
7951da177e4SLinus Torvalds 	int align = max_t(int, L1_CACHE_BYTES, ARCH_MIN_TASKALIGN);
7965905429aSKees Cook 	unsigned long useroffset, usersize;
7971da177e4SLinus Torvalds 
7981da177e4SLinus Torvalds 	/* create a slab on which task_structs can be allocated */
7995905429aSKees Cook 	task_struct_whitelist(&useroffset, &usersize);
8005905429aSKees Cook 	task_struct_cachep = kmem_cache_create_usercopy("task_struct",
8011da177e4SLinus Torvalds 			arch_task_struct_size, align,
8025905429aSKees Cook 			SLAB_PANIC|SLAB_ACCOUNT,
8035905429aSKees Cook 			useroffset, usersize, NULL);
8041da177e4SLinus Torvalds #endif
8051da177e4SLinus Torvalds 
8061da177e4SLinus Torvalds 	/* do the arch specific task caches init */
8071da177e4SLinus Torvalds 	arch_task_cache_init();
8081da177e4SLinus Torvalds 
8091da177e4SLinus Torvalds 	set_max_threads(MAX_THREADS);
8101da177e4SLinus Torvalds 
8111da177e4SLinus Torvalds 	init_task.signal->rlim[RLIMIT_NPROC].rlim_cur = max_threads/2;
8121da177e4SLinus Torvalds 	init_task.signal->rlim[RLIMIT_NPROC].rlim_max = max_threads/2;
8131da177e4SLinus Torvalds 	init_task.signal->rlim[RLIMIT_SIGPENDING] =
8141da177e4SLinus Torvalds 		init_task.signal->rlim[RLIMIT_NPROC];
8151da177e4SLinus Torvalds 
8161da177e4SLinus Torvalds 	for (i = 0; i < UCOUNT_COUNTS; i++) {
8171da177e4SLinus Torvalds 		init_user_ns.ucount_max[i] = max_threads/2;
8181da177e4SLinus Torvalds 	}
8191da177e4SLinus Torvalds 
8201da177e4SLinus Torvalds #ifdef CONFIG_VMAP_STACK
8211da177e4SLinus Torvalds 	cpuhp_setup_state(CPUHP_BP_PREPARE_DYN, "fork:vm_stack_cache",
8221da177e4SLinus Torvalds 			  NULL, free_vm_stack_cache);
8231da177e4SLinus Torvalds #endif
8241da177e4SLinus Torvalds 
8251da177e4SLinus Torvalds 	lockdep_init_task(&init_task);
826aad42dd4SNadav Amit 	uprobes_init();
8271da177e4SLinus Torvalds }
8281da177e4SLinus Torvalds 
8291da177e4SLinus Torvalds int __weak arch_dup_task_struct(struct task_struct *dst,
8301da177e4SLinus Torvalds 					       struct task_struct *src)
8311da177e4SLinus Torvalds {
8321da177e4SLinus Torvalds 	*dst = *src;
8331da177e4SLinus Torvalds 	return 0;
8341da177e4SLinus Torvalds }
8351da177e4SLinus Torvalds 
8361da177e4SLinus Torvalds void set_task_stack_end_magic(struct task_struct *tsk)
8371da177e4SLinus Torvalds {
8381da177e4SLinus Torvalds 	unsigned long *stackend;
8391da177e4SLinus Torvalds 
8401da177e4SLinus Torvalds 	stackend = end_of_stack(tsk);
8411da177e4SLinus Torvalds 	*stackend = STACK_END_MAGIC;	/* for overflow detection */
8421da177e4SLinus Torvalds }
8431da177e4SLinus Torvalds 
8441da177e4SLinus Torvalds static struct task_struct *dup_task_struct(struct task_struct *orig, int node)
8451da177e4SLinus Torvalds {
8461da177e4SLinus Torvalds 	struct task_struct *tsk;
8471da177e4SLinus Torvalds 	unsigned long *stack;
8480f4991e8SYueHaibing 	struct vm_struct *stack_vm_area __maybe_unused;
8491da177e4SLinus Torvalds 	int err;
8501da177e4SLinus Torvalds 
8511da177e4SLinus Torvalds 	if (node == NUMA_NO_NODE)
8521da177e4SLinus Torvalds 		node = tsk_fork_get_node(orig);
8531da177e4SLinus Torvalds 	tsk = alloc_task_struct_node(node);
8541da177e4SLinus Torvalds 	if (!tsk)
8551da177e4SLinus Torvalds 		return NULL;
8561da177e4SLinus Torvalds 
8571da177e4SLinus Torvalds 	stack = alloc_thread_stack_node(tsk, node);
8581da177e4SLinus Torvalds 	if (!stack)
8591da177e4SLinus Torvalds 		goto free_tsk;
8601da177e4SLinus Torvalds 
8619b6f7e16SRoman Gushchin 	if (memcg_charge_kernel_stack(tsk))
8629b6f7e16SRoman Gushchin 		goto free_stack;
8639b6f7e16SRoman Gushchin 
8641da177e4SLinus Torvalds 	stack_vm_area = task_stack_vm_area(tsk);
8651da177e4SLinus Torvalds 
8661da177e4SLinus Torvalds 	err = arch_dup_task_struct(tsk, orig);
8671da177e4SLinus Torvalds 
8681da177e4SLinus Torvalds 	/*
8691da177e4SLinus Torvalds 	 * arch_dup_task_struct() clobbers the stack-related fields.  Make
8701da177e4SLinus Torvalds 	 * sure they're properly initialized before using any stack-related
8711da177e4SLinus Torvalds 	 * functions again.
8721da177e4SLinus Torvalds 	 */
8731da177e4SLinus Torvalds 	tsk->stack = stack;
8741da177e4SLinus Torvalds #ifdef CONFIG_VMAP_STACK
8751da177e4SLinus Torvalds 	tsk->stack_vm_area = stack_vm_area;
8761da177e4SLinus Torvalds #endif
8771da177e4SLinus Torvalds #ifdef CONFIG_THREAD_INFO_IN_TASK
878f0b89d39SElena Reshetova 	refcount_set(&tsk->stack_refcount, 1);
8791da177e4SLinus Torvalds #endif
8801da177e4SLinus Torvalds 
8811da177e4SLinus Torvalds 	if (err)
8821da177e4SLinus Torvalds 		goto free_stack;
8831da177e4SLinus Torvalds 
8841da177e4SLinus Torvalds #ifdef CONFIG_SECCOMP
8851da177e4SLinus Torvalds 	/*
8861da177e4SLinus Torvalds 	 * We must handle setting up seccomp filters once we're under
8871da177e4SLinus Torvalds 	 * the sighand lock in case orig has changed between now and
8881da177e4SLinus Torvalds 	 * then. Until then, filter must be NULL to avoid messing up
8891da177e4SLinus Torvalds 	 * the usage counts on the error path calling free_task.
8901da177e4SLinus Torvalds 	 */
8911da177e4SLinus Torvalds 	tsk->seccomp.filter = NULL;
8921da177e4SLinus Torvalds #endif
8931da177e4SLinus Torvalds 
8941da177e4SLinus Torvalds 	setup_thread_stack(tsk, orig);
8951da177e4SLinus Torvalds 	clear_user_return_notifier(tsk);
8961da177e4SLinus Torvalds 	clear_tsk_need_resched(tsk);
8971da177e4SLinus Torvalds 	set_task_stack_end_magic(tsk);
8981da177e4SLinus Torvalds 
899050e9baaSLinus Torvalds #ifdef CONFIG_STACKPROTECTOR
9001da177e4SLinus Torvalds 	tsk->stack_canary = get_random_canary();
9011da177e4SLinus Torvalds #endif
9023bd37062SSebastian Andrzej Siewior 	if (orig->cpus_ptr == &orig->cpus_mask)
9033bd37062SSebastian Andrzej Siewior 		tsk->cpus_ptr = &tsk->cpus_mask;
9041da177e4SLinus Torvalds 
9051da177e4SLinus Torvalds 	/*
9061da177e4SLinus Torvalds 	 * One for us, one for whoever does the "release_task()" (usually
9071da177e4SLinus Torvalds 	 * parent)
9081da177e4SLinus Torvalds 	 */
909ec1d2819SElena Reshetova 	refcount_set(&tsk->usage, 2);
9101da177e4SLinus Torvalds #ifdef CONFIG_BLK_DEV_IO_TRACE
9111da177e4SLinus Torvalds 	tsk->btrace_seq = 0;
9121da177e4SLinus Torvalds #endif
9131da177e4SLinus Torvalds 	tsk->splice_pipe = NULL;
9141da177e4SLinus Torvalds 	tsk->task_frag.page = NULL;
9151da177e4SLinus Torvalds 	tsk->wake_q.next = NULL;
9161da177e4SLinus Torvalds 
9171da177e4SLinus Torvalds 	account_kernel_stack(tsk, 1);
9181da177e4SLinus Torvalds 
9191da177e4SLinus Torvalds 	kcov_task_init(tsk);
9201da177e4SLinus Torvalds 
9211da177e4SLinus Torvalds #ifdef CONFIG_FAULT_INJECTION
9221da177e4SLinus Torvalds 	tsk->fail_nth = 0;
9231da177e4SLinus Torvalds #endif
9241da177e4SLinus Torvalds 
9252c323017SJosef Bacik #ifdef CONFIG_BLK_CGROUP
9262c323017SJosef Bacik 	tsk->throttle_queue = NULL;
9272c323017SJosef Bacik 	tsk->use_memdelay = 0;
9282c323017SJosef Bacik #endif
9292c323017SJosef Bacik 
930d46eb14bSShakeel Butt #ifdef CONFIG_MEMCG
931d46eb14bSShakeel Butt 	tsk->active_memcg = NULL;
932d46eb14bSShakeel Butt #endif
9331da177e4SLinus Torvalds 	return tsk;
9341da177e4SLinus Torvalds 
9351da177e4SLinus Torvalds free_stack:
9361da177e4SLinus Torvalds 	free_thread_stack(tsk);
9371da177e4SLinus Torvalds free_tsk:
9381da177e4SLinus Torvalds 	free_task_struct(tsk);
9391da177e4SLinus Torvalds 	return NULL;
9401da177e4SLinus Torvalds }
9411da177e4SLinus Torvalds 
9421da177e4SLinus Torvalds __cacheline_aligned_in_smp DEFINE_SPINLOCK(mmlist_lock);
9431da177e4SLinus Torvalds 
9444cb0e11bSHidehiro Kawai static unsigned long default_dump_filter = MMF_DUMP_FILTER_DEFAULT;
9454cb0e11bSHidehiro Kawai 
9464cb0e11bSHidehiro Kawai static int __init coredump_filter_setup(char *s)
9474cb0e11bSHidehiro Kawai {
9484cb0e11bSHidehiro Kawai 	default_dump_filter =
9494cb0e11bSHidehiro Kawai 		(simple_strtoul(s, NULL, 0) << MMF_DUMP_FILTER_SHIFT) &
9504cb0e11bSHidehiro Kawai 		MMF_DUMP_FILTER_MASK;
9514cb0e11bSHidehiro Kawai 	return 1;
9524cb0e11bSHidehiro Kawai }
9534cb0e11bSHidehiro Kawai 
9544cb0e11bSHidehiro Kawai __setup("coredump_filter=", coredump_filter_setup);
9554cb0e11bSHidehiro Kawai 
9561da177e4SLinus Torvalds #include <linux/init_task.h>
9571da177e4SLinus Torvalds 
958858f0993SAlexey Dobriyan static void mm_init_aio(struct mm_struct *mm)
959858f0993SAlexey Dobriyan {
960858f0993SAlexey Dobriyan #ifdef CONFIG_AIO
961858f0993SAlexey Dobriyan 	spin_lock_init(&mm->ioctx_lock);
962db446a08SBenjamin LaHaise 	mm->ioctx_table = NULL;
963858f0993SAlexey Dobriyan #endif
964858f0993SAlexey Dobriyan }
965858f0993SAlexey Dobriyan 
966c3f3ce04SAndrea Arcangeli static __always_inline void mm_clear_owner(struct mm_struct *mm,
967c3f3ce04SAndrea Arcangeli 					   struct task_struct *p)
968c3f3ce04SAndrea Arcangeli {
969c3f3ce04SAndrea Arcangeli #ifdef CONFIG_MEMCG
970c3f3ce04SAndrea Arcangeli 	if (mm->owner == p)
971c3f3ce04SAndrea Arcangeli 		WRITE_ONCE(mm->owner, NULL);
972c3f3ce04SAndrea Arcangeli #endif
973c3f3ce04SAndrea Arcangeli }
974c3f3ce04SAndrea Arcangeli 
97533144e84SVladimir Davydov static void mm_init_owner(struct mm_struct *mm, struct task_struct *p)
97633144e84SVladimir Davydov {
97733144e84SVladimir Davydov #ifdef CONFIG_MEMCG
97833144e84SVladimir Davydov 	mm->owner = p;
97933144e84SVladimir Davydov #endif
98033144e84SVladimir Davydov }
98133144e84SVladimir Davydov 
982355627f5SEric Biggers static void mm_init_uprobes_state(struct mm_struct *mm)
983355627f5SEric Biggers {
984355627f5SEric Biggers #ifdef CONFIG_UPROBES
985355627f5SEric Biggers 	mm->uprobes_state.xol_area = NULL;
986355627f5SEric Biggers #endif
987355627f5SEric Biggers }
988355627f5SEric Biggers 
989bfedb589SEric W. Biederman static struct mm_struct *mm_init(struct mm_struct *mm, struct task_struct *p,
990bfedb589SEric W. Biederman 	struct user_namespace *user_ns)
9911da177e4SLinus Torvalds {
99241f727fdSVladimir Davydov 	mm->mmap = NULL;
99341f727fdSVladimir Davydov 	mm->mm_rb = RB_ROOT;
99441f727fdSVladimir Davydov 	mm->vmacache_seqnum = 0;
9951da177e4SLinus Torvalds 	atomic_set(&mm->mm_users, 1);
9961da177e4SLinus Torvalds 	atomic_set(&mm->mm_count, 1);
9971da177e4SLinus Torvalds 	init_rwsem(&mm->mmap_sem);
9981da177e4SLinus Torvalds 	INIT_LIST_HEAD(&mm->mmlist);
999999d9fc1SOleg Nesterov 	mm->core_state = NULL;
1000af5b0f6aSKirill A. Shutemov 	mm_pgtables_bytes_init(mm);
100141f727fdSVladimir Davydov 	mm->map_count = 0;
100241f727fdSVladimir Davydov 	mm->locked_vm = 0;
100370f8a3caSDavidlohr Bueso 	atomic64_set(&mm->pinned_vm, 0);
1004d559db08SKAMEZAWA Hiroyuki 	memset(&mm->rss_stat, 0, sizeof(mm->rss_stat));
10051da177e4SLinus Torvalds 	spin_lock_init(&mm->page_table_lock);
100688aa7cc6SYang Shi 	spin_lock_init(&mm->arg_lock);
100741f727fdSVladimir Davydov 	mm_init_cpumask(mm);
1008858f0993SAlexey Dobriyan 	mm_init_aio(mm);
1009cf475ad2SBalbir Singh 	mm_init_owner(mm, p);
10102b7e8665SEric Biggers 	RCU_INIT_POINTER(mm->exe_file, NULL);
101141f727fdSVladimir Davydov 	mmu_notifier_mm_init(mm);
1012133ff0eaSJérôme Glisse 	hmm_mm_init(mm);
101316af97dcSNadav Amit 	init_tlb_flush_pending(mm);
101441f727fdSVladimir Davydov #if defined(CONFIG_TRANSPARENT_HUGEPAGE) && !USE_SPLIT_PMD_PTLOCKS
101541f727fdSVladimir Davydov 	mm->pmd_huge_pte = NULL;
101641f727fdSVladimir Davydov #endif
1017355627f5SEric Biggers 	mm_init_uprobes_state(mm);
10181da177e4SLinus Torvalds 
1019a0715cc2SAlex Thorlton 	if (current->mm) {
1020a0715cc2SAlex Thorlton 		mm->flags = current->mm->flags & MMF_INIT_MASK;
1021a0715cc2SAlex Thorlton 		mm->def_flags = current->mm->def_flags & VM_INIT_DEF_MASK;
1022a0715cc2SAlex Thorlton 	} else {
1023a0715cc2SAlex Thorlton 		mm->flags = default_dump_filter;
10241da177e4SLinus Torvalds 		mm->def_flags = 0;
1025a0715cc2SAlex Thorlton 	}
1026a0715cc2SAlex Thorlton 
102741f727fdSVladimir Davydov 	if (mm_alloc_pgd(mm))
102841f727fdSVladimir Davydov 		goto fail_nopgd;
102978fb7466SPavel Emelianov 
103041f727fdSVladimir Davydov 	if (init_new_context(p, mm))
103141f727fdSVladimir Davydov 		goto fail_nocontext;
103241f727fdSVladimir Davydov 
1033bfedb589SEric W. Biederman 	mm->user_ns = get_user_ns(user_ns);
103441f727fdSVladimir Davydov 	return mm;
103541f727fdSVladimir Davydov 
103641f727fdSVladimir Davydov fail_nocontext:
103741f727fdSVladimir Davydov 	mm_free_pgd(mm);
103841f727fdSVladimir Davydov fail_nopgd:
10391da177e4SLinus Torvalds 	free_mm(mm);
10401da177e4SLinus Torvalds 	return NULL;
10411da177e4SLinus Torvalds }
10421da177e4SLinus Torvalds 
10431da177e4SLinus Torvalds /*
10441da177e4SLinus Torvalds  * Allocate and initialize an mm_struct.
10451da177e4SLinus Torvalds  */
10461da177e4SLinus Torvalds struct mm_struct *mm_alloc(void)
10471da177e4SLinus Torvalds {
10481da177e4SLinus Torvalds 	struct mm_struct *mm;
10491da177e4SLinus Torvalds 
10501da177e4SLinus Torvalds 	mm = allocate_mm();
1051de03c72cSKOSAKI Motohiro 	if (!mm)
1052de03c72cSKOSAKI Motohiro 		return NULL;
1053de03c72cSKOSAKI Motohiro 
10541da177e4SLinus Torvalds 	memset(mm, 0, sizeof(*mm));
1055bfedb589SEric W. Biederman 	return mm_init(mm, current, current_user_ns());
10561da177e4SLinus Torvalds }
10571da177e4SLinus Torvalds 
1058ec8d7c14SMichal Hocko static inline void __mmput(struct mm_struct *mm)
10591da177e4SLinus Torvalds {
1060ec8d7c14SMichal Hocko 	VM_BUG_ON(atomic_read(&mm->mm_users));
10610ae26f1bSAndrew Morton 
1062d4b3b638SSrikar Dronamraju 	uprobe_clear_state(mm);
10631da177e4SLinus Torvalds 	exit_aio(mm);
10641c2fb7a4SAndrea Arcangeli 	ksm_exit(mm);
1065ba76149fSAndrea Arcangeli 	khugepaged_exit(mm); /* must run before exit_mmap */
10661da177e4SLinus Torvalds 	exit_mmap(mm);
10676fcb52a5SAaron Lu 	mm_put_huge_zero_page(mm);
1068925d1c40SMatt Helsley 	set_mm_exe_file(mm, NULL);
10691da177e4SLinus Torvalds 	if (!list_empty(&mm->mmlist)) {
10701da177e4SLinus Torvalds 		spin_lock(&mmlist_lock);
10711da177e4SLinus Torvalds 		list_del(&mm->mmlist);
10721da177e4SLinus Torvalds 		spin_unlock(&mmlist_lock);
10731da177e4SLinus Torvalds 	}
1074801460d0SHiroshi Shimamoto 	if (mm->binfmt)
1075801460d0SHiroshi Shimamoto 		module_put(mm->binfmt->module);
10761da177e4SLinus Torvalds 	mmdrop(mm);
10771da177e4SLinus Torvalds }
1078ec8d7c14SMichal Hocko 
1079ec8d7c14SMichal Hocko /*
1080ec8d7c14SMichal Hocko  * Decrement the use count and release all resources for an mm.
1081ec8d7c14SMichal Hocko  */
1082ec8d7c14SMichal Hocko void mmput(struct mm_struct *mm)
1083ec8d7c14SMichal Hocko {
1084ec8d7c14SMichal Hocko 	might_sleep();
1085ec8d7c14SMichal Hocko 
1086ec8d7c14SMichal Hocko 	if (atomic_dec_and_test(&mm->mm_users))
1087ec8d7c14SMichal Hocko 		__mmput(mm);
10881da177e4SLinus Torvalds }
10891da177e4SLinus Torvalds EXPORT_SYMBOL_GPL(mmput);
10901da177e4SLinus Torvalds 
1091a1b2289cSSherry Yang #ifdef CONFIG_MMU
1092a1b2289cSSherry Yang static void mmput_async_fn(struct work_struct *work)
1093a1b2289cSSherry Yang {
1094a1b2289cSSherry Yang 	struct mm_struct *mm = container_of(work, struct mm_struct,
1095a1b2289cSSherry Yang 					    async_put_work);
1096a1b2289cSSherry Yang 
1097a1b2289cSSherry Yang 	__mmput(mm);
1098a1b2289cSSherry Yang }
1099a1b2289cSSherry Yang 
1100a1b2289cSSherry Yang void mmput_async(struct mm_struct *mm)
1101a1b2289cSSherry Yang {
1102a1b2289cSSherry Yang 	if (atomic_dec_and_test(&mm->mm_users)) {
1103a1b2289cSSherry Yang 		INIT_WORK(&mm->async_put_work, mmput_async_fn);
1104a1b2289cSSherry Yang 		schedule_work(&mm->async_put_work);
1105a1b2289cSSherry Yang 	}
1106a1b2289cSSherry Yang }
1107a1b2289cSSherry Yang #endif
1108a1b2289cSSherry Yang 
110990f31d0eSKonstantin Khlebnikov /**
111090f31d0eSKonstantin Khlebnikov  * set_mm_exe_file - change a reference to the mm's executable file
111190f31d0eSKonstantin Khlebnikov  *
111290f31d0eSKonstantin Khlebnikov  * This changes mm's executable file (shown as symlink /proc/[pid]/exe).
111390f31d0eSKonstantin Khlebnikov  *
11146e399cd1SDavidlohr Bueso  * Main users are mmput() and sys_execve(). Callers prevent concurrent
11156e399cd1SDavidlohr Bueso  * invocations: in mmput() nobody alive left, in execve task is single
11166e399cd1SDavidlohr Bueso  * threaded. sys_prctl(PR_SET_MM_MAP/EXE_FILE) also needs to set the
11176e399cd1SDavidlohr Bueso  * mm->exe_file, but does so without using set_mm_exe_file() in order
11186e399cd1SDavidlohr Bueso  * to do avoid the need for any locks.
111990f31d0eSKonstantin Khlebnikov  */
112038646013SJiri Slaby void set_mm_exe_file(struct mm_struct *mm, struct file *new_exe_file)
112138646013SJiri Slaby {
11226e399cd1SDavidlohr Bueso 	struct file *old_exe_file;
11236e399cd1SDavidlohr Bueso 
11246e399cd1SDavidlohr Bueso 	/*
11256e399cd1SDavidlohr Bueso 	 * It is safe to dereference the exe_file without RCU as
11266e399cd1SDavidlohr Bueso 	 * this function is only called if nobody else can access
11276e399cd1SDavidlohr Bueso 	 * this mm -- see comment above for justification.
11286e399cd1SDavidlohr Bueso 	 */
11296e399cd1SDavidlohr Bueso 	old_exe_file = rcu_dereference_raw(mm->exe_file);
113090f31d0eSKonstantin Khlebnikov 
113138646013SJiri Slaby 	if (new_exe_file)
113238646013SJiri Slaby 		get_file(new_exe_file);
113390f31d0eSKonstantin Khlebnikov 	rcu_assign_pointer(mm->exe_file, new_exe_file);
113490f31d0eSKonstantin Khlebnikov 	if (old_exe_file)
113590f31d0eSKonstantin Khlebnikov 		fput(old_exe_file);
113638646013SJiri Slaby }
113738646013SJiri Slaby 
113890f31d0eSKonstantin Khlebnikov /**
113990f31d0eSKonstantin Khlebnikov  * get_mm_exe_file - acquire a reference to the mm's executable file
114090f31d0eSKonstantin Khlebnikov  *
114190f31d0eSKonstantin Khlebnikov  * Returns %NULL if mm has no associated executable file.
114290f31d0eSKonstantin Khlebnikov  * User must release file via fput().
114390f31d0eSKonstantin Khlebnikov  */
114438646013SJiri Slaby struct file *get_mm_exe_file(struct mm_struct *mm)
114538646013SJiri Slaby {
114638646013SJiri Slaby 	struct file *exe_file;
114738646013SJiri Slaby 
114890f31d0eSKonstantin Khlebnikov 	rcu_read_lock();
114990f31d0eSKonstantin Khlebnikov 	exe_file = rcu_dereference(mm->exe_file);
115090f31d0eSKonstantin Khlebnikov 	if (exe_file && !get_file_rcu(exe_file))
115190f31d0eSKonstantin Khlebnikov 		exe_file = NULL;
115290f31d0eSKonstantin Khlebnikov 	rcu_read_unlock();
115338646013SJiri Slaby 	return exe_file;
115438646013SJiri Slaby }
115511163348SDavidlohr Bueso EXPORT_SYMBOL(get_mm_exe_file);
115638646013SJiri Slaby 
11571da177e4SLinus Torvalds /**
1158cd81a917SMateusz Guzik  * get_task_exe_file - acquire a reference to the task's executable file
1159cd81a917SMateusz Guzik  *
1160cd81a917SMateusz Guzik  * Returns %NULL if task's mm (if any) has no associated executable file or
1161cd81a917SMateusz Guzik  * this is a kernel thread with borrowed mm (see the comment above get_task_mm).
1162cd81a917SMateusz Guzik  * User must release file via fput().
1163cd81a917SMateusz Guzik  */
1164cd81a917SMateusz Guzik struct file *get_task_exe_file(struct task_struct *task)
1165cd81a917SMateusz Guzik {
1166cd81a917SMateusz Guzik 	struct file *exe_file = NULL;
1167cd81a917SMateusz Guzik 	struct mm_struct *mm;
1168cd81a917SMateusz Guzik 
1169cd81a917SMateusz Guzik 	task_lock(task);
1170cd81a917SMateusz Guzik 	mm = task->mm;
1171cd81a917SMateusz Guzik 	if (mm) {
1172cd81a917SMateusz Guzik 		if (!(task->flags & PF_KTHREAD))
1173cd81a917SMateusz Guzik 			exe_file = get_mm_exe_file(mm);
1174cd81a917SMateusz Guzik 	}
1175cd81a917SMateusz Guzik 	task_unlock(task);
1176cd81a917SMateusz Guzik 	return exe_file;
1177cd81a917SMateusz Guzik }
1178cd81a917SMateusz Guzik EXPORT_SYMBOL(get_task_exe_file);
1179cd81a917SMateusz Guzik 
1180cd81a917SMateusz Guzik /**
11811da177e4SLinus Torvalds  * get_task_mm - acquire a reference to the task's mm
11821da177e4SLinus Torvalds  *
1183246bb0b1SOleg Nesterov  * Returns %NULL if the task has no mm.  Checks PF_KTHREAD (meaning
11841da177e4SLinus Torvalds  * this kernel workthread has transiently adopted a user mm with use_mm,
11851da177e4SLinus Torvalds  * to do its AIO) is not set and if so returns a reference to it, after
11861da177e4SLinus Torvalds  * bumping up the use count.  User must release the mm via mmput()
11871da177e4SLinus Torvalds  * after use.  Typically used by /proc and ptrace.
11881da177e4SLinus Torvalds  */
11891da177e4SLinus Torvalds struct mm_struct *get_task_mm(struct task_struct *task)
11901da177e4SLinus Torvalds {
11911da177e4SLinus Torvalds 	struct mm_struct *mm;
11921da177e4SLinus Torvalds 
11931da177e4SLinus Torvalds 	task_lock(task);
11941da177e4SLinus Torvalds 	mm = task->mm;
11951da177e4SLinus Torvalds 	if (mm) {
1196246bb0b1SOleg Nesterov 		if (task->flags & PF_KTHREAD)
11971da177e4SLinus Torvalds 			mm = NULL;
11981da177e4SLinus Torvalds 		else
11993fce371bSVegard Nossum 			mmget(mm);
12001da177e4SLinus Torvalds 	}
12011da177e4SLinus Torvalds 	task_unlock(task);
12021da177e4SLinus Torvalds 	return mm;
12031da177e4SLinus Torvalds }
12041da177e4SLinus Torvalds EXPORT_SYMBOL_GPL(get_task_mm);
12051da177e4SLinus Torvalds 
12068cdb878dSChristopher Yeoh struct mm_struct *mm_access(struct task_struct *task, unsigned int mode)
12078cdb878dSChristopher Yeoh {
12088cdb878dSChristopher Yeoh 	struct mm_struct *mm;
12098cdb878dSChristopher Yeoh 	int err;
12108cdb878dSChristopher Yeoh 
12118cdb878dSChristopher Yeoh 	err =  mutex_lock_killable(&task->signal->cred_guard_mutex);
12128cdb878dSChristopher Yeoh 	if (err)
12138cdb878dSChristopher Yeoh 		return ERR_PTR(err);
12148cdb878dSChristopher Yeoh 
12158cdb878dSChristopher Yeoh 	mm = get_task_mm(task);
12168cdb878dSChristopher Yeoh 	if (mm && mm != current->mm &&
12178cdb878dSChristopher Yeoh 			!ptrace_may_access(task, mode)) {
12188cdb878dSChristopher Yeoh 		mmput(mm);
12198cdb878dSChristopher Yeoh 		mm = ERR_PTR(-EACCES);
12208cdb878dSChristopher Yeoh 	}
12218cdb878dSChristopher Yeoh 	mutex_unlock(&task->signal->cred_guard_mutex);
12228cdb878dSChristopher Yeoh 
12238cdb878dSChristopher Yeoh 	return mm;
12248cdb878dSChristopher Yeoh }
12258cdb878dSChristopher Yeoh 
122657b59c4aSOleg Nesterov static void complete_vfork_done(struct task_struct *tsk)
1227c415c3b4SOleg Nesterov {
1228d68b46feSOleg Nesterov 	struct completion *vfork;
1229c415c3b4SOleg Nesterov 
1230d68b46feSOleg Nesterov 	task_lock(tsk);
1231d68b46feSOleg Nesterov 	vfork = tsk->vfork_done;
1232d68b46feSOleg Nesterov 	if (likely(vfork)) {
1233c415c3b4SOleg Nesterov 		tsk->vfork_done = NULL;
1234d68b46feSOleg Nesterov 		complete(vfork);
1235d68b46feSOleg Nesterov 	}
1236d68b46feSOleg Nesterov 	task_unlock(tsk);
1237d68b46feSOleg Nesterov }
1238d68b46feSOleg Nesterov 
1239d68b46feSOleg Nesterov static int wait_for_vfork_done(struct task_struct *child,
1240d68b46feSOleg Nesterov 				struct completion *vfork)
1241d68b46feSOleg Nesterov {
1242d68b46feSOleg Nesterov 	int killed;
1243d68b46feSOleg Nesterov 
1244d68b46feSOleg Nesterov 	freezer_do_not_count();
124576f969e8SRoman Gushchin 	cgroup_enter_frozen();
1246d68b46feSOleg Nesterov 	killed = wait_for_completion_killable(vfork);
124776f969e8SRoman Gushchin 	cgroup_leave_frozen(false);
1248d68b46feSOleg Nesterov 	freezer_count();
1249d68b46feSOleg Nesterov 
1250d68b46feSOleg Nesterov 	if (killed) {
1251d68b46feSOleg Nesterov 		task_lock(child);
1252d68b46feSOleg Nesterov 		child->vfork_done = NULL;
1253d68b46feSOleg Nesterov 		task_unlock(child);
1254d68b46feSOleg Nesterov 	}
1255d68b46feSOleg Nesterov 
1256d68b46feSOleg Nesterov 	put_task_struct(child);
1257d68b46feSOleg Nesterov 	return killed;
1258c415c3b4SOleg Nesterov }
1259c415c3b4SOleg Nesterov 
12601da177e4SLinus Torvalds /* Please note the differences between mmput and mm_release.
12611da177e4SLinus Torvalds  * mmput is called whenever we stop holding onto a mm_struct,
12621da177e4SLinus Torvalds  * error success whatever.
12631da177e4SLinus Torvalds  *
12641da177e4SLinus Torvalds  * mm_release is called after a mm_struct has been removed
12651da177e4SLinus Torvalds  * from the current process.
12661da177e4SLinus Torvalds  *
12671da177e4SLinus Torvalds  * This difference is important for error handling, when we
12681da177e4SLinus Torvalds  * only half set up a mm_struct for a new process and need to restore
12691da177e4SLinus Torvalds  * the old one.  Because we mmput the new mm_struct before
12701da177e4SLinus Torvalds  * restoring the old one. . .
12711da177e4SLinus Torvalds  * Eric Biederman 10 January 1998
12721da177e4SLinus Torvalds  */
12731da177e4SLinus Torvalds void mm_release(struct task_struct *tsk, struct mm_struct *mm)
12741da177e4SLinus Torvalds {
12758141c7f3SLinus Torvalds 	/* Get rid of any futexes when releasing the mm */
12768141c7f3SLinus Torvalds #ifdef CONFIG_FUTEX
1277fc6b177dSPeter Zijlstra 	if (unlikely(tsk->robust_list)) {
12788141c7f3SLinus Torvalds 		exit_robust_list(tsk);
1279fc6b177dSPeter Zijlstra 		tsk->robust_list = NULL;
1280fc6b177dSPeter Zijlstra 	}
12818141c7f3SLinus Torvalds #ifdef CONFIG_COMPAT
1282fc6b177dSPeter Zijlstra 	if (unlikely(tsk->compat_robust_list)) {
12838141c7f3SLinus Torvalds 		compat_exit_robust_list(tsk);
1284fc6b177dSPeter Zijlstra 		tsk->compat_robust_list = NULL;
1285fc6b177dSPeter Zijlstra 	}
12868141c7f3SLinus Torvalds #endif
1287322a2c10SThomas Gleixner 	if (unlikely(!list_empty(&tsk->pi_state_list)))
1288322a2c10SThomas Gleixner 		exit_pi_state_list(tsk);
12898141c7f3SLinus Torvalds #endif
12908141c7f3SLinus Torvalds 
12910326f5a9SSrikar Dronamraju 	uprobe_free_utask(tsk);
12920326f5a9SSrikar Dronamraju 
12931da177e4SLinus Torvalds 	/* Get rid of any cached register state */
12941da177e4SLinus Torvalds 	deactivate_mm(tsk, mm);
12951da177e4SLinus Torvalds 
1296fec1d011SRoland McGrath 	/*
1297735f2770SMichal Hocko 	 * Signal userspace if we're not exiting with a core dump
1298735f2770SMichal Hocko 	 * because we want to leave the value intact for debugging
1299735f2770SMichal Hocko 	 * purposes.
1300fec1d011SRoland McGrath 	 */
13019c8a8228SEric Dumazet 	if (tsk->clear_child_tid) {
1302735f2770SMichal Hocko 		if (!(tsk->signal->flags & SIGNAL_GROUP_COREDUMP) &&
13039c8a8228SEric Dumazet 		    atomic_read(&mm->mm_users) > 1) {
13041da177e4SLinus Torvalds 			/*
13051da177e4SLinus Torvalds 			 * We don't check the error code - if userspace has
13061da177e4SLinus Torvalds 			 * not set up a proper pointer then tough luck.
13071da177e4SLinus Torvalds 			 */
13089c8a8228SEric Dumazet 			put_user(0, tsk->clear_child_tid);
13092de0db99SDominik Brodowski 			do_futex(tsk->clear_child_tid, FUTEX_WAKE,
13102de0db99SDominik Brodowski 					1, NULL, NULL, 0, 0);
13119c8a8228SEric Dumazet 		}
13129c8a8228SEric Dumazet 		tsk->clear_child_tid = NULL;
13131da177e4SLinus Torvalds 	}
1314f7505d64SKonstantin Khlebnikov 
1315f7505d64SKonstantin Khlebnikov 	/*
1316f7505d64SKonstantin Khlebnikov 	 * All done, finally we can wake up parent and return this mm to him.
1317f7505d64SKonstantin Khlebnikov 	 * Also kthread_stop() uses this completion for synchronization.
1318f7505d64SKonstantin Khlebnikov 	 */
1319f7505d64SKonstantin Khlebnikov 	if (tsk->vfork_done)
1320f7505d64SKonstantin Khlebnikov 		complete_vfork_done(tsk);
13211da177e4SLinus Torvalds }
13221da177e4SLinus Torvalds 
132313585fa0SNadav Amit /**
132413585fa0SNadav Amit  * dup_mm() - duplicates an existing mm structure
132513585fa0SNadav Amit  * @tsk: the task_struct with which the new mm will be associated.
132613585fa0SNadav Amit  * @oldmm: the mm to duplicate.
132713585fa0SNadav Amit  *
132813585fa0SNadav Amit  * Allocates a new mm structure and duplicates the provided @oldmm structure
132913585fa0SNadav Amit  * content into it.
133013585fa0SNadav Amit  *
133113585fa0SNadav Amit  * Return: the duplicated mm or NULL on failure.
1332a0a7ec30SJANAK DESAI  */
133313585fa0SNadav Amit static struct mm_struct *dup_mm(struct task_struct *tsk,
133413585fa0SNadav Amit 				struct mm_struct *oldmm)
1335a0a7ec30SJANAK DESAI {
133613585fa0SNadav Amit 	struct mm_struct *mm;
1337a0a7ec30SJANAK DESAI 	int err;
1338a0a7ec30SJANAK DESAI 
1339a0a7ec30SJANAK DESAI 	mm = allocate_mm();
1340a0a7ec30SJANAK DESAI 	if (!mm)
1341a0a7ec30SJANAK DESAI 		goto fail_nomem;
1342a0a7ec30SJANAK DESAI 
1343a0a7ec30SJANAK DESAI 	memcpy(mm, oldmm, sizeof(*mm));
1344a0a7ec30SJANAK DESAI 
1345bfedb589SEric W. Biederman 	if (!mm_init(mm, tsk, mm->user_ns))
1346a0a7ec30SJANAK DESAI 		goto fail_nomem;
1347a0a7ec30SJANAK DESAI 
1348a0a7ec30SJANAK DESAI 	err = dup_mmap(mm, oldmm);
1349a0a7ec30SJANAK DESAI 	if (err)
1350a0a7ec30SJANAK DESAI 		goto free_pt;
1351a0a7ec30SJANAK DESAI 
1352a0a7ec30SJANAK DESAI 	mm->hiwater_rss = get_mm_rss(mm);
1353a0a7ec30SJANAK DESAI 	mm->hiwater_vm = mm->total_vm;
1354a0a7ec30SJANAK DESAI 
1355801460d0SHiroshi Shimamoto 	if (mm->binfmt && !try_module_get(mm->binfmt->module))
1356801460d0SHiroshi Shimamoto 		goto free_pt;
1357801460d0SHiroshi Shimamoto 
1358a0a7ec30SJANAK DESAI 	return mm;
1359a0a7ec30SJANAK DESAI 
1360a0a7ec30SJANAK DESAI free_pt:
1361801460d0SHiroshi Shimamoto 	/* don't put binfmt in mmput, we haven't got module yet */
1362801460d0SHiroshi Shimamoto 	mm->binfmt = NULL;
1363c3f3ce04SAndrea Arcangeli 	mm_init_owner(mm, NULL);
1364a0a7ec30SJANAK DESAI 	mmput(mm);
1365a0a7ec30SJANAK DESAI 
1366a0a7ec30SJANAK DESAI fail_nomem:
1367a0a7ec30SJANAK DESAI 	return NULL;
1368a0a7ec30SJANAK DESAI }
1369a0a7ec30SJANAK DESAI 
13701da177e4SLinus Torvalds static int copy_mm(unsigned long clone_flags, struct task_struct *tsk)
13711da177e4SLinus Torvalds {
13721da177e4SLinus Torvalds 	struct mm_struct *mm, *oldmm;
13731da177e4SLinus Torvalds 	int retval;
13741da177e4SLinus Torvalds 
13751da177e4SLinus Torvalds 	tsk->min_flt = tsk->maj_flt = 0;
13761da177e4SLinus Torvalds 	tsk->nvcsw = tsk->nivcsw = 0;
137717406b82SMandeep Singh Baines #ifdef CONFIG_DETECT_HUNG_TASK
137817406b82SMandeep Singh Baines 	tsk->last_switch_count = tsk->nvcsw + tsk->nivcsw;
1379a2e51445SDmitry Vyukov 	tsk->last_switch_time = 0;
138017406b82SMandeep Singh Baines #endif
13811da177e4SLinus Torvalds 
13821da177e4SLinus Torvalds 	tsk->mm = NULL;
13831da177e4SLinus Torvalds 	tsk->active_mm = NULL;
13841da177e4SLinus Torvalds 
13851da177e4SLinus Torvalds 	/*
13861da177e4SLinus Torvalds 	 * Are we cloning a kernel thread?
13871da177e4SLinus Torvalds 	 *
13881da177e4SLinus Torvalds 	 * We need to steal a active VM for that..
13891da177e4SLinus Torvalds 	 */
13901da177e4SLinus Torvalds 	oldmm = current->mm;
13911da177e4SLinus Torvalds 	if (!oldmm)
13921da177e4SLinus Torvalds 		return 0;
13931da177e4SLinus Torvalds 
1394615d6e87SDavidlohr Bueso 	/* initialize the new vmacache entries */
1395615d6e87SDavidlohr Bueso 	vmacache_flush(tsk);
1396615d6e87SDavidlohr Bueso 
13971da177e4SLinus Torvalds 	if (clone_flags & CLONE_VM) {
13983fce371bSVegard Nossum 		mmget(oldmm);
13991da177e4SLinus Torvalds 		mm = oldmm;
14001da177e4SLinus Torvalds 		goto good_mm;
14011da177e4SLinus Torvalds 	}
14021da177e4SLinus Torvalds 
14031da177e4SLinus Torvalds 	retval = -ENOMEM;
140413585fa0SNadav Amit 	mm = dup_mm(tsk, current->mm);
14051da177e4SLinus Torvalds 	if (!mm)
14061da177e4SLinus Torvalds 		goto fail_nomem;
14071da177e4SLinus Torvalds 
14081da177e4SLinus Torvalds good_mm:
14091da177e4SLinus Torvalds 	tsk->mm = mm;
14101da177e4SLinus Torvalds 	tsk->active_mm = mm;
14111da177e4SLinus Torvalds 	return 0;
14121da177e4SLinus Torvalds 
14131da177e4SLinus Torvalds fail_nomem:
14141da177e4SLinus Torvalds 	return retval;
14151da177e4SLinus Torvalds }
14161da177e4SLinus Torvalds 
1417a39bc516SAlexey Dobriyan static int copy_fs(unsigned long clone_flags, struct task_struct *tsk)
14181da177e4SLinus Torvalds {
1419498052bbSAl Viro 	struct fs_struct *fs = current->fs;
14201da177e4SLinus Torvalds 	if (clone_flags & CLONE_FS) {
1421498052bbSAl Viro 		/* tsk->fs is already what we want */
14222a4419b5SNick Piggin 		spin_lock(&fs->lock);
1423498052bbSAl Viro 		if (fs->in_exec) {
14242a4419b5SNick Piggin 			spin_unlock(&fs->lock);
1425498052bbSAl Viro 			return -EAGAIN;
1426498052bbSAl Viro 		}
1427498052bbSAl Viro 		fs->users++;
14282a4419b5SNick Piggin 		spin_unlock(&fs->lock);
14291da177e4SLinus Torvalds 		return 0;
14301da177e4SLinus Torvalds 	}
1431498052bbSAl Viro 	tsk->fs = copy_fs_struct(fs);
14321da177e4SLinus Torvalds 	if (!tsk->fs)
14331da177e4SLinus Torvalds 		return -ENOMEM;
14341da177e4SLinus Torvalds 	return 0;
14351da177e4SLinus Torvalds }
14361da177e4SLinus Torvalds 
1437a016f338SJANAK DESAI static int copy_files(unsigned long clone_flags, struct task_struct *tsk)
1438a016f338SJANAK DESAI {
1439a016f338SJANAK DESAI 	struct files_struct *oldf, *newf;
1440a016f338SJANAK DESAI 	int error = 0;
1441a016f338SJANAK DESAI 
1442a016f338SJANAK DESAI 	/*
1443a016f338SJANAK DESAI 	 * A background process may not have any files ...
1444a016f338SJANAK DESAI 	 */
1445a016f338SJANAK DESAI 	oldf = current->files;
1446a016f338SJANAK DESAI 	if (!oldf)
1447a016f338SJANAK DESAI 		goto out;
1448a016f338SJANAK DESAI 
1449a016f338SJANAK DESAI 	if (clone_flags & CLONE_FILES) {
1450a016f338SJANAK DESAI 		atomic_inc(&oldf->count);
1451a016f338SJANAK DESAI 		goto out;
1452a016f338SJANAK DESAI 	}
1453a016f338SJANAK DESAI 
1454a016f338SJANAK DESAI 	newf = dup_fd(oldf, &error);
1455a016f338SJANAK DESAI 	if (!newf)
1456a016f338SJANAK DESAI 		goto out;
1457a016f338SJANAK DESAI 
1458a016f338SJANAK DESAI 	tsk->files = newf;
1459a016f338SJANAK DESAI 	error = 0;
1460a016f338SJANAK DESAI out:
1461a016f338SJANAK DESAI 	return error;
1462a016f338SJANAK DESAI }
1463a016f338SJANAK DESAI 
1464fadad878SJens Axboe static int copy_io(unsigned long clone_flags, struct task_struct *tsk)
1465fd0928dfSJens Axboe {
1466fd0928dfSJens Axboe #ifdef CONFIG_BLOCK
1467fd0928dfSJens Axboe 	struct io_context *ioc = current->io_context;
14686e736be7STejun Heo 	struct io_context *new_ioc;
1469fd0928dfSJens Axboe 
1470fd0928dfSJens Axboe 	if (!ioc)
1471fd0928dfSJens Axboe 		return 0;
1472fadad878SJens Axboe 	/*
1473fadad878SJens Axboe 	 * Share io context with parent, if CLONE_IO is set
1474fadad878SJens Axboe 	 */
1475fadad878SJens Axboe 	if (clone_flags & CLONE_IO) {
14763d48749dSTejun Heo 		ioc_task_link(ioc);
14773d48749dSTejun Heo 		tsk->io_context = ioc;
1478fadad878SJens Axboe 	} else if (ioprio_valid(ioc->ioprio)) {
14796e736be7STejun Heo 		new_ioc = get_task_io_context(tsk, GFP_KERNEL, NUMA_NO_NODE);
14806e736be7STejun Heo 		if (unlikely(!new_ioc))
1481fd0928dfSJens Axboe 			return -ENOMEM;
1482fd0928dfSJens Axboe 
14836e736be7STejun Heo 		new_ioc->ioprio = ioc->ioprio;
148411a3122fSTejun Heo 		put_io_context(new_ioc);
1485fd0928dfSJens Axboe 	}
1486fd0928dfSJens Axboe #endif
1487fd0928dfSJens Axboe 	return 0;
1488fd0928dfSJens Axboe }
1489fd0928dfSJens Axboe 
1490a39bc516SAlexey Dobriyan static int copy_sighand(unsigned long clone_flags, struct task_struct *tsk)
14911da177e4SLinus Torvalds {
14921da177e4SLinus Torvalds 	struct sighand_struct *sig;
14931da177e4SLinus Torvalds 
149460348802SZhaolei 	if (clone_flags & CLONE_SIGHAND) {
1495d036bda7SElena Reshetova 		refcount_inc(&current->sighand->count);
14961da177e4SLinus Torvalds 		return 0;
14971da177e4SLinus Torvalds 	}
14981da177e4SLinus Torvalds 	sig = kmem_cache_alloc(sighand_cachep, GFP_KERNEL);
1499e56d0903SIngo Molnar 	rcu_assign_pointer(tsk->sighand, sig);
15001da177e4SLinus Torvalds 	if (!sig)
15011da177e4SLinus Torvalds 		return -ENOMEM;
15029d7fb042SPeter Zijlstra 
1503d036bda7SElena Reshetova 	refcount_set(&sig->count, 1);
150406e62a46SJann Horn 	spin_lock_irq(&current->sighand->siglock);
15051da177e4SLinus Torvalds 	memcpy(sig->action, current->sighand->action, sizeof(sig->action));
150606e62a46SJann Horn 	spin_unlock_irq(&current->sighand->siglock);
15071da177e4SLinus Torvalds 	return 0;
15081da177e4SLinus Torvalds }
15091da177e4SLinus Torvalds 
1510a7e5328aSOleg Nesterov void __cleanup_sighand(struct sighand_struct *sighand)
1511c81addc9SOleg Nesterov {
1512d036bda7SElena Reshetova 	if (refcount_dec_and_test(&sighand->count)) {
1513d80e731eSOleg Nesterov 		signalfd_cleanup(sighand);
1514392809b2SOleg Nesterov 		/*
15155f0d5a3aSPaul E. McKenney 		 * sighand_cachep is SLAB_TYPESAFE_BY_RCU so we can free it
1516392809b2SOleg Nesterov 		 * without an RCU grace period, see __lock_task_sighand().
1517392809b2SOleg Nesterov 		 */
1518c81addc9SOleg Nesterov 		kmem_cache_free(sighand_cachep, sighand);
1519c81addc9SOleg Nesterov 	}
1520d80e731eSOleg Nesterov }
1521c81addc9SOleg Nesterov 
1522b18b6a9cSNicolas Pitre #ifdef CONFIG_POSIX_TIMERS
1523f06febc9SFrank Mayhar /*
1524f06febc9SFrank Mayhar  * Initialize POSIX timer handling for a thread group.
1525f06febc9SFrank Mayhar  */
1526f06febc9SFrank Mayhar static void posix_cpu_timers_init_group(struct signal_struct *sig)
1527f06febc9SFrank Mayhar {
152878d7d407SJiri Slaby 	unsigned long cpu_limit;
152978d7d407SJiri Slaby 
1530316c1608SJason Low 	cpu_limit = READ_ONCE(sig->rlim[RLIMIT_CPU].rlim_cur);
153178d7d407SJiri Slaby 	if (cpu_limit != RLIM_INFINITY) {
1532ebd7e7fcSFrederic Weisbecker 		sig->cputime_expires.prof_exp = cpu_limit * NSEC_PER_SEC;
1533d5c373ebSJason Low 		sig->cputimer.running = true;
15346279a751SOleg Nesterov 	}
15356279a751SOleg Nesterov 
1536f06febc9SFrank Mayhar 	/* The timer lists. */
1537f06febc9SFrank Mayhar 	INIT_LIST_HEAD(&sig->cpu_timers[0]);
1538f06febc9SFrank Mayhar 	INIT_LIST_HEAD(&sig->cpu_timers[1]);
1539f06febc9SFrank Mayhar 	INIT_LIST_HEAD(&sig->cpu_timers[2]);
1540f06febc9SFrank Mayhar }
1541b18b6a9cSNicolas Pitre #else
1542b18b6a9cSNicolas Pitre static inline void posix_cpu_timers_init_group(struct signal_struct *sig) { }
1543b18b6a9cSNicolas Pitre #endif
1544f06febc9SFrank Mayhar 
1545a39bc516SAlexey Dobriyan static int copy_signal(unsigned long clone_flags, struct task_struct *tsk)
15461da177e4SLinus Torvalds {
15471da177e4SLinus Torvalds 	struct signal_struct *sig;
15481da177e4SLinus Torvalds 
15494ab6c083SOleg Nesterov 	if (clone_flags & CLONE_THREAD)
1550490dea45SPeter Zijlstra 		return 0;
15516279a751SOleg Nesterov 
1552a56704efSVeaceslav Falico 	sig = kmem_cache_zalloc(signal_cachep, GFP_KERNEL);
15531da177e4SLinus Torvalds 	tsk->signal = sig;
15541da177e4SLinus Torvalds 	if (!sig)
15551da177e4SLinus Torvalds 		return -ENOMEM;
15561da177e4SLinus Torvalds 
1557b3ac022cSOleg Nesterov 	sig->nr_threads = 1;
15581da177e4SLinus Torvalds 	atomic_set(&sig->live, 1);
155960d4de3fSElena Reshetova 	refcount_set(&sig->sigcnt, 1);
15600c740d0aSOleg Nesterov 
15610c740d0aSOleg Nesterov 	/* list_add(thread_node, thread_head) without INIT_LIST_HEAD() */
15620c740d0aSOleg Nesterov 	sig->thread_head = (struct list_head)LIST_HEAD_INIT(tsk->thread_node);
15630c740d0aSOleg Nesterov 	tsk->thread_node = (struct list_head)LIST_HEAD_INIT(sig->thread_head);
15640c740d0aSOleg Nesterov 
15651da177e4SLinus Torvalds 	init_waitqueue_head(&sig->wait_chldexit);
1566db51aeccSOleg Nesterov 	sig->curr_target = tsk;
15671da177e4SLinus Torvalds 	init_sigpending(&sig->shared_pending);
1568c3ad2c3bSEric W. Biederman 	INIT_HLIST_HEAD(&sig->multiprocess);
1569e78c3496SRik van Riel 	seqlock_init(&sig->stats_lock);
15709d7fb042SPeter Zijlstra 	prev_cputime_init(&sig->prev_cputime);
15711da177e4SLinus Torvalds 
1572baa73d9eSNicolas Pitre #ifdef CONFIG_POSIX_TIMERS
1573b18b6a9cSNicolas Pitre 	INIT_LIST_HEAD(&sig->posix_timers);
1574c9cb2e3dSThomas Gleixner 	hrtimer_init(&sig->real_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
15751da177e4SLinus Torvalds 	sig->real_timer.function = it_real_fn;
1576baa73d9eSNicolas Pitre #endif
15771da177e4SLinus Torvalds 
15781da177e4SLinus Torvalds 	task_lock(current->group_leader);
15791da177e4SLinus Torvalds 	memcpy(sig->rlim, current->signal->rlim, sizeof sig->rlim);
15801da177e4SLinus Torvalds 	task_unlock(current->group_leader);
15811da177e4SLinus Torvalds 
15826279a751SOleg Nesterov 	posix_cpu_timers_init_group(sig);
15836279a751SOleg Nesterov 
1584522ed776SMiloslav Trmac 	tty_audit_fork(sig);
15855091faa4SMike Galbraith 	sched_autogroup_fork(sig);
1586522ed776SMiloslav Trmac 
1587a63d83f4SDavid Rientjes 	sig->oom_score_adj = current->signal->oom_score_adj;
1588dabb16f6SMandeep Singh Baines 	sig->oom_score_adj_min = current->signal->oom_score_adj_min;
158928b83c51SKOSAKI Motohiro 
15909b1bf12dSKOSAKI Motohiro 	mutex_init(&sig->cred_guard_mutex);
15919b1bf12dSKOSAKI Motohiro 
15921da177e4SLinus Torvalds 	return 0;
15931da177e4SLinus Torvalds }
15941da177e4SLinus Torvalds 
1595dbd95212SKees Cook static void copy_seccomp(struct task_struct *p)
1596dbd95212SKees Cook {
1597dbd95212SKees Cook #ifdef CONFIG_SECCOMP
1598dbd95212SKees Cook 	/*
1599dbd95212SKees Cook 	 * Must be called with sighand->lock held, which is common to
1600dbd95212SKees Cook 	 * all threads in the group. Holding cred_guard_mutex is not
1601dbd95212SKees Cook 	 * needed because this new task is not yet running and cannot
1602dbd95212SKees Cook 	 * be racing exec.
1603dbd95212SKees Cook 	 */
160469f6a34bSGuenter Roeck 	assert_spin_locked(&current->sighand->siglock);
1605dbd95212SKees Cook 
1606dbd95212SKees Cook 	/* Ref-count the new filter user, and assign it. */
1607dbd95212SKees Cook 	get_seccomp_filter(current);
1608dbd95212SKees Cook 	p->seccomp = current->seccomp;
1609dbd95212SKees Cook 
1610dbd95212SKees Cook 	/*
1611dbd95212SKees Cook 	 * Explicitly enable no_new_privs here in case it got set
1612dbd95212SKees Cook 	 * between the task_struct being duplicated and holding the
1613dbd95212SKees Cook 	 * sighand lock. The seccomp state and nnp must be in sync.
1614dbd95212SKees Cook 	 */
1615dbd95212SKees Cook 	if (task_no_new_privs(current))
1616dbd95212SKees Cook 		task_set_no_new_privs(p);
1617dbd95212SKees Cook 
1618dbd95212SKees Cook 	/*
1619dbd95212SKees Cook 	 * If the parent gained a seccomp mode after copying thread
1620dbd95212SKees Cook 	 * flags and between before we held the sighand lock, we have
1621dbd95212SKees Cook 	 * to manually enable the seccomp thread flag here.
1622dbd95212SKees Cook 	 */
1623dbd95212SKees Cook 	if (p->seccomp.mode != SECCOMP_MODE_DISABLED)
1624dbd95212SKees Cook 		set_tsk_thread_flag(p, TIF_SECCOMP);
1625dbd95212SKees Cook #endif
1626dbd95212SKees Cook }
1627dbd95212SKees Cook 
162817da2bd9SHeiko Carstens SYSCALL_DEFINE1(set_tid_address, int __user *, tidptr)
16291da177e4SLinus Torvalds {
16301da177e4SLinus Torvalds 	current->clear_child_tid = tidptr;
16311da177e4SLinus Torvalds 
1632b488893aSPavel Emelyanov 	return task_pid_vnr(current);
16331da177e4SLinus Torvalds }
16341da177e4SLinus Torvalds 
1635a39bc516SAlexey Dobriyan static void rt_mutex_init_task(struct task_struct *p)
163623f78d4aSIngo Molnar {
16371d615482SThomas Gleixner 	raw_spin_lock_init(&p->pi_lock);
1638e29e175bSZilvinas Valinskas #ifdef CONFIG_RT_MUTEXES
1639a23ba907SDavidlohr Bueso 	p->pi_waiters = RB_ROOT_CACHED;
1640e96a7705SXunlei Pang 	p->pi_top_task = NULL;
164123f78d4aSIngo Molnar 	p->pi_blocked_on = NULL;
164223f78d4aSIngo Molnar #endif
164323f78d4aSIngo Molnar }
164423f78d4aSIngo Molnar 
1645b18b6a9cSNicolas Pitre #ifdef CONFIG_POSIX_TIMERS
16461da177e4SLinus Torvalds /*
1647f06febc9SFrank Mayhar  * Initialize POSIX timer handling for a single task.
1648f06febc9SFrank Mayhar  */
1649f06febc9SFrank Mayhar static void posix_cpu_timers_init(struct task_struct *tsk)
1650f06febc9SFrank Mayhar {
165164861634SMartin Schwidefsky 	tsk->cputime_expires.prof_exp = 0;
165264861634SMartin Schwidefsky 	tsk->cputime_expires.virt_exp = 0;
1653f06febc9SFrank Mayhar 	tsk->cputime_expires.sched_exp = 0;
1654f06febc9SFrank Mayhar 	INIT_LIST_HEAD(&tsk->cpu_timers[0]);
1655f06febc9SFrank Mayhar 	INIT_LIST_HEAD(&tsk->cpu_timers[1]);
1656f06febc9SFrank Mayhar 	INIT_LIST_HEAD(&tsk->cpu_timers[2]);
1657f06febc9SFrank Mayhar }
1658b18b6a9cSNicolas Pitre #else
1659b18b6a9cSNicolas Pitre static inline void posix_cpu_timers_init(struct task_struct *tsk) { }
1660b18b6a9cSNicolas Pitre #endif
1661f06febc9SFrank Mayhar 
16622c470475SEric W. Biederman static inline void init_task_pid_links(struct task_struct *task)
16632c470475SEric W. Biederman {
16642c470475SEric W. Biederman 	enum pid_type type;
16652c470475SEric W. Biederman 
16662c470475SEric W. Biederman 	for (type = PIDTYPE_PID; type < PIDTYPE_MAX; ++type) {
16672c470475SEric W. Biederman 		INIT_HLIST_NODE(&task->pid_links[type]);
16682c470475SEric W. Biederman 	}
16692c470475SEric W. Biederman }
16702c470475SEric W. Biederman 
167181907739SOleg Nesterov static inline void
167281907739SOleg Nesterov init_task_pid(struct task_struct *task, enum pid_type type, struct pid *pid)
167381907739SOleg Nesterov {
16742c470475SEric W. Biederman 	if (type == PIDTYPE_PID)
16752c470475SEric W. Biederman 		task->thread_pid = pid;
16762c470475SEric W. Biederman 	else
16772c470475SEric W. Biederman 		task->signal->pids[type] = pid;
167881907739SOleg Nesterov }
167981907739SOleg Nesterov 
16806bfbaa51SIngo Molnar static inline void rcu_copy_process(struct task_struct *p)
16816bfbaa51SIngo Molnar {
16826bfbaa51SIngo Molnar #ifdef CONFIG_PREEMPT_RCU
16836bfbaa51SIngo Molnar 	p->rcu_read_lock_nesting = 0;
16846bfbaa51SIngo Molnar 	p->rcu_read_unlock_special.s = 0;
16856bfbaa51SIngo Molnar 	p->rcu_blocked_node = NULL;
16866bfbaa51SIngo Molnar 	INIT_LIST_HEAD(&p->rcu_node_entry);
16876bfbaa51SIngo Molnar #endif /* #ifdef CONFIG_PREEMPT_RCU */
16886bfbaa51SIngo Molnar #ifdef CONFIG_TASKS_RCU
16896bfbaa51SIngo Molnar 	p->rcu_tasks_holdout = false;
16906bfbaa51SIngo Molnar 	INIT_LIST_HEAD(&p->rcu_tasks_holdout_list);
16916bfbaa51SIngo Molnar 	p->rcu_tasks_idle_cpu = -1;
16926bfbaa51SIngo Molnar #endif /* #ifdef CONFIG_TASKS_RCU */
16936bfbaa51SIngo Molnar }
16946bfbaa51SIngo Molnar 
1695b3e58382SChristian Brauner static int pidfd_release(struct inode *inode, struct file *file)
1696b3e58382SChristian Brauner {
1697b3e58382SChristian Brauner 	struct pid *pid = file->private_data;
1698b3e58382SChristian Brauner 
1699b3e58382SChristian Brauner 	file->private_data = NULL;
1700b3e58382SChristian Brauner 	put_pid(pid);
1701b3e58382SChristian Brauner 	return 0;
1702b3e58382SChristian Brauner }
1703b3e58382SChristian Brauner 
1704b3e58382SChristian Brauner #ifdef CONFIG_PROC_FS
1705b3e58382SChristian Brauner static void pidfd_show_fdinfo(struct seq_file *m, struct file *f)
1706b3e58382SChristian Brauner {
1707b3e58382SChristian Brauner 	struct pid_namespace *ns = proc_pid_ns(file_inode(m->file));
1708b3e58382SChristian Brauner 	struct pid *pid = f->private_data;
1709b3e58382SChristian Brauner 
1710b3e58382SChristian Brauner 	seq_put_decimal_ull(m, "Pid:\t", pid_nr_ns(pid, ns));
1711b3e58382SChristian Brauner 	seq_putc(m, '\n');
1712b3e58382SChristian Brauner }
1713b3e58382SChristian Brauner #endif
1714b3e58382SChristian Brauner 
1715b53b0b9dSJoel Fernandes (Google) /*
1716b53b0b9dSJoel Fernandes (Google)  * Poll support for process exit notification.
1717b53b0b9dSJoel Fernandes (Google)  */
1718b53b0b9dSJoel Fernandes (Google) static unsigned int pidfd_poll(struct file *file, struct poll_table_struct *pts)
1719b53b0b9dSJoel Fernandes (Google) {
1720b53b0b9dSJoel Fernandes (Google) 	struct task_struct *task;
1721b53b0b9dSJoel Fernandes (Google) 	struct pid *pid = file->private_data;
1722b53b0b9dSJoel Fernandes (Google) 	int poll_flags = 0;
1723b53b0b9dSJoel Fernandes (Google) 
1724b53b0b9dSJoel Fernandes (Google) 	poll_wait(file, &pid->wait_pidfd, pts);
1725b53b0b9dSJoel Fernandes (Google) 
1726b53b0b9dSJoel Fernandes (Google) 	rcu_read_lock();
1727b53b0b9dSJoel Fernandes (Google) 	task = pid_task(pid, PIDTYPE_PID);
1728b53b0b9dSJoel Fernandes (Google) 	/*
1729b53b0b9dSJoel Fernandes (Google) 	 * Inform pollers only when the whole thread group exits.
1730b53b0b9dSJoel Fernandes (Google) 	 * If the thread group leader exits before all other threads in the
1731b53b0b9dSJoel Fernandes (Google) 	 * group, then poll(2) should block, similar to the wait(2) family.
1732b53b0b9dSJoel Fernandes (Google) 	 */
1733b53b0b9dSJoel Fernandes (Google) 	if (!task || (task->exit_state && thread_group_empty(task)))
1734b53b0b9dSJoel Fernandes (Google) 		poll_flags = POLLIN | POLLRDNORM;
1735b53b0b9dSJoel Fernandes (Google) 	rcu_read_unlock();
1736b53b0b9dSJoel Fernandes (Google) 
1737b53b0b9dSJoel Fernandes (Google) 	return poll_flags;
1738b53b0b9dSJoel Fernandes (Google) }
1739b53b0b9dSJoel Fernandes (Google) 
1740b3e58382SChristian Brauner const struct file_operations pidfd_fops = {
1741b3e58382SChristian Brauner 	.release = pidfd_release,
1742b53b0b9dSJoel Fernandes (Google) 	.poll = pidfd_poll,
1743b3e58382SChristian Brauner #ifdef CONFIG_PROC_FS
1744b3e58382SChristian Brauner 	.show_fdinfo = pidfd_show_fdinfo,
1745b3e58382SChristian Brauner #endif
1746b3e58382SChristian Brauner };
1747b3e58382SChristian Brauner 
1748c3f3ce04SAndrea Arcangeli static void __delayed_free_task(struct rcu_head *rhp)
1749c3f3ce04SAndrea Arcangeli {
1750c3f3ce04SAndrea Arcangeli 	struct task_struct *tsk = container_of(rhp, struct task_struct, rcu);
1751c3f3ce04SAndrea Arcangeli 
1752c3f3ce04SAndrea Arcangeli 	free_task(tsk);
1753c3f3ce04SAndrea Arcangeli }
1754c3f3ce04SAndrea Arcangeli 
1755c3f3ce04SAndrea Arcangeli static __always_inline void delayed_free_task(struct task_struct *tsk)
1756c3f3ce04SAndrea Arcangeli {
1757c3f3ce04SAndrea Arcangeli 	if (IS_ENABLED(CONFIG_MEMCG))
1758c3f3ce04SAndrea Arcangeli 		call_rcu(&tsk->rcu, __delayed_free_task);
1759c3f3ce04SAndrea Arcangeli 	else
1760c3f3ce04SAndrea Arcangeli 		free_task(tsk);
1761c3f3ce04SAndrea Arcangeli }
1762c3f3ce04SAndrea Arcangeli 
1763f06febc9SFrank Mayhar /*
17641da177e4SLinus Torvalds  * This creates a new process as a copy of the old one,
17651da177e4SLinus Torvalds  * but does not actually start it yet.
17661da177e4SLinus Torvalds  *
17671da177e4SLinus Torvalds  * It copies the registers, and all the appropriate
17681da177e4SLinus Torvalds  * parts of the process environment (as per the clone
17691da177e4SLinus Torvalds  * flags). The actual kick-off is left to the caller.
17701da177e4SLinus Torvalds  */
17710766f788SEmese Revfy static __latent_entropy struct task_struct *copy_process(
177209a05394SRoland McGrath 					struct pid *pid,
17733033f14aSJosh Triplett 					int trace,
17747f192e3cSChristian Brauner 					int node,
17757f192e3cSChristian Brauner 					struct kernel_clone_args *args)
17761da177e4SLinus Torvalds {
1777b3e58382SChristian Brauner 	int pidfd = -1, retval;
1778a24efe62SMariusz Kozlowski 	struct task_struct *p;
1779c3ad2c3bSEric W. Biederman 	struct multiprocess_signals delayed;
17806fd2fe49SAl Viro 	struct file *pidfile = NULL;
17817f192e3cSChristian Brauner 	u64 clone_flags = args->flags;
17821da177e4SLinus Torvalds 
1783667b6094SMarcos Paulo de Souza 	/*
1784667b6094SMarcos Paulo de Souza 	 * Don't allow sharing the root directory with processes in a different
1785667b6094SMarcos Paulo de Souza 	 * namespace
1786667b6094SMarcos Paulo de Souza 	 */
17871da177e4SLinus Torvalds 	if ((clone_flags & (CLONE_NEWNS|CLONE_FS)) == (CLONE_NEWNS|CLONE_FS))
17881da177e4SLinus Torvalds 		return ERR_PTR(-EINVAL);
17891da177e4SLinus Torvalds 
1790e66eded8SEric W. Biederman 	if ((clone_flags & (CLONE_NEWUSER|CLONE_FS)) == (CLONE_NEWUSER|CLONE_FS))
1791e66eded8SEric W. Biederman 		return ERR_PTR(-EINVAL);
1792e66eded8SEric W. Biederman 
17931da177e4SLinus Torvalds 	/*
17941da177e4SLinus Torvalds 	 * Thread groups must share signals as well, and detached threads
17951da177e4SLinus Torvalds 	 * can only be started up within the thread group.
17961da177e4SLinus Torvalds 	 */
17971da177e4SLinus Torvalds 	if ((clone_flags & CLONE_THREAD) && !(clone_flags & CLONE_SIGHAND))
17981da177e4SLinus Torvalds 		return ERR_PTR(-EINVAL);
17991da177e4SLinus Torvalds 
18001da177e4SLinus Torvalds 	/*
18011da177e4SLinus Torvalds 	 * Shared signal handlers imply shared VM. By way of the above,
18021da177e4SLinus Torvalds 	 * thread groups also imply shared VM. Blocking this case allows
18031da177e4SLinus Torvalds 	 * for various simplifications in other code.
18041da177e4SLinus Torvalds 	 */
18051da177e4SLinus Torvalds 	if ((clone_flags & CLONE_SIGHAND) && !(clone_flags & CLONE_VM))
18061da177e4SLinus Torvalds 		return ERR_PTR(-EINVAL);
18071da177e4SLinus Torvalds 
1808123be07bSSukadev Bhattiprolu 	/*
1809123be07bSSukadev Bhattiprolu 	 * Siblings of global init remain as zombies on exit since they are
1810123be07bSSukadev Bhattiprolu 	 * not reaped by their parent (swapper). To solve this and to avoid
1811123be07bSSukadev Bhattiprolu 	 * multi-rooted process trees, prevent global and container-inits
1812123be07bSSukadev Bhattiprolu 	 * from creating siblings.
1813123be07bSSukadev Bhattiprolu 	 */
1814123be07bSSukadev Bhattiprolu 	if ((clone_flags & CLONE_PARENT) &&
1815123be07bSSukadev Bhattiprolu 				current->signal->flags & SIGNAL_UNKILLABLE)
1816123be07bSSukadev Bhattiprolu 		return ERR_PTR(-EINVAL);
1817123be07bSSukadev Bhattiprolu 
18188382fcacSEric W. Biederman 	/*
181940a0d32dSOleg Nesterov 	 * If the new process will be in a different pid or user namespace
1820faf00da5SEric W. Biederman 	 * do not allow it to share a thread group with the forking task.
18218382fcacSEric W. Biederman 	 */
1822faf00da5SEric W. Biederman 	if (clone_flags & CLONE_THREAD) {
182340a0d32dSOleg Nesterov 		if ((clone_flags & (CLONE_NEWUSER | CLONE_NEWPID)) ||
182440a0d32dSOleg Nesterov 		    (task_active_pid_ns(current) !=
1825c2b1df2eSAndy Lutomirski 				current->nsproxy->pid_ns_for_children))
18268382fcacSEric W. Biederman 			return ERR_PTR(-EINVAL);
182740a0d32dSOleg Nesterov 	}
18288382fcacSEric W. Biederman 
1829b3e58382SChristian Brauner 	if (clone_flags & CLONE_PIDFD) {
1830b3e58382SChristian Brauner 		/*
1831b3e58382SChristian Brauner 		 * - CLONE_DETACHED is blocked so that we can potentially
1832b3e58382SChristian Brauner 		 *   reuse it later for CLONE_PIDFD.
1833b3e58382SChristian Brauner 		 * - CLONE_THREAD is blocked until someone really needs it.
1834b3e58382SChristian Brauner 		 */
18357f192e3cSChristian Brauner 		if (clone_flags & (CLONE_DETACHED | CLONE_THREAD))
1836b3e58382SChristian Brauner 			return ERR_PTR(-EINVAL);
1837b3e58382SChristian Brauner 	}
1838b3e58382SChristian Brauner 
1839c3ad2c3bSEric W. Biederman 	/*
1840c3ad2c3bSEric W. Biederman 	 * Force any signals received before this point to be delivered
1841c3ad2c3bSEric W. Biederman 	 * before the fork happens.  Collect up signals sent to multiple
1842c3ad2c3bSEric W. Biederman 	 * processes that happen during the fork and delay them so that
1843c3ad2c3bSEric W. Biederman 	 * they appear to happen after the fork.
1844c3ad2c3bSEric W. Biederman 	 */
1845c3ad2c3bSEric W. Biederman 	sigemptyset(&delayed.signal);
1846c3ad2c3bSEric W. Biederman 	INIT_HLIST_NODE(&delayed.node);
1847c3ad2c3bSEric W. Biederman 
1848c3ad2c3bSEric W. Biederman 	spin_lock_irq(&current->sighand->siglock);
1849c3ad2c3bSEric W. Biederman 	if (!(clone_flags & CLONE_THREAD))
1850c3ad2c3bSEric W. Biederman 		hlist_add_head(&delayed.node, &current->signal->multiprocess);
1851c3ad2c3bSEric W. Biederman 	recalc_sigpending();
1852c3ad2c3bSEric W. Biederman 	spin_unlock_irq(&current->sighand->siglock);
1853c3ad2c3bSEric W. Biederman 	retval = -ERESTARTNOINTR;
1854c3ad2c3bSEric W. Biederman 	if (signal_pending(current))
1855c3ad2c3bSEric W. Biederman 		goto fork_out;
1856c3ad2c3bSEric W. Biederman 
18571da177e4SLinus Torvalds 	retval = -ENOMEM;
1858725fc629SAndi Kleen 	p = dup_task_struct(current, node);
18591da177e4SLinus Torvalds 	if (!p)
18601da177e4SLinus Torvalds 		goto fork_out;
18611da177e4SLinus Torvalds 
18624d6501dcSVegard Nossum 	/*
18634d6501dcSVegard Nossum 	 * This _must_ happen before we call free_task(), i.e. before we jump
18644d6501dcSVegard Nossum 	 * to any of the bad_fork_* labels. This is to avoid freeing
18654d6501dcSVegard Nossum 	 * p->set_child_tid which is (ab)used as a kthread's data pointer for
18664d6501dcSVegard Nossum 	 * kernel threads (PF_KTHREAD).
18674d6501dcSVegard Nossum 	 */
18687f192e3cSChristian Brauner 	p->set_child_tid = (clone_flags & CLONE_CHILD_SETTID) ? args->child_tid : NULL;
18694d6501dcSVegard Nossum 	/*
18704d6501dcSVegard Nossum 	 * Clear TID on mm_release()?
18714d6501dcSVegard Nossum 	 */
18727f192e3cSChristian Brauner 	p->clear_child_tid = (clone_flags & CLONE_CHILD_CLEARTID) ? args->child_tid : NULL;
18734d6501dcSVegard Nossum 
1874f7e8b616SSteven Rostedt 	ftrace_graph_init_task(p);
1875f7e8b616SSteven Rostedt 
1876bea493a0SPeter Zijlstra 	rt_mutex_init_task(p);
1877bea493a0SPeter Zijlstra 
1878d12c1a37SIngo Molnar #ifdef CONFIG_PROVE_LOCKING
1879de30a2b3SIngo Molnar 	DEBUG_LOCKS_WARN_ON(!p->hardirqs_enabled);
1880de30a2b3SIngo Molnar 	DEBUG_LOCKS_WARN_ON(!p->softirqs_enabled);
1881de30a2b3SIngo Molnar #endif
18821da177e4SLinus Torvalds 	retval = -EAGAIN;
18833b11a1deSDavid Howells 	if (atomic_read(&p->real_cred->user->processes) >=
188478d7d407SJiri Slaby 			task_rlimit(p, RLIMIT_NPROC)) {
1885b57922b6SEric Paris 		if (p->real_cred->user != INIT_USER &&
1886b57922b6SEric Paris 		    !capable(CAP_SYS_RESOURCE) && !capable(CAP_SYS_ADMIN))
18871da177e4SLinus Torvalds 			goto bad_fork_free;
18881da177e4SLinus Torvalds 	}
188972fa5997SVasiliy Kulikov 	current->flags &= ~PF_NPROC_EXCEEDED;
18901da177e4SLinus Torvalds 
1891f1752eecSDavid Howells 	retval = copy_creds(p, clone_flags);
1892f1752eecSDavid Howells 	if (retval < 0)
1893f1752eecSDavid Howells 		goto bad_fork_free;
18941da177e4SLinus Torvalds 
18951da177e4SLinus Torvalds 	/*
18961da177e4SLinus Torvalds 	 * If multiple threads are within copy_process(), then this check
18971da177e4SLinus Torvalds 	 * triggers too late. This doesn't hurt, the check is only there
18981da177e4SLinus Torvalds 	 * to stop root fork bombs.
18991da177e4SLinus Torvalds 	 */
190004ec93feSLi Zefan 	retval = -EAGAIN;
19011da177e4SLinus Torvalds 	if (nr_threads >= max_threads)
19021da177e4SLinus Torvalds 		goto bad_fork_cleanup_count;
19031da177e4SLinus Torvalds 
1904ca74e92bSShailabh Nagar 	delayacct_tsk_init(p);	/* Must remain after dup_task_struct() */
1905c1de45caSPeter Zijlstra 	p->flags &= ~(PF_SUPERPRIV | PF_WQ_WORKER | PF_IDLE);
1906514ddb44SDavid Rientjes 	p->flags |= PF_FORKNOEXEC;
19071da177e4SLinus Torvalds 	INIT_LIST_HEAD(&p->children);
19081da177e4SLinus Torvalds 	INIT_LIST_HEAD(&p->sibling);
1909f41d911fSPaul E. McKenney 	rcu_copy_process(p);
19101da177e4SLinus Torvalds 	p->vfork_done = NULL;
19111da177e4SLinus Torvalds 	spin_lock_init(&p->alloc_lock);
19121da177e4SLinus Torvalds 
19131da177e4SLinus Torvalds 	init_sigpending(&p->pending);
19141da177e4SLinus Torvalds 
191564861634SMartin Schwidefsky 	p->utime = p->stime = p->gtime = 0;
191640565b5aSStanislaw Gruszka #ifdef CONFIG_ARCH_HAS_SCALED_CPUTIME
191764861634SMartin Schwidefsky 	p->utimescaled = p->stimescaled = 0;
191840565b5aSStanislaw Gruszka #endif
19199d7fb042SPeter Zijlstra 	prev_cputime_init(&p->prev_cputime);
19209d7fb042SPeter Zijlstra 
19216a61671bSFrederic Weisbecker #ifdef CONFIG_VIRT_CPU_ACCOUNTING_GEN
1922bac5b6b6SFrederic Weisbecker 	seqcount_init(&p->vtime.seqcount);
1923bac5b6b6SFrederic Weisbecker 	p->vtime.starttime = 0;
1924bac5b6b6SFrederic Weisbecker 	p->vtime.state = VTIME_INACTIVE;
19256a61671bSFrederic Weisbecker #endif
19266a61671bSFrederic Weisbecker 
1927a3a2e76cSKAMEZAWA Hiroyuki #if defined(SPLIT_RSS_COUNTING)
1928a3a2e76cSKAMEZAWA Hiroyuki 	memset(&p->rss_stat, 0, sizeof(p->rss_stat));
1929a3a2e76cSKAMEZAWA Hiroyuki #endif
1930172ba844SBalbir Singh 
19316976675dSArjan van de Ven 	p->default_timer_slack_ns = current->timer_slack_ns;
19326976675dSArjan van de Ven 
1933eb414681SJohannes Weiner #ifdef CONFIG_PSI
1934eb414681SJohannes Weiner 	p->psi_flags = 0;
1935eb414681SJohannes Weiner #endif
1936eb414681SJohannes Weiner 
19375995477aSAndrea Righi 	task_io_accounting_init(&p->ioac);
19381da177e4SLinus Torvalds 	acct_clear_integrals(p);
19391da177e4SLinus Torvalds 
1940f06febc9SFrank Mayhar 	posix_cpu_timers_init(p);
19411da177e4SLinus Torvalds 
19421da177e4SLinus Torvalds 	p->io_context = NULL;
1943c0b0ae8aSRichard Guy Briggs 	audit_set_context(p, NULL);
1944b4f48b63SPaul Menage 	cgroup_fork(p);
19451da177e4SLinus Torvalds #ifdef CONFIG_NUMA
1946846a16bfSLee Schermerhorn 	p->mempolicy = mpol_dup(p->mempolicy);
19471da177e4SLinus Torvalds 	if (IS_ERR(p->mempolicy)) {
19481da177e4SLinus Torvalds 		retval = PTR_ERR(p->mempolicy);
19491da177e4SLinus Torvalds 		p->mempolicy = NULL;
1950e8604cb4SLi Zefan 		goto bad_fork_cleanup_threadgroup_lock;
19511da177e4SLinus Torvalds 	}
19521da177e4SLinus Torvalds #endif
1953778d3b0fSMichal Hocko #ifdef CONFIG_CPUSETS
1954778d3b0fSMichal Hocko 	p->cpuset_mem_spread_rotor = NUMA_NO_NODE;
1955778d3b0fSMichal Hocko 	p->cpuset_slab_spread_rotor = NUMA_NO_NODE;
1956cc9a6c87SMel Gorman 	seqcount_init(&p->mems_allowed_seq);
1957778d3b0fSMichal Hocko #endif
1958de30a2b3SIngo Molnar #ifdef CONFIG_TRACE_IRQFLAGS
1959de30a2b3SIngo Molnar 	p->irq_events = 0;
1960de30a2b3SIngo Molnar 	p->hardirqs_enabled = 0;
1961de30a2b3SIngo Molnar 	p->hardirq_enable_ip = 0;
1962de30a2b3SIngo Molnar 	p->hardirq_enable_event = 0;
1963de30a2b3SIngo Molnar 	p->hardirq_disable_ip = _THIS_IP_;
1964de30a2b3SIngo Molnar 	p->hardirq_disable_event = 0;
1965de30a2b3SIngo Molnar 	p->softirqs_enabled = 1;
1966de30a2b3SIngo Molnar 	p->softirq_enable_ip = _THIS_IP_;
1967de30a2b3SIngo Molnar 	p->softirq_enable_event = 0;
1968de30a2b3SIngo Molnar 	p->softirq_disable_ip = 0;
1969de30a2b3SIngo Molnar 	p->softirq_disable_event = 0;
1970de30a2b3SIngo Molnar 	p->hardirq_context = 0;
1971de30a2b3SIngo Molnar 	p->softirq_context = 0;
1972de30a2b3SIngo Molnar #endif
19738bcbde54SDavid Hildenbrand 
19748bcbde54SDavid Hildenbrand 	p->pagefault_disabled = 0;
19758bcbde54SDavid Hildenbrand 
1976fbb9ce95SIngo Molnar #ifdef CONFIG_LOCKDEP
1977b09be676SByungchul Park 	lockdep_init_task(p);
1978fbb9ce95SIngo Molnar #endif
19791da177e4SLinus Torvalds 
1980408894eeSIngo Molnar #ifdef CONFIG_DEBUG_MUTEXES
1981408894eeSIngo Molnar 	p->blocked_on = NULL; /* not blocked yet */
1982408894eeSIngo Molnar #endif
1983cafe5635SKent Overstreet #ifdef CONFIG_BCACHE
1984cafe5635SKent Overstreet 	p->sequential_io	= 0;
1985cafe5635SKent Overstreet 	p->sequential_io_avg	= 0;
1986cafe5635SKent Overstreet #endif
19870f481406SMarkus Metzger 
19883c90e6e9SSrivatsa Vaddagiri 	/* Perform scheduler related setup. Assign this task to a CPU. */
1989aab03e05SDario Faggioli 	retval = sched_fork(clone_flags, p);
1990aab03e05SDario Faggioli 	if (retval)
1991aab03e05SDario Faggioli 		goto bad_fork_cleanup_policy;
19926ab423e0SPeter Zijlstra 
1993cdd6c482SIngo Molnar 	retval = perf_event_init_task(p);
19946ab423e0SPeter Zijlstra 	if (retval)
19956ab423e0SPeter Zijlstra 		goto bad_fork_cleanup_policy;
1996fb0a685cSDaniel Rebelo de Oliveira 	retval = audit_alloc(p);
1997fb0a685cSDaniel Rebelo de Oliveira 	if (retval)
19986c72e350SPeter Zijlstra 		goto bad_fork_cleanup_perf;
19991da177e4SLinus Torvalds 	/* copy all the process information */
2000ab602f79SJack Miller 	shm_init_task(p);
2001e4e55b47STetsuo Handa 	retval = security_task_alloc(p, clone_flags);
2002fb0a685cSDaniel Rebelo de Oliveira 	if (retval)
20031da177e4SLinus Torvalds 		goto bad_fork_cleanup_audit;
2004e4e55b47STetsuo Handa 	retval = copy_semundo(clone_flags, p);
2005e4e55b47STetsuo Handa 	if (retval)
2006e4e55b47STetsuo Handa 		goto bad_fork_cleanup_security;
2007fb0a685cSDaniel Rebelo de Oliveira 	retval = copy_files(clone_flags, p);
2008fb0a685cSDaniel Rebelo de Oliveira 	if (retval)
20091da177e4SLinus Torvalds 		goto bad_fork_cleanup_semundo;
2010fb0a685cSDaniel Rebelo de Oliveira 	retval = copy_fs(clone_flags, p);
2011fb0a685cSDaniel Rebelo de Oliveira 	if (retval)
20121da177e4SLinus Torvalds 		goto bad_fork_cleanup_files;
2013fb0a685cSDaniel Rebelo de Oliveira 	retval = copy_sighand(clone_flags, p);
2014fb0a685cSDaniel Rebelo de Oliveira 	if (retval)
20151da177e4SLinus Torvalds 		goto bad_fork_cleanup_fs;
2016fb0a685cSDaniel Rebelo de Oliveira 	retval = copy_signal(clone_flags, p);
2017fb0a685cSDaniel Rebelo de Oliveira 	if (retval)
20181da177e4SLinus Torvalds 		goto bad_fork_cleanup_sighand;
2019fb0a685cSDaniel Rebelo de Oliveira 	retval = copy_mm(clone_flags, p);
2020fb0a685cSDaniel Rebelo de Oliveira 	if (retval)
20211da177e4SLinus Torvalds 		goto bad_fork_cleanup_signal;
2022fb0a685cSDaniel Rebelo de Oliveira 	retval = copy_namespaces(clone_flags, p);
2023fb0a685cSDaniel Rebelo de Oliveira 	if (retval)
2024d84f4f99SDavid Howells 		goto bad_fork_cleanup_mm;
2025fb0a685cSDaniel Rebelo de Oliveira 	retval = copy_io(clone_flags, p);
2026fb0a685cSDaniel Rebelo de Oliveira 	if (retval)
2027fd0928dfSJens Axboe 		goto bad_fork_cleanup_namespaces;
20287f192e3cSChristian Brauner 	retval = copy_thread_tls(clone_flags, args->stack, args->stack_size, p,
20297f192e3cSChristian Brauner 				 args->tls);
20301da177e4SLinus Torvalds 	if (retval)
2031fd0928dfSJens Axboe 		goto bad_fork_cleanup_io;
20321da177e4SLinus Torvalds 
2033afaef01cSAlexander Popov 	stackleak_task_init(p);
2034afaef01cSAlexander Popov 
2035425fb2b4SPavel Emelyanov 	if (pid != &init_struct_pid) {
2036c2b1df2eSAndy Lutomirski 		pid = alloc_pid(p->nsproxy->pid_ns_for_children);
203735f71bc0SMichal Hocko 		if (IS_ERR(pid)) {
203835f71bc0SMichal Hocko 			retval = PTR_ERR(pid);
20390740aa5fSJiri Slaby 			goto bad_fork_cleanup_thread;
2040425fb2b4SPavel Emelyanov 		}
204135f71bc0SMichal Hocko 	}
2042425fb2b4SPavel Emelyanov 
2043b3e58382SChristian Brauner 	/*
2044b3e58382SChristian Brauner 	 * This has to happen after we've potentially unshared the file
2045b3e58382SChristian Brauner 	 * descriptor table (so that the pidfd doesn't leak into the child
2046b3e58382SChristian Brauner 	 * if the fd table isn't shared).
2047b3e58382SChristian Brauner 	 */
2048b3e58382SChristian Brauner 	if (clone_flags & CLONE_PIDFD) {
20496fd2fe49SAl Viro 		retval = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
2050b3e58382SChristian Brauner 		if (retval < 0)
2051b3e58382SChristian Brauner 			goto bad_fork_free_pid;
2052b3e58382SChristian Brauner 
2053b3e58382SChristian Brauner 		pidfd = retval;
20546fd2fe49SAl Viro 
20556fd2fe49SAl Viro 		pidfile = anon_inode_getfile("[pidfd]", &pidfd_fops, pid,
20566fd2fe49SAl Viro 					      O_RDWR | O_CLOEXEC);
20576fd2fe49SAl Viro 		if (IS_ERR(pidfile)) {
20586fd2fe49SAl Viro 			put_unused_fd(pidfd);
205928dd29c0SChristian Brauner 			retval = PTR_ERR(pidfile);
20606fd2fe49SAl Viro 			goto bad_fork_free_pid;
20616fd2fe49SAl Viro 		}
20626fd2fe49SAl Viro 		get_pid(pid);	/* held by pidfile now */
20636fd2fe49SAl Viro 
20647f192e3cSChristian Brauner 		retval = put_user(pidfd, args->pidfd);
2065b3e58382SChristian Brauner 		if (retval)
2066b3e58382SChristian Brauner 			goto bad_fork_put_pidfd;
2067b3e58382SChristian Brauner 	}
2068b3e58382SChristian Brauner 
206973c10101SJens Axboe #ifdef CONFIG_BLOCK
207073c10101SJens Axboe 	p->plug = NULL;
207173c10101SJens Axboe #endif
207242b2dd0aSAlexey Dobriyan #ifdef CONFIG_FUTEX
20738f17d3a5SIngo Molnar 	p->robust_list = NULL;
20748f17d3a5SIngo Molnar #ifdef CONFIG_COMPAT
20758f17d3a5SIngo Molnar 	p->compat_robust_list = NULL;
20768f17d3a5SIngo Molnar #endif
2077c87e2837SIngo Molnar 	INIT_LIST_HEAD(&p->pi_state_list);
2078c87e2837SIngo Molnar 	p->pi_state_cache = NULL;
207942b2dd0aSAlexey Dobriyan #endif
20801da177e4SLinus Torvalds 	/*
2081f9a3879aSGOTO Masanori 	 * sigaltstack should be cleared when sharing the same VM
2082f9a3879aSGOTO Masanori 	 */
2083f9a3879aSGOTO Masanori 	if ((clone_flags & (CLONE_VM|CLONE_VFORK)) == CLONE_VM)
20842a742138SStas Sergeev 		sas_ss_reset(p);
2085f9a3879aSGOTO Masanori 
2086f9a3879aSGOTO Masanori 	/*
20876580807dSOleg Nesterov 	 * Syscall tracing and stepping should be turned off in the
20886580807dSOleg Nesterov 	 * child regardless of CLONE_PTRACE.
20891da177e4SLinus Torvalds 	 */
20906580807dSOleg Nesterov 	user_disable_single_step(p);
20911da177e4SLinus Torvalds 	clear_tsk_thread_flag(p, TIF_SYSCALL_TRACE);
2092ed75e8d5SLaurent Vivier #ifdef TIF_SYSCALL_EMU
2093ed75e8d5SLaurent Vivier 	clear_tsk_thread_flag(p, TIF_SYSCALL_EMU);
2094ed75e8d5SLaurent Vivier #endif
2095e02c9b0dSLin Feng 	clear_tsk_latency_tracing(p);
20961da177e4SLinus Torvalds 
20971da177e4SLinus Torvalds 	/* ok, now we should be set up.. */
209818c830dfSOleg Nesterov 	p->pid = pid_nr(pid);
209918c830dfSOleg Nesterov 	if (clone_flags & CLONE_THREAD) {
21005f8aadd8SOleg Nesterov 		p->exit_signal = -1;
210118c830dfSOleg Nesterov 		p->group_leader = current->group_leader;
210218c830dfSOleg Nesterov 		p->tgid = current->tgid;
210318c830dfSOleg Nesterov 	} else {
210418c830dfSOleg Nesterov 		if (clone_flags & CLONE_PARENT)
21055f8aadd8SOleg Nesterov 			p->exit_signal = current->group_leader->exit_signal;
21065f8aadd8SOleg Nesterov 		else
21077f192e3cSChristian Brauner 			p->exit_signal = args->exit_signal;
210818c830dfSOleg Nesterov 		p->group_leader = p;
210918c830dfSOleg Nesterov 		p->tgid = p->pid;
211018c830dfSOleg Nesterov 	}
21115f8aadd8SOleg Nesterov 
21129d823e8fSWu Fengguang 	p->nr_dirtied = 0;
21139d823e8fSWu Fengguang 	p->nr_dirtied_pause = 128 >> (PAGE_SHIFT - 10);
211483712358SWu Fengguang 	p->dirty_paused_when = 0;
21159d823e8fSWu Fengguang 
2116bb8cbbfeSOleg Nesterov 	p->pdeath_signal = 0;
211747e65328SOleg Nesterov 	INIT_LIST_HEAD(&p->thread_group);
2118158e1645SAl Viro 	p->task_works = NULL;
21191da177e4SLinus Torvalds 
2120780de9ddSIngo Molnar 	cgroup_threadgroup_change_begin(current);
212118c830dfSOleg Nesterov 	/*
21227e47682eSAleksa Sarai 	 * Ensure that the cgroup subsystem policies allow the new process to be
21237e47682eSAleksa Sarai 	 * forked. It should be noted the the new process's css_set can be changed
21247e47682eSAleksa Sarai 	 * between here and cgroup_post_fork() if an organisation operation is in
21257e47682eSAleksa Sarai 	 * progress.
21267e47682eSAleksa Sarai 	 */
2127b53202e6SOleg Nesterov 	retval = cgroup_can_fork(p);
21287e47682eSAleksa Sarai 	if (retval)
2129c3b7112dSChristian Brauner 		goto bad_fork_cgroup_threadgroup_change_end;
21307e47682eSAleksa Sarai 
21317e47682eSAleksa Sarai 	/*
21327b558513SDavid Herrmann 	 * From this point on we must avoid any synchronous user-space
21337b558513SDavid Herrmann 	 * communication until we take the tasklist-lock. In particular, we do
21347b558513SDavid Herrmann 	 * not want user-space to be able to predict the process start-time by
21357b558513SDavid Herrmann 	 * stalling fork(2) after we recorded the start_time but before it is
21367b558513SDavid Herrmann 	 * visible to the system.
21377b558513SDavid Herrmann 	 */
21387b558513SDavid Herrmann 
21397b558513SDavid Herrmann 	p->start_time = ktime_get_ns();
21409285ec4cSJason A. Donenfeld 	p->real_start_time = ktime_get_boottime_ns();
21417b558513SDavid Herrmann 
21427b558513SDavid Herrmann 	/*
214318c830dfSOleg Nesterov 	 * Make it visible to the rest of the system, but dont wake it up yet.
214418c830dfSOleg Nesterov 	 * Need tasklist lock for parent etc handling!
214518c830dfSOleg Nesterov 	 */
21461da177e4SLinus Torvalds 	write_lock_irq(&tasklist_lock);
21471da177e4SLinus Torvalds 
21481da177e4SLinus Torvalds 	/* CLONE_PARENT re-uses the old parent */
21492d5516cbSOleg Nesterov 	if (clone_flags & (CLONE_PARENT|CLONE_THREAD)) {
21501da177e4SLinus Torvalds 		p->real_parent = current->real_parent;
21512d5516cbSOleg Nesterov 		p->parent_exec_id = current->parent_exec_id;
21522d5516cbSOleg Nesterov 	} else {
21531da177e4SLinus Torvalds 		p->real_parent = current;
21542d5516cbSOleg Nesterov 		p->parent_exec_id = current->self_exec_id;
21552d5516cbSOleg Nesterov 	}
21561da177e4SLinus Torvalds 
2157d83a7cb3SJosh Poimboeuf 	klp_copy_process(p);
2158d83a7cb3SJosh Poimboeuf 
21591da177e4SLinus Torvalds 	spin_lock(&current->sighand->siglock);
21604a2c7a78SOleg Nesterov 
21614a2c7a78SOleg Nesterov 	/*
2162dbd95212SKees Cook 	 * Copy seccomp details explicitly here, in case they were changed
2163dbd95212SKees Cook 	 * before holding sighand lock.
2164dbd95212SKees Cook 	 */
2165dbd95212SKees Cook 	copy_seccomp(p);
2166dbd95212SKees Cook 
2167d7822b1eSMathieu Desnoyers 	rseq_fork(p, clone_flags);
2168d7822b1eSMathieu Desnoyers 
21694ca1d3eeSEric W. Biederman 	/* Don't start children in a dying pid namespace */
2170e8cfbc24SGargi Sharma 	if (unlikely(!(ns_of_pid(pid)->pid_allocated & PIDNS_ADDING))) {
21713fd37226SKirill Tkhai 		retval = -ENOMEM;
21723fd37226SKirill Tkhai 		goto bad_fork_cancel_cgroup;
21733fd37226SKirill Tkhai 	}
21744a2c7a78SOleg Nesterov 
21757673bf55SEric W. Biederman 	/* Let kill terminate clone/fork in the middle */
21767673bf55SEric W. Biederman 	if (fatal_signal_pending(current)) {
21777673bf55SEric W. Biederman 		retval = -EINTR;
21787673bf55SEric W. Biederman 		goto bad_fork_cancel_cgroup;
21797673bf55SEric W. Biederman 	}
21807673bf55SEric W. Biederman 
21816fd2fe49SAl Viro 	/* past the last point of failure */
21826fd2fe49SAl Viro 	if (pidfile)
21836fd2fe49SAl Viro 		fd_install(pidfd, pidfile);
21841da177e4SLinus Torvalds 
21852c470475SEric W. Biederman 	init_task_pid_links(p);
218673b9ebfeSOleg Nesterov 	if (likely(p->pid)) {
21874b9d33e6STejun Heo 		ptrace_init_task(p, (clone_flags & CLONE_PTRACE) || trace);
21881da177e4SLinus Torvalds 
218981907739SOleg Nesterov 		init_task_pid(p, PIDTYPE_PID, pid);
21901da177e4SLinus Torvalds 		if (thread_group_leader(p)) {
21916883f81aSEric W. Biederman 			init_task_pid(p, PIDTYPE_TGID, pid);
219281907739SOleg Nesterov 			init_task_pid(p, PIDTYPE_PGID, task_pgrp(current));
219381907739SOleg Nesterov 			init_task_pid(p, PIDTYPE_SID, task_session(current));
219481907739SOleg Nesterov 
21951c4042c2SEric W. Biederman 			if (is_child_reaper(pid)) {
219617cf22c3SEric W. Biederman 				ns_of_pid(pid)->child_reaper = p;
21971c4042c2SEric W. Biederman 				p->signal->flags |= SIGNAL_UNKILLABLE;
21981c4042c2SEric W. Biederman 			}
2199c3ad2c3bSEric W. Biederman 			p->signal->shared_pending.signal = delayed.signal;
22009c9f4dedSAlan Cox 			p->signal->tty = tty_kref_get(current->signal->tty);
2201749860ceSPavel Tikhomirov 			/*
2202749860ceSPavel Tikhomirov 			 * Inherit has_child_subreaper flag under the same
2203749860ceSPavel Tikhomirov 			 * tasklist_lock with adding child to the process tree
2204749860ceSPavel Tikhomirov 			 * for propagate_has_child_subreaper optimization.
2205749860ceSPavel Tikhomirov 			 */
2206749860ceSPavel Tikhomirov 			p->signal->has_child_subreaper = p->real_parent->signal->has_child_subreaper ||
2207749860ceSPavel Tikhomirov 							 p->real_parent->signal->is_child_subreaper;
22089cd80bbbSOleg Nesterov 			list_add_tail(&p->sibling, &p->real_parent->children);
22095e85d4abSEric W. Biederman 			list_add_tail_rcu(&p->tasks, &init_task.tasks);
22106883f81aSEric W. Biederman 			attach_pid(p, PIDTYPE_TGID);
221181907739SOleg Nesterov 			attach_pid(p, PIDTYPE_PGID);
221281907739SOleg Nesterov 			attach_pid(p, PIDTYPE_SID);
2213909ea964SChristoph Lameter 			__this_cpu_inc(process_counts);
221480628ca0SOleg Nesterov 		} else {
221580628ca0SOleg Nesterov 			current->signal->nr_threads++;
221680628ca0SOleg Nesterov 			atomic_inc(&current->signal->live);
221760d4de3fSElena Reshetova 			refcount_inc(&current->signal->sigcnt);
2218924de3b8SEric W. Biederman 			task_join_group_stop(p);
221980628ca0SOleg Nesterov 			list_add_tail_rcu(&p->thread_group,
222080628ca0SOleg Nesterov 					  &p->group_leader->thread_group);
22210c740d0aSOleg Nesterov 			list_add_tail_rcu(&p->thread_node,
22220c740d0aSOleg Nesterov 					  &p->signal->thread_head);
22231da177e4SLinus Torvalds 		}
222481907739SOleg Nesterov 		attach_pid(p, PIDTYPE_PID);
22251da177e4SLinus Torvalds 		nr_threads++;
222673b9ebfeSOleg Nesterov 	}
22271da177e4SLinus Torvalds 	total_forks++;
2228c3ad2c3bSEric W. Biederman 	hlist_del_init(&delayed.node);
22293f17da69SOleg Nesterov 	spin_unlock(&current->sighand->siglock);
22304af4206bSOleg Nesterov 	syscall_tracepoint_update(p);
22311da177e4SLinus Torvalds 	write_unlock_irq(&tasklist_lock);
22324af4206bSOleg Nesterov 
2233c13cf856SAndrew Morton 	proc_fork_connector(p);
2234b53202e6SOleg Nesterov 	cgroup_post_fork(p);
2235780de9ddSIngo Molnar 	cgroup_threadgroup_change_end(current);
2236cdd6c482SIngo Molnar 	perf_event_fork(p);
223743d2b113SKAMEZAWA Hiroyuki 
223843d2b113SKAMEZAWA Hiroyuki 	trace_task_newtask(p, clone_flags);
22393ab67966SOleg Nesterov 	uprobe_copy_process(p, clone_flags);
224043d2b113SKAMEZAWA Hiroyuki 
22411da177e4SLinus Torvalds 	return p;
22421da177e4SLinus Torvalds 
22437e47682eSAleksa Sarai bad_fork_cancel_cgroup:
22443fd37226SKirill Tkhai 	spin_unlock(&current->sighand->siglock);
22453fd37226SKirill Tkhai 	write_unlock_irq(&tasklist_lock);
2246b53202e6SOleg Nesterov 	cgroup_cancel_fork(p);
2247c3b7112dSChristian Brauner bad_fork_cgroup_threadgroup_change_end:
2248c3b7112dSChristian Brauner 	cgroup_threadgroup_change_end(current);
2249b3e58382SChristian Brauner bad_fork_put_pidfd:
22506fd2fe49SAl Viro 	if (clone_flags & CLONE_PIDFD) {
22516fd2fe49SAl Viro 		fput(pidfile);
22526fd2fe49SAl Viro 		put_unused_fd(pidfd);
22536fd2fe49SAl Viro 	}
2254425fb2b4SPavel Emelyanov bad_fork_free_pid:
2255425fb2b4SPavel Emelyanov 	if (pid != &init_struct_pid)
2256425fb2b4SPavel Emelyanov 		free_pid(pid);
22570740aa5fSJiri Slaby bad_fork_cleanup_thread:
22580740aa5fSJiri Slaby 	exit_thread(p);
2259fd0928dfSJens Axboe bad_fork_cleanup_io:
2260b69f2292SLouis Rilling 	if (p->io_context)
2261b69f2292SLouis Rilling 		exit_io_context(p);
2262ab516013SSerge E. Hallyn bad_fork_cleanup_namespaces:
2263444f378bSLinus Torvalds 	exit_task_namespaces(p);
22641da177e4SLinus Torvalds bad_fork_cleanup_mm:
2265c3f3ce04SAndrea Arcangeli 	if (p->mm) {
2266c3f3ce04SAndrea Arcangeli 		mm_clear_owner(p->mm, p);
22671da177e4SLinus Torvalds 		mmput(p->mm);
2268c3f3ce04SAndrea Arcangeli 	}
22691da177e4SLinus Torvalds bad_fork_cleanup_signal:
22704ab6c083SOleg Nesterov 	if (!(clone_flags & CLONE_THREAD))
22711c5354deSMike Galbraith 		free_signal_struct(p->signal);
22721da177e4SLinus Torvalds bad_fork_cleanup_sighand:
2273a7e5328aSOleg Nesterov 	__cleanup_sighand(p->sighand);
22741da177e4SLinus Torvalds bad_fork_cleanup_fs:
22751da177e4SLinus Torvalds 	exit_fs(p); /* blocking */
22761da177e4SLinus Torvalds bad_fork_cleanup_files:
22771da177e4SLinus Torvalds 	exit_files(p); /* blocking */
22781da177e4SLinus Torvalds bad_fork_cleanup_semundo:
22791da177e4SLinus Torvalds 	exit_sem(p);
2280e4e55b47STetsuo Handa bad_fork_cleanup_security:
2281e4e55b47STetsuo Handa 	security_task_free(p);
22821da177e4SLinus Torvalds bad_fork_cleanup_audit:
22831da177e4SLinus Torvalds 	audit_free(p);
22846c72e350SPeter Zijlstra bad_fork_cleanup_perf:
2285cdd6c482SIngo Molnar 	perf_event_free_task(p);
22866c72e350SPeter Zijlstra bad_fork_cleanup_policy:
2287b09be676SByungchul Park 	lockdep_free_task(p);
22881da177e4SLinus Torvalds #ifdef CONFIG_NUMA
2289f0be3d32SLee Schermerhorn 	mpol_put(p->mempolicy);
2290e8604cb4SLi Zefan bad_fork_cleanup_threadgroup_lock:
22911da177e4SLinus Torvalds #endif
229235df17c5SShailabh Nagar 	delayacct_tsk_free(p);
22931da177e4SLinus Torvalds bad_fork_cleanup_count:
2294d84f4f99SDavid Howells 	atomic_dec(&p->cred->user->processes);
2295e0e81739SDavid Howells 	exit_creds(p);
22961da177e4SLinus Torvalds bad_fork_free:
2297405c0759SAndy Lutomirski 	p->state = TASK_DEAD;
229868f24b08SAndy Lutomirski 	put_task_stack(p);
2299c3f3ce04SAndrea Arcangeli 	delayed_free_task(p);
2300fe7d37d1SOleg Nesterov fork_out:
2301c3ad2c3bSEric W. Biederman 	spin_lock_irq(&current->sighand->siglock);
2302c3ad2c3bSEric W. Biederman 	hlist_del_init(&delayed.node);
2303c3ad2c3bSEric W. Biederman 	spin_unlock_irq(&current->sighand->siglock);
2304fe7d37d1SOleg Nesterov 	return ERR_PTR(retval);
23051da177e4SLinus Torvalds }
23061da177e4SLinus Torvalds 
23072c470475SEric W. Biederman static inline void init_idle_pids(struct task_struct *idle)
2308f106eee1SOleg Nesterov {
2309f106eee1SOleg Nesterov 	enum pid_type type;
2310f106eee1SOleg Nesterov 
2311f106eee1SOleg Nesterov 	for (type = PIDTYPE_PID; type < PIDTYPE_MAX; ++type) {
23122c470475SEric W. Biederman 		INIT_HLIST_NODE(&idle->pid_links[type]); /* not really needed */
23132c470475SEric W. Biederman 		init_task_pid(idle, type, &init_struct_pid);
2314f106eee1SOleg Nesterov 	}
2315f106eee1SOleg Nesterov }
2316f106eee1SOleg Nesterov 
23170db0628dSPaul Gortmaker struct task_struct *fork_idle(int cpu)
23181da177e4SLinus Torvalds {
231936c8b586SIngo Molnar 	struct task_struct *task;
23207f192e3cSChristian Brauner 	struct kernel_clone_args args = {
23217f192e3cSChristian Brauner 		.flags = CLONE_VM,
23227f192e3cSChristian Brauner 	};
23237f192e3cSChristian Brauner 
23247f192e3cSChristian Brauner 	task = copy_process(&init_struct_pid, 0, cpu_to_node(cpu), &args);
2325f106eee1SOleg Nesterov 	if (!IS_ERR(task)) {
23262c470475SEric W. Biederman 		init_idle_pids(task);
23271da177e4SLinus Torvalds 		init_idle(task, cpu);
2328f106eee1SOleg Nesterov 	}
232973b9ebfeSOleg Nesterov 
23301da177e4SLinus Torvalds 	return task;
23311da177e4SLinus Torvalds }
23321da177e4SLinus Torvalds 
233313585fa0SNadav Amit struct mm_struct *copy_init_mm(void)
233413585fa0SNadav Amit {
233513585fa0SNadav Amit 	return dup_mm(NULL, &init_mm);
233613585fa0SNadav Amit }
233713585fa0SNadav Amit 
23381da177e4SLinus Torvalds /*
23391da177e4SLinus Torvalds  *  Ok, this is the main fork-routine.
23401da177e4SLinus Torvalds  *
23411da177e4SLinus Torvalds  * It copies the process, and if successful kick-starts
23421da177e4SLinus Torvalds  * it and waits for it to finish using the VM if required.
23431da177e4SLinus Torvalds  */
23447f192e3cSChristian Brauner long _do_fork(struct kernel_clone_args *args)
23451da177e4SLinus Torvalds {
23467f192e3cSChristian Brauner 	u64 clone_flags = args->flags;
23479f5325aaSMarcos Paulo de Souza 	struct completion vfork;
23489f5325aaSMarcos Paulo de Souza 	struct pid *pid;
23491da177e4SLinus Torvalds 	struct task_struct *p;
23501da177e4SLinus Torvalds 	int trace = 0;
235192476d7fSEric W. Biederman 	long nr;
23521da177e4SLinus Torvalds 
2353bdff746aSAndrew Morton 	/*
23544b9d33e6STejun Heo 	 * Determine whether and which event to report to ptracer.  When
23554b9d33e6STejun Heo 	 * called from kernel_thread or CLONE_UNTRACED is explicitly
23564b9d33e6STejun Heo 	 * requested, no event is reported; otherwise, report if the event
23574b9d33e6STejun Heo 	 * for the type of forking is enabled.
235809a05394SRoland McGrath 	 */
2359e80d6661SAl Viro 	if (!(clone_flags & CLONE_UNTRACED)) {
23604b9d33e6STejun Heo 		if (clone_flags & CLONE_VFORK)
23614b9d33e6STejun Heo 			trace = PTRACE_EVENT_VFORK;
23627f192e3cSChristian Brauner 		else if (args->exit_signal != SIGCHLD)
23634b9d33e6STejun Heo 			trace = PTRACE_EVENT_CLONE;
23644b9d33e6STejun Heo 		else
23654b9d33e6STejun Heo 			trace = PTRACE_EVENT_FORK;
23664b9d33e6STejun Heo 
23674b9d33e6STejun Heo 		if (likely(!ptrace_event_enabled(current, trace)))
23684b9d33e6STejun Heo 			trace = 0;
23694b9d33e6STejun Heo 	}
23701da177e4SLinus Torvalds 
23717f192e3cSChristian Brauner 	p = copy_process(NULL, trace, NUMA_NO_NODE, args);
237238addce8SEmese Revfy 	add_latent_entropy();
23739f5325aaSMarcos Paulo de Souza 
23749f5325aaSMarcos Paulo de Souza 	if (IS_ERR(p))
23759f5325aaSMarcos Paulo de Souza 		return PTR_ERR(p);
23769f5325aaSMarcos Paulo de Souza 
23771da177e4SLinus Torvalds 	/*
23781da177e4SLinus Torvalds 	 * Do this prior waking up the new thread - the thread pointer
23791da177e4SLinus Torvalds 	 * might get invalid after that point, if the thread exits quickly.
23801da177e4SLinus Torvalds 	 */
23810a16b607SMathieu Desnoyers 	trace_sched_process_fork(current, p);
23820a16b607SMathieu Desnoyers 
23834e52365fSMatthew Dempsky 	pid = get_task_pid(p, PIDTYPE_PID);
23844e52365fSMatthew Dempsky 	nr = pid_vnr(pid);
238530e49c26SPavel Emelyanov 
238630e49c26SPavel Emelyanov 	if (clone_flags & CLONE_PARENT_SETTID)
23877f192e3cSChristian Brauner 		put_user(nr, args->parent_tid);
2388a6f5e063SSukadev Bhattiprolu 
23891da177e4SLinus Torvalds 	if (clone_flags & CLONE_VFORK) {
23901da177e4SLinus Torvalds 		p->vfork_done = &vfork;
23911da177e4SLinus Torvalds 		init_completion(&vfork);
2392d68b46feSOleg Nesterov 		get_task_struct(p);
23931da177e4SLinus Torvalds 	}
23941da177e4SLinus Torvalds 
23953e51e3edSSamir Bellabes 	wake_up_new_task(p);
23961da177e4SLinus Torvalds 
23974b9d33e6STejun Heo 	/* forking complete and child started to run, tell ptracer */
23984b9d33e6STejun Heo 	if (unlikely(trace))
23994e52365fSMatthew Dempsky 		ptrace_event_pid(trace, pid);
240009a05394SRoland McGrath 
24011da177e4SLinus Torvalds 	if (clone_flags & CLONE_VFORK) {
2402d68b46feSOleg Nesterov 		if (!wait_for_vfork_done(p, &vfork))
24034e52365fSMatthew Dempsky 			ptrace_event_pid(PTRACE_EVENT_VFORK_DONE, pid);
24049f59ce5dSChuck Ebbert 	}
24054e52365fSMatthew Dempsky 
24064e52365fSMatthew Dempsky 	put_pid(pid);
240792476d7fSEric W. Biederman 	return nr;
24081da177e4SLinus Torvalds }
24091da177e4SLinus Torvalds 
2410028b6e8aSDmitry V. Levin bool legacy_clone_args_valid(const struct kernel_clone_args *kargs)
2411028b6e8aSDmitry V. Levin {
2412028b6e8aSDmitry V. Levin 	/* clone(CLONE_PIDFD) uses parent_tidptr to return a pidfd */
2413028b6e8aSDmitry V. Levin 	if ((kargs->flags & CLONE_PIDFD) &&
2414028b6e8aSDmitry V. Levin 	    (kargs->flags & CLONE_PARENT_SETTID))
2415028b6e8aSDmitry V. Levin 		return false;
2416028b6e8aSDmitry V. Levin 
2417028b6e8aSDmitry V. Levin 	return true;
2418028b6e8aSDmitry V. Levin }
2419028b6e8aSDmitry V. Levin 
24203033f14aSJosh Triplett #ifndef CONFIG_HAVE_COPY_THREAD_TLS
24213033f14aSJosh Triplett /* For compatibility with architectures that call do_fork directly rather than
24223033f14aSJosh Triplett  * using the syscall entry points below. */
24233033f14aSJosh Triplett long do_fork(unsigned long clone_flags,
24243033f14aSJosh Triplett 	      unsigned long stack_start,
24253033f14aSJosh Triplett 	      unsigned long stack_size,
24263033f14aSJosh Triplett 	      int __user *parent_tidptr,
24273033f14aSJosh Triplett 	      int __user *child_tidptr)
24283033f14aSJosh Triplett {
24297f192e3cSChristian Brauner 	struct kernel_clone_args args = {
24307f192e3cSChristian Brauner 		.flags		= (clone_flags & ~CSIGNAL),
2431028b6e8aSDmitry V. Levin 		.pidfd		= parent_tidptr,
24327f192e3cSChristian Brauner 		.child_tid	= child_tidptr,
24337f192e3cSChristian Brauner 		.parent_tid	= parent_tidptr,
24347f192e3cSChristian Brauner 		.exit_signal	= (clone_flags & CSIGNAL),
24357f192e3cSChristian Brauner 		.stack		= stack_start,
24367f192e3cSChristian Brauner 		.stack_size	= stack_size,
24377f192e3cSChristian Brauner 	};
24387f192e3cSChristian Brauner 
2439028b6e8aSDmitry V. Levin 	if (!legacy_clone_args_valid(&args))
2440028b6e8aSDmitry V. Levin 		return -EINVAL;
2441028b6e8aSDmitry V. Levin 
24427f192e3cSChristian Brauner 	return _do_fork(&args);
24433033f14aSJosh Triplett }
24443033f14aSJosh Triplett #endif
24453033f14aSJosh Triplett 
24462aa3a7f8SAl Viro /*
24472aa3a7f8SAl Viro  * Create a kernel thread.
24482aa3a7f8SAl Viro  */
24492aa3a7f8SAl Viro pid_t kernel_thread(int (*fn)(void *), void *arg, unsigned long flags)
24502aa3a7f8SAl Viro {
24517f192e3cSChristian Brauner 	struct kernel_clone_args args = {
24527f192e3cSChristian Brauner 		.flags		= ((flags | CLONE_VM | CLONE_UNTRACED) & ~CSIGNAL),
24537f192e3cSChristian Brauner 		.exit_signal	= (flags & CSIGNAL),
24547f192e3cSChristian Brauner 		.stack		= (unsigned long)fn,
24557f192e3cSChristian Brauner 		.stack_size	= (unsigned long)arg,
24567f192e3cSChristian Brauner 	};
24577f192e3cSChristian Brauner 
24587f192e3cSChristian Brauner 	return _do_fork(&args);
24592aa3a7f8SAl Viro }
24602aa3a7f8SAl Viro 
2461d2125043SAl Viro #ifdef __ARCH_WANT_SYS_FORK
2462d2125043SAl Viro SYSCALL_DEFINE0(fork)
2463d2125043SAl Viro {
2464d2125043SAl Viro #ifdef CONFIG_MMU
24657f192e3cSChristian Brauner 	struct kernel_clone_args args = {
24667f192e3cSChristian Brauner 		.exit_signal = SIGCHLD,
24677f192e3cSChristian Brauner 	};
24687f192e3cSChristian Brauner 
24697f192e3cSChristian Brauner 	return _do_fork(&args);
2470d2125043SAl Viro #else
2471d2125043SAl Viro 	/* can not support in nommu mode */
24725d59e182SDaeseok Youn 	return -EINVAL;
2473d2125043SAl Viro #endif
2474d2125043SAl Viro }
2475d2125043SAl Viro #endif
2476d2125043SAl Viro 
2477d2125043SAl Viro #ifdef __ARCH_WANT_SYS_VFORK
2478d2125043SAl Viro SYSCALL_DEFINE0(vfork)
2479d2125043SAl Viro {
24807f192e3cSChristian Brauner 	struct kernel_clone_args args = {
24817f192e3cSChristian Brauner 		.flags		= CLONE_VFORK | CLONE_VM,
24827f192e3cSChristian Brauner 		.exit_signal	= SIGCHLD,
24837f192e3cSChristian Brauner 	};
24847f192e3cSChristian Brauner 
24857f192e3cSChristian Brauner 	return _do_fork(&args);
2486d2125043SAl Viro }
2487d2125043SAl Viro #endif
2488d2125043SAl Viro 
2489d2125043SAl Viro #ifdef __ARCH_WANT_SYS_CLONE
2490d2125043SAl Viro #ifdef CONFIG_CLONE_BACKWARDS
2491d2125043SAl Viro SYSCALL_DEFINE5(clone, unsigned long, clone_flags, unsigned long, newsp,
2492d2125043SAl Viro 		 int __user *, parent_tidptr,
24933033f14aSJosh Triplett 		 unsigned long, tls,
2494d2125043SAl Viro 		 int __user *, child_tidptr)
2495d2125043SAl Viro #elif defined(CONFIG_CLONE_BACKWARDS2)
2496d2125043SAl Viro SYSCALL_DEFINE5(clone, unsigned long, newsp, unsigned long, clone_flags,
2497d2125043SAl Viro 		 int __user *, parent_tidptr,
2498d2125043SAl Viro 		 int __user *, child_tidptr,
24993033f14aSJosh Triplett 		 unsigned long, tls)
2500dfa9771aSMichal Simek #elif defined(CONFIG_CLONE_BACKWARDS3)
2501dfa9771aSMichal Simek SYSCALL_DEFINE6(clone, unsigned long, clone_flags, unsigned long, newsp,
2502dfa9771aSMichal Simek 		int, stack_size,
2503dfa9771aSMichal Simek 		int __user *, parent_tidptr,
2504dfa9771aSMichal Simek 		int __user *, child_tidptr,
25053033f14aSJosh Triplett 		unsigned long, tls)
2506d2125043SAl Viro #else
2507d2125043SAl Viro SYSCALL_DEFINE5(clone, unsigned long, clone_flags, unsigned long, newsp,
2508d2125043SAl Viro 		 int __user *, parent_tidptr,
2509d2125043SAl Viro 		 int __user *, child_tidptr,
25103033f14aSJosh Triplett 		 unsigned long, tls)
2511d2125043SAl Viro #endif
2512d2125043SAl Viro {
25137f192e3cSChristian Brauner 	struct kernel_clone_args args = {
25147f192e3cSChristian Brauner 		.flags		= (clone_flags & ~CSIGNAL),
25157f192e3cSChristian Brauner 		.pidfd		= parent_tidptr,
25167f192e3cSChristian Brauner 		.child_tid	= child_tidptr,
25177f192e3cSChristian Brauner 		.parent_tid	= parent_tidptr,
25187f192e3cSChristian Brauner 		.exit_signal	= (clone_flags & CSIGNAL),
25197f192e3cSChristian Brauner 		.stack		= newsp,
25207f192e3cSChristian Brauner 		.tls		= tls,
25217f192e3cSChristian Brauner 	};
25227f192e3cSChristian Brauner 
2523028b6e8aSDmitry V. Levin 	if (!legacy_clone_args_valid(&args))
25247f192e3cSChristian Brauner 		return -EINVAL;
25257f192e3cSChristian Brauner 
25267f192e3cSChristian Brauner 	return _do_fork(&args);
25277f192e3cSChristian Brauner }
2528d68dbb0cSChristian Brauner #endif
25297f192e3cSChristian Brauner 
2530d68dbb0cSChristian Brauner #ifdef __ARCH_WANT_SYS_CLONE3
25317f192e3cSChristian Brauner noinline static int copy_clone_args_from_user(struct kernel_clone_args *kargs,
25327f192e3cSChristian Brauner 					      struct clone_args __user *uargs,
25337f192e3cSChristian Brauner 					      size_t size)
25347f192e3cSChristian Brauner {
25357f192e3cSChristian Brauner 	struct clone_args args;
25367f192e3cSChristian Brauner 
25377f192e3cSChristian Brauner 	if (unlikely(size > PAGE_SIZE))
25387f192e3cSChristian Brauner 		return -E2BIG;
25397f192e3cSChristian Brauner 
25407f192e3cSChristian Brauner 	if (unlikely(size < sizeof(struct clone_args)))
25417f192e3cSChristian Brauner 		return -EINVAL;
25427f192e3cSChristian Brauner 
25437f192e3cSChristian Brauner 	if (unlikely(!access_ok(uargs, size)))
25447f192e3cSChristian Brauner 		return -EFAULT;
25457f192e3cSChristian Brauner 
25467f192e3cSChristian Brauner 	if (size > sizeof(struct clone_args)) {
25477f192e3cSChristian Brauner 		unsigned char __user *addr;
25487f192e3cSChristian Brauner 		unsigned char __user *end;
25497f192e3cSChristian Brauner 		unsigned char val;
25507f192e3cSChristian Brauner 
25517f192e3cSChristian Brauner 		addr = (void __user *)uargs + sizeof(struct clone_args);
25527f192e3cSChristian Brauner 		end = (void __user *)uargs + size;
25537f192e3cSChristian Brauner 
25547f192e3cSChristian Brauner 		for (; addr < end; addr++) {
25557f192e3cSChristian Brauner 			if (get_user(val, addr))
25567f192e3cSChristian Brauner 				return -EFAULT;
25577f192e3cSChristian Brauner 			if (val)
25587f192e3cSChristian Brauner 				return -E2BIG;
25597f192e3cSChristian Brauner 		}
25607f192e3cSChristian Brauner 
25617f192e3cSChristian Brauner 		size = sizeof(struct clone_args);
25627f192e3cSChristian Brauner 	}
25637f192e3cSChristian Brauner 
25647f192e3cSChristian Brauner 	if (copy_from_user(&args, uargs, size))
25657f192e3cSChristian Brauner 		return -EFAULT;
25667f192e3cSChristian Brauner 
25677f192e3cSChristian Brauner 	*kargs = (struct kernel_clone_args){
25687f192e3cSChristian Brauner 		.flags		= args.flags,
25697f192e3cSChristian Brauner 		.pidfd		= u64_to_user_ptr(args.pidfd),
25707f192e3cSChristian Brauner 		.child_tid	= u64_to_user_ptr(args.child_tid),
25717f192e3cSChristian Brauner 		.parent_tid	= u64_to_user_ptr(args.parent_tid),
25727f192e3cSChristian Brauner 		.exit_signal	= args.exit_signal,
25737f192e3cSChristian Brauner 		.stack		= args.stack,
25747f192e3cSChristian Brauner 		.stack_size	= args.stack_size,
25757f192e3cSChristian Brauner 		.tls		= args.tls,
25767f192e3cSChristian Brauner 	};
25777f192e3cSChristian Brauner 
25787f192e3cSChristian Brauner 	return 0;
25797f192e3cSChristian Brauner }
25807f192e3cSChristian Brauner 
25817f192e3cSChristian Brauner static bool clone3_args_valid(const struct kernel_clone_args *kargs)
25827f192e3cSChristian Brauner {
25837f192e3cSChristian Brauner 	/*
25847f192e3cSChristian Brauner 	 * All lower bits of the flag word are taken.
25857f192e3cSChristian Brauner 	 * Verify that no other unknown flags are passed along.
25867f192e3cSChristian Brauner 	 */
25877f192e3cSChristian Brauner 	if (kargs->flags & ~CLONE_LEGACY_FLAGS)
25887f192e3cSChristian Brauner 		return false;
25897f192e3cSChristian Brauner 
25907f192e3cSChristian Brauner 	/*
25917f192e3cSChristian Brauner 	 * - make the CLONE_DETACHED bit reuseable for clone3
25927f192e3cSChristian Brauner 	 * - make the CSIGNAL bits reuseable for clone3
25937f192e3cSChristian Brauner 	 */
25947f192e3cSChristian Brauner 	if (kargs->flags & (CLONE_DETACHED | CSIGNAL))
25957f192e3cSChristian Brauner 		return false;
25967f192e3cSChristian Brauner 
25977f192e3cSChristian Brauner 	if ((kargs->flags & (CLONE_THREAD | CLONE_PARENT)) &&
25987f192e3cSChristian Brauner 	    kargs->exit_signal)
25997f192e3cSChristian Brauner 		return false;
26007f192e3cSChristian Brauner 
26017f192e3cSChristian Brauner 	return true;
26027f192e3cSChristian Brauner }
26037f192e3cSChristian Brauner 
26047f192e3cSChristian Brauner SYSCALL_DEFINE2(clone3, struct clone_args __user *, uargs, size_t, size)
26057f192e3cSChristian Brauner {
26067f192e3cSChristian Brauner 	int err;
26077f192e3cSChristian Brauner 
26087f192e3cSChristian Brauner 	struct kernel_clone_args kargs;
26097f192e3cSChristian Brauner 
26107f192e3cSChristian Brauner 	err = copy_clone_args_from_user(&kargs, uargs, size);
26117f192e3cSChristian Brauner 	if (err)
26127f192e3cSChristian Brauner 		return err;
26137f192e3cSChristian Brauner 
26147f192e3cSChristian Brauner 	if (!clone3_args_valid(&kargs))
26157f192e3cSChristian Brauner 		return -EINVAL;
26167f192e3cSChristian Brauner 
26177f192e3cSChristian Brauner 	return _do_fork(&kargs);
2618d2125043SAl Viro }
2619d2125043SAl Viro #endif
2620d2125043SAl Viro 
26210f1b92cbSOleg Nesterov void walk_process_tree(struct task_struct *top, proc_visitor visitor, void *data)
26220f1b92cbSOleg Nesterov {
26230f1b92cbSOleg Nesterov 	struct task_struct *leader, *parent, *child;
26240f1b92cbSOleg Nesterov 	int res;
26250f1b92cbSOleg Nesterov 
26260f1b92cbSOleg Nesterov 	read_lock(&tasklist_lock);
26270f1b92cbSOleg Nesterov 	leader = top = top->group_leader;
26280f1b92cbSOleg Nesterov down:
26290f1b92cbSOleg Nesterov 	for_each_thread(leader, parent) {
26300f1b92cbSOleg Nesterov 		list_for_each_entry(child, &parent->children, sibling) {
26310f1b92cbSOleg Nesterov 			res = visitor(child, data);
26320f1b92cbSOleg Nesterov 			if (res) {
26330f1b92cbSOleg Nesterov 				if (res < 0)
26340f1b92cbSOleg Nesterov 					goto out;
26350f1b92cbSOleg Nesterov 				leader = child;
26360f1b92cbSOleg Nesterov 				goto down;
26370f1b92cbSOleg Nesterov 			}
26380f1b92cbSOleg Nesterov up:
26390f1b92cbSOleg Nesterov 			;
26400f1b92cbSOleg Nesterov 		}
26410f1b92cbSOleg Nesterov 	}
26420f1b92cbSOleg Nesterov 
26430f1b92cbSOleg Nesterov 	if (leader != top) {
26440f1b92cbSOleg Nesterov 		child = leader;
26450f1b92cbSOleg Nesterov 		parent = child->real_parent;
26460f1b92cbSOleg Nesterov 		leader = parent->group_leader;
26470f1b92cbSOleg Nesterov 		goto up;
26480f1b92cbSOleg Nesterov 	}
26490f1b92cbSOleg Nesterov out:
26500f1b92cbSOleg Nesterov 	read_unlock(&tasklist_lock);
26510f1b92cbSOleg Nesterov }
26520f1b92cbSOleg Nesterov 
26535fd63b30SRavikiran G Thirumalai #ifndef ARCH_MIN_MMSTRUCT_ALIGN
26545fd63b30SRavikiran G Thirumalai #define ARCH_MIN_MMSTRUCT_ALIGN 0
26555fd63b30SRavikiran G Thirumalai #endif
26565fd63b30SRavikiran G Thirumalai 
265751cc5068SAlexey Dobriyan static void sighand_ctor(void *data)
2658aa1757f9SOleg Nesterov {
2659aa1757f9SOleg Nesterov 	struct sighand_struct *sighand = data;
2660aa1757f9SOleg Nesterov 
2661aa1757f9SOleg Nesterov 	spin_lock_init(&sighand->siglock);
2662b8fceee1SDavide Libenzi 	init_waitqueue_head(&sighand->signalfd_wqh);
2663fba2afaaSDavide Libenzi }
2664aa1757f9SOleg Nesterov 
26651da177e4SLinus Torvalds void __init proc_caches_init(void)
26661da177e4SLinus Torvalds {
2667c1a2f7f0SRik van Riel 	unsigned int mm_size;
2668c1a2f7f0SRik van Riel 
26691da177e4SLinus Torvalds 	sighand_cachep = kmem_cache_create("sighand_cache",
26701da177e4SLinus Torvalds 			sizeof(struct sighand_struct), 0,
26715f0d5a3aSPaul E. McKenney 			SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_TYPESAFE_BY_RCU|
267275f296d9SLevin, Alexander (Sasha Levin) 			SLAB_ACCOUNT, sighand_ctor);
26731da177e4SLinus Torvalds 	signal_cachep = kmem_cache_create("signal_cache",
26741da177e4SLinus Torvalds 			sizeof(struct signal_struct), 0,
267575f296d9SLevin, Alexander (Sasha Levin) 			SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_ACCOUNT,
26765d097056SVladimir Davydov 			NULL);
26771da177e4SLinus Torvalds 	files_cachep = kmem_cache_create("files_cache",
26781da177e4SLinus Torvalds 			sizeof(struct files_struct), 0,
267975f296d9SLevin, Alexander (Sasha Levin) 			SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_ACCOUNT,
26805d097056SVladimir Davydov 			NULL);
26811da177e4SLinus Torvalds 	fs_cachep = kmem_cache_create("fs_cache",
26821da177e4SLinus Torvalds 			sizeof(struct fs_struct), 0,
268375f296d9SLevin, Alexander (Sasha Levin) 			SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_ACCOUNT,
26845d097056SVladimir Davydov 			NULL);
2685c1a2f7f0SRik van Riel 
26866345d24dSLinus Torvalds 	/*
2687c1a2f7f0SRik van Riel 	 * The mm_cpumask is located at the end of mm_struct, and is
2688c1a2f7f0SRik van Riel 	 * dynamically sized based on the maximum CPU number this system
2689c1a2f7f0SRik van Riel 	 * can have, taking hotplug into account (nr_cpu_ids).
26906345d24dSLinus Torvalds 	 */
2691c1a2f7f0SRik van Riel 	mm_size = sizeof(struct mm_struct) + cpumask_size();
2692c1a2f7f0SRik van Riel 
269307dcd7feSDavid Windsor 	mm_cachep = kmem_cache_create_usercopy("mm_struct",
2694c1a2f7f0SRik van Riel 			mm_size, ARCH_MIN_MMSTRUCT_ALIGN,
269575f296d9SLevin, Alexander (Sasha Levin) 			SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_ACCOUNT,
269607dcd7feSDavid Windsor 			offsetof(struct mm_struct, saved_auxv),
269707dcd7feSDavid Windsor 			sizeof_field(struct mm_struct, saved_auxv),
26985d097056SVladimir Davydov 			NULL);
26995d097056SVladimir Davydov 	vm_area_cachep = KMEM_CACHE(vm_area_struct, SLAB_PANIC|SLAB_ACCOUNT);
27008feae131SDavid Howells 	mmap_init();
270166577193SAl Viro 	nsproxy_cache_init();
27021da177e4SLinus Torvalds }
2703cf2e340fSJANAK DESAI 
2704cf2e340fSJANAK DESAI /*
27059bfb23fcSOleg Nesterov  * Check constraints on flags passed to the unshare system call.
2706cf2e340fSJANAK DESAI  */
27079bfb23fcSOleg Nesterov static int check_unshare_flags(unsigned long unshare_flags)
2708cf2e340fSJANAK DESAI {
27099bfb23fcSOleg Nesterov 	if (unshare_flags & ~(CLONE_THREAD|CLONE_FS|CLONE_NEWNS|CLONE_SIGHAND|
27109bfb23fcSOleg Nesterov 				CLONE_VM|CLONE_FILES|CLONE_SYSVSEM|
271150804fe3SEric W. Biederman 				CLONE_NEWUTS|CLONE_NEWIPC|CLONE_NEWNET|
2712a79a908fSAditya Kali 				CLONE_NEWUSER|CLONE_NEWPID|CLONE_NEWCGROUP))
2713cf2e340fSJANAK DESAI 		return -EINVAL;
27149bfb23fcSOleg Nesterov 	/*
271512c641abSEric W. Biederman 	 * Not implemented, but pretend it works if there is nothing
271612c641abSEric W. Biederman 	 * to unshare.  Note that unsharing the address space or the
271712c641abSEric W. Biederman 	 * signal handlers also need to unshare the signal queues (aka
271812c641abSEric W. Biederman 	 * CLONE_THREAD).
27199bfb23fcSOleg Nesterov 	 */
27209bfb23fcSOleg Nesterov 	if (unshare_flags & (CLONE_THREAD | CLONE_SIGHAND | CLONE_VM)) {
272112c641abSEric W. Biederman 		if (!thread_group_empty(current))
272212c641abSEric W. Biederman 			return -EINVAL;
272312c641abSEric W. Biederman 	}
272412c641abSEric W. Biederman 	if (unshare_flags & (CLONE_SIGHAND | CLONE_VM)) {
2725d036bda7SElena Reshetova 		if (refcount_read(&current->sighand->count) > 1)
272612c641abSEric W. Biederman 			return -EINVAL;
272712c641abSEric W. Biederman 	}
272812c641abSEric W. Biederman 	if (unshare_flags & CLONE_VM) {
272912c641abSEric W. Biederman 		if (!current_is_single_threaded())
27309bfb23fcSOleg Nesterov 			return -EINVAL;
27319bfb23fcSOleg Nesterov 	}
2732cf2e340fSJANAK DESAI 
2733cf2e340fSJANAK DESAI 	return 0;
2734cf2e340fSJANAK DESAI }
2735cf2e340fSJANAK DESAI 
2736cf2e340fSJANAK DESAI /*
273799d1419dSJANAK DESAI  * Unshare the filesystem structure if it is being shared
2738cf2e340fSJANAK DESAI  */
2739cf2e340fSJANAK DESAI static int unshare_fs(unsigned long unshare_flags, struct fs_struct **new_fsp)
2740cf2e340fSJANAK DESAI {
2741cf2e340fSJANAK DESAI 	struct fs_struct *fs = current->fs;
2742cf2e340fSJANAK DESAI 
2743498052bbSAl Viro 	if (!(unshare_flags & CLONE_FS) || !fs)
2744498052bbSAl Viro 		return 0;
2745498052bbSAl Viro 
2746498052bbSAl Viro 	/* don't need lock here; in the worst case we'll do useless copy */
2747498052bbSAl Viro 	if (fs->users == 1)
2748498052bbSAl Viro 		return 0;
2749498052bbSAl Viro 
2750498052bbSAl Viro 	*new_fsp = copy_fs_struct(fs);
275199d1419dSJANAK DESAI 	if (!*new_fsp)
275299d1419dSJANAK DESAI 		return -ENOMEM;
2753cf2e340fSJANAK DESAI 
2754cf2e340fSJANAK DESAI 	return 0;
2755cf2e340fSJANAK DESAI }
2756cf2e340fSJANAK DESAI 
2757cf2e340fSJANAK DESAI /*
2758a016f338SJANAK DESAI  * Unshare file descriptor table if it is being shared
2759cf2e340fSJANAK DESAI  */
2760cf2e340fSJANAK DESAI static int unshare_fd(unsigned long unshare_flags, struct files_struct **new_fdp)
2761cf2e340fSJANAK DESAI {
2762cf2e340fSJANAK DESAI 	struct files_struct *fd = current->files;
2763a016f338SJANAK DESAI 	int error = 0;
2764cf2e340fSJANAK DESAI 
2765cf2e340fSJANAK DESAI 	if ((unshare_flags & CLONE_FILES) &&
2766a016f338SJANAK DESAI 	    (fd && atomic_read(&fd->count) > 1)) {
2767a016f338SJANAK DESAI 		*new_fdp = dup_fd(fd, &error);
2768a016f338SJANAK DESAI 		if (!*new_fdp)
2769a016f338SJANAK DESAI 			return error;
2770a016f338SJANAK DESAI 	}
2771cf2e340fSJANAK DESAI 
2772cf2e340fSJANAK DESAI 	return 0;
2773cf2e340fSJANAK DESAI }
2774cf2e340fSJANAK DESAI 
2775cf2e340fSJANAK DESAI /*
2776cf2e340fSJANAK DESAI  * unshare allows a process to 'unshare' part of the process
2777cf2e340fSJANAK DESAI  * context which was originally shared using clone.  copy_*
2778cf2e340fSJANAK DESAI  * functions used by do_fork() cannot be used here directly
2779cf2e340fSJANAK DESAI  * because they modify an inactive task_struct that is being
2780cf2e340fSJANAK DESAI  * constructed. Here we are modifying the current, active,
2781cf2e340fSJANAK DESAI  * task_struct.
2782cf2e340fSJANAK DESAI  */
27839b32105eSDominik Brodowski int ksys_unshare(unsigned long unshare_flags)
2784cf2e340fSJANAK DESAI {
2785cf2e340fSJANAK DESAI 	struct fs_struct *fs, *new_fs = NULL;
2786cf2e340fSJANAK DESAI 	struct files_struct *fd, *new_fd = NULL;
2787b2e0d987SEric W. Biederman 	struct cred *new_cred = NULL;
2788cf7b708cSPavel Emelyanov 	struct nsproxy *new_nsproxy = NULL;
27899edff4abSManfred Spraul 	int do_sysvsem = 0;
27909bfb23fcSOleg Nesterov 	int err;
2791cf2e340fSJANAK DESAI 
279250804fe3SEric W. Biederman 	/*
2793faf00da5SEric W. Biederman 	 * If unsharing a user namespace must also unshare the thread group
2794faf00da5SEric W. Biederman 	 * and unshare the filesystem root and working directories.
2795b2e0d987SEric W. Biederman 	 */
2796b2e0d987SEric W. Biederman 	if (unshare_flags & CLONE_NEWUSER)
2797e66eded8SEric W. Biederman 		unshare_flags |= CLONE_THREAD | CLONE_FS;
2798b2e0d987SEric W. Biederman 	/*
279950804fe3SEric W. Biederman 	 * If unsharing vm, must also unshare signal handlers.
280050804fe3SEric W. Biederman 	 */
280150804fe3SEric W. Biederman 	if (unshare_flags & CLONE_VM)
280250804fe3SEric W. Biederman 		unshare_flags |= CLONE_SIGHAND;
28036013f67fSManfred Spraul 	/*
280412c641abSEric W. Biederman 	 * If unsharing a signal handlers, must also unshare the signal queues.
280512c641abSEric W. Biederman 	 */
280612c641abSEric W. Biederman 	if (unshare_flags & CLONE_SIGHAND)
280712c641abSEric W. Biederman 		unshare_flags |= CLONE_THREAD;
280812c641abSEric W. Biederman 	/*
28099bfb23fcSOleg Nesterov 	 * If unsharing namespace, must also unshare filesystem information.
28109bfb23fcSOleg Nesterov 	 */
28119bfb23fcSOleg Nesterov 	if (unshare_flags & CLONE_NEWNS)
28129bfb23fcSOleg Nesterov 		unshare_flags |= CLONE_FS;
281350804fe3SEric W. Biederman 
281450804fe3SEric W. Biederman 	err = check_unshare_flags(unshare_flags);
281550804fe3SEric W. Biederman 	if (err)
281650804fe3SEric W. Biederman 		goto bad_unshare_out;
28179bfb23fcSOleg Nesterov 	/*
28186013f67fSManfred Spraul 	 * CLONE_NEWIPC must also detach from the undolist: after switching
28196013f67fSManfred Spraul 	 * to a new ipc namespace, the semaphore arrays from the old
28206013f67fSManfred Spraul 	 * namespace are unreachable.
28216013f67fSManfred Spraul 	 */
28226013f67fSManfred Spraul 	if (unshare_flags & (CLONE_NEWIPC|CLONE_SYSVSEM))
28239edff4abSManfred Spraul 		do_sysvsem = 1;
2824fb0a685cSDaniel Rebelo de Oliveira 	err = unshare_fs(unshare_flags, &new_fs);
2825fb0a685cSDaniel Rebelo de Oliveira 	if (err)
28269bfb23fcSOleg Nesterov 		goto bad_unshare_out;
2827fb0a685cSDaniel Rebelo de Oliveira 	err = unshare_fd(unshare_flags, &new_fd);
2828fb0a685cSDaniel Rebelo de Oliveira 	if (err)
28299bfb23fcSOleg Nesterov 		goto bad_unshare_cleanup_fs;
2830b2e0d987SEric W. Biederman 	err = unshare_userns(unshare_flags, &new_cred);
2831fb0a685cSDaniel Rebelo de Oliveira 	if (err)
28329edff4abSManfred Spraul 		goto bad_unshare_cleanup_fd;
2833b2e0d987SEric W. Biederman 	err = unshare_nsproxy_namespaces(unshare_flags, &new_nsproxy,
2834b2e0d987SEric W. Biederman 					 new_cred, new_fs);
2835b2e0d987SEric W. Biederman 	if (err)
2836b2e0d987SEric W. Biederman 		goto bad_unshare_cleanup_cred;
2837cf2e340fSJANAK DESAI 
2838b2e0d987SEric W. Biederman 	if (new_fs || new_fd || do_sysvsem || new_cred || new_nsproxy) {
28399edff4abSManfred Spraul 		if (do_sysvsem) {
28409edff4abSManfred Spraul 			/*
28419edff4abSManfred Spraul 			 * CLONE_SYSVSEM is equivalent to sys_exit().
28429edff4abSManfred Spraul 			 */
28439edff4abSManfred Spraul 			exit_sem(current);
28449edff4abSManfred Spraul 		}
2845ab602f79SJack Miller 		if (unshare_flags & CLONE_NEWIPC) {
2846ab602f79SJack Miller 			/* Orphan segments in old ns (see sem above). */
2847ab602f79SJack Miller 			exit_shm(current);
2848ab602f79SJack Miller 			shm_init_task(current);
2849ab602f79SJack Miller 		}
2850ab516013SSerge E. Hallyn 
28516f977e6bSAlan Cox 		if (new_nsproxy)
2852cf7b708cSPavel Emelyanov 			switch_task_namespaces(current, new_nsproxy);
2853cf2e340fSJANAK DESAI 
2854cf7b708cSPavel Emelyanov 		task_lock(current);
2855cf7b708cSPavel Emelyanov 
2856cf2e340fSJANAK DESAI 		if (new_fs) {
2857cf2e340fSJANAK DESAI 			fs = current->fs;
28582a4419b5SNick Piggin 			spin_lock(&fs->lock);
2859cf2e340fSJANAK DESAI 			current->fs = new_fs;
2860498052bbSAl Viro 			if (--fs->users)
2861498052bbSAl Viro 				new_fs = NULL;
2862498052bbSAl Viro 			else
2863cf2e340fSJANAK DESAI 				new_fs = fs;
28642a4419b5SNick Piggin 			spin_unlock(&fs->lock);
2865cf2e340fSJANAK DESAI 		}
2866cf2e340fSJANAK DESAI 
2867cf2e340fSJANAK DESAI 		if (new_fd) {
2868cf2e340fSJANAK DESAI 			fd = current->files;
2869cf2e340fSJANAK DESAI 			current->files = new_fd;
2870cf2e340fSJANAK DESAI 			new_fd = fd;
2871cf2e340fSJANAK DESAI 		}
2872cf2e340fSJANAK DESAI 
2873cf2e340fSJANAK DESAI 		task_unlock(current);
2874b2e0d987SEric W. Biederman 
2875b2e0d987SEric W. Biederman 		if (new_cred) {
2876b2e0d987SEric W. Biederman 			/* Install the new user namespace */
2877b2e0d987SEric W. Biederman 			commit_creds(new_cred);
2878b2e0d987SEric W. Biederman 			new_cred = NULL;
2879b2e0d987SEric W. Biederman 		}
2880cf2e340fSJANAK DESAI 	}
2881cf2e340fSJANAK DESAI 
2882e4222673SHari Bathini 	perf_event_namespaces(current);
2883e4222673SHari Bathini 
2884b2e0d987SEric W. Biederman bad_unshare_cleanup_cred:
2885b2e0d987SEric W. Biederman 	if (new_cred)
2886b2e0d987SEric W. Biederman 		put_cred(new_cred);
2887cf2e340fSJANAK DESAI bad_unshare_cleanup_fd:
2888cf2e340fSJANAK DESAI 	if (new_fd)
2889cf2e340fSJANAK DESAI 		put_files_struct(new_fd);
2890cf2e340fSJANAK DESAI 
2891cf2e340fSJANAK DESAI bad_unshare_cleanup_fs:
2892cf2e340fSJANAK DESAI 	if (new_fs)
2893498052bbSAl Viro 		free_fs_struct(new_fs);
2894cf2e340fSJANAK DESAI 
2895cf2e340fSJANAK DESAI bad_unshare_out:
2896cf2e340fSJANAK DESAI 	return err;
2897cf2e340fSJANAK DESAI }
28983b125388SAl Viro 
28999b32105eSDominik Brodowski SYSCALL_DEFINE1(unshare, unsigned long, unshare_flags)
29009b32105eSDominik Brodowski {
29019b32105eSDominik Brodowski 	return ksys_unshare(unshare_flags);
29029b32105eSDominik Brodowski }
29039b32105eSDominik Brodowski 
29043b125388SAl Viro /*
29053b125388SAl Viro  *	Helper to unshare the files of the current task.
29063b125388SAl Viro  *	We don't want to expose copy_files internals to
29073b125388SAl Viro  *	the exec layer of the kernel.
29083b125388SAl Viro  */
29093b125388SAl Viro 
29103b125388SAl Viro int unshare_files(struct files_struct **displaced)
29113b125388SAl Viro {
29123b125388SAl Viro 	struct task_struct *task = current;
291350704516SAl Viro 	struct files_struct *copy = NULL;
29143b125388SAl Viro 	int error;
29153b125388SAl Viro 
29163b125388SAl Viro 	error = unshare_fd(CLONE_FILES, &copy);
29173b125388SAl Viro 	if (error || !copy) {
29183b125388SAl Viro 		*displaced = NULL;
29193b125388SAl Viro 		return error;
29203b125388SAl Viro 	}
29213b125388SAl Viro 	*displaced = task->files;
29223b125388SAl Viro 	task_lock(task);
29233b125388SAl Viro 	task->files = copy;
29243b125388SAl Viro 	task_unlock(task);
29253b125388SAl Viro 	return 0;
29263b125388SAl Viro }
292716db3d3fSHeinrich Schuchardt 
292816db3d3fSHeinrich Schuchardt int sysctl_max_threads(struct ctl_table *table, int write,
292916db3d3fSHeinrich Schuchardt 		       void __user *buffer, size_t *lenp, loff_t *ppos)
293016db3d3fSHeinrich Schuchardt {
293116db3d3fSHeinrich Schuchardt 	struct ctl_table t;
293216db3d3fSHeinrich Schuchardt 	int ret;
293316db3d3fSHeinrich Schuchardt 	int threads = max_threads;
293416db3d3fSHeinrich Schuchardt 	int min = MIN_THREADS;
293516db3d3fSHeinrich Schuchardt 	int max = MAX_THREADS;
293616db3d3fSHeinrich Schuchardt 
293716db3d3fSHeinrich Schuchardt 	t = *table;
293816db3d3fSHeinrich Schuchardt 	t.data = &threads;
293916db3d3fSHeinrich Schuchardt 	t.extra1 = &min;
294016db3d3fSHeinrich Schuchardt 	t.extra2 = &max;
294116db3d3fSHeinrich Schuchardt 
294216db3d3fSHeinrich Schuchardt 	ret = proc_dointvec_minmax(&t, write, buffer, lenp, ppos);
294316db3d3fSHeinrich Schuchardt 	if (ret || !write)
294416db3d3fSHeinrich Schuchardt 		return ret;
294516db3d3fSHeinrich Schuchardt 
294616db3d3fSHeinrich Schuchardt 	set_max_threads(threads);
294716db3d3fSHeinrich Schuchardt 
294816db3d3fSHeinrich Schuchardt 	return 0;
294916db3d3fSHeinrich Schuchardt }
2950