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