xref: /openbmc/linux/kernel/fork.c (revision f2e13784c16a98e269b3111ac02ae44446dd589c)
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>
1001da177e4SLinus Torvalds 
1011da177e4SLinus Torvalds #include <asm/pgalloc.h>
1027c0f6ba6SLinus Torvalds #include <linux/uaccess.h>
1031da177e4SLinus Torvalds #include <asm/mmu_context.h>
1041da177e4SLinus Torvalds #include <asm/cacheflush.h>
1051da177e4SLinus Torvalds #include <asm/tlbflush.h>
1061da177e4SLinus Torvalds 
107ad8d75ffSSteven Rostedt #include <trace/events/sched.h>
108ad8d75ffSSteven Rostedt 
10943d2b113SKAMEZAWA Hiroyuki #define CREATE_TRACE_POINTS
11043d2b113SKAMEZAWA Hiroyuki #include <trace/events/task.h>
11143d2b113SKAMEZAWA Hiroyuki 
1121da177e4SLinus Torvalds /*
113ac1b398dSHeinrich Schuchardt  * Minimum number of threads to boot the kernel
114ac1b398dSHeinrich Schuchardt  */
115ac1b398dSHeinrich Schuchardt #define MIN_THREADS 20
116ac1b398dSHeinrich Schuchardt 
117ac1b398dSHeinrich Schuchardt /*
118ac1b398dSHeinrich Schuchardt  * Maximum number of threads
119ac1b398dSHeinrich Schuchardt  */
120ac1b398dSHeinrich Schuchardt #define MAX_THREADS FUTEX_TID_MASK
121ac1b398dSHeinrich Schuchardt 
122ac1b398dSHeinrich Schuchardt /*
1231da177e4SLinus Torvalds  * Protected counters by write_lock_irq(&tasklist_lock)
1241da177e4SLinus Torvalds  */
1251da177e4SLinus Torvalds unsigned long total_forks;	/* Handle normal Linux uptimes. */
1261da177e4SLinus Torvalds int nr_threads;			/* The idle threads do not count.. */
1271da177e4SLinus Torvalds 
1288856ae4dSKefeng Wang static int max_threads;		/* tunable limit on nr_threads */
1291da177e4SLinus Torvalds 
1308495f7e6SSai Praneeth Prakhya #define NAMED_ARRAY_INDEX(x)	[x] = __stringify(x)
1318495f7e6SSai Praneeth Prakhya 
1328495f7e6SSai Praneeth Prakhya static const char * const resident_page_types[] = {
1338495f7e6SSai Praneeth Prakhya 	NAMED_ARRAY_INDEX(MM_FILEPAGES),
1348495f7e6SSai Praneeth Prakhya 	NAMED_ARRAY_INDEX(MM_ANONPAGES),
1358495f7e6SSai Praneeth Prakhya 	NAMED_ARRAY_INDEX(MM_SWAPENTS),
1368495f7e6SSai Praneeth Prakhya 	NAMED_ARRAY_INDEX(MM_SHMEMPAGES),
1378495f7e6SSai Praneeth Prakhya };
1388495f7e6SSai Praneeth Prakhya 
1391da177e4SLinus Torvalds DEFINE_PER_CPU(unsigned long, process_counts) = 0;
1401da177e4SLinus Torvalds 
1411da177e4SLinus Torvalds __cacheline_aligned DEFINE_RWLOCK(tasklist_lock);  /* outer */
142db1466b3SPaul E. McKenney 
143db1466b3SPaul E. McKenney #ifdef CONFIG_PROVE_RCU
144db1466b3SPaul E. McKenney int lockdep_tasklist_lock_is_held(void)
145db1466b3SPaul E. McKenney {
146db1466b3SPaul E. McKenney 	return lockdep_is_held(&tasklist_lock);
147db1466b3SPaul E. McKenney }
148db1466b3SPaul E. McKenney EXPORT_SYMBOL_GPL(lockdep_tasklist_lock_is_held);
149db1466b3SPaul E. McKenney #endif /* #ifdef CONFIG_PROVE_RCU */
1501da177e4SLinus Torvalds 
1511da177e4SLinus Torvalds int nr_processes(void)
1521da177e4SLinus Torvalds {
1531da177e4SLinus Torvalds 	int cpu;
1541da177e4SLinus Torvalds 	int total = 0;
1551da177e4SLinus Torvalds 
1561d510750SIan Campbell 	for_each_possible_cpu(cpu)
1571da177e4SLinus Torvalds 		total += per_cpu(process_counts, cpu);
1581da177e4SLinus Torvalds 
1591da177e4SLinus Torvalds 	return total;
1601da177e4SLinus Torvalds }
1611da177e4SLinus Torvalds 
162f19b9f74SAkinobu Mita void __weak arch_release_task_struct(struct task_struct *tsk)
163f19b9f74SAkinobu Mita {
164f19b9f74SAkinobu Mita }
165f19b9f74SAkinobu Mita 
166f5e10287SThomas Gleixner #ifndef CONFIG_ARCH_TASK_STRUCT_ALLOCATOR
167e18b890bSChristoph Lameter static struct kmem_cache *task_struct_cachep;
16841101809SThomas Gleixner 
16941101809SThomas Gleixner static inline struct task_struct *alloc_task_struct_node(int node)
17041101809SThomas Gleixner {
17141101809SThomas Gleixner 	return kmem_cache_alloc_node(task_struct_cachep, GFP_KERNEL, node);
17241101809SThomas Gleixner }
17341101809SThomas Gleixner 
17441101809SThomas Gleixner static inline void free_task_struct(struct task_struct *tsk)
17541101809SThomas Gleixner {
17641101809SThomas Gleixner 	kmem_cache_free(task_struct_cachep, tsk);
17741101809SThomas Gleixner }
1781da177e4SLinus Torvalds #endif
1791da177e4SLinus Torvalds 
180b235beeaSLinus Torvalds #ifndef CONFIG_ARCH_THREAD_STACK_ALLOCATOR
18141101809SThomas Gleixner 
1820d15d74aSThomas Gleixner /*
1830d15d74aSThomas Gleixner  * Allocate pages if THREAD_SIZE is >= PAGE_SIZE, otherwise use a
1840d15d74aSThomas Gleixner  * kmemcache based allocator.
1850d15d74aSThomas Gleixner  */
186ba14a194SAndy Lutomirski # if THREAD_SIZE >= PAGE_SIZE || defined(CONFIG_VMAP_STACK)
187ac496bf4SAndy Lutomirski 
188ac496bf4SAndy Lutomirski #  ifdef CONFIG_VMAP_STACK
189ac496bf4SAndy Lutomirski /*
190ac496bf4SAndy Lutomirski  * vmalloc() is a bit slow, and calling vfree() enough times will force a TLB
191ac496bf4SAndy Lutomirski  * flush.  Try to minimize the number of calls by caching stacks.
192ac496bf4SAndy Lutomirski  */
193ac496bf4SAndy Lutomirski #define NR_CACHED_STACKS 2
194ac496bf4SAndy Lutomirski static DEFINE_PER_CPU(struct vm_struct *, cached_stacks[NR_CACHED_STACKS]);
19519659c59SHoeun Ryu 
196e540bf31SSebastian Andrzej Siewior struct vm_stack {
197e540bf31SSebastian Andrzej Siewior 	struct rcu_head rcu;
198e540bf31SSebastian Andrzej Siewior 	struct vm_struct *stack_vm_area;
199e540bf31SSebastian Andrzej Siewior };
200e540bf31SSebastian Andrzej Siewior 
201e540bf31SSebastian Andrzej Siewior static bool try_release_thread_stack_to_cache(struct vm_struct *vm)
202e540bf31SSebastian Andrzej Siewior {
203e540bf31SSebastian Andrzej Siewior 	unsigned int i;
204e540bf31SSebastian Andrzej Siewior 
205e540bf31SSebastian Andrzej Siewior 	for (i = 0; i < NR_CACHED_STACKS; i++) {
206e540bf31SSebastian Andrzej Siewior 		if (this_cpu_cmpxchg(cached_stacks[i], NULL, vm) != NULL)
207e540bf31SSebastian Andrzej Siewior 			continue;
208e540bf31SSebastian Andrzej Siewior 		return true;
209e540bf31SSebastian Andrzej Siewior 	}
210e540bf31SSebastian Andrzej Siewior 	return false;
211e540bf31SSebastian Andrzej Siewior }
212e540bf31SSebastian Andrzej Siewior 
213e540bf31SSebastian Andrzej Siewior static void thread_stack_free_rcu(struct rcu_head *rh)
214e540bf31SSebastian Andrzej Siewior {
215e540bf31SSebastian Andrzej Siewior 	struct vm_stack *vm_stack = container_of(rh, struct vm_stack, rcu);
216e540bf31SSebastian Andrzej Siewior 
217e540bf31SSebastian Andrzej Siewior 	if (try_release_thread_stack_to_cache(vm_stack->stack_vm_area))
218e540bf31SSebastian Andrzej Siewior 		return;
219e540bf31SSebastian Andrzej Siewior 
220e540bf31SSebastian Andrzej Siewior 	vfree(vm_stack);
221e540bf31SSebastian Andrzej Siewior }
222e540bf31SSebastian Andrzej Siewior 
223e540bf31SSebastian Andrzej Siewior static void thread_stack_delayed_free(struct task_struct *tsk)
224e540bf31SSebastian Andrzej Siewior {
225e540bf31SSebastian Andrzej Siewior 	struct vm_stack *vm_stack = tsk->stack;
226e540bf31SSebastian Andrzej Siewior 
227e540bf31SSebastian Andrzej Siewior 	vm_stack->stack_vm_area = tsk->stack_vm_area;
228e540bf31SSebastian Andrzej Siewior 	call_rcu(&vm_stack->rcu, thread_stack_free_rcu);
229e540bf31SSebastian Andrzej Siewior }
230e540bf31SSebastian Andrzej Siewior 
23119659c59SHoeun Ryu static int free_vm_stack_cache(unsigned int cpu)
23219659c59SHoeun Ryu {
23319659c59SHoeun Ryu 	struct vm_struct **cached_vm_stacks = per_cpu_ptr(cached_stacks, cpu);
23419659c59SHoeun Ryu 	int i;
23519659c59SHoeun Ryu 
23619659c59SHoeun Ryu 	for (i = 0; i < NR_CACHED_STACKS; i++) {
23719659c59SHoeun Ryu 		struct vm_struct *vm_stack = cached_vm_stacks[i];
23819659c59SHoeun Ryu 
23919659c59SHoeun Ryu 		if (!vm_stack)
24019659c59SHoeun Ryu 			continue;
24119659c59SHoeun Ryu 
24219659c59SHoeun Ryu 		vfree(vm_stack->addr);
24319659c59SHoeun Ryu 		cached_vm_stacks[i] = NULL;
24419659c59SHoeun Ryu 	}
24519659c59SHoeun Ryu 
24619659c59SHoeun Ryu 	return 0;
24719659c59SHoeun Ryu }
248ac496bf4SAndy Lutomirski 
2491a03d3f1SSebastian Andrzej Siewior static int memcg_charge_kernel_stack(struct vm_struct *vm)
250b69c49b7SFUJITA Tomonori {
251f1c1a9eeSSebastian Andrzej Siewior 	int i;
252f1c1a9eeSSebastian Andrzej Siewior 	int ret;
253f1c1a9eeSSebastian Andrzej Siewior 
254f1c1a9eeSSebastian Andrzej Siewior 	BUILD_BUG_ON(IS_ENABLED(CONFIG_VMAP_STACK) && PAGE_SIZE % 1024 != 0);
255f1c1a9eeSSebastian Andrzej Siewior 	BUG_ON(vm->nr_pages != THREAD_SIZE / PAGE_SIZE);
256f1c1a9eeSSebastian Andrzej Siewior 
257f1c1a9eeSSebastian Andrzej Siewior 	for (i = 0; i < THREAD_SIZE / PAGE_SIZE; i++) {
258f1c1a9eeSSebastian Andrzej Siewior 		ret = memcg_kmem_charge_page(vm->pages[i], GFP_KERNEL, 0);
259f1c1a9eeSSebastian Andrzej Siewior 		if (ret)
260f1c1a9eeSSebastian Andrzej Siewior 			goto err;
261f1c1a9eeSSebastian Andrzej Siewior 	}
262f1c1a9eeSSebastian Andrzej Siewior 	return 0;
263f1c1a9eeSSebastian Andrzej Siewior err:
264f1c1a9eeSSebastian Andrzej Siewior 	/*
265f1c1a9eeSSebastian Andrzej Siewior 	 * If memcg_kmem_charge_page() fails, page's memory cgroup pointer is
266f1c1a9eeSSebastian Andrzej Siewior 	 * NULL, and memcg_kmem_uncharge_page() in free_thread_stack() will
267f1c1a9eeSSebastian Andrzej Siewior 	 * ignore this page.
268f1c1a9eeSSebastian Andrzej Siewior 	 */
269f1c1a9eeSSebastian Andrzej Siewior 	for (i = 0; i < THREAD_SIZE / PAGE_SIZE; i++)
270f1c1a9eeSSebastian Andrzej Siewior 		memcg_kmem_uncharge_page(vm->pages[i], 0);
271f1c1a9eeSSebastian Andrzej Siewior 	return ret;
272f1c1a9eeSSebastian Andrzej Siewior }
273f1c1a9eeSSebastian Andrzej Siewior 
2747865aba3SSebastian Andrzej Siewior static int alloc_thread_stack_node(struct task_struct *tsk, int node)
275b69c49b7SFUJITA Tomonori {
2761a03d3f1SSebastian Andrzej Siewior 	struct vm_struct *vm;
277ac496bf4SAndy Lutomirski 	void *stack;
278ac496bf4SAndy Lutomirski 	int i;
279ac496bf4SAndy Lutomirski 
280ac496bf4SAndy Lutomirski 	for (i = 0; i < NR_CACHED_STACKS; i++) {
281112166f8SChristoph Lameter 		struct vm_struct *s;
282112166f8SChristoph Lameter 
283112166f8SChristoph Lameter 		s = this_cpu_xchg(cached_stacks[i], NULL);
284ac496bf4SAndy Lutomirski 
285ac496bf4SAndy Lutomirski 		if (!s)
286ac496bf4SAndy Lutomirski 			continue;
287ac496bf4SAndy Lutomirski 
28851fb34deSAndrey Konovalov 		/* Reset stack metadata. */
289cebd0eb2SAndrey Konovalov 		kasan_unpoison_range(s->addr, THREAD_SIZE);
290eafb149eSDaniel Axtens 
29151fb34deSAndrey Konovalov 		stack = kasan_reset_tag(s->addr);
29251fb34deSAndrey Konovalov 
293ca182551SKonstantin Khlebnikov 		/* Clear stale pointers from reused stack. */
29451fb34deSAndrey Konovalov 		memset(stack, 0, THREAD_SIZE);
295e01e8063SKees Cook 
2961a03d3f1SSebastian Andrzej Siewior 		if (memcg_charge_kernel_stack(s)) {
297f1c1a9eeSSebastian Andrzej Siewior 			vfree(s->addr);
298f1c1a9eeSSebastian Andrzej Siewior 			return -ENOMEM;
299f1c1a9eeSSebastian Andrzej Siewior 		}
300f1c1a9eeSSebastian Andrzej Siewior 
301ac496bf4SAndy Lutomirski 		tsk->stack_vm_area = s;
30251fb34deSAndrey Konovalov 		tsk->stack = stack;
3037865aba3SSebastian Andrzej Siewior 		return 0;
304ac496bf4SAndy Lutomirski 	}
305ac496bf4SAndy Lutomirski 
3069b6f7e16SRoman Gushchin 	/*
3079b6f7e16SRoman Gushchin 	 * Allocated stacks are cached and later reused by new threads,
3089b6f7e16SRoman Gushchin 	 * so memcg accounting is performed manually on assigning/releasing
3099b6f7e16SRoman Gushchin 	 * stacks to tasks. Drop __GFP_ACCOUNT.
3109b6f7e16SRoman Gushchin 	 */
31148ac3c18SMark Rutland 	stack = __vmalloc_node_range(THREAD_SIZE, THREAD_ALIGN,
312ba14a194SAndy Lutomirski 				     VMALLOC_START, VMALLOC_END,
3139b6f7e16SRoman Gushchin 				     THREADINFO_GFP & ~__GFP_ACCOUNT,
314ba14a194SAndy Lutomirski 				     PAGE_KERNEL,
315ac496bf4SAndy Lutomirski 				     0, node, __builtin_return_address(0));
3167865aba3SSebastian Andrzej Siewior 	if (!stack)
3177865aba3SSebastian Andrzej Siewior 		return -ENOMEM;
318ba14a194SAndy Lutomirski 
3191a03d3f1SSebastian Andrzej Siewior 	vm = find_vm_area(stack);
3201a03d3f1SSebastian Andrzej Siewior 	if (memcg_charge_kernel_stack(vm)) {
321f1c1a9eeSSebastian Andrzej Siewior 		vfree(stack);
322f1c1a9eeSSebastian Andrzej Siewior 		return -ENOMEM;
323f1c1a9eeSSebastian Andrzej Siewior 	}
324ba14a194SAndy Lutomirski 	/*
325ba14a194SAndy Lutomirski 	 * We can't call find_vm_area() in interrupt context, and
326ba14a194SAndy Lutomirski 	 * free_thread_stack() can be called in interrupt context,
327ba14a194SAndy Lutomirski 	 * so cache the vm_struct.
328ba14a194SAndy Lutomirski 	 */
3291a03d3f1SSebastian Andrzej Siewior 	tsk->stack_vm_area = vm;
330c08e6a12SAndrey Konovalov 	stack = kasan_reset_tag(stack);
3315eed6f1dSRik van Riel 	tsk->stack = stack;
3327865aba3SSebastian Andrzej Siewior 	return 0;
3335eed6f1dSRik van Riel }
334be9a2277SSebastian Andrzej Siewior 
335be9a2277SSebastian Andrzej Siewior static void free_thread_stack(struct task_struct *tsk)
336be9a2277SSebastian Andrzej Siewior {
337e540bf31SSebastian Andrzej Siewior 	if (!try_release_thread_stack_to_cache(tsk->stack_vm_area))
338e540bf31SSebastian Andrzej Siewior 		thread_stack_delayed_free(tsk);
339be9a2277SSebastian Andrzej Siewior 
340be9a2277SSebastian Andrzej Siewior 	tsk->stack = NULL;
341be9a2277SSebastian Andrzej Siewior 	tsk->stack_vm_area = NULL;
342be9a2277SSebastian Andrzej Siewior }
343be9a2277SSebastian Andrzej Siewior 
344be9a2277SSebastian Andrzej Siewior #  else /* !CONFIG_VMAP_STACK */
345be9a2277SSebastian Andrzej Siewior 
346e540bf31SSebastian Andrzej Siewior static void thread_stack_free_rcu(struct rcu_head *rh)
347e540bf31SSebastian Andrzej Siewior {
348e540bf31SSebastian Andrzej Siewior 	__free_pages(virt_to_page(rh), THREAD_SIZE_ORDER);
349e540bf31SSebastian Andrzej Siewior }
350e540bf31SSebastian Andrzej Siewior 
351e540bf31SSebastian Andrzej Siewior static void thread_stack_delayed_free(struct task_struct *tsk)
352e540bf31SSebastian Andrzej Siewior {
353e540bf31SSebastian Andrzej Siewior 	struct rcu_head *rh = tsk->stack;
354e540bf31SSebastian Andrzej Siewior 
355e540bf31SSebastian Andrzej Siewior 	call_rcu(rh, thread_stack_free_rcu);
356e540bf31SSebastian Andrzej Siewior }
357e540bf31SSebastian Andrzej Siewior 
3587865aba3SSebastian Andrzej Siewior static int alloc_thread_stack_node(struct task_struct *tsk, int node)
359be9a2277SSebastian Andrzej Siewior {
3604949148aSVladimir Davydov 	struct page *page = alloc_pages_node(node, THREADINFO_GFP,
3612889f608SThomas Gleixner 					     THREAD_SIZE_ORDER);
362b6a84016SEric Dumazet 
3631bf4580eSAndrea Arcangeli 	if (likely(page)) {
3648dcc1d34SAndrey Konovalov 		tsk->stack = kasan_reset_tag(page_address(page));
3657865aba3SSebastian Andrzej Siewior 		return 0;
3661bf4580eSAndrea Arcangeli 	}
3677865aba3SSebastian Andrzej Siewior 	return -ENOMEM;
368b69c49b7SFUJITA Tomonori }
369b69c49b7SFUJITA Tomonori 
370be9a2277SSebastian Andrzej Siewior static void free_thread_stack(struct task_struct *tsk)
371b69c49b7SFUJITA Tomonori {
372e540bf31SSebastian Andrzej Siewior 	thread_stack_delayed_free(tsk);
373be9a2277SSebastian Andrzej Siewior 	tsk->stack = NULL;
374ac496bf4SAndy Lutomirski }
375ac496bf4SAndy Lutomirski 
376be9a2277SSebastian Andrzej Siewior #  endif /* CONFIG_VMAP_STACK */
377be9a2277SSebastian Andrzej Siewior # else /* !(THREAD_SIZE >= PAGE_SIZE || defined(CONFIG_VMAP_STACK)) */
378ac496bf4SAndy Lutomirski 
379b235beeaSLinus Torvalds static struct kmem_cache *thread_stack_cache;
3800d15d74aSThomas Gleixner 
381e540bf31SSebastian Andrzej Siewior static void thread_stack_free_rcu(struct rcu_head *rh)
382e540bf31SSebastian Andrzej Siewior {
383e540bf31SSebastian Andrzej Siewior 	kmem_cache_free(thread_stack_cache, rh);
384e540bf31SSebastian Andrzej Siewior }
385e540bf31SSebastian Andrzej Siewior 
386e540bf31SSebastian Andrzej Siewior static void thread_stack_delayed_free(struct task_struct *tsk)
387e540bf31SSebastian Andrzej Siewior {
388e540bf31SSebastian Andrzej Siewior 	struct rcu_head *rh = tsk->stack;
389e540bf31SSebastian Andrzej Siewior 
390e540bf31SSebastian Andrzej Siewior 	call_rcu(rh, thread_stack_free_rcu);
391e540bf31SSebastian Andrzej Siewior }
392e540bf31SSebastian Andrzej Siewior 
3937865aba3SSebastian Andrzej Siewior static int alloc_thread_stack_node(struct task_struct *tsk, int node)
3940d15d74aSThomas Gleixner {
3955eed6f1dSRik van Riel 	unsigned long *stack;
3965eed6f1dSRik van Riel 	stack = kmem_cache_alloc_node(thread_stack_cache, THREADINFO_GFP, node);
3978dcc1d34SAndrey Konovalov 	stack = kasan_reset_tag(stack);
3985eed6f1dSRik van Riel 	tsk->stack = stack;
3997865aba3SSebastian Andrzej Siewior 	return stack ? 0 : -ENOMEM;
4000d15d74aSThomas Gleixner }
4010d15d74aSThomas Gleixner 
402ba14a194SAndy Lutomirski static void free_thread_stack(struct task_struct *tsk)
4030d15d74aSThomas Gleixner {
404e540bf31SSebastian Andrzej Siewior 	thread_stack_delayed_free(tsk);
405be9a2277SSebastian Andrzej Siewior 	tsk->stack = NULL;
4060d15d74aSThomas Gleixner }
4070d15d74aSThomas Gleixner 
408b235beeaSLinus Torvalds void thread_stack_cache_init(void)
4090d15d74aSThomas Gleixner {
410f9d29946SDavid Windsor 	thread_stack_cache = kmem_cache_create_usercopy("thread_stack",
411f9d29946SDavid Windsor 					THREAD_SIZE, THREAD_SIZE, 0, 0,
412f9d29946SDavid Windsor 					THREAD_SIZE, NULL);
413b235beeaSLinus Torvalds 	BUG_ON(thread_stack_cache == NULL);
4140d15d74aSThomas Gleixner }
415be9a2277SSebastian Andrzej Siewior 
416be9a2277SSebastian Andrzej Siewior # endif /* THREAD_SIZE >= PAGE_SIZE || defined(CONFIG_VMAP_STACK) */
4172bb0529cSSebastian Andrzej Siewior #else /* CONFIG_ARCH_THREAD_STACK_ALLOCATOR */
4182bb0529cSSebastian Andrzej Siewior 
4197865aba3SSebastian Andrzej Siewior static int alloc_thread_stack_node(struct task_struct *tsk, int node)
4202bb0529cSSebastian Andrzej Siewior {
4212bb0529cSSebastian Andrzej Siewior 	unsigned long *stack;
4222bb0529cSSebastian Andrzej Siewior 
4232bb0529cSSebastian Andrzej Siewior 	stack = arch_alloc_thread_stack_node(tsk, node);
4242bb0529cSSebastian Andrzej Siewior 	tsk->stack = stack;
4257865aba3SSebastian Andrzej Siewior 	return stack ? 0 : -ENOMEM;
4262bb0529cSSebastian Andrzej Siewior }
4272bb0529cSSebastian Andrzej Siewior 
4282bb0529cSSebastian Andrzej Siewior static void free_thread_stack(struct task_struct *tsk)
4292bb0529cSSebastian Andrzej Siewior {
4302bb0529cSSebastian Andrzej Siewior 	arch_free_thread_stack(tsk);
4312bb0529cSSebastian Andrzej Siewior 	tsk->stack = NULL;
4322bb0529cSSebastian Andrzej Siewior }
4332bb0529cSSebastian Andrzej Siewior 
434be9a2277SSebastian Andrzej Siewior #endif /* !CONFIG_ARCH_THREAD_STACK_ALLOCATOR */
435b69c49b7SFUJITA Tomonori 
4361da177e4SLinus Torvalds /* SLAB cache for signal_struct structures (tsk->signal) */
437e18b890bSChristoph Lameter static struct kmem_cache *signal_cachep;
4381da177e4SLinus Torvalds 
4391da177e4SLinus Torvalds /* SLAB cache for sighand_struct structures (tsk->sighand) */
440e18b890bSChristoph Lameter struct kmem_cache *sighand_cachep;
4411da177e4SLinus Torvalds 
4421da177e4SLinus Torvalds /* SLAB cache for files_struct structures (tsk->files) */
443e18b890bSChristoph Lameter struct kmem_cache *files_cachep;
4441da177e4SLinus Torvalds 
4451da177e4SLinus Torvalds /* SLAB cache for fs_struct structures (tsk->fs) */
446e18b890bSChristoph Lameter struct kmem_cache *fs_cachep;
4471da177e4SLinus Torvalds 
4481da177e4SLinus Torvalds /* SLAB cache for vm_area_struct structures */
4493928d4f5SLinus Torvalds static struct kmem_cache *vm_area_cachep;
4501da177e4SLinus Torvalds 
4511da177e4SLinus Torvalds /* SLAB cache for mm_struct structures (tsk->mm) */
452e18b890bSChristoph Lameter static struct kmem_cache *mm_cachep;
4531da177e4SLinus Torvalds 
454490fc053SLinus Torvalds struct vm_area_struct *vm_area_alloc(struct mm_struct *mm)
4553928d4f5SLinus Torvalds {
456a670468fSAndrew Morton 	struct vm_area_struct *vma;
457490fc053SLinus Torvalds 
458a670468fSAndrew Morton 	vma = kmem_cache_alloc(vm_area_cachep, GFP_KERNEL);
459027232daSKirill A. Shutemov 	if (vma)
460027232daSKirill A. Shutemov 		vma_init(vma, mm);
461490fc053SLinus Torvalds 	return vma;
4623928d4f5SLinus Torvalds }
4633928d4f5SLinus Torvalds 
4643928d4f5SLinus Torvalds struct vm_area_struct *vm_area_dup(struct vm_area_struct *orig)
4653928d4f5SLinus Torvalds {
46695faf699SLinus Torvalds 	struct vm_area_struct *new = kmem_cache_alloc(vm_area_cachep, GFP_KERNEL);
46795faf699SLinus Torvalds 
46895faf699SLinus Torvalds 	if (new) {
469cda099b3SQian Cai 		ASSERT_EXCLUSIVE_WRITER(orig->vm_flags);
470cda099b3SQian Cai 		ASSERT_EXCLUSIVE_WRITER(orig->vm_file);
471cda099b3SQian Cai 		/*
472cda099b3SQian Cai 		 * orig->shared.rb may be modified concurrently, but the clone
473cda099b3SQian Cai 		 * will be reinitialized.
474cda099b3SQian Cai 		 */
47506e78b61SSuren Baghdasaryan 		data_race(memcpy(new, orig, sizeof(*new)));
47695faf699SLinus Torvalds 		INIT_LIST_HEAD(&new->anon_vma_chain);
4775e31275cSSuren Baghdasaryan 		vma_init_lock(new);
4785c26f6acSSuren Baghdasaryan 		dup_anon_vma_name(orig, new);
47995faf699SLinus Torvalds 	}
48095faf699SLinus Torvalds 	return new;
4813928d4f5SLinus Torvalds }
4823928d4f5SLinus Torvalds 
48320cce633SMichel Lespinasse static void __vm_area_free(struct vm_area_struct *vma)
4843928d4f5SLinus Torvalds {
4855c26f6acSSuren Baghdasaryan 	free_anon_vma_name(vma);
4863928d4f5SLinus Torvalds 	kmem_cache_free(vm_area_cachep, vma);
4873928d4f5SLinus Torvalds }
4883928d4f5SLinus Torvalds 
48920cce633SMichel Lespinasse #ifdef CONFIG_PER_VMA_LOCK
49020cce633SMichel Lespinasse static void vm_area_free_rcu_cb(struct rcu_head *head)
49120cce633SMichel Lespinasse {
49220cce633SMichel Lespinasse 	struct vm_area_struct *vma = container_of(head, struct vm_area_struct,
49320cce633SMichel Lespinasse 						  vm_rcu);
494*f2e13784SSuren Baghdasaryan 
495*f2e13784SSuren Baghdasaryan 	/* The vma should not be locked while being destroyed. */
496*f2e13784SSuren Baghdasaryan 	VM_BUG_ON_VMA(rwsem_is_locked(&vma->lock), vma);
49720cce633SMichel Lespinasse 	__vm_area_free(vma);
49820cce633SMichel Lespinasse }
49920cce633SMichel Lespinasse #endif
50020cce633SMichel Lespinasse 
50120cce633SMichel Lespinasse void vm_area_free(struct vm_area_struct *vma)
50220cce633SMichel Lespinasse {
50320cce633SMichel Lespinasse #ifdef CONFIG_PER_VMA_LOCK
50420cce633SMichel Lespinasse 	call_rcu(&vma->vm_rcu, vm_area_free_rcu_cb);
50520cce633SMichel Lespinasse #else
50620cce633SMichel Lespinasse 	__vm_area_free(vma);
50720cce633SMichel Lespinasse #endif
50820cce633SMichel Lespinasse }
50920cce633SMichel Lespinasse 
510ba14a194SAndy Lutomirski static void account_kernel_stack(struct task_struct *tsk, int account)
511c6a7f572SKOSAKI Motohiro {
5120ce055f8SSebastian Andrzej Siewior 	if (IS_ENABLED(CONFIG_VMAP_STACK)) {
513ba14a194SAndy Lutomirski 		struct vm_struct *vm = task_stack_vm_area(tsk);
51427faca83SMuchun Song 		int i;
515ba14a194SAndy Lutomirski 
51627faca83SMuchun Song 		for (i = 0; i < THREAD_SIZE / PAGE_SIZE; i++)
51727faca83SMuchun Song 			mod_lruvec_page_state(vm->pages[i], NR_KERNEL_STACK_KB,
51827faca83SMuchun Song 					      account * (PAGE_SIZE / 1024));
51927faca83SMuchun Song 	} else {
5200ce055f8SSebastian Andrzej Siewior 		void *stack = task_stack_page(tsk);
5210ce055f8SSebastian Andrzej Siewior 
522991e7673SShakeel Butt 		/* All stack pages are in the same node. */
523da3ceeffSMuchun Song 		mod_lruvec_kmem_state(stack, NR_KERNEL_STACK_KB,
524991e7673SShakeel Butt 				      account * (THREAD_SIZE / 1024));
525ba14a194SAndy Lutomirski 	}
52627faca83SMuchun Song }
527c6a7f572SKOSAKI Motohiro 
5281a03d3f1SSebastian Andrzej Siewior void exit_task_stack_account(struct task_struct *tsk)
5299b6f7e16SRoman Gushchin {
5301a03d3f1SSebastian Andrzej Siewior 	account_kernel_stack(tsk, -1);
5319b6f7e16SRoman Gushchin 
5321a03d3f1SSebastian Andrzej Siewior 	if (IS_ENABLED(CONFIG_VMAP_STACK)) {
5331a03d3f1SSebastian Andrzej Siewior 		struct vm_struct *vm;
5349b6f7e16SRoman Gushchin 		int i;
5359b6f7e16SRoman Gushchin 
5361a03d3f1SSebastian Andrzej Siewior 		vm = task_stack_vm_area(tsk);
5371a03d3f1SSebastian Andrzej Siewior 		for (i = 0; i < THREAD_SIZE / PAGE_SIZE; i++)
5381a03d3f1SSebastian Andrzej Siewior 			memcg_kmem_uncharge_page(vm->pages[i], 0);
5399b6f7e16SRoman Gushchin 	}
5409b6f7e16SRoman Gushchin }
5419b6f7e16SRoman Gushchin 
54268f24b08SAndy Lutomirski static void release_task_stack(struct task_struct *tsk)
5431da177e4SLinus Torvalds {
5442f064a59SPeter Zijlstra 	if (WARN_ON(READ_ONCE(tsk->__state) != TASK_DEAD))
545405c0759SAndy Lutomirski 		return;  /* Better to leak the stack than to free prematurely */
546405c0759SAndy Lutomirski 
547ba14a194SAndy Lutomirski 	free_thread_stack(tsk);
54868f24b08SAndy Lutomirski }
54968f24b08SAndy Lutomirski 
55068f24b08SAndy Lutomirski #ifdef CONFIG_THREAD_INFO_IN_TASK
55168f24b08SAndy Lutomirski void put_task_stack(struct task_struct *tsk)
55268f24b08SAndy Lutomirski {
553f0b89d39SElena Reshetova 	if (refcount_dec_and_test(&tsk->stack_refcount))
55468f24b08SAndy Lutomirski 		release_task_stack(tsk);
55568f24b08SAndy Lutomirski }
55668f24b08SAndy Lutomirski #endif
55768f24b08SAndy Lutomirski 
55868f24b08SAndy Lutomirski void free_task(struct task_struct *tsk)
55968f24b08SAndy Lutomirski {
560a1140cb2SKuniyuki Iwashima #ifdef CONFIG_SECCOMP
561a1140cb2SKuniyuki Iwashima 	WARN_ON_ONCE(tsk->seccomp.filter);
562a1140cb2SKuniyuki Iwashima #endif
563b90ca8baSWill Deacon 	release_user_cpus_ptr(tsk);
564d08b9f0cSSami Tolvanen 	scs_release(tsk);
565d08b9f0cSSami Tolvanen 
56668f24b08SAndy Lutomirski #ifndef CONFIG_THREAD_INFO_IN_TASK
56768f24b08SAndy Lutomirski 	/*
56868f24b08SAndy Lutomirski 	 * The task is finally done with both the stack and thread_info,
56968f24b08SAndy Lutomirski 	 * so free both.
57068f24b08SAndy Lutomirski 	 */
57168f24b08SAndy Lutomirski 	release_task_stack(tsk);
57268f24b08SAndy Lutomirski #else
57368f24b08SAndy Lutomirski 	/*
57468f24b08SAndy Lutomirski 	 * If the task had a separate stack allocation, it should be gone
57568f24b08SAndy Lutomirski 	 * by now.
57668f24b08SAndy Lutomirski 	 */
577f0b89d39SElena Reshetova 	WARN_ON_ONCE(refcount_read(&tsk->stack_refcount) != 0);
57868f24b08SAndy Lutomirski #endif
57923f78d4aSIngo Molnar 	rt_mutex_debug_task_free(tsk);
580fb52607aSFrederic Weisbecker 	ftrace_graph_exit_task(tsk);
581f19b9f74SAkinobu Mita 	arch_release_task_struct(tsk);
5821da5c46fSOleg Nesterov 	if (tsk->flags & PF_KTHREAD)
5831da5c46fSOleg Nesterov 		free_kthread_struct(tsk);
5841da177e4SLinus Torvalds 	free_task_struct(tsk);
5851da177e4SLinus Torvalds }
5861da177e4SLinus Torvalds EXPORT_SYMBOL(free_task);
5871da177e4SLinus Torvalds 
588fe69d560SDavid Hildenbrand static void dup_mm_exe_file(struct mm_struct *mm, struct mm_struct *oldmm)
589fe69d560SDavid Hildenbrand {
590fe69d560SDavid Hildenbrand 	struct file *exe_file;
591fe69d560SDavid Hildenbrand 
592fe69d560SDavid Hildenbrand 	exe_file = get_mm_exe_file(oldmm);
593fe69d560SDavid Hildenbrand 	RCU_INIT_POINTER(mm->exe_file, exe_file);
594fe69d560SDavid Hildenbrand 	/*
595fe69d560SDavid Hildenbrand 	 * We depend on the oldmm having properly denied write access to the
596fe69d560SDavid Hildenbrand 	 * exe_file already.
597fe69d560SDavid Hildenbrand 	 */
598fe69d560SDavid Hildenbrand 	if (exe_file && deny_write_access(exe_file))
599fe69d560SDavid Hildenbrand 		pr_warn_once("deny_write_access() failed in %s\n", __func__);
600fe69d560SDavid Hildenbrand }
601fe69d560SDavid Hildenbrand 
6021da177e4SLinus Torvalds #ifdef CONFIG_MMU
6030766f788SEmese Revfy static __latent_entropy int dup_mmap(struct mm_struct *mm,
6040766f788SEmese Revfy 					struct mm_struct *oldmm)
6051da177e4SLinus Torvalds {
606763ecb03SLiam R. Howlett 	struct vm_area_struct *mpnt, *tmp;
6071da177e4SLinus Torvalds 	int retval;
608c9dbe82cSLiam R. Howlett 	unsigned long charge = 0;
609893e26e6SPavel Emelyanov 	LIST_HEAD(uf);
6103b9dbd5eSLiam R. Howlett 	VMA_ITERATOR(old_vmi, oldmm, 0);
6113b9dbd5eSLiam R. Howlett 	VMA_ITERATOR(vmi, mm, 0);
6121da177e4SLinus Torvalds 
61332cdba1eSOleg Nesterov 	uprobe_start_dup_mmap();
614d8ed45c5SMichel Lespinasse 	if (mmap_write_lock_killable(oldmm)) {
6157c051267SMichal Hocko 		retval = -EINTR;
6167c051267SMichal Hocko 		goto fail_uprobe_end;
6177c051267SMichal Hocko 	}
618ec8c0446SRalf Baechle 	flush_cache_dup_mm(oldmm);
619f8ac4ec9SOleg Nesterov 	uprobe_dup_mmap(oldmm, mm);
620ad339451SIngo Molnar 	/*
621ad339451SIngo Molnar 	 * Not linked in yet - no deadlock potential:
622ad339451SIngo Molnar 	 */
623aaa2cc56SMichel Lespinasse 	mmap_write_lock_nested(mm, SINGLE_DEPTH_NESTING);
6247ee78232SHugh Dickins 
62590f31d0eSKonstantin Khlebnikov 	/* No ordering required: file already has been exposed. */
626fe69d560SDavid Hildenbrand 	dup_mm_exe_file(mm, oldmm);
62790f31d0eSKonstantin Khlebnikov 
6284f7d4614SVladimir Davydov 	mm->total_vm = oldmm->total_vm;
62984638335SKonstantin Khlebnikov 	mm->data_vm = oldmm->data_vm;
6304f7d4614SVladimir Davydov 	mm->exec_vm = oldmm->exec_vm;
6314f7d4614SVladimir Davydov 	mm->stack_vm = oldmm->stack_vm;
6324f7d4614SVladimir Davydov 
633f8af4da3SHugh Dickins 	retval = ksm_fork(mm, oldmm);
634f8af4da3SHugh Dickins 	if (retval)
635f8af4da3SHugh Dickins 		goto out;
636d2081b2bSYang Shi 	khugepaged_fork(mm, oldmm);
6371da177e4SLinus Torvalds 
6383b9dbd5eSLiam R. Howlett 	retval = vma_iter_bulk_alloc(&vmi, oldmm->map_count);
639d4af56c5SLiam R. Howlett 	if (retval)
640d4af56c5SLiam R. Howlett 		goto out;
641d4af56c5SLiam R. Howlett 
6423b9dbd5eSLiam R. Howlett 	for_each_vma(old_vmi, mpnt) {
6431da177e4SLinus Torvalds 		struct file *file;
6441da177e4SLinus Torvalds 
6451da177e4SLinus Torvalds 		if (mpnt->vm_flags & VM_DONTCOPY) {
64684638335SKonstantin Khlebnikov 			vm_stat_account(mm, mpnt->vm_flags, -vma_pages(mpnt));
6471da177e4SLinus Torvalds 			continue;
6481da177e4SLinus Torvalds 		}
6491da177e4SLinus Torvalds 		charge = 0;
650655c79bbSTetsuo Handa 		/*
651655c79bbSTetsuo Handa 		 * Don't duplicate many vmas if we've been oom-killed (for
652655c79bbSTetsuo Handa 		 * example)
653655c79bbSTetsuo Handa 		 */
654655c79bbSTetsuo Handa 		if (fatal_signal_pending(current)) {
655655c79bbSTetsuo Handa 			retval = -EINTR;
656d4af56c5SLiam R. Howlett 			goto loop_out;
657655c79bbSTetsuo Handa 		}
6581da177e4SLinus Torvalds 		if (mpnt->vm_flags & VM_ACCOUNT) {
659b2412b7fSHuang Shijie 			unsigned long len = vma_pages(mpnt);
660b2412b7fSHuang Shijie 
661191c5424SAl Viro 			if (security_vm_enough_memory_mm(oldmm, len)) /* sic */
6621da177e4SLinus Torvalds 				goto fail_nomem;
6631da177e4SLinus Torvalds 			charge = len;
6641da177e4SLinus Torvalds 		}
6653928d4f5SLinus Torvalds 		tmp = vm_area_dup(mpnt);
6661da177e4SLinus Torvalds 		if (!tmp)
6671da177e4SLinus Torvalds 			goto fail_nomem;
668ef0855d3SOleg Nesterov 		retval = vma_dup_policy(mpnt, tmp);
669ef0855d3SOleg Nesterov 		if (retval)
6701da177e4SLinus Torvalds 			goto fail_nomem_policy;
671a247c3a9SAndrea Arcangeli 		tmp->vm_mm = mm;
672893e26e6SPavel Emelyanov 		retval = dup_userfaultfd(tmp, &uf);
673893e26e6SPavel Emelyanov 		if (retval)
674893e26e6SPavel Emelyanov 			goto fail_nomem_anon_vma_fork;
675d2cd9edeSRik van Riel 		if (tmp->vm_flags & VM_WIPEONFORK) {
67693949bb2SLi Xinhai 			/*
67793949bb2SLi Xinhai 			 * VM_WIPEONFORK gets a clean slate in the child.
67893949bb2SLi Xinhai 			 * Don't prepare anon_vma until fault since we don't
67993949bb2SLi Xinhai 			 * copy page for current vma.
68093949bb2SLi Xinhai 			 */
681d2cd9edeSRik van Riel 			tmp->anon_vma = NULL;
682d2cd9edeSRik van Riel 		} else if (anon_vma_fork(tmp, mpnt))
6835beb4930SRik van Riel 			goto fail_nomem_anon_vma_fork;
684e430a95aSSuren Baghdasaryan 		vm_flags_clear(tmp, VM_LOCKED_MASK);
6851da177e4SLinus Torvalds 		file = tmp->vm_file;
6861da177e4SLinus Torvalds 		if (file) {
687b88ed205SHugh Dickins 			struct address_space *mapping = file->f_mapping;
688b88ed205SHugh Dickins 
6891da177e4SLinus Torvalds 			get_file(file);
69083cde9e8SDavidlohr Bueso 			i_mmap_lock_write(mapping);
691b88ed205SHugh Dickins 			if (tmp->vm_flags & VM_SHARED)
692cf508b58SMiaohe Lin 				mapping_allow_writable(mapping);
693b88ed205SHugh Dickins 			flush_dcache_mmap_lock(mapping);
694b88ed205SHugh Dickins 			/* insert tmp into the share list, just after mpnt */
6959826a516SMichel Lespinasse 			vma_interval_tree_insert_after(tmp, mpnt,
6969826a516SMichel Lespinasse 					&mapping->i_mmap);
697b88ed205SHugh Dickins 			flush_dcache_mmap_unlock(mapping);
69883cde9e8SDavidlohr Bueso 			i_mmap_unlock_write(mapping);
6991da177e4SLinus Torvalds 		}
7001da177e4SLinus Torvalds 
7011da177e4SLinus Torvalds 		/*
7028d9bfb26SMike Kravetz 		 * Copy/update hugetlb private vma information.
703a1e78772SMel Gorman 		 */
704a1e78772SMel Gorman 		if (is_vm_hugetlb_page(tmp))
7058d9bfb26SMike Kravetz 			hugetlb_dup_vma_private(tmp);
706a1e78772SMel Gorman 
707d4af56c5SLiam R. Howlett 		/* Link the vma into the MT */
7083b9dbd5eSLiam R. Howlett 		if (vma_iter_bulk_store(&vmi, tmp))
7093b9dbd5eSLiam R. Howlett 			goto fail_nomem_vmi_store;
7101da177e4SLinus Torvalds 
7111da177e4SLinus Torvalds 		mm->map_count++;
712d2cd9edeSRik van Riel 		if (!(tmp->vm_flags & VM_WIPEONFORK))
713c78f4636SPeter Xu 			retval = copy_page_range(tmp, mpnt);
7141da177e4SLinus Torvalds 
7151da177e4SLinus Torvalds 		if (tmp->vm_ops && tmp->vm_ops->open)
7161da177e4SLinus Torvalds 			tmp->vm_ops->open(tmp);
7171da177e4SLinus Torvalds 
7181da177e4SLinus Torvalds 		if (retval)
719d4af56c5SLiam R. Howlett 			goto loop_out;
7201da177e4SLinus Torvalds 	}
721d6dd61c8SJeremy Fitzhardinge 	/* a new mm has just been created */
7221ed0cc5aSNadav Amit 	retval = arch_dup_mmap(oldmm, mm);
723d4af56c5SLiam R. Howlett loop_out:
7243b9dbd5eSLiam R. Howlett 	vma_iter_free(&vmi);
7251da177e4SLinus Torvalds out:
726d8ed45c5SMichel Lespinasse 	mmap_write_unlock(mm);
727fd3e42fcSHugh Dickins 	flush_tlb_mm(oldmm);
728d8ed45c5SMichel Lespinasse 	mmap_write_unlock(oldmm);
729893e26e6SPavel Emelyanov 	dup_userfaultfd_complete(&uf);
7307c051267SMichal Hocko fail_uprobe_end:
73132cdba1eSOleg Nesterov 	uprobe_end_dup_mmap();
7321da177e4SLinus Torvalds 	return retval;
733c9dbe82cSLiam R. Howlett 
7343b9dbd5eSLiam R. Howlett fail_nomem_vmi_store:
735c9dbe82cSLiam R. Howlett 	unlink_anon_vmas(tmp);
7365beb4930SRik van Riel fail_nomem_anon_vma_fork:
737ef0855d3SOleg Nesterov 	mpol_put(vma_policy(tmp));
7381da177e4SLinus Torvalds fail_nomem_policy:
7393928d4f5SLinus Torvalds 	vm_area_free(tmp);
7401da177e4SLinus Torvalds fail_nomem:
7411da177e4SLinus Torvalds 	retval = -ENOMEM;
7421da177e4SLinus Torvalds 	vm_unacct_memory(charge);
743d4af56c5SLiam R. Howlett 	goto loop_out;
7441da177e4SLinus Torvalds }
7451da177e4SLinus Torvalds 
7461da177e4SLinus Torvalds static inline int mm_alloc_pgd(struct mm_struct *mm)
7471da177e4SLinus Torvalds {
7481da177e4SLinus Torvalds 	mm->pgd = pgd_alloc(mm);
7491da177e4SLinus Torvalds 	if (unlikely(!mm->pgd))
7501da177e4SLinus Torvalds 		return -ENOMEM;
7511da177e4SLinus Torvalds 	return 0;
7521da177e4SLinus Torvalds }
7531da177e4SLinus Torvalds 
7541da177e4SLinus Torvalds static inline void mm_free_pgd(struct mm_struct *mm)
7551da177e4SLinus Torvalds {
7565e541973SBenjamin Herrenschmidt 	pgd_free(mm, mm->pgd);
7571da177e4SLinus Torvalds }
7581da177e4SLinus Torvalds #else
75990f31d0eSKonstantin Khlebnikov static int dup_mmap(struct mm_struct *mm, struct mm_struct *oldmm)
76090f31d0eSKonstantin Khlebnikov {
761d8ed45c5SMichel Lespinasse 	mmap_write_lock(oldmm);
762fe69d560SDavid Hildenbrand 	dup_mm_exe_file(mm, oldmm);
763d8ed45c5SMichel Lespinasse 	mmap_write_unlock(oldmm);
76490f31d0eSKonstantin Khlebnikov 	return 0;
76590f31d0eSKonstantin Khlebnikov }
7661da177e4SLinus Torvalds #define mm_alloc_pgd(mm)	(0)
7671da177e4SLinus Torvalds #define mm_free_pgd(mm)
7681da177e4SLinus Torvalds #endif /* CONFIG_MMU */
7691da177e4SLinus Torvalds 
770d70f2a14SAndrew Morton static void check_mm(struct mm_struct *mm)
771d70f2a14SAndrew Morton {
772d70f2a14SAndrew Morton 	int i;
773d70f2a14SAndrew Morton 
7748495f7e6SSai Praneeth Prakhya 	BUILD_BUG_ON_MSG(ARRAY_SIZE(resident_page_types) != NR_MM_COUNTERS,
7758495f7e6SSai Praneeth Prakhya 			 "Please make sure 'struct resident_page_types[]' is updated as well");
7768495f7e6SSai Praneeth Prakhya 
777d70f2a14SAndrew Morton 	for (i = 0; i < NR_MM_COUNTERS; i++) {
778f1a79412SShakeel Butt 		long x = percpu_counter_sum(&mm->rss_stat[i]);
779d70f2a14SAndrew Morton 
780d70f2a14SAndrew Morton 		if (unlikely(x))
7818495f7e6SSai Praneeth Prakhya 			pr_alert("BUG: Bad rss-counter state mm:%p type:%s val:%ld\n",
7828495f7e6SSai Praneeth Prakhya 				 mm, resident_page_types[i], x);
783d70f2a14SAndrew Morton 	}
784d70f2a14SAndrew Morton 
785d70f2a14SAndrew Morton 	if (mm_pgtables_bytes(mm))
786d70f2a14SAndrew Morton 		pr_alert("BUG: non-zero pgtables_bytes on freeing mm: %ld\n",
787d70f2a14SAndrew Morton 				mm_pgtables_bytes(mm));
788d70f2a14SAndrew Morton 
789d70f2a14SAndrew Morton #if defined(CONFIG_TRANSPARENT_HUGEPAGE) && !USE_SPLIT_PMD_PTLOCKS
790d70f2a14SAndrew Morton 	VM_BUG_ON_MM(mm->pmd_huge_pte, mm);
791d70f2a14SAndrew Morton #endif
792d70f2a14SAndrew Morton }
7931da177e4SLinus Torvalds 
794e94b1766SChristoph Lameter #define allocate_mm()	(kmem_cache_alloc(mm_cachep, GFP_KERNEL))
7951da177e4SLinus Torvalds #define free_mm(mm)	(kmem_cache_free(mm_cachep, (mm)))
7961da177e4SLinus Torvalds 
7972655421aSNicholas Piggin static void do_check_lazy_tlb(void *arg)
7982655421aSNicholas Piggin {
7992655421aSNicholas Piggin 	struct mm_struct *mm = arg;
8002655421aSNicholas Piggin 
8012655421aSNicholas Piggin 	WARN_ON_ONCE(current->active_mm == mm);
8022655421aSNicholas Piggin }
8032655421aSNicholas Piggin 
8042655421aSNicholas Piggin static void do_shoot_lazy_tlb(void *arg)
8052655421aSNicholas Piggin {
8062655421aSNicholas Piggin 	struct mm_struct *mm = arg;
8072655421aSNicholas Piggin 
8082655421aSNicholas Piggin 	if (current->active_mm == mm) {
8092655421aSNicholas Piggin 		WARN_ON_ONCE(current->mm);
8102655421aSNicholas Piggin 		current->active_mm = &init_mm;
8112655421aSNicholas Piggin 		switch_mm(mm, &init_mm, current);
8122655421aSNicholas Piggin 	}
8132655421aSNicholas Piggin }
8142655421aSNicholas Piggin 
8152655421aSNicholas Piggin static void cleanup_lazy_tlbs(struct mm_struct *mm)
8162655421aSNicholas Piggin {
8172655421aSNicholas Piggin 	if (!IS_ENABLED(CONFIG_MMU_LAZY_TLB_SHOOTDOWN)) {
8182655421aSNicholas Piggin 		/*
8192655421aSNicholas Piggin 		 * In this case, lazy tlb mms are refounted and would not reach
8202655421aSNicholas Piggin 		 * __mmdrop until all CPUs have switched away and mmdrop()ed.
8212655421aSNicholas Piggin 		 */
8222655421aSNicholas Piggin 		return;
8232655421aSNicholas Piggin 	}
8242655421aSNicholas Piggin 
8252655421aSNicholas Piggin 	/*
8262655421aSNicholas Piggin 	 * Lazy mm shootdown does not refcount "lazy tlb mm" usage, rather it
8272655421aSNicholas Piggin 	 * requires lazy mm users to switch to another mm when the refcount
8282655421aSNicholas Piggin 	 * drops to zero, before the mm is freed. This requires IPIs here to
8292655421aSNicholas Piggin 	 * switch kernel threads to init_mm.
8302655421aSNicholas Piggin 	 *
8312655421aSNicholas Piggin 	 * archs that use IPIs to flush TLBs can piggy-back that lazy tlb mm
8322655421aSNicholas Piggin 	 * switch with the final userspace teardown TLB flush which leaves the
8332655421aSNicholas Piggin 	 * mm lazy on this CPU but no others, reducing the need for additional
8342655421aSNicholas Piggin 	 * IPIs here. There are cases where a final IPI is still required here,
8352655421aSNicholas Piggin 	 * such as the final mmdrop being performed on a different CPU than the
8362655421aSNicholas Piggin 	 * one exiting, or kernel threads using the mm when userspace exits.
8372655421aSNicholas Piggin 	 *
8382655421aSNicholas Piggin 	 * IPI overheads have not found to be expensive, but they could be
8392655421aSNicholas Piggin 	 * reduced in a number of possible ways, for example (roughly
8402655421aSNicholas Piggin 	 * increasing order of complexity):
8412655421aSNicholas Piggin 	 * - The last lazy reference created by exit_mm() could instead switch
8422655421aSNicholas Piggin 	 *   to init_mm, however it's probable this will run on the same CPU
8432655421aSNicholas Piggin 	 *   immediately afterwards, so this may not reduce IPIs much.
8442655421aSNicholas Piggin 	 * - A batch of mms requiring IPIs could be gathered and freed at once.
8452655421aSNicholas Piggin 	 * - CPUs store active_mm where it can be remotely checked without a
8462655421aSNicholas Piggin 	 *   lock, to filter out false-positives in the cpumask.
8472655421aSNicholas Piggin 	 * - After mm_users or mm_count reaches zero, switching away from the
8482655421aSNicholas Piggin 	 *   mm could clear mm_cpumask to reduce some IPIs, perhaps together
8492655421aSNicholas Piggin 	 *   with some batching or delaying of the final IPIs.
8502655421aSNicholas Piggin 	 * - A delayed freeing and RCU-like quiescing sequence based on mm
8512655421aSNicholas Piggin 	 *   switching to avoid IPIs completely.
8522655421aSNicholas Piggin 	 */
8532655421aSNicholas Piggin 	on_each_cpu_mask(mm_cpumask(mm), do_shoot_lazy_tlb, (void *)mm, 1);
8542655421aSNicholas Piggin 	if (IS_ENABLED(CONFIG_DEBUG_VM_SHOOT_LAZIES))
8552655421aSNicholas Piggin 		on_each_cpu(do_check_lazy_tlb, (void *)mm, 1);
8562655421aSNicholas Piggin }
8572655421aSNicholas Piggin 
858d70f2a14SAndrew Morton /*
859d70f2a14SAndrew Morton  * Called when the last reference to the mm
860d70f2a14SAndrew Morton  * is dropped: either by a lazy thread or by
861d70f2a14SAndrew Morton  * mmput. Free the page directory and the mm.
862d70f2a14SAndrew Morton  */
863d34bc48fSAndrew Morton void __mmdrop(struct mm_struct *mm)
864d70f2a14SAndrew Morton {
865f1a79412SShakeel Butt 	int i;
866f1a79412SShakeel Butt 
867d70f2a14SAndrew Morton 	BUG_ON(mm == &init_mm);
8683eda69c9SMark Rutland 	WARN_ON_ONCE(mm == current->mm);
8692655421aSNicholas Piggin 
8702655421aSNicholas Piggin 	/* Ensure no CPUs are using this as their lazy tlb mm */
8712655421aSNicholas Piggin 	cleanup_lazy_tlbs(mm);
8722655421aSNicholas Piggin 
8733eda69c9SMark Rutland 	WARN_ON_ONCE(mm == current->active_mm);
874d70f2a14SAndrew Morton 	mm_free_pgd(mm);
875d70f2a14SAndrew Morton 	destroy_context(mm);
876984cfe4eSJason Gunthorpe 	mmu_notifier_subscriptions_destroy(mm);
877d70f2a14SAndrew Morton 	check_mm(mm);
878d70f2a14SAndrew Morton 	put_user_ns(mm->user_ns);
8792667ed10SFenghua Yu 	mm_pasid_drop(mm);
880f1a79412SShakeel Butt 
881f1a79412SShakeel Butt 	for (i = 0; i < NR_MM_COUNTERS; i++)
882f1a79412SShakeel Butt 		percpu_counter_destroy(&mm->rss_stat[i]);
883d70f2a14SAndrew Morton 	free_mm(mm);
884d70f2a14SAndrew Morton }
885d34bc48fSAndrew Morton EXPORT_SYMBOL_GPL(__mmdrop);
886d70f2a14SAndrew Morton 
887d70f2a14SAndrew Morton static void mmdrop_async_fn(struct work_struct *work)
888d70f2a14SAndrew Morton {
889d70f2a14SAndrew Morton 	struct mm_struct *mm;
890d70f2a14SAndrew Morton 
891d70f2a14SAndrew Morton 	mm = container_of(work, struct mm_struct, async_put_work);
892d70f2a14SAndrew Morton 	__mmdrop(mm);
893d70f2a14SAndrew Morton }
894d70f2a14SAndrew Morton 
895d70f2a14SAndrew Morton static void mmdrop_async(struct mm_struct *mm)
896d70f2a14SAndrew Morton {
897d70f2a14SAndrew Morton 	if (unlikely(atomic_dec_and_test(&mm->mm_count))) {
898d70f2a14SAndrew Morton 		INIT_WORK(&mm->async_put_work, mmdrop_async_fn);
899d70f2a14SAndrew Morton 		schedule_work(&mm->async_put_work);
900d70f2a14SAndrew Morton 	}
901d70f2a14SAndrew Morton }
902d70f2a14SAndrew Morton 
9031da177e4SLinus Torvalds static inline void free_signal_struct(struct signal_struct *sig)
9041da177e4SLinus Torvalds {
9051da177e4SLinus Torvalds 	taskstats_tgid_free(sig);
9061da177e4SLinus Torvalds 	sched_autogroup_exit(sig);
9071da177e4SLinus Torvalds 	/*
9081da177e4SLinus Torvalds 	 * __mmdrop is not safe to call from softirq context on x86 due to
9091da177e4SLinus Torvalds 	 * pgd_dtor so postpone it to the async context
9101da177e4SLinus Torvalds 	 */
9111da177e4SLinus Torvalds 	if (sig->oom_mm)
9121da177e4SLinus Torvalds 		mmdrop_async(sig->oom_mm);
9131da177e4SLinus Torvalds 	kmem_cache_free(signal_cachep, sig);
9141da177e4SLinus Torvalds }
9151da177e4SLinus Torvalds 
9161da177e4SLinus Torvalds static inline void put_signal_struct(struct signal_struct *sig)
9171da177e4SLinus Torvalds {
91860d4de3fSElena Reshetova 	if (refcount_dec_and_test(&sig->sigcnt))
9191da177e4SLinus Torvalds 		free_signal_struct(sig);
9201da177e4SLinus Torvalds }
9211da177e4SLinus Torvalds 
9221da177e4SLinus Torvalds void __put_task_struct(struct task_struct *tsk)
9231da177e4SLinus Torvalds {
9241da177e4SLinus Torvalds 	WARN_ON(!tsk->exit_state);
925ec1d2819SElena Reshetova 	WARN_ON(refcount_read(&tsk->usage));
9261da177e4SLinus Torvalds 	WARN_ON(tsk == current);
9271da177e4SLinus Torvalds 
9280f212204SJens Axboe 	io_uring_free(tsk);
9291da177e4SLinus Torvalds 	cgroup_free(tsk);
93016d51a59SJann Horn 	task_numa_free(tsk, true);
9311da177e4SLinus Torvalds 	security_task_free(tsk);
932a10787e6SSong Liu 	bpf_task_storage_free(tsk);
9331da177e4SLinus Torvalds 	exit_creds(tsk);
9341da177e4SLinus Torvalds 	delayacct_tsk_free(tsk);
9351da177e4SLinus Torvalds 	put_signal_struct(tsk->signal);
9366e33cad0SPeter Zijlstra 	sched_core_free(tsk);
9371da177e4SLinus Torvalds 	free_task(tsk);
9381da177e4SLinus Torvalds }
9391da177e4SLinus Torvalds EXPORT_SYMBOL_GPL(__put_task_struct);
9401da177e4SLinus Torvalds 
9411da177e4SLinus Torvalds void __init __weak arch_task_cache_init(void) { }
9421da177e4SLinus Torvalds 
9431da177e4SLinus Torvalds /*
9441da177e4SLinus Torvalds  * set_max_threads
9451da177e4SLinus Torvalds  */
9461da177e4SLinus Torvalds static void set_max_threads(unsigned int max_threads_suggested)
9471da177e4SLinus Torvalds {
9481da177e4SLinus Torvalds 	u64 threads;
949ca79b0c2SArun KS 	unsigned long nr_pages = totalram_pages();
9501da177e4SLinus Torvalds 
9511da177e4SLinus Torvalds 	/*
9521da177e4SLinus Torvalds 	 * The number of threads shall be limited such that the thread
9531da177e4SLinus Torvalds 	 * structures may only consume a small part of the available memory.
9541da177e4SLinus Torvalds 	 */
9553d6357deSArun KS 	if (fls64(nr_pages) + fls64(PAGE_SIZE) > 64)
9561da177e4SLinus Torvalds 		threads = MAX_THREADS;
9571da177e4SLinus Torvalds 	else
9583d6357deSArun KS 		threads = div64_u64((u64) nr_pages * (u64) PAGE_SIZE,
9591da177e4SLinus Torvalds 				    (u64) THREAD_SIZE * 8UL);
9601da177e4SLinus Torvalds 
9611da177e4SLinus Torvalds 	if (threads > max_threads_suggested)
9621da177e4SLinus Torvalds 		threads = max_threads_suggested;
9631da177e4SLinus Torvalds 
9641da177e4SLinus Torvalds 	max_threads = clamp_t(u64, threads, MIN_THREADS, MAX_THREADS);
9651da177e4SLinus Torvalds }
9661da177e4SLinus Torvalds 
9671da177e4SLinus Torvalds #ifdef CONFIG_ARCH_WANTS_DYNAMIC_TASK_STRUCT
9681da177e4SLinus Torvalds /* Initialized by the architecture: */
9691da177e4SLinus Torvalds int arch_task_struct_size __read_mostly;
9701da177e4SLinus Torvalds #endif
9711da177e4SLinus Torvalds 
9724189ff23SChristoph Hellwig #ifndef CONFIG_ARCH_TASK_STRUCT_ALLOCATOR
9735905429aSKees Cook static void task_struct_whitelist(unsigned long *offset, unsigned long *size)
9745905429aSKees Cook {
9755905429aSKees Cook 	/* Fetch thread_struct whitelist for the architecture. */
9765905429aSKees Cook 	arch_thread_struct_whitelist(offset, size);
9775905429aSKees Cook 
9785905429aSKees Cook 	/*
9795905429aSKees Cook 	 * Handle zero-sized whitelist or empty thread_struct, otherwise
9805905429aSKees Cook 	 * adjust offset to position of thread_struct in task_struct.
9815905429aSKees Cook 	 */
9825905429aSKees Cook 	if (unlikely(*size == 0))
9835905429aSKees Cook 		*offset = 0;
9845905429aSKees Cook 	else
9855905429aSKees Cook 		*offset += offsetof(struct task_struct, thread);
9865905429aSKees Cook }
9874189ff23SChristoph Hellwig #endif /* CONFIG_ARCH_TASK_STRUCT_ALLOCATOR */
9885905429aSKees Cook 
9891da177e4SLinus Torvalds void __init fork_init(void)
9901da177e4SLinus Torvalds {
9911da177e4SLinus Torvalds 	int i;
9921da177e4SLinus Torvalds #ifndef CONFIG_ARCH_TASK_STRUCT_ALLOCATOR
9931da177e4SLinus Torvalds #ifndef ARCH_MIN_TASKALIGN
9941da177e4SLinus Torvalds #define ARCH_MIN_TASKALIGN	0
9951da177e4SLinus Torvalds #endif
9961da177e4SLinus Torvalds 	int align = max_t(int, L1_CACHE_BYTES, ARCH_MIN_TASKALIGN);
9975905429aSKees Cook 	unsigned long useroffset, usersize;
9981da177e4SLinus Torvalds 
9991da177e4SLinus Torvalds 	/* create a slab on which task_structs can be allocated */
10005905429aSKees Cook 	task_struct_whitelist(&useroffset, &usersize);
10015905429aSKees Cook 	task_struct_cachep = kmem_cache_create_usercopy("task_struct",
10021da177e4SLinus Torvalds 			arch_task_struct_size, align,
10035905429aSKees Cook 			SLAB_PANIC|SLAB_ACCOUNT,
10045905429aSKees Cook 			useroffset, usersize, NULL);
10051da177e4SLinus Torvalds #endif
10061da177e4SLinus Torvalds 
10071da177e4SLinus Torvalds 	/* do the arch specific task caches init */
10081da177e4SLinus Torvalds 	arch_task_cache_init();
10091da177e4SLinus Torvalds 
10101da177e4SLinus Torvalds 	set_max_threads(MAX_THREADS);
10111da177e4SLinus Torvalds 
10121da177e4SLinus Torvalds 	init_task.signal->rlim[RLIMIT_NPROC].rlim_cur = max_threads/2;
10131da177e4SLinus Torvalds 	init_task.signal->rlim[RLIMIT_NPROC].rlim_max = max_threads/2;
10141da177e4SLinus Torvalds 	init_task.signal->rlim[RLIMIT_SIGPENDING] =
10151da177e4SLinus Torvalds 		init_task.signal->rlim[RLIMIT_NPROC];
10161da177e4SLinus Torvalds 
1017de399236SAlexey Gladkov 	for (i = 0; i < UCOUNT_COUNTS; i++)
10181da177e4SLinus Torvalds 		init_user_ns.ucount_max[i] = max_threads/2;
10191da177e4SLinus Torvalds 
1020de399236SAlexey Gladkov 	set_userns_rlimit_max(&init_user_ns, UCOUNT_RLIMIT_NPROC,      RLIM_INFINITY);
1021de399236SAlexey Gladkov 	set_userns_rlimit_max(&init_user_ns, UCOUNT_RLIMIT_MSGQUEUE,   RLIM_INFINITY);
1022de399236SAlexey Gladkov 	set_userns_rlimit_max(&init_user_ns, UCOUNT_RLIMIT_SIGPENDING, RLIM_INFINITY);
1023de399236SAlexey Gladkov 	set_userns_rlimit_max(&init_user_ns, UCOUNT_RLIMIT_MEMLOCK,    RLIM_INFINITY);
102421d1c5e3SAlexey Gladkov 
10251da177e4SLinus Torvalds #ifdef CONFIG_VMAP_STACK
10261da177e4SLinus Torvalds 	cpuhp_setup_state(CPUHP_BP_PREPARE_DYN, "fork:vm_stack_cache",
10271da177e4SLinus Torvalds 			  NULL, free_vm_stack_cache);
10281da177e4SLinus Torvalds #endif
10291da177e4SLinus Torvalds 
1030d08b9f0cSSami Tolvanen 	scs_init();
1031d08b9f0cSSami Tolvanen 
10321da177e4SLinus Torvalds 	lockdep_init_task(&init_task);
1033aad42dd4SNadav Amit 	uprobes_init();
10341da177e4SLinus Torvalds }
10351da177e4SLinus Torvalds 
10361da177e4SLinus Torvalds int __weak arch_dup_task_struct(struct task_struct *dst,
10371da177e4SLinus Torvalds 					       struct task_struct *src)
10381da177e4SLinus Torvalds {
10391da177e4SLinus Torvalds 	*dst = *src;
10401da177e4SLinus Torvalds 	return 0;
10411da177e4SLinus Torvalds }
10421da177e4SLinus Torvalds 
10431da177e4SLinus Torvalds void set_task_stack_end_magic(struct task_struct *tsk)
10441da177e4SLinus Torvalds {
10451da177e4SLinus Torvalds 	unsigned long *stackend;
10461da177e4SLinus Torvalds 
10471da177e4SLinus Torvalds 	stackend = end_of_stack(tsk);
10481da177e4SLinus Torvalds 	*stackend = STACK_END_MAGIC;	/* for overflow detection */
10491da177e4SLinus Torvalds }
10501da177e4SLinus Torvalds 
10511da177e4SLinus Torvalds static struct task_struct *dup_task_struct(struct task_struct *orig, int node)
10521da177e4SLinus Torvalds {
10531da177e4SLinus Torvalds 	struct task_struct *tsk;
10541da177e4SLinus Torvalds 	int err;
10551da177e4SLinus Torvalds 
10561da177e4SLinus Torvalds 	if (node == NUMA_NO_NODE)
10571da177e4SLinus Torvalds 		node = tsk_fork_get_node(orig);
10581da177e4SLinus Torvalds 	tsk = alloc_task_struct_node(node);
10591da177e4SLinus Torvalds 	if (!tsk)
10601da177e4SLinus Torvalds 		return NULL;
10611da177e4SLinus Torvalds 
1062546c42b2SSebastian Andrzej Siewior 	err = arch_dup_task_struct(tsk, orig);
1063546c42b2SSebastian Andrzej Siewior 	if (err)
10641da177e4SLinus Torvalds 		goto free_tsk;
10651da177e4SLinus Torvalds 
10667865aba3SSebastian Andrzej Siewior 	err = alloc_thread_stack_node(tsk, node);
10677865aba3SSebastian Andrzej Siewior 	if (err)
10681da177e4SLinus Torvalds 		goto free_tsk;
10699b6f7e16SRoman Gushchin 
10701da177e4SLinus Torvalds #ifdef CONFIG_THREAD_INFO_IN_TASK
1071f0b89d39SElena Reshetova 	refcount_set(&tsk->stack_refcount, 1);
10721da177e4SLinus Torvalds #endif
10731a03d3f1SSebastian Andrzej Siewior 	account_kernel_stack(tsk, 1);
10741da177e4SLinus Torvalds 
1075d08b9f0cSSami Tolvanen 	err = scs_prepare(tsk, node);
1076d08b9f0cSSami Tolvanen 	if (err)
1077d08b9f0cSSami Tolvanen 		goto free_stack;
1078d08b9f0cSSami Tolvanen 
10791da177e4SLinus Torvalds #ifdef CONFIG_SECCOMP
10801da177e4SLinus Torvalds 	/*
10811da177e4SLinus Torvalds 	 * We must handle setting up seccomp filters once we're under
10821da177e4SLinus Torvalds 	 * the sighand lock in case orig has changed between now and
10831da177e4SLinus Torvalds 	 * then. Until then, filter must be NULL to avoid messing up
10841da177e4SLinus Torvalds 	 * the usage counts on the error path calling free_task.
10851da177e4SLinus Torvalds 	 */
10861da177e4SLinus Torvalds 	tsk->seccomp.filter = NULL;
10871da177e4SLinus Torvalds #endif
10881da177e4SLinus Torvalds 
10891da177e4SLinus Torvalds 	setup_thread_stack(tsk, orig);
10901da177e4SLinus Torvalds 	clear_user_return_notifier(tsk);
10911da177e4SLinus Torvalds 	clear_tsk_need_resched(tsk);
10921da177e4SLinus Torvalds 	set_task_stack_end_magic(tsk);
10931446e1dfSGabriel Krisman Bertazi 	clear_syscall_work_syscall_user_dispatch(tsk);
10941da177e4SLinus Torvalds 
1095050e9baaSLinus Torvalds #ifdef CONFIG_STACKPROTECTOR
10961da177e4SLinus Torvalds 	tsk->stack_canary = get_random_canary();
10971da177e4SLinus Torvalds #endif
10983bd37062SSebastian Andrzej Siewior 	if (orig->cpus_ptr == &orig->cpus_mask)
10993bd37062SSebastian Andrzej Siewior 		tsk->cpus_ptr = &tsk->cpus_mask;
1100b90ca8baSWill Deacon 	dup_user_cpus_ptr(tsk, orig, node);
11011da177e4SLinus Torvalds 
11021da177e4SLinus Torvalds 	/*
11030ff7b2cfSEric W. Biederman 	 * One for the user space visible state that goes away when reaped.
11040ff7b2cfSEric W. Biederman 	 * One for the scheduler.
11051da177e4SLinus Torvalds 	 */
11060ff7b2cfSEric W. Biederman 	refcount_set(&tsk->rcu_users, 2);
11070ff7b2cfSEric W. Biederman 	/* One for the rcu users */
11080ff7b2cfSEric W. Biederman 	refcount_set(&tsk->usage, 1);
11091da177e4SLinus Torvalds #ifdef CONFIG_BLK_DEV_IO_TRACE
11101da177e4SLinus Torvalds 	tsk->btrace_seq = 0;
11111da177e4SLinus Torvalds #endif
11121da177e4SLinus Torvalds 	tsk->splice_pipe = NULL;
11131da177e4SLinus Torvalds 	tsk->task_frag.page = NULL;
11141da177e4SLinus Torvalds 	tsk->wake_q.next = NULL;
1115e32cf5dfSEric W. Biederman 	tsk->worker_private = NULL;
11161da177e4SLinus Torvalds 
11171da177e4SLinus Torvalds 	kcov_task_init(tsk);
111850b5e49cSAlexander Potapenko 	kmsan_task_create(tsk);
11195fbda3ecSThomas Gleixner 	kmap_local_fork(tsk);
11201da177e4SLinus Torvalds 
11211da177e4SLinus Torvalds #ifdef CONFIG_FAULT_INJECTION
11221da177e4SLinus Torvalds 	tsk->fail_nth = 0;
11231da177e4SLinus Torvalds #endif
11241da177e4SLinus Torvalds 
11252c323017SJosef Bacik #ifdef CONFIG_BLK_CGROUP
1126f05837edSChristoph Hellwig 	tsk->throttle_disk = NULL;
11272c323017SJosef Bacik 	tsk->use_memdelay = 0;
11282c323017SJosef Bacik #endif
11292c323017SJosef Bacik 
1130a3d29e82SPeter Zijlstra #ifdef CONFIG_IOMMU_SVA
1131a3d29e82SPeter Zijlstra 	tsk->pasid_activated = 0;
1132a3d29e82SPeter Zijlstra #endif
1133a3d29e82SPeter Zijlstra 
1134d46eb14bSShakeel Butt #ifdef CONFIG_MEMCG
1135d46eb14bSShakeel Butt 	tsk->active_memcg = NULL;
1136d46eb14bSShakeel Butt #endif
1137b041b525STony Luck 
1138b041b525STony Luck #ifdef CONFIG_CPU_SUP_INTEL
1139b041b525STony Luck 	tsk->reported_split_lock = 0;
1140b041b525STony Luck #endif
1141b041b525STony Luck 
1142af7f588dSMathieu Desnoyers #ifdef CONFIG_SCHED_MM_CID
1143af7f588dSMathieu Desnoyers 	tsk->mm_cid = -1;
1144af7f588dSMathieu Desnoyers 	tsk->mm_cid_active = 0;
1145af7f588dSMathieu Desnoyers #endif
11461da177e4SLinus Torvalds 	return tsk;
11471da177e4SLinus Torvalds 
11481da177e4SLinus Torvalds free_stack:
11491a03d3f1SSebastian Andrzej Siewior 	exit_task_stack_account(tsk);
11501da177e4SLinus Torvalds 	free_thread_stack(tsk);
11511da177e4SLinus Torvalds free_tsk:
11521da177e4SLinus Torvalds 	free_task_struct(tsk);
11531da177e4SLinus Torvalds 	return NULL;
11541da177e4SLinus Torvalds }
11551da177e4SLinus Torvalds 
11561da177e4SLinus Torvalds __cacheline_aligned_in_smp DEFINE_SPINLOCK(mmlist_lock);
11571da177e4SLinus Torvalds 
11584cb0e11bSHidehiro Kawai static unsigned long default_dump_filter = MMF_DUMP_FILTER_DEFAULT;
11594cb0e11bSHidehiro Kawai 
11604cb0e11bSHidehiro Kawai static int __init coredump_filter_setup(char *s)
11614cb0e11bSHidehiro Kawai {
11624cb0e11bSHidehiro Kawai 	default_dump_filter =
11634cb0e11bSHidehiro Kawai 		(simple_strtoul(s, NULL, 0) << MMF_DUMP_FILTER_SHIFT) &
11644cb0e11bSHidehiro Kawai 		MMF_DUMP_FILTER_MASK;
11654cb0e11bSHidehiro Kawai 	return 1;
11664cb0e11bSHidehiro Kawai }
11674cb0e11bSHidehiro Kawai 
11684cb0e11bSHidehiro Kawai __setup("coredump_filter=", coredump_filter_setup);
11694cb0e11bSHidehiro Kawai 
11701da177e4SLinus Torvalds #include <linux/init_task.h>
11711da177e4SLinus Torvalds 
1172858f0993SAlexey Dobriyan static void mm_init_aio(struct mm_struct *mm)
1173858f0993SAlexey Dobriyan {
1174858f0993SAlexey Dobriyan #ifdef CONFIG_AIO
1175858f0993SAlexey Dobriyan 	spin_lock_init(&mm->ioctx_lock);
1176db446a08SBenjamin LaHaise 	mm->ioctx_table = NULL;
1177858f0993SAlexey Dobriyan #endif
1178858f0993SAlexey Dobriyan }
1179858f0993SAlexey Dobriyan 
1180c3f3ce04SAndrea Arcangeli static __always_inline void mm_clear_owner(struct mm_struct *mm,
1181c3f3ce04SAndrea Arcangeli 					   struct task_struct *p)
1182c3f3ce04SAndrea Arcangeli {
1183c3f3ce04SAndrea Arcangeli #ifdef CONFIG_MEMCG
1184c3f3ce04SAndrea Arcangeli 	if (mm->owner == p)
1185c3f3ce04SAndrea Arcangeli 		WRITE_ONCE(mm->owner, NULL);
1186c3f3ce04SAndrea Arcangeli #endif
1187c3f3ce04SAndrea Arcangeli }
1188c3f3ce04SAndrea Arcangeli 
118933144e84SVladimir Davydov static void mm_init_owner(struct mm_struct *mm, struct task_struct *p)
119033144e84SVladimir Davydov {
119133144e84SVladimir Davydov #ifdef CONFIG_MEMCG
119233144e84SVladimir Davydov 	mm->owner = p;
119333144e84SVladimir Davydov #endif
119433144e84SVladimir Davydov }
119533144e84SVladimir Davydov 
1196355627f5SEric Biggers static void mm_init_uprobes_state(struct mm_struct *mm)
1197355627f5SEric Biggers {
1198355627f5SEric Biggers #ifdef CONFIG_UPROBES
1199355627f5SEric Biggers 	mm->uprobes_state.xol_area = NULL;
1200355627f5SEric Biggers #endif
1201355627f5SEric Biggers }
1202355627f5SEric Biggers 
1203bfedb589SEric W. Biederman static struct mm_struct *mm_init(struct mm_struct *mm, struct task_struct *p,
1204bfedb589SEric W. Biederman 	struct user_namespace *user_ns)
12051da177e4SLinus Torvalds {
1206f1a79412SShakeel Butt 	int i;
1207f1a79412SShakeel Butt 
1208d4af56c5SLiam R. Howlett 	mt_init_flags(&mm->mm_mt, MM_MT_FLAGS);
1209d4af56c5SLiam R. Howlett 	mt_set_external_lock(&mm->mm_mt, &mm->mmap_lock);
12101da177e4SLinus Torvalds 	atomic_set(&mm->mm_users, 1);
12111da177e4SLinus Torvalds 	atomic_set(&mm->mm_count, 1);
121257efa1feSJason Gunthorpe 	seqcount_init(&mm->write_protect_seq);
1213d8ed45c5SMichel Lespinasse 	mmap_init_lock(mm);
12141da177e4SLinus Torvalds 	INIT_LIST_HEAD(&mm->mmlist);
12155e31275cSSuren Baghdasaryan #ifdef CONFIG_PER_VMA_LOCK
12165e31275cSSuren Baghdasaryan 	mm->mm_lock_seq = 0;
12175e31275cSSuren Baghdasaryan #endif
1218af5b0f6aSKirill A. Shutemov 	mm_pgtables_bytes_init(mm);
121941f727fdSVladimir Davydov 	mm->map_count = 0;
122041f727fdSVladimir Davydov 	mm->locked_vm = 0;
122170f8a3caSDavidlohr Bueso 	atomic64_set(&mm->pinned_vm, 0);
1222d559db08SKAMEZAWA Hiroyuki 	memset(&mm->rss_stat, 0, sizeof(mm->rss_stat));
12231da177e4SLinus Torvalds 	spin_lock_init(&mm->page_table_lock);
122488aa7cc6SYang Shi 	spin_lock_init(&mm->arg_lock);
122541f727fdSVladimir Davydov 	mm_init_cpumask(mm);
1226858f0993SAlexey Dobriyan 	mm_init_aio(mm);
1227cf475ad2SBalbir Singh 	mm_init_owner(mm, p);
1228a6cbd440SFenghua Yu 	mm_pasid_init(mm);
12292b7e8665SEric Biggers 	RCU_INIT_POINTER(mm->exe_file, NULL);
1230984cfe4eSJason Gunthorpe 	mmu_notifier_subscriptions_init(mm);
123116af97dcSNadav Amit 	init_tlb_flush_pending(mm);
123241f727fdSVladimir Davydov #if defined(CONFIG_TRANSPARENT_HUGEPAGE) && !USE_SPLIT_PMD_PTLOCKS
123341f727fdSVladimir Davydov 	mm->pmd_huge_pte = NULL;
123441f727fdSVladimir Davydov #endif
1235355627f5SEric Biggers 	mm_init_uprobes_state(mm);
123613db8c50SLiu Zixian 	hugetlb_count_init(mm);
12371da177e4SLinus Torvalds 
1238a0715cc2SAlex Thorlton 	if (current->mm) {
1239a0715cc2SAlex Thorlton 		mm->flags = current->mm->flags & MMF_INIT_MASK;
1240a0715cc2SAlex Thorlton 		mm->def_flags = current->mm->def_flags & VM_INIT_DEF_MASK;
1241a0715cc2SAlex Thorlton 	} else {
1242a0715cc2SAlex Thorlton 		mm->flags = default_dump_filter;
12431da177e4SLinus Torvalds 		mm->def_flags = 0;
1244a0715cc2SAlex Thorlton 	}
1245a0715cc2SAlex Thorlton 
124641f727fdSVladimir Davydov 	if (mm_alloc_pgd(mm))
124741f727fdSVladimir Davydov 		goto fail_nopgd;
124878fb7466SPavel Emelianov 
124941f727fdSVladimir Davydov 	if (init_new_context(p, mm))
125041f727fdSVladimir Davydov 		goto fail_nocontext;
125141f727fdSVladimir Davydov 
1252f1a79412SShakeel Butt 	for (i = 0; i < NR_MM_COUNTERS; i++)
1253f1a79412SShakeel Butt 		if (percpu_counter_init(&mm->rss_stat[i], 0, GFP_KERNEL_ACCOUNT))
1254f1a79412SShakeel Butt 			goto fail_pcpu;
1255f1a79412SShakeel Butt 
1256bfedb589SEric W. Biederman 	mm->user_ns = get_user_ns(user_ns);
1257bd74fdaeSYu Zhao 	lru_gen_init_mm(mm);
1258af7f588dSMathieu Desnoyers 	mm_init_cid(mm);
125941f727fdSVladimir Davydov 	return mm;
126041f727fdSVladimir Davydov 
1261f1a79412SShakeel Butt fail_pcpu:
1262f1a79412SShakeel Butt 	while (i > 0)
1263f1a79412SShakeel Butt 		percpu_counter_destroy(&mm->rss_stat[--i]);
126441f727fdSVladimir Davydov fail_nocontext:
126541f727fdSVladimir Davydov 	mm_free_pgd(mm);
126641f727fdSVladimir Davydov fail_nopgd:
12671da177e4SLinus Torvalds 	free_mm(mm);
12681da177e4SLinus Torvalds 	return NULL;
12691da177e4SLinus Torvalds }
12701da177e4SLinus Torvalds 
12711da177e4SLinus Torvalds /*
12721da177e4SLinus Torvalds  * Allocate and initialize an mm_struct.
12731da177e4SLinus Torvalds  */
12741da177e4SLinus Torvalds struct mm_struct *mm_alloc(void)
12751da177e4SLinus Torvalds {
12761da177e4SLinus Torvalds 	struct mm_struct *mm;
12771da177e4SLinus Torvalds 
12781da177e4SLinus Torvalds 	mm = allocate_mm();
1279de03c72cSKOSAKI Motohiro 	if (!mm)
1280de03c72cSKOSAKI Motohiro 		return NULL;
1281de03c72cSKOSAKI Motohiro 
12821da177e4SLinus Torvalds 	memset(mm, 0, sizeof(*mm));
1283bfedb589SEric W. Biederman 	return mm_init(mm, current, current_user_ns());
12841da177e4SLinus Torvalds }
12851da177e4SLinus Torvalds 
1286ec8d7c14SMichal Hocko static inline void __mmput(struct mm_struct *mm)
12871da177e4SLinus Torvalds {
1288ec8d7c14SMichal Hocko 	VM_BUG_ON(atomic_read(&mm->mm_users));
12890ae26f1bSAndrew Morton 
1290d4b3b638SSrikar Dronamraju 	uprobe_clear_state(mm);
12911da177e4SLinus Torvalds 	exit_aio(mm);
12921c2fb7a4SAndrea Arcangeli 	ksm_exit(mm);
1293ba76149fSAndrea Arcangeli 	khugepaged_exit(mm); /* must run before exit_mmap */
12941da177e4SLinus Torvalds 	exit_mmap(mm);
12956fcb52a5SAaron Lu 	mm_put_huge_zero_page(mm);
1296925d1c40SMatt Helsley 	set_mm_exe_file(mm, NULL);
12971da177e4SLinus Torvalds 	if (!list_empty(&mm->mmlist)) {
12981da177e4SLinus Torvalds 		spin_lock(&mmlist_lock);
12991da177e4SLinus Torvalds 		list_del(&mm->mmlist);
13001da177e4SLinus Torvalds 		spin_unlock(&mmlist_lock);
13011da177e4SLinus Torvalds 	}
1302801460d0SHiroshi Shimamoto 	if (mm->binfmt)
1303801460d0SHiroshi Shimamoto 		module_put(mm->binfmt->module);
1304bd74fdaeSYu Zhao 	lru_gen_del_mm(mm);
13051da177e4SLinus Torvalds 	mmdrop(mm);
13061da177e4SLinus Torvalds }
1307ec8d7c14SMichal Hocko 
1308ec8d7c14SMichal Hocko /*
1309ec8d7c14SMichal Hocko  * Decrement the use count and release all resources for an mm.
1310ec8d7c14SMichal Hocko  */
1311ec8d7c14SMichal Hocko void mmput(struct mm_struct *mm)
1312ec8d7c14SMichal Hocko {
1313ec8d7c14SMichal Hocko 	might_sleep();
1314ec8d7c14SMichal Hocko 
1315ec8d7c14SMichal Hocko 	if (atomic_dec_and_test(&mm->mm_users))
1316ec8d7c14SMichal Hocko 		__mmput(mm);
13171da177e4SLinus Torvalds }
13181da177e4SLinus Torvalds EXPORT_SYMBOL_GPL(mmput);
13191da177e4SLinus Torvalds 
1320a1b2289cSSherry Yang #ifdef CONFIG_MMU
1321a1b2289cSSherry Yang static void mmput_async_fn(struct work_struct *work)
1322a1b2289cSSherry Yang {
1323a1b2289cSSherry Yang 	struct mm_struct *mm = container_of(work, struct mm_struct,
1324a1b2289cSSherry Yang 					    async_put_work);
1325a1b2289cSSherry Yang 
1326a1b2289cSSherry Yang 	__mmput(mm);
1327a1b2289cSSherry Yang }
1328a1b2289cSSherry Yang 
1329a1b2289cSSherry Yang void mmput_async(struct mm_struct *mm)
1330a1b2289cSSherry Yang {
1331a1b2289cSSherry Yang 	if (atomic_dec_and_test(&mm->mm_users)) {
1332a1b2289cSSherry Yang 		INIT_WORK(&mm->async_put_work, mmput_async_fn);
1333a1b2289cSSherry Yang 		schedule_work(&mm->async_put_work);
1334a1b2289cSSherry Yang 	}
1335a1b2289cSSherry Yang }
133685eaeb50SYishai Hadas EXPORT_SYMBOL_GPL(mmput_async);
1337a1b2289cSSherry Yang #endif
1338a1b2289cSSherry Yang 
133990f31d0eSKonstantin Khlebnikov /**
134090f31d0eSKonstantin Khlebnikov  * set_mm_exe_file - change a reference to the mm's executable file
134190f31d0eSKonstantin Khlebnikov  *
134290f31d0eSKonstantin Khlebnikov  * This changes mm's executable file (shown as symlink /proc/[pid]/exe).
134390f31d0eSKonstantin Khlebnikov  *
13446e399cd1SDavidlohr Bueso  * Main users are mmput() and sys_execve(). Callers prevent concurrent
13456e399cd1SDavidlohr Bueso  * invocations: in mmput() nobody alive left, in execve task is single
134635d7bdc8SDavid Hildenbrand  * threaded.
1347fe69d560SDavid Hildenbrand  *
1348fe69d560SDavid Hildenbrand  * Can only fail if new_exe_file != NULL.
134990f31d0eSKonstantin Khlebnikov  */
1350fe69d560SDavid Hildenbrand int set_mm_exe_file(struct mm_struct *mm, struct file *new_exe_file)
135138646013SJiri Slaby {
13526e399cd1SDavidlohr Bueso 	struct file *old_exe_file;
13536e399cd1SDavidlohr Bueso 
13546e399cd1SDavidlohr Bueso 	/*
13556e399cd1SDavidlohr Bueso 	 * It is safe to dereference the exe_file without RCU as
13566e399cd1SDavidlohr Bueso 	 * this function is only called if nobody else can access
13576e399cd1SDavidlohr Bueso 	 * this mm -- see comment above for justification.
13586e399cd1SDavidlohr Bueso 	 */
13596e399cd1SDavidlohr Bueso 	old_exe_file = rcu_dereference_raw(mm->exe_file);
136090f31d0eSKonstantin Khlebnikov 
1361fe69d560SDavid Hildenbrand 	if (new_exe_file) {
1362fe69d560SDavid Hildenbrand 		/*
1363fe69d560SDavid Hildenbrand 		 * We expect the caller (i.e., sys_execve) to already denied
1364fe69d560SDavid Hildenbrand 		 * write access, so this is unlikely to fail.
1365fe69d560SDavid Hildenbrand 		 */
1366fe69d560SDavid Hildenbrand 		if (unlikely(deny_write_access(new_exe_file)))
1367fe69d560SDavid Hildenbrand 			return -EACCES;
136838646013SJiri Slaby 		get_file(new_exe_file);
1369fe69d560SDavid Hildenbrand 	}
137090f31d0eSKonstantin Khlebnikov 	rcu_assign_pointer(mm->exe_file, new_exe_file);
1371fe69d560SDavid Hildenbrand 	if (old_exe_file) {
1372fe69d560SDavid Hildenbrand 		allow_write_access(old_exe_file);
137390f31d0eSKonstantin Khlebnikov 		fput(old_exe_file);
137438646013SJiri Slaby 	}
1375fe69d560SDavid Hildenbrand 	return 0;
1376fe69d560SDavid Hildenbrand }
137738646013SJiri Slaby 
137890f31d0eSKonstantin Khlebnikov /**
137935d7bdc8SDavid Hildenbrand  * replace_mm_exe_file - replace a reference to the mm's executable file
138035d7bdc8SDavid Hildenbrand  *
138135d7bdc8SDavid Hildenbrand  * This changes mm's executable file (shown as symlink /proc/[pid]/exe),
138235d7bdc8SDavid Hildenbrand  * dealing with concurrent invocation and without grabbing the mmap lock in
138335d7bdc8SDavid Hildenbrand  * write mode.
138435d7bdc8SDavid Hildenbrand  *
138535d7bdc8SDavid Hildenbrand  * Main user is sys_prctl(PR_SET_MM_MAP/EXE_FILE).
138635d7bdc8SDavid Hildenbrand  */
138735d7bdc8SDavid Hildenbrand int replace_mm_exe_file(struct mm_struct *mm, struct file *new_exe_file)
138835d7bdc8SDavid Hildenbrand {
138935d7bdc8SDavid Hildenbrand 	struct vm_area_struct *vma;
139035d7bdc8SDavid Hildenbrand 	struct file *old_exe_file;
139135d7bdc8SDavid Hildenbrand 	int ret = 0;
139235d7bdc8SDavid Hildenbrand 
139335d7bdc8SDavid Hildenbrand 	/* Forbid mm->exe_file change if old file still mapped. */
139435d7bdc8SDavid Hildenbrand 	old_exe_file = get_mm_exe_file(mm);
139535d7bdc8SDavid Hildenbrand 	if (old_exe_file) {
1396fa5e5876SMatthew Wilcox (Oracle) 		VMA_ITERATOR(vmi, mm, 0);
139735d7bdc8SDavid Hildenbrand 		mmap_read_lock(mm);
1398fa5e5876SMatthew Wilcox (Oracle) 		for_each_vma(vmi, vma) {
139935d7bdc8SDavid Hildenbrand 			if (!vma->vm_file)
140035d7bdc8SDavid Hildenbrand 				continue;
140135d7bdc8SDavid Hildenbrand 			if (path_equal(&vma->vm_file->f_path,
1402fa5e5876SMatthew Wilcox (Oracle) 				       &old_exe_file->f_path)) {
140335d7bdc8SDavid Hildenbrand 				ret = -EBUSY;
1404fa5e5876SMatthew Wilcox (Oracle) 				break;
1405fa5e5876SMatthew Wilcox (Oracle) 			}
140635d7bdc8SDavid Hildenbrand 		}
140735d7bdc8SDavid Hildenbrand 		mmap_read_unlock(mm);
140835d7bdc8SDavid Hildenbrand 		fput(old_exe_file);
140935d7bdc8SDavid Hildenbrand 		if (ret)
141035d7bdc8SDavid Hildenbrand 			return ret;
141135d7bdc8SDavid Hildenbrand 	}
141235d7bdc8SDavid Hildenbrand 
141335d7bdc8SDavid Hildenbrand 	/* set the new file, lockless */
1414fe69d560SDavid Hildenbrand 	ret = deny_write_access(new_exe_file);
1415fe69d560SDavid Hildenbrand 	if (ret)
1416fe69d560SDavid Hildenbrand 		return -EACCES;
141735d7bdc8SDavid Hildenbrand 	get_file(new_exe_file);
1418fe69d560SDavid Hildenbrand 
141935d7bdc8SDavid Hildenbrand 	old_exe_file = xchg(&mm->exe_file, new_exe_file);
1420fe69d560SDavid Hildenbrand 	if (old_exe_file) {
1421fe69d560SDavid Hildenbrand 		/*
1422fe69d560SDavid Hildenbrand 		 * Don't race with dup_mmap() getting the file and disallowing
1423fe69d560SDavid Hildenbrand 		 * write access while someone might open the file writable.
1424fe69d560SDavid Hildenbrand 		 */
1425fe69d560SDavid Hildenbrand 		mmap_read_lock(mm);
1426fe69d560SDavid Hildenbrand 		allow_write_access(old_exe_file);
142735d7bdc8SDavid Hildenbrand 		fput(old_exe_file);
1428fe69d560SDavid Hildenbrand 		mmap_read_unlock(mm);
1429fe69d560SDavid Hildenbrand 	}
143035d7bdc8SDavid Hildenbrand 	return 0;
143135d7bdc8SDavid Hildenbrand }
143238646013SJiri Slaby 
143390f31d0eSKonstantin Khlebnikov /**
143490f31d0eSKonstantin Khlebnikov  * get_mm_exe_file - acquire a reference to the mm's executable file
143590f31d0eSKonstantin Khlebnikov  *
143690f31d0eSKonstantin Khlebnikov  * Returns %NULL if mm has no associated executable file.
143790f31d0eSKonstantin Khlebnikov  * User must release file via fput().
143890f31d0eSKonstantin Khlebnikov  */
143938646013SJiri Slaby struct file *get_mm_exe_file(struct mm_struct *mm)
144038646013SJiri Slaby {
144138646013SJiri Slaby 	struct file *exe_file;
144238646013SJiri Slaby 
144390f31d0eSKonstantin Khlebnikov 	rcu_read_lock();
144490f31d0eSKonstantin Khlebnikov 	exe_file = rcu_dereference(mm->exe_file);
144590f31d0eSKonstantin Khlebnikov 	if (exe_file && !get_file_rcu(exe_file))
144690f31d0eSKonstantin Khlebnikov 		exe_file = NULL;
144790f31d0eSKonstantin Khlebnikov 	rcu_read_unlock();
144838646013SJiri Slaby 	return exe_file;
144938646013SJiri Slaby }
145038646013SJiri Slaby 
14511da177e4SLinus Torvalds /**
1452cd81a917SMateusz Guzik  * get_task_exe_file - acquire a reference to the task's executable file
1453cd81a917SMateusz Guzik  *
1454cd81a917SMateusz Guzik  * Returns %NULL if task's mm (if any) has no associated executable file or
1455cd81a917SMateusz Guzik  * this is a kernel thread with borrowed mm (see the comment above get_task_mm).
1456cd81a917SMateusz Guzik  * User must release file via fput().
1457cd81a917SMateusz Guzik  */
1458cd81a917SMateusz Guzik struct file *get_task_exe_file(struct task_struct *task)
1459cd81a917SMateusz Guzik {
1460cd81a917SMateusz Guzik 	struct file *exe_file = NULL;
1461cd81a917SMateusz Guzik 	struct mm_struct *mm;
1462cd81a917SMateusz Guzik 
1463cd81a917SMateusz Guzik 	task_lock(task);
1464cd81a917SMateusz Guzik 	mm = task->mm;
1465cd81a917SMateusz Guzik 	if (mm) {
1466cd81a917SMateusz Guzik 		if (!(task->flags & PF_KTHREAD))
1467cd81a917SMateusz Guzik 			exe_file = get_mm_exe_file(mm);
1468cd81a917SMateusz Guzik 	}
1469cd81a917SMateusz Guzik 	task_unlock(task);
1470cd81a917SMateusz Guzik 	return exe_file;
1471cd81a917SMateusz Guzik }
1472cd81a917SMateusz Guzik 
1473cd81a917SMateusz Guzik /**
14741da177e4SLinus Torvalds  * get_task_mm - acquire a reference to the task's mm
14751da177e4SLinus Torvalds  *
1476246bb0b1SOleg Nesterov  * Returns %NULL if the task has no mm.  Checks PF_KTHREAD (meaning
14771da177e4SLinus Torvalds  * this kernel workthread has transiently adopted a user mm with use_mm,
14781da177e4SLinus Torvalds  * to do its AIO) is not set and if so returns a reference to it, after
14791da177e4SLinus Torvalds  * bumping up the use count.  User must release the mm via mmput()
14801da177e4SLinus Torvalds  * after use.  Typically used by /proc and ptrace.
14811da177e4SLinus Torvalds  */
14821da177e4SLinus Torvalds struct mm_struct *get_task_mm(struct task_struct *task)
14831da177e4SLinus Torvalds {
14841da177e4SLinus Torvalds 	struct mm_struct *mm;
14851da177e4SLinus Torvalds 
14861da177e4SLinus Torvalds 	task_lock(task);
14871da177e4SLinus Torvalds 	mm = task->mm;
14881da177e4SLinus Torvalds 	if (mm) {
1489246bb0b1SOleg Nesterov 		if (task->flags & PF_KTHREAD)
14901da177e4SLinus Torvalds 			mm = NULL;
14911da177e4SLinus Torvalds 		else
14923fce371bSVegard Nossum 			mmget(mm);
14931da177e4SLinus Torvalds 	}
14941da177e4SLinus Torvalds 	task_unlock(task);
14951da177e4SLinus Torvalds 	return mm;
14961da177e4SLinus Torvalds }
14971da177e4SLinus Torvalds EXPORT_SYMBOL_GPL(get_task_mm);
14981da177e4SLinus Torvalds 
14998cdb878dSChristopher Yeoh struct mm_struct *mm_access(struct task_struct *task, unsigned int mode)
15008cdb878dSChristopher Yeoh {
15018cdb878dSChristopher Yeoh 	struct mm_struct *mm;
15028cdb878dSChristopher Yeoh 	int err;
15038cdb878dSChristopher Yeoh 
1504f7cfd871SEric W. Biederman 	err =  down_read_killable(&task->signal->exec_update_lock);
15058cdb878dSChristopher Yeoh 	if (err)
15068cdb878dSChristopher Yeoh 		return ERR_PTR(err);
15078cdb878dSChristopher Yeoh 
15088cdb878dSChristopher Yeoh 	mm = get_task_mm(task);
15098cdb878dSChristopher Yeoh 	if (mm && mm != current->mm &&
15108cdb878dSChristopher Yeoh 			!ptrace_may_access(task, mode)) {
15118cdb878dSChristopher Yeoh 		mmput(mm);
15128cdb878dSChristopher Yeoh 		mm = ERR_PTR(-EACCES);
15138cdb878dSChristopher Yeoh 	}
1514f7cfd871SEric W. Biederman 	up_read(&task->signal->exec_update_lock);
15158cdb878dSChristopher Yeoh 
15168cdb878dSChristopher Yeoh 	return mm;
15178cdb878dSChristopher Yeoh }
15188cdb878dSChristopher Yeoh 
151957b59c4aSOleg Nesterov static void complete_vfork_done(struct task_struct *tsk)
1520c415c3b4SOleg Nesterov {
1521d68b46feSOleg Nesterov 	struct completion *vfork;
1522c415c3b4SOleg Nesterov 
1523d68b46feSOleg Nesterov 	task_lock(tsk);
1524d68b46feSOleg Nesterov 	vfork = tsk->vfork_done;
1525d68b46feSOleg Nesterov 	if (likely(vfork)) {
1526c415c3b4SOleg Nesterov 		tsk->vfork_done = NULL;
1527d68b46feSOleg Nesterov 		complete(vfork);
1528d68b46feSOleg Nesterov 	}
1529d68b46feSOleg Nesterov 	task_unlock(tsk);
1530d68b46feSOleg Nesterov }
1531d68b46feSOleg Nesterov 
1532d68b46feSOleg Nesterov static int wait_for_vfork_done(struct task_struct *child,
1533d68b46feSOleg Nesterov 				struct completion *vfork)
1534d68b46feSOleg Nesterov {
1535f5d39b02SPeter Zijlstra 	unsigned int state = TASK_UNINTERRUPTIBLE|TASK_KILLABLE|TASK_FREEZABLE;
1536d68b46feSOleg Nesterov 	int killed;
1537d68b46feSOleg Nesterov 
153876f969e8SRoman Gushchin 	cgroup_enter_frozen();
1539f5d39b02SPeter Zijlstra 	killed = wait_for_completion_state(vfork, state);
154076f969e8SRoman Gushchin 	cgroup_leave_frozen(false);
1541d68b46feSOleg Nesterov 
1542d68b46feSOleg Nesterov 	if (killed) {
1543d68b46feSOleg Nesterov 		task_lock(child);
1544d68b46feSOleg Nesterov 		child->vfork_done = NULL;
1545d68b46feSOleg Nesterov 		task_unlock(child);
1546d68b46feSOleg Nesterov 	}
1547d68b46feSOleg Nesterov 
1548d68b46feSOleg Nesterov 	put_task_struct(child);
1549d68b46feSOleg Nesterov 	return killed;
1550c415c3b4SOleg Nesterov }
1551c415c3b4SOleg Nesterov 
15521da177e4SLinus Torvalds /* Please note the differences between mmput and mm_release.
15531da177e4SLinus Torvalds  * mmput is called whenever we stop holding onto a mm_struct,
15541da177e4SLinus Torvalds  * error success whatever.
15551da177e4SLinus Torvalds  *
15561da177e4SLinus Torvalds  * mm_release is called after a mm_struct has been removed
15571da177e4SLinus Torvalds  * from the current process.
15581da177e4SLinus Torvalds  *
15591da177e4SLinus Torvalds  * This difference is important for error handling, when we
15601da177e4SLinus Torvalds  * only half set up a mm_struct for a new process and need to restore
15611da177e4SLinus Torvalds  * the old one.  Because we mmput the new mm_struct before
15621da177e4SLinus Torvalds  * restoring the old one. . .
15631da177e4SLinus Torvalds  * Eric Biederman 10 January 1998
15641da177e4SLinus Torvalds  */
15654610ba7aSThomas Gleixner static void mm_release(struct task_struct *tsk, struct mm_struct *mm)
15661da177e4SLinus Torvalds {
15670326f5a9SSrikar Dronamraju 	uprobe_free_utask(tsk);
15680326f5a9SSrikar Dronamraju 
15691da177e4SLinus Torvalds 	/* Get rid of any cached register state */
15701da177e4SLinus Torvalds 	deactivate_mm(tsk, mm);
15711da177e4SLinus Torvalds 
1572fec1d011SRoland McGrath 	/*
1573735f2770SMichal Hocko 	 * Signal userspace if we're not exiting with a core dump
1574735f2770SMichal Hocko 	 * because we want to leave the value intact for debugging
1575735f2770SMichal Hocko 	 * purposes.
1576fec1d011SRoland McGrath 	 */
15779c8a8228SEric Dumazet 	if (tsk->clear_child_tid) {
157892307383SEric W. Biederman 		if (atomic_read(&mm->mm_users) > 1) {
15791da177e4SLinus Torvalds 			/*
15801da177e4SLinus Torvalds 			 * We don't check the error code - if userspace has
15811da177e4SLinus Torvalds 			 * not set up a proper pointer then tough luck.
15821da177e4SLinus Torvalds 			 */
15839c8a8228SEric Dumazet 			put_user(0, tsk->clear_child_tid);
15842de0db99SDominik Brodowski 			do_futex(tsk->clear_child_tid, FUTEX_WAKE,
15852de0db99SDominik Brodowski 					1, NULL, NULL, 0, 0);
15869c8a8228SEric Dumazet 		}
15879c8a8228SEric Dumazet 		tsk->clear_child_tid = NULL;
15881da177e4SLinus Torvalds 	}
1589f7505d64SKonstantin Khlebnikov 
1590f7505d64SKonstantin Khlebnikov 	/*
1591f7505d64SKonstantin Khlebnikov 	 * All done, finally we can wake up parent and return this mm to him.
1592f7505d64SKonstantin Khlebnikov 	 * Also kthread_stop() uses this completion for synchronization.
1593f7505d64SKonstantin Khlebnikov 	 */
1594f7505d64SKonstantin Khlebnikov 	if (tsk->vfork_done)
1595f7505d64SKonstantin Khlebnikov 		complete_vfork_done(tsk);
15961da177e4SLinus Torvalds }
15971da177e4SLinus Torvalds 
15984610ba7aSThomas Gleixner void exit_mm_release(struct task_struct *tsk, struct mm_struct *mm)
15994610ba7aSThomas Gleixner {
1600150d7158SThomas Gleixner 	futex_exit_release(tsk);
16014610ba7aSThomas Gleixner 	mm_release(tsk, mm);
16024610ba7aSThomas Gleixner }
16034610ba7aSThomas Gleixner 
16044610ba7aSThomas Gleixner void exec_mm_release(struct task_struct *tsk, struct mm_struct *mm)
16054610ba7aSThomas Gleixner {
1606150d7158SThomas Gleixner 	futex_exec_release(tsk);
16074610ba7aSThomas Gleixner 	mm_release(tsk, mm);
16084610ba7aSThomas Gleixner }
16094610ba7aSThomas Gleixner 
161013585fa0SNadav Amit /**
161113585fa0SNadav Amit  * dup_mm() - duplicates an existing mm structure
161213585fa0SNadav Amit  * @tsk: the task_struct with which the new mm will be associated.
161313585fa0SNadav Amit  * @oldmm: the mm to duplicate.
161413585fa0SNadav Amit  *
161513585fa0SNadav Amit  * Allocates a new mm structure and duplicates the provided @oldmm structure
161613585fa0SNadav Amit  * content into it.
161713585fa0SNadav Amit  *
161813585fa0SNadav Amit  * Return: the duplicated mm or NULL on failure.
1619a0a7ec30SJANAK DESAI  */
162013585fa0SNadav Amit static struct mm_struct *dup_mm(struct task_struct *tsk,
162113585fa0SNadav Amit 				struct mm_struct *oldmm)
1622a0a7ec30SJANAK DESAI {
162313585fa0SNadav Amit 	struct mm_struct *mm;
1624a0a7ec30SJANAK DESAI 	int err;
1625a0a7ec30SJANAK DESAI 
1626a0a7ec30SJANAK DESAI 	mm = allocate_mm();
1627a0a7ec30SJANAK DESAI 	if (!mm)
1628a0a7ec30SJANAK DESAI 		goto fail_nomem;
1629a0a7ec30SJANAK DESAI 
1630a0a7ec30SJANAK DESAI 	memcpy(mm, oldmm, sizeof(*mm));
1631a0a7ec30SJANAK DESAI 
1632bfedb589SEric W. Biederman 	if (!mm_init(mm, tsk, mm->user_ns))
1633a0a7ec30SJANAK DESAI 		goto fail_nomem;
1634a0a7ec30SJANAK DESAI 
1635a0a7ec30SJANAK DESAI 	err = dup_mmap(mm, oldmm);
1636a0a7ec30SJANAK DESAI 	if (err)
1637a0a7ec30SJANAK DESAI 		goto free_pt;
1638a0a7ec30SJANAK DESAI 
1639a0a7ec30SJANAK DESAI 	mm->hiwater_rss = get_mm_rss(mm);
1640a0a7ec30SJANAK DESAI 	mm->hiwater_vm = mm->total_vm;
1641a0a7ec30SJANAK DESAI 
1642801460d0SHiroshi Shimamoto 	if (mm->binfmt && !try_module_get(mm->binfmt->module))
1643801460d0SHiroshi Shimamoto 		goto free_pt;
1644801460d0SHiroshi Shimamoto 
1645a0a7ec30SJANAK DESAI 	return mm;
1646a0a7ec30SJANAK DESAI 
1647a0a7ec30SJANAK DESAI free_pt:
1648801460d0SHiroshi Shimamoto 	/* don't put binfmt in mmput, we haven't got module yet */
1649801460d0SHiroshi Shimamoto 	mm->binfmt = NULL;
1650c3f3ce04SAndrea Arcangeli 	mm_init_owner(mm, NULL);
1651a0a7ec30SJANAK DESAI 	mmput(mm);
1652a0a7ec30SJANAK DESAI 
1653a0a7ec30SJANAK DESAI fail_nomem:
1654a0a7ec30SJANAK DESAI 	return NULL;
1655a0a7ec30SJANAK DESAI }
1656a0a7ec30SJANAK DESAI 
16571da177e4SLinus Torvalds static int copy_mm(unsigned long clone_flags, struct task_struct *tsk)
16581da177e4SLinus Torvalds {
16591da177e4SLinus Torvalds 	struct mm_struct *mm, *oldmm;
16601da177e4SLinus Torvalds 
16611da177e4SLinus Torvalds 	tsk->min_flt = tsk->maj_flt = 0;
16621da177e4SLinus Torvalds 	tsk->nvcsw = tsk->nivcsw = 0;
166317406b82SMandeep Singh Baines #ifdef CONFIG_DETECT_HUNG_TASK
166417406b82SMandeep Singh Baines 	tsk->last_switch_count = tsk->nvcsw + tsk->nivcsw;
1665a2e51445SDmitry Vyukov 	tsk->last_switch_time = 0;
166617406b82SMandeep Singh Baines #endif
16671da177e4SLinus Torvalds 
16681da177e4SLinus Torvalds 	tsk->mm = NULL;
16691da177e4SLinus Torvalds 	tsk->active_mm = NULL;
16701da177e4SLinus Torvalds 
16711da177e4SLinus Torvalds 	/*
16721da177e4SLinus Torvalds 	 * Are we cloning a kernel thread?
16731da177e4SLinus Torvalds 	 *
16741da177e4SLinus Torvalds 	 * We need to steal a active VM for that..
16751da177e4SLinus Torvalds 	 */
16761da177e4SLinus Torvalds 	oldmm = current->mm;
16771da177e4SLinus Torvalds 	if (!oldmm)
16781da177e4SLinus Torvalds 		return 0;
16791da177e4SLinus Torvalds 
16801da177e4SLinus Torvalds 	if (clone_flags & CLONE_VM) {
16813fce371bSVegard Nossum 		mmget(oldmm);
16821da177e4SLinus Torvalds 		mm = oldmm;
1683a6895399SRolf Eike Beer 	} else {
168413585fa0SNadav Amit 		mm = dup_mm(tsk, current->mm);
16851da177e4SLinus Torvalds 		if (!mm)
1686a6895399SRolf Eike Beer 			return -ENOMEM;
1687a6895399SRolf Eike Beer 	}
16881da177e4SLinus Torvalds 
16891da177e4SLinus Torvalds 	tsk->mm = mm;
16901da177e4SLinus Torvalds 	tsk->active_mm = mm;
1691af7f588dSMathieu Desnoyers 	sched_mm_cid_fork(tsk);
16921da177e4SLinus Torvalds 	return 0;
16931da177e4SLinus Torvalds }
16941da177e4SLinus Torvalds 
1695a39bc516SAlexey Dobriyan static int copy_fs(unsigned long clone_flags, struct task_struct *tsk)
16961da177e4SLinus Torvalds {
1697498052bbSAl Viro 	struct fs_struct *fs = current->fs;
16981da177e4SLinus Torvalds 	if (clone_flags & CLONE_FS) {
1699498052bbSAl Viro 		/* tsk->fs is already what we want */
17002a4419b5SNick Piggin 		spin_lock(&fs->lock);
1701498052bbSAl Viro 		if (fs->in_exec) {
17022a4419b5SNick Piggin 			spin_unlock(&fs->lock);
1703498052bbSAl Viro 			return -EAGAIN;
1704498052bbSAl Viro 		}
1705498052bbSAl Viro 		fs->users++;
17062a4419b5SNick Piggin 		spin_unlock(&fs->lock);
17071da177e4SLinus Torvalds 		return 0;
17081da177e4SLinus Torvalds 	}
1709498052bbSAl Viro 	tsk->fs = copy_fs_struct(fs);
17101da177e4SLinus Torvalds 	if (!tsk->fs)
17111da177e4SLinus Torvalds 		return -ENOMEM;
17121da177e4SLinus Torvalds 	return 0;
17131da177e4SLinus Torvalds }
17141da177e4SLinus Torvalds 
1715a016f338SJANAK DESAI static int copy_files(unsigned long clone_flags, struct task_struct *tsk)
1716a016f338SJANAK DESAI {
1717a016f338SJANAK DESAI 	struct files_struct *oldf, *newf;
1718a016f338SJANAK DESAI 	int error = 0;
1719a016f338SJANAK DESAI 
1720a016f338SJANAK DESAI 	/*
1721a016f338SJANAK DESAI 	 * A background process may not have any files ...
1722a016f338SJANAK DESAI 	 */
1723a016f338SJANAK DESAI 	oldf = current->files;
1724a016f338SJANAK DESAI 	if (!oldf)
1725a016f338SJANAK DESAI 		goto out;
1726a016f338SJANAK DESAI 
1727a016f338SJANAK DESAI 	if (clone_flags & CLONE_FILES) {
1728a016f338SJANAK DESAI 		atomic_inc(&oldf->count);
1729a016f338SJANAK DESAI 		goto out;
1730a016f338SJANAK DESAI 	}
1731a016f338SJANAK DESAI 
173260997c3dSChristian Brauner 	newf = dup_fd(oldf, NR_OPEN_MAX, &error);
1733a016f338SJANAK DESAI 	if (!newf)
1734a016f338SJANAK DESAI 		goto out;
1735a016f338SJANAK DESAI 
1736a016f338SJANAK DESAI 	tsk->files = newf;
1737a016f338SJANAK DESAI 	error = 0;
1738a016f338SJANAK DESAI out:
1739a016f338SJANAK DESAI 	return error;
1740a016f338SJANAK DESAI }
1741a016f338SJANAK DESAI 
1742a39bc516SAlexey Dobriyan static int copy_sighand(unsigned long clone_flags, struct task_struct *tsk)
17431da177e4SLinus Torvalds {
17441da177e4SLinus Torvalds 	struct sighand_struct *sig;
17451da177e4SLinus Torvalds 
174660348802SZhaolei 	if (clone_flags & CLONE_SIGHAND) {
1747d036bda7SElena Reshetova 		refcount_inc(&current->sighand->count);
17481da177e4SLinus Torvalds 		return 0;
17491da177e4SLinus Torvalds 	}
17501da177e4SLinus Torvalds 	sig = kmem_cache_alloc(sighand_cachep, GFP_KERNEL);
17510c282b06SMadhuparna Bhowmik 	RCU_INIT_POINTER(tsk->sighand, sig);
17521da177e4SLinus Torvalds 	if (!sig)
17531da177e4SLinus Torvalds 		return -ENOMEM;
17549d7fb042SPeter Zijlstra 
1755d036bda7SElena Reshetova 	refcount_set(&sig->count, 1);
175606e62a46SJann Horn 	spin_lock_irq(&current->sighand->siglock);
17571da177e4SLinus Torvalds 	memcpy(sig->action, current->sighand->action, sizeof(sig->action));
175806e62a46SJann Horn 	spin_unlock_irq(&current->sighand->siglock);
1759b612e5dfSChristian Brauner 
1760b612e5dfSChristian Brauner 	/* Reset all signal handler not set to SIG_IGN to SIG_DFL. */
1761b612e5dfSChristian Brauner 	if (clone_flags & CLONE_CLEAR_SIGHAND)
1762b612e5dfSChristian Brauner 		flush_signal_handlers(tsk, 0);
1763b612e5dfSChristian Brauner 
17641da177e4SLinus Torvalds 	return 0;
17651da177e4SLinus Torvalds }
17661da177e4SLinus Torvalds 
1767a7e5328aSOleg Nesterov void __cleanup_sighand(struct sighand_struct *sighand)
1768c81addc9SOleg Nesterov {
1769d036bda7SElena Reshetova 	if (refcount_dec_and_test(&sighand->count)) {
1770d80e731eSOleg Nesterov 		signalfd_cleanup(sighand);
1771392809b2SOleg Nesterov 		/*
17725f0d5a3aSPaul E. McKenney 		 * sighand_cachep is SLAB_TYPESAFE_BY_RCU so we can free it
1773392809b2SOleg Nesterov 		 * without an RCU grace period, see __lock_task_sighand().
1774392809b2SOleg Nesterov 		 */
1775c81addc9SOleg Nesterov 		kmem_cache_free(sighand_cachep, sighand);
1776c81addc9SOleg Nesterov 	}
1777d80e731eSOleg Nesterov }
1778c81addc9SOleg Nesterov 
1779f06febc9SFrank Mayhar /*
1780f06febc9SFrank Mayhar  * Initialize POSIX timer handling for a thread group.
1781f06febc9SFrank Mayhar  */
1782f06febc9SFrank Mayhar static void posix_cpu_timers_init_group(struct signal_struct *sig)
1783f06febc9SFrank Mayhar {
17842b69942fSThomas Gleixner 	struct posix_cputimers *pct = &sig->posix_cputimers;
178578d7d407SJiri Slaby 	unsigned long cpu_limit;
178678d7d407SJiri Slaby 
1787316c1608SJason Low 	cpu_limit = READ_ONCE(sig->rlim[RLIMIT_CPU].rlim_cur);
17883a245c0fSThomas Gleixner 	posix_cputimers_group_init(pct, cpu_limit);
17896279a751SOleg Nesterov }
17906279a751SOleg Nesterov 
1791a39bc516SAlexey Dobriyan static int copy_signal(unsigned long clone_flags, struct task_struct *tsk)
17921da177e4SLinus Torvalds {
17931da177e4SLinus Torvalds 	struct signal_struct *sig;
17941da177e4SLinus Torvalds 
17954ab6c083SOleg Nesterov 	if (clone_flags & CLONE_THREAD)
1796490dea45SPeter Zijlstra 		return 0;
17976279a751SOleg Nesterov 
1798a56704efSVeaceslav Falico 	sig = kmem_cache_zalloc(signal_cachep, GFP_KERNEL);
17991da177e4SLinus Torvalds 	tsk->signal = sig;
18001da177e4SLinus Torvalds 	if (!sig)
18011da177e4SLinus Torvalds 		return -ENOMEM;
18021da177e4SLinus Torvalds 
1803b3ac022cSOleg Nesterov 	sig->nr_threads = 1;
1804d80f7d7bSEric W. Biederman 	sig->quick_threads = 1;
18051da177e4SLinus Torvalds 	atomic_set(&sig->live, 1);
180660d4de3fSElena Reshetova 	refcount_set(&sig->sigcnt, 1);
18070c740d0aSOleg Nesterov 
18080c740d0aSOleg Nesterov 	/* list_add(thread_node, thread_head) without INIT_LIST_HEAD() */
18090c740d0aSOleg Nesterov 	sig->thread_head = (struct list_head)LIST_HEAD_INIT(tsk->thread_node);
18100c740d0aSOleg Nesterov 	tsk->thread_node = (struct list_head)LIST_HEAD_INIT(sig->thread_head);
18110c740d0aSOleg Nesterov 
18121da177e4SLinus Torvalds 	init_waitqueue_head(&sig->wait_chldexit);
1813db51aeccSOleg Nesterov 	sig->curr_target = tsk;
18141da177e4SLinus Torvalds 	init_sigpending(&sig->shared_pending);
1815c3ad2c3bSEric W. Biederman 	INIT_HLIST_HEAD(&sig->multiprocess);
1816e78c3496SRik van Riel 	seqlock_init(&sig->stats_lock);
18179d7fb042SPeter Zijlstra 	prev_cputime_init(&sig->prev_cputime);
18181da177e4SLinus Torvalds 
1819baa73d9eSNicolas Pitre #ifdef CONFIG_POSIX_TIMERS
1820b18b6a9cSNicolas Pitre 	INIT_LIST_HEAD(&sig->posix_timers);
1821c9cb2e3dSThomas Gleixner 	hrtimer_init(&sig->real_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
18221da177e4SLinus Torvalds 	sig->real_timer.function = it_real_fn;
1823baa73d9eSNicolas Pitre #endif
18241da177e4SLinus Torvalds 
18251da177e4SLinus Torvalds 	task_lock(current->group_leader);
18261da177e4SLinus Torvalds 	memcpy(sig->rlim, current->signal->rlim, sizeof sig->rlim);
18271da177e4SLinus Torvalds 	task_unlock(current->group_leader);
18281da177e4SLinus Torvalds 
18296279a751SOleg Nesterov 	posix_cpu_timers_init_group(sig);
18306279a751SOleg Nesterov 
1831522ed776SMiloslav Trmac 	tty_audit_fork(sig);
18325091faa4SMike Galbraith 	sched_autogroup_fork(sig);
1833522ed776SMiloslav Trmac 
1834a63d83f4SDavid Rientjes 	sig->oom_score_adj = current->signal->oom_score_adj;
1835dabb16f6SMandeep Singh Baines 	sig->oom_score_adj_min = current->signal->oom_score_adj_min;
183628b83c51SKOSAKI Motohiro 
18379b1bf12dSKOSAKI Motohiro 	mutex_init(&sig->cred_guard_mutex);
1838f7cfd871SEric W. Biederman 	init_rwsem(&sig->exec_update_lock);
18399b1bf12dSKOSAKI Motohiro 
18401da177e4SLinus Torvalds 	return 0;
18411da177e4SLinus Torvalds }
18421da177e4SLinus Torvalds 
1843dbd95212SKees Cook static void copy_seccomp(struct task_struct *p)
1844dbd95212SKees Cook {
1845dbd95212SKees Cook #ifdef CONFIG_SECCOMP
1846dbd95212SKees Cook 	/*
1847dbd95212SKees Cook 	 * Must be called with sighand->lock held, which is common to
1848dbd95212SKees Cook 	 * all threads in the group. Holding cred_guard_mutex is not
1849dbd95212SKees Cook 	 * needed because this new task is not yet running and cannot
1850dbd95212SKees Cook 	 * be racing exec.
1851dbd95212SKees Cook 	 */
185269f6a34bSGuenter Roeck 	assert_spin_locked(&current->sighand->siglock);
1853dbd95212SKees Cook 
1854dbd95212SKees Cook 	/* Ref-count the new filter user, and assign it. */
1855dbd95212SKees Cook 	get_seccomp_filter(current);
1856dbd95212SKees Cook 	p->seccomp = current->seccomp;
1857dbd95212SKees Cook 
1858dbd95212SKees Cook 	/*
1859dbd95212SKees Cook 	 * Explicitly enable no_new_privs here in case it got set
1860dbd95212SKees Cook 	 * between the task_struct being duplicated and holding the
1861dbd95212SKees Cook 	 * sighand lock. The seccomp state and nnp must be in sync.
1862dbd95212SKees Cook 	 */
1863dbd95212SKees Cook 	if (task_no_new_privs(current))
1864dbd95212SKees Cook 		task_set_no_new_privs(p);
1865dbd95212SKees Cook 
1866dbd95212SKees Cook 	/*
1867dbd95212SKees Cook 	 * If the parent gained a seccomp mode after copying thread
1868dbd95212SKees Cook 	 * flags and between before we held the sighand lock, we have
1869dbd95212SKees Cook 	 * to manually enable the seccomp thread flag here.
1870dbd95212SKees Cook 	 */
1871dbd95212SKees Cook 	if (p->seccomp.mode != SECCOMP_MODE_DISABLED)
187223d67a54SGabriel Krisman Bertazi 		set_task_syscall_work(p, SECCOMP);
1873dbd95212SKees Cook #endif
1874dbd95212SKees Cook }
1875dbd95212SKees Cook 
187617da2bd9SHeiko Carstens SYSCALL_DEFINE1(set_tid_address, int __user *, tidptr)
18771da177e4SLinus Torvalds {
18781da177e4SLinus Torvalds 	current->clear_child_tid = tidptr;
18791da177e4SLinus Torvalds 
1880b488893aSPavel Emelyanov 	return task_pid_vnr(current);
18811da177e4SLinus Torvalds }
18821da177e4SLinus Torvalds 
1883a39bc516SAlexey Dobriyan static void rt_mutex_init_task(struct task_struct *p)
188423f78d4aSIngo Molnar {
18851d615482SThomas Gleixner 	raw_spin_lock_init(&p->pi_lock);
1886e29e175bSZilvinas Valinskas #ifdef CONFIG_RT_MUTEXES
1887a23ba907SDavidlohr Bueso 	p->pi_waiters = RB_ROOT_CACHED;
1888e96a7705SXunlei Pang 	p->pi_top_task = NULL;
188923f78d4aSIngo Molnar 	p->pi_blocked_on = NULL;
189023f78d4aSIngo Molnar #endif
189123f78d4aSIngo Molnar }
189223f78d4aSIngo Molnar 
18932c470475SEric W. Biederman static inline void init_task_pid_links(struct task_struct *task)
18942c470475SEric W. Biederman {
18952c470475SEric W. Biederman 	enum pid_type type;
18962c470475SEric W. Biederman 
189796e1e984SAlexander Guril 	for (type = PIDTYPE_PID; type < PIDTYPE_MAX; ++type)
18982c470475SEric W. Biederman 		INIT_HLIST_NODE(&task->pid_links[type]);
18992c470475SEric W. Biederman }
19002c470475SEric W. Biederman 
190181907739SOleg Nesterov static inline void
190281907739SOleg Nesterov init_task_pid(struct task_struct *task, enum pid_type type, struct pid *pid)
190381907739SOleg Nesterov {
19042c470475SEric W. Biederman 	if (type == PIDTYPE_PID)
19052c470475SEric W. Biederman 		task->thread_pid = pid;
19062c470475SEric W. Biederman 	else
19072c470475SEric W. Biederman 		task->signal->pids[type] = pid;
190881907739SOleg Nesterov }
190981907739SOleg Nesterov 
19106bfbaa51SIngo Molnar static inline void rcu_copy_process(struct task_struct *p)
19116bfbaa51SIngo Molnar {
19126bfbaa51SIngo Molnar #ifdef CONFIG_PREEMPT_RCU
19136bfbaa51SIngo Molnar 	p->rcu_read_lock_nesting = 0;
19146bfbaa51SIngo Molnar 	p->rcu_read_unlock_special.s = 0;
19156bfbaa51SIngo Molnar 	p->rcu_blocked_node = NULL;
19166bfbaa51SIngo Molnar 	INIT_LIST_HEAD(&p->rcu_node_entry);
19176bfbaa51SIngo Molnar #endif /* #ifdef CONFIG_PREEMPT_RCU */
19186bfbaa51SIngo Molnar #ifdef CONFIG_TASKS_RCU
19196bfbaa51SIngo Molnar 	p->rcu_tasks_holdout = false;
19206bfbaa51SIngo Molnar 	INIT_LIST_HEAD(&p->rcu_tasks_holdout_list);
19216bfbaa51SIngo Molnar 	p->rcu_tasks_idle_cpu = -1;
19226bfbaa51SIngo Molnar #endif /* #ifdef CONFIG_TASKS_RCU */
1923d5f177d3SPaul E. McKenney #ifdef CONFIG_TASKS_TRACE_RCU
1924d5f177d3SPaul E. McKenney 	p->trc_reader_nesting = 0;
1925276c4104SPaul E. McKenney 	p->trc_reader_special.s = 0;
1926d5f177d3SPaul E. McKenney 	INIT_LIST_HEAD(&p->trc_holdout_list);
1927434c9eefSPaul E. McKenney 	INIT_LIST_HEAD(&p->trc_blkd_node);
1928d5f177d3SPaul E. McKenney #endif /* #ifdef CONFIG_TASKS_TRACE_RCU */
19296bfbaa51SIngo Molnar }
19306bfbaa51SIngo Molnar 
19313695eae5SChristian Brauner struct pid *pidfd_pid(const struct file *file)
19323695eae5SChristian Brauner {
19333695eae5SChristian Brauner 	if (file->f_op == &pidfd_fops)
19343695eae5SChristian Brauner 		return file->private_data;
19353695eae5SChristian Brauner 
19363695eae5SChristian Brauner 	return ERR_PTR(-EBADF);
19373695eae5SChristian Brauner }
19383695eae5SChristian Brauner 
1939b3e58382SChristian Brauner static int pidfd_release(struct inode *inode, struct file *file)
1940b3e58382SChristian Brauner {
1941b3e58382SChristian Brauner 	struct pid *pid = file->private_data;
1942b3e58382SChristian Brauner 
1943b3e58382SChristian Brauner 	file->private_data = NULL;
1944b3e58382SChristian Brauner 	put_pid(pid);
1945b3e58382SChristian Brauner 	return 0;
1946b3e58382SChristian Brauner }
1947b3e58382SChristian Brauner 
1948b3e58382SChristian Brauner #ifdef CONFIG_PROC_FS
194915d42eb2SChristian Kellner /**
195015d42eb2SChristian Kellner  * pidfd_show_fdinfo - print information about a pidfd
195115d42eb2SChristian Kellner  * @m: proc fdinfo file
195215d42eb2SChristian Kellner  * @f: file referencing a pidfd
195315d42eb2SChristian Kellner  *
195415d42eb2SChristian Kellner  * Pid:
195515d42eb2SChristian Kellner  * This function will print the pid that a given pidfd refers to in the
195615d42eb2SChristian Kellner  * pid namespace of the procfs instance.
195715d42eb2SChristian Kellner  * If the pid namespace of the process is not a descendant of the pid
195815d42eb2SChristian Kellner  * namespace of the procfs instance 0 will be shown as its pid. This is
195915d42eb2SChristian Kellner  * similar to calling getppid() on a process whose parent is outside of
196015d42eb2SChristian Kellner  * its pid namespace.
196115d42eb2SChristian Kellner  *
196215d42eb2SChristian Kellner  * NSpid:
196315d42eb2SChristian Kellner  * If pid namespaces are supported then this function will also print
196415d42eb2SChristian Kellner  * the pid of a given pidfd refers to for all descendant pid namespaces
196515d42eb2SChristian Kellner  * starting from the current pid namespace of the instance, i.e. the
196615d42eb2SChristian Kellner  * Pid field and the first entry in the NSpid field will be identical.
196715d42eb2SChristian Kellner  * If the pid namespace of the process is not a descendant of the pid
196815d42eb2SChristian Kellner  * namespace of the procfs instance 0 will be shown as its first NSpid
196915d42eb2SChristian Kellner  * entry and no others will be shown.
197015d42eb2SChristian Kellner  * Note that this differs from the Pid and NSpid fields in
197115d42eb2SChristian Kellner  * /proc/<pid>/status where Pid and NSpid are always shown relative to
197215d42eb2SChristian Kellner  * the  pid namespace of the procfs instance. The difference becomes
197315d42eb2SChristian Kellner  * obvious when sending around a pidfd between pid namespaces from a
1974a8ca6b13SXiaofeng Cao  * different branch of the tree, i.e. where no ancestral relation is
197515d42eb2SChristian Kellner  * present between the pid namespaces:
197615d42eb2SChristian Kellner  * - create two new pid namespaces ns1 and ns2 in the initial pid
197715d42eb2SChristian Kellner  *   namespace (also take care to create new mount namespaces in the
197815d42eb2SChristian Kellner  *   new pid namespace and mount procfs)
197915d42eb2SChristian Kellner  * - create a process with a pidfd in ns1
198015d42eb2SChristian Kellner  * - send pidfd from ns1 to ns2
198115d42eb2SChristian Kellner  * - read /proc/self/fdinfo/<pidfd> and observe that both Pid and NSpid
198215d42eb2SChristian Kellner  *   have exactly one entry, which is 0
198315d42eb2SChristian Kellner  */
1984b3e58382SChristian Brauner static void pidfd_show_fdinfo(struct seq_file *m, struct file *f)
1985b3e58382SChristian Brauner {
1986b3e58382SChristian Brauner 	struct pid *pid = f->private_data;
19873d6d8da4SChristian Brauner 	struct pid_namespace *ns;
19883d6d8da4SChristian Brauner 	pid_t nr = -1;
1989b3e58382SChristian Brauner 
19903d6d8da4SChristian Brauner 	if (likely(pid_has_task(pid, PIDTYPE_PID))) {
19919d78edeaSAlexey Gladkov 		ns = proc_pid_ns(file_inode(m->file)->i_sb);
19923d6d8da4SChristian Brauner 		nr = pid_nr_ns(pid, ns);
19933d6d8da4SChristian Brauner 	}
19943d6d8da4SChristian Brauner 
19953d6d8da4SChristian Brauner 	seq_put_decimal_ll(m, "Pid:\t", nr);
199615d42eb2SChristian Kellner 
199715d42eb2SChristian Kellner #ifdef CONFIG_PID_NS
19983d6d8da4SChristian Brauner 	seq_put_decimal_ll(m, "\nNSpid:\t", nr);
19993d6d8da4SChristian Brauner 	if (nr > 0) {
200015d42eb2SChristian Kellner 		int i;
200115d42eb2SChristian Kellner 
200215d42eb2SChristian Kellner 		/* If nr is non-zero it means that 'pid' is valid and that
200315d42eb2SChristian Kellner 		 * ns, i.e. the pid namespace associated with the procfs
200415d42eb2SChristian Kellner 		 * instance, is in the pid namespace hierarchy of pid.
200515d42eb2SChristian Kellner 		 * Start at one below the already printed level.
200615d42eb2SChristian Kellner 		 */
200715d42eb2SChristian Kellner 		for (i = ns->level + 1; i <= pid->level; i++)
20083d6d8da4SChristian Brauner 			seq_put_decimal_ll(m, "\t", pid->numbers[i].nr);
200915d42eb2SChristian Kellner 	}
201015d42eb2SChristian Kellner #endif
2011b3e58382SChristian Brauner 	seq_putc(m, '\n');
2012b3e58382SChristian Brauner }
2013b3e58382SChristian Brauner #endif
2014b3e58382SChristian Brauner 
2015b53b0b9dSJoel Fernandes (Google) /*
2016b53b0b9dSJoel Fernandes (Google)  * Poll support for process exit notification.
2017b53b0b9dSJoel Fernandes (Google)  */
20189e77716aSLuc Van Oostenryck static __poll_t pidfd_poll(struct file *file, struct poll_table_struct *pts)
2019b53b0b9dSJoel Fernandes (Google) {
2020b53b0b9dSJoel Fernandes (Google) 	struct pid *pid = file->private_data;
20219e77716aSLuc Van Oostenryck 	__poll_t poll_flags = 0;
2022b53b0b9dSJoel Fernandes (Google) 
2023b53b0b9dSJoel Fernandes (Google) 	poll_wait(file, &pid->wait_pidfd, pts);
2024b53b0b9dSJoel Fernandes (Google) 
2025b53b0b9dSJoel Fernandes (Google) 	/*
2026b53b0b9dSJoel Fernandes (Google) 	 * Inform pollers only when the whole thread group exits.
2027b53b0b9dSJoel Fernandes (Google) 	 * If the thread group leader exits before all other threads in the
2028b53b0b9dSJoel Fernandes (Google) 	 * group, then poll(2) should block, similar to the wait(2) family.
2029b53b0b9dSJoel Fernandes (Google) 	 */
203038fd525aSEric W. Biederman 	if (thread_group_exited(pid))
20319e77716aSLuc Van Oostenryck 		poll_flags = EPOLLIN | EPOLLRDNORM;
2032b53b0b9dSJoel Fernandes (Google) 
2033b53b0b9dSJoel Fernandes (Google) 	return poll_flags;
2034b53b0b9dSJoel Fernandes (Google) }
2035b53b0b9dSJoel Fernandes (Google) 
2036b3e58382SChristian Brauner const struct file_operations pidfd_fops = {
2037b3e58382SChristian Brauner 	.release = pidfd_release,
2038b53b0b9dSJoel Fernandes (Google) 	.poll = pidfd_poll,
2039b3e58382SChristian Brauner #ifdef CONFIG_PROC_FS
2040b3e58382SChristian Brauner 	.show_fdinfo = pidfd_show_fdinfo,
2041b3e58382SChristian Brauner #endif
2042b3e58382SChristian Brauner };
2043b3e58382SChristian Brauner 
2044c3f3ce04SAndrea Arcangeli static void __delayed_free_task(struct rcu_head *rhp)
2045c3f3ce04SAndrea Arcangeli {
2046c3f3ce04SAndrea Arcangeli 	struct task_struct *tsk = container_of(rhp, struct task_struct, rcu);
2047c3f3ce04SAndrea Arcangeli 
2048c3f3ce04SAndrea Arcangeli 	free_task(tsk);
2049c3f3ce04SAndrea Arcangeli }
2050c3f3ce04SAndrea Arcangeli 
2051c3f3ce04SAndrea Arcangeli static __always_inline void delayed_free_task(struct task_struct *tsk)
2052c3f3ce04SAndrea Arcangeli {
2053c3f3ce04SAndrea Arcangeli 	if (IS_ENABLED(CONFIG_MEMCG))
2054c3f3ce04SAndrea Arcangeli 		call_rcu(&tsk->rcu, __delayed_free_task);
2055c3f3ce04SAndrea Arcangeli 	else
2056c3f3ce04SAndrea Arcangeli 		free_task(tsk);
2057c3f3ce04SAndrea Arcangeli }
2058c3f3ce04SAndrea Arcangeli 
205967197a4fSSuren Baghdasaryan static void copy_oom_score_adj(u64 clone_flags, struct task_struct *tsk)
206067197a4fSSuren Baghdasaryan {
206167197a4fSSuren Baghdasaryan 	/* Skip if kernel thread */
206267197a4fSSuren Baghdasaryan 	if (!tsk->mm)
206367197a4fSSuren Baghdasaryan 		return;
206467197a4fSSuren Baghdasaryan 
206567197a4fSSuren Baghdasaryan 	/* Skip if spawning a thread or using vfork */
206667197a4fSSuren Baghdasaryan 	if ((clone_flags & (CLONE_VM | CLONE_THREAD | CLONE_VFORK)) != CLONE_VM)
206767197a4fSSuren Baghdasaryan 		return;
206867197a4fSSuren Baghdasaryan 
206967197a4fSSuren Baghdasaryan 	/* We need to synchronize with __set_oom_adj */
207067197a4fSSuren Baghdasaryan 	mutex_lock(&oom_adj_mutex);
207167197a4fSSuren Baghdasaryan 	set_bit(MMF_MULTIPROCESS, &tsk->mm->flags);
207267197a4fSSuren Baghdasaryan 	/* Update the values in case they were changed after copy_signal */
207367197a4fSSuren Baghdasaryan 	tsk->signal->oom_score_adj = current->signal->oom_score_adj;
207467197a4fSSuren Baghdasaryan 	tsk->signal->oom_score_adj_min = current->signal->oom_score_adj_min;
207567197a4fSSuren Baghdasaryan 	mutex_unlock(&oom_adj_mutex);
207667197a4fSSuren Baghdasaryan }
207767197a4fSSuren Baghdasaryan 
207879257534SDaniel Bristot de Oliveira #ifdef CONFIG_RV
207979257534SDaniel Bristot de Oliveira static void rv_task_fork(struct task_struct *p)
208079257534SDaniel Bristot de Oliveira {
208179257534SDaniel Bristot de Oliveira 	int i;
208279257534SDaniel Bristot de Oliveira 
208379257534SDaniel Bristot de Oliveira 	for (i = 0; i < RV_PER_TASK_MONITORS; i++)
208479257534SDaniel Bristot de Oliveira 		p->rv[i].da_mon.monitoring = false;
208579257534SDaniel Bristot de Oliveira }
208679257534SDaniel Bristot de Oliveira #else
208779257534SDaniel Bristot de Oliveira #define rv_task_fork(p) do {} while (0)
208879257534SDaniel Bristot de Oliveira #endif
208979257534SDaniel Bristot de Oliveira 
2090f06febc9SFrank Mayhar /*
20911da177e4SLinus Torvalds  * This creates a new process as a copy of the old one,
20921da177e4SLinus Torvalds  * but does not actually start it yet.
20931da177e4SLinus Torvalds  *
20941da177e4SLinus Torvalds  * It copies the registers, and all the appropriate
20951da177e4SLinus Torvalds  * parts of the process environment (as per the clone
20961da177e4SLinus Torvalds  * flags). The actual kick-off is left to the caller.
20971da177e4SLinus Torvalds  */
20980766f788SEmese Revfy static __latent_entropy struct task_struct *copy_process(
209909a05394SRoland McGrath 					struct pid *pid,
21003033f14aSJosh Triplett 					int trace,
21017f192e3cSChristian Brauner 					int node,
21027f192e3cSChristian Brauner 					struct kernel_clone_args *args)
21031da177e4SLinus Torvalds {
2104b3e58382SChristian Brauner 	int pidfd = -1, retval;
2105a24efe62SMariusz Kozlowski 	struct task_struct *p;
2106c3ad2c3bSEric W. Biederman 	struct multiprocess_signals delayed;
21076fd2fe49SAl Viro 	struct file *pidfile = NULL;
2108c5febea0SEric W. Biederman 	const u64 clone_flags = args->flags;
2109769071acSAndrei Vagin 	struct nsproxy *nsp = current->nsproxy;
21101da177e4SLinus Torvalds 
2111667b6094SMarcos Paulo de Souza 	/*
2112667b6094SMarcos Paulo de Souza 	 * Don't allow sharing the root directory with processes in a different
2113667b6094SMarcos Paulo de Souza 	 * namespace
2114667b6094SMarcos Paulo de Souza 	 */
21151da177e4SLinus Torvalds 	if ((clone_flags & (CLONE_NEWNS|CLONE_FS)) == (CLONE_NEWNS|CLONE_FS))
21161da177e4SLinus Torvalds 		return ERR_PTR(-EINVAL);
21171da177e4SLinus Torvalds 
2118e66eded8SEric W. Biederman 	if ((clone_flags & (CLONE_NEWUSER|CLONE_FS)) == (CLONE_NEWUSER|CLONE_FS))
2119e66eded8SEric W. Biederman 		return ERR_PTR(-EINVAL);
2120e66eded8SEric W. Biederman 
21211da177e4SLinus Torvalds 	/*
21221da177e4SLinus Torvalds 	 * Thread groups must share signals as well, and detached threads
21231da177e4SLinus Torvalds 	 * can only be started up within the thread group.
21241da177e4SLinus Torvalds 	 */
21251da177e4SLinus Torvalds 	if ((clone_flags & CLONE_THREAD) && !(clone_flags & CLONE_SIGHAND))
21261da177e4SLinus Torvalds 		return ERR_PTR(-EINVAL);
21271da177e4SLinus Torvalds 
21281da177e4SLinus Torvalds 	/*
21291da177e4SLinus Torvalds 	 * Shared signal handlers imply shared VM. By way of the above,
21301da177e4SLinus Torvalds 	 * thread groups also imply shared VM. Blocking this case allows
21311da177e4SLinus Torvalds 	 * for various simplifications in other code.
21321da177e4SLinus Torvalds 	 */
21331da177e4SLinus Torvalds 	if ((clone_flags & CLONE_SIGHAND) && !(clone_flags & CLONE_VM))
21341da177e4SLinus Torvalds 		return ERR_PTR(-EINVAL);
21351da177e4SLinus Torvalds 
2136123be07bSSukadev Bhattiprolu 	/*
2137123be07bSSukadev Bhattiprolu 	 * Siblings of global init remain as zombies on exit since they are
2138123be07bSSukadev Bhattiprolu 	 * not reaped by their parent (swapper). To solve this and to avoid
2139123be07bSSukadev Bhattiprolu 	 * multi-rooted process trees, prevent global and container-inits
2140123be07bSSukadev Bhattiprolu 	 * from creating siblings.
2141123be07bSSukadev Bhattiprolu 	 */
2142123be07bSSukadev Bhattiprolu 	if ((clone_flags & CLONE_PARENT) &&
2143123be07bSSukadev Bhattiprolu 				current->signal->flags & SIGNAL_UNKILLABLE)
2144123be07bSSukadev Bhattiprolu 		return ERR_PTR(-EINVAL);
2145123be07bSSukadev Bhattiprolu 
21468382fcacSEric W. Biederman 	/*
214740a0d32dSOleg Nesterov 	 * If the new process will be in a different pid or user namespace
2148faf00da5SEric W. Biederman 	 * do not allow it to share a thread group with the forking task.
21498382fcacSEric W. Biederman 	 */
2150faf00da5SEric W. Biederman 	if (clone_flags & CLONE_THREAD) {
215140a0d32dSOleg Nesterov 		if ((clone_flags & (CLONE_NEWUSER | CLONE_NEWPID)) ||
2152769071acSAndrei Vagin 		    (task_active_pid_ns(current) != nsp->pid_ns_for_children))
2153769071acSAndrei Vagin 			return ERR_PTR(-EINVAL);
2154769071acSAndrei Vagin 	}
2155769071acSAndrei Vagin 
2156b3e58382SChristian Brauner 	if (clone_flags & CLONE_PIDFD) {
2157b3e58382SChristian Brauner 		/*
2158b3e58382SChristian Brauner 		 * - CLONE_DETACHED is blocked so that we can potentially
2159b3e58382SChristian Brauner 		 *   reuse it later for CLONE_PIDFD.
2160b3e58382SChristian Brauner 		 * - CLONE_THREAD is blocked until someone really needs it.
2161b3e58382SChristian Brauner 		 */
21627f192e3cSChristian Brauner 		if (clone_flags & (CLONE_DETACHED | CLONE_THREAD))
2163b3e58382SChristian Brauner 			return ERR_PTR(-EINVAL);
2164b3e58382SChristian Brauner 	}
2165b3e58382SChristian Brauner 
2166c3ad2c3bSEric W. Biederman 	/*
2167c3ad2c3bSEric W. Biederman 	 * Force any signals received before this point to be delivered
2168c3ad2c3bSEric W. Biederman 	 * before the fork happens.  Collect up signals sent to multiple
2169c3ad2c3bSEric W. Biederman 	 * processes that happen during the fork and delay them so that
2170c3ad2c3bSEric W. Biederman 	 * they appear to happen after the fork.
2171c3ad2c3bSEric W. Biederman 	 */
2172c3ad2c3bSEric W. Biederman 	sigemptyset(&delayed.signal);
2173c3ad2c3bSEric W. Biederman 	INIT_HLIST_NODE(&delayed.node);
2174c3ad2c3bSEric W. Biederman 
2175c3ad2c3bSEric W. Biederman 	spin_lock_irq(&current->sighand->siglock);
2176c3ad2c3bSEric W. Biederman 	if (!(clone_flags & CLONE_THREAD))
2177c3ad2c3bSEric W. Biederman 		hlist_add_head(&delayed.node, &current->signal->multiprocess);
2178c3ad2c3bSEric W. Biederman 	recalc_sigpending();
2179c3ad2c3bSEric W. Biederman 	spin_unlock_irq(&current->sighand->siglock);
2180c3ad2c3bSEric W. Biederman 	retval = -ERESTARTNOINTR;
218166ae0d1eSJens Axboe 	if (task_sigpending(current))
2182c3ad2c3bSEric W. Biederman 		goto fork_out;
2183c3ad2c3bSEric W. Biederman 
21841da177e4SLinus Torvalds 	retval = -ENOMEM;
2185725fc629SAndi Kleen 	p = dup_task_struct(current, node);
21861da177e4SLinus Torvalds 	if (!p)
21871da177e4SLinus Torvalds 		goto fork_out;
2188753550ebSEric W. Biederman 	p->flags &= ~PF_KTHREAD;
2189753550ebSEric W. Biederman 	if (args->kthread)
2190753550ebSEric W. Biederman 		p->flags |= PF_KTHREAD;
2191b16b3855SJens Axboe 	if (args->io_thread) {
2192b16b3855SJens Axboe 		/*
2193b16b3855SJens Axboe 		 * Mark us an IO worker, and block any signal that isn't
2194b16b3855SJens Axboe 		 * fatal or STOP
2195b16b3855SJens Axboe 		 */
2196cc440e87SJens Axboe 		p->flags |= PF_IO_WORKER;
2197b16b3855SJens Axboe 		siginitsetinv(&p->blocked, sigmask(SIGKILL)|sigmask(SIGSTOP));
2198b16b3855SJens Axboe 	}
21991da177e4SLinus Torvalds 
22007f192e3cSChristian Brauner 	p->set_child_tid = (clone_flags & CLONE_CHILD_SETTID) ? args->child_tid : NULL;
22014d6501dcSVegard Nossum 	/*
22024d6501dcSVegard Nossum 	 * Clear TID on mm_release()?
22034d6501dcSVegard Nossum 	 */
22047f192e3cSChristian Brauner 	p->clear_child_tid = (clone_flags & CLONE_CHILD_CLEARTID) ? args->child_tid : NULL;
22054d6501dcSVegard Nossum 
2206f7e8b616SSteven Rostedt 	ftrace_graph_init_task(p);
2207f7e8b616SSteven Rostedt 
2208bea493a0SPeter Zijlstra 	rt_mutex_init_task(p);
2209bea493a0SPeter Zijlstra 
2210a21ee605SPeter Zijlstra 	lockdep_assert_irqs_enabled();
2211d12c1a37SIngo Molnar #ifdef CONFIG_PROVE_LOCKING
2212de30a2b3SIngo Molnar 	DEBUG_LOCKS_WARN_ON(!p->softirqs_enabled);
2213de30a2b3SIngo Molnar #endif
22148f2f9c4dSEric W. Biederman 	retval = copy_creds(p, clone_flags);
22158f2f9c4dSEric W. Biederman 	if (retval < 0)
22168f2f9c4dSEric W. Biederman 		goto bad_fork_free;
22178f2f9c4dSEric W. Biederman 
22181da177e4SLinus Torvalds 	retval = -EAGAIN;
2219de399236SAlexey Gladkov 	if (is_rlimit_overlimit(task_ucounts(p), UCOUNT_RLIMIT_NPROC, rlimit(RLIMIT_NPROC))) {
2220b57922b6SEric Paris 		if (p->real_cred->user != INIT_USER &&
2221b57922b6SEric Paris 		    !capable(CAP_SYS_RESOURCE) && !capable(CAP_SYS_ADMIN))
22228f2f9c4dSEric W. Biederman 			goto bad_fork_cleanup_count;
22231da177e4SLinus Torvalds 	}
222472fa5997SVasiliy Kulikov 	current->flags &= ~PF_NPROC_EXCEEDED;
22251da177e4SLinus Torvalds 
22261da177e4SLinus Torvalds 	/*
22271da177e4SLinus Torvalds 	 * If multiple threads are within copy_process(), then this check
22281da177e4SLinus Torvalds 	 * triggers too late. This doesn't hurt, the check is only there
22291da177e4SLinus Torvalds 	 * to stop root fork bombs.
22301da177e4SLinus Torvalds 	 */
223104ec93feSLi Zefan 	retval = -EAGAIN;
2232c17d1a3aSWeilong Chen 	if (data_race(nr_threads >= max_threads))
22331da177e4SLinus Torvalds 		goto bad_fork_cleanup_count;
22341da177e4SLinus Torvalds 
2235ca74e92bSShailabh Nagar 	delayacct_tsk_init(p);	/* Must remain after dup_task_struct() */
2236a8ea6fc9SFrederic Weisbecker 	p->flags &= ~(PF_SUPERPRIV | PF_WQ_WORKER | PF_IDLE | PF_NO_SETAFFINITY);
2237514ddb44SDavid Rientjes 	p->flags |= PF_FORKNOEXEC;
22381da177e4SLinus Torvalds 	INIT_LIST_HEAD(&p->children);
22391da177e4SLinus Torvalds 	INIT_LIST_HEAD(&p->sibling);
2240f41d911fSPaul E. McKenney 	rcu_copy_process(p);
22411da177e4SLinus Torvalds 	p->vfork_done = NULL;
22421da177e4SLinus Torvalds 	spin_lock_init(&p->alloc_lock);
22431da177e4SLinus Torvalds 
22441da177e4SLinus Torvalds 	init_sigpending(&p->pending);
22451da177e4SLinus Torvalds 
224664861634SMartin Schwidefsky 	p->utime = p->stime = p->gtime = 0;
224740565b5aSStanislaw Gruszka #ifdef CONFIG_ARCH_HAS_SCALED_CPUTIME
224864861634SMartin Schwidefsky 	p->utimescaled = p->stimescaled = 0;
224940565b5aSStanislaw Gruszka #endif
22509d7fb042SPeter Zijlstra 	prev_cputime_init(&p->prev_cputime);
22519d7fb042SPeter Zijlstra 
22526a61671bSFrederic Weisbecker #ifdef CONFIG_VIRT_CPU_ACCOUNTING_GEN
2253bac5b6b6SFrederic Weisbecker 	seqcount_init(&p->vtime.seqcount);
2254bac5b6b6SFrederic Weisbecker 	p->vtime.starttime = 0;
2255bac5b6b6SFrederic Weisbecker 	p->vtime.state = VTIME_INACTIVE;
22566a61671bSFrederic Weisbecker #endif
22576a61671bSFrederic Weisbecker 
22580f212204SJens Axboe #ifdef CONFIG_IO_URING
22590f212204SJens Axboe 	p->io_uring = NULL;
22600f212204SJens Axboe #endif
22610f212204SJens Axboe 
2262a3a2e76cSKAMEZAWA Hiroyuki #if defined(SPLIT_RSS_COUNTING)
2263a3a2e76cSKAMEZAWA Hiroyuki 	memset(&p->rss_stat, 0, sizeof(p->rss_stat));
2264a3a2e76cSKAMEZAWA Hiroyuki #endif
2265172ba844SBalbir Singh 
22666976675dSArjan van de Ven 	p->default_timer_slack_ns = current->timer_slack_ns;
22676976675dSArjan van de Ven 
2268eb414681SJohannes Weiner #ifdef CONFIG_PSI
2269eb414681SJohannes Weiner 	p->psi_flags = 0;
2270eb414681SJohannes Weiner #endif
2271eb414681SJohannes Weiner 
22725995477aSAndrea Righi 	task_io_accounting_init(&p->ioac);
22731da177e4SLinus Torvalds 	acct_clear_integrals(p);
22741da177e4SLinus Torvalds 
22753a245c0fSThomas Gleixner 	posix_cputimers_init(&p->posix_cputimers);
22761da177e4SLinus Torvalds 
22771da177e4SLinus Torvalds 	p->io_context = NULL;
2278c0b0ae8aSRichard Guy Briggs 	audit_set_context(p, NULL);
2279b4f48b63SPaul Menage 	cgroup_fork(p);
2280343f4c49SEric W. Biederman 	if (args->kthread) {
228140966e31SEric W. Biederman 		if (!set_kthread_struct(p))
2282ff8288ffSEric W. Biederman 			goto bad_fork_cleanup_delayacct;
228340966e31SEric W. Biederman 	}
22841da177e4SLinus Torvalds #ifdef CONFIG_NUMA
2285846a16bfSLee Schermerhorn 	p->mempolicy = mpol_dup(p->mempolicy);
22861da177e4SLinus Torvalds 	if (IS_ERR(p->mempolicy)) {
22871da177e4SLinus Torvalds 		retval = PTR_ERR(p->mempolicy);
22881da177e4SLinus Torvalds 		p->mempolicy = NULL;
2289ff8288ffSEric W. Biederman 		goto bad_fork_cleanup_delayacct;
22901da177e4SLinus Torvalds 	}
22911da177e4SLinus Torvalds #endif
2292778d3b0fSMichal Hocko #ifdef CONFIG_CPUSETS
2293778d3b0fSMichal Hocko 	p->cpuset_mem_spread_rotor = NUMA_NO_NODE;
2294778d3b0fSMichal Hocko 	p->cpuset_slab_spread_rotor = NUMA_NO_NODE;
2295b7505861SAhmed S. Darwish 	seqcount_spinlock_init(&p->mems_allowed_seq, &p->alloc_lock);
2296778d3b0fSMichal Hocko #endif
2297de30a2b3SIngo Molnar #ifdef CONFIG_TRACE_IRQFLAGS
22980584df9cSMarco Elver 	memset(&p->irqtrace, 0, sizeof(p->irqtrace));
22990584df9cSMarco Elver 	p->irqtrace.hardirq_disable_ip	= _THIS_IP_;
23000584df9cSMarco Elver 	p->irqtrace.softirq_enable_ip	= _THIS_IP_;
2301de30a2b3SIngo Molnar 	p->softirqs_enabled		= 1;
2302de30a2b3SIngo Molnar 	p->softirq_context		= 0;
2303de30a2b3SIngo Molnar #endif
23048bcbde54SDavid Hildenbrand 
23058bcbde54SDavid Hildenbrand 	p->pagefault_disabled = 0;
23068bcbde54SDavid Hildenbrand 
2307fbb9ce95SIngo Molnar #ifdef CONFIG_LOCKDEP
2308b09be676SByungchul Park 	lockdep_init_task(p);
2309fbb9ce95SIngo Molnar #endif
23101da177e4SLinus Torvalds 
2311408894eeSIngo Molnar #ifdef CONFIG_DEBUG_MUTEXES
2312408894eeSIngo Molnar 	p->blocked_on = NULL; /* not blocked yet */
2313408894eeSIngo Molnar #endif
2314cafe5635SKent Overstreet #ifdef CONFIG_BCACHE
2315cafe5635SKent Overstreet 	p->sequential_io	= 0;
2316cafe5635SKent Overstreet 	p->sequential_io_avg	= 0;
2317cafe5635SKent Overstreet #endif
2318a10787e6SSong Liu #ifdef CONFIG_BPF_SYSCALL
2319a10787e6SSong Liu 	RCU_INIT_POINTER(p->bpf_storage, NULL);
2320c7603cfaSAndrii Nakryiko 	p->bpf_ctx = NULL;
2321a10787e6SSong Liu #endif
23220f481406SMarkus Metzger 
23233c90e6e9SSrivatsa Vaddagiri 	/* Perform scheduler related setup. Assign this task to a CPU. */
2324aab03e05SDario Faggioli 	retval = sched_fork(clone_flags, p);
2325aab03e05SDario Faggioli 	if (retval)
2326aab03e05SDario Faggioli 		goto bad_fork_cleanup_policy;
23276ab423e0SPeter Zijlstra 
23282b26f0aaSMarco Elver 	retval = perf_event_init_task(p, clone_flags);
23296ab423e0SPeter Zijlstra 	if (retval)
23306ab423e0SPeter Zijlstra 		goto bad_fork_cleanup_policy;
2331fb0a685cSDaniel Rebelo de Oliveira 	retval = audit_alloc(p);
2332fb0a685cSDaniel Rebelo de Oliveira 	if (retval)
23336c72e350SPeter Zijlstra 		goto bad_fork_cleanup_perf;
23341da177e4SLinus Torvalds 	/* copy all the process information */
2335ab602f79SJack Miller 	shm_init_task(p);
2336e4e55b47STetsuo Handa 	retval = security_task_alloc(p, clone_flags);
2337fb0a685cSDaniel Rebelo de Oliveira 	if (retval)
23381da177e4SLinus Torvalds 		goto bad_fork_cleanup_audit;
2339e4e55b47STetsuo Handa 	retval = copy_semundo(clone_flags, p);
2340e4e55b47STetsuo Handa 	if (retval)
2341e4e55b47STetsuo Handa 		goto bad_fork_cleanup_security;
2342fb0a685cSDaniel Rebelo de Oliveira 	retval = copy_files(clone_flags, p);
2343fb0a685cSDaniel Rebelo de Oliveira 	if (retval)
23441da177e4SLinus Torvalds 		goto bad_fork_cleanup_semundo;
2345fb0a685cSDaniel Rebelo de Oliveira 	retval = copy_fs(clone_flags, p);
2346fb0a685cSDaniel Rebelo de Oliveira 	if (retval)
23471da177e4SLinus Torvalds 		goto bad_fork_cleanup_files;
2348fb0a685cSDaniel Rebelo de Oliveira 	retval = copy_sighand(clone_flags, p);
2349fb0a685cSDaniel Rebelo de Oliveira 	if (retval)
23501da177e4SLinus Torvalds 		goto bad_fork_cleanup_fs;
2351fb0a685cSDaniel Rebelo de Oliveira 	retval = copy_signal(clone_flags, p);
2352fb0a685cSDaniel Rebelo de Oliveira 	if (retval)
23531da177e4SLinus Torvalds 		goto bad_fork_cleanup_sighand;
2354fb0a685cSDaniel Rebelo de Oliveira 	retval = copy_mm(clone_flags, p);
2355fb0a685cSDaniel Rebelo de Oliveira 	if (retval)
23561da177e4SLinus Torvalds 		goto bad_fork_cleanup_signal;
2357fb0a685cSDaniel Rebelo de Oliveira 	retval = copy_namespaces(clone_flags, p);
2358fb0a685cSDaniel Rebelo de Oliveira 	if (retval)
2359d84f4f99SDavid Howells 		goto bad_fork_cleanup_mm;
2360fb0a685cSDaniel Rebelo de Oliveira 	retval = copy_io(clone_flags, p);
2361fb0a685cSDaniel Rebelo de Oliveira 	if (retval)
2362fd0928dfSJens Axboe 		goto bad_fork_cleanup_namespaces;
2363c5febea0SEric W. Biederman 	retval = copy_thread(p, args);
23641da177e4SLinus Torvalds 	if (retval)
2365fd0928dfSJens Axboe 		goto bad_fork_cleanup_io;
23661da177e4SLinus Torvalds 
2367afaef01cSAlexander Popov 	stackleak_task_init(p);
2368afaef01cSAlexander Popov 
2369425fb2b4SPavel Emelyanov 	if (pid != &init_struct_pid) {
237049cb2fc4SAdrian Reber 		pid = alloc_pid(p->nsproxy->pid_ns_for_children, args->set_tid,
237149cb2fc4SAdrian Reber 				args->set_tid_size);
237235f71bc0SMichal Hocko 		if (IS_ERR(pid)) {
237335f71bc0SMichal Hocko 			retval = PTR_ERR(pid);
23740740aa5fSJiri Slaby 			goto bad_fork_cleanup_thread;
2375425fb2b4SPavel Emelyanov 		}
237635f71bc0SMichal Hocko 	}
2377425fb2b4SPavel Emelyanov 
2378b3e58382SChristian Brauner 	/*
2379b3e58382SChristian Brauner 	 * This has to happen after we've potentially unshared the file
2380b3e58382SChristian Brauner 	 * descriptor table (so that the pidfd doesn't leak into the child
2381b3e58382SChristian Brauner 	 * if the fd table isn't shared).
2382b3e58382SChristian Brauner 	 */
2383b3e58382SChristian Brauner 	if (clone_flags & CLONE_PIDFD) {
23846fd2fe49SAl Viro 		retval = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
2385b3e58382SChristian Brauner 		if (retval < 0)
2386b3e58382SChristian Brauner 			goto bad_fork_free_pid;
2387b3e58382SChristian Brauner 
2388b3e58382SChristian Brauner 		pidfd = retval;
23896fd2fe49SAl Viro 
23906fd2fe49SAl Viro 		pidfile = anon_inode_getfile("[pidfd]", &pidfd_fops, pid,
23916fd2fe49SAl Viro 					      O_RDWR | O_CLOEXEC);
23926fd2fe49SAl Viro 		if (IS_ERR(pidfile)) {
23936fd2fe49SAl Viro 			put_unused_fd(pidfd);
239428dd29c0SChristian Brauner 			retval = PTR_ERR(pidfile);
23956fd2fe49SAl Viro 			goto bad_fork_free_pid;
23966fd2fe49SAl Viro 		}
23976fd2fe49SAl Viro 		get_pid(pid);	/* held by pidfile now */
23986fd2fe49SAl Viro 
23997f192e3cSChristian Brauner 		retval = put_user(pidfd, args->pidfd);
2400b3e58382SChristian Brauner 		if (retval)
2401b3e58382SChristian Brauner 			goto bad_fork_put_pidfd;
2402b3e58382SChristian Brauner 	}
2403b3e58382SChristian Brauner 
240473c10101SJens Axboe #ifdef CONFIG_BLOCK
240573c10101SJens Axboe 	p->plug = NULL;
240673c10101SJens Axboe #endif
2407ba31c1a4SThomas Gleixner 	futex_init_task(p);
2408ba31c1a4SThomas Gleixner 
24091da177e4SLinus Torvalds 	/*
2410f9a3879aSGOTO Masanori 	 * sigaltstack should be cleared when sharing the same VM
2411f9a3879aSGOTO Masanori 	 */
2412f9a3879aSGOTO Masanori 	if ((clone_flags & (CLONE_VM|CLONE_VFORK)) == CLONE_VM)
24132a742138SStas Sergeev 		sas_ss_reset(p);
2414f9a3879aSGOTO Masanori 
2415f9a3879aSGOTO Masanori 	/*
24166580807dSOleg Nesterov 	 * Syscall tracing and stepping should be turned off in the
24176580807dSOleg Nesterov 	 * child regardless of CLONE_PTRACE.
24181da177e4SLinus Torvalds 	 */
24196580807dSOleg Nesterov 	user_disable_single_step(p);
242064c19ba2SGabriel Krisman Bertazi 	clear_task_syscall_work(p, SYSCALL_TRACE);
242164eb35f7SGabriel Krisman Bertazi #if defined(CONFIG_GENERIC_ENTRY) || defined(TIF_SYSCALL_EMU)
242264eb35f7SGabriel Krisman Bertazi 	clear_task_syscall_work(p, SYSCALL_EMU);
2423ed75e8d5SLaurent Vivier #endif
2424e02c9b0dSLin Feng 	clear_tsk_latency_tracing(p);
24251da177e4SLinus Torvalds 
24261da177e4SLinus Torvalds 	/* ok, now we should be set up.. */
242718c830dfSOleg Nesterov 	p->pid = pid_nr(pid);
242818c830dfSOleg Nesterov 	if (clone_flags & CLONE_THREAD) {
242918c830dfSOleg Nesterov 		p->group_leader = current->group_leader;
243018c830dfSOleg Nesterov 		p->tgid = current->tgid;
243118c830dfSOleg Nesterov 	} else {
243218c830dfSOleg Nesterov 		p->group_leader = p;
243318c830dfSOleg Nesterov 		p->tgid = p->pid;
243418c830dfSOleg Nesterov 	}
24355f8aadd8SOleg Nesterov 
24369d823e8fSWu Fengguang 	p->nr_dirtied = 0;
24379d823e8fSWu Fengguang 	p->nr_dirtied_pause = 128 >> (PAGE_SHIFT - 10);
243883712358SWu Fengguang 	p->dirty_paused_when = 0;
24399d823e8fSWu Fengguang 
2440bb8cbbfeSOleg Nesterov 	p->pdeath_signal = 0;
244147e65328SOleg Nesterov 	INIT_LIST_HEAD(&p->thread_group);
2442158e1645SAl Viro 	p->task_works = NULL;
2443ca7752caSMichael Pratt 	clear_posix_cputimers_work(p);
24441da177e4SLinus Torvalds 
2445d741bf41SPeter Zijlstra #ifdef CONFIG_KRETPROBES
2446d741bf41SPeter Zijlstra 	p->kretprobe_instances.first = NULL;
2447d741bf41SPeter Zijlstra #endif
244854ecbe6fSMasami Hiramatsu #ifdef CONFIG_RETHOOK
244954ecbe6fSMasami Hiramatsu 	p->rethooks.first = NULL;
245054ecbe6fSMasami Hiramatsu #endif
2451d741bf41SPeter Zijlstra 
245218c830dfSOleg Nesterov 	/*
24537e47682eSAleksa Sarai 	 * Ensure that the cgroup subsystem policies allow the new process to be
24547b7b8a2cSRandy Dunlap 	 * forked. It should be noted that the new process's css_set can be changed
24557e47682eSAleksa Sarai 	 * between here and cgroup_post_fork() if an organisation operation is in
24567e47682eSAleksa Sarai 	 * progress.
24577e47682eSAleksa Sarai 	 */
2458ef2c41cfSChristian Brauner 	retval = cgroup_can_fork(p, args);
24597e47682eSAleksa Sarai 	if (retval)
24605a5cf5cbSChristian Brauner 		goto bad_fork_put_pidfd;
24617e47682eSAleksa Sarai 
24627e47682eSAleksa Sarai 	/*
2463b1e82065SPeter Zijlstra 	 * Now that the cgroups are pinned, re-clone the parent cgroup and put
2464b1e82065SPeter Zijlstra 	 * the new task on the correct runqueue. All this *before* the task
2465b1e82065SPeter Zijlstra 	 * becomes visible.
2466b1e82065SPeter Zijlstra 	 *
2467b1e82065SPeter Zijlstra 	 * This isn't part of ->can_fork() because while the re-cloning is
2468b1e82065SPeter Zijlstra 	 * cgroup specific, it unconditionally needs to place the task on a
2469b1e82065SPeter Zijlstra 	 * runqueue.
2470b1e82065SPeter Zijlstra 	 */
2471b1e82065SPeter Zijlstra 	sched_cgroup_fork(p, args);
2472b1e82065SPeter Zijlstra 
2473b1e82065SPeter Zijlstra 	/*
24747b558513SDavid Herrmann 	 * From this point on we must avoid any synchronous user-space
24757b558513SDavid Herrmann 	 * communication until we take the tasklist-lock. In particular, we do
24767b558513SDavid Herrmann 	 * not want user-space to be able to predict the process start-time by
24777b558513SDavid Herrmann 	 * stalling fork(2) after we recorded the start_time but before it is
24787b558513SDavid Herrmann 	 * visible to the system.
24797b558513SDavid Herrmann 	 */
24807b558513SDavid Herrmann 
24817b558513SDavid Herrmann 	p->start_time = ktime_get_ns();
2482cf25e24dSPeter Zijlstra 	p->start_boottime = ktime_get_boottime_ns();
24837b558513SDavid Herrmann 
24847b558513SDavid Herrmann 	/*
248518c830dfSOleg Nesterov 	 * Make it visible to the rest of the system, but dont wake it up yet.
248618c830dfSOleg Nesterov 	 * Need tasklist lock for parent etc handling!
248718c830dfSOleg Nesterov 	 */
24881da177e4SLinus Torvalds 	write_lock_irq(&tasklist_lock);
24891da177e4SLinus Torvalds 
24901da177e4SLinus Torvalds 	/* CLONE_PARENT re-uses the old parent */
24912d5516cbSOleg Nesterov 	if (clone_flags & (CLONE_PARENT|CLONE_THREAD)) {
24921da177e4SLinus Torvalds 		p->real_parent = current->real_parent;
24932d5516cbSOleg Nesterov 		p->parent_exec_id = current->parent_exec_id;
2494b4e00444SEddy Wu 		if (clone_flags & CLONE_THREAD)
2495b4e00444SEddy Wu 			p->exit_signal = -1;
2496b4e00444SEddy Wu 		else
2497b4e00444SEddy Wu 			p->exit_signal = current->group_leader->exit_signal;
24982d5516cbSOleg Nesterov 	} else {
24991da177e4SLinus Torvalds 		p->real_parent = current;
25002d5516cbSOleg Nesterov 		p->parent_exec_id = current->self_exec_id;
2501b4e00444SEddy Wu 		p->exit_signal = args->exit_signal;
25022d5516cbSOleg Nesterov 	}
25031da177e4SLinus Torvalds 
2504d83a7cb3SJosh Poimboeuf 	klp_copy_process(p);
2505d83a7cb3SJosh Poimboeuf 
250685dd3f61SPeter Zijlstra 	sched_core_fork(p);
250785dd3f61SPeter Zijlstra 
25081da177e4SLinus Torvalds 	spin_lock(&current->sighand->siglock);
25094a2c7a78SOleg Nesterov 
251079257534SDaniel Bristot de Oliveira 	rv_task_fork(p);
251179257534SDaniel Bristot de Oliveira 
2512d7822b1eSMathieu Desnoyers 	rseq_fork(p, clone_flags);
2513d7822b1eSMathieu Desnoyers 
25144ca1d3eeSEric W. Biederman 	/* Don't start children in a dying pid namespace */
2515e8cfbc24SGargi Sharma 	if (unlikely(!(ns_of_pid(pid)->pid_allocated & PIDNS_ADDING))) {
25163fd37226SKirill Tkhai 		retval = -ENOMEM;
25173fd37226SKirill Tkhai 		goto bad_fork_cancel_cgroup;
25183fd37226SKirill Tkhai 	}
25194a2c7a78SOleg Nesterov 
25207673bf55SEric W. Biederman 	/* Let kill terminate clone/fork in the middle */
25217673bf55SEric W. Biederman 	if (fatal_signal_pending(current)) {
25227673bf55SEric W. Biederman 		retval = -EINTR;
25237673bf55SEric W. Biederman 		goto bad_fork_cancel_cgroup;
25247673bf55SEric W. Biederman 	}
25257673bf55SEric W. Biederman 
2526a1140cb2SKuniyuki Iwashima 	/* No more failure paths after this point. */
2527a1140cb2SKuniyuki Iwashima 
2528a1140cb2SKuniyuki Iwashima 	/*
2529a1140cb2SKuniyuki Iwashima 	 * Copy seccomp details explicitly here, in case they were changed
2530a1140cb2SKuniyuki Iwashima 	 * before holding sighand lock.
2531a1140cb2SKuniyuki Iwashima 	 */
2532a1140cb2SKuniyuki Iwashima 	copy_seccomp(p);
2533a1140cb2SKuniyuki Iwashima 
25342c470475SEric W. Biederman 	init_task_pid_links(p);
253573b9ebfeSOleg Nesterov 	if (likely(p->pid)) {
25364b9d33e6STejun Heo 		ptrace_init_task(p, (clone_flags & CLONE_PTRACE) || trace);
25371da177e4SLinus Torvalds 
253881907739SOleg Nesterov 		init_task_pid(p, PIDTYPE_PID, pid);
25391da177e4SLinus Torvalds 		if (thread_group_leader(p)) {
25406883f81aSEric W. Biederman 			init_task_pid(p, PIDTYPE_TGID, pid);
254181907739SOleg Nesterov 			init_task_pid(p, PIDTYPE_PGID, task_pgrp(current));
254281907739SOleg Nesterov 			init_task_pid(p, PIDTYPE_SID, task_session(current));
254381907739SOleg Nesterov 
25441c4042c2SEric W. Biederman 			if (is_child_reaper(pid)) {
254517cf22c3SEric W. Biederman 				ns_of_pid(pid)->child_reaper = p;
25461c4042c2SEric W. Biederman 				p->signal->flags |= SIGNAL_UNKILLABLE;
25471c4042c2SEric W. Biederman 			}
2548c3ad2c3bSEric W. Biederman 			p->signal->shared_pending.signal = delayed.signal;
25499c9f4dedSAlan Cox 			p->signal->tty = tty_kref_get(current->signal->tty);
2550749860ceSPavel Tikhomirov 			/*
2551749860ceSPavel Tikhomirov 			 * Inherit has_child_subreaper flag under the same
2552749860ceSPavel Tikhomirov 			 * tasklist_lock with adding child to the process tree
2553749860ceSPavel Tikhomirov 			 * for propagate_has_child_subreaper optimization.
2554749860ceSPavel Tikhomirov 			 */
2555749860ceSPavel Tikhomirov 			p->signal->has_child_subreaper = p->real_parent->signal->has_child_subreaper ||
2556749860ceSPavel Tikhomirov 							 p->real_parent->signal->is_child_subreaper;
25579cd80bbbSOleg Nesterov 			list_add_tail(&p->sibling, &p->real_parent->children);
25585e85d4abSEric W. Biederman 			list_add_tail_rcu(&p->tasks, &init_task.tasks);
25596883f81aSEric W. Biederman 			attach_pid(p, PIDTYPE_TGID);
256081907739SOleg Nesterov 			attach_pid(p, PIDTYPE_PGID);
256181907739SOleg Nesterov 			attach_pid(p, PIDTYPE_SID);
2562909ea964SChristoph Lameter 			__this_cpu_inc(process_counts);
256380628ca0SOleg Nesterov 		} else {
256480628ca0SOleg Nesterov 			current->signal->nr_threads++;
2565d80f7d7bSEric W. Biederman 			current->signal->quick_threads++;
256680628ca0SOleg Nesterov 			atomic_inc(&current->signal->live);
256760d4de3fSElena Reshetova 			refcount_inc(&current->signal->sigcnt);
2568924de3b8SEric W. Biederman 			task_join_group_stop(p);
256980628ca0SOleg Nesterov 			list_add_tail_rcu(&p->thread_group,
257080628ca0SOleg Nesterov 					  &p->group_leader->thread_group);
25710c740d0aSOleg Nesterov 			list_add_tail_rcu(&p->thread_node,
25720c740d0aSOleg Nesterov 					  &p->signal->thread_head);
25731da177e4SLinus Torvalds 		}
257481907739SOleg Nesterov 		attach_pid(p, PIDTYPE_PID);
25751da177e4SLinus Torvalds 		nr_threads++;
257673b9ebfeSOleg Nesterov 	}
25771da177e4SLinus Torvalds 	total_forks++;
2578c3ad2c3bSEric W. Biederman 	hlist_del_init(&delayed.node);
25793f17da69SOleg Nesterov 	spin_unlock(&current->sighand->siglock);
25804af4206bSOleg Nesterov 	syscall_tracepoint_update(p);
25811da177e4SLinus Torvalds 	write_unlock_irq(&tasklist_lock);
25824af4206bSOleg Nesterov 
2583ddc204b5SWaiman Long 	if (pidfile)
2584ddc204b5SWaiman Long 		fd_install(pidfd, pidfile);
2585ddc204b5SWaiman Long 
2586c13cf856SAndrew Morton 	proc_fork_connector(p);
2587b1e82065SPeter Zijlstra 	sched_post_fork(p);
2588ef2c41cfSChristian Brauner 	cgroup_post_fork(p, args);
2589cdd6c482SIngo Molnar 	perf_event_fork(p);
259043d2b113SKAMEZAWA Hiroyuki 
259143d2b113SKAMEZAWA Hiroyuki 	trace_task_newtask(p, clone_flags);
25923ab67966SOleg Nesterov 	uprobe_copy_process(p, clone_flags);
259343d2b113SKAMEZAWA Hiroyuki 
259467197a4fSSuren Baghdasaryan 	copy_oom_score_adj(clone_flags, p);
259567197a4fSSuren Baghdasaryan 
25961da177e4SLinus Torvalds 	return p;
25971da177e4SLinus Torvalds 
25987e47682eSAleksa Sarai bad_fork_cancel_cgroup:
259985dd3f61SPeter Zijlstra 	sched_core_free(p);
26003fd37226SKirill Tkhai 	spin_unlock(&current->sighand->siglock);
26013fd37226SKirill Tkhai 	write_unlock_irq(&tasklist_lock);
2602ef2c41cfSChristian Brauner 	cgroup_cancel_fork(p, args);
2603b3e58382SChristian Brauner bad_fork_put_pidfd:
26046fd2fe49SAl Viro 	if (clone_flags & CLONE_PIDFD) {
26056fd2fe49SAl Viro 		fput(pidfile);
26066fd2fe49SAl Viro 		put_unused_fd(pidfd);
26076fd2fe49SAl Viro 	}
2608425fb2b4SPavel Emelyanov bad_fork_free_pid:
2609425fb2b4SPavel Emelyanov 	if (pid != &init_struct_pid)
2610425fb2b4SPavel Emelyanov 		free_pid(pid);
26110740aa5fSJiri Slaby bad_fork_cleanup_thread:
26120740aa5fSJiri Slaby 	exit_thread(p);
2613fd0928dfSJens Axboe bad_fork_cleanup_io:
2614b69f2292SLouis Rilling 	if (p->io_context)
2615b69f2292SLouis Rilling 		exit_io_context(p);
2616ab516013SSerge E. Hallyn bad_fork_cleanup_namespaces:
2617444f378bSLinus Torvalds 	exit_task_namespaces(p);
26181da177e4SLinus Torvalds bad_fork_cleanup_mm:
2619c3f3ce04SAndrea Arcangeli 	if (p->mm) {
2620c3f3ce04SAndrea Arcangeli 		mm_clear_owner(p->mm, p);
26211da177e4SLinus Torvalds 		mmput(p->mm);
2622c3f3ce04SAndrea Arcangeli 	}
26231da177e4SLinus Torvalds bad_fork_cleanup_signal:
26244ab6c083SOleg Nesterov 	if (!(clone_flags & CLONE_THREAD))
26251c5354deSMike Galbraith 		free_signal_struct(p->signal);
26261da177e4SLinus Torvalds bad_fork_cleanup_sighand:
2627a7e5328aSOleg Nesterov 	__cleanup_sighand(p->sighand);
26281da177e4SLinus Torvalds bad_fork_cleanup_fs:
26291da177e4SLinus Torvalds 	exit_fs(p); /* blocking */
26301da177e4SLinus Torvalds bad_fork_cleanup_files:
26311da177e4SLinus Torvalds 	exit_files(p); /* blocking */
26321da177e4SLinus Torvalds bad_fork_cleanup_semundo:
26331da177e4SLinus Torvalds 	exit_sem(p);
2634e4e55b47STetsuo Handa bad_fork_cleanup_security:
2635e4e55b47STetsuo Handa 	security_task_free(p);
26361da177e4SLinus Torvalds bad_fork_cleanup_audit:
26371da177e4SLinus Torvalds 	audit_free(p);
26386c72e350SPeter Zijlstra bad_fork_cleanup_perf:
2639cdd6c482SIngo Molnar 	perf_event_free_task(p);
26406c72e350SPeter Zijlstra bad_fork_cleanup_policy:
2641b09be676SByungchul Park 	lockdep_free_task(p);
26421da177e4SLinus Torvalds #ifdef CONFIG_NUMA
2643f0be3d32SLee Schermerhorn 	mpol_put(p->mempolicy);
26441da177e4SLinus Torvalds #endif
2645ff8288ffSEric W. Biederman bad_fork_cleanup_delayacct:
264635df17c5SShailabh Nagar 	delayacct_tsk_free(p);
26471da177e4SLinus Torvalds bad_fork_cleanup_count:
264821d1c5e3SAlexey Gladkov 	dec_rlimit_ucounts(task_ucounts(p), UCOUNT_RLIMIT_NPROC, 1);
2649e0e81739SDavid Howells 	exit_creds(p);
26501da177e4SLinus Torvalds bad_fork_free:
26512f064a59SPeter Zijlstra 	WRITE_ONCE(p->__state, TASK_DEAD);
26521a03d3f1SSebastian Andrzej Siewior 	exit_task_stack_account(p);
265368f24b08SAndy Lutomirski 	put_task_stack(p);
2654c3f3ce04SAndrea Arcangeli 	delayed_free_task(p);
2655fe7d37d1SOleg Nesterov fork_out:
2656c3ad2c3bSEric W. Biederman 	spin_lock_irq(&current->sighand->siglock);
2657c3ad2c3bSEric W. Biederman 	hlist_del_init(&delayed.node);
2658c3ad2c3bSEric W. Biederman 	spin_unlock_irq(&current->sighand->siglock);
2659fe7d37d1SOleg Nesterov 	return ERR_PTR(retval);
26601da177e4SLinus Torvalds }
26611da177e4SLinus Torvalds 
26622c470475SEric W. Biederman static inline void init_idle_pids(struct task_struct *idle)
2663f106eee1SOleg Nesterov {
2664f106eee1SOleg Nesterov 	enum pid_type type;
2665f106eee1SOleg Nesterov 
2666f106eee1SOleg Nesterov 	for (type = PIDTYPE_PID; type < PIDTYPE_MAX; ++type) {
26672c470475SEric W. Biederman 		INIT_HLIST_NODE(&idle->pid_links[type]); /* not really needed */
26682c470475SEric W. Biederman 		init_task_pid(idle, type, &init_struct_pid);
2669f106eee1SOleg Nesterov 	}
2670f106eee1SOleg Nesterov }
2671f106eee1SOleg Nesterov 
267236cb0e1cSEric W. Biederman static int idle_dummy(void *dummy)
267336cb0e1cSEric W. Biederman {
267436cb0e1cSEric W. Biederman 	/* This function is never called */
267536cb0e1cSEric W. Biederman 	return 0;
267636cb0e1cSEric W. Biederman }
267736cb0e1cSEric W. Biederman 
2678f1a0a376SValentin Schneider struct task_struct * __init fork_idle(int cpu)
26791da177e4SLinus Torvalds {
268036c8b586SIngo Molnar 	struct task_struct *task;
26817f192e3cSChristian Brauner 	struct kernel_clone_args args = {
26827f192e3cSChristian Brauner 		.flags		= CLONE_VM,
26835bd2e97cSEric W. Biederman 		.fn		= &idle_dummy,
26845bd2e97cSEric W. Biederman 		.fn_arg		= NULL,
2685343f4c49SEric W. Biederman 		.kthread	= 1,
268636cb0e1cSEric W. Biederman 		.idle		= 1,
26877f192e3cSChristian Brauner 	};
26887f192e3cSChristian Brauner 
26897f192e3cSChristian Brauner 	task = copy_process(&init_struct_pid, 0, cpu_to_node(cpu), &args);
2690f106eee1SOleg Nesterov 	if (!IS_ERR(task)) {
26912c470475SEric W. Biederman 		init_idle_pids(task);
26921da177e4SLinus Torvalds 		init_idle(task, cpu);
2693f106eee1SOleg Nesterov 	}
269473b9ebfeSOleg Nesterov 
26951da177e4SLinus Torvalds 	return task;
26961da177e4SLinus Torvalds }
26971da177e4SLinus Torvalds 
26981da177e4SLinus Torvalds /*
2699cc440e87SJens Axboe  * This is like kernel_clone(), but shaved down and tailored to just
2700cc440e87SJens Axboe  * creating io_uring workers. It returns a created task, or an error pointer.
2701cc440e87SJens Axboe  * The returned task is inactive, and the caller must fire it up through
2702cc440e87SJens Axboe  * wake_up_new_task(p). All signals are blocked in the created task.
2703cc440e87SJens Axboe  */
2704cc440e87SJens Axboe struct task_struct *create_io_thread(int (*fn)(void *), void *arg, int node)
2705cc440e87SJens Axboe {
2706cc440e87SJens Axboe 	unsigned long flags = CLONE_FS|CLONE_FILES|CLONE_SIGHAND|CLONE_THREAD|
2707cc440e87SJens Axboe 				CLONE_IO;
2708cc440e87SJens Axboe 	struct kernel_clone_args args = {
2709cc440e87SJens Axboe 		.flags		= ((lower_32_bits(flags) | CLONE_VM |
2710cc440e87SJens Axboe 				    CLONE_UNTRACED) & ~CSIGNAL),
2711cc440e87SJens Axboe 		.exit_signal	= (lower_32_bits(flags) & CSIGNAL),
27125bd2e97cSEric W. Biederman 		.fn		= fn,
27135bd2e97cSEric W. Biederman 		.fn_arg		= arg,
2714cc440e87SJens Axboe 		.io_thread	= 1,
2715cc440e87SJens Axboe 	};
2716cc440e87SJens Axboe 
2717b16b3855SJens Axboe 	return copy_process(NULL, 0, node, &args);
2718cc440e87SJens Axboe }
2719cc440e87SJens Axboe 
2720cc440e87SJens Axboe /*
27211da177e4SLinus Torvalds  *  Ok, this is the main fork-routine.
27221da177e4SLinus Torvalds  *
27231da177e4SLinus Torvalds  * It copies the process, and if successful kick-starts
27241da177e4SLinus Torvalds  * it and waits for it to finish using the VM if required.
2725a0eb9abdSEugene Syromiatnikov  *
2726a0eb9abdSEugene Syromiatnikov  * args->exit_signal is expected to be checked for sanity by the caller.
27271da177e4SLinus Torvalds  */
2728cad6967aSChristian Brauner pid_t kernel_clone(struct kernel_clone_args *args)
27291da177e4SLinus Torvalds {
27307f192e3cSChristian Brauner 	u64 clone_flags = args->flags;
27319f5325aaSMarcos Paulo de Souza 	struct completion vfork;
27329f5325aaSMarcos Paulo de Souza 	struct pid *pid;
27331da177e4SLinus Torvalds 	struct task_struct *p;
27341da177e4SLinus Torvalds 	int trace = 0;
2735cad6967aSChristian Brauner 	pid_t nr;
27361da177e4SLinus Torvalds 
2737bdff746aSAndrew Morton 	/*
27383af8588cSChristian Brauner 	 * For legacy clone() calls, CLONE_PIDFD uses the parent_tid argument
27393af8588cSChristian Brauner 	 * to return the pidfd. Hence, CLONE_PIDFD and CLONE_PARENT_SETTID are
27403af8588cSChristian Brauner 	 * mutually exclusive. With clone3() CLONE_PIDFD has grown a separate
27413af8588cSChristian Brauner 	 * field in struct clone_args and it still doesn't make sense to have
27423af8588cSChristian Brauner 	 * them both point at the same memory location. Performing this check
27433af8588cSChristian Brauner 	 * here has the advantage that we don't need to have a separate helper
27443af8588cSChristian Brauner 	 * to check for legacy clone().
27453af8588cSChristian Brauner 	 */
27463af8588cSChristian Brauner 	if ((args->flags & CLONE_PIDFD) &&
27473af8588cSChristian Brauner 	    (args->flags & CLONE_PARENT_SETTID) &&
27483af8588cSChristian Brauner 	    (args->pidfd == args->parent_tid))
27493af8588cSChristian Brauner 		return -EINVAL;
27503af8588cSChristian Brauner 
27513af8588cSChristian Brauner 	/*
27524b9d33e6STejun Heo 	 * Determine whether and which event to report to ptracer.  When
27534b9d33e6STejun Heo 	 * called from kernel_thread or CLONE_UNTRACED is explicitly
27544b9d33e6STejun Heo 	 * requested, no event is reported; otherwise, report if the event
27554b9d33e6STejun Heo 	 * for the type of forking is enabled.
275609a05394SRoland McGrath 	 */
2757e80d6661SAl Viro 	if (!(clone_flags & CLONE_UNTRACED)) {
27584b9d33e6STejun Heo 		if (clone_flags & CLONE_VFORK)
27594b9d33e6STejun Heo 			trace = PTRACE_EVENT_VFORK;
27607f192e3cSChristian Brauner 		else if (args->exit_signal != SIGCHLD)
27614b9d33e6STejun Heo 			trace = PTRACE_EVENT_CLONE;
27624b9d33e6STejun Heo 		else
27634b9d33e6STejun Heo 			trace = PTRACE_EVENT_FORK;
27644b9d33e6STejun Heo 
27654b9d33e6STejun Heo 		if (likely(!ptrace_event_enabled(current, trace)))
27664b9d33e6STejun Heo 			trace = 0;
27674b9d33e6STejun Heo 	}
27681da177e4SLinus Torvalds 
27697f192e3cSChristian Brauner 	p = copy_process(NULL, trace, NUMA_NO_NODE, args);
277038addce8SEmese Revfy 	add_latent_entropy();
27719f5325aaSMarcos Paulo de Souza 
27729f5325aaSMarcos Paulo de Souza 	if (IS_ERR(p))
27739f5325aaSMarcos Paulo de Souza 		return PTR_ERR(p);
27749f5325aaSMarcos Paulo de Souza 
27751da177e4SLinus Torvalds 	/*
27761da177e4SLinus Torvalds 	 * Do this prior waking up the new thread - the thread pointer
27771da177e4SLinus Torvalds 	 * might get invalid after that point, if the thread exits quickly.
27781da177e4SLinus Torvalds 	 */
27790a16b607SMathieu Desnoyers 	trace_sched_process_fork(current, p);
27800a16b607SMathieu Desnoyers 
27814e52365fSMatthew Dempsky 	pid = get_task_pid(p, PIDTYPE_PID);
27824e52365fSMatthew Dempsky 	nr = pid_vnr(pid);
278330e49c26SPavel Emelyanov 
278430e49c26SPavel Emelyanov 	if (clone_flags & CLONE_PARENT_SETTID)
27857f192e3cSChristian Brauner 		put_user(nr, args->parent_tid);
2786a6f5e063SSukadev Bhattiprolu 
27871da177e4SLinus Torvalds 	if (clone_flags & CLONE_VFORK) {
27881da177e4SLinus Torvalds 		p->vfork_done = &vfork;
27891da177e4SLinus Torvalds 		init_completion(&vfork);
2790d68b46feSOleg Nesterov 		get_task_struct(p);
27911da177e4SLinus Torvalds 	}
27921da177e4SLinus Torvalds 
2793bd74fdaeSYu Zhao 	if (IS_ENABLED(CONFIG_LRU_GEN) && !(clone_flags & CLONE_VM)) {
2794bd74fdaeSYu Zhao 		/* lock the task to synchronize with memcg migration */
2795bd74fdaeSYu Zhao 		task_lock(p);
2796bd74fdaeSYu Zhao 		lru_gen_add_mm(p->mm);
2797bd74fdaeSYu Zhao 		task_unlock(p);
2798bd74fdaeSYu Zhao 	}
2799bd74fdaeSYu Zhao 
28003e51e3edSSamir Bellabes 	wake_up_new_task(p);
28011da177e4SLinus Torvalds 
28024b9d33e6STejun Heo 	/* forking complete and child started to run, tell ptracer */
28034b9d33e6STejun Heo 	if (unlikely(trace))
28044e52365fSMatthew Dempsky 		ptrace_event_pid(trace, pid);
280509a05394SRoland McGrath 
28061da177e4SLinus Torvalds 	if (clone_flags & CLONE_VFORK) {
2807d68b46feSOleg Nesterov 		if (!wait_for_vfork_done(p, &vfork))
28084e52365fSMatthew Dempsky 			ptrace_event_pid(PTRACE_EVENT_VFORK_DONE, pid);
28099f59ce5dSChuck Ebbert 	}
28104e52365fSMatthew Dempsky 
28114e52365fSMatthew Dempsky 	put_pid(pid);
281292476d7fSEric W. Biederman 	return nr;
28131da177e4SLinus Torvalds }
28141da177e4SLinus Torvalds 
28152aa3a7f8SAl Viro /*
28162aa3a7f8SAl Viro  * Create a kernel thread.
28172aa3a7f8SAl Viro  */
28182aa3a7f8SAl Viro pid_t kernel_thread(int (*fn)(void *), void *arg, unsigned long flags)
28192aa3a7f8SAl Viro {
28207f192e3cSChristian Brauner 	struct kernel_clone_args args = {
28213f2c788aSChristian Brauner 		.flags		= ((lower_32_bits(flags) | CLONE_VM |
28223f2c788aSChristian Brauner 				    CLONE_UNTRACED) & ~CSIGNAL),
28233f2c788aSChristian Brauner 		.exit_signal	= (lower_32_bits(flags) & CSIGNAL),
28245bd2e97cSEric W. Biederman 		.fn		= fn,
28255bd2e97cSEric W. Biederman 		.fn_arg		= arg,
2826343f4c49SEric W. Biederman 		.kthread	= 1,
2827343f4c49SEric W. Biederman 	};
2828343f4c49SEric W. Biederman 
2829343f4c49SEric W. Biederman 	return kernel_clone(&args);
2830343f4c49SEric W. Biederman }
2831343f4c49SEric W. Biederman 
2832343f4c49SEric W. Biederman /*
2833343f4c49SEric W. Biederman  * Create a user mode thread.
2834343f4c49SEric W. Biederman  */
2835343f4c49SEric W. Biederman pid_t user_mode_thread(int (*fn)(void *), void *arg, unsigned long flags)
2836343f4c49SEric W. Biederman {
2837343f4c49SEric W. Biederman 	struct kernel_clone_args args = {
2838343f4c49SEric W. Biederman 		.flags		= ((lower_32_bits(flags) | CLONE_VM |
2839343f4c49SEric W. Biederman 				    CLONE_UNTRACED) & ~CSIGNAL),
2840343f4c49SEric W. Biederman 		.exit_signal	= (lower_32_bits(flags) & CSIGNAL),
28415bd2e97cSEric W. Biederman 		.fn		= fn,
28425bd2e97cSEric W. Biederman 		.fn_arg		= arg,
28437f192e3cSChristian Brauner 	};
28447f192e3cSChristian Brauner 
2845cad6967aSChristian Brauner 	return kernel_clone(&args);
28462aa3a7f8SAl Viro }
28472aa3a7f8SAl Viro 
2848d2125043SAl Viro #ifdef __ARCH_WANT_SYS_FORK
2849d2125043SAl Viro SYSCALL_DEFINE0(fork)
2850d2125043SAl Viro {
2851d2125043SAl Viro #ifdef CONFIG_MMU
28527f192e3cSChristian Brauner 	struct kernel_clone_args args = {
28537f192e3cSChristian Brauner 		.exit_signal = SIGCHLD,
28547f192e3cSChristian Brauner 	};
28557f192e3cSChristian Brauner 
2856cad6967aSChristian Brauner 	return kernel_clone(&args);
2857d2125043SAl Viro #else
2858d2125043SAl Viro 	/* can not support in nommu mode */
28595d59e182SDaeseok Youn 	return -EINVAL;
2860d2125043SAl Viro #endif
2861d2125043SAl Viro }
2862d2125043SAl Viro #endif
2863d2125043SAl Viro 
2864d2125043SAl Viro #ifdef __ARCH_WANT_SYS_VFORK
2865d2125043SAl Viro SYSCALL_DEFINE0(vfork)
2866d2125043SAl Viro {
28677f192e3cSChristian Brauner 	struct kernel_clone_args args = {
28687f192e3cSChristian Brauner 		.flags		= CLONE_VFORK | CLONE_VM,
28697f192e3cSChristian Brauner 		.exit_signal	= SIGCHLD,
28707f192e3cSChristian Brauner 	};
28717f192e3cSChristian Brauner 
2872cad6967aSChristian Brauner 	return kernel_clone(&args);
2873d2125043SAl Viro }
2874d2125043SAl Viro #endif
2875d2125043SAl Viro 
2876d2125043SAl Viro #ifdef __ARCH_WANT_SYS_CLONE
2877d2125043SAl Viro #ifdef CONFIG_CLONE_BACKWARDS
2878d2125043SAl Viro SYSCALL_DEFINE5(clone, unsigned long, clone_flags, unsigned long, newsp,
2879d2125043SAl Viro 		 int __user *, parent_tidptr,
28803033f14aSJosh Triplett 		 unsigned long, tls,
2881d2125043SAl Viro 		 int __user *, child_tidptr)
2882d2125043SAl Viro #elif defined(CONFIG_CLONE_BACKWARDS2)
2883d2125043SAl Viro SYSCALL_DEFINE5(clone, unsigned long, newsp, unsigned long, clone_flags,
2884d2125043SAl Viro 		 int __user *, parent_tidptr,
2885d2125043SAl Viro 		 int __user *, child_tidptr,
28863033f14aSJosh Triplett 		 unsigned long, tls)
2887dfa9771aSMichal Simek #elif defined(CONFIG_CLONE_BACKWARDS3)
2888dfa9771aSMichal Simek SYSCALL_DEFINE6(clone, unsigned long, clone_flags, unsigned long, newsp,
2889dfa9771aSMichal Simek 		int, stack_size,
2890dfa9771aSMichal Simek 		int __user *, parent_tidptr,
2891dfa9771aSMichal Simek 		int __user *, child_tidptr,
28923033f14aSJosh Triplett 		unsigned long, tls)
2893d2125043SAl Viro #else
2894d2125043SAl Viro SYSCALL_DEFINE5(clone, unsigned long, clone_flags, unsigned long, newsp,
2895d2125043SAl Viro 		 int __user *, parent_tidptr,
2896d2125043SAl Viro 		 int __user *, child_tidptr,
28973033f14aSJosh Triplett 		 unsigned long, tls)
2898d2125043SAl Viro #endif
2899d2125043SAl Viro {
29007f192e3cSChristian Brauner 	struct kernel_clone_args args = {
29013f2c788aSChristian Brauner 		.flags		= (lower_32_bits(clone_flags) & ~CSIGNAL),
29027f192e3cSChristian Brauner 		.pidfd		= parent_tidptr,
29037f192e3cSChristian Brauner 		.child_tid	= child_tidptr,
29047f192e3cSChristian Brauner 		.parent_tid	= parent_tidptr,
29053f2c788aSChristian Brauner 		.exit_signal	= (lower_32_bits(clone_flags) & CSIGNAL),
29067f192e3cSChristian Brauner 		.stack		= newsp,
29077f192e3cSChristian Brauner 		.tls		= tls,
29087f192e3cSChristian Brauner 	};
29097f192e3cSChristian Brauner 
2910cad6967aSChristian Brauner 	return kernel_clone(&args);
29117f192e3cSChristian Brauner }
2912d68dbb0cSChristian Brauner #endif
29137f192e3cSChristian Brauner 
2914d68dbb0cSChristian Brauner #ifdef __ARCH_WANT_SYS_CLONE3
2915dd499f7aSAmanieu d'Antras 
29167f192e3cSChristian Brauner noinline static int copy_clone_args_from_user(struct kernel_clone_args *kargs,
29177f192e3cSChristian Brauner 					      struct clone_args __user *uargs,
2918f14c234bSAleksa Sarai 					      size_t usize)
29197f192e3cSChristian Brauner {
2920f14c234bSAleksa Sarai 	int err;
29217f192e3cSChristian Brauner 	struct clone_args args;
292249cb2fc4SAdrian Reber 	pid_t *kset_tid = kargs->set_tid;
29237f192e3cSChristian Brauner 
2924a966dcfeSEugene Syromiatnikov 	BUILD_BUG_ON(offsetofend(struct clone_args, tls) !=
2925a966dcfeSEugene Syromiatnikov 		     CLONE_ARGS_SIZE_VER0);
2926a966dcfeSEugene Syromiatnikov 	BUILD_BUG_ON(offsetofend(struct clone_args, set_tid_size) !=
2927a966dcfeSEugene Syromiatnikov 		     CLONE_ARGS_SIZE_VER1);
2928a966dcfeSEugene Syromiatnikov 	BUILD_BUG_ON(offsetofend(struct clone_args, cgroup) !=
2929a966dcfeSEugene Syromiatnikov 		     CLONE_ARGS_SIZE_VER2);
2930a966dcfeSEugene Syromiatnikov 	BUILD_BUG_ON(sizeof(struct clone_args) != CLONE_ARGS_SIZE_VER2);
2931a966dcfeSEugene Syromiatnikov 
2932f14c234bSAleksa Sarai 	if (unlikely(usize > PAGE_SIZE))
29337f192e3cSChristian Brauner 		return -E2BIG;
2934f14c234bSAleksa Sarai 	if (unlikely(usize < CLONE_ARGS_SIZE_VER0))
29357f192e3cSChristian Brauner 		return -EINVAL;
29367f192e3cSChristian Brauner 
2937f14c234bSAleksa Sarai 	err = copy_struct_from_user(&args, sizeof(args), uargs, usize);
2938f14c234bSAleksa Sarai 	if (err)
2939f14c234bSAleksa Sarai 		return err;
29407f192e3cSChristian Brauner 
294149cb2fc4SAdrian Reber 	if (unlikely(args.set_tid_size > MAX_PID_NS_LEVEL))
294249cb2fc4SAdrian Reber 		return -EINVAL;
294349cb2fc4SAdrian Reber 
294449cb2fc4SAdrian Reber 	if (unlikely(!args.set_tid && args.set_tid_size > 0))
294549cb2fc4SAdrian Reber 		return -EINVAL;
294649cb2fc4SAdrian Reber 
294749cb2fc4SAdrian Reber 	if (unlikely(args.set_tid && args.set_tid_size == 0))
294849cb2fc4SAdrian Reber 		return -EINVAL;
294949cb2fc4SAdrian Reber 
2950a0eb9abdSEugene Syromiatnikov 	/*
2951a0eb9abdSEugene Syromiatnikov 	 * Verify that higher 32bits of exit_signal are unset and that
2952a0eb9abdSEugene Syromiatnikov 	 * it is a valid signal
2953a0eb9abdSEugene Syromiatnikov 	 */
2954a0eb9abdSEugene Syromiatnikov 	if (unlikely((args.exit_signal & ~((u64)CSIGNAL)) ||
2955a0eb9abdSEugene Syromiatnikov 		     !valid_signal(args.exit_signal)))
2956a0eb9abdSEugene Syromiatnikov 		return -EINVAL;
2957a0eb9abdSEugene Syromiatnikov 
295862173872SEugene Syromiatnikov 	if ((args.flags & CLONE_INTO_CGROUP) &&
295962173872SEugene Syromiatnikov 	    (args.cgroup > INT_MAX || usize < CLONE_ARGS_SIZE_VER2))
2960ef2c41cfSChristian Brauner 		return -EINVAL;
2961ef2c41cfSChristian Brauner 
29627f192e3cSChristian Brauner 	*kargs = (struct kernel_clone_args){
29637f192e3cSChristian Brauner 		.flags		= args.flags,
29647f192e3cSChristian Brauner 		.pidfd		= u64_to_user_ptr(args.pidfd),
29657f192e3cSChristian Brauner 		.child_tid	= u64_to_user_ptr(args.child_tid),
29667f192e3cSChristian Brauner 		.parent_tid	= u64_to_user_ptr(args.parent_tid),
29677f192e3cSChristian Brauner 		.exit_signal	= args.exit_signal,
29687f192e3cSChristian Brauner 		.stack		= args.stack,
29697f192e3cSChristian Brauner 		.stack_size	= args.stack_size,
29707f192e3cSChristian Brauner 		.tls		= args.tls,
297149cb2fc4SAdrian Reber 		.set_tid_size	= args.set_tid_size,
2972ef2c41cfSChristian Brauner 		.cgroup		= args.cgroup,
29737f192e3cSChristian Brauner 	};
29747f192e3cSChristian Brauner 
297549cb2fc4SAdrian Reber 	if (args.set_tid &&
297649cb2fc4SAdrian Reber 		copy_from_user(kset_tid, u64_to_user_ptr(args.set_tid),
297749cb2fc4SAdrian Reber 			(kargs->set_tid_size * sizeof(pid_t))))
297849cb2fc4SAdrian Reber 		return -EFAULT;
297949cb2fc4SAdrian Reber 
298049cb2fc4SAdrian Reber 	kargs->set_tid = kset_tid;
298149cb2fc4SAdrian Reber 
29827f192e3cSChristian Brauner 	return 0;
29837f192e3cSChristian Brauner }
29847f192e3cSChristian Brauner 
2985fa729c4dSChristian Brauner /**
2986fa729c4dSChristian Brauner  * clone3_stack_valid - check and prepare stack
2987fa729c4dSChristian Brauner  * @kargs: kernel clone args
2988fa729c4dSChristian Brauner  *
2989fa729c4dSChristian Brauner  * Verify that the stack arguments userspace gave us are sane.
2990fa729c4dSChristian Brauner  * In addition, set the stack direction for userspace since it's easy for us to
2991fa729c4dSChristian Brauner  * determine.
2992fa729c4dSChristian Brauner  */
2993fa729c4dSChristian Brauner static inline bool clone3_stack_valid(struct kernel_clone_args *kargs)
2994fa729c4dSChristian Brauner {
2995fa729c4dSChristian Brauner 	if (kargs->stack == 0) {
2996fa729c4dSChristian Brauner 		if (kargs->stack_size > 0)
2997fa729c4dSChristian Brauner 			return false;
2998fa729c4dSChristian Brauner 	} else {
2999fa729c4dSChristian Brauner 		if (kargs->stack_size == 0)
3000fa729c4dSChristian Brauner 			return false;
3001fa729c4dSChristian Brauner 
3002fa729c4dSChristian Brauner 		if (!access_ok((void __user *)kargs->stack, kargs->stack_size))
3003fa729c4dSChristian Brauner 			return false;
3004fa729c4dSChristian Brauner 
3005fa729c4dSChristian Brauner #if !defined(CONFIG_STACK_GROWSUP) && !defined(CONFIG_IA64)
3006fa729c4dSChristian Brauner 		kargs->stack += kargs->stack_size;
3007fa729c4dSChristian Brauner #endif
3008fa729c4dSChristian Brauner 	}
3009fa729c4dSChristian Brauner 
3010fa729c4dSChristian Brauner 	return true;
3011fa729c4dSChristian Brauner }
3012fa729c4dSChristian Brauner 
3013fa729c4dSChristian Brauner static bool clone3_args_valid(struct kernel_clone_args *kargs)
30147f192e3cSChristian Brauner {
3015b612e5dfSChristian Brauner 	/* Verify that no unknown flags are passed along. */
3016ef2c41cfSChristian Brauner 	if (kargs->flags &
3017ef2c41cfSChristian Brauner 	    ~(CLONE_LEGACY_FLAGS | CLONE_CLEAR_SIGHAND | CLONE_INTO_CGROUP))
30187f192e3cSChristian Brauner 		return false;
30197f192e3cSChristian Brauner 
30207f192e3cSChristian Brauner 	/*
3021a8ca6b13SXiaofeng Cao 	 * - make the CLONE_DETACHED bit reusable for clone3
3022a8ca6b13SXiaofeng Cao 	 * - make the CSIGNAL bits reusable for clone3
30237f192e3cSChristian Brauner 	 */
3024a402f1e3STobias Klauser 	if (kargs->flags & (CLONE_DETACHED | (CSIGNAL & (~CLONE_NEWTIME))))
30257f192e3cSChristian Brauner 		return false;
30267f192e3cSChristian Brauner 
3027b612e5dfSChristian Brauner 	if ((kargs->flags & (CLONE_SIGHAND | CLONE_CLEAR_SIGHAND)) ==
3028b612e5dfSChristian Brauner 	    (CLONE_SIGHAND | CLONE_CLEAR_SIGHAND))
3029b612e5dfSChristian Brauner 		return false;
3030b612e5dfSChristian Brauner 
30317f192e3cSChristian Brauner 	if ((kargs->flags & (CLONE_THREAD | CLONE_PARENT)) &&
30327f192e3cSChristian Brauner 	    kargs->exit_signal)
30337f192e3cSChristian Brauner 		return false;
30347f192e3cSChristian Brauner 
3035fa729c4dSChristian Brauner 	if (!clone3_stack_valid(kargs))
3036fa729c4dSChristian Brauner 		return false;
3037fa729c4dSChristian Brauner 
30387f192e3cSChristian Brauner 	return true;
30397f192e3cSChristian Brauner }
30407f192e3cSChristian Brauner 
3041501bd016SChristian Brauner /**
3042501bd016SChristian Brauner  * clone3 - create a new process with specific properties
3043501bd016SChristian Brauner  * @uargs: argument structure
3044501bd016SChristian Brauner  * @size:  size of @uargs
3045501bd016SChristian Brauner  *
3046501bd016SChristian Brauner  * clone3() is the extensible successor to clone()/clone2().
3047501bd016SChristian Brauner  * It takes a struct as argument that is versioned by its size.
3048501bd016SChristian Brauner  *
3049501bd016SChristian Brauner  * Return: On success, a positive PID for the child process.
3050501bd016SChristian Brauner  *         On error, a negative errno number.
3051501bd016SChristian Brauner  */
30527f192e3cSChristian Brauner SYSCALL_DEFINE2(clone3, struct clone_args __user *, uargs, size_t, size)
30537f192e3cSChristian Brauner {
30547f192e3cSChristian Brauner 	int err;
30557f192e3cSChristian Brauner 
30567f192e3cSChristian Brauner 	struct kernel_clone_args kargs;
305749cb2fc4SAdrian Reber 	pid_t set_tid[MAX_PID_NS_LEVEL];
305849cb2fc4SAdrian Reber 
305949cb2fc4SAdrian Reber 	kargs.set_tid = set_tid;
30607f192e3cSChristian Brauner 
30617f192e3cSChristian Brauner 	err = copy_clone_args_from_user(&kargs, uargs, size);
30627f192e3cSChristian Brauner 	if (err)
30637f192e3cSChristian Brauner 		return err;
30647f192e3cSChristian Brauner 
30657f192e3cSChristian Brauner 	if (!clone3_args_valid(&kargs))
30667f192e3cSChristian Brauner 		return -EINVAL;
30677f192e3cSChristian Brauner 
3068cad6967aSChristian Brauner 	return kernel_clone(&kargs);
3069d2125043SAl Viro }
3070d2125043SAl Viro #endif
3071d2125043SAl Viro 
30720f1b92cbSOleg Nesterov void walk_process_tree(struct task_struct *top, proc_visitor visitor, void *data)
30730f1b92cbSOleg Nesterov {
30740f1b92cbSOleg Nesterov 	struct task_struct *leader, *parent, *child;
30750f1b92cbSOleg Nesterov 	int res;
30760f1b92cbSOleg Nesterov 
30770f1b92cbSOleg Nesterov 	read_lock(&tasklist_lock);
30780f1b92cbSOleg Nesterov 	leader = top = top->group_leader;
30790f1b92cbSOleg Nesterov down:
30800f1b92cbSOleg Nesterov 	for_each_thread(leader, parent) {
30810f1b92cbSOleg Nesterov 		list_for_each_entry(child, &parent->children, sibling) {
30820f1b92cbSOleg Nesterov 			res = visitor(child, data);
30830f1b92cbSOleg Nesterov 			if (res) {
30840f1b92cbSOleg Nesterov 				if (res < 0)
30850f1b92cbSOleg Nesterov 					goto out;
30860f1b92cbSOleg Nesterov 				leader = child;
30870f1b92cbSOleg Nesterov 				goto down;
30880f1b92cbSOleg Nesterov 			}
30890f1b92cbSOleg Nesterov up:
30900f1b92cbSOleg Nesterov 			;
30910f1b92cbSOleg Nesterov 		}
30920f1b92cbSOleg Nesterov 	}
30930f1b92cbSOleg Nesterov 
30940f1b92cbSOleg Nesterov 	if (leader != top) {
30950f1b92cbSOleg Nesterov 		child = leader;
30960f1b92cbSOleg Nesterov 		parent = child->real_parent;
30970f1b92cbSOleg Nesterov 		leader = parent->group_leader;
30980f1b92cbSOleg Nesterov 		goto up;
30990f1b92cbSOleg Nesterov 	}
31000f1b92cbSOleg Nesterov out:
31010f1b92cbSOleg Nesterov 	read_unlock(&tasklist_lock);
31020f1b92cbSOleg Nesterov }
31030f1b92cbSOleg Nesterov 
31045fd63b30SRavikiran G Thirumalai #ifndef ARCH_MIN_MMSTRUCT_ALIGN
31055fd63b30SRavikiran G Thirumalai #define ARCH_MIN_MMSTRUCT_ALIGN 0
31065fd63b30SRavikiran G Thirumalai #endif
31075fd63b30SRavikiran G Thirumalai 
310851cc5068SAlexey Dobriyan static void sighand_ctor(void *data)
3109aa1757f9SOleg Nesterov {
3110aa1757f9SOleg Nesterov 	struct sighand_struct *sighand = data;
3111aa1757f9SOleg Nesterov 
3112aa1757f9SOleg Nesterov 	spin_lock_init(&sighand->siglock);
3113b8fceee1SDavide Libenzi 	init_waitqueue_head(&sighand->signalfd_wqh);
3114fba2afaaSDavide Libenzi }
3115aa1757f9SOleg Nesterov 
3116af806027SPeter Zijlstra void __init mm_cache_init(void)
31171da177e4SLinus Torvalds {
3118c1a2f7f0SRik van Riel 	unsigned int mm_size;
3119c1a2f7f0SRik van Riel 
3120af806027SPeter Zijlstra 	/*
3121af806027SPeter Zijlstra 	 * The mm_cpumask is located at the end of mm_struct, and is
3122af806027SPeter Zijlstra 	 * dynamically sized based on the maximum CPU number this system
3123af806027SPeter Zijlstra 	 * can have, taking hotplug into account (nr_cpu_ids).
3124af806027SPeter Zijlstra 	 */
3125af7f588dSMathieu Desnoyers 	mm_size = sizeof(struct mm_struct) + cpumask_size() + mm_cid_size();
3126af806027SPeter Zijlstra 
3127af806027SPeter Zijlstra 	mm_cachep = kmem_cache_create_usercopy("mm_struct",
3128af806027SPeter Zijlstra 			mm_size, ARCH_MIN_MMSTRUCT_ALIGN,
3129af806027SPeter Zijlstra 			SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_ACCOUNT,
3130af806027SPeter Zijlstra 			offsetof(struct mm_struct, saved_auxv),
3131af806027SPeter Zijlstra 			sizeof_field(struct mm_struct, saved_auxv),
3132af806027SPeter Zijlstra 			NULL);
3133af806027SPeter Zijlstra }
3134af806027SPeter Zijlstra 
3135af806027SPeter Zijlstra void __init proc_caches_init(void)
3136af806027SPeter Zijlstra {
31371da177e4SLinus Torvalds 	sighand_cachep = kmem_cache_create("sighand_cache",
31381da177e4SLinus Torvalds 			sizeof(struct sighand_struct), 0,
31395f0d5a3aSPaul E. McKenney 			SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_TYPESAFE_BY_RCU|
314075f296d9SLevin, Alexander (Sasha Levin) 			SLAB_ACCOUNT, sighand_ctor);
31411da177e4SLinus Torvalds 	signal_cachep = kmem_cache_create("signal_cache",
31421da177e4SLinus Torvalds 			sizeof(struct signal_struct), 0,
314375f296d9SLevin, Alexander (Sasha Levin) 			SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_ACCOUNT,
31445d097056SVladimir Davydov 			NULL);
31451da177e4SLinus Torvalds 	files_cachep = kmem_cache_create("files_cache",
31461da177e4SLinus Torvalds 			sizeof(struct files_struct), 0,
314775f296d9SLevin, Alexander (Sasha Levin) 			SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_ACCOUNT,
31485d097056SVladimir Davydov 			NULL);
31491da177e4SLinus Torvalds 	fs_cachep = kmem_cache_create("fs_cache",
31501da177e4SLinus Torvalds 			sizeof(struct fs_struct), 0,
315175f296d9SLevin, Alexander (Sasha Levin) 			SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_ACCOUNT,
31525d097056SVladimir Davydov 			NULL);
3153c1a2f7f0SRik van Riel 
31545d097056SVladimir Davydov 	vm_area_cachep = KMEM_CACHE(vm_area_struct, SLAB_PANIC|SLAB_ACCOUNT);
31558feae131SDavid Howells 	mmap_init();
315666577193SAl Viro 	nsproxy_cache_init();
31571da177e4SLinus Torvalds }
3158cf2e340fSJANAK DESAI 
3159cf2e340fSJANAK DESAI /*
31609bfb23fcSOleg Nesterov  * Check constraints on flags passed to the unshare system call.
3161cf2e340fSJANAK DESAI  */
31629bfb23fcSOleg Nesterov static int check_unshare_flags(unsigned long unshare_flags)
3163cf2e340fSJANAK DESAI {
31649bfb23fcSOleg Nesterov 	if (unshare_flags & ~(CLONE_THREAD|CLONE_FS|CLONE_NEWNS|CLONE_SIGHAND|
31659bfb23fcSOleg Nesterov 				CLONE_VM|CLONE_FILES|CLONE_SYSVSEM|
316650804fe3SEric W. Biederman 				CLONE_NEWUTS|CLONE_NEWIPC|CLONE_NEWNET|
3167769071acSAndrei Vagin 				CLONE_NEWUSER|CLONE_NEWPID|CLONE_NEWCGROUP|
3168769071acSAndrei Vagin 				CLONE_NEWTIME))
3169cf2e340fSJANAK DESAI 		return -EINVAL;
31709bfb23fcSOleg Nesterov 	/*
317112c641abSEric W. Biederman 	 * Not implemented, but pretend it works if there is nothing
317212c641abSEric W. Biederman 	 * to unshare.  Note that unsharing the address space or the
317312c641abSEric W. Biederman 	 * signal handlers also need to unshare the signal queues (aka
317412c641abSEric W. Biederman 	 * CLONE_THREAD).
31759bfb23fcSOleg Nesterov 	 */
31769bfb23fcSOleg Nesterov 	if (unshare_flags & (CLONE_THREAD | CLONE_SIGHAND | CLONE_VM)) {
317712c641abSEric W. Biederman 		if (!thread_group_empty(current))
317812c641abSEric W. Biederman 			return -EINVAL;
317912c641abSEric W. Biederman 	}
318012c641abSEric W. Biederman 	if (unshare_flags & (CLONE_SIGHAND | CLONE_VM)) {
3181d036bda7SElena Reshetova 		if (refcount_read(&current->sighand->count) > 1)
318212c641abSEric W. Biederman 			return -EINVAL;
318312c641abSEric W. Biederman 	}
318412c641abSEric W. Biederman 	if (unshare_flags & CLONE_VM) {
318512c641abSEric W. Biederman 		if (!current_is_single_threaded())
31869bfb23fcSOleg Nesterov 			return -EINVAL;
31879bfb23fcSOleg Nesterov 	}
3188cf2e340fSJANAK DESAI 
3189cf2e340fSJANAK DESAI 	return 0;
3190cf2e340fSJANAK DESAI }
3191cf2e340fSJANAK DESAI 
3192cf2e340fSJANAK DESAI /*
319399d1419dSJANAK DESAI  * Unshare the filesystem structure if it is being shared
3194cf2e340fSJANAK DESAI  */
3195cf2e340fSJANAK DESAI static int unshare_fs(unsigned long unshare_flags, struct fs_struct **new_fsp)
3196cf2e340fSJANAK DESAI {
3197cf2e340fSJANAK DESAI 	struct fs_struct *fs = current->fs;
3198cf2e340fSJANAK DESAI 
3199498052bbSAl Viro 	if (!(unshare_flags & CLONE_FS) || !fs)
3200498052bbSAl Viro 		return 0;
3201498052bbSAl Viro 
3202498052bbSAl Viro 	/* don't need lock here; in the worst case we'll do useless copy */
3203498052bbSAl Viro 	if (fs->users == 1)
3204498052bbSAl Viro 		return 0;
3205498052bbSAl Viro 
3206498052bbSAl Viro 	*new_fsp = copy_fs_struct(fs);
320799d1419dSJANAK DESAI 	if (!*new_fsp)
320899d1419dSJANAK DESAI 		return -ENOMEM;
3209cf2e340fSJANAK DESAI 
3210cf2e340fSJANAK DESAI 	return 0;
3211cf2e340fSJANAK DESAI }
3212cf2e340fSJANAK DESAI 
3213cf2e340fSJANAK DESAI /*
3214a016f338SJANAK DESAI  * Unshare file descriptor table if it is being shared
3215cf2e340fSJANAK DESAI  */
321660997c3dSChristian Brauner int unshare_fd(unsigned long unshare_flags, unsigned int max_fds,
321760997c3dSChristian Brauner 	       struct files_struct **new_fdp)
3218cf2e340fSJANAK DESAI {
3219cf2e340fSJANAK DESAI 	struct files_struct *fd = current->files;
3220a016f338SJANAK DESAI 	int error = 0;
3221cf2e340fSJANAK DESAI 
3222cf2e340fSJANAK DESAI 	if ((unshare_flags & CLONE_FILES) &&
3223a016f338SJANAK DESAI 	    (fd && atomic_read(&fd->count) > 1)) {
322460997c3dSChristian Brauner 		*new_fdp = dup_fd(fd, max_fds, &error);
3225a016f338SJANAK DESAI 		if (!*new_fdp)
3226a016f338SJANAK DESAI 			return error;
3227a016f338SJANAK DESAI 	}
3228cf2e340fSJANAK DESAI 
3229cf2e340fSJANAK DESAI 	return 0;
3230cf2e340fSJANAK DESAI }
3231cf2e340fSJANAK DESAI 
3232cf2e340fSJANAK DESAI /*
3233cf2e340fSJANAK DESAI  * unshare allows a process to 'unshare' part of the process
3234cf2e340fSJANAK DESAI  * context which was originally shared using clone.  copy_*
3235cad6967aSChristian Brauner  * functions used by kernel_clone() cannot be used here directly
3236cf2e340fSJANAK DESAI  * because they modify an inactive task_struct that is being
3237cf2e340fSJANAK DESAI  * constructed. Here we are modifying the current, active,
3238cf2e340fSJANAK DESAI  * task_struct.
3239cf2e340fSJANAK DESAI  */
32409b32105eSDominik Brodowski int ksys_unshare(unsigned long unshare_flags)
3241cf2e340fSJANAK DESAI {
3242cf2e340fSJANAK DESAI 	struct fs_struct *fs, *new_fs = NULL;
3243ba1f70ddSRan Xiaokai 	struct files_struct *new_fd = NULL;
3244b2e0d987SEric W. Biederman 	struct cred *new_cred = NULL;
3245cf7b708cSPavel Emelyanov 	struct nsproxy *new_nsproxy = NULL;
32469edff4abSManfred Spraul 	int do_sysvsem = 0;
32479bfb23fcSOleg Nesterov 	int err;
3248cf2e340fSJANAK DESAI 
324950804fe3SEric W. Biederman 	/*
3250faf00da5SEric W. Biederman 	 * If unsharing a user namespace must also unshare the thread group
3251faf00da5SEric W. Biederman 	 * and unshare the filesystem root and working directories.
3252b2e0d987SEric W. Biederman 	 */
3253b2e0d987SEric W. Biederman 	if (unshare_flags & CLONE_NEWUSER)
3254e66eded8SEric W. Biederman 		unshare_flags |= CLONE_THREAD | CLONE_FS;
3255b2e0d987SEric W. Biederman 	/*
325650804fe3SEric W. Biederman 	 * If unsharing vm, must also unshare signal handlers.
325750804fe3SEric W. Biederman 	 */
325850804fe3SEric W. Biederman 	if (unshare_flags & CLONE_VM)
325950804fe3SEric W. Biederman 		unshare_flags |= CLONE_SIGHAND;
32606013f67fSManfred Spraul 	/*
326112c641abSEric W. Biederman 	 * If unsharing a signal handlers, must also unshare the signal queues.
326212c641abSEric W. Biederman 	 */
326312c641abSEric W. Biederman 	if (unshare_flags & CLONE_SIGHAND)
326412c641abSEric W. Biederman 		unshare_flags |= CLONE_THREAD;
326512c641abSEric W. Biederman 	/*
32669bfb23fcSOleg Nesterov 	 * If unsharing namespace, must also unshare filesystem information.
32679bfb23fcSOleg Nesterov 	 */
32689bfb23fcSOleg Nesterov 	if (unshare_flags & CLONE_NEWNS)
32699bfb23fcSOleg Nesterov 		unshare_flags |= CLONE_FS;
327050804fe3SEric W. Biederman 
327150804fe3SEric W. Biederman 	err = check_unshare_flags(unshare_flags);
327250804fe3SEric W. Biederman 	if (err)
327350804fe3SEric W. Biederman 		goto bad_unshare_out;
32749bfb23fcSOleg Nesterov 	/*
32756013f67fSManfred Spraul 	 * CLONE_NEWIPC must also detach from the undolist: after switching
32766013f67fSManfred Spraul 	 * to a new ipc namespace, the semaphore arrays from the old
32776013f67fSManfred Spraul 	 * namespace are unreachable.
32786013f67fSManfred Spraul 	 */
32796013f67fSManfred Spraul 	if (unshare_flags & (CLONE_NEWIPC|CLONE_SYSVSEM))
32809edff4abSManfred Spraul 		do_sysvsem = 1;
3281fb0a685cSDaniel Rebelo de Oliveira 	err = unshare_fs(unshare_flags, &new_fs);
3282fb0a685cSDaniel Rebelo de Oliveira 	if (err)
32839bfb23fcSOleg Nesterov 		goto bad_unshare_out;
328460997c3dSChristian Brauner 	err = unshare_fd(unshare_flags, NR_OPEN_MAX, &new_fd);
3285fb0a685cSDaniel Rebelo de Oliveira 	if (err)
32869bfb23fcSOleg Nesterov 		goto bad_unshare_cleanup_fs;
3287b2e0d987SEric W. Biederman 	err = unshare_userns(unshare_flags, &new_cred);
3288fb0a685cSDaniel Rebelo de Oliveira 	if (err)
32899edff4abSManfred Spraul 		goto bad_unshare_cleanup_fd;
3290b2e0d987SEric W. Biederman 	err = unshare_nsproxy_namespaces(unshare_flags, &new_nsproxy,
3291b2e0d987SEric W. Biederman 					 new_cred, new_fs);
3292b2e0d987SEric W. Biederman 	if (err)
3293b2e0d987SEric W. Biederman 		goto bad_unshare_cleanup_cred;
3294cf2e340fSJANAK DESAI 
3295905ae01cSAlexey Gladkov 	if (new_cred) {
3296905ae01cSAlexey Gladkov 		err = set_cred_ucounts(new_cred);
3297905ae01cSAlexey Gladkov 		if (err)
3298905ae01cSAlexey Gladkov 			goto bad_unshare_cleanup_cred;
3299905ae01cSAlexey Gladkov 	}
3300905ae01cSAlexey Gladkov 
3301b2e0d987SEric W. Biederman 	if (new_fs || new_fd || do_sysvsem || new_cred || new_nsproxy) {
33029edff4abSManfred Spraul 		if (do_sysvsem) {
33039edff4abSManfred Spraul 			/*
33049edff4abSManfred Spraul 			 * CLONE_SYSVSEM is equivalent to sys_exit().
33059edff4abSManfred Spraul 			 */
33069edff4abSManfred Spraul 			exit_sem(current);
33079edff4abSManfred Spraul 		}
3308ab602f79SJack Miller 		if (unshare_flags & CLONE_NEWIPC) {
3309ab602f79SJack Miller 			/* Orphan segments in old ns (see sem above). */
3310ab602f79SJack Miller 			exit_shm(current);
3311ab602f79SJack Miller 			shm_init_task(current);
3312ab602f79SJack Miller 		}
3313ab516013SSerge E. Hallyn 
33146f977e6bSAlan Cox 		if (new_nsproxy)
3315cf7b708cSPavel Emelyanov 			switch_task_namespaces(current, new_nsproxy);
3316cf2e340fSJANAK DESAI 
3317cf7b708cSPavel Emelyanov 		task_lock(current);
3318cf7b708cSPavel Emelyanov 
3319cf2e340fSJANAK DESAI 		if (new_fs) {
3320cf2e340fSJANAK DESAI 			fs = current->fs;
33212a4419b5SNick Piggin 			spin_lock(&fs->lock);
3322cf2e340fSJANAK DESAI 			current->fs = new_fs;
3323498052bbSAl Viro 			if (--fs->users)
3324498052bbSAl Viro 				new_fs = NULL;
3325498052bbSAl Viro 			else
3326cf2e340fSJANAK DESAI 				new_fs = fs;
33272a4419b5SNick Piggin 			spin_unlock(&fs->lock);
3328cf2e340fSJANAK DESAI 		}
3329cf2e340fSJANAK DESAI 
3330ba1f70ddSRan Xiaokai 		if (new_fd)
3331ba1f70ddSRan Xiaokai 			swap(current->files, new_fd);
3332cf2e340fSJANAK DESAI 
3333cf2e340fSJANAK DESAI 		task_unlock(current);
3334b2e0d987SEric W. Biederman 
3335b2e0d987SEric W. Biederman 		if (new_cred) {
3336b2e0d987SEric W. Biederman 			/* Install the new user namespace */
3337b2e0d987SEric W. Biederman 			commit_creds(new_cred);
3338b2e0d987SEric W. Biederman 			new_cred = NULL;
3339b2e0d987SEric W. Biederman 		}
3340cf2e340fSJANAK DESAI 	}
3341cf2e340fSJANAK DESAI 
3342e4222673SHari Bathini 	perf_event_namespaces(current);
3343e4222673SHari Bathini 
3344b2e0d987SEric W. Biederman bad_unshare_cleanup_cred:
3345b2e0d987SEric W. Biederman 	if (new_cred)
3346b2e0d987SEric W. Biederman 		put_cred(new_cred);
3347cf2e340fSJANAK DESAI bad_unshare_cleanup_fd:
3348cf2e340fSJANAK DESAI 	if (new_fd)
3349cf2e340fSJANAK DESAI 		put_files_struct(new_fd);
3350cf2e340fSJANAK DESAI 
3351cf2e340fSJANAK DESAI bad_unshare_cleanup_fs:
3352cf2e340fSJANAK DESAI 	if (new_fs)
3353498052bbSAl Viro 		free_fs_struct(new_fs);
3354cf2e340fSJANAK DESAI 
3355cf2e340fSJANAK DESAI bad_unshare_out:
3356cf2e340fSJANAK DESAI 	return err;
3357cf2e340fSJANAK DESAI }
33583b125388SAl Viro 
33599b32105eSDominik Brodowski SYSCALL_DEFINE1(unshare, unsigned long, unshare_flags)
33609b32105eSDominik Brodowski {
33619b32105eSDominik Brodowski 	return ksys_unshare(unshare_flags);
33629b32105eSDominik Brodowski }
33639b32105eSDominik Brodowski 
33643b125388SAl Viro /*
33653b125388SAl Viro  *	Helper to unshare the files of the current task.
33663b125388SAl Viro  *	We don't want to expose copy_files internals to
33673b125388SAl Viro  *	the exec layer of the kernel.
33683b125388SAl Viro  */
33693b125388SAl Viro 
33701f702603SEric W. Biederman int unshare_files(void)
33713b125388SAl Viro {
33723b125388SAl Viro 	struct task_struct *task = current;
33731f702603SEric W. Biederman 	struct files_struct *old, *copy = NULL;
33743b125388SAl Viro 	int error;
33753b125388SAl Viro 
337660997c3dSChristian Brauner 	error = unshare_fd(CLONE_FILES, NR_OPEN_MAX, &copy);
33771f702603SEric W. Biederman 	if (error || !copy)
33783b125388SAl Viro 		return error;
33791f702603SEric W. Biederman 
33801f702603SEric W. Biederman 	old = task->files;
33813b125388SAl Viro 	task_lock(task);
33823b125388SAl Viro 	task->files = copy;
33833b125388SAl Viro 	task_unlock(task);
33841f702603SEric W. Biederman 	put_files_struct(old);
33853b125388SAl Viro 	return 0;
33863b125388SAl Viro }
338716db3d3fSHeinrich Schuchardt 
338816db3d3fSHeinrich Schuchardt int sysctl_max_threads(struct ctl_table *table, int write,
3389b0daa2c7STobias Klauser 		       void *buffer, size_t *lenp, loff_t *ppos)
339016db3d3fSHeinrich Schuchardt {
339116db3d3fSHeinrich Schuchardt 	struct ctl_table t;
339216db3d3fSHeinrich Schuchardt 	int ret;
339316db3d3fSHeinrich Schuchardt 	int threads = max_threads;
3394b0f53dbcSMichal Hocko 	int min = 1;
339516db3d3fSHeinrich Schuchardt 	int max = MAX_THREADS;
339616db3d3fSHeinrich Schuchardt 
339716db3d3fSHeinrich Schuchardt 	t = *table;
339816db3d3fSHeinrich Schuchardt 	t.data = &threads;
339916db3d3fSHeinrich Schuchardt 	t.extra1 = &min;
340016db3d3fSHeinrich Schuchardt 	t.extra2 = &max;
340116db3d3fSHeinrich Schuchardt 
340216db3d3fSHeinrich Schuchardt 	ret = proc_dointvec_minmax(&t, write, buffer, lenp, ppos);
340316db3d3fSHeinrich Schuchardt 	if (ret || !write)
340416db3d3fSHeinrich Schuchardt 		return ret;
340516db3d3fSHeinrich Schuchardt 
3406b0f53dbcSMichal Hocko 	max_threads = threads;
340716db3d3fSHeinrich Schuchardt 
340816db3d3fSHeinrich Schuchardt 	return 0;
340916db3d3fSHeinrich Schuchardt }
3410