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