blkcg: Make blkg_root_lookup() work for queues in bypass mode
[linux] / 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
95 #include <asm/pgtable.h>
96 #include <asm/pgalloc.h>
97 #include <linux/uaccess.h>
98 #include <asm/mmu_context.h>
99 #include <asm/cacheflush.h>
100 #include <asm/tlbflush.h>
101
102 #include <trace/events/sched.h>
103
104 #define CREATE_TRACE_POINTS
105 #include <trace/events/task.h>
106
107 /*
108  * Minimum number of threads to boot the kernel
109  */
110 #define MIN_THREADS 20
111
112 /*
113  * Maximum number of threads
114  */
115 #define MAX_THREADS FUTEX_TID_MASK
116
117 /*
118  * Protected counters by write_lock_irq(&tasklist_lock)
119  */
120 unsigned long total_forks;      /* Handle normal Linux uptimes. */
121 int nr_threads;                 /* The idle threads do not count.. */
122
123 int max_threads;                /* tunable limit on nr_threads */
124
125 DEFINE_PER_CPU(unsigned long, process_counts) = 0;
126
127 __cacheline_aligned DEFINE_RWLOCK(tasklist_lock);  /* outer */
128
129 #ifdef CONFIG_PROVE_RCU
130 int lockdep_tasklist_lock_is_held(void)
131 {
132         return lockdep_is_held(&tasklist_lock);
133 }
134 EXPORT_SYMBOL_GPL(lockdep_tasklist_lock_is_held);
135 #endif /* #ifdef CONFIG_PROVE_RCU */
136
137 int nr_processes(void)
138 {
139         int cpu;
140         int total = 0;
141
142         for_each_possible_cpu(cpu)
143                 total += per_cpu(process_counts, cpu);
144
145         return total;
146 }
147
148 void __weak arch_release_task_struct(struct task_struct *tsk)
149 {
150 }
151
152 #ifndef CONFIG_ARCH_TASK_STRUCT_ALLOCATOR
153 static struct kmem_cache *task_struct_cachep;
154
155 static inline struct task_struct *alloc_task_struct_node(int node)
156 {
157         return kmem_cache_alloc_node(task_struct_cachep, GFP_KERNEL, node);
158 }
159
160 static inline void free_task_struct(struct task_struct *tsk)
161 {
162         kmem_cache_free(task_struct_cachep, tsk);
163 }
164 #endif
165
166 void __weak arch_release_thread_stack(unsigned long *stack)
167 {
168 }
169
170 #ifndef CONFIG_ARCH_THREAD_STACK_ALLOCATOR
171
172 /*
173  * Allocate pages if THREAD_SIZE is >= PAGE_SIZE, otherwise use a
174  * kmemcache based allocator.
175  */
176 # if THREAD_SIZE >= PAGE_SIZE || defined(CONFIG_VMAP_STACK)
177
178 #ifdef CONFIG_VMAP_STACK
179 /*
180  * vmalloc() is a bit slow, and calling vfree() enough times will force a TLB
181  * flush.  Try to minimize the number of calls by caching stacks.
182  */
183 #define NR_CACHED_STACKS 2
184 static DEFINE_PER_CPU(struct vm_struct *, cached_stacks[NR_CACHED_STACKS]);
185
186 static int free_vm_stack_cache(unsigned int cpu)
187 {
188         struct vm_struct **cached_vm_stacks = per_cpu_ptr(cached_stacks, cpu);
189         int i;
190
191         for (i = 0; i < NR_CACHED_STACKS; i++) {
192                 struct vm_struct *vm_stack = cached_vm_stacks[i];
193
194                 if (!vm_stack)
195                         continue;
196
197                 vfree(vm_stack->addr);
198                 cached_vm_stacks[i] = NULL;
199         }
200
201         return 0;
202 }
203 #endif
204
205 static unsigned long *alloc_thread_stack_node(struct task_struct *tsk, int node)
206 {
207 #ifdef CONFIG_VMAP_STACK
208         void *stack;
209         int i;
210
211         for (i = 0; i < NR_CACHED_STACKS; i++) {
212                 struct vm_struct *s;
213
214                 s = this_cpu_xchg(cached_stacks[i], NULL);
215
216                 if (!s)
217                         continue;
218
219                 /* Clear stale pointers from reused stack. */
220                 memset(s->addr, 0, THREAD_SIZE);
221
222                 tsk->stack_vm_area = s;
223                 return s->addr;
224         }
225
226         stack = __vmalloc_node_range(THREAD_SIZE, THREAD_ALIGN,
227                                      VMALLOC_START, VMALLOC_END,
228                                      THREADINFO_GFP,
229                                      PAGE_KERNEL,
230                                      0, node, __builtin_return_address(0));
231
232         /*
233          * We can't call find_vm_area() in interrupt context, and
234          * free_thread_stack() can be called in interrupt context,
235          * so cache the vm_struct.
236          */
237         if (stack)
238                 tsk->stack_vm_area = find_vm_area(stack);
239         return stack;
240 #else
241         struct page *page = alloc_pages_node(node, THREADINFO_GFP,
242                                              THREAD_SIZE_ORDER);
243
244         return page ? page_address(page) : NULL;
245 #endif
246 }
247
248 static inline void free_thread_stack(struct task_struct *tsk)
249 {
250 #ifdef CONFIG_VMAP_STACK
251         if (task_stack_vm_area(tsk)) {
252                 int i;
253
254                 for (i = 0; i < NR_CACHED_STACKS; i++) {
255                         if (this_cpu_cmpxchg(cached_stacks[i],
256                                         NULL, tsk->stack_vm_area) != NULL)
257                                 continue;
258
259                         return;
260                 }
261
262                 vfree_atomic(tsk->stack);
263                 return;
264         }
265 #endif
266
267         __free_pages(virt_to_page(tsk->stack), THREAD_SIZE_ORDER);
268 }
269 # else
270 static struct kmem_cache *thread_stack_cache;
271
272 static unsigned long *alloc_thread_stack_node(struct task_struct *tsk,
273                                                   int node)
274 {
275         return kmem_cache_alloc_node(thread_stack_cache, THREADINFO_GFP, node);
276 }
277
278 static void free_thread_stack(struct task_struct *tsk)
279 {
280         kmem_cache_free(thread_stack_cache, tsk->stack);
281 }
282
283 void thread_stack_cache_init(void)
284 {
285         thread_stack_cache = kmem_cache_create_usercopy("thread_stack",
286                                         THREAD_SIZE, THREAD_SIZE, 0, 0,
287                                         THREAD_SIZE, NULL);
288         BUG_ON(thread_stack_cache == NULL);
289 }
290 # endif
291 #endif
292
293 /* SLAB cache for signal_struct structures (tsk->signal) */
294 static struct kmem_cache *signal_cachep;
295
296 /* SLAB cache for sighand_struct structures (tsk->sighand) */
297 struct kmem_cache *sighand_cachep;
298
299 /* SLAB cache for files_struct structures (tsk->files) */
300 struct kmem_cache *files_cachep;
301
302 /* SLAB cache for fs_struct structures (tsk->fs) */
303 struct kmem_cache *fs_cachep;
304
305 /* SLAB cache for vm_area_struct structures */
306 static struct kmem_cache *vm_area_cachep;
307
308 /* SLAB cache for mm_struct structures (tsk->mm) */
309 static struct kmem_cache *mm_cachep;
310
311 struct vm_area_struct *vm_area_alloc(struct mm_struct *mm)
312 {
313         struct vm_area_struct *vma = kmem_cache_zalloc(vm_area_cachep, GFP_KERNEL);
314
315         if (vma) {
316                 vma->vm_mm = mm;
317                 INIT_LIST_HEAD(&vma->anon_vma_chain);
318         }
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         return tsk;
877
878 free_stack:
879         free_thread_stack(tsk);
880 free_tsk:
881         free_task_struct(tsk);
882         return NULL;
883 }
884
885 __cacheline_aligned_in_smp DEFINE_SPINLOCK(mmlist_lock);
886
887 static unsigned long default_dump_filter = MMF_DUMP_FILTER_DEFAULT;
888
889 static int __init coredump_filter_setup(char *s)
890 {
891         default_dump_filter =
892                 (simple_strtoul(s, NULL, 0) << MMF_DUMP_FILTER_SHIFT) &
893                 MMF_DUMP_FILTER_MASK;
894         return 1;
895 }
896
897 __setup("coredump_filter=", coredump_filter_setup);
898
899 #include <linux/init_task.h>
900
901 static void mm_init_aio(struct mm_struct *mm)
902 {
903 #ifdef CONFIG_AIO
904         spin_lock_init(&mm->ioctx_lock);
905         mm->ioctx_table = NULL;
906 #endif
907 }
908
909 static void mm_init_owner(struct mm_struct *mm, struct task_struct *p)
910 {
911 #ifdef CONFIG_MEMCG
912         mm->owner = p;
913 #endif
914 }
915
916 static void mm_init_uprobes_state(struct mm_struct *mm)
917 {
918 #ifdef CONFIG_UPROBES
919         mm->uprobes_state.xol_area = NULL;
920 #endif
921 }
922
923 static struct mm_struct *mm_init(struct mm_struct *mm, struct task_struct *p,
924         struct user_namespace *user_ns)
925 {
926         mm->mmap = NULL;
927         mm->mm_rb = RB_ROOT;
928         mm->vmacache_seqnum = 0;
929         atomic_set(&mm->mm_users, 1);
930         atomic_set(&mm->mm_count, 1);
931         init_rwsem(&mm->mmap_sem);
932         INIT_LIST_HEAD(&mm->mmlist);
933         mm->core_state = NULL;
934         mm_pgtables_bytes_init(mm);
935         mm->map_count = 0;
936         mm->locked_vm = 0;
937         mm->pinned_vm = 0;
938         memset(&mm->rss_stat, 0, sizeof(mm->rss_stat));
939         spin_lock_init(&mm->page_table_lock);
940         spin_lock_init(&mm->arg_lock);
941         mm_init_cpumask(mm);
942         mm_init_aio(mm);
943         mm_init_owner(mm, p);
944         RCU_INIT_POINTER(mm->exe_file, NULL);
945         mmu_notifier_mm_init(mm);
946         hmm_mm_init(mm);
947         init_tlb_flush_pending(mm);
948 #if defined(CONFIG_TRANSPARENT_HUGEPAGE) && !USE_SPLIT_PMD_PTLOCKS
949         mm->pmd_huge_pte = NULL;
950 #endif
951         mm_init_uprobes_state(mm);
952
953         if (current->mm) {
954                 mm->flags = current->mm->flags & MMF_INIT_MASK;
955                 mm->def_flags = current->mm->def_flags & VM_INIT_DEF_MASK;
956         } else {
957                 mm->flags = default_dump_filter;
958                 mm->def_flags = 0;
959         }
960
961         if (mm_alloc_pgd(mm))
962                 goto fail_nopgd;
963
964         if (init_new_context(p, mm))
965                 goto fail_nocontext;
966
967         mm->user_ns = get_user_ns(user_ns);
968         return mm;
969
970 fail_nocontext:
971         mm_free_pgd(mm);
972 fail_nopgd:
973         free_mm(mm);
974         return NULL;
975 }
976
977 /*
978  * Allocate and initialize an mm_struct.
979  */
980 struct mm_struct *mm_alloc(void)
981 {
982         struct mm_struct *mm;
983
984         mm = allocate_mm();
985         if (!mm)
986                 return NULL;
987
988         memset(mm, 0, sizeof(*mm));
989         return mm_init(mm, current, current_user_ns());
990 }
991
992 static inline void __mmput(struct mm_struct *mm)
993 {
994         VM_BUG_ON(atomic_read(&mm->mm_users));
995
996         uprobe_clear_state(mm);
997         exit_aio(mm);
998         ksm_exit(mm);
999         khugepaged_exit(mm); /* must run before exit_mmap */
1000         exit_mmap(mm);
1001         mm_put_huge_zero_page(mm);
1002         set_mm_exe_file(mm, NULL);
1003         if (!list_empty(&mm->mmlist)) {
1004                 spin_lock(&mmlist_lock);
1005                 list_del(&mm->mmlist);
1006                 spin_unlock(&mmlist_lock);
1007         }
1008         if (mm->binfmt)
1009                 module_put(mm->binfmt->module);
1010         mmdrop(mm);
1011 }
1012
1013 /*
1014  * Decrement the use count and release all resources for an mm.
1015  */
1016 void mmput(struct mm_struct *mm)
1017 {
1018         might_sleep();
1019
1020         if (atomic_dec_and_test(&mm->mm_users))
1021                 __mmput(mm);
1022 }
1023 EXPORT_SYMBOL_GPL(mmput);
1024
1025 #ifdef CONFIG_MMU
1026 static void mmput_async_fn(struct work_struct *work)
1027 {
1028         struct mm_struct *mm = container_of(work, struct mm_struct,
1029                                             async_put_work);
1030
1031         __mmput(mm);
1032 }
1033
1034 void mmput_async(struct mm_struct *mm)
1035 {
1036         if (atomic_dec_and_test(&mm->mm_users)) {
1037                 INIT_WORK(&mm->async_put_work, mmput_async_fn);
1038                 schedule_work(&mm->async_put_work);
1039         }
1040 }
1041 #endif
1042
1043 /**
1044  * set_mm_exe_file - change a reference to the mm's executable file
1045  *
1046  * This changes mm's executable file (shown as symlink /proc/[pid]/exe).
1047  *
1048  * Main users are mmput() and sys_execve(). Callers prevent concurrent
1049  * invocations: in mmput() nobody alive left, in execve task is single
1050  * threaded. sys_prctl(PR_SET_MM_MAP/EXE_FILE) also needs to set the
1051  * mm->exe_file, but does so without using set_mm_exe_file() in order
1052  * to do avoid the need for any locks.
1053  */
1054 void set_mm_exe_file(struct mm_struct *mm, struct file *new_exe_file)
1055 {
1056         struct file *old_exe_file;
1057
1058         /*
1059          * It is safe to dereference the exe_file without RCU as
1060          * this function is only called if nobody else can access
1061          * this mm -- see comment above for justification.
1062          */
1063         old_exe_file = rcu_dereference_raw(mm->exe_file);
1064
1065         if (new_exe_file)
1066                 get_file(new_exe_file);
1067         rcu_assign_pointer(mm->exe_file, new_exe_file);
1068         if (old_exe_file)
1069                 fput(old_exe_file);
1070 }
1071
1072 /**
1073  * get_mm_exe_file - acquire a reference to the mm's executable file
1074  *
1075  * Returns %NULL if mm has no associated executable file.
1076  * User must release file via fput().
1077  */
1078 struct file *get_mm_exe_file(struct mm_struct *mm)
1079 {
1080         struct file *exe_file;
1081
1082         rcu_read_lock();
1083         exe_file = rcu_dereference(mm->exe_file);
1084         if (exe_file && !get_file_rcu(exe_file))
1085                 exe_file = NULL;
1086         rcu_read_unlock();
1087         return exe_file;
1088 }
1089 EXPORT_SYMBOL(get_mm_exe_file);
1090
1091 /**
1092  * get_task_exe_file - acquire a reference to the task's executable file
1093  *
1094  * Returns %NULL if task's mm (if any) has no associated executable file or
1095  * this is a kernel thread with borrowed mm (see the comment above get_task_mm).
1096  * User must release file via fput().
1097  */
1098 struct file *get_task_exe_file(struct task_struct *task)
1099 {
1100         struct file *exe_file = NULL;
1101         struct mm_struct *mm;
1102
1103         task_lock(task);
1104         mm = task->mm;
1105         if (mm) {
1106                 if (!(task->flags & PF_KTHREAD))
1107                         exe_file = get_mm_exe_file(mm);
1108         }
1109         task_unlock(task);
1110         return exe_file;
1111 }
1112 EXPORT_SYMBOL(get_task_exe_file);
1113
1114 /**
1115  * get_task_mm - acquire a reference to the task's mm
1116  *
1117  * Returns %NULL if the task has no mm.  Checks PF_KTHREAD (meaning
1118  * this kernel workthread has transiently adopted a user mm with use_mm,
1119  * to do its AIO) is not set and if so returns a reference to it, after
1120  * bumping up the use count.  User must release the mm via mmput()
1121  * after use.  Typically used by /proc and ptrace.
1122  */
1123 struct mm_struct *get_task_mm(struct task_struct *task)
1124 {
1125         struct mm_struct *mm;
1126
1127         task_lock(task);
1128         mm = task->mm;
1129         if (mm) {
1130                 if (task->flags & PF_KTHREAD)
1131                         mm = NULL;
1132                 else
1133                         mmget(mm);
1134         }
1135         task_unlock(task);
1136         return mm;
1137 }
1138 EXPORT_SYMBOL_GPL(get_task_mm);
1139
1140 struct mm_struct *mm_access(struct task_struct *task, unsigned int mode)
1141 {
1142         struct mm_struct *mm;
1143         int err;
1144
1145         err =  mutex_lock_killable(&task->signal->cred_guard_mutex);
1146         if (err)
1147                 return ERR_PTR(err);
1148
1149         mm = get_task_mm(task);
1150         if (mm && mm != current->mm &&
1151                         !ptrace_may_access(task, mode)) {
1152                 mmput(mm);
1153                 mm = ERR_PTR(-EACCES);
1154         }
1155         mutex_unlock(&task->signal->cred_guard_mutex);
1156
1157         return mm;
1158 }
1159
1160 static void complete_vfork_done(struct task_struct *tsk)
1161 {
1162         struct completion *vfork;
1163
1164         task_lock(tsk);
1165         vfork = tsk->vfork_done;
1166         if (likely(vfork)) {
1167                 tsk->vfork_done = NULL;
1168                 complete(vfork);
1169         }
1170         task_unlock(tsk);
1171 }
1172
1173 static int wait_for_vfork_done(struct task_struct *child,
1174                                 struct completion *vfork)
1175 {
1176         int killed;
1177
1178         freezer_do_not_count();
1179         killed = wait_for_completion_killable(vfork);
1180         freezer_count();
1181
1182         if (killed) {
1183                 task_lock(child);
1184                 child->vfork_done = NULL;
1185                 task_unlock(child);
1186         }
1187
1188         put_task_struct(child);
1189         return killed;
1190 }
1191
1192 /* Please note the differences between mmput and mm_release.
1193  * mmput is called whenever we stop holding onto a mm_struct,
1194  * error success whatever.
1195  *
1196  * mm_release is called after a mm_struct has been removed
1197  * from the current process.
1198  *
1199  * This difference is important for error handling, when we
1200  * only half set up a mm_struct for a new process and need to restore
1201  * the old one.  Because we mmput the new mm_struct before
1202  * restoring the old one. . .
1203  * Eric Biederman 10 January 1998
1204  */
1205 void mm_release(struct task_struct *tsk, struct mm_struct *mm)
1206 {
1207         /* Get rid of any futexes when releasing the mm */
1208 #ifdef CONFIG_FUTEX
1209         if (unlikely(tsk->robust_list)) {
1210                 exit_robust_list(tsk);
1211                 tsk->robust_list = NULL;
1212         }
1213 #ifdef CONFIG_COMPAT
1214         if (unlikely(tsk->compat_robust_list)) {
1215                 compat_exit_robust_list(tsk);
1216                 tsk->compat_robust_list = NULL;
1217         }
1218 #endif
1219         if (unlikely(!list_empty(&tsk->pi_state_list)))
1220                 exit_pi_state_list(tsk);
1221 #endif
1222
1223         uprobe_free_utask(tsk);
1224
1225         /* Get rid of any cached register state */
1226         deactivate_mm(tsk, mm);
1227
1228         /*
1229          * Signal userspace if we're not exiting with a core dump
1230          * because we want to leave the value intact for debugging
1231          * purposes.
1232          */
1233         if (tsk->clear_child_tid) {
1234                 if (!(tsk->signal->flags & SIGNAL_GROUP_COREDUMP) &&
1235                     atomic_read(&mm->mm_users) > 1) {
1236                         /*
1237                          * We don't check the error code - if userspace has
1238                          * not set up a proper pointer then tough luck.
1239                          */
1240                         put_user(0, tsk->clear_child_tid);
1241                         do_futex(tsk->clear_child_tid, FUTEX_WAKE,
1242                                         1, NULL, NULL, 0, 0);
1243                 }
1244                 tsk->clear_child_tid = NULL;
1245         }
1246
1247         /*
1248          * All done, finally we can wake up parent and return this mm to him.
1249          * Also kthread_stop() uses this completion for synchronization.
1250          */
1251         if (tsk->vfork_done)
1252                 complete_vfork_done(tsk);
1253 }
1254
1255 /*
1256  * Allocate a new mm structure and copy contents from the
1257  * mm structure of the passed in task structure.
1258  */
1259 static struct mm_struct *dup_mm(struct task_struct *tsk)
1260 {
1261         struct mm_struct *mm, *oldmm = current->mm;
1262         int err;
1263
1264         mm = allocate_mm();
1265         if (!mm)
1266                 goto fail_nomem;
1267
1268         memcpy(mm, oldmm, sizeof(*mm));
1269
1270         if (!mm_init(mm, tsk, mm->user_ns))
1271                 goto fail_nomem;
1272
1273         err = dup_mmap(mm, oldmm);
1274         if (err)
1275                 goto free_pt;
1276
1277         mm->hiwater_rss = get_mm_rss(mm);
1278         mm->hiwater_vm = mm->total_vm;
1279
1280         if (mm->binfmt && !try_module_get(mm->binfmt->module))
1281                 goto free_pt;
1282
1283         return mm;
1284
1285 free_pt:
1286         /* don't put binfmt in mmput, we haven't got module yet */
1287         mm->binfmt = NULL;
1288         mmput(mm);
1289
1290 fail_nomem:
1291         return NULL;
1292 }
1293
1294 static int copy_mm(unsigned long clone_flags, struct task_struct *tsk)
1295 {
1296         struct mm_struct *mm, *oldmm;
1297         int retval;
1298
1299         tsk->min_flt = tsk->maj_flt = 0;
1300         tsk->nvcsw = tsk->nivcsw = 0;
1301 #ifdef CONFIG_DETECT_HUNG_TASK
1302         tsk->last_switch_count = tsk->nvcsw + tsk->nivcsw;
1303 #endif
1304
1305         tsk->mm = NULL;
1306         tsk->active_mm = NULL;
1307
1308         /*
1309          * Are we cloning a kernel thread?
1310          *
1311          * We need to steal a active VM for that..
1312          */
1313         oldmm = current->mm;
1314         if (!oldmm)
1315                 return 0;
1316
1317         /* initialize the new vmacache entries */
1318         vmacache_flush(tsk);
1319
1320         if (clone_flags & CLONE_VM) {
1321                 mmget(oldmm);
1322                 mm = oldmm;
1323                 goto good_mm;
1324         }
1325
1326         retval = -ENOMEM;
1327         mm = dup_mm(tsk);
1328         if (!mm)
1329                 goto fail_nomem;
1330
1331 good_mm:
1332         tsk->mm = mm;
1333         tsk->active_mm = mm;
1334         return 0;
1335
1336 fail_nomem:
1337         return retval;
1338 }
1339
1340 static int copy_fs(unsigned long clone_flags, struct task_struct *tsk)
1341 {
1342         struct fs_struct *fs = current->fs;
1343         if (clone_flags & CLONE_FS) {
1344                 /* tsk->fs is already what we want */
1345                 spin_lock(&fs->lock);
1346                 if (fs->in_exec) {
1347                         spin_unlock(&fs->lock);
1348                         return -EAGAIN;
1349                 }
1350                 fs->users++;
1351                 spin_unlock(&fs->lock);
1352                 return 0;
1353         }
1354         tsk->fs = copy_fs_struct(fs);
1355         if (!tsk->fs)
1356                 return -ENOMEM;
1357         return 0;
1358 }
1359
1360 static int copy_files(unsigned long clone_flags, struct task_struct *tsk)
1361 {
1362         struct files_struct *oldf, *newf;
1363         int error = 0;
1364
1365         /*
1366          * A background process may not have any files ...
1367          */
1368         oldf = current->files;
1369         if (!oldf)
1370                 goto out;
1371
1372         if (clone_flags & CLONE_FILES) {
1373                 atomic_inc(&oldf->count);
1374                 goto out;
1375         }
1376
1377         newf = dup_fd(oldf, &error);
1378         if (!newf)
1379                 goto out;
1380
1381         tsk->files = newf;
1382         error = 0;
1383 out:
1384         return error;
1385 }
1386
1387 static int copy_io(unsigned long clone_flags, struct task_struct *tsk)
1388 {
1389 #ifdef CONFIG_BLOCK
1390         struct io_context *ioc = current->io_context;
1391         struct io_context *new_ioc;
1392
1393         if (!ioc)
1394                 return 0;
1395         /*
1396          * Share io context with parent, if CLONE_IO is set
1397          */
1398         if (clone_flags & CLONE_IO) {
1399                 ioc_task_link(ioc);
1400                 tsk->io_context = ioc;
1401         } else if (ioprio_valid(ioc->ioprio)) {
1402                 new_ioc = get_task_io_context(tsk, GFP_KERNEL, NUMA_NO_NODE);
1403                 if (unlikely(!new_ioc))
1404                         return -ENOMEM;
1405
1406                 new_ioc->ioprio = ioc->ioprio;
1407                 put_io_context(new_ioc);
1408         }
1409 #endif
1410         return 0;
1411 }
1412
1413 static int copy_sighand(unsigned long clone_flags, struct task_struct *tsk)
1414 {
1415         struct sighand_struct *sig;
1416
1417         if (clone_flags & CLONE_SIGHAND) {
1418                 atomic_inc(&current->sighand->count);
1419                 return 0;
1420         }
1421         sig = kmem_cache_alloc(sighand_cachep, GFP_KERNEL);
1422         rcu_assign_pointer(tsk->sighand, sig);
1423         if (!sig)
1424                 return -ENOMEM;
1425
1426         atomic_set(&sig->count, 1);
1427         memcpy(sig->action, current->sighand->action, sizeof(sig->action));
1428         return 0;
1429 }
1430
1431 void __cleanup_sighand(struct sighand_struct *sighand)
1432 {
1433         if (atomic_dec_and_test(&sighand->count)) {
1434                 signalfd_cleanup(sighand);
1435                 /*
1436                  * sighand_cachep is SLAB_TYPESAFE_BY_RCU so we can free it
1437                  * without an RCU grace period, see __lock_task_sighand().
1438                  */
1439                 kmem_cache_free(sighand_cachep, sighand);
1440         }
1441 }
1442
1443 #ifdef CONFIG_POSIX_TIMERS
1444 /*
1445  * Initialize POSIX timer handling for a thread group.
1446  */
1447 static void posix_cpu_timers_init_group(struct signal_struct *sig)
1448 {
1449         unsigned long cpu_limit;
1450
1451         cpu_limit = READ_ONCE(sig->rlim[RLIMIT_CPU].rlim_cur);
1452         if (cpu_limit != RLIM_INFINITY) {
1453                 sig->cputime_expires.prof_exp = cpu_limit * NSEC_PER_SEC;
1454                 sig->cputimer.running = true;
1455         }
1456
1457         /* The timer lists. */
1458         INIT_LIST_HEAD(&sig->cpu_timers[0]);
1459         INIT_LIST_HEAD(&sig->cpu_timers[1]);
1460         INIT_LIST_HEAD(&sig->cpu_timers[2]);
1461 }
1462 #else
1463 static inline void posix_cpu_timers_init_group(struct signal_struct *sig) { }
1464 #endif
1465
1466 static int copy_signal(unsigned long clone_flags, struct task_struct *tsk)
1467 {
1468         struct signal_struct *sig;
1469
1470         if (clone_flags & CLONE_THREAD)
1471                 return 0;
1472
1473         sig = kmem_cache_zalloc(signal_cachep, GFP_KERNEL);
1474         tsk->signal = sig;
1475         if (!sig)
1476                 return -ENOMEM;
1477
1478         sig->nr_threads = 1;
1479         atomic_set(&sig->live, 1);
1480         atomic_set(&sig->sigcnt, 1);
1481
1482         /* list_add(thread_node, thread_head) without INIT_LIST_HEAD() */
1483         sig->thread_head = (struct list_head)LIST_HEAD_INIT(tsk->thread_node);
1484         tsk->thread_node = (struct list_head)LIST_HEAD_INIT(sig->thread_head);
1485
1486         init_waitqueue_head(&sig->wait_chldexit);
1487         sig->curr_target = tsk;
1488         init_sigpending(&sig->shared_pending);
1489         seqlock_init(&sig->stats_lock);
1490         prev_cputime_init(&sig->prev_cputime);
1491
1492 #ifdef CONFIG_POSIX_TIMERS
1493         INIT_LIST_HEAD(&sig->posix_timers);
1494         hrtimer_init(&sig->real_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
1495         sig->real_timer.function = it_real_fn;
1496 #endif
1497
1498         task_lock(current->group_leader);
1499         memcpy(sig->rlim, current->signal->rlim, sizeof sig->rlim);
1500         task_unlock(current->group_leader);
1501
1502         posix_cpu_timers_init_group(sig);
1503
1504         tty_audit_fork(sig);
1505         sched_autogroup_fork(sig);
1506
1507         sig->oom_score_adj = current->signal->oom_score_adj;
1508         sig->oom_score_adj_min = current->signal->oom_score_adj_min;
1509
1510         mutex_init(&sig->cred_guard_mutex);
1511
1512         return 0;
1513 }
1514
1515 static void copy_seccomp(struct task_struct *p)
1516 {
1517 #ifdef CONFIG_SECCOMP
1518         /*
1519          * Must be called with sighand->lock held, which is common to
1520          * all threads in the group. Holding cred_guard_mutex is not
1521          * needed because this new task is not yet running and cannot
1522          * be racing exec.
1523          */
1524         assert_spin_locked(&current->sighand->siglock);
1525
1526         /* Ref-count the new filter user, and assign it. */
1527         get_seccomp_filter(current);
1528         p->seccomp = current->seccomp;
1529
1530         /*
1531          * Explicitly enable no_new_privs here in case it got set
1532          * between the task_struct being duplicated and holding the
1533          * sighand lock. The seccomp state and nnp must be in sync.
1534          */
1535         if (task_no_new_privs(current))
1536                 task_set_no_new_privs(p);
1537
1538         /*
1539          * If the parent gained a seccomp mode after copying thread
1540          * flags and between before we held the sighand lock, we have
1541          * to manually enable the seccomp thread flag here.
1542          */
1543         if (p->seccomp.mode != SECCOMP_MODE_DISABLED)
1544                 set_tsk_thread_flag(p, TIF_SECCOMP);
1545 #endif
1546 }
1547
1548 SYSCALL_DEFINE1(set_tid_address, int __user *, tidptr)
1549 {
1550         current->clear_child_tid = tidptr;
1551
1552         return task_pid_vnr(current);
1553 }
1554
1555 static void rt_mutex_init_task(struct task_struct *p)
1556 {
1557         raw_spin_lock_init(&p->pi_lock);
1558 #ifdef CONFIG_RT_MUTEXES
1559         p->pi_waiters = RB_ROOT_CACHED;
1560         p->pi_top_task = NULL;
1561         p->pi_blocked_on = NULL;
1562 #endif
1563 }
1564
1565 #ifdef CONFIG_POSIX_TIMERS
1566 /*
1567  * Initialize POSIX timer handling for a single task.
1568  */
1569 static void posix_cpu_timers_init(struct task_struct *tsk)
1570 {
1571         tsk->cputime_expires.prof_exp = 0;
1572         tsk->cputime_expires.virt_exp = 0;
1573         tsk->cputime_expires.sched_exp = 0;
1574         INIT_LIST_HEAD(&tsk->cpu_timers[0]);
1575         INIT_LIST_HEAD(&tsk->cpu_timers[1]);
1576         INIT_LIST_HEAD(&tsk->cpu_timers[2]);
1577 }
1578 #else
1579 static inline void posix_cpu_timers_init(struct task_struct *tsk) { }
1580 #endif
1581
1582 static inline void
1583 init_task_pid(struct task_struct *task, enum pid_type type, struct pid *pid)
1584 {
1585          task->pids[type].pid = pid;
1586 }
1587
1588 static inline void rcu_copy_process(struct task_struct *p)
1589 {
1590 #ifdef CONFIG_PREEMPT_RCU
1591         p->rcu_read_lock_nesting = 0;
1592         p->rcu_read_unlock_special.s = 0;
1593         p->rcu_blocked_node = NULL;
1594         INIT_LIST_HEAD(&p->rcu_node_entry);
1595 #endif /* #ifdef CONFIG_PREEMPT_RCU */
1596 #ifdef CONFIG_TASKS_RCU
1597         p->rcu_tasks_holdout = false;
1598         INIT_LIST_HEAD(&p->rcu_tasks_holdout_list);
1599         p->rcu_tasks_idle_cpu = -1;
1600 #endif /* #ifdef CONFIG_TASKS_RCU */
1601 }
1602
1603 /*
1604  * This creates a new process as a copy of the old one,
1605  * but does not actually start it yet.
1606  *
1607  * It copies the registers, and all the appropriate
1608  * parts of the process environment (as per the clone
1609  * flags). The actual kick-off is left to the caller.
1610  */
1611 static __latent_entropy struct task_struct *copy_process(
1612                                         unsigned long clone_flags,
1613                                         unsigned long stack_start,
1614                                         unsigned long stack_size,
1615                                         int __user *child_tidptr,
1616                                         struct pid *pid,
1617                                         int trace,
1618                                         unsigned long tls,
1619                                         int node)
1620 {
1621         int retval;
1622         struct task_struct *p;
1623
1624         /*
1625          * Don't allow sharing the root directory with processes in a different
1626          * namespace
1627          */
1628         if ((clone_flags & (CLONE_NEWNS|CLONE_FS)) == (CLONE_NEWNS|CLONE_FS))
1629                 return ERR_PTR(-EINVAL);
1630
1631         if ((clone_flags & (CLONE_NEWUSER|CLONE_FS)) == (CLONE_NEWUSER|CLONE_FS))
1632                 return ERR_PTR(-EINVAL);
1633
1634         /*
1635          * Thread groups must share signals as well, and detached threads
1636          * can only be started up within the thread group.
1637          */
1638         if ((clone_flags & CLONE_THREAD) && !(clone_flags & CLONE_SIGHAND))
1639                 return ERR_PTR(-EINVAL);
1640
1641         /*
1642          * Shared signal handlers imply shared VM. By way of the above,
1643          * thread groups also imply shared VM. Blocking this case allows
1644          * for various simplifications in other code.
1645          */
1646         if ((clone_flags & CLONE_SIGHAND) && !(clone_flags & CLONE_VM))
1647                 return ERR_PTR(-EINVAL);
1648
1649         /*
1650          * Siblings of global init remain as zombies on exit since they are
1651          * not reaped by their parent (swapper). To solve this and to avoid
1652          * multi-rooted process trees, prevent global and container-inits
1653          * from creating siblings.
1654          */
1655         if ((clone_flags & CLONE_PARENT) &&
1656                                 current->signal->flags & SIGNAL_UNKILLABLE)
1657                 return ERR_PTR(-EINVAL);
1658
1659         /*
1660          * If the new process will be in a different pid or user namespace
1661          * do not allow it to share a thread group with the forking task.
1662          */
1663         if (clone_flags & CLONE_THREAD) {
1664                 if ((clone_flags & (CLONE_NEWUSER | CLONE_NEWPID)) ||
1665                     (task_active_pid_ns(current) !=
1666                                 current->nsproxy->pid_ns_for_children))
1667                         return ERR_PTR(-EINVAL);
1668         }
1669
1670         retval = -ENOMEM;
1671         p = dup_task_struct(current, node);
1672         if (!p)
1673                 goto fork_out;
1674
1675         /*
1676          * This _must_ happen before we call free_task(), i.e. before we jump
1677          * to any of the bad_fork_* labels. This is to avoid freeing
1678          * p->set_child_tid which is (ab)used as a kthread's data pointer for
1679          * kernel threads (PF_KTHREAD).
1680          */
1681         p->set_child_tid = (clone_flags & CLONE_CHILD_SETTID) ? child_tidptr : NULL;
1682         /*
1683          * Clear TID on mm_release()?
1684          */
1685         p->clear_child_tid = (clone_flags & CLONE_CHILD_CLEARTID) ? child_tidptr : NULL;
1686
1687         ftrace_graph_init_task(p);
1688
1689         rt_mutex_init_task(p);
1690
1691 #ifdef CONFIG_PROVE_LOCKING
1692         DEBUG_LOCKS_WARN_ON(!p->hardirqs_enabled);
1693         DEBUG_LOCKS_WARN_ON(!p->softirqs_enabled);
1694 #endif
1695         retval = -EAGAIN;
1696         if (atomic_read(&p->real_cred->user->processes) >=
1697                         task_rlimit(p, RLIMIT_NPROC)) {
1698                 if (p->real_cred->user != INIT_USER &&
1699                     !capable(CAP_SYS_RESOURCE) && !capable(CAP_SYS_ADMIN))
1700                         goto bad_fork_free;
1701         }
1702         current->flags &= ~PF_NPROC_EXCEEDED;
1703
1704         retval = copy_creds(p, clone_flags);
1705         if (retval < 0)
1706                 goto bad_fork_free;
1707
1708         /*
1709          * If multiple threads are within copy_process(), then this check
1710          * triggers too late. This doesn't hurt, the check is only there
1711          * to stop root fork bombs.
1712          */
1713         retval = -EAGAIN;
1714         if (nr_threads >= max_threads)
1715                 goto bad_fork_cleanup_count;
1716
1717         delayacct_tsk_init(p);  /* Must remain after dup_task_struct() */
1718         p->flags &= ~(PF_SUPERPRIV | PF_WQ_WORKER | PF_IDLE);
1719         p->flags |= PF_FORKNOEXEC;
1720         INIT_LIST_HEAD(&p->children);
1721         INIT_LIST_HEAD(&p->sibling);
1722         rcu_copy_process(p);
1723         p->vfork_done = NULL;
1724         spin_lock_init(&p->alloc_lock);
1725
1726         init_sigpending(&p->pending);
1727
1728         p->utime = p->stime = p->gtime = 0;
1729 #ifdef CONFIG_ARCH_HAS_SCALED_CPUTIME
1730         p->utimescaled = p->stimescaled = 0;
1731 #endif
1732         prev_cputime_init(&p->prev_cputime);
1733
1734 #ifdef CONFIG_VIRT_CPU_ACCOUNTING_GEN
1735         seqcount_init(&p->vtime.seqcount);
1736         p->vtime.starttime = 0;
1737         p->vtime.state = VTIME_INACTIVE;
1738 #endif
1739
1740 #if defined(SPLIT_RSS_COUNTING)
1741         memset(&p->rss_stat, 0, sizeof(p->rss_stat));
1742 #endif
1743
1744         p->default_timer_slack_ns = current->timer_slack_ns;
1745
1746         task_io_accounting_init(&p->ioac);
1747         acct_clear_integrals(p);
1748
1749         posix_cpu_timers_init(p);
1750
1751         p->start_time = ktime_get_ns();
1752         p->real_start_time = ktime_get_boot_ns();
1753         p->io_context = NULL;
1754         audit_set_context(p, NULL);
1755         cgroup_fork(p);
1756 #ifdef CONFIG_NUMA
1757         p->mempolicy = mpol_dup(p->mempolicy);
1758         if (IS_ERR(p->mempolicy)) {
1759                 retval = PTR_ERR(p->mempolicy);
1760                 p->mempolicy = NULL;
1761                 goto bad_fork_cleanup_threadgroup_lock;
1762         }
1763 #endif
1764 #ifdef CONFIG_CPUSETS
1765         p->cpuset_mem_spread_rotor = NUMA_NO_NODE;
1766         p->cpuset_slab_spread_rotor = NUMA_NO_NODE;
1767         seqcount_init(&p->mems_allowed_seq);
1768 #endif
1769 #ifdef CONFIG_TRACE_IRQFLAGS
1770         p->irq_events = 0;
1771         p->hardirqs_enabled = 0;
1772         p->hardirq_enable_ip = 0;
1773         p->hardirq_enable_event = 0;
1774         p->hardirq_disable_ip = _THIS_IP_;
1775         p->hardirq_disable_event = 0;
1776         p->softirqs_enabled = 1;
1777         p->softirq_enable_ip = _THIS_IP_;
1778         p->softirq_enable_event = 0;
1779         p->softirq_disable_ip = 0;
1780         p->softirq_disable_event = 0;
1781         p->hardirq_context = 0;
1782         p->softirq_context = 0;
1783 #endif
1784
1785         p->pagefault_disabled = 0;
1786
1787 #ifdef CONFIG_LOCKDEP
1788         p->lockdep_depth = 0; /* no locks held yet */
1789         p->curr_chain_key = 0;
1790         p->lockdep_recursion = 0;
1791         lockdep_init_task(p);
1792 #endif
1793
1794 #ifdef CONFIG_DEBUG_MUTEXES
1795         p->blocked_on = NULL; /* not blocked yet */
1796 #endif
1797 #ifdef CONFIG_BCACHE
1798         p->sequential_io        = 0;
1799         p->sequential_io_avg    = 0;
1800 #endif
1801
1802         /* Perform scheduler related setup. Assign this task to a CPU. */
1803         retval = sched_fork(clone_flags, p);
1804         if (retval)
1805                 goto bad_fork_cleanup_policy;
1806
1807         retval = perf_event_init_task(p);
1808         if (retval)
1809                 goto bad_fork_cleanup_policy;
1810         retval = audit_alloc(p);
1811         if (retval)
1812                 goto bad_fork_cleanup_perf;
1813         /* copy all the process information */
1814         shm_init_task(p);
1815         retval = security_task_alloc(p, clone_flags);
1816         if (retval)
1817                 goto bad_fork_cleanup_audit;
1818         retval = copy_semundo(clone_flags, p);
1819         if (retval)
1820                 goto bad_fork_cleanup_security;
1821         retval = copy_files(clone_flags, p);
1822         if (retval)
1823                 goto bad_fork_cleanup_semundo;
1824         retval = copy_fs(clone_flags, p);
1825         if (retval)
1826                 goto bad_fork_cleanup_files;
1827         retval = copy_sighand(clone_flags, p);
1828         if (retval)
1829                 goto bad_fork_cleanup_fs;
1830         retval = copy_signal(clone_flags, p);
1831         if (retval)
1832                 goto bad_fork_cleanup_sighand;
1833         retval = copy_mm(clone_flags, p);
1834         if (retval)
1835                 goto bad_fork_cleanup_signal;
1836         retval = copy_namespaces(clone_flags, p);
1837         if (retval)
1838                 goto bad_fork_cleanup_mm;
1839         retval = copy_io(clone_flags, p);
1840         if (retval)
1841                 goto bad_fork_cleanup_namespaces;
1842         retval = copy_thread_tls(clone_flags, stack_start, stack_size, p, tls);
1843         if (retval)
1844                 goto bad_fork_cleanup_io;
1845
1846         if (pid != &init_struct_pid) {
1847                 pid = alloc_pid(p->nsproxy->pid_ns_for_children);
1848                 if (IS_ERR(pid)) {
1849                         retval = PTR_ERR(pid);
1850                         goto bad_fork_cleanup_thread;
1851                 }
1852         }
1853
1854 #ifdef CONFIG_BLOCK
1855         p->plug = NULL;
1856 #endif
1857 #ifdef CONFIG_FUTEX
1858         p->robust_list = NULL;
1859 #ifdef CONFIG_COMPAT
1860         p->compat_robust_list = NULL;
1861 #endif
1862         INIT_LIST_HEAD(&p->pi_state_list);
1863         p->pi_state_cache = NULL;
1864 #endif
1865         /*
1866          * sigaltstack should be cleared when sharing the same VM
1867          */
1868         if ((clone_flags & (CLONE_VM|CLONE_VFORK)) == CLONE_VM)
1869                 sas_ss_reset(p);
1870
1871         /*
1872          * Syscall tracing and stepping should be turned off in the
1873          * child regardless of CLONE_PTRACE.
1874          */
1875         user_disable_single_step(p);
1876         clear_tsk_thread_flag(p, TIF_SYSCALL_TRACE);
1877 #ifdef TIF_SYSCALL_EMU
1878         clear_tsk_thread_flag(p, TIF_SYSCALL_EMU);
1879 #endif
1880         clear_all_latency_tracing(p);
1881
1882         /* ok, now we should be set up.. */
1883         p->pid = pid_nr(pid);
1884         if (clone_flags & CLONE_THREAD) {
1885                 p->exit_signal = -1;
1886                 p->group_leader = current->group_leader;
1887                 p->tgid = current->tgid;
1888         } else {
1889                 if (clone_flags & CLONE_PARENT)
1890                         p->exit_signal = current->group_leader->exit_signal;
1891                 else
1892                         p->exit_signal = (clone_flags & CSIGNAL);
1893                 p->group_leader = p;
1894                 p->tgid = p->pid;
1895         }
1896
1897         p->nr_dirtied = 0;
1898         p->nr_dirtied_pause = 128 >> (PAGE_SHIFT - 10);
1899         p->dirty_paused_when = 0;
1900
1901         p->pdeath_signal = 0;
1902         INIT_LIST_HEAD(&p->thread_group);
1903         p->task_works = NULL;
1904
1905         cgroup_threadgroup_change_begin(current);
1906         /*
1907          * Ensure that the cgroup subsystem policies allow the new process to be
1908          * forked. It should be noted the the new process's css_set can be changed
1909          * between here and cgroup_post_fork() if an organisation operation is in
1910          * progress.
1911          */
1912         retval = cgroup_can_fork(p);
1913         if (retval)
1914                 goto bad_fork_free_pid;
1915
1916         /*
1917          * Make it visible to the rest of the system, but dont wake it up yet.
1918          * Need tasklist lock for parent etc handling!
1919          */
1920         write_lock_irq(&tasklist_lock);
1921
1922         /* CLONE_PARENT re-uses the old parent */
1923         if (clone_flags & (CLONE_PARENT|CLONE_THREAD)) {
1924                 p->real_parent = current->real_parent;
1925                 p->parent_exec_id = current->parent_exec_id;
1926         } else {
1927                 p->real_parent = current;
1928                 p->parent_exec_id = current->self_exec_id;
1929         }
1930
1931         klp_copy_process(p);
1932
1933         spin_lock(&current->sighand->siglock);
1934
1935         /*
1936          * Copy seccomp details explicitly here, in case they were changed
1937          * before holding sighand lock.
1938          */
1939         copy_seccomp(p);
1940
1941         rseq_fork(p, clone_flags);
1942
1943         /*
1944          * Process group and session signals need to be delivered to just the
1945          * parent before the fork or both the parent and the child after the
1946          * fork. Restart if a signal comes in before we add the new process to
1947          * it's process group.
1948          * A fatal signal pending means that current will exit, so the new
1949          * thread can't slip out of an OOM kill (or normal SIGKILL).
1950         */
1951         recalc_sigpending();
1952         if (signal_pending(current)) {
1953                 retval = -ERESTARTNOINTR;
1954                 goto bad_fork_cancel_cgroup;
1955         }
1956         if (unlikely(!(ns_of_pid(pid)->pid_allocated & PIDNS_ADDING))) {
1957                 retval = -ENOMEM;
1958                 goto bad_fork_cancel_cgroup;
1959         }
1960
1961         if (likely(p->pid)) {
1962                 ptrace_init_task(p, (clone_flags & CLONE_PTRACE) || trace);
1963
1964                 init_task_pid(p, PIDTYPE_PID, pid);
1965                 if (thread_group_leader(p)) {
1966                         init_task_pid(p, PIDTYPE_PGID, task_pgrp(current));
1967                         init_task_pid(p, PIDTYPE_SID, task_session(current));
1968
1969                         if (is_child_reaper(pid)) {
1970                                 ns_of_pid(pid)->child_reaper = p;
1971                                 p->signal->flags |= SIGNAL_UNKILLABLE;
1972                         }
1973
1974                         p->signal->leader_pid = pid;
1975                         p->signal->tty = tty_kref_get(current->signal->tty);
1976                         /*
1977                          * Inherit has_child_subreaper flag under the same
1978                          * tasklist_lock with adding child to the process tree
1979                          * for propagate_has_child_subreaper optimization.
1980                          */
1981                         p->signal->has_child_subreaper = p->real_parent->signal->has_child_subreaper ||
1982                                                          p->real_parent->signal->is_child_subreaper;
1983                         list_add_tail(&p->sibling, &p->real_parent->children);
1984                         list_add_tail_rcu(&p->tasks, &init_task.tasks);
1985                         attach_pid(p, PIDTYPE_PGID);
1986                         attach_pid(p, PIDTYPE_SID);
1987                         __this_cpu_inc(process_counts);
1988                 } else {
1989                         current->signal->nr_threads++;
1990                         atomic_inc(&current->signal->live);
1991                         atomic_inc(&current->signal->sigcnt);
1992                         list_add_tail_rcu(&p->thread_group,
1993                                           &p->group_leader->thread_group);
1994                         list_add_tail_rcu(&p->thread_node,
1995                                           &p->signal->thread_head);
1996                 }
1997                 attach_pid(p, PIDTYPE_PID);
1998                 nr_threads++;
1999         }
2000
2001         total_forks++;
2002         spin_unlock(&current->sighand->siglock);
2003         syscall_tracepoint_update(p);
2004         write_unlock_irq(&tasklist_lock);
2005
2006         proc_fork_connector(p);
2007         cgroup_post_fork(p);
2008         cgroup_threadgroup_change_end(current);
2009         perf_event_fork(p);
2010
2011         trace_task_newtask(p, clone_flags);
2012         uprobe_copy_process(p, clone_flags);
2013
2014         return p;
2015
2016 bad_fork_cancel_cgroup:
2017         spin_unlock(&current->sighand->siglock);
2018         write_unlock_irq(&tasklist_lock);
2019         cgroup_cancel_fork(p);
2020 bad_fork_free_pid:
2021         cgroup_threadgroup_change_end(current);
2022         if (pid != &init_struct_pid)
2023                 free_pid(pid);
2024 bad_fork_cleanup_thread:
2025         exit_thread(p);
2026 bad_fork_cleanup_io:
2027         if (p->io_context)
2028                 exit_io_context(p);
2029 bad_fork_cleanup_namespaces:
2030         exit_task_namespaces(p);
2031 bad_fork_cleanup_mm:
2032         if (p->mm)
2033                 mmput(p->mm);
2034 bad_fork_cleanup_signal:
2035         if (!(clone_flags & CLONE_THREAD))
2036                 free_signal_struct(p->signal);
2037 bad_fork_cleanup_sighand:
2038         __cleanup_sighand(p->sighand);
2039 bad_fork_cleanup_fs:
2040         exit_fs(p); /* blocking */
2041 bad_fork_cleanup_files:
2042         exit_files(p); /* blocking */
2043 bad_fork_cleanup_semundo:
2044         exit_sem(p);
2045 bad_fork_cleanup_security:
2046         security_task_free(p);
2047 bad_fork_cleanup_audit:
2048         audit_free(p);
2049 bad_fork_cleanup_perf:
2050         perf_event_free_task(p);
2051 bad_fork_cleanup_policy:
2052         lockdep_free_task(p);
2053 #ifdef CONFIG_NUMA
2054         mpol_put(p->mempolicy);
2055 bad_fork_cleanup_threadgroup_lock:
2056 #endif
2057         delayacct_tsk_free(p);
2058 bad_fork_cleanup_count:
2059         atomic_dec(&p->cred->user->processes);
2060         exit_creds(p);
2061 bad_fork_free:
2062         p->state = TASK_DEAD;
2063         put_task_stack(p);
2064         free_task(p);
2065 fork_out:
2066         return ERR_PTR(retval);
2067 }
2068
2069 static inline void init_idle_pids(struct pid_link *links)
2070 {
2071         enum pid_type type;
2072
2073         for (type = PIDTYPE_PID; type < PIDTYPE_MAX; ++type) {
2074                 INIT_HLIST_NODE(&links[type].node); /* not really needed */
2075                 links[type].pid = &init_struct_pid;
2076         }
2077 }
2078
2079 struct task_struct *fork_idle(int cpu)
2080 {
2081         struct task_struct *task;
2082         task = copy_process(CLONE_VM, 0, 0, NULL, &init_struct_pid, 0, 0,
2083                             cpu_to_node(cpu));
2084         if (!IS_ERR(task)) {
2085                 init_idle_pids(task->pids);
2086                 init_idle(task, cpu);
2087         }
2088
2089         return task;
2090 }
2091
2092 /*
2093  *  Ok, this is the main fork-routine.
2094  *
2095  * It copies the process, and if successful kick-starts
2096  * it and waits for it to finish using the VM if required.
2097  */
2098 long _do_fork(unsigned long clone_flags,
2099               unsigned long stack_start,
2100               unsigned long stack_size,
2101               int __user *parent_tidptr,
2102               int __user *child_tidptr,
2103               unsigned long tls)
2104 {
2105         struct completion vfork;
2106         struct pid *pid;
2107         struct task_struct *p;
2108         int trace = 0;
2109         long nr;
2110
2111         /*
2112          * Determine whether and which event to report to ptracer.  When
2113          * called from kernel_thread or CLONE_UNTRACED is explicitly
2114          * requested, no event is reported; otherwise, report if the event
2115          * for the type of forking is enabled.
2116          */
2117         if (!(clone_flags & CLONE_UNTRACED)) {
2118                 if (clone_flags & CLONE_VFORK)
2119                         trace = PTRACE_EVENT_VFORK;
2120                 else if ((clone_flags & CSIGNAL) != SIGCHLD)
2121                         trace = PTRACE_EVENT_CLONE;
2122                 else
2123                         trace = PTRACE_EVENT_FORK;
2124
2125                 if (likely(!ptrace_event_enabled(current, trace)))
2126                         trace = 0;
2127         }
2128
2129         p = copy_process(clone_flags, stack_start, stack_size,
2130                          child_tidptr, NULL, trace, tls, NUMA_NO_NODE);
2131         add_latent_entropy();
2132
2133         if (IS_ERR(p))
2134                 return PTR_ERR(p);
2135
2136         /*
2137          * Do this prior waking up the new thread - the thread pointer
2138          * might get invalid after that point, if the thread exits quickly.
2139          */
2140         trace_sched_process_fork(current, p);
2141
2142         pid = get_task_pid(p, PIDTYPE_PID);
2143         nr = pid_vnr(pid);
2144
2145         if (clone_flags & CLONE_PARENT_SETTID)
2146                 put_user(nr, parent_tidptr);
2147
2148         if (clone_flags & CLONE_VFORK) {
2149                 p->vfork_done = &vfork;
2150                 init_completion(&vfork);
2151                 get_task_struct(p);
2152         }
2153
2154         wake_up_new_task(p);
2155
2156         /* forking complete and child started to run, tell ptracer */
2157         if (unlikely(trace))
2158                 ptrace_event_pid(trace, pid);
2159
2160         if (clone_flags & CLONE_VFORK) {
2161                 if (!wait_for_vfork_done(p, &vfork))
2162                         ptrace_event_pid(PTRACE_EVENT_VFORK_DONE, pid);
2163         }
2164
2165         put_pid(pid);
2166         return nr;
2167 }
2168
2169 #ifndef CONFIG_HAVE_COPY_THREAD_TLS
2170 /* For compatibility with architectures that call do_fork directly rather than
2171  * using the syscall entry points below. */
2172 long do_fork(unsigned long clone_flags,
2173               unsigned long stack_start,
2174               unsigned long stack_size,
2175               int __user *parent_tidptr,
2176               int __user *child_tidptr)
2177 {
2178         return _do_fork(clone_flags, stack_start, stack_size,
2179                         parent_tidptr, child_tidptr, 0);
2180 }
2181 #endif
2182
2183 /*
2184  * Create a kernel thread.
2185  */
2186 pid_t kernel_thread(int (*fn)(void *), void *arg, unsigned long flags)
2187 {
2188         return _do_fork(flags|CLONE_VM|CLONE_UNTRACED, (unsigned long)fn,
2189                 (unsigned long)arg, NULL, NULL, 0);
2190 }
2191
2192 #ifdef __ARCH_WANT_SYS_FORK
2193 SYSCALL_DEFINE0(fork)
2194 {
2195 #ifdef CONFIG_MMU
2196         return _do_fork(SIGCHLD, 0, 0, NULL, NULL, 0);
2197 #else
2198         /* can not support in nommu mode */
2199         return -EINVAL;
2200 #endif
2201 }
2202 #endif
2203
2204 #ifdef __ARCH_WANT_SYS_VFORK
2205 SYSCALL_DEFINE0(vfork)
2206 {
2207         return _do_fork(CLONE_VFORK | CLONE_VM | SIGCHLD, 0,
2208                         0, NULL, NULL, 0);
2209 }
2210 #endif
2211
2212 #ifdef __ARCH_WANT_SYS_CLONE
2213 #ifdef CONFIG_CLONE_BACKWARDS
2214 SYSCALL_DEFINE5(clone, unsigned long, clone_flags, unsigned long, newsp,
2215                  int __user *, parent_tidptr,
2216                  unsigned long, tls,
2217                  int __user *, child_tidptr)
2218 #elif defined(CONFIG_CLONE_BACKWARDS2)
2219 SYSCALL_DEFINE5(clone, unsigned long, newsp, unsigned long, clone_flags,
2220                  int __user *, parent_tidptr,
2221                  int __user *, child_tidptr,
2222                  unsigned long, tls)
2223 #elif defined(CONFIG_CLONE_BACKWARDS3)
2224 SYSCALL_DEFINE6(clone, unsigned long, clone_flags, unsigned long, newsp,
2225                 int, stack_size,
2226                 int __user *, parent_tidptr,
2227                 int __user *, child_tidptr,
2228                 unsigned long, tls)
2229 #else
2230 SYSCALL_DEFINE5(clone, unsigned long, clone_flags, unsigned long, newsp,
2231                  int __user *, parent_tidptr,
2232                  int __user *, child_tidptr,
2233                  unsigned long, tls)
2234 #endif
2235 {
2236         return _do_fork(clone_flags, newsp, 0, parent_tidptr, child_tidptr, tls);
2237 }
2238 #endif
2239
2240 void walk_process_tree(struct task_struct *top, proc_visitor visitor, void *data)
2241 {
2242         struct task_struct *leader, *parent, *child;
2243         int res;
2244
2245         read_lock(&tasklist_lock);
2246         leader = top = top->group_leader;
2247 down:
2248         for_each_thread(leader, parent) {
2249                 list_for_each_entry(child, &parent->children, sibling) {
2250                         res = visitor(child, data);
2251                         if (res) {
2252                                 if (res < 0)
2253                                         goto out;
2254                                 leader = child;
2255                                 goto down;
2256                         }
2257 up:
2258                         ;
2259                 }
2260         }
2261
2262         if (leader != top) {
2263                 child = leader;
2264                 parent = child->real_parent;
2265                 leader = parent->group_leader;
2266                 goto up;
2267         }
2268 out:
2269         read_unlock(&tasklist_lock);
2270 }
2271
2272 #ifndef ARCH_MIN_MMSTRUCT_ALIGN
2273 #define ARCH_MIN_MMSTRUCT_ALIGN 0
2274 #endif
2275
2276 static void sighand_ctor(void *data)
2277 {
2278         struct sighand_struct *sighand = data;
2279
2280         spin_lock_init(&sighand->siglock);
2281         init_waitqueue_head(&sighand->signalfd_wqh);
2282 }
2283
2284 void __init proc_caches_init(void)
2285 {
2286         sighand_cachep = kmem_cache_create("sighand_cache",
2287                         sizeof(struct sighand_struct), 0,
2288                         SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_TYPESAFE_BY_RCU|
2289                         SLAB_ACCOUNT, sighand_ctor);
2290         signal_cachep = kmem_cache_create("signal_cache",
2291                         sizeof(struct signal_struct), 0,
2292                         SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_ACCOUNT,
2293                         NULL);
2294         files_cachep = kmem_cache_create("files_cache",
2295                         sizeof(struct files_struct), 0,
2296                         SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_ACCOUNT,
2297                         NULL);
2298         fs_cachep = kmem_cache_create("fs_cache",
2299                         sizeof(struct fs_struct), 0,
2300                         SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_ACCOUNT,
2301                         NULL);
2302         /*
2303          * FIXME! The "sizeof(struct mm_struct)" currently includes the
2304          * whole struct cpumask for the OFFSTACK case. We could change
2305          * this to *only* allocate as much of it as required by the
2306          * maximum number of CPU's we can ever have.  The cpumask_allocation
2307          * is at the end of the structure, exactly for that reason.
2308          */
2309         mm_cachep = kmem_cache_create_usercopy("mm_struct",
2310                         sizeof(struct mm_struct), ARCH_MIN_MMSTRUCT_ALIGN,
2311                         SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_ACCOUNT,
2312                         offsetof(struct mm_struct, saved_auxv),
2313                         sizeof_field(struct mm_struct, saved_auxv),
2314                         NULL);
2315         vm_area_cachep = KMEM_CACHE(vm_area_struct, SLAB_PANIC|SLAB_ACCOUNT);
2316         mmap_init();
2317         nsproxy_cache_init();
2318 }
2319
2320 /*
2321  * Check constraints on flags passed to the unshare system call.
2322  */
2323 static int check_unshare_flags(unsigned long unshare_flags)
2324 {
2325         if (unshare_flags & ~(CLONE_THREAD|CLONE_FS|CLONE_NEWNS|CLONE_SIGHAND|
2326                                 CLONE_VM|CLONE_FILES|CLONE_SYSVSEM|
2327                                 CLONE_NEWUTS|CLONE_NEWIPC|CLONE_NEWNET|
2328                                 CLONE_NEWUSER|CLONE_NEWPID|CLONE_NEWCGROUP))
2329                 return -EINVAL;
2330         /*
2331          * Not implemented, but pretend it works if there is nothing
2332          * to unshare.  Note that unsharing the address space or the
2333          * signal handlers also need to unshare the signal queues (aka
2334          * CLONE_THREAD).
2335          */
2336         if (unshare_flags & (CLONE_THREAD | CLONE_SIGHAND | CLONE_VM)) {
2337                 if (!thread_group_empty(current))
2338                         return -EINVAL;
2339         }
2340         if (unshare_flags & (CLONE_SIGHAND | CLONE_VM)) {
2341                 if (atomic_read(&current->sighand->count) > 1)
2342                         return -EINVAL;
2343         }
2344         if (unshare_flags & CLONE_VM) {
2345                 if (!current_is_single_threaded())
2346                         return -EINVAL;
2347         }
2348
2349         return 0;
2350 }
2351
2352 /*
2353  * Unshare the filesystem structure if it is being shared
2354  */
2355 static int unshare_fs(unsigned long unshare_flags, struct fs_struct **new_fsp)
2356 {
2357         struct fs_struct *fs = current->fs;
2358
2359         if (!(unshare_flags & CLONE_FS) || !fs)
2360                 return 0;
2361
2362         /* don't need lock here; in the worst case we'll do useless copy */
2363         if (fs->users == 1)
2364                 return 0;
2365
2366         *new_fsp = copy_fs_struct(fs);
2367         if (!*new_fsp)
2368                 return -ENOMEM;
2369
2370         return 0;
2371 }
2372
2373 /*
2374  * Unshare file descriptor table if it is being shared
2375  */
2376 static int unshare_fd(unsigned long unshare_flags, struct files_struct **new_fdp)
2377 {
2378         struct files_struct *fd = current->files;
2379         int error = 0;
2380
2381         if ((unshare_flags & CLONE_FILES) &&
2382             (fd && atomic_read(&fd->count) > 1)) {
2383                 *new_fdp = dup_fd(fd, &error);
2384                 if (!*new_fdp)
2385                         return error;
2386         }
2387
2388         return 0;
2389 }
2390
2391 /*
2392  * unshare allows a process to 'unshare' part of the process
2393  * context which was originally shared using clone.  copy_*
2394  * functions used by do_fork() cannot be used here directly
2395  * because they modify an inactive task_struct that is being
2396  * constructed. Here we are modifying the current, active,
2397  * task_struct.
2398  */
2399 int ksys_unshare(unsigned long unshare_flags)
2400 {
2401         struct fs_struct *fs, *new_fs = NULL;
2402         struct files_struct *fd, *new_fd = NULL;
2403         struct cred *new_cred = NULL;
2404         struct nsproxy *new_nsproxy = NULL;
2405         int do_sysvsem = 0;
2406         int err;
2407
2408         /*
2409          * If unsharing a user namespace must also unshare the thread group
2410          * and unshare the filesystem root and working directories.
2411          */
2412         if (unshare_flags & CLONE_NEWUSER)
2413                 unshare_flags |= CLONE_THREAD | CLONE_FS;
2414         /*
2415          * If unsharing vm, must also unshare signal handlers.
2416          */
2417         if (unshare_flags & CLONE_VM)
2418                 unshare_flags |= CLONE_SIGHAND;
2419         /*
2420          * If unsharing a signal handlers, must also unshare the signal queues.
2421          */
2422         if (unshare_flags & CLONE_SIGHAND)
2423                 unshare_flags |= CLONE_THREAD;
2424         /*
2425          * If unsharing namespace, must also unshare filesystem information.
2426          */
2427         if (unshare_flags & CLONE_NEWNS)
2428                 unshare_flags |= CLONE_FS;
2429
2430         err = check_unshare_flags(unshare_flags);
2431         if (err)
2432                 goto bad_unshare_out;
2433         /*
2434          * CLONE_NEWIPC must also detach from the undolist: after switching
2435          * to a new ipc namespace, the semaphore arrays from the old
2436          * namespace are unreachable.
2437          */
2438         if (unshare_flags & (CLONE_NEWIPC|CLONE_SYSVSEM))
2439                 do_sysvsem = 1;
2440         err = unshare_fs(unshare_flags, &new_fs);
2441         if (err)
2442                 goto bad_unshare_out;
2443         err = unshare_fd(unshare_flags, &new_fd);
2444         if (err)
2445                 goto bad_unshare_cleanup_fs;
2446         err = unshare_userns(unshare_flags, &new_cred);
2447         if (err)
2448                 goto bad_unshare_cleanup_fd;
2449         err = unshare_nsproxy_namespaces(unshare_flags, &new_nsproxy,
2450                                          new_cred, new_fs);
2451         if (err)
2452                 goto bad_unshare_cleanup_cred;
2453
2454         if (new_fs || new_fd || do_sysvsem || new_cred || new_nsproxy) {
2455                 if (do_sysvsem) {
2456                         /*
2457                          * CLONE_SYSVSEM is equivalent to sys_exit().
2458                          */
2459                         exit_sem(current);
2460                 }
2461                 if (unshare_flags & CLONE_NEWIPC) {
2462                         /* Orphan segments in old ns (see sem above). */
2463                         exit_shm(current);
2464                         shm_init_task(current);
2465                 }
2466
2467                 if (new_nsproxy)
2468                         switch_task_namespaces(current, new_nsproxy);
2469
2470                 task_lock(current);
2471
2472                 if (new_fs) {
2473                         fs = current->fs;
2474                         spin_lock(&fs->lock);
2475                         current->fs = new_fs;
2476                         if (--fs->users)
2477                                 new_fs = NULL;
2478                         else
2479                                 new_fs = fs;
2480                         spin_unlock(&fs->lock);
2481                 }
2482
2483                 if (new_fd) {
2484                         fd = current->files;
2485                         current->files = new_fd;
2486                         new_fd = fd;
2487                 }
2488
2489                 task_unlock(current);
2490
2491                 if (new_cred) {
2492                         /* Install the new user namespace */
2493                         commit_creds(new_cred);
2494                         new_cred = NULL;
2495                 }
2496         }
2497
2498         perf_event_namespaces(current);
2499
2500 bad_unshare_cleanup_cred:
2501         if (new_cred)
2502                 put_cred(new_cred);
2503 bad_unshare_cleanup_fd:
2504         if (new_fd)
2505                 put_files_struct(new_fd);
2506
2507 bad_unshare_cleanup_fs:
2508         if (new_fs)
2509                 free_fs_struct(new_fs);
2510
2511 bad_unshare_out:
2512         return err;
2513 }
2514
2515 SYSCALL_DEFINE1(unshare, unsigned long, unshare_flags)
2516 {
2517         return ksys_unshare(unshare_flags);
2518 }
2519
2520 /*
2521  *      Helper to unshare the files of the current task.
2522  *      We don't want to expose copy_files internals to
2523  *      the exec layer of the kernel.
2524  */
2525
2526 int unshare_files(struct files_struct **displaced)
2527 {
2528         struct task_struct *task = current;
2529         struct files_struct *copy = NULL;
2530         int error;
2531
2532         error = unshare_fd(CLONE_FILES, &copy);
2533         if (error || !copy) {
2534                 *displaced = NULL;
2535                 return error;
2536         }
2537         *displaced = task->files;
2538         task_lock(task);
2539         task->files = copy;
2540         task_unlock(task);
2541         return 0;
2542 }
2543
2544 int sysctl_max_threads(struct ctl_table *table, int write,
2545                        void __user *buffer, size_t *lenp, loff_t *ppos)
2546 {
2547         struct ctl_table t;
2548         int ret;
2549         int threads = max_threads;
2550         int min = MIN_THREADS;
2551         int max = MAX_THREADS;
2552
2553         t = *table;
2554         t.data = &threads;
2555         t.extra1 = &min;
2556         t.extra2 = &max;
2557
2558         ret = proc_dointvec_minmax(&t, write, buffer, lenp, ppos);
2559         if (ret || !write)
2560                 return ret;
2561
2562         set_max_threads(threads);
2563
2564         return 0;
2565 }