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