OSDN Git Service

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