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