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