OSDN Git Service

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