• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  *  linux/kernel/fork.c
3  *
4  *  Copyright (C) 1991, 1992  Linus Torvalds
5  */
6 
7 /*
8  *  'fork.c' contains the help-routines for the 'fork' system call
9  * (see also entry.S and others).
10  * Fork is rather simple, once you get the hang of it, but the memory
11  * management can be a bitch. See 'mm/memory.c': 'copy_page_range()'
12  */
13 
14 #include <linux/slab.h>
15 #include <linux/sched/autogroup.h>
16 #include <linux/sched/mm.h>
17 #include <linux/sched/coredump.h>
18 #include <linux/sched/user.h>
19 #include <linux/sched/numa_balancing.h>
20 #include <linux/sched/stat.h>
21 #include <linux/sched/task.h>
22 #include <linux/sched/task_stack.h>
23 #include <linux/sched/cputime.h>
24 #include <linux/rtmutex.h>
25 #include <linux/init.h>
26 #include <linux/unistd.h>
27 #include <linux/module.h>
28 #include <linux/vmalloc.h>
29 #include <linux/completion.h>
30 #include <linux/personality.h>
31 #include <linux/mempolicy.h>
32 #include <linux/sem.h>
33 #include <linux/file.h>
34 #include <linux/fdtable.h>
35 #include <linux/iocontext.h>
36 #include <linux/key.h>
37 #include <linux/binfmts.h>
38 #include <linux/mman.h>
39 #include <linux/mmu_notifier.h>
40 #include <linux/hmm.h>
41 #include <linux/fs.h>
42 #include <linux/mm.h>
43 #include <linux/vmacache.h>
44 #include <linux/nsproxy.h>
45 #include <linux/capability.h>
46 #include <linux/cpu.h>
47 #include <linux/cgroup.h>
48 #include <linux/security.h>
49 #include <linux/hugetlb.h>
50 #include <linux/seccomp.h>
51 #include <linux/swap.h>
52 #include <linux/syscalls.h>
53 #include <linux/jiffies.h>
54 #include <linux/futex.h>
55 #include <linux/compat.h>
56 #include <linux/kthread.h>
57 #include <linux/task_io_accounting_ops.h>
58 #include <linux/rcupdate.h>
59 #include <linux/ptrace.h>
60 #include <linux/mount.h>
61 #include <linux/audit.h>
62 #include <linux/memcontrol.h>
63 #include <linux/ftrace.h>
64 #include <linux/proc_fs.h>
65 #include <linux/profile.h>
66 #include <linux/rmap.h>
67 #include <linux/ksm.h>
68 #include <linux/acct.h>
69 #include <linux/userfaultfd_k.h>
70 #include <linux/tsacct_kern.h>
71 #include <linux/cn_proc.h>
72 #include <linux/freezer.h>
73 #include <linux/delayacct.h>
74 #include <linux/taskstats_kern.h>
75 #include <linux/random.h>
76 #include <linux/tty.h>
77 #include <linux/blkdev.h>
78 #include <linux/fs_struct.h>
79 #include <linux/magic.h>
80 #include <linux/perf_event.h>
81 #include <linux/posix-timers.h>
82 #include <linux/user-return-notifier.h>
83 #include <linux/oom.h>
84 #include <linux/khugepaged.h>
85 #include <linux/signalfd.h>
86 #include <linux/uprobes.h>
87 #include <linux/aio.h>
88 #include <linux/compiler.h>
89 #include <linux/sysctl.h>
90 #include <linux/kcov.h>
91 #include <linux/livepatch.h>
92 #include <linux/thread_info.h>
93 #include <linux/cpufreq_times.h>
94 
95 #include <asm/pgtable.h>
96 #include <asm/pgalloc.h>
97 #include <linux/uaccess.h>
98 #include <asm/mmu_context.h>
99 #include <asm/cacheflush.h>
100 #include <asm/tlbflush.h>
101 
102 #include <trace/events/sched.h>
103 
104 #define CREATE_TRACE_POINTS
105 #include <trace/events/task.h>
106 
107 /*
108  * Minimum number of threads to boot the kernel
109  */
110 #define MIN_THREADS 20
111 
112 /*
113  * Maximum number of threads
114  */
115 #define MAX_THREADS FUTEX_TID_MASK
116 
117 /*
118  * Protected counters by write_lock_irq(&tasklist_lock)
119  */
120 unsigned long total_forks;	/* Handle normal Linux uptimes. */
121 int nr_threads;			/* The idle threads do not count.. */
122 
123 int max_threads;		/* tunable limit on nr_threads */
124 
125 DEFINE_PER_CPU(unsigned long, process_counts) = 0;
126 
127 __cacheline_aligned DEFINE_RWLOCK(tasklist_lock);  /* outer */
128 
129 #ifdef CONFIG_PROVE_RCU
lockdep_tasklist_lock_is_held(void)130 int lockdep_tasklist_lock_is_held(void)
131 {
132 	return lockdep_is_held(&tasklist_lock);
133 }
134 EXPORT_SYMBOL_GPL(lockdep_tasklist_lock_is_held);
135 #endif /* #ifdef CONFIG_PROVE_RCU */
136 
nr_processes(void)137 int nr_processes(void)
138 {
139 	int cpu;
140 	int total = 0;
141 
142 	for_each_possible_cpu(cpu)
143 		total += per_cpu(process_counts, cpu);
144 
145 	return total;
146 }
147 
arch_release_task_struct(struct task_struct * tsk)148 void __weak arch_release_task_struct(struct task_struct *tsk)
149 {
150 }
151 
152 #ifndef CONFIG_ARCH_TASK_STRUCT_ALLOCATOR
153 static struct kmem_cache *task_struct_cachep;
154 
alloc_task_struct_node(int node)155 static inline struct task_struct *alloc_task_struct_node(int node)
156 {
157 	return kmem_cache_alloc_node(task_struct_cachep, GFP_KERNEL, node);
158 }
159 
free_task_struct(struct task_struct * tsk)160 static inline void free_task_struct(struct task_struct *tsk)
161 {
162 	kmem_cache_free(task_struct_cachep, tsk);
163 }
164 #endif
165 
166 #ifndef CONFIG_ARCH_THREAD_STACK_ALLOCATOR
167 
168 /*
169  * Allocate pages if THREAD_SIZE is >= PAGE_SIZE, otherwise use a
170  * kmemcache based allocator.
171  */
172 # if THREAD_SIZE >= PAGE_SIZE || defined(CONFIG_VMAP_STACK)
173 
174 #ifdef CONFIG_VMAP_STACK
175 /*
176  * vmalloc() is a bit slow, and calling vfree() enough times will force a TLB
177  * flush.  Try to minimize the number of calls by caching stacks.
178  */
179 #define NR_CACHED_STACKS 2
180 static DEFINE_PER_CPU(struct vm_struct *, cached_stacks[NR_CACHED_STACKS]);
181 
free_vm_stack_cache(unsigned int cpu)182 static int free_vm_stack_cache(unsigned int cpu)
183 {
184 	struct vm_struct **cached_vm_stacks = per_cpu_ptr(cached_stacks, cpu);
185 	int i;
186 
187 	for (i = 0; i < NR_CACHED_STACKS; i++) {
188 		struct vm_struct *vm_stack = cached_vm_stacks[i];
189 
190 		if (!vm_stack)
191 			continue;
192 
193 		vfree(vm_stack->addr);
194 		cached_vm_stacks[i] = NULL;
195 	}
196 
197 	return 0;
198 }
199 #endif
200 
alloc_thread_stack_node(struct task_struct * tsk,int node)201 static unsigned long *alloc_thread_stack_node(struct task_struct *tsk, int node)
202 {
203 #ifdef CONFIG_VMAP_STACK
204 	void *stack;
205 	int i;
206 
207 	for (i = 0; i < NR_CACHED_STACKS; i++) {
208 		struct vm_struct *s;
209 
210 		s = this_cpu_xchg(cached_stacks[i], NULL);
211 
212 		if (!s)
213 			continue;
214 
215 		/* Clear stale pointers from reused stack. */
216 		memset(s->addr, 0, THREAD_SIZE);
217 
218 		tsk->stack_vm_area = s;
219 		return s->addr;
220 	}
221 
222 	stack = __vmalloc_node_range(THREAD_SIZE, THREAD_ALIGN,
223 				     VMALLOC_START, VMALLOC_END,
224 				     THREADINFO_GFP,
225 				     PAGE_KERNEL,
226 				     0, node, __builtin_return_address(0));
227 
228 	/*
229 	 * We can't call find_vm_area() in interrupt context, and
230 	 * free_thread_stack() can be called in interrupt context,
231 	 * so cache the vm_struct.
232 	 */
233 	if (stack)
234 		tsk->stack_vm_area = find_vm_area(stack);
235 	return stack;
236 #else
237 	struct page *page = alloc_pages_node(node, THREADINFO_GFP,
238 					     THREAD_SIZE_ORDER);
239 
240 	return page ? page_address(page) : NULL;
241 #endif
242 }
243 
free_thread_stack(struct task_struct * tsk)244 static inline void free_thread_stack(struct task_struct *tsk)
245 {
246 #ifdef CONFIG_VMAP_STACK
247 	if (task_stack_vm_area(tsk)) {
248 		int i;
249 
250 		for (i = 0; i < NR_CACHED_STACKS; i++) {
251 			if (this_cpu_cmpxchg(cached_stacks[i],
252 					NULL, tsk->stack_vm_area) != NULL)
253 				continue;
254 
255 			return;
256 		}
257 
258 		vfree_atomic(tsk->stack);
259 		return;
260 	}
261 #endif
262 
263 	__free_pages(virt_to_page(tsk->stack), THREAD_SIZE_ORDER);
264 }
265 # else
266 static struct kmem_cache *thread_stack_cache;
267 
alloc_thread_stack_node(struct task_struct * tsk,int node)268 static unsigned long *alloc_thread_stack_node(struct task_struct *tsk,
269 						  int node)
270 {
271 	return kmem_cache_alloc_node(thread_stack_cache, THREADINFO_GFP, node);
272 }
273 
free_thread_stack(struct task_struct * tsk)274 static void free_thread_stack(struct task_struct *tsk)
275 {
276 	kmem_cache_free(thread_stack_cache, tsk->stack);
277 }
278 
thread_stack_cache_init(void)279 void thread_stack_cache_init(void)
280 {
281 	thread_stack_cache = kmem_cache_create("thread_stack", THREAD_SIZE,
282 					      THREAD_SIZE, 0, NULL);
283 	BUG_ON(thread_stack_cache == NULL);
284 }
285 # endif
286 #endif
287 
288 /* SLAB cache for signal_struct structures (tsk->signal) */
289 static struct kmem_cache *signal_cachep;
290 
291 /* SLAB cache for sighand_struct structures (tsk->sighand) */
292 struct kmem_cache *sighand_cachep;
293 
294 /* SLAB cache for files_struct structures (tsk->files) */
295 struct kmem_cache *files_cachep;
296 
297 /* SLAB cache for fs_struct structures (tsk->fs) */
298 struct kmem_cache *fs_cachep;
299 
300 /* SLAB cache for vm_area_struct structures */
301 struct kmem_cache *vm_area_cachep;
302 
303 /* SLAB cache for mm_struct structures (tsk->mm) */
304 static struct kmem_cache *mm_cachep;
305 
account_kernel_stack(struct task_struct * tsk,int account)306 static void account_kernel_stack(struct task_struct *tsk, int account)
307 {
308 	void *stack = task_stack_page(tsk);
309 	struct vm_struct *vm = task_stack_vm_area(tsk);
310 
311 	BUILD_BUG_ON(IS_ENABLED(CONFIG_VMAP_STACK) && PAGE_SIZE % 1024 != 0);
312 
313 	if (vm) {
314 		int i;
315 
316 		BUG_ON(vm->nr_pages != THREAD_SIZE / PAGE_SIZE);
317 
318 		for (i = 0; i < THREAD_SIZE / PAGE_SIZE; i++) {
319 			mod_zone_page_state(page_zone(vm->pages[i]),
320 					    NR_KERNEL_STACK_KB,
321 					    PAGE_SIZE / 1024 * account);
322 		}
323 
324 		/* All stack pages belong to the same memcg. */
325 		mod_memcg_page_state(vm->pages[0], MEMCG_KERNEL_STACK_KB,
326 				     account * (THREAD_SIZE / 1024));
327 	} else {
328 		/*
329 		 * All stack pages are in the same zone and belong to the
330 		 * same memcg.
331 		 */
332 		struct page *first_page = virt_to_page(stack);
333 
334 		mod_zone_page_state(page_zone(first_page), NR_KERNEL_STACK_KB,
335 				    THREAD_SIZE / 1024 * account);
336 
337 		mod_memcg_page_state(first_page, MEMCG_KERNEL_STACK_KB,
338 				     account * (THREAD_SIZE / 1024));
339 	}
340 }
341 
release_task_stack(struct task_struct * tsk)342 static void release_task_stack(struct task_struct *tsk)
343 {
344 	if (WARN_ON(tsk->state != TASK_DEAD))
345 		return;  /* Better to leak the stack than to free prematurely */
346 
347 	account_kernel_stack(tsk, -1);
348 	free_thread_stack(tsk);
349 	tsk->stack = NULL;
350 #ifdef CONFIG_VMAP_STACK
351 	tsk->stack_vm_area = NULL;
352 #endif
353 }
354 
355 #ifdef CONFIG_THREAD_INFO_IN_TASK
put_task_stack(struct task_struct * tsk)356 void put_task_stack(struct task_struct *tsk)
357 {
358 	if (atomic_dec_and_test(&tsk->stack_refcount))
359 		release_task_stack(tsk);
360 }
361 #endif
362 
free_task(struct task_struct * tsk)363 void free_task(struct task_struct *tsk)
364 {
365 	cpufreq_task_times_exit(tsk);
366 
367 #ifndef CONFIG_THREAD_INFO_IN_TASK
368 	/*
369 	 * The task is finally done with both the stack and thread_info,
370 	 * so free both.
371 	 */
372 	release_task_stack(tsk);
373 #else
374 	/*
375 	 * If the task had a separate stack allocation, it should be gone
376 	 * by now.
377 	 */
378 	WARN_ON_ONCE(atomic_read(&tsk->stack_refcount) != 0);
379 #endif
380 	rt_mutex_debug_task_free(tsk);
381 	ftrace_graph_exit_task(tsk);
382 	put_seccomp_filter(tsk);
383 	arch_release_task_struct(tsk);
384 	if (tsk->flags & PF_KTHREAD)
385 		free_kthread_struct(tsk);
386 	free_task_struct(tsk);
387 }
388 EXPORT_SYMBOL(free_task);
389 
free_signal_struct(struct signal_struct * sig)390 static inline void free_signal_struct(struct signal_struct *sig)
391 {
392 	taskstats_tgid_free(sig);
393 	sched_autogroup_exit(sig);
394 	/*
395 	 * __mmdrop is not safe to call from softirq context on x86 due to
396 	 * pgd_dtor so postpone it to the async context
397 	 */
398 	if (sig->oom_mm)
399 		mmdrop_async(sig->oom_mm);
400 	kmem_cache_free(signal_cachep, sig);
401 }
402 
put_signal_struct(struct signal_struct * sig)403 static inline void put_signal_struct(struct signal_struct *sig)
404 {
405 	if (atomic_dec_and_test(&sig->sigcnt))
406 		free_signal_struct(sig);
407 }
408 
__put_task_struct(struct task_struct * tsk)409 void __put_task_struct(struct task_struct *tsk)
410 {
411 	WARN_ON(!tsk->exit_state);
412 	WARN_ON(atomic_read(&tsk->usage));
413 	WARN_ON(tsk == current);
414 
415 	cgroup_free(tsk);
416 	task_numa_free(tsk, true);
417 	security_task_free(tsk);
418 	exit_creds(tsk);
419 	delayacct_tsk_free(tsk);
420 	put_signal_struct(tsk->signal);
421 
422 	if (!profile_handoff_task(tsk))
423 		free_task(tsk);
424 }
425 EXPORT_SYMBOL_GPL(__put_task_struct);
426 
arch_task_cache_init(void)427 void __init __weak arch_task_cache_init(void) { }
428 
429 /*
430  * set_max_threads
431  */
set_max_threads(unsigned int max_threads_suggested)432 static void set_max_threads(unsigned int max_threads_suggested)
433 {
434 	u64 threads;
435 
436 	/*
437 	 * The number of threads shall be limited such that the thread
438 	 * structures may only consume a small part of the available memory.
439 	 */
440 	if (fls64(totalram_pages) + fls64(PAGE_SIZE) > 64)
441 		threads = MAX_THREADS;
442 	else
443 		threads = div64_u64((u64) totalram_pages * (u64) PAGE_SIZE,
444 				    (u64) THREAD_SIZE * 8UL);
445 
446 	if (threads > max_threads_suggested)
447 		threads = max_threads_suggested;
448 
449 	max_threads = clamp_t(u64, threads, MIN_THREADS, MAX_THREADS);
450 }
451 
452 #ifdef CONFIG_ARCH_WANTS_DYNAMIC_TASK_STRUCT
453 /* Initialized by the architecture: */
454 int arch_task_struct_size __read_mostly;
455 #endif
456 
fork_init(void)457 void __init fork_init(void)
458 {
459 	int i;
460 #ifndef CONFIG_ARCH_TASK_STRUCT_ALLOCATOR
461 #ifndef ARCH_MIN_TASKALIGN
462 #define ARCH_MIN_TASKALIGN	0
463 #endif
464 	int align = max_t(int, L1_CACHE_BYTES, ARCH_MIN_TASKALIGN);
465 
466 	/* create a slab on which task_structs can be allocated */
467 	task_struct_cachep = kmem_cache_create("task_struct",
468 			arch_task_struct_size, align,
469 			SLAB_PANIC|SLAB_ACCOUNT, NULL);
470 #endif
471 
472 	/* do the arch specific task caches init */
473 	arch_task_cache_init();
474 
475 	set_max_threads(MAX_THREADS);
476 
477 	init_task.signal->rlim[RLIMIT_NPROC].rlim_cur = max_threads/2;
478 	init_task.signal->rlim[RLIMIT_NPROC].rlim_max = max_threads/2;
479 	init_task.signal->rlim[RLIMIT_SIGPENDING] =
480 		init_task.signal->rlim[RLIMIT_NPROC];
481 
482 	for (i = 0; i < UCOUNT_COUNTS; i++) {
483 		init_user_ns.ucount_max[i] = max_threads/2;
484 	}
485 
486 #ifdef CONFIG_VMAP_STACK
487 	cpuhp_setup_state(CPUHP_BP_PREPARE_DYN, "fork:vm_stack_cache",
488 			  NULL, free_vm_stack_cache);
489 #endif
490 
491 	lockdep_init_task(&init_task);
492 }
493 
arch_dup_task_struct(struct task_struct * dst,struct task_struct * src)494 int __weak arch_dup_task_struct(struct task_struct *dst,
495 					       struct task_struct *src)
496 {
497 	*dst = *src;
498 	return 0;
499 }
500 
set_task_stack_end_magic(struct task_struct * tsk)501 void set_task_stack_end_magic(struct task_struct *tsk)
502 {
503 	unsigned long *stackend;
504 
505 	stackend = end_of_stack(tsk);
506 	*stackend = STACK_END_MAGIC;	/* for overflow detection */
507 }
508 
dup_task_struct(struct task_struct * orig,int node)509 static struct task_struct *dup_task_struct(struct task_struct *orig, int node)
510 {
511 	struct task_struct *tsk;
512 	unsigned long *stack;
513 	struct vm_struct *stack_vm_area;
514 	int err;
515 
516 	if (node == NUMA_NO_NODE)
517 		node = tsk_fork_get_node(orig);
518 	tsk = alloc_task_struct_node(node);
519 	if (!tsk)
520 		return NULL;
521 
522 	stack = alloc_thread_stack_node(tsk, node);
523 	if (!stack)
524 		goto free_tsk;
525 
526 	stack_vm_area = task_stack_vm_area(tsk);
527 
528 	err = arch_dup_task_struct(tsk, orig);
529 
530 	/*
531 	 * arch_dup_task_struct() clobbers the stack-related fields.  Make
532 	 * sure they're properly initialized before using any stack-related
533 	 * functions again.
534 	 */
535 	tsk->stack = stack;
536 #ifdef CONFIG_VMAP_STACK
537 	tsk->stack_vm_area = stack_vm_area;
538 #endif
539 #ifdef CONFIG_THREAD_INFO_IN_TASK
540 	atomic_set(&tsk->stack_refcount, 1);
541 #endif
542 
543 	if (err)
544 		goto free_stack;
545 
546 #ifdef CONFIG_SECCOMP
547 	/*
548 	 * We must handle setting up seccomp filters once we're under
549 	 * the sighand lock in case orig has changed between now and
550 	 * then. Until then, filter must be NULL to avoid messing up
551 	 * the usage counts on the error path calling free_task.
552 	 */
553 	tsk->seccomp.filter = NULL;
554 #endif
555 
556 	setup_thread_stack(tsk, orig);
557 	clear_user_return_notifier(tsk);
558 	clear_tsk_need_resched(tsk);
559 	set_task_stack_end_magic(tsk);
560 
561 #ifdef CONFIG_CC_STACKPROTECTOR
562 	tsk->stack_canary = get_random_canary();
563 #endif
564 
565 	/*
566 	 * One for us, one for whoever does the "release_task()" (usually
567 	 * parent)
568 	 */
569 	atomic_set(&tsk->usage, 2);
570 #ifdef CONFIG_BLK_DEV_IO_TRACE
571 	tsk->btrace_seq = 0;
572 #endif
573 	tsk->splice_pipe = NULL;
574 	tsk->task_frag.page = NULL;
575 	tsk->wake_q.next = NULL;
576 
577 	account_kernel_stack(tsk, 1);
578 
579 	kcov_task_init(tsk);
580 
581 #ifdef CONFIG_FAULT_INJECTION
582 	tsk->fail_nth = 0;
583 #endif
584 
585 	return tsk;
586 
587 free_stack:
588 	free_thread_stack(tsk);
589 free_tsk:
590 	free_task_struct(tsk);
591 	return NULL;
592 }
593 
594 #ifdef CONFIG_MMU
dup_mmap(struct mm_struct * mm,struct mm_struct * oldmm)595 static __latent_entropy int dup_mmap(struct mm_struct *mm,
596 					struct mm_struct *oldmm)
597 {
598 	struct vm_area_struct *mpnt, *tmp, *prev, **pprev;
599 	struct rb_node **rb_link, *rb_parent;
600 	int retval;
601 	unsigned long charge;
602 	LIST_HEAD(uf);
603 
604 	uprobe_start_dup_mmap();
605 	if (down_write_killable(&oldmm->mmap_sem)) {
606 		retval = -EINTR;
607 		goto fail_uprobe_end;
608 	}
609 	flush_cache_dup_mm(oldmm);
610 	uprobe_dup_mmap(oldmm, mm);
611 	/*
612 	 * Not linked in yet - no deadlock potential:
613 	 */
614 	down_write_nested(&mm->mmap_sem, SINGLE_DEPTH_NESTING);
615 
616 	/* No ordering required: file already has been exposed. */
617 	RCU_INIT_POINTER(mm->exe_file, get_mm_exe_file(oldmm));
618 
619 	mm->total_vm = oldmm->total_vm;
620 	mm->data_vm = oldmm->data_vm;
621 	mm->exec_vm = oldmm->exec_vm;
622 	mm->stack_vm = oldmm->stack_vm;
623 
624 	rb_link = &mm->mm_rb.rb_node;
625 	rb_parent = NULL;
626 	pprev = &mm->mmap;
627 	retval = ksm_fork(mm, oldmm);
628 	if (retval)
629 		goto out;
630 	retval = khugepaged_fork(mm, oldmm);
631 	if (retval)
632 		goto out;
633 
634 	prev = NULL;
635 	for (mpnt = oldmm->mmap; mpnt; mpnt = mpnt->vm_next) {
636 		struct file *file;
637 
638 		if (mpnt->vm_flags & VM_DONTCOPY) {
639 			vm_stat_account(mm, mpnt->vm_flags, -vma_pages(mpnt));
640 			continue;
641 		}
642 		charge = 0;
643 		if (mpnt->vm_flags & VM_ACCOUNT) {
644 			unsigned long len = vma_pages(mpnt);
645 
646 			if (security_vm_enough_memory_mm(oldmm, len)) /* sic */
647 				goto fail_nomem;
648 			charge = len;
649 		}
650 		tmp = kmem_cache_alloc(vm_area_cachep, GFP_KERNEL);
651 		if (!tmp)
652 			goto fail_nomem;
653 		*tmp = *mpnt;
654 		INIT_LIST_HEAD(&tmp->anon_vma_chain);
655 		retval = vma_dup_policy(mpnt, tmp);
656 		if (retval)
657 			goto fail_nomem_policy;
658 		tmp->vm_mm = mm;
659 		retval = dup_userfaultfd(tmp, &uf);
660 		if (retval)
661 			goto fail_nomem_anon_vma_fork;
662 		if (tmp->vm_flags & VM_WIPEONFORK) {
663 			/* VM_WIPEONFORK gets a clean slate in the child. */
664 			tmp->anon_vma = NULL;
665 			if (anon_vma_prepare(tmp))
666 				goto fail_nomem_anon_vma_fork;
667 		} else if (anon_vma_fork(tmp, mpnt))
668 			goto fail_nomem_anon_vma_fork;
669 		tmp->vm_flags &= ~(VM_LOCKED | VM_LOCKONFAULT);
670 		tmp->vm_next = tmp->vm_prev = NULL;
671 		file = tmp->vm_file;
672 		if (file) {
673 			struct inode *inode = file_inode(file);
674 			struct address_space *mapping = file->f_mapping;
675 
676 			get_file(file);
677 			if (tmp->vm_flags & VM_DENYWRITE)
678 				atomic_dec(&inode->i_writecount);
679 			i_mmap_lock_write(mapping);
680 			if (tmp->vm_flags & VM_SHARED)
681 				atomic_inc(&mapping->i_mmap_writable);
682 			flush_dcache_mmap_lock(mapping);
683 			/* insert tmp into the share list, just after mpnt */
684 			vma_interval_tree_insert_after(tmp, mpnt,
685 					&mapping->i_mmap);
686 			flush_dcache_mmap_unlock(mapping);
687 			i_mmap_unlock_write(mapping);
688 		}
689 
690 		/*
691 		 * Clear hugetlb-related page reserves for children. This only
692 		 * affects MAP_PRIVATE mappings. Faults generated by the child
693 		 * are not guaranteed to succeed, even if read-only
694 		 */
695 		if (is_vm_hugetlb_page(tmp))
696 			reset_vma_resv_huge_pages(tmp);
697 
698 		/*
699 		 * Link in the new vma and copy the page table entries.
700 		 */
701 		*pprev = tmp;
702 		pprev = &tmp->vm_next;
703 		tmp->vm_prev = prev;
704 		prev = tmp;
705 
706 		__vma_link_rb(mm, tmp, rb_link, rb_parent);
707 		rb_link = &tmp->vm_rb.rb_right;
708 		rb_parent = &tmp->vm_rb;
709 
710 		mm->map_count++;
711 		if (!(tmp->vm_flags & VM_WIPEONFORK))
712 			retval = copy_page_range(mm, oldmm, mpnt);
713 
714 		if (tmp->vm_ops && tmp->vm_ops->open)
715 			tmp->vm_ops->open(tmp);
716 
717 		if (retval)
718 			goto out;
719 	}
720 	/* a new mm has just been created */
721 	retval = arch_dup_mmap(oldmm, mm);
722 out:
723 	up_write(&mm->mmap_sem);
724 	flush_tlb_mm(oldmm);
725 	up_write(&oldmm->mmap_sem);
726 	dup_userfaultfd_complete(&uf);
727 fail_uprobe_end:
728 	uprobe_end_dup_mmap();
729 	return retval;
730 fail_nomem_anon_vma_fork:
731 	mpol_put(vma_policy(tmp));
732 fail_nomem_policy:
733 	kmem_cache_free(vm_area_cachep, tmp);
734 fail_nomem:
735 	retval = -ENOMEM;
736 	vm_unacct_memory(charge);
737 	goto out;
738 }
739 
mm_alloc_pgd(struct mm_struct * mm)740 static inline int mm_alloc_pgd(struct mm_struct *mm)
741 {
742 	mm->pgd = pgd_alloc(mm);
743 	if (unlikely(!mm->pgd))
744 		return -ENOMEM;
745 	return 0;
746 }
747 
mm_free_pgd(struct mm_struct * mm)748 static inline void mm_free_pgd(struct mm_struct *mm)
749 {
750 	pgd_free(mm, mm->pgd);
751 }
752 #else
dup_mmap(struct mm_struct * mm,struct mm_struct * oldmm)753 static int dup_mmap(struct mm_struct *mm, struct mm_struct *oldmm)
754 {
755 	down_write(&oldmm->mmap_sem);
756 	RCU_INIT_POINTER(mm->exe_file, get_mm_exe_file(oldmm));
757 	up_write(&oldmm->mmap_sem);
758 	return 0;
759 }
760 #define mm_alloc_pgd(mm)	(0)
761 #define mm_free_pgd(mm)
762 #endif /* CONFIG_MMU */
763 
764 __cacheline_aligned_in_smp DEFINE_SPINLOCK(mmlist_lock);
765 
766 #define allocate_mm()	(kmem_cache_alloc(mm_cachep, GFP_KERNEL))
767 #define free_mm(mm)	(kmem_cache_free(mm_cachep, (mm)))
768 
769 static unsigned long default_dump_filter = MMF_DUMP_FILTER_DEFAULT;
770 
coredump_filter_setup(char * s)771 static int __init coredump_filter_setup(char *s)
772 {
773 	default_dump_filter =
774 		(simple_strtoul(s, NULL, 0) << MMF_DUMP_FILTER_SHIFT) &
775 		MMF_DUMP_FILTER_MASK;
776 	return 1;
777 }
778 
779 __setup("coredump_filter=", coredump_filter_setup);
780 
781 #include <linux/init_task.h>
782 
mm_init_aio(struct mm_struct * mm)783 static void mm_init_aio(struct mm_struct *mm)
784 {
785 #ifdef CONFIG_AIO
786 	spin_lock_init(&mm->ioctx_lock);
787 	mm->ioctx_table = NULL;
788 #endif
789 }
790 
mm_clear_owner(struct mm_struct * mm,struct task_struct * p)791 static __always_inline void mm_clear_owner(struct mm_struct *mm,
792 					   struct task_struct *p)
793 {
794 #ifdef CONFIG_MEMCG
795 	if (mm->owner == p)
796 		WRITE_ONCE(mm->owner, NULL);
797 #endif
798 }
799 
mm_init_owner(struct mm_struct * mm,struct task_struct * p)800 static void mm_init_owner(struct mm_struct *mm, struct task_struct *p)
801 {
802 #ifdef CONFIG_MEMCG
803 	mm->owner = p;
804 #endif
805 }
806 
mm_init_uprobes_state(struct mm_struct * mm)807 static void mm_init_uprobes_state(struct mm_struct *mm)
808 {
809 #ifdef CONFIG_UPROBES
810 	mm->uprobes_state.xol_area = NULL;
811 #endif
812 }
813 
mm_init(struct mm_struct * mm,struct task_struct * p,struct user_namespace * user_ns)814 static struct mm_struct *mm_init(struct mm_struct *mm, struct task_struct *p,
815 	struct user_namespace *user_ns)
816 {
817 	mm->mmap = NULL;
818 	mm->mm_rb = RB_ROOT;
819 	mm->vmacache_seqnum = 0;
820 	atomic_set(&mm->mm_users, 1);
821 	atomic_set(&mm->mm_count, 1);
822 	init_rwsem(&mm->mmap_sem);
823 	INIT_LIST_HEAD(&mm->mmlist);
824 	mm->core_state = NULL;
825 	atomic_long_set(&mm->nr_ptes, 0);
826 	mm_nr_pmds_init(mm);
827 	mm->map_count = 0;
828 	mm->locked_vm = 0;
829 	mm->pinned_vm = 0;
830 	memset(&mm->rss_stat, 0, sizeof(mm->rss_stat));
831 	spin_lock_init(&mm->page_table_lock);
832 	mm_init_cpumask(mm);
833 	mm_init_aio(mm);
834 	mm_init_owner(mm, p);
835 	RCU_INIT_POINTER(mm->exe_file, NULL);
836 	mmu_notifier_mm_init(mm);
837 	hmm_mm_init(mm);
838 	init_tlb_flush_pending(mm);
839 #if defined(CONFIG_TRANSPARENT_HUGEPAGE) && !USE_SPLIT_PMD_PTLOCKS
840 	mm->pmd_huge_pte = NULL;
841 #endif
842 	mm_init_uprobes_state(mm);
843 
844 	if (current->mm) {
845 		mm->flags = current->mm->flags & MMF_INIT_MASK;
846 		mm->def_flags = current->mm->def_flags & VM_INIT_DEF_MASK;
847 	} else {
848 		mm->flags = default_dump_filter;
849 		mm->def_flags = 0;
850 	}
851 
852 	if (mm_alloc_pgd(mm))
853 		goto fail_nopgd;
854 
855 	if (init_new_context(p, mm))
856 		goto fail_nocontext;
857 
858 	mm->user_ns = get_user_ns(user_ns);
859 	return mm;
860 
861 fail_nocontext:
862 	mm_free_pgd(mm);
863 fail_nopgd:
864 	free_mm(mm);
865 	return NULL;
866 }
867 
check_mm(struct mm_struct * mm)868 static void check_mm(struct mm_struct *mm)
869 {
870 	int i;
871 
872 	for (i = 0; i < NR_MM_COUNTERS; i++) {
873 		long x = atomic_long_read(&mm->rss_stat.count[i]);
874 
875 		if (unlikely(x))
876 			printk(KERN_ALERT "BUG: Bad rss-counter state "
877 					  "mm:%p idx:%d val:%ld\n", mm, i, x);
878 	}
879 
880 	if (atomic_long_read(&mm->nr_ptes))
881 		pr_alert("BUG: non-zero nr_ptes on freeing mm: %ld\n",
882 				atomic_long_read(&mm->nr_ptes));
883 	if (mm_nr_pmds(mm))
884 		pr_alert("BUG: non-zero nr_pmds on freeing mm: %ld\n",
885 				mm_nr_pmds(mm));
886 
887 #if defined(CONFIG_TRANSPARENT_HUGEPAGE) && !USE_SPLIT_PMD_PTLOCKS
888 	VM_BUG_ON_MM(mm->pmd_huge_pte, mm);
889 #endif
890 }
891 
892 /*
893  * Allocate and initialize an mm_struct.
894  */
mm_alloc(void)895 struct mm_struct *mm_alloc(void)
896 {
897 	struct mm_struct *mm;
898 
899 	mm = allocate_mm();
900 	if (!mm)
901 		return NULL;
902 
903 	memset(mm, 0, sizeof(*mm));
904 	return mm_init(mm, current, current_user_ns());
905 }
906 
907 /*
908  * Called when the last reference to the mm
909  * is dropped: either by a lazy thread or by
910  * mmput. Free the page directory and the mm.
911  */
__mmdrop(struct mm_struct * mm)912 void __mmdrop(struct mm_struct *mm)
913 {
914 	BUG_ON(mm == &init_mm);
915 	mm_free_pgd(mm);
916 	destroy_context(mm);
917 	hmm_mm_destroy(mm);
918 	mmu_notifier_mm_destroy(mm);
919 	check_mm(mm);
920 	put_user_ns(mm->user_ns);
921 	free_mm(mm);
922 }
923 EXPORT_SYMBOL_GPL(__mmdrop);
924 
__mmput(struct mm_struct * mm)925 static inline void __mmput(struct mm_struct *mm)
926 {
927 	VM_BUG_ON(atomic_read(&mm->mm_users));
928 
929 	uprobe_clear_state(mm);
930 	exit_aio(mm);
931 	ksm_exit(mm);
932 	khugepaged_exit(mm); /* must run before exit_mmap */
933 	exit_mmap(mm);
934 	mm_put_huge_zero_page(mm);
935 	set_mm_exe_file(mm, NULL);
936 	if (!list_empty(&mm->mmlist)) {
937 		spin_lock(&mmlist_lock);
938 		list_del(&mm->mmlist);
939 		spin_unlock(&mmlist_lock);
940 	}
941 	if (mm->binfmt)
942 		module_put(mm->binfmt->module);
943 	mmdrop(mm);
944 }
945 
946 /*
947  * Decrement the use count and release all resources for an mm.
948  */
mmput(struct mm_struct * mm)949 void mmput(struct mm_struct *mm)
950 {
951 	might_sleep();
952 
953 	if (atomic_dec_and_test(&mm->mm_users))
954 		__mmput(mm);
955 }
956 EXPORT_SYMBOL_GPL(mmput);
957 
958 #ifdef CONFIG_MMU
mmput_async_fn(struct work_struct * work)959 static void mmput_async_fn(struct work_struct *work)
960 {
961 	struct mm_struct *mm = container_of(work, struct mm_struct,
962 					    async_put_work);
963 
964 	__mmput(mm);
965 }
966 
mmput_async(struct mm_struct * mm)967 void mmput_async(struct mm_struct *mm)
968 {
969 	if (atomic_dec_and_test(&mm->mm_users)) {
970 		INIT_WORK(&mm->async_put_work, mmput_async_fn);
971 		schedule_work(&mm->async_put_work);
972 	}
973 }
974 #endif
975 
976 /**
977  * set_mm_exe_file - change a reference to the mm's executable file
978  *
979  * This changes mm's executable file (shown as symlink /proc/[pid]/exe).
980  *
981  * Main users are mmput() and sys_execve(). Callers prevent concurrent
982  * invocations: in mmput() nobody alive left, in execve task is single
983  * threaded. sys_prctl(PR_SET_MM_MAP/EXE_FILE) also needs to set the
984  * mm->exe_file, but does so without using set_mm_exe_file() in order
985  * to do avoid the need for any locks.
986  */
set_mm_exe_file(struct mm_struct * mm,struct file * new_exe_file)987 void set_mm_exe_file(struct mm_struct *mm, struct file *new_exe_file)
988 {
989 	struct file *old_exe_file;
990 
991 	/*
992 	 * It is safe to dereference the exe_file without RCU as
993 	 * this function is only called if nobody else can access
994 	 * this mm -- see comment above for justification.
995 	 */
996 	old_exe_file = rcu_dereference_raw(mm->exe_file);
997 
998 	if (new_exe_file)
999 		get_file(new_exe_file);
1000 	rcu_assign_pointer(mm->exe_file, new_exe_file);
1001 	if (old_exe_file)
1002 		fput(old_exe_file);
1003 }
1004 
1005 /**
1006  * get_mm_exe_file - acquire a reference to the mm's executable file
1007  *
1008  * Returns %NULL if mm has no associated executable file.
1009  * User must release file via fput().
1010  */
get_mm_exe_file(struct mm_struct * mm)1011 struct file *get_mm_exe_file(struct mm_struct *mm)
1012 {
1013 	struct file *exe_file;
1014 
1015 	rcu_read_lock();
1016 	exe_file = rcu_dereference(mm->exe_file);
1017 	if (exe_file && !get_file_rcu(exe_file))
1018 		exe_file = NULL;
1019 	rcu_read_unlock();
1020 	return exe_file;
1021 }
1022 EXPORT_SYMBOL(get_mm_exe_file);
1023 
1024 /**
1025  * get_task_exe_file - acquire a reference to the task's executable file
1026  *
1027  * Returns %NULL if task's mm (if any) has no associated executable file or
1028  * this is a kernel thread with borrowed mm (see the comment above get_task_mm).
1029  * User must release file via fput().
1030  */
get_task_exe_file(struct task_struct * task)1031 struct file *get_task_exe_file(struct task_struct *task)
1032 {
1033 	struct file *exe_file = NULL;
1034 	struct mm_struct *mm;
1035 
1036 	task_lock(task);
1037 	mm = task->mm;
1038 	if (mm) {
1039 		if (!(task->flags & PF_KTHREAD))
1040 			exe_file = get_mm_exe_file(mm);
1041 	}
1042 	task_unlock(task);
1043 	return exe_file;
1044 }
1045 EXPORT_SYMBOL(get_task_exe_file);
1046 
1047 /**
1048  * get_task_mm - acquire a reference to the task's mm
1049  *
1050  * Returns %NULL if the task has no mm.  Checks PF_KTHREAD (meaning
1051  * this kernel workthread has transiently adopted a user mm with use_mm,
1052  * to do its AIO) is not set and if so returns a reference to it, after
1053  * bumping up the use count.  User must release the mm via mmput()
1054  * after use.  Typically used by /proc and ptrace.
1055  */
get_task_mm(struct task_struct * task)1056 struct mm_struct *get_task_mm(struct task_struct *task)
1057 {
1058 	struct mm_struct *mm;
1059 
1060 	task_lock(task);
1061 	mm = task->mm;
1062 	if (mm) {
1063 		if (task->flags & PF_KTHREAD)
1064 			mm = NULL;
1065 		else
1066 			mmget(mm);
1067 	}
1068 	task_unlock(task);
1069 	return mm;
1070 }
1071 EXPORT_SYMBOL_GPL(get_task_mm);
1072 
mm_access(struct task_struct * task,unsigned int mode)1073 struct mm_struct *mm_access(struct task_struct *task, unsigned int mode)
1074 {
1075 	struct mm_struct *mm;
1076 	int err;
1077 
1078 	err =  mutex_lock_killable(&task->signal->cred_guard_mutex);
1079 	if (err)
1080 		return ERR_PTR(err);
1081 
1082 	mm = get_task_mm(task);
1083 	if (mm && mm != current->mm &&
1084 			!ptrace_may_access(task, mode)) {
1085 		mmput(mm);
1086 		mm = ERR_PTR(-EACCES);
1087 	}
1088 	mutex_unlock(&task->signal->cred_guard_mutex);
1089 
1090 	return mm;
1091 }
1092 
complete_vfork_done(struct task_struct * tsk)1093 static void complete_vfork_done(struct task_struct *tsk)
1094 {
1095 	struct completion *vfork;
1096 
1097 	task_lock(tsk);
1098 	vfork = tsk->vfork_done;
1099 	if (likely(vfork)) {
1100 		tsk->vfork_done = NULL;
1101 		complete(vfork);
1102 	}
1103 	task_unlock(tsk);
1104 }
1105 
wait_for_vfork_done(struct task_struct * child,struct completion * vfork)1106 static int wait_for_vfork_done(struct task_struct *child,
1107 				struct completion *vfork)
1108 {
1109 	int killed;
1110 
1111 	freezer_do_not_count();
1112 	killed = wait_for_completion_killable(vfork);
1113 	freezer_count();
1114 
1115 	if (killed) {
1116 		task_lock(child);
1117 		child->vfork_done = NULL;
1118 		task_unlock(child);
1119 	}
1120 
1121 	put_task_struct(child);
1122 	return killed;
1123 }
1124 
1125 /* Please note the differences between mmput and mm_release.
1126  * mmput is called whenever we stop holding onto a mm_struct,
1127  * error success whatever.
1128  *
1129  * mm_release is called after a mm_struct has been removed
1130  * from the current process.
1131  *
1132  * This difference is important for error handling, when we
1133  * only half set up a mm_struct for a new process and need to restore
1134  * the old one.  Because we mmput the new mm_struct before
1135  * restoring the old one. . .
1136  * Eric Biederman 10 January 1998
1137  */
mm_release(struct task_struct * tsk,struct mm_struct * mm)1138 static void mm_release(struct task_struct *tsk, struct mm_struct *mm)
1139 {
1140 	uprobe_free_utask(tsk);
1141 
1142 	/* Get rid of any cached register state */
1143 	deactivate_mm(tsk, mm);
1144 
1145 	/*
1146 	 * Signal userspace if we're not exiting with a core dump
1147 	 * because we want to leave the value intact for debugging
1148 	 * purposes.
1149 	 */
1150 	if (tsk->clear_child_tid) {
1151 		if (!(tsk->signal->flags & SIGNAL_GROUP_COREDUMP) &&
1152 		    atomic_read(&mm->mm_users) > 1) {
1153 			/*
1154 			 * We don't check the error code - if userspace has
1155 			 * not set up a proper pointer then tough luck.
1156 			 */
1157 			put_user(0, tsk->clear_child_tid);
1158 			sys_futex(tsk->clear_child_tid, FUTEX_WAKE,
1159 					1, NULL, NULL, 0);
1160 		}
1161 		tsk->clear_child_tid = NULL;
1162 	}
1163 
1164 	/*
1165 	 * All done, finally we can wake up parent and return this mm to him.
1166 	 * Also kthread_stop() uses this completion for synchronization.
1167 	 */
1168 	if (tsk->vfork_done)
1169 		complete_vfork_done(tsk);
1170 }
1171 
exit_mm_release(struct task_struct * tsk,struct mm_struct * mm)1172 void exit_mm_release(struct task_struct *tsk, struct mm_struct *mm)
1173 {
1174 	futex_exit_release(tsk);
1175 	mm_release(tsk, mm);
1176 }
1177 
exec_mm_release(struct task_struct * tsk,struct mm_struct * mm)1178 void exec_mm_release(struct task_struct *tsk, struct mm_struct *mm)
1179 {
1180 	futex_exec_release(tsk);
1181 	mm_release(tsk, mm);
1182 }
1183 
1184 /*
1185  * Allocate a new mm structure and copy contents from the
1186  * mm structure of the passed in task structure.
1187  */
dup_mm(struct task_struct * tsk)1188 static struct mm_struct *dup_mm(struct task_struct *tsk)
1189 {
1190 	struct mm_struct *mm, *oldmm = current->mm;
1191 	int err;
1192 
1193 	mm = allocate_mm();
1194 	if (!mm)
1195 		goto fail_nomem;
1196 
1197 	memcpy(mm, oldmm, sizeof(*mm));
1198 
1199 	if (!mm_init(mm, tsk, mm->user_ns))
1200 		goto fail_nomem;
1201 
1202 	err = dup_mmap(mm, oldmm);
1203 	if (err)
1204 		goto free_pt;
1205 
1206 	mm->hiwater_rss = get_mm_rss(mm);
1207 	mm->hiwater_vm = mm->total_vm;
1208 
1209 	if (mm->binfmt && !try_module_get(mm->binfmt->module))
1210 		goto free_pt;
1211 
1212 	return mm;
1213 
1214 free_pt:
1215 	/* don't put binfmt in mmput, we haven't got module yet */
1216 	mm->binfmt = NULL;
1217 	mm_init_owner(mm, NULL);
1218 	mmput(mm);
1219 
1220 fail_nomem:
1221 	return NULL;
1222 }
1223 
copy_mm(unsigned long clone_flags,struct task_struct * tsk)1224 static int copy_mm(unsigned long clone_flags, struct task_struct *tsk)
1225 {
1226 	struct mm_struct *mm, *oldmm;
1227 	int retval;
1228 
1229 	tsk->min_flt = tsk->maj_flt = 0;
1230 	tsk->nvcsw = tsk->nivcsw = 0;
1231 #ifdef CONFIG_DETECT_HUNG_TASK
1232 	tsk->last_switch_count = tsk->nvcsw + tsk->nivcsw;
1233 #endif
1234 
1235 	tsk->mm = NULL;
1236 	tsk->active_mm = NULL;
1237 
1238 	/*
1239 	 * Are we cloning a kernel thread?
1240 	 *
1241 	 * We need to steal a active VM for that..
1242 	 */
1243 	oldmm = current->mm;
1244 	if (!oldmm)
1245 		return 0;
1246 
1247 	/* initialize the new vmacache entries */
1248 	vmacache_flush(tsk);
1249 
1250 	if (clone_flags & CLONE_VM) {
1251 		mmget(oldmm);
1252 		mm = oldmm;
1253 		goto good_mm;
1254 	}
1255 
1256 	retval = -ENOMEM;
1257 	mm = dup_mm(tsk);
1258 	if (!mm)
1259 		goto fail_nomem;
1260 
1261 good_mm:
1262 	tsk->mm = mm;
1263 	tsk->active_mm = mm;
1264 	return 0;
1265 
1266 fail_nomem:
1267 	return retval;
1268 }
1269 
copy_fs(unsigned long clone_flags,struct task_struct * tsk)1270 static int copy_fs(unsigned long clone_flags, struct task_struct *tsk)
1271 {
1272 	struct fs_struct *fs = current->fs;
1273 	if (clone_flags & CLONE_FS) {
1274 		/* tsk->fs is already what we want */
1275 		spin_lock(&fs->lock);
1276 		if (fs->in_exec) {
1277 			spin_unlock(&fs->lock);
1278 			return -EAGAIN;
1279 		}
1280 		fs->users++;
1281 		spin_unlock(&fs->lock);
1282 		return 0;
1283 	}
1284 	tsk->fs = copy_fs_struct(fs);
1285 	if (!tsk->fs)
1286 		return -ENOMEM;
1287 	return 0;
1288 }
1289 
copy_files(unsigned long clone_flags,struct task_struct * tsk)1290 static int copy_files(unsigned long clone_flags, struct task_struct *tsk)
1291 {
1292 	struct files_struct *oldf, *newf;
1293 	int error = 0;
1294 
1295 	/*
1296 	 * A background process may not have any files ...
1297 	 */
1298 	oldf = current->files;
1299 	if (!oldf)
1300 		goto out;
1301 
1302 	if (clone_flags & CLONE_FILES) {
1303 		atomic_inc(&oldf->count);
1304 		goto out;
1305 	}
1306 
1307 	newf = dup_fd(oldf, &error);
1308 	if (!newf)
1309 		goto out;
1310 
1311 	tsk->files = newf;
1312 	error = 0;
1313 out:
1314 	return error;
1315 }
1316 
copy_io(unsigned long clone_flags,struct task_struct * tsk)1317 static int copy_io(unsigned long clone_flags, struct task_struct *tsk)
1318 {
1319 #ifdef CONFIG_BLOCK
1320 	struct io_context *ioc = current->io_context;
1321 	struct io_context *new_ioc;
1322 
1323 	if (!ioc)
1324 		return 0;
1325 	/*
1326 	 * Share io context with parent, if CLONE_IO is set
1327 	 */
1328 	if (clone_flags & CLONE_IO) {
1329 		ioc_task_link(ioc);
1330 		tsk->io_context = ioc;
1331 	} else if (ioprio_valid(ioc->ioprio)) {
1332 		new_ioc = get_task_io_context(tsk, GFP_KERNEL, NUMA_NO_NODE);
1333 		if (unlikely(!new_ioc))
1334 			return -ENOMEM;
1335 
1336 		new_ioc->ioprio = ioc->ioprio;
1337 		put_io_context(new_ioc);
1338 	}
1339 #endif
1340 	return 0;
1341 }
1342 
copy_sighand(unsigned long clone_flags,struct task_struct * tsk)1343 static int copy_sighand(unsigned long clone_flags, struct task_struct *tsk)
1344 {
1345 	struct sighand_struct *sig;
1346 
1347 	if (clone_flags & CLONE_SIGHAND) {
1348 		atomic_inc(&current->sighand->count);
1349 		return 0;
1350 	}
1351 	sig = kmem_cache_alloc(sighand_cachep, GFP_KERNEL);
1352 	rcu_assign_pointer(tsk->sighand, sig);
1353 	if (!sig)
1354 		return -ENOMEM;
1355 
1356 	atomic_set(&sig->count, 1);
1357 	spin_lock_irq(&current->sighand->siglock);
1358 	memcpy(sig->action, current->sighand->action, sizeof(sig->action));
1359 	spin_unlock_irq(&current->sighand->siglock);
1360 	return 0;
1361 }
1362 
__cleanup_sighand(struct sighand_struct * sighand)1363 void __cleanup_sighand(struct sighand_struct *sighand)
1364 {
1365 	if (atomic_dec_and_test(&sighand->count)) {
1366 		signalfd_cleanup(sighand);
1367 		/*
1368 		 * sighand_cachep is SLAB_TYPESAFE_BY_RCU so we can free it
1369 		 * without an RCU grace period, see __lock_task_sighand().
1370 		 */
1371 		kmem_cache_free(sighand_cachep, sighand);
1372 	}
1373 }
1374 
1375 #ifdef CONFIG_POSIX_TIMERS
1376 /*
1377  * Initialize POSIX timer handling for a thread group.
1378  */
posix_cpu_timers_init_group(struct signal_struct * sig)1379 static void posix_cpu_timers_init_group(struct signal_struct *sig)
1380 {
1381 	unsigned long cpu_limit;
1382 
1383 	cpu_limit = READ_ONCE(sig->rlim[RLIMIT_CPU].rlim_cur);
1384 	if (cpu_limit != RLIM_INFINITY) {
1385 		sig->cputime_expires.prof_exp = cpu_limit * NSEC_PER_SEC;
1386 		sig->cputimer.running = true;
1387 	}
1388 
1389 	/* The timer lists. */
1390 	INIT_LIST_HEAD(&sig->cpu_timers[0]);
1391 	INIT_LIST_HEAD(&sig->cpu_timers[1]);
1392 	INIT_LIST_HEAD(&sig->cpu_timers[2]);
1393 }
1394 #else
posix_cpu_timers_init_group(struct signal_struct * sig)1395 static inline void posix_cpu_timers_init_group(struct signal_struct *sig) { }
1396 #endif
1397 
copy_signal(unsigned long clone_flags,struct task_struct * tsk)1398 static int copy_signal(unsigned long clone_flags, struct task_struct *tsk)
1399 {
1400 	struct signal_struct *sig;
1401 
1402 	if (clone_flags & CLONE_THREAD)
1403 		return 0;
1404 
1405 	sig = kmem_cache_zalloc(signal_cachep, GFP_KERNEL);
1406 	tsk->signal = sig;
1407 	if (!sig)
1408 		return -ENOMEM;
1409 
1410 	sig->nr_threads = 1;
1411 	atomic_set(&sig->live, 1);
1412 	atomic_set(&sig->sigcnt, 1);
1413 
1414 	/* list_add(thread_node, thread_head) without INIT_LIST_HEAD() */
1415 	sig->thread_head = (struct list_head)LIST_HEAD_INIT(tsk->thread_node);
1416 	tsk->thread_node = (struct list_head)LIST_HEAD_INIT(sig->thread_head);
1417 
1418 	init_waitqueue_head(&sig->wait_chldexit);
1419 	sig->curr_target = tsk;
1420 	init_sigpending(&sig->shared_pending);
1421 	seqlock_init(&sig->stats_lock);
1422 	prev_cputime_init(&sig->prev_cputime);
1423 
1424 #ifdef CONFIG_POSIX_TIMERS
1425 	INIT_LIST_HEAD(&sig->posix_timers);
1426 	hrtimer_init(&sig->real_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
1427 	sig->real_timer.function = it_real_fn;
1428 #endif
1429 
1430 	task_lock(current->group_leader);
1431 	memcpy(sig->rlim, current->signal->rlim, sizeof sig->rlim);
1432 	task_unlock(current->group_leader);
1433 
1434 	posix_cpu_timers_init_group(sig);
1435 
1436 	tty_audit_fork(sig);
1437 	sched_autogroup_fork(sig);
1438 
1439 	sig->oom_score_adj = current->signal->oom_score_adj;
1440 	sig->oom_score_adj_min = current->signal->oom_score_adj_min;
1441 
1442 	mutex_init(&sig->cred_guard_mutex);
1443 
1444 	return 0;
1445 }
1446 
copy_seccomp(struct task_struct * p)1447 static void copy_seccomp(struct task_struct *p)
1448 {
1449 #ifdef CONFIG_SECCOMP
1450 	/*
1451 	 * Must be called with sighand->lock held, which is common to
1452 	 * all threads in the group. Holding cred_guard_mutex is not
1453 	 * needed because this new task is not yet running and cannot
1454 	 * be racing exec.
1455 	 */
1456 	assert_spin_locked(&current->sighand->siglock);
1457 
1458 	/* Ref-count the new filter user, and assign it. */
1459 	get_seccomp_filter(current);
1460 	p->seccomp = current->seccomp;
1461 
1462 	/*
1463 	 * Explicitly enable no_new_privs here in case it got set
1464 	 * between the task_struct being duplicated and holding the
1465 	 * sighand lock. The seccomp state and nnp must be in sync.
1466 	 */
1467 	if (task_no_new_privs(current))
1468 		task_set_no_new_privs(p);
1469 
1470 	/*
1471 	 * If the parent gained a seccomp mode after copying thread
1472 	 * flags and between before we held the sighand lock, we have
1473 	 * to manually enable the seccomp thread flag here.
1474 	 */
1475 	if (p->seccomp.mode != SECCOMP_MODE_DISABLED)
1476 		set_tsk_thread_flag(p, TIF_SECCOMP);
1477 #endif
1478 }
1479 
SYSCALL_DEFINE1(set_tid_address,int __user *,tidptr)1480 SYSCALL_DEFINE1(set_tid_address, int __user *, tidptr)
1481 {
1482 	current->clear_child_tid = tidptr;
1483 
1484 	return task_pid_vnr(current);
1485 }
1486 
rt_mutex_init_task(struct task_struct * p)1487 static void rt_mutex_init_task(struct task_struct *p)
1488 {
1489 	raw_spin_lock_init(&p->pi_lock);
1490 #ifdef CONFIG_RT_MUTEXES
1491 	p->pi_waiters = RB_ROOT_CACHED;
1492 	p->pi_top_task = NULL;
1493 	p->pi_blocked_on = NULL;
1494 #endif
1495 }
1496 
1497 #ifdef CONFIG_POSIX_TIMERS
1498 /*
1499  * Initialize POSIX timer handling for a single task.
1500  */
posix_cpu_timers_init(struct task_struct * tsk)1501 static void posix_cpu_timers_init(struct task_struct *tsk)
1502 {
1503 	tsk->cputime_expires.prof_exp = 0;
1504 	tsk->cputime_expires.virt_exp = 0;
1505 	tsk->cputime_expires.sched_exp = 0;
1506 	INIT_LIST_HEAD(&tsk->cpu_timers[0]);
1507 	INIT_LIST_HEAD(&tsk->cpu_timers[1]);
1508 	INIT_LIST_HEAD(&tsk->cpu_timers[2]);
1509 }
1510 #else
posix_cpu_timers_init(struct task_struct * tsk)1511 static inline void posix_cpu_timers_init(struct task_struct *tsk) { }
1512 #endif
1513 
1514 static inline void
init_task_pid(struct task_struct * task,enum pid_type type,struct pid * pid)1515 init_task_pid(struct task_struct *task, enum pid_type type, struct pid *pid)
1516 {
1517 	 task->pids[type].pid = pid;
1518 }
1519 
rcu_copy_process(struct task_struct * p)1520 static inline void rcu_copy_process(struct task_struct *p)
1521 {
1522 #ifdef CONFIG_PREEMPT_RCU
1523 	p->rcu_read_lock_nesting = 0;
1524 	p->rcu_read_unlock_special.s = 0;
1525 	p->rcu_blocked_node = NULL;
1526 	INIT_LIST_HEAD(&p->rcu_node_entry);
1527 #endif /* #ifdef CONFIG_PREEMPT_RCU */
1528 #ifdef CONFIG_TASKS_RCU
1529 	p->rcu_tasks_holdout = false;
1530 	INIT_LIST_HEAD(&p->rcu_tasks_holdout_list);
1531 	p->rcu_tasks_idle_cpu = -1;
1532 #endif /* #ifdef CONFIG_TASKS_RCU */
1533 }
1534 
__delayed_free_task(struct rcu_head * rhp)1535 static void __delayed_free_task(struct rcu_head *rhp)
1536 {
1537 	struct task_struct *tsk = container_of(rhp, struct task_struct, rcu);
1538 
1539 	free_task(tsk);
1540 }
1541 
delayed_free_task(struct task_struct * tsk)1542 static __always_inline void delayed_free_task(struct task_struct *tsk)
1543 {
1544 	if (IS_ENABLED(CONFIG_MEMCG))
1545 		call_rcu(&tsk->rcu, __delayed_free_task);
1546 	else
1547 		free_task(tsk);
1548 }
1549 
1550 /*
1551  * This creates a new process as a copy of the old one,
1552  * but does not actually start it yet.
1553  *
1554  * It copies the registers, and all the appropriate
1555  * parts of the process environment (as per the clone
1556  * flags). The actual kick-off is left to the caller.
1557  */
copy_process(unsigned long clone_flags,unsigned long stack_start,unsigned long stack_size,int __user * child_tidptr,struct pid * pid,int trace,unsigned long tls,int node)1558 static __latent_entropy struct task_struct *copy_process(
1559 					unsigned long clone_flags,
1560 					unsigned long stack_start,
1561 					unsigned long stack_size,
1562 					int __user *child_tidptr,
1563 					struct pid *pid,
1564 					int trace,
1565 					unsigned long tls,
1566 					int node)
1567 {
1568 	int retval;
1569 	struct task_struct *p;
1570 
1571 	if ((clone_flags & (CLONE_NEWNS|CLONE_FS)) == (CLONE_NEWNS|CLONE_FS))
1572 		return ERR_PTR(-EINVAL);
1573 
1574 	if ((clone_flags & (CLONE_NEWUSER|CLONE_FS)) == (CLONE_NEWUSER|CLONE_FS))
1575 		return ERR_PTR(-EINVAL);
1576 
1577 	/*
1578 	 * Thread groups must share signals as well, and detached threads
1579 	 * can only be started up within the thread group.
1580 	 */
1581 	if ((clone_flags & CLONE_THREAD) && !(clone_flags & CLONE_SIGHAND))
1582 		return ERR_PTR(-EINVAL);
1583 
1584 	/*
1585 	 * Shared signal handlers imply shared VM. By way of the above,
1586 	 * thread groups also imply shared VM. Blocking this case allows
1587 	 * for various simplifications in other code.
1588 	 */
1589 	if ((clone_flags & CLONE_SIGHAND) && !(clone_flags & CLONE_VM))
1590 		return ERR_PTR(-EINVAL);
1591 
1592 	/*
1593 	 * Siblings of global init remain as zombies on exit since they are
1594 	 * not reaped by their parent (swapper). To solve this and to avoid
1595 	 * multi-rooted process trees, prevent global and container-inits
1596 	 * from creating siblings.
1597 	 */
1598 	if ((clone_flags & CLONE_PARENT) &&
1599 				current->signal->flags & SIGNAL_UNKILLABLE)
1600 		return ERR_PTR(-EINVAL);
1601 
1602 	/*
1603 	 * If the new process will be in a different pid or user namespace
1604 	 * do not allow it to share a thread group with the forking task.
1605 	 */
1606 	if (clone_flags & CLONE_THREAD) {
1607 		if ((clone_flags & (CLONE_NEWUSER | CLONE_NEWPID)) ||
1608 		    (task_active_pid_ns(current) !=
1609 				current->nsproxy->pid_ns_for_children))
1610 			return ERR_PTR(-EINVAL);
1611 	}
1612 
1613 	retval = -ENOMEM;
1614 	p = dup_task_struct(current, node);
1615 	if (!p)
1616 		goto fork_out;
1617 
1618 	cpufreq_task_times_init(p);
1619 
1620 	/*
1621 	 * This _must_ happen before we call free_task(), i.e. before we jump
1622 	 * to any of the bad_fork_* labels. This is to avoid freeing
1623 	 * p->set_child_tid which is (ab)used as a kthread's data pointer for
1624 	 * kernel threads (PF_KTHREAD).
1625 	 */
1626 	p->set_child_tid = (clone_flags & CLONE_CHILD_SETTID) ? child_tidptr : NULL;
1627 	/*
1628 	 * Clear TID on mm_release()?
1629 	 */
1630 	p->clear_child_tid = (clone_flags & CLONE_CHILD_CLEARTID) ? child_tidptr : NULL;
1631 
1632 	ftrace_graph_init_task(p);
1633 
1634 	rt_mutex_init_task(p);
1635 
1636 #ifdef CONFIG_PROVE_LOCKING
1637 	DEBUG_LOCKS_WARN_ON(!p->hardirqs_enabled);
1638 	DEBUG_LOCKS_WARN_ON(!p->softirqs_enabled);
1639 #endif
1640 	retval = -EAGAIN;
1641 	if (atomic_read(&p->real_cred->user->processes) >=
1642 			task_rlimit(p, RLIMIT_NPROC)) {
1643 		if (p->real_cred->user != INIT_USER &&
1644 		    !capable(CAP_SYS_RESOURCE) && !capable(CAP_SYS_ADMIN))
1645 			goto bad_fork_free;
1646 	}
1647 	current->flags &= ~PF_NPROC_EXCEEDED;
1648 
1649 	retval = copy_creds(p, clone_flags);
1650 	if (retval < 0)
1651 		goto bad_fork_free;
1652 
1653 	/*
1654 	 * If multiple threads are within copy_process(), then this check
1655 	 * triggers too late. This doesn't hurt, the check is only there
1656 	 * to stop root fork bombs.
1657 	 */
1658 	retval = -EAGAIN;
1659 	if (nr_threads >= max_threads)
1660 		goto bad_fork_cleanup_count;
1661 
1662 	delayacct_tsk_init(p);	/* Must remain after dup_task_struct() */
1663 	p->flags &= ~(PF_SUPERPRIV | PF_WQ_WORKER | PF_IDLE);
1664 	p->flags |= PF_FORKNOEXEC;
1665 	INIT_LIST_HEAD(&p->children);
1666 	INIT_LIST_HEAD(&p->sibling);
1667 	rcu_copy_process(p);
1668 	p->vfork_done = NULL;
1669 	spin_lock_init(&p->alloc_lock);
1670 
1671 	init_sigpending(&p->pending);
1672 
1673 	p->utime = p->stime = p->gtime = 0;
1674 #ifdef CONFIG_ARCH_HAS_SCALED_CPUTIME
1675 	p->utimescaled = p->stimescaled = 0;
1676 #endif
1677 	prev_cputime_init(&p->prev_cputime);
1678 
1679 #ifdef CONFIG_VIRT_CPU_ACCOUNTING_GEN
1680 	seqcount_init(&p->vtime.seqcount);
1681 	p->vtime.starttime = 0;
1682 	p->vtime.state = VTIME_INACTIVE;
1683 #endif
1684 
1685 #if defined(SPLIT_RSS_COUNTING)
1686 	memset(&p->rss_stat, 0, sizeof(p->rss_stat));
1687 #endif
1688 
1689 	p->default_timer_slack_ns = current->timer_slack_ns;
1690 
1691 #ifdef CONFIG_PSI
1692 	p->psi_flags = 0;
1693 #endif
1694 
1695 	task_io_accounting_init(&p->ioac);
1696 	acct_clear_integrals(p);
1697 
1698 	posix_cpu_timers_init(p);
1699 
1700 	p->io_context = NULL;
1701 	p->audit_context = NULL;
1702 	cgroup_fork(p);
1703 #ifdef CONFIG_NUMA
1704 	p->mempolicy = mpol_dup(p->mempolicy);
1705 	if (IS_ERR(p->mempolicy)) {
1706 		retval = PTR_ERR(p->mempolicy);
1707 		p->mempolicy = NULL;
1708 		goto bad_fork_cleanup_threadgroup_lock;
1709 	}
1710 #endif
1711 #ifdef CONFIG_CPUSETS
1712 	p->cpuset_mem_spread_rotor = NUMA_NO_NODE;
1713 	p->cpuset_slab_spread_rotor = NUMA_NO_NODE;
1714 	seqcount_init(&p->mems_allowed_seq);
1715 #endif
1716 #ifdef CONFIG_TRACE_IRQFLAGS
1717 	p->irq_events = 0;
1718 	p->hardirqs_enabled = 0;
1719 	p->hardirq_enable_ip = 0;
1720 	p->hardirq_enable_event = 0;
1721 	p->hardirq_disable_ip = _THIS_IP_;
1722 	p->hardirq_disable_event = 0;
1723 	p->softirqs_enabled = 1;
1724 	p->softirq_enable_ip = _THIS_IP_;
1725 	p->softirq_enable_event = 0;
1726 	p->softirq_disable_ip = 0;
1727 	p->softirq_disable_event = 0;
1728 	p->hardirq_context = 0;
1729 	p->softirq_context = 0;
1730 #endif
1731 
1732 	p->pagefault_disabled = 0;
1733 
1734 #ifdef CONFIG_LOCKDEP
1735 	p->lockdep_depth = 0; /* no locks held yet */
1736 	p->curr_chain_key = 0;
1737 	p->lockdep_recursion = 0;
1738 	lockdep_init_task(p);
1739 #endif
1740 
1741 #ifdef CONFIG_DEBUG_MUTEXES
1742 	p->blocked_on = NULL; /* not blocked yet */
1743 #endif
1744 #ifdef CONFIG_BCACHE
1745 	p->sequential_io	= 0;
1746 	p->sequential_io_avg	= 0;
1747 #endif
1748 
1749 	/* Perform scheduler related setup. Assign this task to a CPU. */
1750 	retval = sched_fork(clone_flags, p);
1751 	if (retval)
1752 		goto bad_fork_cleanup_policy;
1753 
1754 	retval = perf_event_init_task(p);
1755 	if (retval)
1756 		goto bad_fork_cleanup_policy;
1757 	retval = audit_alloc(p);
1758 	if (retval)
1759 		goto bad_fork_cleanup_perf;
1760 	/* copy all the process information */
1761 	shm_init_task(p);
1762 	retval = security_task_alloc(p, clone_flags);
1763 	if (retval)
1764 		goto bad_fork_cleanup_audit;
1765 	retval = copy_semundo(clone_flags, p);
1766 	if (retval)
1767 		goto bad_fork_cleanup_security;
1768 	retval = copy_files(clone_flags, p);
1769 	if (retval)
1770 		goto bad_fork_cleanup_semundo;
1771 	retval = copy_fs(clone_flags, p);
1772 	if (retval)
1773 		goto bad_fork_cleanup_files;
1774 	retval = copy_sighand(clone_flags, p);
1775 	if (retval)
1776 		goto bad_fork_cleanup_fs;
1777 	retval = copy_signal(clone_flags, p);
1778 	if (retval)
1779 		goto bad_fork_cleanup_sighand;
1780 	retval = copy_mm(clone_flags, p);
1781 	if (retval)
1782 		goto bad_fork_cleanup_signal;
1783 	retval = copy_namespaces(clone_flags, p);
1784 	if (retval)
1785 		goto bad_fork_cleanup_mm;
1786 	retval = copy_io(clone_flags, p);
1787 	if (retval)
1788 		goto bad_fork_cleanup_namespaces;
1789 	retval = copy_thread_tls(clone_flags, stack_start, stack_size, p, tls);
1790 	if (retval)
1791 		goto bad_fork_cleanup_io;
1792 
1793 	if (pid != &init_struct_pid) {
1794 		pid = alloc_pid(p->nsproxy->pid_ns_for_children);
1795 		if (IS_ERR(pid)) {
1796 			retval = PTR_ERR(pid);
1797 			goto bad_fork_cleanup_thread;
1798 		}
1799 	}
1800 
1801 #ifdef CONFIG_BLOCK
1802 	p->plug = NULL;
1803 #endif
1804 	futex_init_task(p);
1805 
1806 	/*
1807 	 * sigaltstack should be cleared when sharing the same VM
1808 	 */
1809 	if ((clone_flags & (CLONE_VM|CLONE_VFORK)) == CLONE_VM)
1810 		sas_ss_reset(p);
1811 
1812 	/*
1813 	 * Syscall tracing and stepping should be turned off in the
1814 	 * child regardless of CLONE_PTRACE.
1815 	 */
1816 	user_disable_single_step(p);
1817 	clear_tsk_thread_flag(p, TIF_SYSCALL_TRACE);
1818 #ifdef TIF_SYSCALL_EMU
1819 	clear_tsk_thread_flag(p, TIF_SYSCALL_EMU);
1820 #endif
1821 	clear_all_latency_tracing(p);
1822 
1823 	/* ok, now we should be set up.. */
1824 	p->pid = pid_nr(pid);
1825 	if (clone_flags & CLONE_THREAD) {
1826 		p->exit_signal = -1;
1827 		p->group_leader = current->group_leader;
1828 		p->tgid = current->tgid;
1829 	} else {
1830 		if (clone_flags & CLONE_PARENT)
1831 			p->exit_signal = current->group_leader->exit_signal;
1832 		else
1833 			p->exit_signal = (clone_flags & CSIGNAL);
1834 		p->group_leader = p;
1835 		p->tgid = p->pid;
1836 	}
1837 
1838 	p->nr_dirtied = 0;
1839 	p->nr_dirtied_pause = 128 >> (PAGE_SHIFT - 10);
1840 	p->dirty_paused_when = 0;
1841 
1842 	p->pdeath_signal = 0;
1843 	INIT_LIST_HEAD(&p->thread_group);
1844 	p->task_works = NULL;
1845 
1846 	cgroup_threadgroup_change_begin(current);
1847 	/*
1848 	 * Ensure that the cgroup subsystem policies allow the new process to be
1849 	 * forked. It should be noted the the new process's css_set can be changed
1850 	 * between here and cgroup_post_fork() if an organisation operation is in
1851 	 * progress.
1852 	 */
1853 	retval = cgroup_can_fork(p);
1854 	if (retval)
1855 		goto bad_fork_free_pid;
1856 
1857 	/*
1858 	 * From this point on we must avoid any synchronous user-space
1859 	 * communication until we take the tasklist-lock. In particular, we do
1860 	 * not want user-space to be able to predict the process start-time by
1861 	 * stalling fork(2) after we recorded the start_time but before it is
1862 	 * visible to the system.
1863 	 */
1864 
1865 	p->start_time = ktime_get_ns();
1866 	p->real_start_time = ktime_get_boot_ns();
1867 
1868 	/*
1869 	 * Make it visible to the rest of the system, but dont wake it up yet.
1870 	 * Need tasklist lock for parent etc handling!
1871 	 */
1872 	write_lock_irq(&tasklist_lock);
1873 
1874 	/* CLONE_PARENT re-uses the old parent */
1875 	if (clone_flags & (CLONE_PARENT|CLONE_THREAD)) {
1876 		p->real_parent = current->real_parent;
1877 		p->parent_exec_id = current->parent_exec_id;
1878 	} else {
1879 		p->real_parent = current;
1880 		p->parent_exec_id = current->self_exec_id;
1881 	}
1882 
1883 	klp_copy_process(p);
1884 
1885 	spin_lock(&current->sighand->siglock);
1886 
1887 	/*
1888 	 * Copy seccomp details explicitly here, in case they were changed
1889 	 * before holding sighand lock.
1890 	 */
1891 	copy_seccomp(p);
1892 
1893 	/*
1894 	 * Process group and session signals need to be delivered to just the
1895 	 * parent before the fork or both the parent and the child after the
1896 	 * fork. Restart if a signal comes in before we add the new process to
1897 	 * it's process group.
1898 	 * A fatal signal pending means that current will exit, so the new
1899 	 * thread can't slip out of an OOM kill (or normal SIGKILL).
1900 	*/
1901 	recalc_sigpending();
1902 	if (signal_pending(current)) {
1903 		retval = -ERESTARTNOINTR;
1904 		goto bad_fork_cancel_cgroup;
1905 	}
1906 	if (unlikely(!(ns_of_pid(pid)->nr_hashed & PIDNS_HASH_ADDING))) {
1907 		retval = -ENOMEM;
1908 		goto bad_fork_cancel_cgroup;
1909 	}
1910 
1911 	if (likely(p->pid)) {
1912 		ptrace_init_task(p, (clone_flags & CLONE_PTRACE) || trace);
1913 
1914 		init_task_pid(p, PIDTYPE_PID, pid);
1915 		if (thread_group_leader(p)) {
1916 			init_task_pid(p, PIDTYPE_PGID, task_pgrp(current));
1917 			init_task_pid(p, PIDTYPE_SID, task_session(current));
1918 
1919 			if (is_child_reaper(pid)) {
1920 				ns_of_pid(pid)->child_reaper = p;
1921 				p->signal->flags |= SIGNAL_UNKILLABLE;
1922 			}
1923 
1924 			p->signal->leader_pid = pid;
1925 			p->signal->tty = tty_kref_get(current->signal->tty);
1926 			/*
1927 			 * Inherit has_child_subreaper flag under the same
1928 			 * tasklist_lock with adding child to the process tree
1929 			 * for propagate_has_child_subreaper optimization.
1930 			 */
1931 			p->signal->has_child_subreaper = p->real_parent->signal->has_child_subreaper ||
1932 							 p->real_parent->signal->is_child_subreaper;
1933 			list_add_tail(&p->sibling, &p->real_parent->children);
1934 			list_add_tail_rcu(&p->tasks, &init_task.tasks);
1935 			attach_pid(p, PIDTYPE_PGID);
1936 			attach_pid(p, PIDTYPE_SID);
1937 			__this_cpu_inc(process_counts);
1938 		} else {
1939 			current->signal->nr_threads++;
1940 			atomic_inc(&current->signal->live);
1941 			atomic_inc(&current->signal->sigcnt);
1942 			list_add_tail_rcu(&p->thread_group,
1943 					  &p->group_leader->thread_group);
1944 			list_add_tail_rcu(&p->thread_node,
1945 					  &p->signal->thread_head);
1946 		}
1947 		attach_pid(p, PIDTYPE_PID);
1948 		nr_threads++;
1949 	}
1950 
1951 	total_forks++;
1952 	spin_unlock(&current->sighand->siglock);
1953 	syscall_tracepoint_update(p);
1954 	write_unlock_irq(&tasklist_lock);
1955 
1956 	proc_fork_connector(p);
1957 	cgroup_post_fork(p);
1958 	cgroup_threadgroup_change_end(current);
1959 	perf_event_fork(p);
1960 
1961 	trace_task_newtask(p, clone_flags);
1962 	uprobe_copy_process(p, clone_flags);
1963 
1964 	return p;
1965 
1966 bad_fork_cancel_cgroup:
1967 	spin_unlock(&current->sighand->siglock);
1968 	write_unlock_irq(&tasklist_lock);
1969 	cgroup_cancel_fork(p);
1970 bad_fork_free_pid:
1971 	cgroup_threadgroup_change_end(current);
1972 	if (pid != &init_struct_pid)
1973 		free_pid(pid);
1974 bad_fork_cleanup_thread:
1975 	exit_thread(p);
1976 bad_fork_cleanup_io:
1977 	if (p->io_context)
1978 		exit_io_context(p);
1979 bad_fork_cleanup_namespaces:
1980 	exit_task_namespaces(p);
1981 bad_fork_cleanup_mm:
1982 	if (p->mm) {
1983 		mm_clear_owner(p->mm, p);
1984 		mmput(p->mm);
1985 	}
1986 bad_fork_cleanup_signal:
1987 	if (!(clone_flags & CLONE_THREAD))
1988 		free_signal_struct(p->signal);
1989 bad_fork_cleanup_sighand:
1990 	__cleanup_sighand(p->sighand);
1991 bad_fork_cleanup_fs:
1992 	exit_fs(p); /* blocking */
1993 bad_fork_cleanup_files:
1994 	exit_files(p); /* blocking */
1995 bad_fork_cleanup_semundo:
1996 	exit_sem(p);
1997 bad_fork_cleanup_security:
1998 	security_task_free(p);
1999 bad_fork_cleanup_audit:
2000 	audit_free(p);
2001 bad_fork_cleanup_perf:
2002 	perf_event_free_task(p);
2003 bad_fork_cleanup_policy:
2004 	lockdep_free_task(p);
2005 #ifdef CONFIG_NUMA
2006 	mpol_put(p->mempolicy);
2007 bad_fork_cleanup_threadgroup_lock:
2008 #endif
2009 	delayacct_tsk_free(p);
2010 bad_fork_cleanup_count:
2011 	atomic_dec(&p->cred->user->processes);
2012 	exit_creds(p);
2013 bad_fork_free:
2014 	p->state = TASK_DEAD;
2015 	put_task_stack(p);
2016 	delayed_free_task(p);
2017 fork_out:
2018 	return ERR_PTR(retval);
2019 }
2020 
init_idle_pids(struct pid_link * links)2021 static inline void init_idle_pids(struct pid_link *links)
2022 {
2023 	enum pid_type type;
2024 
2025 	for (type = PIDTYPE_PID; type < PIDTYPE_MAX; ++type) {
2026 		INIT_HLIST_NODE(&links[type].node); /* not really needed */
2027 		links[type].pid = &init_struct_pid;
2028 	}
2029 }
2030 
fork_idle(int cpu)2031 struct task_struct *fork_idle(int cpu)
2032 {
2033 	struct task_struct *task;
2034 	task = copy_process(CLONE_VM, 0, 0, NULL, &init_struct_pid, 0, 0,
2035 			    cpu_to_node(cpu));
2036 	if (!IS_ERR(task)) {
2037 		init_idle_pids(task->pids);
2038 		init_idle(task, cpu);
2039 	}
2040 
2041 	return task;
2042 }
2043 
2044 /*
2045  *  Ok, this is the main fork-routine.
2046  *
2047  * It copies the process, and if successful kick-starts
2048  * it and waits for it to finish using the VM if required.
2049  */
_do_fork(unsigned long clone_flags,unsigned long stack_start,unsigned long stack_size,int __user * parent_tidptr,int __user * child_tidptr,unsigned long tls)2050 long _do_fork(unsigned long clone_flags,
2051 	      unsigned long stack_start,
2052 	      unsigned long stack_size,
2053 	      int __user *parent_tidptr,
2054 	      int __user *child_tidptr,
2055 	      unsigned long tls)
2056 {
2057 	struct task_struct *p;
2058 	int trace = 0;
2059 	long nr;
2060 
2061 	/*
2062 	 * Determine whether and which event to report to ptracer.  When
2063 	 * called from kernel_thread or CLONE_UNTRACED is explicitly
2064 	 * requested, no event is reported; otherwise, report if the event
2065 	 * for the type of forking is enabled.
2066 	 */
2067 	if (!(clone_flags & CLONE_UNTRACED)) {
2068 		if (clone_flags & CLONE_VFORK)
2069 			trace = PTRACE_EVENT_VFORK;
2070 		else if ((clone_flags & CSIGNAL) != SIGCHLD)
2071 			trace = PTRACE_EVENT_CLONE;
2072 		else
2073 			trace = PTRACE_EVENT_FORK;
2074 
2075 		if (likely(!ptrace_event_enabled(current, trace)))
2076 			trace = 0;
2077 	}
2078 
2079 	p = copy_process(clone_flags, stack_start, stack_size,
2080 			 child_tidptr, NULL, trace, tls, NUMA_NO_NODE);
2081 	add_latent_entropy();
2082 	/*
2083 	 * Do this prior waking up the new thread - the thread pointer
2084 	 * might get invalid after that point, if the thread exits quickly.
2085 	 */
2086 	if (!IS_ERR(p)) {
2087 		struct completion vfork;
2088 		struct pid *pid;
2089 
2090 		cpufreq_task_times_alloc(p);
2091 
2092 		trace_sched_process_fork(current, p);
2093 
2094 		pid = get_task_pid(p, PIDTYPE_PID);
2095 		nr = pid_vnr(pid);
2096 
2097 		if (clone_flags & CLONE_PARENT_SETTID)
2098 			put_user(nr, parent_tidptr);
2099 
2100 		if (clone_flags & CLONE_VFORK) {
2101 			p->vfork_done = &vfork;
2102 			init_completion(&vfork);
2103 			get_task_struct(p);
2104 		}
2105 
2106 		wake_up_new_task(p);
2107 
2108 		/* forking complete and child started to run, tell ptracer */
2109 		if (unlikely(trace))
2110 			ptrace_event_pid(trace, pid);
2111 
2112 		if (clone_flags & CLONE_VFORK) {
2113 			if (!wait_for_vfork_done(p, &vfork))
2114 				ptrace_event_pid(PTRACE_EVENT_VFORK_DONE, pid);
2115 		}
2116 
2117 		put_pid(pid);
2118 	} else {
2119 		nr = PTR_ERR(p);
2120 	}
2121 	return nr;
2122 }
2123 
2124 #ifndef CONFIG_HAVE_COPY_THREAD_TLS
2125 /* For compatibility with architectures that call do_fork directly rather than
2126  * using the syscall entry points below. */
do_fork(unsigned long clone_flags,unsigned long stack_start,unsigned long stack_size,int __user * parent_tidptr,int __user * child_tidptr)2127 long do_fork(unsigned long clone_flags,
2128 	      unsigned long stack_start,
2129 	      unsigned long stack_size,
2130 	      int __user *parent_tidptr,
2131 	      int __user *child_tidptr)
2132 {
2133 	return _do_fork(clone_flags, stack_start, stack_size,
2134 			parent_tidptr, child_tidptr, 0);
2135 }
2136 #endif
2137 
2138 /*
2139  * Create a kernel thread.
2140  */
kernel_thread(int (* fn)(void *),void * arg,unsigned long flags)2141 pid_t kernel_thread(int (*fn)(void *), void *arg, unsigned long flags)
2142 {
2143 	return _do_fork(flags|CLONE_VM|CLONE_UNTRACED, (unsigned long)fn,
2144 		(unsigned long)arg, NULL, NULL, 0);
2145 }
2146 
2147 #ifdef __ARCH_WANT_SYS_FORK
SYSCALL_DEFINE0(fork)2148 SYSCALL_DEFINE0(fork)
2149 {
2150 #ifdef CONFIG_MMU
2151 	return _do_fork(SIGCHLD, 0, 0, NULL, NULL, 0);
2152 #else
2153 	/* can not support in nommu mode */
2154 	return -EINVAL;
2155 #endif
2156 }
2157 #endif
2158 
2159 #ifdef __ARCH_WANT_SYS_VFORK
SYSCALL_DEFINE0(vfork)2160 SYSCALL_DEFINE0(vfork)
2161 {
2162 	return _do_fork(CLONE_VFORK | CLONE_VM | SIGCHLD, 0,
2163 			0, NULL, NULL, 0);
2164 }
2165 #endif
2166 
2167 #ifdef __ARCH_WANT_SYS_CLONE
2168 #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)2169 SYSCALL_DEFINE5(clone, unsigned long, clone_flags, unsigned long, newsp,
2170 		 int __user *, parent_tidptr,
2171 		 unsigned long, tls,
2172 		 int __user *, child_tidptr)
2173 #elif defined(CONFIG_CLONE_BACKWARDS2)
2174 SYSCALL_DEFINE5(clone, unsigned long, newsp, unsigned long, clone_flags,
2175 		 int __user *, parent_tidptr,
2176 		 int __user *, child_tidptr,
2177 		 unsigned long, tls)
2178 #elif defined(CONFIG_CLONE_BACKWARDS3)
2179 SYSCALL_DEFINE6(clone, unsigned long, clone_flags, unsigned long, newsp,
2180 		int, stack_size,
2181 		int __user *, parent_tidptr,
2182 		int __user *, child_tidptr,
2183 		unsigned long, tls)
2184 #else
2185 SYSCALL_DEFINE5(clone, unsigned long, clone_flags, unsigned long, newsp,
2186 		 int __user *, parent_tidptr,
2187 		 int __user *, child_tidptr,
2188 		 unsigned long, tls)
2189 #endif
2190 {
2191 	return _do_fork(clone_flags, newsp, 0, parent_tidptr, child_tidptr, tls);
2192 }
2193 #endif
2194 
walk_process_tree(struct task_struct * top,proc_visitor visitor,void * data)2195 void walk_process_tree(struct task_struct *top, proc_visitor visitor, void *data)
2196 {
2197 	struct task_struct *leader, *parent, *child;
2198 	int res;
2199 
2200 	read_lock(&tasklist_lock);
2201 	leader = top = top->group_leader;
2202 down:
2203 	for_each_thread(leader, parent) {
2204 		list_for_each_entry(child, &parent->children, sibling) {
2205 			res = visitor(child, data);
2206 			if (res) {
2207 				if (res < 0)
2208 					goto out;
2209 				leader = child;
2210 				goto down;
2211 			}
2212 up:
2213 			;
2214 		}
2215 	}
2216 
2217 	if (leader != top) {
2218 		child = leader;
2219 		parent = child->real_parent;
2220 		leader = parent->group_leader;
2221 		goto up;
2222 	}
2223 out:
2224 	read_unlock(&tasklist_lock);
2225 }
2226 
2227 #ifndef ARCH_MIN_MMSTRUCT_ALIGN
2228 #define ARCH_MIN_MMSTRUCT_ALIGN 0
2229 #endif
2230 
sighand_ctor(void * data)2231 static void sighand_ctor(void *data)
2232 {
2233 	struct sighand_struct *sighand = data;
2234 
2235 	spin_lock_init(&sighand->siglock);
2236 	init_waitqueue_head(&sighand->signalfd_wqh);
2237 }
2238 
proc_caches_init(void)2239 void __init proc_caches_init(void)
2240 {
2241 	sighand_cachep = kmem_cache_create("sighand_cache",
2242 			sizeof(struct sighand_struct), 0,
2243 			SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_TYPESAFE_BY_RCU|
2244 			SLAB_ACCOUNT, sighand_ctor);
2245 	signal_cachep = kmem_cache_create("signal_cache",
2246 			sizeof(struct signal_struct), 0,
2247 			SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_ACCOUNT,
2248 			NULL);
2249 	files_cachep = kmem_cache_create("files_cache",
2250 			sizeof(struct files_struct), 0,
2251 			SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_ACCOUNT,
2252 			NULL);
2253 	fs_cachep = kmem_cache_create("fs_cache",
2254 			sizeof(struct fs_struct), 0,
2255 			SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_ACCOUNT,
2256 			NULL);
2257 	/*
2258 	 * FIXME! The "sizeof(struct mm_struct)" currently includes the
2259 	 * whole struct cpumask for the OFFSTACK case. We could change
2260 	 * this to *only* allocate as much of it as required by the
2261 	 * maximum number of CPU's we can ever have.  The cpumask_allocation
2262 	 * is at the end of the structure, exactly for that reason.
2263 	 */
2264 	mm_cachep = kmem_cache_create("mm_struct",
2265 			sizeof(struct mm_struct), ARCH_MIN_MMSTRUCT_ALIGN,
2266 			SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_ACCOUNT,
2267 			NULL);
2268 	vm_area_cachep = KMEM_CACHE(vm_area_struct, SLAB_PANIC|SLAB_ACCOUNT);
2269 	mmap_init();
2270 	nsproxy_cache_init();
2271 }
2272 
2273 /*
2274  * Check constraints on flags passed to the unshare system call.
2275  */
check_unshare_flags(unsigned long unshare_flags)2276 static int check_unshare_flags(unsigned long unshare_flags)
2277 {
2278 	if (unshare_flags & ~(CLONE_THREAD|CLONE_FS|CLONE_NEWNS|CLONE_SIGHAND|
2279 				CLONE_VM|CLONE_FILES|CLONE_SYSVSEM|
2280 				CLONE_NEWUTS|CLONE_NEWIPC|CLONE_NEWNET|
2281 				CLONE_NEWUSER|CLONE_NEWPID|CLONE_NEWCGROUP))
2282 		return -EINVAL;
2283 	/*
2284 	 * Not implemented, but pretend it works if there is nothing
2285 	 * to unshare.  Note that unsharing the address space or the
2286 	 * signal handlers also need to unshare the signal queues (aka
2287 	 * CLONE_THREAD).
2288 	 */
2289 	if (unshare_flags & (CLONE_THREAD | CLONE_SIGHAND | CLONE_VM)) {
2290 		if (!thread_group_empty(current))
2291 			return -EINVAL;
2292 	}
2293 	if (unshare_flags & (CLONE_SIGHAND | CLONE_VM)) {
2294 		if (atomic_read(&current->sighand->count) > 1)
2295 			return -EINVAL;
2296 	}
2297 	if (unshare_flags & CLONE_VM) {
2298 		if (!current_is_single_threaded())
2299 			return -EINVAL;
2300 	}
2301 
2302 	return 0;
2303 }
2304 
2305 /*
2306  * Unshare the filesystem structure if it is being shared
2307  */
unshare_fs(unsigned long unshare_flags,struct fs_struct ** new_fsp)2308 static int unshare_fs(unsigned long unshare_flags, struct fs_struct **new_fsp)
2309 {
2310 	struct fs_struct *fs = current->fs;
2311 
2312 	if (!(unshare_flags & CLONE_FS) || !fs)
2313 		return 0;
2314 
2315 	/* don't need lock here; in the worst case we'll do useless copy */
2316 	if (fs->users == 1)
2317 		return 0;
2318 
2319 	*new_fsp = copy_fs_struct(fs);
2320 	if (!*new_fsp)
2321 		return -ENOMEM;
2322 
2323 	return 0;
2324 }
2325 
2326 /*
2327  * Unshare file descriptor table if it is being shared
2328  */
unshare_fd(unsigned long unshare_flags,struct files_struct ** new_fdp)2329 static int unshare_fd(unsigned long unshare_flags, struct files_struct **new_fdp)
2330 {
2331 	struct files_struct *fd = current->files;
2332 	int error = 0;
2333 
2334 	if ((unshare_flags & CLONE_FILES) &&
2335 	    (fd && atomic_read(&fd->count) > 1)) {
2336 		*new_fdp = dup_fd(fd, &error);
2337 		if (!*new_fdp)
2338 			return error;
2339 	}
2340 
2341 	return 0;
2342 }
2343 
2344 /*
2345  * unshare allows a process to 'unshare' part of the process
2346  * context which was originally shared using clone.  copy_*
2347  * functions used by do_fork() cannot be used here directly
2348  * because they modify an inactive task_struct that is being
2349  * constructed. Here we are modifying the current, active,
2350  * task_struct.
2351  */
SYSCALL_DEFINE1(unshare,unsigned long,unshare_flags)2352 SYSCALL_DEFINE1(unshare, unsigned long, unshare_flags)
2353 {
2354 	struct fs_struct *fs, *new_fs = NULL;
2355 	struct files_struct *fd, *new_fd = NULL;
2356 	struct cred *new_cred = NULL;
2357 	struct nsproxy *new_nsproxy = NULL;
2358 	int do_sysvsem = 0;
2359 	int err;
2360 
2361 	/*
2362 	 * If unsharing a user namespace must also unshare the thread group
2363 	 * and unshare the filesystem root and working directories.
2364 	 */
2365 	if (unshare_flags & CLONE_NEWUSER)
2366 		unshare_flags |= CLONE_THREAD | CLONE_FS;
2367 	/*
2368 	 * If unsharing vm, must also unshare signal handlers.
2369 	 */
2370 	if (unshare_flags & CLONE_VM)
2371 		unshare_flags |= CLONE_SIGHAND;
2372 	/*
2373 	 * If unsharing a signal handlers, must also unshare the signal queues.
2374 	 */
2375 	if (unshare_flags & CLONE_SIGHAND)
2376 		unshare_flags |= CLONE_THREAD;
2377 	/*
2378 	 * If unsharing namespace, must also unshare filesystem information.
2379 	 */
2380 	if (unshare_flags & CLONE_NEWNS)
2381 		unshare_flags |= CLONE_FS;
2382 
2383 	err = check_unshare_flags(unshare_flags);
2384 	if (err)
2385 		goto bad_unshare_out;
2386 	/*
2387 	 * CLONE_NEWIPC must also detach from the undolist: after switching
2388 	 * to a new ipc namespace, the semaphore arrays from the old
2389 	 * namespace are unreachable.
2390 	 */
2391 	if (unshare_flags & (CLONE_NEWIPC|CLONE_SYSVSEM))
2392 		do_sysvsem = 1;
2393 	err = unshare_fs(unshare_flags, &new_fs);
2394 	if (err)
2395 		goto bad_unshare_out;
2396 	err = unshare_fd(unshare_flags, &new_fd);
2397 	if (err)
2398 		goto bad_unshare_cleanup_fs;
2399 	err = unshare_userns(unshare_flags, &new_cred);
2400 	if (err)
2401 		goto bad_unshare_cleanup_fd;
2402 	err = unshare_nsproxy_namespaces(unshare_flags, &new_nsproxy,
2403 					 new_cred, new_fs);
2404 	if (err)
2405 		goto bad_unshare_cleanup_cred;
2406 
2407 	if (new_fs || new_fd || do_sysvsem || new_cred || new_nsproxy) {
2408 		if (do_sysvsem) {
2409 			/*
2410 			 * CLONE_SYSVSEM is equivalent to sys_exit().
2411 			 */
2412 			exit_sem(current);
2413 		}
2414 		if (unshare_flags & CLONE_NEWIPC) {
2415 			/* Orphan segments in old ns (see sem above). */
2416 			exit_shm(current);
2417 			shm_init_task(current);
2418 		}
2419 
2420 		if (new_nsproxy)
2421 			switch_task_namespaces(current, new_nsproxy);
2422 
2423 		task_lock(current);
2424 
2425 		if (new_fs) {
2426 			fs = current->fs;
2427 			spin_lock(&fs->lock);
2428 			current->fs = new_fs;
2429 			if (--fs->users)
2430 				new_fs = NULL;
2431 			else
2432 				new_fs = fs;
2433 			spin_unlock(&fs->lock);
2434 		}
2435 
2436 		if (new_fd) {
2437 			fd = current->files;
2438 			current->files = new_fd;
2439 			new_fd = fd;
2440 		}
2441 
2442 		task_unlock(current);
2443 
2444 		if (new_cred) {
2445 			/* Install the new user namespace */
2446 			commit_creds(new_cred);
2447 			new_cred = NULL;
2448 		}
2449 	}
2450 
2451 	perf_event_namespaces(current);
2452 
2453 bad_unshare_cleanup_cred:
2454 	if (new_cred)
2455 		put_cred(new_cred);
2456 bad_unshare_cleanup_fd:
2457 	if (new_fd)
2458 		put_files_struct(new_fd);
2459 
2460 bad_unshare_cleanup_fs:
2461 	if (new_fs)
2462 		free_fs_struct(new_fs);
2463 
2464 bad_unshare_out:
2465 	return err;
2466 }
2467 
2468 /*
2469  *	Helper to unshare the files of the current task.
2470  *	We don't want to expose copy_files internals to
2471  *	the exec layer of the kernel.
2472  */
2473 
unshare_files(struct files_struct ** displaced)2474 int unshare_files(struct files_struct **displaced)
2475 {
2476 	struct task_struct *task = current;
2477 	struct files_struct *copy = NULL;
2478 	int error;
2479 
2480 	error = unshare_fd(CLONE_FILES, &copy);
2481 	if (error || !copy) {
2482 		*displaced = NULL;
2483 		return error;
2484 	}
2485 	*displaced = task->files;
2486 	task_lock(task);
2487 	task->files = copy;
2488 	task_unlock(task);
2489 	return 0;
2490 }
2491 
sysctl_max_threads(struct ctl_table * table,int write,void __user * buffer,size_t * lenp,loff_t * ppos)2492 int sysctl_max_threads(struct ctl_table *table, int write,
2493 		       void __user *buffer, size_t *lenp, loff_t *ppos)
2494 {
2495 	struct ctl_table t;
2496 	int ret;
2497 	int threads = max_threads;
2498 	int min = 1;
2499 	int max = MAX_THREADS;
2500 
2501 	t = *table;
2502 	t.data = &threads;
2503 	t.extra1 = &min;
2504 	t.extra2 = &max;
2505 
2506 	ret = proc_dointvec_minmax(&t, write, buffer, lenp, ppos);
2507 	if (ret || !write)
2508 		return ret;
2509 
2510 	max_threads = threads;
2511 
2512 	return 0;
2513 }
2514