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