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