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