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