• 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 		__mmput(mm);
1202 }
1203 EXPORT_SYMBOL_GPL(mmput);
1204 
1205 #ifdef CONFIG_MMU
mmput_async_fn(struct work_struct * work)1206 static void mmput_async_fn(struct work_struct *work)
1207 {
1208 	struct mm_struct *mm = container_of(work, struct mm_struct,
1209 					    async_put_work);
1210 
1211 	__mmput(mm);
1212 }
1213 
mmput_async(struct mm_struct * mm)1214 void mmput_async(struct mm_struct *mm)
1215 {
1216 	if (atomic_dec_and_test(&mm->mm_users)) {
1217 		INIT_WORK(&mm->async_put_work, mmput_async_fn);
1218 		schedule_work(&mm->async_put_work);
1219 	}
1220 }
1221 EXPORT_SYMBOL_GPL(mmput_async);
1222 #endif
1223 
1224 /**
1225  * set_mm_exe_file - change a reference to the mm's executable file
1226  *
1227  * This changes mm's executable file (shown as symlink /proc/[pid]/exe).
1228  *
1229  * Main users are mmput() and sys_execve(). Callers prevent concurrent
1230  * invocations: in mmput() nobody alive left, in execve task is single
1231  * threaded.
1232  *
1233  * Can only fail if new_exe_file != NULL.
1234  */
set_mm_exe_file(struct mm_struct * mm,struct file * new_exe_file)1235 int set_mm_exe_file(struct mm_struct *mm, struct file *new_exe_file)
1236 {
1237 	struct file *old_exe_file;
1238 
1239 	/*
1240 	 * It is safe to dereference the exe_file without RCU as
1241 	 * this function is only called if nobody else can access
1242 	 * this mm -- see comment above for justification.
1243 	 */
1244 	old_exe_file = rcu_dereference_raw(mm->exe_file);
1245 
1246 	if (new_exe_file) {
1247 		/*
1248 		 * We expect the caller (i.e., sys_execve) to already denied
1249 		 * write access, so this is unlikely to fail.
1250 		 */
1251 		if (unlikely(deny_write_access(new_exe_file)))
1252 			return -EACCES;
1253 		get_file(new_exe_file);
1254 	}
1255 	rcu_assign_pointer(mm->exe_file, new_exe_file);
1256 	if (old_exe_file) {
1257 		allow_write_access(old_exe_file);
1258 		fput(old_exe_file);
1259 	}
1260 	return 0;
1261 }
1262 
1263 /**
1264  * replace_mm_exe_file - replace a reference to the mm's executable file
1265  *
1266  * This changes mm's executable file (shown as symlink /proc/[pid]/exe),
1267  * dealing with concurrent invocation and without grabbing the mmap lock in
1268  * write mode.
1269  *
1270  * Main user is sys_prctl(PR_SET_MM_MAP/EXE_FILE).
1271  */
replace_mm_exe_file(struct mm_struct * mm,struct file * new_exe_file)1272 int replace_mm_exe_file(struct mm_struct *mm, struct file *new_exe_file)
1273 {
1274 	struct vm_area_struct *vma;
1275 	struct file *old_exe_file;
1276 	int ret = 0;
1277 
1278 	/* Forbid mm->exe_file change if old file still mapped. */
1279 	old_exe_file = get_mm_exe_file(mm);
1280 	if (old_exe_file) {
1281 		mmap_read_lock(mm);
1282 		for (vma = mm->mmap; vma && !ret; vma = vma->vm_next) {
1283 			if (!vma->vm_file)
1284 				continue;
1285 			if (path_equal(&vma->vm_file->f_path,
1286 				       &old_exe_file->f_path))
1287 				ret = -EBUSY;
1288 		}
1289 		mmap_read_unlock(mm);
1290 		fput(old_exe_file);
1291 		if (ret)
1292 			return ret;
1293 	}
1294 
1295 	/* set the new file, lockless */
1296 	ret = deny_write_access(new_exe_file);
1297 	if (ret)
1298 		return -EACCES;
1299 	get_file(new_exe_file);
1300 
1301 	old_exe_file = xchg(&mm->exe_file, new_exe_file);
1302 	if (old_exe_file) {
1303 		/*
1304 		 * Don't race with dup_mmap() getting the file and disallowing
1305 		 * write access while someone might open the file writable.
1306 		 */
1307 		mmap_read_lock(mm);
1308 		allow_write_access(old_exe_file);
1309 		fput(old_exe_file);
1310 		mmap_read_unlock(mm);
1311 	}
1312 	return 0;
1313 }
1314 
1315 /**
1316  * get_mm_exe_file - acquire a reference to the mm's executable file
1317  *
1318  * Returns %NULL if mm has no associated executable file.
1319  * User must release file via fput().
1320  */
get_mm_exe_file(struct mm_struct * mm)1321 struct file *get_mm_exe_file(struct mm_struct *mm)
1322 {
1323 	struct file *exe_file;
1324 
1325 	rcu_read_lock();
1326 	exe_file = rcu_dereference(mm->exe_file);
1327 	if (exe_file && !get_file_rcu(exe_file))
1328 		exe_file = NULL;
1329 	rcu_read_unlock();
1330 	return exe_file;
1331 }
1332 
1333 /**
1334  * get_task_exe_file - acquire a reference to the task's executable file
1335  *
1336  * Returns %NULL if task's mm (if any) has no associated executable file or
1337  * this is a kernel thread with borrowed mm (see the comment above get_task_mm).
1338  * User must release file via fput().
1339  */
get_task_exe_file(struct task_struct * task)1340 struct file *get_task_exe_file(struct task_struct *task)
1341 {
1342 	struct file *exe_file = NULL;
1343 	struct mm_struct *mm;
1344 
1345 	task_lock(task);
1346 	mm = task->mm;
1347 	if (mm) {
1348 		if (!(task->flags & PF_KTHREAD))
1349 			exe_file = get_mm_exe_file(mm);
1350 	}
1351 	task_unlock(task);
1352 	return exe_file;
1353 }
1354 
1355 /**
1356  * get_task_mm - acquire a reference to the task's mm
1357  *
1358  * Returns %NULL if the task has no mm.  Checks PF_KTHREAD (meaning
1359  * this kernel workthread has transiently adopted a user mm with use_mm,
1360  * to do its AIO) is not set and if so returns a reference to it, after
1361  * bumping up the use count.  User must release the mm via mmput()
1362  * after use.  Typically used by /proc and ptrace.
1363  */
get_task_mm(struct task_struct * task)1364 struct mm_struct *get_task_mm(struct task_struct *task)
1365 {
1366 	struct mm_struct *mm;
1367 
1368 	task_lock(task);
1369 	mm = task->mm;
1370 	if (mm) {
1371 		if (task->flags & PF_KTHREAD)
1372 			mm = NULL;
1373 		else
1374 			mmget(mm);
1375 	}
1376 	task_unlock(task);
1377 	return mm;
1378 }
1379 EXPORT_SYMBOL_GPL(get_task_mm);
1380 
mm_access(struct task_struct * task,unsigned int mode)1381 struct mm_struct *mm_access(struct task_struct *task, unsigned int mode)
1382 {
1383 	struct mm_struct *mm;
1384 	int err;
1385 
1386 	err =  down_read_killable(&task->signal->exec_update_lock);
1387 	if (err)
1388 		return ERR_PTR(err);
1389 
1390 	mm = get_task_mm(task);
1391 	if (mm && mm != current->mm &&
1392 			!ptrace_may_access(task, mode)) {
1393 		mmput(mm);
1394 		mm = ERR_PTR(-EACCES);
1395 	}
1396 	up_read(&task->signal->exec_update_lock);
1397 
1398 	return mm;
1399 }
1400 
complete_vfork_done(struct task_struct * tsk)1401 static void complete_vfork_done(struct task_struct *tsk)
1402 {
1403 	struct completion *vfork;
1404 
1405 	task_lock(tsk);
1406 	vfork = tsk->vfork_done;
1407 	if (likely(vfork)) {
1408 		tsk->vfork_done = NULL;
1409 		complete(vfork);
1410 	}
1411 	task_unlock(tsk);
1412 }
1413 
wait_for_vfork_done(struct task_struct * child,struct completion * vfork)1414 static int wait_for_vfork_done(struct task_struct *child,
1415 				struct completion *vfork)
1416 {
1417 	int killed;
1418 
1419 	freezer_do_not_count();
1420 	cgroup_enter_frozen();
1421 	killed = wait_for_completion_killable(vfork);
1422 	cgroup_leave_frozen(false);
1423 	freezer_count();
1424 
1425 	if (killed) {
1426 		task_lock(child);
1427 		child->vfork_done = NULL;
1428 		task_unlock(child);
1429 	}
1430 
1431 	put_task_struct(child);
1432 	return killed;
1433 }
1434 
1435 /* Please note the differences between mmput and mm_release.
1436  * mmput is called whenever we stop holding onto a mm_struct,
1437  * error success whatever.
1438  *
1439  * mm_release is called after a mm_struct has been removed
1440  * from the current process.
1441  *
1442  * This difference is important for error handling, when we
1443  * only half set up a mm_struct for a new process and need to restore
1444  * the old one.  Because we mmput the new mm_struct before
1445  * restoring the old one. . .
1446  * Eric Biederman 10 January 1998
1447  */
mm_release(struct task_struct * tsk,struct mm_struct * mm)1448 static void mm_release(struct task_struct *tsk, struct mm_struct *mm)
1449 {
1450 	uprobe_free_utask(tsk);
1451 
1452 	/* Get rid of any cached register state */
1453 	deactivate_mm(tsk, mm);
1454 
1455 	/*
1456 	 * Signal userspace if we're not exiting with a core dump
1457 	 * because we want to leave the value intact for debugging
1458 	 * purposes.
1459 	 */
1460 	if (tsk->clear_child_tid) {
1461 		if (!(tsk->signal->flags & SIGNAL_GROUP_COREDUMP) &&
1462 		    atomic_read(&mm->mm_users) > 1) {
1463 			/*
1464 			 * We don't check the error code - if userspace has
1465 			 * not set up a proper pointer then tough luck.
1466 			 */
1467 			put_user(0, tsk->clear_child_tid);
1468 			do_futex(tsk->clear_child_tid, FUTEX_WAKE,
1469 					1, NULL, NULL, 0, 0);
1470 		}
1471 		tsk->clear_child_tid = NULL;
1472 	}
1473 
1474 	/*
1475 	 * All done, finally we can wake up parent and return this mm to him.
1476 	 * Also kthread_stop() uses this completion for synchronization.
1477 	 */
1478 	if (tsk->vfork_done)
1479 		complete_vfork_done(tsk);
1480 }
1481 
exit_mm_release(struct task_struct * tsk,struct mm_struct * mm)1482 void exit_mm_release(struct task_struct *tsk, struct mm_struct *mm)
1483 {
1484 	futex_exit_release(tsk);
1485 	mm_release(tsk, mm);
1486 }
1487 
exec_mm_release(struct task_struct * tsk,struct mm_struct * mm)1488 void exec_mm_release(struct task_struct *tsk, struct mm_struct *mm)
1489 {
1490 	futex_exec_release(tsk);
1491 	mm_release(tsk, mm);
1492 }
1493 
1494 /**
1495  * dup_mm() - duplicates an existing mm structure
1496  * @tsk: the task_struct with which the new mm will be associated.
1497  * @oldmm: the mm to duplicate.
1498  *
1499  * Allocates a new mm structure and duplicates the provided @oldmm structure
1500  * content into it.
1501  *
1502  * Return: the duplicated mm or NULL on failure.
1503  */
dup_mm(struct task_struct * tsk,struct mm_struct * oldmm)1504 static struct mm_struct *dup_mm(struct task_struct *tsk,
1505 				struct mm_struct *oldmm)
1506 {
1507 	struct mm_struct *mm;
1508 	int err;
1509 
1510 	mm = allocate_mm();
1511 	if (!mm)
1512 		goto fail_nomem;
1513 
1514 	memcpy(mm, oldmm, sizeof(*mm));
1515 
1516 	if (!mm_init(mm, tsk, mm->user_ns))
1517 		goto fail_nomem;
1518 
1519 	err = dup_mmap(mm, oldmm);
1520 	if (err)
1521 		goto free_pt;
1522 
1523 	mm->hiwater_rss = get_mm_rss(mm);
1524 	mm->hiwater_vm = mm->total_vm;
1525 
1526 	if (mm->binfmt && !try_module_get(mm->binfmt->module))
1527 		goto free_pt;
1528 
1529 	return mm;
1530 
1531 free_pt:
1532 	/* don't put binfmt in mmput, we haven't got module yet */
1533 	mm->binfmt = NULL;
1534 	mm_init_owner(mm, NULL);
1535 	mmput(mm);
1536 
1537 fail_nomem:
1538 	return NULL;
1539 }
1540 
copy_mm(unsigned long clone_flags,struct task_struct * tsk)1541 static int copy_mm(unsigned long clone_flags, struct task_struct *tsk)
1542 {
1543 	struct mm_struct *mm, *oldmm;
1544 
1545 	tsk->min_flt = tsk->maj_flt = 0;
1546 	tsk->nvcsw = tsk->nivcsw = 0;
1547 #ifdef CONFIG_DETECT_HUNG_TASK
1548 	tsk->last_switch_count = tsk->nvcsw + tsk->nivcsw;
1549 	tsk->last_switch_time = 0;
1550 #endif
1551 
1552 	tsk->mm = NULL;
1553 	tsk->active_mm = NULL;
1554 
1555 	/*
1556 	 * Are we cloning a kernel thread?
1557 	 *
1558 	 * We need to steal a active VM for that..
1559 	 */
1560 	oldmm = current->mm;
1561 	if (!oldmm)
1562 		return 0;
1563 
1564 	/* initialize the new vmacache entries */
1565 	vmacache_flush(tsk);
1566 
1567 	if (clone_flags & CLONE_VM) {
1568 		mmget(oldmm);
1569 		mm = oldmm;
1570 	} else {
1571 		mm = dup_mm(tsk, current->mm);
1572 		if (!mm)
1573 			return -ENOMEM;
1574 	}
1575 
1576 	tsk->mm = mm;
1577 	tsk->active_mm = mm;
1578 	return 0;
1579 }
1580 
copy_fs(unsigned long clone_flags,struct task_struct * tsk)1581 static int copy_fs(unsigned long clone_flags, struct task_struct *tsk)
1582 {
1583 	struct fs_struct *fs = current->fs;
1584 	if (clone_flags & CLONE_FS) {
1585 		/* tsk->fs is already what we want */
1586 		spin_lock(&fs->lock);
1587 		if (fs->in_exec) {
1588 			spin_unlock(&fs->lock);
1589 			return -EAGAIN;
1590 		}
1591 		fs->users++;
1592 		spin_unlock(&fs->lock);
1593 		return 0;
1594 	}
1595 	tsk->fs = copy_fs_struct(fs);
1596 	if (!tsk->fs)
1597 		return -ENOMEM;
1598 	return 0;
1599 }
1600 
copy_files(unsigned long clone_flags,struct task_struct * tsk)1601 static int copy_files(unsigned long clone_flags, struct task_struct *tsk)
1602 {
1603 	struct files_struct *oldf, *newf;
1604 	int error = 0;
1605 
1606 	/*
1607 	 * A background process may not have any files ...
1608 	 */
1609 	oldf = current->files;
1610 	if (!oldf)
1611 		goto out;
1612 
1613 	if (clone_flags & CLONE_FILES) {
1614 		atomic_inc(&oldf->count);
1615 		goto out;
1616 	}
1617 
1618 	newf = dup_fd(oldf, NR_OPEN_MAX, &error);
1619 	if (!newf)
1620 		goto out;
1621 
1622 	tsk->files = newf;
1623 	error = 0;
1624 out:
1625 	return error;
1626 }
1627 
copy_io(unsigned long clone_flags,struct task_struct * tsk)1628 static int copy_io(unsigned long clone_flags, struct task_struct *tsk)
1629 {
1630 #ifdef CONFIG_BLOCK
1631 	struct io_context *ioc = current->io_context;
1632 	struct io_context *new_ioc;
1633 
1634 	if (!ioc)
1635 		return 0;
1636 	/*
1637 	 * Share io context with parent, if CLONE_IO is set
1638 	 */
1639 	if (clone_flags & CLONE_IO) {
1640 		ioc_task_link(ioc);
1641 		tsk->io_context = ioc;
1642 	} else if (ioprio_valid(ioc->ioprio)) {
1643 		new_ioc = get_task_io_context(tsk, GFP_KERNEL, NUMA_NO_NODE);
1644 		if (unlikely(!new_ioc))
1645 			return -ENOMEM;
1646 
1647 		new_ioc->ioprio = ioc->ioprio;
1648 		put_io_context(new_ioc);
1649 	}
1650 #endif
1651 	return 0;
1652 }
1653 
copy_sighand(unsigned long clone_flags,struct task_struct * tsk)1654 static int copy_sighand(unsigned long clone_flags, struct task_struct *tsk)
1655 {
1656 	struct sighand_struct *sig;
1657 
1658 	if (clone_flags & CLONE_SIGHAND) {
1659 		refcount_inc(&current->sighand->count);
1660 		return 0;
1661 	}
1662 	sig = kmem_cache_alloc(sighand_cachep, GFP_KERNEL);
1663 	RCU_INIT_POINTER(tsk->sighand, sig);
1664 	if (!sig)
1665 		return -ENOMEM;
1666 
1667 	refcount_set(&sig->count, 1);
1668 	spin_lock_irq(&current->sighand->siglock);
1669 	memcpy(sig->action, current->sighand->action, sizeof(sig->action));
1670 	spin_unlock_irq(&current->sighand->siglock);
1671 
1672 	/* Reset all signal handler not set to SIG_IGN to SIG_DFL. */
1673 	if (clone_flags & CLONE_CLEAR_SIGHAND)
1674 		flush_signal_handlers(tsk, 0);
1675 
1676 	return 0;
1677 }
1678 
__cleanup_sighand(struct sighand_struct * sighand)1679 void __cleanup_sighand(struct sighand_struct *sighand)
1680 {
1681 	if (refcount_dec_and_test(&sighand->count)) {
1682 		signalfd_cleanup(sighand);
1683 		/*
1684 		 * sighand_cachep is SLAB_TYPESAFE_BY_RCU so we can free it
1685 		 * without an RCU grace period, see __lock_task_sighand().
1686 		 */
1687 		kmem_cache_free(sighand_cachep, sighand);
1688 	}
1689 }
1690 
1691 /*
1692  * Initialize POSIX timer handling for a thread group.
1693  */
posix_cpu_timers_init_group(struct signal_struct * sig)1694 static void posix_cpu_timers_init_group(struct signal_struct *sig)
1695 {
1696 	struct posix_cputimers *pct = &sig->posix_cputimers;
1697 	unsigned long cpu_limit;
1698 
1699 	cpu_limit = READ_ONCE(sig->rlim[RLIMIT_CPU].rlim_cur);
1700 	posix_cputimers_group_init(pct, cpu_limit);
1701 }
1702 
copy_signal(unsigned long clone_flags,struct task_struct * tsk)1703 static int copy_signal(unsigned long clone_flags, struct task_struct *tsk)
1704 {
1705 	struct signal_struct *sig;
1706 
1707 	if (clone_flags & CLONE_THREAD)
1708 		return 0;
1709 
1710 	sig = kmem_cache_zalloc(signal_cachep, GFP_KERNEL);
1711 	tsk->signal = sig;
1712 	if (!sig)
1713 		return -ENOMEM;
1714 
1715 	sig->nr_threads = 1;
1716 	atomic_set(&sig->live, 1);
1717 	refcount_set(&sig->sigcnt, 1);
1718 
1719 	/* list_add(thread_node, thread_head) without INIT_LIST_HEAD() */
1720 	sig->thread_head = (struct list_head)LIST_HEAD_INIT(tsk->thread_node);
1721 	tsk->thread_node = (struct list_head)LIST_HEAD_INIT(sig->thread_head);
1722 
1723 	init_waitqueue_head(&sig->wait_chldexit);
1724 	sig->curr_target = tsk;
1725 	init_sigpending(&sig->shared_pending);
1726 	INIT_HLIST_HEAD(&sig->multiprocess);
1727 	seqlock_init(&sig->stats_lock);
1728 	prev_cputime_init(&sig->prev_cputime);
1729 
1730 #ifdef CONFIG_POSIX_TIMERS
1731 	INIT_LIST_HEAD(&sig->posix_timers);
1732 	hrtimer_init(&sig->real_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
1733 	sig->real_timer.function = it_real_fn;
1734 #endif
1735 
1736 	task_lock(current->group_leader);
1737 	memcpy(sig->rlim, current->signal->rlim, sizeof sig->rlim);
1738 	task_unlock(current->group_leader);
1739 
1740 	posix_cpu_timers_init_group(sig);
1741 
1742 	tty_audit_fork(sig);
1743 	sched_autogroup_fork(sig);
1744 
1745 	sig->oom_score_adj = current->signal->oom_score_adj;
1746 	sig->oom_score_adj_min = current->signal->oom_score_adj_min;
1747 
1748 	mutex_init(&sig->cred_guard_mutex);
1749 	init_rwsem(&sig->exec_update_lock);
1750 
1751 	return 0;
1752 }
1753 
copy_seccomp(struct task_struct * p)1754 static void copy_seccomp(struct task_struct *p)
1755 {
1756 #ifdef CONFIG_SECCOMP
1757 	/*
1758 	 * Must be called with sighand->lock held, which is common to
1759 	 * all threads in the group. Holding cred_guard_mutex is not
1760 	 * needed because this new task is not yet running and cannot
1761 	 * be racing exec.
1762 	 */
1763 	assert_spin_locked(&current->sighand->siglock);
1764 
1765 	/* Ref-count the new filter user, and assign it. */
1766 	get_seccomp_filter(current);
1767 	p->seccomp = current->seccomp;
1768 
1769 	/*
1770 	 * Explicitly enable no_new_privs here in case it got set
1771 	 * between the task_struct being duplicated and holding the
1772 	 * sighand lock. The seccomp state and nnp must be in sync.
1773 	 */
1774 	if (task_no_new_privs(current))
1775 		task_set_no_new_privs(p);
1776 
1777 	/*
1778 	 * If the parent gained a seccomp mode after copying thread
1779 	 * flags and between before we held the sighand lock, we have
1780 	 * to manually enable the seccomp thread flag here.
1781 	 */
1782 	if (p->seccomp.mode != SECCOMP_MODE_DISABLED)
1783 		set_task_syscall_work(p, SECCOMP);
1784 #endif
1785 }
1786 
SYSCALL_DEFINE1(set_tid_address,int __user *,tidptr)1787 SYSCALL_DEFINE1(set_tid_address, int __user *, tidptr)
1788 {
1789 	current->clear_child_tid = tidptr;
1790 
1791 	return task_pid_vnr(current);
1792 }
1793 
rt_mutex_init_task(struct task_struct * p)1794 static void rt_mutex_init_task(struct task_struct *p)
1795 {
1796 	raw_spin_lock_init(&p->pi_lock);
1797 #ifdef CONFIG_RT_MUTEXES
1798 	p->pi_waiters = RB_ROOT_CACHED;
1799 	p->pi_top_task = NULL;
1800 	p->pi_blocked_on = NULL;
1801 #endif
1802 }
1803 
init_task_pid_links(struct task_struct * task)1804 static inline void init_task_pid_links(struct task_struct *task)
1805 {
1806 	enum pid_type type;
1807 
1808 	for (type = PIDTYPE_PID; type < PIDTYPE_MAX; ++type)
1809 		INIT_HLIST_NODE(&task->pid_links[type]);
1810 }
1811 
1812 static inline void
init_task_pid(struct task_struct * task,enum pid_type type,struct pid * pid)1813 init_task_pid(struct task_struct *task, enum pid_type type, struct pid *pid)
1814 {
1815 	if (type == PIDTYPE_PID)
1816 		task->thread_pid = pid;
1817 	else
1818 		task->signal->pids[type] = pid;
1819 }
1820 
rcu_copy_process(struct task_struct * p)1821 static inline void rcu_copy_process(struct task_struct *p)
1822 {
1823 #ifdef CONFIG_PREEMPT_RCU
1824 	p->rcu_read_lock_nesting = 0;
1825 	p->rcu_read_unlock_special.s = 0;
1826 	p->rcu_blocked_node = NULL;
1827 	INIT_LIST_HEAD(&p->rcu_node_entry);
1828 #endif /* #ifdef CONFIG_PREEMPT_RCU */
1829 #ifdef CONFIG_TASKS_RCU
1830 	p->rcu_tasks_holdout = false;
1831 	INIT_LIST_HEAD(&p->rcu_tasks_holdout_list);
1832 	p->rcu_tasks_idle_cpu = -1;
1833 #endif /* #ifdef CONFIG_TASKS_RCU */
1834 #ifdef CONFIG_TASKS_TRACE_RCU
1835 	p->trc_reader_nesting = 0;
1836 	p->trc_reader_special.s = 0;
1837 	INIT_LIST_HEAD(&p->trc_holdout_list);
1838 #endif /* #ifdef CONFIG_TASKS_TRACE_RCU */
1839 }
1840 
pidfd_pid(const struct file * file)1841 struct pid *pidfd_pid(const struct file *file)
1842 {
1843 	if (file->f_op == &pidfd_fops)
1844 		return file->private_data;
1845 
1846 	return ERR_PTR(-EBADF);
1847 }
1848 
pidfd_release(struct inode * inode,struct file * file)1849 static int pidfd_release(struct inode *inode, struct file *file)
1850 {
1851 	struct pid *pid = file->private_data;
1852 
1853 	file->private_data = NULL;
1854 	put_pid(pid);
1855 	return 0;
1856 }
1857 
1858 #ifdef CONFIG_PROC_FS
1859 /**
1860  * pidfd_show_fdinfo - print information about a pidfd
1861  * @m: proc fdinfo file
1862  * @f: file referencing a pidfd
1863  *
1864  * Pid:
1865  * This function will print the pid that a given pidfd refers to in the
1866  * pid namespace of the procfs instance.
1867  * If the pid namespace of the process is not a descendant of the pid
1868  * namespace of the procfs instance 0 will be shown as its pid. This is
1869  * similar to calling getppid() on a process whose parent is outside of
1870  * its pid namespace.
1871  *
1872  * NSpid:
1873  * If pid namespaces are supported then this function will also print
1874  * the pid of a given pidfd refers to for all descendant pid namespaces
1875  * starting from the current pid namespace of the instance, i.e. the
1876  * Pid field and the first entry in the NSpid field will be identical.
1877  * If the pid namespace of the process is not a descendant of the pid
1878  * namespace of the procfs instance 0 will be shown as its first NSpid
1879  * entry and no others will be shown.
1880  * Note that this differs from the Pid and NSpid fields in
1881  * /proc/<pid>/status where Pid and NSpid are always shown relative to
1882  * the  pid namespace of the procfs instance. The difference becomes
1883  * obvious when sending around a pidfd between pid namespaces from a
1884  * different branch of the tree, i.e. where no ancestral relation is
1885  * present between the pid namespaces:
1886  * - create two new pid namespaces ns1 and ns2 in the initial pid
1887  *   namespace (also take care to create new mount namespaces in the
1888  *   new pid namespace and mount procfs)
1889  * - create a process with a pidfd in ns1
1890  * - send pidfd from ns1 to ns2
1891  * - read /proc/self/fdinfo/<pidfd> and observe that both Pid and NSpid
1892  *   have exactly one entry, which is 0
1893  */
pidfd_show_fdinfo(struct seq_file * m,struct file * f)1894 static void pidfd_show_fdinfo(struct seq_file *m, struct file *f)
1895 {
1896 	struct pid *pid = f->private_data;
1897 	struct pid_namespace *ns;
1898 	pid_t nr = -1;
1899 
1900 	if (likely(pid_has_task(pid, PIDTYPE_PID))) {
1901 		ns = proc_pid_ns(file_inode(m->file)->i_sb);
1902 		nr = pid_nr_ns(pid, ns);
1903 	}
1904 
1905 	seq_put_decimal_ll(m, "Pid:\t", nr);
1906 
1907 #ifdef CONFIG_PID_NS
1908 	seq_put_decimal_ll(m, "\nNSpid:\t", nr);
1909 	if (nr > 0) {
1910 		int i;
1911 
1912 		/* If nr is non-zero it means that 'pid' is valid and that
1913 		 * ns, i.e. the pid namespace associated with the procfs
1914 		 * instance, is in the pid namespace hierarchy of pid.
1915 		 * Start at one below the already printed level.
1916 		 */
1917 		for (i = ns->level + 1; i <= pid->level; i++)
1918 			seq_put_decimal_ll(m, "\t", pid->numbers[i].nr);
1919 	}
1920 #endif
1921 	seq_putc(m, '\n');
1922 }
1923 #endif
1924 
1925 /*
1926  * Poll support for process exit notification.
1927  */
pidfd_poll(struct file * file,struct poll_table_struct * pts)1928 static __poll_t pidfd_poll(struct file *file, struct poll_table_struct *pts)
1929 {
1930 	struct pid *pid = file->private_data;
1931 	__poll_t poll_flags = 0;
1932 
1933 	poll_wait(file, &pid->wait_pidfd, pts);
1934 
1935 	/*
1936 	 * Inform pollers only when the whole thread group exits.
1937 	 * If the thread group leader exits before all other threads in the
1938 	 * group, then poll(2) should block, similar to the wait(2) family.
1939 	 */
1940 	if (thread_group_exited(pid))
1941 		poll_flags = EPOLLIN | EPOLLRDNORM;
1942 
1943 	return poll_flags;
1944 }
1945 
1946 const struct file_operations pidfd_fops = {
1947 	.release = pidfd_release,
1948 	.poll = pidfd_poll,
1949 #ifdef CONFIG_PROC_FS
1950 	.show_fdinfo = pidfd_show_fdinfo,
1951 #endif
1952 };
1953 
__delayed_free_task(struct rcu_head * rhp)1954 static void __delayed_free_task(struct rcu_head *rhp)
1955 {
1956 	struct task_struct *tsk = container_of(rhp, struct task_struct, rcu);
1957 
1958 	free_task(tsk);
1959 }
1960 
delayed_free_task(struct task_struct * tsk)1961 static __always_inline void delayed_free_task(struct task_struct *tsk)
1962 {
1963 	if (IS_ENABLED(CONFIG_MEMCG))
1964 		call_rcu(&tsk->rcu, __delayed_free_task);
1965 	else
1966 		free_task(tsk);
1967 }
1968 
copy_oom_score_adj(u64 clone_flags,struct task_struct * tsk)1969 static void copy_oom_score_adj(u64 clone_flags, struct task_struct *tsk)
1970 {
1971 	/* Skip if kernel thread */
1972 	if (!tsk->mm)
1973 		return;
1974 
1975 	/* Skip if spawning a thread or using vfork */
1976 	if ((clone_flags & (CLONE_VM | CLONE_THREAD | CLONE_VFORK)) != CLONE_VM)
1977 		return;
1978 
1979 	/* We need to synchronize with __set_oom_adj */
1980 	mutex_lock(&oom_adj_mutex);
1981 	set_bit(MMF_MULTIPROCESS, &tsk->mm->flags);
1982 	/* Update the values in case they were changed after copy_signal */
1983 	tsk->signal->oom_score_adj = current->signal->oom_score_adj;
1984 	tsk->signal->oom_score_adj_min = current->signal->oom_score_adj_min;
1985 	mutex_unlock(&oom_adj_mutex);
1986 }
1987 
1988 /*
1989  * This creates a new process as a copy of the old one,
1990  * but does not actually start it yet.
1991  *
1992  * It copies the registers, and all the appropriate
1993  * parts of the process environment (as per the clone
1994  * flags). The actual kick-off is left to the caller.
1995  */
copy_process(struct pid * pid,int trace,int node,struct kernel_clone_args * args)1996 static __latent_entropy struct task_struct *copy_process(
1997 					struct pid *pid,
1998 					int trace,
1999 					int node,
2000 					struct kernel_clone_args *args)
2001 {
2002 	int pidfd = -1, retval;
2003 	struct task_struct *p;
2004 	struct multiprocess_signals delayed;
2005 	struct file *pidfile = NULL;
2006 	u64 clone_flags = args->flags;
2007 	struct nsproxy *nsp = current->nsproxy;
2008 
2009 	/*
2010 	 * Don't allow sharing the root directory with processes in a different
2011 	 * namespace
2012 	 */
2013 	if ((clone_flags & (CLONE_NEWNS|CLONE_FS)) == (CLONE_NEWNS|CLONE_FS))
2014 		return ERR_PTR(-EINVAL);
2015 
2016 	if ((clone_flags & (CLONE_NEWUSER|CLONE_FS)) == (CLONE_NEWUSER|CLONE_FS))
2017 		return ERR_PTR(-EINVAL);
2018 
2019 	/*
2020 	 * Thread groups must share signals as well, and detached threads
2021 	 * can only be started up within the thread group.
2022 	 */
2023 	if ((clone_flags & CLONE_THREAD) && !(clone_flags & CLONE_SIGHAND))
2024 		return ERR_PTR(-EINVAL);
2025 
2026 	/*
2027 	 * Shared signal handlers imply shared VM. By way of the above,
2028 	 * thread groups also imply shared VM. Blocking this case allows
2029 	 * for various simplifications in other code.
2030 	 */
2031 	if ((clone_flags & CLONE_SIGHAND) && !(clone_flags & CLONE_VM))
2032 		return ERR_PTR(-EINVAL);
2033 
2034 	/*
2035 	 * Siblings of global init remain as zombies on exit since they are
2036 	 * not reaped by their parent (swapper). To solve this and to avoid
2037 	 * multi-rooted process trees, prevent global and container-inits
2038 	 * from creating siblings.
2039 	 */
2040 	if ((clone_flags & CLONE_PARENT) &&
2041 				current->signal->flags & SIGNAL_UNKILLABLE)
2042 		return ERR_PTR(-EINVAL);
2043 
2044 	/*
2045 	 * If the new process will be in a different pid or user namespace
2046 	 * do not allow it to share a thread group with the forking task.
2047 	 */
2048 	if (clone_flags & CLONE_THREAD) {
2049 		if ((clone_flags & (CLONE_NEWUSER | CLONE_NEWPID)) ||
2050 		    (task_active_pid_ns(current) != nsp->pid_ns_for_children))
2051 			return ERR_PTR(-EINVAL);
2052 	}
2053 
2054 	/*
2055 	 * If the new process will be in a different time namespace
2056 	 * do not allow it to share VM or a thread group with the forking task.
2057 	 */
2058 	if (clone_flags & (CLONE_THREAD | CLONE_VM)) {
2059 		if (nsp->time_ns != nsp->time_ns_for_children)
2060 			return ERR_PTR(-EINVAL);
2061 	}
2062 
2063 	if (clone_flags & CLONE_PIDFD) {
2064 		/*
2065 		 * - CLONE_DETACHED is blocked so that we can potentially
2066 		 *   reuse it later for CLONE_PIDFD.
2067 		 * - CLONE_THREAD is blocked until someone really needs it.
2068 		 */
2069 		if (clone_flags & (CLONE_DETACHED | CLONE_THREAD))
2070 			return ERR_PTR(-EINVAL);
2071 	}
2072 
2073 	/*
2074 	 * Force any signals received before this point to be delivered
2075 	 * before the fork happens.  Collect up signals sent to multiple
2076 	 * processes that happen during the fork and delay them so that
2077 	 * they appear to happen after the fork.
2078 	 */
2079 	sigemptyset(&delayed.signal);
2080 	INIT_HLIST_NODE(&delayed.node);
2081 
2082 	spin_lock_irq(&current->sighand->siglock);
2083 	if (!(clone_flags & CLONE_THREAD))
2084 		hlist_add_head(&delayed.node, &current->signal->multiprocess);
2085 	recalc_sigpending();
2086 	spin_unlock_irq(&current->sighand->siglock);
2087 	retval = -ERESTARTNOINTR;
2088 	if (task_sigpending(current))
2089 		goto fork_out;
2090 
2091 	retval = -ENOMEM;
2092 	p = dup_task_struct(current, node);
2093 	if (!p)
2094 		goto fork_out;
2095 	if (args->io_thread) {
2096 		/*
2097 		 * Mark us an IO worker, and block any signal that isn't
2098 		 * fatal or STOP
2099 		 */
2100 		p->flags |= PF_IO_WORKER;
2101 		siginitsetinv(&p->blocked, sigmask(SIGKILL)|sigmask(SIGSTOP));
2102 	}
2103 
2104 	cpufreq_task_times_init(p);
2105 
2106 	/*
2107 	 * This _must_ happen before we call free_task(), i.e. before we jump
2108 	 * to any of the bad_fork_* labels. This is to avoid freeing
2109 	 * p->set_child_tid which is (ab)used as a kthread's data pointer for
2110 	 * kernel threads (PF_KTHREAD).
2111 	 */
2112 	p->set_child_tid = (clone_flags & CLONE_CHILD_SETTID) ? args->child_tid : NULL;
2113 	/*
2114 	 * Clear TID on mm_release()?
2115 	 */
2116 	p->clear_child_tid = (clone_flags & CLONE_CHILD_CLEARTID) ? args->child_tid : NULL;
2117 
2118 	ftrace_graph_init_task(p);
2119 
2120 	rt_mutex_init_task(p);
2121 
2122 	lockdep_assert_irqs_enabled();
2123 #ifdef CONFIG_PROVE_LOCKING
2124 	DEBUG_LOCKS_WARN_ON(!p->softirqs_enabled);
2125 #endif
2126 	retval = copy_creds(p, clone_flags);
2127 	if (retval < 0)
2128 		goto bad_fork_free;
2129 
2130 	retval = -EAGAIN;
2131 	if (is_ucounts_overlimit(task_ucounts(p), UCOUNT_RLIMIT_NPROC, rlimit(RLIMIT_NPROC))) {
2132 		if (p->real_cred->user != INIT_USER &&
2133 		    !capable(CAP_SYS_RESOURCE) && !capable(CAP_SYS_ADMIN))
2134 			goto bad_fork_cleanup_count;
2135 	}
2136 	current->flags &= ~PF_NPROC_EXCEEDED;
2137 
2138 	/*
2139 	 * If multiple threads are within copy_process(), then this check
2140 	 * triggers too late. This doesn't hurt, the check is only there
2141 	 * to stop root fork bombs.
2142 	 */
2143 	retval = -EAGAIN;
2144 	if (data_race(nr_threads >= max_threads))
2145 		goto bad_fork_cleanup_count;
2146 
2147 	delayacct_tsk_init(p);	/* Must remain after dup_task_struct() */
2148 	p->flags &= ~(PF_SUPERPRIV | PF_WQ_WORKER | PF_IDLE | PF_NO_SETAFFINITY);
2149 	p->flags |= PF_FORKNOEXEC;
2150 	INIT_LIST_HEAD(&p->children);
2151 	INIT_LIST_HEAD(&p->sibling);
2152 	rcu_copy_process(p);
2153 	p->vfork_done = NULL;
2154 	spin_lock_init(&p->alloc_lock);
2155 
2156 	init_sigpending(&p->pending);
2157 
2158 	p->utime = p->stime = p->gtime = 0;
2159 #ifdef CONFIG_ARCH_HAS_SCALED_CPUTIME
2160 	p->utimescaled = p->stimescaled = 0;
2161 #endif
2162 	prev_cputime_init(&p->prev_cputime);
2163 
2164 #ifdef CONFIG_VIRT_CPU_ACCOUNTING_GEN
2165 	seqcount_init(&p->vtime.seqcount);
2166 	p->vtime.starttime = 0;
2167 	p->vtime.state = VTIME_INACTIVE;
2168 #endif
2169 
2170 #ifdef CONFIG_IO_URING
2171 	p->io_uring = NULL;
2172 #endif
2173 
2174 #if defined(SPLIT_RSS_COUNTING)
2175 	memset(&p->rss_stat, 0, sizeof(p->rss_stat));
2176 #endif
2177 
2178 	p->default_timer_slack_ns = current->timer_slack_ns;
2179 
2180 #ifdef CONFIG_PSI
2181 	p->psi_flags = 0;
2182 #endif
2183 
2184 	task_io_accounting_init(&p->ioac);
2185 	acct_clear_integrals(p);
2186 
2187 	posix_cputimers_init(&p->posix_cputimers);
2188 
2189 	p->io_context = NULL;
2190 	audit_set_context(p, NULL);
2191 	cgroup_fork(p);
2192 #ifdef CONFIG_NUMA
2193 	p->mempolicy = mpol_dup(p->mempolicy);
2194 	if (IS_ERR(p->mempolicy)) {
2195 		retval = PTR_ERR(p->mempolicy);
2196 		p->mempolicy = NULL;
2197 		goto bad_fork_cleanup_threadgroup_lock;
2198 	}
2199 #endif
2200 #ifdef CONFIG_CPUSETS
2201 	p->cpuset_mem_spread_rotor = NUMA_NO_NODE;
2202 	p->cpuset_slab_spread_rotor = NUMA_NO_NODE;
2203 	seqcount_spinlock_init(&p->mems_allowed_seq, &p->alloc_lock);
2204 #endif
2205 #ifdef CONFIG_TRACE_IRQFLAGS
2206 	memset(&p->irqtrace, 0, sizeof(p->irqtrace));
2207 	p->irqtrace.hardirq_disable_ip	= _THIS_IP_;
2208 	p->irqtrace.softirq_enable_ip	= _THIS_IP_;
2209 	p->softirqs_enabled		= 1;
2210 	p->softirq_context		= 0;
2211 #endif
2212 
2213 	p->pagefault_disabled = 0;
2214 
2215 #ifdef CONFIG_LOCKDEP
2216 	lockdep_init_task(p);
2217 #endif
2218 
2219 #ifdef CONFIG_DEBUG_MUTEXES
2220 	p->blocked_on = NULL; /* not blocked yet */
2221 #endif
2222 #ifdef CONFIG_BCACHE
2223 	p->sequential_io	= 0;
2224 	p->sequential_io_avg	= 0;
2225 #endif
2226 #ifdef CONFIG_BPF_SYSCALL
2227 	RCU_INIT_POINTER(p->bpf_storage, NULL);
2228 	p->bpf_ctx = NULL;
2229 #endif
2230 
2231 	/* Perform scheduler related setup. Assign this task to a CPU. */
2232 	retval = sched_fork(clone_flags, p);
2233 	if (retval)
2234 		goto bad_fork_cleanup_policy;
2235 
2236 	retval = perf_event_init_task(p, clone_flags);
2237 	if (retval)
2238 		goto bad_fork_cleanup_policy;
2239 	retval = audit_alloc(p);
2240 	if (retval)
2241 		goto bad_fork_cleanup_perf;
2242 	/* copy all the process information */
2243 	shm_init_task(p);
2244 	retval = security_task_alloc(p, clone_flags);
2245 	if (retval)
2246 		goto bad_fork_cleanup_audit;
2247 	retval = copy_semundo(clone_flags, p);
2248 	if (retval)
2249 		goto bad_fork_cleanup_security;
2250 	retval = copy_files(clone_flags, p);
2251 	if (retval)
2252 		goto bad_fork_cleanup_semundo;
2253 	retval = copy_fs(clone_flags, p);
2254 	if (retval)
2255 		goto bad_fork_cleanup_files;
2256 	retval = copy_sighand(clone_flags, p);
2257 	if (retval)
2258 		goto bad_fork_cleanup_fs;
2259 	retval = copy_signal(clone_flags, p);
2260 	if (retval)
2261 		goto bad_fork_cleanup_sighand;
2262 	retval = copy_mm(clone_flags, p);
2263 	if (retval)
2264 		goto bad_fork_cleanup_signal;
2265 	retval = copy_namespaces(clone_flags, p);
2266 	if (retval)
2267 		goto bad_fork_cleanup_mm;
2268 	retval = copy_io(clone_flags, p);
2269 	if (retval)
2270 		goto bad_fork_cleanup_namespaces;
2271 	retval = copy_thread(clone_flags, args->stack, args->stack_size, p, args->tls);
2272 	if (retval)
2273 		goto bad_fork_cleanup_io;
2274 
2275 	stackleak_task_init(p);
2276 
2277 	if (pid != &init_struct_pid) {
2278 		pid = alloc_pid(p->nsproxy->pid_ns_for_children, args->set_tid,
2279 				args->set_tid_size);
2280 		if (IS_ERR(pid)) {
2281 			retval = PTR_ERR(pid);
2282 			goto bad_fork_cleanup_thread;
2283 		}
2284 	}
2285 
2286 	/*
2287 	 * This has to happen after we've potentially unshared the file
2288 	 * descriptor table (so that the pidfd doesn't leak into the child
2289 	 * if the fd table isn't shared).
2290 	 */
2291 	if (clone_flags & CLONE_PIDFD) {
2292 		retval = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
2293 		if (retval < 0)
2294 			goto bad_fork_free_pid;
2295 
2296 		pidfd = retval;
2297 
2298 		pidfile = anon_inode_getfile("[pidfd]", &pidfd_fops, pid,
2299 					      O_RDWR | O_CLOEXEC);
2300 		if (IS_ERR(pidfile)) {
2301 			put_unused_fd(pidfd);
2302 			retval = PTR_ERR(pidfile);
2303 			goto bad_fork_free_pid;
2304 		}
2305 		get_pid(pid);	/* held by pidfile now */
2306 
2307 		retval = put_user(pidfd, args->pidfd);
2308 		if (retval)
2309 			goto bad_fork_put_pidfd;
2310 	}
2311 
2312 #ifdef CONFIG_BLOCK
2313 	p->plug = NULL;
2314 #endif
2315 	futex_init_task(p);
2316 
2317 	/*
2318 	 * sigaltstack should be cleared when sharing the same VM
2319 	 */
2320 	if ((clone_flags & (CLONE_VM|CLONE_VFORK)) == CLONE_VM)
2321 		sas_ss_reset(p);
2322 
2323 	/*
2324 	 * Syscall tracing and stepping should be turned off in the
2325 	 * child regardless of CLONE_PTRACE.
2326 	 */
2327 	user_disable_single_step(p);
2328 	clear_task_syscall_work(p, SYSCALL_TRACE);
2329 #if defined(CONFIG_GENERIC_ENTRY) || defined(TIF_SYSCALL_EMU)
2330 	clear_task_syscall_work(p, SYSCALL_EMU);
2331 #endif
2332 	clear_tsk_latency_tracing(p);
2333 
2334 	/* ok, now we should be set up.. */
2335 	p->pid = pid_nr(pid);
2336 	if (clone_flags & CLONE_THREAD) {
2337 		p->group_leader = current->group_leader;
2338 		p->tgid = current->tgid;
2339 	} else {
2340 		p->group_leader = p;
2341 		p->tgid = p->pid;
2342 	}
2343 
2344 	p->nr_dirtied = 0;
2345 	p->nr_dirtied_pause = 128 >> (PAGE_SHIFT - 10);
2346 	p->dirty_paused_when = 0;
2347 
2348 	p->pdeath_signal = 0;
2349 	INIT_LIST_HEAD(&p->thread_group);
2350 	p->task_works = NULL;
2351 	clear_posix_cputimers_work(p);
2352 
2353 #ifdef CONFIG_KRETPROBES
2354 	p->kretprobe_instances.first = NULL;
2355 #endif
2356 
2357 	/*
2358 	 * Ensure that the cgroup subsystem policies allow the new process to be
2359 	 * forked. It should be noted that the new process's css_set can be changed
2360 	 * between here and cgroup_post_fork() if an organisation operation is in
2361 	 * progress.
2362 	 */
2363 	retval = cgroup_can_fork(p, args);
2364 	if (retval)
2365 		goto bad_fork_put_pidfd;
2366 
2367 	/*
2368 	 * Now that the cgroups are pinned, re-clone the parent cgroup and put
2369 	 * the new task on the correct runqueue. All this *before* the task
2370 	 * becomes visible.
2371 	 *
2372 	 * This isn't part of ->can_fork() because while the re-cloning is
2373 	 * cgroup specific, it unconditionally needs to place the task on a
2374 	 * runqueue.
2375 	 */
2376 	sched_cgroup_fork(p, args);
2377 
2378 	/*
2379 	 * From this point on we must avoid any synchronous user-space
2380 	 * communication until we take the tasklist-lock. In particular, we do
2381 	 * not want user-space to be able to predict the process start-time by
2382 	 * stalling fork(2) after we recorded the start_time but before it is
2383 	 * visible to the system.
2384 	 */
2385 
2386 	p->start_time = ktime_get_ns();
2387 	p->start_boottime = ktime_get_boottime_ns();
2388 
2389 	/*
2390 	 * Make it visible to the rest of the system, but dont wake it up yet.
2391 	 * Need tasklist lock for parent etc handling!
2392 	 */
2393 	write_lock_irq(&tasklist_lock);
2394 
2395 	/* CLONE_PARENT re-uses the old parent */
2396 	if (clone_flags & (CLONE_PARENT|CLONE_THREAD)) {
2397 		p->real_parent = current->real_parent;
2398 		p->parent_exec_id = current->parent_exec_id;
2399 		if (clone_flags & CLONE_THREAD)
2400 			p->exit_signal = -1;
2401 		else
2402 			p->exit_signal = current->group_leader->exit_signal;
2403 	} else {
2404 		p->real_parent = current;
2405 		p->parent_exec_id = current->self_exec_id;
2406 		p->exit_signal = args->exit_signal;
2407 	}
2408 
2409 	klp_copy_process(p);
2410 
2411 	sched_core_fork(p);
2412 
2413 	spin_lock(&current->sighand->siglock);
2414 
2415 	rseq_fork(p, clone_flags);
2416 
2417 	/* Don't start children in a dying pid namespace */
2418 	if (unlikely(!(ns_of_pid(pid)->pid_allocated & PIDNS_ADDING))) {
2419 		retval = -ENOMEM;
2420 		goto bad_fork_cancel_cgroup;
2421 	}
2422 
2423 	/* Let kill terminate clone/fork in the middle */
2424 	if (fatal_signal_pending(current)) {
2425 		retval = -EINTR;
2426 		goto bad_fork_cancel_cgroup;
2427 	}
2428 
2429 	/* No more failure paths after this point. */
2430 
2431 	/*
2432 	 * Copy seccomp details explicitly here, in case they were changed
2433 	 * before holding sighand lock.
2434 	 */
2435 	copy_seccomp(p);
2436 
2437 	init_task_pid_links(p);
2438 	if (likely(p->pid)) {
2439 		ptrace_init_task(p, (clone_flags & CLONE_PTRACE) || trace);
2440 
2441 		init_task_pid(p, PIDTYPE_PID, pid);
2442 		if (thread_group_leader(p)) {
2443 			init_task_pid(p, PIDTYPE_TGID, pid);
2444 			init_task_pid(p, PIDTYPE_PGID, task_pgrp(current));
2445 			init_task_pid(p, PIDTYPE_SID, task_session(current));
2446 
2447 			if (is_child_reaper(pid)) {
2448 				ns_of_pid(pid)->child_reaper = p;
2449 				p->signal->flags |= SIGNAL_UNKILLABLE;
2450 			}
2451 			p->signal->shared_pending.signal = delayed.signal;
2452 			p->signal->tty = tty_kref_get(current->signal->tty);
2453 			/*
2454 			 * Inherit has_child_subreaper flag under the same
2455 			 * tasklist_lock with adding child to the process tree
2456 			 * for propagate_has_child_subreaper optimization.
2457 			 */
2458 			p->signal->has_child_subreaper = p->real_parent->signal->has_child_subreaper ||
2459 							 p->real_parent->signal->is_child_subreaper;
2460 			list_add_tail(&p->sibling, &p->real_parent->children);
2461 			list_add_tail_rcu(&p->tasks, &init_task.tasks);
2462 			attach_pid(p, PIDTYPE_TGID);
2463 			attach_pid(p, PIDTYPE_PGID);
2464 			attach_pid(p, PIDTYPE_SID);
2465 			__this_cpu_inc(process_counts);
2466 		} else {
2467 			current->signal->nr_threads++;
2468 			atomic_inc(&current->signal->live);
2469 			refcount_inc(&current->signal->sigcnt);
2470 			task_join_group_stop(p);
2471 			list_add_tail_rcu(&p->thread_group,
2472 					  &p->group_leader->thread_group);
2473 			list_add_tail_rcu(&p->thread_node,
2474 					  &p->signal->thread_head);
2475 		}
2476 		attach_pid(p, PIDTYPE_PID);
2477 		nr_threads++;
2478 	}
2479 	total_forks++;
2480 	hlist_del_init(&delayed.node);
2481 	spin_unlock(&current->sighand->siglock);
2482 	syscall_tracepoint_update(p);
2483 	write_unlock_irq(&tasklist_lock);
2484 
2485 	if (pidfile)
2486 		fd_install(pidfd, pidfile);
2487 
2488 	proc_fork_connector(p);
2489 	sched_post_fork(p);
2490 	cgroup_post_fork(p, args);
2491 	perf_event_fork(p);
2492 
2493 	trace_task_newtask(p, clone_flags);
2494 	uprobe_copy_process(p, clone_flags);
2495 
2496 	copy_oom_score_adj(clone_flags, p);
2497 
2498 	return p;
2499 
2500 bad_fork_cancel_cgroup:
2501 	sched_core_free(p);
2502 	spin_unlock(&current->sighand->siglock);
2503 	write_unlock_irq(&tasklist_lock);
2504 	cgroup_cancel_fork(p, args);
2505 bad_fork_put_pidfd:
2506 	if (clone_flags & CLONE_PIDFD) {
2507 		fput(pidfile);
2508 		put_unused_fd(pidfd);
2509 	}
2510 bad_fork_free_pid:
2511 	if (pid != &init_struct_pid)
2512 		free_pid(pid);
2513 bad_fork_cleanup_thread:
2514 	exit_thread(p);
2515 bad_fork_cleanup_io:
2516 	if (p->io_context)
2517 		exit_io_context(p);
2518 bad_fork_cleanup_namespaces:
2519 	exit_task_namespaces(p);
2520 bad_fork_cleanup_mm:
2521 	if (p->mm) {
2522 		mm_clear_owner(p->mm, p);
2523 		mmput(p->mm);
2524 	}
2525 bad_fork_cleanup_signal:
2526 	if (!(clone_flags & CLONE_THREAD))
2527 		free_signal_struct(p->signal);
2528 bad_fork_cleanup_sighand:
2529 	__cleanup_sighand(p->sighand);
2530 bad_fork_cleanup_fs:
2531 	exit_fs(p); /* blocking */
2532 bad_fork_cleanup_files:
2533 	exit_files(p); /* blocking */
2534 bad_fork_cleanup_semundo:
2535 	exit_sem(p);
2536 bad_fork_cleanup_security:
2537 	security_task_free(p);
2538 bad_fork_cleanup_audit:
2539 	audit_free(p);
2540 bad_fork_cleanup_perf:
2541 	perf_event_free_task(p);
2542 bad_fork_cleanup_policy:
2543 	lockdep_free_task(p);
2544 #ifdef CONFIG_NUMA
2545 	mpol_put(p->mempolicy);
2546 bad_fork_cleanup_threadgroup_lock:
2547 #endif
2548 	delayacct_tsk_free(p);
2549 bad_fork_cleanup_count:
2550 	dec_rlimit_ucounts(task_ucounts(p), UCOUNT_RLIMIT_NPROC, 1);
2551 	exit_creds(p);
2552 bad_fork_free:
2553 	WRITE_ONCE(p->__state, TASK_DEAD);
2554 	put_task_stack(p);
2555 	delayed_free_task(p);
2556 fork_out:
2557 	spin_lock_irq(&current->sighand->siglock);
2558 	hlist_del_init(&delayed.node);
2559 	spin_unlock_irq(&current->sighand->siglock);
2560 	return ERR_PTR(retval);
2561 }
2562 
init_idle_pids(struct task_struct * idle)2563 static inline void init_idle_pids(struct task_struct *idle)
2564 {
2565 	enum pid_type type;
2566 
2567 	for (type = PIDTYPE_PID; type < PIDTYPE_MAX; ++type) {
2568 		INIT_HLIST_NODE(&idle->pid_links[type]); /* not really needed */
2569 		init_task_pid(idle, type, &init_struct_pid);
2570 	}
2571 }
2572 
fork_idle(int cpu)2573 struct task_struct * __init fork_idle(int cpu)
2574 {
2575 	struct task_struct *task;
2576 	struct kernel_clone_args args = {
2577 		.flags = CLONE_VM,
2578 	};
2579 
2580 	task = copy_process(&init_struct_pid, 0, cpu_to_node(cpu), &args);
2581 	if (!IS_ERR(task)) {
2582 		init_idle_pids(task);
2583 		init_idle(task, cpu);
2584 	}
2585 
2586 	return task;
2587 }
2588 
2589 /*
2590  * This is like kernel_clone(), but shaved down and tailored to just
2591  * creating io_uring workers. It returns a created task, or an error pointer.
2592  * The returned task is inactive, and the caller must fire it up through
2593  * wake_up_new_task(p). All signals are blocked in the created task.
2594  */
create_io_thread(int (* fn)(void *),void * arg,int node)2595 struct task_struct *create_io_thread(int (*fn)(void *), void *arg, int node)
2596 {
2597 	unsigned long flags = CLONE_FS|CLONE_FILES|CLONE_SIGHAND|CLONE_THREAD|
2598 				CLONE_IO;
2599 	struct kernel_clone_args args = {
2600 		.flags		= ((lower_32_bits(flags) | CLONE_VM |
2601 				    CLONE_UNTRACED) & ~CSIGNAL),
2602 		.exit_signal	= (lower_32_bits(flags) & CSIGNAL),
2603 		.stack		= (unsigned long)fn,
2604 		.stack_size	= (unsigned long)arg,
2605 		.io_thread	= 1,
2606 	};
2607 
2608 	return copy_process(NULL, 0, node, &args);
2609 }
2610 
2611 /*
2612  *  Ok, this is the main fork-routine.
2613  *
2614  * It copies the process, and if successful kick-starts
2615  * it and waits for it to finish using the VM if required.
2616  *
2617  * args->exit_signal is expected to be checked for sanity by the caller.
2618  */
kernel_clone(struct kernel_clone_args * args)2619 pid_t kernel_clone(struct kernel_clone_args *args)
2620 {
2621 	u64 clone_flags = args->flags;
2622 	struct completion vfork;
2623 	struct pid *pid;
2624 	struct task_struct *p;
2625 	int trace = 0;
2626 	pid_t nr;
2627 
2628 	/*
2629 	 * For legacy clone() calls, CLONE_PIDFD uses the parent_tid argument
2630 	 * to return the pidfd. Hence, CLONE_PIDFD and CLONE_PARENT_SETTID are
2631 	 * mutually exclusive. With clone3() CLONE_PIDFD has grown a separate
2632 	 * field in struct clone_args and it still doesn't make sense to have
2633 	 * them both point at the same memory location. Performing this check
2634 	 * here has the advantage that we don't need to have a separate helper
2635 	 * to check for legacy clone().
2636 	 */
2637 	if ((args->flags & CLONE_PIDFD) &&
2638 	    (args->flags & CLONE_PARENT_SETTID) &&
2639 	    (args->pidfd == args->parent_tid))
2640 		return -EINVAL;
2641 
2642 	/*
2643 	 * Determine whether and which event to report to ptracer.  When
2644 	 * called from kernel_thread or CLONE_UNTRACED is explicitly
2645 	 * requested, no event is reported; otherwise, report if the event
2646 	 * for the type of forking is enabled.
2647 	 */
2648 	if (!(clone_flags & CLONE_UNTRACED)) {
2649 		if (clone_flags & CLONE_VFORK)
2650 			trace = PTRACE_EVENT_VFORK;
2651 		else if (args->exit_signal != SIGCHLD)
2652 			trace = PTRACE_EVENT_CLONE;
2653 		else
2654 			trace = PTRACE_EVENT_FORK;
2655 
2656 		if (likely(!ptrace_event_enabled(current, trace)))
2657 			trace = 0;
2658 	}
2659 
2660 	p = copy_process(NULL, trace, NUMA_NO_NODE, args);
2661 	add_latent_entropy();
2662 
2663 	if (IS_ERR(p))
2664 		return PTR_ERR(p);
2665 
2666 	cpufreq_task_times_alloc(p);
2667 
2668 	/*
2669 	 * Do this prior waking up the new thread - the thread pointer
2670 	 * might get invalid after that point, if the thread exits quickly.
2671 	 */
2672 	trace_sched_process_fork(current, p);
2673 
2674 	pid = get_task_pid(p, PIDTYPE_PID);
2675 	nr = pid_vnr(pid);
2676 
2677 	if (clone_flags & CLONE_PARENT_SETTID)
2678 		put_user(nr, args->parent_tid);
2679 
2680 	if (clone_flags & CLONE_VFORK) {
2681 		p->vfork_done = &vfork;
2682 		init_completion(&vfork);
2683 		get_task_struct(p);
2684 	}
2685 
2686 	if (IS_ENABLED(CONFIG_LRU_GEN) && !(clone_flags & CLONE_VM)) {
2687 		/* lock the task to synchronize with memcg migration */
2688 		task_lock(p);
2689 		lru_gen_add_mm(p->mm);
2690 		task_unlock(p);
2691 	}
2692 
2693 	wake_up_new_task(p);
2694 
2695 	/* forking complete and child started to run, tell ptracer */
2696 	if (unlikely(trace))
2697 		ptrace_event_pid(trace, pid);
2698 
2699 	if (clone_flags & CLONE_VFORK) {
2700 		if (!wait_for_vfork_done(p, &vfork))
2701 			ptrace_event_pid(PTRACE_EVENT_VFORK_DONE, pid);
2702 	}
2703 
2704 	put_pid(pid);
2705 	return nr;
2706 }
2707 
2708 /*
2709  * Create a kernel thread.
2710  */
kernel_thread(int (* fn)(void *),void * arg,unsigned long flags)2711 pid_t kernel_thread(int (*fn)(void *), void *arg, unsigned long flags)
2712 {
2713 	struct kernel_clone_args args = {
2714 		.flags		= ((lower_32_bits(flags) | CLONE_VM |
2715 				    CLONE_UNTRACED) & ~CSIGNAL),
2716 		.exit_signal	= (lower_32_bits(flags) & CSIGNAL),
2717 		.stack		= (unsigned long)fn,
2718 		.stack_size	= (unsigned long)arg,
2719 	};
2720 
2721 	return kernel_clone(&args);
2722 }
2723 
2724 #ifdef __ARCH_WANT_SYS_FORK
SYSCALL_DEFINE0(fork)2725 SYSCALL_DEFINE0(fork)
2726 {
2727 #ifdef CONFIG_MMU
2728 	struct kernel_clone_args args = {
2729 		.exit_signal = SIGCHLD,
2730 	};
2731 
2732 	return kernel_clone(&args);
2733 #else
2734 	/* can not support in nommu mode */
2735 	return -EINVAL;
2736 #endif
2737 }
2738 #endif
2739 
2740 #ifdef __ARCH_WANT_SYS_VFORK
SYSCALL_DEFINE0(vfork)2741 SYSCALL_DEFINE0(vfork)
2742 {
2743 	struct kernel_clone_args args = {
2744 		.flags		= CLONE_VFORK | CLONE_VM,
2745 		.exit_signal	= SIGCHLD,
2746 	};
2747 
2748 	return kernel_clone(&args);
2749 }
2750 #endif
2751 
2752 #ifdef __ARCH_WANT_SYS_CLONE
2753 #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)2754 SYSCALL_DEFINE5(clone, unsigned long, clone_flags, unsigned long, newsp,
2755 		 int __user *, parent_tidptr,
2756 		 unsigned long, tls,
2757 		 int __user *, child_tidptr)
2758 #elif defined(CONFIG_CLONE_BACKWARDS2)
2759 SYSCALL_DEFINE5(clone, unsigned long, newsp, unsigned long, clone_flags,
2760 		 int __user *, parent_tidptr,
2761 		 int __user *, child_tidptr,
2762 		 unsigned long, tls)
2763 #elif defined(CONFIG_CLONE_BACKWARDS3)
2764 SYSCALL_DEFINE6(clone, unsigned long, clone_flags, unsigned long, newsp,
2765 		int, stack_size,
2766 		int __user *, parent_tidptr,
2767 		int __user *, child_tidptr,
2768 		unsigned long, tls)
2769 #else
2770 SYSCALL_DEFINE5(clone, unsigned long, clone_flags, unsigned long, newsp,
2771 		 int __user *, parent_tidptr,
2772 		 int __user *, child_tidptr,
2773 		 unsigned long, tls)
2774 #endif
2775 {
2776 	struct kernel_clone_args args = {
2777 		.flags		= (lower_32_bits(clone_flags) & ~CSIGNAL),
2778 		.pidfd		= parent_tidptr,
2779 		.child_tid	= child_tidptr,
2780 		.parent_tid	= parent_tidptr,
2781 		.exit_signal	= (lower_32_bits(clone_flags) & CSIGNAL),
2782 		.stack		= newsp,
2783 		.tls		= tls,
2784 	};
2785 
2786 	return kernel_clone(&args);
2787 }
2788 #endif
2789 
2790 #ifdef __ARCH_WANT_SYS_CLONE3
2791 
copy_clone_args_from_user(struct kernel_clone_args * kargs,struct clone_args __user * uargs,size_t usize)2792 noinline static int copy_clone_args_from_user(struct kernel_clone_args *kargs,
2793 					      struct clone_args __user *uargs,
2794 					      size_t usize)
2795 {
2796 	int err;
2797 	struct clone_args args;
2798 	pid_t *kset_tid = kargs->set_tid;
2799 
2800 	BUILD_BUG_ON(offsetofend(struct clone_args, tls) !=
2801 		     CLONE_ARGS_SIZE_VER0);
2802 	BUILD_BUG_ON(offsetofend(struct clone_args, set_tid_size) !=
2803 		     CLONE_ARGS_SIZE_VER1);
2804 	BUILD_BUG_ON(offsetofend(struct clone_args, cgroup) !=
2805 		     CLONE_ARGS_SIZE_VER2);
2806 	BUILD_BUG_ON(sizeof(struct clone_args) != CLONE_ARGS_SIZE_VER2);
2807 
2808 	if (unlikely(usize > PAGE_SIZE))
2809 		return -E2BIG;
2810 	if (unlikely(usize < CLONE_ARGS_SIZE_VER0))
2811 		return -EINVAL;
2812 
2813 	err = copy_struct_from_user(&args, sizeof(args), uargs, usize);
2814 	if (err)
2815 		return err;
2816 
2817 	if (unlikely(args.set_tid_size > MAX_PID_NS_LEVEL))
2818 		return -EINVAL;
2819 
2820 	if (unlikely(!args.set_tid && args.set_tid_size > 0))
2821 		return -EINVAL;
2822 
2823 	if (unlikely(args.set_tid && args.set_tid_size == 0))
2824 		return -EINVAL;
2825 
2826 	/*
2827 	 * Verify that higher 32bits of exit_signal are unset and that
2828 	 * it is a valid signal
2829 	 */
2830 	if (unlikely((args.exit_signal & ~((u64)CSIGNAL)) ||
2831 		     !valid_signal(args.exit_signal)))
2832 		return -EINVAL;
2833 
2834 	if ((args.flags & CLONE_INTO_CGROUP) &&
2835 	    (args.cgroup > INT_MAX || usize < CLONE_ARGS_SIZE_VER2))
2836 		return -EINVAL;
2837 
2838 	*kargs = (struct kernel_clone_args){
2839 		.flags		= args.flags,
2840 		.pidfd		= u64_to_user_ptr(args.pidfd),
2841 		.child_tid	= u64_to_user_ptr(args.child_tid),
2842 		.parent_tid	= u64_to_user_ptr(args.parent_tid),
2843 		.exit_signal	= args.exit_signal,
2844 		.stack		= args.stack,
2845 		.stack_size	= args.stack_size,
2846 		.tls		= args.tls,
2847 		.set_tid_size	= args.set_tid_size,
2848 		.cgroup		= args.cgroup,
2849 	};
2850 
2851 	if (args.set_tid &&
2852 		copy_from_user(kset_tid, u64_to_user_ptr(args.set_tid),
2853 			(kargs->set_tid_size * sizeof(pid_t))))
2854 		return -EFAULT;
2855 
2856 	kargs->set_tid = kset_tid;
2857 
2858 	return 0;
2859 }
2860 
2861 /**
2862  * clone3_stack_valid - check and prepare stack
2863  * @kargs: kernel clone args
2864  *
2865  * Verify that the stack arguments userspace gave us are sane.
2866  * In addition, set the stack direction for userspace since it's easy for us to
2867  * determine.
2868  */
clone3_stack_valid(struct kernel_clone_args * kargs)2869 static inline bool clone3_stack_valid(struct kernel_clone_args *kargs)
2870 {
2871 	if (kargs->stack == 0) {
2872 		if (kargs->stack_size > 0)
2873 			return false;
2874 	} else {
2875 		if (kargs->stack_size == 0)
2876 			return false;
2877 
2878 		if (!access_ok((void __user *)kargs->stack, kargs->stack_size))
2879 			return false;
2880 
2881 #if !defined(CONFIG_STACK_GROWSUP) && !defined(CONFIG_IA64)
2882 		kargs->stack += kargs->stack_size;
2883 #endif
2884 	}
2885 
2886 	return true;
2887 }
2888 
clone3_args_valid(struct kernel_clone_args * kargs)2889 static bool clone3_args_valid(struct kernel_clone_args *kargs)
2890 {
2891 	/* Verify that no unknown flags are passed along. */
2892 	if (kargs->flags &
2893 	    ~(CLONE_LEGACY_FLAGS | CLONE_CLEAR_SIGHAND | CLONE_INTO_CGROUP))
2894 		return false;
2895 
2896 	/*
2897 	 * - make the CLONE_DETACHED bit reusable for clone3
2898 	 * - make the CSIGNAL bits reusable for clone3
2899 	 */
2900 	if (kargs->flags & (CLONE_DETACHED | (CSIGNAL & (~CLONE_NEWTIME))))
2901 		return false;
2902 
2903 	if ((kargs->flags & (CLONE_SIGHAND | CLONE_CLEAR_SIGHAND)) ==
2904 	    (CLONE_SIGHAND | CLONE_CLEAR_SIGHAND))
2905 		return false;
2906 
2907 	if ((kargs->flags & (CLONE_THREAD | CLONE_PARENT)) &&
2908 	    kargs->exit_signal)
2909 		return false;
2910 
2911 	if (!clone3_stack_valid(kargs))
2912 		return false;
2913 
2914 	return true;
2915 }
2916 
2917 /**
2918  * clone3 - create a new process with specific properties
2919  * @uargs: argument structure
2920  * @size:  size of @uargs
2921  *
2922  * clone3() is the extensible successor to clone()/clone2().
2923  * It takes a struct as argument that is versioned by its size.
2924  *
2925  * Return: On success, a positive PID for the child process.
2926  *         On error, a negative errno number.
2927  */
SYSCALL_DEFINE2(clone3,struct clone_args __user *,uargs,size_t,size)2928 SYSCALL_DEFINE2(clone3, struct clone_args __user *, uargs, size_t, size)
2929 {
2930 	int err;
2931 
2932 	struct kernel_clone_args kargs;
2933 	pid_t set_tid[MAX_PID_NS_LEVEL];
2934 
2935 	kargs.set_tid = set_tid;
2936 
2937 	err = copy_clone_args_from_user(&kargs, uargs, size);
2938 	if (err)
2939 		return err;
2940 
2941 	if (!clone3_args_valid(&kargs))
2942 		return -EINVAL;
2943 
2944 	return kernel_clone(&kargs);
2945 }
2946 #endif
2947 
walk_process_tree(struct task_struct * top,proc_visitor visitor,void * data)2948 void walk_process_tree(struct task_struct *top, proc_visitor visitor, void *data)
2949 {
2950 	struct task_struct *leader, *parent, *child;
2951 	int res;
2952 
2953 	read_lock(&tasklist_lock);
2954 	leader = top = top->group_leader;
2955 down:
2956 	for_each_thread(leader, parent) {
2957 		list_for_each_entry(child, &parent->children, sibling) {
2958 			res = visitor(child, data);
2959 			if (res) {
2960 				if (res < 0)
2961 					goto out;
2962 				leader = child;
2963 				goto down;
2964 			}
2965 up:
2966 			;
2967 		}
2968 	}
2969 
2970 	if (leader != top) {
2971 		child = leader;
2972 		parent = child->real_parent;
2973 		leader = parent->group_leader;
2974 		goto up;
2975 	}
2976 out:
2977 	read_unlock(&tasklist_lock);
2978 }
2979 
2980 #ifndef ARCH_MIN_MMSTRUCT_ALIGN
2981 #define ARCH_MIN_MMSTRUCT_ALIGN 0
2982 #endif
2983 
sighand_ctor(void * data)2984 static void sighand_ctor(void *data)
2985 {
2986 	struct sighand_struct *sighand = data;
2987 
2988 	spin_lock_init(&sighand->siglock);
2989 	init_waitqueue_head(&sighand->signalfd_wqh);
2990 }
2991 
mm_cache_init(void)2992 void __init mm_cache_init(void)
2993 {
2994 	unsigned int mm_size;
2995 
2996 	/*
2997 	 * The mm_cpumask is located at the end of mm_struct, and is
2998 	 * dynamically sized based on the maximum CPU number this system
2999 	 * can have, taking hotplug into account (nr_cpu_ids).
3000 	 */
3001 	mm_size = sizeof(struct mm_struct) + cpumask_size();
3002 
3003 	mm_cachep = kmem_cache_create_usercopy("mm_struct",
3004 			mm_size, ARCH_MIN_MMSTRUCT_ALIGN,
3005 			SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_ACCOUNT,
3006 			offsetof(struct mm_struct, saved_auxv),
3007 			sizeof_field(struct mm_struct, saved_auxv),
3008 			NULL);
3009 }
3010 
proc_caches_init(void)3011 void __init proc_caches_init(void)
3012 {
3013 	sighand_cachep = kmem_cache_create("sighand_cache",
3014 			sizeof(struct sighand_struct), 0,
3015 			SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_TYPESAFE_BY_RCU|
3016 			SLAB_ACCOUNT, sighand_ctor);
3017 	signal_cachep = kmem_cache_create("signal_cache",
3018 			sizeof(struct signal_struct), 0,
3019 			SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_ACCOUNT,
3020 			NULL);
3021 	files_cachep = kmem_cache_create("files_cache",
3022 			sizeof(struct files_struct), 0,
3023 			SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_ACCOUNT,
3024 			NULL);
3025 	fs_cachep = kmem_cache_create("fs_cache",
3026 			sizeof(struct fs_struct), 0,
3027 			SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_ACCOUNT,
3028 			NULL);
3029 
3030 	vm_area_cachep = KMEM_CACHE(vm_area_struct, SLAB_PANIC|SLAB_ACCOUNT);
3031 	mmap_init();
3032 	nsproxy_cache_init();
3033 }
3034 
3035 /*
3036  * Check constraints on flags passed to the unshare system call.
3037  */
check_unshare_flags(unsigned long unshare_flags)3038 static int check_unshare_flags(unsigned long unshare_flags)
3039 {
3040 	if (unshare_flags & ~(CLONE_THREAD|CLONE_FS|CLONE_NEWNS|CLONE_SIGHAND|
3041 				CLONE_VM|CLONE_FILES|CLONE_SYSVSEM|
3042 				CLONE_NEWUTS|CLONE_NEWIPC|CLONE_NEWNET|
3043 				CLONE_NEWUSER|CLONE_NEWPID|CLONE_NEWCGROUP|
3044 				CLONE_NEWTIME))
3045 		return -EINVAL;
3046 	/*
3047 	 * Not implemented, but pretend it works if there is nothing
3048 	 * to unshare.  Note that unsharing the address space or the
3049 	 * signal handlers also need to unshare the signal queues (aka
3050 	 * CLONE_THREAD).
3051 	 */
3052 	if (unshare_flags & (CLONE_THREAD | CLONE_SIGHAND | CLONE_VM)) {
3053 		if (!thread_group_empty(current))
3054 			return -EINVAL;
3055 	}
3056 	if (unshare_flags & (CLONE_SIGHAND | CLONE_VM)) {
3057 		if (refcount_read(&current->sighand->count) > 1)
3058 			return -EINVAL;
3059 	}
3060 	if (unshare_flags & CLONE_VM) {
3061 		if (!current_is_single_threaded())
3062 			return -EINVAL;
3063 	}
3064 
3065 	return 0;
3066 }
3067 
3068 /*
3069  * Unshare the filesystem structure if it is being shared
3070  */
unshare_fs(unsigned long unshare_flags,struct fs_struct ** new_fsp)3071 static int unshare_fs(unsigned long unshare_flags, struct fs_struct **new_fsp)
3072 {
3073 	struct fs_struct *fs = current->fs;
3074 
3075 	if (!(unshare_flags & CLONE_FS) || !fs)
3076 		return 0;
3077 
3078 	/* don't need lock here; in the worst case we'll do useless copy */
3079 	if (fs->users == 1)
3080 		return 0;
3081 
3082 	*new_fsp = copy_fs_struct(fs);
3083 	if (!*new_fsp)
3084 		return -ENOMEM;
3085 
3086 	return 0;
3087 }
3088 
3089 /*
3090  * Unshare file descriptor table if it is being shared
3091  */
unshare_fd(unsigned long unshare_flags,unsigned int max_fds,struct files_struct ** new_fdp)3092 int unshare_fd(unsigned long unshare_flags, unsigned int max_fds,
3093 	       struct files_struct **new_fdp)
3094 {
3095 	struct files_struct *fd = current->files;
3096 	int error = 0;
3097 
3098 	if ((unshare_flags & CLONE_FILES) &&
3099 	    (fd && atomic_read(&fd->count) > 1)) {
3100 		*new_fdp = dup_fd(fd, max_fds, &error);
3101 		if (!*new_fdp)
3102 			return error;
3103 	}
3104 
3105 	return 0;
3106 }
3107 
3108 /*
3109  * unshare allows a process to 'unshare' part of the process
3110  * context which was originally shared using clone.  copy_*
3111  * functions used by kernel_clone() cannot be used here directly
3112  * because they modify an inactive task_struct that is being
3113  * constructed. Here we are modifying the current, active,
3114  * task_struct.
3115  */
ksys_unshare(unsigned long unshare_flags)3116 int ksys_unshare(unsigned long unshare_flags)
3117 {
3118 	struct fs_struct *fs, *new_fs = NULL;
3119 	struct files_struct *fd, *new_fd = NULL;
3120 	struct cred *new_cred = NULL;
3121 	struct nsproxy *new_nsproxy = NULL;
3122 	int do_sysvsem = 0;
3123 	int err;
3124 
3125 	/*
3126 	 * If unsharing a user namespace must also unshare the thread group
3127 	 * and unshare the filesystem root and working directories.
3128 	 */
3129 	if (unshare_flags & CLONE_NEWUSER)
3130 		unshare_flags |= CLONE_THREAD | CLONE_FS;
3131 	/*
3132 	 * If unsharing vm, must also unshare signal handlers.
3133 	 */
3134 	if (unshare_flags & CLONE_VM)
3135 		unshare_flags |= CLONE_SIGHAND;
3136 	/*
3137 	 * If unsharing a signal handlers, must also unshare the signal queues.
3138 	 */
3139 	if (unshare_flags & CLONE_SIGHAND)
3140 		unshare_flags |= CLONE_THREAD;
3141 	/*
3142 	 * If unsharing namespace, must also unshare filesystem information.
3143 	 */
3144 	if (unshare_flags & CLONE_NEWNS)
3145 		unshare_flags |= CLONE_FS;
3146 
3147 	err = check_unshare_flags(unshare_flags);
3148 	if (err)
3149 		goto bad_unshare_out;
3150 	/*
3151 	 * CLONE_NEWIPC must also detach from the undolist: after switching
3152 	 * to a new ipc namespace, the semaphore arrays from the old
3153 	 * namespace are unreachable.
3154 	 */
3155 	if (unshare_flags & (CLONE_NEWIPC|CLONE_SYSVSEM))
3156 		do_sysvsem = 1;
3157 	err = unshare_fs(unshare_flags, &new_fs);
3158 	if (err)
3159 		goto bad_unshare_out;
3160 	err = unshare_fd(unshare_flags, NR_OPEN_MAX, &new_fd);
3161 	if (err)
3162 		goto bad_unshare_cleanup_fs;
3163 	err = unshare_userns(unshare_flags, &new_cred);
3164 	if (err)
3165 		goto bad_unshare_cleanup_fd;
3166 	err = unshare_nsproxy_namespaces(unshare_flags, &new_nsproxy,
3167 					 new_cred, new_fs);
3168 	if (err)
3169 		goto bad_unshare_cleanup_cred;
3170 
3171 	if (new_cred) {
3172 		err = set_cred_ucounts(new_cred);
3173 		if (err)
3174 			goto bad_unshare_cleanup_cred;
3175 	}
3176 
3177 	if (new_fs || new_fd || do_sysvsem || new_cred || new_nsproxy) {
3178 		if (do_sysvsem) {
3179 			/*
3180 			 * CLONE_SYSVSEM is equivalent to sys_exit().
3181 			 */
3182 			exit_sem(current);
3183 		}
3184 		if (unshare_flags & CLONE_NEWIPC) {
3185 			/* Orphan segments in old ns (see sem above). */
3186 			exit_shm(current);
3187 			shm_init_task(current);
3188 		}
3189 
3190 		if (new_nsproxy)
3191 			switch_task_namespaces(current, new_nsproxy);
3192 
3193 		task_lock(current);
3194 
3195 		if (new_fs) {
3196 			fs = current->fs;
3197 			spin_lock(&fs->lock);
3198 			current->fs = new_fs;
3199 			if (--fs->users)
3200 				new_fs = NULL;
3201 			else
3202 				new_fs = fs;
3203 			spin_unlock(&fs->lock);
3204 		}
3205 
3206 		if (new_fd) {
3207 			fd = current->files;
3208 			current->files = new_fd;
3209 			new_fd = fd;
3210 		}
3211 
3212 		task_unlock(current);
3213 
3214 		if (new_cred) {
3215 			/* Install the new user namespace */
3216 			commit_creds(new_cred);
3217 			new_cred = NULL;
3218 		}
3219 	}
3220 
3221 	perf_event_namespaces(current);
3222 
3223 bad_unshare_cleanup_cred:
3224 	if (new_cred)
3225 		put_cred(new_cred);
3226 bad_unshare_cleanup_fd:
3227 	if (new_fd)
3228 		put_files_struct(new_fd);
3229 
3230 bad_unshare_cleanup_fs:
3231 	if (new_fs)
3232 		free_fs_struct(new_fs);
3233 
3234 bad_unshare_out:
3235 	return err;
3236 }
3237 
SYSCALL_DEFINE1(unshare,unsigned long,unshare_flags)3238 SYSCALL_DEFINE1(unshare, unsigned long, unshare_flags)
3239 {
3240 	return ksys_unshare(unshare_flags);
3241 }
3242 
3243 /*
3244  *	Helper to unshare the files of the current task.
3245  *	We don't want to expose copy_files internals to
3246  *	the exec layer of the kernel.
3247  */
3248 
unshare_files(void)3249 int unshare_files(void)
3250 {
3251 	struct task_struct *task = current;
3252 	struct files_struct *old, *copy = NULL;
3253 	int error;
3254 
3255 	error = unshare_fd(CLONE_FILES, NR_OPEN_MAX, &copy);
3256 	if (error || !copy)
3257 		return error;
3258 
3259 	old = task->files;
3260 	task_lock(task);
3261 	task->files = copy;
3262 	task_unlock(task);
3263 	put_files_struct(old);
3264 	return 0;
3265 }
3266 
sysctl_max_threads(struct ctl_table * table,int write,void * buffer,size_t * lenp,loff_t * ppos)3267 int sysctl_max_threads(struct ctl_table *table, int write,
3268 		       void *buffer, size_t *lenp, loff_t *ppos)
3269 {
3270 	struct ctl_table t;
3271 	int ret;
3272 	int threads = max_threads;
3273 	int min = 1;
3274 	int max = MAX_THREADS;
3275 
3276 	t = *table;
3277 	t.data = &threads;
3278 	t.extra1 = &min;
3279 	t.extra2 = &max;
3280 
3281 	ret = proc_dointvec_minmax(&t, write, buffer, lenp, ppos);
3282 	if (ret || !write)
3283 		return ret;
3284 
3285 	max_threads = threads;
3286 
3287 	return 0;
3288 }
3289