xref: /openbmc/linux/kernel/fork.c (revision 1a03d3f13ffe5dd24142d6db629e72c11b704d99)
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>
431da177e4SLinus Torvalds #include <linux/fs.h>
44615d6e87SDavidlohr Bueso #include <linux/mm.h>
4517fca131SArnd Bergmann #include <linux/mm_inline.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>
805ad4e53bSAl Viro #include <linux/fs_struct.h>
817c9f8861SEric Sandeen #include <linux/magic.h>
82cdd6c482SIngo Molnar #include <linux/perf_event.h>
8342c4ab41SStanislaw Gruszka #include <linux/posix-timers.h>
848e7cac79SAvi Kivity #include <linux/user-return-notifier.h>
853d5992d2SYing Han #include <linux/oom.h>
86ba76149fSAndrea Arcangeli #include <linux/khugepaged.h>
87d80e731eSOleg Nesterov #include <linux/signalfd.h>
880326f5a9SSrikar Dronamraju #include <linux/uprobes.h>
89a27bb332SKent Overstreet #include <linux/aio.h>
9052f5684cSGideon Israel Dsouza #include <linux/compiler.h>
9116db3d3fSHeinrich Schuchardt #include <linux/sysctl.h>
925c9a8750SDmitry Vyukov #include <linux/kcov.h>
93d83a7cb3SJosh Poimboeuf #include <linux/livepatch.h>
9448ac3c18SMark Rutland #include <linux/thread_info.h>
95afaef01cSAlexander Popov #include <linux/stackleak.h>
96eafb149eSDaniel Axtens #include <linux/kasan.h>
97d08b9f0cSSami Tolvanen #include <linux/scs.h>
980f212204SJens Axboe #include <linux/io_uring.h>
99a10787e6SSong Liu #include <linux/bpf.h>
1001da177e4SLinus Torvalds 
1011da177e4SLinus Torvalds #include <asm/pgalloc.h>
1027c0f6ba6SLinus Torvalds #include <linux/uaccess.h>
1031da177e4SLinus Torvalds #include <asm/mmu_context.h>
1041da177e4SLinus Torvalds #include <asm/cacheflush.h>
1051da177e4SLinus Torvalds #include <asm/tlbflush.h>
1061da177e4SLinus Torvalds 
107ad8d75ffSSteven Rostedt #include <trace/events/sched.h>
108ad8d75ffSSteven Rostedt 
10943d2b113SKAMEZAWA Hiroyuki #define CREATE_TRACE_POINTS
11043d2b113SKAMEZAWA Hiroyuki #include <trace/events/task.h>
11143d2b113SKAMEZAWA Hiroyuki 
1121da177e4SLinus Torvalds /*
113ac1b398dSHeinrich Schuchardt  * Minimum number of threads to boot the kernel
114ac1b398dSHeinrich Schuchardt  */
115ac1b398dSHeinrich Schuchardt #define MIN_THREADS 20
116ac1b398dSHeinrich Schuchardt 
117ac1b398dSHeinrich Schuchardt /*
118ac1b398dSHeinrich Schuchardt  * Maximum number of threads
119ac1b398dSHeinrich Schuchardt  */
120ac1b398dSHeinrich Schuchardt #define MAX_THREADS FUTEX_TID_MASK
121ac1b398dSHeinrich Schuchardt 
122ac1b398dSHeinrich Schuchardt /*
1231da177e4SLinus Torvalds  * Protected counters by write_lock_irq(&tasklist_lock)
1241da177e4SLinus Torvalds  */
1251da177e4SLinus Torvalds unsigned long total_forks;	/* Handle normal Linux uptimes. */
1261da177e4SLinus Torvalds int nr_threads;			/* The idle threads do not count.. */
1271da177e4SLinus Torvalds 
1288856ae4dSKefeng Wang static int max_threads;		/* tunable limit on nr_threads */
1291da177e4SLinus Torvalds 
1308495f7e6SSai Praneeth Prakhya #define NAMED_ARRAY_INDEX(x)	[x] = __stringify(x)
1318495f7e6SSai Praneeth Prakhya 
1328495f7e6SSai Praneeth Prakhya static const char * const resident_page_types[] = {
1338495f7e6SSai Praneeth Prakhya 	NAMED_ARRAY_INDEX(MM_FILEPAGES),
1348495f7e6SSai Praneeth Prakhya 	NAMED_ARRAY_INDEX(MM_ANONPAGES),
1358495f7e6SSai Praneeth Prakhya 	NAMED_ARRAY_INDEX(MM_SWAPENTS),
1368495f7e6SSai Praneeth Prakhya 	NAMED_ARRAY_INDEX(MM_SHMEMPAGES),
1378495f7e6SSai Praneeth Prakhya };
1388495f7e6SSai Praneeth Prakhya 
1391da177e4SLinus Torvalds DEFINE_PER_CPU(unsigned long, process_counts) = 0;
1401da177e4SLinus Torvalds 
1411da177e4SLinus Torvalds __cacheline_aligned DEFINE_RWLOCK(tasklist_lock);  /* outer */
142db1466b3SPaul E. McKenney 
143db1466b3SPaul E. McKenney #ifdef CONFIG_PROVE_RCU
144db1466b3SPaul E. McKenney int lockdep_tasklist_lock_is_held(void)
145db1466b3SPaul E. McKenney {
146db1466b3SPaul E. McKenney 	return lockdep_is_held(&tasklist_lock);
147db1466b3SPaul E. McKenney }
148db1466b3SPaul E. McKenney EXPORT_SYMBOL_GPL(lockdep_tasklist_lock_is_held);
149db1466b3SPaul E. McKenney #endif /* #ifdef CONFIG_PROVE_RCU */
1501da177e4SLinus Torvalds 
1511da177e4SLinus Torvalds int nr_processes(void)
1521da177e4SLinus Torvalds {
1531da177e4SLinus Torvalds 	int cpu;
1541da177e4SLinus Torvalds 	int total = 0;
1551da177e4SLinus Torvalds 
1561d510750SIan Campbell 	for_each_possible_cpu(cpu)
1571da177e4SLinus Torvalds 		total += per_cpu(process_counts, cpu);
1581da177e4SLinus Torvalds 
1591da177e4SLinus Torvalds 	return total;
1601da177e4SLinus Torvalds }
1611da177e4SLinus Torvalds 
162f19b9f74SAkinobu Mita void __weak arch_release_task_struct(struct task_struct *tsk)
163f19b9f74SAkinobu Mita {
164f19b9f74SAkinobu Mita }
165f19b9f74SAkinobu Mita 
166f5e10287SThomas Gleixner #ifndef CONFIG_ARCH_TASK_STRUCT_ALLOCATOR
167e18b890bSChristoph Lameter static struct kmem_cache *task_struct_cachep;
16841101809SThomas Gleixner 
16941101809SThomas Gleixner static inline struct task_struct *alloc_task_struct_node(int node)
17041101809SThomas Gleixner {
17141101809SThomas Gleixner 	return kmem_cache_alloc_node(task_struct_cachep, GFP_KERNEL, node);
17241101809SThomas Gleixner }
17341101809SThomas Gleixner 
17441101809SThomas Gleixner static inline void free_task_struct(struct task_struct *tsk)
17541101809SThomas Gleixner {
17641101809SThomas Gleixner 	kmem_cache_free(task_struct_cachep, tsk);
17741101809SThomas Gleixner }
1781da177e4SLinus Torvalds #endif
1791da177e4SLinus Torvalds 
180b235beeaSLinus Torvalds #ifndef CONFIG_ARCH_THREAD_STACK_ALLOCATOR
18141101809SThomas Gleixner 
1820d15d74aSThomas Gleixner /*
1830d15d74aSThomas Gleixner  * Allocate pages if THREAD_SIZE is >= PAGE_SIZE, otherwise use a
1840d15d74aSThomas Gleixner  * kmemcache based allocator.
1850d15d74aSThomas Gleixner  */
186ba14a194SAndy Lutomirski # if THREAD_SIZE >= PAGE_SIZE || defined(CONFIG_VMAP_STACK)
187ac496bf4SAndy Lutomirski 
188ac496bf4SAndy Lutomirski #  ifdef CONFIG_VMAP_STACK
189ac496bf4SAndy Lutomirski /*
190ac496bf4SAndy Lutomirski  * vmalloc() is a bit slow, and calling vfree() enough times will force a TLB
191ac496bf4SAndy Lutomirski  * flush.  Try to minimize the number of calls by caching stacks.
192ac496bf4SAndy Lutomirski  */
193ac496bf4SAndy Lutomirski #define NR_CACHED_STACKS 2
194ac496bf4SAndy Lutomirski static DEFINE_PER_CPU(struct vm_struct *, cached_stacks[NR_CACHED_STACKS]);
19519659c59SHoeun Ryu 
19619659c59SHoeun Ryu static int free_vm_stack_cache(unsigned int cpu)
19719659c59SHoeun Ryu {
19819659c59SHoeun Ryu 	struct vm_struct **cached_vm_stacks = per_cpu_ptr(cached_stacks, cpu);
19919659c59SHoeun Ryu 	int i;
20019659c59SHoeun Ryu 
20119659c59SHoeun Ryu 	for (i = 0; i < NR_CACHED_STACKS; i++) {
20219659c59SHoeun Ryu 		struct vm_struct *vm_stack = cached_vm_stacks[i];
20319659c59SHoeun Ryu 
20419659c59SHoeun Ryu 		if (!vm_stack)
20519659c59SHoeun Ryu 			continue;
20619659c59SHoeun Ryu 
20719659c59SHoeun Ryu 		vfree(vm_stack->addr);
20819659c59SHoeun Ryu 		cached_vm_stacks[i] = NULL;
20919659c59SHoeun Ryu 	}
21019659c59SHoeun Ryu 
21119659c59SHoeun Ryu 	return 0;
21219659c59SHoeun Ryu }
213ac496bf4SAndy Lutomirski 
214*1a03d3f1SSebastian Andrzej Siewior static int memcg_charge_kernel_stack(struct vm_struct *vm)
215f1c1a9eeSSebastian Andrzej Siewior {
216f1c1a9eeSSebastian Andrzej Siewior 	int i;
217f1c1a9eeSSebastian Andrzej Siewior 	int ret;
218f1c1a9eeSSebastian Andrzej Siewior 
219f1c1a9eeSSebastian Andrzej Siewior 	BUILD_BUG_ON(IS_ENABLED(CONFIG_VMAP_STACK) && PAGE_SIZE % 1024 != 0);
220f1c1a9eeSSebastian Andrzej Siewior 	BUG_ON(vm->nr_pages != THREAD_SIZE / PAGE_SIZE);
221f1c1a9eeSSebastian Andrzej Siewior 
222f1c1a9eeSSebastian Andrzej Siewior 	for (i = 0; i < THREAD_SIZE / PAGE_SIZE; i++) {
223f1c1a9eeSSebastian Andrzej Siewior 		ret = memcg_kmem_charge_page(vm->pages[i], GFP_KERNEL, 0);
224f1c1a9eeSSebastian Andrzej Siewior 		if (ret)
225f1c1a9eeSSebastian Andrzej Siewior 			goto err;
226f1c1a9eeSSebastian Andrzej Siewior 	}
227f1c1a9eeSSebastian Andrzej Siewior 	return 0;
228f1c1a9eeSSebastian Andrzej Siewior err:
229f1c1a9eeSSebastian Andrzej Siewior 	/*
230f1c1a9eeSSebastian Andrzej Siewior 	 * If memcg_kmem_charge_page() fails, page's memory cgroup pointer is
231f1c1a9eeSSebastian Andrzej Siewior 	 * NULL, and memcg_kmem_uncharge_page() in free_thread_stack() will
232f1c1a9eeSSebastian Andrzej Siewior 	 * ignore this page.
233f1c1a9eeSSebastian Andrzej Siewior 	 */
234f1c1a9eeSSebastian Andrzej Siewior 	for (i = 0; i < THREAD_SIZE / PAGE_SIZE; i++)
235f1c1a9eeSSebastian Andrzej Siewior 		memcg_kmem_uncharge_page(vm->pages[i], 0);
236f1c1a9eeSSebastian Andrzej Siewior 	return ret;
237f1c1a9eeSSebastian Andrzej Siewior }
238f1c1a9eeSSebastian Andrzej Siewior 
2397865aba3SSebastian Andrzej Siewior static int alloc_thread_stack_node(struct task_struct *tsk, int node)
240b69c49b7SFUJITA Tomonori {
241*1a03d3f1SSebastian Andrzej Siewior 	struct vm_struct *vm;
242ac496bf4SAndy Lutomirski 	void *stack;
243ac496bf4SAndy Lutomirski 	int i;
244ac496bf4SAndy Lutomirski 
245ac496bf4SAndy Lutomirski 	for (i = 0; i < NR_CACHED_STACKS; i++) {
246112166f8SChristoph Lameter 		struct vm_struct *s;
247112166f8SChristoph Lameter 
248112166f8SChristoph Lameter 		s = this_cpu_xchg(cached_stacks[i], NULL);
249ac496bf4SAndy Lutomirski 
250ac496bf4SAndy Lutomirski 		if (!s)
251ac496bf4SAndy Lutomirski 			continue;
252ac496bf4SAndy Lutomirski 
253cebd0eb2SAndrey Konovalov 		/* Mark stack accessible for KASAN. */
254cebd0eb2SAndrey Konovalov 		kasan_unpoison_range(s->addr, THREAD_SIZE);
255eafb149eSDaniel Axtens 
256ca182551SKonstantin Khlebnikov 		/* Clear stale pointers from reused stack. */
257ca182551SKonstantin Khlebnikov 		memset(s->addr, 0, THREAD_SIZE);
258e01e8063SKees Cook 
259*1a03d3f1SSebastian Andrzej Siewior 		if (memcg_charge_kernel_stack(s)) {
260f1c1a9eeSSebastian Andrzej Siewior 			vfree(s->addr);
261f1c1a9eeSSebastian Andrzej Siewior 			return -ENOMEM;
262f1c1a9eeSSebastian Andrzej Siewior 		}
263f1c1a9eeSSebastian Andrzej Siewior 
264ac496bf4SAndy Lutomirski 		tsk->stack_vm_area = s;
265ba4a4574SShakeel Butt 		tsk->stack = s->addr;
2667865aba3SSebastian Andrzej Siewior 		return 0;
267ac496bf4SAndy Lutomirski 	}
268ac496bf4SAndy Lutomirski 
2699b6f7e16SRoman Gushchin 	/*
2709b6f7e16SRoman Gushchin 	 * Allocated stacks are cached and later reused by new threads,
2719b6f7e16SRoman Gushchin 	 * so memcg accounting is performed manually on assigning/releasing
2729b6f7e16SRoman Gushchin 	 * stacks to tasks. Drop __GFP_ACCOUNT.
2739b6f7e16SRoman Gushchin 	 */
27448ac3c18SMark Rutland 	stack = __vmalloc_node_range(THREAD_SIZE, THREAD_ALIGN,
275ba14a194SAndy Lutomirski 				     VMALLOC_START, VMALLOC_END,
2769b6f7e16SRoman Gushchin 				     THREADINFO_GFP & ~__GFP_ACCOUNT,
277ba14a194SAndy Lutomirski 				     PAGE_KERNEL,
278ac496bf4SAndy Lutomirski 				     0, node, __builtin_return_address(0));
2797865aba3SSebastian Andrzej Siewior 	if (!stack)
2807865aba3SSebastian Andrzej Siewior 		return -ENOMEM;
281f1c1a9eeSSebastian Andrzej Siewior 
282*1a03d3f1SSebastian Andrzej Siewior 	vm = find_vm_area(stack);
283*1a03d3f1SSebastian Andrzej Siewior 	if (memcg_charge_kernel_stack(vm)) {
284f1c1a9eeSSebastian Andrzej Siewior 		vfree(stack);
285f1c1a9eeSSebastian Andrzej Siewior 		return -ENOMEM;
286f1c1a9eeSSebastian Andrzej Siewior 	}
287ba14a194SAndy Lutomirski 	/*
288ba14a194SAndy Lutomirski 	 * We can't call find_vm_area() in interrupt context, and
289ba14a194SAndy Lutomirski 	 * free_thread_stack() can be called in interrupt context,
290ba14a194SAndy Lutomirski 	 * so cache the vm_struct.
291ba14a194SAndy Lutomirski 	 */
292*1a03d3f1SSebastian Andrzej Siewior 	tsk->stack_vm_area = vm;
2935eed6f1dSRik van Riel 	tsk->stack = stack;
2947865aba3SSebastian Andrzej Siewior 	return 0;
295be9a2277SSebastian Andrzej Siewior }
296be9a2277SSebastian Andrzej Siewior 
297be9a2277SSebastian Andrzej Siewior static void free_thread_stack(struct task_struct *tsk)
298be9a2277SSebastian Andrzej Siewior {
299be9a2277SSebastian Andrzej Siewior 	int i;
300be9a2277SSebastian Andrzej Siewior 
301be9a2277SSebastian Andrzej Siewior 	for (i = 0; i < NR_CACHED_STACKS; i++) {
302be9a2277SSebastian Andrzej Siewior 		if (this_cpu_cmpxchg(cached_stacks[i], NULL,
303be9a2277SSebastian Andrzej Siewior 				     tsk->stack_vm_area) != NULL)
304be9a2277SSebastian Andrzej Siewior 			continue;
305be9a2277SSebastian Andrzej Siewior 
306be9a2277SSebastian Andrzej Siewior 		tsk->stack = NULL;
307be9a2277SSebastian Andrzej Siewior 		tsk->stack_vm_area = NULL;
308be9a2277SSebastian Andrzej Siewior 		return;
309be9a2277SSebastian Andrzej Siewior 	}
310be9a2277SSebastian Andrzej Siewior 	vfree_atomic(tsk->stack);
311be9a2277SSebastian Andrzej Siewior 	tsk->stack = NULL;
312be9a2277SSebastian Andrzej Siewior 	tsk->stack_vm_area = NULL;
313be9a2277SSebastian Andrzej Siewior }
314be9a2277SSebastian Andrzej Siewior 
315be9a2277SSebastian Andrzej Siewior #  else /* !CONFIG_VMAP_STACK */
316be9a2277SSebastian Andrzej Siewior 
3177865aba3SSebastian Andrzej Siewior static int alloc_thread_stack_node(struct task_struct *tsk, int node)
318be9a2277SSebastian Andrzej Siewior {
3194949148aSVladimir Davydov 	struct page *page = alloc_pages_node(node, THREADINFO_GFP,
3202889f608SThomas Gleixner 					     THREAD_SIZE_ORDER);
321b6a84016SEric Dumazet 
3221bf4580eSAndrea Arcangeli 	if (likely(page)) {
3238dcc1d34SAndrey Konovalov 		tsk->stack = kasan_reset_tag(page_address(page));
3247865aba3SSebastian Andrzej Siewior 		return 0;
3251bf4580eSAndrea Arcangeli 	}
3267865aba3SSebastian Andrzej Siewior 	return -ENOMEM;
327b69c49b7SFUJITA Tomonori }
328b69c49b7SFUJITA Tomonori 
329be9a2277SSebastian Andrzej Siewior static void free_thread_stack(struct task_struct *tsk)
330b69c49b7SFUJITA Tomonori {
331ba14a194SAndy Lutomirski 	__free_pages(virt_to_page(tsk->stack), THREAD_SIZE_ORDER);
332be9a2277SSebastian Andrzej Siewior 	tsk->stack = NULL;
333b69c49b7SFUJITA Tomonori }
334be9a2277SSebastian Andrzej Siewior 
335be9a2277SSebastian Andrzej Siewior #  endif /* CONFIG_VMAP_STACK */
336be9a2277SSebastian Andrzej Siewior # else /* !(THREAD_SIZE >= PAGE_SIZE || defined(CONFIG_VMAP_STACK)) */
337be9a2277SSebastian Andrzej Siewior 
338b235beeaSLinus Torvalds static struct kmem_cache *thread_stack_cache;
3390d15d74aSThomas Gleixner 
3407865aba3SSebastian Andrzej Siewior static int alloc_thread_stack_node(struct task_struct *tsk, int node)
3410d15d74aSThomas Gleixner {
3425eed6f1dSRik van Riel 	unsigned long *stack;
3435eed6f1dSRik van Riel 	stack = kmem_cache_alloc_node(thread_stack_cache, THREADINFO_GFP, node);
3448dcc1d34SAndrey Konovalov 	stack = kasan_reset_tag(stack);
3455eed6f1dSRik van Riel 	tsk->stack = stack;
3467865aba3SSebastian Andrzej Siewior 	return stack ? 0 : -ENOMEM;
3470d15d74aSThomas Gleixner }
3480d15d74aSThomas Gleixner 
349ba14a194SAndy Lutomirski static void free_thread_stack(struct task_struct *tsk)
3500d15d74aSThomas Gleixner {
351ba14a194SAndy Lutomirski 	kmem_cache_free(thread_stack_cache, tsk->stack);
352be9a2277SSebastian Andrzej Siewior 	tsk->stack = NULL;
3530d15d74aSThomas Gleixner }
3540d15d74aSThomas Gleixner 
355b235beeaSLinus Torvalds void thread_stack_cache_init(void)
3560d15d74aSThomas Gleixner {
357f9d29946SDavid Windsor 	thread_stack_cache = kmem_cache_create_usercopy("thread_stack",
358f9d29946SDavid Windsor 					THREAD_SIZE, THREAD_SIZE, 0, 0,
359f9d29946SDavid Windsor 					THREAD_SIZE, NULL);
360b235beeaSLinus Torvalds 	BUG_ON(thread_stack_cache == NULL);
3610d15d74aSThomas Gleixner }
362be9a2277SSebastian Andrzej Siewior 
363be9a2277SSebastian Andrzej Siewior # endif /* THREAD_SIZE >= PAGE_SIZE || defined(CONFIG_VMAP_STACK) */
3642bb0529cSSebastian Andrzej Siewior #else /* CONFIG_ARCH_THREAD_STACK_ALLOCATOR */
3652bb0529cSSebastian Andrzej Siewior 
3667865aba3SSebastian Andrzej Siewior static int alloc_thread_stack_node(struct task_struct *tsk, int node)
3672bb0529cSSebastian Andrzej Siewior {
3682bb0529cSSebastian Andrzej Siewior 	unsigned long *stack;
3692bb0529cSSebastian Andrzej Siewior 
3702bb0529cSSebastian Andrzej Siewior 	stack = arch_alloc_thread_stack_node(tsk, node);
3712bb0529cSSebastian Andrzej Siewior 	tsk->stack = stack;
3727865aba3SSebastian Andrzej Siewior 	return stack ? 0 : -ENOMEM;
3732bb0529cSSebastian Andrzej Siewior }
3742bb0529cSSebastian Andrzej Siewior 
3752bb0529cSSebastian Andrzej Siewior static void free_thread_stack(struct task_struct *tsk)
3762bb0529cSSebastian Andrzej Siewior {
3772bb0529cSSebastian Andrzej Siewior 	arch_free_thread_stack(tsk);
3782bb0529cSSebastian Andrzej Siewior 	tsk->stack = NULL;
3792bb0529cSSebastian Andrzej Siewior }
3802bb0529cSSebastian Andrzej Siewior 
381be9a2277SSebastian Andrzej Siewior #endif /* !CONFIG_ARCH_THREAD_STACK_ALLOCATOR */
382b69c49b7SFUJITA Tomonori 
3831da177e4SLinus Torvalds /* SLAB cache for signal_struct structures (tsk->signal) */
384e18b890bSChristoph Lameter static struct kmem_cache *signal_cachep;
3851da177e4SLinus Torvalds 
3861da177e4SLinus Torvalds /* SLAB cache for sighand_struct structures (tsk->sighand) */
387e18b890bSChristoph Lameter struct kmem_cache *sighand_cachep;
3881da177e4SLinus Torvalds 
3891da177e4SLinus Torvalds /* SLAB cache for files_struct structures (tsk->files) */
390e18b890bSChristoph Lameter struct kmem_cache *files_cachep;
3911da177e4SLinus Torvalds 
3921da177e4SLinus Torvalds /* SLAB cache for fs_struct structures (tsk->fs) */
393e18b890bSChristoph Lameter struct kmem_cache *fs_cachep;
3941da177e4SLinus Torvalds 
3951da177e4SLinus Torvalds /* SLAB cache for vm_area_struct structures */
3963928d4f5SLinus Torvalds static struct kmem_cache *vm_area_cachep;
3971da177e4SLinus Torvalds 
3981da177e4SLinus Torvalds /* SLAB cache for mm_struct structures (tsk->mm) */
399e18b890bSChristoph Lameter static struct kmem_cache *mm_cachep;
4001da177e4SLinus Torvalds 
401490fc053SLinus Torvalds struct vm_area_struct *vm_area_alloc(struct mm_struct *mm)
4023928d4f5SLinus Torvalds {
403a670468fSAndrew Morton 	struct vm_area_struct *vma;
404490fc053SLinus Torvalds 
405a670468fSAndrew Morton 	vma = kmem_cache_alloc(vm_area_cachep, GFP_KERNEL);
406027232daSKirill A. Shutemov 	if (vma)
407027232daSKirill A. Shutemov 		vma_init(vma, mm);
408490fc053SLinus Torvalds 	return vma;
4093928d4f5SLinus Torvalds }
4103928d4f5SLinus Torvalds 
4113928d4f5SLinus Torvalds struct vm_area_struct *vm_area_dup(struct vm_area_struct *orig)
4123928d4f5SLinus Torvalds {
41395faf699SLinus Torvalds 	struct vm_area_struct *new = kmem_cache_alloc(vm_area_cachep, GFP_KERNEL);
41495faf699SLinus Torvalds 
41595faf699SLinus Torvalds 	if (new) {
416cda099b3SQian Cai 		ASSERT_EXCLUSIVE_WRITER(orig->vm_flags);
417cda099b3SQian Cai 		ASSERT_EXCLUSIVE_WRITER(orig->vm_file);
418cda099b3SQian Cai 		/*
419cda099b3SQian Cai 		 * orig->shared.rb may be modified concurrently, but the clone
420cda099b3SQian Cai 		 * will be reinitialized.
421cda099b3SQian Cai 		 */
422cda099b3SQian Cai 		*new = data_race(*orig);
42395faf699SLinus Torvalds 		INIT_LIST_HEAD(&new->anon_vma_chain);
424e39a4b33SLi Xinhai 		new->vm_next = new->vm_prev = NULL;
4259a10064fSColin Cross 		dup_vma_anon_name(orig, new);
42695faf699SLinus Torvalds 	}
42795faf699SLinus Torvalds 	return new;
4283928d4f5SLinus Torvalds }
4293928d4f5SLinus Torvalds 
4303928d4f5SLinus Torvalds void vm_area_free(struct vm_area_struct *vma)
4313928d4f5SLinus Torvalds {
4329a10064fSColin Cross 	free_vma_anon_name(vma);
4333928d4f5SLinus Torvalds 	kmem_cache_free(vm_area_cachep, vma);
4343928d4f5SLinus Torvalds }
4353928d4f5SLinus Torvalds 
436ba14a194SAndy Lutomirski static void account_kernel_stack(struct task_struct *tsk, int account)
437c6a7f572SKOSAKI Motohiro {
438ba14a194SAndy Lutomirski 	void *stack = task_stack_page(tsk);
439ba14a194SAndy Lutomirski 	struct vm_struct *vm = task_stack_vm_area(tsk);
440ba14a194SAndy Lutomirski 
44127faca83SMuchun Song 	if (vm) {
44227faca83SMuchun Song 		int i;
443ba14a194SAndy Lutomirski 
44427faca83SMuchun Song 		for (i = 0; i < THREAD_SIZE / PAGE_SIZE; i++)
44527faca83SMuchun Song 			mod_lruvec_page_state(vm->pages[i], NR_KERNEL_STACK_KB,
44627faca83SMuchun Song 					      account * (PAGE_SIZE / 1024));
44727faca83SMuchun Song 	} else {
448991e7673SShakeel Butt 		/* All stack pages are in the same node. */
449da3ceeffSMuchun Song 		mod_lruvec_kmem_state(stack, NR_KERNEL_STACK_KB,
450991e7673SShakeel Butt 				      account * (THREAD_SIZE / 1024));
451ba14a194SAndy Lutomirski 	}
45227faca83SMuchun Song }
453c6a7f572SKOSAKI Motohiro 
454*1a03d3f1SSebastian Andrzej Siewior void exit_task_stack_account(struct task_struct *tsk)
455*1a03d3f1SSebastian Andrzej Siewior {
456*1a03d3f1SSebastian Andrzej Siewior 	account_kernel_stack(tsk, -1);
457*1a03d3f1SSebastian Andrzej Siewior 
458*1a03d3f1SSebastian Andrzej Siewior 	if (IS_ENABLED(CONFIG_VMAP_STACK)) {
459*1a03d3f1SSebastian Andrzej Siewior 		struct vm_struct *vm;
460*1a03d3f1SSebastian Andrzej Siewior 		int i;
461*1a03d3f1SSebastian Andrzej Siewior 
462*1a03d3f1SSebastian Andrzej Siewior 		vm = task_stack_vm_area(tsk);
463*1a03d3f1SSebastian Andrzej Siewior 		for (i = 0; i < THREAD_SIZE / PAGE_SIZE; i++)
464*1a03d3f1SSebastian Andrzej Siewior 			memcg_kmem_uncharge_page(vm->pages[i], 0);
465*1a03d3f1SSebastian Andrzej Siewior 	}
466*1a03d3f1SSebastian Andrzej Siewior }
467*1a03d3f1SSebastian Andrzej Siewior 
46868f24b08SAndy Lutomirski static void release_task_stack(struct task_struct *tsk)
4691da177e4SLinus Torvalds {
4702f064a59SPeter Zijlstra 	if (WARN_ON(READ_ONCE(tsk->__state) != TASK_DEAD))
471405c0759SAndy Lutomirski 		return;  /* Better to leak the stack than to free prematurely */
472405c0759SAndy Lutomirski 
473ba14a194SAndy Lutomirski 	free_thread_stack(tsk);
47468f24b08SAndy Lutomirski }
47568f24b08SAndy Lutomirski 
47668f24b08SAndy Lutomirski #ifdef CONFIG_THREAD_INFO_IN_TASK
47768f24b08SAndy Lutomirski void put_task_stack(struct task_struct *tsk)
47868f24b08SAndy Lutomirski {
479f0b89d39SElena Reshetova 	if (refcount_dec_and_test(&tsk->stack_refcount))
48068f24b08SAndy Lutomirski 		release_task_stack(tsk);
48168f24b08SAndy Lutomirski }
48268f24b08SAndy Lutomirski #endif
48368f24b08SAndy Lutomirski 
48468f24b08SAndy Lutomirski void free_task(struct task_struct *tsk)
48568f24b08SAndy Lutomirski {
486b90ca8baSWill Deacon 	release_user_cpus_ptr(tsk);
487d08b9f0cSSami Tolvanen 	scs_release(tsk);
488d08b9f0cSSami Tolvanen 
48968f24b08SAndy Lutomirski #ifndef CONFIG_THREAD_INFO_IN_TASK
49068f24b08SAndy Lutomirski 	/*
49168f24b08SAndy Lutomirski 	 * The task is finally done with both the stack and thread_info,
49268f24b08SAndy Lutomirski 	 * so free both.
49368f24b08SAndy Lutomirski 	 */
49468f24b08SAndy Lutomirski 	release_task_stack(tsk);
49568f24b08SAndy Lutomirski #else
49668f24b08SAndy Lutomirski 	/*
49768f24b08SAndy Lutomirski 	 * If the task had a separate stack allocation, it should be gone
49868f24b08SAndy Lutomirski 	 * by now.
49968f24b08SAndy Lutomirski 	 */
500f0b89d39SElena Reshetova 	WARN_ON_ONCE(refcount_read(&tsk->stack_refcount) != 0);
50168f24b08SAndy Lutomirski #endif
50223f78d4aSIngo Molnar 	rt_mutex_debug_task_free(tsk);
503fb52607aSFrederic Weisbecker 	ftrace_graph_exit_task(tsk);
504f19b9f74SAkinobu Mita 	arch_release_task_struct(tsk);
5051da5c46fSOleg Nesterov 	if (tsk->flags & PF_KTHREAD)
5061da5c46fSOleg Nesterov 		free_kthread_struct(tsk);
5071da177e4SLinus Torvalds 	free_task_struct(tsk);
5081da177e4SLinus Torvalds }
5091da177e4SLinus Torvalds EXPORT_SYMBOL(free_task);
5101da177e4SLinus Torvalds 
511fe69d560SDavid Hildenbrand static void dup_mm_exe_file(struct mm_struct *mm, struct mm_struct *oldmm)
512fe69d560SDavid Hildenbrand {
513fe69d560SDavid Hildenbrand 	struct file *exe_file;
514fe69d560SDavid Hildenbrand 
515fe69d560SDavid Hildenbrand 	exe_file = get_mm_exe_file(oldmm);
516fe69d560SDavid Hildenbrand 	RCU_INIT_POINTER(mm->exe_file, exe_file);
517fe69d560SDavid Hildenbrand 	/*
518fe69d560SDavid Hildenbrand 	 * We depend on the oldmm having properly denied write access to the
519fe69d560SDavid Hildenbrand 	 * exe_file already.
520fe69d560SDavid Hildenbrand 	 */
521fe69d560SDavid Hildenbrand 	if (exe_file && deny_write_access(exe_file))
522fe69d560SDavid Hildenbrand 		pr_warn_once("deny_write_access() failed in %s\n", __func__);
523fe69d560SDavid Hildenbrand }
524fe69d560SDavid Hildenbrand 
5251da177e4SLinus Torvalds #ifdef CONFIG_MMU
5260766f788SEmese Revfy static __latent_entropy int dup_mmap(struct mm_struct *mm,
5270766f788SEmese Revfy 					struct mm_struct *oldmm)
5281da177e4SLinus Torvalds {
529297c5eeeSLinus Torvalds 	struct vm_area_struct *mpnt, *tmp, *prev, **pprev;
5301da177e4SLinus Torvalds 	struct rb_node **rb_link, *rb_parent;
5311da177e4SLinus Torvalds 	int retval;
5321da177e4SLinus Torvalds 	unsigned long charge;
533893e26e6SPavel Emelyanov 	LIST_HEAD(uf);
5341da177e4SLinus Torvalds 
53532cdba1eSOleg Nesterov 	uprobe_start_dup_mmap();
536d8ed45c5SMichel Lespinasse 	if (mmap_write_lock_killable(oldmm)) {
5377c051267SMichal Hocko 		retval = -EINTR;
5387c051267SMichal Hocko 		goto fail_uprobe_end;
5397c051267SMichal Hocko 	}
540ec8c0446SRalf Baechle 	flush_cache_dup_mm(oldmm);
541f8ac4ec9SOleg Nesterov 	uprobe_dup_mmap(oldmm, mm);
542ad339451SIngo Molnar 	/*
543ad339451SIngo Molnar 	 * Not linked in yet - no deadlock potential:
544ad339451SIngo Molnar 	 */
545aaa2cc56SMichel Lespinasse 	mmap_write_lock_nested(mm, SINGLE_DEPTH_NESTING);
5467ee78232SHugh Dickins 
54790f31d0eSKonstantin Khlebnikov 	/* No ordering required: file already has been exposed. */
548fe69d560SDavid Hildenbrand 	dup_mm_exe_file(mm, oldmm);
54990f31d0eSKonstantin Khlebnikov 
5504f7d4614SVladimir Davydov 	mm->total_vm = oldmm->total_vm;
55184638335SKonstantin Khlebnikov 	mm->data_vm = oldmm->data_vm;
5524f7d4614SVladimir Davydov 	mm->exec_vm = oldmm->exec_vm;
5534f7d4614SVladimir Davydov 	mm->stack_vm = oldmm->stack_vm;
5544f7d4614SVladimir Davydov 
5551da177e4SLinus Torvalds 	rb_link = &mm->mm_rb.rb_node;
5561da177e4SLinus Torvalds 	rb_parent = NULL;
5571da177e4SLinus Torvalds 	pprev = &mm->mmap;
558f8af4da3SHugh Dickins 	retval = ksm_fork(mm, oldmm);
559f8af4da3SHugh Dickins 	if (retval)
560f8af4da3SHugh Dickins 		goto out;
561ba76149fSAndrea Arcangeli 	retval = khugepaged_fork(mm, oldmm);
562ba76149fSAndrea Arcangeli 	if (retval)
563ba76149fSAndrea Arcangeli 		goto out;
5641da177e4SLinus Torvalds 
565297c5eeeSLinus Torvalds 	prev = NULL;
566fd3e42fcSHugh Dickins 	for (mpnt = oldmm->mmap; mpnt; mpnt = mpnt->vm_next) {
5671da177e4SLinus Torvalds 		struct file *file;
5681da177e4SLinus Torvalds 
5691da177e4SLinus Torvalds 		if (mpnt->vm_flags & VM_DONTCOPY) {
57084638335SKonstantin Khlebnikov 			vm_stat_account(mm, mpnt->vm_flags, -vma_pages(mpnt));
5711da177e4SLinus Torvalds 			continue;
5721da177e4SLinus Torvalds 		}
5731da177e4SLinus Torvalds 		charge = 0;
574655c79bbSTetsuo Handa 		/*
575655c79bbSTetsuo Handa 		 * Don't duplicate many vmas if we've been oom-killed (for
576655c79bbSTetsuo Handa 		 * example)
577655c79bbSTetsuo Handa 		 */
578655c79bbSTetsuo Handa 		if (fatal_signal_pending(current)) {
579655c79bbSTetsuo Handa 			retval = -EINTR;
580655c79bbSTetsuo Handa 			goto out;
581655c79bbSTetsuo Handa 		}
5821da177e4SLinus Torvalds 		if (mpnt->vm_flags & VM_ACCOUNT) {
583b2412b7fSHuang Shijie 			unsigned long len = vma_pages(mpnt);
584b2412b7fSHuang Shijie 
585191c5424SAl Viro 			if (security_vm_enough_memory_mm(oldmm, len)) /* sic */
5861da177e4SLinus Torvalds 				goto fail_nomem;
5871da177e4SLinus Torvalds 			charge = len;
5881da177e4SLinus Torvalds 		}
5893928d4f5SLinus Torvalds 		tmp = vm_area_dup(mpnt);
5901da177e4SLinus Torvalds 		if (!tmp)
5911da177e4SLinus Torvalds 			goto fail_nomem;
592ef0855d3SOleg Nesterov 		retval = vma_dup_policy(mpnt, tmp);
593ef0855d3SOleg Nesterov 		if (retval)
5941da177e4SLinus Torvalds 			goto fail_nomem_policy;
595a247c3a9SAndrea Arcangeli 		tmp->vm_mm = mm;
596893e26e6SPavel Emelyanov 		retval = dup_userfaultfd(tmp, &uf);
597893e26e6SPavel Emelyanov 		if (retval)
598893e26e6SPavel Emelyanov 			goto fail_nomem_anon_vma_fork;
599d2cd9edeSRik van Riel 		if (tmp->vm_flags & VM_WIPEONFORK) {
60093949bb2SLi Xinhai 			/*
60193949bb2SLi Xinhai 			 * VM_WIPEONFORK gets a clean slate in the child.
60293949bb2SLi Xinhai 			 * Don't prepare anon_vma until fault since we don't
60393949bb2SLi Xinhai 			 * copy page for current vma.
60493949bb2SLi Xinhai 			 */
605d2cd9edeSRik van Riel 			tmp->anon_vma = NULL;
606d2cd9edeSRik van Riel 		} else if (anon_vma_fork(tmp, mpnt))
6075beb4930SRik van Riel 			goto fail_nomem_anon_vma_fork;
608893e26e6SPavel Emelyanov 		tmp->vm_flags &= ~(VM_LOCKED | VM_LOCKONFAULT);
6091da177e4SLinus Torvalds 		file = tmp->vm_file;
6101da177e4SLinus Torvalds 		if (file) {
611b88ed205SHugh Dickins 			struct address_space *mapping = file->f_mapping;
612b88ed205SHugh Dickins 
6131da177e4SLinus Torvalds 			get_file(file);
61483cde9e8SDavidlohr Bueso 			i_mmap_lock_write(mapping);
615b88ed205SHugh Dickins 			if (tmp->vm_flags & VM_SHARED)
616cf508b58SMiaohe Lin 				mapping_allow_writable(mapping);
617b88ed205SHugh Dickins 			flush_dcache_mmap_lock(mapping);
618b88ed205SHugh Dickins 			/* insert tmp into the share list, just after mpnt */
6199826a516SMichel Lespinasse 			vma_interval_tree_insert_after(tmp, mpnt,
6209826a516SMichel Lespinasse 					&mapping->i_mmap);
621b88ed205SHugh Dickins 			flush_dcache_mmap_unlock(mapping);
62283cde9e8SDavidlohr Bueso 			i_mmap_unlock_write(mapping);
6231da177e4SLinus Torvalds 		}
6241da177e4SLinus Torvalds 
6251da177e4SLinus Torvalds 		/*
626a1e78772SMel Gorman 		 * Clear hugetlb-related page reserves for children. This only
627a1e78772SMel Gorman 		 * affects MAP_PRIVATE mappings. Faults generated by the child
628a1e78772SMel Gorman 		 * are not guaranteed to succeed, even if read-only
629a1e78772SMel Gorman 		 */
630a1e78772SMel Gorman 		if (is_vm_hugetlb_page(tmp))
631a1e78772SMel Gorman 			reset_vma_resv_huge_pages(tmp);
632a1e78772SMel Gorman 
633a1e78772SMel Gorman 		/*
6347ee78232SHugh Dickins 		 * Link in the new vma and copy the page table entries.
6351da177e4SLinus Torvalds 		 */
6361da177e4SLinus Torvalds 		*pprev = tmp;
6371da177e4SLinus Torvalds 		pprev = &tmp->vm_next;
638297c5eeeSLinus Torvalds 		tmp->vm_prev = prev;
639297c5eeeSLinus Torvalds 		prev = tmp;
6401da177e4SLinus Torvalds 
6411da177e4SLinus Torvalds 		__vma_link_rb(mm, tmp, rb_link, rb_parent);
6421da177e4SLinus Torvalds 		rb_link = &tmp->vm_rb.rb_right;
6431da177e4SLinus Torvalds 		rb_parent = &tmp->vm_rb;
6441da177e4SLinus Torvalds 
6451da177e4SLinus Torvalds 		mm->map_count++;
646d2cd9edeSRik van Riel 		if (!(tmp->vm_flags & VM_WIPEONFORK))
647c78f4636SPeter Xu 			retval = copy_page_range(tmp, mpnt);
6481da177e4SLinus Torvalds 
6491da177e4SLinus Torvalds 		if (tmp->vm_ops && tmp->vm_ops->open)
6501da177e4SLinus Torvalds 			tmp->vm_ops->open(tmp);
6511da177e4SLinus Torvalds 
6521da177e4SLinus Torvalds 		if (retval)
6531da177e4SLinus Torvalds 			goto out;
6541da177e4SLinus Torvalds 	}
655d6dd61c8SJeremy Fitzhardinge 	/* a new mm has just been created */
6561ed0cc5aSNadav Amit 	retval = arch_dup_mmap(oldmm, mm);
6571da177e4SLinus Torvalds out:
658d8ed45c5SMichel Lespinasse 	mmap_write_unlock(mm);
659fd3e42fcSHugh Dickins 	flush_tlb_mm(oldmm);
660d8ed45c5SMichel Lespinasse 	mmap_write_unlock(oldmm);
661893e26e6SPavel Emelyanov 	dup_userfaultfd_complete(&uf);
6627c051267SMichal Hocko fail_uprobe_end:
66332cdba1eSOleg Nesterov 	uprobe_end_dup_mmap();
6641da177e4SLinus Torvalds 	return retval;
6655beb4930SRik van Riel fail_nomem_anon_vma_fork:
666ef0855d3SOleg Nesterov 	mpol_put(vma_policy(tmp));
6671da177e4SLinus Torvalds fail_nomem_policy:
6683928d4f5SLinus Torvalds 	vm_area_free(tmp);
6691da177e4SLinus Torvalds fail_nomem:
6701da177e4SLinus Torvalds 	retval = -ENOMEM;
6711da177e4SLinus Torvalds 	vm_unacct_memory(charge);
6721da177e4SLinus Torvalds 	goto out;
6731da177e4SLinus Torvalds }
6741da177e4SLinus Torvalds 
6751da177e4SLinus Torvalds static inline int mm_alloc_pgd(struct mm_struct *mm)
6761da177e4SLinus Torvalds {
6771da177e4SLinus Torvalds 	mm->pgd = pgd_alloc(mm);
6781da177e4SLinus Torvalds 	if (unlikely(!mm->pgd))
6791da177e4SLinus Torvalds 		return -ENOMEM;
6801da177e4SLinus Torvalds 	return 0;
6811da177e4SLinus Torvalds }
6821da177e4SLinus Torvalds 
6831da177e4SLinus Torvalds static inline void mm_free_pgd(struct mm_struct *mm)
6841da177e4SLinus Torvalds {
6855e541973SBenjamin Herrenschmidt 	pgd_free(mm, mm->pgd);
6861da177e4SLinus Torvalds }
6871da177e4SLinus Torvalds #else
68890f31d0eSKonstantin Khlebnikov static int dup_mmap(struct mm_struct *mm, struct mm_struct *oldmm)
68990f31d0eSKonstantin Khlebnikov {
690d8ed45c5SMichel Lespinasse 	mmap_write_lock(oldmm);
691fe69d560SDavid Hildenbrand 	dup_mm_exe_file(mm, oldmm);
692d8ed45c5SMichel Lespinasse 	mmap_write_unlock(oldmm);
69390f31d0eSKonstantin Khlebnikov 	return 0;
69490f31d0eSKonstantin Khlebnikov }
6951da177e4SLinus Torvalds #define mm_alloc_pgd(mm)	(0)
6961da177e4SLinus Torvalds #define mm_free_pgd(mm)
6971da177e4SLinus Torvalds #endif /* CONFIG_MMU */
6981da177e4SLinus Torvalds 
699d70f2a14SAndrew Morton static void check_mm(struct mm_struct *mm)
700d70f2a14SAndrew Morton {
701d70f2a14SAndrew Morton 	int i;
702d70f2a14SAndrew Morton 
7038495f7e6SSai Praneeth Prakhya 	BUILD_BUG_ON_MSG(ARRAY_SIZE(resident_page_types) != NR_MM_COUNTERS,
7048495f7e6SSai Praneeth Prakhya 			 "Please make sure 'struct resident_page_types[]' is updated as well");
7058495f7e6SSai Praneeth Prakhya 
706d70f2a14SAndrew Morton 	for (i = 0; i < NR_MM_COUNTERS; i++) {
707d70f2a14SAndrew Morton 		long x = atomic_long_read(&mm->rss_stat.count[i]);
708d70f2a14SAndrew Morton 
709d70f2a14SAndrew Morton 		if (unlikely(x))
7108495f7e6SSai Praneeth Prakhya 			pr_alert("BUG: Bad rss-counter state mm:%p type:%s val:%ld\n",
7118495f7e6SSai Praneeth Prakhya 				 mm, resident_page_types[i], x);
712d70f2a14SAndrew Morton 	}
713d70f2a14SAndrew Morton 
714d70f2a14SAndrew Morton 	if (mm_pgtables_bytes(mm))
715d70f2a14SAndrew Morton 		pr_alert("BUG: non-zero pgtables_bytes on freeing mm: %ld\n",
716d70f2a14SAndrew Morton 				mm_pgtables_bytes(mm));
717d70f2a14SAndrew Morton 
718d70f2a14SAndrew Morton #if defined(CONFIG_TRANSPARENT_HUGEPAGE) && !USE_SPLIT_PMD_PTLOCKS
719d70f2a14SAndrew Morton 	VM_BUG_ON_MM(mm->pmd_huge_pte, mm);
720d70f2a14SAndrew Morton #endif
721d70f2a14SAndrew Morton }
7221da177e4SLinus Torvalds 
723e94b1766SChristoph Lameter #define allocate_mm()	(kmem_cache_alloc(mm_cachep, GFP_KERNEL))
7241da177e4SLinus Torvalds #define free_mm(mm)	(kmem_cache_free(mm_cachep, (mm)))
7251da177e4SLinus Torvalds 
726d70f2a14SAndrew Morton /*
727d70f2a14SAndrew Morton  * Called when the last reference to the mm
728d70f2a14SAndrew Morton  * is dropped: either by a lazy thread or by
729d70f2a14SAndrew Morton  * mmput. Free the page directory and the mm.
730d70f2a14SAndrew Morton  */
731d34bc48fSAndrew Morton void __mmdrop(struct mm_struct *mm)
732d70f2a14SAndrew Morton {
733d70f2a14SAndrew Morton 	BUG_ON(mm == &init_mm);
7343eda69c9SMark Rutland 	WARN_ON_ONCE(mm == current->mm);
7353eda69c9SMark Rutland 	WARN_ON_ONCE(mm == current->active_mm);
736d70f2a14SAndrew Morton 	mm_free_pgd(mm);
737d70f2a14SAndrew Morton 	destroy_context(mm);
738984cfe4eSJason Gunthorpe 	mmu_notifier_subscriptions_destroy(mm);
739d70f2a14SAndrew Morton 	check_mm(mm);
740d70f2a14SAndrew Morton 	put_user_ns(mm->user_ns);
741d70f2a14SAndrew Morton 	free_mm(mm);
742d70f2a14SAndrew Morton }
743d34bc48fSAndrew Morton EXPORT_SYMBOL_GPL(__mmdrop);
744d70f2a14SAndrew Morton 
745d70f2a14SAndrew Morton static void mmdrop_async_fn(struct work_struct *work)
746d70f2a14SAndrew Morton {
747d70f2a14SAndrew Morton 	struct mm_struct *mm;
748d70f2a14SAndrew Morton 
749d70f2a14SAndrew Morton 	mm = container_of(work, struct mm_struct, async_put_work);
750d70f2a14SAndrew Morton 	__mmdrop(mm);
751d70f2a14SAndrew Morton }
752d70f2a14SAndrew Morton 
753d70f2a14SAndrew Morton static void mmdrop_async(struct mm_struct *mm)
754d70f2a14SAndrew Morton {
755d70f2a14SAndrew Morton 	if (unlikely(atomic_dec_and_test(&mm->mm_count))) {
756d70f2a14SAndrew Morton 		INIT_WORK(&mm->async_put_work, mmdrop_async_fn);
757d70f2a14SAndrew Morton 		schedule_work(&mm->async_put_work);
758d70f2a14SAndrew Morton 	}
759d70f2a14SAndrew Morton }
760d70f2a14SAndrew Morton 
7611da177e4SLinus Torvalds static inline void free_signal_struct(struct signal_struct *sig)
7621da177e4SLinus Torvalds {
7631da177e4SLinus Torvalds 	taskstats_tgid_free(sig);
7641da177e4SLinus Torvalds 	sched_autogroup_exit(sig);
7651da177e4SLinus Torvalds 	/*
7661da177e4SLinus Torvalds 	 * __mmdrop is not safe to call from softirq context on x86 due to
7671da177e4SLinus Torvalds 	 * pgd_dtor so postpone it to the async context
7681da177e4SLinus Torvalds 	 */
7691da177e4SLinus Torvalds 	if (sig->oom_mm)
7701da177e4SLinus Torvalds 		mmdrop_async(sig->oom_mm);
7711da177e4SLinus Torvalds 	kmem_cache_free(signal_cachep, sig);
7721da177e4SLinus Torvalds }
7731da177e4SLinus Torvalds 
7741da177e4SLinus Torvalds static inline void put_signal_struct(struct signal_struct *sig)
7751da177e4SLinus Torvalds {
77660d4de3fSElena Reshetova 	if (refcount_dec_and_test(&sig->sigcnt))
7771da177e4SLinus Torvalds 		free_signal_struct(sig);
7781da177e4SLinus Torvalds }
7791da177e4SLinus Torvalds 
7801da177e4SLinus Torvalds void __put_task_struct(struct task_struct *tsk)
7811da177e4SLinus Torvalds {
7821da177e4SLinus Torvalds 	WARN_ON(!tsk->exit_state);
783ec1d2819SElena Reshetova 	WARN_ON(refcount_read(&tsk->usage));
7841da177e4SLinus Torvalds 	WARN_ON(tsk == current);
7851da177e4SLinus Torvalds 
7860f212204SJens Axboe 	io_uring_free(tsk);
7871da177e4SLinus Torvalds 	cgroup_free(tsk);
78816d51a59SJann Horn 	task_numa_free(tsk, true);
7891da177e4SLinus Torvalds 	security_task_free(tsk);
790a10787e6SSong Liu 	bpf_task_storage_free(tsk);
7911da177e4SLinus Torvalds 	exit_creds(tsk);
7921da177e4SLinus Torvalds 	delayacct_tsk_free(tsk);
7931da177e4SLinus Torvalds 	put_signal_struct(tsk->signal);
7946e33cad0SPeter Zijlstra 	sched_core_free(tsk);
7951da177e4SLinus Torvalds 	free_task(tsk);
7961da177e4SLinus Torvalds }
7971da177e4SLinus Torvalds EXPORT_SYMBOL_GPL(__put_task_struct);
7981da177e4SLinus Torvalds 
7991da177e4SLinus Torvalds void __init __weak arch_task_cache_init(void) { }
8001da177e4SLinus Torvalds 
8011da177e4SLinus Torvalds /*
8021da177e4SLinus Torvalds  * set_max_threads
8031da177e4SLinus Torvalds  */
8041da177e4SLinus Torvalds static void set_max_threads(unsigned int max_threads_suggested)
8051da177e4SLinus Torvalds {
8061da177e4SLinus Torvalds 	u64 threads;
807ca79b0c2SArun KS 	unsigned long nr_pages = totalram_pages();
8081da177e4SLinus Torvalds 
8091da177e4SLinus Torvalds 	/*
8101da177e4SLinus Torvalds 	 * The number of threads shall be limited such that the thread
8111da177e4SLinus Torvalds 	 * structures may only consume a small part of the available memory.
8121da177e4SLinus Torvalds 	 */
8133d6357deSArun KS 	if (fls64(nr_pages) + fls64(PAGE_SIZE) > 64)
8141da177e4SLinus Torvalds 		threads = MAX_THREADS;
8151da177e4SLinus Torvalds 	else
8163d6357deSArun KS 		threads = div64_u64((u64) nr_pages * (u64) PAGE_SIZE,
8171da177e4SLinus Torvalds 				    (u64) THREAD_SIZE * 8UL);
8181da177e4SLinus Torvalds 
8191da177e4SLinus Torvalds 	if (threads > max_threads_suggested)
8201da177e4SLinus Torvalds 		threads = max_threads_suggested;
8211da177e4SLinus Torvalds 
8221da177e4SLinus Torvalds 	max_threads = clamp_t(u64, threads, MIN_THREADS, MAX_THREADS);
8231da177e4SLinus Torvalds }
8241da177e4SLinus Torvalds 
8251da177e4SLinus Torvalds #ifdef CONFIG_ARCH_WANTS_DYNAMIC_TASK_STRUCT
8261da177e4SLinus Torvalds /* Initialized by the architecture: */
8271da177e4SLinus Torvalds int arch_task_struct_size __read_mostly;
8281da177e4SLinus Torvalds #endif
8291da177e4SLinus Torvalds 
8304189ff23SChristoph Hellwig #ifndef CONFIG_ARCH_TASK_STRUCT_ALLOCATOR
8315905429aSKees Cook static void task_struct_whitelist(unsigned long *offset, unsigned long *size)
8325905429aSKees Cook {
8335905429aSKees Cook 	/* Fetch thread_struct whitelist for the architecture. */
8345905429aSKees Cook 	arch_thread_struct_whitelist(offset, size);
8355905429aSKees Cook 
8365905429aSKees Cook 	/*
8375905429aSKees Cook 	 * Handle zero-sized whitelist or empty thread_struct, otherwise
8385905429aSKees Cook 	 * adjust offset to position of thread_struct in task_struct.
8395905429aSKees Cook 	 */
8405905429aSKees Cook 	if (unlikely(*size == 0))
8415905429aSKees Cook 		*offset = 0;
8425905429aSKees Cook 	else
8435905429aSKees Cook 		*offset += offsetof(struct task_struct, thread);
8445905429aSKees Cook }
8454189ff23SChristoph Hellwig #endif /* CONFIG_ARCH_TASK_STRUCT_ALLOCATOR */
8465905429aSKees Cook 
8471da177e4SLinus Torvalds void __init fork_init(void)
8481da177e4SLinus Torvalds {
8491da177e4SLinus Torvalds 	int i;
8501da177e4SLinus Torvalds #ifndef CONFIG_ARCH_TASK_STRUCT_ALLOCATOR
8511da177e4SLinus Torvalds #ifndef ARCH_MIN_TASKALIGN
8521da177e4SLinus Torvalds #define ARCH_MIN_TASKALIGN	0
8531da177e4SLinus Torvalds #endif
8541da177e4SLinus Torvalds 	int align = max_t(int, L1_CACHE_BYTES, ARCH_MIN_TASKALIGN);
8555905429aSKees Cook 	unsigned long useroffset, usersize;
8561da177e4SLinus Torvalds 
8571da177e4SLinus Torvalds 	/* create a slab on which task_structs can be allocated */
8585905429aSKees Cook 	task_struct_whitelist(&useroffset, &usersize);
8595905429aSKees Cook 	task_struct_cachep = kmem_cache_create_usercopy("task_struct",
8601da177e4SLinus Torvalds 			arch_task_struct_size, align,
8615905429aSKees Cook 			SLAB_PANIC|SLAB_ACCOUNT,
8625905429aSKees Cook 			useroffset, usersize, NULL);
8631da177e4SLinus Torvalds #endif
8641da177e4SLinus Torvalds 
8651da177e4SLinus Torvalds 	/* do the arch specific task caches init */
8661da177e4SLinus Torvalds 	arch_task_cache_init();
8671da177e4SLinus Torvalds 
8681da177e4SLinus Torvalds 	set_max_threads(MAX_THREADS);
8691da177e4SLinus Torvalds 
8701da177e4SLinus Torvalds 	init_task.signal->rlim[RLIMIT_NPROC].rlim_cur = max_threads/2;
8711da177e4SLinus Torvalds 	init_task.signal->rlim[RLIMIT_NPROC].rlim_max = max_threads/2;
8721da177e4SLinus Torvalds 	init_task.signal->rlim[RLIMIT_SIGPENDING] =
8731da177e4SLinus Torvalds 		init_task.signal->rlim[RLIMIT_NPROC];
8741da177e4SLinus Torvalds 
87521d1c5e3SAlexey Gladkov 	for (i = 0; i < MAX_PER_NAMESPACE_UCOUNTS; i++)
8761da177e4SLinus Torvalds 		init_user_ns.ucount_max[i] = max_threads/2;
8771da177e4SLinus Torvalds 
8785ddf994fSEric W. Biederman 	set_rlimit_ucount_max(&init_user_ns, UCOUNT_RLIMIT_NPROC,      RLIM_INFINITY);
8795ddf994fSEric W. Biederman 	set_rlimit_ucount_max(&init_user_ns, UCOUNT_RLIMIT_MSGQUEUE,   RLIM_INFINITY);
8805ddf994fSEric W. Biederman 	set_rlimit_ucount_max(&init_user_ns, UCOUNT_RLIMIT_SIGPENDING, RLIM_INFINITY);
8815ddf994fSEric W. Biederman 	set_rlimit_ucount_max(&init_user_ns, UCOUNT_RLIMIT_MEMLOCK,    RLIM_INFINITY);
88221d1c5e3SAlexey Gladkov 
8831da177e4SLinus Torvalds #ifdef CONFIG_VMAP_STACK
8841da177e4SLinus Torvalds 	cpuhp_setup_state(CPUHP_BP_PREPARE_DYN, "fork:vm_stack_cache",
8851da177e4SLinus Torvalds 			  NULL, free_vm_stack_cache);
8861da177e4SLinus Torvalds #endif
8871da177e4SLinus Torvalds 
888d08b9f0cSSami Tolvanen 	scs_init();
889d08b9f0cSSami Tolvanen 
8901da177e4SLinus Torvalds 	lockdep_init_task(&init_task);
891aad42dd4SNadav Amit 	uprobes_init();
8921da177e4SLinus Torvalds }
8931da177e4SLinus Torvalds 
8941da177e4SLinus Torvalds int __weak arch_dup_task_struct(struct task_struct *dst,
8951da177e4SLinus Torvalds 					       struct task_struct *src)
8961da177e4SLinus Torvalds {
8971da177e4SLinus Torvalds 	*dst = *src;
8981da177e4SLinus Torvalds 	return 0;
8991da177e4SLinus Torvalds }
9001da177e4SLinus Torvalds 
9011da177e4SLinus Torvalds void set_task_stack_end_magic(struct task_struct *tsk)
9021da177e4SLinus Torvalds {
9031da177e4SLinus Torvalds 	unsigned long *stackend;
9041da177e4SLinus Torvalds 
9051da177e4SLinus Torvalds 	stackend = end_of_stack(tsk);
9061da177e4SLinus Torvalds 	*stackend = STACK_END_MAGIC;	/* for overflow detection */
9071da177e4SLinus Torvalds }
9081da177e4SLinus Torvalds 
9091da177e4SLinus Torvalds static struct task_struct *dup_task_struct(struct task_struct *orig, int node)
9101da177e4SLinus Torvalds {
9111da177e4SLinus Torvalds 	struct task_struct *tsk;
9121da177e4SLinus Torvalds 	int err;
9131da177e4SLinus Torvalds 
9141da177e4SLinus Torvalds 	if (node == NUMA_NO_NODE)
9151da177e4SLinus Torvalds 		node = tsk_fork_get_node(orig);
9161da177e4SLinus Torvalds 	tsk = alloc_task_struct_node(node);
9171da177e4SLinus Torvalds 	if (!tsk)
9181da177e4SLinus Torvalds 		return NULL;
9191da177e4SLinus Torvalds 
920546c42b2SSebastian Andrzej Siewior 	err = arch_dup_task_struct(tsk, orig);
921546c42b2SSebastian Andrzej Siewior 	if (err)
922546c42b2SSebastian Andrzej Siewior 		goto free_tsk;
923546c42b2SSebastian Andrzej Siewior 
9247865aba3SSebastian Andrzej Siewior 	err = alloc_thread_stack_node(tsk, node);
9257865aba3SSebastian Andrzej Siewior 	if (err)
9261da177e4SLinus Torvalds 		goto free_tsk;
9271da177e4SLinus Torvalds 
9281da177e4SLinus Torvalds #ifdef CONFIG_THREAD_INFO_IN_TASK
929f0b89d39SElena Reshetova 	refcount_set(&tsk->stack_refcount, 1);
9301da177e4SLinus Torvalds #endif
931*1a03d3f1SSebastian Andrzej Siewior 	account_kernel_stack(tsk, 1);
9321da177e4SLinus Torvalds 
933d08b9f0cSSami Tolvanen 	err = scs_prepare(tsk, node);
934d08b9f0cSSami Tolvanen 	if (err)
935d08b9f0cSSami Tolvanen 		goto free_stack;
936d08b9f0cSSami Tolvanen 
9371da177e4SLinus Torvalds #ifdef CONFIG_SECCOMP
9381da177e4SLinus Torvalds 	/*
9391da177e4SLinus Torvalds 	 * We must handle setting up seccomp filters once we're under
9401da177e4SLinus Torvalds 	 * the sighand lock in case orig has changed between now and
9411da177e4SLinus Torvalds 	 * then. Until then, filter must be NULL to avoid messing up
9421da177e4SLinus Torvalds 	 * the usage counts on the error path calling free_task.
9431da177e4SLinus Torvalds 	 */
9441da177e4SLinus Torvalds 	tsk->seccomp.filter = NULL;
9451da177e4SLinus Torvalds #endif
9461da177e4SLinus Torvalds 
9471da177e4SLinus Torvalds 	setup_thread_stack(tsk, orig);
9481da177e4SLinus Torvalds 	clear_user_return_notifier(tsk);
9491da177e4SLinus Torvalds 	clear_tsk_need_resched(tsk);
9501da177e4SLinus Torvalds 	set_task_stack_end_magic(tsk);
9511446e1dfSGabriel Krisman Bertazi 	clear_syscall_work_syscall_user_dispatch(tsk);
9521da177e4SLinus Torvalds 
953050e9baaSLinus Torvalds #ifdef CONFIG_STACKPROTECTOR
9541da177e4SLinus Torvalds 	tsk->stack_canary = get_random_canary();
9551da177e4SLinus Torvalds #endif
9563bd37062SSebastian Andrzej Siewior 	if (orig->cpus_ptr == &orig->cpus_mask)
9573bd37062SSebastian Andrzej Siewior 		tsk->cpus_ptr = &tsk->cpus_mask;
958b90ca8baSWill Deacon 	dup_user_cpus_ptr(tsk, orig, node);
9591da177e4SLinus Torvalds 
9601da177e4SLinus Torvalds 	/*
9610ff7b2cfSEric W. Biederman 	 * One for the user space visible state that goes away when reaped.
9620ff7b2cfSEric W. Biederman 	 * One for the scheduler.
9631da177e4SLinus Torvalds 	 */
9640ff7b2cfSEric W. Biederman 	refcount_set(&tsk->rcu_users, 2);
9650ff7b2cfSEric W. Biederman 	/* One for the rcu users */
9660ff7b2cfSEric W. Biederman 	refcount_set(&tsk->usage, 1);
9671da177e4SLinus Torvalds #ifdef CONFIG_BLK_DEV_IO_TRACE
9681da177e4SLinus Torvalds 	tsk->btrace_seq = 0;
9691da177e4SLinus Torvalds #endif
9701da177e4SLinus Torvalds 	tsk->splice_pipe = NULL;
9711da177e4SLinus Torvalds 	tsk->task_frag.page = NULL;
9721da177e4SLinus Torvalds 	tsk->wake_q.next = NULL;
973e32cf5dfSEric W. Biederman 	tsk->worker_private = NULL;
9741da177e4SLinus Torvalds 
9751da177e4SLinus Torvalds 	kcov_task_init(tsk);
9765fbda3ecSThomas Gleixner 	kmap_local_fork(tsk);
9771da177e4SLinus Torvalds 
9781da177e4SLinus Torvalds #ifdef CONFIG_FAULT_INJECTION
9791da177e4SLinus Torvalds 	tsk->fail_nth = 0;
9801da177e4SLinus Torvalds #endif
9811da177e4SLinus Torvalds 
9822c323017SJosef Bacik #ifdef CONFIG_BLK_CGROUP
9832c323017SJosef Bacik 	tsk->throttle_queue = NULL;
9842c323017SJosef Bacik 	tsk->use_memdelay = 0;
9852c323017SJosef Bacik #endif
9862c323017SJosef Bacik 
987d46eb14bSShakeel Butt #ifdef CONFIG_MEMCG
988d46eb14bSShakeel Butt 	tsk->active_memcg = NULL;
989d46eb14bSShakeel Butt #endif
9901da177e4SLinus Torvalds 	return tsk;
9911da177e4SLinus Torvalds 
9921da177e4SLinus Torvalds free_stack:
993*1a03d3f1SSebastian Andrzej Siewior 	exit_task_stack_account(tsk);
9941da177e4SLinus Torvalds 	free_thread_stack(tsk);
9951da177e4SLinus Torvalds free_tsk:
9961da177e4SLinus Torvalds 	free_task_struct(tsk);
9971da177e4SLinus Torvalds 	return NULL;
9981da177e4SLinus Torvalds }
9991da177e4SLinus Torvalds 
10001da177e4SLinus Torvalds __cacheline_aligned_in_smp DEFINE_SPINLOCK(mmlist_lock);
10011da177e4SLinus Torvalds 
10024cb0e11bSHidehiro Kawai static unsigned long default_dump_filter = MMF_DUMP_FILTER_DEFAULT;
10034cb0e11bSHidehiro Kawai 
10044cb0e11bSHidehiro Kawai static int __init coredump_filter_setup(char *s)
10054cb0e11bSHidehiro Kawai {
10064cb0e11bSHidehiro Kawai 	default_dump_filter =
10074cb0e11bSHidehiro Kawai 		(simple_strtoul(s, NULL, 0) << MMF_DUMP_FILTER_SHIFT) &
10084cb0e11bSHidehiro Kawai 		MMF_DUMP_FILTER_MASK;
10094cb0e11bSHidehiro Kawai 	return 1;
10104cb0e11bSHidehiro Kawai }
10114cb0e11bSHidehiro Kawai 
10124cb0e11bSHidehiro Kawai __setup("coredump_filter=", coredump_filter_setup);
10134cb0e11bSHidehiro Kawai 
10141da177e4SLinus Torvalds #include <linux/init_task.h>
10151da177e4SLinus Torvalds 
1016858f0993SAlexey Dobriyan static void mm_init_aio(struct mm_struct *mm)
1017858f0993SAlexey Dobriyan {
1018858f0993SAlexey Dobriyan #ifdef CONFIG_AIO
1019858f0993SAlexey Dobriyan 	spin_lock_init(&mm->ioctx_lock);
1020db446a08SBenjamin LaHaise 	mm->ioctx_table = NULL;
1021858f0993SAlexey Dobriyan #endif
1022858f0993SAlexey Dobriyan }
1023858f0993SAlexey Dobriyan 
1024c3f3ce04SAndrea Arcangeli static __always_inline void mm_clear_owner(struct mm_struct *mm,
1025c3f3ce04SAndrea Arcangeli 					   struct task_struct *p)
1026c3f3ce04SAndrea Arcangeli {
1027c3f3ce04SAndrea Arcangeli #ifdef CONFIG_MEMCG
1028c3f3ce04SAndrea Arcangeli 	if (mm->owner == p)
1029c3f3ce04SAndrea Arcangeli 		WRITE_ONCE(mm->owner, NULL);
1030c3f3ce04SAndrea Arcangeli #endif
1031c3f3ce04SAndrea Arcangeli }
1032c3f3ce04SAndrea Arcangeli 
103333144e84SVladimir Davydov static void mm_init_owner(struct mm_struct *mm, struct task_struct *p)
103433144e84SVladimir Davydov {
103533144e84SVladimir Davydov #ifdef CONFIG_MEMCG
103633144e84SVladimir Davydov 	mm->owner = p;
103733144e84SVladimir Davydov #endif
103833144e84SVladimir Davydov }
103933144e84SVladimir Davydov 
104082e69a12SFenghua Yu static void mm_init_pasid(struct mm_struct *mm)
104182e69a12SFenghua Yu {
104282e69a12SFenghua Yu #ifdef CONFIG_IOMMU_SUPPORT
104382e69a12SFenghua Yu 	mm->pasid = INIT_PASID;
104482e69a12SFenghua Yu #endif
104582e69a12SFenghua Yu }
104682e69a12SFenghua Yu 
1047355627f5SEric Biggers static void mm_init_uprobes_state(struct mm_struct *mm)
1048355627f5SEric Biggers {
1049355627f5SEric Biggers #ifdef CONFIG_UPROBES
1050355627f5SEric Biggers 	mm->uprobes_state.xol_area = NULL;
1051355627f5SEric Biggers #endif
1052355627f5SEric Biggers }
1053355627f5SEric Biggers 
1054bfedb589SEric W. Biederman static struct mm_struct *mm_init(struct mm_struct *mm, struct task_struct *p,
1055bfedb589SEric W. Biederman 	struct user_namespace *user_ns)
10561da177e4SLinus Torvalds {
105741f727fdSVladimir Davydov 	mm->mmap = NULL;
105841f727fdSVladimir Davydov 	mm->mm_rb = RB_ROOT;
105941f727fdSVladimir Davydov 	mm->vmacache_seqnum = 0;
10601da177e4SLinus Torvalds 	atomic_set(&mm->mm_users, 1);
10611da177e4SLinus Torvalds 	atomic_set(&mm->mm_count, 1);
106257efa1feSJason Gunthorpe 	seqcount_init(&mm->write_protect_seq);
1063d8ed45c5SMichel Lespinasse 	mmap_init_lock(mm);
10641da177e4SLinus Torvalds 	INIT_LIST_HEAD(&mm->mmlist);
1065af5b0f6aSKirill A. Shutemov 	mm_pgtables_bytes_init(mm);
106641f727fdSVladimir Davydov 	mm->map_count = 0;
106741f727fdSVladimir Davydov 	mm->locked_vm = 0;
106870f8a3caSDavidlohr Bueso 	atomic64_set(&mm->pinned_vm, 0);
1069d559db08SKAMEZAWA Hiroyuki 	memset(&mm->rss_stat, 0, sizeof(mm->rss_stat));
10701da177e4SLinus Torvalds 	spin_lock_init(&mm->page_table_lock);
107188aa7cc6SYang Shi 	spin_lock_init(&mm->arg_lock);
107241f727fdSVladimir Davydov 	mm_init_cpumask(mm);
1073858f0993SAlexey Dobriyan 	mm_init_aio(mm);
1074cf475ad2SBalbir Singh 	mm_init_owner(mm, p);
107582e69a12SFenghua Yu 	mm_init_pasid(mm);
10762b7e8665SEric Biggers 	RCU_INIT_POINTER(mm->exe_file, NULL);
1077984cfe4eSJason Gunthorpe 	mmu_notifier_subscriptions_init(mm);
107816af97dcSNadav Amit 	init_tlb_flush_pending(mm);
107941f727fdSVladimir Davydov #if defined(CONFIG_TRANSPARENT_HUGEPAGE) && !USE_SPLIT_PMD_PTLOCKS
108041f727fdSVladimir Davydov 	mm->pmd_huge_pte = NULL;
108141f727fdSVladimir Davydov #endif
1082355627f5SEric Biggers 	mm_init_uprobes_state(mm);
108313db8c50SLiu Zixian 	hugetlb_count_init(mm);
10841da177e4SLinus Torvalds 
1085a0715cc2SAlex Thorlton 	if (current->mm) {
1086a0715cc2SAlex Thorlton 		mm->flags = current->mm->flags & MMF_INIT_MASK;
1087a0715cc2SAlex Thorlton 		mm->def_flags = current->mm->def_flags & VM_INIT_DEF_MASK;
1088a0715cc2SAlex Thorlton 	} else {
1089a0715cc2SAlex Thorlton 		mm->flags = default_dump_filter;
10901da177e4SLinus Torvalds 		mm->def_flags = 0;
1091a0715cc2SAlex Thorlton 	}
1092a0715cc2SAlex Thorlton 
109341f727fdSVladimir Davydov 	if (mm_alloc_pgd(mm))
109441f727fdSVladimir Davydov 		goto fail_nopgd;
109578fb7466SPavel Emelianov 
109641f727fdSVladimir Davydov 	if (init_new_context(p, mm))
109741f727fdSVladimir Davydov 		goto fail_nocontext;
109841f727fdSVladimir Davydov 
1099bfedb589SEric W. Biederman 	mm->user_ns = get_user_ns(user_ns);
110041f727fdSVladimir Davydov 	return mm;
110141f727fdSVladimir Davydov 
110241f727fdSVladimir Davydov fail_nocontext:
110341f727fdSVladimir Davydov 	mm_free_pgd(mm);
110441f727fdSVladimir Davydov fail_nopgd:
11051da177e4SLinus Torvalds 	free_mm(mm);
11061da177e4SLinus Torvalds 	return NULL;
11071da177e4SLinus Torvalds }
11081da177e4SLinus Torvalds 
11091da177e4SLinus Torvalds /*
11101da177e4SLinus Torvalds  * Allocate and initialize an mm_struct.
11111da177e4SLinus Torvalds  */
11121da177e4SLinus Torvalds struct mm_struct *mm_alloc(void)
11131da177e4SLinus Torvalds {
11141da177e4SLinus Torvalds 	struct mm_struct *mm;
11151da177e4SLinus Torvalds 
11161da177e4SLinus Torvalds 	mm = allocate_mm();
1117de03c72cSKOSAKI Motohiro 	if (!mm)
1118de03c72cSKOSAKI Motohiro 		return NULL;
1119de03c72cSKOSAKI Motohiro 
11201da177e4SLinus Torvalds 	memset(mm, 0, sizeof(*mm));
1121bfedb589SEric W. Biederman 	return mm_init(mm, current, current_user_ns());
11221da177e4SLinus Torvalds }
11231da177e4SLinus Torvalds 
1124ec8d7c14SMichal Hocko static inline void __mmput(struct mm_struct *mm)
11251da177e4SLinus Torvalds {
1126ec8d7c14SMichal Hocko 	VM_BUG_ON(atomic_read(&mm->mm_users));
11270ae26f1bSAndrew Morton 
1128d4b3b638SSrikar Dronamraju 	uprobe_clear_state(mm);
11291da177e4SLinus Torvalds 	exit_aio(mm);
11301c2fb7a4SAndrea Arcangeli 	ksm_exit(mm);
1131ba76149fSAndrea Arcangeli 	khugepaged_exit(mm); /* must run before exit_mmap */
11321da177e4SLinus Torvalds 	exit_mmap(mm);
11336fcb52a5SAaron Lu 	mm_put_huge_zero_page(mm);
1134925d1c40SMatt Helsley 	set_mm_exe_file(mm, NULL);
11351da177e4SLinus Torvalds 	if (!list_empty(&mm->mmlist)) {
11361da177e4SLinus Torvalds 		spin_lock(&mmlist_lock);
11371da177e4SLinus Torvalds 		list_del(&mm->mmlist);
11381da177e4SLinus Torvalds 		spin_unlock(&mmlist_lock);
11391da177e4SLinus Torvalds 	}
1140801460d0SHiroshi Shimamoto 	if (mm->binfmt)
1141801460d0SHiroshi Shimamoto 		module_put(mm->binfmt->module);
11421da177e4SLinus Torvalds 	mmdrop(mm);
11431da177e4SLinus Torvalds }
1144ec8d7c14SMichal Hocko 
1145ec8d7c14SMichal Hocko /*
1146ec8d7c14SMichal Hocko  * Decrement the use count and release all resources for an mm.
1147ec8d7c14SMichal Hocko  */
1148ec8d7c14SMichal Hocko void mmput(struct mm_struct *mm)
1149ec8d7c14SMichal Hocko {
1150ec8d7c14SMichal Hocko 	might_sleep();
1151ec8d7c14SMichal Hocko 
1152ec8d7c14SMichal Hocko 	if (atomic_dec_and_test(&mm->mm_users))
1153ec8d7c14SMichal Hocko 		__mmput(mm);
11541da177e4SLinus Torvalds }
11551da177e4SLinus Torvalds EXPORT_SYMBOL_GPL(mmput);
11561da177e4SLinus Torvalds 
1157a1b2289cSSherry Yang #ifdef CONFIG_MMU
1158a1b2289cSSherry Yang static void mmput_async_fn(struct work_struct *work)
1159a1b2289cSSherry Yang {
1160a1b2289cSSherry Yang 	struct mm_struct *mm = container_of(work, struct mm_struct,
1161a1b2289cSSherry Yang 					    async_put_work);
1162a1b2289cSSherry Yang 
1163a1b2289cSSherry Yang 	__mmput(mm);
1164a1b2289cSSherry Yang }
1165a1b2289cSSherry Yang 
1166a1b2289cSSherry Yang void mmput_async(struct mm_struct *mm)
1167a1b2289cSSherry Yang {
1168a1b2289cSSherry Yang 	if (atomic_dec_and_test(&mm->mm_users)) {
1169a1b2289cSSherry Yang 		INIT_WORK(&mm->async_put_work, mmput_async_fn);
1170a1b2289cSSherry Yang 		schedule_work(&mm->async_put_work);
1171a1b2289cSSherry Yang 	}
1172a1b2289cSSherry Yang }
1173a1b2289cSSherry Yang #endif
1174a1b2289cSSherry Yang 
117590f31d0eSKonstantin Khlebnikov /**
117690f31d0eSKonstantin Khlebnikov  * set_mm_exe_file - change a reference to the mm's executable file
117790f31d0eSKonstantin Khlebnikov  *
117890f31d0eSKonstantin Khlebnikov  * This changes mm's executable file (shown as symlink /proc/[pid]/exe).
117990f31d0eSKonstantin Khlebnikov  *
11806e399cd1SDavidlohr Bueso  * Main users are mmput() and sys_execve(). Callers prevent concurrent
11816e399cd1SDavidlohr Bueso  * invocations: in mmput() nobody alive left, in execve task is single
118235d7bdc8SDavid Hildenbrand  * threaded.
1183fe69d560SDavid Hildenbrand  *
1184fe69d560SDavid Hildenbrand  * Can only fail if new_exe_file != NULL.
118590f31d0eSKonstantin Khlebnikov  */
1186fe69d560SDavid Hildenbrand int set_mm_exe_file(struct mm_struct *mm, struct file *new_exe_file)
118738646013SJiri Slaby {
11886e399cd1SDavidlohr Bueso 	struct file *old_exe_file;
11896e399cd1SDavidlohr Bueso 
11906e399cd1SDavidlohr Bueso 	/*
11916e399cd1SDavidlohr Bueso 	 * It is safe to dereference the exe_file without RCU as
11926e399cd1SDavidlohr Bueso 	 * this function is only called if nobody else can access
11936e399cd1SDavidlohr Bueso 	 * this mm -- see comment above for justification.
11946e399cd1SDavidlohr Bueso 	 */
11956e399cd1SDavidlohr Bueso 	old_exe_file = rcu_dereference_raw(mm->exe_file);
119690f31d0eSKonstantin Khlebnikov 
1197fe69d560SDavid Hildenbrand 	if (new_exe_file) {
1198fe69d560SDavid Hildenbrand 		/*
1199fe69d560SDavid Hildenbrand 		 * We expect the caller (i.e., sys_execve) to already denied
1200fe69d560SDavid Hildenbrand 		 * write access, so this is unlikely to fail.
1201fe69d560SDavid Hildenbrand 		 */
1202fe69d560SDavid Hildenbrand 		if (unlikely(deny_write_access(new_exe_file)))
1203fe69d560SDavid Hildenbrand 			return -EACCES;
120438646013SJiri Slaby 		get_file(new_exe_file);
1205fe69d560SDavid Hildenbrand 	}
120690f31d0eSKonstantin Khlebnikov 	rcu_assign_pointer(mm->exe_file, new_exe_file);
1207fe69d560SDavid Hildenbrand 	if (old_exe_file) {
1208fe69d560SDavid Hildenbrand 		allow_write_access(old_exe_file);
120990f31d0eSKonstantin Khlebnikov 		fput(old_exe_file);
121038646013SJiri Slaby 	}
1211fe69d560SDavid Hildenbrand 	return 0;
1212fe69d560SDavid Hildenbrand }
121338646013SJiri Slaby 
121490f31d0eSKonstantin Khlebnikov /**
121535d7bdc8SDavid Hildenbrand  * replace_mm_exe_file - replace a reference to the mm's executable file
121635d7bdc8SDavid Hildenbrand  *
121735d7bdc8SDavid Hildenbrand  * This changes mm's executable file (shown as symlink /proc/[pid]/exe),
121835d7bdc8SDavid Hildenbrand  * dealing with concurrent invocation and without grabbing the mmap lock in
121935d7bdc8SDavid Hildenbrand  * write mode.
122035d7bdc8SDavid Hildenbrand  *
122135d7bdc8SDavid Hildenbrand  * Main user is sys_prctl(PR_SET_MM_MAP/EXE_FILE).
122235d7bdc8SDavid Hildenbrand  */
122335d7bdc8SDavid Hildenbrand int replace_mm_exe_file(struct mm_struct *mm, struct file *new_exe_file)
122435d7bdc8SDavid Hildenbrand {
122535d7bdc8SDavid Hildenbrand 	struct vm_area_struct *vma;
122635d7bdc8SDavid Hildenbrand 	struct file *old_exe_file;
122735d7bdc8SDavid Hildenbrand 	int ret = 0;
122835d7bdc8SDavid Hildenbrand 
122935d7bdc8SDavid Hildenbrand 	/* Forbid mm->exe_file change if old file still mapped. */
123035d7bdc8SDavid Hildenbrand 	old_exe_file = get_mm_exe_file(mm);
123135d7bdc8SDavid Hildenbrand 	if (old_exe_file) {
123235d7bdc8SDavid Hildenbrand 		mmap_read_lock(mm);
123335d7bdc8SDavid Hildenbrand 		for (vma = mm->mmap; vma && !ret; vma = vma->vm_next) {
123435d7bdc8SDavid Hildenbrand 			if (!vma->vm_file)
123535d7bdc8SDavid Hildenbrand 				continue;
123635d7bdc8SDavid Hildenbrand 			if (path_equal(&vma->vm_file->f_path,
123735d7bdc8SDavid Hildenbrand 				       &old_exe_file->f_path))
123835d7bdc8SDavid Hildenbrand 				ret = -EBUSY;
123935d7bdc8SDavid Hildenbrand 		}
124035d7bdc8SDavid Hildenbrand 		mmap_read_unlock(mm);
124135d7bdc8SDavid Hildenbrand 		fput(old_exe_file);
124235d7bdc8SDavid Hildenbrand 		if (ret)
124335d7bdc8SDavid Hildenbrand 			return ret;
124435d7bdc8SDavid Hildenbrand 	}
124535d7bdc8SDavid Hildenbrand 
124635d7bdc8SDavid Hildenbrand 	/* set the new file, lockless */
1247fe69d560SDavid Hildenbrand 	ret = deny_write_access(new_exe_file);
1248fe69d560SDavid Hildenbrand 	if (ret)
1249fe69d560SDavid Hildenbrand 		return -EACCES;
125035d7bdc8SDavid Hildenbrand 	get_file(new_exe_file);
1251fe69d560SDavid Hildenbrand 
125235d7bdc8SDavid Hildenbrand 	old_exe_file = xchg(&mm->exe_file, new_exe_file);
1253fe69d560SDavid Hildenbrand 	if (old_exe_file) {
1254fe69d560SDavid Hildenbrand 		/*
1255fe69d560SDavid Hildenbrand 		 * Don't race with dup_mmap() getting the file and disallowing
1256fe69d560SDavid Hildenbrand 		 * write access while someone might open the file writable.
1257fe69d560SDavid Hildenbrand 		 */
1258fe69d560SDavid Hildenbrand 		mmap_read_lock(mm);
1259fe69d560SDavid Hildenbrand 		allow_write_access(old_exe_file);
126035d7bdc8SDavid Hildenbrand 		fput(old_exe_file);
1261fe69d560SDavid Hildenbrand 		mmap_read_unlock(mm);
1262fe69d560SDavid Hildenbrand 	}
126335d7bdc8SDavid Hildenbrand 	return 0;
126435d7bdc8SDavid Hildenbrand }
126538646013SJiri Slaby 
126690f31d0eSKonstantin Khlebnikov /**
126790f31d0eSKonstantin Khlebnikov  * get_mm_exe_file - acquire a reference to the mm's executable file
126890f31d0eSKonstantin Khlebnikov  *
126990f31d0eSKonstantin Khlebnikov  * Returns %NULL if mm has no associated executable file.
127090f31d0eSKonstantin Khlebnikov  * User must release file via fput().
127190f31d0eSKonstantin Khlebnikov  */
127238646013SJiri Slaby struct file *get_mm_exe_file(struct mm_struct *mm)
127338646013SJiri Slaby {
127438646013SJiri Slaby 	struct file *exe_file;
127538646013SJiri Slaby 
127690f31d0eSKonstantin Khlebnikov 	rcu_read_lock();
127790f31d0eSKonstantin Khlebnikov 	exe_file = rcu_dereference(mm->exe_file);
127890f31d0eSKonstantin Khlebnikov 	if (exe_file && !get_file_rcu(exe_file))
127990f31d0eSKonstantin Khlebnikov 		exe_file = NULL;
128090f31d0eSKonstantin Khlebnikov 	rcu_read_unlock();
128138646013SJiri Slaby 	return exe_file;
128238646013SJiri Slaby }
128338646013SJiri Slaby 
12841da177e4SLinus Torvalds /**
1285cd81a917SMateusz Guzik  * get_task_exe_file - acquire a reference to the task's executable file
1286cd81a917SMateusz Guzik  *
1287cd81a917SMateusz Guzik  * Returns %NULL if task's mm (if any) has no associated executable file or
1288cd81a917SMateusz Guzik  * this is a kernel thread with borrowed mm (see the comment above get_task_mm).
1289cd81a917SMateusz Guzik  * User must release file via fput().
1290cd81a917SMateusz Guzik  */
1291cd81a917SMateusz Guzik struct file *get_task_exe_file(struct task_struct *task)
1292cd81a917SMateusz Guzik {
1293cd81a917SMateusz Guzik 	struct file *exe_file = NULL;
1294cd81a917SMateusz Guzik 	struct mm_struct *mm;
1295cd81a917SMateusz Guzik 
1296cd81a917SMateusz Guzik 	task_lock(task);
1297cd81a917SMateusz Guzik 	mm = task->mm;
1298cd81a917SMateusz Guzik 	if (mm) {
1299cd81a917SMateusz Guzik 		if (!(task->flags & PF_KTHREAD))
1300cd81a917SMateusz Guzik 			exe_file = get_mm_exe_file(mm);
1301cd81a917SMateusz Guzik 	}
1302cd81a917SMateusz Guzik 	task_unlock(task);
1303cd81a917SMateusz Guzik 	return exe_file;
1304cd81a917SMateusz Guzik }
1305cd81a917SMateusz Guzik 
1306cd81a917SMateusz Guzik /**
13071da177e4SLinus Torvalds  * get_task_mm - acquire a reference to the task's mm
13081da177e4SLinus Torvalds  *
1309246bb0b1SOleg Nesterov  * Returns %NULL if the task has no mm.  Checks PF_KTHREAD (meaning
13101da177e4SLinus Torvalds  * this kernel workthread has transiently adopted a user mm with use_mm,
13111da177e4SLinus Torvalds  * to do its AIO) is not set and if so returns a reference to it, after
13121da177e4SLinus Torvalds  * bumping up the use count.  User must release the mm via mmput()
13131da177e4SLinus Torvalds  * after use.  Typically used by /proc and ptrace.
13141da177e4SLinus Torvalds  */
13151da177e4SLinus Torvalds struct mm_struct *get_task_mm(struct task_struct *task)
13161da177e4SLinus Torvalds {
13171da177e4SLinus Torvalds 	struct mm_struct *mm;
13181da177e4SLinus Torvalds 
13191da177e4SLinus Torvalds 	task_lock(task);
13201da177e4SLinus Torvalds 	mm = task->mm;
13211da177e4SLinus Torvalds 	if (mm) {
1322246bb0b1SOleg Nesterov 		if (task->flags & PF_KTHREAD)
13231da177e4SLinus Torvalds 			mm = NULL;
13241da177e4SLinus Torvalds 		else
13253fce371bSVegard Nossum 			mmget(mm);
13261da177e4SLinus Torvalds 	}
13271da177e4SLinus Torvalds 	task_unlock(task);
13281da177e4SLinus Torvalds 	return mm;
13291da177e4SLinus Torvalds }
13301da177e4SLinus Torvalds EXPORT_SYMBOL_GPL(get_task_mm);
13311da177e4SLinus Torvalds 
13328cdb878dSChristopher Yeoh struct mm_struct *mm_access(struct task_struct *task, unsigned int mode)
13338cdb878dSChristopher Yeoh {
13348cdb878dSChristopher Yeoh 	struct mm_struct *mm;
13358cdb878dSChristopher Yeoh 	int err;
13368cdb878dSChristopher Yeoh 
1337f7cfd871SEric W. Biederman 	err =  down_read_killable(&task->signal->exec_update_lock);
13388cdb878dSChristopher Yeoh 	if (err)
13398cdb878dSChristopher Yeoh 		return ERR_PTR(err);
13408cdb878dSChristopher Yeoh 
13418cdb878dSChristopher Yeoh 	mm = get_task_mm(task);
13428cdb878dSChristopher Yeoh 	if (mm && mm != current->mm &&
13438cdb878dSChristopher Yeoh 			!ptrace_may_access(task, mode)) {
13448cdb878dSChristopher Yeoh 		mmput(mm);
13458cdb878dSChristopher Yeoh 		mm = ERR_PTR(-EACCES);
13468cdb878dSChristopher Yeoh 	}
1347f7cfd871SEric W. Biederman 	up_read(&task->signal->exec_update_lock);
13488cdb878dSChristopher Yeoh 
13498cdb878dSChristopher Yeoh 	return mm;
13508cdb878dSChristopher Yeoh }
13518cdb878dSChristopher Yeoh 
135257b59c4aSOleg Nesterov static void complete_vfork_done(struct task_struct *tsk)
1353c415c3b4SOleg Nesterov {
1354d68b46feSOleg Nesterov 	struct completion *vfork;
1355c415c3b4SOleg Nesterov 
1356d68b46feSOleg Nesterov 	task_lock(tsk);
1357d68b46feSOleg Nesterov 	vfork = tsk->vfork_done;
1358d68b46feSOleg Nesterov 	if (likely(vfork)) {
1359c415c3b4SOleg Nesterov 		tsk->vfork_done = NULL;
1360d68b46feSOleg Nesterov 		complete(vfork);
1361d68b46feSOleg Nesterov 	}
1362d68b46feSOleg Nesterov 	task_unlock(tsk);
1363d68b46feSOleg Nesterov }
1364d68b46feSOleg Nesterov 
1365d68b46feSOleg Nesterov static int wait_for_vfork_done(struct task_struct *child,
1366d68b46feSOleg Nesterov 				struct completion *vfork)
1367d68b46feSOleg Nesterov {
1368d68b46feSOleg Nesterov 	int killed;
1369d68b46feSOleg Nesterov 
1370d68b46feSOleg Nesterov 	freezer_do_not_count();
137176f969e8SRoman Gushchin 	cgroup_enter_frozen();
1372d68b46feSOleg Nesterov 	killed = wait_for_completion_killable(vfork);
137376f969e8SRoman Gushchin 	cgroup_leave_frozen(false);
1374d68b46feSOleg Nesterov 	freezer_count();
1375d68b46feSOleg Nesterov 
1376d68b46feSOleg Nesterov 	if (killed) {
1377d68b46feSOleg Nesterov 		task_lock(child);
1378d68b46feSOleg Nesterov 		child->vfork_done = NULL;
1379d68b46feSOleg Nesterov 		task_unlock(child);
1380d68b46feSOleg Nesterov 	}
1381d68b46feSOleg Nesterov 
1382d68b46feSOleg Nesterov 	put_task_struct(child);
1383d68b46feSOleg Nesterov 	return killed;
1384c415c3b4SOleg Nesterov }
1385c415c3b4SOleg Nesterov 
13861da177e4SLinus Torvalds /* Please note the differences between mmput and mm_release.
13871da177e4SLinus Torvalds  * mmput is called whenever we stop holding onto a mm_struct,
13881da177e4SLinus Torvalds  * error success whatever.
13891da177e4SLinus Torvalds  *
13901da177e4SLinus Torvalds  * mm_release is called after a mm_struct has been removed
13911da177e4SLinus Torvalds  * from the current process.
13921da177e4SLinus Torvalds  *
13931da177e4SLinus Torvalds  * This difference is important for error handling, when we
13941da177e4SLinus Torvalds  * only half set up a mm_struct for a new process and need to restore
13951da177e4SLinus Torvalds  * the old one.  Because we mmput the new mm_struct before
13961da177e4SLinus Torvalds  * restoring the old one. . .
13971da177e4SLinus Torvalds  * Eric Biederman 10 January 1998
13981da177e4SLinus Torvalds  */
13994610ba7aSThomas Gleixner static void mm_release(struct task_struct *tsk, struct mm_struct *mm)
14001da177e4SLinus Torvalds {
14010326f5a9SSrikar Dronamraju 	uprobe_free_utask(tsk);
14020326f5a9SSrikar Dronamraju 
14031da177e4SLinus Torvalds 	/* Get rid of any cached register state */
14041da177e4SLinus Torvalds 	deactivate_mm(tsk, mm);
14051da177e4SLinus Torvalds 
1406fec1d011SRoland McGrath 	/*
1407735f2770SMichal Hocko 	 * Signal userspace if we're not exiting with a core dump
1408735f2770SMichal Hocko 	 * because we want to leave the value intact for debugging
1409735f2770SMichal Hocko 	 * purposes.
1410fec1d011SRoland McGrath 	 */
14119c8a8228SEric Dumazet 	if (tsk->clear_child_tid) {
141292307383SEric W. Biederman 		if (atomic_read(&mm->mm_users) > 1) {
14131da177e4SLinus Torvalds 			/*
14141da177e4SLinus Torvalds 			 * We don't check the error code - if userspace has
14151da177e4SLinus Torvalds 			 * not set up a proper pointer then tough luck.
14161da177e4SLinus Torvalds 			 */
14179c8a8228SEric Dumazet 			put_user(0, tsk->clear_child_tid);
14182de0db99SDominik Brodowski 			do_futex(tsk->clear_child_tid, FUTEX_WAKE,
14192de0db99SDominik Brodowski 					1, NULL, NULL, 0, 0);
14209c8a8228SEric Dumazet 		}
14219c8a8228SEric Dumazet 		tsk->clear_child_tid = NULL;
14221da177e4SLinus Torvalds 	}
1423f7505d64SKonstantin Khlebnikov 
1424f7505d64SKonstantin Khlebnikov 	/*
1425f7505d64SKonstantin Khlebnikov 	 * All done, finally we can wake up parent and return this mm to him.
1426f7505d64SKonstantin Khlebnikov 	 * Also kthread_stop() uses this completion for synchronization.
1427f7505d64SKonstantin Khlebnikov 	 */
1428f7505d64SKonstantin Khlebnikov 	if (tsk->vfork_done)
1429f7505d64SKonstantin Khlebnikov 		complete_vfork_done(tsk);
14301da177e4SLinus Torvalds }
14311da177e4SLinus Torvalds 
14324610ba7aSThomas Gleixner void exit_mm_release(struct task_struct *tsk, struct mm_struct *mm)
14334610ba7aSThomas Gleixner {
1434150d7158SThomas Gleixner 	futex_exit_release(tsk);
14354610ba7aSThomas Gleixner 	mm_release(tsk, mm);
14364610ba7aSThomas Gleixner }
14374610ba7aSThomas Gleixner 
14384610ba7aSThomas Gleixner void exec_mm_release(struct task_struct *tsk, struct mm_struct *mm)
14394610ba7aSThomas Gleixner {
1440150d7158SThomas Gleixner 	futex_exec_release(tsk);
14414610ba7aSThomas Gleixner 	mm_release(tsk, mm);
14424610ba7aSThomas Gleixner }
14434610ba7aSThomas Gleixner 
144413585fa0SNadav Amit /**
144513585fa0SNadav Amit  * dup_mm() - duplicates an existing mm structure
144613585fa0SNadav Amit  * @tsk: the task_struct with which the new mm will be associated.
144713585fa0SNadav Amit  * @oldmm: the mm to duplicate.
144813585fa0SNadav Amit  *
144913585fa0SNadav Amit  * Allocates a new mm structure and duplicates the provided @oldmm structure
145013585fa0SNadav Amit  * content into it.
145113585fa0SNadav Amit  *
145213585fa0SNadav Amit  * Return: the duplicated mm or NULL on failure.
1453a0a7ec30SJANAK DESAI  */
145413585fa0SNadav Amit static struct mm_struct *dup_mm(struct task_struct *tsk,
145513585fa0SNadav Amit 				struct mm_struct *oldmm)
1456a0a7ec30SJANAK DESAI {
145713585fa0SNadav Amit 	struct mm_struct *mm;
1458a0a7ec30SJANAK DESAI 	int err;
1459a0a7ec30SJANAK DESAI 
1460a0a7ec30SJANAK DESAI 	mm = allocate_mm();
1461a0a7ec30SJANAK DESAI 	if (!mm)
1462a0a7ec30SJANAK DESAI 		goto fail_nomem;
1463a0a7ec30SJANAK DESAI 
1464a0a7ec30SJANAK DESAI 	memcpy(mm, oldmm, sizeof(*mm));
1465a0a7ec30SJANAK DESAI 
1466bfedb589SEric W. Biederman 	if (!mm_init(mm, tsk, mm->user_ns))
1467a0a7ec30SJANAK DESAI 		goto fail_nomem;
1468a0a7ec30SJANAK DESAI 
1469a0a7ec30SJANAK DESAI 	err = dup_mmap(mm, oldmm);
1470a0a7ec30SJANAK DESAI 	if (err)
1471a0a7ec30SJANAK DESAI 		goto free_pt;
1472a0a7ec30SJANAK DESAI 
1473a0a7ec30SJANAK DESAI 	mm->hiwater_rss = get_mm_rss(mm);
1474a0a7ec30SJANAK DESAI 	mm->hiwater_vm = mm->total_vm;
1475a0a7ec30SJANAK DESAI 
1476801460d0SHiroshi Shimamoto 	if (mm->binfmt && !try_module_get(mm->binfmt->module))
1477801460d0SHiroshi Shimamoto 		goto free_pt;
1478801460d0SHiroshi Shimamoto 
1479a0a7ec30SJANAK DESAI 	return mm;
1480a0a7ec30SJANAK DESAI 
1481a0a7ec30SJANAK DESAI free_pt:
1482801460d0SHiroshi Shimamoto 	/* don't put binfmt in mmput, we haven't got module yet */
1483801460d0SHiroshi Shimamoto 	mm->binfmt = NULL;
1484c3f3ce04SAndrea Arcangeli 	mm_init_owner(mm, NULL);
1485a0a7ec30SJANAK DESAI 	mmput(mm);
1486a0a7ec30SJANAK DESAI 
1487a0a7ec30SJANAK DESAI fail_nomem:
1488a0a7ec30SJANAK DESAI 	return NULL;
1489a0a7ec30SJANAK DESAI }
1490a0a7ec30SJANAK DESAI 
14911da177e4SLinus Torvalds static int copy_mm(unsigned long clone_flags, struct task_struct *tsk)
14921da177e4SLinus Torvalds {
14931da177e4SLinus Torvalds 	struct mm_struct *mm, *oldmm;
14941da177e4SLinus Torvalds 
14951da177e4SLinus Torvalds 	tsk->min_flt = tsk->maj_flt = 0;
14961da177e4SLinus Torvalds 	tsk->nvcsw = tsk->nivcsw = 0;
149717406b82SMandeep Singh Baines #ifdef CONFIG_DETECT_HUNG_TASK
149817406b82SMandeep Singh Baines 	tsk->last_switch_count = tsk->nvcsw + tsk->nivcsw;
1499a2e51445SDmitry Vyukov 	tsk->last_switch_time = 0;
150017406b82SMandeep Singh Baines #endif
15011da177e4SLinus Torvalds 
15021da177e4SLinus Torvalds 	tsk->mm = NULL;
15031da177e4SLinus Torvalds 	tsk->active_mm = NULL;
15041da177e4SLinus Torvalds 
15051da177e4SLinus Torvalds 	/*
15061da177e4SLinus Torvalds 	 * Are we cloning a kernel thread?
15071da177e4SLinus Torvalds 	 *
15081da177e4SLinus Torvalds 	 * We need to steal a active VM for that..
15091da177e4SLinus Torvalds 	 */
15101da177e4SLinus Torvalds 	oldmm = current->mm;
15111da177e4SLinus Torvalds 	if (!oldmm)
15121da177e4SLinus Torvalds 		return 0;
15131da177e4SLinus Torvalds 
1514615d6e87SDavidlohr Bueso 	/* initialize the new vmacache entries */
1515615d6e87SDavidlohr Bueso 	vmacache_flush(tsk);
1516615d6e87SDavidlohr Bueso 
15171da177e4SLinus Torvalds 	if (clone_flags & CLONE_VM) {
15183fce371bSVegard Nossum 		mmget(oldmm);
15191da177e4SLinus Torvalds 		mm = oldmm;
1520a6895399SRolf Eike Beer 	} else {
152113585fa0SNadav Amit 		mm = dup_mm(tsk, current->mm);
15221da177e4SLinus Torvalds 		if (!mm)
1523a6895399SRolf Eike Beer 			return -ENOMEM;
1524a6895399SRolf Eike Beer 	}
15251da177e4SLinus Torvalds 
15261da177e4SLinus Torvalds 	tsk->mm = mm;
15271da177e4SLinus Torvalds 	tsk->active_mm = mm;
15281da177e4SLinus Torvalds 	return 0;
15291da177e4SLinus Torvalds }
15301da177e4SLinus Torvalds 
1531a39bc516SAlexey Dobriyan static int copy_fs(unsigned long clone_flags, struct task_struct *tsk)
15321da177e4SLinus Torvalds {
1533498052bbSAl Viro 	struct fs_struct *fs = current->fs;
15341da177e4SLinus Torvalds 	if (clone_flags & CLONE_FS) {
1535498052bbSAl Viro 		/* tsk->fs is already what we want */
15362a4419b5SNick Piggin 		spin_lock(&fs->lock);
1537498052bbSAl Viro 		if (fs->in_exec) {
15382a4419b5SNick Piggin 			spin_unlock(&fs->lock);
1539498052bbSAl Viro 			return -EAGAIN;
1540498052bbSAl Viro 		}
1541498052bbSAl Viro 		fs->users++;
15422a4419b5SNick Piggin 		spin_unlock(&fs->lock);
15431da177e4SLinus Torvalds 		return 0;
15441da177e4SLinus Torvalds 	}
1545498052bbSAl Viro 	tsk->fs = copy_fs_struct(fs);
15461da177e4SLinus Torvalds 	if (!tsk->fs)
15471da177e4SLinus Torvalds 		return -ENOMEM;
15481da177e4SLinus Torvalds 	return 0;
15491da177e4SLinus Torvalds }
15501da177e4SLinus Torvalds 
1551a016f338SJANAK DESAI static int copy_files(unsigned long clone_flags, struct task_struct *tsk)
1552a016f338SJANAK DESAI {
1553a016f338SJANAK DESAI 	struct files_struct *oldf, *newf;
1554a016f338SJANAK DESAI 	int error = 0;
1555a016f338SJANAK DESAI 
1556a016f338SJANAK DESAI 	/*
1557a016f338SJANAK DESAI 	 * A background process may not have any files ...
1558a016f338SJANAK DESAI 	 */
1559a016f338SJANAK DESAI 	oldf = current->files;
1560a016f338SJANAK DESAI 	if (!oldf)
1561a016f338SJANAK DESAI 		goto out;
1562a016f338SJANAK DESAI 
1563a016f338SJANAK DESAI 	if (clone_flags & CLONE_FILES) {
1564a016f338SJANAK DESAI 		atomic_inc(&oldf->count);
1565a016f338SJANAK DESAI 		goto out;
1566a016f338SJANAK DESAI 	}
1567a016f338SJANAK DESAI 
156860997c3dSChristian Brauner 	newf = dup_fd(oldf, NR_OPEN_MAX, &error);
1569a016f338SJANAK DESAI 	if (!newf)
1570a016f338SJANAK DESAI 		goto out;
1571a016f338SJANAK DESAI 
1572a016f338SJANAK DESAI 	tsk->files = newf;
1573a016f338SJANAK DESAI 	error = 0;
1574a016f338SJANAK DESAI out:
1575a016f338SJANAK DESAI 	return error;
1576a016f338SJANAK DESAI }
1577a016f338SJANAK DESAI 
1578a39bc516SAlexey Dobriyan static int copy_sighand(unsigned long clone_flags, struct task_struct *tsk)
15791da177e4SLinus Torvalds {
15801da177e4SLinus Torvalds 	struct sighand_struct *sig;
15811da177e4SLinus Torvalds 
158260348802SZhaolei 	if (clone_flags & CLONE_SIGHAND) {
1583d036bda7SElena Reshetova 		refcount_inc(&current->sighand->count);
15841da177e4SLinus Torvalds 		return 0;
15851da177e4SLinus Torvalds 	}
15861da177e4SLinus Torvalds 	sig = kmem_cache_alloc(sighand_cachep, GFP_KERNEL);
15870c282b06SMadhuparna Bhowmik 	RCU_INIT_POINTER(tsk->sighand, sig);
15881da177e4SLinus Torvalds 	if (!sig)
15891da177e4SLinus Torvalds 		return -ENOMEM;
15909d7fb042SPeter Zijlstra 
1591d036bda7SElena Reshetova 	refcount_set(&sig->count, 1);
159206e62a46SJann Horn 	spin_lock_irq(&current->sighand->siglock);
15931da177e4SLinus Torvalds 	memcpy(sig->action, current->sighand->action, sizeof(sig->action));
159406e62a46SJann Horn 	spin_unlock_irq(&current->sighand->siglock);
1595b612e5dfSChristian Brauner 
1596b612e5dfSChristian Brauner 	/* Reset all signal handler not set to SIG_IGN to SIG_DFL. */
1597b612e5dfSChristian Brauner 	if (clone_flags & CLONE_CLEAR_SIGHAND)
1598b612e5dfSChristian Brauner 		flush_signal_handlers(tsk, 0);
1599b612e5dfSChristian Brauner 
16001da177e4SLinus Torvalds 	return 0;
16011da177e4SLinus Torvalds }
16021da177e4SLinus Torvalds 
1603a7e5328aSOleg Nesterov void __cleanup_sighand(struct sighand_struct *sighand)
1604c81addc9SOleg Nesterov {
1605d036bda7SElena Reshetova 	if (refcount_dec_and_test(&sighand->count)) {
1606d80e731eSOleg Nesterov 		signalfd_cleanup(sighand);
1607392809b2SOleg Nesterov 		/*
16085f0d5a3aSPaul E. McKenney 		 * sighand_cachep is SLAB_TYPESAFE_BY_RCU so we can free it
1609392809b2SOleg Nesterov 		 * without an RCU grace period, see __lock_task_sighand().
1610392809b2SOleg Nesterov 		 */
1611c81addc9SOleg Nesterov 		kmem_cache_free(sighand_cachep, sighand);
1612c81addc9SOleg Nesterov 	}
1613d80e731eSOleg Nesterov }
1614c81addc9SOleg Nesterov 
1615f06febc9SFrank Mayhar /*
1616f06febc9SFrank Mayhar  * Initialize POSIX timer handling for a thread group.
1617f06febc9SFrank Mayhar  */
1618f06febc9SFrank Mayhar static void posix_cpu_timers_init_group(struct signal_struct *sig)
1619f06febc9SFrank Mayhar {
16202b69942fSThomas Gleixner 	struct posix_cputimers *pct = &sig->posix_cputimers;
162178d7d407SJiri Slaby 	unsigned long cpu_limit;
162278d7d407SJiri Slaby 
1623316c1608SJason Low 	cpu_limit = READ_ONCE(sig->rlim[RLIMIT_CPU].rlim_cur);
16243a245c0fSThomas Gleixner 	posix_cputimers_group_init(pct, cpu_limit);
16256279a751SOleg Nesterov }
16266279a751SOleg Nesterov 
1627a39bc516SAlexey Dobriyan static int copy_signal(unsigned long clone_flags, struct task_struct *tsk)
16281da177e4SLinus Torvalds {
16291da177e4SLinus Torvalds 	struct signal_struct *sig;
16301da177e4SLinus Torvalds 
16314ab6c083SOleg Nesterov 	if (clone_flags & CLONE_THREAD)
1632490dea45SPeter Zijlstra 		return 0;
16336279a751SOleg Nesterov 
1634a56704efSVeaceslav Falico 	sig = kmem_cache_zalloc(signal_cachep, GFP_KERNEL);
16351da177e4SLinus Torvalds 	tsk->signal = sig;
16361da177e4SLinus Torvalds 	if (!sig)
16371da177e4SLinus Torvalds 		return -ENOMEM;
16381da177e4SLinus Torvalds 
1639b3ac022cSOleg Nesterov 	sig->nr_threads = 1;
16401da177e4SLinus Torvalds 	atomic_set(&sig->live, 1);
164160d4de3fSElena Reshetova 	refcount_set(&sig->sigcnt, 1);
16420c740d0aSOleg Nesterov 
16430c740d0aSOleg Nesterov 	/* list_add(thread_node, thread_head) without INIT_LIST_HEAD() */
16440c740d0aSOleg Nesterov 	sig->thread_head = (struct list_head)LIST_HEAD_INIT(tsk->thread_node);
16450c740d0aSOleg Nesterov 	tsk->thread_node = (struct list_head)LIST_HEAD_INIT(sig->thread_head);
16460c740d0aSOleg Nesterov 
16471da177e4SLinus Torvalds 	init_waitqueue_head(&sig->wait_chldexit);
1648db51aeccSOleg Nesterov 	sig->curr_target = tsk;
16491da177e4SLinus Torvalds 	init_sigpending(&sig->shared_pending);
1650c3ad2c3bSEric W. Biederman 	INIT_HLIST_HEAD(&sig->multiprocess);
1651e78c3496SRik van Riel 	seqlock_init(&sig->stats_lock);
16529d7fb042SPeter Zijlstra 	prev_cputime_init(&sig->prev_cputime);
16531da177e4SLinus Torvalds 
1654baa73d9eSNicolas Pitre #ifdef CONFIG_POSIX_TIMERS
1655b18b6a9cSNicolas Pitre 	INIT_LIST_HEAD(&sig->posix_timers);
1656c9cb2e3dSThomas Gleixner 	hrtimer_init(&sig->real_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
16571da177e4SLinus Torvalds 	sig->real_timer.function = it_real_fn;
1658baa73d9eSNicolas Pitre #endif
16591da177e4SLinus Torvalds 
16601da177e4SLinus Torvalds 	task_lock(current->group_leader);
16611da177e4SLinus Torvalds 	memcpy(sig->rlim, current->signal->rlim, sizeof sig->rlim);
16621da177e4SLinus Torvalds 	task_unlock(current->group_leader);
16631da177e4SLinus Torvalds 
16646279a751SOleg Nesterov 	posix_cpu_timers_init_group(sig);
16656279a751SOleg Nesterov 
1666522ed776SMiloslav Trmac 	tty_audit_fork(sig);
16675091faa4SMike Galbraith 	sched_autogroup_fork(sig);
1668522ed776SMiloslav Trmac 
1669a63d83f4SDavid Rientjes 	sig->oom_score_adj = current->signal->oom_score_adj;
1670dabb16f6SMandeep Singh Baines 	sig->oom_score_adj_min = current->signal->oom_score_adj_min;
167128b83c51SKOSAKI Motohiro 
16729b1bf12dSKOSAKI Motohiro 	mutex_init(&sig->cred_guard_mutex);
1673f7cfd871SEric W. Biederman 	init_rwsem(&sig->exec_update_lock);
16749b1bf12dSKOSAKI Motohiro 
16751da177e4SLinus Torvalds 	return 0;
16761da177e4SLinus Torvalds }
16771da177e4SLinus Torvalds 
1678dbd95212SKees Cook static void copy_seccomp(struct task_struct *p)
1679dbd95212SKees Cook {
1680dbd95212SKees Cook #ifdef CONFIG_SECCOMP
1681dbd95212SKees Cook 	/*
1682dbd95212SKees Cook 	 * Must be called with sighand->lock held, which is common to
1683dbd95212SKees Cook 	 * all threads in the group. Holding cred_guard_mutex is not
1684dbd95212SKees Cook 	 * needed because this new task is not yet running and cannot
1685dbd95212SKees Cook 	 * be racing exec.
1686dbd95212SKees Cook 	 */
168769f6a34bSGuenter Roeck 	assert_spin_locked(&current->sighand->siglock);
1688dbd95212SKees Cook 
1689dbd95212SKees Cook 	/* Ref-count the new filter user, and assign it. */
1690dbd95212SKees Cook 	get_seccomp_filter(current);
1691dbd95212SKees Cook 	p->seccomp = current->seccomp;
1692dbd95212SKees Cook 
1693dbd95212SKees Cook 	/*
1694dbd95212SKees Cook 	 * Explicitly enable no_new_privs here in case it got set
1695dbd95212SKees Cook 	 * between the task_struct being duplicated and holding the
1696dbd95212SKees Cook 	 * sighand lock. The seccomp state and nnp must be in sync.
1697dbd95212SKees Cook 	 */
1698dbd95212SKees Cook 	if (task_no_new_privs(current))
1699dbd95212SKees Cook 		task_set_no_new_privs(p);
1700dbd95212SKees Cook 
1701dbd95212SKees Cook 	/*
1702dbd95212SKees Cook 	 * If the parent gained a seccomp mode after copying thread
1703dbd95212SKees Cook 	 * flags and between before we held the sighand lock, we have
1704dbd95212SKees Cook 	 * to manually enable the seccomp thread flag here.
1705dbd95212SKees Cook 	 */
1706dbd95212SKees Cook 	if (p->seccomp.mode != SECCOMP_MODE_DISABLED)
170723d67a54SGabriel Krisman Bertazi 		set_task_syscall_work(p, SECCOMP);
1708dbd95212SKees Cook #endif
1709dbd95212SKees Cook }
1710dbd95212SKees Cook 
171117da2bd9SHeiko Carstens SYSCALL_DEFINE1(set_tid_address, int __user *, tidptr)
17121da177e4SLinus Torvalds {
17131da177e4SLinus Torvalds 	current->clear_child_tid = tidptr;
17141da177e4SLinus Torvalds 
1715b488893aSPavel Emelyanov 	return task_pid_vnr(current);
17161da177e4SLinus Torvalds }
17171da177e4SLinus Torvalds 
1718a39bc516SAlexey Dobriyan static void rt_mutex_init_task(struct task_struct *p)
171923f78d4aSIngo Molnar {
17201d615482SThomas Gleixner 	raw_spin_lock_init(&p->pi_lock);
1721e29e175bSZilvinas Valinskas #ifdef CONFIG_RT_MUTEXES
1722a23ba907SDavidlohr Bueso 	p->pi_waiters = RB_ROOT_CACHED;
1723e96a7705SXunlei Pang 	p->pi_top_task = NULL;
172423f78d4aSIngo Molnar 	p->pi_blocked_on = NULL;
172523f78d4aSIngo Molnar #endif
172623f78d4aSIngo Molnar }
172723f78d4aSIngo Molnar 
17282c470475SEric W. Biederman static inline void init_task_pid_links(struct task_struct *task)
17292c470475SEric W. Biederman {
17302c470475SEric W. Biederman 	enum pid_type type;
17312c470475SEric W. Biederman 
173296e1e984SAlexander Guril 	for (type = PIDTYPE_PID; type < PIDTYPE_MAX; ++type)
17332c470475SEric W. Biederman 		INIT_HLIST_NODE(&task->pid_links[type]);
17342c470475SEric W. Biederman }
17352c470475SEric W. Biederman 
173681907739SOleg Nesterov static inline void
173781907739SOleg Nesterov init_task_pid(struct task_struct *task, enum pid_type type, struct pid *pid)
173881907739SOleg Nesterov {
17392c470475SEric W. Biederman 	if (type == PIDTYPE_PID)
17402c470475SEric W. Biederman 		task->thread_pid = pid;
17412c470475SEric W. Biederman 	else
17422c470475SEric W. Biederman 		task->signal->pids[type] = pid;
174381907739SOleg Nesterov }
174481907739SOleg Nesterov 
17456bfbaa51SIngo Molnar static inline void rcu_copy_process(struct task_struct *p)
17466bfbaa51SIngo Molnar {
17476bfbaa51SIngo Molnar #ifdef CONFIG_PREEMPT_RCU
17486bfbaa51SIngo Molnar 	p->rcu_read_lock_nesting = 0;
17496bfbaa51SIngo Molnar 	p->rcu_read_unlock_special.s = 0;
17506bfbaa51SIngo Molnar 	p->rcu_blocked_node = NULL;
17516bfbaa51SIngo Molnar 	INIT_LIST_HEAD(&p->rcu_node_entry);
17526bfbaa51SIngo Molnar #endif /* #ifdef CONFIG_PREEMPT_RCU */
17536bfbaa51SIngo Molnar #ifdef CONFIG_TASKS_RCU
17546bfbaa51SIngo Molnar 	p->rcu_tasks_holdout = false;
17556bfbaa51SIngo Molnar 	INIT_LIST_HEAD(&p->rcu_tasks_holdout_list);
17566bfbaa51SIngo Molnar 	p->rcu_tasks_idle_cpu = -1;
17576bfbaa51SIngo Molnar #endif /* #ifdef CONFIG_TASKS_RCU */
1758d5f177d3SPaul E. McKenney #ifdef CONFIG_TASKS_TRACE_RCU
1759d5f177d3SPaul E. McKenney 	p->trc_reader_nesting = 0;
1760276c4104SPaul E. McKenney 	p->trc_reader_special.s = 0;
1761d5f177d3SPaul E. McKenney 	INIT_LIST_HEAD(&p->trc_holdout_list);
1762d5f177d3SPaul E. McKenney #endif /* #ifdef CONFIG_TASKS_TRACE_RCU */
17636bfbaa51SIngo Molnar }
17646bfbaa51SIngo Molnar 
17653695eae5SChristian Brauner struct pid *pidfd_pid(const struct file *file)
17663695eae5SChristian Brauner {
17673695eae5SChristian Brauner 	if (file->f_op == &pidfd_fops)
17683695eae5SChristian Brauner 		return file->private_data;
17693695eae5SChristian Brauner 
17703695eae5SChristian Brauner 	return ERR_PTR(-EBADF);
17713695eae5SChristian Brauner }
17723695eae5SChristian Brauner 
1773b3e58382SChristian Brauner static int pidfd_release(struct inode *inode, struct file *file)
1774b3e58382SChristian Brauner {
1775b3e58382SChristian Brauner 	struct pid *pid = file->private_data;
1776b3e58382SChristian Brauner 
1777b3e58382SChristian Brauner 	file->private_data = NULL;
1778b3e58382SChristian Brauner 	put_pid(pid);
1779b3e58382SChristian Brauner 	return 0;
1780b3e58382SChristian Brauner }
1781b3e58382SChristian Brauner 
1782b3e58382SChristian Brauner #ifdef CONFIG_PROC_FS
178315d42eb2SChristian Kellner /**
178415d42eb2SChristian Kellner  * pidfd_show_fdinfo - print information about a pidfd
178515d42eb2SChristian Kellner  * @m: proc fdinfo file
178615d42eb2SChristian Kellner  * @f: file referencing a pidfd
178715d42eb2SChristian Kellner  *
178815d42eb2SChristian Kellner  * Pid:
178915d42eb2SChristian Kellner  * This function will print the pid that a given pidfd refers to in the
179015d42eb2SChristian Kellner  * pid namespace of the procfs instance.
179115d42eb2SChristian Kellner  * If the pid namespace of the process is not a descendant of the pid
179215d42eb2SChristian Kellner  * namespace of the procfs instance 0 will be shown as its pid. This is
179315d42eb2SChristian Kellner  * similar to calling getppid() on a process whose parent is outside of
179415d42eb2SChristian Kellner  * its pid namespace.
179515d42eb2SChristian Kellner  *
179615d42eb2SChristian Kellner  * NSpid:
179715d42eb2SChristian Kellner  * If pid namespaces are supported then this function will also print
179815d42eb2SChristian Kellner  * the pid of a given pidfd refers to for all descendant pid namespaces
179915d42eb2SChristian Kellner  * starting from the current pid namespace of the instance, i.e. the
180015d42eb2SChristian Kellner  * Pid field and the first entry in the NSpid field will be identical.
180115d42eb2SChristian Kellner  * If the pid namespace of the process is not a descendant of the pid
180215d42eb2SChristian Kellner  * namespace of the procfs instance 0 will be shown as its first NSpid
180315d42eb2SChristian Kellner  * entry and no others will be shown.
180415d42eb2SChristian Kellner  * Note that this differs from the Pid and NSpid fields in
180515d42eb2SChristian Kellner  * /proc/<pid>/status where Pid and NSpid are always shown relative to
180615d42eb2SChristian Kellner  * the  pid namespace of the procfs instance. The difference becomes
180715d42eb2SChristian Kellner  * obvious when sending around a pidfd between pid namespaces from a
1808a8ca6b13SXiaofeng Cao  * different branch of the tree, i.e. where no ancestral relation is
180915d42eb2SChristian Kellner  * present between the pid namespaces:
181015d42eb2SChristian Kellner  * - create two new pid namespaces ns1 and ns2 in the initial pid
181115d42eb2SChristian Kellner  *   namespace (also take care to create new mount namespaces in the
181215d42eb2SChristian Kellner  *   new pid namespace and mount procfs)
181315d42eb2SChristian Kellner  * - create a process with a pidfd in ns1
181415d42eb2SChristian Kellner  * - send pidfd from ns1 to ns2
181515d42eb2SChristian Kellner  * - read /proc/self/fdinfo/<pidfd> and observe that both Pid and NSpid
181615d42eb2SChristian Kellner  *   have exactly one entry, which is 0
181715d42eb2SChristian Kellner  */
1818b3e58382SChristian Brauner static void pidfd_show_fdinfo(struct seq_file *m, struct file *f)
1819b3e58382SChristian Brauner {
1820b3e58382SChristian Brauner 	struct pid *pid = f->private_data;
18213d6d8da4SChristian Brauner 	struct pid_namespace *ns;
18223d6d8da4SChristian Brauner 	pid_t nr = -1;
1823b3e58382SChristian Brauner 
18243d6d8da4SChristian Brauner 	if (likely(pid_has_task(pid, PIDTYPE_PID))) {
18259d78edeaSAlexey Gladkov 		ns = proc_pid_ns(file_inode(m->file)->i_sb);
18263d6d8da4SChristian Brauner 		nr = pid_nr_ns(pid, ns);
18273d6d8da4SChristian Brauner 	}
18283d6d8da4SChristian Brauner 
18293d6d8da4SChristian Brauner 	seq_put_decimal_ll(m, "Pid:\t", nr);
183015d42eb2SChristian Kellner 
183115d42eb2SChristian Kellner #ifdef CONFIG_PID_NS
18323d6d8da4SChristian Brauner 	seq_put_decimal_ll(m, "\nNSpid:\t", nr);
18333d6d8da4SChristian Brauner 	if (nr > 0) {
183415d42eb2SChristian Kellner 		int i;
183515d42eb2SChristian Kellner 
183615d42eb2SChristian Kellner 		/* If nr is non-zero it means that 'pid' is valid and that
183715d42eb2SChristian Kellner 		 * ns, i.e. the pid namespace associated with the procfs
183815d42eb2SChristian Kellner 		 * instance, is in the pid namespace hierarchy of pid.
183915d42eb2SChristian Kellner 		 * Start at one below the already printed level.
184015d42eb2SChristian Kellner 		 */
184115d42eb2SChristian Kellner 		for (i = ns->level + 1; i <= pid->level; i++)
18423d6d8da4SChristian Brauner 			seq_put_decimal_ll(m, "\t", pid->numbers[i].nr);
184315d42eb2SChristian Kellner 	}
184415d42eb2SChristian Kellner #endif
1845b3e58382SChristian Brauner 	seq_putc(m, '\n');
1846b3e58382SChristian Brauner }
1847b3e58382SChristian Brauner #endif
1848b3e58382SChristian Brauner 
1849b53b0b9dSJoel Fernandes (Google) /*
1850b53b0b9dSJoel Fernandes (Google)  * Poll support for process exit notification.
1851b53b0b9dSJoel Fernandes (Google)  */
18529e77716aSLuc Van Oostenryck static __poll_t pidfd_poll(struct file *file, struct poll_table_struct *pts)
1853b53b0b9dSJoel Fernandes (Google) {
1854b53b0b9dSJoel Fernandes (Google) 	struct pid *pid = file->private_data;
18559e77716aSLuc Van Oostenryck 	__poll_t poll_flags = 0;
1856b53b0b9dSJoel Fernandes (Google) 
1857b53b0b9dSJoel Fernandes (Google) 	poll_wait(file, &pid->wait_pidfd, pts);
1858b53b0b9dSJoel Fernandes (Google) 
1859b53b0b9dSJoel Fernandes (Google) 	/*
1860b53b0b9dSJoel Fernandes (Google) 	 * Inform pollers only when the whole thread group exits.
1861b53b0b9dSJoel Fernandes (Google) 	 * If the thread group leader exits before all other threads in the
1862b53b0b9dSJoel Fernandes (Google) 	 * group, then poll(2) should block, similar to the wait(2) family.
1863b53b0b9dSJoel Fernandes (Google) 	 */
186438fd525aSEric W. Biederman 	if (thread_group_exited(pid))
18659e77716aSLuc Van Oostenryck 		poll_flags = EPOLLIN | EPOLLRDNORM;
1866b53b0b9dSJoel Fernandes (Google) 
1867b53b0b9dSJoel Fernandes (Google) 	return poll_flags;
1868b53b0b9dSJoel Fernandes (Google) }
1869b53b0b9dSJoel Fernandes (Google) 
1870b3e58382SChristian Brauner const struct file_operations pidfd_fops = {
1871b3e58382SChristian Brauner 	.release = pidfd_release,
1872b53b0b9dSJoel Fernandes (Google) 	.poll = pidfd_poll,
1873b3e58382SChristian Brauner #ifdef CONFIG_PROC_FS
1874b3e58382SChristian Brauner 	.show_fdinfo = pidfd_show_fdinfo,
1875b3e58382SChristian Brauner #endif
1876b3e58382SChristian Brauner };
1877b3e58382SChristian Brauner 
1878c3f3ce04SAndrea Arcangeli static void __delayed_free_task(struct rcu_head *rhp)
1879c3f3ce04SAndrea Arcangeli {
1880c3f3ce04SAndrea Arcangeli 	struct task_struct *tsk = container_of(rhp, struct task_struct, rcu);
1881c3f3ce04SAndrea Arcangeli 
1882c3f3ce04SAndrea Arcangeli 	free_task(tsk);
1883c3f3ce04SAndrea Arcangeli }
1884c3f3ce04SAndrea Arcangeli 
1885c3f3ce04SAndrea Arcangeli static __always_inline void delayed_free_task(struct task_struct *tsk)
1886c3f3ce04SAndrea Arcangeli {
1887c3f3ce04SAndrea Arcangeli 	if (IS_ENABLED(CONFIG_MEMCG))
1888c3f3ce04SAndrea Arcangeli 		call_rcu(&tsk->rcu, __delayed_free_task);
1889c3f3ce04SAndrea Arcangeli 	else
1890c3f3ce04SAndrea Arcangeli 		free_task(tsk);
1891c3f3ce04SAndrea Arcangeli }
1892c3f3ce04SAndrea Arcangeli 
189367197a4fSSuren Baghdasaryan static void copy_oom_score_adj(u64 clone_flags, struct task_struct *tsk)
189467197a4fSSuren Baghdasaryan {
189567197a4fSSuren Baghdasaryan 	/* Skip if kernel thread */
189667197a4fSSuren Baghdasaryan 	if (!tsk->mm)
189767197a4fSSuren Baghdasaryan 		return;
189867197a4fSSuren Baghdasaryan 
189967197a4fSSuren Baghdasaryan 	/* Skip if spawning a thread or using vfork */
190067197a4fSSuren Baghdasaryan 	if ((clone_flags & (CLONE_VM | CLONE_THREAD | CLONE_VFORK)) != CLONE_VM)
190167197a4fSSuren Baghdasaryan 		return;
190267197a4fSSuren Baghdasaryan 
190367197a4fSSuren Baghdasaryan 	/* We need to synchronize with __set_oom_adj */
190467197a4fSSuren Baghdasaryan 	mutex_lock(&oom_adj_mutex);
190567197a4fSSuren Baghdasaryan 	set_bit(MMF_MULTIPROCESS, &tsk->mm->flags);
190667197a4fSSuren Baghdasaryan 	/* Update the values in case they were changed after copy_signal */
190767197a4fSSuren Baghdasaryan 	tsk->signal->oom_score_adj = current->signal->oom_score_adj;
190867197a4fSSuren Baghdasaryan 	tsk->signal->oom_score_adj_min = current->signal->oom_score_adj_min;
190967197a4fSSuren Baghdasaryan 	mutex_unlock(&oom_adj_mutex);
191067197a4fSSuren Baghdasaryan }
191167197a4fSSuren Baghdasaryan 
1912f06febc9SFrank Mayhar /*
19131da177e4SLinus Torvalds  * This creates a new process as a copy of the old one,
19141da177e4SLinus Torvalds  * but does not actually start it yet.
19151da177e4SLinus Torvalds  *
19161da177e4SLinus Torvalds  * It copies the registers, and all the appropriate
19171da177e4SLinus Torvalds  * parts of the process environment (as per the clone
19181da177e4SLinus Torvalds  * flags). The actual kick-off is left to the caller.
19191da177e4SLinus Torvalds  */
19200766f788SEmese Revfy static __latent_entropy struct task_struct *copy_process(
192109a05394SRoland McGrath 					struct pid *pid,
19223033f14aSJosh Triplett 					int trace,
19237f192e3cSChristian Brauner 					int node,
19247f192e3cSChristian Brauner 					struct kernel_clone_args *args)
19251da177e4SLinus Torvalds {
1926b3e58382SChristian Brauner 	int pidfd = -1, retval;
1927a24efe62SMariusz Kozlowski 	struct task_struct *p;
1928c3ad2c3bSEric W. Biederman 	struct multiprocess_signals delayed;
19296fd2fe49SAl Viro 	struct file *pidfile = NULL;
19307f192e3cSChristian Brauner 	u64 clone_flags = args->flags;
1931769071acSAndrei Vagin 	struct nsproxy *nsp = current->nsproxy;
19321da177e4SLinus Torvalds 
1933667b6094SMarcos Paulo de Souza 	/*
1934667b6094SMarcos Paulo de Souza 	 * Don't allow sharing the root directory with processes in a different
1935667b6094SMarcos Paulo de Souza 	 * namespace
1936667b6094SMarcos Paulo de Souza 	 */
19371da177e4SLinus Torvalds 	if ((clone_flags & (CLONE_NEWNS|CLONE_FS)) == (CLONE_NEWNS|CLONE_FS))
19381da177e4SLinus Torvalds 		return ERR_PTR(-EINVAL);
19391da177e4SLinus Torvalds 
1940e66eded8SEric W. Biederman 	if ((clone_flags & (CLONE_NEWUSER|CLONE_FS)) == (CLONE_NEWUSER|CLONE_FS))
1941e66eded8SEric W. Biederman 		return ERR_PTR(-EINVAL);
1942e66eded8SEric W. Biederman 
19431da177e4SLinus Torvalds 	/*
19441da177e4SLinus Torvalds 	 * Thread groups must share signals as well, and detached threads
19451da177e4SLinus Torvalds 	 * can only be started up within the thread group.
19461da177e4SLinus Torvalds 	 */
19471da177e4SLinus Torvalds 	if ((clone_flags & CLONE_THREAD) && !(clone_flags & CLONE_SIGHAND))
19481da177e4SLinus Torvalds 		return ERR_PTR(-EINVAL);
19491da177e4SLinus Torvalds 
19501da177e4SLinus Torvalds 	/*
19511da177e4SLinus Torvalds 	 * Shared signal handlers imply shared VM. By way of the above,
19521da177e4SLinus Torvalds 	 * thread groups also imply shared VM. Blocking this case allows
19531da177e4SLinus Torvalds 	 * for various simplifications in other code.
19541da177e4SLinus Torvalds 	 */
19551da177e4SLinus Torvalds 	if ((clone_flags & CLONE_SIGHAND) && !(clone_flags & CLONE_VM))
19561da177e4SLinus Torvalds 		return ERR_PTR(-EINVAL);
19571da177e4SLinus Torvalds 
1958123be07bSSukadev Bhattiprolu 	/*
1959123be07bSSukadev Bhattiprolu 	 * Siblings of global init remain as zombies on exit since they are
1960123be07bSSukadev Bhattiprolu 	 * not reaped by their parent (swapper). To solve this and to avoid
1961123be07bSSukadev Bhattiprolu 	 * multi-rooted process trees, prevent global and container-inits
1962123be07bSSukadev Bhattiprolu 	 * from creating siblings.
1963123be07bSSukadev Bhattiprolu 	 */
1964123be07bSSukadev Bhattiprolu 	if ((clone_flags & CLONE_PARENT) &&
1965123be07bSSukadev Bhattiprolu 				current->signal->flags & SIGNAL_UNKILLABLE)
1966123be07bSSukadev Bhattiprolu 		return ERR_PTR(-EINVAL);
1967123be07bSSukadev Bhattiprolu 
19688382fcacSEric W. Biederman 	/*
196940a0d32dSOleg Nesterov 	 * If the new process will be in a different pid or user namespace
1970faf00da5SEric W. Biederman 	 * do not allow it to share a thread group with the forking task.
19718382fcacSEric W. Biederman 	 */
1972faf00da5SEric W. Biederman 	if (clone_flags & CLONE_THREAD) {
197340a0d32dSOleg Nesterov 		if ((clone_flags & (CLONE_NEWUSER | CLONE_NEWPID)) ||
1974769071acSAndrei Vagin 		    (task_active_pid_ns(current) != nsp->pid_ns_for_children))
1975769071acSAndrei Vagin 			return ERR_PTR(-EINVAL);
1976769071acSAndrei Vagin 	}
1977769071acSAndrei Vagin 
1978769071acSAndrei Vagin 	/*
1979769071acSAndrei Vagin 	 * If the new process will be in a different time namespace
1980769071acSAndrei Vagin 	 * do not allow it to share VM or a thread group with the forking task.
1981769071acSAndrei Vagin 	 */
1982769071acSAndrei Vagin 	if (clone_flags & (CLONE_THREAD | CLONE_VM)) {
1983769071acSAndrei Vagin 		if (nsp->time_ns != nsp->time_ns_for_children)
19848382fcacSEric W. Biederman 			return ERR_PTR(-EINVAL);
198540a0d32dSOleg Nesterov 	}
19868382fcacSEric W. Biederman 
1987b3e58382SChristian Brauner 	if (clone_flags & CLONE_PIDFD) {
1988b3e58382SChristian Brauner 		/*
1989b3e58382SChristian Brauner 		 * - CLONE_DETACHED is blocked so that we can potentially
1990b3e58382SChristian Brauner 		 *   reuse it later for CLONE_PIDFD.
1991b3e58382SChristian Brauner 		 * - CLONE_THREAD is blocked until someone really needs it.
1992b3e58382SChristian Brauner 		 */
19937f192e3cSChristian Brauner 		if (clone_flags & (CLONE_DETACHED | CLONE_THREAD))
1994b3e58382SChristian Brauner 			return ERR_PTR(-EINVAL);
1995b3e58382SChristian Brauner 	}
1996b3e58382SChristian Brauner 
1997c3ad2c3bSEric W. Biederman 	/*
1998c3ad2c3bSEric W. Biederman 	 * Force any signals received before this point to be delivered
1999c3ad2c3bSEric W. Biederman 	 * before the fork happens.  Collect up signals sent to multiple
2000c3ad2c3bSEric W. Biederman 	 * processes that happen during the fork and delay them so that
2001c3ad2c3bSEric W. Biederman 	 * they appear to happen after the fork.
2002c3ad2c3bSEric W. Biederman 	 */
2003c3ad2c3bSEric W. Biederman 	sigemptyset(&delayed.signal);
2004c3ad2c3bSEric W. Biederman 	INIT_HLIST_NODE(&delayed.node);
2005c3ad2c3bSEric W. Biederman 
2006c3ad2c3bSEric W. Biederman 	spin_lock_irq(&current->sighand->siglock);
2007c3ad2c3bSEric W. Biederman 	if (!(clone_flags & CLONE_THREAD))
2008c3ad2c3bSEric W. Biederman 		hlist_add_head(&delayed.node, &current->signal->multiprocess);
2009c3ad2c3bSEric W. Biederman 	recalc_sigpending();
2010c3ad2c3bSEric W. Biederman 	spin_unlock_irq(&current->sighand->siglock);
2011c3ad2c3bSEric W. Biederman 	retval = -ERESTARTNOINTR;
201266ae0d1eSJens Axboe 	if (task_sigpending(current))
2013c3ad2c3bSEric W. Biederman 		goto fork_out;
2014c3ad2c3bSEric W. Biederman 
20151da177e4SLinus Torvalds 	retval = -ENOMEM;
2016725fc629SAndi Kleen 	p = dup_task_struct(current, node);
20171da177e4SLinus Torvalds 	if (!p)
20181da177e4SLinus Torvalds 		goto fork_out;
2019b16b3855SJens Axboe 	if (args->io_thread) {
2020b16b3855SJens Axboe 		/*
2021b16b3855SJens Axboe 		 * Mark us an IO worker, and block any signal that isn't
2022b16b3855SJens Axboe 		 * fatal or STOP
2023b16b3855SJens Axboe 		 */
2024cc440e87SJens Axboe 		p->flags |= PF_IO_WORKER;
2025b16b3855SJens Axboe 		siginitsetinv(&p->blocked, sigmask(SIGKILL)|sigmask(SIGSTOP));
2026b16b3855SJens Axboe 	}
20271da177e4SLinus Torvalds 
20287f192e3cSChristian Brauner 	p->set_child_tid = (clone_flags & CLONE_CHILD_SETTID) ? args->child_tid : NULL;
20294d6501dcSVegard Nossum 	/*
20304d6501dcSVegard Nossum 	 * Clear TID on mm_release()?
20314d6501dcSVegard Nossum 	 */
20327f192e3cSChristian Brauner 	p->clear_child_tid = (clone_flags & CLONE_CHILD_CLEARTID) ? args->child_tid : NULL;
20334d6501dcSVegard Nossum 
2034f7e8b616SSteven Rostedt 	ftrace_graph_init_task(p);
2035f7e8b616SSteven Rostedt 
2036bea493a0SPeter Zijlstra 	rt_mutex_init_task(p);
2037bea493a0SPeter Zijlstra 
2038a21ee605SPeter Zijlstra 	lockdep_assert_irqs_enabled();
2039d12c1a37SIngo Molnar #ifdef CONFIG_PROVE_LOCKING
2040de30a2b3SIngo Molnar 	DEBUG_LOCKS_WARN_ON(!p->softirqs_enabled);
2041de30a2b3SIngo Molnar #endif
20428f2f9c4dSEric W. Biederman 	retval = copy_creds(p, clone_flags);
20438f2f9c4dSEric W. Biederman 	if (retval < 0)
20448f2f9c4dSEric W. Biederman 		goto bad_fork_free;
20458f2f9c4dSEric W. Biederman 
20461da177e4SLinus Torvalds 	retval = -EAGAIN;
204721d1c5e3SAlexey Gladkov 	if (is_ucounts_overlimit(task_ucounts(p), UCOUNT_RLIMIT_NPROC, rlimit(RLIMIT_NPROC))) {
2048b57922b6SEric Paris 		if (p->real_cred->user != INIT_USER &&
2049b57922b6SEric Paris 		    !capable(CAP_SYS_RESOURCE) && !capable(CAP_SYS_ADMIN))
20508f2f9c4dSEric W. Biederman 			goto bad_fork_cleanup_count;
20511da177e4SLinus Torvalds 	}
205272fa5997SVasiliy Kulikov 	current->flags &= ~PF_NPROC_EXCEEDED;
20531da177e4SLinus Torvalds 
20541da177e4SLinus Torvalds 	/*
20551da177e4SLinus Torvalds 	 * If multiple threads are within copy_process(), then this check
20561da177e4SLinus Torvalds 	 * triggers too late. This doesn't hurt, the check is only there
20571da177e4SLinus Torvalds 	 * to stop root fork bombs.
20581da177e4SLinus Torvalds 	 */
205904ec93feSLi Zefan 	retval = -EAGAIN;
2060c17d1a3aSWeilong Chen 	if (data_race(nr_threads >= max_threads))
20611da177e4SLinus Torvalds 		goto bad_fork_cleanup_count;
20621da177e4SLinus Torvalds 
2063ca74e92bSShailabh Nagar 	delayacct_tsk_init(p);	/* Must remain after dup_task_struct() */
2064a8ea6fc9SFrederic Weisbecker 	p->flags &= ~(PF_SUPERPRIV | PF_WQ_WORKER | PF_IDLE | PF_NO_SETAFFINITY);
2065514ddb44SDavid Rientjes 	p->flags |= PF_FORKNOEXEC;
20661da177e4SLinus Torvalds 	INIT_LIST_HEAD(&p->children);
20671da177e4SLinus Torvalds 	INIT_LIST_HEAD(&p->sibling);
2068f41d911fSPaul E. McKenney 	rcu_copy_process(p);
20691da177e4SLinus Torvalds 	p->vfork_done = NULL;
20701da177e4SLinus Torvalds 	spin_lock_init(&p->alloc_lock);
20711da177e4SLinus Torvalds 
20721da177e4SLinus Torvalds 	init_sigpending(&p->pending);
20731da177e4SLinus Torvalds 
207464861634SMartin Schwidefsky 	p->utime = p->stime = p->gtime = 0;
207540565b5aSStanislaw Gruszka #ifdef CONFIG_ARCH_HAS_SCALED_CPUTIME
207664861634SMartin Schwidefsky 	p->utimescaled = p->stimescaled = 0;
207740565b5aSStanislaw Gruszka #endif
20789d7fb042SPeter Zijlstra 	prev_cputime_init(&p->prev_cputime);
20799d7fb042SPeter Zijlstra 
20806a61671bSFrederic Weisbecker #ifdef CONFIG_VIRT_CPU_ACCOUNTING_GEN
2081bac5b6b6SFrederic Weisbecker 	seqcount_init(&p->vtime.seqcount);
2082bac5b6b6SFrederic Weisbecker 	p->vtime.starttime = 0;
2083bac5b6b6SFrederic Weisbecker 	p->vtime.state = VTIME_INACTIVE;
20846a61671bSFrederic Weisbecker #endif
20856a61671bSFrederic Weisbecker 
20860f212204SJens Axboe #ifdef CONFIG_IO_URING
20870f212204SJens Axboe 	p->io_uring = NULL;
20880f212204SJens Axboe #endif
20890f212204SJens Axboe 
2090a3a2e76cSKAMEZAWA Hiroyuki #if defined(SPLIT_RSS_COUNTING)
2091a3a2e76cSKAMEZAWA Hiroyuki 	memset(&p->rss_stat, 0, sizeof(p->rss_stat));
2092a3a2e76cSKAMEZAWA Hiroyuki #endif
2093172ba844SBalbir Singh 
20946976675dSArjan van de Ven 	p->default_timer_slack_ns = current->timer_slack_ns;
20956976675dSArjan van de Ven 
2096eb414681SJohannes Weiner #ifdef CONFIG_PSI
2097eb414681SJohannes Weiner 	p->psi_flags = 0;
2098eb414681SJohannes Weiner #endif
2099eb414681SJohannes Weiner 
21005995477aSAndrea Righi 	task_io_accounting_init(&p->ioac);
21011da177e4SLinus Torvalds 	acct_clear_integrals(p);
21021da177e4SLinus Torvalds 
21033a245c0fSThomas Gleixner 	posix_cputimers_init(&p->posix_cputimers);
21041da177e4SLinus Torvalds 
21051da177e4SLinus Torvalds 	p->io_context = NULL;
2106c0b0ae8aSRichard Guy Briggs 	audit_set_context(p, NULL);
2107b4f48b63SPaul Menage 	cgroup_fork(p);
210840966e31SEric W. Biederman 	if (p->flags & PF_KTHREAD) {
210940966e31SEric W. Biederman 		if (!set_kthread_struct(p))
2110ff8288ffSEric W. Biederman 			goto bad_fork_cleanup_delayacct;
211140966e31SEric W. Biederman 	}
21121da177e4SLinus Torvalds #ifdef CONFIG_NUMA
2113846a16bfSLee Schermerhorn 	p->mempolicy = mpol_dup(p->mempolicy);
21141da177e4SLinus Torvalds 	if (IS_ERR(p->mempolicy)) {
21151da177e4SLinus Torvalds 		retval = PTR_ERR(p->mempolicy);
21161da177e4SLinus Torvalds 		p->mempolicy = NULL;
2117ff8288ffSEric W. Biederman 		goto bad_fork_cleanup_delayacct;
21181da177e4SLinus Torvalds 	}
21191da177e4SLinus Torvalds #endif
2120778d3b0fSMichal Hocko #ifdef CONFIG_CPUSETS
2121778d3b0fSMichal Hocko 	p->cpuset_mem_spread_rotor = NUMA_NO_NODE;
2122778d3b0fSMichal Hocko 	p->cpuset_slab_spread_rotor = NUMA_NO_NODE;
2123b7505861SAhmed S. Darwish 	seqcount_spinlock_init(&p->mems_allowed_seq, &p->alloc_lock);
2124778d3b0fSMichal Hocko #endif
2125de30a2b3SIngo Molnar #ifdef CONFIG_TRACE_IRQFLAGS
21260584df9cSMarco Elver 	memset(&p->irqtrace, 0, sizeof(p->irqtrace));
21270584df9cSMarco Elver 	p->irqtrace.hardirq_disable_ip	= _THIS_IP_;
21280584df9cSMarco Elver 	p->irqtrace.softirq_enable_ip	= _THIS_IP_;
2129de30a2b3SIngo Molnar 	p->softirqs_enabled		= 1;
2130de30a2b3SIngo Molnar 	p->softirq_context		= 0;
2131de30a2b3SIngo Molnar #endif
21328bcbde54SDavid Hildenbrand 
21338bcbde54SDavid Hildenbrand 	p->pagefault_disabled = 0;
21348bcbde54SDavid Hildenbrand 
2135fbb9ce95SIngo Molnar #ifdef CONFIG_LOCKDEP
2136b09be676SByungchul Park 	lockdep_init_task(p);
2137fbb9ce95SIngo Molnar #endif
21381da177e4SLinus Torvalds 
2139408894eeSIngo Molnar #ifdef CONFIG_DEBUG_MUTEXES
2140408894eeSIngo Molnar 	p->blocked_on = NULL; /* not blocked yet */
2141408894eeSIngo Molnar #endif
2142cafe5635SKent Overstreet #ifdef CONFIG_BCACHE
2143cafe5635SKent Overstreet 	p->sequential_io	= 0;
2144cafe5635SKent Overstreet 	p->sequential_io_avg	= 0;
2145cafe5635SKent Overstreet #endif
2146a10787e6SSong Liu #ifdef CONFIG_BPF_SYSCALL
2147a10787e6SSong Liu 	RCU_INIT_POINTER(p->bpf_storage, NULL);
2148c7603cfaSAndrii Nakryiko 	p->bpf_ctx = NULL;
2149a10787e6SSong Liu #endif
21500f481406SMarkus Metzger 
21513c90e6e9SSrivatsa Vaddagiri 	/* Perform scheduler related setup. Assign this task to a CPU. */
2152aab03e05SDario Faggioli 	retval = sched_fork(clone_flags, p);
2153aab03e05SDario Faggioli 	if (retval)
2154aab03e05SDario Faggioli 		goto bad_fork_cleanup_policy;
21556ab423e0SPeter Zijlstra 
21562b26f0aaSMarco Elver 	retval = perf_event_init_task(p, clone_flags);
21576ab423e0SPeter Zijlstra 	if (retval)
21586ab423e0SPeter Zijlstra 		goto bad_fork_cleanup_policy;
2159fb0a685cSDaniel Rebelo de Oliveira 	retval = audit_alloc(p);
2160fb0a685cSDaniel Rebelo de Oliveira 	if (retval)
21616c72e350SPeter Zijlstra 		goto bad_fork_cleanup_perf;
21621da177e4SLinus Torvalds 	/* copy all the process information */
2163ab602f79SJack Miller 	shm_init_task(p);
2164e4e55b47STetsuo Handa 	retval = security_task_alloc(p, clone_flags);
2165fb0a685cSDaniel Rebelo de Oliveira 	if (retval)
21661da177e4SLinus Torvalds 		goto bad_fork_cleanup_audit;
2167e4e55b47STetsuo Handa 	retval = copy_semundo(clone_flags, p);
2168e4e55b47STetsuo Handa 	if (retval)
2169e4e55b47STetsuo Handa 		goto bad_fork_cleanup_security;
2170fb0a685cSDaniel Rebelo de Oliveira 	retval = copy_files(clone_flags, p);
2171fb0a685cSDaniel Rebelo de Oliveira 	if (retval)
21721da177e4SLinus Torvalds 		goto bad_fork_cleanup_semundo;
2173fb0a685cSDaniel Rebelo de Oliveira 	retval = copy_fs(clone_flags, p);
2174fb0a685cSDaniel Rebelo de Oliveira 	if (retval)
21751da177e4SLinus Torvalds 		goto bad_fork_cleanup_files;
2176fb0a685cSDaniel Rebelo de Oliveira 	retval = copy_sighand(clone_flags, p);
2177fb0a685cSDaniel Rebelo de Oliveira 	if (retval)
21781da177e4SLinus Torvalds 		goto bad_fork_cleanup_fs;
2179fb0a685cSDaniel Rebelo de Oliveira 	retval = copy_signal(clone_flags, p);
2180fb0a685cSDaniel Rebelo de Oliveira 	if (retval)
21811da177e4SLinus Torvalds 		goto bad_fork_cleanup_sighand;
2182fb0a685cSDaniel Rebelo de Oliveira 	retval = copy_mm(clone_flags, p);
2183fb0a685cSDaniel Rebelo de Oliveira 	if (retval)
21841da177e4SLinus Torvalds 		goto bad_fork_cleanup_signal;
2185fb0a685cSDaniel Rebelo de Oliveira 	retval = copy_namespaces(clone_flags, p);
2186fb0a685cSDaniel Rebelo de Oliveira 	if (retval)
2187d84f4f99SDavid Howells 		goto bad_fork_cleanup_mm;
2188fb0a685cSDaniel Rebelo de Oliveira 	retval = copy_io(clone_flags, p);
2189fb0a685cSDaniel Rebelo de Oliveira 	if (retval)
2190fd0928dfSJens Axboe 		goto bad_fork_cleanup_namespaces;
2191714acdbdSChristian Brauner 	retval = copy_thread(clone_flags, args->stack, args->stack_size, p, args->tls);
21921da177e4SLinus Torvalds 	if (retval)
2193fd0928dfSJens Axboe 		goto bad_fork_cleanup_io;
21941da177e4SLinus Torvalds 
2195afaef01cSAlexander Popov 	stackleak_task_init(p);
2196afaef01cSAlexander Popov 
2197425fb2b4SPavel Emelyanov 	if (pid != &init_struct_pid) {
219849cb2fc4SAdrian Reber 		pid = alloc_pid(p->nsproxy->pid_ns_for_children, args->set_tid,
219949cb2fc4SAdrian Reber 				args->set_tid_size);
220035f71bc0SMichal Hocko 		if (IS_ERR(pid)) {
220135f71bc0SMichal Hocko 			retval = PTR_ERR(pid);
22020740aa5fSJiri Slaby 			goto bad_fork_cleanup_thread;
2203425fb2b4SPavel Emelyanov 		}
220435f71bc0SMichal Hocko 	}
2205425fb2b4SPavel Emelyanov 
2206b3e58382SChristian Brauner 	/*
2207b3e58382SChristian Brauner 	 * This has to happen after we've potentially unshared the file
2208b3e58382SChristian Brauner 	 * descriptor table (so that the pidfd doesn't leak into the child
2209b3e58382SChristian Brauner 	 * if the fd table isn't shared).
2210b3e58382SChristian Brauner 	 */
2211b3e58382SChristian Brauner 	if (clone_flags & CLONE_PIDFD) {
22126fd2fe49SAl Viro 		retval = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
2213b3e58382SChristian Brauner 		if (retval < 0)
2214b3e58382SChristian Brauner 			goto bad_fork_free_pid;
2215b3e58382SChristian Brauner 
2216b3e58382SChristian Brauner 		pidfd = retval;
22176fd2fe49SAl Viro 
22186fd2fe49SAl Viro 		pidfile = anon_inode_getfile("[pidfd]", &pidfd_fops, pid,
22196fd2fe49SAl Viro 					      O_RDWR | O_CLOEXEC);
22206fd2fe49SAl Viro 		if (IS_ERR(pidfile)) {
22216fd2fe49SAl Viro 			put_unused_fd(pidfd);
222228dd29c0SChristian Brauner 			retval = PTR_ERR(pidfile);
22236fd2fe49SAl Viro 			goto bad_fork_free_pid;
22246fd2fe49SAl Viro 		}
22256fd2fe49SAl Viro 		get_pid(pid);	/* held by pidfile now */
22266fd2fe49SAl Viro 
22277f192e3cSChristian Brauner 		retval = put_user(pidfd, args->pidfd);
2228b3e58382SChristian Brauner 		if (retval)
2229b3e58382SChristian Brauner 			goto bad_fork_put_pidfd;
2230b3e58382SChristian Brauner 	}
2231b3e58382SChristian Brauner 
223273c10101SJens Axboe #ifdef CONFIG_BLOCK
223373c10101SJens Axboe 	p->plug = NULL;
223473c10101SJens Axboe #endif
2235ba31c1a4SThomas Gleixner 	futex_init_task(p);
2236ba31c1a4SThomas Gleixner 
22371da177e4SLinus Torvalds 	/*
2238f9a3879aSGOTO Masanori 	 * sigaltstack should be cleared when sharing the same VM
2239f9a3879aSGOTO Masanori 	 */
2240f9a3879aSGOTO Masanori 	if ((clone_flags & (CLONE_VM|CLONE_VFORK)) == CLONE_VM)
22412a742138SStas Sergeev 		sas_ss_reset(p);
2242f9a3879aSGOTO Masanori 
2243f9a3879aSGOTO Masanori 	/*
22446580807dSOleg Nesterov 	 * Syscall tracing and stepping should be turned off in the
22456580807dSOleg Nesterov 	 * child regardless of CLONE_PTRACE.
22461da177e4SLinus Torvalds 	 */
22476580807dSOleg Nesterov 	user_disable_single_step(p);
224864c19ba2SGabriel Krisman Bertazi 	clear_task_syscall_work(p, SYSCALL_TRACE);
224964eb35f7SGabriel Krisman Bertazi #if defined(CONFIG_GENERIC_ENTRY) || defined(TIF_SYSCALL_EMU)
225064eb35f7SGabriel Krisman Bertazi 	clear_task_syscall_work(p, SYSCALL_EMU);
2251ed75e8d5SLaurent Vivier #endif
2252e02c9b0dSLin Feng 	clear_tsk_latency_tracing(p);
22531da177e4SLinus Torvalds 
22541da177e4SLinus Torvalds 	/* ok, now we should be set up.. */
225518c830dfSOleg Nesterov 	p->pid = pid_nr(pid);
225618c830dfSOleg Nesterov 	if (clone_flags & CLONE_THREAD) {
225718c830dfSOleg Nesterov 		p->group_leader = current->group_leader;
225818c830dfSOleg Nesterov 		p->tgid = current->tgid;
225918c830dfSOleg Nesterov 	} else {
226018c830dfSOleg Nesterov 		p->group_leader = p;
226118c830dfSOleg Nesterov 		p->tgid = p->pid;
226218c830dfSOleg Nesterov 	}
22635f8aadd8SOleg Nesterov 
22649d823e8fSWu Fengguang 	p->nr_dirtied = 0;
22659d823e8fSWu Fengguang 	p->nr_dirtied_pause = 128 >> (PAGE_SHIFT - 10);
226683712358SWu Fengguang 	p->dirty_paused_when = 0;
22679d823e8fSWu Fengguang 
2268bb8cbbfeSOleg Nesterov 	p->pdeath_signal = 0;
226947e65328SOleg Nesterov 	INIT_LIST_HEAD(&p->thread_group);
2270158e1645SAl Viro 	p->task_works = NULL;
2271ca7752caSMichael Pratt 	clear_posix_cputimers_work(p);
22721da177e4SLinus Torvalds 
2273d741bf41SPeter Zijlstra #ifdef CONFIG_KRETPROBES
2274d741bf41SPeter Zijlstra 	p->kretprobe_instances.first = NULL;
2275d741bf41SPeter Zijlstra #endif
2276d741bf41SPeter Zijlstra 
227718c830dfSOleg Nesterov 	/*
22787e47682eSAleksa Sarai 	 * Ensure that the cgroup subsystem policies allow the new process to be
22797b7b8a2cSRandy Dunlap 	 * forked. It should be noted that the new process's css_set can be changed
22807e47682eSAleksa Sarai 	 * between here and cgroup_post_fork() if an organisation operation is in
22817e47682eSAleksa Sarai 	 * progress.
22827e47682eSAleksa Sarai 	 */
2283ef2c41cfSChristian Brauner 	retval = cgroup_can_fork(p, args);
22847e47682eSAleksa Sarai 	if (retval)
22855a5cf5cbSChristian Brauner 		goto bad_fork_put_pidfd;
22867e47682eSAleksa Sarai 
22877e47682eSAleksa Sarai 	/*
2288b1e82065SPeter Zijlstra 	 * Now that the cgroups are pinned, re-clone the parent cgroup and put
2289b1e82065SPeter Zijlstra 	 * the new task on the correct runqueue. All this *before* the task
2290b1e82065SPeter Zijlstra 	 * becomes visible.
2291b1e82065SPeter Zijlstra 	 *
2292b1e82065SPeter Zijlstra 	 * This isn't part of ->can_fork() because while the re-cloning is
2293b1e82065SPeter Zijlstra 	 * cgroup specific, it unconditionally needs to place the task on a
2294b1e82065SPeter Zijlstra 	 * runqueue.
2295b1e82065SPeter Zijlstra 	 */
2296b1e82065SPeter Zijlstra 	sched_cgroup_fork(p, args);
2297b1e82065SPeter Zijlstra 
2298b1e82065SPeter Zijlstra 	/*
22997b558513SDavid Herrmann 	 * From this point on we must avoid any synchronous user-space
23007b558513SDavid Herrmann 	 * communication until we take the tasklist-lock. In particular, we do
23017b558513SDavid Herrmann 	 * not want user-space to be able to predict the process start-time by
23027b558513SDavid Herrmann 	 * stalling fork(2) after we recorded the start_time but before it is
23037b558513SDavid Herrmann 	 * visible to the system.
23047b558513SDavid Herrmann 	 */
23057b558513SDavid Herrmann 
23067b558513SDavid Herrmann 	p->start_time = ktime_get_ns();
2307cf25e24dSPeter Zijlstra 	p->start_boottime = ktime_get_boottime_ns();
23087b558513SDavid Herrmann 
23097b558513SDavid Herrmann 	/*
231018c830dfSOleg Nesterov 	 * Make it visible to the rest of the system, but dont wake it up yet.
231118c830dfSOleg Nesterov 	 * Need tasklist lock for parent etc handling!
231218c830dfSOleg Nesterov 	 */
23131da177e4SLinus Torvalds 	write_lock_irq(&tasklist_lock);
23141da177e4SLinus Torvalds 
23151da177e4SLinus Torvalds 	/* CLONE_PARENT re-uses the old parent */
23162d5516cbSOleg Nesterov 	if (clone_flags & (CLONE_PARENT|CLONE_THREAD)) {
23171da177e4SLinus Torvalds 		p->real_parent = current->real_parent;
23182d5516cbSOleg Nesterov 		p->parent_exec_id = current->parent_exec_id;
2319b4e00444SEddy Wu 		if (clone_flags & CLONE_THREAD)
2320b4e00444SEddy Wu 			p->exit_signal = -1;
2321b4e00444SEddy Wu 		else
2322b4e00444SEddy Wu 			p->exit_signal = current->group_leader->exit_signal;
23232d5516cbSOleg Nesterov 	} else {
23241da177e4SLinus Torvalds 		p->real_parent = current;
23252d5516cbSOleg Nesterov 		p->parent_exec_id = current->self_exec_id;
2326b4e00444SEddy Wu 		p->exit_signal = args->exit_signal;
23272d5516cbSOleg Nesterov 	}
23281da177e4SLinus Torvalds 
2329d83a7cb3SJosh Poimboeuf 	klp_copy_process(p);
2330d83a7cb3SJosh Poimboeuf 
233185dd3f61SPeter Zijlstra 	sched_core_fork(p);
233285dd3f61SPeter Zijlstra 
23331da177e4SLinus Torvalds 	spin_lock(&current->sighand->siglock);
23344a2c7a78SOleg Nesterov 
23354a2c7a78SOleg Nesterov 	/*
2336dbd95212SKees Cook 	 * Copy seccomp details explicitly here, in case they were changed
2337dbd95212SKees Cook 	 * before holding sighand lock.
2338dbd95212SKees Cook 	 */
2339dbd95212SKees Cook 	copy_seccomp(p);
2340dbd95212SKees Cook 
2341d7822b1eSMathieu Desnoyers 	rseq_fork(p, clone_flags);
2342d7822b1eSMathieu Desnoyers 
23434ca1d3eeSEric W. Biederman 	/* Don't start children in a dying pid namespace */
2344e8cfbc24SGargi Sharma 	if (unlikely(!(ns_of_pid(pid)->pid_allocated & PIDNS_ADDING))) {
23453fd37226SKirill Tkhai 		retval = -ENOMEM;
23463fd37226SKirill Tkhai 		goto bad_fork_cancel_cgroup;
23473fd37226SKirill Tkhai 	}
23484a2c7a78SOleg Nesterov 
23497673bf55SEric W. Biederman 	/* Let kill terminate clone/fork in the middle */
23507673bf55SEric W. Biederman 	if (fatal_signal_pending(current)) {
23517673bf55SEric W. Biederman 		retval = -EINTR;
23527673bf55SEric W. Biederman 		goto bad_fork_cancel_cgroup;
23537673bf55SEric W. Biederman 	}
23547673bf55SEric W. Biederman 
23552c470475SEric W. Biederman 	init_task_pid_links(p);
235673b9ebfeSOleg Nesterov 	if (likely(p->pid)) {
23574b9d33e6STejun Heo 		ptrace_init_task(p, (clone_flags & CLONE_PTRACE) || trace);
23581da177e4SLinus Torvalds 
235981907739SOleg Nesterov 		init_task_pid(p, PIDTYPE_PID, pid);
23601da177e4SLinus Torvalds 		if (thread_group_leader(p)) {
23616883f81aSEric W. Biederman 			init_task_pid(p, PIDTYPE_TGID, pid);
236281907739SOleg Nesterov 			init_task_pid(p, PIDTYPE_PGID, task_pgrp(current));
236381907739SOleg Nesterov 			init_task_pid(p, PIDTYPE_SID, task_session(current));
236481907739SOleg Nesterov 
23651c4042c2SEric W. Biederman 			if (is_child_reaper(pid)) {
236617cf22c3SEric W. Biederman 				ns_of_pid(pid)->child_reaper = p;
23671c4042c2SEric W. Biederman 				p->signal->flags |= SIGNAL_UNKILLABLE;
23681c4042c2SEric W. Biederman 			}
2369c3ad2c3bSEric W. Biederman 			p->signal->shared_pending.signal = delayed.signal;
23709c9f4dedSAlan Cox 			p->signal->tty = tty_kref_get(current->signal->tty);
2371749860ceSPavel Tikhomirov 			/*
2372749860ceSPavel Tikhomirov 			 * Inherit has_child_subreaper flag under the same
2373749860ceSPavel Tikhomirov 			 * tasklist_lock with adding child to the process tree
2374749860ceSPavel Tikhomirov 			 * for propagate_has_child_subreaper optimization.
2375749860ceSPavel Tikhomirov 			 */
2376749860ceSPavel Tikhomirov 			p->signal->has_child_subreaper = p->real_parent->signal->has_child_subreaper ||
2377749860ceSPavel Tikhomirov 							 p->real_parent->signal->is_child_subreaper;
23789cd80bbbSOleg Nesterov 			list_add_tail(&p->sibling, &p->real_parent->children);
23795e85d4abSEric W. Biederman 			list_add_tail_rcu(&p->tasks, &init_task.tasks);
23806883f81aSEric W. Biederman 			attach_pid(p, PIDTYPE_TGID);
238181907739SOleg Nesterov 			attach_pid(p, PIDTYPE_PGID);
238281907739SOleg Nesterov 			attach_pid(p, PIDTYPE_SID);
2383909ea964SChristoph Lameter 			__this_cpu_inc(process_counts);
238480628ca0SOleg Nesterov 		} else {
238580628ca0SOleg Nesterov 			current->signal->nr_threads++;
238680628ca0SOleg Nesterov 			atomic_inc(&current->signal->live);
238760d4de3fSElena Reshetova 			refcount_inc(&current->signal->sigcnt);
2388924de3b8SEric W. Biederman 			task_join_group_stop(p);
238980628ca0SOleg Nesterov 			list_add_tail_rcu(&p->thread_group,
239080628ca0SOleg Nesterov 					  &p->group_leader->thread_group);
23910c740d0aSOleg Nesterov 			list_add_tail_rcu(&p->thread_node,
23920c740d0aSOleg Nesterov 					  &p->signal->thread_head);
23931da177e4SLinus Torvalds 		}
239481907739SOleg Nesterov 		attach_pid(p, PIDTYPE_PID);
23951da177e4SLinus Torvalds 		nr_threads++;
239673b9ebfeSOleg Nesterov 	}
23971da177e4SLinus Torvalds 	total_forks++;
2398c3ad2c3bSEric W. Biederman 	hlist_del_init(&delayed.node);
23993f17da69SOleg Nesterov 	spin_unlock(&current->sighand->siglock);
24004af4206bSOleg Nesterov 	syscall_tracepoint_update(p);
24011da177e4SLinus Torvalds 	write_unlock_irq(&tasklist_lock);
24024af4206bSOleg Nesterov 
2403ddc204b5SWaiman Long 	if (pidfile)
2404ddc204b5SWaiman Long 		fd_install(pidfd, pidfile);
2405ddc204b5SWaiman Long 
2406c13cf856SAndrew Morton 	proc_fork_connector(p);
2407b1e82065SPeter Zijlstra 	sched_post_fork(p);
2408ef2c41cfSChristian Brauner 	cgroup_post_fork(p, args);
2409cdd6c482SIngo Molnar 	perf_event_fork(p);
241043d2b113SKAMEZAWA Hiroyuki 
241143d2b113SKAMEZAWA Hiroyuki 	trace_task_newtask(p, clone_flags);
24123ab67966SOleg Nesterov 	uprobe_copy_process(p, clone_flags);
241343d2b113SKAMEZAWA Hiroyuki 
241467197a4fSSuren Baghdasaryan 	copy_oom_score_adj(clone_flags, p);
241567197a4fSSuren Baghdasaryan 
24161da177e4SLinus Torvalds 	return p;
24171da177e4SLinus Torvalds 
24187e47682eSAleksa Sarai bad_fork_cancel_cgroup:
241985dd3f61SPeter Zijlstra 	sched_core_free(p);
24203fd37226SKirill Tkhai 	spin_unlock(&current->sighand->siglock);
24213fd37226SKirill Tkhai 	write_unlock_irq(&tasklist_lock);
2422ef2c41cfSChristian Brauner 	cgroup_cancel_fork(p, args);
2423b3e58382SChristian Brauner bad_fork_put_pidfd:
24246fd2fe49SAl Viro 	if (clone_flags & CLONE_PIDFD) {
24256fd2fe49SAl Viro 		fput(pidfile);
24266fd2fe49SAl Viro 		put_unused_fd(pidfd);
24276fd2fe49SAl Viro 	}
2428425fb2b4SPavel Emelyanov bad_fork_free_pid:
2429425fb2b4SPavel Emelyanov 	if (pid != &init_struct_pid)
2430425fb2b4SPavel Emelyanov 		free_pid(pid);
24310740aa5fSJiri Slaby bad_fork_cleanup_thread:
24320740aa5fSJiri Slaby 	exit_thread(p);
2433fd0928dfSJens Axboe bad_fork_cleanup_io:
2434b69f2292SLouis Rilling 	if (p->io_context)
2435b69f2292SLouis Rilling 		exit_io_context(p);
2436ab516013SSerge E. Hallyn bad_fork_cleanup_namespaces:
2437444f378bSLinus Torvalds 	exit_task_namespaces(p);
24381da177e4SLinus Torvalds bad_fork_cleanup_mm:
2439c3f3ce04SAndrea Arcangeli 	if (p->mm) {
2440c3f3ce04SAndrea Arcangeli 		mm_clear_owner(p->mm, p);
24411da177e4SLinus Torvalds 		mmput(p->mm);
2442c3f3ce04SAndrea Arcangeli 	}
24431da177e4SLinus Torvalds bad_fork_cleanup_signal:
24444ab6c083SOleg Nesterov 	if (!(clone_flags & CLONE_THREAD))
24451c5354deSMike Galbraith 		free_signal_struct(p->signal);
24461da177e4SLinus Torvalds bad_fork_cleanup_sighand:
2447a7e5328aSOleg Nesterov 	__cleanup_sighand(p->sighand);
24481da177e4SLinus Torvalds bad_fork_cleanup_fs:
24491da177e4SLinus Torvalds 	exit_fs(p); /* blocking */
24501da177e4SLinus Torvalds bad_fork_cleanup_files:
24511da177e4SLinus Torvalds 	exit_files(p); /* blocking */
24521da177e4SLinus Torvalds bad_fork_cleanup_semundo:
24531da177e4SLinus Torvalds 	exit_sem(p);
2454e4e55b47STetsuo Handa bad_fork_cleanup_security:
2455e4e55b47STetsuo Handa 	security_task_free(p);
24561da177e4SLinus Torvalds bad_fork_cleanup_audit:
24571da177e4SLinus Torvalds 	audit_free(p);
24586c72e350SPeter Zijlstra bad_fork_cleanup_perf:
2459cdd6c482SIngo Molnar 	perf_event_free_task(p);
24606c72e350SPeter Zijlstra bad_fork_cleanup_policy:
2461b09be676SByungchul Park 	lockdep_free_task(p);
24621da177e4SLinus Torvalds #ifdef CONFIG_NUMA
2463f0be3d32SLee Schermerhorn 	mpol_put(p->mempolicy);
24641da177e4SLinus Torvalds #endif
2465ff8288ffSEric W. Biederman bad_fork_cleanup_delayacct:
246635df17c5SShailabh Nagar 	delayacct_tsk_free(p);
24671da177e4SLinus Torvalds bad_fork_cleanup_count:
246821d1c5e3SAlexey Gladkov 	dec_rlimit_ucounts(task_ucounts(p), UCOUNT_RLIMIT_NPROC, 1);
2469e0e81739SDavid Howells 	exit_creds(p);
24701da177e4SLinus Torvalds bad_fork_free:
24712f064a59SPeter Zijlstra 	WRITE_ONCE(p->__state, TASK_DEAD);
2472*1a03d3f1SSebastian Andrzej Siewior 	exit_task_stack_account(p);
247368f24b08SAndy Lutomirski 	put_task_stack(p);
2474c3f3ce04SAndrea Arcangeli 	delayed_free_task(p);
2475fe7d37d1SOleg Nesterov fork_out:
2476c3ad2c3bSEric W. Biederman 	spin_lock_irq(&current->sighand->siglock);
2477c3ad2c3bSEric W. Biederman 	hlist_del_init(&delayed.node);
2478c3ad2c3bSEric W. Biederman 	spin_unlock_irq(&current->sighand->siglock);
2479fe7d37d1SOleg Nesterov 	return ERR_PTR(retval);
24801da177e4SLinus Torvalds }
24811da177e4SLinus Torvalds 
24822c470475SEric W. Biederman static inline void init_idle_pids(struct task_struct *idle)
2483f106eee1SOleg Nesterov {
2484f106eee1SOleg Nesterov 	enum pid_type type;
2485f106eee1SOleg Nesterov 
2486f106eee1SOleg Nesterov 	for (type = PIDTYPE_PID; type < PIDTYPE_MAX; ++type) {
24872c470475SEric W. Biederman 		INIT_HLIST_NODE(&idle->pid_links[type]); /* not really needed */
24882c470475SEric W. Biederman 		init_task_pid(idle, type, &init_struct_pid);
2489f106eee1SOleg Nesterov 	}
2490f106eee1SOleg Nesterov }
2491f106eee1SOleg Nesterov 
2492f1a0a376SValentin Schneider struct task_struct * __init fork_idle(int cpu)
24931da177e4SLinus Torvalds {
249436c8b586SIngo Molnar 	struct task_struct *task;
24957f192e3cSChristian Brauner 	struct kernel_clone_args args = {
24967f192e3cSChristian Brauner 		.flags = CLONE_VM,
24977f192e3cSChristian Brauner 	};
24987f192e3cSChristian Brauner 
24997f192e3cSChristian Brauner 	task = copy_process(&init_struct_pid, 0, cpu_to_node(cpu), &args);
2500f106eee1SOleg Nesterov 	if (!IS_ERR(task)) {
25012c470475SEric W. Biederman 		init_idle_pids(task);
25021da177e4SLinus Torvalds 		init_idle(task, cpu);
2503f106eee1SOleg Nesterov 	}
250473b9ebfeSOleg Nesterov 
25051da177e4SLinus Torvalds 	return task;
25061da177e4SLinus Torvalds }
25071da177e4SLinus Torvalds 
250813585fa0SNadav Amit struct mm_struct *copy_init_mm(void)
250913585fa0SNadav Amit {
251013585fa0SNadav Amit 	return dup_mm(NULL, &init_mm);
251113585fa0SNadav Amit }
251213585fa0SNadav Amit 
25131da177e4SLinus Torvalds /*
2514cc440e87SJens Axboe  * This is like kernel_clone(), but shaved down and tailored to just
2515cc440e87SJens Axboe  * creating io_uring workers. It returns a created task, or an error pointer.
2516cc440e87SJens Axboe  * The returned task is inactive, and the caller must fire it up through
2517cc440e87SJens Axboe  * wake_up_new_task(p). All signals are blocked in the created task.
2518cc440e87SJens Axboe  */
2519cc440e87SJens Axboe struct task_struct *create_io_thread(int (*fn)(void *), void *arg, int node)
2520cc440e87SJens Axboe {
2521cc440e87SJens Axboe 	unsigned long flags = CLONE_FS|CLONE_FILES|CLONE_SIGHAND|CLONE_THREAD|
2522cc440e87SJens Axboe 				CLONE_IO;
2523cc440e87SJens Axboe 	struct kernel_clone_args args = {
2524cc440e87SJens Axboe 		.flags		= ((lower_32_bits(flags) | CLONE_VM |
2525cc440e87SJens Axboe 				    CLONE_UNTRACED) & ~CSIGNAL),
2526cc440e87SJens Axboe 		.exit_signal	= (lower_32_bits(flags) & CSIGNAL),
2527cc440e87SJens Axboe 		.stack		= (unsigned long)fn,
2528cc440e87SJens Axboe 		.stack_size	= (unsigned long)arg,
2529cc440e87SJens Axboe 		.io_thread	= 1,
2530cc440e87SJens Axboe 	};
2531cc440e87SJens Axboe 
2532b16b3855SJens Axboe 	return copy_process(NULL, 0, node, &args);
2533cc440e87SJens Axboe }
2534cc440e87SJens Axboe 
2535cc440e87SJens Axboe /*
25361da177e4SLinus Torvalds  *  Ok, this is the main fork-routine.
25371da177e4SLinus Torvalds  *
25381da177e4SLinus Torvalds  * It copies the process, and if successful kick-starts
25391da177e4SLinus Torvalds  * it and waits for it to finish using the VM if required.
2540a0eb9abdSEugene Syromiatnikov  *
2541a0eb9abdSEugene Syromiatnikov  * args->exit_signal is expected to be checked for sanity by the caller.
25421da177e4SLinus Torvalds  */
2543cad6967aSChristian Brauner pid_t kernel_clone(struct kernel_clone_args *args)
25441da177e4SLinus Torvalds {
25457f192e3cSChristian Brauner 	u64 clone_flags = args->flags;
25469f5325aaSMarcos Paulo de Souza 	struct completion vfork;
25479f5325aaSMarcos Paulo de Souza 	struct pid *pid;
25481da177e4SLinus Torvalds 	struct task_struct *p;
25491da177e4SLinus Torvalds 	int trace = 0;
2550cad6967aSChristian Brauner 	pid_t nr;
25511da177e4SLinus Torvalds 
2552bdff746aSAndrew Morton 	/*
25533af8588cSChristian Brauner 	 * For legacy clone() calls, CLONE_PIDFD uses the parent_tid argument
25543af8588cSChristian Brauner 	 * to return the pidfd. Hence, CLONE_PIDFD and CLONE_PARENT_SETTID are
25553af8588cSChristian Brauner 	 * mutually exclusive. With clone3() CLONE_PIDFD has grown a separate
25563af8588cSChristian Brauner 	 * field in struct clone_args and it still doesn't make sense to have
25573af8588cSChristian Brauner 	 * them both point at the same memory location. Performing this check
25583af8588cSChristian Brauner 	 * here has the advantage that we don't need to have a separate helper
25593af8588cSChristian Brauner 	 * to check for legacy clone().
25603af8588cSChristian Brauner 	 */
25613af8588cSChristian Brauner 	if ((args->flags & CLONE_PIDFD) &&
25623af8588cSChristian Brauner 	    (args->flags & CLONE_PARENT_SETTID) &&
25633af8588cSChristian Brauner 	    (args->pidfd == args->parent_tid))
25643af8588cSChristian Brauner 		return -EINVAL;
25653af8588cSChristian Brauner 
25663af8588cSChristian Brauner 	/*
25674b9d33e6STejun Heo 	 * Determine whether and which event to report to ptracer.  When
25684b9d33e6STejun Heo 	 * called from kernel_thread or CLONE_UNTRACED is explicitly
25694b9d33e6STejun Heo 	 * requested, no event is reported; otherwise, report if the event
25704b9d33e6STejun Heo 	 * for the type of forking is enabled.
257109a05394SRoland McGrath 	 */
2572e80d6661SAl Viro 	if (!(clone_flags & CLONE_UNTRACED)) {
25734b9d33e6STejun Heo 		if (clone_flags & CLONE_VFORK)
25744b9d33e6STejun Heo 			trace = PTRACE_EVENT_VFORK;
25757f192e3cSChristian Brauner 		else if (args->exit_signal != SIGCHLD)
25764b9d33e6STejun Heo 			trace = PTRACE_EVENT_CLONE;
25774b9d33e6STejun Heo 		else
25784b9d33e6STejun Heo 			trace = PTRACE_EVENT_FORK;
25794b9d33e6STejun Heo 
25804b9d33e6STejun Heo 		if (likely(!ptrace_event_enabled(current, trace)))
25814b9d33e6STejun Heo 			trace = 0;
25824b9d33e6STejun Heo 	}
25831da177e4SLinus Torvalds 
25847f192e3cSChristian Brauner 	p = copy_process(NULL, trace, NUMA_NO_NODE, args);
258538addce8SEmese Revfy 	add_latent_entropy();
25869f5325aaSMarcos Paulo de Souza 
25879f5325aaSMarcos Paulo de Souza 	if (IS_ERR(p))
25889f5325aaSMarcos Paulo de Souza 		return PTR_ERR(p);
25899f5325aaSMarcos Paulo de Souza 
25901da177e4SLinus Torvalds 	/*
25911da177e4SLinus Torvalds 	 * Do this prior waking up the new thread - the thread pointer
25921da177e4SLinus Torvalds 	 * might get invalid after that point, if the thread exits quickly.
25931da177e4SLinus Torvalds 	 */
25940a16b607SMathieu Desnoyers 	trace_sched_process_fork(current, p);
25950a16b607SMathieu Desnoyers 
25964e52365fSMatthew Dempsky 	pid = get_task_pid(p, PIDTYPE_PID);
25974e52365fSMatthew Dempsky 	nr = pid_vnr(pid);
259830e49c26SPavel Emelyanov 
259930e49c26SPavel Emelyanov 	if (clone_flags & CLONE_PARENT_SETTID)
26007f192e3cSChristian Brauner 		put_user(nr, args->parent_tid);
2601a6f5e063SSukadev Bhattiprolu 
26021da177e4SLinus Torvalds 	if (clone_flags & CLONE_VFORK) {
26031da177e4SLinus Torvalds 		p->vfork_done = &vfork;
26041da177e4SLinus Torvalds 		init_completion(&vfork);
2605d68b46feSOleg Nesterov 		get_task_struct(p);
26061da177e4SLinus Torvalds 	}
26071da177e4SLinus Torvalds 
26083e51e3edSSamir Bellabes 	wake_up_new_task(p);
26091da177e4SLinus Torvalds 
26104b9d33e6STejun Heo 	/* forking complete and child started to run, tell ptracer */
26114b9d33e6STejun Heo 	if (unlikely(trace))
26124e52365fSMatthew Dempsky 		ptrace_event_pid(trace, pid);
261309a05394SRoland McGrath 
26141da177e4SLinus Torvalds 	if (clone_flags & CLONE_VFORK) {
2615d68b46feSOleg Nesterov 		if (!wait_for_vfork_done(p, &vfork))
26164e52365fSMatthew Dempsky 			ptrace_event_pid(PTRACE_EVENT_VFORK_DONE, pid);
26179f59ce5dSChuck Ebbert 	}
26184e52365fSMatthew Dempsky 
26194e52365fSMatthew Dempsky 	put_pid(pid);
262092476d7fSEric W. Biederman 	return nr;
26211da177e4SLinus Torvalds }
26221da177e4SLinus Torvalds 
26232aa3a7f8SAl Viro /*
26242aa3a7f8SAl Viro  * Create a kernel thread.
26252aa3a7f8SAl Viro  */
26262aa3a7f8SAl Viro pid_t kernel_thread(int (*fn)(void *), void *arg, unsigned long flags)
26272aa3a7f8SAl Viro {
26287f192e3cSChristian Brauner 	struct kernel_clone_args args = {
26293f2c788aSChristian Brauner 		.flags		= ((lower_32_bits(flags) | CLONE_VM |
26303f2c788aSChristian Brauner 				    CLONE_UNTRACED) & ~CSIGNAL),
26313f2c788aSChristian Brauner 		.exit_signal	= (lower_32_bits(flags) & CSIGNAL),
26327f192e3cSChristian Brauner 		.stack		= (unsigned long)fn,
26337f192e3cSChristian Brauner 		.stack_size	= (unsigned long)arg,
26347f192e3cSChristian Brauner 	};
26357f192e3cSChristian Brauner 
2636cad6967aSChristian Brauner 	return kernel_clone(&args);
26372aa3a7f8SAl Viro }
26382aa3a7f8SAl Viro 
2639d2125043SAl Viro #ifdef __ARCH_WANT_SYS_FORK
2640d2125043SAl Viro SYSCALL_DEFINE0(fork)
2641d2125043SAl Viro {
2642d2125043SAl Viro #ifdef CONFIG_MMU
26437f192e3cSChristian Brauner 	struct kernel_clone_args args = {
26447f192e3cSChristian Brauner 		.exit_signal = SIGCHLD,
26457f192e3cSChristian Brauner 	};
26467f192e3cSChristian Brauner 
2647cad6967aSChristian Brauner 	return kernel_clone(&args);
2648d2125043SAl Viro #else
2649d2125043SAl Viro 	/* can not support in nommu mode */
26505d59e182SDaeseok Youn 	return -EINVAL;
2651d2125043SAl Viro #endif
2652d2125043SAl Viro }
2653d2125043SAl Viro #endif
2654d2125043SAl Viro 
2655d2125043SAl Viro #ifdef __ARCH_WANT_SYS_VFORK
2656d2125043SAl Viro SYSCALL_DEFINE0(vfork)
2657d2125043SAl Viro {
26587f192e3cSChristian Brauner 	struct kernel_clone_args args = {
26597f192e3cSChristian Brauner 		.flags		= CLONE_VFORK | CLONE_VM,
26607f192e3cSChristian Brauner 		.exit_signal	= SIGCHLD,
26617f192e3cSChristian Brauner 	};
26627f192e3cSChristian Brauner 
2663cad6967aSChristian Brauner 	return kernel_clone(&args);
2664d2125043SAl Viro }
2665d2125043SAl Viro #endif
2666d2125043SAl Viro 
2667d2125043SAl Viro #ifdef __ARCH_WANT_SYS_CLONE
2668d2125043SAl Viro #ifdef CONFIG_CLONE_BACKWARDS
2669d2125043SAl Viro SYSCALL_DEFINE5(clone, unsigned long, clone_flags, unsigned long, newsp,
2670d2125043SAl Viro 		 int __user *, parent_tidptr,
26713033f14aSJosh Triplett 		 unsigned long, tls,
2672d2125043SAl Viro 		 int __user *, child_tidptr)
2673d2125043SAl Viro #elif defined(CONFIG_CLONE_BACKWARDS2)
2674d2125043SAl Viro SYSCALL_DEFINE5(clone, unsigned long, newsp, unsigned long, clone_flags,
2675d2125043SAl Viro 		 int __user *, parent_tidptr,
2676d2125043SAl Viro 		 int __user *, child_tidptr,
26773033f14aSJosh Triplett 		 unsigned long, tls)
2678dfa9771aSMichal Simek #elif defined(CONFIG_CLONE_BACKWARDS3)
2679dfa9771aSMichal Simek SYSCALL_DEFINE6(clone, unsigned long, clone_flags, unsigned long, newsp,
2680dfa9771aSMichal Simek 		int, stack_size,
2681dfa9771aSMichal Simek 		int __user *, parent_tidptr,
2682dfa9771aSMichal Simek 		int __user *, child_tidptr,
26833033f14aSJosh Triplett 		unsigned long, tls)
2684d2125043SAl Viro #else
2685d2125043SAl Viro SYSCALL_DEFINE5(clone, unsigned long, clone_flags, unsigned long, newsp,
2686d2125043SAl Viro 		 int __user *, parent_tidptr,
2687d2125043SAl Viro 		 int __user *, child_tidptr,
26883033f14aSJosh Triplett 		 unsigned long, tls)
2689d2125043SAl Viro #endif
2690d2125043SAl Viro {
26917f192e3cSChristian Brauner 	struct kernel_clone_args args = {
26923f2c788aSChristian Brauner 		.flags		= (lower_32_bits(clone_flags) & ~CSIGNAL),
26937f192e3cSChristian Brauner 		.pidfd		= parent_tidptr,
26947f192e3cSChristian Brauner 		.child_tid	= child_tidptr,
26957f192e3cSChristian Brauner 		.parent_tid	= parent_tidptr,
26963f2c788aSChristian Brauner 		.exit_signal	= (lower_32_bits(clone_flags) & CSIGNAL),
26977f192e3cSChristian Brauner 		.stack		= newsp,
26987f192e3cSChristian Brauner 		.tls		= tls,
26997f192e3cSChristian Brauner 	};
27007f192e3cSChristian Brauner 
2701cad6967aSChristian Brauner 	return kernel_clone(&args);
27027f192e3cSChristian Brauner }
2703d68dbb0cSChristian Brauner #endif
27047f192e3cSChristian Brauner 
2705d68dbb0cSChristian Brauner #ifdef __ARCH_WANT_SYS_CLONE3
2706dd499f7aSAmanieu d'Antras 
27077f192e3cSChristian Brauner noinline static int copy_clone_args_from_user(struct kernel_clone_args *kargs,
27087f192e3cSChristian Brauner 					      struct clone_args __user *uargs,
2709f14c234bSAleksa Sarai 					      size_t usize)
27107f192e3cSChristian Brauner {
2711f14c234bSAleksa Sarai 	int err;
27127f192e3cSChristian Brauner 	struct clone_args args;
271349cb2fc4SAdrian Reber 	pid_t *kset_tid = kargs->set_tid;
27147f192e3cSChristian Brauner 
2715a966dcfeSEugene Syromiatnikov 	BUILD_BUG_ON(offsetofend(struct clone_args, tls) !=
2716a966dcfeSEugene Syromiatnikov 		     CLONE_ARGS_SIZE_VER0);
2717a966dcfeSEugene Syromiatnikov 	BUILD_BUG_ON(offsetofend(struct clone_args, set_tid_size) !=
2718a966dcfeSEugene Syromiatnikov 		     CLONE_ARGS_SIZE_VER1);
2719a966dcfeSEugene Syromiatnikov 	BUILD_BUG_ON(offsetofend(struct clone_args, cgroup) !=
2720a966dcfeSEugene Syromiatnikov 		     CLONE_ARGS_SIZE_VER2);
2721a966dcfeSEugene Syromiatnikov 	BUILD_BUG_ON(sizeof(struct clone_args) != CLONE_ARGS_SIZE_VER2);
2722a966dcfeSEugene Syromiatnikov 
2723f14c234bSAleksa Sarai 	if (unlikely(usize > PAGE_SIZE))
27247f192e3cSChristian Brauner 		return -E2BIG;
2725f14c234bSAleksa Sarai 	if (unlikely(usize < CLONE_ARGS_SIZE_VER0))
27267f192e3cSChristian Brauner 		return -EINVAL;
27277f192e3cSChristian Brauner 
2728f14c234bSAleksa Sarai 	err = copy_struct_from_user(&args, sizeof(args), uargs, usize);
2729f14c234bSAleksa Sarai 	if (err)
2730f14c234bSAleksa Sarai 		return err;
27317f192e3cSChristian Brauner 
273249cb2fc4SAdrian Reber 	if (unlikely(args.set_tid_size > MAX_PID_NS_LEVEL))
273349cb2fc4SAdrian Reber 		return -EINVAL;
273449cb2fc4SAdrian Reber 
273549cb2fc4SAdrian Reber 	if (unlikely(!args.set_tid && args.set_tid_size > 0))
273649cb2fc4SAdrian Reber 		return -EINVAL;
273749cb2fc4SAdrian Reber 
273849cb2fc4SAdrian Reber 	if (unlikely(args.set_tid && args.set_tid_size == 0))
273949cb2fc4SAdrian Reber 		return -EINVAL;
274049cb2fc4SAdrian Reber 
2741a0eb9abdSEugene Syromiatnikov 	/*
2742a0eb9abdSEugene Syromiatnikov 	 * Verify that higher 32bits of exit_signal are unset and that
2743a0eb9abdSEugene Syromiatnikov 	 * it is a valid signal
2744a0eb9abdSEugene Syromiatnikov 	 */
2745a0eb9abdSEugene Syromiatnikov 	if (unlikely((args.exit_signal & ~((u64)CSIGNAL)) ||
2746a0eb9abdSEugene Syromiatnikov 		     !valid_signal(args.exit_signal)))
2747a0eb9abdSEugene Syromiatnikov 		return -EINVAL;
2748a0eb9abdSEugene Syromiatnikov 
274962173872SEugene Syromiatnikov 	if ((args.flags & CLONE_INTO_CGROUP) &&
275062173872SEugene Syromiatnikov 	    (args.cgroup > INT_MAX || usize < CLONE_ARGS_SIZE_VER2))
2751ef2c41cfSChristian Brauner 		return -EINVAL;
2752ef2c41cfSChristian Brauner 
27537f192e3cSChristian Brauner 	*kargs = (struct kernel_clone_args){
27547f192e3cSChristian Brauner 		.flags		= args.flags,
27557f192e3cSChristian Brauner 		.pidfd		= u64_to_user_ptr(args.pidfd),
27567f192e3cSChristian Brauner 		.child_tid	= u64_to_user_ptr(args.child_tid),
27577f192e3cSChristian Brauner 		.parent_tid	= u64_to_user_ptr(args.parent_tid),
27587f192e3cSChristian Brauner 		.exit_signal	= args.exit_signal,
27597f192e3cSChristian Brauner 		.stack		= args.stack,
27607f192e3cSChristian Brauner 		.stack_size	= args.stack_size,
27617f192e3cSChristian Brauner 		.tls		= args.tls,
276249cb2fc4SAdrian Reber 		.set_tid_size	= args.set_tid_size,
2763ef2c41cfSChristian Brauner 		.cgroup		= args.cgroup,
27647f192e3cSChristian Brauner 	};
27657f192e3cSChristian Brauner 
276649cb2fc4SAdrian Reber 	if (args.set_tid &&
276749cb2fc4SAdrian Reber 		copy_from_user(kset_tid, u64_to_user_ptr(args.set_tid),
276849cb2fc4SAdrian Reber 			(kargs->set_tid_size * sizeof(pid_t))))
276949cb2fc4SAdrian Reber 		return -EFAULT;
277049cb2fc4SAdrian Reber 
277149cb2fc4SAdrian Reber 	kargs->set_tid = kset_tid;
277249cb2fc4SAdrian Reber 
27737f192e3cSChristian Brauner 	return 0;
27747f192e3cSChristian Brauner }
27757f192e3cSChristian Brauner 
2776fa729c4dSChristian Brauner /**
2777fa729c4dSChristian Brauner  * clone3_stack_valid - check and prepare stack
2778fa729c4dSChristian Brauner  * @kargs: kernel clone args
2779fa729c4dSChristian Brauner  *
2780fa729c4dSChristian Brauner  * Verify that the stack arguments userspace gave us are sane.
2781fa729c4dSChristian Brauner  * In addition, set the stack direction for userspace since it's easy for us to
2782fa729c4dSChristian Brauner  * determine.
2783fa729c4dSChristian Brauner  */
2784fa729c4dSChristian Brauner static inline bool clone3_stack_valid(struct kernel_clone_args *kargs)
2785fa729c4dSChristian Brauner {
2786fa729c4dSChristian Brauner 	if (kargs->stack == 0) {
2787fa729c4dSChristian Brauner 		if (kargs->stack_size > 0)
2788fa729c4dSChristian Brauner 			return false;
2789fa729c4dSChristian Brauner 	} else {
2790fa729c4dSChristian Brauner 		if (kargs->stack_size == 0)
2791fa729c4dSChristian Brauner 			return false;
2792fa729c4dSChristian Brauner 
2793fa729c4dSChristian Brauner 		if (!access_ok((void __user *)kargs->stack, kargs->stack_size))
2794fa729c4dSChristian Brauner 			return false;
2795fa729c4dSChristian Brauner 
2796fa729c4dSChristian Brauner #if !defined(CONFIG_STACK_GROWSUP) && !defined(CONFIG_IA64)
2797fa729c4dSChristian Brauner 		kargs->stack += kargs->stack_size;
2798fa729c4dSChristian Brauner #endif
2799fa729c4dSChristian Brauner 	}
2800fa729c4dSChristian Brauner 
2801fa729c4dSChristian Brauner 	return true;
2802fa729c4dSChristian Brauner }
2803fa729c4dSChristian Brauner 
2804fa729c4dSChristian Brauner static bool clone3_args_valid(struct kernel_clone_args *kargs)
28057f192e3cSChristian Brauner {
2806b612e5dfSChristian Brauner 	/* Verify that no unknown flags are passed along. */
2807ef2c41cfSChristian Brauner 	if (kargs->flags &
2808ef2c41cfSChristian Brauner 	    ~(CLONE_LEGACY_FLAGS | CLONE_CLEAR_SIGHAND | CLONE_INTO_CGROUP))
28097f192e3cSChristian Brauner 		return false;
28107f192e3cSChristian Brauner 
28117f192e3cSChristian Brauner 	/*
2812a8ca6b13SXiaofeng Cao 	 * - make the CLONE_DETACHED bit reusable for clone3
2813a8ca6b13SXiaofeng Cao 	 * - make the CSIGNAL bits reusable for clone3
28147f192e3cSChristian Brauner 	 */
28157f192e3cSChristian Brauner 	if (kargs->flags & (CLONE_DETACHED | CSIGNAL))
28167f192e3cSChristian Brauner 		return false;
28177f192e3cSChristian Brauner 
2818b612e5dfSChristian Brauner 	if ((kargs->flags & (CLONE_SIGHAND | CLONE_CLEAR_SIGHAND)) ==
2819b612e5dfSChristian Brauner 	    (CLONE_SIGHAND | CLONE_CLEAR_SIGHAND))
2820b612e5dfSChristian Brauner 		return false;
2821b612e5dfSChristian Brauner 
28227f192e3cSChristian Brauner 	if ((kargs->flags & (CLONE_THREAD | CLONE_PARENT)) &&
28237f192e3cSChristian Brauner 	    kargs->exit_signal)
28247f192e3cSChristian Brauner 		return false;
28257f192e3cSChristian Brauner 
2826fa729c4dSChristian Brauner 	if (!clone3_stack_valid(kargs))
2827fa729c4dSChristian Brauner 		return false;
2828fa729c4dSChristian Brauner 
28297f192e3cSChristian Brauner 	return true;
28307f192e3cSChristian Brauner }
28317f192e3cSChristian Brauner 
2832501bd016SChristian Brauner /**
2833501bd016SChristian Brauner  * clone3 - create a new process with specific properties
2834501bd016SChristian Brauner  * @uargs: argument structure
2835501bd016SChristian Brauner  * @size:  size of @uargs
2836501bd016SChristian Brauner  *
2837501bd016SChristian Brauner  * clone3() is the extensible successor to clone()/clone2().
2838501bd016SChristian Brauner  * It takes a struct as argument that is versioned by its size.
2839501bd016SChristian Brauner  *
2840501bd016SChristian Brauner  * Return: On success, a positive PID for the child process.
2841501bd016SChristian Brauner  *         On error, a negative errno number.
2842501bd016SChristian Brauner  */
28437f192e3cSChristian Brauner SYSCALL_DEFINE2(clone3, struct clone_args __user *, uargs, size_t, size)
28447f192e3cSChristian Brauner {
28457f192e3cSChristian Brauner 	int err;
28467f192e3cSChristian Brauner 
28477f192e3cSChristian Brauner 	struct kernel_clone_args kargs;
284849cb2fc4SAdrian Reber 	pid_t set_tid[MAX_PID_NS_LEVEL];
284949cb2fc4SAdrian Reber 
285049cb2fc4SAdrian Reber 	kargs.set_tid = set_tid;
28517f192e3cSChristian Brauner 
28527f192e3cSChristian Brauner 	err = copy_clone_args_from_user(&kargs, uargs, size);
28537f192e3cSChristian Brauner 	if (err)
28547f192e3cSChristian Brauner 		return err;
28557f192e3cSChristian Brauner 
28567f192e3cSChristian Brauner 	if (!clone3_args_valid(&kargs))
28577f192e3cSChristian Brauner 		return -EINVAL;
28587f192e3cSChristian Brauner 
2859cad6967aSChristian Brauner 	return kernel_clone(&kargs);
2860d2125043SAl Viro }
2861d2125043SAl Viro #endif
2862d2125043SAl Viro 
28630f1b92cbSOleg Nesterov void walk_process_tree(struct task_struct *top, proc_visitor visitor, void *data)
28640f1b92cbSOleg Nesterov {
28650f1b92cbSOleg Nesterov 	struct task_struct *leader, *parent, *child;
28660f1b92cbSOleg Nesterov 	int res;
28670f1b92cbSOleg Nesterov 
28680f1b92cbSOleg Nesterov 	read_lock(&tasklist_lock);
28690f1b92cbSOleg Nesterov 	leader = top = top->group_leader;
28700f1b92cbSOleg Nesterov down:
28710f1b92cbSOleg Nesterov 	for_each_thread(leader, parent) {
28720f1b92cbSOleg Nesterov 		list_for_each_entry(child, &parent->children, sibling) {
28730f1b92cbSOleg Nesterov 			res = visitor(child, data);
28740f1b92cbSOleg Nesterov 			if (res) {
28750f1b92cbSOleg Nesterov 				if (res < 0)
28760f1b92cbSOleg Nesterov 					goto out;
28770f1b92cbSOleg Nesterov 				leader = child;
28780f1b92cbSOleg Nesterov 				goto down;
28790f1b92cbSOleg Nesterov 			}
28800f1b92cbSOleg Nesterov up:
28810f1b92cbSOleg Nesterov 			;
28820f1b92cbSOleg Nesterov 		}
28830f1b92cbSOleg Nesterov 	}
28840f1b92cbSOleg Nesterov 
28850f1b92cbSOleg Nesterov 	if (leader != top) {
28860f1b92cbSOleg Nesterov 		child = leader;
28870f1b92cbSOleg Nesterov 		parent = child->real_parent;
28880f1b92cbSOleg Nesterov 		leader = parent->group_leader;
28890f1b92cbSOleg Nesterov 		goto up;
28900f1b92cbSOleg Nesterov 	}
28910f1b92cbSOleg Nesterov out:
28920f1b92cbSOleg Nesterov 	read_unlock(&tasklist_lock);
28930f1b92cbSOleg Nesterov }
28940f1b92cbSOleg Nesterov 
28955fd63b30SRavikiran G Thirumalai #ifndef ARCH_MIN_MMSTRUCT_ALIGN
28965fd63b30SRavikiran G Thirumalai #define ARCH_MIN_MMSTRUCT_ALIGN 0
28975fd63b30SRavikiran G Thirumalai #endif
28985fd63b30SRavikiran G Thirumalai 
289951cc5068SAlexey Dobriyan static void sighand_ctor(void *data)
2900aa1757f9SOleg Nesterov {
2901aa1757f9SOleg Nesterov 	struct sighand_struct *sighand = data;
2902aa1757f9SOleg Nesterov 
2903aa1757f9SOleg Nesterov 	spin_lock_init(&sighand->siglock);
2904b8fceee1SDavide Libenzi 	init_waitqueue_head(&sighand->signalfd_wqh);
2905fba2afaaSDavide Libenzi }
2906aa1757f9SOleg Nesterov 
29071da177e4SLinus Torvalds void __init proc_caches_init(void)
29081da177e4SLinus Torvalds {
2909c1a2f7f0SRik van Riel 	unsigned int mm_size;
2910c1a2f7f0SRik van Riel 
29111da177e4SLinus Torvalds 	sighand_cachep = kmem_cache_create("sighand_cache",
29121da177e4SLinus Torvalds 			sizeof(struct sighand_struct), 0,
29135f0d5a3aSPaul E. McKenney 			SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_TYPESAFE_BY_RCU|
291475f296d9SLevin, Alexander (Sasha Levin) 			SLAB_ACCOUNT, sighand_ctor);
29151da177e4SLinus Torvalds 	signal_cachep = kmem_cache_create("signal_cache",
29161da177e4SLinus Torvalds 			sizeof(struct signal_struct), 0,
291775f296d9SLevin, Alexander (Sasha Levin) 			SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_ACCOUNT,
29185d097056SVladimir Davydov 			NULL);
29191da177e4SLinus Torvalds 	files_cachep = kmem_cache_create("files_cache",
29201da177e4SLinus Torvalds 			sizeof(struct files_struct), 0,
292175f296d9SLevin, Alexander (Sasha Levin) 			SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_ACCOUNT,
29225d097056SVladimir Davydov 			NULL);
29231da177e4SLinus Torvalds 	fs_cachep = kmem_cache_create("fs_cache",
29241da177e4SLinus Torvalds 			sizeof(struct fs_struct), 0,
292575f296d9SLevin, Alexander (Sasha Levin) 			SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_ACCOUNT,
29265d097056SVladimir Davydov 			NULL);
2927c1a2f7f0SRik van Riel 
29286345d24dSLinus Torvalds 	/*
2929c1a2f7f0SRik van Riel 	 * The mm_cpumask is located at the end of mm_struct, and is
2930c1a2f7f0SRik van Riel 	 * dynamically sized based on the maximum CPU number this system
2931c1a2f7f0SRik van Riel 	 * can have, taking hotplug into account (nr_cpu_ids).
29326345d24dSLinus Torvalds 	 */
2933c1a2f7f0SRik van Riel 	mm_size = sizeof(struct mm_struct) + cpumask_size();
2934c1a2f7f0SRik van Riel 
293507dcd7feSDavid Windsor 	mm_cachep = kmem_cache_create_usercopy("mm_struct",
2936c1a2f7f0SRik van Riel 			mm_size, ARCH_MIN_MMSTRUCT_ALIGN,
293775f296d9SLevin, Alexander (Sasha Levin) 			SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_ACCOUNT,
293807dcd7feSDavid Windsor 			offsetof(struct mm_struct, saved_auxv),
293907dcd7feSDavid Windsor 			sizeof_field(struct mm_struct, saved_auxv),
29405d097056SVladimir Davydov 			NULL);
29415d097056SVladimir Davydov 	vm_area_cachep = KMEM_CACHE(vm_area_struct, SLAB_PANIC|SLAB_ACCOUNT);
29428feae131SDavid Howells 	mmap_init();
294366577193SAl Viro 	nsproxy_cache_init();
29441da177e4SLinus Torvalds }
2945cf2e340fSJANAK DESAI 
2946cf2e340fSJANAK DESAI /*
29479bfb23fcSOleg Nesterov  * Check constraints on flags passed to the unshare system call.
2948cf2e340fSJANAK DESAI  */
29499bfb23fcSOleg Nesterov static int check_unshare_flags(unsigned long unshare_flags)
2950cf2e340fSJANAK DESAI {
29519bfb23fcSOleg Nesterov 	if (unshare_flags & ~(CLONE_THREAD|CLONE_FS|CLONE_NEWNS|CLONE_SIGHAND|
29529bfb23fcSOleg Nesterov 				CLONE_VM|CLONE_FILES|CLONE_SYSVSEM|
295350804fe3SEric W. Biederman 				CLONE_NEWUTS|CLONE_NEWIPC|CLONE_NEWNET|
2954769071acSAndrei Vagin 				CLONE_NEWUSER|CLONE_NEWPID|CLONE_NEWCGROUP|
2955769071acSAndrei Vagin 				CLONE_NEWTIME))
2956cf2e340fSJANAK DESAI 		return -EINVAL;
29579bfb23fcSOleg Nesterov 	/*
295812c641abSEric W. Biederman 	 * Not implemented, but pretend it works if there is nothing
295912c641abSEric W. Biederman 	 * to unshare.  Note that unsharing the address space or the
296012c641abSEric W. Biederman 	 * signal handlers also need to unshare the signal queues (aka
296112c641abSEric W. Biederman 	 * CLONE_THREAD).
29629bfb23fcSOleg Nesterov 	 */
29639bfb23fcSOleg Nesterov 	if (unshare_flags & (CLONE_THREAD | CLONE_SIGHAND | CLONE_VM)) {
296412c641abSEric W. Biederman 		if (!thread_group_empty(current))
296512c641abSEric W. Biederman 			return -EINVAL;
296612c641abSEric W. Biederman 	}
296712c641abSEric W. Biederman 	if (unshare_flags & (CLONE_SIGHAND | CLONE_VM)) {
2968d036bda7SElena Reshetova 		if (refcount_read(&current->sighand->count) > 1)
296912c641abSEric W. Biederman 			return -EINVAL;
297012c641abSEric W. Biederman 	}
297112c641abSEric W. Biederman 	if (unshare_flags & CLONE_VM) {
297212c641abSEric W. Biederman 		if (!current_is_single_threaded())
29739bfb23fcSOleg Nesterov 			return -EINVAL;
29749bfb23fcSOleg Nesterov 	}
2975cf2e340fSJANAK DESAI 
2976cf2e340fSJANAK DESAI 	return 0;
2977cf2e340fSJANAK DESAI }
2978cf2e340fSJANAK DESAI 
2979cf2e340fSJANAK DESAI /*
298099d1419dSJANAK DESAI  * Unshare the filesystem structure if it is being shared
2981cf2e340fSJANAK DESAI  */
2982cf2e340fSJANAK DESAI static int unshare_fs(unsigned long unshare_flags, struct fs_struct **new_fsp)
2983cf2e340fSJANAK DESAI {
2984cf2e340fSJANAK DESAI 	struct fs_struct *fs = current->fs;
2985cf2e340fSJANAK DESAI 
2986498052bbSAl Viro 	if (!(unshare_flags & CLONE_FS) || !fs)
2987498052bbSAl Viro 		return 0;
2988498052bbSAl Viro 
2989498052bbSAl Viro 	/* don't need lock here; in the worst case we'll do useless copy */
2990498052bbSAl Viro 	if (fs->users == 1)
2991498052bbSAl Viro 		return 0;
2992498052bbSAl Viro 
2993498052bbSAl Viro 	*new_fsp = copy_fs_struct(fs);
299499d1419dSJANAK DESAI 	if (!*new_fsp)
299599d1419dSJANAK DESAI 		return -ENOMEM;
2996cf2e340fSJANAK DESAI 
2997cf2e340fSJANAK DESAI 	return 0;
2998cf2e340fSJANAK DESAI }
2999cf2e340fSJANAK DESAI 
3000cf2e340fSJANAK DESAI /*
3001a016f338SJANAK DESAI  * Unshare file descriptor table if it is being shared
3002cf2e340fSJANAK DESAI  */
300360997c3dSChristian Brauner int unshare_fd(unsigned long unshare_flags, unsigned int max_fds,
300460997c3dSChristian Brauner 	       struct files_struct **new_fdp)
3005cf2e340fSJANAK DESAI {
3006cf2e340fSJANAK DESAI 	struct files_struct *fd = current->files;
3007a016f338SJANAK DESAI 	int error = 0;
3008cf2e340fSJANAK DESAI 
3009cf2e340fSJANAK DESAI 	if ((unshare_flags & CLONE_FILES) &&
3010a016f338SJANAK DESAI 	    (fd && atomic_read(&fd->count) > 1)) {
301160997c3dSChristian Brauner 		*new_fdp = dup_fd(fd, max_fds, &error);
3012a016f338SJANAK DESAI 		if (!*new_fdp)
3013a016f338SJANAK DESAI 			return error;
3014a016f338SJANAK DESAI 	}
3015cf2e340fSJANAK DESAI 
3016cf2e340fSJANAK DESAI 	return 0;
3017cf2e340fSJANAK DESAI }
3018cf2e340fSJANAK DESAI 
3019cf2e340fSJANAK DESAI /*
3020cf2e340fSJANAK DESAI  * unshare allows a process to 'unshare' part of the process
3021cf2e340fSJANAK DESAI  * context which was originally shared using clone.  copy_*
3022cad6967aSChristian Brauner  * functions used by kernel_clone() cannot be used here directly
3023cf2e340fSJANAK DESAI  * because they modify an inactive task_struct that is being
3024cf2e340fSJANAK DESAI  * constructed. Here we are modifying the current, active,
3025cf2e340fSJANAK DESAI  * task_struct.
3026cf2e340fSJANAK DESAI  */
30279b32105eSDominik Brodowski int ksys_unshare(unsigned long unshare_flags)
3028cf2e340fSJANAK DESAI {
3029cf2e340fSJANAK DESAI 	struct fs_struct *fs, *new_fs = NULL;
3030ba1f70ddSRan Xiaokai 	struct files_struct *new_fd = NULL;
3031b2e0d987SEric W. Biederman 	struct cred *new_cred = NULL;
3032cf7b708cSPavel Emelyanov 	struct nsproxy *new_nsproxy = NULL;
30339edff4abSManfred Spraul 	int do_sysvsem = 0;
30349bfb23fcSOleg Nesterov 	int err;
3035cf2e340fSJANAK DESAI 
303650804fe3SEric W. Biederman 	/*
3037faf00da5SEric W. Biederman 	 * If unsharing a user namespace must also unshare the thread group
3038faf00da5SEric W. Biederman 	 * and unshare the filesystem root and working directories.
3039b2e0d987SEric W. Biederman 	 */
3040b2e0d987SEric W. Biederman 	if (unshare_flags & CLONE_NEWUSER)
3041e66eded8SEric W. Biederman 		unshare_flags |= CLONE_THREAD | CLONE_FS;
3042b2e0d987SEric W. Biederman 	/*
304350804fe3SEric W. Biederman 	 * If unsharing vm, must also unshare signal handlers.
304450804fe3SEric W. Biederman 	 */
304550804fe3SEric W. Biederman 	if (unshare_flags & CLONE_VM)
304650804fe3SEric W. Biederman 		unshare_flags |= CLONE_SIGHAND;
30476013f67fSManfred Spraul 	/*
304812c641abSEric W. Biederman 	 * If unsharing a signal handlers, must also unshare the signal queues.
304912c641abSEric W. Biederman 	 */
305012c641abSEric W. Biederman 	if (unshare_flags & CLONE_SIGHAND)
305112c641abSEric W. Biederman 		unshare_flags |= CLONE_THREAD;
305212c641abSEric W. Biederman 	/*
30539bfb23fcSOleg Nesterov 	 * If unsharing namespace, must also unshare filesystem information.
30549bfb23fcSOleg Nesterov 	 */
30559bfb23fcSOleg Nesterov 	if (unshare_flags & CLONE_NEWNS)
30569bfb23fcSOleg Nesterov 		unshare_flags |= CLONE_FS;
305750804fe3SEric W. Biederman 
305850804fe3SEric W. Biederman 	err = check_unshare_flags(unshare_flags);
305950804fe3SEric W. Biederman 	if (err)
306050804fe3SEric W. Biederman 		goto bad_unshare_out;
30619bfb23fcSOleg Nesterov 	/*
30626013f67fSManfred Spraul 	 * CLONE_NEWIPC must also detach from the undolist: after switching
30636013f67fSManfred Spraul 	 * to a new ipc namespace, the semaphore arrays from the old
30646013f67fSManfred Spraul 	 * namespace are unreachable.
30656013f67fSManfred Spraul 	 */
30666013f67fSManfred Spraul 	if (unshare_flags & (CLONE_NEWIPC|CLONE_SYSVSEM))
30679edff4abSManfred Spraul 		do_sysvsem = 1;
3068fb0a685cSDaniel Rebelo de Oliveira 	err = unshare_fs(unshare_flags, &new_fs);
3069fb0a685cSDaniel Rebelo de Oliveira 	if (err)
30709bfb23fcSOleg Nesterov 		goto bad_unshare_out;
307160997c3dSChristian Brauner 	err = unshare_fd(unshare_flags, NR_OPEN_MAX, &new_fd);
3072fb0a685cSDaniel Rebelo de Oliveira 	if (err)
30739bfb23fcSOleg Nesterov 		goto bad_unshare_cleanup_fs;
3074b2e0d987SEric W. Biederman 	err = unshare_userns(unshare_flags, &new_cred);
3075fb0a685cSDaniel Rebelo de Oliveira 	if (err)
30769edff4abSManfred Spraul 		goto bad_unshare_cleanup_fd;
3077b2e0d987SEric W. Biederman 	err = unshare_nsproxy_namespaces(unshare_flags, &new_nsproxy,
3078b2e0d987SEric W. Biederman 					 new_cred, new_fs);
3079b2e0d987SEric W. Biederman 	if (err)
3080b2e0d987SEric W. Biederman 		goto bad_unshare_cleanup_cred;
3081cf2e340fSJANAK DESAI 
3082905ae01cSAlexey Gladkov 	if (new_cred) {
3083905ae01cSAlexey Gladkov 		err = set_cred_ucounts(new_cred);
3084905ae01cSAlexey Gladkov 		if (err)
3085905ae01cSAlexey Gladkov 			goto bad_unshare_cleanup_cred;
3086905ae01cSAlexey Gladkov 	}
3087905ae01cSAlexey Gladkov 
3088b2e0d987SEric W. Biederman 	if (new_fs || new_fd || do_sysvsem || new_cred || new_nsproxy) {
30899edff4abSManfred Spraul 		if (do_sysvsem) {
30909edff4abSManfred Spraul 			/*
30919edff4abSManfred Spraul 			 * CLONE_SYSVSEM is equivalent to sys_exit().
30929edff4abSManfred Spraul 			 */
30939edff4abSManfred Spraul 			exit_sem(current);
30949edff4abSManfred Spraul 		}
3095ab602f79SJack Miller 		if (unshare_flags & CLONE_NEWIPC) {
3096ab602f79SJack Miller 			/* Orphan segments in old ns (see sem above). */
3097ab602f79SJack Miller 			exit_shm(current);
3098ab602f79SJack Miller 			shm_init_task(current);
3099ab602f79SJack Miller 		}
3100ab516013SSerge E. Hallyn 
31016f977e6bSAlan Cox 		if (new_nsproxy)
3102cf7b708cSPavel Emelyanov 			switch_task_namespaces(current, new_nsproxy);
3103cf2e340fSJANAK DESAI 
3104cf7b708cSPavel Emelyanov 		task_lock(current);
3105cf7b708cSPavel Emelyanov 
3106cf2e340fSJANAK DESAI 		if (new_fs) {
3107cf2e340fSJANAK DESAI 			fs = current->fs;
31082a4419b5SNick Piggin 			spin_lock(&fs->lock);
3109cf2e340fSJANAK DESAI 			current->fs = new_fs;
3110498052bbSAl Viro 			if (--fs->users)
3111498052bbSAl Viro 				new_fs = NULL;
3112498052bbSAl Viro 			else
3113cf2e340fSJANAK DESAI 				new_fs = fs;
31142a4419b5SNick Piggin 			spin_unlock(&fs->lock);
3115cf2e340fSJANAK DESAI 		}
3116cf2e340fSJANAK DESAI 
3117ba1f70ddSRan Xiaokai 		if (new_fd)
3118ba1f70ddSRan Xiaokai 			swap(current->files, new_fd);
3119cf2e340fSJANAK DESAI 
3120cf2e340fSJANAK DESAI 		task_unlock(current);
3121b2e0d987SEric W. Biederman 
3122b2e0d987SEric W. Biederman 		if (new_cred) {
3123b2e0d987SEric W. Biederman 			/* Install the new user namespace */
3124b2e0d987SEric W. Biederman 			commit_creds(new_cred);
3125b2e0d987SEric W. Biederman 			new_cred = NULL;
3126b2e0d987SEric W. Biederman 		}
3127cf2e340fSJANAK DESAI 	}
3128cf2e340fSJANAK DESAI 
3129e4222673SHari Bathini 	perf_event_namespaces(current);
3130e4222673SHari Bathini 
3131b2e0d987SEric W. Biederman bad_unshare_cleanup_cred:
3132b2e0d987SEric W. Biederman 	if (new_cred)
3133b2e0d987SEric W. Biederman 		put_cred(new_cred);
3134cf2e340fSJANAK DESAI bad_unshare_cleanup_fd:
3135cf2e340fSJANAK DESAI 	if (new_fd)
3136cf2e340fSJANAK DESAI 		put_files_struct(new_fd);
3137cf2e340fSJANAK DESAI 
3138cf2e340fSJANAK DESAI bad_unshare_cleanup_fs:
3139cf2e340fSJANAK DESAI 	if (new_fs)
3140498052bbSAl Viro 		free_fs_struct(new_fs);
3141cf2e340fSJANAK DESAI 
3142cf2e340fSJANAK DESAI bad_unshare_out:
3143cf2e340fSJANAK DESAI 	return err;
3144cf2e340fSJANAK DESAI }
31453b125388SAl Viro 
31469b32105eSDominik Brodowski SYSCALL_DEFINE1(unshare, unsigned long, unshare_flags)
31479b32105eSDominik Brodowski {
31489b32105eSDominik Brodowski 	return ksys_unshare(unshare_flags);
31499b32105eSDominik Brodowski }
31509b32105eSDominik Brodowski 
31513b125388SAl Viro /*
31523b125388SAl Viro  *	Helper to unshare the files of the current task.
31533b125388SAl Viro  *	We don't want to expose copy_files internals to
31543b125388SAl Viro  *	the exec layer of the kernel.
31553b125388SAl Viro  */
31563b125388SAl Viro 
31571f702603SEric W. Biederman int unshare_files(void)
31583b125388SAl Viro {
31593b125388SAl Viro 	struct task_struct *task = current;
31601f702603SEric W. Biederman 	struct files_struct *old, *copy = NULL;
31613b125388SAl Viro 	int error;
31623b125388SAl Viro 
316360997c3dSChristian Brauner 	error = unshare_fd(CLONE_FILES, NR_OPEN_MAX, &copy);
31641f702603SEric W. Biederman 	if (error || !copy)
31653b125388SAl Viro 		return error;
31661f702603SEric W. Biederman 
31671f702603SEric W. Biederman 	old = task->files;
31683b125388SAl Viro 	task_lock(task);
31693b125388SAl Viro 	task->files = copy;
31703b125388SAl Viro 	task_unlock(task);
31711f702603SEric W. Biederman 	put_files_struct(old);
31723b125388SAl Viro 	return 0;
31733b125388SAl Viro }
317416db3d3fSHeinrich Schuchardt 
317516db3d3fSHeinrich Schuchardt int sysctl_max_threads(struct ctl_table *table, int write,
3176b0daa2c7STobias Klauser 		       void *buffer, size_t *lenp, loff_t *ppos)
317716db3d3fSHeinrich Schuchardt {
317816db3d3fSHeinrich Schuchardt 	struct ctl_table t;
317916db3d3fSHeinrich Schuchardt 	int ret;
318016db3d3fSHeinrich Schuchardt 	int threads = max_threads;
3181b0f53dbcSMichal Hocko 	int min = 1;
318216db3d3fSHeinrich Schuchardt 	int max = MAX_THREADS;
318316db3d3fSHeinrich Schuchardt 
318416db3d3fSHeinrich Schuchardt 	t = *table;
318516db3d3fSHeinrich Schuchardt 	t.data = &threads;
318616db3d3fSHeinrich Schuchardt 	t.extra1 = &min;
318716db3d3fSHeinrich Schuchardt 	t.extra2 = &max;
318816db3d3fSHeinrich Schuchardt 
318916db3d3fSHeinrich Schuchardt 	ret = proc_dointvec_minmax(&t, write, buffer, lenp, ppos);
319016db3d3fSHeinrich Schuchardt 	if (ret || !write)
319116db3d3fSHeinrich Schuchardt 		return ret;
319216db3d3fSHeinrich Schuchardt 
3193b0f53dbcSMichal Hocko 	max_threads = threads;
319416db3d3fSHeinrich Schuchardt 
319516db3d3fSHeinrich Schuchardt 	return 0;
319616db3d3fSHeinrich Schuchardt }
3197