1 // SPDX-License-Identifier: GPL-2.0-only
5 * Copyright (C) 1991, 1992 Linus Torvalds
9 * 'fork.c' contains the help-routines for the 'fork' system call
10 * (see also entry.S and others).
11 * Fork is rather simple, once you get the hang of it, but the memory
12 * management can be a bitch. See 'mm/memory.c': 'copy_page_range()'
15 #include <linux/anon_inodes.h>
16 #include <linux/slab.h>
17 #include <linux/sched/autogroup.h>
18 #include <linux/sched/mm.h>
19 #include <linux/sched/coredump.h>
20 #include <linux/sched/user.h>
21 #include <linux/sched/numa_balancing.h>
22 #include <linux/sched/stat.h>
23 #include <linux/sched/task.h>
24 #include <linux/sched/task_stack.h>
25 #include <linux/sched/cputime.h>
26 #include <linux/seq_file.h>
27 #include <linux/rtmutex.h>
28 #include <linux/init.h>
29 #include <linux/unistd.h>
30 #include <linux/module.h>
31 #include <linux/vmalloc.h>
32 #include <linux/completion.h>
33 #include <linux/personality.h>
34 #include <linux/mempolicy.h>
35 #include <linux/sem.h>
36 #include <linux/file.h>
37 #include <linux/fdtable.h>
38 #include <linux/iocontext.h>
39 #include <linux/key.h>
40 #include <linux/binfmts.h>
41 #include <linux/mman.h>
42 #include <linux/mmu_notifier.h>
45 #include <linux/vmacache.h>
46 #include <linux/nsproxy.h>
47 #include <linux/capability.h>
48 #include <linux/cpu.h>
49 #include <linux/cgroup.h>
50 #include <linux/security.h>
51 #include <linux/hugetlb.h>
52 #include <linux/seccomp.h>
53 #include <linux/swap.h>
54 #include <linux/syscalls.h>
55 #include <linux/jiffies.h>
56 #include <linux/futex.h>
57 #include <linux/compat.h>
58 #include <linux/kthread.h>
59 #include <linux/task_io_accounting_ops.h>
60 #include <linux/rcupdate.h>
61 #include <linux/ptrace.h>
62 #include <linux/mount.h>
63 #include <linux/audit.h>
64 #include <linux/memcontrol.h>
65 #include <linux/ftrace.h>
66 #include <linux/proc_fs.h>
67 #include <linux/profile.h>
68 #include <linux/rmap.h>
69 #include <linux/ksm.h>
70 #include <linux/acct.h>
71 #include <linux/userfaultfd_k.h>
72 #include <linux/tsacct_kern.h>
73 #include <linux/cn_proc.h>
74 #include <linux/freezer.h>
75 #include <linux/delayacct.h>
76 #include <linux/taskstats_kern.h>
77 #include <linux/random.h>
78 #include <linux/tty.h>
79 #include <linux/blkdev.h>
80 #include <linux/fs_struct.h>
81 #include <linux/magic.h>
82 #include <linux/perf_event.h>
83 #include <linux/posix-timers.h>
84 #include <linux/user-return-notifier.h>
85 #include <linux/oom.h>
86 #include <linux/khugepaged.h>
87 #include <linux/signalfd.h>
88 #include <linux/uprobes.h>
89 #include <linux/aio.h>
90 #include <linux/compiler.h>
91 #include <linux/sysctl.h>
92 #include <linux/kcov.h>
93 #include <linux/livepatch.h>
94 #include <linux/thread_info.h>
95 #include <linux/stackleak.h>
96 #include <linux/kasan.h>
97 #include <linux/scs.h>
98 #include <linux/io_uring.h>
99 #include <linux/bpf.h>
101 #include <asm/pgalloc.h>
102 #include <linux/uaccess.h>
103 #include <asm/mmu_context.h>
104 #include <asm/cacheflush.h>
105 #include <asm/tlbflush.h>
107 #include <trace/events/sched.h>
109 #define CREATE_TRACE_POINTS
110 #include <trace/events/task.h>
113 * Minimum number of threads to boot the kernel
115 #define MIN_THREADS 20
118 * Maximum number of threads
120 #define MAX_THREADS FUTEX_TID_MASK
123 * Protected counters by write_lock_irq(&tasklist_lock)
125 unsigned long total_forks; /* Handle normal Linux uptimes. */
126 int nr_threads; /* The idle threads do not count.. */
128 static int max_threads; /* tunable limit on nr_threads */
130 #define NAMED_ARRAY_INDEX(x) [x] = __stringify(x)
132 static const char * const resident_page_types[] = {
133 NAMED_ARRAY_INDEX(MM_FILEPAGES),
134 NAMED_ARRAY_INDEX(MM_ANONPAGES),
135 NAMED_ARRAY_INDEX(MM_SWAPENTS),
136 NAMED_ARRAY_INDEX(MM_SHMEMPAGES),
139 DEFINE_PER_CPU(unsigned long, process_counts) = 0;
141 __cacheline_aligned DEFINE_RWLOCK(tasklist_lock); /* outer */
143 #ifdef CONFIG_PROVE_RCU
144 int lockdep_tasklist_lock_is_held(void)
146 return lockdep_is_held(&tasklist_lock);
148 EXPORT_SYMBOL_GPL(lockdep_tasklist_lock_is_held);
149 #endif /* #ifdef CONFIG_PROVE_RCU */
151 int nr_processes(void)
156 for_each_possible_cpu(cpu)
157 total += per_cpu(process_counts, cpu);
162 void __weak arch_release_task_struct(struct task_struct *tsk)
166 #ifndef CONFIG_ARCH_TASK_STRUCT_ALLOCATOR
167 static struct kmem_cache *task_struct_cachep;
169 static inline struct task_struct *alloc_task_struct_node(int node)
171 return kmem_cache_alloc_node(task_struct_cachep, GFP_KERNEL, node);
174 static inline void free_task_struct(struct task_struct *tsk)
176 kmem_cache_free(task_struct_cachep, tsk);
180 #ifndef CONFIG_ARCH_THREAD_STACK_ALLOCATOR
183 * Allocate pages if THREAD_SIZE is >= PAGE_SIZE, otherwise use a
184 * kmemcache based allocator.
186 # if THREAD_SIZE >= PAGE_SIZE || defined(CONFIG_VMAP_STACK)
188 #ifdef CONFIG_VMAP_STACK
190 * vmalloc() is a bit slow, and calling vfree() enough times will force a TLB
191 * flush. Try to minimize the number of calls by caching stacks.
193 #define NR_CACHED_STACKS 2
194 static DEFINE_PER_CPU(struct vm_struct *, cached_stacks[NR_CACHED_STACKS]);
196 static int free_vm_stack_cache(unsigned int cpu)
198 struct vm_struct **cached_vm_stacks = per_cpu_ptr(cached_stacks, cpu);
201 for (i = 0; i < NR_CACHED_STACKS; i++) {
202 struct vm_struct *vm_stack = cached_vm_stacks[i];
207 vfree(vm_stack->addr);
208 cached_vm_stacks[i] = NULL;
215 static unsigned long *alloc_thread_stack_node(struct task_struct *tsk, int node)
217 #ifdef CONFIG_VMAP_STACK
221 for (i = 0; i < NR_CACHED_STACKS; i++) {
224 s = this_cpu_xchg(cached_stacks[i], NULL);
229 /* Mark stack accessible for KASAN. */
230 kasan_unpoison_range(s->addr, THREAD_SIZE);
232 /* Clear stale pointers from reused stack. */
233 memset(s->addr, 0, THREAD_SIZE);
235 tsk->stack_vm_area = s;
236 tsk->stack = s->addr;
241 * Allocated stacks are cached and later reused by new threads,
242 * so memcg accounting is performed manually on assigning/releasing
243 * stacks to tasks. Drop __GFP_ACCOUNT.
245 stack = __vmalloc_node_range(THREAD_SIZE, THREAD_ALIGN,
246 VMALLOC_START, VMALLOC_END,
247 THREADINFO_GFP & ~__GFP_ACCOUNT,
249 0, node, __builtin_return_address(0));
252 * We can't call find_vm_area() in interrupt context, and
253 * free_thread_stack() can be called in interrupt context,
254 * so cache the vm_struct.
257 tsk->stack_vm_area = find_vm_area(stack);
262 struct page *page = alloc_pages_node(node, THREADINFO_GFP,
266 tsk->stack = kasan_reset_tag(page_address(page));
273 static inline void free_thread_stack(struct task_struct *tsk)
275 #ifdef CONFIG_VMAP_STACK
276 struct vm_struct *vm = task_stack_vm_area(tsk);
281 for (i = 0; i < THREAD_SIZE / PAGE_SIZE; i++)
282 memcg_kmem_uncharge_page(vm->pages[i], 0);
284 for (i = 0; i < NR_CACHED_STACKS; i++) {
285 if (this_cpu_cmpxchg(cached_stacks[i],
286 NULL, tsk->stack_vm_area) != NULL)
292 if (!IS_ENABLED(CONFIG_PREEMPT_RT))
293 vfree_atomic(tsk->stack);
300 __free_pages(virt_to_page(tsk->stack), THREAD_SIZE_ORDER);
303 static struct kmem_cache *thread_stack_cache;
305 static unsigned long *alloc_thread_stack_node(struct task_struct *tsk,
308 unsigned long *stack;
309 stack = kmem_cache_alloc_node(thread_stack_cache, THREADINFO_GFP, node);
310 stack = kasan_reset_tag(stack);
315 static void free_thread_stack(struct task_struct *tsk)
317 kmem_cache_free(thread_stack_cache, tsk->stack);
320 void thread_stack_cache_init(void)
322 thread_stack_cache = kmem_cache_create_usercopy("thread_stack",
323 THREAD_SIZE, THREAD_SIZE, 0, 0,
325 BUG_ON(thread_stack_cache == NULL);
330 /* SLAB cache for signal_struct structures (tsk->signal) */
331 static struct kmem_cache *signal_cachep;
333 /* SLAB cache for sighand_struct structures (tsk->sighand) */
334 struct kmem_cache *sighand_cachep;
336 /* SLAB cache for files_struct structures (tsk->files) */
337 struct kmem_cache *files_cachep;
339 /* SLAB cache for fs_struct structures (tsk->fs) */
340 struct kmem_cache *fs_cachep;
342 /* SLAB cache for vm_area_struct structures */
343 static struct kmem_cache *vm_area_cachep;
345 /* SLAB cache for mm_struct structures (tsk->mm) */
346 static struct kmem_cache *mm_cachep;
348 struct vm_area_struct *vm_area_alloc(struct mm_struct *mm)
350 struct vm_area_struct *vma;
352 vma = kmem_cache_alloc(vm_area_cachep, GFP_KERNEL);
358 struct vm_area_struct *vm_area_dup(struct vm_area_struct *orig)
360 struct vm_area_struct *new = kmem_cache_alloc(vm_area_cachep, GFP_KERNEL);
363 ASSERT_EXCLUSIVE_WRITER(orig->vm_flags);
364 ASSERT_EXCLUSIVE_WRITER(orig->vm_file);
366 * orig->shared.rb may be modified concurrently, but the clone
367 * will be reinitialized.
369 *new = data_race(*orig);
370 INIT_LIST_HEAD(&new->anon_vma_chain);
371 new->vm_next = new->vm_prev = NULL;
376 void vm_area_free(struct vm_area_struct *vma)
378 kmem_cache_free(vm_area_cachep, vma);
381 static void account_kernel_stack(struct task_struct *tsk, int account)
383 void *stack = task_stack_page(tsk);
384 struct vm_struct *vm = task_stack_vm_area(tsk);
389 for (i = 0; i < THREAD_SIZE / PAGE_SIZE; i++)
390 mod_lruvec_page_state(vm->pages[i], NR_KERNEL_STACK_KB,
391 account * (PAGE_SIZE / 1024));
393 /* All stack pages are in the same node. */
394 mod_lruvec_kmem_state(stack, NR_KERNEL_STACK_KB,
395 account * (THREAD_SIZE / 1024));
399 static int memcg_charge_kernel_stack(struct task_struct *tsk)
401 #ifdef CONFIG_VMAP_STACK
402 struct vm_struct *vm = task_stack_vm_area(tsk);
405 BUILD_BUG_ON(IS_ENABLED(CONFIG_VMAP_STACK) && PAGE_SIZE % 1024 != 0);
410 BUG_ON(vm->nr_pages != THREAD_SIZE / PAGE_SIZE);
412 for (i = 0; i < THREAD_SIZE / PAGE_SIZE; i++) {
414 * If memcg_kmem_charge_page() fails, page's
415 * memory cgroup pointer is NULL, and
416 * memcg_kmem_uncharge_page() in free_thread_stack()
417 * will ignore this page.
419 ret = memcg_kmem_charge_page(vm->pages[i], GFP_KERNEL,
429 static void release_task_stack(struct task_struct *tsk)
431 if (WARN_ON(READ_ONCE(tsk->__state) != TASK_DEAD))
432 return; /* Better to leak the stack than to free prematurely */
434 account_kernel_stack(tsk, -1);
435 free_thread_stack(tsk);
437 #ifdef CONFIG_VMAP_STACK
438 tsk->stack_vm_area = NULL;
442 #ifdef CONFIG_THREAD_INFO_IN_TASK
443 void put_task_stack(struct task_struct *tsk)
445 if (refcount_dec_and_test(&tsk->stack_refcount))
446 release_task_stack(tsk);
450 void free_task(struct task_struct *tsk)
452 #ifdef CONFIG_SECCOMP
453 WARN_ON_ONCE(tsk->seccomp.filter);
455 release_user_cpus_ptr(tsk);
458 #ifndef CONFIG_THREAD_INFO_IN_TASK
460 * The task is finally done with both the stack and thread_info,
463 release_task_stack(tsk);
466 * If the task had a separate stack allocation, it should be gone
469 WARN_ON_ONCE(refcount_read(&tsk->stack_refcount) != 0);
471 rt_mutex_debug_task_free(tsk);
472 ftrace_graph_exit_task(tsk);
473 arch_release_task_struct(tsk);
474 if (tsk->flags & PF_KTHREAD)
475 free_kthread_struct(tsk);
476 free_task_struct(tsk);
478 EXPORT_SYMBOL(free_task);
480 static void dup_mm_exe_file(struct mm_struct *mm, struct mm_struct *oldmm)
482 struct file *exe_file;
484 exe_file = get_mm_exe_file(oldmm);
485 RCU_INIT_POINTER(mm->exe_file, exe_file);
487 * We depend on the oldmm having properly denied write access to the
490 if (exe_file && deny_write_access(exe_file))
491 pr_warn_once("deny_write_access() failed in %s\n", __func__);
495 static __latent_entropy int dup_mmap(struct mm_struct *mm,
496 struct mm_struct *oldmm)
498 struct vm_area_struct *mpnt, *tmp, *prev, **pprev;
499 struct rb_node **rb_link, *rb_parent;
501 unsigned long charge;
504 uprobe_start_dup_mmap();
505 if (mmap_write_lock_killable(oldmm)) {
507 goto fail_uprobe_end;
509 flush_cache_dup_mm(oldmm);
510 uprobe_dup_mmap(oldmm, mm);
512 * Not linked in yet - no deadlock potential:
514 mmap_write_lock_nested(mm, SINGLE_DEPTH_NESTING);
516 /* No ordering required: file already has been exposed. */
517 dup_mm_exe_file(mm, oldmm);
519 mm->total_vm = oldmm->total_vm;
520 mm->data_vm = oldmm->data_vm;
521 mm->exec_vm = oldmm->exec_vm;
522 mm->stack_vm = oldmm->stack_vm;
524 rb_link = &mm->mm_rb.rb_node;
527 retval = ksm_fork(mm, oldmm);
530 retval = khugepaged_fork(mm, oldmm);
535 for (mpnt = oldmm->mmap; mpnt; mpnt = mpnt->vm_next) {
538 if (mpnt->vm_flags & VM_DONTCOPY) {
539 vm_stat_account(mm, mpnt->vm_flags, -vma_pages(mpnt));
544 * Don't duplicate many vmas if we've been oom-killed (for
547 if (fatal_signal_pending(current)) {
551 if (mpnt->vm_flags & VM_ACCOUNT) {
552 unsigned long len = vma_pages(mpnt);
554 if (security_vm_enough_memory_mm(oldmm, len)) /* sic */
558 tmp = vm_area_dup(mpnt);
561 retval = vma_dup_policy(mpnt, tmp);
563 goto fail_nomem_policy;
565 retval = dup_userfaultfd(tmp, &uf);
567 goto fail_nomem_anon_vma_fork;
568 if (tmp->vm_flags & VM_WIPEONFORK) {
570 * VM_WIPEONFORK gets a clean slate in the child.
571 * Don't prepare anon_vma until fault since we don't
572 * copy page for current vma.
574 tmp->anon_vma = NULL;
575 } else if (anon_vma_fork(tmp, mpnt))
576 goto fail_nomem_anon_vma_fork;
577 tmp->vm_flags &= ~(VM_LOCKED | VM_LOCKONFAULT);
580 struct address_space *mapping = file->f_mapping;
583 i_mmap_lock_write(mapping);
584 if (tmp->vm_flags & VM_SHARED)
585 mapping_allow_writable(mapping);
586 flush_dcache_mmap_lock(mapping);
587 /* insert tmp into the share list, just after mpnt */
588 vma_interval_tree_insert_after(tmp, mpnt,
590 flush_dcache_mmap_unlock(mapping);
591 i_mmap_unlock_write(mapping);
595 * Clear hugetlb-related page reserves for children. This only
596 * affects MAP_PRIVATE mappings. Faults generated by the child
597 * are not guaranteed to succeed, even if read-only
599 if (is_vm_hugetlb_page(tmp))
600 reset_vma_resv_huge_pages(tmp);
603 * Link in the new vma and copy the page table entries.
606 pprev = &tmp->vm_next;
610 __vma_link_rb(mm, tmp, rb_link, rb_parent);
611 rb_link = &tmp->vm_rb.rb_right;
612 rb_parent = &tmp->vm_rb;
615 if (!(tmp->vm_flags & VM_WIPEONFORK))
616 retval = copy_page_range(tmp, mpnt);
618 if (tmp->vm_ops && tmp->vm_ops->open)
619 tmp->vm_ops->open(tmp);
624 /* a new mm has just been created */
625 retval = arch_dup_mmap(oldmm, mm);
627 mmap_write_unlock(mm);
629 mmap_write_unlock(oldmm);
630 dup_userfaultfd_complete(&uf);
632 uprobe_end_dup_mmap();
634 fail_nomem_anon_vma_fork:
635 mpol_put(vma_policy(tmp));
640 vm_unacct_memory(charge);
644 static inline int mm_alloc_pgd(struct mm_struct *mm)
646 mm->pgd = pgd_alloc(mm);
647 if (unlikely(!mm->pgd))
652 static inline void mm_free_pgd(struct mm_struct *mm)
654 pgd_free(mm, mm->pgd);
657 static int dup_mmap(struct mm_struct *mm, struct mm_struct *oldmm)
659 mmap_write_lock(oldmm);
660 dup_mm_exe_file(mm, oldmm);
661 mmap_write_unlock(oldmm);
664 #define mm_alloc_pgd(mm) (0)
665 #define mm_free_pgd(mm)
666 #endif /* CONFIG_MMU */
668 static void check_mm(struct mm_struct *mm)
672 BUILD_BUG_ON_MSG(ARRAY_SIZE(resident_page_types) != NR_MM_COUNTERS,
673 "Please make sure 'struct resident_page_types[]' is updated as well");
675 for (i = 0; i < NR_MM_COUNTERS; i++) {
676 long x = atomic_long_read(&mm->rss_stat.count[i]);
679 pr_alert("BUG: Bad rss-counter state mm:%p type:%s val:%ld\n",
680 mm, resident_page_types[i], x);
683 if (mm_pgtables_bytes(mm))
684 pr_alert("BUG: non-zero pgtables_bytes on freeing mm: %ld\n",
685 mm_pgtables_bytes(mm));
687 #if defined(CONFIG_TRANSPARENT_HUGEPAGE) && !USE_SPLIT_PMD_PTLOCKS
688 VM_BUG_ON_MM(mm->pmd_huge_pte, mm);
692 #define allocate_mm() (kmem_cache_alloc(mm_cachep, GFP_KERNEL))
693 #define free_mm(mm) (kmem_cache_free(mm_cachep, (mm)))
696 * Called when the last reference to the mm
697 * is dropped: either by a lazy thread or by
698 * mmput. Free the page directory and the mm.
700 void __mmdrop(struct mm_struct *mm)
702 BUG_ON(mm == &init_mm);
703 WARN_ON_ONCE(mm == current->mm);
704 WARN_ON_ONCE(mm == current->active_mm);
707 mmu_notifier_subscriptions_destroy(mm);
709 put_user_ns(mm->user_ns);
712 EXPORT_SYMBOL_GPL(__mmdrop);
714 #ifdef CONFIG_PREEMPT_RT
716 * RCU callback for delayed mm drop. Not strictly RCU, but call_rcu() is
717 * by far the least expensive way to do that.
719 void __mmdrop_delayed(struct rcu_head *rhp)
721 struct mm_struct *mm = container_of(rhp, struct mm_struct, delayed_drop);
727 static void mmdrop_async_fn(struct work_struct *work)
729 struct mm_struct *mm;
731 mm = container_of(work, struct mm_struct, async_put_work);
735 static void mmdrop_async(struct mm_struct *mm)
737 if (unlikely(atomic_dec_and_test(&mm->mm_count))) {
738 INIT_WORK(&mm->async_put_work, mmdrop_async_fn);
739 schedule_work(&mm->async_put_work);
743 static inline void free_signal_struct(struct signal_struct *sig)
745 taskstats_tgid_free(sig);
746 sched_autogroup_exit(sig);
748 * __mmdrop is not safe to call from softirq context on x86 due to
749 * pgd_dtor so postpone it to the async context
752 mmdrop_async(sig->oom_mm);
753 kmem_cache_free(signal_cachep, sig);
756 static inline void put_signal_struct(struct signal_struct *sig)
758 if (refcount_dec_and_test(&sig->sigcnt))
759 free_signal_struct(sig);
762 void __put_task_struct(struct task_struct *tsk)
764 WARN_ON(!tsk->exit_state);
765 WARN_ON(refcount_read(&tsk->usage));
766 WARN_ON(tsk == current);
770 task_numa_free(tsk, true);
771 security_task_free(tsk);
772 bpf_task_storage_free(tsk);
774 delayacct_tsk_free(tsk);
775 put_signal_struct(tsk->signal);
776 sched_core_free(tsk);
778 if (!profile_handoff_task(tsk))
781 EXPORT_SYMBOL_GPL(__put_task_struct);
783 void __init __weak arch_task_cache_init(void) { }
788 static void set_max_threads(unsigned int max_threads_suggested)
791 unsigned long nr_pages = totalram_pages();
794 * The number of threads shall be limited such that the thread
795 * structures may only consume a small part of the available memory.
797 if (fls64(nr_pages) + fls64(PAGE_SIZE) > 64)
798 threads = MAX_THREADS;
800 threads = div64_u64((u64) nr_pages * (u64) PAGE_SIZE,
801 (u64) THREAD_SIZE * 8UL);
803 if (threads > max_threads_suggested)
804 threads = max_threads_suggested;
806 max_threads = clamp_t(u64, threads, MIN_THREADS, MAX_THREADS);
809 #ifdef CONFIG_ARCH_WANTS_DYNAMIC_TASK_STRUCT
810 /* Initialized by the architecture: */
811 int arch_task_struct_size __read_mostly;
814 #ifndef CONFIG_ARCH_TASK_STRUCT_ALLOCATOR
815 static void task_struct_whitelist(unsigned long *offset, unsigned long *size)
817 /* Fetch thread_struct whitelist for the architecture. */
818 arch_thread_struct_whitelist(offset, size);
821 * Handle zero-sized whitelist or empty thread_struct, otherwise
822 * adjust offset to position of thread_struct in task_struct.
824 if (unlikely(*size == 0))
827 *offset += offsetof(struct task_struct, thread);
829 #endif /* CONFIG_ARCH_TASK_STRUCT_ALLOCATOR */
831 void __init fork_init(void)
834 #ifndef CONFIG_ARCH_TASK_STRUCT_ALLOCATOR
835 #ifndef ARCH_MIN_TASKALIGN
836 #define ARCH_MIN_TASKALIGN 0
838 int align = max_t(int, L1_CACHE_BYTES, ARCH_MIN_TASKALIGN);
839 unsigned long useroffset, usersize;
841 /* create a slab on which task_structs can be allocated */
842 task_struct_whitelist(&useroffset, &usersize);
843 task_struct_cachep = kmem_cache_create_usercopy("task_struct",
844 arch_task_struct_size, align,
845 SLAB_PANIC|SLAB_ACCOUNT,
846 useroffset, usersize, NULL);
849 /* do the arch specific task caches init */
850 arch_task_cache_init();
852 set_max_threads(MAX_THREADS);
854 init_task.signal->rlim[RLIMIT_NPROC].rlim_cur = max_threads/2;
855 init_task.signal->rlim[RLIMIT_NPROC].rlim_max = max_threads/2;
856 init_task.signal->rlim[RLIMIT_SIGPENDING] =
857 init_task.signal->rlim[RLIMIT_NPROC];
859 for (i = 0; i < MAX_PER_NAMESPACE_UCOUNTS; i++)
860 init_user_ns.ucount_max[i] = max_threads/2;
862 set_rlimit_ucount_max(&init_user_ns, UCOUNT_RLIMIT_NPROC, RLIM_INFINITY);
863 set_rlimit_ucount_max(&init_user_ns, UCOUNT_RLIMIT_MSGQUEUE, RLIM_INFINITY);
864 set_rlimit_ucount_max(&init_user_ns, UCOUNT_RLIMIT_SIGPENDING, RLIM_INFINITY);
865 set_rlimit_ucount_max(&init_user_ns, UCOUNT_RLIMIT_MEMLOCK, RLIM_INFINITY);
867 #ifdef CONFIG_VMAP_STACK
868 cpuhp_setup_state(CPUHP_BP_PREPARE_DYN, "fork:vm_stack_cache",
869 NULL, free_vm_stack_cache);
874 lockdep_init_task(&init_task);
878 int __weak arch_dup_task_struct(struct task_struct *dst,
879 struct task_struct *src)
885 void set_task_stack_end_magic(struct task_struct *tsk)
887 unsigned long *stackend;
889 stackend = end_of_stack(tsk);
890 *stackend = STACK_END_MAGIC; /* for overflow detection */
893 static struct task_struct *dup_task_struct(struct task_struct *orig, int node)
895 struct task_struct *tsk;
896 unsigned long *stack;
897 struct vm_struct *stack_vm_area __maybe_unused;
900 if (node == NUMA_NO_NODE)
901 node = tsk_fork_get_node(orig);
902 tsk = alloc_task_struct_node(node);
906 stack = alloc_thread_stack_node(tsk, node);
910 if (memcg_charge_kernel_stack(tsk))
913 stack_vm_area = task_stack_vm_area(tsk);
915 err = arch_dup_task_struct(tsk, orig);
918 * arch_dup_task_struct() clobbers the stack-related fields. Make
919 * sure they're properly initialized before using any stack-related
923 #ifdef CONFIG_VMAP_STACK
924 tsk->stack_vm_area = stack_vm_area;
926 #ifdef CONFIG_THREAD_INFO_IN_TASK
927 refcount_set(&tsk->stack_refcount, 1);
933 err = scs_prepare(tsk, node);
937 #ifdef CONFIG_SECCOMP
939 * We must handle setting up seccomp filters once we're under
940 * the sighand lock in case orig has changed between now and
941 * then. Until then, filter must be NULL to avoid messing up
942 * the usage counts on the error path calling free_task.
944 tsk->seccomp.filter = NULL;
947 setup_thread_stack(tsk, orig);
948 clear_user_return_notifier(tsk);
949 clear_tsk_need_resched(tsk);
950 set_task_stack_end_magic(tsk);
951 clear_syscall_work_syscall_user_dispatch(tsk);
953 #ifdef CONFIG_STACKPROTECTOR
954 tsk->stack_canary = get_random_canary();
956 if (orig->cpus_ptr == &orig->cpus_mask)
957 tsk->cpus_ptr = &tsk->cpus_mask;
958 dup_user_cpus_ptr(tsk, orig, node);
961 * One for the user space visible state that goes away when reaped.
962 * One for the scheduler.
964 refcount_set(&tsk->rcu_users, 2);
965 /* One for the rcu users */
966 refcount_set(&tsk->usage, 1);
967 #ifdef CONFIG_BLK_DEV_IO_TRACE
970 tsk->splice_pipe = NULL;
971 tsk->task_frag.page = NULL;
972 tsk->wake_q.next = NULL;
973 tsk->pf_io_worker = NULL;
975 account_kernel_stack(tsk, 1);
978 kmap_local_fork(tsk);
980 #ifdef CONFIG_FAULT_INJECTION
984 #ifdef CONFIG_BLK_CGROUP
985 tsk->throttle_queue = NULL;
986 tsk->use_memdelay = 0;
990 tsk->active_memcg = NULL;
995 free_thread_stack(tsk);
997 free_task_struct(tsk);
1001 __cacheline_aligned_in_smp DEFINE_SPINLOCK(mmlist_lock);
1003 static unsigned long default_dump_filter = MMF_DUMP_FILTER_DEFAULT;
1005 static int __init coredump_filter_setup(char *s)
1007 default_dump_filter =
1008 (simple_strtoul(s, NULL, 0) << MMF_DUMP_FILTER_SHIFT) &
1009 MMF_DUMP_FILTER_MASK;
1013 __setup("coredump_filter=", coredump_filter_setup);
1015 #include <linux/init_task.h>
1017 static void mm_init_aio(struct mm_struct *mm)
1020 spin_lock_init(&mm->ioctx_lock);
1021 mm->ioctx_table = NULL;
1025 static __always_inline void mm_clear_owner(struct mm_struct *mm,
1026 struct task_struct *p)
1030 WRITE_ONCE(mm->owner, NULL);
1034 static void mm_init_owner(struct mm_struct *mm, struct task_struct *p)
1041 static void mm_init_pasid(struct mm_struct *mm)
1043 #ifdef CONFIG_IOMMU_SUPPORT
1044 mm->pasid = INIT_PASID;
1048 static void mm_init_uprobes_state(struct mm_struct *mm)
1050 #ifdef CONFIG_UPROBES
1051 mm->uprobes_state.xol_area = NULL;
1055 static struct mm_struct *mm_init(struct mm_struct *mm, struct task_struct *p,
1056 struct user_namespace *user_ns)
1059 mm->mm_rb = RB_ROOT;
1060 mm->vmacache_seqnum = 0;
1061 atomic_set(&mm->mm_users, 1);
1062 atomic_set(&mm->mm_count, 1);
1063 seqcount_init(&mm->write_protect_seq);
1065 INIT_LIST_HEAD(&mm->mmlist);
1066 mm->core_state = NULL;
1067 mm_pgtables_bytes_init(mm);
1070 atomic64_set(&mm->pinned_vm, 0);
1071 memset(&mm->rss_stat, 0, sizeof(mm->rss_stat));
1072 spin_lock_init(&mm->page_table_lock);
1073 spin_lock_init(&mm->arg_lock);
1074 mm_init_cpumask(mm);
1076 mm_init_owner(mm, p);
1078 RCU_INIT_POINTER(mm->exe_file, NULL);
1079 mmu_notifier_subscriptions_init(mm);
1080 init_tlb_flush_pending(mm);
1081 #if defined(CONFIG_TRANSPARENT_HUGEPAGE) && !USE_SPLIT_PMD_PTLOCKS
1082 mm->pmd_huge_pte = NULL;
1084 mm_init_uprobes_state(mm);
1085 hugetlb_count_init(mm);
1088 mm->flags = current->mm->flags & MMF_INIT_MASK;
1089 mm->def_flags = current->mm->def_flags & VM_INIT_DEF_MASK;
1091 mm->flags = default_dump_filter;
1095 if (mm_alloc_pgd(mm))
1098 if (init_new_context(p, mm))
1099 goto fail_nocontext;
1101 mm->user_ns = get_user_ns(user_ns);
1112 * Allocate and initialize an mm_struct.
1114 struct mm_struct *mm_alloc(void)
1116 struct mm_struct *mm;
1122 memset(mm, 0, sizeof(*mm));
1123 return mm_init(mm, current, current_user_ns());
1126 static inline void __mmput(struct mm_struct *mm)
1128 VM_BUG_ON(atomic_read(&mm->mm_users));
1130 uprobe_clear_state(mm);
1133 khugepaged_exit(mm); /* must run before exit_mmap */
1135 mm_put_huge_zero_page(mm);
1136 set_mm_exe_file(mm, NULL);
1137 if (!list_empty(&mm->mmlist)) {
1138 spin_lock(&mmlist_lock);
1139 list_del(&mm->mmlist);
1140 spin_unlock(&mmlist_lock);
1143 module_put(mm->binfmt->module);
1148 * Decrement the use count and release all resources for an mm.
1150 void mmput(struct mm_struct *mm)
1154 if (atomic_dec_and_test(&mm->mm_users))
1157 EXPORT_SYMBOL_GPL(mmput);
1160 static void mmput_async_fn(struct work_struct *work)
1162 struct mm_struct *mm = container_of(work, struct mm_struct,
1168 void mmput_async(struct mm_struct *mm)
1170 if (atomic_dec_and_test(&mm->mm_users)) {
1171 INIT_WORK(&mm->async_put_work, mmput_async_fn);
1172 schedule_work(&mm->async_put_work);
1175 EXPORT_SYMBOL_GPL(mmput_async);
1179 * set_mm_exe_file - change a reference to the mm's executable file
1181 * This changes mm's executable file (shown as symlink /proc/[pid]/exe).
1183 * Main users are mmput() and sys_execve(). Callers prevent concurrent
1184 * invocations: in mmput() nobody alive left, in execve task is single
1187 * Can only fail if new_exe_file != NULL.
1189 int set_mm_exe_file(struct mm_struct *mm, struct file *new_exe_file)
1191 struct file *old_exe_file;
1194 * It is safe to dereference the exe_file without RCU as
1195 * this function is only called if nobody else can access
1196 * this mm -- see comment above for justification.
1198 old_exe_file = rcu_dereference_raw(mm->exe_file);
1202 * We expect the caller (i.e., sys_execve) to already denied
1203 * write access, so this is unlikely to fail.
1205 if (unlikely(deny_write_access(new_exe_file)))
1207 get_file(new_exe_file);
1209 rcu_assign_pointer(mm->exe_file, new_exe_file);
1211 allow_write_access(old_exe_file);
1218 * replace_mm_exe_file - replace a reference to the mm's executable file
1220 * This changes mm's executable file (shown as symlink /proc/[pid]/exe),
1221 * dealing with concurrent invocation and without grabbing the mmap lock in
1224 * Main user is sys_prctl(PR_SET_MM_MAP/EXE_FILE).
1226 int replace_mm_exe_file(struct mm_struct *mm, struct file *new_exe_file)
1228 struct vm_area_struct *vma;
1229 struct file *old_exe_file;
1232 /* Forbid mm->exe_file change if old file still mapped. */
1233 old_exe_file = get_mm_exe_file(mm);
1236 for (vma = mm->mmap; vma && !ret; vma = vma->vm_next) {
1239 if (path_equal(&vma->vm_file->f_path,
1240 &old_exe_file->f_path))
1243 mmap_read_unlock(mm);
1249 /* set the new file, lockless */
1250 ret = deny_write_access(new_exe_file);
1253 get_file(new_exe_file);
1255 old_exe_file = xchg(&mm->exe_file, new_exe_file);
1258 * Don't race with dup_mmap() getting the file and disallowing
1259 * write access while someone might open the file writable.
1262 allow_write_access(old_exe_file);
1264 mmap_read_unlock(mm);
1270 * get_mm_exe_file - acquire a reference to the mm's executable file
1272 * Returns %NULL if mm has no associated executable file.
1273 * User must release file via fput().
1275 struct file *get_mm_exe_file(struct mm_struct *mm)
1277 struct file *exe_file;
1280 exe_file = rcu_dereference(mm->exe_file);
1281 if (exe_file && !get_file_rcu(exe_file))
1288 * get_task_exe_file - acquire a reference to the task's executable file
1290 * Returns %NULL if task's mm (if any) has no associated executable file or
1291 * this is a kernel thread with borrowed mm (see the comment above get_task_mm).
1292 * User must release file via fput().
1294 struct file *get_task_exe_file(struct task_struct *task)
1296 struct file *exe_file = NULL;
1297 struct mm_struct *mm;
1302 if (!(task->flags & PF_KTHREAD))
1303 exe_file = get_mm_exe_file(mm);
1310 * get_task_mm - acquire a reference to the task's mm
1312 * Returns %NULL if the task has no mm. Checks PF_KTHREAD (meaning
1313 * this kernel workthread has transiently adopted a user mm with use_mm,
1314 * to do its AIO) is not set and if so returns a reference to it, after
1315 * bumping up the use count. User must release the mm via mmput()
1316 * after use. Typically used by /proc and ptrace.
1318 struct mm_struct *get_task_mm(struct task_struct *task)
1320 struct mm_struct *mm;
1325 if (task->flags & PF_KTHREAD)
1333 EXPORT_SYMBOL_GPL(get_task_mm);
1335 struct mm_struct *mm_access(struct task_struct *task, unsigned int mode)
1337 struct mm_struct *mm;
1340 err = down_read_killable(&task->signal->exec_update_lock);
1342 return ERR_PTR(err);
1344 mm = get_task_mm(task);
1345 if (mm && mm != current->mm &&
1346 !ptrace_may_access(task, mode)) {
1348 mm = ERR_PTR(-EACCES);
1350 up_read(&task->signal->exec_update_lock);
1355 static void complete_vfork_done(struct task_struct *tsk)
1357 struct completion *vfork;
1360 vfork = tsk->vfork_done;
1361 if (likely(vfork)) {
1362 tsk->vfork_done = NULL;
1368 static int wait_for_vfork_done(struct task_struct *child,
1369 struct completion *vfork)
1373 freezer_do_not_count();
1374 cgroup_enter_frozen();
1375 killed = wait_for_completion_killable(vfork);
1376 cgroup_leave_frozen(false);
1381 child->vfork_done = NULL;
1385 put_task_struct(child);
1389 /* Please note the differences between mmput and mm_release.
1390 * mmput is called whenever we stop holding onto a mm_struct,
1391 * error success whatever.
1393 * mm_release is called after a mm_struct has been removed
1394 * from the current process.
1396 * This difference is important for error handling, when we
1397 * only half set up a mm_struct for a new process and need to restore
1398 * the old one. Because we mmput the new mm_struct before
1399 * restoring the old one. . .
1400 * Eric Biederman 10 January 1998
1402 static void mm_release(struct task_struct *tsk, struct mm_struct *mm)
1404 uprobe_free_utask(tsk);
1406 /* Get rid of any cached register state */
1407 deactivate_mm(tsk, mm);
1410 * Signal userspace if we're not exiting with a core dump
1411 * because we want to leave the value intact for debugging
1414 if (tsk->clear_child_tid) {
1415 if (!(tsk->signal->flags & SIGNAL_GROUP_COREDUMP) &&
1416 atomic_read(&mm->mm_users) > 1) {
1418 * We don't check the error code - if userspace has
1419 * not set up a proper pointer then tough luck.
1421 put_user(0, tsk->clear_child_tid);
1422 do_futex(tsk->clear_child_tid, FUTEX_WAKE,
1423 1, NULL, NULL, 0, 0);
1425 tsk->clear_child_tid = NULL;
1429 * All done, finally we can wake up parent and return this mm to him.
1430 * Also kthread_stop() uses this completion for synchronization.
1432 if (tsk->vfork_done)
1433 complete_vfork_done(tsk);
1436 void exit_mm_release(struct task_struct *tsk, struct mm_struct *mm)
1438 futex_exit_release(tsk);
1439 mm_release(tsk, mm);
1442 void exec_mm_release(struct task_struct *tsk, struct mm_struct *mm)
1444 futex_exec_release(tsk);
1445 mm_release(tsk, mm);
1449 * dup_mm() - duplicates an existing mm structure
1450 * @tsk: the task_struct with which the new mm will be associated.
1451 * @oldmm: the mm to duplicate.
1453 * Allocates a new mm structure and duplicates the provided @oldmm structure
1456 * Return: the duplicated mm or NULL on failure.
1458 static struct mm_struct *dup_mm(struct task_struct *tsk,
1459 struct mm_struct *oldmm)
1461 struct mm_struct *mm;
1468 memcpy(mm, oldmm, sizeof(*mm));
1470 if (!mm_init(mm, tsk, mm->user_ns))
1473 err = dup_mmap(mm, oldmm);
1477 mm->hiwater_rss = get_mm_rss(mm);
1478 mm->hiwater_vm = mm->total_vm;
1480 if (mm->binfmt && !try_module_get(mm->binfmt->module))
1486 /* don't put binfmt in mmput, we haven't got module yet */
1488 mm_init_owner(mm, NULL);
1495 static int copy_mm(unsigned long clone_flags, struct task_struct *tsk)
1497 struct mm_struct *mm, *oldmm;
1499 tsk->min_flt = tsk->maj_flt = 0;
1500 tsk->nvcsw = tsk->nivcsw = 0;
1501 #ifdef CONFIG_DETECT_HUNG_TASK
1502 tsk->last_switch_count = tsk->nvcsw + tsk->nivcsw;
1503 tsk->last_switch_time = 0;
1507 tsk->active_mm = NULL;
1510 * Are we cloning a kernel thread?
1512 * We need to steal a active VM for that..
1514 oldmm = current->mm;
1518 /* initialize the new vmacache entries */
1519 vmacache_flush(tsk);
1521 if (clone_flags & CLONE_VM) {
1525 mm = dup_mm(tsk, current->mm);
1531 tsk->active_mm = mm;
1535 static int copy_fs(unsigned long clone_flags, struct task_struct *tsk)
1537 struct fs_struct *fs = current->fs;
1538 if (clone_flags & CLONE_FS) {
1539 /* tsk->fs is already what we want */
1540 spin_lock(&fs->lock);
1542 spin_unlock(&fs->lock);
1546 spin_unlock(&fs->lock);
1549 tsk->fs = copy_fs_struct(fs);
1555 static int copy_files(unsigned long clone_flags, struct task_struct *tsk)
1557 struct files_struct *oldf, *newf;
1561 * A background process may not have any files ...
1563 oldf = current->files;
1567 if (clone_flags & CLONE_FILES) {
1568 atomic_inc(&oldf->count);
1572 newf = dup_fd(oldf, NR_OPEN_MAX, &error);
1582 static int copy_io(unsigned long clone_flags, struct task_struct *tsk)
1585 struct io_context *ioc = current->io_context;
1586 struct io_context *new_ioc;
1591 * Share io context with parent, if CLONE_IO is set
1593 if (clone_flags & CLONE_IO) {
1595 tsk->io_context = ioc;
1596 } else if (ioprio_valid(ioc->ioprio)) {
1597 new_ioc = get_task_io_context(tsk, GFP_KERNEL, NUMA_NO_NODE);
1598 if (unlikely(!new_ioc))
1601 new_ioc->ioprio = ioc->ioprio;
1602 put_io_context(new_ioc);
1608 static int copy_sighand(unsigned long clone_flags, struct task_struct *tsk)
1610 struct sighand_struct *sig;
1612 if (clone_flags & CLONE_SIGHAND) {
1613 refcount_inc(¤t->sighand->count);
1616 sig = kmem_cache_alloc(sighand_cachep, GFP_KERNEL);
1617 RCU_INIT_POINTER(tsk->sighand, sig);
1621 refcount_set(&sig->count, 1);
1622 spin_lock_irq(¤t->sighand->siglock);
1623 memcpy(sig->action, current->sighand->action, sizeof(sig->action));
1624 spin_unlock_irq(¤t->sighand->siglock);
1626 /* Reset all signal handler not set to SIG_IGN to SIG_DFL. */
1627 if (clone_flags & CLONE_CLEAR_SIGHAND)
1628 flush_signal_handlers(tsk, 0);
1633 void __cleanup_sighand(struct sighand_struct *sighand)
1635 if (refcount_dec_and_test(&sighand->count)) {
1636 signalfd_cleanup(sighand);
1638 * sighand_cachep is SLAB_TYPESAFE_BY_RCU so we can free it
1639 * without an RCU grace period, see __lock_task_sighand().
1641 kmem_cache_free(sighand_cachep, sighand);
1646 * Initialize POSIX timer handling for a thread group.
1648 static void posix_cpu_timers_init_group(struct signal_struct *sig)
1650 struct posix_cputimers *pct = &sig->posix_cputimers;
1651 unsigned long cpu_limit;
1653 cpu_limit = READ_ONCE(sig->rlim[RLIMIT_CPU].rlim_cur);
1654 posix_cputimers_group_init(pct, cpu_limit);
1657 static int copy_signal(unsigned long clone_flags, struct task_struct *tsk)
1659 struct signal_struct *sig;
1661 if (clone_flags & CLONE_THREAD)
1664 sig = kmem_cache_zalloc(signal_cachep, GFP_KERNEL);
1669 sig->nr_threads = 1;
1670 atomic_set(&sig->live, 1);
1671 refcount_set(&sig->sigcnt, 1);
1673 /* list_add(thread_node, thread_head) without INIT_LIST_HEAD() */
1674 sig->thread_head = (struct list_head)LIST_HEAD_INIT(tsk->thread_node);
1675 tsk->thread_node = (struct list_head)LIST_HEAD_INIT(sig->thread_head);
1677 init_waitqueue_head(&sig->wait_chldexit);
1678 sig->curr_target = tsk;
1679 init_sigpending(&sig->shared_pending);
1680 INIT_HLIST_HEAD(&sig->multiprocess);
1681 seqlock_init(&sig->stats_lock);
1682 prev_cputime_init(&sig->prev_cputime);
1684 #ifdef CONFIG_POSIX_TIMERS
1685 INIT_LIST_HEAD(&sig->posix_timers);
1686 hrtimer_init(&sig->real_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
1687 sig->real_timer.function = it_real_fn;
1690 task_lock(current->group_leader);
1691 memcpy(sig->rlim, current->signal->rlim, sizeof sig->rlim);
1692 task_unlock(current->group_leader);
1694 posix_cpu_timers_init_group(sig);
1696 tty_audit_fork(sig);
1697 sched_autogroup_fork(sig);
1699 sig->oom_score_adj = current->signal->oom_score_adj;
1700 sig->oom_score_adj_min = current->signal->oom_score_adj_min;
1702 mutex_init(&sig->cred_guard_mutex);
1703 init_rwsem(&sig->exec_update_lock);
1708 static void copy_seccomp(struct task_struct *p)
1710 #ifdef CONFIG_SECCOMP
1712 * Must be called with sighand->lock held, which is common to
1713 * all threads in the group. Holding cred_guard_mutex is not
1714 * needed because this new task is not yet running and cannot
1717 assert_spin_locked(¤t->sighand->siglock);
1719 /* Ref-count the new filter user, and assign it. */
1720 get_seccomp_filter(current);
1721 p->seccomp = current->seccomp;
1724 * Explicitly enable no_new_privs here in case it got set
1725 * between the task_struct being duplicated and holding the
1726 * sighand lock. The seccomp state and nnp must be in sync.
1728 if (task_no_new_privs(current))
1729 task_set_no_new_privs(p);
1732 * If the parent gained a seccomp mode after copying thread
1733 * flags and between before we held the sighand lock, we have
1734 * to manually enable the seccomp thread flag here.
1736 if (p->seccomp.mode != SECCOMP_MODE_DISABLED)
1737 set_task_syscall_work(p, SECCOMP);
1741 SYSCALL_DEFINE1(set_tid_address, int __user *, tidptr)
1743 current->clear_child_tid = tidptr;
1745 return task_pid_vnr(current);
1748 static void rt_mutex_init_task(struct task_struct *p)
1750 raw_spin_lock_init(&p->pi_lock);
1751 #ifdef CONFIG_RT_MUTEXES
1752 p->pi_waiters = RB_ROOT_CACHED;
1753 p->pi_top_task = NULL;
1754 p->pi_blocked_on = NULL;
1758 static inline void init_task_pid_links(struct task_struct *task)
1762 for (type = PIDTYPE_PID; type < PIDTYPE_MAX; ++type)
1763 INIT_HLIST_NODE(&task->pid_links[type]);
1767 init_task_pid(struct task_struct *task, enum pid_type type, struct pid *pid)
1769 if (type == PIDTYPE_PID)
1770 task->thread_pid = pid;
1772 task->signal->pids[type] = pid;
1775 static inline void rcu_copy_process(struct task_struct *p)
1777 #ifdef CONFIG_PREEMPT_RCU
1778 p->rcu_read_lock_nesting = 0;
1779 p->rcu_read_unlock_special.s = 0;
1780 p->rcu_blocked_node = NULL;
1781 INIT_LIST_HEAD(&p->rcu_node_entry);
1782 #endif /* #ifdef CONFIG_PREEMPT_RCU */
1783 #ifdef CONFIG_TASKS_RCU
1784 p->rcu_tasks_holdout = false;
1785 INIT_LIST_HEAD(&p->rcu_tasks_holdout_list);
1786 p->rcu_tasks_idle_cpu = -1;
1787 #endif /* #ifdef CONFIG_TASKS_RCU */
1788 #ifdef CONFIG_TASKS_TRACE_RCU
1789 p->trc_reader_nesting = 0;
1790 p->trc_reader_special.s = 0;
1791 INIT_LIST_HEAD(&p->trc_holdout_list);
1792 #endif /* #ifdef CONFIG_TASKS_TRACE_RCU */
1795 struct pid *pidfd_pid(const struct file *file)
1797 if (file->f_op == &pidfd_fops)
1798 return file->private_data;
1800 return ERR_PTR(-EBADF);
1803 static int pidfd_release(struct inode *inode, struct file *file)
1805 struct pid *pid = file->private_data;
1807 file->private_data = NULL;
1812 #ifdef CONFIG_PROC_FS
1814 * pidfd_show_fdinfo - print information about a pidfd
1815 * @m: proc fdinfo file
1816 * @f: file referencing a pidfd
1819 * This function will print the pid that a given pidfd refers to in the
1820 * pid namespace of the procfs instance.
1821 * If the pid namespace of the process is not a descendant of the pid
1822 * namespace of the procfs instance 0 will be shown as its pid. This is
1823 * similar to calling getppid() on a process whose parent is outside of
1824 * its pid namespace.
1827 * If pid namespaces are supported then this function will also print
1828 * the pid of a given pidfd refers to for all descendant pid namespaces
1829 * starting from the current pid namespace of the instance, i.e. the
1830 * Pid field and the first entry in the NSpid field will be identical.
1831 * If the pid namespace of the process is not a descendant of the pid
1832 * namespace of the procfs instance 0 will be shown as its first NSpid
1833 * entry and no others will be shown.
1834 * Note that this differs from the Pid and NSpid fields in
1835 * /proc/<pid>/status where Pid and NSpid are always shown relative to
1836 * the pid namespace of the procfs instance. The difference becomes
1837 * obvious when sending around a pidfd between pid namespaces from a
1838 * different branch of the tree, i.e. where no ancestral relation is
1839 * present between the pid namespaces:
1840 * - create two new pid namespaces ns1 and ns2 in the initial pid
1841 * namespace (also take care to create new mount namespaces in the
1842 * new pid namespace and mount procfs)
1843 * - create a process with a pidfd in ns1
1844 * - send pidfd from ns1 to ns2
1845 * - read /proc/self/fdinfo/<pidfd> and observe that both Pid and NSpid
1846 * have exactly one entry, which is 0
1848 static void pidfd_show_fdinfo(struct seq_file *m, struct file *f)
1850 struct pid *pid = f->private_data;
1851 struct pid_namespace *ns;
1854 if (likely(pid_has_task(pid, PIDTYPE_PID))) {
1855 ns = proc_pid_ns(file_inode(m->file)->i_sb);
1856 nr = pid_nr_ns(pid, ns);
1859 seq_put_decimal_ll(m, "Pid:\t", nr);
1861 #ifdef CONFIG_PID_NS
1862 seq_put_decimal_ll(m, "\nNSpid:\t", nr);
1866 /* If nr is non-zero it means that 'pid' is valid and that
1867 * ns, i.e. the pid namespace associated with the procfs
1868 * instance, is in the pid namespace hierarchy of pid.
1869 * Start at one below the already printed level.
1871 for (i = ns->level + 1; i <= pid->level; i++)
1872 seq_put_decimal_ll(m, "\t", pid->numbers[i].nr);
1880 * Poll support for process exit notification.
1882 static __poll_t pidfd_poll(struct file *file, struct poll_table_struct *pts)
1884 struct pid *pid = file->private_data;
1885 __poll_t poll_flags = 0;
1887 poll_wait(file, &pid->wait_pidfd, pts);
1890 * Inform pollers only when the whole thread group exits.
1891 * If the thread group leader exits before all other threads in the
1892 * group, then poll(2) should block, similar to the wait(2) family.
1894 if (thread_group_exited(pid))
1895 poll_flags = EPOLLIN | EPOLLRDNORM;
1900 const struct file_operations pidfd_fops = {
1901 .release = pidfd_release,
1903 #ifdef CONFIG_PROC_FS
1904 .show_fdinfo = pidfd_show_fdinfo,
1908 static void __delayed_free_task(struct rcu_head *rhp)
1910 struct task_struct *tsk = container_of(rhp, struct task_struct, rcu);
1915 static __always_inline void delayed_free_task(struct task_struct *tsk)
1917 if (IS_ENABLED(CONFIG_MEMCG))
1918 call_rcu(&tsk->rcu, __delayed_free_task);
1923 static void copy_oom_score_adj(u64 clone_flags, struct task_struct *tsk)
1925 /* Skip if kernel thread */
1929 /* Skip if spawning a thread or using vfork */
1930 if ((clone_flags & (CLONE_VM | CLONE_THREAD | CLONE_VFORK)) != CLONE_VM)
1933 /* We need to synchronize with __set_oom_adj */
1934 mutex_lock(&oom_adj_mutex);
1935 set_bit(MMF_MULTIPROCESS, &tsk->mm->flags);
1936 /* Update the values in case they were changed after copy_signal */
1937 tsk->signal->oom_score_adj = current->signal->oom_score_adj;
1938 tsk->signal->oom_score_adj_min = current->signal->oom_score_adj_min;
1939 mutex_unlock(&oom_adj_mutex);
1943 * This creates a new process as a copy of the old one,
1944 * but does not actually start it yet.
1946 * It copies the registers, and all the appropriate
1947 * parts of the process environment (as per the clone
1948 * flags). The actual kick-off is left to the caller.
1950 static __latent_entropy struct task_struct *copy_process(
1954 struct kernel_clone_args *args)
1956 int pidfd = -1, retval;
1957 struct task_struct *p;
1958 struct multiprocess_signals delayed;
1959 struct file *pidfile = NULL;
1960 u64 clone_flags = args->flags;
1961 struct nsproxy *nsp = current->nsproxy;
1964 * Don't allow sharing the root directory with processes in a different
1967 if ((clone_flags & (CLONE_NEWNS|CLONE_FS)) == (CLONE_NEWNS|CLONE_FS))
1968 return ERR_PTR(-EINVAL);
1970 if ((clone_flags & (CLONE_NEWUSER|CLONE_FS)) == (CLONE_NEWUSER|CLONE_FS))
1971 return ERR_PTR(-EINVAL);
1974 * Thread groups must share signals as well, and detached threads
1975 * can only be started up within the thread group.
1977 if ((clone_flags & CLONE_THREAD) && !(clone_flags & CLONE_SIGHAND))
1978 return ERR_PTR(-EINVAL);
1981 * Shared signal handlers imply shared VM. By way of the above,
1982 * thread groups also imply shared VM. Blocking this case allows
1983 * for various simplifications in other code.
1985 if ((clone_flags & CLONE_SIGHAND) && !(clone_flags & CLONE_VM))
1986 return ERR_PTR(-EINVAL);
1989 * Siblings of global init remain as zombies on exit since they are
1990 * not reaped by their parent (swapper). To solve this and to avoid
1991 * multi-rooted process trees, prevent global and container-inits
1992 * from creating siblings.
1994 if ((clone_flags & CLONE_PARENT) &&
1995 current->signal->flags & SIGNAL_UNKILLABLE)
1996 return ERR_PTR(-EINVAL);
1999 * If the new process will be in a different pid or user namespace
2000 * do not allow it to share a thread group with the forking task.
2002 if (clone_flags & CLONE_THREAD) {
2003 if ((clone_flags & (CLONE_NEWUSER | CLONE_NEWPID)) ||
2004 (task_active_pid_ns(current) != nsp->pid_ns_for_children))
2005 return ERR_PTR(-EINVAL);
2009 * If the new process will be in a different time namespace
2010 * do not allow it to share VM or a thread group with the forking task.
2012 if (clone_flags & (CLONE_THREAD | CLONE_VM)) {
2013 if (nsp->time_ns != nsp->time_ns_for_children)
2014 return ERR_PTR(-EINVAL);
2017 if (clone_flags & CLONE_PIDFD) {
2019 * - CLONE_DETACHED is blocked so that we can potentially
2020 * reuse it later for CLONE_PIDFD.
2021 * - CLONE_THREAD is blocked until someone really needs it.
2023 if (clone_flags & (CLONE_DETACHED | CLONE_THREAD))
2024 return ERR_PTR(-EINVAL);
2028 * Force any signals received before this point to be delivered
2029 * before the fork happens. Collect up signals sent to multiple
2030 * processes that happen during the fork and delay them so that
2031 * they appear to happen after the fork.
2033 sigemptyset(&delayed.signal);
2034 INIT_HLIST_NODE(&delayed.node);
2036 spin_lock_irq(¤t->sighand->siglock);
2037 if (!(clone_flags & CLONE_THREAD))
2038 hlist_add_head(&delayed.node, ¤t->signal->multiprocess);
2039 recalc_sigpending();
2040 spin_unlock_irq(¤t->sighand->siglock);
2041 retval = -ERESTARTNOINTR;
2042 if (task_sigpending(current))
2046 p = dup_task_struct(current, node);
2049 if (args->io_thread) {
2051 * Mark us an IO worker, and block any signal that isn't
2054 p->flags |= PF_IO_WORKER;
2055 siginitsetinv(&p->blocked, sigmask(SIGKILL)|sigmask(SIGSTOP));
2059 * This _must_ happen before we call free_task(), i.e. before we jump
2060 * to any of the bad_fork_* labels. This is to avoid freeing
2061 * p->set_child_tid which is (ab)used as a kthread's data pointer for
2062 * kernel threads (PF_KTHREAD).
2064 p->set_child_tid = (clone_flags & CLONE_CHILD_SETTID) ? args->child_tid : NULL;
2066 * Clear TID on mm_release()?
2068 p->clear_child_tid = (clone_flags & CLONE_CHILD_CLEARTID) ? args->child_tid : NULL;
2070 ftrace_graph_init_task(p);
2072 rt_mutex_init_task(p);
2074 lockdep_assert_irqs_enabled();
2075 #ifdef CONFIG_PROVE_LOCKING
2076 DEBUG_LOCKS_WARN_ON(!p->softirqs_enabled);
2078 retval = copy_creds(p, clone_flags);
2083 if (is_ucounts_overlimit(task_ucounts(p), UCOUNT_RLIMIT_NPROC, rlimit(RLIMIT_NPROC))) {
2084 if (p->real_cred->user != INIT_USER &&
2085 !capable(CAP_SYS_RESOURCE) && !capable(CAP_SYS_ADMIN))
2086 goto bad_fork_cleanup_count;
2088 current->flags &= ~PF_NPROC_EXCEEDED;
2091 * If multiple threads are within copy_process(), then this check
2092 * triggers too late. This doesn't hurt, the check is only there
2093 * to stop root fork bombs.
2096 if (data_race(nr_threads >= max_threads))
2097 goto bad_fork_cleanup_count;
2099 delayacct_tsk_init(p); /* Must remain after dup_task_struct() */
2100 p->flags &= ~(PF_SUPERPRIV | PF_WQ_WORKER | PF_IDLE | PF_NO_SETAFFINITY);
2101 p->flags |= PF_FORKNOEXEC;
2102 INIT_LIST_HEAD(&p->children);
2103 INIT_LIST_HEAD(&p->sibling);
2104 rcu_copy_process(p);
2105 p->vfork_done = NULL;
2106 spin_lock_init(&p->alloc_lock);
2108 init_sigpending(&p->pending);
2110 p->utime = p->stime = p->gtime = 0;
2111 #ifdef CONFIG_ARCH_HAS_SCALED_CPUTIME
2112 p->utimescaled = p->stimescaled = 0;
2114 prev_cputime_init(&p->prev_cputime);
2116 #ifdef CONFIG_VIRT_CPU_ACCOUNTING_GEN
2117 seqcount_init(&p->vtime.seqcount);
2118 p->vtime.starttime = 0;
2119 p->vtime.state = VTIME_INACTIVE;
2122 #ifdef CONFIG_IO_URING
2126 #if defined(SPLIT_RSS_COUNTING)
2127 memset(&p->rss_stat, 0, sizeof(p->rss_stat));
2130 p->default_timer_slack_ns = current->timer_slack_ns;
2136 task_io_accounting_init(&p->ioac);
2137 acct_clear_integrals(p);
2139 posix_cputimers_init(&p->posix_cputimers);
2141 p->io_context = NULL;
2142 audit_set_context(p, NULL);
2145 p->mempolicy = mpol_dup(p->mempolicy);
2146 if (IS_ERR(p->mempolicy)) {
2147 retval = PTR_ERR(p->mempolicy);
2148 p->mempolicy = NULL;
2149 goto bad_fork_cleanup_threadgroup_lock;
2152 #ifdef CONFIG_CPUSETS
2153 p->cpuset_mem_spread_rotor = NUMA_NO_NODE;
2154 p->cpuset_slab_spread_rotor = NUMA_NO_NODE;
2155 seqcount_spinlock_init(&p->mems_allowed_seq, &p->alloc_lock);
2157 #ifdef CONFIG_TRACE_IRQFLAGS
2158 memset(&p->irqtrace, 0, sizeof(p->irqtrace));
2159 p->irqtrace.hardirq_disable_ip = _THIS_IP_;
2160 p->irqtrace.softirq_enable_ip = _THIS_IP_;
2161 p->softirqs_enabled = 1;
2162 p->softirq_context = 0;
2165 p->pagefault_disabled = 0;
2167 #ifdef CONFIG_LOCKDEP
2168 lockdep_init_task(p);
2171 #ifdef CONFIG_DEBUG_MUTEXES
2172 p->blocked_on = NULL; /* not blocked yet */
2174 #ifdef CONFIG_BCACHE
2175 p->sequential_io = 0;
2176 p->sequential_io_avg = 0;
2178 #ifdef CONFIG_BPF_SYSCALL
2179 RCU_INIT_POINTER(p->bpf_storage, NULL);
2183 /* Perform scheduler related setup. Assign this task to a CPU. */
2184 retval = sched_fork(clone_flags, p);
2186 goto bad_fork_cleanup_policy;
2188 retval = perf_event_init_task(p, clone_flags);
2190 goto bad_fork_cleanup_policy;
2191 retval = audit_alloc(p);
2193 goto bad_fork_cleanup_perf;
2194 /* copy all the process information */
2196 retval = security_task_alloc(p, clone_flags);
2198 goto bad_fork_cleanup_audit;
2199 retval = copy_semundo(clone_flags, p);
2201 goto bad_fork_cleanup_security;
2202 retval = copy_files(clone_flags, p);
2204 goto bad_fork_cleanup_semundo;
2205 retval = copy_fs(clone_flags, p);
2207 goto bad_fork_cleanup_files;
2208 retval = copy_sighand(clone_flags, p);
2210 goto bad_fork_cleanup_fs;
2211 retval = copy_signal(clone_flags, p);
2213 goto bad_fork_cleanup_sighand;
2214 retval = copy_mm(clone_flags, p);
2216 goto bad_fork_cleanup_signal;
2217 retval = copy_namespaces(clone_flags, p);
2219 goto bad_fork_cleanup_mm;
2220 retval = copy_io(clone_flags, p);
2222 goto bad_fork_cleanup_namespaces;
2223 retval = copy_thread(clone_flags, args->stack, args->stack_size, p, args->tls);
2225 goto bad_fork_cleanup_io;
2227 stackleak_task_init(p);
2229 if (pid != &init_struct_pid) {
2230 pid = alloc_pid(p->nsproxy->pid_ns_for_children, args->set_tid,
2231 args->set_tid_size);
2233 retval = PTR_ERR(pid);
2234 goto bad_fork_cleanup_thread;
2239 * This has to happen after we've potentially unshared the file
2240 * descriptor table (so that the pidfd doesn't leak into the child
2241 * if the fd table isn't shared).
2243 if (clone_flags & CLONE_PIDFD) {
2244 retval = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
2246 goto bad_fork_free_pid;
2250 pidfile = anon_inode_getfile("[pidfd]", &pidfd_fops, pid,
2251 O_RDWR | O_CLOEXEC);
2252 if (IS_ERR(pidfile)) {
2253 put_unused_fd(pidfd);
2254 retval = PTR_ERR(pidfile);
2255 goto bad_fork_free_pid;
2257 get_pid(pid); /* held by pidfile now */
2259 retval = put_user(pidfd, args->pidfd);
2261 goto bad_fork_put_pidfd;
2270 * sigaltstack should be cleared when sharing the same VM
2272 if ((clone_flags & (CLONE_VM|CLONE_VFORK)) == CLONE_VM)
2276 * Syscall tracing and stepping should be turned off in the
2277 * child regardless of CLONE_PTRACE.
2279 user_disable_single_step(p);
2280 clear_task_syscall_work(p, SYSCALL_TRACE);
2281 #if defined(CONFIG_GENERIC_ENTRY) || defined(TIF_SYSCALL_EMU)
2282 clear_task_syscall_work(p, SYSCALL_EMU);
2284 clear_tsk_latency_tracing(p);
2286 /* ok, now we should be set up.. */
2287 p->pid = pid_nr(pid);
2288 if (clone_flags & CLONE_THREAD) {
2289 p->group_leader = current->group_leader;
2290 p->tgid = current->tgid;
2292 p->group_leader = p;
2297 p->nr_dirtied_pause = 128 >> (PAGE_SHIFT - 10);
2298 p->dirty_paused_when = 0;
2300 p->pdeath_signal = 0;
2301 INIT_LIST_HEAD(&p->thread_group);
2302 p->task_works = NULL;
2303 clear_posix_cputimers_work(p);
2305 #ifdef CONFIG_KRETPROBES
2306 p->kretprobe_instances.first = NULL;
2310 * Ensure that the cgroup subsystem policies allow the new process to be
2311 * forked. It should be noted that the new process's css_set can be changed
2312 * between here and cgroup_post_fork() if an organisation operation is in
2315 retval = cgroup_can_fork(p, args);
2317 goto bad_fork_put_pidfd;
2320 * Now that the cgroups are pinned, re-clone the parent cgroup and put
2321 * the new task on the correct runqueue. All this *before* the task
2324 * This isn't part of ->can_fork() because while the re-cloning is
2325 * cgroup specific, it unconditionally needs to place the task on a
2328 sched_cgroup_fork(p, args);
2331 * From this point on we must avoid any synchronous user-space
2332 * communication until we take the tasklist-lock. In particular, we do
2333 * not want user-space to be able to predict the process start-time by
2334 * stalling fork(2) after we recorded the start_time but before it is
2335 * visible to the system.
2338 p->start_time = ktime_get_ns();
2339 p->start_boottime = ktime_get_boottime_ns();
2342 * Make it visible to the rest of the system, but dont wake it up yet.
2343 * Need tasklist lock for parent etc handling!
2345 write_lock_irq(&tasklist_lock);
2347 /* CLONE_PARENT re-uses the old parent */
2348 if (clone_flags & (CLONE_PARENT|CLONE_THREAD)) {
2349 p->real_parent = current->real_parent;
2350 p->parent_exec_id = current->parent_exec_id;
2351 if (clone_flags & CLONE_THREAD)
2352 p->exit_signal = -1;
2354 p->exit_signal = current->group_leader->exit_signal;
2356 p->real_parent = current;
2357 p->parent_exec_id = current->self_exec_id;
2358 p->exit_signal = args->exit_signal;
2361 klp_copy_process(p);
2365 spin_lock(¤t->sighand->siglock);
2367 rseq_fork(p, clone_flags);
2369 /* Don't start children in a dying pid namespace */
2370 if (unlikely(!(ns_of_pid(pid)->pid_allocated & PIDNS_ADDING))) {
2372 goto bad_fork_cancel_cgroup;
2375 /* Let kill terminate clone/fork in the middle */
2376 if (fatal_signal_pending(current)) {
2378 goto bad_fork_cancel_cgroup;
2381 /* No more failure paths after this point. */
2384 * Copy seccomp details explicitly here, in case they were changed
2385 * before holding sighand lock.
2389 init_task_pid_links(p);
2390 if (likely(p->pid)) {
2391 ptrace_init_task(p, (clone_flags & CLONE_PTRACE) || trace);
2393 init_task_pid(p, PIDTYPE_PID, pid);
2394 if (thread_group_leader(p)) {
2395 init_task_pid(p, PIDTYPE_TGID, pid);
2396 init_task_pid(p, PIDTYPE_PGID, task_pgrp(current));
2397 init_task_pid(p, PIDTYPE_SID, task_session(current));
2399 if (is_child_reaper(pid)) {
2400 ns_of_pid(pid)->child_reaper = p;
2401 p->signal->flags |= SIGNAL_UNKILLABLE;
2403 p->signal->shared_pending.signal = delayed.signal;
2404 p->signal->tty = tty_kref_get(current->signal->tty);
2406 * Inherit has_child_subreaper flag under the same
2407 * tasklist_lock with adding child to the process tree
2408 * for propagate_has_child_subreaper optimization.
2410 p->signal->has_child_subreaper = p->real_parent->signal->has_child_subreaper ||
2411 p->real_parent->signal->is_child_subreaper;
2412 list_add_tail(&p->sibling, &p->real_parent->children);
2413 list_add_tail_rcu(&p->tasks, &init_task.tasks);
2414 attach_pid(p, PIDTYPE_TGID);
2415 attach_pid(p, PIDTYPE_PGID);
2416 attach_pid(p, PIDTYPE_SID);
2417 __this_cpu_inc(process_counts);
2419 current->signal->nr_threads++;
2420 atomic_inc(¤t->signal->live);
2421 refcount_inc(¤t->signal->sigcnt);
2422 task_join_group_stop(p);
2423 list_add_tail_rcu(&p->thread_group,
2424 &p->group_leader->thread_group);
2425 list_add_tail_rcu(&p->thread_node,
2426 &p->signal->thread_head);
2428 attach_pid(p, PIDTYPE_PID);
2432 hlist_del_init(&delayed.node);
2433 spin_unlock(¤t->sighand->siglock);
2434 syscall_tracepoint_update(p);
2435 write_unlock_irq(&tasklist_lock);
2438 fd_install(pidfd, pidfile);
2440 proc_fork_connector(p);
2442 cgroup_post_fork(p, args);
2445 trace_task_newtask(p, clone_flags);
2446 uprobe_copy_process(p, clone_flags);
2448 copy_oom_score_adj(clone_flags, p);
2452 bad_fork_cancel_cgroup:
2454 spin_unlock(¤t->sighand->siglock);
2455 write_unlock_irq(&tasklist_lock);
2456 cgroup_cancel_fork(p, args);
2458 if (clone_flags & CLONE_PIDFD) {
2460 put_unused_fd(pidfd);
2463 if (pid != &init_struct_pid)
2465 bad_fork_cleanup_thread:
2467 bad_fork_cleanup_io:
2470 bad_fork_cleanup_namespaces:
2471 exit_task_namespaces(p);
2472 bad_fork_cleanup_mm:
2474 mm_clear_owner(p->mm, p);
2477 bad_fork_cleanup_signal:
2478 if (!(clone_flags & CLONE_THREAD))
2479 free_signal_struct(p->signal);
2480 bad_fork_cleanup_sighand:
2481 __cleanup_sighand(p->sighand);
2482 bad_fork_cleanup_fs:
2483 exit_fs(p); /* blocking */
2484 bad_fork_cleanup_files:
2485 exit_files(p); /* blocking */
2486 bad_fork_cleanup_semundo:
2488 bad_fork_cleanup_security:
2489 security_task_free(p);
2490 bad_fork_cleanup_audit:
2492 bad_fork_cleanup_perf:
2493 perf_event_free_task(p);
2494 bad_fork_cleanup_policy:
2495 lockdep_free_task(p);
2497 mpol_put(p->mempolicy);
2498 bad_fork_cleanup_threadgroup_lock:
2500 delayacct_tsk_free(p);
2501 bad_fork_cleanup_count:
2502 dec_rlimit_ucounts(task_ucounts(p), UCOUNT_RLIMIT_NPROC, 1);
2505 WRITE_ONCE(p->__state, TASK_DEAD);
2507 delayed_free_task(p);
2509 spin_lock_irq(¤t->sighand->siglock);
2510 hlist_del_init(&delayed.node);
2511 spin_unlock_irq(¤t->sighand->siglock);
2512 return ERR_PTR(retval);
2515 static inline void init_idle_pids(struct task_struct *idle)
2519 for (type = PIDTYPE_PID; type < PIDTYPE_MAX; ++type) {
2520 INIT_HLIST_NODE(&idle->pid_links[type]); /* not really needed */
2521 init_task_pid(idle, type, &init_struct_pid);
2525 struct task_struct * __init fork_idle(int cpu)
2527 struct task_struct *task;
2528 struct kernel_clone_args args = {
2532 task = copy_process(&init_struct_pid, 0, cpu_to_node(cpu), &args);
2533 if (!IS_ERR(task)) {
2534 init_idle_pids(task);
2535 init_idle(task, cpu);
2541 struct mm_struct *copy_init_mm(void)
2543 return dup_mm(NULL, &init_mm);
2547 * This is like kernel_clone(), but shaved down and tailored to just
2548 * creating io_uring workers. It returns a created task, or an error pointer.
2549 * The returned task is inactive, and the caller must fire it up through
2550 * wake_up_new_task(p). All signals are blocked in the created task.
2552 struct task_struct *create_io_thread(int (*fn)(void *), void *arg, int node)
2554 unsigned long flags = CLONE_FS|CLONE_FILES|CLONE_SIGHAND|CLONE_THREAD|
2556 struct kernel_clone_args args = {
2557 .flags = ((lower_32_bits(flags) | CLONE_VM |
2558 CLONE_UNTRACED) & ~CSIGNAL),
2559 .exit_signal = (lower_32_bits(flags) & CSIGNAL),
2560 .stack = (unsigned long)fn,
2561 .stack_size = (unsigned long)arg,
2565 return copy_process(NULL, 0, node, &args);
2569 * Ok, this is the main fork-routine.
2571 * It copies the process, and if successful kick-starts
2572 * it and waits for it to finish using the VM if required.
2574 * args->exit_signal is expected to be checked for sanity by the caller.
2576 pid_t kernel_clone(struct kernel_clone_args *args)
2578 u64 clone_flags = args->flags;
2579 struct completion vfork;
2581 struct task_struct *p;
2586 * For legacy clone() calls, CLONE_PIDFD uses the parent_tid argument
2587 * to return the pidfd. Hence, CLONE_PIDFD and CLONE_PARENT_SETTID are
2588 * mutually exclusive. With clone3() CLONE_PIDFD has grown a separate
2589 * field in struct clone_args and it still doesn't make sense to have
2590 * them both point at the same memory location. Performing this check
2591 * here has the advantage that we don't need to have a separate helper
2592 * to check for legacy clone().
2594 if ((args->flags & CLONE_PIDFD) &&
2595 (args->flags & CLONE_PARENT_SETTID) &&
2596 (args->pidfd == args->parent_tid))
2600 * Determine whether and which event to report to ptracer. When
2601 * called from kernel_thread or CLONE_UNTRACED is explicitly
2602 * requested, no event is reported; otherwise, report if the event
2603 * for the type of forking is enabled.
2605 if (!(clone_flags & CLONE_UNTRACED)) {
2606 if (clone_flags & CLONE_VFORK)
2607 trace = PTRACE_EVENT_VFORK;
2608 else if (args->exit_signal != SIGCHLD)
2609 trace = PTRACE_EVENT_CLONE;
2611 trace = PTRACE_EVENT_FORK;
2613 if (likely(!ptrace_event_enabled(current, trace)))
2617 p = copy_process(NULL, trace, NUMA_NO_NODE, args);
2618 add_latent_entropy();
2624 * Do this prior waking up the new thread - the thread pointer
2625 * might get invalid after that point, if the thread exits quickly.
2627 trace_sched_process_fork(current, p);
2629 pid = get_task_pid(p, PIDTYPE_PID);
2632 if (clone_flags & CLONE_PARENT_SETTID)
2633 put_user(nr, args->parent_tid);
2635 if (clone_flags & CLONE_VFORK) {
2636 p->vfork_done = &vfork;
2637 init_completion(&vfork);
2641 wake_up_new_task(p);
2643 /* forking complete and child started to run, tell ptracer */
2644 if (unlikely(trace))
2645 ptrace_event_pid(trace, pid);
2647 if (clone_flags & CLONE_VFORK) {
2648 if (!wait_for_vfork_done(p, &vfork))
2649 ptrace_event_pid(PTRACE_EVENT_VFORK_DONE, pid);
2657 * Create a kernel thread.
2659 pid_t kernel_thread(int (*fn)(void *), void *arg, unsigned long flags)
2661 struct kernel_clone_args args = {
2662 .flags = ((lower_32_bits(flags) | CLONE_VM |
2663 CLONE_UNTRACED) & ~CSIGNAL),
2664 .exit_signal = (lower_32_bits(flags) & CSIGNAL),
2665 .stack = (unsigned long)fn,
2666 .stack_size = (unsigned long)arg,
2669 return kernel_clone(&args);
2672 #ifdef __ARCH_WANT_SYS_FORK
2673 SYSCALL_DEFINE0(fork)
2676 struct kernel_clone_args args = {
2677 .exit_signal = SIGCHLD,
2680 return kernel_clone(&args);
2682 /* can not support in nommu mode */
2688 #ifdef __ARCH_WANT_SYS_VFORK
2689 SYSCALL_DEFINE0(vfork)
2691 struct kernel_clone_args args = {
2692 .flags = CLONE_VFORK | CLONE_VM,
2693 .exit_signal = SIGCHLD,
2696 return kernel_clone(&args);
2700 #ifdef __ARCH_WANT_SYS_CLONE
2701 #ifdef CONFIG_CLONE_BACKWARDS
2702 SYSCALL_DEFINE5(clone, unsigned long, clone_flags, unsigned long, newsp,
2703 int __user *, parent_tidptr,
2705 int __user *, child_tidptr)
2706 #elif defined(CONFIG_CLONE_BACKWARDS2)
2707 SYSCALL_DEFINE5(clone, unsigned long, newsp, unsigned long, clone_flags,
2708 int __user *, parent_tidptr,
2709 int __user *, child_tidptr,
2711 #elif defined(CONFIG_CLONE_BACKWARDS3)
2712 SYSCALL_DEFINE6(clone, unsigned long, clone_flags, unsigned long, newsp,
2714 int __user *, parent_tidptr,
2715 int __user *, child_tidptr,
2718 SYSCALL_DEFINE5(clone, unsigned long, clone_flags, unsigned long, newsp,
2719 int __user *, parent_tidptr,
2720 int __user *, child_tidptr,
2724 struct kernel_clone_args args = {
2725 .flags = (lower_32_bits(clone_flags) & ~CSIGNAL),
2726 .pidfd = parent_tidptr,
2727 .child_tid = child_tidptr,
2728 .parent_tid = parent_tidptr,
2729 .exit_signal = (lower_32_bits(clone_flags) & CSIGNAL),
2734 return kernel_clone(&args);
2738 #ifdef __ARCH_WANT_SYS_CLONE3
2740 noinline static int copy_clone_args_from_user(struct kernel_clone_args *kargs,
2741 struct clone_args __user *uargs,
2745 struct clone_args args;
2746 pid_t *kset_tid = kargs->set_tid;
2748 BUILD_BUG_ON(offsetofend(struct clone_args, tls) !=
2749 CLONE_ARGS_SIZE_VER0);
2750 BUILD_BUG_ON(offsetofend(struct clone_args, set_tid_size) !=
2751 CLONE_ARGS_SIZE_VER1);
2752 BUILD_BUG_ON(offsetofend(struct clone_args, cgroup) !=
2753 CLONE_ARGS_SIZE_VER2);
2754 BUILD_BUG_ON(sizeof(struct clone_args) != CLONE_ARGS_SIZE_VER2);
2756 if (unlikely(usize > PAGE_SIZE))
2758 if (unlikely(usize < CLONE_ARGS_SIZE_VER0))
2761 err = copy_struct_from_user(&args, sizeof(args), uargs, usize);
2765 if (unlikely(args.set_tid_size > MAX_PID_NS_LEVEL))
2768 if (unlikely(!args.set_tid && args.set_tid_size > 0))
2771 if (unlikely(args.set_tid && args.set_tid_size == 0))
2775 * Verify that higher 32bits of exit_signal are unset and that
2776 * it is a valid signal
2778 if (unlikely((args.exit_signal & ~((u64)CSIGNAL)) ||
2779 !valid_signal(args.exit_signal)))
2782 if ((args.flags & CLONE_INTO_CGROUP) &&
2783 (args.cgroup > INT_MAX || usize < CLONE_ARGS_SIZE_VER2))
2786 *kargs = (struct kernel_clone_args){
2787 .flags = args.flags,
2788 .pidfd = u64_to_user_ptr(args.pidfd),
2789 .child_tid = u64_to_user_ptr(args.child_tid),
2790 .parent_tid = u64_to_user_ptr(args.parent_tid),
2791 .exit_signal = args.exit_signal,
2792 .stack = args.stack,
2793 .stack_size = args.stack_size,
2795 .set_tid_size = args.set_tid_size,
2796 .cgroup = args.cgroup,
2800 copy_from_user(kset_tid, u64_to_user_ptr(args.set_tid),
2801 (kargs->set_tid_size * sizeof(pid_t))))
2804 kargs->set_tid = kset_tid;
2810 * clone3_stack_valid - check and prepare stack
2811 * @kargs: kernel clone args
2813 * Verify that the stack arguments userspace gave us are sane.
2814 * In addition, set the stack direction for userspace since it's easy for us to
2817 static inline bool clone3_stack_valid(struct kernel_clone_args *kargs)
2819 if (kargs->stack == 0) {
2820 if (kargs->stack_size > 0)
2823 if (kargs->stack_size == 0)
2826 if (!access_ok((void __user *)kargs->stack, kargs->stack_size))
2829 #if !defined(CONFIG_STACK_GROWSUP) && !defined(CONFIG_IA64)
2830 kargs->stack += kargs->stack_size;
2837 static bool clone3_args_valid(struct kernel_clone_args *kargs)
2839 /* Verify that no unknown flags are passed along. */
2841 ~(CLONE_LEGACY_FLAGS | CLONE_CLEAR_SIGHAND | CLONE_INTO_CGROUP))
2845 * - make the CLONE_DETACHED bit reusable for clone3
2846 * - make the CSIGNAL bits reusable for clone3
2848 if (kargs->flags & (CLONE_DETACHED | CSIGNAL))
2851 if ((kargs->flags & (CLONE_SIGHAND | CLONE_CLEAR_SIGHAND)) ==
2852 (CLONE_SIGHAND | CLONE_CLEAR_SIGHAND))
2855 if ((kargs->flags & (CLONE_THREAD | CLONE_PARENT)) &&
2859 if (!clone3_stack_valid(kargs))
2866 * clone3 - create a new process with specific properties
2867 * @uargs: argument structure
2868 * @size: size of @uargs
2870 * clone3() is the extensible successor to clone()/clone2().
2871 * It takes a struct as argument that is versioned by its size.
2873 * Return: On success, a positive PID for the child process.
2874 * On error, a negative errno number.
2876 SYSCALL_DEFINE2(clone3, struct clone_args __user *, uargs, size_t, size)
2880 struct kernel_clone_args kargs;
2881 pid_t set_tid[MAX_PID_NS_LEVEL];
2883 kargs.set_tid = set_tid;
2885 err = copy_clone_args_from_user(&kargs, uargs, size);
2889 if (!clone3_args_valid(&kargs))
2892 return kernel_clone(&kargs);
2896 void walk_process_tree(struct task_struct *top, proc_visitor visitor, void *data)
2898 struct task_struct *leader, *parent, *child;
2901 read_lock(&tasklist_lock);
2902 leader = top = top->group_leader;
2904 for_each_thread(leader, parent) {
2905 list_for_each_entry(child, &parent->children, sibling) {
2906 res = visitor(child, data);
2918 if (leader != top) {
2920 parent = child->real_parent;
2921 leader = parent->group_leader;
2925 read_unlock(&tasklist_lock);
2928 #ifndef ARCH_MIN_MMSTRUCT_ALIGN
2929 #define ARCH_MIN_MMSTRUCT_ALIGN 0
2932 static void sighand_ctor(void *data)
2934 struct sighand_struct *sighand = data;
2936 spin_lock_init(&sighand->siglock);
2937 init_waitqueue_head(&sighand->signalfd_wqh);
2940 void __init proc_caches_init(void)
2942 unsigned int mm_size;
2944 sighand_cachep = kmem_cache_create("sighand_cache",
2945 sizeof(struct sighand_struct), 0,
2946 SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_TYPESAFE_BY_RCU|
2947 SLAB_ACCOUNT, sighand_ctor);
2948 signal_cachep = kmem_cache_create("signal_cache",
2949 sizeof(struct signal_struct), 0,
2950 SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_ACCOUNT,
2952 files_cachep = kmem_cache_create("files_cache",
2953 sizeof(struct files_struct), 0,
2954 SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_ACCOUNT,
2956 fs_cachep = kmem_cache_create("fs_cache",
2957 sizeof(struct fs_struct), 0,
2958 SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_ACCOUNT,
2962 * The mm_cpumask is located at the end of mm_struct, and is
2963 * dynamically sized based on the maximum CPU number this system
2964 * can have, taking hotplug into account (nr_cpu_ids).
2966 mm_size = sizeof(struct mm_struct) + cpumask_size();
2968 mm_cachep = kmem_cache_create_usercopy("mm_struct",
2969 mm_size, ARCH_MIN_MMSTRUCT_ALIGN,
2970 SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_ACCOUNT,
2971 offsetof(struct mm_struct, saved_auxv),
2972 sizeof_field(struct mm_struct, saved_auxv),
2974 vm_area_cachep = KMEM_CACHE(vm_area_struct, SLAB_PANIC|SLAB_ACCOUNT);
2976 nsproxy_cache_init();
2980 * Check constraints on flags passed to the unshare system call.
2982 static int check_unshare_flags(unsigned long unshare_flags)
2984 if (unshare_flags & ~(CLONE_THREAD|CLONE_FS|CLONE_NEWNS|CLONE_SIGHAND|
2985 CLONE_VM|CLONE_FILES|CLONE_SYSVSEM|
2986 CLONE_NEWUTS|CLONE_NEWIPC|CLONE_NEWNET|
2987 CLONE_NEWUSER|CLONE_NEWPID|CLONE_NEWCGROUP|
2991 * Not implemented, but pretend it works if there is nothing
2992 * to unshare. Note that unsharing the address space or the
2993 * signal handlers also need to unshare the signal queues (aka
2996 if (unshare_flags & (CLONE_THREAD | CLONE_SIGHAND | CLONE_VM)) {
2997 if (!thread_group_empty(current))
3000 if (unshare_flags & (CLONE_SIGHAND | CLONE_VM)) {
3001 if (refcount_read(¤t->sighand->count) > 1)
3004 if (unshare_flags & CLONE_VM) {
3005 if (!current_is_single_threaded())
3013 * Unshare the filesystem structure if it is being shared
3015 static int unshare_fs(unsigned long unshare_flags, struct fs_struct **new_fsp)
3017 struct fs_struct *fs = current->fs;
3019 if (!(unshare_flags & CLONE_FS) || !fs)
3022 /* don't need lock here; in the worst case we'll do useless copy */
3026 *new_fsp = copy_fs_struct(fs);
3034 * Unshare file descriptor table if it is being shared
3036 int unshare_fd(unsigned long unshare_flags, unsigned int max_fds,
3037 struct files_struct **new_fdp)
3039 struct files_struct *fd = current->files;
3042 if ((unshare_flags & CLONE_FILES) &&
3043 (fd && atomic_read(&fd->count) > 1)) {
3044 *new_fdp = dup_fd(fd, max_fds, &error);
3053 * unshare allows a process to 'unshare' part of the process
3054 * context which was originally shared using clone. copy_*
3055 * functions used by kernel_clone() cannot be used here directly
3056 * because they modify an inactive task_struct that is being
3057 * constructed. Here we are modifying the current, active,
3060 int ksys_unshare(unsigned long unshare_flags)
3062 struct fs_struct *fs, *new_fs = NULL;
3063 struct files_struct *fd, *new_fd = NULL;
3064 struct cred *new_cred = NULL;
3065 struct nsproxy *new_nsproxy = NULL;
3070 * If unsharing a user namespace must also unshare the thread group
3071 * and unshare the filesystem root and working directories.
3073 if (unshare_flags & CLONE_NEWUSER)
3074 unshare_flags |= CLONE_THREAD | CLONE_FS;
3076 * If unsharing vm, must also unshare signal handlers.
3078 if (unshare_flags & CLONE_VM)
3079 unshare_flags |= CLONE_SIGHAND;
3081 * If unsharing a signal handlers, must also unshare the signal queues.
3083 if (unshare_flags & CLONE_SIGHAND)
3084 unshare_flags |= CLONE_THREAD;
3086 * If unsharing namespace, must also unshare filesystem information.
3088 if (unshare_flags & CLONE_NEWNS)
3089 unshare_flags |= CLONE_FS;
3091 err = check_unshare_flags(unshare_flags);
3093 goto bad_unshare_out;
3095 * CLONE_NEWIPC must also detach from the undolist: after switching
3096 * to a new ipc namespace, the semaphore arrays from the old
3097 * namespace are unreachable.
3099 if (unshare_flags & (CLONE_NEWIPC|CLONE_SYSVSEM))
3101 err = unshare_fs(unshare_flags, &new_fs);
3103 goto bad_unshare_out;
3104 err = unshare_fd(unshare_flags, NR_OPEN_MAX, &new_fd);
3106 goto bad_unshare_cleanup_fs;
3107 err = unshare_userns(unshare_flags, &new_cred);
3109 goto bad_unshare_cleanup_fd;
3110 err = unshare_nsproxy_namespaces(unshare_flags, &new_nsproxy,
3113 goto bad_unshare_cleanup_cred;
3116 err = set_cred_ucounts(new_cred);
3118 goto bad_unshare_cleanup_cred;
3121 if (new_fs || new_fd || do_sysvsem || new_cred || new_nsproxy) {
3124 * CLONE_SYSVSEM is equivalent to sys_exit().
3128 if (unshare_flags & CLONE_NEWIPC) {
3129 /* Orphan segments in old ns (see sem above). */
3131 shm_init_task(current);
3135 switch_task_namespaces(current, new_nsproxy);
3141 spin_lock(&fs->lock);
3142 current->fs = new_fs;
3147 spin_unlock(&fs->lock);
3151 fd = current->files;
3152 current->files = new_fd;
3156 task_unlock(current);
3159 /* Install the new user namespace */
3160 commit_creds(new_cred);
3165 perf_event_namespaces(current);
3167 bad_unshare_cleanup_cred:
3170 bad_unshare_cleanup_fd:
3172 put_files_struct(new_fd);
3174 bad_unshare_cleanup_fs:
3176 free_fs_struct(new_fs);
3182 SYSCALL_DEFINE1(unshare, unsigned long, unshare_flags)
3184 return ksys_unshare(unshare_flags);
3188 * Helper to unshare the files of the current task.
3189 * We don't want to expose copy_files internals to
3190 * the exec layer of the kernel.
3193 int unshare_files(void)
3195 struct task_struct *task = current;
3196 struct files_struct *old, *copy = NULL;
3199 error = unshare_fd(CLONE_FILES, NR_OPEN_MAX, ©);
3207 put_files_struct(old);
3211 int sysctl_max_threads(struct ctl_table *table, int write,
3212 void *buffer, size_t *lenp, loff_t *ppos)
3216 int threads = max_threads;
3218 int max = MAX_THREADS;
3225 ret = proc_dointvec_minmax(&t, write, buffer, lenp, ppos);
3229 max_threads = threads;