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