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