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