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