xref: /openbmc/linux/kernel/fork.c (revision 008cfe4418b3dbda2ff820cdd7b1a5ce458ae444)
1457c8996SThomas Gleixner // SPDX-License-Identifier: GPL-2.0-only
21da177e4SLinus Torvalds /*
31da177e4SLinus Torvalds  *  linux/kernel/fork.c
41da177e4SLinus Torvalds  *
51da177e4SLinus Torvalds  *  Copyright (C) 1991, 1992  Linus Torvalds
61da177e4SLinus Torvalds  */
71da177e4SLinus Torvalds 
81da177e4SLinus Torvalds /*
91da177e4SLinus Torvalds  *  'fork.c' contains the help-routines for the 'fork' system call
101da177e4SLinus Torvalds  * (see also entry.S and others).
111da177e4SLinus Torvalds  * Fork is rather simple, once you get the hang of it, but the memory
121da177e4SLinus Torvalds  * management can be a bitch. See 'mm/memory.c': 'copy_page_range()'
131da177e4SLinus Torvalds  */
141da177e4SLinus Torvalds 
15b3e58382SChristian Brauner #include <linux/anon_inodes.h>
161da177e4SLinus Torvalds #include <linux/slab.h>
174eb5aaa3SIngo Molnar #include <linux/sched/autogroup.h>
186e84f315SIngo Molnar #include <linux/sched/mm.h>
19f7ccbae4SIngo Molnar #include <linux/sched/coredump.h>
208703e8a4SIngo Molnar #include <linux/sched/user.h>
216a3827d7SIngo Molnar #include <linux/sched/numa_balancing.h>
2203441a34SIngo Molnar #include <linux/sched/stat.h>
2329930025SIngo Molnar #include <linux/sched/task.h>
2468db0cf1SIngo Molnar #include <linux/sched/task_stack.h>
2532ef5517SIngo Molnar #include <linux/sched/cputime.h>
26b3e58382SChristian Brauner #include <linux/seq_file.h>
27037741a6SIngo Molnar #include <linux/rtmutex.h>
281da177e4SLinus Torvalds #include <linux/init.h>
291da177e4SLinus Torvalds #include <linux/unistd.h>
301da177e4SLinus Torvalds #include <linux/module.h>
311da177e4SLinus Torvalds #include <linux/vmalloc.h>
321da177e4SLinus Torvalds #include <linux/completion.h>
331da177e4SLinus Torvalds #include <linux/personality.h>
341da177e4SLinus Torvalds #include <linux/mempolicy.h>
351da177e4SLinus Torvalds #include <linux/sem.h>
361da177e4SLinus Torvalds #include <linux/file.h>
379f3acc31SAl Viro #include <linux/fdtable.h>
38da9cbc87SJens Axboe #include <linux/iocontext.h>
391da177e4SLinus Torvalds #include <linux/key.h>
401da177e4SLinus Torvalds #include <linux/binfmts.h>
411da177e4SLinus Torvalds #include <linux/mman.h>
42cddb8a5cSAndrea Arcangeli #include <linux/mmu_notifier.h>
431da177e4SLinus Torvalds #include <linux/fs.h>
44615d6e87SDavidlohr Bueso #include <linux/mm.h>
45615d6e87SDavidlohr Bueso #include <linux/vmacache.h>
46ab516013SSerge E. Hallyn #include <linux/nsproxy.h>
47c59ede7bSRandy.Dunlap #include <linux/capability.h>
481da177e4SLinus Torvalds #include <linux/cpu.h>
49b4f48b63SPaul Menage #include <linux/cgroup.h>
501da177e4SLinus Torvalds #include <linux/security.h>
51a1e78772SMel Gorman #include <linux/hugetlb.h>
52e2cfabdfSWill Drewry #include <linux/seccomp.h>
531da177e4SLinus Torvalds #include <linux/swap.h>
541da177e4SLinus Torvalds #include <linux/syscalls.h>
551da177e4SLinus Torvalds #include <linux/jiffies.h>
561da177e4SLinus Torvalds #include <linux/futex.h>
578141c7f3SLinus Torvalds #include <linux/compat.h>
58207205a2SEric Dumazet #include <linux/kthread.h>
597c3ab738SAndrew Morton #include <linux/task_io_accounting_ops.h>
60ab2af1f5SDipankar Sarma #include <linux/rcupdate.h>
611da177e4SLinus Torvalds #include <linux/ptrace.h>
621da177e4SLinus Torvalds #include <linux/mount.h>
631da177e4SLinus Torvalds #include <linux/audit.h>
6478fb7466SPavel Emelianov #include <linux/memcontrol.h>
65f201ae23SFrederic Weisbecker #include <linux/ftrace.h>
665e2bf014SMike Galbraith #include <linux/proc_fs.h>
671da177e4SLinus Torvalds #include <linux/profile.h>
681da177e4SLinus Torvalds #include <linux/rmap.h>
69f8af4da3SHugh Dickins #include <linux/ksm.h>
701da177e4SLinus Torvalds #include <linux/acct.h>
71893e26e6SPavel Emelyanov #include <linux/userfaultfd_k.h>
728f0ab514SJay Lan #include <linux/tsacct_kern.h>
739f46080cSMatt Helsley #include <linux/cn_proc.h>
74ba96a0c8SRafael J. Wysocki #include <linux/freezer.h>
75ca74e92bSShailabh Nagar #include <linux/delayacct.h>
76ad4ecbcbSShailabh Nagar #include <linux/taskstats_kern.h>
770a425405SArjan van de Ven #include <linux/random.h>
78522ed776SMiloslav Trmac #include <linux/tty.h>
79fd0928dfSJens Axboe #include <linux/blkdev.h>
805ad4e53bSAl Viro #include <linux/fs_struct.h>
817c9f8861SEric Sandeen #include <linux/magic.h>
82cdd6c482SIngo Molnar #include <linux/perf_event.h>
8342c4ab41SStanislaw Gruszka #include <linux/posix-timers.h>
848e7cac79SAvi Kivity #include <linux/user-return-notifier.h>
853d5992d2SYing Han #include <linux/oom.h>
86ba76149fSAndrea Arcangeli #include <linux/khugepaged.h>
87d80e731eSOleg Nesterov #include <linux/signalfd.h>
880326f5a9SSrikar Dronamraju #include <linux/uprobes.h>
89a27bb332SKent Overstreet #include <linux/aio.h>
9052f5684cSGideon Israel Dsouza #include <linux/compiler.h>
9116db3d3fSHeinrich Schuchardt #include <linux/sysctl.h>
925c9a8750SDmitry Vyukov #include <linux/kcov.h>
93d83a7cb3SJosh Poimboeuf #include <linux/livepatch.h>
9448ac3c18SMark Rutland #include <linux/thread_info.h>
95afaef01cSAlexander Popov #include <linux/stackleak.h>
96eafb149eSDaniel Axtens #include <linux/kasan.h>
97d08b9f0cSSami Tolvanen #include <linux/scs.h>
981da177e4SLinus Torvalds 
991da177e4SLinus Torvalds #include <asm/pgalloc.h>
1007c0f6ba6SLinus Torvalds #include <linux/uaccess.h>
1011da177e4SLinus Torvalds #include <asm/mmu_context.h>
1021da177e4SLinus Torvalds #include <asm/cacheflush.h>
1031da177e4SLinus Torvalds #include <asm/tlbflush.h>
1041da177e4SLinus Torvalds 
105ad8d75ffSSteven Rostedt #include <trace/events/sched.h>
106ad8d75ffSSteven Rostedt 
10743d2b113SKAMEZAWA Hiroyuki #define CREATE_TRACE_POINTS
10843d2b113SKAMEZAWA Hiroyuki #include <trace/events/task.h>
10943d2b113SKAMEZAWA Hiroyuki 
1101da177e4SLinus Torvalds /*
111ac1b398dSHeinrich Schuchardt  * Minimum number of threads to boot the kernel
112ac1b398dSHeinrich Schuchardt  */
113ac1b398dSHeinrich Schuchardt #define MIN_THREADS 20
114ac1b398dSHeinrich Schuchardt 
115ac1b398dSHeinrich Schuchardt /*
116ac1b398dSHeinrich Schuchardt  * Maximum number of threads
117ac1b398dSHeinrich Schuchardt  */
118ac1b398dSHeinrich Schuchardt #define MAX_THREADS FUTEX_TID_MASK
119ac1b398dSHeinrich Schuchardt 
120ac1b398dSHeinrich Schuchardt /*
1211da177e4SLinus Torvalds  * Protected counters by write_lock_irq(&tasklist_lock)
1221da177e4SLinus Torvalds  */
1231da177e4SLinus Torvalds unsigned long total_forks;	/* Handle normal Linux uptimes. */
1241da177e4SLinus Torvalds int nr_threads;			/* The idle threads do not count.. */
1251da177e4SLinus Torvalds 
1268856ae4dSKefeng Wang static int max_threads;		/* tunable limit on nr_threads */
1271da177e4SLinus Torvalds 
1288495f7e6SSai Praneeth Prakhya #define NAMED_ARRAY_INDEX(x)	[x] = __stringify(x)
1298495f7e6SSai Praneeth Prakhya 
1308495f7e6SSai Praneeth Prakhya static const char * const resident_page_types[] = {
1318495f7e6SSai Praneeth Prakhya 	NAMED_ARRAY_INDEX(MM_FILEPAGES),
1328495f7e6SSai Praneeth Prakhya 	NAMED_ARRAY_INDEX(MM_ANONPAGES),
1338495f7e6SSai Praneeth Prakhya 	NAMED_ARRAY_INDEX(MM_SWAPENTS),
1348495f7e6SSai Praneeth Prakhya 	NAMED_ARRAY_INDEX(MM_SHMEMPAGES),
1358495f7e6SSai Praneeth Prakhya };
1368495f7e6SSai Praneeth Prakhya 
1371da177e4SLinus Torvalds DEFINE_PER_CPU(unsigned long, process_counts) = 0;
1381da177e4SLinus Torvalds 
1391da177e4SLinus Torvalds __cacheline_aligned DEFINE_RWLOCK(tasklist_lock);  /* outer */
140db1466b3SPaul E. McKenney 
141db1466b3SPaul E. McKenney #ifdef CONFIG_PROVE_RCU
142db1466b3SPaul E. McKenney int lockdep_tasklist_lock_is_held(void)
143db1466b3SPaul E. McKenney {
144db1466b3SPaul E. McKenney 	return lockdep_is_held(&tasklist_lock);
145db1466b3SPaul E. McKenney }
146db1466b3SPaul E. McKenney EXPORT_SYMBOL_GPL(lockdep_tasklist_lock_is_held);
147db1466b3SPaul E. McKenney #endif /* #ifdef CONFIG_PROVE_RCU */
1481da177e4SLinus Torvalds 
1491da177e4SLinus Torvalds int nr_processes(void)
1501da177e4SLinus Torvalds {
1511da177e4SLinus Torvalds 	int cpu;
1521da177e4SLinus Torvalds 	int total = 0;
1531da177e4SLinus Torvalds 
1541d510750SIan Campbell 	for_each_possible_cpu(cpu)
1551da177e4SLinus Torvalds 		total += per_cpu(process_counts, cpu);
1561da177e4SLinus Torvalds 
1571da177e4SLinus Torvalds 	return total;
1581da177e4SLinus Torvalds }
1591da177e4SLinus Torvalds 
160f19b9f74SAkinobu Mita void __weak arch_release_task_struct(struct task_struct *tsk)
161f19b9f74SAkinobu Mita {
162f19b9f74SAkinobu Mita }
163f19b9f74SAkinobu Mita 
164f5e10287SThomas Gleixner #ifndef CONFIG_ARCH_TASK_STRUCT_ALLOCATOR
165e18b890bSChristoph Lameter static struct kmem_cache *task_struct_cachep;
16641101809SThomas Gleixner 
16741101809SThomas Gleixner static inline struct task_struct *alloc_task_struct_node(int node)
16841101809SThomas Gleixner {
16941101809SThomas Gleixner 	return kmem_cache_alloc_node(task_struct_cachep, GFP_KERNEL, node);
17041101809SThomas Gleixner }
17141101809SThomas Gleixner 
17241101809SThomas Gleixner static inline void free_task_struct(struct task_struct *tsk)
17341101809SThomas Gleixner {
17441101809SThomas Gleixner 	kmem_cache_free(task_struct_cachep, tsk);
17541101809SThomas Gleixner }
1761da177e4SLinus Torvalds #endif
1771da177e4SLinus Torvalds 
178b235beeaSLinus Torvalds #ifndef CONFIG_ARCH_THREAD_STACK_ALLOCATOR
17941101809SThomas Gleixner 
1800d15d74aSThomas Gleixner /*
1810d15d74aSThomas Gleixner  * Allocate pages if THREAD_SIZE is >= PAGE_SIZE, otherwise use a
1820d15d74aSThomas Gleixner  * kmemcache based allocator.
1830d15d74aSThomas Gleixner  */
184ba14a194SAndy Lutomirski # if THREAD_SIZE >= PAGE_SIZE || defined(CONFIG_VMAP_STACK)
185ac496bf4SAndy Lutomirski 
186ac496bf4SAndy Lutomirski #ifdef CONFIG_VMAP_STACK
187ac496bf4SAndy Lutomirski /*
188ac496bf4SAndy Lutomirski  * vmalloc() is a bit slow, and calling vfree() enough times will force a TLB
189ac496bf4SAndy Lutomirski  * flush.  Try to minimize the number of calls by caching stacks.
190ac496bf4SAndy Lutomirski  */
191ac496bf4SAndy Lutomirski #define NR_CACHED_STACKS 2
192ac496bf4SAndy Lutomirski static DEFINE_PER_CPU(struct vm_struct *, cached_stacks[NR_CACHED_STACKS]);
19319659c59SHoeun Ryu 
19419659c59SHoeun Ryu static int free_vm_stack_cache(unsigned int cpu)
19519659c59SHoeun Ryu {
19619659c59SHoeun Ryu 	struct vm_struct **cached_vm_stacks = per_cpu_ptr(cached_stacks, cpu);
19719659c59SHoeun Ryu 	int i;
19819659c59SHoeun Ryu 
19919659c59SHoeun Ryu 	for (i = 0; i < NR_CACHED_STACKS; i++) {
20019659c59SHoeun Ryu 		struct vm_struct *vm_stack = cached_vm_stacks[i];
20119659c59SHoeun Ryu 
20219659c59SHoeun Ryu 		if (!vm_stack)
20319659c59SHoeun Ryu 			continue;
20419659c59SHoeun Ryu 
20519659c59SHoeun Ryu 		vfree(vm_stack->addr);
20619659c59SHoeun Ryu 		cached_vm_stacks[i] = NULL;
20719659c59SHoeun Ryu 	}
20819659c59SHoeun Ryu 
20919659c59SHoeun Ryu 	return 0;
21019659c59SHoeun Ryu }
211ac496bf4SAndy Lutomirski #endif
212ac496bf4SAndy Lutomirski 
213ba14a194SAndy Lutomirski static unsigned long *alloc_thread_stack_node(struct task_struct *tsk, int node)
214b69c49b7SFUJITA Tomonori {
215ba14a194SAndy Lutomirski #ifdef CONFIG_VMAP_STACK
216ac496bf4SAndy Lutomirski 	void *stack;
217ac496bf4SAndy Lutomirski 	int i;
218ac496bf4SAndy Lutomirski 
219ac496bf4SAndy Lutomirski 	for (i = 0; i < NR_CACHED_STACKS; i++) {
220112166f8SChristoph Lameter 		struct vm_struct *s;
221112166f8SChristoph Lameter 
222112166f8SChristoph Lameter 		s = this_cpu_xchg(cached_stacks[i], NULL);
223ac496bf4SAndy Lutomirski 
224ac496bf4SAndy Lutomirski 		if (!s)
225ac496bf4SAndy Lutomirski 			continue;
226ac496bf4SAndy Lutomirski 
227eafb149eSDaniel Axtens 		/* Clear the KASAN shadow of the stack. */
228eafb149eSDaniel Axtens 		kasan_unpoison_shadow(s->addr, THREAD_SIZE);
229eafb149eSDaniel Axtens 
230ca182551SKonstantin Khlebnikov 		/* Clear stale pointers from reused stack. */
231ca182551SKonstantin Khlebnikov 		memset(s->addr, 0, THREAD_SIZE);
232e01e8063SKees Cook 
233ac496bf4SAndy Lutomirski 		tsk->stack_vm_area = s;
234ba4a4574SShakeel Butt 		tsk->stack = s->addr;
235ac496bf4SAndy Lutomirski 		return s->addr;
236ac496bf4SAndy Lutomirski 	}
237ac496bf4SAndy Lutomirski 
2389b6f7e16SRoman Gushchin 	/*
2399b6f7e16SRoman Gushchin 	 * Allocated stacks are cached and later reused by new threads,
2409b6f7e16SRoman Gushchin 	 * so memcg accounting is performed manually on assigning/releasing
2419b6f7e16SRoman Gushchin 	 * stacks to tasks. Drop __GFP_ACCOUNT.
2429b6f7e16SRoman Gushchin 	 */
24348ac3c18SMark Rutland 	stack = __vmalloc_node_range(THREAD_SIZE, THREAD_ALIGN,
244ba14a194SAndy Lutomirski 				     VMALLOC_START, VMALLOC_END,
2459b6f7e16SRoman Gushchin 				     THREADINFO_GFP & ~__GFP_ACCOUNT,
246ba14a194SAndy Lutomirski 				     PAGE_KERNEL,
247ac496bf4SAndy Lutomirski 				     0, node, __builtin_return_address(0));
248ba14a194SAndy Lutomirski 
249ba14a194SAndy Lutomirski 	/*
250ba14a194SAndy Lutomirski 	 * We can't call find_vm_area() in interrupt context, and
251ba14a194SAndy Lutomirski 	 * free_thread_stack() can be called in interrupt context,
252ba14a194SAndy Lutomirski 	 * so cache the vm_struct.
253ba14a194SAndy Lutomirski 	 */
2545eed6f1dSRik van Riel 	if (stack) {
255ba14a194SAndy Lutomirski 		tsk->stack_vm_area = find_vm_area(stack);
2565eed6f1dSRik van Riel 		tsk->stack = stack;
2575eed6f1dSRik van Riel 	}
258ba14a194SAndy Lutomirski 	return stack;
259ba14a194SAndy Lutomirski #else
2604949148aSVladimir Davydov 	struct page *page = alloc_pages_node(node, THREADINFO_GFP,
2612889f608SThomas Gleixner 					     THREAD_SIZE_ORDER);
262b6a84016SEric Dumazet 
2631bf4580eSAndrea Arcangeli 	if (likely(page)) {
2648dcc1d34SAndrey Konovalov 		tsk->stack = kasan_reset_tag(page_address(page));
2651bf4580eSAndrea Arcangeli 		return tsk->stack;
2661bf4580eSAndrea Arcangeli 	}
2671bf4580eSAndrea Arcangeli 	return NULL;
268ba14a194SAndy Lutomirski #endif
269b69c49b7SFUJITA Tomonori }
270b69c49b7SFUJITA Tomonori 
271ba14a194SAndy Lutomirski static inline void free_thread_stack(struct task_struct *tsk)
272b69c49b7SFUJITA Tomonori {
273ac496bf4SAndy Lutomirski #ifdef CONFIG_VMAP_STACK
2749b6f7e16SRoman Gushchin 	struct vm_struct *vm = task_stack_vm_area(tsk);
2759b6f7e16SRoman Gushchin 
2769b6f7e16SRoman Gushchin 	if (vm) {
277ac496bf4SAndy Lutomirski 		int i;
278ac496bf4SAndy Lutomirski 
279991e7673SShakeel Butt 		for (i = 0; i < THREAD_SIZE / PAGE_SIZE; i++)
280f4b00eabSRoman Gushchin 			memcg_kmem_uncharge_page(vm->pages[i], 0);
2819b6f7e16SRoman Gushchin 
282ac496bf4SAndy Lutomirski 		for (i = 0; i < NR_CACHED_STACKS; i++) {
283112166f8SChristoph Lameter 			if (this_cpu_cmpxchg(cached_stacks[i],
284112166f8SChristoph Lameter 					NULL, tsk->stack_vm_area) != NULL)
285ac496bf4SAndy Lutomirski 				continue;
286ac496bf4SAndy Lutomirski 
287ac496bf4SAndy Lutomirski 			return;
288ac496bf4SAndy Lutomirski 		}
289ac496bf4SAndy Lutomirski 
2900f110a9bSAndrey Ryabinin 		vfree_atomic(tsk->stack);
291ac496bf4SAndy Lutomirski 		return;
292ac496bf4SAndy Lutomirski 	}
293ac496bf4SAndy Lutomirski #endif
294ac496bf4SAndy Lutomirski 
295ba14a194SAndy Lutomirski 	__free_pages(virt_to_page(tsk->stack), THREAD_SIZE_ORDER);
296b69c49b7SFUJITA Tomonori }
2970d15d74aSThomas Gleixner # else
298b235beeaSLinus Torvalds static struct kmem_cache *thread_stack_cache;
2990d15d74aSThomas Gleixner 
3009521d399SMichael Ellerman static unsigned long *alloc_thread_stack_node(struct task_struct *tsk,
3010d15d74aSThomas Gleixner 						  int node)
3020d15d74aSThomas Gleixner {
3035eed6f1dSRik van Riel 	unsigned long *stack;
3045eed6f1dSRik van Riel 	stack = kmem_cache_alloc_node(thread_stack_cache, THREADINFO_GFP, node);
3058dcc1d34SAndrey Konovalov 	stack = kasan_reset_tag(stack);
3065eed6f1dSRik van Riel 	tsk->stack = stack;
3075eed6f1dSRik van Riel 	return stack;
3080d15d74aSThomas Gleixner }
3090d15d74aSThomas Gleixner 
310ba14a194SAndy Lutomirski static void free_thread_stack(struct task_struct *tsk)
3110d15d74aSThomas Gleixner {
312ba14a194SAndy Lutomirski 	kmem_cache_free(thread_stack_cache, tsk->stack);
3130d15d74aSThomas Gleixner }
3140d15d74aSThomas Gleixner 
315b235beeaSLinus Torvalds void thread_stack_cache_init(void)
3160d15d74aSThomas Gleixner {
317f9d29946SDavid Windsor 	thread_stack_cache = kmem_cache_create_usercopy("thread_stack",
318f9d29946SDavid Windsor 					THREAD_SIZE, THREAD_SIZE, 0, 0,
319f9d29946SDavid Windsor 					THREAD_SIZE, NULL);
320b235beeaSLinus Torvalds 	BUG_ON(thread_stack_cache == NULL);
3210d15d74aSThomas Gleixner }
3220d15d74aSThomas Gleixner # endif
323b69c49b7SFUJITA Tomonori #endif
324b69c49b7SFUJITA Tomonori 
3251da177e4SLinus Torvalds /* SLAB cache for signal_struct structures (tsk->signal) */
326e18b890bSChristoph Lameter static struct kmem_cache *signal_cachep;
3271da177e4SLinus Torvalds 
3281da177e4SLinus Torvalds /* SLAB cache for sighand_struct structures (tsk->sighand) */
329e18b890bSChristoph Lameter struct kmem_cache *sighand_cachep;
3301da177e4SLinus Torvalds 
3311da177e4SLinus Torvalds /* SLAB cache for files_struct structures (tsk->files) */
332e18b890bSChristoph Lameter struct kmem_cache *files_cachep;
3331da177e4SLinus Torvalds 
3341da177e4SLinus Torvalds /* SLAB cache for fs_struct structures (tsk->fs) */
335e18b890bSChristoph Lameter struct kmem_cache *fs_cachep;
3361da177e4SLinus Torvalds 
3371da177e4SLinus Torvalds /* SLAB cache for vm_area_struct structures */
3383928d4f5SLinus Torvalds static struct kmem_cache *vm_area_cachep;
3391da177e4SLinus Torvalds 
3401da177e4SLinus Torvalds /* SLAB cache for mm_struct structures (tsk->mm) */
341e18b890bSChristoph Lameter static struct kmem_cache *mm_cachep;
3421da177e4SLinus Torvalds 
343490fc053SLinus Torvalds struct vm_area_struct *vm_area_alloc(struct mm_struct *mm)
3443928d4f5SLinus Torvalds {
345a670468fSAndrew Morton 	struct vm_area_struct *vma;
346490fc053SLinus Torvalds 
347a670468fSAndrew Morton 	vma = kmem_cache_alloc(vm_area_cachep, GFP_KERNEL);
348027232daSKirill A. Shutemov 	if (vma)
349027232daSKirill A. Shutemov 		vma_init(vma, mm);
350490fc053SLinus Torvalds 	return vma;
3513928d4f5SLinus Torvalds }
3523928d4f5SLinus Torvalds 
3533928d4f5SLinus Torvalds struct vm_area_struct *vm_area_dup(struct vm_area_struct *orig)
3543928d4f5SLinus Torvalds {
35595faf699SLinus Torvalds 	struct vm_area_struct *new = kmem_cache_alloc(vm_area_cachep, GFP_KERNEL);
35695faf699SLinus Torvalds 
35795faf699SLinus Torvalds 	if (new) {
358cda099b3SQian Cai 		ASSERT_EXCLUSIVE_WRITER(orig->vm_flags);
359cda099b3SQian Cai 		ASSERT_EXCLUSIVE_WRITER(orig->vm_file);
360cda099b3SQian Cai 		/*
361cda099b3SQian Cai 		 * orig->shared.rb may be modified concurrently, but the clone
362cda099b3SQian Cai 		 * will be reinitialized.
363cda099b3SQian Cai 		 */
364cda099b3SQian Cai 		*new = data_race(*orig);
36595faf699SLinus Torvalds 		INIT_LIST_HEAD(&new->anon_vma_chain);
366e39a4b33SLi Xinhai 		new->vm_next = new->vm_prev = NULL;
36795faf699SLinus Torvalds 	}
36895faf699SLinus Torvalds 	return new;
3693928d4f5SLinus Torvalds }
3703928d4f5SLinus Torvalds 
3713928d4f5SLinus Torvalds void vm_area_free(struct vm_area_struct *vma)
3723928d4f5SLinus Torvalds {
3733928d4f5SLinus Torvalds 	kmem_cache_free(vm_area_cachep, vma);
3743928d4f5SLinus Torvalds }
3753928d4f5SLinus Torvalds 
376ba14a194SAndy Lutomirski static void account_kernel_stack(struct task_struct *tsk, int account)
377c6a7f572SKOSAKI Motohiro {
378ba14a194SAndy Lutomirski 	void *stack = task_stack_page(tsk);
379ba14a194SAndy Lutomirski 	struct vm_struct *vm = task_stack_vm_area(tsk);
380ba14a194SAndy Lutomirski 
381ba14a194SAndy Lutomirski 
382991e7673SShakeel Butt 	/* All stack pages are in the same node. */
383991e7673SShakeel Butt 	if (vm)
384991e7673SShakeel Butt 		mod_lruvec_page_state(vm->pages[0], NR_KERNEL_STACK_KB,
385efdc9490SAndy Lutomirski 				      account * (THREAD_SIZE / 1024));
386991e7673SShakeel Butt 	else
387991e7673SShakeel Butt 		mod_lruvec_slab_state(stack, NR_KERNEL_STACK_KB,
388991e7673SShakeel Butt 				      account * (THREAD_SIZE / 1024));
389ba14a194SAndy Lutomirski }
390c6a7f572SKOSAKI Motohiro 
3919b6f7e16SRoman Gushchin static int memcg_charge_kernel_stack(struct task_struct *tsk)
3929b6f7e16SRoman Gushchin {
3939b6f7e16SRoman Gushchin #ifdef CONFIG_VMAP_STACK
3949b6f7e16SRoman Gushchin 	struct vm_struct *vm = task_stack_vm_area(tsk);
3959b6f7e16SRoman Gushchin 	int ret;
3969b6f7e16SRoman Gushchin 
397991e7673SShakeel Butt 	BUILD_BUG_ON(IS_ENABLED(CONFIG_VMAP_STACK) && PAGE_SIZE % 1024 != 0);
398991e7673SShakeel Butt 
3999b6f7e16SRoman Gushchin 	if (vm) {
4009b6f7e16SRoman Gushchin 		int i;
4019b6f7e16SRoman Gushchin 
402991e7673SShakeel Butt 		BUG_ON(vm->nr_pages != THREAD_SIZE / PAGE_SIZE);
403991e7673SShakeel Butt 
4049b6f7e16SRoman Gushchin 		for (i = 0; i < THREAD_SIZE / PAGE_SIZE; i++) {
4059b6f7e16SRoman Gushchin 			/*
406f4b00eabSRoman Gushchin 			 * If memcg_kmem_charge_page() fails, page->mem_cgroup
407991e7673SShakeel Butt 			 * pointer is NULL, and memcg_kmem_uncharge_page() in
408991e7673SShakeel Butt 			 * free_thread_stack() will ignore this page.
4099b6f7e16SRoman Gushchin 			 */
410f4b00eabSRoman Gushchin 			ret = memcg_kmem_charge_page(vm->pages[i], GFP_KERNEL,
411f4b00eabSRoman Gushchin 						     0);
4129b6f7e16SRoman Gushchin 			if (ret)
4139b6f7e16SRoman Gushchin 				return ret;
4149b6f7e16SRoman Gushchin 		}
4159b6f7e16SRoman Gushchin 	}
4169b6f7e16SRoman Gushchin #endif
4179b6f7e16SRoman Gushchin 	return 0;
4189b6f7e16SRoman Gushchin }
4199b6f7e16SRoman Gushchin 
42068f24b08SAndy Lutomirski static void release_task_stack(struct task_struct *tsk)
4211da177e4SLinus Torvalds {
422405c0759SAndy Lutomirski 	if (WARN_ON(tsk->state != TASK_DEAD))
423405c0759SAndy Lutomirski 		return;  /* Better to leak the stack than to free prematurely */
424405c0759SAndy Lutomirski 
425ba14a194SAndy Lutomirski 	account_kernel_stack(tsk, -1);
426ba14a194SAndy Lutomirski 	free_thread_stack(tsk);
42768f24b08SAndy Lutomirski 	tsk->stack = NULL;
42868f24b08SAndy Lutomirski #ifdef CONFIG_VMAP_STACK
42968f24b08SAndy Lutomirski 	tsk->stack_vm_area = NULL;
43068f24b08SAndy Lutomirski #endif
43168f24b08SAndy Lutomirski }
43268f24b08SAndy Lutomirski 
43368f24b08SAndy Lutomirski #ifdef CONFIG_THREAD_INFO_IN_TASK
43468f24b08SAndy Lutomirski void put_task_stack(struct task_struct *tsk)
43568f24b08SAndy Lutomirski {
436f0b89d39SElena Reshetova 	if (refcount_dec_and_test(&tsk->stack_refcount))
43768f24b08SAndy Lutomirski 		release_task_stack(tsk);
43868f24b08SAndy Lutomirski }
43968f24b08SAndy Lutomirski #endif
44068f24b08SAndy Lutomirski 
44168f24b08SAndy Lutomirski void free_task(struct task_struct *tsk)
44268f24b08SAndy Lutomirski {
443d08b9f0cSSami Tolvanen 	scs_release(tsk);
444d08b9f0cSSami Tolvanen 
44568f24b08SAndy Lutomirski #ifndef CONFIG_THREAD_INFO_IN_TASK
44668f24b08SAndy Lutomirski 	/*
44768f24b08SAndy Lutomirski 	 * The task is finally done with both the stack and thread_info,
44868f24b08SAndy Lutomirski 	 * so free both.
44968f24b08SAndy Lutomirski 	 */
45068f24b08SAndy Lutomirski 	release_task_stack(tsk);
45168f24b08SAndy Lutomirski #else
45268f24b08SAndy Lutomirski 	/*
45368f24b08SAndy Lutomirski 	 * If the task had a separate stack allocation, it should be gone
45468f24b08SAndy Lutomirski 	 * by now.
45568f24b08SAndy Lutomirski 	 */
456f0b89d39SElena Reshetova 	WARN_ON_ONCE(refcount_read(&tsk->stack_refcount) != 0);
45768f24b08SAndy Lutomirski #endif
45823f78d4aSIngo Molnar 	rt_mutex_debug_task_free(tsk);
459fb52607aSFrederic Weisbecker 	ftrace_graph_exit_task(tsk);
460f19b9f74SAkinobu Mita 	arch_release_task_struct(tsk);
4611da5c46fSOleg Nesterov 	if (tsk->flags & PF_KTHREAD)
4621da5c46fSOleg Nesterov 		free_kthread_struct(tsk);
4631da177e4SLinus Torvalds 	free_task_struct(tsk);
4641da177e4SLinus Torvalds }
4651da177e4SLinus Torvalds EXPORT_SYMBOL(free_task);
4661da177e4SLinus Torvalds 
4671da177e4SLinus Torvalds #ifdef CONFIG_MMU
4680766f788SEmese Revfy static __latent_entropy int dup_mmap(struct mm_struct *mm,
4690766f788SEmese Revfy 					struct mm_struct *oldmm)
4701da177e4SLinus Torvalds {
471297c5eeeSLinus Torvalds 	struct vm_area_struct *mpnt, *tmp, *prev, **pprev;
4721da177e4SLinus Torvalds 	struct rb_node **rb_link, *rb_parent;
4731da177e4SLinus Torvalds 	int retval;
4741da177e4SLinus Torvalds 	unsigned long charge;
475893e26e6SPavel Emelyanov 	LIST_HEAD(uf);
4761da177e4SLinus Torvalds 
47732cdba1eSOleg Nesterov 	uprobe_start_dup_mmap();
478d8ed45c5SMichel Lespinasse 	if (mmap_write_lock_killable(oldmm)) {
4797c051267SMichal Hocko 		retval = -EINTR;
4807c051267SMichal Hocko 		goto fail_uprobe_end;
4817c051267SMichal Hocko 	}
482ec8c0446SRalf Baechle 	flush_cache_dup_mm(oldmm);
483f8ac4ec9SOleg Nesterov 	uprobe_dup_mmap(oldmm, mm);
484ad339451SIngo Molnar 	/*
485ad339451SIngo Molnar 	 * Not linked in yet - no deadlock potential:
486ad339451SIngo Molnar 	 */
487aaa2cc56SMichel Lespinasse 	mmap_write_lock_nested(mm, SINGLE_DEPTH_NESTING);
4887ee78232SHugh Dickins 
48990f31d0eSKonstantin Khlebnikov 	/* No ordering required: file already has been exposed. */
49090f31d0eSKonstantin Khlebnikov 	RCU_INIT_POINTER(mm->exe_file, get_mm_exe_file(oldmm));
49190f31d0eSKonstantin Khlebnikov 
4924f7d4614SVladimir Davydov 	mm->total_vm = oldmm->total_vm;
49384638335SKonstantin Khlebnikov 	mm->data_vm = oldmm->data_vm;
4944f7d4614SVladimir Davydov 	mm->exec_vm = oldmm->exec_vm;
4954f7d4614SVladimir Davydov 	mm->stack_vm = oldmm->stack_vm;
4964f7d4614SVladimir Davydov 
4971da177e4SLinus Torvalds 	rb_link = &mm->mm_rb.rb_node;
4981da177e4SLinus Torvalds 	rb_parent = NULL;
4991da177e4SLinus Torvalds 	pprev = &mm->mmap;
500f8af4da3SHugh Dickins 	retval = ksm_fork(mm, oldmm);
501f8af4da3SHugh Dickins 	if (retval)
502f8af4da3SHugh Dickins 		goto out;
503ba76149fSAndrea Arcangeli 	retval = khugepaged_fork(mm, oldmm);
504ba76149fSAndrea Arcangeli 	if (retval)
505ba76149fSAndrea Arcangeli 		goto out;
5061da177e4SLinus Torvalds 
507297c5eeeSLinus Torvalds 	prev = NULL;
508fd3e42fcSHugh Dickins 	for (mpnt = oldmm->mmap; mpnt; mpnt = mpnt->vm_next) {
5091da177e4SLinus Torvalds 		struct file *file;
5101da177e4SLinus Torvalds 
5111da177e4SLinus Torvalds 		if (mpnt->vm_flags & VM_DONTCOPY) {
51284638335SKonstantin Khlebnikov 			vm_stat_account(mm, mpnt->vm_flags, -vma_pages(mpnt));
5131da177e4SLinus Torvalds 			continue;
5141da177e4SLinus Torvalds 		}
5151da177e4SLinus Torvalds 		charge = 0;
516655c79bbSTetsuo Handa 		/*
517655c79bbSTetsuo Handa 		 * Don't duplicate many vmas if we've been oom-killed (for
518655c79bbSTetsuo Handa 		 * example)
519655c79bbSTetsuo Handa 		 */
520655c79bbSTetsuo Handa 		if (fatal_signal_pending(current)) {
521655c79bbSTetsuo Handa 			retval = -EINTR;
522655c79bbSTetsuo Handa 			goto out;
523655c79bbSTetsuo Handa 		}
5241da177e4SLinus Torvalds 		if (mpnt->vm_flags & VM_ACCOUNT) {
525b2412b7fSHuang Shijie 			unsigned long len = vma_pages(mpnt);
526b2412b7fSHuang Shijie 
527191c5424SAl Viro 			if (security_vm_enough_memory_mm(oldmm, len)) /* sic */
5281da177e4SLinus Torvalds 				goto fail_nomem;
5291da177e4SLinus Torvalds 			charge = len;
5301da177e4SLinus Torvalds 		}
5313928d4f5SLinus Torvalds 		tmp = vm_area_dup(mpnt);
5321da177e4SLinus Torvalds 		if (!tmp)
5331da177e4SLinus Torvalds 			goto fail_nomem;
534ef0855d3SOleg Nesterov 		retval = vma_dup_policy(mpnt, tmp);
535ef0855d3SOleg Nesterov 		if (retval)
5361da177e4SLinus Torvalds 			goto fail_nomem_policy;
537a247c3a9SAndrea Arcangeli 		tmp->vm_mm = mm;
538893e26e6SPavel Emelyanov 		retval = dup_userfaultfd(tmp, &uf);
539893e26e6SPavel Emelyanov 		if (retval)
540893e26e6SPavel Emelyanov 			goto fail_nomem_anon_vma_fork;
541d2cd9edeSRik van Riel 		if (tmp->vm_flags & VM_WIPEONFORK) {
54293949bb2SLi Xinhai 			/*
54393949bb2SLi Xinhai 			 * VM_WIPEONFORK gets a clean slate in the child.
54493949bb2SLi Xinhai 			 * Don't prepare anon_vma until fault since we don't
54593949bb2SLi Xinhai 			 * copy page for current vma.
54693949bb2SLi Xinhai 			 */
547d2cd9edeSRik van Riel 			tmp->anon_vma = NULL;
548d2cd9edeSRik van Riel 		} else if (anon_vma_fork(tmp, mpnt))
5495beb4930SRik van Riel 			goto fail_nomem_anon_vma_fork;
550893e26e6SPavel Emelyanov 		tmp->vm_flags &= ~(VM_LOCKED | VM_LOCKONFAULT);
5511da177e4SLinus Torvalds 		file = tmp->vm_file;
5521da177e4SLinus Torvalds 		if (file) {
553496ad9aaSAl Viro 			struct inode *inode = file_inode(file);
554b88ed205SHugh Dickins 			struct address_space *mapping = file->f_mapping;
555b88ed205SHugh Dickins 
5561da177e4SLinus Torvalds 			get_file(file);
5571da177e4SLinus Torvalds 			if (tmp->vm_flags & VM_DENYWRITE)
5581da177e4SLinus Torvalds 				atomic_dec(&inode->i_writecount);
55983cde9e8SDavidlohr Bueso 			i_mmap_lock_write(mapping);
560b88ed205SHugh Dickins 			if (tmp->vm_flags & VM_SHARED)
5614bb5f5d9SDavid Herrmann 				atomic_inc(&mapping->i_mmap_writable);
562b88ed205SHugh Dickins 			flush_dcache_mmap_lock(mapping);
563b88ed205SHugh Dickins 			/* insert tmp into the share list, just after mpnt */
5649826a516SMichel Lespinasse 			vma_interval_tree_insert_after(tmp, mpnt,
5659826a516SMichel Lespinasse 					&mapping->i_mmap);
566b88ed205SHugh Dickins 			flush_dcache_mmap_unlock(mapping);
56783cde9e8SDavidlohr Bueso 			i_mmap_unlock_write(mapping);
5681da177e4SLinus Torvalds 		}
5691da177e4SLinus Torvalds 
5701da177e4SLinus Torvalds 		/*
571a1e78772SMel Gorman 		 * Clear hugetlb-related page reserves for children. This only
572a1e78772SMel Gorman 		 * affects MAP_PRIVATE mappings. Faults generated by the child
573a1e78772SMel Gorman 		 * are not guaranteed to succeed, even if read-only
574a1e78772SMel Gorman 		 */
575a1e78772SMel Gorman 		if (is_vm_hugetlb_page(tmp))
576a1e78772SMel Gorman 			reset_vma_resv_huge_pages(tmp);
577a1e78772SMel Gorman 
578a1e78772SMel Gorman 		/*
5797ee78232SHugh Dickins 		 * Link in the new vma and copy the page table entries.
5801da177e4SLinus Torvalds 		 */
5811da177e4SLinus Torvalds 		*pprev = tmp;
5821da177e4SLinus Torvalds 		pprev = &tmp->vm_next;
583297c5eeeSLinus Torvalds 		tmp->vm_prev = prev;
584297c5eeeSLinus Torvalds 		prev = tmp;
5851da177e4SLinus Torvalds 
5861da177e4SLinus Torvalds 		__vma_link_rb(mm, tmp, rb_link, rb_parent);
5871da177e4SLinus Torvalds 		rb_link = &tmp->vm_rb.rb_right;
5881da177e4SLinus Torvalds 		rb_parent = &tmp->vm_rb;
5891da177e4SLinus Torvalds 
5901da177e4SLinus Torvalds 		mm->map_count++;
591d2cd9edeSRik van Riel 		if (!(tmp->vm_flags & VM_WIPEONFORK))
5920b0db14cSHugh Dickins 			retval = copy_page_range(mm, oldmm, mpnt);
5931da177e4SLinus Torvalds 
5941da177e4SLinus Torvalds 		if (tmp->vm_ops && tmp->vm_ops->open)
5951da177e4SLinus Torvalds 			tmp->vm_ops->open(tmp);
5961da177e4SLinus Torvalds 
5971da177e4SLinus Torvalds 		if (retval)
5981da177e4SLinus Torvalds 			goto out;
5991da177e4SLinus Torvalds 	}
600d6dd61c8SJeremy Fitzhardinge 	/* a new mm has just been created */
6011ed0cc5aSNadav Amit 	retval = arch_dup_mmap(oldmm, mm);
6021da177e4SLinus Torvalds out:
603d8ed45c5SMichel Lespinasse 	mmap_write_unlock(mm);
604fd3e42fcSHugh Dickins 	flush_tlb_mm(oldmm);
605d8ed45c5SMichel Lespinasse 	mmap_write_unlock(oldmm);
606893e26e6SPavel Emelyanov 	dup_userfaultfd_complete(&uf);
6077c051267SMichal Hocko fail_uprobe_end:
60832cdba1eSOleg Nesterov 	uprobe_end_dup_mmap();
6091da177e4SLinus Torvalds 	return retval;
6105beb4930SRik van Riel fail_nomem_anon_vma_fork:
611ef0855d3SOleg Nesterov 	mpol_put(vma_policy(tmp));
6121da177e4SLinus Torvalds fail_nomem_policy:
6133928d4f5SLinus Torvalds 	vm_area_free(tmp);
6141da177e4SLinus Torvalds fail_nomem:
6151da177e4SLinus Torvalds 	retval = -ENOMEM;
6161da177e4SLinus Torvalds 	vm_unacct_memory(charge);
6171da177e4SLinus Torvalds 	goto out;
6181da177e4SLinus Torvalds }
6191da177e4SLinus Torvalds 
6201da177e4SLinus Torvalds static inline int mm_alloc_pgd(struct mm_struct *mm)
6211da177e4SLinus Torvalds {
6221da177e4SLinus Torvalds 	mm->pgd = pgd_alloc(mm);
6231da177e4SLinus Torvalds 	if (unlikely(!mm->pgd))
6241da177e4SLinus Torvalds 		return -ENOMEM;
6251da177e4SLinus Torvalds 	return 0;
6261da177e4SLinus Torvalds }
6271da177e4SLinus Torvalds 
6281da177e4SLinus Torvalds static inline void mm_free_pgd(struct mm_struct *mm)
6291da177e4SLinus Torvalds {
6305e541973SBenjamin Herrenschmidt 	pgd_free(mm, mm->pgd);
6311da177e4SLinus Torvalds }
6321da177e4SLinus Torvalds #else
63390f31d0eSKonstantin Khlebnikov static int dup_mmap(struct mm_struct *mm, struct mm_struct *oldmm)
63490f31d0eSKonstantin Khlebnikov {
635d8ed45c5SMichel Lespinasse 	mmap_write_lock(oldmm);
63690f31d0eSKonstantin Khlebnikov 	RCU_INIT_POINTER(mm->exe_file, get_mm_exe_file(oldmm));
637d8ed45c5SMichel Lespinasse 	mmap_write_unlock(oldmm);
63890f31d0eSKonstantin Khlebnikov 	return 0;
63990f31d0eSKonstantin Khlebnikov }
6401da177e4SLinus Torvalds #define mm_alloc_pgd(mm)	(0)
6411da177e4SLinus Torvalds #define mm_free_pgd(mm)
6421da177e4SLinus Torvalds #endif /* CONFIG_MMU */
6431da177e4SLinus Torvalds 
644d70f2a14SAndrew Morton static void check_mm(struct mm_struct *mm)
645d70f2a14SAndrew Morton {
646d70f2a14SAndrew Morton 	int i;
647d70f2a14SAndrew Morton 
6488495f7e6SSai Praneeth Prakhya 	BUILD_BUG_ON_MSG(ARRAY_SIZE(resident_page_types) != NR_MM_COUNTERS,
6498495f7e6SSai Praneeth Prakhya 			 "Please make sure 'struct resident_page_types[]' is updated as well");
6508495f7e6SSai Praneeth Prakhya 
651d70f2a14SAndrew Morton 	for (i = 0; i < NR_MM_COUNTERS; i++) {
652d70f2a14SAndrew Morton 		long x = atomic_long_read(&mm->rss_stat.count[i]);
653d70f2a14SAndrew Morton 
654d70f2a14SAndrew Morton 		if (unlikely(x))
6558495f7e6SSai Praneeth Prakhya 			pr_alert("BUG: Bad rss-counter state mm:%p type:%s val:%ld\n",
6568495f7e6SSai Praneeth Prakhya 				 mm, resident_page_types[i], x);
657d70f2a14SAndrew Morton 	}
658d70f2a14SAndrew Morton 
659d70f2a14SAndrew Morton 	if (mm_pgtables_bytes(mm))
660d70f2a14SAndrew Morton 		pr_alert("BUG: non-zero pgtables_bytes on freeing mm: %ld\n",
661d70f2a14SAndrew Morton 				mm_pgtables_bytes(mm));
662d70f2a14SAndrew Morton 
663d70f2a14SAndrew Morton #if defined(CONFIG_TRANSPARENT_HUGEPAGE) && !USE_SPLIT_PMD_PTLOCKS
664d70f2a14SAndrew Morton 	VM_BUG_ON_MM(mm->pmd_huge_pte, mm);
665d70f2a14SAndrew Morton #endif
666d70f2a14SAndrew Morton }
6671da177e4SLinus Torvalds 
668e94b1766SChristoph Lameter #define allocate_mm()	(kmem_cache_alloc(mm_cachep, GFP_KERNEL))
6691da177e4SLinus Torvalds #define free_mm(mm)	(kmem_cache_free(mm_cachep, (mm)))
6701da177e4SLinus Torvalds 
671d70f2a14SAndrew Morton /*
672d70f2a14SAndrew Morton  * Called when the last reference to the mm
673d70f2a14SAndrew Morton  * is dropped: either by a lazy thread or by
674d70f2a14SAndrew Morton  * mmput. Free the page directory and the mm.
675d70f2a14SAndrew Morton  */
676d34bc48fSAndrew Morton void __mmdrop(struct mm_struct *mm)
677d70f2a14SAndrew Morton {
678d70f2a14SAndrew Morton 	BUG_ON(mm == &init_mm);
6793eda69c9SMark Rutland 	WARN_ON_ONCE(mm == current->mm);
6803eda69c9SMark Rutland 	WARN_ON_ONCE(mm == current->active_mm);
681d70f2a14SAndrew Morton 	mm_free_pgd(mm);
682d70f2a14SAndrew Morton 	destroy_context(mm);
683984cfe4eSJason Gunthorpe 	mmu_notifier_subscriptions_destroy(mm);
684d70f2a14SAndrew Morton 	check_mm(mm);
685d70f2a14SAndrew Morton 	put_user_ns(mm->user_ns);
686d70f2a14SAndrew Morton 	free_mm(mm);
687d70f2a14SAndrew Morton }
688d34bc48fSAndrew Morton EXPORT_SYMBOL_GPL(__mmdrop);
689d70f2a14SAndrew Morton 
690d70f2a14SAndrew Morton static void mmdrop_async_fn(struct work_struct *work)
691d70f2a14SAndrew Morton {
692d70f2a14SAndrew Morton 	struct mm_struct *mm;
693d70f2a14SAndrew Morton 
694d70f2a14SAndrew Morton 	mm = container_of(work, struct mm_struct, async_put_work);
695d70f2a14SAndrew Morton 	__mmdrop(mm);
696d70f2a14SAndrew Morton }
697d70f2a14SAndrew Morton 
698d70f2a14SAndrew Morton static void mmdrop_async(struct mm_struct *mm)
699d70f2a14SAndrew Morton {
700d70f2a14SAndrew Morton 	if (unlikely(atomic_dec_and_test(&mm->mm_count))) {
701d70f2a14SAndrew Morton 		INIT_WORK(&mm->async_put_work, mmdrop_async_fn);
702d70f2a14SAndrew Morton 		schedule_work(&mm->async_put_work);
703d70f2a14SAndrew Morton 	}
704d70f2a14SAndrew Morton }
705d70f2a14SAndrew Morton 
7061da177e4SLinus Torvalds static inline void free_signal_struct(struct signal_struct *sig)
7071da177e4SLinus Torvalds {
7081da177e4SLinus Torvalds 	taskstats_tgid_free(sig);
7091da177e4SLinus Torvalds 	sched_autogroup_exit(sig);
7101da177e4SLinus Torvalds 	/*
7111da177e4SLinus Torvalds 	 * __mmdrop is not safe to call from softirq context on x86 due to
7121da177e4SLinus Torvalds 	 * pgd_dtor so postpone it to the async context
7131da177e4SLinus Torvalds 	 */
7141da177e4SLinus Torvalds 	if (sig->oom_mm)
7151da177e4SLinus Torvalds 		mmdrop_async(sig->oom_mm);
7161da177e4SLinus Torvalds 	kmem_cache_free(signal_cachep, sig);
7171da177e4SLinus Torvalds }
7181da177e4SLinus Torvalds 
7191da177e4SLinus Torvalds static inline void put_signal_struct(struct signal_struct *sig)
7201da177e4SLinus Torvalds {
72160d4de3fSElena Reshetova 	if (refcount_dec_and_test(&sig->sigcnt))
7221da177e4SLinus Torvalds 		free_signal_struct(sig);
7231da177e4SLinus Torvalds }
7241da177e4SLinus Torvalds 
7251da177e4SLinus Torvalds void __put_task_struct(struct task_struct *tsk)
7261da177e4SLinus Torvalds {
7271da177e4SLinus Torvalds 	WARN_ON(!tsk->exit_state);
728ec1d2819SElena Reshetova 	WARN_ON(refcount_read(&tsk->usage));
7291da177e4SLinus Torvalds 	WARN_ON(tsk == current);
7301da177e4SLinus Torvalds 
7311da177e4SLinus Torvalds 	cgroup_free(tsk);
73216d51a59SJann Horn 	task_numa_free(tsk, true);
7331da177e4SLinus Torvalds 	security_task_free(tsk);
7341da177e4SLinus Torvalds 	exit_creds(tsk);
7351da177e4SLinus Torvalds 	delayacct_tsk_free(tsk);
7361da177e4SLinus Torvalds 	put_signal_struct(tsk->signal);
7371da177e4SLinus Torvalds 
7381da177e4SLinus Torvalds 	if (!profile_handoff_task(tsk))
7391da177e4SLinus Torvalds 		free_task(tsk);
7401da177e4SLinus Torvalds }
7411da177e4SLinus Torvalds EXPORT_SYMBOL_GPL(__put_task_struct);
7421da177e4SLinus Torvalds 
7431da177e4SLinus Torvalds void __init __weak arch_task_cache_init(void) { }
7441da177e4SLinus Torvalds 
7451da177e4SLinus Torvalds /*
7461da177e4SLinus Torvalds  * set_max_threads
7471da177e4SLinus Torvalds  */
7481da177e4SLinus Torvalds static void set_max_threads(unsigned int max_threads_suggested)
7491da177e4SLinus Torvalds {
7501da177e4SLinus Torvalds 	u64 threads;
751ca79b0c2SArun KS 	unsigned long nr_pages = totalram_pages();
7521da177e4SLinus Torvalds 
7531da177e4SLinus Torvalds 	/*
7541da177e4SLinus Torvalds 	 * The number of threads shall be limited such that the thread
7551da177e4SLinus Torvalds 	 * structures may only consume a small part of the available memory.
7561da177e4SLinus Torvalds 	 */
7573d6357deSArun KS 	if (fls64(nr_pages) + fls64(PAGE_SIZE) > 64)
7581da177e4SLinus Torvalds 		threads = MAX_THREADS;
7591da177e4SLinus Torvalds 	else
7603d6357deSArun KS 		threads = div64_u64((u64) nr_pages * (u64) PAGE_SIZE,
7611da177e4SLinus Torvalds 				    (u64) THREAD_SIZE * 8UL);
7621da177e4SLinus Torvalds 
7631da177e4SLinus Torvalds 	if (threads > max_threads_suggested)
7641da177e4SLinus Torvalds 		threads = max_threads_suggested;
7651da177e4SLinus Torvalds 
7661da177e4SLinus Torvalds 	max_threads = clamp_t(u64, threads, MIN_THREADS, MAX_THREADS);
7671da177e4SLinus Torvalds }
7681da177e4SLinus Torvalds 
7691da177e4SLinus Torvalds #ifdef CONFIG_ARCH_WANTS_DYNAMIC_TASK_STRUCT
7701da177e4SLinus Torvalds /* Initialized by the architecture: */
7711da177e4SLinus Torvalds int arch_task_struct_size __read_mostly;
7721da177e4SLinus Torvalds #endif
7731da177e4SLinus Torvalds 
7744189ff23SChristoph Hellwig #ifndef CONFIG_ARCH_TASK_STRUCT_ALLOCATOR
7755905429aSKees Cook static void task_struct_whitelist(unsigned long *offset, unsigned long *size)
7765905429aSKees Cook {
7775905429aSKees Cook 	/* Fetch thread_struct whitelist for the architecture. */
7785905429aSKees Cook 	arch_thread_struct_whitelist(offset, size);
7795905429aSKees Cook 
7805905429aSKees Cook 	/*
7815905429aSKees Cook 	 * Handle zero-sized whitelist or empty thread_struct, otherwise
7825905429aSKees Cook 	 * adjust offset to position of thread_struct in task_struct.
7835905429aSKees Cook 	 */
7845905429aSKees Cook 	if (unlikely(*size == 0))
7855905429aSKees Cook 		*offset = 0;
7865905429aSKees Cook 	else
7875905429aSKees Cook 		*offset += offsetof(struct task_struct, thread);
7885905429aSKees Cook }
7894189ff23SChristoph Hellwig #endif /* CONFIG_ARCH_TASK_STRUCT_ALLOCATOR */
7905905429aSKees Cook 
7911da177e4SLinus Torvalds void __init fork_init(void)
7921da177e4SLinus Torvalds {
7931da177e4SLinus Torvalds 	int i;
7941da177e4SLinus Torvalds #ifndef CONFIG_ARCH_TASK_STRUCT_ALLOCATOR
7951da177e4SLinus Torvalds #ifndef ARCH_MIN_TASKALIGN
7961da177e4SLinus Torvalds #define ARCH_MIN_TASKALIGN	0
7971da177e4SLinus Torvalds #endif
7981da177e4SLinus Torvalds 	int align = max_t(int, L1_CACHE_BYTES, ARCH_MIN_TASKALIGN);
7995905429aSKees Cook 	unsigned long useroffset, usersize;
8001da177e4SLinus Torvalds 
8011da177e4SLinus Torvalds 	/* create a slab on which task_structs can be allocated */
8025905429aSKees Cook 	task_struct_whitelist(&useroffset, &usersize);
8035905429aSKees Cook 	task_struct_cachep = kmem_cache_create_usercopy("task_struct",
8041da177e4SLinus Torvalds 			arch_task_struct_size, align,
8055905429aSKees Cook 			SLAB_PANIC|SLAB_ACCOUNT,
8065905429aSKees Cook 			useroffset, usersize, NULL);
8071da177e4SLinus Torvalds #endif
8081da177e4SLinus Torvalds 
8091da177e4SLinus Torvalds 	/* do the arch specific task caches init */
8101da177e4SLinus Torvalds 	arch_task_cache_init();
8111da177e4SLinus Torvalds 
8121da177e4SLinus Torvalds 	set_max_threads(MAX_THREADS);
8131da177e4SLinus Torvalds 
8141da177e4SLinus Torvalds 	init_task.signal->rlim[RLIMIT_NPROC].rlim_cur = max_threads/2;
8151da177e4SLinus Torvalds 	init_task.signal->rlim[RLIMIT_NPROC].rlim_max = max_threads/2;
8161da177e4SLinus Torvalds 	init_task.signal->rlim[RLIMIT_SIGPENDING] =
8171da177e4SLinus Torvalds 		init_task.signal->rlim[RLIMIT_NPROC];
8181da177e4SLinus Torvalds 
8191da177e4SLinus Torvalds 	for (i = 0; i < UCOUNT_COUNTS; i++) {
8201da177e4SLinus Torvalds 		init_user_ns.ucount_max[i] = max_threads/2;
8211da177e4SLinus Torvalds 	}
8221da177e4SLinus Torvalds 
8231da177e4SLinus Torvalds #ifdef CONFIG_VMAP_STACK
8241da177e4SLinus Torvalds 	cpuhp_setup_state(CPUHP_BP_PREPARE_DYN, "fork:vm_stack_cache",
8251da177e4SLinus Torvalds 			  NULL, free_vm_stack_cache);
8261da177e4SLinus Torvalds #endif
8271da177e4SLinus Torvalds 
828d08b9f0cSSami Tolvanen 	scs_init();
829d08b9f0cSSami Tolvanen 
8301da177e4SLinus Torvalds 	lockdep_init_task(&init_task);
831aad42dd4SNadav Amit 	uprobes_init();
8321da177e4SLinus Torvalds }
8331da177e4SLinus Torvalds 
8341da177e4SLinus Torvalds int __weak arch_dup_task_struct(struct task_struct *dst,
8351da177e4SLinus Torvalds 					       struct task_struct *src)
8361da177e4SLinus Torvalds {
8371da177e4SLinus Torvalds 	*dst = *src;
8381da177e4SLinus Torvalds 	return 0;
8391da177e4SLinus Torvalds }
8401da177e4SLinus Torvalds 
8411da177e4SLinus Torvalds void set_task_stack_end_magic(struct task_struct *tsk)
8421da177e4SLinus Torvalds {
8431da177e4SLinus Torvalds 	unsigned long *stackend;
8441da177e4SLinus Torvalds 
8451da177e4SLinus Torvalds 	stackend = end_of_stack(tsk);
8461da177e4SLinus Torvalds 	*stackend = STACK_END_MAGIC;	/* for overflow detection */
8471da177e4SLinus Torvalds }
8481da177e4SLinus Torvalds 
8491da177e4SLinus Torvalds static struct task_struct *dup_task_struct(struct task_struct *orig, int node)
8501da177e4SLinus Torvalds {
8511da177e4SLinus Torvalds 	struct task_struct *tsk;
8521da177e4SLinus Torvalds 	unsigned long *stack;
8530f4991e8SYueHaibing 	struct vm_struct *stack_vm_area __maybe_unused;
8541da177e4SLinus Torvalds 	int err;
8551da177e4SLinus Torvalds 
8561da177e4SLinus Torvalds 	if (node == NUMA_NO_NODE)
8571da177e4SLinus Torvalds 		node = tsk_fork_get_node(orig);
8581da177e4SLinus Torvalds 	tsk = alloc_task_struct_node(node);
8591da177e4SLinus Torvalds 	if (!tsk)
8601da177e4SLinus Torvalds 		return NULL;
8611da177e4SLinus Torvalds 
8621da177e4SLinus Torvalds 	stack = alloc_thread_stack_node(tsk, node);
8631da177e4SLinus Torvalds 	if (!stack)
8641da177e4SLinus Torvalds 		goto free_tsk;
8651da177e4SLinus Torvalds 
8669b6f7e16SRoman Gushchin 	if (memcg_charge_kernel_stack(tsk))
8679b6f7e16SRoman Gushchin 		goto free_stack;
8689b6f7e16SRoman Gushchin 
8691da177e4SLinus Torvalds 	stack_vm_area = task_stack_vm_area(tsk);
8701da177e4SLinus Torvalds 
8711da177e4SLinus Torvalds 	err = arch_dup_task_struct(tsk, orig);
8721da177e4SLinus Torvalds 
8731da177e4SLinus Torvalds 	/*
8741da177e4SLinus Torvalds 	 * arch_dup_task_struct() clobbers the stack-related fields.  Make
8751da177e4SLinus Torvalds 	 * sure they're properly initialized before using any stack-related
8761da177e4SLinus Torvalds 	 * functions again.
8771da177e4SLinus Torvalds 	 */
8781da177e4SLinus Torvalds 	tsk->stack = stack;
8791da177e4SLinus Torvalds #ifdef CONFIG_VMAP_STACK
8801da177e4SLinus Torvalds 	tsk->stack_vm_area = stack_vm_area;
8811da177e4SLinus Torvalds #endif
8821da177e4SLinus Torvalds #ifdef CONFIG_THREAD_INFO_IN_TASK
883f0b89d39SElena Reshetova 	refcount_set(&tsk->stack_refcount, 1);
8841da177e4SLinus Torvalds #endif
8851da177e4SLinus Torvalds 
8861da177e4SLinus Torvalds 	if (err)
8871da177e4SLinus Torvalds 		goto free_stack;
8881da177e4SLinus Torvalds 
889d08b9f0cSSami Tolvanen 	err = scs_prepare(tsk, node);
890d08b9f0cSSami Tolvanen 	if (err)
891d08b9f0cSSami Tolvanen 		goto free_stack;
892d08b9f0cSSami Tolvanen 
8931da177e4SLinus Torvalds #ifdef CONFIG_SECCOMP
8941da177e4SLinus Torvalds 	/*
8951da177e4SLinus Torvalds 	 * We must handle setting up seccomp filters once we're under
8961da177e4SLinus Torvalds 	 * the sighand lock in case orig has changed between now and
8971da177e4SLinus Torvalds 	 * then. Until then, filter must be NULL to avoid messing up
8981da177e4SLinus Torvalds 	 * the usage counts on the error path calling free_task.
8991da177e4SLinus Torvalds 	 */
9001da177e4SLinus Torvalds 	tsk->seccomp.filter = NULL;
9011da177e4SLinus Torvalds #endif
9021da177e4SLinus Torvalds 
9031da177e4SLinus Torvalds 	setup_thread_stack(tsk, orig);
9041da177e4SLinus Torvalds 	clear_user_return_notifier(tsk);
9051da177e4SLinus Torvalds 	clear_tsk_need_resched(tsk);
9061da177e4SLinus Torvalds 	set_task_stack_end_magic(tsk);
9071da177e4SLinus Torvalds 
908050e9baaSLinus Torvalds #ifdef CONFIG_STACKPROTECTOR
9091da177e4SLinus Torvalds 	tsk->stack_canary = get_random_canary();
9101da177e4SLinus Torvalds #endif
9113bd37062SSebastian Andrzej Siewior 	if (orig->cpus_ptr == &orig->cpus_mask)
9123bd37062SSebastian Andrzej Siewior 		tsk->cpus_ptr = &tsk->cpus_mask;
9131da177e4SLinus Torvalds 
9141da177e4SLinus Torvalds 	/*
9150ff7b2cfSEric W. Biederman 	 * One for the user space visible state that goes away when reaped.
9160ff7b2cfSEric W. Biederman 	 * One for the scheduler.
9171da177e4SLinus Torvalds 	 */
9180ff7b2cfSEric W. Biederman 	refcount_set(&tsk->rcu_users, 2);
9190ff7b2cfSEric W. Biederman 	/* One for the rcu users */
9200ff7b2cfSEric W. Biederman 	refcount_set(&tsk->usage, 1);
9211da177e4SLinus Torvalds #ifdef CONFIG_BLK_DEV_IO_TRACE
9221da177e4SLinus Torvalds 	tsk->btrace_seq = 0;
9231da177e4SLinus Torvalds #endif
9241da177e4SLinus Torvalds 	tsk->splice_pipe = NULL;
9251da177e4SLinus Torvalds 	tsk->task_frag.page = NULL;
9261da177e4SLinus Torvalds 	tsk->wake_q.next = NULL;
9271da177e4SLinus Torvalds 
9281da177e4SLinus Torvalds 	account_kernel_stack(tsk, 1);
9291da177e4SLinus Torvalds 
9301da177e4SLinus Torvalds 	kcov_task_init(tsk);
9311da177e4SLinus Torvalds 
9321da177e4SLinus Torvalds #ifdef CONFIG_FAULT_INJECTION
9331da177e4SLinus Torvalds 	tsk->fail_nth = 0;
9341da177e4SLinus Torvalds #endif
9351da177e4SLinus Torvalds 
9362c323017SJosef Bacik #ifdef CONFIG_BLK_CGROUP
9372c323017SJosef Bacik 	tsk->throttle_queue = NULL;
9382c323017SJosef Bacik 	tsk->use_memdelay = 0;
9392c323017SJosef Bacik #endif
9402c323017SJosef Bacik 
941d46eb14bSShakeel Butt #ifdef CONFIG_MEMCG
942d46eb14bSShakeel Butt 	tsk->active_memcg = NULL;
943d46eb14bSShakeel Butt #endif
9441da177e4SLinus Torvalds 	return tsk;
9451da177e4SLinus Torvalds 
9461da177e4SLinus Torvalds free_stack:
9471da177e4SLinus Torvalds 	free_thread_stack(tsk);
9481da177e4SLinus Torvalds free_tsk:
9491da177e4SLinus Torvalds 	free_task_struct(tsk);
9501da177e4SLinus Torvalds 	return NULL;
9511da177e4SLinus Torvalds }
9521da177e4SLinus Torvalds 
9531da177e4SLinus Torvalds __cacheline_aligned_in_smp DEFINE_SPINLOCK(mmlist_lock);
9541da177e4SLinus Torvalds 
9554cb0e11bSHidehiro Kawai static unsigned long default_dump_filter = MMF_DUMP_FILTER_DEFAULT;
9564cb0e11bSHidehiro Kawai 
9574cb0e11bSHidehiro Kawai static int __init coredump_filter_setup(char *s)
9584cb0e11bSHidehiro Kawai {
9594cb0e11bSHidehiro Kawai 	default_dump_filter =
9604cb0e11bSHidehiro Kawai 		(simple_strtoul(s, NULL, 0) << MMF_DUMP_FILTER_SHIFT) &
9614cb0e11bSHidehiro Kawai 		MMF_DUMP_FILTER_MASK;
9624cb0e11bSHidehiro Kawai 	return 1;
9634cb0e11bSHidehiro Kawai }
9644cb0e11bSHidehiro Kawai 
9654cb0e11bSHidehiro Kawai __setup("coredump_filter=", coredump_filter_setup);
9664cb0e11bSHidehiro Kawai 
9671da177e4SLinus Torvalds #include <linux/init_task.h>
9681da177e4SLinus Torvalds 
969858f0993SAlexey Dobriyan static void mm_init_aio(struct mm_struct *mm)
970858f0993SAlexey Dobriyan {
971858f0993SAlexey Dobriyan #ifdef CONFIG_AIO
972858f0993SAlexey Dobriyan 	spin_lock_init(&mm->ioctx_lock);
973db446a08SBenjamin LaHaise 	mm->ioctx_table = NULL;
974858f0993SAlexey Dobriyan #endif
975858f0993SAlexey Dobriyan }
976858f0993SAlexey Dobriyan 
977c3f3ce04SAndrea Arcangeli static __always_inline void mm_clear_owner(struct mm_struct *mm,
978c3f3ce04SAndrea Arcangeli 					   struct task_struct *p)
979c3f3ce04SAndrea Arcangeli {
980c3f3ce04SAndrea Arcangeli #ifdef CONFIG_MEMCG
981c3f3ce04SAndrea Arcangeli 	if (mm->owner == p)
982c3f3ce04SAndrea Arcangeli 		WRITE_ONCE(mm->owner, NULL);
983c3f3ce04SAndrea Arcangeli #endif
984c3f3ce04SAndrea Arcangeli }
985c3f3ce04SAndrea Arcangeli 
98633144e84SVladimir Davydov static void mm_init_owner(struct mm_struct *mm, struct task_struct *p)
98733144e84SVladimir Davydov {
98833144e84SVladimir Davydov #ifdef CONFIG_MEMCG
98933144e84SVladimir Davydov 	mm->owner = p;
99033144e84SVladimir Davydov #endif
99133144e84SVladimir Davydov }
99233144e84SVladimir Davydov 
993355627f5SEric Biggers static void mm_init_uprobes_state(struct mm_struct *mm)
994355627f5SEric Biggers {
995355627f5SEric Biggers #ifdef CONFIG_UPROBES
996355627f5SEric Biggers 	mm->uprobes_state.xol_area = NULL;
997355627f5SEric Biggers #endif
998355627f5SEric Biggers }
999355627f5SEric Biggers 
1000bfedb589SEric W. Biederman static struct mm_struct *mm_init(struct mm_struct *mm, struct task_struct *p,
1001bfedb589SEric W. Biederman 	struct user_namespace *user_ns)
10021da177e4SLinus Torvalds {
100341f727fdSVladimir Davydov 	mm->mmap = NULL;
100441f727fdSVladimir Davydov 	mm->mm_rb = RB_ROOT;
100541f727fdSVladimir Davydov 	mm->vmacache_seqnum = 0;
10061da177e4SLinus Torvalds 	atomic_set(&mm->mm_users, 1);
10071da177e4SLinus Torvalds 	atomic_set(&mm->mm_count, 1);
1008d8ed45c5SMichel Lespinasse 	mmap_init_lock(mm);
10091da177e4SLinus Torvalds 	INIT_LIST_HEAD(&mm->mmlist);
1010999d9fc1SOleg Nesterov 	mm->core_state = NULL;
1011af5b0f6aSKirill A. Shutemov 	mm_pgtables_bytes_init(mm);
101241f727fdSVladimir Davydov 	mm->map_count = 0;
101341f727fdSVladimir Davydov 	mm->locked_vm = 0;
1014*008cfe44SPeter Xu 	atomic_set(&mm->has_pinned, 0);
101570f8a3caSDavidlohr Bueso 	atomic64_set(&mm->pinned_vm, 0);
1016d559db08SKAMEZAWA Hiroyuki 	memset(&mm->rss_stat, 0, sizeof(mm->rss_stat));
10171da177e4SLinus Torvalds 	spin_lock_init(&mm->page_table_lock);
101888aa7cc6SYang Shi 	spin_lock_init(&mm->arg_lock);
101941f727fdSVladimir Davydov 	mm_init_cpumask(mm);
1020858f0993SAlexey Dobriyan 	mm_init_aio(mm);
1021cf475ad2SBalbir Singh 	mm_init_owner(mm, p);
10222b7e8665SEric Biggers 	RCU_INIT_POINTER(mm->exe_file, NULL);
1023984cfe4eSJason Gunthorpe 	mmu_notifier_subscriptions_init(mm);
102416af97dcSNadav Amit 	init_tlb_flush_pending(mm);
102541f727fdSVladimir Davydov #if defined(CONFIG_TRANSPARENT_HUGEPAGE) && !USE_SPLIT_PMD_PTLOCKS
102641f727fdSVladimir Davydov 	mm->pmd_huge_pte = NULL;
102741f727fdSVladimir Davydov #endif
1028355627f5SEric Biggers 	mm_init_uprobes_state(mm);
10291da177e4SLinus Torvalds 
1030a0715cc2SAlex Thorlton 	if (current->mm) {
1031a0715cc2SAlex Thorlton 		mm->flags = current->mm->flags & MMF_INIT_MASK;
1032a0715cc2SAlex Thorlton 		mm->def_flags = current->mm->def_flags & VM_INIT_DEF_MASK;
1033a0715cc2SAlex Thorlton 	} else {
1034a0715cc2SAlex Thorlton 		mm->flags = default_dump_filter;
10351da177e4SLinus Torvalds 		mm->def_flags = 0;
1036a0715cc2SAlex Thorlton 	}
1037a0715cc2SAlex Thorlton 
103841f727fdSVladimir Davydov 	if (mm_alloc_pgd(mm))
103941f727fdSVladimir Davydov 		goto fail_nopgd;
104078fb7466SPavel Emelianov 
104141f727fdSVladimir Davydov 	if (init_new_context(p, mm))
104241f727fdSVladimir Davydov 		goto fail_nocontext;
104341f727fdSVladimir Davydov 
1044bfedb589SEric W. Biederman 	mm->user_ns = get_user_ns(user_ns);
104541f727fdSVladimir Davydov 	return mm;
104641f727fdSVladimir Davydov 
104741f727fdSVladimir Davydov fail_nocontext:
104841f727fdSVladimir Davydov 	mm_free_pgd(mm);
104941f727fdSVladimir Davydov fail_nopgd:
10501da177e4SLinus Torvalds 	free_mm(mm);
10511da177e4SLinus Torvalds 	return NULL;
10521da177e4SLinus Torvalds }
10531da177e4SLinus Torvalds 
10541da177e4SLinus Torvalds /*
10551da177e4SLinus Torvalds  * Allocate and initialize an mm_struct.
10561da177e4SLinus Torvalds  */
10571da177e4SLinus Torvalds struct mm_struct *mm_alloc(void)
10581da177e4SLinus Torvalds {
10591da177e4SLinus Torvalds 	struct mm_struct *mm;
10601da177e4SLinus Torvalds 
10611da177e4SLinus Torvalds 	mm = allocate_mm();
1062de03c72cSKOSAKI Motohiro 	if (!mm)
1063de03c72cSKOSAKI Motohiro 		return NULL;
1064de03c72cSKOSAKI Motohiro 
10651da177e4SLinus Torvalds 	memset(mm, 0, sizeof(*mm));
1066bfedb589SEric W. Biederman 	return mm_init(mm, current, current_user_ns());
10671da177e4SLinus Torvalds }
10681da177e4SLinus Torvalds 
1069ec8d7c14SMichal Hocko static inline void __mmput(struct mm_struct *mm)
10701da177e4SLinus Torvalds {
1071ec8d7c14SMichal Hocko 	VM_BUG_ON(atomic_read(&mm->mm_users));
10720ae26f1bSAndrew Morton 
1073d4b3b638SSrikar Dronamraju 	uprobe_clear_state(mm);
10741da177e4SLinus Torvalds 	exit_aio(mm);
10751c2fb7a4SAndrea Arcangeli 	ksm_exit(mm);
1076ba76149fSAndrea Arcangeli 	khugepaged_exit(mm); /* must run before exit_mmap */
10771da177e4SLinus Torvalds 	exit_mmap(mm);
10786fcb52a5SAaron Lu 	mm_put_huge_zero_page(mm);
1079925d1c40SMatt Helsley 	set_mm_exe_file(mm, NULL);
10801da177e4SLinus Torvalds 	if (!list_empty(&mm->mmlist)) {
10811da177e4SLinus Torvalds 		spin_lock(&mmlist_lock);
10821da177e4SLinus Torvalds 		list_del(&mm->mmlist);
10831da177e4SLinus Torvalds 		spin_unlock(&mmlist_lock);
10841da177e4SLinus Torvalds 	}
1085801460d0SHiroshi Shimamoto 	if (mm->binfmt)
1086801460d0SHiroshi Shimamoto 		module_put(mm->binfmt->module);
10871da177e4SLinus Torvalds 	mmdrop(mm);
10881da177e4SLinus Torvalds }
1089ec8d7c14SMichal Hocko 
1090ec8d7c14SMichal Hocko /*
1091ec8d7c14SMichal Hocko  * Decrement the use count and release all resources for an mm.
1092ec8d7c14SMichal Hocko  */
1093ec8d7c14SMichal Hocko void mmput(struct mm_struct *mm)
1094ec8d7c14SMichal Hocko {
1095ec8d7c14SMichal Hocko 	might_sleep();
1096ec8d7c14SMichal Hocko 
1097ec8d7c14SMichal Hocko 	if (atomic_dec_and_test(&mm->mm_users))
1098ec8d7c14SMichal Hocko 		__mmput(mm);
10991da177e4SLinus Torvalds }
11001da177e4SLinus Torvalds EXPORT_SYMBOL_GPL(mmput);
11011da177e4SLinus Torvalds 
1102a1b2289cSSherry Yang #ifdef CONFIG_MMU
1103a1b2289cSSherry Yang static void mmput_async_fn(struct work_struct *work)
1104a1b2289cSSherry Yang {
1105a1b2289cSSherry Yang 	struct mm_struct *mm = container_of(work, struct mm_struct,
1106a1b2289cSSherry Yang 					    async_put_work);
1107a1b2289cSSherry Yang 
1108a1b2289cSSherry Yang 	__mmput(mm);
1109a1b2289cSSherry Yang }
1110a1b2289cSSherry Yang 
1111a1b2289cSSherry Yang void mmput_async(struct mm_struct *mm)
1112a1b2289cSSherry Yang {
1113a1b2289cSSherry Yang 	if (atomic_dec_and_test(&mm->mm_users)) {
1114a1b2289cSSherry Yang 		INIT_WORK(&mm->async_put_work, mmput_async_fn);
1115a1b2289cSSherry Yang 		schedule_work(&mm->async_put_work);
1116a1b2289cSSherry Yang 	}
1117a1b2289cSSherry Yang }
1118a1b2289cSSherry Yang #endif
1119a1b2289cSSherry Yang 
112090f31d0eSKonstantin Khlebnikov /**
112190f31d0eSKonstantin Khlebnikov  * set_mm_exe_file - change a reference to the mm's executable file
112290f31d0eSKonstantin Khlebnikov  *
112390f31d0eSKonstantin Khlebnikov  * This changes mm's executable file (shown as symlink /proc/[pid]/exe).
112490f31d0eSKonstantin Khlebnikov  *
11256e399cd1SDavidlohr Bueso  * Main users are mmput() and sys_execve(). Callers prevent concurrent
11266e399cd1SDavidlohr Bueso  * invocations: in mmput() nobody alive left, in execve task is single
11276e399cd1SDavidlohr Bueso  * threaded. sys_prctl(PR_SET_MM_MAP/EXE_FILE) also needs to set the
11286e399cd1SDavidlohr Bueso  * mm->exe_file, but does so without using set_mm_exe_file() in order
11296e399cd1SDavidlohr Bueso  * to do avoid the need for any locks.
113090f31d0eSKonstantin Khlebnikov  */
113138646013SJiri Slaby void set_mm_exe_file(struct mm_struct *mm, struct file *new_exe_file)
113238646013SJiri Slaby {
11336e399cd1SDavidlohr Bueso 	struct file *old_exe_file;
11346e399cd1SDavidlohr Bueso 
11356e399cd1SDavidlohr Bueso 	/*
11366e399cd1SDavidlohr Bueso 	 * It is safe to dereference the exe_file without RCU as
11376e399cd1SDavidlohr Bueso 	 * this function is only called if nobody else can access
11386e399cd1SDavidlohr Bueso 	 * this mm -- see comment above for justification.
11396e399cd1SDavidlohr Bueso 	 */
11406e399cd1SDavidlohr Bueso 	old_exe_file = rcu_dereference_raw(mm->exe_file);
114190f31d0eSKonstantin Khlebnikov 
114238646013SJiri Slaby 	if (new_exe_file)
114338646013SJiri Slaby 		get_file(new_exe_file);
114490f31d0eSKonstantin Khlebnikov 	rcu_assign_pointer(mm->exe_file, new_exe_file);
114590f31d0eSKonstantin Khlebnikov 	if (old_exe_file)
114690f31d0eSKonstantin Khlebnikov 		fput(old_exe_file);
114738646013SJiri Slaby }
114838646013SJiri Slaby 
114990f31d0eSKonstantin Khlebnikov /**
115090f31d0eSKonstantin Khlebnikov  * get_mm_exe_file - acquire a reference to the mm's executable file
115190f31d0eSKonstantin Khlebnikov  *
115290f31d0eSKonstantin Khlebnikov  * Returns %NULL if mm has no associated executable file.
115390f31d0eSKonstantin Khlebnikov  * User must release file via fput().
115490f31d0eSKonstantin Khlebnikov  */
115538646013SJiri Slaby struct file *get_mm_exe_file(struct mm_struct *mm)
115638646013SJiri Slaby {
115738646013SJiri Slaby 	struct file *exe_file;
115838646013SJiri Slaby 
115990f31d0eSKonstantin Khlebnikov 	rcu_read_lock();
116090f31d0eSKonstantin Khlebnikov 	exe_file = rcu_dereference(mm->exe_file);
116190f31d0eSKonstantin Khlebnikov 	if (exe_file && !get_file_rcu(exe_file))
116290f31d0eSKonstantin Khlebnikov 		exe_file = NULL;
116390f31d0eSKonstantin Khlebnikov 	rcu_read_unlock();
116438646013SJiri Slaby 	return exe_file;
116538646013SJiri Slaby }
116611163348SDavidlohr Bueso EXPORT_SYMBOL(get_mm_exe_file);
116738646013SJiri Slaby 
11681da177e4SLinus Torvalds /**
1169cd81a917SMateusz Guzik  * get_task_exe_file - acquire a reference to the task's executable file
1170cd81a917SMateusz Guzik  *
1171cd81a917SMateusz Guzik  * Returns %NULL if task's mm (if any) has no associated executable file or
1172cd81a917SMateusz Guzik  * this is a kernel thread with borrowed mm (see the comment above get_task_mm).
1173cd81a917SMateusz Guzik  * User must release file via fput().
1174cd81a917SMateusz Guzik  */
1175cd81a917SMateusz Guzik struct file *get_task_exe_file(struct task_struct *task)
1176cd81a917SMateusz Guzik {
1177cd81a917SMateusz Guzik 	struct file *exe_file = NULL;
1178cd81a917SMateusz Guzik 	struct mm_struct *mm;
1179cd81a917SMateusz Guzik 
1180cd81a917SMateusz Guzik 	task_lock(task);
1181cd81a917SMateusz Guzik 	mm = task->mm;
1182cd81a917SMateusz Guzik 	if (mm) {
1183cd81a917SMateusz Guzik 		if (!(task->flags & PF_KTHREAD))
1184cd81a917SMateusz Guzik 			exe_file = get_mm_exe_file(mm);
1185cd81a917SMateusz Guzik 	}
1186cd81a917SMateusz Guzik 	task_unlock(task);
1187cd81a917SMateusz Guzik 	return exe_file;
1188cd81a917SMateusz Guzik }
1189cd81a917SMateusz Guzik EXPORT_SYMBOL(get_task_exe_file);
1190cd81a917SMateusz Guzik 
1191cd81a917SMateusz Guzik /**
11921da177e4SLinus Torvalds  * get_task_mm - acquire a reference to the task's mm
11931da177e4SLinus Torvalds  *
1194246bb0b1SOleg Nesterov  * Returns %NULL if the task has no mm.  Checks PF_KTHREAD (meaning
11951da177e4SLinus Torvalds  * this kernel workthread has transiently adopted a user mm with use_mm,
11961da177e4SLinus Torvalds  * to do its AIO) is not set and if so returns a reference to it, after
11971da177e4SLinus Torvalds  * bumping up the use count.  User must release the mm via mmput()
11981da177e4SLinus Torvalds  * after use.  Typically used by /proc and ptrace.
11991da177e4SLinus Torvalds  */
12001da177e4SLinus Torvalds struct mm_struct *get_task_mm(struct task_struct *task)
12011da177e4SLinus Torvalds {
12021da177e4SLinus Torvalds 	struct mm_struct *mm;
12031da177e4SLinus Torvalds 
12041da177e4SLinus Torvalds 	task_lock(task);
12051da177e4SLinus Torvalds 	mm = task->mm;
12061da177e4SLinus Torvalds 	if (mm) {
1207246bb0b1SOleg Nesterov 		if (task->flags & PF_KTHREAD)
12081da177e4SLinus Torvalds 			mm = NULL;
12091da177e4SLinus Torvalds 		else
12103fce371bSVegard Nossum 			mmget(mm);
12111da177e4SLinus Torvalds 	}
12121da177e4SLinus Torvalds 	task_unlock(task);
12131da177e4SLinus Torvalds 	return mm;
12141da177e4SLinus Torvalds }
12151da177e4SLinus Torvalds EXPORT_SYMBOL_GPL(get_task_mm);
12161da177e4SLinus Torvalds 
12178cdb878dSChristopher Yeoh struct mm_struct *mm_access(struct task_struct *task, unsigned int mode)
12188cdb878dSChristopher Yeoh {
12198cdb878dSChristopher Yeoh 	struct mm_struct *mm;
12208cdb878dSChristopher Yeoh 	int err;
12218cdb878dSChristopher Yeoh 
12223e74fabdSBernd Edlinger 	err =  mutex_lock_killable(&task->signal->exec_update_mutex);
12238cdb878dSChristopher Yeoh 	if (err)
12248cdb878dSChristopher Yeoh 		return ERR_PTR(err);
12258cdb878dSChristopher Yeoh 
12268cdb878dSChristopher Yeoh 	mm = get_task_mm(task);
12278cdb878dSChristopher Yeoh 	if (mm && mm != current->mm &&
12288cdb878dSChristopher Yeoh 			!ptrace_may_access(task, mode)) {
12298cdb878dSChristopher Yeoh 		mmput(mm);
12308cdb878dSChristopher Yeoh 		mm = ERR_PTR(-EACCES);
12318cdb878dSChristopher Yeoh 	}
12323e74fabdSBernd Edlinger 	mutex_unlock(&task->signal->exec_update_mutex);
12338cdb878dSChristopher Yeoh 
12348cdb878dSChristopher Yeoh 	return mm;
12358cdb878dSChristopher Yeoh }
12368cdb878dSChristopher Yeoh 
123757b59c4aSOleg Nesterov static void complete_vfork_done(struct task_struct *tsk)
1238c415c3b4SOleg Nesterov {
1239d68b46feSOleg Nesterov 	struct completion *vfork;
1240c415c3b4SOleg Nesterov 
1241d68b46feSOleg Nesterov 	task_lock(tsk);
1242d68b46feSOleg Nesterov 	vfork = tsk->vfork_done;
1243d68b46feSOleg Nesterov 	if (likely(vfork)) {
1244c415c3b4SOleg Nesterov 		tsk->vfork_done = NULL;
1245d68b46feSOleg Nesterov 		complete(vfork);
1246d68b46feSOleg Nesterov 	}
1247d68b46feSOleg Nesterov 	task_unlock(tsk);
1248d68b46feSOleg Nesterov }
1249d68b46feSOleg Nesterov 
1250d68b46feSOleg Nesterov static int wait_for_vfork_done(struct task_struct *child,
1251d68b46feSOleg Nesterov 				struct completion *vfork)
1252d68b46feSOleg Nesterov {
1253d68b46feSOleg Nesterov 	int killed;
1254d68b46feSOleg Nesterov 
1255d68b46feSOleg Nesterov 	freezer_do_not_count();
125676f969e8SRoman Gushchin 	cgroup_enter_frozen();
1257d68b46feSOleg Nesterov 	killed = wait_for_completion_killable(vfork);
125876f969e8SRoman Gushchin 	cgroup_leave_frozen(false);
1259d68b46feSOleg Nesterov 	freezer_count();
1260d68b46feSOleg Nesterov 
1261d68b46feSOleg Nesterov 	if (killed) {
1262d68b46feSOleg Nesterov 		task_lock(child);
1263d68b46feSOleg Nesterov 		child->vfork_done = NULL;
1264d68b46feSOleg Nesterov 		task_unlock(child);
1265d68b46feSOleg Nesterov 	}
1266d68b46feSOleg Nesterov 
1267d68b46feSOleg Nesterov 	put_task_struct(child);
1268d68b46feSOleg Nesterov 	return killed;
1269c415c3b4SOleg Nesterov }
1270c415c3b4SOleg Nesterov 
12711da177e4SLinus Torvalds /* Please note the differences between mmput and mm_release.
12721da177e4SLinus Torvalds  * mmput is called whenever we stop holding onto a mm_struct,
12731da177e4SLinus Torvalds  * error success whatever.
12741da177e4SLinus Torvalds  *
12751da177e4SLinus Torvalds  * mm_release is called after a mm_struct has been removed
12761da177e4SLinus Torvalds  * from the current process.
12771da177e4SLinus Torvalds  *
12781da177e4SLinus Torvalds  * This difference is important for error handling, when we
12791da177e4SLinus Torvalds  * only half set up a mm_struct for a new process and need to restore
12801da177e4SLinus Torvalds  * the old one.  Because we mmput the new mm_struct before
12811da177e4SLinus Torvalds  * restoring the old one. . .
12821da177e4SLinus Torvalds  * Eric Biederman 10 January 1998
12831da177e4SLinus Torvalds  */
12844610ba7aSThomas Gleixner static void mm_release(struct task_struct *tsk, struct mm_struct *mm)
12851da177e4SLinus Torvalds {
12860326f5a9SSrikar Dronamraju 	uprobe_free_utask(tsk);
12870326f5a9SSrikar Dronamraju 
12881da177e4SLinus Torvalds 	/* Get rid of any cached register state */
12891da177e4SLinus Torvalds 	deactivate_mm(tsk, mm);
12901da177e4SLinus Torvalds 
1291fec1d011SRoland McGrath 	/*
1292735f2770SMichal Hocko 	 * Signal userspace if we're not exiting with a core dump
1293735f2770SMichal Hocko 	 * because we want to leave the value intact for debugging
1294735f2770SMichal Hocko 	 * purposes.
1295fec1d011SRoland McGrath 	 */
12969c8a8228SEric Dumazet 	if (tsk->clear_child_tid) {
1297735f2770SMichal Hocko 		if (!(tsk->signal->flags & SIGNAL_GROUP_COREDUMP) &&
12989c8a8228SEric Dumazet 		    atomic_read(&mm->mm_users) > 1) {
12991da177e4SLinus Torvalds 			/*
13001da177e4SLinus Torvalds 			 * We don't check the error code - if userspace has
13011da177e4SLinus Torvalds 			 * not set up a proper pointer then tough luck.
13021da177e4SLinus Torvalds 			 */
13039c8a8228SEric Dumazet 			put_user(0, tsk->clear_child_tid);
13042de0db99SDominik Brodowski 			do_futex(tsk->clear_child_tid, FUTEX_WAKE,
13052de0db99SDominik Brodowski 					1, NULL, NULL, 0, 0);
13069c8a8228SEric Dumazet 		}
13079c8a8228SEric Dumazet 		tsk->clear_child_tid = NULL;
13081da177e4SLinus Torvalds 	}
1309f7505d64SKonstantin Khlebnikov 
1310f7505d64SKonstantin Khlebnikov 	/*
1311f7505d64SKonstantin Khlebnikov 	 * All done, finally we can wake up parent and return this mm to him.
1312f7505d64SKonstantin Khlebnikov 	 * Also kthread_stop() uses this completion for synchronization.
1313f7505d64SKonstantin Khlebnikov 	 */
1314f7505d64SKonstantin Khlebnikov 	if (tsk->vfork_done)
1315f7505d64SKonstantin Khlebnikov 		complete_vfork_done(tsk);
13161da177e4SLinus Torvalds }
13171da177e4SLinus Torvalds 
13184610ba7aSThomas Gleixner void exit_mm_release(struct task_struct *tsk, struct mm_struct *mm)
13194610ba7aSThomas Gleixner {
1320150d7158SThomas Gleixner 	futex_exit_release(tsk);
13214610ba7aSThomas Gleixner 	mm_release(tsk, mm);
13224610ba7aSThomas Gleixner }
13234610ba7aSThomas Gleixner 
13244610ba7aSThomas Gleixner void exec_mm_release(struct task_struct *tsk, struct mm_struct *mm)
13254610ba7aSThomas Gleixner {
1326150d7158SThomas Gleixner 	futex_exec_release(tsk);
13274610ba7aSThomas Gleixner 	mm_release(tsk, mm);
13284610ba7aSThomas Gleixner }
13294610ba7aSThomas Gleixner 
133013585fa0SNadav Amit /**
133113585fa0SNadav Amit  * dup_mm() - duplicates an existing mm structure
133213585fa0SNadav Amit  * @tsk: the task_struct with which the new mm will be associated.
133313585fa0SNadav Amit  * @oldmm: the mm to duplicate.
133413585fa0SNadav Amit  *
133513585fa0SNadav Amit  * Allocates a new mm structure and duplicates the provided @oldmm structure
133613585fa0SNadav Amit  * content into it.
133713585fa0SNadav Amit  *
133813585fa0SNadav Amit  * Return: the duplicated mm or NULL on failure.
1339a0a7ec30SJANAK DESAI  */
134013585fa0SNadav Amit static struct mm_struct *dup_mm(struct task_struct *tsk,
134113585fa0SNadav Amit 				struct mm_struct *oldmm)
1342a0a7ec30SJANAK DESAI {
134313585fa0SNadav Amit 	struct mm_struct *mm;
1344a0a7ec30SJANAK DESAI 	int err;
1345a0a7ec30SJANAK DESAI 
1346a0a7ec30SJANAK DESAI 	mm = allocate_mm();
1347a0a7ec30SJANAK DESAI 	if (!mm)
1348a0a7ec30SJANAK DESAI 		goto fail_nomem;
1349a0a7ec30SJANAK DESAI 
1350a0a7ec30SJANAK DESAI 	memcpy(mm, oldmm, sizeof(*mm));
1351a0a7ec30SJANAK DESAI 
1352bfedb589SEric W. Biederman 	if (!mm_init(mm, tsk, mm->user_ns))
1353a0a7ec30SJANAK DESAI 		goto fail_nomem;
1354a0a7ec30SJANAK DESAI 
1355a0a7ec30SJANAK DESAI 	err = dup_mmap(mm, oldmm);
1356a0a7ec30SJANAK DESAI 	if (err)
1357a0a7ec30SJANAK DESAI 		goto free_pt;
1358a0a7ec30SJANAK DESAI 
1359a0a7ec30SJANAK DESAI 	mm->hiwater_rss = get_mm_rss(mm);
1360a0a7ec30SJANAK DESAI 	mm->hiwater_vm = mm->total_vm;
1361a0a7ec30SJANAK DESAI 
1362801460d0SHiroshi Shimamoto 	if (mm->binfmt && !try_module_get(mm->binfmt->module))
1363801460d0SHiroshi Shimamoto 		goto free_pt;
1364801460d0SHiroshi Shimamoto 
1365a0a7ec30SJANAK DESAI 	return mm;
1366a0a7ec30SJANAK DESAI 
1367a0a7ec30SJANAK DESAI free_pt:
1368801460d0SHiroshi Shimamoto 	/* don't put binfmt in mmput, we haven't got module yet */
1369801460d0SHiroshi Shimamoto 	mm->binfmt = NULL;
1370c3f3ce04SAndrea Arcangeli 	mm_init_owner(mm, NULL);
1371a0a7ec30SJANAK DESAI 	mmput(mm);
1372a0a7ec30SJANAK DESAI 
1373a0a7ec30SJANAK DESAI fail_nomem:
1374a0a7ec30SJANAK DESAI 	return NULL;
1375a0a7ec30SJANAK DESAI }
1376a0a7ec30SJANAK DESAI 
13771da177e4SLinus Torvalds static int copy_mm(unsigned long clone_flags, struct task_struct *tsk)
13781da177e4SLinus Torvalds {
13791da177e4SLinus Torvalds 	struct mm_struct *mm, *oldmm;
13801da177e4SLinus Torvalds 	int retval;
13811da177e4SLinus Torvalds 
13821da177e4SLinus Torvalds 	tsk->min_flt = tsk->maj_flt = 0;
13831da177e4SLinus Torvalds 	tsk->nvcsw = tsk->nivcsw = 0;
138417406b82SMandeep Singh Baines #ifdef CONFIG_DETECT_HUNG_TASK
138517406b82SMandeep Singh Baines 	tsk->last_switch_count = tsk->nvcsw + tsk->nivcsw;
1386a2e51445SDmitry Vyukov 	tsk->last_switch_time = 0;
138717406b82SMandeep Singh Baines #endif
13881da177e4SLinus Torvalds 
13891da177e4SLinus Torvalds 	tsk->mm = NULL;
13901da177e4SLinus Torvalds 	tsk->active_mm = NULL;
13911da177e4SLinus Torvalds 
13921da177e4SLinus Torvalds 	/*
13931da177e4SLinus Torvalds 	 * Are we cloning a kernel thread?
13941da177e4SLinus Torvalds 	 *
13951da177e4SLinus Torvalds 	 * We need to steal a active VM for that..
13961da177e4SLinus Torvalds 	 */
13971da177e4SLinus Torvalds 	oldmm = current->mm;
13981da177e4SLinus Torvalds 	if (!oldmm)
13991da177e4SLinus Torvalds 		return 0;
14001da177e4SLinus Torvalds 
1401615d6e87SDavidlohr Bueso 	/* initialize the new vmacache entries */
1402615d6e87SDavidlohr Bueso 	vmacache_flush(tsk);
1403615d6e87SDavidlohr Bueso 
14041da177e4SLinus Torvalds 	if (clone_flags & CLONE_VM) {
14053fce371bSVegard Nossum 		mmget(oldmm);
14061da177e4SLinus Torvalds 		mm = oldmm;
14071da177e4SLinus Torvalds 		goto good_mm;
14081da177e4SLinus Torvalds 	}
14091da177e4SLinus Torvalds 
14101da177e4SLinus Torvalds 	retval = -ENOMEM;
141113585fa0SNadav Amit 	mm = dup_mm(tsk, current->mm);
14121da177e4SLinus Torvalds 	if (!mm)
14131da177e4SLinus Torvalds 		goto fail_nomem;
14141da177e4SLinus Torvalds 
14151da177e4SLinus Torvalds good_mm:
14161da177e4SLinus Torvalds 	tsk->mm = mm;
14171da177e4SLinus Torvalds 	tsk->active_mm = mm;
14181da177e4SLinus Torvalds 	return 0;
14191da177e4SLinus Torvalds 
14201da177e4SLinus Torvalds fail_nomem:
14211da177e4SLinus Torvalds 	return retval;
14221da177e4SLinus Torvalds }
14231da177e4SLinus Torvalds 
1424a39bc516SAlexey Dobriyan static int copy_fs(unsigned long clone_flags, struct task_struct *tsk)
14251da177e4SLinus Torvalds {
1426498052bbSAl Viro 	struct fs_struct *fs = current->fs;
14271da177e4SLinus Torvalds 	if (clone_flags & CLONE_FS) {
1428498052bbSAl Viro 		/* tsk->fs is already what we want */
14292a4419b5SNick Piggin 		spin_lock(&fs->lock);
1430498052bbSAl Viro 		if (fs->in_exec) {
14312a4419b5SNick Piggin 			spin_unlock(&fs->lock);
1432498052bbSAl Viro 			return -EAGAIN;
1433498052bbSAl Viro 		}
1434498052bbSAl Viro 		fs->users++;
14352a4419b5SNick Piggin 		spin_unlock(&fs->lock);
14361da177e4SLinus Torvalds 		return 0;
14371da177e4SLinus Torvalds 	}
1438498052bbSAl Viro 	tsk->fs = copy_fs_struct(fs);
14391da177e4SLinus Torvalds 	if (!tsk->fs)
14401da177e4SLinus Torvalds 		return -ENOMEM;
14411da177e4SLinus Torvalds 	return 0;
14421da177e4SLinus Torvalds }
14431da177e4SLinus Torvalds 
1444a016f338SJANAK DESAI static int copy_files(unsigned long clone_flags, struct task_struct *tsk)
1445a016f338SJANAK DESAI {
1446a016f338SJANAK DESAI 	struct files_struct *oldf, *newf;
1447a016f338SJANAK DESAI 	int error = 0;
1448a016f338SJANAK DESAI 
1449a016f338SJANAK DESAI 	/*
1450a016f338SJANAK DESAI 	 * A background process may not have any files ...
1451a016f338SJANAK DESAI 	 */
1452a016f338SJANAK DESAI 	oldf = current->files;
1453a016f338SJANAK DESAI 	if (!oldf)
1454a016f338SJANAK DESAI 		goto out;
1455a016f338SJANAK DESAI 
1456a016f338SJANAK DESAI 	if (clone_flags & CLONE_FILES) {
1457a016f338SJANAK DESAI 		atomic_inc(&oldf->count);
1458a016f338SJANAK DESAI 		goto out;
1459a016f338SJANAK DESAI 	}
1460a016f338SJANAK DESAI 
146160997c3dSChristian Brauner 	newf = dup_fd(oldf, NR_OPEN_MAX, &error);
1462a016f338SJANAK DESAI 	if (!newf)
1463a016f338SJANAK DESAI 		goto out;
1464a016f338SJANAK DESAI 
1465a016f338SJANAK DESAI 	tsk->files = newf;
1466a016f338SJANAK DESAI 	error = 0;
1467a016f338SJANAK DESAI out:
1468a016f338SJANAK DESAI 	return error;
1469a016f338SJANAK DESAI }
1470a016f338SJANAK DESAI 
1471fadad878SJens Axboe static int copy_io(unsigned long clone_flags, struct task_struct *tsk)
1472fd0928dfSJens Axboe {
1473fd0928dfSJens Axboe #ifdef CONFIG_BLOCK
1474fd0928dfSJens Axboe 	struct io_context *ioc = current->io_context;
14756e736be7STejun Heo 	struct io_context *new_ioc;
1476fd0928dfSJens Axboe 
1477fd0928dfSJens Axboe 	if (!ioc)
1478fd0928dfSJens Axboe 		return 0;
1479fadad878SJens Axboe 	/*
1480fadad878SJens Axboe 	 * Share io context with parent, if CLONE_IO is set
1481fadad878SJens Axboe 	 */
1482fadad878SJens Axboe 	if (clone_flags & CLONE_IO) {
14833d48749dSTejun Heo 		ioc_task_link(ioc);
14843d48749dSTejun Heo 		tsk->io_context = ioc;
1485fadad878SJens Axboe 	} else if (ioprio_valid(ioc->ioprio)) {
14866e736be7STejun Heo 		new_ioc = get_task_io_context(tsk, GFP_KERNEL, NUMA_NO_NODE);
14876e736be7STejun Heo 		if (unlikely(!new_ioc))
1488fd0928dfSJens Axboe 			return -ENOMEM;
1489fd0928dfSJens Axboe 
14906e736be7STejun Heo 		new_ioc->ioprio = ioc->ioprio;
149111a3122fSTejun Heo 		put_io_context(new_ioc);
1492fd0928dfSJens Axboe 	}
1493fd0928dfSJens Axboe #endif
1494fd0928dfSJens Axboe 	return 0;
1495fd0928dfSJens Axboe }
1496fd0928dfSJens Axboe 
1497a39bc516SAlexey Dobriyan static int copy_sighand(unsigned long clone_flags, struct task_struct *tsk)
14981da177e4SLinus Torvalds {
14991da177e4SLinus Torvalds 	struct sighand_struct *sig;
15001da177e4SLinus Torvalds 
150160348802SZhaolei 	if (clone_flags & CLONE_SIGHAND) {
1502d036bda7SElena Reshetova 		refcount_inc(&current->sighand->count);
15031da177e4SLinus Torvalds 		return 0;
15041da177e4SLinus Torvalds 	}
15051da177e4SLinus Torvalds 	sig = kmem_cache_alloc(sighand_cachep, GFP_KERNEL);
15060c282b06SMadhuparna Bhowmik 	RCU_INIT_POINTER(tsk->sighand, sig);
15071da177e4SLinus Torvalds 	if (!sig)
15081da177e4SLinus Torvalds 		return -ENOMEM;
15099d7fb042SPeter Zijlstra 
1510d036bda7SElena Reshetova 	refcount_set(&sig->count, 1);
151106e62a46SJann Horn 	spin_lock_irq(&current->sighand->siglock);
15121da177e4SLinus Torvalds 	memcpy(sig->action, current->sighand->action, sizeof(sig->action));
151306e62a46SJann Horn 	spin_unlock_irq(&current->sighand->siglock);
1514b612e5dfSChristian Brauner 
1515b612e5dfSChristian Brauner 	/* Reset all signal handler not set to SIG_IGN to SIG_DFL. */
1516b612e5dfSChristian Brauner 	if (clone_flags & CLONE_CLEAR_SIGHAND)
1517b612e5dfSChristian Brauner 		flush_signal_handlers(tsk, 0);
1518b612e5dfSChristian Brauner 
15191da177e4SLinus Torvalds 	return 0;
15201da177e4SLinus Torvalds }
15211da177e4SLinus Torvalds 
1522a7e5328aSOleg Nesterov void __cleanup_sighand(struct sighand_struct *sighand)
1523c81addc9SOleg Nesterov {
1524d036bda7SElena Reshetova 	if (refcount_dec_and_test(&sighand->count)) {
1525d80e731eSOleg Nesterov 		signalfd_cleanup(sighand);
1526392809b2SOleg Nesterov 		/*
15275f0d5a3aSPaul E. McKenney 		 * sighand_cachep is SLAB_TYPESAFE_BY_RCU so we can free it
1528392809b2SOleg Nesterov 		 * without an RCU grace period, see __lock_task_sighand().
1529392809b2SOleg Nesterov 		 */
1530c81addc9SOleg Nesterov 		kmem_cache_free(sighand_cachep, sighand);
1531c81addc9SOleg Nesterov 	}
1532d80e731eSOleg Nesterov }
1533c81addc9SOleg Nesterov 
1534f06febc9SFrank Mayhar /*
1535f06febc9SFrank Mayhar  * Initialize POSIX timer handling for a thread group.
1536f06febc9SFrank Mayhar  */
1537f06febc9SFrank Mayhar static void posix_cpu_timers_init_group(struct signal_struct *sig)
1538f06febc9SFrank Mayhar {
15392b69942fSThomas Gleixner 	struct posix_cputimers *pct = &sig->posix_cputimers;
154078d7d407SJiri Slaby 	unsigned long cpu_limit;
154178d7d407SJiri Slaby 
1542316c1608SJason Low 	cpu_limit = READ_ONCE(sig->rlim[RLIMIT_CPU].rlim_cur);
15433a245c0fSThomas Gleixner 	posix_cputimers_group_init(pct, cpu_limit);
15446279a751SOleg Nesterov }
15456279a751SOleg Nesterov 
1546a39bc516SAlexey Dobriyan static int copy_signal(unsigned long clone_flags, struct task_struct *tsk)
15471da177e4SLinus Torvalds {
15481da177e4SLinus Torvalds 	struct signal_struct *sig;
15491da177e4SLinus Torvalds 
15504ab6c083SOleg Nesterov 	if (clone_flags & CLONE_THREAD)
1551490dea45SPeter Zijlstra 		return 0;
15526279a751SOleg Nesterov 
1553a56704efSVeaceslav Falico 	sig = kmem_cache_zalloc(signal_cachep, GFP_KERNEL);
15541da177e4SLinus Torvalds 	tsk->signal = sig;
15551da177e4SLinus Torvalds 	if (!sig)
15561da177e4SLinus Torvalds 		return -ENOMEM;
15571da177e4SLinus Torvalds 
1558b3ac022cSOleg Nesterov 	sig->nr_threads = 1;
15591da177e4SLinus Torvalds 	atomic_set(&sig->live, 1);
156060d4de3fSElena Reshetova 	refcount_set(&sig->sigcnt, 1);
15610c740d0aSOleg Nesterov 
15620c740d0aSOleg Nesterov 	/* list_add(thread_node, thread_head) without INIT_LIST_HEAD() */
15630c740d0aSOleg Nesterov 	sig->thread_head = (struct list_head)LIST_HEAD_INIT(tsk->thread_node);
15640c740d0aSOleg Nesterov 	tsk->thread_node = (struct list_head)LIST_HEAD_INIT(sig->thread_head);
15650c740d0aSOleg Nesterov 
15661da177e4SLinus Torvalds 	init_waitqueue_head(&sig->wait_chldexit);
1567db51aeccSOleg Nesterov 	sig->curr_target = tsk;
15681da177e4SLinus Torvalds 	init_sigpending(&sig->shared_pending);
1569c3ad2c3bSEric W. Biederman 	INIT_HLIST_HEAD(&sig->multiprocess);
1570e78c3496SRik van Riel 	seqlock_init(&sig->stats_lock);
15719d7fb042SPeter Zijlstra 	prev_cputime_init(&sig->prev_cputime);
15721da177e4SLinus Torvalds 
1573baa73d9eSNicolas Pitre #ifdef CONFIG_POSIX_TIMERS
1574b18b6a9cSNicolas Pitre 	INIT_LIST_HEAD(&sig->posix_timers);
1575c9cb2e3dSThomas Gleixner 	hrtimer_init(&sig->real_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
15761da177e4SLinus Torvalds 	sig->real_timer.function = it_real_fn;
1577baa73d9eSNicolas Pitre #endif
15781da177e4SLinus Torvalds 
15791da177e4SLinus Torvalds 	task_lock(current->group_leader);
15801da177e4SLinus Torvalds 	memcpy(sig->rlim, current->signal->rlim, sizeof sig->rlim);
15811da177e4SLinus Torvalds 	task_unlock(current->group_leader);
15821da177e4SLinus Torvalds 
15836279a751SOleg Nesterov 	posix_cpu_timers_init_group(sig);
15846279a751SOleg Nesterov 
1585522ed776SMiloslav Trmac 	tty_audit_fork(sig);
15865091faa4SMike Galbraith 	sched_autogroup_fork(sig);
1587522ed776SMiloslav Trmac 
1588a63d83f4SDavid Rientjes 	sig->oom_score_adj = current->signal->oom_score_adj;
1589dabb16f6SMandeep Singh Baines 	sig->oom_score_adj_min = current->signal->oom_score_adj_min;
159028b83c51SKOSAKI Motohiro 
15919b1bf12dSKOSAKI Motohiro 	mutex_init(&sig->cred_guard_mutex);
1592eea96732SEric W. Biederman 	mutex_init(&sig->exec_update_mutex);
15939b1bf12dSKOSAKI Motohiro 
15941da177e4SLinus Torvalds 	return 0;
15951da177e4SLinus Torvalds }
15961da177e4SLinus Torvalds 
1597dbd95212SKees Cook static void copy_seccomp(struct task_struct *p)
1598dbd95212SKees Cook {
1599dbd95212SKees Cook #ifdef CONFIG_SECCOMP
1600dbd95212SKees Cook 	/*
1601dbd95212SKees Cook 	 * Must be called with sighand->lock held, which is common to
1602dbd95212SKees Cook 	 * all threads in the group. Holding cred_guard_mutex is not
1603dbd95212SKees Cook 	 * needed because this new task is not yet running and cannot
1604dbd95212SKees Cook 	 * be racing exec.
1605dbd95212SKees Cook 	 */
160669f6a34bSGuenter Roeck 	assert_spin_locked(&current->sighand->siglock);
1607dbd95212SKees Cook 
1608dbd95212SKees Cook 	/* Ref-count the new filter user, and assign it. */
1609dbd95212SKees Cook 	get_seccomp_filter(current);
1610dbd95212SKees Cook 	p->seccomp = current->seccomp;
1611dbd95212SKees Cook 
1612dbd95212SKees Cook 	/*
1613dbd95212SKees Cook 	 * Explicitly enable no_new_privs here in case it got set
1614dbd95212SKees Cook 	 * between the task_struct being duplicated and holding the
1615dbd95212SKees Cook 	 * sighand lock. The seccomp state and nnp must be in sync.
1616dbd95212SKees Cook 	 */
1617dbd95212SKees Cook 	if (task_no_new_privs(current))
1618dbd95212SKees Cook 		task_set_no_new_privs(p);
1619dbd95212SKees Cook 
1620dbd95212SKees Cook 	/*
1621dbd95212SKees Cook 	 * If the parent gained a seccomp mode after copying thread
1622dbd95212SKees Cook 	 * flags and between before we held the sighand lock, we have
1623dbd95212SKees Cook 	 * to manually enable the seccomp thread flag here.
1624dbd95212SKees Cook 	 */
1625dbd95212SKees Cook 	if (p->seccomp.mode != SECCOMP_MODE_DISABLED)
1626dbd95212SKees Cook 		set_tsk_thread_flag(p, TIF_SECCOMP);
1627dbd95212SKees Cook #endif
1628dbd95212SKees Cook }
1629dbd95212SKees Cook 
163017da2bd9SHeiko Carstens SYSCALL_DEFINE1(set_tid_address, int __user *, tidptr)
16311da177e4SLinus Torvalds {
16321da177e4SLinus Torvalds 	current->clear_child_tid = tidptr;
16331da177e4SLinus Torvalds 
1634b488893aSPavel Emelyanov 	return task_pid_vnr(current);
16351da177e4SLinus Torvalds }
16361da177e4SLinus Torvalds 
1637a39bc516SAlexey Dobriyan static void rt_mutex_init_task(struct task_struct *p)
163823f78d4aSIngo Molnar {
16391d615482SThomas Gleixner 	raw_spin_lock_init(&p->pi_lock);
1640e29e175bSZilvinas Valinskas #ifdef CONFIG_RT_MUTEXES
1641a23ba907SDavidlohr Bueso 	p->pi_waiters = RB_ROOT_CACHED;
1642e96a7705SXunlei Pang 	p->pi_top_task = NULL;
164323f78d4aSIngo Molnar 	p->pi_blocked_on = NULL;
164423f78d4aSIngo Molnar #endif
164523f78d4aSIngo Molnar }
164623f78d4aSIngo Molnar 
16472c470475SEric W. Biederman static inline void init_task_pid_links(struct task_struct *task)
16482c470475SEric W. Biederman {
16492c470475SEric W. Biederman 	enum pid_type type;
16502c470475SEric W. Biederman 
16512c470475SEric W. Biederman 	for (type = PIDTYPE_PID; type < PIDTYPE_MAX; ++type) {
16522c470475SEric W. Biederman 		INIT_HLIST_NODE(&task->pid_links[type]);
16532c470475SEric W. Biederman 	}
16542c470475SEric W. Biederman }
16552c470475SEric W. Biederman 
165681907739SOleg Nesterov static inline void
165781907739SOleg Nesterov init_task_pid(struct task_struct *task, enum pid_type type, struct pid *pid)
165881907739SOleg Nesterov {
16592c470475SEric W. Biederman 	if (type == PIDTYPE_PID)
16602c470475SEric W. Biederman 		task->thread_pid = pid;
16612c470475SEric W. Biederman 	else
16622c470475SEric W. Biederman 		task->signal->pids[type] = pid;
166381907739SOleg Nesterov }
166481907739SOleg Nesterov 
16656bfbaa51SIngo Molnar static inline void rcu_copy_process(struct task_struct *p)
16666bfbaa51SIngo Molnar {
16676bfbaa51SIngo Molnar #ifdef CONFIG_PREEMPT_RCU
16686bfbaa51SIngo Molnar 	p->rcu_read_lock_nesting = 0;
16696bfbaa51SIngo Molnar 	p->rcu_read_unlock_special.s = 0;
16706bfbaa51SIngo Molnar 	p->rcu_blocked_node = NULL;
16716bfbaa51SIngo Molnar 	INIT_LIST_HEAD(&p->rcu_node_entry);
16726bfbaa51SIngo Molnar #endif /* #ifdef CONFIG_PREEMPT_RCU */
16736bfbaa51SIngo Molnar #ifdef CONFIG_TASKS_RCU
16746bfbaa51SIngo Molnar 	p->rcu_tasks_holdout = false;
16756bfbaa51SIngo Molnar 	INIT_LIST_HEAD(&p->rcu_tasks_holdout_list);
16766bfbaa51SIngo Molnar 	p->rcu_tasks_idle_cpu = -1;
16776bfbaa51SIngo Molnar #endif /* #ifdef CONFIG_TASKS_RCU */
1678d5f177d3SPaul E. McKenney #ifdef CONFIG_TASKS_TRACE_RCU
1679d5f177d3SPaul E. McKenney 	p->trc_reader_nesting = 0;
1680276c4104SPaul E. McKenney 	p->trc_reader_special.s = 0;
1681d5f177d3SPaul E. McKenney 	INIT_LIST_HEAD(&p->trc_holdout_list);
1682d5f177d3SPaul E. McKenney #endif /* #ifdef CONFIG_TASKS_TRACE_RCU */
16836bfbaa51SIngo Molnar }
16846bfbaa51SIngo Molnar 
16853695eae5SChristian Brauner struct pid *pidfd_pid(const struct file *file)
16863695eae5SChristian Brauner {
16873695eae5SChristian Brauner 	if (file->f_op == &pidfd_fops)
16883695eae5SChristian Brauner 		return file->private_data;
16893695eae5SChristian Brauner 
16903695eae5SChristian Brauner 	return ERR_PTR(-EBADF);
16913695eae5SChristian Brauner }
16923695eae5SChristian Brauner 
1693b3e58382SChristian Brauner static int pidfd_release(struct inode *inode, struct file *file)
1694b3e58382SChristian Brauner {
1695b3e58382SChristian Brauner 	struct pid *pid = file->private_data;
1696b3e58382SChristian Brauner 
1697b3e58382SChristian Brauner 	file->private_data = NULL;
1698b3e58382SChristian Brauner 	put_pid(pid);
1699b3e58382SChristian Brauner 	return 0;
1700b3e58382SChristian Brauner }
1701b3e58382SChristian Brauner 
1702b3e58382SChristian Brauner #ifdef CONFIG_PROC_FS
170315d42eb2SChristian Kellner /**
170415d42eb2SChristian Kellner  * pidfd_show_fdinfo - print information about a pidfd
170515d42eb2SChristian Kellner  * @m: proc fdinfo file
170615d42eb2SChristian Kellner  * @f: file referencing a pidfd
170715d42eb2SChristian Kellner  *
170815d42eb2SChristian Kellner  * Pid:
170915d42eb2SChristian Kellner  * This function will print the pid that a given pidfd refers to in the
171015d42eb2SChristian Kellner  * pid namespace of the procfs instance.
171115d42eb2SChristian Kellner  * If the pid namespace of the process is not a descendant of the pid
171215d42eb2SChristian Kellner  * namespace of the procfs instance 0 will be shown as its pid. This is
171315d42eb2SChristian Kellner  * similar to calling getppid() on a process whose parent is outside of
171415d42eb2SChristian Kellner  * its pid namespace.
171515d42eb2SChristian Kellner  *
171615d42eb2SChristian Kellner  * NSpid:
171715d42eb2SChristian Kellner  * If pid namespaces are supported then this function will also print
171815d42eb2SChristian Kellner  * the pid of a given pidfd refers to for all descendant pid namespaces
171915d42eb2SChristian Kellner  * starting from the current pid namespace of the instance, i.e. the
172015d42eb2SChristian Kellner  * Pid field and the first entry in the NSpid field will be identical.
172115d42eb2SChristian Kellner  * If the pid namespace of the process is not a descendant of the pid
172215d42eb2SChristian Kellner  * namespace of the procfs instance 0 will be shown as its first NSpid
172315d42eb2SChristian Kellner  * entry and no others will be shown.
172415d42eb2SChristian Kellner  * Note that this differs from the Pid and NSpid fields in
172515d42eb2SChristian Kellner  * /proc/<pid>/status where Pid and NSpid are always shown relative to
172615d42eb2SChristian Kellner  * the  pid namespace of the procfs instance. The difference becomes
172715d42eb2SChristian Kellner  * obvious when sending around a pidfd between pid namespaces from a
172815d42eb2SChristian Kellner  * different branch of the tree, i.e. where no ancestoral relation is
172915d42eb2SChristian Kellner  * present between the pid namespaces:
173015d42eb2SChristian Kellner  * - create two new pid namespaces ns1 and ns2 in the initial pid
173115d42eb2SChristian Kellner  *   namespace (also take care to create new mount namespaces in the
173215d42eb2SChristian Kellner  *   new pid namespace and mount procfs)
173315d42eb2SChristian Kellner  * - create a process with a pidfd in ns1
173415d42eb2SChristian Kellner  * - send pidfd from ns1 to ns2
173515d42eb2SChristian Kellner  * - read /proc/self/fdinfo/<pidfd> and observe that both Pid and NSpid
173615d42eb2SChristian Kellner  *   have exactly one entry, which is 0
173715d42eb2SChristian Kellner  */
1738b3e58382SChristian Brauner static void pidfd_show_fdinfo(struct seq_file *m, struct file *f)
1739b3e58382SChristian Brauner {
1740b3e58382SChristian Brauner 	struct pid *pid = f->private_data;
17413d6d8da4SChristian Brauner 	struct pid_namespace *ns;
17423d6d8da4SChristian Brauner 	pid_t nr = -1;
1743b3e58382SChristian Brauner 
17443d6d8da4SChristian Brauner 	if (likely(pid_has_task(pid, PIDTYPE_PID))) {
17459d78edeaSAlexey Gladkov 		ns = proc_pid_ns(file_inode(m->file)->i_sb);
17463d6d8da4SChristian Brauner 		nr = pid_nr_ns(pid, ns);
17473d6d8da4SChristian Brauner 	}
17483d6d8da4SChristian Brauner 
17493d6d8da4SChristian Brauner 	seq_put_decimal_ll(m, "Pid:\t", nr);
175015d42eb2SChristian Kellner 
175115d42eb2SChristian Kellner #ifdef CONFIG_PID_NS
17523d6d8da4SChristian Brauner 	seq_put_decimal_ll(m, "\nNSpid:\t", nr);
17533d6d8da4SChristian Brauner 	if (nr > 0) {
175415d42eb2SChristian Kellner 		int i;
175515d42eb2SChristian Kellner 
175615d42eb2SChristian Kellner 		/* If nr is non-zero it means that 'pid' is valid and that
175715d42eb2SChristian Kellner 		 * ns, i.e. the pid namespace associated with the procfs
175815d42eb2SChristian Kellner 		 * instance, is in the pid namespace hierarchy of pid.
175915d42eb2SChristian Kellner 		 * Start at one below the already printed level.
176015d42eb2SChristian Kellner 		 */
176115d42eb2SChristian Kellner 		for (i = ns->level + 1; i <= pid->level; i++)
17623d6d8da4SChristian Brauner 			seq_put_decimal_ll(m, "\t", pid->numbers[i].nr);
176315d42eb2SChristian Kellner 	}
176415d42eb2SChristian Kellner #endif
1765b3e58382SChristian Brauner 	seq_putc(m, '\n');
1766b3e58382SChristian Brauner }
1767b3e58382SChristian Brauner #endif
1768b3e58382SChristian Brauner 
1769b53b0b9dSJoel Fernandes (Google) /*
1770b53b0b9dSJoel Fernandes (Google)  * Poll support for process exit notification.
1771b53b0b9dSJoel Fernandes (Google)  */
17729e77716aSLuc Van Oostenryck static __poll_t pidfd_poll(struct file *file, struct poll_table_struct *pts)
1773b53b0b9dSJoel Fernandes (Google) {
1774b53b0b9dSJoel Fernandes (Google) 	struct pid *pid = file->private_data;
17759e77716aSLuc Van Oostenryck 	__poll_t poll_flags = 0;
1776b53b0b9dSJoel Fernandes (Google) 
1777b53b0b9dSJoel Fernandes (Google) 	poll_wait(file, &pid->wait_pidfd, pts);
1778b53b0b9dSJoel Fernandes (Google) 
1779b53b0b9dSJoel Fernandes (Google) 	/*
1780b53b0b9dSJoel Fernandes (Google) 	 * Inform pollers only when the whole thread group exits.
1781b53b0b9dSJoel Fernandes (Google) 	 * If the thread group leader exits before all other threads in the
1782b53b0b9dSJoel Fernandes (Google) 	 * group, then poll(2) should block, similar to the wait(2) family.
1783b53b0b9dSJoel Fernandes (Google) 	 */
178438fd525aSEric W. Biederman 	if (thread_group_exited(pid))
17859e77716aSLuc Van Oostenryck 		poll_flags = EPOLLIN | EPOLLRDNORM;
1786b53b0b9dSJoel Fernandes (Google) 
1787b53b0b9dSJoel Fernandes (Google) 	return poll_flags;
1788b53b0b9dSJoel Fernandes (Google) }
1789b53b0b9dSJoel Fernandes (Google) 
1790b3e58382SChristian Brauner const struct file_operations pidfd_fops = {
1791b3e58382SChristian Brauner 	.release = pidfd_release,
1792b53b0b9dSJoel Fernandes (Google) 	.poll = pidfd_poll,
1793b3e58382SChristian Brauner #ifdef CONFIG_PROC_FS
1794b3e58382SChristian Brauner 	.show_fdinfo = pidfd_show_fdinfo,
1795b3e58382SChristian Brauner #endif
1796b3e58382SChristian Brauner };
1797b3e58382SChristian Brauner 
1798c3f3ce04SAndrea Arcangeli static void __delayed_free_task(struct rcu_head *rhp)
1799c3f3ce04SAndrea Arcangeli {
1800c3f3ce04SAndrea Arcangeli 	struct task_struct *tsk = container_of(rhp, struct task_struct, rcu);
1801c3f3ce04SAndrea Arcangeli 
1802c3f3ce04SAndrea Arcangeli 	free_task(tsk);
1803c3f3ce04SAndrea Arcangeli }
1804c3f3ce04SAndrea Arcangeli 
1805c3f3ce04SAndrea Arcangeli static __always_inline void delayed_free_task(struct task_struct *tsk)
1806c3f3ce04SAndrea Arcangeli {
1807c3f3ce04SAndrea Arcangeli 	if (IS_ENABLED(CONFIG_MEMCG))
1808c3f3ce04SAndrea Arcangeli 		call_rcu(&tsk->rcu, __delayed_free_task);
1809c3f3ce04SAndrea Arcangeli 	else
1810c3f3ce04SAndrea Arcangeli 		free_task(tsk);
1811c3f3ce04SAndrea Arcangeli }
1812c3f3ce04SAndrea Arcangeli 
1813f06febc9SFrank Mayhar /*
18141da177e4SLinus Torvalds  * This creates a new process as a copy of the old one,
18151da177e4SLinus Torvalds  * but does not actually start it yet.
18161da177e4SLinus Torvalds  *
18171da177e4SLinus Torvalds  * It copies the registers, and all the appropriate
18181da177e4SLinus Torvalds  * parts of the process environment (as per the clone
18191da177e4SLinus Torvalds  * flags). The actual kick-off is left to the caller.
18201da177e4SLinus Torvalds  */
18210766f788SEmese Revfy static __latent_entropy struct task_struct *copy_process(
182209a05394SRoland McGrath 					struct pid *pid,
18233033f14aSJosh Triplett 					int trace,
18247f192e3cSChristian Brauner 					int node,
18257f192e3cSChristian Brauner 					struct kernel_clone_args *args)
18261da177e4SLinus Torvalds {
1827b3e58382SChristian Brauner 	int pidfd = -1, retval;
1828a24efe62SMariusz Kozlowski 	struct task_struct *p;
1829c3ad2c3bSEric W. Biederman 	struct multiprocess_signals delayed;
18306fd2fe49SAl Viro 	struct file *pidfile = NULL;
18317f192e3cSChristian Brauner 	u64 clone_flags = args->flags;
1832769071acSAndrei Vagin 	struct nsproxy *nsp = current->nsproxy;
18331da177e4SLinus Torvalds 
1834667b6094SMarcos Paulo de Souza 	/*
1835667b6094SMarcos Paulo de Souza 	 * Don't allow sharing the root directory with processes in a different
1836667b6094SMarcos Paulo de Souza 	 * namespace
1837667b6094SMarcos Paulo de Souza 	 */
18381da177e4SLinus Torvalds 	if ((clone_flags & (CLONE_NEWNS|CLONE_FS)) == (CLONE_NEWNS|CLONE_FS))
18391da177e4SLinus Torvalds 		return ERR_PTR(-EINVAL);
18401da177e4SLinus Torvalds 
1841e66eded8SEric W. Biederman 	if ((clone_flags & (CLONE_NEWUSER|CLONE_FS)) == (CLONE_NEWUSER|CLONE_FS))
1842e66eded8SEric W. Biederman 		return ERR_PTR(-EINVAL);
1843e66eded8SEric W. Biederman 
18441da177e4SLinus Torvalds 	/*
18451da177e4SLinus Torvalds 	 * Thread groups must share signals as well, and detached threads
18461da177e4SLinus Torvalds 	 * can only be started up within the thread group.
18471da177e4SLinus Torvalds 	 */
18481da177e4SLinus Torvalds 	if ((clone_flags & CLONE_THREAD) && !(clone_flags & CLONE_SIGHAND))
18491da177e4SLinus Torvalds 		return ERR_PTR(-EINVAL);
18501da177e4SLinus Torvalds 
18511da177e4SLinus Torvalds 	/*
18521da177e4SLinus Torvalds 	 * Shared signal handlers imply shared VM. By way of the above,
18531da177e4SLinus Torvalds 	 * thread groups also imply shared VM. Blocking this case allows
18541da177e4SLinus Torvalds 	 * for various simplifications in other code.
18551da177e4SLinus Torvalds 	 */
18561da177e4SLinus Torvalds 	if ((clone_flags & CLONE_SIGHAND) && !(clone_flags & CLONE_VM))
18571da177e4SLinus Torvalds 		return ERR_PTR(-EINVAL);
18581da177e4SLinus Torvalds 
1859123be07bSSukadev Bhattiprolu 	/*
1860123be07bSSukadev Bhattiprolu 	 * Siblings of global init remain as zombies on exit since they are
1861123be07bSSukadev Bhattiprolu 	 * not reaped by their parent (swapper). To solve this and to avoid
1862123be07bSSukadev Bhattiprolu 	 * multi-rooted process trees, prevent global and container-inits
1863123be07bSSukadev Bhattiprolu 	 * from creating siblings.
1864123be07bSSukadev Bhattiprolu 	 */
1865123be07bSSukadev Bhattiprolu 	if ((clone_flags & CLONE_PARENT) &&
1866123be07bSSukadev Bhattiprolu 				current->signal->flags & SIGNAL_UNKILLABLE)
1867123be07bSSukadev Bhattiprolu 		return ERR_PTR(-EINVAL);
1868123be07bSSukadev Bhattiprolu 
18698382fcacSEric W. Biederman 	/*
187040a0d32dSOleg Nesterov 	 * If the new process will be in a different pid or user namespace
1871faf00da5SEric W. Biederman 	 * do not allow it to share a thread group with the forking task.
18728382fcacSEric W. Biederman 	 */
1873faf00da5SEric W. Biederman 	if (clone_flags & CLONE_THREAD) {
187440a0d32dSOleg Nesterov 		if ((clone_flags & (CLONE_NEWUSER | CLONE_NEWPID)) ||
1875769071acSAndrei Vagin 		    (task_active_pid_ns(current) != nsp->pid_ns_for_children))
1876769071acSAndrei Vagin 			return ERR_PTR(-EINVAL);
1877769071acSAndrei Vagin 	}
1878769071acSAndrei Vagin 
1879769071acSAndrei Vagin 	/*
1880769071acSAndrei Vagin 	 * If the new process will be in a different time namespace
1881769071acSAndrei Vagin 	 * do not allow it to share VM or a thread group with the forking task.
1882769071acSAndrei Vagin 	 */
1883769071acSAndrei Vagin 	if (clone_flags & (CLONE_THREAD | CLONE_VM)) {
1884769071acSAndrei Vagin 		if (nsp->time_ns != nsp->time_ns_for_children)
18858382fcacSEric W. Biederman 			return ERR_PTR(-EINVAL);
188640a0d32dSOleg Nesterov 	}
18878382fcacSEric W. Biederman 
1888b3e58382SChristian Brauner 	if (clone_flags & CLONE_PIDFD) {
1889b3e58382SChristian Brauner 		/*
1890b3e58382SChristian Brauner 		 * - CLONE_DETACHED is blocked so that we can potentially
1891b3e58382SChristian Brauner 		 *   reuse it later for CLONE_PIDFD.
1892b3e58382SChristian Brauner 		 * - CLONE_THREAD is blocked until someone really needs it.
1893b3e58382SChristian Brauner 		 */
18947f192e3cSChristian Brauner 		if (clone_flags & (CLONE_DETACHED | CLONE_THREAD))
1895b3e58382SChristian Brauner 			return ERR_PTR(-EINVAL);
1896b3e58382SChristian Brauner 	}
1897b3e58382SChristian Brauner 
1898c3ad2c3bSEric W. Biederman 	/*
1899c3ad2c3bSEric W. Biederman 	 * Force any signals received before this point to be delivered
1900c3ad2c3bSEric W. Biederman 	 * before the fork happens.  Collect up signals sent to multiple
1901c3ad2c3bSEric W. Biederman 	 * processes that happen during the fork and delay them so that
1902c3ad2c3bSEric W. Biederman 	 * they appear to happen after the fork.
1903c3ad2c3bSEric W. Biederman 	 */
1904c3ad2c3bSEric W. Biederman 	sigemptyset(&delayed.signal);
1905c3ad2c3bSEric W. Biederman 	INIT_HLIST_NODE(&delayed.node);
1906c3ad2c3bSEric W. Biederman 
1907c3ad2c3bSEric W. Biederman 	spin_lock_irq(&current->sighand->siglock);
1908c3ad2c3bSEric W. Biederman 	if (!(clone_flags & CLONE_THREAD))
1909c3ad2c3bSEric W. Biederman 		hlist_add_head(&delayed.node, &current->signal->multiprocess);
1910c3ad2c3bSEric W. Biederman 	recalc_sigpending();
1911c3ad2c3bSEric W. Biederman 	spin_unlock_irq(&current->sighand->siglock);
1912c3ad2c3bSEric W. Biederman 	retval = -ERESTARTNOINTR;
1913c3ad2c3bSEric W. Biederman 	if (signal_pending(current))
1914c3ad2c3bSEric W. Biederman 		goto fork_out;
1915c3ad2c3bSEric W. Biederman 
19161da177e4SLinus Torvalds 	retval = -ENOMEM;
1917725fc629SAndi Kleen 	p = dup_task_struct(current, node);
19181da177e4SLinus Torvalds 	if (!p)
19191da177e4SLinus Torvalds 		goto fork_out;
19201da177e4SLinus Torvalds 
19214d6501dcSVegard Nossum 	/*
19224d6501dcSVegard Nossum 	 * This _must_ happen before we call free_task(), i.e. before we jump
19234d6501dcSVegard Nossum 	 * to any of the bad_fork_* labels. This is to avoid freeing
19244d6501dcSVegard Nossum 	 * p->set_child_tid which is (ab)used as a kthread's data pointer for
19254d6501dcSVegard Nossum 	 * kernel threads (PF_KTHREAD).
19264d6501dcSVegard Nossum 	 */
19277f192e3cSChristian Brauner 	p->set_child_tid = (clone_flags & CLONE_CHILD_SETTID) ? args->child_tid : NULL;
19284d6501dcSVegard Nossum 	/*
19294d6501dcSVegard Nossum 	 * Clear TID on mm_release()?
19304d6501dcSVegard Nossum 	 */
19317f192e3cSChristian Brauner 	p->clear_child_tid = (clone_flags & CLONE_CHILD_CLEARTID) ? args->child_tid : NULL;
19324d6501dcSVegard Nossum 
1933f7e8b616SSteven Rostedt 	ftrace_graph_init_task(p);
1934f7e8b616SSteven Rostedt 
1935bea493a0SPeter Zijlstra 	rt_mutex_init_task(p);
1936bea493a0SPeter Zijlstra 
1937a21ee605SPeter Zijlstra 	lockdep_assert_irqs_enabled();
1938d12c1a37SIngo Molnar #ifdef CONFIG_PROVE_LOCKING
1939de30a2b3SIngo Molnar 	DEBUG_LOCKS_WARN_ON(!p->softirqs_enabled);
1940de30a2b3SIngo Molnar #endif
19411da177e4SLinus Torvalds 	retval = -EAGAIN;
19423b11a1deSDavid Howells 	if (atomic_read(&p->real_cred->user->processes) >=
194378d7d407SJiri Slaby 			task_rlimit(p, RLIMIT_NPROC)) {
1944b57922b6SEric Paris 		if (p->real_cred->user != INIT_USER &&
1945b57922b6SEric Paris 		    !capable(CAP_SYS_RESOURCE) && !capable(CAP_SYS_ADMIN))
19461da177e4SLinus Torvalds 			goto bad_fork_free;
19471da177e4SLinus Torvalds 	}
194872fa5997SVasiliy Kulikov 	current->flags &= ~PF_NPROC_EXCEEDED;
19491da177e4SLinus Torvalds 
1950f1752eecSDavid Howells 	retval = copy_creds(p, clone_flags);
1951f1752eecSDavid Howells 	if (retval < 0)
1952f1752eecSDavid Howells 		goto bad_fork_free;
19531da177e4SLinus Torvalds 
19541da177e4SLinus Torvalds 	/*
19551da177e4SLinus Torvalds 	 * If multiple threads are within copy_process(), then this check
19561da177e4SLinus Torvalds 	 * triggers too late. This doesn't hurt, the check is only there
19571da177e4SLinus Torvalds 	 * to stop root fork bombs.
19581da177e4SLinus Torvalds 	 */
195904ec93feSLi Zefan 	retval = -EAGAIN;
1960c17d1a3aSWeilong Chen 	if (data_race(nr_threads >= max_threads))
19611da177e4SLinus Torvalds 		goto bad_fork_cleanup_count;
19621da177e4SLinus Torvalds 
1963ca74e92bSShailabh Nagar 	delayacct_tsk_init(p);	/* Must remain after dup_task_struct() */
1964c1de45caSPeter Zijlstra 	p->flags &= ~(PF_SUPERPRIV | PF_WQ_WORKER | PF_IDLE);
1965514ddb44SDavid Rientjes 	p->flags |= PF_FORKNOEXEC;
19661da177e4SLinus Torvalds 	INIT_LIST_HEAD(&p->children);
19671da177e4SLinus Torvalds 	INIT_LIST_HEAD(&p->sibling);
1968f41d911fSPaul E. McKenney 	rcu_copy_process(p);
19691da177e4SLinus Torvalds 	p->vfork_done = NULL;
19701da177e4SLinus Torvalds 	spin_lock_init(&p->alloc_lock);
19711da177e4SLinus Torvalds 
19721da177e4SLinus Torvalds 	init_sigpending(&p->pending);
19731da177e4SLinus Torvalds 
197464861634SMartin Schwidefsky 	p->utime = p->stime = p->gtime = 0;
197540565b5aSStanislaw Gruszka #ifdef CONFIG_ARCH_HAS_SCALED_CPUTIME
197664861634SMartin Schwidefsky 	p->utimescaled = p->stimescaled = 0;
197740565b5aSStanislaw Gruszka #endif
19789d7fb042SPeter Zijlstra 	prev_cputime_init(&p->prev_cputime);
19799d7fb042SPeter Zijlstra 
19806a61671bSFrederic Weisbecker #ifdef CONFIG_VIRT_CPU_ACCOUNTING_GEN
1981bac5b6b6SFrederic Weisbecker 	seqcount_init(&p->vtime.seqcount);
1982bac5b6b6SFrederic Weisbecker 	p->vtime.starttime = 0;
1983bac5b6b6SFrederic Weisbecker 	p->vtime.state = VTIME_INACTIVE;
19846a61671bSFrederic Weisbecker #endif
19856a61671bSFrederic Weisbecker 
1986a3a2e76cSKAMEZAWA Hiroyuki #if defined(SPLIT_RSS_COUNTING)
1987a3a2e76cSKAMEZAWA Hiroyuki 	memset(&p->rss_stat, 0, sizeof(p->rss_stat));
1988a3a2e76cSKAMEZAWA Hiroyuki #endif
1989172ba844SBalbir Singh 
19906976675dSArjan van de Ven 	p->default_timer_slack_ns = current->timer_slack_ns;
19916976675dSArjan van de Ven 
1992eb414681SJohannes Weiner #ifdef CONFIG_PSI
1993eb414681SJohannes Weiner 	p->psi_flags = 0;
1994eb414681SJohannes Weiner #endif
1995eb414681SJohannes Weiner 
19965995477aSAndrea Righi 	task_io_accounting_init(&p->ioac);
19971da177e4SLinus Torvalds 	acct_clear_integrals(p);
19981da177e4SLinus Torvalds 
19993a245c0fSThomas Gleixner 	posix_cputimers_init(&p->posix_cputimers);
20001da177e4SLinus Torvalds 
20011da177e4SLinus Torvalds 	p->io_context = NULL;
2002c0b0ae8aSRichard Guy Briggs 	audit_set_context(p, NULL);
2003b4f48b63SPaul Menage 	cgroup_fork(p);
20041da177e4SLinus Torvalds #ifdef CONFIG_NUMA
2005846a16bfSLee Schermerhorn 	p->mempolicy = mpol_dup(p->mempolicy);
20061da177e4SLinus Torvalds 	if (IS_ERR(p->mempolicy)) {
20071da177e4SLinus Torvalds 		retval = PTR_ERR(p->mempolicy);
20081da177e4SLinus Torvalds 		p->mempolicy = NULL;
2009e8604cb4SLi Zefan 		goto bad_fork_cleanup_threadgroup_lock;
20101da177e4SLinus Torvalds 	}
20111da177e4SLinus Torvalds #endif
2012778d3b0fSMichal Hocko #ifdef CONFIG_CPUSETS
2013778d3b0fSMichal Hocko 	p->cpuset_mem_spread_rotor = NUMA_NO_NODE;
2014778d3b0fSMichal Hocko 	p->cpuset_slab_spread_rotor = NUMA_NO_NODE;
2015b7505861SAhmed S. Darwish 	seqcount_spinlock_init(&p->mems_allowed_seq, &p->alloc_lock);
2016778d3b0fSMichal Hocko #endif
2017de30a2b3SIngo Molnar #ifdef CONFIG_TRACE_IRQFLAGS
20180584df9cSMarco Elver 	memset(&p->irqtrace, 0, sizeof(p->irqtrace));
20190584df9cSMarco Elver 	p->irqtrace.hardirq_disable_ip	= _THIS_IP_;
20200584df9cSMarco Elver 	p->irqtrace.softirq_enable_ip	= _THIS_IP_;
2021de30a2b3SIngo Molnar 	p->softirqs_enabled		= 1;
2022de30a2b3SIngo Molnar 	p->softirq_context		= 0;
2023de30a2b3SIngo Molnar #endif
20248bcbde54SDavid Hildenbrand 
20258bcbde54SDavid Hildenbrand 	p->pagefault_disabled = 0;
20268bcbde54SDavid Hildenbrand 
2027fbb9ce95SIngo Molnar #ifdef CONFIG_LOCKDEP
2028b09be676SByungchul Park 	lockdep_init_task(p);
2029fbb9ce95SIngo Molnar #endif
20301da177e4SLinus Torvalds 
2031408894eeSIngo Molnar #ifdef CONFIG_DEBUG_MUTEXES
2032408894eeSIngo Molnar 	p->blocked_on = NULL; /* not blocked yet */
2033408894eeSIngo Molnar #endif
2034cafe5635SKent Overstreet #ifdef CONFIG_BCACHE
2035cafe5635SKent Overstreet 	p->sequential_io	= 0;
2036cafe5635SKent Overstreet 	p->sequential_io_avg	= 0;
2037cafe5635SKent Overstreet #endif
20380f481406SMarkus Metzger 
20393c90e6e9SSrivatsa Vaddagiri 	/* Perform scheduler related setup. Assign this task to a CPU. */
2040aab03e05SDario Faggioli 	retval = sched_fork(clone_flags, p);
2041aab03e05SDario Faggioli 	if (retval)
2042aab03e05SDario Faggioli 		goto bad_fork_cleanup_policy;
20436ab423e0SPeter Zijlstra 
2044cdd6c482SIngo Molnar 	retval = perf_event_init_task(p);
20456ab423e0SPeter Zijlstra 	if (retval)
20466ab423e0SPeter Zijlstra 		goto bad_fork_cleanup_policy;
2047fb0a685cSDaniel Rebelo de Oliveira 	retval = audit_alloc(p);
2048fb0a685cSDaniel Rebelo de Oliveira 	if (retval)
20496c72e350SPeter Zijlstra 		goto bad_fork_cleanup_perf;
20501da177e4SLinus Torvalds 	/* copy all the process information */
2051ab602f79SJack Miller 	shm_init_task(p);
2052e4e55b47STetsuo Handa 	retval = security_task_alloc(p, clone_flags);
2053fb0a685cSDaniel Rebelo de Oliveira 	if (retval)
20541da177e4SLinus Torvalds 		goto bad_fork_cleanup_audit;
2055e4e55b47STetsuo Handa 	retval = copy_semundo(clone_flags, p);
2056e4e55b47STetsuo Handa 	if (retval)
2057e4e55b47STetsuo Handa 		goto bad_fork_cleanup_security;
2058fb0a685cSDaniel Rebelo de Oliveira 	retval = copy_files(clone_flags, p);
2059fb0a685cSDaniel Rebelo de Oliveira 	if (retval)
20601da177e4SLinus Torvalds 		goto bad_fork_cleanup_semundo;
2061fb0a685cSDaniel Rebelo de Oliveira 	retval = copy_fs(clone_flags, p);
2062fb0a685cSDaniel Rebelo de Oliveira 	if (retval)
20631da177e4SLinus Torvalds 		goto bad_fork_cleanup_files;
2064fb0a685cSDaniel Rebelo de Oliveira 	retval = copy_sighand(clone_flags, p);
2065fb0a685cSDaniel Rebelo de Oliveira 	if (retval)
20661da177e4SLinus Torvalds 		goto bad_fork_cleanup_fs;
2067fb0a685cSDaniel Rebelo de Oliveira 	retval = copy_signal(clone_flags, p);
2068fb0a685cSDaniel Rebelo de Oliveira 	if (retval)
20691da177e4SLinus Torvalds 		goto bad_fork_cleanup_sighand;
2070fb0a685cSDaniel Rebelo de Oliveira 	retval = copy_mm(clone_flags, p);
2071fb0a685cSDaniel Rebelo de Oliveira 	if (retval)
20721da177e4SLinus Torvalds 		goto bad_fork_cleanup_signal;
2073fb0a685cSDaniel Rebelo de Oliveira 	retval = copy_namespaces(clone_flags, p);
2074fb0a685cSDaniel Rebelo de Oliveira 	if (retval)
2075d84f4f99SDavid Howells 		goto bad_fork_cleanup_mm;
2076fb0a685cSDaniel Rebelo de Oliveira 	retval = copy_io(clone_flags, p);
2077fb0a685cSDaniel Rebelo de Oliveira 	if (retval)
2078fd0928dfSJens Axboe 		goto bad_fork_cleanup_namespaces;
2079714acdbdSChristian Brauner 	retval = copy_thread(clone_flags, args->stack, args->stack_size, p, args->tls);
20801da177e4SLinus Torvalds 	if (retval)
2081fd0928dfSJens Axboe 		goto bad_fork_cleanup_io;
20821da177e4SLinus Torvalds 
2083afaef01cSAlexander Popov 	stackleak_task_init(p);
2084afaef01cSAlexander Popov 
2085425fb2b4SPavel Emelyanov 	if (pid != &init_struct_pid) {
208649cb2fc4SAdrian Reber 		pid = alloc_pid(p->nsproxy->pid_ns_for_children, args->set_tid,
208749cb2fc4SAdrian Reber 				args->set_tid_size);
208835f71bc0SMichal Hocko 		if (IS_ERR(pid)) {
208935f71bc0SMichal Hocko 			retval = PTR_ERR(pid);
20900740aa5fSJiri Slaby 			goto bad_fork_cleanup_thread;
2091425fb2b4SPavel Emelyanov 		}
209235f71bc0SMichal Hocko 	}
2093425fb2b4SPavel Emelyanov 
2094b3e58382SChristian Brauner 	/*
2095b3e58382SChristian Brauner 	 * This has to happen after we've potentially unshared the file
2096b3e58382SChristian Brauner 	 * descriptor table (so that the pidfd doesn't leak into the child
2097b3e58382SChristian Brauner 	 * if the fd table isn't shared).
2098b3e58382SChristian Brauner 	 */
2099b3e58382SChristian Brauner 	if (clone_flags & CLONE_PIDFD) {
21006fd2fe49SAl Viro 		retval = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
2101b3e58382SChristian Brauner 		if (retval < 0)
2102b3e58382SChristian Brauner 			goto bad_fork_free_pid;
2103b3e58382SChristian Brauner 
2104b3e58382SChristian Brauner 		pidfd = retval;
21056fd2fe49SAl Viro 
21066fd2fe49SAl Viro 		pidfile = anon_inode_getfile("[pidfd]", &pidfd_fops, pid,
21076fd2fe49SAl Viro 					      O_RDWR | O_CLOEXEC);
21086fd2fe49SAl Viro 		if (IS_ERR(pidfile)) {
21096fd2fe49SAl Viro 			put_unused_fd(pidfd);
211028dd29c0SChristian Brauner 			retval = PTR_ERR(pidfile);
21116fd2fe49SAl Viro 			goto bad_fork_free_pid;
21126fd2fe49SAl Viro 		}
21136fd2fe49SAl Viro 		get_pid(pid);	/* held by pidfile now */
21146fd2fe49SAl Viro 
21157f192e3cSChristian Brauner 		retval = put_user(pidfd, args->pidfd);
2116b3e58382SChristian Brauner 		if (retval)
2117b3e58382SChristian Brauner 			goto bad_fork_put_pidfd;
2118b3e58382SChristian Brauner 	}
2119b3e58382SChristian Brauner 
212073c10101SJens Axboe #ifdef CONFIG_BLOCK
212173c10101SJens Axboe 	p->plug = NULL;
212273c10101SJens Axboe #endif
2123ba31c1a4SThomas Gleixner 	futex_init_task(p);
2124ba31c1a4SThomas Gleixner 
21251da177e4SLinus Torvalds 	/*
2126f9a3879aSGOTO Masanori 	 * sigaltstack should be cleared when sharing the same VM
2127f9a3879aSGOTO Masanori 	 */
2128f9a3879aSGOTO Masanori 	if ((clone_flags & (CLONE_VM|CLONE_VFORK)) == CLONE_VM)
21292a742138SStas Sergeev 		sas_ss_reset(p);
2130f9a3879aSGOTO Masanori 
2131f9a3879aSGOTO Masanori 	/*
21326580807dSOleg Nesterov 	 * Syscall tracing and stepping should be turned off in the
21336580807dSOleg Nesterov 	 * child regardless of CLONE_PTRACE.
21341da177e4SLinus Torvalds 	 */
21356580807dSOleg Nesterov 	user_disable_single_step(p);
21361da177e4SLinus Torvalds 	clear_tsk_thread_flag(p, TIF_SYSCALL_TRACE);
2137ed75e8d5SLaurent Vivier #ifdef TIF_SYSCALL_EMU
2138ed75e8d5SLaurent Vivier 	clear_tsk_thread_flag(p, TIF_SYSCALL_EMU);
2139ed75e8d5SLaurent Vivier #endif
2140e02c9b0dSLin Feng 	clear_tsk_latency_tracing(p);
21411da177e4SLinus Torvalds 
21421da177e4SLinus Torvalds 	/* ok, now we should be set up.. */
214318c830dfSOleg Nesterov 	p->pid = pid_nr(pid);
214418c830dfSOleg Nesterov 	if (clone_flags & CLONE_THREAD) {
21455f8aadd8SOleg Nesterov 		p->exit_signal = -1;
214618c830dfSOleg Nesterov 		p->group_leader = current->group_leader;
214718c830dfSOleg Nesterov 		p->tgid = current->tgid;
214818c830dfSOleg Nesterov 	} else {
214918c830dfSOleg Nesterov 		if (clone_flags & CLONE_PARENT)
21505f8aadd8SOleg Nesterov 			p->exit_signal = current->group_leader->exit_signal;
21515f8aadd8SOleg Nesterov 		else
21527f192e3cSChristian Brauner 			p->exit_signal = args->exit_signal;
215318c830dfSOleg Nesterov 		p->group_leader = p;
215418c830dfSOleg Nesterov 		p->tgid = p->pid;
215518c830dfSOleg Nesterov 	}
21565f8aadd8SOleg Nesterov 
21579d823e8fSWu Fengguang 	p->nr_dirtied = 0;
21589d823e8fSWu Fengguang 	p->nr_dirtied_pause = 128 >> (PAGE_SHIFT - 10);
215983712358SWu Fengguang 	p->dirty_paused_when = 0;
21609d823e8fSWu Fengguang 
2161bb8cbbfeSOleg Nesterov 	p->pdeath_signal = 0;
216247e65328SOleg Nesterov 	INIT_LIST_HEAD(&p->thread_group);
2163158e1645SAl Viro 	p->task_works = NULL;
21641da177e4SLinus Torvalds 
216518c830dfSOleg Nesterov 	/*
21667e47682eSAleksa Sarai 	 * Ensure that the cgroup subsystem policies allow the new process to be
21677e47682eSAleksa Sarai 	 * forked. It should be noted the the new process's css_set can be changed
21687e47682eSAleksa Sarai 	 * between here and cgroup_post_fork() if an organisation operation is in
21697e47682eSAleksa Sarai 	 * progress.
21707e47682eSAleksa Sarai 	 */
2171ef2c41cfSChristian Brauner 	retval = cgroup_can_fork(p, args);
21727e47682eSAleksa Sarai 	if (retval)
21735a5cf5cbSChristian Brauner 		goto bad_fork_put_pidfd;
21747e47682eSAleksa Sarai 
21757e47682eSAleksa Sarai 	/*
21767b558513SDavid Herrmann 	 * From this point on we must avoid any synchronous user-space
21777b558513SDavid Herrmann 	 * communication until we take the tasklist-lock. In particular, we do
21787b558513SDavid Herrmann 	 * not want user-space to be able to predict the process start-time by
21797b558513SDavid Herrmann 	 * stalling fork(2) after we recorded the start_time but before it is
21807b558513SDavid Herrmann 	 * visible to the system.
21817b558513SDavid Herrmann 	 */
21827b558513SDavid Herrmann 
21837b558513SDavid Herrmann 	p->start_time = ktime_get_ns();
2184cf25e24dSPeter Zijlstra 	p->start_boottime = ktime_get_boottime_ns();
21857b558513SDavid Herrmann 
21867b558513SDavid Herrmann 	/*
218718c830dfSOleg Nesterov 	 * Make it visible to the rest of the system, but dont wake it up yet.
218818c830dfSOleg Nesterov 	 * Need tasklist lock for parent etc handling!
218918c830dfSOleg Nesterov 	 */
21901da177e4SLinus Torvalds 	write_lock_irq(&tasklist_lock);
21911da177e4SLinus Torvalds 
21921da177e4SLinus Torvalds 	/* CLONE_PARENT re-uses the old parent */
21932d5516cbSOleg Nesterov 	if (clone_flags & (CLONE_PARENT|CLONE_THREAD)) {
21941da177e4SLinus Torvalds 		p->real_parent = current->real_parent;
21952d5516cbSOleg Nesterov 		p->parent_exec_id = current->parent_exec_id;
21962d5516cbSOleg Nesterov 	} else {
21971da177e4SLinus Torvalds 		p->real_parent = current;
21982d5516cbSOleg Nesterov 		p->parent_exec_id = current->self_exec_id;
21992d5516cbSOleg Nesterov 	}
22001da177e4SLinus Torvalds 
2201d83a7cb3SJosh Poimboeuf 	klp_copy_process(p);
2202d83a7cb3SJosh Poimboeuf 
22031da177e4SLinus Torvalds 	spin_lock(&current->sighand->siglock);
22044a2c7a78SOleg Nesterov 
22054a2c7a78SOleg Nesterov 	/*
2206dbd95212SKees Cook 	 * Copy seccomp details explicitly here, in case they were changed
2207dbd95212SKees Cook 	 * before holding sighand lock.
2208dbd95212SKees Cook 	 */
2209dbd95212SKees Cook 	copy_seccomp(p);
2210dbd95212SKees Cook 
2211d7822b1eSMathieu Desnoyers 	rseq_fork(p, clone_flags);
2212d7822b1eSMathieu Desnoyers 
22134ca1d3eeSEric W. Biederman 	/* Don't start children in a dying pid namespace */
2214e8cfbc24SGargi Sharma 	if (unlikely(!(ns_of_pid(pid)->pid_allocated & PIDNS_ADDING))) {
22153fd37226SKirill Tkhai 		retval = -ENOMEM;
22163fd37226SKirill Tkhai 		goto bad_fork_cancel_cgroup;
22173fd37226SKirill Tkhai 	}
22184a2c7a78SOleg Nesterov 
22197673bf55SEric W. Biederman 	/* Let kill terminate clone/fork in the middle */
22207673bf55SEric W. Biederman 	if (fatal_signal_pending(current)) {
22217673bf55SEric W. Biederman 		retval = -EINTR;
22227673bf55SEric W. Biederman 		goto bad_fork_cancel_cgroup;
22237673bf55SEric W. Biederman 	}
22247673bf55SEric W. Biederman 
22256fd2fe49SAl Viro 	/* past the last point of failure */
22266fd2fe49SAl Viro 	if (pidfile)
22276fd2fe49SAl Viro 		fd_install(pidfd, pidfile);
22281da177e4SLinus Torvalds 
22292c470475SEric W. Biederman 	init_task_pid_links(p);
223073b9ebfeSOleg Nesterov 	if (likely(p->pid)) {
22314b9d33e6STejun Heo 		ptrace_init_task(p, (clone_flags & CLONE_PTRACE) || trace);
22321da177e4SLinus Torvalds 
223381907739SOleg Nesterov 		init_task_pid(p, PIDTYPE_PID, pid);
22341da177e4SLinus Torvalds 		if (thread_group_leader(p)) {
22356883f81aSEric W. Biederman 			init_task_pid(p, PIDTYPE_TGID, pid);
223681907739SOleg Nesterov 			init_task_pid(p, PIDTYPE_PGID, task_pgrp(current));
223781907739SOleg Nesterov 			init_task_pid(p, PIDTYPE_SID, task_session(current));
223881907739SOleg Nesterov 
22391c4042c2SEric W. Biederman 			if (is_child_reaper(pid)) {
224017cf22c3SEric W. Biederman 				ns_of_pid(pid)->child_reaper = p;
22411c4042c2SEric W. Biederman 				p->signal->flags |= SIGNAL_UNKILLABLE;
22421c4042c2SEric W. Biederman 			}
2243c3ad2c3bSEric W. Biederman 			p->signal->shared_pending.signal = delayed.signal;
22449c9f4dedSAlan Cox 			p->signal->tty = tty_kref_get(current->signal->tty);
2245749860ceSPavel Tikhomirov 			/*
2246749860ceSPavel Tikhomirov 			 * Inherit has_child_subreaper flag under the same
2247749860ceSPavel Tikhomirov 			 * tasklist_lock with adding child to the process tree
2248749860ceSPavel Tikhomirov 			 * for propagate_has_child_subreaper optimization.
2249749860ceSPavel Tikhomirov 			 */
2250749860ceSPavel Tikhomirov 			p->signal->has_child_subreaper = p->real_parent->signal->has_child_subreaper ||
2251749860ceSPavel Tikhomirov 							 p->real_parent->signal->is_child_subreaper;
22529cd80bbbSOleg Nesterov 			list_add_tail(&p->sibling, &p->real_parent->children);
22535e85d4abSEric W. Biederman 			list_add_tail_rcu(&p->tasks, &init_task.tasks);
22546883f81aSEric W. Biederman 			attach_pid(p, PIDTYPE_TGID);
225581907739SOleg Nesterov 			attach_pid(p, PIDTYPE_PGID);
225681907739SOleg Nesterov 			attach_pid(p, PIDTYPE_SID);
2257909ea964SChristoph Lameter 			__this_cpu_inc(process_counts);
225880628ca0SOleg Nesterov 		} else {
225980628ca0SOleg Nesterov 			current->signal->nr_threads++;
226080628ca0SOleg Nesterov 			atomic_inc(&current->signal->live);
226160d4de3fSElena Reshetova 			refcount_inc(&current->signal->sigcnt);
2262924de3b8SEric W. Biederman 			task_join_group_stop(p);
226380628ca0SOleg Nesterov 			list_add_tail_rcu(&p->thread_group,
226480628ca0SOleg Nesterov 					  &p->group_leader->thread_group);
22650c740d0aSOleg Nesterov 			list_add_tail_rcu(&p->thread_node,
22660c740d0aSOleg Nesterov 					  &p->signal->thread_head);
22671da177e4SLinus Torvalds 		}
226881907739SOleg Nesterov 		attach_pid(p, PIDTYPE_PID);
22691da177e4SLinus Torvalds 		nr_threads++;
227073b9ebfeSOleg Nesterov 	}
22711da177e4SLinus Torvalds 	total_forks++;
2272c3ad2c3bSEric W. Biederman 	hlist_del_init(&delayed.node);
22733f17da69SOleg Nesterov 	spin_unlock(&current->sighand->siglock);
22744af4206bSOleg Nesterov 	syscall_tracepoint_update(p);
22751da177e4SLinus Torvalds 	write_unlock_irq(&tasklist_lock);
22764af4206bSOleg Nesterov 
2277c13cf856SAndrew Morton 	proc_fork_connector(p);
227813685c4aSQais Yousef 	sched_post_fork(p);
2279ef2c41cfSChristian Brauner 	cgroup_post_fork(p, args);
2280cdd6c482SIngo Molnar 	perf_event_fork(p);
228143d2b113SKAMEZAWA Hiroyuki 
228243d2b113SKAMEZAWA Hiroyuki 	trace_task_newtask(p, clone_flags);
22833ab67966SOleg Nesterov 	uprobe_copy_process(p, clone_flags);
228443d2b113SKAMEZAWA Hiroyuki 
22851da177e4SLinus Torvalds 	return p;
22861da177e4SLinus Torvalds 
22877e47682eSAleksa Sarai bad_fork_cancel_cgroup:
22883fd37226SKirill Tkhai 	spin_unlock(&current->sighand->siglock);
22893fd37226SKirill Tkhai 	write_unlock_irq(&tasklist_lock);
2290ef2c41cfSChristian Brauner 	cgroup_cancel_fork(p, args);
2291b3e58382SChristian Brauner bad_fork_put_pidfd:
22926fd2fe49SAl Viro 	if (clone_flags & CLONE_PIDFD) {
22936fd2fe49SAl Viro 		fput(pidfile);
22946fd2fe49SAl Viro 		put_unused_fd(pidfd);
22956fd2fe49SAl Viro 	}
2296425fb2b4SPavel Emelyanov bad_fork_free_pid:
2297425fb2b4SPavel Emelyanov 	if (pid != &init_struct_pid)
2298425fb2b4SPavel Emelyanov 		free_pid(pid);
22990740aa5fSJiri Slaby bad_fork_cleanup_thread:
23000740aa5fSJiri Slaby 	exit_thread(p);
2301fd0928dfSJens Axboe bad_fork_cleanup_io:
2302b69f2292SLouis Rilling 	if (p->io_context)
2303b69f2292SLouis Rilling 		exit_io_context(p);
2304ab516013SSerge E. Hallyn bad_fork_cleanup_namespaces:
2305444f378bSLinus Torvalds 	exit_task_namespaces(p);
23061da177e4SLinus Torvalds bad_fork_cleanup_mm:
2307c3f3ce04SAndrea Arcangeli 	if (p->mm) {
2308c3f3ce04SAndrea Arcangeli 		mm_clear_owner(p->mm, p);
23091da177e4SLinus Torvalds 		mmput(p->mm);
2310c3f3ce04SAndrea Arcangeli 	}
23111da177e4SLinus Torvalds bad_fork_cleanup_signal:
23124ab6c083SOleg Nesterov 	if (!(clone_flags & CLONE_THREAD))
23131c5354deSMike Galbraith 		free_signal_struct(p->signal);
23141da177e4SLinus Torvalds bad_fork_cleanup_sighand:
2315a7e5328aSOleg Nesterov 	__cleanup_sighand(p->sighand);
23161da177e4SLinus Torvalds bad_fork_cleanup_fs:
23171da177e4SLinus Torvalds 	exit_fs(p); /* blocking */
23181da177e4SLinus Torvalds bad_fork_cleanup_files:
23191da177e4SLinus Torvalds 	exit_files(p); /* blocking */
23201da177e4SLinus Torvalds bad_fork_cleanup_semundo:
23211da177e4SLinus Torvalds 	exit_sem(p);
2322e4e55b47STetsuo Handa bad_fork_cleanup_security:
2323e4e55b47STetsuo Handa 	security_task_free(p);
23241da177e4SLinus Torvalds bad_fork_cleanup_audit:
23251da177e4SLinus Torvalds 	audit_free(p);
23266c72e350SPeter Zijlstra bad_fork_cleanup_perf:
2327cdd6c482SIngo Molnar 	perf_event_free_task(p);
23286c72e350SPeter Zijlstra bad_fork_cleanup_policy:
2329b09be676SByungchul Park 	lockdep_free_task(p);
23301da177e4SLinus Torvalds #ifdef CONFIG_NUMA
2331f0be3d32SLee Schermerhorn 	mpol_put(p->mempolicy);
2332e8604cb4SLi Zefan bad_fork_cleanup_threadgroup_lock:
23331da177e4SLinus Torvalds #endif
233435df17c5SShailabh Nagar 	delayacct_tsk_free(p);
23351da177e4SLinus Torvalds bad_fork_cleanup_count:
2336d84f4f99SDavid Howells 	atomic_dec(&p->cred->user->processes);
2337e0e81739SDavid Howells 	exit_creds(p);
23381da177e4SLinus Torvalds bad_fork_free:
2339405c0759SAndy Lutomirski 	p->state = TASK_DEAD;
234068f24b08SAndy Lutomirski 	put_task_stack(p);
2341c3f3ce04SAndrea Arcangeli 	delayed_free_task(p);
2342fe7d37d1SOleg Nesterov fork_out:
2343c3ad2c3bSEric W. Biederman 	spin_lock_irq(&current->sighand->siglock);
2344c3ad2c3bSEric W. Biederman 	hlist_del_init(&delayed.node);
2345c3ad2c3bSEric W. Biederman 	spin_unlock_irq(&current->sighand->siglock);
2346fe7d37d1SOleg Nesterov 	return ERR_PTR(retval);
23471da177e4SLinus Torvalds }
23481da177e4SLinus Torvalds 
23492c470475SEric W. Biederman static inline void init_idle_pids(struct task_struct *idle)
2350f106eee1SOleg Nesterov {
2351f106eee1SOleg Nesterov 	enum pid_type type;
2352f106eee1SOleg Nesterov 
2353f106eee1SOleg Nesterov 	for (type = PIDTYPE_PID; type < PIDTYPE_MAX; ++type) {
23542c470475SEric W. Biederman 		INIT_HLIST_NODE(&idle->pid_links[type]); /* not really needed */
23552c470475SEric W. Biederman 		init_task_pid(idle, type, &init_struct_pid);
2356f106eee1SOleg Nesterov 	}
2357f106eee1SOleg Nesterov }
2358f106eee1SOleg Nesterov 
23590db0628dSPaul Gortmaker struct task_struct *fork_idle(int cpu)
23601da177e4SLinus Torvalds {
236136c8b586SIngo Molnar 	struct task_struct *task;
23627f192e3cSChristian Brauner 	struct kernel_clone_args args = {
23637f192e3cSChristian Brauner 		.flags = CLONE_VM,
23647f192e3cSChristian Brauner 	};
23657f192e3cSChristian Brauner 
23667f192e3cSChristian Brauner 	task = copy_process(&init_struct_pid, 0, cpu_to_node(cpu), &args);
2367f106eee1SOleg Nesterov 	if (!IS_ERR(task)) {
23682c470475SEric W. Biederman 		init_idle_pids(task);
23691da177e4SLinus Torvalds 		init_idle(task, cpu);
2370f106eee1SOleg Nesterov 	}
237173b9ebfeSOleg Nesterov 
23721da177e4SLinus Torvalds 	return task;
23731da177e4SLinus Torvalds }
23741da177e4SLinus Torvalds 
237513585fa0SNadav Amit struct mm_struct *copy_init_mm(void)
237613585fa0SNadav Amit {
237713585fa0SNadav Amit 	return dup_mm(NULL, &init_mm);
237813585fa0SNadav Amit }
237913585fa0SNadav Amit 
23801da177e4SLinus Torvalds /*
23811da177e4SLinus Torvalds  *  Ok, this is the main fork-routine.
23821da177e4SLinus Torvalds  *
23831da177e4SLinus Torvalds  * It copies the process, and if successful kick-starts
23841da177e4SLinus Torvalds  * it and waits for it to finish using the VM if required.
2385a0eb9abdSEugene Syromiatnikov  *
2386a0eb9abdSEugene Syromiatnikov  * args->exit_signal is expected to be checked for sanity by the caller.
23871da177e4SLinus Torvalds  */
23887f192e3cSChristian Brauner long _do_fork(struct kernel_clone_args *args)
23891da177e4SLinus Torvalds {
23907f192e3cSChristian Brauner 	u64 clone_flags = args->flags;
23919f5325aaSMarcos Paulo de Souza 	struct completion vfork;
23929f5325aaSMarcos Paulo de Souza 	struct pid *pid;
23931da177e4SLinus Torvalds 	struct task_struct *p;
23941da177e4SLinus Torvalds 	int trace = 0;
239592476d7fSEric W. Biederman 	long nr;
23961da177e4SLinus Torvalds 
2397bdff746aSAndrew Morton 	/*
23983af8588cSChristian Brauner 	 * For legacy clone() calls, CLONE_PIDFD uses the parent_tid argument
23993af8588cSChristian Brauner 	 * to return the pidfd. Hence, CLONE_PIDFD and CLONE_PARENT_SETTID are
24003af8588cSChristian Brauner 	 * mutually exclusive. With clone3() CLONE_PIDFD has grown a separate
24013af8588cSChristian Brauner 	 * field in struct clone_args and it still doesn't make sense to have
24023af8588cSChristian Brauner 	 * them both point at the same memory location. Performing this check
24033af8588cSChristian Brauner 	 * here has the advantage that we don't need to have a separate helper
24043af8588cSChristian Brauner 	 * to check for legacy clone().
24053af8588cSChristian Brauner 	 */
24063af8588cSChristian Brauner 	if ((args->flags & CLONE_PIDFD) &&
24073af8588cSChristian Brauner 	    (args->flags & CLONE_PARENT_SETTID) &&
24083af8588cSChristian Brauner 	    (args->pidfd == args->parent_tid))
24093af8588cSChristian Brauner 		return -EINVAL;
24103af8588cSChristian Brauner 
24113af8588cSChristian Brauner 	/*
24124b9d33e6STejun Heo 	 * Determine whether and which event to report to ptracer.  When
24134b9d33e6STejun Heo 	 * called from kernel_thread or CLONE_UNTRACED is explicitly
24144b9d33e6STejun Heo 	 * requested, no event is reported; otherwise, report if the event
24154b9d33e6STejun Heo 	 * for the type of forking is enabled.
241609a05394SRoland McGrath 	 */
2417e80d6661SAl Viro 	if (!(clone_flags & CLONE_UNTRACED)) {
24184b9d33e6STejun Heo 		if (clone_flags & CLONE_VFORK)
24194b9d33e6STejun Heo 			trace = PTRACE_EVENT_VFORK;
24207f192e3cSChristian Brauner 		else if (args->exit_signal != SIGCHLD)
24214b9d33e6STejun Heo 			trace = PTRACE_EVENT_CLONE;
24224b9d33e6STejun Heo 		else
24234b9d33e6STejun Heo 			trace = PTRACE_EVENT_FORK;
24244b9d33e6STejun Heo 
24254b9d33e6STejun Heo 		if (likely(!ptrace_event_enabled(current, trace)))
24264b9d33e6STejun Heo 			trace = 0;
24274b9d33e6STejun Heo 	}
24281da177e4SLinus Torvalds 
24297f192e3cSChristian Brauner 	p = copy_process(NULL, trace, NUMA_NO_NODE, args);
243038addce8SEmese Revfy 	add_latent_entropy();
24319f5325aaSMarcos Paulo de Souza 
24329f5325aaSMarcos Paulo de Souza 	if (IS_ERR(p))
24339f5325aaSMarcos Paulo de Souza 		return PTR_ERR(p);
24349f5325aaSMarcos Paulo de Souza 
24351da177e4SLinus Torvalds 	/*
24361da177e4SLinus Torvalds 	 * Do this prior waking up the new thread - the thread pointer
24371da177e4SLinus Torvalds 	 * might get invalid after that point, if the thread exits quickly.
24381da177e4SLinus Torvalds 	 */
24390a16b607SMathieu Desnoyers 	trace_sched_process_fork(current, p);
24400a16b607SMathieu Desnoyers 
24414e52365fSMatthew Dempsky 	pid = get_task_pid(p, PIDTYPE_PID);
24424e52365fSMatthew Dempsky 	nr = pid_vnr(pid);
244330e49c26SPavel Emelyanov 
244430e49c26SPavel Emelyanov 	if (clone_flags & CLONE_PARENT_SETTID)
24457f192e3cSChristian Brauner 		put_user(nr, args->parent_tid);
2446a6f5e063SSukadev Bhattiprolu 
24471da177e4SLinus Torvalds 	if (clone_flags & CLONE_VFORK) {
24481da177e4SLinus Torvalds 		p->vfork_done = &vfork;
24491da177e4SLinus Torvalds 		init_completion(&vfork);
2450d68b46feSOleg Nesterov 		get_task_struct(p);
24511da177e4SLinus Torvalds 	}
24521da177e4SLinus Torvalds 
24533e51e3edSSamir Bellabes 	wake_up_new_task(p);
24541da177e4SLinus Torvalds 
24554b9d33e6STejun Heo 	/* forking complete and child started to run, tell ptracer */
24564b9d33e6STejun Heo 	if (unlikely(trace))
24574e52365fSMatthew Dempsky 		ptrace_event_pid(trace, pid);
245809a05394SRoland McGrath 
24591da177e4SLinus Torvalds 	if (clone_flags & CLONE_VFORK) {
2460d68b46feSOleg Nesterov 		if (!wait_for_vfork_done(p, &vfork))
24614e52365fSMatthew Dempsky 			ptrace_event_pid(PTRACE_EVENT_VFORK_DONE, pid);
24629f59ce5dSChuck Ebbert 	}
24634e52365fSMatthew Dempsky 
24644e52365fSMatthew Dempsky 	put_pid(pid);
246592476d7fSEric W. Biederman 	return nr;
24661da177e4SLinus Torvalds }
24671da177e4SLinus Torvalds 
24682aa3a7f8SAl Viro /*
24692aa3a7f8SAl Viro  * Create a kernel thread.
24702aa3a7f8SAl Viro  */
24712aa3a7f8SAl Viro pid_t kernel_thread(int (*fn)(void *), void *arg, unsigned long flags)
24722aa3a7f8SAl Viro {
24737f192e3cSChristian Brauner 	struct kernel_clone_args args = {
24743f2c788aSChristian Brauner 		.flags		= ((lower_32_bits(flags) | CLONE_VM |
24753f2c788aSChristian Brauner 				    CLONE_UNTRACED) & ~CSIGNAL),
24763f2c788aSChristian Brauner 		.exit_signal	= (lower_32_bits(flags) & CSIGNAL),
24777f192e3cSChristian Brauner 		.stack		= (unsigned long)fn,
24787f192e3cSChristian Brauner 		.stack_size	= (unsigned long)arg,
24797f192e3cSChristian Brauner 	};
24807f192e3cSChristian Brauner 
24817f192e3cSChristian Brauner 	return _do_fork(&args);
24822aa3a7f8SAl Viro }
24832aa3a7f8SAl Viro 
2484d2125043SAl Viro #ifdef __ARCH_WANT_SYS_FORK
2485d2125043SAl Viro SYSCALL_DEFINE0(fork)
2486d2125043SAl Viro {
2487d2125043SAl Viro #ifdef CONFIG_MMU
24887f192e3cSChristian Brauner 	struct kernel_clone_args args = {
24897f192e3cSChristian Brauner 		.exit_signal = SIGCHLD,
24907f192e3cSChristian Brauner 	};
24917f192e3cSChristian Brauner 
24927f192e3cSChristian Brauner 	return _do_fork(&args);
2493d2125043SAl Viro #else
2494d2125043SAl Viro 	/* can not support in nommu mode */
24955d59e182SDaeseok Youn 	return -EINVAL;
2496d2125043SAl Viro #endif
2497d2125043SAl Viro }
2498d2125043SAl Viro #endif
2499d2125043SAl Viro 
2500d2125043SAl Viro #ifdef __ARCH_WANT_SYS_VFORK
2501d2125043SAl Viro SYSCALL_DEFINE0(vfork)
2502d2125043SAl Viro {
25037f192e3cSChristian Brauner 	struct kernel_clone_args args = {
25047f192e3cSChristian Brauner 		.flags		= CLONE_VFORK | CLONE_VM,
25057f192e3cSChristian Brauner 		.exit_signal	= SIGCHLD,
25067f192e3cSChristian Brauner 	};
25077f192e3cSChristian Brauner 
25087f192e3cSChristian Brauner 	return _do_fork(&args);
2509d2125043SAl Viro }
2510d2125043SAl Viro #endif
2511d2125043SAl Viro 
2512d2125043SAl Viro #ifdef __ARCH_WANT_SYS_CLONE
2513d2125043SAl Viro #ifdef CONFIG_CLONE_BACKWARDS
2514d2125043SAl Viro SYSCALL_DEFINE5(clone, unsigned long, clone_flags, unsigned long, newsp,
2515d2125043SAl Viro 		 int __user *, parent_tidptr,
25163033f14aSJosh Triplett 		 unsigned long, tls,
2517d2125043SAl Viro 		 int __user *, child_tidptr)
2518d2125043SAl Viro #elif defined(CONFIG_CLONE_BACKWARDS2)
2519d2125043SAl Viro SYSCALL_DEFINE5(clone, unsigned long, newsp, unsigned long, clone_flags,
2520d2125043SAl Viro 		 int __user *, parent_tidptr,
2521d2125043SAl Viro 		 int __user *, child_tidptr,
25223033f14aSJosh Triplett 		 unsigned long, tls)
2523dfa9771aSMichal Simek #elif defined(CONFIG_CLONE_BACKWARDS3)
2524dfa9771aSMichal Simek SYSCALL_DEFINE6(clone, unsigned long, clone_flags, unsigned long, newsp,
2525dfa9771aSMichal Simek 		int, stack_size,
2526dfa9771aSMichal Simek 		int __user *, parent_tidptr,
2527dfa9771aSMichal Simek 		int __user *, child_tidptr,
25283033f14aSJosh Triplett 		unsigned long, tls)
2529d2125043SAl Viro #else
2530d2125043SAl Viro SYSCALL_DEFINE5(clone, unsigned long, clone_flags, unsigned long, newsp,
2531d2125043SAl Viro 		 int __user *, parent_tidptr,
2532d2125043SAl Viro 		 int __user *, child_tidptr,
25333033f14aSJosh Triplett 		 unsigned long, tls)
2534d2125043SAl Viro #endif
2535d2125043SAl Viro {
25367f192e3cSChristian Brauner 	struct kernel_clone_args args = {
25373f2c788aSChristian Brauner 		.flags		= (lower_32_bits(clone_flags) & ~CSIGNAL),
25387f192e3cSChristian Brauner 		.pidfd		= parent_tidptr,
25397f192e3cSChristian Brauner 		.child_tid	= child_tidptr,
25407f192e3cSChristian Brauner 		.parent_tid	= parent_tidptr,
25413f2c788aSChristian Brauner 		.exit_signal	= (lower_32_bits(clone_flags) & CSIGNAL),
25427f192e3cSChristian Brauner 		.stack		= newsp,
25437f192e3cSChristian Brauner 		.tls		= tls,
25447f192e3cSChristian Brauner 	};
25457f192e3cSChristian Brauner 
25467f192e3cSChristian Brauner 	return _do_fork(&args);
25477f192e3cSChristian Brauner }
2548d68dbb0cSChristian Brauner #endif
25497f192e3cSChristian Brauner 
2550d68dbb0cSChristian Brauner #ifdef __ARCH_WANT_SYS_CLONE3
2551dd499f7aSAmanieu d'Antras 
25527f192e3cSChristian Brauner noinline static int copy_clone_args_from_user(struct kernel_clone_args *kargs,
25537f192e3cSChristian Brauner 					      struct clone_args __user *uargs,
2554f14c234bSAleksa Sarai 					      size_t usize)
25557f192e3cSChristian Brauner {
2556f14c234bSAleksa Sarai 	int err;
25577f192e3cSChristian Brauner 	struct clone_args args;
255849cb2fc4SAdrian Reber 	pid_t *kset_tid = kargs->set_tid;
25597f192e3cSChristian Brauner 
2560a966dcfeSEugene Syromiatnikov 	BUILD_BUG_ON(offsetofend(struct clone_args, tls) !=
2561a966dcfeSEugene Syromiatnikov 		     CLONE_ARGS_SIZE_VER0);
2562a966dcfeSEugene Syromiatnikov 	BUILD_BUG_ON(offsetofend(struct clone_args, set_tid_size) !=
2563a966dcfeSEugene Syromiatnikov 		     CLONE_ARGS_SIZE_VER1);
2564a966dcfeSEugene Syromiatnikov 	BUILD_BUG_ON(offsetofend(struct clone_args, cgroup) !=
2565a966dcfeSEugene Syromiatnikov 		     CLONE_ARGS_SIZE_VER2);
2566a966dcfeSEugene Syromiatnikov 	BUILD_BUG_ON(sizeof(struct clone_args) != CLONE_ARGS_SIZE_VER2);
2567a966dcfeSEugene Syromiatnikov 
2568f14c234bSAleksa Sarai 	if (unlikely(usize > PAGE_SIZE))
25697f192e3cSChristian Brauner 		return -E2BIG;
2570f14c234bSAleksa Sarai 	if (unlikely(usize < CLONE_ARGS_SIZE_VER0))
25717f192e3cSChristian Brauner 		return -EINVAL;
25727f192e3cSChristian Brauner 
2573f14c234bSAleksa Sarai 	err = copy_struct_from_user(&args, sizeof(args), uargs, usize);
2574f14c234bSAleksa Sarai 	if (err)
2575f14c234bSAleksa Sarai 		return err;
25767f192e3cSChristian Brauner 
257749cb2fc4SAdrian Reber 	if (unlikely(args.set_tid_size > MAX_PID_NS_LEVEL))
257849cb2fc4SAdrian Reber 		return -EINVAL;
257949cb2fc4SAdrian Reber 
258049cb2fc4SAdrian Reber 	if (unlikely(!args.set_tid && args.set_tid_size > 0))
258149cb2fc4SAdrian Reber 		return -EINVAL;
258249cb2fc4SAdrian Reber 
258349cb2fc4SAdrian Reber 	if (unlikely(args.set_tid && args.set_tid_size == 0))
258449cb2fc4SAdrian Reber 		return -EINVAL;
258549cb2fc4SAdrian Reber 
2586a0eb9abdSEugene Syromiatnikov 	/*
2587a0eb9abdSEugene Syromiatnikov 	 * Verify that higher 32bits of exit_signal are unset and that
2588a0eb9abdSEugene Syromiatnikov 	 * it is a valid signal
2589a0eb9abdSEugene Syromiatnikov 	 */
2590a0eb9abdSEugene Syromiatnikov 	if (unlikely((args.exit_signal & ~((u64)CSIGNAL)) ||
2591a0eb9abdSEugene Syromiatnikov 		     !valid_signal(args.exit_signal)))
2592a0eb9abdSEugene Syromiatnikov 		return -EINVAL;
2593a0eb9abdSEugene Syromiatnikov 
259462173872SEugene Syromiatnikov 	if ((args.flags & CLONE_INTO_CGROUP) &&
259562173872SEugene Syromiatnikov 	    (args.cgroup > INT_MAX || usize < CLONE_ARGS_SIZE_VER2))
2596ef2c41cfSChristian Brauner 		return -EINVAL;
2597ef2c41cfSChristian Brauner 
25987f192e3cSChristian Brauner 	*kargs = (struct kernel_clone_args){
25997f192e3cSChristian Brauner 		.flags		= args.flags,
26007f192e3cSChristian Brauner 		.pidfd		= u64_to_user_ptr(args.pidfd),
26017f192e3cSChristian Brauner 		.child_tid	= u64_to_user_ptr(args.child_tid),
26027f192e3cSChristian Brauner 		.parent_tid	= u64_to_user_ptr(args.parent_tid),
26037f192e3cSChristian Brauner 		.exit_signal	= args.exit_signal,
26047f192e3cSChristian Brauner 		.stack		= args.stack,
26057f192e3cSChristian Brauner 		.stack_size	= args.stack_size,
26067f192e3cSChristian Brauner 		.tls		= args.tls,
260749cb2fc4SAdrian Reber 		.set_tid_size	= args.set_tid_size,
2608ef2c41cfSChristian Brauner 		.cgroup		= args.cgroup,
26097f192e3cSChristian Brauner 	};
26107f192e3cSChristian Brauner 
261149cb2fc4SAdrian Reber 	if (args.set_tid &&
261249cb2fc4SAdrian Reber 		copy_from_user(kset_tid, u64_to_user_ptr(args.set_tid),
261349cb2fc4SAdrian Reber 			(kargs->set_tid_size * sizeof(pid_t))))
261449cb2fc4SAdrian Reber 		return -EFAULT;
261549cb2fc4SAdrian Reber 
261649cb2fc4SAdrian Reber 	kargs->set_tid = kset_tid;
261749cb2fc4SAdrian Reber 
26187f192e3cSChristian Brauner 	return 0;
26197f192e3cSChristian Brauner }
26207f192e3cSChristian Brauner 
2621fa729c4dSChristian Brauner /**
2622fa729c4dSChristian Brauner  * clone3_stack_valid - check and prepare stack
2623fa729c4dSChristian Brauner  * @kargs: kernel clone args
2624fa729c4dSChristian Brauner  *
2625fa729c4dSChristian Brauner  * Verify that the stack arguments userspace gave us are sane.
2626fa729c4dSChristian Brauner  * In addition, set the stack direction for userspace since it's easy for us to
2627fa729c4dSChristian Brauner  * determine.
2628fa729c4dSChristian Brauner  */
2629fa729c4dSChristian Brauner static inline bool clone3_stack_valid(struct kernel_clone_args *kargs)
2630fa729c4dSChristian Brauner {
2631fa729c4dSChristian Brauner 	if (kargs->stack == 0) {
2632fa729c4dSChristian Brauner 		if (kargs->stack_size > 0)
2633fa729c4dSChristian Brauner 			return false;
2634fa729c4dSChristian Brauner 	} else {
2635fa729c4dSChristian Brauner 		if (kargs->stack_size == 0)
2636fa729c4dSChristian Brauner 			return false;
2637fa729c4dSChristian Brauner 
2638fa729c4dSChristian Brauner 		if (!access_ok((void __user *)kargs->stack, kargs->stack_size))
2639fa729c4dSChristian Brauner 			return false;
2640fa729c4dSChristian Brauner 
2641fa729c4dSChristian Brauner #if !defined(CONFIG_STACK_GROWSUP) && !defined(CONFIG_IA64)
2642fa729c4dSChristian Brauner 		kargs->stack += kargs->stack_size;
2643fa729c4dSChristian Brauner #endif
2644fa729c4dSChristian Brauner 	}
2645fa729c4dSChristian Brauner 
2646fa729c4dSChristian Brauner 	return true;
2647fa729c4dSChristian Brauner }
2648fa729c4dSChristian Brauner 
2649fa729c4dSChristian Brauner static bool clone3_args_valid(struct kernel_clone_args *kargs)
26507f192e3cSChristian Brauner {
2651b612e5dfSChristian Brauner 	/* Verify that no unknown flags are passed along. */
2652ef2c41cfSChristian Brauner 	if (kargs->flags &
2653ef2c41cfSChristian Brauner 	    ~(CLONE_LEGACY_FLAGS | CLONE_CLEAR_SIGHAND | CLONE_INTO_CGROUP))
26547f192e3cSChristian Brauner 		return false;
26557f192e3cSChristian Brauner 
26567f192e3cSChristian Brauner 	/*
26577f192e3cSChristian Brauner 	 * - make the CLONE_DETACHED bit reuseable for clone3
26587f192e3cSChristian Brauner 	 * - make the CSIGNAL bits reuseable for clone3
26597f192e3cSChristian Brauner 	 */
26607f192e3cSChristian Brauner 	if (kargs->flags & (CLONE_DETACHED | CSIGNAL))
26617f192e3cSChristian Brauner 		return false;
26627f192e3cSChristian Brauner 
2663b612e5dfSChristian Brauner 	if ((kargs->flags & (CLONE_SIGHAND | CLONE_CLEAR_SIGHAND)) ==
2664b612e5dfSChristian Brauner 	    (CLONE_SIGHAND | CLONE_CLEAR_SIGHAND))
2665b612e5dfSChristian Brauner 		return false;
2666b612e5dfSChristian Brauner 
26677f192e3cSChristian Brauner 	if ((kargs->flags & (CLONE_THREAD | CLONE_PARENT)) &&
26687f192e3cSChristian Brauner 	    kargs->exit_signal)
26697f192e3cSChristian Brauner 		return false;
26707f192e3cSChristian Brauner 
2671fa729c4dSChristian Brauner 	if (!clone3_stack_valid(kargs))
2672fa729c4dSChristian Brauner 		return false;
2673fa729c4dSChristian Brauner 
26747f192e3cSChristian Brauner 	return true;
26757f192e3cSChristian Brauner }
26767f192e3cSChristian Brauner 
2677501bd016SChristian Brauner /**
2678501bd016SChristian Brauner  * clone3 - create a new process with specific properties
2679501bd016SChristian Brauner  * @uargs: argument structure
2680501bd016SChristian Brauner  * @size:  size of @uargs
2681501bd016SChristian Brauner  *
2682501bd016SChristian Brauner  * clone3() is the extensible successor to clone()/clone2().
2683501bd016SChristian Brauner  * It takes a struct as argument that is versioned by its size.
2684501bd016SChristian Brauner  *
2685501bd016SChristian Brauner  * Return: On success, a positive PID for the child process.
2686501bd016SChristian Brauner  *         On error, a negative errno number.
2687501bd016SChristian Brauner  */
26887f192e3cSChristian Brauner SYSCALL_DEFINE2(clone3, struct clone_args __user *, uargs, size_t, size)
26897f192e3cSChristian Brauner {
26907f192e3cSChristian Brauner 	int err;
26917f192e3cSChristian Brauner 
26927f192e3cSChristian Brauner 	struct kernel_clone_args kargs;
269349cb2fc4SAdrian Reber 	pid_t set_tid[MAX_PID_NS_LEVEL];
269449cb2fc4SAdrian Reber 
269549cb2fc4SAdrian Reber 	kargs.set_tid = set_tid;
26967f192e3cSChristian Brauner 
26977f192e3cSChristian Brauner 	err = copy_clone_args_from_user(&kargs, uargs, size);
26987f192e3cSChristian Brauner 	if (err)
26997f192e3cSChristian Brauner 		return err;
27007f192e3cSChristian Brauner 
27017f192e3cSChristian Brauner 	if (!clone3_args_valid(&kargs))
27027f192e3cSChristian Brauner 		return -EINVAL;
27037f192e3cSChristian Brauner 
27047f192e3cSChristian Brauner 	return _do_fork(&kargs);
2705d2125043SAl Viro }
2706d2125043SAl Viro #endif
2707d2125043SAl Viro 
27080f1b92cbSOleg Nesterov void walk_process_tree(struct task_struct *top, proc_visitor visitor, void *data)
27090f1b92cbSOleg Nesterov {
27100f1b92cbSOleg Nesterov 	struct task_struct *leader, *parent, *child;
27110f1b92cbSOleg Nesterov 	int res;
27120f1b92cbSOleg Nesterov 
27130f1b92cbSOleg Nesterov 	read_lock(&tasklist_lock);
27140f1b92cbSOleg Nesterov 	leader = top = top->group_leader;
27150f1b92cbSOleg Nesterov down:
27160f1b92cbSOleg Nesterov 	for_each_thread(leader, parent) {
27170f1b92cbSOleg Nesterov 		list_for_each_entry(child, &parent->children, sibling) {
27180f1b92cbSOleg Nesterov 			res = visitor(child, data);
27190f1b92cbSOleg Nesterov 			if (res) {
27200f1b92cbSOleg Nesterov 				if (res < 0)
27210f1b92cbSOleg Nesterov 					goto out;
27220f1b92cbSOleg Nesterov 				leader = child;
27230f1b92cbSOleg Nesterov 				goto down;
27240f1b92cbSOleg Nesterov 			}
27250f1b92cbSOleg Nesterov up:
27260f1b92cbSOleg Nesterov 			;
27270f1b92cbSOleg Nesterov 		}
27280f1b92cbSOleg Nesterov 	}
27290f1b92cbSOleg Nesterov 
27300f1b92cbSOleg Nesterov 	if (leader != top) {
27310f1b92cbSOleg Nesterov 		child = leader;
27320f1b92cbSOleg Nesterov 		parent = child->real_parent;
27330f1b92cbSOleg Nesterov 		leader = parent->group_leader;
27340f1b92cbSOleg Nesterov 		goto up;
27350f1b92cbSOleg Nesterov 	}
27360f1b92cbSOleg Nesterov out:
27370f1b92cbSOleg Nesterov 	read_unlock(&tasklist_lock);
27380f1b92cbSOleg Nesterov }
27390f1b92cbSOleg Nesterov 
27405fd63b30SRavikiran G Thirumalai #ifndef ARCH_MIN_MMSTRUCT_ALIGN
27415fd63b30SRavikiran G Thirumalai #define ARCH_MIN_MMSTRUCT_ALIGN 0
27425fd63b30SRavikiran G Thirumalai #endif
27435fd63b30SRavikiran G Thirumalai 
274451cc5068SAlexey Dobriyan static void sighand_ctor(void *data)
2745aa1757f9SOleg Nesterov {
2746aa1757f9SOleg Nesterov 	struct sighand_struct *sighand = data;
2747aa1757f9SOleg Nesterov 
2748aa1757f9SOleg Nesterov 	spin_lock_init(&sighand->siglock);
2749b8fceee1SDavide Libenzi 	init_waitqueue_head(&sighand->signalfd_wqh);
2750fba2afaaSDavide Libenzi }
2751aa1757f9SOleg Nesterov 
27521da177e4SLinus Torvalds void __init proc_caches_init(void)
27531da177e4SLinus Torvalds {
2754c1a2f7f0SRik van Riel 	unsigned int mm_size;
2755c1a2f7f0SRik van Riel 
27561da177e4SLinus Torvalds 	sighand_cachep = kmem_cache_create("sighand_cache",
27571da177e4SLinus Torvalds 			sizeof(struct sighand_struct), 0,
27585f0d5a3aSPaul E. McKenney 			SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_TYPESAFE_BY_RCU|
275975f296d9SLevin, Alexander (Sasha Levin) 			SLAB_ACCOUNT, sighand_ctor);
27601da177e4SLinus Torvalds 	signal_cachep = kmem_cache_create("signal_cache",
27611da177e4SLinus Torvalds 			sizeof(struct signal_struct), 0,
276275f296d9SLevin, Alexander (Sasha Levin) 			SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_ACCOUNT,
27635d097056SVladimir Davydov 			NULL);
27641da177e4SLinus Torvalds 	files_cachep = kmem_cache_create("files_cache",
27651da177e4SLinus Torvalds 			sizeof(struct files_struct), 0,
276675f296d9SLevin, Alexander (Sasha Levin) 			SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_ACCOUNT,
27675d097056SVladimir Davydov 			NULL);
27681da177e4SLinus Torvalds 	fs_cachep = kmem_cache_create("fs_cache",
27691da177e4SLinus Torvalds 			sizeof(struct fs_struct), 0,
277075f296d9SLevin, Alexander (Sasha Levin) 			SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_ACCOUNT,
27715d097056SVladimir Davydov 			NULL);
2772c1a2f7f0SRik van Riel 
27736345d24dSLinus Torvalds 	/*
2774c1a2f7f0SRik van Riel 	 * The mm_cpumask is located at the end of mm_struct, and is
2775c1a2f7f0SRik van Riel 	 * dynamically sized based on the maximum CPU number this system
2776c1a2f7f0SRik van Riel 	 * can have, taking hotplug into account (nr_cpu_ids).
27776345d24dSLinus Torvalds 	 */
2778c1a2f7f0SRik van Riel 	mm_size = sizeof(struct mm_struct) + cpumask_size();
2779c1a2f7f0SRik van Riel 
278007dcd7feSDavid Windsor 	mm_cachep = kmem_cache_create_usercopy("mm_struct",
2781c1a2f7f0SRik van Riel 			mm_size, ARCH_MIN_MMSTRUCT_ALIGN,
278275f296d9SLevin, Alexander (Sasha Levin) 			SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_ACCOUNT,
278307dcd7feSDavid Windsor 			offsetof(struct mm_struct, saved_auxv),
278407dcd7feSDavid Windsor 			sizeof_field(struct mm_struct, saved_auxv),
27855d097056SVladimir Davydov 			NULL);
27865d097056SVladimir Davydov 	vm_area_cachep = KMEM_CACHE(vm_area_struct, SLAB_PANIC|SLAB_ACCOUNT);
27878feae131SDavid Howells 	mmap_init();
278866577193SAl Viro 	nsproxy_cache_init();
27891da177e4SLinus Torvalds }
2790cf2e340fSJANAK DESAI 
2791cf2e340fSJANAK DESAI /*
27929bfb23fcSOleg Nesterov  * Check constraints on flags passed to the unshare system call.
2793cf2e340fSJANAK DESAI  */
27949bfb23fcSOleg Nesterov static int check_unshare_flags(unsigned long unshare_flags)
2795cf2e340fSJANAK DESAI {
27969bfb23fcSOleg Nesterov 	if (unshare_flags & ~(CLONE_THREAD|CLONE_FS|CLONE_NEWNS|CLONE_SIGHAND|
27979bfb23fcSOleg Nesterov 				CLONE_VM|CLONE_FILES|CLONE_SYSVSEM|
279850804fe3SEric W. Biederman 				CLONE_NEWUTS|CLONE_NEWIPC|CLONE_NEWNET|
2799769071acSAndrei Vagin 				CLONE_NEWUSER|CLONE_NEWPID|CLONE_NEWCGROUP|
2800769071acSAndrei Vagin 				CLONE_NEWTIME))
2801cf2e340fSJANAK DESAI 		return -EINVAL;
28029bfb23fcSOleg Nesterov 	/*
280312c641abSEric W. Biederman 	 * Not implemented, but pretend it works if there is nothing
280412c641abSEric W. Biederman 	 * to unshare.  Note that unsharing the address space or the
280512c641abSEric W. Biederman 	 * signal handlers also need to unshare the signal queues (aka
280612c641abSEric W. Biederman 	 * CLONE_THREAD).
28079bfb23fcSOleg Nesterov 	 */
28089bfb23fcSOleg Nesterov 	if (unshare_flags & (CLONE_THREAD | CLONE_SIGHAND | CLONE_VM)) {
280912c641abSEric W. Biederman 		if (!thread_group_empty(current))
281012c641abSEric W. Biederman 			return -EINVAL;
281112c641abSEric W. Biederman 	}
281212c641abSEric W. Biederman 	if (unshare_flags & (CLONE_SIGHAND | CLONE_VM)) {
2813d036bda7SElena Reshetova 		if (refcount_read(&current->sighand->count) > 1)
281412c641abSEric W. Biederman 			return -EINVAL;
281512c641abSEric W. Biederman 	}
281612c641abSEric W. Biederman 	if (unshare_flags & CLONE_VM) {
281712c641abSEric W. Biederman 		if (!current_is_single_threaded())
28189bfb23fcSOleg Nesterov 			return -EINVAL;
28199bfb23fcSOleg Nesterov 	}
2820cf2e340fSJANAK DESAI 
2821cf2e340fSJANAK DESAI 	return 0;
2822cf2e340fSJANAK DESAI }
2823cf2e340fSJANAK DESAI 
2824cf2e340fSJANAK DESAI /*
282599d1419dSJANAK DESAI  * Unshare the filesystem structure if it is being shared
2826cf2e340fSJANAK DESAI  */
2827cf2e340fSJANAK DESAI static int unshare_fs(unsigned long unshare_flags, struct fs_struct **new_fsp)
2828cf2e340fSJANAK DESAI {
2829cf2e340fSJANAK DESAI 	struct fs_struct *fs = current->fs;
2830cf2e340fSJANAK DESAI 
2831498052bbSAl Viro 	if (!(unshare_flags & CLONE_FS) || !fs)
2832498052bbSAl Viro 		return 0;
2833498052bbSAl Viro 
2834498052bbSAl Viro 	/* don't need lock here; in the worst case we'll do useless copy */
2835498052bbSAl Viro 	if (fs->users == 1)
2836498052bbSAl Viro 		return 0;
2837498052bbSAl Viro 
2838498052bbSAl Viro 	*new_fsp = copy_fs_struct(fs);
283999d1419dSJANAK DESAI 	if (!*new_fsp)
284099d1419dSJANAK DESAI 		return -ENOMEM;
2841cf2e340fSJANAK DESAI 
2842cf2e340fSJANAK DESAI 	return 0;
2843cf2e340fSJANAK DESAI }
2844cf2e340fSJANAK DESAI 
2845cf2e340fSJANAK DESAI /*
2846a016f338SJANAK DESAI  * Unshare file descriptor table if it is being shared
2847cf2e340fSJANAK DESAI  */
284860997c3dSChristian Brauner int unshare_fd(unsigned long unshare_flags, unsigned int max_fds,
284960997c3dSChristian Brauner 	       struct files_struct **new_fdp)
2850cf2e340fSJANAK DESAI {
2851cf2e340fSJANAK DESAI 	struct files_struct *fd = current->files;
2852a016f338SJANAK DESAI 	int error = 0;
2853cf2e340fSJANAK DESAI 
2854cf2e340fSJANAK DESAI 	if ((unshare_flags & CLONE_FILES) &&
2855a016f338SJANAK DESAI 	    (fd && atomic_read(&fd->count) > 1)) {
285660997c3dSChristian Brauner 		*new_fdp = dup_fd(fd, max_fds, &error);
2857a016f338SJANAK DESAI 		if (!*new_fdp)
2858a016f338SJANAK DESAI 			return error;
2859a016f338SJANAK DESAI 	}
2860cf2e340fSJANAK DESAI 
2861cf2e340fSJANAK DESAI 	return 0;
2862cf2e340fSJANAK DESAI }
2863cf2e340fSJANAK DESAI 
2864cf2e340fSJANAK DESAI /*
2865cf2e340fSJANAK DESAI  * unshare allows a process to 'unshare' part of the process
2866cf2e340fSJANAK DESAI  * context which was originally shared using clone.  copy_*
2867ff2a9112SChristian Brauner  * functions used by _do_fork() cannot be used here directly
2868cf2e340fSJANAK DESAI  * because they modify an inactive task_struct that is being
2869cf2e340fSJANAK DESAI  * constructed. Here we are modifying the current, active,
2870cf2e340fSJANAK DESAI  * task_struct.
2871cf2e340fSJANAK DESAI  */
28729b32105eSDominik Brodowski int ksys_unshare(unsigned long unshare_flags)
2873cf2e340fSJANAK DESAI {
2874cf2e340fSJANAK DESAI 	struct fs_struct *fs, *new_fs = NULL;
2875cf2e340fSJANAK DESAI 	struct files_struct *fd, *new_fd = NULL;
2876b2e0d987SEric W. Biederman 	struct cred *new_cred = NULL;
2877cf7b708cSPavel Emelyanov 	struct nsproxy *new_nsproxy = NULL;
28789edff4abSManfred Spraul 	int do_sysvsem = 0;
28799bfb23fcSOleg Nesterov 	int err;
2880cf2e340fSJANAK DESAI 
288150804fe3SEric W. Biederman 	/*
2882faf00da5SEric W. Biederman 	 * If unsharing a user namespace must also unshare the thread group
2883faf00da5SEric W. Biederman 	 * and unshare the filesystem root and working directories.
2884b2e0d987SEric W. Biederman 	 */
2885b2e0d987SEric W. Biederman 	if (unshare_flags & CLONE_NEWUSER)
2886e66eded8SEric W. Biederman 		unshare_flags |= CLONE_THREAD | CLONE_FS;
2887b2e0d987SEric W. Biederman 	/*
288850804fe3SEric W. Biederman 	 * If unsharing vm, must also unshare signal handlers.
288950804fe3SEric W. Biederman 	 */
289050804fe3SEric W. Biederman 	if (unshare_flags & CLONE_VM)
289150804fe3SEric W. Biederman 		unshare_flags |= CLONE_SIGHAND;
28926013f67fSManfred Spraul 	/*
289312c641abSEric W. Biederman 	 * If unsharing a signal handlers, must also unshare the signal queues.
289412c641abSEric W. Biederman 	 */
289512c641abSEric W. Biederman 	if (unshare_flags & CLONE_SIGHAND)
289612c641abSEric W. Biederman 		unshare_flags |= CLONE_THREAD;
289712c641abSEric W. Biederman 	/*
28989bfb23fcSOleg Nesterov 	 * If unsharing namespace, must also unshare filesystem information.
28999bfb23fcSOleg Nesterov 	 */
29009bfb23fcSOleg Nesterov 	if (unshare_flags & CLONE_NEWNS)
29019bfb23fcSOleg Nesterov 		unshare_flags |= CLONE_FS;
290250804fe3SEric W. Biederman 
290350804fe3SEric W. Biederman 	err = check_unshare_flags(unshare_flags);
290450804fe3SEric W. Biederman 	if (err)
290550804fe3SEric W. Biederman 		goto bad_unshare_out;
29069bfb23fcSOleg Nesterov 	/*
29076013f67fSManfred Spraul 	 * CLONE_NEWIPC must also detach from the undolist: after switching
29086013f67fSManfred Spraul 	 * to a new ipc namespace, the semaphore arrays from the old
29096013f67fSManfred Spraul 	 * namespace are unreachable.
29106013f67fSManfred Spraul 	 */
29116013f67fSManfred Spraul 	if (unshare_flags & (CLONE_NEWIPC|CLONE_SYSVSEM))
29129edff4abSManfred Spraul 		do_sysvsem = 1;
2913fb0a685cSDaniel Rebelo de Oliveira 	err = unshare_fs(unshare_flags, &new_fs);
2914fb0a685cSDaniel Rebelo de Oliveira 	if (err)
29159bfb23fcSOleg Nesterov 		goto bad_unshare_out;
291660997c3dSChristian Brauner 	err = unshare_fd(unshare_flags, NR_OPEN_MAX, &new_fd);
2917fb0a685cSDaniel Rebelo de Oliveira 	if (err)
29189bfb23fcSOleg Nesterov 		goto bad_unshare_cleanup_fs;
2919b2e0d987SEric W. Biederman 	err = unshare_userns(unshare_flags, &new_cred);
2920fb0a685cSDaniel Rebelo de Oliveira 	if (err)
29219edff4abSManfred Spraul 		goto bad_unshare_cleanup_fd;
2922b2e0d987SEric W. Biederman 	err = unshare_nsproxy_namespaces(unshare_flags, &new_nsproxy,
2923b2e0d987SEric W. Biederman 					 new_cred, new_fs);
2924b2e0d987SEric W. Biederman 	if (err)
2925b2e0d987SEric W. Biederman 		goto bad_unshare_cleanup_cred;
2926cf2e340fSJANAK DESAI 
2927b2e0d987SEric W. Biederman 	if (new_fs || new_fd || do_sysvsem || new_cred || new_nsproxy) {
29289edff4abSManfred Spraul 		if (do_sysvsem) {
29299edff4abSManfred Spraul 			/*
29309edff4abSManfred Spraul 			 * CLONE_SYSVSEM is equivalent to sys_exit().
29319edff4abSManfred Spraul 			 */
29329edff4abSManfred Spraul 			exit_sem(current);
29339edff4abSManfred Spraul 		}
2934ab602f79SJack Miller 		if (unshare_flags & CLONE_NEWIPC) {
2935ab602f79SJack Miller 			/* Orphan segments in old ns (see sem above). */
2936ab602f79SJack Miller 			exit_shm(current);
2937ab602f79SJack Miller 			shm_init_task(current);
2938ab602f79SJack Miller 		}
2939ab516013SSerge E. Hallyn 
29406f977e6bSAlan Cox 		if (new_nsproxy)
2941cf7b708cSPavel Emelyanov 			switch_task_namespaces(current, new_nsproxy);
2942cf2e340fSJANAK DESAI 
2943cf7b708cSPavel Emelyanov 		task_lock(current);
2944cf7b708cSPavel Emelyanov 
2945cf2e340fSJANAK DESAI 		if (new_fs) {
2946cf2e340fSJANAK DESAI 			fs = current->fs;
29472a4419b5SNick Piggin 			spin_lock(&fs->lock);
2948cf2e340fSJANAK DESAI 			current->fs = new_fs;
2949498052bbSAl Viro 			if (--fs->users)
2950498052bbSAl Viro 				new_fs = NULL;
2951498052bbSAl Viro 			else
2952cf2e340fSJANAK DESAI 				new_fs = fs;
29532a4419b5SNick Piggin 			spin_unlock(&fs->lock);
2954cf2e340fSJANAK DESAI 		}
2955cf2e340fSJANAK DESAI 
2956cf2e340fSJANAK DESAI 		if (new_fd) {
2957cf2e340fSJANAK DESAI 			fd = current->files;
2958cf2e340fSJANAK DESAI 			current->files = new_fd;
2959cf2e340fSJANAK DESAI 			new_fd = fd;
2960cf2e340fSJANAK DESAI 		}
2961cf2e340fSJANAK DESAI 
2962cf2e340fSJANAK DESAI 		task_unlock(current);
2963b2e0d987SEric W. Biederman 
2964b2e0d987SEric W. Biederman 		if (new_cred) {
2965b2e0d987SEric W. Biederman 			/* Install the new user namespace */
2966b2e0d987SEric W. Biederman 			commit_creds(new_cred);
2967b2e0d987SEric W. Biederman 			new_cred = NULL;
2968b2e0d987SEric W. Biederman 		}
2969cf2e340fSJANAK DESAI 	}
2970cf2e340fSJANAK DESAI 
2971e4222673SHari Bathini 	perf_event_namespaces(current);
2972e4222673SHari Bathini 
2973b2e0d987SEric W. Biederman bad_unshare_cleanup_cred:
2974b2e0d987SEric W. Biederman 	if (new_cred)
2975b2e0d987SEric W. Biederman 		put_cred(new_cred);
2976cf2e340fSJANAK DESAI bad_unshare_cleanup_fd:
2977cf2e340fSJANAK DESAI 	if (new_fd)
2978cf2e340fSJANAK DESAI 		put_files_struct(new_fd);
2979cf2e340fSJANAK DESAI 
2980cf2e340fSJANAK DESAI bad_unshare_cleanup_fs:
2981cf2e340fSJANAK DESAI 	if (new_fs)
2982498052bbSAl Viro 		free_fs_struct(new_fs);
2983cf2e340fSJANAK DESAI 
2984cf2e340fSJANAK DESAI bad_unshare_out:
2985cf2e340fSJANAK DESAI 	return err;
2986cf2e340fSJANAK DESAI }
29873b125388SAl Viro 
29889b32105eSDominik Brodowski SYSCALL_DEFINE1(unshare, unsigned long, unshare_flags)
29899b32105eSDominik Brodowski {
29909b32105eSDominik Brodowski 	return ksys_unshare(unshare_flags);
29919b32105eSDominik Brodowski }
29929b32105eSDominik Brodowski 
29933b125388SAl Viro /*
29943b125388SAl Viro  *	Helper to unshare the files of the current task.
29953b125388SAl Viro  *	We don't want to expose copy_files internals to
29963b125388SAl Viro  *	the exec layer of the kernel.
29973b125388SAl Viro  */
29983b125388SAl Viro 
29993b125388SAl Viro int unshare_files(struct files_struct **displaced)
30003b125388SAl Viro {
30013b125388SAl Viro 	struct task_struct *task = current;
300250704516SAl Viro 	struct files_struct *copy = NULL;
30033b125388SAl Viro 	int error;
30043b125388SAl Viro 
300560997c3dSChristian Brauner 	error = unshare_fd(CLONE_FILES, NR_OPEN_MAX, &copy);
30063b125388SAl Viro 	if (error || !copy) {
30073b125388SAl Viro 		*displaced = NULL;
30083b125388SAl Viro 		return error;
30093b125388SAl Viro 	}
30103b125388SAl Viro 	*displaced = task->files;
30113b125388SAl Viro 	task_lock(task);
30123b125388SAl Viro 	task->files = copy;
30133b125388SAl Viro 	task_unlock(task);
30143b125388SAl Viro 	return 0;
30153b125388SAl Viro }
301616db3d3fSHeinrich Schuchardt 
301716db3d3fSHeinrich Schuchardt int sysctl_max_threads(struct ctl_table *table, int write,
3018b0daa2c7STobias Klauser 		       void *buffer, size_t *lenp, loff_t *ppos)
301916db3d3fSHeinrich Schuchardt {
302016db3d3fSHeinrich Schuchardt 	struct ctl_table t;
302116db3d3fSHeinrich Schuchardt 	int ret;
302216db3d3fSHeinrich Schuchardt 	int threads = max_threads;
3023b0f53dbcSMichal Hocko 	int min = 1;
302416db3d3fSHeinrich Schuchardt 	int max = MAX_THREADS;
302516db3d3fSHeinrich Schuchardt 
302616db3d3fSHeinrich Schuchardt 	t = *table;
302716db3d3fSHeinrich Schuchardt 	t.data = &threads;
302816db3d3fSHeinrich Schuchardt 	t.extra1 = &min;
302916db3d3fSHeinrich Schuchardt 	t.extra2 = &max;
303016db3d3fSHeinrich Schuchardt 
303116db3d3fSHeinrich Schuchardt 	ret = proc_dointvec_minmax(&t, write, buffer, lenp, ppos);
303216db3d3fSHeinrich Schuchardt 	if (ret || !write)
303316db3d3fSHeinrich Schuchardt 		return ret;
303416db3d3fSHeinrich Schuchardt 
3035b0f53dbcSMichal Hocko 	max_threads = threads;
303616db3d3fSHeinrich Schuchardt 
303716db3d3fSHeinrich Schuchardt 	return 0;
303816db3d3fSHeinrich Schuchardt }
3039