xref: /linux-6.15/kernel/fork.c (revision b25bcabb)
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 	return new;
502 }
503 
504 void vm_area_free(struct vm_area_struct *vma)
505 {
506 	/* The vma should be detached while being destroyed. */
507 	vma_assert_detached(vma);
508 	vma_numab_state_free(vma);
509 	free_anon_vma_name(vma);
510 	kmem_cache_free(vm_area_cachep, vma);
511 }
512 
513 static void account_kernel_stack(struct task_struct *tsk, int account)
514 {
515 	if (IS_ENABLED(CONFIG_VMAP_STACK)) {
516 		struct vm_struct *vm = task_stack_vm_area(tsk);
517 		int i;
518 
519 		for (i = 0; i < THREAD_SIZE / PAGE_SIZE; i++)
520 			mod_lruvec_page_state(vm->pages[i], NR_KERNEL_STACK_KB,
521 					      account * (PAGE_SIZE / 1024));
522 	} else {
523 		void *stack = task_stack_page(tsk);
524 
525 		/* All stack pages are in the same node. */
526 		mod_lruvec_kmem_state(stack, NR_KERNEL_STACK_KB,
527 				      account * (THREAD_SIZE / 1024));
528 	}
529 }
530 
531 void exit_task_stack_account(struct task_struct *tsk)
532 {
533 	account_kernel_stack(tsk, -1);
534 
535 	if (IS_ENABLED(CONFIG_VMAP_STACK)) {
536 		struct vm_struct *vm;
537 		int i;
538 
539 		vm = task_stack_vm_area(tsk);
540 		for (i = 0; i < THREAD_SIZE / PAGE_SIZE; i++)
541 			memcg_kmem_uncharge_page(vm->pages[i], 0);
542 	}
543 }
544 
545 static void release_task_stack(struct task_struct *tsk)
546 {
547 	if (WARN_ON(READ_ONCE(tsk->__state) != TASK_DEAD))
548 		return;  /* Better to leak the stack than to free prematurely */
549 
550 	free_thread_stack(tsk);
551 }
552 
553 #ifdef CONFIG_THREAD_INFO_IN_TASK
554 void put_task_stack(struct task_struct *tsk)
555 {
556 	if (refcount_dec_and_test(&tsk->stack_refcount))
557 		release_task_stack(tsk);
558 }
559 #endif
560 
561 void free_task(struct task_struct *tsk)
562 {
563 #ifdef CONFIG_SECCOMP
564 	WARN_ON_ONCE(tsk->seccomp.filter);
565 #endif
566 	release_user_cpus_ptr(tsk);
567 	scs_release(tsk);
568 
569 #ifndef CONFIG_THREAD_INFO_IN_TASK
570 	/*
571 	 * The task is finally done with both the stack and thread_info,
572 	 * so free both.
573 	 */
574 	release_task_stack(tsk);
575 #else
576 	/*
577 	 * If the task had a separate stack allocation, it should be gone
578 	 * by now.
579 	 */
580 	WARN_ON_ONCE(refcount_read(&tsk->stack_refcount) != 0);
581 #endif
582 	rt_mutex_debug_task_free(tsk);
583 	ftrace_graph_exit_task(tsk);
584 	arch_release_task_struct(tsk);
585 	if (tsk->flags & PF_KTHREAD)
586 		free_kthread_struct(tsk);
587 	bpf_task_storage_free(tsk);
588 	free_task_struct(tsk);
589 }
590 EXPORT_SYMBOL(free_task);
591 
592 static void dup_mm_exe_file(struct mm_struct *mm, struct mm_struct *oldmm)
593 {
594 	struct file *exe_file;
595 
596 	exe_file = get_mm_exe_file(oldmm);
597 	RCU_INIT_POINTER(mm->exe_file, exe_file);
598 	/*
599 	 * We depend on the oldmm having properly denied write access to the
600 	 * exe_file already.
601 	 */
602 	if (exe_file && exe_file_deny_write_access(exe_file))
603 		pr_warn_once("exe_file_deny_write_access() failed in %s\n", __func__);
604 }
605 
606 #ifdef CONFIG_MMU
607 static __latent_entropy int dup_mmap(struct mm_struct *mm,
608 					struct mm_struct *oldmm)
609 {
610 	struct vm_area_struct *mpnt, *tmp;
611 	int retval;
612 	unsigned long charge = 0;
613 	LIST_HEAD(uf);
614 	VMA_ITERATOR(vmi, mm, 0);
615 
616 	if (mmap_write_lock_killable(oldmm))
617 		return -EINTR;
618 	flush_cache_dup_mm(oldmm);
619 	uprobe_dup_mmap(oldmm, mm);
620 	/*
621 	 * Not linked in yet - no deadlock potential:
622 	 */
623 	mmap_write_lock_nested(mm, SINGLE_DEPTH_NESTING);
624 
625 	/* No ordering required: file already has been exposed. */
626 	dup_mm_exe_file(mm, oldmm);
627 
628 	mm->total_vm = oldmm->total_vm;
629 	mm->data_vm = oldmm->data_vm;
630 	mm->exec_vm = oldmm->exec_vm;
631 	mm->stack_vm = oldmm->stack_vm;
632 
633 	/* Use __mt_dup() to efficiently build an identical maple tree. */
634 	retval = __mt_dup(&oldmm->mm_mt, &mm->mm_mt, GFP_KERNEL);
635 	if (unlikely(retval))
636 		goto out;
637 
638 	mt_clear_in_rcu(vmi.mas.tree);
639 	for_each_vma(vmi, mpnt) {
640 		struct file *file;
641 
642 		vma_start_write(mpnt);
643 		if (mpnt->vm_flags & VM_DONTCOPY) {
644 			retval = vma_iter_clear_gfp(&vmi, mpnt->vm_start,
645 						    mpnt->vm_end, GFP_KERNEL);
646 			if (retval)
647 				goto loop_out;
648 
649 			vm_stat_account(mm, mpnt->vm_flags, -vma_pages(mpnt));
650 			continue;
651 		}
652 		charge = 0;
653 		/*
654 		 * Don't duplicate many vmas if we've been oom-killed (for
655 		 * example)
656 		 */
657 		if (fatal_signal_pending(current)) {
658 			retval = -EINTR;
659 			goto loop_out;
660 		}
661 		if (mpnt->vm_flags & VM_ACCOUNT) {
662 			unsigned long len = vma_pages(mpnt);
663 
664 			if (security_vm_enough_memory_mm(oldmm, len)) /* sic */
665 				goto fail_nomem;
666 			charge = len;
667 		}
668 		tmp = vm_area_dup(mpnt);
669 		if (!tmp)
670 			goto fail_nomem;
671 		retval = vma_dup_policy(mpnt, tmp);
672 		if (retval)
673 			goto fail_nomem_policy;
674 		tmp->vm_mm = mm;
675 		retval = dup_userfaultfd(tmp, &uf);
676 		if (retval)
677 			goto fail_nomem_anon_vma_fork;
678 		if (tmp->vm_flags & VM_WIPEONFORK) {
679 			/*
680 			 * VM_WIPEONFORK gets a clean slate in the child.
681 			 * Don't prepare anon_vma until fault since we don't
682 			 * copy page for current vma.
683 			 */
684 			tmp->anon_vma = NULL;
685 		} else if (anon_vma_fork(tmp, mpnt))
686 			goto fail_nomem_anon_vma_fork;
687 		vm_flags_clear(tmp, VM_LOCKED_MASK);
688 		/*
689 		 * Copy/update hugetlb private vma information.
690 		 */
691 		if (is_vm_hugetlb_page(tmp))
692 			hugetlb_dup_vma_private(tmp);
693 
694 		/*
695 		 * Link the vma into the MT. After using __mt_dup(), memory
696 		 * allocation is not necessary here, so it cannot fail.
697 		 */
698 		vma_iter_bulk_store(&vmi, tmp);
699 
700 		mm->map_count++;
701 
702 		if (tmp->vm_ops && tmp->vm_ops->open)
703 			tmp->vm_ops->open(tmp);
704 
705 		file = tmp->vm_file;
706 		if (file) {
707 			struct address_space *mapping = file->f_mapping;
708 
709 			get_file(file);
710 			i_mmap_lock_write(mapping);
711 			if (vma_is_shared_maywrite(tmp))
712 				mapping_allow_writable(mapping);
713 			flush_dcache_mmap_lock(mapping);
714 			/* insert tmp into the share list, just after mpnt */
715 			vma_interval_tree_insert_after(tmp, mpnt,
716 					&mapping->i_mmap);
717 			flush_dcache_mmap_unlock(mapping);
718 			i_mmap_unlock_write(mapping);
719 		}
720 
721 		if (!(tmp->vm_flags & VM_WIPEONFORK))
722 			retval = copy_page_range(tmp, mpnt);
723 
724 		if (retval) {
725 			mpnt = vma_next(&vmi);
726 			goto loop_out;
727 		}
728 	}
729 	/* a new mm has just been created */
730 	retval = arch_dup_mmap(oldmm, mm);
731 loop_out:
732 	vma_iter_free(&vmi);
733 	if (!retval) {
734 		mt_set_in_rcu(vmi.mas.tree);
735 		ksm_fork(mm, oldmm);
736 		khugepaged_fork(mm, oldmm);
737 	} else {
738 
739 		/*
740 		 * The entire maple tree has already been duplicated. If the
741 		 * mmap duplication fails, mark the failure point with
742 		 * XA_ZERO_ENTRY. In exit_mmap(), if this marker is encountered,
743 		 * stop releasing VMAs that have not been duplicated after this
744 		 * point.
745 		 */
746 		if (mpnt) {
747 			mas_set_range(&vmi.mas, mpnt->vm_start, mpnt->vm_end - 1);
748 			mas_store(&vmi.mas, XA_ZERO_ENTRY);
749 			/* Avoid OOM iterating a broken tree */
750 			set_bit(MMF_OOM_SKIP, &mm->flags);
751 		}
752 		/*
753 		 * The mm_struct is going to exit, but the locks will be dropped
754 		 * first.  Set the mm_struct as unstable is advisable as it is
755 		 * not fully initialised.
756 		 */
757 		set_bit(MMF_UNSTABLE, &mm->flags);
758 	}
759 out:
760 	mmap_write_unlock(mm);
761 	flush_tlb_mm(oldmm);
762 	mmap_write_unlock(oldmm);
763 	if (!retval)
764 		dup_userfaultfd_complete(&uf);
765 	else
766 		dup_userfaultfd_fail(&uf);
767 	return retval;
768 
769 fail_nomem_anon_vma_fork:
770 	mpol_put(vma_policy(tmp));
771 fail_nomem_policy:
772 	vm_area_free(tmp);
773 fail_nomem:
774 	retval = -ENOMEM;
775 	vm_unacct_memory(charge);
776 	goto loop_out;
777 }
778 
779 static inline int mm_alloc_pgd(struct mm_struct *mm)
780 {
781 	mm->pgd = pgd_alloc(mm);
782 	if (unlikely(!mm->pgd))
783 		return -ENOMEM;
784 	return 0;
785 }
786 
787 static inline void mm_free_pgd(struct mm_struct *mm)
788 {
789 	pgd_free(mm, mm->pgd);
790 }
791 #else
792 static int dup_mmap(struct mm_struct *mm, struct mm_struct *oldmm)
793 {
794 	mmap_write_lock(oldmm);
795 	dup_mm_exe_file(mm, oldmm);
796 	mmap_write_unlock(oldmm);
797 	return 0;
798 }
799 #define mm_alloc_pgd(mm)	(0)
800 #define mm_free_pgd(mm)
801 #endif /* CONFIG_MMU */
802 
803 #ifdef CONFIG_MM_ID
804 static DEFINE_IDA(mm_ida);
805 
806 static inline int mm_alloc_id(struct mm_struct *mm)
807 {
808 	int ret;
809 
810 	ret = ida_alloc_range(&mm_ida, MM_ID_MIN, MM_ID_MAX, GFP_KERNEL);
811 	if (ret < 0)
812 		return ret;
813 	mm->mm_id = ret;
814 	return 0;
815 }
816 
817 static inline void mm_free_id(struct mm_struct *mm)
818 {
819 	const mm_id_t id = mm->mm_id;
820 
821 	mm->mm_id = MM_ID_DUMMY;
822 	if (id == MM_ID_DUMMY)
823 		return;
824 	if (WARN_ON_ONCE(id < MM_ID_MIN || id > MM_ID_MAX))
825 		return;
826 	ida_free(&mm_ida, id);
827 }
828 #else /* !CONFIG_MM_ID */
829 static inline int mm_alloc_id(struct mm_struct *mm) { return 0; }
830 static inline void mm_free_id(struct mm_struct *mm) {}
831 #endif /* CONFIG_MM_ID */
832 
833 static void check_mm(struct mm_struct *mm)
834 {
835 	int i;
836 
837 	BUILD_BUG_ON_MSG(ARRAY_SIZE(resident_page_types) != NR_MM_COUNTERS,
838 			 "Please make sure 'struct resident_page_types[]' is updated as well");
839 
840 	for (i = 0; i < NR_MM_COUNTERS; i++) {
841 		long x = percpu_counter_sum(&mm->rss_stat[i]);
842 
843 		if (unlikely(x))
844 			pr_alert("BUG: Bad rss-counter state mm:%p type:%s val:%ld\n",
845 				 mm, resident_page_types[i], x);
846 	}
847 
848 	if (mm_pgtables_bytes(mm))
849 		pr_alert("BUG: non-zero pgtables_bytes on freeing mm: %ld\n",
850 				mm_pgtables_bytes(mm));
851 
852 #if defined(CONFIG_TRANSPARENT_HUGEPAGE) && !defined(CONFIG_SPLIT_PMD_PTLOCKS)
853 	VM_BUG_ON_MM(mm->pmd_huge_pte, mm);
854 #endif
855 }
856 
857 #define allocate_mm()	(kmem_cache_alloc(mm_cachep, GFP_KERNEL))
858 #define free_mm(mm)	(kmem_cache_free(mm_cachep, (mm)))
859 
860 static void do_check_lazy_tlb(void *arg)
861 {
862 	struct mm_struct *mm = arg;
863 
864 	WARN_ON_ONCE(current->active_mm == mm);
865 }
866 
867 static void do_shoot_lazy_tlb(void *arg)
868 {
869 	struct mm_struct *mm = arg;
870 
871 	if (current->active_mm == mm) {
872 		WARN_ON_ONCE(current->mm);
873 		current->active_mm = &init_mm;
874 		switch_mm(mm, &init_mm, current);
875 	}
876 }
877 
878 static void cleanup_lazy_tlbs(struct mm_struct *mm)
879 {
880 	if (!IS_ENABLED(CONFIG_MMU_LAZY_TLB_SHOOTDOWN)) {
881 		/*
882 		 * In this case, lazy tlb mms are refounted and would not reach
883 		 * __mmdrop until all CPUs have switched away and mmdrop()ed.
884 		 */
885 		return;
886 	}
887 
888 	/*
889 	 * Lazy mm shootdown does not refcount "lazy tlb mm" usage, rather it
890 	 * requires lazy mm users to switch to another mm when the refcount
891 	 * drops to zero, before the mm is freed. This requires IPIs here to
892 	 * switch kernel threads to init_mm.
893 	 *
894 	 * archs that use IPIs to flush TLBs can piggy-back that lazy tlb mm
895 	 * switch with the final userspace teardown TLB flush which leaves the
896 	 * mm lazy on this CPU but no others, reducing the need for additional
897 	 * IPIs here. There are cases where a final IPI is still required here,
898 	 * such as the final mmdrop being performed on a different CPU than the
899 	 * one exiting, or kernel threads using the mm when userspace exits.
900 	 *
901 	 * IPI overheads have not found to be expensive, but they could be
902 	 * reduced in a number of possible ways, for example (roughly
903 	 * increasing order of complexity):
904 	 * - The last lazy reference created by exit_mm() could instead switch
905 	 *   to init_mm, however it's probable this will run on the same CPU
906 	 *   immediately afterwards, so this may not reduce IPIs much.
907 	 * - A batch of mms requiring IPIs could be gathered and freed at once.
908 	 * - CPUs store active_mm where it can be remotely checked without a
909 	 *   lock, to filter out false-positives in the cpumask.
910 	 * - After mm_users or mm_count reaches zero, switching away from the
911 	 *   mm could clear mm_cpumask to reduce some IPIs, perhaps together
912 	 *   with some batching or delaying of the final IPIs.
913 	 * - A delayed freeing and RCU-like quiescing sequence based on mm
914 	 *   switching to avoid IPIs completely.
915 	 */
916 	on_each_cpu_mask(mm_cpumask(mm), do_shoot_lazy_tlb, (void *)mm, 1);
917 	if (IS_ENABLED(CONFIG_DEBUG_VM_SHOOT_LAZIES))
918 		on_each_cpu(do_check_lazy_tlb, (void *)mm, 1);
919 }
920 
921 /*
922  * Called when the last reference to the mm
923  * is dropped: either by a lazy thread or by
924  * mmput. Free the page directory and the mm.
925  */
926 void __mmdrop(struct mm_struct *mm)
927 {
928 	BUG_ON(mm == &init_mm);
929 	WARN_ON_ONCE(mm == current->mm);
930 
931 	/* Ensure no CPUs are using this as their lazy tlb mm */
932 	cleanup_lazy_tlbs(mm);
933 
934 	WARN_ON_ONCE(mm == current->active_mm);
935 	mm_free_pgd(mm);
936 	mm_free_id(mm);
937 	destroy_context(mm);
938 	mmu_notifier_subscriptions_destroy(mm);
939 	check_mm(mm);
940 	put_user_ns(mm->user_ns);
941 	mm_pasid_drop(mm);
942 	mm_destroy_cid(mm);
943 	percpu_counter_destroy_many(mm->rss_stat, NR_MM_COUNTERS);
944 
945 	free_mm(mm);
946 }
947 EXPORT_SYMBOL_GPL(__mmdrop);
948 
949 static void mmdrop_async_fn(struct work_struct *work)
950 {
951 	struct mm_struct *mm;
952 
953 	mm = container_of(work, struct mm_struct, async_put_work);
954 	__mmdrop(mm);
955 }
956 
957 static void mmdrop_async(struct mm_struct *mm)
958 {
959 	if (unlikely(atomic_dec_and_test(&mm->mm_count))) {
960 		INIT_WORK(&mm->async_put_work, mmdrop_async_fn);
961 		schedule_work(&mm->async_put_work);
962 	}
963 }
964 
965 static inline void free_signal_struct(struct signal_struct *sig)
966 {
967 	taskstats_tgid_free(sig);
968 	sched_autogroup_exit(sig);
969 	/*
970 	 * __mmdrop is not safe to call from softirq context on x86 due to
971 	 * pgd_dtor so postpone it to the async context
972 	 */
973 	if (sig->oom_mm)
974 		mmdrop_async(sig->oom_mm);
975 	kmem_cache_free(signal_cachep, sig);
976 }
977 
978 static inline void put_signal_struct(struct signal_struct *sig)
979 {
980 	if (refcount_dec_and_test(&sig->sigcnt))
981 		free_signal_struct(sig);
982 }
983 
984 void __put_task_struct(struct task_struct *tsk)
985 {
986 	WARN_ON(!tsk->exit_state);
987 	WARN_ON(refcount_read(&tsk->usage));
988 	WARN_ON(tsk == current);
989 
990 	sched_ext_free(tsk);
991 	io_uring_free(tsk);
992 	cgroup_free(tsk);
993 	task_numa_free(tsk, true);
994 	security_task_free(tsk);
995 	exit_creds(tsk);
996 	delayacct_tsk_free(tsk);
997 	put_signal_struct(tsk->signal);
998 	sched_core_free(tsk);
999 	free_task(tsk);
1000 }
1001 EXPORT_SYMBOL_GPL(__put_task_struct);
1002 
1003 void __put_task_struct_rcu_cb(struct rcu_head *rhp)
1004 {
1005 	struct task_struct *task = container_of(rhp, struct task_struct, rcu);
1006 
1007 	__put_task_struct(task);
1008 }
1009 EXPORT_SYMBOL_GPL(__put_task_struct_rcu_cb);
1010 
1011 void __init __weak arch_task_cache_init(void) { }
1012 
1013 /*
1014  * set_max_threads
1015  */
1016 static void __init set_max_threads(unsigned int max_threads_suggested)
1017 {
1018 	u64 threads;
1019 	unsigned long nr_pages = memblock_estimated_nr_free_pages();
1020 
1021 	/*
1022 	 * The number of threads shall be limited such that the thread
1023 	 * structures may only consume a small part of the available memory.
1024 	 */
1025 	if (fls64(nr_pages) + fls64(PAGE_SIZE) > 64)
1026 		threads = MAX_THREADS;
1027 	else
1028 		threads = div64_u64((u64) nr_pages * (u64) PAGE_SIZE,
1029 				    (u64) THREAD_SIZE * 8UL);
1030 
1031 	if (threads > max_threads_suggested)
1032 		threads = max_threads_suggested;
1033 
1034 	max_threads = clamp_t(u64, threads, MIN_THREADS, MAX_THREADS);
1035 }
1036 
1037 #ifdef CONFIG_ARCH_WANTS_DYNAMIC_TASK_STRUCT
1038 /* Initialized by the architecture: */
1039 int arch_task_struct_size __read_mostly;
1040 #endif
1041 
1042 static void __init task_struct_whitelist(unsigned long *offset, unsigned long *size)
1043 {
1044 	/* Fetch thread_struct whitelist for the architecture. */
1045 	arch_thread_struct_whitelist(offset, size);
1046 
1047 	/*
1048 	 * Handle zero-sized whitelist or empty thread_struct, otherwise
1049 	 * adjust offset to position of thread_struct in task_struct.
1050 	 */
1051 	if (unlikely(*size == 0))
1052 		*offset = 0;
1053 	else
1054 		*offset += offsetof(struct task_struct, thread);
1055 }
1056 
1057 void __init fork_init(void)
1058 {
1059 	int i;
1060 #ifndef ARCH_MIN_TASKALIGN
1061 #define ARCH_MIN_TASKALIGN	0
1062 #endif
1063 	int align = max_t(int, L1_CACHE_BYTES, ARCH_MIN_TASKALIGN);
1064 	unsigned long useroffset, usersize;
1065 
1066 	/* create a slab on which task_structs can be allocated */
1067 	task_struct_whitelist(&useroffset, &usersize);
1068 	task_struct_cachep = kmem_cache_create_usercopy("task_struct",
1069 			arch_task_struct_size, align,
1070 			SLAB_PANIC|SLAB_ACCOUNT,
1071 			useroffset, usersize, NULL);
1072 
1073 	/* do the arch specific task caches init */
1074 	arch_task_cache_init();
1075 
1076 	set_max_threads(MAX_THREADS);
1077 
1078 	init_task.signal->rlim[RLIMIT_NPROC].rlim_cur = max_threads/2;
1079 	init_task.signal->rlim[RLIMIT_NPROC].rlim_max = max_threads/2;
1080 	init_task.signal->rlim[RLIMIT_SIGPENDING] =
1081 		init_task.signal->rlim[RLIMIT_NPROC];
1082 
1083 	for (i = 0; i < UCOUNT_COUNTS; i++)
1084 		init_user_ns.ucount_max[i] = max_threads/2;
1085 
1086 	set_userns_rlimit_max(&init_user_ns, UCOUNT_RLIMIT_NPROC,      RLIM_INFINITY);
1087 	set_userns_rlimit_max(&init_user_ns, UCOUNT_RLIMIT_MSGQUEUE,   RLIM_INFINITY);
1088 	set_userns_rlimit_max(&init_user_ns, UCOUNT_RLIMIT_SIGPENDING, RLIM_INFINITY);
1089 	set_userns_rlimit_max(&init_user_ns, UCOUNT_RLIMIT_MEMLOCK,    RLIM_INFINITY);
1090 
1091 #ifdef CONFIG_VMAP_STACK
1092 	cpuhp_setup_state(CPUHP_BP_PREPARE_DYN, "fork:vm_stack_cache",
1093 			  NULL, free_vm_stack_cache);
1094 #endif
1095 
1096 	scs_init();
1097 
1098 	lockdep_init_task(&init_task);
1099 	uprobes_init();
1100 }
1101 
1102 int __weak arch_dup_task_struct(struct task_struct *dst,
1103 					       struct task_struct *src)
1104 {
1105 	*dst = *src;
1106 	return 0;
1107 }
1108 
1109 void set_task_stack_end_magic(struct task_struct *tsk)
1110 {
1111 	unsigned long *stackend;
1112 
1113 	stackend = end_of_stack(tsk);
1114 	*stackend = STACK_END_MAGIC;	/* for overflow detection */
1115 }
1116 
1117 static struct task_struct *dup_task_struct(struct task_struct *orig, int node)
1118 {
1119 	struct task_struct *tsk;
1120 	int err;
1121 
1122 	if (node == NUMA_NO_NODE)
1123 		node = tsk_fork_get_node(orig);
1124 	tsk = alloc_task_struct_node(node);
1125 	if (!tsk)
1126 		return NULL;
1127 
1128 	err = arch_dup_task_struct(tsk, orig);
1129 	if (err)
1130 		goto free_tsk;
1131 
1132 	err = alloc_thread_stack_node(tsk, node);
1133 	if (err)
1134 		goto free_tsk;
1135 
1136 #ifdef CONFIG_THREAD_INFO_IN_TASK
1137 	refcount_set(&tsk->stack_refcount, 1);
1138 #endif
1139 	account_kernel_stack(tsk, 1);
1140 
1141 	err = scs_prepare(tsk, node);
1142 	if (err)
1143 		goto free_stack;
1144 
1145 #ifdef CONFIG_SECCOMP
1146 	/*
1147 	 * We must handle setting up seccomp filters once we're under
1148 	 * the sighand lock in case orig has changed between now and
1149 	 * then. Until then, filter must be NULL to avoid messing up
1150 	 * the usage counts on the error path calling free_task.
1151 	 */
1152 	tsk->seccomp.filter = NULL;
1153 #endif
1154 
1155 	setup_thread_stack(tsk, orig);
1156 	clear_user_return_notifier(tsk);
1157 	clear_tsk_need_resched(tsk);
1158 	set_task_stack_end_magic(tsk);
1159 	clear_syscall_work_syscall_user_dispatch(tsk);
1160 
1161 #ifdef CONFIG_STACKPROTECTOR
1162 	tsk->stack_canary = get_random_canary();
1163 #endif
1164 	if (orig->cpus_ptr == &orig->cpus_mask)
1165 		tsk->cpus_ptr = &tsk->cpus_mask;
1166 	dup_user_cpus_ptr(tsk, orig, node);
1167 
1168 	/*
1169 	 * One for the user space visible state that goes away when reaped.
1170 	 * One for the scheduler.
1171 	 */
1172 	refcount_set(&tsk->rcu_users, 2);
1173 	/* One for the rcu users */
1174 	refcount_set(&tsk->usage, 1);
1175 #ifdef CONFIG_BLK_DEV_IO_TRACE
1176 	tsk->btrace_seq = 0;
1177 #endif
1178 	tsk->splice_pipe = NULL;
1179 	tsk->task_frag.page = NULL;
1180 	tsk->wake_q.next = NULL;
1181 	tsk->worker_private = NULL;
1182 
1183 	kcov_task_init(tsk);
1184 	kmsan_task_create(tsk);
1185 	kmap_local_fork(tsk);
1186 
1187 #ifdef CONFIG_FAULT_INJECTION
1188 	tsk->fail_nth = 0;
1189 #endif
1190 
1191 #ifdef CONFIG_BLK_CGROUP
1192 	tsk->throttle_disk = NULL;
1193 	tsk->use_memdelay = 0;
1194 #endif
1195 
1196 #ifdef CONFIG_ARCH_HAS_CPU_PASID
1197 	tsk->pasid_activated = 0;
1198 #endif
1199 
1200 #ifdef CONFIG_MEMCG
1201 	tsk->active_memcg = NULL;
1202 #endif
1203 
1204 #ifdef CONFIG_X86_BUS_LOCK_DETECT
1205 	tsk->reported_split_lock = 0;
1206 #endif
1207 
1208 #ifdef CONFIG_SCHED_MM_CID
1209 	tsk->mm_cid = -1;
1210 	tsk->last_mm_cid = -1;
1211 	tsk->mm_cid_active = 0;
1212 	tsk->migrate_from_cpu = -1;
1213 #endif
1214 	return tsk;
1215 
1216 free_stack:
1217 	exit_task_stack_account(tsk);
1218 	free_thread_stack(tsk);
1219 free_tsk:
1220 	free_task_struct(tsk);
1221 	return NULL;
1222 }
1223 
1224 __cacheline_aligned_in_smp DEFINE_SPINLOCK(mmlist_lock);
1225 
1226 static unsigned long default_dump_filter = MMF_DUMP_FILTER_DEFAULT;
1227 
1228 static int __init coredump_filter_setup(char *s)
1229 {
1230 	default_dump_filter =
1231 		(simple_strtoul(s, NULL, 0) << MMF_DUMP_FILTER_SHIFT) &
1232 		MMF_DUMP_FILTER_MASK;
1233 	return 1;
1234 }
1235 
1236 __setup("coredump_filter=", coredump_filter_setup);
1237 
1238 #include <linux/init_task.h>
1239 
1240 static void mm_init_aio(struct mm_struct *mm)
1241 {
1242 #ifdef CONFIG_AIO
1243 	spin_lock_init(&mm->ioctx_lock);
1244 	mm->ioctx_table = NULL;
1245 #endif
1246 }
1247 
1248 static __always_inline void mm_clear_owner(struct mm_struct *mm,
1249 					   struct task_struct *p)
1250 {
1251 #ifdef CONFIG_MEMCG
1252 	if (mm->owner == p)
1253 		WRITE_ONCE(mm->owner, NULL);
1254 #endif
1255 }
1256 
1257 static void mm_init_owner(struct mm_struct *mm, struct task_struct *p)
1258 {
1259 #ifdef CONFIG_MEMCG
1260 	mm->owner = p;
1261 #endif
1262 }
1263 
1264 static void mm_init_uprobes_state(struct mm_struct *mm)
1265 {
1266 #ifdef CONFIG_UPROBES
1267 	mm->uprobes_state.xol_area = NULL;
1268 #endif
1269 }
1270 
1271 static void mmap_init_lock(struct mm_struct *mm)
1272 {
1273 	init_rwsem(&mm->mmap_lock);
1274 	mm_lock_seqcount_init(mm);
1275 #ifdef CONFIG_PER_VMA_LOCK
1276 	rcuwait_init(&mm->vma_writer_wait);
1277 #endif
1278 }
1279 
1280 static struct mm_struct *mm_init(struct mm_struct *mm, struct task_struct *p,
1281 	struct user_namespace *user_ns)
1282 {
1283 	mt_init_flags(&mm->mm_mt, MM_MT_FLAGS);
1284 	mt_set_external_lock(&mm->mm_mt, &mm->mmap_lock);
1285 	atomic_set(&mm->mm_users, 1);
1286 	atomic_set(&mm->mm_count, 1);
1287 	seqcount_init(&mm->write_protect_seq);
1288 	mmap_init_lock(mm);
1289 	INIT_LIST_HEAD(&mm->mmlist);
1290 	mm_pgtables_bytes_init(mm);
1291 	mm->map_count = 0;
1292 	mm->locked_vm = 0;
1293 	atomic64_set(&mm->pinned_vm, 0);
1294 	memset(&mm->rss_stat, 0, sizeof(mm->rss_stat));
1295 	spin_lock_init(&mm->page_table_lock);
1296 	spin_lock_init(&mm->arg_lock);
1297 	mm_init_cpumask(mm);
1298 	mm_init_aio(mm);
1299 	mm_init_owner(mm, p);
1300 	mm_pasid_init(mm);
1301 	RCU_INIT_POINTER(mm->exe_file, NULL);
1302 	mmu_notifier_subscriptions_init(mm);
1303 	init_tlb_flush_pending(mm);
1304 #if defined(CONFIG_TRANSPARENT_HUGEPAGE) && !defined(CONFIG_SPLIT_PMD_PTLOCKS)
1305 	mm->pmd_huge_pte = NULL;
1306 #endif
1307 	mm_init_uprobes_state(mm);
1308 	hugetlb_count_init(mm);
1309 
1310 	if (current->mm) {
1311 		mm->flags = mmf_init_flags(current->mm->flags);
1312 		mm->def_flags = current->mm->def_flags & VM_INIT_DEF_MASK;
1313 	} else {
1314 		mm->flags = default_dump_filter;
1315 		mm->def_flags = 0;
1316 	}
1317 
1318 	if (mm_alloc_pgd(mm))
1319 		goto fail_nopgd;
1320 
1321 	if (mm_alloc_id(mm))
1322 		goto fail_noid;
1323 
1324 	if (init_new_context(p, mm))
1325 		goto fail_nocontext;
1326 
1327 	if (mm_alloc_cid(mm, p))
1328 		goto fail_cid;
1329 
1330 	if (percpu_counter_init_many(mm->rss_stat, 0, GFP_KERNEL_ACCOUNT,
1331 				     NR_MM_COUNTERS))
1332 		goto fail_pcpu;
1333 
1334 	mm->user_ns = get_user_ns(user_ns);
1335 	lru_gen_init_mm(mm);
1336 	return mm;
1337 
1338 fail_pcpu:
1339 	mm_destroy_cid(mm);
1340 fail_cid:
1341 	destroy_context(mm);
1342 fail_nocontext:
1343 	mm_free_id(mm);
1344 fail_noid:
1345 	mm_free_pgd(mm);
1346 fail_nopgd:
1347 	free_mm(mm);
1348 	return NULL;
1349 }
1350 
1351 /*
1352  * Allocate and initialize an mm_struct.
1353  */
1354 struct mm_struct *mm_alloc(void)
1355 {
1356 	struct mm_struct *mm;
1357 
1358 	mm = allocate_mm();
1359 	if (!mm)
1360 		return NULL;
1361 
1362 	memset(mm, 0, sizeof(*mm));
1363 	return mm_init(mm, current, current_user_ns());
1364 }
1365 EXPORT_SYMBOL_IF_KUNIT(mm_alloc);
1366 
1367 static inline void __mmput(struct mm_struct *mm)
1368 {
1369 	VM_BUG_ON(atomic_read(&mm->mm_users));
1370 
1371 	uprobe_clear_state(mm);
1372 	exit_aio(mm);
1373 	ksm_exit(mm);
1374 	khugepaged_exit(mm); /* must run before exit_mmap */
1375 	exit_mmap(mm);
1376 	mm_put_huge_zero_folio(mm);
1377 	set_mm_exe_file(mm, NULL);
1378 	if (!list_empty(&mm->mmlist)) {
1379 		spin_lock(&mmlist_lock);
1380 		list_del(&mm->mmlist);
1381 		spin_unlock(&mmlist_lock);
1382 	}
1383 	if (mm->binfmt)
1384 		module_put(mm->binfmt->module);
1385 	lru_gen_del_mm(mm);
1386 	mmdrop(mm);
1387 }
1388 
1389 /*
1390  * Decrement the use count and release all resources for an mm.
1391  */
1392 void mmput(struct mm_struct *mm)
1393 {
1394 	might_sleep();
1395 
1396 	if (atomic_dec_and_test(&mm->mm_users))
1397 		__mmput(mm);
1398 }
1399 EXPORT_SYMBOL_GPL(mmput);
1400 
1401 #ifdef CONFIG_MMU
1402 static void mmput_async_fn(struct work_struct *work)
1403 {
1404 	struct mm_struct *mm = container_of(work, struct mm_struct,
1405 					    async_put_work);
1406 
1407 	__mmput(mm);
1408 }
1409 
1410 void mmput_async(struct mm_struct *mm)
1411 {
1412 	if (atomic_dec_and_test(&mm->mm_users)) {
1413 		INIT_WORK(&mm->async_put_work, mmput_async_fn);
1414 		schedule_work(&mm->async_put_work);
1415 	}
1416 }
1417 EXPORT_SYMBOL_GPL(mmput_async);
1418 #endif
1419 
1420 /**
1421  * set_mm_exe_file - change a reference to the mm's executable file
1422  * @mm: The mm to change.
1423  * @new_exe_file: The new file to use.
1424  *
1425  * This changes mm's executable file (shown as symlink /proc/[pid]/exe).
1426  *
1427  * Main users are mmput() and sys_execve(). Callers prevent concurrent
1428  * invocations: in mmput() nobody alive left, in execve it happens before
1429  * the new mm is made visible to anyone.
1430  *
1431  * Can only fail if new_exe_file != NULL.
1432  */
1433 int set_mm_exe_file(struct mm_struct *mm, struct file *new_exe_file)
1434 {
1435 	struct file *old_exe_file;
1436 
1437 	/*
1438 	 * It is safe to dereference the exe_file without RCU as
1439 	 * this function is only called if nobody else can access
1440 	 * this mm -- see comment above for justification.
1441 	 */
1442 	old_exe_file = rcu_dereference_raw(mm->exe_file);
1443 
1444 	if (new_exe_file) {
1445 		/*
1446 		 * We expect the caller (i.e., sys_execve) to already denied
1447 		 * write access, so this is unlikely to fail.
1448 		 */
1449 		if (unlikely(exe_file_deny_write_access(new_exe_file)))
1450 			return -EACCES;
1451 		get_file(new_exe_file);
1452 	}
1453 	rcu_assign_pointer(mm->exe_file, new_exe_file);
1454 	if (old_exe_file) {
1455 		exe_file_allow_write_access(old_exe_file);
1456 		fput(old_exe_file);
1457 	}
1458 	return 0;
1459 }
1460 
1461 /**
1462  * replace_mm_exe_file - replace a reference to the mm's executable file
1463  * @mm: The mm to change.
1464  * @new_exe_file: The new file to use.
1465  *
1466  * This changes mm's executable file (shown as symlink /proc/[pid]/exe).
1467  *
1468  * Main user is sys_prctl(PR_SET_MM_MAP/EXE_FILE).
1469  */
1470 int replace_mm_exe_file(struct mm_struct *mm, struct file *new_exe_file)
1471 {
1472 	struct vm_area_struct *vma;
1473 	struct file *old_exe_file;
1474 	int ret = 0;
1475 
1476 	/* Forbid mm->exe_file change if old file still mapped. */
1477 	old_exe_file = get_mm_exe_file(mm);
1478 	if (old_exe_file) {
1479 		VMA_ITERATOR(vmi, mm, 0);
1480 		mmap_read_lock(mm);
1481 		for_each_vma(vmi, vma) {
1482 			if (!vma->vm_file)
1483 				continue;
1484 			if (path_equal(&vma->vm_file->f_path,
1485 				       &old_exe_file->f_path)) {
1486 				ret = -EBUSY;
1487 				break;
1488 			}
1489 		}
1490 		mmap_read_unlock(mm);
1491 		fput(old_exe_file);
1492 		if (ret)
1493 			return ret;
1494 	}
1495 
1496 	ret = exe_file_deny_write_access(new_exe_file);
1497 	if (ret)
1498 		return -EACCES;
1499 	get_file(new_exe_file);
1500 
1501 	/* set the new file */
1502 	mmap_write_lock(mm);
1503 	old_exe_file = rcu_dereference_raw(mm->exe_file);
1504 	rcu_assign_pointer(mm->exe_file, new_exe_file);
1505 	mmap_write_unlock(mm);
1506 
1507 	if (old_exe_file) {
1508 		exe_file_allow_write_access(old_exe_file);
1509 		fput(old_exe_file);
1510 	}
1511 	return 0;
1512 }
1513 
1514 /**
1515  * get_mm_exe_file - acquire a reference to the mm's executable file
1516  * @mm: The mm of interest.
1517  *
1518  * Returns %NULL if mm has no associated executable file.
1519  * User must release file via fput().
1520  */
1521 struct file *get_mm_exe_file(struct mm_struct *mm)
1522 {
1523 	struct file *exe_file;
1524 
1525 	rcu_read_lock();
1526 	exe_file = get_file_rcu(&mm->exe_file);
1527 	rcu_read_unlock();
1528 	return exe_file;
1529 }
1530 
1531 /**
1532  * get_task_exe_file - acquire a reference to the task's executable file
1533  * @task: The task.
1534  *
1535  * Returns %NULL if task's mm (if any) has no associated executable file or
1536  * this is a kernel thread with borrowed mm (see the comment above get_task_mm).
1537  * User must release file via fput().
1538  */
1539 struct file *get_task_exe_file(struct task_struct *task)
1540 {
1541 	struct file *exe_file = NULL;
1542 	struct mm_struct *mm;
1543 
1544 	if (task->flags & PF_KTHREAD)
1545 		return NULL;
1546 
1547 	task_lock(task);
1548 	mm = task->mm;
1549 	if (mm)
1550 		exe_file = get_mm_exe_file(mm);
1551 	task_unlock(task);
1552 	return exe_file;
1553 }
1554 
1555 /**
1556  * get_task_mm - acquire a reference to the task's mm
1557  * @task: The task.
1558  *
1559  * Returns %NULL if the task has no mm.  Checks PF_KTHREAD (meaning
1560  * this kernel workthread has transiently adopted a user mm with use_mm,
1561  * to do its AIO) is not set and if so returns a reference to it, after
1562  * bumping up the use count.  User must release the mm via mmput()
1563  * after use.  Typically used by /proc and ptrace.
1564  */
1565 struct mm_struct *get_task_mm(struct task_struct *task)
1566 {
1567 	struct mm_struct *mm;
1568 
1569 	if (task->flags & PF_KTHREAD)
1570 		return NULL;
1571 
1572 	task_lock(task);
1573 	mm = task->mm;
1574 	if (mm)
1575 		mmget(mm);
1576 	task_unlock(task);
1577 	return mm;
1578 }
1579 EXPORT_SYMBOL_GPL(get_task_mm);
1580 
1581 struct mm_struct *mm_access(struct task_struct *task, unsigned int mode)
1582 {
1583 	struct mm_struct *mm;
1584 	int err;
1585 
1586 	err =  down_read_killable(&task->signal->exec_update_lock);
1587 	if (err)
1588 		return ERR_PTR(err);
1589 
1590 	mm = get_task_mm(task);
1591 	if (!mm) {
1592 		mm = ERR_PTR(-ESRCH);
1593 	} else if (mm != current->mm && !ptrace_may_access(task, mode)) {
1594 		mmput(mm);
1595 		mm = ERR_PTR(-EACCES);
1596 	}
1597 	up_read(&task->signal->exec_update_lock);
1598 
1599 	return mm;
1600 }
1601 
1602 static void complete_vfork_done(struct task_struct *tsk)
1603 {
1604 	struct completion *vfork;
1605 
1606 	task_lock(tsk);
1607 	vfork = tsk->vfork_done;
1608 	if (likely(vfork)) {
1609 		tsk->vfork_done = NULL;
1610 		complete(vfork);
1611 	}
1612 	task_unlock(tsk);
1613 }
1614 
1615 static int wait_for_vfork_done(struct task_struct *child,
1616 				struct completion *vfork)
1617 {
1618 	unsigned int state = TASK_KILLABLE|TASK_FREEZABLE;
1619 	int killed;
1620 
1621 	cgroup_enter_frozen();
1622 	killed = wait_for_completion_state(vfork, state);
1623 	cgroup_leave_frozen(false);
1624 
1625 	if (killed) {
1626 		task_lock(child);
1627 		child->vfork_done = NULL;
1628 		task_unlock(child);
1629 	}
1630 
1631 	put_task_struct(child);
1632 	return killed;
1633 }
1634 
1635 /* Please note the differences between mmput and mm_release.
1636  * mmput is called whenever we stop holding onto a mm_struct,
1637  * error success whatever.
1638  *
1639  * mm_release is called after a mm_struct has been removed
1640  * from the current process.
1641  *
1642  * This difference is important for error handling, when we
1643  * only half set up a mm_struct for a new process and need to restore
1644  * the old one.  Because we mmput the new mm_struct before
1645  * restoring the old one. . .
1646  * Eric Biederman 10 January 1998
1647  */
1648 static void mm_release(struct task_struct *tsk, struct mm_struct *mm)
1649 {
1650 	uprobe_free_utask(tsk);
1651 
1652 	/* Get rid of any cached register state */
1653 	deactivate_mm(tsk, mm);
1654 
1655 	/*
1656 	 * Signal userspace if we're not exiting with a core dump
1657 	 * because we want to leave the value intact for debugging
1658 	 * purposes.
1659 	 */
1660 	if (tsk->clear_child_tid) {
1661 		if (atomic_read(&mm->mm_users) > 1) {
1662 			/*
1663 			 * We don't check the error code - if userspace has
1664 			 * not set up a proper pointer then tough luck.
1665 			 */
1666 			put_user(0, tsk->clear_child_tid);
1667 			do_futex(tsk->clear_child_tid, FUTEX_WAKE,
1668 					1, NULL, NULL, 0, 0);
1669 		}
1670 		tsk->clear_child_tid = NULL;
1671 	}
1672 
1673 	/*
1674 	 * All done, finally we can wake up parent and return this mm to him.
1675 	 * Also kthread_stop() uses this completion for synchronization.
1676 	 */
1677 	if (tsk->vfork_done)
1678 		complete_vfork_done(tsk);
1679 }
1680 
1681 void exit_mm_release(struct task_struct *tsk, struct mm_struct *mm)
1682 {
1683 	futex_exit_release(tsk);
1684 	mm_release(tsk, mm);
1685 }
1686 
1687 void exec_mm_release(struct task_struct *tsk, struct mm_struct *mm)
1688 {
1689 	futex_exec_release(tsk);
1690 	mm_release(tsk, mm);
1691 }
1692 
1693 /**
1694  * dup_mm() - duplicates an existing mm structure
1695  * @tsk: the task_struct with which the new mm will be associated.
1696  * @oldmm: the mm to duplicate.
1697  *
1698  * Allocates a new mm structure and duplicates the provided @oldmm structure
1699  * content into it.
1700  *
1701  * Return: the duplicated mm or NULL on failure.
1702  */
1703 static struct mm_struct *dup_mm(struct task_struct *tsk,
1704 				struct mm_struct *oldmm)
1705 {
1706 	struct mm_struct *mm;
1707 	int err;
1708 
1709 	mm = allocate_mm();
1710 	if (!mm)
1711 		goto fail_nomem;
1712 
1713 	memcpy(mm, oldmm, sizeof(*mm));
1714 
1715 	if (!mm_init(mm, tsk, mm->user_ns))
1716 		goto fail_nomem;
1717 
1718 	uprobe_start_dup_mmap();
1719 	err = dup_mmap(mm, oldmm);
1720 	if (err)
1721 		goto free_pt;
1722 	uprobe_end_dup_mmap();
1723 
1724 	mm->hiwater_rss = get_mm_rss(mm);
1725 	mm->hiwater_vm = mm->total_vm;
1726 
1727 	if (mm->binfmt && !try_module_get(mm->binfmt->module))
1728 		goto free_pt;
1729 
1730 	return mm;
1731 
1732 free_pt:
1733 	/* don't put binfmt in mmput, we haven't got module yet */
1734 	mm->binfmt = NULL;
1735 	mm_init_owner(mm, NULL);
1736 	mmput(mm);
1737 	if (err)
1738 		uprobe_end_dup_mmap();
1739 
1740 fail_nomem:
1741 	return NULL;
1742 }
1743 
1744 static int copy_mm(unsigned long clone_flags, struct task_struct *tsk)
1745 {
1746 	struct mm_struct *mm, *oldmm;
1747 
1748 	tsk->min_flt = tsk->maj_flt = 0;
1749 	tsk->nvcsw = tsk->nivcsw = 0;
1750 #ifdef CONFIG_DETECT_HUNG_TASK
1751 	tsk->last_switch_count = tsk->nvcsw + tsk->nivcsw;
1752 	tsk->last_switch_time = 0;
1753 #endif
1754 
1755 	tsk->mm = NULL;
1756 	tsk->active_mm = NULL;
1757 
1758 	/*
1759 	 * Are we cloning a kernel thread?
1760 	 *
1761 	 * We need to steal a active VM for that..
1762 	 */
1763 	oldmm = current->mm;
1764 	if (!oldmm)
1765 		return 0;
1766 
1767 	if (clone_flags & CLONE_VM) {
1768 		mmget(oldmm);
1769 		mm = oldmm;
1770 	} else {
1771 		mm = dup_mm(tsk, current->mm);
1772 		if (!mm)
1773 			return -ENOMEM;
1774 	}
1775 
1776 	tsk->mm = mm;
1777 	tsk->active_mm = mm;
1778 	sched_mm_cid_fork(tsk);
1779 	return 0;
1780 }
1781 
1782 static int copy_fs(unsigned long clone_flags, struct task_struct *tsk)
1783 {
1784 	struct fs_struct *fs = current->fs;
1785 	if (clone_flags & CLONE_FS) {
1786 		/* tsk->fs is already what we want */
1787 		spin_lock(&fs->lock);
1788 		/* "users" and "in_exec" locked for check_unsafe_exec() */
1789 		if (fs->in_exec) {
1790 			spin_unlock(&fs->lock);
1791 			return -EAGAIN;
1792 		}
1793 		fs->users++;
1794 		spin_unlock(&fs->lock);
1795 		return 0;
1796 	}
1797 	tsk->fs = copy_fs_struct(fs);
1798 	if (!tsk->fs)
1799 		return -ENOMEM;
1800 	return 0;
1801 }
1802 
1803 static int copy_files(unsigned long clone_flags, struct task_struct *tsk,
1804 		      int no_files)
1805 {
1806 	struct files_struct *oldf, *newf;
1807 
1808 	/*
1809 	 * A background process may not have any files ...
1810 	 */
1811 	oldf = current->files;
1812 	if (!oldf)
1813 		return 0;
1814 
1815 	if (no_files) {
1816 		tsk->files = NULL;
1817 		return 0;
1818 	}
1819 
1820 	if (clone_flags & CLONE_FILES) {
1821 		atomic_inc(&oldf->count);
1822 		return 0;
1823 	}
1824 
1825 	newf = dup_fd(oldf, NULL);
1826 	if (IS_ERR(newf))
1827 		return PTR_ERR(newf);
1828 
1829 	tsk->files = newf;
1830 	return 0;
1831 }
1832 
1833 static int copy_sighand(unsigned long clone_flags, struct task_struct *tsk)
1834 {
1835 	struct sighand_struct *sig;
1836 
1837 	if (clone_flags & CLONE_SIGHAND) {
1838 		refcount_inc(&current->sighand->count);
1839 		return 0;
1840 	}
1841 	sig = kmem_cache_alloc(sighand_cachep, GFP_KERNEL);
1842 	RCU_INIT_POINTER(tsk->sighand, sig);
1843 	if (!sig)
1844 		return -ENOMEM;
1845 
1846 	refcount_set(&sig->count, 1);
1847 	spin_lock_irq(&current->sighand->siglock);
1848 	memcpy(sig->action, current->sighand->action, sizeof(sig->action));
1849 	spin_unlock_irq(&current->sighand->siglock);
1850 
1851 	/* Reset all signal handler not set to SIG_IGN to SIG_DFL. */
1852 	if (clone_flags & CLONE_CLEAR_SIGHAND)
1853 		flush_signal_handlers(tsk, 0);
1854 
1855 	return 0;
1856 }
1857 
1858 void __cleanup_sighand(struct sighand_struct *sighand)
1859 {
1860 	if (refcount_dec_and_test(&sighand->count)) {
1861 		signalfd_cleanup(sighand);
1862 		/*
1863 		 * sighand_cachep is SLAB_TYPESAFE_BY_RCU so we can free it
1864 		 * without an RCU grace period, see __lock_task_sighand().
1865 		 */
1866 		kmem_cache_free(sighand_cachep, sighand);
1867 	}
1868 }
1869 
1870 /*
1871  * Initialize POSIX timer handling for a thread group.
1872  */
1873 static void posix_cpu_timers_init_group(struct signal_struct *sig)
1874 {
1875 	struct posix_cputimers *pct = &sig->posix_cputimers;
1876 	unsigned long cpu_limit;
1877 
1878 	cpu_limit = READ_ONCE(sig->rlim[RLIMIT_CPU].rlim_cur);
1879 	posix_cputimers_group_init(pct, cpu_limit);
1880 }
1881 
1882 static int copy_signal(unsigned long clone_flags, struct task_struct *tsk)
1883 {
1884 	struct signal_struct *sig;
1885 
1886 	if (clone_flags & CLONE_THREAD)
1887 		return 0;
1888 
1889 	sig = kmem_cache_zalloc(signal_cachep, GFP_KERNEL);
1890 	tsk->signal = sig;
1891 	if (!sig)
1892 		return -ENOMEM;
1893 
1894 	sig->nr_threads = 1;
1895 	sig->quick_threads = 1;
1896 	atomic_set(&sig->live, 1);
1897 	refcount_set(&sig->sigcnt, 1);
1898 
1899 	/* list_add(thread_node, thread_head) without INIT_LIST_HEAD() */
1900 	sig->thread_head = (struct list_head)LIST_HEAD_INIT(tsk->thread_node);
1901 	tsk->thread_node = (struct list_head)LIST_HEAD_INIT(sig->thread_head);
1902 
1903 	init_waitqueue_head(&sig->wait_chldexit);
1904 	sig->curr_target = tsk;
1905 	init_sigpending(&sig->shared_pending);
1906 	INIT_HLIST_HEAD(&sig->multiprocess);
1907 	seqlock_init(&sig->stats_lock);
1908 	prev_cputime_init(&sig->prev_cputime);
1909 
1910 #ifdef CONFIG_POSIX_TIMERS
1911 	INIT_HLIST_HEAD(&sig->posix_timers);
1912 	INIT_HLIST_HEAD(&sig->ignored_posix_timers);
1913 	hrtimer_init(&sig->real_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
1914 	sig->real_timer.function = it_real_fn;
1915 #endif
1916 
1917 	task_lock(current->group_leader);
1918 	memcpy(sig->rlim, current->signal->rlim, sizeof sig->rlim);
1919 	task_unlock(current->group_leader);
1920 
1921 	posix_cpu_timers_init_group(sig);
1922 
1923 	tty_audit_fork(sig);
1924 	sched_autogroup_fork(sig);
1925 
1926 	sig->oom_score_adj = current->signal->oom_score_adj;
1927 	sig->oom_score_adj_min = current->signal->oom_score_adj_min;
1928 
1929 	mutex_init(&sig->cred_guard_mutex);
1930 	init_rwsem(&sig->exec_update_lock);
1931 
1932 	return 0;
1933 }
1934 
1935 static void copy_seccomp(struct task_struct *p)
1936 {
1937 #ifdef CONFIG_SECCOMP
1938 	/*
1939 	 * Must be called with sighand->lock held, which is common to
1940 	 * all threads in the group. Holding cred_guard_mutex is not
1941 	 * needed because this new task is not yet running and cannot
1942 	 * be racing exec.
1943 	 */
1944 	assert_spin_locked(&current->sighand->siglock);
1945 
1946 	/* Ref-count the new filter user, and assign it. */
1947 	get_seccomp_filter(current);
1948 	p->seccomp = current->seccomp;
1949 
1950 	/*
1951 	 * Explicitly enable no_new_privs here in case it got set
1952 	 * between the task_struct being duplicated and holding the
1953 	 * sighand lock. The seccomp state and nnp must be in sync.
1954 	 */
1955 	if (task_no_new_privs(current))
1956 		task_set_no_new_privs(p);
1957 
1958 	/*
1959 	 * If the parent gained a seccomp mode after copying thread
1960 	 * flags and between before we held the sighand lock, we have
1961 	 * to manually enable the seccomp thread flag here.
1962 	 */
1963 	if (p->seccomp.mode != SECCOMP_MODE_DISABLED)
1964 		set_task_syscall_work(p, SECCOMP);
1965 #endif
1966 }
1967 
1968 SYSCALL_DEFINE1(set_tid_address, int __user *, tidptr)
1969 {
1970 	current->clear_child_tid = tidptr;
1971 
1972 	return task_pid_vnr(current);
1973 }
1974 
1975 static void rt_mutex_init_task(struct task_struct *p)
1976 {
1977 	raw_spin_lock_init(&p->pi_lock);
1978 #ifdef CONFIG_RT_MUTEXES
1979 	p->pi_waiters = RB_ROOT_CACHED;
1980 	p->pi_top_task = NULL;
1981 	p->pi_blocked_on = NULL;
1982 #endif
1983 }
1984 
1985 static inline void init_task_pid_links(struct task_struct *task)
1986 {
1987 	enum pid_type type;
1988 
1989 	for (type = PIDTYPE_PID; type < PIDTYPE_MAX; ++type)
1990 		INIT_HLIST_NODE(&task->pid_links[type]);
1991 }
1992 
1993 static inline void
1994 init_task_pid(struct task_struct *task, enum pid_type type, struct pid *pid)
1995 {
1996 	if (type == PIDTYPE_PID)
1997 		task->thread_pid = pid;
1998 	else
1999 		task->signal->pids[type] = pid;
2000 }
2001 
2002 static inline void rcu_copy_process(struct task_struct *p)
2003 {
2004 #ifdef CONFIG_PREEMPT_RCU
2005 	p->rcu_read_lock_nesting = 0;
2006 	p->rcu_read_unlock_special.s = 0;
2007 	p->rcu_blocked_node = NULL;
2008 	INIT_LIST_HEAD(&p->rcu_node_entry);
2009 #endif /* #ifdef CONFIG_PREEMPT_RCU */
2010 #ifdef CONFIG_TASKS_RCU
2011 	p->rcu_tasks_holdout = false;
2012 	INIT_LIST_HEAD(&p->rcu_tasks_holdout_list);
2013 	p->rcu_tasks_idle_cpu = -1;
2014 	INIT_LIST_HEAD(&p->rcu_tasks_exit_list);
2015 #endif /* #ifdef CONFIG_TASKS_RCU */
2016 #ifdef CONFIG_TASKS_TRACE_RCU
2017 	p->trc_reader_nesting = 0;
2018 	p->trc_reader_special.s = 0;
2019 	INIT_LIST_HEAD(&p->trc_holdout_list);
2020 	INIT_LIST_HEAD(&p->trc_blkd_node);
2021 #endif /* #ifdef CONFIG_TASKS_TRACE_RCU */
2022 }
2023 
2024 /**
2025  * __pidfd_prepare - allocate a new pidfd_file and reserve a pidfd
2026  * @pid:   the struct pid for which to create a pidfd
2027  * @flags: flags of the new @pidfd
2028  * @ret: Where to return the file for the pidfd.
2029  *
2030  * Allocate a new file that stashes @pid and reserve a new pidfd number in the
2031  * caller's file descriptor table. The pidfd is reserved but not installed yet.
2032  *
2033  * The helper doesn't perform checks on @pid which makes it useful for pidfds
2034  * created via CLONE_PIDFD where @pid has no task attached when the pidfd and
2035  * pidfd file are prepared.
2036  *
2037  * If this function returns successfully the caller is responsible to either
2038  * call fd_install() passing the returned pidfd and pidfd file as arguments in
2039  * order to install the pidfd into its file descriptor table or they must use
2040  * put_unused_fd() and fput() on the returned pidfd and pidfd file
2041  * respectively.
2042  *
2043  * This function is useful when a pidfd must already be reserved but there
2044  * might still be points of failure afterwards and the caller wants to ensure
2045  * that no pidfd is leaked into its file descriptor table.
2046  *
2047  * Return: On success, a reserved pidfd is returned from the function and a new
2048  *         pidfd file is returned in the last argument to the function. On
2049  *         error, a negative error code is returned from the function and the
2050  *         last argument remains unchanged.
2051  */
2052 static int __pidfd_prepare(struct pid *pid, unsigned int flags, struct file **ret)
2053 {
2054 	int pidfd;
2055 	struct file *pidfd_file;
2056 
2057 	pidfd = get_unused_fd_flags(O_CLOEXEC);
2058 	if (pidfd < 0)
2059 		return pidfd;
2060 
2061 	pidfd_file = pidfs_alloc_file(pid, flags | O_RDWR);
2062 	if (IS_ERR(pidfd_file)) {
2063 		put_unused_fd(pidfd);
2064 		return PTR_ERR(pidfd_file);
2065 	}
2066 	/*
2067 	 * anon_inode_getfile() ignores everything outside of the
2068 	 * O_ACCMODE | O_NONBLOCK mask, set PIDFD_THREAD manually.
2069 	 */
2070 	pidfd_file->f_flags |= (flags & PIDFD_THREAD);
2071 	*ret = pidfd_file;
2072 	return pidfd;
2073 }
2074 
2075 /**
2076  * pidfd_prepare - allocate a new pidfd_file and reserve a pidfd
2077  * @pid:   the struct pid for which to create a pidfd
2078  * @flags: flags of the new @pidfd
2079  * @ret: Where to return the pidfd.
2080  *
2081  * Allocate a new file that stashes @pid and reserve a new pidfd number in the
2082  * caller's file descriptor table. The pidfd is reserved but not installed yet.
2083  *
2084  * The helper verifies that @pid is still in use, without PIDFD_THREAD the
2085  * task identified by @pid must be a thread-group leader.
2086  *
2087  * If this function returns successfully the caller is responsible to either
2088  * call fd_install() passing the returned pidfd and pidfd file as arguments in
2089  * order to install the pidfd into its file descriptor table or they must use
2090  * put_unused_fd() and fput() on the returned pidfd and pidfd file
2091  * respectively.
2092  *
2093  * This function is useful when a pidfd must already be reserved but there
2094  * might still be points of failure afterwards and the caller wants to ensure
2095  * that no pidfd is leaked into its file descriptor table.
2096  *
2097  * Return: On success, a reserved pidfd is returned from the function and a new
2098  *         pidfd file is returned in the last argument to the function. On
2099  *         error, a negative error code is returned from the function and the
2100  *         last argument remains unchanged.
2101  */
2102 int pidfd_prepare(struct pid *pid, unsigned int flags, struct file **ret)
2103 {
2104 	bool thread = flags & PIDFD_THREAD;
2105 
2106 	if (!pid || !pid_has_task(pid, thread ? PIDTYPE_PID : PIDTYPE_TGID))
2107 		return -EINVAL;
2108 
2109 	return __pidfd_prepare(pid, flags, ret);
2110 }
2111 
2112 static void __delayed_free_task(struct rcu_head *rhp)
2113 {
2114 	struct task_struct *tsk = container_of(rhp, struct task_struct, rcu);
2115 
2116 	free_task(tsk);
2117 }
2118 
2119 static __always_inline void delayed_free_task(struct task_struct *tsk)
2120 {
2121 	if (IS_ENABLED(CONFIG_MEMCG))
2122 		call_rcu(&tsk->rcu, __delayed_free_task);
2123 	else
2124 		free_task(tsk);
2125 }
2126 
2127 static void copy_oom_score_adj(u64 clone_flags, struct task_struct *tsk)
2128 {
2129 	/* Skip if kernel thread */
2130 	if (!tsk->mm)
2131 		return;
2132 
2133 	/* Skip if spawning a thread or using vfork */
2134 	if ((clone_flags & (CLONE_VM | CLONE_THREAD | CLONE_VFORK)) != CLONE_VM)
2135 		return;
2136 
2137 	/* We need to synchronize with __set_oom_adj */
2138 	mutex_lock(&oom_adj_mutex);
2139 	set_bit(MMF_MULTIPROCESS, &tsk->mm->flags);
2140 	/* Update the values in case they were changed after copy_signal */
2141 	tsk->signal->oom_score_adj = current->signal->oom_score_adj;
2142 	tsk->signal->oom_score_adj_min = current->signal->oom_score_adj_min;
2143 	mutex_unlock(&oom_adj_mutex);
2144 }
2145 
2146 #ifdef CONFIG_RV
2147 static void rv_task_fork(struct task_struct *p)
2148 {
2149 	int i;
2150 
2151 	for (i = 0; i < RV_PER_TASK_MONITORS; i++)
2152 		p->rv[i].da_mon.monitoring = false;
2153 }
2154 #else
2155 #define rv_task_fork(p) do {} while (0)
2156 #endif
2157 
2158 /*
2159  * This creates a new process as a copy of the old one,
2160  * but does not actually start it yet.
2161  *
2162  * It copies the registers, and all the appropriate
2163  * parts of the process environment (as per the clone
2164  * flags). The actual kick-off is left to the caller.
2165  */
2166 __latent_entropy struct task_struct *copy_process(
2167 					struct pid *pid,
2168 					int trace,
2169 					int node,
2170 					struct kernel_clone_args *args)
2171 {
2172 	int pidfd = -1, retval;
2173 	struct task_struct *p;
2174 	struct multiprocess_signals delayed;
2175 	struct file *pidfile = NULL;
2176 	const u64 clone_flags = args->flags;
2177 	struct nsproxy *nsp = current->nsproxy;
2178 
2179 	/*
2180 	 * Don't allow sharing the root directory with processes in a different
2181 	 * namespace
2182 	 */
2183 	if ((clone_flags & (CLONE_NEWNS|CLONE_FS)) == (CLONE_NEWNS|CLONE_FS))
2184 		return ERR_PTR(-EINVAL);
2185 
2186 	if ((clone_flags & (CLONE_NEWUSER|CLONE_FS)) == (CLONE_NEWUSER|CLONE_FS))
2187 		return ERR_PTR(-EINVAL);
2188 
2189 	/*
2190 	 * Thread groups must share signals as well, and detached threads
2191 	 * can only be started up within the thread group.
2192 	 */
2193 	if ((clone_flags & CLONE_THREAD) && !(clone_flags & CLONE_SIGHAND))
2194 		return ERR_PTR(-EINVAL);
2195 
2196 	/*
2197 	 * Shared signal handlers imply shared VM. By way of the above,
2198 	 * thread groups also imply shared VM. Blocking this case allows
2199 	 * for various simplifications in other code.
2200 	 */
2201 	if ((clone_flags & CLONE_SIGHAND) && !(clone_flags & CLONE_VM))
2202 		return ERR_PTR(-EINVAL);
2203 
2204 	/*
2205 	 * Siblings of global init remain as zombies on exit since they are
2206 	 * not reaped by their parent (swapper). To solve this and to avoid
2207 	 * multi-rooted process trees, prevent global and container-inits
2208 	 * from creating siblings.
2209 	 */
2210 	if ((clone_flags & CLONE_PARENT) &&
2211 				current->signal->flags & SIGNAL_UNKILLABLE)
2212 		return ERR_PTR(-EINVAL);
2213 
2214 	/*
2215 	 * If the new process will be in a different pid or user namespace
2216 	 * do not allow it to share a thread group with the forking task.
2217 	 */
2218 	if (clone_flags & CLONE_THREAD) {
2219 		if ((clone_flags & (CLONE_NEWUSER | CLONE_NEWPID)) ||
2220 		    (task_active_pid_ns(current) != nsp->pid_ns_for_children))
2221 			return ERR_PTR(-EINVAL);
2222 	}
2223 
2224 	if (clone_flags & CLONE_PIDFD) {
2225 		/*
2226 		 * - CLONE_DETACHED is blocked so that we can potentially
2227 		 *   reuse it later for CLONE_PIDFD.
2228 		 */
2229 		if (clone_flags & CLONE_DETACHED)
2230 			return ERR_PTR(-EINVAL);
2231 	}
2232 
2233 	/*
2234 	 * Force any signals received before this point to be delivered
2235 	 * before the fork happens.  Collect up signals sent to multiple
2236 	 * processes that happen during the fork and delay them so that
2237 	 * they appear to happen after the fork.
2238 	 */
2239 	sigemptyset(&delayed.signal);
2240 	INIT_HLIST_NODE(&delayed.node);
2241 
2242 	spin_lock_irq(&current->sighand->siglock);
2243 	if (!(clone_flags & CLONE_THREAD))
2244 		hlist_add_head(&delayed.node, &current->signal->multiprocess);
2245 	recalc_sigpending();
2246 	spin_unlock_irq(&current->sighand->siglock);
2247 	retval = -ERESTARTNOINTR;
2248 	if (task_sigpending(current))
2249 		goto fork_out;
2250 
2251 	retval = -ENOMEM;
2252 	p = dup_task_struct(current, node);
2253 	if (!p)
2254 		goto fork_out;
2255 	p->flags &= ~PF_KTHREAD;
2256 	if (args->kthread)
2257 		p->flags |= PF_KTHREAD;
2258 	if (args->user_worker) {
2259 		/*
2260 		 * Mark us a user worker, and block any signal that isn't
2261 		 * fatal or STOP
2262 		 */
2263 		p->flags |= PF_USER_WORKER;
2264 		siginitsetinv(&p->blocked, sigmask(SIGKILL)|sigmask(SIGSTOP));
2265 	}
2266 	if (args->io_thread)
2267 		p->flags |= PF_IO_WORKER;
2268 
2269 	if (args->name)
2270 		strscpy_pad(p->comm, args->name, sizeof(p->comm));
2271 
2272 	p->set_child_tid = (clone_flags & CLONE_CHILD_SETTID) ? args->child_tid : NULL;
2273 	/*
2274 	 * Clear TID on mm_release()?
2275 	 */
2276 	p->clear_child_tid = (clone_flags & CLONE_CHILD_CLEARTID) ? args->child_tid : NULL;
2277 
2278 	ftrace_graph_init_task(p);
2279 
2280 	rt_mutex_init_task(p);
2281 
2282 	lockdep_assert_irqs_enabled();
2283 #ifdef CONFIG_PROVE_LOCKING
2284 	DEBUG_LOCKS_WARN_ON(!p->softirqs_enabled);
2285 #endif
2286 	retval = copy_creds(p, clone_flags);
2287 	if (retval < 0)
2288 		goto bad_fork_free;
2289 
2290 	retval = -EAGAIN;
2291 	if (is_rlimit_overlimit(task_ucounts(p), UCOUNT_RLIMIT_NPROC, rlimit(RLIMIT_NPROC))) {
2292 		if (p->real_cred->user != INIT_USER &&
2293 		    !capable(CAP_SYS_RESOURCE) && !capable(CAP_SYS_ADMIN))
2294 			goto bad_fork_cleanup_count;
2295 	}
2296 	current->flags &= ~PF_NPROC_EXCEEDED;
2297 
2298 	/*
2299 	 * If multiple threads are within copy_process(), then this check
2300 	 * triggers too late. This doesn't hurt, the check is only there
2301 	 * to stop root fork bombs.
2302 	 */
2303 	retval = -EAGAIN;
2304 	if (data_race(nr_threads >= max_threads))
2305 		goto bad_fork_cleanup_count;
2306 
2307 	delayacct_tsk_init(p);	/* Must remain after dup_task_struct() */
2308 	p->flags &= ~(PF_SUPERPRIV | PF_WQ_WORKER | PF_IDLE | PF_NO_SETAFFINITY);
2309 	p->flags |= PF_FORKNOEXEC;
2310 	INIT_LIST_HEAD(&p->children);
2311 	INIT_LIST_HEAD(&p->sibling);
2312 	rcu_copy_process(p);
2313 	p->vfork_done = NULL;
2314 	spin_lock_init(&p->alloc_lock);
2315 
2316 	init_sigpending(&p->pending);
2317 
2318 	p->utime = p->stime = p->gtime = 0;
2319 #ifdef CONFIG_ARCH_HAS_SCALED_CPUTIME
2320 	p->utimescaled = p->stimescaled = 0;
2321 #endif
2322 	prev_cputime_init(&p->prev_cputime);
2323 
2324 #ifdef CONFIG_VIRT_CPU_ACCOUNTING_GEN
2325 	seqcount_init(&p->vtime.seqcount);
2326 	p->vtime.starttime = 0;
2327 	p->vtime.state = VTIME_INACTIVE;
2328 #endif
2329 
2330 #ifdef CONFIG_IO_URING
2331 	p->io_uring = NULL;
2332 #endif
2333 
2334 	p->default_timer_slack_ns = current->timer_slack_ns;
2335 
2336 #ifdef CONFIG_PSI
2337 	p->psi_flags = 0;
2338 #endif
2339 
2340 	task_io_accounting_init(&p->ioac);
2341 	acct_clear_integrals(p);
2342 
2343 	posix_cputimers_init(&p->posix_cputimers);
2344 	tick_dep_init_task(p);
2345 
2346 	p->io_context = NULL;
2347 	audit_set_context(p, NULL);
2348 	cgroup_fork(p);
2349 	if (args->kthread) {
2350 		if (!set_kthread_struct(p))
2351 			goto bad_fork_cleanup_delayacct;
2352 	}
2353 #ifdef CONFIG_NUMA
2354 	p->mempolicy = mpol_dup(p->mempolicy);
2355 	if (IS_ERR(p->mempolicy)) {
2356 		retval = PTR_ERR(p->mempolicy);
2357 		p->mempolicy = NULL;
2358 		goto bad_fork_cleanup_delayacct;
2359 	}
2360 #endif
2361 #ifdef CONFIG_CPUSETS
2362 	p->cpuset_mem_spread_rotor = NUMA_NO_NODE;
2363 	seqcount_spinlock_init(&p->mems_allowed_seq, &p->alloc_lock);
2364 #endif
2365 #ifdef CONFIG_TRACE_IRQFLAGS
2366 	memset(&p->irqtrace, 0, sizeof(p->irqtrace));
2367 	p->irqtrace.hardirq_disable_ip	= _THIS_IP_;
2368 	p->irqtrace.softirq_enable_ip	= _THIS_IP_;
2369 	p->softirqs_enabled		= 1;
2370 	p->softirq_context		= 0;
2371 #endif
2372 
2373 	p->pagefault_disabled = 0;
2374 
2375 #ifdef CONFIG_LOCKDEP
2376 	lockdep_init_task(p);
2377 #endif
2378 
2379 #ifdef CONFIG_DEBUG_MUTEXES
2380 	p->blocked_on = NULL; /* not blocked yet */
2381 #endif
2382 #ifdef CONFIG_BCACHE
2383 	p->sequential_io	= 0;
2384 	p->sequential_io_avg	= 0;
2385 #endif
2386 #ifdef CONFIG_BPF_SYSCALL
2387 	RCU_INIT_POINTER(p->bpf_storage, NULL);
2388 	p->bpf_ctx = NULL;
2389 #endif
2390 
2391 	/* Perform scheduler related setup. Assign this task to a CPU. */
2392 	retval = sched_fork(clone_flags, p);
2393 	if (retval)
2394 		goto bad_fork_cleanup_policy;
2395 
2396 	retval = perf_event_init_task(p, clone_flags);
2397 	if (retval)
2398 		goto bad_fork_sched_cancel_fork;
2399 	retval = audit_alloc(p);
2400 	if (retval)
2401 		goto bad_fork_cleanup_perf;
2402 	/* copy all the process information */
2403 	shm_init_task(p);
2404 	retval = security_task_alloc(p, clone_flags);
2405 	if (retval)
2406 		goto bad_fork_cleanup_audit;
2407 	retval = copy_semundo(clone_flags, p);
2408 	if (retval)
2409 		goto bad_fork_cleanup_security;
2410 	retval = copy_files(clone_flags, p, args->no_files);
2411 	if (retval)
2412 		goto bad_fork_cleanup_semundo;
2413 	retval = copy_fs(clone_flags, p);
2414 	if (retval)
2415 		goto bad_fork_cleanup_files;
2416 	retval = copy_sighand(clone_flags, p);
2417 	if (retval)
2418 		goto bad_fork_cleanup_fs;
2419 	retval = copy_signal(clone_flags, p);
2420 	if (retval)
2421 		goto bad_fork_cleanup_sighand;
2422 	retval = copy_mm(clone_flags, p);
2423 	if (retval)
2424 		goto bad_fork_cleanup_signal;
2425 	retval = copy_namespaces(clone_flags, p);
2426 	if (retval)
2427 		goto bad_fork_cleanup_mm;
2428 	retval = copy_io(clone_flags, p);
2429 	if (retval)
2430 		goto bad_fork_cleanup_namespaces;
2431 	retval = copy_thread(p, args);
2432 	if (retval)
2433 		goto bad_fork_cleanup_io;
2434 
2435 	stackleak_task_init(p);
2436 
2437 	if (pid != &init_struct_pid) {
2438 		pid = alloc_pid(p->nsproxy->pid_ns_for_children, args->set_tid,
2439 				args->set_tid_size);
2440 		if (IS_ERR(pid)) {
2441 			retval = PTR_ERR(pid);
2442 			goto bad_fork_cleanup_thread;
2443 		}
2444 	}
2445 
2446 	/*
2447 	 * This has to happen after we've potentially unshared the file
2448 	 * descriptor table (so that the pidfd doesn't leak into the child
2449 	 * if the fd table isn't shared).
2450 	 */
2451 	if (clone_flags & CLONE_PIDFD) {
2452 		int flags = (clone_flags & CLONE_THREAD) ? PIDFD_THREAD : 0;
2453 
2454 		/* Note that no task has been attached to @pid yet. */
2455 		retval = __pidfd_prepare(pid, flags, &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