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