xref: /openbmc/linux/kernel/fork.c (revision b612e5df4587c934bd056bf05f4a1deca4de4f75)
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 
1288495f7e6SSai Praneeth Prakhya #define NAMED_ARRAY_INDEX(x)	[x] = __stringify(x)
1298495f7e6SSai Praneeth Prakhya 
1308495f7e6SSai Praneeth Prakhya static const char * const resident_page_types[] = {
1318495f7e6SSai Praneeth Prakhya 	NAMED_ARRAY_INDEX(MM_FILEPAGES),
1328495f7e6SSai Praneeth Prakhya 	NAMED_ARRAY_INDEX(MM_ANONPAGES),
1338495f7e6SSai Praneeth Prakhya 	NAMED_ARRAY_INDEX(MM_SWAPENTS),
1348495f7e6SSai Praneeth Prakhya 	NAMED_ARRAY_INDEX(MM_SHMEMPAGES),
1358495f7e6SSai Praneeth Prakhya };
1368495f7e6SSai Praneeth Prakhya 
1371da177e4SLinus Torvalds DEFINE_PER_CPU(unsigned long, process_counts) = 0;
1381da177e4SLinus Torvalds 
1391da177e4SLinus Torvalds __cacheline_aligned DEFINE_RWLOCK(tasklist_lock);  /* outer */
140db1466b3SPaul E. McKenney 
141db1466b3SPaul E. McKenney #ifdef CONFIG_PROVE_RCU
142db1466b3SPaul E. McKenney int lockdep_tasklist_lock_is_held(void)
143db1466b3SPaul E. McKenney {
144db1466b3SPaul E. McKenney 	return lockdep_is_held(&tasklist_lock);
145db1466b3SPaul E. McKenney }
146db1466b3SPaul E. McKenney EXPORT_SYMBOL_GPL(lockdep_tasklist_lock_is_held);
147db1466b3SPaul E. McKenney #endif /* #ifdef CONFIG_PROVE_RCU */
1481da177e4SLinus Torvalds 
1491da177e4SLinus Torvalds int nr_processes(void)
1501da177e4SLinus Torvalds {
1511da177e4SLinus Torvalds 	int cpu;
1521da177e4SLinus Torvalds 	int total = 0;
1531da177e4SLinus Torvalds 
1541d510750SIan Campbell 	for_each_possible_cpu(cpu)
1551da177e4SLinus Torvalds 		total += per_cpu(process_counts, cpu);
1561da177e4SLinus Torvalds 
1571da177e4SLinus Torvalds 	return total;
1581da177e4SLinus Torvalds }
1591da177e4SLinus Torvalds 
160f19b9f74SAkinobu Mita void __weak arch_release_task_struct(struct task_struct *tsk)
161f19b9f74SAkinobu Mita {
162f19b9f74SAkinobu Mita }
163f19b9f74SAkinobu Mita 
164f5e10287SThomas Gleixner #ifndef CONFIG_ARCH_TASK_STRUCT_ALLOCATOR
165e18b890bSChristoph Lameter static struct kmem_cache *task_struct_cachep;
16641101809SThomas Gleixner 
16741101809SThomas Gleixner static inline struct task_struct *alloc_task_struct_node(int node)
16841101809SThomas Gleixner {
16941101809SThomas Gleixner 	return kmem_cache_alloc_node(task_struct_cachep, GFP_KERNEL, node);
17041101809SThomas Gleixner }
17141101809SThomas Gleixner 
17241101809SThomas Gleixner static inline void free_task_struct(struct task_struct *tsk)
17341101809SThomas Gleixner {
17441101809SThomas Gleixner 	kmem_cache_free(task_struct_cachep, tsk);
17541101809SThomas Gleixner }
1761da177e4SLinus Torvalds #endif
1771da177e4SLinus Torvalds 
178b235beeaSLinus Torvalds #ifndef CONFIG_ARCH_THREAD_STACK_ALLOCATOR
17941101809SThomas Gleixner 
1800d15d74aSThomas Gleixner /*
1810d15d74aSThomas Gleixner  * Allocate pages if THREAD_SIZE is >= PAGE_SIZE, otherwise use a
1820d15d74aSThomas Gleixner  * kmemcache based allocator.
1830d15d74aSThomas Gleixner  */
184ba14a194SAndy Lutomirski # if THREAD_SIZE >= PAGE_SIZE || defined(CONFIG_VMAP_STACK)
185ac496bf4SAndy Lutomirski 
186ac496bf4SAndy Lutomirski #ifdef CONFIG_VMAP_STACK
187ac496bf4SAndy Lutomirski /*
188ac496bf4SAndy Lutomirski  * vmalloc() is a bit slow, and calling vfree() enough times will force a TLB
189ac496bf4SAndy Lutomirski  * flush.  Try to minimize the number of calls by caching stacks.
190ac496bf4SAndy Lutomirski  */
191ac496bf4SAndy Lutomirski #define NR_CACHED_STACKS 2
192ac496bf4SAndy Lutomirski static DEFINE_PER_CPU(struct vm_struct *, cached_stacks[NR_CACHED_STACKS]);
19319659c59SHoeun Ryu 
19419659c59SHoeun Ryu static int free_vm_stack_cache(unsigned int cpu)
19519659c59SHoeun Ryu {
19619659c59SHoeun Ryu 	struct vm_struct **cached_vm_stacks = per_cpu_ptr(cached_stacks, cpu);
19719659c59SHoeun Ryu 	int i;
19819659c59SHoeun Ryu 
19919659c59SHoeun Ryu 	for (i = 0; i < NR_CACHED_STACKS; i++) {
20019659c59SHoeun Ryu 		struct vm_struct *vm_stack = cached_vm_stacks[i];
20119659c59SHoeun Ryu 
20219659c59SHoeun Ryu 		if (!vm_stack)
20319659c59SHoeun Ryu 			continue;
20419659c59SHoeun Ryu 
20519659c59SHoeun Ryu 		vfree(vm_stack->addr);
20619659c59SHoeun Ryu 		cached_vm_stacks[i] = NULL;
20719659c59SHoeun Ryu 	}
20819659c59SHoeun Ryu 
20919659c59SHoeun Ryu 	return 0;
21019659c59SHoeun Ryu }
211ac496bf4SAndy Lutomirski #endif
212ac496bf4SAndy Lutomirski 
213ba14a194SAndy Lutomirski static unsigned long *alloc_thread_stack_node(struct task_struct *tsk, int node)
214b69c49b7SFUJITA Tomonori {
215ba14a194SAndy Lutomirski #ifdef CONFIG_VMAP_STACK
216ac496bf4SAndy Lutomirski 	void *stack;
217ac496bf4SAndy Lutomirski 	int i;
218ac496bf4SAndy Lutomirski 
219ac496bf4SAndy Lutomirski 	for (i = 0; i < NR_CACHED_STACKS; i++) {
220112166f8SChristoph Lameter 		struct vm_struct *s;
221112166f8SChristoph Lameter 
222112166f8SChristoph Lameter 		s = this_cpu_xchg(cached_stacks[i], NULL);
223ac496bf4SAndy Lutomirski 
224ac496bf4SAndy Lutomirski 		if (!s)
225ac496bf4SAndy Lutomirski 			continue;
226ac496bf4SAndy Lutomirski 
227ca182551SKonstantin Khlebnikov 		/* Clear stale pointers from reused stack. */
228ca182551SKonstantin Khlebnikov 		memset(s->addr, 0, THREAD_SIZE);
229e01e8063SKees Cook 
230ac496bf4SAndy Lutomirski 		tsk->stack_vm_area = s;
231ba4a4574SShakeel Butt 		tsk->stack = s->addr;
232ac496bf4SAndy Lutomirski 		return s->addr;
233ac496bf4SAndy Lutomirski 	}
234ac496bf4SAndy Lutomirski 
2359b6f7e16SRoman Gushchin 	/*
2369b6f7e16SRoman Gushchin 	 * Allocated stacks are cached and later reused by new threads,
2379b6f7e16SRoman Gushchin 	 * so memcg accounting is performed manually on assigning/releasing
2389b6f7e16SRoman Gushchin 	 * stacks to tasks. Drop __GFP_ACCOUNT.
2399b6f7e16SRoman Gushchin 	 */
24048ac3c18SMark Rutland 	stack = __vmalloc_node_range(THREAD_SIZE, THREAD_ALIGN,
241ba14a194SAndy Lutomirski 				     VMALLOC_START, VMALLOC_END,
2429b6f7e16SRoman Gushchin 				     THREADINFO_GFP & ~__GFP_ACCOUNT,
243ba14a194SAndy Lutomirski 				     PAGE_KERNEL,
244ac496bf4SAndy Lutomirski 				     0, node, __builtin_return_address(0));
245ba14a194SAndy Lutomirski 
246ba14a194SAndy Lutomirski 	/*
247ba14a194SAndy Lutomirski 	 * We can't call find_vm_area() in interrupt context, and
248ba14a194SAndy Lutomirski 	 * free_thread_stack() can be called in interrupt context,
249ba14a194SAndy Lutomirski 	 * so cache the vm_struct.
250ba14a194SAndy Lutomirski 	 */
2515eed6f1dSRik van Riel 	if (stack) {
252ba14a194SAndy Lutomirski 		tsk->stack_vm_area = find_vm_area(stack);
2535eed6f1dSRik van Riel 		tsk->stack = stack;
2545eed6f1dSRik van Riel 	}
255ba14a194SAndy Lutomirski 	return stack;
256ba14a194SAndy Lutomirski #else
2574949148aSVladimir Davydov 	struct page *page = alloc_pages_node(node, THREADINFO_GFP,
2582889f608SThomas Gleixner 					     THREAD_SIZE_ORDER);
259b6a84016SEric Dumazet 
2601bf4580eSAndrea Arcangeli 	if (likely(page)) {
2611bf4580eSAndrea Arcangeli 		tsk->stack = page_address(page);
2621bf4580eSAndrea Arcangeli 		return tsk->stack;
2631bf4580eSAndrea Arcangeli 	}
2641bf4580eSAndrea Arcangeli 	return NULL;
265ba14a194SAndy Lutomirski #endif
266b69c49b7SFUJITA Tomonori }
267b69c49b7SFUJITA Tomonori 
268ba14a194SAndy Lutomirski static inline void free_thread_stack(struct task_struct *tsk)
269b69c49b7SFUJITA Tomonori {
270ac496bf4SAndy Lutomirski #ifdef CONFIG_VMAP_STACK
2719b6f7e16SRoman Gushchin 	struct vm_struct *vm = task_stack_vm_area(tsk);
2729b6f7e16SRoman Gushchin 
2739b6f7e16SRoman Gushchin 	if (vm) {
274ac496bf4SAndy Lutomirski 		int i;
275ac496bf4SAndy Lutomirski 
2769b6f7e16SRoman Gushchin 		for (i = 0; i < THREAD_SIZE / PAGE_SIZE; i++) {
2779b6f7e16SRoman Gushchin 			mod_memcg_page_state(vm->pages[i],
2789b6f7e16SRoman Gushchin 					     MEMCG_KERNEL_STACK_KB,
2799b6f7e16SRoman Gushchin 					     -(int)(PAGE_SIZE / 1024));
2809b6f7e16SRoman Gushchin 
2819b6f7e16SRoman Gushchin 			memcg_kmem_uncharge(vm->pages[i], 0);
2829b6f7e16SRoman Gushchin 		}
2839b6f7e16SRoman Gushchin 
284ac496bf4SAndy Lutomirski 		for (i = 0; i < NR_CACHED_STACKS; i++) {
285112166f8SChristoph Lameter 			if (this_cpu_cmpxchg(cached_stacks[i],
286112166f8SChristoph Lameter 					NULL, tsk->stack_vm_area) != NULL)
287ac496bf4SAndy Lutomirski 				continue;
288ac496bf4SAndy Lutomirski 
289ac496bf4SAndy Lutomirski 			return;
290ac496bf4SAndy Lutomirski 		}
291ac496bf4SAndy Lutomirski 
2920f110a9bSAndrey Ryabinin 		vfree_atomic(tsk->stack);
293ac496bf4SAndy Lutomirski 		return;
294ac496bf4SAndy Lutomirski 	}
295ac496bf4SAndy Lutomirski #endif
296ac496bf4SAndy Lutomirski 
297ba14a194SAndy Lutomirski 	__free_pages(virt_to_page(tsk->stack), THREAD_SIZE_ORDER);
298b69c49b7SFUJITA Tomonori }
2990d15d74aSThomas Gleixner # else
300b235beeaSLinus Torvalds static struct kmem_cache *thread_stack_cache;
3010d15d74aSThomas Gleixner 
3029521d399SMichael Ellerman static unsigned long *alloc_thread_stack_node(struct task_struct *tsk,
3030d15d74aSThomas Gleixner 						  int node)
3040d15d74aSThomas Gleixner {
3055eed6f1dSRik van Riel 	unsigned long *stack;
3065eed6f1dSRik van Riel 	stack = kmem_cache_alloc_node(thread_stack_cache, THREADINFO_GFP, node);
3075eed6f1dSRik van Riel 	tsk->stack = stack;
3085eed6f1dSRik van Riel 	return stack;
3090d15d74aSThomas Gleixner }
3100d15d74aSThomas Gleixner 
311ba14a194SAndy Lutomirski static void free_thread_stack(struct task_struct *tsk)
3120d15d74aSThomas Gleixner {
313ba14a194SAndy Lutomirski 	kmem_cache_free(thread_stack_cache, tsk->stack);
3140d15d74aSThomas Gleixner }
3150d15d74aSThomas Gleixner 
316b235beeaSLinus Torvalds void thread_stack_cache_init(void)
3170d15d74aSThomas Gleixner {
318f9d29946SDavid Windsor 	thread_stack_cache = kmem_cache_create_usercopy("thread_stack",
319f9d29946SDavid Windsor 					THREAD_SIZE, THREAD_SIZE, 0, 0,
320f9d29946SDavid Windsor 					THREAD_SIZE, NULL);
321b235beeaSLinus Torvalds 	BUG_ON(thread_stack_cache == NULL);
3220d15d74aSThomas Gleixner }
3230d15d74aSThomas Gleixner # endif
324b69c49b7SFUJITA Tomonori #endif
325b69c49b7SFUJITA Tomonori 
3261da177e4SLinus Torvalds /* SLAB cache for signal_struct structures (tsk->signal) */
327e18b890bSChristoph Lameter static struct kmem_cache *signal_cachep;
3281da177e4SLinus Torvalds 
3291da177e4SLinus Torvalds /* SLAB cache for sighand_struct structures (tsk->sighand) */
330e18b890bSChristoph Lameter struct kmem_cache *sighand_cachep;
3311da177e4SLinus Torvalds 
3321da177e4SLinus Torvalds /* SLAB cache for files_struct structures (tsk->files) */
333e18b890bSChristoph Lameter struct kmem_cache *files_cachep;
3341da177e4SLinus Torvalds 
3351da177e4SLinus Torvalds /* SLAB cache for fs_struct structures (tsk->fs) */
336e18b890bSChristoph Lameter struct kmem_cache *fs_cachep;
3371da177e4SLinus Torvalds 
3381da177e4SLinus Torvalds /* SLAB cache for vm_area_struct structures */
3393928d4f5SLinus Torvalds static struct kmem_cache *vm_area_cachep;
3401da177e4SLinus Torvalds 
3411da177e4SLinus Torvalds /* SLAB cache for mm_struct structures (tsk->mm) */
342e18b890bSChristoph Lameter static struct kmem_cache *mm_cachep;
3431da177e4SLinus Torvalds 
344490fc053SLinus Torvalds struct vm_area_struct *vm_area_alloc(struct mm_struct *mm)
3453928d4f5SLinus Torvalds {
346a670468fSAndrew Morton 	struct vm_area_struct *vma;
347490fc053SLinus Torvalds 
348a670468fSAndrew Morton 	vma = kmem_cache_alloc(vm_area_cachep, GFP_KERNEL);
349027232daSKirill A. Shutemov 	if (vma)
350027232daSKirill A. Shutemov 		vma_init(vma, mm);
351490fc053SLinus Torvalds 	return vma;
3523928d4f5SLinus Torvalds }
3533928d4f5SLinus Torvalds 
3543928d4f5SLinus Torvalds struct vm_area_struct *vm_area_dup(struct vm_area_struct *orig)
3553928d4f5SLinus Torvalds {
35695faf699SLinus Torvalds 	struct vm_area_struct *new = kmem_cache_alloc(vm_area_cachep, GFP_KERNEL);
35795faf699SLinus Torvalds 
35895faf699SLinus Torvalds 	if (new) {
35995faf699SLinus Torvalds 		*new = *orig;
36095faf699SLinus Torvalds 		INIT_LIST_HEAD(&new->anon_vma_chain);
36195faf699SLinus Torvalds 	}
36295faf699SLinus Torvalds 	return new;
3633928d4f5SLinus Torvalds }
3643928d4f5SLinus Torvalds 
3653928d4f5SLinus Torvalds void vm_area_free(struct vm_area_struct *vma)
3663928d4f5SLinus Torvalds {
3673928d4f5SLinus Torvalds 	kmem_cache_free(vm_area_cachep, vma);
3683928d4f5SLinus Torvalds }
3693928d4f5SLinus Torvalds 
370ba14a194SAndy Lutomirski static void account_kernel_stack(struct task_struct *tsk, int account)
371c6a7f572SKOSAKI Motohiro {
372ba14a194SAndy Lutomirski 	void *stack = task_stack_page(tsk);
373ba14a194SAndy Lutomirski 	struct vm_struct *vm = task_stack_vm_area(tsk);
374ba14a194SAndy Lutomirski 
375ba14a194SAndy Lutomirski 	BUILD_BUG_ON(IS_ENABLED(CONFIG_VMAP_STACK) && PAGE_SIZE % 1024 != 0);
376ba14a194SAndy Lutomirski 
377ba14a194SAndy Lutomirski 	if (vm) {
378ba14a194SAndy Lutomirski 		int i;
379ba14a194SAndy Lutomirski 
380ba14a194SAndy Lutomirski 		BUG_ON(vm->nr_pages != THREAD_SIZE / PAGE_SIZE);
381ba14a194SAndy Lutomirski 
382ba14a194SAndy Lutomirski 		for (i = 0; i < THREAD_SIZE / PAGE_SIZE; i++) {
383ba14a194SAndy Lutomirski 			mod_zone_page_state(page_zone(vm->pages[i]),
384ba14a194SAndy Lutomirski 					    NR_KERNEL_STACK_KB,
385ba14a194SAndy Lutomirski 					    PAGE_SIZE / 1024 * account);
386ba14a194SAndy Lutomirski 		}
387ba14a194SAndy Lutomirski 	} else {
388ba14a194SAndy Lutomirski 		/*
389ba14a194SAndy Lutomirski 		 * All stack pages are in the same zone and belong to the
390ba14a194SAndy Lutomirski 		 * same memcg.
391ba14a194SAndy Lutomirski 		 */
392efdc9490SAndy Lutomirski 		struct page *first_page = virt_to_page(stack);
393c6a7f572SKOSAKI Motohiro 
394efdc9490SAndy Lutomirski 		mod_zone_page_state(page_zone(first_page), NR_KERNEL_STACK_KB,
395d30dd8beSAndy Lutomirski 				    THREAD_SIZE / 1024 * account);
396efdc9490SAndy Lutomirski 
397ed52be7bSJohannes Weiner 		mod_memcg_page_state(first_page, MEMCG_KERNEL_STACK_KB,
398efdc9490SAndy Lutomirski 				     account * (THREAD_SIZE / 1024));
399c6a7f572SKOSAKI Motohiro 	}
400ba14a194SAndy Lutomirski }
401c6a7f572SKOSAKI Motohiro 
4029b6f7e16SRoman Gushchin static int memcg_charge_kernel_stack(struct task_struct *tsk)
4039b6f7e16SRoman Gushchin {
4049b6f7e16SRoman Gushchin #ifdef CONFIG_VMAP_STACK
4059b6f7e16SRoman Gushchin 	struct vm_struct *vm = task_stack_vm_area(tsk);
4069b6f7e16SRoman Gushchin 	int ret;
4079b6f7e16SRoman Gushchin 
4089b6f7e16SRoman Gushchin 	if (vm) {
4099b6f7e16SRoman Gushchin 		int i;
4109b6f7e16SRoman Gushchin 
4119b6f7e16SRoman Gushchin 		for (i = 0; i < THREAD_SIZE / PAGE_SIZE; i++) {
4129b6f7e16SRoman Gushchin 			/*
4139b6f7e16SRoman Gushchin 			 * If memcg_kmem_charge() fails, page->mem_cgroup
4149b6f7e16SRoman Gushchin 			 * pointer is NULL, and both memcg_kmem_uncharge()
4159b6f7e16SRoman Gushchin 			 * and mod_memcg_page_state() in free_thread_stack()
4169b6f7e16SRoman Gushchin 			 * will ignore this page. So it's safe.
4179b6f7e16SRoman Gushchin 			 */
4189b6f7e16SRoman Gushchin 			ret = memcg_kmem_charge(vm->pages[i], GFP_KERNEL, 0);
4199b6f7e16SRoman Gushchin 			if (ret)
4209b6f7e16SRoman Gushchin 				return ret;
4219b6f7e16SRoman Gushchin 
4229b6f7e16SRoman Gushchin 			mod_memcg_page_state(vm->pages[i],
4239b6f7e16SRoman Gushchin 					     MEMCG_KERNEL_STACK_KB,
4249b6f7e16SRoman Gushchin 					     PAGE_SIZE / 1024);
4259b6f7e16SRoman Gushchin 		}
4269b6f7e16SRoman Gushchin 	}
4279b6f7e16SRoman Gushchin #endif
4289b6f7e16SRoman Gushchin 	return 0;
4299b6f7e16SRoman Gushchin }
4309b6f7e16SRoman Gushchin 
43168f24b08SAndy Lutomirski static void release_task_stack(struct task_struct *tsk)
4321da177e4SLinus Torvalds {
433405c0759SAndy Lutomirski 	if (WARN_ON(tsk->state != TASK_DEAD))
434405c0759SAndy Lutomirski 		return;  /* Better to leak the stack than to free prematurely */
435405c0759SAndy Lutomirski 
436ba14a194SAndy Lutomirski 	account_kernel_stack(tsk, -1);
437ba14a194SAndy Lutomirski 	free_thread_stack(tsk);
43868f24b08SAndy Lutomirski 	tsk->stack = NULL;
43968f24b08SAndy Lutomirski #ifdef CONFIG_VMAP_STACK
44068f24b08SAndy Lutomirski 	tsk->stack_vm_area = NULL;
44168f24b08SAndy Lutomirski #endif
44268f24b08SAndy Lutomirski }
44368f24b08SAndy Lutomirski 
44468f24b08SAndy Lutomirski #ifdef CONFIG_THREAD_INFO_IN_TASK
44568f24b08SAndy Lutomirski void put_task_stack(struct task_struct *tsk)
44668f24b08SAndy Lutomirski {
447f0b89d39SElena Reshetova 	if (refcount_dec_and_test(&tsk->stack_refcount))
44868f24b08SAndy Lutomirski 		release_task_stack(tsk);
44968f24b08SAndy Lutomirski }
45068f24b08SAndy Lutomirski #endif
45168f24b08SAndy Lutomirski 
45268f24b08SAndy Lutomirski void free_task(struct task_struct *tsk)
45368f24b08SAndy Lutomirski {
45468f24b08SAndy Lutomirski #ifndef CONFIG_THREAD_INFO_IN_TASK
45568f24b08SAndy Lutomirski 	/*
45668f24b08SAndy Lutomirski 	 * The task is finally done with both the stack and thread_info,
45768f24b08SAndy Lutomirski 	 * so free both.
45868f24b08SAndy Lutomirski 	 */
45968f24b08SAndy Lutomirski 	release_task_stack(tsk);
46068f24b08SAndy Lutomirski #else
46168f24b08SAndy Lutomirski 	/*
46268f24b08SAndy Lutomirski 	 * If the task had a separate stack allocation, it should be gone
46368f24b08SAndy Lutomirski 	 * by now.
46468f24b08SAndy Lutomirski 	 */
465f0b89d39SElena Reshetova 	WARN_ON_ONCE(refcount_read(&tsk->stack_refcount) != 0);
46668f24b08SAndy Lutomirski #endif
46723f78d4aSIngo Molnar 	rt_mutex_debug_task_free(tsk);
468fb52607aSFrederic Weisbecker 	ftrace_graph_exit_task(tsk);
469e2cfabdfSWill Drewry 	put_seccomp_filter(tsk);
470f19b9f74SAkinobu Mita 	arch_release_task_struct(tsk);
4711da5c46fSOleg Nesterov 	if (tsk->flags & PF_KTHREAD)
4721da5c46fSOleg Nesterov 		free_kthread_struct(tsk);
4731da177e4SLinus Torvalds 	free_task_struct(tsk);
4741da177e4SLinus Torvalds }
4751da177e4SLinus Torvalds EXPORT_SYMBOL(free_task);
4761da177e4SLinus Torvalds 
4771da177e4SLinus Torvalds #ifdef CONFIG_MMU
4780766f788SEmese Revfy static __latent_entropy int dup_mmap(struct mm_struct *mm,
4790766f788SEmese Revfy 					struct mm_struct *oldmm)
4801da177e4SLinus Torvalds {
481297c5eeeSLinus Torvalds 	struct vm_area_struct *mpnt, *tmp, *prev, **pprev;
4821da177e4SLinus Torvalds 	struct rb_node **rb_link, *rb_parent;
4831da177e4SLinus Torvalds 	int retval;
4841da177e4SLinus Torvalds 	unsigned long charge;
485893e26e6SPavel Emelyanov 	LIST_HEAD(uf);
4861da177e4SLinus Torvalds 
48732cdba1eSOleg Nesterov 	uprobe_start_dup_mmap();
4887c051267SMichal Hocko 	if (down_write_killable(&oldmm->mmap_sem)) {
4897c051267SMichal Hocko 		retval = -EINTR;
4907c051267SMichal Hocko 		goto fail_uprobe_end;
4917c051267SMichal Hocko 	}
492ec8c0446SRalf Baechle 	flush_cache_dup_mm(oldmm);
493f8ac4ec9SOleg Nesterov 	uprobe_dup_mmap(oldmm, mm);
494ad339451SIngo Molnar 	/*
495ad339451SIngo Molnar 	 * Not linked in yet - no deadlock potential:
496ad339451SIngo Molnar 	 */
497ad339451SIngo Molnar 	down_write_nested(&mm->mmap_sem, SINGLE_DEPTH_NESTING);
4987ee78232SHugh Dickins 
49990f31d0eSKonstantin Khlebnikov 	/* No ordering required: file already has been exposed. */
50090f31d0eSKonstantin Khlebnikov 	RCU_INIT_POINTER(mm->exe_file, get_mm_exe_file(oldmm));
50190f31d0eSKonstantin Khlebnikov 
5024f7d4614SVladimir Davydov 	mm->total_vm = oldmm->total_vm;
50384638335SKonstantin Khlebnikov 	mm->data_vm = oldmm->data_vm;
5044f7d4614SVladimir Davydov 	mm->exec_vm = oldmm->exec_vm;
5054f7d4614SVladimir Davydov 	mm->stack_vm = oldmm->stack_vm;
5064f7d4614SVladimir Davydov 
5071da177e4SLinus Torvalds 	rb_link = &mm->mm_rb.rb_node;
5081da177e4SLinus Torvalds 	rb_parent = NULL;
5091da177e4SLinus Torvalds 	pprev = &mm->mmap;
510f8af4da3SHugh Dickins 	retval = ksm_fork(mm, oldmm);
511f8af4da3SHugh Dickins 	if (retval)
512f8af4da3SHugh Dickins 		goto out;
513ba76149fSAndrea Arcangeli 	retval = khugepaged_fork(mm, oldmm);
514ba76149fSAndrea Arcangeli 	if (retval)
515ba76149fSAndrea Arcangeli 		goto out;
5161da177e4SLinus Torvalds 
517297c5eeeSLinus Torvalds 	prev = NULL;
518fd3e42fcSHugh Dickins 	for (mpnt = oldmm->mmap; mpnt; mpnt = mpnt->vm_next) {
5191da177e4SLinus Torvalds 		struct file *file;
5201da177e4SLinus Torvalds 
5211da177e4SLinus Torvalds 		if (mpnt->vm_flags & VM_DONTCOPY) {
52284638335SKonstantin Khlebnikov 			vm_stat_account(mm, mpnt->vm_flags, -vma_pages(mpnt));
5231da177e4SLinus Torvalds 			continue;
5241da177e4SLinus Torvalds 		}
5251da177e4SLinus Torvalds 		charge = 0;
526655c79bbSTetsuo Handa 		/*
527655c79bbSTetsuo Handa 		 * Don't duplicate many vmas if we've been oom-killed (for
528655c79bbSTetsuo Handa 		 * example)
529655c79bbSTetsuo Handa 		 */
530655c79bbSTetsuo Handa 		if (fatal_signal_pending(current)) {
531655c79bbSTetsuo Handa 			retval = -EINTR;
532655c79bbSTetsuo Handa 			goto out;
533655c79bbSTetsuo Handa 		}
5341da177e4SLinus Torvalds 		if (mpnt->vm_flags & VM_ACCOUNT) {
535b2412b7fSHuang Shijie 			unsigned long len = vma_pages(mpnt);
536b2412b7fSHuang Shijie 
537191c5424SAl Viro 			if (security_vm_enough_memory_mm(oldmm, len)) /* sic */
5381da177e4SLinus Torvalds 				goto fail_nomem;
5391da177e4SLinus Torvalds 			charge = len;
5401da177e4SLinus Torvalds 		}
5413928d4f5SLinus Torvalds 		tmp = vm_area_dup(mpnt);
5421da177e4SLinus Torvalds 		if (!tmp)
5431da177e4SLinus Torvalds 			goto fail_nomem;
544ef0855d3SOleg Nesterov 		retval = vma_dup_policy(mpnt, tmp);
545ef0855d3SOleg Nesterov 		if (retval)
5461da177e4SLinus Torvalds 			goto fail_nomem_policy;
547a247c3a9SAndrea Arcangeli 		tmp->vm_mm = mm;
548893e26e6SPavel Emelyanov 		retval = dup_userfaultfd(tmp, &uf);
549893e26e6SPavel Emelyanov 		if (retval)
550893e26e6SPavel Emelyanov 			goto fail_nomem_anon_vma_fork;
551d2cd9edeSRik van Riel 		if (tmp->vm_flags & VM_WIPEONFORK) {
552d2cd9edeSRik van Riel 			/* VM_WIPEONFORK gets a clean slate in the child. */
553d2cd9edeSRik van Riel 			tmp->anon_vma = NULL;
554d2cd9edeSRik van Riel 			if (anon_vma_prepare(tmp))
555d2cd9edeSRik van Riel 				goto fail_nomem_anon_vma_fork;
556d2cd9edeSRik van Riel 		} else if (anon_vma_fork(tmp, mpnt))
5575beb4930SRik van Riel 			goto fail_nomem_anon_vma_fork;
558893e26e6SPavel Emelyanov 		tmp->vm_flags &= ~(VM_LOCKED | VM_LOCKONFAULT);
559297c5eeeSLinus Torvalds 		tmp->vm_next = tmp->vm_prev = NULL;
5601da177e4SLinus Torvalds 		file = tmp->vm_file;
5611da177e4SLinus Torvalds 		if (file) {
562496ad9aaSAl Viro 			struct inode *inode = file_inode(file);
563b88ed205SHugh Dickins 			struct address_space *mapping = file->f_mapping;
564b88ed205SHugh Dickins 
5651da177e4SLinus Torvalds 			get_file(file);
5661da177e4SLinus Torvalds 			if (tmp->vm_flags & VM_DENYWRITE)
5671da177e4SLinus Torvalds 				atomic_dec(&inode->i_writecount);
56883cde9e8SDavidlohr Bueso 			i_mmap_lock_write(mapping);
569b88ed205SHugh Dickins 			if (tmp->vm_flags & VM_SHARED)
5704bb5f5d9SDavid Herrmann 				atomic_inc(&mapping->i_mmap_writable);
571b88ed205SHugh Dickins 			flush_dcache_mmap_lock(mapping);
572b88ed205SHugh Dickins 			/* insert tmp into the share list, just after mpnt */
5739826a516SMichel Lespinasse 			vma_interval_tree_insert_after(tmp, mpnt,
5749826a516SMichel Lespinasse 					&mapping->i_mmap);
575b88ed205SHugh Dickins 			flush_dcache_mmap_unlock(mapping);
57683cde9e8SDavidlohr Bueso 			i_mmap_unlock_write(mapping);
5771da177e4SLinus Torvalds 		}
5781da177e4SLinus Torvalds 
5791da177e4SLinus Torvalds 		/*
580a1e78772SMel Gorman 		 * Clear hugetlb-related page reserves for children. This only
581a1e78772SMel Gorman 		 * affects MAP_PRIVATE mappings. Faults generated by the child
582a1e78772SMel Gorman 		 * are not guaranteed to succeed, even if read-only
583a1e78772SMel Gorman 		 */
584a1e78772SMel Gorman 		if (is_vm_hugetlb_page(tmp))
585a1e78772SMel Gorman 			reset_vma_resv_huge_pages(tmp);
586a1e78772SMel Gorman 
587a1e78772SMel Gorman 		/*
5887ee78232SHugh Dickins 		 * Link in the new vma and copy the page table entries.
5891da177e4SLinus Torvalds 		 */
5901da177e4SLinus Torvalds 		*pprev = tmp;
5911da177e4SLinus Torvalds 		pprev = &tmp->vm_next;
592297c5eeeSLinus Torvalds 		tmp->vm_prev = prev;
593297c5eeeSLinus Torvalds 		prev = tmp;
5941da177e4SLinus Torvalds 
5951da177e4SLinus Torvalds 		__vma_link_rb(mm, tmp, rb_link, rb_parent);
5961da177e4SLinus Torvalds 		rb_link = &tmp->vm_rb.rb_right;
5971da177e4SLinus Torvalds 		rb_parent = &tmp->vm_rb;
5981da177e4SLinus Torvalds 
5991da177e4SLinus Torvalds 		mm->map_count++;
600d2cd9edeSRik van Riel 		if (!(tmp->vm_flags & VM_WIPEONFORK))
6010b0db14cSHugh Dickins 			retval = copy_page_range(mm, oldmm, mpnt);
6021da177e4SLinus Torvalds 
6031da177e4SLinus Torvalds 		if (tmp->vm_ops && tmp->vm_ops->open)
6041da177e4SLinus Torvalds 			tmp->vm_ops->open(tmp);
6051da177e4SLinus Torvalds 
6061da177e4SLinus Torvalds 		if (retval)
6071da177e4SLinus Torvalds 			goto out;
6081da177e4SLinus Torvalds 	}
609d6dd61c8SJeremy Fitzhardinge 	/* a new mm has just been created */
6101ed0cc5aSNadav Amit 	retval = arch_dup_mmap(oldmm, mm);
6111da177e4SLinus Torvalds out:
6127ee78232SHugh Dickins 	up_write(&mm->mmap_sem);
613fd3e42fcSHugh Dickins 	flush_tlb_mm(oldmm);
6141da177e4SLinus Torvalds 	up_write(&oldmm->mmap_sem);
615893e26e6SPavel Emelyanov 	dup_userfaultfd_complete(&uf);
6167c051267SMichal Hocko fail_uprobe_end:
61732cdba1eSOleg Nesterov 	uprobe_end_dup_mmap();
6181da177e4SLinus Torvalds 	return retval;
6195beb4930SRik van Riel fail_nomem_anon_vma_fork:
620ef0855d3SOleg Nesterov 	mpol_put(vma_policy(tmp));
6211da177e4SLinus Torvalds fail_nomem_policy:
6223928d4f5SLinus Torvalds 	vm_area_free(tmp);
6231da177e4SLinus Torvalds fail_nomem:
6241da177e4SLinus Torvalds 	retval = -ENOMEM;
6251da177e4SLinus Torvalds 	vm_unacct_memory(charge);
6261da177e4SLinus Torvalds 	goto out;
6271da177e4SLinus Torvalds }
6281da177e4SLinus Torvalds 
6291da177e4SLinus Torvalds static inline int mm_alloc_pgd(struct mm_struct *mm)
6301da177e4SLinus Torvalds {
6311da177e4SLinus Torvalds 	mm->pgd = pgd_alloc(mm);
6321da177e4SLinus Torvalds 	if (unlikely(!mm->pgd))
6331da177e4SLinus Torvalds 		return -ENOMEM;
6341da177e4SLinus Torvalds 	return 0;
6351da177e4SLinus Torvalds }
6361da177e4SLinus Torvalds 
6371da177e4SLinus Torvalds static inline void mm_free_pgd(struct mm_struct *mm)
6381da177e4SLinus Torvalds {
6395e541973SBenjamin Herrenschmidt 	pgd_free(mm, mm->pgd);
6401da177e4SLinus Torvalds }
6411da177e4SLinus Torvalds #else
64290f31d0eSKonstantin Khlebnikov static int dup_mmap(struct mm_struct *mm, struct mm_struct *oldmm)
64390f31d0eSKonstantin Khlebnikov {
64490f31d0eSKonstantin Khlebnikov 	down_write(&oldmm->mmap_sem);
64590f31d0eSKonstantin Khlebnikov 	RCU_INIT_POINTER(mm->exe_file, get_mm_exe_file(oldmm));
64690f31d0eSKonstantin Khlebnikov 	up_write(&oldmm->mmap_sem);
64790f31d0eSKonstantin Khlebnikov 	return 0;
64890f31d0eSKonstantin Khlebnikov }
6491da177e4SLinus Torvalds #define mm_alloc_pgd(mm)	(0)
6501da177e4SLinus Torvalds #define mm_free_pgd(mm)
6511da177e4SLinus Torvalds #endif /* CONFIG_MMU */
6521da177e4SLinus Torvalds 
653d70f2a14SAndrew Morton static void check_mm(struct mm_struct *mm)
654d70f2a14SAndrew Morton {
655d70f2a14SAndrew Morton 	int i;
656d70f2a14SAndrew Morton 
6578495f7e6SSai Praneeth Prakhya 	BUILD_BUG_ON_MSG(ARRAY_SIZE(resident_page_types) != NR_MM_COUNTERS,
6588495f7e6SSai Praneeth Prakhya 			 "Please make sure 'struct resident_page_types[]' is updated as well");
6598495f7e6SSai Praneeth Prakhya 
660d70f2a14SAndrew Morton 	for (i = 0; i < NR_MM_COUNTERS; i++) {
661d70f2a14SAndrew Morton 		long x = atomic_long_read(&mm->rss_stat.count[i]);
662d70f2a14SAndrew Morton 
663d70f2a14SAndrew Morton 		if (unlikely(x))
6648495f7e6SSai Praneeth Prakhya 			pr_alert("BUG: Bad rss-counter state mm:%p type:%s val:%ld\n",
6658495f7e6SSai Praneeth Prakhya 				 mm, resident_page_types[i], x);
666d70f2a14SAndrew Morton 	}
667d70f2a14SAndrew Morton 
668d70f2a14SAndrew Morton 	if (mm_pgtables_bytes(mm))
669d70f2a14SAndrew Morton 		pr_alert("BUG: non-zero pgtables_bytes on freeing mm: %ld\n",
670d70f2a14SAndrew Morton 				mm_pgtables_bytes(mm));
671d70f2a14SAndrew Morton 
672d70f2a14SAndrew Morton #if defined(CONFIG_TRANSPARENT_HUGEPAGE) && !USE_SPLIT_PMD_PTLOCKS
673d70f2a14SAndrew Morton 	VM_BUG_ON_MM(mm->pmd_huge_pte, mm);
674d70f2a14SAndrew Morton #endif
675d70f2a14SAndrew Morton }
6761da177e4SLinus Torvalds 
677e94b1766SChristoph Lameter #define allocate_mm()	(kmem_cache_alloc(mm_cachep, GFP_KERNEL))
6781da177e4SLinus Torvalds #define free_mm(mm)	(kmem_cache_free(mm_cachep, (mm)))
6791da177e4SLinus Torvalds 
680d70f2a14SAndrew Morton /*
681d70f2a14SAndrew Morton  * Called when the last reference to the mm
682d70f2a14SAndrew Morton  * is dropped: either by a lazy thread or by
683d70f2a14SAndrew Morton  * mmput. Free the page directory and the mm.
684d70f2a14SAndrew Morton  */
685d34bc48fSAndrew Morton void __mmdrop(struct mm_struct *mm)
686d70f2a14SAndrew Morton {
687d70f2a14SAndrew Morton 	BUG_ON(mm == &init_mm);
6883eda69c9SMark Rutland 	WARN_ON_ONCE(mm == current->mm);
6893eda69c9SMark Rutland 	WARN_ON_ONCE(mm == current->active_mm);
690d70f2a14SAndrew Morton 	mm_free_pgd(mm);
691d70f2a14SAndrew Morton 	destroy_context(mm);
692d70f2a14SAndrew Morton 	mmu_notifier_mm_destroy(mm);
693d70f2a14SAndrew Morton 	check_mm(mm);
694d70f2a14SAndrew Morton 	put_user_ns(mm->user_ns);
695d70f2a14SAndrew Morton 	free_mm(mm);
696d70f2a14SAndrew Morton }
697d34bc48fSAndrew Morton EXPORT_SYMBOL_GPL(__mmdrop);
698d70f2a14SAndrew Morton 
699d70f2a14SAndrew Morton static void mmdrop_async_fn(struct work_struct *work)
700d70f2a14SAndrew Morton {
701d70f2a14SAndrew Morton 	struct mm_struct *mm;
702d70f2a14SAndrew Morton 
703d70f2a14SAndrew Morton 	mm = container_of(work, struct mm_struct, async_put_work);
704d70f2a14SAndrew Morton 	__mmdrop(mm);
705d70f2a14SAndrew Morton }
706d70f2a14SAndrew Morton 
707d70f2a14SAndrew Morton static void mmdrop_async(struct mm_struct *mm)
708d70f2a14SAndrew Morton {
709d70f2a14SAndrew Morton 	if (unlikely(atomic_dec_and_test(&mm->mm_count))) {
710d70f2a14SAndrew Morton 		INIT_WORK(&mm->async_put_work, mmdrop_async_fn);
711d70f2a14SAndrew Morton 		schedule_work(&mm->async_put_work);
712d70f2a14SAndrew Morton 	}
713d70f2a14SAndrew Morton }
714d70f2a14SAndrew Morton 
7151da177e4SLinus Torvalds static inline void free_signal_struct(struct signal_struct *sig)
7161da177e4SLinus Torvalds {
7171da177e4SLinus Torvalds 	taskstats_tgid_free(sig);
7181da177e4SLinus Torvalds 	sched_autogroup_exit(sig);
7191da177e4SLinus Torvalds 	/*
7201da177e4SLinus Torvalds 	 * __mmdrop is not safe to call from softirq context on x86 due to
7211da177e4SLinus Torvalds 	 * pgd_dtor so postpone it to the async context
7221da177e4SLinus Torvalds 	 */
7231da177e4SLinus Torvalds 	if (sig->oom_mm)
7241da177e4SLinus Torvalds 		mmdrop_async(sig->oom_mm);
7251da177e4SLinus Torvalds 	kmem_cache_free(signal_cachep, sig);
7261da177e4SLinus Torvalds }
7271da177e4SLinus Torvalds 
7281da177e4SLinus Torvalds static inline void put_signal_struct(struct signal_struct *sig)
7291da177e4SLinus Torvalds {
73060d4de3fSElena Reshetova 	if (refcount_dec_and_test(&sig->sigcnt))
7311da177e4SLinus Torvalds 		free_signal_struct(sig);
7321da177e4SLinus Torvalds }
7331da177e4SLinus Torvalds 
7341da177e4SLinus Torvalds void __put_task_struct(struct task_struct *tsk)
7351da177e4SLinus Torvalds {
7361da177e4SLinus Torvalds 	WARN_ON(!tsk->exit_state);
737ec1d2819SElena Reshetova 	WARN_ON(refcount_read(&tsk->usage));
7381da177e4SLinus Torvalds 	WARN_ON(tsk == current);
7391da177e4SLinus Torvalds 
7401da177e4SLinus Torvalds 	cgroup_free(tsk);
74116d51a59SJann Horn 	task_numa_free(tsk, true);
7421da177e4SLinus Torvalds 	security_task_free(tsk);
7431da177e4SLinus Torvalds 	exit_creds(tsk);
7441da177e4SLinus Torvalds 	delayacct_tsk_free(tsk);
7451da177e4SLinus Torvalds 	put_signal_struct(tsk->signal);
7461da177e4SLinus Torvalds 
7471da177e4SLinus Torvalds 	if (!profile_handoff_task(tsk))
7481da177e4SLinus Torvalds 		free_task(tsk);
7491da177e4SLinus Torvalds }
7501da177e4SLinus Torvalds EXPORT_SYMBOL_GPL(__put_task_struct);
7511da177e4SLinus Torvalds 
7521da177e4SLinus Torvalds void __init __weak arch_task_cache_init(void) { }
7531da177e4SLinus Torvalds 
7541da177e4SLinus Torvalds /*
7551da177e4SLinus Torvalds  * set_max_threads
7561da177e4SLinus Torvalds  */
7571da177e4SLinus Torvalds static void set_max_threads(unsigned int max_threads_suggested)
7581da177e4SLinus Torvalds {
7591da177e4SLinus Torvalds 	u64 threads;
760ca79b0c2SArun KS 	unsigned long nr_pages = totalram_pages();
7611da177e4SLinus Torvalds 
7621da177e4SLinus Torvalds 	/*
7631da177e4SLinus Torvalds 	 * The number of threads shall be limited such that the thread
7641da177e4SLinus Torvalds 	 * structures may only consume a small part of the available memory.
7651da177e4SLinus Torvalds 	 */
7663d6357deSArun KS 	if (fls64(nr_pages) + fls64(PAGE_SIZE) > 64)
7671da177e4SLinus Torvalds 		threads = MAX_THREADS;
7681da177e4SLinus Torvalds 	else
7693d6357deSArun KS 		threads = div64_u64((u64) nr_pages * (u64) PAGE_SIZE,
7701da177e4SLinus Torvalds 				    (u64) THREAD_SIZE * 8UL);
7711da177e4SLinus Torvalds 
7721da177e4SLinus Torvalds 	if (threads > max_threads_suggested)
7731da177e4SLinus Torvalds 		threads = max_threads_suggested;
7741da177e4SLinus Torvalds 
7751da177e4SLinus Torvalds 	max_threads = clamp_t(u64, threads, MIN_THREADS, MAX_THREADS);
7761da177e4SLinus Torvalds }
7771da177e4SLinus Torvalds 
7781da177e4SLinus Torvalds #ifdef CONFIG_ARCH_WANTS_DYNAMIC_TASK_STRUCT
7791da177e4SLinus Torvalds /* Initialized by the architecture: */
7801da177e4SLinus Torvalds int arch_task_struct_size __read_mostly;
7811da177e4SLinus Torvalds #endif
7821da177e4SLinus Torvalds 
7834189ff23SChristoph Hellwig #ifndef CONFIG_ARCH_TASK_STRUCT_ALLOCATOR
7845905429aSKees Cook static void task_struct_whitelist(unsigned long *offset, unsigned long *size)
7855905429aSKees Cook {
7865905429aSKees Cook 	/* Fetch thread_struct whitelist for the architecture. */
7875905429aSKees Cook 	arch_thread_struct_whitelist(offset, size);
7885905429aSKees Cook 
7895905429aSKees Cook 	/*
7905905429aSKees Cook 	 * Handle zero-sized whitelist or empty thread_struct, otherwise
7915905429aSKees Cook 	 * adjust offset to position of thread_struct in task_struct.
7925905429aSKees Cook 	 */
7935905429aSKees Cook 	if (unlikely(*size == 0))
7945905429aSKees Cook 		*offset = 0;
7955905429aSKees Cook 	else
7965905429aSKees Cook 		*offset += offsetof(struct task_struct, thread);
7975905429aSKees Cook }
7984189ff23SChristoph Hellwig #endif /* CONFIG_ARCH_TASK_STRUCT_ALLOCATOR */
7995905429aSKees Cook 
8001da177e4SLinus Torvalds void __init fork_init(void)
8011da177e4SLinus Torvalds {
8021da177e4SLinus Torvalds 	int i;
8031da177e4SLinus Torvalds #ifndef CONFIG_ARCH_TASK_STRUCT_ALLOCATOR
8041da177e4SLinus Torvalds #ifndef ARCH_MIN_TASKALIGN
8051da177e4SLinus Torvalds #define ARCH_MIN_TASKALIGN	0
8061da177e4SLinus Torvalds #endif
8071da177e4SLinus Torvalds 	int align = max_t(int, L1_CACHE_BYTES, ARCH_MIN_TASKALIGN);
8085905429aSKees Cook 	unsigned long useroffset, usersize;
8091da177e4SLinus Torvalds 
8101da177e4SLinus Torvalds 	/* create a slab on which task_structs can be allocated */
8115905429aSKees Cook 	task_struct_whitelist(&useroffset, &usersize);
8125905429aSKees Cook 	task_struct_cachep = kmem_cache_create_usercopy("task_struct",
8131da177e4SLinus Torvalds 			arch_task_struct_size, align,
8145905429aSKees Cook 			SLAB_PANIC|SLAB_ACCOUNT,
8155905429aSKees Cook 			useroffset, usersize, NULL);
8161da177e4SLinus Torvalds #endif
8171da177e4SLinus Torvalds 
8181da177e4SLinus Torvalds 	/* do the arch specific task caches init */
8191da177e4SLinus Torvalds 	arch_task_cache_init();
8201da177e4SLinus Torvalds 
8211da177e4SLinus Torvalds 	set_max_threads(MAX_THREADS);
8221da177e4SLinus Torvalds 
8231da177e4SLinus Torvalds 	init_task.signal->rlim[RLIMIT_NPROC].rlim_cur = max_threads/2;
8241da177e4SLinus Torvalds 	init_task.signal->rlim[RLIMIT_NPROC].rlim_max = max_threads/2;
8251da177e4SLinus Torvalds 	init_task.signal->rlim[RLIMIT_SIGPENDING] =
8261da177e4SLinus Torvalds 		init_task.signal->rlim[RLIMIT_NPROC];
8271da177e4SLinus Torvalds 
8281da177e4SLinus Torvalds 	for (i = 0; i < UCOUNT_COUNTS; i++) {
8291da177e4SLinus Torvalds 		init_user_ns.ucount_max[i] = max_threads/2;
8301da177e4SLinus Torvalds 	}
8311da177e4SLinus Torvalds 
8321da177e4SLinus Torvalds #ifdef CONFIG_VMAP_STACK
8331da177e4SLinus Torvalds 	cpuhp_setup_state(CPUHP_BP_PREPARE_DYN, "fork:vm_stack_cache",
8341da177e4SLinus Torvalds 			  NULL, free_vm_stack_cache);
8351da177e4SLinus Torvalds #endif
8361da177e4SLinus Torvalds 
8371da177e4SLinus Torvalds 	lockdep_init_task(&init_task);
838aad42dd4SNadav Amit 	uprobes_init();
8391da177e4SLinus Torvalds }
8401da177e4SLinus Torvalds 
8411da177e4SLinus Torvalds int __weak arch_dup_task_struct(struct task_struct *dst,
8421da177e4SLinus Torvalds 					       struct task_struct *src)
8431da177e4SLinus Torvalds {
8441da177e4SLinus Torvalds 	*dst = *src;
8451da177e4SLinus Torvalds 	return 0;
8461da177e4SLinus Torvalds }
8471da177e4SLinus Torvalds 
8481da177e4SLinus Torvalds void set_task_stack_end_magic(struct task_struct *tsk)
8491da177e4SLinus Torvalds {
8501da177e4SLinus Torvalds 	unsigned long *stackend;
8511da177e4SLinus Torvalds 
8521da177e4SLinus Torvalds 	stackend = end_of_stack(tsk);
8531da177e4SLinus Torvalds 	*stackend = STACK_END_MAGIC;	/* for overflow detection */
8541da177e4SLinus Torvalds }
8551da177e4SLinus Torvalds 
8561da177e4SLinus Torvalds static struct task_struct *dup_task_struct(struct task_struct *orig, int node)
8571da177e4SLinus Torvalds {
8581da177e4SLinus Torvalds 	struct task_struct *tsk;
8591da177e4SLinus Torvalds 	unsigned long *stack;
8600f4991e8SYueHaibing 	struct vm_struct *stack_vm_area __maybe_unused;
8611da177e4SLinus Torvalds 	int err;
8621da177e4SLinus Torvalds 
8631da177e4SLinus Torvalds 	if (node == NUMA_NO_NODE)
8641da177e4SLinus Torvalds 		node = tsk_fork_get_node(orig);
8651da177e4SLinus Torvalds 	tsk = alloc_task_struct_node(node);
8661da177e4SLinus Torvalds 	if (!tsk)
8671da177e4SLinus Torvalds 		return NULL;
8681da177e4SLinus Torvalds 
8691da177e4SLinus Torvalds 	stack = alloc_thread_stack_node(tsk, node);
8701da177e4SLinus Torvalds 	if (!stack)
8711da177e4SLinus Torvalds 		goto free_tsk;
8721da177e4SLinus Torvalds 
8739b6f7e16SRoman Gushchin 	if (memcg_charge_kernel_stack(tsk))
8749b6f7e16SRoman Gushchin 		goto free_stack;
8759b6f7e16SRoman Gushchin 
8761da177e4SLinus Torvalds 	stack_vm_area = task_stack_vm_area(tsk);
8771da177e4SLinus Torvalds 
8781da177e4SLinus Torvalds 	err = arch_dup_task_struct(tsk, orig);
8791da177e4SLinus Torvalds 
8801da177e4SLinus Torvalds 	/*
8811da177e4SLinus Torvalds 	 * arch_dup_task_struct() clobbers the stack-related fields.  Make
8821da177e4SLinus Torvalds 	 * sure they're properly initialized before using any stack-related
8831da177e4SLinus Torvalds 	 * functions again.
8841da177e4SLinus Torvalds 	 */
8851da177e4SLinus Torvalds 	tsk->stack = stack;
8861da177e4SLinus Torvalds #ifdef CONFIG_VMAP_STACK
8871da177e4SLinus Torvalds 	tsk->stack_vm_area = stack_vm_area;
8881da177e4SLinus Torvalds #endif
8891da177e4SLinus Torvalds #ifdef CONFIG_THREAD_INFO_IN_TASK
890f0b89d39SElena Reshetova 	refcount_set(&tsk->stack_refcount, 1);
8911da177e4SLinus Torvalds #endif
8921da177e4SLinus Torvalds 
8931da177e4SLinus Torvalds 	if (err)
8941da177e4SLinus Torvalds 		goto free_stack;
8951da177e4SLinus Torvalds 
8961da177e4SLinus Torvalds #ifdef CONFIG_SECCOMP
8971da177e4SLinus Torvalds 	/*
8981da177e4SLinus Torvalds 	 * We must handle setting up seccomp filters once we're under
8991da177e4SLinus Torvalds 	 * the sighand lock in case orig has changed between now and
9001da177e4SLinus Torvalds 	 * then. Until then, filter must be NULL to avoid messing up
9011da177e4SLinus Torvalds 	 * the usage counts on the error path calling free_task.
9021da177e4SLinus Torvalds 	 */
9031da177e4SLinus Torvalds 	tsk->seccomp.filter = NULL;
9041da177e4SLinus Torvalds #endif
9051da177e4SLinus Torvalds 
9061da177e4SLinus Torvalds 	setup_thread_stack(tsk, orig);
9071da177e4SLinus Torvalds 	clear_user_return_notifier(tsk);
9081da177e4SLinus Torvalds 	clear_tsk_need_resched(tsk);
9091da177e4SLinus Torvalds 	set_task_stack_end_magic(tsk);
9101da177e4SLinus Torvalds 
911050e9baaSLinus Torvalds #ifdef CONFIG_STACKPROTECTOR
9121da177e4SLinus Torvalds 	tsk->stack_canary = get_random_canary();
9131da177e4SLinus Torvalds #endif
9143bd37062SSebastian Andrzej Siewior 	if (orig->cpus_ptr == &orig->cpus_mask)
9153bd37062SSebastian Andrzej Siewior 		tsk->cpus_ptr = &tsk->cpus_mask;
9161da177e4SLinus Torvalds 
9171da177e4SLinus Torvalds 	/*
9180ff7b2cfSEric W. Biederman 	 * One for the user space visible state that goes away when reaped.
9190ff7b2cfSEric W. Biederman 	 * One for the scheduler.
9201da177e4SLinus Torvalds 	 */
9210ff7b2cfSEric W. Biederman 	refcount_set(&tsk->rcu_users, 2);
9220ff7b2cfSEric W. Biederman 	/* One for the rcu users */
9230ff7b2cfSEric W. Biederman 	refcount_set(&tsk->usage, 1);
9241da177e4SLinus Torvalds #ifdef CONFIG_BLK_DEV_IO_TRACE
9251da177e4SLinus Torvalds 	tsk->btrace_seq = 0;
9261da177e4SLinus Torvalds #endif
9271da177e4SLinus Torvalds 	tsk->splice_pipe = NULL;
9281da177e4SLinus Torvalds 	tsk->task_frag.page = NULL;
9291da177e4SLinus Torvalds 	tsk->wake_q.next = NULL;
9301da177e4SLinus Torvalds 
9311da177e4SLinus Torvalds 	account_kernel_stack(tsk, 1);
9321da177e4SLinus Torvalds 
9331da177e4SLinus Torvalds 	kcov_task_init(tsk);
9341da177e4SLinus Torvalds 
9351da177e4SLinus Torvalds #ifdef CONFIG_FAULT_INJECTION
9361da177e4SLinus Torvalds 	tsk->fail_nth = 0;
9371da177e4SLinus Torvalds #endif
9381da177e4SLinus Torvalds 
9392c323017SJosef Bacik #ifdef CONFIG_BLK_CGROUP
9402c323017SJosef Bacik 	tsk->throttle_queue = NULL;
9412c323017SJosef Bacik 	tsk->use_memdelay = 0;
9422c323017SJosef Bacik #endif
9432c323017SJosef Bacik 
944d46eb14bSShakeel Butt #ifdef CONFIG_MEMCG
945d46eb14bSShakeel Butt 	tsk->active_memcg = NULL;
946d46eb14bSShakeel Butt #endif
9471da177e4SLinus Torvalds 	return tsk;
9481da177e4SLinus Torvalds 
9491da177e4SLinus Torvalds free_stack:
9501da177e4SLinus Torvalds 	free_thread_stack(tsk);
9511da177e4SLinus Torvalds free_tsk:
9521da177e4SLinus Torvalds 	free_task_struct(tsk);
9531da177e4SLinus Torvalds 	return NULL;
9541da177e4SLinus Torvalds }
9551da177e4SLinus Torvalds 
9561da177e4SLinus Torvalds __cacheline_aligned_in_smp DEFINE_SPINLOCK(mmlist_lock);
9571da177e4SLinus Torvalds 
9584cb0e11bSHidehiro Kawai static unsigned long default_dump_filter = MMF_DUMP_FILTER_DEFAULT;
9594cb0e11bSHidehiro Kawai 
9604cb0e11bSHidehiro Kawai static int __init coredump_filter_setup(char *s)
9614cb0e11bSHidehiro Kawai {
9624cb0e11bSHidehiro Kawai 	default_dump_filter =
9634cb0e11bSHidehiro Kawai 		(simple_strtoul(s, NULL, 0) << MMF_DUMP_FILTER_SHIFT) &
9644cb0e11bSHidehiro Kawai 		MMF_DUMP_FILTER_MASK;
9654cb0e11bSHidehiro Kawai 	return 1;
9664cb0e11bSHidehiro Kawai }
9674cb0e11bSHidehiro Kawai 
9684cb0e11bSHidehiro Kawai __setup("coredump_filter=", coredump_filter_setup);
9694cb0e11bSHidehiro Kawai 
9701da177e4SLinus Torvalds #include <linux/init_task.h>
9711da177e4SLinus Torvalds 
972858f0993SAlexey Dobriyan static void mm_init_aio(struct mm_struct *mm)
973858f0993SAlexey Dobriyan {
974858f0993SAlexey Dobriyan #ifdef CONFIG_AIO
975858f0993SAlexey Dobriyan 	spin_lock_init(&mm->ioctx_lock);
976db446a08SBenjamin LaHaise 	mm->ioctx_table = NULL;
977858f0993SAlexey Dobriyan #endif
978858f0993SAlexey Dobriyan }
979858f0993SAlexey Dobriyan 
980c3f3ce04SAndrea Arcangeli static __always_inline void mm_clear_owner(struct mm_struct *mm,
981c3f3ce04SAndrea Arcangeli 					   struct task_struct *p)
982c3f3ce04SAndrea Arcangeli {
983c3f3ce04SAndrea Arcangeli #ifdef CONFIG_MEMCG
984c3f3ce04SAndrea Arcangeli 	if (mm->owner == p)
985c3f3ce04SAndrea Arcangeli 		WRITE_ONCE(mm->owner, NULL);
986c3f3ce04SAndrea Arcangeli #endif
987c3f3ce04SAndrea Arcangeli }
988c3f3ce04SAndrea Arcangeli 
98933144e84SVladimir Davydov static void mm_init_owner(struct mm_struct *mm, struct task_struct *p)
99033144e84SVladimir Davydov {
99133144e84SVladimir Davydov #ifdef CONFIG_MEMCG
99233144e84SVladimir Davydov 	mm->owner = p;
99333144e84SVladimir Davydov #endif
99433144e84SVladimir Davydov }
99533144e84SVladimir Davydov 
996355627f5SEric Biggers static void mm_init_uprobes_state(struct mm_struct *mm)
997355627f5SEric Biggers {
998355627f5SEric Biggers #ifdef CONFIG_UPROBES
999355627f5SEric Biggers 	mm->uprobes_state.xol_area = NULL;
1000355627f5SEric Biggers #endif
1001355627f5SEric Biggers }
1002355627f5SEric Biggers 
1003bfedb589SEric W. Biederman static struct mm_struct *mm_init(struct mm_struct *mm, struct task_struct *p,
1004bfedb589SEric W. Biederman 	struct user_namespace *user_ns)
10051da177e4SLinus Torvalds {
100641f727fdSVladimir Davydov 	mm->mmap = NULL;
100741f727fdSVladimir Davydov 	mm->mm_rb = RB_ROOT;
100841f727fdSVladimir Davydov 	mm->vmacache_seqnum = 0;
10091da177e4SLinus Torvalds 	atomic_set(&mm->mm_users, 1);
10101da177e4SLinus Torvalds 	atomic_set(&mm->mm_count, 1);
10111da177e4SLinus Torvalds 	init_rwsem(&mm->mmap_sem);
10121da177e4SLinus Torvalds 	INIT_LIST_HEAD(&mm->mmlist);
1013999d9fc1SOleg Nesterov 	mm->core_state = NULL;
1014af5b0f6aSKirill A. Shutemov 	mm_pgtables_bytes_init(mm);
101541f727fdSVladimir Davydov 	mm->map_count = 0;
101641f727fdSVladimir Davydov 	mm->locked_vm = 0;
101770f8a3caSDavidlohr Bueso 	atomic64_set(&mm->pinned_vm, 0);
1018d559db08SKAMEZAWA Hiroyuki 	memset(&mm->rss_stat, 0, sizeof(mm->rss_stat));
10191da177e4SLinus Torvalds 	spin_lock_init(&mm->page_table_lock);
102088aa7cc6SYang Shi 	spin_lock_init(&mm->arg_lock);
102141f727fdSVladimir Davydov 	mm_init_cpumask(mm);
1022858f0993SAlexey Dobriyan 	mm_init_aio(mm);
1023cf475ad2SBalbir Singh 	mm_init_owner(mm, p);
10242b7e8665SEric Biggers 	RCU_INIT_POINTER(mm->exe_file, NULL);
102541f727fdSVladimir Davydov 	mmu_notifier_mm_init(mm);
102616af97dcSNadav Amit 	init_tlb_flush_pending(mm);
102741f727fdSVladimir Davydov #if defined(CONFIG_TRANSPARENT_HUGEPAGE) && !USE_SPLIT_PMD_PTLOCKS
102841f727fdSVladimir Davydov 	mm->pmd_huge_pte = NULL;
102941f727fdSVladimir Davydov #endif
1030355627f5SEric Biggers 	mm_init_uprobes_state(mm);
10311da177e4SLinus Torvalds 
1032a0715cc2SAlex Thorlton 	if (current->mm) {
1033a0715cc2SAlex Thorlton 		mm->flags = current->mm->flags & MMF_INIT_MASK;
1034a0715cc2SAlex Thorlton 		mm->def_flags = current->mm->def_flags & VM_INIT_DEF_MASK;
1035a0715cc2SAlex Thorlton 	} else {
1036a0715cc2SAlex Thorlton 		mm->flags = default_dump_filter;
10371da177e4SLinus Torvalds 		mm->def_flags = 0;
1038a0715cc2SAlex Thorlton 	}
1039a0715cc2SAlex Thorlton 
104041f727fdSVladimir Davydov 	if (mm_alloc_pgd(mm))
104141f727fdSVladimir Davydov 		goto fail_nopgd;
104278fb7466SPavel Emelianov 
104341f727fdSVladimir Davydov 	if (init_new_context(p, mm))
104441f727fdSVladimir Davydov 		goto fail_nocontext;
104541f727fdSVladimir Davydov 
1046bfedb589SEric W. Biederman 	mm->user_ns = get_user_ns(user_ns);
104741f727fdSVladimir Davydov 	return mm;
104841f727fdSVladimir Davydov 
104941f727fdSVladimir Davydov fail_nocontext:
105041f727fdSVladimir Davydov 	mm_free_pgd(mm);
105141f727fdSVladimir Davydov fail_nopgd:
10521da177e4SLinus Torvalds 	free_mm(mm);
10531da177e4SLinus Torvalds 	return NULL;
10541da177e4SLinus Torvalds }
10551da177e4SLinus Torvalds 
10561da177e4SLinus Torvalds /*
10571da177e4SLinus Torvalds  * Allocate and initialize an mm_struct.
10581da177e4SLinus Torvalds  */
10591da177e4SLinus Torvalds struct mm_struct *mm_alloc(void)
10601da177e4SLinus Torvalds {
10611da177e4SLinus Torvalds 	struct mm_struct *mm;
10621da177e4SLinus Torvalds 
10631da177e4SLinus Torvalds 	mm = allocate_mm();
1064de03c72cSKOSAKI Motohiro 	if (!mm)
1065de03c72cSKOSAKI Motohiro 		return NULL;
1066de03c72cSKOSAKI Motohiro 
10671da177e4SLinus Torvalds 	memset(mm, 0, sizeof(*mm));
1068bfedb589SEric W. Biederman 	return mm_init(mm, current, current_user_ns());
10691da177e4SLinus Torvalds }
10701da177e4SLinus Torvalds 
1071ec8d7c14SMichal Hocko static inline void __mmput(struct mm_struct *mm)
10721da177e4SLinus Torvalds {
1073ec8d7c14SMichal Hocko 	VM_BUG_ON(atomic_read(&mm->mm_users));
10740ae26f1bSAndrew Morton 
1075d4b3b638SSrikar Dronamraju 	uprobe_clear_state(mm);
10761da177e4SLinus Torvalds 	exit_aio(mm);
10771c2fb7a4SAndrea Arcangeli 	ksm_exit(mm);
1078ba76149fSAndrea Arcangeli 	khugepaged_exit(mm); /* must run before exit_mmap */
10791da177e4SLinus Torvalds 	exit_mmap(mm);
10806fcb52a5SAaron Lu 	mm_put_huge_zero_page(mm);
1081925d1c40SMatt Helsley 	set_mm_exe_file(mm, NULL);
10821da177e4SLinus Torvalds 	if (!list_empty(&mm->mmlist)) {
10831da177e4SLinus Torvalds 		spin_lock(&mmlist_lock);
10841da177e4SLinus Torvalds 		list_del(&mm->mmlist);
10851da177e4SLinus Torvalds 		spin_unlock(&mmlist_lock);
10861da177e4SLinus Torvalds 	}
1087801460d0SHiroshi Shimamoto 	if (mm->binfmt)
1088801460d0SHiroshi Shimamoto 		module_put(mm->binfmt->module);
10891da177e4SLinus Torvalds 	mmdrop(mm);
10901da177e4SLinus Torvalds }
1091ec8d7c14SMichal Hocko 
1092ec8d7c14SMichal Hocko /*
1093ec8d7c14SMichal Hocko  * Decrement the use count and release all resources for an mm.
1094ec8d7c14SMichal Hocko  */
1095ec8d7c14SMichal Hocko void mmput(struct mm_struct *mm)
1096ec8d7c14SMichal Hocko {
1097ec8d7c14SMichal Hocko 	might_sleep();
1098ec8d7c14SMichal Hocko 
1099ec8d7c14SMichal Hocko 	if (atomic_dec_and_test(&mm->mm_users))
1100ec8d7c14SMichal Hocko 		__mmput(mm);
11011da177e4SLinus Torvalds }
11021da177e4SLinus Torvalds EXPORT_SYMBOL_GPL(mmput);
11031da177e4SLinus Torvalds 
1104a1b2289cSSherry Yang #ifdef CONFIG_MMU
1105a1b2289cSSherry Yang static void mmput_async_fn(struct work_struct *work)
1106a1b2289cSSherry Yang {
1107a1b2289cSSherry Yang 	struct mm_struct *mm = container_of(work, struct mm_struct,
1108a1b2289cSSherry Yang 					    async_put_work);
1109a1b2289cSSherry Yang 
1110a1b2289cSSherry Yang 	__mmput(mm);
1111a1b2289cSSherry Yang }
1112a1b2289cSSherry Yang 
1113a1b2289cSSherry Yang void mmput_async(struct mm_struct *mm)
1114a1b2289cSSherry Yang {
1115a1b2289cSSherry Yang 	if (atomic_dec_and_test(&mm->mm_users)) {
1116a1b2289cSSherry Yang 		INIT_WORK(&mm->async_put_work, mmput_async_fn);
1117a1b2289cSSherry Yang 		schedule_work(&mm->async_put_work);
1118a1b2289cSSherry Yang 	}
1119a1b2289cSSherry Yang }
1120a1b2289cSSherry Yang #endif
1121a1b2289cSSherry Yang 
112290f31d0eSKonstantin Khlebnikov /**
112390f31d0eSKonstantin Khlebnikov  * set_mm_exe_file - change a reference to the mm's executable file
112490f31d0eSKonstantin Khlebnikov  *
112590f31d0eSKonstantin Khlebnikov  * This changes mm's executable file (shown as symlink /proc/[pid]/exe).
112690f31d0eSKonstantin Khlebnikov  *
11276e399cd1SDavidlohr Bueso  * Main users are mmput() and sys_execve(). Callers prevent concurrent
11286e399cd1SDavidlohr Bueso  * invocations: in mmput() nobody alive left, in execve task is single
11296e399cd1SDavidlohr Bueso  * threaded. sys_prctl(PR_SET_MM_MAP/EXE_FILE) also needs to set the
11306e399cd1SDavidlohr Bueso  * mm->exe_file, but does so without using set_mm_exe_file() in order
11316e399cd1SDavidlohr Bueso  * to do avoid the need for any locks.
113290f31d0eSKonstantin Khlebnikov  */
113338646013SJiri Slaby void set_mm_exe_file(struct mm_struct *mm, struct file *new_exe_file)
113438646013SJiri Slaby {
11356e399cd1SDavidlohr Bueso 	struct file *old_exe_file;
11366e399cd1SDavidlohr Bueso 
11376e399cd1SDavidlohr Bueso 	/*
11386e399cd1SDavidlohr Bueso 	 * It is safe to dereference the exe_file without RCU as
11396e399cd1SDavidlohr Bueso 	 * this function is only called if nobody else can access
11406e399cd1SDavidlohr Bueso 	 * this mm -- see comment above for justification.
11416e399cd1SDavidlohr Bueso 	 */
11426e399cd1SDavidlohr Bueso 	old_exe_file = rcu_dereference_raw(mm->exe_file);
114390f31d0eSKonstantin Khlebnikov 
114438646013SJiri Slaby 	if (new_exe_file)
114538646013SJiri Slaby 		get_file(new_exe_file);
114690f31d0eSKonstantin Khlebnikov 	rcu_assign_pointer(mm->exe_file, new_exe_file);
114790f31d0eSKonstantin Khlebnikov 	if (old_exe_file)
114890f31d0eSKonstantin Khlebnikov 		fput(old_exe_file);
114938646013SJiri Slaby }
115038646013SJiri Slaby 
115190f31d0eSKonstantin Khlebnikov /**
115290f31d0eSKonstantin Khlebnikov  * get_mm_exe_file - acquire a reference to the mm's executable file
115390f31d0eSKonstantin Khlebnikov  *
115490f31d0eSKonstantin Khlebnikov  * Returns %NULL if mm has no associated executable file.
115590f31d0eSKonstantin Khlebnikov  * User must release file via fput().
115690f31d0eSKonstantin Khlebnikov  */
115738646013SJiri Slaby struct file *get_mm_exe_file(struct mm_struct *mm)
115838646013SJiri Slaby {
115938646013SJiri Slaby 	struct file *exe_file;
116038646013SJiri Slaby 
116190f31d0eSKonstantin Khlebnikov 	rcu_read_lock();
116290f31d0eSKonstantin Khlebnikov 	exe_file = rcu_dereference(mm->exe_file);
116390f31d0eSKonstantin Khlebnikov 	if (exe_file && !get_file_rcu(exe_file))
116490f31d0eSKonstantin Khlebnikov 		exe_file = NULL;
116590f31d0eSKonstantin Khlebnikov 	rcu_read_unlock();
116638646013SJiri Slaby 	return exe_file;
116738646013SJiri Slaby }
116811163348SDavidlohr Bueso EXPORT_SYMBOL(get_mm_exe_file);
116938646013SJiri Slaby 
11701da177e4SLinus Torvalds /**
1171cd81a917SMateusz Guzik  * get_task_exe_file - acquire a reference to the task's executable file
1172cd81a917SMateusz Guzik  *
1173cd81a917SMateusz Guzik  * Returns %NULL if task's mm (if any) has no associated executable file or
1174cd81a917SMateusz Guzik  * this is a kernel thread with borrowed mm (see the comment above get_task_mm).
1175cd81a917SMateusz Guzik  * User must release file via fput().
1176cd81a917SMateusz Guzik  */
1177cd81a917SMateusz Guzik struct file *get_task_exe_file(struct task_struct *task)
1178cd81a917SMateusz Guzik {
1179cd81a917SMateusz Guzik 	struct file *exe_file = NULL;
1180cd81a917SMateusz Guzik 	struct mm_struct *mm;
1181cd81a917SMateusz Guzik 
1182cd81a917SMateusz Guzik 	task_lock(task);
1183cd81a917SMateusz Guzik 	mm = task->mm;
1184cd81a917SMateusz Guzik 	if (mm) {
1185cd81a917SMateusz Guzik 		if (!(task->flags & PF_KTHREAD))
1186cd81a917SMateusz Guzik 			exe_file = get_mm_exe_file(mm);
1187cd81a917SMateusz Guzik 	}
1188cd81a917SMateusz Guzik 	task_unlock(task);
1189cd81a917SMateusz Guzik 	return exe_file;
1190cd81a917SMateusz Guzik }
1191cd81a917SMateusz Guzik EXPORT_SYMBOL(get_task_exe_file);
1192cd81a917SMateusz Guzik 
1193cd81a917SMateusz Guzik /**
11941da177e4SLinus Torvalds  * get_task_mm - acquire a reference to the task's mm
11951da177e4SLinus Torvalds  *
1196246bb0b1SOleg Nesterov  * Returns %NULL if the task has no mm.  Checks PF_KTHREAD (meaning
11971da177e4SLinus Torvalds  * this kernel workthread has transiently adopted a user mm with use_mm,
11981da177e4SLinus Torvalds  * to do its AIO) is not set and if so returns a reference to it, after
11991da177e4SLinus Torvalds  * bumping up the use count.  User must release the mm via mmput()
12001da177e4SLinus Torvalds  * after use.  Typically used by /proc and ptrace.
12011da177e4SLinus Torvalds  */
12021da177e4SLinus Torvalds struct mm_struct *get_task_mm(struct task_struct *task)
12031da177e4SLinus Torvalds {
12041da177e4SLinus Torvalds 	struct mm_struct *mm;
12051da177e4SLinus Torvalds 
12061da177e4SLinus Torvalds 	task_lock(task);
12071da177e4SLinus Torvalds 	mm = task->mm;
12081da177e4SLinus Torvalds 	if (mm) {
1209246bb0b1SOleg Nesterov 		if (task->flags & PF_KTHREAD)
12101da177e4SLinus Torvalds 			mm = NULL;
12111da177e4SLinus Torvalds 		else
12123fce371bSVegard Nossum 			mmget(mm);
12131da177e4SLinus Torvalds 	}
12141da177e4SLinus Torvalds 	task_unlock(task);
12151da177e4SLinus Torvalds 	return mm;
12161da177e4SLinus Torvalds }
12171da177e4SLinus Torvalds EXPORT_SYMBOL_GPL(get_task_mm);
12181da177e4SLinus Torvalds 
12198cdb878dSChristopher Yeoh struct mm_struct *mm_access(struct task_struct *task, unsigned int mode)
12208cdb878dSChristopher Yeoh {
12218cdb878dSChristopher Yeoh 	struct mm_struct *mm;
12228cdb878dSChristopher Yeoh 	int err;
12238cdb878dSChristopher Yeoh 
12248cdb878dSChristopher Yeoh 	err =  mutex_lock_killable(&task->signal->cred_guard_mutex);
12258cdb878dSChristopher Yeoh 	if (err)
12268cdb878dSChristopher Yeoh 		return ERR_PTR(err);
12278cdb878dSChristopher Yeoh 
12288cdb878dSChristopher Yeoh 	mm = get_task_mm(task);
12298cdb878dSChristopher Yeoh 	if (mm && mm != current->mm &&
12308cdb878dSChristopher Yeoh 			!ptrace_may_access(task, mode)) {
12318cdb878dSChristopher Yeoh 		mmput(mm);
12328cdb878dSChristopher Yeoh 		mm = ERR_PTR(-EACCES);
12338cdb878dSChristopher Yeoh 	}
12348cdb878dSChristopher Yeoh 	mutex_unlock(&task->signal->cred_guard_mutex);
12358cdb878dSChristopher Yeoh 
12368cdb878dSChristopher Yeoh 	return mm;
12378cdb878dSChristopher Yeoh }
12388cdb878dSChristopher Yeoh 
123957b59c4aSOleg Nesterov static void complete_vfork_done(struct task_struct *tsk)
1240c415c3b4SOleg Nesterov {
1241d68b46feSOleg Nesterov 	struct completion *vfork;
1242c415c3b4SOleg Nesterov 
1243d68b46feSOleg Nesterov 	task_lock(tsk);
1244d68b46feSOleg Nesterov 	vfork = tsk->vfork_done;
1245d68b46feSOleg Nesterov 	if (likely(vfork)) {
1246c415c3b4SOleg Nesterov 		tsk->vfork_done = NULL;
1247d68b46feSOleg Nesterov 		complete(vfork);
1248d68b46feSOleg Nesterov 	}
1249d68b46feSOleg Nesterov 	task_unlock(tsk);
1250d68b46feSOleg Nesterov }
1251d68b46feSOleg Nesterov 
1252d68b46feSOleg Nesterov static int wait_for_vfork_done(struct task_struct *child,
1253d68b46feSOleg Nesterov 				struct completion *vfork)
1254d68b46feSOleg Nesterov {
1255d68b46feSOleg Nesterov 	int killed;
1256d68b46feSOleg Nesterov 
1257d68b46feSOleg Nesterov 	freezer_do_not_count();
125876f969e8SRoman Gushchin 	cgroup_enter_frozen();
1259d68b46feSOleg Nesterov 	killed = wait_for_completion_killable(vfork);
126076f969e8SRoman Gushchin 	cgroup_leave_frozen(false);
1261d68b46feSOleg Nesterov 	freezer_count();
1262d68b46feSOleg Nesterov 
1263d68b46feSOleg Nesterov 	if (killed) {
1264d68b46feSOleg Nesterov 		task_lock(child);
1265d68b46feSOleg Nesterov 		child->vfork_done = NULL;
1266d68b46feSOleg Nesterov 		task_unlock(child);
1267d68b46feSOleg Nesterov 	}
1268d68b46feSOleg Nesterov 
1269d68b46feSOleg Nesterov 	put_task_struct(child);
1270d68b46feSOleg Nesterov 	return killed;
1271c415c3b4SOleg Nesterov }
1272c415c3b4SOleg Nesterov 
12731da177e4SLinus Torvalds /* Please note the differences between mmput and mm_release.
12741da177e4SLinus Torvalds  * mmput is called whenever we stop holding onto a mm_struct,
12751da177e4SLinus Torvalds  * error success whatever.
12761da177e4SLinus Torvalds  *
12771da177e4SLinus Torvalds  * mm_release is called after a mm_struct has been removed
12781da177e4SLinus Torvalds  * from the current process.
12791da177e4SLinus Torvalds  *
12801da177e4SLinus Torvalds  * This difference is important for error handling, when we
12811da177e4SLinus Torvalds  * only half set up a mm_struct for a new process and need to restore
12821da177e4SLinus Torvalds  * the old one.  Because we mmput the new mm_struct before
12831da177e4SLinus Torvalds  * restoring the old one. . .
12841da177e4SLinus Torvalds  * Eric Biederman 10 January 1998
12851da177e4SLinus Torvalds  */
12861da177e4SLinus Torvalds void mm_release(struct task_struct *tsk, struct mm_struct *mm)
12871da177e4SLinus Torvalds {
12888141c7f3SLinus Torvalds 	/* Get rid of any futexes when releasing the mm */
12898141c7f3SLinus Torvalds #ifdef CONFIG_FUTEX
1290fc6b177dSPeter Zijlstra 	if (unlikely(tsk->robust_list)) {
12918141c7f3SLinus Torvalds 		exit_robust_list(tsk);
1292fc6b177dSPeter Zijlstra 		tsk->robust_list = NULL;
1293fc6b177dSPeter Zijlstra 	}
12948141c7f3SLinus Torvalds #ifdef CONFIG_COMPAT
1295fc6b177dSPeter Zijlstra 	if (unlikely(tsk->compat_robust_list)) {
12968141c7f3SLinus Torvalds 		compat_exit_robust_list(tsk);
1297fc6b177dSPeter Zijlstra 		tsk->compat_robust_list = NULL;
1298fc6b177dSPeter Zijlstra 	}
12998141c7f3SLinus Torvalds #endif
1300322a2c10SThomas Gleixner 	if (unlikely(!list_empty(&tsk->pi_state_list)))
1301322a2c10SThomas Gleixner 		exit_pi_state_list(tsk);
13028141c7f3SLinus Torvalds #endif
13038141c7f3SLinus Torvalds 
13040326f5a9SSrikar Dronamraju 	uprobe_free_utask(tsk);
13050326f5a9SSrikar Dronamraju 
13061da177e4SLinus Torvalds 	/* Get rid of any cached register state */
13071da177e4SLinus Torvalds 	deactivate_mm(tsk, mm);
13081da177e4SLinus Torvalds 
1309fec1d011SRoland McGrath 	/*
1310735f2770SMichal Hocko 	 * Signal userspace if we're not exiting with a core dump
1311735f2770SMichal Hocko 	 * because we want to leave the value intact for debugging
1312735f2770SMichal Hocko 	 * purposes.
1313fec1d011SRoland McGrath 	 */
13149c8a8228SEric Dumazet 	if (tsk->clear_child_tid) {
1315735f2770SMichal Hocko 		if (!(tsk->signal->flags & SIGNAL_GROUP_COREDUMP) &&
13169c8a8228SEric Dumazet 		    atomic_read(&mm->mm_users) > 1) {
13171da177e4SLinus Torvalds 			/*
13181da177e4SLinus Torvalds 			 * We don't check the error code - if userspace has
13191da177e4SLinus Torvalds 			 * not set up a proper pointer then tough luck.
13201da177e4SLinus Torvalds 			 */
13219c8a8228SEric Dumazet 			put_user(0, tsk->clear_child_tid);
13222de0db99SDominik Brodowski 			do_futex(tsk->clear_child_tid, FUTEX_WAKE,
13232de0db99SDominik Brodowski 					1, NULL, NULL, 0, 0);
13249c8a8228SEric Dumazet 		}
13259c8a8228SEric Dumazet 		tsk->clear_child_tid = NULL;
13261da177e4SLinus Torvalds 	}
1327f7505d64SKonstantin Khlebnikov 
1328f7505d64SKonstantin Khlebnikov 	/*
1329f7505d64SKonstantin Khlebnikov 	 * All done, finally we can wake up parent and return this mm to him.
1330f7505d64SKonstantin Khlebnikov 	 * Also kthread_stop() uses this completion for synchronization.
1331f7505d64SKonstantin Khlebnikov 	 */
1332f7505d64SKonstantin Khlebnikov 	if (tsk->vfork_done)
1333f7505d64SKonstantin Khlebnikov 		complete_vfork_done(tsk);
13341da177e4SLinus Torvalds }
13351da177e4SLinus Torvalds 
133613585fa0SNadav Amit /**
133713585fa0SNadav Amit  * dup_mm() - duplicates an existing mm structure
133813585fa0SNadav Amit  * @tsk: the task_struct with which the new mm will be associated.
133913585fa0SNadav Amit  * @oldmm: the mm to duplicate.
134013585fa0SNadav Amit  *
134113585fa0SNadav Amit  * Allocates a new mm structure and duplicates the provided @oldmm structure
134213585fa0SNadav Amit  * content into it.
134313585fa0SNadav Amit  *
134413585fa0SNadav Amit  * Return: the duplicated mm or NULL on failure.
1345a0a7ec30SJANAK DESAI  */
134613585fa0SNadav Amit static struct mm_struct *dup_mm(struct task_struct *tsk,
134713585fa0SNadav Amit 				struct mm_struct *oldmm)
1348a0a7ec30SJANAK DESAI {
134913585fa0SNadav Amit 	struct mm_struct *mm;
1350a0a7ec30SJANAK DESAI 	int err;
1351a0a7ec30SJANAK DESAI 
1352a0a7ec30SJANAK DESAI 	mm = allocate_mm();
1353a0a7ec30SJANAK DESAI 	if (!mm)
1354a0a7ec30SJANAK DESAI 		goto fail_nomem;
1355a0a7ec30SJANAK DESAI 
1356a0a7ec30SJANAK DESAI 	memcpy(mm, oldmm, sizeof(*mm));
1357a0a7ec30SJANAK DESAI 
1358bfedb589SEric W. Biederman 	if (!mm_init(mm, tsk, mm->user_ns))
1359a0a7ec30SJANAK DESAI 		goto fail_nomem;
1360a0a7ec30SJANAK DESAI 
1361a0a7ec30SJANAK DESAI 	err = dup_mmap(mm, oldmm);
1362a0a7ec30SJANAK DESAI 	if (err)
1363a0a7ec30SJANAK DESAI 		goto free_pt;
1364a0a7ec30SJANAK DESAI 
1365a0a7ec30SJANAK DESAI 	mm->hiwater_rss = get_mm_rss(mm);
1366a0a7ec30SJANAK DESAI 	mm->hiwater_vm = mm->total_vm;
1367a0a7ec30SJANAK DESAI 
1368801460d0SHiroshi Shimamoto 	if (mm->binfmt && !try_module_get(mm->binfmt->module))
1369801460d0SHiroshi Shimamoto 		goto free_pt;
1370801460d0SHiroshi Shimamoto 
1371a0a7ec30SJANAK DESAI 	return mm;
1372a0a7ec30SJANAK DESAI 
1373a0a7ec30SJANAK DESAI free_pt:
1374801460d0SHiroshi Shimamoto 	/* don't put binfmt in mmput, we haven't got module yet */
1375801460d0SHiroshi Shimamoto 	mm->binfmt = NULL;
1376c3f3ce04SAndrea Arcangeli 	mm_init_owner(mm, NULL);
1377a0a7ec30SJANAK DESAI 	mmput(mm);
1378a0a7ec30SJANAK DESAI 
1379a0a7ec30SJANAK DESAI fail_nomem:
1380a0a7ec30SJANAK DESAI 	return NULL;
1381a0a7ec30SJANAK DESAI }
1382a0a7ec30SJANAK DESAI 
13831da177e4SLinus Torvalds static int copy_mm(unsigned long clone_flags, struct task_struct *tsk)
13841da177e4SLinus Torvalds {
13851da177e4SLinus Torvalds 	struct mm_struct *mm, *oldmm;
13861da177e4SLinus Torvalds 	int retval;
13871da177e4SLinus Torvalds 
13881da177e4SLinus Torvalds 	tsk->min_flt = tsk->maj_flt = 0;
13891da177e4SLinus Torvalds 	tsk->nvcsw = tsk->nivcsw = 0;
139017406b82SMandeep Singh Baines #ifdef CONFIG_DETECT_HUNG_TASK
139117406b82SMandeep Singh Baines 	tsk->last_switch_count = tsk->nvcsw + tsk->nivcsw;
1392a2e51445SDmitry Vyukov 	tsk->last_switch_time = 0;
139317406b82SMandeep Singh Baines #endif
13941da177e4SLinus Torvalds 
13951da177e4SLinus Torvalds 	tsk->mm = NULL;
13961da177e4SLinus Torvalds 	tsk->active_mm = NULL;
13971da177e4SLinus Torvalds 
13981da177e4SLinus Torvalds 	/*
13991da177e4SLinus Torvalds 	 * Are we cloning a kernel thread?
14001da177e4SLinus Torvalds 	 *
14011da177e4SLinus Torvalds 	 * We need to steal a active VM for that..
14021da177e4SLinus Torvalds 	 */
14031da177e4SLinus Torvalds 	oldmm = current->mm;
14041da177e4SLinus Torvalds 	if (!oldmm)
14051da177e4SLinus Torvalds 		return 0;
14061da177e4SLinus Torvalds 
1407615d6e87SDavidlohr Bueso 	/* initialize the new vmacache entries */
1408615d6e87SDavidlohr Bueso 	vmacache_flush(tsk);
1409615d6e87SDavidlohr Bueso 
14101da177e4SLinus Torvalds 	if (clone_flags & CLONE_VM) {
14113fce371bSVegard Nossum 		mmget(oldmm);
14121da177e4SLinus Torvalds 		mm = oldmm;
14131da177e4SLinus Torvalds 		goto good_mm;
14141da177e4SLinus Torvalds 	}
14151da177e4SLinus Torvalds 
14161da177e4SLinus Torvalds 	retval = -ENOMEM;
141713585fa0SNadav Amit 	mm = dup_mm(tsk, current->mm);
14181da177e4SLinus Torvalds 	if (!mm)
14191da177e4SLinus Torvalds 		goto fail_nomem;
14201da177e4SLinus Torvalds 
14211da177e4SLinus Torvalds good_mm:
14221da177e4SLinus Torvalds 	tsk->mm = mm;
14231da177e4SLinus Torvalds 	tsk->active_mm = mm;
14241da177e4SLinus Torvalds 	return 0;
14251da177e4SLinus Torvalds 
14261da177e4SLinus Torvalds fail_nomem:
14271da177e4SLinus Torvalds 	return retval;
14281da177e4SLinus Torvalds }
14291da177e4SLinus Torvalds 
1430a39bc516SAlexey Dobriyan static int copy_fs(unsigned long clone_flags, struct task_struct *tsk)
14311da177e4SLinus Torvalds {
1432498052bbSAl Viro 	struct fs_struct *fs = current->fs;
14331da177e4SLinus Torvalds 	if (clone_flags & CLONE_FS) {
1434498052bbSAl Viro 		/* tsk->fs is already what we want */
14352a4419b5SNick Piggin 		spin_lock(&fs->lock);
1436498052bbSAl Viro 		if (fs->in_exec) {
14372a4419b5SNick Piggin 			spin_unlock(&fs->lock);
1438498052bbSAl Viro 			return -EAGAIN;
1439498052bbSAl Viro 		}
1440498052bbSAl Viro 		fs->users++;
14412a4419b5SNick Piggin 		spin_unlock(&fs->lock);
14421da177e4SLinus Torvalds 		return 0;
14431da177e4SLinus Torvalds 	}
1444498052bbSAl Viro 	tsk->fs = copy_fs_struct(fs);
14451da177e4SLinus Torvalds 	if (!tsk->fs)
14461da177e4SLinus Torvalds 		return -ENOMEM;
14471da177e4SLinus Torvalds 	return 0;
14481da177e4SLinus Torvalds }
14491da177e4SLinus Torvalds 
1450a016f338SJANAK DESAI static int copy_files(unsigned long clone_flags, struct task_struct *tsk)
1451a016f338SJANAK DESAI {
1452a016f338SJANAK DESAI 	struct files_struct *oldf, *newf;
1453a016f338SJANAK DESAI 	int error = 0;
1454a016f338SJANAK DESAI 
1455a016f338SJANAK DESAI 	/*
1456a016f338SJANAK DESAI 	 * A background process may not have any files ...
1457a016f338SJANAK DESAI 	 */
1458a016f338SJANAK DESAI 	oldf = current->files;
1459a016f338SJANAK DESAI 	if (!oldf)
1460a016f338SJANAK DESAI 		goto out;
1461a016f338SJANAK DESAI 
1462a016f338SJANAK DESAI 	if (clone_flags & CLONE_FILES) {
1463a016f338SJANAK DESAI 		atomic_inc(&oldf->count);
1464a016f338SJANAK DESAI 		goto out;
1465a016f338SJANAK DESAI 	}
1466a016f338SJANAK DESAI 
1467a016f338SJANAK DESAI 	newf = dup_fd(oldf, &error);
1468a016f338SJANAK DESAI 	if (!newf)
1469a016f338SJANAK DESAI 		goto out;
1470a016f338SJANAK DESAI 
1471a016f338SJANAK DESAI 	tsk->files = newf;
1472a016f338SJANAK DESAI 	error = 0;
1473a016f338SJANAK DESAI out:
1474a016f338SJANAK DESAI 	return error;
1475a016f338SJANAK DESAI }
1476a016f338SJANAK DESAI 
1477fadad878SJens Axboe static int copy_io(unsigned long clone_flags, struct task_struct *tsk)
1478fd0928dfSJens Axboe {
1479fd0928dfSJens Axboe #ifdef CONFIG_BLOCK
1480fd0928dfSJens Axboe 	struct io_context *ioc = current->io_context;
14816e736be7STejun Heo 	struct io_context *new_ioc;
1482fd0928dfSJens Axboe 
1483fd0928dfSJens Axboe 	if (!ioc)
1484fd0928dfSJens Axboe 		return 0;
1485fadad878SJens Axboe 	/*
1486fadad878SJens Axboe 	 * Share io context with parent, if CLONE_IO is set
1487fadad878SJens Axboe 	 */
1488fadad878SJens Axboe 	if (clone_flags & CLONE_IO) {
14893d48749dSTejun Heo 		ioc_task_link(ioc);
14903d48749dSTejun Heo 		tsk->io_context = ioc;
1491fadad878SJens Axboe 	} else if (ioprio_valid(ioc->ioprio)) {
14926e736be7STejun Heo 		new_ioc = get_task_io_context(tsk, GFP_KERNEL, NUMA_NO_NODE);
14936e736be7STejun Heo 		if (unlikely(!new_ioc))
1494fd0928dfSJens Axboe 			return -ENOMEM;
1495fd0928dfSJens Axboe 
14966e736be7STejun Heo 		new_ioc->ioprio = ioc->ioprio;
149711a3122fSTejun Heo 		put_io_context(new_ioc);
1498fd0928dfSJens Axboe 	}
1499fd0928dfSJens Axboe #endif
1500fd0928dfSJens Axboe 	return 0;
1501fd0928dfSJens Axboe }
1502fd0928dfSJens Axboe 
1503a39bc516SAlexey Dobriyan static int copy_sighand(unsigned long clone_flags, struct task_struct *tsk)
15041da177e4SLinus Torvalds {
15051da177e4SLinus Torvalds 	struct sighand_struct *sig;
15061da177e4SLinus Torvalds 
150760348802SZhaolei 	if (clone_flags & CLONE_SIGHAND) {
1508d036bda7SElena Reshetova 		refcount_inc(&current->sighand->count);
15091da177e4SLinus Torvalds 		return 0;
15101da177e4SLinus Torvalds 	}
15111da177e4SLinus Torvalds 	sig = kmem_cache_alloc(sighand_cachep, GFP_KERNEL);
1512e56d0903SIngo Molnar 	rcu_assign_pointer(tsk->sighand, sig);
15131da177e4SLinus Torvalds 	if (!sig)
15141da177e4SLinus Torvalds 		return -ENOMEM;
15159d7fb042SPeter Zijlstra 
1516d036bda7SElena Reshetova 	refcount_set(&sig->count, 1);
151706e62a46SJann Horn 	spin_lock_irq(&current->sighand->siglock);
15181da177e4SLinus Torvalds 	memcpy(sig->action, current->sighand->action, sizeof(sig->action));
151906e62a46SJann Horn 	spin_unlock_irq(&current->sighand->siglock);
1520*b612e5dfSChristian Brauner 
1521*b612e5dfSChristian Brauner 	/* Reset all signal handler not set to SIG_IGN to SIG_DFL. */
1522*b612e5dfSChristian Brauner 	if (clone_flags & CLONE_CLEAR_SIGHAND)
1523*b612e5dfSChristian Brauner 		flush_signal_handlers(tsk, 0);
1524*b612e5dfSChristian Brauner 
15251da177e4SLinus Torvalds 	return 0;
15261da177e4SLinus Torvalds }
15271da177e4SLinus Torvalds 
1528a7e5328aSOleg Nesterov void __cleanup_sighand(struct sighand_struct *sighand)
1529c81addc9SOleg Nesterov {
1530d036bda7SElena Reshetova 	if (refcount_dec_and_test(&sighand->count)) {
1531d80e731eSOleg Nesterov 		signalfd_cleanup(sighand);
1532392809b2SOleg Nesterov 		/*
15335f0d5a3aSPaul E. McKenney 		 * sighand_cachep is SLAB_TYPESAFE_BY_RCU so we can free it
1534392809b2SOleg Nesterov 		 * without an RCU grace period, see __lock_task_sighand().
1535392809b2SOleg Nesterov 		 */
1536c81addc9SOleg Nesterov 		kmem_cache_free(sighand_cachep, sighand);
1537c81addc9SOleg Nesterov 	}
1538d80e731eSOleg Nesterov }
1539c81addc9SOleg Nesterov 
1540f06febc9SFrank Mayhar /*
1541f06febc9SFrank Mayhar  * Initialize POSIX timer handling for a thread group.
1542f06febc9SFrank Mayhar  */
1543f06febc9SFrank Mayhar static void posix_cpu_timers_init_group(struct signal_struct *sig)
1544f06febc9SFrank Mayhar {
15452b69942fSThomas Gleixner 	struct posix_cputimers *pct = &sig->posix_cputimers;
154678d7d407SJiri Slaby 	unsigned long cpu_limit;
154778d7d407SJiri Slaby 
1548316c1608SJason Low 	cpu_limit = READ_ONCE(sig->rlim[RLIMIT_CPU].rlim_cur);
15493a245c0fSThomas Gleixner 	posix_cputimers_group_init(pct, cpu_limit);
15506279a751SOleg Nesterov }
15516279a751SOleg Nesterov 
1552a39bc516SAlexey Dobriyan static int copy_signal(unsigned long clone_flags, struct task_struct *tsk)
15531da177e4SLinus Torvalds {
15541da177e4SLinus Torvalds 	struct signal_struct *sig;
15551da177e4SLinus Torvalds 
15564ab6c083SOleg Nesterov 	if (clone_flags & CLONE_THREAD)
1557490dea45SPeter Zijlstra 		return 0;
15586279a751SOleg Nesterov 
1559a56704efSVeaceslav Falico 	sig = kmem_cache_zalloc(signal_cachep, GFP_KERNEL);
15601da177e4SLinus Torvalds 	tsk->signal = sig;
15611da177e4SLinus Torvalds 	if (!sig)
15621da177e4SLinus Torvalds 		return -ENOMEM;
15631da177e4SLinus Torvalds 
1564b3ac022cSOleg Nesterov 	sig->nr_threads = 1;
15651da177e4SLinus Torvalds 	atomic_set(&sig->live, 1);
156660d4de3fSElena Reshetova 	refcount_set(&sig->sigcnt, 1);
15670c740d0aSOleg Nesterov 
15680c740d0aSOleg Nesterov 	/* list_add(thread_node, thread_head) without INIT_LIST_HEAD() */
15690c740d0aSOleg Nesterov 	sig->thread_head = (struct list_head)LIST_HEAD_INIT(tsk->thread_node);
15700c740d0aSOleg Nesterov 	tsk->thread_node = (struct list_head)LIST_HEAD_INIT(sig->thread_head);
15710c740d0aSOleg Nesterov 
15721da177e4SLinus Torvalds 	init_waitqueue_head(&sig->wait_chldexit);
1573db51aeccSOleg Nesterov 	sig->curr_target = tsk;
15741da177e4SLinus Torvalds 	init_sigpending(&sig->shared_pending);
1575c3ad2c3bSEric W. Biederman 	INIT_HLIST_HEAD(&sig->multiprocess);
1576e78c3496SRik van Riel 	seqlock_init(&sig->stats_lock);
15779d7fb042SPeter Zijlstra 	prev_cputime_init(&sig->prev_cputime);
15781da177e4SLinus Torvalds 
1579baa73d9eSNicolas Pitre #ifdef CONFIG_POSIX_TIMERS
1580b18b6a9cSNicolas Pitre 	INIT_LIST_HEAD(&sig->posix_timers);
1581c9cb2e3dSThomas Gleixner 	hrtimer_init(&sig->real_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
15821da177e4SLinus Torvalds 	sig->real_timer.function = it_real_fn;
1583baa73d9eSNicolas Pitre #endif
15841da177e4SLinus Torvalds 
15851da177e4SLinus Torvalds 	task_lock(current->group_leader);
15861da177e4SLinus Torvalds 	memcpy(sig->rlim, current->signal->rlim, sizeof sig->rlim);
15871da177e4SLinus Torvalds 	task_unlock(current->group_leader);
15881da177e4SLinus Torvalds 
15896279a751SOleg Nesterov 	posix_cpu_timers_init_group(sig);
15906279a751SOleg Nesterov 
1591522ed776SMiloslav Trmac 	tty_audit_fork(sig);
15925091faa4SMike Galbraith 	sched_autogroup_fork(sig);
1593522ed776SMiloslav Trmac 
1594a63d83f4SDavid Rientjes 	sig->oom_score_adj = current->signal->oom_score_adj;
1595dabb16f6SMandeep Singh Baines 	sig->oom_score_adj_min = current->signal->oom_score_adj_min;
159628b83c51SKOSAKI Motohiro 
15979b1bf12dSKOSAKI Motohiro 	mutex_init(&sig->cred_guard_mutex);
15989b1bf12dSKOSAKI Motohiro 
15991da177e4SLinus Torvalds 	return 0;
16001da177e4SLinus Torvalds }
16011da177e4SLinus Torvalds 
1602dbd95212SKees Cook static void copy_seccomp(struct task_struct *p)
1603dbd95212SKees Cook {
1604dbd95212SKees Cook #ifdef CONFIG_SECCOMP
1605dbd95212SKees Cook 	/*
1606dbd95212SKees Cook 	 * Must be called with sighand->lock held, which is common to
1607dbd95212SKees Cook 	 * all threads in the group. Holding cred_guard_mutex is not
1608dbd95212SKees Cook 	 * needed because this new task is not yet running and cannot
1609dbd95212SKees Cook 	 * be racing exec.
1610dbd95212SKees Cook 	 */
161169f6a34bSGuenter Roeck 	assert_spin_locked(&current->sighand->siglock);
1612dbd95212SKees Cook 
1613dbd95212SKees Cook 	/* Ref-count the new filter user, and assign it. */
1614dbd95212SKees Cook 	get_seccomp_filter(current);
1615dbd95212SKees Cook 	p->seccomp = current->seccomp;
1616dbd95212SKees Cook 
1617dbd95212SKees Cook 	/*
1618dbd95212SKees Cook 	 * Explicitly enable no_new_privs here in case it got set
1619dbd95212SKees Cook 	 * between the task_struct being duplicated and holding the
1620dbd95212SKees Cook 	 * sighand lock. The seccomp state and nnp must be in sync.
1621dbd95212SKees Cook 	 */
1622dbd95212SKees Cook 	if (task_no_new_privs(current))
1623dbd95212SKees Cook 		task_set_no_new_privs(p);
1624dbd95212SKees Cook 
1625dbd95212SKees Cook 	/*
1626dbd95212SKees Cook 	 * If the parent gained a seccomp mode after copying thread
1627dbd95212SKees Cook 	 * flags and between before we held the sighand lock, we have
1628dbd95212SKees Cook 	 * to manually enable the seccomp thread flag here.
1629dbd95212SKees Cook 	 */
1630dbd95212SKees Cook 	if (p->seccomp.mode != SECCOMP_MODE_DISABLED)
1631dbd95212SKees Cook 		set_tsk_thread_flag(p, TIF_SECCOMP);
1632dbd95212SKees Cook #endif
1633dbd95212SKees Cook }
1634dbd95212SKees Cook 
163517da2bd9SHeiko Carstens SYSCALL_DEFINE1(set_tid_address, int __user *, tidptr)
16361da177e4SLinus Torvalds {
16371da177e4SLinus Torvalds 	current->clear_child_tid = tidptr;
16381da177e4SLinus Torvalds 
1639b488893aSPavel Emelyanov 	return task_pid_vnr(current);
16401da177e4SLinus Torvalds }
16411da177e4SLinus Torvalds 
1642a39bc516SAlexey Dobriyan static void rt_mutex_init_task(struct task_struct *p)
164323f78d4aSIngo Molnar {
16441d615482SThomas Gleixner 	raw_spin_lock_init(&p->pi_lock);
1645e29e175bSZilvinas Valinskas #ifdef CONFIG_RT_MUTEXES
1646a23ba907SDavidlohr Bueso 	p->pi_waiters = RB_ROOT_CACHED;
1647e96a7705SXunlei Pang 	p->pi_top_task = NULL;
164823f78d4aSIngo Molnar 	p->pi_blocked_on = NULL;
164923f78d4aSIngo Molnar #endif
165023f78d4aSIngo Molnar }
165123f78d4aSIngo Molnar 
16522c470475SEric W. Biederman static inline void init_task_pid_links(struct task_struct *task)
16532c470475SEric W. Biederman {
16542c470475SEric W. Biederman 	enum pid_type type;
16552c470475SEric W. Biederman 
16562c470475SEric W. Biederman 	for (type = PIDTYPE_PID; type < PIDTYPE_MAX; ++type) {
16572c470475SEric W. Biederman 		INIT_HLIST_NODE(&task->pid_links[type]);
16582c470475SEric W. Biederman 	}
16592c470475SEric W. Biederman }
16602c470475SEric W. Biederman 
166181907739SOleg Nesterov static inline void
166281907739SOleg Nesterov init_task_pid(struct task_struct *task, enum pid_type type, struct pid *pid)
166381907739SOleg Nesterov {
16642c470475SEric W. Biederman 	if (type == PIDTYPE_PID)
16652c470475SEric W. Biederman 		task->thread_pid = pid;
16662c470475SEric W. Biederman 	else
16672c470475SEric W. Biederman 		task->signal->pids[type] = pid;
166881907739SOleg Nesterov }
166981907739SOleg Nesterov 
16706bfbaa51SIngo Molnar static inline void rcu_copy_process(struct task_struct *p)
16716bfbaa51SIngo Molnar {
16726bfbaa51SIngo Molnar #ifdef CONFIG_PREEMPT_RCU
16736bfbaa51SIngo Molnar 	p->rcu_read_lock_nesting = 0;
16746bfbaa51SIngo Molnar 	p->rcu_read_unlock_special.s = 0;
16756bfbaa51SIngo Molnar 	p->rcu_blocked_node = NULL;
16766bfbaa51SIngo Molnar 	INIT_LIST_HEAD(&p->rcu_node_entry);
16776bfbaa51SIngo Molnar #endif /* #ifdef CONFIG_PREEMPT_RCU */
16786bfbaa51SIngo Molnar #ifdef CONFIG_TASKS_RCU
16796bfbaa51SIngo Molnar 	p->rcu_tasks_holdout = false;
16806bfbaa51SIngo Molnar 	INIT_LIST_HEAD(&p->rcu_tasks_holdout_list);
16816bfbaa51SIngo Molnar 	p->rcu_tasks_idle_cpu = -1;
16826bfbaa51SIngo Molnar #endif /* #ifdef CONFIG_TASKS_RCU */
16836bfbaa51SIngo Molnar }
16846bfbaa51SIngo Molnar 
16853695eae5SChristian Brauner struct pid *pidfd_pid(const struct file *file)
16863695eae5SChristian Brauner {
16873695eae5SChristian Brauner 	if (file->f_op == &pidfd_fops)
16883695eae5SChristian Brauner 		return file->private_data;
16893695eae5SChristian Brauner 
16903695eae5SChristian Brauner 	return ERR_PTR(-EBADF);
16913695eae5SChristian Brauner }
16923695eae5SChristian Brauner 
1693b3e58382SChristian Brauner static int pidfd_release(struct inode *inode, struct file *file)
1694b3e58382SChristian Brauner {
1695b3e58382SChristian Brauner 	struct pid *pid = file->private_data;
1696b3e58382SChristian Brauner 
1697b3e58382SChristian Brauner 	file->private_data = NULL;
1698b3e58382SChristian Brauner 	put_pid(pid);
1699b3e58382SChristian Brauner 	return 0;
1700b3e58382SChristian Brauner }
1701b3e58382SChristian Brauner 
1702b3e58382SChristian Brauner #ifdef CONFIG_PROC_FS
170315d42eb2SChristian Kellner /**
170415d42eb2SChristian Kellner  * pidfd_show_fdinfo - print information about a pidfd
170515d42eb2SChristian Kellner  * @m: proc fdinfo file
170615d42eb2SChristian Kellner  * @f: file referencing a pidfd
170715d42eb2SChristian Kellner  *
170815d42eb2SChristian Kellner  * Pid:
170915d42eb2SChristian Kellner  * This function will print the pid that a given pidfd refers to in the
171015d42eb2SChristian Kellner  * pid namespace of the procfs instance.
171115d42eb2SChristian Kellner  * If the pid namespace of the process is not a descendant of the pid
171215d42eb2SChristian Kellner  * namespace of the procfs instance 0 will be shown as its pid. This is
171315d42eb2SChristian Kellner  * similar to calling getppid() on a process whose parent is outside of
171415d42eb2SChristian Kellner  * its pid namespace.
171515d42eb2SChristian Kellner  *
171615d42eb2SChristian Kellner  * NSpid:
171715d42eb2SChristian Kellner  * If pid namespaces are supported then this function will also print
171815d42eb2SChristian Kellner  * the pid of a given pidfd refers to for all descendant pid namespaces
171915d42eb2SChristian Kellner  * starting from the current pid namespace of the instance, i.e. the
172015d42eb2SChristian Kellner  * Pid field and the first entry in the NSpid field will be identical.
172115d42eb2SChristian Kellner  * If the pid namespace of the process is not a descendant of the pid
172215d42eb2SChristian Kellner  * namespace of the procfs instance 0 will be shown as its first NSpid
172315d42eb2SChristian Kellner  * entry and no others will be shown.
172415d42eb2SChristian Kellner  * Note that this differs from the Pid and NSpid fields in
172515d42eb2SChristian Kellner  * /proc/<pid>/status where Pid and NSpid are always shown relative to
172615d42eb2SChristian Kellner  * the  pid namespace of the procfs instance. The difference becomes
172715d42eb2SChristian Kellner  * obvious when sending around a pidfd between pid namespaces from a
172815d42eb2SChristian Kellner  * different branch of the tree, i.e. where no ancestoral relation is
172915d42eb2SChristian Kellner  * present between the pid namespaces:
173015d42eb2SChristian Kellner  * - create two new pid namespaces ns1 and ns2 in the initial pid
173115d42eb2SChristian Kellner  *   namespace (also take care to create new mount namespaces in the
173215d42eb2SChristian Kellner  *   new pid namespace and mount procfs)
173315d42eb2SChristian Kellner  * - create a process with a pidfd in ns1
173415d42eb2SChristian Kellner  * - send pidfd from ns1 to ns2
173515d42eb2SChristian Kellner  * - read /proc/self/fdinfo/<pidfd> and observe that both Pid and NSpid
173615d42eb2SChristian Kellner  *   have exactly one entry, which is 0
173715d42eb2SChristian Kellner  */
1738b3e58382SChristian Brauner static void pidfd_show_fdinfo(struct seq_file *m, struct file *f)
1739b3e58382SChristian Brauner {
1740b3e58382SChristian Brauner 	struct pid *pid = f->private_data;
17413d6d8da4SChristian Brauner 	struct pid_namespace *ns;
17423d6d8da4SChristian Brauner 	pid_t nr = -1;
1743b3e58382SChristian Brauner 
17443d6d8da4SChristian Brauner 	if (likely(pid_has_task(pid, PIDTYPE_PID))) {
17453d6d8da4SChristian Brauner 		ns = proc_pid_ns(file_inode(m->file));
17463d6d8da4SChristian Brauner 		nr = pid_nr_ns(pid, ns);
17473d6d8da4SChristian Brauner 	}
17483d6d8da4SChristian Brauner 
17493d6d8da4SChristian Brauner 	seq_put_decimal_ll(m, "Pid:\t", nr);
175015d42eb2SChristian Kellner 
175115d42eb2SChristian Kellner #ifdef CONFIG_PID_NS
17523d6d8da4SChristian Brauner 	seq_put_decimal_ll(m, "\nNSpid:\t", nr);
17533d6d8da4SChristian Brauner 	if (nr > 0) {
175415d42eb2SChristian Kellner 		int i;
175515d42eb2SChristian Kellner 
175615d42eb2SChristian Kellner 		/* If nr is non-zero it means that 'pid' is valid and that
175715d42eb2SChristian Kellner 		 * ns, i.e. the pid namespace associated with the procfs
175815d42eb2SChristian Kellner 		 * instance, is in the pid namespace hierarchy of pid.
175915d42eb2SChristian Kellner 		 * Start at one below the already printed level.
176015d42eb2SChristian Kellner 		 */
176115d42eb2SChristian Kellner 		for (i = ns->level + 1; i <= pid->level; i++)
17623d6d8da4SChristian Brauner 			seq_put_decimal_ll(m, "\t", pid->numbers[i].nr);
176315d42eb2SChristian Kellner 	}
176415d42eb2SChristian Kellner #endif
1765b3e58382SChristian Brauner 	seq_putc(m, '\n');
1766b3e58382SChristian Brauner }
1767b3e58382SChristian Brauner #endif
1768b3e58382SChristian Brauner 
1769b53b0b9dSJoel Fernandes (Google) /*
1770b53b0b9dSJoel Fernandes (Google)  * Poll support for process exit notification.
1771b53b0b9dSJoel Fernandes (Google)  */
1772b53b0b9dSJoel Fernandes (Google) static unsigned int pidfd_poll(struct file *file, struct poll_table_struct *pts)
1773b53b0b9dSJoel Fernandes (Google) {
1774b53b0b9dSJoel Fernandes (Google) 	struct task_struct *task;
1775b53b0b9dSJoel Fernandes (Google) 	struct pid *pid = file->private_data;
1776b53b0b9dSJoel Fernandes (Google) 	int poll_flags = 0;
1777b53b0b9dSJoel Fernandes (Google) 
1778b53b0b9dSJoel Fernandes (Google) 	poll_wait(file, &pid->wait_pidfd, pts);
1779b53b0b9dSJoel Fernandes (Google) 
1780b53b0b9dSJoel Fernandes (Google) 	rcu_read_lock();
1781b53b0b9dSJoel Fernandes (Google) 	task = pid_task(pid, PIDTYPE_PID);
1782b53b0b9dSJoel Fernandes (Google) 	/*
1783b53b0b9dSJoel Fernandes (Google) 	 * Inform pollers only when the whole thread group exits.
1784b53b0b9dSJoel Fernandes (Google) 	 * If the thread group leader exits before all other threads in the
1785b53b0b9dSJoel Fernandes (Google) 	 * group, then poll(2) should block, similar to the wait(2) family.
1786b53b0b9dSJoel Fernandes (Google) 	 */
1787b53b0b9dSJoel Fernandes (Google) 	if (!task || (task->exit_state && thread_group_empty(task)))
1788b53b0b9dSJoel Fernandes (Google) 		poll_flags = POLLIN | POLLRDNORM;
1789b53b0b9dSJoel Fernandes (Google) 	rcu_read_unlock();
1790b53b0b9dSJoel Fernandes (Google) 
1791b53b0b9dSJoel Fernandes (Google) 	return poll_flags;
1792b53b0b9dSJoel Fernandes (Google) }
1793b53b0b9dSJoel Fernandes (Google) 
1794b3e58382SChristian Brauner const struct file_operations pidfd_fops = {
1795b3e58382SChristian Brauner 	.release = pidfd_release,
1796b53b0b9dSJoel Fernandes (Google) 	.poll = pidfd_poll,
1797b3e58382SChristian Brauner #ifdef CONFIG_PROC_FS
1798b3e58382SChristian Brauner 	.show_fdinfo = pidfd_show_fdinfo,
1799b3e58382SChristian Brauner #endif
1800b3e58382SChristian Brauner };
1801b3e58382SChristian Brauner 
1802c3f3ce04SAndrea Arcangeli static void __delayed_free_task(struct rcu_head *rhp)
1803c3f3ce04SAndrea Arcangeli {
1804c3f3ce04SAndrea Arcangeli 	struct task_struct *tsk = container_of(rhp, struct task_struct, rcu);
1805c3f3ce04SAndrea Arcangeli 
1806c3f3ce04SAndrea Arcangeli 	free_task(tsk);
1807c3f3ce04SAndrea Arcangeli }
1808c3f3ce04SAndrea Arcangeli 
1809c3f3ce04SAndrea Arcangeli static __always_inline void delayed_free_task(struct task_struct *tsk)
1810c3f3ce04SAndrea Arcangeli {
1811c3f3ce04SAndrea Arcangeli 	if (IS_ENABLED(CONFIG_MEMCG))
1812c3f3ce04SAndrea Arcangeli 		call_rcu(&tsk->rcu, __delayed_free_task);
1813c3f3ce04SAndrea Arcangeli 	else
1814c3f3ce04SAndrea Arcangeli 		free_task(tsk);
1815c3f3ce04SAndrea Arcangeli }
1816c3f3ce04SAndrea Arcangeli 
1817f06febc9SFrank Mayhar /*
18181da177e4SLinus Torvalds  * This creates a new process as a copy of the old one,
18191da177e4SLinus Torvalds  * but does not actually start it yet.
18201da177e4SLinus Torvalds  *
18211da177e4SLinus Torvalds  * It copies the registers, and all the appropriate
18221da177e4SLinus Torvalds  * parts of the process environment (as per the clone
18231da177e4SLinus Torvalds  * flags). The actual kick-off is left to the caller.
18241da177e4SLinus Torvalds  */
18250766f788SEmese Revfy static __latent_entropy struct task_struct *copy_process(
182609a05394SRoland McGrath 					struct pid *pid,
18273033f14aSJosh Triplett 					int trace,
18287f192e3cSChristian Brauner 					int node,
18297f192e3cSChristian Brauner 					struct kernel_clone_args *args)
18301da177e4SLinus Torvalds {
1831b3e58382SChristian Brauner 	int pidfd = -1, retval;
1832a24efe62SMariusz Kozlowski 	struct task_struct *p;
1833c3ad2c3bSEric W. Biederman 	struct multiprocess_signals delayed;
18346fd2fe49SAl Viro 	struct file *pidfile = NULL;
18357f192e3cSChristian Brauner 	u64 clone_flags = args->flags;
18361da177e4SLinus Torvalds 
1837667b6094SMarcos Paulo de Souza 	/*
1838667b6094SMarcos Paulo de Souza 	 * Don't allow sharing the root directory with processes in a different
1839667b6094SMarcos Paulo de Souza 	 * namespace
1840667b6094SMarcos Paulo de Souza 	 */
18411da177e4SLinus Torvalds 	if ((clone_flags & (CLONE_NEWNS|CLONE_FS)) == (CLONE_NEWNS|CLONE_FS))
18421da177e4SLinus Torvalds 		return ERR_PTR(-EINVAL);
18431da177e4SLinus Torvalds 
1844e66eded8SEric W. Biederman 	if ((clone_flags & (CLONE_NEWUSER|CLONE_FS)) == (CLONE_NEWUSER|CLONE_FS))
1845e66eded8SEric W. Biederman 		return ERR_PTR(-EINVAL);
1846e66eded8SEric W. Biederman 
18471da177e4SLinus Torvalds 	/*
18481da177e4SLinus Torvalds 	 * Thread groups must share signals as well, and detached threads
18491da177e4SLinus Torvalds 	 * can only be started up within the thread group.
18501da177e4SLinus Torvalds 	 */
18511da177e4SLinus Torvalds 	if ((clone_flags & CLONE_THREAD) && !(clone_flags & CLONE_SIGHAND))
18521da177e4SLinus Torvalds 		return ERR_PTR(-EINVAL);
18531da177e4SLinus Torvalds 
18541da177e4SLinus Torvalds 	/*
18551da177e4SLinus Torvalds 	 * Shared signal handlers imply shared VM. By way of the above,
18561da177e4SLinus Torvalds 	 * thread groups also imply shared VM. Blocking this case allows
18571da177e4SLinus Torvalds 	 * for various simplifications in other code.
18581da177e4SLinus Torvalds 	 */
18591da177e4SLinus Torvalds 	if ((clone_flags & CLONE_SIGHAND) && !(clone_flags & CLONE_VM))
18601da177e4SLinus Torvalds 		return ERR_PTR(-EINVAL);
18611da177e4SLinus Torvalds 
1862123be07bSSukadev Bhattiprolu 	/*
1863123be07bSSukadev Bhattiprolu 	 * Siblings of global init remain as zombies on exit since they are
1864123be07bSSukadev Bhattiprolu 	 * not reaped by their parent (swapper). To solve this and to avoid
1865123be07bSSukadev Bhattiprolu 	 * multi-rooted process trees, prevent global and container-inits
1866123be07bSSukadev Bhattiprolu 	 * from creating siblings.
1867123be07bSSukadev Bhattiprolu 	 */
1868123be07bSSukadev Bhattiprolu 	if ((clone_flags & CLONE_PARENT) &&
1869123be07bSSukadev Bhattiprolu 				current->signal->flags & SIGNAL_UNKILLABLE)
1870123be07bSSukadev Bhattiprolu 		return ERR_PTR(-EINVAL);
1871123be07bSSukadev Bhattiprolu 
18728382fcacSEric W. Biederman 	/*
187340a0d32dSOleg Nesterov 	 * If the new process will be in a different pid or user namespace
1874faf00da5SEric W. Biederman 	 * do not allow it to share a thread group with the forking task.
18758382fcacSEric W. Biederman 	 */
1876faf00da5SEric W. Biederman 	if (clone_flags & CLONE_THREAD) {
187740a0d32dSOleg Nesterov 		if ((clone_flags & (CLONE_NEWUSER | CLONE_NEWPID)) ||
187840a0d32dSOleg Nesterov 		    (task_active_pid_ns(current) !=
1879c2b1df2eSAndy Lutomirski 				current->nsproxy->pid_ns_for_children))
18808382fcacSEric W. Biederman 			return ERR_PTR(-EINVAL);
188140a0d32dSOleg Nesterov 	}
18828382fcacSEric W. Biederman 
1883b3e58382SChristian Brauner 	if (clone_flags & CLONE_PIDFD) {
1884b3e58382SChristian Brauner 		/*
1885b3e58382SChristian Brauner 		 * - CLONE_DETACHED is blocked so that we can potentially
1886b3e58382SChristian Brauner 		 *   reuse it later for CLONE_PIDFD.
1887b3e58382SChristian Brauner 		 * - CLONE_THREAD is blocked until someone really needs it.
1888b3e58382SChristian Brauner 		 */
18897f192e3cSChristian Brauner 		if (clone_flags & (CLONE_DETACHED | CLONE_THREAD))
1890b3e58382SChristian Brauner 			return ERR_PTR(-EINVAL);
1891b3e58382SChristian Brauner 	}
1892b3e58382SChristian Brauner 
1893c3ad2c3bSEric W. Biederman 	/*
1894c3ad2c3bSEric W. Biederman 	 * Force any signals received before this point to be delivered
1895c3ad2c3bSEric W. Biederman 	 * before the fork happens.  Collect up signals sent to multiple
1896c3ad2c3bSEric W. Biederman 	 * processes that happen during the fork and delay them so that
1897c3ad2c3bSEric W. Biederman 	 * they appear to happen after the fork.
1898c3ad2c3bSEric W. Biederman 	 */
1899c3ad2c3bSEric W. Biederman 	sigemptyset(&delayed.signal);
1900c3ad2c3bSEric W. Biederman 	INIT_HLIST_NODE(&delayed.node);
1901c3ad2c3bSEric W. Biederman 
1902c3ad2c3bSEric W. Biederman 	spin_lock_irq(&current->sighand->siglock);
1903c3ad2c3bSEric W. Biederman 	if (!(clone_flags & CLONE_THREAD))
1904c3ad2c3bSEric W. Biederman 		hlist_add_head(&delayed.node, &current->signal->multiprocess);
1905c3ad2c3bSEric W. Biederman 	recalc_sigpending();
1906c3ad2c3bSEric W. Biederman 	spin_unlock_irq(&current->sighand->siglock);
1907c3ad2c3bSEric W. Biederman 	retval = -ERESTARTNOINTR;
1908c3ad2c3bSEric W. Biederman 	if (signal_pending(current))
1909c3ad2c3bSEric W. Biederman 		goto fork_out;
1910c3ad2c3bSEric W. Biederman 
19111da177e4SLinus Torvalds 	retval = -ENOMEM;
1912725fc629SAndi Kleen 	p = dup_task_struct(current, node);
19131da177e4SLinus Torvalds 	if (!p)
19141da177e4SLinus Torvalds 		goto fork_out;
19151da177e4SLinus Torvalds 
19164d6501dcSVegard Nossum 	/*
19174d6501dcSVegard Nossum 	 * This _must_ happen before we call free_task(), i.e. before we jump
19184d6501dcSVegard Nossum 	 * to any of the bad_fork_* labels. This is to avoid freeing
19194d6501dcSVegard Nossum 	 * p->set_child_tid which is (ab)used as a kthread's data pointer for
19204d6501dcSVegard Nossum 	 * kernel threads (PF_KTHREAD).
19214d6501dcSVegard Nossum 	 */
19227f192e3cSChristian Brauner 	p->set_child_tid = (clone_flags & CLONE_CHILD_SETTID) ? args->child_tid : NULL;
19234d6501dcSVegard Nossum 	/*
19244d6501dcSVegard Nossum 	 * Clear TID on mm_release()?
19254d6501dcSVegard Nossum 	 */
19267f192e3cSChristian Brauner 	p->clear_child_tid = (clone_flags & CLONE_CHILD_CLEARTID) ? args->child_tid : NULL;
19274d6501dcSVegard Nossum 
1928f7e8b616SSteven Rostedt 	ftrace_graph_init_task(p);
1929f7e8b616SSteven Rostedt 
1930bea493a0SPeter Zijlstra 	rt_mutex_init_task(p);
1931bea493a0SPeter Zijlstra 
1932d12c1a37SIngo Molnar #ifdef CONFIG_PROVE_LOCKING
1933de30a2b3SIngo Molnar 	DEBUG_LOCKS_WARN_ON(!p->hardirqs_enabled);
1934de30a2b3SIngo Molnar 	DEBUG_LOCKS_WARN_ON(!p->softirqs_enabled);
1935de30a2b3SIngo Molnar #endif
19361da177e4SLinus Torvalds 	retval = -EAGAIN;
19373b11a1deSDavid Howells 	if (atomic_read(&p->real_cred->user->processes) >=
193878d7d407SJiri Slaby 			task_rlimit(p, RLIMIT_NPROC)) {
1939b57922b6SEric Paris 		if (p->real_cred->user != INIT_USER &&
1940b57922b6SEric Paris 		    !capable(CAP_SYS_RESOURCE) && !capable(CAP_SYS_ADMIN))
19411da177e4SLinus Torvalds 			goto bad_fork_free;
19421da177e4SLinus Torvalds 	}
194372fa5997SVasiliy Kulikov 	current->flags &= ~PF_NPROC_EXCEEDED;
19441da177e4SLinus Torvalds 
1945f1752eecSDavid Howells 	retval = copy_creds(p, clone_flags);
1946f1752eecSDavid Howells 	if (retval < 0)
1947f1752eecSDavid Howells 		goto bad_fork_free;
19481da177e4SLinus Torvalds 
19491da177e4SLinus Torvalds 	/*
19501da177e4SLinus Torvalds 	 * If multiple threads are within copy_process(), then this check
19511da177e4SLinus Torvalds 	 * triggers too late. This doesn't hurt, the check is only there
19521da177e4SLinus Torvalds 	 * to stop root fork bombs.
19531da177e4SLinus Torvalds 	 */
195404ec93feSLi Zefan 	retval = -EAGAIN;
19551da177e4SLinus Torvalds 	if (nr_threads >= max_threads)
19561da177e4SLinus Torvalds 		goto bad_fork_cleanup_count;
19571da177e4SLinus Torvalds 
1958ca74e92bSShailabh Nagar 	delayacct_tsk_init(p);	/* Must remain after dup_task_struct() */
1959c1de45caSPeter Zijlstra 	p->flags &= ~(PF_SUPERPRIV | PF_WQ_WORKER | PF_IDLE);
1960514ddb44SDavid Rientjes 	p->flags |= PF_FORKNOEXEC;
19611da177e4SLinus Torvalds 	INIT_LIST_HEAD(&p->children);
19621da177e4SLinus Torvalds 	INIT_LIST_HEAD(&p->sibling);
1963f41d911fSPaul E. McKenney 	rcu_copy_process(p);
19641da177e4SLinus Torvalds 	p->vfork_done = NULL;
19651da177e4SLinus Torvalds 	spin_lock_init(&p->alloc_lock);
19661da177e4SLinus Torvalds 
19671da177e4SLinus Torvalds 	init_sigpending(&p->pending);
19681da177e4SLinus Torvalds 
196964861634SMartin Schwidefsky 	p->utime = p->stime = p->gtime = 0;
197040565b5aSStanislaw Gruszka #ifdef CONFIG_ARCH_HAS_SCALED_CPUTIME
197164861634SMartin Schwidefsky 	p->utimescaled = p->stimescaled = 0;
197240565b5aSStanislaw Gruszka #endif
19739d7fb042SPeter Zijlstra 	prev_cputime_init(&p->prev_cputime);
19749d7fb042SPeter Zijlstra 
19756a61671bSFrederic Weisbecker #ifdef CONFIG_VIRT_CPU_ACCOUNTING_GEN
1976bac5b6b6SFrederic Weisbecker 	seqcount_init(&p->vtime.seqcount);
1977bac5b6b6SFrederic Weisbecker 	p->vtime.starttime = 0;
1978bac5b6b6SFrederic Weisbecker 	p->vtime.state = VTIME_INACTIVE;
19796a61671bSFrederic Weisbecker #endif
19806a61671bSFrederic Weisbecker 
1981a3a2e76cSKAMEZAWA Hiroyuki #if defined(SPLIT_RSS_COUNTING)
1982a3a2e76cSKAMEZAWA Hiroyuki 	memset(&p->rss_stat, 0, sizeof(p->rss_stat));
1983a3a2e76cSKAMEZAWA Hiroyuki #endif
1984172ba844SBalbir Singh 
19856976675dSArjan van de Ven 	p->default_timer_slack_ns = current->timer_slack_ns;
19866976675dSArjan van de Ven 
1987eb414681SJohannes Weiner #ifdef CONFIG_PSI
1988eb414681SJohannes Weiner 	p->psi_flags = 0;
1989eb414681SJohannes Weiner #endif
1990eb414681SJohannes Weiner 
19915995477aSAndrea Righi 	task_io_accounting_init(&p->ioac);
19921da177e4SLinus Torvalds 	acct_clear_integrals(p);
19931da177e4SLinus Torvalds 
19943a245c0fSThomas Gleixner 	posix_cputimers_init(&p->posix_cputimers);
19951da177e4SLinus Torvalds 
19961da177e4SLinus Torvalds 	p->io_context = NULL;
1997c0b0ae8aSRichard Guy Briggs 	audit_set_context(p, NULL);
1998b4f48b63SPaul Menage 	cgroup_fork(p);
19991da177e4SLinus Torvalds #ifdef CONFIG_NUMA
2000846a16bfSLee Schermerhorn 	p->mempolicy = mpol_dup(p->mempolicy);
20011da177e4SLinus Torvalds 	if (IS_ERR(p->mempolicy)) {
20021da177e4SLinus Torvalds 		retval = PTR_ERR(p->mempolicy);
20031da177e4SLinus Torvalds 		p->mempolicy = NULL;
2004e8604cb4SLi Zefan 		goto bad_fork_cleanup_threadgroup_lock;
20051da177e4SLinus Torvalds 	}
20061da177e4SLinus Torvalds #endif
2007778d3b0fSMichal Hocko #ifdef CONFIG_CPUSETS
2008778d3b0fSMichal Hocko 	p->cpuset_mem_spread_rotor = NUMA_NO_NODE;
2009778d3b0fSMichal Hocko 	p->cpuset_slab_spread_rotor = NUMA_NO_NODE;
2010cc9a6c87SMel Gorman 	seqcount_init(&p->mems_allowed_seq);
2011778d3b0fSMichal Hocko #endif
2012de30a2b3SIngo Molnar #ifdef CONFIG_TRACE_IRQFLAGS
2013de30a2b3SIngo Molnar 	p->irq_events = 0;
2014de30a2b3SIngo Molnar 	p->hardirqs_enabled = 0;
2015de30a2b3SIngo Molnar 	p->hardirq_enable_ip = 0;
2016de30a2b3SIngo Molnar 	p->hardirq_enable_event = 0;
2017de30a2b3SIngo Molnar 	p->hardirq_disable_ip = _THIS_IP_;
2018de30a2b3SIngo Molnar 	p->hardirq_disable_event = 0;
2019de30a2b3SIngo Molnar 	p->softirqs_enabled = 1;
2020de30a2b3SIngo Molnar 	p->softirq_enable_ip = _THIS_IP_;
2021de30a2b3SIngo Molnar 	p->softirq_enable_event = 0;
2022de30a2b3SIngo Molnar 	p->softirq_disable_ip = 0;
2023de30a2b3SIngo Molnar 	p->softirq_disable_event = 0;
2024de30a2b3SIngo Molnar 	p->hardirq_context = 0;
2025de30a2b3SIngo Molnar 	p->softirq_context = 0;
2026de30a2b3SIngo Molnar #endif
20278bcbde54SDavid Hildenbrand 
20288bcbde54SDavid Hildenbrand 	p->pagefault_disabled = 0;
20298bcbde54SDavid Hildenbrand 
2030fbb9ce95SIngo Molnar #ifdef CONFIG_LOCKDEP
2031b09be676SByungchul Park 	lockdep_init_task(p);
2032fbb9ce95SIngo Molnar #endif
20331da177e4SLinus Torvalds 
2034408894eeSIngo Molnar #ifdef CONFIG_DEBUG_MUTEXES
2035408894eeSIngo Molnar 	p->blocked_on = NULL; /* not blocked yet */
2036408894eeSIngo Molnar #endif
2037cafe5635SKent Overstreet #ifdef CONFIG_BCACHE
2038cafe5635SKent Overstreet 	p->sequential_io	= 0;
2039cafe5635SKent Overstreet 	p->sequential_io_avg	= 0;
2040cafe5635SKent Overstreet #endif
20410f481406SMarkus Metzger 
20423c90e6e9SSrivatsa Vaddagiri 	/* Perform scheduler related setup. Assign this task to a CPU. */
2043aab03e05SDario Faggioli 	retval = sched_fork(clone_flags, p);
2044aab03e05SDario Faggioli 	if (retval)
2045aab03e05SDario Faggioli 		goto bad_fork_cleanup_policy;
20466ab423e0SPeter Zijlstra 
2047cdd6c482SIngo Molnar 	retval = perf_event_init_task(p);
20486ab423e0SPeter Zijlstra 	if (retval)
20496ab423e0SPeter Zijlstra 		goto bad_fork_cleanup_policy;
2050fb0a685cSDaniel Rebelo de Oliveira 	retval = audit_alloc(p);
2051fb0a685cSDaniel Rebelo de Oliveira 	if (retval)
20526c72e350SPeter Zijlstra 		goto bad_fork_cleanup_perf;
20531da177e4SLinus Torvalds 	/* copy all the process information */
2054ab602f79SJack Miller 	shm_init_task(p);
2055e4e55b47STetsuo Handa 	retval = security_task_alloc(p, clone_flags);
2056fb0a685cSDaniel Rebelo de Oliveira 	if (retval)
20571da177e4SLinus Torvalds 		goto bad_fork_cleanup_audit;
2058e4e55b47STetsuo Handa 	retval = copy_semundo(clone_flags, p);
2059e4e55b47STetsuo Handa 	if (retval)
2060e4e55b47STetsuo Handa 		goto bad_fork_cleanup_security;
2061fb0a685cSDaniel Rebelo de Oliveira 	retval = copy_files(clone_flags, p);
2062fb0a685cSDaniel Rebelo de Oliveira 	if (retval)
20631da177e4SLinus Torvalds 		goto bad_fork_cleanup_semundo;
2064fb0a685cSDaniel Rebelo de Oliveira 	retval = copy_fs(clone_flags, p);
2065fb0a685cSDaniel Rebelo de Oliveira 	if (retval)
20661da177e4SLinus Torvalds 		goto bad_fork_cleanup_files;
2067fb0a685cSDaniel Rebelo de Oliveira 	retval = copy_sighand(clone_flags, p);
2068fb0a685cSDaniel Rebelo de Oliveira 	if (retval)
20691da177e4SLinus Torvalds 		goto bad_fork_cleanup_fs;
2070fb0a685cSDaniel Rebelo de Oliveira 	retval = copy_signal(clone_flags, p);
2071fb0a685cSDaniel Rebelo de Oliveira 	if (retval)
20721da177e4SLinus Torvalds 		goto bad_fork_cleanup_sighand;
2073fb0a685cSDaniel Rebelo de Oliveira 	retval = copy_mm(clone_flags, p);
2074fb0a685cSDaniel Rebelo de Oliveira 	if (retval)
20751da177e4SLinus Torvalds 		goto bad_fork_cleanup_signal;
2076fb0a685cSDaniel Rebelo de Oliveira 	retval = copy_namespaces(clone_flags, p);
2077fb0a685cSDaniel Rebelo de Oliveira 	if (retval)
2078d84f4f99SDavid Howells 		goto bad_fork_cleanup_mm;
2079fb0a685cSDaniel Rebelo de Oliveira 	retval = copy_io(clone_flags, p);
2080fb0a685cSDaniel Rebelo de Oliveira 	if (retval)
2081fd0928dfSJens Axboe 		goto bad_fork_cleanup_namespaces;
20827f192e3cSChristian Brauner 	retval = copy_thread_tls(clone_flags, args->stack, args->stack_size, p,
20837f192e3cSChristian Brauner 				 args->tls);
20841da177e4SLinus Torvalds 	if (retval)
2085fd0928dfSJens Axboe 		goto bad_fork_cleanup_io;
20861da177e4SLinus Torvalds 
2087afaef01cSAlexander Popov 	stackleak_task_init(p);
2088afaef01cSAlexander Popov 
2089425fb2b4SPavel Emelyanov 	if (pid != &init_struct_pid) {
2090c2b1df2eSAndy Lutomirski 		pid = alloc_pid(p->nsproxy->pid_ns_for_children);
209135f71bc0SMichal Hocko 		if (IS_ERR(pid)) {
209235f71bc0SMichal Hocko 			retval = PTR_ERR(pid);
20930740aa5fSJiri Slaby 			goto bad_fork_cleanup_thread;
2094425fb2b4SPavel Emelyanov 		}
209535f71bc0SMichal Hocko 	}
2096425fb2b4SPavel Emelyanov 
2097b3e58382SChristian Brauner 	/*
2098b3e58382SChristian Brauner 	 * This has to happen after we've potentially unshared the file
2099b3e58382SChristian Brauner 	 * descriptor table (so that the pidfd doesn't leak into the child
2100b3e58382SChristian Brauner 	 * if the fd table isn't shared).
2101b3e58382SChristian Brauner 	 */
2102b3e58382SChristian Brauner 	if (clone_flags & CLONE_PIDFD) {
21036fd2fe49SAl Viro 		retval = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
2104b3e58382SChristian Brauner 		if (retval < 0)
2105b3e58382SChristian Brauner 			goto bad_fork_free_pid;
2106b3e58382SChristian Brauner 
2107b3e58382SChristian Brauner 		pidfd = retval;
21086fd2fe49SAl Viro 
21096fd2fe49SAl Viro 		pidfile = anon_inode_getfile("[pidfd]", &pidfd_fops, pid,
21106fd2fe49SAl Viro 					      O_RDWR | O_CLOEXEC);
21116fd2fe49SAl Viro 		if (IS_ERR(pidfile)) {
21126fd2fe49SAl Viro 			put_unused_fd(pidfd);
211328dd29c0SChristian Brauner 			retval = PTR_ERR(pidfile);
21146fd2fe49SAl Viro 			goto bad_fork_free_pid;
21156fd2fe49SAl Viro 		}
21166fd2fe49SAl Viro 		get_pid(pid);	/* held by pidfile now */
21176fd2fe49SAl Viro 
21187f192e3cSChristian Brauner 		retval = put_user(pidfd, args->pidfd);
2119b3e58382SChristian Brauner 		if (retval)
2120b3e58382SChristian Brauner 			goto bad_fork_put_pidfd;
2121b3e58382SChristian Brauner 	}
2122b3e58382SChristian Brauner 
212373c10101SJens Axboe #ifdef CONFIG_BLOCK
212473c10101SJens Axboe 	p->plug = NULL;
212573c10101SJens Axboe #endif
212642b2dd0aSAlexey Dobriyan #ifdef CONFIG_FUTEX
21278f17d3a5SIngo Molnar 	p->robust_list = NULL;
21288f17d3a5SIngo Molnar #ifdef CONFIG_COMPAT
21298f17d3a5SIngo Molnar 	p->compat_robust_list = NULL;
21308f17d3a5SIngo Molnar #endif
2131c87e2837SIngo Molnar 	INIT_LIST_HEAD(&p->pi_state_list);
2132c87e2837SIngo Molnar 	p->pi_state_cache = NULL;
213342b2dd0aSAlexey Dobriyan #endif
21341da177e4SLinus Torvalds 	/*
2135f9a3879aSGOTO Masanori 	 * sigaltstack should be cleared when sharing the same VM
2136f9a3879aSGOTO Masanori 	 */
2137f9a3879aSGOTO Masanori 	if ((clone_flags & (CLONE_VM|CLONE_VFORK)) == CLONE_VM)
21382a742138SStas Sergeev 		sas_ss_reset(p);
2139f9a3879aSGOTO Masanori 
2140f9a3879aSGOTO Masanori 	/*
21416580807dSOleg Nesterov 	 * Syscall tracing and stepping should be turned off in the
21426580807dSOleg Nesterov 	 * child regardless of CLONE_PTRACE.
21431da177e4SLinus Torvalds 	 */
21446580807dSOleg Nesterov 	user_disable_single_step(p);
21451da177e4SLinus Torvalds 	clear_tsk_thread_flag(p, TIF_SYSCALL_TRACE);
2146ed75e8d5SLaurent Vivier #ifdef TIF_SYSCALL_EMU
2147ed75e8d5SLaurent Vivier 	clear_tsk_thread_flag(p, TIF_SYSCALL_EMU);
2148ed75e8d5SLaurent Vivier #endif
2149e02c9b0dSLin Feng 	clear_tsk_latency_tracing(p);
21501da177e4SLinus Torvalds 
21511da177e4SLinus Torvalds 	/* ok, now we should be set up.. */
215218c830dfSOleg Nesterov 	p->pid = pid_nr(pid);
215318c830dfSOleg Nesterov 	if (clone_flags & CLONE_THREAD) {
21545f8aadd8SOleg Nesterov 		p->exit_signal = -1;
215518c830dfSOleg Nesterov 		p->group_leader = current->group_leader;
215618c830dfSOleg Nesterov 		p->tgid = current->tgid;
215718c830dfSOleg Nesterov 	} else {
215818c830dfSOleg Nesterov 		if (clone_flags & CLONE_PARENT)
21595f8aadd8SOleg Nesterov 			p->exit_signal = current->group_leader->exit_signal;
21605f8aadd8SOleg Nesterov 		else
21617f192e3cSChristian Brauner 			p->exit_signal = args->exit_signal;
216218c830dfSOleg Nesterov 		p->group_leader = p;
216318c830dfSOleg Nesterov 		p->tgid = p->pid;
216418c830dfSOleg Nesterov 	}
21655f8aadd8SOleg Nesterov 
21669d823e8fSWu Fengguang 	p->nr_dirtied = 0;
21679d823e8fSWu Fengguang 	p->nr_dirtied_pause = 128 >> (PAGE_SHIFT - 10);
216883712358SWu Fengguang 	p->dirty_paused_when = 0;
21699d823e8fSWu Fengguang 
2170bb8cbbfeSOleg Nesterov 	p->pdeath_signal = 0;
217147e65328SOleg Nesterov 	INIT_LIST_HEAD(&p->thread_group);
2172158e1645SAl Viro 	p->task_works = NULL;
21731da177e4SLinus Torvalds 
2174780de9ddSIngo Molnar 	cgroup_threadgroup_change_begin(current);
217518c830dfSOleg Nesterov 	/*
21767e47682eSAleksa Sarai 	 * Ensure that the cgroup subsystem policies allow the new process to be
21777e47682eSAleksa Sarai 	 * forked. It should be noted the the new process's css_set can be changed
21787e47682eSAleksa Sarai 	 * between here and cgroup_post_fork() if an organisation operation is in
21797e47682eSAleksa Sarai 	 * progress.
21807e47682eSAleksa Sarai 	 */
2181b53202e6SOleg Nesterov 	retval = cgroup_can_fork(p);
21827e47682eSAleksa Sarai 	if (retval)
2183c3b7112dSChristian Brauner 		goto bad_fork_cgroup_threadgroup_change_end;
21847e47682eSAleksa Sarai 
21857e47682eSAleksa Sarai 	/*
21867b558513SDavid Herrmann 	 * From this point on we must avoid any synchronous user-space
21877b558513SDavid Herrmann 	 * communication until we take the tasklist-lock. In particular, we do
21887b558513SDavid Herrmann 	 * not want user-space to be able to predict the process start-time by
21897b558513SDavid Herrmann 	 * stalling fork(2) after we recorded the start_time but before it is
21907b558513SDavid Herrmann 	 * visible to the system.
21917b558513SDavid Herrmann 	 */
21927b558513SDavid Herrmann 
21937b558513SDavid Herrmann 	p->start_time = ktime_get_ns();
21949285ec4cSJason A. Donenfeld 	p->real_start_time = ktime_get_boottime_ns();
21957b558513SDavid Herrmann 
21967b558513SDavid Herrmann 	/*
219718c830dfSOleg Nesterov 	 * Make it visible to the rest of the system, but dont wake it up yet.
219818c830dfSOleg Nesterov 	 * Need tasklist lock for parent etc handling!
219918c830dfSOleg Nesterov 	 */
22001da177e4SLinus Torvalds 	write_lock_irq(&tasklist_lock);
22011da177e4SLinus Torvalds 
22021da177e4SLinus Torvalds 	/* CLONE_PARENT re-uses the old parent */
22032d5516cbSOleg Nesterov 	if (clone_flags & (CLONE_PARENT|CLONE_THREAD)) {
22041da177e4SLinus Torvalds 		p->real_parent = current->real_parent;
22052d5516cbSOleg Nesterov 		p->parent_exec_id = current->parent_exec_id;
22062d5516cbSOleg Nesterov 	} else {
22071da177e4SLinus Torvalds 		p->real_parent = current;
22082d5516cbSOleg Nesterov 		p->parent_exec_id = current->self_exec_id;
22092d5516cbSOleg Nesterov 	}
22101da177e4SLinus Torvalds 
2211d83a7cb3SJosh Poimboeuf 	klp_copy_process(p);
2212d83a7cb3SJosh Poimboeuf 
22131da177e4SLinus Torvalds 	spin_lock(&current->sighand->siglock);
22144a2c7a78SOleg Nesterov 
22154a2c7a78SOleg Nesterov 	/*
2216dbd95212SKees Cook 	 * Copy seccomp details explicitly here, in case they were changed
2217dbd95212SKees Cook 	 * before holding sighand lock.
2218dbd95212SKees Cook 	 */
2219dbd95212SKees Cook 	copy_seccomp(p);
2220dbd95212SKees Cook 
2221d7822b1eSMathieu Desnoyers 	rseq_fork(p, clone_flags);
2222d7822b1eSMathieu Desnoyers 
22234ca1d3eeSEric W. Biederman 	/* Don't start children in a dying pid namespace */
2224e8cfbc24SGargi Sharma 	if (unlikely(!(ns_of_pid(pid)->pid_allocated & PIDNS_ADDING))) {
22253fd37226SKirill Tkhai 		retval = -ENOMEM;
22263fd37226SKirill Tkhai 		goto bad_fork_cancel_cgroup;
22273fd37226SKirill Tkhai 	}
22284a2c7a78SOleg Nesterov 
22297673bf55SEric W. Biederman 	/* Let kill terminate clone/fork in the middle */
22307673bf55SEric W. Biederman 	if (fatal_signal_pending(current)) {
22317673bf55SEric W. Biederman 		retval = -EINTR;
22327673bf55SEric W. Biederman 		goto bad_fork_cancel_cgroup;
22337673bf55SEric W. Biederman 	}
22347673bf55SEric W. Biederman 
22356fd2fe49SAl Viro 	/* past the last point of failure */
22366fd2fe49SAl Viro 	if (pidfile)
22376fd2fe49SAl Viro 		fd_install(pidfd, pidfile);
22381da177e4SLinus Torvalds 
22392c470475SEric W. Biederman 	init_task_pid_links(p);
224073b9ebfeSOleg Nesterov 	if (likely(p->pid)) {
22414b9d33e6STejun Heo 		ptrace_init_task(p, (clone_flags & CLONE_PTRACE) || trace);
22421da177e4SLinus Torvalds 
224381907739SOleg Nesterov 		init_task_pid(p, PIDTYPE_PID, pid);
22441da177e4SLinus Torvalds 		if (thread_group_leader(p)) {
22456883f81aSEric W. Biederman 			init_task_pid(p, PIDTYPE_TGID, pid);
224681907739SOleg Nesterov 			init_task_pid(p, PIDTYPE_PGID, task_pgrp(current));
224781907739SOleg Nesterov 			init_task_pid(p, PIDTYPE_SID, task_session(current));
224881907739SOleg Nesterov 
22491c4042c2SEric W. Biederman 			if (is_child_reaper(pid)) {
225017cf22c3SEric W. Biederman 				ns_of_pid(pid)->child_reaper = p;
22511c4042c2SEric W. Biederman 				p->signal->flags |= SIGNAL_UNKILLABLE;
22521c4042c2SEric W. Biederman 			}
2253c3ad2c3bSEric W. Biederman 			p->signal->shared_pending.signal = delayed.signal;
22549c9f4dedSAlan Cox 			p->signal->tty = tty_kref_get(current->signal->tty);
2255749860ceSPavel Tikhomirov 			/*
2256749860ceSPavel Tikhomirov 			 * Inherit has_child_subreaper flag under the same
2257749860ceSPavel Tikhomirov 			 * tasklist_lock with adding child to the process tree
2258749860ceSPavel Tikhomirov 			 * for propagate_has_child_subreaper optimization.
2259749860ceSPavel Tikhomirov 			 */
2260749860ceSPavel Tikhomirov 			p->signal->has_child_subreaper = p->real_parent->signal->has_child_subreaper ||
2261749860ceSPavel Tikhomirov 							 p->real_parent->signal->is_child_subreaper;
22629cd80bbbSOleg Nesterov 			list_add_tail(&p->sibling, &p->real_parent->children);
22635e85d4abSEric W. Biederman 			list_add_tail_rcu(&p->tasks, &init_task.tasks);
22646883f81aSEric W. Biederman 			attach_pid(p, PIDTYPE_TGID);
226581907739SOleg Nesterov 			attach_pid(p, PIDTYPE_PGID);
226681907739SOleg Nesterov 			attach_pid(p, PIDTYPE_SID);
2267909ea964SChristoph Lameter 			__this_cpu_inc(process_counts);
226880628ca0SOleg Nesterov 		} else {
226980628ca0SOleg Nesterov 			current->signal->nr_threads++;
227080628ca0SOleg Nesterov 			atomic_inc(&current->signal->live);
227160d4de3fSElena Reshetova 			refcount_inc(&current->signal->sigcnt);
2272924de3b8SEric W. Biederman 			task_join_group_stop(p);
227380628ca0SOleg Nesterov 			list_add_tail_rcu(&p->thread_group,
227480628ca0SOleg Nesterov 					  &p->group_leader->thread_group);
22750c740d0aSOleg Nesterov 			list_add_tail_rcu(&p->thread_node,
22760c740d0aSOleg Nesterov 					  &p->signal->thread_head);
22771da177e4SLinus Torvalds 		}
227881907739SOleg Nesterov 		attach_pid(p, PIDTYPE_PID);
22791da177e4SLinus Torvalds 		nr_threads++;
228073b9ebfeSOleg Nesterov 	}
22811da177e4SLinus Torvalds 	total_forks++;
2282c3ad2c3bSEric W. Biederman 	hlist_del_init(&delayed.node);
22833f17da69SOleg Nesterov 	spin_unlock(&current->sighand->siglock);
22844af4206bSOleg Nesterov 	syscall_tracepoint_update(p);
22851da177e4SLinus Torvalds 	write_unlock_irq(&tasklist_lock);
22864af4206bSOleg Nesterov 
2287c13cf856SAndrew Morton 	proc_fork_connector(p);
2288b53202e6SOleg Nesterov 	cgroup_post_fork(p);
2289780de9ddSIngo Molnar 	cgroup_threadgroup_change_end(current);
2290cdd6c482SIngo Molnar 	perf_event_fork(p);
229143d2b113SKAMEZAWA Hiroyuki 
229243d2b113SKAMEZAWA Hiroyuki 	trace_task_newtask(p, clone_flags);
22933ab67966SOleg Nesterov 	uprobe_copy_process(p, clone_flags);
229443d2b113SKAMEZAWA Hiroyuki 
22951da177e4SLinus Torvalds 	return p;
22961da177e4SLinus Torvalds 
22977e47682eSAleksa Sarai bad_fork_cancel_cgroup:
22983fd37226SKirill Tkhai 	spin_unlock(&current->sighand->siglock);
22993fd37226SKirill Tkhai 	write_unlock_irq(&tasklist_lock);
2300b53202e6SOleg Nesterov 	cgroup_cancel_fork(p);
2301c3b7112dSChristian Brauner bad_fork_cgroup_threadgroup_change_end:
2302c3b7112dSChristian Brauner 	cgroup_threadgroup_change_end(current);
2303b3e58382SChristian Brauner bad_fork_put_pidfd:
23046fd2fe49SAl Viro 	if (clone_flags & CLONE_PIDFD) {
23056fd2fe49SAl Viro 		fput(pidfile);
23066fd2fe49SAl Viro 		put_unused_fd(pidfd);
23076fd2fe49SAl Viro 	}
2308425fb2b4SPavel Emelyanov bad_fork_free_pid:
2309425fb2b4SPavel Emelyanov 	if (pid != &init_struct_pid)
2310425fb2b4SPavel Emelyanov 		free_pid(pid);
23110740aa5fSJiri Slaby bad_fork_cleanup_thread:
23120740aa5fSJiri Slaby 	exit_thread(p);
2313fd0928dfSJens Axboe bad_fork_cleanup_io:
2314b69f2292SLouis Rilling 	if (p->io_context)
2315b69f2292SLouis Rilling 		exit_io_context(p);
2316ab516013SSerge E. Hallyn bad_fork_cleanup_namespaces:
2317444f378bSLinus Torvalds 	exit_task_namespaces(p);
23181da177e4SLinus Torvalds bad_fork_cleanup_mm:
2319c3f3ce04SAndrea Arcangeli 	if (p->mm) {
2320c3f3ce04SAndrea Arcangeli 		mm_clear_owner(p->mm, p);
23211da177e4SLinus Torvalds 		mmput(p->mm);
2322c3f3ce04SAndrea Arcangeli 	}
23231da177e4SLinus Torvalds bad_fork_cleanup_signal:
23244ab6c083SOleg Nesterov 	if (!(clone_flags & CLONE_THREAD))
23251c5354deSMike Galbraith 		free_signal_struct(p->signal);
23261da177e4SLinus Torvalds bad_fork_cleanup_sighand:
2327a7e5328aSOleg Nesterov 	__cleanup_sighand(p->sighand);
23281da177e4SLinus Torvalds bad_fork_cleanup_fs:
23291da177e4SLinus Torvalds 	exit_fs(p); /* blocking */
23301da177e4SLinus Torvalds bad_fork_cleanup_files:
23311da177e4SLinus Torvalds 	exit_files(p); /* blocking */
23321da177e4SLinus Torvalds bad_fork_cleanup_semundo:
23331da177e4SLinus Torvalds 	exit_sem(p);
2334e4e55b47STetsuo Handa bad_fork_cleanup_security:
2335e4e55b47STetsuo Handa 	security_task_free(p);
23361da177e4SLinus Torvalds bad_fork_cleanup_audit:
23371da177e4SLinus Torvalds 	audit_free(p);
23386c72e350SPeter Zijlstra bad_fork_cleanup_perf:
2339cdd6c482SIngo Molnar 	perf_event_free_task(p);
23406c72e350SPeter Zijlstra bad_fork_cleanup_policy:
2341b09be676SByungchul Park 	lockdep_free_task(p);
23421da177e4SLinus Torvalds #ifdef CONFIG_NUMA
2343f0be3d32SLee Schermerhorn 	mpol_put(p->mempolicy);
2344e8604cb4SLi Zefan bad_fork_cleanup_threadgroup_lock:
23451da177e4SLinus Torvalds #endif
234635df17c5SShailabh Nagar 	delayacct_tsk_free(p);
23471da177e4SLinus Torvalds bad_fork_cleanup_count:
2348d84f4f99SDavid Howells 	atomic_dec(&p->cred->user->processes);
2349e0e81739SDavid Howells 	exit_creds(p);
23501da177e4SLinus Torvalds bad_fork_free:
2351405c0759SAndy Lutomirski 	p->state = TASK_DEAD;
235268f24b08SAndy Lutomirski 	put_task_stack(p);
2353c3f3ce04SAndrea Arcangeli 	delayed_free_task(p);
2354fe7d37d1SOleg Nesterov fork_out:
2355c3ad2c3bSEric W. Biederman 	spin_lock_irq(&current->sighand->siglock);
2356c3ad2c3bSEric W. Biederman 	hlist_del_init(&delayed.node);
2357c3ad2c3bSEric W. Biederman 	spin_unlock_irq(&current->sighand->siglock);
2358fe7d37d1SOleg Nesterov 	return ERR_PTR(retval);
23591da177e4SLinus Torvalds }
23601da177e4SLinus Torvalds 
23612c470475SEric W. Biederman static inline void init_idle_pids(struct task_struct *idle)
2362f106eee1SOleg Nesterov {
2363f106eee1SOleg Nesterov 	enum pid_type type;
2364f106eee1SOleg Nesterov 
2365f106eee1SOleg Nesterov 	for (type = PIDTYPE_PID; type < PIDTYPE_MAX; ++type) {
23662c470475SEric W. Biederman 		INIT_HLIST_NODE(&idle->pid_links[type]); /* not really needed */
23672c470475SEric W. Biederman 		init_task_pid(idle, type, &init_struct_pid);
2368f106eee1SOleg Nesterov 	}
2369f106eee1SOleg Nesterov }
2370f106eee1SOleg Nesterov 
23710db0628dSPaul Gortmaker struct task_struct *fork_idle(int cpu)
23721da177e4SLinus Torvalds {
237336c8b586SIngo Molnar 	struct task_struct *task;
23747f192e3cSChristian Brauner 	struct kernel_clone_args args = {
23757f192e3cSChristian Brauner 		.flags = CLONE_VM,
23767f192e3cSChristian Brauner 	};
23777f192e3cSChristian Brauner 
23787f192e3cSChristian Brauner 	task = copy_process(&init_struct_pid, 0, cpu_to_node(cpu), &args);
2379f106eee1SOleg Nesterov 	if (!IS_ERR(task)) {
23802c470475SEric W. Biederman 		init_idle_pids(task);
23811da177e4SLinus Torvalds 		init_idle(task, cpu);
2382f106eee1SOleg Nesterov 	}
238373b9ebfeSOleg Nesterov 
23841da177e4SLinus Torvalds 	return task;
23851da177e4SLinus Torvalds }
23861da177e4SLinus Torvalds 
238713585fa0SNadav Amit struct mm_struct *copy_init_mm(void)
238813585fa0SNadav Amit {
238913585fa0SNadav Amit 	return dup_mm(NULL, &init_mm);
239013585fa0SNadav Amit }
239113585fa0SNadav Amit 
23921da177e4SLinus Torvalds /*
23931da177e4SLinus Torvalds  *  Ok, this is the main fork-routine.
23941da177e4SLinus Torvalds  *
23951da177e4SLinus Torvalds  * It copies the process, and if successful kick-starts
23961da177e4SLinus Torvalds  * it and waits for it to finish using the VM if required.
2397a0eb9abdSEugene Syromiatnikov  *
2398a0eb9abdSEugene Syromiatnikov  * args->exit_signal is expected to be checked for sanity by the caller.
23991da177e4SLinus Torvalds  */
24007f192e3cSChristian Brauner long _do_fork(struct kernel_clone_args *args)
24011da177e4SLinus Torvalds {
24027f192e3cSChristian Brauner 	u64 clone_flags = args->flags;
24039f5325aaSMarcos Paulo de Souza 	struct completion vfork;
24049f5325aaSMarcos Paulo de Souza 	struct pid *pid;
24051da177e4SLinus Torvalds 	struct task_struct *p;
24061da177e4SLinus Torvalds 	int trace = 0;
240792476d7fSEric W. Biederman 	long nr;
24081da177e4SLinus Torvalds 
2409bdff746aSAndrew Morton 	/*
24104b9d33e6STejun Heo 	 * Determine whether and which event to report to ptracer.  When
24114b9d33e6STejun Heo 	 * called from kernel_thread or CLONE_UNTRACED is explicitly
24124b9d33e6STejun Heo 	 * requested, no event is reported; otherwise, report if the event
24134b9d33e6STejun Heo 	 * for the type of forking is enabled.
241409a05394SRoland McGrath 	 */
2415e80d6661SAl Viro 	if (!(clone_flags & CLONE_UNTRACED)) {
24164b9d33e6STejun Heo 		if (clone_flags & CLONE_VFORK)
24174b9d33e6STejun Heo 			trace = PTRACE_EVENT_VFORK;
24187f192e3cSChristian Brauner 		else if (args->exit_signal != SIGCHLD)
24194b9d33e6STejun Heo 			trace = PTRACE_EVENT_CLONE;
24204b9d33e6STejun Heo 		else
24214b9d33e6STejun Heo 			trace = PTRACE_EVENT_FORK;
24224b9d33e6STejun Heo 
24234b9d33e6STejun Heo 		if (likely(!ptrace_event_enabled(current, trace)))
24244b9d33e6STejun Heo 			trace = 0;
24254b9d33e6STejun Heo 	}
24261da177e4SLinus Torvalds 
24277f192e3cSChristian Brauner 	p = copy_process(NULL, trace, NUMA_NO_NODE, args);
242838addce8SEmese Revfy 	add_latent_entropy();
24299f5325aaSMarcos Paulo de Souza 
24309f5325aaSMarcos Paulo de Souza 	if (IS_ERR(p))
24319f5325aaSMarcos Paulo de Souza 		return PTR_ERR(p);
24329f5325aaSMarcos Paulo de Souza 
24331da177e4SLinus Torvalds 	/*
24341da177e4SLinus Torvalds 	 * Do this prior waking up the new thread - the thread pointer
24351da177e4SLinus Torvalds 	 * might get invalid after that point, if the thread exits quickly.
24361da177e4SLinus Torvalds 	 */
24370a16b607SMathieu Desnoyers 	trace_sched_process_fork(current, p);
24380a16b607SMathieu Desnoyers 
24394e52365fSMatthew Dempsky 	pid = get_task_pid(p, PIDTYPE_PID);
24404e52365fSMatthew Dempsky 	nr = pid_vnr(pid);
244130e49c26SPavel Emelyanov 
244230e49c26SPavel Emelyanov 	if (clone_flags & CLONE_PARENT_SETTID)
24437f192e3cSChristian Brauner 		put_user(nr, args->parent_tid);
2444a6f5e063SSukadev Bhattiprolu 
24451da177e4SLinus Torvalds 	if (clone_flags & CLONE_VFORK) {
24461da177e4SLinus Torvalds 		p->vfork_done = &vfork;
24471da177e4SLinus Torvalds 		init_completion(&vfork);
2448d68b46feSOleg Nesterov 		get_task_struct(p);
24491da177e4SLinus Torvalds 	}
24501da177e4SLinus Torvalds 
24513e51e3edSSamir Bellabes 	wake_up_new_task(p);
24521da177e4SLinus Torvalds 
24534b9d33e6STejun Heo 	/* forking complete and child started to run, tell ptracer */
24544b9d33e6STejun Heo 	if (unlikely(trace))
24554e52365fSMatthew Dempsky 		ptrace_event_pid(trace, pid);
245609a05394SRoland McGrath 
24571da177e4SLinus Torvalds 	if (clone_flags & CLONE_VFORK) {
2458d68b46feSOleg Nesterov 		if (!wait_for_vfork_done(p, &vfork))
24594e52365fSMatthew Dempsky 			ptrace_event_pid(PTRACE_EVENT_VFORK_DONE, pid);
24609f59ce5dSChuck Ebbert 	}
24614e52365fSMatthew Dempsky 
24624e52365fSMatthew Dempsky 	put_pid(pid);
246392476d7fSEric W. Biederman 	return nr;
24641da177e4SLinus Torvalds }
24651da177e4SLinus Torvalds 
2466028b6e8aSDmitry V. Levin bool legacy_clone_args_valid(const struct kernel_clone_args *kargs)
2467028b6e8aSDmitry V. Levin {
2468028b6e8aSDmitry V. Levin 	/* clone(CLONE_PIDFD) uses parent_tidptr to return a pidfd */
2469028b6e8aSDmitry V. Levin 	if ((kargs->flags & CLONE_PIDFD) &&
2470028b6e8aSDmitry V. Levin 	    (kargs->flags & CLONE_PARENT_SETTID))
2471028b6e8aSDmitry V. Levin 		return false;
2472028b6e8aSDmitry V. Levin 
2473028b6e8aSDmitry V. Levin 	return true;
2474028b6e8aSDmitry V. Levin }
2475028b6e8aSDmitry V. Levin 
24763033f14aSJosh Triplett #ifndef CONFIG_HAVE_COPY_THREAD_TLS
24773033f14aSJosh Triplett /* For compatibility with architectures that call do_fork directly rather than
24783033f14aSJosh Triplett  * using the syscall entry points below. */
24793033f14aSJosh Triplett long do_fork(unsigned long clone_flags,
24803033f14aSJosh Triplett 	      unsigned long stack_start,
24813033f14aSJosh Triplett 	      unsigned long stack_size,
24823033f14aSJosh Triplett 	      int __user *parent_tidptr,
24833033f14aSJosh Triplett 	      int __user *child_tidptr)
24843033f14aSJosh Triplett {
24857f192e3cSChristian Brauner 	struct kernel_clone_args args = {
24867f192e3cSChristian Brauner 		.flags		= (clone_flags & ~CSIGNAL),
2487028b6e8aSDmitry V. Levin 		.pidfd		= parent_tidptr,
24887f192e3cSChristian Brauner 		.child_tid	= child_tidptr,
24897f192e3cSChristian Brauner 		.parent_tid	= parent_tidptr,
24907f192e3cSChristian Brauner 		.exit_signal	= (clone_flags & CSIGNAL),
24917f192e3cSChristian Brauner 		.stack		= stack_start,
24927f192e3cSChristian Brauner 		.stack_size	= stack_size,
24937f192e3cSChristian Brauner 	};
24947f192e3cSChristian Brauner 
2495028b6e8aSDmitry V. Levin 	if (!legacy_clone_args_valid(&args))
2496028b6e8aSDmitry V. Levin 		return -EINVAL;
2497028b6e8aSDmitry V. Levin 
24987f192e3cSChristian Brauner 	return _do_fork(&args);
24993033f14aSJosh Triplett }
25003033f14aSJosh Triplett #endif
25013033f14aSJosh Triplett 
25022aa3a7f8SAl Viro /*
25032aa3a7f8SAl Viro  * Create a kernel thread.
25042aa3a7f8SAl Viro  */
25052aa3a7f8SAl Viro pid_t kernel_thread(int (*fn)(void *), void *arg, unsigned long flags)
25062aa3a7f8SAl Viro {
25077f192e3cSChristian Brauner 	struct kernel_clone_args args = {
25087f192e3cSChristian Brauner 		.flags		= ((flags | CLONE_VM | CLONE_UNTRACED) & ~CSIGNAL),
25097f192e3cSChristian Brauner 		.exit_signal	= (flags & CSIGNAL),
25107f192e3cSChristian Brauner 		.stack		= (unsigned long)fn,
25117f192e3cSChristian Brauner 		.stack_size	= (unsigned long)arg,
25127f192e3cSChristian Brauner 	};
25137f192e3cSChristian Brauner 
25147f192e3cSChristian Brauner 	return _do_fork(&args);
25152aa3a7f8SAl Viro }
25162aa3a7f8SAl Viro 
2517d2125043SAl Viro #ifdef __ARCH_WANT_SYS_FORK
2518d2125043SAl Viro SYSCALL_DEFINE0(fork)
2519d2125043SAl Viro {
2520d2125043SAl Viro #ifdef CONFIG_MMU
25217f192e3cSChristian Brauner 	struct kernel_clone_args args = {
25227f192e3cSChristian Brauner 		.exit_signal = SIGCHLD,
25237f192e3cSChristian Brauner 	};
25247f192e3cSChristian Brauner 
25257f192e3cSChristian Brauner 	return _do_fork(&args);
2526d2125043SAl Viro #else
2527d2125043SAl Viro 	/* can not support in nommu mode */
25285d59e182SDaeseok Youn 	return -EINVAL;
2529d2125043SAl Viro #endif
2530d2125043SAl Viro }
2531d2125043SAl Viro #endif
2532d2125043SAl Viro 
2533d2125043SAl Viro #ifdef __ARCH_WANT_SYS_VFORK
2534d2125043SAl Viro SYSCALL_DEFINE0(vfork)
2535d2125043SAl Viro {
25367f192e3cSChristian Brauner 	struct kernel_clone_args args = {
25377f192e3cSChristian Brauner 		.flags		= CLONE_VFORK | CLONE_VM,
25387f192e3cSChristian Brauner 		.exit_signal	= SIGCHLD,
25397f192e3cSChristian Brauner 	};
25407f192e3cSChristian Brauner 
25417f192e3cSChristian Brauner 	return _do_fork(&args);
2542d2125043SAl Viro }
2543d2125043SAl Viro #endif
2544d2125043SAl Viro 
2545d2125043SAl Viro #ifdef __ARCH_WANT_SYS_CLONE
2546d2125043SAl Viro #ifdef CONFIG_CLONE_BACKWARDS
2547d2125043SAl Viro SYSCALL_DEFINE5(clone, unsigned long, clone_flags, unsigned long, newsp,
2548d2125043SAl Viro 		 int __user *, parent_tidptr,
25493033f14aSJosh Triplett 		 unsigned long, tls,
2550d2125043SAl Viro 		 int __user *, child_tidptr)
2551d2125043SAl Viro #elif defined(CONFIG_CLONE_BACKWARDS2)
2552d2125043SAl Viro SYSCALL_DEFINE5(clone, unsigned long, newsp, unsigned long, clone_flags,
2553d2125043SAl Viro 		 int __user *, parent_tidptr,
2554d2125043SAl Viro 		 int __user *, child_tidptr,
25553033f14aSJosh Triplett 		 unsigned long, tls)
2556dfa9771aSMichal Simek #elif defined(CONFIG_CLONE_BACKWARDS3)
2557dfa9771aSMichal Simek SYSCALL_DEFINE6(clone, unsigned long, clone_flags, unsigned long, newsp,
2558dfa9771aSMichal Simek 		int, stack_size,
2559dfa9771aSMichal Simek 		int __user *, parent_tidptr,
2560dfa9771aSMichal Simek 		int __user *, child_tidptr,
25613033f14aSJosh Triplett 		unsigned long, tls)
2562d2125043SAl Viro #else
2563d2125043SAl Viro SYSCALL_DEFINE5(clone, unsigned long, clone_flags, unsigned long, newsp,
2564d2125043SAl Viro 		 int __user *, parent_tidptr,
2565d2125043SAl Viro 		 int __user *, child_tidptr,
25663033f14aSJosh Triplett 		 unsigned long, tls)
2567d2125043SAl Viro #endif
2568d2125043SAl Viro {
25697f192e3cSChristian Brauner 	struct kernel_clone_args args = {
25707f192e3cSChristian Brauner 		.flags		= (clone_flags & ~CSIGNAL),
25717f192e3cSChristian Brauner 		.pidfd		= parent_tidptr,
25727f192e3cSChristian Brauner 		.child_tid	= child_tidptr,
25737f192e3cSChristian Brauner 		.parent_tid	= parent_tidptr,
25747f192e3cSChristian Brauner 		.exit_signal	= (clone_flags & CSIGNAL),
25757f192e3cSChristian Brauner 		.stack		= newsp,
25767f192e3cSChristian Brauner 		.tls		= tls,
25777f192e3cSChristian Brauner 	};
25787f192e3cSChristian Brauner 
2579028b6e8aSDmitry V. Levin 	if (!legacy_clone_args_valid(&args))
25807f192e3cSChristian Brauner 		return -EINVAL;
25817f192e3cSChristian Brauner 
25827f192e3cSChristian Brauner 	return _do_fork(&args);
25837f192e3cSChristian Brauner }
2584d68dbb0cSChristian Brauner #endif
25857f192e3cSChristian Brauner 
2586d68dbb0cSChristian Brauner #ifdef __ARCH_WANT_SYS_CLONE3
25877f192e3cSChristian Brauner noinline static int copy_clone_args_from_user(struct kernel_clone_args *kargs,
25887f192e3cSChristian Brauner 					      struct clone_args __user *uargs,
2589f14c234bSAleksa Sarai 					      size_t usize)
25907f192e3cSChristian Brauner {
2591f14c234bSAleksa Sarai 	int err;
25927f192e3cSChristian Brauner 	struct clone_args args;
25937f192e3cSChristian Brauner 
2594f14c234bSAleksa Sarai 	if (unlikely(usize > PAGE_SIZE))
25957f192e3cSChristian Brauner 		return -E2BIG;
2596f14c234bSAleksa Sarai 	if (unlikely(usize < CLONE_ARGS_SIZE_VER0))
25977f192e3cSChristian Brauner 		return -EINVAL;
25987f192e3cSChristian Brauner 
2599f14c234bSAleksa Sarai 	err = copy_struct_from_user(&args, sizeof(args), uargs, usize);
2600f14c234bSAleksa Sarai 	if (err)
2601f14c234bSAleksa Sarai 		return err;
26027f192e3cSChristian Brauner 
2603a0eb9abdSEugene Syromiatnikov 	/*
2604a0eb9abdSEugene Syromiatnikov 	 * Verify that higher 32bits of exit_signal are unset and that
2605a0eb9abdSEugene Syromiatnikov 	 * it is a valid signal
2606a0eb9abdSEugene Syromiatnikov 	 */
2607a0eb9abdSEugene Syromiatnikov 	if (unlikely((args.exit_signal & ~((u64)CSIGNAL)) ||
2608a0eb9abdSEugene Syromiatnikov 		     !valid_signal(args.exit_signal)))
2609a0eb9abdSEugene Syromiatnikov 		return -EINVAL;
2610a0eb9abdSEugene Syromiatnikov 
26117f192e3cSChristian Brauner 	*kargs = (struct kernel_clone_args){
26127f192e3cSChristian Brauner 		.flags		= args.flags,
26137f192e3cSChristian Brauner 		.pidfd		= u64_to_user_ptr(args.pidfd),
26147f192e3cSChristian Brauner 		.child_tid	= u64_to_user_ptr(args.child_tid),
26157f192e3cSChristian Brauner 		.parent_tid	= u64_to_user_ptr(args.parent_tid),
26167f192e3cSChristian Brauner 		.exit_signal	= args.exit_signal,
26177f192e3cSChristian Brauner 		.stack		= args.stack,
26187f192e3cSChristian Brauner 		.stack_size	= args.stack_size,
26197f192e3cSChristian Brauner 		.tls		= args.tls,
26207f192e3cSChristian Brauner 	};
26217f192e3cSChristian Brauner 
26227f192e3cSChristian Brauner 	return 0;
26237f192e3cSChristian Brauner }
26247f192e3cSChristian Brauner 
26257f192e3cSChristian Brauner static bool clone3_args_valid(const struct kernel_clone_args *kargs)
26267f192e3cSChristian Brauner {
2627*b612e5dfSChristian Brauner 	/* Verify that no unknown flags are passed along. */
2628*b612e5dfSChristian Brauner 	if (kargs->flags & ~(CLONE_LEGACY_FLAGS | CLONE_CLEAR_SIGHAND))
26297f192e3cSChristian Brauner 		return false;
26307f192e3cSChristian Brauner 
26317f192e3cSChristian Brauner 	/*
26327f192e3cSChristian Brauner 	 * - make the CLONE_DETACHED bit reuseable for clone3
26337f192e3cSChristian Brauner 	 * - make the CSIGNAL bits reuseable for clone3
26347f192e3cSChristian Brauner 	 */
26357f192e3cSChristian Brauner 	if (kargs->flags & (CLONE_DETACHED | CSIGNAL))
26367f192e3cSChristian Brauner 		return false;
26377f192e3cSChristian Brauner 
2638*b612e5dfSChristian Brauner 	if ((kargs->flags & (CLONE_SIGHAND | CLONE_CLEAR_SIGHAND)) ==
2639*b612e5dfSChristian Brauner 	    (CLONE_SIGHAND | CLONE_CLEAR_SIGHAND))
2640*b612e5dfSChristian Brauner 		return false;
2641*b612e5dfSChristian Brauner 
26427f192e3cSChristian Brauner 	if ((kargs->flags & (CLONE_THREAD | CLONE_PARENT)) &&
26437f192e3cSChristian Brauner 	    kargs->exit_signal)
26447f192e3cSChristian Brauner 		return false;
26457f192e3cSChristian Brauner 
26467f192e3cSChristian Brauner 	return true;
26477f192e3cSChristian Brauner }
26487f192e3cSChristian Brauner 
2649501bd016SChristian Brauner /**
2650501bd016SChristian Brauner  * clone3 - create a new process with specific properties
2651501bd016SChristian Brauner  * @uargs: argument structure
2652501bd016SChristian Brauner  * @size:  size of @uargs
2653501bd016SChristian Brauner  *
2654501bd016SChristian Brauner  * clone3() is the extensible successor to clone()/clone2().
2655501bd016SChristian Brauner  * It takes a struct as argument that is versioned by its size.
2656501bd016SChristian Brauner  *
2657501bd016SChristian Brauner  * Return: On success, a positive PID for the child process.
2658501bd016SChristian Brauner  *         On error, a negative errno number.
2659501bd016SChristian Brauner  */
26607f192e3cSChristian Brauner SYSCALL_DEFINE2(clone3, struct clone_args __user *, uargs, size_t, size)
26617f192e3cSChristian Brauner {
26627f192e3cSChristian Brauner 	int err;
26637f192e3cSChristian Brauner 
26647f192e3cSChristian Brauner 	struct kernel_clone_args kargs;
26657f192e3cSChristian Brauner 
26667f192e3cSChristian Brauner 	err = copy_clone_args_from_user(&kargs, uargs, size);
26677f192e3cSChristian Brauner 	if (err)
26687f192e3cSChristian Brauner 		return err;
26697f192e3cSChristian Brauner 
26707f192e3cSChristian Brauner 	if (!clone3_args_valid(&kargs))
26717f192e3cSChristian Brauner 		return -EINVAL;
26727f192e3cSChristian Brauner 
26737f192e3cSChristian Brauner 	return _do_fork(&kargs);
2674d2125043SAl Viro }
2675d2125043SAl Viro #endif
2676d2125043SAl Viro 
26770f1b92cbSOleg Nesterov void walk_process_tree(struct task_struct *top, proc_visitor visitor, void *data)
26780f1b92cbSOleg Nesterov {
26790f1b92cbSOleg Nesterov 	struct task_struct *leader, *parent, *child;
26800f1b92cbSOleg Nesterov 	int res;
26810f1b92cbSOleg Nesterov 
26820f1b92cbSOleg Nesterov 	read_lock(&tasklist_lock);
26830f1b92cbSOleg Nesterov 	leader = top = top->group_leader;
26840f1b92cbSOleg Nesterov down:
26850f1b92cbSOleg Nesterov 	for_each_thread(leader, parent) {
26860f1b92cbSOleg Nesterov 		list_for_each_entry(child, &parent->children, sibling) {
26870f1b92cbSOleg Nesterov 			res = visitor(child, data);
26880f1b92cbSOleg Nesterov 			if (res) {
26890f1b92cbSOleg Nesterov 				if (res < 0)
26900f1b92cbSOleg Nesterov 					goto out;
26910f1b92cbSOleg Nesterov 				leader = child;
26920f1b92cbSOleg Nesterov 				goto down;
26930f1b92cbSOleg Nesterov 			}
26940f1b92cbSOleg Nesterov up:
26950f1b92cbSOleg Nesterov 			;
26960f1b92cbSOleg Nesterov 		}
26970f1b92cbSOleg Nesterov 	}
26980f1b92cbSOleg Nesterov 
26990f1b92cbSOleg Nesterov 	if (leader != top) {
27000f1b92cbSOleg Nesterov 		child = leader;
27010f1b92cbSOleg Nesterov 		parent = child->real_parent;
27020f1b92cbSOleg Nesterov 		leader = parent->group_leader;
27030f1b92cbSOleg Nesterov 		goto up;
27040f1b92cbSOleg Nesterov 	}
27050f1b92cbSOleg Nesterov out:
27060f1b92cbSOleg Nesterov 	read_unlock(&tasklist_lock);
27070f1b92cbSOleg Nesterov }
27080f1b92cbSOleg Nesterov 
27095fd63b30SRavikiran G Thirumalai #ifndef ARCH_MIN_MMSTRUCT_ALIGN
27105fd63b30SRavikiran G Thirumalai #define ARCH_MIN_MMSTRUCT_ALIGN 0
27115fd63b30SRavikiran G Thirumalai #endif
27125fd63b30SRavikiran G Thirumalai 
271351cc5068SAlexey Dobriyan static void sighand_ctor(void *data)
2714aa1757f9SOleg Nesterov {
2715aa1757f9SOleg Nesterov 	struct sighand_struct *sighand = data;
2716aa1757f9SOleg Nesterov 
2717aa1757f9SOleg Nesterov 	spin_lock_init(&sighand->siglock);
2718b8fceee1SDavide Libenzi 	init_waitqueue_head(&sighand->signalfd_wqh);
2719fba2afaaSDavide Libenzi }
2720aa1757f9SOleg Nesterov 
27211da177e4SLinus Torvalds void __init proc_caches_init(void)
27221da177e4SLinus Torvalds {
2723c1a2f7f0SRik van Riel 	unsigned int mm_size;
2724c1a2f7f0SRik van Riel 
27251da177e4SLinus Torvalds 	sighand_cachep = kmem_cache_create("sighand_cache",
27261da177e4SLinus Torvalds 			sizeof(struct sighand_struct), 0,
27275f0d5a3aSPaul E. McKenney 			SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_TYPESAFE_BY_RCU|
272875f296d9SLevin, Alexander (Sasha Levin) 			SLAB_ACCOUNT, sighand_ctor);
27291da177e4SLinus Torvalds 	signal_cachep = kmem_cache_create("signal_cache",
27301da177e4SLinus Torvalds 			sizeof(struct signal_struct), 0,
273175f296d9SLevin, Alexander (Sasha Levin) 			SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_ACCOUNT,
27325d097056SVladimir Davydov 			NULL);
27331da177e4SLinus Torvalds 	files_cachep = kmem_cache_create("files_cache",
27341da177e4SLinus Torvalds 			sizeof(struct files_struct), 0,
273575f296d9SLevin, Alexander (Sasha Levin) 			SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_ACCOUNT,
27365d097056SVladimir Davydov 			NULL);
27371da177e4SLinus Torvalds 	fs_cachep = kmem_cache_create("fs_cache",
27381da177e4SLinus Torvalds 			sizeof(struct fs_struct), 0,
273975f296d9SLevin, Alexander (Sasha Levin) 			SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_ACCOUNT,
27405d097056SVladimir Davydov 			NULL);
2741c1a2f7f0SRik van Riel 
27426345d24dSLinus Torvalds 	/*
2743c1a2f7f0SRik van Riel 	 * The mm_cpumask is located at the end of mm_struct, and is
2744c1a2f7f0SRik van Riel 	 * dynamically sized based on the maximum CPU number this system
2745c1a2f7f0SRik van Riel 	 * can have, taking hotplug into account (nr_cpu_ids).
27466345d24dSLinus Torvalds 	 */
2747c1a2f7f0SRik van Riel 	mm_size = sizeof(struct mm_struct) + cpumask_size();
2748c1a2f7f0SRik van Riel 
274907dcd7feSDavid Windsor 	mm_cachep = kmem_cache_create_usercopy("mm_struct",
2750c1a2f7f0SRik van Riel 			mm_size, ARCH_MIN_MMSTRUCT_ALIGN,
275175f296d9SLevin, Alexander (Sasha Levin) 			SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_ACCOUNT,
275207dcd7feSDavid Windsor 			offsetof(struct mm_struct, saved_auxv),
275307dcd7feSDavid Windsor 			sizeof_field(struct mm_struct, saved_auxv),
27545d097056SVladimir Davydov 			NULL);
27555d097056SVladimir Davydov 	vm_area_cachep = KMEM_CACHE(vm_area_struct, SLAB_PANIC|SLAB_ACCOUNT);
27568feae131SDavid Howells 	mmap_init();
275766577193SAl Viro 	nsproxy_cache_init();
27581da177e4SLinus Torvalds }
2759cf2e340fSJANAK DESAI 
2760cf2e340fSJANAK DESAI /*
27619bfb23fcSOleg Nesterov  * Check constraints on flags passed to the unshare system call.
2762cf2e340fSJANAK DESAI  */
27639bfb23fcSOleg Nesterov static int check_unshare_flags(unsigned long unshare_flags)
2764cf2e340fSJANAK DESAI {
27659bfb23fcSOleg Nesterov 	if (unshare_flags & ~(CLONE_THREAD|CLONE_FS|CLONE_NEWNS|CLONE_SIGHAND|
27669bfb23fcSOleg Nesterov 				CLONE_VM|CLONE_FILES|CLONE_SYSVSEM|
276750804fe3SEric W. Biederman 				CLONE_NEWUTS|CLONE_NEWIPC|CLONE_NEWNET|
2768a79a908fSAditya Kali 				CLONE_NEWUSER|CLONE_NEWPID|CLONE_NEWCGROUP))
2769cf2e340fSJANAK DESAI 		return -EINVAL;
27709bfb23fcSOleg Nesterov 	/*
277112c641abSEric W. Biederman 	 * Not implemented, but pretend it works if there is nothing
277212c641abSEric W. Biederman 	 * to unshare.  Note that unsharing the address space or the
277312c641abSEric W. Biederman 	 * signal handlers also need to unshare the signal queues (aka
277412c641abSEric W. Biederman 	 * CLONE_THREAD).
27759bfb23fcSOleg Nesterov 	 */
27769bfb23fcSOleg Nesterov 	if (unshare_flags & (CLONE_THREAD | CLONE_SIGHAND | CLONE_VM)) {
277712c641abSEric W. Biederman 		if (!thread_group_empty(current))
277812c641abSEric W. Biederman 			return -EINVAL;
277912c641abSEric W. Biederman 	}
278012c641abSEric W. Biederman 	if (unshare_flags & (CLONE_SIGHAND | CLONE_VM)) {
2781d036bda7SElena Reshetova 		if (refcount_read(&current->sighand->count) > 1)
278212c641abSEric W. Biederman 			return -EINVAL;
278312c641abSEric W. Biederman 	}
278412c641abSEric W. Biederman 	if (unshare_flags & CLONE_VM) {
278512c641abSEric W. Biederman 		if (!current_is_single_threaded())
27869bfb23fcSOleg Nesterov 			return -EINVAL;
27879bfb23fcSOleg Nesterov 	}
2788cf2e340fSJANAK DESAI 
2789cf2e340fSJANAK DESAI 	return 0;
2790cf2e340fSJANAK DESAI }
2791cf2e340fSJANAK DESAI 
2792cf2e340fSJANAK DESAI /*
279399d1419dSJANAK DESAI  * Unshare the filesystem structure if it is being shared
2794cf2e340fSJANAK DESAI  */
2795cf2e340fSJANAK DESAI static int unshare_fs(unsigned long unshare_flags, struct fs_struct **new_fsp)
2796cf2e340fSJANAK DESAI {
2797cf2e340fSJANAK DESAI 	struct fs_struct *fs = current->fs;
2798cf2e340fSJANAK DESAI 
2799498052bbSAl Viro 	if (!(unshare_flags & CLONE_FS) || !fs)
2800498052bbSAl Viro 		return 0;
2801498052bbSAl Viro 
2802498052bbSAl Viro 	/* don't need lock here; in the worst case we'll do useless copy */
2803498052bbSAl Viro 	if (fs->users == 1)
2804498052bbSAl Viro 		return 0;
2805498052bbSAl Viro 
2806498052bbSAl Viro 	*new_fsp = copy_fs_struct(fs);
280799d1419dSJANAK DESAI 	if (!*new_fsp)
280899d1419dSJANAK DESAI 		return -ENOMEM;
2809cf2e340fSJANAK DESAI 
2810cf2e340fSJANAK DESAI 	return 0;
2811cf2e340fSJANAK DESAI }
2812cf2e340fSJANAK DESAI 
2813cf2e340fSJANAK DESAI /*
2814a016f338SJANAK DESAI  * Unshare file descriptor table if it is being shared
2815cf2e340fSJANAK DESAI  */
2816cf2e340fSJANAK DESAI static int unshare_fd(unsigned long unshare_flags, struct files_struct **new_fdp)
2817cf2e340fSJANAK DESAI {
2818cf2e340fSJANAK DESAI 	struct files_struct *fd = current->files;
2819a016f338SJANAK DESAI 	int error = 0;
2820cf2e340fSJANAK DESAI 
2821cf2e340fSJANAK DESAI 	if ((unshare_flags & CLONE_FILES) &&
2822a016f338SJANAK DESAI 	    (fd && atomic_read(&fd->count) > 1)) {
2823a016f338SJANAK DESAI 		*new_fdp = dup_fd(fd, &error);
2824a016f338SJANAK DESAI 		if (!*new_fdp)
2825a016f338SJANAK DESAI 			return error;
2826a016f338SJANAK DESAI 	}
2827cf2e340fSJANAK DESAI 
2828cf2e340fSJANAK DESAI 	return 0;
2829cf2e340fSJANAK DESAI }
2830cf2e340fSJANAK DESAI 
2831cf2e340fSJANAK DESAI /*
2832cf2e340fSJANAK DESAI  * unshare allows a process to 'unshare' part of the process
2833cf2e340fSJANAK DESAI  * context which was originally shared using clone.  copy_*
2834cf2e340fSJANAK DESAI  * functions used by do_fork() cannot be used here directly
2835cf2e340fSJANAK DESAI  * because they modify an inactive task_struct that is being
2836cf2e340fSJANAK DESAI  * constructed. Here we are modifying the current, active,
2837cf2e340fSJANAK DESAI  * task_struct.
2838cf2e340fSJANAK DESAI  */
28399b32105eSDominik Brodowski int ksys_unshare(unsigned long unshare_flags)
2840cf2e340fSJANAK DESAI {
2841cf2e340fSJANAK DESAI 	struct fs_struct *fs, *new_fs = NULL;
2842cf2e340fSJANAK DESAI 	struct files_struct *fd, *new_fd = NULL;
2843b2e0d987SEric W. Biederman 	struct cred *new_cred = NULL;
2844cf7b708cSPavel Emelyanov 	struct nsproxy *new_nsproxy = NULL;
28459edff4abSManfred Spraul 	int do_sysvsem = 0;
28469bfb23fcSOleg Nesterov 	int err;
2847cf2e340fSJANAK DESAI 
284850804fe3SEric W. Biederman 	/*
2849faf00da5SEric W. Biederman 	 * If unsharing a user namespace must also unshare the thread group
2850faf00da5SEric W. Biederman 	 * and unshare the filesystem root and working directories.
2851b2e0d987SEric W. Biederman 	 */
2852b2e0d987SEric W. Biederman 	if (unshare_flags & CLONE_NEWUSER)
2853e66eded8SEric W. Biederman 		unshare_flags |= CLONE_THREAD | CLONE_FS;
2854b2e0d987SEric W. Biederman 	/*
285550804fe3SEric W. Biederman 	 * If unsharing vm, must also unshare signal handlers.
285650804fe3SEric W. Biederman 	 */
285750804fe3SEric W. Biederman 	if (unshare_flags & CLONE_VM)
285850804fe3SEric W. Biederman 		unshare_flags |= CLONE_SIGHAND;
28596013f67fSManfred Spraul 	/*
286012c641abSEric W. Biederman 	 * If unsharing a signal handlers, must also unshare the signal queues.
286112c641abSEric W. Biederman 	 */
286212c641abSEric W. Biederman 	if (unshare_flags & CLONE_SIGHAND)
286312c641abSEric W. Biederman 		unshare_flags |= CLONE_THREAD;
286412c641abSEric W. Biederman 	/*
28659bfb23fcSOleg Nesterov 	 * If unsharing namespace, must also unshare filesystem information.
28669bfb23fcSOleg Nesterov 	 */
28679bfb23fcSOleg Nesterov 	if (unshare_flags & CLONE_NEWNS)
28689bfb23fcSOleg Nesterov 		unshare_flags |= CLONE_FS;
286950804fe3SEric W. Biederman 
287050804fe3SEric W. Biederman 	err = check_unshare_flags(unshare_flags);
287150804fe3SEric W. Biederman 	if (err)
287250804fe3SEric W. Biederman 		goto bad_unshare_out;
28739bfb23fcSOleg Nesterov 	/*
28746013f67fSManfred Spraul 	 * CLONE_NEWIPC must also detach from the undolist: after switching
28756013f67fSManfred Spraul 	 * to a new ipc namespace, the semaphore arrays from the old
28766013f67fSManfred Spraul 	 * namespace are unreachable.
28776013f67fSManfred Spraul 	 */
28786013f67fSManfred Spraul 	if (unshare_flags & (CLONE_NEWIPC|CLONE_SYSVSEM))
28799edff4abSManfred Spraul 		do_sysvsem = 1;
2880fb0a685cSDaniel Rebelo de Oliveira 	err = unshare_fs(unshare_flags, &new_fs);
2881fb0a685cSDaniel Rebelo de Oliveira 	if (err)
28829bfb23fcSOleg Nesterov 		goto bad_unshare_out;
2883fb0a685cSDaniel Rebelo de Oliveira 	err = unshare_fd(unshare_flags, &new_fd);
2884fb0a685cSDaniel Rebelo de Oliveira 	if (err)
28859bfb23fcSOleg Nesterov 		goto bad_unshare_cleanup_fs;
2886b2e0d987SEric W. Biederman 	err = unshare_userns(unshare_flags, &new_cred);
2887fb0a685cSDaniel Rebelo de Oliveira 	if (err)
28889edff4abSManfred Spraul 		goto bad_unshare_cleanup_fd;
2889b2e0d987SEric W. Biederman 	err = unshare_nsproxy_namespaces(unshare_flags, &new_nsproxy,
2890b2e0d987SEric W. Biederman 					 new_cred, new_fs);
2891b2e0d987SEric W. Biederman 	if (err)
2892b2e0d987SEric W. Biederman 		goto bad_unshare_cleanup_cred;
2893cf2e340fSJANAK DESAI 
2894b2e0d987SEric W. Biederman 	if (new_fs || new_fd || do_sysvsem || new_cred || new_nsproxy) {
28959edff4abSManfred Spraul 		if (do_sysvsem) {
28969edff4abSManfred Spraul 			/*
28979edff4abSManfred Spraul 			 * CLONE_SYSVSEM is equivalent to sys_exit().
28989edff4abSManfred Spraul 			 */
28999edff4abSManfred Spraul 			exit_sem(current);
29009edff4abSManfred Spraul 		}
2901ab602f79SJack Miller 		if (unshare_flags & CLONE_NEWIPC) {
2902ab602f79SJack Miller 			/* Orphan segments in old ns (see sem above). */
2903ab602f79SJack Miller 			exit_shm(current);
2904ab602f79SJack Miller 			shm_init_task(current);
2905ab602f79SJack Miller 		}
2906ab516013SSerge E. Hallyn 
29076f977e6bSAlan Cox 		if (new_nsproxy)
2908cf7b708cSPavel Emelyanov 			switch_task_namespaces(current, new_nsproxy);
2909cf2e340fSJANAK DESAI 
2910cf7b708cSPavel Emelyanov 		task_lock(current);
2911cf7b708cSPavel Emelyanov 
2912cf2e340fSJANAK DESAI 		if (new_fs) {
2913cf2e340fSJANAK DESAI 			fs = current->fs;
29142a4419b5SNick Piggin 			spin_lock(&fs->lock);
2915cf2e340fSJANAK DESAI 			current->fs = new_fs;
2916498052bbSAl Viro 			if (--fs->users)
2917498052bbSAl Viro 				new_fs = NULL;
2918498052bbSAl Viro 			else
2919cf2e340fSJANAK DESAI 				new_fs = fs;
29202a4419b5SNick Piggin 			spin_unlock(&fs->lock);
2921cf2e340fSJANAK DESAI 		}
2922cf2e340fSJANAK DESAI 
2923cf2e340fSJANAK DESAI 		if (new_fd) {
2924cf2e340fSJANAK DESAI 			fd = current->files;
2925cf2e340fSJANAK DESAI 			current->files = new_fd;
2926cf2e340fSJANAK DESAI 			new_fd = fd;
2927cf2e340fSJANAK DESAI 		}
2928cf2e340fSJANAK DESAI 
2929cf2e340fSJANAK DESAI 		task_unlock(current);
2930b2e0d987SEric W. Biederman 
2931b2e0d987SEric W. Biederman 		if (new_cred) {
2932b2e0d987SEric W. Biederman 			/* Install the new user namespace */
2933b2e0d987SEric W. Biederman 			commit_creds(new_cred);
2934b2e0d987SEric W. Biederman 			new_cred = NULL;
2935b2e0d987SEric W. Biederman 		}
2936cf2e340fSJANAK DESAI 	}
2937cf2e340fSJANAK DESAI 
2938e4222673SHari Bathini 	perf_event_namespaces(current);
2939e4222673SHari Bathini 
2940b2e0d987SEric W. Biederman bad_unshare_cleanup_cred:
2941b2e0d987SEric W. Biederman 	if (new_cred)
2942b2e0d987SEric W. Biederman 		put_cred(new_cred);
2943cf2e340fSJANAK DESAI bad_unshare_cleanup_fd:
2944cf2e340fSJANAK DESAI 	if (new_fd)
2945cf2e340fSJANAK DESAI 		put_files_struct(new_fd);
2946cf2e340fSJANAK DESAI 
2947cf2e340fSJANAK DESAI bad_unshare_cleanup_fs:
2948cf2e340fSJANAK DESAI 	if (new_fs)
2949498052bbSAl Viro 		free_fs_struct(new_fs);
2950cf2e340fSJANAK DESAI 
2951cf2e340fSJANAK DESAI bad_unshare_out:
2952cf2e340fSJANAK DESAI 	return err;
2953cf2e340fSJANAK DESAI }
29543b125388SAl Viro 
29559b32105eSDominik Brodowski SYSCALL_DEFINE1(unshare, unsigned long, unshare_flags)
29569b32105eSDominik Brodowski {
29579b32105eSDominik Brodowski 	return ksys_unshare(unshare_flags);
29589b32105eSDominik Brodowski }
29599b32105eSDominik Brodowski 
29603b125388SAl Viro /*
29613b125388SAl Viro  *	Helper to unshare the files of the current task.
29623b125388SAl Viro  *	We don't want to expose copy_files internals to
29633b125388SAl Viro  *	the exec layer of the kernel.
29643b125388SAl Viro  */
29653b125388SAl Viro 
29663b125388SAl Viro int unshare_files(struct files_struct **displaced)
29673b125388SAl Viro {
29683b125388SAl Viro 	struct task_struct *task = current;
296950704516SAl Viro 	struct files_struct *copy = NULL;
29703b125388SAl Viro 	int error;
29713b125388SAl Viro 
29723b125388SAl Viro 	error = unshare_fd(CLONE_FILES, &copy);
29733b125388SAl Viro 	if (error || !copy) {
29743b125388SAl Viro 		*displaced = NULL;
29753b125388SAl Viro 		return error;
29763b125388SAl Viro 	}
29773b125388SAl Viro 	*displaced = task->files;
29783b125388SAl Viro 	task_lock(task);
29793b125388SAl Viro 	task->files = copy;
29803b125388SAl Viro 	task_unlock(task);
29813b125388SAl Viro 	return 0;
29823b125388SAl Viro }
298316db3d3fSHeinrich Schuchardt 
298416db3d3fSHeinrich Schuchardt int sysctl_max_threads(struct ctl_table *table, int write,
298516db3d3fSHeinrich Schuchardt 		       void __user *buffer, size_t *lenp, loff_t *ppos)
298616db3d3fSHeinrich Schuchardt {
298716db3d3fSHeinrich Schuchardt 	struct ctl_table t;
298816db3d3fSHeinrich Schuchardt 	int ret;
298916db3d3fSHeinrich Schuchardt 	int threads = max_threads;
2990b0f53dbcSMichal Hocko 	int min = 1;
299116db3d3fSHeinrich Schuchardt 	int max = MAX_THREADS;
299216db3d3fSHeinrich Schuchardt 
299316db3d3fSHeinrich Schuchardt 	t = *table;
299416db3d3fSHeinrich Schuchardt 	t.data = &threads;
299516db3d3fSHeinrich Schuchardt 	t.extra1 = &min;
299616db3d3fSHeinrich Schuchardt 	t.extra2 = &max;
299716db3d3fSHeinrich Schuchardt 
299816db3d3fSHeinrich Schuchardt 	ret = proc_dointvec_minmax(&t, write, buffer, lenp, ppos);
299916db3d3fSHeinrich Schuchardt 	if (ret || !write)
300016db3d3fSHeinrich Schuchardt 		return ret;
300116db3d3fSHeinrich Schuchardt 
3002b0f53dbcSMichal Hocko 	max_threads = threads;
300316db3d3fSHeinrich Schuchardt 
300416db3d3fSHeinrich Schuchardt 	return 0;
300516db3d3fSHeinrich Schuchardt }
3006