xref: /openbmc/linux/kernel/fork.c (revision 14ef95be6f5558fb9e43aaf06ef9a1d6e0cae6c8)
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>
4050b5e49cSAlexander Potapenko #include <linux/kmsan.h>
411da177e4SLinus Torvalds #include <linux/binfmts.h>
421da177e4SLinus Torvalds #include <linux/mman.h>
43cddb8a5cSAndrea Arcangeli #include <linux/mmu_notifier.h>
441da177e4SLinus Torvalds #include <linux/fs.h>
45615d6e87SDavidlohr Bueso #include <linux/mm.h>
4617fca131SArnd Bergmann #include <linux/mm_inline.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>
78522ed776SMiloslav Trmac #include <linux/tty.h>
795ad4e53bSAl Viro #include <linux/fs_struct.h>
807c9f8861SEric Sandeen #include <linux/magic.h>
81cdd6c482SIngo Molnar #include <linux/perf_event.h>
8242c4ab41SStanislaw Gruszka #include <linux/posix-timers.h>
838e7cac79SAvi Kivity #include <linux/user-return-notifier.h>
843d5992d2SYing Han #include <linux/oom.h>
85ba76149fSAndrea Arcangeli #include <linux/khugepaged.h>
86d80e731eSOleg Nesterov #include <linux/signalfd.h>
870326f5a9SSrikar Dronamraju #include <linux/uprobes.h>
88a27bb332SKent Overstreet #include <linux/aio.h>
8952f5684cSGideon Israel Dsouza #include <linux/compiler.h>
9016db3d3fSHeinrich Schuchardt #include <linux/sysctl.h>
915c9a8750SDmitry Vyukov #include <linux/kcov.h>
92d83a7cb3SJosh Poimboeuf #include <linux/livepatch.h>
9348ac3c18SMark Rutland #include <linux/thread_info.h>
94afaef01cSAlexander Popov #include <linux/stackleak.h>
95eafb149eSDaniel Axtens #include <linux/kasan.h>
96d08b9f0cSSami Tolvanen #include <linux/scs.h>
970f212204SJens Axboe #include <linux/io_uring.h>
98a10787e6SSong Liu #include <linux/bpf.h>
99b3883a9aSJason A. Donenfeld #include <linux/stackprotector.h>
100fd593511SBeau Belgrave #include <linux/user_events.h>
101cd389115SJacob Pan #include <linux/iommu.h>
1021da177e4SLinus Torvalds 
1031da177e4SLinus Torvalds #include <asm/pgalloc.h>
1047c0f6ba6SLinus Torvalds #include <linux/uaccess.h>
1051da177e4SLinus Torvalds #include <asm/mmu_context.h>
1061da177e4SLinus Torvalds #include <asm/cacheflush.h>
1071da177e4SLinus Torvalds #include <asm/tlbflush.h>
1081da177e4SLinus Torvalds 
109ad8d75ffSSteven Rostedt #include <trace/events/sched.h>
110ad8d75ffSSteven Rostedt 
11143d2b113SKAMEZAWA Hiroyuki #define CREATE_TRACE_POINTS
11243d2b113SKAMEZAWA Hiroyuki #include <trace/events/task.h>
11343d2b113SKAMEZAWA Hiroyuki 
1141da177e4SLinus Torvalds /*
115ac1b398dSHeinrich Schuchardt  * Minimum number of threads to boot the kernel
116ac1b398dSHeinrich Schuchardt  */
117ac1b398dSHeinrich Schuchardt #define MIN_THREADS 20
118ac1b398dSHeinrich Schuchardt 
119ac1b398dSHeinrich Schuchardt /*
120ac1b398dSHeinrich Schuchardt  * Maximum number of threads
121ac1b398dSHeinrich Schuchardt  */
122ac1b398dSHeinrich Schuchardt #define MAX_THREADS FUTEX_TID_MASK
123ac1b398dSHeinrich Schuchardt 
124ac1b398dSHeinrich Schuchardt /*
1251da177e4SLinus Torvalds  * Protected counters by write_lock_irq(&tasklist_lock)
1261da177e4SLinus Torvalds  */
1271da177e4SLinus Torvalds unsigned long total_forks;	/* Handle normal Linux uptimes. */
1281da177e4SLinus Torvalds int nr_threads;			/* The idle threads do not count.. */
1291da177e4SLinus Torvalds 
1308856ae4dSKefeng Wang static int max_threads;		/* tunable limit on nr_threads */
1311da177e4SLinus Torvalds 
1328495f7e6SSai Praneeth Prakhya #define NAMED_ARRAY_INDEX(x)	[x] = __stringify(x)
1338495f7e6SSai Praneeth Prakhya 
1348495f7e6SSai Praneeth Prakhya static const char * const resident_page_types[] = {
1358495f7e6SSai Praneeth Prakhya 	NAMED_ARRAY_INDEX(MM_FILEPAGES),
1368495f7e6SSai Praneeth Prakhya 	NAMED_ARRAY_INDEX(MM_ANONPAGES),
1378495f7e6SSai Praneeth Prakhya 	NAMED_ARRAY_INDEX(MM_SWAPENTS),
1388495f7e6SSai Praneeth Prakhya 	NAMED_ARRAY_INDEX(MM_SHMEMPAGES),
1398495f7e6SSai Praneeth Prakhya };
1408495f7e6SSai Praneeth Prakhya 
1411da177e4SLinus Torvalds DEFINE_PER_CPU(unsigned long, process_counts) = 0;
1421da177e4SLinus Torvalds 
1431da177e4SLinus Torvalds __cacheline_aligned DEFINE_RWLOCK(tasklist_lock);  /* outer */
144db1466b3SPaul E. McKenney 
145db1466b3SPaul E. McKenney #ifdef CONFIG_PROVE_RCU
146db1466b3SPaul E. McKenney int lockdep_tasklist_lock_is_held(void)
147db1466b3SPaul E. McKenney {
148db1466b3SPaul E. McKenney 	return lockdep_is_held(&tasklist_lock);
149db1466b3SPaul E. McKenney }
150db1466b3SPaul E. McKenney EXPORT_SYMBOL_GPL(lockdep_tasklist_lock_is_held);
151db1466b3SPaul E. McKenney #endif /* #ifdef CONFIG_PROVE_RCU */
1521da177e4SLinus Torvalds 
1531da177e4SLinus Torvalds int nr_processes(void)
1541da177e4SLinus Torvalds {
1551da177e4SLinus Torvalds 	int cpu;
1561da177e4SLinus Torvalds 	int total = 0;
1571da177e4SLinus Torvalds 
1581d510750SIan Campbell 	for_each_possible_cpu(cpu)
1591da177e4SLinus Torvalds 		total += per_cpu(process_counts, cpu);
1601da177e4SLinus Torvalds 
1611da177e4SLinus Torvalds 	return total;
1621da177e4SLinus Torvalds }
1631da177e4SLinus Torvalds 
164f19b9f74SAkinobu Mita void __weak arch_release_task_struct(struct task_struct *tsk)
165f19b9f74SAkinobu Mita {
166f19b9f74SAkinobu Mita }
167f19b9f74SAkinobu Mita 
168f5e10287SThomas Gleixner #ifndef CONFIG_ARCH_TASK_STRUCT_ALLOCATOR
169e18b890bSChristoph Lameter static struct kmem_cache *task_struct_cachep;
17041101809SThomas Gleixner 
17141101809SThomas Gleixner static inline struct task_struct *alloc_task_struct_node(int node)
17241101809SThomas Gleixner {
17341101809SThomas Gleixner 	return kmem_cache_alloc_node(task_struct_cachep, GFP_KERNEL, node);
17441101809SThomas Gleixner }
17541101809SThomas Gleixner 
17641101809SThomas Gleixner static inline void free_task_struct(struct task_struct *tsk)
17741101809SThomas Gleixner {
17841101809SThomas Gleixner 	kmem_cache_free(task_struct_cachep, tsk);
17941101809SThomas Gleixner }
1801da177e4SLinus Torvalds #endif
1811da177e4SLinus Torvalds 
182b235beeaSLinus Torvalds #ifndef CONFIG_ARCH_THREAD_STACK_ALLOCATOR
18341101809SThomas Gleixner 
1840d15d74aSThomas Gleixner /*
1850d15d74aSThomas Gleixner  * Allocate pages if THREAD_SIZE is >= PAGE_SIZE, otherwise use a
1860d15d74aSThomas Gleixner  * kmemcache based allocator.
1870d15d74aSThomas Gleixner  */
188ba14a194SAndy Lutomirski # if THREAD_SIZE >= PAGE_SIZE || defined(CONFIG_VMAP_STACK)
189ac496bf4SAndy Lutomirski 
190ac496bf4SAndy Lutomirski #  ifdef CONFIG_VMAP_STACK
191ac496bf4SAndy Lutomirski /*
192ac496bf4SAndy Lutomirski  * vmalloc() is a bit slow, and calling vfree() enough times will force a TLB
193ac496bf4SAndy Lutomirski  * flush.  Try to minimize the number of calls by caching stacks.
194ac496bf4SAndy Lutomirski  */
195ac496bf4SAndy Lutomirski #define NR_CACHED_STACKS 2
196ac496bf4SAndy Lutomirski static DEFINE_PER_CPU(struct vm_struct *, cached_stacks[NR_CACHED_STACKS]);
19719659c59SHoeun Ryu 
198e540bf31SSebastian Andrzej Siewior struct vm_stack {
199e540bf31SSebastian Andrzej Siewior 	struct rcu_head rcu;
200e540bf31SSebastian Andrzej Siewior 	struct vm_struct *stack_vm_area;
201e540bf31SSebastian Andrzej Siewior };
202e540bf31SSebastian Andrzej Siewior 
203e540bf31SSebastian Andrzej Siewior static bool try_release_thread_stack_to_cache(struct vm_struct *vm)
204e540bf31SSebastian Andrzej Siewior {
205e540bf31SSebastian Andrzej Siewior 	unsigned int i;
206e540bf31SSebastian Andrzej Siewior 
207e540bf31SSebastian Andrzej Siewior 	for (i = 0; i < NR_CACHED_STACKS; i++) {
208e540bf31SSebastian Andrzej Siewior 		if (this_cpu_cmpxchg(cached_stacks[i], NULL, vm) != NULL)
209e540bf31SSebastian Andrzej Siewior 			continue;
210e540bf31SSebastian Andrzej Siewior 		return true;
211e540bf31SSebastian Andrzej Siewior 	}
212e540bf31SSebastian Andrzej Siewior 	return false;
213e540bf31SSebastian Andrzej Siewior }
214e540bf31SSebastian Andrzej Siewior 
215e540bf31SSebastian Andrzej Siewior static void thread_stack_free_rcu(struct rcu_head *rh)
216e540bf31SSebastian Andrzej Siewior {
217e540bf31SSebastian Andrzej Siewior 	struct vm_stack *vm_stack = container_of(rh, struct vm_stack, rcu);
218e540bf31SSebastian Andrzej Siewior 
219e540bf31SSebastian Andrzej Siewior 	if (try_release_thread_stack_to_cache(vm_stack->stack_vm_area))
220e540bf31SSebastian Andrzej Siewior 		return;
221e540bf31SSebastian Andrzej Siewior 
222e540bf31SSebastian Andrzej Siewior 	vfree(vm_stack);
223e540bf31SSebastian Andrzej Siewior }
224e540bf31SSebastian Andrzej Siewior 
225e540bf31SSebastian Andrzej Siewior static void thread_stack_delayed_free(struct task_struct *tsk)
226e540bf31SSebastian Andrzej Siewior {
227e540bf31SSebastian Andrzej Siewior 	struct vm_stack *vm_stack = tsk->stack;
228e540bf31SSebastian Andrzej Siewior 
229e540bf31SSebastian Andrzej Siewior 	vm_stack->stack_vm_area = tsk->stack_vm_area;
230e540bf31SSebastian Andrzej Siewior 	call_rcu(&vm_stack->rcu, thread_stack_free_rcu);
231e540bf31SSebastian Andrzej Siewior }
232e540bf31SSebastian Andrzej Siewior 
23319659c59SHoeun Ryu static int free_vm_stack_cache(unsigned int cpu)
23419659c59SHoeun Ryu {
23519659c59SHoeun Ryu 	struct vm_struct **cached_vm_stacks = per_cpu_ptr(cached_stacks, cpu);
23619659c59SHoeun Ryu 	int i;
23719659c59SHoeun Ryu 
23819659c59SHoeun Ryu 	for (i = 0; i < NR_CACHED_STACKS; i++) {
23919659c59SHoeun Ryu 		struct vm_struct *vm_stack = cached_vm_stacks[i];
24019659c59SHoeun Ryu 
24119659c59SHoeun Ryu 		if (!vm_stack)
24219659c59SHoeun Ryu 			continue;
24319659c59SHoeun Ryu 
24419659c59SHoeun Ryu 		vfree(vm_stack->addr);
24519659c59SHoeun Ryu 		cached_vm_stacks[i] = NULL;
24619659c59SHoeun Ryu 	}
24719659c59SHoeun Ryu 
24819659c59SHoeun Ryu 	return 0;
24919659c59SHoeun Ryu }
250ac496bf4SAndy Lutomirski 
2511a03d3f1SSebastian Andrzej Siewior static int memcg_charge_kernel_stack(struct vm_struct *vm)
252b69c49b7SFUJITA Tomonori {
253f1c1a9eeSSebastian Andrzej Siewior 	int i;
254f1c1a9eeSSebastian Andrzej Siewior 	int ret;
2554e2f6342SHaifeng Xu 	int nr_charged = 0;
256f1c1a9eeSSebastian Andrzej Siewior 
257f1c1a9eeSSebastian Andrzej Siewior 	BUG_ON(vm->nr_pages != THREAD_SIZE / PAGE_SIZE);
258f1c1a9eeSSebastian Andrzej Siewior 
259f1c1a9eeSSebastian Andrzej Siewior 	for (i = 0; i < THREAD_SIZE / PAGE_SIZE; i++) {
260f1c1a9eeSSebastian Andrzej Siewior 		ret = memcg_kmem_charge_page(vm->pages[i], GFP_KERNEL, 0);
261f1c1a9eeSSebastian Andrzej Siewior 		if (ret)
262f1c1a9eeSSebastian Andrzej Siewior 			goto err;
2634e2f6342SHaifeng Xu 		nr_charged++;
264f1c1a9eeSSebastian Andrzej Siewior 	}
265f1c1a9eeSSebastian Andrzej Siewior 	return 0;
266f1c1a9eeSSebastian Andrzej Siewior err:
2674e2f6342SHaifeng Xu 	for (i = 0; i < nr_charged; i++)
268f1c1a9eeSSebastian Andrzej Siewior 		memcg_kmem_uncharge_page(vm->pages[i], 0);
269f1c1a9eeSSebastian Andrzej Siewior 	return ret;
270f1c1a9eeSSebastian Andrzej Siewior }
271f1c1a9eeSSebastian Andrzej Siewior 
2727865aba3SSebastian Andrzej Siewior static int alloc_thread_stack_node(struct task_struct *tsk, int node)
273b69c49b7SFUJITA Tomonori {
2741a03d3f1SSebastian Andrzej Siewior 	struct vm_struct *vm;
275ac496bf4SAndy Lutomirski 	void *stack;
276ac496bf4SAndy Lutomirski 	int i;
277ac496bf4SAndy Lutomirski 
278ac496bf4SAndy Lutomirski 	for (i = 0; i < NR_CACHED_STACKS; i++) {
279112166f8SChristoph Lameter 		struct vm_struct *s;
280112166f8SChristoph Lameter 
281112166f8SChristoph Lameter 		s = this_cpu_xchg(cached_stacks[i], NULL);
282ac496bf4SAndy Lutomirski 
283ac496bf4SAndy Lutomirski 		if (!s)
284ac496bf4SAndy Lutomirski 			continue;
285ac496bf4SAndy Lutomirski 
28651fb34deSAndrey Konovalov 		/* Reset stack metadata. */
287cebd0eb2SAndrey Konovalov 		kasan_unpoison_range(s->addr, THREAD_SIZE);
288eafb149eSDaniel Axtens 
28951fb34deSAndrey Konovalov 		stack = kasan_reset_tag(s->addr);
29051fb34deSAndrey Konovalov 
291ca182551SKonstantin Khlebnikov 		/* Clear stale pointers from reused stack. */
29251fb34deSAndrey Konovalov 		memset(stack, 0, THREAD_SIZE);
293e01e8063SKees Cook 
2941a03d3f1SSebastian Andrzej Siewior 		if (memcg_charge_kernel_stack(s)) {
295f1c1a9eeSSebastian Andrzej Siewior 			vfree(s->addr);
296f1c1a9eeSSebastian Andrzej Siewior 			return -ENOMEM;
297f1c1a9eeSSebastian Andrzej Siewior 		}
298f1c1a9eeSSebastian Andrzej Siewior 
299ac496bf4SAndy Lutomirski 		tsk->stack_vm_area = s;
30051fb34deSAndrey Konovalov 		tsk->stack = stack;
3017865aba3SSebastian Andrzej Siewior 		return 0;
302ac496bf4SAndy Lutomirski 	}
303ac496bf4SAndy Lutomirski 
3049b6f7e16SRoman Gushchin 	/*
3059b6f7e16SRoman Gushchin 	 * Allocated stacks are cached and later reused by new threads,
3069b6f7e16SRoman Gushchin 	 * so memcg accounting is performed manually on assigning/releasing
3079b6f7e16SRoman Gushchin 	 * stacks to tasks. Drop __GFP_ACCOUNT.
3089b6f7e16SRoman Gushchin 	 */
30948ac3c18SMark Rutland 	stack = __vmalloc_node_range(THREAD_SIZE, THREAD_ALIGN,
310ba14a194SAndy Lutomirski 				     VMALLOC_START, VMALLOC_END,
3119b6f7e16SRoman Gushchin 				     THREADINFO_GFP & ~__GFP_ACCOUNT,
312ba14a194SAndy Lutomirski 				     PAGE_KERNEL,
313ac496bf4SAndy Lutomirski 				     0, node, __builtin_return_address(0));
3147865aba3SSebastian Andrzej Siewior 	if (!stack)
3157865aba3SSebastian Andrzej Siewior 		return -ENOMEM;
316ba14a194SAndy Lutomirski 
3171a03d3f1SSebastian Andrzej Siewior 	vm = find_vm_area(stack);
3181a03d3f1SSebastian Andrzej Siewior 	if (memcg_charge_kernel_stack(vm)) {
319f1c1a9eeSSebastian Andrzej Siewior 		vfree(stack);
320f1c1a9eeSSebastian Andrzej Siewior 		return -ENOMEM;
321f1c1a9eeSSebastian Andrzej Siewior 	}
322ba14a194SAndy Lutomirski 	/*
323ba14a194SAndy Lutomirski 	 * We can't call find_vm_area() in interrupt context, and
324ba14a194SAndy Lutomirski 	 * free_thread_stack() can be called in interrupt context,
325ba14a194SAndy Lutomirski 	 * so cache the vm_struct.
326ba14a194SAndy Lutomirski 	 */
3271a03d3f1SSebastian Andrzej Siewior 	tsk->stack_vm_area = vm;
328c08e6a12SAndrey Konovalov 	stack = kasan_reset_tag(stack);
3295eed6f1dSRik van Riel 	tsk->stack = stack;
3307865aba3SSebastian Andrzej Siewior 	return 0;
3315eed6f1dSRik van Riel }
332be9a2277SSebastian Andrzej Siewior 
333be9a2277SSebastian Andrzej Siewior static void free_thread_stack(struct task_struct *tsk)
334be9a2277SSebastian Andrzej Siewior {
335e540bf31SSebastian Andrzej Siewior 	if (!try_release_thread_stack_to_cache(tsk->stack_vm_area))
336e540bf31SSebastian Andrzej Siewior 		thread_stack_delayed_free(tsk);
337be9a2277SSebastian Andrzej Siewior 
338be9a2277SSebastian Andrzej Siewior 	tsk->stack = NULL;
339be9a2277SSebastian Andrzej Siewior 	tsk->stack_vm_area = NULL;
340be9a2277SSebastian Andrzej Siewior }
341be9a2277SSebastian Andrzej Siewior 
342be9a2277SSebastian Andrzej Siewior #  else /* !CONFIG_VMAP_STACK */
343be9a2277SSebastian Andrzej Siewior 
344e540bf31SSebastian Andrzej Siewior static void thread_stack_free_rcu(struct rcu_head *rh)
345e540bf31SSebastian Andrzej Siewior {
346e540bf31SSebastian Andrzej Siewior 	__free_pages(virt_to_page(rh), THREAD_SIZE_ORDER);
347e540bf31SSebastian Andrzej Siewior }
348e540bf31SSebastian Andrzej Siewior 
349e540bf31SSebastian Andrzej Siewior static void thread_stack_delayed_free(struct task_struct *tsk)
350e540bf31SSebastian Andrzej Siewior {
351e540bf31SSebastian Andrzej Siewior 	struct rcu_head *rh = tsk->stack;
352e540bf31SSebastian Andrzej Siewior 
353e540bf31SSebastian Andrzej Siewior 	call_rcu(rh, thread_stack_free_rcu);
354e540bf31SSebastian Andrzej Siewior }
355e540bf31SSebastian Andrzej Siewior 
3567865aba3SSebastian Andrzej Siewior static int alloc_thread_stack_node(struct task_struct *tsk, int node)
357be9a2277SSebastian Andrzej Siewior {
3584949148aSVladimir Davydov 	struct page *page = alloc_pages_node(node, THREADINFO_GFP,
3592889f608SThomas Gleixner 					     THREAD_SIZE_ORDER);
360b6a84016SEric Dumazet 
3611bf4580eSAndrea Arcangeli 	if (likely(page)) {
3628dcc1d34SAndrey Konovalov 		tsk->stack = kasan_reset_tag(page_address(page));
3637865aba3SSebastian Andrzej Siewior 		return 0;
3641bf4580eSAndrea Arcangeli 	}
3657865aba3SSebastian Andrzej Siewior 	return -ENOMEM;
366b69c49b7SFUJITA Tomonori }
367b69c49b7SFUJITA Tomonori 
368be9a2277SSebastian Andrzej Siewior static void free_thread_stack(struct task_struct *tsk)
369b69c49b7SFUJITA Tomonori {
370e540bf31SSebastian Andrzej Siewior 	thread_stack_delayed_free(tsk);
371be9a2277SSebastian Andrzej Siewior 	tsk->stack = NULL;
372ac496bf4SAndy Lutomirski }
373ac496bf4SAndy Lutomirski 
374be9a2277SSebastian Andrzej Siewior #  endif /* CONFIG_VMAP_STACK */
375be9a2277SSebastian Andrzej Siewior # else /* !(THREAD_SIZE >= PAGE_SIZE || defined(CONFIG_VMAP_STACK)) */
376ac496bf4SAndy Lutomirski 
377b235beeaSLinus Torvalds static struct kmem_cache *thread_stack_cache;
3780d15d74aSThomas Gleixner 
379e540bf31SSebastian Andrzej Siewior static void thread_stack_free_rcu(struct rcu_head *rh)
380e540bf31SSebastian Andrzej Siewior {
381e540bf31SSebastian Andrzej Siewior 	kmem_cache_free(thread_stack_cache, rh);
382e540bf31SSebastian Andrzej Siewior }
383e540bf31SSebastian Andrzej Siewior 
384e540bf31SSebastian Andrzej Siewior static void thread_stack_delayed_free(struct task_struct *tsk)
385e540bf31SSebastian Andrzej Siewior {
386e540bf31SSebastian Andrzej Siewior 	struct rcu_head *rh = tsk->stack;
387e540bf31SSebastian Andrzej Siewior 
388e540bf31SSebastian Andrzej Siewior 	call_rcu(rh, thread_stack_free_rcu);
389e540bf31SSebastian Andrzej Siewior }
390e540bf31SSebastian Andrzej Siewior 
3917865aba3SSebastian Andrzej Siewior static int alloc_thread_stack_node(struct task_struct *tsk, int node)
3920d15d74aSThomas Gleixner {
3935eed6f1dSRik van Riel 	unsigned long *stack;
3945eed6f1dSRik van Riel 	stack = kmem_cache_alloc_node(thread_stack_cache, THREADINFO_GFP, node);
3958dcc1d34SAndrey Konovalov 	stack = kasan_reset_tag(stack);
3965eed6f1dSRik van Riel 	tsk->stack = stack;
3977865aba3SSebastian Andrzej Siewior 	return stack ? 0 : -ENOMEM;
3980d15d74aSThomas Gleixner }
3990d15d74aSThomas Gleixner 
400ba14a194SAndy Lutomirski static void free_thread_stack(struct task_struct *tsk)
4010d15d74aSThomas Gleixner {
402e540bf31SSebastian Andrzej Siewior 	thread_stack_delayed_free(tsk);
403be9a2277SSebastian Andrzej Siewior 	tsk->stack = NULL;
4040d15d74aSThomas Gleixner }
4050d15d74aSThomas Gleixner 
406b235beeaSLinus Torvalds void thread_stack_cache_init(void)
4070d15d74aSThomas Gleixner {
408f9d29946SDavid Windsor 	thread_stack_cache = kmem_cache_create_usercopy("thread_stack",
409f9d29946SDavid Windsor 					THREAD_SIZE, THREAD_SIZE, 0, 0,
410f9d29946SDavid Windsor 					THREAD_SIZE, NULL);
411b235beeaSLinus Torvalds 	BUG_ON(thread_stack_cache == NULL);
4120d15d74aSThomas Gleixner }
413be9a2277SSebastian Andrzej Siewior 
414be9a2277SSebastian Andrzej Siewior # endif /* THREAD_SIZE >= PAGE_SIZE || defined(CONFIG_VMAP_STACK) */
4152bb0529cSSebastian Andrzej Siewior #else /* CONFIG_ARCH_THREAD_STACK_ALLOCATOR */
4162bb0529cSSebastian Andrzej Siewior 
4177865aba3SSebastian Andrzej Siewior static int alloc_thread_stack_node(struct task_struct *tsk, int node)
4182bb0529cSSebastian Andrzej Siewior {
4192bb0529cSSebastian Andrzej Siewior 	unsigned long *stack;
4202bb0529cSSebastian Andrzej Siewior 
4212bb0529cSSebastian Andrzej Siewior 	stack = arch_alloc_thread_stack_node(tsk, node);
4222bb0529cSSebastian Andrzej Siewior 	tsk->stack = stack;
4237865aba3SSebastian Andrzej Siewior 	return stack ? 0 : -ENOMEM;
4242bb0529cSSebastian Andrzej Siewior }
4252bb0529cSSebastian Andrzej Siewior 
4262bb0529cSSebastian Andrzej Siewior static void free_thread_stack(struct task_struct *tsk)
4272bb0529cSSebastian Andrzej Siewior {
4282bb0529cSSebastian Andrzej Siewior 	arch_free_thread_stack(tsk);
4292bb0529cSSebastian Andrzej Siewior 	tsk->stack = NULL;
4302bb0529cSSebastian Andrzej Siewior }
4312bb0529cSSebastian Andrzej Siewior 
432be9a2277SSebastian Andrzej Siewior #endif /* !CONFIG_ARCH_THREAD_STACK_ALLOCATOR */
433b69c49b7SFUJITA Tomonori 
4341da177e4SLinus Torvalds /* SLAB cache for signal_struct structures (tsk->signal) */
435e18b890bSChristoph Lameter static struct kmem_cache *signal_cachep;
4361da177e4SLinus Torvalds 
4371da177e4SLinus Torvalds /* SLAB cache for sighand_struct structures (tsk->sighand) */
438e18b890bSChristoph Lameter struct kmem_cache *sighand_cachep;
4391da177e4SLinus Torvalds 
4401da177e4SLinus Torvalds /* SLAB cache for files_struct structures (tsk->files) */
441e18b890bSChristoph Lameter struct kmem_cache *files_cachep;
4421da177e4SLinus Torvalds 
4431da177e4SLinus Torvalds /* SLAB cache for fs_struct structures (tsk->fs) */
444e18b890bSChristoph Lameter struct kmem_cache *fs_cachep;
4451da177e4SLinus Torvalds 
4461da177e4SLinus Torvalds /* SLAB cache for vm_area_struct structures */
4473928d4f5SLinus Torvalds static struct kmem_cache *vm_area_cachep;
4481da177e4SLinus Torvalds 
4491da177e4SLinus Torvalds /* SLAB cache for mm_struct structures (tsk->mm) */
450e18b890bSChristoph Lameter static struct kmem_cache *mm_cachep;
4511da177e4SLinus Torvalds 
452c7f8f31cSSuren Baghdasaryan #ifdef CONFIG_PER_VMA_LOCK
453c7f8f31cSSuren Baghdasaryan 
454c7f8f31cSSuren Baghdasaryan /* SLAB cache for vm_area_struct.lock */
455c7f8f31cSSuren Baghdasaryan static struct kmem_cache *vma_lock_cachep;
456c7f8f31cSSuren Baghdasaryan 
457c7f8f31cSSuren Baghdasaryan static bool vma_lock_alloc(struct vm_area_struct *vma)
458c7f8f31cSSuren Baghdasaryan {
459c7f8f31cSSuren Baghdasaryan 	vma->vm_lock = kmem_cache_alloc(vma_lock_cachep, GFP_KERNEL);
460c7f8f31cSSuren Baghdasaryan 	if (!vma->vm_lock)
461c7f8f31cSSuren Baghdasaryan 		return false;
462c7f8f31cSSuren Baghdasaryan 
463c7f8f31cSSuren Baghdasaryan 	init_rwsem(&vma->vm_lock->lock);
464c7f8f31cSSuren Baghdasaryan 	vma->vm_lock_seq = -1;
465c7f8f31cSSuren Baghdasaryan 
466c7f8f31cSSuren Baghdasaryan 	return true;
467c7f8f31cSSuren Baghdasaryan }
468c7f8f31cSSuren Baghdasaryan 
469c7f8f31cSSuren Baghdasaryan static inline void vma_lock_free(struct vm_area_struct *vma)
470c7f8f31cSSuren Baghdasaryan {
471c7f8f31cSSuren Baghdasaryan 	kmem_cache_free(vma_lock_cachep, vma->vm_lock);
472c7f8f31cSSuren Baghdasaryan }
473c7f8f31cSSuren Baghdasaryan 
474c7f8f31cSSuren Baghdasaryan #else /* CONFIG_PER_VMA_LOCK */
475c7f8f31cSSuren Baghdasaryan 
476c7f8f31cSSuren Baghdasaryan static inline bool vma_lock_alloc(struct vm_area_struct *vma) { return true; }
477c7f8f31cSSuren Baghdasaryan static inline void vma_lock_free(struct vm_area_struct *vma) {}
478c7f8f31cSSuren Baghdasaryan 
479c7f8f31cSSuren Baghdasaryan #endif /* CONFIG_PER_VMA_LOCK */
480c7f8f31cSSuren Baghdasaryan 
481490fc053SLinus Torvalds struct vm_area_struct *vm_area_alloc(struct mm_struct *mm)
4823928d4f5SLinus Torvalds {
483a670468fSAndrew Morton 	struct vm_area_struct *vma;
484490fc053SLinus Torvalds 
485a670468fSAndrew Morton 	vma = kmem_cache_alloc(vm_area_cachep, GFP_KERNEL);
486c7f8f31cSSuren Baghdasaryan 	if (!vma)
487c7f8f31cSSuren Baghdasaryan 		return NULL;
488c7f8f31cSSuren Baghdasaryan 
489027232daSKirill A. Shutemov 	vma_init(vma, mm);
490c7f8f31cSSuren Baghdasaryan 	if (!vma_lock_alloc(vma)) {
491c7f8f31cSSuren Baghdasaryan 		kmem_cache_free(vm_area_cachep, vma);
492c7f8f31cSSuren Baghdasaryan 		return NULL;
493c7f8f31cSSuren Baghdasaryan 	}
494c7f8f31cSSuren Baghdasaryan 
495490fc053SLinus Torvalds 	return vma;
4963928d4f5SLinus Torvalds }
4973928d4f5SLinus Torvalds 
4983928d4f5SLinus Torvalds struct vm_area_struct *vm_area_dup(struct vm_area_struct *orig)
4993928d4f5SLinus Torvalds {
50095faf699SLinus Torvalds 	struct vm_area_struct *new = kmem_cache_alloc(vm_area_cachep, GFP_KERNEL);
50195faf699SLinus Torvalds 
502c7f8f31cSSuren Baghdasaryan 	if (!new)
503c7f8f31cSSuren Baghdasaryan 		return NULL;
504c7f8f31cSSuren Baghdasaryan 
505cda099b3SQian Cai 	ASSERT_EXCLUSIVE_WRITER(orig->vm_flags);
506cda099b3SQian Cai 	ASSERT_EXCLUSIVE_WRITER(orig->vm_file);
507cda099b3SQian Cai 	/*
508cda099b3SQian Cai 	 * orig->shared.rb may be modified concurrently, but the clone
509cda099b3SQian Cai 	 * will be reinitialized.
510cda099b3SQian Cai 	 */
51106e78b61SSuren Baghdasaryan 	data_race(memcpy(new, orig, sizeof(*new)));
512c7f8f31cSSuren Baghdasaryan 	if (!vma_lock_alloc(new)) {
513c7f8f31cSSuren Baghdasaryan 		kmem_cache_free(vm_area_cachep, new);
514c7f8f31cSSuren Baghdasaryan 		return NULL;
51595faf699SLinus Torvalds 	}
516c7f8f31cSSuren Baghdasaryan 	INIT_LIST_HEAD(&new->anon_vma_chain);
517ef6a22b7SMel Gorman 	vma_numab_state_init(new);
518c7f8f31cSSuren Baghdasaryan 	dup_anon_vma_name(orig, new);
519c7f8f31cSSuren Baghdasaryan 
52095faf699SLinus Torvalds 	return new;
5213928d4f5SLinus Torvalds }
5223928d4f5SLinus Torvalds 
5230d2ebf9cSSuren Baghdasaryan void __vm_area_free(struct vm_area_struct *vma)
5243928d4f5SLinus Torvalds {
525ef6a22b7SMel Gorman 	vma_numab_state_free(vma);
5265c26f6acSSuren Baghdasaryan 	free_anon_vma_name(vma);
527c7f8f31cSSuren Baghdasaryan 	vma_lock_free(vma);
5283928d4f5SLinus Torvalds 	kmem_cache_free(vm_area_cachep, vma);
5293928d4f5SLinus Torvalds }
5303928d4f5SLinus Torvalds 
53120cce633SMichel Lespinasse #ifdef CONFIG_PER_VMA_LOCK
53220cce633SMichel Lespinasse static void vm_area_free_rcu_cb(struct rcu_head *head)
53320cce633SMichel Lespinasse {
53420cce633SMichel Lespinasse 	struct vm_area_struct *vma = container_of(head, struct vm_area_struct,
53520cce633SMichel Lespinasse 						  vm_rcu);
536f2e13784SSuren Baghdasaryan 
537f2e13784SSuren Baghdasaryan 	/* The vma should not be locked while being destroyed. */
538c7f8f31cSSuren Baghdasaryan 	VM_BUG_ON_VMA(rwsem_is_locked(&vma->vm_lock->lock), vma);
53920cce633SMichel Lespinasse 	__vm_area_free(vma);
54020cce633SMichel Lespinasse }
54120cce633SMichel Lespinasse #endif
54220cce633SMichel Lespinasse 
5431da177e4SLinus Torvalds void vm_area_free(struct vm_area_struct *vma)
5441da177e4SLinus Torvalds {
54520cce633SMichel Lespinasse #ifdef CONFIG_PER_VMA_LOCK
54620cce633SMichel Lespinasse 	call_rcu(&vma->vm_rcu, vm_area_free_rcu_cb);
54720cce633SMichel Lespinasse #else
54820cce633SMichel Lespinasse 	__vm_area_free(vma);
54920cce633SMichel Lespinasse #endif
5501da177e4SLinus Torvalds }
5511da177e4SLinus Torvalds 
552ba14a194SAndy Lutomirski static void account_kernel_stack(struct task_struct *tsk, int account)
553c6a7f572SKOSAKI Motohiro {
5540ce055f8SSebastian Andrzej Siewior 	if (IS_ENABLED(CONFIG_VMAP_STACK)) {
555ba14a194SAndy Lutomirski 		struct vm_struct *vm = task_stack_vm_area(tsk);
55627faca83SMuchun Song 		int i;
557ba14a194SAndy Lutomirski 
55827faca83SMuchun Song 		for (i = 0; i < THREAD_SIZE / PAGE_SIZE; i++)
55927faca83SMuchun Song 			mod_lruvec_page_state(vm->pages[i], NR_KERNEL_STACK_KB,
56027faca83SMuchun Song 					      account * (PAGE_SIZE / 1024));
56127faca83SMuchun Song 	} else {
5620ce055f8SSebastian Andrzej Siewior 		void *stack = task_stack_page(tsk);
5630ce055f8SSebastian Andrzej Siewior 
564991e7673SShakeel Butt 		/* All stack pages are in the same node. */
565da3ceeffSMuchun Song 		mod_lruvec_kmem_state(stack, NR_KERNEL_STACK_KB,
566991e7673SShakeel Butt 				      account * (THREAD_SIZE / 1024));
567ba14a194SAndy Lutomirski 	}
56827faca83SMuchun Song }
569c6a7f572SKOSAKI Motohiro 
5701a03d3f1SSebastian Andrzej Siewior void exit_task_stack_account(struct task_struct *tsk)
5719b6f7e16SRoman Gushchin {
5721a03d3f1SSebastian Andrzej Siewior 	account_kernel_stack(tsk, -1);
5739b6f7e16SRoman Gushchin 
5741a03d3f1SSebastian Andrzej Siewior 	if (IS_ENABLED(CONFIG_VMAP_STACK)) {
5751a03d3f1SSebastian Andrzej Siewior 		struct vm_struct *vm;
5769b6f7e16SRoman Gushchin 		int i;
5779b6f7e16SRoman Gushchin 
5781a03d3f1SSebastian Andrzej Siewior 		vm = task_stack_vm_area(tsk);
5791a03d3f1SSebastian Andrzej Siewior 		for (i = 0; i < THREAD_SIZE / PAGE_SIZE; i++)
5801a03d3f1SSebastian Andrzej Siewior 			memcg_kmem_uncharge_page(vm->pages[i], 0);
5819b6f7e16SRoman Gushchin 	}
5829b6f7e16SRoman Gushchin }
5839b6f7e16SRoman Gushchin 
58468f24b08SAndy Lutomirski static void release_task_stack(struct task_struct *tsk)
5851da177e4SLinus Torvalds {
5862f064a59SPeter Zijlstra 	if (WARN_ON(READ_ONCE(tsk->__state) != TASK_DEAD))
587405c0759SAndy Lutomirski 		return;  /* Better to leak the stack than to free prematurely */
588405c0759SAndy Lutomirski 
589ba14a194SAndy Lutomirski 	free_thread_stack(tsk);
59068f24b08SAndy Lutomirski }
59168f24b08SAndy Lutomirski 
59268f24b08SAndy Lutomirski #ifdef CONFIG_THREAD_INFO_IN_TASK
59368f24b08SAndy Lutomirski void put_task_stack(struct task_struct *tsk)
59468f24b08SAndy Lutomirski {
595f0b89d39SElena Reshetova 	if (refcount_dec_and_test(&tsk->stack_refcount))
59668f24b08SAndy Lutomirski 		release_task_stack(tsk);
59768f24b08SAndy Lutomirski }
59868f24b08SAndy Lutomirski #endif
59968f24b08SAndy Lutomirski 
60068f24b08SAndy Lutomirski void free_task(struct task_struct *tsk)
60168f24b08SAndy Lutomirski {
602a1140cb2SKuniyuki Iwashima #ifdef CONFIG_SECCOMP
603a1140cb2SKuniyuki Iwashima 	WARN_ON_ONCE(tsk->seccomp.filter);
604a1140cb2SKuniyuki Iwashima #endif
605b90ca8baSWill Deacon 	release_user_cpus_ptr(tsk);
606d08b9f0cSSami Tolvanen 	scs_release(tsk);
607d08b9f0cSSami Tolvanen 
60868f24b08SAndy Lutomirski #ifndef CONFIG_THREAD_INFO_IN_TASK
60968f24b08SAndy Lutomirski 	/*
61068f24b08SAndy Lutomirski 	 * The task is finally done with both the stack and thread_info,
61168f24b08SAndy Lutomirski 	 * so free both.
61268f24b08SAndy Lutomirski 	 */
61368f24b08SAndy Lutomirski 	release_task_stack(tsk);
61468f24b08SAndy Lutomirski #else
61568f24b08SAndy Lutomirski 	/*
61668f24b08SAndy Lutomirski 	 * If the task had a separate stack allocation, it should be gone
61768f24b08SAndy Lutomirski 	 * by now.
61868f24b08SAndy Lutomirski 	 */
619f0b89d39SElena Reshetova 	WARN_ON_ONCE(refcount_read(&tsk->stack_refcount) != 0);
62068f24b08SAndy Lutomirski #endif
62123f78d4aSIngo Molnar 	rt_mutex_debug_task_free(tsk);
622fb52607aSFrederic Weisbecker 	ftrace_graph_exit_task(tsk);
623f19b9f74SAkinobu Mita 	arch_release_task_struct(tsk);
6241da5c46fSOleg Nesterov 	if (tsk->flags & PF_KTHREAD)
6251da5c46fSOleg Nesterov 		free_kthread_struct(tsk);
626b0fd1852SKP Singh 	bpf_task_storage_free(tsk);
6271da177e4SLinus Torvalds 	free_task_struct(tsk);
6281da177e4SLinus Torvalds }
6291da177e4SLinus Torvalds EXPORT_SYMBOL(free_task);
6301da177e4SLinus Torvalds 
631fe69d560SDavid Hildenbrand static void dup_mm_exe_file(struct mm_struct *mm, struct mm_struct *oldmm)
632fe69d560SDavid Hildenbrand {
633fe69d560SDavid Hildenbrand 	struct file *exe_file;
634fe69d560SDavid Hildenbrand 
635fe69d560SDavid Hildenbrand 	exe_file = get_mm_exe_file(oldmm);
636fe69d560SDavid Hildenbrand 	RCU_INIT_POINTER(mm->exe_file, exe_file);
637fe69d560SDavid Hildenbrand 	/*
638fe69d560SDavid Hildenbrand 	 * We depend on the oldmm having properly denied write access to the
639fe69d560SDavid Hildenbrand 	 * exe_file already.
640fe69d560SDavid Hildenbrand 	 */
641fe69d560SDavid Hildenbrand 	if (exe_file && deny_write_access(exe_file))
642fe69d560SDavid Hildenbrand 		pr_warn_once("deny_write_access() failed in %s\n", __func__);
643fe69d560SDavid Hildenbrand }
644fe69d560SDavid Hildenbrand 
6451da177e4SLinus Torvalds #ifdef CONFIG_MMU
6460766f788SEmese Revfy static __latent_entropy int dup_mmap(struct mm_struct *mm,
6470766f788SEmese Revfy 					struct mm_struct *oldmm)
6481da177e4SLinus Torvalds {
649763ecb03SLiam R. Howlett 	struct vm_area_struct *mpnt, *tmp;
6501da177e4SLinus Torvalds 	int retval;
651c9dbe82cSLiam R. Howlett 	unsigned long charge = 0;
652893e26e6SPavel Emelyanov 	LIST_HEAD(uf);
6533b9dbd5eSLiam R. Howlett 	VMA_ITERATOR(old_vmi, oldmm, 0);
6543b9dbd5eSLiam R. Howlett 	VMA_ITERATOR(vmi, mm, 0);
6551da177e4SLinus Torvalds 
65632cdba1eSOleg Nesterov 	uprobe_start_dup_mmap();
657d8ed45c5SMichel Lespinasse 	if (mmap_write_lock_killable(oldmm)) {
6587c051267SMichal Hocko 		retval = -EINTR;
6597c051267SMichal Hocko 		goto fail_uprobe_end;
6607c051267SMichal Hocko 	}
661ec8c0446SRalf Baechle 	flush_cache_dup_mm(oldmm);
662f8ac4ec9SOleg Nesterov 	uprobe_dup_mmap(oldmm, mm);
663ad339451SIngo Molnar 	/*
664ad339451SIngo Molnar 	 * Not linked in yet - no deadlock potential:
665ad339451SIngo Molnar 	 */
666aaa2cc56SMichel Lespinasse 	mmap_write_lock_nested(mm, SINGLE_DEPTH_NESTING);
6677ee78232SHugh Dickins 
66890f31d0eSKonstantin Khlebnikov 	/* No ordering required: file already has been exposed. */
669fe69d560SDavid Hildenbrand 	dup_mm_exe_file(mm, oldmm);
67090f31d0eSKonstantin Khlebnikov 
6714f7d4614SVladimir Davydov 	mm->total_vm = oldmm->total_vm;
67284638335SKonstantin Khlebnikov 	mm->data_vm = oldmm->data_vm;
6734f7d4614SVladimir Davydov 	mm->exec_vm = oldmm->exec_vm;
6744f7d4614SVladimir Davydov 	mm->stack_vm = oldmm->stack_vm;
6754f7d4614SVladimir Davydov 
676f8af4da3SHugh Dickins 	retval = ksm_fork(mm, oldmm);
677f8af4da3SHugh Dickins 	if (retval)
678f8af4da3SHugh Dickins 		goto out;
679d2081b2bSYang Shi 	khugepaged_fork(mm, oldmm);
6801da177e4SLinus Torvalds 
6813b9dbd5eSLiam R. Howlett 	retval = vma_iter_bulk_alloc(&vmi, oldmm->map_count);
682d4af56c5SLiam R. Howlett 	if (retval)
683d4af56c5SLiam R. Howlett 		goto out;
684d4af56c5SLiam R. Howlett 
6853dd44325SLiam R. Howlett 	mt_clear_in_rcu(vmi.mas.tree);
6863b9dbd5eSLiam R. Howlett 	for_each_vma(old_vmi, mpnt) {
6871da177e4SLinus Torvalds 		struct file *file;
6881da177e4SLinus Torvalds 
689fb49c455SSuren Baghdasaryan 		vma_start_write(mpnt);
6901da177e4SLinus Torvalds 		if (mpnt->vm_flags & VM_DONTCOPY) {
69184638335SKonstantin Khlebnikov 			vm_stat_account(mm, mpnt->vm_flags, -vma_pages(mpnt));
6921da177e4SLinus Torvalds 			continue;
6931da177e4SLinus Torvalds 		}
6941da177e4SLinus Torvalds 		charge = 0;
695655c79bbSTetsuo Handa 		/*
696655c79bbSTetsuo Handa 		 * Don't duplicate many vmas if we've been oom-killed (for
697655c79bbSTetsuo Handa 		 * example)
698655c79bbSTetsuo Handa 		 */
699655c79bbSTetsuo Handa 		if (fatal_signal_pending(current)) {
700655c79bbSTetsuo Handa 			retval = -EINTR;
701d4af56c5SLiam R. Howlett 			goto loop_out;
702655c79bbSTetsuo Handa 		}
7031da177e4SLinus Torvalds 		if (mpnt->vm_flags & VM_ACCOUNT) {
704b2412b7fSHuang Shijie 			unsigned long len = vma_pages(mpnt);
705b2412b7fSHuang Shijie 
706191c5424SAl Viro 			if (security_vm_enough_memory_mm(oldmm, len)) /* sic */
7071da177e4SLinus Torvalds 				goto fail_nomem;
7081da177e4SLinus Torvalds 			charge = len;
7091da177e4SLinus Torvalds 		}
7103928d4f5SLinus Torvalds 		tmp = vm_area_dup(mpnt);
7111da177e4SLinus Torvalds 		if (!tmp)
7121da177e4SLinus Torvalds 			goto fail_nomem;
713ef0855d3SOleg Nesterov 		retval = vma_dup_policy(mpnt, tmp);
714ef0855d3SOleg Nesterov 		if (retval)
7151da177e4SLinus Torvalds 			goto fail_nomem_policy;
716a247c3a9SAndrea Arcangeli 		tmp->vm_mm = mm;
717893e26e6SPavel Emelyanov 		retval = dup_userfaultfd(tmp, &uf);
718893e26e6SPavel Emelyanov 		if (retval)
719893e26e6SPavel Emelyanov 			goto fail_nomem_anon_vma_fork;
720d2cd9edeSRik van Riel 		if (tmp->vm_flags & VM_WIPEONFORK) {
72193949bb2SLi Xinhai 			/*
72293949bb2SLi Xinhai 			 * VM_WIPEONFORK gets a clean slate in the child.
72393949bb2SLi Xinhai 			 * Don't prepare anon_vma until fault since we don't
72493949bb2SLi Xinhai 			 * copy page for current vma.
72593949bb2SLi Xinhai 			 */
726d2cd9edeSRik van Riel 			tmp->anon_vma = NULL;
727d2cd9edeSRik van Riel 		} else if (anon_vma_fork(tmp, mpnt))
7285beb4930SRik van Riel 			goto fail_nomem_anon_vma_fork;
729e430a95aSSuren Baghdasaryan 		vm_flags_clear(tmp, VM_LOCKED_MASK);
7301da177e4SLinus Torvalds 		file = tmp->vm_file;
7311da177e4SLinus Torvalds 		if (file) {
732b88ed205SHugh Dickins 			struct address_space *mapping = file->f_mapping;
733b88ed205SHugh Dickins 
7341da177e4SLinus Torvalds 			get_file(file);
73583cde9e8SDavidlohr Bueso 			i_mmap_lock_write(mapping);
736b88ed205SHugh Dickins 			if (tmp->vm_flags & VM_SHARED)
737cf508b58SMiaohe Lin 				mapping_allow_writable(mapping);
738b88ed205SHugh Dickins 			flush_dcache_mmap_lock(mapping);
739b88ed205SHugh Dickins 			/* insert tmp into the share list, just after mpnt */
7409826a516SMichel Lespinasse 			vma_interval_tree_insert_after(tmp, mpnt,
7419826a516SMichel Lespinasse 					&mapping->i_mmap);
742b88ed205SHugh Dickins 			flush_dcache_mmap_unlock(mapping);
74383cde9e8SDavidlohr Bueso 			i_mmap_unlock_write(mapping);
7441da177e4SLinus Torvalds 		}
7451da177e4SLinus Torvalds 
7461da177e4SLinus Torvalds 		/*
7478d9bfb26SMike Kravetz 		 * Copy/update hugetlb private vma information.
748a1e78772SMel Gorman 		 */
749a1e78772SMel Gorman 		if (is_vm_hugetlb_page(tmp))
7508d9bfb26SMike Kravetz 			hugetlb_dup_vma_private(tmp);
751a1e78772SMel Gorman 
752d4af56c5SLiam R. Howlett 		/* Link the vma into the MT */
7533b9dbd5eSLiam R. Howlett 		if (vma_iter_bulk_store(&vmi, tmp))
7543b9dbd5eSLiam R. Howlett 			goto fail_nomem_vmi_store;
7551da177e4SLinus Torvalds 
7561da177e4SLinus Torvalds 		mm->map_count++;
757d2cd9edeSRik van Riel 		if (!(tmp->vm_flags & VM_WIPEONFORK))
758c78f4636SPeter Xu 			retval = copy_page_range(tmp, mpnt);
7591da177e4SLinus Torvalds 
7601da177e4SLinus Torvalds 		if (tmp->vm_ops && tmp->vm_ops->open)
7611da177e4SLinus Torvalds 			tmp->vm_ops->open(tmp);
7621da177e4SLinus Torvalds 
7631da177e4SLinus Torvalds 		if (retval)
764d4af56c5SLiam R. Howlett 			goto loop_out;
7651da177e4SLinus Torvalds 	}
766d6dd61c8SJeremy Fitzhardinge 	/* a new mm has just been created */
7671ed0cc5aSNadav Amit 	retval = arch_dup_mmap(oldmm, mm);
768d4af56c5SLiam R. Howlett loop_out:
7693b9dbd5eSLiam R. Howlett 	vma_iter_free(&vmi);
7703dd44325SLiam R. Howlett 	if (!retval)
7713dd44325SLiam R. Howlett 		mt_set_in_rcu(vmi.mas.tree);
7721da177e4SLinus Torvalds out:
773d8ed45c5SMichel Lespinasse 	mmap_write_unlock(mm);
774fd3e42fcSHugh Dickins 	flush_tlb_mm(oldmm);
775d8ed45c5SMichel Lespinasse 	mmap_write_unlock(oldmm);
776893e26e6SPavel Emelyanov 	dup_userfaultfd_complete(&uf);
7777c051267SMichal Hocko fail_uprobe_end:
77832cdba1eSOleg Nesterov 	uprobe_end_dup_mmap();
7791da177e4SLinus Torvalds 	return retval;
780c9dbe82cSLiam R. Howlett 
7813b9dbd5eSLiam R. Howlett fail_nomem_vmi_store:
782c9dbe82cSLiam R. Howlett 	unlink_anon_vmas(tmp);
7835beb4930SRik van Riel fail_nomem_anon_vma_fork:
784ef0855d3SOleg Nesterov 	mpol_put(vma_policy(tmp));
7851da177e4SLinus Torvalds fail_nomem_policy:
7863928d4f5SLinus Torvalds 	vm_area_free(tmp);
7871da177e4SLinus Torvalds fail_nomem:
7881da177e4SLinus Torvalds 	retval = -ENOMEM;
7891da177e4SLinus Torvalds 	vm_unacct_memory(charge);
790d4af56c5SLiam R. Howlett 	goto loop_out;
7911da177e4SLinus Torvalds }
7921da177e4SLinus Torvalds 
7931da177e4SLinus Torvalds static inline int mm_alloc_pgd(struct mm_struct *mm)
7941da177e4SLinus Torvalds {
7951da177e4SLinus Torvalds 	mm->pgd = pgd_alloc(mm);
7961da177e4SLinus Torvalds 	if (unlikely(!mm->pgd))
7971da177e4SLinus Torvalds 		return -ENOMEM;
7981da177e4SLinus Torvalds 	return 0;
7991da177e4SLinus Torvalds }
8001da177e4SLinus Torvalds 
8011da177e4SLinus Torvalds static inline void mm_free_pgd(struct mm_struct *mm)
8021da177e4SLinus Torvalds {
8035e541973SBenjamin Herrenschmidt 	pgd_free(mm, mm->pgd);
8041da177e4SLinus Torvalds }
8051da177e4SLinus Torvalds #else
80690f31d0eSKonstantin Khlebnikov static int dup_mmap(struct mm_struct *mm, struct mm_struct *oldmm)
80790f31d0eSKonstantin Khlebnikov {
808d8ed45c5SMichel Lespinasse 	mmap_write_lock(oldmm);
809fe69d560SDavid Hildenbrand 	dup_mm_exe_file(mm, oldmm);
810d8ed45c5SMichel Lespinasse 	mmap_write_unlock(oldmm);
81190f31d0eSKonstantin Khlebnikov 	return 0;
81290f31d0eSKonstantin Khlebnikov }
8131da177e4SLinus Torvalds #define mm_alloc_pgd(mm)	(0)
8141da177e4SLinus Torvalds #define mm_free_pgd(mm)
8151da177e4SLinus Torvalds #endif /* CONFIG_MMU */
8161da177e4SLinus Torvalds 
817d70f2a14SAndrew Morton static void check_mm(struct mm_struct *mm)
818d70f2a14SAndrew Morton {
819d70f2a14SAndrew Morton 	int i;
820d70f2a14SAndrew Morton 
8218495f7e6SSai Praneeth Prakhya 	BUILD_BUG_ON_MSG(ARRAY_SIZE(resident_page_types) != NR_MM_COUNTERS,
8228495f7e6SSai Praneeth Prakhya 			 "Please make sure 'struct resident_page_types[]' is updated as well");
8238495f7e6SSai Praneeth Prakhya 
824d70f2a14SAndrew Morton 	for (i = 0; i < NR_MM_COUNTERS; i++) {
825f1a79412SShakeel Butt 		long x = percpu_counter_sum(&mm->rss_stat[i]);
826d70f2a14SAndrew Morton 
827d70f2a14SAndrew Morton 		if (unlikely(x))
8288495f7e6SSai Praneeth Prakhya 			pr_alert("BUG: Bad rss-counter state mm:%p type:%s val:%ld\n",
8298495f7e6SSai Praneeth Prakhya 				 mm, resident_page_types[i], x);
830d70f2a14SAndrew Morton 	}
831d70f2a14SAndrew Morton 
832d70f2a14SAndrew Morton 	if (mm_pgtables_bytes(mm))
833d70f2a14SAndrew Morton 		pr_alert("BUG: non-zero pgtables_bytes on freeing mm: %ld\n",
834d70f2a14SAndrew Morton 				mm_pgtables_bytes(mm));
835d70f2a14SAndrew Morton 
836d70f2a14SAndrew Morton #if defined(CONFIG_TRANSPARENT_HUGEPAGE) && !USE_SPLIT_PMD_PTLOCKS
837d70f2a14SAndrew Morton 	VM_BUG_ON_MM(mm->pmd_huge_pte, mm);
838d70f2a14SAndrew Morton #endif
839d70f2a14SAndrew Morton }
8401da177e4SLinus Torvalds 
841e94b1766SChristoph Lameter #define allocate_mm()	(kmem_cache_alloc(mm_cachep, GFP_KERNEL))
8421da177e4SLinus Torvalds #define free_mm(mm)	(kmem_cache_free(mm_cachep, (mm)))
8431da177e4SLinus Torvalds 
8442655421aSNicholas Piggin static void do_check_lazy_tlb(void *arg)
8452655421aSNicholas Piggin {
8462655421aSNicholas Piggin 	struct mm_struct *mm = arg;
8472655421aSNicholas Piggin 
8482655421aSNicholas Piggin 	WARN_ON_ONCE(current->active_mm == mm);
8492655421aSNicholas Piggin }
8502655421aSNicholas Piggin 
8512655421aSNicholas Piggin static void do_shoot_lazy_tlb(void *arg)
8522655421aSNicholas Piggin {
8532655421aSNicholas Piggin 	struct mm_struct *mm = arg;
8542655421aSNicholas Piggin 
8552655421aSNicholas Piggin 	if (current->active_mm == mm) {
8562655421aSNicholas Piggin 		WARN_ON_ONCE(current->mm);
8572655421aSNicholas Piggin 		current->active_mm = &init_mm;
8582655421aSNicholas Piggin 		switch_mm(mm, &init_mm, current);
8592655421aSNicholas Piggin 	}
8602655421aSNicholas Piggin }
8612655421aSNicholas Piggin 
8622655421aSNicholas Piggin static void cleanup_lazy_tlbs(struct mm_struct *mm)
8632655421aSNicholas Piggin {
8642655421aSNicholas Piggin 	if (!IS_ENABLED(CONFIG_MMU_LAZY_TLB_SHOOTDOWN)) {
8652655421aSNicholas Piggin 		/*
8662655421aSNicholas Piggin 		 * In this case, lazy tlb mms are refounted and would not reach
8672655421aSNicholas Piggin 		 * __mmdrop until all CPUs have switched away and mmdrop()ed.
8682655421aSNicholas Piggin 		 */
8692655421aSNicholas Piggin 		return;
8702655421aSNicholas Piggin 	}
8712655421aSNicholas Piggin 
8722655421aSNicholas Piggin 	/*
8732655421aSNicholas Piggin 	 * Lazy mm shootdown does not refcount "lazy tlb mm" usage, rather it
8742655421aSNicholas Piggin 	 * requires lazy mm users to switch to another mm when the refcount
8752655421aSNicholas Piggin 	 * drops to zero, before the mm is freed. This requires IPIs here to
8762655421aSNicholas Piggin 	 * switch kernel threads to init_mm.
8772655421aSNicholas Piggin 	 *
8782655421aSNicholas Piggin 	 * archs that use IPIs to flush TLBs can piggy-back that lazy tlb mm
8792655421aSNicholas Piggin 	 * switch with the final userspace teardown TLB flush which leaves the
8802655421aSNicholas Piggin 	 * mm lazy on this CPU but no others, reducing the need for additional
8812655421aSNicholas Piggin 	 * IPIs here. There are cases where a final IPI is still required here,
8822655421aSNicholas Piggin 	 * such as the final mmdrop being performed on a different CPU than the
8832655421aSNicholas Piggin 	 * one exiting, or kernel threads using the mm when userspace exits.
8842655421aSNicholas Piggin 	 *
8852655421aSNicholas Piggin 	 * IPI overheads have not found to be expensive, but they could be
8862655421aSNicholas Piggin 	 * reduced in a number of possible ways, for example (roughly
8872655421aSNicholas Piggin 	 * increasing order of complexity):
8882655421aSNicholas Piggin 	 * - The last lazy reference created by exit_mm() could instead switch
8892655421aSNicholas Piggin 	 *   to init_mm, however it's probable this will run on the same CPU
8902655421aSNicholas Piggin 	 *   immediately afterwards, so this may not reduce IPIs much.
8912655421aSNicholas Piggin 	 * - A batch of mms requiring IPIs could be gathered and freed at once.
8922655421aSNicholas Piggin 	 * - CPUs store active_mm where it can be remotely checked without a
8932655421aSNicholas Piggin 	 *   lock, to filter out false-positives in the cpumask.
8942655421aSNicholas Piggin 	 * - After mm_users or mm_count reaches zero, switching away from the
8952655421aSNicholas Piggin 	 *   mm could clear mm_cpumask to reduce some IPIs, perhaps together
8962655421aSNicholas Piggin 	 *   with some batching or delaying of the final IPIs.
8972655421aSNicholas Piggin 	 * - A delayed freeing and RCU-like quiescing sequence based on mm
8982655421aSNicholas Piggin 	 *   switching to avoid IPIs completely.
8992655421aSNicholas Piggin 	 */
9002655421aSNicholas Piggin 	on_each_cpu_mask(mm_cpumask(mm), do_shoot_lazy_tlb, (void *)mm, 1);
9012655421aSNicholas Piggin 	if (IS_ENABLED(CONFIG_DEBUG_VM_SHOOT_LAZIES))
9022655421aSNicholas Piggin 		on_each_cpu(do_check_lazy_tlb, (void *)mm, 1);
9032655421aSNicholas Piggin }
9042655421aSNicholas Piggin 
905d70f2a14SAndrew Morton /*
906d70f2a14SAndrew Morton  * Called when the last reference to the mm
907d70f2a14SAndrew Morton  * is dropped: either by a lazy thread or by
908d70f2a14SAndrew Morton  * mmput. Free the page directory and the mm.
909d70f2a14SAndrew Morton  */
910d34bc48fSAndrew Morton void __mmdrop(struct mm_struct *mm)
911d70f2a14SAndrew Morton {
912d70f2a14SAndrew Morton 	BUG_ON(mm == &init_mm);
9133eda69c9SMark Rutland 	WARN_ON_ONCE(mm == current->mm);
9142655421aSNicholas Piggin 
9152655421aSNicholas Piggin 	/* Ensure no CPUs are using this as their lazy tlb mm */
9162655421aSNicholas Piggin 	cleanup_lazy_tlbs(mm);
9172655421aSNicholas Piggin 
9183eda69c9SMark Rutland 	WARN_ON_ONCE(mm == current->active_mm);
919d70f2a14SAndrew Morton 	mm_free_pgd(mm);
920d70f2a14SAndrew Morton 	destroy_context(mm);
921984cfe4eSJason Gunthorpe 	mmu_notifier_subscriptions_destroy(mm);
922d70f2a14SAndrew Morton 	check_mm(mm);
923d70f2a14SAndrew Morton 	put_user_ns(mm->user_ns);
9242667ed10SFenghua Yu 	mm_pasid_drop(mm);
925223baf9dSMathieu Desnoyers 	mm_destroy_cid(mm);
926*14ef95beSMateusz Guzik 	percpu_counter_destroy_many(mm->rss_stat, NR_MM_COUNTERS);
927f1a79412SShakeel Butt 
928d70f2a14SAndrew Morton 	free_mm(mm);
929d70f2a14SAndrew Morton }
930d34bc48fSAndrew Morton EXPORT_SYMBOL_GPL(__mmdrop);
931d70f2a14SAndrew Morton 
932d70f2a14SAndrew Morton static void mmdrop_async_fn(struct work_struct *work)
933d70f2a14SAndrew Morton {
934d70f2a14SAndrew Morton 	struct mm_struct *mm;
935d70f2a14SAndrew Morton 
936d70f2a14SAndrew Morton 	mm = container_of(work, struct mm_struct, async_put_work);
937d70f2a14SAndrew Morton 	__mmdrop(mm);
938d70f2a14SAndrew Morton }
939d70f2a14SAndrew Morton 
940d70f2a14SAndrew Morton static void mmdrop_async(struct mm_struct *mm)
941d70f2a14SAndrew Morton {
942d70f2a14SAndrew Morton 	if (unlikely(atomic_dec_and_test(&mm->mm_count))) {
943d70f2a14SAndrew Morton 		INIT_WORK(&mm->async_put_work, mmdrop_async_fn);
944d70f2a14SAndrew Morton 		schedule_work(&mm->async_put_work);
945d70f2a14SAndrew Morton 	}
946d70f2a14SAndrew Morton }
947d70f2a14SAndrew Morton 
9481da177e4SLinus Torvalds static inline void free_signal_struct(struct signal_struct *sig)
9491da177e4SLinus Torvalds {
9501da177e4SLinus Torvalds 	taskstats_tgid_free(sig);
9511da177e4SLinus Torvalds 	sched_autogroup_exit(sig);
9521da177e4SLinus Torvalds 	/*
9531da177e4SLinus Torvalds 	 * __mmdrop is not safe to call from softirq context on x86 due to
9541da177e4SLinus Torvalds 	 * pgd_dtor so postpone it to the async context
9551da177e4SLinus Torvalds 	 */
9561da177e4SLinus Torvalds 	if (sig->oom_mm)
9571da177e4SLinus Torvalds 		mmdrop_async(sig->oom_mm);
9581da177e4SLinus Torvalds 	kmem_cache_free(signal_cachep, sig);
9591da177e4SLinus Torvalds }
9601da177e4SLinus Torvalds 
9611da177e4SLinus Torvalds static inline void put_signal_struct(struct signal_struct *sig)
9621da177e4SLinus Torvalds {
96360d4de3fSElena Reshetova 	if (refcount_dec_and_test(&sig->sigcnt))
9641da177e4SLinus Torvalds 		free_signal_struct(sig);
9651da177e4SLinus Torvalds }
9661da177e4SLinus Torvalds 
9671da177e4SLinus Torvalds void __put_task_struct(struct task_struct *tsk)
9681da177e4SLinus Torvalds {
9691da177e4SLinus Torvalds 	WARN_ON(!tsk->exit_state);
970ec1d2819SElena Reshetova 	WARN_ON(refcount_read(&tsk->usage));
9711da177e4SLinus Torvalds 	WARN_ON(tsk == current);
9721da177e4SLinus Torvalds 
9730f212204SJens Axboe 	io_uring_free(tsk);
9741da177e4SLinus Torvalds 	cgroup_free(tsk);
97516d51a59SJann Horn 	task_numa_free(tsk, true);
9761da177e4SLinus Torvalds 	security_task_free(tsk);
9771da177e4SLinus Torvalds 	exit_creds(tsk);
9781da177e4SLinus Torvalds 	delayacct_tsk_free(tsk);
9791da177e4SLinus Torvalds 	put_signal_struct(tsk->signal);
9806e33cad0SPeter Zijlstra 	sched_core_free(tsk);
9811da177e4SLinus Torvalds 	free_task(tsk);
9821da177e4SLinus Torvalds }
9831da177e4SLinus Torvalds EXPORT_SYMBOL_GPL(__put_task_struct);
9841da177e4SLinus Torvalds 
9851da177e4SLinus Torvalds void __init __weak arch_task_cache_init(void) { }
9861da177e4SLinus Torvalds 
9871da177e4SLinus Torvalds /*
9881da177e4SLinus Torvalds  * set_max_threads
9891da177e4SLinus Torvalds  */
9901da177e4SLinus Torvalds static void set_max_threads(unsigned int max_threads_suggested)
9911da177e4SLinus Torvalds {
9921da177e4SLinus Torvalds 	u64 threads;
993ca79b0c2SArun KS 	unsigned long nr_pages = totalram_pages();
9941da177e4SLinus Torvalds 
9951da177e4SLinus Torvalds 	/*
9961da177e4SLinus Torvalds 	 * The number of threads shall be limited such that the thread
9971da177e4SLinus Torvalds 	 * structures may only consume a small part of the available memory.
9981da177e4SLinus Torvalds 	 */
9993d6357deSArun KS 	if (fls64(nr_pages) + fls64(PAGE_SIZE) > 64)
10001da177e4SLinus Torvalds 		threads = MAX_THREADS;
10011da177e4SLinus Torvalds 	else
10023d6357deSArun KS 		threads = div64_u64((u64) nr_pages * (u64) PAGE_SIZE,
10031da177e4SLinus Torvalds 				    (u64) THREAD_SIZE * 8UL);
10041da177e4SLinus Torvalds 
10051da177e4SLinus Torvalds 	if (threads > max_threads_suggested)
10061da177e4SLinus Torvalds 		threads = max_threads_suggested;
10071da177e4SLinus Torvalds 
10081da177e4SLinus Torvalds 	max_threads = clamp_t(u64, threads, MIN_THREADS, MAX_THREADS);
10091da177e4SLinus Torvalds }
10101da177e4SLinus Torvalds 
10111da177e4SLinus Torvalds #ifdef CONFIG_ARCH_WANTS_DYNAMIC_TASK_STRUCT
10121da177e4SLinus Torvalds /* Initialized by the architecture: */
10131da177e4SLinus Torvalds int arch_task_struct_size __read_mostly;
10141da177e4SLinus Torvalds #endif
10151da177e4SLinus Torvalds 
10164189ff23SChristoph Hellwig #ifndef CONFIG_ARCH_TASK_STRUCT_ALLOCATOR
10175905429aSKees Cook static void task_struct_whitelist(unsigned long *offset, unsigned long *size)
10185905429aSKees Cook {
10195905429aSKees Cook 	/* Fetch thread_struct whitelist for the architecture. */
10205905429aSKees Cook 	arch_thread_struct_whitelist(offset, size);
10215905429aSKees Cook 
10225905429aSKees Cook 	/*
10235905429aSKees Cook 	 * Handle zero-sized whitelist or empty thread_struct, otherwise
10245905429aSKees Cook 	 * adjust offset to position of thread_struct in task_struct.
10255905429aSKees Cook 	 */
10265905429aSKees Cook 	if (unlikely(*size == 0))
10275905429aSKees Cook 		*offset = 0;
10285905429aSKees Cook 	else
10295905429aSKees Cook 		*offset += offsetof(struct task_struct, thread);
10305905429aSKees Cook }
10314189ff23SChristoph Hellwig #endif /* CONFIG_ARCH_TASK_STRUCT_ALLOCATOR */
10325905429aSKees Cook 
10331da177e4SLinus Torvalds void __init fork_init(void)
10341da177e4SLinus Torvalds {
10351da177e4SLinus Torvalds 	int i;
10361da177e4SLinus Torvalds #ifndef CONFIG_ARCH_TASK_STRUCT_ALLOCATOR
10371da177e4SLinus Torvalds #ifndef ARCH_MIN_TASKALIGN
10381da177e4SLinus Torvalds #define ARCH_MIN_TASKALIGN	0
10391da177e4SLinus Torvalds #endif
10401da177e4SLinus Torvalds 	int align = max_t(int, L1_CACHE_BYTES, ARCH_MIN_TASKALIGN);
10415905429aSKees Cook 	unsigned long useroffset, usersize;
10421da177e4SLinus Torvalds 
10431da177e4SLinus Torvalds 	/* create a slab on which task_structs can be allocated */
10445905429aSKees Cook 	task_struct_whitelist(&useroffset, &usersize);
10455905429aSKees Cook 	task_struct_cachep = kmem_cache_create_usercopy("task_struct",
10461da177e4SLinus Torvalds 			arch_task_struct_size, align,
10475905429aSKees Cook 			SLAB_PANIC|SLAB_ACCOUNT,
10485905429aSKees Cook 			useroffset, usersize, NULL);
10491da177e4SLinus Torvalds #endif
10501da177e4SLinus Torvalds 
10511da177e4SLinus Torvalds 	/* do the arch specific task caches init */
10521da177e4SLinus Torvalds 	arch_task_cache_init();
10531da177e4SLinus Torvalds 
10541da177e4SLinus Torvalds 	set_max_threads(MAX_THREADS);
10551da177e4SLinus Torvalds 
10561da177e4SLinus Torvalds 	init_task.signal->rlim[RLIMIT_NPROC].rlim_cur = max_threads/2;
10571da177e4SLinus Torvalds 	init_task.signal->rlim[RLIMIT_NPROC].rlim_max = max_threads/2;
10581da177e4SLinus Torvalds 	init_task.signal->rlim[RLIMIT_SIGPENDING] =
10591da177e4SLinus Torvalds 		init_task.signal->rlim[RLIMIT_NPROC];
10601da177e4SLinus Torvalds 
1061de399236SAlexey Gladkov 	for (i = 0; i < UCOUNT_COUNTS; i++)
10621da177e4SLinus Torvalds 		init_user_ns.ucount_max[i] = max_threads/2;
10631da177e4SLinus Torvalds 
1064de399236SAlexey Gladkov 	set_userns_rlimit_max(&init_user_ns, UCOUNT_RLIMIT_NPROC,      RLIM_INFINITY);
1065de399236SAlexey Gladkov 	set_userns_rlimit_max(&init_user_ns, UCOUNT_RLIMIT_MSGQUEUE,   RLIM_INFINITY);
1066de399236SAlexey Gladkov 	set_userns_rlimit_max(&init_user_ns, UCOUNT_RLIMIT_SIGPENDING, RLIM_INFINITY);
1067de399236SAlexey Gladkov 	set_userns_rlimit_max(&init_user_ns, UCOUNT_RLIMIT_MEMLOCK,    RLIM_INFINITY);
106821d1c5e3SAlexey Gladkov 
10691da177e4SLinus Torvalds #ifdef CONFIG_VMAP_STACK
10701da177e4SLinus Torvalds 	cpuhp_setup_state(CPUHP_BP_PREPARE_DYN, "fork:vm_stack_cache",
10711da177e4SLinus Torvalds 			  NULL, free_vm_stack_cache);
10721da177e4SLinus Torvalds #endif
10731da177e4SLinus Torvalds 
1074d08b9f0cSSami Tolvanen 	scs_init();
1075d08b9f0cSSami Tolvanen 
10761da177e4SLinus Torvalds 	lockdep_init_task(&init_task);
1077aad42dd4SNadav Amit 	uprobes_init();
10781da177e4SLinus Torvalds }
10791da177e4SLinus Torvalds 
10801da177e4SLinus Torvalds int __weak arch_dup_task_struct(struct task_struct *dst,
10811da177e4SLinus Torvalds 					       struct task_struct *src)
10821da177e4SLinus Torvalds {
10831da177e4SLinus Torvalds 	*dst = *src;
10841da177e4SLinus Torvalds 	return 0;
10851da177e4SLinus Torvalds }
10861da177e4SLinus Torvalds 
10871da177e4SLinus Torvalds void set_task_stack_end_magic(struct task_struct *tsk)
10881da177e4SLinus Torvalds {
10891da177e4SLinus Torvalds 	unsigned long *stackend;
10901da177e4SLinus Torvalds 
10911da177e4SLinus Torvalds 	stackend = end_of_stack(tsk);
10921da177e4SLinus Torvalds 	*stackend = STACK_END_MAGIC;	/* for overflow detection */
10931da177e4SLinus Torvalds }
10941da177e4SLinus Torvalds 
10951da177e4SLinus Torvalds static struct task_struct *dup_task_struct(struct task_struct *orig, int node)
10961da177e4SLinus Torvalds {
10971da177e4SLinus Torvalds 	struct task_struct *tsk;
10981da177e4SLinus Torvalds 	int err;
10991da177e4SLinus Torvalds 
11001da177e4SLinus Torvalds 	if (node == NUMA_NO_NODE)
11011da177e4SLinus Torvalds 		node = tsk_fork_get_node(orig);
11021da177e4SLinus Torvalds 	tsk = alloc_task_struct_node(node);
11031da177e4SLinus Torvalds 	if (!tsk)
11041da177e4SLinus Torvalds 		return NULL;
11051da177e4SLinus Torvalds 
1106546c42b2SSebastian Andrzej Siewior 	err = arch_dup_task_struct(tsk, orig);
1107546c42b2SSebastian Andrzej Siewior 	if (err)
11081da177e4SLinus Torvalds 		goto free_tsk;
11091da177e4SLinus Torvalds 
11107865aba3SSebastian Andrzej Siewior 	err = alloc_thread_stack_node(tsk, node);
11117865aba3SSebastian Andrzej Siewior 	if (err)
11121da177e4SLinus Torvalds 		goto free_tsk;
11139b6f7e16SRoman Gushchin 
11141da177e4SLinus Torvalds #ifdef CONFIG_THREAD_INFO_IN_TASK
1115f0b89d39SElena Reshetova 	refcount_set(&tsk->stack_refcount, 1);
11161da177e4SLinus Torvalds #endif
11171a03d3f1SSebastian Andrzej Siewior 	account_kernel_stack(tsk, 1);
11181da177e4SLinus Torvalds 
1119d08b9f0cSSami Tolvanen 	err = scs_prepare(tsk, node);
1120d08b9f0cSSami Tolvanen 	if (err)
1121d08b9f0cSSami Tolvanen 		goto free_stack;
1122d08b9f0cSSami Tolvanen 
11231da177e4SLinus Torvalds #ifdef CONFIG_SECCOMP
11241da177e4SLinus Torvalds 	/*
11251da177e4SLinus Torvalds 	 * We must handle setting up seccomp filters once we're under
11261da177e4SLinus Torvalds 	 * the sighand lock in case orig has changed between now and
11271da177e4SLinus Torvalds 	 * then. Until then, filter must be NULL to avoid messing up
11281da177e4SLinus Torvalds 	 * the usage counts on the error path calling free_task.
11291da177e4SLinus Torvalds 	 */
11301da177e4SLinus Torvalds 	tsk->seccomp.filter = NULL;
11311da177e4SLinus Torvalds #endif
11321da177e4SLinus Torvalds 
11331da177e4SLinus Torvalds 	setup_thread_stack(tsk, orig);
11341da177e4SLinus Torvalds 	clear_user_return_notifier(tsk);
11351da177e4SLinus Torvalds 	clear_tsk_need_resched(tsk);
11361da177e4SLinus Torvalds 	set_task_stack_end_magic(tsk);
11371446e1dfSGabriel Krisman Bertazi 	clear_syscall_work_syscall_user_dispatch(tsk);
11381da177e4SLinus Torvalds 
1139050e9baaSLinus Torvalds #ifdef CONFIG_STACKPROTECTOR
11401da177e4SLinus Torvalds 	tsk->stack_canary = get_random_canary();
11411da177e4SLinus Torvalds #endif
11423bd37062SSebastian Andrzej Siewior 	if (orig->cpus_ptr == &orig->cpus_mask)
11433bd37062SSebastian Andrzej Siewior 		tsk->cpus_ptr = &tsk->cpus_mask;
1144b90ca8baSWill Deacon 	dup_user_cpus_ptr(tsk, orig, node);
11451da177e4SLinus Torvalds 
11461da177e4SLinus Torvalds 	/*
11470ff7b2cfSEric W. Biederman 	 * One for the user space visible state that goes away when reaped.
11480ff7b2cfSEric W. Biederman 	 * One for the scheduler.
11491da177e4SLinus Torvalds 	 */
11500ff7b2cfSEric W. Biederman 	refcount_set(&tsk->rcu_users, 2);
11510ff7b2cfSEric W. Biederman 	/* One for the rcu users */
11520ff7b2cfSEric W. Biederman 	refcount_set(&tsk->usage, 1);
11531da177e4SLinus Torvalds #ifdef CONFIG_BLK_DEV_IO_TRACE
11541da177e4SLinus Torvalds 	tsk->btrace_seq = 0;
11551da177e4SLinus Torvalds #endif
11561da177e4SLinus Torvalds 	tsk->splice_pipe = NULL;
11571da177e4SLinus Torvalds 	tsk->task_frag.page = NULL;
11581da177e4SLinus Torvalds 	tsk->wake_q.next = NULL;
1159e32cf5dfSEric W. Biederman 	tsk->worker_private = NULL;
11601da177e4SLinus Torvalds 
11611da177e4SLinus Torvalds 	kcov_task_init(tsk);
116250b5e49cSAlexander Potapenko 	kmsan_task_create(tsk);
11635fbda3ecSThomas Gleixner 	kmap_local_fork(tsk);
11641da177e4SLinus Torvalds 
11651da177e4SLinus Torvalds #ifdef CONFIG_FAULT_INJECTION
11661da177e4SLinus Torvalds 	tsk->fail_nth = 0;
11671da177e4SLinus Torvalds #endif
11681da177e4SLinus Torvalds 
11692c323017SJosef Bacik #ifdef CONFIG_BLK_CGROUP
1170f05837edSChristoph Hellwig 	tsk->throttle_disk = NULL;
11712c323017SJosef Bacik 	tsk->use_memdelay = 0;
11722c323017SJosef Bacik #endif
11732c323017SJosef Bacik 
1174a3d29e82SPeter Zijlstra #ifdef CONFIG_IOMMU_SVA
1175a3d29e82SPeter Zijlstra 	tsk->pasid_activated = 0;
1176a3d29e82SPeter Zijlstra #endif
1177a3d29e82SPeter Zijlstra 
1178d46eb14bSShakeel Butt #ifdef CONFIG_MEMCG
1179d46eb14bSShakeel Butt 	tsk->active_memcg = NULL;
1180d46eb14bSShakeel Butt #endif
1181b041b525STony Luck 
1182b041b525STony Luck #ifdef CONFIG_CPU_SUP_INTEL
1183b041b525STony Luck 	tsk->reported_split_lock = 0;
1184b041b525STony Luck #endif
1185b041b525STony Luck 
1186af7f588dSMathieu Desnoyers #ifdef CONFIG_SCHED_MM_CID
1187af7f588dSMathieu Desnoyers 	tsk->mm_cid = -1;
1188223baf9dSMathieu Desnoyers 	tsk->last_mm_cid = -1;
1189af7f588dSMathieu Desnoyers 	tsk->mm_cid_active = 0;
1190223baf9dSMathieu Desnoyers 	tsk->migrate_from_cpu = -1;
1191af7f588dSMathieu Desnoyers #endif
11921da177e4SLinus Torvalds 	return tsk;
11931da177e4SLinus Torvalds 
11941da177e4SLinus Torvalds free_stack:
11951a03d3f1SSebastian Andrzej Siewior 	exit_task_stack_account(tsk);
11961da177e4SLinus Torvalds 	free_thread_stack(tsk);
11971da177e4SLinus Torvalds free_tsk:
11981da177e4SLinus Torvalds 	free_task_struct(tsk);
11991da177e4SLinus Torvalds 	return NULL;
12001da177e4SLinus Torvalds }
12011da177e4SLinus Torvalds 
12021da177e4SLinus Torvalds __cacheline_aligned_in_smp DEFINE_SPINLOCK(mmlist_lock);
12031da177e4SLinus Torvalds 
12044cb0e11bSHidehiro Kawai static unsigned long default_dump_filter = MMF_DUMP_FILTER_DEFAULT;
12054cb0e11bSHidehiro Kawai 
12064cb0e11bSHidehiro Kawai static int __init coredump_filter_setup(char *s)
12074cb0e11bSHidehiro Kawai {
12084cb0e11bSHidehiro Kawai 	default_dump_filter =
12094cb0e11bSHidehiro Kawai 		(simple_strtoul(s, NULL, 0) << MMF_DUMP_FILTER_SHIFT) &
12104cb0e11bSHidehiro Kawai 		MMF_DUMP_FILTER_MASK;
12114cb0e11bSHidehiro Kawai 	return 1;
12124cb0e11bSHidehiro Kawai }
12134cb0e11bSHidehiro Kawai 
12144cb0e11bSHidehiro Kawai __setup("coredump_filter=", coredump_filter_setup);
12154cb0e11bSHidehiro Kawai 
12161da177e4SLinus Torvalds #include <linux/init_task.h>
12171da177e4SLinus Torvalds 
1218858f0993SAlexey Dobriyan static void mm_init_aio(struct mm_struct *mm)
1219858f0993SAlexey Dobriyan {
1220858f0993SAlexey Dobriyan #ifdef CONFIG_AIO
1221858f0993SAlexey Dobriyan 	spin_lock_init(&mm->ioctx_lock);
1222db446a08SBenjamin LaHaise 	mm->ioctx_table = NULL;
1223858f0993SAlexey Dobriyan #endif
1224858f0993SAlexey Dobriyan }
1225858f0993SAlexey Dobriyan 
1226c3f3ce04SAndrea Arcangeli static __always_inline void mm_clear_owner(struct mm_struct *mm,
1227c3f3ce04SAndrea Arcangeli 					   struct task_struct *p)
1228c3f3ce04SAndrea Arcangeli {
1229c3f3ce04SAndrea Arcangeli #ifdef CONFIG_MEMCG
1230c3f3ce04SAndrea Arcangeli 	if (mm->owner == p)
1231c3f3ce04SAndrea Arcangeli 		WRITE_ONCE(mm->owner, NULL);
1232c3f3ce04SAndrea Arcangeli #endif
1233c3f3ce04SAndrea Arcangeli }
1234c3f3ce04SAndrea Arcangeli 
123533144e84SVladimir Davydov static void mm_init_owner(struct mm_struct *mm, struct task_struct *p)
123633144e84SVladimir Davydov {
123733144e84SVladimir Davydov #ifdef CONFIG_MEMCG
123833144e84SVladimir Davydov 	mm->owner = p;
123933144e84SVladimir Davydov #endif
124033144e84SVladimir Davydov }
124133144e84SVladimir Davydov 
1242355627f5SEric Biggers static void mm_init_uprobes_state(struct mm_struct *mm)
1243355627f5SEric Biggers {
1244355627f5SEric Biggers #ifdef CONFIG_UPROBES
1245355627f5SEric Biggers 	mm->uprobes_state.xol_area = NULL;
1246355627f5SEric Biggers #endif
1247355627f5SEric Biggers }
1248355627f5SEric Biggers 
1249bfedb589SEric W. Biederman static struct mm_struct *mm_init(struct mm_struct *mm, struct task_struct *p,
1250bfedb589SEric W. Biederman 	struct user_namespace *user_ns)
12511da177e4SLinus Torvalds {
1252d4af56c5SLiam R. Howlett 	mt_init_flags(&mm->mm_mt, MM_MT_FLAGS);
1253d4af56c5SLiam R. Howlett 	mt_set_external_lock(&mm->mm_mt, &mm->mmap_lock);
12541da177e4SLinus Torvalds 	atomic_set(&mm->mm_users, 1);
12551da177e4SLinus Torvalds 	atomic_set(&mm->mm_count, 1);
125657efa1feSJason Gunthorpe 	seqcount_init(&mm->write_protect_seq);
1257d8ed45c5SMichel Lespinasse 	mmap_init_lock(mm);
12581da177e4SLinus Torvalds 	INIT_LIST_HEAD(&mm->mmlist);
12595e31275cSSuren Baghdasaryan #ifdef CONFIG_PER_VMA_LOCK
12605e31275cSSuren Baghdasaryan 	mm->mm_lock_seq = 0;
12615e31275cSSuren Baghdasaryan #endif
1262af5b0f6aSKirill A. Shutemov 	mm_pgtables_bytes_init(mm);
126341f727fdSVladimir Davydov 	mm->map_count = 0;
126441f727fdSVladimir Davydov 	mm->locked_vm = 0;
126570f8a3caSDavidlohr Bueso 	atomic64_set(&mm->pinned_vm, 0);
1266d559db08SKAMEZAWA Hiroyuki 	memset(&mm->rss_stat, 0, sizeof(mm->rss_stat));
12671da177e4SLinus Torvalds 	spin_lock_init(&mm->page_table_lock);
126888aa7cc6SYang Shi 	spin_lock_init(&mm->arg_lock);
126941f727fdSVladimir Davydov 	mm_init_cpumask(mm);
1270858f0993SAlexey Dobriyan 	mm_init_aio(mm);
1271cf475ad2SBalbir Singh 	mm_init_owner(mm, p);
1272a6cbd440SFenghua Yu 	mm_pasid_init(mm);
12732b7e8665SEric Biggers 	RCU_INIT_POINTER(mm->exe_file, NULL);
1274984cfe4eSJason Gunthorpe 	mmu_notifier_subscriptions_init(mm);
127516af97dcSNadav Amit 	init_tlb_flush_pending(mm);
127641f727fdSVladimir Davydov #if defined(CONFIG_TRANSPARENT_HUGEPAGE) && !USE_SPLIT_PMD_PTLOCKS
127741f727fdSVladimir Davydov 	mm->pmd_huge_pte = NULL;
127841f727fdSVladimir Davydov #endif
1279355627f5SEric Biggers 	mm_init_uprobes_state(mm);
128013db8c50SLiu Zixian 	hugetlb_count_init(mm);
12811da177e4SLinus Torvalds 
1282a0715cc2SAlex Thorlton 	if (current->mm) {
1283a0715cc2SAlex Thorlton 		mm->flags = current->mm->flags & MMF_INIT_MASK;
1284a0715cc2SAlex Thorlton 		mm->def_flags = current->mm->def_flags & VM_INIT_DEF_MASK;
1285a0715cc2SAlex Thorlton 	} else {
1286a0715cc2SAlex Thorlton 		mm->flags = default_dump_filter;
12871da177e4SLinus Torvalds 		mm->def_flags = 0;
1288a0715cc2SAlex Thorlton 	}
1289a0715cc2SAlex Thorlton 
129041f727fdSVladimir Davydov 	if (mm_alloc_pgd(mm))
129141f727fdSVladimir Davydov 		goto fail_nopgd;
129278fb7466SPavel Emelianov 
129341f727fdSVladimir Davydov 	if (init_new_context(p, mm))
129441f727fdSVladimir Davydov 		goto fail_nocontext;
129541f727fdSVladimir Davydov 
1296223baf9dSMathieu Desnoyers 	if (mm_alloc_cid(mm))
1297223baf9dSMathieu Desnoyers 		goto fail_cid;
1298223baf9dSMathieu Desnoyers 
1299*14ef95beSMateusz Guzik 	if (percpu_counter_init_many(mm->rss_stat, 0, GFP_KERNEL_ACCOUNT,
1300*14ef95beSMateusz Guzik 				     NR_MM_COUNTERS))
1301f1a79412SShakeel Butt 		goto fail_pcpu;
1302f1a79412SShakeel Butt 
1303bfedb589SEric W. Biederman 	mm->user_ns = get_user_ns(user_ns);
1304bd74fdaeSYu Zhao 	lru_gen_init_mm(mm);
130541f727fdSVladimir Davydov 	return mm;
130641f727fdSVladimir Davydov 
1307f1a79412SShakeel Butt fail_pcpu:
1308223baf9dSMathieu Desnoyers 	mm_destroy_cid(mm);
1309223baf9dSMathieu Desnoyers fail_cid:
1310b20b0368SMathieu Desnoyers 	destroy_context(mm);
131141f727fdSVladimir Davydov fail_nocontext:
131241f727fdSVladimir Davydov 	mm_free_pgd(mm);
131341f727fdSVladimir Davydov fail_nopgd:
13141da177e4SLinus Torvalds 	free_mm(mm);
13151da177e4SLinus Torvalds 	return NULL;
13161da177e4SLinus Torvalds }
13171da177e4SLinus Torvalds 
13181da177e4SLinus Torvalds /*
13191da177e4SLinus Torvalds  * Allocate and initialize an mm_struct.
13201da177e4SLinus Torvalds  */
13211da177e4SLinus Torvalds struct mm_struct *mm_alloc(void)
13221da177e4SLinus Torvalds {
13231da177e4SLinus Torvalds 	struct mm_struct *mm;
13241da177e4SLinus Torvalds 
13251da177e4SLinus Torvalds 	mm = allocate_mm();
1326de03c72cSKOSAKI Motohiro 	if (!mm)
1327de03c72cSKOSAKI Motohiro 		return NULL;
1328de03c72cSKOSAKI Motohiro 
13291da177e4SLinus Torvalds 	memset(mm, 0, sizeof(*mm));
1330bfedb589SEric W. Biederman 	return mm_init(mm, current, current_user_ns());
13311da177e4SLinus Torvalds }
13321da177e4SLinus Torvalds 
1333ec8d7c14SMichal Hocko static inline void __mmput(struct mm_struct *mm)
13341da177e4SLinus Torvalds {
1335ec8d7c14SMichal Hocko 	VM_BUG_ON(atomic_read(&mm->mm_users));
13360ae26f1bSAndrew Morton 
1337d4b3b638SSrikar Dronamraju 	uprobe_clear_state(mm);
13381da177e4SLinus Torvalds 	exit_aio(mm);
13391c2fb7a4SAndrea Arcangeli 	ksm_exit(mm);
1340ba76149fSAndrea Arcangeli 	khugepaged_exit(mm); /* must run before exit_mmap */
13411da177e4SLinus Torvalds 	exit_mmap(mm);
13426fcb52a5SAaron Lu 	mm_put_huge_zero_page(mm);
1343925d1c40SMatt Helsley 	set_mm_exe_file(mm, NULL);
13441da177e4SLinus Torvalds 	if (!list_empty(&mm->mmlist)) {
13451da177e4SLinus Torvalds 		spin_lock(&mmlist_lock);
13461da177e4SLinus Torvalds 		list_del(&mm->mmlist);
13471da177e4SLinus Torvalds 		spin_unlock(&mmlist_lock);
13481da177e4SLinus Torvalds 	}
1349801460d0SHiroshi Shimamoto 	if (mm->binfmt)
1350801460d0SHiroshi Shimamoto 		module_put(mm->binfmt->module);
1351bd74fdaeSYu Zhao 	lru_gen_del_mm(mm);
13521da177e4SLinus Torvalds 	mmdrop(mm);
13531da177e4SLinus Torvalds }
1354ec8d7c14SMichal Hocko 
1355ec8d7c14SMichal Hocko /*
1356ec8d7c14SMichal Hocko  * Decrement the use count and release all resources for an mm.
1357ec8d7c14SMichal Hocko  */
1358ec8d7c14SMichal Hocko void mmput(struct mm_struct *mm)
1359ec8d7c14SMichal Hocko {
1360ec8d7c14SMichal Hocko 	might_sleep();
1361ec8d7c14SMichal Hocko 
1362ec8d7c14SMichal Hocko 	if (atomic_dec_and_test(&mm->mm_users))
1363ec8d7c14SMichal Hocko 		__mmput(mm);
13641da177e4SLinus Torvalds }
13651da177e4SLinus Torvalds EXPORT_SYMBOL_GPL(mmput);
13661da177e4SLinus Torvalds 
1367a1b2289cSSherry Yang #ifdef CONFIG_MMU
1368a1b2289cSSherry Yang static void mmput_async_fn(struct work_struct *work)
1369a1b2289cSSherry Yang {
1370a1b2289cSSherry Yang 	struct mm_struct *mm = container_of(work, struct mm_struct,
1371a1b2289cSSherry Yang 					    async_put_work);
1372a1b2289cSSherry Yang 
1373a1b2289cSSherry Yang 	__mmput(mm);
1374a1b2289cSSherry Yang }
1375a1b2289cSSherry Yang 
1376a1b2289cSSherry Yang void mmput_async(struct mm_struct *mm)
1377a1b2289cSSherry Yang {
1378a1b2289cSSherry Yang 	if (atomic_dec_and_test(&mm->mm_users)) {
1379a1b2289cSSherry Yang 		INIT_WORK(&mm->async_put_work, mmput_async_fn);
1380a1b2289cSSherry Yang 		schedule_work(&mm->async_put_work);
1381a1b2289cSSherry Yang 	}
1382a1b2289cSSherry Yang }
138385eaeb50SYishai Hadas EXPORT_SYMBOL_GPL(mmput_async);
1384a1b2289cSSherry Yang #endif
1385a1b2289cSSherry Yang 
138690f31d0eSKonstantin Khlebnikov /**
138790f31d0eSKonstantin Khlebnikov  * set_mm_exe_file - change a reference to the mm's executable file
138890f31d0eSKonstantin Khlebnikov  *
138990f31d0eSKonstantin Khlebnikov  * This changes mm's executable file (shown as symlink /proc/[pid]/exe).
139090f31d0eSKonstantin Khlebnikov  *
13916e399cd1SDavidlohr Bueso  * Main users are mmput() and sys_execve(). Callers prevent concurrent
13926e399cd1SDavidlohr Bueso  * invocations: in mmput() nobody alive left, in execve task is single
139335d7bdc8SDavid Hildenbrand  * threaded.
1394fe69d560SDavid Hildenbrand  *
1395fe69d560SDavid Hildenbrand  * Can only fail if new_exe_file != NULL.
139690f31d0eSKonstantin Khlebnikov  */
1397fe69d560SDavid Hildenbrand int set_mm_exe_file(struct mm_struct *mm, struct file *new_exe_file)
139838646013SJiri Slaby {
13996e399cd1SDavidlohr Bueso 	struct file *old_exe_file;
14006e399cd1SDavidlohr Bueso 
14016e399cd1SDavidlohr Bueso 	/*
14026e399cd1SDavidlohr Bueso 	 * It is safe to dereference the exe_file without RCU as
14036e399cd1SDavidlohr Bueso 	 * this function is only called if nobody else can access
14046e399cd1SDavidlohr Bueso 	 * this mm -- see comment above for justification.
14056e399cd1SDavidlohr Bueso 	 */
14066e399cd1SDavidlohr Bueso 	old_exe_file = rcu_dereference_raw(mm->exe_file);
140790f31d0eSKonstantin Khlebnikov 
1408fe69d560SDavid Hildenbrand 	if (new_exe_file) {
1409fe69d560SDavid Hildenbrand 		/*
1410fe69d560SDavid Hildenbrand 		 * We expect the caller (i.e., sys_execve) to already denied
1411fe69d560SDavid Hildenbrand 		 * write access, so this is unlikely to fail.
1412fe69d560SDavid Hildenbrand 		 */
1413fe69d560SDavid Hildenbrand 		if (unlikely(deny_write_access(new_exe_file)))
1414fe69d560SDavid Hildenbrand 			return -EACCES;
141538646013SJiri Slaby 		get_file(new_exe_file);
1416fe69d560SDavid Hildenbrand 	}
141790f31d0eSKonstantin Khlebnikov 	rcu_assign_pointer(mm->exe_file, new_exe_file);
1418fe69d560SDavid Hildenbrand 	if (old_exe_file) {
1419fe69d560SDavid Hildenbrand 		allow_write_access(old_exe_file);
142090f31d0eSKonstantin Khlebnikov 		fput(old_exe_file);
142138646013SJiri Slaby 	}
1422fe69d560SDavid Hildenbrand 	return 0;
1423fe69d560SDavid Hildenbrand }
142438646013SJiri Slaby 
142590f31d0eSKonstantin Khlebnikov /**
142635d7bdc8SDavid Hildenbrand  * replace_mm_exe_file - replace a reference to the mm's executable file
142735d7bdc8SDavid Hildenbrand  *
142835d7bdc8SDavid Hildenbrand  * This changes mm's executable file (shown as symlink /proc/[pid]/exe),
142935d7bdc8SDavid Hildenbrand  * dealing with concurrent invocation and without grabbing the mmap lock in
143035d7bdc8SDavid Hildenbrand  * write mode.
143135d7bdc8SDavid Hildenbrand  *
143235d7bdc8SDavid Hildenbrand  * Main user is sys_prctl(PR_SET_MM_MAP/EXE_FILE).
143335d7bdc8SDavid Hildenbrand  */
143435d7bdc8SDavid Hildenbrand int replace_mm_exe_file(struct mm_struct *mm, struct file *new_exe_file)
143535d7bdc8SDavid Hildenbrand {
143635d7bdc8SDavid Hildenbrand 	struct vm_area_struct *vma;
143735d7bdc8SDavid Hildenbrand 	struct file *old_exe_file;
143835d7bdc8SDavid Hildenbrand 	int ret = 0;
143935d7bdc8SDavid Hildenbrand 
144035d7bdc8SDavid Hildenbrand 	/* Forbid mm->exe_file change if old file still mapped. */
144135d7bdc8SDavid Hildenbrand 	old_exe_file = get_mm_exe_file(mm);
144235d7bdc8SDavid Hildenbrand 	if (old_exe_file) {
1443fa5e5876SMatthew Wilcox (Oracle) 		VMA_ITERATOR(vmi, mm, 0);
144435d7bdc8SDavid Hildenbrand 		mmap_read_lock(mm);
1445fa5e5876SMatthew Wilcox (Oracle) 		for_each_vma(vmi, vma) {
144635d7bdc8SDavid Hildenbrand 			if (!vma->vm_file)
144735d7bdc8SDavid Hildenbrand 				continue;
144835d7bdc8SDavid Hildenbrand 			if (path_equal(&vma->vm_file->f_path,
1449fa5e5876SMatthew Wilcox (Oracle) 				       &old_exe_file->f_path)) {
145035d7bdc8SDavid Hildenbrand 				ret = -EBUSY;
1451fa5e5876SMatthew Wilcox (Oracle) 				break;
1452fa5e5876SMatthew Wilcox (Oracle) 			}
145335d7bdc8SDavid Hildenbrand 		}
145435d7bdc8SDavid Hildenbrand 		mmap_read_unlock(mm);
145535d7bdc8SDavid Hildenbrand 		fput(old_exe_file);
145635d7bdc8SDavid Hildenbrand 		if (ret)
145735d7bdc8SDavid Hildenbrand 			return ret;
145835d7bdc8SDavid Hildenbrand 	}
145935d7bdc8SDavid Hildenbrand 
146035d7bdc8SDavid Hildenbrand 	/* set the new file, lockless */
1461fe69d560SDavid Hildenbrand 	ret = deny_write_access(new_exe_file);
1462fe69d560SDavid Hildenbrand 	if (ret)
1463fe69d560SDavid Hildenbrand 		return -EACCES;
146435d7bdc8SDavid Hildenbrand 	get_file(new_exe_file);
1465fe69d560SDavid Hildenbrand 
146635d7bdc8SDavid Hildenbrand 	old_exe_file = xchg(&mm->exe_file, new_exe_file);
1467fe69d560SDavid Hildenbrand 	if (old_exe_file) {
1468fe69d560SDavid Hildenbrand 		/*
1469fe69d560SDavid Hildenbrand 		 * Don't race with dup_mmap() getting the file and disallowing
1470fe69d560SDavid Hildenbrand 		 * write access while someone might open the file writable.
1471fe69d560SDavid Hildenbrand 		 */
1472fe69d560SDavid Hildenbrand 		mmap_read_lock(mm);
1473fe69d560SDavid Hildenbrand 		allow_write_access(old_exe_file);
147435d7bdc8SDavid Hildenbrand 		fput(old_exe_file);
1475fe69d560SDavid Hildenbrand 		mmap_read_unlock(mm);
1476fe69d560SDavid Hildenbrand 	}
147735d7bdc8SDavid Hildenbrand 	return 0;
147835d7bdc8SDavid Hildenbrand }
147938646013SJiri Slaby 
148090f31d0eSKonstantin Khlebnikov /**
148190f31d0eSKonstantin Khlebnikov  * get_mm_exe_file - acquire a reference to the mm's executable file
148290f31d0eSKonstantin Khlebnikov  *
148390f31d0eSKonstantin Khlebnikov  * Returns %NULL if mm has no associated executable file.
148490f31d0eSKonstantin Khlebnikov  * User must release file via fput().
148590f31d0eSKonstantin Khlebnikov  */
148638646013SJiri Slaby struct file *get_mm_exe_file(struct mm_struct *mm)
148738646013SJiri Slaby {
148838646013SJiri Slaby 	struct file *exe_file;
148938646013SJiri Slaby 
149090f31d0eSKonstantin Khlebnikov 	rcu_read_lock();
149190f31d0eSKonstantin Khlebnikov 	exe_file = rcu_dereference(mm->exe_file);
149290f31d0eSKonstantin Khlebnikov 	if (exe_file && !get_file_rcu(exe_file))
149390f31d0eSKonstantin Khlebnikov 		exe_file = NULL;
149490f31d0eSKonstantin Khlebnikov 	rcu_read_unlock();
149538646013SJiri Slaby 	return exe_file;
149638646013SJiri Slaby }
149738646013SJiri Slaby 
14981da177e4SLinus Torvalds /**
1499cd81a917SMateusz Guzik  * get_task_exe_file - acquire a reference to the task's executable file
1500cd81a917SMateusz Guzik  *
1501cd81a917SMateusz Guzik  * Returns %NULL if task's mm (if any) has no associated executable file or
1502cd81a917SMateusz Guzik  * this is a kernel thread with borrowed mm (see the comment above get_task_mm).
1503cd81a917SMateusz Guzik  * User must release file via fput().
1504cd81a917SMateusz Guzik  */
1505cd81a917SMateusz Guzik struct file *get_task_exe_file(struct task_struct *task)
1506cd81a917SMateusz Guzik {
1507cd81a917SMateusz Guzik 	struct file *exe_file = NULL;
1508cd81a917SMateusz Guzik 	struct mm_struct *mm;
1509cd81a917SMateusz Guzik 
1510cd81a917SMateusz Guzik 	task_lock(task);
1511cd81a917SMateusz Guzik 	mm = task->mm;
1512cd81a917SMateusz Guzik 	if (mm) {
1513cd81a917SMateusz Guzik 		if (!(task->flags & PF_KTHREAD))
1514cd81a917SMateusz Guzik 			exe_file = get_mm_exe_file(mm);
1515cd81a917SMateusz Guzik 	}
1516cd81a917SMateusz Guzik 	task_unlock(task);
1517cd81a917SMateusz Guzik 	return exe_file;
1518cd81a917SMateusz Guzik }
1519cd81a917SMateusz Guzik 
1520cd81a917SMateusz Guzik /**
15211da177e4SLinus Torvalds  * get_task_mm - acquire a reference to the task's mm
15221da177e4SLinus Torvalds  *
1523246bb0b1SOleg Nesterov  * Returns %NULL if the task has no mm.  Checks PF_KTHREAD (meaning
15241da177e4SLinus Torvalds  * this kernel workthread has transiently adopted a user mm with use_mm,
15251da177e4SLinus Torvalds  * to do its AIO) is not set and if so returns a reference to it, after
15261da177e4SLinus Torvalds  * bumping up the use count.  User must release the mm via mmput()
15271da177e4SLinus Torvalds  * after use.  Typically used by /proc and ptrace.
15281da177e4SLinus Torvalds  */
15291da177e4SLinus Torvalds struct mm_struct *get_task_mm(struct task_struct *task)
15301da177e4SLinus Torvalds {
15311da177e4SLinus Torvalds 	struct mm_struct *mm;
15321da177e4SLinus Torvalds 
15331da177e4SLinus Torvalds 	task_lock(task);
15341da177e4SLinus Torvalds 	mm = task->mm;
15351da177e4SLinus Torvalds 	if (mm) {
1536246bb0b1SOleg Nesterov 		if (task->flags & PF_KTHREAD)
15371da177e4SLinus Torvalds 			mm = NULL;
15381da177e4SLinus Torvalds 		else
15393fce371bSVegard Nossum 			mmget(mm);
15401da177e4SLinus Torvalds 	}
15411da177e4SLinus Torvalds 	task_unlock(task);
15421da177e4SLinus Torvalds 	return mm;
15431da177e4SLinus Torvalds }
15441da177e4SLinus Torvalds EXPORT_SYMBOL_GPL(get_task_mm);
15451da177e4SLinus Torvalds 
15468cdb878dSChristopher Yeoh struct mm_struct *mm_access(struct task_struct *task, unsigned int mode)
15478cdb878dSChristopher Yeoh {
15488cdb878dSChristopher Yeoh 	struct mm_struct *mm;
15498cdb878dSChristopher Yeoh 	int err;
15508cdb878dSChristopher Yeoh 
1551f7cfd871SEric W. Biederman 	err =  down_read_killable(&task->signal->exec_update_lock);
15528cdb878dSChristopher Yeoh 	if (err)
15538cdb878dSChristopher Yeoh 		return ERR_PTR(err);
15548cdb878dSChristopher Yeoh 
15558cdb878dSChristopher Yeoh 	mm = get_task_mm(task);
15568cdb878dSChristopher Yeoh 	if (mm && mm != current->mm &&
15578cdb878dSChristopher Yeoh 			!ptrace_may_access(task, mode)) {
15588cdb878dSChristopher Yeoh 		mmput(mm);
15598cdb878dSChristopher Yeoh 		mm = ERR_PTR(-EACCES);
15608cdb878dSChristopher Yeoh 	}
1561f7cfd871SEric W. Biederman 	up_read(&task->signal->exec_update_lock);
15628cdb878dSChristopher Yeoh 
15638cdb878dSChristopher Yeoh 	return mm;
15648cdb878dSChristopher Yeoh }
15658cdb878dSChristopher Yeoh 
156657b59c4aSOleg Nesterov static void complete_vfork_done(struct task_struct *tsk)
1567c415c3b4SOleg Nesterov {
1568d68b46feSOleg Nesterov 	struct completion *vfork;
1569c415c3b4SOleg Nesterov 
1570d68b46feSOleg Nesterov 	task_lock(tsk);
1571d68b46feSOleg Nesterov 	vfork = tsk->vfork_done;
1572d68b46feSOleg Nesterov 	if (likely(vfork)) {
1573c415c3b4SOleg Nesterov 		tsk->vfork_done = NULL;
1574d68b46feSOleg Nesterov 		complete(vfork);
1575d68b46feSOleg Nesterov 	}
1576d68b46feSOleg Nesterov 	task_unlock(tsk);
1577d68b46feSOleg Nesterov }
1578d68b46feSOleg Nesterov 
1579d68b46feSOleg Nesterov static int wait_for_vfork_done(struct task_struct *child,
1580d68b46feSOleg Nesterov 				struct completion *vfork)
1581d68b46feSOleg Nesterov {
1582f5d39b02SPeter Zijlstra 	unsigned int state = TASK_UNINTERRUPTIBLE|TASK_KILLABLE|TASK_FREEZABLE;
1583d68b46feSOleg Nesterov 	int killed;
1584d68b46feSOleg Nesterov 
158576f969e8SRoman Gushchin 	cgroup_enter_frozen();
1586f5d39b02SPeter Zijlstra 	killed = wait_for_completion_state(vfork, state);
158776f969e8SRoman Gushchin 	cgroup_leave_frozen(false);
1588d68b46feSOleg Nesterov 
1589d68b46feSOleg Nesterov 	if (killed) {
1590d68b46feSOleg Nesterov 		task_lock(child);
1591d68b46feSOleg Nesterov 		child->vfork_done = NULL;
1592d68b46feSOleg Nesterov 		task_unlock(child);
1593d68b46feSOleg Nesterov 	}
1594d68b46feSOleg Nesterov 
1595d68b46feSOleg Nesterov 	put_task_struct(child);
1596d68b46feSOleg Nesterov 	return killed;
1597c415c3b4SOleg Nesterov }
1598c415c3b4SOleg Nesterov 
15991da177e4SLinus Torvalds /* Please note the differences between mmput and mm_release.
16001da177e4SLinus Torvalds  * mmput is called whenever we stop holding onto a mm_struct,
16011da177e4SLinus Torvalds  * error success whatever.
16021da177e4SLinus Torvalds  *
16031da177e4SLinus Torvalds  * mm_release is called after a mm_struct has been removed
16041da177e4SLinus Torvalds  * from the current process.
16051da177e4SLinus Torvalds  *
16061da177e4SLinus Torvalds  * This difference is important for error handling, when we
16071da177e4SLinus Torvalds  * only half set up a mm_struct for a new process and need to restore
16081da177e4SLinus Torvalds  * the old one.  Because we mmput the new mm_struct before
16091da177e4SLinus Torvalds  * restoring the old one. . .
16101da177e4SLinus Torvalds  * Eric Biederman 10 January 1998
16111da177e4SLinus Torvalds  */
16124610ba7aSThomas Gleixner static void mm_release(struct task_struct *tsk, struct mm_struct *mm)
16131da177e4SLinus Torvalds {
16140326f5a9SSrikar Dronamraju 	uprobe_free_utask(tsk);
16150326f5a9SSrikar Dronamraju 
16161da177e4SLinus Torvalds 	/* Get rid of any cached register state */
16171da177e4SLinus Torvalds 	deactivate_mm(tsk, mm);
16181da177e4SLinus Torvalds 
1619fec1d011SRoland McGrath 	/*
1620735f2770SMichal Hocko 	 * Signal userspace if we're not exiting with a core dump
1621735f2770SMichal Hocko 	 * because we want to leave the value intact for debugging
1622735f2770SMichal Hocko 	 * purposes.
1623fec1d011SRoland McGrath 	 */
16249c8a8228SEric Dumazet 	if (tsk->clear_child_tid) {
162592307383SEric W. Biederman 		if (atomic_read(&mm->mm_users) > 1) {
16261da177e4SLinus Torvalds 			/*
16271da177e4SLinus Torvalds 			 * We don't check the error code - if userspace has
16281da177e4SLinus Torvalds 			 * not set up a proper pointer then tough luck.
16291da177e4SLinus Torvalds 			 */
16309c8a8228SEric Dumazet 			put_user(0, tsk->clear_child_tid);
16312de0db99SDominik Brodowski 			do_futex(tsk->clear_child_tid, FUTEX_WAKE,
16322de0db99SDominik Brodowski 					1, NULL, NULL, 0, 0);
16339c8a8228SEric Dumazet 		}
16349c8a8228SEric Dumazet 		tsk->clear_child_tid = NULL;
16351da177e4SLinus Torvalds 	}
1636f7505d64SKonstantin Khlebnikov 
1637f7505d64SKonstantin Khlebnikov 	/*
1638f7505d64SKonstantin Khlebnikov 	 * All done, finally we can wake up parent and return this mm to him.
1639f7505d64SKonstantin Khlebnikov 	 * Also kthread_stop() uses this completion for synchronization.
1640f7505d64SKonstantin Khlebnikov 	 */
1641f7505d64SKonstantin Khlebnikov 	if (tsk->vfork_done)
1642f7505d64SKonstantin Khlebnikov 		complete_vfork_done(tsk);
16431da177e4SLinus Torvalds }
16441da177e4SLinus Torvalds 
16454610ba7aSThomas Gleixner void exit_mm_release(struct task_struct *tsk, struct mm_struct *mm)
16464610ba7aSThomas Gleixner {
1647150d7158SThomas Gleixner 	futex_exit_release(tsk);
16484610ba7aSThomas Gleixner 	mm_release(tsk, mm);
16494610ba7aSThomas Gleixner }
16504610ba7aSThomas Gleixner 
16514610ba7aSThomas Gleixner void exec_mm_release(struct task_struct *tsk, struct mm_struct *mm)
16524610ba7aSThomas Gleixner {
1653150d7158SThomas Gleixner 	futex_exec_release(tsk);
16544610ba7aSThomas Gleixner 	mm_release(tsk, mm);
16554610ba7aSThomas Gleixner }
16564610ba7aSThomas Gleixner 
165713585fa0SNadav Amit /**
165813585fa0SNadav Amit  * dup_mm() - duplicates an existing mm structure
165913585fa0SNadav Amit  * @tsk: the task_struct with which the new mm will be associated.
166013585fa0SNadav Amit  * @oldmm: the mm to duplicate.
166113585fa0SNadav Amit  *
166213585fa0SNadav Amit  * Allocates a new mm structure and duplicates the provided @oldmm structure
166313585fa0SNadav Amit  * content into it.
166413585fa0SNadav Amit  *
166513585fa0SNadav Amit  * Return: the duplicated mm or NULL on failure.
1666a0a7ec30SJANAK DESAI  */
166713585fa0SNadav Amit static struct mm_struct *dup_mm(struct task_struct *tsk,
166813585fa0SNadav Amit 				struct mm_struct *oldmm)
1669a0a7ec30SJANAK DESAI {
167013585fa0SNadav Amit 	struct mm_struct *mm;
1671a0a7ec30SJANAK DESAI 	int err;
1672a0a7ec30SJANAK DESAI 
1673a0a7ec30SJANAK DESAI 	mm = allocate_mm();
1674a0a7ec30SJANAK DESAI 	if (!mm)
1675a0a7ec30SJANAK DESAI 		goto fail_nomem;
1676a0a7ec30SJANAK DESAI 
1677a0a7ec30SJANAK DESAI 	memcpy(mm, oldmm, sizeof(*mm));
1678a0a7ec30SJANAK DESAI 
1679bfedb589SEric W. Biederman 	if (!mm_init(mm, tsk, mm->user_ns))
1680a0a7ec30SJANAK DESAI 		goto fail_nomem;
1681a0a7ec30SJANAK DESAI 
1682a0a7ec30SJANAK DESAI 	err = dup_mmap(mm, oldmm);
1683a0a7ec30SJANAK DESAI 	if (err)
1684a0a7ec30SJANAK DESAI 		goto free_pt;
1685a0a7ec30SJANAK DESAI 
1686a0a7ec30SJANAK DESAI 	mm->hiwater_rss = get_mm_rss(mm);
1687a0a7ec30SJANAK DESAI 	mm->hiwater_vm = mm->total_vm;
1688a0a7ec30SJANAK DESAI 
1689801460d0SHiroshi Shimamoto 	if (mm->binfmt && !try_module_get(mm->binfmt->module))
1690801460d0SHiroshi Shimamoto 		goto free_pt;
1691801460d0SHiroshi Shimamoto 
1692a0a7ec30SJANAK DESAI 	return mm;
1693a0a7ec30SJANAK DESAI 
1694a0a7ec30SJANAK DESAI free_pt:
1695801460d0SHiroshi Shimamoto 	/* don't put binfmt in mmput, we haven't got module yet */
1696801460d0SHiroshi Shimamoto 	mm->binfmt = NULL;
1697c3f3ce04SAndrea Arcangeli 	mm_init_owner(mm, NULL);
1698a0a7ec30SJANAK DESAI 	mmput(mm);
1699a0a7ec30SJANAK DESAI 
1700a0a7ec30SJANAK DESAI fail_nomem:
1701a0a7ec30SJANAK DESAI 	return NULL;
1702a0a7ec30SJANAK DESAI }
1703a0a7ec30SJANAK DESAI 
17041da177e4SLinus Torvalds static int copy_mm(unsigned long clone_flags, struct task_struct *tsk)
17051da177e4SLinus Torvalds {
17061da177e4SLinus Torvalds 	struct mm_struct *mm, *oldmm;
17071da177e4SLinus Torvalds 
17081da177e4SLinus Torvalds 	tsk->min_flt = tsk->maj_flt = 0;
17091da177e4SLinus Torvalds 	tsk->nvcsw = tsk->nivcsw = 0;
171017406b82SMandeep Singh Baines #ifdef CONFIG_DETECT_HUNG_TASK
171117406b82SMandeep Singh Baines 	tsk->last_switch_count = tsk->nvcsw + tsk->nivcsw;
1712a2e51445SDmitry Vyukov 	tsk->last_switch_time = 0;
171317406b82SMandeep Singh Baines #endif
17141da177e4SLinus Torvalds 
17151da177e4SLinus Torvalds 	tsk->mm = NULL;
17161da177e4SLinus Torvalds 	tsk->active_mm = NULL;
17171da177e4SLinus Torvalds 
17181da177e4SLinus Torvalds 	/*
17191da177e4SLinus Torvalds 	 * Are we cloning a kernel thread?
17201da177e4SLinus Torvalds 	 *
17211da177e4SLinus Torvalds 	 * We need to steal a active VM for that..
17221da177e4SLinus Torvalds 	 */
17231da177e4SLinus Torvalds 	oldmm = current->mm;
17241da177e4SLinus Torvalds 	if (!oldmm)
17251da177e4SLinus Torvalds 		return 0;
17261da177e4SLinus Torvalds 
17271da177e4SLinus Torvalds 	if (clone_flags & CLONE_VM) {
17283fce371bSVegard Nossum 		mmget(oldmm);
17291da177e4SLinus Torvalds 		mm = oldmm;
1730a6895399SRolf Eike Beer 	} else {
173113585fa0SNadav Amit 		mm = dup_mm(tsk, current->mm);
17321da177e4SLinus Torvalds 		if (!mm)
1733a6895399SRolf Eike Beer 			return -ENOMEM;
1734a6895399SRolf Eike Beer 	}
17351da177e4SLinus Torvalds 
17361da177e4SLinus Torvalds 	tsk->mm = mm;
17371da177e4SLinus Torvalds 	tsk->active_mm = mm;
1738af7f588dSMathieu Desnoyers 	sched_mm_cid_fork(tsk);
17391da177e4SLinus Torvalds 	return 0;
17401da177e4SLinus Torvalds }
17411da177e4SLinus Torvalds 
1742a39bc516SAlexey Dobriyan static int copy_fs(unsigned long clone_flags, struct task_struct *tsk)
17431da177e4SLinus Torvalds {
1744498052bbSAl Viro 	struct fs_struct *fs = current->fs;
17451da177e4SLinus Torvalds 	if (clone_flags & CLONE_FS) {
1746498052bbSAl Viro 		/* tsk->fs is already what we want */
17472a4419b5SNick Piggin 		spin_lock(&fs->lock);
1748498052bbSAl Viro 		if (fs->in_exec) {
17492a4419b5SNick Piggin 			spin_unlock(&fs->lock);
1750498052bbSAl Viro 			return -EAGAIN;
1751498052bbSAl Viro 		}
1752498052bbSAl Viro 		fs->users++;
17532a4419b5SNick Piggin 		spin_unlock(&fs->lock);
17541da177e4SLinus Torvalds 		return 0;
17551da177e4SLinus Torvalds 	}
1756498052bbSAl Viro 	tsk->fs = copy_fs_struct(fs);
17571da177e4SLinus Torvalds 	if (!tsk->fs)
17581da177e4SLinus Torvalds 		return -ENOMEM;
17591da177e4SLinus Torvalds 	return 0;
17601da177e4SLinus Torvalds }
17611da177e4SLinus Torvalds 
176211f3f500SMike Christie static int copy_files(unsigned long clone_flags, struct task_struct *tsk,
176311f3f500SMike Christie 		      int no_files)
1764a016f338SJANAK DESAI {
1765a016f338SJANAK DESAI 	struct files_struct *oldf, *newf;
1766a016f338SJANAK DESAI 	int error = 0;
1767a016f338SJANAK DESAI 
1768a016f338SJANAK DESAI 	/*
1769a016f338SJANAK DESAI 	 * A background process may not have any files ...
1770a016f338SJANAK DESAI 	 */
1771a016f338SJANAK DESAI 	oldf = current->files;
1772a016f338SJANAK DESAI 	if (!oldf)
1773a016f338SJANAK DESAI 		goto out;
1774a016f338SJANAK DESAI 
177511f3f500SMike Christie 	if (no_files) {
177611f3f500SMike Christie 		tsk->files = NULL;
177711f3f500SMike Christie 		goto out;
177811f3f500SMike Christie 	}
177911f3f500SMike Christie 
1780a016f338SJANAK DESAI 	if (clone_flags & CLONE_FILES) {
1781a016f338SJANAK DESAI 		atomic_inc(&oldf->count);
1782a016f338SJANAK DESAI 		goto out;
1783a016f338SJANAK DESAI 	}
1784a016f338SJANAK DESAI 
178560997c3dSChristian Brauner 	newf = dup_fd(oldf, NR_OPEN_MAX, &error);
1786a016f338SJANAK DESAI 	if (!newf)
1787a016f338SJANAK DESAI 		goto out;
1788a016f338SJANAK DESAI 
1789a016f338SJANAK DESAI 	tsk->files = newf;
1790a016f338SJANAK DESAI 	error = 0;
1791a016f338SJANAK DESAI out:
1792a016f338SJANAK DESAI 	return error;
1793a016f338SJANAK DESAI }
1794a016f338SJANAK DESAI 
1795a39bc516SAlexey Dobriyan static int copy_sighand(unsigned long clone_flags, struct task_struct *tsk)
17961da177e4SLinus Torvalds {
17971da177e4SLinus Torvalds 	struct sighand_struct *sig;
17981da177e4SLinus Torvalds 
179960348802SZhaolei 	if (clone_flags & CLONE_SIGHAND) {
1800d036bda7SElena Reshetova 		refcount_inc(&current->sighand->count);
18011da177e4SLinus Torvalds 		return 0;
18021da177e4SLinus Torvalds 	}
18031da177e4SLinus Torvalds 	sig = kmem_cache_alloc(sighand_cachep, GFP_KERNEL);
18040c282b06SMadhuparna Bhowmik 	RCU_INIT_POINTER(tsk->sighand, sig);
18051da177e4SLinus Torvalds 	if (!sig)
18061da177e4SLinus Torvalds 		return -ENOMEM;
18079d7fb042SPeter Zijlstra 
1808d036bda7SElena Reshetova 	refcount_set(&sig->count, 1);
180906e62a46SJann Horn 	spin_lock_irq(&current->sighand->siglock);
18101da177e4SLinus Torvalds 	memcpy(sig->action, current->sighand->action, sizeof(sig->action));
181106e62a46SJann Horn 	spin_unlock_irq(&current->sighand->siglock);
1812b612e5dfSChristian Brauner 
1813b612e5dfSChristian Brauner 	/* Reset all signal handler not set to SIG_IGN to SIG_DFL. */
1814b612e5dfSChristian Brauner 	if (clone_flags & CLONE_CLEAR_SIGHAND)
1815b612e5dfSChristian Brauner 		flush_signal_handlers(tsk, 0);
1816b612e5dfSChristian Brauner 
18171da177e4SLinus Torvalds 	return 0;
18181da177e4SLinus Torvalds }
18191da177e4SLinus Torvalds 
1820a7e5328aSOleg Nesterov void __cleanup_sighand(struct sighand_struct *sighand)
1821c81addc9SOleg Nesterov {
1822d036bda7SElena Reshetova 	if (refcount_dec_and_test(&sighand->count)) {
1823d80e731eSOleg Nesterov 		signalfd_cleanup(sighand);
1824392809b2SOleg Nesterov 		/*
18255f0d5a3aSPaul E. McKenney 		 * sighand_cachep is SLAB_TYPESAFE_BY_RCU so we can free it
1826392809b2SOleg Nesterov 		 * without an RCU grace period, see __lock_task_sighand().
1827392809b2SOleg Nesterov 		 */
1828c81addc9SOleg Nesterov 		kmem_cache_free(sighand_cachep, sighand);
1829c81addc9SOleg Nesterov 	}
1830d80e731eSOleg Nesterov }
1831c81addc9SOleg Nesterov 
1832f06febc9SFrank Mayhar /*
1833f06febc9SFrank Mayhar  * Initialize POSIX timer handling for a thread group.
1834f06febc9SFrank Mayhar  */
1835f06febc9SFrank Mayhar static void posix_cpu_timers_init_group(struct signal_struct *sig)
1836f06febc9SFrank Mayhar {
18372b69942fSThomas Gleixner 	struct posix_cputimers *pct = &sig->posix_cputimers;
183878d7d407SJiri Slaby 	unsigned long cpu_limit;
183978d7d407SJiri Slaby 
1840316c1608SJason Low 	cpu_limit = READ_ONCE(sig->rlim[RLIMIT_CPU].rlim_cur);
18413a245c0fSThomas Gleixner 	posix_cputimers_group_init(pct, cpu_limit);
18426279a751SOleg Nesterov }
18436279a751SOleg Nesterov 
1844a39bc516SAlexey Dobriyan static int copy_signal(unsigned long clone_flags, struct task_struct *tsk)
18451da177e4SLinus Torvalds {
18461da177e4SLinus Torvalds 	struct signal_struct *sig;
18471da177e4SLinus Torvalds 
18484ab6c083SOleg Nesterov 	if (clone_flags & CLONE_THREAD)
1849490dea45SPeter Zijlstra 		return 0;
18506279a751SOleg Nesterov 
1851a56704efSVeaceslav Falico 	sig = kmem_cache_zalloc(signal_cachep, GFP_KERNEL);
18521da177e4SLinus Torvalds 	tsk->signal = sig;
18531da177e4SLinus Torvalds 	if (!sig)
18541da177e4SLinus Torvalds 		return -ENOMEM;
18551da177e4SLinus Torvalds 
1856b3ac022cSOleg Nesterov 	sig->nr_threads = 1;
1857d80f7d7bSEric W. Biederman 	sig->quick_threads = 1;
18581da177e4SLinus Torvalds 	atomic_set(&sig->live, 1);
185960d4de3fSElena Reshetova 	refcount_set(&sig->sigcnt, 1);
18600c740d0aSOleg Nesterov 
18610c740d0aSOleg Nesterov 	/* list_add(thread_node, thread_head) without INIT_LIST_HEAD() */
18620c740d0aSOleg Nesterov 	sig->thread_head = (struct list_head)LIST_HEAD_INIT(tsk->thread_node);
18630c740d0aSOleg Nesterov 	tsk->thread_node = (struct list_head)LIST_HEAD_INIT(sig->thread_head);
18640c740d0aSOleg Nesterov 
18651da177e4SLinus Torvalds 	init_waitqueue_head(&sig->wait_chldexit);
1866db51aeccSOleg Nesterov 	sig->curr_target = tsk;
18671da177e4SLinus Torvalds 	init_sigpending(&sig->shared_pending);
1868c3ad2c3bSEric W. Biederman 	INIT_HLIST_HEAD(&sig->multiprocess);
1869e78c3496SRik van Riel 	seqlock_init(&sig->stats_lock);
18709d7fb042SPeter Zijlstra 	prev_cputime_init(&sig->prev_cputime);
18711da177e4SLinus Torvalds 
1872baa73d9eSNicolas Pitre #ifdef CONFIG_POSIX_TIMERS
1873b18b6a9cSNicolas Pitre 	INIT_LIST_HEAD(&sig->posix_timers);
1874c9cb2e3dSThomas Gleixner 	hrtimer_init(&sig->real_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
18751da177e4SLinus Torvalds 	sig->real_timer.function = it_real_fn;
1876baa73d9eSNicolas Pitre #endif
18771da177e4SLinus Torvalds 
18781da177e4SLinus Torvalds 	task_lock(current->group_leader);
18791da177e4SLinus Torvalds 	memcpy(sig->rlim, current->signal->rlim, sizeof sig->rlim);
18801da177e4SLinus Torvalds 	task_unlock(current->group_leader);
18811da177e4SLinus Torvalds 
18826279a751SOleg Nesterov 	posix_cpu_timers_init_group(sig);
18836279a751SOleg Nesterov 
1884522ed776SMiloslav Trmac 	tty_audit_fork(sig);
18855091faa4SMike Galbraith 	sched_autogroup_fork(sig);
1886522ed776SMiloslav Trmac 
1887a63d83f4SDavid Rientjes 	sig->oom_score_adj = current->signal->oom_score_adj;
1888dabb16f6SMandeep Singh Baines 	sig->oom_score_adj_min = current->signal->oom_score_adj_min;
188928b83c51SKOSAKI Motohiro 
18909b1bf12dSKOSAKI Motohiro 	mutex_init(&sig->cred_guard_mutex);
1891f7cfd871SEric W. Biederman 	init_rwsem(&sig->exec_update_lock);
18929b1bf12dSKOSAKI Motohiro 
18931da177e4SLinus Torvalds 	return 0;
18941da177e4SLinus Torvalds }
18951da177e4SLinus Torvalds 
1896dbd95212SKees Cook static void copy_seccomp(struct task_struct *p)
1897dbd95212SKees Cook {
1898dbd95212SKees Cook #ifdef CONFIG_SECCOMP
1899dbd95212SKees Cook 	/*
1900dbd95212SKees Cook 	 * Must be called with sighand->lock held, which is common to
1901dbd95212SKees Cook 	 * all threads in the group. Holding cred_guard_mutex is not
1902dbd95212SKees Cook 	 * needed because this new task is not yet running and cannot
1903dbd95212SKees Cook 	 * be racing exec.
1904dbd95212SKees Cook 	 */
190569f6a34bSGuenter Roeck 	assert_spin_locked(&current->sighand->siglock);
1906dbd95212SKees Cook 
1907dbd95212SKees Cook 	/* Ref-count the new filter user, and assign it. */
1908dbd95212SKees Cook 	get_seccomp_filter(current);
1909dbd95212SKees Cook 	p->seccomp = current->seccomp;
1910dbd95212SKees Cook 
1911dbd95212SKees Cook 	/*
1912dbd95212SKees Cook 	 * Explicitly enable no_new_privs here in case it got set
1913dbd95212SKees Cook 	 * between the task_struct being duplicated and holding the
1914dbd95212SKees Cook 	 * sighand lock. The seccomp state and nnp must be in sync.
1915dbd95212SKees Cook 	 */
1916dbd95212SKees Cook 	if (task_no_new_privs(current))
1917dbd95212SKees Cook 		task_set_no_new_privs(p);
1918dbd95212SKees Cook 
1919dbd95212SKees Cook 	/*
1920dbd95212SKees Cook 	 * If the parent gained a seccomp mode after copying thread
1921dbd95212SKees Cook 	 * flags and between before we held the sighand lock, we have
1922dbd95212SKees Cook 	 * to manually enable the seccomp thread flag here.
1923dbd95212SKees Cook 	 */
1924dbd95212SKees Cook 	if (p->seccomp.mode != SECCOMP_MODE_DISABLED)
192523d67a54SGabriel Krisman Bertazi 		set_task_syscall_work(p, SECCOMP);
1926dbd95212SKees Cook #endif
1927dbd95212SKees Cook }
1928dbd95212SKees Cook 
192917da2bd9SHeiko Carstens SYSCALL_DEFINE1(set_tid_address, int __user *, tidptr)
19301da177e4SLinus Torvalds {
19311da177e4SLinus Torvalds 	current->clear_child_tid = tidptr;
19321da177e4SLinus Torvalds 
1933b488893aSPavel Emelyanov 	return task_pid_vnr(current);
19341da177e4SLinus Torvalds }
19351da177e4SLinus Torvalds 
1936a39bc516SAlexey Dobriyan static void rt_mutex_init_task(struct task_struct *p)
193723f78d4aSIngo Molnar {
19381d615482SThomas Gleixner 	raw_spin_lock_init(&p->pi_lock);
1939e29e175bSZilvinas Valinskas #ifdef CONFIG_RT_MUTEXES
1940a23ba907SDavidlohr Bueso 	p->pi_waiters = RB_ROOT_CACHED;
1941e96a7705SXunlei Pang 	p->pi_top_task = NULL;
194223f78d4aSIngo Molnar 	p->pi_blocked_on = NULL;
194323f78d4aSIngo Molnar #endif
194423f78d4aSIngo Molnar }
194523f78d4aSIngo Molnar 
19462c470475SEric W. Biederman static inline void init_task_pid_links(struct task_struct *task)
19472c470475SEric W. Biederman {
19482c470475SEric W. Biederman 	enum pid_type type;
19492c470475SEric W. Biederman 
195096e1e984SAlexander Guril 	for (type = PIDTYPE_PID; type < PIDTYPE_MAX; ++type)
19512c470475SEric W. Biederman 		INIT_HLIST_NODE(&task->pid_links[type]);
19522c470475SEric W. Biederman }
19532c470475SEric W. Biederman 
195481907739SOleg Nesterov static inline void
195581907739SOleg Nesterov init_task_pid(struct task_struct *task, enum pid_type type, struct pid *pid)
195681907739SOleg Nesterov {
19572c470475SEric W. Biederman 	if (type == PIDTYPE_PID)
19582c470475SEric W. Biederman 		task->thread_pid = pid;
19592c470475SEric W. Biederman 	else
19602c470475SEric W. Biederman 		task->signal->pids[type] = pid;
196181907739SOleg Nesterov }
196281907739SOleg Nesterov 
19636bfbaa51SIngo Molnar static inline void rcu_copy_process(struct task_struct *p)
19646bfbaa51SIngo Molnar {
19656bfbaa51SIngo Molnar #ifdef CONFIG_PREEMPT_RCU
19666bfbaa51SIngo Molnar 	p->rcu_read_lock_nesting = 0;
19676bfbaa51SIngo Molnar 	p->rcu_read_unlock_special.s = 0;
19686bfbaa51SIngo Molnar 	p->rcu_blocked_node = NULL;
19696bfbaa51SIngo Molnar 	INIT_LIST_HEAD(&p->rcu_node_entry);
19706bfbaa51SIngo Molnar #endif /* #ifdef CONFIG_PREEMPT_RCU */
19716bfbaa51SIngo Molnar #ifdef CONFIG_TASKS_RCU
19726bfbaa51SIngo Molnar 	p->rcu_tasks_holdout = false;
19736bfbaa51SIngo Molnar 	INIT_LIST_HEAD(&p->rcu_tasks_holdout_list);
19746bfbaa51SIngo Molnar 	p->rcu_tasks_idle_cpu = -1;
19756bfbaa51SIngo Molnar #endif /* #ifdef CONFIG_TASKS_RCU */
1976d5f177d3SPaul E. McKenney #ifdef CONFIG_TASKS_TRACE_RCU
1977d5f177d3SPaul E. McKenney 	p->trc_reader_nesting = 0;
1978276c4104SPaul E. McKenney 	p->trc_reader_special.s = 0;
1979d5f177d3SPaul E. McKenney 	INIT_LIST_HEAD(&p->trc_holdout_list);
1980434c9eefSPaul E. McKenney 	INIT_LIST_HEAD(&p->trc_blkd_node);
1981d5f177d3SPaul E. McKenney #endif /* #ifdef CONFIG_TASKS_TRACE_RCU */
19826bfbaa51SIngo Molnar }
19836bfbaa51SIngo Molnar 
19843695eae5SChristian Brauner struct pid *pidfd_pid(const struct file *file)
19853695eae5SChristian Brauner {
19863695eae5SChristian Brauner 	if (file->f_op == &pidfd_fops)
19873695eae5SChristian Brauner 		return file->private_data;
19883695eae5SChristian Brauner 
19893695eae5SChristian Brauner 	return ERR_PTR(-EBADF);
19903695eae5SChristian Brauner }
19913695eae5SChristian Brauner 
1992b3e58382SChristian Brauner static int pidfd_release(struct inode *inode, struct file *file)
1993b3e58382SChristian Brauner {
1994b3e58382SChristian Brauner 	struct pid *pid = file->private_data;
1995b3e58382SChristian Brauner 
1996b3e58382SChristian Brauner 	file->private_data = NULL;
1997b3e58382SChristian Brauner 	put_pid(pid);
1998b3e58382SChristian Brauner 	return 0;
1999b3e58382SChristian Brauner }
2000b3e58382SChristian Brauner 
2001b3e58382SChristian Brauner #ifdef CONFIG_PROC_FS
200215d42eb2SChristian Kellner /**
200315d42eb2SChristian Kellner  * pidfd_show_fdinfo - print information about a pidfd
200415d42eb2SChristian Kellner  * @m: proc fdinfo file
200515d42eb2SChristian Kellner  * @f: file referencing a pidfd
200615d42eb2SChristian Kellner  *
200715d42eb2SChristian Kellner  * Pid:
200815d42eb2SChristian Kellner  * This function will print the pid that a given pidfd refers to in the
200915d42eb2SChristian Kellner  * pid namespace of the procfs instance.
201015d42eb2SChristian Kellner  * If the pid namespace of the process is not a descendant of the pid
201115d42eb2SChristian Kellner  * namespace of the procfs instance 0 will be shown as its pid. This is
201215d42eb2SChristian Kellner  * similar to calling getppid() on a process whose parent is outside of
201315d42eb2SChristian Kellner  * its pid namespace.
201415d42eb2SChristian Kellner  *
201515d42eb2SChristian Kellner  * NSpid:
201615d42eb2SChristian Kellner  * If pid namespaces are supported then this function will also print
201715d42eb2SChristian Kellner  * the pid of a given pidfd refers to for all descendant pid namespaces
201815d42eb2SChristian Kellner  * starting from the current pid namespace of the instance, i.e. the
201915d42eb2SChristian Kellner  * Pid field and the first entry in the NSpid field will be identical.
202015d42eb2SChristian Kellner  * If the pid namespace of the process is not a descendant of the pid
202115d42eb2SChristian Kellner  * namespace of the procfs instance 0 will be shown as its first NSpid
202215d42eb2SChristian Kellner  * entry and no others will be shown.
202315d42eb2SChristian Kellner  * Note that this differs from the Pid and NSpid fields in
202415d42eb2SChristian Kellner  * /proc/<pid>/status where Pid and NSpid are always shown relative to
202515d42eb2SChristian Kellner  * the  pid namespace of the procfs instance. The difference becomes
202615d42eb2SChristian Kellner  * obvious when sending around a pidfd between pid namespaces from a
2027a8ca6b13SXiaofeng Cao  * different branch of the tree, i.e. where no ancestral relation is
202815d42eb2SChristian Kellner  * present between the pid namespaces:
202915d42eb2SChristian Kellner  * - create two new pid namespaces ns1 and ns2 in the initial pid
203015d42eb2SChristian Kellner  *   namespace (also take care to create new mount namespaces in the
203115d42eb2SChristian Kellner  *   new pid namespace and mount procfs)
203215d42eb2SChristian Kellner  * - create a process with a pidfd in ns1
203315d42eb2SChristian Kellner  * - send pidfd from ns1 to ns2
203415d42eb2SChristian Kellner  * - read /proc/self/fdinfo/<pidfd> and observe that both Pid and NSpid
203515d42eb2SChristian Kellner  *   have exactly one entry, which is 0
203615d42eb2SChristian Kellner  */
2037b3e58382SChristian Brauner static void pidfd_show_fdinfo(struct seq_file *m, struct file *f)
2038b3e58382SChristian Brauner {
2039b3e58382SChristian Brauner 	struct pid *pid = f->private_data;
20403d6d8da4SChristian Brauner 	struct pid_namespace *ns;
20413d6d8da4SChristian Brauner 	pid_t nr = -1;
2042b3e58382SChristian Brauner 
20433d6d8da4SChristian Brauner 	if (likely(pid_has_task(pid, PIDTYPE_PID))) {
20449d78edeaSAlexey Gladkov 		ns = proc_pid_ns(file_inode(m->file)->i_sb);
20453d6d8da4SChristian Brauner 		nr = pid_nr_ns(pid, ns);
20463d6d8da4SChristian Brauner 	}
20473d6d8da4SChristian Brauner 
20483d6d8da4SChristian Brauner 	seq_put_decimal_ll(m, "Pid:\t", nr);
204915d42eb2SChristian Kellner 
205015d42eb2SChristian Kellner #ifdef CONFIG_PID_NS
20513d6d8da4SChristian Brauner 	seq_put_decimal_ll(m, "\nNSpid:\t", nr);
20523d6d8da4SChristian Brauner 	if (nr > 0) {
205315d42eb2SChristian Kellner 		int i;
205415d42eb2SChristian Kellner 
205515d42eb2SChristian Kellner 		/* If nr is non-zero it means that 'pid' is valid and that
205615d42eb2SChristian Kellner 		 * ns, i.e. the pid namespace associated with the procfs
205715d42eb2SChristian Kellner 		 * instance, is in the pid namespace hierarchy of pid.
205815d42eb2SChristian Kellner 		 * Start at one below the already printed level.
205915d42eb2SChristian Kellner 		 */
206015d42eb2SChristian Kellner 		for (i = ns->level + 1; i <= pid->level; i++)
20613d6d8da4SChristian Brauner 			seq_put_decimal_ll(m, "\t", pid->numbers[i].nr);
206215d42eb2SChristian Kellner 	}
206315d42eb2SChristian Kellner #endif
2064b3e58382SChristian Brauner 	seq_putc(m, '\n');
2065b3e58382SChristian Brauner }
2066b3e58382SChristian Brauner #endif
2067b3e58382SChristian Brauner 
2068b53b0b9dSJoel Fernandes (Google) /*
2069b53b0b9dSJoel Fernandes (Google)  * Poll support for process exit notification.
2070b53b0b9dSJoel Fernandes (Google)  */
20719e77716aSLuc Van Oostenryck static __poll_t pidfd_poll(struct file *file, struct poll_table_struct *pts)
2072b53b0b9dSJoel Fernandes (Google) {
2073b53b0b9dSJoel Fernandes (Google) 	struct pid *pid = file->private_data;
20749e77716aSLuc Van Oostenryck 	__poll_t poll_flags = 0;
2075b53b0b9dSJoel Fernandes (Google) 
2076b53b0b9dSJoel Fernandes (Google) 	poll_wait(file, &pid->wait_pidfd, pts);
2077b53b0b9dSJoel Fernandes (Google) 
2078b53b0b9dSJoel Fernandes (Google) 	/*
2079b53b0b9dSJoel Fernandes (Google) 	 * Inform pollers only when the whole thread group exits.
2080b53b0b9dSJoel Fernandes (Google) 	 * If the thread group leader exits before all other threads in the
2081b53b0b9dSJoel Fernandes (Google) 	 * group, then poll(2) should block, similar to the wait(2) family.
2082b53b0b9dSJoel Fernandes (Google) 	 */
208338fd525aSEric W. Biederman 	if (thread_group_exited(pid))
20849e77716aSLuc Van Oostenryck 		poll_flags = EPOLLIN | EPOLLRDNORM;
2085b53b0b9dSJoel Fernandes (Google) 
2086b53b0b9dSJoel Fernandes (Google) 	return poll_flags;
2087b53b0b9dSJoel Fernandes (Google) }
2088b53b0b9dSJoel Fernandes (Google) 
2089b3e58382SChristian Brauner const struct file_operations pidfd_fops = {
2090b3e58382SChristian Brauner 	.release = pidfd_release,
2091b53b0b9dSJoel Fernandes (Google) 	.poll = pidfd_poll,
2092b3e58382SChristian Brauner #ifdef CONFIG_PROC_FS
2093b3e58382SChristian Brauner 	.show_fdinfo = pidfd_show_fdinfo,
2094b3e58382SChristian Brauner #endif
2095b3e58382SChristian Brauner };
2096b3e58382SChristian Brauner 
20976ae930d9SChristian Brauner /**
20986ae930d9SChristian Brauner  * __pidfd_prepare - allocate a new pidfd_file and reserve a pidfd
20996ae930d9SChristian Brauner  * @pid:   the struct pid for which to create a pidfd
21006ae930d9SChristian Brauner  * @flags: flags of the new @pidfd
21016ae930d9SChristian Brauner  * @pidfd: the pidfd to return
21026ae930d9SChristian Brauner  *
21036ae930d9SChristian Brauner  * Allocate a new file that stashes @pid and reserve a new pidfd number in the
21046ae930d9SChristian Brauner  * caller's file descriptor table. The pidfd is reserved but not installed yet.
21056ae930d9SChristian Brauner 
21066ae930d9SChristian Brauner  * The helper doesn't perform checks on @pid which makes it useful for pidfds
21076ae930d9SChristian Brauner  * created via CLONE_PIDFD where @pid has no task attached when the pidfd and
21086ae930d9SChristian Brauner  * pidfd file are prepared.
21096ae930d9SChristian Brauner  *
21106ae930d9SChristian Brauner  * If this function returns successfully the caller is responsible to either
21116ae930d9SChristian Brauner  * call fd_install() passing the returned pidfd and pidfd file as arguments in
21126ae930d9SChristian Brauner  * order to install the pidfd into its file descriptor table or they must use
21136ae930d9SChristian Brauner  * put_unused_fd() and fput() on the returned pidfd and pidfd file
21146ae930d9SChristian Brauner  * respectively.
21156ae930d9SChristian Brauner  *
21166ae930d9SChristian Brauner  * This function is useful when a pidfd must already be reserved but there
21176ae930d9SChristian Brauner  * might still be points of failure afterwards and the caller wants to ensure
21186ae930d9SChristian Brauner  * that no pidfd is leaked into its file descriptor table.
21196ae930d9SChristian Brauner  *
21206ae930d9SChristian Brauner  * Return: On success, a reserved pidfd is returned from the function and a new
21216ae930d9SChristian Brauner  *         pidfd file is returned in the last argument to the function. On
21226ae930d9SChristian Brauner  *         error, a negative error code is returned from the function and the
21236ae930d9SChristian Brauner  *         last argument remains unchanged.
21246ae930d9SChristian Brauner  */
21256ae930d9SChristian Brauner static int __pidfd_prepare(struct pid *pid, unsigned int flags, struct file **ret)
21266ae930d9SChristian Brauner {
21276ae930d9SChristian Brauner 	int pidfd;
21286ae930d9SChristian Brauner 	struct file *pidfd_file;
21296ae930d9SChristian Brauner 
21306ae930d9SChristian Brauner 	if (flags & ~(O_NONBLOCK | O_RDWR | O_CLOEXEC))
21316ae930d9SChristian Brauner 		return -EINVAL;
21326ae930d9SChristian Brauner 
21336ae930d9SChristian Brauner 	pidfd = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
21346ae930d9SChristian Brauner 	if (pidfd < 0)
21356ae930d9SChristian Brauner 		return pidfd;
21366ae930d9SChristian Brauner 
21376ae930d9SChristian Brauner 	pidfd_file = anon_inode_getfile("[pidfd]", &pidfd_fops, pid,
21386ae930d9SChristian Brauner 					flags | O_RDWR | O_CLOEXEC);
21396ae930d9SChristian Brauner 	if (IS_ERR(pidfd_file)) {
21406ae930d9SChristian Brauner 		put_unused_fd(pidfd);
21416ae930d9SChristian Brauner 		return PTR_ERR(pidfd_file);
21426ae930d9SChristian Brauner 	}
21436ae930d9SChristian Brauner 	get_pid(pid); /* held by pidfd_file now */
21446ae930d9SChristian Brauner 	*ret = pidfd_file;
21456ae930d9SChristian Brauner 	return pidfd;
21466ae930d9SChristian Brauner }
21476ae930d9SChristian Brauner 
21486ae930d9SChristian Brauner /**
21496ae930d9SChristian Brauner  * pidfd_prepare - allocate a new pidfd_file and reserve a pidfd
21506ae930d9SChristian Brauner  * @pid:   the struct pid for which to create a pidfd
21516ae930d9SChristian Brauner  * @flags: flags of the new @pidfd
21526ae930d9SChristian Brauner  * @pidfd: the pidfd to return
21536ae930d9SChristian Brauner  *
21546ae930d9SChristian Brauner  * Allocate a new file that stashes @pid and reserve a new pidfd number in the
21556ae930d9SChristian Brauner  * caller's file descriptor table. The pidfd is reserved but not installed yet.
21566ae930d9SChristian Brauner  *
21576ae930d9SChristian Brauner  * The helper verifies that @pid is used as a thread group leader.
21586ae930d9SChristian Brauner  *
21596ae930d9SChristian Brauner  * If this function returns successfully the caller is responsible to either
21606ae930d9SChristian Brauner  * call fd_install() passing the returned pidfd and pidfd file as arguments in
21616ae930d9SChristian Brauner  * order to install the pidfd into its file descriptor table or they must use
21626ae930d9SChristian Brauner  * put_unused_fd() and fput() on the returned pidfd and pidfd file
21636ae930d9SChristian Brauner  * respectively.
21646ae930d9SChristian Brauner  *
21656ae930d9SChristian Brauner  * This function is useful when a pidfd must already be reserved but there
21666ae930d9SChristian Brauner  * might still be points of failure afterwards and the caller wants to ensure
21676ae930d9SChristian Brauner  * that no pidfd is leaked into its file descriptor table.
21686ae930d9SChristian Brauner  *
21696ae930d9SChristian Brauner  * Return: On success, a reserved pidfd is returned from the function and a new
21706ae930d9SChristian Brauner  *         pidfd file is returned in the last argument to the function. On
21716ae930d9SChristian Brauner  *         error, a negative error code is returned from the function and the
21726ae930d9SChristian Brauner  *         last argument remains unchanged.
21736ae930d9SChristian Brauner  */
21746ae930d9SChristian Brauner int pidfd_prepare(struct pid *pid, unsigned int flags, struct file **ret)
21756ae930d9SChristian Brauner {
21766ae930d9SChristian Brauner 	if (!pid || !pid_has_task(pid, PIDTYPE_TGID))
21776ae930d9SChristian Brauner 		return -EINVAL;
21786ae930d9SChristian Brauner 
21796ae930d9SChristian Brauner 	return __pidfd_prepare(pid, flags, ret);
21806ae930d9SChristian Brauner }
21816ae930d9SChristian Brauner 
2182c3f3ce04SAndrea Arcangeli static void __delayed_free_task(struct rcu_head *rhp)
2183c3f3ce04SAndrea Arcangeli {
2184c3f3ce04SAndrea Arcangeli 	struct task_struct *tsk = container_of(rhp, struct task_struct, rcu);
2185c3f3ce04SAndrea Arcangeli 
2186c3f3ce04SAndrea Arcangeli 	free_task(tsk);
2187c3f3ce04SAndrea Arcangeli }
2188c3f3ce04SAndrea Arcangeli 
2189c3f3ce04SAndrea Arcangeli static __always_inline void delayed_free_task(struct task_struct *tsk)
2190c3f3ce04SAndrea Arcangeli {
2191c3f3ce04SAndrea Arcangeli 	if (IS_ENABLED(CONFIG_MEMCG))
2192c3f3ce04SAndrea Arcangeli 		call_rcu(&tsk->rcu, __delayed_free_task);
2193c3f3ce04SAndrea Arcangeli 	else
2194c3f3ce04SAndrea Arcangeli 		free_task(tsk);
2195c3f3ce04SAndrea Arcangeli }
2196c3f3ce04SAndrea Arcangeli 
219767197a4fSSuren Baghdasaryan static void copy_oom_score_adj(u64 clone_flags, struct task_struct *tsk)
219867197a4fSSuren Baghdasaryan {
219967197a4fSSuren Baghdasaryan 	/* Skip if kernel thread */
220067197a4fSSuren Baghdasaryan 	if (!tsk->mm)
220167197a4fSSuren Baghdasaryan 		return;
220267197a4fSSuren Baghdasaryan 
220367197a4fSSuren Baghdasaryan 	/* Skip if spawning a thread or using vfork */
220467197a4fSSuren Baghdasaryan 	if ((clone_flags & (CLONE_VM | CLONE_THREAD | CLONE_VFORK)) != CLONE_VM)
220567197a4fSSuren Baghdasaryan 		return;
220667197a4fSSuren Baghdasaryan 
220767197a4fSSuren Baghdasaryan 	/* We need to synchronize with __set_oom_adj */
220867197a4fSSuren Baghdasaryan 	mutex_lock(&oom_adj_mutex);
220967197a4fSSuren Baghdasaryan 	set_bit(MMF_MULTIPROCESS, &tsk->mm->flags);
221067197a4fSSuren Baghdasaryan 	/* Update the values in case they were changed after copy_signal */
221167197a4fSSuren Baghdasaryan 	tsk->signal->oom_score_adj = current->signal->oom_score_adj;
221267197a4fSSuren Baghdasaryan 	tsk->signal->oom_score_adj_min = current->signal->oom_score_adj_min;
221367197a4fSSuren Baghdasaryan 	mutex_unlock(&oom_adj_mutex);
221467197a4fSSuren Baghdasaryan }
221567197a4fSSuren Baghdasaryan 
221679257534SDaniel Bristot de Oliveira #ifdef CONFIG_RV
221779257534SDaniel Bristot de Oliveira static void rv_task_fork(struct task_struct *p)
221879257534SDaniel Bristot de Oliveira {
221979257534SDaniel Bristot de Oliveira 	int i;
222079257534SDaniel Bristot de Oliveira 
222179257534SDaniel Bristot de Oliveira 	for (i = 0; i < RV_PER_TASK_MONITORS; i++)
222279257534SDaniel Bristot de Oliveira 		p->rv[i].da_mon.monitoring = false;
222379257534SDaniel Bristot de Oliveira }
222479257534SDaniel Bristot de Oliveira #else
222579257534SDaniel Bristot de Oliveira #define rv_task_fork(p) do {} while (0)
222679257534SDaniel Bristot de Oliveira #endif
222779257534SDaniel Bristot de Oliveira 
2228f06febc9SFrank Mayhar /*
22291da177e4SLinus Torvalds  * This creates a new process as a copy of the old one,
22301da177e4SLinus Torvalds  * but does not actually start it yet.
22311da177e4SLinus Torvalds  *
22321da177e4SLinus Torvalds  * It copies the registers, and all the appropriate
22331da177e4SLinus Torvalds  * parts of the process environment (as per the clone
22341da177e4SLinus Torvalds  * flags). The actual kick-off is left to the caller.
22351da177e4SLinus Torvalds  */
223689c8e98dSMike Christie __latent_entropy struct task_struct *copy_process(
223709a05394SRoland McGrath 					struct pid *pid,
22383033f14aSJosh Triplett 					int trace,
22397f192e3cSChristian Brauner 					int node,
22407f192e3cSChristian Brauner 					struct kernel_clone_args *args)
22411da177e4SLinus Torvalds {
2242b3e58382SChristian Brauner 	int pidfd = -1, retval;
2243a24efe62SMariusz Kozlowski 	struct task_struct *p;
2244c3ad2c3bSEric W. Biederman 	struct multiprocess_signals delayed;
22456fd2fe49SAl Viro 	struct file *pidfile = NULL;
2246c5febea0SEric W. Biederman 	const u64 clone_flags = args->flags;
2247769071acSAndrei Vagin 	struct nsproxy *nsp = current->nsproxy;
22481da177e4SLinus Torvalds 
2249667b6094SMarcos Paulo de Souza 	/*
2250667b6094SMarcos Paulo de Souza 	 * Don't allow sharing the root directory with processes in a different
2251667b6094SMarcos Paulo de Souza 	 * namespace
2252667b6094SMarcos Paulo de Souza 	 */
22531da177e4SLinus Torvalds 	if ((clone_flags & (CLONE_NEWNS|CLONE_FS)) == (CLONE_NEWNS|CLONE_FS))
22541da177e4SLinus Torvalds 		return ERR_PTR(-EINVAL);
22551da177e4SLinus Torvalds 
2256e66eded8SEric W. Biederman 	if ((clone_flags & (CLONE_NEWUSER|CLONE_FS)) == (CLONE_NEWUSER|CLONE_FS))
2257e66eded8SEric W. Biederman 		return ERR_PTR(-EINVAL);
2258e66eded8SEric W. Biederman 
22591da177e4SLinus Torvalds 	/*
22601da177e4SLinus Torvalds 	 * Thread groups must share signals as well, and detached threads
22611da177e4SLinus Torvalds 	 * can only be started up within the thread group.
22621da177e4SLinus Torvalds 	 */
22631da177e4SLinus Torvalds 	if ((clone_flags & CLONE_THREAD) && !(clone_flags & CLONE_SIGHAND))
22641da177e4SLinus Torvalds 		return ERR_PTR(-EINVAL);
22651da177e4SLinus Torvalds 
22661da177e4SLinus Torvalds 	/*
22671da177e4SLinus Torvalds 	 * Shared signal handlers imply shared VM. By way of the above,
22681da177e4SLinus Torvalds 	 * thread groups also imply shared VM. Blocking this case allows
22691da177e4SLinus Torvalds 	 * for various simplifications in other code.
22701da177e4SLinus Torvalds 	 */
22711da177e4SLinus Torvalds 	if ((clone_flags & CLONE_SIGHAND) && !(clone_flags & CLONE_VM))
22721da177e4SLinus Torvalds 		return ERR_PTR(-EINVAL);
22731da177e4SLinus Torvalds 
2274123be07bSSukadev Bhattiprolu 	/*
2275123be07bSSukadev Bhattiprolu 	 * Siblings of global init remain as zombies on exit since they are
2276123be07bSSukadev Bhattiprolu 	 * not reaped by their parent (swapper). To solve this and to avoid
2277123be07bSSukadev Bhattiprolu 	 * multi-rooted process trees, prevent global and container-inits
2278123be07bSSukadev Bhattiprolu 	 * from creating siblings.
2279123be07bSSukadev Bhattiprolu 	 */
2280123be07bSSukadev Bhattiprolu 	if ((clone_flags & CLONE_PARENT) &&
2281123be07bSSukadev Bhattiprolu 				current->signal->flags & SIGNAL_UNKILLABLE)
2282123be07bSSukadev Bhattiprolu 		return ERR_PTR(-EINVAL);
2283123be07bSSukadev Bhattiprolu 
22848382fcacSEric W. Biederman 	/*
228540a0d32dSOleg Nesterov 	 * If the new process will be in a different pid or user namespace
2286faf00da5SEric W. Biederman 	 * do not allow it to share a thread group with the forking task.
22878382fcacSEric W. Biederman 	 */
2288faf00da5SEric W. Biederman 	if (clone_flags & CLONE_THREAD) {
228940a0d32dSOleg Nesterov 		if ((clone_flags & (CLONE_NEWUSER | CLONE_NEWPID)) ||
2290769071acSAndrei Vagin 		    (task_active_pid_ns(current) != nsp->pid_ns_for_children))
2291769071acSAndrei Vagin 			return ERR_PTR(-EINVAL);
2292769071acSAndrei Vagin 	}
2293769071acSAndrei Vagin 
2294b3e58382SChristian Brauner 	if (clone_flags & CLONE_PIDFD) {
2295b3e58382SChristian Brauner 		/*
2296b3e58382SChristian Brauner 		 * - CLONE_DETACHED is blocked so that we can potentially
2297b3e58382SChristian Brauner 		 *   reuse it later for CLONE_PIDFD.
2298b3e58382SChristian Brauner 		 * - CLONE_THREAD is blocked until someone really needs it.
2299b3e58382SChristian Brauner 		 */
23007f192e3cSChristian Brauner 		if (clone_flags & (CLONE_DETACHED | CLONE_THREAD))
2301b3e58382SChristian Brauner 			return ERR_PTR(-EINVAL);
2302b3e58382SChristian Brauner 	}
2303b3e58382SChristian Brauner 
2304c3ad2c3bSEric W. Biederman 	/*
2305c3ad2c3bSEric W. Biederman 	 * Force any signals received before this point to be delivered
2306c3ad2c3bSEric W. Biederman 	 * before the fork happens.  Collect up signals sent to multiple
2307c3ad2c3bSEric W. Biederman 	 * processes that happen during the fork and delay them so that
2308c3ad2c3bSEric W. Biederman 	 * they appear to happen after the fork.
2309c3ad2c3bSEric W. Biederman 	 */
2310c3ad2c3bSEric W. Biederman 	sigemptyset(&delayed.signal);
2311c3ad2c3bSEric W. Biederman 	INIT_HLIST_NODE(&delayed.node);
2312c3ad2c3bSEric W. Biederman 
2313c3ad2c3bSEric W. Biederman 	spin_lock_irq(&current->sighand->siglock);
2314c3ad2c3bSEric W. Biederman 	if (!(clone_flags & CLONE_THREAD))
2315c3ad2c3bSEric W. Biederman 		hlist_add_head(&delayed.node, &current->signal->multiprocess);
2316c3ad2c3bSEric W. Biederman 	recalc_sigpending();
2317c3ad2c3bSEric W. Biederman 	spin_unlock_irq(&current->sighand->siglock);
2318c3ad2c3bSEric W. Biederman 	retval = -ERESTARTNOINTR;
231966ae0d1eSJens Axboe 	if (task_sigpending(current))
2320c3ad2c3bSEric W. Biederman 		goto fork_out;
2321c3ad2c3bSEric W. Biederman 
23221da177e4SLinus Torvalds 	retval = -ENOMEM;
2323725fc629SAndi Kleen 	p = dup_task_struct(current, node);
23241da177e4SLinus Torvalds 	if (!p)
23251da177e4SLinus Torvalds 		goto fork_out;
2326753550ebSEric W. Biederman 	p->flags &= ~PF_KTHREAD;
2327753550ebSEric W. Biederman 	if (args->kthread)
2328753550ebSEric W. Biederman 		p->flags |= PF_KTHREAD;
2329f9010dbdSMike Christie 	if (args->user_worker) {
2330b16b3855SJens Axboe 		/*
2331f9010dbdSMike Christie 		 * Mark us a user worker, and block any signal that isn't
2332b16b3855SJens Axboe 		 * fatal or STOP
2333b16b3855SJens Axboe 		 */
2334f9010dbdSMike Christie 		p->flags |= PF_USER_WORKER;
2335b16b3855SJens Axboe 		siginitsetinv(&p->blocked, sigmask(SIGKILL)|sigmask(SIGSTOP));
2336b16b3855SJens Axboe 	}
2337f9010dbdSMike Christie 	if (args->io_thread)
2338f9010dbdSMike Christie 		p->flags |= PF_IO_WORKER;
23391da177e4SLinus Torvalds 
2340cf587db2SMike Christie 	if (args->name)
2341cf587db2SMike Christie 		strscpy_pad(p->comm, args->name, sizeof(p->comm));
2342cf587db2SMike Christie 
23437f192e3cSChristian Brauner 	p->set_child_tid = (clone_flags & CLONE_CHILD_SETTID) ? args->child_tid : NULL;
23444d6501dcSVegard Nossum 	/*
23454d6501dcSVegard Nossum 	 * Clear TID on mm_release()?
23464d6501dcSVegard Nossum 	 */
23477f192e3cSChristian Brauner 	p->clear_child_tid = (clone_flags & CLONE_CHILD_CLEARTID) ? args->child_tid : NULL;
23484d6501dcSVegard Nossum 
2349f7e8b616SSteven Rostedt 	ftrace_graph_init_task(p);
2350f7e8b616SSteven Rostedt 
2351bea493a0SPeter Zijlstra 	rt_mutex_init_task(p);
2352bea493a0SPeter Zijlstra 
2353a21ee605SPeter Zijlstra 	lockdep_assert_irqs_enabled();
2354d12c1a37SIngo Molnar #ifdef CONFIG_PROVE_LOCKING
2355de30a2b3SIngo Molnar 	DEBUG_LOCKS_WARN_ON(!p->softirqs_enabled);
2356de30a2b3SIngo Molnar #endif
23578f2f9c4dSEric W. Biederman 	retval = copy_creds(p, clone_flags);
23588f2f9c4dSEric W. Biederman 	if (retval < 0)
23598f2f9c4dSEric W. Biederman 		goto bad_fork_free;
23608f2f9c4dSEric W. Biederman 
23611da177e4SLinus Torvalds 	retval = -EAGAIN;
2362de399236SAlexey Gladkov 	if (is_rlimit_overlimit(task_ucounts(p), UCOUNT_RLIMIT_NPROC, rlimit(RLIMIT_NPROC))) {
2363b57922b6SEric Paris 		if (p->real_cred->user != INIT_USER &&
2364b57922b6SEric Paris 		    !capable(CAP_SYS_RESOURCE) && !capable(CAP_SYS_ADMIN))
23658f2f9c4dSEric W. Biederman 			goto bad_fork_cleanup_count;
23661da177e4SLinus Torvalds 	}
236772fa5997SVasiliy Kulikov 	current->flags &= ~PF_NPROC_EXCEEDED;
23681da177e4SLinus Torvalds 
23691da177e4SLinus Torvalds 	/*
23701da177e4SLinus Torvalds 	 * If multiple threads are within copy_process(), then this check
23711da177e4SLinus Torvalds 	 * triggers too late. This doesn't hurt, the check is only there
23721da177e4SLinus Torvalds 	 * to stop root fork bombs.
23731da177e4SLinus Torvalds 	 */
237404ec93feSLi Zefan 	retval = -EAGAIN;
2375c17d1a3aSWeilong Chen 	if (data_race(nr_threads >= max_threads))
23761da177e4SLinus Torvalds 		goto bad_fork_cleanup_count;
23771da177e4SLinus Torvalds 
2378ca74e92bSShailabh Nagar 	delayacct_tsk_init(p);	/* Must remain after dup_task_struct() */
2379a8ea6fc9SFrederic Weisbecker 	p->flags &= ~(PF_SUPERPRIV | PF_WQ_WORKER | PF_IDLE | PF_NO_SETAFFINITY);
2380514ddb44SDavid Rientjes 	p->flags |= PF_FORKNOEXEC;
23811da177e4SLinus Torvalds 	INIT_LIST_HEAD(&p->children);
23821da177e4SLinus Torvalds 	INIT_LIST_HEAD(&p->sibling);
2383f41d911fSPaul E. McKenney 	rcu_copy_process(p);
23841da177e4SLinus Torvalds 	p->vfork_done = NULL;
23851da177e4SLinus Torvalds 	spin_lock_init(&p->alloc_lock);
23861da177e4SLinus Torvalds 
23871da177e4SLinus Torvalds 	init_sigpending(&p->pending);
23881da177e4SLinus Torvalds 
238964861634SMartin Schwidefsky 	p->utime = p->stime = p->gtime = 0;
239040565b5aSStanislaw Gruszka #ifdef CONFIG_ARCH_HAS_SCALED_CPUTIME
239164861634SMartin Schwidefsky 	p->utimescaled = p->stimescaled = 0;
239240565b5aSStanislaw Gruszka #endif
23939d7fb042SPeter Zijlstra 	prev_cputime_init(&p->prev_cputime);
23949d7fb042SPeter Zijlstra 
23956a61671bSFrederic Weisbecker #ifdef CONFIG_VIRT_CPU_ACCOUNTING_GEN
2396bac5b6b6SFrederic Weisbecker 	seqcount_init(&p->vtime.seqcount);
2397bac5b6b6SFrederic Weisbecker 	p->vtime.starttime = 0;
2398bac5b6b6SFrederic Weisbecker 	p->vtime.state = VTIME_INACTIVE;
23996a61671bSFrederic Weisbecker #endif
24006a61671bSFrederic Weisbecker 
24010f212204SJens Axboe #ifdef CONFIG_IO_URING
24020f212204SJens Axboe 	p->io_uring = NULL;
24030f212204SJens Axboe #endif
24040f212204SJens Axboe 
2405a3a2e76cSKAMEZAWA Hiroyuki #if defined(SPLIT_RSS_COUNTING)
2406a3a2e76cSKAMEZAWA Hiroyuki 	memset(&p->rss_stat, 0, sizeof(p->rss_stat));
2407a3a2e76cSKAMEZAWA Hiroyuki #endif
2408172ba844SBalbir Singh 
24096976675dSArjan van de Ven 	p->default_timer_slack_ns = current->timer_slack_ns;
24106976675dSArjan van de Ven 
2411eb414681SJohannes Weiner #ifdef CONFIG_PSI
2412eb414681SJohannes Weiner 	p->psi_flags = 0;
2413eb414681SJohannes Weiner #endif
2414eb414681SJohannes Weiner 
24155995477aSAndrea Righi 	task_io_accounting_init(&p->ioac);
24161da177e4SLinus Torvalds 	acct_clear_integrals(p);
24171da177e4SLinus Torvalds 
24183a245c0fSThomas Gleixner 	posix_cputimers_init(&p->posix_cputimers);
24191da177e4SLinus Torvalds 
24201da177e4SLinus Torvalds 	p->io_context = NULL;
2421c0b0ae8aSRichard Guy Briggs 	audit_set_context(p, NULL);
2422b4f48b63SPaul Menage 	cgroup_fork(p);
2423343f4c49SEric W. Biederman 	if (args->kthread) {
242440966e31SEric W. Biederman 		if (!set_kthread_struct(p))
2425ff8288ffSEric W. Biederman 			goto bad_fork_cleanup_delayacct;
242640966e31SEric W. Biederman 	}
24271da177e4SLinus Torvalds #ifdef CONFIG_NUMA
2428846a16bfSLee Schermerhorn 	p->mempolicy = mpol_dup(p->mempolicy);
24291da177e4SLinus Torvalds 	if (IS_ERR(p->mempolicy)) {
24301da177e4SLinus Torvalds 		retval = PTR_ERR(p->mempolicy);
24311da177e4SLinus Torvalds 		p->mempolicy = NULL;
2432ff8288ffSEric W. Biederman 		goto bad_fork_cleanup_delayacct;
24331da177e4SLinus Torvalds 	}
24341da177e4SLinus Torvalds #endif
2435778d3b0fSMichal Hocko #ifdef CONFIG_CPUSETS
2436778d3b0fSMichal Hocko 	p->cpuset_mem_spread_rotor = NUMA_NO_NODE;
2437778d3b0fSMichal Hocko 	p->cpuset_slab_spread_rotor = NUMA_NO_NODE;
2438b7505861SAhmed S. Darwish 	seqcount_spinlock_init(&p->mems_allowed_seq, &p->alloc_lock);
2439778d3b0fSMichal Hocko #endif
2440de30a2b3SIngo Molnar #ifdef CONFIG_TRACE_IRQFLAGS
24410584df9cSMarco Elver 	memset(&p->irqtrace, 0, sizeof(p->irqtrace));
24420584df9cSMarco Elver 	p->irqtrace.hardirq_disable_ip	= _THIS_IP_;
24430584df9cSMarco Elver 	p->irqtrace.softirq_enable_ip	= _THIS_IP_;
2444de30a2b3SIngo Molnar 	p->softirqs_enabled		= 1;
2445de30a2b3SIngo Molnar 	p->softirq_context		= 0;
2446de30a2b3SIngo Molnar #endif
24478bcbde54SDavid Hildenbrand 
24488bcbde54SDavid Hildenbrand 	p->pagefault_disabled = 0;
24498bcbde54SDavid Hildenbrand 
2450fbb9ce95SIngo Molnar #ifdef CONFIG_LOCKDEP
2451b09be676SByungchul Park 	lockdep_init_task(p);
2452fbb9ce95SIngo Molnar #endif
24531da177e4SLinus Torvalds 
2454408894eeSIngo Molnar #ifdef CONFIG_DEBUG_MUTEXES
2455408894eeSIngo Molnar 	p->blocked_on = NULL; /* not blocked yet */
2456408894eeSIngo Molnar #endif
2457cafe5635SKent Overstreet #ifdef CONFIG_BCACHE
2458cafe5635SKent Overstreet 	p->sequential_io	= 0;
2459cafe5635SKent Overstreet 	p->sequential_io_avg	= 0;
2460cafe5635SKent Overstreet #endif
2461a10787e6SSong Liu #ifdef CONFIG_BPF_SYSCALL
2462a10787e6SSong Liu 	RCU_INIT_POINTER(p->bpf_storage, NULL);
2463c7603cfaSAndrii Nakryiko 	p->bpf_ctx = NULL;
2464a10787e6SSong Liu #endif
24650f481406SMarkus Metzger 
24663c90e6e9SSrivatsa Vaddagiri 	/* Perform scheduler related setup. Assign this task to a CPU. */
2467aab03e05SDario Faggioli 	retval = sched_fork(clone_flags, p);
2468aab03e05SDario Faggioli 	if (retval)
2469aab03e05SDario Faggioli 		goto bad_fork_cleanup_policy;
24706ab423e0SPeter Zijlstra 
24712b26f0aaSMarco Elver 	retval = perf_event_init_task(p, clone_flags);
24726ab423e0SPeter Zijlstra 	if (retval)
24736ab423e0SPeter Zijlstra 		goto bad_fork_cleanup_policy;
2474fb0a685cSDaniel Rebelo de Oliveira 	retval = audit_alloc(p);
2475fb0a685cSDaniel Rebelo de Oliveira 	if (retval)
24766c72e350SPeter Zijlstra 		goto bad_fork_cleanup_perf;
24771da177e4SLinus Torvalds 	/* copy all the process information */
2478ab602f79SJack Miller 	shm_init_task(p);
2479e4e55b47STetsuo Handa 	retval = security_task_alloc(p, clone_flags);
2480fb0a685cSDaniel Rebelo de Oliveira 	if (retval)
24811da177e4SLinus Torvalds 		goto bad_fork_cleanup_audit;
2482e4e55b47STetsuo Handa 	retval = copy_semundo(clone_flags, p);
2483e4e55b47STetsuo Handa 	if (retval)
2484e4e55b47STetsuo Handa 		goto bad_fork_cleanup_security;
248511f3f500SMike Christie 	retval = copy_files(clone_flags, p, args->no_files);
2486fb0a685cSDaniel Rebelo de Oliveira 	if (retval)
24871da177e4SLinus Torvalds 		goto bad_fork_cleanup_semundo;
2488fb0a685cSDaniel Rebelo de Oliveira 	retval = copy_fs(clone_flags, p);
2489fb0a685cSDaniel Rebelo de Oliveira 	if (retval)
24901da177e4SLinus Torvalds 		goto bad_fork_cleanup_files;
2491fb0a685cSDaniel Rebelo de Oliveira 	retval = copy_sighand(clone_flags, p);
2492fb0a685cSDaniel Rebelo de Oliveira 	if (retval)
24931da177e4SLinus Torvalds 		goto bad_fork_cleanup_fs;
2494fb0a685cSDaniel Rebelo de Oliveira 	retval = copy_signal(clone_flags, p);
2495fb0a685cSDaniel Rebelo de Oliveira 	if (retval)
24961da177e4SLinus Torvalds 		goto bad_fork_cleanup_sighand;
2497fb0a685cSDaniel Rebelo de Oliveira 	retval = copy_mm(clone_flags, p);
2498fb0a685cSDaniel Rebelo de Oliveira 	if (retval)
24991da177e4SLinus Torvalds 		goto bad_fork_cleanup_signal;
2500fb0a685cSDaniel Rebelo de Oliveira 	retval = copy_namespaces(clone_flags, p);
2501fb0a685cSDaniel Rebelo de Oliveira 	if (retval)
2502d84f4f99SDavid Howells 		goto bad_fork_cleanup_mm;
2503fb0a685cSDaniel Rebelo de Oliveira 	retval = copy_io(clone_flags, p);
2504fb0a685cSDaniel Rebelo de Oliveira 	if (retval)
2505fd0928dfSJens Axboe 		goto bad_fork_cleanup_namespaces;
2506c5febea0SEric W. Biederman 	retval = copy_thread(p, args);
25071da177e4SLinus Torvalds 	if (retval)
2508fd0928dfSJens Axboe 		goto bad_fork_cleanup_io;
25091da177e4SLinus Torvalds 
2510afaef01cSAlexander Popov 	stackleak_task_init(p);
2511afaef01cSAlexander Popov 
2512425fb2b4SPavel Emelyanov 	if (pid != &init_struct_pid) {
251349cb2fc4SAdrian Reber 		pid = alloc_pid(p->nsproxy->pid_ns_for_children, args->set_tid,
251449cb2fc4SAdrian Reber 				args->set_tid_size);
251535f71bc0SMichal Hocko 		if (IS_ERR(pid)) {
251635f71bc0SMichal Hocko 			retval = PTR_ERR(pid);
25170740aa5fSJiri Slaby 			goto bad_fork_cleanup_thread;
2518425fb2b4SPavel Emelyanov 		}
251935f71bc0SMichal Hocko 	}
2520425fb2b4SPavel Emelyanov 
2521b3e58382SChristian Brauner 	/*
2522b3e58382SChristian Brauner 	 * This has to happen after we've potentially unshared the file
2523b3e58382SChristian Brauner 	 * descriptor table (so that the pidfd doesn't leak into the child
2524b3e58382SChristian Brauner 	 * if the fd table isn't shared).
2525b3e58382SChristian Brauner 	 */
2526b3e58382SChristian Brauner 	if (clone_flags & CLONE_PIDFD) {
2527ca7707f5SChristian Brauner 		/* Note that no task has been attached to @pid yet. */
2528ca7707f5SChristian Brauner 		retval = __pidfd_prepare(pid, O_RDWR | O_CLOEXEC, &pidfile);
2529b3e58382SChristian Brauner 		if (retval < 0)
2530b3e58382SChristian Brauner 			goto bad_fork_free_pid;
2531b3e58382SChristian Brauner 		pidfd = retval;
25326fd2fe49SAl Viro 
25337f192e3cSChristian Brauner 		retval = put_user(pidfd, args->pidfd);
2534b3e58382SChristian Brauner 		if (retval)
2535b3e58382SChristian Brauner 			goto bad_fork_put_pidfd;
2536b3e58382SChristian Brauner 	}
2537b3e58382SChristian Brauner 
253873c10101SJens Axboe #ifdef CONFIG_BLOCK
253973c10101SJens Axboe 	p->plug = NULL;
254073c10101SJens Axboe #endif
2541ba31c1a4SThomas Gleixner 	futex_init_task(p);
2542ba31c1a4SThomas Gleixner 
25431da177e4SLinus Torvalds 	/*
2544f9a3879aSGOTO Masanori 	 * sigaltstack should be cleared when sharing the same VM
2545f9a3879aSGOTO Masanori 	 */
2546f9a3879aSGOTO Masanori 	if ((clone_flags & (CLONE_VM|CLONE_VFORK)) == CLONE_VM)
25472a742138SStas Sergeev 		sas_ss_reset(p);
2548f9a3879aSGOTO Masanori 
2549f9a3879aSGOTO Masanori 	/*
25506580807dSOleg Nesterov 	 * Syscall tracing and stepping should be turned off in the
25516580807dSOleg Nesterov 	 * child regardless of CLONE_PTRACE.
25521da177e4SLinus Torvalds 	 */
25536580807dSOleg Nesterov 	user_disable_single_step(p);
255464c19ba2SGabriel Krisman Bertazi 	clear_task_syscall_work(p, SYSCALL_TRACE);
255564eb35f7SGabriel Krisman Bertazi #if defined(CONFIG_GENERIC_ENTRY) || defined(TIF_SYSCALL_EMU)
255664eb35f7SGabriel Krisman Bertazi 	clear_task_syscall_work(p, SYSCALL_EMU);
2557ed75e8d5SLaurent Vivier #endif
2558e02c9b0dSLin Feng 	clear_tsk_latency_tracing(p);
25591da177e4SLinus Torvalds 
25601da177e4SLinus Torvalds 	/* ok, now we should be set up.. */
256118c830dfSOleg Nesterov 	p->pid = pid_nr(pid);
256218c830dfSOleg Nesterov 	if (clone_flags & CLONE_THREAD) {
256318c830dfSOleg Nesterov 		p->group_leader = current->group_leader;
256418c830dfSOleg Nesterov 		p->tgid = current->tgid;
256518c830dfSOleg Nesterov 	} else {
256618c830dfSOleg Nesterov 		p->group_leader = p;
256718c830dfSOleg Nesterov 		p->tgid = p->pid;
256818c830dfSOleg Nesterov 	}
25695f8aadd8SOleg Nesterov 
25709d823e8fSWu Fengguang 	p->nr_dirtied = 0;
25719d823e8fSWu Fengguang 	p->nr_dirtied_pause = 128 >> (PAGE_SHIFT - 10);
257283712358SWu Fengguang 	p->dirty_paused_when = 0;
25739d823e8fSWu Fengguang 
2574bb8cbbfeSOleg Nesterov 	p->pdeath_signal = 0;
257547e65328SOleg Nesterov 	INIT_LIST_HEAD(&p->thread_group);
2576158e1645SAl Viro 	p->task_works = NULL;
2577ca7752caSMichael Pratt 	clear_posix_cputimers_work(p);
25781da177e4SLinus Torvalds 
2579d741bf41SPeter Zijlstra #ifdef CONFIG_KRETPROBES
2580d741bf41SPeter Zijlstra 	p->kretprobe_instances.first = NULL;
2581d741bf41SPeter Zijlstra #endif
258254ecbe6fSMasami Hiramatsu #ifdef CONFIG_RETHOOK
258354ecbe6fSMasami Hiramatsu 	p->rethooks.first = NULL;
258454ecbe6fSMasami Hiramatsu #endif
2585d741bf41SPeter Zijlstra 
258618c830dfSOleg Nesterov 	/*
25877e47682eSAleksa Sarai 	 * Ensure that the cgroup subsystem policies allow the new process to be
25887b7b8a2cSRandy Dunlap 	 * forked. It should be noted that the new process's css_set can be changed
25897e47682eSAleksa Sarai 	 * between here and cgroup_post_fork() if an organisation operation is in
25907e47682eSAleksa Sarai 	 * progress.
25917e47682eSAleksa Sarai 	 */
2592ef2c41cfSChristian Brauner 	retval = cgroup_can_fork(p, args);
25937e47682eSAleksa Sarai 	if (retval)
25945a5cf5cbSChristian Brauner 		goto bad_fork_put_pidfd;
25957e47682eSAleksa Sarai 
25967e47682eSAleksa Sarai 	/*
2597b1e82065SPeter Zijlstra 	 * Now that the cgroups are pinned, re-clone the parent cgroup and put
2598b1e82065SPeter Zijlstra 	 * the new task on the correct runqueue. All this *before* the task
2599b1e82065SPeter Zijlstra 	 * becomes visible.
2600b1e82065SPeter Zijlstra 	 *
2601b1e82065SPeter Zijlstra 	 * This isn't part of ->can_fork() because while the re-cloning is
2602b1e82065SPeter Zijlstra 	 * cgroup specific, it unconditionally needs to place the task on a
2603b1e82065SPeter Zijlstra 	 * runqueue.
2604b1e82065SPeter Zijlstra 	 */
2605b1e82065SPeter Zijlstra 	sched_cgroup_fork(p, args);
2606b1e82065SPeter Zijlstra 
2607b1e82065SPeter Zijlstra 	/*
26087b558513SDavid Herrmann 	 * From this point on we must avoid any synchronous user-space
26097b558513SDavid Herrmann 	 * communication until we take the tasklist-lock. In particular, we do
26107b558513SDavid Herrmann 	 * not want user-space to be able to predict the process start-time by
26117b558513SDavid Herrmann 	 * stalling fork(2) after we recorded the start_time but before it is
26127b558513SDavid Herrmann 	 * visible to the system.
26137b558513SDavid Herrmann 	 */
26147b558513SDavid Herrmann 
26157b558513SDavid Herrmann 	p->start_time = ktime_get_ns();
2616cf25e24dSPeter Zijlstra 	p->start_boottime = ktime_get_boottime_ns();
26177b558513SDavid Herrmann 
26187b558513SDavid Herrmann 	/*
261918c830dfSOleg Nesterov 	 * Make it visible to the rest of the system, but dont wake it up yet.
262018c830dfSOleg Nesterov 	 * Need tasklist lock for parent etc handling!
262118c830dfSOleg Nesterov 	 */
26221da177e4SLinus Torvalds 	write_lock_irq(&tasklist_lock);
26231da177e4SLinus Torvalds 
26241da177e4SLinus Torvalds 	/* CLONE_PARENT re-uses the old parent */
26252d5516cbSOleg Nesterov 	if (clone_flags & (CLONE_PARENT|CLONE_THREAD)) {
26261da177e4SLinus Torvalds 		p->real_parent = current->real_parent;
26272d5516cbSOleg Nesterov 		p->parent_exec_id = current->parent_exec_id;
2628b4e00444SEddy Wu 		if (clone_flags & CLONE_THREAD)
2629b4e00444SEddy Wu 			p->exit_signal = -1;
2630b4e00444SEddy Wu 		else
2631b4e00444SEddy Wu 			p->exit_signal = current->group_leader->exit_signal;
26322d5516cbSOleg Nesterov 	} else {
26331da177e4SLinus Torvalds 		p->real_parent = current;
26342d5516cbSOleg Nesterov 		p->parent_exec_id = current->self_exec_id;
2635b4e00444SEddy Wu 		p->exit_signal = args->exit_signal;
26362d5516cbSOleg Nesterov 	}
26371da177e4SLinus Torvalds 
2638d83a7cb3SJosh Poimboeuf 	klp_copy_process(p);
2639d83a7cb3SJosh Poimboeuf 
264085dd3f61SPeter Zijlstra 	sched_core_fork(p);
264185dd3f61SPeter Zijlstra 
26421da177e4SLinus Torvalds 	spin_lock(&current->sighand->siglock);
26434a2c7a78SOleg Nesterov 
264479257534SDaniel Bristot de Oliveira 	rv_task_fork(p);
264579257534SDaniel Bristot de Oliveira 
2646d7822b1eSMathieu Desnoyers 	rseq_fork(p, clone_flags);
2647d7822b1eSMathieu Desnoyers 
26484ca1d3eeSEric W. Biederman 	/* Don't start children in a dying pid namespace */
2649e8cfbc24SGargi Sharma 	if (unlikely(!(ns_of_pid(pid)->pid_allocated & PIDNS_ADDING))) {
26503fd37226SKirill Tkhai 		retval = -ENOMEM;
26513fd37226SKirill Tkhai 		goto bad_fork_cancel_cgroup;
26523fd37226SKirill Tkhai 	}
26534a2c7a78SOleg Nesterov 
26547673bf55SEric W. Biederman 	/* Let kill terminate clone/fork in the middle */
26557673bf55SEric W. Biederman 	if (fatal_signal_pending(current)) {
26567673bf55SEric W. Biederman 		retval = -EINTR;
26577673bf55SEric W. Biederman 		goto bad_fork_cancel_cgroup;
26587673bf55SEric W. Biederman 	}
26597673bf55SEric W. Biederman 
2660a1140cb2SKuniyuki Iwashima 	/* No more failure paths after this point. */
2661a1140cb2SKuniyuki Iwashima 
2662a1140cb2SKuniyuki Iwashima 	/*
2663a1140cb2SKuniyuki Iwashima 	 * Copy seccomp details explicitly here, in case they were changed
2664a1140cb2SKuniyuki Iwashima 	 * before holding sighand lock.
2665a1140cb2SKuniyuki Iwashima 	 */
2666a1140cb2SKuniyuki Iwashima 	copy_seccomp(p);
2667a1140cb2SKuniyuki Iwashima 
26682c470475SEric W. Biederman 	init_task_pid_links(p);
266973b9ebfeSOleg Nesterov 	if (likely(p->pid)) {
26704b9d33e6STejun Heo 		ptrace_init_task(p, (clone_flags & CLONE_PTRACE) || trace);
26711da177e4SLinus Torvalds 
267281907739SOleg Nesterov 		init_task_pid(p, PIDTYPE_PID, pid);
26731da177e4SLinus Torvalds 		if (thread_group_leader(p)) {
26746883f81aSEric W. Biederman 			init_task_pid(p, PIDTYPE_TGID, pid);
267581907739SOleg Nesterov 			init_task_pid(p, PIDTYPE_PGID, task_pgrp(current));
267681907739SOleg Nesterov 			init_task_pid(p, PIDTYPE_SID, task_session(current));
267781907739SOleg Nesterov 
26781c4042c2SEric W. Biederman 			if (is_child_reaper(pid)) {
267917cf22c3SEric W. Biederman 				ns_of_pid(pid)->child_reaper = p;
26801c4042c2SEric W. Biederman 				p->signal->flags |= SIGNAL_UNKILLABLE;
26811c4042c2SEric W. Biederman 			}
2682c3ad2c3bSEric W. Biederman 			p->signal->shared_pending.signal = delayed.signal;
26839c9f4dedSAlan Cox 			p->signal->tty = tty_kref_get(current->signal->tty);
2684749860ceSPavel Tikhomirov 			/*
2685749860ceSPavel Tikhomirov 			 * Inherit has_child_subreaper flag under the same
2686749860ceSPavel Tikhomirov 			 * tasklist_lock with adding child to the process tree
2687749860ceSPavel Tikhomirov 			 * for propagate_has_child_subreaper optimization.
2688749860ceSPavel Tikhomirov 			 */
2689749860ceSPavel Tikhomirov 			p->signal->has_child_subreaper = p->real_parent->signal->has_child_subreaper ||
2690749860ceSPavel Tikhomirov 							 p->real_parent->signal->is_child_subreaper;
26919cd80bbbSOleg Nesterov 			list_add_tail(&p->sibling, &p->real_parent->children);
26925e85d4abSEric W. Biederman 			list_add_tail_rcu(&p->tasks, &init_task.tasks);
26936883f81aSEric W. Biederman 			attach_pid(p, PIDTYPE_TGID);
269481907739SOleg Nesterov 			attach_pid(p, PIDTYPE_PGID);
269581907739SOleg Nesterov 			attach_pid(p, PIDTYPE_SID);
2696909ea964SChristoph Lameter 			__this_cpu_inc(process_counts);
269780628ca0SOleg Nesterov 		} else {
269880628ca0SOleg Nesterov 			current->signal->nr_threads++;
2699d80f7d7bSEric W. Biederman 			current->signal->quick_threads++;
270080628ca0SOleg Nesterov 			atomic_inc(&current->signal->live);
270160d4de3fSElena Reshetova 			refcount_inc(&current->signal->sigcnt);
2702924de3b8SEric W. Biederman 			task_join_group_stop(p);
270380628ca0SOleg Nesterov 			list_add_tail_rcu(&p->thread_group,
270480628ca0SOleg Nesterov 					  &p->group_leader->thread_group);
27050c740d0aSOleg Nesterov 			list_add_tail_rcu(&p->thread_node,
27060c740d0aSOleg Nesterov 					  &p->signal->thread_head);
27071da177e4SLinus Torvalds 		}
270881907739SOleg Nesterov 		attach_pid(p, PIDTYPE_PID);
27091da177e4SLinus Torvalds 		nr_threads++;
271073b9ebfeSOleg Nesterov 	}
27111da177e4SLinus Torvalds 	total_forks++;
2712c3ad2c3bSEric W. Biederman 	hlist_del_init(&delayed.node);
27133f17da69SOleg Nesterov 	spin_unlock(&current->sighand->siglock);
27144af4206bSOleg Nesterov 	syscall_tracepoint_update(p);
27151da177e4SLinus Torvalds 	write_unlock_irq(&tasklist_lock);
27164af4206bSOleg Nesterov 
2717ddc204b5SWaiman Long 	if (pidfile)
2718ddc204b5SWaiman Long 		fd_install(pidfd, pidfile);
2719ddc204b5SWaiman Long 
2720c13cf856SAndrew Morton 	proc_fork_connector(p);
2721b1e82065SPeter Zijlstra 	sched_post_fork(p);
2722ef2c41cfSChristian Brauner 	cgroup_post_fork(p, args);
2723cdd6c482SIngo Molnar 	perf_event_fork(p);
272443d2b113SKAMEZAWA Hiroyuki 
272543d2b113SKAMEZAWA Hiroyuki 	trace_task_newtask(p, clone_flags);
27263ab67966SOleg Nesterov 	uprobe_copy_process(p, clone_flags);
2727fd593511SBeau Belgrave 	user_events_fork(p, clone_flags);
272843d2b113SKAMEZAWA Hiroyuki 
272967197a4fSSuren Baghdasaryan 	copy_oom_score_adj(clone_flags, p);
273067197a4fSSuren Baghdasaryan 
27311da177e4SLinus Torvalds 	return p;
27321da177e4SLinus Torvalds 
27337e47682eSAleksa Sarai bad_fork_cancel_cgroup:
273485dd3f61SPeter Zijlstra 	sched_core_free(p);
27353fd37226SKirill Tkhai 	spin_unlock(&current->sighand->siglock);
27363fd37226SKirill Tkhai 	write_unlock_irq(&tasklist_lock);
2737ef2c41cfSChristian Brauner 	cgroup_cancel_fork(p, args);
2738b3e58382SChristian Brauner bad_fork_put_pidfd:
27396fd2fe49SAl Viro 	if (clone_flags & CLONE_PIDFD) {
27406fd2fe49SAl Viro 		fput(pidfile);
27416fd2fe49SAl Viro 		put_unused_fd(pidfd);
27426fd2fe49SAl Viro 	}
2743425fb2b4SPavel Emelyanov bad_fork_free_pid:
2744425fb2b4SPavel Emelyanov 	if (pid != &init_struct_pid)
2745425fb2b4SPavel Emelyanov 		free_pid(pid);
27460740aa5fSJiri Slaby bad_fork_cleanup_thread:
27470740aa5fSJiri Slaby 	exit_thread(p);
2748fd0928dfSJens Axboe bad_fork_cleanup_io:
2749b69f2292SLouis Rilling 	if (p->io_context)
2750b69f2292SLouis Rilling 		exit_io_context(p);
2751ab516013SSerge E. Hallyn bad_fork_cleanup_namespaces:
2752444f378bSLinus Torvalds 	exit_task_namespaces(p);
27531da177e4SLinus Torvalds bad_fork_cleanup_mm:
2754c3f3ce04SAndrea Arcangeli 	if (p->mm) {
2755c3f3ce04SAndrea Arcangeli 		mm_clear_owner(p->mm, p);
27561da177e4SLinus Torvalds 		mmput(p->mm);
2757c3f3ce04SAndrea Arcangeli 	}
27581da177e4SLinus Torvalds bad_fork_cleanup_signal:
27594ab6c083SOleg Nesterov 	if (!(clone_flags & CLONE_THREAD))
27601c5354deSMike Galbraith 		free_signal_struct(p->signal);
27611da177e4SLinus Torvalds bad_fork_cleanup_sighand:
2762a7e5328aSOleg Nesterov 	__cleanup_sighand(p->sighand);
27631da177e4SLinus Torvalds bad_fork_cleanup_fs:
27641da177e4SLinus Torvalds 	exit_fs(p); /* blocking */
27651da177e4SLinus Torvalds bad_fork_cleanup_files:
27661da177e4SLinus Torvalds 	exit_files(p); /* blocking */
27671da177e4SLinus Torvalds bad_fork_cleanup_semundo:
27681da177e4SLinus Torvalds 	exit_sem(p);
2769e4e55b47STetsuo Handa bad_fork_cleanup_security:
2770e4e55b47STetsuo Handa 	security_task_free(p);
27711da177e4SLinus Torvalds bad_fork_cleanup_audit:
27721da177e4SLinus Torvalds 	audit_free(p);
27736c72e350SPeter Zijlstra bad_fork_cleanup_perf:
2774cdd6c482SIngo Molnar 	perf_event_free_task(p);
27756c72e350SPeter Zijlstra bad_fork_cleanup_policy:
2776b09be676SByungchul Park 	lockdep_free_task(p);
27771da177e4SLinus Torvalds #ifdef CONFIG_NUMA
2778f0be3d32SLee Schermerhorn 	mpol_put(p->mempolicy);
27791da177e4SLinus Torvalds #endif
2780ff8288ffSEric W. Biederman bad_fork_cleanup_delayacct:
278135df17c5SShailabh Nagar 	delayacct_tsk_free(p);
27821da177e4SLinus Torvalds bad_fork_cleanup_count:
278321d1c5e3SAlexey Gladkov 	dec_rlimit_ucounts(task_ucounts(p), UCOUNT_RLIMIT_NPROC, 1);
2784e0e81739SDavid Howells 	exit_creds(p);
27851da177e4SLinus Torvalds bad_fork_free:
27862f064a59SPeter Zijlstra 	WRITE_ONCE(p->__state, TASK_DEAD);
27871a03d3f1SSebastian Andrzej Siewior 	exit_task_stack_account(p);
278868f24b08SAndy Lutomirski 	put_task_stack(p);
2789c3f3ce04SAndrea Arcangeli 	delayed_free_task(p);
2790fe7d37d1SOleg Nesterov fork_out:
2791c3ad2c3bSEric W. Biederman 	spin_lock_irq(&current->sighand->siglock);
2792c3ad2c3bSEric W. Biederman 	hlist_del_init(&delayed.node);
2793c3ad2c3bSEric W. Biederman 	spin_unlock_irq(&current->sighand->siglock);
2794fe7d37d1SOleg Nesterov 	return ERR_PTR(retval);
27951da177e4SLinus Torvalds }
27961da177e4SLinus Torvalds 
27972c470475SEric W. Biederman static inline void init_idle_pids(struct task_struct *idle)
2798f106eee1SOleg Nesterov {
2799f106eee1SOleg Nesterov 	enum pid_type type;
2800f106eee1SOleg Nesterov 
2801f106eee1SOleg Nesterov 	for (type = PIDTYPE_PID; type < PIDTYPE_MAX; ++type) {
28022c470475SEric W. Biederman 		INIT_HLIST_NODE(&idle->pid_links[type]); /* not really needed */
28032c470475SEric W. Biederman 		init_task_pid(idle, type, &init_struct_pid);
2804f106eee1SOleg Nesterov 	}
2805f106eee1SOleg Nesterov }
2806f106eee1SOleg Nesterov 
280736cb0e1cSEric W. Biederman static int idle_dummy(void *dummy)
280836cb0e1cSEric W. Biederman {
280936cb0e1cSEric W. Biederman 	/* This function is never called */
281036cb0e1cSEric W. Biederman 	return 0;
281136cb0e1cSEric W. Biederman }
281236cb0e1cSEric W. Biederman 
2813f1a0a376SValentin Schneider struct task_struct * __init fork_idle(int cpu)
28141da177e4SLinus Torvalds {
281536c8b586SIngo Molnar 	struct task_struct *task;
28167f192e3cSChristian Brauner 	struct kernel_clone_args args = {
28177f192e3cSChristian Brauner 		.flags		= CLONE_VM,
28185bd2e97cSEric W. Biederman 		.fn		= &idle_dummy,
28195bd2e97cSEric W. Biederman 		.fn_arg		= NULL,
2820343f4c49SEric W. Biederman 		.kthread	= 1,
282136cb0e1cSEric W. Biederman 		.idle		= 1,
28227f192e3cSChristian Brauner 	};
28237f192e3cSChristian Brauner 
28247f192e3cSChristian Brauner 	task = copy_process(&init_struct_pid, 0, cpu_to_node(cpu), &args);
2825f106eee1SOleg Nesterov 	if (!IS_ERR(task)) {
28262c470475SEric W. Biederman 		init_idle_pids(task);
28271da177e4SLinus Torvalds 		init_idle(task, cpu);
2828f106eee1SOleg Nesterov 	}
282973b9ebfeSOleg Nesterov 
28301da177e4SLinus Torvalds 	return task;
28311da177e4SLinus Torvalds }
28321da177e4SLinus Torvalds 
28331da177e4SLinus Torvalds /*
2834cc440e87SJens Axboe  * This is like kernel_clone(), but shaved down and tailored to just
2835cc440e87SJens Axboe  * creating io_uring workers. It returns a created task, or an error pointer.
2836cc440e87SJens Axboe  * The returned task is inactive, and the caller must fire it up through
2837cc440e87SJens Axboe  * wake_up_new_task(p). All signals are blocked in the created task.
2838cc440e87SJens Axboe  */
2839cc440e87SJens Axboe struct task_struct *create_io_thread(int (*fn)(void *), void *arg, int node)
2840cc440e87SJens Axboe {
2841cc440e87SJens Axboe 	unsigned long flags = CLONE_FS|CLONE_FILES|CLONE_SIGHAND|CLONE_THREAD|
2842cc440e87SJens Axboe 				CLONE_IO;
2843cc440e87SJens Axboe 	struct kernel_clone_args args = {
2844cc440e87SJens Axboe 		.flags		= ((lower_32_bits(flags) | CLONE_VM |
2845cc440e87SJens Axboe 				    CLONE_UNTRACED) & ~CSIGNAL),
2846cc440e87SJens Axboe 		.exit_signal	= (lower_32_bits(flags) & CSIGNAL),
28475bd2e97cSEric W. Biederman 		.fn		= fn,
28485bd2e97cSEric W. Biederman 		.fn_arg		= arg,
2849cc440e87SJens Axboe 		.io_thread	= 1,
285054e6842dSMike Christie 		.user_worker	= 1,
2851cc440e87SJens Axboe 	};
2852cc440e87SJens Axboe 
2853b16b3855SJens Axboe 	return copy_process(NULL, 0, node, &args);
2854cc440e87SJens Axboe }
2855cc440e87SJens Axboe 
2856cc440e87SJens Axboe /*
28571da177e4SLinus Torvalds  *  Ok, this is the main fork-routine.
28581da177e4SLinus Torvalds  *
28591da177e4SLinus Torvalds  * It copies the process, and if successful kick-starts
28601da177e4SLinus Torvalds  * it and waits for it to finish using the VM if required.
2861a0eb9abdSEugene Syromiatnikov  *
2862a0eb9abdSEugene Syromiatnikov  * args->exit_signal is expected to be checked for sanity by the caller.
28631da177e4SLinus Torvalds  */
2864cad6967aSChristian Brauner pid_t kernel_clone(struct kernel_clone_args *args)
28651da177e4SLinus Torvalds {
28667f192e3cSChristian Brauner 	u64 clone_flags = args->flags;
28679f5325aaSMarcos Paulo de Souza 	struct completion vfork;
28689f5325aaSMarcos Paulo de Souza 	struct pid *pid;
28691da177e4SLinus Torvalds 	struct task_struct *p;
28701da177e4SLinus Torvalds 	int trace = 0;
2871cad6967aSChristian Brauner 	pid_t nr;
28721da177e4SLinus Torvalds 
2873bdff746aSAndrew Morton 	/*
28743af8588cSChristian Brauner 	 * For legacy clone() calls, CLONE_PIDFD uses the parent_tid argument
28753af8588cSChristian Brauner 	 * to return the pidfd. Hence, CLONE_PIDFD and CLONE_PARENT_SETTID are
28763af8588cSChristian Brauner 	 * mutually exclusive. With clone3() CLONE_PIDFD has grown a separate
28773af8588cSChristian Brauner 	 * field in struct clone_args and it still doesn't make sense to have
28783af8588cSChristian Brauner 	 * them both point at the same memory location. Performing this check
28793af8588cSChristian Brauner 	 * here has the advantage that we don't need to have a separate helper
28803af8588cSChristian Brauner 	 * to check for legacy clone().
28813af8588cSChristian Brauner 	 */
28823af8588cSChristian Brauner 	if ((args->flags & CLONE_PIDFD) &&
28833af8588cSChristian Brauner 	    (args->flags & CLONE_PARENT_SETTID) &&
28843af8588cSChristian Brauner 	    (args->pidfd == args->parent_tid))
28853af8588cSChristian Brauner 		return -EINVAL;
28863af8588cSChristian Brauner 
28873af8588cSChristian Brauner 	/*
28884b9d33e6STejun Heo 	 * Determine whether and which event to report to ptracer.  When
28894b9d33e6STejun Heo 	 * called from kernel_thread or CLONE_UNTRACED is explicitly
28904b9d33e6STejun Heo 	 * requested, no event is reported; otherwise, report if the event
28914b9d33e6STejun Heo 	 * for the type of forking is enabled.
289209a05394SRoland McGrath 	 */
2893e80d6661SAl Viro 	if (!(clone_flags & CLONE_UNTRACED)) {
28944b9d33e6STejun Heo 		if (clone_flags & CLONE_VFORK)
28954b9d33e6STejun Heo 			trace = PTRACE_EVENT_VFORK;
28967f192e3cSChristian Brauner 		else if (args->exit_signal != SIGCHLD)
28974b9d33e6STejun Heo 			trace = PTRACE_EVENT_CLONE;
28984b9d33e6STejun Heo 		else
28994b9d33e6STejun Heo 			trace = PTRACE_EVENT_FORK;
29004b9d33e6STejun Heo 
29014b9d33e6STejun Heo 		if (likely(!ptrace_event_enabled(current, trace)))
29024b9d33e6STejun Heo 			trace = 0;
29034b9d33e6STejun Heo 	}
29041da177e4SLinus Torvalds 
29057f192e3cSChristian Brauner 	p = copy_process(NULL, trace, NUMA_NO_NODE, args);
290638addce8SEmese Revfy 	add_latent_entropy();
29079f5325aaSMarcos Paulo de Souza 
29089f5325aaSMarcos Paulo de Souza 	if (IS_ERR(p))
29099f5325aaSMarcos Paulo de Souza 		return PTR_ERR(p);
29109f5325aaSMarcos Paulo de Souza 
29111da177e4SLinus Torvalds 	/*
29121da177e4SLinus Torvalds 	 * Do this prior waking up the new thread - the thread pointer
29131da177e4SLinus Torvalds 	 * might get invalid after that point, if the thread exits quickly.
29141da177e4SLinus Torvalds 	 */
29150a16b607SMathieu Desnoyers 	trace_sched_process_fork(current, p);
29160a16b607SMathieu Desnoyers 
29174e52365fSMatthew Dempsky 	pid = get_task_pid(p, PIDTYPE_PID);
29184e52365fSMatthew Dempsky 	nr = pid_vnr(pid);
291930e49c26SPavel Emelyanov 
292030e49c26SPavel Emelyanov 	if (clone_flags & CLONE_PARENT_SETTID)
29217f192e3cSChristian Brauner 		put_user(nr, args->parent_tid);
2922a6f5e063SSukadev Bhattiprolu 
29231da177e4SLinus Torvalds 	if (clone_flags & CLONE_VFORK) {
29241da177e4SLinus Torvalds 		p->vfork_done = &vfork;
29251da177e4SLinus Torvalds 		init_completion(&vfork);
2926d68b46feSOleg Nesterov 		get_task_struct(p);
29271da177e4SLinus Torvalds 	}
29281da177e4SLinus Torvalds 
2929bd74fdaeSYu Zhao 	if (IS_ENABLED(CONFIG_LRU_GEN) && !(clone_flags & CLONE_VM)) {
2930bd74fdaeSYu Zhao 		/* lock the task to synchronize with memcg migration */
2931bd74fdaeSYu Zhao 		task_lock(p);
2932bd74fdaeSYu Zhao 		lru_gen_add_mm(p->mm);
2933bd74fdaeSYu Zhao 		task_unlock(p);
2934bd74fdaeSYu Zhao 	}
2935bd74fdaeSYu Zhao 
29363e51e3edSSamir Bellabes 	wake_up_new_task(p);
29371da177e4SLinus Torvalds 
29384b9d33e6STejun Heo 	/* forking complete and child started to run, tell ptracer */
29394b9d33e6STejun Heo 	if (unlikely(trace))
29404e52365fSMatthew Dempsky 		ptrace_event_pid(trace, pid);
294109a05394SRoland McGrath 
29421da177e4SLinus Torvalds 	if (clone_flags & CLONE_VFORK) {
2943d68b46feSOleg Nesterov 		if (!wait_for_vfork_done(p, &vfork))
29444e52365fSMatthew Dempsky 			ptrace_event_pid(PTRACE_EVENT_VFORK_DONE, pid);
29459f59ce5dSChuck Ebbert 	}
29464e52365fSMatthew Dempsky 
29474e52365fSMatthew Dempsky 	put_pid(pid);
294892476d7fSEric W. Biederman 	return nr;
29491da177e4SLinus Torvalds }
29501da177e4SLinus Torvalds 
29512aa3a7f8SAl Viro /*
29522aa3a7f8SAl Viro  * Create a kernel thread.
29532aa3a7f8SAl Viro  */
2954cf587db2SMike Christie pid_t kernel_thread(int (*fn)(void *), void *arg, const char *name,
2955cf587db2SMike Christie 		    unsigned long flags)
29562aa3a7f8SAl Viro {
29577f192e3cSChristian Brauner 	struct kernel_clone_args args = {
29583f2c788aSChristian Brauner 		.flags		= ((lower_32_bits(flags) | CLONE_VM |
29593f2c788aSChristian Brauner 				    CLONE_UNTRACED) & ~CSIGNAL),
29603f2c788aSChristian Brauner 		.exit_signal	= (lower_32_bits(flags) & CSIGNAL),
29615bd2e97cSEric W. Biederman 		.fn		= fn,
29625bd2e97cSEric W. Biederman 		.fn_arg		= arg,
2963cf587db2SMike Christie 		.name		= name,
2964343f4c49SEric W. Biederman 		.kthread	= 1,
2965343f4c49SEric W. Biederman 	};
2966343f4c49SEric W. Biederman 
2967343f4c49SEric W. Biederman 	return kernel_clone(&args);
2968343f4c49SEric W. Biederman }
2969343f4c49SEric W. Biederman 
2970343f4c49SEric W. Biederman /*
2971343f4c49SEric W. Biederman  * Create a user mode thread.
2972343f4c49SEric W. Biederman  */
2973343f4c49SEric W. Biederman pid_t user_mode_thread(int (*fn)(void *), void *arg, unsigned long flags)
2974343f4c49SEric W. Biederman {
2975343f4c49SEric W. Biederman 	struct kernel_clone_args args = {
2976343f4c49SEric W. Biederman 		.flags		= ((lower_32_bits(flags) | CLONE_VM |
2977343f4c49SEric W. Biederman 				    CLONE_UNTRACED) & ~CSIGNAL),
2978343f4c49SEric W. Biederman 		.exit_signal	= (lower_32_bits(flags) & CSIGNAL),
29795bd2e97cSEric W. Biederman 		.fn		= fn,
29805bd2e97cSEric W. Biederman 		.fn_arg		= arg,
29817f192e3cSChristian Brauner 	};
29827f192e3cSChristian Brauner 
2983cad6967aSChristian Brauner 	return kernel_clone(&args);
29842aa3a7f8SAl Viro }
29852aa3a7f8SAl Viro 
2986d2125043SAl Viro #ifdef __ARCH_WANT_SYS_FORK
2987d2125043SAl Viro SYSCALL_DEFINE0(fork)
2988d2125043SAl Viro {
2989d2125043SAl Viro #ifdef CONFIG_MMU
29907f192e3cSChristian Brauner 	struct kernel_clone_args args = {
29917f192e3cSChristian Brauner 		.exit_signal = SIGCHLD,
29927f192e3cSChristian Brauner 	};
29937f192e3cSChristian Brauner 
2994cad6967aSChristian Brauner 	return kernel_clone(&args);
2995d2125043SAl Viro #else
2996d2125043SAl Viro 	/* can not support in nommu mode */
29975d59e182SDaeseok Youn 	return -EINVAL;
2998d2125043SAl Viro #endif
2999d2125043SAl Viro }
3000d2125043SAl Viro #endif
3001d2125043SAl Viro 
3002d2125043SAl Viro #ifdef __ARCH_WANT_SYS_VFORK
3003d2125043SAl Viro SYSCALL_DEFINE0(vfork)
3004d2125043SAl Viro {
30057f192e3cSChristian Brauner 	struct kernel_clone_args args = {
30067f192e3cSChristian Brauner 		.flags		= CLONE_VFORK | CLONE_VM,
30077f192e3cSChristian Brauner 		.exit_signal	= SIGCHLD,
30087f192e3cSChristian Brauner 	};
30097f192e3cSChristian Brauner 
3010cad6967aSChristian Brauner 	return kernel_clone(&args);
3011d2125043SAl Viro }
3012d2125043SAl Viro #endif
3013d2125043SAl Viro 
3014d2125043SAl Viro #ifdef __ARCH_WANT_SYS_CLONE
3015d2125043SAl Viro #ifdef CONFIG_CLONE_BACKWARDS
3016d2125043SAl Viro SYSCALL_DEFINE5(clone, unsigned long, clone_flags, unsigned long, newsp,
3017d2125043SAl Viro 		 int __user *, parent_tidptr,
30183033f14aSJosh Triplett 		 unsigned long, tls,
3019d2125043SAl Viro 		 int __user *, child_tidptr)
3020d2125043SAl Viro #elif defined(CONFIG_CLONE_BACKWARDS2)
3021d2125043SAl Viro SYSCALL_DEFINE5(clone, unsigned long, newsp, unsigned long, clone_flags,
3022d2125043SAl Viro 		 int __user *, parent_tidptr,
3023d2125043SAl Viro 		 int __user *, child_tidptr,
30243033f14aSJosh Triplett 		 unsigned long, tls)
3025dfa9771aSMichal Simek #elif defined(CONFIG_CLONE_BACKWARDS3)
3026dfa9771aSMichal Simek SYSCALL_DEFINE6(clone, unsigned long, clone_flags, unsigned long, newsp,
3027dfa9771aSMichal Simek 		int, stack_size,
3028dfa9771aSMichal Simek 		int __user *, parent_tidptr,
3029dfa9771aSMichal Simek 		int __user *, child_tidptr,
30303033f14aSJosh Triplett 		unsigned long, tls)
3031d2125043SAl Viro #else
3032d2125043SAl Viro SYSCALL_DEFINE5(clone, unsigned long, clone_flags, unsigned long, newsp,
3033d2125043SAl Viro 		 int __user *, parent_tidptr,
3034d2125043SAl Viro 		 int __user *, child_tidptr,
30353033f14aSJosh Triplett 		 unsigned long, tls)
3036d2125043SAl Viro #endif
3037d2125043SAl Viro {
30387f192e3cSChristian Brauner 	struct kernel_clone_args args = {
30393f2c788aSChristian Brauner 		.flags		= (lower_32_bits(clone_flags) & ~CSIGNAL),
30407f192e3cSChristian Brauner 		.pidfd		= parent_tidptr,
30417f192e3cSChristian Brauner 		.child_tid	= child_tidptr,
30427f192e3cSChristian Brauner 		.parent_tid	= parent_tidptr,
30433f2c788aSChristian Brauner 		.exit_signal	= (lower_32_bits(clone_flags) & CSIGNAL),
30447f192e3cSChristian Brauner 		.stack		= newsp,
30457f192e3cSChristian Brauner 		.tls		= tls,
30467f192e3cSChristian Brauner 	};
30477f192e3cSChristian Brauner 
3048cad6967aSChristian Brauner 	return kernel_clone(&args);
30497f192e3cSChristian Brauner }
3050d68dbb0cSChristian Brauner #endif
30517f192e3cSChristian Brauner 
3052d68dbb0cSChristian Brauner #ifdef __ARCH_WANT_SYS_CLONE3
3053dd499f7aSAmanieu d'Antras 
30547f192e3cSChristian Brauner noinline static int copy_clone_args_from_user(struct kernel_clone_args *kargs,
30557f192e3cSChristian Brauner 					      struct clone_args __user *uargs,
3056f14c234bSAleksa Sarai 					      size_t usize)
30577f192e3cSChristian Brauner {
3058f14c234bSAleksa Sarai 	int err;
30597f192e3cSChristian Brauner 	struct clone_args args;
306049cb2fc4SAdrian Reber 	pid_t *kset_tid = kargs->set_tid;
30617f192e3cSChristian Brauner 
3062a966dcfeSEugene Syromiatnikov 	BUILD_BUG_ON(offsetofend(struct clone_args, tls) !=
3063a966dcfeSEugene Syromiatnikov 		     CLONE_ARGS_SIZE_VER0);
3064a966dcfeSEugene Syromiatnikov 	BUILD_BUG_ON(offsetofend(struct clone_args, set_tid_size) !=
3065a966dcfeSEugene Syromiatnikov 		     CLONE_ARGS_SIZE_VER1);
3066a966dcfeSEugene Syromiatnikov 	BUILD_BUG_ON(offsetofend(struct clone_args, cgroup) !=
3067a966dcfeSEugene Syromiatnikov 		     CLONE_ARGS_SIZE_VER2);
3068a966dcfeSEugene Syromiatnikov 	BUILD_BUG_ON(sizeof(struct clone_args) != CLONE_ARGS_SIZE_VER2);
3069a966dcfeSEugene Syromiatnikov 
3070f14c234bSAleksa Sarai 	if (unlikely(usize > PAGE_SIZE))
30717f192e3cSChristian Brauner 		return -E2BIG;
3072f14c234bSAleksa Sarai 	if (unlikely(usize < CLONE_ARGS_SIZE_VER0))
30737f192e3cSChristian Brauner 		return -EINVAL;
30747f192e3cSChristian Brauner 
3075f14c234bSAleksa Sarai 	err = copy_struct_from_user(&args, sizeof(args), uargs, usize);
3076f14c234bSAleksa Sarai 	if (err)
3077f14c234bSAleksa Sarai 		return err;
30787f192e3cSChristian Brauner 
307949cb2fc4SAdrian Reber 	if (unlikely(args.set_tid_size > MAX_PID_NS_LEVEL))
308049cb2fc4SAdrian Reber 		return -EINVAL;
308149cb2fc4SAdrian Reber 
308249cb2fc4SAdrian Reber 	if (unlikely(!args.set_tid && args.set_tid_size > 0))
308349cb2fc4SAdrian Reber 		return -EINVAL;
308449cb2fc4SAdrian Reber 
308549cb2fc4SAdrian Reber 	if (unlikely(args.set_tid && args.set_tid_size == 0))
308649cb2fc4SAdrian Reber 		return -EINVAL;
308749cb2fc4SAdrian Reber 
3088a0eb9abdSEugene Syromiatnikov 	/*
3089a0eb9abdSEugene Syromiatnikov 	 * Verify that higher 32bits of exit_signal are unset and that
3090a0eb9abdSEugene Syromiatnikov 	 * it is a valid signal
3091a0eb9abdSEugene Syromiatnikov 	 */
3092a0eb9abdSEugene Syromiatnikov 	if (unlikely((args.exit_signal & ~((u64)CSIGNAL)) ||
3093a0eb9abdSEugene Syromiatnikov 		     !valid_signal(args.exit_signal)))
3094a0eb9abdSEugene Syromiatnikov 		return -EINVAL;
3095a0eb9abdSEugene Syromiatnikov 
309662173872SEugene Syromiatnikov 	if ((args.flags & CLONE_INTO_CGROUP) &&
309762173872SEugene Syromiatnikov 	    (args.cgroup > INT_MAX || usize < CLONE_ARGS_SIZE_VER2))
3098ef2c41cfSChristian Brauner 		return -EINVAL;
3099ef2c41cfSChristian Brauner 
31007f192e3cSChristian Brauner 	*kargs = (struct kernel_clone_args){
31017f192e3cSChristian Brauner 		.flags		= args.flags,
31027f192e3cSChristian Brauner 		.pidfd		= u64_to_user_ptr(args.pidfd),
31037f192e3cSChristian Brauner 		.child_tid	= u64_to_user_ptr(args.child_tid),
31047f192e3cSChristian Brauner 		.parent_tid	= u64_to_user_ptr(args.parent_tid),
31057f192e3cSChristian Brauner 		.exit_signal	= args.exit_signal,
31067f192e3cSChristian Brauner 		.stack		= args.stack,
31077f192e3cSChristian Brauner 		.stack_size	= args.stack_size,
31087f192e3cSChristian Brauner 		.tls		= args.tls,
310949cb2fc4SAdrian Reber 		.set_tid_size	= args.set_tid_size,
3110ef2c41cfSChristian Brauner 		.cgroup		= args.cgroup,
31117f192e3cSChristian Brauner 	};
31127f192e3cSChristian Brauner 
311349cb2fc4SAdrian Reber 	if (args.set_tid &&
311449cb2fc4SAdrian Reber 		copy_from_user(kset_tid, u64_to_user_ptr(args.set_tid),
311549cb2fc4SAdrian Reber 			(kargs->set_tid_size * sizeof(pid_t))))
311649cb2fc4SAdrian Reber 		return -EFAULT;
311749cb2fc4SAdrian Reber 
311849cb2fc4SAdrian Reber 	kargs->set_tid = kset_tid;
311949cb2fc4SAdrian Reber 
31207f192e3cSChristian Brauner 	return 0;
31217f192e3cSChristian Brauner }
31227f192e3cSChristian Brauner 
3123fa729c4dSChristian Brauner /**
3124fa729c4dSChristian Brauner  * clone3_stack_valid - check and prepare stack
3125fa729c4dSChristian Brauner  * @kargs: kernel clone args
3126fa729c4dSChristian Brauner  *
3127fa729c4dSChristian Brauner  * Verify that the stack arguments userspace gave us are sane.
3128fa729c4dSChristian Brauner  * In addition, set the stack direction for userspace since it's easy for us to
3129fa729c4dSChristian Brauner  * determine.
3130fa729c4dSChristian Brauner  */
3131fa729c4dSChristian Brauner static inline bool clone3_stack_valid(struct kernel_clone_args *kargs)
3132fa729c4dSChristian Brauner {
3133fa729c4dSChristian Brauner 	if (kargs->stack == 0) {
3134fa729c4dSChristian Brauner 		if (kargs->stack_size > 0)
3135fa729c4dSChristian Brauner 			return false;
3136fa729c4dSChristian Brauner 	} else {
3137fa729c4dSChristian Brauner 		if (kargs->stack_size == 0)
3138fa729c4dSChristian Brauner 			return false;
3139fa729c4dSChristian Brauner 
3140fa729c4dSChristian Brauner 		if (!access_ok((void __user *)kargs->stack, kargs->stack_size))
3141fa729c4dSChristian Brauner 			return false;
3142fa729c4dSChristian Brauner 
3143fa729c4dSChristian Brauner #if !defined(CONFIG_STACK_GROWSUP) && !defined(CONFIG_IA64)
3144fa729c4dSChristian Brauner 		kargs->stack += kargs->stack_size;
3145fa729c4dSChristian Brauner #endif
3146fa729c4dSChristian Brauner 	}
3147fa729c4dSChristian Brauner 
3148fa729c4dSChristian Brauner 	return true;
3149fa729c4dSChristian Brauner }
3150fa729c4dSChristian Brauner 
3151fa729c4dSChristian Brauner static bool clone3_args_valid(struct kernel_clone_args *kargs)
31527f192e3cSChristian Brauner {
3153b612e5dfSChristian Brauner 	/* Verify that no unknown flags are passed along. */
3154ef2c41cfSChristian Brauner 	if (kargs->flags &
3155ef2c41cfSChristian Brauner 	    ~(CLONE_LEGACY_FLAGS | CLONE_CLEAR_SIGHAND | CLONE_INTO_CGROUP))
31567f192e3cSChristian Brauner 		return false;
31577f192e3cSChristian Brauner 
31587f192e3cSChristian Brauner 	/*
3159a8ca6b13SXiaofeng Cao 	 * - make the CLONE_DETACHED bit reusable for clone3
3160a8ca6b13SXiaofeng Cao 	 * - make the CSIGNAL bits reusable for clone3
31617f192e3cSChristian Brauner 	 */
3162a402f1e3STobias Klauser 	if (kargs->flags & (CLONE_DETACHED | (CSIGNAL & (~CLONE_NEWTIME))))
31637f192e3cSChristian Brauner 		return false;
31647f192e3cSChristian Brauner 
3165b612e5dfSChristian Brauner 	if ((kargs->flags & (CLONE_SIGHAND | CLONE_CLEAR_SIGHAND)) ==
3166b612e5dfSChristian Brauner 	    (CLONE_SIGHAND | CLONE_CLEAR_SIGHAND))
3167b612e5dfSChristian Brauner 		return false;
3168b612e5dfSChristian Brauner 
31697f192e3cSChristian Brauner 	if ((kargs->flags & (CLONE_THREAD | CLONE_PARENT)) &&
31707f192e3cSChristian Brauner 	    kargs->exit_signal)
31717f192e3cSChristian Brauner 		return false;
31727f192e3cSChristian Brauner 
3173fa729c4dSChristian Brauner 	if (!clone3_stack_valid(kargs))
3174fa729c4dSChristian Brauner 		return false;
3175fa729c4dSChristian Brauner 
31767f192e3cSChristian Brauner 	return true;
31777f192e3cSChristian Brauner }
31787f192e3cSChristian Brauner 
3179501bd016SChristian Brauner /**
3180501bd016SChristian Brauner  * clone3 - create a new process with specific properties
3181501bd016SChristian Brauner  * @uargs: argument structure
3182501bd016SChristian Brauner  * @size:  size of @uargs
3183501bd016SChristian Brauner  *
3184501bd016SChristian Brauner  * clone3() is the extensible successor to clone()/clone2().
3185501bd016SChristian Brauner  * It takes a struct as argument that is versioned by its size.
3186501bd016SChristian Brauner  *
3187501bd016SChristian Brauner  * Return: On success, a positive PID for the child process.
3188501bd016SChristian Brauner  *         On error, a negative errno number.
3189501bd016SChristian Brauner  */
31907f192e3cSChristian Brauner SYSCALL_DEFINE2(clone3, struct clone_args __user *, uargs, size_t, size)
31917f192e3cSChristian Brauner {
31927f192e3cSChristian Brauner 	int err;
31937f192e3cSChristian Brauner 
31947f192e3cSChristian Brauner 	struct kernel_clone_args kargs;
319549cb2fc4SAdrian Reber 	pid_t set_tid[MAX_PID_NS_LEVEL];
319649cb2fc4SAdrian Reber 
319749cb2fc4SAdrian Reber 	kargs.set_tid = set_tid;
31987f192e3cSChristian Brauner 
31997f192e3cSChristian Brauner 	err = copy_clone_args_from_user(&kargs, uargs, size);
32007f192e3cSChristian Brauner 	if (err)
32017f192e3cSChristian Brauner 		return err;
32027f192e3cSChristian Brauner 
32037f192e3cSChristian Brauner 	if (!clone3_args_valid(&kargs))
32047f192e3cSChristian Brauner 		return -EINVAL;
32057f192e3cSChristian Brauner 
3206cad6967aSChristian Brauner 	return kernel_clone(&kargs);
3207d2125043SAl Viro }
3208d2125043SAl Viro #endif
3209d2125043SAl Viro 
32100f1b92cbSOleg Nesterov void walk_process_tree(struct task_struct *top, proc_visitor visitor, void *data)
32110f1b92cbSOleg Nesterov {
32120f1b92cbSOleg Nesterov 	struct task_struct *leader, *parent, *child;
32130f1b92cbSOleg Nesterov 	int res;
32140f1b92cbSOleg Nesterov 
32150f1b92cbSOleg Nesterov 	read_lock(&tasklist_lock);
32160f1b92cbSOleg Nesterov 	leader = top = top->group_leader;
32170f1b92cbSOleg Nesterov down:
32180f1b92cbSOleg Nesterov 	for_each_thread(leader, parent) {
32190f1b92cbSOleg Nesterov 		list_for_each_entry(child, &parent->children, sibling) {
32200f1b92cbSOleg Nesterov 			res = visitor(child, data);
32210f1b92cbSOleg Nesterov 			if (res) {
32220f1b92cbSOleg Nesterov 				if (res < 0)
32230f1b92cbSOleg Nesterov 					goto out;
32240f1b92cbSOleg Nesterov 				leader = child;
32250f1b92cbSOleg Nesterov 				goto down;
32260f1b92cbSOleg Nesterov 			}
32270f1b92cbSOleg Nesterov up:
32280f1b92cbSOleg Nesterov 			;
32290f1b92cbSOleg Nesterov 		}
32300f1b92cbSOleg Nesterov 	}
32310f1b92cbSOleg Nesterov 
32320f1b92cbSOleg Nesterov 	if (leader != top) {
32330f1b92cbSOleg Nesterov 		child = leader;
32340f1b92cbSOleg Nesterov 		parent = child->real_parent;
32350f1b92cbSOleg Nesterov 		leader = parent->group_leader;
32360f1b92cbSOleg Nesterov 		goto up;
32370f1b92cbSOleg Nesterov 	}
32380f1b92cbSOleg Nesterov out:
32390f1b92cbSOleg Nesterov 	read_unlock(&tasklist_lock);
32400f1b92cbSOleg Nesterov }
32410f1b92cbSOleg Nesterov 
32425fd63b30SRavikiran G Thirumalai #ifndef ARCH_MIN_MMSTRUCT_ALIGN
32435fd63b30SRavikiran G Thirumalai #define ARCH_MIN_MMSTRUCT_ALIGN 0
32445fd63b30SRavikiran G Thirumalai #endif
32455fd63b30SRavikiran G Thirumalai 
324651cc5068SAlexey Dobriyan static void sighand_ctor(void *data)
3247aa1757f9SOleg Nesterov {
3248aa1757f9SOleg Nesterov 	struct sighand_struct *sighand = data;
3249aa1757f9SOleg Nesterov 
3250aa1757f9SOleg Nesterov 	spin_lock_init(&sighand->siglock);
3251b8fceee1SDavide Libenzi 	init_waitqueue_head(&sighand->signalfd_wqh);
3252fba2afaaSDavide Libenzi }
3253aa1757f9SOleg Nesterov 
3254af806027SPeter Zijlstra void __init mm_cache_init(void)
32551da177e4SLinus Torvalds {
3256c1a2f7f0SRik van Riel 	unsigned int mm_size;
3257c1a2f7f0SRik van Riel 
3258af806027SPeter Zijlstra 	/*
3259af806027SPeter Zijlstra 	 * The mm_cpumask is located at the end of mm_struct, and is
3260af806027SPeter Zijlstra 	 * dynamically sized based on the maximum CPU number this system
3261af806027SPeter Zijlstra 	 * can have, taking hotplug into account (nr_cpu_ids).
3262af806027SPeter Zijlstra 	 */
3263af7f588dSMathieu Desnoyers 	mm_size = sizeof(struct mm_struct) + cpumask_size() + mm_cid_size();
3264af806027SPeter Zijlstra 
3265af806027SPeter Zijlstra 	mm_cachep = kmem_cache_create_usercopy("mm_struct",
3266af806027SPeter Zijlstra 			mm_size, ARCH_MIN_MMSTRUCT_ALIGN,
3267af806027SPeter Zijlstra 			SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_ACCOUNT,
3268af806027SPeter Zijlstra 			offsetof(struct mm_struct, saved_auxv),
3269af806027SPeter Zijlstra 			sizeof_field(struct mm_struct, saved_auxv),
3270af806027SPeter Zijlstra 			NULL);
3271af806027SPeter Zijlstra }
3272af806027SPeter Zijlstra 
3273af806027SPeter Zijlstra void __init proc_caches_init(void)
3274af806027SPeter Zijlstra {
32751da177e4SLinus Torvalds 	sighand_cachep = kmem_cache_create("sighand_cache",
32761da177e4SLinus Torvalds 			sizeof(struct sighand_struct), 0,
32775f0d5a3aSPaul E. McKenney 			SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_TYPESAFE_BY_RCU|
327875f296d9SLevin, Alexander (Sasha Levin) 			SLAB_ACCOUNT, sighand_ctor);
32791da177e4SLinus Torvalds 	signal_cachep = kmem_cache_create("signal_cache",
32801da177e4SLinus Torvalds 			sizeof(struct signal_struct), 0,
328175f296d9SLevin, Alexander (Sasha Levin) 			SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_ACCOUNT,
32825d097056SVladimir Davydov 			NULL);
32831da177e4SLinus Torvalds 	files_cachep = kmem_cache_create("files_cache",
32841da177e4SLinus Torvalds 			sizeof(struct files_struct), 0,
328575f296d9SLevin, Alexander (Sasha Levin) 			SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_ACCOUNT,
32865d097056SVladimir Davydov 			NULL);
32871da177e4SLinus Torvalds 	fs_cachep = kmem_cache_create("fs_cache",
32881da177e4SLinus Torvalds 			sizeof(struct fs_struct), 0,
328975f296d9SLevin, Alexander (Sasha Levin) 			SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_ACCOUNT,
32905d097056SVladimir Davydov 			NULL);
3291c1a2f7f0SRik van Riel 
32925d097056SVladimir Davydov 	vm_area_cachep = KMEM_CACHE(vm_area_struct, SLAB_PANIC|SLAB_ACCOUNT);
3293c7f8f31cSSuren Baghdasaryan #ifdef CONFIG_PER_VMA_LOCK
3294c7f8f31cSSuren Baghdasaryan 	vma_lock_cachep = KMEM_CACHE(vma_lock, SLAB_PANIC|SLAB_ACCOUNT);
3295c7f8f31cSSuren Baghdasaryan #endif
32968feae131SDavid Howells 	mmap_init();
329766577193SAl Viro 	nsproxy_cache_init();
32981da177e4SLinus Torvalds }
3299cf2e340fSJANAK DESAI 
3300cf2e340fSJANAK DESAI /*
33019bfb23fcSOleg Nesterov  * Check constraints on flags passed to the unshare system call.
3302cf2e340fSJANAK DESAI  */
33039bfb23fcSOleg Nesterov static int check_unshare_flags(unsigned long unshare_flags)
3304cf2e340fSJANAK DESAI {
33059bfb23fcSOleg Nesterov 	if (unshare_flags & ~(CLONE_THREAD|CLONE_FS|CLONE_NEWNS|CLONE_SIGHAND|
33069bfb23fcSOleg Nesterov 				CLONE_VM|CLONE_FILES|CLONE_SYSVSEM|
330750804fe3SEric W. Biederman 				CLONE_NEWUTS|CLONE_NEWIPC|CLONE_NEWNET|
3308769071acSAndrei Vagin 				CLONE_NEWUSER|CLONE_NEWPID|CLONE_NEWCGROUP|
3309769071acSAndrei Vagin 				CLONE_NEWTIME))
3310cf2e340fSJANAK DESAI 		return -EINVAL;
33119bfb23fcSOleg Nesterov 	/*
331212c641abSEric W. Biederman 	 * Not implemented, but pretend it works if there is nothing
331312c641abSEric W. Biederman 	 * to unshare.  Note that unsharing the address space or the
331412c641abSEric W. Biederman 	 * signal handlers also need to unshare the signal queues (aka
331512c641abSEric W. Biederman 	 * CLONE_THREAD).
33169bfb23fcSOleg Nesterov 	 */
33179bfb23fcSOleg Nesterov 	if (unshare_flags & (CLONE_THREAD | CLONE_SIGHAND | CLONE_VM)) {
331812c641abSEric W. Biederman 		if (!thread_group_empty(current))
331912c641abSEric W. Biederman 			return -EINVAL;
332012c641abSEric W. Biederman 	}
332112c641abSEric W. Biederman 	if (unshare_flags & (CLONE_SIGHAND | CLONE_VM)) {
3322d036bda7SElena Reshetova 		if (refcount_read(&current->sighand->count) > 1)
332312c641abSEric W. Biederman 			return -EINVAL;
332412c641abSEric W. Biederman 	}
332512c641abSEric W. Biederman 	if (unshare_flags & CLONE_VM) {
332612c641abSEric W. Biederman 		if (!current_is_single_threaded())
33279bfb23fcSOleg Nesterov 			return -EINVAL;
33289bfb23fcSOleg Nesterov 	}
3329cf2e340fSJANAK DESAI 
3330cf2e340fSJANAK DESAI 	return 0;
3331cf2e340fSJANAK DESAI }
3332cf2e340fSJANAK DESAI 
3333cf2e340fSJANAK DESAI /*
333499d1419dSJANAK DESAI  * Unshare the filesystem structure if it is being shared
3335cf2e340fSJANAK DESAI  */
3336cf2e340fSJANAK DESAI static int unshare_fs(unsigned long unshare_flags, struct fs_struct **new_fsp)
3337cf2e340fSJANAK DESAI {
3338cf2e340fSJANAK DESAI 	struct fs_struct *fs = current->fs;
3339cf2e340fSJANAK DESAI 
3340498052bbSAl Viro 	if (!(unshare_flags & CLONE_FS) || !fs)
3341498052bbSAl Viro 		return 0;
3342498052bbSAl Viro 
3343498052bbSAl Viro 	/* don't need lock here; in the worst case we'll do useless copy */
3344498052bbSAl Viro 	if (fs->users == 1)
3345498052bbSAl Viro 		return 0;
3346498052bbSAl Viro 
3347498052bbSAl Viro 	*new_fsp = copy_fs_struct(fs);
334899d1419dSJANAK DESAI 	if (!*new_fsp)
334999d1419dSJANAK DESAI 		return -ENOMEM;
3350cf2e340fSJANAK DESAI 
3351cf2e340fSJANAK DESAI 	return 0;
3352cf2e340fSJANAK DESAI }
3353cf2e340fSJANAK DESAI 
3354cf2e340fSJANAK DESAI /*
3355a016f338SJANAK DESAI  * Unshare file descriptor table if it is being shared
3356cf2e340fSJANAK DESAI  */
335760997c3dSChristian Brauner int unshare_fd(unsigned long unshare_flags, unsigned int max_fds,
335860997c3dSChristian Brauner 	       struct files_struct **new_fdp)
3359cf2e340fSJANAK DESAI {
3360cf2e340fSJANAK DESAI 	struct files_struct *fd = current->files;
3361a016f338SJANAK DESAI 	int error = 0;
3362cf2e340fSJANAK DESAI 
3363cf2e340fSJANAK DESAI 	if ((unshare_flags & CLONE_FILES) &&
3364a016f338SJANAK DESAI 	    (fd && atomic_read(&fd->count) > 1)) {
336560997c3dSChristian Brauner 		*new_fdp = dup_fd(fd, max_fds, &error);
3366a016f338SJANAK DESAI 		if (!*new_fdp)
3367a016f338SJANAK DESAI 			return error;
3368a016f338SJANAK DESAI 	}
3369cf2e340fSJANAK DESAI 
3370cf2e340fSJANAK DESAI 	return 0;
3371cf2e340fSJANAK DESAI }
3372cf2e340fSJANAK DESAI 
3373cf2e340fSJANAK DESAI /*
3374cf2e340fSJANAK DESAI  * unshare allows a process to 'unshare' part of the process
3375cf2e340fSJANAK DESAI  * context which was originally shared using clone.  copy_*
3376cad6967aSChristian Brauner  * functions used by kernel_clone() cannot be used here directly
3377cf2e340fSJANAK DESAI  * because they modify an inactive task_struct that is being
3378cf2e340fSJANAK DESAI  * constructed. Here we are modifying the current, active,
3379cf2e340fSJANAK DESAI  * task_struct.
3380cf2e340fSJANAK DESAI  */
33819b32105eSDominik Brodowski int ksys_unshare(unsigned long unshare_flags)
3382cf2e340fSJANAK DESAI {
3383cf2e340fSJANAK DESAI 	struct fs_struct *fs, *new_fs = NULL;
3384ba1f70ddSRan Xiaokai 	struct files_struct *new_fd = NULL;
3385b2e0d987SEric W. Biederman 	struct cred *new_cred = NULL;
3386cf7b708cSPavel Emelyanov 	struct nsproxy *new_nsproxy = NULL;
33879edff4abSManfred Spraul 	int do_sysvsem = 0;
33889bfb23fcSOleg Nesterov 	int err;
3389cf2e340fSJANAK DESAI 
339050804fe3SEric W. Biederman 	/*
3391faf00da5SEric W. Biederman 	 * If unsharing a user namespace must also unshare the thread group
3392faf00da5SEric W. Biederman 	 * and unshare the filesystem root and working directories.
3393b2e0d987SEric W. Biederman 	 */
3394b2e0d987SEric W. Biederman 	if (unshare_flags & CLONE_NEWUSER)
3395e66eded8SEric W. Biederman 		unshare_flags |= CLONE_THREAD | CLONE_FS;
3396b2e0d987SEric W. Biederman 	/*
339750804fe3SEric W. Biederman 	 * If unsharing vm, must also unshare signal handlers.
339850804fe3SEric W. Biederman 	 */
339950804fe3SEric W. Biederman 	if (unshare_flags & CLONE_VM)
340050804fe3SEric W. Biederman 		unshare_flags |= CLONE_SIGHAND;
34016013f67fSManfred Spraul 	/*
340212c641abSEric W. Biederman 	 * If unsharing a signal handlers, must also unshare the signal queues.
340312c641abSEric W. Biederman 	 */
340412c641abSEric W. Biederman 	if (unshare_flags & CLONE_SIGHAND)
340512c641abSEric W. Biederman 		unshare_flags |= CLONE_THREAD;
340612c641abSEric W. Biederman 	/*
34079bfb23fcSOleg Nesterov 	 * If unsharing namespace, must also unshare filesystem information.
34089bfb23fcSOleg Nesterov 	 */
34099bfb23fcSOleg Nesterov 	if (unshare_flags & CLONE_NEWNS)
34109bfb23fcSOleg Nesterov 		unshare_flags |= CLONE_FS;
341150804fe3SEric W. Biederman 
341250804fe3SEric W. Biederman 	err = check_unshare_flags(unshare_flags);
341350804fe3SEric W. Biederman 	if (err)
341450804fe3SEric W. Biederman 		goto bad_unshare_out;
34159bfb23fcSOleg Nesterov 	/*
34166013f67fSManfred Spraul 	 * CLONE_NEWIPC must also detach from the undolist: after switching
34176013f67fSManfred Spraul 	 * to a new ipc namespace, the semaphore arrays from the old
34186013f67fSManfred Spraul 	 * namespace are unreachable.
34196013f67fSManfred Spraul 	 */
34206013f67fSManfred Spraul 	if (unshare_flags & (CLONE_NEWIPC|CLONE_SYSVSEM))
34219edff4abSManfred Spraul 		do_sysvsem = 1;
3422fb0a685cSDaniel Rebelo de Oliveira 	err = unshare_fs(unshare_flags, &new_fs);
3423fb0a685cSDaniel Rebelo de Oliveira 	if (err)
34249bfb23fcSOleg Nesterov 		goto bad_unshare_out;
342560997c3dSChristian Brauner 	err = unshare_fd(unshare_flags, NR_OPEN_MAX, &new_fd);
3426fb0a685cSDaniel Rebelo de Oliveira 	if (err)
34279bfb23fcSOleg Nesterov 		goto bad_unshare_cleanup_fs;
3428b2e0d987SEric W. Biederman 	err = unshare_userns(unshare_flags, &new_cred);
3429fb0a685cSDaniel Rebelo de Oliveira 	if (err)
34309edff4abSManfred Spraul 		goto bad_unshare_cleanup_fd;
3431b2e0d987SEric W. Biederman 	err = unshare_nsproxy_namespaces(unshare_flags, &new_nsproxy,
3432b2e0d987SEric W. Biederman 					 new_cred, new_fs);
3433b2e0d987SEric W. Biederman 	if (err)
3434b2e0d987SEric W. Biederman 		goto bad_unshare_cleanup_cred;
3435cf2e340fSJANAK DESAI 
3436905ae01cSAlexey Gladkov 	if (new_cred) {
3437905ae01cSAlexey Gladkov 		err = set_cred_ucounts(new_cred);
3438905ae01cSAlexey Gladkov 		if (err)
3439905ae01cSAlexey Gladkov 			goto bad_unshare_cleanup_cred;
3440905ae01cSAlexey Gladkov 	}
3441905ae01cSAlexey Gladkov 
3442b2e0d987SEric W. Biederman 	if (new_fs || new_fd || do_sysvsem || new_cred || new_nsproxy) {
34439edff4abSManfred Spraul 		if (do_sysvsem) {
34449edff4abSManfred Spraul 			/*
34459edff4abSManfred Spraul 			 * CLONE_SYSVSEM is equivalent to sys_exit().
34469edff4abSManfred Spraul 			 */
34479edff4abSManfred Spraul 			exit_sem(current);
34489edff4abSManfred Spraul 		}
3449ab602f79SJack Miller 		if (unshare_flags & CLONE_NEWIPC) {
3450ab602f79SJack Miller 			/* Orphan segments in old ns (see sem above). */
3451ab602f79SJack Miller 			exit_shm(current);
3452ab602f79SJack Miller 			shm_init_task(current);
3453ab602f79SJack Miller 		}
3454ab516013SSerge E. Hallyn 
34556f977e6bSAlan Cox 		if (new_nsproxy)
3456cf7b708cSPavel Emelyanov 			switch_task_namespaces(current, new_nsproxy);
3457cf2e340fSJANAK DESAI 
3458cf7b708cSPavel Emelyanov 		task_lock(current);
3459cf7b708cSPavel Emelyanov 
3460cf2e340fSJANAK DESAI 		if (new_fs) {
3461cf2e340fSJANAK DESAI 			fs = current->fs;
34622a4419b5SNick Piggin 			spin_lock(&fs->lock);
3463cf2e340fSJANAK DESAI 			current->fs = new_fs;
3464498052bbSAl Viro 			if (--fs->users)
3465498052bbSAl Viro 				new_fs = NULL;
3466498052bbSAl Viro 			else
3467cf2e340fSJANAK DESAI 				new_fs = fs;
34682a4419b5SNick Piggin 			spin_unlock(&fs->lock);
3469cf2e340fSJANAK DESAI 		}
3470cf2e340fSJANAK DESAI 
3471ba1f70ddSRan Xiaokai 		if (new_fd)
3472ba1f70ddSRan Xiaokai 			swap(current->files, new_fd);
3473cf2e340fSJANAK DESAI 
3474cf2e340fSJANAK DESAI 		task_unlock(current);
3475b2e0d987SEric W. Biederman 
3476b2e0d987SEric W. Biederman 		if (new_cred) {
3477b2e0d987SEric W. Biederman 			/* Install the new user namespace */
3478b2e0d987SEric W. Biederman 			commit_creds(new_cred);
3479b2e0d987SEric W. Biederman 			new_cred = NULL;
3480b2e0d987SEric W. Biederman 		}
3481cf2e340fSJANAK DESAI 	}
3482cf2e340fSJANAK DESAI 
3483e4222673SHari Bathini 	perf_event_namespaces(current);
3484e4222673SHari Bathini 
3485b2e0d987SEric W. Biederman bad_unshare_cleanup_cred:
3486b2e0d987SEric W. Biederman 	if (new_cred)
3487b2e0d987SEric W. Biederman 		put_cred(new_cred);
3488cf2e340fSJANAK DESAI bad_unshare_cleanup_fd:
3489cf2e340fSJANAK DESAI 	if (new_fd)
3490cf2e340fSJANAK DESAI 		put_files_struct(new_fd);
3491cf2e340fSJANAK DESAI 
3492cf2e340fSJANAK DESAI bad_unshare_cleanup_fs:
3493cf2e340fSJANAK DESAI 	if (new_fs)
3494498052bbSAl Viro 		free_fs_struct(new_fs);
3495cf2e340fSJANAK DESAI 
3496cf2e340fSJANAK DESAI bad_unshare_out:
3497cf2e340fSJANAK DESAI 	return err;
3498cf2e340fSJANAK DESAI }
34993b125388SAl Viro 
35009b32105eSDominik Brodowski SYSCALL_DEFINE1(unshare, unsigned long, unshare_flags)
35019b32105eSDominik Brodowski {
35029b32105eSDominik Brodowski 	return ksys_unshare(unshare_flags);
35039b32105eSDominik Brodowski }
35049b32105eSDominik Brodowski 
35053b125388SAl Viro /*
35063b125388SAl Viro  *	Helper to unshare the files of the current task.
35073b125388SAl Viro  *	We don't want to expose copy_files internals to
35083b125388SAl Viro  *	the exec layer of the kernel.
35093b125388SAl Viro  */
35103b125388SAl Viro 
35111f702603SEric W. Biederman int unshare_files(void)
35123b125388SAl Viro {
35133b125388SAl Viro 	struct task_struct *task = current;
35141f702603SEric W. Biederman 	struct files_struct *old, *copy = NULL;
35153b125388SAl Viro 	int error;
35163b125388SAl Viro 
351760997c3dSChristian Brauner 	error = unshare_fd(CLONE_FILES, NR_OPEN_MAX, &copy);
35181f702603SEric W. Biederman 	if (error || !copy)
35193b125388SAl Viro 		return error;
35201f702603SEric W. Biederman 
35211f702603SEric W. Biederman 	old = task->files;
35223b125388SAl Viro 	task_lock(task);
35233b125388SAl Viro 	task->files = copy;
35243b125388SAl Viro 	task_unlock(task);
35251f702603SEric W. Biederman 	put_files_struct(old);
35263b125388SAl Viro 	return 0;
35273b125388SAl Viro }
352816db3d3fSHeinrich Schuchardt 
352916db3d3fSHeinrich Schuchardt int sysctl_max_threads(struct ctl_table *table, int write,
3530b0daa2c7STobias Klauser 		       void *buffer, size_t *lenp, loff_t *ppos)
353116db3d3fSHeinrich Schuchardt {
353216db3d3fSHeinrich Schuchardt 	struct ctl_table t;
353316db3d3fSHeinrich Schuchardt 	int ret;
353416db3d3fSHeinrich Schuchardt 	int threads = max_threads;
3535b0f53dbcSMichal Hocko 	int min = 1;
353616db3d3fSHeinrich Schuchardt 	int max = MAX_THREADS;
353716db3d3fSHeinrich Schuchardt 
353816db3d3fSHeinrich Schuchardt 	t = *table;
353916db3d3fSHeinrich Schuchardt 	t.data = &threads;
354016db3d3fSHeinrich Schuchardt 	t.extra1 = &min;
354116db3d3fSHeinrich Schuchardt 	t.extra2 = &max;
354216db3d3fSHeinrich Schuchardt 
354316db3d3fSHeinrich Schuchardt 	ret = proc_dointvec_minmax(&t, write, buffer, lenp, ppos);
354416db3d3fSHeinrich Schuchardt 	if (ret || !write)
354516db3d3fSHeinrich Schuchardt 		return ret;
354616db3d3fSHeinrich Schuchardt 
3547b0f53dbcSMichal Hocko 	max_threads = threads;
354816db3d3fSHeinrich Schuchardt 
354916db3d3fSHeinrich Schuchardt 	return 0;
355016db3d3fSHeinrich Schuchardt }
3551