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