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