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