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