xref: /linux/kernel/fork.c (revision 4d6575949d914c5fb8ec2d6ca3a706f9a2b434b7)
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_file: return the new pidfs file
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 verifies that @pid is still in use, without PIDFD_THREAD the
2048  * task identified by @pid must be a thread-group leader.
2049  *
2050  * If this function returns successfully the caller is responsible to either
2051  * call fd_install() passing the returned pidfd and pidfd file as arguments in
2052  * order to install the pidfd into its file descriptor table or they must use
2053  * put_unused_fd() and fput() on the returned pidfd and pidfd file
2054  * respectively.
2055  *
2056  * This function is useful when a pidfd must already be reserved but there
2057  * might still be points of failure afterwards and the caller wants to ensure
2058  * that no pidfd is leaked into its file descriptor table.
2059  *
2060  * Return: On success, a reserved pidfd is returned from the function and a new
2061  *         pidfd file is returned in the last argument to the function. On
2062  *         error, a negative error code is returned from the function and the
2063  *         last argument remains unchanged.
2064  */
2065 int pidfd_prepare(struct pid *pid, unsigned int flags, struct file **ret_file)
2066 {
2067 	struct file *pidfs_file;
2068 
2069 	/*
2070 	 * PIDFD_STALE is only allowed to be passed if the caller knows
2071 	 * that @pid is already registered in pidfs and thus
2072 	 * PIDFD_INFO_EXIT information is guaranteed to be available.
2073 	 */
2074 	if (!(flags & PIDFD_STALE)) {
2075 		/*
2076 		 * While holding the pidfd waitqueue lock removing the
2077 		 * task linkage for the thread-group leader pid
2078 		 * (PIDTYPE_TGID) isn't possible. Thus, if there's still
2079 		 * task linkage for PIDTYPE_PID not having thread-group
2080 		 * leader linkage for the pid means it wasn't a
2081 		 * thread-group leader in the first place.
2082 		 */
2083 		guard(spinlock_irq)(&pid->wait_pidfd.lock);
2084 
2085 		/* Task has already been reaped. */
2086 		if (!pid_has_task(pid, PIDTYPE_PID))
2087 			return -ESRCH;
2088 		/*
2089 		 * If this struct pid isn't used as a thread-group
2090 		 * leader but the caller requested to create a
2091 		 * thread-group leader pidfd then report ENOENT.
2092 		 */
2093 		if (!(flags & PIDFD_THREAD) && !pid_has_task(pid, PIDTYPE_TGID))
2094 			return -ENOENT;
2095 	}
2096 
2097 	CLASS(get_unused_fd, pidfd)(O_CLOEXEC);
2098 	if (pidfd < 0)
2099 		return pidfd;
2100 
2101 	pidfs_file = pidfs_alloc_file(pid, flags | O_RDWR);
2102 	if (IS_ERR(pidfs_file))
2103 		return PTR_ERR(pidfs_file);
2104 
2105 	*ret_file = pidfs_file;
2106 	return take_fd(pidfd);
2107 }
2108 
2109 static void __delayed_free_task(struct rcu_head *rhp)
2110 {
2111 	struct task_struct *tsk = container_of(rhp, struct task_struct, rcu);
2112 
2113 	free_task(tsk);
2114 }
2115 
2116 static __always_inline void delayed_free_task(struct task_struct *tsk)
2117 {
2118 	if (IS_ENABLED(CONFIG_MEMCG))
2119 		call_rcu(&tsk->rcu, __delayed_free_task);
2120 	else
2121 		free_task(tsk);
2122 }
2123 
2124 static void copy_oom_score_adj(u64 clone_flags, struct task_struct *tsk)
2125 {
2126 	/* Skip if kernel thread */
2127 	if (!tsk->mm)
2128 		return;
2129 
2130 	/* Skip if spawning a thread or using vfork */
2131 	if ((clone_flags & (CLONE_VM | CLONE_THREAD | CLONE_VFORK)) != CLONE_VM)
2132 		return;
2133 
2134 	/* We need to synchronize with __set_oom_adj */
2135 	mutex_lock(&oom_adj_mutex);
2136 	set_bit(MMF_MULTIPROCESS, &tsk->mm->flags);
2137 	/* Update the values in case they were changed after copy_signal */
2138 	tsk->signal->oom_score_adj = current->signal->oom_score_adj;
2139 	tsk->signal->oom_score_adj_min = current->signal->oom_score_adj_min;
2140 	mutex_unlock(&oom_adj_mutex);
2141 }
2142 
2143 #ifdef CONFIG_RV
2144 static void rv_task_fork(struct task_struct *p)
2145 {
2146 	int i;
2147 
2148 	for (i = 0; i < RV_PER_TASK_MONITORS; i++)
2149 		p->rv[i].da_mon.monitoring = false;
2150 }
2151 #else
2152 #define rv_task_fork(p) do {} while (0)
2153 #endif
2154 
2155 /*
2156  * This creates a new process as a copy of the old one,
2157  * but does not actually start it yet.
2158  *
2159  * It copies the registers, and all the appropriate
2160  * parts of the process environment (as per the clone
2161  * flags). The actual kick-off is left to the caller.
2162  */
2163 __latent_entropy struct task_struct *copy_process(
2164 					struct pid *pid,
2165 					int trace,
2166 					int node,
2167 					struct kernel_clone_args *args)
2168 {
2169 	int pidfd = -1, retval;
2170 	struct task_struct *p;
2171 	struct multiprocess_signals delayed;
2172 	struct file *pidfile = NULL;
2173 	const u64 clone_flags = args->flags;
2174 	struct nsproxy *nsp = current->nsproxy;
2175 
2176 	/*
2177 	 * Don't allow sharing the root directory with processes in a different
2178 	 * namespace
2179 	 */
2180 	if ((clone_flags & (CLONE_NEWNS|CLONE_FS)) == (CLONE_NEWNS|CLONE_FS))
2181 		return ERR_PTR(-EINVAL);
2182 
2183 	if ((clone_flags & (CLONE_NEWUSER|CLONE_FS)) == (CLONE_NEWUSER|CLONE_FS))
2184 		return ERR_PTR(-EINVAL);
2185 
2186 	/*
2187 	 * Thread groups must share signals as well, and detached threads
2188 	 * can only be started up within the thread group.
2189 	 */
2190 	if ((clone_flags & CLONE_THREAD) && !(clone_flags & CLONE_SIGHAND))
2191 		return ERR_PTR(-EINVAL);
2192 
2193 	/*
2194 	 * Shared signal handlers imply shared VM. By way of the above,
2195 	 * thread groups also imply shared VM. Blocking this case allows
2196 	 * for various simplifications in other code.
2197 	 */
2198 	if ((clone_flags & CLONE_SIGHAND) && !(clone_flags & CLONE_VM))
2199 		return ERR_PTR(-EINVAL);
2200 
2201 	/*
2202 	 * Siblings of global init remain as zombies on exit since they are
2203 	 * not reaped by their parent (swapper). To solve this and to avoid
2204 	 * multi-rooted process trees, prevent global and container-inits
2205 	 * from creating siblings.
2206 	 */
2207 	if ((clone_flags & CLONE_PARENT) &&
2208 				current->signal->flags & SIGNAL_UNKILLABLE)
2209 		return ERR_PTR(-EINVAL);
2210 
2211 	/*
2212 	 * If the new process will be in a different pid or user namespace
2213 	 * do not allow it to share a thread group with the forking task.
2214 	 */
2215 	if (clone_flags & CLONE_THREAD) {
2216 		if ((clone_flags & (CLONE_NEWUSER | CLONE_NEWPID)) ||
2217 		    (task_active_pid_ns(current) != nsp->pid_ns_for_children))
2218 			return ERR_PTR(-EINVAL);
2219 	}
2220 
2221 	if (clone_flags & CLONE_PIDFD) {
2222 		/*
2223 		 * - CLONE_DETACHED is blocked so that we can potentially
2224 		 *   reuse it later for CLONE_PIDFD.
2225 		 */
2226 		if (clone_flags & CLONE_DETACHED)
2227 			return ERR_PTR(-EINVAL);
2228 	}
2229 
2230 	/*
2231 	 * Force any signals received before this point to be delivered
2232 	 * before the fork happens.  Collect up signals sent to multiple
2233 	 * processes that happen during the fork and delay them so that
2234 	 * they appear to happen after the fork.
2235 	 */
2236 	sigemptyset(&delayed.signal);
2237 	INIT_HLIST_NODE(&delayed.node);
2238 
2239 	spin_lock_irq(&current->sighand->siglock);
2240 	if (!(clone_flags & CLONE_THREAD))
2241 		hlist_add_head(&delayed.node, &current->signal->multiprocess);
2242 	recalc_sigpending();
2243 	spin_unlock_irq(&current->sighand->siglock);
2244 	retval = -ERESTARTNOINTR;
2245 	if (task_sigpending(current))
2246 		goto fork_out;
2247 
2248 	retval = -ENOMEM;
2249 	p = dup_task_struct(current, node);
2250 	if (!p)
2251 		goto fork_out;
2252 	p->flags &= ~PF_KTHREAD;
2253 	if (args->kthread)
2254 		p->flags |= PF_KTHREAD;
2255 	if (args->user_worker) {
2256 		/*
2257 		 * Mark us a user worker, and block any signal that isn't
2258 		 * fatal or STOP
2259 		 */
2260 		p->flags |= PF_USER_WORKER;
2261 		siginitsetinv(&p->blocked, sigmask(SIGKILL)|sigmask(SIGSTOP));
2262 	}
2263 	if (args->io_thread)
2264 		p->flags |= PF_IO_WORKER;
2265 
2266 	if (args->name)
2267 		strscpy_pad(p->comm, args->name, sizeof(p->comm));
2268 
2269 	p->set_child_tid = (clone_flags & CLONE_CHILD_SETTID) ? args->child_tid : NULL;
2270 	/*
2271 	 * Clear TID on mm_release()?
2272 	 */
2273 	p->clear_child_tid = (clone_flags & CLONE_CHILD_CLEARTID) ? args->child_tid : NULL;
2274 
2275 	ftrace_graph_init_task(p);
2276 
2277 	rt_mutex_init_task(p);
2278 
2279 	lockdep_assert_irqs_enabled();
2280 #ifdef CONFIG_PROVE_LOCKING
2281 	DEBUG_LOCKS_WARN_ON(!p->softirqs_enabled);
2282 #endif
2283 	retval = copy_creds(p, clone_flags);
2284 	if (retval < 0)
2285 		goto bad_fork_free;
2286 
2287 	retval = -EAGAIN;
2288 	if (is_rlimit_overlimit(task_ucounts(p), UCOUNT_RLIMIT_NPROC, rlimit(RLIMIT_NPROC))) {
2289 		if (p->real_cred->user != INIT_USER &&
2290 		    !capable(CAP_SYS_RESOURCE) && !capable(CAP_SYS_ADMIN))
2291 			goto bad_fork_cleanup_count;
2292 	}
2293 	current->flags &= ~PF_NPROC_EXCEEDED;
2294 
2295 	/*
2296 	 * If multiple threads are within copy_process(), then this check
2297 	 * triggers too late. This doesn't hurt, the check is only there
2298 	 * to stop root fork bombs.
2299 	 */
2300 	retval = -EAGAIN;
2301 	if (data_race(nr_threads >= max_threads))
2302 		goto bad_fork_cleanup_count;
2303 
2304 	delayacct_tsk_init(p);	/* Must remain after dup_task_struct() */
2305 	p->flags &= ~(PF_SUPERPRIV | PF_WQ_WORKER | PF_IDLE | PF_NO_SETAFFINITY);
2306 	p->flags |= PF_FORKNOEXEC;
2307 	INIT_LIST_HEAD(&p->children);
2308 	INIT_LIST_HEAD(&p->sibling);
2309 	rcu_copy_process(p);
2310 	p->vfork_done = NULL;
2311 	spin_lock_init(&p->alloc_lock);
2312 
2313 	init_sigpending(&p->pending);
2314 
2315 	p->utime = p->stime = p->gtime = 0;
2316 #ifdef CONFIG_ARCH_HAS_SCALED_CPUTIME
2317 	p->utimescaled = p->stimescaled = 0;
2318 #endif
2319 	prev_cputime_init(&p->prev_cputime);
2320 
2321 #ifdef CONFIG_VIRT_CPU_ACCOUNTING_GEN
2322 	seqcount_init(&p->vtime.seqcount);
2323 	p->vtime.starttime = 0;
2324 	p->vtime.state = VTIME_INACTIVE;
2325 #endif
2326 
2327 #ifdef CONFIG_IO_URING
2328 	p->io_uring = NULL;
2329 #endif
2330 
2331 	p->default_timer_slack_ns = current->timer_slack_ns;
2332 
2333 #ifdef CONFIG_PSI
2334 	p->psi_flags = 0;
2335 #endif
2336 
2337 	task_io_accounting_init(&p->ioac);
2338 	acct_clear_integrals(p);
2339 
2340 	posix_cputimers_init(&p->posix_cputimers);
2341 	tick_dep_init_task(p);
2342 
2343 	p->io_context = NULL;
2344 	audit_set_context(p, NULL);
2345 	cgroup_fork(p);
2346 	if (args->kthread) {
2347 		if (!set_kthread_struct(p))
2348 			goto bad_fork_cleanup_delayacct;
2349 	}
2350 #ifdef CONFIG_NUMA
2351 	p->mempolicy = mpol_dup(p->mempolicy);
2352 	if (IS_ERR(p->mempolicy)) {
2353 		retval = PTR_ERR(p->mempolicy);
2354 		p->mempolicy = NULL;
2355 		goto bad_fork_cleanup_delayacct;
2356 	}
2357 #endif
2358 #ifdef CONFIG_CPUSETS
2359 	p->cpuset_mem_spread_rotor = NUMA_NO_NODE;
2360 	seqcount_spinlock_init(&p->mems_allowed_seq, &p->alloc_lock);
2361 #endif
2362 #ifdef CONFIG_TRACE_IRQFLAGS
2363 	memset(&p->irqtrace, 0, sizeof(p->irqtrace));
2364 	p->irqtrace.hardirq_disable_ip	= _THIS_IP_;
2365 	p->irqtrace.softirq_enable_ip	= _THIS_IP_;
2366 	p->softirqs_enabled		= 1;
2367 	p->softirq_context		= 0;
2368 #endif
2369 
2370 	p->pagefault_disabled = 0;
2371 
2372 #ifdef CONFIG_LOCKDEP
2373 	lockdep_init_task(p);
2374 #endif
2375 
2376 #ifdef CONFIG_DEBUG_MUTEXES
2377 	p->blocked_on = NULL; /* not blocked yet */
2378 #endif
2379 #ifdef CONFIG_BCACHE
2380 	p->sequential_io	= 0;
2381 	p->sequential_io_avg	= 0;
2382 #endif
2383 #ifdef CONFIG_BPF_SYSCALL
2384 	RCU_INIT_POINTER(p->bpf_storage, NULL);
2385 	p->bpf_ctx = NULL;
2386 #endif
2387 
2388 	/* Perform scheduler related setup. Assign this task to a CPU. */
2389 	retval = sched_fork(clone_flags, p);
2390 	if (retval)
2391 		goto bad_fork_cleanup_policy;
2392 
2393 	retval = perf_event_init_task(p, clone_flags);
2394 	if (retval)
2395 		goto bad_fork_sched_cancel_fork;
2396 	retval = audit_alloc(p);
2397 	if (retval)
2398 		goto bad_fork_cleanup_perf;
2399 	/* copy all the process information */
2400 	shm_init_task(p);
2401 	retval = security_task_alloc(p, clone_flags);
2402 	if (retval)
2403 		goto bad_fork_cleanup_audit;
2404 	retval = copy_semundo(clone_flags, p);
2405 	if (retval)
2406 		goto bad_fork_cleanup_security;
2407 	retval = copy_files(clone_flags, p, args->no_files);
2408 	if (retval)
2409 		goto bad_fork_cleanup_semundo;
2410 	retval = copy_fs(clone_flags, p);
2411 	if (retval)
2412 		goto bad_fork_cleanup_files;
2413 	retval = copy_sighand(clone_flags, p);
2414 	if (retval)
2415 		goto bad_fork_cleanup_fs;
2416 	retval = copy_signal(clone_flags, p);
2417 	if (retval)
2418 		goto bad_fork_cleanup_sighand;
2419 	retval = copy_mm(clone_flags, p);
2420 	if (retval)
2421 		goto bad_fork_cleanup_signal;
2422 	retval = copy_namespaces(clone_flags, p);
2423 	if (retval)
2424 		goto bad_fork_cleanup_mm;
2425 	retval = copy_io(clone_flags, p);
2426 	if (retval)
2427 		goto bad_fork_cleanup_namespaces;
2428 	retval = copy_thread(p, args);
2429 	if (retval)
2430 		goto bad_fork_cleanup_io;
2431 
2432 	stackleak_task_init(p);
2433 
2434 	if (pid != &init_struct_pid) {
2435 		pid = alloc_pid(p->nsproxy->pid_ns_for_children, args->set_tid,
2436 				args->set_tid_size);
2437 		if (IS_ERR(pid)) {
2438 			retval = PTR_ERR(pid);
2439 			goto bad_fork_cleanup_thread;
2440 		}
2441 	}
2442 
2443 	/*
2444 	 * This has to happen after we've potentially unshared the file
2445 	 * descriptor table (so that the pidfd doesn't leak into the child
2446 	 * if the fd table isn't shared).
2447 	 */
2448 	if (clone_flags & CLONE_PIDFD) {
2449 		int flags = (clone_flags & CLONE_THREAD) ? PIDFD_THREAD : 0;
2450 
2451 		/*
2452 		 * Note that no task has been attached to @pid yet indicate
2453 		 * that via CLONE_PIDFD.
2454 		 */
2455 		retval = pidfd_prepare(pid, flags | PIDFD_STALE, &pidfile);
2456 		if (retval < 0)
2457 			goto bad_fork_free_pid;
2458 		pidfd = retval;
2459 
2460 		retval = put_user(pidfd, args->pidfd);
2461 		if (retval)
2462 			goto bad_fork_put_pidfd;
2463 	}
2464 
2465 #ifdef CONFIG_BLOCK
2466 	p->plug = NULL;
2467 #endif
2468 	futex_init_task(p);
2469 
2470 	/*
2471 	 * sigaltstack should be cleared when sharing the same VM
2472 	 */
2473 	if ((clone_flags & (CLONE_VM|CLONE_VFORK)) == CLONE_VM)
2474 		sas_ss_reset(p);
2475 
2476 	/*
2477 	 * Syscall tracing and stepping should be turned off in the
2478 	 * child regardless of CLONE_PTRACE.
2479 	 */
2480 	user_disable_single_step(p);
2481 	clear_task_syscall_work(p, SYSCALL_TRACE);
2482 #if defined(CONFIG_GENERIC_ENTRY) || defined(TIF_SYSCALL_EMU)
2483 	clear_task_syscall_work(p, SYSCALL_EMU);
2484 #endif
2485 	clear_tsk_latency_tracing(p);
2486 
2487 	/* ok, now we should be set up.. */
2488 	p->pid = pid_nr(pid);
2489 	if (clone_flags & CLONE_THREAD) {
2490 		p->group_leader = current->group_leader;
2491 		p->tgid = current->tgid;
2492 	} else {
2493 		p->group_leader = p;
2494 		p->tgid = p->pid;
2495 	}
2496 
2497 	p->nr_dirtied = 0;
2498 	p->nr_dirtied_pause = 128 >> (PAGE_SHIFT - 10);
2499 	p->dirty_paused_when = 0;
2500 
2501 	p->pdeath_signal = 0;
2502 	p->task_works = NULL;
2503 	clear_posix_cputimers_work(p);
2504 
2505 #ifdef CONFIG_KRETPROBES
2506 	p->kretprobe_instances.first = NULL;
2507 #endif
2508 #ifdef CONFIG_RETHOOK
2509 	p->rethooks.first = NULL;
2510 #endif
2511 
2512 	/*
2513 	 * Ensure that the cgroup subsystem policies allow the new process to be
2514 	 * forked. It should be noted that the new process's css_set can be changed
2515 	 * between here and cgroup_post_fork() if an organisation operation is in
2516 	 * progress.
2517 	 */
2518 	retval = cgroup_can_fork(p, args);
2519 	if (retval)
2520 		goto bad_fork_put_pidfd;
2521 
2522 	/*
2523 	 * Now that the cgroups are pinned, re-clone the parent cgroup and put
2524 	 * the new task on the correct runqueue. All this *before* the task
2525 	 * becomes visible.
2526 	 *
2527 	 * This isn't part of ->can_fork() because while the re-cloning is
2528 	 * cgroup specific, it unconditionally needs to place the task on a
2529 	 * runqueue.
2530 	 */
2531 	retval = sched_cgroup_fork(p, args);
2532 	if (retval)
2533 		goto bad_fork_cancel_cgroup;
2534 
2535 	/*
2536 	 * From this point on we must avoid any synchronous user-space
2537 	 * communication until we take the tasklist-lock. In particular, we do
2538 	 * not want user-space to be able to predict the process start-time by
2539 	 * stalling fork(2) after we recorded the start_time but before it is
2540 	 * visible to the system.
2541 	 */
2542 
2543 	p->start_time = ktime_get_ns();
2544 	p->start_boottime = ktime_get_boottime_ns();
2545 
2546 	/*
2547 	 * Make it visible to the rest of the system, but dont wake it up yet.
2548 	 * Need tasklist lock for parent etc handling!
2549 	 */
2550 	write_lock_irq(&tasklist_lock);
2551 
2552 	/* CLONE_PARENT re-uses the old parent */
2553 	if (clone_flags & (CLONE_PARENT|CLONE_THREAD)) {
2554 		p->real_parent = current->real_parent;
2555 		p->parent_exec_id = current->parent_exec_id;
2556 		if (clone_flags & CLONE_THREAD)
2557 			p->exit_signal = -1;
2558 		else
2559 			p->exit_signal = current->group_leader->exit_signal;
2560 	} else {
2561 		p->real_parent = current;
2562 		p->parent_exec_id = current->self_exec_id;
2563 		p->exit_signal = args->exit_signal;
2564 	}
2565 
2566 	klp_copy_process(p);
2567 
2568 	sched_core_fork(p);
2569 
2570 	spin_lock(&current->sighand->siglock);
2571 
2572 	rv_task_fork(p);
2573 
2574 	rseq_fork(p, clone_flags);
2575 
2576 	/* Don't start children in a dying pid namespace */
2577 	if (unlikely(!(ns_of_pid(pid)->pid_allocated & PIDNS_ADDING))) {
2578 		retval = -ENOMEM;
2579 		goto bad_fork_core_free;
2580 	}
2581 
2582 	/* Let kill terminate clone/fork in the middle */
2583 	if (fatal_signal_pending(current)) {
2584 		retval = -EINTR;
2585 		goto bad_fork_core_free;
2586 	}
2587 
2588 	/* No more failure paths after this point. */
2589 
2590 	/*
2591 	 * Copy seccomp details explicitly here, in case they were changed
2592 	 * before holding sighand lock.
2593 	 */
2594 	copy_seccomp(p);
2595 
2596 	init_task_pid_links(p);
2597 	if (likely(p->pid)) {
2598 		ptrace_init_task(p, (clone_flags & CLONE_PTRACE) || trace);
2599 
2600 		init_task_pid(p, PIDTYPE_PID, pid);
2601 		if (thread_group_leader(p)) {
2602 			init_task_pid(p, PIDTYPE_TGID, pid);
2603 			init_task_pid(p, PIDTYPE_PGID, task_pgrp(current));
2604 			init_task_pid(p, PIDTYPE_SID, task_session(current));
2605 
2606 			if (is_child_reaper(pid)) {
2607 				ns_of_pid(pid)->child_reaper = p;
2608 				p->signal->flags |= SIGNAL_UNKILLABLE;
2609 			}
2610 			p->signal->shared_pending.signal = delayed.signal;
2611 			p->signal->tty = tty_kref_get(current->signal->tty);
2612 			/*
2613 			 * Inherit has_child_subreaper flag under the same
2614 			 * tasklist_lock with adding child to the process tree
2615 			 * for propagate_has_child_subreaper optimization.
2616 			 */
2617 			p->signal->has_child_subreaper = p->real_parent->signal->has_child_subreaper ||
2618 							 p->real_parent->signal->is_child_subreaper;
2619 			list_add_tail(&p->sibling, &p->real_parent->children);
2620 			list_add_tail_rcu(&p->tasks, &init_task.tasks);
2621 			attach_pid(p, PIDTYPE_TGID);
2622 			attach_pid(p, PIDTYPE_PGID);
2623 			attach_pid(p, PIDTYPE_SID);
2624 			__this_cpu_inc(process_counts);
2625 		} else {
2626 			current->signal->nr_threads++;
2627 			current->signal->quick_threads++;
2628 			atomic_inc(&current->signal->live);
2629 			refcount_inc(&current->signal->sigcnt);
2630 			task_join_group_stop(p);
2631 			list_add_tail_rcu(&p->thread_node,
2632 					  &p->signal->thread_head);
2633 		}
2634 		attach_pid(p, PIDTYPE_PID);
2635 		nr_threads++;
2636 	}
2637 	total_forks++;
2638 	hlist_del_init(&delayed.node);
2639 	spin_unlock(&current->sighand->siglock);
2640 	syscall_tracepoint_update(p);
2641 	write_unlock_irq(&tasklist_lock);
2642 
2643 	if (pidfile)
2644 		fd_install(pidfd, pidfile);
2645 
2646 	proc_fork_connector(p);
2647 	sched_post_fork(p);
2648 	cgroup_post_fork(p, args);
2649 	perf_event_fork(p);
2650 
2651 	trace_task_newtask(p, clone_flags);
2652 	uprobe_copy_process(p, clone_flags);
2653 	user_events_fork(p, clone_flags);
2654 
2655 	copy_oom_score_adj(clone_flags, p);
2656 
2657 	return p;
2658 
2659 bad_fork_core_free:
2660 	sched_core_free(p);
2661 	spin_unlock(&current->sighand->siglock);
2662 	write_unlock_irq(&tasklist_lock);
2663 bad_fork_cancel_cgroup:
2664 	cgroup_cancel_fork(p, args);
2665 bad_fork_put_pidfd:
2666 	if (clone_flags & CLONE_PIDFD) {
2667 		fput(pidfile);
2668 		put_unused_fd(pidfd);
2669 	}
2670 bad_fork_free_pid:
2671 	if (pid != &init_struct_pid)
2672 		free_pid(pid);
2673 bad_fork_cleanup_thread:
2674 	exit_thread(p);
2675 bad_fork_cleanup_io:
2676 	if (p->io_context)
2677 		exit_io_context(p);
2678 bad_fork_cleanup_namespaces:
2679 	exit_task_namespaces(p);
2680 bad_fork_cleanup_mm:
2681 	if (p->mm) {
2682 		mm_clear_owner(p->mm, p);
2683 		mmput(p->mm);
2684 	}
2685 bad_fork_cleanup_signal:
2686 	if (!(clone_flags & CLONE_THREAD))
2687 		free_signal_struct(p->signal);
2688 bad_fork_cleanup_sighand:
2689 	__cleanup_sighand(p->sighand);
2690 bad_fork_cleanup_fs:
2691 	exit_fs(p); /* blocking */
2692 bad_fork_cleanup_files:
2693 	exit_files(p); /* blocking */
2694 bad_fork_cleanup_semundo:
2695 	exit_sem(p);
2696 bad_fork_cleanup_security:
2697 	security_task_free(p);
2698 bad_fork_cleanup_audit:
2699 	audit_free(p);
2700 bad_fork_cleanup_perf:
2701 	perf_event_free_task(p);
2702 bad_fork_sched_cancel_fork:
2703 	sched_cancel_fork(p);
2704 bad_fork_cleanup_policy:
2705 	lockdep_free_task(p);
2706 #ifdef CONFIG_NUMA
2707 	mpol_put(p->mempolicy);
2708 #endif
2709 bad_fork_cleanup_delayacct:
2710 	delayacct_tsk_free(p);
2711 bad_fork_cleanup_count:
2712 	dec_rlimit_ucounts(task_ucounts(p), UCOUNT_RLIMIT_NPROC, 1);
2713 	exit_creds(p);
2714 bad_fork_free:
2715 	WRITE_ONCE(p->__state, TASK_DEAD);
2716 	exit_task_stack_account(p);
2717 	put_task_stack(p);
2718 	delayed_free_task(p);
2719 fork_out:
2720 	spin_lock_irq(&current->sighand->siglock);
2721 	hlist_del_init(&delayed.node);
2722 	spin_unlock_irq(&current->sighand->siglock);
2723 	return ERR_PTR(retval);
2724 }
2725 
2726 static inline void init_idle_pids(struct task_struct *idle)
2727 {
2728 	enum pid_type type;
2729 
2730 	for (type = PIDTYPE_PID; type < PIDTYPE_MAX; ++type) {
2731 		INIT_HLIST_NODE(&idle->pid_links[type]); /* not really needed */
2732 		init_task_pid(idle, type, &init_struct_pid);
2733 	}
2734 }
2735 
2736 static int idle_dummy(void *dummy)
2737 {
2738 	/* This function is never called */
2739 	return 0;
2740 }
2741 
2742 struct task_struct * __init fork_idle(int cpu)
2743 {
2744 	struct task_struct *task;
2745 	struct kernel_clone_args args = {
2746 		.flags		= CLONE_VM,
2747 		.fn		= &idle_dummy,
2748 		.fn_arg		= NULL,
2749 		.kthread	= 1,
2750 		.idle		= 1,
2751 	};
2752 
2753 	task = copy_process(&init_struct_pid, 0, cpu_to_node(cpu), &args);
2754 	if (!IS_ERR(task)) {
2755 		init_idle_pids(task);
2756 		init_idle(task, cpu);
2757 	}
2758 
2759 	return task;
2760 }
2761 
2762 /*
2763  * This is like kernel_clone(), but shaved down and tailored to just
2764  * creating io_uring workers. It returns a created task, or an error pointer.
2765  * The returned task is inactive, and the caller must fire it up through
2766  * wake_up_new_task(p). All signals are blocked in the created task.
2767  */
2768 struct task_struct *create_io_thread(int (*fn)(void *), void *arg, int node)
2769 {
2770 	unsigned long flags = CLONE_FS|CLONE_FILES|CLONE_SIGHAND|CLONE_THREAD|
2771 				CLONE_IO;
2772 	struct kernel_clone_args args = {
2773 		.flags		= ((lower_32_bits(flags) | CLONE_VM |
2774 				    CLONE_UNTRACED) & ~CSIGNAL),
2775 		.exit_signal	= (lower_32_bits(flags) & CSIGNAL),
2776 		.fn		= fn,
2777 		.fn_arg		= arg,
2778 		.io_thread	= 1,
2779 		.user_worker	= 1,
2780 	};
2781 
2782 	return copy_process(NULL, 0, node, &args);
2783 }
2784 
2785 /*
2786  *  Ok, this is the main fork-routine.
2787  *
2788  * It copies the process, and if successful kick-starts
2789  * it and waits for it to finish using the VM if required.
2790  *
2791  * args->exit_signal is expected to be checked for sanity by the caller.
2792  */
2793 pid_t kernel_clone(struct kernel_clone_args *args)
2794 {
2795 	u64 clone_flags = args->flags;
2796 	struct completion vfork;
2797 	struct pid *pid;
2798 	struct task_struct *p;
2799 	int trace = 0;
2800 	pid_t nr;
2801 
2802 	/*
2803 	 * For legacy clone() calls, CLONE_PIDFD uses the parent_tid argument
2804 	 * to return the pidfd. Hence, CLONE_PIDFD and CLONE_PARENT_SETTID are
2805 	 * mutually exclusive. With clone3() CLONE_PIDFD has grown a separate
2806 	 * field in struct clone_args and it still doesn't make sense to have
2807 	 * them both point at the same memory location. Performing this check
2808 	 * here has the advantage that we don't need to have a separate helper
2809 	 * to check for legacy clone().
2810 	 */
2811 	if ((clone_flags & CLONE_PIDFD) &&
2812 	    (clone_flags & CLONE_PARENT_SETTID) &&
2813 	    (args->pidfd == args->parent_tid))
2814 		return -EINVAL;
2815 
2816 	/*
2817 	 * Determine whether and which event to report to ptracer.  When
2818 	 * called from kernel_thread or CLONE_UNTRACED is explicitly
2819 	 * requested, no event is reported; otherwise, report if the event
2820 	 * for the type of forking is enabled.
2821 	 */
2822 	if (!(clone_flags & CLONE_UNTRACED)) {
2823 		if (clone_flags & CLONE_VFORK)
2824 			trace = PTRACE_EVENT_VFORK;
2825 		else if (args->exit_signal != SIGCHLD)
2826 			trace = PTRACE_EVENT_CLONE;
2827 		else
2828 			trace = PTRACE_EVENT_FORK;
2829 
2830 		if (likely(!ptrace_event_enabled(current, trace)))
2831 			trace = 0;
2832 	}
2833 
2834 	p = copy_process(NULL, trace, NUMA_NO_NODE, args);
2835 	add_latent_entropy();
2836 
2837 	if (IS_ERR(p))
2838 		return PTR_ERR(p);
2839 
2840 	/*
2841 	 * Do this prior waking up the new thread - the thread pointer
2842 	 * might get invalid after that point, if the thread exits quickly.
2843 	 */
2844 	trace_sched_process_fork(current, p);
2845 
2846 	pid = get_task_pid(p, PIDTYPE_PID);
2847 	nr = pid_vnr(pid);
2848 
2849 	if (clone_flags & CLONE_PARENT_SETTID)
2850 		put_user(nr, args->parent_tid);
2851 
2852 	if (clone_flags & CLONE_VFORK) {
2853 		p->vfork_done = &vfork;
2854 		init_completion(&vfork);
2855 		get_task_struct(p);
2856 	}
2857 
2858 	if (IS_ENABLED(CONFIG_LRU_GEN_WALKS_MMU) && !(clone_flags & CLONE_VM)) {
2859 		/* lock the task to synchronize with memcg migration */
2860 		task_lock(p);
2861 		lru_gen_add_mm(p->mm);
2862 		task_unlock(p);
2863 	}
2864 
2865 	wake_up_new_task(p);
2866 
2867 	/* forking complete and child started to run, tell ptracer */
2868 	if (unlikely(trace))
2869 		ptrace_event_pid(trace, pid);
2870 
2871 	if (clone_flags & CLONE_VFORK) {
2872 		if (!wait_for_vfork_done(p, &vfork))
2873 			ptrace_event_pid(PTRACE_EVENT_VFORK_DONE, pid);
2874 	}
2875 
2876 	put_pid(pid);
2877 	return nr;
2878 }
2879 
2880 /*
2881  * Create a kernel thread.
2882  */
2883 pid_t kernel_thread(int (*fn)(void *), void *arg, const char *name,
2884 		    unsigned long flags)
2885 {
2886 	struct kernel_clone_args args = {
2887 		.flags		= ((lower_32_bits(flags) | CLONE_VM |
2888 				    CLONE_UNTRACED) & ~CSIGNAL),
2889 		.exit_signal	= (lower_32_bits(flags) & CSIGNAL),
2890 		.fn		= fn,
2891 		.fn_arg		= arg,
2892 		.name		= name,
2893 		.kthread	= 1,
2894 	};
2895 
2896 	return kernel_clone(&args);
2897 }
2898 
2899 /*
2900  * Create a user mode thread.
2901  */
2902 pid_t user_mode_thread(int (*fn)(void *), void *arg, unsigned long flags)
2903 {
2904 	struct kernel_clone_args args = {
2905 		.flags		= ((lower_32_bits(flags) | CLONE_VM |
2906 				    CLONE_UNTRACED) & ~CSIGNAL),
2907 		.exit_signal	= (lower_32_bits(flags) & CSIGNAL),
2908 		.fn		= fn,
2909 		.fn_arg		= arg,
2910 	};
2911 
2912 	return kernel_clone(&args);
2913 }
2914 
2915 #ifdef __ARCH_WANT_SYS_FORK
2916 SYSCALL_DEFINE0(fork)
2917 {
2918 #ifdef CONFIG_MMU
2919 	struct kernel_clone_args args = {
2920 		.exit_signal = SIGCHLD,
2921 	};
2922 
2923 	return kernel_clone(&args);
2924 #else
2925 	/* can not support in nommu mode */
2926 	return -EINVAL;
2927 #endif
2928 }
2929 #endif
2930 
2931 #ifdef __ARCH_WANT_SYS_VFORK
2932 SYSCALL_DEFINE0(vfork)
2933 {
2934 	struct kernel_clone_args args = {
2935 		.flags		= CLONE_VFORK | CLONE_VM,
2936 		.exit_signal	= SIGCHLD,
2937 	};
2938 
2939 	return kernel_clone(&args);
2940 }
2941 #endif
2942 
2943 #ifdef __ARCH_WANT_SYS_CLONE
2944 #ifdef CONFIG_CLONE_BACKWARDS
2945 SYSCALL_DEFINE5(clone, unsigned long, clone_flags, unsigned long, newsp,
2946 		 int __user *, parent_tidptr,
2947 		 unsigned long, tls,
2948 		 int __user *, child_tidptr)
2949 #elif defined(CONFIG_CLONE_BACKWARDS2)
2950 SYSCALL_DEFINE5(clone, unsigned long, newsp, unsigned long, clone_flags,
2951 		 int __user *, parent_tidptr,
2952 		 int __user *, child_tidptr,
2953 		 unsigned long, tls)
2954 #elif defined(CONFIG_CLONE_BACKWARDS3)
2955 SYSCALL_DEFINE6(clone, unsigned long, clone_flags, unsigned long, newsp,
2956 		int, stack_size,
2957 		int __user *, parent_tidptr,
2958 		int __user *, child_tidptr,
2959 		unsigned long, tls)
2960 #else
2961 SYSCALL_DEFINE5(clone, unsigned long, clone_flags, unsigned long, newsp,
2962 		 int __user *, parent_tidptr,
2963 		 int __user *, child_tidptr,
2964 		 unsigned long, tls)
2965 #endif
2966 {
2967 	struct kernel_clone_args args = {
2968 		.flags		= (lower_32_bits(clone_flags) & ~CSIGNAL),
2969 		.pidfd		= parent_tidptr,
2970 		.child_tid	= child_tidptr,
2971 		.parent_tid	= parent_tidptr,
2972 		.exit_signal	= (lower_32_bits(clone_flags) & CSIGNAL),
2973 		.stack		= newsp,
2974 		.tls		= tls,
2975 	};
2976 
2977 	return kernel_clone(&args);
2978 }
2979 #endif
2980 
2981 noinline static int copy_clone_args_from_user(struct kernel_clone_args *kargs,
2982 					      struct clone_args __user *uargs,
2983 					      size_t usize)
2984 {
2985 	int err;
2986 	struct clone_args args;
2987 	pid_t *kset_tid = kargs->set_tid;
2988 
2989 	BUILD_BUG_ON(offsetofend(struct clone_args, tls) !=
2990 		     CLONE_ARGS_SIZE_VER0);
2991 	BUILD_BUG_ON(offsetofend(struct clone_args, set_tid_size) !=
2992 		     CLONE_ARGS_SIZE_VER1);
2993 	BUILD_BUG_ON(offsetofend(struct clone_args, cgroup) !=
2994 		     CLONE_ARGS_SIZE_VER2);
2995 	BUILD_BUG_ON(sizeof(struct clone_args) != CLONE_ARGS_SIZE_VER2);
2996 
2997 	if (unlikely(usize > PAGE_SIZE))
2998 		return -E2BIG;
2999 	if (unlikely(usize < CLONE_ARGS_SIZE_VER0))
3000 		return -EINVAL;
3001 
3002 	err = copy_struct_from_user(&args, sizeof(args), uargs, usize);
3003 	if (err)
3004 		return err;
3005 
3006 	if (unlikely(args.set_tid_size > MAX_PID_NS_LEVEL))
3007 		return -EINVAL;
3008 
3009 	if (unlikely(!args.set_tid && args.set_tid_size > 0))
3010 		return -EINVAL;
3011 
3012 	if (unlikely(args.set_tid && args.set_tid_size == 0))
3013 		return -EINVAL;
3014 
3015 	/*
3016 	 * Verify that higher 32bits of exit_signal are unset and that
3017 	 * it is a valid signal
3018 	 */
3019 	if (unlikely((args.exit_signal & ~((u64)CSIGNAL)) ||
3020 		     !valid_signal(args.exit_signal)))
3021 		return -EINVAL;
3022 
3023 	if ((args.flags & CLONE_INTO_CGROUP) &&
3024 	    (args.cgroup > INT_MAX || usize < CLONE_ARGS_SIZE_VER2))
3025 		return -EINVAL;
3026 
3027 	*kargs = (struct kernel_clone_args){
3028 		.flags		= args.flags,
3029 		.pidfd		= u64_to_user_ptr(args.pidfd),
3030 		.child_tid	= u64_to_user_ptr(args.child_tid),
3031 		.parent_tid	= u64_to_user_ptr(args.parent_tid),
3032 		.exit_signal	= args.exit_signal,
3033 		.stack		= args.stack,
3034 		.stack_size	= args.stack_size,
3035 		.tls		= args.tls,
3036 		.set_tid_size	= args.set_tid_size,
3037 		.cgroup		= args.cgroup,
3038 	};
3039 
3040 	if (args.set_tid &&
3041 		copy_from_user(kset_tid, u64_to_user_ptr(args.set_tid),
3042 			(kargs->set_tid_size * sizeof(pid_t))))
3043 		return -EFAULT;
3044 
3045 	kargs->set_tid = kset_tid;
3046 
3047 	return 0;
3048 }
3049 
3050 /**
3051  * clone3_stack_valid - check and prepare stack
3052  * @kargs: kernel clone args
3053  *
3054  * Verify that the stack arguments userspace gave us are sane.
3055  * In addition, set the stack direction for userspace since it's easy for us to
3056  * determine.
3057  */
3058 static inline bool clone3_stack_valid(struct kernel_clone_args *kargs)
3059 {
3060 	if (kargs->stack == 0) {
3061 		if (kargs->stack_size > 0)
3062 			return false;
3063 	} else {
3064 		if (kargs->stack_size == 0)
3065 			return false;
3066 
3067 		if (!access_ok((void __user *)kargs->stack, kargs->stack_size))
3068 			return false;
3069 
3070 #if !defined(CONFIG_STACK_GROWSUP)
3071 		kargs->stack += kargs->stack_size;
3072 #endif
3073 	}
3074 
3075 	return true;
3076 }
3077 
3078 static bool clone3_args_valid(struct kernel_clone_args *kargs)
3079 {
3080 	/* Verify that no unknown flags are passed along. */
3081 	if (kargs->flags &
3082 	    ~(CLONE_LEGACY_FLAGS | CLONE_CLEAR_SIGHAND | CLONE_INTO_CGROUP))
3083 		return false;
3084 
3085 	/*
3086 	 * - make the CLONE_DETACHED bit reusable for clone3
3087 	 * - make the CSIGNAL bits reusable for clone3
3088 	 */
3089 	if (kargs->flags & (CLONE_DETACHED | (CSIGNAL & (~CLONE_NEWTIME))))
3090 		return false;
3091 
3092 	if ((kargs->flags & (CLONE_SIGHAND | CLONE_CLEAR_SIGHAND)) ==
3093 	    (CLONE_SIGHAND | CLONE_CLEAR_SIGHAND))
3094 		return false;
3095 
3096 	if ((kargs->flags & (CLONE_THREAD | CLONE_PARENT)) &&
3097 	    kargs->exit_signal)
3098 		return false;
3099 
3100 	if (!clone3_stack_valid(kargs))
3101 		return false;
3102 
3103 	return true;
3104 }
3105 
3106 /**
3107  * sys_clone3 - create a new process with specific properties
3108  * @uargs: argument structure
3109  * @size:  size of @uargs
3110  *
3111  * clone3() is the extensible successor to clone()/clone2().
3112  * It takes a struct as argument that is versioned by its size.
3113  *
3114  * Return: On success, a positive PID for the child process.
3115  *         On error, a negative errno number.
3116  */
3117 SYSCALL_DEFINE2(clone3, struct clone_args __user *, uargs, size_t, size)
3118 {
3119 	int err;
3120 
3121 	struct kernel_clone_args kargs;
3122 	pid_t set_tid[MAX_PID_NS_LEVEL];
3123 
3124 #ifdef __ARCH_BROKEN_SYS_CLONE3
3125 #warning clone3() entry point is missing, please fix
3126 	return -ENOSYS;
3127 #endif
3128 
3129 	kargs.set_tid = set_tid;
3130 
3131 	err = copy_clone_args_from_user(&kargs, uargs, size);
3132 	if (err)
3133 		return err;
3134 
3135 	if (!clone3_args_valid(&kargs))
3136 		return -EINVAL;
3137 
3138 	return kernel_clone(&kargs);
3139 }
3140 
3141 void walk_process_tree(struct task_struct *top, proc_visitor visitor, void *data)
3142 {
3143 	struct task_struct *leader, *parent, *child;
3144 	int res;
3145 
3146 	read_lock(&tasklist_lock);
3147 	leader = top = top->group_leader;
3148 down:
3149 	for_each_thread(leader, parent) {
3150 		list_for_each_entry(child, &parent->children, sibling) {
3151 			res = visitor(child, data);
3152 			if (res) {
3153 				if (res < 0)
3154 					goto out;
3155 				leader = child;
3156 				goto down;
3157 			}
3158 up:
3159 			;
3160 		}
3161 	}
3162 
3163 	if (leader != top) {
3164 		child = leader;
3165 		parent = child->real_parent;
3166 		leader = parent->group_leader;
3167 		goto up;
3168 	}
3169 out:
3170 	read_unlock(&tasklist_lock);
3171 }
3172 
3173 #ifndef ARCH_MIN_MMSTRUCT_ALIGN
3174 #define ARCH_MIN_MMSTRUCT_ALIGN 0
3175 #endif
3176 
3177 static void sighand_ctor(void *data)
3178 {
3179 	struct sighand_struct *sighand = data;
3180 
3181 	spin_lock_init(&sighand->siglock);
3182 	init_waitqueue_head(&sighand->signalfd_wqh);
3183 }
3184 
3185 void __init mm_cache_init(void)
3186 {
3187 	unsigned int mm_size;
3188 
3189 	/*
3190 	 * The mm_cpumask is located at the end of mm_struct, and is
3191 	 * dynamically sized based on the maximum CPU number this system
3192 	 * can have, taking hotplug into account (nr_cpu_ids).
3193 	 */
3194 	mm_size = sizeof(struct mm_struct) + cpumask_size() + mm_cid_size();
3195 
3196 	mm_cachep = kmem_cache_create_usercopy("mm_struct",
3197 			mm_size, ARCH_MIN_MMSTRUCT_ALIGN,
3198 			SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_ACCOUNT,
3199 			offsetof(struct mm_struct, saved_auxv),
3200 			sizeof_field(struct mm_struct, saved_auxv),
3201 			NULL);
3202 }
3203 
3204 void __init proc_caches_init(void)
3205 {
3206 	struct kmem_cache_args args = {
3207 		.use_freeptr_offset = true,
3208 		.freeptr_offset = offsetof(struct vm_area_struct, vm_freeptr),
3209 	};
3210 
3211 	sighand_cachep = kmem_cache_create("sighand_cache",
3212 			sizeof(struct sighand_struct), 0,
3213 			SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_TYPESAFE_BY_RCU|
3214 			SLAB_ACCOUNT, sighand_ctor);
3215 	signal_cachep = kmem_cache_create("signal_cache",
3216 			sizeof(struct signal_struct), 0,
3217 			SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_ACCOUNT,
3218 			NULL);
3219 	files_cachep = kmem_cache_create("files_cache",
3220 			sizeof(struct files_struct), 0,
3221 			SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_ACCOUNT,
3222 			NULL);
3223 	fs_cachep = kmem_cache_create("fs_cache",
3224 			sizeof(struct fs_struct), 0,
3225 			SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_ACCOUNT,
3226 			NULL);
3227 	vm_area_cachep = kmem_cache_create("vm_area_struct",
3228 			sizeof(struct vm_area_struct), &args,
3229 			SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_TYPESAFE_BY_RCU|
3230 			SLAB_ACCOUNT);
3231 	mmap_init();
3232 	nsproxy_cache_init();
3233 }
3234 
3235 /*
3236  * Check constraints on flags passed to the unshare system call.
3237  */
3238 static int check_unshare_flags(unsigned long unshare_flags)
3239 {
3240 	if (unshare_flags & ~(CLONE_THREAD|CLONE_FS|CLONE_NEWNS|CLONE_SIGHAND|
3241 				CLONE_VM|CLONE_FILES|CLONE_SYSVSEM|
3242 				CLONE_NEWUTS|CLONE_NEWIPC|CLONE_NEWNET|
3243 				CLONE_NEWUSER|CLONE_NEWPID|CLONE_NEWCGROUP|
3244 				CLONE_NEWTIME))
3245 		return -EINVAL;
3246 	/*
3247 	 * Not implemented, but pretend it works if there is nothing
3248 	 * to unshare.  Note that unsharing the address space or the
3249 	 * signal handlers also need to unshare the signal queues (aka
3250 	 * CLONE_THREAD).
3251 	 */
3252 	if (unshare_flags & (CLONE_THREAD | CLONE_SIGHAND | CLONE_VM)) {
3253 		if (!thread_group_empty(current))
3254 			return -EINVAL;
3255 	}
3256 	if (unshare_flags & (CLONE_SIGHAND | CLONE_VM)) {
3257 		if (refcount_read(&current->sighand->count) > 1)
3258 			return -EINVAL;
3259 	}
3260 	if (unshare_flags & CLONE_VM) {
3261 		if (!current_is_single_threaded())
3262 			return -EINVAL;
3263 	}
3264 
3265 	return 0;
3266 }
3267 
3268 /*
3269  * Unshare the filesystem structure if it is being shared
3270  */
3271 static int unshare_fs(unsigned long unshare_flags, struct fs_struct **new_fsp)
3272 {
3273 	struct fs_struct *fs = current->fs;
3274 
3275 	if (!(unshare_flags & CLONE_FS) || !fs)
3276 		return 0;
3277 
3278 	/* don't need lock here; in the worst case we'll do useless copy */
3279 	if (fs->users == 1)
3280 		return 0;
3281 
3282 	*new_fsp = copy_fs_struct(fs);
3283 	if (!*new_fsp)
3284 		return -ENOMEM;
3285 
3286 	return 0;
3287 }
3288 
3289 /*
3290  * Unshare file descriptor table if it is being shared
3291  */
3292 static int unshare_fd(unsigned long unshare_flags, struct files_struct **new_fdp)
3293 {
3294 	struct files_struct *fd = current->files;
3295 
3296 	if ((unshare_flags & CLONE_FILES) &&
3297 	    (fd && atomic_read(&fd->count) > 1)) {
3298 		fd = dup_fd(fd, NULL);
3299 		if (IS_ERR(fd))
3300 			return PTR_ERR(fd);
3301 		*new_fdp = fd;
3302 	}
3303 
3304 	return 0;
3305 }
3306 
3307 /*
3308  * unshare allows a process to 'unshare' part of the process
3309  * context which was originally shared using clone.  copy_*
3310  * functions used by kernel_clone() cannot be used here directly
3311  * because they modify an inactive task_struct that is being
3312  * constructed. Here we are modifying the current, active,
3313  * task_struct.
3314  */
3315 int ksys_unshare(unsigned long unshare_flags)
3316 {
3317 	struct fs_struct *fs, *new_fs = NULL;
3318 	struct files_struct *new_fd = NULL;
3319 	struct cred *new_cred = NULL;
3320 	struct nsproxy *new_nsproxy = NULL;
3321 	int do_sysvsem = 0;
3322 	int err;
3323 
3324 	/*
3325 	 * If unsharing a user namespace must also unshare the thread group
3326 	 * and unshare the filesystem root and working directories.
3327 	 */
3328 	if (unshare_flags & CLONE_NEWUSER)
3329 		unshare_flags |= CLONE_THREAD | CLONE_FS;
3330 	/*
3331 	 * If unsharing vm, must also unshare signal handlers.
3332 	 */
3333 	if (unshare_flags & CLONE_VM)
3334 		unshare_flags |= CLONE_SIGHAND;
3335 	/*
3336 	 * If unsharing a signal handlers, must also unshare the signal queues.
3337 	 */
3338 	if (unshare_flags & CLONE_SIGHAND)
3339 		unshare_flags |= CLONE_THREAD;
3340 	/*
3341 	 * If unsharing namespace, must also unshare filesystem information.
3342 	 */
3343 	if (unshare_flags & CLONE_NEWNS)
3344 		unshare_flags |= CLONE_FS;
3345 
3346 	err = check_unshare_flags(unshare_flags);
3347 	if (err)
3348 		goto bad_unshare_out;
3349 	/*
3350 	 * CLONE_NEWIPC must also detach from the undolist: after switching
3351 	 * to a new ipc namespace, the semaphore arrays from the old
3352 	 * namespace are unreachable.
3353 	 */
3354 	if (unshare_flags & (CLONE_NEWIPC|CLONE_SYSVSEM))
3355 		do_sysvsem = 1;
3356 	err = unshare_fs(unshare_flags, &new_fs);
3357 	if (err)
3358 		goto bad_unshare_out;
3359 	err = unshare_fd(unshare_flags, &new_fd);
3360 	if (err)
3361 		goto bad_unshare_cleanup_fs;
3362 	err = unshare_userns(unshare_flags, &new_cred);
3363 	if (err)
3364 		goto bad_unshare_cleanup_fd;
3365 	err = unshare_nsproxy_namespaces(unshare_flags, &new_nsproxy,
3366 					 new_cred, new_fs);
3367 	if (err)
3368 		goto bad_unshare_cleanup_cred;
3369 
3370 	if (new_cred) {
3371 		err = set_cred_ucounts(new_cred);
3372 		if (err)
3373 			goto bad_unshare_cleanup_cred;
3374 	}
3375 
3376 	if (new_fs || new_fd || do_sysvsem || new_cred || new_nsproxy) {
3377 		if (do_sysvsem) {
3378 			/*
3379 			 * CLONE_SYSVSEM is equivalent to sys_exit().
3380 			 */
3381 			exit_sem(current);
3382 		}
3383 		if (unshare_flags & CLONE_NEWIPC) {
3384 			/* Orphan segments in old ns (see sem above). */
3385 			exit_shm(current);
3386 			shm_init_task(current);
3387 		}
3388 
3389 		if (new_nsproxy)
3390 			switch_task_namespaces(current, new_nsproxy);
3391 
3392 		task_lock(current);
3393 
3394 		if (new_fs) {
3395 			fs = current->fs;
3396 			spin_lock(&fs->lock);
3397 			current->fs = new_fs;
3398 			if (--fs->users)
3399 				new_fs = NULL;
3400 			else
3401 				new_fs = fs;
3402 			spin_unlock(&fs->lock);
3403 		}
3404 
3405 		if (new_fd)
3406 			swap(current->files, new_fd);
3407 
3408 		task_unlock(current);
3409 
3410 		if (new_cred) {
3411 			/* Install the new user namespace */
3412 			commit_creds(new_cred);
3413 			new_cred = NULL;
3414 		}
3415 	}
3416 
3417 	perf_event_namespaces(current);
3418 
3419 bad_unshare_cleanup_cred:
3420 	if (new_cred)
3421 		put_cred(new_cred);
3422 bad_unshare_cleanup_fd:
3423 	if (new_fd)
3424 		put_files_struct(new_fd);
3425 
3426 bad_unshare_cleanup_fs:
3427 	if (new_fs)
3428 		free_fs_struct(new_fs);
3429 
3430 bad_unshare_out:
3431 	return err;
3432 }
3433 
3434 SYSCALL_DEFINE1(unshare, unsigned long, unshare_flags)
3435 {
3436 	return ksys_unshare(unshare_flags);
3437 }
3438 
3439 /*
3440  *	Helper to unshare the files of the current task.
3441  *	We don't want to expose copy_files internals to
3442  *	the exec layer of the kernel.
3443  */
3444 
3445 int unshare_files(void)
3446 {
3447 	struct task_struct *task = current;
3448 	struct files_struct *old, *copy = NULL;
3449 	int error;
3450 
3451 	error = unshare_fd(CLONE_FILES, &copy);
3452 	if (error || !copy)
3453 		return error;
3454 
3455 	old = task->files;
3456 	task_lock(task);
3457 	task->files = copy;
3458 	task_unlock(task);
3459 	put_files_struct(old);
3460 	return 0;
3461 }
3462 
3463 int sysctl_max_threads(const struct ctl_table *table, int write,
3464 		       void *buffer, size_t *lenp, loff_t *ppos)
3465 {
3466 	struct ctl_table t;
3467 	int ret;
3468 	int threads = max_threads;
3469 	int min = 1;
3470 	int max = MAX_THREADS;
3471 
3472 	t = *table;
3473 	t.data = &threads;
3474 	t.extra1 = &min;
3475 	t.extra2 = &max;
3476 
3477 	ret = proc_dointvec_minmax(&t, write, buffer, lenp, ppos);
3478 	if (ret || !write)
3479 		return ret;
3480 
3481 	max_threads = threads;
3482 
3483 	return 0;
3484 }
3485