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