4 * Copyright (C) 1991, 1992 Linus Torvalds
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()'
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>
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>
94 #include <asm/pgtable.h>
95 #include <asm/pgalloc.h>
96 #include <linux/uaccess.h>
97 #include <asm/mmu_context.h>
98 #include <asm/cacheflush.h>
99 #include <asm/tlbflush.h>
101 #include <trace/events/sched.h>
103 #define CREATE_TRACE_POINTS
104 #include <trace/events/task.h>
107 * Minimum number of threads to boot the kernel
109 #define MIN_THREADS 20
112 * Maximum number of threads
114 #define MAX_THREADS FUTEX_TID_MASK
117 * Protected counters by write_lock_irq(&tasklist_lock)
119 unsigned long total_forks; /* Handle normal Linux uptimes. */
120 int nr_threads; /* The idle threads do not count.. */
122 int max_threads; /* tunable limit on nr_threads */
124 DEFINE_PER_CPU(unsigned long, process_counts) = 0;
126 __cacheline_aligned DEFINE_RWLOCK(tasklist_lock); /* outer */
128 #ifdef CONFIG_PROVE_RCU
129 int lockdep_tasklist_lock_is_held(void)
131 return lockdep_is_held(&tasklist_lock);
133 EXPORT_SYMBOL_GPL(lockdep_tasklist_lock_is_held);
134 #endif /* #ifdef CONFIG_PROVE_RCU */
136 int nr_processes(void)
141 for_each_possible_cpu(cpu)
142 total += per_cpu(process_counts, cpu);
147 void __weak arch_release_task_struct(struct task_struct *tsk)
151 #ifndef CONFIG_ARCH_TASK_STRUCT_ALLOCATOR
152 static struct kmem_cache *task_struct_cachep;
154 static inline struct task_struct *alloc_task_struct_node(int node)
156 return kmem_cache_alloc_node(task_struct_cachep, GFP_KERNEL, node);
159 static inline void free_task_struct(struct task_struct *tsk)
161 kmem_cache_free(task_struct_cachep, tsk);
165 #ifndef CONFIG_ARCH_THREAD_STACK_ALLOCATOR
168 * Allocate pages if THREAD_SIZE is >= PAGE_SIZE, otherwise use a
169 * kmemcache based allocator.
171 # if THREAD_SIZE >= PAGE_SIZE || defined(CONFIG_VMAP_STACK)
173 #ifdef CONFIG_VMAP_STACK
175 * vmalloc() is a bit slow, and calling vfree() enough times will force a TLB
176 * flush. Try to minimize the number of calls by caching stacks.
178 #define NR_CACHED_STACKS 2
179 static DEFINE_PER_CPU(struct vm_struct *, cached_stacks[NR_CACHED_STACKS]);
181 static int free_vm_stack_cache(unsigned int cpu)
183 struct vm_struct **cached_vm_stacks = per_cpu_ptr(cached_stacks, cpu);
186 for (i = 0; i < NR_CACHED_STACKS; i++) {
187 struct vm_struct *vm_stack = cached_vm_stacks[i];
192 vfree(vm_stack->addr);
193 cached_vm_stacks[i] = NULL;
200 static unsigned long *alloc_thread_stack_node(struct task_struct *tsk, int node)
202 #ifdef CONFIG_VMAP_STACK
206 for (i = 0; i < NR_CACHED_STACKS; i++) {
209 s = this_cpu_xchg(cached_stacks[i], NULL);
214 /* Clear stale pointers from reused stack. */
215 memset(s->addr, 0, THREAD_SIZE);
217 tsk->stack_vm_area = s;
221 stack = __vmalloc_node_range(THREAD_SIZE, THREAD_ALIGN,
222 VMALLOC_START, VMALLOC_END,
225 0, node, __builtin_return_address(0));
228 * We can't call find_vm_area() in interrupt context, and
229 * free_thread_stack() can be called in interrupt context,
230 * so cache the vm_struct.
233 tsk->stack_vm_area = find_vm_area(stack);
236 struct page *page = alloc_pages_node(node, THREADINFO_GFP,
239 return page ? page_address(page) : NULL;
243 static inline void free_thread_stack(struct task_struct *tsk)
245 #ifdef CONFIG_VMAP_STACK
246 if (task_stack_vm_area(tsk)) {
249 for (i = 0; i < NR_CACHED_STACKS; i++) {
250 if (this_cpu_cmpxchg(cached_stacks[i],
251 NULL, tsk->stack_vm_area) != NULL)
257 vfree_atomic(tsk->stack);
262 __free_pages(virt_to_page(tsk->stack), THREAD_SIZE_ORDER);
265 static struct kmem_cache *thread_stack_cache;
267 static unsigned long *alloc_thread_stack_node(struct task_struct *tsk,
270 return kmem_cache_alloc_node(thread_stack_cache, THREADINFO_GFP, node);
273 static void free_thread_stack(struct task_struct *tsk)
275 kmem_cache_free(thread_stack_cache, tsk->stack);
278 void thread_stack_cache_init(void)
280 thread_stack_cache = kmem_cache_create("thread_stack", THREAD_SIZE,
281 THREAD_SIZE, 0, NULL);
282 BUG_ON(thread_stack_cache == NULL);
287 /* SLAB cache for signal_struct structures (tsk->signal) */
288 static struct kmem_cache *signal_cachep;
290 /* SLAB cache for sighand_struct structures (tsk->sighand) */
291 struct kmem_cache *sighand_cachep;
293 /* SLAB cache for files_struct structures (tsk->files) */
294 struct kmem_cache *files_cachep;
296 /* SLAB cache for fs_struct structures (tsk->fs) */
297 struct kmem_cache *fs_cachep;
299 /* SLAB cache for vm_area_struct structures */
300 struct kmem_cache *vm_area_cachep;
302 /* SLAB cache for mm_struct structures (tsk->mm) */
303 static struct kmem_cache *mm_cachep;
305 static void account_kernel_stack(struct task_struct *tsk, int account)
307 void *stack = task_stack_page(tsk);
308 struct vm_struct *vm = task_stack_vm_area(tsk);
310 BUILD_BUG_ON(IS_ENABLED(CONFIG_VMAP_STACK) && PAGE_SIZE % 1024 != 0);
315 BUG_ON(vm->nr_pages != THREAD_SIZE / PAGE_SIZE);
317 for (i = 0; i < THREAD_SIZE / PAGE_SIZE; i++) {
318 mod_zone_page_state(page_zone(vm->pages[i]),
320 PAGE_SIZE / 1024 * account);
323 /* All stack pages belong to the same memcg. */
324 mod_memcg_page_state(vm->pages[0], MEMCG_KERNEL_STACK_KB,
325 account * (THREAD_SIZE / 1024));
328 * All stack pages are in the same zone and belong to the
331 struct page *first_page = virt_to_page(stack);
333 mod_zone_page_state(page_zone(first_page), NR_KERNEL_STACK_KB,
334 THREAD_SIZE / 1024 * account);
336 mod_memcg_page_state(first_page, MEMCG_KERNEL_STACK_KB,
337 account * (THREAD_SIZE / 1024));
341 static void release_task_stack(struct task_struct *tsk)
343 if (WARN_ON(tsk->state != TASK_DEAD))
344 return; /* Better to leak the stack than to free prematurely */
346 account_kernel_stack(tsk, -1);
347 free_thread_stack(tsk);
349 #ifdef CONFIG_VMAP_STACK
350 tsk->stack_vm_area = NULL;
354 #ifdef CONFIG_THREAD_INFO_IN_TASK
355 void put_task_stack(struct task_struct *tsk)
357 if (atomic_dec_and_test(&tsk->stack_refcount))
358 release_task_stack(tsk);
362 void free_task(struct task_struct *tsk)
364 #ifndef CONFIG_THREAD_INFO_IN_TASK
366 * The task is finally done with both the stack and thread_info,
369 release_task_stack(tsk);
372 * If the task had a separate stack allocation, it should be gone
375 WARN_ON_ONCE(atomic_read(&tsk->stack_refcount) != 0);
377 rt_mutex_debug_task_free(tsk);
378 ftrace_graph_exit_task(tsk);
379 put_seccomp_filter(tsk);
380 arch_release_task_struct(tsk);
381 if (tsk->flags & PF_KTHREAD)
382 free_kthread_struct(tsk);
383 free_task_struct(tsk);
385 EXPORT_SYMBOL(free_task);
387 static inline void free_signal_struct(struct signal_struct *sig)
389 taskstats_tgid_free(sig);
390 sched_autogroup_exit(sig);
392 * __mmdrop is not safe to call from softirq context on x86 due to
393 * pgd_dtor so postpone it to the async context
396 mmdrop_async(sig->oom_mm);
397 kmem_cache_free(signal_cachep, sig);
400 static inline void put_signal_struct(struct signal_struct *sig)
402 if (atomic_dec_and_test(&sig->sigcnt))
403 free_signal_struct(sig);
406 void __put_task_struct(struct task_struct *tsk)
408 WARN_ON(!tsk->exit_state);
409 WARN_ON(atomic_read(&tsk->usage));
410 WARN_ON(tsk == current);
413 task_numa_free(tsk, true);
414 security_task_free(tsk);
416 delayacct_tsk_free(tsk);
417 put_signal_struct(tsk->signal);
419 if (!profile_handoff_task(tsk))
422 EXPORT_SYMBOL_GPL(__put_task_struct);
424 void __init __weak arch_task_cache_init(void) { }
429 static void set_max_threads(unsigned int max_threads_suggested)
434 * The number of threads shall be limited such that the thread
435 * structures may only consume a small part of the available memory.
437 if (fls64(totalram_pages) + fls64(PAGE_SIZE) > 64)
438 threads = MAX_THREADS;
440 threads = div64_u64((u64) totalram_pages * (u64) PAGE_SIZE,
441 (u64) THREAD_SIZE * 8UL);
443 if (threads > max_threads_suggested)
444 threads = max_threads_suggested;
446 max_threads = clamp_t(u64, threads, MIN_THREADS, MAX_THREADS);
449 #ifdef CONFIG_ARCH_WANTS_DYNAMIC_TASK_STRUCT
450 /* Initialized by the architecture: */
451 int arch_task_struct_size __read_mostly;
454 void __init fork_init(void)
457 #ifndef CONFIG_ARCH_TASK_STRUCT_ALLOCATOR
458 #ifndef ARCH_MIN_TASKALIGN
459 #define ARCH_MIN_TASKALIGN 0
461 int align = max_t(int, L1_CACHE_BYTES, ARCH_MIN_TASKALIGN);
463 /* create a slab on which task_structs can be allocated */
464 task_struct_cachep = kmem_cache_create("task_struct",
465 arch_task_struct_size, align,
466 SLAB_PANIC|SLAB_ACCOUNT, NULL);
469 /* do the arch specific task caches init */
470 arch_task_cache_init();
472 set_max_threads(MAX_THREADS);
474 init_task.signal->rlim[RLIMIT_NPROC].rlim_cur = max_threads/2;
475 init_task.signal->rlim[RLIMIT_NPROC].rlim_max = max_threads/2;
476 init_task.signal->rlim[RLIMIT_SIGPENDING] =
477 init_task.signal->rlim[RLIMIT_NPROC];
479 for (i = 0; i < UCOUNT_COUNTS; i++) {
480 init_user_ns.ucount_max[i] = max_threads/2;
483 #ifdef CONFIG_VMAP_STACK
484 cpuhp_setup_state(CPUHP_BP_PREPARE_DYN, "fork:vm_stack_cache",
485 NULL, free_vm_stack_cache);
488 lockdep_init_task(&init_task);
491 int __weak arch_dup_task_struct(struct task_struct *dst,
492 struct task_struct *src)
498 void set_task_stack_end_magic(struct task_struct *tsk)
500 unsigned long *stackend;
502 stackend = end_of_stack(tsk);
503 *stackend = STACK_END_MAGIC; /* for overflow detection */
506 static struct task_struct *dup_task_struct(struct task_struct *orig, int node)
508 struct task_struct *tsk;
509 unsigned long *stack;
510 struct vm_struct *stack_vm_area;
513 if (node == NUMA_NO_NODE)
514 node = tsk_fork_get_node(orig);
515 tsk = alloc_task_struct_node(node);
519 stack = alloc_thread_stack_node(tsk, node);
523 stack_vm_area = task_stack_vm_area(tsk);
525 err = arch_dup_task_struct(tsk, orig);
528 * arch_dup_task_struct() clobbers the stack-related fields. Make
529 * sure they're properly initialized before using any stack-related
533 #ifdef CONFIG_VMAP_STACK
534 tsk->stack_vm_area = stack_vm_area;
536 #ifdef CONFIG_THREAD_INFO_IN_TASK
537 atomic_set(&tsk->stack_refcount, 1);
543 #ifdef CONFIG_SECCOMP
545 * We must handle setting up seccomp filters once we're under
546 * the sighand lock in case orig has changed between now and
547 * then. Until then, filter must be NULL to avoid messing up
548 * the usage counts on the error path calling free_task.
550 tsk->seccomp.filter = NULL;
553 setup_thread_stack(tsk, orig);
554 clear_user_return_notifier(tsk);
555 clear_tsk_need_resched(tsk);
556 set_task_stack_end_magic(tsk);
558 #ifdef CONFIG_CC_STACKPROTECTOR
559 tsk->stack_canary = get_random_canary();
563 * One for us, one for whoever does the "release_task()" (usually
566 atomic_set(&tsk->usage, 2);
567 #ifdef CONFIG_BLK_DEV_IO_TRACE
570 tsk->splice_pipe = NULL;
571 tsk->task_frag.page = NULL;
572 tsk->wake_q.next = NULL;
574 account_kernel_stack(tsk, 1);
578 #ifdef CONFIG_FAULT_INJECTION
585 free_thread_stack(tsk);
587 free_task_struct(tsk);
592 static __latent_entropy int dup_mmap(struct mm_struct *mm,
593 struct mm_struct *oldmm)
595 struct vm_area_struct *mpnt, *tmp, *prev, **pprev;
596 struct rb_node **rb_link, *rb_parent;
598 unsigned long charge;
601 uprobe_start_dup_mmap();
602 if (down_write_killable(&oldmm->mmap_sem)) {
604 goto fail_uprobe_end;
606 flush_cache_dup_mm(oldmm);
607 uprobe_dup_mmap(oldmm, mm);
609 * Not linked in yet - no deadlock potential:
611 down_write_nested(&mm->mmap_sem, SINGLE_DEPTH_NESTING);
613 /* No ordering required: file already has been exposed. */
614 RCU_INIT_POINTER(mm->exe_file, get_mm_exe_file(oldmm));
616 mm->total_vm = oldmm->total_vm;
617 mm->data_vm = oldmm->data_vm;
618 mm->exec_vm = oldmm->exec_vm;
619 mm->stack_vm = oldmm->stack_vm;
621 rb_link = &mm->mm_rb.rb_node;
624 retval = ksm_fork(mm, oldmm);
627 retval = khugepaged_fork(mm, oldmm);
632 for (mpnt = oldmm->mmap; mpnt; mpnt = mpnt->vm_next) {
635 if (mpnt->vm_flags & VM_DONTCOPY) {
636 vm_stat_account(mm, mpnt->vm_flags, -vma_pages(mpnt));
640 if (mpnt->vm_flags & VM_ACCOUNT) {
641 unsigned long len = vma_pages(mpnt);
643 if (security_vm_enough_memory_mm(oldmm, len)) /* sic */
647 tmp = kmem_cache_alloc(vm_area_cachep, GFP_KERNEL);
651 INIT_LIST_HEAD(&tmp->anon_vma_chain);
652 retval = vma_dup_policy(mpnt, tmp);
654 goto fail_nomem_policy;
656 retval = dup_userfaultfd(tmp, &uf);
658 goto fail_nomem_anon_vma_fork;
659 if (tmp->vm_flags & VM_WIPEONFORK) {
660 /* VM_WIPEONFORK gets a clean slate in the child. */
661 tmp->anon_vma = NULL;
662 if (anon_vma_prepare(tmp))
663 goto fail_nomem_anon_vma_fork;
664 } else if (anon_vma_fork(tmp, mpnt))
665 goto fail_nomem_anon_vma_fork;
666 tmp->vm_flags &= ~(VM_LOCKED | VM_LOCKONFAULT);
667 tmp->vm_next = tmp->vm_prev = NULL;
670 struct inode *inode = file_inode(file);
671 struct address_space *mapping = file->f_mapping;
674 if (tmp->vm_flags & VM_DENYWRITE)
675 atomic_dec(&inode->i_writecount);
676 i_mmap_lock_write(mapping);
677 if (tmp->vm_flags & VM_SHARED)
678 atomic_inc(&mapping->i_mmap_writable);
679 flush_dcache_mmap_lock(mapping);
680 /* insert tmp into the share list, just after mpnt */
681 vma_interval_tree_insert_after(tmp, mpnt,
683 flush_dcache_mmap_unlock(mapping);
684 i_mmap_unlock_write(mapping);
688 * Clear hugetlb-related page reserves for children. This only
689 * affects MAP_PRIVATE mappings. Faults generated by the child
690 * are not guaranteed to succeed, even if read-only
692 if (is_vm_hugetlb_page(tmp))
693 reset_vma_resv_huge_pages(tmp);
696 * Link in the new vma and copy the page table entries.
699 pprev = &tmp->vm_next;
703 __vma_link_rb(mm, tmp, rb_link, rb_parent);
704 rb_link = &tmp->vm_rb.rb_right;
705 rb_parent = &tmp->vm_rb;
708 if (!(tmp->vm_flags & VM_WIPEONFORK))
709 retval = copy_page_range(mm, oldmm, mpnt);
711 if (tmp->vm_ops && tmp->vm_ops->open)
712 tmp->vm_ops->open(tmp);
717 /* a new mm has just been created */
718 retval = arch_dup_mmap(oldmm, mm);
720 up_write(&mm->mmap_sem);
722 up_write(&oldmm->mmap_sem);
723 dup_userfaultfd_complete(&uf);
725 uprobe_end_dup_mmap();
727 fail_nomem_anon_vma_fork:
728 mpol_put(vma_policy(tmp));
730 kmem_cache_free(vm_area_cachep, tmp);
733 vm_unacct_memory(charge);
737 static inline int mm_alloc_pgd(struct mm_struct *mm)
739 mm->pgd = pgd_alloc(mm);
740 if (unlikely(!mm->pgd))
745 static inline void mm_free_pgd(struct mm_struct *mm)
747 pgd_free(mm, mm->pgd);
750 static int dup_mmap(struct mm_struct *mm, struct mm_struct *oldmm)
752 down_write(&oldmm->mmap_sem);
753 RCU_INIT_POINTER(mm->exe_file, get_mm_exe_file(oldmm));
754 up_write(&oldmm->mmap_sem);
757 #define mm_alloc_pgd(mm) (0)
758 #define mm_free_pgd(mm)
759 #endif /* CONFIG_MMU */
761 __cacheline_aligned_in_smp DEFINE_SPINLOCK(mmlist_lock);
763 #define allocate_mm() (kmem_cache_alloc(mm_cachep, GFP_KERNEL))
764 #define free_mm(mm) (kmem_cache_free(mm_cachep, (mm)))
766 static unsigned long default_dump_filter = MMF_DUMP_FILTER_DEFAULT;
768 static int __init coredump_filter_setup(char *s)
770 default_dump_filter =
771 (simple_strtoul(s, NULL, 0) << MMF_DUMP_FILTER_SHIFT) &
772 MMF_DUMP_FILTER_MASK;
776 __setup("coredump_filter=", coredump_filter_setup);
778 #include <linux/init_task.h>
780 static void mm_init_aio(struct mm_struct *mm)
783 spin_lock_init(&mm->ioctx_lock);
784 mm->ioctx_table = NULL;
788 static __always_inline void mm_clear_owner(struct mm_struct *mm,
789 struct task_struct *p)
793 WRITE_ONCE(mm->owner, NULL);
797 static void mm_init_owner(struct mm_struct *mm, struct task_struct *p)
804 static void mm_init_uprobes_state(struct mm_struct *mm)
806 #ifdef CONFIG_UPROBES
807 mm->uprobes_state.xol_area = NULL;
811 static struct mm_struct *mm_init(struct mm_struct *mm, struct task_struct *p,
812 struct user_namespace *user_ns)
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);
827 memset(&mm->rss_stat, 0, sizeof(mm->rss_stat));
828 spin_lock_init(&mm->page_table_lock);
831 mm_init_owner(mm, p);
832 RCU_INIT_POINTER(mm->exe_file, NULL);
833 mmu_notifier_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;
839 mm_init_uprobes_state(mm);
840 hugetlb_count_init(mm);
843 mm->flags = current->mm->flags & MMF_INIT_MASK;
844 mm->def_flags = current->mm->def_flags & VM_INIT_DEF_MASK;
846 mm->flags = default_dump_filter;
850 if (mm_alloc_pgd(mm))
853 if (init_new_context(p, mm))
856 mm->user_ns = get_user_ns(user_ns);
866 static void check_mm(struct mm_struct *mm)
870 for (i = 0; i < NR_MM_COUNTERS; i++) {
871 long x = atomic_long_read(&mm->rss_stat.count[i]);
874 printk(KERN_ALERT "BUG: Bad rss-counter state "
875 "mm:%p idx:%d val:%ld\n", mm, i, x);
878 if (atomic_long_read(&mm->nr_ptes))
879 pr_alert("BUG: non-zero nr_ptes on freeing mm: %ld\n",
880 atomic_long_read(&mm->nr_ptes));
882 pr_alert("BUG: non-zero nr_pmds on freeing mm: %ld\n",
885 #if defined(CONFIG_TRANSPARENT_HUGEPAGE) && !USE_SPLIT_PMD_PTLOCKS
886 VM_BUG_ON_MM(mm->pmd_huge_pte, mm);
891 * Allocate and initialize an mm_struct.
893 struct mm_struct *mm_alloc(void)
895 struct mm_struct *mm;
901 memset(mm, 0, sizeof(*mm));
902 return mm_init(mm, current, current_user_ns());
906 * Called when the last reference to the mm
907 * is dropped: either by a lazy thread or by
908 * mmput. Free the page directory and the mm.
910 void __mmdrop(struct mm_struct *mm)
912 BUG_ON(mm == &init_mm);
916 mmu_notifier_mm_destroy(mm);
918 put_user_ns(mm->user_ns);
921 EXPORT_SYMBOL_GPL(__mmdrop);
923 static inline void __mmput(struct mm_struct *mm)
925 VM_BUG_ON(atomic_read(&mm->mm_users));
927 uprobe_clear_state(mm);
930 khugepaged_exit(mm); /* must run before exit_mmap */
932 mm_put_huge_zero_page(mm);
933 set_mm_exe_file(mm, NULL);
934 if (!list_empty(&mm->mmlist)) {
935 spin_lock(&mmlist_lock);
936 list_del(&mm->mmlist);
937 spin_unlock(&mmlist_lock);
940 module_put(mm->binfmt->module);
945 * Decrement the use count and release all resources for an mm.
947 void mmput(struct mm_struct *mm)
951 if (atomic_dec_and_test(&mm->mm_users))
954 EXPORT_SYMBOL_GPL(mmput);
957 static void mmput_async_fn(struct work_struct *work)
959 struct mm_struct *mm = container_of(work, struct mm_struct,
965 void mmput_async(struct mm_struct *mm)
967 if (atomic_dec_and_test(&mm->mm_users)) {
968 INIT_WORK(&mm->async_put_work, mmput_async_fn);
969 schedule_work(&mm->async_put_work);
975 * set_mm_exe_file - change a reference to the mm's executable file
977 * This changes mm's executable file (shown as symlink /proc/[pid]/exe).
979 * Main users are mmput() and sys_execve(). Callers prevent concurrent
980 * invocations: in mmput() nobody alive left, in execve task is single
981 * threaded. sys_prctl(PR_SET_MM_MAP/EXE_FILE) also needs to set the
982 * mm->exe_file, but does so without using set_mm_exe_file() in order
983 * to do avoid the need for any locks.
985 void set_mm_exe_file(struct mm_struct *mm, struct file *new_exe_file)
987 struct file *old_exe_file;
990 * It is safe to dereference the exe_file without RCU as
991 * this function is only called if nobody else can access
992 * this mm -- see comment above for justification.
994 old_exe_file = rcu_dereference_raw(mm->exe_file);
997 get_file(new_exe_file);
998 rcu_assign_pointer(mm->exe_file, new_exe_file);
1004 * get_mm_exe_file - acquire a reference to the mm's executable file
1006 * Returns %NULL if mm has no associated executable file.
1007 * User must release file via fput().
1009 struct file *get_mm_exe_file(struct mm_struct *mm)
1011 struct file *exe_file;
1014 exe_file = rcu_dereference(mm->exe_file);
1015 if (exe_file && !get_file_rcu(exe_file))
1020 EXPORT_SYMBOL(get_mm_exe_file);
1023 * get_task_exe_file - acquire a reference to the task's executable file
1025 * Returns %NULL if task's mm (if any) has no associated executable file or
1026 * this is a kernel thread with borrowed mm (see the comment above get_task_mm).
1027 * User must release file via fput().
1029 struct file *get_task_exe_file(struct task_struct *task)
1031 struct file *exe_file = NULL;
1032 struct mm_struct *mm;
1037 if (!(task->flags & PF_KTHREAD))
1038 exe_file = get_mm_exe_file(mm);
1043 EXPORT_SYMBOL(get_task_exe_file);
1046 * get_task_mm - acquire a reference to the task's mm
1048 * Returns %NULL if the task has no mm. Checks PF_KTHREAD (meaning
1049 * this kernel workthread has transiently adopted a user mm with use_mm,
1050 * to do its AIO) is not set and if so returns a reference to it, after
1051 * bumping up the use count. User must release the mm via mmput()
1052 * after use. Typically used by /proc and ptrace.
1054 struct mm_struct *get_task_mm(struct task_struct *task)
1056 struct mm_struct *mm;
1061 if (task->flags & PF_KTHREAD)
1069 EXPORT_SYMBOL_GPL(get_task_mm);
1071 struct mm_struct *mm_access(struct task_struct *task, unsigned int mode)
1073 struct mm_struct *mm;
1076 err = mutex_lock_killable(&task->signal->cred_guard_mutex);
1078 return ERR_PTR(err);
1080 mm = get_task_mm(task);
1081 if (mm && mm != current->mm &&
1082 !ptrace_may_access(task, mode)) {
1084 mm = ERR_PTR(-EACCES);
1086 mutex_unlock(&task->signal->cred_guard_mutex);
1091 static void complete_vfork_done(struct task_struct *tsk)
1093 struct completion *vfork;
1096 vfork = tsk->vfork_done;
1097 if (likely(vfork)) {
1098 tsk->vfork_done = NULL;
1104 static int wait_for_vfork_done(struct task_struct *child,
1105 struct completion *vfork)
1109 freezer_do_not_count();
1110 killed = wait_for_completion_killable(vfork);
1115 child->vfork_done = NULL;
1119 put_task_struct(child);
1123 /* Please note the differences between mmput and mm_release.
1124 * mmput is called whenever we stop holding onto a mm_struct,
1125 * error success whatever.
1127 * mm_release is called after a mm_struct has been removed
1128 * from the current process.
1130 * This difference is important for error handling, when we
1131 * only half set up a mm_struct for a new process and need to restore
1132 * the old one. Because we mmput the new mm_struct before
1133 * restoring the old one. . .
1134 * Eric Biederman 10 January 1998
1136 static void mm_release(struct task_struct *tsk, struct mm_struct *mm)
1138 uprobe_free_utask(tsk);
1140 /* Get rid of any cached register state */
1141 deactivate_mm(tsk, mm);
1144 * Signal userspace if we're not exiting with a core dump
1145 * because we want to leave the value intact for debugging
1148 if (tsk->clear_child_tid) {
1149 if (!(tsk->signal->flags & SIGNAL_GROUP_COREDUMP) &&
1150 atomic_read(&mm->mm_users) > 1) {
1152 * We don't check the error code - if userspace has
1153 * not set up a proper pointer then tough luck.
1155 put_user(0, tsk->clear_child_tid);
1156 sys_futex(tsk->clear_child_tid, FUTEX_WAKE,
1159 tsk->clear_child_tid = NULL;
1163 * All done, finally we can wake up parent and return this mm to him.
1164 * Also kthread_stop() uses this completion for synchronization.
1166 if (tsk->vfork_done)
1167 complete_vfork_done(tsk);
1170 void exit_mm_release(struct task_struct *tsk, struct mm_struct *mm)
1172 futex_exit_release(tsk);
1173 mm_release(tsk, mm);
1176 void exec_mm_release(struct task_struct *tsk, struct mm_struct *mm)
1178 futex_exec_release(tsk);
1179 mm_release(tsk, mm);
1183 * Allocate a new mm structure and copy contents from the
1184 * mm structure of the passed in task structure.
1186 static struct mm_struct *dup_mm(struct task_struct *tsk)
1188 struct mm_struct *mm, *oldmm = current->mm;
1195 memcpy(mm, oldmm, sizeof(*mm));
1197 if (!mm_init(mm, tsk, mm->user_ns))
1200 err = dup_mmap(mm, oldmm);
1204 mm->hiwater_rss = get_mm_rss(mm);
1205 mm->hiwater_vm = mm->total_vm;
1207 if (mm->binfmt && !try_module_get(mm->binfmt->module))
1213 /* don't put binfmt in mmput, we haven't got module yet */
1215 mm_init_owner(mm, NULL);
1222 static int copy_mm(unsigned long clone_flags, struct task_struct *tsk)
1224 struct mm_struct *mm, *oldmm;
1227 tsk->min_flt = tsk->maj_flt = 0;
1228 tsk->nvcsw = tsk->nivcsw = 0;
1229 #ifdef CONFIG_DETECT_HUNG_TASK
1230 tsk->last_switch_count = tsk->nvcsw + tsk->nivcsw;
1234 tsk->active_mm = NULL;
1237 * Are we cloning a kernel thread?
1239 * We need to steal a active VM for that..
1241 oldmm = current->mm;
1245 /* initialize the new vmacache entries */
1246 vmacache_flush(tsk);
1248 if (clone_flags & CLONE_VM) {
1261 tsk->active_mm = mm;
1268 static int copy_fs(unsigned long clone_flags, struct task_struct *tsk)
1270 struct fs_struct *fs = current->fs;
1271 if (clone_flags & CLONE_FS) {
1272 /* tsk->fs is already what we want */
1273 spin_lock(&fs->lock);
1275 spin_unlock(&fs->lock);
1279 spin_unlock(&fs->lock);
1282 tsk->fs = copy_fs_struct(fs);
1288 static int copy_files(unsigned long clone_flags, struct task_struct *tsk)
1290 struct files_struct *oldf, *newf;
1294 * A background process may not have any files ...
1296 oldf = current->files;
1300 if (clone_flags & CLONE_FILES) {
1301 atomic_inc(&oldf->count);
1305 newf = dup_fd(oldf, &error);
1315 static int copy_io(unsigned long clone_flags, struct task_struct *tsk)
1318 struct io_context *ioc = current->io_context;
1319 struct io_context *new_ioc;
1324 * Share io context with parent, if CLONE_IO is set
1326 if (clone_flags & CLONE_IO) {
1328 tsk->io_context = ioc;
1329 } else if (ioprio_valid(ioc->ioprio)) {
1330 new_ioc = get_task_io_context(tsk, GFP_KERNEL, NUMA_NO_NODE);
1331 if (unlikely(!new_ioc))
1334 new_ioc->ioprio = ioc->ioprio;
1335 put_io_context(new_ioc);
1341 static int copy_sighand(unsigned long clone_flags, struct task_struct *tsk)
1343 struct sighand_struct *sig;
1345 if (clone_flags & CLONE_SIGHAND) {
1346 atomic_inc(¤t->sighand->count);
1349 sig = kmem_cache_alloc(sighand_cachep, GFP_KERNEL);
1350 rcu_assign_pointer(tsk->sighand, sig);
1354 atomic_set(&sig->count, 1);
1355 spin_lock_irq(¤t->sighand->siglock);
1356 memcpy(sig->action, current->sighand->action, sizeof(sig->action));
1357 spin_unlock_irq(¤t->sighand->siglock);
1361 void __cleanup_sighand(struct sighand_struct *sighand)
1363 if (atomic_dec_and_test(&sighand->count)) {
1364 signalfd_cleanup(sighand);
1366 * sighand_cachep is SLAB_TYPESAFE_BY_RCU so we can free it
1367 * without an RCU grace period, see __lock_task_sighand().
1369 kmem_cache_free(sighand_cachep, sighand);
1373 #ifdef CONFIG_POSIX_TIMERS
1375 * Initialize POSIX timer handling for a thread group.
1377 static void posix_cpu_timers_init_group(struct signal_struct *sig)
1379 unsigned long cpu_limit;
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;
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]);
1393 static inline void posix_cpu_timers_init_group(struct signal_struct *sig) { }
1396 static int copy_signal(unsigned long clone_flags, struct task_struct *tsk)
1398 struct signal_struct *sig;
1400 if (clone_flags & CLONE_THREAD)
1403 sig = kmem_cache_zalloc(signal_cachep, GFP_KERNEL);
1408 sig->nr_threads = 1;
1409 atomic_set(&sig->live, 1);
1410 atomic_set(&sig->sigcnt, 1);
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);
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);
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;
1428 task_lock(current->group_leader);
1429 memcpy(sig->rlim, current->signal->rlim, sizeof sig->rlim);
1430 task_unlock(current->group_leader);
1432 posix_cpu_timers_init_group(sig);
1434 tty_audit_fork(sig);
1435 sched_autogroup_fork(sig);
1437 sig->oom_score_adj = current->signal->oom_score_adj;
1438 sig->oom_score_adj_min = current->signal->oom_score_adj_min;
1440 mutex_init(&sig->cred_guard_mutex);
1445 static void copy_seccomp(struct task_struct *p)
1447 #ifdef CONFIG_SECCOMP
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
1454 assert_spin_locked(¤t->sighand->siglock);
1456 /* Ref-count the new filter user, and assign it. */
1457 get_seccomp_filter(current);
1458 p->seccomp = current->seccomp;
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.
1465 if (task_no_new_privs(current))
1466 task_set_no_new_privs(p);
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.
1473 if (p->seccomp.mode != SECCOMP_MODE_DISABLED)
1474 set_tsk_thread_flag(p, TIF_SECCOMP);
1478 SYSCALL_DEFINE1(set_tid_address, int __user *, tidptr)
1480 current->clear_child_tid = tidptr;
1482 return task_pid_vnr(current);
1485 static void rt_mutex_init_task(struct task_struct *p)
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;
1495 #ifdef CONFIG_POSIX_TIMERS
1497 * Initialize POSIX timer handling for a single task.
1499 static void posix_cpu_timers_init(struct task_struct *tsk)
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]);
1509 static inline void posix_cpu_timers_init(struct task_struct *tsk) { }
1513 init_task_pid(struct task_struct *task, enum pid_type type, struct pid *pid)
1515 task->pids[type].pid = pid;
1518 static inline void rcu_copy_process(struct task_struct *p)
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 */
1533 static void __delayed_free_task(struct rcu_head *rhp)
1535 struct task_struct *tsk = container_of(rhp, struct task_struct, rcu);
1540 static __always_inline void delayed_free_task(struct task_struct *tsk)
1542 if (IS_ENABLED(CONFIG_MEMCG))
1543 call_rcu(&tsk->rcu, __delayed_free_task);
1548 static void copy_oom_score_adj(u64 clone_flags, struct task_struct *tsk)
1550 /* Skip if kernel thread */
1554 /* Skip if spawning a thread or using vfork */
1555 if ((clone_flags & (CLONE_VM | CLONE_THREAD | CLONE_VFORK)) != CLONE_VM)
1558 /* We need to synchronize with __set_oom_adj */
1559 mutex_lock(&oom_adj_mutex);
1560 set_bit(MMF_MULTIPROCESS, &tsk->mm->flags);
1561 /* Update the values in case they were changed after copy_signal */
1562 tsk->signal->oom_score_adj = current->signal->oom_score_adj;
1563 tsk->signal->oom_score_adj_min = current->signal->oom_score_adj_min;
1564 mutex_unlock(&oom_adj_mutex);
1568 * This creates a new process as a copy of the old one,
1569 * but does not actually start it yet.
1571 * It copies the registers, and all the appropriate
1572 * parts of the process environment (as per the clone
1573 * flags). The actual kick-off is left to the caller.
1575 static __latent_entropy struct task_struct *copy_process(
1576 unsigned long clone_flags,
1577 unsigned long stack_start,
1578 unsigned long stack_size,
1579 int __user *child_tidptr,
1586 struct task_struct *p;
1588 if ((clone_flags & (CLONE_NEWNS|CLONE_FS)) == (CLONE_NEWNS|CLONE_FS))
1589 return ERR_PTR(-EINVAL);
1591 if ((clone_flags & (CLONE_NEWUSER|CLONE_FS)) == (CLONE_NEWUSER|CLONE_FS))
1592 return ERR_PTR(-EINVAL);
1595 * Thread groups must share signals as well, and detached threads
1596 * can only be started up within the thread group.
1598 if ((clone_flags & CLONE_THREAD) && !(clone_flags & CLONE_SIGHAND))
1599 return ERR_PTR(-EINVAL);
1602 * Shared signal handlers imply shared VM. By way of the above,
1603 * thread groups also imply shared VM. Blocking this case allows
1604 * for various simplifications in other code.
1606 if ((clone_flags & CLONE_SIGHAND) && !(clone_flags & CLONE_VM))
1607 return ERR_PTR(-EINVAL);
1610 * Siblings of global init remain as zombies on exit since they are
1611 * not reaped by their parent (swapper). To solve this and to avoid
1612 * multi-rooted process trees, prevent global and container-inits
1613 * from creating siblings.
1615 if ((clone_flags & CLONE_PARENT) &&
1616 current->signal->flags & SIGNAL_UNKILLABLE)
1617 return ERR_PTR(-EINVAL);
1620 * If the new process will be in a different pid or user namespace
1621 * do not allow it to share a thread group with the forking task.
1623 if (clone_flags & CLONE_THREAD) {
1624 if ((clone_flags & (CLONE_NEWUSER | CLONE_NEWPID)) ||
1625 (task_active_pid_ns(current) !=
1626 current->nsproxy->pid_ns_for_children))
1627 return ERR_PTR(-EINVAL);
1631 p = dup_task_struct(current, node);
1636 * This _must_ happen before we call free_task(), i.e. before we jump
1637 * to any of the bad_fork_* labels. This is to avoid freeing
1638 * p->set_child_tid which is (ab)used as a kthread's data pointer for
1639 * kernel threads (PF_KTHREAD).
1641 p->set_child_tid = (clone_flags & CLONE_CHILD_SETTID) ? child_tidptr : NULL;
1643 * Clear TID on mm_release()?
1645 p->clear_child_tid = (clone_flags & CLONE_CHILD_CLEARTID) ? child_tidptr : NULL;
1647 ftrace_graph_init_task(p);
1649 rt_mutex_init_task(p);
1651 #ifdef CONFIG_PROVE_LOCKING
1652 DEBUG_LOCKS_WARN_ON(!p->hardirqs_enabled);
1653 DEBUG_LOCKS_WARN_ON(!p->softirqs_enabled);
1656 if (atomic_read(&p->real_cred->user->processes) >=
1657 task_rlimit(p, RLIMIT_NPROC)) {
1658 if (p->real_cred->user != INIT_USER &&
1659 !capable(CAP_SYS_RESOURCE) && !capable(CAP_SYS_ADMIN))
1662 current->flags &= ~PF_NPROC_EXCEEDED;
1664 retval = copy_creds(p, clone_flags);
1669 * If multiple threads are within copy_process(), then this check
1670 * triggers too late. This doesn't hurt, the check is only there
1671 * to stop root fork bombs.
1674 if (nr_threads >= max_threads)
1675 goto bad_fork_cleanup_count;
1677 delayacct_tsk_init(p); /* Must remain after dup_task_struct() */
1678 p->flags &= ~(PF_SUPERPRIV | PF_WQ_WORKER | PF_IDLE);
1679 p->flags |= PF_FORKNOEXEC;
1680 INIT_LIST_HEAD(&p->children);
1681 INIT_LIST_HEAD(&p->sibling);
1682 rcu_copy_process(p);
1683 p->vfork_done = NULL;
1684 spin_lock_init(&p->alloc_lock);
1686 init_sigpending(&p->pending);
1688 p->utime = p->stime = p->gtime = 0;
1689 #ifdef CONFIG_ARCH_HAS_SCALED_CPUTIME
1690 p->utimescaled = p->stimescaled = 0;
1692 prev_cputime_init(&p->prev_cputime);
1694 #ifdef CONFIG_VIRT_CPU_ACCOUNTING_GEN
1695 seqcount_init(&p->vtime.seqcount);
1696 p->vtime.starttime = 0;
1697 p->vtime.state = VTIME_INACTIVE;
1700 #if defined(SPLIT_RSS_COUNTING)
1701 memset(&p->rss_stat, 0, sizeof(p->rss_stat));
1704 p->default_timer_slack_ns = current->timer_slack_ns;
1706 task_io_accounting_init(&p->ioac);
1707 acct_clear_integrals(p);
1709 posix_cpu_timers_init(p);
1711 p->io_context = NULL;
1712 p->audit_context = NULL;
1715 p->mempolicy = mpol_dup(p->mempolicy);
1716 if (IS_ERR(p->mempolicy)) {
1717 retval = PTR_ERR(p->mempolicy);
1718 p->mempolicy = NULL;
1719 goto bad_fork_cleanup_threadgroup_lock;
1722 #ifdef CONFIG_CPUSETS
1723 p->cpuset_mem_spread_rotor = NUMA_NO_NODE;
1724 p->cpuset_slab_spread_rotor = NUMA_NO_NODE;
1725 seqcount_init(&p->mems_allowed_seq);
1727 #ifdef CONFIG_TRACE_IRQFLAGS
1729 p->hardirqs_enabled = 0;
1730 p->hardirq_enable_ip = 0;
1731 p->hardirq_enable_event = 0;
1732 p->hardirq_disable_ip = _THIS_IP_;
1733 p->hardirq_disable_event = 0;
1734 p->softirqs_enabled = 1;
1735 p->softirq_enable_ip = _THIS_IP_;
1736 p->softirq_enable_event = 0;
1737 p->softirq_disable_ip = 0;
1738 p->softirq_disable_event = 0;
1739 p->hardirq_context = 0;
1740 p->softirq_context = 0;
1743 p->pagefault_disabled = 0;
1745 #ifdef CONFIG_LOCKDEP
1746 p->lockdep_depth = 0; /* no locks held yet */
1747 p->curr_chain_key = 0;
1748 p->lockdep_recursion = 0;
1749 lockdep_init_task(p);
1752 #ifdef CONFIG_DEBUG_MUTEXES
1753 p->blocked_on = NULL; /* not blocked yet */
1755 #ifdef CONFIG_BCACHE
1756 p->sequential_io = 0;
1757 p->sequential_io_avg = 0;
1760 /* Perform scheduler related setup. Assign this task to a CPU. */
1761 retval = sched_fork(clone_flags, p);
1763 goto bad_fork_cleanup_policy;
1765 retval = perf_event_init_task(p);
1767 goto bad_fork_cleanup_policy;
1768 retval = audit_alloc(p);
1770 goto bad_fork_cleanup_perf;
1771 /* copy all the process information */
1773 retval = security_task_alloc(p, clone_flags);
1775 goto bad_fork_cleanup_audit;
1776 retval = copy_semundo(clone_flags, p);
1778 goto bad_fork_cleanup_security;
1779 retval = copy_files(clone_flags, p);
1781 goto bad_fork_cleanup_semundo;
1782 retval = copy_fs(clone_flags, p);
1784 goto bad_fork_cleanup_files;
1785 retval = copy_sighand(clone_flags, p);
1787 goto bad_fork_cleanup_fs;
1788 retval = copy_signal(clone_flags, p);
1790 goto bad_fork_cleanup_sighand;
1791 retval = copy_mm(clone_flags, p);
1793 goto bad_fork_cleanup_signal;
1794 retval = copy_namespaces(clone_flags, p);
1796 goto bad_fork_cleanup_mm;
1797 retval = copy_io(clone_flags, p);
1799 goto bad_fork_cleanup_namespaces;
1800 retval = copy_thread_tls(clone_flags, stack_start, stack_size, p, tls);
1802 goto bad_fork_cleanup_io;
1804 if (pid != &init_struct_pid) {
1805 pid = alloc_pid(p->nsproxy->pid_ns_for_children);
1807 retval = PTR_ERR(pid);
1808 goto bad_fork_cleanup_thread;
1818 * sigaltstack should be cleared when sharing the same VM
1820 if ((clone_flags & (CLONE_VM|CLONE_VFORK)) == CLONE_VM)
1824 * Syscall tracing and stepping should be turned off in the
1825 * child regardless of CLONE_PTRACE.
1827 user_disable_single_step(p);
1828 clear_tsk_thread_flag(p, TIF_SYSCALL_TRACE);
1829 #ifdef TIF_SYSCALL_EMU
1830 clear_tsk_thread_flag(p, TIF_SYSCALL_EMU);
1832 clear_all_latency_tracing(p);
1834 /* ok, now we should be set up.. */
1835 p->pid = pid_nr(pid);
1836 if (clone_flags & CLONE_THREAD) {
1837 p->group_leader = current->group_leader;
1838 p->tgid = current->tgid;
1840 p->group_leader = p;
1845 p->nr_dirtied_pause = 128 >> (PAGE_SHIFT - 10);
1846 p->dirty_paused_when = 0;
1848 p->pdeath_signal = 0;
1849 INIT_LIST_HEAD(&p->thread_group);
1850 p->task_works = NULL;
1852 cgroup_threadgroup_change_begin(current);
1854 * Ensure that the cgroup subsystem policies allow the new process to be
1855 * forked. It should be noted the the new process's css_set can be changed
1856 * between here and cgroup_post_fork() if an organisation operation is in
1859 retval = cgroup_can_fork(p);
1861 goto bad_fork_free_pid;
1864 * From this point on we must avoid any synchronous user-space
1865 * communication until we take the tasklist-lock. In particular, we do
1866 * not want user-space to be able to predict the process start-time by
1867 * stalling fork(2) after we recorded the start_time but before it is
1868 * visible to the system.
1871 p->start_time = ktime_get_ns();
1872 p->real_start_time = ktime_get_boot_ns();
1875 * Make it visible to the rest of the system, but dont wake it up yet.
1876 * Need tasklist lock for parent etc handling!
1878 write_lock_irq(&tasklist_lock);
1880 /* CLONE_PARENT re-uses the old parent */
1881 if (clone_flags & (CLONE_PARENT|CLONE_THREAD)) {
1882 p->real_parent = current->real_parent;
1883 p->parent_exec_id = current->parent_exec_id;
1884 if (clone_flags & CLONE_THREAD)
1885 p->exit_signal = -1;
1887 p->exit_signal = current->group_leader->exit_signal;
1889 p->real_parent = current;
1890 p->parent_exec_id = current->self_exec_id;
1891 p->exit_signal = (clone_flags & CSIGNAL);
1894 klp_copy_process(p);
1896 spin_lock(¤t->sighand->siglock);
1899 * Copy seccomp details explicitly here, in case they were changed
1900 * before holding sighand lock.
1905 * Process group and session signals need to be delivered to just the
1906 * parent before the fork or both the parent and the child after the
1907 * fork. Restart if a signal comes in before we add the new process to
1908 * it's process group.
1909 * A fatal signal pending means that current will exit, so the new
1910 * thread can't slip out of an OOM kill (or normal SIGKILL).
1912 recalc_sigpending();
1913 if (signal_pending(current)) {
1914 retval = -ERESTARTNOINTR;
1915 goto bad_fork_cancel_cgroup;
1917 if (unlikely(!(ns_of_pid(pid)->nr_hashed & PIDNS_HASH_ADDING))) {
1919 goto bad_fork_cancel_cgroup;
1922 if (likely(p->pid)) {
1923 ptrace_init_task(p, (clone_flags & CLONE_PTRACE) || trace);
1925 init_task_pid(p, PIDTYPE_PID, pid);
1926 if (thread_group_leader(p)) {
1927 init_task_pid(p, PIDTYPE_PGID, task_pgrp(current));
1928 init_task_pid(p, PIDTYPE_SID, task_session(current));
1930 if (is_child_reaper(pid)) {
1931 ns_of_pid(pid)->child_reaper = p;
1932 p->signal->flags |= SIGNAL_UNKILLABLE;
1935 p->signal->leader_pid = pid;
1936 p->signal->tty = tty_kref_get(current->signal->tty);
1938 * Inherit has_child_subreaper flag under the same
1939 * tasklist_lock with adding child to the process tree
1940 * for propagate_has_child_subreaper optimization.
1942 p->signal->has_child_subreaper = p->real_parent->signal->has_child_subreaper ||
1943 p->real_parent->signal->is_child_subreaper;
1944 list_add_tail(&p->sibling, &p->real_parent->children);
1945 list_add_tail_rcu(&p->tasks, &init_task.tasks);
1946 attach_pid(p, PIDTYPE_PGID);
1947 attach_pid(p, PIDTYPE_SID);
1948 __this_cpu_inc(process_counts);
1950 current->signal->nr_threads++;
1951 atomic_inc(¤t->signal->live);
1952 atomic_inc(¤t->signal->sigcnt);
1953 list_add_tail_rcu(&p->thread_group,
1954 &p->group_leader->thread_group);
1955 list_add_tail_rcu(&p->thread_node,
1956 &p->signal->thread_head);
1958 attach_pid(p, PIDTYPE_PID);
1963 spin_unlock(¤t->sighand->siglock);
1964 syscall_tracepoint_update(p);
1965 write_unlock_irq(&tasklist_lock);
1967 proc_fork_connector(p);
1968 cgroup_post_fork(p);
1969 cgroup_threadgroup_change_end(current);
1972 trace_task_newtask(p, clone_flags);
1973 uprobe_copy_process(p, clone_flags);
1975 copy_oom_score_adj(clone_flags, p);
1979 bad_fork_cancel_cgroup:
1980 spin_unlock(¤t->sighand->siglock);
1981 write_unlock_irq(&tasklist_lock);
1982 cgroup_cancel_fork(p);
1984 cgroup_threadgroup_change_end(current);
1985 if (pid != &init_struct_pid)
1987 bad_fork_cleanup_thread:
1989 bad_fork_cleanup_io:
1992 bad_fork_cleanup_namespaces:
1993 exit_task_namespaces(p);
1994 bad_fork_cleanup_mm:
1996 mm_clear_owner(p->mm, p);
1999 bad_fork_cleanup_signal:
2000 if (!(clone_flags & CLONE_THREAD))
2001 free_signal_struct(p->signal);
2002 bad_fork_cleanup_sighand:
2003 __cleanup_sighand(p->sighand);
2004 bad_fork_cleanup_fs:
2005 exit_fs(p); /* blocking */
2006 bad_fork_cleanup_files:
2007 exit_files(p); /* blocking */
2008 bad_fork_cleanup_semundo:
2010 bad_fork_cleanup_security:
2011 security_task_free(p);
2012 bad_fork_cleanup_audit:
2014 bad_fork_cleanup_perf:
2015 perf_event_free_task(p);
2016 bad_fork_cleanup_policy:
2017 lockdep_free_task(p);
2019 mpol_put(p->mempolicy);
2020 bad_fork_cleanup_threadgroup_lock:
2022 delayacct_tsk_free(p);
2023 bad_fork_cleanup_count:
2024 atomic_dec(&p->cred->user->processes);
2027 p->state = TASK_DEAD;
2029 delayed_free_task(p);
2031 return ERR_PTR(retval);
2034 static inline void init_idle_pids(struct pid_link *links)
2038 for (type = PIDTYPE_PID; type < PIDTYPE_MAX; ++type) {
2039 INIT_HLIST_NODE(&links[type].node); /* not really needed */
2040 links[type].pid = &init_struct_pid;
2044 struct task_struct *fork_idle(int cpu)
2046 struct task_struct *task;
2047 task = copy_process(CLONE_VM, 0, 0, NULL, &init_struct_pid, 0, 0,
2049 if (!IS_ERR(task)) {
2050 init_idle_pids(task->pids);
2051 init_idle(task, cpu);
2058 * Ok, this is the main fork-routine.
2060 * It copies the process, and if successful kick-starts
2061 * it and waits for it to finish using the VM if required.
2063 long _do_fork(unsigned long clone_flags,
2064 unsigned long stack_start,
2065 unsigned long stack_size,
2066 int __user *parent_tidptr,
2067 int __user *child_tidptr,
2070 struct task_struct *p;
2075 * Determine whether and which event to report to ptracer. When
2076 * called from kernel_thread or CLONE_UNTRACED is explicitly
2077 * requested, no event is reported; otherwise, report if the event
2078 * for the type of forking is enabled.
2080 if (!(clone_flags & CLONE_UNTRACED)) {
2081 if (clone_flags & CLONE_VFORK)
2082 trace = PTRACE_EVENT_VFORK;
2083 else if ((clone_flags & CSIGNAL) != SIGCHLD)
2084 trace = PTRACE_EVENT_CLONE;
2086 trace = PTRACE_EVENT_FORK;
2088 if (likely(!ptrace_event_enabled(current, trace)))
2092 p = copy_process(clone_flags, stack_start, stack_size,
2093 child_tidptr, NULL, trace, tls, NUMA_NO_NODE);
2094 add_latent_entropy();
2096 * Do this prior waking up the new thread - the thread pointer
2097 * might get invalid after that point, if the thread exits quickly.
2100 struct completion vfork;
2103 trace_sched_process_fork(current, p);
2105 pid = get_task_pid(p, PIDTYPE_PID);
2108 if (clone_flags & CLONE_PARENT_SETTID)
2109 put_user(nr, parent_tidptr);
2111 if (clone_flags & CLONE_VFORK) {
2112 p->vfork_done = &vfork;
2113 init_completion(&vfork);
2117 wake_up_new_task(p);
2119 /* forking complete and child started to run, tell ptracer */
2120 if (unlikely(trace))
2121 ptrace_event_pid(trace, pid);
2123 if (clone_flags & CLONE_VFORK) {
2124 if (!wait_for_vfork_done(p, &vfork))
2125 ptrace_event_pid(PTRACE_EVENT_VFORK_DONE, pid);
2135 #ifndef CONFIG_HAVE_COPY_THREAD_TLS
2136 /* For compatibility with architectures that call do_fork directly rather than
2137 * using the syscall entry points below. */
2138 long do_fork(unsigned long clone_flags,
2139 unsigned long stack_start,
2140 unsigned long stack_size,
2141 int __user *parent_tidptr,
2142 int __user *child_tidptr)
2144 return _do_fork(clone_flags, stack_start, stack_size,
2145 parent_tidptr, child_tidptr, 0);
2150 * Create a kernel thread.
2152 pid_t kernel_thread(int (*fn)(void *), void *arg, unsigned long flags)
2154 return _do_fork(flags|CLONE_VM|CLONE_UNTRACED, (unsigned long)fn,
2155 (unsigned long)arg, NULL, NULL, 0);
2158 #ifdef __ARCH_WANT_SYS_FORK
2159 SYSCALL_DEFINE0(fork)
2162 return _do_fork(SIGCHLD, 0, 0, NULL, NULL, 0);
2164 /* can not support in nommu mode */
2170 #ifdef __ARCH_WANT_SYS_VFORK
2171 SYSCALL_DEFINE0(vfork)
2173 return _do_fork(CLONE_VFORK | CLONE_VM | SIGCHLD, 0,
2178 #ifdef __ARCH_WANT_SYS_CLONE
2179 #ifdef CONFIG_CLONE_BACKWARDS
2180 SYSCALL_DEFINE5(clone, unsigned long, clone_flags, unsigned long, newsp,
2181 int __user *, parent_tidptr,
2183 int __user *, child_tidptr)
2184 #elif defined(CONFIG_CLONE_BACKWARDS2)
2185 SYSCALL_DEFINE5(clone, unsigned long, newsp, unsigned long, clone_flags,
2186 int __user *, parent_tidptr,
2187 int __user *, child_tidptr,
2189 #elif defined(CONFIG_CLONE_BACKWARDS3)
2190 SYSCALL_DEFINE6(clone, unsigned long, clone_flags, unsigned long, newsp,
2192 int __user *, parent_tidptr,
2193 int __user *, child_tidptr,
2196 SYSCALL_DEFINE5(clone, unsigned long, clone_flags, unsigned long, newsp,
2197 int __user *, parent_tidptr,
2198 int __user *, child_tidptr,
2202 return _do_fork(clone_flags, newsp, 0, parent_tidptr, child_tidptr, tls);
2206 void walk_process_tree(struct task_struct *top, proc_visitor visitor, void *data)
2208 struct task_struct *leader, *parent, *child;
2211 read_lock(&tasklist_lock);
2212 leader = top = top->group_leader;
2214 for_each_thread(leader, parent) {
2215 list_for_each_entry(child, &parent->children, sibling) {
2216 res = visitor(child, data);
2228 if (leader != top) {
2230 parent = child->real_parent;
2231 leader = parent->group_leader;
2235 read_unlock(&tasklist_lock);
2238 #ifndef ARCH_MIN_MMSTRUCT_ALIGN
2239 #define ARCH_MIN_MMSTRUCT_ALIGN 0
2242 static void sighand_ctor(void *data)
2244 struct sighand_struct *sighand = data;
2246 spin_lock_init(&sighand->siglock);
2247 init_waitqueue_head(&sighand->signalfd_wqh);
2250 void __init proc_caches_init(void)
2252 sighand_cachep = kmem_cache_create("sighand_cache",
2253 sizeof(struct sighand_struct), 0,
2254 SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_TYPESAFE_BY_RCU|
2255 SLAB_ACCOUNT, sighand_ctor);
2256 signal_cachep = kmem_cache_create("signal_cache",
2257 sizeof(struct signal_struct), 0,
2258 SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_ACCOUNT,
2260 files_cachep = kmem_cache_create("files_cache",
2261 sizeof(struct files_struct), 0,
2262 SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_ACCOUNT,
2264 fs_cachep = kmem_cache_create("fs_cache",
2265 sizeof(struct fs_struct), 0,
2266 SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_ACCOUNT,
2269 * FIXME! The "sizeof(struct mm_struct)" currently includes the
2270 * whole struct cpumask for the OFFSTACK case. We could change
2271 * this to *only* allocate as much of it as required by the
2272 * maximum number of CPU's we can ever have. The cpumask_allocation
2273 * is at the end of the structure, exactly for that reason.
2275 mm_cachep = kmem_cache_create("mm_struct",
2276 sizeof(struct mm_struct), ARCH_MIN_MMSTRUCT_ALIGN,
2277 SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_ACCOUNT,
2279 vm_area_cachep = KMEM_CACHE(vm_area_struct, SLAB_PANIC|SLAB_ACCOUNT);
2281 nsproxy_cache_init();
2285 * Check constraints on flags passed to the unshare system call.
2287 static int check_unshare_flags(unsigned long unshare_flags)
2289 if (unshare_flags & ~(CLONE_THREAD|CLONE_FS|CLONE_NEWNS|CLONE_SIGHAND|
2290 CLONE_VM|CLONE_FILES|CLONE_SYSVSEM|
2291 CLONE_NEWUTS|CLONE_NEWIPC|CLONE_NEWNET|
2292 CLONE_NEWUSER|CLONE_NEWPID|CLONE_NEWCGROUP))
2295 * Not implemented, but pretend it works if there is nothing
2296 * to unshare. Note that unsharing the address space or the
2297 * signal handlers also need to unshare the signal queues (aka
2300 if (unshare_flags & (CLONE_THREAD | CLONE_SIGHAND | CLONE_VM)) {
2301 if (!thread_group_empty(current))
2304 if (unshare_flags & (CLONE_SIGHAND | CLONE_VM)) {
2305 if (atomic_read(¤t->sighand->count) > 1)
2308 if (unshare_flags & CLONE_VM) {
2309 if (!current_is_single_threaded())
2317 * Unshare the filesystem structure if it is being shared
2319 static int unshare_fs(unsigned long unshare_flags, struct fs_struct **new_fsp)
2321 struct fs_struct *fs = current->fs;
2323 if (!(unshare_flags & CLONE_FS) || !fs)
2326 /* don't need lock here; in the worst case we'll do useless copy */
2330 *new_fsp = copy_fs_struct(fs);
2338 * Unshare file descriptor table if it is being shared
2340 static int unshare_fd(unsigned long unshare_flags, struct files_struct **new_fdp)
2342 struct files_struct *fd = current->files;
2345 if ((unshare_flags & CLONE_FILES) &&
2346 (fd && atomic_read(&fd->count) > 1)) {
2347 *new_fdp = dup_fd(fd, &error);
2356 * unshare allows a process to 'unshare' part of the process
2357 * context which was originally shared using clone. copy_*
2358 * functions used by do_fork() cannot be used here directly
2359 * because they modify an inactive task_struct that is being
2360 * constructed. Here we are modifying the current, active,
2363 SYSCALL_DEFINE1(unshare, unsigned long, unshare_flags)
2365 struct fs_struct *fs, *new_fs = NULL;
2366 struct files_struct *fd, *new_fd = NULL;
2367 struct cred *new_cred = NULL;
2368 struct nsproxy *new_nsproxy = NULL;
2373 * If unsharing a user namespace must also unshare the thread group
2374 * and unshare the filesystem root and working directories.
2376 if (unshare_flags & CLONE_NEWUSER)
2377 unshare_flags |= CLONE_THREAD | CLONE_FS;
2379 * If unsharing vm, must also unshare signal handlers.
2381 if (unshare_flags & CLONE_VM)
2382 unshare_flags |= CLONE_SIGHAND;
2384 * If unsharing a signal handlers, must also unshare the signal queues.
2386 if (unshare_flags & CLONE_SIGHAND)
2387 unshare_flags |= CLONE_THREAD;
2389 * If unsharing namespace, must also unshare filesystem information.
2391 if (unshare_flags & CLONE_NEWNS)
2392 unshare_flags |= CLONE_FS;
2394 err = check_unshare_flags(unshare_flags);
2396 goto bad_unshare_out;
2398 * CLONE_NEWIPC must also detach from the undolist: after switching
2399 * to a new ipc namespace, the semaphore arrays from the old
2400 * namespace are unreachable.
2402 if (unshare_flags & (CLONE_NEWIPC|CLONE_SYSVSEM))
2404 err = unshare_fs(unshare_flags, &new_fs);
2406 goto bad_unshare_out;
2407 err = unshare_fd(unshare_flags, &new_fd);
2409 goto bad_unshare_cleanup_fs;
2410 err = unshare_userns(unshare_flags, &new_cred);
2412 goto bad_unshare_cleanup_fd;
2413 err = unshare_nsproxy_namespaces(unshare_flags, &new_nsproxy,
2416 goto bad_unshare_cleanup_cred;
2418 if (new_fs || new_fd || do_sysvsem || new_cred || new_nsproxy) {
2421 * CLONE_SYSVSEM is equivalent to sys_exit().
2425 if (unshare_flags & CLONE_NEWIPC) {
2426 /* Orphan segments in old ns (see sem above). */
2428 shm_init_task(current);
2432 switch_task_namespaces(current, new_nsproxy);
2438 spin_lock(&fs->lock);
2439 current->fs = new_fs;
2444 spin_unlock(&fs->lock);
2448 fd = current->files;
2449 current->files = new_fd;
2453 task_unlock(current);
2456 /* Install the new user namespace */
2457 commit_creds(new_cred);
2462 perf_event_namespaces(current);
2464 bad_unshare_cleanup_cred:
2467 bad_unshare_cleanup_fd:
2469 put_files_struct(new_fd);
2471 bad_unshare_cleanup_fs:
2473 free_fs_struct(new_fs);
2480 * Helper to unshare the files of the current task.
2481 * We don't want to expose copy_files internals to
2482 * the exec layer of the kernel.
2485 int unshare_files(struct files_struct **displaced)
2487 struct task_struct *task = current;
2488 struct files_struct *copy = NULL;
2491 error = unshare_fd(CLONE_FILES, ©);
2492 if (error || !copy) {
2496 *displaced = task->files;
2503 int sysctl_max_threads(struct ctl_table *table, int write,
2504 void __user *buffer, size_t *lenp, loff_t *ppos)
2508 int threads = max_threads;
2510 int max = MAX_THREADS;
2517 ret = proc_dointvec_minmax(&t, write, buffer, lenp, ppos);
2521 max_threads = threads;