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