• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  *  linux/kernel/fork.c
4  *
5  *  Copyright (C) 1991, 1992  Linus Torvalds
6  */
7 
8 /*
9  *  'fork.c' contains the help-routines for the 'fork' system call
10  * (see also entry.S and others).
11  * Fork is rather simple, once you get the hang of it, but the memory
12  * management can be a bitch. See 'mm/memory.c': 'copy_page_range()'
13  */
14 
15 #include <linux/anon_inodes.h>
16 #include <linux/slab.h>
17 #include <linux/sched/autogroup.h>
18 #include <linux/sched/mm.h>
19 #include <linux/sched/coredump.h>
20 #include <linux/sched/user.h>
21 #include <linux/sched/numa_balancing.h>
22 #include <linux/sched/stat.h>
23 #include <linux/sched/task.h>
24 #include <linux/sched/task_stack.h>
25 #include <linux/sched/cputime.h>
26 #include <linux/seq_file.h>
27 #include <linux/rtmutex.h>
28 #include <linux/init.h>
29 #include <linux/unistd.h>
30 #include <linux/module.h>
31 #include <linux/vmalloc.h>
32 #include <linux/completion.h>
33 #include <linux/personality.h>
34 #include <linux/mempolicy.h>
35 #include <linux/sem.h>
36 #include <linux/file.h>
37 #include <linux/fdtable.h>
38 #include <linux/iocontext.h>
39 #include <linux/key.h>
40 #include <linux/binfmts.h>
41 #include <linux/mman.h>
42 #include <linux/mmu_notifier.h>
43 #include <linux/fs.h>
44 #include <linux/mm.h>
45 #include <linux/mm_inline.h>
46 #include <linux/vmacache.h>
47 #include <linux/nsproxy.h>
48 #include <linux/capability.h>
49 #include <linux/cpu.h>
50 #include <linux/cgroup.h>
51 #include <linux/security.h>
52 #include <linux/hugetlb.h>
53 #include <linux/seccomp.h>
54 #include <linux/swap.h>
55 #include <linux/syscalls.h>
56 #include <linux/jiffies.h>
57 #include <linux/futex.h>
58 #include <linux/compat.h>
59 #include <linux/kthread.h>
60 #include <linux/task_io_accounting_ops.h>
61 #include <linux/rcupdate.h>
62 #include <linux/ptrace.h>
63 #include <linux/mount.h>
64 #include <linux/audit.h>
65 #include <linux/memcontrol.h>
66 #include <linux/ftrace.h>
67 #include <linux/proc_fs.h>
68 #include <linux/profile.h>
69 #include <linux/rmap.h>
70 #include <linux/ksm.h>
71 #include <linux/acct.h>
72 #include <linux/userfaultfd_k.h>
73 #include <linux/tsacct_kern.h>
74 #include <linux/cn_proc.h>
75 #include <linux/freezer.h>
76 #include <linux/delayacct.h>
77 #include <linux/taskstats_kern.h>
78 #include <linux/random.h>
79 #include <linux/tty.h>
80 #include <linux/blkdev.h>
81 #include <linux/fs_struct.h>
82 #include <linux/magic.h>
83 #include <linux/perf_event.h>
84 #include <linux/posix-timers.h>
85 #include <linux/user-return-notifier.h>
86 #include <linux/oom.h>
87 #include <linux/khugepaged.h>
88 #include <linux/signalfd.h>
89 #include <linux/uprobes.h>
90 #include <linux/aio.h>
91 #include <linux/compiler.h>
92 #include <linux/sysctl.h>
93 #include <linux/kcov.h>
94 #include <linux/livepatch.h>
95 #include <linux/thread_info.h>
96 #include <linux/stackleak.h>
97 #include <linux/kasan.h>
98 #include <linux/scs.h>
99 #include <linux/io_uring.h>
100 #ifdef CONFIG_RECLAIM_ACCT
101 #include <linux/reclaim_acct.h>
102 #endif
103 #include <linux/mm_purgeable.h>
104 
105 #include <asm/pgalloc.h>
106 #include <linux/uaccess.h>
107 #include <asm/mmu_context.h>
108 #include <asm/cacheflush.h>
109 #include <asm/tlbflush.h>
110 
111 #include <trace/events/sched.h>
112 
113 #define CREATE_TRACE_POINTS
114 #include <trace/events/task.h>
115 
116 /*
117  * Minimum number of threads to boot the kernel
118  */
119 #define MIN_THREADS 20
120 
121 /*
122  * Maximum number of threads
123  */
124 #define MAX_THREADS FUTEX_TID_MASK
125 
126 /*
127  * Protected counters by write_lock_irq(&tasklist_lock)
128  */
129 unsigned long total_forks;	/* Handle normal Linux uptimes. */
130 int nr_threads;			/* The idle threads do not count.. */
131 
132 static int max_threads;		/* tunable limit on nr_threads */
133 
134 #define NAMED_ARRAY_INDEX(x)	[x] = __stringify(x)
135 
136 static const char * const resident_page_types[] = {
137 	NAMED_ARRAY_INDEX(MM_FILEPAGES),
138 	NAMED_ARRAY_INDEX(MM_ANONPAGES),
139 	NAMED_ARRAY_INDEX(MM_SWAPENTS),
140 	NAMED_ARRAY_INDEX(MM_SHMEMPAGES),
141 };
142 
143 DEFINE_PER_CPU(unsigned long, process_counts) = 0;
144 
145 __cacheline_aligned DEFINE_RWLOCK(tasklist_lock);  /* outer */
146 
147 #ifdef CONFIG_PROVE_RCU
lockdep_tasklist_lock_is_held(void)148 int lockdep_tasklist_lock_is_held(void)
149 {
150 	return lockdep_is_held(&tasklist_lock);
151 }
152 EXPORT_SYMBOL_GPL(lockdep_tasklist_lock_is_held);
153 #endif /* #ifdef CONFIG_PROVE_RCU */
154 
nr_processes(void)155 int nr_processes(void)
156 {
157 	int cpu;
158 	int total = 0;
159 
160 	for_each_possible_cpu(cpu)
161 		total += per_cpu(process_counts, cpu);
162 
163 	return total;
164 }
165 
arch_release_task_struct(struct task_struct * tsk)166 void __weak arch_release_task_struct(struct task_struct *tsk)
167 {
168 }
169 
170 #ifndef CONFIG_ARCH_TASK_STRUCT_ALLOCATOR
171 static struct kmem_cache *task_struct_cachep;
172 
alloc_task_struct_node(int node)173 static inline struct task_struct *alloc_task_struct_node(int node)
174 {
175 	return kmem_cache_alloc_node(task_struct_cachep, GFP_KERNEL, node);
176 }
177 
free_task_struct(struct task_struct * tsk)178 static inline void free_task_struct(struct task_struct *tsk)
179 {
180 	kmem_cache_free(task_struct_cachep, tsk);
181 }
182 #endif
183 
184 #ifndef CONFIG_ARCH_THREAD_STACK_ALLOCATOR
185 
186 /*
187  * Allocate pages if THREAD_SIZE is >= PAGE_SIZE, otherwise use a
188  * kmemcache based allocator.
189  */
190 # if THREAD_SIZE >= PAGE_SIZE || defined(CONFIG_VMAP_STACK)
191 
192 #ifdef CONFIG_VMAP_STACK
193 /*
194  * vmalloc() is a bit slow, and calling vfree() enough times will force a TLB
195  * flush.  Try to minimize the number of calls by caching stacks.
196  */
197 #define NR_CACHED_STACKS 2
198 static DEFINE_PER_CPU(struct vm_struct *, cached_stacks[NR_CACHED_STACKS]);
199 
free_vm_stack_cache(unsigned int cpu)200 static int free_vm_stack_cache(unsigned int cpu)
201 {
202 	struct vm_struct **cached_vm_stacks = per_cpu_ptr(cached_stacks, cpu);
203 	int i;
204 
205 	for (i = 0; i < NR_CACHED_STACKS; i++) {
206 		struct vm_struct *vm_stack = cached_vm_stacks[i];
207 
208 		if (!vm_stack)
209 			continue;
210 
211 		vfree(vm_stack->addr);
212 		cached_vm_stacks[i] = NULL;
213 	}
214 
215 	return 0;
216 }
217 #endif
218 
alloc_thread_stack_node(struct task_struct * tsk,int node)219 static unsigned long *alloc_thread_stack_node(struct task_struct *tsk, int node)
220 {
221 #ifdef CONFIG_VMAP_STACK
222 	void *stack;
223 	int i;
224 
225 	for (i = 0; i < NR_CACHED_STACKS; i++) {
226 		struct vm_struct *s;
227 
228 		s = this_cpu_xchg(cached_stacks[i], NULL);
229 
230 		if (!s)
231 			continue;
232 
233 		/* Clear the KASAN shadow of the stack. */
234 		kasan_unpoison_shadow(s->addr, THREAD_SIZE);
235 
236 		/* Clear stale pointers from reused stack. */
237 		memset(s->addr, 0, THREAD_SIZE);
238 
239 		tsk->stack_vm_area = s;
240 		tsk->stack = s->addr;
241 		return s->addr;
242 	}
243 
244 	/*
245 	 * Allocated stacks are cached and later reused by new threads,
246 	 * so memcg accounting is performed manually on assigning/releasing
247 	 * stacks to tasks. Drop __GFP_ACCOUNT.
248 	 */
249 	stack = __vmalloc_node_range(THREAD_SIZE, THREAD_ALIGN,
250 				     VMALLOC_START, VMALLOC_END,
251 				     THREADINFO_GFP & ~__GFP_ACCOUNT,
252 				     PAGE_KERNEL,
253 				     0, node, __builtin_return_address(0));
254 
255 	/*
256 	 * We can't call find_vm_area() in interrupt context, and
257 	 * free_thread_stack() can be called in interrupt context,
258 	 * so cache the vm_struct.
259 	 */
260 	if (stack) {
261 		tsk->stack_vm_area = find_vm_area(stack);
262 		tsk->stack = stack;
263 	}
264 	return stack;
265 #else
266 	struct page *page = alloc_pages_node(node, THREADINFO_GFP,
267 					     THREAD_SIZE_ORDER);
268 
269 	if (likely(page)) {
270 		tsk->stack = kasan_reset_tag(page_address(page));
271 		return tsk->stack;
272 	}
273 	return NULL;
274 #endif
275 }
276 
free_thread_stack(struct task_struct * tsk)277 static inline void free_thread_stack(struct task_struct *tsk)
278 {
279 #ifdef CONFIG_VMAP_STACK
280 	struct vm_struct *vm = task_stack_vm_area(tsk);
281 
282 	if (vm) {
283 		int i;
284 
285 		for (i = 0; i < THREAD_SIZE / PAGE_SIZE; i++)
286 			memcg_kmem_uncharge_page(vm->pages[i], 0);
287 
288 		for (i = 0; i < NR_CACHED_STACKS; i++) {
289 			if (this_cpu_cmpxchg(cached_stacks[i],
290 					NULL, tsk->stack_vm_area) != NULL)
291 				continue;
292 
293 			return;
294 		}
295 
296 		vfree_atomic(tsk->stack);
297 		return;
298 	}
299 #endif
300 
301 	__free_pages(virt_to_page(tsk->stack), THREAD_SIZE_ORDER);
302 }
303 # else
304 static struct kmem_cache *thread_stack_cache;
305 
alloc_thread_stack_node(struct task_struct * tsk,int node)306 static unsigned long *alloc_thread_stack_node(struct task_struct *tsk,
307 						  int node)
308 {
309 	unsigned long *stack;
310 	stack = kmem_cache_alloc_node(thread_stack_cache, THREADINFO_GFP, node);
311 	stack = kasan_reset_tag(stack);
312 	tsk->stack = stack;
313 	return stack;
314 }
315 
free_thread_stack(struct task_struct * tsk)316 static void free_thread_stack(struct task_struct *tsk)
317 {
318 	kmem_cache_free(thread_stack_cache, tsk->stack);
319 }
320 
thread_stack_cache_init(void)321 void thread_stack_cache_init(void)
322 {
323 	thread_stack_cache = kmem_cache_create_usercopy("thread_stack",
324 					THREAD_SIZE, THREAD_SIZE, 0, 0,
325 					THREAD_SIZE, NULL);
326 	BUG_ON(thread_stack_cache == NULL);
327 }
328 # endif
329 #endif
330 
331 /* SLAB cache for signal_struct structures (tsk->signal) */
332 static struct kmem_cache *signal_cachep;
333 
334 /* SLAB cache for sighand_struct structures (tsk->sighand) */
335 struct kmem_cache *sighand_cachep;
336 
337 /* SLAB cache for files_struct structures (tsk->files) */
338 struct kmem_cache *files_cachep;
339 
340 /* SLAB cache for fs_struct structures (tsk->fs) */
341 struct kmem_cache *fs_cachep;
342 
343 /* SLAB cache for vm_area_struct structures */
344 static struct kmem_cache *vm_area_cachep;
345 
346 /* SLAB cache for mm_struct structures (tsk->mm) */
347 static struct kmem_cache *mm_cachep;
348 
vm_area_alloc(struct mm_struct * mm)349 struct vm_area_struct *vm_area_alloc(struct mm_struct *mm)
350 {
351 	struct vm_area_struct *vma;
352 
353 	vma = kmem_cache_alloc(vm_area_cachep, GFP_KERNEL);
354 	if (vma)
355 		vma_init(vma, mm);
356 	return vma;
357 }
358 
vm_area_dup(struct vm_area_struct * orig)359 struct vm_area_struct *vm_area_dup(struct vm_area_struct *orig)
360 {
361 	struct vm_area_struct *new = kmem_cache_alloc(vm_area_cachep, GFP_KERNEL);
362 
363 	if (new) {
364 		ASSERT_EXCLUSIVE_WRITER(orig->vm_flags);
365 		ASSERT_EXCLUSIVE_WRITER(orig->vm_file);
366 		/*
367 		 * orig->shared.rb may be modified concurrently, but the clone
368 		 * will be reinitialized.
369 		 */
370 		*new = data_race(*orig);
371 		INIT_LIST_HEAD(&new->anon_vma_chain);
372 		new->vm_next = new->vm_prev = NULL;
373 		dup_anon_vma_name(orig, new);
374 	}
375 	return new;
376 }
377 
vm_area_free(struct vm_area_struct * vma)378 void vm_area_free(struct vm_area_struct *vma)
379 {
380 	free_anon_vma_name(vma);
381 	kmem_cache_free(vm_area_cachep, vma);
382 }
383 
account_kernel_stack(struct task_struct * tsk,int account)384 static void account_kernel_stack(struct task_struct *tsk, int account)
385 {
386 	void *stack = task_stack_page(tsk);
387 	struct vm_struct *vm = task_stack_vm_area(tsk);
388 
389 
390 	/* All stack pages are in the same node. */
391 	if (vm)
392 		mod_lruvec_page_state(vm->pages[0], NR_KERNEL_STACK_KB,
393 				      account * (THREAD_SIZE / 1024));
394 	else
395 		mod_lruvec_slab_state(stack, NR_KERNEL_STACK_KB,
396 				      account * (THREAD_SIZE / 1024));
397 }
398 
memcg_charge_kernel_stack(struct task_struct * tsk)399 static int memcg_charge_kernel_stack(struct task_struct *tsk)
400 {
401 #ifdef CONFIG_VMAP_STACK
402 	struct vm_struct *vm = task_stack_vm_area(tsk);
403 	int ret;
404 
405 	BUILD_BUG_ON(IS_ENABLED(CONFIG_VMAP_STACK) && PAGE_SIZE % 1024 != 0);
406 
407 	if (vm) {
408 		int i;
409 
410 		BUG_ON(vm->nr_pages != THREAD_SIZE / PAGE_SIZE);
411 
412 		for (i = 0; i < THREAD_SIZE / PAGE_SIZE; i++) {
413 			/*
414 			 * If memcg_kmem_charge_page() fails, page->mem_cgroup
415 			 * pointer is NULL, and memcg_kmem_uncharge_page() in
416 			 * free_thread_stack() will ignore this page.
417 			 */
418 			ret = memcg_kmem_charge_page(vm->pages[i], GFP_KERNEL,
419 						     0);
420 			if (ret)
421 				return ret;
422 		}
423 	}
424 #endif
425 	return 0;
426 }
427 
release_task_stack(struct task_struct * tsk)428 static void release_task_stack(struct task_struct *tsk)
429 {
430 	if (WARN_ON(tsk->state != TASK_DEAD))
431 		return;  /* Better to leak the stack than to free prematurely */
432 
433 	account_kernel_stack(tsk, -1);
434 	free_thread_stack(tsk);
435 	tsk->stack = NULL;
436 #ifdef CONFIG_VMAP_STACK
437 	tsk->stack_vm_area = NULL;
438 #endif
439 }
440 
441 #ifdef CONFIG_THREAD_INFO_IN_TASK
put_task_stack(struct task_struct * tsk)442 void put_task_stack(struct task_struct *tsk)
443 {
444 	if (refcount_dec_and_test(&tsk->stack_refcount))
445 		release_task_stack(tsk);
446 }
447 #endif
448 
free_task(struct task_struct * tsk)449 void free_task(struct task_struct *tsk)
450 {
451 	scs_release(tsk);
452 
453 #ifndef CONFIG_THREAD_INFO_IN_TASK
454 	/*
455 	 * The task is finally done with both the stack and thread_info,
456 	 * so free both.
457 	 */
458 	release_task_stack(tsk);
459 #else
460 	/*
461 	 * If the task had a separate stack allocation, it should be gone
462 	 * by now.
463 	 */
464 	WARN_ON_ONCE(refcount_read(&tsk->stack_refcount) != 0);
465 #endif
466 	rt_mutex_debug_task_free(tsk);
467 	ftrace_graph_exit_task(tsk);
468 	arch_release_task_struct(tsk);
469 	if (tsk->flags & PF_KTHREAD)
470 		free_kthread_struct(tsk);
471 	free_task_struct(tsk);
472 }
473 EXPORT_SYMBOL(free_task);
474 
475 #ifdef CONFIG_MMU
dup_mmap(struct mm_struct * mm,struct mm_struct * oldmm)476 static __latent_entropy int dup_mmap(struct mm_struct *mm,
477 					struct mm_struct *oldmm)
478 {
479 	struct vm_area_struct *mpnt, *tmp, *prev, **pprev;
480 	struct rb_node **rb_link, *rb_parent;
481 	int retval;
482 	unsigned long charge;
483 	LIST_HEAD(uf);
484 
485 	uprobe_start_dup_mmap();
486 	if (mmap_write_lock_killable(oldmm)) {
487 		retval = -EINTR;
488 		goto fail_uprobe_end;
489 	}
490 	flush_cache_dup_mm(oldmm);
491 	uprobe_dup_mmap(oldmm, mm);
492 	/*
493 	 * Not linked in yet - no deadlock potential:
494 	 */
495 	mmap_write_lock_nested(mm, SINGLE_DEPTH_NESTING);
496 
497 	/* No ordering required: file already has been exposed. */
498 	RCU_INIT_POINTER(mm->exe_file, get_mm_exe_file(oldmm));
499 
500 	mm->total_vm = oldmm->total_vm;
501 	mm->data_vm = oldmm->data_vm;
502 	mm->exec_vm = oldmm->exec_vm;
503 	mm->stack_vm = oldmm->stack_vm;
504 
505 	rb_link = &mm->mm_rb.rb_node;
506 	rb_parent = NULL;
507 	pprev = &mm->mmap;
508 	retval = ksm_fork(mm, oldmm);
509 	if (retval)
510 		goto out;
511 	retval = khugepaged_fork(mm, oldmm);
512 	if (retval)
513 		goto out;
514 
515 	prev = NULL;
516 	for (mpnt = oldmm->mmap; mpnt; mpnt = mpnt->vm_next) {
517 		struct file *file;
518 
519 		if (mpnt->vm_flags & VM_DONTCOPY) {
520 			vm_stat_account(mm, mpnt->vm_flags, -vma_pages(mpnt));
521 			continue;
522 		}
523 		charge = 0;
524 		/*
525 		 * Don't duplicate many vmas if we've been oom-killed (for
526 		 * example)
527 		 */
528 		if (fatal_signal_pending(current)) {
529 			retval = -EINTR;
530 			goto out;
531 		}
532 		if (mpnt->vm_flags & VM_ACCOUNT) {
533 			unsigned long len = vma_pages(mpnt);
534 
535 			if (security_vm_enough_memory_mm(oldmm, len)) /* sic */
536 				goto fail_nomem;
537 			charge = len;
538 		}
539 		tmp = vm_area_dup(mpnt);
540 		if (!tmp)
541 			goto fail_nomem;
542 		retval = vma_dup_policy(mpnt, tmp);
543 		if (retval)
544 			goto fail_nomem_policy;
545 		tmp->vm_mm = mm;
546 		retval = dup_userfaultfd(tmp, &uf);
547 		if (retval)
548 			goto fail_nomem_anon_vma_fork;
549 		if (tmp->vm_flags & VM_WIPEONFORK) {
550 			/*
551 			 * VM_WIPEONFORK gets a clean slate in the child.
552 			 * Don't prepare anon_vma until fault since we don't
553 			 * copy page for current vma.
554 			 */
555 			tmp->anon_vma = NULL;
556 		} else if (anon_vma_fork(tmp, mpnt))
557 			goto fail_nomem_anon_vma_fork;
558 		tmp->vm_flags &= ~(VM_LOCKED | VM_LOCKONFAULT);
559 		file = tmp->vm_file;
560 		if (file) {
561 			struct inode *inode = file_inode(file);
562 			struct address_space *mapping = file->f_mapping;
563 
564 			get_file(file);
565 			if (tmp->vm_flags & VM_DENYWRITE)
566 				put_write_access(inode);
567 			i_mmap_lock_write(mapping);
568 			if (tmp->vm_flags & VM_SHARED)
569 				mapping_allow_writable(mapping);
570 			flush_dcache_mmap_lock(mapping);
571 			/* insert tmp into the share list, just after mpnt */
572 			vma_interval_tree_insert_after(tmp, mpnt,
573 					&mapping->i_mmap);
574 			flush_dcache_mmap_unlock(mapping);
575 			i_mmap_unlock_write(mapping);
576 		}
577 
578 		/*
579 		 * Clear hugetlb-related page reserves for children. This only
580 		 * affects MAP_PRIVATE mappings. Faults generated by the child
581 		 * are not guaranteed to succeed, even if read-only
582 		 */
583 		if (is_vm_hugetlb_page(tmp))
584 			reset_vma_resv_huge_pages(tmp);
585 
586 		/*
587 		 * Link in the new vma and copy the page table entries.
588 		 */
589 		*pprev = tmp;
590 		pprev = &tmp->vm_next;
591 		tmp->vm_prev = prev;
592 		prev = tmp;
593 
594 		__vma_link_rb(mm, tmp, rb_link, rb_parent);
595 		rb_link = &tmp->vm_rb.rb_right;
596 		rb_parent = &tmp->vm_rb;
597 
598 		mm->map_count++;
599 		if (!(tmp->vm_flags & VM_WIPEONFORK))
600 			retval = copy_page_range(tmp, mpnt);
601 
602 		if (tmp->vm_ops && tmp->vm_ops->open)
603 			tmp->vm_ops->open(tmp);
604 
605 		if (retval)
606 			goto out;
607 	}
608 	/* a new mm has just been created */
609 	retval = arch_dup_mmap(oldmm, mm);
610 out:
611 	mmap_write_unlock(mm);
612 	flush_tlb_mm(oldmm);
613 	mmap_write_unlock(oldmm);
614 	dup_userfaultfd_complete(&uf);
615 fail_uprobe_end:
616 	uprobe_end_dup_mmap();
617 	return retval;
618 fail_nomem_anon_vma_fork:
619 	mpol_put(vma_policy(tmp));
620 fail_nomem_policy:
621 	vm_area_free(tmp);
622 fail_nomem:
623 	retval = -ENOMEM;
624 	vm_unacct_memory(charge);
625 	goto out;
626 }
627 
mm_alloc_pgd(struct mm_struct * mm)628 static inline int mm_alloc_pgd(struct mm_struct *mm)
629 {
630 	mm_init_uxpgd(mm);
631 	mm->pgd = pgd_alloc(mm);
632 	if (unlikely(!mm->pgd))
633 		return -ENOMEM;
634 	return 0;
635 }
636 
mm_free_pgd(struct mm_struct * mm)637 static inline void mm_free_pgd(struct mm_struct *mm)
638 {
639 	pgd_free(mm, mm->pgd);
640 	mm_clear_uxpgd(mm);
641 }
642 #else
dup_mmap(struct mm_struct * mm,struct mm_struct * oldmm)643 static int dup_mmap(struct mm_struct *mm, struct mm_struct *oldmm)
644 {
645 	mmap_write_lock(oldmm);
646 	RCU_INIT_POINTER(mm->exe_file, get_mm_exe_file(oldmm));
647 	mmap_write_unlock(oldmm);
648 	return 0;
649 }
650 #define mm_alloc_pgd(mm)	(0)
651 #define mm_free_pgd(mm)
652 #endif /* CONFIG_MMU */
653 
check_mm(struct mm_struct * mm)654 static void check_mm(struct mm_struct *mm)
655 {
656 	int i;
657 
658 	BUILD_BUG_ON_MSG(ARRAY_SIZE(resident_page_types) != NR_MM_COUNTERS,
659 			 "Please make sure 'struct resident_page_types[]' is updated as well");
660 
661 	for (i = 0; i < NR_MM_COUNTERS; i++) {
662 		long x = atomic_long_read(&mm->rss_stat.count[i]);
663 
664 		if (unlikely(x))
665 			pr_alert("BUG: Bad rss-counter state mm:%p type:%s val:%ld\n",
666 				 mm, resident_page_types[i], x);
667 	}
668 
669 	if (mm_pgtables_bytes(mm))
670 		pr_alert("BUG: non-zero pgtables_bytes on freeing mm: %ld\n",
671 				mm_pgtables_bytes(mm));
672 
673 #if defined(CONFIG_TRANSPARENT_HUGEPAGE) && !USE_SPLIT_PMD_PTLOCKS
674 	VM_BUG_ON_MM(mm->pmd_huge_pte, mm);
675 #endif
676 }
677 
678 #define allocate_mm()	(kmem_cache_alloc(mm_cachep, GFP_KERNEL))
679 #define free_mm(mm)	(kmem_cache_free(mm_cachep, (mm)))
680 
681 /*
682  * Called when the last reference to the mm
683  * is dropped: either by a lazy thread or by
684  * mmput. Free the page directory and the mm.
685  */
__mmdrop(struct mm_struct * mm)686 void __mmdrop(struct mm_struct *mm)
687 {
688 	BUG_ON(mm == &init_mm);
689 	WARN_ON_ONCE(mm == current->mm);
690 	WARN_ON_ONCE(mm == current->active_mm);
691 	mm_free_pgd(mm);
692 	destroy_context(mm);
693 	mmu_notifier_subscriptions_destroy(mm);
694 	check_mm(mm);
695 	put_user_ns(mm->user_ns);
696 	free_mm(mm);
697 }
698 EXPORT_SYMBOL_GPL(__mmdrop);
699 
mmdrop_async_fn(struct work_struct * work)700 static void mmdrop_async_fn(struct work_struct *work)
701 {
702 	struct mm_struct *mm;
703 
704 	mm = container_of(work, struct mm_struct, async_put_work);
705 	__mmdrop(mm);
706 }
707 
mmdrop_async(struct mm_struct * mm)708 static void mmdrop_async(struct mm_struct *mm)
709 {
710 	if (unlikely(atomic_dec_and_test(&mm->mm_count))) {
711 		INIT_WORK(&mm->async_put_work, mmdrop_async_fn);
712 		schedule_work(&mm->async_put_work);
713 	}
714 }
715 
free_signal_struct(struct signal_struct * sig)716 static inline void free_signal_struct(struct signal_struct *sig)
717 {
718 	taskstats_tgid_free(sig);
719 	sched_autogroup_exit(sig);
720 	/*
721 	 * __mmdrop is not safe to call from softirq context on x86 due to
722 	 * pgd_dtor so postpone it to the async context
723 	 */
724 	if (sig->oom_mm)
725 		mmdrop_async(sig->oom_mm);
726 	kmem_cache_free(signal_cachep, sig);
727 }
728 
put_signal_struct(struct signal_struct * sig)729 static inline void put_signal_struct(struct signal_struct *sig)
730 {
731 	if (refcount_dec_and_test(&sig->sigcnt))
732 		free_signal_struct(sig);
733 }
734 
__put_task_struct(struct task_struct * tsk)735 void __put_task_struct(struct task_struct *tsk)
736 {
737 	WARN_ON(!tsk->exit_state);
738 	WARN_ON(refcount_read(&tsk->usage));
739 	WARN_ON(tsk == current);
740 
741 	io_uring_free(tsk);
742 	cgroup_free(tsk);
743 	task_numa_free(tsk, true);
744 	security_task_free(tsk);
745 	exit_creds(tsk);
746 	delayacct_tsk_free(tsk);
747 	put_signal_struct(tsk->signal);
748 
749 	if (!profile_handoff_task(tsk))
750 		free_task(tsk);
751 }
752 EXPORT_SYMBOL_GPL(__put_task_struct);
753 
arch_task_cache_init(void)754 void __init __weak arch_task_cache_init(void) { }
755 
756 /*
757  * set_max_threads
758  */
set_max_threads(unsigned int max_threads_suggested)759 static void set_max_threads(unsigned int max_threads_suggested)
760 {
761 	u64 threads;
762 	unsigned long nr_pages = totalram_pages();
763 
764 	/*
765 	 * The number of threads shall be limited such that the thread
766 	 * structures may only consume a small part of the available memory.
767 	 */
768 	if (fls64(nr_pages) + fls64(PAGE_SIZE) > 64)
769 		threads = MAX_THREADS;
770 	else
771 		threads = div64_u64((u64) nr_pages * (u64) PAGE_SIZE,
772 				    (u64) THREAD_SIZE * 8UL);
773 
774 	if (threads > max_threads_suggested)
775 		threads = max_threads_suggested;
776 
777 	max_threads = clamp_t(u64, threads, MIN_THREADS, MAX_THREADS);
778 }
779 
780 #ifdef CONFIG_ARCH_WANTS_DYNAMIC_TASK_STRUCT
781 /* Initialized by the architecture: */
782 int arch_task_struct_size __read_mostly;
783 #endif
784 
785 #ifndef CONFIG_ARCH_TASK_STRUCT_ALLOCATOR
task_struct_whitelist(unsigned long * offset,unsigned long * size)786 static void task_struct_whitelist(unsigned long *offset, unsigned long *size)
787 {
788 	/* Fetch thread_struct whitelist for the architecture. */
789 	arch_thread_struct_whitelist(offset, size);
790 
791 	/*
792 	 * Handle zero-sized whitelist or empty thread_struct, otherwise
793 	 * adjust offset to position of thread_struct in task_struct.
794 	 */
795 	if (unlikely(*size == 0))
796 		*offset = 0;
797 	else
798 		*offset += offsetof(struct task_struct, thread);
799 }
800 #endif /* CONFIG_ARCH_TASK_STRUCT_ALLOCATOR */
801 
fork_init(void)802 void __init fork_init(void)
803 {
804 	int i;
805 #ifndef CONFIG_ARCH_TASK_STRUCT_ALLOCATOR
806 #ifndef ARCH_MIN_TASKALIGN
807 #define ARCH_MIN_TASKALIGN	0
808 #endif
809 	int align = max_t(int, L1_CACHE_BYTES, ARCH_MIN_TASKALIGN);
810 	unsigned long useroffset, usersize;
811 
812 	/* create a slab on which task_structs can be allocated */
813 	task_struct_whitelist(&useroffset, &usersize);
814 	task_struct_cachep = kmem_cache_create_usercopy("task_struct",
815 			arch_task_struct_size, align,
816 			SLAB_PANIC|SLAB_ACCOUNT,
817 			useroffset, usersize, NULL);
818 #endif
819 
820 	/* do the arch specific task caches init */
821 	arch_task_cache_init();
822 
823 	set_max_threads(MAX_THREADS);
824 
825 	init_task.signal->rlim[RLIMIT_NPROC].rlim_cur = max_threads/2;
826 	init_task.signal->rlim[RLIMIT_NPROC].rlim_max = max_threads/2;
827 	init_task.signal->rlim[RLIMIT_SIGPENDING] =
828 		init_task.signal->rlim[RLIMIT_NPROC];
829 
830 	for (i = 0; i < UCOUNT_COUNTS; i++) {
831 		init_user_ns.ucount_max[i] = max_threads/2;
832 	}
833 
834 #ifdef CONFIG_VMAP_STACK
835 	cpuhp_setup_state(CPUHP_BP_PREPARE_DYN, "fork:vm_stack_cache",
836 			  NULL, free_vm_stack_cache);
837 #endif
838 
839 	scs_init();
840 
841 	lockdep_init_task(&init_task);
842 	uprobes_init();
843 }
844 
arch_dup_task_struct(struct task_struct * dst,struct task_struct * src)845 int __weak arch_dup_task_struct(struct task_struct *dst,
846 					       struct task_struct *src)
847 {
848 	*dst = *src;
849 	return 0;
850 }
851 
set_task_stack_end_magic(struct task_struct * tsk)852 void set_task_stack_end_magic(struct task_struct *tsk)
853 {
854 	unsigned long *stackend;
855 
856 	stackend = end_of_stack(tsk);
857 	*stackend = STACK_END_MAGIC;	/* for overflow detection */
858 }
859 
dup_task_struct(struct task_struct * orig,int node)860 static struct task_struct *dup_task_struct(struct task_struct *orig, int node)
861 {
862 	struct task_struct *tsk;
863 	unsigned long *stack;
864 	struct vm_struct *stack_vm_area __maybe_unused;
865 	int err;
866 
867 	if (node == NUMA_NO_NODE)
868 		node = tsk_fork_get_node(orig);
869 	tsk = alloc_task_struct_node(node);
870 	if (!tsk)
871 		return NULL;
872 
873 	stack = alloc_thread_stack_node(tsk, node);
874 	if (!stack)
875 		goto free_tsk;
876 
877 	if (memcg_charge_kernel_stack(tsk))
878 		goto free_stack;
879 
880 	stack_vm_area = task_stack_vm_area(tsk);
881 
882 	err = arch_dup_task_struct(tsk, orig);
883 
884 #ifdef CONFIG_ACCESS_TOKENID
885 	tsk->token = orig->token;
886 	tsk->ftoken = 0;
887 #endif
888 	/*
889 	 * arch_dup_task_struct() clobbers the stack-related fields.  Make
890 	 * sure they're properly initialized before using any stack-related
891 	 * functions again.
892 	 */
893 	tsk->stack = stack;
894 #ifdef CONFIG_VMAP_STACK
895 	tsk->stack_vm_area = stack_vm_area;
896 #endif
897 #ifdef CONFIG_THREAD_INFO_IN_TASK
898 	refcount_set(&tsk->stack_refcount, 1);
899 #endif
900 
901 	if (err)
902 		goto free_stack;
903 
904 	err = scs_prepare(tsk, node);
905 	if (err)
906 		goto free_stack;
907 
908 #ifdef CONFIG_SECCOMP
909 	/*
910 	 * We must handle setting up seccomp filters once we're under
911 	 * the sighand lock in case orig has changed between now and
912 	 * then. Until then, filter must be NULL to avoid messing up
913 	 * the usage counts on the error path calling free_task.
914 	 */
915 	tsk->seccomp.filter = NULL;
916 #endif
917 
918 	setup_thread_stack(tsk, orig);
919 	clear_user_return_notifier(tsk);
920 	clear_tsk_need_resched(tsk);
921 	set_task_stack_end_magic(tsk);
922 
923 #ifdef CONFIG_STACKPROTECTOR
924 	tsk->stack_canary = get_random_canary();
925 #endif
926 	if (orig->cpus_ptr == &orig->cpus_mask)
927 		tsk->cpus_ptr = &tsk->cpus_mask;
928 
929 	/*
930 	 * One for the user space visible state that goes away when reaped.
931 	 * One for the scheduler.
932 	 */
933 	refcount_set(&tsk->rcu_users, 2);
934 	/* One for the rcu users */
935 	refcount_set(&tsk->usage, 1);
936 #ifdef CONFIG_BLK_DEV_IO_TRACE
937 	tsk->btrace_seq = 0;
938 #endif
939 	tsk->splice_pipe = NULL;
940 	tsk->task_frag.page = NULL;
941 	tsk->wake_q.next = NULL;
942 	tsk->pf_io_worker = NULL;
943 
944 	account_kernel_stack(tsk, 1);
945 
946 	kcov_task_init(tsk);
947 
948 #ifdef CONFIG_FAULT_INJECTION
949 	tsk->fail_nth = 0;
950 #endif
951 
952 #ifdef CONFIG_BLK_CGROUP
953 	tsk->throttle_queue = NULL;
954 	tsk->use_memdelay = 0;
955 #endif
956 
957 #ifdef CONFIG_MEMCG
958 	tsk->active_memcg = NULL;
959 #endif
960 	return tsk;
961 
962 free_stack:
963 	free_thread_stack(tsk);
964 free_tsk:
965 	free_task_struct(tsk);
966 	return NULL;
967 }
968 
969 __cacheline_aligned_in_smp DEFINE_SPINLOCK(mmlist_lock);
970 
971 static unsigned long default_dump_filter = MMF_DUMP_FILTER_DEFAULT;
972 
coredump_filter_setup(char * s)973 static int __init coredump_filter_setup(char *s)
974 {
975 	default_dump_filter =
976 		(simple_strtoul(s, NULL, 0) << MMF_DUMP_FILTER_SHIFT) &
977 		MMF_DUMP_FILTER_MASK;
978 	return 1;
979 }
980 
981 __setup("coredump_filter=", coredump_filter_setup);
982 
983 #include <linux/init_task.h>
984 
mm_init_aio(struct mm_struct * mm)985 static void mm_init_aio(struct mm_struct *mm)
986 {
987 #ifdef CONFIG_AIO
988 	spin_lock_init(&mm->ioctx_lock);
989 	mm->ioctx_table = NULL;
990 #endif
991 }
992 
mm_clear_owner(struct mm_struct * mm,struct task_struct * p)993 static __always_inline void mm_clear_owner(struct mm_struct *mm,
994 					   struct task_struct *p)
995 {
996 #ifdef CONFIG_MEMCG
997 	if (mm->owner == p)
998 		WRITE_ONCE(mm->owner, NULL);
999 #endif
1000 }
1001 
mm_init_owner(struct mm_struct * mm,struct task_struct * p)1002 static void mm_init_owner(struct mm_struct *mm, struct task_struct *p)
1003 {
1004 #ifdef CONFIG_MEMCG
1005 	mm->owner = p;
1006 #endif
1007 }
1008 
mm_init_pasid(struct mm_struct * mm)1009 static void mm_init_pasid(struct mm_struct *mm)
1010 {
1011 #ifdef CONFIG_IOMMU_SUPPORT
1012 	mm->pasid = INIT_PASID;
1013 #endif
1014 }
1015 
mm_init_uprobes_state(struct mm_struct * mm)1016 static void mm_init_uprobes_state(struct mm_struct *mm)
1017 {
1018 #ifdef CONFIG_UPROBES
1019 	mm->uprobes_state.xol_area = NULL;
1020 #endif
1021 }
1022 
mm_init(struct mm_struct * mm,struct task_struct * p,struct user_namespace * user_ns)1023 static struct mm_struct *mm_init(struct mm_struct *mm, struct task_struct *p,
1024 	struct user_namespace *user_ns)
1025 {
1026 	mm->mmap = NULL;
1027 	mm->mm_rb = RB_ROOT;
1028 	mm->vmacache_seqnum = 0;
1029 #ifdef CONFIG_RSS_THRESHOLD
1030 	mm->rss_threshold = 0;
1031 #endif
1032 	atomic_set(&mm->mm_users, 1);
1033 	atomic_set(&mm->mm_count, 1);
1034 	seqcount_init(&mm->write_protect_seq);
1035 	mmap_init_lock(mm);
1036 	INIT_LIST_HEAD(&mm->mmlist);
1037 	mm->core_state = NULL;
1038 	mm_pgtables_bytes_init(mm);
1039 	mm->map_count = 0;
1040 	mm->locked_vm = 0;
1041 	atomic_set(&mm->has_pinned, 0);
1042 	atomic64_set(&mm->pinned_vm, 0);
1043 	memset(&mm->rss_stat, 0, sizeof(mm->rss_stat));
1044 	spin_lock_init(&mm->page_table_lock);
1045 	spin_lock_init(&mm->arg_lock);
1046 	mm_init_cpumask(mm);
1047 	mm_init_aio(mm);
1048 	mm_init_owner(mm, p);
1049 	mm_init_pasid(mm);
1050 	RCU_INIT_POINTER(mm->exe_file, NULL);
1051 	mmu_notifier_subscriptions_init(mm);
1052 	init_tlb_flush_pending(mm);
1053 #if defined(CONFIG_TRANSPARENT_HUGEPAGE) && !USE_SPLIT_PMD_PTLOCKS
1054 	mm->pmd_huge_pte = NULL;
1055 #endif
1056 	mm_init_uprobes_state(mm);
1057 	hugetlb_count_init(mm);
1058 
1059 	if (current->mm) {
1060 		mm->flags = current->mm->flags & MMF_INIT_MASK;
1061 		mm->def_flags = current->mm->def_flags & VM_INIT_DEF_MASK;
1062 	} else {
1063 		mm->flags = default_dump_filter;
1064 		mm->def_flags = 0;
1065 	}
1066 
1067 	if (mm_alloc_pgd(mm))
1068 		goto fail_nopgd;
1069 
1070 	if (init_new_context(p, mm))
1071 		goto fail_nocontext;
1072 
1073 	mm->user_ns = get_user_ns(user_ns);
1074 	return mm;
1075 
1076 fail_nocontext:
1077 	mm_free_pgd(mm);
1078 fail_nopgd:
1079 	free_mm(mm);
1080 	return NULL;
1081 }
1082 
1083 /*
1084  * Allocate and initialize an mm_struct.
1085  */
mm_alloc(void)1086 struct mm_struct *mm_alloc(void)
1087 {
1088 	struct mm_struct *mm;
1089 
1090 	mm = allocate_mm();
1091 	if (!mm)
1092 		return NULL;
1093 
1094 	memset(mm, 0, sizeof(*mm));
1095 	return mm_init(mm, current, current_user_ns());
1096 }
1097 
__mmput(struct mm_struct * mm)1098 static inline void __mmput(struct mm_struct *mm)
1099 {
1100 	VM_BUG_ON(atomic_read(&mm->mm_users));
1101 
1102 	uprobe_clear_state(mm);
1103 	exit_aio(mm);
1104 	ksm_exit(mm);
1105 	khugepaged_exit(mm); /* must run before exit_mmap */
1106 	exit_mmap(mm);
1107 	mm_put_huge_zero_page(mm);
1108 	set_mm_exe_file(mm, NULL);
1109 	if (!list_empty(&mm->mmlist)) {
1110 		spin_lock(&mmlist_lock);
1111 		list_del(&mm->mmlist);
1112 		spin_unlock(&mmlist_lock);
1113 	}
1114 	if (mm->binfmt)
1115 		module_put(mm->binfmt->module);
1116 	mmdrop(mm);
1117 }
1118 
1119 /*
1120  * Decrement the use count and release all resources for an mm.
1121  */
mmput(struct mm_struct * mm)1122 void mmput(struct mm_struct *mm)
1123 {
1124 	might_sleep();
1125 
1126 	if (atomic_dec_and_test(&mm->mm_users))
1127 		__mmput(mm);
1128 }
1129 EXPORT_SYMBOL_GPL(mmput);
1130 
1131 #ifdef CONFIG_MMU
mmput_async_fn(struct work_struct * work)1132 static void mmput_async_fn(struct work_struct *work)
1133 {
1134 	struct mm_struct *mm = container_of(work, struct mm_struct,
1135 					    async_put_work);
1136 
1137 	__mmput(mm);
1138 }
1139 
mmput_async(struct mm_struct * mm)1140 void mmput_async(struct mm_struct *mm)
1141 {
1142 	if (atomic_dec_and_test(&mm->mm_users)) {
1143 		INIT_WORK(&mm->async_put_work, mmput_async_fn);
1144 		schedule_work(&mm->async_put_work);
1145 	}
1146 }
1147 EXPORT_SYMBOL_GPL(mmput_async);
1148 #endif
1149 
1150 /**
1151  * set_mm_exe_file - change a reference to the mm's executable file
1152  *
1153  * This changes mm's executable file (shown as symlink /proc/[pid]/exe).
1154  *
1155  * Main users are mmput() and sys_execve(). Callers prevent concurrent
1156  * invocations: in mmput() nobody alive left, in execve task is single
1157  * threaded. sys_prctl(PR_SET_MM_MAP/EXE_FILE) also needs to set the
1158  * mm->exe_file, but does so without using set_mm_exe_file() in order
1159  * to do avoid the need for any locks.
1160  */
set_mm_exe_file(struct mm_struct * mm,struct file * new_exe_file)1161 void set_mm_exe_file(struct mm_struct *mm, struct file *new_exe_file)
1162 {
1163 	struct file *old_exe_file;
1164 
1165 	/*
1166 	 * It is safe to dereference the exe_file without RCU as
1167 	 * this function is only called if nobody else can access
1168 	 * this mm -- see comment above for justification.
1169 	 */
1170 	old_exe_file = rcu_dereference_raw(mm->exe_file);
1171 
1172 	if (new_exe_file)
1173 		get_file(new_exe_file);
1174 	rcu_assign_pointer(mm->exe_file, new_exe_file);
1175 	if (old_exe_file)
1176 		fput(old_exe_file);
1177 }
1178 
1179 /**
1180  * get_mm_exe_file - acquire a reference to the mm's executable file
1181  *
1182  * Returns %NULL if mm has no associated executable file.
1183  * User must release file via fput().
1184  */
get_mm_exe_file(struct mm_struct * mm)1185 struct file *get_mm_exe_file(struct mm_struct *mm)
1186 {
1187 	struct file *exe_file;
1188 
1189 	rcu_read_lock();
1190 	exe_file = rcu_dereference(mm->exe_file);
1191 	if (exe_file && !get_file_rcu(exe_file))
1192 		exe_file = NULL;
1193 	rcu_read_unlock();
1194 	return exe_file;
1195 }
1196 EXPORT_SYMBOL(get_mm_exe_file);
1197 
1198 /**
1199  * get_task_exe_file - acquire a reference to the task's executable file
1200  *
1201  * Returns %NULL if task's mm (if any) has no associated executable file or
1202  * this is a kernel thread with borrowed mm (see the comment above get_task_mm).
1203  * User must release file via fput().
1204  */
get_task_exe_file(struct task_struct * task)1205 struct file *get_task_exe_file(struct task_struct *task)
1206 {
1207 	struct file *exe_file = NULL;
1208 	struct mm_struct *mm;
1209 
1210 	task_lock(task);
1211 	mm = task->mm;
1212 	if (mm) {
1213 		if (!(task->flags & PF_KTHREAD))
1214 			exe_file = get_mm_exe_file(mm);
1215 	}
1216 	task_unlock(task);
1217 	return exe_file;
1218 }
1219 EXPORT_SYMBOL(get_task_exe_file);
1220 
1221 /**
1222  * get_task_mm - acquire a reference to the task's mm
1223  *
1224  * Returns %NULL if the task has no mm.  Checks PF_KTHREAD (meaning
1225  * this kernel workthread has transiently adopted a user mm with use_mm,
1226  * to do its AIO) is not set and if so returns a reference to it, after
1227  * bumping up the use count.  User must release the mm via mmput()
1228  * after use.  Typically used by /proc and ptrace.
1229  */
get_task_mm(struct task_struct * task)1230 struct mm_struct *get_task_mm(struct task_struct *task)
1231 {
1232 	struct mm_struct *mm;
1233 
1234 	task_lock(task);
1235 	mm = task->mm;
1236 	if (mm) {
1237 		if (task->flags & PF_KTHREAD)
1238 			mm = NULL;
1239 		else
1240 			mmget(mm);
1241 	}
1242 	task_unlock(task);
1243 	return mm;
1244 }
1245 EXPORT_SYMBOL_GPL(get_task_mm);
1246 
mm_access(struct task_struct * task,unsigned int mode)1247 struct mm_struct *mm_access(struct task_struct *task, unsigned int mode)
1248 {
1249 	struct mm_struct *mm;
1250 	int err;
1251 
1252 	err =  down_read_killable(&task->signal->exec_update_lock);
1253 	if (err)
1254 		return ERR_PTR(err);
1255 
1256 	mm = get_task_mm(task);
1257 	if (mm && mm != current->mm &&
1258 			!ptrace_may_access(task, mode)) {
1259 		mmput(mm);
1260 		mm = ERR_PTR(-EACCES);
1261 	}
1262 	up_read(&task->signal->exec_update_lock);
1263 
1264 	return mm;
1265 }
1266 
complete_vfork_done(struct task_struct * tsk)1267 static void complete_vfork_done(struct task_struct *tsk)
1268 {
1269 	struct completion *vfork;
1270 
1271 	task_lock(tsk);
1272 	vfork = tsk->vfork_done;
1273 	if (likely(vfork)) {
1274 		tsk->vfork_done = NULL;
1275 		complete(vfork);
1276 	}
1277 	task_unlock(tsk);
1278 }
1279 
wait_for_vfork_done(struct task_struct * child,struct completion * vfork)1280 static int wait_for_vfork_done(struct task_struct *child,
1281 				struct completion *vfork)
1282 {
1283 	int killed;
1284 
1285 	freezer_do_not_count();
1286 	cgroup_enter_frozen();
1287 	killed = wait_for_completion_killable(vfork);
1288 	cgroup_leave_frozen(false);
1289 	freezer_count();
1290 
1291 	if (killed) {
1292 		task_lock(child);
1293 		child->vfork_done = NULL;
1294 		task_unlock(child);
1295 	}
1296 
1297 	put_task_struct(child);
1298 	return killed;
1299 }
1300 
1301 /* Please note the differences between mmput and mm_release.
1302  * mmput is called whenever we stop holding onto a mm_struct,
1303  * error success whatever.
1304  *
1305  * mm_release is called after a mm_struct has been removed
1306  * from the current process.
1307  *
1308  * This difference is important for error handling, when we
1309  * only half set up a mm_struct for a new process and need to restore
1310  * the old one.  Because we mmput the new mm_struct before
1311  * restoring the old one. . .
1312  * Eric Biederman 10 January 1998
1313  */
mm_release(struct task_struct * tsk,struct mm_struct * mm)1314 static void mm_release(struct task_struct *tsk, struct mm_struct *mm)
1315 {
1316 	uprobe_free_utask(tsk);
1317 
1318 	/* Get rid of any cached register state */
1319 	deactivate_mm(tsk, mm);
1320 
1321 	/*
1322 	 * Signal userspace if we're not exiting with a core dump
1323 	 * because we want to leave the value intact for debugging
1324 	 * purposes.
1325 	 */
1326 	if (tsk->clear_child_tid) {
1327 		if (!(tsk->signal->flags & SIGNAL_GROUP_COREDUMP) &&
1328 		    atomic_read(&mm->mm_users) > 1) {
1329 			/*
1330 			 * We don't check the error code - if userspace has
1331 			 * not set up a proper pointer then tough luck.
1332 			 */
1333 			put_user(0, tsk->clear_child_tid);
1334 			do_futex(tsk->clear_child_tid, FUTEX_WAKE,
1335 					1, NULL, NULL, 0, 0);
1336 		}
1337 		tsk->clear_child_tid = NULL;
1338 	}
1339 
1340 	/*
1341 	 * All done, finally we can wake up parent and return this mm to him.
1342 	 * Also kthread_stop() uses this completion for synchronization.
1343 	 */
1344 	if (tsk->vfork_done)
1345 		complete_vfork_done(tsk);
1346 }
1347 
exit_mm_release(struct task_struct * tsk,struct mm_struct * mm)1348 void exit_mm_release(struct task_struct *tsk, struct mm_struct *mm)
1349 {
1350 	futex_exit_release(tsk);
1351 	mm_release(tsk, mm);
1352 }
1353 
exec_mm_release(struct task_struct * tsk,struct mm_struct * mm)1354 void exec_mm_release(struct task_struct *tsk, struct mm_struct *mm)
1355 {
1356 	futex_exec_release(tsk);
1357 	mm_release(tsk, mm);
1358 }
1359 
1360 /**
1361  * dup_mm() - duplicates an existing mm structure
1362  * @tsk: the task_struct with which the new mm will be associated.
1363  * @oldmm: the mm to duplicate.
1364  *
1365  * Allocates a new mm structure and duplicates the provided @oldmm structure
1366  * content into it.
1367  *
1368  * Return: the duplicated mm or NULL on failure.
1369  */
dup_mm(struct task_struct * tsk,struct mm_struct * oldmm)1370 static struct mm_struct *dup_mm(struct task_struct *tsk,
1371 				struct mm_struct *oldmm)
1372 {
1373 	struct mm_struct *mm;
1374 	int err;
1375 
1376 	mm = allocate_mm();
1377 	if (!mm)
1378 		goto fail_nomem;
1379 
1380 	memcpy(mm, oldmm, sizeof(*mm));
1381 
1382 	if (!mm_init(mm, tsk, mm->user_ns))
1383 		goto fail_nomem;
1384 
1385 	err = dup_mmap(mm, oldmm);
1386 	if (err)
1387 		goto free_pt;
1388 
1389 	mm->hiwater_rss = get_mm_rss(mm);
1390 	mm->hiwater_vm = mm->total_vm;
1391 	#ifdef CONFIG_RSS_THRESHOLD
1392 	    mm->rss_threshold = oldmm->rss_threshold;
1393 	#endif
1394 
1395 	if (mm->binfmt && !try_module_get(mm->binfmt->module))
1396 		goto free_pt;
1397 
1398 	return mm;
1399 
1400 free_pt:
1401 	/* don't put binfmt in mmput, we haven't got module yet */
1402 	mm->binfmt = NULL;
1403 	mm_init_owner(mm, NULL);
1404 	mmput(mm);
1405 
1406 fail_nomem:
1407 	return NULL;
1408 }
1409 
copy_mm(unsigned long clone_flags,struct task_struct * tsk)1410 static int copy_mm(unsigned long clone_flags, struct task_struct *tsk)
1411 {
1412 	struct mm_struct *mm, *oldmm;
1413 	int retval;
1414 
1415 	tsk->min_flt = tsk->maj_flt = 0;
1416 	tsk->nvcsw = tsk->nivcsw = 0;
1417 #ifdef CONFIG_DETECT_HUNG_TASK
1418 	tsk->last_switch_count = tsk->nvcsw + tsk->nivcsw;
1419 	tsk->last_switch_time = 0;
1420 #endif
1421 
1422 	tsk->mm = NULL;
1423 	tsk->active_mm = NULL;
1424 
1425 	/*
1426 	 * Are we cloning a kernel thread?
1427 	 *
1428 	 * We need to steal a active VM for that..
1429 	 */
1430 	oldmm = current->mm;
1431 	if (!oldmm)
1432 		return 0;
1433 
1434 	/* initialize the new vmacache entries */
1435 	vmacache_flush(tsk);
1436 
1437 	if (clone_flags & CLONE_VM) {
1438 		mmget(oldmm);
1439 		mm = oldmm;
1440 		goto good_mm;
1441 	}
1442 
1443 	retval = -ENOMEM;
1444 	mm = dup_mm(tsk, current->mm);
1445 	if (!mm)
1446 		goto fail_nomem;
1447 
1448 good_mm:
1449 	tsk->mm = mm;
1450 	tsk->active_mm = mm;
1451 	return 0;
1452 
1453 fail_nomem:
1454 	return retval;
1455 }
1456 
copy_fs(unsigned long clone_flags,struct task_struct * tsk)1457 static int copy_fs(unsigned long clone_flags, struct task_struct *tsk)
1458 {
1459 	struct fs_struct *fs = current->fs;
1460 	if (clone_flags & CLONE_FS) {
1461 		/* tsk->fs is already what we want */
1462 		spin_lock(&fs->lock);
1463 		if (fs->in_exec) {
1464 			spin_unlock(&fs->lock);
1465 			return -EAGAIN;
1466 		}
1467 		fs->users++;
1468 		spin_unlock(&fs->lock);
1469 		return 0;
1470 	}
1471 	tsk->fs = copy_fs_struct(fs);
1472 	if (!tsk->fs)
1473 		return -ENOMEM;
1474 	return 0;
1475 }
1476 
copy_files(unsigned long clone_flags,struct task_struct * tsk)1477 static int copy_files(unsigned long clone_flags, struct task_struct *tsk)
1478 {
1479 	struct files_struct *oldf, *newf;
1480 	int error = 0;
1481 
1482 	/*
1483 	 * A background process may not have any files ...
1484 	 */
1485 	oldf = current->files;
1486 	if (!oldf)
1487 		goto out;
1488 
1489 	if (clone_flags & CLONE_FILES) {
1490 		atomic_inc(&oldf->count);
1491 		goto out;
1492 	}
1493 
1494 	newf = dup_fd(oldf, NR_OPEN_MAX, &error);
1495 	if (!newf)
1496 		goto out;
1497 
1498 	tsk->files = newf;
1499 	error = 0;
1500 out:
1501 	return error;
1502 }
1503 
copy_io(unsigned long clone_flags,struct task_struct * tsk)1504 static int copy_io(unsigned long clone_flags, struct task_struct *tsk)
1505 {
1506 #ifdef CONFIG_BLOCK
1507 	struct io_context *ioc = current->io_context;
1508 	struct io_context *new_ioc;
1509 
1510 	if (!ioc)
1511 		return 0;
1512 	/*
1513 	 * Share io context with parent, if CLONE_IO is set
1514 	 */
1515 	if (clone_flags & CLONE_IO) {
1516 		ioc_task_link(ioc);
1517 		tsk->io_context = ioc;
1518 	} else if (ioprio_valid(ioc->ioprio)) {
1519 		new_ioc = get_task_io_context(tsk, GFP_KERNEL, NUMA_NO_NODE);
1520 		if (unlikely(!new_ioc))
1521 			return -ENOMEM;
1522 
1523 		new_ioc->ioprio = ioc->ioprio;
1524 		put_io_context(new_ioc);
1525 	}
1526 #endif
1527 	return 0;
1528 }
1529 
copy_sighand(unsigned long clone_flags,struct task_struct * tsk)1530 static int copy_sighand(unsigned long clone_flags, struct task_struct *tsk)
1531 {
1532 	struct sighand_struct *sig;
1533 
1534 	if (clone_flags & CLONE_SIGHAND) {
1535 		refcount_inc(&current->sighand->count);
1536 		return 0;
1537 	}
1538 	sig = kmem_cache_alloc(sighand_cachep, GFP_KERNEL);
1539 	RCU_INIT_POINTER(tsk->sighand, sig);
1540 	if (!sig)
1541 		return -ENOMEM;
1542 
1543 	refcount_set(&sig->count, 1);
1544 	spin_lock_irq(&current->sighand->siglock);
1545 	memcpy(sig->action, current->sighand->action, sizeof(sig->action));
1546 	spin_unlock_irq(&current->sighand->siglock);
1547 
1548 	/* Reset all signal handler not set to SIG_IGN to SIG_DFL. */
1549 	if (clone_flags & CLONE_CLEAR_SIGHAND)
1550 		flush_signal_handlers(tsk, 0);
1551 
1552 	return 0;
1553 }
1554 
__cleanup_sighand(struct sighand_struct * sighand)1555 void __cleanup_sighand(struct sighand_struct *sighand)
1556 {
1557 	if (refcount_dec_and_test(&sighand->count)) {
1558 		signalfd_cleanup(sighand);
1559 		/*
1560 		 * sighand_cachep is SLAB_TYPESAFE_BY_RCU so we can free it
1561 		 * without an RCU grace period, see __lock_task_sighand().
1562 		 */
1563 		kmem_cache_free(sighand_cachep, sighand);
1564 	}
1565 }
1566 
1567 /*
1568  * Initialize POSIX timer handling for a thread group.
1569  */
posix_cpu_timers_init_group(struct signal_struct * sig)1570 static void posix_cpu_timers_init_group(struct signal_struct *sig)
1571 {
1572 	struct posix_cputimers *pct = &sig->posix_cputimers;
1573 	unsigned long cpu_limit;
1574 
1575 	cpu_limit = READ_ONCE(sig->rlim[RLIMIT_CPU].rlim_cur);
1576 	posix_cputimers_group_init(pct, cpu_limit);
1577 }
1578 
copy_signal(unsigned long clone_flags,struct task_struct * tsk)1579 static int copy_signal(unsigned long clone_flags, struct task_struct *tsk)
1580 {
1581 	struct signal_struct *sig;
1582 
1583 	if (clone_flags & CLONE_THREAD)
1584 		return 0;
1585 
1586 	sig = kmem_cache_zalloc(signal_cachep, GFP_KERNEL);
1587 	tsk->signal = sig;
1588 	if (!sig)
1589 		return -ENOMEM;
1590 
1591 	sig->nr_threads = 1;
1592 	atomic_set(&sig->live, 1);
1593 	refcount_set(&sig->sigcnt, 1);
1594 
1595 	/* list_add(thread_node, thread_head) without INIT_LIST_HEAD() */
1596 	sig->thread_head = (struct list_head)LIST_HEAD_INIT(tsk->thread_node);
1597 	tsk->thread_node = (struct list_head)LIST_HEAD_INIT(sig->thread_head);
1598 
1599 	init_waitqueue_head(&sig->wait_chldexit);
1600 	sig->curr_target = tsk;
1601 	init_sigpending(&sig->shared_pending);
1602 	INIT_HLIST_HEAD(&sig->multiprocess);
1603 	seqlock_init(&sig->stats_lock);
1604 	prev_cputime_init(&sig->prev_cputime);
1605 
1606 #ifdef CONFIG_POSIX_TIMERS
1607 	INIT_LIST_HEAD(&sig->posix_timers);
1608 	hrtimer_init(&sig->real_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
1609 	sig->real_timer.function = it_real_fn;
1610 #endif
1611 
1612 	task_lock(current->group_leader);
1613 	memcpy(sig->rlim, current->signal->rlim, sizeof sig->rlim);
1614 	task_unlock(current->group_leader);
1615 
1616 	posix_cpu_timers_init_group(sig);
1617 
1618 	tty_audit_fork(sig);
1619 	sched_autogroup_fork(sig);
1620 
1621 	sig->oom_score_adj = current->signal->oom_score_adj;
1622 	sig->oom_score_adj_min = current->signal->oom_score_adj_min;
1623 
1624 	mutex_init(&sig->cred_guard_mutex);
1625 	init_rwsem(&sig->exec_update_lock);
1626 
1627 	return 0;
1628 }
1629 
copy_seccomp(struct task_struct * p)1630 static void copy_seccomp(struct task_struct *p)
1631 {
1632 #ifdef CONFIG_SECCOMP
1633 	/*
1634 	 * Must be called with sighand->lock held, which is common to
1635 	 * all threads in the group. Holding cred_guard_mutex is not
1636 	 * needed because this new task is not yet running and cannot
1637 	 * be racing exec.
1638 	 */
1639 	assert_spin_locked(&current->sighand->siglock);
1640 
1641 	/* Ref-count the new filter user, and assign it. */
1642 	get_seccomp_filter(current);
1643 	p->seccomp = current->seccomp;
1644 
1645 	/*
1646 	 * Explicitly enable no_new_privs here in case it got set
1647 	 * between the task_struct being duplicated and holding the
1648 	 * sighand lock. The seccomp state and nnp must be in sync.
1649 	 */
1650 	if (task_no_new_privs(current))
1651 		task_set_no_new_privs(p);
1652 
1653 	/*
1654 	 * If the parent gained a seccomp mode after copying thread
1655 	 * flags and between before we held the sighand lock, we have
1656 	 * to manually enable the seccomp thread flag here.
1657 	 */
1658 	if (p->seccomp.mode != SECCOMP_MODE_DISABLED)
1659 		set_tsk_thread_flag(p, TIF_SECCOMP);
1660 #endif
1661 }
1662 
SYSCALL_DEFINE1(set_tid_address,int __user *,tidptr)1663 SYSCALL_DEFINE1(set_tid_address, int __user *, tidptr)
1664 {
1665 	current->clear_child_tid = tidptr;
1666 
1667 	return task_pid_vnr(current);
1668 }
1669 
rt_mutex_init_task(struct task_struct * p)1670 static void rt_mutex_init_task(struct task_struct *p)
1671 {
1672 	raw_spin_lock_init(&p->pi_lock);
1673 #ifdef CONFIG_RT_MUTEXES
1674 	p->pi_waiters = RB_ROOT_CACHED;
1675 	p->pi_top_task = NULL;
1676 	p->pi_blocked_on = NULL;
1677 #endif
1678 }
1679 
init_task_pid_links(struct task_struct * task)1680 static inline void init_task_pid_links(struct task_struct *task)
1681 {
1682 	enum pid_type type;
1683 
1684 	for (type = PIDTYPE_PID; type < PIDTYPE_MAX; ++type) {
1685 		INIT_HLIST_NODE(&task->pid_links[type]);
1686 	}
1687 }
1688 
1689 static inline void
init_task_pid(struct task_struct * task,enum pid_type type,struct pid * pid)1690 init_task_pid(struct task_struct *task, enum pid_type type, struct pid *pid)
1691 {
1692 	if (type == PIDTYPE_PID)
1693 		task->thread_pid = pid;
1694 	else
1695 		task->signal->pids[type] = pid;
1696 }
1697 
rcu_copy_process(struct task_struct * p)1698 static inline void rcu_copy_process(struct task_struct *p)
1699 {
1700 #ifdef CONFIG_PREEMPT_RCU
1701 	p->rcu_read_lock_nesting = 0;
1702 	p->rcu_read_unlock_special.s = 0;
1703 	p->rcu_blocked_node = NULL;
1704 	INIT_LIST_HEAD(&p->rcu_node_entry);
1705 #endif /* #ifdef CONFIG_PREEMPT_RCU */
1706 #ifdef CONFIG_TASKS_RCU
1707 	p->rcu_tasks_holdout = false;
1708 	INIT_LIST_HEAD(&p->rcu_tasks_holdout_list);
1709 	p->rcu_tasks_idle_cpu = -1;
1710 #endif /* #ifdef CONFIG_TASKS_RCU */
1711 #ifdef CONFIG_TASKS_TRACE_RCU
1712 	p->trc_reader_nesting = 0;
1713 	p->trc_reader_special.s = 0;
1714 	INIT_LIST_HEAD(&p->trc_holdout_list);
1715 #endif /* #ifdef CONFIG_TASKS_TRACE_RCU */
1716 }
1717 
pidfd_pid(const struct file * file)1718 struct pid *pidfd_pid(const struct file *file)
1719 {
1720 	if (file->f_op == &pidfd_fops)
1721 		return file->private_data;
1722 
1723 	return ERR_PTR(-EBADF);
1724 }
1725 
pidfd_release(struct inode * inode,struct file * file)1726 static int pidfd_release(struct inode *inode, struct file *file)
1727 {
1728 	struct pid *pid = file->private_data;
1729 
1730 	file->private_data = NULL;
1731 	put_pid(pid);
1732 	return 0;
1733 }
1734 
1735 #ifdef CONFIG_PROC_FS
1736 /**
1737  * pidfd_show_fdinfo - print information about a pidfd
1738  * @m: proc fdinfo file
1739  * @f: file referencing a pidfd
1740  *
1741  * Pid:
1742  * This function will print the pid that a given pidfd refers to in the
1743  * pid namespace of the procfs instance.
1744  * If the pid namespace of the process is not a descendant of the pid
1745  * namespace of the procfs instance 0 will be shown as its pid. This is
1746  * similar to calling getppid() on a process whose parent is outside of
1747  * its pid namespace.
1748  *
1749  * NSpid:
1750  * If pid namespaces are supported then this function will also print
1751  * the pid of a given pidfd refers to for all descendant pid namespaces
1752  * starting from the current pid namespace of the instance, i.e. the
1753  * Pid field and the first entry in the NSpid field will be identical.
1754  * If the pid namespace of the process is not a descendant of the pid
1755  * namespace of the procfs instance 0 will be shown as its first NSpid
1756  * entry and no others will be shown.
1757  * Note that this differs from the Pid and NSpid fields in
1758  * /proc/<pid>/status where Pid and NSpid are always shown relative to
1759  * the  pid namespace of the procfs instance. The difference becomes
1760  * obvious when sending around a pidfd between pid namespaces from a
1761  * different branch of the tree, i.e. where no ancestoral relation is
1762  * present between the pid namespaces:
1763  * - create two new pid namespaces ns1 and ns2 in the initial pid
1764  *   namespace (also take care to create new mount namespaces in the
1765  *   new pid namespace and mount procfs)
1766  * - create a process with a pidfd in ns1
1767  * - send pidfd from ns1 to ns2
1768  * - read /proc/self/fdinfo/<pidfd> and observe that both Pid and NSpid
1769  *   have exactly one entry, which is 0
1770  */
pidfd_show_fdinfo(struct seq_file * m,struct file * f)1771 static void pidfd_show_fdinfo(struct seq_file *m, struct file *f)
1772 {
1773 	struct pid *pid = f->private_data;
1774 	struct pid_namespace *ns;
1775 	pid_t nr = -1;
1776 
1777 	if (likely(pid_has_task(pid, PIDTYPE_PID))) {
1778 		ns = proc_pid_ns(file_inode(m->file)->i_sb);
1779 		nr = pid_nr_ns(pid, ns);
1780 	}
1781 
1782 	seq_put_decimal_ll(m, "Pid:\t", nr);
1783 
1784 #ifdef CONFIG_PID_NS
1785 	seq_put_decimal_ll(m, "\nNSpid:\t", nr);
1786 	if (nr > 0) {
1787 		int i;
1788 
1789 		/* If nr is non-zero it means that 'pid' is valid and that
1790 		 * ns, i.e. the pid namespace associated with the procfs
1791 		 * instance, is in the pid namespace hierarchy of pid.
1792 		 * Start at one below the already printed level.
1793 		 */
1794 		for (i = ns->level + 1; i <= pid->level; i++)
1795 			seq_put_decimal_ll(m, "\t", pid->numbers[i].nr);
1796 	}
1797 #endif
1798 	seq_putc(m, '\n');
1799 }
1800 #endif
1801 
1802 /*
1803  * Poll support for process exit notification.
1804  */
pidfd_poll(struct file * file,struct poll_table_struct * pts)1805 static __poll_t pidfd_poll(struct file *file, struct poll_table_struct *pts)
1806 {
1807 	struct pid *pid = file->private_data;
1808 	__poll_t poll_flags = 0;
1809 
1810 	poll_wait(file, &pid->wait_pidfd, pts);
1811 
1812 	/*
1813 	 * Inform pollers only when the whole thread group exits.
1814 	 * If the thread group leader exits before all other threads in the
1815 	 * group, then poll(2) should block, similar to the wait(2) family.
1816 	 */
1817 	if (thread_group_exited(pid))
1818 		poll_flags = EPOLLIN | EPOLLRDNORM;
1819 
1820 	return poll_flags;
1821 }
1822 
1823 const struct file_operations pidfd_fops = {
1824 	.release = pidfd_release,
1825 	.poll = pidfd_poll,
1826 #ifdef CONFIG_PROC_FS
1827 	.show_fdinfo = pidfd_show_fdinfo,
1828 #endif
1829 };
1830 
__delayed_free_task(struct rcu_head * rhp)1831 static void __delayed_free_task(struct rcu_head *rhp)
1832 {
1833 	struct task_struct *tsk = container_of(rhp, struct task_struct, rcu);
1834 
1835 	free_task(tsk);
1836 }
1837 
delayed_free_task(struct task_struct * tsk)1838 static __always_inline void delayed_free_task(struct task_struct *tsk)
1839 {
1840 	if (IS_ENABLED(CONFIG_MEMCG))
1841 		call_rcu(&tsk->rcu, __delayed_free_task);
1842 	else
1843 		free_task(tsk);
1844 }
1845 
copy_oom_score_adj(u64 clone_flags,struct task_struct * tsk)1846 static void copy_oom_score_adj(u64 clone_flags, struct task_struct *tsk)
1847 {
1848 	/* Skip if kernel thread */
1849 	if (!tsk->mm)
1850 		return;
1851 
1852 	/* Skip if spawning a thread or using vfork */
1853 	if ((clone_flags & (CLONE_VM | CLONE_THREAD | CLONE_VFORK)) != CLONE_VM)
1854 		return;
1855 
1856 	/* We need to synchronize with __set_oom_adj */
1857 	mutex_lock(&oom_adj_mutex);
1858 	set_bit(MMF_MULTIPROCESS, &tsk->mm->flags);
1859 	/* Update the values in case they were changed after copy_signal */
1860 	tsk->signal->oom_score_adj = current->signal->oom_score_adj;
1861 	tsk->signal->oom_score_adj_min = current->signal->oom_score_adj_min;
1862 	mutex_unlock(&oom_adj_mutex);
1863 }
1864 
1865 /*
1866  * This creates a new process as a copy of the old one,
1867  * but does not actually start it yet.
1868  *
1869  * It copies the registers, and all the appropriate
1870  * parts of the process environment (as per the clone
1871  * flags). The actual kick-off is left to the caller.
1872  */
copy_process(struct pid * pid,int trace,int node,struct kernel_clone_args * args)1873 static __latent_entropy struct task_struct *copy_process(
1874 					struct pid *pid,
1875 					int trace,
1876 					int node,
1877 					struct kernel_clone_args *args)
1878 {
1879 	int pidfd = -1, retval;
1880 	struct task_struct *p;
1881 	struct multiprocess_signals delayed;
1882 	struct file *pidfile = NULL;
1883 	u64 clone_flags = args->flags;
1884 	struct nsproxy *nsp = current->nsproxy;
1885 
1886 	/*
1887 	 * Don't allow sharing the root directory with processes in a different
1888 	 * namespace
1889 	 */
1890 	if ((clone_flags & (CLONE_NEWNS|CLONE_FS)) == (CLONE_NEWNS|CLONE_FS))
1891 		return ERR_PTR(-EINVAL);
1892 
1893 	if ((clone_flags & (CLONE_NEWUSER|CLONE_FS)) == (CLONE_NEWUSER|CLONE_FS))
1894 		return ERR_PTR(-EINVAL);
1895 
1896 	/*
1897 	 * Thread groups must share signals as well, and detached threads
1898 	 * can only be started up within the thread group.
1899 	 */
1900 	if ((clone_flags & CLONE_THREAD) && !(clone_flags & CLONE_SIGHAND))
1901 		return ERR_PTR(-EINVAL);
1902 
1903 	/*
1904 	 * Shared signal handlers imply shared VM. By way of the above,
1905 	 * thread groups also imply shared VM. Blocking this case allows
1906 	 * for various simplifications in other code.
1907 	 */
1908 	if ((clone_flags & CLONE_SIGHAND) && !(clone_flags & CLONE_VM))
1909 		return ERR_PTR(-EINVAL);
1910 
1911 	/*
1912 	 * Siblings of global init remain as zombies on exit since they are
1913 	 * not reaped by their parent (swapper). To solve this and to avoid
1914 	 * multi-rooted process trees, prevent global and container-inits
1915 	 * from creating siblings.
1916 	 */
1917 	if ((clone_flags & CLONE_PARENT) &&
1918 				current->signal->flags & SIGNAL_UNKILLABLE)
1919 		return ERR_PTR(-EINVAL);
1920 
1921 	/*
1922 	 * If the new process will be in a different pid or user namespace
1923 	 * do not allow it to share a thread group with the forking task.
1924 	 */
1925 	if (clone_flags & CLONE_THREAD) {
1926 		if ((clone_flags & (CLONE_NEWUSER | CLONE_NEWPID)) ||
1927 		    (task_active_pid_ns(current) != nsp->pid_ns_for_children))
1928 			return ERR_PTR(-EINVAL);
1929 	}
1930 
1931 	/*
1932 	 * If the new process will be in a different time namespace
1933 	 * do not allow it to share VM or a thread group with the forking task.
1934 	 */
1935 	if (clone_flags & (CLONE_THREAD | CLONE_VM)) {
1936 		if (nsp->time_ns != nsp->time_ns_for_children)
1937 			return ERR_PTR(-EINVAL);
1938 	}
1939 
1940 	if (clone_flags & CLONE_PIDFD) {
1941 		/*
1942 		 * - CLONE_DETACHED is blocked so that we can potentially
1943 		 *   reuse it later for CLONE_PIDFD.
1944 		 * - CLONE_THREAD is blocked until someone really needs it.
1945 		 */
1946 		if (clone_flags & (CLONE_DETACHED | CLONE_THREAD))
1947 			return ERR_PTR(-EINVAL);
1948 	}
1949 
1950 	/*
1951 	 * Force any signals received before this point to be delivered
1952 	 * before the fork happens.  Collect up signals sent to multiple
1953 	 * processes that happen during the fork and delay them so that
1954 	 * they appear to happen after the fork.
1955 	 */
1956 	sigemptyset(&delayed.signal);
1957 	INIT_HLIST_NODE(&delayed.node);
1958 
1959 	spin_lock_irq(&current->sighand->siglock);
1960 	if (!(clone_flags & CLONE_THREAD))
1961 		hlist_add_head(&delayed.node, &current->signal->multiprocess);
1962 	recalc_sigpending();
1963 	spin_unlock_irq(&current->sighand->siglock);
1964 	retval = -ERESTARTNOINTR;
1965 	if (task_sigpending(current))
1966 		goto fork_out;
1967 
1968 	retval = -ENOMEM;
1969 	p = dup_task_struct(current, node);
1970 	if (!p)
1971 		goto fork_out;
1972 	if (args->io_thread) {
1973 		/*
1974 		 * Mark us an IO worker, and block any signal that isn't
1975 		 * fatal or STOP
1976 		 */
1977 		p->flags |= PF_IO_WORKER;
1978 		siginitsetinv(&p->blocked, sigmask(SIGKILL)|sigmask(SIGSTOP));
1979 	}
1980 
1981 	/*
1982 	 * This _must_ happen before we call free_task(), i.e. before we jump
1983 	 * to any of the bad_fork_* labels. This is to avoid freeing
1984 	 * p->set_child_tid which is (ab)used as a kthread's data pointer for
1985 	 * kernel threads (PF_KTHREAD).
1986 	 */
1987 	p->set_child_tid = (clone_flags & CLONE_CHILD_SETTID) ? args->child_tid : NULL;
1988 	/*
1989 	 * Clear TID on mm_release()?
1990 	 */
1991 	p->clear_child_tid = (clone_flags & CLONE_CHILD_CLEARTID) ? args->child_tid : NULL;
1992 
1993 	ftrace_graph_init_task(p);
1994 
1995 	rt_mutex_init_task(p);
1996 
1997 	lockdep_assert_irqs_enabled();
1998 #ifdef CONFIG_PROVE_LOCKING
1999 	DEBUG_LOCKS_WARN_ON(!p->softirqs_enabled);
2000 #endif
2001 	retval = -EAGAIN;
2002 	if (atomic_read(&p->real_cred->user->processes) >=
2003 			task_rlimit(p, RLIMIT_NPROC)) {
2004 		if (p->real_cred->user != INIT_USER &&
2005 		    !capable(CAP_SYS_RESOURCE) && !capable(CAP_SYS_ADMIN))
2006 			goto bad_fork_free;
2007 	}
2008 	current->flags &= ~PF_NPROC_EXCEEDED;
2009 
2010 	retval = copy_creds(p, clone_flags);
2011 	if (retval < 0)
2012 		goto bad_fork_free;
2013 
2014 	/*
2015 	 * If multiple threads are within copy_process(), then this check
2016 	 * triggers too late. This doesn't hurt, the check is only there
2017 	 * to stop root fork bombs.
2018 	 */
2019 	retval = -EAGAIN;
2020 	if (data_race(nr_threads >= max_threads))
2021 		goto bad_fork_cleanup_count;
2022 
2023 	delayacct_tsk_init(p);	/* Must remain after dup_task_struct() */
2024 #ifdef CONFIG_RECLAIM_ACCT
2025 	reclaimacct_tsk_init(p);
2026 #endif
2027 	p->flags &= ~(PF_SUPERPRIV | PF_WQ_WORKER | PF_IDLE);
2028 	p->flags |= PF_FORKNOEXEC;
2029 	INIT_LIST_HEAD(&p->children);
2030 	INIT_LIST_HEAD(&p->sibling);
2031 	rcu_copy_process(p);
2032 	p->vfork_done = NULL;
2033 	spin_lock_init(&p->alloc_lock);
2034 
2035 	init_sigpending(&p->pending);
2036 
2037 	p->utime = p->stime = p->gtime = 0;
2038 #ifdef CONFIG_ARCH_HAS_SCALED_CPUTIME
2039 	p->utimescaled = p->stimescaled = 0;
2040 #endif
2041 	prev_cputime_init(&p->prev_cputime);
2042 
2043 #ifdef CONFIG_VIRT_CPU_ACCOUNTING_GEN
2044 	seqcount_init(&p->vtime.seqcount);
2045 	p->vtime.starttime = 0;
2046 	p->vtime.state = VTIME_INACTIVE;
2047 #endif
2048 
2049 #ifdef CONFIG_IO_URING
2050 	p->io_uring = NULL;
2051 #endif
2052 
2053 #if defined(SPLIT_RSS_COUNTING)
2054 	memset(&p->rss_stat, 0, sizeof(p->rss_stat));
2055 #endif
2056 
2057 	p->default_timer_slack_ns = current->timer_slack_ns;
2058 
2059 #ifdef CONFIG_PSI
2060 	p->psi_flags = 0;
2061 #endif
2062 
2063 	task_io_accounting_init(&p->ioac);
2064 	acct_clear_integrals(p);
2065 
2066 	posix_cputimers_init(&p->posix_cputimers);
2067 
2068 	p->io_context = NULL;
2069 	audit_set_context(p, NULL);
2070 	cgroup_fork(p);
2071 #ifdef CONFIG_NUMA
2072 	p->mempolicy = mpol_dup(p->mempolicy);
2073 	if (IS_ERR(p->mempolicy)) {
2074 		retval = PTR_ERR(p->mempolicy);
2075 		p->mempolicy = NULL;
2076 		goto bad_fork_cleanup_threadgroup_lock;
2077 	}
2078 #endif
2079 #ifdef CONFIG_CPUSETS
2080 	p->cpuset_mem_spread_rotor = NUMA_NO_NODE;
2081 	p->cpuset_slab_spread_rotor = NUMA_NO_NODE;
2082 	seqcount_spinlock_init(&p->mems_allowed_seq, &p->alloc_lock);
2083 #endif
2084 #ifdef CONFIG_TRACE_IRQFLAGS
2085 	memset(&p->irqtrace, 0, sizeof(p->irqtrace));
2086 	p->irqtrace.hardirq_disable_ip	= _THIS_IP_;
2087 	p->irqtrace.softirq_enable_ip	= _THIS_IP_;
2088 	p->softirqs_enabled		= 1;
2089 	p->softirq_context		= 0;
2090 #endif
2091 
2092 	p->pagefault_disabled = 0;
2093 
2094 #ifdef CONFIG_LOCKDEP
2095 	lockdep_init_task(p);
2096 #endif
2097 
2098 #ifdef CONFIG_DEBUG_MUTEXES
2099 	p->blocked_on = NULL; /* not blocked yet */
2100 #endif
2101 #ifdef CONFIG_BCACHE
2102 	p->sequential_io	= 0;
2103 	p->sequential_io_avg	= 0;
2104 #endif
2105 #ifdef CONFIG_BPF_SYSCALL
2106 	p->bpf_ctx = NULL;
2107 #endif
2108 
2109 	/* Perform scheduler related setup. Assign this task to a CPU. */
2110 	retval = sched_fork(clone_flags, p);
2111 	if (retval)
2112 		goto bad_fork_cleanup_policy;
2113 
2114 	retval = perf_event_init_task(p);
2115 	if (retval)
2116 		goto bad_fork_cleanup_policy;
2117 	retval = audit_alloc(p);
2118 	if (retval)
2119 		goto bad_fork_cleanup_perf;
2120 	/* copy all the process information */
2121 	shm_init_task(p);
2122 	retval = security_task_alloc(p, clone_flags);
2123 	if (retval)
2124 		goto bad_fork_cleanup_audit;
2125 	retval = copy_semundo(clone_flags, p);
2126 	if (retval)
2127 		goto bad_fork_cleanup_security;
2128 	retval = copy_files(clone_flags, p);
2129 	if (retval)
2130 		goto bad_fork_cleanup_semundo;
2131 	retval = copy_fs(clone_flags, p);
2132 	if (retval)
2133 		goto bad_fork_cleanup_files;
2134 	retval = copy_sighand(clone_flags, p);
2135 	if (retval)
2136 		goto bad_fork_cleanup_fs;
2137 	retval = copy_signal(clone_flags, p);
2138 	if (retval)
2139 		goto bad_fork_cleanup_sighand;
2140 	retval = copy_mm(clone_flags, p);
2141 	if (retval)
2142 		goto bad_fork_cleanup_signal;
2143 	retval = copy_namespaces(clone_flags, p);
2144 	if (retval)
2145 		goto bad_fork_cleanup_mm;
2146 	retval = copy_io(clone_flags, p);
2147 	if (retval)
2148 		goto bad_fork_cleanup_namespaces;
2149 	retval = copy_thread(clone_flags, args->stack, args->stack_size, p, args->tls);
2150 	if (retval)
2151 		goto bad_fork_cleanup_io;
2152 
2153 	stackleak_task_init(p);
2154 
2155 	if (pid != &init_struct_pid) {
2156 		pid = alloc_pid(p->nsproxy->pid_ns_for_children, args->set_tid,
2157 				args->set_tid_size);
2158 		if (IS_ERR(pid)) {
2159 			retval = PTR_ERR(pid);
2160 			goto bad_fork_cleanup_thread;
2161 		}
2162 	}
2163 
2164 	/*
2165 	 * This has to happen after we've potentially unshared the file
2166 	 * descriptor table (so that the pidfd doesn't leak into the child
2167 	 * if the fd table isn't shared).
2168 	 */
2169 	if (clone_flags & CLONE_PIDFD) {
2170 		retval = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
2171 		if (retval < 0)
2172 			goto bad_fork_free_pid;
2173 
2174 		pidfd = retval;
2175 
2176 		pidfile = anon_inode_getfile("[pidfd]", &pidfd_fops, pid,
2177 					      O_RDWR | O_CLOEXEC);
2178 		if (IS_ERR(pidfile)) {
2179 			put_unused_fd(pidfd);
2180 			retval = PTR_ERR(pidfile);
2181 			goto bad_fork_free_pid;
2182 		}
2183 		get_pid(pid);	/* held by pidfile now */
2184 
2185 		retval = put_user(pidfd, args->pidfd);
2186 		if (retval)
2187 			goto bad_fork_put_pidfd;
2188 	}
2189 
2190 #ifdef CONFIG_BLOCK
2191 	p->plug = NULL;
2192 #endif
2193 	futex_init_task(p);
2194 
2195 	/*
2196 	 * sigaltstack should be cleared when sharing the same VM
2197 	 */
2198 	if ((clone_flags & (CLONE_VM|CLONE_VFORK)) == CLONE_VM)
2199 		sas_ss_reset(p);
2200 
2201 	/*
2202 	 * Syscall tracing and stepping should be turned off in the
2203 	 * child regardless of CLONE_PTRACE.
2204 	 */
2205 	user_disable_single_step(p);
2206 	clear_tsk_thread_flag(p, TIF_SYSCALL_TRACE);
2207 #ifdef TIF_SYSCALL_EMU
2208 	clear_tsk_thread_flag(p, TIF_SYSCALL_EMU);
2209 #endif
2210 	clear_tsk_latency_tracing(p);
2211 
2212 	/* ok, now we should be set up.. */
2213 	p->pid = pid_nr(pid);
2214 	if (clone_flags & CLONE_THREAD) {
2215 		p->group_leader = current->group_leader;
2216 		p->tgid = current->tgid;
2217 	} else {
2218 		p->group_leader = p;
2219 		p->tgid = p->pid;
2220 	}
2221 
2222 	p->nr_dirtied = 0;
2223 	p->nr_dirtied_pause = 128 >> (PAGE_SHIFT - 10);
2224 	p->dirty_paused_when = 0;
2225 
2226 	p->pdeath_signal = 0;
2227 	INIT_LIST_HEAD(&p->thread_group);
2228 	p->task_works = NULL;
2229 	clear_posix_cputimers_work(p);
2230 
2231 	/*
2232 	 * Ensure that the cgroup subsystem policies allow the new process to be
2233 	 * forked. It should be noted that the new process's css_set can be changed
2234 	 * between here and cgroup_post_fork() if an organisation operation is in
2235 	 * progress.
2236 	 */
2237 	retval = cgroup_can_fork(p, args);
2238 	if (retval)
2239 		goto bad_fork_put_pidfd;
2240 
2241 	/*
2242 	 * From this point on we must avoid any synchronous user-space
2243 	 * communication until we take the tasklist-lock. In particular, we do
2244 	 * not want user-space to be able to predict the process start-time by
2245 	 * stalling fork(2) after we recorded the start_time but before it is
2246 	 * visible to the system.
2247 	 */
2248 
2249 	p->start_time = ktime_get_ns();
2250 	p->start_boottime = ktime_get_boottime_ns();
2251 
2252 	/*
2253 	 * Make it visible to the rest of the system, but dont wake it up yet.
2254 	 * Need tasklist lock for parent etc handling!
2255 	 */
2256 	write_lock_irq(&tasklist_lock);
2257 
2258 	/* CLONE_PARENT re-uses the old parent */
2259 	if (clone_flags & (CLONE_PARENT|CLONE_THREAD)) {
2260 		p->real_parent = current->real_parent;
2261 		p->parent_exec_id = current->parent_exec_id;
2262 		if (clone_flags & CLONE_THREAD)
2263 			p->exit_signal = -1;
2264 		else
2265 			p->exit_signal = current->group_leader->exit_signal;
2266 	} else {
2267 		p->real_parent = current;
2268 		p->parent_exec_id = current->self_exec_id;
2269 		p->exit_signal = args->exit_signal;
2270 	}
2271 
2272 	klp_copy_process(p);
2273 
2274 	spin_lock(&current->sighand->siglock);
2275 
2276 	/*
2277 	 * Copy seccomp details explicitly here, in case they were changed
2278 	 * before holding sighand lock.
2279 	 */
2280 	copy_seccomp(p);
2281 
2282 	rseq_fork(p, clone_flags);
2283 
2284 	/* Don't start children in a dying pid namespace */
2285 	if (unlikely(!(ns_of_pid(pid)->pid_allocated & PIDNS_ADDING))) {
2286 		retval = -ENOMEM;
2287 		goto bad_fork_cancel_cgroup;
2288 	}
2289 
2290 	/* Let kill terminate clone/fork in the middle */
2291 	if (fatal_signal_pending(current)) {
2292 		retval = -EINTR;
2293 		goto bad_fork_cancel_cgroup;
2294 	}
2295 
2296 	init_task_pid_links(p);
2297 	if (likely(p->pid)) {
2298 		ptrace_init_task(p, (clone_flags & CLONE_PTRACE) || trace);
2299 
2300 		init_task_pid(p, PIDTYPE_PID, pid);
2301 		if (thread_group_leader(p)) {
2302 			init_task_pid(p, PIDTYPE_TGID, pid);
2303 			init_task_pid(p, PIDTYPE_PGID, task_pgrp(current));
2304 			init_task_pid(p, PIDTYPE_SID, task_session(current));
2305 
2306 			if (is_child_reaper(pid)) {
2307 				ns_of_pid(pid)->child_reaper = p;
2308 				p->signal->flags |= SIGNAL_UNKILLABLE;
2309 			}
2310 			p->signal->shared_pending.signal = delayed.signal;
2311 			p->signal->tty = tty_kref_get(current->signal->tty);
2312 			/*
2313 			 * Inherit has_child_subreaper flag under the same
2314 			 * tasklist_lock with adding child to the process tree
2315 			 * for propagate_has_child_subreaper optimization.
2316 			 */
2317 			p->signal->has_child_subreaper = p->real_parent->signal->has_child_subreaper ||
2318 							 p->real_parent->signal->is_child_subreaper;
2319 			list_add_tail(&p->sibling, &p->real_parent->children);
2320 			list_add_tail_rcu(&p->tasks, &init_task.tasks);
2321 			attach_pid(p, PIDTYPE_TGID);
2322 			attach_pid(p, PIDTYPE_PGID);
2323 			attach_pid(p, PIDTYPE_SID);
2324 			__this_cpu_inc(process_counts);
2325 		} else {
2326 			current->signal->nr_threads++;
2327 			atomic_inc(&current->signal->live);
2328 			refcount_inc(&current->signal->sigcnt);
2329 			task_join_group_stop(p);
2330 			list_add_tail_rcu(&p->thread_group,
2331 					  &p->group_leader->thread_group);
2332 			list_add_tail_rcu(&p->thread_node,
2333 					  &p->signal->thread_head);
2334 		}
2335 		attach_pid(p, PIDTYPE_PID);
2336 		nr_threads++;
2337 	}
2338 	total_forks++;
2339 	hlist_del_init(&delayed.node);
2340 	spin_unlock(&current->sighand->siglock);
2341 	syscall_tracepoint_update(p);
2342 	write_unlock_irq(&tasklist_lock);
2343 
2344 	if (pidfile)
2345 		fd_install(pidfd, pidfile);
2346 
2347 	proc_fork_connector(p);
2348 	sched_post_fork(p, args);
2349 	cgroup_post_fork(p, args);
2350 	perf_event_fork(p);
2351 
2352 	trace_task_newtask(p, clone_flags);
2353 	uprobe_copy_process(p, clone_flags);
2354 
2355 	copy_oom_score_adj(clone_flags, p);
2356 
2357 	return p;
2358 
2359 bad_fork_cancel_cgroup:
2360 	spin_unlock(&current->sighand->siglock);
2361 	write_unlock_irq(&tasklist_lock);
2362 	cgroup_cancel_fork(p, args);
2363 bad_fork_put_pidfd:
2364 	if (clone_flags & CLONE_PIDFD) {
2365 		fput(pidfile);
2366 		put_unused_fd(pidfd);
2367 	}
2368 bad_fork_free_pid:
2369 	if (pid != &init_struct_pid)
2370 		free_pid(pid);
2371 bad_fork_cleanup_thread:
2372 	exit_thread(p);
2373 bad_fork_cleanup_io:
2374 	if (p->io_context)
2375 		exit_io_context(p);
2376 bad_fork_cleanup_namespaces:
2377 	exit_task_namespaces(p);
2378 bad_fork_cleanup_mm:
2379 	if (p->mm) {
2380 		mm_clear_owner(p->mm, p);
2381 		mmput(p->mm);
2382 	}
2383 bad_fork_cleanup_signal:
2384 	if (!(clone_flags & CLONE_THREAD))
2385 		free_signal_struct(p->signal);
2386 bad_fork_cleanup_sighand:
2387 	__cleanup_sighand(p->sighand);
2388 bad_fork_cleanup_fs:
2389 	exit_fs(p); /* blocking */
2390 bad_fork_cleanup_files:
2391 	exit_files(p); /* blocking */
2392 bad_fork_cleanup_semundo:
2393 	exit_sem(p);
2394 bad_fork_cleanup_security:
2395 	security_task_free(p);
2396 bad_fork_cleanup_audit:
2397 	audit_free(p);
2398 bad_fork_cleanup_perf:
2399 	perf_event_free_task(p);
2400 bad_fork_cleanup_policy:
2401 	lockdep_free_task(p);
2402 	free_task_load_ptrs(p);
2403 #ifdef CONFIG_NUMA
2404 	mpol_put(p->mempolicy);
2405 bad_fork_cleanup_threadgroup_lock:
2406 #endif
2407 	delayacct_tsk_free(p);
2408 bad_fork_cleanup_count:
2409 	atomic_dec(&p->cred->user->processes);
2410 	exit_creds(p);
2411 bad_fork_free:
2412 	p->state = TASK_DEAD;
2413 	put_task_stack(p);
2414 	delayed_free_task(p);
2415 fork_out:
2416 	spin_lock_irq(&current->sighand->siglock);
2417 	hlist_del_init(&delayed.node);
2418 	spin_unlock_irq(&current->sighand->siglock);
2419 	return ERR_PTR(retval);
2420 }
2421 
init_idle_pids(struct task_struct * idle)2422 static inline void init_idle_pids(struct task_struct *idle)
2423 {
2424 	enum pid_type type;
2425 
2426 	for (type = PIDTYPE_PID; type < PIDTYPE_MAX; ++type) {
2427 		INIT_HLIST_NODE(&idle->pid_links[type]); /* not really needed */
2428 		init_task_pid(idle, type, &init_struct_pid);
2429 	}
2430 }
2431 
fork_idle(int cpu)2432 struct task_struct * __init fork_idle(int cpu)
2433 {
2434 	struct task_struct *task;
2435 	struct kernel_clone_args args = {
2436 		.flags = CLONE_VM,
2437 	};
2438 
2439 	task = copy_process(&init_struct_pid, 0, cpu_to_node(cpu), &args);
2440 	if (!IS_ERR(task)) {
2441 		init_idle_pids(task);
2442 		init_idle(task, cpu);
2443 	}
2444 
2445 	return task;
2446 }
2447 
copy_init_mm(void)2448 struct mm_struct *copy_init_mm(void)
2449 {
2450 	return dup_mm(NULL, &init_mm);
2451 }
2452 
2453 /*
2454  * This is like kernel_clone(), but shaved down and tailored to just
2455  * creating io_uring workers. It returns a created task, or an error pointer.
2456  * The returned task is inactive, and the caller must fire it up through
2457  * wake_up_new_task(p). All signals are blocked in the created task.
2458  */
create_io_thread(int (* fn)(void *),void * arg,int node)2459 struct task_struct *create_io_thread(int (*fn)(void *), void *arg, int node)
2460 {
2461 	unsigned long flags = CLONE_FS|CLONE_FILES|CLONE_SIGHAND|CLONE_THREAD|
2462 				CLONE_IO;
2463 	struct kernel_clone_args args = {
2464 		.flags		= ((lower_32_bits(flags) | CLONE_VM |
2465 				    CLONE_UNTRACED) & ~CSIGNAL),
2466 		.exit_signal	= (lower_32_bits(flags) & CSIGNAL),
2467 		.stack		= (unsigned long)fn,
2468 		.stack_size	= (unsigned long)arg,
2469 		.io_thread	= 1,
2470 	};
2471 
2472 	return copy_process(NULL, 0, node, &args);
2473 }
2474 
2475 /*
2476  *  Ok, this is the main fork-routine.
2477  *
2478  * It copies the process, and if successful kick-starts
2479  * it and waits for it to finish using the VM if required.
2480  *
2481  * args->exit_signal is expected to be checked for sanity by the caller.
2482  */
kernel_clone(struct kernel_clone_args * args)2483 pid_t kernel_clone(struct kernel_clone_args *args)
2484 {
2485 	u64 clone_flags = args->flags;
2486 	struct completion vfork;
2487 	struct pid *pid;
2488 	struct task_struct *p;
2489 	int trace = 0;
2490 	pid_t nr;
2491 
2492 	/*
2493 	 * For legacy clone() calls, CLONE_PIDFD uses the parent_tid argument
2494 	 * to return the pidfd. Hence, CLONE_PIDFD and CLONE_PARENT_SETTID are
2495 	 * mutually exclusive. With clone3() CLONE_PIDFD has grown a separate
2496 	 * field in struct clone_args and it still doesn't make sense to have
2497 	 * them both point at the same memory location. Performing this check
2498 	 * here has the advantage that we don't need to have a separate helper
2499 	 * to check for legacy clone().
2500 	 */
2501 	if ((args->flags & CLONE_PIDFD) &&
2502 	    (args->flags & CLONE_PARENT_SETTID) &&
2503 	    (args->pidfd == args->parent_tid))
2504 		return -EINVAL;
2505 
2506 	/*
2507 	 * Determine whether and which event to report to ptracer.  When
2508 	 * called from kernel_thread or CLONE_UNTRACED is explicitly
2509 	 * requested, no event is reported; otherwise, report if the event
2510 	 * for the type of forking is enabled.
2511 	 */
2512 	if (!(clone_flags & CLONE_UNTRACED)) {
2513 		if (clone_flags & CLONE_VFORK)
2514 			trace = PTRACE_EVENT_VFORK;
2515 		else if (args->exit_signal != SIGCHLD)
2516 			trace = PTRACE_EVENT_CLONE;
2517 		else
2518 			trace = PTRACE_EVENT_FORK;
2519 
2520 		if (likely(!ptrace_event_enabled(current, trace)))
2521 			trace = 0;
2522 	}
2523 
2524 	p = copy_process(NULL, trace, NUMA_NO_NODE, args);
2525 	add_latent_entropy();
2526 
2527 	if (IS_ERR(p))
2528 		return PTR_ERR(p);
2529 
2530 	/*
2531 	 * Do this prior waking up the new thread - the thread pointer
2532 	 * might get invalid after that point, if the thread exits quickly.
2533 	 */
2534 	trace_sched_process_fork(current, p);
2535 
2536 	pid = get_task_pid(p, PIDTYPE_PID);
2537 	nr = pid_vnr(pid);
2538 
2539 	if (clone_flags & CLONE_PARENT_SETTID)
2540 		put_user(nr, args->parent_tid);
2541 
2542 	if (clone_flags & CLONE_VFORK) {
2543 		p->vfork_done = &vfork;
2544 		init_completion(&vfork);
2545 		get_task_struct(p);
2546 	}
2547 
2548 	wake_up_new_task(p);
2549 
2550 	/* forking complete and child started to run, tell ptracer */
2551 	if (unlikely(trace))
2552 		ptrace_event_pid(trace, pid);
2553 
2554 	if (clone_flags & CLONE_VFORK) {
2555 		if (!wait_for_vfork_done(p, &vfork))
2556 			ptrace_event_pid(PTRACE_EVENT_VFORK_DONE, pid);
2557 	}
2558 
2559 	put_pid(pid);
2560 	return nr;
2561 }
2562 
2563 /*
2564  * Create a kernel thread.
2565  */
kernel_thread(int (* fn)(void *),void * arg,unsigned long flags)2566 pid_t kernel_thread(int (*fn)(void *), void *arg, unsigned long flags)
2567 {
2568 	struct kernel_clone_args args = {
2569 		.flags		= ((lower_32_bits(flags) | CLONE_VM |
2570 				    CLONE_UNTRACED) & ~CSIGNAL),
2571 		.exit_signal	= (lower_32_bits(flags) & CSIGNAL),
2572 		.stack		= (unsigned long)fn,
2573 		.stack_size	= (unsigned long)arg,
2574 	};
2575 
2576 	return kernel_clone(&args);
2577 }
2578 
2579 #ifdef __ARCH_WANT_SYS_FORK
SYSCALL_DEFINE0(fork)2580 SYSCALL_DEFINE0(fork)
2581 {
2582 #ifdef CONFIG_MMU
2583 	struct kernel_clone_args args = {
2584 		.exit_signal = SIGCHLD,
2585 	};
2586 
2587 	return kernel_clone(&args);
2588 #else
2589 	/* can not support in nommu mode */
2590 	return -EINVAL;
2591 #endif
2592 }
2593 #endif
2594 
2595 #ifdef __ARCH_WANT_SYS_VFORK
SYSCALL_DEFINE0(vfork)2596 SYSCALL_DEFINE0(vfork)
2597 {
2598 	struct kernel_clone_args args = {
2599 		.flags		= CLONE_VFORK | CLONE_VM,
2600 		.exit_signal	= SIGCHLD,
2601 	};
2602 
2603 	return kernel_clone(&args);
2604 }
2605 #endif
2606 
2607 #ifdef __ARCH_WANT_SYS_CLONE
2608 #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)2609 SYSCALL_DEFINE5(clone, unsigned long, clone_flags, unsigned long, newsp,
2610 		 int __user *, parent_tidptr,
2611 		 unsigned long, tls,
2612 		 int __user *, child_tidptr)
2613 #elif defined(CONFIG_CLONE_BACKWARDS2)
2614 SYSCALL_DEFINE5(clone, unsigned long, newsp, unsigned long, clone_flags,
2615 		 int __user *, parent_tidptr,
2616 		 int __user *, child_tidptr,
2617 		 unsigned long, tls)
2618 #elif defined(CONFIG_CLONE_BACKWARDS3)
2619 SYSCALL_DEFINE6(clone, unsigned long, clone_flags, unsigned long, newsp,
2620 		int, stack_size,
2621 		int __user *, parent_tidptr,
2622 		int __user *, child_tidptr,
2623 		unsigned long, tls)
2624 #else
2625 SYSCALL_DEFINE5(clone, unsigned long, clone_flags, unsigned long, newsp,
2626 		 int __user *, parent_tidptr,
2627 		 int __user *, child_tidptr,
2628 		 unsigned long, tls)
2629 #endif
2630 {
2631 	struct kernel_clone_args args = {
2632 		.flags		= (lower_32_bits(clone_flags) & ~CSIGNAL),
2633 		.pidfd		= parent_tidptr,
2634 		.child_tid	= child_tidptr,
2635 		.parent_tid	= parent_tidptr,
2636 		.exit_signal	= (lower_32_bits(clone_flags) & CSIGNAL),
2637 		.stack		= newsp,
2638 		.tls		= tls,
2639 	};
2640 
2641 	return kernel_clone(&args);
2642 }
2643 #endif
2644 
2645 #ifdef __ARCH_WANT_SYS_CLONE3
2646 
copy_clone_args_from_user(struct kernel_clone_args * kargs,struct clone_args __user * uargs,size_t usize)2647 noinline static int copy_clone_args_from_user(struct kernel_clone_args *kargs,
2648 					      struct clone_args __user *uargs,
2649 					      size_t usize)
2650 {
2651 	int err;
2652 	struct clone_args args;
2653 	pid_t *kset_tid = kargs->set_tid;
2654 
2655 	BUILD_BUG_ON(offsetofend(struct clone_args, tls) !=
2656 		     CLONE_ARGS_SIZE_VER0);
2657 	BUILD_BUG_ON(offsetofend(struct clone_args, set_tid_size) !=
2658 		     CLONE_ARGS_SIZE_VER1);
2659 	BUILD_BUG_ON(offsetofend(struct clone_args, cgroup) !=
2660 		     CLONE_ARGS_SIZE_VER2);
2661 	BUILD_BUG_ON(sizeof(struct clone_args) != CLONE_ARGS_SIZE_VER2);
2662 
2663 	if (unlikely(usize > PAGE_SIZE))
2664 		return -E2BIG;
2665 	if (unlikely(usize < CLONE_ARGS_SIZE_VER0))
2666 		return -EINVAL;
2667 
2668 	err = copy_struct_from_user(&args, sizeof(args), uargs, usize);
2669 	if (err)
2670 		return err;
2671 
2672 	if (unlikely(args.set_tid_size > MAX_PID_NS_LEVEL))
2673 		return -EINVAL;
2674 
2675 	if (unlikely(!args.set_tid && args.set_tid_size > 0))
2676 		return -EINVAL;
2677 
2678 	if (unlikely(args.set_tid && args.set_tid_size == 0))
2679 		return -EINVAL;
2680 
2681 	/*
2682 	 * Verify that higher 32bits of exit_signal are unset and that
2683 	 * it is a valid signal
2684 	 */
2685 	if (unlikely((args.exit_signal & ~((u64)CSIGNAL)) ||
2686 		     !valid_signal(args.exit_signal)))
2687 		return -EINVAL;
2688 
2689 	if ((args.flags & CLONE_INTO_CGROUP) &&
2690 	    (args.cgroup > INT_MAX || usize < CLONE_ARGS_SIZE_VER2))
2691 		return -EINVAL;
2692 
2693 	*kargs = (struct kernel_clone_args){
2694 		.flags		= args.flags,
2695 		.pidfd		= u64_to_user_ptr(args.pidfd),
2696 		.child_tid	= u64_to_user_ptr(args.child_tid),
2697 		.parent_tid	= u64_to_user_ptr(args.parent_tid),
2698 		.exit_signal	= args.exit_signal,
2699 		.stack		= args.stack,
2700 		.stack_size	= args.stack_size,
2701 		.tls		= args.tls,
2702 		.set_tid_size	= args.set_tid_size,
2703 		.cgroup		= args.cgroup,
2704 	};
2705 
2706 	if (args.set_tid &&
2707 		copy_from_user(kset_tid, u64_to_user_ptr(args.set_tid),
2708 			(kargs->set_tid_size * sizeof(pid_t))))
2709 		return -EFAULT;
2710 
2711 	kargs->set_tid = kset_tid;
2712 
2713 	return 0;
2714 }
2715 
2716 /**
2717  * clone3_stack_valid - check and prepare stack
2718  * @kargs: kernel clone args
2719  *
2720  * Verify that the stack arguments userspace gave us are sane.
2721  * In addition, set the stack direction for userspace since it's easy for us to
2722  * determine.
2723  */
clone3_stack_valid(struct kernel_clone_args * kargs)2724 static inline bool clone3_stack_valid(struct kernel_clone_args *kargs)
2725 {
2726 	if (kargs->stack == 0) {
2727 		if (kargs->stack_size > 0)
2728 			return false;
2729 	} else {
2730 		if (kargs->stack_size == 0)
2731 			return false;
2732 
2733 		if (!access_ok((void __user *)kargs->stack, kargs->stack_size))
2734 			return false;
2735 
2736 #if !defined(CONFIG_STACK_GROWSUP) && !defined(CONFIG_IA64)
2737 		kargs->stack += kargs->stack_size;
2738 #endif
2739 	}
2740 
2741 	return true;
2742 }
2743 
clone3_args_valid(struct kernel_clone_args * kargs)2744 static bool clone3_args_valid(struct kernel_clone_args *kargs)
2745 {
2746 	/* Verify that no unknown flags are passed along. */
2747 	if (kargs->flags &
2748 	    ~(CLONE_LEGACY_FLAGS | CLONE_CLEAR_SIGHAND | CLONE_INTO_CGROUP))
2749 		return false;
2750 
2751 	/*
2752 	 * - make the CLONE_DETACHED bit reuseable for clone3
2753 	 * - make the CSIGNAL bits reuseable for clone3
2754 	 */
2755 	if (kargs->flags & (CLONE_DETACHED | CSIGNAL))
2756 		return false;
2757 
2758 	if ((kargs->flags & (CLONE_SIGHAND | CLONE_CLEAR_SIGHAND)) ==
2759 	    (CLONE_SIGHAND | CLONE_CLEAR_SIGHAND))
2760 		return false;
2761 
2762 	if ((kargs->flags & (CLONE_THREAD | CLONE_PARENT)) &&
2763 	    kargs->exit_signal)
2764 		return false;
2765 
2766 	if (!clone3_stack_valid(kargs))
2767 		return false;
2768 
2769 	return true;
2770 }
2771 
2772 /**
2773  * clone3 - create a new process with specific properties
2774  * @uargs: argument structure
2775  * @size:  size of @uargs
2776  *
2777  * clone3() is the extensible successor to clone()/clone2().
2778  * It takes a struct as argument that is versioned by its size.
2779  *
2780  * Return: On success, a positive PID for the child process.
2781  *         On error, a negative errno number.
2782  */
SYSCALL_DEFINE2(clone3,struct clone_args __user *,uargs,size_t,size)2783 SYSCALL_DEFINE2(clone3, struct clone_args __user *, uargs, size_t, size)
2784 {
2785 	int err;
2786 
2787 	struct kernel_clone_args kargs;
2788 	pid_t set_tid[MAX_PID_NS_LEVEL];
2789 
2790 	kargs.set_tid = set_tid;
2791 
2792 	err = copy_clone_args_from_user(&kargs, uargs, size);
2793 	if (err)
2794 		return err;
2795 
2796 	if (!clone3_args_valid(&kargs))
2797 		return -EINVAL;
2798 
2799 	return kernel_clone(&kargs);
2800 }
2801 #endif
2802 
walk_process_tree(struct task_struct * top,proc_visitor visitor,void * data)2803 void walk_process_tree(struct task_struct *top, proc_visitor visitor, void *data)
2804 {
2805 	struct task_struct *leader, *parent, *child;
2806 	int res;
2807 
2808 	read_lock(&tasklist_lock);
2809 	leader = top = top->group_leader;
2810 down:
2811 	for_each_thread(leader, parent) {
2812 		list_for_each_entry(child, &parent->children, sibling) {
2813 			res = visitor(child, data);
2814 			if (res) {
2815 				if (res < 0)
2816 					goto out;
2817 				leader = child;
2818 				goto down;
2819 			}
2820 up:
2821 			;
2822 		}
2823 	}
2824 
2825 	if (leader != top) {
2826 		child = leader;
2827 		parent = child->real_parent;
2828 		leader = parent->group_leader;
2829 		goto up;
2830 	}
2831 out:
2832 	read_unlock(&tasklist_lock);
2833 }
2834 
2835 #ifndef ARCH_MIN_MMSTRUCT_ALIGN
2836 #define ARCH_MIN_MMSTRUCT_ALIGN 0
2837 #endif
2838 
sighand_ctor(void * data)2839 static void sighand_ctor(void *data)
2840 {
2841 	struct sighand_struct *sighand = data;
2842 
2843 	spin_lock_init(&sighand->siglock);
2844 	init_waitqueue_head(&sighand->signalfd_wqh);
2845 }
2846 
proc_caches_init(void)2847 void __init proc_caches_init(void)
2848 {
2849 	unsigned int mm_size;
2850 
2851 	sighand_cachep = kmem_cache_create("sighand_cache",
2852 			sizeof(struct sighand_struct), 0,
2853 			SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_TYPESAFE_BY_RCU|
2854 			SLAB_ACCOUNT, sighand_ctor);
2855 	signal_cachep = kmem_cache_create("signal_cache",
2856 			sizeof(struct signal_struct), 0,
2857 			SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_ACCOUNT,
2858 			NULL);
2859 	files_cachep = kmem_cache_create("files_cache",
2860 			sizeof(struct files_struct), 0,
2861 			SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_ACCOUNT,
2862 			NULL);
2863 	fs_cachep = kmem_cache_create("fs_cache",
2864 			sizeof(struct fs_struct), 0,
2865 			SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_ACCOUNT,
2866 			NULL);
2867 
2868 	/*
2869 	 * The mm_cpumask is located at the end of mm_struct, and is
2870 	 * dynamically sized based on the maximum CPU number this system
2871 	 * can have, taking hotplug into account (nr_cpu_ids).
2872 	 */
2873 	mm_size = sizeof(struct mm_struct) + cpumask_size();
2874 
2875 	mm_cachep = kmem_cache_create_usercopy("mm_struct",
2876 			mm_size, ARCH_MIN_MMSTRUCT_ALIGN,
2877 			SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_ACCOUNT,
2878 			offsetof(struct mm_struct, saved_auxv),
2879 			sizeof_field(struct mm_struct, saved_auxv),
2880 			NULL);
2881 	vm_area_cachep = KMEM_CACHE(vm_area_struct, SLAB_PANIC|SLAB_ACCOUNT);
2882 	mmap_init();
2883 	nsproxy_cache_init();
2884 }
2885 
2886 /*
2887  * Check constraints on flags passed to the unshare system call.
2888  */
check_unshare_flags(unsigned long unshare_flags)2889 static int check_unshare_flags(unsigned long unshare_flags)
2890 {
2891 	if (unshare_flags & ~(CLONE_THREAD|CLONE_FS|CLONE_NEWNS|CLONE_SIGHAND|
2892 				CLONE_VM|CLONE_FILES|CLONE_SYSVSEM|
2893 				CLONE_NEWUTS|CLONE_NEWIPC|CLONE_NEWNET|
2894 				CLONE_NEWUSER|CLONE_NEWPID|CLONE_NEWCGROUP|
2895 				CLONE_NEWTIME))
2896 		return -EINVAL;
2897 	/*
2898 	 * Not implemented, but pretend it works if there is nothing
2899 	 * to unshare.  Note that unsharing the address space or the
2900 	 * signal handlers also need to unshare the signal queues (aka
2901 	 * CLONE_THREAD).
2902 	 */
2903 	if (unshare_flags & (CLONE_THREAD | CLONE_SIGHAND | CLONE_VM)) {
2904 		if (!thread_group_empty(current))
2905 			return -EINVAL;
2906 	}
2907 	if (unshare_flags & (CLONE_SIGHAND | CLONE_VM)) {
2908 		if (refcount_read(&current->sighand->count) > 1)
2909 			return -EINVAL;
2910 	}
2911 	if (unshare_flags & CLONE_VM) {
2912 		if (!current_is_single_threaded())
2913 			return -EINVAL;
2914 	}
2915 
2916 	return 0;
2917 }
2918 
2919 /*
2920  * Unshare the filesystem structure if it is being shared
2921  */
unshare_fs(unsigned long unshare_flags,struct fs_struct ** new_fsp)2922 static int unshare_fs(unsigned long unshare_flags, struct fs_struct **new_fsp)
2923 {
2924 	struct fs_struct *fs = current->fs;
2925 
2926 	if (!(unshare_flags & CLONE_FS) || !fs)
2927 		return 0;
2928 
2929 	/* don't need lock here; in the worst case we'll do useless copy */
2930 	if (fs->users == 1)
2931 		return 0;
2932 
2933 	*new_fsp = copy_fs_struct(fs);
2934 	if (!*new_fsp)
2935 		return -ENOMEM;
2936 
2937 	return 0;
2938 }
2939 
2940 /*
2941  * Unshare file descriptor table if it is being shared
2942  */
unshare_fd(unsigned long unshare_flags,unsigned int max_fds,struct files_struct ** new_fdp)2943 int unshare_fd(unsigned long unshare_flags, unsigned int max_fds,
2944 	       struct files_struct **new_fdp)
2945 {
2946 	struct files_struct *fd = current->files;
2947 	int error = 0;
2948 
2949 	if ((unshare_flags & CLONE_FILES) &&
2950 	    (fd && atomic_read(&fd->count) > 1)) {
2951 		*new_fdp = dup_fd(fd, max_fds, &error);
2952 		if (!*new_fdp)
2953 			return error;
2954 	}
2955 
2956 	return 0;
2957 }
2958 
2959 /*
2960  * unshare allows a process to 'unshare' part of the process
2961  * context which was originally shared using clone.  copy_*
2962  * functions used by kernel_clone() cannot be used here directly
2963  * because they modify an inactive task_struct that is being
2964  * constructed. Here we are modifying the current, active,
2965  * task_struct.
2966  */
ksys_unshare(unsigned long unshare_flags)2967 int ksys_unshare(unsigned long unshare_flags)
2968 {
2969 	struct fs_struct *fs, *new_fs = NULL;
2970 	struct files_struct *fd, *new_fd = NULL;
2971 	struct cred *new_cred = NULL;
2972 	struct nsproxy *new_nsproxy = NULL;
2973 	int do_sysvsem = 0;
2974 	int err;
2975 
2976 	/*
2977 	 * If unsharing a user namespace must also unshare the thread group
2978 	 * and unshare the filesystem root and working directories.
2979 	 */
2980 	if (unshare_flags & CLONE_NEWUSER)
2981 		unshare_flags |= CLONE_THREAD | CLONE_FS;
2982 	/*
2983 	 * If unsharing vm, must also unshare signal handlers.
2984 	 */
2985 	if (unshare_flags & CLONE_VM)
2986 		unshare_flags |= CLONE_SIGHAND;
2987 	/*
2988 	 * If unsharing a signal handlers, must also unshare the signal queues.
2989 	 */
2990 	if (unshare_flags & CLONE_SIGHAND)
2991 		unshare_flags |= CLONE_THREAD;
2992 	/*
2993 	 * If unsharing namespace, must also unshare filesystem information.
2994 	 */
2995 	if (unshare_flags & CLONE_NEWNS)
2996 		unshare_flags |= CLONE_FS;
2997 
2998 	err = check_unshare_flags(unshare_flags);
2999 	if (err)
3000 		goto bad_unshare_out;
3001 	/*
3002 	 * CLONE_NEWIPC must also detach from the undolist: after switching
3003 	 * to a new ipc namespace, the semaphore arrays from the old
3004 	 * namespace are unreachable.
3005 	 */
3006 	if (unshare_flags & (CLONE_NEWIPC|CLONE_SYSVSEM))
3007 		do_sysvsem = 1;
3008 	err = unshare_fs(unshare_flags, &new_fs);
3009 	if (err)
3010 		goto bad_unshare_out;
3011 	err = unshare_fd(unshare_flags, NR_OPEN_MAX, &new_fd);
3012 	if (err)
3013 		goto bad_unshare_cleanup_fs;
3014 	err = unshare_userns(unshare_flags, &new_cred);
3015 	if (err)
3016 		goto bad_unshare_cleanup_fd;
3017 	err = unshare_nsproxy_namespaces(unshare_flags, &new_nsproxy,
3018 					 new_cred, new_fs);
3019 	if (err)
3020 		goto bad_unshare_cleanup_cred;
3021 
3022 	if (new_fs || new_fd || do_sysvsem || new_cred || new_nsproxy) {
3023 		if (do_sysvsem) {
3024 			/*
3025 			 * CLONE_SYSVSEM is equivalent to sys_exit().
3026 			 */
3027 			exit_sem(current);
3028 		}
3029 		if (unshare_flags & CLONE_NEWIPC) {
3030 			/* Orphan segments in old ns (see sem above). */
3031 			exit_shm(current);
3032 			shm_init_task(current);
3033 		}
3034 
3035 		if (new_nsproxy)
3036 			switch_task_namespaces(current, new_nsproxy);
3037 
3038 		task_lock(current);
3039 
3040 		if (new_fs) {
3041 			fs = current->fs;
3042 			spin_lock(&fs->lock);
3043 			current->fs = new_fs;
3044 			if (--fs->users)
3045 				new_fs = NULL;
3046 			else
3047 				new_fs = fs;
3048 			spin_unlock(&fs->lock);
3049 		}
3050 
3051 		if (new_fd) {
3052 			fd = current->files;
3053 			current->files = new_fd;
3054 			new_fd = fd;
3055 		}
3056 
3057 		task_unlock(current);
3058 
3059 		if (new_cred) {
3060 			/* Install the new user namespace */
3061 			commit_creds(new_cred);
3062 			new_cred = NULL;
3063 		}
3064 	}
3065 
3066 	perf_event_namespaces(current);
3067 
3068 bad_unshare_cleanup_cred:
3069 	if (new_cred)
3070 		put_cred(new_cred);
3071 bad_unshare_cleanup_fd:
3072 	if (new_fd)
3073 		put_files_struct(new_fd);
3074 
3075 bad_unshare_cleanup_fs:
3076 	if (new_fs)
3077 		free_fs_struct(new_fs);
3078 
3079 bad_unshare_out:
3080 	return err;
3081 }
3082 
SYSCALL_DEFINE1(unshare,unsigned long,unshare_flags)3083 SYSCALL_DEFINE1(unshare, unsigned long, unshare_flags)
3084 {
3085 	return ksys_unshare(unshare_flags);
3086 }
3087 
3088 /*
3089  *	Helper to unshare the files of the current task.
3090  *	We don't want to expose copy_files internals to
3091  *	the exec layer of the kernel.
3092  */
3093 
unshare_files(struct files_struct ** displaced)3094 int unshare_files(struct files_struct **displaced)
3095 {
3096 	struct task_struct *task = current;
3097 	struct files_struct *copy = NULL;
3098 	int error;
3099 
3100 	error = unshare_fd(CLONE_FILES, NR_OPEN_MAX, &copy);
3101 	if (error || !copy) {
3102 		*displaced = NULL;
3103 		return error;
3104 	}
3105 	*displaced = task->files;
3106 	task_lock(task);
3107 	task->files = copy;
3108 	task_unlock(task);
3109 	return 0;
3110 }
3111 
sysctl_max_threads(struct ctl_table * table,int write,void * buffer,size_t * lenp,loff_t * ppos)3112 int sysctl_max_threads(struct ctl_table *table, int write,
3113 		       void *buffer, size_t *lenp, loff_t *ppos)
3114 {
3115 	struct ctl_table t;
3116 	int ret;
3117 	int threads = max_threads;
3118 	int min = 1;
3119 	int max = MAX_THREADS;
3120 
3121 	t = *table;
3122 	t.data = &threads;
3123 	t.extra1 = &min;
3124 	t.extra2 = &max;
3125 
3126 	ret = proc_dointvec_minmax(&t, write, buffer, lenp, ppos);
3127 	if (ret || !write)
3128 		return ret;
3129 
3130 	max_threads = threads;
3131 
3132 	return 0;
3133 }
3134