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/rtmutex.h>
24 #include <linux/init.h>
25 #include <linux/unistd.h>
26 #include <linux/module.h>
27 #include <linux/vmalloc.h>
28 #include <linux/completion.h>
29 #include <linux/personality.h>
30 #include <linux/mempolicy.h>
31 #include <linux/sem.h>
32 #include <linux/file.h>
33 #include <linux/fdtable.h>
34 #include <linux/iocontext.h>
35 #include <linux/key.h>
36 #include <linux/binfmts.h>
37 #include <linux/mman.h>
38 #include <linux/mmu_notifier.h>
41 #include <linux/vmacache.h>
42 #include <linux/nsproxy.h>
43 #include <linux/capability.h>
44 #include <linux/cpu.h>
45 #include <linux/cgroup.h>
46 #include <linux/security.h>
47 #include <linux/hugetlb.h>
48 #include <linux/seccomp.h>
49 #include <linux/swap.h>
50 #include <linux/syscalls.h>
51 #include <linux/jiffies.h>
52 #include <linux/futex.h>
53 #include <linux/compat.h>
54 #include <linux/kthread.h>
55 #include <linux/task_io_accounting_ops.h>
56 #include <linux/rcupdate.h>
57 #include <linux/ptrace.h>
58 #include <linux/mount.h>
59 #include <linux/audit.h>
60 #include <linux/memcontrol.h>
61 #include <linux/ftrace.h>
62 #include <linux/proc_fs.h>
63 #include <linux/profile.h>
64 #include <linux/rmap.h>
65 #include <linux/ksm.h>
66 #include <linux/acct.h>
67 #include <linux/userfaultfd_k.h>
68 #include <linux/tsacct_kern.h>
69 #include <linux/cn_proc.h>
70 #include <linux/freezer.h>
71 #include <linux/delayacct.h>
72 #include <linux/taskstats_kern.h>
73 #include <linux/random.h>
74 #include <linux/tty.h>
75 #include <linux/blkdev.h>
76 #include <linux/fs_struct.h>
77 #include <linux/magic.h>
78 #include <linux/perf_event.h>
79 #include <linux/posix-timers.h>
80 #include <linux/user-return-notifier.h>
81 #include <linux/oom.h>
82 #include <linux/khugepaged.h>
83 #include <linux/signalfd.h>
84 #include <linux/uprobes.h>
85 #include <linux/aio.h>
86 #include <linux/compiler.h>
87 #include <linux/sysctl.h>
88 #include <linux/kcov.h>
90 #include <asm/pgtable.h>
91 #include <asm/pgalloc.h>
92 #include <linux/uaccess.h>
93 #include <asm/mmu_context.h>
94 #include <asm/cacheflush.h>
95 #include <asm/tlbflush.h>
97 #include <trace/events/sched.h>
99 #define CREATE_TRACE_POINTS
100 #include <trace/events/task.h>
103 * Minimum number of threads to boot the kernel
105 #define MIN_THREADS 20
108 * Maximum number of threads
110 #define MAX_THREADS FUTEX_TID_MASK
113 * Protected counters by write_lock_irq(&tasklist_lock)
115 unsigned long total_forks
; /* Handle normal Linux uptimes. */
116 int nr_threads
; /* The idle threads do not count.. */
118 int max_threads
; /* tunable limit on nr_threads */
120 DEFINE_PER_CPU(unsigned long, process_counts
) = 0;
122 __cacheline_aligned
DEFINE_RWLOCK(tasklist_lock
); /* outer */
124 #ifdef CONFIG_PROVE_RCU
125 int lockdep_tasklist_lock_is_held(void)
127 return lockdep_is_held(&tasklist_lock
);
129 EXPORT_SYMBOL_GPL(lockdep_tasklist_lock_is_held
);
130 #endif /* #ifdef CONFIG_PROVE_RCU */
132 int nr_processes(void)
137 for_each_possible_cpu(cpu
)
138 total
+= per_cpu(process_counts
, cpu
);
143 void __weak
arch_release_task_struct(struct task_struct
*tsk
)
147 #ifndef CONFIG_ARCH_TASK_STRUCT_ALLOCATOR
148 static struct kmem_cache
*task_struct_cachep
;
150 static inline struct task_struct
*alloc_task_struct_node(int node
)
152 return kmem_cache_alloc_node(task_struct_cachep
, GFP_KERNEL
, node
);
155 static inline void free_task_struct(struct task_struct
*tsk
)
157 kmem_cache_free(task_struct_cachep
, tsk
);
161 void __weak
arch_release_thread_stack(unsigned long *stack
)
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
]);
182 static unsigned long *alloc_thread_stack_node(struct task_struct
*tsk
, int node
)
184 #ifdef CONFIG_VMAP_STACK
189 for (i
= 0; i
< NR_CACHED_STACKS
; i
++) {
190 struct vm_struct
*s
= this_cpu_read(cached_stacks
[i
]);
194 this_cpu_write(cached_stacks
[i
], NULL
);
196 tsk
->stack_vm_area
= s
;
202 stack
= __vmalloc_node_range(THREAD_SIZE
, THREAD_SIZE
,
203 VMALLOC_START
, VMALLOC_END
,
204 THREADINFO_GFP
| __GFP_HIGHMEM
,
206 0, node
, __builtin_return_address(0));
209 * We can't call find_vm_area() in interrupt context, and
210 * free_thread_stack() can be called in interrupt context,
211 * so cache the vm_struct.
214 tsk
->stack_vm_area
= find_vm_area(stack
);
217 struct page
*page
= alloc_pages_node(node
, THREADINFO_GFP
,
220 return page
? page_address(page
) : NULL
;
224 static inline void free_thread_stack(struct task_struct
*tsk
)
226 #ifdef CONFIG_VMAP_STACK
227 if (task_stack_vm_area(tsk
)) {
231 local_irq_save(flags
);
232 for (i
= 0; i
< NR_CACHED_STACKS
; i
++) {
233 if (this_cpu_read(cached_stacks
[i
]))
236 this_cpu_write(cached_stacks
[i
], tsk
->stack_vm_area
);
237 local_irq_restore(flags
);
240 local_irq_restore(flags
);
242 vfree_atomic(tsk
->stack
);
247 __free_pages(virt_to_page(tsk
->stack
), THREAD_SIZE_ORDER
);
250 static struct kmem_cache
*thread_stack_cache
;
252 static unsigned long *alloc_thread_stack_node(struct task_struct
*tsk
,
255 return kmem_cache_alloc_node(thread_stack_cache
, THREADINFO_GFP
, node
);
258 static void free_thread_stack(struct task_struct
*tsk
)
260 kmem_cache_free(thread_stack_cache
, tsk
->stack
);
263 void thread_stack_cache_init(void)
265 thread_stack_cache
= kmem_cache_create("thread_stack", THREAD_SIZE
,
266 THREAD_SIZE
, 0, NULL
);
267 BUG_ON(thread_stack_cache
== NULL
);
272 /* SLAB cache for signal_struct structures (tsk->signal) */
273 static struct kmem_cache
*signal_cachep
;
275 /* SLAB cache for sighand_struct structures (tsk->sighand) */
276 struct kmem_cache
*sighand_cachep
;
278 /* SLAB cache for files_struct structures (tsk->files) */
279 struct kmem_cache
*files_cachep
;
281 /* SLAB cache for fs_struct structures (tsk->fs) */
282 struct kmem_cache
*fs_cachep
;
284 /* SLAB cache for vm_area_struct structures */
285 struct kmem_cache
*vm_area_cachep
;
287 /* SLAB cache for mm_struct structures (tsk->mm) */
288 static struct kmem_cache
*mm_cachep
;
290 static void account_kernel_stack(struct task_struct
*tsk
, int account
)
292 void *stack
= task_stack_page(tsk
);
293 struct vm_struct
*vm
= task_stack_vm_area(tsk
);
295 BUILD_BUG_ON(IS_ENABLED(CONFIG_VMAP_STACK
) && PAGE_SIZE
% 1024 != 0);
300 BUG_ON(vm
->nr_pages
!= THREAD_SIZE
/ PAGE_SIZE
);
302 for (i
= 0; i
< THREAD_SIZE
/ PAGE_SIZE
; i
++) {
303 mod_zone_page_state(page_zone(vm
->pages
[i
]),
305 PAGE_SIZE
/ 1024 * account
);
308 /* All stack pages belong to the same memcg. */
309 memcg_kmem_update_page_stat(vm
->pages
[0], MEMCG_KERNEL_STACK_KB
,
310 account
* (THREAD_SIZE
/ 1024));
313 * All stack pages are in the same zone and belong to the
316 struct page
*first_page
= virt_to_page(stack
);
318 mod_zone_page_state(page_zone(first_page
), NR_KERNEL_STACK_KB
,
319 THREAD_SIZE
/ 1024 * account
);
321 memcg_kmem_update_page_stat(first_page
, MEMCG_KERNEL_STACK_KB
,
322 account
* (THREAD_SIZE
/ 1024));
326 static void release_task_stack(struct task_struct
*tsk
)
328 if (WARN_ON(tsk
->state
!= TASK_DEAD
))
329 return; /* Better to leak the stack than to free prematurely */
331 account_kernel_stack(tsk
, -1);
332 arch_release_thread_stack(tsk
->stack
);
333 free_thread_stack(tsk
);
335 #ifdef CONFIG_VMAP_STACK
336 tsk
->stack_vm_area
= NULL
;
340 #ifdef CONFIG_THREAD_INFO_IN_TASK
341 void put_task_stack(struct task_struct
*tsk
)
343 if (atomic_dec_and_test(&tsk
->stack_refcount
))
344 release_task_stack(tsk
);
348 void free_task(struct task_struct
*tsk
)
350 #ifndef CONFIG_THREAD_INFO_IN_TASK
352 * The task is finally done with both the stack and thread_info,
355 release_task_stack(tsk
);
358 * If the task had a separate stack allocation, it should be gone
361 WARN_ON_ONCE(atomic_read(&tsk
->stack_refcount
) != 0);
363 rt_mutex_debug_task_free(tsk
);
364 ftrace_graph_exit_task(tsk
);
365 put_seccomp_filter(tsk
);
366 arch_release_task_struct(tsk
);
367 if (tsk
->flags
& PF_KTHREAD
)
368 free_kthread_struct(tsk
);
369 free_task_struct(tsk
);
371 EXPORT_SYMBOL(free_task
);
373 static inline void free_signal_struct(struct signal_struct
*sig
)
375 taskstats_tgid_free(sig
);
376 sched_autogroup_exit(sig
);
378 * __mmdrop is not safe to call from softirq context on x86 due to
379 * pgd_dtor so postpone it to the async context
382 mmdrop_async(sig
->oom_mm
);
383 kmem_cache_free(signal_cachep
, sig
);
386 static inline void put_signal_struct(struct signal_struct
*sig
)
388 if (atomic_dec_and_test(&sig
->sigcnt
))
389 free_signal_struct(sig
);
392 void __put_task_struct(struct task_struct
*tsk
)
394 WARN_ON(!tsk
->exit_state
);
395 WARN_ON(atomic_read(&tsk
->usage
));
396 WARN_ON(tsk
== current
);
400 security_task_free(tsk
);
402 delayacct_tsk_free(tsk
);
403 put_signal_struct(tsk
->signal
);
405 if (!profile_handoff_task(tsk
))
408 EXPORT_SYMBOL_GPL(__put_task_struct
);
410 void __init __weak
arch_task_cache_init(void) { }
415 static void set_max_threads(unsigned int max_threads_suggested
)
420 * The number of threads shall be limited such that the thread
421 * structures may only consume a small part of the available memory.
423 if (fls64(totalram_pages
) + fls64(PAGE_SIZE
) > 64)
424 threads
= MAX_THREADS
;
426 threads
= div64_u64((u64
) totalram_pages
* (u64
) PAGE_SIZE
,
427 (u64
) THREAD_SIZE
* 8UL);
429 if (threads
> max_threads_suggested
)
430 threads
= max_threads_suggested
;
432 max_threads
= clamp_t(u64
, threads
, MIN_THREADS
, MAX_THREADS
);
435 #ifdef CONFIG_ARCH_WANTS_DYNAMIC_TASK_STRUCT
436 /* Initialized by the architecture: */
437 int arch_task_struct_size __read_mostly
;
440 void __init
fork_init(void)
443 #ifndef CONFIG_ARCH_TASK_STRUCT_ALLOCATOR
444 #ifndef ARCH_MIN_TASKALIGN
445 #define ARCH_MIN_TASKALIGN 0
447 int align
= max_t(int, L1_CACHE_BYTES
, ARCH_MIN_TASKALIGN
);
449 /* create a slab on which task_structs can be allocated */
450 task_struct_cachep
= kmem_cache_create("task_struct",
451 arch_task_struct_size
, align
,
452 SLAB_PANIC
|SLAB_NOTRACK
|SLAB_ACCOUNT
, NULL
);
455 /* do the arch specific task caches init */
456 arch_task_cache_init();
458 set_max_threads(MAX_THREADS
);
460 init_task
.signal
->rlim
[RLIMIT_NPROC
].rlim_cur
= max_threads
/2;
461 init_task
.signal
->rlim
[RLIMIT_NPROC
].rlim_max
= max_threads
/2;
462 init_task
.signal
->rlim
[RLIMIT_SIGPENDING
] =
463 init_task
.signal
->rlim
[RLIMIT_NPROC
];
465 for (i
= 0; i
< UCOUNT_COUNTS
; i
++) {
466 init_user_ns
.ucount_max
[i
] = max_threads
/2;
470 int __weak
arch_dup_task_struct(struct task_struct
*dst
,
471 struct task_struct
*src
)
477 void set_task_stack_end_magic(struct task_struct
*tsk
)
479 unsigned long *stackend
;
481 stackend
= end_of_stack(tsk
);
482 *stackend
= STACK_END_MAGIC
; /* for overflow detection */
485 static struct task_struct
*dup_task_struct(struct task_struct
*orig
, int node
)
487 struct task_struct
*tsk
;
488 unsigned long *stack
;
489 struct vm_struct
*stack_vm_area
;
492 if (node
== NUMA_NO_NODE
)
493 node
= tsk_fork_get_node(orig
);
494 tsk
= alloc_task_struct_node(node
);
498 stack
= alloc_thread_stack_node(tsk
, node
);
502 stack_vm_area
= task_stack_vm_area(tsk
);
504 err
= arch_dup_task_struct(tsk
, orig
);
507 * arch_dup_task_struct() clobbers the stack-related fields. Make
508 * sure they're properly initialized before using any stack-related
512 #ifdef CONFIG_VMAP_STACK
513 tsk
->stack_vm_area
= stack_vm_area
;
515 #ifdef CONFIG_THREAD_INFO_IN_TASK
516 atomic_set(&tsk
->stack_refcount
, 1);
522 #ifdef CONFIG_SECCOMP
524 * We must handle setting up seccomp filters once we're under
525 * the sighand lock in case orig has changed between now and
526 * then. Until then, filter must be NULL to avoid messing up
527 * the usage counts on the error path calling free_task.
529 tsk
->seccomp
.filter
= NULL
;
532 setup_thread_stack(tsk
, orig
);
533 clear_user_return_notifier(tsk
);
534 clear_tsk_need_resched(tsk
);
535 set_task_stack_end_magic(tsk
);
537 #ifdef CONFIG_CC_STACKPROTECTOR
538 tsk
->stack_canary
= get_random_int();
542 * One for us, one for whoever does the "release_task()" (usually
545 atomic_set(&tsk
->usage
, 2);
546 #ifdef CONFIG_BLK_DEV_IO_TRACE
549 tsk
->splice_pipe
= NULL
;
550 tsk
->task_frag
.page
= NULL
;
551 tsk
->wake_q
.next
= NULL
;
553 account_kernel_stack(tsk
, 1);
560 free_thread_stack(tsk
);
562 free_task_struct(tsk
);
567 static __latent_entropy
int dup_mmap(struct mm_struct
*mm
,
568 struct mm_struct
*oldmm
)
570 struct vm_area_struct
*mpnt
, *tmp
, *prev
, **pprev
;
571 struct rb_node
**rb_link
, *rb_parent
;
573 unsigned long charge
;
576 uprobe_start_dup_mmap();
577 if (down_write_killable(&oldmm
->mmap_sem
)) {
579 goto fail_uprobe_end
;
581 flush_cache_dup_mm(oldmm
);
582 uprobe_dup_mmap(oldmm
, mm
);
584 * Not linked in yet - no deadlock potential:
586 down_write_nested(&mm
->mmap_sem
, SINGLE_DEPTH_NESTING
);
588 /* No ordering required: file already has been exposed. */
589 RCU_INIT_POINTER(mm
->exe_file
, get_mm_exe_file(oldmm
));
591 mm
->total_vm
= oldmm
->total_vm
;
592 mm
->data_vm
= oldmm
->data_vm
;
593 mm
->exec_vm
= oldmm
->exec_vm
;
594 mm
->stack_vm
= oldmm
->stack_vm
;
596 rb_link
= &mm
->mm_rb
.rb_node
;
599 retval
= ksm_fork(mm
, oldmm
);
602 retval
= khugepaged_fork(mm
, oldmm
);
607 for (mpnt
= oldmm
->mmap
; mpnt
; mpnt
= mpnt
->vm_next
) {
610 if (mpnt
->vm_flags
& VM_DONTCOPY
) {
611 vm_stat_account(mm
, mpnt
->vm_flags
, -vma_pages(mpnt
));
615 if (mpnt
->vm_flags
& VM_ACCOUNT
) {
616 unsigned long len
= vma_pages(mpnt
);
618 if (security_vm_enough_memory_mm(oldmm
, len
)) /* sic */
622 tmp
= kmem_cache_alloc(vm_area_cachep
, GFP_KERNEL
);
626 INIT_LIST_HEAD(&tmp
->anon_vma_chain
);
627 retval
= vma_dup_policy(mpnt
, tmp
);
629 goto fail_nomem_policy
;
631 retval
= dup_userfaultfd(tmp
, &uf
);
633 goto fail_nomem_anon_vma_fork
;
634 if (anon_vma_fork(tmp
, mpnt
))
635 goto fail_nomem_anon_vma_fork
;
636 tmp
->vm_flags
&= ~(VM_LOCKED
| VM_LOCKONFAULT
);
637 tmp
->vm_next
= tmp
->vm_prev
= NULL
;
640 struct inode
*inode
= file_inode(file
);
641 struct address_space
*mapping
= file
->f_mapping
;
644 if (tmp
->vm_flags
& VM_DENYWRITE
)
645 atomic_dec(&inode
->i_writecount
);
646 i_mmap_lock_write(mapping
);
647 if (tmp
->vm_flags
& VM_SHARED
)
648 atomic_inc(&mapping
->i_mmap_writable
);
649 flush_dcache_mmap_lock(mapping
);
650 /* insert tmp into the share list, just after mpnt */
651 vma_interval_tree_insert_after(tmp
, mpnt
,
653 flush_dcache_mmap_unlock(mapping
);
654 i_mmap_unlock_write(mapping
);
658 * Clear hugetlb-related page reserves for children. This only
659 * affects MAP_PRIVATE mappings. Faults generated by the child
660 * are not guaranteed to succeed, even if read-only
662 if (is_vm_hugetlb_page(tmp
))
663 reset_vma_resv_huge_pages(tmp
);
666 * Link in the new vma and copy the page table entries.
669 pprev
= &tmp
->vm_next
;
673 __vma_link_rb(mm
, tmp
, rb_link
, rb_parent
);
674 rb_link
= &tmp
->vm_rb
.rb_right
;
675 rb_parent
= &tmp
->vm_rb
;
678 retval
= copy_page_range(mm
, oldmm
, mpnt
);
680 if (tmp
->vm_ops
&& tmp
->vm_ops
->open
)
681 tmp
->vm_ops
->open(tmp
);
686 /* a new mm has just been created */
687 arch_dup_mmap(oldmm
, mm
);
690 up_write(&mm
->mmap_sem
);
692 up_write(&oldmm
->mmap_sem
);
693 dup_userfaultfd_complete(&uf
);
695 uprobe_end_dup_mmap();
697 fail_nomem_anon_vma_fork
:
698 mpol_put(vma_policy(tmp
));
700 kmem_cache_free(vm_area_cachep
, tmp
);
703 vm_unacct_memory(charge
);
707 static inline int mm_alloc_pgd(struct mm_struct
*mm
)
709 mm
->pgd
= pgd_alloc(mm
);
710 if (unlikely(!mm
->pgd
))
715 static inline void mm_free_pgd(struct mm_struct
*mm
)
717 pgd_free(mm
, mm
->pgd
);
720 static int dup_mmap(struct mm_struct
*mm
, struct mm_struct
*oldmm
)
722 down_write(&oldmm
->mmap_sem
);
723 RCU_INIT_POINTER(mm
->exe_file
, get_mm_exe_file(oldmm
));
724 up_write(&oldmm
->mmap_sem
);
727 #define mm_alloc_pgd(mm) (0)
728 #define mm_free_pgd(mm)
729 #endif /* CONFIG_MMU */
731 __cacheline_aligned_in_smp
DEFINE_SPINLOCK(mmlist_lock
);
733 #define allocate_mm() (kmem_cache_alloc(mm_cachep, GFP_KERNEL))
734 #define free_mm(mm) (kmem_cache_free(mm_cachep, (mm)))
736 static unsigned long default_dump_filter
= MMF_DUMP_FILTER_DEFAULT
;
738 static int __init
coredump_filter_setup(char *s
)
740 default_dump_filter
=
741 (simple_strtoul(s
, NULL
, 0) << MMF_DUMP_FILTER_SHIFT
) &
742 MMF_DUMP_FILTER_MASK
;
746 __setup("coredump_filter=", coredump_filter_setup
);
748 #include <linux/init_task.h>
750 static void mm_init_aio(struct mm_struct
*mm
)
753 spin_lock_init(&mm
->ioctx_lock
);
754 mm
->ioctx_table
= NULL
;
758 static void mm_init_owner(struct mm_struct
*mm
, struct task_struct
*p
)
765 static struct mm_struct
*mm_init(struct mm_struct
*mm
, struct task_struct
*p
,
766 struct user_namespace
*user_ns
)
770 mm
->vmacache_seqnum
= 0;
771 atomic_set(&mm
->mm_users
, 1);
772 atomic_set(&mm
->mm_count
, 1);
773 init_rwsem(&mm
->mmap_sem
);
774 INIT_LIST_HEAD(&mm
->mmlist
);
775 mm
->core_state
= NULL
;
776 atomic_long_set(&mm
->nr_ptes
, 0);
781 memset(&mm
->rss_stat
, 0, sizeof(mm
->rss_stat
));
782 spin_lock_init(&mm
->page_table_lock
);
785 mm_init_owner(mm
, p
);
786 mmu_notifier_mm_init(mm
);
787 clear_tlb_flush_pending(mm
);
788 #if defined(CONFIG_TRANSPARENT_HUGEPAGE) && !USE_SPLIT_PMD_PTLOCKS
789 mm
->pmd_huge_pte
= NULL
;
793 mm
->flags
= current
->mm
->flags
& MMF_INIT_MASK
;
794 mm
->def_flags
= current
->mm
->def_flags
& VM_INIT_DEF_MASK
;
796 mm
->flags
= default_dump_filter
;
800 if (mm_alloc_pgd(mm
))
803 if (init_new_context(p
, mm
))
806 mm
->user_ns
= get_user_ns(user_ns
);
816 static void check_mm(struct mm_struct
*mm
)
820 for (i
= 0; i
< NR_MM_COUNTERS
; i
++) {
821 long x
= atomic_long_read(&mm
->rss_stat
.count
[i
]);
824 printk(KERN_ALERT
"BUG: Bad rss-counter state "
825 "mm:%p idx:%d val:%ld\n", mm
, i
, x
);
828 if (atomic_long_read(&mm
->nr_ptes
))
829 pr_alert("BUG: non-zero nr_ptes on freeing mm: %ld\n",
830 atomic_long_read(&mm
->nr_ptes
));
832 pr_alert("BUG: non-zero nr_pmds on freeing mm: %ld\n",
835 #if defined(CONFIG_TRANSPARENT_HUGEPAGE) && !USE_SPLIT_PMD_PTLOCKS
836 VM_BUG_ON_MM(mm
->pmd_huge_pte
, mm
);
841 * Allocate and initialize an mm_struct.
843 struct mm_struct
*mm_alloc(void)
845 struct mm_struct
*mm
;
851 memset(mm
, 0, sizeof(*mm
));
852 return mm_init(mm
, current
, current_user_ns());
856 * Called when the last reference to the mm
857 * is dropped: either by a lazy thread or by
858 * mmput. Free the page directory and the mm.
860 void __mmdrop(struct mm_struct
*mm
)
862 BUG_ON(mm
== &init_mm
);
865 mmu_notifier_mm_destroy(mm
);
867 put_user_ns(mm
->user_ns
);
870 EXPORT_SYMBOL_GPL(__mmdrop
);
872 static inline void __mmput(struct mm_struct
*mm
)
874 VM_BUG_ON(atomic_read(&mm
->mm_users
));
876 uprobe_clear_state(mm
);
879 khugepaged_exit(mm
); /* must run before exit_mmap */
881 mm_put_huge_zero_page(mm
);
882 set_mm_exe_file(mm
, NULL
);
883 if (!list_empty(&mm
->mmlist
)) {
884 spin_lock(&mmlist_lock
);
885 list_del(&mm
->mmlist
);
886 spin_unlock(&mmlist_lock
);
889 module_put(mm
->binfmt
->module
);
890 set_bit(MMF_OOM_SKIP
, &mm
->flags
);
895 * Decrement the use count and release all resources for an mm.
897 void mmput(struct mm_struct
*mm
)
901 if (atomic_dec_and_test(&mm
->mm_users
))
904 EXPORT_SYMBOL_GPL(mmput
);
907 static void mmput_async_fn(struct work_struct
*work
)
909 struct mm_struct
*mm
= container_of(work
, struct mm_struct
, async_put_work
);
913 void mmput_async(struct mm_struct
*mm
)
915 if (atomic_dec_and_test(&mm
->mm_users
)) {
916 INIT_WORK(&mm
->async_put_work
, mmput_async_fn
);
917 schedule_work(&mm
->async_put_work
);
923 * set_mm_exe_file - change a reference to the mm's executable file
925 * This changes mm's executable file (shown as symlink /proc/[pid]/exe).
927 * Main users are mmput() and sys_execve(). Callers prevent concurrent
928 * invocations: in mmput() nobody alive left, in execve task is single
929 * threaded. sys_prctl(PR_SET_MM_MAP/EXE_FILE) also needs to set the
930 * mm->exe_file, but does so without using set_mm_exe_file() in order
931 * to do avoid the need for any locks.
933 void set_mm_exe_file(struct mm_struct
*mm
, struct file
*new_exe_file
)
935 struct file
*old_exe_file
;
938 * It is safe to dereference the exe_file without RCU as
939 * this function is only called if nobody else can access
940 * this mm -- see comment above for justification.
942 old_exe_file
= rcu_dereference_raw(mm
->exe_file
);
945 get_file(new_exe_file
);
946 rcu_assign_pointer(mm
->exe_file
, new_exe_file
);
952 * get_mm_exe_file - acquire a reference to the mm's executable file
954 * Returns %NULL if mm has no associated executable file.
955 * User must release file via fput().
957 struct file
*get_mm_exe_file(struct mm_struct
*mm
)
959 struct file
*exe_file
;
962 exe_file
= rcu_dereference(mm
->exe_file
);
963 if (exe_file
&& !get_file_rcu(exe_file
))
968 EXPORT_SYMBOL(get_mm_exe_file
);
971 * get_task_exe_file - acquire a reference to the task's executable file
973 * Returns %NULL if task's mm (if any) has no associated executable file or
974 * this is a kernel thread with borrowed mm (see the comment above get_task_mm).
975 * User must release file via fput().
977 struct file
*get_task_exe_file(struct task_struct
*task
)
979 struct file
*exe_file
= NULL
;
980 struct mm_struct
*mm
;
985 if (!(task
->flags
& PF_KTHREAD
))
986 exe_file
= get_mm_exe_file(mm
);
991 EXPORT_SYMBOL(get_task_exe_file
);
994 * get_task_mm - acquire a reference to the task's mm
996 * Returns %NULL if the task has no mm. Checks PF_KTHREAD (meaning
997 * this kernel workthread has transiently adopted a user mm with use_mm,
998 * to do its AIO) is not set and if so returns a reference to it, after
999 * bumping up the use count. User must release the mm via mmput()
1000 * after use. Typically used by /proc and ptrace.
1002 struct mm_struct
*get_task_mm(struct task_struct
*task
)
1004 struct mm_struct
*mm
;
1009 if (task
->flags
& PF_KTHREAD
)
1017 EXPORT_SYMBOL_GPL(get_task_mm
);
1019 struct mm_struct
*mm_access(struct task_struct
*task
, unsigned int mode
)
1021 struct mm_struct
*mm
;
1024 err
= mutex_lock_killable(&task
->signal
->cred_guard_mutex
);
1026 return ERR_PTR(err
);
1028 mm
= get_task_mm(task
);
1029 if (mm
&& mm
!= current
->mm
&&
1030 !ptrace_may_access(task
, mode
)) {
1032 mm
= ERR_PTR(-EACCES
);
1034 mutex_unlock(&task
->signal
->cred_guard_mutex
);
1039 static void complete_vfork_done(struct task_struct
*tsk
)
1041 struct completion
*vfork
;
1044 vfork
= tsk
->vfork_done
;
1045 if (likely(vfork
)) {
1046 tsk
->vfork_done
= NULL
;
1052 static int wait_for_vfork_done(struct task_struct
*child
,
1053 struct completion
*vfork
)
1057 freezer_do_not_count();
1058 killed
= wait_for_completion_killable(vfork
);
1063 child
->vfork_done
= NULL
;
1067 put_task_struct(child
);
1071 /* Please note the differences between mmput and mm_release.
1072 * mmput is called whenever we stop holding onto a mm_struct,
1073 * error success whatever.
1075 * mm_release is called after a mm_struct has been removed
1076 * from the current process.
1078 * This difference is important for error handling, when we
1079 * only half set up a mm_struct for a new process and need to restore
1080 * the old one. Because we mmput the new mm_struct before
1081 * restoring the old one. . .
1082 * Eric Biederman 10 January 1998
1084 void mm_release(struct task_struct
*tsk
, struct mm_struct
*mm
)
1086 /* Get rid of any futexes when releasing the mm */
1088 if (unlikely(tsk
->robust_list
)) {
1089 exit_robust_list(tsk
);
1090 tsk
->robust_list
= NULL
;
1092 #ifdef CONFIG_COMPAT
1093 if (unlikely(tsk
->compat_robust_list
)) {
1094 compat_exit_robust_list(tsk
);
1095 tsk
->compat_robust_list
= NULL
;
1098 if (unlikely(!list_empty(&tsk
->pi_state_list
)))
1099 exit_pi_state_list(tsk
);
1102 uprobe_free_utask(tsk
);
1104 /* Get rid of any cached register state */
1105 deactivate_mm(tsk
, mm
);
1108 * Signal userspace if we're not exiting with a core dump
1109 * because we want to leave the value intact for debugging
1112 if (tsk
->clear_child_tid
) {
1113 if (!(tsk
->signal
->flags
& SIGNAL_GROUP_COREDUMP
) &&
1114 atomic_read(&mm
->mm_users
) > 1) {
1116 * We don't check the error code - if userspace has
1117 * not set up a proper pointer then tough luck.
1119 put_user(0, tsk
->clear_child_tid
);
1120 sys_futex(tsk
->clear_child_tid
, FUTEX_WAKE
,
1123 tsk
->clear_child_tid
= NULL
;
1127 * All done, finally we can wake up parent and return this mm to him.
1128 * Also kthread_stop() uses this completion for synchronization.
1130 if (tsk
->vfork_done
)
1131 complete_vfork_done(tsk
);
1135 * Allocate a new mm structure and copy contents from the
1136 * mm structure of the passed in task structure.
1138 static struct mm_struct
*dup_mm(struct task_struct
*tsk
)
1140 struct mm_struct
*mm
, *oldmm
= current
->mm
;
1147 memcpy(mm
, oldmm
, sizeof(*mm
));
1149 if (!mm_init(mm
, tsk
, mm
->user_ns
))
1152 err
= dup_mmap(mm
, oldmm
);
1156 mm
->hiwater_rss
= get_mm_rss(mm
);
1157 mm
->hiwater_vm
= mm
->total_vm
;
1159 if (mm
->binfmt
&& !try_module_get(mm
->binfmt
->module
))
1165 /* don't put binfmt in mmput, we haven't got module yet */
1173 static int copy_mm(unsigned long clone_flags
, struct task_struct
*tsk
)
1175 struct mm_struct
*mm
, *oldmm
;
1178 tsk
->min_flt
= tsk
->maj_flt
= 0;
1179 tsk
->nvcsw
= tsk
->nivcsw
= 0;
1180 #ifdef CONFIG_DETECT_HUNG_TASK
1181 tsk
->last_switch_count
= tsk
->nvcsw
+ tsk
->nivcsw
;
1185 tsk
->active_mm
= NULL
;
1188 * Are we cloning a kernel thread?
1190 * We need to steal a active VM for that..
1192 oldmm
= current
->mm
;
1196 /* initialize the new vmacache entries */
1197 vmacache_flush(tsk
);
1199 if (clone_flags
& CLONE_VM
) {
1212 tsk
->active_mm
= mm
;
1219 static int copy_fs(unsigned long clone_flags
, struct task_struct
*tsk
)
1221 struct fs_struct
*fs
= current
->fs
;
1222 if (clone_flags
& CLONE_FS
) {
1223 /* tsk->fs is already what we want */
1224 spin_lock(&fs
->lock
);
1226 spin_unlock(&fs
->lock
);
1230 spin_unlock(&fs
->lock
);
1233 tsk
->fs
= copy_fs_struct(fs
);
1239 static int copy_files(unsigned long clone_flags
, struct task_struct
*tsk
)
1241 struct files_struct
*oldf
, *newf
;
1245 * A background process may not have any files ...
1247 oldf
= current
->files
;
1251 if (clone_flags
& CLONE_FILES
) {
1252 atomic_inc(&oldf
->count
);
1256 newf
= dup_fd(oldf
, &error
);
1266 static int copy_io(unsigned long clone_flags
, struct task_struct
*tsk
)
1269 struct io_context
*ioc
= current
->io_context
;
1270 struct io_context
*new_ioc
;
1275 * Share io context with parent, if CLONE_IO is set
1277 if (clone_flags
& CLONE_IO
) {
1279 tsk
->io_context
= ioc
;
1280 } else if (ioprio_valid(ioc
->ioprio
)) {
1281 new_ioc
= get_task_io_context(tsk
, GFP_KERNEL
, NUMA_NO_NODE
);
1282 if (unlikely(!new_ioc
))
1285 new_ioc
->ioprio
= ioc
->ioprio
;
1286 put_io_context(new_ioc
);
1292 static int copy_sighand(unsigned long clone_flags
, struct task_struct
*tsk
)
1294 struct sighand_struct
*sig
;
1296 if (clone_flags
& CLONE_SIGHAND
) {
1297 atomic_inc(¤t
->sighand
->count
);
1300 sig
= kmem_cache_alloc(sighand_cachep
, GFP_KERNEL
);
1301 rcu_assign_pointer(tsk
->sighand
, sig
);
1305 atomic_set(&sig
->count
, 1);
1306 memcpy(sig
->action
, current
->sighand
->action
, sizeof(sig
->action
));
1310 void __cleanup_sighand(struct sighand_struct
*sighand
)
1312 if (atomic_dec_and_test(&sighand
->count
)) {
1313 signalfd_cleanup(sighand
);
1315 * sighand_cachep is SLAB_DESTROY_BY_RCU so we can free it
1316 * without an RCU grace period, see __lock_task_sighand().
1318 kmem_cache_free(sighand_cachep
, sighand
);
1322 #ifdef CONFIG_POSIX_TIMERS
1324 * Initialize POSIX timer handling for a thread group.
1326 static void posix_cpu_timers_init_group(struct signal_struct
*sig
)
1328 unsigned long cpu_limit
;
1330 cpu_limit
= READ_ONCE(sig
->rlim
[RLIMIT_CPU
].rlim_cur
);
1331 if (cpu_limit
!= RLIM_INFINITY
) {
1332 sig
->cputime_expires
.prof_exp
= cpu_limit
* NSEC_PER_SEC
;
1333 sig
->cputimer
.running
= true;
1336 /* The timer lists. */
1337 INIT_LIST_HEAD(&sig
->cpu_timers
[0]);
1338 INIT_LIST_HEAD(&sig
->cpu_timers
[1]);
1339 INIT_LIST_HEAD(&sig
->cpu_timers
[2]);
1342 static inline void posix_cpu_timers_init_group(struct signal_struct
*sig
) { }
1345 static int copy_signal(unsigned long clone_flags
, struct task_struct
*tsk
)
1347 struct signal_struct
*sig
;
1349 if (clone_flags
& CLONE_THREAD
)
1352 sig
= kmem_cache_zalloc(signal_cachep
, GFP_KERNEL
);
1357 sig
->nr_threads
= 1;
1358 atomic_set(&sig
->live
, 1);
1359 atomic_set(&sig
->sigcnt
, 1);
1361 /* list_add(thread_node, thread_head) without INIT_LIST_HEAD() */
1362 sig
->thread_head
= (struct list_head
)LIST_HEAD_INIT(tsk
->thread_node
);
1363 tsk
->thread_node
= (struct list_head
)LIST_HEAD_INIT(sig
->thread_head
);
1365 init_waitqueue_head(&sig
->wait_chldexit
);
1366 sig
->curr_target
= tsk
;
1367 init_sigpending(&sig
->shared_pending
);
1368 seqlock_init(&sig
->stats_lock
);
1369 prev_cputime_init(&sig
->prev_cputime
);
1371 #ifdef CONFIG_POSIX_TIMERS
1372 INIT_LIST_HEAD(&sig
->posix_timers
);
1373 hrtimer_init(&sig
->real_timer
, CLOCK_MONOTONIC
, HRTIMER_MODE_REL
);
1374 sig
->real_timer
.function
= it_real_fn
;
1377 task_lock(current
->group_leader
);
1378 memcpy(sig
->rlim
, current
->signal
->rlim
, sizeof sig
->rlim
);
1379 task_unlock(current
->group_leader
);
1381 posix_cpu_timers_init_group(sig
);
1383 tty_audit_fork(sig
);
1384 sched_autogroup_fork(sig
);
1386 sig
->oom_score_adj
= current
->signal
->oom_score_adj
;
1387 sig
->oom_score_adj_min
= current
->signal
->oom_score_adj_min
;
1389 mutex_init(&sig
->cred_guard_mutex
);
1394 static void copy_seccomp(struct task_struct
*p
)
1396 #ifdef CONFIG_SECCOMP
1398 * Must be called with sighand->lock held, which is common to
1399 * all threads in the group. Holding cred_guard_mutex is not
1400 * needed because this new task is not yet running and cannot
1403 assert_spin_locked(¤t
->sighand
->siglock
);
1405 /* Ref-count the new filter user, and assign it. */
1406 get_seccomp_filter(current
);
1407 p
->seccomp
= current
->seccomp
;
1410 * Explicitly enable no_new_privs here in case it got set
1411 * between the task_struct being duplicated and holding the
1412 * sighand lock. The seccomp state and nnp must be in sync.
1414 if (task_no_new_privs(current
))
1415 task_set_no_new_privs(p
);
1418 * If the parent gained a seccomp mode after copying thread
1419 * flags and between before we held the sighand lock, we have
1420 * to manually enable the seccomp thread flag here.
1422 if (p
->seccomp
.mode
!= SECCOMP_MODE_DISABLED
)
1423 set_tsk_thread_flag(p
, TIF_SECCOMP
);
1427 SYSCALL_DEFINE1(set_tid_address
, int __user
*, tidptr
)
1429 current
->clear_child_tid
= tidptr
;
1431 return task_pid_vnr(current
);
1434 static void rt_mutex_init_task(struct task_struct
*p
)
1436 raw_spin_lock_init(&p
->pi_lock
);
1437 #ifdef CONFIG_RT_MUTEXES
1438 p
->pi_waiters
= RB_ROOT
;
1439 p
->pi_waiters_leftmost
= NULL
;
1440 p
->pi_blocked_on
= NULL
;
1444 #ifdef CONFIG_POSIX_TIMERS
1446 * Initialize POSIX timer handling for a single task.
1448 static void posix_cpu_timers_init(struct task_struct
*tsk
)
1450 tsk
->cputime_expires
.prof_exp
= 0;
1451 tsk
->cputime_expires
.virt_exp
= 0;
1452 tsk
->cputime_expires
.sched_exp
= 0;
1453 INIT_LIST_HEAD(&tsk
->cpu_timers
[0]);
1454 INIT_LIST_HEAD(&tsk
->cpu_timers
[1]);
1455 INIT_LIST_HEAD(&tsk
->cpu_timers
[2]);
1458 static inline void posix_cpu_timers_init(struct task_struct
*tsk
) { }
1462 init_task_pid(struct task_struct
*task
, enum pid_type type
, struct pid
*pid
)
1464 task
->pids
[type
].pid
= pid
;
1468 * This creates a new process as a copy of the old one,
1469 * but does not actually start it yet.
1471 * It copies the registers, and all the appropriate
1472 * parts of the process environment (as per the clone
1473 * flags). The actual kick-off is left to the caller.
1475 static __latent_entropy
struct task_struct
*copy_process(
1476 unsigned long clone_flags
,
1477 unsigned long stack_start
,
1478 unsigned long stack_size
,
1479 int __user
*child_tidptr
,
1486 struct task_struct
*p
;
1488 if ((clone_flags
& (CLONE_NEWNS
|CLONE_FS
)) == (CLONE_NEWNS
|CLONE_FS
))
1489 return ERR_PTR(-EINVAL
);
1491 if ((clone_flags
& (CLONE_NEWUSER
|CLONE_FS
)) == (CLONE_NEWUSER
|CLONE_FS
))
1492 return ERR_PTR(-EINVAL
);
1495 * Thread groups must share signals as well, and detached threads
1496 * can only be started up within the thread group.
1498 if ((clone_flags
& CLONE_THREAD
) && !(clone_flags
& CLONE_SIGHAND
))
1499 return ERR_PTR(-EINVAL
);
1502 * Shared signal handlers imply shared VM. By way of the above,
1503 * thread groups also imply shared VM. Blocking this case allows
1504 * for various simplifications in other code.
1506 if ((clone_flags
& CLONE_SIGHAND
) && !(clone_flags
& CLONE_VM
))
1507 return ERR_PTR(-EINVAL
);
1510 * Siblings of global init remain as zombies on exit since they are
1511 * not reaped by their parent (swapper). To solve this and to avoid
1512 * multi-rooted process trees, prevent global and container-inits
1513 * from creating siblings.
1515 if ((clone_flags
& CLONE_PARENT
) &&
1516 current
->signal
->flags
& SIGNAL_UNKILLABLE
)
1517 return ERR_PTR(-EINVAL
);
1520 * If the new process will be in a different pid or user namespace
1521 * do not allow it to share a thread group with the forking task.
1523 if (clone_flags
& CLONE_THREAD
) {
1524 if ((clone_flags
& (CLONE_NEWUSER
| CLONE_NEWPID
)) ||
1525 (task_active_pid_ns(current
) !=
1526 current
->nsproxy
->pid_ns_for_children
))
1527 return ERR_PTR(-EINVAL
);
1530 retval
= security_task_create(clone_flags
);
1535 p
= dup_task_struct(current
, node
);
1539 ftrace_graph_init_task(p
);
1541 rt_mutex_init_task(p
);
1543 #ifdef CONFIG_PROVE_LOCKING
1544 DEBUG_LOCKS_WARN_ON(!p
->hardirqs_enabled
);
1545 DEBUG_LOCKS_WARN_ON(!p
->softirqs_enabled
);
1548 if (atomic_read(&p
->real_cred
->user
->processes
) >=
1549 task_rlimit(p
, RLIMIT_NPROC
)) {
1550 if (p
->real_cred
->user
!= INIT_USER
&&
1551 !capable(CAP_SYS_RESOURCE
) && !capable(CAP_SYS_ADMIN
))
1554 current
->flags
&= ~PF_NPROC_EXCEEDED
;
1556 retval
= copy_creds(p
, clone_flags
);
1561 * If multiple threads are within copy_process(), then this check
1562 * triggers too late. This doesn't hurt, the check is only there
1563 * to stop root fork bombs.
1566 if (nr_threads
>= max_threads
)
1567 goto bad_fork_cleanup_count
;
1569 delayacct_tsk_init(p
); /* Must remain after dup_task_struct() */
1570 p
->flags
&= ~(PF_SUPERPRIV
| PF_WQ_WORKER
| PF_IDLE
);
1571 p
->flags
|= PF_FORKNOEXEC
;
1572 INIT_LIST_HEAD(&p
->children
);
1573 INIT_LIST_HEAD(&p
->sibling
);
1574 rcu_copy_process(p
);
1575 p
->vfork_done
= NULL
;
1576 spin_lock_init(&p
->alloc_lock
);
1578 init_sigpending(&p
->pending
);
1580 p
->utime
= p
->stime
= p
->gtime
= 0;
1581 #ifdef CONFIG_ARCH_HAS_SCALED_CPUTIME
1582 p
->utimescaled
= p
->stimescaled
= 0;
1584 prev_cputime_init(&p
->prev_cputime
);
1586 #ifdef CONFIG_VIRT_CPU_ACCOUNTING_GEN
1587 seqcount_init(&p
->vtime_seqcount
);
1589 p
->vtime_snap_whence
= VTIME_INACTIVE
;
1592 #if defined(SPLIT_RSS_COUNTING)
1593 memset(&p
->rss_stat
, 0, sizeof(p
->rss_stat
));
1596 p
->default_timer_slack_ns
= current
->timer_slack_ns
;
1598 task_io_accounting_init(&p
->ioac
);
1599 acct_clear_integrals(p
);
1601 posix_cpu_timers_init(p
);
1603 p
->start_time
= ktime_get_ns();
1604 p
->real_start_time
= ktime_get_boot_ns();
1605 p
->io_context
= NULL
;
1606 p
->audit_context
= NULL
;
1609 p
->mempolicy
= mpol_dup(p
->mempolicy
);
1610 if (IS_ERR(p
->mempolicy
)) {
1611 retval
= PTR_ERR(p
->mempolicy
);
1612 p
->mempolicy
= NULL
;
1613 goto bad_fork_cleanup_threadgroup_lock
;
1616 #ifdef CONFIG_CPUSETS
1617 p
->cpuset_mem_spread_rotor
= NUMA_NO_NODE
;
1618 p
->cpuset_slab_spread_rotor
= NUMA_NO_NODE
;
1619 seqcount_init(&p
->mems_allowed_seq
);
1621 #ifdef CONFIG_TRACE_IRQFLAGS
1623 p
->hardirqs_enabled
= 0;
1624 p
->hardirq_enable_ip
= 0;
1625 p
->hardirq_enable_event
= 0;
1626 p
->hardirq_disable_ip
= _THIS_IP_
;
1627 p
->hardirq_disable_event
= 0;
1628 p
->softirqs_enabled
= 1;
1629 p
->softirq_enable_ip
= _THIS_IP_
;
1630 p
->softirq_enable_event
= 0;
1631 p
->softirq_disable_ip
= 0;
1632 p
->softirq_disable_event
= 0;
1633 p
->hardirq_context
= 0;
1634 p
->softirq_context
= 0;
1637 p
->pagefault_disabled
= 0;
1639 #ifdef CONFIG_LOCKDEP
1640 p
->lockdep_depth
= 0; /* no locks held yet */
1641 p
->curr_chain_key
= 0;
1642 p
->lockdep_recursion
= 0;
1645 #ifdef CONFIG_DEBUG_MUTEXES
1646 p
->blocked_on
= NULL
; /* not blocked yet */
1648 #ifdef CONFIG_BCACHE
1649 p
->sequential_io
= 0;
1650 p
->sequential_io_avg
= 0;
1653 /* Perform scheduler related setup. Assign this task to a CPU. */
1654 retval
= sched_fork(clone_flags
, p
);
1656 goto bad_fork_cleanup_policy
;
1658 retval
= perf_event_init_task(p
);
1660 goto bad_fork_cleanup_policy
;
1661 retval
= audit_alloc(p
);
1663 goto bad_fork_cleanup_perf
;
1664 /* copy all the process information */
1666 retval
= copy_semundo(clone_flags
, p
);
1668 goto bad_fork_cleanup_audit
;
1669 retval
= copy_files(clone_flags
, p
);
1671 goto bad_fork_cleanup_semundo
;
1672 retval
= copy_fs(clone_flags
, p
);
1674 goto bad_fork_cleanup_files
;
1675 retval
= copy_sighand(clone_flags
, p
);
1677 goto bad_fork_cleanup_fs
;
1678 retval
= copy_signal(clone_flags
, p
);
1680 goto bad_fork_cleanup_sighand
;
1681 retval
= copy_mm(clone_flags
, p
);
1683 goto bad_fork_cleanup_signal
;
1684 retval
= copy_namespaces(clone_flags
, p
);
1686 goto bad_fork_cleanup_mm
;
1687 retval
= copy_io(clone_flags
, p
);
1689 goto bad_fork_cleanup_namespaces
;
1690 retval
= copy_thread_tls(clone_flags
, stack_start
, stack_size
, p
, tls
);
1692 goto bad_fork_cleanup_io
;
1694 if (pid
!= &init_struct_pid
) {
1695 pid
= alloc_pid(p
->nsproxy
->pid_ns_for_children
);
1697 retval
= PTR_ERR(pid
);
1698 goto bad_fork_cleanup_thread
;
1702 p
->set_child_tid
= (clone_flags
& CLONE_CHILD_SETTID
) ? child_tidptr
: NULL
;
1704 * Clear TID on mm_release()?
1706 p
->clear_child_tid
= (clone_flags
& CLONE_CHILD_CLEARTID
) ? child_tidptr
: NULL
;
1711 p
->robust_list
= NULL
;
1712 #ifdef CONFIG_COMPAT
1713 p
->compat_robust_list
= NULL
;
1715 INIT_LIST_HEAD(&p
->pi_state_list
);
1716 p
->pi_state_cache
= NULL
;
1719 * sigaltstack should be cleared when sharing the same VM
1721 if ((clone_flags
& (CLONE_VM
|CLONE_VFORK
)) == CLONE_VM
)
1725 * Syscall tracing and stepping should be turned off in the
1726 * child regardless of CLONE_PTRACE.
1728 user_disable_single_step(p
);
1729 clear_tsk_thread_flag(p
, TIF_SYSCALL_TRACE
);
1730 #ifdef TIF_SYSCALL_EMU
1731 clear_tsk_thread_flag(p
, TIF_SYSCALL_EMU
);
1733 clear_all_latency_tracing(p
);
1735 /* ok, now we should be set up.. */
1736 p
->pid
= pid_nr(pid
);
1737 if (clone_flags
& CLONE_THREAD
) {
1738 p
->exit_signal
= -1;
1739 p
->group_leader
= current
->group_leader
;
1740 p
->tgid
= current
->tgid
;
1742 if (clone_flags
& CLONE_PARENT
)
1743 p
->exit_signal
= current
->group_leader
->exit_signal
;
1745 p
->exit_signal
= (clone_flags
& CSIGNAL
);
1746 p
->group_leader
= p
;
1751 p
->nr_dirtied_pause
= 128 >> (PAGE_SHIFT
- 10);
1752 p
->dirty_paused_when
= 0;
1754 p
->pdeath_signal
= 0;
1755 INIT_LIST_HEAD(&p
->thread_group
);
1756 p
->task_works
= NULL
;
1758 cgroup_threadgroup_change_begin(current
);
1760 * Ensure that the cgroup subsystem policies allow the new process to be
1761 * forked. It should be noted the the new process's css_set can be changed
1762 * between here and cgroup_post_fork() if an organisation operation is in
1765 retval
= cgroup_can_fork(p
);
1767 goto bad_fork_free_pid
;
1770 * Make it visible to the rest of the system, but dont wake it up yet.
1771 * Need tasklist lock for parent etc handling!
1773 write_lock_irq(&tasklist_lock
);
1775 /* CLONE_PARENT re-uses the old parent */
1776 if (clone_flags
& (CLONE_PARENT
|CLONE_THREAD
)) {
1777 p
->real_parent
= current
->real_parent
;
1778 p
->parent_exec_id
= current
->parent_exec_id
;
1780 p
->real_parent
= current
;
1781 p
->parent_exec_id
= current
->self_exec_id
;
1784 spin_lock(¤t
->sighand
->siglock
);
1787 * Copy seccomp details explicitly here, in case they were changed
1788 * before holding sighand lock.
1793 * Process group and session signals need to be delivered to just the
1794 * parent before the fork or both the parent and the child after the
1795 * fork. Restart if a signal comes in before we add the new process to
1796 * it's process group.
1797 * A fatal signal pending means that current will exit, so the new
1798 * thread can't slip out of an OOM kill (or normal SIGKILL).
1800 recalc_sigpending();
1801 if (signal_pending(current
)) {
1802 spin_unlock(¤t
->sighand
->siglock
);
1803 write_unlock_irq(&tasklist_lock
);
1804 retval
= -ERESTARTNOINTR
;
1805 goto bad_fork_cancel_cgroup
;
1808 if (likely(p
->pid
)) {
1809 ptrace_init_task(p
, (clone_flags
& CLONE_PTRACE
) || trace
);
1811 init_task_pid(p
, PIDTYPE_PID
, pid
);
1812 if (thread_group_leader(p
)) {
1813 init_task_pid(p
, PIDTYPE_PGID
, task_pgrp(current
));
1814 init_task_pid(p
, PIDTYPE_SID
, task_session(current
));
1816 if (is_child_reaper(pid
)) {
1817 ns_of_pid(pid
)->child_reaper
= p
;
1818 p
->signal
->flags
|= SIGNAL_UNKILLABLE
;
1821 p
->signal
->leader_pid
= pid
;
1822 p
->signal
->tty
= tty_kref_get(current
->signal
->tty
);
1824 * Inherit has_child_subreaper flag under the same
1825 * tasklist_lock with adding child to the process tree
1826 * for propagate_has_child_subreaper optimization.
1828 p
->signal
->has_child_subreaper
= p
->real_parent
->signal
->has_child_subreaper
||
1829 p
->real_parent
->signal
->is_child_subreaper
;
1830 list_add_tail(&p
->sibling
, &p
->real_parent
->children
);
1831 list_add_tail_rcu(&p
->tasks
, &init_task
.tasks
);
1832 attach_pid(p
, PIDTYPE_PGID
);
1833 attach_pid(p
, PIDTYPE_SID
);
1834 __this_cpu_inc(process_counts
);
1836 current
->signal
->nr_threads
++;
1837 atomic_inc(¤t
->signal
->live
);
1838 atomic_inc(¤t
->signal
->sigcnt
);
1839 list_add_tail_rcu(&p
->thread_group
,
1840 &p
->group_leader
->thread_group
);
1841 list_add_tail_rcu(&p
->thread_node
,
1842 &p
->signal
->thread_head
);
1844 attach_pid(p
, PIDTYPE_PID
);
1849 spin_unlock(¤t
->sighand
->siglock
);
1850 syscall_tracepoint_update(p
);
1851 write_unlock_irq(&tasklist_lock
);
1853 proc_fork_connector(p
);
1854 cgroup_post_fork(p
);
1855 cgroup_threadgroup_change_end(current
);
1858 trace_task_newtask(p
, clone_flags
);
1859 uprobe_copy_process(p
, clone_flags
);
1863 bad_fork_cancel_cgroup
:
1864 cgroup_cancel_fork(p
);
1866 cgroup_threadgroup_change_end(current
);
1867 if (pid
!= &init_struct_pid
)
1869 bad_fork_cleanup_thread
:
1871 bad_fork_cleanup_io
:
1874 bad_fork_cleanup_namespaces
:
1875 exit_task_namespaces(p
);
1876 bad_fork_cleanup_mm
:
1879 bad_fork_cleanup_signal
:
1880 if (!(clone_flags
& CLONE_THREAD
))
1881 free_signal_struct(p
->signal
);
1882 bad_fork_cleanup_sighand
:
1883 __cleanup_sighand(p
->sighand
);
1884 bad_fork_cleanup_fs
:
1885 exit_fs(p
); /* blocking */
1886 bad_fork_cleanup_files
:
1887 exit_files(p
); /* blocking */
1888 bad_fork_cleanup_semundo
:
1890 bad_fork_cleanup_audit
:
1892 bad_fork_cleanup_perf
:
1893 perf_event_free_task(p
);
1894 bad_fork_cleanup_policy
:
1896 mpol_put(p
->mempolicy
);
1897 bad_fork_cleanup_threadgroup_lock
:
1899 delayacct_tsk_free(p
);
1900 bad_fork_cleanup_count
:
1901 atomic_dec(&p
->cred
->user
->processes
);
1904 p
->state
= TASK_DEAD
;
1908 return ERR_PTR(retval
);
1911 static inline void init_idle_pids(struct pid_link
*links
)
1915 for (type
= PIDTYPE_PID
; type
< PIDTYPE_MAX
; ++type
) {
1916 INIT_HLIST_NODE(&links
[type
].node
); /* not really needed */
1917 links
[type
].pid
= &init_struct_pid
;
1921 struct task_struct
*fork_idle(int cpu
)
1923 struct task_struct
*task
;
1924 task
= copy_process(CLONE_VM
, 0, 0, NULL
, &init_struct_pid
, 0, 0,
1926 if (!IS_ERR(task
)) {
1927 init_idle_pids(task
->pids
);
1928 init_idle(task
, cpu
);
1935 * Ok, this is the main fork-routine.
1937 * It copies the process, and if successful kick-starts
1938 * it and waits for it to finish using the VM if required.
1940 long _do_fork(unsigned long clone_flags
,
1941 unsigned long stack_start
,
1942 unsigned long stack_size
,
1943 int __user
*parent_tidptr
,
1944 int __user
*child_tidptr
,
1947 struct task_struct
*p
;
1952 * Determine whether and which event to report to ptracer. When
1953 * called from kernel_thread or CLONE_UNTRACED is explicitly
1954 * requested, no event is reported; otherwise, report if the event
1955 * for the type of forking is enabled.
1957 if (!(clone_flags
& CLONE_UNTRACED
)) {
1958 if (clone_flags
& CLONE_VFORK
)
1959 trace
= PTRACE_EVENT_VFORK
;
1960 else if ((clone_flags
& CSIGNAL
) != SIGCHLD
)
1961 trace
= PTRACE_EVENT_CLONE
;
1963 trace
= PTRACE_EVENT_FORK
;
1965 if (likely(!ptrace_event_enabled(current
, trace
)))
1969 p
= copy_process(clone_flags
, stack_start
, stack_size
,
1970 child_tidptr
, NULL
, trace
, tls
, NUMA_NO_NODE
);
1971 add_latent_entropy();
1973 * Do this prior waking up the new thread - the thread pointer
1974 * might get invalid after that point, if the thread exits quickly.
1977 struct completion vfork
;
1980 trace_sched_process_fork(current
, p
);
1982 pid
= get_task_pid(p
, PIDTYPE_PID
);
1985 if (clone_flags
& CLONE_PARENT_SETTID
)
1986 put_user(nr
, parent_tidptr
);
1988 if (clone_flags
& CLONE_VFORK
) {
1989 p
->vfork_done
= &vfork
;
1990 init_completion(&vfork
);
1994 wake_up_new_task(p
);
1996 /* forking complete and child started to run, tell ptracer */
1997 if (unlikely(trace
))
1998 ptrace_event_pid(trace
, pid
);
2000 if (clone_flags
& CLONE_VFORK
) {
2001 if (!wait_for_vfork_done(p
, &vfork
))
2002 ptrace_event_pid(PTRACE_EVENT_VFORK_DONE
, pid
);
2012 #ifndef CONFIG_HAVE_COPY_THREAD_TLS
2013 /* For compatibility with architectures that call do_fork directly rather than
2014 * using the syscall entry points below. */
2015 long do_fork(unsigned long clone_flags
,
2016 unsigned long stack_start
,
2017 unsigned long stack_size
,
2018 int __user
*parent_tidptr
,
2019 int __user
*child_tidptr
)
2021 return _do_fork(clone_flags
, stack_start
, stack_size
,
2022 parent_tidptr
, child_tidptr
, 0);
2027 * Create a kernel thread.
2029 pid_t
kernel_thread(int (*fn
)(void *), void *arg
, unsigned long flags
)
2031 return _do_fork(flags
|CLONE_VM
|CLONE_UNTRACED
, (unsigned long)fn
,
2032 (unsigned long)arg
, NULL
, NULL
, 0);
2035 #ifdef __ARCH_WANT_SYS_FORK
2036 SYSCALL_DEFINE0(fork
)
2039 return _do_fork(SIGCHLD
, 0, 0, NULL
, NULL
, 0);
2041 /* can not support in nommu mode */
2047 #ifdef __ARCH_WANT_SYS_VFORK
2048 SYSCALL_DEFINE0(vfork
)
2050 return _do_fork(CLONE_VFORK
| CLONE_VM
| SIGCHLD
, 0,
2055 #ifdef __ARCH_WANT_SYS_CLONE
2056 #ifdef CONFIG_CLONE_BACKWARDS
2057 SYSCALL_DEFINE5(clone
, unsigned long, clone_flags
, unsigned long, newsp
,
2058 int __user
*, parent_tidptr
,
2060 int __user
*, child_tidptr
)
2061 #elif defined(CONFIG_CLONE_BACKWARDS2)
2062 SYSCALL_DEFINE5(clone
, unsigned long, newsp
, unsigned long, clone_flags
,
2063 int __user
*, parent_tidptr
,
2064 int __user
*, child_tidptr
,
2066 #elif defined(CONFIG_CLONE_BACKWARDS3)
2067 SYSCALL_DEFINE6(clone
, unsigned long, clone_flags
, unsigned long, newsp
,
2069 int __user
*, parent_tidptr
,
2070 int __user
*, child_tidptr
,
2073 SYSCALL_DEFINE5(clone
, unsigned long, clone_flags
, unsigned long, newsp
,
2074 int __user
*, parent_tidptr
,
2075 int __user
*, child_tidptr
,
2079 return _do_fork(clone_flags
, newsp
, 0, parent_tidptr
, child_tidptr
, tls
);
2083 void walk_process_tree(struct task_struct
*top
, proc_visitor visitor
, void *data
)
2085 struct task_struct
*leader
, *parent
, *child
;
2088 read_lock(&tasklist_lock
);
2089 leader
= top
= top
->group_leader
;
2091 for_each_thread(leader
, parent
) {
2092 list_for_each_entry(child
, &parent
->children
, sibling
) {
2093 res
= visitor(child
, data
);
2105 if (leader
!= top
) {
2107 parent
= child
->real_parent
;
2108 leader
= parent
->group_leader
;
2112 read_unlock(&tasklist_lock
);
2115 #ifndef ARCH_MIN_MMSTRUCT_ALIGN
2116 #define ARCH_MIN_MMSTRUCT_ALIGN 0
2119 static void sighand_ctor(void *data
)
2121 struct sighand_struct
*sighand
= data
;
2123 spin_lock_init(&sighand
->siglock
);
2124 init_waitqueue_head(&sighand
->signalfd_wqh
);
2127 void __init
proc_caches_init(void)
2129 sighand_cachep
= kmem_cache_create("sighand_cache",
2130 sizeof(struct sighand_struct
), 0,
2131 SLAB_HWCACHE_ALIGN
|SLAB_PANIC
|SLAB_DESTROY_BY_RCU
|
2132 SLAB_NOTRACK
|SLAB_ACCOUNT
, sighand_ctor
);
2133 signal_cachep
= kmem_cache_create("signal_cache",
2134 sizeof(struct signal_struct
), 0,
2135 SLAB_HWCACHE_ALIGN
|SLAB_PANIC
|SLAB_NOTRACK
|SLAB_ACCOUNT
,
2137 files_cachep
= kmem_cache_create("files_cache",
2138 sizeof(struct files_struct
), 0,
2139 SLAB_HWCACHE_ALIGN
|SLAB_PANIC
|SLAB_NOTRACK
|SLAB_ACCOUNT
,
2141 fs_cachep
= kmem_cache_create("fs_cache",
2142 sizeof(struct fs_struct
), 0,
2143 SLAB_HWCACHE_ALIGN
|SLAB_PANIC
|SLAB_NOTRACK
|SLAB_ACCOUNT
,
2146 * FIXME! The "sizeof(struct mm_struct)" currently includes the
2147 * whole struct cpumask for the OFFSTACK case. We could change
2148 * this to *only* allocate as much of it as required by the
2149 * maximum number of CPU's we can ever have. The cpumask_allocation
2150 * is at the end of the structure, exactly for that reason.
2152 mm_cachep
= kmem_cache_create("mm_struct",
2153 sizeof(struct mm_struct
), ARCH_MIN_MMSTRUCT_ALIGN
,
2154 SLAB_HWCACHE_ALIGN
|SLAB_PANIC
|SLAB_NOTRACK
|SLAB_ACCOUNT
,
2156 vm_area_cachep
= KMEM_CACHE(vm_area_struct
, SLAB_PANIC
|SLAB_ACCOUNT
);
2158 nsproxy_cache_init();
2162 * Check constraints on flags passed to the unshare system call.
2164 static int check_unshare_flags(unsigned long unshare_flags
)
2166 if (unshare_flags
& ~(CLONE_THREAD
|CLONE_FS
|CLONE_NEWNS
|CLONE_SIGHAND
|
2167 CLONE_VM
|CLONE_FILES
|CLONE_SYSVSEM
|
2168 CLONE_NEWUTS
|CLONE_NEWIPC
|CLONE_NEWNET
|
2169 CLONE_NEWUSER
|CLONE_NEWPID
|CLONE_NEWCGROUP
))
2172 * Not implemented, but pretend it works if there is nothing
2173 * to unshare. Note that unsharing the address space or the
2174 * signal handlers also need to unshare the signal queues (aka
2177 if (unshare_flags
& (CLONE_THREAD
| CLONE_SIGHAND
| CLONE_VM
)) {
2178 if (!thread_group_empty(current
))
2181 if (unshare_flags
& (CLONE_SIGHAND
| CLONE_VM
)) {
2182 if (atomic_read(¤t
->sighand
->count
) > 1)
2185 if (unshare_flags
& CLONE_VM
) {
2186 if (!current_is_single_threaded())
2194 * Unshare the filesystem structure if it is being shared
2196 static int unshare_fs(unsigned long unshare_flags
, struct fs_struct
**new_fsp
)
2198 struct fs_struct
*fs
= current
->fs
;
2200 if (!(unshare_flags
& CLONE_FS
) || !fs
)
2203 /* don't need lock here; in the worst case we'll do useless copy */
2207 *new_fsp
= copy_fs_struct(fs
);
2215 * Unshare file descriptor table if it is being shared
2217 static int unshare_fd(unsigned long unshare_flags
, struct files_struct
**new_fdp
)
2219 struct files_struct
*fd
= current
->files
;
2222 if ((unshare_flags
& CLONE_FILES
) &&
2223 (fd
&& atomic_read(&fd
->count
) > 1)) {
2224 *new_fdp
= dup_fd(fd
, &error
);
2233 * unshare allows a process to 'unshare' part of the process
2234 * context which was originally shared using clone. copy_*
2235 * functions used by do_fork() cannot be used here directly
2236 * because they modify an inactive task_struct that is being
2237 * constructed. Here we are modifying the current, active,
2240 SYSCALL_DEFINE1(unshare
, unsigned long, unshare_flags
)
2242 struct fs_struct
*fs
, *new_fs
= NULL
;
2243 struct files_struct
*fd
, *new_fd
= NULL
;
2244 struct cred
*new_cred
= NULL
;
2245 struct nsproxy
*new_nsproxy
= NULL
;
2250 * If unsharing a user namespace must also unshare the thread group
2251 * and unshare the filesystem root and working directories.
2253 if (unshare_flags
& CLONE_NEWUSER
)
2254 unshare_flags
|= CLONE_THREAD
| CLONE_FS
;
2256 * If unsharing vm, must also unshare signal handlers.
2258 if (unshare_flags
& CLONE_VM
)
2259 unshare_flags
|= CLONE_SIGHAND
;
2261 * If unsharing a signal handlers, must also unshare the signal queues.
2263 if (unshare_flags
& CLONE_SIGHAND
)
2264 unshare_flags
|= CLONE_THREAD
;
2266 * If unsharing namespace, must also unshare filesystem information.
2268 if (unshare_flags
& CLONE_NEWNS
)
2269 unshare_flags
|= CLONE_FS
;
2271 err
= check_unshare_flags(unshare_flags
);
2273 goto bad_unshare_out
;
2275 * CLONE_NEWIPC must also detach from the undolist: after switching
2276 * to a new ipc namespace, the semaphore arrays from the old
2277 * namespace are unreachable.
2279 if (unshare_flags
& (CLONE_NEWIPC
|CLONE_SYSVSEM
))
2281 err
= unshare_fs(unshare_flags
, &new_fs
);
2283 goto bad_unshare_out
;
2284 err
= unshare_fd(unshare_flags
, &new_fd
);
2286 goto bad_unshare_cleanup_fs
;
2287 err
= unshare_userns(unshare_flags
, &new_cred
);
2289 goto bad_unshare_cleanup_fd
;
2290 err
= unshare_nsproxy_namespaces(unshare_flags
, &new_nsproxy
,
2293 goto bad_unshare_cleanup_cred
;
2295 if (new_fs
|| new_fd
|| do_sysvsem
|| new_cred
|| new_nsproxy
) {
2298 * CLONE_SYSVSEM is equivalent to sys_exit().
2302 if (unshare_flags
& CLONE_NEWIPC
) {
2303 /* Orphan segments in old ns (see sem above). */
2305 shm_init_task(current
);
2309 switch_task_namespaces(current
, new_nsproxy
);
2315 spin_lock(&fs
->lock
);
2316 current
->fs
= new_fs
;
2321 spin_unlock(&fs
->lock
);
2325 fd
= current
->files
;
2326 current
->files
= new_fd
;
2330 task_unlock(current
);
2333 /* Install the new user namespace */
2334 commit_creds(new_cred
);
2339 bad_unshare_cleanup_cred
:
2342 bad_unshare_cleanup_fd
:
2344 put_files_struct(new_fd
);
2346 bad_unshare_cleanup_fs
:
2348 free_fs_struct(new_fs
);
2355 * Helper to unshare the files of the current task.
2356 * We don't want to expose copy_files internals to
2357 * the exec layer of the kernel.
2360 int unshare_files(struct files_struct
**displaced
)
2362 struct task_struct
*task
= current
;
2363 struct files_struct
*copy
= NULL
;
2366 error
= unshare_fd(CLONE_FILES
, ©
);
2367 if (error
|| !copy
) {
2371 *displaced
= task
->files
;
2378 int sysctl_max_threads(struct ctl_table
*table
, int write
,
2379 void __user
*buffer
, size_t *lenp
, loff_t
*ppos
)
2383 int threads
= max_threads
;
2384 int min
= MIN_THREADS
;
2385 int max
= MAX_THREADS
;
2392 ret
= proc_dointvec_minmax(&t
, write
, buffer
, lenp
, ppos
);
2396 set_max_threads(threads
);