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