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