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