xref: /openbmc/linux/kernel/fork.c (revision ac1b398de1ef94aeee8ba87b0120763526572a6e)
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>
771da177e4SLinus Torvalds 
781da177e4SLinus Torvalds #include <asm/pgtable.h>
791da177e4SLinus Torvalds #include <asm/pgalloc.h>
801da177e4SLinus Torvalds #include <asm/uaccess.h>
811da177e4SLinus Torvalds #include <asm/mmu_context.h>
821da177e4SLinus Torvalds #include <asm/cacheflush.h>
831da177e4SLinus Torvalds #include <asm/tlbflush.h>
841da177e4SLinus Torvalds 
85ad8d75ffSSteven Rostedt #include <trace/events/sched.h>
86ad8d75ffSSteven Rostedt 
8743d2b113SKAMEZAWA Hiroyuki #define CREATE_TRACE_POINTS
8843d2b113SKAMEZAWA Hiroyuki #include <trace/events/task.h>
8943d2b113SKAMEZAWA Hiroyuki 
901da177e4SLinus Torvalds /*
91*ac1b398dSHeinrich Schuchardt  * Minimum number of threads to boot the kernel
92*ac1b398dSHeinrich Schuchardt  */
93*ac1b398dSHeinrich Schuchardt #define MIN_THREADS 20
94*ac1b398dSHeinrich Schuchardt 
95*ac1b398dSHeinrich Schuchardt /*
96*ac1b398dSHeinrich Schuchardt  * Maximum number of threads
97*ac1b398dSHeinrich Schuchardt  */
98*ac1b398dSHeinrich Schuchardt #define MAX_THREADS FUTEX_TID_MASK
99*ac1b398dSHeinrich Schuchardt 
100*ac1b398dSHeinrich Schuchardt /*
1011da177e4SLinus Torvalds  * Protected counters by write_lock_irq(&tasklist_lock)
1021da177e4SLinus Torvalds  */
1031da177e4SLinus Torvalds unsigned long total_forks;	/* Handle normal Linux uptimes. */
1041da177e4SLinus Torvalds int nr_threads;			/* The idle threads do not count.. */
1051da177e4SLinus Torvalds 
1061da177e4SLinus Torvalds int max_threads;		/* tunable limit on nr_threads */
1071da177e4SLinus Torvalds 
1081da177e4SLinus Torvalds DEFINE_PER_CPU(unsigned long, process_counts) = 0;
1091da177e4SLinus Torvalds 
1101da177e4SLinus Torvalds __cacheline_aligned DEFINE_RWLOCK(tasklist_lock);  /* outer */
111db1466b3SPaul E. McKenney 
112db1466b3SPaul E. McKenney #ifdef CONFIG_PROVE_RCU
113db1466b3SPaul E. McKenney int lockdep_tasklist_lock_is_held(void)
114db1466b3SPaul E. McKenney {
115db1466b3SPaul E. McKenney 	return lockdep_is_held(&tasklist_lock);
116db1466b3SPaul E. McKenney }
117db1466b3SPaul E. McKenney EXPORT_SYMBOL_GPL(lockdep_tasklist_lock_is_held);
118db1466b3SPaul E. McKenney #endif /* #ifdef CONFIG_PROVE_RCU */
1191da177e4SLinus Torvalds 
1201da177e4SLinus Torvalds int nr_processes(void)
1211da177e4SLinus Torvalds {
1221da177e4SLinus Torvalds 	int cpu;
1231da177e4SLinus Torvalds 	int total = 0;
1241da177e4SLinus Torvalds 
1251d510750SIan Campbell 	for_each_possible_cpu(cpu)
1261da177e4SLinus Torvalds 		total += per_cpu(process_counts, cpu);
1271da177e4SLinus Torvalds 
1281da177e4SLinus Torvalds 	return total;
1291da177e4SLinus Torvalds }
1301da177e4SLinus Torvalds 
131f19b9f74SAkinobu Mita void __weak arch_release_task_struct(struct task_struct *tsk)
132f19b9f74SAkinobu Mita {
133f19b9f74SAkinobu Mita }
134f19b9f74SAkinobu Mita 
135f5e10287SThomas Gleixner #ifndef CONFIG_ARCH_TASK_STRUCT_ALLOCATOR
136e18b890bSChristoph Lameter static struct kmem_cache *task_struct_cachep;
13741101809SThomas Gleixner 
13841101809SThomas Gleixner static inline struct task_struct *alloc_task_struct_node(int node)
13941101809SThomas Gleixner {
14041101809SThomas Gleixner 	return kmem_cache_alloc_node(task_struct_cachep, GFP_KERNEL, node);
14141101809SThomas Gleixner }
14241101809SThomas Gleixner 
14341101809SThomas Gleixner static inline void free_task_struct(struct task_struct *tsk)
14441101809SThomas Gleixner {
14541101809SThomas Gleixner 	kmem_cache_free(task_struct_cachep, tsk);
14641101809SThomas Gleixner }
1471da177e4SLinus Torvalds #endif
1481da177e4SLinus Torvalds 
149f19b9f74SAkinobu Mita void __weak arch_release_thread_info(struct thread_info *ti)
150f19b9f74SAkinobu Mita {
151f19b9f74SAkinobu Mita }
152f19b9f74SAkinobu Mita 
153f5e10287SThomas Gleixner #ifndef CONFIG_ARCH_THREAD_INFO_ALLOCATOR
15441101809SThomas Gleixner 
1550d15d74aSThomas Gleixner /*
1560d15d74aSThomas Gleixner  * Allocate pages if THREAD_SIZE is >= PAGE_SIZE, otherwise use a
1570d15d74aSThomas Gleixner  * kmemcache based allocator.
1580d15d74aSThomas Gleixner  */
1590d15d74aSThomas Gleixner # if THREAD_SIZE >= PAGE_SIZE
160b6a84016SEric Dumazet static struct thread_info *alloc_thread_info_node(struct task_struct *tsk,
161b6a84016SEric Dumazet 						  int node)
162b69c49b7SFUJITA Tomonori {
16352383431SVladimir Davydov 	struct page *page = alloc_kmem_pages_node(node, THREADINFO_GFP,
1642889f608SThomas Gleixner 						  THREAD_SIZE_ORDER);
165b6a84016SEric Dumazet 
166b6a84016SEric Dumazet 	return page ? page_address(page) : NULL;
167b69c49b7SFUJITA Tomonori }
168b69c49b7SFUJITA Tomonori 
169b69c49b7SFUJITA Tomonori static inline void free_thread_info(struct thread_info *ti)
170b69c49b7SFUJITA Tomonori {
17152383431SVladimir Davydov 	free_kmem_pages((unsigned long)ti, THREAD_SIZE_ORDER);
172b69c49b7SFUJITA Tomonori }
1730d15d74aSThomas Gleixner # else
1740d15d74aSThomas Gleixner static struct kmem_cache *thread_info_cache;
1750d15d74aSThomas Gleixner 
1760d15d74aSThomas Gleixner static struct thread_info *alloc_thread_info_node(struct task_struct *tsk,
1770d15d74aSThomas Gleixner 						  int node)
1780d15d74aSThomas Gleixner {
1790d15d74aSThomas Gleixner 	return kmem_cache_alloc_node(thread_info_cache, THREADINFO_GFP, node);
1800d15d74aSThomas Gleixner }
1810d15d74aSThomas Gleixner 
1820d15d74aSThomas Gleixner static void free_thread_info(struct thread_info *ti)
1830d15d74aSThomas Gleixner {
1840d15d74aSThomas Gleixner 	kmem_cache_free(thread_info_cache, ti);
1850d15d74aSThomas Gleixner }
1860d15d74aSThomas Gleixner 
1870d15d74aSThomas Gleixner void thread_info_cache_init(void)
1880d15d74aSThomas Gleixner {
1890d15d74aSThomas Gleixner 	thread_info_cache = kmem_cache_create("thread_info", THREAD_SIZE,
1900d15d74aSThomas Gleixner 					      THREAD_SIZE, 0, NULL);
1910d15d74aSThomas Gleixner 	BUG_ON(thread_info_cache == NULL);
1920d15d74aSThomas Gleixner }
1930d15d74aSThomas Gleixner # endif
194b69c49b7SFUJITA Tomonori #endif
195b69c49b7SFUJITA Tomonori 
1961da177e4SLinus Torvalds /* SLAB cache for signal_struct structures (tsk->signal) */
197e18b890bSChristoph Lameter static struct kmem_cache *signal_cachep;
1981da177e4SLinus Torvalds 
1991da177e4SLinus Torvalds /* SLAB cache for sighand_struct structures (tsk->sighand) */
200e18b890bSChristoph Lameter struct kmem_cache *sighand_cachep;
2011da177e4SLinus Torvalds 
2021da177e4SLinus Torvalds /* SLAB cache for files_struct structures (tsk->files) */
203e18b890bSChristoph Lameter struct kmem_cache *files_cachep;
2041da177e4SLinus Torvalds 
2051da177e4SLinus Torvalds /* SLAB cache for fs_struct structures (tsk->fs) */
206e18b890bSChristoph Lameter struct kmem_cache *fs_cachep;
2071da177e4SLinus Torvalds 
2081da177e4SLinus Torvalds /* SLAB cache for vm_area_struct structures */
209e18b890bSChristoph Lameter struct kmem_cache *vm_area_cachep;
2101da177e4SLinus Torvalds 
2111da177e4SLinus Torvalds /* SLAB cache for mm_struct structures (tsk->mm) */
212e18b890bSChristoph Lameter static struct kmem_cache *mm_cachep;
2131da177e4SLinus Torvalds 
214c6a7f572SKOSAKI Motohiro static void account_kernel_stack(struct thread_info *ti, int account)
215c6a7f572SKOSAKI Motohiro {
216c6a7f572SKOSAKI Motohiro 	struct zone *zone = page_zone(virt_to_page(ti));
217c6a7f572SKOSAKI Motohiro 
218c6a7f572SKOSAKI Motohiro 	mod_zone_page_state(zone, NR_KERNEL_STACK, account);
219c6a7f572SKOSAKI Motohiro }
220c6a7f572SKOSAKI Motohiro 
2211da177e4SLinus Torvalds void free_task(struct task_struct *tsk)
2221da177e4SLinus Torvalds {
223c6a7f572SKOSAKI Motohiro 	account_kernel_stack(tsk->stack, -1);
224f19b9f74SAkinobu Mita 	arch_release_thread_info(tsk->stack);
225f7e4217bSRoman Zippel 	free_thread_info(tsk->stack);
22623f78d4aSIngo Molnar 	rt_mutex_debug_task_free(tsk);
227fb52607aSFrederic Weisbecker 	ftrace_graph_exit_task(tsk);
228e2cfabdfSWill Drewry 	put_seccomp_filter(tsk);
229f19b9f74SAkinobu Mita 	arch_release_task_struct(tsk);
2301da177e4SLinus Torvalds 	free_task_struct(tsk);
2311da177e4SLinus Torvalds }
2321da177e4SLinus Torvalds EXPORT_SYMBOL(free_task);
2331da177e4SLinus Torvalds 
234ea6d290cSOleg Nesterov static inline void free_signal_struct(struct signal_struct *sig)
235ea6d290cSOleg Nesterov {
23697101eb4SOleg Nesterov 	taskstats_tgid_free(sig);
2371c5354deSMike Galbraith 	sched_autogroup_exit(sig);
238ea6d290cSOleg Nesterov 	kmem_cache_free(signal_cachep, sig);
239ea6d290cSOleg Nesterov }
240ea6d290cSOleg Nesterov 
241ea6d290cSOleg Nesterov static inline void put_signal_struct(struct signal_struct *sig)
242ea6d290cSOleg Nesterov {
2431c5354deSMike Galbraith 	if (atomic_dec_and_test(&sig->sigcnt))
244ea6d290cSOleg Nesterov 		free_signal_struct(sig);
245ea6d290cSOleg Nesterov }
246ea6d290cSOleg Nesterov 
247158d9ebdSAndrew Morton void __put_task_struct(struct task_struct *tsk)
2481da177e4SLinus Torvalds {
249270f722dSEugene Teo 	WARN_ON(!tsk->exit_state);
2501da177e4SLinus Torvalds 	WARN_ON(atomic_read(&tsk->usage));
2511da177e4SLinus Torvalds 	WARN_ON(tsk == current);
2521da177e4SLinus Torvalds 
253156654f4SMike Galbraith 	task_numa_free(tsk);
2541a2a4d06SKees Cook 	security_task_free(tsk);
255e0e81739SDavid Howells 	exit_creds(tsk);
25635df17c5SShailabh Nagar 	delayacct_tsk_free(tsk);
257ea6d290cSOleg Nesterov 	put_signal_struct(tsk->signal);
2581da177e4SLinus Torvalds 
2591da177e4SLinus Torvalds 	if (!profile_handoff_task(tsk))
2601da177e4SLinus Torvalds 		free_task(tsk);
2611da177e4SLinus Torvalds }
26277c100c8SRik van Riel EXPORT_SYMBOL_GPL(__put_task_struct);
2631da177e4SLinus Torvalds 
2646c0a9fa6SThomas Gleixner void __init __weak arch_task_cache_init(void) { }
26561c4628bSSuresh Siddha 
266ff691f6eSHeinrich Schuchardt /*
267ff691f6eSHeinrich Schuchardt  * set_max_threads
268ff691f6eSHeinrich Schuchardt  */
269ff691f6eSHeinrich Schuchardt static void set_max_threads(void)
270ff691f6eSHeinrich Schuchardt {
271*ac1b398dSHeinrich Schuchardt 	u64 threads;
272ff691f6eSHeinrich Schuchardt 
273ff691f6eSHeinrich Schuchardt 	/*
274*ac1b398dSHeinrich Schuchardt 	 * The number of threads shall be limited such that the thread
275*ac1b398dSHeinrich Schuchardt 	 * structures may only consume a small part of the available memory.
276ff691f6eSHeinrich Schuchardt 	 */
277*ac1b398dSHeinrich Schuchardt 	if (fls64(totalram_pages) + fls64(PAGE_SIZE) > 64)
278*ac1b398dSHeinrich Schuchardt 		threads = MAX_THREADS;
279*ac1b398dSHeinrich Schuchardt 	else
280*ac1b398dSHeinrich Schuchardt 		threads = div64_u64((u64) totalram_pages * (u64) PAGE_SIZE,
281*ac1b398dSHeinrich Schuchardt 				    (u64) THREAD_SIZE * 8UL);
282*ac1b398dSHeinrich Schuchardt 
283*ac1b398dSHeinrich Schuchardt 	max_threads = clamp_t(u64, threads, MIN_THREADS, MAX_THREADS);
284ff691f6eSHeinrich Schuchardt }
285ff691f6eSHeinrich Schuchardt 
286ff691f6eSHeinrich Schuchardt void __init fork_init(void)
2871da177e4SLinus Torvalds {
288f5e10287SThomas Gleixner #ifndef CONFIG_ARCH_TASK_STRUCT_ALLOCATOR
2891da177e4SLinus Torvalds #ifndef ARCH_MIN_TASKALIGN
2901da177e4SLinus Torvalds #define ARCH_MIN_TASKALIGN	L1_CACHE_BYTES
2911da177e4SLinus Torvalds #endif
2921da177e4SLinus Torvalds 	/* create a slab on which task_structs can be allocated */
2931da177e4SLinus Torvalds 	task_struct_cachep =
2941da177e4SLinus Torvalds 		kmem_cache_create("task_struct", sizeof(struct task_struct),
2952dff4405SVegard Nossum 			ARCH_MIN_TASKALIGN, SLAB_PANIC | SLAB_NOTRACK, NULL);
2961da177e4SLinus Torvalds #endif
2971da177e4SLinus Torvalds 
29861c4628bSSuresh Siddha 	/* do the arch specific task caches init */
29961c4628bSSuresh Siddha 	arch_task_cache_init();
30061c4628bSSuresh Siddha 
301ff691f6eSHeinrich Schuchardt 	set_max_threads();
3021da177e4SLinus Torvalds 
3031da177e4SLinus Torvalds 	init_task.signal->rlim[RLIMIT_NPROC].rlim_cur = max_threads/2;
3041da177e4SLinus Torvalds 	init_task.signal->rlim[RLIMIT_NPROC].rlim_max = max_threads/2;
3051da177e4SLinus Torvalds 	init_task.signal->rlim[RLIMIT_SIGPENDING] =
3061da177e4SLinus Torvalds 		init_task.signal->rlim[RLIMIT_NPROC];
3071da177e4SLinus Torvalds }
3081da177e4SLinus Torvalds 
30952f5684cSGideon Israel Dsouza int __weak arch_dup_task_struct(struct task_struct *dst,
31061c4628bSSuresh Siddha 					       struct task_struct *src)
31161c4628bSSuresh Siddha {
31261c4628bSSuresh Siddha 	*dst = *src;
31361c4628bSSuresh Siddha 	return 0;
31461c4628bSSuresh Siddha }
31561c4628bSSuresh Siddha 
316d4311ff1SAaron Tomlin void set_task_stack_end_magic(struct task_struct *tsk)
317d4311ff1SAaron Tomlin {
318d4311ff1SAaron Tomlin 	unsigned long *stackend;
319d4311ff1SAaron Tomlin 
320d4311ff1SAaron Tomlin 	stackend = end_of_stack(tsk);
321d4311ff1SAaron Tomlin 	*stackend = STACK_END_MAGIC;	/* for overflow detection */
322d4311ff1SAaron Tomlin }
323d4311ff1SAaron Tomlin 
3241da177e4SLinus Torvalds static struct task_struct *dup_task_struct(struct task_struct *orig)
3251da177e4SLinus Torvalds {
3261da177e4SLinus Torvalds 	struct task_struct *tsk;
3271da177e4SLinus Torvalds 	struct thread_info *ti;
328207205a2SEric Dumazet 	int node = tsk_fork_get_node(orig);
3293e26c149SPeter Zijlstra 	int err;
3301da177e4SLinus Torvalds 
331504f52b5SEric Dumazet 	tsk = alloc_task_struct_node(node);
3321da177e4SLinus Torvalds 	if (!tsk)
3331da177e4SLinus Torvalds 		return NULL;
3341da177e4SLinus Torvalds 
335b6a84016SEric Dumazet 	ti = alloc_thread_info_node(tsk, node);
336f19b9f74SAkinobu Mita 	if (!ti)
337f19b9f74SAkinobu Mita 		goto free_tsk;
3381da177e4SLinus Torvalds 
33961c4628bSSuresh Siddha 	err = arch_dup_task_struct(tsk, orig);
34061c4628bSSuresh Siddha 	if (err)
341f19b9f74SAkinobu Mita 		goto free_ti;
34261c4628bSSuresh Siddha 
34387bec58aSAndrew Morton 	tsk->stack = ti;
344dbd95212SKees Cook #ifdef CONFIG_SECCOMP
345dbd95212SKees Cook 	/*
346dbd95212SKees Cook 	 * We must handle setting up seccomp filters once we're under
347dbd95212SKees Cook 	 * the sighand lock in case orig has changed between now and
348dbd95212SKees Cook 	 * then. Until then, filter must be NULL to avoid messing up
349dbd95212SKees Cook 	 * the usage counts on the error path calling free_task.
350dbd95212SKees Cook 	 */
351dbd95212SKees Cook 	tsk->seccomp.filter = NULL;
352dbd95212SKees Cook #endif
35387bec58aSAndrew Morton 
35487bec58aSAndrew Morton 	setup_thread_stack(tsk, orig);
3558e7cac79SAvi Kivity 	clear_user_return_notifier(tsk);
356f26f9affSMike Galbraith 	clear_tsk_need_resched(tsk);
357d4311ff1SAaron Tomlin 	set_task_stack_end_magic(tsk);
3581da177e4SLinus Torvalds 
3590a425405SArjan van de Ven #ifdef CONFIG_CC_STACKPROTECTOR
3600a425405SArjan van de Ven 	tsk->stack_canary = get_random_int();
3610a425405SArjan van de Ven #endif
3620a425405SArjan van de Ven 
363fb0a685cSDaniel Rebelo de Oliveira 	/*
364fb0a685cSDaniel Rebelo de Oliveira 	 * One for us, one for whoever does the "release_task()" (usually
365fb0a685cSDaniel Rebelo de Oliveira 	 * parent)
366fb0a685cSDaniel Rebelo de Oliveira 	 */
3671da177e4SLinus Torvalds 	atomic_set(&tsk->usage, 2);
3686c5c9341SAlexey Dobriyan #ifdef CONFIG_BLK_DEV_IO_TRACE
3692056a782SJens Axboe 	tsk->btrace_seq = 0;
3706c5c9341SAlexey Dobriyan #endif
371a0aa7f68SJens Axboe 	tsk->splice_pipe = NULL;
3725640f768SEric Dumazet 	tsk->task_frag.page = NULL;
373c6a7f572SKOSAKI Motohiro 
374c6a7f572SKOSAKI Motohiro 	account_kernel_stack(ti, 1);
375c6a7f572SKOSAKI Motohiro 
3761da177e4SLinus Torvalds 	return tsk;
37761c4628bSSuresh Siddha 
378f19b9f74SAkinobu Mita free_ti:
37961c4628bSSuresh Siddha 	free_thread_info(ti);
380f19b9f74SAkinobu Mita free_tsk:
38161c4628bSSuresh Siddha 	free_task_struct(tsk);
38261c4628bSSuresh Siddha 	return NULL;
3831da177e4SLinus Torvalds }
3841da177e4SLinus Torvalds 
3851da177e4SLinus Torvalds #ifdef CONFIG_MMU
386a39bc516SAlexey Dobriyan static int dup_mmap(struct mm_struct *mm, struct mm_struct *oldmm)
3871da177e4SLinus Torvalds {
388297c5eeeSLinus Torvalds 	struct vm_area_struct *mpnt, *tmp, *prev, **pprev;
3891da177e4SLinus Torvalds 	struct rb_node **rb_link, *rb_parent;
3901da177e4SLinus Torvalds 	int retval;
3911da177e4SLinus Torvalds 	unsigned long charge;
3921da177e4SLinus Torvalds 
39332cdba1eSOleg Nesterov 	uprobe_start_dup_mmap();
3941da177e4SLinus Torvalds 	down_write(&oldmm->mmap_sem);
395ec8c0446SRalf Baechle 	flush_cache_dup_mm(oldmm);
396f8ac4ec9SOleg Nesterov 	uprobe_dup_mmap(oldmm, mm);
397ad339451SIngo Molnar 	/*
398ad339451SIngo Molnar 	 * Not linked in yet - no deadlock potential:
399ad339451SIngo Molnar 	 */
400ad339451SIngo Molnar 	down_write_nested(&mm->mmap_sem, SINGLE_DEPTH_NESTING);
4017ee78232SHugh Dickins 
4024f7d4614SVladimir Davydov 	mm->total_vm = oldmm->total_vm;
4034f7d4614SVladimir Davydov 	mm->shared_vm = oldmm->shared_vm;
4044f7d4614SVladimir Davydov 	mm->exec_vm = oldmm->exec_vm;
4054f7d4614SVladimir Davydov 	mm->stack_vm = oldmm->stack_vm;
4064f7d4614SVladimir Davydov 
4071da177e4SLinus Torvalds 	rb_link = &mm->mm_rb.rb_node;
4081da177e4SLinus Torvalds 	rb_parent = NULL;
4091da177e4SLinus Torvalds 	pprev = &mm->mmap;
410f8af4da3SHugh Dickins 	retval = ksm_fork(mm, oldmm);
411f8af4da3SHugh Dickins 	if (retval)
412f8af4da3SHugh Dickins 		goto out;
413ba76149fSAndrea Arcangeli 	retval = khugepaged_fork(mm, oldmm);
414ba76149fSAndrea Arcangeli 	if (retval)
415ba76149fSAndrea Arcangeli 		goto out;
4161da177e4SLinus Torvalds 
417297c5eeeSLinus Torvalds 	prev = NULL;
418fd3e42fcSHugh Dickins 	for (mpnt = oldmm->mmap; mpnt; mpnt = mpnt->vm_next) {
4191da177e4SLinus Torvalds 		struct file *file;
4201da177e4SLinus Torvalds 
4211da177e4SLinus Torvalds 		if (mpnt->vm_flags & VM_DONTCOPY) {
422ab50b8edSHugh Dickins 			vm_stat_account(mm, mpnt->vm_flags, mpnt->vm_file,
42344de9d0cSHuang Shijie 							-vma_pages(mpnt));
4241da177e4SLinus Torvalds 			continue;
4251da177e4SLinus Torvalds 		}
4261da177e4SLinus Torvalds 		charge = 0;
4271da177e4SLinus Torvalds 		if (mpnt->vm_flags & VM_ACCOUNT) {
428b2412b7fSHuang Shijie 			unsigned long len = vma_pages(mpnt);
429b2412b7fSHuang Shijie 
430191c5424SAl Viro 			if (security_vm_enough_memory_mm(oldmm, len)) /* sic */
4311da177e4SLinus Torvalds 				goto fail_nomem;
4321da177e4SLinus Torvalds 			charge = len;
4331da177e4SLinus Torvalds 		}
434e94b1766SChristoph Lameter 		tmp = kmem_cache_alloc(vm_area_cachep, GFP_KERNEL);
4351da177e4SLinus Torvalds 		if (!tmp)
4361da177e4SLinus Torvalds 			goto fail_nomem;
4371da177e4SLinus Torvalds 		*tmp = *mpnt;
4385beb4930SRik van Riel 		INIT_LIST_HEAD(&tmp->anon_vma_chain);
439ef0855d3SOleg Nesterov 		retval = vma_dup_policy(mpnt, tmp);
440ef0855d3SOleg Nesterov 		if (retval)
4411da177e4SLinus Torvalds 			goto fail_nomem_policy;
442a247c3a9SAndrea Arcangeli 		tmp->vm_mm = mm;
4435beb4930SRik van Riel 		if (anon_vma_fork(tmp, mpnt))
4445beb4930SRik van Riel 			goto fail_nomem_anon_vma_fork;
4451da177e4SLinus Torvalds 		tmp->vm_flags &= ~VM_LOCKED;
446297c5eeeSLinus Torvalds 		tmp->vm_next = tmp->vm_prev = NULL;
4471da177e4SLinus Torvalds 		file = tmp->vm_file;
4481da177e4SLinus Torvalds 		if (file) {
449496ad9aaSAl Viro 			struct inode *inode = file_inode(file);
450b88ed205SHugh Dickins 			struct address_space *mapping = file->f_mapping;
451b88ed205SHugh Dickins 
4521da177e4SLinus Torvalds 			get_file(file);
4531da177e4SLinus Torvalds 			if (tmp->vm_flags & VM_DENYWRITE)
4541da177e4SLinus Torvalds 				atomic_dec(&inode->i_writecount);
45583cde9e8SDavidlohr Bueso 			i_mmap_lock_write(mapping);
456b88ed205SHugh Dickins 			if (tmp->vm_flags & VM_SHARED)
4574bb5f5d9SDavid Herrmann 				atomic_inc(&mapping->i_mmap_writable);
458b88ed205SHugh Dickins 			flush_dcache_mmap_lock(mapping);
459b88ed205SHugh Dickins 			/* insert tmp into the share list, just after mpnt */
4609826a516SMichel Lespinasse 			vma_interval_tree_insert_after(tmp, mpnt,
4619826a516SMichel Lespinasse 					&mapping->i_mmap);
462b88ed205SHugh Dickins 			flush_dcache_mmap_unlock(mapping);
46383cde9e8SDavidlohr Bueso 			i_mmap_unlock_write(mapping);
4641da177e4SLinus Torvalds 		}
4651da177e4SLinus Torvalds 
4661da177e4SLinus Torvalds 		/*
467a1e78772SMel Gorman 		 * Clear hugetlb-related page reserves for children. This only
468a1e78772SMel Gorman 		 * affects MAP_PRIVATE mappings. Faults generated by the child
469a1e78772SMel Gorman 		 * are not guaranteed to succeed, even if read-only
470a1e78772SMel Gorman 		 */
471a1e78772SMel Gorman 		if (is_vm_hugetlb_page(tmp))
472a1e78772SMel Gorman 			reset_vma_resv_huge_pages(tmp);
473a1e78772SMel Gorman 
474a1e78772SMel Gorman 		/*
4757ee78232SHugh Dickins 		 * Link in the new vma and copy the page table entries.
4761da177e4SLinus Torvalds 		 */
4771da177e4SLinus Torvalds 		*pprev = tmp;
4781da177e4SLinus Torvalds 		pprev = &tmp->vm_next;
479297c5eeeSLinus Torvalds 		tmp->vm_prev = prev;
480297c5eeeSLinus Torvalds 		prev = tmp;
4811da177e4SLinus Torvalds 
4821da177e4SLinus Torvalds 		__vma_link_rb(mm, tmp, rb_link, rb_parent);
4831da177e4SLinus Torvalds 		rb_link = &tmp->vm_rb.rb_right;
4841da177e4SLinus Torvalds 		rb_parent = &tmp->vm_rb;
4851da177e4SLinus Torvalds 
4861da177e4SLinus Torvalds 		mm->map_count++;
4870b0db14cSHugh Dickins 		retval = copy_page_range(mm, oldmm, mpnt);
4881da177e4SLinus Torvalds 
4891da177e4SLinus Torvalds 		if (tmp->vm_ops && tmp->vm_ops->open)
4901da177e4SLinus Torvalds 			tmp->vm_ops->open(tmp);
4911da177e4SLinus Torvalds 
4921da177e4SLinus Torvalds 		if (retval)
4931da177e4SLinus Torvalds 			goto out;
4941da177e4SLinus Torvalds 	}
495d6dd61c8SJeremy Fitzhardinge 	/* a new mm has just been created */
496d6dd61c8SJeremy Fitzhardinge 	arch_dup_mmap(oldmm, mm);
4971da177e4SLinus Torvalds 	retval = 0;
4981da177e4SLinus Torvalds out:
4997ee78232SHugh Dickins 	up_write(&mm->mmap_sem);
500fd3e42fcSHugh Dickins 	flush_tlb_mm(oldmm);
5011da177e4SLinus Torvalds 	up_write(&oldmm->mmap_sem);
50232cdba1eSOleg Nesterov 	uprobe_end_dup_mmap();
5031da177e4SLinus Torvalds 	return retval;
5045beb4930SRik van Riel fail_nomem_anon_vma_fork:
505ef0855d3SOleg Nesterov 	mpol_put(vma_policy(tmp));
5061da177e4SLinus Torvalds fail_nomem_policy:
5071da177e4SLinus Torvalds 	kmem_cache_free(vm_area_cachep, tmp);
5081da177e4SLinus Torvalds fail_nomem:
5091da177e4SLinus Torvalds 	retval = -ENOMEM;
5101da177e4SLinus Torvalds 	vm_unacct_memory(charge);
5111da177e4SLinus Torvalds 	goto out;
5121da177e4SLinus Torvalds }
5131da177e4SLinus Torvalds 
5141da177e4SLinus Torvalds static inline int mm_alloc_pgd(struct mm_struct *mm)
5151da177e4SLinus Torvalds {
5161da177e4SLinus Torvalds 	mm->pgd = pgd_alloc(mm);
5171da177e4SLinus Torvalds 	if (unlikely(!mm->pgd))
5181da177e4SLinus Torvalds 		return -ENOMEM;
5191da177e4SLinus Torvalds 	return 0;
5201da177e4SLinus Torvalds }
5211da177e4SLinus Torvalds 
5221da177e4SLinus Torvalds static inline void mm_free_pgd(struct mm_struct *mm)
5231da177e4SLinus Torvalds {
5245e541973SBenjamin Herrenschmidt 	pgd_free(mm, mm->pgd);
5251da177e4SLinus Torvalds }
5261da177e4SLinus Torvalds #else
5271da177e4SLinus Torvalds #define dup_mmap(mm, oldmm)	(0)
5281da177e4SLinus Torvalds #define mm_alloc_pgd(mm)	(0)
5291da177e4SLinus Torvalds #define mm_free_pgd(mm)
5301da177e4SLinus Torvalds #endif /* CONFIG_MMU */
5311da177e4SLinus Torvalds 
5321da177e4SLinus Torvalds __cacheline_aligned_in_smp DEFINE_SPINLOCK(mmlist_lock);
5331da177e4SLinus Torvalds 
534e94b1766SChristoph Lameter #define allocate_mm()	(kmem_cache_alloc(mm_cachep, GFP_KERNEL))
5351da177e4SLinus Torvalds #define free_mm(mm)	(kmem_cache_free(mm_cachep, (mm)))
5361da177e4SLinus Torvalds 
5374cb0e11bSHidehiro Kawai static unsigned long default_dump_filter = MMF_DUMP_FILTER_DEFAULT;
5384cb0e11bSHidehiro Kawai 
5394cb0e11bSHidehiro Kawai static int __init coredump_filter_setup(char *s)
5404cb0e11bSHidehiro Kawai {
5414cb0e11bSHidehiro Kawai 	default_dump_filter =
5424cb0e11bSHidehiro Kawai 		(simple_strtoul(s, NULL, 0) << MMF_DUMP_FILTER_SHIFT) &
5434cb0e11bSHidehiro Kawai 		MMF_DUMP_FILTER_MASK;
5444cb0e11bSHidehiro Kawai 	return 1;
5454cb0e11bSHidehiro Kawai }
5464cb0e11bSHidehiro Kawai 
5474cb0e11bSHidehiro Kawai __setup("coredump_filter=", coredump_filter_setup);
5484cb0e11bSHidehiro Kawai 
5491da177e4SLinus Torvalds #include <linux/init_task.h>
5501da177e4SLinus Torvalds 
551858f0993SAlexey Dobriyan static void mm_init_aio(struct mm_struct *mm)
552858f0993SAlexey Dobriyan {
553858f0993SAlexey Dobriyan #ifdef CONFIG_AIO
554858f0993SAlexey Dobriyan 	spin_lock_init(&mm->ioctx_lock);
555db446a08SBenjamin LaHaise 	mm->ioctx_table = NULL;
556858f0993SAlexey Dobriyan #endif
557858f0993SAlexey Dobriyan }
558858f0993SAlexey Dobriyan 
55933144e84SVladimir Davydov static void mm_init_owner(struct mm_struct *mm, struct task_struct *p)
56033144e84SVladimir Davydov {
56133144e84SVladimir Davydov #ifdef CONFIG_MEMCG
56233144e84SVladimir Davydov 	mm->owner = p;
56333144e84SVladimir Davydov #endif
56433144e84SVladimir Davydov }
56533144e84SVladimir Davydov 
56678fb7466SPavel Emelianov static struct mm_struct *mm_init(struct mm_struct *mm, struct task_struct *p)
5671da177e4SLinus Torvalds {
56841f727fdSVladimir Davydov 	mm->mmap = NULL;
56941f727fdSVladimir Davydov 	mm->mm_rb = RB_ROOT;
57041f727fdSVladimir Davydov 	mm->vmacache_seqnum = 0;
5711da177e4SLinus Torvalds 	atomic_set(&mm->mm_users, 1);
5721da177e4SLinus Torvalds 	atomic_set(&mm->mm_count, 1);
5731da177e4SLinus Torvalds 	init_rwsem(&mm->mmap_sem);
5741da177e4SLinus Torvalds 	INIT_LIST_HEAD(&mm->mmlist);
575999d9fc1SOleg Nesterov 	mm->core_state = NULL;
576e1f56c89SKirill A. Shutemov 	atomic_long_set(&mm->nr_ptes, 0);
5772d2f5119SKirill A. Shutemov 	mm_nr_pmds_init(mm);
57841f727fdSVladimir Davydov 	mm->map_count = 0;
57941f727fdSVladimir Davydov 	mm->locked_vm = 0;
580ce65cefaSVladimir Davydov 	mm->pinned_vm = 0;
581d559db08SKAMEZAWA Hiroyuki 	memset(&mm->rss_stat, 0, sizeof(mm->rss_stat));
5821da177e4SLinus Torvalds 	spin_lock_init(&mm->page_table_lock);
58341f727fdSVladimir Davydov 	mm_init_cpumask(mm);
584858f0993SAlexey Dobriyan 	mm_init_aio(mm);
585cf475ad2SBalbir Singh 	mm_init_owner(mm, p);
58641f727fdSVladimir Davydov 	mmu_notifier_mm_init(mm);
58720841405SRik van Riel 	clear_tlb_flush_pending(mm);
58841f727fdSVladimir Davydov #if defined(CONFIG_TRANSPARENT_HUGEPAGE) && !USE_SPLIT_PMD_PTLOCKS
58941f727fdSVladimir Davydov 	mm->pmd_huge_pte = NULL;
59041f727fdSVladimir Davydov #endif
5911da177e4SLinus Torvalds 
592a0715cc2SAlex Thorlton 	if (current->mm) {
593a0715cc2SAlex Thorlton 		mm->flags = current->mm->flags & MMF_INIT_MASK;
594a0715cc2SAlex Thorlton 		mm->def_flags = current->mm->def_flags & VM_INIT_DEF_MASK;
595a0715cc2SAlex Thorlton 	} else {
596a0715cc2SAlex Thorlton 		mm->flags = default_dump_filter;
5971da177e4SLinus Torvalds 		mm->def_flags = 0;
598a0715cc2SAlex Thorlton 	}
599a0715cc2SAlex Thorlton 
60041f727fdSVladimir Davydov 	if (mm_alloc_pgd(mm))
60141f727fdSVladimir Davydov 		goto fail_nopgd;
60278fb7466SPavel Emelianov 
60341f727fdSVladimir Davydov 	if (init_new_context(p, mm))
60441f727fdSVladimir Davydov 		goto fail_nocontext;
60541f727fdSVladimir Davydov 
60641f727fdSVladimir Davydov 	return mm;
60741f727fdSVladimir Davydov 
60841f727fdSVladimir Davydov fail_nocontext:
60941f727fdSVladimir Davydov 	mm_free_pgd(mm);
61041f727fdSVladimir Davydov fail_nopgd:
6111da177e4SLinus Torvalds 	free_mm(mm);
6121da177e4SLinus Torvalds 	return NULL;
6131da177e4SLinus Torvalds }
6141da177e4SLinus Torvalds 
615c3f0327fSKonstantin Khlebnikov static void check_mm(struct mm_struct *mm)
616c3f0327fSKonstantin Khlebnikov {
617c3f0327fSKonstantin Khlebnikov 	int i;
618c3f0327fSKonstantin Khlebnikov 
619c3f0327fSKonstantin Khlebnikov 	for (i = 0; i < NR_MM_COUNTERS; i++) {
620c3f0327fSKonstantin Khlebnikov 		long x = atomic_long_read(&mm->rss_stat.count[i]);
621c3f0327fSKonstantin Khlebnikov 
622c3f0327fSKonstantin Khlebnikov 		if (unlikely(x))
623c3f0327fSKonstantin Khlebnikov 			printk(KERN_ALERT "BUG: Bad rss-counter state "
624c3f0327fSKonstantin Khlebnikov 					  "mm:%p idx:%d val:%ld\n", mm, i, x);
625c3f0327fSKonstantin Khlebnikov 	}
626b30fe6c7SKirill A. Shutemov 
627b30fe6c7SKirill A. Shutemov 	if (atomic_long_read(&mm->nr_ptes))
628b30fe6c7SKirill A. Shutemov 		pr_alert("BUG: non-zero nr_ptes on freeing mm: %ld\n",
629b30fe6c7SKirill A. Shutemov 				atomic_long_read(&mm->nr_ptes));
630b30fe6c7SKirill A. Shutemov 	if (mm_nr_pmds(mm))
631b30fe6c7SKirill A. Shutemov 		pr_alert("BUG: non-zero nr_pmds on freeing mm: %ld\n",
632b30fe6c7SKirill A. Shutemov 				mm_nr_pmds(mm));
633b30fe6c7SKirill A. Shutemov 
634e009bb30SKirill A. Shutemov #if defined(CONFIG_TRANSPARENT_HUGEPAGE) && !USE_SPLIT_PMD_PTLOCKS
63596dad67fSSasha Levin 	VM_BUG_ON_MM(mm->pmd_huge_pte, mm);
636c3f0327fSKonstantin Khlebnikov #endif
637c3f0327fSKonstantin Khlebnikov }
638c3f0327fSKonstantin Khlebnikov 
6391da177e4SLinus Torvalds /*
6401da177e4SLinus Torvalds  * Allocate and initialize an mm_struct.
6411da177e4SLinus Torvalds  */
6421da177e4SLinus Torvalds struct mm_struct *mm_alloc(void)
6431da177e4SLinus Torvalds {
6441da177e4SLinus Torvalds 	struct mm_struct *mm;
6451da177e4SLinus Torvalds 
6461da177e4SLinus Torvalds 	mm = allocate_mm();
647de03c72cSKOSAKI Motohiro 	if (!mm)
648de03c72cSKOSAKI Motohiro 		return NULL;
649de03c72cSKOSAKI Motohiro 
6501da177e4SLinus Torvalds 	memset(mm, 0, sizeof(*mm));
6516345d24dSLinus Torvalds 	return mm_init(mm, current);
6521da177e4SLinus Torvalds }
6531da177e4SLinus Torvalds 
6541da177e4SLinus Torvalds /*
6551da177e4SLinus Torvalds  * Called when the last reference to the mm
6561da177e4SLinus Torvalds  * is dropped: either by a lazy thread or by
6571da177e4SLinus Torvalds  * mmput. Free the page directory and the mm.
6581da177e4SLinus Torvalds  */
6597ad5b3a5SHarvey Harrison void __mmdrop(struct mm_struct *mm)
6601da177e4SLinus Torvalds {
6611da177e4SLinus Torvalds 	BUG_ON(mm == &init_mm);
6621da177e4SLinus Torvalds 	mm_free_pgd(mm);
6631da177e4SLinus Torvalds 	destroy_context(mm);
664cddb8a5cSAndrea Arcangeli 	mmu_notifier_mm_destroy(mm);
665c3f0327fSKonstantin Khlebnikov 	check_mm(mm);
6661da177e4SLinus Torvalds 	free_mm(mm);
6671da177e4SLinus Torvalds }
6686d4e4c4fSAvi Kivity EXPORT_SYMBOL_GPL(__mmdrop);
6691da177e4SLinus Torvalds 
6701da177e4SLinus Torvalds /*
6711da177e4SLinus Torvalds  * Decrement the use count and release all resources for an mm.
6721da177e4SLinus Torvalds  */
6731da177e4SLinus Torvalds void mmput(struct mm_struct *mm)
6741da177e4SLinus Torvalds {
6750ae26f1bSAndrew Morton 	might_sleep();
6760ae26f1bSAndrew Morton 
6771da177e4SLinus Torvalds 	if (atomic_dec_and_test(&mm->mm_users)) {
678d4b3b638SSrikar Dronamraju 		uprobe_clear_state(mm);
6791da177e4SLinus Torvalds 		exit_aio(mm);
6801c2fb7a4SAndrea Arcangeli 		ksm_exit(mm);
681ba76149fSAndrea Arcangeli 		khugepaged_exit(mm); /* must run before exit_mmap */
6821da177e4SLinus Torvalds 		exit_mmap(mm);
683925d1c40SMatt Helsley 		set_mm_exe_file(mm, NULL);
6841da177e4SLinus Torvalds 		if (!list_empty(&mm->mmlist)) {
6851da177e4SLinus Torvalds 			spin_lock(&mmlist_lock);
6861da177e4SLinus Torvalds 			list_del(&mm->mmlist);
6871da177e4SLinus Torvalds 			spin_unlock(&mmlist_lock);
6881da177e4SLinus Torvalds 		}
689801460d0SHiroshi Shimamoto 		if (mm->binfmt)
690801460d0SHiroshi Shimamoto 			module_put(mm->binfmt->module);
6911da177e4SLinus Torvalds 		mmdrop(mm);
6921da177e4SLinus Torvalds 	}
6931da177e4SLinus Torvalds }
6941da177e4SLinus Torvalds EXPORT_SYMBOL_GPL(mmput);
6951da177e4SLinus Torvalds 
69638646013SJiri Slaby void set_mm_exe_file(struct mm_struct *mm, struct file *new_exe_file)
69738646013SJiri Slaby {
69838646013SJiri Slaby 	if (new_exe_file)
69938646013SJiri Slaby 		get_file(new_exe_file);
70038646013SJiri Slaby 	if (mm->exe_file)
70138646013SJiri Slaby 		fput(mm->exe_file);
70238646013SJiri Slaby 	mm->exe_file = new_exe_file;
70338646013SJiri Slaby }
70438646013SJiri Slaby 
70538646013SJiri Slaby struct file *get_mm_exe_file(struct mm_struct *mm)
70638646013SJiri Slaby {
70738646013SJiri Slaby 	struct file *exe_file;
70838646013SJiri Slaby 
7092dd8ad81SKonstantin Khlebnikov 	/* We need mmap_sem to protect against races with removal of exe_file */
71038646013SJiri Slaby 	down_read(&mm->mmap_sem);
71138646013SJiri Slaby 	exe_file = mm->exe_file;
71238646013SJiri Slaby 	if (exe_file)
71338646013SJiri Slaby 		get_file(exe_file);
71438646013SJiri Slaby 	up_read(&mm->mmap_sem);
71538646013SJiri Slaby 	return exe_file;
71638646013SJiri Slaby }
71738646013SJiri Slaby 
71838646013SJiri Slaby static void dup_mm_exe_file(struct mm_struct *oldmm, struct mm_struct *newmm)
71938646013SJiri Slaby {
72038646013SJiri Slaby 	/* It's safe to write the exe_file pointer without exe_file_lock because
72138646013SJiri Slaby 	 * this is called during fork when the task is not yet in /proc */
72238646013SJiri Slaby 	newmm->exe_file = get_mm_exe_file(oldmm);
72338646013SJiri Slaby }
72438646013SJiri Slaby 
7251da177e4SLinus Torvalds /**
7261da177e4SLinus Torvalds  * get_task_mm - acquire a reference to the task's mm
7271da177e4SLinus Torvalds  *
728246bb0b1SOleg Nesterov  * Returns %NULL if the task has no mm.  Checks PF_KTHREAD (meaning
7291da177e4SLinus Torvalds  * this kernel workthread has transiently adopted a user mm with use_mm,
7301da177e4SLinus Torvalds  * to do its AIO) is not set and if so returns a reference to it, after
7311da177e4SLinus Torvalds  * bumping up the use count.  User must release the mm via mmput()
7321da177e4SLinus Torvalds  * after use.  Typically used by /proc and ptrace.
7331da177e4SLinus Torvalds  */
7341da177e4SLinus Torvalds struct mm_struct *get_task_mm(struct task_struct *task)
7351da177e4SLinus Torvalds {
7361da177e4SLinus Torvalds 	struct mm_struct *mm;
7371da177e4SLinus Torvalds 
7381da177e4SLinus Torvalds 	task_lock(task);
7391da177e4SLinus Torvalds 	mm = task->mm;
7401da177e4SLinus Torvalds 	if (mm) {
741246bb0b1SOleg Nesterov 		if (task->flags & PF_KTHREAD)
7421da177e4SLinus Torvalds 			mm = NULL;
7431da177e4SLinus Torvalds 		else
7441da177e4SLinus Torvalds 			atomic_inc(&mm->mm_users);
7451da177e4SLinus Torvalds 	}
7461da177e4SLinus Torvalds 	task_unlock(task);
7471da177e4SLinus Torvalds 	return mm;
7481da177e4SLinus Torvalds }
7491da177e4SLinus Torvalds EXPORT_SYMBOL_GPL(get_task_mm);
7501da177e4SLinus Torvalds 
7518cdb878dSChristopher Yeoh struct mm_struct *mm_access(struct task_struct *task, unsigned int mode)
7528cdb878dSChristopher Yeoh {
7538cdb878dSChristopher Yeoh 	struct mm_struct *mm;
7548cdb878dSChristopher Yeoh 	int err;
7558cdb878dSChristopher Yeoh 
7568cdb878dSChristopher Yeoh 	err =  mutex_lock_killable(&task->signal->cred_guard_mutex);
7578cdb878dSChristopher Yeoh 	if (err)
7588cdb878dSChristopher Yeoh 		return ERR_PTR(err);
7598cdb878dSChristopher Yeoh 
7608cdb878dSChristopher Yeoh 	mm = get_task_mm(task);
7618cdb878dSChristopher Yeoh 	if (mm && mm != current->mm &&
7628cdb878dSChristopher Yeoh 			!ptrace_may_access(task, mode)) {
7638cdb878dSChristopher Yeoh 		mmput(mm);
7648cdb878dSChristopher Yeoh 		mm = ERR_PTR(-EACCES);
7658cdb878dSChristopher Yeoh 	}
7668cdb878dSChristopher Yeoh 	mutex_unlock(&task->signal->cred_guard_mutex);
7678cdb878dSChristopher Yeoh 
7688cdb878dSChristopher Yeoh 	return mm;
7698cdb878dSChristopher Yeoh }
7708cdb878dSChristopher Yeoh 
77157b59c4aSOleg Nesterov static void complete_vfork_done(struct task_struct *tsk)
772c415c3b4SOleg Nesterov {
773d68b46feSOleg Nesterov 	struct completion *vfork;
774c415c3b4SOleg Nesterov 
775d68b46feSOleg Nesterov 	task_lock(tsk);
776d68b46feSOleg Nesterov 	vfork = tsk->vfork_done;
777d68b46feSOleg Nesterov 	if (likely(vfork)) {
778c415c3b4SOleg Nesterov 		tsk->vfork_done = NULL;
779d68b46feSOleg Nesterov 		complete(vfork);
780d68b46feSOleg Nesterov 	}
781d68b46feSOleg Nesterov 	task_unlock(tsk);
782d68b46feSOleg Nesterov }
783d68b46feSOleg Nesterov 
784d68b46feSOleg Nesterov static int wait_for_vfork_done(struct task_struct *child,
785d68b46feSOleg Nesterov 				struct completion *vfork)
786d68b46feSOleg Nesterov {
787d68b46feSOleg Nesterov 	int killed;
788d68b46feSOleg Nesterov 
789d68b46feSOleg Nesterov 	freezer_do_not_count();
790d68b46feSOleg Nesterov 	killed = wait_for_completion_killable(vfork);
791d68b46feSOleg Nesterov 	freezer_count();
792d68b46feSOleg Nesterov 
793d68b46feSOleg Nesterov 	if (killed) {
794d68b46feSOleg Nesterov 		task_lock(child);
795d68b46feSOleg Nesterov 		child->vfork_done = NULL;
796d68b46feSOleg Nesterov 		task_unlock(child);
797d68b46feSOleg Nesterov 	}
798d68b46feSOleg Nesterov 
799d68b46feSOleg Nesterov 	put_task_struct(child);
800d68b46feSOleg Nesterov 	return killed;
801c415c3b4SOleg Nesterov }
802c415c3b4SOleg Nesterov 
8031da177e4SLinus Torvalds /* Please note the differences between mmput and mm_release.
8041da177e4SLinus Torvalds  * mmput is called whenever we stop holding onto a mm_struct,
8051da177e4SLinus Torvalds  * error success whatever.
8061da177e4SLinus Torvalds  *
8071da177e4SLinus Torvalds  * mm_release is called after a mm_struct has been removed
8081da177e4SLinus Torvalds  * from the current process.
8091da177e4SLinus Torvalds  *
8101da177e4SLinus Torvalds  * This difference is important for error handling, when we
8111da177e4SLinus Torvalds  * only half set up a mm_struct for a new process and need to restore
8121da177e4SLinus Torvalds  * the old one.  Because we mmput the new mm_struct before
8131da177e4SLinus Torvalds  * restoring the old one. . .
8141da177e4SLinus Torvalds  * Eric Biederman 10 January 1998
8151da177e4SLinus Torvalds  */
8161da177e4SLinus Torvalds void mm_release(struct task_struct *tsk, struct mm_struct *mm)
8171da177e4SLinus Torvalds {
8188141c7f3SLinus Torvalds 	/* Get rid of any futexes when releasing the mm */
8198141c7f3SLinus Torvalds #ifdef CONFIG_FUTEX
820fc6b177dSPeter Zijlstra 	if (unlikely(tsk->robust_list)) {
8218141c7f3SLinus Torvalds 		exit_robust_list(tsk);
822fc6b177dSPeter Zijlstra 		tsk->robust_list = NULL;
823fc6b177dSPeter Zijlstra 	}
8248141c7f3SLinus Torvalds #ifdef CONFIG_COMPAT
825fc6b177dSPeter Zijlstra 	if (unlikely(tsk->compat_robust_list)) {
8268141c7f3SLinus Torvalds 		compat_exit_robust_list(tsk);
827fc6b177dSPeter Zijlstra 		tsk->compat_robust_list = NULL;
828fc6b177dSPeter Zijlstra 	}
8298141c7f3SLinus Torvalds #endif
830322a2c10SThomas Gleixner 	if (unlikely(!list_empty(&tsk->pi_state_list)))
831322a2c10SThomas Gleixner 		exit_pi_state_list(tsk);
8328141c7f3SLinus Torvalds #endif
8338141c7f3SLinus Torvalds 
8340326f5a9SSrikar Dronamraju 	uprobe_free_utask(tsk);
8350326f5a9SSrikar Dronamraju 
8361da177e4SLinus Torvalds 	/* Get rid of any cached register state */
8371da177e4SLinus Torvalds 	deactivate_mm(tsk, mm);
8381da177e4SLinus Torvalds 
839fec1d011SRoland McGrath 	/*
840fec1d011SRoland McGrath 	 * If we're exiting normally, clear a user-space tid field if
841fec1d011SRoland McGrath 	 * requested.  We leave this alone when dying by signal, to leave
842fec1d011SRoland McGrath 	 * the value intact in a core dump, and to save the unnecessary
843d68b46feSOleg Nesterov 	 * trouble, say, a killed vfork parent shouldn't touch this mm.
844d68b46feSOleg Nesterov 	 * Userland only wants this done for a sys_exit.
845fec1d011SRoland McGrath 	 */
8469c8a8228SEric Dumazet 	if (tsk->clear_child_tid) {
8479c8a8228SEric Dumazet 		if (!(tsk->flags & PF_SIGNALED) &&
8489c8a8228SEric Dumazet 		    atomic_read(&mm->mm_users) > 1) {
8491da177e4SLinus Torvalds 			/*
8501da177e4SLinus Torvalds 			 * We don't check the error code - if userspace has
8511da177e4SLinus Torvalds 			 * not set up a proper pointer then tough luck.
8521da177e4SLinus Torvalds 			 */
8539c8a8228SEric Dumazet 			put_user(0, tsk->clear_child_tid);
8549c8a8228SEric Dumazet 			sys_futex(tsk->clear_child_tid, FUTEX_WAKE,
8559c8a8228SEric Dumazet 					1, NULL, NULL, 0);
8569c8a8228SEric Dumazet 		}
8579c8a8228SEric Dumazet 		tsk->clear_child_tid = NULL;
8581da177e4SLinus Torvalds 	}
859f7505d64SKonstantin Khlebnikov 
860f7505d64SKonstantin Khlebnikov 	/*
861f7505d64SKonstantin Khlebnikov 	 * All done, finally we can wake up parent and return this mm to him.
862f7505d64SKonstantin Khlebnikov 	 * Also kthread_stop() uses this completion for synchronization.
863f7505d64SKonstantin Khlebnikov 	 */
864f7505d64SKonstantin Khlebnikov 	if (tsk->vfork_done)
865f7505d64SKonstantin Khlebnikov 		complete_vfork_done(tsk);
8661da177e4SLinus Torvalds }
8671da177e4SLinus Torvalds 
868a0a7ec30SJANAK DESAI /*
869a0a7ec30SJANAK DESAI  * Allocate a new mm structure and copy contents from the
870a0a7ec30SJANAK DESAI  * mm structure of the passed in task structure.
871a0a7ec30SJANAK DESAI  */
872ff252c1fSDaeSeok Youn static struct mm_struct *dup_mm(struct task_struct *tsk)
873a0a7ec30SJANAK DESAI {
874a0a7ec30SJANAK DESAI 	struct mm_struct *mm, *oldmm = current->mm;
875a0a7ec30SJANAK DESAI 	int err;
876a0a7ec30SJANAK DESAI 
877a0a7ec30SJANAK DESAI 	mm = allocate_mm();
878a0a7ec30SJANAK DESAI 	if (!mm)
879a0a7ec30SJANAK DESAI 		goto fail_nomem;
880a0a7ec30SJANAK DESAI 
881a0a7ec30SJANAK DESAI 	memcpy(mm, oldmm, sizeof(*mm));
882a0a7ec30SJANAK DESAI 
88378fb7466SPavel Emelianov 	if (!mm_init(mm, tsk))
884a0a7ec30SJANAK DESAI 		goto fail_nomem;
885a0a7ec30SJANAK DESAI 
886925d1c40SMatt Helsley 	dup_mm_exe_file(oldmm, mm);
887925d1c40SMatt Helsley 
888a0a7ec30SJANAK DESAI 	err = dup_mmap(mm, oldmm);
889a0a7ec30SJANAK DESAI 	if (err)
890a0a7ec30SJANAK DESAI 		goto free_pt;
891a0a7ec30SJANAK DESAI 
892a0a7ec30SJANAK DESAI 	mm->hiwater_rss = get_mm_rss(mm);
893a0a7ec30SJANAK DESAI 	mm->hiwater_vm = mm->total_vm;
894a0a7ec30SJANAK DESAI 
895801460d0SHiroshi Shimamoto 	if (mm->binfmt && !try_module_get(mm->binfmt->module))
896801460d0SHiroshi Shimamoto 		goto free_pt;
897801460d0SHiroshi Shimamoto 
898a0a7ec30SJANAK DESAI 	return mm;
899a0a7ec30SJANAK DESAI 
900a0a7ec30SJANAK DESAI free_pt:
901801460d0SHiroshi Shimamoto 	/* don't put binfmt in mmput, we haven't got module yet */
902801460d0SHiroshi Shimamoto 	mm->binfmt = NULL;
903a0a7ec30SJANAK DESAI 	mmput(mm);
904a0a7ec30SJANAK DESAI 
905a0a7ec30SJANAK DESAI fail_nomem:
906a0a7ec30SJANAK DESAI 	return NULL;
907a0a7ec30SJANAK DESAI }
908a0a7ec30SJANAK DESAI 
9091da177e4SLinus Torvalds static int copy_mm(unsigned long clone_flags, struct task_struct *tsk)
9101da177e4SLinus Torvalds {
9111da177e4SLinus Torvalds 	struct mm_struct *mm, *oldmm;
9121da177e4SLinus Torvalds 	int retval;
9131da177e4SLinus Torvalds 
9141da177e4SLinus Torvalds 	tsk->min_flt = tsk->maj_flt = 0;
9151da177e4SLinus Torvalds 	tsk->nvcsw = tsk->nivcsw = 0;
91617406b82SMandeep Singh Baines #ifdef CONFIG_DETECT_HUNG_TASK
91717406b82SMandeep Singh Baines 	tsk->last_switch_count = tsk->nvcsw + tsk->nivcsw;
91817406b82SMandeep Singh Baines #endif
9191da177e4SLinus Torvalds 
9201da177e4SLinus Torvalds 	tsk->mm = NULL;
9211da177e4SLinus Torvalds 	tsk->active_mm = NULL;
9221da177e4SLinus Torvalds 
9231da177e4SLinus Torvalds 	/*
9241da177e4SLinus Torvalds 	 * Are we cloning a kernel thread?
9251da177e4SLinus Torvalds 	 *
9261da177e4SLinus Torvalds 	 * We need to steal a active VM for that..
9271da177e4SLinus Torvalds 	 */
9281da177e4SLinus Torvalds 	oldmm = current->mm;
9291da177e4SLinus Torvalds 	if (!oldmm)
9301da177e4SLinus Torvalds 		return 0;
9311da177e4SLinus Torvalds 
932615d6e87SDavidlohr Bueso 	/* initialize the new vmacache entries */
933615d6e87SDavidlohr Bueso 	vmacache_flush(tsk);
934615d6e87SDavidlohr Bueso 
9351da177e4SLinus Torvalds 	if (clone_flags & CLONE_VM) {
9361da177e4SLinus Torvalds 		atomic_inc(&oldmm->mm_users);
9371da177e4SLinus Torvalds 		mm = oldmm;
9381da177e4SLinus Torvalds 		goto good_mm;
9391da177e4SLinus Torvalds 	}
9401da177e4SLinus Torvalds 
9411da177e4SLinus Torvalds 	retval = -ENOMEM;
942a0a7ec30SJANAK DESAI 	mm = dup_mm(tsk);
9431da177e4SLinus Torvalds 	if (!mm)
9441da177e4SLinus Torvalds 		goto fail_nomem;
9451da177e4SLinus Torvalds 
9461da177e4SLinus Torvalds good_mm:
9471da177e4SLinus Torvalds 	tsk->mm = mm;
9481da177e4SLinus Torvalds 	tsk->active_mm = mm;
9491da177e4SLinus Torvalds 	return 0;
9501da177e4SLinus Torvalds 
9511da177e4SLinus Torvalds fail_nomem:
9521da177e4SLinus Torvalds 	return retval;
9531da177e4SLinus Torvalds }
9541da177e4SLinus Torvalds 
955a39bc516SAlexey Dobriyan static int copy_fs(unsigned long clone_flags, struct task_struct *tsk)
9561da177e4SLinus Torvalds {
957498052bbSAl Viro 	struct fs_struct *fs = current->fs;
9581da177e4SLinus Torvalds 	if (clone_flags & CLONE_FS) {
959498052bbSAl Viro 		/* tsk->fs is already what we want */
9602a4419b5SNick Piggin 		spin_lock(&fs->lock);
961498052bbSAl Viro 		if (fs->in_exec) {
9622a4419b5SNick Piggin 			spin_unlock(&fs->lock);
963498052bbSAl Viro 			return -EAGAIN;
964498052bbSAl Viro 		}
965498052bbSAl Viro 		fs->users++;
9662a4419b5SNick Piggin 		spin_unlock(&fs->lock);
9671da177e4SLinus Torvalds 		return 0;
9681da177e4SLinus Torvalds 	}
969498052bbSAl Viro 	tsk->fs = copy_fs_struct(fs);
9701da177e4SLinus Torvalds 	if (!tsk->fs)
9711da177e4SLinus Torvalds 		return -ENOMEM;
9721da177e4SLinus Torvalds 	return 0;
9731da177e4SLinus Torvalds }
9741da177e4SLinus Torvalds 
975a016f338SJANAK DESAI static int copy_files(unsigned long clone_flags, struct task_struct *tsk)
976a016f338SJANAK DESAI {
977a016f338SJANAK DESAI 	struct files_struct *oldf, *newf;
978a016f338SJANAK DESAI 	int error = 0;
979a016f338SJANAK DESAI 
980a016f338SJANAK DESAI 	/*
981a016f338SJANAK DESAI 	 * A background process may not have any files ...
982a016f338SJANAK DESAI 	 */
983a016f338SJANAK DESAI 	oldf = current->files;
984a016f338SJANAK DESAI 	if (!oldf)
985a016f338SJANAK DESAI 		goto out;
986a016f338SJANAK DESAI 
987a016f338SJANAK DESAI 	if (clone_flags & CLONE_FILES) {
988a016f338SJANAK DESAI 		atomic_inc(&oldf->count);
989a016f338SJANAK DESAI 		goto out;
990a016f338SJANAK DESAI 	}
991a016f338SJANAK DESAI 
992a016f338SJANAK DESAI 	newf = dup_fd(oldf, &error);
993a016f338SJANAK DESAI 	if (!newf)
994a016f338SJANAK DESAI 		goto out;
995a016f338SJANAK DESAI 
996a016f338SJANAK DESAI 	tsk->files = newf;
997a016f338SJANAK DESAI 	error = 0;
998a016f338SJANAK DESAI out:
999a016f338SJANAK DESAI 	return error;
1000a016f338SJANAK DESAI }
1001a016f338SJANAK DESAI 
1002fadad878SJens Axboe static int copy_io(unsigned long clone_flags, struct task_struct *tsk)
1003fd0928dfSJens Axboe {
1004fd0928dfSJens Axboe #ifdef CONFIG_BLOCK
1005fd0928dfSJens Axboe 	struct io_context *ioc = current->io_context;
10066e736be7STejun Heo 	struct io_context *new_ioc;
1007fd0928dfSJens Axboe 
1008fd0928dfSJens Axboe 	if (!ioc)
1009fd0928dfSJens Axboe 		return 0;
1010fadad878SJens Axboe 	/*
1011fadad878SJens Axboe 	 * Share io context with parent, if CLONE_IO is set
1012fadad878SJens Axboe 	 */
1013fadad878SJens Axboe 	if (clone_flags & CLONE_IO) {
10143d48749dSTejun Heo 		ioc_task_link(ioc);
10153d48749dSTejun Heo 		tsk->io_context = ioc;
1016fadad878SJens Axboe 	} else if (ioprio_valid(ioc->ioprio)) {
10176e736be7STejun Heo 		new_ioc = get_task_io_context(tsk, GFP_KERNEL, NUMA_NO_NODE);
10186e736be7STejun Heo 		if (unlikely(!new_ioc))
1019fd0928dfSJens Axboe 			return -ENOMEM;
1020fd0928dfSJens Axboe 
10216e736be7STejun Heo 		new_ioc->ioprio = ioc->ioprio;
102211a3122fSTejun Heo 		put_io_context(new_ioc);
1023fd0928dfSJens Axboe 	}
1024fd0928dfSJens Axboe #endif
1025fd0928dfSJens Axboe 	return 0;
1026fd0928dfSJens Axboe }
1027fd0928dfSJens Axboe 
1028a39bc516SAlexey Dobriyan static int copy_sighand(unsigned long clone_flags, struct task_struct *tsk)
10291da177e4SLinus Torvalds {
10301da177e4SLinus Torvalds 	struct sighand_struct *sig;
10311da177e4SLinus Torvalds 
103260348802SZhaolei 	if (clone_flags & CLONE_SIGHAND) {
10331da177e4SLinus Torvalds 		atomic_inc(&current->sighand->count);
10341da177e4SLinus Torvalds 		return 0;
10351da177e4SLinus Torvalds 	}
10361da177e4SLinus Torvalds 	sig = kmem_cache_alloc(sighand_cachep, GFP_KERNEL);
1037e56d0903SIngo Molnar 	rcu_assign_pointer(tsk->sighand, sig);
10381da177e4SLinus Torvalds 	if (!sig)
10391da177e4SLinus Torvalds 		return -ENOMEM;
10401da177e4SLinus Torvalds 	atomic_set(&sig->count, 1);
10411da177e4SLinus Torvalds 	memcpy(sig->action, current->sighand->action, sizeof(sig->action));
10421da177e4SLinus Torvalds 	return 0;
10431da177e4SLinus Torvalds }
10441da177e4SLinus Torvalds 
1045a7e5328aSOleg Nesterov void __cleanup_sighand(struct sighand_struct *sighand)
1046c81addc9SOleg Nesterov {
1047d80e731eSOleg Nesterov 	if (atomic_dec_and_test(&sighand->count)) {
1048d80e731eSOleg Nesterov 		signalfd_cleanup(sighand);
1049392809b2SOleg Nesterov 		/*
1050392809b2SOleg Nesterov 		 * sighand_cachep is SLAB_DESTROY_BY_RCU so we can free it
1051392809b2SOleg Nesterov 		 * without an RCU grace period, see __lock_task_sighand().
1052392809b2SOleg Nesterov 		 */
1053c81addc9SOleg Nesterov 		kmem_cache_free(sighand_cachep, sighand);
1054c81addc9SOleg Nesterov 	}
1055d80e731eSOleg Nesterov }
1056c81addc9SOleg Nesterov 
1057f06febc9SFrank Mayhar /*
1058f06febc9SFrank Mayhar  * Initialize POSIX timer handling for a thread group.
1059f06febc9SFrank Mayhar  */
1060f06febc9SFrank Mayhar static void posix_cpu_timers_init_group(struct signal_struct *sig)
1061f06febc9SFrank Mayhar {
106278d7d407SJiri Slaby 	unsigned long cpu_limit;
106378d7d407SJiri Slaby 
1064f06febc9SFrank Mayhar 	/* Thread group counters. */
1065f06febc9SFrank Mayhar 	thread_group_cputime_init(sig);
1066f06febc9SFrank Mayhar 
106778d7d407SJiri Slaby 	cpu_limit = ACCESS_ONCE(sig->rlim[RLIMIT_CPU].rlim_cur);
106878d7d407SJiri Slaby 	if (cpu_limit != RLIM_INFINITY) {
106978d7d407SJiri Slaby 		sig->cputime_expires.prof_exp = secs_to_cputime(cpu_limit);
10706279a751SOleg Nesterov 		sig->cputimer.running = 1;
10716279a751SOleg Nesterov 	}
10726279a751SOleg Nesterov 
1073f06febc9SFrank Mayhar 	/* The timer lists. */
1074f06febc9SFrank Mayhar 	INIT_LIST_HEAD(&sig->cpu_timers[0]);
1075f06febc9SFrank Mayhar 	INIT_LIST_HEAD(&sig->cpu_timers[1]);
1076f06febc9SFrank Mayhar 	INIT_LIST_HEAD(&sig->cpu_timers[2]);
1077f06febc9SFrank Mayhar }
1078f06febc9SFrank Mayhar 
1079a39bc516SAlexey Dobriyan static int copy_signal(unsigned long clone_flags, struct task_struct *tsk)
10801da177e4SLinus Torvalds {
10811da177e4SLinus Torvalds 	struct signal_struct *sig;
10821da177e4SLinus Torvalds 
10834ab6c083SOleg Nesterov 	if (clone_flags & CLONE_THREAD)
1084490dea45SPeter Zijlstra 		return 0;
10856279a751SOleg Nesterov 
1086a56704efSVeaceslav Falico 	sig = kmem_cache_zalloc(signal_cachep, GFP_KERNEL);
10871da177e4SLinus Torvalds 	tsk->signal = sig;
10881da177e4SLinus Torvalds 	if (!sig)
10891da177e4SLinus Torvalds 		return -ENOMEM;
10901da177e4SLinus Torvalds 
1091b3ac022cSOleg Nesterov 	sig->nr_threads = 1;
10921da177e4SLinus Torvalds 	atomic_set(&sig->live, 1);
1093b3ac022cSOleg Nesterov 	atomic_set(&sig->sigcnt, 1);
10940c740d0aSOleg Nesterov 
10950c740d0aSOleg Nesterov 	/* list_add(thread_node, thread_head) without INIT_LIST_HEAD() */
10960c740d0aSOleg Nesterov 	sig->thread_head = (struct list_head)LIST_HEAD_INIT(tsk->thread_node);
10970c740d0aSOleg Nesterov 	tsk->thread_node = (struct list_head)LIST_HEAD_INIT(sig->thread_head);
10980c740d0aSOleg Nesterov 
10991da177e4SLinus Torvalds 	init_waitqueue_head(&sig->wait_chldexit);
1100db51aeccSOleg Nesterov 	sig->curr_target = tsk;
11011da177e4SLinus Torvalds 	init_sigpending(&sig->shared_pending);
11021da177e4SLinus Torvalds 	INIT_LIST_HEAD(&sig->posix_timers);
1103e78c3496SRik van Riel 	seqlock_init(&sig->stats_lock);
11041da177e4SLinus Torvalds 
1105c9cb2e3dSThomas Gleixner 	hrtimer_init(&sig->real_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
11061da177e4SLinus Torvalds 	sig->real_timer.function = it_real_fn;
11071da177e4SLinus Torvalds 
11081da177e4SLinus Torvalds 	task_lock(current->group_leader);
11091da177e4SLinus Torvalds 	memcpy(sig->rlim, current->signal->rlim, sizeof sig->rlim);
11101da177e4SLinus Torvalds 	task_unlock(current->group_leader);
11111da177e4SLinus Torvalds 
11126279a751SOleg Nesterov 	posix_cpu_timers_init_group(sig);
11136279a751SOleg Nesterov 
1114522ed776SMiloslav Trmac 	tty_audit_fork(sig);
11155091faa4SMike Galbraith 	sched_autogroup_fork(sig);
1116522ed776SMiloslav Trmac 
11174714d1d3SBen Blum #ifdef CONFIG_CGROUPS
1118257058aeSTejun Heo 	init_rwsem(&sig->group_rwsem);
11194714d1d3SBen Blum #endif
11204714d1d3SBen Blum 
1121a63d83f4SDavid Rientjes 	sig->oom_score_adj = current->signal->oom_score_adj;
1122dabb16f6SMandeep Singh Baines 	sig->oom_score_adj_min = current->signal->oom_score_adj_min;
112328b83c51SKOSAKI Motohiro 
1124ebec18a6SLennart Poettering 	sig->has_child_subreaper = current->signal->has_child_subreaper ||
1125ebec18a6SLennart Poettering 				   current->signal->is_child_subreaper;
1126ebec18a6SLennart Poettering 
11279b1bf12dSKOSAKI Motohiro 	mutex_init(&sig->cred_guard_mutex);
11289b1bf12dSKOSAKI Motohiro 
11291da177e4SLinus Torvalds 	return 0;
11301da177e4SLinus Torvalds }
11311da177e4SLinus Torvalds 
1132dbd95212SKees Cook static void copy_seccomp(struct task_struct *p)
1133dbd95212SKees Cook {
1134dbd95212SKees Cook #ifdef CONFIG_SECCOMP
1135dbd95212SKees Cook 	/*
1136dbd95212SKees Cook 	 * Must be called with sighand->lock held, which is common to
1137dbd95212SKees Cook 	 * all threads in the group. Holding cred_guard_mutex is not
1138dbd95212SKees Cook 	 * needed because this new task is not yet running and cannot
1139dbd95212SKees Cook 	 * be racing exec.
1140dbd95212SKees Cook 	 */
114169f6a34bSGuenter Roeck 	assert_spin_locked(&current->sighand->siglock);
1142dbd95212SKees Cook 
1143dbd95212SKees Cook 	/* Ref-count the new filter user, and assign it. */
1144dbd95212SKees Cook 	get_seccomp_filter(current);
1145dbd95212SKees Cook 	p->seccomp = current->seccomp;
1146dbd95212SKees Cook 
1147dbd95212SKees Cook 	/*
1148dbd95212SKees Cook 	 * Explicitly enable no_new_privs here in case it got set
1149dbd95212SKees Cook 	 * between the task_struct being duplicated and holding the
1150dbd95212SKees Cook 	 * sighand lock. The seccomp state and nnp must be in sync.
1151dbd95212SKees Cook 	 */
1152dbd95212SKees Cook 	if (task_no_new_privs(current))
1153dbd95212SKees Cook 		task_set_no_new_privs(p);
1154dbd95212SKees Cook 
1155dbd95212SKees Cook 	/*
1156dbd95212SKees Cook 	 * If the parent gained a seccomp mode after copying thread
1157dbd95212SKees Cook 	 * flags and between before we held the sighand lock, we have
1158dbd95212SKees Cook 	 * to manually enable the seccomp thread flag here.
1159dbd95212SKees Cook 	 */
1160dbd95212SKees Cook 	if (p->seccomp.mode != SECCOMP_MODE_DISABLED)
1161dbd95212SKees Cook 		set_tsk_thread_flag(p, TIF_SECCOMP);
1162dbd95212SKees Cook #endif
1163dbd95212SKees Cook }
1164dbd95212SKees Cook 
116517da2bd9SHeiko Carstens SYSCALL_DEFINE1(set_tid_address, int __user *, tidptr)
11661da177e4SLinus Torvalds {
11671da177e4SLinus Torvalds 	current->clear_child_tid = tidptr;
11681da177e4SLinus Torvalds 
1169b488893aSPavel Emelyanov 	return task_pid_vnr(current);
11701da177e4SLinus Torvalds }
11711da177e4SLinus Torvalds 
1172a39bc516SAlexey Dobriyan static void rt_mutex_init_task(struct task_struct *p)
117323f78d4aSIngo Molnar {
11741d615482SThomas Gleixner 	raw_spin_lock_init(&p->pi_lock);
1175e29e175bSZilvinas Valinskas #ifdef CONFIG_RT_MUTEXES
1176fb00aca4SPeter Zijlstra 	p->pi_waiters = RB_ROOT;
1177fb00aca4SPeter Zijlstra 	p->pi_waiters_leftmost = NULL;
117823f78d4aSIngo Molnar 	p->pi_blocked_on = NULL;
117923f78d4aSIngo Molnar #endif
118023f78d4aSIngo Molnar }
118123f78d4aSIngo Molnar 
11821da177e4SLinus Torvalds /*
1183f06febc9SFrank Mayhar  * Initialize POSIX timer handling for a single task.
1184f06febc9SFrank Mayhar  */
1185f06febc9SFrank Mayhar static void posix_cpu_timers_init(struct task_struct *tsk)
1186f06febc9SFrank Mayhar {
118764861634SMartin Schwidefsky 	tsk->cputime_expires.prof_exp = 0;
118864861634SMartin Schwidefsky 	tsk->cputime_expires.virt_exp = 0;
1189f06febc9SFrank Mayhar 	tsk->cputime_expires.sched_exp = 0;
1190f06febc9SFrank Mayhar 	INIT_LIST_HEAD(&tsk->cpu_timers[0]);
1191f06febc9SFrank Mayhar 	INIT_LIST_HEAD(&tsk->cpu_timers[1]);
1192f06febc9SFrank Mayhar 	INIT_LIST_HEAD(&tsk->cpu_timers[2]);
1193f06febc9SFrank Mayhar }
1194f06febc9SFrank Mayhar 
119581907739SOleg Nesterov static inline void
119681907739SOleg Nesterov init_task_pid(struct task_struct *task, enum pid_type type, struct pid *pid)
119781907739SOleg Nesterov {
119881907739SOleg Nesterov 	 task->pids[type].pid = pid;
119981907739SOleg Nesterov }
120081907739SOleg Nesterov 
1201f06febc9SFrank Mayhar /*
12021da177e4SLinus Torvalds  * This creates a new process as a copy of the old one,
12031da177e4SLinus Torvalds  * but does not actually start it yet.
12041da177e4SLinus Torvalds  *
12051da177e4SLinus Torvalds  * It copies the registers, and all the appropriate
12061da177e4SLinus Torvalds  * parts of the process environment (as per the clone
12071da177e4SLinus Torvalds  * flags). The actual kick-off is left to the caller.
12081da177e4SLinus Torvalds  */
120936c8b586SIngo Molnar static struct task_struct *copy_process(unsigned long clone_flags,
12101da177e4SLinus Torvalds 					unsigned long stack_start,
12111da177e4SLinus Torvalds 					unsigned long stack_size,
12121da177e4SLinus Torvalds 					int __user *child_tidptr,
121309a05394SRoland McGrath 					struct pid *pid,
121409a05394SRoland McGrath 					int trace)
12151da177e4SLinus Torvalds {
12161da177e4SLinus Torvalds 	int retval;
1217a24efe62SMariusz Kozlowski 	struct task_struct *p;
12181da177e4SLinus Torvalds 
12191da177e4SLinus Torvalds 	if ((clone_flags & (CLONE_NEWNS|CLONE_FS)) == (CLONE_NEWNS|CLONE_FS))
12201da177e4SLinus Torvalds 		return ERR_PTR(-EINVAL);
12211da177e4SLinus Torvalds 
1222e66eded8SEric W. Biederman 	if ((clone_flags & (CLONE_NEWUSER|CLONE_FS)) == (CLONE_NEWUSER|CLONE_FS))
1223e66eded8SEric W. Biederman 		return ERR_PTR(-EINVAL);
1224e66eded8SEric W. Biederman 
12251da177e4SLinus Torvalds 	/*
12261da177e4SLinus Torvalds 	 * Thread groups must share signals as well, and detached threads
12271da177e4SLinus Torvalds 	 * can only be started up within the thread group.
12281da177e4SLinus Torvalds 	 */
12291da177e4SLinus Torvalds 	if ((clone_flags & CLONE_THREAD) && !(clone_flags & CLONE_SIGHAND))
12301da177e4SLinus Torvalds 		return ERR_PTR(-EINVAL);
12311da177e4SLinus Torvalds 
12321da177e4SLinus Torvalds 	/*
12331da177e4SLinus Torvalds 	 * Shared signal handlers imply shared VM. By way of the above,
12341da177e4SLinus Torvalds 	 * thread groups also imply shared VM. Blocking this case allows
12351da177e4SLinus Torvalds 	 * for various simplifications in other code.
12361da177e4SLinus Torvalds 	 */
12371da177e4SLinus Torvalds 	if ((clone_flags & CLONE_SIGHAND) && !(clone_flags & CLONE_VM))
12381da177e4SLinus Torvalds 		return ERR_PTR(-EINVAL);
12391da177e4SLinus Torvalds 
1240123be07bSSukadev Bhattiprolu 	/*
1241123be07bSSukadev Bhattiprolu 	 * Siblings of global init remain as zombies on exit since they are
1242123be07bSSukadev Bhattiprolu 	 * not reaped by their parent (swapper). To solve this and to avoid
1243123be07bSSukadev Bhattiprolu 	 * multi-rooted process trees, prevent global and container-inits
1244123be07bSSukadev Bhattiprolu 	 * from creating siblings.
1245123be07bSSukadev Bhattiprolu 	 */
1246123be07bSSukadev Bhattiprolu 	if ((clone_flags & CLONE_PARENT) &&
1247123be07bSSukadev Bhattiprolu 				current->signal->flags & SIGNAL_UNKILLABLE)
1248123be07bSSukadev Bhattiprolu 		return ERR_PTR(-EINVAL);
1249123be07bSSukadev Bhattiprolu 
12508382fcacSEric W. Biederman 	/*
125140a0d32dSOleg Nesterov 	 * If the new process will be in a different pid or user namespace
125240a0d32dSOleg Nesterov 	 * do not allow it to share a thread group or signal handlers or
125340a0d32dSOleg Nesterov 	 * parent with the forking task.
12548382fcacSEric W. Biederman 	 */
12551f7f4ddeSEric W. Biederman 	if (clone_flags & CLONE_SIGHAND) {
125640a0d32dSOleg Nesterov 		if ((clone_flags & (CLONE_NEWUSER | CLONE_NEWPID)) ||
125740a0d32dSOleg Nesterov 		    (task_active_pid_ns(current) !=
1258c2b1df2eSAndy Lutomirski 				current->nsproxy->pid_ns_for_children))
12598382fcacSEric W. Biederman 			return ERR_PTR(-EINVAL);
126040a0d32dSOleg Nesterov 	}
12618382fcacSEric W. Biederman 
12621da177e4SLinus Torvalds 	retval = security_task_create(clone_flags);
12631da177e4SLinus Torvalds 	if (retval)
12641da177e4SLinus Torvalds 		goto fork_out;
12651da177e4SLinus Torvalds 
12661da177e4SLinus Torvalds 	retval = -ENOMEM;
12671da177e4SLinus Torvalds 	p = dup_task_struct(current);
12681da177e4SLinus Torvalds 	if (!p)
12691da177e4SLinus Torvalds 		goto fork_out;
12701da177e4SLinus Torvalds 
1271f7e8b616SSteven Rostedt 	ftrace_graph_init_task(p);
1272f7e8b616SSteven Rostedt 
1273bea493a0SPeter Zijlstra 	rt_mutex_init_task(p);
1274bea493a0SPeter Zijlstra 
1275d12c1a37SIngo Molnar #ifdef CONFIG_PROVE_LOCKING
1276de30a2b3SIngo Molnar 	DEBUG_LOCKS_WARN_ON(!p->hardirqs_enabled);
1277de30a2b3SIngo Molnar 	DEBUG_LOCKS_WARN_ON(!p->softirqs_enabled);
1278de30a2b3SIngo Molnar #endif
12791da177e4SLinus Torvalds 	retval = -EAGAIN;
12803b11a1deSDavid Howells 	if (atomic_read(&p->real_cred->user->processes) >=
128178d7d407SJiri Slaby 			task_rlimit(p, RLIMIT_NPROC)) {
1282b57922b6SEric Paris 		if (p->real_cred->user != INIT_USER &&
1283b57922b6SEric Paris 		    !capable(CAP_SYS_RESOURCE) && !capable(CAP_SYS_ADMIN))
12841da177e4SLinus Torvalds 			goto bad_fork_free;
12851da177e4SLinus Torvalds 	}
128672fa5997SVasiliy Kulikov 	current->flags &= ~PF_NPROC_EXCEEDED;
12871da177e4SLinus Torvalds 
1288f1752eecSDavid Howells 	retval = copy_creds(p, clone_flags);
1289f1752eecSDavid Howells 	if (retval < 0)
1290f1752eecSDavid Howells 		goto bad_fork_free;
12911da177e4SLinus Torvalds 
12921da177e4SLinus Torvalds 	/*
12931da177e4SLinus Torvalds 	 * If multiple threads are within copy_process(), then this check
12941da177e4SLinus Torvalds 	 * triggers too late. This doesn't hurt, the check is only there
12951da177e4SLinus Torvalds 	 * to stop root fork bombs.
12961da177e4SLinus Torvalds 	 */
129704ec93feSLi Zefan 	retval = -EAGAIN;
12981da177e4SLinus Torvalds 	if (nr_threads >= max_threads)
12991da177e4SLinus Torvalds 		goto bad_fork_cleanup_count;
13001da177e4SLinus Torvalds 
1301ca74e92bSShailabh Nagar 	delayacct_tsk_init(p);	/* Must remain after dup_task_struct() */
1302514ddb44SDavid Rientjes 	p->flags &= ~(PF_SUPERPRIV | PF_WQ_WORKER);
1303514ddb44SDavid Rientjes 	p->flags |= PF_FORKNOEXEC;
13041da177e4SLinus Torvalds 	INIT_LIST_HEAD(&p->children);
13051da177e4SLinus Torvalds 	INIT_LIST_HEAD(&p->sibling);
1306f41d911fSPaul E. McKenney 	rcu_copy_process(p);
13071da177e4SLinus Torvalds 	p->vfork_done = NULL;
13081da177e4SLinus Torvalds 	spin_lock_init(&p->alloc_lock);
13091da177e4SLinus Torvalds 
13101da177e4SLinus Torvalds 	init_sigpending(&p->pending);
13111da177e4SLinus Torvalds 
131264861634SMartin Schwidefsky 	p->utime = p->stime = p->gtime = 0;
131364861634SMartin Schwidefsky 	p->utimescaled = p->stimescaled = 0;
13149fbc42eaSFrederic Weisbecker #ifndef CONFIG_VIRT_CPU_ACCOUNTING_NATIVE
1315d37f761dSFrederic Weisbecker 	p->prev_cputime.utime = p->prev_cputime.stime = 0;
1316d99ca3b9SHidetoshi Seto #endif
13176a61671bSFrederic Weisbecker #ifdef CONFIG_VIRT_CPU_ACCOUNTING_GEN
13186a61671bSFrederic Weisbecker 	seqlock_init(&p->vtime_seqlock);
13196a61671bSFrederic Weisbecker 	p->vtime_snap = 0;
13206a61671bSFrederic Weisbecker 	p->vtime_snap_whence = VTIME_SLEEPING;
13216a61671bSFrederic Weisbecker #endif
13226a61671bSFrederic Weisbecker 
1323a3a2e76cSKAMEZAWA Hiroyuki #if defined(SPLIT_RSS_COUNTING)
1324a3a2e76cSKAMEZAWA Hiroyuki 	memset(&p->rss_stat, 0, sizeof(p->rss_stat));
1325a3a2e76cSKAMEZAWA Hiroyuki #endif
1326172ba844SBalbir Singh 
13276976675dSArjan van de Ven 	p->default_timer_slack_ns = current->timer_slack_ns;
13286976675dSArjan van de Ven 
13295995477aSAndrea Righi 	task_io_accounting_init(&p->ioac);
13301da177e4SLinus Torvalds 	acct_clear_integrals(p);
13311da177e4SLinus Torvalds 
1332f06febc9SFrank Mayhar 	posix_cpu_timers_init(p);
13331da177e4SLinus Torvalds 
1334ccbf62d8SThomas Gleixner 	p->start_time = ktime_get_ns();
133557e0be04SThomas Gleixner 	p->real_start_time = ktime_get_boot_ns();
13361da177e4SLinus Torvalds 	p->io_context = NULL;
13371da177e4SLinus Torvalds 	p->audit_context = NULL;
13384714d1d3SBen Blum 	if (clone_flags & CLONE_THREAD)
1339257058aeSTejun Heo 		threadgroup_change_begin(current);
1340b4f48b63SPaul Menage 	cgroup_fork(p);
13411da177e4SLinus Torvalds #ifdef CONFIG_NUMA
1342846a16bfSLee Schermerhorn 	p->mempolicy = mpol_dup(p->mempolicy);
13431da177e4SLinus Torvalds 	if (IS_ERR(p->mempolicy)) {
13441da177e4SLinus Torvalds 		retval = PTR_ERR(p->mempolicy);
13451da177e4SLinus Torvalds 		p->mempolicy = NULL;
1346e8604cb4SLi Zefan 		goto bad_fork_cleanup_threadgroup_lock;
13471da177e4SLinus Torvalds 	}
13481da177e4SLinus Torvalds #endif
1349778d3b0fSMichal Hocko #ifdef CONFIG_CPUSETS
1350778d3b0fSMichal Hocko 	p->cpuset_mem_spread_rotor = NUMA_NO_NODE;
1351778d3b0fSMichal Hocko 	p->cpuset_slab_spread_rotor = NUMA_NO_NODE;
1352cc9a6c87SMel Gorman 	seqcount_init(&p->mems_allowed_seq);
1353778d3b0fSMichal Hocko #endif
1354de30a2b3SIngo Molnar #ifdef CONFIG_TRACE_IRQFLAGS
1355de30a2b3SIngo Molnar 	p->irq_events = 0;
1356de30a2b3SIngo Molnar 	p->hardirqs_enabled = 0;
1357de30a2b3SIngo Molnar 	p->hardirq_enable_ip = 0;
1358de30a2b3SIngo Molnar 	p->hardirq_enable_event = 0;
1359de30a2b3SIngo Molnar 	p->hardirq_disable_ip = _THIS_IP_;
1360de30a2b3SIngo Molnar 	p->hardirq_disable_event = 0;
1361de30a2b3SIngo Molnar 	p->softirqs_enabled = 1;
1362de30a2b3SIngo Molnar 	p->softirq_enable_ip = _THIS_IP_;
1363de30a2b3SIngo Molnar 	p->softirq_enable_event = 0;
1364de30a2b3SIngo Molnar 	p->softirq_disable_ip = 0;
1365de30a2b3SIngo Molnar 	p->softirq_disable_event = 0;
1366de30a2b3SIngo Molnar 	p->hardirq_context = 0;
1367de30a2b3SIngo Molnar 	p->softirq_context = 0;
1368de30a2b3SIngo Molnar #endif
1369fbb9ce95SIngo Molnar #ifdef CONFIG_LOCKDEP
1370fbb9ce95SIngo Molnar 	p->lockdep_depth = 0; /* no locks held yet */
1371fbb9ce95SIngo Molnar 	p->curr_chain_key = 0;
1372fbb9ce95SIngo Molnar 	p->lockdep_recursion = 0;
1373fbb9ce95SIngo Molnar #endif
13741da177e4SLinus Torvalds 
1375408894eeSIngo Molnar #ifdef CONFIG_DEBUG_MUTEXES
1376408894eeSIngo Molnar 	p->blocked_on = NULL; /* not blocked yet */
1377408894eeSIngo Molnar #endif
1378cafe5635SKent Overstreet #ifdef CONFIG_BCACHE
1379cafe5635SKent Overstreet 	p->sequential_io	= 0;
1380cafe5635SKent Overstreet 	p->sequential_io_avg	= 0;
1381cafe5635SKent Overstreet #endif
13820f481406SMarkus Metzger 
13833c90e6e9SSrivatsa Vaddagiri 	/* Perform scheduler related setup. Assign this task to a CPU. */
1384aab03e05SDario Faggioli 	retval = sched_fork(clone_flags, p);
1385aab03e05SDario Faggioli 	if (retval)
1386aab03e05SDario Faggioli 		goto bad_fork_cleanup_policy;
13876ab423e0SPeter Zijlstra 
1388cdd6c482SIngo Molnar 	retval = perf_event_init_task(p);
13896ab423e0SPeter Zijlstra 	if (retval)
13906ab423e0SPeter Zijlstra 		goto bad_fork_cleanup_policy;
1391fb0a685cSDaniel Rebelo de Oliveira 	retval = audit_alloc(p);
1392fb0a685cSDaniel Rebelo de Oliveira 	if (retval)
13936c72e350SPeter Zijlstra 		goto bad_fork_cleanup_perf;
13941da177e4SLinus Torvalds 	/* copy all the process information */
1395ab602f79SJack Miller 	shm_init_task(p);
1396fb0a685cSDaniel Rebelo de Oliveira 	retval = copy_semundo(clone_flags, p);
1397fb0a685cSDaniel Rebelo de Oliveira 	if (retval)
13981da177e4SLinus Torvalds 		goto bad_fork_cleanup_audit;
1399fb0a685cSDaniel Rebelo de Oliveira 	retval = copy_files(clone_flags, p);
1400fb0a685cSDaniel Rebelo de Oliveira 	if (retval)
14011da177e4SLinus Torvalds 		goto bad_fork_cleanup_semundo;
1402fb0a685cSDaniel Rebelo de Oliveira 	retval = copy_fs(clone_flags, p);
1403fb0a685cSDaniel Rebelo de Oliveira 	if (retval)
14041da177e4SLinus Torvalds 		goto bad_fork_cleanup_files;
1405fb0a685cSDaniel Rebelo de Oliveira 	retval = copy_sighand(clone_flags, p);
1406fb0a685cSDaniel Rebelo de Oliveira 	if (retval)
14071da177e4SLinus Torvalds 		goto bad_fork_cleanup_fs;
1408fb0a685cSDaniel Rebelo de Oliveira 	retval = copy_signal(clone_flags, p);
1409fb0a685cSDaniel Rebelo de Oliveira 	if (retval)
14101da177e4SLinus Torvalds 		goto bad_fork_cleanup_sighand;
1411fb0a685cSDaniel Rebelo de Oliveira 	retval = copy_mm(clone_flags, p);
1412fb0a685cSDaniel Rebelo de Oliveira 	if (retval)
14131da177e4SLinus Torvalds 		goto bad_fork_cleanup_signal;
1414fb0a685cSDaniel Rebelo de Oliveira 	retval = copy_namespaces(clone_flags, p);
1415fb0a685cSDaniel Rebelo de Oliveira 	if (retval)
1416d84f4f99SDavid Howells 		goto bad_fork_cleanup_mm;
1417fb0a685cSDaniel Rebelo de Oliveira 	retval = copy_io(clone_flags, p);
1418fb0a685cSDaniel Rebelo de Oliveira 	if (retval)
1419fd0928dfSJens Axboe 		goto bad_fork_cleanup_namespaces;
1420afa86fc4SAl Viro 	retval = copy_thread(clone_flags, stack_start, stack_size, p);
14211da177e4SLinus Torvalds 	if (retval)
1422fd0928dfSJens Axboe 		goto bad_fork_cleanup_io;
14231da177e4SLinus Torvalds 
1424425fb2b4SPavel Emelyanov 	if (pid != &init_struct_pid) {
1425c2b1df2eSAndy Lutomirski 		pid = alloc_pid(p->nsproxy->pid_ns_for_children);
142635f71bc0SMichal Hocko 		if (IS_ERR(pid)) {
142735f71bc0SMichal Hocko 			retval = PTR_ERR(pid);
1428fd0928dfSJens Axboe 			goto bad_fork_cleanup_io;
1429425fb2b4SPavel Emelyanov 		}
143035f71bc0SMichal Hocko 	}
1431425fb2b4SPavel Emelyanov 
14321da177e4SLinus Torvalds 	p->set_child_tid = (clone_flags & CLONE_CHILD_SETTID) ? child_tidptr : NULL;
14331da177e4SLinus Torvalds 	/*
14341da177e4SLinus Torvalds 	 * Clear TID on mm_release()?
14351da177e4SLinus Torvalds 	 */
14361da177e4SLinus Torvalds 	p->clear_child_tid = (clone_flags & CLONE_CHILD_CLEARTID) ? child_tidptr : NULL;
143773c10101SJens Axboe #ifdef CONFIG_BLOCK
143873c10101SJens Axboe 	p->plug = NULL;
143973c10101SJens Axboe #endif
144042b2dd0aSAlexey Dobriyan #ifdef CONFIG_FUTEX
14418f17d3a5SIngo Molnar 	p->robust_list = NULL;
14428f17d3a5SIngo Molnar #ifdef CONFIG_COMPAT
14438f17d3a5SIngo Molnar 	p->compat_robust_list = NULL;
14448f17d3a5SIngo Molnar #endif
1445c87e2837SIngo Molnar 	INIT_LIST_HEAD(&p->pi_state_list);
1446c87e2837SIngo Molnar 	p->pi_state_cache = NULL;
144742b2dd0aSAlexey Dobriyan #endif
14481da177e4SLinus Torvalds 	/*
1449f9a3879aSGOTO Masanori 	 * sigaltstack should be cleared when sharing the same VM
1450f9a3879aSGOTO Masanori 	 */
1451f9a3879aSGOTO Masanori 	if ((clone_flags & (CLONE_VM|CLONE_VFORK)) == CLONE_VM)
1452f9a3879aSGOTO Masanori 		p->sas_ss_sp = p->sas_ss_size = 0;
1453f9a3879aSGOTO Masanori 
1454f9a3879aSGOTO Masanori 	/*
14556580807dSOleg Nesterov 	 * Syscall tracing and stepping should be turned off in the
14566580807dSOleg Nesterov 	 * child regardless of CLONE_PTRACE.
14571da177e4SLinus Torvalds 	 */
14586580807dSOleg Nesterov 	user_disable_single_step(p);
14591da177e4SLinus Torvalds 	clear_tsk_thread_flag(p, TIF_SYSCALL_TRACE);
1460ed75e8d5SLaurent Vivier #ifdef TIF_SYSCALL_EMU
1461ed75e8d5SLaurent Vivier 	clear_tsk_thread_flag(p, TIF_SYSCALL_EMU);
1462ed75e8d5SLaurent Vivier #endif
14639745512cSArjan van de Ven 	clear_all_latency_tracing(p);
14641da177e4SLinus Torvalds 
14651da177e4SLinus Torvalds 	/* ok, now we should be set up.. */
146618c830dfSOleg Nesterov 	p->pid = pid_nr(pid);
146718c830dfSOleg Nesterov 	if (clone_flags & CLONE_THREAD) {
14685f8aadd8SOleg Nesterov 		p->exit_signal = -1;
146918c830dfSOleg Nesterov 		p->group_leader = current->group_leader;
147018c830dfSOleg Nesterov 		p->tgid = current->tgid;
147118c830dfSOleg Nesterov 	} else {
147218c830dfSOleg Nesterov 		if (clone_flags & CLONE_PARENT)
14735f8aadd8SOleg Nesterov 			p->exit_signal = current->group_leader->exit_signal;
14745f8aadd8SOleg Nesterov 		else
14755f8aadd8SOleg Nesterov 			p->exit_signal = (clone_flags & CSIGNAL);
147618c830dfSOleg Nesterov 		p->group_leader = p;
147718c830dfSOleg Nesterov 		p->tgid = p->pid;
147818c830dfSOleg Nesterov 	}
14795f8aadd8SOleg Nesterov 
14809d823e8fSWu Fengguang 	p->nr_dirtied = 0;
14819d823e8fSWu Fengguang 	p->nr_dirtied_pause = 128 >> (PAGE_SHIFT - 10);
148283712358SWu Fengguang 	p->dirty_paused_when = 0;
14839d823e8fSWu Fengguang 
1484bb8cbbfeSOleg Nesterov 	p->pdeath_signal = 0;
148547e65328SOleg Nesterov 	INIT_LIST_HEAD(&p->thread_group);
1486158e1645SAl Viro 	p->task_works = NULL;
14871da177e4SLinus Torvalds 
148818c830dfSOleg Nesterov 	/*
148918c830dfSOleg Nesterov 	 * Make it visible to the rest of the system, but dont wake it up yet.
149018c830dfSOleg Nesterov 	 * Need tasklist lock for parent etc handling!
149118c830dfSOleg Nesterov 	 */
14921da177e4SLinus Torvalds 	write_lock_irq(&tasklist_lock);
14931da177e4SLinus Torvalds 
14941da177e4SLinus Torvalds 	/* CLONE_PARENT re-uses the old parent */
14952d5516cbSOleg Nesterov 	if (clone_flags & (CLONE_PARENT|CLONE_THREAD)) {
14961da177e4SLinus Torvalds 		p->real_parent = current->real_parent;
14972d5516cbSOleg Nesterov 		p->parent_exec_id = current->parent_exec_id;
14982d5516cbSOleg Nesterov 	} else {
14991da177e4SLinus Torvalds 		p->real_parent = current;
15002d5516cbSOleg Nesterov 		p->parent_exec_id = current->self_exec_id;
15012d5516cbSOleg Nesterov 	}
15021da177e4SLinus Torvalds 
15031da177e4SLinus Torvalds 	spin_lock(&current->sighand->siglock);
15044a2c7a78SOleg Nesterov 
15054a2c7a78SOleg Nesterov 	/*
1506dbd95212SKees Cook 	 * Copy seccomp details explicitly here, in case they were changed
1507dbd95212SKees Cook 	 * before holding sighand lock.
1508dbd95212SKees Cook 	 */
1509dbd95212SKees Cook 	copy_seccomp(p);
1510dbd95212SKees Cook 
1511dbd95212SKees Cook 	/*
15124a2c7a78SOleg Nesterov 	 * Process group and session signals need to be delivered to just the
15134a2c7a78SOleg Nesterov 	 * parent before the fork or both the parent and the child after the
15144a2c7a78SOleg Nesterov 	 * fork. Restart if a signal comes in before we add the new process to
15154a2c7a78SOleg Nesterov 	 * it's process group.
15164a2c7a78SOleg Nesterov 	 * A fatal signal pending means that current will exit, so the new
15174a2c7a78SOleg Nesterov 	 * thread can't slip out of an OOM kill (or normal SIGKILL).
15184a2c7a78SOleg Nesterov 	*/
15194a2c7a78SOleg Nesterov 	recalc_sigpending();
15204a2c7a78SOleg Nesterov 	if (signal_pending(current)) {
15214a2c7a78SOleg Nesterov 		spin_unlock(&current->sighand->siglock);
15224a2c7a78SOleg Nesterov 		write_unlock_irq(&tasklist_lock);
15234a2c7a78SOleg Nesterov 		retval = -ERESTARTNOINTR;
1524f7e8b616SSteven Rostedt 		goto bad_fork_free_pid;
15254a2c7a78SOleg Nesterov 	}
15264a2c7a78SOleg Nesterov 
152773b9ebfeSOleg Nesterov 	if (likely(p->pid)) {
15284b9d33e6STejun Heo 		ptrace_init_task(p, (clone_flags & CLONE_PTRACE) || trace);
15291da177e4SLinus Torvalds 
153081907739SOleg Nesterov 		init_task_pid(p, PIDTYPE_PID, pid);
15311da177e4SLinus Torvalds 		if (thread_group_leader(p)) {
153281907739SOleg Nesterov 			init_task_pid(p, PIDTYPE_PGID, task_pgrp(current));
153381907739SOleg Nesterov 			init_task_pid(p, PIDTYPE_SID, task_session(current));
153481907739SOleg Nesterov 
15351c4042c2SEric W. Biederman 			if (is_child_reaper(pid)) {
153617cf22c3SEric W. Biederman 				ns_of_pid(pid)->child_reaper = p;
15371c4042c2SEric W. Biederman 				p->signal->flags |= SIGNAL_UNKILLABLE;
15381c4042c2SEric W. Biederman 			}
15395cd17569SEric W. Biederman 
1540fea9d175SOleg Nesterov 			p->signal->leader_pid = pid;
15419c9f4dedSAlan Cox 			p->signal->tty = tty_kref_get(current->signal->tty);
15429cd80bbbSOleg Nesterov 			list_add_tail(&p->sibling, &p->real_parent->children);
15435e85d4abSEric W. Biederman 			list_add_tail_rcu(&p->tasks, &init_task.tasks);
154481907739SOleg Nesterov 			attach_pid(p, PIDTYPE_PGID);
154581907739SOleg Nesterov 			attach_pid(p, PIDTYPE_SID);
1546909ea964SChristoph Lameter 			__this_cpu_inc(process_counts);
154780628ca0SOleg Nesterov 		} else {
154880628ca0SOleg Nesterov 			current->signal->nr_threads++;
154980628ca0SOleg Nesterov 			atomic_inc(&current->signal->live);
155080628ca0SOleg Nesterov 			atomic_inc(&current->signal->sigcnt);
155180628ca0SOleg Nesterov 			list_add_tail_rcu(&p->thread_group,
155280628ca0SOleg Nesterov 					  &p->group_leader->thread_group);
15530c740d0aSOleg Nesterov 			list_add_tail_rcu(&p->thread_node,
15540c740d0aSOleg Nesterov 					  &p->signal->thread_head);
15551da177e4SLinus Torvalds 		}
155681907739SOleg Nesterov 		attach_pid(p, PIDTYPE_PID);
15571da177e4SLinus Torvalds 		nr_threads++;
155873b9ebfeSOleg Nesterov 	}
155973b9ebfeSOleg Nesterov 
15601da177e4SLinus Torvalds 	total_forks++;
15613f17da69SOleg Nesterov 	spin_unlock(&current->sighand->siglock);
15624af4206bSOleg Nesterov 	syscall_tracepoint_update(p);
15631da177e4SLinus Torvalds 	write_unlock_irq(&tasklist_lock);
15644af4206bSOleg Nesterov 
1565c13cf856SAndrew Morton 	proc_fork_connector(p);
1566817929ecSPaul Menage 	cgroup_post_fork(p);
15674714d1d3SBen Blum 	if (clone_flags & CLONE_THREAD)
1568257058aeSTejun Heo 		threadgroup_change_end(current);
1569cdd6c482SIngo Molnar 	perf_event_fork(p);
157043d2b113SKAMEZAWA Hiroyuki 
157143d2b113SKAMEZAWA Hiroyuki 	trace_task_newtask(p, clone_flags);
15723ab67966SOleg Nesterov 	uprobe_copy_process(p, clone_flags);
157343d2b113SKAMEZAWA Hiroyuki 
15741da177e4SLinus Torvalds 	return p;
15751da177e4SLinus Torvalds 
1576425fb2b4SPavel Emelyanov bad_fork_free_pid:
1577425fb2b4SPavel Emelyanov 	if (pid != &init_struct_pid)
1578425fb2b4SPavel Emelyanov 		free_pid(pid);
1579fd0928dfSJens Axboe bad_fork_cleanup_io:
1580b69f2292SLouis Rilling 	if (p->io_context)
1581b69f2292SLouis Rilling 		exit_io_context(p);
1582ab516013SSerge E. Hallyn bad_fork_cleanup_namespaces:
1583444f378bSLinus Torvalds 	exit_task_namespaces(p);
15841da177e4SLinus Torvalds bad_fork_cleanup_mm:
1585c9f01245SDavid Rientjes 	if (p->mm)
15861da177e4SLinus Torvalds 		mmput(p->mm);
15871da177e4SLinus Torvalds bad_fork_cleanup_signal:
15884ab6c083SOleg Nesterov 	if (!(clone_flags & CLONE_THREAD))
15891c5354deSMike Galbraith 		free_signal_struct(p->signal);
15901da177e4SLinus Torvalds bad_fork_cleanup_sighand:
1591a7e5328aSOleg Nesterov 	__cleanup_sighand(p->sighand);
15921da177e4SLinus Torvalds bad_fork_cleanup_fs:
15931da177e4SLinus Torvalds 	exit_fs(p); /* blocking */
15941da177e4SLinus Torvalds bad_fork_cleanup_files:
15951da177e4SLinus Torvalds 	exit_files(p); /* blocking */
15961da177e4SLinus Torvalds bad_fork_cleanup_semundo:
15971da177e4SLinus Torvalds 	exit_sem(p);
15981da177e4SLinus Torvalds bad_fork_cleanup_audit:
15991da177e4SLinus Torvalds 	audit_free(p);
16006c72e350SPeter Zijlstra bad_fork_cleanup_perf:
1601cdd6c482SIngo Molnar 	perf_event_free_task(p);
16026c72e350SPeter Zijlstra bad_fork_cleanup_policy:
16031da177e4SLinus Torvalds #ifdef CONFIG_NUMA
1604f0be3d32SLee Schermerhorn 	mpol_put(p->mempolicy);
1605e8604cb4SLi Zefan bad_fork_cleanup_threadgroup_lock:
16061da177e4SLinus Torvalds #endif
16074714d1d3SBen Blum 	if (clone_flags & CLONE_THREAD)
1608257058aeSTejun Heo 		threadgroup_change_end(current);
160935df17c5SShailabh Nagar 	delayacct_tsk_free(p);
16101da177e4SLinus Torvalds bad_fork_cleanup_count:
1611d84f4f99SDavid Howells 	atomic_dec(&p->cred->user->processes);
1612e0e81739SDavid Howells 	exit_creds(p);
16131da177e4SLinus Torvalds bad_fork_free:
16141da177e4SLinus Torvalds 	free_task(p);
1615fe7d37d1SOleg Nesterov fork_out:
1616fe7d37d1SOleg Nesterov 	return ERR_PTR(retval);
16171da177e4SLinus Torvalds }
16181da177e4SLinus Torvalds 
1619f106eee1SOleg Nesterov static inline void init_idle_pids(struct pid_link *links)
1620f106eee1SOleg Nesterov {
1621f106eee1SOleg Nesterov 	enum pid_type type;
1622f106eee1SOleg Nesterov 
1623f106eee1SOleg Nesterov 	for (type = PIDTYPE_PID; type < PIDTYPE_MAX; ++type) {
1624f106eee1SOleg Nesterov 		INIT_HLIST_NODE(&links[type].node); /* not really needed */
1625f106eee1SOleg Nesterov 		links[type].pid = &init_struct_pid;
1626f106eee1SOleg Nesterov 	}
1627f106eee1SOleg Nesterov }
1628f106eee1SOleg Nesterov 
16290db0628dSPaul Gortmaker struct task_struct *fork_idle(int cpu)
16301da177e4SLinus Torvalds {
163136c8b586SIngo Molnar 	struct task_struct *task;
163262e791c1SAl Viro 	task = copy_process(CLONE_VM, 0, 0, NULL, &init_struct_pid, 0);
1633f106eee1SOleg Nesterov 	if (!IS_ERR(task)) {
1634f106eee1SOleg Nesterov 		init_idle_pids(task->pids);
16351da177e4SLinus Torvalds 		init_idle(task, cpu);
1636f106eee1SOleg Nesterov 	}
163773b9ebfeSOleg Nesterov 
16381da177e4SLinus Torvalds 	return task;
16391da177e4SLinus Torvalds }
16401da177e4SLinus Torvalds 
16411da177e4SLinus Torvalds /*
16421da177e4SLinus Torvalds  *  Ok, this is the main fork-routine.
16431da177e4SLinus Torvalds  *
16441da177e4SLinus Torvalds  * It copies the process, and if successful kick-starts
16451da177e4SLinus Torvalds  * it and waits for it to finish using the VM if required.
16461da177e4SLinus Torvalds  */
16471da177e4SLinus Torvalds long do_fork(unsigned long clone_flags,
16481da177e4SLinus Torvalds 	      unsigned long stack_start,
16491da177e4SLinus Torvalds 	      unsigned long stack_size,
16501da177e4SLinus Torvalds 	      int __user *parent_tidptr,
16511da177e4SLinus Torvalds 	      int __user *child_tidptr)
16521da177e4SLinus Torvalds {
16531da177e4SLinus Torvalds 	struct task_struct *p;
16541da177e4SLinus Torvalds 	int trace = 0;
165592476d7fSEric W. Biederman 	long nr;
16561da177e4SLinus Torvalds 
1657bdff746aSAndrew Morton 	/*
16584b9d33e6STejun Heo 	 * Determine whether and which event to report to ptracer.  When
16594b9d33e6STejun Heo 	 * called from kernel_thread or CLONE_UNTRACED is explicitly
16604b9d33e6STejun Heo 	 * requested, no event is reported; otherwise, report if the event
16614b9d33e6STejun Heo 	 * for the type of forking is enabled.
166209a05394SRoland McGrath 	 */
1663e80d6661SAl Viro 	if (!(clone_flags & CLONE_UNTRACED)) {
16644b9d33e6STejun Heo 		if (clone_flags & CLONE_VFORK)
16654b9d33e6STejun Heo 			trace = PTRACE_EVENT_VFORK;
16664b9d33e6STejun Heo 		else if ((clone_flags & CSIGNAL) != SIGCHLD)
16674b9d33e6STejun Heo 			trace = PTRACE_EVENT_CLONE;
16684b9d33e6STejun Heo 		else
16694b9d33e6STejun Heo 			trace = PTRACE_EVENT_FORK;
16704b9d33e6STejun Heo 
16714b9d33e6STejun Heo 		if (likely(!ptrace_event_enabled(current, trace)))
16724b9d33e6STejun Heo 			trace = 0;
16734b9d33e6STejun Heo 	}
16741da177e4SLinus Torvalds 
167562e791c1SAl Viro 	p = copy_process(clone_flags, stack_start, stack_size,
167609a05394SRoland McGrath 			 child_tidptr, NULL, trace);
16771da177e4SLinus Torvalds 	/*
16781da177e4SLinus Torvalds 	 * Do this prior waking up the new thread - the thread pointer
16791da177e4SLinus Torvalds 	 * might get invalid after that point, if the thread exits quickly.
16801da177e4SLinus Torvalds 	 */
16811da177e4SLinus Torvalds 	if (!IS_ERR(p)) {
16821da177e4SLinus Torvalds 		struct completion vfork;
16834e52365fSMatthew Dempsky 		struct pid *pid;
16841da177e4SLinus Torvalds 
16850a16b607SMathieu Desnoyers 		trace_sched_process_fork(current, p);
16860a16b607SMathieu Desnoyers 
16874e52365fSMatthew Dempsky 		pid = get_task_pid(p, PIDTYPE_PID);
16884e52365fSMatthew Dempsky 		nr = pid_vnr(pid);
168930e49c26SPavel Emelyanov 
169030e49c26SPavel Emelyanov 		if (clone_flags & CLONE_PARENT_SETTID)
169130e49c26SPavel Emelyanov 			put_user(nr, parent_tidptr);
1692a6f5e063SSukadev Bhattiprolu 
16931da177e4SLinus Torvalds 		if (clone_flags & CLONE_VFORK) {
16941da177e4SLinus Torvalds 			p->vfork_done = &vfork;
16951da177e4SLinus Torvalds 			init_completion(&vfork);
1696d68b46feSOleg Nesterov 			get_task_struct(p);
16971da177e4SLinus Torvalds 		}
16981da177e4SLinus Torvalds 
16993e51e3edSSamir Bellabes 		wake_up_new_task(p);
17001da177e4SLinus Torvalds 
17014b9d33e6STejun Heo 		/* forking complete and child started to run, tell ptracer */
17024b9d33e6STejun Heo 		if (unlikely(trace))
17034e52365fSMatthew Dempsky 			ptrace_event_pid(trace, pid);
170409a05394SRoland McGrath 
17051da177e4SLinus Torvalds 		if (clone_flags & CLONE_VFORK) {
1706d68b46feSOleg Nesterov 			if (!wait_for_vfork_done(p, &vfork))
17074e52365fSMatthew Dempsky 				ptrace_event_pid(PTRACE_EVENT_VFORK_DONE, pid);
17089f59ce5dSChuck Ebbert 		}
17094e52365fSMatthew Dempsky 
17104e52365fSMatthew Dempsky 		put_pid(pid);
17111da177e4SLinus Torvalds 	} else {
171292476d7fSEric W. Biederman 		nr = PTR_ERR(p);
17131da177e4SLinus Torvalds 	}
171492476d7fSEric W. Biederman 	return nr;
17151da177e4SLinus Torvalds }
17161da177e4SLinus Torvalds 
17172aa3a7f8SAl Viro /*
17182aa3a7f8SAl Viro  * Create a kernel thread.
17192aa3a7f8SAl Viro  */
17202aa3a7f8SAl Viro pid_t kernel_thread(int (*fn)(void *), void *arg, unsigned long flags)
17212aa3a7f8SAl Viro {
1722e80d6661SAl Viro 	return do_fork(flags|CLONE_VM|CLONE_UNTRACED, (unsigned long)fn,
17232aa3a7f8SAl Viro 		(unsigned long)arg, NULL, NULL);
17242aa3a7f8SAl Viro }
17252aa3a7f8SAl Viro 
1726d2125043SAl Viro #ifdef __ARCH_WANT_SYS_FORK
1727d2125043SAl Viro SYSCALL_DEFINE0(fork)
1728d2125043SAl Viro {
1729d2125043SAl Viro #ifdef CONFIG_MMU
1730e80d6661SAl Viro 	return do_fork(SIGCHLD, 0, 0, NULL, NULL);
1731d2125043SAl Viro #else
1732d2125043SAl Viro 	/* can not support in nommu mode */
17335d59e182SDaeseok Youn 	return -EINVAL;
1734d2125043SAl Viro #endif
1735d2125043SAl Viro }
1736d2125043SAl Viro #endif
1737d2125043SAl Viro 
1738d2125043SAl Viro #ifdef __ARCH_WANT_SYS_VFORK
1739d2125043SAl Viro SYSCALL_DEFINE0(vfork)
1740d2125043SAl Viro {
1741e80d6661SAl Viro 	return do_fork(CLONE_VFORK | CLONE_VM | SIGCHLD, 0,
1742d2125043SAl Viro 			0, NULL, NULL);
1743d2125043SAl Viro }
1744d2125043SAl Viro #endif
1745d2125043SAl Viro 
1746d2125043SAl Viro #ifdef __ARCH_WANT_SYS_CLONE
1747d2125043SAl Viro #ifdef CONFIG_CLONE_BACKWARDS
1748d2125043SAl Viro SYSCALL_DEFINE5(clone, unsigned long, clone_flags, unsigned long, newsp,
1749d2125043SAl Viro 		 int __user *, parent_tidptr,
1750d2125043SAl Viro 		 int, tls_val,
1751d2125043SAl Viro 		 int __user *, child_tidptr)
1752d2125043SAl Viro #elif defined(CONFIG_CLONE_BACKWARDS2)
1753d2125043SAl Viro SYSCALL_DEFINE5(clone, unsigned long, newsp, unsigned long, clone_flags,
1754d2125043SAl Viro 		 int __user *, parent_tidptr,
1755d2125043SAl Viro 		 int __user *, child_tidptr,
1756d2125043SAl Viro 		 int, tls_val)
1757dfa9771aSMichal Simek #elif defined(CONFIG_CLONE_BACKWARDS3)
1758dfa9771aSMichal Simek SYSCALL_DEFINE6(clone, unsigned long, clone_flags, unsigned long, newsp,
1759dfa9771aSMichal Simek 		int, stack_size,
1760dfa9771aSMichal Simek 		int __user *, parent_tidptr,
1761dfa9771aSMichal Simek 		int __user *, child_tidptr,
1762dfa9771aSMichal Simek 		int, tls_val)
1763d2125043SAl Viro #else
1764d2125043SAl Viro SYSCALL_DEFINE5(clone, unsigned long, clone_flags, unsigned long, newsp,
1765d2125043SAl Viro 		 int __user *, parent_tidptr,
1766d2125043SAl Viro 		 int __user *, child_tidptr,
1767d2125043SAl Viro 		 int, tls_val)
1768d2125043SAl Viro #endif
1769d2125043SAl Viro {
17702cf09666SAl Viro 	return do_fork(clone_flags, newsp, 0, parent_tidptr, child_tidptr);
1771d2125043SAl Viro }
1772d2125043SAl Viro #endif
1773d2125043SAl Viro 
17745fd63b30SRavikiran G Thirumalai #ifndef ARCH_MIN_MMSTRUCT_ALIGN
17755fd63b30SRavikiran G Thirumalai #define ARCH_MIN_MMSTRUCT_ALIGN 0
17765fd63b30SRavikiran G Thirumalai #endif
17775fd63b30SRavikiran G Thirumalai 
177851cc5068SAlexey Dobriyan static void sighand_ctor(void *data)
1779aa1757f9SOleg Nesterov {
1780aa1757f9SOleg Nesterov 	struct sighand_struct *sighand = data;
1781aa1757f9SOleg Nesterov 
1782aa1757f9SOleg Nesterov 	spin_lock_init(&sighand->siglock);
1783b8fceee1SDavide Libenzi 	init_waitqueue_head(&sighand->signalfd_wqh);
1784fba2afaaSDavide Libenzi }
1785aa1757f9SOleg Nesterov 
17861da177e4SLinus Torvalds void __init proc_caches_init(void)
17871da177e4SLinus Torvalds {
17881da177e4SLinus Torvalds 	sighand_cachep = kmem_cache_create("sighand_cache",
17891da177e4SLinus Torvalds 			sizeof(struct sighand_struct), 0,
17902dff4405SVegard Nossum 			SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_DESTROY_BY_RCU|
17912dff4405SVegard Nossum 			SLAB_NOTRACK, sighand_ctor);
17921da177e4SLinus Torvalds 	signal_cachep = kmem_cache_create("signal_cache",
17931da177e4SLinus Torvalds 			sizeof(struct signal_struct), 0,
17942dff4405SVegard Nossum 			SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_NOTRACK, NULL);
17951da177e4SLinus Torvalds 	files_cachep = kmem_cache_create("files_cache",
17961da177e4SLinus Torvalds 			sizeof(struct files_struct), 0,
17972dff4405SVegard Nossum 			SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_NOTRACK, NULL);
17981da177e4SLinus Torvalds 	fs_cachep = kmem_cache_create("fs_cache",
17991da177e4SLinus Torvalds 			sizeof(struct fs_struct), 0,
18002dff4405SVegard Nossum 			SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_NOTRACK, NULL);
18016345d24dSLinus Torvalds 	/*
18026345d24dSLinus Torvalds 	 * FIXME! The "sizeof(struct mm_struct)" currently includes the
18036345d24dSLinus Torvalds 	 * whole struct cpumask for the OFFSTACK case. We could change
18046345d24dSLinus Torvalds 	 * this to *only* allocate as much of it as required by the
18056345d24dSLinus Torvalds 	 * maximum number of CPU's we can ever have.  The cpumask_allocation
18066345d24dSLinus Torvalds 	 * is at the end of the structure, exactly for that reason.
18076345d24dSLinus Torvalds 	 */
18081da177e4SLinus Torvalds 	mm_cachep = kmem_cache_create("mm_struct",
18095fd63b30SRavikiran G Thirumalai 			sizeof(struct mm_struct), ARCH_MIN_MMSTRUCT_ALIGN,
18102dff4405SVegard Nossum 			SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_NOTRACK, NULL);
181133e5d769SDavid Howells 	vm_area_cachep = KMEM_CACHE(vm_area_struct, SLAB_PANIC);
18128feae131SDavid Howells 	mmap_init();
181366577193SAl Viro 	nsproxy_cache_init();
18141da177e4SLinus Torvalds }
1815cf2e340fSJANAK DESAI 
1816cf2e340fSJANAK DESAI /*
18179bfb23fcSOleg Nesterov  * Check constraints on flags passed to the unshare system call.
1818cf2e340fSJANAK DESAI  */
18199bfb23fcSOleg Nesterov static int check_unshare_flags(unsigned long unshare_flags)
1820cf2e340fSJANAK DESAI {
18219bfb23fcSOleg Nesterov 	if (unshare_flags & ~(CLONE_THREAD|CLONE_FS|CLONE_NEWNS|CLONE_SIGHAND|
18229bfb23fcSOleg Nesterov 				CLONE_VM|CLONE_FILES|CLONE_SYSVSEM|
182350804fe3SEric W. Biederman 				CLONE_NEWUTS|CLONE_NEWIPC|CLONE_NEWNET|
1824b2e0d987SEric W. Biederman 				CLONE_NEWUSER|CLONE_NEWPID))
1825cf2e340fSJANAK DESAI 		return -EINVAL;
18269bfb23fcSOleg Nesterov 	/*
18279bfb23fcSOleg Nesterov 	 * Not implemented, but pretend it works if there is nothing to
18289bfb23fcSOleg Nesterov 	 * unshare. Note that unsharing CLONE_THREAD or CLONE_SIGHAND
18299bfb23fcSOleg Nesterov 	 * needs to unshare vm.
18309bfb23fcSOleg Nesterov 	 */
18319bfb23fcSOleg Nesterov 	if (unshare_flags & (CLONE_THREAD | CLONE_SIGHAND | CLONE_VM)) {
18329bfb23fcSOleg Nesterov 		/* FIXME: get_task_mm() increments ->mm_users */
18339bfb23fcSOleg Nesterov 		if (atomic_read(&current->mm->mm_users) > 1)
18349bfb23fcSOleg Nesterov 			return -EINVAL;
18359bfb23fcSOleg Nesterov 	}
1836cf2e340fSJANAK DESAI 
1837cf2e340fSJANAK DESAI 	return 0;
1838cf2e340fSJANAK DESAI }
1839cf2e340fSJANAK DESAI 
1840cf2e340fSJANAK DESAI /*
184199d1419dSJANAK DESAI  * Unshare the filesystem structure if it is being shared
1842cf2e340fSJANAK DESAI  */
1843cf2e340fSJANAK DESAI static int unshare_fs(unsigned long unshare_flags, struct fs_struct **new_fsp)
1844cf2e340fSJANAK DESAI {
1845cf2e340fSJANAK DESAI 	struct fs_struct *fs = current->fs;
1846cf2e340fSJANAK DESAI 
1847498052bbSAl Viro 	if (!(unshare_flags & CLONE_FS) || !fs)
1848498052bbSAl Viro 		return 0;
1849498052bbSAl Viro 
1850498052bbSAl Viro 	/* don't need lock here; in the worst case we'll do useless copy */
1851498052bbSAl Viro 	if (fs->users == 1)
1852498052bbSAl Viro 		return 0;
1853498052bbSAl Viro 
1854498052bbSAl Viro 	*new_fsp = copy_fs_struct(fs);
185599d1419dSJANAK DESAI 	if (!*new_fsp)
185699d1419dSJANAK DESAI 		return -ENOMEM;
1857cf2e340fSJANAK DESAI 
1858cf2e340fSJANAK DESAI 	return 0;
1859cf2e340fSJANAK DESAI }
1860cf2e340fSJANAK DESAI 
1861cf2e340fSJANAK DESAI /*
1862a016f338SJANAK DESAI  * Unshare file descriptor table if it is being shared
1863cf2e340fSJANAK DESAI  */
1864cf2e340fSJANAK DESAI static int unshare_fd(unsigned long unshare_flags, struct files_struct **new_fdp)
1865cf2e340fSJANAK DESAI {
1866cf2e340fSJANAK DESAI 	struct files_struct *fd = current->files;
1867a016f338SJANAK DESAI 	int error = 0;
1868cf2e340fSJANAK DESAI 
1869cf2e340fSJANAK DESAI 	if ((unshare_flags & CLONE_FILES) &&
1870a016f338SJANAK DESAI 	    (fd && atomic_read(&fd->count) > 1)) {
1871a016f338SJANAK DESAI 		*new_fdp = dup_fd(fd, &error);
1872a016f338SJANAK DESAI 		if (!*new_fdp)
1873a016f338SJANAK DESAI 			return error;
1874a016f338SJANAK DESAI 	}
1875cf2e340fSJANAK DESAI 
1876cf2e340fSJANAK DESAI 	return 0;
1877cf2e340fSJANAK DESAI }
1878cf2e340fSJANAK DESAI 
1879cf2e340fSJANAK DESAI /*
1880cf2e340fSJANAK DESAI  * unshare allows a process to 'unshare' part of the process
1881cf2e340fSJANAK DESAI  * context which was originally shared using clone.  copy_*
1882cf2e340fSJANAK DESAI  * functions used by do_fork() cannot be used here directly
1883cf2e340fSJANAK DESAI  * because they modify an inactive task_struct that is being
1884cf2e340fSJANAK DESAI  * constructed. Here we are modifying the current, active,
1885cf2e340fSJANAK DESAI  * task_struct.
1886cf2e340fSJANAK DESAI  */
18876559eed8SHeiko Carstens SYSCALL_DEFINE1(unshare, unsigned long, unshare_flags)
1888cf2e340fSJANAK DESAI {
1889cf2e340fSJANAK DESAI 	struct fs_struct *fs, *new_fs = NULL;
1890cf2e340fSJANAK DESAI 	struct files_struct *fd, *new_fd = NULL;
1891b2e0d987SEric W. Biederman 	struct cred *new_cred = NULL;
1892cf7b708cSPavel Emelyanov 	struct nsproxy *new_nsproxy = NULL;
18939edff4abSManfred Spraul 	int do_sysvsem = 0;
18949bfb23fcSOleg Nesterov 	int err;
1895cf2e340fSJANAK DESAI 
189650804fe3SEric W. Biederman 	/*
1897b2e0d987SEric W. Biederman 	 * If unsharing a user namespace must also unshare the thread.
1898b2e0d987SEric W. Biederman 	 */
1899b2e0d987SEric W. Biederman 	if (unshare_flags & CLONE_NEWUSER)
1900e66eded8SEric W. Biederman 		unshare_flags |= CLONE_THREAD | CLONE_FS;
1901b2e0d987SEric W. Biederman 	/*
190250804fe3SEric W. Biederman 	 * If unsharing a thread from a thread group, must also unshare vm.
190350804fe3SEric W. Biederman 	 */
190450804fe3SEric W. Biederman 	if (unshare_flags & CLONE_THREAD)
190550804fe3SEric W. Biederman 		unshare_flags |= CLONE_VM;
190650804fe3SEric W. Biederman 	/*
190750804fe3SEric W. Biederman 	 * If unsharing vm, must also unshare signal handlers.
190850804fe3SEric W. Biederman 	 */
190950804fe3SEric W. Biederman 	if (unshare_flags & CLONE_VM)
191050804fe3SEric W. Biederman 		unshare_flags |= CLONE_SIGHAND;
19116013f67fSManfred Spraul 	/*
19129bfb23fcSOleg Nesterov 	 * If unsharing namespace, must also unshare filesystem information.
19139bfb23fcSOleg Nesterov 	 */
19149bfb23fcSOleg Nesterov 	if (unshare_flags & CLONE_NEWNS)
19159bfb23fcSOleg Nesterov 		unshare_flags |= CLONE_FS;
191650804fe3SEric W. Biederman 
191750804fe3SEric W. Biederman 	err = check_unshare_flags(unshare_flags);
191850804fe3SEric W. Biederman 	if (err)
191950804fe3SEric W. Biederman 		goto bad_unshare_out;
19209bfb23fcSOleg Nesterov 	/*
19216013f67fSManfred Spraul 	 * CLONE_NEWIPC must also detach from the undolist: after switching
19226013f67fSManfred Spraul 	 * to a new ipc namespace, the semaphore arrays from the old
19236013f67fSManfred Spraul 	 * namespace are unreachable.
19246013f67fSManfred Spraul 	 */
19256013f67fSManfred Spraul 	if (unshare_flags & (CLONE_NEWIPC|CLONE_SYSVSEM))
19269edff4abSManfred Spraul 		do_sysvsem = 1;
1927fb0a685cSDaniel Rebelo de Oliveira 	err = unshare_fs(unshare_flags, &new_fs);
1928fb0a685cSDaniel Rebelo de Oliveira 	if (err)
19299bfb23fcSOleg Nesterov 		goto bad_unshare_out;
1930fb0a685cSDaniel Rebelo de Oliveira 	err = unshare_fd(unshare_flags, &new_fd);
1931fb0a685cSDaniel Rebelo de Oliveira 	if (err)
19329bfb23fcSOleg Nesterov 		goto bad_unshare_cleanup_fs;
1933b2e0d987SEric W. Biederman 	err = unshare_userns(unshare_flags, &new_cred);
1934fb0a685cSDaniel Rebelo de Oliveira 	if (err)
19359edff4abSManfred Spraul 		goto bad_unshare_cleanup_fd;
1936b2e0d987SEric W. Biederman 	err = unshare_nsproxy_namespaces(unshare_flags, &new_nsproxy,
1937b2e0d987SEric W. Biederman 					 new_cred, new_fs);
1938b2e0d987SEric W. Biederman 	if (err)
1939b2e0d987SEric W. Biederman 		goto bad_unshare_cleanup_cred;
1940cf2e340fSJANAK DESAI 
1941b2e0d987SEric W. Biederman 	if (new_fs || new_fd || do_sysvsem || new_cred || new_nsproxy) {
19429edff4abSManfred Spraul 		if (do_sysvsem) {
19439edff4abSManfred Spraul 			/*
19449edff4abSManfred Spraul 			 * CLONE_SYSVSEM is equivalent to sys_exit().
19459edff4abSManfred Spraul 			 */
19469edff4abSManfred Spraul 			exit_sem(current);
19479edff4abSManfred Spraul 		}
1948ab602f79SJack Miller 		if (unshare_flags & CLONE_NEWIPC) {
1949ab602f79SJack Miller 			/* Orphan segments in old ns (see sem above). */
1950ab602f79SJack Miller 			exit_shm(current);
1951ab602f79SJack Miller 			shm_init_task(current);
1952ab602f79SJack Miller 		}
1953ab516013SSerge E. Hallyn 
19546f977e6bSAlan Cox 		if (new_nsproxy)
1955cf7b708cSPavel Emelyanov 			switch_task_namespaces(current, new_nsproxy);
1956cf2e340fSJANAK DESAI 
1957cf7b708cSPavel Emelyanov 		task_lock(current);
1958cf7b708cSPavel Emelyanov 
1959cf2e340fSJANAK DESAI 		if (new_fs) {
1960cf2e340fSJANAK DESAI 			fs = current->fs;
19612a4419b5SNick Piggin 			spin_lock(&fs->lock);
1962cf2e340fSJANAK DESAI 			current->fs = new_fs;
1963498052bbSAl Viro 			if (--fs->users)
1964498052bbSAl Viro 				new_fs = NULL;
1965498052bbSAl Viro 			else
1966cf2e340fSJANAK DESAI 				new_fs = fs;
19672a4419b5SNick Piggin 			spin_unlock(&fs->lock);
1968cf2e340fSJANAK DESAI 		}
1969cf2e340fSJANAK DESAI 
1970cf2e340fSJANAK DESAI 		if (new_fd) {
1971cf2e340fSJANAK DESAI 			fd = current->files;
1972cf2e340fSJANAK DESAI 			current->files = new_fd;
1973cf2e340fSJANAK DESAI 			new_fd = fd;
1974cf2e340fSJANAK DESAI 		}
1975cf2e340fSJANAK DESAI 
1976cf2e340fSJANAK DESAI 		task_unlock(current);
1977b2e0d987SEric W. Biederman 
1978b2e0d987SEric W. Biederman 		if (new_cred) {
1979b2e0d987SEric W. Biederman 			/* Install the new user namespace */
1980b2e0d987SEric W. Biederman 			commit_creds(new_cred);
1981b2e0d987SEric W. Biederman 			new_cred = NULL;
1982b2e0d987SEric W. Biederman 		}
1983cf2e340fSJANAK DESAI 	}
1984cf2e340fSJANAK DESAI 
1985b2e0d987SEric W. Biederman bad_unshare_cleanup_cred:
1986b2e0d987SEric W. Biederman 	if (new_cred)
1987b2e0d987SEric W. Biederman 		put_cred(new_cred);
1988cf2e340fSJANAK DESAI bad_unshare_cleanup_fd:
1989cf2e340fSJANAK DESAI 	if (new_fd)
1990cf2e340fSJANAK DESAI 		put_files_struct(new_fd);
1991cf2e340fSJANAK DESAI 
1992cf2e340fSJANAK DESAI bad_unshare_cleanup_fs:
1993cf2e340fSJANAK DESAI 	if (new_fs)
1994498052bbSAl Viro 		free_fs_struct(new_fs);
1995cf2e340fSJANAK DESAI 
1996cf2e340fSJANAK DESAI bad_unshare_out:
1997cf2e340fSJANAK DESAI 	return err;
1998cf2e340fSJANAK DESAI }
19993b125388SAl Viro 
20003b125388SAl Viro /*
20013b125388SAl Viro  *	Helper to unshare the files of the current task.
20023b125388SAl Viro  *	We don't want to expose copy_files internals to
20033b125388SAl Viro  *	the exec layer of the kernel.
20043b125388SAl Viro  */
20053b125388SAl Viro 
20063b125388SAl Viro int unshare_files(struct files_struct **displaced)
20073b125388SAl Viro {
20083b125388SAl Viro 	struct task_struct *task = current;
200950704516SAl Viro 	struct files_struct *copy = NULL;
20103b125388SAl Viro 	int error;
20113b125388SAl Viro 
20123b125388SAl Viro 	error = unshare_fd(CLONE_FILES, &copy);
20133b125388SAl Viro 	if (error || !copy) {
20143b125388SAl Viro 		*displaced = NULL;
20153b125388SAl Viro 		return error;
20163b125388SAl Viro 	}
20173b125388SAl Viro 	*displaced = task->files;
20183b125388SAl Viro 	task_lock(task);
20193b125388SAl Viro 	task->files = copy;
20203b125388SAl Viro 	task_unlock(task);
20213b125388SAl Viro 	return 0;
20223b125388SAl Viro }
2023