xref: /openbmc/linux/kernel/fork.c (revision 26db62f179d112d345031e14926a4cda9cd40d6e)
11da177e4SLinus Torvalds /*
21da177e4SLinus Torvalds  *  linux/kernel/fork.c
31da177e4SLinus Torvalds  *
41da177e4SLinus Torvalds  *  Copyright (C) 1991, 1992  Linus Torvalds
51da177e4SLinus Torvalds  */
61da177e4SLinus Torvalds 
71da177e4SLinus Torvalds /*
81da177e4SLinus Torvalds  *  'fork.c' contains the help-routines for the 'fork' system call
91da177e4SLinus Torvalds  * (see also entry.S and others).
101da177e4SLinus Torvalds  * Fork is rather simple, once you get the hang of it, but the memory
111da177e4SLinus Torvalds  * management can be a bitch. See 'mm/memory.c': 'copy_page_range()'
121da177e4SLinus Torvalds  */
131da177e4SLinus Torvalds 
141da177e4SLinus Torvalds #include <linux/slab.h>
151da177e4SLinus Torvalds #include <linux/init.h>
161da177e4SLinus Torvalds #include <linux/unistd.h>
171da177e4SLinus Torvalds #include <linux/module.h>
181da177e4SLinus Torvalds #include <linux/vmalloc.h>
191da177e4SLinus Torvalds #include <linux/completion.h>
201da177e4SLinus Torvalds #include <linux/personality.h>
211da177e4SLinus Torvalds #include <linux/mempolicy.h>
221da177e4SLinus Torvalds #include <linux/sem.h>
231da177e4SLinus Torvalds #include <linux/file.h>
249f3acc31SAl Viro #include <linux/fdtable.h>
25da9cbc87SJens Axboe #include <linux/iocontext.h>
261da177e4SLinus Torvalds #include <linux/key.h>
271da177e4SLinus Torvalds #include <linux/binfmts.h>
281da177e4SLinus Torvalds #include <linux/mman.h>
29cddb8a5cSAndrea Arcangeli #include <linux/mmu_notifier.h>
301da177e4SLinus Torvalds #include <linux/fs.h>
31615d6e87SDavidlohr Bueso #include <linux/mm.h>
32615d6e87SDavidlohr Bueso #include <linux/vmacache.h>
33ab516013SSerge E. Hallyn #include <linux/nsproxy.h>
34c59ede7bSRandy.Dunlap #include <linux/capability.h>
351da177e4SLinus Torvalds #include <linux/cpu.h>
36b4f48b63SPaul Menage #include <linux/cgroup.h>
371da177e4SLinus Torvalds #include <linux/security.h>
38a1e78772SMel Gorman #include <linux/hugetlb.h>
39e2cfabdfSWill Drewry #include <linux/seccomp.h>
401da177e4SLinus Torvalds #include <linux/swap.h>
411da177e4SLinus Torvalds #include <linux/syscalls.h>
421da177e4SLinus Torvalds #include <linux/jiffies.h>
431da177e4SLinus Torvalds #include <linux/futex.h>
448141c7f3SLinus Torvalds #include <linux/compat.h>
45207205a2SEric Dumazet #include <linux/kthread.h>
467c3ab738SAndrew Morton #include <linux/task_io_accounting_ops.h>
47ab2af1f5SDipankar Sarma #include <linux/rcupdate.h>
481da177e4SLinus Torvalds #include <linux/ptrace.h>
491da177e4SLinus Torvalds #include <linux/mount.h>
501da177e4SLinus Torvalds #include <linux/audit.h>
5178fb7466SPavel Emelianov #include <linux/memcontrol.h>
52f201ae23SFrederic Weisbecker #include <linux/ftrace.h>
535e2bf014SMike Galbraith #include <linux/proc_fs.h>
541da177e4SLinus Torvalds #include <linux/profile.h>
551da177e4SLinus Torvalds #include <linux/rmap.h>
56f8af4da3SHugh Dickins #include <linux/ksm.h>
571da177e4SLinus Torvalds #include <linux/acct.h>
588f0ab514SJay Lan #include <linux/tsacct_kern.h>
599f46080cSMatt Helsley #include <linux/cn_proc.h>
60ba96a0c8SRafael J. Wysocki #include <linux/freezer.h>
61ca74e92bSShailabh Nagar #include <linux/delayacct.h>
62ad4ecbcbSShailabh Nagar #include <linux/taskstats_kern.h>
630a425405SArjan van de Ven #include <linux/random.h>
64522ed776SMiloslav Trmac #include <linux/tty.h>
65fd0928dfSJens Axboe #include <linux/blkdev.h>
665ad4e53bSAl Viro #include <linux/fs_struct.h>
677c9f8861SEric Sandeen #include <linux/magic.h>
68cdd6c482SIngo Molnar #include <linux/perf_event.h>
6942c4ab41SStanislaw Gruszka #include <linux/posix-timers.h>
708e7cac79SAvi Kivity #include <linux/user-return-notifier.h>
713d5992d2SYing Han #include <linux/oom.h>
72ba76149fSAndrea Arcangeli #include <linux/khugepaged.h>
73d80e731eSOleg Nesterov #include <linux/signalfd.h>
740326f5a9SSrikar Dronamraju #include <linux/uprobes.h>
75a27bb332SKent Overstreet #include <linux/aio.h>
7652f5684cSGideon Israel Dsouza #include <linux/compiler.h>
7716db3d3fSHeinrich Schuchardt #include <linux/sysctl.h>
785c9a8750SDmitry Vyukov #include <linux/kcov.h>
791da177e4SLinus Torvalds 
801da177e4SLinus Torvalds #include <asm/pgtable.h>
811da177e4SLinus Torvalds #include <asm/pgalloc.h>
821da177e4SLinus Torvalds #include <asm/uaccess.h>
831da177e4SLinus Torvalds #include <asm/mmu_context.h>
841da177e4SLinus Torvalds #include <asm/cacheflush.h>
851da177e4SLinus Torvalds #include <asm/tlbflush.h>
861da177e4SLinus Torvalds 
87ad8d75ffSSteven Rostedt #include <trace/events/sched.h>
88ad8d75ffSSteven Rostedt 
8943d2b113SKAMEZAWA Hiroyuki #define CREATE_TRACE_POINTS
9043d2b113SKAMEZAWA Hiroyuki #include <trace/events/task.h>
9143d2b113SKAMEZAWA Hiroyuki 
921da177e4SLinus Torvalds /*
93ac1b398dSHeinrich Schuchardt  * Minimum number of threads to boot the kernel
94ac1b398dSHeinrich Schuchardt  */
95ac1b398dSHeinrich Schuchardt #define MIN_THREADS 20
96ac1b398dSHeinrich Schuchardt 
97ac1b398dSHeinrich Schuchardt /*
98ac1b398dSHeinrich Schuchardt  * Maximum number of threads
99ac1b398dSHeinrich Schuchardt  */
100ac1b398dSHeinrich Schuchardt #define MAX_THREADS FUTEX_TID_MASK
101ac1b398dSHeinrich Schuchardt 
102ac1b398dSHeinrich Schuchardt /*
1031da177e4SLinus Torvalds  * Protected counters by write_lock_irq(&tasklist_lock)
1041da177e4SLinus Torvalds  */
1051da177e4SLinus Torvalds unsigned long total_forks;	/* Handle normal Linux uptimes. */
1061da177e4SLinus Torvalds int nr_threads;			/* The idle threads do not count.. */
1071da177e4SLinus Torvalds 
1081da177e4SLinus Torvalds int max_threads;		/* tunable limit on nr_threads */
1091da177e4SLinus Torvalds 
1101da177e4SLinus Torvalds DEFINE_PER_CPU(unsigned long, process_counts) = 0;
1111da177e4SLinus Torvalds 
1121da177e4SLinus Torvalds __cacheline_aligned DEFINE_RWLOCK(tasklist_lock);  /* outer */
113db1466b3SPaul E. McKenney 
114db1466b3SPaul E. McKenney #ifdef CONFIG_PROVE_RCU
115db1466b3SPaul E. McKenney int lockdep_tasklist_lock_is_held(void)
116db1466b3SPaul E. McKenney {
117db1466b3SPaul E. McKenney 	return lockdep_is_held(&tasklist_lock);
118db1466b3SPaul E. McKenney }
119db1466b3SPaul E. McKenney EXPORT_SYMBOL_GPL(lockdep_tasklist_lock_is_held);
120db1466b3SPaul E. McKenney #endif /* #ifdef CONFIG_PROVE_RCU */
1211da177e4SLinus Torvalds 
1221da177e4SLinus Torvalds int nr_processes(void)
1231da177e4SLinus Torvalds {
1241da177e4SLinus Torvalds 	int cpu;
1251da177e4SLinus Torvalds 	int total = 0;
1261da177e4SLinus Torvalds 
1271d510750SIan Campbell 	for_each_possible_cpu(cpu)
1281da177e4SLinus Torvalds 		total += per_cpu(process_counts, cpu);
1291da177e4SLinus Torvalds 
1301da177e4SLinus Torvalds 	return total;
1311da177e4SLinus Torvalds }
1321da177e4SLinus Torvalds 
133f19b9f74SAkinobu Mita void __weak arch_release_task_struct(struct task_struct *tsk)
134f19b9f74SAkinobu Mita {
135f19b9f74SAkinobu Mita }
136f19b9f74SAkinobu Mita 
137f5e10287SThomas Gleixner #ifndef CONFIG_ARCH_TASK_STRUCT_ALLOCATOR
138e18b890bSChristoph Lameter static struct kmem_cache *task_struct_cachep;
13941101809SThomas Gleixner 
14041101809SThomas Gleixner static inline struct task_struct *alloc_task_struct_node(int node)
14141101809SThomas Gleixner {
14241101809SThomas Gleixner 	return kmem_cache_alloc_node(task_struct_cachep, GFP_KERNEL, node);
14341101809SThomas Gleixner }
14441101809SThomas Gleixner 
14541101809SThomas Gleixner static inline void free_task_struct(struct task_struct *tsk)
14641101809SThomas Gleixner {
14741101809SThomas Gleixner 	kmem_cache_free(task_struct_cachep, tsk);
14841101809SThomas Gleixner }
1491da177e4SLinus Torvalds #endif
1501da177e4SLinus Torvalds 
151b235beeaSLinus Torvalds void __weak arch_release_thread_stack(unsigned long *stack)
152f19b9f74SAkinobu Mita {
153f19b9f74SAkinobu Mita }
154f19b9f74SAkinobu Mita 
155b235beeaSLinus Torvalds #ifndef CONFIG_ARCH_THREAD_STACK_ALLOCATOR
15641101809SThomas Gleixner 
1570d15d74aSThomas Gleixner /*
1580d15d74aSThomas Gleixner  * Allocate pages if THREAD_SIZE is >= PAGE_SIZE, otherwise use a
1590d15d74aSThomas Gleixner  * kmemcache based allocator.
1600d15d74aSThomas Gleixner  */
161ba14a194SAndy Lutomirski # if THREAD_SIZE >= PAGE_SIZE || defined(CONFIG_VMAP_STACK)
162ac496bf4SAndy Lutomirski 
163ac496bf4SAndy Lutomirski #ifdef CONFIG_VMAP_STACK
164ac496bf4SAndy Lutomirski /*
165ac496bf4SAndy Lutomirski  * vmalloc() is a bit slow, and calling vfree() enough times will force a TLB
166ac496bf4SAndy Lutomirski  * flush.  Try to minimize the number of calls by caching stacks.
167ac496bf4SAndy Lutomirski  */
168ac496bf4SAndy Lutomirski #define NR_CACHED_STACKS 2
169ac496bf4SAndy Lutomirski static DEFINE_PER_CPU(struct vm_struct *, cached_stacks[NR_CACHED_STACKS]);
170ac496bf4SAndy Lutomirski #endif
171ac496bf4SAndy Lutomirski 
172ba14a194SAndy Lutomirski static unsigned long *alloc_thread_stack_node(struct task_struct *tsk, int node)
173b69c49b7SFUJITA Tomonori {
174ba14a194SAndy Lutomirski #ifdef CONFIG_VMAP_STACK
175ac496bf4SAndy Lutomirski 	void *stack;
176ac496bf4SAndy Lutomirski 	int i;
177ac496bf4SAndy Lutomirski 
178ac496bf4SAndy Lutomirski 	local_irq_disable();
179ac496bf4SAndy Lutomirski 	for (i = 0; i < NR_CACHED_STACKS; i++) {
180ac496bf4SAndy Lutomirski 		struct vm_struct *s = this_cpu_read(cached_stacks[i]);
181ac496bf4SAndy Lutomirski 
182ac496bf4SAndy Lutomirski 		if (!s)
183ac496bf4SAndy Lutomirski 			continue;
184ac496bf4SAndy Lutomirski 		this_cpu_write(cached_stacks[i], NULL);
185ac496bf4SAndy Lutomirski 
186ac496bf4SAndy Lutomirski 		tsk->stack_vm_area = s;
187ac496bf4SAndy Lutomirski 		local_irq_enable();
188ac496bf4SAndy Lutomirski 		return s->addr;
189ac496bf4SAndy Lutomirski 	}
190ac496bf4SAndy Lutomirski 	local_irq_enable();
191ac496bf4SAndy Lutomirski 
192ac496bf4SAndy Lutomirski 	stack = __vmalloc_node_range(THREAD_SIZE, THREAD_SIZE,
193ba14a194SAndy Lutomirski 				     VMALLOC_START, VMALLOC_END,
194ba14a194SAndy Lutomirski 				     THREADINFO_GFP | __GFP_HIGHMEM,
195ba14a194SAndy Lutomirski 				     PAGE_KERNEL,
196ac496bf4SAndy Lutomirski 				     0, node, __builtin_return_address(0));
197ba14a194SAndy Lutomirski 
198ba14a194SAndy Lutomirski 	/*
199ba14a194SAndy Lutomirski 	 * We can't call find_vm_area() in interrupt context, and
200ba14a194SAndy Lutomirski 	 * free_thread_stack() can be called in interrupt context,
201ba14a194SAndy Lutomirski 	 * so cache the vm_struct.
202ba14a194SAndy Lutomirski 	 */
203ba14a194SAndy Lutomirski 	if (stack)
204ba14a194SAndy Lutomirski 		tsk->stack_vm_area = find_vm_area(stack);
205ba14a194SAndy Lutomirski 	return stack;
206ba14a194SAndy Lutomirski #else
2074949148aSVladimir Davydov 	struct page *page = alloc_pages_node(node, THREADINFO_GFP,
2082889f608SThomas Gleixner 					     THREAD_SIZE_ORDER);
209b6a84016SEric Dumazet 
210b6a84016SEric Dumazet 	return page ? page_address(page) : NULL;
211ba14a194SAndy Lutomirski #endif
212b69c49b7SFUJITA Tomonori }
213b69c49b7SFUJITA Tomonori 
214ba14a194SAndy Lutomirski static inline void free_thread_stack(struct task_struct *tsk)
215b69c49b7SFUJITA Tomonori {
216ac496bf4SAndy Lutomirski #ifdef CONFIG_VMAP_STACK
217ac496bf4SAndy Lutomirski 	if (task_stack_vm_area(tsk)) {
218ac496bf4SAndy Lutomirski 		unsigned long flags;
219ac496bf4SAndy Lutomirski 		int i;
220ac496bf4SAndy Lutomirski 
221ac496bf4SAndy Lutomirski 		local_irq_save(flags);
222ac496bf4SAndy Lutomirski 		for (i = 0; i < NR_CACHED_STACKS; i++) {
223ac496bf4SAndy Lutomirski 			if (this_cpu_read(cached_stacks[i]))
224ac496bf4SAndy Lutomirski 				continue;
225ac496bf4SAndy Lutomirski 
226ac496bf4SAndy Lutomirski 			this_cpu_write(cached_stacks[i], tsk->stack_vm_area);
227ac496bf4SAndy Lutomirski 			local_irq_restore(flags);
228ac496bf4SAndy Lutomirski 			return;
229ac496bf4SAndy Lutomirski 		}
230ac496bf4SAndy Lutomirski 		local_irq_restore(flags);
231ac496bf4SAndy Lutomirski 
232ba14a194SAndy Lutomirski 		vfree(tsk->stack);
233ac496bf4SAndy Lutomirski 		return;
234ac496bf4SAndy Lutomirski 	}
235ac496bf4SAndy Lutomirski #endif
236ac496bf4SAndy Lutomirski 
237ba14a194SAndy Lutomirski 	__free_pages(virt_to_page(tsk->stack), THREAD_SIZE_ORDER);
238b69c49b7SFUJITA Tomonori }
2390d15d74aSThomas Gleixner # else
240b235beeaSLinus Torvalds static struct kmem_cache *thread_stack_cache;
2410d15d74aSThomas Gleixner 
2429521d399SMichael Ellerman static unsigned long *alloc_thread_stack_node(struct task_struct *tsk,
2430d15d74aSThomas Gleixner 						  int node)
2440d15d74aSThomas Gleixner {
245b235beeaSLinus Torvalds 	return kmem_cache_alloc_node(thread_stack_cache, THREADINFO_GFP, node);
2460d15d74aSThomas Gleixner }
2470d15d74aSThomas Gleixner 
248ba14a194SAndy Lutomirski static void free_thread_stack(struct task_struct *tsk)
2490d15d74aSThomas Gleixner {
250ba14a194SAndy Lutomirski 	kmem_cache_free(thread_stack_cache, tsk->stack);
2510d15d74aSThomas Gleixner }
2520d15d74aSThomas Gleixner 
253b235beeaSLinus Torvalds void thread_stack_cache_init(void)
2540d15d74aSThomas Gleixner {
255b235beeaSLinus Torvalds 	thread_stack_cache = kmem_cache_create("thread_stack", THREAD_SIZE,
2560d15d74aSThomas Gleixner 					      THREAD_SIZE, 0, NULL);
257b235beeaSLinus Torvalds 	BUG_ON(thread_stack_cache == NULL);
2580d15d74aSThomas Gleixner }
2590d15d74aSThomas Gleixner # endif
260b69c49b7SFUJITA Tomonori #endif
261b69c49b7SFUJITA Tomonori 
2621da177e4SLinus Torvalds /* SLAB cache for signal_struct structures (tsk->signal) */
263e18b890bSChristoph Lameter static struct kmem_cache *signal_cachep;
2641da177e4SLinus Torvalds 
2651da177e4SLinus Torvalds /* SLAB cache for sighand_struct structures (tsk->sighand) */
266e18b890bSChristoph Lameter struct kmem_cache *sighand_cachep;
2671da177e4SLinus Torvalds 
2681da177e4SLinus Torvalds /* SLAB cache for files_struct structures (tsk->files) */
269e18b890bSChristoph Lameter struct kmem_cache *files_cachep;
2701da177e4SLinus Torvalds 
2711da177e4SLinus Torvalds /* SLAB cache for fs_struct structures (tsk->fs) */
272e18b890bSChristoph Lameter struct kmem_cache *fs_cachep;
2731da177e4SLinus Torvalds 
2741da177e4SLinus Torvalds /* SLAB cache for vm_area_struct structures */
275e18b890bSChristoph Lameter struct kmem_cache *vm_area_cachep;
2761da177e4SLinus Torvalds 
2771da177e4SLinus Torvalds /* SLAB cache for mm_struct structures (tsk->mm) */
278e18b890bSChristoph Lameter static struct kmem_cache *mm_cachep;
2791da177e4SLinus Torvalds 
280ba14a194SAndy Lutomirski static void account_kernel_stack(struct task_struct *tsk, int account)
281c6a7f572SKOSAKI Motohiro {
282ba14a194SAndy Lutomirski 	void *stack = task_stack_page(tsk);
283ba14a194SAndy Lutomirski 	struct vm_struct *vm = task_stack_vm_area(tsk);
284ba14a194SAndy Lutomirski 
285ba14a194SAndy Lutomirski 	BUILD_BUG_ON(IS_ENABLED(CONFIG_VMAP_STACK) && PAGE_SIZE % 1024 != 0);
286ba14a194SAndy Lutomirski 
287ba14a194SAndy Lutomirski 	if (vm) {
288ba14a194SAndy Lutomirski 		int i;
289ba14a194SAndy Lutomirski 
290ba14a194SAndy Lutomirski 		BUG_ON(vm->nr_pages != THREAD_SIZE / PAGE_SIZE);
291ba14a194SAndy Lutomirski 
292ba14a194SAndy Lutomirski 		for (i = 0; i < THREAD_SIZE / PAGE_SIZE; i++) {
293ba14a194SAndy Lutomirski 			mod_zone_page_state(page_zone(vm->pages[i]),
294ba14a194SAndy Lutomirski 					    NR_KERNEL_STACK_KB,
295ba14a194SAndy Lutomirski 					    PAGE_SIZE / 1024 * account);
296ba14a194SAndy Lutomirski 		}
297ba14a194SAndy Lutomirski 
298ba14a194SAndy Lutomirski 		/* All stack pages belong to the same memcg. */
299ba14a194SAndy Lutomirski 		memcg_kmem_update_page_stat(vm->pages[0], MEMCG_KERNEL_STACK_KB,
300ba14a194SAndy Lutomirski 					    account * (THREAD_SIZE / 1024));
301ba14a194SAndy Lutomirski 	} else {
302ba14a194SAndy Lutomirski 		/*
303ba14a194SAndy Lutomirski 		 * All stack pages are in the same zone and belong to the
304ba14a194SAndy Lutomirski 		 * same memcg.
305ba14a194SAndy Lutomirski 		 */
306efdc9490SAndy Lutomirski 		struct page *first_page = virt_to_page(stack);
307c6a7f572SKOSAKI Motohiro 
308efdc9490SAndy Lutomirski 		mod_zone_page_state(page_zone(first_page), NR_KERNEL_STACK_KB,
309d30dd8beSAndy Lutomirski 				    THREAD_SIZE / 1024 * account);
310efdc9490SAndy Lutomirski 
311ba14a194SAndy Lutomirski 		memcg_kmem_update_page_stat(first_page, MEMCG_KERNEL_STACK_KB,
312efdc9490SAndy Lutomirski 					    account * (THREAD_SIZE / 1024));
313c6a7f572SKOSAKI Motohiro 	}
314ba14a194SAndy Lutomirski }
315c6a7f572SKOSAKI Motohiro 
31668f24b08SAndy Lutomirski static void release_task_stack(struct task_struct *tsk)
3171da177e4SLinus Torvalds {
318ba14a194SAndy Lutomirski 	account_kernel_stack(tsk, -1);
319b235beeaSLinus Torvalds 	arch_release_thread_stack(tsk->stack);
320ba14a194SAndy Lutomirski 	free_thread_stack(tsk);
32168f24b08SAndy Lutomirski 	tsk->stack = NULL;
32268f24b08SAndy Lutomirski #ifdef CONFIG_VMAP_STACK
32368f24b08SAndy Lutomirski 	tsk->stack_vm_area = NULL;
32468f24b08SAndy Lutomirski #endif
32568f24b08SAndy Lutomirski }
32668f24b08SAndy Lutomirski 
32768f24b08SAndy Lutomirski #ifdef CONFIG_THREAD_INFO_IN_TASK
32868f24b08SAndy Lutomirski void put_task_stack(struct task_struct *tsk)
32968f24b08SAndy Lutomirski {
33068f24b08SAndy Lutomirski 	if (atomic_dec_and_test(&tsk->stack_refcount))
33168f24b08SAndy Lutomirski 		release_task_stack(tsk);
33268f24b08SAndy Lutomirski }
33368f24b08SAndy Lutomirski #endif
33468f24b08SAndy Lutomirski 
33568f24b08SAndy Lutomirski void free_task(struct task_struct *tsk)
33668f24b08SAndy Lutomirski {
33768f24b08SAndy Lutomirski #ifndef CONFIG_THREAD_INFO_IN_TASK
33868f24b08SAndy Lutomirski 	/*
33968f24b08SAndy Lutomirski 	 * The task is finally done with both the stack and thread_info,
34068f24b08SAndy Lutomirski 	 * so free both.
34168f24b08SAndy Lutomirski 	 */
34268f24b08SAndy Lutomirski 	release_task_stack(tsk);
34368f24b08SAndy Lutomirski #else
34468f24b08SAndy Lutomirski 	/*
34568f24b08SAndy Lutomirski 	 * If the task had a separate stack allocation, it should be gone
34668f24b08SAndy Lutomirski 	 * by now.
34768f24b08SAndy Lutomirski 	 */
34868f24b08SAndy Lutomirski 	WARN_ON_ONCE(atomic_read(&tsk->stack_refcount) != 0);
34968f24b08SAndy Lutomirski #endif
35023f78d4aSIngo Molnar 	rt_mutex_debug_task_free(tsk);
351fb52607aSFrederic Weisbecker 	ftrace_graph_exit_task(tsk);
352e2cfabdfSWill Drewry 	put_seccomp_filter(tsk);
353f19b9f74SAkinobu Mita 	arch_release_task_struct(tsk);
3541da177e4SLinus Torvalds 	free_task_struct(tsk);
3551da177e4SLinus Torvalds }
3561da177e4SLinus Torvalds EXPORT_SYMBOL(free_task);
3571da177e4SLinus Torvalds 
358ea6d290cSOleg Nesterov static inline void free_signal_struct(struct signal_struct *sig)
359ea6d290cSOleg Nesterov {
36097101eb4SOleg Nesterov 	taskstats_tgid_free(sig);
3611c5354deSMike Galbraith 	sched_autogroup_exit(sig);
362*26db62f1SMichal Hocko 	if (sig->oom_mm)
363*26db62f1SMichal Hocko 		mmdrop(sig->oom_mm);
364ea6d290cSOleg Nesterov 	kmem_cache_free(signal_cachep, sig);
365ea6d290cSOleg Nesterov }
366ea6d290cSOleg Nesterov 
367ea6d290cSOleg Nesterov static inline void put_signal_struct(struct signal_struct *sig)
368ea6d290cSOleg Nesterov {
3691c5354deSMike Galbraith 	if (atomic_dec_and_test(&sig->sigcnt))
370ea6d290cSOleg Nesterov 		free_signal_struct(sig);
371ea6d290cSOleg Nesterov }
372ea6d290cSOleg Nesterov 
373158d9ebdSAndrew Morton void __put_task_struct(struct task_struct *tsk)
3741da177e4SLinus Torvalds {
375270f722dSEugene Teo 	WARN_ON(!tsk->exit_state);
3761da177e4SLinus Torvalds 	WARN_ON(atomic_read(&tsk->usage));
3771da177e4SLinus Torvalds 	WARN_ON(tsk == current);
3781da177e4SLinus Torvalds 
3792e91fa7fSTejun Heo 	cgroup_free(tsk);
380156654f4SMike Galbraith 	task_numa_free(tsk);
3811a2a4d06SKees Cook 	security_task_free(tsk);
382e0e81739SDavid Howells 	exit_creds(tsk);
38335df17c5SShailabh Nagar 	delayacct_tsk_free(tsk);
384ea6d290cSOleg Nesterov 	put_signal_struct(tsk->signal);
3851da177e4SLinus Torvalds 
3861da177e4SLinus Torvalds 	if (!profile_handoff_task(tsk))
3871da177e4SLinus Torvalds 		free_task(tsk);
3881da177e4SLinus Torvalds }
38977c100c8SRik van Riel EXPORT_SYMBOL_GPL(__put_task_struct);
3901da177e4SLinus Torvalds 
3916c0a9fa6SThomas Gleixner void __init __weak arch_task_cache_init(void) { }
39261c4628bSSuresh Siddha 
393ff691f6eSHeinrich Schuchardt /*
394ff691f6eSHeinrich Schuchardt  * set_max_threads
395ff691f6eSHeinrich Schuchardt  */
39616db3d3fSHeinrich Schuchardt static void set_max_threads(unsigned int max_threads_suggested)
397ff691f6eSHeinrich Schuchardt {
398ac1b398dSHeinrich Schuchardt 	u64 threads;
399ff691f6eSHeinrich Schuchardt 
400ff691f6eSHeinrich Schuchardt 	/*
401ac1b398dSHeinrich Schuchardt 	 * The number of threads shall be limited such that the thread
402ac1b398dSHeinrich Schuchardt 	 * structures may only consume a small part of the available memory.
403ff691f6eSHeinrich Schuchardt 	 */
404ac1b398dSHeinrich Schuchardt 	if (fls64(totalram_pages) + fls64(PAGE_SIZE) > 64)
405ac1b398dSHeinrich Schuchardt 		threads = MAX_THREADS;
406ac1b398dSHeinrich Schuchardt 	else
407ac1b398dSHeinrich Schuchardt 		threads = div64_u64((u64) totalram_pages * (u64) PAGE_SIZE,
408ac1b398dSHeinrich Schuchardt 				    (u64) THREAD_SIZE * 8UL);
409ac1b398dSHeinrich Schuchardt 
41016db3d3fSHeinrich Schuchardt 	if (threads > max_threads_suggested)
41116db3d3fSHeinrich Schuchardt 		threads = max_threads_suggested;
41216db3d3fSHeinrich Schuchardt 
413ac1b398dSHeinrich Schuchardt 	max_threads = clamp_t(u64, threads, MIN_THREADS, MAX_THREADS);
414ff691f6eSHeinrich Schuchardt }
415ff691f6eSHeinrich Schuchardt 
4165aaeb5c0SIngo Molnar #ifdef CONFIG_ARCH_WANTS_DYNAMIC_TASK_STRUCT
4175aaeb5c0SIngo Molnar /* Initialized by the architecture: */
4185aaeb5c0SIngo Molnar int arch_task_struct_size __read_mostly;
4195aaeb5c0SIngo Molnar #endif
4200c8c0f03SDave Hansen 
421ff691f6eSHeinrich Schuchardt void __init fork_init(void)
4221da177e4SLinus Torvalds {
42325f9c081SEric W. Biederman 	int i;
424f5e10287SThomas Gleixner #ifndef CONFIG_ARCH_TASK_STRUCT_ALLOCATOR
4251da177e4SLinus Torvalds #ifndef ARCH_MIN_TASKALIGN
4261da177e4SLinus Torvalds #define ARCH_MIN_TASKALIGN	L1_CACHE_BYTES
4271da177e4SLinus Torvalds #endif
4281da177e4SLinus Torvalds 	/* create a slab on which task_structs can be allocated */
4295d097056SVladimir Davydov 	task_struct_cachep = kmem_cache_create("task_struct",
4305d097056SVladimir Davydov 			arch_task_struct_size, ARCH_MIN_TASKALIGN,
4315d097056SVladimir Davydov 			SLAB_PANIC|SLAB_NOTRACK|SLAB_ACCOUNT, NULL);
4321da177e4SLinus Torvalds #endif
4331da177e4SLinus Torvalds 
43461c4628bSSuresh Siddha 	/* do the arch specific task caches init */
43561c4628bSSuresh Siddha 	arch_task_cache_init();
43661c4628bSSuresh Siddha 
43716db3d3fSHeinrich Schuchardt 	set_max_threads(MAX_THREADS);
4381da177e4SLinus Torvalds 
4391da177e4SLinus Torvalds 	init_task.signal->rlim[RLIMIT_NPROC].rlim_cur = max_threads/2;
4401da177e4SLinus Torvalds 	init_task.signal->rlim[RLIMIT_NPROC].rlim_max = max_threads/2;
4411da177e4SLinus Torvalds 	init_task.signal->rlim[RLIMIT_SIGPENDING] =
4421da177e4SLinus Torvalds 		init_task.signal->rlim[RLIMIT_NPROC];
443b376c3e1SEric W. Biederman 
44425f9c081SEric W. Biederman 	for (i = 0; i < UCOUNT_COUNTS; i++) {
44525f9c081SEric W. Biederman 		init_user_ns.ucount_max[i] = max_threads/2;
44625f9c081SEric W. Biederman 	}
4471da177e4SLinus Torvalds }
4481da177e4SLinus Torvalds 
44952f5684cSGideon Israel Dsouza int __weak arch_dup_task_struct(struct task_struct *dst,
45061c4628bSSuresh Siddha 					       struct task_struct *src)
45161c4628bSSuresh Siddha {
45261c4628bSSuresh Siddha 	*dst = *src;
45361c4628bSSuresh Siddha 	return 0;
45461c4628bSSuresh Siddha }
45561c4628bSSuresh Siddha 
456d4311ff1SAaron Tomlin void set_task_stack_end_magic(struct task_struct *tsk)
457d4311ff1SAaron Tomlin {
458d4311ff1SAaron Tomlin 	unsigned long *stackend;
459d4311ff1SAaron Tomlin 
460d4311ff1SAaron Tomlin 	stackend = end_of_stack(tsk);
461d4311ff1SAaron Tomlin 	*stackend = STACK_END_MAGIC;	/* for overflow detection */
462d4311ff1SAaron Tomlin }
463d4311ff1SAaron Tomlin 
464725fc629SAndi Kleen static struct task_struct *dup_task_struct(struct task_struct *orig, int node)
4651da177e4SLinus Torvalds {
4661da177e4SLinus Torvalds 	struct task_struct *tsk;
467b235beeaSLinus Torvalds 	unsigned long *stack;
468ba14a194SAndy Lutomirski 	struct vm_struct *stack_vm_area;
4693e26c149SPeter Zijlstra 	int err;
4701da177e4SLinus Torvalds 
471725fc629SAndi Kleen 	if (node == NUMA_NO_NODE)
472725fc629SAndi Kleen 		node = tsk_fork_get_node(orig);
473504f52b5SEric Dumazet 	tsk = alloc_task_struct_node(node);
4741da177e4SLinus Torvalds 	if (!tsk)
4751da177e4SLinus Torvalds 		return NULL;
4761da177e4SLinus Torvalds 
477b235beeaSLinus Torvalds 	stack = alloc_thread_stack_node(tsk, node);
478b235beeaSLinus Torvalds 	if (!stack)
479f19b9f74SAkinobu Mita 		goto free_tsk;
4801da177e4SLinus Torvalds 
481ba14a194SAndy Lutomirski 	stack_vm_area = task_stack_vm_area(tsk);
482ba14a194SAndy Lutomirski 
48361c4628bSSuresh Siddha 	err = arch_dup_task_struct(tsk, orig);
484ba14a194SAndy Lutomirski 
485ba14a194SAndy Lutomirski 	/*
486ba14a194SAndy Lutomirski 	 * arch_dup_task_struct() clobbers the stack-related fields.  Make
487ba14a194SAndy Lutomirski 	 * sure they're properly initialized before using any stack-related
488ba14a194SAndy Lutomirski 	 * functions again.
489ba14a194SAndy Lutomirski 	 */
490ba14a194SAndy Lutomirski 	tsk->stack = stack;
491ba14a194SAndy Lutomirski #ifdef CONFIG_VMAP_STACK
492ba14a194SAndy Lutomirski 	tsk->stack_vm_area = stack_vm_area;
493ba14a194SAndy Lutomirski #endif
49468f24b08SAndy Lutomirski #ifdef CONFIG_THREAD_INFO_IN_TASK
49568f24b08SAndy Lutomirski 	atomic_set(&tsk->stack_refcount, 1);
49668f24b08SAndy Lutomirski #endif
497ba14a194SAndy Lutomirski 
49861c4628bSSuresh Siddha 	if (err)
499b235beeaSLinus Torvalds 		goto free_stack;
50061c4628bSSuresh Siddha 
501dbd95212SKees Cook #ifdef CONFIG_SECCOMP
502dbd95212SKees Cook 	/*
503dbd95212SKees Cook 	 * We must handle setting up seccomp filters once we're under
504dbd95212SKees Cook 	 * the sighand lock in case orig has changed between now and
505dbd95212SKees Cook 	 * then. Until then, filter must be NULL to avoid messing up
506dbd95212SKees Cook 	 * the usage counts on the error path calling free_task.
507dbd95212SKees Cook 	 */
508dbd95212SKees Cook 	tsk->seccomp.filter = NULL;
509dbd95212SKees Cook #endif
51087bec58aSAndrew Morton 
51187bec58aSAndrew Morton 	setup_thread_stack(tsk, orig);
5128e7cac79SAvi Kivity 	clear_user_return_notifier(tsk);
513f26f9affSMike Galbraith 	clear_tsk_need_resched(tsk);
514d4311ff1SAaron Tomlin 	set_task_stack_end_magic(tsk);
5151da177e4SLinus Torvalds 
5160a425405SArjan van de Ven #ifdef CONFIG_CC_STACKPROTECTOR
5170a425405SArjan van de Ven 	tsk->stack_canary = get_random_int();
5180a425405SArjan van de Ven #endif
5190a425405SArjan van de Ven 
520fb0a685cSDaniel Rebelo de Oliveira 	/*
521fb0a685cSDaniel Rebelo de Oliveira 	 * One for us, one for whoever does the "release_task()" (usually
522fb0a685cSDaniel Rebelo de Oliveira 	 * parent)
523fb0a685cSDaniel Rebelo de Oliveira 	 */
5241da177e4SLinus Torvalds 	atomic_set(&tsk->usage, 2);
5256c5c9341SAlexey Dobriyan #ifdef CONFIG_BLK_DEV_IO_TRACE
5262056a782SJens Axboe 	tsk->btrace_seq = 0;
5276c5c9341SAlexey Dobriyan #endif
528a0aa7f68SJens Axboe 	tsk->splice_pipe = NULL;
5295640f768SEric Dumazet 	tsk->task_frag.page = NULL;
530093e5840SSebastian Andrzej Siewior 	tsk->wake_q.next = NULL;
531c6a7f572SKOSAKI Motohiro 
532ba14a194SAndy Lutomirski 	account_kernel_stack(tsk, 1);
533c6a7f572SKOSAKI Motohiro 
5345c9a8750SDmitry Vyukov 	kcov_task_init(tsk);
5355c9a8750SDmitry Vyukov 
5361da177e4SLinus Torvalds 	return tsk;
53761c4628bSSuresh Siddha 
538b235beeaSLinus Torvalds free_stack:
539ba14a194SAndy Lutomirski 	free_thread_stack(tsk);
540f19b9f74SAkinobu Mita free_tsk:
54161c4628bSSuresh Siddha 	free_task_struct(tsk);
54261c4628bSSuresh Siddha 	return NULL;
5431da177e4SLinus Torvalds }
5441da177e4SLinus Torvalds 
5451da177e4SLinus Torvalds #ifdef CONFIG_MMU
546a39bc516SAlexey Dobriyan static int dup_mmap(struct mm_struct *mm, struct mm_struct *oldmm)
5471da177e4SLinus Torvalds {
548297c5eeeSLinus Torvalds 	struct vm_area_struct *mpnt, *tmp, *prev, **pprev;
5491da177e4SLinus Torvalds 	struct rb_node **rb_link, *rb_parent;
5501da177e4SLinus Torvalds 	int retval;
5511da177e4SLinus Torvalds 	unsigned long charge;
5521da177e4SLinus Torvalds 
55332cdba1eSOleg Nesterov 	uprobe_start_dup_mmap();
5547c051267SMichal Hocko 	if (down_write_killable(&oldmm->mmap_sem)) {
5557c051267SMichal Hocko 		retval = -EINTR;
5567c051267SMichal Hocko 		goto fail_uprobe_end;
5577c051267SMichal Hocko 	}
558ec8c0446SRalf Baechle 	flush_cache_dup_mm(oldmm);
559f8ac4ec9SOleg Nesterov 	uprobe_dup_mmap(oldmm, mm);
560ad339451SIngo Molnar 	/*
561ad339451SIngo Molnar 	 * Not linked in yet - no deadlock potential:
562ad339451SIngo Molnar 	 */
563ad339451SIngo Molnar 	down_write_nested(&mm->mmap_sem, SINGLE_DEPTH_NESTING);
5647ee78232SHugh Dickins 
56590f31d0eSKonstantin Khlebnikov 	/* No ordering required: file already has been exposed. */
56690f31d0eSKonstantin Khlebnikov 	RCU_INIT_POINTER(mm->exe_file, get_mm_exe_file(oldmm));
56790f31d0eSKonstantin Khlebnikov 
5684f7d4614SVladimir Davydov 	mm->total_vm = oldmm->total_vm;
56984638335SKonstantin Khlebnikov 	mm->data_vm = oldmm->data_vm;
5704f7d4614SVladimir Davydov 	mm->exec_vm = oldmm->exec_vm;
5714f7d4614SVladimir Davydov 	mm->stack_vm = oldmm->stack_vm;
5724f7d4614SVladimir Davydov 
5731da177e4SLinus Torvalds 	rb_link = &mm->mm_rb.rb_node;
5741da177e4SLinus Torvalds 	rb_parent = NULL;
5751da177e4SLinus Torvalds 	pprev = &mm->mmap;
576f8af4da3SHugh Dickins 	retval = ksm_fork(mm, oldmm);
577f8af4da3SHugh Dickins 	if (retval)
578f8af4da3SHugh Dickins 		goto out;
579ba76149fSAndrea Arcangeli 	retval = khugepaged_fork(mm, oldmm);
580ba76149fSAndrea Arcangeli 	if (retval)
581ba76149fSAndrea Arcangeli 		goto out;
5821da177e4SLinus Torvalds 
583297c5eeeSLinus Torvalds 	prev = NULL;
584fd3e42fcSHugh Dickins 	for (mpnt = oldmm->mmap; mpnt; mpnt = mpnt->vm_next) {
5851da177e4SLinus Torvalds 		struct file *file;
5861da177e4SLinus Torvalds 
5871da177e4SLinus Torvalds 		if (mpnt->vm_flags & VM_DONTCOPY) {
58884638335SKonstantin Khlebnikov 			vm_stat_account(mm, mpnt->vm_flags, -vma_pages(mpnt));
5891da177e4SLinus Torvalds 			continue;
5901da177e4SLinus Torvalds 		}
5911da177e4SLinus Torvalds 		charge = 0;
5921da177e4SLinus Torvalds 		if (mpnt->vm_flags & VM_ACCOUNT) {
593b2412b7fSHuang Shijie 			unsigned long len = vma_pages(mpnt);
594b2412b7fSHuang Shijie 
595191c5424SAl Viro 			if (security_vm_enough_memory_mm(oldmm, len)) /* sic */
5961da177e4SLinus Torvalds 				goto fail_nomem;
5971da177e4SLinus Torvalds 			charge = len;
5981da177e4SLinus Torvalds 		}
599e94b1766SChristoph Lameter 		tmp = kmem_cache_alloc(vm_area_cachep, GFP_KERNEL);
6001da177e4SLinus Torvalds 		if (!tmp)
6011da177e4SLinus Torvalds 			goto fail_nomem;
6021da177e4SLinus Torvalds 		*tmp = *mpnt;
6035beb4930SRik van Riel 		INIT_LIST_HEAD(&tmp->anon_vma_chain);
604ef0855d3SOleg Nesterov 		retval = vma_dup_policy(mpnt, tmp);
605ef0855d3SOleg Nesterov 		if (retval)
6061da177e4SLinus Torvalds 			goto fail_nomem_policy;
607a247c3a9SAndrea Arcangeli 		tmp->vm_mm = mm;
6085beb4930SRik van Riel 		if (anon_vma_fork(tmp, mpnt))
6095beb4930SRik van Riel 			goto fail_nomem_anon_vma_fork;
610de60f5f1SEric B Munson 		tmp->vm_flags &=
611de60f5f1SEric B Munson 			~(VM_LOCKED|VM_LOCKONFAULT|VM_UFFD_MISSING|VM_UFFD_WP);
612297c5eeeSLinus Torvalds 		tmp->vm_next = tmp->vm_prev = NULL;
613745f234bSAndrea Arcangeli 		tmp->vm_userfaultfd_ctx = NULL_VM_UFFD_CTX;
6141da177e4SLinus Torvalds 		file = tmp->vm_file;
6151da177e4SLinus Torvalds 		if (file) {
616496ad9aaSAl Viro 			struct inode *inode = file_inode(file);
617b88ed205SHugh Dickins 			struct address_space *mapping = file->f_mapping;
618b88ed205SHugh Dickins 
6191da177e4SLinus Torvalds 			get_file(file);
6201da177e4SLinus Torvalds 			if (tmp->vm_flags & VM_DENYWRITE)
6211da177e4SLinus Torvalds 				atomic_dec(&inode->i_writecount);
62283cde9e8SDavidlohr Bueso 			i_mmap_lock_write(mapping);
623b88ed205SHugh Dickins 			if (tmp->vm_flags & VM_SHARED)
6244bb5f5d9SDavid Herrmann 				atomic_inc(&mapping->i_mmap_writable);
625b88ed205SHugh Dickins 			flush_dcache_mmap_lock(mapping);
626b88ed205SHugh Dickins 			/* insert tmp into the share list, just after mpnt */
6279826a516SMichel Lespinasse 			vma_interval_tree_insert_after(tmp, mpnt,
6289826a516SMichel Lespinasse 					&mapping->i_mmap);
629b88ed205SHugh Dickins 			flush_dcache_mmap_unlock(mapping);
63083cde9e8SDavidlohr Bueso 			i_mmap_unlock_write(mapping);
6311da177e4SLinus Torvalds 		}
6321da177e4SLinus Torvalds 
6331da177e4SLinus Torvalds 		/*
634a1e78772SMel Gorman 		 * Clear hugetlb-related page reserves for children. This only
635a1e78772SMel Gorman 		 * affects MAP_PRIVATE mappings. Faults generated by the child
636a1e78772SMel Gorman 		 * are not guaranteed to succeed, even if read-only
637a1e78772SMel Gorman 		 */
638a1e78772SMel Gorman 		if (is_vm_hugetlb_page(tmp))
639a1e78772SMel Gorman 			reset_vma_resv_huge_pages(tmp);
640a1e78772SMel Gorman 
641a1e78772SMel Gorman 		/*
6427ee78232SHugh Dickins 		 * Link in the new vma and copy the page table entries.
6431da177e4SLinus Torvalds 		 */
6441da177e4SLinus Torvalds 		*pprev = tmp;
6451da177e4SLinus Torvalds 		pprev = &tmp->vm_next;
646297c5eeeSLinus Torvalds 		tmp->vm_prev = prev;
647297c5eeeSLinus Torvalds 		prev = tmp;
6481da177e4SLinus Torvalds 
6491da177e4SLinus Torvalds 		__vma_link_rb(mm, tmp, rb_link, rb_parent);
6501da177e4SLinus Torvalds 		rb_link = &tmp->vm_rb.rb_right;
6511da177e4SLinus Torvalds 		rb_parent = &tmp->vm_rb;
6521da177e4SLinus Torvalds 
6531da177e4SLinus Torvalds 		mm->map_count++;
6540b0db14cSHugh Dickins 		retval = copy_page_range(mm, oldmm, mpnt);
6551da177e4SLinus Torvalds 
6561da177e4SLinus Torvalds 		if (tmp->vm_ops && tmp->vm_ops->open)
6571da177e4SLinus Torvalds 			tmp->vm_ops->open(tmp);
6581da177e4SLinus Torvalds 
6591da177e4SLinus Torvalds 		if (retval)
6601da177e4SLinus Torvalds 			goto out;
6611da177e4SLinus Torvalds 	}
662d6dd61c8SJeremy Fitzhardinge 	/* a new mm has just been created */
663d6dd61c8SJeremy Fitzhardinge 	arch_dup_mmap(oldmm, mm);
6641da177e4SLinus Torvalds 	retval = 0;
6651da177e4SLinus Torvalds out:
6667ee78232SHugh Dickins 	up_write(&mm->mmap_sem);
667fd3e42fcSHugh Dickins 	flush_tlb_mm(oldmm);
6681da177e4SLinus Torvalds 	up_write(&oldmm->mmap_sem);
6697c051267SMichal Hocko fail_uprobe_end:
67032cdba1eSOleg Nesterov 	uprobe_end_dup_mmap();
6711da177e4SLinus Torvalds 	return retval;
6725beb4930SRik van Riel fail_nomem_anon_vma_fork:
673ef0855d3SOleg Nesterov 	mpol_put(vma_policy(tmp));
6741da177e4SLinus Torvalds fail_nomem_policy:
6751da177e4SLinus Torvalds 	kmem_cache_free(vm_area_cachep, tmp);
6761da177e4SLinus Torvalds fail_nomem:
6771da177e4SLinus Torvalds 	retval = -ENOMEM;
6781da177e4SLinus Torvalds 	vm_unacct_memory(charge);
6791da177e4SLinus Torvalds 	goto out;
6801da177e4SLinus Torvalds }
6811da177e4SLinus Torvalds 
6821da177e4SLinus Torvalds static inline int mm_alloc_pgd(struct mm_struct *mm)
6831da177e4SLinus Torvalds {
6841da177e4SLinus Torvalds 	mm->pgd = pgd_alloc(mm);
6851da177e4SLinus Torvalds 	if (unlikely(!mm->pgd))
6861da177e4SLinus Torvalds 		return -ENOMEM;
6871da177e4SLinus Torvalds 	return 0;
6881da177e4SLinus Torvalds }
6891da177e4SLinus Torvalds 
6901da177e4SLinus Torvalds static inline void mm_free_pgd(struct mm_struct *mm)
6911da177e4SLinus Torvalds {
6925e541973SBenjamin Herrenschmidt 	pgd_free(mm, mm->pgd);
6931da177e4SLinus Torvalds }
6941da177e4SLinus Torvalds #else
69590f31d0eSKonstantin Khlebnikov static int dup_mmap(struct mm_struct *mm, struct mm_struct *oldmm)
69690f31d0eSKonstantin Khlebnikov {
69790f31d0eSKonstantin Khlebnikov 	down_write(&oldmm->mmap_sem);
69890f31d0eSKonstantin Khlebnikov 	RCU_INIT_POINTER(mm->exe_file, get_mm_exe_file(oldmm));
69990f31d0eSKonstantin Khlebnikov 	up_write(&oldmm->mmap_sem);
70090f31d0eSKonstantin Khlebnikov 	return 0;
70190f31d0eSKonstantin Khlebnikov }
7021da177e4SLinus Torvalds #define mm_alloc_pgd(mm)	(0)
7031da177e4SLinus Torvalds #define mm_free_pgd(mm)
7041da177e4SLinus Torvalds #endif /* CONFIG_MMU */
7051da177e4SLinus Torvalds 
7061da177e4SLinus Torvalds __cacheline_aligned_in_smp DEFINE_SPINLOCK(mmlist_lock);
7071da177e4SLinus Torvalds 
708e94b1766SChristoph Lameter #define allocate_mm()	(kmem_cache_alloc(mm_cachep, GFP_KERNEL))
7091da177e4SLinus Torvalds #define free_mm(mm)	(kmem_cache_free(mm_cachep, (mm)))
7101da177e4SLinus Torvalds 
7114cb0e11bSHidehiro Kawai static unsigned long default_dump_filter = MMF_DUMP_FILTER_DEFAULT;
7124cb0e11bSHidehiro Kawai 
7134cb0e11bSHidehiro Kawai static int __init coredump_filter_setup(char *s)
7144cb0e11bSHidehiro Kawai {
7154cb0e11bSHidehiro Kawai 	default_dump_filter =
7164cb0e11bSHidehiro Kawai 		(simple_strtoul(s, NULL, 0) << MMF_DUMP_FILTER_SHIFT) &
7174cb0e11bSHidehiro Kawai 		MMF_DUMP_FILTER_MASK;
7184cb0e11bSHidehiro Kawai 	return 1;
7194cb0e11bSHidehiro Kawai }
7204cb0e11bSHidehiro Kawai 
7214cb0e11bSHidehiro Kawai __setup("coredump_filter=", coredump_filter_setup);
7224cb0e11bSHidehiro Kawai 
7231da177e4SLinus Torvalds #include <linux/init_task.h>
7241da177e4SLinus Torvalds 
725858f0993SAlexey Dobriyan static void mm_init_aio(struct mm_struct *mm)
726858f0993SAlexey Dobriyan {
727858f0993SAlexey Dobriyan #ifdef CONFIG_AIO
728858f0993SAlexey Dobriyan 	spin_lock_init(&mm->ioctx_lock);
729db446a08SBenjamin LaHaise 	mm->ioctx_table = NULL;
730858f0993SAlexey Dobriyan #endif
731858f0993SAlexey Dobriyan }
732858f0993SAlexey Dobriyan 
73333144e84SVladimir Davydov static void mm_init_owner(struct mm_struct *mm, struct task_struct *p)
73433144e84SVladimir Davydov {
73533144e84SVladimir Davydov #ifdef CONFIG_MEMCG
73633144e84SVladimir Davydov 	mm->owner = p;
73733144e84SVladimir Davydov #endif
73833144e84SVladimir Davydov }
73933144e84SVladimir Davydov 
74078fb7466SPavel Emelianov static struct mm_struct *mm_init(struct mm_struct *mm, struct task_struct *p)
7411da177e4SLinus Torvalds {
74241f727fdSVladimir Davydov 	mm->mmap = NULL;
74341f727fdSVladimir Davydov 	mm->mm_rb = RB_ROOT;
74441f727fdSVladimir Davydov 	mm->vmacache_seqnum = 0;
7451da177e4SLinus Torvalds 	atomic_set(&mm->mm_users, 1);
7461da177e4SLinus Torvalds 	atomic_set(&mm->mm_count, 1);
7471da177e4SLinus Torvalds 	init_rwsem(&mm->mmap_sem);
7481da177e4SLinus Torvalds 	INIT_LIST_HEAD(&mm->mmlist);
749999d9fc1SOleg Nesterov 	mm->core_state = NULL;
750e1f56c89SKirill A. Shutemov 	atomic_long_set(&mm->nr_ptes, 0);
7512d2f5119SKirill A. Shutemov 	mm_nr_pmds_init(mm);
75241f727fdSVladimir Davydov 	mm->map_count = 0;
75341f727fdSVladimir Davydov 	mm->locked_vm = 0;
754ce65cefaSVladimir Davydov 	mm->pinned_vm = 0;
755d559db08SKAMEZAWA Hiroyuki 	memset(&mm->rss_stat, 0, sizeof(mm->rss_stat));
7561da177e4SLinus Torvalds 	spin_lock_init(&mm->page_table_lock);
75741f727fdSVladimir Davydov 	mm_init_cpumask(mm);
758858f0993SAlexey Dobriyan 	mm_init_aio(mm);
759cf475ad2SBalbir Singh 	mm_init_owner(mm, p);
76041f727fdSVladimir Davydov 	mmu_notifier_mm_init(mm);
76120841405SRik van Riel 	clear_tlb_flush_pending(mm);
76241f727fdSVladimir Davydov #if defined(CONFIG_TRANSPARENT_HUGEPAGE) && !USE_SPLIT_PMD_PTLOCKS
76341f727fdSVladimir Davydov 	mm->pmd_huge_pte = NULL;
76441f727fdSVladimir Davydov #endif
7651da177e4SLinus Torvalds 
766a0715cc2SAlex Thorlton 	if (current->mm) {
767a0715cc2SAlex Thorlton 		mm->flags = current->mm->flags & MMF_INIT_MASK;
768a0715cc2SAlex Thorlton 		mm->def_flags = current->mm->def_flags & VM_INIT_DEF_MASK;
769a0715cc2SAlex Thorlton 	} else {
770a0715cc2SAlex Thorlton 		mm->flags = default_dump_filter;
7711da177e4SLinus Torvalds 		mm->def_flags = 0;
772a0715cc2SAlex Thorlton 	}
773a0715cc2SAlex Thorlton 
77441f727fdSVladimir Davydov 	if (mm_alloc_pgd(mm))
77541f727fdSVladimir Davydov 		goto fail_nopgd;
77678fb7466SPavel Emelianov 
77741f727fdSVladimir Davydov 	if (init_new_context(p, mm))
77841f727fdSVladimir Davydov 		goto fail_nocontext;
77941f727fdSVladimir Davydov 
78041f727fdSVladimir Davydov 	return mm;
78141f727fdSVladimir Davydov 
78241f727fdSVladimir Davydov fail_nocontext:
78341f727fdSVladimir Davydov 	mm_free_pgd(mm);
78441f727fdSVladimir Davydov fail_nopgd:
7851da177e4SLinus Torvalds 	free_mm(mm);
7861da177e4SLinus Torvalds 	return NULL;
7871da177e4SLinus Torvalds }
7881da177e4SLinus Torvalds 
789c3f0327fSKonstantin Khlebnikov static void check_mm(struct mm_struct *mm)
790c3f0327fSKonstantin Khlebnikov {
791c3f0327fSKonstantin Khlebnikov 	int i;
792c3f0327fSKonstantin Khlebnikov 
793c3f0327fSKonstantin Khlebnikov 	for (i = 0; i < NR_MM_COUNTERS; i++) {
794c3f0327fSKonstantin Khlebnikov 		long x = atomic_long_read(&mm->rss_stat.count[i]);
795c3f0327fSKonstantin Khlebnikov 
796c3f0327fSKonstantin Khlebnikov 		if (unlikely(x))
797c3f0327fSKonstantin Khlebnikov 			printk(KERN_ALERT "BUG: Bad rss-counter state "
798c3f0327fSKonstantin Khlebnikov 					  "mm:%p idx:%d val:%ld\n", mm, i, x);
799c3f0327fSKonstantin Khlebnikov 	}
800b30fe6c7SKirill A. Shutemov 
801b30fe6c7SKirill A. Shutemov 	if (atomic_long_read(&mm->nr_ptes))
802b30fe6c7SKirill A. Shutemov 		pr_alert("BUG: non-zero nr_ptes on freeing mm: %ld\n",
803b30fe6c7SKirill A. Shutemov 				atomic_long_read(&mm->nr_ptes));
804b30fe6c7SKirill A. Shutemov 	if (mm_nr_pmds(mm))
805b30fe6c7SKirill A. Shutemov 		pr_alert("BUG: non-zero nr_pmds on freeing mm: %ld\n",
806b30fe6c7SKirill A. Shutemov 				mm_nr_pmds(mm));
807b30fe6c7SKirill A. Shutemov 
808e009bb30SKirill A. Shutemov #if defined(CONFIG_TRANSPARENT_HUGEPAGE) && !USE_SPLIT_PMD_PTLOCKS
80996dad67fSSasha Levin 	VM_BUG_ON_MM(mm->pmd_huge_pte, mm);
810c3f0327fSKonstantin Khlebnikov #endif
811c3f0327fSKonstantin Khlebnikov }
812c3f0327fSKonstantin Khlebnikov 
8131da177e4SLinus Torvalds /*
8141da177e4SLinus Torvalds  * Allocate and initialize an mm_struct.
8151da177e4SLinus Torvalds  */
8161da177e4SLinus Torvalds struct mm_struct *mm_alloc(void)
8171da177e4SLinus Torvalds {
8181da177e4SLinus Torvalds 	struct mm_struct *mm;
8191da177e4SLinus Torvalds 
8201da177e4SLinus Torvalds 	mm = allocate_mm();
821de03c72cSKOSAKI Motohiro 	if (!mm)
822de03c72cSKOSAKI Motohiro 		return NULL;
823de03c72cSKOSAKI Motohiro 
8241da177e4SLinus Torvalds 	memset(mm, 0, sizeof(*mm));
8256345d24dSLinus Torvalds 	return mm_init(mm, current);
8261da177e4SLinus Torvalds }
8271da177e4SLinus Torvalds 
8281da177e4SLinus Torvalds /*
8291da177e4SLinus Torvalds  * Called when the last reference to the mm
8301da177e4SLinus Torvalds  * is dropped: either by a lazy thread or by
8311da177e4SLinus Torvalds  * mmput. Free the page directory and the mm.
8321da177e4SLinus Torvalds  */
8337ad5b3a5SHarvey Harrison void __mmdrop(struct mm_struct *mm)
8341da177e4SLinus Torvalds {
8351da177e4SLinus Torvalds 	BUG_ON(mm == &init_mm);
8361da177e4SLinus Torvalds 	mm_free_pgd(mm);
8371da177e4SLinus Torvalds 	destroy_context(mm);
838cddb8a5cSAndrea Arcangeli 	mmu_notifier_mm_destroy(mm);
839c3f0327fSKonstantin Khlebnikov 	check_mm(mm);
8401da177e4SLinus Torvalds 	free_mm(mm);
8411da177e4SLinus Torvalds }
8426d4e4c4fSAvi Kivity EXPORT_SYMBOL_GPL(__mmdrop);
8431da177e4SLinus Torvalds 
844ec8d7c14SMichal Hocko static inline void __mmput(struct mm_struct *mm)
8451da177e4SLinus Torvalds {
846ec8d7c14SMichal Hocko 	VM_BUG_ON(atomic_read(&mm->mm_users));
8470ae26f1bSAndrew Morton 
848d4b3b638SSrikar Dronamraju 	uprobe_clear_state(mm);
8491da177e4SLinus Torvalds 	exit_aio(mm);
8501c2fb7a4SAndrea Arcangeli 	ksm_exit(mm);
851ba76149fSAndrea Arcangeli 	khugepaged_exit(mm); /* must run before exit_mmap */
8521da177e4SLinus Torvalds 	exit_mmap(mm);
853925d1c40SMatt Helsley 	set_mm_exe_file(mm, NULL);
8541da177e4SLinus Torvalds 	if (!list_empty(&mm->mmlist)) {
8551da177e4SLinus Torvalds 		spin_lock(&mmlist_lock);
8561da177e4SLinus Torvalds 		list_del(&mm->mmlist);
8571da177e4SLinus Torvalds 		spin_unlock(&mmlist_lock);
8581da177e4SLinus Torvalds 	}
859801460d0SHiroshi Shimamoto 	if (mm->binfmt)
860801460d0SHiroshi Shimamoto 		module_put(mm->binfmt->module);
8611da177e4SLinus Torvalds 	mmdrop(mm);
8621da177e4SLinus Torvalds }
863ec8d7c14SMichal Hocko 
864ec8d7c14SMichal Hocko /*
865ec8d7c14SMichal Hocko  * Decrement the use count and release all resources for an mm.
866ec8d7c14SMichal Hocko  */
867ec8d7c14SMichal Hocko void mmput(struct mm_struct *mm)
868ec8d7c14SMichal Hocko {
869ec8d7c14SMichal Hocko 	might_sleep();
870ec8d7c14SMichal Hocko 
871ec8d7c14SMichal Hocko 	if (atomic_dec_and_test(&mm->mm_users))
872ec8d7c14SMichal Hocko 		__mmput(mm);
8731da177e4SLinus Torvalds }
8741da177e4SLinus Torvalds EXPORT_SYMBOL_GPL(mmput);
8751da177e4SLinus Torvalds 
8767ef949d7SMichal Hocko #ifdef CONFIG_MMU
877ec8d7c14SMichal Hocko static void mmput_async_fn(struct work_struct *work)
878ec8d7c14SMichal Hocko {
879ec8d7c14SMichal Hocko 	struct mm_struct *mm = container_of(work, struct mm_struct, async_put_work);
880ec8d7c14SMichal Hocko 	__mmput(mm);
881ec8d7c14SMichal Hocko }
882ec8d7c14SMichal Hocko 
883ec8d7c14SMichal Hocko void mmput_async(struct mm_struct *mm)
884ec8d7c14SMichal Hocko {
885ec8d7c14SMichal Hocko 	if (atomic_dec_and_test(&mm->mm_users)) {
886ec8d7c14SMichal Hocko 		INIT_WORK(&mm->async_put_work, mmput_async_fn);
887ec8d7c14SMichal Hocko 		schedule_work(&mm->async_put_work);
888ec8d7c14SMichal Hocko 	}
889ec8d7c14SMichal Hocko }
8907ef949d7SMichal Hocko #endif
891ec8d7c14SMichal Hocko 
89290f31d0eSKonstantin Khlebnikov /**
89390f31d0eSKonstantin Khlebnikov  * set_mm_exe_file - change a reference to the mm's executable file
89490f31d0eSKonstantin Khlebnikov  *
89590f31d0eSKonstantin Khlebnikov  * This changes mm's executable file (shown as symlink /proc/[pid]/exe).
89690f31d0eSKonstantin Khlebnikov  *
8976e399cd1SDavidlohr Bueso  * Main users are mmput() and sys_execve(). Callers prevent concurrent
8986e399cd1SDavidlohr Bueso  * invocations: in mmput() nobody alive left, in execve task is single
8996e399cd1SDavidlohr Bueso  * threaded. sys_prctl(PR_SET_MM_MAP/EXE_FILE) also needs to set the
9006e399cd1SDavidlohr Bueso  * mm->exe_file, but does so without using set_mm_exe_file() in order
9016e399cd1SDavidlohr Bueso  * to do avoid the need for any locks.
90290f31d0eSKonstantin Khlebnikov  */
90338646013SJiri Slaby void set_mm_exe_file(struct mm_struct *mm, struct file *new_exe_file)
90438646013SJiri Slaby {
9056e399cd1SDavidlohr Bueso 	struct file *old_exe_file;
9066e399cd1SDavidlohr Bueso 
9076e399cd1SDavidlohr Bueso 	/*
9086e399cd1SDavidlohr Bueso 	 * It is safe to dereference the exe_file without RCU as
9096e399cd1SDavidlohr Bueso 	 * this function is only called if nobody else can access
9106e399cd1SDavidlohr Bueso 	 * this mm -- see comment above for justification.
9116e399cd1SDavidlohr Bueso 	 */
9126e399cd1SDavidlohr Bueso 	old_exe_file = rcu_dereference_raw(mm->exe_file);
91390f31d0eSKonstantin Khlebnikov 
91438646013SJiri Slaby 	if (new_exe_file)
91538646013SJiri Slaby 		get_file(new_exe_file);
91690f31d0eSKonstantin Khlebnikov 	rcu_assign_pointer(mm->exe_file, new_exe_file);
91790f31d0eSKonstantin Khlebnikov 	if (old_exe_file)
91890f31d0eSKonstantin Khlebnikov 		fput(old_exe_file);
91938646013SJiri Slaby }
92038646013SJiri Slaby 
92190f31d0eSKonstantin Khlebnikov /**
92290f31d0eSKonstantin Khlebnikov  * get_mm_exe_file - acquire a reference to the mm's executable file
92390f31d0eSKonstantin Khlebnikov  *
92490f31d0eSKonstantin Khlebnikov  * Returns %NULL if mm has no associated executable file.
92590f31d0eSKonstantin Khlebnikov  * User must release file via fput().
92690f31d0eSKonstantin Khlebnikov  */
92738646013SJiri Slaby struct file *get_mm_exe_file(struct mm_struct *mm)
92838646013SJiri Slaby {
92938646013SJiri Slaby 	struct file *exe_file;
93038646013SJiri Slaby 
93190f31d0eSKonstantin Khlebnikov 	rcu_read_lock();
93290f31d0eSKonstantin Khlebnikov 	exe_file = rcu_dereference(mm->exe_file);
93390f31d0eSKonstantin Khlebnikov 	if (exe_file && !get_file_rcu(exe_file))
93490f31d0eSKonstantin Khlebnikov 		exe_file = NULL;
93590f31d0eSKonstantin Khlebnikov 	rcu_read_unlock();
93638646013SJiri Slaby 	return exe_file;
93738646013SJiri Slaby }
93811163348SDavidlohr Bueso EXPORT_SYMBOL(get_mm_exe_file);
93938646013SJiri Slaby 
9401da177e4SLinus Torvalds /**
941cd81a917SMateusz Guzik  * get_task_exe_file - acquire a reference to the task's executable file
942cd81a917SMateusz Guzik  *
943cd81a917SMateusz Guzik  * Returns %NULL if task's mm (if any) has no associated executable file or
944cd81a917SMateusz Guzik  * this is a kernel thread with borrowed mm (see the comment above get_task_mm).
945cd81a917SMateusz Guzik  * User must release file via fput().
946cd81a917SMateusz Guzik  */
947cd81a917SMateusz Guzik struct file *get_task_exe_file(struct task_struct *task)
948cd81a917SMateusz Guzik {
949cd81a917SMateusz Guzik 	struct file *exe_file = NULL;
950cd81a917SMateusz Guzik 	struct mm_struct *mm;
951cd81a917SMateusz Guzik 
952cd81a917SMateusz Guzik 	task_lock(task);
953cd81a917SMateusz Guzik 	mm = task->mm;
954cd81a917SMateusz Guzik 	if (mm) {
955cd81a917SMateusz Guzik 		if (!(task->flags & PF_KTHREAD))
956cd81a917SMateusz Guzik 			exe_file = get_mm_exe_file(mm);
957cd81a917SMateusz Guzik 	}
958cd81a917SMateusz Guzik 	task_unlock(task);
959cd81a917SMateusz Guzik 	return exe_file;
960cd81a917SMateusz Guzik }
961cd81a917SMateusz Guzik EXPORT_SYMBOL(get_task_exe_file);
962cd81a917SMateusz Guzik 
963cd81a917SMateusz Guzik /**
9641da177e4SLinus Torvalds  * get_task_mm - acquire a reference to the task's mm
9651da177e4SLinus Torvalds  *
966246bb0b1SOleg Nesterov  * Returns %NULL if the task has no mm.  Checks PF_KTHREAD (meaning
9671da177e4SLinus Torvalds  * this kernel workthread has transiently adopted a user mm with use_mm,
9681da177e4SLinus Torvalds  * to do its AIO) is not set and if so returns a reference to it, after
9691da177e4SLinus Torvalds  * bumping up the use count.  User must release the mm via mmput()
9701da177e4SLinus Torvalds  * after use.  Typically used by /proc and ptrace.
9711da177e4SLinus Torvalds  */
9721da177e4SLinus Torvalds struct mm_struct *get_task_mm(struct task_struct *task)
9731da177e4SLinus Torvalds {
9741da177e4SLinus Torvalds 	struct mm_struct *mm;
9751da177e4SLinus Torvalds 
9761da177e4SLinus Torvalds 	task_lock(task);
9771da177e4SLinus Torvalds 	mm = task->mm;
9781da177e4SLinus Torvalds 	if (mm) {
979246bb0b1SOleg Nesterov 		if (task->flags & PF_KTHREAD)
9801da177e4SLinus Torvalds 			mm = NULL;
9811da177e4SLinus Torvalds 		else
9821da177e4SLinus Torvalds 			atomic_inc(&mm->mm_users);
9831da177e4SLinus Torvalds 	}
9841da177e4SLinus Torvalds 	task_unlock(task);
9851da177e4SLinus Torvalds 	return mm;
9861da177e4SLinus Torvalds }
9871da177e4SLinus Torvalds EXPORT_SYMBOL_GPL(get_task_mm);
9881da177e4SLinus Torvalds 
9898cdb878dSChristopher Yeoh struct mm_struct *mm_access(struct task_struct *task, unsigned int mode)
9908cdb878dSChristopher Yeoh {
9918cdb878dSChristopher Yeoh 	struct mm_struct *mm;
9928cdb878dSChristopher Yeoh 	int err;
9938cdb878dSChristopher Yeoh 
9948cdb878dSChristopher Yeoh 	err =  mutex_lock_killable(&task->signal->cred_guard_mutex);
9958cdb878dSChristopher Yeoh 	if (err)
9968cdb878dSChristopher Yeoh 		return ERR_PTR(err);
9978cdb878dSChristopher Yeoh 
9988cdb878dSChristopher Yeoh 	mm = get_task_mm(task);
9998cdb878dSChristopher Yeoh 	if (mm && mm != current->mm &&
10008cdb878dSChristopher Yeoh 			!ptrace_may_access(task, mode)) {
10018cdb878dSChristopher Yeoh 		mmput(mm);
10028cdb878dSChristopher Yeoh 		mm = ERR_PTR(-EACCES);
10038cdb878dSChristopher Yeoh 	}
10048cdb878dSChristopher Yeoh 	mutex_unlock(&task->signal->cred_guard_mutex);
10058cdb878dSChristopher Yeoh 
10068cdb878dSChristopher Yeoh 	return mm;
10078cdb878dSChristopher Yeoh }
10088cdb878dSChristopher Yeoh 
100957b59c4aSOleg Nesterov static void complete_vfork_done(struct task_struct *tsk)
1010c415c3b4SOleg Nesterov {
1011d68b46feSOleg Nesterov 	struct completion *vfork;
1012c415c3b4SOleg Nesterov 
1013d68b46feSOleg Nesterov 	task_lock(tsk);
1014d68b46feSOleg Nesterov 	vfork = tsk->vfork_done;
1015d68b46feSOleg Nesterov 	if (likely(vfork)) {
1016c415c3b4SOleg Nesterov 		tsk->vfork_done = NULL;
1017d68b46feSOleg Nesterov 		complete(vfork);
1018d68b46feSOleg Nesterov 	}
1019d68b46feSOleg Nesterov 	task_unlock(tsk);
1020d68b46feSOleg Nesterov }
1021d68b46feSOleg Nesterov 
1022d68b46feSOleg Nesterov static int wait_for_vfork_done(struct task_struct *child,
1023d68b46feSOleg Nesterov 				struct completion *vfork)
1024d68b46feSOleg Nesterov {
1025d68b46feSOleg Nesterov 	int killed;
1026d68b46feSOleg Nesterov 
1027d68b46feSOleg Nesterov 	freezer_do_not_count();
1028d68b46feSOleg Nesterov 	killed = wait_for_completion_killable(vfork);
1029d68b46feSOleg Nesterov 	freezer_count();
1030d68b46feSOleg Nesterov 
1031d68b46feSOleg Nesterov 	if (killed) {
1032d68b46feSOleg Nesterov 		task_lock(child);
1033d68b46feSOleg Nesterov 		child->vfork_done = NULL;
1034d68b46feSOleg Nesterov 		task_unlock(child);
1035d68b46feSOleg Nesterov 	}
1036d68b46feSOleg Nesterov 
1037d68b46feSOleg Nesterov 	put_task_struct(child);
1038d68b46feSOleg Nesterov 	return killed;
1039c415c3b4SOleg Nesterov }
1040c415c3b4SOleg Nesterov 
10411da177e4SLinus Torvalds /* Please note the differences between mmput and mm_release.
10421da177e4SLinus Torvalds  * mmput is called whenever we stop holding onto a mm_struct,
10431da177e4SLinus Torvalds  * error success whatever.
10441da177e4SLinus Torvalds  *
10451da177e4SLinus Torvalds  * mm_release is called after a mm_struct has been removed
10461da177e4SLinus Torvalds  * from the current process.
10471da177e4SLinus Torvalds  *
10481da177e4SLinus Torvalds  * This difference is important for error handling, when we
10491da177e4SLinus Torvalds  * only half set up a mm_struct for a new process and need to restore
10501da177e4SLinus Torvalds  * the old one.  Because we mmput the new mm_struct before
10511da177e4SLinus Torvalds  * restoring the old one. . .
10521da177e4SLinus Torvalds  * Eric Biederman 10 January 1998
10531da177e4SLinus Torvalds  */
10541da177e4SLinus Torvalds void mm_release(struct task_struct *tsk, struct mm_struct *mm)
10551da177e4SLinus Torvalds {
10568141c7f3SLinus Torvalds 	/* Get rid of any futexes when releasing the mm */
10578141c7f3SLinus Torvalds #ifdef CONFIG_FUTEX
1058fc6b177dSPeter Zijlstra 	if (unlikely(tsk->robust_list)) {
10598141c7f3SLinus Torvalds 		exit_robust_list(tsk);
1060fc6b177dSPeter Zijlstra 		tsk->robust_list = NULL;
1061fc6b177dSPeter Zijlstra 	}
10628141c7f3SLinus Torvalds #ifdef CONFIG_COMPAT
1063fc6b177dSPeter Zijlstra 	if (unlikely(tsk->compat_robust_list)) {
10648141c7f3SLinus Torvalds 		compat_exit_robust_list(tsk);
1065fc6b177dSPeter Zijlstra 		tsk->compat_robust_list = NULL;
1066fc6b177dSPeter Zijlstra 	}
10678141c7f3SLinus Torvalds #endif
1068322a2c10SThomas Gleixner 	if (unlikely(!list_empty(&tsk->pi_state_list)))
1069322a2c10SThomas Gleixner 		exit_pi_state_list(tsk);
10708141c7f3SLinus Torvalds #endif
10718141c7f3SLinus Torvalds 
10720326f5a9SSrikar Dronamraju 	uprobe_free_utask(tsk);
10730326f5a9SSrikar Dronamraju 
10741da177e4SLinus Torvalds 	/* Get rid of any cached register state */
10751da177e4SLinus Torvalds 	deactivate_mm(tsk, mm);
10761da177e4SLinus Torvalds 
1077fec1d011SRoland McGrath 	/*
1078735f2770SMichal Hocko 	 * Signal userspace if we're not exiting with a core dump
1079735f2770SMichal Hocko 	 * because we want to leave the value intact for debugging
1080735f2770SMichal Hocko 	 * purposes.
1081fec1d011SRoland McGrath 	 */
10829c8a8228SEric Dumazet 	if (tsk->clear_child_tid) {
1083735f2770SMichal Hocko 		if (!(tsk->signal->flags & SIGNAL_GROUP_COREDUMP) &&
10849c8a8228SEric Dumazet 		    atomic_read(&mm->mm_users) > 1) {
10851da177e4SLinus Torvalds 			/*
10861da177e4SLinus Torvalds 			 * We don't check the error code - if userspace has
10871da177e4SLinus Torvalds 			 * not set up a proper pointer then tough luck.
10881da177e4SLinus Torvalds 			 */
10899c8a8228SEric Dumazet 			put_user(0, tsk->clear_child_tid);
10909c8a8228SEric Dumazet 			sys_futex(tsk->clear_child_tid, FUTEX_WAKE,
10919c8a8228SEric Dumazet 					1, NULL, NULL, 0);
10929c8a8228SEric Dumazet 		}
10939c8a8228SEric Dumazet 		tsk->clear_child_tid = NULL;
10941da177e4SLinus Torvalds 	}
1095f7505d64SKonstantin Khlebnikov 
1096f7505d64SKonstantin Khlebnikov 	/*
1097f7505d64SKonstantin Khlebnikov 	 * All done, finally we can wake up parent and return this mm to him.
1098f7505d64SKonstantin Khlebnikov 	 * Also kthread_stop() uses this completion for synchronization.
1099f7505d64SKonstantin Khlebnikov 	 */
1100f7505d64SKonstantin Khlebnikov 	if (tsk->vfork_done)
1101f7505d64SKonstantin Khlebnikov 		complete_vfork_done(tsk);
11021da177e4SLinus Torvalds }
11031da177e4SLinus Torvalds 
1104a0a7ec30SJANAK DESAI /*
1105a0a7ec30SJANAK DESAI  * Allocate a new mm structure and copy contents from the
1106a0a7ec30SJANAK DESAI  * mm structure of the passed in task structure.
1107a0a7ec30SJANAK DESAI  */
1108ff252c1fSDaeSeok Youn static struct mm_struct *dup_mm(struct task_struct *tsk)
1109a0a7ec30SJANAK DESAI {
1110a0a7ec30SJANAK DESAI 	struct mm_struct *mm, *oldmm = current->mm;
1111a0a7ec30SJANAK DESAI 	int err;
1112a0a7ec30SJANAK DESAI 
1113a0a7ec30SJANAK DESAI 	mm = allocate_mm();
1114a0a7ec30SJANAK DESAI 	if (!mm)
1115a0a7ec30SJANAK DESAI 		goto fail_nomem;
1116a0a7ec30SJANAK DESAI 
1117a0a7ec30SJANAK DESAI 	memcpy(mm, oldmm, sizeof(*mm));
1118a0a7ec30SJANAK DESAI 
111978fb7466SPavel Emelianov 	if (!mm_init(mm, tsk))
1120a0a7ec30SJANAK DESAI 		goto fail_nomem;
1121a0a7ec30SJANAK DESAI 
1122a0a7ec30SJANAK DESAI 	err = dup_mmap(mm, oldmm);
1123a0a7ec30SJANAK DESAI 	if (err)
1124a0a7ec30SJANAK DESAI 		goto free_pt;
1125a0a7ec30SJANAK DESAI 
1126a0a7ec30SJANAK DESAI 	mm->hiwater_rss = get_mm_rss(mm);
1127a0a7ec30SJANAK DESAI 	mm->hiwater_vm = mm->total_vm;
1128a0a7ec30SJANAK DESAI 
1129801460d0SHiroshi Shimamoto 	if (mm->binfmt && !try_module_get(mm->binfmt->module))
1130801460d0SHiroshi Shimamoto 		goto free_pt;
1131801460d0SHiroshi Shimamoto 
1132a0a7ec30SJANAK DESAI 	return mm;
1133a0a7ec30SJANAK DESAI 
1134a0a7ec30SJANAK DESAI free_pt:
1135801460d0SHiroshi Shimamoto 	/* don't put binfmt in mmput, we haven't got module yet */
1136801460d0SHiroshi Shimamoto 	mm->binfmt = NULL;
1137a0a7ec30SJANAK DESAI 	mmput(mm);
1138a0a7ec30SJANAK DESAI 
1139a0a7ec30SJANAK DESAI fail_nomem:
1140a0a7ec30SJANAK DESAI 	return NULL;
1141a0a7ec30SJANAK DESAI }
1142a0a7ec30SJANAK DESAI 
11431da177e4SLinus Torvalds static int copy_mm(unsigned long clone_flags, struct task_struct *tsk)
11441da177e4SLinus Torvalds {
11451da177e4SLinus Torvalds 	struct mm_struct *mm, *oldmm;
11461da177e4SLinus Torvalds 	int retval;
11471da177e4SLinus Torvalds 
11481da177e4SLinus Torvalds 	tsk->min_flt = tsk->maj_flt = 0;
11491da177e4SLinus Torvalds 	tsk->nvcsw = tsk->nivcsw = 0;
115017406b82SMandeep Singh Baines #ifdef CONFIG_DETECT_HUNG_TASK
115117406b82SMandeep Singh Baines 	tsk->last_switch_count = tsk->nvcsw + tsk->nivcsw;
115217406b82SMandeep Singh Baines #endif
11531da177e4SLinus Torvalds 
11541da177e4SLinus Torvalds 	tsk->mm = NULL;
11551da177e4SLinus Torvalds 	tsk->active_mm = NULL;
11561da177e4SLinus Torvalds 
11571da177e4SLinus Torvalds 	/*
11581da177e4SLinus Torvalds 	 * Are we cloning a kernel thread?
11591da177e4SLinus Torvalds 	 *
11601da177e4SLinus Torvalds 	 * We need to steal a active VM for that..
11611da177e4SLinus Torvalds 	 */
11621da177e4SLinus Torvalds 	oldmm = current->mm;
11631da177e4SLinus Torvalds 	if (!oldmm)
11641da177e4SLinus Torvalds 		return 0;
11651da177e4SLinus Torvalds 
1166615d6e87SDavidlohr Bueso 	/* initialize the new vmacache entries */
1167615d6e87SDavidlohr Bueso 	vmacache_flush(tsk);
1168615d6e87SDavidlohr Bueso 
11691da177e4SLinus Torvalds 	if (clone_flags & CLONE_VM) {
11701da177e4SLinus Torvalds 		atomic_inc(&oldmm->mm_users);
11711da177e4SLinus Torvalds 		mm = oldmm;
11721da177e4SLinus Torvalds 		goto good_mm;
11731da177e4SLinus Torvalds 	}
11741da177e4SLinus Torvalds 
11751da177e4SLinus Torvalds 	retval = -ENOMEM;
1176a0a7ec30SJANAK DESAI 	mm = dup_mm(tsk);
11771da177e4SLinus Torvalds 	if (!mm)
11781da177e4SLinus Torvalds 		goto fail_nomem;
11791da177e4SLinus Torvalds 
11801da177e4SLinus Torvalds good_mm:
11811da177e4SLinus Torvalds 	tsk->mm = mm;
11821da177e4SLinus Torvalds 	tsk->active_mm = mm;
11831da177e4SLinus Torvalds 	return 0;
11841da177e4SLinus Torvalds 
11851da177e4SLinus Torvalds fail_nomem:
11861da177e4SLinus Torvalds 	return retval;
11871da177e4SLinus Torvalds }
11881da177e4SLinus Torvalds 
1189a39bc516SAlexey Dobriyan static int copy_fs(unsigned long clone_flags, struct task_struct *tsk)
11901da177e4SLinus Torvalds {
1191498052bbSAl Viro 	struct fs_struct *fs = current->fs;
11921da177e4SLinus Torvalds 	if (clone_flags & CLONE_FS) {
1193498052bbSAl Viro 		/* tsk->fs is already what we want */
11942a4419b5SNick Piggin 		spin_lock(&fs->lock);
1195498052bbSAl Viro 		if (fs->in_exec) {
11962a4419b5SNick Piggin 			spin_unlock(&fs->lock);
1197498052bbSAl Viro 			return -EAGAIN;
1198498052bbSAl Viro 		}
1199498052bbSAl Viro 		fs->users++;
12002a4419b5SNick Piggin 		spin_unlock(&fs->lock);
12011da177e4SLinus Torvalds 		return 0;
12021da177e4SLinus Torvalds 	}
1203498052bbSAl Viro 	tsk->fs = copy_fs_struct(fs);
12041da177e4SLinus Torvalds 	if (!tsk->fs)
12051da177e4SLinus Torvalds 		return -ENOMEM;
12061da177e4SLinus Torvalds 	return 0;
12071da177e4SLinus Torvalds }
12081da177e4SLinus Torvalds 
1209a016f338SJANAK DESAI static int copy_files(unsigned long clone_flags, struct task_struct *tsk)
1210a016f338SJANAK DESAI {
1211a016f338SJANAK DESAI 	struct files_struct *oldf, *newf;
1212a016f338SJANAK DESAI 	int error = 0;
1213a016f338SJANAK DESAI 
1214a016f338SJANAK DESAI 	/*
1215a016f338SJANAK DESAI 	 * A background process may not have any files ...
1216a016f338SJANAK DESAI 	 */
1217a016f338SJANAK DESAI 	oldf = current->files;
1218a016f338SJANAK DESAI 	if (!oldf)
1219a016f338SJANAK DESAI 		goto out;
1220a016f338SJANAK DESAI 
1221a016f338SJANAK DESAI 	if (clone_flags & CLONE_FILES) {
1222a016f338SJANAK DESAI 		atomic_inc(&oldf->count);
1223a016f338SJANAK DESAI 		goto out;
1224a016f338SJANAK DESAI 	}
1225a016f338SJANAK DESAI 
1226a016f338SJANAK DESAI 	newf = dup_fd(oldf, &error);
1227a016f338SJANAK DESAI 	if (!newf)
1228a016f338SJANAK DESAI 		goto out;
1229a016f338SJANAK DESAI 
1230a016f338SJANAK DESAI 	tsk->files = newf;
1231a016f338SJANAK DESAI 	error = 0;
1232a016f338SJANAK DESAI out:
1233a016f338SJANAK DESAI 	return error;
1234a016f338SJANAK DESAI }
1235a016f338SJANAK DESAI 
1236fadad878SJens Axboe static int copy_io(unsigned long clone_flags, struct task_struct *tsk)
1237fd0928dfSJens Axboe {
1238fd0928dfSJens Axboe #ifdef CONFIG_BLOCK
1239fd0928dfSJens Axboe 	struct io_context *ioc = current->io_context;
12406e736be7STejun Heo 	struct io_context *new_ioc;
1241fd0928dfSJens Axboe 
1242fd0928dfSJens Axboe 	if (!ioc)
1243fd0928dfSJens Axboe 		return 0;
1244fadad878SJens Axboe 	/*
1245fadad878SJens Axboe 	 * Share io context with parent, if CLONE_IO is set
1246fadad878SJens Axboe 	 */
1247fadad878SJens Axboe 	if (clone_flags & CLONE_IO) {
12483d48749dSTejun Heo 		ioc_task_link(ioc);
12493d48749dSTejun Heo 		tsk->io_context = ioc;
1250fadad878SJens Axboe 	} else if (ioprio_valid(ioc->ioprio)) {
12516e736be7STejun Heo 		new_ioc = get_task_io_context(tsk, GFP_KERNEL, NUMA_NO_NODE);
12526e736be7STejun Heo 		if (unlikely(!new_ioc))
1253fd0928dfSJens Axboe 			return -ENOMEM;
1254fd0928dfSJens Axboe 
12556e736be7STejun Heo 		new_ioc->ioprio = ioc->ioprio;
125611a3122fSTejun Heo 		put_io_context(new_ioc);
1257fd0928dfSJens Axboe 	}
1258fd0928dfSJens Axboe #endif
1259fd0928dfSJens Axboe 	return 0;
1260fd0928dfSJens Axboe }
1261fd0928dfSJens Axboe 
1262a39bc516SAlexey Dobriyan static int copy_sighand(unsigned long clone_flags, struct task_struct *tsk)
12631da177e4SLinus Torvalds {
12641da177e4SLinus Torvalds 	struct sighand_struct *sig;
12651da177e4SLinus Torvalds 
126660348802SZhaolei 	if (clone_flags & CLONE_SIGHAND) {
12671da177e4SLinus Torvalds 		atomic_inc(&current->sighand->count);
12681da177e4SLinus Torvalds 		return 0;
12691da177e4SLinus Torvalds 	}
12701da177e4SLinus Torvalds 	sig = kmem_cache_alloc(sighand_cachep, GFP_KERNEL);
1271e56d0903SIngo Molnar 	rcu_assign_pointer(tsk->sighand, sig);
12721da177e4SLinus Torvalds 	if (!sig)
12731da177e4SLinus Torvalds 		return -ENOMEM;
12749d7fb042SPeter Zijlstra 
12751da177e4SLinus Torvalds 	atomic_set(&sig->count, 1);
12761da177e4SLinus Torvalds 	memcpy(sig->action, current->sighand->action, sizeof(sig->action));
12771da177e4SLinus Torvalds 	return 0;
12781da177e4SLinus Torvalds }
12791da177e4SLinus Torvalds 
1280a7e5328aSOleg Nesterov void __cleanup_sighand(struct sighand_struct *sighand)
1281c81addc9SOleg Nesterov {
1282d80e731eSOleg Nesterov 	if (atomic_dec_and_test(&sighand->count)) {
1283d80e731eSOleg Nesterov 		signalfd_cleanup(sighand);
1284392809b2SOleg Nesterov 		/*
1285392809b2SOleg Nesterov 		 * sighand_cachep is SLAB_DESTROY_BY_RCU so we can free it
1286392809b2SOleg Nesterov 		 * without an RCU grace period, see __lock_task_sighand().
1287392809b2SOleg Nesterov 		 */
1288c81addc9SOleg Nesterov 		kmem_cache_free(sighand_cachep, sighand);
1289c81addc9SOleg Nesterov 	}
1290d80e731eSOleg Nesterov }
1291c81addc9SOleg Nesterov 
1292f06febc9SFrank Mayhar /*
1293f06febc9SFrank Mayhar  * Initialize POSIX timer handling for a thread group.
1294f06febc9SFrank Mayhar  */
1295f06febc9SFrank Mayhar static void posix_cpu_timers_init_group(struct signal_struct *sig)
1296f06febc9SFrank Mayhar {
129778d7d407SJiri Slaby 	unsigned long cpu_limit;
129878d7d407SJiri Slaby 
1299316c1608SJason Low 	cpu_limit = READ_ONCE(sig->rlim[RLIMIT_CPU].rlim_cur);
130078d7d407SJiri Slaby 	if (cpu_limit != RLIM_INFINITY) {
130178d7d407SJiri Slaby 		sig->cputime_expires.prof_exp = secs_to_cputime(cpu_limit);
1302d5c373ebSJason Low 		sig->cputimer.running = true;
13036279a751SOleg Nesterov 	}
13046279a751SOleg Nesterov 
1305f06febc9SFrank Mayhar 	/* The timer lists. */
1306f06febc9SFrank Mayhar 	INIT_LIST_HEAD(&sig->cpu_timers[0]);
1307f06febc9SFrank Mayhar 	INIT_LIST_HEAD(&sig->cpu_timers[1]);
1308f06febc9SFrank Mayhar 	INIT_LIST_HEAD(&sig->cpu_timers[2]);
1309f06febc9SFrank Mayhar }
1310f06febc9SFrank Mayhar 
1311a39bc516SAlexey Dobriyan static int copy_signal(unsigned long clone_flags, struct task_struct *tsk)
13121da177e4SLinus Torvalds {
13131da177e4SLinus Torvalds 	struct signal_struct *sig;
13141da177e4SLinus Torvalds 
13154ab6c083SOleg Nesterov 	if (clone_flags & CLONE_THREAD)
1316490dea45SPeter Zijlstra 		return 0;
13176279a751SOleg Nesterov 
1318a56704efSVeaceslav Falico 	sig = kmem_cache_zalloc(signal_cachep, GFP_KERNEL);
13191da177e4SLinus Torvalds 	tsk->signal = sig;
13201da177e4SLinus Torvalds 	if (!sig)
13211da177e4SLinus Torvalds 		return -ENOMEM;
13221da177e4SLinus Torvalds 
1323b3ac022cSOleg Nesterov 	sig->nr_threads = 1;
13241da177e4SLinus Torvalds 	atomic_set(&sig->live, 1);
1325b3ac022cSOleg Nesterov 	atomic_set(&sig->sigcnt, 1);
13260c740d0aSOleg Nesterov 
13270c740d0aSOleg Nesterov 	/* list_add(thread_node, thread_head) without INIT_LIST_HEAD() */
13280c740d0aSOleg Nesterov 	sig->thread_head = (struct list_head)LIST_HEAD_INIT(tsk->thread_node);
13290c740d0aSOleg Nesterov 	tsk->thread_node = (struct list_head)LIST_HEAD_INIT(sig->thread_head);
13300c740d0aSOleg Nesterov 
13311da177e4SLinus Torvalds 	init_waitqueue_head(&sig->wait_chldexit);
1332db51aeccSOleg Nesterov 	sig->curr_target = tsk;
13331da177e4SLinus Torvalds 	init_sigpending(&sig->shared_pending);
13341da177e4SLinus Torvalds 	INIT_LIST_HEAD(&sig->posix_timers);
1335e78c3496SRik van Riel 	seqlock_init(&sig->stats_lock);
13369d7fb042SPeter Zijlstra 	prev_cputime_init(&sig->prev_cputime);
13371da177e4SLinus Torvalds 
1338c9cb2e3dSThomas Gleixner 	hrtimer_init(&sig->real_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
13391da177e4SLinus Torvalds 	sig->real_timer.function = it_real_fn;
13401da177e4SLinus Torvalds 
13411da177e4SLinus Torvalds 	task_lock(current->group_leader);
13421da177e4SLinus Torvalds 	memcpy(sig->rlim, current->signal->rlim, sizeof sig->rlim);
13431da177e4SLinus Torvalds 	task_unlock(current->group_leader);
13441da177e4SLinus Torvalds 
13456279a751SOleg Nesterov 	posix_cpu_timers_init_group(sig);
13466279a751SOleg Nesterov 
1347522ed776SMiloslav Trmac 	tty_audit_fork(sig);
13485091faa4SMike Galbraith 	sched_autogroup_fork(sig);
1349522ed776SMiloslav Trmac 
1350a63d83f4SDavid Rientjes 	sig->oom_score_adj = current->signal->oom_score_adj;
1351dabb16f6SMandeep Singh Baines 	sig->oom_score_adj_min = current->signal->oom_score_adj_min;
135228b83c51SKOSAKI Motohiro 
1353ebec18a6SLennart Poettering 	sig->has_child_subreaper = current->signal->has_child_subreaper ||
1354ebec18a6SLennart Poettering 				   current->signal->is_child_subreaper;
1355ebec18a6SLennart Poettering 
13569b1bf12dSKOSAKI Motohiro 	mutex_init(&sig->cred_guard_mutex);
13579b1bf12dSKOSAKI Motohiro 
13581da177e4SLinus Torvalds 	return 0;
13591da177e4SLinus Torvalds }
13601da177e4SLinus Torvalds 
1361dbd95212SKees Cook static void copy_seccomp(struct task_struct *p)
1362dbd95212SKees Cook {
1363dbd95212SKees Cook #ifdef CONFIG_SECCOMP
1364dbd95212SKees Cook 	/*
1365dbd95212SKees Cook 	 * Must be called with sighand->lock held, which is common to
1366dbd95212SKees Cook 	 * all threads in the group. Holding cred_guard_mutex is not
1367dbd95212SKees Cook 	 * needed because this new task is not yet running and cannot
1368dbd95212SKees Cook 	 * be racing exec.
1369dbd95212SKees Cook 	 */
137069f6a34bSGuenter Roeck 	assert_spin_locked(&current->sighand->siglock);
1371dbd95212SKees Cook 
1372dbd95212SKees Cook 	/* Ref-count the new filter user, and assign it. */
1373dbd95212SKees Cook 	get_seccomp_filter(current);
1374dbd95212SKees Cook 	p->seccomp = current->seccomp;
1375dbd95212SKees Cook 
1376dbd95212SKees Cook 	/*
1377dbd95212SKees Cook 	 * Explicitly enable no_new_privs here in case it got set
1378dbd95212SKees Cook 	 * between the task_struct being duplicated and holding the
1379dbd95212SKees Cook 	 * sighand lock. The seccomp state and nnp must be in sync.
1380dbd95212SKees Cook 	 */
1381dbd95212SKees Cook 	if (task_no_new_privs(current))
1382dbd95212SKees Cook 		task_set_no_new_privs(p);
1383dbd95212SKees Cook 
1384dbd95212SKees Cook 	/*
1385dbd95212SKees Cook 	 * If the parent gained a seccomp mode after copying thread
1386dbd95212SKees Cook 	 * flags and between before we held the sighand lock, we have
1387dbd95212SKees Cook 	 * to manually enable the seccomp thread flag here.
1388dbd95212SKees Cook 	 */
1389dbd95212SKees Cook 	if (p->seccomp.mode != SECCOMP_MODE_DISABLED)
1390dbd95212SKees Cook 		set_tsk_thread_flag(p, TIF_SECCOMP);
1391dbd95212SKees Cook #endif
1392dbd95212SKees Cook }
1393dbd95212SKees Cook 
139417da2bd9SHeiko Carstens SYSCALL_DEFINE1(set_tid_address, int __user *, tidptr)
13951da177e4SLinus Torvalds {
13961da177e4SLinus Torvalds 	current->clear_child_tid = tidptr;
13971da177e4SLinus Torvalds 
1398b488893aSPavel Emelyanov 	return task_pid_vnr(current);
13991da177e4SLinus Torvalds }
14001da177e4SLinus Torvalds 
1401a39bc516SAlexey Dobriyan static void rt_mutex_init_task(struct task_struct *p)
140223f78d4aSIngo Molnar {
14031d615482SThomas Gleixner 	raw_spin_lock_init(&p->pi_lock);
1404e29e175bSZilvinas Valinskas #ifdef CONFIG_RT_MUTEXES
1405fb00aca4SPeter Zijlstra 	p->pi_waiters = RB_ROOT;
1406fb00aca4SPeter Zijlstra 	p->pi_waiters_leftmost = NULL;
140723f78d4aSIngo Molnar 	p->pi_blocked_on = NULL;
140823f78d4aSIngo Molnar #endif
140923f78d4aSIngo Molnar }
141023f78d4aSIngo Molnar 
14111da177e4SLinus Torvalds /*
1412f06febc9SFrank Mayhar  * Initialize POSIX timer handling for a single task.
1413f06febc9SFrank Mayhar  */
1414f06febc9SFrank Mayhar static void posix_cpu_timers_init(struct task_struct *tsk)
1415f06febc9SFrank Mayhar {
141664861634SMartin Schwidefsky 	tsk->cputime_expires.prof_exp = 0;
141764861634SMartin Schwidefsky 	tsk->cputime_expires.virt_exp = 0;
1418f06febc9SFrank Mayhar 	tsk->cputime_expires.sched_exp = 0;
1419f06febc9SFrank Mayhar 	INIT_LIST_HEAD(&tsk->cpu_timers[0]);
1420f06febc9SFrank Mayhar 	INIT_LIST_HEAD(&tsk->cpu_timers[1]);
1421f06febc9SFrank Mayhar 	INIT_LIST_HEAD(&tsk->cpu_timers[2]);
1422f06febc9SFrank Mayhar }
1423f06febc9SFrank Mayhar 
142481907739SOleg Nesterov static inline void
142581907739SOleg Nesterov init_task_pid(struct task_struct *task, enum pid_type type, struct pid *pid)
142681907739SOleg Nesterov {
142781907739SOleg Nesterov 	 task->pids[type].pid = pid;
142881907739SOleg Nesterov }
142981907739SOleg Nesterov 
1430f06febc9SFrank Mayhar /*
14311da177e4SLinus Torvalds  * This creates a new process as a copy of the old one,
14321da177e4SLinus Torvalds  * but does not actually start it yet.
14331da177e4SLinus Torvalds  *
14341da177e4SLinus Torvalds  * It copies the registers, and all the appropriate
14351da177e4SLinus Torvalds  * parts of the process environment (as per the clone
14361da177e4SLinus Torvalds  * flags). The actual kick-off is left to the caller.
14371da177e4SLinus Torvalds  */
143836c8b586SIngo Molnar static struct task_struct *copy_process(unsigned long clone_flags,
14391da177e4SLinus Torvalds 					unsigned long stack_start,
14401da177e4SLinus Torvalds 					unsigned long stack_size,
14411da177e4SLinus Torvalds 					int __user *child_tidptr,
144209a05394SRoland McGrath 					struct pid *pid,
14433033f14aSJosh Triplett 					int trace,
1444725fc629SAndi Kleen 					unsigned long tls,
1445725fc629SAndi Kleen 					int node)
14461da177e4SLinus Torvalds {
14471da177e4SLinus Torvalds 	int retval;
1448a24efe62SMariusz Kozlowski 	struct task_struct *p;
14491da177e4SLinus Torvalds 
14501da177e4SLinus Torvalds 	if ((clone_flags & (CLONE_NEWNS|CLONE_FS)) == (CLONE_NEWNS|CLONE_FS))
14511da177e4SLinus Torvalds 		return ERR_PTR(-EINVAL);
14521da177e4SLinus Torvalds 
1453e66eded8SEric W. Biederman 	if ((clone_flags & (CLONE_NEWUSER|CLONE_FS)) == (CLONE_NEWUSER|CLONE_FS))
1454e66eded8SEric W. Biederman 		return ERR_PTR(-EINVAL);
1455e66eded8SEric W. Biederman 
14561da177e4SLinus Torvalds 	/*
14571da177e4SLinus Torvalds 	 * Thread groups must share signals as well, and detached threads
14581da177e4SLinus Torvalds 	 * can only be started up within the thread group.
14591da177e4SLinus Torvalds 	 */
14601da177e4SLinus Torvalds 	if ((clone_flags & CLONE_THREAD) && !(clone_flags & CLONE_SIGHAND))
14611da177e4SLinus Torvalds 		return ERR_PTR(-EINVAL);
14621da177e4SLinus Torvalds 
14631da177e4SLinus Torvalds 	/*
14641da177e4SLinus Torvalds 	 * Shared signal handlers imply shared VM. By way of the above,
14651da177e4SLinus Torvalds 	 * thread groups also imply shared VM. Blocking this case allows
14661da177e4SLinus Torvalds 	 * for various simplifications in other code.
14671da177e4SLinus Torvalds 	 */
14681da177e4SLinus Torvalds 	if ((clone_flags & CLONE_SIGHAND) && !(clone_flags & CLONE_VM))
14691da177e4SLinus Torvalds 		return ERR_PTR(-EINVAL);
14701da177e4SLinus Torvalds 
1471123be07bSSukadev Bhattiprolu 	/*
1472123be07bSSukadev Bhattiprolu 	 * Siblings of global init remain as zombies on exit since they are
1473123be07bSSukadev Bhattiprolu 	 * not reaped by their parent (swapper). To solve this and to avoid
1474123be07bSSukadev Bhattiprolu 	 * multi-rooted process trees, prevent global and container-inits
1475123be07bSSukadev Bhattiprolu 	 * from creating siblings.
1476123be07bSSukadev Bhattiprolu 	 */
1477123be07bSSukadev Bhattiprolu 	if ((clone_flags & CLONE_PARENT) &&
1478123be07bSSukadev Bhattiprolu 				current->signal->flags & SIGNAL_UNKILLABLE)
1479123be07bSSukadev Bhattiprolu 		return ERR_PTR(-EINVAL);
1480123be07bSSukadev Bhattiprolu 
14818382fcacSEric W. Biederman 	/*
148240a0d32dSOleg Nesterov 	 * If the new process will be in a different pid or user namespace
1483faf00da5SEric W. Biederman 	 * do not allow it to share a thread group with the forking task.
14848382fcacSEric W. Biederman 	 */
1485faf00da5SEric W. Biederman 	if (clone_flags & CLONE_THREAD) {
148640a0d32dSOleg Nesterov 		if ((clone_flags & (CLONE_NEWUSER | CLONE_NEWPID)) ||
148740a0d32dSOleg Nesterov 		    (task_active_pid_ns(current) !=
1488c2b1df2eSAndy Lutomirski 				current->nsproxy->pid_ns_for_children))
14898382fcacSEric W. Biederman 			return ERR_PTR(-EINVAL);
149040a0d32dSOleg Nesterov 	}
14918382fcacSEric W. Biederman 
14921da177e4SLinus Torvalds 	retval = security_task_create(clone_flags);
14931da177e4SLinus Torvalds 	if (retval)
14941da177e4SLinus Torvalds 		goto fork_out;
14951da177e4SLinus Torvalds 
14961da177e4SLinus Torvalds 	retval = -ENOMEM;
1497725fc629SAndi Kleen 	p = dup_task_struct(current, node);
14981da177e4SLinus Torvalds 	if (!p)
14991da177e4SLinus Torvalds 		goto fork_out;
15001da177e4SLinus Torvalds 
1501f7e8b616SSteven Rostedt 	ftrace_graph_init_task(p);
1502f7e8b616SSteven Rostedt 
1503bea493a0SPeter Zijlstra 	rt_mutex_init_task(p);
1504bea493a0SPeter Zijlstra 
1505d12c1a37SIngo Molnar #ifdef CONFIG_PROVE_LOCKING
1506de30a2b3SIngo Molnar 	DEBUG_LOCKS_WARN_ON(!p->hardirqs_enabled);
1507de30a2b3SIngo Molnar 	DEBUG_LOCKS_WARN_ON(!p->softirqs_enabled);
1508de30a2b3SIngo Molnar #endif
15091da177e4SLinus Torvalds 	retval = -EAGAIN;
15103b11a1deSDavid Howells 	if (atomic_read(&p->real_cred->user->processes) >=
151178d7d407SJiri Slaby 			task_rlimit(p, RLIMIT_NPROC)) {
1512b57922b6SEric Paris 		if (p->real_cred->user != INIT_USER &&
1513b57922b6SEric Paris 		    !capable(CAP_SYS_RESOURCE) && !capable(CAP_SYS_ADMIN))
15141da177e4SLinus Torvalds 			goto bad_fork_free;
15151da177e4SLinus Torvalds 	}
151672fa5997SVasiliy Kulikov 	current->flags &= ~PF_NPROC_EXCEEDED;
15171da177e4SLinus Torvalds 
1518f1752eecSDavid Howells 	retval = copy_creds(p, clone_flags);
1519f1752eecSDavid Howells 	if (retval < 0)
1520f1752eecSDavid Howells 		goto bad_fork_free;
15211da177e4SLinus Torvalds 
15221da177e4SLinus Torvalds 	/*
15231da177e4SLinus Torvalds 	 * If multiple threads are within copy_process(), then this check
15241da177e4SLinus Torvalds 	 * triggers too late. This doesn't hurt, the check is only there
15251da177e4SLinus Torvalds 	 * to stop root fork bombs.
15261da177e4SLinus Torvalds 	 */
152704ec93feSLi Zefan 	retval = -EAGAIN;
15281da177e4SLinus Torvalds 	if (nr_threads >= max_threads)
15291da177e4SLinus Torvalds 		goto bad_fork_cleanup_count;
15301da177e4SLinus Torvalds 
1531ca74e92bSShailabh Nagar 	delayacct_tsk_init(p);	/* Must remain after dup_task_struct() */
1532514ddb44SDavid Rientjes 	p->flags &= ~(PF_SUPERPRIV | PF_WQ_WORKER);
1533514ddb44SDavid Rientjes 	p->flags |= PF_FORKNOEXEC;
15341da177e4SLinus Torvalds 	INIT_LIST_HEAD(&p->children);
15351da177e4SLinus Torvalds 	INIT_LIST_HEAD(&p->sibling);
1536f41d911fSPaul E. McKenney 	rcu_copy_process(p);
15371da177e4SLinus Torvalds 	p->vfork_done = NULL;
15381da177e4SLinus Torvalds 	spin_lock_init(&p->alloc_lock);
15391da177e4SLinus Torvalds 
15401da177e4SLinus Torvalds 	init_sigpending(&p->pending);
15411da177e4SLinus Torvalds 
154264861634SMartin Schwidefsky 	p->utime = p->stime = p->gtime = 0;
154364861634SMartin Schwidefsky 	p->utimescaled = p->stimescaled = 0;
15449d7fb042SPeter Zijlstra 	prev_cputime_init(&p->prev_cputime);
15459d7fb042SPeter Zijlstra 
15466a61671bSFrederic Weisbecker #ifdef CONFIG_VIRT_CPU_ACCOUNTING_GEN
1547b7ce2277SFrederic Weisbecker 	seqcount_init(&p->vtime_seqcount);
15486a61671bSFrederic Weisbecker 	p->vtime_snap = 0;
15497098c1eaSFrederic Weisbecker 	p->vtime_snap_whence = VTIME_INACTIVE;
15506a61671bSFrederic Weisbecker #endif
15516a61671bSFrederic Weisbecker 
1552a3a2e76cSKAMEZAWA Hiroyuki #if defined(SPLIT_RSS_COUNTING)
1553a3a2e76cSKAMEZAWA Hiroyuki 	memset(&p->rss_stat, 0, sizeof(p->rss_stat));
1554a3a2e76cSKAMEZAWA Hiroyuki #endif
1555172ba844SBalbir Singh 
15566976675dSArjan van de Ven 	p->default_timer_slack_ns = current->timer_slack_ns;
15576976675dSArjan van de Ven 
15585995477aSAndrea Righi 	task_io_accounting_init(&p->ioac);
15591da177e4SLinus Torvalds 	acct_clear_integrals(p);
15601da177e4SLinus Torvalds 
1561f06febc9SFrank Mayhar 	posix_cpu_timers_init(p);
15621da177e4SLinus Torvalds 
1563ccbf62d8SThomas Gleixner 	p->start_time = ktime_get_ns();
156457e0be04SThomas Gleixner 	p->real_start_time = ktime_get_boot_ns();
15651da177e4SLinus Torvalds 	p->io_context = NULL;
15661da177e4SLinus Torvalds 	p->audit_context = NULL;
1567b4f48b63SPaul Menage 	cgroup_fork(p);
15681da177e4SLinus Torvalds #ifdef CONFIG_NUMA
1569846a16bfSLee Schermerhorn 	p->mempolicy = mpol_dup(p->mempolicy);
15701da177e4SLinus Torvalds 	if (IS_ERR(p->mempolicy)) {
15711da177e4SLinus Torvalds 		retval = PTR_ERR(p->mempolicy);
15721da177e4SLinus Torvalds 		p->mempolicy = NULL;
1573e8604cb4SLi Zefan 		goto bad_fork_cleanup_threadgroup_lock;
15741da177e4SLinus Torvalds 	}
15751da177e4SLinus Torvalds #endif
1576778d3b0fSMichal Hocko #ifdef CONFIG_CPUSETS
1577778d3b0fSMichal Hocko 	p->cpuset_mem_spread_rotor = NUMA_NO_NODE;
1578778d3b0fSMichal Hocko 	p->cpuset_slab_spread_rotor = NUMA_NO_NODE;
1579cc9a6c87SMel Gorman 	seqcount_init(&p->mems_allowed_seq);
1580778d3b0fSMichal Hocko #endif
1581de30a2b3SIngo Molnar #ifdef CONFIG_TRACE_IRQFLAGS
1582de30a2b3SIngo Molnar 	p->irq_events = 0;
1583de30a2b3SIngo Molnar 	p->hardirqs_enabled = 0;
1584de30a2b3SIngo Molnar 	p->hardirq_enable_ip = 0;
1585de30a2b3SIngo Molnar 	p->hardirq_enable_event = 0;
1586de30a2b3SIngo Molnar 	p->hardirq_disable_ip = _THIS_IP_;
1587de30a2b3SIngo Molnar 	p->hardirq_disable_event = 0;
1588de30a2b3SIngo Molnar 	p->softirqs_enabled = 1;
1589de30a2b3SIngo Molnar 	p->softirq_enable_ip = _THIS_IP_;
1590de30a2b3SIngo Molnar 	p->softirq_enable_event = 0;
1591de30a2b3SIngo Molnar 	p->softirq_disable_ip = 0;
1592de30a2b3SIngo Molnar 	p->softirq_disable_event = 0;
1593de30a2b3SIngo Molnar 	p->hardirq_context = 0;
1594de30a2b3SIngo Molnar 	p->softirq_context = 0;
1595de30a2b3SIngo Molnar #endif
15968bcbde54SDavid Hildenbrand 
15978bcbde54SDavid Hildenbrand 	p->pagefault_disabled = 0;
15988bcbde54SDavid Hildenbrand 
1599fbb9ce95SIngo Molnar #ifdef CONFIG_LOCKDEP
1600fbb9ce95SIngo Molnar 	p->lockdep_depth = 0; /* no locks held yet */
1601fbb9ce95SIngo Molnar 	p->curr_chain_key = 0;
1602fbb9ce95SIngo Molnar 	p->lockdep_recursion = 0;
1603fbb9ce95SIngo Molnar #endif
16041da177e4SLinus Torvalds 
1605408894eeSIngo Molnar #ifdef CONFIG_DEBUG_MUTEXES
1606408894eeSIngo Molnar 	p->blocked_on = NULL; /* not blocked yet */
1607408894eeSIngo Molnar #endif
1608cafe5635SKent Overstreet #ifdef CONFIG_BCACHE
1609cafe5635SKent Overstreet 	p->sequential_io	= 0;
1610cafe5635SKent Overstreet 	p->sequential_io_avg	= 0;
1611cafe5635SKent Overstreet #endif
16120f481406SMarkus Metzger 
16133c90e6e9SSrivatsa Vaddagiri 	/* Perform scheduler related setup. Assign this task to a CPU. */
1614aab03e05SDario Faggioli 	retval = sched_fork(clone_flags, p);
1615aab03e05SDario Faggioli 	if (retval)
1616aab03e05SDario Faggioli 		goto bad_fork_cleanup_policy;
16176ab423e0SPeter Zijlstra 
1618cdd6c482SIngo Molnar 	retval = perf_event_init_task(p);
16196ab423e0SPeter Zijlstra 	if (retval)
16206ab423e0SPeter Zijlstra 		goto bad_fork_cleanup_policy;
1621fb0a685cSDaniel Rebelo de Oliveira 	retval = audit_alloc(p);
1622fb0a685cSDaniel Rebelo de Oliveira 	if (retval)
16236c72e350SPeter Zijlstra 		goto bad_fork_cleanup_perf;
16241da177e4SLinus Torvalds 	/* copy all the process information */
1625ab602f79SJack Miller 	shm_init_task(p);
1626fb0a685cSDaniel Rebelo de Oliveira 	retval = copy_semundo(clone_flags, p);
1627fb0a685cSDaniel Rebelo de Oliveira 	if (retval)
16281da177e4SLinus Torvalds 		goto bad_fork_cleanup_audit;
1629fb0a685cSDaniel Rebelo de Oliveira 	retval = copy_files(clone_flags, p);
1630fb0a685cSDaniel Rebelo de Oliveira 	if (retval)
16311da177e4SLinus Torvalds 		goto bad_fork_cleanup_semundo;
1632fb0a685cSDaniel Rebelo de Oliveira 	retval = copy_fs(clone_flags, p);
1633fb0a685cSDaniel Rebelo de Oliveira 	if (retval)
16341da177e4SLinus Torvalds 		goto bad_fork_cleanup_files;
1635fb0a685cSDaniel Rebelo de Oliveira 	retval = copy_sighand(clone_flags, p);
1636fb0a685cSDaniel Rebelo de Oliveira 	if (retval)
16371da177e4SLinus Torvalds 		goto bad_fork_cleanup_fs;
1638fb0a685cSDaniel Rebelo de Oliveira 	retval = copy_signal(clone_flags, p);
1639fb0a685cSDaniel Rebelo de Oliveira 	if (retval)
16401da177e4SLinus Torvalds 		goto bad_fork_cleanup_sighand;
1641fb0a685cSDaniel Rebelo de Oliveira 	retval = copy_mm(clone_flags, p);
1642fb0a685cSDaniel Rebelo de Oliveira 	if (retval)
16431da177e4SLinus Torvalds 		goto bad_fork_cleanup_signal;
1644fb0a685cSDaniel Rebelo de Oliveira 	retval = copy_namespaces(clone_flags, p);
1645fb0a685cSDaniel Rebelo de Oliveira 	if (retval)
1646d84f4f99SDavid Howells 		goto bad_fork_cleanup_mm;
1647fb0a685cSDaniel Rebelo de Oliveira 	retval = copy_io(clone_flags, p);
1648fb0a685cSDaniel Rebelo de Oliveira 	if (retval)
1649fd0928dfSJens Axboe 		goto bad_fork_cleanup_namespaces;
16503033f14aSJosh Triplett 	retval = copy_thread_tls(clone_flags, stack_start, stack_size, p, tls);
16511da177e4SLinus Torvalds 	if (retval)
1652fd0928dfSJens Axboe 		goto bad_fork_cleanup_io;
16531da177e4SLinus Torvalds 
1654425fb2b4SPavel Emelyanov 	if (pid != &init_struct_pid) {
1655c2b1df2eSAndy Lutomirski 		pid = alloc_pid(p->nsproxy->pid_ns_for_children);
165635f71bc0SMichal Hocko 		if (IS_ERR(pid)) {
165735f71bc0SMichal Hocko 			retval = PTR_ERR(pid);
16580740aa5fSJiri Slaby 			goto bad_fork_cleanup_thread;
1659425fb2b4SPavel Emelyanov 		}
166035f71bc0SMichal Hocko 	}
1661425fb2b4SPavel Emelyanov 
16621da177e4SLinus Torvalds 	p->set_child_tid = (clone_flags & CLONE_CHILD_SETTID) ? child_tidptr : NULL;
16631da177e4SLinus Torvalds 	/*
16641da177e4SLinus Torvalds 	 * Clear TID on mm_release()?
16651da177e4SLinus Torvalds 	 */
16661da177e4SLinus Torvalds 	p->clear_child_tid = (clone_flags & CLONE_CHILD_CLEARTID) ? child_tidptr : NULL;
166773c10101SJens Axboe #ifdef CONFIG_BLOCK
166873c10101SJens Axboe 	p->plug = NULL;
166973c10101SJens Axboe #endif
167042b2dd0aSAlexey Dobriyan #ifdef CONFIG_FUTEX
16718f17d3a5SIngo Molnar 	p->robust_list = NULL;
16728f17d3a5SIngo Molnar #ifdef CONFIG_COMPAT
16738f17d3a5SIngo Molnar 	p->compat_robust_list = NULL;
16748f17d3a5SIngo Molnar #endif
1675c87e2837SIngo Molnar 	INIT_LIST_HEAD(&p->pi_state_list);
1676c87e2837SIngo Molnar 	p->pi_state_cache = NULL;
167742b2dd0aSAlexey Dobriyan #endif
16781da177e4SLinus Torvalds 	/*
1679f9a3879aSGOTO Masanori 	 * sigaltstack should be cleared when sharing the same VM
1680f9a3879aSGOTO Masanori 	 */
1681f9a3879aSGOTO Masanori 	if ((clone_flags & (CLONE_VM|CLONE_VFORK)) == CLONE_VM)
16822a742138SStas Sergeev 		sas_ss_reset(p);
1683f9a3879aSGOTO Masanori 
1684f9a3879aSGOTO Masanori 	/*
16856580807dSOleg Nesterov 	 * Syscall tracing and stepping should be turned off in the
16866580807dSOleg Nesterov 	 * child regardless of CLONE_PTRACE.
16871da177e4SLinus Torvalds 	 */
16886580807dSOleg Nesterov 	user_disable_single_step(p);
16891da177e4SLinus Torvalds 	clear_tsk_thread_flag(p, TIF_SYSCALL_TRACE);
1690ed75e8d5SLaurent Vivier #ifdef TIF_SYSCALL_EMU
1691ed75e8d5SLaurent Vivier 	clear_tsk_thread_flag(p, TIF_SYSCALL_EMU);
1692ed75e8d5SLaurent Vivier #endif
16939745512cSArjan van de Ven 	clear_all_latency_tracing(p);
16941da177e4SLinus Torvalds 
16951da177e4SLinus Torvalds 	/* ok, now we should be set up.. */
169618c830dfSOleg Nesterov 	p->pid = pid_nr(pid);
169718c830dfSOleg Nesterov 	if (clone_flags & CLONE_THREAD) {
16985f8aadd8SOleg Nesterov 		p->exit_signal = -1;
169918c830dfSOleg Nesterov 		p->group_leader = current->group_leader;
170018c830dfSOleg Nesterov 		p->tgid = current->tgid;
170118c830dfSOleg Nesterov 	} else {
170218c830dfSOleg Nesterov 		if (clone_flags & CLONE_PARENT)
17035f8aadd8SOleg Nesterov 			p->exit_signal = current->group_leader->exit_signal;
17045f8aadd8SOleg Nesterov 		else
17055f8aadd8SOleg Nesterov 			p->exit_signal = (clone_flags & CSIGNAL);
170618c830dfSOleg Nesterov 		p->group_leader = p;
170718c830dfSOleg Nesterov 		p->tgid = p->pid;
170818c830dfSOleg Nesterov 	}
17095f8aadd8SOleg Nesterov 
17109d823e8fSWu Fengguang 	p->nr_dirtied = 0;
17119d823e8fSWu Fengguang 	p->nr_dirtied_pause = 128 >> (PAGE_SHIFT - 10);
171283712358SWu Fengguang 	p->dirty_paused_when = 0;
17139d823e8fSWu Fengguang 
1714bb8cbbfeSOleg Nesterov 	p->pdeath_signal = 0;
171547e65328SOleg Nesterov 	INIT_LIST_HEAD(&p->thread_group);
1716158e1645SAl Viro 	p->task_works = NULL;
17171da177e4SLinus Torvalds 
1718568ac888SBalbir Singh 	threadgroup_change_begin(current);
171918c830dfSOleg Nesterov 	/*
17207e47682eSAleksa Sarai 	 * Ensure that the cgroup subsystem policies allow the new process to be
17217e47682eSAleksa Sarai 	 * forked. It should be noted the the new process's css_set can be changed
17227e47682eSAleksa Sarai 	 * between here and cgroup_post_fork() if an organisation operation is in
17237e47682eSAleksa Sarai 	 * progress.
17247e47682eSAleksa Sarai 	 */
1725b53202e6SOleg Nesterov 	retval = cgroup_can_fork(p);
17267e47682eSAleksa Sarai 	if (retval)
17277e47682eSAleksa Sarai 		goto bad_fork_free_pid;
17287e47682eSAleksa Sarai 
17297e47682eSAleksa Sarai 	/*
173018c830dfSOleg Nesterov 	 * Make it visible to the rest of the system, but dont wake it up yet.
173118c830dfSOleg Nesterov 	 * Need tasklist lock for parent etc handling!
173218c830dfSOleg Nesterov 	 */
17331da177e4SLinus Torvalds 	write_lock_irq(&tasklist_lock);
17341da177e4SLinus Torvalds 
17351da177e4SLinus Torvalds 	/* CLONE_PARENT re-uses the old parent */
17362d5516cbSOleg Nesterov 	if (clone_flags & (CLONE_PARENT|CLONE_THREAD)) {
17371da177e4SLinus Torvalds 		p->real_parent = current->real_parent;
17382d5516cbSOleg Nesterov 		p->parent_exec_id = current->parent_exec_id;
17392d5516cbSOleg Nesterov 	} else {
17401da177e4SLinus Torvalds 		p->real_parent = current;
17412d5516cbSOleg Nesterov 		p->parent_exec_id = current->self_exec_id;
17422d5516cbSOleg Nesterov 	}
17431da177e4SLinus Torvalds 
17441da177e4SLinus Torvalds 	spin_lock(&current->sighand->siglock);
17454a2c7a78SOleg Nesterov 
17464a2c7a78SOleg Nesterov 	/*
1747dbd95212SKees Cook 	 * Copy seccomp details explicitly here, in case they were changed
1748dbd95212SKees Cook 	 * before holding sighand lock.
1749dbd95212SKees Cook 	 */
1750dbd95212SKees Cook 	copy_seccomp(p);
1751dbd95212SKees Cook 
1752dbd95212SKees Cook 	/*
17534a2c7a78SOleg Nesterov 	 * Process group and session signals need to be delivered to just the
17544a2c7a78SOleg Nesterov 	 * parent before the fork or both the parent and the child after the
17554a2c7a78SOleg Nesterov 	 * fork. Restart if a signal comes in before we add the new process to
17564a2c7a78SOleg Nesterov 	 * it's process group.
17574a2c7a78SOleg Nesterov 	 * A fatal signal pending means that current will exit, so the new
17584a2c7a78SOleg Nesterov 	 * thread can't slip out of an OOM kill (or normal SIGKILL).
17594a2c7a78SOleg Nesterov 	*/
17604a2c7a78SOleg Nesterov 	recalc_sigpending();
17614a2c7a78SOleg Nesterov 	if (signal_pending(current)) {
17624a2c7a78SOleg Nesterov 		spin_unlock(&current->sighand->siglock);
17634a2c7a78SOleg Nesterov 		write_unlock_irq(&tasklist_lock);
17644a2c7a78SOleg Nesterov 		retval = -ERESTARTNOINTR;
17657e47682eSAleksa Sarai 		goto bad_fork_cancel_cgroup;
17664a2c7a78SOleg Nesterov 	}
17674a2c7a78SOleg Nesterov 
176873b9ebfeSOleg Nesterov 	if (likely(p->pid)) {
17694b9d33e6STejun Heo 		ptrace_init_task(p, (clone_flags & CLONE_PTRACE) || trace);
17701da177e4SLinus Torvalds 
177181907739SOleg Nesterov 		init_task_pid(p, PIDTYPE_PID, pid);
17721da177e4SLinus Torvalds 		if (thread_group_leader(p)) {
177381907739SOleg Nesterov 			init_task_pid(p, PIDTYPE_PGID, task_pgrp(current));
177481907739SOleg Nesterov 			init_task_pid(p, PIDTYPE_SID, task_session(current));
177581907739SOleg Nesterov 
17761c4042c2SEric W. Biederman 			if (is_child_reaper(pid)) {
177717cf22c3SEric W. Biederman 				ns_of_pid(pid)->child_reaper = p;
17781c4042c2SEric W. Biederman 				p->signal->flags |= SIGNAL_UNKILLABLE;
17791c4042c2SEric W. Biederman 			}
17805cd17569SEric W. Biederman 
1781fea9d175SOleg Nesterov 			p->signal->leader_pid = pid;
17829c9f4dedSAlan Cox 			p->signal->tty = tty_kref_get(current->signal->tty);
17839cd80bbbSOleg Nesterov 			list_add_tail(&p->sibling, &p->real_parent->children);
17845e85d4abSEric W. Biederman 			list_add_tail_rcu(&p->tasks, &init_task.tasks);
178581907739SOleg Nesterov 			attach_pid(p, PIDTYPE_PGID);
178681907739SOleg Nesterov 			attach_pid(p, PIDTYPE_SID);
1787909ea964SChristoph Lameter 			__this_cpu_inc(process_counts);
178880628ca0SOleg Nesterov 		} else {
178980628ca0SOleg Nesterov 			current->signal->nr_threads++;
179080628ca0SOleg Nesterov 			atomic_inc(&current->signal->live);
179180628ca0SOleg Nesterov 			atomic_inc(&current->signal->sigcnt);
179280628ca0SOleg Nesterov 			list_add_tail_rcu(&p->thread_group,
179380628ca0SOleg Nesterov 					  &p->group_leader->thread_group);
17940c740d0aSOleg Nesterov 			list_add_tail_rcu(&p->thread_node,
17950c740d0aSOleg Nesterov 					  &p->signal->thread_head);
17961da177e4SLinus Torvalds 		}
179781907739SOleg Nesterov 		attach_pid(p, PIDTYPE_PID);
17981da177e4SLinus Torvalds 		nr_threads++;
179973b9ebfeSOleg Nesterov 	}
180073b9ebfeSOleg Nesterov 
18011da177e4SLinus Torvalds 	total_forks++;
18023f17da69SOleg Nesterov 	spin_unlock(&current->sighand->siglock);
18034af4206bSOleg Nesterov 	syscall_tracepoint_update(p);
18041da177e4SLinus Torvalds 	write_unlock_irq(&tasklist_lock);
18054af4206bSOleg Nesterov 
1806c13cf856SAndrew Morton 	proc_fork_connector(p);
1807b53202e6SOleg Nesterov 	cgroup_post_fork(p);
1808257058aeSTejun Heo 	threadgroup_change_end(current);
1809cdd6c482SIngo Molnar 	perf_event_fork(p);
181043d2b113SKAMEZAWA Hiroyuki 
181143d2b113SKAMEZAWA Hiroyuki 	trace_task_newtask(p, clone_flags);
18123ab67966SOleg Nesterov 	uprobe_copy_process(p, clone_flags);
181343d2b113SKAMEZAWA Hiroyuki 
18141da177e4SLinus Torvalds 	return p;
18151da177e4SLinus Torvalds 
18167e47682eSAleksa Sarai bad_fork_cancel_cgroup:
1817b53202e6SOleg Nesterov 	cgroup_cancel_fork(p);
1818425fb2b4SPavel Emelyanov bad_fork_free_pid:
1819568ac888SBalbir Singh 	threadgroup_change_end(current);
1820425fb2b4SPavel Emelyanov 	if (pid != &init_struct_pid)
1821425fb2b4SPavel Emelyanov 		free_pid(pid);
18220740aa5fSJiri Slaby bad_fork_cleanup_thread:
18230740aa5fSJiri Slaby 	exit_thread(p);
1824fd0928dfSJens Axboe bad_fork_cleanup_io:
1825b69f2292SLouis Rilling 	if (p->io_context)
1826b69f2292SLouis Rilling 		exit_io_context(p);
1827ab516013SSerge E. Hallyn bad_fork_cleanup_namespaces:
1828444f378bSLinus Torvalds 	exit_task_namespaces(p);
18291da177e4SLinus Torvalds bad_fork_cleanup_mm:
1830c9f01245SDavid Rientjes 	if (p->mm)
18311da177e4SLinus Torvalds 		mmput(p->mm);
18321da177e4SLinus Torvalds bad_fork_cleanup_signal:
18334ab6c083SOleg Nesterov 	if (!(clone_flags & CLONE_THREAD))
18341c5354deSMike Galbraith 		free_signal_struct(p->signal);
18351da177e4SLinus Torvalds bad_fork_cleanup_sighand:
1836a7e5328aSOleg Nesterov 	__cleanup_sighand(p->sighand);
18371da177e4SLinus Torvalds bad_fork_cleanup_fs:
18381da177e4SLinus Torvalds 	exit_fs(p); /* blocking */
18391da177e4SLinus Torvalds bad_fork_cleanup_files:
18401da177e4SLinus Torvalds 	exit_files(p); /* blocking */
18411da177e4SLinus Torvalds bad_fork_cleanup_semundo:
18421da177e4SLinus Torvalds 	exit_sem(p);
18431da177e4SLinus Torvalds bad_fork_cleanup_audit:
18441da177e4SLinus Torvalds 	audit_free(p);
18456c72e350SPeter Zijlstra bad_fork_cleanup_perf:
1846cdd6c482SIngo Molnar 	perf_event_free_task(p);
18476c72e350SPeter Zijlstra bad_fork_cleanup_policy:
18481da177e4SLinus Torvalds #ifdef CONFIG_NUMA
1849f0be3d32SLee Schermerhorn 	mpol_put(p->mempolicy);
1850e8604cb4SLi Zefan bad_fork_cleanup_threadgroup_lock:
18511da177e4SLinus Torvalds #endif
185235df17c5SShailabh Nagar 	delayacct_tsk_free(p);
18531da177e4SLinus Torvalds bad_fork_cleanup_count:
1854d84f4f99SDavid Howells 	atomic_dec(&p->cred->user->processes);
1855e0e81739SDavid Howells 	exit_creds(p);
18561da177e4SLinus Torvalds bad_fork_free:
185768f24b08SAndy Lutomirski 	put_task_stack(p);
18581da177e4SLinus Torvalds 	free_task(p);
1859fe7d37d1SOleg Nesterov fork_out:
1860fe7d37d1SOleg Nesterov 	return ERR_PTR(retval);
18611da177e4SLinus Torvalds }
18621da177e4SLinus Torvalds 
1863f106eee1SOleg Nesterov static inline void init_idle_pids(struct pid_link *links)
1864f106eee1SOleg Nesterov {
1865f106eee1SOleg Nesterov 	enum pid_type type;
1866f106eee1SOleg Nesterov 
1867f106eee1SOleg Nesterov 	for (type = PIDTYPE_PID; type < PIDTYPE_MAX; ++type) {
1868f106eee1SOleg Nesterov 		INIT_HLIST_NODE(&links[type].node); /* not really needed */
1869f106eee1SOleg Nesterov 		links[type].pid = &init_struct_pid;
1870f106eee1SOleg Nesterov 	}
1871f106eee1SOleg Nesterov }
1872f106eee1SOleg Nesterov 
18730db0628dSPaul Gortmaker struct task_struct *fork_idle(int cpu)
18741da177e4SLinus Torvalds {
187536c8b586SIngo Molnar 	struct task_struct *task;
1876725fc629SAndi Kleen 	task = copy_process(CLONE_VM, 0, 0, NULL, &init_struct_pid, 0, 0,
1877725fc629SAndi Kleen 			    cpu_to_node(cpu));
1878f106eee1SOleg Nesterov 	if (!IS_ERR(task)) {
1879f106eee1SOleg Nesterov 		init_idle_pids(task->pids);
18801da177e4SLinus Torvalds 		init_idle(task, cpu);
1881f106eee1SOleg Nesterov 	}
188273b9ebfeSOleg Nesterov 
18831da177e4SLinus Torvalds 	return task;
18841da177e4SLinus Torvalds }
18851da177e4SLinus Torvalds 
18861da177e4SLinus Torvalds /*
18871da177e4SLinus Torvalds  *  Ok, this is the main fork-routine.
18881da177e4SLinus Torvalds  *
18891da177e4SLinus Torvalds  * It copies the process, and if successful kick-starts
18901da177e4SLinus Torvalds  * it and waits for it to finish using the VM if required.
18911da177e4SLinus Torvalds  */
18923033f14aSJosh Triplett long _do_fork(unsigned long clone_flags,
18931da177e4SLinus Torvalds 	      unsigned long stack_start,
18941da177e4SLinus Torvalds 	      unsigned long stack_size,
18951da177e4SLinus Torvalds 	      int __user *parent_tidptr,
18963033f14aSJosh Triplett 	      int __user *child_tidptr,
18973033f14aSJosh Triplett 	      unsigned long tls)
18981da177e4SLinus Torvalds {
18991da177e4SLinus Torvalds 	struct task_struct *p;
19001da177e4SLinus Torvalds 	int trace = 0;
190192476d7fSEric W. Biederman 	long nr;
19021da177e4SLinus Torvalds 
1903bdff746aSAndrew Morton 	/*
19044b9d33e6STejun Heo 	 * Determine whether and which event to report to ptracer.  When
19054b9d33e6STejun Heo 	 * called from kernel_thread or CLONE_UNTRACED is explicitly
19064b9d33e6STejun Heo 	 * requested, no event is reported; otherwise, report if the event
19074b9d33e6STejun Heo 	 * for the type of forking is enabled.
190809a05394SRoland McGrath 	 */
1909e80d6661SAl Viro 	if (!(clone_flags & CLONE_UNTRACED)) {
19104b9d33e6STejun Heo 		if (clone_flags & CLONE_VFORK)
19114b9d33e6STejun Heo 			trace = PTRACE_EVENT_VFORK;
19124b9d33e6STejun Heo 		else if ((clone_flags & CSIGNAL) != SIGCHLD)
19134b9d33e6STejun Heo 			trace = PTRACE_EVENT_CLONE;
19144b9d33e6STejun Heo 		else
19154b9d33e6STejun Heo 			trace = PTRACE_EVENT_FORK;
19164b9d33e6STejun Heo 
19174b9d33e6STejun Heo 		if (likely(!ptrace_event_enabled(current, trace)))
19184b9d33e6STejun Heo 			trace = 0;
19194b9d33e6STejun Heo 	}
19201da177e4SLinus Torvalds 
192162e791c1SAl Viro 	p = copy_process(clone_flags, stack_start, stack_size,
1922725fc629SAndi Kleen 			 child_tidptr, NULL, trace, tls, NUMA_NO_NODE);
19231da177e4SLinus Torvalds 	/*
19241da177e4SLinus Torvalds 	 * Do this prior waking up the new thread - the thread pointer
19251da177e4SLinus Torvalds 	 * might get invalid after that point, if the thread exits quickly.
19261da177e4SLinus Torvalds 	 */
19271da177e4SLinus Torvalds 	if (!IS_ERR(p)) {
19281da177e4SLinus Torvalds 		struct completion vfork;
19294e52365fSMatthew Dempsky 		struct pid *pid;
19301da177e4SLinus Torvalds 
19310a16b607SMathieu Desnoyers 		trace_sched_process_fork(current, p);
19320a16b607SMathieu Desnoyers 
19334e52365fSMatthew Dempsky 		pid = get_task_pid(p, PIDTYPE_PID);
19344e52365fSMatthew Dempsky 		nr = pid_vnr(pid);
193530e49c26SPavel Emelyanov 
193630e49c26SPavel Emelyanov 		if (clone_flags & CLONE_PARENT_SETTID)
193730e49c26SPavel Emelyanov 			put_user(nr, parent_tidptr);
1938a6f5e063SSukadev Bhattiprolu 
19391da177e4SLinus Torvalds 		if (clone_flags & CLONE_VFORK) {
19401da177e4SLinus Torvalds 			p->vfork_done = &vfork;
19411da177e4SLinus Torvalds 			init_completion(&vfork);
1942d68b46feSOleg Nesterov 			get_task_struct(p);
19431da177e4SLinus Torvalds 		}
19441da177e4SLinus Torvalds 
19453e51e3edSSamir Bellabes 		wake_up_new_task(p);
19461da177e4SLinus Torvalds 
19474b9d33e6STejun Heo 		/* forking complete and child started to run, tell ptracer */
19484b9d33e6STejun Heo 		if (unlikely(trace))
19494e52365fSMatthew Dempsky 			ptrace_event_pid(trace, pid);
195009a05394SRoland McGrath 
19511da177e4SLinus Torvalds 		if (clone_flags & CLONE_VFORK) {
1952d68b46feSOleg Nesterov 			if (!wait_for_vfork_done(p, &vfork))
19534e52365fSMatthew Dempsky 				ptrace_event_pid(PTRACE_EVENT_VFORK_DONE, pid);
19549f59ce5dSChuck Ebbert 		}
19554e52365fSMatthew Dempsky 
19564e52365fSMatthew Dempsky 		put_pid(pid);
19571da177e4SLinus Torvalds 	} else {
195892476d7fSEric W. Biederman 		nr = PTR_ERR(p);
19591da177e4SLinus Torvalds 	}
196092476d7fSEric W. Biederman 	return nr;
19611da177e4SLinus Torvalds }
19621da177e4SLinus Torvalds 
19633033f14aSJosh Triplett #ifndef CONFIG_HAVE_COPY_THREAD_TLS
19643033f14aSJosh Triplett /* For compatibility with architectures that call do_fork directly rather than
19653033f14aSJosh Triplett  * using the syscall entry points below. */
19663033f14aSJosh Triplett long do_fork(unsigned long clone_flags,
19673033f14aSJosh Triplett 	      unsigned long stack_start,
19683033f14aSJosh Triplett 	      unsigned long stack_size,
19693033f14aSJosh Triplett 	      int __user *parent_tidptr,
19703033f14aSJosh Triplett 	      int __user *child_tidptr)
19713033f14aSJosh Triplett {
19723033f14aSJosh Triplett 	return _do_fork(clone_flags, stack_start, stack_size,
19733033f14aSJosh Triplett 			parent_tidptr, child_tidptr, 0);
19743033f14aSJosh Triplett }
19753033f14aSJosh Triplett #endif
19763033f14aSJosh Triplett 
19772aa3a7f8SAl Viro /*
19782aa3a7f8SAl Viro  * Create a kernel thread.
19792aa3a7f8SAl Viro  */
19802aa3a7f8SAl Viro pid_t kernel_thread(int (*fn)(void *), void *arg, unsigned long flags)
19812aa3a7f8SAl Viro {
19823033f14aSJosh Triplett 	return _do_fork(flags|CLONE_VM|CLONE_UNTRACED, (unsigned long)fn,
19833033f14aSJosh Triplett 		(unsigned long)arg, NULL, NULL, 0);
19842aa3a7f8SAl Viro }
19852aa3a7f8SAl Viro 
1986d2125043SAl Viro #ifdef __ARCH_WANT_SYS_FORK
1987d2125043SAl Viro SYSCALL_DEFINE0(fork)
1988d2125043SAl Viro {
1989d2125043SAl Viro #ifdef CONFIG_MMU
19903033f14aSJosh Triplett 	return _do_fork(SIGCHLD, 0, 0, NULL, NULL, 0);
1991d2125043SAl Viro #else
1992d2125043SAl Viro 	/* can not support in nommu mode */
19935d59e182SDaeseok Youn 	return -EINVAL;
1994d2125043SAl Viro #endif
1995d2125043SAl Viro }
1996d2125043SAl Viro #endif
1997d2125043SAl Viro 
1998d2125043SAl Viro #ifdef __ARCH_WANT_SYS_VFORK
1999d2125043SAl Viro SYSCALL_DEFINE0(vfork)
2000d2125043SAl Viro {
20013033f14aSJosh Triplett 	return _do_fork(CLONE_VFORK | CLONE_VM | SIGCHLD, 0,
20023033f14aSJosh Triplett 			0, NULL, NULL, 0);
2003d2125043SAl Viro }
2004d2125043SAl Viro #endif
2005d2125043SAl Viro 
2006d2125043SAl Viro #ifdef __ARCH_WANT_SYS_CLONE
2007d2125043SAl Viro #ifdef CONFIG_CLONE_BACKWARDS
2008d2125043SAl Viro SYSCALL_DEFINE5(clone, unsigned long, clone_flags, unsigned long, newsp,
2009d2125043SAl Viro 		 int __user *, parent_tidptr,
20103033f14aSJosh Triplett 		 unsigned long, tls,
2011d2125043SAl Viro 		 int __user *, child_tidptr)
2012d2125043SAl Viro #elif defined(CONFIG_CLONE_BACKWARDS2)
2013d2125043SAl Viro SYSCALL_DEFINE5(clone, unsigned long, newsp, unsigned long, clone_flags,
2014d2125043SAl Viro 		 int __user *, parent_tidptr,
2015d2125043SAl Viro 		 int __user *, child_tidptr,
20163033f14aSJosh Triplett 		 unsigned long, tls)
2017dfa9771aSMichal Simek #elif defined(CONFIG_CLONE_BACKWARDS3)
2018dfa9771aSMichal Simek SYSCALL_DEFINE6(clone, unsigned long, clone_flags, unsigned long, newsp,
2019dfa9771aSMichal Simek 		int, stack_size,
2020dfa9771aSMichal Simek 		int __user *, parent_tidptr,
2021dfa9771aSMichal Simek 		int __user *, child_tidptr,
20223033f14aSJosh Triplett 		unsigned long, tls)
2023d2125043SAl Viro #else
2024d2125043SAl Viro SYSCALL_DEFINE5(clone, unsigned long, clone_flags, unsigned long, newsp,
2025d2125043SAl Viro 		 int __user *, parent_tidptr,
2026d2125043SAl Viro 		 int __user *, child_tidptr,
20273033f14aSJosh Triplett 		 unsigned long, tls)
2028d2125043SAl Viro #endif
2029d2125043SAl Viro {
20303033f14aSJosh Triplett 	return _do_fork(clone_flags, newsp, 0, parent_tidptr, child_tidptr, tls);
2031d2125043SAl Viro }
2032d2125043SAl Viro #endif
2033d2125043SAl Viro 
20345fd63b30SRavikiran G Thirumalai #ifndef ARCH_MIN_MMSTRUCT_ALIGN
20355fd63b30SRavikiran G Thirumalai #define ARCH_MIN_MMSTRUCT_ALIGN 0
20365fd63b30SRavikiran G Thirumalai #endif
20375fd63b30SRavikiran G Thirumalai 
203851cc5068SAlexey Dobriyan static void sighand_ctor(void *data)
2039aa1757f9SOleg Nesterov {
2040aa1757f9SOleg Nesterov 	struct sighand_struct *sighand = data;
2041aa1757f9SOleg Nesterov 
2042aa1757f9SOleg Nesterov 	spin_lock_init(&sighand->siglock);
2043b8fceee1SDavide Libenzi 	init_waitqueue_head(&sighand->signalfd_wqh);
2044fba2afaaSDavide Libenzi }
2045aa1757f9SOleg Nesterov 
20461da177e4SLinus Torvalds void __init proc_caches_init(void)
20471da177e4SLinus Torvalds {
20481da177e4SLinus Torvalds 	sighand_cachep = kmem_cache_create("sighand_cache",
20491da177e4SLinus Torvalds 			sizeof(struct sighand_struct), 0,
20502dff4405SVegard Nossum 			SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_DESTROY_BY_RCU|
20515d097056SVladimir Davydov 			SLAB_NOTRACK|SLAB_ACCOUNT, sighand_ctor);
20521da177e4SLinus Torvalds 	signal_cachep = kmem_cache_create("signal_cache",
20531da177e4SLinus Torvalds 			sizeof(struct signal_struct), 0,
20545d097056SVladimir Davydov 			SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_NOTRACK|SLAB_ACCOUNT,
20555d097056SVladimir Davydov 			NULL);
20561da177e4SLinus Torvalds 	files_cachep = kmem_cache_create("files_cache",
20571da177e4SLinus Torvalds 			sizeof(struct files_struct), 0,
20585d097056SVladimir Davydov 			SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_NOTRACK|SLAB_ACCOUNT,
20595d097056SVladimir Davydov 			NULL);
20601da177e4SLinus Torvalds 	fs_cachep = kmem_cache_create("fs_cache",
20611da177e4SLinus Torvalds 			sizeof(struct fs_struct), 0,
20625d097056SVladimir Davydov 			SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_NOTRACK|SLAB_ACCOUNT,
20635d097056SVladimir Davydov 			NULL);
20646345d24dSLinus Torvalds 	/*
20656345d24dSLinus Torvalds 	 * FIXME! The "sizeof(struct mm_struct)" currently includes the
20666345d24dSLinus Torvalds 	 * whole struct cpumask for the OFFSTACK case. We could change
20676345d24dSLinus Torvalds 	 * this to *only* allocate as much of it as required by the
20686345d24dSLinus Torvalds 	 * maximum number of CPU's we can ever have.  The cpumask_allocation
20696345d24dSLinus Torvalds 	 * is at the end of the structure, exactly for that reason.
20706345d24dSLinus Torvalds 	 */
20711da177e4SLinus Torvalds 	mm_cachep = kmem_cache_create("mm_struct",
20725fd63b30SRavikiran G Thirumalai 			sizeof(struct mm_struct), ARCH_MIN_MMSTRUCT_ALIGN,
20735d097056SVladimir Davydov 			SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_NOTRACK|SLAB_ACCOUNT,
20745d097056SVladimir Davydov 			NULL);
20755d097056SVladimir Davydov 	vm_area_cachep = KMEM_CACHE(vm_area_struct, SLAB_PANIC|SLAB_ACCOUNT);
20768feae131SDavid Howells 	mmap_init();
207766577193SAl Viro 	nsproxy_cache_init();
20781da177e4SLinus Torvalds }
2079cf2e340fSJANAK DESAI 
2080cf2e340fSJANAK DESAI /*
20819bfb23fcSOleg Nesterov  * Check constraints on flags passed to the unshare system call.
2082cf2e340fSJANAK DESAI  */
20839bfb23fcSOleg Nesterov static int check_unshare_flags(unsigned long unshare_flags)
2084cf2e340fSJANAK DESAI {
20859bfb23fcSOleg Nesterov 	if (unshare_flags & ~(CLONE_THREAD|CLONE_FS|CLONE_NEWNS|CLONE_SIGHAND|
20869bfb23fcSOleg Nesterov 				CLONE_VM|CLONE_FILES|CLONE_SYSVSEM|
208750804fe3SEric W. Biederman 				CLONE_NEWUTS|CLONE_NEWIPC|CLONE_NEWNET|
2088a79a908fSAditya Kali 				CLONE_NEWUSER|CLONE_NEWPID|CLONE_NEWCGROUP))
2089cf2e340fSJANAK DESAI 		return -EINVAL;
20909bfb23fcSOleg Nesterov 	/*
209112c641abSEric W. Biederman 	 * Not implemented, but pretend it works if there is nothing
209212c641abSEric W. Biederman 	 * to unshare.  Note that unsharing the address space or the
209312c641abSEric W. Biederman 	 * signal handlers also need to unshare the signal queues (aka
209412c641abSEric W. Biederman 	 * CLONE_THREAD).
20959bfb23fcSOleg Nesterov 	 */
20969bfb23fcSOleg Nesterov 	if (unshare_flags & (CLONE_THREAD | CLONE_SIGHAND | CLONE_VM)) {
209712c641abSEric W. Biederman 		if (!thread_group_empty(current))
209812c641abSEric W. Biederman 			return -EINVAL;
209912c641abSEric W. Biederman 	}
210012c641abSEric W. Biederman 	if (unshare_flags & (CLONE_SIGHAND | CLONE_VM)) {
210112c641abSEric W. Biederman 		if (atomic_read(&current->sighand->count) > 1)
210212c641abSEric W. Biederman 			return -EINVAL;
210312c641abSEric W. Biederman 	}
210412c641abSEric W. Biederman 	if (unshare_flags & CLONE_VM) {
210512c641abSEric W. Biederman 		if (!current_is_single_threaded())
21069bfb23fcSOleg Nesterov 			return -EINVAL;
21079bfb23fcSOleg Nesterov 	}
2108cf2e340fSJANAK DESAI 
2109cf2e340fSJANAK DESAI 	return 0;
2110cf2e340fSJANAK DESAI }
2111cf2e340fSJANAK DESAI 
2112cf2e340fSJANAK DESAI /*
211399d1419dSJANAK DESAI  * Unshare the filesystem structure if it is being shared
2114cf2e340fSJANAK DESAI  */
2115cf2e340fSJANAK DESAI static int unshare_fs(unsigned long unshare_flags, struct fs_struct **new_fsp)
2116cf2e340fSJANAK DESAI {
2117cf2e340fSJANAK DESAI 	struct fs_struct *fs = current->fs;
2118cf2e340fSJANAK DESAI 
2119498052bbSAl Viro 	if (!(unshare_flags & CLONE_FS) || !fs)
2120498052bbSAl Viro 		return 0;
2121498052bbSAl Viro 
2122498052bbSAl Viro 	/* don't need lock here; in the worst case we'll do useless copy */
2123498052bbSAl Viro 	if (fs->users == 1)
2124498052bbSAl Viro 		return 0;
2125498052bbSAl Viro 
2126498052bbSAl Viro 	*new_fsp = copy_fs_struct(fs);
212799d1419dSJANAK DESAI 	if (!*new_fsp)
212899d1419dSJANAK DESAI 		return -ENOMEM;
2129cf2e340fSJANAK DESAI 
2130cf2e340fSJANAK DESAI 	return 0;
2131cf2e340fSJANAK DESAI }
2132cf2e340fSJANAK DESAI 
2133cf2e340fSJANAK DESAI /*
2134a016f338SJANAK DESAI  * Unshare file descriptor table if it is being shared
2135cf2e340fSJANAK DESAI  */
2136cf2e340fSJANAK DESAI static int unshare_fd(unsigned long unshare_flags, struct files_struct **new_fdp)
2137cf2e340fSJANAK DESAI {
2138cf2e340fSJANAK DESAI 	struct files_struct *fd = current->files;
2139a016f338SJANAK DESAI 	int error = 0;
2140cf2e340fSJANAK DESAI 
2141cf2e340fSJANAK DESAI 	if ((unshare_flags & CLONE_FILES) &&
2142a016f338SJANAK DESAI 	    (fd && atomic_read(&fd->count) > 1)) {
2143a016f338SJANAK DESAI 		*new_fdp = dup_fd(fd, &error);
2144a016f338SJANAK DESAI 		if (!*new_fdp)
2145a016f338SJANAK DESAI 			return error;
2146a016f338SJANAK DESAI 	}
2147cf2e340fSJANAK DESAI 
2148cf2e340fSJANAK DESAI 	return 0;
2149cf2e340fSJANAK DESAI }
2150cf2e340fSJANAK DESAI 
2151cf2e340fSJANAK DESAI /*
2152cf2e340fSJANAK DESAI  * unshare allows a process to 'unshare' part of the process
2153cf2e340fSJANAK DESAI  * context which was originally shared using clone.  copy_*
2154cf2e340fSJANAK DESAI  * functions used by do_fork() cannot be used here directly
2155cf2e340fSJANAK DESAI  * because they modify an inactive task_struct that is being
2156cf2e340fSJANAK DESAI  * constructed. Here we are modifying the current, active,
2157cf2e340fSJANAK DESAI  * task_struct.
2158cf2e340fSJANAK DESAI  */
21596559eed8SHeiko Carstens SYSCALL_DEFINE1(unshare, unsigned long, unshare_flags)
2160cf2e340fSJANAK DESAI {
2161cf2e340fSJANAK DESAI 	struct fs_struct *fs, *new_fs = NULL;
2162cf2e340fSJANAK DESAI 	struct files_struct *fd, *new_fd = NULL;
2163b2e0d987SEric W. Biederman 	struct cred *new_cred = NULL;
2164cf7b708cSPavel Emelyanov 	struct nsproxy *new_nsproxy = NULL;
21659edff4abSManfred Spraul 	int do_sysvsem = 0;
21669bfb23fcSOleg Nesterov 	int err;
2167cf2e340fSJANAK DESAI 
216850804fe3SEric W. Biederman 	/*
2169faf00da5SEric W. Biederman 	 * If unsharing a user namespace must also unshare the thread group
2170faf00da5SEric W. Biederman 	 * and unshare the filesystem root and working directories.
2171b2e0d987SEric W. Biederman 	 */
2172b2e0d987SEric W. Biederman 	if (unshare_flags & CLONE_NEWUSER)
2173e66eded8SEric W. Biederman 		unshare_flags |= CLONE_THREAD | CLONE_FS;
2174b2e0d987SEric W. Biederman 	/*
217550804fe3SEric W. Biederman 	 * If unsharing vm, must also unshare signal handlers.
217650804fe3SEric W. Biederman 	 */
217750804fe3SEric W. Biederman 	if (unshare_flags & CLONE_VM)
217850804fe3SEric W. Biederman 		unshare_flags |= CLONE_SIGHAND;
21796013f67fSManfred Spraul 	/*
218012c641abSEric W. Biederman 	 * If unsharing a signal handlers, must also unshare the signal queues.
218112c641abSEric W. Biederman 	 */
218212c641abSEric W. Biederman 	if (unshare_flags & CLONE_SIGHAND)
218312c641abSEric W. Biederman 		unshare_flags |= CLONE_THREAD;
218412c641abSEric W. Biederman 	/*
21859bfb23fcSOleg Nesterov 	 * If unsharing namespace, must also unshare filesystem information.
21869bfb23fcSOleg Nesterov 	 */
21879bfb23fcSOleg Nesterov 	if (unshare_flags & CLONE_NEWNS)
21889bfb23fcSOleg Nesterov 		unshare_flags |= CLONE_FS;
218950804fe3SEric W. Biederman 
219050804fe3SEric W. Biederman 	err = check_unshare_flags(unshare_flags);
219150804fe3SEric W. Biederman 	if (err)
219250804fe3SEric W. Biederman 		goto bad_unshare_out;
21939bfb23fcSOleg Nesterov 	/*
21946013f67fSManfred Spraul 	 * CLONE_NEWIPC must also detach from the undolist: after switching
21956013f67fSManfred Spraul 	 * to a new ipc namespace, the semaphore arrays from the old
21966013f67fSManfred Spraul 	 * namespace are unreachable.
21976013f67fSManfred Spraul 	 */
21986013f67fSManfred Spraul 	if (unshare_flags & (CLONE_NEWIPC|CLONE_SYSVSEM))
21999edff4abSManfred Spraul 		do_sysvsem = 1;
2200fb0a685cSDaniel Rebelo de Oliveira 	err = unshare_fs(unshare_flags, &new_fs);
2201fb0a685cSDaniel Rebelo de Oliveira 	if (err)
22029bfb23fcSOleg Nesterov 		goto bad_unshare_out;
2203fb0a685cSDaniel Rebelo de Oliveira 	err = unshare_fd(unshare_flags, &new_fd);
2204fb0a685cSDaniel Rebelo de Oliveira 	if (err)
22059bfb23fcSOleg Nesterov 		goto bad_unshare_cleanup_fs;
2206b2e0d987SEric W. Biederman 	err = unshare_userns(unshare_flags, &new_cred);
2207fb0a685cSDaniel Rebelo de Oliveira 	if (err)
22089edff4abSManfred Spraul 		goto bad_unshare_cleanup_fd;
2209b2e0d987SEric W. Biederman 	err = unshare_nsproxy_namespaces(unshare_flags, &new_nsproxy,
2210b2e0d987SEric W. Biederman 					 new_cred, new_fs);
2211b2e0d987SEric W. Biederman 	if (err)
2212b2e0d987SEric W. Biederman 		goto bad_unshare_cleanup_cred;
2213cf2e340fSJANAK DESAI 
2214b2e0d987SEric W. Biederman 	if (new_fs || new_fd || do_sysvsem || new_cred || new_nsproxy) {
22159edff4abSManfred Spraul 		if (do_sysvsem) {
22169edff4abSManfred Spraul 			/*
22179edff4abSManfred Spraul 			 * CLONE_SYSVSEM is equivalent to sys_exit().
22189edff4abSManfred Spraul 			 */
22199edff4abSManfred Spraul 			exit_sem(current);
22209edff4abSManfred Spraul 		}
2221ab602f79SJack Miller 		if (unshare_flags & CLONE_NEWIPC) {
2222ab602f79SJack Miller 			/* Orphan segments in old ns (see sem above). */
2223ab602f79SJack Miller 			exit_shm(current);
2224ab602f79SJack Miller 			shm_init_task(current);
2225ab602f79SJack Miller 		}
2226ab516013SSerge E. Hallyn 
22276f977e6bSAlan Cox 		if (new_nsproxy)
2228cf7b708cSPavel Emelyanov 			switch_task_namespaces(current, new_nsproxy);
2229cf2e340fSJANAK DESAI 
2230cf7b708cSPavel Emelyanov 		task_lock(current);
2231cf7b708cSPavel Emelyanov 
2232cf2e340fSJANAK DESAI 		if (new_fs) {
2233cf2e340fSJANAK DESAI 			fs = current->fs;
22342a4419b5SNick Piggin 			spin_lock(&fs->lock);
2235cf2e340fSJANAK DESAI 			current->fs = new_fs;
2236498052bbSAl Viro 			if (--fs->users)
2237498052bbSAl Viro 				new_fs = NULL;
2238498052bbSAl Viro 			else
2239cf2e340fSJANAK DESAI 				new_fs = fs;
22402a4419b5SNick Piggin 			spin_unlock(&fs->lock);
2241cf2e340fSJANAK DESAI 		}
2242cf2e340fSJANAK DESAI 
2243cf2e340fSJANAK DESAI 		if (new_fd) {
2244cf2e340fSJANAK DESAI 			fd = current->files;
2245cf2e340fSJANAK DESAI 			current->files = new_fd;
2246cf2e340fSJANAK DESAI 			new_fd = fd;
2247cf2e340fSJANAK DESAI 		}
2248cf2e340fSJANAK DESAI 
2249cf2e340fSJANAK DESAI 		task_unlock(current);
2250b2e0d987SEric W. Biederman 
2251b2e0d987SEric W. Biederman 		if (new_cred) {
2252b2e0d987SEric W. Biederman 			/* Install the new user namespace */
2253b2e0d987SEric W. Biederman 			commit_creds(new_cred);
2254b2e0d987SEric W. Biederman 			new_cred = NULL;
2255b2e0d987SEric W. Biederman 		}
2256cf2e340fSJANAK DESAI 	}
2257cf2e340fSJANAK DESAI 
2258b2e0d987SEric W. Biederman bad_unshare_cleanup_cred:
2259b2e0d987SEric W. Biederman 	if (new_cred)
2260b2e0d987SEric W. Biederman 		put_cred(new_cred);
2261cf2e340fSJANAK DESAI bad_unshare_cleanup_fd:
2262cf2e340fSJANAK DESAI 	if (new_fd)
2263cf2e340fSJANAK DESAI 		put_files_struct(new_fd);
2264cf2e340fSJANAK DESAI 
2265cf2e340fSJANAK DESAI bad_unshare_cleanup_fs:
2266cf2e340fSJANAK DESAI 	if (new_fs)
2267498052bbSAl Viro 		free_fs_struct(new_fs);
2268cf2e340fSJANAK DESAI 
2269cf2e340fSJANAK DESAI bad_unshare_out:
2270cf2e340fSJANAK DESAI 	return err;
2271cf2e340fSJANAK DESAI }
22723b125388SAl Viro 
22733b125388SAl Viro /*
22743b125388SAl Viro  *	Helper to unshare the files of the current task.
22753b125388SAl Viro  *	We don't want to expose copy_files internals to
22763b125388SAl Viro  *	the exec layer of the kernel.
22773b125388SAl Viro  */
22783b125388SAl Viro 
22793b125388SAl Viro int unshare_files(struct files_struct **displaced)
22803b125388SAl Viro {
22813b125388SAl Viro 	struct task_struct *task = current;
228250704516SAl Viro 	struct files_struct *copy = NULL;
22833b125388SAl Viro 	int error;
22843b125388SAl Viro 
22853b125388SAl Viro 	error = unshare_fd(CLONE_FILES, &copy);
22863b125388SAl Viro 	if (error || !copy) {
22873b125388SAl Viro 		*displaced = NULL;
22883b125388SAl Viro 		return error;
22893b125388SAl Viro 	}
22903b125388SAl Viro 	*displaced = task->files;
22913b125388SAl Viro 	task_lock(task);
22923b125388SAl Viro 	task->files = copy;
22933b125388SAl Viro 	task_unlock(task);
22943b125388SAl Viro 	return 0;
22953b125388SAl Viro }
229616db3d3fSHeinrich Schuchardt 
229716db3d3fSHeinrich Schuchardt int sysctl_max_threads(struct ctl_table *table, int write,
229816db3d3fSHeinrich Schuchardt 		       void __user *buffer, size_t *lenp, loff_t *ppos)
229916db3d3fSHeinrich Schuchardt {
230016db3d3fSHeinrich Schuchardt 	struct ctl_table t;
230116db3d3fSHeinrich Schuchardt 	int ret;
230216db3d3fSHeinrich Schuchardt 	int threads = max_threads;
230316db3d3fSHeinrich Schuchardt 	int min = MIN_THREADS;
230416db3d3fSHeinrich Schuchardt 	int max = MAX_THREADS;
230516db3d3fSHeinrich Schuchardt 
230616db3d3fSHeinrich Schuchardt 	t = *table;
230716db3d3fSHeinrich Schuchardt 	t.data = &threads;
230816db3d3fSHeinrich Schuchardt 	t.extra1 = &min;
230916db3d3fSHeinrich Schuchardt 	t.extra2 = &max;
231016db3d3fSHeinrich Schuchardt 
231116db3d3fSHeinrich Schuchardt 	ret = proc_dointvec_minmax(&t, write, buffer, lenp, ppos);
231216db3d3fSHeinrich Schuchardt 	if (ret || !write)
231316db3d3fSHeinrich Schuchardt 		return ret;
231416db3d3fSHeinrich Schuchardt 
231516db3d3fSHeinrich Schuchardt 	set_max_threads(threads);
231616db3d3fSHeinrich Schuchardt 
231716db3d3fSHeinrich Schuchardt 	return 0;
231816db3d3fSHeinrich Schuchardt }
2319