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