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