OSDN Git Service

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