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