xref: /openbmc/linux/kernel/fork.c (revision ba14a194a434ccc8f733e263ad2ce941e35e5787)
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  */
161*ba14a194SAndy Lutomirski # if THREAD_SIZE >= PAGE_SIZE || defined(CONFIG_VMAP_STACK)
162*ba14a194SAndy Lutomirski static unsigned long *alloc_thread_stack_node(struct task_struct *tsk, int node)
163b69c49b7SFUJITA Tomonori {
164*ba14a194SAndy Lutomirski #ifdef CONFIG_VMAP_STACK
165*ba14a194SAndy Lutomirski 	void *stack = __vmalloc_node_range(THREAD_SIZE, THREAD_SIZE,
166*ba14a194SAndy Lutomirski 					   VMALLOC_START, VMALLOC_END,
167*ba14a194SAndy Lutomirski 					   THREADINFO_GFP | __GFP_HIGHMEM,
168*ba14a194SAndy Lutomirski 					   PAGE_KERNEL,
169*ba14a194SAndy Lutomirski 					   0, node,
170*ba14a194SAndy Lutomirski 					   __builtin_return_address(0));
171*ba14a194SAndy Lutomirski 
172*ba14a194SAndy Lutomirski 	/*
173*ba14a194SAndy Lutomirski 	 * We can't call find_vm_area() in interrupt context, and
174*ba14a194SAndy Lutomirski 	 * free_thread_stack() can be called in interrupt context,
175*ba14a194SAndy Lutomirski 	 * so cache the vm_struct.
176*ba14a194SAndy Lutomirski 	 */
177*ba14a194SAndy Lutomirski 	if (stack)
178*ba14a194SAndy Lutomirski 		tsk->stack_vm_area = find_vm_area(stack);
179*ba14a194SAndy Lutomirski 	return stack;
180*ba14a194SAndy Lutomirski #else
1814949148aSVladimir Davydov 	struct page *page = alloc_pages_node(node, THREADINFO_GFP,
1822889f608SThomas Gleixner 					     THREAD_SIZE_ORDER);
183b6a84016SEric Dumazet 
184b6a84016SEric Dumazet 	return page ? page_address(page) : NULL;
185*ba14a194SAndy Lutomirski #endif
186b69c49b7SFUJITA Tomonori }
187b69c49b7SFUJITA Tomonori 
188*ba14a194SAndy Lutomirski static inline void free_thread_stack(struct task_struct *tsk)
189b69c49b7SFUJITA Tomonori {
190*ba14a194SAndy Lutomirski 	if (task_stack_vm_area(tsk))
191*ba14a194SAndy Lutomirski 		vfree(tsk->stack);
192*ba14a194SAndy Lutomirski 	else
193*ba14a194SAndy Lutomirski 		__free_pages(virt_to_page(tsk->stack), THREAD_SIZE_ORDER);
194b69c49b7SFUJITA Tomonori }
1950d15d74aSThomas Gleixner # else
196b235beeaSLinus Torvalds static struct kmem_cache *thread_stack_cache;
1970d15d74aSThomas Gleixner 
1989521d399SMichael Ellerman static unsigned long *alloc_thread_stack_node(struct task_struct *tsk,
1990d15d74aSThomas Gleixner 						  int node)
2000d15d74aSThomas Gleixner {
201b235beeaSLinus Torvalds 	return kmem_cache_alloc_node(thread_stack_cache, THREADINFO_GFP, node);
2020d15d74aSThomas Gleixner }
2030d15d74aSThomas Gleixner 
204*ba14a194SAndy Lutomirski static void free_thread_stack(struct task_struct *tsk)
2050d15d74aSThomas Gleixner {
206*ba14a194SAndy Lutomirski 	kmem_cache_free(thread_stack_cache, tsk->stack);
2070d15d74aSThomas Gleixner }
2080d15d74aSThomas Gleixner 
209b235beeaSLinus Torvalds void thread_stack_cache_init(void)
2100d15d74aSThomas Gleixner {
211b235beeaSLinus Torvalds 	thread_stack_cache = kmem_cache_create("thread_stack", THREAD_SIZE,
2120d15d74aSThomas Gleixner 					      THREAD_SIZE, 0, NULL);
213b235beeaSLinus Torvalds 	BUG_ON(thread_stack_cache == NULL);
2140d15d74aSThomas Gleixner }
2150d15d74aSThomas Gleixner # endif
216b69c49b7SFUJITA Tomonori #endif
217b69c49b7SFUJITA Tomonori 
2181da177e4SLinus Torvalds /* SLAB cache for signal_struct structures (tsk->signal) */
219e18b890bSChristoph Lameter static struct kmem_cache *signal_cachep;
2201da177e4SLinus Torvalds 
2211da177e4SLinus Torvalds /* SLAB cache for sighand_struct structures (tsk->sighand) */
222e18b890bSChristoph Lameter struct kmem_cache *sighand_cachep;
2231da177e4SLinus Torvalds 
2241da177e4SLinus Torvalds /* SLAB cache for files_struct structures (tsk->files) */
225e18b890bSChristoph Lameter struct kmem_cache *files_cachep;
2261da177e4SLinus Torvalds 
2271da177e4SLinus Torvalds /* SLAB cache for fs_struct structures (tsk->fs) */
228e18b890bSChristoph Lameter struct kmem_cache *fs_cachep;
2291da177e4SLinus Torvalds 
2301da177e4SLinus Torvalds /* SLAB cache for vm_area_struct structures */
231e18b890bSChristoph Lameter struct kmem_cache *vm_area_cachep;
2321da177e4SLinus Torvalds 
2331da177e4SLinus Torvalds /* SLAB cache for mm_struct structures (tsk->mm) */
234e18b890bSChristoph Lameter static struct kmem_cache *mm_cachep;
2351da177e4SLinus Torvalds 
236*ba14a194SAndy Lutomirski static void account_kernel_stack(struct task_struct *tsk, int account)
237c6a7f572SKOSAKI Motohiro {
238*ba14a194SAndy Lutomirski 	void *stack = task_stack_page(tsk);
239*ba14a194SAndy Lutomirski 	struct vm_struct *vm = task_stack_vm_area(tsk);
240*ba14a194SAndy Lutomirski 
241*ba14a194SAndy Lutomirski 	BUILD_BUG_ON(IS_ENABLED(CONFIG_VMAP_STACK) && PAGE_SIZE % 1024 != 0);
242*ba14a194SAndy Lutomirski 
243*ba14a194SAndy Lutomirski 	if (vm) {
244*ba14a194SAndy Lutomirski 		int i;
245*ba14a194SAndy Lutomirski 
246*ba14a194SAndy Lutomirski 		BUG_ON(vm->nr_pages != THREAD_SIZE / PAGE_SIZE);
247*ba14a194SAndy Lutomirski 
248*ba14a194SAndy Lutomirski 		for (i = 0; i < THREAD_SIZE / PAGE_SIZE; i++) {
249*ba14a194SAndy Lutomirski 			mod_zone_page_state(page_zone(vm->pages[i]),
250*ba14a194SAndy Lutomirski 					    NR_KERNEL_STACK_KB,
251*ba14a194SAndy Lutomirski 					    PAGE_SIZE / 1024 * account);
252*ba14a194SAndy Lutomirski 		}
253*ba14a194SAndy Lutomirski 
254*ba14a194SAndy Lutomirski 		/* All stack pages belong to the same memcg. */
255*ba14a194SAndy Lutomirski 		memcg_kmem_update_page_stat(vm->pages[0], MEMCG_KERNEL_STACK_KB,
256*ba14a194SAndy Lutomirski 					    account * (THREAD_SIZE / 1024));
257*ba14a194SAndy Lutomirski 	} else {
258*ba14a194SAndy Lutomirski 		/*
259*ba14a194SAndy Lutomirski 		 * All stack pages are in the same zone and belong to the
260*ba14a194SAndy Lutomirski 		 * same memcg.
261*ba14a194SAndy Lutomirski 		 */
262efdc9490SAndy Lutomirski 		struct page *first_page = virt_to_page(stack);
263c6a7f572SKOSAKI Motohiro 
264efdc9490SAndy Lutomirski 		mod_zone_page_state(page_zone(first_page), NR_KERNEL_STACK_KB,
265d30dd8beSAndy Lutomirski 				    THREAD_SIZE / 1024 * account);
266efdc9490SAndy Lutomirski 
267*ba14a194SAndy Lutomirski 		memcg_kmem_update_page_stat(first_page, MEMCG_KERNEL_STACK_KB,
268efdc9490SAndy Lutomirski 					    account * (THREAD_SIZE / 1024));
269c6a7f572SKOSAKI Motohiro 	}
270*ba14a194SAndy Lutomirski }
271c6a7f572SKOSAKI Motohiro 
2721da177e4SLinus Torvalds void free_task(struct task_struct *tsk)
2731da177e4SLinus Torvalds {
274*ba14a194SAndy Lutomirski 	account_kernel_stack(tsk, -1);
275b235beeaSLinus Torvalds 	arch_release_thread_stack(tsk->stack);
276*ba14a194SAndy Lutomirski 	free_thread_stack(tsk);
27723f78d4aSIngo Molnar 	rt_mutex_debug_task_free(tsk);
278fb52607aSFrederic Weisbecker 	ftrace_graph_exit_task(tsk);
279e2cfabdfSWill Drewry 	put_seccomp_filter(tsk);
280f19b9f74SAkinobu Mita 	arch_release_task_struct(tsk);
2811da177e4SLinus Torvalds 	free_task_struct(tsk);
2821da177e4SLinus Torvalds }
2831da177e4SLinus Torvalds EXPORT_SYMBOL(free_task);
2841da177e4SLinus Torvalds 
285ea6d290cSOleg Nesterov static inline void free_signal_struct(struct signal_struct *sig)
286ea6d290cSOleg Nesterov {
28797101eb4SOleg Nesterov 	taskstats_tgid_free(sig);
2881c5354deSMike Galbraith 	sched_autogroup_exit(sig);
289ea6d290cSOleg Nesterov 	kmem_cache_free(signal_cachep, sig);
290ea6d290cSOleg Nesterov }
291ea6d290cSOleg Nesterov 
292ea6d290cSOleg Nesterov static inline void put_signal_struct(struct signal_struct *sig)
293ea6d290cSOleg Nesterov {
2941c5354deSMike Galbraith 	if (atomic_dec_and_test(&sig->sigcnt))
295ea6d290cSOleg Nesterov 		free_signal_struct(sig);
296ea6d290cSOleg Nesterov }
297ea6d290cSOleg Nesterov 
298158d9ebdSAndrew Morton void __put_task_struct(struct task_struct *tsk)
2991da177e4SLinus Torvalds {
300270f722dSEugene Teo 	WARN_ON(!tsk->exit_state);
3011da177e4SLinus Torvalds 	WARN_ON(atomic_read(&tsk->usage));
3021da177e4SLinus Torvalds 	WARN_ON(tsk == current);
3031da177e4SLinus Torvalds 
3042e91fa7fSTejun Heo 	cgroup_free(tsk);
305156654f4SMike Galbraith 	task_numa_free(tsk);
3061a2a4d06SKees Cook 	security_task_free(tsk);
307e0e81739SDavid Howells 	exit_creds(tsk);
30835df17c5SShailabh Nagar 	delayacct_tsk_free(tsk);
309ea6d290cSOleg Nesterov 	put_signal_struct(tsk->signal);
3101da177e4SLinus Torvalds 
3111da177e4SLinus Torvalds 	if (!profile_handoff_task(tsk))
3121da177e4SLinus Torvalds 		free_task(tsk);
3131da177e4SLinus Torvalds }
31477c100c8SRik van Riel EXPORT_SYMBOL_GPL(__put_task_struct);
3151da177e4SLinus Torvalds 
3166c0a9fa6SThomas Gleixner void __init __weak arch_task_cache_init(void) { }
31761c4628bSSuresh Siddha 
318ff691f6eSHeinrich Schuchardt /*
319ff691f6eSHeinrich Schuchardt  * set_max_threads
320ff691f6eSHeinrich Schuchardt  */
32116db3d3fSHeinrich Schuchardt static void set_max_threads(unsigned int max_threads_suggested)
322ff691f6eSHeinrich Schuchardt {
323ac1b398dSHeinrich Schuchardt 	u64 threads;
324ff691f6eSHeinrich Schuchardt 
325ff691f6eSHeinrich Schuchardt 	/*
326ac1b398dSHeinrich Schuchardt 	 * The number of threads shall be limited such that the thread
327ac1b398dSHeinrich Schuchardt 	 * structures may only consume a small part of the available memory.
328ff691f6eSHeinrich Schuchardt 	 */
329ac1b398dSHeinrich Schuchardt 	if (fls64(totalram_pages) + fls64(PAGE_SIZE) > 64)
330ac1b398dSHeinrich Schuchardt 		threads = MAX_THREADS;
331ac1b398dSHeinrich Schuchardt 	else
332ac1b398dSHeinrich Schuchardt 		threads = div64_u64((u64) totalram_pages * (u64) PAGE_SIZE,
333ac1b398dSHeinrich Schuchardt 				    (u64) THREAD_SIZE * 8UL);
334ac1b398dSHeinrich Schuchardt 
33516db3d3fSHeinrich Schuchardt 	if (threads > max_threads_suggested)
33616db3d3fSHeinrich Schuchardt 		threads = max_threads_suggested;
33716db3d3fSHeinrich Schuchardt 
338ac1b398dSHeinrich Schuchardt 	max_threads = clamp_t(u64, threads, MIN_THREADS, MAX_THREADS);
339ff691f6eSHeinrich Schuchardt }
340ff691f6eSHeinrich Schuchardt 
3415aaeb5c0SIngo Molnar #ifdef CONFIG_ARCH_WANTS_DYNAMIC_TASK_STRUCT
3425aaeb5c0SIngo Molnar /* Initialized by the architecture: */
3435aaeb5c0SIngo Molnar int arch_task_struct_size __read_mostly;
3445aaeb5c0SIngo Molnar #endif
3450c8c0f03SDave Hansen 
346ff691f6eSHeinrich Schuchardt void __init fork_init(void)
3471da177e4SLinus Torvalds {
348f5e10287SThomas Gleixner #ifndef CONFIG_ARCH_TASK_STRUCT_ALLOCATOR
3491da177e4SLinus Torvalds #ifndef ARCH_MIN_TASKALIGN
3501da177e4SLinus Torvalds #define ARCH_MIN_TASKALIGN	L1_CACHE_BYTES
3511da177e4SLinus Torvalds #endif
3521da177e4SLinus Torvalds 	/* create a slab on which task_structs can be allocated */
3535d097056SVladimir Davydov 	task_struct_cachep = kmem_cache_create("task_struct",
3545d097056SVladimir Davydov 			arch_task_struct_size, ARCH_MIN_TASKALIGN,
3555d097056SVladimir Davydov 			SLAB_PANIC|SLAB_NOTRACK|SLAB_ACCOUNT, NULL);
3561da177e4SLinus Torvalds #endif
3571da177e4SLinus Torvalds 
35861c4628bSSuresh Siddha 	/* do the arch specific task caches init */
35961c4628bSSuresh Siddha 	arch_task_cache_init();
36061c4628bSSuresh Siddha 
36116db3d3fSHeinrich Schuchardt 	set_max_threads(MAX_THREADS);
3621da177e4SLinus Torvalds 
3631da177e4SLinus Torvalds 	init_task.signal->rlim[RLIMIT_NPROC].rlim_cur = max_threads/2;
3641da177e4SLinus Torvalds 	init_task.signal->rlim[RLIMIT_NPROC].rlim_max = max_threads/2;
3651da177e4SLinus Torvalds 	init_task.signal->rlim[RLIMIT_SIGPENDING] =
3661da177e4SLinus Torvalds 		init_task.signal->rlim[RLIMIT_NPROC];
3671da177e4SLinus Torvalds }
3681da177e4SLinus Torvalds 
36952f5684cSGideon Israel Dsouza int __weak arch_dup_task_struct(struct task_struct *dst,
37061c4628bSSuresh Siddha 					       struct task_struct *src)
37161c4628bSSuresh Siddha {
37261c4628bSSuresh Siddha 	*dst = *src;
37361c4628bSSuresh Siddha 	return 0;
37461c4628bSSuresh Siddha }
37561c4628bSSuresh Siddha 
376d4311ff1SAaron Tomlin void set_task_stack_end_magic(struct task_struct *tsk)
377d4311ff1SAaron Tomlin {
378d4311ff1SAaron Tomlin 	unsigned long *stackend;
379d4311ff1SAaron Tomlin 
380d4311ff1SAaron Tomlin 	stackend = end_of_stack(tsk);
381d4311ff1SAaron Tomlin 	*stackend = STACK_END_MAGIC;	/* for overflow detection */
382d4311ff1SAaron Tomlin }
383d4311ff1SAaron Tomlin 
384725fc629SAndi Kleen static struct task_struct *dup_task_struct(struct task_struct *orig, int node)
3851da177e4SLinus Torvalds {
3861da177e4SLinus Torvalds 	struct task_struct *tsk;
387b235beeaSLinus Torvalds 	unsigned long *stack;
388*ba14a194SAndy Lutomirski 	struct vm_struct *stack_vm_area;
3893e26c149SPeter Zijlstra 	int err;
3901da177e4SLinus Torvalds 
391725fc629SAndi Kleen 	if (node == NUMA_NO_NODE)
392725fc629SAndi Kleen 		node = tsk_fork_get_node(orig);
393504f52b5SEric Dumazet 	tsk = alloc_task_struct_node(node);
3941da177e4SLinus Torvalds 	if (!tsk)
3951da177e4SLinus Torvalds 		return NULL;
3961da177e4SLinus Torvalds 
397b235beeaSLinus Torvalds 	stack = alloc_thread_stack_node(tsk, node);
398b235beeaSLinus Torvalds 	if (!stack)
399f19b9f74SAkinobu Mita 		goto free_tsk;
4001da177e4SLinus Torvalds 
401*ba14a194SAndy Lutomirski 	stack_vm_area = task_stack_vm_area(tsk);
402*ba14a194SAndy Lutomirski 
40361c4628bSSuresh Siddha 	err = arch_dup_task_struct(tsk, orig);
404*ba14a194SAndy Lutomirski 
405*ba14a194SAndy Lutomirski 	/*
406*ba14a194SAndy Lutomirski 	 * arch_dup_task_struct() clobbers the stack-related fields.  Make
407*ba14a194SAndy Lutomirski 	 * sure they're properly initialized before using any stack-related
408*ba14a194SAndy Lutomirski 	 * functions again.
409*ba14a194SAndy Lutomirski 	 */
410*ba14a194SAndy Lutomirski 	tsk->stack = stack;
411*ba14a194SAndy Lutomirski #ifdef CONFIG_VMAP_STACK
412*ba14a194SAndy Lutomirski 	tsk->stack_vm_area = stack_vm_area;
413*ba14a194SAndy Lutomirski #endif
414*ba14a194SAndy Lutomirski 
41561c4628bSSuresh Siddha 	if (err)
416b235beeaSLinus Torvalds 		goto free_stack;
41761c4628bSSuresh Siddha 
418dbd95212SKees Cook #ifdef CONFIG_SECCOMP
419dbd95212SKees Cook 	/*
420dbd95212SKees Cook 	 * We must handle setting up seccomp filters once we're under
421dbd95212SKees Cook 	 * the sighand lock in case orig has changed between now and
422dbd95212SKees Cook 	 * then. Until then, filter must be NULL to avoid messing up
423dbd95212SKees Cook 	 * the usage counts on the error path calling free_task.
424dbd95212SKees Cook 	 */
425dbd95212SKees Cook 	tsk->seccomp.filter = NULL;
426dbd95212SKees Cook #endif
42787bec58aSAndrew Morton 
42887bec58aSAndrew Morton 	setup_thread_stack(tsk, orig);
4298e7cac79SAvi Kivity 	clear_user_return_notifier(tsk);
430f26f9affSMike Galbraith 	clear_tsk_need_resched(tsk);
431d4311ff1SAaron Tomlin 	set_task_stack_end_magic(tsk);
4321da177e4SLinus Torvalds 
4330a425405SArjan van de Ven #ifdef CONFIG_CC_STACKPROTECTOR
4340a425405SArjan van de Ven 	tsk->stack_canary = get_random_int();
4350a425405SArjan van de Ven #endif
4360a425405SArjan van de Ven 
437fb0a685cSDaniel Rebelo de Oliveira 	/*
438fb0a685cSDaniel Rebelo de Oliveira 	 * One for us, one for whoever does the "release_task()" (usually
439fb0a685cSDaniel Rebelo de Oliveira 	 * parent)
440fb0a685cSDaniel Rebelo de Oliveira 	 */
4411da177e4SLinus Torvalds 	atomic_set(&tsk->usage, 2);
4426c5c9341SAlexey Dobriyan #ifdef CONFIG_BLK_DEV_IO_TRACE
4432056a782SJens Axboe 	tsk->btrace_seq = 0;
4446c5c9341SAlexey Dobriyan #endif
445a0aa7f68SJens Axboe 	tsk->splice_pipe = NULL;
4465640f768SEric Dumazet 	tsk->task_frag.page = NULL;
447093e5840SSebastian Andrzej Siewior 	tsk->wake_q.next = NULL;
448c6a7f572SKOSAKI Motohiro 
449*ba14a194SAndy Lutomirski 	account_kernel_stack(tsk, 1);
450c6a7f572SKOSAKI Motohiro 
4515c9a8750SDmitry Vyukov 	kcov_task_init(tsk);
4525c9a8750SDmitry Vyukov 
4531da177e4SLinus Torvalds 	return tsk;
45461c4628bSSuresh Siddha 
455b235beeaSLinus Torvalds free_stack:
456*ba14a194SAndy Lutomirski 	free_thread_stack(tsk);
457f19b9f74SAkinobu Mita free_tsk:
45861c4628bSSuresh Siddha 	free_task_struct(tsk);
45961c4628bSSuresh Siddha 	return NULL;
4601da177e4SLinus Torvalds }
4611da177e4SLinus Torvalds 
4621da177e4SLinus Torvalds #ifdef CONFIG_MMU
463a39bc516SAlexey Dobriyan static int dup_mmap(struct mm_struct *mm, struct mm_struct *oldmm)
4641da177e4SLinus Torvalds {
465297c5eeeSLinus Torvalds 	struct vm_area_struct *mpnt, *tmp, *prev, **pprev;
4661da177e4SLinus Torvalds 	struct rb_node **rb_link, *rb_parent;
4671da177e4SLinus Torvalds 	int retval;
4681da177e4SLinus Torvalds 	unsigned long charge;
4691da177e4SLinus Torvalds 
47032cdba1eSOleg Nesterov 	uprobe_start_dup_mmap();
4717c051267SMichal Hocko 	if (down_write_killable(&oldmm->mmap_sem)) {
4727c051267SMichal Hocko 		retval = -EINTR;
4737c051267SMichal Hocko 		goto fail_uprobe_end;
4747c051267SMichal Hocko 	}
475ec8c0446SRalf Baechle 	flush_cache_dup_mm(oldmm);
476f8ac4ec9SOleg Nesterov 	uprobe_dup_mmap(oldmm, mm);
477ad339451SIngo Molnar 	/*
478ad339451SIngo Molnar 	 * Not linked in yet - no deadlock potential:
479ad339451SIngo Molnar 	 */
480ad339451SIngo Molnar 	down_write_nested(&mm->mmap_sem, SINGLE_DEPTH_NESTING);
4817ee78232SHugh Dickins 
48290f31d0eSKonstantin Khlebnikov 	/* No ordering required: file already has been exposed. */
48390f31d0eSKonstantin Khlebnikov 	RCU_INIT_POINTER(mm->exe_file, get_mm_exe_file(oldmm));
48490f31d0eSKonstantin Khlebnikov 
4854f7d4614SVladimir Davydov 	mm->total_vm = oldmm->total_vm;
48684638335SKonstantin Khlebnikov 	mm->data_vm = oldmm->data_vm;
4874f7d4614SVladimir Davydov 	mm->exec_vm = oldmm->exec_vm;
4884f7d4614SVladimir Davydov 	mm->stack_vm = oldmm->stack_vm;
4894f7d4614SVladimir Davydov 
4901da177e4SLinus Torvalds 	rb_link = &mm->mm_rb.rb_node;
4911da177e4SLinus Torvalds 	rb_parent = NULL;
4921da177e4SLinus Torvalds 	pprev = &mm->mmap;
493f8af4da3SHugh Dickins 	retval = ksm_fork(mm, oldmm);
494f8af4da3SHugh Dickins 	if (retval)
495f8af4da3SHugh Dickins 		goto out;
496ba76149fSAndrea Arcangeli 	retval = khugepaged_fork(mm, oldmm);
497ba76149fSAndrea Arcangeli 	if (retval)
498ba76149fSAndrea Arcangeli 		goto out;
4991da177e4SLinus Torvalds 
500297c5eeeSLinus Torvalds 	prev = NULL;
501fd3e42fcSHugh Dickins 	for (mpnt = oldmm->mmap; mpnt; mpnt = mpnt->vm_next) {
5021da177e4SLinus Torvalds 		struct file *file;
5031da177e4SLinus Torvalds 
5041da177e4SLinus Torvalds 		if (mpnt->vm_flags & VM_DONTCOPY) {
50584638335SKonstantin Khlebnikov 			vm_stat_account(mm, mpnt->vm_flags, -vma_pages(mpnt));
5061da177e4SLinus Torvalds 			continue;
5071da177e4SLinus Torvalds 		}
5081da177e4SLinus Torvalds 		charge = 0;
5091da177e4SLinus Torvalds 		if (mpnt->vm_flags & VM_ACCOUNT) {
510b2412b7fSHuang Shijie 			unsigned long len = vma_pages(mpnt);
511b2412b7fSHuang Shijie 
512191c5424SAl Viro 			if (security_vm_enough_memory_mm(oldmm, len)) /* sic */
5131da177e4SLinus Torvalds 				goto fail_nomem;
5141da177e4SLinus Torvalds 			charge = len;
5151da177e4SLinus Torvalds 		}
516e94b1766SChristoph Lameter 		tmp = kmem_cache_alloc(vm_area_cachep, GFP_KERNEL);
5171da177e4SLinus Torvalds 		if (!tmp)
5181da177e4SLinus Torvalds 			goto fail_nomem;
5191da177e4SLinus Torvalds 		*tmp = *mpnt;
5205beb4930SRik van Riel 		INIT_LIST_HEAD(&tmp->anon_vma_chain);
521ef0855d3SOleg Nesterov 		retval = vma_dup_policy(mpnt, tmp);
522ef0855d3SOleg Nesterov 		if (retval)
5231da177e4SLinus Torvalds 			goto fail_nomem_policy;
524a247c3a9SAndrea Arcangeli 		tmp->vm_mm = mm;
5255beb4930SRik van Riel 		if (anon_vma_fork(tmp, mpnt))
5265beb4930SRik van Riel 			goto fail_nomem_anon_vma_fork;
527de60f5f1SEric B Munson 		tmp->vm_flags &=
528de60f5f1SEric B Munson 			~(VM_LOCKED|VM_LOCKONFAULT|VM_UFFD_MISSING|VM_UFFD_WP);
529297c5eeeSLinus Torvalds 		tmp->vm_next = tmp->vm_prev = NULL;
530745f234bSAndrea Arcangeli 		tmp->vm_userfaultfd_ctx = NULL_VM_UFFD_CTX;
5311da177e4SLinus Torvalds 		file = tmp->vm_file;
5321da177e4SLinus Torvalds 		if (file) {
533496ad9aaSAl Viro 			struct inode *inode = file_inode(file);
534b88ed205SHugh Dickins 			struct address_space *mapping = file->f_mapping;
535b88ed205SHugh Dickins 
5361da177e4SLinus Torvalds 			get_file(file);
5371da177e4SLinus Torvalds 			if (tmp->vm_flags & VM_DENYWRITE)
5381da177e4SLinus Torvalds 				atomic_dec(&inode->i_writecount);
53983cde9e8SDavidlohr Bueso 			i_mmap_lock_write(mapping);
540b88ed205SHugh Dickins 			if (tmp->vm_flags & VM_SHARED)
5414bb5f5d9SDavid Herrmann 				atomic_inc(&mapping->i_mmap_writable);
542b88ed205SHugh Dickins 			flush_dcache_mmap_lock(mapping);
543b88ed205SHugh Dickins 			/* insert tmp into the share list, just after mpnt */
5449826a516SMichel Lespinasse 			vma_interval_tree_insert_after(tmp, mpnt,
5459826a516SMichel Lespinasse 					&mapping->i_mmap);
546b88ed205SHugh Dickins 			flush_dcache_mmap_unlock(mapping);
54783cde9e8SDavidlohr Bueso 			i_mmap_unlock_write(mapping);
5481da177e4SLinus Torvalds 		}
5491da177e4SLinus Torvalds 
5501da177e4SLinus Torvalds 		/*
551a1e78772SMel Gorman 		 * Clear hugetlb-related page reserves for children. This only
552a1e78772SMel Gorman 		 * affects MAP_PRIVATE mappings. Faults generated by the child
553a1e78772SMel Gorman 		 * are not guaranteed to succeed, even if read-only
554a1e78772SMel Gorman 		 */
555a1e78772SMel Gorman 		if (is_vm_hugetlb_page(tmp))
556a1e78772SMel Gorman 			reset_vma_resv_huge_pages(tmp);
557a1e78772SMel Gorman 
558a1e78772SMel Gorman 		/*
5597ee78232SHugh Dickins 		 * Link in the new vma and copy the page table entries.
5601da177e4SLinus Torvalds 		 */
5611da177e4SLinus Torvalds 		*pprev = tmp;
5621da177e4SLinus Torvalds 		pprev = &tmp->vm_next;
563297c5eeeSLinus Torvalds 		tmp->vm_prev = prev;
564297c5eeeSLinus Torvalds 		prev = tmp;
5651da177e4SLinus Torvalds 
5661da177e4SLinus Torvalds 		__vma_link_rb(mm, tmp, rb_link, rb_parent);
5671da177e4SLinus Torvalds 		rb_link = &tmp->vm_rb.rb_right;
5681da177e4SLinus Torvalds 		rb_parent = &tmp->vm_rb;
5691da177e4SLinus Torvalds 
5701da177e4SLinus Torvalds 		mm->map_count++;
5710b0db14cSHugh Dickins 		retval = copy_page_range(mm, oldmm, mpnt);
5721da177e4SLinus Torvalds 
5731da177e4SLinus Torvalds 		if (tmp->vm_ops && tmp->vm_ops->open)
5741da177e4SLinus Torvalds 			tmp->vm_ops->open(tmp);
5751da177e4SLinus Torvalds 
5761da177e4SLinus Torvalds 		if (retval)
5771da177e4SLinus Torvalds 			goto out;
5781da177e4SLinus Torvalds 	}
579d6dd61c8SJeremy Fitzhardinge 	/* a new mm has just been created */
580d6dd61c8SJeremy Fitzhardinge 	arch_dup_mmap(oldmm, mm);
5811da177e4SLinus Torvalds 	retval = 0;
5821da177e4SLinus Torvalds out:
5837ee78232SHugh Dickins 	up_write(&mm->mmap_sem);
584fd3e42fcSHugh Dickins 	flush_tlb_mm(oldmm);
5851da177e4SLinus Torvalds 	up_write(&oldmm->mmap_sem);
5867c051267SMichal Hocko fail_uprobe_end:
58732cdba1eSOleg Nesterov 	uprobe_end_dup_mmap();
5881da177e4SLinus Torvalds 	return retval;
5895beb4930SRik van Riel fail_nomem_anon_vma_fork:
590ef0855d3SOleg Nesterov 	mpol_put(vma_policy(tmp));
5911da177e4SLinus Torvalds fail_nomem_policy:
5921da177e4SLinus Torvalds 	kmem_cache_free(vm_area_cachep, tmp);
5931da177e4SLinus Torvalds fail_nomem:
5941da177e4SLinus Torvalds 	retval = -ENOMEM;
5951da177e4SLinus Torvalds 	vm_unacct_memory(charge);
5961da177e4SLinus Torvalds 	goto out;
5971da177e4SLinus Torvalds }
5981da177e4SLinus Torvalds 
5991da177e4SLinus Torvalds static inline int mm_alloc_pgd(struct mm_struct *mm)
6001da177e4SLinus Torvalds {
6011da177e4SLinus Torvalds 	mm->pgd = pgd_alloc(mm);
6021da177e4SLinus Torvalds 	if (unlikely(!mm->pgd))
6031da177e4SLinus Torvalds 		return -ENOMEM;
6041da177e4SLinus Torvalds 	return 0;
6051da177e4SLinus Torvalds }
6061da177e4SLinus Torvalds 
6071da177e4SLinus Torvalds static inline void mm_free_pgd(struct mm_struct *mm)
6081da177e4SLinus Torvalds {
6095e541973SBenjamin Herrenschmidt 	pgd_free(mm, mm->pgd);
6101da177e4SLinus Torvalds }
6111da177e4SLinus Torvalds #else
61290f31d0eSKonstantin Khlebnikov static int dup_mmap(struct mm_struct *mm, struct mm_struct *oldmm)
61390f31d0eSKonstantin Khlebnikov {
61490f31d0eSKonstantin Khlebnikov 	down_write(&oldmm->mmap_sem);
61590f31d0eSKonstantin Khlebnikov 	RCU_INIT_POINTER(mm->exe_file, get_mm_exe_file(oldmm));
61690f31d0eSKonstantin Khlebnikov 	up_write(&oldmm->mmap_sem);
61790f31d0eSKonstantin Khlebnikov 	return 0;
61890f31d0eSKonstantin Khlebnikov }
6191da177e4SLinus Torvalds #define mm_alloc_pgd(mm)	(0)
6201da177e4SLinus Torvalds #define mm_free_pgd(mm)
6211da177e4SLinus Torvalds #endif /* CONFIG_MMU */
6221da177e4SLinus Torvalds 
6231da177e4SLinus Torvalds __cacheline_aligned_in_smp DEFINE_SPINLOCK(mmlist_lock);
6241da177e4SLinus Torvalds 
625e94b1766SChristoph Lameter #define allocate_mm()	(kmem_cache_alloc(mm_cachep, GFP_KERNEL))
6261da177e4SLinus Torvalds #define free_mm(mm)	(kmem_cache_free(mm_cachep, (mm)))
6271da177e4SLinus Torvalds 
6284cb0e11bSHidehiro Kawai static unsigned long default_dump_filter = MMF_DUMP_FILTER_DEFAULT;
6294cb0e11bSHidehiro Kawai 
6304cb0e11bSHidehiro Kawai static int __init coredump_filter_setup(char *s)
6314cb0e11bSHidehiro Kawai {
6324cb0e11bSHidehiro Kawai 	default_dump_filter =
6334cb0e11bSHidehiro Kawai 		(simple_strtoul(s, NULL, 0) << MMF_DUMP_FILTER_SHIFT) &
6344cb0e11bSHidehiro Kawai 		MMF_DUMP_FILTER_MASK;
6354cb0e11bSHidehiro Kawai 	return 1;
6364cb0e11bSHidehiro Kawai }
6374cb0e11bSHidehiro Kawai 
6384cb0e11bSHidehiro Kawai __setup("coredump_filter=", coredump_filter_setup);
6394cb0e11bSHidehiro Kawai 
6401da177e4SLinus Torvalds #include <linux/init_task.h>
6411da177e4SLinus Torvalds 
642858f0993SAlexey Dobriyan static void mm_init_aio(struct mm_struct *mm)
643858f0993SAlexey Dobriyan {
644858f0993SAlexey Dobriyan #ifdef CONFIG_AIO
645858f0993SAlexey Dobriyan 	spin_lock_init(&mm->ioctx_lock);
646db446a08SBenjamin LaHaise 	mm->ioctx_table = NULL;
647858f0993SAlexey Dobriyan #endif
648858f0993SAlexey Dobriyan }
649858f0993SAlexey Dobriyan 
65033144e84SVladimir Davydov static void mm_init_owner(struct mm_struct *mm, struct task_struct *p)
65133144e84SVladimir Davydov {
65233144e84SVladimir Davydov #ifdef CONFIG_MEMCG
65333144e84SVladimir Davydov 	mm->owner = p;
65433144e84SVladimir Davydov #endif
65533144e84SVladimir Davydov }
65633144e84SVladimir Davydov 
65778fb7466SPavel Emelianov static struct mm_struct *mm_init(struct mm_struct *mm, struct task_struct *p)
6581da177e4SLinus Torvalds {
65941f727fdSVladimir Davydov 	mm->mmap = NULL;
66041f727fdSVladimir Davydov 	mm->mm_rb = RB_ROOT;
66141f727fdSVladimir Davydov 	mm->vmacache_seqnum = 0;
6621da177e4SLinus Torvalds 	atomic_set(&mm->mm_users, 1);
6631da177e4SLinus Torvalds 	atomic_set(&mm->mm_count, 1);
6641da177e4SLinus Torvalds 	init_rwsem(&mm->mmap_sem);
6651da177e4SLinus Torvalds 	INIT_LIST_HEAD(&mm->mmlist);
666999d9fc1SOleg Nesterov 	mm->core_state = NULL;
667e1f56c89SKirill A. Shutemov 	atomic_long_set(&mm->nr_ptes, 0);
6682d2f5119SKirill A. Shutemov 	mm_nr_pmds_init(mm);
66941f727fdSVladimir Davydov 	mm->map_count = 0;
67041f727fdSVladimir Davydov 	mm->locked_vm = 0;
671ce65cefaSVladimir Davydov 	mm->pinned_vm = 0;
672d559db08SKAMEZAWA Hiroyuki 	memset(&mm->rss_stat, 0, sizeof(mm->rss_stat));
6731da177e4SLinus Torvalds 	spin_lock_init(&mm->page_table_lock);
67441f727fdSVladimir Davydov 	mm_init_cpumask(mm);
675858f0993SAlexey Dobriyan 	mm_init_aio(mm);
676cf475ad2SBalbir Singh 	mm_init_owner(mm, p);
67741f727fdSVladimir Davydov 	mmu_notifier_mm_init(mm);
67820841405SRik van Riel 	clear_tlb_flush_pending(mm);
67941f727fdSVladimir Davydov #if defined(CONFIG_TRANSPARENT_HUGEPAGE) && !USE_SPLIT_PMD_PTLOCKS
68041f727fdSVladimir Davydov 	mm->pmd_huge_pte = NULL;
68141f727fdSVladimir Davydov #endif
6821da177e4SLinus Torvalds 
683a0715cc2SAlex Thorlton 	if (current->mm) {
684a0715cc2SAlex Thorlton 		mm->flags = current->mm->flags & MMF_INIT_MASK;
685a0715cc2SAlex Thorlton 		mm->def_flags = current->mm->def_flags & VM_INIT_DEF_MASK;
686a0715cc2SAlex Thorlton 	} else {
687a0715cc2SAlex Thorlton 		mm->flags = default_dump_filter;
6881da177e4SLinus Torvalds 		mm->def_flags = 0;
689a0715cc2SAlex Thorlton 	}
690a0715cc2SAlex Thorlton 
69141f727fdSVladimir Davydov 	if (mm_alloc_pgd(mm))
69241f727fdSVladimir Davydov 		goto fail_nopgd;
69378fb7466SPavel Emelianov 
69441f727fdSVladimir Davydov 	if (init_new_context(p, mm))
69541f727fdSVladimir Davydov 		goto fail_nocontext;
69641f727fdSVladimir Davydov 
69741f727fdSVladimir Davydov 	return mm;
69841f727fdSVladimir Davydov 
69941f727fdSVladimir Davydov fail_nocontext:
70041f727fdSVladimir Davydov 	mm_free_pgd(mm);
70141f727fdSVladimir Davydov fail_nopgd:
7021da177e4SLinus Torvalds 	free_mm(mm);
7031da177e4SLinus Torvalds 	return NULL;
7041da177e4SLinus Torvalds }
7051da177e4SLinus Torvalds 
706c3f0327fSKonstantin Khlebnikov static void check_mm(struct mm_struct *mm)
707c3f0327fSKonstantin Khlebnikov {
708c3f0327fSKonstantin Khlebnikov 	int i;
709c3f0327fSKonstantin Khlebnikov 
710c3f0327fSKonstantin Khlebnikov 	for (i = 0; i < NR_MM_COUNTERS; i++) {
711c3f0327fSKonstantin Khlebnikov 		long x = atomic_long_read(&mm->rss_stat.count[i]);
712c3f0327fSKonstantin Khlebnikov 
713c3f0327fSKonstantin Khlebnikov 		if (unlikely(x))
714c3f0327fSKonstantin Khlebnikov 			printk(KERN_ALERT "BUG: Bad rss-counter state "
715c3f0327fSKonstantin Khlebnikov 					  "mm:%p idx:%d val:%ld\n", mm, i, x);
716c3f0327fSKonstantin Khlebnikov 	}
717b30fe6c7SKirill A. Shutemov 
718b30fe6c7SKirill A. Shutemov 	if (atomic_long_read(&mm->nr_ptes))
719b30fe6c7SKirill A. Shutemov 		pr_alert("BUG: non-zero nr_ptes on freeing mm: %ld\n",
720b30fe6c7SKirill A. Shutemov 				atomic_long_read(&mm->nr_ptes));
721b30fe6c7SKirill A. Shutemov 	if (mm_nr_pmds(mm))
722b30fe6c7SKirill A. Shutemov 		pr_alert("BUG: non-zero nr_pmds on freeing mm: %ld\n",
723b30fe6c7SKirill A. Shutemov 				mm_nr_pmds(mm));
724b30fe6c7SKirill A. Shutemov 
725e009bb30SKirill A. Shutemov #if defined(CONFIG_TRANSPARENT_HUGEPAGE) && !USE_SPLIT_PMD_PTLOCKS
72696dad67fSSasha Levin 	VM_BUG_ON_MM(mm->pmd_huge_pte, mm);
727c3f0327fSKonstantin Khlebnikov #endif
728c3f0327fSKonstantin Khlebnikov }
729c3f0327fSKonstantin Khlebnikov 
7301da177e4SLinus Torvalds /*
7311da177e4SLinus Torvalds  * Allocate and initialize an mm_struct.
7321da177e4SLinus Torvalds  */
7331da177e4SLinus Torvalds struct mm_struct *mm_alloc(void)
7341da177e4SLinus Torvalds {
7351da177e4SLinus Torvalds 	struct mm_struct *mm;
7361da177e4SLinus Torvalds 
7371da177e4SLinus Torvalds 	mm = allocate_mm();
738de03c72cSKOSAKI Motohiro 	if (!mm)
739de03c72cSKOSAKI Motohiro 		return NULL;
740de03c72cSKOSAKI Motohiro 
7411da177e4SLinus Torvalds 	memset(mm, 0, sizeof(*mm));
7426345d24dSLinus Torvalds 	return mm_init(mm, current);
7431da177e4SLinus Torvalds }
7441da177e4SLinus Torvalds 
7451da177e4SLinus Torvalds /*
7461da177e4SLinus Torvalds  * Called when the last reference to the mm
7471da177e4SLinus Torvalds  * is dropped: either by a lazy thread or by
7481da177e4SLinus Torvalds  * mmput. Free the page directory and the mm.
7491da177e4SLinus Torvalds  */
7507ad5b3a5SHarvey Harrison void __mmdrop(struct mm_struct *mm)
7511da177e4SLinus Torvalds {
7521da177e4SLinus Torvalds 	BUG_ON(mm == &init_mm);
7531da177e4SLinus Torvalds 	mm_free_pgd(mm);
7541da177e4SLinus Torvalds 	destroy_context(mm);
755cddb8a5cSAndrea Arcangeli 	mmu_notifier_mm_destroy(mm);
756c3f0327fSKonstantin Khlebnikov 	check_mm(mm);
7571da177e4SLinus Torvalds 	free_mm(mm);
7581da177e4SLinus Torvalds }
7596d4e4c4fSAvi Kivity EXPORT_SYMBOL_GPL(__mmdrop);
7601da177e4SLinus Torvalds 
761ec8d7c14SMichal Hocko static inline void __mmput(struct mm_struct *mm)
7621da177e4SLinus Torvalds {
763ec8d7c14SMichal Hocko 	VM_BUG_ON(atomic_read(&mm->mm_users));
7640ae26f1bSAndrew Morton 
765d4b3b638SSrikar Dronamraju 	uprobe_clear_state(mm);
7661da177e4SLinus Torvalds 	exit_aio(mm);
7671c2fb7a4SAndrea Arcangeli 	ksm_exit(mm);
768ba76149fSAndrea Arcangeli 	khugepaged_exit(mm); /* must run before exit_mmap */
7691da177e4SLinus Torvalds 	exit_mmap(mm);
770925d1c40SMatt Helsley 	set_mm_exe_file(mm, NULL);
7711da177e4SLinus Torvalds 	if (!list_empty(&mm->mmlist)) {
7721da177e4SLinus Torvalds 		spin_lock(&mmlist_lock);
7731da177e4SLinus Torvalds 		list_del(&mm->mmlist);
7741da177e4SLinus Torvalds 		spin_unlock(&mmlist_lock);
7751da177e4SLinus Torvalds 	}
776801460d0SHiroshi Shimamoto 	if (mm->binfmt)
777801460d0SHiroshi Shimamoto 		module_put(mm->binfmt->module);
7781da177e4SLinus Torvalds 	mmdrop(mm);
7791da177e4SLinus Torvalds }
780ec8d7c14SMichal Hocko 
781ec8d7c14SMichal Hocko /*
782ec8d7c14SMichal Hocko  * Decrement the use count and release all resources for an mm.
783ec8d7c14SMichal Hocko  */
784ec8d7c14SMichal Hocko void mmput(struct mm_struct *mm)
785ec8d7c14SMichal Hocko {
786ec8d7c14SMichal Hocko 	might_sleep();
787ec8d7c14SMichal Hocko 
788ec8d7c14SMichal Hocko 	if (atomic_dec_and_test(&mm->mm_users))
789ec8d7c14SMichal Hocko 		__mmput(mm);
7901da177e4SLinus Torvalds }
7911da177e4SLinus Torvalds EXPORT_SYMBOL_GPL(mmput);
7921da177e4SLinus Torvalds 
7937ef949d7SMichal Hocko #ifdef CONFIG_MMU
794ec8d7c14SMichal Hocko static void mmput_async_fn(struct work_struct *work)
795ec8d7c14SMichal Hocko {
796ec8d7c14SMichal Hocko 	struct mm_struct *mm = container_of(work, struct mm_struct, async_put_work);
797ec8d7c14SMichal Hocko 	__mmput(mm);
798ec8d7c14SMichal Hocko }
799ec8d7c14SMichal Hocko 
800ec8d7c14SMichal Hocko void mmput_async(struct mm_struct *mm)
801ec8d7c14SMichal Hocko {
802ec8d7c14SMichal Hocko 	if (atomic_dec_and_test(&mm->mm_users)) {
803ec8d7c14SMichal Hocko 		INIT_WORK(&mm->async_put_work, mmput_async_fn);
804ec8d7c14SMichal Hocko 		schedule_work(&mm->async_put_work);
805ec8d7c14SMichal Hocko 	}
806ec8d7c14SMichal Hocko }
8077ef949d7SMichal Hocko #endif
808ec8d7c14SMichal Hocko 
80990f31d0eSKonstantin Khlebnikov /**
81090f31d0eSKonstantin Khlebnikov  * set_mm_exe_file - change a reference to the mm's executable file
81190f31d0eSKonstantin Khlebnikov  *
81290f31d0eSKonstantin Khlebnikov  * This changes mm's executable file (shown as symlink /proc/[pid]/exe).
81390f31d0eSKonstantin Khlebnikov  *
8146e399cd1SDavidlohr Bueso  * Main users are mmput() and sys_execve(). Callers prevent concurrent
8156e399cd1SDavidlohr Bueso  * invocations: in mmput() nobody alive left, in execve task is single
8166e399cd1SDavidlohr Bueso  * threaded. sys_prctl(PR_SET_MM_MAP/EXE_FILE) also needs to set the
8176e399cd1SDavidlohr Bueso  * mm->exe_file, but does so without using set_mm_exe_file() in order
8186e399cd1SDavidlohr Bueso  * to do avoid the need for any locks.
81990f31d0eSKonstantin Khlebnikov  */
82038646013SJiri Slaby void set_mm_exe_file(struct mm_struct *mm, struct file *new_exe_file)
82138646013SJiri Slaby {
8226e399cd1SDavidlohr Bueso 	struct file *old_exe_file;
8236e399cd1SDavidlohr Bueso 
8246e399cd1SDavidlohr Bueso 	/*
8256e399cd1SDavidlohr Bueso 	 * It is safe to dereference the exe_file without RCU as
8266e399cd1SDavidlohr Bueso 	 * this function is only called if nobody else can access
8276e399cd1SDavidlohr Bueso 	 * this mm -- see comment above for justification.
8286e399cd1SDavidlohr Bueso 	 */
8296e399cd1SDavidlohr Bueso 	old_exe_file = rcu_dereference_raw(mm->exe_file);
83090f31d0eSKonstantin Khlebnikov 
83138646013SJiri Slaby 	if (new_exe_file)
83238646013SJiri Slaby 		get_file(new_exe_file);
83390f31d0eSKonstantin Khlebnikov 	rcu_assign_pointer(mm->exe_file, new_exe_file);
83490f31d0eSKonstantin Khlebnikov 	if (old_exe_file)
83590f31d0eSKonstantin Khlebnikov 		fput(old_exe_file);
83638646013SJiri Slaby }
83738646013SJiri Slaby 
83890f31d0eSKonstantin Khlebnikov /**
83990f31d0eSKonstantin Khlebnikov  * get_mm_exe_file - acquire a reference to the mm's executable file
84090f31d0eSKonstantin Khlebnikov  *
84190f31d0eSKonstantin Khlebnikov  * Returns %NULL if mm has no associated executable file.
84290f31d0eSKonstantin Khlebnikov  * User must release file via fput().
84390f31d0eSKonstantin Khlebnikov  */
84438646013SJiri Slaby struct file *get_mm_exe_file(struct mm_struct *mm)
84538646013SJiri Slaby {
84638646013SJiri Slaby 	struct file *exe_file;
84738646013SJiri Slaby 
84890f31d0eSKonstantin Khlebnikov 	rcu_read_lock();
84990f31d0eSKonstantin Khlebnikov 	exe_file = rcu_dereference(mm->exe_file);
85090f31d0eSKonstantin Khlebnikov 	if (exe_file && !get_file_rcu(exe_file))
85190f31d0eSKonstantin Khlebnikov 		exe_file = NULL;
85290f31d0eSKonstantin Khlebnikov 	rcu_read_unlock();
85338646013SJiri Slaby 	return exe_file;
85438646013SJiri Slaby }
85511163348SDavidlohr Bueso EXPORT_SYMBOL(get_mm_exe_file);
85638646013SJiri Slaby 
8571da177e4SLinus Torvalds /**
8581da177e4SLinus Torvalds  * get_task_mm - acquire a reference to the task's mm
8591da177e4SLinus Torvalds  *
860246bb0b1SOleg Nesterov  * Returns %NULL if the task has no mm.  Checks PF_KTHREAD (meaning
8611da177e4SLinus Torvalds  * this kernel workthread has transiently adopted a user mm with use_mm,
8621da177e4SLinus Torvalds  * to do its AIO) is not set and if so returns a reference to it, after
8631da177e4SLinus Torvalds  * bumping up the use count.  User must release the mm via mmput()
8641da177e4SLinus Torvalds  * after use.  Typically used by /proc and ptrace.
8651da177e4SLinus Torvalds  */
8661da177e4SLinus Torvalds struct mm_struct *get_task_mm(struct task_struct *task)
8671da177e4SLinus Torvalds {
8681da177e4SLinus Torvalds 	struct mm_struct *mm;
8691da177e4SLinus Torvalds 
8701da177e4SLinus Torvalds 	task_lock(task);
8711da177e4SLinus Torvalds 	mm = task->mm;
8721da177e4SLinus Torvalds 	if (mm) {
873246bb0b1SOleg Nesterov 		if (task->flags & PF_KTHREAD)
8741da177e4SLinus Torvalds 			mm = NULL;
8751da177e4SLinus Torvalds 		else
8761da177e4SLinus Torvalds 			atomic_inc(&mm->mm_users);
8771da177e4SLinus Torvalds 	}
8781da177e4SLinus Torvalds 	task_unlock(task);
8791da177e4SLinus Torvalds 	return mm;
8801da177e4SLinus Torvalds }
8811da177e4SLinus Torvalds EXPORT_SYMBOL_GPL(get_task_mm);
8821da177e4SLinus Torvalds 
8838cdb878dSChristopher Yeoh struct mm_struct *mm_access(struct task_struct *task, unsigned int mode)
8848cdb878dSChristopher Yeoh {
8858cdb878dSChristopher Yeoh 	struct mm_struct *mm;
8868cdb878dSChristopher Yeoh 	int err;
8878cdb878dSChristopher Yeoh 
8888cdb878dSChristopher Yeoh 	err =  mutex_lock_killable(&task->signal->cred_guard_mutex);
8898cdb878dSChristopher Yeoh 	if (err)
8908cdb878dSChristopher Yeoh 		return ERR_PTR(err);
8918cdb878dSChristopher Yeoh 
8928cdb878dSChristopher Yeoh 	mm = get_task_mm(task);
8938cdb878dSChristopher Yeoh 	if (mm && mm != current->mm &&
8948cdb878dSChristopher Yeoh 			!ptrace_may_access(task, mode)) {
8958cdb878dSChristopher Yeoh 		mmput(mm);
8968cdb878dSChristopher Yeoh 		mm = ERR_PTR(-EACCES);
8978cdb878dSChristopher Yeoh 	}
8988cdb878dSChristopher Yeoh 	mutex_unlock(&task->signal->cred_guard_mutex);
8998cdb878dSChristopher Yeoh 
9008cdb878dSChristopher Yeoh 	return mm;
9018cdb878dSChristopher Yeoh }
9028cdb878dSChristopher Yeoh 
90357b59c4aSOleg Nesterov static void complete_vfork_done(struct task_struct *tsk)
904c415c3b4SOleg Nesterov {
905d68b46feSOleg Nesterov 	struct completion *vfork;
906c415c3b4SOleg Nesterov 
907d68b46feSOleg Nesterov 	task_lock(tsk);
908d68b46feSOleg Nesterov 	vfork = tsk->vfork_done;
909d68b46feSOleg Nesterov 	if (likely(vfork)) {
910c415c3b4SOleg Nesterov 		tsk->vfork_done = NULL;
911d68b46feSOleg Nesterov 		complete(vfork);
912d68b46feSOleg Nesterov 	}
913d68b46feSOleg Nesterov 	task_unlock(tsk);
914d68b46feSOleg Nesterov }
915d68b46feSOleg Nesterov 
916d68b46feSOleg Nesterov static int wait_for_vfork_done(struct task_struct *child,
917d68b46feSOleg Nesterov 				struct completion *vfork)
918d68b46feSOleg Nesterov {
919d68b46feSOleg Nesterov 	int killed;
920d68b46feSOleg Nesterov 
921d68b46feSOleg Nesterov 	freezer_do_not_count();
922d68b46feSOleg Nesterov 	killed = wait_for_completion_killable(vfork);
923d68b46feSOleg Nesterov 	freezer_count();
924d68b46feSOleg Nesterov 
925d68b46feSOleg Nesterov 	if (killed) {
926d68b46feSOleg Nesterov 		task_lock(child);
927d68b46feSOleg Nesterov 		child->vfork_done = NULL;
928d68b46feSOleg Nesterov 		task_unlock(child);
929d68b46feSOleg Nesterov 	}
930d68b46feSOleg Nesterov 
931d68b46feSOleg Nesterov 	put_task_struct(child);
932d68b46feSOleg Nesterov 	return killed;
933c415c3b4SOleg Nesterov }
934c415c3b4SOleg Nesterov 
9351da177e4SLinus Torvalds /* Please note the differences between mmput and mm_release.
9361da177e4SLinus Torvalds  * mmput is called whenever we stop holding onto a mm_struct,
9371da177e4SLinus Torvalds  * error success whatever.
9381da177e4SLinus Torvalds  *
9391da177e4SLinus Torvalds  * mm_release is called after a mm_struct has been removed
9401da177e4SLinus Torvalds  * from the current process.
9411da177e4SLinus Torvalds  *
9421da177e4SLinus Torvalds  * This difference is important for error handling, when we
9431da177e4SLinus Torvalds  * only half set up a mm_struct for a new process and need to restore
9441da177e4SLinus Torvalds  * the old one.  Because we mmput the new mm_struct before
9451da177e4SLinus Torvalds  * restoring the old one. . .
9461da177e4SLinus Torvalds  * Eric Biederman 10 January 1998
9471da177e4SLinus Torvalds  */
9481da177e4SLinus Torvalds void mm_release(struct task_struct *tsk, struct mm_struct *mm)
9491da177e4SLinus Torvalds {
9508141c7f3SLinus Torvalds 	/* Get rid of any futexes when releasing the mm */
9518141c7f3SLinus Torvalds #ifdef CONFIG_FUTEX
952fc6b177dSPeter Zijlstra 	if (unlikely(tsk->robust_list)) {
9538141c7f3SLinus Torvalds 		exit_robust_list(tsk);
954fc6b177dSPeter Zijlstra 		tsk->robust_list = NULL;
955fc6b177dSPeter Zijlstra 	}
9568141c7f3SLinus Torvalds #ifdef CONFIG_COMPAT
957fc6b177dSPeter Zijlstra 	if (unlikely(tsk->compat_robust_list)) {
9588141c7f3SLinus Torvalds 		compat_exit_robust_list(tsk);
959fc6b177dSPeter Zijlstra 		tsk->compat_robust_list = NULL;
960fc6b177dSPeter Zijlstra 	}
9618141c7f3SLinus Torvalds #endif
962322a2c10SThomas Gleixner 	if (unlikely(!list_empty(&tsk->pi_state_list)))
963322a2c10SThomas Gleixner 		exit_pi_state_list(tsk);
9648141c7f3SLinus Torvalds #endif
9658141c7f3SLinus Torvalds 
9660326f5a9SSrikar Dronamraju 	uprobe_free_utask(tsk);
9670326f5a9SSrikar Dronamraju 
9681da177e4SLinus Torvalds 	/* Get rid of any cached register state */
9691da177e4SLinus Torvalds 	deactivate_mm(tsk, mm);
9701da177e4SLinus Torvalds 
971fec1d011SRoland McGrath 	/*
972fec1d011SRoland McGrath 	 * If we're exiting normally, clear a user-space tid field if
973fec1d011SRoland McGrath 	 * requested.  We leave this alone when dying by signal, to leave
974fec1d011SRoland McGrath 	 * the value intact in a core dump, and to save the unnecessary
975d68b46feSOleg Nesterov 	 * trouble, say, a killed vfork parent shouldn't touch this mm.
976d68b46feSOleg Nesterov 	 * Userland only wants this done for a sys_exit.
977fec1d011SRoland McGrath 	 */
9789c8a8228SEric Dumazet 	if (tsk->clear_child_tid) {
9799c8a8228SEric Dumazet 		if (!(tsk->flags & PF_SIGNALED) &&
9809c8a8228SEric Dumazet 		    atomic_read(&mm->mm_users) > 1) {
9811da177e4SLinus Torvalds 			/*
9821da177e4SLinus Torvalds 			 * We don't check the error code - if userspace has
9831da177e4SLinus Torvalds 			 * not set up a proper pointer then tough luck.
9841da177e4SLinus Torvalds 			 */
9859c8a8228SEric Dumazet 			put_user(0, tsk->clear_child_tid);
9869c8a8228SEric Dumazet 			sys_futex(tsk->clear_child_tid, FUTEX_WAKE,
9879c8a8228SEric Dumazet 					1, NULL, NULL, 0);
9889c8a8228SEric Dumazet 		}
9899c8a8228SEric Dumazet 		tsk->clear_child_tid = NULL;
9901da177e4SLinus Torvalds 	}
991f7505d64SKonstantin Khlebnikov 
992f7505d64SKonstantin Khlebnikov 	/*
993f7505d64SKonstantin Khlebnikov 	 * All done, finally we can wake up parent and return this mm to him.
994f7505d64SKonstantin Khlebnikov 	 * Also kthread_stop() uses this completion for synchronization.
995f7505d64SKonstantin Khlebnikov 	 */
996f7505d64SKonstantin Khlebnikov 	if (tsk->vfork_done)
997f7505d64SKonstantin Khlebnikov 		complete_vfork_done(tsk);
9981da177e4SLinus Torvalds }
9991da177e4SLinus Torvalds 
1000a0a7ec30SJANAK DESAI /*
1001a0a7ec30SJANAK DESAI  * Allocate a new mm structure and copy contents from the
1002a0a7ec30SJANAK DESAI  * mm structure of the passed in task structure.
1003a0a7ec30SJANAK DESAI  */
1004ff252c1fSDaeSeok Youn static struct mm_struct *dup_mm(struct task_struct *tsk)
1005a0a7ec30SJANAK DESAI {
1006a0a7ec30SJANAK DESAI 	struct mm_struct *mm, *oldmm = current->mm;
1007a0a7ec30SJANAK DESAI 	int err;
1008a0a7ec30SJANAK DESAI 
1009a0a7ec30SJANAK DESAI 	mm = allocate_mm();
1010a0a7ec30SJANAK DESAI 	if (!mm)
1011a0a7ec30SJANAK DESAI 		goto fail_nomem;
1012a0a7ec30SJANAK DESAI 
1013a0a7ec30SJANAK DESAI 	memcpy(mm, oldmm, sizeof(*mm));
1014a0a7ec30SJANAK DESAI 
101578fb7466SPavel Emelianov 	if (!mm_init(mm, tsk))
1016a0a7ec30SJANAK DESAI 		goto fail_nomem;
1017a0a7ec30SJANAK DESAI 
1018a0a7ec30SJANAK DESAI 	err = dup_mmap(mm, oldmm);
1019a0a7ec30SJANAK DESAI 	if (err)
1020a0a7ec30SJANAK DESAI 		goto free_pt;
1021a0a7ec30SJANAK DESAI 
1022a0a7ec30SJANAK DESAI 	mm->hiwater_rss = get_mm_rss(mm);
1023a0a7ec30SJANAK DESAI 	mm->hiwater_vm = mm->total_vm;
1024a0a7ec30SJANAK DESAI 
1025801460d0SHiroshi Shimamoto 	if (mm->binfmt && !try_module_get(mm->binfmt->module))
1026801460d0SHiroshi Shimamoto 		goto free_pt;
1027801460d0SHiroshi Shimamoto 
1028a0a7ec30SJANAK DESAI 	return mm;
1029a0a7ec30SJANAK DESAI 
1030a0a7ec30SJANAK DESAI free_pt:
1031801460d0SHiroshi Shimamoto 	/* don't put binfmt in mmput, we haven't got module yet */
1032801460d0SHiroshi Shimamoto 	mm->binfmt = NULL;
1033a0a7ec30SJANAK DESAI 	mmput(mm);
1034a0a7ec30SJANAK DESAI 
1035a0a7ec30SJANAK DESAI fail_nomem:
1036a0a7ec30SJANAK DESAI 	return NULL;
1037a0a7ec30SJANAK DESAI }
1038a0a7ec30SJANAK DESAI 
10391da177e4SLinus Torvalds static int copy_mm(unsigned long clone_flags, struct task_struct *tsk)
10401da177e4SLinus Torvalds {
10411da177e4SLinus Torvalds 	struct mm_struct *mm, *oldmm;
10421da177e4SLinus Torvalds 	int retval;
10431da177e4SLinus Torvalds 
10441da177e4SLinus Torvalds 	tsk->min_flt = tsk->maj_flt = 0;
10451da177e4SLinus Torvalds 	tsk->nvcsw = tsk->nivcsw = 0;
104617406b82SMandeep Singh Baines #ifdef CONFIG_DETECT_HUNG_TASK
104717406b82SMandeep Singh Baines 	tsk->last_switch_count = tsk->nvcsw + tsk->nivcsw;
104817406b82SMandeep Singh Baines #endif
10491da177e4SLinus Torvalds 
10501da177e4SLinus Torvalds 	tsk->mm = NULL;
10511da177e4SLinus Torvalds 	tsk->active_mm = NULL;
10521da177e4SLinus Torvalds 
10531da177e4SLinus Torvalds 	/*
10541da177e4SLinus Torvalds 	 * Are we cloning a kernel thread?
10551da177e4SLinus Torvalds 	 *
10561da177e4SLinus Torvalds 	 * We need to steal a active VM for that..
10571da177e4SLinus Torvalds 	 */
10581da177e4SLinus Torvalds 	oldmm = current->mm;
10591da177e4SLinus Torvalds 	if (!oldmm)
10601da177e4SLinus Torvalds 		return 0;
10611da177e4SLinus Torvalds 
1062615d6e87SDavidlohr Bueso 	/* initialize the new vmacache entries */
1063615d6e87SDavidlohr Bueso 	vmacache_flush(tsk);
1064615d6e87SDavidlohr Bueso 
10651da177e4SLinus Torvalds 	if (clone_flags & CLONE_VM) {
10661da177e4SLinus Torvalds 		atomic_inc(&oldmm->mm_users);
10671da177e4SLinus Torvalds 		mm = oldmm;
10681da177e4SLinus Torvalds 		goto good_mm;
10691da177e4SLinus Torvalds 	}
10701da177e4SLinus Torvalds 
10711da177e4SLinus Torvalds 	retval = -ENOMEM;
1072a0a7ec30SJANAK DESAI 	mm = dup_mm(tsk);
10731da177e4SLinus Torvalds 	if (!mm)
10741da177e4SLinus Torvalds 		goto fail_nomem;
10751da177e4SLinus Torvalds 
10761da177e4SLinus Torvalds good_mm:
10771da177e4SLinus Torvalds 	tsk->mm = mm;
10781da177e4SLinus Torvalds 	tsk->active_mm = mm;
10791da177e4SLinus Torvalds 	return 0;
10801da177e4SLinus Torvalds 
10811da177e4SLinus Torvalds fail_nomem:
10821da177e4SLinus Torvalds 	return retval;
10831da177e4SLinus Torvalds }
10841da177e4SLinus Torvalds 
1085a39bc516SAlexey Dobriyan static int copy_fs(unsigned long clone_flags, struct task_struct *tsk)
10861da177e4SLinus Torvalds {
1087498052bbSAl Viro 	struct fs_struct *fs = current->fs;
10881da177e4SLinus Torvalds 	if (clone_flags & CLONE_FS) {
1089498052bbSAl Viro 		/* tsk->fs is already what we want */
10902a4419b5SNick Piggin 		spin_lock(&fs->lock);
1091498052bbSAl Viro 		if (fs->in_exec) {
10922a4419b5SNick Piggin 			spin_unlock(&fs->lock);
1093498052bbSAl Viro 			return -EAGAIN;
1094498052bbSAl Viro 		}
1095498052bbSAl Viro 		fs->users++;
10962a4419b5SNick Piggin 		spin_unlock(&fs->lock);
10971da177e4SLinus Torvalds 		return 0;
10981da177e4SLinus Torvalds 	}
1099498052bbSAl Viro 	tsk->fs = copy_fs_struct(fs);
11001da177e4SLinus Torvalds 	if (!tsk->fs)
11011da177e4SLinus Torvalds 		return -ENOMEM;
11021da177e4SLinus Torvalds 	return 0;
11031da177e4SLinus Torvalds }
11041da177e4SLinus Torvalds 
1105a016f338SJANAK DESAI static int copy_files(unsigned long clone_flags, struct task_struct *tsk)
1106a016f338SJANAK DESAI {
1107a016f338SJANAK DESAI 	struct files_struct *oldf, *newf;
1108a016f338SJANAK DESAI 	int error = 0;
1109a016f338SJANAK DESAI 
1110a016f338SJANAK DESAI 	/*
1111a016f338SJANAK DESAI 	 * A background process may not have any files ...
1112a016f338SJANAK DESAI 	 */
1113a016f338SJANAK DESAI 	oldf = current->files;
1114a016f338SJANAK DESAI 	if (!oldf)
1115a016f338SJANAK DESAI 		goto out;
1116a016f338SJANAK DESAI 
1117a016f338SJANAK DESAI 	if (clone_flags & CLONE_FILES) {
1118a016f338SJANAK DESAI 		atomic_inc(&oldf->count);
1119a016f338SJANAK DESAI 		goto out;
1120a016f338SJANAK DESAI 	}
1121a016f338SJANAK DESAI 
1122a016f338SJANAK DESAI 	newf = dup_fd(oldf, &error);
1123a016f338SJANAK DESAI 	if (!newf)
1124a016f338SJANAK DESAI 		goto out;
1125a016f338SJANAK DESAI 
1126a016f338SJANAK DESAI 	tsk->files = newf;
1127a016f338SJANAK DESAI 	error = 0;
1128a016f338SJANAK DESAI out:
1129a016f338SJANAK DESAI 	return error;
1130a016f338SJANAK DESAI }
1131a016f338SJANAK DESAI 
1132fadad878SJens Axboe static int copy_io(unsigned long clone_flags, struct task_struct *tsk)
1133fd0928dfSJens Axboe {
1134fd0928dfSJens Axboe #ifdef CONFIG_BLOCK
1135fd0928dfSJens Axboe 	struct io_context *ioc = current->io_context;
11366e736be7STejun Heo 	struct io_context *new_ioc;
1137fd0928dfSJens Axboe 
1138fd0928dfSJens Axboe 	if (!ioc)
1139fd0928dfSJens Axboe 		return 0;
1140fadad878SJens Axboe 	/*
1141fadad878SJens Axboe 	 * Share io context with parent, if CLONE_IO is set
1142fadad878SJens Axboe 	 */
1143fadad878SJens Axboe 	if (clone_flags & CLONE_IO) {
11443d48749dSTejun Heo 		ioc_task_link(ioc);
11453d48749dSTejun Heo 		tsk->io_context = ioc;
1146fadad878SJens Axboe 	} else if (ioprio_valid(ioc->ioprio)) {
11476e736be7STejun Heo 		new_ioc = get_task_io_context(tsk, GFP_KERNEL, NUMA_NO_NODE);
11486e736be7STejun Heo 		if (unlikely(!new_ioc))
1149fd0928dfSJens Axboe 			return -ENOMEM;
1150fd0928dfSJens Axboe 
11516e736be7STejun Heo 		new_ioc->ioprio = ioc->ioprio;
115211a3122fSTejun Heo 		put_io_context(new_ioc);
1153fd0928dfSJens Axboe 	}
1154fd0928dfSJens Axboe #endif
1155fd0928dfSJens Axboe 	return 0;
1156fd0928dfSJens Axboe }
1157fd0928dfSJens Axboe 
1158a39bc516SAlexey Dobriyan static int copy_sighand(unsigned long clone_flags, struct task_struct *tsk)
11591da177e4SLinus Torvalds {
11601da177e4SLinus Torvalds 	struct sighand_struct *sig;
11611da177e4SLinus Torvalds 
116260348802SZhaolei 	if (clone_flags & CLONE_SIGHAND) {
11631da177e4SLinus Torvalds 		atomic_inc(&current->sighand->count);
11641da177e4SLinus Torvalds 		return 0;
11651da177e4SLinus Torvalds 	}
11661da177e4SLinus Torvalds 	sig = kmem_cache_alloc(sighand_cachep, GFP_KERNEL);
1167e56d0903SIngo Molnar 	rcu_assign_pointer(tsk->sighand, sig);
11681da177e4SLinus Torvalds 	if (!sig)
11691da177e4SLinus Torvalds 		return -ENOMEM;
11709d7fb042SPeter Zijlstra 
11711da177e4SLinus Torvalds 	atomic_set(&sig->count, 1);
11721da177e4SLinus Torvalds 	memcpy(sig->action, current->sighand->action, sizeof(sig->action));
11731da177e4SLinus Torvalds 	return 0;
11741da177e4SLinus Torvalds }
11751da177e4SLinus Torvalds 
1176a7e5328aSOleg Nesterov void __cleanup_sighand(struct sighand_struct *sighand)
1177c81addc9SOleg Nesterov {
1178d80e731eSOleg Nesterov 	if (atomic_dec_and_test(&sighand->count)) {
1179d80e731eSOleg Nesterov 		signalfd_cleanup(sighand);
1180392809b2SOleg Nesterov 		/*
1181392809b2SOleg Nesterov 		 * sighand_cachep is SLAB_DESTROY_BY_RCU so we can free it
1182392809b2SOleg Nesterov 		 * without an RCU grace period, see __lock_task_sighand().
1183392809b2SOleg Nesterov 		 */
1184c81addc9SOleg Nesterov 		kmem_cache_free(sighand_cachep, sighand);
1185c81addc9SOleg Nesterov 	}
1186d80e731eSOleg Nesterov }
1187c81addc9SOleg Nesterov 
1188f06febc9SFrank Mayhar /*
1189f06febc9SFrank Mayhar  * Initialize POSIX timer handling for a thread group.
1190f06febc9SFrank Mayhar  */
1191f06febc9SFrank Mayhar static void posix_cpu_timers_init_group(struct signal_struct *sig)
1192f06febc9SFrank Mayhar {
119378d7d407SJiri Slaby 	unsigned long cpu_limit;
119478d7d407SJiri Slaby 
1195316c1608SJason Low 	cpu_limit = READ_ONCE(sig->rlim[RLIMIT_CPU].rlim_cur);
119678d7d407SJiri Slaby 	if (cpu_limit != RLIM_INFINITY) {
119778d7d407SJiri Slaby 		sig->cputime_expires.prof_exp = secs_to_cputime(cpu_limit);
1198d5c373ebSJason Low 		sig->cputimer.running = true;
11996279a751SOleg Nesterov 	}
12006279a751SOleg Nesterov 
1201f06febc9SFrank Mayhar 	/* The timer lists. */
1202f06febc9SFrank Mayhar 	INIT_LIST_HEAD(&sig->cpu_timers[0]);
1203f06febc9SFrank Mayhar 	INIT_LIST_HEAD(&sig->cpu_timers[1]);
1204f06febc9SFrank Mayhar 	INIT_LIST_HEAD(&sig->cpu_timers[2]);
1205f06febc9SFrank Mayhar }
1206f06febc9SFrank Mayhar 
1207a39bc516SAlexey Dobriyan static int copy_signal(unsigned long clone_flags, struct task_struct *tsk)
12081da177e4SLinus Torvalds {
12091da177e4SLinus Torvalds 	struct signal_struct *sig;
12101da177e4SLinus Torvalds 
12114ab6c083SOleg Nesterov 	if (clone_flags & CLONE_THREAD)
1212490dea45SPeter Zijlstra 		return 0;
12136279a751SOleg Nesterov 
1214a56704efSVeaceslav Falico 	sig = kmem_cache_zalloc(signal_cachep, GFP_KERNEL);
12151da177e4SLinus Torvalds 	tsk->signal = sig;
12161da177e4SLinus Torvalds 	if (!sig)
12171da177e4SLinus Torvalds 		return -ENOMEM;
12181da177e4SLinus Torvalds 
1219b3ac022cSOleg Nesterov 	sig->nr_threads = 1;
12201da177e4SLinus Torvalds 	atomic_set(&sig->live, 1);
1221b3ac022cSOleg Nesterov 	atomic_set(&sig->sigcnt, 1);
12220c740d0aSOleg Nesterov 
12230c740d0aSOleg Nesterov 	/* list_add(thread_node, thread_head) without INIT_LIST_HEAD() */
12240c740d0aSOleg Nesterov 	sig->thread_head = (struct list_head)LIST_HEAD_INIT(tsk->thread_node);
12250c740d0aSOleg Nesterov 	tsk->thread_node = (struct list_head)LIST_HEAD_INIT(sig->thread_head);
12260c740d0aSOleg Nesterov 
12271da177e4SLinus Torvalds 	init_waitqueue_head(&sig->wait_chldexit);
1228db51aeccSOleg Nesterov 	sig->curr_target = tsk;
12291da177e4SLinus Torvalds 	init_sigpending(&sig->shared_pending);
12301da177e4SLinus Torvalds 	INIT_LIST_HEAD(&sig->posix_timers);
1231e78c3496SRik van Riel 	seqlock_init(&sig->stats_lock);
12329d7fb042SPeter Zijlstra 	prev_cputime_init(&sig->prev_cputime);
12331da177e4SLinus Torvalds 
1234c9cb2e3dSThomas Gleixner 	hrtimer_init(&sig->real_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
12351da177e4SLinus Torvalds 	sig->real_timer.function = it_real_fn;
12361da177e4SLinus Torvalds 
12371da177e4SLinus Torvalds 	task_lock(current->group_leader);
12381da177e4SLinus Torvalds 	memcpy(sig->rlim, current->signal->rlim, sizeof sig->rlim);
12391da177e4SLinus Torvalds 	task_unlock(current->group_leader);
12401da177e4SLinus Torvalds 
12416279a751SOleg Nesterov 	posix_cpu_timers_init_group(sig);
12426279a751SOleg Nesterov 
1243522ed776SMiloslav Trmac 	tty_audit_fork(sig);
12445091faa4SMike Galbraith 	sched_autogroup_fork(sig);
1245522ed776SMiloslav Trmac 
1246a63d83f4SDavid Rientjes 	sig->oom_score_adj = current->signal->oom_score_adj;
1247dabb16f6SMandeep Singh Baines 	sig->oom_score_adj_min = current->signal->oom_score_adj_min;
124828b83c51SKOSAKI Motohiro 
1249ebec18a6SLennart Poettering 	sig->has_child_subreaper = current->signal->has_child_subreaper ||
1250ebec18a6SLennart Poettering 				   current->signal->is_child_subreaper;
1251ebec18a6SLennart Poettering 
12529b1bf12dSKOSAKI Motohiro 	mutex_init(&sig->cred_guard_mutex);
12539b1bf12dSKOSAKI Motohiro 
12541da177e4SLinus Torvalds 	return 0;
12551da177e4SLinus Torvalds }
12561da177e4SLinus Torvalds 
1257dbd95212SKees Cook static void copy_seccomp(struct task_struct *p)
1258dbd95212SKees Cook {
1259dbd95212SKees Cook #ifdef CONFIG_SECCOMP
1260dbd95212SKees Cook 	/*
1261dbd95212SKees Cook 	 * Must be called with sighand->lock held, which is common to
1262dbd95212SKees Cook 	 * all threads in the group. Holding cred_guard_mutex is not
1263dbd95212SKees Cook 	 * needed because this new task is not yet running and cannot
1264dbd95212SKees Cook 	 * be racing exec.
1265dbd95212SKees Cook 	 */
126669f6a34bSGuenter Roeck 	assert_spin_locked(&current->sighand->siglock);
1267dbd95212SKees Cook 
1268dbd95212SKees Cook 	/* Ref-count the new filter user, and assign it. */
1269dbd95212SKees Cook 	get_seccomp_filter(current);
1270dbd95212SKees Cook 	p->seccomp = current->seccomp;
1271dbd95212SKees Cook 
1272dbd95212SKees Cook 	/*
1273dbd95212SKees Cook 	 * Explicitly enable no_new_privs here in case it got set
1274dbd95212SKees Cook 	 * between the task_struct being duplicated and holding the
1275dbd95212SKees Cook 	 * sighand lock. The seccomp state and nnp must be in sync.
1276dbd95212SKees Cook 	 */
1277dbd95212SKees Cook 	if (task_no_new_privs(current))
1278dbd95212SKees Cook 		task_set_no_new_privs(p);
1279dbd95212SKees Cook 
1280dbd95212SKees Cook 	/*
1281dbd95212SKees Cook 	 * If the parent gained a seccomp mode after copying thread
1282dbd95212SKees Cook 	 * flags and between before we held the sighand lock, we have
1283dbd95212SKees Cook 	 * to manually enable the seccomp thread flag here.
1284dbd95212SKees Cook 	 */
1285dbd95212SKees Cook 	if (p->seccomp.mode != SECCOMP_MODE_DISABLED)
1286dbd95212SKees Cook 		set_tsk_thread_flag(p, TIF_SECCOMP);
1287dbd95212SKees Cook #endif
1288dbd95212SKees Cook }
1289dbd95212SKees Cook 
129017da2bd9SHeiko Carstens SYSCALL_DEFINE1(set_tid_address, int __user *, tidptr)
12911da177e4SLinus Torvalds {
12921da177e4SLinus Torvalds 	current->clear_child_tid = tidptr;
12931da177e4SLinus Torvalds 
1294b488893aSPavel Emelyanov 	return task_pid_vnr(current);
12951da177e4SLinus Torvalds }
12961da177e4SLinus Torvalds 
1297a39bc516SAlexey Dobriyan static void rt_mutex_init_task(struct task_struct *p)
129823f78d4aSIngo Molnar {
12991d615482SThomas Gleixner 	raw_spin_lock_init(&p->pi_lock);
1300e29e175bSZilvinas Valinskas #ifdef CONFIG_RT_MUTEXES
1301fb00aca4SPeter Zijlstra 	p->pi_waiters = RB_ROOT;
1302fb00aca4SPeter Zijlstra 	p->pi_waiters_leftmost = NULL;
130323f78d4aSIngo Molnar 	p->pi_blocked_on = NULL;
130423f78d4aSIngo Molnar #endif
130523f78d4aSIngo Molnar }
130623f78d4aSIngo Molnar 
13071da177e4SLinus Torvalds /*
1308f06febc9SFrank Mayhar  * Initialize POSIX timer handling for a single task.
1309f06febc9SFrank Mayhar  */
1310f06febc9SFrank Mayhar static void posix_cpu_timers_init(struct task_struct *tsk)
1311f06febc9SFrank Mayhar {
131264861634SMartin Schwidefsky 	tsk->cputime_expires.prof_exp = 0;
131364861634SMartin Schwidefsky 	tsk->cputime_expires.virt_exp = 0;
1314f06febc9SFrank Mayhar 	tsk->cputime_expires.sched_exp = 0;
1315f06febc9SFrank Mayhar 	INIT_LIST_HEAD(&tsk->cpu_timers[0]);
1316f06febc9SFrank Mayhar 	INIT_LIST_HEAD(&tsk->cpu_timers[1]);
1317f06febc9SFrank Mayhar 	INIT_LIST_HEAD(&tsk->cpu_timers[2]);
1318f06febc9SFrank Mayhar }
1319f06febc9SFrank Mayhar 
132081907739SOleg Nesterov static inline void
132181907739SOleg Nesterov init_task_pid(struct task_struct *task, enum pid_type type, struct pid *pid)
132281907739SOleg Nesterov {
132381907739SOleg Nesterov 	 task->pids[type].pid = pid;
132481907739SOleg Nesterov }
132581907739SOleg Nesterov 
1326f06febc9SFrank Mayhar /*
13271da177e4SLinus Torvalds  * This creates a new process as a copy of the old one,
13281da177e4SLinus Torvalds  * but does not actually start it yet.
13291da177e4SLinus Torvalds  *
13301da177e4SLinus Torvalds  * It copies the registers, and all the appropriate
13311da177e4SLinus Torvalds  * parts of the process environment (as per the clone
13321da177e4SLinus Torvalds  * flags). The actual kick-off is left to the caller.
13331da177e4SLinus Torvalds  */
133436c8b586SIngo Molnar static struct task_struct *copy_process(unsigned long clone_flags,
13351da177e4SLinus Torvalds 					unsigned long stack_start,
13361da177e4SLinus Torvalds 					unsigned long stack_size,
13371da177e4SLinus Torvalds 					int __user *child_tidptr,
133809a05394SRoland McGrath 					struct pid *pid,
13393033f14aSJosh Triplett 					int trace,
1340725fc629SAndi Kleen 					unsigned long tls,
1341725fc629SAndi Kleen 					int node)
13421da177e4SLinus Torvalds {
13431da177e4SLinus Torvalds 	int retval;
1344a24efe62SMariusz Kozlowski 	struct task_struct *p;
13451da177e4SLinus Torvalds 
13461da177e4SLinus Torvalds 	if ((clone_flags & (CLONE_NEWNS|CLONE_FS)) == (CLONE_NEWNS|CLONE_FS))
13471da177e4SLinus Torvalds 		return ERR_PTR(-EINVAL);
13481da177e4SLinus Torvalds 
1349e66eded8SEric W. Biederman 	if ((clone_flags & (CLONE_NEWUSER|CLONE_FS)) == (CLONE_NEWUSER|CLONE_FS))
1350e66eded8SEric W. Biederman 		return ERR_PTR(-EINVAL);
1351e66eded8SEric W. Biederman 
13521da177e4SLinus Torvalds 	/*
13531da177e4SLinus Torvalds 	 * Thread groups must share signals as well, and detached threads
13541da177e4SLinus Torvalds 	 * can only be started up within the thread group.
13551da177e4SLinus Torvalds 	 */
13561da177e4SLinus Torvalds 	if ((clone_flags & CLONE_THREAD) && !(clone_flags & CLONE_SIGHAND))
13571da177e4SLinus Torvalds 		return ERR_PTR(-EINVAL);
13581da177e4SLinus Torvalds 
13591da177e4SLinus Torvalds 	/*
13601da177e4SLinus Torvalds 	 * Shared signal handlers imply shared VM. By way of the above,
13611da177e4SLinus Torvalds 	 * thread groups also imply shared VM. Blocking this case allows
13621da177e4SLinus Torvalds 	 * for various simplifications in other code.
13631da177e4SLinus Torvalds 	 */
13641da177e4SLinus Torvalds 	if ((clone_flags & CLONE_SIGHAND) && !(clone_flags & CLONE_VM))
13651da177e4SLinus Torvalds 		return ERR_PTR(-EINVAL);
13661da177e4SLinus Torvalds 
1367123be07bSSukadev Bhattiprolu 	/*
1368123be07bSSukadev Bhattiprolu 	 * Siblings of global init remain as zombies on exit since they are
1369123be07bSSukadev Bhattiprolu 	 * not reaped by their parent (swapper). To solve this and to avoid
1370123be07bSSukadev Bhattiprolu 	 * multi-rooted process trees, prevent global and container-inits
1371123be07bSSukadev Bhattiprolu 	 * from creating siblings.
1372123be07bSSukadev Bhattiprolu 	 */
1373123be07bSSukadev Bhattiprolu 	if ((clone_flags & CLONE_PARENT) &&
1374123be07bSSukadev Bhattiprolu 				current->signal->flags & SIGNAL_UNKILLABLE)
1375123be07bSSukadev Bhattiprolu 		return ERR_PTR(-EINVAL);
1376123be07bSSukadev Bhattiprolu 
13778382fcacSEric W. Biederman 	/*
137840a0d32dSOleg Nesterov 	 * If the new process will be in a different pid or user namespace
1379faf00da5SEric W. Biederman 	 * do not allow it to share a thread group with the forking task.
13808382fcacSEric W. Biederman 	 */
1381faf00da5SEric W. Biederman 	if (clone_flags & CLONE_THREAD) {
138240a0d32dSOleg Nesterov 		if ((clone_flags & (CLONE_NEWUSER | CLONE_NEWPID)) ||
138340a0d32dSOleg Nesterov 		    (task_active_pid_ns(current) !=
1384c2b1df2eSAndy Lutomirski 				current->nsproxy->pid_ns_for_children))
13858382fcacSEric W. Biederman 			return ERR_PTR(-EINVAL);
138640a0d32dSOleg Nesterov 	}
13878382fcacSEric W. Biederman 
13881da177e4SLinus Torvalds 	retval = security_task_create(clone_flags);
13891da177e4SLinus Torvalds 	if (retval)
13901da177e4SLinus Torvalds 		goto fork_out;
13911da177e4SLinus Torvalds 
13921da177e4SLinus Torvalds 	retval = -ENOMEM;
1393725fc629SAndi Kleen 	p = dup_task_struct(current, node);
13941da177e4SLinus Torvalds 	if (!p)
13951da177e4SLinus Torvalds 		goto fork_out;
13961da177e4SLinus Torvalds 
1397f7e8b616SSteven Rostedt 	ftrace_graph_init_task(p);
1398f7e8b616SSteven Rostedt 
1399bea493a0SPeter Zijlstra 	rt_mutex_init_task(p);
1400bea493a0SPeter Zijlstra 
1401d12c1a37SIngo Molnar #ifdef CONFIG_PROVE_LOCKING
1402de30a2b3SIngo Molnar 	DEBUG_LOCKS_WARN_ON(!p->hardirqs_enabled);
1403de30a2b3SIngo Molnar 	DEBUG_LOCKS_WARN_ON(!p->softirqs_enabled);
1404de30a2b3SIngo Molnar #endif
14051da177e4SLinus Torvalds 	retval = -EAGAIN;
14063b11a1deSDavid Howells 	if (atomic_read(&p->real_cred->user->processes) >=
140778d7d407SJiri Slaby 			task_rlimit(p, RLIMIT_NPROC)) {
1408b57922b6SEric Paris 		if (p->real_cred->user != INIT_USER &&
1409b57922b6SEric Paris 		    !capable(CAP_SYS_RESOURCE) && !capable(CAP_SYS_ADMIN))
14101da177e4SLinus Torvalds 			goto bad_fork_free;
14111da177e4SLinus Torvalds 	}
141272fa5997SVasiliy Kulikov 	current->flags &= ~PF_NPROC_EXCEEDED;
14131da177e4SLinus Torvalds 
1414f1752eecSDavid Howells 	retval = copy_creds(p, clone_flags);
1415f1752eecSDavid Howells 	if (retval < 0)
1416f1752eecSDavid Howells 		goto bad_fork_free;
14171da177e4SLinus Torvalds 
14181da177e4SLinus Torvalds 	/*
14191da177e4SLinus Torvalds 	 * If multiple threads are within copy_process(), then this check
14201da177e4SLinus Torvalds 	 * triggers too late. This doesn't hurt, the check is only there
14211da177e4SLinus Torvalds 	 * to stop root fork bombs.
14221da177e4SLinus Torvalds 	 */
142304ec93feSLi Zefan 	retval = -EAGAIN;
14241da177e4SLinus Torvalds 	if (nr_threads >= max_threads)
14251da177e4SLinus Torvalds 		goto bad_fork_cleanup_count;
14261da177e4SLinus Torvalds 
1427ca74e92bSShailabh Nagar 	delayacct_tsk_init(p);	/* Must remain after dup_task_struct() */
1428514ddb44SDavid Rientjes 	p->flags &= ~(PF_SUPERPRIV | PF_WQ_WORKER);
1429514ddb44SDavid Rientjes 	p->flags |= PF_FORKNOEXEC;
14301da177e4SLinus Torvalds 	INIT_LIST_HEAD(&p->children);
14311da177e4SLinus Torvalds 	INIT_LIST_HEAD(&p->sibling);
1432f41d911fSPaul E. McKenney 	rcu_copy_process(p);
14331da177e4SLinus Torvalds 	p->vfork_done = NULL;
14341da177e4SLinus Torvalds 	spin_lock_init(&p->alloc_lock);
14351da177e4SLinus Torvalds 
14361da177e4SLinus Torvalds 	init_sigpending(&p->pending);
14371da177e4SLinus Torvalds 
143864861634SMartin Schwidefsky 	p->utime = p->stime = p->gtime = 0;
143964861634SMartin Schwidefsky 	p->utimescaled = p->stimescaled = 0;
14409d7fb042SPeter Zijlstra 	prev_cputime_init(&p->prev_cputime);
14419d7fb042SPeter Zijlstra 
14426a61671bSFrederic Weisbecker #ifdef CONFIG_VIRT_CPU_ACCOUNTING_GEN
1443b7ce2277SFrederic Weisbecker 	seqcount_init(&p->vtime_seqcount);
14446a61671bSFrederic Weisbecker 	p->vtime_snap = 0;
14457098c1eaSFrederic Weisbecker 	p->vtime_snap_whence = VTIME_INACTIVE;
14466a61671bSFrederic Weisbecker #endif
14476a61671bSFrederic Weisbecker 
1448a3a2e76cSKAMEZAWA Hiroyuki #if defined(SPLIT_RSS_COUNTING)
1449a3a2e76cSKAMEZAWA Hiroyuki 	memset(&p->rss_stat, 0, sizeof(p->rss_stat));
1450a3a2e76cSKAMEZAWA Hiroyuki #endif
1451172ba844SBalbir Singh 
14526976675dSArjan van de Ven 	p->default_timer_slack_ns = current->timer_slack_ns;
14536976675dSArjan van de Ven 
14545995477aSAndrea Righi 	task_io_accounting_init(&p->ioac);
14551da177e4SLinus Torvalds 	acct_clear_integrals(p);
14561da177e4SLinus Torvalds 
1457f06febc9SFrank Mayhar 	posix_cpu_timers_init(p);
14581da177e4SLinus Torvalds 
1459ccbf62d8SThomas Gleixner 	p->start_time = ktime_get_ns();
146057e0be04SThomas Gleixner 	p->real_start_time = ktime_get_boot_ns();
14611da177e4SLinus Torvalds 	p->io_context = NULL;
14621da177e4SLinus Torvalds 	p->audit_context = NULL;
1463257058aeSTejun Heo 	threadgroup_change_begin(current);
1464b4f48b63SPaul Menage 	cgroup_fork(p);
14651da177e4SLinus Torvalds #ifdef CONFIG_NUMA
1466846a16bfSLee Schermerhorn 	p->mempolicy = mpol_dup(p->mempolicy);
14671da177e4SLinus Torvalds 	if (IS_ERR(p->mempolicy)) {
14681da177e4SLinus Torvalds 		retval = PTR_ERR(p->mempolicy);
14691da177e4SLinus Torvalds 		p->mempolicy = NULL;
1470e8604cb4SLi Zefan 		goto bad_fork_cleanup_threadgroup_lock;
14711da177e4SLinus Torvalds 	}
14721da177e4SLinus Torvalds #endif
1473778d3b0fSMichal Hocko #ifdef CONFIG_CPUSETS
1474778d3b0fSMichal Hocko 	p->cpuset_mem_spread_rotor = NUMA_NO_NODE;
1475778d3b0fSMichal Hocko 	p->cpuset_slab_spread_rotor = NUMA_NO_NODE;
1476cc9a6c87SMel Gorman 	seqcount_init(&p->mems_allowed_seq);
1477778d3b0fSMichal Hocko #endif
1478de30a2b3SIngo Molnar #ifdef CONFIG_TRACE_IRQFLAGS
1479de30a2b3SIngo Molnar 	p->irq_events = 0;
1480de30a2b3SIngo Molnar 	p->hardirqs_enabled = 0;
1481de30a2b3SIngo Molnar 	p->hardirq_enable_ip = 0;
1482de30a2b3SIngo Molnar 	p->hardirq_enable_event = 0;
1483de30a2b3SIngo Molnar 	p->hardirq_disable_ip = _THIS_IP_;
1484de30a2b3SIngo Molnar 	p->hardirq_disable_event = 0;
1485de30a2b3SIngo Molnar 	p->softirqs_enabled = 1;
1486de30a2b3SIngo Molnar 	p->softirq_enable_ip = _THIS_IP_;
1487de30a2b3SIngo Molnar 	p->softirq_enable_event = 0;
1488de30a2b3SIngo Molnar 	p->softirq_disable_ip = 0;
1489de30a2b3SIngo Molnar 	p->softirq_disable_event = 0;
1490de30a2b3SIngo Molnar 	p->hardirq_context = 0;
1491de30a2b3SIngo Molnar 	p->softirq_context = 0;
1492de30a2b3SIngo Molnar #endif
14938bcbde54SDavid Hildenbrand 
14948bcbde54SDavid Hildenbrand 	p->pagefault_disabled = 0;
14958bcbde54SDavid Hildenbrand 
1496fbb9ce95SIngo Molnar #ifdef CONFIG_LOCKDEP
1497fbb9ce95SIngo Molnar 	p->lockdep_depth = 0; /* no locks held yet */
1498fbb9ce95SIngo Molnar 	p->curr_chain_key = 0;
1499fbb9ce95SIngo Molnar 	p->lockdep_recursion = 0;
1500fbb9ce95SIngo Molnar #endif
15011da177e4SLinus Torvalds 
1502408894eeSIngo Molnar #ifdef CONFIG_DEBUG_MUTEXES
1503408894eeSIngo Molnar 	p->blocked_on = NULL; /* not blocked yet */
1504408894eeSIngo Molnar #endif
1505cafe5635SKent Overstreet #ifdef CONFIG_BCACHE
1506cafe5635SKent Overstreet 	p->sequential_io	= 0;
1507cafe5635SKent Overstreet 	p->sequential_io_avg	= 0;
1508cafe5635SKent Overstreet #endif
15090f481406SMarkus Metzger 
15103c90e6e9SSrivatsa Vaddagiri 	/* Perform scheduler related setup. Assign this task to a CPU. */
1511aab03e05SDario Faggioli 	retval = sched_fork(clone_flags, p);
1512aab03e05SDario Faggioli 	if (retval)
1513aab03e05SDario Faggioli 		goto bad_fork_cleanup_policy;
15146ab423e0SPeter Zijlstra 
1515cdd6c482SIngo Molnar 	retval = perf_event_init_task(p);
15166ab423e0SPeter Zijlstra 	if (retval)
15176ab423e0SPeter Zijlstra 		goto bad_fork_cleanup_policy;
1518fb0a685cSDaniel Rebelo de Oliveira 	retval = audit_alloc(p);
1519fb0a685cSDaniel Rebelo de Oliveira 	if (retval)
15206c72e350SPeter Zijlstra 		goto bad_fork_cleanup_perf;
15211da177e4SLinus Torvalds 	/* copy all the process information */
1522ab602f79SJack Miller 	shm_init_task(p);
1523fb0a685cSDaniel Rebelo de Oliveira 	retval = copy_semundo(clone_flags, p);
1524fb0a685cSDaniel Rebelo de Oliveira 	if (retval)
15251da177e4SLinus Torvalds 		goto bad_fork_cleanup_audit;
1526fb0a685cSDaniel Rebelo de Oliveira 	retval = copy_files(clone_flags, p);
1527fb0a685cSDaniel Rebelo de Oliveira 	if (retval)
15281da177e4SLinus Torvalds 		goto bad_fork_cleanup_semundo;
1529fb0a685cSDaniel Rebelo de Oliveira 	retval = copy_fs(clone_flags, p);
1530fb0a685cSDaniel Rebelo de Oliveira 	if (retval)
15311da177e4SLinus Torvalds 		goto bad_fork_cleanup_files;
1532fb0a685cSDaniel Rebelo de Oliveira 	retval = copy_sighand(clone_flags, p);
1533fb0a685cSDaniel Rebelo de Oliveira 	if (retval)
15341da177e4SLinus Torvalds 		goto bad_fork_cleanup_fs;
1535fb0a685cSDaniel Rebelo de Oliveira 	retval = copy_signal(clone_flags, p);
1536fb0a685cSDaniel Rebelo de Oliveira 	if (retval)
15371da177e4SLinus Torvalds 		goto bad_fork_cleanup_sighand;
1538fb0a685cSDaniel Rebelo de Oliveira 	retval = copy_mm(clone_flags, p);
1539fb0a685cSDaniel Rebelo de Oliveira 	if (retval)
15401da177e4SLinus Torvalds 		goto bad_fork_cleanup_signal;
1541fb0a685cSDaniel Rebelo de Oliveira 	retval = copy_namespaces(clone_flags, p);
1542fb0a685cSDaniel Rebelo de Oliveira 	if (retval)
1543d84f4f99SDavid Howells 		goto bad_fork_cleanup_mm;
1544fb0a685cSDaniel Rebelo de Oliveira 	retval = copy_io(clone_flags, p);
1545fb0a685cSDaniel Rebelo de Oliveira 	if (retval)
1546fd0928dfSJens Axboe 		goto bad_fork_cleanup_namespaces;
15473033f14aSJosh Triplett 	retval = copy_thread_tls(clone_flags, stack_start, stack_size, p, tls);
15481da177e4SLinus Torvalds 	if (retval)
1549fd0928dfSJens Axboe 		goto bad_fork_cleanup_io;
15501da177e4SLinus Torvalds 
1551425fb2b4SPavel Emelyanov 	if (pid != &init_struct_pid) {
1552c2b1df2eSAndy Lutomirski 		pid = alloc_pid(p->nsproxy->pid_ns_for_children);
155335f71bc0SMichal Hocko 		if (IS_ERR(pid)) {
155435f71bc0SMichal Hocko 			retval = PTR_ERR(pid);
15550740aa5fSJiri Slaby 			goto bad_fork_cleanup_thread;
1556425fb2b4SPavel Emelyanov 		}
155735f71bc0SMichal Hocko 	}
1558425fb2b4SPavel Emelyanov 
15591da177e4SLinus Torvalds 	p->set_child_tid = (clone_flags & CLONE_CHILD_SETTID) ? child_tidptr : NULL;
15601da177e4SLinus Torvalds 	/*
15611da177e4SLinus Torvalds 	 * Clear TID on mm_release()?
15621da177e4SLinus Torvalds 	 */
15631da177e4SLinus Torvalds 	p->clear_child_tid = (clone_flags & CLONE_CHILD_CLEARTID) ? child_tidptr : NULL;
156473c10101SJens Axboe #ifdef CONFIG_BLOCK
156573c10101SJens Axboe 	p->plug = NULL;
156673c10101SJens Axboe #endif
156742b2dd0aSAlexey Dobriyan #ifdef CONFIG_FUTEX
15688f17d3a5SIngo Molnar 	p->robust_list = NULL;
15698f17d3a5SIngo Molnar #ifdef CONFIG_COMPAT
15708f17d3a5SIngo Molnar 	p->compat_robust_list = NULL;
15718f17d3a5SIngo Molnar #endif
1572c87e2837SIngo Molnar 	INIT_LIST_HEAD(&p->pi_state_list);
1573c87e2837SIngo Molnar 	p->pi_state_cache = NULL;
157442b2dd0aSAlexey Dobriyan #endif
15751da177e4SLinus Torvalds 	/*
1576f9a3879aSGOTO Masanori 	 * sigaltstack should be cleared when sharing the same VM
1577f9a3879aSGOTO Masanori 	 */
1578f9a3879aSGOTO Masanori 	if ((clone_flags & (CLONE_VM|CLONE_VFORK)) == CLONE_VM)
15792a742138SStas Sergeev 		sas_ss_reset(p);
1580f9a3879aSGOTO Masanori 
1581f9a3879aSGOTO Masanori 	/*
15826580807dSOleg Nesterov 	 * Syscall tracing and stepping should be turned off in the
15836580807dSOleg Nesterov 	 * child regardless of CLONE_PTRACE.
15841da177e4SLinus Torvalds 	 */
15856580807dSOleg Nesterov 	user_disable_single_step(p);
15861da177e4SLinus Torvalds 	clear_tsk_thread_flag(p, TIF_SYSCALL_TRACE);
1587ed75e8d5SLaurent Vivier #ifdef TIF_SYSCALL_EMU
1588ed75e8d5SLaurent Vivier 	clear_tsk_thread_flag(p, TIF_SYSCALL_EMU);
1589ed75e8d5SLaurent Vivier #endif
15909745512cSArjan van de Ven 	clear_all_latency_tracing(p);
15911da177e4SLinus Torvalds 
15921da177e4SLinus Torvalds 	/* ok, now we should be set up.. */
159318c830dfSOleg Nesterov 	p->pid = pid_nr(pid);
159418c830dfSOleg Nesterov 	if (clone_flags & CLONE_THREAD) {
15955f8aadd8SOleg Nesterov 		p->exit_signal = -1;
159618c830dfSOleg Nesterov 		p->group_leader = current->group_leader;
159718c830dfSOleg Nesterov 		p->tgid = current->tgid;
159818c830dfSOleg Nesterov 	} else {
159918c830dfSOleg Nesterov 		if (clone_flags & CLONE_PARENT)
16005f8aadd8SOleg Nesterov 			p->exit_signal = current->group_leader->exit_signal;
16015f8aadd8SOleg Nesterov 		else
16025f8aadd8SOleg Nesterov 			p->exit_signal = (clone_flags & CSIGNAL);
160318c830dfSOleg Nesterov 		p->group_leader = p;
160418c830dfSOleg Nesterov 		p->tgid = p->pid;
160518c830dfSOleg Nesterov 	}
16065f8aadd8SOleg Nesterov 
16079d823e8fSWu Fengguang 	p->nr_dirtied = 0;
16089d823e8fSWu Fengguang 	p->nr_dirtied_pause = 128 >> (PAGE_SHIFT - 10);
160983712358SWu Fengguang 	p->dirty_paused_when = 0;
16109d823e8fSWu Fengguang 
1611bb8cbbfeSOleg Nesterov 	p->pdeath_signal = 0;
161247e65328SOleg Nesterov 	INIT_LIST_HEAD(&p->thread_group);
1613158e1645SAl Viro 	p->task_works = NULL;
16141da177e4SLinus Torvalds 
161518c830dfSOleg Nesterov 	/*
16167e47682eSAleksa Sarai 	 * Ensure that the cgroup subsystem policies allow the new process to be
16177e47682eSAleksa Sarai 	 * forked. It should be noted the the new process's css_set can be changed
16187e47682eSAleksa Sarai 	 * between here and cgroup_post_fork() if an organisation operation is in
16197e47682eSAleksa Sarai 	 * progress.
16207e47682eSAleksa Sarai 	 */
1621b53202e6SOleg Nesterov 	retval = cgroup_can_fork(p);
16227e47682eSAleksa Sarai 	if (retval)
16237e47682eSAleksa Sarai 		goto bad_fork_free_pid;
16247e47682eSAleksa Sarai 
16257e47682eSAleksa Sarai 	/*
162618c830dfSOleg Nesterov 	 * Make it visible to the rest of the system, but dont wake it up yet.
162718c830dfSOleg Nesterov 	 * Need tasklist lock for parent etc handling!
162818c830dfSOleg Nesterov 	 */
16291da177e4SLinus Torvalds 	write_lock_irq(&tasklist_lock);
16301da177e4SLinus Torvalds 
16311da177e4SLinus Torvalds 	/* CLONE_PARENT re-uses the old parent */
16322d5516cbSOleg Nesterov 	if (clone_flags & (CLONE_PARENT|CLONE_THREAD)) {
16331da177e4SLinus Torvalds 		p->real_parent = current->real_parent;
16342d5516cbSOleg Nesterov 		p->parent_exec_id = current->parent_exec_id;
16352d5516cbSOleg Nesterov 	} else {
16361da177e4SLinus Torvalds 		p->real_parent = current;
16372d5516cbSOleg Nesterov 		p->parent_exec_id = current->self_exec_id;
16382d5516cbSOleg Nesterov 	}
16391da177e4SLinus Torvalds 
16401da177e4SLinus Torvalds 	spin_lock(&current->sighand->siglock);
16414a2c7a78SOleg Nesterov 
16424a2c7a78SOleg Nesterov 	/*
1643dbd95212SKees Cook 	 * Copy seccomp details explicitly here, in case they were changed
1644dbd95212SKees Cook 	 * before holding sighand lock.
1645dbd95212SKees Cook 	 */
1646dbd95212SKees Cook 	copy_seccomp(p);
1647dbd95212SKees Cook 
1648dbd95212SKees Cook 	/*
16494a2c7a78SOleg Nesterov 	 * Process group and session signals need to be delivered to just the
16504a2c7a78SOleg Nesterov 	 * parent before the fork or both the parent and the child after the
16514a2c7a78SOleg Nesterov 	 * fork. Restart if a signal comes in before we add the new process to
16524a2c7a78SOleg Nesterov 	 * it's process group.
16534a2c7a78SOleg Nesterov 	 * A fatal signal pending means that current will exit, so the new
16544a2c7a78SOleg Nesterov 	 * thread can't slip out of an OOM kill (or normal SIGKILL).
16554a2c7a78SOleg Nesterov 	*/
16564a2c7a78SOleg Nesterov 	recalc_sigpending();
16574a2c7a78SOleg Nesterov 	if (signal_pending(current)) {
16584a2c7a78SOleg Nesterov 		spin_unlock(&current->sighand->siglock);
16594a2c7a78SOleg Nesterov 		write_unlock_irq(&tasklist_lock);
16604a2c7a78SOleg Nesterov 		retval = -ERESTARTNOINTR;
16617e47682eSAleksa Sarai 		goto bad_fork_cancel_cgroup;
16624a2c7a78SOleg Nesterov 	}
16634a2c7a78SOleg Nesterov 
166473b9ebfeSOleg Nesterov 	if (likely(p->pid)) {
16654b9d33e6STejun Heo 		ptrace_init_task(p, (clone_flags & CLONE_PTRACE) || trace);
16661da177e4SLinus Torvalds 
166781907739SOleg Nesterov 		init_task_pid(p, PIDTYPE_PID, pid);
16681da177e4SLinus Torvalds 		if (thread_group_leader(p)) {
166981907739SOleg Nesterov 			init_task_pid(p, PIDTYPE_PGID, task_pgrp(current));
167081907739SOleg Nesterov 			init_task_pid(p, PIDTYPE_SID, task_session(current));
167181907739SOleg Nesterov 
16721c4042c2SEric W. Biederman 			if (is_child_reaper(pid)) {
167317cf22c3SEric W. Biederman 				ns_of_pid(pid)->child_reaper = p;
16741c4042c2SEric W. Biederman 				p->signal->flags |= SIGNAL_UNKILLABLE;
16751c4042c2SEric W. Biederman 			}
16765cd17569SEric W. Biederman 
1677fea9d175SOleg Nesterov 			p->signal->leader_pid = pid;
16789c9f4dedSAlan Cox 			p->signal->tty = tty_kref_get(current->signal->tty);
16799cd80bbbSOleg Nesterov 			list_add_tail(&p->sibling, &p->real_parent->children);
16805e85d4abSEric W. Biederman 			list_add_tail_rcu(&p->tasks, &init_task.tasks);
168181907739SOleg Nesterov 			attach_pid(p, PIDTYPE_PGID);
168281907739SOleg Nesterov 			attach_pid(p, PIDTYPE_SID);
1683909ea964SChristoph Lameter 			__this_cpu_inc(process_counts);
168480628ca0SOleg Nesterov 		} else {
168580628ca0SOleg Nesterov 			current->signal->nr_threads++;
168680628ca0SOleg Nesterov 			atomic_inc(&current->signal->live);
168780628ca0SOleg Nesterov 			atomic_inc(&current->signal->sigcnt);
168880628ca0SOleg Nesterov 			list_add_tail_rcu(&p->thread_group,
168980628ca0SOleg Nesterov 					  &p->group_leader->thread_group);
16900c740d0aSOleg Nesterov 			list_add_tail_rcu(&p->thread_node,
16910c740d0aSOleg Nesterov 					  &p->signal->thread_head);
16921da177e4SLinus Torvalds 		}
169381907739SOleg Nesterov 		attach_pid(p, PIDTYPE_PID);
16941da177e4SLinus Torvalds 		nr_threads++;
169573b9ebfeSOleg Nesterov 	}
169673b9ebfeSOleg Nesterov 
16971da177e4SLinus Torvalds 	total_forks++;
16983f17da69SOleg Nesterov 	spin_unlock(&current->sighand->siglock);
16994af4206bSOleg Nesterov 	syscall_tracepoint_update(p);
17001da177e4SLinus Torvalds 	write_unlock_irq(&tasklist_lock);
17014af4206bSOleg Nesterov 
1702c13cf856SAndrew Morton 	proc_fork_connector(p);
1703b53202e6SOleg Nesterov 	cgroup_post_fork(p);
1704257058aeSTejun Heo 	threadgroup_change_end(current);
1705cdd6c482SIngo Molnar 	perf_event_fork(p);
170643d2b113SKAMEZAWA Hiroyuki 
170743d2b113SKAMEZAWA Hiroyuki 	trace_task_newtask(p, clone_flags);
17083ab67966SOleg Nesterov 	uprobe_copy_process(p, clone_flags);
170943d2b113SKAMEZAWA Hiroyuki 
17101da177e4SLinus Torvalds 	return p;
17111da177e4SLinus Torvalds 
17127e47682eSAleksa Sarai bad_fork_cancel_cgroup:
1713b53202e6SOleg Nesterov 	cgroup_cancel_fork(p);
1714425fb2b4SPavel Emelyanov bad_fork_free_pid:
1715425fb2b4SPavel Emelyanov 	if (pid != &init_struct_pid)
1716425fb2b4SPavel Emelyanov 		free_pid(pid);
17170740aa5fSJiri Slaby bad_fork_cleanup_thread:
17180740aa5fSJiri Slaby 	exit_thread(p);
1719fd0928dfSJens Axboe bad_fork_cleanup_io:
1720b69f2292SLouis Rilling 	if (p->io_context)
1721b69f2292SLouis Rilling 		exit_io_context(p);
1722ab516013SSerge E. Hallyn bad_fork_cleanup_namespaces:
1723444f378bSLinus Torvalds 	exit_task_namespaces(p);
17241da177e4SLinus Torvalds bad_fork_cleanup_mm:
1725c9f01245SDavid Rientjes 	if (p->mm)
17261da177e4SLinus Torvalds 		mmput(p->mm);
17271da177e4SLinus Torvalds bad_fork_cleanup_signal:
17284ab6c083SOleg Nesterov 	if (!(clone_flags & CLONE_THREAD))
17291c5354deSMike Galbraith 		free_signal_struct(p->signal);
17301da177e4SLinus Torvalds bad_fork_cleanup_sighand:
1731a7e5328aSOleg Nesterov 	__cleanup_sighand(p->sighand);
17321da177e4SLinus Torvalds bad_fork_cleanup_fs:
17331da177e4SLinus Torvalds 	exit_fs(p); /* blocking */
17341da177e4SLinus Torvalds bad_fork_cleanup_files:
17351da177e4SLinus Torvalds 	exit_files(p); /* blocking */
17361da177e4SLinus Torvalds bad_fork_cleanup_semundo:
17371da177e4SLinus Torvalds 	exit_sem(p);
17381da177e4SLinus Torvalds bad_fork_cleanup_audit:
17391da177e4SLinus Torvalds 	audit_free(p);
17406c72e350SPeter Zijlstra bad_fork_cleanup_perf:
1741cdd6c482SIngo Molnar 	perf_event_free_task(p);
17426c72e350SPeter Zijlstra bad_fork_cleanup_policy:
17431da177e4SLinus Torvalds #ifdef CONFIG_NUMA
1744f0be3d32SLee Schermerhorn 	mpol_put(p->mempolicy);
1745e8604cb4SLi Zefan bad_fork_cleanup_threadgroup_lock:
17461da177e4SLinus Torvalds #endif
1747257058aeSTejun Heo 	threadgroup_change_end(current);
174835df17c5SShailabh Nagar 	delayacct_tsk_free(p);
17491da177e4SLinus Torvalds bad_fork_cleanup_count:
1750d84f4f99SDavid Howells 	atomic_dec(&p->cred->user->processes);
1751e0e81739SDavid Howells 	exit_creds(p);
17521da177e4SLinus Torvalds bad_fork_free:
17531da177e4SLinus Torvalds 	free_task(p);
1754fe7d37d1SOleg Nesterov fork_out:
1755fe7d37d1SOleg Nesterov 	return ERR_PTR(retval);
17561da177e4SLinus Torvalds }
17571da177e4SLinus Torvalds 
1758f106eee1SOleg Nesterov static inline void init_idle_pids(struct pid_link *links)
1759f106eee1SOleg Nesterov {
1760f106eee1SOleg Nesterov 	enum pid_type type;
1761f106eee1SOleg Nesterov 
1762f106eee1SOleg Nesterov 	for (type = PIDTYPE_PID; type < PIDTYPE_MAX; ++type) {
1763f106eee1SOleg Nesterov 		INIT_HLIST_NODE(&links[type].node); /* not really needed */
1764f106eee1SOleg Nesterov 		links[type].pid = &init_struct_pid;
1765f106eee1SOleg Nesterov 	}
1766f106eee1SOleg Nesterov }
1767f106eee1SOleg Nesterov 
17680db0628dSPaul Gortmaker struct task_struct *fork_idle(int cpu)
17691da177e4SLinus Torvalds {
177036c8b586SIngo Molnar 	struct task_struct *task;
1771725fc629SAndi Kleen 	task = copy_process(CLONE_VM, 0, 0, NULL, &init_struct_pid, 0, 0,
1772725fc629SAndi Kleen 			    cpu_to_node(cpu));
1773f106eee1SOleg Nesterov 	if (!IS_ERR(task)) {
1774f106eee1SOleg Nesterov 		init_idle_pids(task->pids);
17751da177e4SLinus Torvalds 		init_idle(task, cpu);
1776f106eee1SOleg Nesterov 	}
177773b9ebfeSOleg Nesterov 
17781da177e4SLinus Torvalds 	return task;
17791da177e4SLinus Torvalds }
17801da177e4SLinus Torvalds 
17811da177e4SLinus Torvalds /*
17821da177e4SLinus Torvalds  *  Ok, this is the main fork-routine.
17831da177e4SLinus Torvalds  *
17841da177e4SLinus Torvalds  * It copies the process, and if successful kick-starts
17851da177e4SLinus Torvalds  * it and waits for it to finish using the VM if required.
17861da177e4SLinus Torvalds  */
17873033f14aSJosh Triplett long _do_fork(unsigned long clone_flags,
17881da177e4SLinus Torvalds 	      unsigned long stack_start,
17891da177e4SLinus Torvalds 	      unsigned long stack_size,
17901da177e4SLinus Torvalds 	      int __user *parent_tidptr,
17913033f14aSJosh Triplett 	      int __user *child_tidptr,
17923033f14aSJosh Triplett 	      unsigned long tls)
17931da177e4SLinus Torvalds {
17941da177e4SLinus Torvalds 	struct task_struct *p;
17951da177e4SLinus Torvalds 	int trace = 0;
179692476d7fSEric W. Biederman 	long nr;
17971da177e4SLinus Torvalds 
1798bdff746aSAndrew Morton 	/*
17994b9d33e6STejun Heo 	 * Determine whether and which event to report to ptracer.  When
18004b9d33e6STejun Heo 	 * called from kernel_thread or CLONE_UNTRACED is explicitly
18014b9d33e6STejun Heo 	 * requested, no event is reported; otherwise, report if the event
18024b9d33e6STejun Heo 	 * for the type of forking is enabled.
180309a05394SRoland McGrath 	 */
1804e80d6661SAl Viro 	if (!(clone_flags & CLONE_UNTRACED)) {
18054b9d33e6STejun Heo 		if (clone_flags & CLONE_VFORK)
18064b9d33e6STejun Heo 			trace = PTRACE_EVENT_VFORK;
18074b9d33e6STejun Heo 		else if ((clone_flags & CSIGNAL) != SIGCHLD)
18084b9d33e6STejun Heo 			trace = PTRACE_EVENT_CLONE;
18094b9d33e6STejun Heo 		else
18104b9d33e6STejun Heo 			trace = PTRACE_EVENT_FORK;
18114b9d33e6STejun Heo 
18124b9d33e6STejun Heo 		if (likely(!ptrace_event_enabled(current, trace)))
18134b9d33e6STejun Heo 			trace = 0;
18144b9d33e6STejun Heo 	}
18151da177e4SLinus Torvalds 
181662e791c1SAl Viro 	p = copy_process(clone_flags, stack_start, stack_size,
1817725fc629SAndi Kleen 			 child_tidptr, NULL, trace, tls, NUMA_NO_NODE);
18181da177e4SLinus Torvalds 	/*
18191da177e4SLinus Torvalds 	 * Do this prior waking up the new thread - the thread pointer
18201da177e4SLinus Torvalds 	 * might get invalid after that point, if the thread exits quickly.
18211da177e4SLinus Torvalds 	 */
18221da177e4SLinus Torvalds 	if (!IS_ERR(p)) {
18231da177e4SLinus Torvalds 		struct completion vfork;
18244e52365fSMatthew Dempsky 		struct pid *pid;
18251da177e4SLinus Torvalds 
18260a16b607SMathieu Desnoyers 		trace_sched_process_fork(current, p);
18270a16b607SMathieu Desnoyers 
18284e52365fSMatthew Dempsky 		pid = get_task_pid(p, PIDTYPE_PID);
18294e52365fSMatthew Dempsky 		nr = pid_vnr(pid);
183030e49c26SPavel Emelyanov 
183130e49c26SPavel Emelyanov 		if (clone_flags & CLONE_PARENT_SETTID)
183230e49c26SPavel Emelyanov 			put_user(nr, parent_tidptr);
1833a6f5e063SSukadev Bhattiprolu 
18341da177e4SLinus Torvalds 		if (clone_flags & CLONE_VFORK) {
18351da177e4SLinus Torvalds 			p->vfork_done = &vfork;
18361da177e4SLinus Torvalds 			init_completion(&vfork);
1837d68b46feSOleg Nesterov 			get_task_struct(p);
18381da177e4SLinus Torvalds 		}
18391da177e4SLinus Torvalds 
18403e51e3edSSamir Bellabes 		wake_up_new_task(p);
18411da177e4SLinus Torvalds 
18424b9d33e6STejun Heo 		/* forking complete and child started to run, tell ptracer */
18434b9d33e6STejun Heo 		if (unlikely(trace))
18444e52365fSMatthew Dempsky 			ptrace_event_pid(trace, pid);
184509a05394SRoland McGrath 
18461da177e4SLinus Torvalds 		if (clone_flags & CLONE_VFORK) {
1847d68b46feSOleg Nesterov 			if (!wait_for_vfork_done(p, &vfork))
18484e52365fSMatthew Dempsky 				ptrace_event_pid(PTRACE_EVENT_VFORK_DONE, pid);
18499f59ce5dSChuck Ebbert 		}
18504e52365fSMatthew Dempsky 
18514e52365fSMatthew Dempsky 		put_pid(pid);
18521da177e4SLinus Torvalds 	} else {
185392476d7fSEric W. Biederman 		nr = PTR_ERR(p);
18541da177e4SLinus Torvalds 	}
185592476d7fSEric W. Biederman 	return nr;
18561da177e4SLinus Torvalds }
18571da177e4SLinus Torvalds 
18583033f14aSJosh Triplett #ifndef CONFIG_HAVE_COPY_THREAD_TLS
18593033f14aSJosh Triplett /* For compatibility with architectures that call do_fork directly rather than
18603033f14aSJosh Triplett  * using the syscall entry points below. */
18613033f14aSJosh Triplett long do_fork(unsigned long clone_flags,
18623033f14aSJosh Triplett 	      unsigned long stack_start,
18633033f14aSJosh Triplett 	      unsigned long stack_size,
18643033f14aSJosh Triplett 	      int __user *parent_tidptr,
18653033f14aSJosh Triplett 	      int __user *child_tidptr)
18663033f14aSJosh Triplett {
18673033f14aSJosh Triplett 	return _do_fork(clone_flags, stack_start, stack_size,
18683033f14aSJosh Triplett 			parent_tidptr, child_tidptr, 0);
18693033f14aSJosh Triplett }
18703033f14aSJosh Triplett #endif
18713033f14aSJosh Triplett 
18722aa3a7f8SAl Viro /*
18732aa3a7f8SAl Viro  * Create a kernel thread.
18742aa3a7f8SAl Viro  */
18752aa3a7f8SAl Viro pid_t kernel_thread(int (*fn)(void *), void *arg, unsigned long flags)
18762aa3a7f8SAl Viro {
18773033f14aSJosh Triplett 	return _do_fork(flags|CLONE_VM|CLONE_UNTRACED, (unsigned long)fn,
18783033f14aSJosh Triplett 		(unsigned long)arg, NULL, NULL, 0);
18792aa3a7f8SAl Viro }
18802aa3a7f8SAl Viro 
1881d2125043SAl Viro #ifdef __ARCH_WANT_SYS_FORK
1882d2125043SAl Viro SYSCALL_DEFINE0(fork)
1883d2125043SAl Viro {
1884d2125043SAl Viro #ifdef CONFIG_MMU
18853033f14aSJosh Triplett 	return _do_fork(SIGCHLD, 0, 0, NULL, NULL, 0);
1886d2125043SAl Viro #else
1887d2125043SAl Viro 	/* can not support in nommu mode */
18885d59e182SDaeseok Youn 	return -EINVAL;
1889d2125043SAl Viro #endif
1890d2125043SAl Viro }
1891d2125043SAl Viro #endif
1892d2125043SAl Viro 
1893d2125043SAl Viro #ifdef __ARCH_WANT_SYS_VFORK
1894d2125043SAl Viro SYSCALL_DEFINE0(vfork)
1895d2125043SAl Viro {
18963033f14aSJosh Triplett 	return _do_fork(CLONE_VFORK | CLONE_VM | SIGCHLD, 0,
18973033f14aSJosh Triplett 			0, NULL, NULL, 0);
1898d2125043SAl Viro }
1899d2125043SAl Viro #endif
1900d2125043SAl Viro 
1901d2125043SAl Viro #ifdef __ARCH_WANT_SYS_CLONE
1902d2125043SAl Viro #ifdef CONFIG_CLONE_BACKWARDS
1903d2125043SAl Viro SYSCALL_DEFINE5(clone, unsigned long, clone_flags, unsigned long, newsp,
1904d2125043SAl Viro 		 int __user *, parent_tidptr,
19053033f14aSJosh Triplett 		 unsigned long, tls,
1906d2125043SAl Viro 		 int __user *, child_tidptr)
1907d2125043SAl Viro #elif defined(CONFIG_CLONE_BACKWARDS2)
1908d2125043SAl Viro SYSCALL_DEFINE5(clone, unsigned long, newsp, unsigned long, clone_flags,
1909d2125043SAl Viro 		 int __user *, parent_tidptr,
1910d2125043SAl Viro 		 int __user *, child_tidptr,
19113033f14aSJosh Triplett 		 unsigned long, tls)
1912dfa9771aSMichal Simek #elif defined(CONFIG_CLONE_BACKWARDS3)
1913dfa9771aSMichal Simek SYSCALL_DEFINE6(clone, unsigned long, clone_flags, unsigned long, newsp,
1914dfa9771aSMichal Simek 		int, stack_size,
1915dfa9771aSMichal Simek 		int __user *, parent_tidptr,
1916dfa9771aSMichal Simek 		int __user *, child_tidptr,
19173033f14aSJosh Triplett 		unsigned long, tls)
1918d2125043SAl Viro #else
1919d2125043SAl Viro SYSCALL_DEFINE5(clone, unsigned long, clone_flags, unsigned long, newsp,
1920d2125043SAl Viro 		 int __user *, parent_tidptr,
1921d2125043SAl Viro 		 int __user *, child_tidptr,
19223033f14aSJosh Triplett 		 unsigned long, tls)
1923d2125043SAl Viro #endif
1924d2125043SAl Viro {
19253033f14aSJosh Triplett 	return _do_fork(clone_flags, newsp, 0, parent_tidptr, child_tidptr, tls);
1926d2125043SAl Viro }
1927d2125043SAl Viro #endif
1928d2125043SAl Viro 
19295fd63b30SRavikiran G Thirumalai #ifndef ARCH_MIN_MMSTRUCT_ALIGN
19305fd63b30SRavikiran G Thirumalai #define ARCH_MIN_MMSTRUCT_ALIGN 0
19315fd63b30SRavikiran G Thirumalai #endif
19325fd63b30SRavikiran G Thirumalai 
193351cc5068SAlexey Dobriyan static void sighand_ctor(void *data)
1934aa1757f9SOleg Nesterov {
1935aa1757f9SOleg Nesterov 	struct sighand_struct *sighand = data;
1936aa1757f9SOleg Nesterov 
1937aa1757f9SOleg Nesterov 	spin_lock_init(&sighand->siglock);
1938b8fceee1SDavide Libenzi 	init_waitqueue_head(&sighand->signalfd_wqh);
1939fba2afaaSDavide Libenzi }
1940aa1757f9SOleg Nesterov 
19411da177e4SLinus Torvalds void __init proc_caches_init(void)
19421da177e4SLinus Torvalds {
19431da177e4SLinus Torvalds 	sighand_cachep = kmem_cache_create("sighand_cache",
19441da177e4SLinus Torvalds 			sizeof(struct sighand_struct), 0,
19452dff4405SVegard Nossum 			SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_DESTROY_BY_RCU|
19465d097056SVladimir Davydov 			SLAB_NOTRACK|SLAB_ACCOUNT, sighand_ctor);
19471da177e4SLinus Torvalds 	signal_cachep = kmem_cache_create("signal_cache",
19481da177e4SLinus Torvalds 			sizeof(struct signal_struct), 0,
19495d097056SVladimir Davydov 			SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_NOTRACK|SLAB_ACCOUNT,
19505d097056SVladimir Davydov 			NULL);
19511da177e4SLinus Torvalds 	files_cachep = kmem_cache_create("files_cache",
19521da177e4SLinus Torvalds 			sizeof(struct files_struct), 0,
19535d097056SVladimir Davydov 			SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_NOTRACK|SLAB_ACCOUNT,
19545d097056SVladimir Davydov 			NULL);
19551da177e4SLinus Torvalds 	fs_cachep = kmem_cache_create("fs_cache",
19561da177e4SLinus Torvalds 			sizeof(struct fs_struct), 0,
19575d097056SVladimir Davydov 			SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_NOTRACK|SLAB_ACCOUNT,
19585d097056SVladimir Davydov 			NULL);
19596345d24dSLinus Torvalds 	/*
19606345d24dSLinus Torvalds 	 * FIXME! The "sizeof(struct mm_struct)" currently includes the
19616345d24dSLinus Torvalds 	 * whole struct cpumask for the OFFSTACK case. We could change
19626345d24dSLinus Torvalds 	 * this to *only* allocate as much of it as required by the
19636345d24dSLinus Torvalds 	 * maximum number of CPU's we can ever have.  The cpumask_allocation
19646345d24dSLinus Torvalds 	 * is at the end of the structure, exactly for that reason.
19656345d24dSLinus Torvalds 	 */
19661da177e4SLinus Torvalds 	mm_cachep = kmem_cache_create("mm_struct",
19675fd63b30SRavikiran G Thirumalai 			sizeof(struct mm_struct), ARCH_MIN_MMSTRUCT_ALIGN,
19685d097056SVladimir Davydov 			SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_NOTRACK|SLAB_ACCOUNT,
19695d097056SVladimir Davydov 			NULL);
19705d097056SVladimir Davydov 	vm_area_cachep = KMEM_CACHE(vm_area_struct, SLAB_PANIC|SLAB_ACCOUNT);
19718feae131SDavid Howells 	mmap_init();
197266577193SAl Viro 	nsproxy_cache_init();
19731da177e4SLinus Torvalds }
1974cf2e340fSJANAK DESAI 
1975cf2e340fSJANAK DESAI /*
19769bfb23fcSOleg Nesterov  * Check constraints on flags passed to the unshare system call.
1977cf2e340fSJANAK DESAI  */
19789bfb23fcSOleg Nesterov static int check_unshare_flags(unsigned long unshare_flags)
1979cf2e340fSJANAK DESAI {
19809bfb23fcSOleg Nesterov 	if (unshare_flags & ~(CLONE_THREAD|CLONE_FS|CLONE_NEWNS|CLONE_SIGHAND|
19819bfb23fcSOleg Nesterov 				CLONE_VM|CLONE_FILES|CLONE_SYSVSEM|
198250804fe3SEric W. Biederman 				CLONE_NEWUTS|CLONE_NEWIPC|CLONE_NEWNET|
1983a79a908fSAditya Kali 				CLONE_NEWUSER|CLONE_NEWPID|CLONE_NEWCGROUP))
1984cf2e340fSJANAK DESAI 		return -EINVAL;
19859bfb23fcSOleg Nesterov 	/*
198612c641abSEric W. Biederman 	 * Not implemented, but pretend it works if there is nothing
198712c641abSEric W. Biederman 	 * to unshare.  Note that unsharing the address space or the
198812c641abSEric W. Biederman 	 * signal handlers also need to unshare the signal queues (aka
198912c641abSEric W. Biederman 	 * CLONE_THREAD).
19909bfb23fcSOleg Nesterov 	 */
19919bfb23fcSOleg Nesterov 	if (unshare_flags & (CLONE_THREAD | CLONE_SIGHAND | CLONE_VM)) {
199212c641abSEric W. Biederman 		if (!thread_group_empty(current))
199312c641abSEric W. Biederman 			return -EINVAL;
199412c641abSEric W. Biederman 	}
199512c641abSEric W. Biederman 	if (unshare_flags & (CLONE_SIGHAND | CLONE_VM)) {
199612c641abSEric W. Biederman 		if (atomic_read(&current->sighand->count) > 1)
199712c641abSEric W. Biederman 			return -EINVAL;
199812c641abSEric W. Biederman 	}
199912c641abSEric W. Biederman 	if (unshare_flags & CLONE_VM) {
200012c641abSEric W. Biederman 		if (!current_is_single_threaded())
20019bfb23fcSOleg Nesterov 			return -EINVAL;
20029bfb23fcSOleg Nesterov 	}
2003cf2e340fSJANAK DESAI 
2004cf2e340fSJANAK DESAI 	return 0;
2005cf2e340fSJANAK DESAI }
2006cf2e340fSJANAK DESAI 
2007cf2e340fSJANAK DESAI /*
200899d1419dSJANAK DESAI  * Unshare the filesystem structure if it is being shared
2009cf2e340fSJANAK DESAI  */
2010cf2e340fSJANAK DESAI static int unshare_fs(unsigned long unshare_flags, struct fs_struct **new_fsp)
2011cf2e340fSJANAK DESAI {
2012cf2e340fSJANAK DESAI 	struct fs_struct *fs = current->fs;
2013cf2e340fSJANAK DESAI 
2014498052bbSAl Viro 	if (!(unshare_flags & CLONE_FS) || !fs)
2015498052bbSAl Viro 		return 0;
2016498052bbSAl Viro 
2017498052bbSAl Viro 	/* don't need lock here; in the worst case we'll do useless copy */
2018498052bbSAl Viro 	if (fs->users == 1)
2019498052bbSAl Viro 		return 0;
2020498052bbSAl Viro 
2021498052bbSAl Viro 	*new_fsp = copy_fs_struct(fs);
202299d1419dSJANAK DESAI 	if (!*new_fsp)
202399d1419dSJANAK DESAI 		return -ENOMEM;
2024cf2e340fSJANAK DESAI 
2025cf2e340fSJANAK DESAI 	return 0;
2026cf2e340fSJANAK DESAI }
2027cf2e340fSJANAK DESAI 
2028cf2e340fSJANAK DESAI /*
2029a016f338SJANAK DESAI  * Unshare file descriptor table if it is being shared
2030cf2e340fSJANAK DESAI  */
2031cf2e340fSJANAK DESAI static int unshare_fd(unsigned long unshare_flags, struct files_struct **new_fdp)
2032cf2e340fSJANAK DESAI {
2033cf2e340fSJANAK DESAI 	struct files_struct *fd = current->files;
2034a016f338SJANAK DESAI 	int error = 0;
2035cf2e340fSJANAK DESAI 
2036cf2e340fSJANAK DESAI 	if ((unshare_flags & CLONE_FILES) &&
2037a016f338SJANAK DESAI 	    (fd && atomic_read(&fd->count) > 1)) {
2038a016f338SJANAK DESAI 		*new_fdp = dup_fd(fd, &error);
2039a016f338SJANAK DESAI 		if (!*new_fdp)
2040a016f338SJANAK DESAI 			return error;
2041a016f338SJANAK DESAI 	}
2042cf2e340fSJANAK DESAI 
2043cf2e340fSJANAK DESAI 	return 0;
2044cf2e340fSJANAK DESAI }
2045cf2e340fSJANAK DESAI 
2046cf2e340fSJANAK DESAI /*
2047cf2e340fSJANAK DESAI  * unshare allows a process to 'unshare' part of the process
2048cf2e340fSJANAK DESAI  * context which was originally shared using clone.  copy_*
2049cf2e340fSJANAK DESAI  * functions used by do_fork() cannot be used here directly
2050cf2e340fSJANAK DESAI  * because they modify an inactive task_struct that is being
2051cf2e340fSJANAK DESAI  * constructed. Here we are modifying the current, active,
2052cf2e340fSJANAK DESAI  * task_struct.
2053cf2e340fSJANAK DESAI  */
20546559eed8SHeiko Carstens SYSCALL_DEFINE1(unshare, unsigned long, unshare_flags)
2055cf2e340fSJANAK DESAI {
2056cf2e340fSJANAK DESAI 	struct fs_struct *fs, *new_fs = NULL;
2057cf2e340fSJANAK DESAI 	struct files_struct *fd, *new_fd = NULL;
2058b2e0d987SEric W. Biederman 	struct cred *new_cred = NULL;
2059cf7b708cSPavel Emelyanov 	struct nsproxy *new_nsproxy = NULL;
20609edff4abSManfred Spraul 	int do_sysvsem = 0;
20619bfb23fcSOleg Nesterov 	int err;
2062cf2e340fSJANAK DESAI 
206350804fe3SEric W. Biederman 	/*
2064faf00da5SEric W. Biederman 	 * If unsharing a user namespace must also unshare the thread group
2065faf00da5SEric W. Biederman 	 * and unshare the filesystem root and working directories.
2066b2e0d987SEric W. Biederman 	 */
2067b2e0d987SEric W. Biederman 	if (unshare_flags & CLONE_NEWUSER)
2068e66eded8SEric W. Biederman 		unshare_flags |= CLONE_THREAD | CLONE_FS;
2069b2e0d987SEric W. Biederman 	/*
207050804fe3SEric W. Biederman 	 * If unsharing vm, must also unshare signal handlers.
207150804fe3SEric W. Biederman 	 */
207250804fe3SEric W. Biederman 	if (unshare_flags & CLONE_VM)
207350804fe3SEric W. Biederman 		unshare_flags |= CLONE_SIGHAND;
20746013f67fSManfred Spraul 	/*
207512c641abSEric W. Biederman 	 * If unsharing a signal handlers, must also unshare the signal queues.
207612c641abSEric W. Biederman 	 */
207712c641abSEric W. Biederman 	if (unshare_flags & CLONE_SIGHAND)
207812c641abSEric W. Biederman 		unshare_flags |= CLONE_THREAD;
207912c641abSEric W. Biederman 	/*
20809bfb23fcSOleg Nesterov 	 * If unsharing namespace, must also unshare filesystem information.
20819bfb23fcSOleg Nesterov 	 */
20829bfb23fcSOleg Nesterov 	if (unshare_flags & CLONE_NEWNS)
20839bfb23fcSOleg Nesterov 		unshare_flags |= CLONE_FS;
208450804fe3SEric W. Biederman 
208550804fe3SEric W. Biederman 	err = check_unshare_flags(unshare_flags);
208650804fe3SEric W. Biederman 	if (err)
208750804fe3SEric W. Biederman 		goto bad_unshare_out;
20889bfb23fcSOleg Nesterov 	/*
20896013f67fSManfred Spraul 	 * CLONE_NEWIPC must also detach from the undolist: after switching
20906013f67fSManfred Spraul 	 * to a new ipc namespace, the semaphore arrays from the old
20916013f67fSManfred Spraul 	 * namespace are unreachable.
20926013f67fSManfred Spraul 	 */
20936013f67fSManfred Spraul 	if (unshare_flags & (CLONE_NEWIPC|CLONE_SYSVSEM))
20949edff4abSManfred Spraul 		do_sysvsem = 1;
2095fb0a685cSDaniel Rebelo de Oliveira 	err = unshare_fs(unshare_flags, &new_fs);
2096fb0a685cSDaniel Rebelo de Oliveira 	if (err)
20979bfb23fcSOleg Nesterov 		goto bad_unshare_out;
2098fb0a685cSDaniel Rebelo de Oliveira 	err = unshare_fd(unshare_flags, &new_fd);
2099fb0a685cSDaniel Rebelo de Oliveira 	if (err)
21009bfb23fcSOleg Nesterov 		goto bad_unshare_cleanup_fs;
2101b2e0d987SEric W. Biederman 	err = unshare_userns(unshare_flags, &new_cred);
2102fb0a685cSDaniel Rebelo de Oliveira 	if (err)
21039edff4abSManfred Spraul 		goto bad_unshare_cleanup_fd;
2104b2e0d987SEric W. Biederman 	err = unshare_nsproxy_namespaces(unshare_flags, &new_nsproxy,
2105b2e0d987SEric W. Biederman 					 new_cred, new_fs);
2106b2e0d987SEric W. Biederman 	if (err)
2107b2e0d987SEric W. Biederman 		goto bad_unshare_cleanup_cred;
2108cf2e340fSJANAK DESAI 
2109b2e0d987SEric W. Biederman 	if (new_fs || new_fd || do_sysvsem || new_cred || new_nsproxy) {
21109edff4abSManfred Spraul 		if (do_sysvsem) {
21119edff4abSManfred Spraul 			/*
21129edff4abSManfred Spraul 			 * CLONE_SYSVSEM is equivalent to sys_exit().
21139edff4abSManfred Spraul 			 */
21149edff4abSManfred Spraul 			exit_sem(current);
21159edff4abSManfred Spraul 		}
2116ab602f79SJack Miller 		if (unshare_flags & CLONE_NEWIPC) {
2117ab602f79SJack Miller 			/* Orphan segments in old ns (see sem above). */
2118ab602f79SJack Miller 			exit_shm(current);
2119ab602f79SJack Miller 			shm_init_task(current);
2120ab602f79SJack Miller 		}
2121ab516013SSerge E. Hallyn 
21226f977e6bSAlan Cox 		if (new_nsproxy)
2123cf7b708cSPavel Emelyanov 			switch_task_namespaces(current, new_nsproxy);
2124cf2e340fSJANAK DESAI 
2125cf7b708cSPavel Emelyanov 		task_lock(current);
2126cf7b708cSPavel Emelyanov 
2127cf2e340fSJANAK DESAI 		if (new_fs) {
2128cf2e340fSJANAK DESAI 			fs = current->fs;
21292a4419b5SNick Piggin 			spin_lock(&fs->lock);
2130cf2e340fSJANAK DESAI 			current->fs = new_fs;
2131498052bbSAl Viro 			if (--fs->users)
2132498052bbSAl Viro 				new_fs = NULL;
2133498052bbSAl Viro 			else
2134cf2e340fSJANAK DESAI 				new_fs = fs;
21352a4419b5SNick Piggin 			spin_unlock(&fs->lock);
2136cf2e340fSJANAK DESAI 		}
2137cf2e340fSJANAK DESAI 
2138cf2e340fSJANAK DESAI 		if (new_fd) {
2139cf2e340fSJANAK DESAI 			fd = current->files;
2140cf2e340fSJANAK DESAI 			current->files = new_fd;
2141cf2e340fSJANAK DESAI 			new_fd = fd;
2142cf2e340fSJANAK DESAI 		}
2143cf2e340fSJANAK DESAI 
2144cf2e340fSJANAK DESAI 		task_unlock(current);
2145b2e0d987SEric W. Biederman 
2146b2e0d987SEric W. Biederman 		if (new_cred) {
2147b2e0d987SEric W. Biederman 			/* Install the new user namespace */
2148b2e0d987SEric W. Biederman 			commit_creds(new_cred);
2149b2e0d987SEric W. Biederman 			new_cred = NULL;
2150b2e0d987SEric W. Biederman 		}
2151cf2e340fSJANAK DESAI 	}
2152cf2e340fSJANAK DESAI 
2153b2e0d987SEric W. Biederman bad_unshare_cleanup_cred:
2154b2e0d987SEric W. Biederman 	if (new_cred)
2155b2e0d987SEric W. Biederman 		put_cred(new_cred);
2156cf2e340fSJANAK DESAI bad_unshare_cleanup_fd:
2157cf2e340fSJANAK DESAI 	if (new_fd)
2158cf2e340fSJANAK DESAI 		put_files_struct(new_fd);
2159cf2e340fSJANAK DESAI 
2160cf2e340fSJANAK DESAI bad_unshare_cleanup_fs:
2161cf2e340fSJANAK DESAI 	if (new_fs)
2162498052bbSAl Viro 		free_fs_struct(new_fs);
2163cf2e340fSJANAK DESAI 
2164cf2e340fSJANAK DESAI bad_unshare_out:
2165cf2e340fSJANAK DESAI 	return err;
2166cf2e340fSJANAK DESAI }
21673b125388SAl Viro 
21683b125388SAl Viro /*
21693b125388SAl Viro  *	Helper to unshare the files of the current task.
21703b125388SAl Viro  *	We don't want to expose copy_files internals to
21713b125388SAl Viro  *	the exec layer of the kernel.
21723b125388SAl Viro  */
21733b125388SAl Viro 
21743b125388SAl Viro int unshare_files(struct files_struct **displaced)
21753b125388SAl Viro {
21763b125388SAl Viro 	struct task_struct *task = current;
217750704516SAl Viro 	struct files_struct *copy = NULL;
21783b125388SAl Viro 	int error;
21793b125388SAl Viro 
21803b125388SAl Viro 	error = unshare_fd(CLONE_FILES, &copy);
21813b125388SAl Viro 	if (error || !copy) {
21823b125388SAl Viro 		*displaced = NULL;
21833b125388SAl Viro 		return error;
21843b125388SAl Viro 	}
21853b125388SAl Viro 	*displaced = task->files;
21863b125388SAl Viro 	task_lock(task);
21873b125388SAl Viro 	task->files = copy;
21883b125388SAl Viro 	task_unlock(task);
21893b125388SAl Viro 	return 0;
21903b125388SAl Viro }
219116db3d3fSHeinrich Schuchardt 
219216db3d3fSHeinrich Schuchardt int sysctl_max_threads(struct ctl_table *table, int write,
219316db3d3fSHeinrich Schuchardt 		       void __user *buffer, size_t *lenp, loff_t *ppos)
219416db3d3fSHeinrich Schuchardt {
219516db3d3fSHeinrich Schuchardt 	struct ctl_table t;
219616db3d3fSHeinrich Schuchardt 	int ret;
219716db3d3fSHeinrich Schuchardt 	int threads = max_threads;
219816db3d3fSHeinrich Schuchardt 	int min = MIN_THREADS;
219916db3d3fSHeinrich Schuchardt 	int max = MAX_THREADS;
220016db3d3fSHeinrich Schuchardt 
220116db3d3fSHeinrich Schuchardt 	t = *table;
220216db3d3fSHeinrich Schuchardt 	t.data = &threads;
220316db3d3fSHeinrich Schuchardt 	t.extra1 = &min;
220416db3d3fSHeinrich Schuchardt 	t.extra2 = &max;
220516db3d3fSHeinrich Schuchardt 
220616db3d3fSHeinrich Schuchardt 	ret = proc_dointvec_minmax(&t, write, buffer, lenp, ppos);
220716db3d3fSHeinrich Schuchardt 	if (ret || !write)
220816db3d3fSHeinrich Schuchardt 		return ret;
220916db3d3fSHeinrich Schuchardt 
221016db3d3fSHeinrich Schuchardt 	set_max_threads(threads);
221116db3d3fSHeinrich Schuchardt 
221216db3d3fSHeinrich Schuchardt 	return 0;
221316db3d3fSHeinrich Schuchardt }
2214