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