xref: /openbmc/linux/kernel/fork.c (revision 7c051267931a9be9c6620cc17b362bc6ee6dedc8)
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 
151f19b9f74SAkinobu Mita void __weak arch_release_thread_info(struct thread_info *ti)
152f19b9f74SAkinobu Mita {
153f19b9f74SAkinobu Mita }
154f19b9f74SAkinobu Mita 
155f5e10287SThomas Gleixner #ifndef CONFIG_ARCH_THREAD_INFO_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  */
1610d15d74aSThomas Gleixner # if THREAD_SIZE >= PAGE_SIZE
162b6a84016SEric Dumazet static struct thread_info *alloc_thread_info_node(struct task_struct *tsk,
163b6a84016SEric Dumazet 						  int node)
164b69c49b7SFUJITA Tomonori {
16552383431SVladimir Davydov 	struct page *page = alloc_kmem_pages_node(node, THREADINFO_GFP,
1662889f608SThomas Gleixner 						  THREAD_SIZE_ORDER);
167b6a84016SEric Dumazet 
16812580e4bSVladimir Davydov 	if (page)
16912580e4bSVladimir Davydov 		memcg_kmem_update_page_stat(page, MEMCG_KERNEL_STACK,
17012580e4bSVladimir Davydov 					    1 << THREAD_SIZE_ORDER);
17112580e4bSVladimir Davydov 
172b6a84016SEric Dumazet 	return page ? page_address(page) : NULL;
173b69c49b7SFUJITA Tomonori }
174b69c49b7SFUJITA Tomonori 
175b69c49b7SFUJITA Tomonori static inline void free_thread_info(struct thread_info *ti)
176b69c49b7SFUJITA Tomonori {
17712580e4bSVladimir Davydov 	struct page *page = virt_to_page(ti);
17812580e4bSVladimir Davydov 
17912580e4bSVladimir Davydov 	memcg_kmem_update_page_stat(page, MEMCG_KERNEL_STACK,
18012580e4bSVladimir Davydov 				    -(1 << THREAD_SIZE_ORDER));
18112580e4bSVladimir Davydov 	__free_kmem_pages(page, THREAD_SIZE_ORDER);
182b69c49b7SFUJITA Tomonori }
1830d15d74aSThomas Gleixner # else
1840d15d74aSThomas Gleixner static struct kmem_cache *thread_info_cache;
1850d15d74aSThomas Gleixner 
1860d15d74aSThomas Gleixner static struct thread_info *alloc_thread_info_node(struct task_struct *tsk,
1870d15d74aSThomas Gleixner 						  int node)
1880d15d74aSThomas Gleixner {
1890d15d74aSThomas Gleixner 	return kmem_cache_alloc_node(thread_info_cache, THREADINFO_GFP, node);
1900d15d74aSThomas Gleixner }
1910d15d74aSThomas Gleixner 
1920d15d74aSThomas Gleixner static void free_thread_info(struct thread_info *ti)
1930d15d74aSThomas Gleixner {
1940d15d74aSThomas Gleixner 	kmem_cache_free(thread_info_cache, ti);
1950d15d74aSThomas Gleixner }
1960d15d74aSThomas Gleixner 
1970d15d74aSThomas Gleixner void thread_info_cache_init(void)
1980d15d74aSThomas Gleixner {
1990d15d74aSThomas Gleixner 	thread_info_cache = kmem_cache_create("thread_info", THREAD_SIZE,
2000d15d74aSThomas Gleixner 					      THREAD_SIZE, 0, NULL);
2010d15d74aSThomas Gleixner 	BUG_ON(thread_info_cache == NULL);
2020d15d74aSThomas Gleixner }
2030d15d74aSThomas Gleixner # endif
204b69c49b7SFUJITA Tomonori #endif
205b69c49b7SFUJITA Tomonori 
2061da177e4SLinus Torvalds /* SLAB cache for signal_struct structures (tsk->signal) */
207e18b890bSChristoph Lameter static struct kmem_cache *signal_cachep;
2081da177e4SLinus Torvalds 
2091da177e4SLinus Torvalds /* SLAB cache for sighand_struct structures (tsk->sighand) */
210e18b890bSChristoph Lameter struct kmem_cache *sighand_cachep;
2111da177e4SLinus Torvalds 
2121da177e4SLinus Torvalds /* SLAB cache for files_struct structures (tsk->files) */
213e18b890bSChristoph Lameter struct kmem_cache *files_cachep;
2141da177e4SLinus Torvalds 
2151da177e4SLinus Torvalds /* SLAB cache for fs_struct structures (tsk->fs) */
216e18b890bSChristoph Lameter struct kmem_cache *fs_cachep;
2171da177e4SLinus Torvalds 
2181da177e4SLinus Torvalds /* SLAB cache for vm_area_struct structures */
219e18b890bSChristoph Lameter struct kmem_cache *vm_area_cachep;
2201da177e4SLinus Torvalds 
2211da177e4SLinus Torvalds /* SLAB cache for mm_struct structures (tsk->mm) */
222e18b890bSChristoph Lameter static struct kmem_cache *mm_cachep;
2231da177e4SLinus Torvalds 
224c6a7f572SKOSAKI Motohiro static void account_kernel_stack(struct thread_info *ti, int account)
225c6a7f572SKOSAKI Motohiro {
226c6a7f572SKOSAKI Motohiro 	struct zone *zone = page_zone(virt_to_page(ti));
227c6a7f572SKOSAKI Motohiro 
228c6a7f572SKOSAKI Motohiro 	mod_zone_page_state(zone, NR_KERNEL_STACK, account);
229c6a7f572SKOSAKI Motohiro }
230c6a7f572SKOSAKI Motohiro 
2311da177e4SLinus Torvalds void free_task(struct task_struct *tsk)
2321da177e4SLinus Torvalds {
233c6a7f572SKOSAKI Motohiro 	account_kernel_stack(tsk->stack, -1);
234f19b9f74SAkinobu Mita 	arch_release_thread_info(tsk->stack);
235f7e4217bSRoman Zippel 	free_thread_info(tsk->stack);
23623f78d4aSIngo Molnar 	rt_mutex_debug_task_free(tsk);
237fb52607aSFrederic Weisbecker 	ftrace_graph_exit_task(tsk);
238e2cfabdfSWill Drewry 	put_seccomp_filter(tsk);
239f19b9f74SAkinobu Mita 	arch_release_task_struct(tsk);
2401da177e4SLinus Torvalds 	free_task_struct(tsk);
2411da177e4SLinus Torvalds }
2421da177e4SLinus Torvalds EXPORT_SYMBOL(free_task);
2431da177e4SLinus Torvalds 
244ea6d290cSOleg Nesterov static inline void free_signal_struct(struct signal_struct *sig)
245ea6d290cSOleg Nesterov {
24697101eb4SOleg Nesterov 	taskstats_tgid_free(sig);
2471c5354deSMike Galbraith 	sched_autogroup_exit(sig);
248ea6d290cSOleg Nesterov 	kmem_cache_free(signal_cachep, sig);
249ea6d290cSOleg Nesterov }
250ea6d290cSOleg Nesterov 
251ea6d290cSOleg Nesterov static inline void put_signal_struct(struct signal_struct *sig)
252ea6d290cSOleg Nesterov {
2531c5354deSMike Galbraith 	if (atomic_dec_and_test(&sig->sigcnt))
254ea6d290cSOleg Nesterov 		free_signal_struct(sig);
255ea6d290cSOleg Nesterov }
256ea6d290cSOleg Nesterov 
257158d9ebdSAndrew Morton void __put_task_struct(struct task_struct *tsk)
2581da177e4SLinus Torvalds {
259270f722dSEugene Teo 	WARN_ON(!tsk->exit_state);
2601da177e4SLinus Torvalds 	WARN_ON(atomic_read(&tsk->usage));
2611da177e4SLinus Torvalds 	WARN_ON(tsk == current);
2621da177e4SLinus Torvalds 
2632e91fa7fSTejun Heo 	cgroup_free(tsk);
264156654f4SMike Galbraith 	task_numa_free(tsk);
2651a2a4d06SKees Cook 	security_task_free(tsk);
266e0e81739SDavid Howells 	exit_creds(tsk);
26735df17c5SShailabh Nagar 	delayacct_tsk_free(tsk);
268ea6d290cSOleg Nesterov 	put_signal_struct(tsk->signal);
2691da177e4SLinus Torvalds 
2701da177e4SLinus Torvalds 	if (!profile_handoff_task(tsk))
2711da177e4SLinus Torvalds 		free_task(tsk);
2721da177e4SLinus Torvalds }
27377c100c8SRik van Riel EXPORT_SYMBOL_GPL(__put_task_struct);
2741da177e4SLinus Torvalds 
2756c0a9fa6SThomas Gleixner void __init __weak arch_task_cache_init(void) { }
27661c4628bSSuresh Siddha 
277ff691f6eSHeinrich Schuchardt /*
278ff691f6eSHeinrich Schuchardt  * set_max_threads
279ff691f6eSHeinrich Schuchardt  */
28016db3d3fSHeinrich Schuchardt static void set_max_threads(unsigned int max_threads_suggested)
281ff691f6eSHeinrich Schuchardt {
282ac1b398dSHeinrich Schuchardt 	u64 threads;
283ff691f6eSHeinrich Schuchardt 
284ff691f6eSHeinrich Schuchardt 	/*
285ac1b398dSHeinrich Schuchardt 	 * The number of threads shall be limited such that the thread
286ac1b398dSHeinrich Schuchardt 	 * structures may only consume a small part of the available memory.
287ff691f6eSHeinrich Schuchardt 	 */
288ac1b398dSHeinrich Schuchardt 	if (fls64(totalram_pages) + fls64(PAGE_SIZE) > 64)
289ac1b398dSHeinrich Schuchardt 		threads = MAX_THREADS;
290ac1b398dSHeinrich Schuchardt 	else
291ac1b398dSHeinrich Schuchardt 		threads = div64_u64((u64) totalram_pages * (u64) PAGE_SIZE,
292ac1b398dSHeinrich Schuchardt 				    (u64) THREAD_SIZE * 8UL);
293ac1b398dSHeinrich Schuchardt 
29416db3d3fSHeinrich Schuchardt 	if (threads > max_threads_suggested)
29516db3d3fSHeinrich Schuchardt 		threads = max_threads_suggested;
29616db3d3fSHeinrich Schuchardt 
297ac1b398dSHeinrich Schuchardt 	max_threads = clamp_t(u64, threads, MIN_THREADS, MAX_THREADS);
298ff691f6eSHeinrich Schuchardt }
299ff691f6eSHeinrich Schuchardt 
3005aaeb5c0SIngo Molnar #ifdef CONFIG_ARCH_WANTS_DYNAMIC_TASK_STRUCT
3015aaeb5c0SIngo Molnar /* Initialized by the architecture: */
3025aaeb5c0SIngo Molnar int arch_task_struct_size __read_mostly;
3035aaeb5c0SIngo Molnar #endif
3040c8c0f03SDave Hansen 
305ff691f6eSHeinrich Schuchardt void __init fork_init(void)
3061da177e4SLinus Torvalds {
307f5e10287SThomas Gleixner #ifndef CONFIG_ARCH_TASK_STRUCT_ALLOCATOR
3081da177e4SLinus Torvalds #ifndef ARCH_MIN_TASKALIGN
3091da177e4SLinus Torvalds #define ARCH_MIN_TASKALIGN	L1_CACHE_BYTES
3101da177e4SLinus Torvalds #endif
3111da177e4SLinus Torvalds 	/* create a slab on which task_structs can be allocated */
3125d097056SVladimir Davydov 	task_struct_cachep = kmem_cache_create("task_struct",
3135d097056SVladimir Davydov 			arch_task_struct_size, ARCH_MIN_TASKALIGN,
3145d097056SVladimir Davydov 			SLAB_PANIC|SLAB_NOTRACK|SLAB_ACCOUNT, NULL);
3151da177e4SLinus Torvalds #endif
3161da177e4SLinus Torvalds 
31761c4628bSSuresh Siddha 	/* do the arch specific task caches init */
31861c4628bSSuresh Siddha 	arch_task_cache_init();
31961c4628bSSuresh Siddha 
32016db3d3fSHeinrich Schuchardt 	set_max_threads(MAX_THREADS);
3211da177e4SLinus Torvalds 
3221da177e4SLinus Torvalds 	init_task.signal->rlim[RLIMIT_NPROC].rlim_cur = max_threads/2;
3231da177e4SLinus Torvalds 	init_task.signal->rlim[RLIMIT_NPROC].rlim_max = max_threads/2;
3241da177e4SLinus Torvalds 	init_task.signal->rlim[RLIMIT_SIGPENDING] =
3251da177e4SLinus Torvalds 		init_task.signal->rlim[RLIMIT_NPROC];
3261da177e4SLinus Torvalds }
3271da177e4SLinus Torvalds 
32852f5684cSGideon Israel Dsouza int __weak arch_dup_task_struct(struct task_struct *dst,
32961c4628bSSuresh Siddha 					       struct task_struct *src)
33061c4628bSSuresh Siddha {
33161c4628bSSuresh Siddha 	*dst = *src;
33261c4628bSSuresh Siddha 	return 0;
33361c4628bSSuresh Siddha }
33461c4628bSSuresh Siddha 
335d4311ff1SAaron Tomlin void set_task_stack_end_magic(struct task_struct *tsk)
336d4311ff1SAaron Tomlin {
337d4311ff1SAaron Tomlin 	unsigned long *stackend;
338d4311ff1SAaron Tomlin 
339d4311ff1SAaron Tomlin 	stackend = end_of_stack(tsk);
340d4311ff1SAaron Tomlin 	*stackend = STACK_END_MAGIC;	/* for overflow detection */
341d4311ff1SAaron Tomlin }
342d4311ff1SAaron Tomlin 
343725fc629SAndi Kleen static struct task_struct *dup_task_struct(struct task_struct *orig, int node)
3441da177e4SLinus Torvalds {
3451da177e4SLinus Torvalds 	struct task_struct *tsk;
3461da177e4SLinus Torvalds 	struct thread_info *ti;
3473e26c149SPeter Zijlstra 	int err;
3481da177e4SLinus Torvalds 
349725fc629SAndi Kleen 	if (node == NUMA_NO_NODE)
350725fc629SAndi Kleen 		node = tsk_fork_get_node(orig);
351504f52b5SEric Dumazet 	tsk = alloc_task_struct_node(node);
3521da177e4SLinus Torvalds 	if (!tsk)
3531da177e4SLinus Torvalds 		return NULL;
3541da177e4SLinus Torvalds 
355b6a84016SEric Dumazet 	ti = alloc_thread_info_node(tsk, node);
356f19b9f74SAkinobu Mita 	if (!ti)
357f19b9f74SAkinobu Mita 		goto free_tsk;
3581da177e4SLinus Torvalds 
35961c4628bSSuresh Siddha 	err = arch_dup_task_struct(tsk, orig);
36061c4628bSSuresh Siddha 	if (err)
361f19b9f74SAkinobu Mita 		goto free_ti;
36261c4628bSSuresh Siddha 
36387bec58aSAndrew Morton 	tsk->stack = ti;
364dbd95212SKees Cook #ifdef CONFIG_SECCOMP
365dbd95212SKees Cook 	/*
366dbd95212SKees Cook 	 * We must handle setting up seccomp filters once we're under
367dbd95212SKees Cook 	 * the sighand lock in case orig has changed between now and
368dbd95212SKees Cook 	 * then. Until then, filter must be NULL to avoid messing up
369dbd95212SKees Cook 	 * the usage counts on the error path calling free_task.
370dbd95212SKees Cook 	 */
371dbd95212SKees Cook 	tsk->seccomp.filter = NULL;
372dbd95212SKees Cook #endif
37387bec58aSAndrew Morton 
37487bec58aSAndrew Morton 	setup_thread_stack(tsk, orig);
3758e7cac79SAvi Kivity 	clear_user_return_notifier(tsk);
376f26f9affSMike Galbraith 	clear_tsk_need_resched(tsk);
377d4311ff1SAaron Tomlin 	set_task_stack_end_magic(tsk);
3781da177e4SLinus Torvalds 
3790a425405SArjan van de Ven #ifdef CONFIG_CC_STACKPROTECTOR
3800a425405SArjan van de Ven 	tsk->stack_canary = get_random_int();
3810a425405SArjan van de Ven #endif
3820a425405SArjan van de Ven 
383fb0a685cSDaniel Rebelo de Oliveira 	/*
384fb0a685cSDaniel Rebelo de Oliveira 	 * One for us, one for whoever does the "release_task()" (usually
385fb0a685cSDaniel Rebelo de Oliveira 	 * parent)
386fb0a685cSDaniel Rebelo de Oliveira 	 */
3871da177e4SLinus Torvalds 	atomic_set(&tsk->usage, 2);
3886c5c9341SAlexey Dobriyan #ifdef CONFIG_BLK_DEV_IO_TRACE
3892056a782SJens Axboe 	tsk->btrace_seq = 0;
3906c5c9341SAlexey Dobriyan #endif
391a0aa7f68SJens Axboe 	tsk->splice_pipe = NULL;
3925640f768SEric Dumazet 	tsk->task_frag.page = NULL;
393093e5840SSebastian Andrzej Siewior 	tsk->wake_q.next = NULL;
394c6a7f572SKOSAKI Motohiro 
395c6a7f572SKOSAKI Motohiro 	account_kernel_stack(ti, 1);
396c6a7f572SKOSAKI Motohiro 
3975c9a8750SDmitry Vyukov 	kcov_task_init(tsk);
3985c9a8750SDmitry Vyukov 
3991da177e4SLinus Torvalds 	return tsk;
40061c4628bSSuresh Siddha 
401f19b9f74SAkinobu Mita free_ti:
40261c4628bSSuresh Siddha 	free_thread_info(ti);
403f19b9f74SAkinobu Mita free_tsk:
40461c4628bSSuresh Siddha 	free_task_struct(tsk);
40561c4628bSSuresh Siddha 	return NULL;
4061da177e4SLinus Torvalds }
4071da177e4SLinus Torvalds 
4081da177e4SLinus Torvalds #ifdef CONFIG_MMU
409a39bc516SAlexey Dobriyan static int dup_mmap(struct mm_struct *mm, struct mm_struct *oldmm)
4101da177e4SLinus Torvalds {
411297c5eeeSLinus Torvalds 	struct vm_area_struct *mpnt, *tmp, *prev, **pprev;
4121da177e4SLinus Torvalds 	struct rb_node **rb_link, *rb_parent;
4131da177e4SLinus Torvalds 	int retval;
4141da177e4SLinus Torvalds 	unsigned long charge;
4151da177e4SLinus Torvalds 
41632cdba1eSOleg Nesterov 	uprobe_start_dup_mmap();
417*7c051267SMichal Hocko 	if (down_write_killable(&oldmm->mmap_sem)) {
418*7c051267SMichal Hocko 		retval = -EINTR;
419*7c051267SMichal Hocko 		goto fail_uprobe_end;
420*7c051267SMichal Hocko 	}
421ec8c0446SRalf Baechle 	flush_cache_dup_mm(oldmm);
422f8ac4ec9SOleg Nesterov 	uprobe_dup_mmap(oldmm, mm);
423ad339451SIngo Molnar 	/*
424ad339451SIngo Molnar 	 * Not linked in yet - no deadlock potential:
425ad339451SIngo Molnar 	 */
426ad339451SIngo Molnar 	down_write_nested(&mm->mmap_sem, SINGLE_DEPTH_NESTING);
4277ee78232SHugh Dickins 
42890f31d0eSKonstantin Khlebnikov 	/* No ordering required: file already has been exposed. */
42990f31d0eSKonstantin Khlebnikov 	RCU_INIT_POINTER(mm->exe_file, get_mm_exe_file(oldmm));
43090f31d0eSKonstantin Khlebnikov 
4314f7d4614SVladimir Davydov 	mm->total_vm = oldmm->total_vm;
43284638335SKonstantin Khlebnikov 	mm->data_vm = oldmm->data_vm;
4334f7d4614SVladimir Davydov 	mm->exec_vm = oldmm->exec_vm;
4344f7d4614SVladimir Davydov 	mm->stack_vm = oldmm->stack_vm;
4354f7d4614SVladimir Davydov 
4361da177e4SLinus Torvalds 	rb_link = &mm->mm_rb.rb_node;
4371da177e4SLinus Torvalds 	rb_parent = NULL;
4381da177e4SLinus Torvalds 	pprev = &mm->mmap;
439f8af4da3SHugh Dickins 	retval = ksm_fork(mm, oldmm);
440f8af4da3SHugh Dickins 	if (retval)
441f8af4da3SHugh Dickins 		goto out;
442ba76149fSAndrea Arcangeli 	retval = khugepaged_fork(mm, oldmm);
443ba76149fSAndrea Arcangeli 	if (retval)
444ba76149fSAndrea Arcangeli 		goto out;
4451da177e4SLinus Torvalds 
446297c5eeeSLinus Torvalds 	prev = NULL;
447fd3e42fcSHugh Dickins 	for (mpnt = oldmm->mmap; mpnt; mpnt = mpnt->vm_next) {
4481da177e4SLinus Torvalds 		struct file *file;
4491da177e4SLinus Torvalds 
4501da177e4SLinus Torvalds 		if (mpnt->vm_flags & VM_DONTCOPY) {
45184638335SKonstantin Khlebnikov 			vm_stat_account(mm, mpnt->vm_flags, -vma_pages(mpnt));
4521da177e4SLinus Torvalds 			continue;
4531da177e4SLinus Torvalds 		}
4541da177e4SLinus Torvalds 		charge = 0;
4551da177e4SLinus Torvalds 		if (mpnt->vm_flags & VM_ACCOUNT) {
456b2412b7fSHuang Shijie 			unsigned long len = vma_pages(mpnt);
457b2412b7fSHuang Shijie 
458191c5424SAl Viro 			if (security_vm_enough_memory_mm(oldmm, len)) /* sic */
4591da177e4SLinus Torvalds 				goto fail_nomem;
4601da177e4SLinus Torvalds 			charge = len;
4611da177e4SLinus Torvalds 		}
462e94b1766SChristoph Lameter 		tmp = kmem_cache_alloc(vm_area_cachep, GFP_KERNEL);
4631da177e4SLinus Torvalds 		if (!tmp)
4641da177e4SLinus Torvalds 			goto fail_nomem;
4651da177e4SLinus Torvalds 		*tmp = *mpnt;
4665beb4930SRik van Riel 		INIT_LIST_HEAD(&tmp->anon_vma_chain);
467ef0855d3SOleg Nesterov 		retval = vma_dup_policy(mpnt, tmp);
468ef0855d3SOleg Nesterov 		if (retval)
4691da177e4SLinus Torvalds 			goto fail_nomem_policy;
470a247c3a9SAndrea Arcangeli 		tmp->vm_mm = mm;
4715beb4930SRik van Riel 		if (anon_vma_fork(tmp, mpnt))
4725beb4930SRik van Riel 			goto fail_nomem_anon_vma_fork;
473de60f5f1SEric B Munson 		tmp->vm_flags &=
474de60f5f1SEric B Munson 			~(VM_LOCKED|VM_LOCKONFAULT|VM_UFFD_MISSING|VM_UFFD_WP);
475297c5eeeSLinus Torvalds 		tmp->vm_next = tmp->vm_prev = NULL;
476745f234bSAndrea Arcangeli 		tmp->vm_userfaultfd_ctx = NULL_VM_UFFD_CTX;
4771da177e4SLinus Torvalds 		file = tmp->vm_file;
4781da177e4SLinus Torvalds 		if (file) {
479496ad9aaSAl Viro 			struct inode *inode = file_inode(file);
480b88ed205SHugh Dickins 			struct address_space *mapping = file->f_mapping;
481b88ed205SHugh Dickins 
4821da177e4SLinus Torvalds 			get_file(file);
4831da177e4SLinus Torvalds 			if (tmp->vm_flags & VM_DENYWRITE)
4841da177e4SLinus Torvalds 				atomic_dec(&inode->i_writecount);
48583cde9e8SDavidlohr Bueso 			i_mmap_lock_write(mapping);
486b88ed205SHugh Dickins 			if (tmp->vm_flags & VM_SHARED)
4874bb5f5d9SDavid Herrmann 				atomic_inc(&mapping->i_mmap_writable);
488b88ed205SHugh Dickins 			flush_dcache_mmap_lock(mapping);
489b88ed205SHugh Dickins 			/* insert tmp into the share list, just after mpnt */
4909826a516SMichel Lespinasse 			vma_interval_tree_insert_after(tmp, mpnt,
4919826a516SMichel Lespinasse 					&mapping->i_mmap);
492b88ed205SHugh Dickins 			flush_dcache_mmap_unlock(mapping);
49383cde9e8SDavidlohr Bueso 			i_mmap_unlock_write(mapping);
4941da177e4SLinus Torvalds 		}
4951da177e4SLinus Torvalds 
4961da177e4SLinus Torvalds 		/*
497a1e78772SMel Gorman 		 * Clear hugetlb-related page reserves for children. This only
498a1e78772SMel Gorman 		 * affects MAP_PRIVATE mappings. Faults generated by the child
499a1e78772SMel Gorman 		 * are not guaranteed to succeed, even if read-only
500a1e78772SMel Gorman 		 */
501a1e78772SMel Gorman 		if (is_vm_hugetlb_page(tmp))
502a1e78772SMel Gorman 			reset_vma_resv_huge_pages(tmp);
503a1e78772SMel Gorman 
504a1e78772SMel Gorman 		/*
5057ee78232SHugh Dickins 		 * Link in the new vma and copy the page table entries.
5061da177e4SLinus Torvalds 		 */
5071da177e4SLinus Torvalds 		*pprev = tmp;
5081da177e4SLinus Torvalds 		pprev = &tmp->vm_next;
509297c5eeeSLinus Torvalds 		tmp->vm_prev = prev;
510297c5eeeSLinus Torvalds 		prev = tmp;
5111da177e4SLinus Torvalds 
5121da177e4SLinus Torvalds 		__vma_link_rb(mm, tmp, rb_link, rb_parent);
5131da177e4SLinus Torvalds 		rb_link = &tmp->vm_rb.rb_right;
5141da177e4SLinus Torvalds 		rb_parent = &tmp->vm_rb;
5151da177e4SLinus Torvalds 
5161da177e4SLinus Torvalds 		mm->map_count++;
5170b0db14cSHugh Dickins 		retval = copy_page_range(mm, oldmm, mpnt);
5181da177e4SLinus Torvalds 
5191da177e4SLinus Torvalds 		if (tmp->vm_ops && tmp->vm_ops->open)
5201da177e4SLinus Torvalds 			tmp->vm_ops->open(tmp);
5211da177e4SLinus Torvalds 
5221da177e4SLinus Torvalds 		if (retval)
5231da177e4SLinus Torvalds 			goto out;
5241da177e4SLinus Torvalds 	}
525d6dd61c8SJeremy Fitzhardinge 	/* a new mm has just been created */
526d6dd61c8SJeremy Fitzhardinge 	arch_dup_mmap(oldmm, mm);
5271da177e4SLinus Torvalds 	retval = 0;
5281da177e4SLinus Torvalds out:
5297ee78232SHugh Dickins 	up_write(&mm->mmap_sem);
530fd3e42fcSHugh Dickins 	flush_tlb_mm(oldmm);
5311da177e4SLinus Torvalds 	up_write(&oldmm->mmap_sem);
532*7c051267SMichal Hocko fail_uprobe_end:
53332cdba1eSOleg Nesterov 	uprobe_end_dup_mmap();
5341da177e4SLinus Torvalds 	return retval;
5355beb4930SRik van Riel fail_nomem_anon_vma_fork:
536ef0855d3SOleg Nesterov 	mpol_put(vma_policy(tmp));
5371da177e4SLinus Torvalds fail_nomem_policy:
5381da177e4SLinus Torvalds 	kmem_cache_free(vm_area_cachep, tmp);
5391da177e4SLinus Torvalds fail_nomem:
5401da177e4SLinus Torvalds 	retval = -ENOMEM;
5411da177e4SLinus Torvalds 	vm_unacct_memory(charge);
5421da177e4SLinus Torvalds 	goto out;
5431da177e4SLinus Torvalds }
5441da177e4SLinus Torvalds 
5451da177e4SLinus Torvalds static inline int mm_alloc_pgd(struct mm_struct *mm)
5461da177e4SLinus Torvalds {
5471da177e4SLinus Torvalds 	mm->pgd = pgd_alloc(mm);
5481da177e4SLinus Torvalds 	if (unlikely(!mm->pgd))
5491da177e4SLinus Torvalds 		return -ENOMEM;
5501da177e4SLinus Torvalds 	return 0;
5511da177e4SLinus Torvalds }
5521da177e4SLinus Torvalds 
5531da177e4SLinus Torvalds static inline void mm_free_pgd(struct mm_struct *mm)
5541da177e4SLinus Torvalds {
5555e541973SBenjamin Herrenschmidt 	pgd_free(mm, mm->pgd);
5561da177e4SLinus Torvalds }
5571da177e4SLinus Torvalds #else
55890f31d0eSKonstantin Khlebnikov static int dup_mmap(struct mm_struct *mm, struct mm_struct *oldmm)
55990f31d0eSKonstantin Khlebnikov {
56090f31d0eSKonstantin Khlebnikov 	down_write(&oldmm->mmap_sem);
56190f31d0eSKonstantin Khlebnikov 	RCU_INIT_POINTER(mm->exe_file, get_mm_exe_file(oldmm));
56290f31d0eSKonstantin Khlebnikov 	up_write(&oldmm->mmap_sem);
56390f31d0eSKonstantin Khlebnikov 	return 0;
56490f31d0eSKonstantin Khlebnikov }
5651da177e4SLinus Torvalds #define mm_alloc_pgd(mm)	(0)
5661da177e4SLinus Torvalds #define mm_free_pgd(mm)
5671da177e4SLinus Torvalds #endif /* CONFIG_MMU */
5681da177e4SLinus Torvalds 
5691da177e4SLinus Torvalds __cacheline_aligned_in_smp DEFINE_SPINLOCK(mmlist_lock);
5701da177e4SLinus Torvalds 
571e94b1766SChristoph Lameter #define allocate_mm()	(kmem_cache_alloc(mm_cachep, GFP_KERNEL))
5721da177e4SLinus Torvalds #define free_mm(mm)	(kmem_cache_free(mm_cachep, (mm)))
5731da177e4SLinus Torvalds 
5744cb0e11bSHidehiro Kawai static unsigned long default_dump_filter = MMF_DUMP_FILTER_DEFAULT;
5754cb0e11bSHidehiro Kawai 
5764cb0e11bSHidehiro Kawai static int __init coredump_filter_setup(char *s)
5774cb0e11bSHidehiro Kawai {
5784cb0e11bSHidehiro Kawai 	default_dump_filter =
5794cb0e11bSHidehiro Kawai 		(simple_strtoul(s, NULL, 0) << MMF_DUMP_FILTER_SHIFT) &
5804cb0e11bSHidehiro Kawai 		MMF_DUMP_FILTER_MASK;
5814cb0e11bSHidehiro Kawai 	return 1;
5824cb0e11bSHidehiro Kawai }
5834cb0e11bSHidehiro Kawai 
5844cb0e11bSHidehiro Kawai __setup("coredump_filter=", coredump_filter_setup);
5854cb0e11bSHidehiro Kawai 
5861da177e4SLinus Torvalds #include <linux/init_task.h>
5871da177e4SLinus Torvalds 
588858f0993SAlexey Dobriyan static void mm_init_aio(struct mm_struct *mm)
589858f0993SAlexey Dobriyan {
590858f0993SAlexey Dobriyan #ifdef CONFIG_AIO
591858f0993SAlexey Dobriyan 	spin_lock_init(&mm->ioctx_lock);
592db446a08SBenjamin LaHaise 	mm->ioctx_table = NULL;
593858f0993SAlexey Dobriyan #endif
594858f0993SAlexey Dobriyan }
595858f0993SAlexey Dobriyan 
59633144e84SVladimir Davydov static void mm_init_owner(struct mm_struct *mm, struct task_struct *p)
59733144e84SVladimir Davydov {
59833144e84SVladimir Davydov #ifdef CONFIG_MEMCG
59933144e84SVladimir Davydov 	mm->owner = p;
60033144e84SVladimir Davydov #endif
60133144e84SVladimir Davydov }
60233144e84SVladimir Davydov 
60378fb7466SPavel Emelianov static struct mm_struct *mm_init(struct mm_struct *mm, struct task_struct *p)
6041da177e4SLinus Torvalds {
60541f727fdSVladimir Davydov 	mm->mmap = NULL;
60641f727fdSVladimir Davydov 	mm->mm_rb = RB_ROOT;
60741f727fdSVladimir Davydov 	mm->vmacache_seqnum = 0;
6081da177e4SLinus Torvalds 	atomic_set(&mm->mm_users, 1);
6091da177e4SLinus Torvalds 	atomic_set(&mm->mm_count, 1);
6101da177e4SLinus Torvalds 	init_rwsem(&mm->mmap_sem);
6111da177e4SLinus Torvalds 	INIT_LIST_HEAD(&mm->mmlist);
612999d9fc1SOleg Nesterov 	mm->core_state = NULL;
613e1f56c89SKirill A. Shutemov 	atomic_long_set(&mm->nr_ptes, 0);
6142d2f5119SKirill A. Shutemov 	mm_nr_pmds_init(mm);
61541f727fdSVladimir Davydov 	mm->map_count = 0;
61641f727fdSVladimir Davydov 	mm->locked_vm = 0;
617ce65cefaSVladimir Davydov 	mm->pinned_vm = 0;
618d559db08SKAMEZAWA Hiroyuki 	memset(&mm->rss_stat, 0, sizeof(mm->rss_stat));
6191da177e4SLinus Torvalds 	spin_lock_init(&mm->page_table_lock);
62041f727fdSVladimir Davydov 	mm_init_cpumask(mm);
621858f0993SAlexey Dobriyan 	mm_init_aio(mm);
622cf475ad2SBalbir Singh 	mm_init_owner(mm, p);
62341f727fdSVladimir Davydov 	mmu_notifier_mm_init(mm);
62420841405SRik van Riel 	clear_tlb_flush_pending(mm);
62541f727fdSVladimir Davydov #if defined(CONFIG_TRANSPARENT_HUGEPAGE) && !USE_SPLIT_PMD_PTLOCKS
62641f727fdSVladimir Davydov 	mm->pmd_huge_pte = NULL;
62741f727fdSVladimir Davydov #endif
6281da177e4SLinus Torvalds 
629a0715cc2SAlex Thorlton 	if (current->mm) {
630a0715cc2SAlex Thorlton 		mm->flags = current->mm->flags & MMF_INIT_MASK;
631a0715cc2SAlex Thorlton 		mm->def_flags = current->mm->def_flags & VM_INIT_DEF_MASK;
632a0715cc2SAlex Thorlton 	} else {
633a0715cc2SAlex Thorlton 		mm->flags = default_dump_filter;
6341da177e4SLinus Torvalds 		mm->def_flags = 0;
635a0715cc2SAlex Thorlton 	}
636a0715cc2SAlex Thorlton 
63741f727fdSVladimir Davydov 	if (mm_alloc_pgd(mm))
63841f727fdSVladimir Davydov 		goto fail_nopgd;
63978fb7466SPavel Emelianov 
64041f727fdSVladimir Davydov 	if (init_new_context(p, mm))
64141f727fdSVladimir Davydov 		goto fail_nocontext;
64241f727fdSVladimir Davydov 
64341f727fdSVladimir Davydov 	return mm;
64441f727fdSVladimir Davydov 
64541f727fdSVladimir Davydov fail_nocontext:
64641f727fdSVladimir Davydov 	mm_free_pgd(mm);
64741f727fdSVladimir Davydov fail_nopgd:
6481da177e4SLinus Torvalds 	free_mm(mm);
6491da177e4SLinus Torvalds 	return NULL;
6501da177e4SLinus Torvalds }
6511da177e4SLinus Torvalds 
652c3f0327fSKonstantin Khlebnikov static void check_mm(struct mm_struct *mm)
653c3f0327fSKonstantin Khlebnikov {
654c3f0327fSKonstantin Khlebnikov 	int i;
655c3f0327fSKonstantin Khlebnikov 
656c3f0327fSKonstantin Khlebnikov 	for (i = 0; i < NR_MM_COUNTERS; i++) {
657c3f0327fSKonstantin Khlebnikov 		long x = atomic_long_read(&mm->rss_stat.count[i]);
658c3f0327fSKonstantin Khlebnikov 
659c3f0327fSKonstantin Khlebnikov 		if (unlikely(x))
660c3f0327fSKonstantin Khlebnikov 			printk(KERN_ALERT "BUG: Bad rss-counter state "
661c3f0327fSKonstantin Khlebnikov 					  "mm:%p idx:%d val:%ld\n", mm, i, x);
662c3f0327fSKonstantin Khlebnikov 	}
663b30fe6c7SKirill A. Shutemov 
664b30fe6c7SKirill A. Shutemov 	if (atomic_long_read(&mm->nr_ptes))
665b30fe6c7SKirill A. Shutemov 		pr_alert("BUG: non-zero nr_ptes on freeing mm: %ld\n",
666b30fe6c7SKirill A. Shutemov 				atomic_long_read(&mm->nr_ptes));
667b30fe6c7SKirill A. Shutemov 	if (mm_nr_pmds(mm))
668b30fe6c7SKirill A. Shutemov 		pr_alert("BUG: non-zero nr_pmds on freeing mm: %ld\n",
669b30fe6c7SKirill A. Shutemov 				mm_nr_pmds(mm));
670b30fe6c7SKirill A. Shutemov 
671e009bb30SKirill A. Shutemov #if defined(CONFIG_TRANSPARENT_HUGEPAGE) && !USE_SPLIT_PMD_PTLOCKS
67296dad67fSSasha Levin 	VM_BUG_ON_MM(mm->pmd_huge_pte, mm);
673c3f0327fSKonstantin Khlebnikov #endif
674c3f0327fSKonstantin Khlebnikov }
675c3f0327fSKonstantin Khlebnikov 
6761da177e4SLinus Torvalds /*
6771da177e4SLinus Torvalds  * Allocate and initialize an mm_struct.
6781da177e4SLinus Torvalds  */
6791da177e4SLinus Torvalds struct mm_struct *mm_alloc(void)
6801da177e4SLinus Torvalds {
6811da177e4SLinus Torvalds 	struct mm_struct *mm;
6821da177e4SLinus Torvalds 
6831da177e4SLinus Torvalds 	mm = allocate_mm();
684de03c72cSKOSAKI Motohiro 	if (!mm)
685de03c72cSKOSAKI Motohiro 		return NULL;
686de03c72cSKOSAKI Motohiro 
6871da177e4SLinus Torvalds 	memset(mm, 0, sizeof(*mm));
6886345d24dSLinus Torvalds 	return mm_init(mm, current);
6891da177e4SLinus Torvalds }
6901da177e4SLinus Torvalds 
6911da177e4SLinus Torvalds /*
6921da177e4SLinus Torvalds  * Called when the last reference to the mm
6931da177e4SLinus Torvalds  * is dropped: either by a lazy thread or by
6941da177e4SLinus Torvalds  * mmput. Free the page directory and the mm.
6951da177e4SLinus Torvalds  */
6967ad5b3a5SHarvey Harrison void __mmdrop(struct mm_struct *mm)
6971da177e4SLinus Torvalds {
6981da177e4SLinus Torvalds 	BUG_ON(mm == &init_mm);
6991da177e4SLinus Torvalds 	mm_free_pgd(mm);
7001da177e4SLinus Torvalds 	destroy_context(mm);
701cddb8a5cSAndrea Arcangeli 	mmu_notifier_mm_destroy(mm);
702c3f0327fSKonstantin Khlebnikov 	check_mm(mm);
7031da177e4SLinus Torvalds 	free_mm(mm);
7041da177e4SLinus Torvalds }
7056d4e4c4fSAvi Kivity EXPORT_SYMBOL_GPL(__mmdrop);
7061da177e4SLinus Torvalds 
707ec8d7c14SMichal Hocko static inline void __mmput(struct mm_struct *mm)
7081da177e4SLinus Torvalds {
709ec8d7c14SMichal Hocko 	VM_BUG_ON(atomic_read(&mm->mm_users));
7100ae26f1bSAndrew Morton 
711d4b3b638SSrikar Dronamraju 	uprobe_clear_state(mm);
7121da177e4SLinus Torvalds 	exit_aio(mm);
7131c2fb7a4SAndrea Arcangeli 	ksm_exit(mm);
714ba76149fSAndrea Arcangeli 	khugepaged_exit(mm); /* must run before exit_mmap */
7151da177e4SLinus Torvalds 	exit_mmap(mm);
716925d1c40SMatt Helsley 	set_mm_exe_file(mm, NULL);
7171da177e4SLinus Torvalds 	if (!list_empty(&mm->mmlist)) {
7181da177e4SLinus Torvalds 		spin_lock(&mmlist_lock);
7191da177e4SLinus Torvalds 		list_del(&mm->mmlist);
7201da177e4SLinus Torvalds 		spin_unlock(&mmlist_lock);
7211da177e4SLinus Torvalds 	}
722801460d0SHiroshi Shimamoto 	if (mm->binfmt)
723801460d0SHiroshi Shimamoto 		module_put(mm->binfmt->module);
7241da177e4SLinus Torvalds 	mmdrop(mm);
7251da177e4SLinus Torvalds }
726ec8d7c14SMichal Hocko 
727ec8d7c14SMichal Hocko /*
728ec8d7c14SMichal Hocko  * Decrement the use count and release all resources for an mm.
729ec8d7c14SMichal Hocko  */
730ec8d7c14SMichal Hocko void mmput(struct mm_struct *mm)
731ec8d7c14SMichal Hocko {
732ec8d7c14SMichal Hocko 	might_sleep();
733ec8d7c14SMichal Hocko 
734ec8d7c14SMichal Hocko 	if (atomic_dec_and_test(&mm->mm_users))
735ec8d7c14SMichal Hocko 		__mmput(mm);
7361da177e4SLinus Torvalds }
7371da177e4SLinus Torvalds EXPORT_SYMBOL_GPL(mmput);
7381da177e4SLinus Torvalds 
739ec8d7c14SMichal Hocko static void mmput_async_fn(struct work_struct *work)
740ec8d7c14SMichal Hocko {
741ec8d7c14SMichal Hocko 	struct mm_struct *mm = container_of(work, struct mm_struct, async_put_work);
742ec8d7c14SMichal Hocko 	__mmput(mm);
743ec8d7c14SMichal Hocko }
744ec8d7c14SMichal Hocko 
745ec8d7c14SMichal Hocko void mmput_async(struct mm_struct *mm)
746ec8d7c14SMichal Hocko {
747ec8d7c14SMichal Hocko 	if (atomic_dec_and_test(&mm->mm_users)) {
748ec8d7c14SMichal Hocko 		INIT_WORK(&mm->async_put_work, mmput_async_fn);
749ec8d7c14SMichal Hocko 		schedule_work(&mm->async_put_work);
750ec8d7c14SMichal Hocko 	}
751ec8d7c14SMichal Hocko }
752ec8d7c14SMichal Hocko 
75390f31d0eSKonstantin Khlebnikov /**
75490f31d0eSKonstantin Khlebnikov  * set_mm_exe_file - change a reference to the mm's executable file
75590f31d0eSKonstantin Khlebnikov  *
75690f31d0eSKonstantin Khlebnikov  * This changes mm's executable file (shown as symlink /proc/[pid]/exe).
75790f31d0eSKonstantin Khlebnikov  *
7586e399cd1SDavidlohr Bueso  * Main users are mmput() and sys_execve(). Callers prevent concurrent
7596e399cd1SDavidlohr Bueso  * invocations: in mmput() nobody alive left, in execve task is single
7606e399cd1SDavidlohr Bueso  * threaded. sys_prctl(PR_SET_MM_MAP/EXE_FILE) also needs to set the
7616e399cd1SDavidlohr Bueso  * mm->exe_file, but does so without using set_mm_exe_file() in order
7626e399cd1SDavidlohr Bueso  * to do avoid the need for any locks.
76390f31d0eSKonstantin Khlebnikov  */
76438646013SJiri Slaby void set_mm_exe_file(struct mm_struct *mm, struct file *new_exe_file)
76538646013SJiri Slaby {
7666e399cd1SDavidlohr Bueso 	struct file *old_exe_file;
7676e399cd1SDavidlohr Bueso 
7686e399cd1SDavidlohr Bueso 	/*
7696e399cd1SDavidlohr Bueso 	 * It is safe to dereference the exe_file without RCU as
7706e399cd1SDavidlohr Bueso 	 * this function is only called if nobody else can access
7716e399cd1SDavidlohr Bueso 	 * this mm -- see comment above for justification.
7726e399cd1SDavidlohr Bueso 	 */
7736e399cd1SDavidlohr Bueso 	old_exe_file = rcu_dereference_raw(mm->exe_file);
77490f31d0eSKonstantin Khlebnikov 
77538646013SJiri Slaby 	if (new_exe_file)
77638646013SJiri Slaby 		get_file(new_exe_file);
77790f31d0eSKonstantin Khlebnikov 	rcu_assign_pointer(mm->exe_file, new_exe_file);
77890f31d0eSKonstantin Khlebnikov 	if (old_exe_file)
77990f31d0eSKonstantin Khlebnikov 		fput(old_exe_file);
78038646013SJiri Slaby }
78138646013SJiri Slaby 
78290f31d0eSKonstantin Khlebnikov /**
78390f31d0eSKonstantin Khlebnikov  * get_mm_exe_file - acquire a reference to the mm's executable file
78490f31d0eSKonstantin Khlebnikov  *
78590f31d0eSKonstantin Khlebnikov  * Returns %NULL if mm has no associated executable file.
78690f31d0eSKonstantin Khlebnikov  * User must release file via fput().
78790f31d0eSKonstantin Khlebnikov  */
78838646013SJiri Slaby struct file *get_mm_exe_file(struct mm_struct *mm)
78938646013SJiri Slaby {
79038646013SJiri Slaby 	struct file *exe_file;
79138646013SJiri Slaby 
79290f31d0eSKonstantin Khlebnikov 	rcu_read_lock();
79390f31d0eSKonstantin Khlebnikov 	exe_file = rcu_dereference(mm->exe_file);
79490f31d0eSKonstantin Khlebnikov 	if (exe_file && !get_file_rcu(exe_file))
79590f31d0eSKonstantin Khlebnikov 		exe_file = NULL;
79690f31d0eSKonstantin Khlebnikov 	rcu_read_unlock();
79738646013SJiri Slaby 	return exe_file;
79838646013SJiri Slaby }
79911163348SDavidlohr Bueso EXPORT_SYMBOL(get_mm_exe_file);
80038646013SJiri Slaby 
8011da177e4SLinus Torvalds /**
8021da177e4SLinus Torvalds  * get_task_mm - acquire a reference to the task's mm
8031da177e4SLinus Torvalds  *
804246bb0b1SOleg Nesterov  * Returns %NULL if the task has no mm.  Checks PF_KTHREAD (meaning
8051da177e4SLinus Torvalds  * this kernel workthread has transiently adopted a user mm with use_mm,
8061da177e4SLinus Torvalds  * to do its AIO) is not set and if so returns a reference to it, after
8071da177e4SLinus Torvalds  * bumping up the use count.  User must release the mm via mmput()
8081da177e4SLinus Torvalds  * after use.  Typically used by /proc and ptrace.
8091da177e4SLinus Torvalds  */
8101da177e4SLinus Torvalds struct mm_struct *get_task_mm(struct task_struct *task)
8111da177e4SLinus Torvalds {
8121da177e4SLinus Torvalds 	struct mm_struct *mm;
8131da177e4SLinus Torvalds 
8141da177e4SLinus Torvalds 	task_lock(task);
8151da177e4SLinus Torvalds 	mm = task->mm;
8161da177e4SLinus Torvalds 	if (mm) {
817246bb0b1SOleg Nesterov 		if (task->flags & PF_KTHREAD)
8181da177e4SLinus Torvalds 			mm = NULL;
8191da177e4SLinus Torvalds 		else
8201da177e4SLinus Torvalds 			atomic_inc(&mm->mm_users);
8211da177e4SLinus Torvalds 	}
8221da177e4SLinus Torvalds 	task_unlock(task);
8231da177e4SLinus Torvalds 	return mm;
8241da177e4SLinus Torvalds }
8251da177e4SLinus Torvalds EXPORT_SYMBOL_GPL(get_task_mm);
8261da177e4SLinus Torvalds 
8278cdb878dSChristopher Yeoh struct mm_struct *mm_access(struct task_struct *task, unsigned int mode)
8288cdb878dSChristopher Yeoh {
8298cdb878dSChristopher Yeoh 	struct mm_struct *mm;
8308cdb878dSChristopher Yeoh 	int err;
8318cdb878dSChristopher Yeoh 
8328cdb878dSChristopher Yeoh 	err =  mutex_lock_killable(&task->signal->cred_guard_mutex);
8338cdb878dSChristopher Yeoh 	if (err)
8348cdb878dSChristopher Yeoh 		return ERR_PTR(err);
8358cdb878dSChristopher Yeoh 
8368cdb878dSChristopher Yeoh 	mm = get_task_mm(task);
8378cdb878dSChristopher Yeoh 	if (mm && mm != current->mm &&
8388cdb878dSChristopher Yeoh 			!ptrace_may_access(task, mode)) {
8398cdb878dSChristopher Yeoh 		mmput(mm);
8408cdb878dSChristopher Yeoh 		mm = ERR_PTR(-EACCES);
8418cdb878dSChristopher Yeoh 	}
8428cdb878dSChristopher Yeoh 	mutex_unlock(&task->signal->cred_guard_mutex);
8438cdb878dSChristopher Yeoh 
8448cdb878dSChristopher Yeoh 	return mm;
8458cdb878dSChristopher Yeoh }
8468cdb878dSChristopher Yeoh 
84757b59c4aSOleg Nesterov static void complete_vfork_done(struct task_struct *tsk)
848c415c3b4SOleg Nesterov {
849d68b46feSOleg Nesterov 	struct completion *vfork;
850c415c3b4SOleg Nesterov 
851d68b46feSOleg Nesterov 	task_lock(tsk);
852d68b46feSOleg Nesterov 	vfork = tsk->vfork_done;
853d68b46feSOleg Nesterov 	if (likely(vfork)) {
854c415c3b4SOleg Nesterov 		tsk->vfork_done = NULL;
855d68b46feSOleg Nesterov 		complete(vfork);
856d68b46feSOleg Nesterov 	}
857d68b46feSOleg Nesterov 	task_unlock(tsk);
858d68b46feSOleg Nesterov }
859d68b46feSOleg Nesterov 
860d68b46feSOleg Nesterov static int wait_for_vfork_done(struct task_struct *child,
861d68b46feSOleg Nesterov 				struct completion *vfork)
862d68b46feSOleg Nesterov {
863d68b46feSOleg Nesterov 	int killed;
864d68b46feSOleg Nesterov 
865d68b46feSOleg Nesterov 	freezer_do_not_count();
866d68b46feSOleg Nesterov 	killed = wait_for_completion_killable(vfork);
867d68b46feSOleg Nesterov 	freezer_count();
868d68b46feSOleg Nesterov 
869d68b46feSOleg Nesterov 	if (killed) {
870d68b46feSOleg Nesterov 		task_lock(child);
871d68b46feSOleg Nesterov 		child->vfork_done = NULL;
872d68b46feSOleg Nesterov 		task_unlock(child);
873d68b46feSOleg Nesterov 	}
874d68b46feSOleg Nesterov 
875d68b46feSOleg Nesterov 	put_task_struct(child);
876d68b46feSOleg Nesterov 	return killed;
877c415c3b4SOleg Nesterov }
878c415c3b4SOleg Nesterov 
8791da177e4SLinus Torvalds /* Please note the differences between mmput and mm_release.
8801da177e4SLinus Torvalds  * mmput is called whenever we stop holding onto a mm_struct,
8811da177e4SLinus Torvalds  * error success whatever.
8821da177e4SLinus Torvalds  *
8831da177e4SLinus Torvalds  * mm_release is called after a mm_struct has been removed
8841da177e4SLinus Torvalds  * from the current process.
8851da177e4SLinus Torvalds  *
8861da177e4SLinus Torvalds  * This difference is important for error handling, when we
8871da177e4SLinus Torvalds  * only half set up a mm_struct for a new process and need to restore
8881da177e4SLinus Torvalds  * the old one.  Because we mmput the new mm_struct before
8891da177e4SLinus Torvalds  * restoring the old one. . .
8901da177e4SLinus Torvalds  * Eric Biederman 10 January 1998
8911da177e4SLinus Torvalds  */
8921da177e4SLinus Torvalds void mm_release(struct task_struct *tsk, struct mm_struct *mm)
8931da177e4SLinus Torvalds {
8948141c7f3SLinus Torvalds 	/* Get rid of any futexes when releasing the mm */
8958141c7f3SLinus Torvalds #ifdef CONFIG_FUTEX
896fc6b177dSPeter Zijlstra 	if (unlikely(tsk->robust_list)) {
8978141c7f3SLinus Torvalds 		exit_robust_list(tsk);
898fc6b177dSPeter Zijlstra 		tsk->robust_list = NULL;
899fc6b177dSPeter Zijlstra 	}
9008141c7f3SLinus Torvalds #ifdef CONFIG_COMPAT
901fc6b177dSPeter Zijlstra 	if (unlikely(tsk->compat_robust_list)) {
9028141c7f3SLinus Torvalds 		compat_exit_robust_list(tsk);
903fc6b177dSPeter Zijlstra 		tsk->compat_robust_list = NULL;
904fc6b177dSPeter Zijlstra 	}
9058141c7f3SLinus Torvalds #endif
906322a2c10SThomas Gleixner 	if (unlikely(!list_empty(&tsk->pi_state_list)))
907322a2c10SThomas Gleixner 		exit_pi_state_list(tsk);
9088141c7f3SLinus Torvalds #endif
9098141c7f3SLinus Torvalds 
9100326f5a9SSrikar Dronamraju 	uprobe_free_utask(tsk);
9110326f5a9SSrikar Dronamraju 
9121da177e4SLinus Torvalds 	/* Get rid of any cached register state */
9131da177e4SLinus Torvalds 	deactivate_mm(tsk, mm);
9141da177e4SLinus Torvalds 
915fec1d011SRoland McGrath 	/*
916fec1d011SRoland McGrath 	 * If we're exiting normally, clear a user-space tid field if
917fec1d011SRoland McGrath 	 * requested.  We leave this alone when dying by signal, to leave
918fec1d011SRoland McGrath 	 * the value intact in a core dump, and to save the unnecessary
919d68b46feSOleg Nesterov 	 * trouble, say, a killed vfork parent shouldn't touch this mm.
920d68b46feSOleg Nesterov 	 * Userland only wants this done for a sys_exit.
921fec1d011SRoland McGrath 	 */
9229c8a8228SEric Dumazet 	if (tsk->clear_child_tid) {
9239c8a8228SEric Dumazet 		if (!(tsk->flags & PF_SIGNALED) &&
9249c8a8228SEric Dumazet 		    atomic_read(&mm->mm_users) > 1) {
9251da177e4SLinus Torvalds 			/*
9261da177e4SLinus Torvalds 			 * We don't check the error code - if userspace has
9271da177e4SLinus Torvalds 			 * not set up a proper pointer then tough luck.
9281da177e4SLinus Torvalds 			 */
9299c8a8228SEric Dumazet 			put_user(0, tsk->clear_child_tid);
9309c8a8228SEric Dumazet 			sys_futex(tsk->clear_child_tid, FUTEX_WAKE,
9319c8a8228SEric Dumazet 					1, NULL, NULL, 0);
9329c8a8228SEric Dumazet 		}
9339c8a8228SEric Dumazet 		tsk->clear_child_tid = NULL;
9341da177e4SLinus Torvalds 	}
935f7505d64SKonstantin Khlebnikov 
936f7505d64SKonstantin Khlebnikov 	/*
937f7505d64SKonstantin Khlebnikov 	 * All done, finally we can wake up parent and return this mm to him.
938f7505d64SKonstantin Khlebnikov 	 * Also kthread_stop() uses this completion for synchronization.
939f7505d64SKonstantin Khlebnikov 	 */
940f7505d64SKonstantin Khlebnikov 	if (tsk->vfork_done)
941f7505d64SKonstantin Khlebnikov 		complete_vfork_done(tsk);
9421da177e4SLinus Torvalds }
9431da177e4SLinus Torvalds 
944a0a7ec30SJANAK DESAI /*
945a0a7ec30SJANAK DESAI  * Allocate a new mm structure and copy contents from the
946a0a7ec30SJANAK DESAI  * mm structure of the passed in task structure.
947a0a7ec30SJANAK DESAI  */
948ff252c1fSDaeSeok Youn static struct mm_struct *dup_mm(struct task_struct *tsk)
949a0a7ec30SJANAK DESAI {
950a0a7ec30SJANAK DESAI 	struct mm_struct *mm, *oldmm = current->mm;
951a0a7ec30SJANAK DESAI 	int err;
952a0a7ec30SJANAK DESAI 
953a0a7ec30SJANAK DESAI 	mm = allocate_mm();
954a0a7ec30SJANAK DESAI 	if (!mm)
955a0a7ec30SJANAK DESAI 		goto fail_nomem;
956a0a7ec30SJANAK DESAI 
957a0a7ec30SJANAK DESAI 	memcpy(mm, oldmm, sizeof(*mm));
958a0a7ec30SJANAK DESAI 
95978fb7466SPavel Emelianov 	if (!mm_init(mm, tsk))
960a0a7ec30SJANAK DESAI 		goto fail_nomem;
961a0a7ec30SJANAK DESAI 
962a0a7ec30SJANAK DESAI 	err = dup_mmap(mm, oldmm);
963a0a7ec30SJANAK DESAI 	if (err)
964a0a7ec30SJANAK DESAI 		goto free_pt;
965a0a7ec30SJANAK DESAI 
966a0a7ec30SJANAK DESAI 	mm->hiwater_rss = get_mm_rss(mm);
967a0a7ec30SJANAK DESAI 	mm->hiwater_vm = mm->total_vm;
968a0a7ec30SJANAK DESAI 
969801460d0SHiroshi Shimamoto 	if (mm->binfmt && !try_module_get(mm->binfmt->module))
970801460d0SHiroshi Shimamoto 		goto free_pt;
971801460d0SHiroshi Shimamoto 
972a0a7ec30SJANAK DESAI 	return mm;
973a0a7ec30SJANAK DESAI 
974a0a7ec30SJANAK DESAI free_pt:
975801460d0SHiroshi Shimamoto 	/* don't put binfmt in mmput, we haven't got module yet */
976801460d0SHiroshi Shimamoto 	mm->binfmt = NULL;
977a0a7ec30SJANAK DESAI 	mmput(mm);
978a0a7ec30SJANAK DESAI 
979a0a7ec30SJANAK DESAI fail_nomem:
980a0a7ec30SJANAK DESAI 	return NULL;
981a0a7ec30SJANAK DESAI }
982a0a7ec30SJANAK DESAI 
9831da177e4SLinus Torvalds static int copy_mm(unsigned long clone_flags, struct task_struct *tsk)
9841da177e4SLinus Torvalds {
9851da177e4SLinus Torvalds 	struct mm_struct *mm, *oldmm;
9861da177e4SLinus Torvalds 	int retval;
9871da177e4SLinus Torvalds 
9881da177e4SLinus Torvalds 	tsk->min_flt = tsk->maj_flt = 0;
9891da177e4SLinus Torvalds 	tsk->nvcsw = tsk->nivcsw = 0;
99017406b82SMandeep Singh Baines #ifdef CONFIG_DETECT_HUNG_TASK
99117406b82SMandeep Singh Baines 	tsk->last_switch_count = tsk->nvcsw + tsk->nivcsw;
99217406b82SMandeep Singh Baines #endif
9931da177e4SLinus Torvalds 
9941da177e4SLinus Torvalds 	tsk->mm = NULL;
9951da177e4SLinus Torvalds 	tsk->active_mm = NULL;
9961da177e4SLinus Torvalds 
9971da177e4SLinus Torvalds 	/*
9981da177e4SLinus Torvalds 	 * Are we cloning a kernel thread?
9991da177e4SLinus Torvalds 	 *
10001da177e4SLinus Torvalds 	 * We need to steal a active VM for that..
10011da177e4SLinus Torvalds 	 */
10021da177e4SLinus Torvalds 	oldmm = current->mm;
10031da177e4SLinus Torvalds 	if (!oldmm)
10041da177e4SLinus Torvalds 		return 0;
10051da177e4SLinus Torvalds 
1006615d6e87SDavidlohr Bueso 	/* initialize the new vmacache entries */
1007615d6e87SDavidlohr Bueso 	vmacache_flush(tsk);
1008615d6e87SDavidlohr Bueso 
10091da177e4SLinus Torvalds 	if (clone_flags & CLONE_VM) {
10101da177e4SLinus Torvalds 		atomic_inc(&oldmm->mm_users);
10111da177e4SLinus Torvalds 		mm = oldmm;
10121da177e4SLinus Torvalds 		goto good_mm;
10131da177e4SLinus Torvalds 	}
10141da177e4SLinus Torvalds 
10151da177e4SLinus Torvalds 	retval = -ENOMEM;
1016a0a7ec30SJANAK DESAI 	mm = dup_mm(tsk);
10171da177e4SLinus Torvalds 	if (!mm)
10181da177e4SLinus Torvalds 		goto fail_nomem;
10191da177e4SLinus Torvalds 
10201da177e4SLinus Torvalds good_mm:
10211da177e4SLinus Torvalds 	tsk->mm = mm;
10221da177e4SLinus Torvalds 	tsk->active_mm = mm;
10231da177e4SLinus Torvalds 	return 0;
10241da177e4SLinus Torvalds 
10251da177e4SLinus Torvalds fail_nomem:
10261da177e4SLinus Torvalds 	return retval;
10271da177e4SLinus Torvalds }
10281da177e4SLinus Torvalds 
1029a39bc516SAlexey Dobriyan static int copy_fs(unsigned long clone_flags, struct task_struct *tsk)
10301da177e4SLinus Torvalds {
1031498052bbSAl Viro 	struct fs_struct *fs = current->fs;
10321da177e4SLinus Torvalds 	if (clone_flags & CLONE_FS) {
1033498052bbSAl Viro 		/* tsk->fs is already what we want */
10342a4419b5SNick Piggin 		spin_lock(&fs->lock);
1035498052bbSAl Viro 		if (fs->in_exec) {
10362a4419b5SNick Piggin 			spin_unlock(&fs->lock);
1037498052bbSAl Viro 			return -EAGAIN;
1038498052bbSAl Viro 		}
1039498052bbSAl Viro 		fs->users++;
10402a4419b5SNick Piggin 		spin_unlock(&fs->lock);
10411da177e4SLinus Torvalds 		return 0;
10421da177e4SLinus Torvalds 	}
1043498052bbSAl Viro 	tsk->fs = copy_fs_struct(fs);
10441da177e4SLinus Torvalds 	if (!tsk->fs)
10451da177e4SLinus Torvalds 		return -ENOMEM;
10461da177e4SLinus Torvalds 	return 0;
10471da177e4SLinus Torvalds }
10481da177e4SLinus Torvalds 
1049a016f338SJANAK DESAI static int copy_files(unsigned long clone_flags, struct task_struct *tsk)
1050a016f338SJANAK DESAI {
1051a016f338SJANAK DESAI 	struct files_struct *oldf, *newf;
1052a016f338SJANAK DESAI 	int error = 0;
1053a016f338SJANAK DESAI 
1054a016f338SJANAK DESAI 	/*
1055a016f338SJANAK DESAI 	 * A background process may not have any files ...
1056a016f338SJANAK DESAI 	 */
1057a016f338SJANAK DESAI 	oldf = current->files;
1058a016f338SJANAK DESAI 	if (!oldf)
1059a016f338SJANAK DESAI 		goto out;
1060a016f338SJANAK DESAI 
1061a016f338SJANAK DESAI 	if (clone_flags & CLONE_FILES) {
1062a016f338SJANAK DESAI 		atomic_inc(&oldf->count);
1063a016f338SJANAK DESAI 		goto out;
1064a016f338SJANAK DESAI 	}
1065a016f338SJANAK DESAI 
1066a016f338SJANAK DESAI 	newf = dup_fd(oldf, &error);
1067a016f338SJANAK DESAI 	if (!newf)
1068a016f338SJANAK DESAI 		goto out;
1069a016f338SJANAK DESAI 
1070a016f338SJANAK DESAI 	tsk->files = newf;
1071a016f338SJANAK DESAI 	error = 0;
1072a016f338SJANAK DESAI out:
1073a016f338SJANAK DESAI 	return error;
1074a016f338SJANAK DESAI }
1075a016f338SJANAK DESAI 
1076fadad878SJens Axboe static int copy_io(unsigned long clone_flags, struct task_struct *tsk)
1077fd0928dfSJens Axboe {
1078fd0928dfSJens Axboe #ifdef CONFIG_BLOCK
1079fd0928dfSJens Axboe 	struct io_context *ioc = current->io_context;
10806e736be7STejun Heo 	struct io_context *new_ioc;
1081fd0928dfSJens Axboe 
1082fd0928dfSJens Axboe 	if (!ioc)
1083fd0928dfSJens Axboe 		return 0;
1084fadad878SJens Axboe 	/*
1085fadad878SJens Axboe 	 * Share io context with parent, if CLONE_IO is set
1086fadad878SJens Axboe 	 */
1087fadad878SJens Axboe 	if (clone_flags & CLONE_IO) {
10883d48749dSTejun Heo 		ioc_task_link(ioc);
10893d48749dSTejun Heo 		tsk->io_context = ioc;
1090fadad878SJens Axboe 	} else if (ioprio_valid(ioc->ioprio)) {
10916e736be7STejun Heo 		new_ioc = get_task_io_context(tsk, GFP_KERNEL, NUMA_NO_NODE);
10926e736be7STejun Heo 		if (unlikely(!new_ioc))
1093fd0928dfSJens Axboe 			return -ENOMEM;
1094fd0928dfSJens Axboe 
10956e736be7STejun Heo 		new_ioc->ioprio = ioc->ioprio;
109611a3122fSTejun Heo 		put_io_context(new_ioc);
1097fd0928dfSJens Axboe 	}
1098fd0928dfSJens Axboe #endif
1099fd0928dfSJens Axboe 	return 0;
1100fd0928dfSJens Axboe }
1101fd0928dfSJens Axboe 
1102a39bc516SAlexey Dobriyan static int copy_sighand(unsigned long clone_flags, struct task_struct *tsk)
11031da177e4SLinus Torvalds {
11041da177e4SLinus Torvalds 	struct sighand_struct *sig;
11051da177e4SLinus Torvalds 
110660348802SZhaolei 	if (clone_flags & CLONE_SIGHAND) {
11071da177e4SLinus Torvalds 		atomic_inc(&current->sighand->count);
11081da177e4SLinus Torvalds 		return 0;
11091da177e4SLinus Torvalds 	}
11101da177e4SLinus Torvalds 	sig = kmem_cache_alloc(sighand_cachep, GFP_KERNEL);
1111e56d0903SIngo Molnar 	rcu_assign_pointer(tsk->sighand, sig);
11121da177e4SLinus Torvalds 	if (!sig)
11131da177e4SLinus Torvalds 		return -ENOMEM;
11149d7fb042SPeter Zijlstra 
11151da177e4SLinus Torvalds 	atomic_set(&sig->count, 1);
11161da177e4SLinus Torvalds 	memcpy(sig->action, current->sighand->action, sizeof(sig->action));
11171da177e4SLinus Torvalds 	return 0;
11181da177e4SLinus Torvalds }
11191da177e4SLinus Torvalds 
1120a7e5328aSOleg Nesterov void __cleanup_sighand(struct sighand_struct *sighand)
1121c81addc9SOleg Nesterov {
1122d80e731eSOleg Nesterov 	if (atomic_dec_and_test(&sighand->count)) {
1123d80e731eSOleg Nesterov 		signalfd_cleanup(sighand);
1124392809b2SOleg Nesterov 		/*
1125392809b2SOleg Nesterov 		 * sighand_cachep is SLAB_DESTROY_BY_RCU so we can free it
1126392809b2SOleg Nesterov 		 * without an RCU grace period, see __lock_task_sighand().
1127392809b2SOleg Nesterov 		 */
1128c81addc9SOleg Nesterov 		kmem_cache_free(sighand_cachep, sighand);
1129c81addc9SOleg Nesterov 	}
1130d80e731eSOleg Nesterov }
1131c81addc9SOleg Nesterov 
1132f06febc9SFrank Mayhar /*
1133f06febc9SFrank Mayhar  * Initialize POSIX timer handling for a thread group.
1134f06febc9SFrank Mayhar  */
1135f06febc9SFrank Mayhar static void posix_cpu_timers_init_group(struct signal_struct *sig)
1136f06febc9SFrank Mayhar {
113778d7d407SJiri Slaby 	unsigned long cpu_limit;
113878d7d407SJiri Slaby 
1139316c1608SJason Low 	cpu_limit = READ_ONCE(sig->rlim[RLIMIT_CPU].rlim_cur);
114078d7d407SJiri Slaby 	if (cpu_limit != RLIM_INFINITY) {
114178d7d407SJiri Slaby 		sig->cputime_expires.prof_exp = secs_to_cputime(cpu_limit);
1142d5c373ebSJason Low 		sig->cputimer.running = true;
11436279a751SOleg Nesterov 	}
11446279a751SOleg Nesterov 
1145f06febc9SFrank Mayhar 	/* The timer lists. */
1146f06febc9SFrank Mayhar 	INIT_LIST_HEAD(&sig->cpu_timers[0]);
1147f06febc9SFrank Mayhar 	INIT_LIST_HEAD(&sig->cpu_timers[1]);
1148f06febc9SFrank Mayhar 	INIT_LIST_HEAD(&sig->cpu_timers[2]);
1149f06febc9SFrank Mayhar }
1150f06febc9SFrank Mayhar 
1151a39bc516SAlexey Dobriyan static int copy_signal(unsigned long clone_flags, struct task_struct *tsk)
11521da177e4SLinus Torvalds {
11531da177e4SLinus Torvalds 	struct signal_struct *sig;
11541da177e4SLinus Torvalds 
11554ab6c083SOleg Nesterov 	if (clone_flags & CLONE_THREAD)
1156490dea45SPeter Zijlstra 		return 0;
11576279a751SOleg Nesterov 
1158a56704efSVeaceslav Falico 	sig = kmem_cache_zalloc(signal_cachep, GFP_KERNEL);
11591da177e4SLinus Torvalds 	tsk->signal = sig;
11601da177e4SLinus Torvalds 	if (!sig)
11611da177e4SLinus Torvalds 		return -ENOMEM;
11621da177e4SLinus Torvalds 
1163b3ac022cSOleg Nesterov 	sig->nr_threads = 1;
11641da177e4SLinus Torvalds 	atomic_set(&sig->live, 1);
1165b3ac022cSOleg Nesterov 	atomic_set(&sig->sigcnt, 1);
11660c740d0aSOleg Nesterov 
11670c740d0aSOleg Nesterov 	/* list_add(thread_node, thread_head) without INIT_LIST_HEAD() */
11680c740d0aSOleg Nesterov 	sig->thread_head = (struct list_head)LIST_HEAD_INIT(tsk->thread_node);
11690c740d0aSOleg Nesterov 	tsk->thread_node = (struct list_head)LIST_HEAD_INIT(sig->thread_head);
11700c740d0aSOleg Nesterov 
11711da177e4SLinus Torvalds 	init_waitqueue_head(&sig->wait_chldexit);
1172db51aeccSOleg Nesterov 	sig->curr_target = tsk;
11731da177e4SLinus Torvalds 	init_sigpending(&sig->shared_pending);
11741da177e4SLinus Torvalds 	INIT_LIST_HEAD(&sig->posix_timers);
1175e78c3496SRik van Riel 	seqlock_init(&sig->stats_lock);
11769d7fb042SPeter Zijlstra 	prev_cputime_init(&sig->prev_cputime);
11771da177e4SLinus Torvalds 
1178c9cb2e3dSThomas Gleixner 	hrtimer_init(&sig->real_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
11791da177e4SLinus Torvalds 	sig->real_timer.function = it_real_fn;
11801da177e4SLinus Torvalds 
11811da177e4SLinus Torvalds 	task_lock(current->group_leader);
11821da177e4SLinus Torvalds 	memcpy(sig->rlim, current->signal->rlim, sizeof sig->rlim);
11831da177e4SLinus Torvalds 	task_unlock(current->group_leader);
11841da177e4SLinus Torvalds 
11856279a751SOleg Nesterov 	posix_cpu_timers_init_group(sig);
11866279a751SOleg Nesterov 
1187522ed776SMiloslav Trmac 	tty_audit_fork(sig);
11885091faa4SMike Galbraith 	sched_autogroup_fork(sig);
1189522ed776SMiloslav Trmac 
1190a63d83f4SDavid Rientjes 	sig->oom_score_adj = current->signal->oom_score_adj;
1191dabb16f6SMandeep Singh Baines 	sig->oom_score_adj_min = current->signal->oom_score_adj_min;
119228b83c51SKOSAKI Motohiro 
1193ebec18a6SLennart Poettering 	sig->has_child_subreaper = current->signal->has_child_subreaper ||
1194ebec18a6SLennart Poettering 				   current->signal->is_child_subreaper;
1195ebec18a6SLennart Poettering 
11969b1bf12dSKOSAKI Motohiro 	mutex_init(&sig->cred_guard_mutex);
11979b1bf12dSKOSAKI Motohiro 
11981da177e4SLinus Torvalds 	return 0;
11991da177e4SLinus Torvalds }
12001da177e4SLinus Torvalds 
1201dbd95212SKees Cook static void copy_seccomp(struct task_struct *p)
1202dbd95212SKees Cook {
1203dbd95212SKees Cook #ifdef CONFIG_SECCOMP
1204dbd95212SKees Cook 	/*
1205dbd95212SKees Cook 	 * Must be called with sighand->lock held, which is common to
1206dbd95212SKees Cook 	 * all threads in the group. Holding cred_guard_mutex is not
1207dbd95212SKees Cook 	 * needed because this new task is not yet running and cannot
1208dbd95212SKees Cook 	 * be racing exec.
1209dbd95212SKees Cook 	 */
121069f6a34bSGuenter Roeck 	assert_spin_locked(&current->sighand->siglock);
1211dbd95212SKees Cook 
1212dbd95212SKees Cook 	/* Ref-count the new filter user, and assign it. */
1213dbd95212SKees Cook 	get_seccomp_filter(current);
1214dbd95212SKees Cook 	p->seccomp = current->seccomp;
1215dbd95212SKees Cook 
1216dbd95212SKees Cook 	/*
1217dbd95212SKees Cook 	 * Explicitly enable no_new_privs here in case it got set
1218dbd95212SKees Cook 	 * between the task_struct being duplicated and holding the
1219dbd95212SKees Cook 	 * sighand lock. The seccomp state and nnp must be in sync.
1220dbd95212SKees Cook 	 */
1221dbd95212SKees Cook 	if (task_no_new_privs(current))
1222dbd95212SKees Cook 		task_set_no_new_privs(p);
1223dbd95212SKees Cook 
1224dbd95212SKees Cook 	/*
1225dbd95212SKees Cook 	 * If the parent gained a seccomp mode after copying thread
1226dbd95212SKees Cook 	 * flags and between before we held the sighand lock, we have
1227dbd95212SKees Cook 	 * to manually enable the seccomp thread flag here.
1228dbd95212SKees Cook 	 */
1229dbd95212SKees Cook 	if (p->seccomp.mode != SECCOMP_MODE_DISABLED)
1230dbd95212SKees Cook 		set_tsk_thread_flag(p, TIF_SECCOMP);
1231dbd95212SKees Cook #endif
1232dbd95212SKees Cook }
1233dbd95212SKees Cook 
123417da2bd9SHeiko Carstens SYSCALL_DEFINE1(set_tid_address, int __user *, tidptr)
12351da177e4SLinus Torvalds {
12361da177e4SLinus Torvalds 	current->clear_child_tid = tidptr;
12371da177e4SLinus Torvalds 
1238b488893aSPavel Emelyanov 	return task_pid_vnr(current);
12391da177e4SLinus Torvalds }
12401da177e4SLinus Torvalds 
1241a39bc516SAlexey Dobriyan static void rt_mutex_init_task(struct task_struct *p)
124223f78d4aSIngo Molnar {
12431d615482SThomas Gleixner 	raw_spin_lock_init(&p->pi_lock);
1244e29e175bSZilvinas Valinskas #ifdef CONFIG_RT_MUTEXES
1245fb00aca4SPeter Zijlstra 	p->pi_waiters = RB_ROOT;
1246fb00aca4SPeter Zijlstra 	p->pi_waiters_leftmost = NULL;
124723f78d4aSIngo Molnar 	p->pi_blocked_on = NULL;
124823f78d4aSIngo Molnar #endif
124923f78d4aSIngo Molnar }
125023f78d4aSIngo Molnar 
12511da177e4SLinus Torvalds /*
1252f06febc9SFrank Mayhar  * Initialize POSIX timer handling for a single task.
1253f06febc9SFrank Mayhar  */
1254f06febc9SFrank Mayhar static void posix_cpu_timers_init(struct task_struct *tsk)
1255f06febc9SFrank Mayhar {
125664861634SMartin Schwidefsky 	tsk->cputime_expires.prof_exp = 0;
125764861634SMartin Schwidefsky 	tsk->cputime_expires.virt_exp = 0;
1258f06febc9SFrank Mayhar 	tsk->cputime_expires.sched_exp = 0;
1259f06febc9SFrank Mayhar 	INIT_LIST_HEAD(&tsk->cpu_timers[0]);
1260f06febc9SFrank Mayhar 	INIT_LIST_HEAD(&tsk->cpu_timers[1]);
1261f06febc9SFrank Mayhar 	INIT_LIST_HEAD(&tsk->cpu_timers[2]);
1262f06febc9SFrank Mayhar }
1263f06febc9SFrank Mayhar 
126481907739SOleg Nesterov static inline void
126581907739SOleg Nesterov init_task_pid(struct task_struct *task, enum pid_type type, struct pid *pid)
126681907739SOleg Nesterov {
126781907739SOleg Nesterov 	 task->pids[type].pid = pid;
126881907739SOleg Nesterov }
126981907739SOleg Nesterov 
1270f06febc9SFrank Mayhar /*
12711da177e4SLinus Torvalds  * This creates a new process as a copy of the old one,
12721da177e4SLinus Torvalds  * but does not actually start it yet.
12731da177e4SLinus Torvalds  *
12741da177e4SLinus Torvalds  * It copies the registers, and all the appropriate
12751da177e4SLinus Torvalds  * parts of the process environment (as per the clone
12761da177e4SLinus Torvalds  * flags). The actual kick-off is left to the caller.
12771da177e4SLinus Torvalds  */
127836c8b586SIngo Molnar static struct task_struct *copy_process(unsigned long clone_flags,
12791da177e4SLinus Torvalds 					unsigned long stack_start,
12801da177e4SLinus Torvalds 					unsigned long stack_size,
12811da177e4SLinus Torvalds 					int __user *child_tidptr,
128209a05394SRoland McGrath 					struct pid *pid,
12833033f14aSJosh Triplett 					int trace,
1284725fc629SAndi Kleen 					unsigned long tls,
1285725fc629SAndi Kleen 					int node)
12861da177e4SLinus Torvalds {
12871da177e4SLinus Torvalds 	int retval;
1288a24efe62SMariusz Kozlowski 	struct task_struct *p;
12891da177e4SLinus Torvalds 
12901da177e4SLinus Torvalds 	if ((clone_flags & (CLONE_NEWNS|CLONE_FS)) == (CLONE_NEWNS|CLONE_FS))
12911da177e4SLinus Torvalds 		return ERR_PTR(-EINVAL);
12921da177e4SLinus Torvalds 
1293e66eded8SEric W. Biederman 	if ((clone_flags & (CLONE_NEWUSER|CLONE_FS)) == (CLONE_NEWUSER|CLONE_FS))
1294e66eded8SEric W. Biederman 		return ERR_PTR(-EINVAL);
1295e66eded8SEric W. Biederman 
12961da177e4SLinus Torvalds 	/*
12971da177e4SLinus Torvalds 	 * Thread groups must share signals as well, and detached threads
12981da177e4SLinus Torvalds 	 * can only be started up within the thread group.
12991da177e4SLinus Torvalds 	 */
13001da177e4SLinus Torvalds 	if ((clone_flags & CLONE_THREAD) && !(clone_flags & CLONE_SIGHAND))
13011da177e4SLinus Torvalds 		return ERR_PTR(-EINVAL);
13021da177e4SLinus Torvalds 
13031da177e4SLinus Torvalds 	/*
13041da177e4SLinus Torvalds 	 * Shared signal handlers imply shared VM. By way of the above,
13051da177e4SLinus Torvalds 	 * thread groups also imply shared VM. Blocking this case allows
13061da177e4SLinus Torvalds 	 * for various simplifications in other code.
13071da177e4SLinus Torvalds 	 */
13081da177e4SLinus Torvalds 	if ((clone_flags & CLONE_SIGHAND) && !(clone_flags & CLONE_VM))
13091da177e4SLinus Torvalds 		return ERR_PTR(-EINVAL);
13101da177e4SLinus Torvalds 
1311123be07bSSukadev Bhattiprolu 	/*
1312123be07bSSukadev Bhattiprolu 	 * Siblings of global init remain as zombies on exit since they are
1313123be07bSSukadev Bhattiprolu 	 * not reaped by their parent (swapper). To solve this and to avoid
1314123be07bSSukadev Bhattiprolu 	 * multi-rooted process trees, prevent global and container-inits
1315123be07bSSukadev Bhattiprolu 	 * from creating siblings.
1316123be07bSSukadev Bhattiprolu 	 */
1317123be07bSSukadev Bhattiprolu 	if ((clone_flags & CLONE_PARENT) &&
1318123be07bSSukadev Bhattiprolu 				current->signal->flags & SIGNAL_UNKILLABLE)
1319123be07bSSukadev Bhattiprolu 		return ERR_PTR(-EINVAL);
1320123be07bSSukadev Bhattiprolu 
13218382fcacSEric W. Biederman 	/*
132240a0d32dSOleg Nesterov 	 * If the new process will be in a different pid or user namespace
1323faf00da5SEric W. Biederman 	 * do not allow it to share a thread group with the forking task.
13248382fcacSEric W. Biederman 	 */
1325faf00da5SEric W. Biederman 	if (clone_flags & CLONE_THREAD) {
132640a0d32dSOleg Nesterov 		if ((clone_flags & (CLONE_NEWUSER | CLONE_NEWPID)) ||
132740a0d32dSOleg Nesterov 		    (task_active_pid_ns(current) !=
1328c2b1df2eSAndy Lutomirski 				current->nsproxy->pid_ns_for_children))
13298382fcacSEric W. Biederman 			return ERR_PTR(-EINVAL);
133040a0d32dSOleg Nesterov 	}
13318382fcacSEric W. Biederman 
13321da177e4SLinus Torvalds 	retval = security_task_create(clone_flags);
13331da177e4SLinus Torvalds 	if (retval)
13341da177e4SLinus Torvalds 		goto fork_out;
13351da177e4SLinus Torvalds 
13361da177e4SLinus Torvalds 	retval = -ENOMEM;
1337725fc629SAndi Kleen 	p = dup_task_struct(current, node);
13381da177e4SLinus Torvalds 	if (!p)
13391da177e4SLinus Torvalds 		goto fork_out;
13401da177e4SLinus Torvalds 
1341f7e8b616SSteven Rostedt 	ftrace_graph_init_task(p);
1342f7e8b616SSteven Rostedt 
1343bea493a0SPeter Zijlstra 	rt_mutex_init_task(p);
1344bea493a0SPeter Zijlstra 
1345d12c1a37SIngo Molnar #ifdef CONFIG_PROVE_LOCKING
1346de30a2b3SIngo Molnar 	DEBUG_LOCKS_WARN_ON(!p->hardirqs_enabled);
1347de30a2b3SIngo Molnar 	DEBUG_LOCKS_WARN_ON(!p->softirqs_enabled);
1348de30a2b3SIngo Molnar #endif
13491da177e4SLinus Torvalds 	retval = -EAGAIN;
13503b11a1deSDavid Howells 	if (atomic_read(&p->real_cred->user->processes) >=
135178d7d407SJiri Slaby 			task_rlimit(p, RLIMIT_NPROC)) {
1352b57922b6SEric Paris 		if (p->real_cred->user != INIT_USER &&
1353b57922b6SEric Paris 		    !capable(CAP_SYS_RESOURCE) && !capable(CAP_SYS_ADMIN))
13541da177e4SLinus Torvalds 			goto bad_fork_free;
13551da177e4SLinus Torvalds 	}
135672fa5997SVasiliy Kulikov 	current->flags &= ~PF_NPROC_EXCEEDED;
13571da177e4SLinus Torvalds 
1358f1752eecSDavid Howells 	retval = copy_creds(p, clone_flags);
1359f1752eecSDavid Howells 	if (retval < 0)
1360f1752eecSDavid Howells 		goto bad_fork_free;
13611da177e4SLinus Torvalds 
13621da177e4SLinus Torvalds 	/*
13631da177e4SLinus Torvalds 	 * If multiple threads are within copy_process(), then this check
13641da177e4SLinus Torvalds 	 * triggers too late. This doesn't hurt, the check is only there
13651da177e4SLinus Torvalds 	 * to stop root fork bombs.
13661da177e4SLinus Torvalds 	 */
136704ec93feSLi Zefan 	retval = -EAGAIN;
13681da177e4SLinus Torvalds 	if (nr_threads >= max_threads)
13691da177e4SLinus Torvalds 		goto bad_fork_cleanup_count;
13701da177e4SLinus Torvalds 
1371ca74e92bSShailabh Nagar 	delayacct_tsk_init(p);	/* Must remain after dup_task_struct() */
1372514ddb44SDavid Rientjes 	p->flags &= ~(PF_SUPERPRIV | PF_WQ_WORKER);
1373514ddb44SDavid Rientjes 	p->flags |= PF_FORKNOEXEC;
13741da177e4SLinus Torvalds 	INIT_LIST_HEAD(&p->children);
13751da177e4SLinus Torvalds 	INIT_LIST_HEAD(&p->sibling);
1376f41d911fSPaul E. McKenney 	rcu_copy_process(p);
13771da177e4SLinus Torvalds 	p->vfork_done = NULL;
13781da177e4SLinus Torvalds 	spin_lock_init(&p->alloc_lock);
13791da177e4SLinus Torvalds 
13801da177e4SLinus Torvalds 	init_sigpending(&p->pending);
13811da177e4SLinus Torvalds 
138264861634SMartin Schwidefsky 	p->utime = p->stime = p->gtime = 0;
138364861634SMartin Schwidefsky 	p->utimescaled = p->stimescaled = 0;
13849d7fb042SPeter Zijlstra 	prev_cputime_init(&p->prev_cputime);
13859d7fb042SPeter Zijlstra 
13866a61671bSFrederic Weisbecker #ifdef CONFIG_VIRT_CPU_ACCOUNTING_GEN
1387b7ce2277SFrederic Weisbecker 	seqcount_init(&p->vtime_seqcount);
13886a61671bSFrederic Weisbecker 	p->vtime_snap = 0;
13897098c1eaSFrederic Weisbecker 	p->vtime_snap_whence = VTIME_INACTIVE;
13906a61671bSFrederic Weisbecker #endif
13916a61671bSFrederic Weisbecker 
1392a3a2e76cSKAMEZAWA Hiroyuki #if defined(SPLIT_RSS_COUNTING)
1393a3a2e76cSKAMEZAWA Hiroyuki 	memset(&p->rss_stat, 0, sizeof(p->rss_stat));
1394a3a2e76cSKAMEZAWA Hiroyuki #endif
1395172ba844SBalbir Singh 
13966976675dSArjan van de Ven 	p->default_timer_slack_ns = current->timer_slack_ns;
13976976675dSArjan van de Ven 
13985995477aSAndrea Righi 	task_io_accounting_init(&p->ioac);
13991da177e4SLinus Torvalds 	acct_clear_integrals(p);
14001da177e4SLinus Torvalds 
1401f06febc9SFrank Mayhar 	posix_cpu_timers_init(p);
14021da177e4SLinus Torvalds 
1403ccbf62d8SThomas Gleixner 	p->start_time = ktime_get_ns();
140457e0be04SThomas Gleixner 	p->real_start_time = ktime_get_boot_ns();
14051da177e4SLinus Torvalds 	p->io_context = NULL;
14061da177e4SLinus Torvalds 	p->audit_context = NULL;
1407257058aeSTejun Heo 	threadgroup_change_begin(current);
1408b4f48b63SPaul Menage 	cgroup_fork(p);
14091da177e4SLinus Torvalds #ifdef CONFIG_NUMA
1410846a16bfSLee Schermerhorn 	p->mempolicy = mpol_dup(p->mempolicy);
14111da177e4SLinus Torvalds 	if (IS_ERR(p->mempolicy)) {
14121da177e4SLinus Torvalds 		retval = PTR_ERR(p->mempolicy);
14131da177e4SLinus Torvalds 		p->mempolicy = NULL;
1414e8604cb4SLi Zefan 		goto bad_fork_cleanup_threadgroup_lock;
14151da177e4SLinus Torvalds 	}
14161da177e4SLinus Torvalds #endif
1417778d3b0fSMichal Hocko #ifdef CONFIG_CPUSETS
1418778d3b0fSMichal Hocko 	p->cpuset_mem_spread_rotor = NUMA_NO_NODE;
1419778d3b0fSMichal Hocko 	p->cpuset_slab_spread_rotor = NUMA_NO_NODE;
1420cc9a6c87SMel Gorman 	seqcount_init(&p->mems_allowed_seq);
1421778d3b0fSMichal Hocko #endif
1422de30a2b3SIngo Molnar #ifdef CONFIG_TRACE_IRQFLAGS
1423de30a2b3SIngo Molnar 	p->irq_events = 0;
1424de30a2b3SIngo Molnar 	p->hardirqs_enabled = 0;
1425de30a2b3SIngo Molnar 	p->hardirq_enable_ip = 0;
1426de30a2b3SIngo Molnar 	p->hardirq_enable_event = 0;
1427de30a2b3SIngo Molnar 	p->hardirq_disable_ip = _THIS_IP_;
1428de30a2b3SIngo Molnar 	p->hardirq_disable_event = 0;
1429de30a2b3SIngo Molnar 	p->softirqs_enabled = 1;
1430de30a2b3SIngo Molnar 	p->softirq_enable_ip = _THIS_IP_;
1431de30a2b3SIngo Molnar 	p->softirq_enable_event = 0;
1432de30a2b3SIngo Molnar 	p->softirq_disable_ip = 0;
1433de30a2b3SIngo Molnar 	p->softirq_disable_event = 0;
1434de30a2b3SIngo Molnar 	p->hardirq_context = 0;
1435de30a2b3SIngo Molnar 	p->softirq_context = 0;
1436de30a2b3SIngo Molnar #endif
14378bcbde54SDavid Hildenbrand 
14388bcbde54SDavid Hildenbrand 	p->pagefault_disabled = 0;
14398bcbde54SDavid Hildenbrand 
1440fbb9ce95SIngo Molnar #ifdef CONFIG_LOCKDEP
1441fbb9ce95SIngo Molnar 	p->lockdep_depth = 0; /* no locks held yet */
1442fbb9ce95SIngo Molnar 	p->curr_chain_key = 0;
1443fbb9ce95SIngo Molnar 	p->lockdep_recursion = 0;
1444fbb9ce95SIngo Molnar #endif
14451da177e4SLinus Torvalds 
1446408894eeSIngo Molnar #ifdef CONFIG_DEBUG_MUTEXES
1447408894eeSIngo Molnar 	p->blocked_on = NULL; /* not blocked yet */
1448408894eeSIngo Molnar #endif
1449cafe5635SKent Overstreet #ifdef CONFIG_BCACHE
1450cafe5635SKent Overstreet 	p->sequential_io	= 0;
1451cafe5635SKent Overstreet 	p->sequential_io_avg	= 0;
1452cafe5635SKent Overstreet #endif
14530f481406SMarkus Metzger 
14543c90e6e9SSrivatsa Vaddagiri 	/* Perform scheduler related setup. Assign this task to a CPU. */
1455aab03e05SDario Faggioli 	retval = sched_fork(clone_flags, p);
1456aab03e05SDario Faggioli 	if (retval)
1457aab03e05SDario Faggioli 		goto bad_fork_cleanup_policy;
14586ab423e0SPeter Zijlstra 
1459cdd6c482SIngo Molnar 	retval = perf_event_init_task(p);
14606ab423e0SPeter Zijlstra 	if (retval)
14616ab423e0SPeter Zijlstra 		goto bad_fork_cleanup_policy;
1462fb0a685cSDaniel Rebelo de Oliveira 	retval = audit_alloc(p);
1463fb0a685cSDaniel Rebelo de Oliveira 	if (retval)
14646c72e350SPeter Zijlstra 		goto bad_fork_cleanup_perf;
14651da177e4SLinus Torvalds 	/* copy all the process information */
1466ab602f79SJack Miller 	shm_init_task(p);
1467fb0a685cSDaniel Rebelo de Oliveira 	retval = copy_semundo(clone_flags, p);
1468fb0a685cSDaniel Rebelo de Oliveira 	if (retval)
14691da177e4SLinus Torvalds 		goto bad_fork_cleanup_audit;
1470fb0a685cSDaniel Rebelo de Oliveira 	retval = copy_files(clone_flags, p);
1471fb0a685cSDaniel Rebelo de Oliveira 	if (retval)
14721da177e4SLinus Torvalds 		goto bad_fork_cleanup_semundo;
1473fb0a685cSDaniel Rebelo de Oliveira 	retval = copy_fs(clone_flags, p);
1474fb0a685cSDaniel Rebelo de Oliveira 	if (retval)
14751da177e4SLinus Torvalds 		goto bad_fork_cleanup_files;
1476fb0a685cSDaniel Rebelo de Oliveira 	retval = copy_sighand(clone_flags, p);
1477fb0a685cSDaniel Rebelo de Oliveira 	if (retval)
14781da177e4SLinus Torvalds 		goto bad_fork_cleanup_fs;
1479fb0a685cSDaniel Rebelo de Oliveira 	retval = copy_signal(clone_flags, p);
1480fb0a685cSDaniel Rebelo de Oliveira 	if (retval)
14811da177e4SLinus Torvalds 		goto bad_fork_cleanup_sighand;
1482fb0a685cSDaniel Rebelo de Oliveira 	retval = copy_mm(clone_flags, p);
1483fb0a685cSDaniel Rebelo de Oliveira 	if (retval)
14841da177e4SLinus Torvalds 		goto bad_fork_cleanup_signal;
1485fb0a685cSDaniel Rebelo de Oliveira 	retval = copy_namespaces(clone_flags, p);
1486fb0a685cSDaniel Rebelo de Oliveira 	if (retval)
1487d84f4f99SDavid Howells 		goto bad_fork_cleanup_mm;
1488fb0a685cSDaniel Rebelo de Oliveira 	retval = copy_io(clone_flags, p);
1489fb0a685cSDaniel Rebelo de Oliveira 	if (retval)
1490fd0928dfSJens Axboe 		goto bad_fork_cleanup_namespaces;
14913033f14aSJosh Triplett 	retval = copy_thread_tls(clone_flags, stack_start, stack_size, p, tls);
14921da177e4SLinus Torvalds 	if (retval)
1493fd0928dfSJens Axboe 		goto bad_fork_cleanup_io;
14941da177e4SLinus Torvalds 
1495425fb2b4SPavel Emelyanov 	if (pid != &init_struct_pid) {
1496c2b1df2eSAndy Lutomirski 		pid = alloc_pid(p->nsproxy->pid_ns_for_children);
149735f71bc0SMichal Hocko 		if (IS_ERR(pid)) {
149835f71bc0SMichal Hocko 			retval = PTR_ERR(pid);
14990740aa5fSJiri Slaby 			goto bad_fork_cleanup_thread;
1500425fb2b4SPavel Emelyanov 		}
150135f71bc0SMichal Hocko 	}
1502425fb2b4SPavel Emelyanov 
15031da177e4SLinus Torvalds 	p->set_child_tid = (clone_flags & CLONE_CHILD_SETTID) ? child_tidptr : NULL;
15041da177e4SLinus Torvalds 	/*
15051da177e4SLinus Torvalds 	 * Clear TID on mm_release()?
15061da177e4SLinus Torvalds 	 */
15071da177e4SLinus Torvalds 	p->clear_child_tid = (clone_flags & CLONE_CHILD_CLEARTID) ? child_tidptr : NULL;
150873c10101SJens Axboe #ifdef CONFIG_BLOCK
150973c10101SJens Axboe 	p->plug = NULL;
151073c10101SJens Axboe #endif
151142b2dd0aSAlexey Dobriyan #ifdef CONFIG_FUTEX
15128f17d3a5SIngo Molnar 	p->robust_list = NULL;
15138f17d3a5SIngo Molnar #ifdef CONFIG_COMPAT
15148f17d3a5SIngo Molnar 	p->compat_robust_list = NULL;
15158f17d3a5SIngo Molnar #endif
1516c87e2837SIngo Molnar 	INIT_LIST_HEAD(&p->pi_state_list);
1517c87e2837SIngo Molnar 	p->pi_state_cache = NULL;
151842b2dd0aSAlexey Dobriyan #endif
15191da177e4SLinus Torvalds 	/*
1520f9a3879aSGOTO Masanori 	 * sigaltstack should be cleared when sharing the same VM
1521f9a3879aSGOTO Masanori 	 */
1522f9a3879aSGOTO Masanori 	if ((clone_flags & (CLONE_VM|CLONE_VFORK)) == CLONE_VM)
15232a742138SStas Sergeev 		sas_ss_reset(p);
1524f9a3879aSGOTO Masanori 
1525f9a3879aSGOTO Masanori 	/*
15266580807dSOleg Nesterov 	 * Syscall tracing and stepping should be turned off in the
15276580807dSOleg Nesterov 	 * child regardless of CLONE_PTRACE.
15281da177e4SLinus Torvalds 	 */
15296580807dSOleg Nesterov 	user_disable_single_step(p);
15301da177e4SLinus Torvalds 	clear_tsk_thread_flag(p, TIF_SYSCALL_TRACE);
1531ed75e8d5SLaurent Vivier #ifdef TIF_SYSCALL_EMU
1532ed75e8d5SLaurent Vivier 	clear_tsk_thread_flag(p, TIF_SYSCALL_EMU);
1533ed75e8d5SLaurent Vivier #endif
15349745512cSArjan van de Ven 	clear_all_latency_tracing(p);
15351da177e4SLinus Torvalds 
15361da177e4SLinus Torvalds 	/* ok, now we should be set up.. */
153718c830dfSOleg Nesterov 	p->pid = pid_nr(pid);
153818c830dfSOleg Nesterov 	if (clone_flags & CLONE_THREAD) {
15395f8aadd8SOleg Nesterov 		p->exit_signal = -1;
154018c830dfSOleg Nesterov 		p->group_leader = current->group_leader;
154118c830dfSOleg Nesterov 		p->tgid = current->tgid;
154218c830dfSOleg Nesterov 	} else {
154318c830dfSOleg Nesterov 		if (clone_flags & CLONE_PARENT)
15445f8aadd8SOleg Nesterov 			p->exit_signal = current->group_leader->exit_signal;
15455f8aadd8SOleg Nesterov 		else
15465f8aadd8SOleg Nesterov 			p->exit_signal = (clone_flags & CSIGNAL);
154718c830dfSOleg Nesterov 		p->group_leader = p;
154818c830dfSOleg Nesterov 		p->tgid = p->pid;
154918c830dfSOleg Nesterov 	}
15505f8aadd8SOleg Nesterov 
15519d823e8fSWu Fengguang 	p->nr_dirtied = 0;
15529d823e8fSWu Fengguang 	p->nr_dirtied_pause = 128 >> (PAGE_SHIFT - 10);
155383712358SWu Fengguang 	p->dirty_paused_when = 0;
15549d823e8fSWu Fengguang 
1555bb8cbbfeSOleg Nesterov 	p->pdeath_signal = 0;
155647e65328SOleg Nesterov 	INIT_LIST_HEAD(&p->thread_group);
1557158e1645SAl Viro 	p->task_works = NULL;
15581da177e4SLinus Torvalds 
155918c830dfSOleg Nesterov 	/*
15607e47682eSAleksa Sarai 	 * Ensure that the cgroup subsystem policies allow the new process to be
15617e47682eSAleksa Sarai 	 * forked. It should be noted the the new process's css_set can be changed
15627e47682eSAleksa Sarai 	 * between here and cgroup_post_fork() if an organisation operation is in
15637e47682eSAleksa Sarai 	 * progress.
15647e47682eSAleksa Sarai 	 */
1565b53202e6SOleg Nesterov 	retval = cgroup_can_fork(p);
15667e47682eSAleksa Sarai 	if (retval)
15677e47682eSAleksa Sarai 		goto bad_fork_free_pid;
15687e47682eSAleksa Sarai 
15697e47682eSAleksa Sarai 	/*
157018c830dfSOleg Nesterov 	 * Make it visible to the rest of the system, but dont wake it up yet.
157118c830dfSOleg Nesterov 	 * Need tasklist lock for parent etc handling!
157218c830dfSOleg Nesterov 	 */
15731da177e4SLinus Torvalds 	write_lock_irq(&tasklist_lock);
15741da177e4SLinus Torvalds 
15751da177e4SLinus Torvalds 	/* CLONE_PARENT re-uses the old parent */
15762d5516cbSOleg Nesterov 	if (clone_flags & (CLONE_PARENT|CLONE_THREAD)) {
15771da177e4SLinus Torvalds 		p->real_parent = current->real_parent;
15782d5516cbSOleg Nesterov 		p->parent_exec_id = current->parent_exec_id;
15792d5516cbSOleg Nesterov 	} else {
15801da177e4SLinus Torvalds 		p->real_parent = current;
15812d5516cbSOleg Nesterov 		p->parent_exec_id = current->self_exec_id;
15822d5516cbSOleg Nesterov 	}
15831da177e4SLinus Torvalds 
15841da177e4SLinus Torvalds 	spin_lock(&current->sighand->siglock);
15854a2c7a78SOleg Nesterov 
15864a2c7a78SOleg Nesterov 	/*
1587dbd95212SKees Cook 	 * Copy seccomp details explicitly here, in case they were changed
1588dbd95212SKees Cook 	 * before holding sighand lock.
1589dbd95212SKees Cook 	 */
1590dbd95212SKees Cook 	copy_seccomp(p);
1591dbd95212SKees Cook 
1592dbd95212SKees Cook 	/*
15934a2c7a78SOleg Nesterov 	 * Process group and session signals need to be delivered to just the
15944a2c7a78SOleg Nesterov 	 * parent before the fork or both the parent and the child after the
15954a2c7a78SOleg Nesterov 	 * fork. Restart if a signal comes in before we add the new process to
15964a2c7a78SOleg Nesterov 	 * it's process group.
15974a2c7a78SOleg Nesterov 	 * A fatal signal pending means that current will exit, so the new
15984a2c7a78SOleg Nesterov 	 * thread can't slip out of an OOM kill (or normal SIGKILL).
15994a2c7a78SOleg Nesterov 	*/
16004a2c7a78SOleg Nesterov 	recalc_sigpending();
16014a2c7a78SOleg Nesterov 	if (signal_pending(current)) {
16024a2c7a78SOleg Nesterov 		spin_unlock(&current->sighand->siglock);
16034a2c7a78SOleg Nesterov 		write_unlock_irq(&tasklist_lock);
16044a2c7a78SOleg Nesterov 		retval = -ERESTARTNOINTR;
16057e47682eSAleksa Sarai 		goto bad_fork_cancel_cgroup;
16064a2c7a78SOleg Nesterov 	}
16074a2c7a78SOleg Nesterov 
160873b9ebfeSOleg Nesterov 	if (likely(p->pid)) {
16094b9d33e6STejun Heo 		ptrace_init_task(p, (clone_flags & CLONE_PTRACE) || trace);
16101da177e4SLinus Torvalds 
161181907739SOleg Nesterov 		init_task_pid(p, PIDTYPE_PID, pid);
16121da177e4SLinus Torvalds 		if (thread_group_leader(p)) {
161381907739SOleg Nesterov 			init_task_pid(p, PIDTYPE_PGID, task_pgrp(current));
161481907739SOleg Nesterov 			init_task_pid(p, PIDTYPE_SID, task_session(current));
161581907739SOleg Nesterov 
16161c4042c2SEric W. Biederman 			if (is_child_reaper(pid)) {
161717cf22c3SEric W. Biederman 				ns_of_pid(pid)->child_reaper = p;
16181c4042c2SEric W. Biederman 				p->signal->flags |= SIGNAL_UNKILLABLE;
16191c4042c2SEric W. Biederman 			}
16205cd17569SEric W. Biederman 
1621fea9d175SOleg Nesterov 			p->signal->leader_pid = pid;
16229c9f4dedSAlan Cox 			p->signal->tty = tty_kref_get(current->signal->tty);
16239cd80bbbSOleg Nesterov 			list_add_tail(&p->sibling, &p->real_parent->children);
16245e85d4abSEric W. Biederman 			list_add_tail_rcu(&p->tasks, &init_task.tasks);
162581907739SOleg Nesterov 			attach_pid(p, PIDTYPE_PGID);
162681907739SOleg Nesterov 			attach_pid(p, PIDTYPE_SID);
1627909ea964SChristoph Lameter 			__this_cpu_inc(process_counts);
162880628ca0SOleg Nesterov 		} else {
162980628ca0SOleg Nesterov 			current->signal->nr_threads++;
163080628ca0SOleg Nesterov 			atomic_inc(&current->signal->live);
163180628ca0SOleg Nesterov 			atomic_inc(&current->signal->sigcnt);
163280628ca0SOleg Nesterov 			list_add_tail_rcu(&p->thread_group,
163380628ca0SOleg Nesterov 					  &p->group_leader->thread_group);
16340c740d0aSOleg Nesterov 			list_add_tail_rcu(&p->thread_node,
16350c740d0aSOleg Nesterov 					  &p->signal->thread_head);
16361da177e4SLinus Torvalds 		}
163781907739SOleg Nesterov 		attach_pid(p, PIDTYPE_PID);
16381da177e4SLinus Torvalds 		nr_threads++;
163973b9ebfeSOleg Nesterov 	}
164073b9ebfeSOleg Nesterov 
16411da177e4SLinus Torvalds 	total_forks++;
16423f17da69SOleg Nesterov 	spin_unlock(&current->sighand->siglock);
16434af4206bSOleg Nesterov 	syscall_tracepoint_update(p);
16441da177e4SLinus Torvalds 	write_unlock_irq(&tasklist_lock);
16454af4206bSOleg Nesterov 
1646c13cf856SAndrew Morton 	proc_fork_connector(p);
1647b53202e6SOleg Nesterov 	cgroup_post_fork(p);
1648257058aeSTejun Heo 	threadgroup_change_end(current);
1649cdd6c482SIngo Molnar 	perf_event_fork(p);
165043d2b113SKAMEZAWA Hiroyuki 
165143d2b113SKAMEZAWA Hiroyuki 	trace_task_newtask(p, clone_flags);
16523ab67966SOleg Nesterov 	uprobe_copy_process(p, clone_flags);
165343d2b113SKAMEZAWA Hiroyuki 
16541da177e4SLinus Torvalds 	return p;
16551da177e4SLinus Torvalds 
16567e47682eSAleksa Sarai bad_fork_cancel_cgroup:
1657b53202e6SOleg Nesterov 	cgroup_cancel_fork(p);
1658425fb2b4SPavel Emelyanov bad_fork_free_pid:
1659425fb2b4SPavel Emelyanov 	if (pid != &init_struct_pid)
1660425fb2b4SPavel Emelyanov 		free_pid(pid);
16610740aa5fSJiri Slaby bad_fork_cleanup_thread:
16620740aa5fSJiri Slaby 	exit_thread(p);
1663fd0928dfSJens Axboe bad_fork_cleanup_io:
1664b69f2292SLouis Rilling 	if (p->io_context)
1665b69f2292SLouis Rilling 		exit_io_context(p);
1666ab516013SSerge E. Hallyn bad_fork_cleanup_namespaces:
1667444f378bSLinus Torvalds 	exit_task_namespaces(p);
16681da177e4SLinus Torvalds bad_fork_cleanup_mm:
1669c9f01245SDavid Rientjes 	if (p->mm)
16701da177e4SLinus Torvalds 		mmput(p->mm);
16711da177e4SLinus Torvalds bad_fork_cleanup_signal:
16724ab6c083SOleg Nesterov 	if (!(clone_flags & CLONE_THREAD))
16731c5354deSMike Galbraith 		free_signal_struct(p->signal);
16741da177e4SLinus Torvalds bad_fork_cleanup_sighand:
1675a7e5328aSOleg Nesterov 	__cleanup_sighand(p->sighand);
16761da177e4SLinus Torvalds bad_fork_cleanup_fs:
16771da177e4SLinus Torvalds 	exit_fs(p); /* blocking */
16781da177e4SLinus Torvalds bad_fork_cleanup_files:
16791da177e4SLinus Torvalds 	exit_files(p); /* blocking */
16801da177e4SLinus Torvalds bad_fork_cleanup_semundo:
16811da177e4SLinus Torvalds 	exit_sem(p);
16821da177e4SLinus Torvalds bad_fork_cleanup_audit:
16831da177e4SLinus Torvalds 	audit_free(p);
16846c72e350SPeter Zijlstra bad_fork_cleanup_perf:
1685cdd6c482SIngo Molnar 	perf_event_free_task(p);
16866c72e350SPeter Zijlstra bad_fork_cleanup_policy:
16871da177e4SLinus Torvalds #ifdef CONFIG_NUMA
1688f0be3d32SLee Schermerhorn 	mpol_put(p->mempolicy);
1689e8604cb4SLi Zefan bad_fork_cleanup_threadgroup_lock:
16901da177e4SLinus Torvalds #endif
1691257058aeSTejun Heo 	threadgroup_change_end(current);
169235df17c5SShailabh Nagar 	delayacct_tsk_free(p);
16931da177e4SLinus Torvalds bad_fork_cleanup_count:
1694d84f4f99SDavid Howells 	atomic_dec(&p->cred->user->processes);
1695e0e81739SDavid Howells 	exit_creds(p);
16961da177e4SLinus Torvalds bad_fork_free:
16971da177e4SLinus Torvalds 	free_task(p);
1698fe7d37d1SOleg Nesterov fork_out:
1699fe7d37d1SOleg Nesterov 	return ERR_PTR(retval);
17001da177e4SLinus Torvalds }
17011da177e4SLinus Torvalds 
1702f106eee1SOleg Nesterov static inline void init_idle_pids(struct pid_link *links)
1703f106eee1SOleg Nesterov {
1704f106eee1SOleg Nesterov 	enum pid_type type;
1705f106eee1SOleg Nesterov 
1706f106eee1SOleg Nesterov 	for (type = PIDTYPE_PID; type < PIDTYPE_MAX; ++type) {
1707f106eee1SOleg Nesterov 		INIT_HLIST_NODE(&links[type].node); /* not really needed */
1708f106eee1SOleg Nesterov 		links[type].pid = &init_struct_pid;
1709f106eee1SOleg Nesterov 	}
1710f106eee1SOleg Nesterov }
1711f106eee1SOleg Nesterov 
17120db0628dSPaul Gortmaker struct task_struct *fork_idle(int cpu)
17131da177e4SLinus Torvalds {
171436c8b586SIngo Molnar 	struct task_struct *task;
1715725fc629SAndi Kleen 	task = copy_process(CLONE_VM, 0, 0, NULL, &init_struct_pid, 0, 0,
1716725fc629SAndi Kleen 			    cpu_to_node(cpu));
1717f106eee1SOleg Nesterov 	if (!IS_ERR(task)) {
1718f106eee1SOleg Nesterov 		init_idle_pids(task->pids);
17191da177e4SLinus Torvalds 		init_idle(task, cpu);
1720f106eee1SOleg Nesterov 	}
172173b9ebfeSOleg Nesterov 
17221da177e4SLinus Torvalds 	return task;
17231da177e4SLinus Torvalds }
17241da177e4SLinus Torvalds 
17251da177e4SLinus Torvalds /*
17261da177e4SLinus Torvalds  *  Ok, this is the main fork-routine.
17271da177e4SLinus Torvalds  *
17281da177e4SLinus Torvalds  * It copies the process, and if successful kick-starts
17291da177e4SLinus Torvalds  * it and waits for it to finish using the VM if required.
17301da177e4SLinus Torvalds  */
17313033f14aSJosh Triplett long _do_fork(unsigned long clone_flags,
17321da177e4SLinus Torvalds 	      unsigned long stack_start,
17331da177e4SLinus Torvalds 	      unsigned long stack_size,
17341da177e4SLinus Torvalds 	      int __user *parent_tidptr,
17353033f14aSJosh Triplett 	      int __user *child_tidptr,
17363033f14aSJosh Triplett 	      unsigned long tls)
17371da177e4SLinus Torvalds {
17381da177e4SLinus Torvalds 	struct task_struct *p;
17391da177e4SLinus Torvalds 	int trace = 0;
174092476d7fSEric W. Biederman 	long nr;
17411da177e4SLinus Torvalds 
1742bdff746aSAndrew Morton 	/*
17434b9d33e6STejun Heo 	 * Determine whether and which event to report to ptracer.  When
17444b9d33e6STejun Heo 	 * called from kernel_thread or CLONE_UNTRACED is explicitly
17454b9d33e6STejun Heo 	 * requested, no event is reported; otherwise, report if the event
17464b9d33e6STejun Heo 	 * for the type of forking is enabled.
174709a05394SRoland McGrath 	 */
1748e80d6661SAl Viro 	if (!(clone_flags & CLONE_UNTRACED)) {
17494b9d33e6STejun Heo 		if (clone_flags & CLONE_VFORK)
17504b9d33e6STejun Heo 			trace = PTRACE_EVENT_VFORK;
17514b9d33e6STejun Heo 		else if ((clone_flags & CSIGNAL) != SIGCHLD)
17524b9d33e6STejun Heo 			trace = PTRACE_EVENT_CLONE;
17534b9d33e6STejun Heo 		else
17544b9d33e6STejun Heo 			trace = PTRACE_EVENT_FORK;
17554b9d33e6STejun Heo 
17564b9d33e6STejun Heo 		if (likely(!ptrace_event_enabled(current, trace)))
17574b9d33e6STejun Heo 			trace = 0;
17584b9d33e6STejun Heo 	}
17591da177e4SLinus Torvalds 
176062e791c1SAl Viro 	p = copy_process(clone_flags, stack_start, stack_size,
1761725fc629SAndi Kleen 			 child_tidptr, NULL, trace, tls, NUMA_NO_NODE);
17621da177e4SLinus Torvalds 	/*
17631da177e4SLinus Torvalds 	 * Do this prior waking up the new thread - the thread pointer
17641da177e4SLinus Torvalds 	 * might get invalid after that point, if the thread exits quickly.
17651da177e4SLinus Torvalds 	 */
17661da177e4SLinus Torvalds 	if (!IS_ERR(p)) {
17671da177e4SLinus Torvalds 		struct completion vfork;
17684e52365fSMatthew Dempsky 		struct pid *pid;
17691da177e4SLinus Torvalds 
17700a16b607SMathieu Desnoyers 		trace_sched_process_fork(current, p);
17710a16b607SMathieu Desnoyers 
17724e52365fSMatthew Dempsky 		pid = get_task_pid(p, PIDTYPE_PID);
17734e52365fSMatthew Dempsky 		nr = pid_vnr(pid);
177430e49c26SPavel Emelyanov 
177530e49c26SPavel Emelyanov 		if (clone_flags & CLONE_PARENT_SETTID)
177630e49c26SPavel Emelyanov 			put_user(nr, parent_tidptr);
1777a6f5e063SSukadev Bhattiprolu 
17781da177e4SLinus Torvalds 		if (clone_flags & CLONE_VFORK) {
17791da177e4SLinus Torvalds 			p->vfork_done = &vfork;
17801da177e4SLinus Torvalds 			init_completion(&vfork);
1781d68b46feSOleg Nesterov 			get_task_struct(p);
17821da177e4SLinus Torvalds 		}
17831da177e4SLinus Torvalds 
17843e51e3edSSamir Bellabes 		wake_up_new_task(p);
17851da177e4SLinus Torvalds 
17864b9d33e6STejun Heo 		/* forking complete and child started to run, tell ptracer */
17874b9d33e6STejun Heo 		if (unlikely(trace))
17884e52365fSMatthew Dempsky 			ptrace_event_pid(trace, pid);
178909a05394SRoland McGrath 
17901da177e4SLinus Torvalds 		if (clone_flags & CLONE_VFORK) {
1791d68b46feSOleg Nesterov 			if (!wait_for_vfork_done(p, &vfork))
17924e52365fSMatthew Dempsky 				ptrace_event_pid(PTRACE_EVENT_VFORK_DONE, pid);
17939f59ce5dSChuck Ebbert 		}
17944e52365fSMatthew Dempsky 
17954e52365fSMatthew Dempsky 		put_pid(pid);
17961da177e4SLinus Torvalds 	} else {
179792476d7fSEric W. Biederman 		nr = PTR_ERR(p);
17981da177e4SLinus Torvalds 	}
179992476d7fSEric W. Biederman 	return nr;
18001da177e4SLinus Torvalds }
18011da177e4SLinus Torvalds 
18023033f14aSJosh Triplett #ifndef CONFIG_HAVE_COPY_THREAD_TLS
18033033f14aSJosh Triplett /* For compatibility with architectures that call do_fork directly rather than
18043033f14aSJosh Triplett  * using the syscall entry points below. */
18053033f14aSJosh Triplett long do_fork(unsigned long clone_flags,
18063033f14aSJosh Triplett 	      unsigned long stack_start,
18073033f14aSJosh Triplett 	      unsigned long stack_size,
18083033f14aSJosh Triplett 	      int __user *parent_tidptr,
18093033f14aSJosh Triplett 	      int __user *child_tidptr)
18103033f14aSJosh Triplett {
18113033f14aSJosh Triplett 	return _do_fork(clone_flags, stack_start, stack_size,
18123033f14aSJosh Triplett 			parent_tidptr, child_tidptr, 0);
18133033f14aSJosh Triplett }
18143033f14aSJosh Triplett #endif
18153033f14aSJosh Triplett 
18162aa3a7f8SAl Viro /*
18172aa3a7f8SAl Viro  * Create a kernel thread.
18182aa3a7f8SAl Viro  */
18192aa3a7f8SAl Viro pid_t kernel_thread(int (*fn)(void *), void *arg, unsigned long flags)
18202aa3a7f8SAl Viro {
18213033f14aSJosh Triplett 	return _do_fork(flags|CLONE_VM|CLONE_UNTRACED, (unsigned long)fn,
18223033f14aSJosh Triplett 		(unsigned long)arg, NULL, NULL, 0);
18232aa3a7f8SAl Viro }
18242aa3a7f8SAl Viro 
1825d2125043SAl Viro #ifdef __ARCH_WANT_SYS_FORK
1826d2125043SAl Viro SYSCALL_DEFINE0(fork)
1827d2125043SAl Viro {
1828d2125043SAl Viro #ifdef CONFIG_MMU
18293033f14aSJosh Triplett 	return _do_fork(SIGCHLD, 0, 0, NULL, NULL, 0);
1830d2125043SAl Viro #else
1831d2125043SAl Viro 	/* can not support in nommu mode */
18325d59e182SDaeseok Youn 	return -EINVAL;
1833d2125043SAl Viro #endif
1834d2125043SAl Viro }
1835d2125043SAl Viro #endif
1836d2125043SAl Viro 
1837d2125043SAl Viro #ifdef __ARCH_WANT_SYS_VFORK
1838d2125043SAl Viro SYSCALL_DEFINE0(vfork)
1839d2125043SAl Viro {
18403033f14aSJosh Triplett 	return _do_fork(CLONE_VFORK | CLONE_VM | SIGCHLD, 0,
18413033f14aSJosh Triplett 			0, NULL, NULL, 0);
1842d2125043SAl Viro }
1843d2125043SAl Viro #endif
1844d2125043SAl Viro 
1845d2125043SAl Viro #ifdef __ARCH_WANT_SYS_CLONE
1846d2125043SAl Viro #ifdef CONFIG_CLONE_BACKWARDS
1847d2125043SAl Viro SYSCALL_DEFINE5(clone, unsigned long, clone_flags, unsigned long, newsp,
1848d2125043SAl Viro 		 int __user *, parent_tidptr,
18493033f14aSJosh Triplett 		 unsigned long, tls,
1850d2125043SAl Viro 		 int __user *, child_tidptr)
1851d2125043SAl Viro #elif defined(CONFIG_CLONE_BACKWARDS2)
1852d2125043SAl Viro SYSCALL_DEFINE5(clone, unsigned long, newsp, unsigned long, clone_flags,
1853d2125043SAl Viro 		 int __user *, parent_tidptr,
1854d2125043SAl Viro 		 int __user *, child_tidptr,
18553033f14aSJosh Triplett 		 unsigned long, tls)
1856dfa9771aSMichal Simek #elif defined(CONFIG_CLONE_BACKWARDS3)
1857dfa9771aSMichal Simek SYSCALL_DEFINE6(clone, unsigned long, clone_flags, unsigned long, newsp,
1858dfa9771aSMichal Simek 		int, stack_size,
1859dfa9771aSMichal Simek 		int __user *, parent_tidptr,
1860dfa9771aSMichal Simek 		int __user *, child_tidptr,
18613033f14aSJosh Triplett 		unsigned long, tls)
1862d2125043SAl Viro #else
1863d2125043SAl Viro SYSCALL_DEFINE5(clone, unsigned long, clone_flags, unsigned long, newsp,
1864d2125043SAl Viro 		 int __user *, parent_tidptr,
1865d2125043SAl Viro 		 int __user *, child_tidptr,
18663033f14aSJosh Triplett 		 unsigned long, tls)
1867d2125043SAl Viro #endif
1868d2125043SAl Viro {
18693033f14aSJosh Triplett 	return _do_fork(clone_flags, newsp, 0, parent_tidptr, child_tidptr, tls);
1870d2125043SAl Viro }
1871d2125043SAl Viro #endif
1872d2125043SAl Viro 
18735fd63b30SRavikiran G Thirumalai #ifndef ARCH_MIN_MMSTRUCT_ALIGN
18745fd63b30SRavikiran G Thirumalai #define ARCH_MIN_MMSTRUCT_ALIGN 0
18755fd63b30SRavikiran G Thirumalai #endif
18765fd63b30SRavikiran G Thirumalai 
187751cc5068SAlexey Dobriyan static void sighand_ctor(void *data)
1878aa1757f9SOleg Nesterov {
1879aa1757f9SOleg Nesterov 	struct sighand_struct *sighand = data;
1880aa1757f9SOleg Nesterov 
1881aa1757f9SOleg Nesterov 	spin_lock_init(&sighand->siglock);
1882b8fceee1SDavide Libenzi 	init_waitqueue_head(&sighand->signalfd_wqh);
1883fba2afaaSDavide Libenzi }
1884aa1757f9SOleg Nesterov 
18851da177e4SLinus Torvalds void __init proc_caches_init(void)
18861da177e4SLinus Torvalds {
18871da177e4SLinus Torvalds 	sighand_cachep = kmem_cache_create("sighand_cache",
18881da177e4SLinus Torvalds 			sizeof(struct sighand_struct), 0,
18892dff4405SVegard Nossum 			SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_DESTROY_BY_RCU|
18905d097056SVladimir Davydov 			SLAB_NOTRACK|SLAB_ACCOUNT, sighand_ctor);
18911da177e4SLinus Torvalds 	signal_cachep = kmem_cache_create("signal_cache",
18921da177e4SLinus Torvalds 			sizeof(struct signal_struct), 0,
18935d097056SVladimir Davydov 			SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_NOTRACK|SLAB_ACCOUNT,
18945d097056SVladimir Davydov 			NULL);
18951da177e4SLinus Torvalds 	files_cachep = kmem_cache_create("files_cache",
18961da177e4SLinus Torvalds 			sizeof(struct files_struct), 0,
18975d097056SVladimir Davydov 			SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_NOTRACK|SLAB_ACCOUNT,
18985d097056SVladimir Davydov 			NULL);
18991da177e4SLinus Torvalds 	fs_cachep = kmem_cache_create("fs_cache",
19001da177e4SLinus Torvalds 			sizeof(struct fs_struct), 0,
19015d097056SVladimir Davydov 			SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_NOTRACK|SLAB_ACCOUNT,
19025d097056SVladimir Davydov 			NULL);
19036345d24dSLinus Torvalds 	/*
19046345d24dSLinus Torvalds 	 * FIXME! The "sizeof(struct mm_struct)" currently includes the
19056345d24dSLinus Torvalds 	 * whole struct cpumask for the OFFSTACK case. We could change
19066345d24dSLinus Torvalds 	 * this to *only* allocate as much of it as required by the
19076345d24dSLinus Torvalds 	 * maximum number of CPU's we can ever have.  The cpumask_allocation
19086345d24dSLinus Torvalds 	 * is at the end of the structure, exactly for that reason.
19096345d24dSLinus Torvalds 	 */
19101da177e4SLinus Torvalds 	mm_cachep = kmem_cache_create("mm_struct",
19115fd63b30SRavikiran G Thirumalai 			sizeof(struct mm_struct), ARCH_MIN_MMSTRUCT_ALIGN,
19125d097056SVladimir Davydov 			SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_NOTRACK|SLAB_ACCOUNT,
19135d097056SVladimir Davydov 			NULL);
19145d097056SVladimir Davydov 	vm_area_cachep = KMEM_CACHE(vm_area_struct, SLAB_PANIC|SLAB_ACCOUNT);
19158feae131SDavid Howells 	mmap_init();
191666577193SAl Viro 	nsproxy_cache_init();
19171da177e4SLinus Torvalds }
1918cf2e340fSJANAK DESAI 
1919cf2e340fSJANAK DESAI /*
19209bfb23fcSOleg Nesterov  * Check constraints on flags passed to the unshare system call.
1921cf2e340fSJANAK DESAI  */
19229bfb23fcSOleg Nesterov static int check_unshare_flags(unsigned long unshare_flags)
1923cf2e340fSJANAK DESAI {
19249bfb23fcSOleg Nesterov 	if (unshare_flags & ~(CLONE_THREAD|CLONE_FS|CLONE_NEWNS|CLONE_SIGHAND|
19259bfb23fcSOleg Nesterov 				CLONE_VM|CLONE_FILES|CLONE_SYSVSEM|
192650804fe3SEric W. Biederman 				CLONE_NEWUTS|CLONE_NEWIPC|CLONE_NEWNET|
1927a79a908fSAditya Kali 				CLONE_NEWUSER|CLONE_NEWPID|CLONE_NEWCGROUP))
1928cf2e340fSJANAK DESAI 		return -EINVAL;
19299bfb23fcSOleg Nesterov 	/*
193012c641abSEric W. Biederman 	 * Not implemented, but pretend it works if there is nothing
193112c641abSEric W. Biederman 	 * to unshare.  Note that unsharing the address space or the
193212c641abSEric W. Biederman 	 * signal handlers also need to unshare the signal queues (aka
193312c641abSEric W. Biederman 	 * CLONE_THREAD).
19349bfb23fcSOleg Nesterov 	 */
19359bfb23fcSOleg Nesterov 	if (unshare_flags & (CLONE_THREAD | CLONE_SIGHAND | CLONE_VM)) {
193612c641abSEric W. Biederman 		if (!thread_group_empty(current))
193712c641abSEric W. Biederman 			return -EINVAL;
193812c641abSEric W. Biederman 	}
193912c641abSEric W. Biederman 	if (unshare_flags & (CLONE_SIGHAND | CLONE_VM)) {
194012c641abSEric W. Biederman 		if (atomic_read(&current->sighand->count) > 1)
194112c641abSEric W. Biederman 			return -EINVAL;
194212c641abSEric W. Biederman 	}
194312c641abSEric W. Biederman 	if (unshare_flags & CLONE_VM) {
194412c641abSEric W. Biederman 		if (!current_is_single_threaded())
19459bfb23fcSOleg Nesterov 			return -EINVAL;
19469bfb23fcSOleg Nesterov 	}
1947cf2e340fSJANAK DESAI 
1948cf2e340fSJANAK DESAI 	return 0;
1949cf2e340fSJANAK DESAI }
1950cf2e340fSJANAK DESAI 
1951cf2e340fSJANAK DESAI /*
195299d1419dSJANAK DESAI  * Unshare the filesystem structure if it is being shared
1953cf2e340fSJANAK DESAI  */
1954cf2e340fSJANAK DESAI static int unshare_fs(unsigned long unshare_flags, struct fs_struct **new_fsp)
1955cf2e340fSJANAK DESAI {
1956cf2e340fSJANAK DESAI 	struct fs_struct *fs = current->fs;
1957cf2e340fSJANAK DESAI 
1958498052bbSAl Viro 	if (!(unshare_flags & CLONE_FS) || !fs)
1959498052bbSAl Viro 		return 0;
1960498052bbSAl Viro 
1961498052bbSAl Viro 	/* don't need lock here; in the worst case we'll do useless copy */
1962498052bbSAl Viro 	if (fs->users == 1)
1963498052bbSAl Viro 		return 0;
1964498052bbSAl Viro 
1965498052bbSAl Viro 	*new_fsp = copy_fs_struct(fs);
196699d1419dSJANAK DESAI 	if (!*new_fsp)
196799d1419dSJANAK DESAI 		return -ENOMEM;
1968cf2e340fSJANAK DESAI 
1969cf2e340fSJANAK DESAI 	return 0;
1970cf2e340fSJANAK DESAI }
1971cf2e340fSJANAK DESAI 
1972cf2e340fSJANAK DESAI /*
1973a016f338SJANAK DESAI  * Unshare file descriptor table if it is being shared
1974cf2e340fSJANAK DESAI  */
1975cf2e340fSJANAK DESAI static int unshare_fd(unsigned long unshare_flags, struct files_struct **new_fdp)
1976cf2e340fSJANAK DESAI {
1977cf2e340fSJANAK DESAI 	struct files_struct *fd = current->files;
1978a016f338SJANAK DESAI 	int error = 0;
1979cf2e340fSJANAK DESAI 
1980cf2e340fSJANAK DESAI 	if ((unshare_flags & CLONE_FILES) &&
1981a016f338SJANAK DESAI 	    (fd && atomic_read(&fd->count) > 1)) {
1982a016f338SJANAK DESAI 		*new_fdp = dup_fd(fd, &error);
1983a016f338SJANAK DESAI 		if (!*new_fdp)
1984a016f338SJANAK DESAI 			return error;
1985a016f338SJANAK DESAI 	}
1986cf2e340fSJANAK DESAI 
1987cf2e340fSJANAK DESAI 	return 0;
1988cf2e340fSJANAK DESAI }
1989cf2e340fSJANAK DESAI 
1990cf2e340fSJANAK DESAI /*
1991cf2e340fSJANAK DESAI  * unshare allows a process to 'unshare' part of the process
1992cf2e340fSJANAK DESAI  * context which was originally shared using clone.  copy_*
1993cf2e340fSJANAK DESAI  * functions used by do_fork() cannot be used here directly
1994cf2e340fSJANAK DESAI  * because they modify an inactive task_struct that is being
1995cf2e340fSJANAK DESAI  * constructed. Here we are modifying the current, active,
1996cf2e340fSJANAK DESAI  * task_struct.
1997cf2e340fSJANAK DESAI  */
19986559eed8SHeiko Carstens SYSCALL_DEFINE1(unshare, unsigned long, unshare_flags)
1999cf2e340fSJANAK DESAI {
2000cf2e340fSJANAK DESAI 	struct fs_struct *fs, *new_fs = NULL;
2001cf2e340fSJANAK DESAI 	struct files_struct *fd, *new_fd = NULL;
2002b2e0d987SEric W. Biederman 	struct cred *new_cred = NULL;
2003cf7b708cSPavel Emelyanov 	struct nsproxy *new_nsproxy = NULL;
20049edff4abSManfred Spraul 	int do_sysvsem = 0;
20059bfb23fcSOleg Nesterov 	int err;
2006cf2e340fSJANAK DESAI 
200750804fe3SEric W. Biederman 	/*
2008faf00da5SEric W. Biederman 	 * If unsharing a user namespace must also unshare the thread group
2009faf00da5SEric W. Biederman 	 * and unshare the filesystem root and working directories.
2010b2e0d987SEric W. Biederman 	 */
2011b2e0d987SEric W. Biederman 	if (unshare_flags & CLONE_NEWUSER)
2012e66eded8SEric W. Biederman 		unshare_flags |= CLONE_THREAD | CLONE_FS;
2013b2e0d987SEric W. Biederman 	/*
201450804fe3SEric W. Biederman 	 * If unsharing vm, must also unshare signal handlers.
201550804fe3SEric W. Biederman 	 */
201650804fe3SEric W. Biederman 	if (unshare_flags & CLONE_VM)
201750804fe3SEric W. Biederman 		unshare_flags |= CLONE_SIGHAND;
20186013f67fSManfred Spraul 	/*
201912c641abSEric W. Biederman 	 * If unsharing a signal handlers, must also unshare the signal queues.
202012c641abSEric W. Biederman 	 */
202112c641abSEric W. Biederman 	if (unshare_flags & CLONE_SIGHAND)
202212c641abSEric W. Biederman 		unshare_flags |= CLONE_THREAD;
202312c641abSEric W. Biederman 	/*
20249bfb23fcSOleg Nesterov 	 * If unsharing namespace, must also unshare filesystem information.
20259bfb23fcSOleg Nesterov 	 */
20269bfb23fcSOleg Nesterov 	if (unshare_flags & CLONE_NEWNS)
20279bfb23fcSOleg Nesterov 		unshare_flags |= CLONE_FS;
202850804fe3SEric W. Biederman 
202950804fe3SEric W. Biederman 	err = check_unshare_flags(unshare_flags);
203050804fe3SEric W. Biederman 	if (err)
203150804fe3SEric W. Biederman 		goto bad_unshare_out;
20329bfb23fcSOleg Nesterov 	/*
20336013f67fSManfred Spraul 	 * CLONE_NEWIPC must also detach from the undolist: after switching
20346013f67fSManfred Spraul 	 * to a new ipc namespace, the semaphore arrays from the old
20356013f67fSManfred Spraul 	 * namespace are unreachable.
20366013f67fSManfred Spraul 	 */
20376013f67fSManfred Spraul 	if (unshare_flags & (CLONE_NEWIPC|CLONE_SYSVSEM))
20389edff4abSManfred Spraul 		do_sysvsem = 1;
2039fb0a685cSDaniel Rebelo de Oliveira 	err = unshare_fs(unshare_flags, &new_fs);
2040fb0a685cSDaniel Rebelo de Oliveira 	if (err)
20419bfb23fcSOleg Nesterov 		goto bad_unshare_out;
2042fb0a685cSDaniel Rebelo de Oliveira 	err = unshare_fd(unshare_flags, &new_fd);
2043fb0a685cSDaniel Rebelo de Oliveira 	if (err)
20449bfb23fcSOleg Nesterov 		goto bad_unshare_cleanup_fs;
2045b2e0d987SEric W. Biederman 	err = unshare_userns(unshare_flags, &new_cred);
2046fb0a685cSDaniel Rebelo de Oliveira 	if (err)
20479edff4abSManfred Spraul 		goto bad_unshare_cleanup_fd;
2048b2e0d987SEric W. Biederman 	err = unshare_nsproxy_namespaces(unshare_flags, &new_nsproxy,
2049b2e0d987SEric W. Biederman 					 new_cred, new_fs);
2050b2e0d987SEric W. Biederman 	if (err)
2051b2e0d987SEric W. Biederman 		goto bad_unshare_cleanup_cred;
2052cf2e340fSJANAK DESAI 
2053b2e0d987SEric W. Biederman 	if (new_fs || new_fd || do_sysvsem || new_cred || new_nsproxy) {
20549edff4abSManfred Spraul 		if (do_sysvsem) {
20559edff4abSManfred Spraul 			/*
20569edff4abSManfred Spraul 			 * CLONE_SYSVSEM is equivalent to sys_exit().
20579edff4abSManfred Spraul 			 */
20589edff4abSManfred Spraul 			exit_sem(current);
20599edff4abSManfred Spraul 		}
2060ab602f79SJack Miller 		if (unshare_flags & CLONE_NEWIPC) {
2061ab602f79SJack Miller 			/* Orphan segments in old ns (see sem above). */
2062ab602f79SJack Miller 			exit_shm(current);
2063ab602f79SJack Miller 			shm_init_task(current);
2064ab602f79SJack Miller 		}
2065ab516013SSerge E. Hallyn 
20666f977e6bSAlan Cox 		if (new_nsproxy)
2067cf7b708cSPavel Emelyanov 			switch_task_namespaces(current, new_nsproxy);
2068cf2e340fSJANAK DESAI 
2069cf7b708cSPavel Emelyanov 		task_lock(current);
2070cf7b708cSPavel Emelyanov 
2071cf2e340fSJANAK DESAI 		if (new_fs) {
2072cf2e340fSJANAK DESAI 			fs = current->fs;
20732a4419b5SNick Piggin 			spin_lock(&fs->lock);
2074cf2e340fSJANAK DESAI 			current->fs = new_fs;
2075498052bbSAl Viro 			if (--fs->users)
2076498052bbSAl Viro 				new_fs = NULL;
2077498052bbSAl Viro 			else
2078cf2e340fSJANAK DESAI 				new_fs = fs;
20792a4419b5SNick Piggin 			spin_unlock(&fs->lock);
2080cf2e340fSJANAK DESAI 		}
2081cf2e340fSJANAK DESAI 
2082cf2e340fSJANAK DESAI 		if (new_fd) {
2083cf2e340fSJANAK DESAI 			fd = current->files;
2084cf2e340fSJANAK DESAI 			current->files = new_fd;
2085cf2e340fSJANAK DESAI 			new_fd = fd;
2086cf2e340fSJANAK DESAI 		}
2087cf2e340fSJANAK DESAI 
2088cf2e340fSJANAK DESAI 		task_unlock(current);
2089b2e0d987SEric W. Biederman 
2090b2e0d987SEric W. Biederman 		if (new_cred) {
2091b2e0d987SEric W. Biederman 			/* Install the new user namespace */
2092b2e0d987SEric W. Biederman 			commit_creds(new_cred);
2093b2e0d987SEric W. Biederman 			new_cred = NULL;
2094b2e0d987SEric W. Biederman 		}
2095cf2e340fSJANAK DESAI 	}
2096cf2e340fSJANAK DESAI 
2097b2e0d987SEric W. Biederman bad_unshare_cleanup_cred:
2098b2e0d987SEric W. Biederman 	if (new_cred)
2099b2e0d987SEric W. Biederman 		put_cred(new_cred);
2100cf2e340fSJANAK DESAI bad_unshare_cleanup_fd:
2101cf2e340fSJANAK DESAI 	if (new_fd)
2102cf2e340fSJANAK DESAI 		put_files_struct(new_fd);
2103cf2e340fSJANAK DESAI 
2104cf2e340fSJANAK DESAI bad_unshare_cleanup_fs:
2105cf2e340fSJANAK DESAI 	if (new_fs)
2106498052bbSAl Viro 		free_fs_struct(new_fs);
2107cf2e340fSJANAK DESAI 
2108cf2e340fSJANAK DESAI bad_unshare_out:
2109cf2e340fSJANAK DESAI 	return err;
2110cf2e340fSJANAK DESAI }
21113b125388SAl Viro 
21123b125388SAl Viro /*
21133b125388SAl Viro  *	Helper to unshare the files of the current task.
21143b125388SAl Viro  *	We don't want to expose copy_files internals to
21153b125388SAl Viro  *	the exec layer of the kernel.
21163b125388SAl Viro  */
21173b125388SAl Viro 
21183b125388SAl Viro int unshare_files(struct files_struct **displaced)
21193b125388SAl Viro {
21203b125388SAl Viro 	struct task_struct *task = current;
212150704516SAl Viro 	struct files_struct *copy = NULL;
21223b125388SAl Viro 	int error;
21233b125388SAl Viro 
21243b125388SAl Viro 	error = unshare_fd(CLONE_FILES, &copy);
21253b125388SAl Viro 	if (error || !copy) {
21263b125388SAl Viro 		*displaced = NULL;
21273b125388SAl Viro 		return error;
21283b125388SAl Viro 	}
21293b125388SAl Viro 	*displaced = task->files;
21303b125388SAl Viro 	task_lock(task);
21313b125388SAl Viro 	task->files = copy;
21323b125388SAl Viro 	task_unlock(task);
21333b125388SAl Viro 	return 0;
21343b125388SAl Viro }
213516db3d3fSHeinrich Schuchardt 
213616db3d3fSHeinrich Schuchardt int sysctl_max_threads(struct ctl_table *table, int write,
213716db3d3fSHeinrich Schuchardt 		       void __user *buffer, size_t *lenp, loff_t *ppos)
213816db3d3fSHeinrich Schuchardt {
213916db3d3fSHeinrich Schuchardt 	struct ctl_table t;
214016db3d3fSHeinrich Schuchardt 	int ret;
214116db3d3fSHeinrich Schuchardt 	int threads = max_threads;
214216db3d3fSHeinrich Schuchardt 	int min = MIN_THREADS;
214316db3d3fSHeinrich Schuchardt 	int max = MAX_THREADS;
214416db3d3fSHeinrich Schuchardt 
214516db3d3fSHeinrich Schuchardt 	t = *table;
214616db3d3fSHeinrich Schuchardt 	t.data = &threads;
214716db3d3fSHeinrich Schuchardt 	t.extra1 = &min;
214816db3d3fSHeinrich Schuchardt 	t.extra2 = &max;
214916db3d3fSHeinrich Schuchardt 
215016db3d3fSHeinrich Schuchardt 	ret = proc_dointvec_minmax(&t, write, buffer, lenp, ppos);
215116db3d3fSHeinrich Schuchardt 	if (ret || !write)
215216db3d3fSHeinrich Schuchardt 		return ret;
215316db3d3fSHeinrich Schuchardt 
215416db3d3fSHeinrich Schuchardt 	set_max_threads(threads);
215516db3d3fSHeinrich Schuchardt 
215616db3d3fSHeinrich Schuchardt 	return 0;
215716db3d3fSHeinrich Schuchardt }
2158