• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  *  linux/kernel/fork.c
3  *
4  *  Copyright (C) 1991, 1992  Linus Torvalds
5  */
6 
7 /*
8  *  'fork.c' contains the help-routines for the 'fork' system call
9  * (see also entry.S and others).
10  * Fork is rather simple, once you get the hang of it, but the memory
11  * management can be a bitch. See 'mm/memory.c': 'copy_page_range()'
12  */
13 
14 #include <linux/slab.h>
15 #include <linux/init.h>
16 #include <linux/unistd.h>
17 #include <linux/module.h>
18 #include <linux/vmalloc.h>
19 #include <linux/completion.h>
20 #include <linux/personality.h>
21 #include <linux/mempolicy.h>
22 #include <linux/sem.h>
23 #include <linux/file.h>
24 #include <linux/fdtable.h>
25 #include <linux/iocontext.h>
26 #include <linux/key.h>
27 #include <linux/binfmts.h>
28 #include <linux/mman.h>
29 #include <linux/mmu_notifier.h>
30 #include <linux/fs.h>
31 #include <linux/mm.h>
32 #include <linux/vmacache.h>
33 #include <linux/nsproxy.h>
34 #include <linux/capability.h>
35 #include <linux/cpu.h>
36 #include <linux/cgroup.h>
37 #include <linux/security.h>
38 #include <linux/hugetlb.h>
39 #include <linux/seccomp.h>
40 #include <linux/swap.h>
41 #include <linux/syscalls.h>
42 #include <linux/jiffies.h>
43 #include <linux/futex.h>
44 #include <linux/compat.h>
45 #include <linux/kthread.h>
46 #include <linux/task_io_accounting_ops.h>
47 #include <linux/rcupdate.h>
48 #include <linux/ptrace.h>
49 #include <linux/mount.h>
50 #include <linux/audit.h>
51 #include <linux/memcontrol.h>
52 #include <linux/ftrace.h>
53 #include <linux/proc_fs.h>
54 #include <linux/profile.h>
55 #include <linux/rmap.h>
56 #include <linux/ksm.h>
57 #include <linux/acct.h>
58 #include <linux/tsacct_kern.h>
59 #include <linux/cn_proc.h>
60 #include <linux/freezer.h>
61 #include <linux/delayacct.h>
62 #include <linux/taskstats_kern.h>
63 #include <linux/random.h>
64 #include <linux/tty.h>
65 #include <linux/blkdev.h>
66 #include <linux/fs_struct.h>
67 #include <linux/magic.h>
68 #include <linux/perf_event.h>
69 #include <linux/posix-timers.h>
70 #include <linux/user-return-notifier.h>
71 #include <linux/oom.h>
72 #include <linux/khugepaged.h>
73 #include <linux/signalfd.h>
74 #include <linux/uprobes.h>
75 #include <linux/aio.h>
76 #include <linux/compiler.h>
77 #include <linux/kcov.h>
78 
79 #include <asm/pgtable.h>
80 #include <asm/pgalloc.h>
81 #include <asm/uaccess.h>
82 #include <asm/mmu_context.h>
83 #include <asm/cacheflush.h>
84 #include <asm/tlbflush.h>
85 
86 #include <trace/events/sched.h>
87 
88 #define CREATE_TRACE_POINTS
89 #include <trace/events/task.h>
90 
91 /*
92  * Protected counters by write_lock_irq(&tasklist_lock)
93  */
94 unsigned long total_forks;	/* Handle normal Linux uptimes. */
95 int nr_threads;			/* The idle threads do not count.. */
96 
97 int max_threads;		/* tunable limit on nr_threads */
98 
99 DEFINE_PER_CPU(unsigned long, process_counts) = 0;
100 
101 __cacheline_aligned DEFINE_RWLOCK(tasklist_lock);  /* outer */
102 
103 #ifdef CONFIG_PROVE_RCU
lockdep_tasklist_lock_is_held(void)104 int lockdep_tasklist_lock_is_held(void)
105 {
106 	return lockdep_is_held(&tasklist_lock);
107 }
108 EXPORT_SYMBOL_GPL(lockdep_tasklist_lock_is_held);
109 #endif /* #ifdef CONFIG_PROVE_RCU */
110 
nr_processes(void)111 int nr_processes(void)
112 {
113 	int cpu;
114 	int total = 0;
115 
116 	for_each_possible_cpu(cpu)
117 		total += per_cpu(process_counts, cpu);
118 
119 	return total;
120 }
121 
arch_release_task_struct(struct task_struct * tsk)122 void __weak arch_release_task_struct(struct task_struct *tsk)
123 {
124 }
125 
126 #ifndef CONFIG_ARCH_TASK_STRUCT_ALLOCATOR
127 static struct kmem_cache *task_struct_cachep;
128 
alloc_task_struct_node(int node)129 static inline struct task_struct *alloc_task_struct_node(int node)
130 {
131 	return kmem_cache_alloc_node(task_struct_cachep, GFP_KERNEL, node);
132 }
133 
free_task_struct(struct task_struct * tsk)134 static inline void free_task_struct(struct task_struct *tsk)
135 {
136 	kmem_cache_free(task_struct_cachep, tsk);
137 }
138 #endif
139 
arch_release_thread_info(struct thread_info * ti)140 void __weak arch_release_thread_info(struct thread_info *ti)
141 {
142 }
143 
144 #ifndef CONFIG_ARCH_THREAD_INFO_ALLOCATOR
145 
146 /*
147  * Allocate pages if THREAD_SIZE is >= PAGE_SIZE, otherwise use a
148  * kmemcache based allocator.
149  */
150 # if THREAD_SIZE >= PAGE_SIZE
alloc_thread_info_node(struct task_struct * tsk,int node)151 static struct thread_info *alloc_thread_info_node(struct task_struct *tsk,
152 						  int node)
153 {
154 	struct page *page = alloc_kmem_pages_node(node, THREADINFO_GFP,
155 						  THREAD_SIZE_ORDER);
156 
157 	return page ? page_address(page) : NULL;
158 }
159 
free_thread_info(struct thread_info * ti)160 static inline void free_thread_info(struct thread_info *ti)
161 {
162 	free_kmem_pages((unsigned long)ti, THREAD_SIZE_ORDER);
163 }
164 # else
165 static struct kmem_cache *thread_info_cache;
166 
alloc_thread_info_node(struct task_struct * tsk,int node)167 static struct thread_info *alloc_thread_info_node(struct task_struct *tsk,
168 						  int node)
169 {
170 	return kmem_cache_alloc_node(thread_info_cache, THREADINFO_GFP, node);
171 }
172 
free_thread_info(struct thread_info * ti)173 static void free_thread_info(struct thread_info *ti)
174 {
175 	kmem_cache_free(thread_info_cache, ti);
176 }
177 
thread_info_cache_init(void)178 void thread_info_cache_init(void)
179 {
180 	thread_info_cache = kmem_cache_create("thread_info", THREAD_SIZE,
181 					      THREAD_SIZE, 0, NULL);
182 	BUG_ON(thread_info_cache == NULL);
183 }
184 # endif
185 #endif
186 
187 /* SLAB cache for signal_struct structures (tsk->signal) */
188 static struct kmem_cache *signal_cachep;
189 
190 /* SLAB cache for sighand_struct structures (tsk->sighand) */
191 struct kmem_cache *sighand_cachep;
192 
193 /* SLAB cache for files_struct structures (tsk->files) */
194 struct kmem_cache *files_cachep;
195 
196 /* SLAB cache for fs_struct structures (tsk->fs) */
197 struct kmem_cache *fs_cachep;
198 
199 /* SLAB cache for vm_area_struct structures */
200 struct kmem_cache *vm_area_cachep;
201 
202 /* SLAB cache for mm_struct structures (tsk->mm) */
203 static struct kmem_cache *mm_cachep;
204 
205 /* Notifier list called when a task struct is freed */
206 static ATOMIC_NOTIFIER_HEAD(task_free_notifier);
207 
account_kernel_stack(struct thread_info * ti,int account)208 static void account_kernel_stack(struct thread_info *ti, int account)
209 {
210 	struct zone *zone = page_zone(virt_to_page(ti));
211 
212 	mod_zone_page_state(zone, NR_KERNEL_STACK, account);
213 }
214 
free_task(struct task_struct * tsk)215 void free_task(struct task_struct *tsk)
216 {
217 	account_kernel_stack(tsk->stack, -1);
218 	arch_release_thread_info(tsk->stack);
219 	free_thread_info(tsk->stack);
220 	rt_mutex_debug_task_free(tsk);
221 	ftrace_graph_exit_task(tsk);
222 	put_seccomp_filter(tsk);
223 	arch_release_task_struct(tsk);
224 	free_task_struct(tsk);
225 }
226 EXPORT_SYMBOL(free_task);
227 
free_signal_struct(struct signal_struct * sig)228 static inline void free_signal_struct(struct signal_struct *sig)
229 {
230 	taskstats_tgid_free(sig);
231 	sched_autogroup_exit(sig);
232 	kmem_cache_free(signal_cachep, sig);
233 }
234 
put_signal_struct(struct signal_struct * sig)235 static inline void put_signal_struct(struct signal_struct *sig)
236 {
237 	if (atomic_dec_and_test(&sig->sigcnt))
238 		free_signal_struct(sig);
239 }
240 
task_free_register(struct notifier_block * n)241 int task_free_register(struct notifier_block *n)
242 {
243 	return atomic_notifier_chain_register(&task_free_notifier, n);
244 }
245 EXPORT_SYMBOL(task_free_register);
246 
task_free_unregister(struct notifier_block * n)247 int task_free_unregister(struct notifier_block *n)
248 {
249 	return atomic_notifier_chain_unregister(&task_free_notifier, n);
250 }
251 EXPORT_SYMBOL(task_free_unregister);
252 
__put_task_struct(struct task_struct * tsk)253 void __put_task_struct(struct task_struct *tsk)
254 {
255 	WARN_ON(!tsk->exit_state);
256 	WARN_ON(atomic_read(&tsk->usage));
257 	WARN_ON(tsk == current);
258 
259 	task_numa_free(tsk);
260 	security_task_free(tsk);
261 	exit_creds(tsk);
262 	delayacct_tsk_free(tsk);
263 	put_signal_struct(tsk->signal);
264 
265 	atomic_notifier_call_chain(&task_free_notifier, 0, tsk);
266 	if (!profile_handoff_task(tsk))
267 		free_task(tsk);
268 }
269 EXPORT_SYMBOL_GPL(__put_task_struct);
270 
arch_task_cache_init(void)271 void __init __weak arch_task_cache_init(void) { }
272 
fork_init(unsigned long mempages)273 void __init fork_init(unsigned long mempages)
274 {
275 #ifndef CONFIG_ARCH_TASK_STRUCT_ALLOCATOR
276 #ifndef ARCH_MIN_TASKALIGN
277 #define ARCH_MIN_TASKALIGN	L1_CACHE_BYTES
278 #endif
279 	/* create a slab on which task_structs can be allocated */
280 	task_struct_cachep =
281 		kmem_cache_create("task_struct", sizeof(struct task_struct),
282 			ARCH_MIN_TASKALIGN, SLAB_PANIC | SLAB_NOTRACK, NULL);
283 #endif
284 
285 	/* do the arch specific task caches init */
286 	arch_task_cache_init();
287 
288 	/*
289 	 * The default maximum number of threads is set to a safe
290 	 * value: the thread structures can take up at most half
291 	 * of memory.
292 	 */
293 	max_threads = mempages / (8 * THREAD_SIZE / PAGE_SIZE);
294 
295 	/*
296 	 * we need to allow at least 20 threads to boot a system
297 	 */
298 	if (max_threads < 20)
299 		max_threads = 20;
300 
301 	init_task.signal->rlim[RLIMIT_NPROC].rlim_cur = max_threads/2;
302 	init_task.signal->rlim[RLIMIT_NPROC].rlim_max = max_threads/2;
303 	init_task.signal->rlim[RLIMIT_SIGPENDING] =
304 		init_task.signal->rlim[RLIMIT_NPROC];
305 }
306 
arch_dup_task_struct(struct task_struct * dst,struct task_struct * src)307 int __weak arch_dup_task_struct(struct task_struct *dst,
308 					       struct task_struct *src)
309 {
310 	*dst = *src;
311 	return 0;
312 }
313 
set_task_stack_end_magic(struct task_struct * tsk)314 void set_task_stack_end_magic(struct task_struct *tsk)
315 {
316 	unsigned long *stackend;
317 
318 	stackend = end_of_stack(tsk);
319 	*stackend = STACK_END_MAGIC;	/* for overflow detection */
320 }
321 
dup_task_struct(struct task_struct * orig)322 static struct task_struct *dup_task_struct(struct task_struct *orig)
323 {
324 	struct task_struct *tsk;
325 	struct thread_info *ti;
326 	int node = tsk_fork_get_node(orig);
327 	int err;
328 
329 	tsk = alloc_task_struct_node(node);
330 	if (!tsk)
331 		return NULL;
332 
333 	ti = alloc_thread_info_node(tsk, node);
334 	if (!ti)
335 		goto free_tsk;
336 
337 	err = arch_dup_task_struct(tsk, orig);
338 	if (err)
339 		goto free_ti;
340 
341 	tsk->stack = ti;
342 #ifdef CONFIG_SECCOMP
343 	/*
344 	 * We must handle setting up seccomp filters once we're under
345 	 * the sighand lock in case orig has changed between now and
346 	 * then. Until then, filter must be NULL to avoid messing up
347 	 * the usage counts on the error path calling free_task.
348 	 */
349 	tsk->seccomp.filter = NULL;
350 #endif
351 
352 	setup_thread_stack(tsk, orig);
353 	clear_user_return_notifier(tsk);
354 	clear_tsk_need_resched(tsk);
355 	set_task_stack_end_magic(tsk);
356 
357 #ifdef CONFIG_CC_STACKPROTECTOR
358 	tsk->stack_canary = get_random_long();
359 #endif
360 
361 	/*
362 	 * One for us, one for whoever does the "release_task()" (usually
363 	 * parent)
364 	 */
365 	atomic_set(&tsk->usage, 2);
366 #ifdef CONFIG_BLK_DEV_IO_TRACE
367 	tsk->btrace_seq = 0;
368 #endif
369 	tsk->splice_pipe = NULL;
370 	tsk->task_frag.page = NULL;
371 
372 	account_kernel_stack(ti, 1);
373 
374 	kcov_task_init(tsk);
375 
376 	return tsk;
377 
378 free_ti:
379 	free_thread_info(ti);
380 free_tsk:
381 	free_task_struct(tsk);
382 	return NULL;
383 }
384 
385 #ifdef CONFIG_MMU
dup_mmap(struct mm_struct * mm,struct mm_struct * oldmm)386 static int dup_mmap(struct mm_struct *mm, struct mm_struct *oldmm)
387 {
388 	struct vm_area_struct *mpnt, *tmp, *prev, **pprev;
389 	struct rb_node **rb_link, *rb_parent;
390 	int retval;
391 	unsigned long charge;
392 
393 	uprobe_start_dup_mmap();
394 	down_write(&oldmm->mmap_sem);
395 	flush_cache_dup_mm(oldmm);
396 	uprobe_dup_mmap(oldmm, mm);
397 	/*
398 	 * Not linked in yet - no deadlock potential:
399 	 */
400 	down_write_nested(&mm->mmap_sem, SINGLE_DEPTH_NESTING);
401 
402 	mm->total_vm = oldmm->total_vm;
403 	mm->shared_vm = oldmm->shared_vm;
404 	mm->exec_vm = oldmm->exec_vm;
405 	mm->stack_vm = oldmm->stack_vm;
406 
407 	rb_link = &mm->mm_rb.rb_node;
408 	rb_parent = NULL;
409 	pprev = &mm->mmap;
410 	retval = ksm_fork(mm, oldmm);
411 	if (retval)
412 		goto out;
413 	retval = khugepaged_fork(mm, oldmm);
414 	if (retval)
415 		goto out;
416 
417 	prev = NULL;
418 	for (mpnt = oldmm->mmap; mpnt; mpnt = mpnt->vm_next) {
419 		struct file *file;
420 
421 		if (mpnt->vm_flags & VM_DONTCOPY) {
422 			vm_stat_account(mm, mpnt->vm_flags, mpnt->vm_file,
423 							-vma_pages(mpnt));
424 			continue;
425 		}
426 		charge = 0;
427 		if (mpnt->vm_flags & VM_ACCOUNT) {
428 			unsigned long len = vma_pages(mpnt);
429 
430 			if (security_vm_enough_memory_mm(oldmm, len)) /* sic */
431 				goto fail_nomem;
432 			charge = len;
433 		}
434 		tmp = kmem_cache_alloc(vm_area_cachep, GFP_KERNEL);
435 		if (!tmp)
436 			goto fail_nomem;
437 		*tmp = *mpnt;
438 		INIT_LIST_HEAD(&tmp->anon_vma_chain);
439 		retval = vma_dup_policy(mpnt, tmp);
440 		if (retval)
441 			goto fail_nomem_policy;
442 		tmp->vm_mm = mm;
443 		if (anon_vma_fork(tmp, mpnt))
444 			goto fail_nomem_anon_vma_fork;
445 		tmp->vm_flags &= ~VM_LOCKED;
446 		tmp->vm_next = tmp->vm_prev = NULL;
447 		file = tmp->vm_file;
448 		if (file) {
449 			struct inode *inode = file_inode(file);
450 			struct address_space *mapping = file->f_mapping;
451 
452 			get_file(file);
453 			if (tmp->vm_flags & VM_DENYWRITE)
454 				atomic_dec(&inode->i_writecount);
455 			mutex_lock(&mapping->i_mmap_mutex);
456 			if (tmp->vm_flags & VM_SHARED)
457 				atomic_inc(&mapping->i_mmap_writable);
458 			flush_dcache_mmap_lock(mapping);
459 			/* insert tmp into the share list, just after mpnt */
460 			if (unlikely(tmp->vm_flags & VM_NONLINEAR))
461 				vma_nonlinear_insert(tmp,
462 						&mapping->i_mmap_nonlinear);
463 			else
464 				vma_interval_tree_insert_after(tmp, mpnt,
465 							&mapping->i_mmap);
466 			flush_dcache_mmap_unlock(mapping);
467 			mutex_unlock(&mapping->i_mmap_mutex);
468 		}
469 
470 		/*
471 		 * Clear hugetlb-related page reserves for children. This only
472 		 * affects MAP_PRIVATE mappings. Faults generated by the child
473 		 * are not guaranteed to succeed, even if read-only
474 		 */
475 		if (is_vm_hugetlb_page(tmp))
476 			reset_vma_resv_huge_pages(tmp);
477 
478 		/*
479 		 * Link in the new vma and copy the page table entries.
480 		 */
481 		*pprev = tmp;
482 		pprev = &tmp->vm_next;
483 		tmp->vm_prev = prev;
484 		prev = tmp;
485 
486 		__vma_link_rb(mm, tmp, rb_link, rb_parent);
487 		rb_link = &tmp->vm_rb.rb_right;
488 		rb_parent = &tmp->vm_rb;
489 
490 		mm->map_count++;
491 		retval = copy_page_range(mm, oldmm, mpnt);
492 
493 		if (tmp->vm_ops && tmp->vm_ops->open)
494 			tmp->vm_ops->open(tmp);
495 
496 		if (retval)
497 			goto out;
498 	}
499 	/* a new mm has just been created */
500 	arch_dup_mmap(oldmm, mm);
501 	retval = 0;
502 out:
503 	up_write(&mm->mmap_sem);
504 	flush_tlb_mm(oldmm);
505 	up_write(&oldmm->mmap_sem);
506 	uprobe_end_dup_mmap();
507 	return retval;
508 fail_nomem_anon_vma_fork:
509 	mpol_put(vma_policy(tmp));
510 fail_nomem_policy:
511 	kmem_cache_free(vm_area_cachep, tmp);
512 fail_nomem:
513 	retval = -ENOMEM;
514 	vm_unacct_memory(charge);
515 	goto out;
516 }
517 
mm_alloc_pgd(struct mm_struct * mm)518 static inline int mm_alloc_pgd(struct mm_struct *mm)
519 {
520 	mm->pgd = pgd_alloc(mm);
521 	if (unlikely(!mm->pgd))
522 		return -ENOMEM;
523 	return 0;
524 }
525 
mm_free_pgd(struct mm_struct * mm)526 static inline void mm_free_pgd(struct mm_struct *mm)
527 {
528 	pgd_free(mm, mm->pgd);
529 }
530 #else
531 #define dup_mmap(mm, oldmm)	(0)
532 #define mm_alloc_pgd(mm)	(0)
533 #define mm_free_pgd(mm)
534 #endif /* CONFIG_MMU */
535 
536 __cacheline_aligned_in_smp DEFINE_SPINLOCK(mmlist_lock);
537 
538 #define allocate_mm()	(kmem_cache_alloc(mm_cachep, GFP_KERNEL))
539 #define free_mm(mm)	(kmem_cache_free(mm_cachep, (mm)))
540 
541 static unsigned long default_dump_filter = MMF_DUMP_FILTER_DEFAULT;
542 
coredump_filter_setup(char * s)543 static int __init coredump_filter_setup(char *s)
544 {
545 	default_dump_filter =
546 		(simple_strtoul(s, NULL, 0) << MMF_DUMP_FILTER_SHIFT) &
547 		MMF_DUMP_FILTER_MASK;
548 	return 1;
549 }
550 
551 __setup("coredump_filter=", coredump_filter_setup);
552 
553 #include <linux/init_task.h>
554 
mm_init_aio(struct mm_struct * mm)555 static void mm_init_aio(struct mm_struct *mm)
556 {
557 #ifdef CONFIG_AIO
558 	spin_lock_init(&mm->ioctx_lock);
559 	mm->ioctx_table = NULL;
560 #endif
561 }
562 
mm_init_owner(struct mm_struct * mm,struct task_struct * p)563 static void mm_init_owner(struct mm_struct *mm, struct task_struct *p)
564 {
565 #ifdef CONFIG_MEMCG
566 	mm->owner = p;
567 #endif
568 }
569 
mm_init(struct mm_struct * mm,struct task_struct * p)570 static struct mm_struct *mm_init(struct mm_struct *mm, struct task_struct *p)
571 {
572 	mm->mmap = NULL;
573 	mm->mm_rb = RB_ROOT;
574 	mm->vmacache_seqnum = 0;
575 	atomic_set(&mm->mm_users, 1);
576 	atomic_set(&mm->mm_count, 1);
577 	init_rwsem(&mm->mmap_sem);
578 	INIT_LIST_HEAD(&mm->mmlist);
579 	mm->core_state = NULL;
580 	atomic_long_set(&mm->nr_ptes, 0);
581 	mm->map_count = 0;
582 	mm->locked_vm = 0;
583 	mm->pinned_vm = 0;
584 	memset(&mm->rss_stat, 0, sizeof(mm->rss_stat));
585 	spin_lock_init(&mm->page_table_lock);
586 	mm_init_cpumask(mm);
587 	mm_init_aio(mm);
588 	mm_init_owner(mm, p);
589 	mmu_notifier_mm_init(mm);
590 	clear_tlb_flush_pending(mm);
591 #if defined(CONFIG_TRANSPARENT_HUGEPAGE) && !USE_SPLIT_PMD_PTLOCKS
592 	mm->pmd_huge_pte = NULL;
593 #endif
594 
595 	if (current->mm) {
596 		mm->flags = current->mm->flags & MMF_INIT_MASK;
597 		mm->def_flags = current->mm->def_flags & VM_INIT_DEF_MASK;
598 	} else {
599 		mm->flags = default_dump_filter;
600 		mm->def_flags = 0;
601 	}
602 
603 	if (mm_alloc_pgd(mm))
604 		goto fail_nopgd;
605 
606 	if (init_new_context(p, mm))
607 		goto fail_nocontext;
608 
609 	return mm;
610 
611 fail_nocontext:
612 	mm_free_pgd(mm);
613 fail_nopgd:
614 	free_mm(mm);
615 	return NULL;
616 }
617 
check_mm(struct mm_struct * mm)618 static void check_mm(struct mm_struct *mm)
619 {
620 	int i;
621 
622 	for (i = 0; i < NR_MM_COUNTERS; i++) {
623 		long x = atomic_long_read(&mm->rss_stat.count[i]);
624 
625 		if (unlikely(x))
626 			printk(KERN_ALERT "BUG: Bad rss-counter state "
627 					  "mm:%p idx:%d val:%ld\n", mm, i, x);
628 	}
629 #if defined(CONFIG_TRANSPARENT_HUGEPAGE) && !USE_SPLIT_PMD_PTLOCKS
630 	VM_BUG_ON_MM(mm->pmd_huge_pte, mm);
631 #endif
632 }
633 
634 /*
635  * Allocate and initialize an mm_struct.
636  */
mm_alloc(void)637 struct mm_struct *mm_alloc(void)
638 {
639 	struct mm_struct *mm;
640 
641 	mm = allocate_mm();
642 	if (!mm)
643 		return NULL;
644 
645 	memset(mm, 0, sizeof(*mm));
646 	return mm_init(mm, current);
647 }
648 
649 /*
650  * Called when the last reference to the mm
651  * is dropped: either by a lazy thread or by
652  * mmput. Free the page directory and the mm.
653  */
__mmdrop(struct mm_struct * mm)654 void __mmdrop(struct mm_struct *mm)
655 {
656 	BUG_ON(mm == &init_mm);
657 	mm_free_pgd(mm);
658 	destroy_context(mm);
659 	mmu_notifier_mm_destroy(mm);
660 	check_mm(mm);
661 	free_mm(mm);
662 }
663 EXPORT_SYMBOL_GPL(__mmdrop);
664 
__mmput(struct mm_struct * mm)665 static inline void __mmput(struct mm_struct *mm)
666 {
667 	VM_BUG_ON(atomic_read(&mm->mm_users));
668 
669 	uprobe_clear_state(mm);
670 	exit_aio(mm);
671 	ksm_exit(mm);
672 	khugepaged_exit(mm); /* must run before exit_mmap */
673 	exit_mmap(mm);
674 	set_mm_exe_file(mm, NULL);
675 	if (!list_empty(&mm->mmlist)) {
676 		spin_lock(&mmlist_lock);
677 		list_del(&mm->mmlist);
678 		spin_unlock(&mmlist_lock);
679 	}
680 	if (mm->binfmt)
681 		module_put(mm->binfmt->module);
682 	mmdrop(mm);
683 }
684 
685 /*
686  * Decrement the use count and release all resources for an mm.
687  */
mmput(struct mm_struct * mm)688 void mmput(struct mm_struct *mm)
689 {
690 	might_sleep();
691 
692 	if (atomic_dec_and_test(&mm->mm_users))
693 		__mmput(mm);
694 }
695 EXPORT_SYMBOL_GPL(mmput);
696 
mmput_async_fn(struct work_struct * work)697 static void mmput_async_fn(struct work_struct *work)
698 {
699 	struct mm_struct *mm = container_of(work, struct mm_struct, async_put_work);
700 	__mmput(mm);
701 }
702 
mmput_async(struct mm_struct * mm)703 void mmput_async(struct mm_struct *mm)
704 {
705 	if (atomic_dec_and_test(&mm->mm_users)) {
706 		INIT_WORK(&mm->async_put_work, mmput_async_fn);
707 		schedule_work(&mm->async_put_work);
708 	}
709 }
710 
set_mm_exe_file(struct mm_struct * mm,struct file * new_exe_file)711 void set_mm_exe_file(struct mm_struct *mm, struct file *new_exe_file)
712 {
713 	if (new_exe_file)
714 		get_file(new_exe_file);
715 	if (mm->exe_file)
716 		fput(mm->exe_file);
717 	mm->exe_file = new_exe_file;
718 }
719 
get_mm_exe_file(struct mm_struct * mm)720 struct file *get_mm_exe_file(struct mm_struct *mm)
721 {
722 	struct file *exe_file;
723 
724 	/* We need mmap_sem to protect against races with removal of exe_file */
725 	down_read(&mm->mmap_sem);
726 	exe_file = mm->exe_file;
727 	if (exe_file)
728 		get_file(exe_file);
729 	up_read(&mm->mmap_sem);
730 	return exe_file;
731 }
732 
dup_mm_exe_file(struct mm_struct * oldmm,struct mm_struct * newmm)733 static void dup_mm_exe_file(struct mm_struct *oldmm, struct mm_struct *newmm)
734 {
735 	/* It's safe to write the exe_file pointer without exe_file_lock because
736 	 * this is called during fork when the task is not yet in /proc */
737 	newmm->exe_file = get_mm_exe_file(oldmm);
738 }
739 
740 /**
741  * get_task_mm - acquire a reference to the task's mm
742  *
743  * Returns %NULL if the task has no mm.  Checks PF_KTHREAD (meaning
744  * this kernel workthread has transiently adopted a user mm with use_mm,
745  * to do its AIO) is not set and if so returns a reference to it, after
746  * bumping up the use count.  User must release the mm via mmput()
747  * after use.  Typically used by /proc and ptrace.
748  */
get_task_mm(struct task_struct * task)749 struct mm_struct *get_task_mm(struct task_struct *task)
750 {
751 	struct mm_struct *mm;
752 
753 	task_lock(task);
754 	mm = task->mm;
755 	if (mm) {
756 		if (task->flags & PF_KTHREAD)
757 			mm = NULL;
758 		else
759 			atomic_inc(&mm->mm_users);
760 	}
761 	task_unlock(task);
762 	return mm;
763 }
764 EXPORT_SYMBOL_GPL(get_task_mm);
765 
mm_access(struct task_struct * task,unsigned int mode)766 struct mm_struct *mm_access(struct task_struct *task, unsigned int mode)
767 {
768 	struct mm_struct *mm;
769 	int err;
770 
771 	err =  mutex_lock_killable(&task->signal->cred_guard_mutex);
772 	if (err)
773 		return ERR_PTR(err);
774 
775 	mm = get_task_mm(task);
776 	if (mm && mm != current->mm &&
777 			!ptrace_may_access(task, mode)) {
778 		mmput(mm);
779 		mm = ERR_PTR(-EACCES);
780 	}
781 	mutex_unlock(&task->signal->cred_guard_mutex);
782 
783 	return mm;
784 }
785 
complete_vfork_done(struct task_struct * tsk)786 static void complete_vfork_done(struct task_struct *tsk)
787 {
788 	struct completion *vfork;
789 
790 	task_lock(tsk);
791 	vfork = tsk->vfork_done;
792 	if (likely(vfork)) {
793 		tsk->vfork_done = NULL;
794 		complete(vfork);
795 	}
796 	task_unlock(tsk);
797 }
798 
wait_for_vfork_done(struct task_struct * child,struct completion * vfork)799 static int wait_for_vfork_done(struct task_struct *child,
800 				struct completion *vfork)
801 {
802 	int killed;
803 
804 	freezer_do_not_count();
805 	killed = wait_for_completion_killable(vfork);
806 	freezer_count();
807 
808 	if (killed) {
809 		task_lock(child);
810 		child->vfork_done = NULL;
811 		task_unlock(child);
812 	}
813 
814 	put_task_struct(child);
815 	return killed;
816 }
817 
818 /* Please note the differences between mmput and mm_release.
819  * mmput is called whenever we stop holding onto a mm_struct,
820  * error success whatever.
821  *
822  * mm_release is called after a mm_struct has been removed
823  * from the current process.
824  *
825  * This difference is important for error handling, when we
826  * only half set up a mm_struct for a new process and need to restore
827  * the old one.  Because we mmput the new mm_struct before
828  * restoring the old one. . .
829  * Eric Biederman 10 January 1998
830  */
mm_release(struct task_struct * tsk,struct mm_struct * mm)831 void mm_release(struct task_struct *tsk, struct mm_struct *mm)
832 {
833 	/* Get rid of any futexes when releasing the mm */
834 #ifdef CONFIG_FUTEX
835 	if (unlikely(tsk->robust_list)) {
836 		exit_robust_list(tsk);
837 		tsk->robust_list = NULL;
838 	}
839 #ifdef CONFIG_COMPAT
840 	if (unlikely(tsk->compat_robust_list)) {
841 		compat_exit_robust_list(tsk);
842 		tsk->compat_robust_list = NULL;
843 	}
844 #endif
845 	if (unlikely(!list_empty(&tsk->pi_state_list)))
846 		exit_pi_state_list(tsk);
847 #endif
848 
849 	uprobe_free_utask(tsk);
850 
851 	/* Get rid of any cached register state */
852 	deactivate_mm(tsk, mm);
853 
854 	/*
855 	 * If we're exiting normally, clear a user-space tid field if
856 	 * requested.  We leave this alone when dying by signal, to leave
857 	 * the value intact in a core dump, and to save the unnecessary
858 	 * trouble, say, a killed vfork parent shouldn't touch this mm.
859 	 * Userland only wants this done for a sys_exit.
860 	 */
861 	if (tsk->clear_child_tid) {
862 		if (!(tsk->flags & PF_SIGNALED) &&
863 		    atomic_read(&mm->mm_users) > 1) {
864 			/*
865 			 * We don't check the error code - if userspace has
866 			 * not set up a proper pointer then tough luck.
867 			 */
868 			put_user(0, tsk->clear_child_tid);
869 			sys_futex(tsk->clear_child_tid, FUTEX_WAKE,
870 					1, NULL, NULL, 0);
871 		}
872 		tsk->clear_child_tid = NULL;
873 	}
874 
875 	/*
876 	 * All done, finally we can wake up parent and return this mm to him.
877 	 * Also kthread_stop() uses this completion for synchronization.
878 	 */
879 	if (tsk->vfork_done)
880 		complete_vfork_done(tsk);
881 }
882 
883 /*
884  * Allocate a new mm structure and copy contents from the
885  * mm structure of the passed in task structure.
886  */
dup_mm(struct task_struct * tsk)887 static struct mm_struct *dup_mm(struct task_struct *tsk)
888 {
889 	struct mm_struct *mm, *oldmm = current->mm;
890 	int err;
891 
892 	mm = allocate_mm();
893 	if (!mm)
894 		goto fail_nomem;
895 
896 	memcpy(mm, oldmm, sizeof(*mm));
897 
898 	if (!mm_init(mm, tsk))
899 		goto fail_nomem;
900 
901 	dup_mm_exe_file(oldmm, mm);
902 
903 	err = dup_mmap(mm, oldmm);
904 	if (err)
905 		goto free_pt;
906 
907 	mm->hiwater_rss = get_mm_rss(mm);
908 	mm->hiwater_vm = mm->total_vm;
909 
910 	if (mm->binfmt && !try_module_get(mm->binfmt->module))
911 		goto free_pt;
912 
913 	return mm;
914 
915 free_pt:
916 	/* don't put binfmt in mmput, we haven't got module yet */
917 	mm->binfmt = NULL;
918 	mmput(mm);
919 
920 fail_nomem:
921 	return NULL;
922 }
923 
copy_mm(unsigned long clone_flags,struct task_struct * tsk)924 static int copy_mm(unsigned long clone_flags, struct task_struct *tsk)
925 {
926 	struct mm_struct *mm, *oldmm;
927 	int retval;
928 
929 	tsk->min_flt = tsk->maj_flt = 0;
930 	tsk->nvcsw = tsk->nivcsw = 0;
931 #ifdef CONFIG_DETECT_HUNG_TASK
932 	tsk->last_switch_count = tsk->nvcsw + tsk->nivcsw;
933 #endif
934 
935 	tsk->mm = NULL;
936 	tsk->active_mm = NULL;
937 
938 	/*
939 	 * Are we cloning a kernel thread?
940 	 *
941 	 * We need to steal a active VM for that..
942 	 */
943 	oldmm = current->mm;
944 	if (!oldmm)
945 		return 0;
946 
947 	/* initialize the new vmacache entries */
948 	vmacache_flush(tsk);
949 
950 	if (clone_flags & CLONE_VM) {
951 		atomic_inc(&oldmm->mm_users);
952 		mm = oldmm;
953 		goto good_mm;
954 	}
955 
956 	retval = -ENOMEM;
957 	mm = dup_mm(tsk);
958 	if (!mm)
959 		goto fail_nomem;
960 
961 good_mm:
962 	tsk->mm = mm;
963 	tsk->active_mm = mm;
964 	return 0;
965 
966 fail_nomem:
967 	return retval;
968 }
969 
copy_fs(unsigned long clone_flags,struct task_struct * tsk)970 static int copy_fs(unsigned long clone_flags, struct task_struct *tsk)
971 {
972 	struct fs_struct *fs = current->fs;
973 	if (clone_flags & CLONE_FS) {
974 		/* tsk->fs is already what we want */
975 		spin_lock(&fs->lock);
976 		if (fs->in_exec) {
977 			spin_unlock(&fs->lock);
978 			return -EAGAIN;
979 		}
980 		fs->users++;
981 		spin_unlock(&fs->lock);
982 		return 0;
983 	}
984 	tsk->fs = copy_fs_struct(fs);
985 	if (!tsk->fs)
986 		return -ENOMEM;
987 	return 0;
988 }
989 
copy_files(unsigned long clone_flags,struct task_struct * tsk)990 static int copy_files(unsigned long clone_flags, struct task_struct *tsk)
991 {
992 	struct files_struct *oldf, *newf;
993 	int error = 0;
994 
995 	/*
996 	 * A background process may not have any files ...
997 	 */
998 	oldf = current->files;
999 	if (!oldf)
1000 		goto out;
1001 
1002 	if (clone_flags & CLONE_FILES) {
1003 		atomic_inc(&oldf->count);
1004 		goto out;
1005 	}
1006 
1007 	newf = dup_fd(oldf, &error);
1008 	if (!newf)
1009 		goto out;
1010 
1011 	tsk->files = newf;
1012 	error = 0;
1013 out:
1014 	return error;
1015 }
1016 
copy_io(unsigned long clone_flags,struct task_struct * tsk)1017 static int copy_io(unsigned long clone_flags, struct task_struct *tsk)
1018 {
1019 #ifdef CONFIG_BLOCK
1020 	struct io_context *ioc = current->io_context;
1021 	struct io_context *new_ioc;
1022 
1023 	if (!ioc)
1024 		return 0;
1025 	/*
1026 	 * Share io context with parent, if CLONE_IO is set
1027 	 */
1028 	if (clone_flags & CLONE_IO) {
1029 		ioc_task_link(ioc);
1030 		tsk->io_context = ioc;
1031 	} else if (ioprio_valid(ioc->ioprio)) {
1032 		new_ioc = get_task_io_context(tsk, GFP_KERNEL, NUMA_NO_NODE);
1033 		if (unlikely(!new_ioc))
1034 			return -ENOMEM;
1035 
1036 		new_ioc->ioprio = ioc->ioprio;
1037 		put_io_context(new_ioc);
1038 	}
1039 #endif
1040 	return 0;
1041 }
1042 
copy_sighand(unsigned long clone_flags,struct task_struct * tsk)1043 static int copy_sighand(unsigned long clone_flags, struct task_struct *tsk)
1044 {
1045 	struct sighand_struct *sig;
1046 
1047 	if (clone_flags & CLONE_SIGHAND) {
1048 		atomic_inc(&current->sighand->count);
1049 		return 0;
1050 	}
1051 	sig = kmem_cache_alloc(sighand_cachep, GFP_KERNEL);
1052 	rcu_assign_pointer(tsk->sighand, sig);
1053 	if (!sig)
1054 		return -ENOMEM;
1055 	atomic_set(&sig->count, 1);
1056 	memcpy(sig->action, current->sighand->action, sizeof(sig->action));
1057 	return 0;
1058 }
1059 
__cleanup_sighand(struct sighand_struct * sighand)1060 void __cleanup_sighand(struct sighand_struct *sighand)
1061 {
1062 	if (atomic_dec_and_test(&sighand->count)) {
1063 		signalfd_cleanup(sighand);
1064 		kmem_cache_free(sighand_cachep, sighand);
1065 	}
1066 }
1067 
1068 
1069 /*
1070  * Initialize POSIX timer handling for a thread group.
1071  */
posix_cpu_timers_init_group(struct signal_struct * sig)1072 static void posix_cpu_timers_init_group(struct signal_struct *sig)
1073 {
1074 	unsigned long cpu_limit;
1075 
1076 	/* Thread group counters. */
1077 	thread_group_cputime_init(sig);
1078 
1079 	cpu_limit = READ_ONCE(sig->rlim[RLIMIT_CPU].rlim_cur);
1080 	if (cpu_limit != RLIM_INFINITY) {
1081 		sig->cputime_expires.prof_exp = secs_to_cputime(cpu_limit);
1082 		sig->cputimer.running = 1;
1083 	}
1084 
1085 	/* The timer lists. */
1086 	INIT_LIST_HEAD(&sig->cpu_timers[0]);
1087 	INIT_LIST_HEAD(&sig->cpu_timers[1]);
1088 	INIT_LIST_HEAD(&sig->cpu_timers[2]);
1089 }
1090 
copy_signal(unsigned long clone_flags,struct task_struct * tsk)1091 static int copy_signal(unsigned long clone_flags, struct task_struct *tsk)
1092 {
1093 	struct signal_struct *sig;
1094 
1095 	if (clone_flags & CLONE_THREAD)
1096 		return 0;
1097 
1098 	sig = kmem_cache_zalloc(signal_cachep, GFP_KERNEL);
1099 	tsk->signal = sig;
1100 	if (!sig)
1101 		return -ENOMEM;
1102 
1103 	sig->nr_threads = 1;
1104 	atomic_set(&sig->live, 1);
1105 	atomic_set(&sig->sigcnt, 1);
1106 
1107 	/* list_add(thread_node, thread_head) without INIT_LIST_HEAD() */
1108 	sig->thread_head = (struct list_head)LIST_HEAD_INIT(tsk->thread_node);
1109 	tsk->thread_node = (struct list_head)LIST_HEAD_INIT(sig->thread_head);
1110 
1111 	init_waitqueue_head(&sig->wait_chldexit);
1112 	sig->curr_target = tsk;
1113 	init_sigpending(&sig->shared_pending);
1114 	INIT_LIST_HEAD(&sig->posix_timers);
1115 	seqlock_init(&sig->stats_lock);
1116 
1117 	hrtimer_init(&sig->real_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
1118 	sig->real_timer.function = it_real_fn;
1119 
1120 	task_lock(current->group_leader);
1121 	memcpy(sig->rlim, current->signal->rlim, sizeof sig->rlim);
1122 	task_unlock(current->group_leader);
1123 
1124 	posix_cpu_timers_init_group(sig);
1125 
1126 	tty_audit_fork(sig);
1127 	sched_autogroup_fork(sig);
1128 
1129 #ifdef CONFIG_CGROUPS
1130 	init_rwsem(&sig->group_rwsem);
1131 #endif
1132 
1133 	sig->oom_score_adj = current->signal->oom_score_adj;
1134 	sig->oom_score_adj_min = current->signal->oom_score_adj_min;
1135 
1136 	sig->has_child_subreaper = current->signal->has_child_subreaper ||
1137 				   current->signal->is_child_subreaper;
1138 
1139 	mutex_init(&sig->cred_guard_mutex);
1140 
1141 	return 0;
1142 }
1143 
copy_seccomp(struct task_struct * p)1144 static void copy_seccomp(struct task_struct *p)
1145 {
1146 #ifdef CONFIG_SECCOMP
1147 	/*
1148 	 * Must be called with sighand->lock held, which is common to
1149 	 * all threads in the group. Holding cred_guard_mutex is not
1150 	 * needed because this new task is not yet running and cannot
1151 	 * be racing exec.
1152 	 */
1153 	assert_spin_locked(&current->sighand->siglock);
1154 
1155 	/* Ref-count the new filter user, and assign it. */
1156 	get_seccomp_filter(current);
1157 	p->seccomp = current->seccomp;
1158 
1159 	/*
1160 	 * Explicitly enable no_new_privs here in case it got set
1161 	 * between the task_struct being duplicated and holding the
1162 	 * sighand lock. The seccomp state and nnp must be in sync.
1163 	 */
1164 	if (task_no_new_privs(current))
1165 		task_set_no_new_privs(p);
1166 
1167 	/*
1168 	 * If the parent gained a seccomp mode after copying thread
1169 	 * flags and between before we held the sighand lock, we have
1170 	 * to manually enable the seccomp thread flag here.
1171 	 */
1172 	if (p->seccomp.mode != SECCOMP_MODE_DISABLED)
1173 		set_tsk_thread_flag(p, TIF_SECCOMP);
1174 #endif
1175 }
1176 
SYSCALL_DEFINE1(set_tid_address,int __user *,tidptr)1177 SYSCALL_DEFINE1(set_tid_address, int __user *, tidptr)
1178 {
1179 	current->clear_child_tid = tidptr;
1180 
1181 	return task_pid_vnr(current);
1182 }
1183 
rt_mutex_init_task(struct task_struct * p)1184 static void rt_mutex_init_task(struct task_struct *p)
1185 {
1186 	raw_spin_lock_init(&p->pi_lock);
1187 #ifdef CONFIG_RT_MUTEXES
1188 	p->pi_waiters = RB_ROOT;
1189 	p->pi_waiters_leftmost = NULL;
1190 	p->pi_blocked_on = NULL;
1191 #endif
1192 }
1193 
1194 /*
1195  * Initialize POSIX timer handling for a single task.
1196  */
posix_cpu_timers_init(struct task_struct * tsk)1197 static void posix_cpu_timers_init(struct task_struct *tsk)
1198 {
1199 	tsk->cputime_expires.prof_exp = 0;
1200 	tsk->cputime_expires.virt_exp = 0;
1201 	tsk->cputime_expires.sched_exp = 0;
1202 	INIT_LIST_HEAD(&tsk->cpu_timers[0]);
1203 	INIT_LIST_HEAD(&tsk->cpu_timers[1]);
1204 	INIT_LIST_HEAD(&tsk->cpu_timers[2]);
1205 }
1206 
1207 static inline void
init_task_pid(struct task_struct * task,enum pid_type type,struct pid * pid)1208 init_task_pid(struct task_struct *task, enum pid_type type, struct pid *pid)
1209 {
1210 	 task->pids[type].pid = pid;
1211 }
1212 
1213 /*
1214  * This creates a new process as a copy of the old one,
1215  * but does not actually start it yet.
1216  *
1217  * It copies the registers, and all the appropriate
1218  * parts of the process environment (as per the clone
1219  * flags). The actual kick-off is left to the caller.
1220  */
copy_process(unsigned long clone_flags,unsigned long stack_start,unsigned long stack_size,int __user * child_tidptr,struct pid * pid,int trace)1221 static struct task_struct *copy_process(unsigned long clone_flags,
1222 					unsigned long stack_start,
1223 					unsigned long stack_size,
1224 					int __user *child_tidptr,
1225 					struct pid *pid,
1226 					int trace)
1227 {
1228 	int retval;
1229 	struct task_struct *p;
1230 
1231 	if ((clone_flags & (CLONE_NEWNS|CLONE_FS)) == (CLONE_NEWNS|CLONE_FS))
1232 		return ERR_PTR(-EINVAL);
1233 
1234 	if ((clone_flags & (CLONE_NEWUSER|CLONE_FS)) == (CLONE_NEWUSER|CLONE_FS))
1235 		return ERR_PTR(-EINVAL);
1236 
1237 	/*
1238 	 * Thread groups must share signals as well, and detached threads
1239 	 * can only be started up within the thread group.
1240 	 */
1241 	if ((clone_flags & CLONE_THREAD) && !(clone_flags & CLONE_SIGHAND))
1242 		return ERR_PTR(-EINVAL);
1243 
1244 	/*
1245 	 * Shared signal handlers imply shared VM. By way of the above,
1246 	 * thread groups also imply shared VM. Blocking this case allows
1247 	 * for various simplifications in other code.
1248 	 */
1249 	if ((clone_flags & CLONE_SIGHAND) && !(clone_flags & CLONE_VM))
1250 		return ERR_PTR(-EINVAL);
1251 
1252 	/*
1253 	 * Siblings of global init remain as zombies on exit since they are
1254 	 * not reaped by their parent (swapper). To solve this and to avoid
1255 	 * multi-rooted process trees, prevent global and container-inits
1256 	 * from creating siblings.
1257 	 */
1258 	if ((clone_flags & CLONE_PARENT) &&
1259 				current->signal->flags & SIGNAL_UNKILLABLE)
1260 		return ERR_PTR(-EINVAL);
1261 
1262 	/*
1263 	 * If the new process will be in a different pid or user namespace
1264 	 * do not allow it to share a thread group or signal handlers or
1265 	 * parent with the forking task.
1266 	 */
1267 	if (clone_flags & CLONE_SIGHAND) {
1268 		if ((clone_flags & (CLONE_NEWUSER | CLONE_NEWPID)) ||
1269 		    (task_active_pid_ns(current) !=
1270 				current->nsproxy->pid_ns_for_children))
1271 			return ERR_PTR(-EINVAL);
1272 	}
1273 
1274 	retval = security_task_create(clone_flags);
1275 	if (retval)
1276 		goto fork_out;
1277 
1278 	retval = -ENOMEM;
1279 	p = dup_task_struct(current);
1280 	if (!p)
1281 		goto fork_out;
1282 
1283 	ftrace_graph_init_task(p);
1284 
1285 	rt_mutex_init_task(p);
1286 
1287 #ifdef CONFIG_PROVE_LOCKING
1288 	DEBUG_LOCKS_WARN_ON(!p->hardirqs_enabled);
1289 	DEBUG_LOCKS_WARN_ON(!p->softirqs_enabled);
1290 #endif
1291 	retval = -EAGAIN;
1292 	if (atomic_read(&p->real_cred->user->processes) >=
1293 			task_rlimit(p, RLIMIT_NPROC)) {
1294 		if (p->real_cred->user != INIT_USER &&
1295 		    !capable(CAP_SYS_RESOURCE) && !capable(CAP_SYS_ADMIN))
1296 			goto bad_fork_free;
1297 	}
1298 	current->flags &= ~PF_NPROC_EXCEEDED;
1299 
1300 	retval = copy_creds(p, clone_flags);
1301 	if (retval < 0)
1302 		goto bad_fork_free;
1303 
1304 	/*
1305 	 * If multiple threads are within copy_process(), then this check
1306 	 * triggers too late. This doesn't hurt, the check is only there
1307 	 * to stop root fork bombs.
1308 	 */
1309 	retval = -EAGAIN;
1310 	if (nr_threads >= max_threads)
1311 		goto bad_fork_cleanup_count;
1312 
1313 	if (!try_module_get(task_thread_info(p)->exec_domain->module))
1314 		goto bad_fork_cleanup_count;
1315 
1316 	delayacct_tsk_init(p);	/* Must remain after dup_task_struct() */
1317 	p->flags &= ~(PF_SUPERPRIV | PF_WQ_WORKER);
1318 	p->flags |= PF_FORKNOEXEC;
1319 	INIT_LIST_HEAD(&p->children);
1320 	INIT_LIST_HEAD(&p->sibling);
1321 	rcu_copy_process(p);
1322 	p->vfork_done = NULL;
1323 	spin_lock_init(&p->alloc_lock);
1324 
1325 	init_sigpending(&p->pending);
1326 
1327 	p->utime = p->stime = p->gtime = 0;
1328 	p->utimescaled = p->stimescaled = 0;
1329 	p->cpu_power = 0;
1330 #ifndef CONFIG_VIRT_CPU_ACCOUNTING_NATIVE
1331 	p->prev_cputime.utime = p->prev_cputime.stime = 0;
1332 #endif
1333 #ifdef CONFIG_VIRT_CPU_ACCOUNTING_GEN
1334 	seqlock_init(&p->vtime_seqlock);
1335 	p->vtime_snap = 0;
1336 	p->vtime_snap_whence = VTIME_SLEEPING;
1337 #endif
1338 
1339 #if defined(SPLIT_RSS_COUNTING)
1340 	memset(&p->rss_stat, 0, sizeof(p->rss_stat));
1341 #endif
1342 
1343 	p->default_timer_slack_ns = current->timer_slack_ns;
1344 
1345 	task_io_accounting_init(&p->ioac);
1346 	acct_clear_integrals(p);
1347 
1348 	posix_cpu_timers_init(p);
1349 
1350 	p->start_time = ktime_get_ns();
1351 	p->real_start_time = ktime_get_boot_ns();
1352 	p->io_context = NULL;
1353 	p->audit_context = NULL;
1354 	if (clone_flags & CLONE_THREAD)
1355 		threadgroup_change_begin(current);
1356 	cgroup_fork(p);
1357 #ifdef CONFIG_NUMA
1358 	p->mempolicy = mpol_dup(p->mempolicy);
1359 	if (IS_ERR(p->mempolicy)) {
1360 		retval = PTR_ERR(p->mempolicy);
1361 		p->mempolicy = NULL;
1362 		goto bad_fork_cleanup_threadgroup_lock;
1363 	}
1364 #endif
1365 #ifdef CONFIG_CPUSETS
1366 	p->cpuset_mem_spread_rotor = NUMA_NO_NODE;
1367 	p->cpuset_slab_spread_rotor = NUMA_NO_NODE;
1368 	seqcount_init(&p->mems_allowed_seq);
1369 #endif
1370 #ifdef CONFIG_TRACE_IRQFLAGS
1371 	p->irq_events = 0;
1372 	p->hardirqs_enabled = 0;
1373 	p->hardirq_enable_ip = 0;
1374 	p->hardirq_enable_event = 0;
1375 	p->hardirq_disable_ip = _THIS_IP_;
1376 	p->hardirq_disable_event = 0;
1377 	p->softirqs_enabled = 1;
1378 	p->softirq_enable_ip = _THIS_IP_;
1379 	p->softirq_enable_event = 0;
1380 	p->softirq_disable_ip = 0;
1381 	p->softirq_disable_event = 0;
1382 	p->hardirq_context = 0;
1383 	p->softirq_context = 0;
1384 #endif
1385 #ifdef CONFIG_LOCKDEP
1386 	p->lockdep_depth = 0; /* no locks held yet */
1387 	p->curr_chain_key = 0;
1388 	p->lockdep_recursion = 0;
1389 #endif
1390 
1391 #ifdef CONFIG_DEBUG_MUTEXES
1392 	p->blocked_on = NULL; /* not blocked yet */
1393 #endif
1394 #ifdef CONFIG_BCACHE
1395 	p->sequential_io	= 0;
1396 	p->sequential_io_avg	= 0;
1397 #endif
1398 
1399 	/* Perform scheduler related setup. Assign this task to a CPU. */
1400 	retval = sched_fork(clone_flags, p);
1401 	if (retval)
1402 		goto bad_fork_cleanup_policy;
1403 
1404 	retval = perf_event_init_task(p);
1405 	if (retval)
1406 		goto bad_fork_cleanup_policy;
1407 	retval = audit_alloc(p);
1408 	if (retval)
1409 		goto bad_fork_cleanup_perf;
1410 	/* copy all the process information */
1411 	shm_init_task(p);
1412 	retval = copy_semundo(clone_flags, p);
1413 	if (retval)
1414 		goto bad_fork_cleanup_audit;
1415 	retval = copy_files(clone_flags, p);
1416 	if (retval)
1417 		goto bad_fork_cleanup_semundo;
1418 	retval = copy_fs(clone_flags, p);
1419 	if (retval)
1420 		goto bad_fork_cleanup_files;
1421 	retval = copy_sighand(clone_flags, p);
1422 	if (retval)
1423 		goto bad_fork_cleanup_fs;
1424 	retval = copy_signal(clone_flags, p);
1425 	if (retval)
1426 		goto bad_fork_cleanup_sighand;
1427 	retval = copy_mm(clone_flags, p);
1428 	if (retval)
1429 		goto bad_fork_cleanup_signal;
1430 	retval = copy_namespaces(clone_flags, p);
1431 	if (retval)
1432 		goto bad_fork_cleanup_mm;
1433 	retval = copy_io(clone_flags, p);
1434 	if (retval)
1435 		goto bad_fork_cleanup_namespaces;
1436 	retval = copy_thread(clone_flags, stack_start, stack_size, p);
1437 	if (retval)
1438 		goto bad_fork_cleanup_io;
1439 
1440 	if (pid != &init_struct_pid) {
1441 		retval = -ENOMEM;
1442 		pid = alloc_pid(p->nsproxy->pid_ns_for_children);
1443 		if (!pid)
1444 			goto bad_fork_cleanup_io;
1445 	}
1446 
1447 	p->set_child_tid = (clone_flags & CLONE_CHILD_SETTID) ? child_tidptr : NULL;
1448 	/*
1449 	 * Clear TID on mm_release()?
1450 	 */
1451 	p->clear_child_tid = (clone_flags & CLONE_CHILD_CLEARTID) ? child_tidptr : NULL;
1452 #ifdef CONFIG_BLOCK
1453 	p->plug = NULL;
1454 #endif
1455 #ifdef CONFIG_FUTEX
1456 	p->robust_list = NULL;
1457 #ifdef CONFIG_COMPAT
1458 	p->compat_robust_list = NULL;
1459 #endif
1460 	INIT_LIST_HEAD(&p->pi_state_list);
1461 	p->pi_state_cache = NULL;
1462 #endif
1463 	/*
1464 	 * sigaltstack should be cleared when sharing the same VM
1465 	 */
1466 	if ((clone_flags & (CLONE_VM|CLONE_VFORK)) == CLONE_VM)
1467 		p->sas_ss_sp = p->sas_ss_size = 0;
1468 
1469 	/*
1470 	 * Syscall tracing and stepping should be turned off in the
1471 	 * child regardless of CLONE_PTRACE.
1472 	 */
1473 	user_disable_single_step(p);
1474 	clear_tsk_thread_flag(p, TIF_SYSCALL_TRACE);
1475 #ifdef TIF_SYSCALL_EMU
1476 	clear_tsk_thread_flag(p, TIF_SYSCALL_EMU);
1477 #endif
1478 	clear_all_latency_tracing(p);
1479 
1480 	/* ok, now we should be set up.. */
1481 	p->pid = pid_nr(pid);
1482 	if (clone_flags & CLONE_THREAD) {
1483 		p->exit_signal = -1;
1484 		p->group_leader = current->group_leader;
1485 		p->tgid = current->tgid;
1486 	} else {
1487 		if (clone_flags & CLONE_PARENT)
1488 			p->exit_signal = current->group_leader->exit_signal;
1489 		else
1490 			p->exit_signal = (clone_flags & CSIGNAL);
1491 		p->group_leader = p;
1492 		p->tgid = p->pid;
1493 	}
1494 
1495 	p->nr_dirtied = 0;
1496 	p->nr_dirtied_pause = 128 >> (PAGE_SHIFT - 10);
1497 	p->dirty_paused_when = 0;
1498 
1499 	p->pdeath_signal = 0;
1500 	INIT_LIST_HEAD(&p->thread_group);
1501 	p->task_works = NULL;
1502 
1503 	/*
1504 	 * Make it visible to the rest of the system, but dont wake it up yet.
1505 	 * Need tasklist lock for parent etc handling!
1506 	 */
1507 	write_lock_irq(&tasklist_lock);
1508 
1509 	/* CLONE_PARENT re-uses the old parent */
1510 	if (clone_flags & (CLONE_PARENT|CLONE_THREAD)) {
1511 		p->real_parent = current->real_parent;
1512 		p->parent_exec_id = current->parent_exec_id;
1513 	} else {
1514 		p->real_parent = current;
1515 		p->parent_exec_id = current->self_exec_id;
1516 	}
1517 
1518 	spin_lock(&current->sighand->siglock);
1519 
1520 	/*
1521 	 * Copy seccomp details explicitly here, in case they were changed
1522 	 * before holding sighand lock.
1523 	 */
1524 	copy_seccomp(p);
1525 
1526 	/*
1527 	 * Process group and session signals need to be delivered to just the
1528 	 * parent before the fork or both the parent and the child after the
1529 	 * fork. Restart if a signal comes in before we add the new process to
1530 	 * it's process group.
1531 	 * A fatal signal pending means that current will exit, so the new
1532 	 * thread can't slip out of an OOM kill (or normal SIGKILL).
1533 	*/
1534 	recalc_sigpending();
1535 	if (signal_pending(current)) {
1536 		spin_unlock(&current->sighand->siglock);
1537 		write_unlock_irq(&tasklist_lock);
1538 		retval = -ERESTARTNOINTR;
1539 		goto bad_fork_free_pid;
1540 	}
1541 
1542 	if (likely(p->pid)) {
1543 		ptrace_init_task(p, (clone_flags & CLONE_PTRACE) || trace);
1544 
1545 		init_task_pid(p, PIDTYPE_PID, pid);
1546 		if (thread_group_leader(p)) {
1547 			init_task_pid(p, PIDTYPE_PGID, task_pgrp(current));
1548 			init_task_pid(p, PIDTYPE_SID, task_session(current));
1549 
1550 			if (is_child_reaper(pid)) {
1551 				ns_of_pid(pid)->child_reaper = p;
1552 				p->signal->flags |= SIGNAL_UNKILLABLE;
1553 			}
1554 
1555 			p->signal->leader_pid = pid;
1556 			p->signal->tty = tty_kref_get(current->signal->tty);
1557 			list_add_tail(&p->sibling, &p->real_parent->children);
1558 			list_add_tail_rcu(&p->tasks, &init_task.tasks);
1559 			attach_pid(p, PIDTYPE_PGID);
1560 			attach_pid(p, PIDTYPE_SID);
1561 			__this_cpu_inc(process_counts);
1562 		} else {
1563 			current->signal->nr_threads++;
1564 			atomic_inc(&current->signal->live);
1565 			atomic_inc(&current->signal->sigcnt);
1566 			list_add_tail_rcu(&p->thread_group,
1567 					  &p->group_leader->thread_group);
1568 			list_add_tail_rcu(&p->thread_node,
1569 					  &p->signal->thread_head);
1570 		}
1571 		attach_pid(p, PIDTYPE_PID);
1572 		nr_threads++;
1573 	}
1574 
1575 	total_forks++;
1576 	spin_unlock(&current->sighand->siglock);
1577 	syscall_tracepoint_update(p);
1578 	write_unlock_irq(&tasklist_lock);
1579 
1580 	proc_fork_connector(p);
1581 	cgroup_post_fork(p);
1582 	if (clone_flags & CLONE_THREAD)
1583 		threadgroup_change_end(current);
1584 	perf_event_fork(p);
1585 
1586 	trace_task_newtask(p, clone_flags);
1587 	uprobe_copy_process(p, clone_flags);
1588 
1589 	return p;
1590 
1591 bad_fork_free_pid:
1592 	if (pid != &init_struct_pid)
1593 		free_pid(pid);
1594 bad_fork_cleanup_io:
1595 	if (p->io_context)
1596 		exit_io_context(p);
1597 bad_fork_cleanup_namespaces:
1598 	exit_task_namespaces(p);
1599 bad_fork_cleanup_mm:
1600 	if (p->mm)
1601 		mmput(p->mm);
1602 bad_fork_cleanup_signal:
1603 	if (!(clone_flags & CLONE_THREAD))
1604 		free_signal_struct(p->signal);
1605 bad_fork_cleanup_sighand:
1606 	__cleanup_sighand(p->sighand);
1607 bad_fork_cleanup_fs:
1608 	exit_fs(p); /* blocking */
1609 bad_fork_cleanup_files:
1610 	exit_files(p); /* blocking */
1611 bad_fork_cleanup_semundo:
1612 	exit_sem(p);
1613 bad_fork_cleanup_audit:
1614 	audit_free(p);
1615 bad_fork_cleanup_perf:
1616 	perf_event_free_task(p);
1617 bad_fork_cleanup_policy:
1618 #ifdef CONFIG_NUMA
1619 	mpol_put(p->mempolicy);
1620 bad_fork_cleanup_threadgroup_lock:
1621 #endif
1622 	if (clone_flags & CLONE_THREAD)
1623 		threadgroup_change_end(current);
1624 	delayacct_tsk_free(p);
1625 	module_put(task_thread_info(p)->exec_domain->module);
1626 bad_fork_cleanup_count:
1627 	atomic_dec(&p->cred->user->processes);
1628 	exit_creds(p);
1629 bad_fork_free:
1630 	free_task(p);
1631 fork_out:
1632 	return ERR_PTR(retval);
1633 }
1634 
init_idle_pids(struct pid_link * links)1635 static inline void init_idle_pids(struct pid_link *links)
1636 {
1637 	enum pid_type type;
1638 
1639 	for (type = PIDTYPE_PID; type < PIDTYPE_MAX; ++type) {
1640 		INIT_HLIST_NODE(&links[type].node); /* not really needed */
1641 		links[type].pid = &init_struct_pid;
1642 	}
1643 }
1644 
fork_idle(int cpu)1645 struct task_struct *fork_idle(int cpu)
1646 {
1647 	struct task_struct *task;
1648 	task = copy_process(CLONE_VM, 0, 0, NULL, &init_struct_pid, 0);
1649 	if (!IS_ERR(task)) {
1650 		init_idle_pids(task->pids);
1651 		init_idle(task, cpu);
1652 	}
1653 
1654 	return task;
1655 }
1656 
1657 /*
1658  *  Ok, this is the main fork-routine.
1659  *
1660  * It copies the process, and if successful kick-starts
1661  * it and waits for it to finish using the VM if required.
1662  */
do_fork(unsigned long clone_flags,unsigned long stack_start,unsigned long stack_size,int __user * parent_tidptr,int __user * child_tidptr)1663 long do_fork(unsigned long clone_flags,
1664 	      unsigned long stack_start,
1665 	      unsigned long stack_size,
1666 	      int __user *parent_tidptr,
1667 	      int __user *child_tidptr)
1668 {
1669 	struct task_struct *p;
1670 	int trace = 0;
1671 	long nr;
1672 
1673 	/*
1674 	 * Determine whether and which event to report to ptracer.  When
1675 	 * called from kernel_thread or CLONE_UNTRACED is explicitly
1676 	 * requested, no event is reported; otherwise, report if the event
1677 	 * for the type of forking is enabled.
1678 	 */
1679 	if (!(clone_flags & CLONE_UNTRACED)) {
1680 		if (clone_flags & CLONE_VFORK)
1681 			trace = PTRACE_EVENT_VFORK;
1682 		else if ((clone_flags & CSIGNAL) != SIGCHLD)
1683 			trace = PTRACE_EVENT_CLONE;
1684 		else
1685 			trace = PTRACE_EVENT_FORK;
1686 
1687 		if (likely(!ptrace_event_enabled(current, trace)))
1688 			trace = 0;
1689 	}
1690 
1691 	p = copy_process(clone_flags, stack_start, stack_size,
1692 			 child_tidptr, NULL, trace);
1693 	/*
1694 	 * Do this prior waking up the new thread - the thread pointer
1695 	 * might get invalid after that point, if the thread exits quickly.
1696 	 */
1697 	if (!IS_ERR(p)) {
1698 		struct completion vfork;
1699 		struct pid *pid;
1700 
1701 		trace_sched_process_fork(current, p);
1702 
1703 		pid = get_task_pid(p, PIDTYPE_PID);
1704 		nr = pid_vnr(pid);
1705 
1706 		if (clone_flags & CLONE_PARENT_SETTID)
1707 			put_user(nr, parent_tidptr);
1708 
1709 		if (clone_flags & CLONE_VFORK) {
1710 			p->vfork_done = &vfork;
1711 			init_completion(&vfork);
1712 			get_task_struct(p);
1713 		}
1714 
1715 		wake_up_new_task(p);
1716 
1717 		/* forking complete and child started to run, tell ptracer */
1718 		if (unlikely(trace))
1719 			ptrace_event_pid(trace, pid);
1720 
1721 		if (clone_flags & CLONE_VFORK) {
1722 			if (!wait_for_vfork_done(p, &vfork))
1723 				ptrace_event_pid(PTRACE_EVENT_VFORK_DONE, pid);
1724 		}
1725 
1726 		put_pid(pid);
1727 	} else {
1728 		nr = PTR_ERR(p);
1729 	}
1730 	return nr;
1731 }
1732 
1733 /*
1734  * Create a kernel thread.
1735  */
kernel_thread(int (* fn)(void *),void * arg,unsigned long flags)1736 pid_t kernel_thread(int (*fn)(void *), void *arg, unsigned long flags)
1737 {
1738 	return do_fork(flags|CLONE_VM|CLONE_UNTRACED, (unsigned long)fn,
1739 		(unsigned long)arg, NULL, NULL);
1740 }
1741 
1742 #ifdef __ARCH_WANT_SYS_FORK
SYSCALL_DEFINE0(fork)1743 SYSCALL_DEFINE0(fork)
1744 {
1745 #ifdef CONFIG_MMU
1746 	return do_fork(SIGCHLD, 0, 0, NULL, NULL);
1747 #else
1748 	/* can not support in nommu mode */
1749 	return -EINVAL;
1750 #endif
1751 }
1752 #endif
1753 
1754 #ifdef __ARCH_WANT_SYS_VFORK
SYSCALL_DEFINE0(vfork)1755 SYSCALL_DEFINE0(vfork)
1756 {
1757 	return do_fork(CLONE_VFORK | CLONE_VM | SIGCHLD, 0,
1758 			0, NULL, NULL);
1759 }
1760 #endif
1761 
1762 #ifdef __ARCH_WANT_SYS_CLONE
1763 #ifdef CONFIG_CLONE_BACKWARDS
SYSCALL_DEFINE5(clone,unsigned long,clone_flags,unsigned long,newsp,int __user *,parent_tidptr,int,tls_val,int __user *,child_tidptr)1764 SYSCALL_DEFINE5(clone, unsigned long, clone_flags, unsigned long, newsp,
1765 		 int __user *, parent_tidptr,
1766 		 int, tls_val,
1767 		 int __user *, child_tidptr)
1768 #elif defined(CONFIG_CLONE_BACKWARDS2)
1769 SYSCALL_DEFINE5(clone, unsigned long, newsp, unsigned long, clone_flags,
1770 		 int __user *, parent_tidptr,
1771 		 int __user *, child_tidptr,
1772 		 int, tls_val)
1773 #elif defined(CONFIG_CLONE_BACKWARDS3)
1774 SYSCALL_DEFINE6(clone, unsigned long, clone_flags, unsigned long, newsp,
1775 		int, stack_size,
1776 		int __user *, parent_tidptr,
1777 		int __user *, child_tidptr,
1778 		int, tls_val)
1779 #else
1780 SYSCALL_DEFINE5(clone, unsigned long, clone_flags, unsigned long, newsp,
1781 		 int __user *, parent_tidptr,
1782 		 int __user *, child_tidptr,
1783 		 int, tls_val)
1784 #endif
1785 {
1786 	return do_fork(clone_flags, newsp, 0, parent_tidptr, child_tidptr);
1787 }
1788 #endif
1789 
1790 #ifndef ARCH_MIN_MMSTRUCT_ALIGN
1791 #define ARCH_MIN_MMSTRUCT_ALIGN 0
1792 #endif
1793 
sighand_ctor(void * data)1794 static void sighand_ctor(void *data)
1795 {
1796 	struct sighand_struct *sighand = data;
1797 
1798 	spin_lock_init(&sighand->siglock);
1799 	init_waitqueue_head(&sighand->signalfd_wqh);
1800 }
1801 
proc_caches_init(void)1802 void __init proc_caches_init(void)
1803 {
1804 	sighand_cachep = kmem_cache_create("sighand_cache",
1805 			sizeof(struct sighand_struct), 0,
1806 			SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_DESTROY_BY_RCU|
1807 			SLAB_NOTRACK, sighand_ctor);
1808 	signal_cachep = kmem_cache_create("signal_cache",
1809 			sizeof(struct signal_struct), 0,
1810 			SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_NOTRACK, NULL);
1811 	files_cachep = kmem_cache_create("files_cache",
1812 			sizeof(struct files_struct), 0,
1813 			SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_NOTRACK, NULL);
1814 	fs_cachep = kmem_cache_create("fs_cache",
1815 			sizeof(struct fs_struct), 0,
1816 			SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_NOTRACK, NULL);
1817 	/*
1818 	 * FIXME! The "sizeof(struct mm_struct)" currently includes the
1819 	 * whole struct cpumask for the OFFSTACK case. We could change
1820 	 * this to *only* allocate as much of it as required by the
1821 	 * maximum number of CPU's we can ever have.  The cpumask_allocation
1822 	 * is at the end of the structure, exactly for that reason.
1823 	 */
1824 	mm_cachep = kmem_cache_create("mm_struct",
1825 			sizeof(struct mm_struct), ARCH_MIN_MMSTRUCT_ALIGN,
1826 			SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_NOTRACK, NULL);
1827 	vm_area_cachep = KMEM_CACHE(vm_area_struct, SLAB_PANIC);
1828 	mmap_init();
1829 	nsproxy_cache_init();
1830 }
1831 
1832 /*
1833  * Check constraints on flags passed to the unshare system call.
1834  */
check_unshare_flags(unsigned long unshare_flags)1835 static int check_unshare_flags(unsigned long unshare_flags)
1836 {
1837 	if (unshare_flags & ~(CLONE_THREAD|CLONE_FS|CLONE_NEWNS|CLONE_SIGHAND|
1838 				CLONE_VM|CLONE_FILES|CLONE_SYSVSEM|
1839 				CLONE_NEWUTS|CLONE_NEWIPC|CLONE_NEWNET|
1840 				CLONE_NEWUSER|CLONE_NEWPID))
1841 		return -EINVAL;
1842 	/*
1843 	 * Not implemented, but pretend it works if there is nothing
1844 	 * to unshare.  Note that unsharing the address space or the
1845 	 * signal handlers also need to unshare the signal queues (aka
1846 	 * CLONE_THREAD).
1847 	 */
1848 	if (unshare_flags & (CLONE_THREAD | CLONE_SIGHAND | CLONE_VM)) {
1849 		if (!thread_group_empty(current))
1850 			return -EINVAL;
1851 	}
1852 	if (unshare_flags & (CLONE_SIGHAND | CLONE_VM)) {
1853 		if (atomic_read(&current->sighand->count) > 1)
1854 			return -EINVAL;
1855 	}
1856 	if (unshare_flags & CLONE_VM) {
1857 		if (!current_is_single_threaded())
1858 			return -EINVAL;
1859 	}
1860 
1861 	return 0;
1862 }
1863 
1864 /*
1865  * Unshare the filesystem structure if it is being shared
1866  */
unshare_fs(unsigned long unshare_flags,struct fs_struct ** new_fsp)1867 static int unshare_fs(unsigned long unshare_flags, struct fs_struct **new_fsp)
1868 {
1869 	struct fs_struct *fs = current->fs;
1870 
1871 	if (!(unshare_flags & CLONE_FS) || !fs)
1872 		return 0;
1873 
1874 	/* don't need lock here; in the worst case we'll do useless copy */
1875 	if (fs->users == 1)
1876 		return 0;
1877 
1878 	*new_fsp = copy_fs_struct(fs);
1879 	if (!*new_fsp)
1880 		return -ENOMEM;
1881 
1882 	return 0;
1883 }
1884 
1885 /*
1886  * Unshare file descriptor table if it is being shared
1887  */
unshare_fd(unsigned long unshare_flags,struct files_struct ** new_fdp)1888 static int unshare_fd(unsigned long unshare_flags, struct files_struct **new_fdp)
1889 {
1890 	struct files_struct *fd = current->files;
1891 	int error = 0;
1892 
1893 	if ((unshare_flags & CLONE_FILES) &&
1894 	    (fd && atomic_read(&fd->count) > 1)) {
1895 		*new_fdp = dup_fd(fd, &error);
1896 		if (!*new_fdp)
1897 			return error;
1898 	}
1899 
1900 	return 0;
1901 }
1902 
1903 /*
1904  * unshare allows a process to 'unshare' part of the process
1905  * context which was originally shared using clone.  copy_*
1906  * functions used by do_fork() cannot be used here directly
1907  * because they modify an inactive task_struct that is being
1908  * constructed. Here we are modifying the current, active,
1909  * task_struct.
1910  */
SYSCALL_DEFINE1(unshare,unsigned long,unshare_flags)1911 SYSCALL_DEFINE1(unshare, unsigned long, unshare_flags)
1912 {
1913 	struct fs_struct *fs, *new_fs = NULL;
1914 	struct files_struct *fd, *new_fd = NULL;
1915 	struct cred *new_cred = NULL;
1916 	struct nsproxy *new_nsproxy = NULL;
1917 	int do_sysvsem = 0;
1918 	int err;
1919 
1920 	/*
1921 	 * If unsharing a user namespace must also unshare the thread.
1922 	 */
1923 	if (unshare_flags & CLONE_NEWUSER)
1924 		unshare_flags |= CLONE_THREAD | CLONE_FS;
1925 	/*
1926 	 * If unsharing vm, must also unshare signal handlers.
1927 	 */
1928 	if (unshare_flags & CLONE_VM)
1929 		unshare_flags |= CLONE_SIGHAND;
1930 	/*
1931 	 * If unsharing a signal handlers, must also unshare the signal queues.
1932 	 */
1933 	if (unshare_flags & CLONE_SIGHAND)
1934 		unshare_flags |= CLONE_THREAD;
1935 	/*
1936 	 * If unsharing namespace, must also unshare filesystem information.
1937 	 */
1938 	if (unshare_flags & CLONE_NEWNS)
1939 		unshare_flags |= CLONE_FS;
1940 
1941 	err = check_unshare_flags(unshare_flags);
1942 	if (err)
1943 		goto bad_unshare_out;
1944 	/*
1945 	 * CLONE_NEWIPC must also detach from the undolist: after switching
1946 	 * to a new ipc namespace, the semaphore arrays from the old
1947 	 * namespace are unreachable.
1948 	 */
1949 	if (unshare_flags & (CLONE_NEWIPC|CLONE_SYSVSEM))
1950 		do_sysvsem = 1;
1951 	err = unshare_fs(unshare_flags, &new_fs);
1952 	if (err)
1953 		goto bad_unshare_out;
1954 	err = unshare_fd(unshare_flags, &new_fd);
1955 	if (err)
1956 		goto bad_unshare_cleanup_fs;
1957 	err = unshare_userns(unshare_flags, &new_cred);
1958 	if (err)
1959 		goto bad_unshare_cleanup_fd;
1960 	err = unshare_nsproxy_namespaces(unshare_flags, &new_nsproxy,
1961 					 new_cred, new_fs);
1962 	if (err)
1963 		goto bad_unshare_cleanup_cred;
1964 
1965 	if (new_fs || new_fd || do_sysvsem || new_cred || new_nsproxy) {
1966 		if (do_sysvsem) {
1967 			/*
1968 			 * CLONE_SYSVSEM is equivalent to sys_exit().
1969 			 */
1970 			exit_sem(current);
1971 		}
1972 		if (unshare_flags & CLONE_NEWIPC) {
1973 			/* Orphan segments in old ns (see sem above). */
1974 			exit_shm(current);
1975 			shm_init_task(current);
1976 		}
1977 
1978 		if (new_nsproxy)
1979 			switch_task_namespaces(current, new_nsproxy);
1980 
1981 		task_lock(current);
1982 
1983 		if (new_fs) {
1984 			fs = current->fs;
1985 			spin_lock(&fs->lock);
1986 			current->fs = new_fs;
1987 			if (--fs->users)
1988 				new_fs = NULL;
1989 			else
1990 				new_fs = fs;
1991 			spin_unlock(&fs->lock);
1992 		}
1993 
1994 		if (new_fd) {
1995 			fd = current->files;
1996 			current->files = new_fd;
1997 			new_fd = fd;
1998 		}
1999 
2000 		task_unlock(current);
2001 
2002 		if (new_cred) {
2003 			/* Install the new user namespace */
2004 			commit_creds(new_cred);
2005 			new_cred = NULL;
2006 		}
2007 	}
2008 
2009 bad_unshare_cleanup_cred:
2010 	if (new_cred)
2011 		put_cred(new_cred);
2012 bad_unshare_cleanup_fd:
2013 	if (new_fd)
2014 		put_files_struct(new_fd);
2015 
2016 bad_unshare_cleanup_fs:
2017 	if (new_fs)
2018 		free_fs_struct(new_fs);
2019 
2020 bad_unshare_out:
2021 	return err;
2022 }
2023 
2024 /*
2025  *	Helper to unshare the files of the current task.
2026  *	We don't want to expose copy_files internals to
2027  *	the exec layer of the kernel.
2028  */
2029 
unshare_files(struct files_struct ** displaced)2030 int unshare_files(struct files_struct **displaced)
2031 {
2032 	struct task_struct *task = current;
2033 	struct files_struct *copy = NULL;
2034 	int error;
2035 
2036 	error = unshare_fd(CLONE_FILES, &copy);
2037 	if (error || !copy) {
2038 		*displaced = NULL;
2039 		return error;
2040 	}
2041 	*displaced = task->files;
2042 	task_lock(task);
2043 	task->files = copy;
2044 	task_unlock(task);
2045 	return 0;
2046 }
2047