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