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