Merge tag 'kgdb-5.2-rc1' of git://git.kernel.org/pub/scm/linux/kernel/git/danielt...
[linux-2.6-microblaze.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/anon_inodes.h>
15 #include <linux/slab.h>
16 #include <linux/sched/autogroup.h>
17 #include <linux/sched/mm.h>
18 #include <linux/sched/coredump.h>
19 #include <linux/sched/user.h>
20 #include <linux/sched/numa_balancing.h>
21 #include <linux/sched/stat.h>
22 #include <linux/sched/task.h>
23 #include <linux/sched/task_stack.h>
24 #include <linux/sched/cputime.h>
25 #include <linux/seq_file.h>
26 #include <linux/rtmutex.h>
27 #include <linux/init.h>
28 #include <linux/unistd.h>
29 #include <linux/module.h>
30 #include <linux/vmalloc.h>
31 #include <linux/completion.h>
32 #include <linux/personality.h>
33 #include <linux/mempolicy.h>
34 #include <linux/sem.h>
35 #include <linux/file.h>
36 #include <linux/fdtable.h>
37 #include <linux/iocontext.h>
38 #include <linux/key.h>
39 #include <linux/binfmts.h>
40 #include <linux/mman.h>
41 #include <linux/mmu_notifier.h>
42 #include <linux/hmm.h>
43 #include <linux/fs.h>
44 #include <linux/mm.h>
45 #include <linux/vmacache.h>
46 #include <linux/nsproxy.h>
47 #include <linux/capability.h>
48 #include <linux/cpu.h>
49 #include <linux/cgroup.h>
50 #include <linux/security.h>
51 #include <linux/hugetlb.h>
52 #include <linux/seccomp.h>
53 #include <linux/swap.h>
54 #include <linux/syscalls.h>
55 #include <linux/jiffies.h>
56 #include <linux/futex.h>
57 #include <linux/compat.h>
58 #include <linux/kthread.h>
59 #include <linux/task_io_accounting_ops.h>
60 #include <linux/rcupdate.h>
61 #include <linux/ptrace.h>
62 #include <linux/mount.h>
63 #include <linux/audit.h>
64 #include <linux/memcontrol.h>
65 #include <linux/ftrace.h>
66 #include <linux/proc_fs.h>
67 #include <linux/profile.h>
68 #include <linux/rmap.h>
69 #include <linux/ksm.h>
70 #include <linux/acct.h>
71 #include <linux/userfaultfd_k.h>
72 #include <linux/tsacct_kern.h>
73 #include <linux/cn_proc.h>
74 #include <linux/freezer.h>
75 #include <linux/delayacct.h>
76 #include <linux/taskstats_kern.h>
77 #include <linux/random.h>
78 #include <linux/tty.h>
79 #include <linux/blkdev.h>
80 #include <linux/fs_struct.h>
81 #include <linux/magic.h>
82 #include <linux/perf_event.h>
83 #include <linux/posix-timers.h>
84 #include <linux/user-return-notifier.h>
85 #include <linux/oom.h>
86 #include <linux/khugepaged.h>
87 #include <linux/signalfd.h>
88 #include <linux/uprobes.h>
89 #include <linux/aio.h>
90 #include <linux/compiler.h>
91 #include <linux/sysctl.h>
92 #include <linux/kcov.h>
93 #include <linux/livepatch.h>
94 #include <linux/thread_info.h>
95 #include <linux/stackleak.h>
96
97 #include <asm/pgtable.h>
98 #include <asm/pgalloc.h>
99 #include <linux/uaccess.h>
100 #include <asm/mmu_context.h>
101 #include <asm/cacheflush.h>
102 #include <asm/tlbflush.h>
103
104 #include <trace/events/sched.h>
105
106 #define CREATE_TRACE_POINTS
107 #include <trace/events/task.h>
108
109 /*
110  * Minimum number of threads to boot the kernel
111  */
112 #define MIN_THREADS 20
113
114 /*
115  * Maximum number of threads
116  */
117 #define MAX_THREADS FUTEX_TID_MASK
118
119 /*
120  * Protected counters by write_lock_irq(&tasklist_lock)
121  */
122 unsigned long total_forks;      /* Handle normal Linux uptimes. */
123 int nr_threads;                 /* The idle threads do not count.. */
124
125 int max_threads;                /* tunable limit on nr_threads */
126
127 DEFINE_PER_CPU(unsigned long, process_counts) = 0;
128
129 __cacheline_aligned DEFINE_RWLOCK(tasklist_lock);  /* outer */
130
131 #ifdef CONFIG_PROVE_RCU
132 int lockdep_tasklist_lock_is_held(void)
133 {
134         return lockdep_is_held(&tasklist_lock);
135 }
136 EXPORT_SYMBOL_GPL(lockdep_tasklist_lock_is_held);
137 #endif /* #ifdef CONFIG_PROVE_RCU */
138
139 int nr_processes(void)
140 {
141         int cpu;
142         int total = 0;
143
144         for_each_possible_cpu(cpu)
145                 total += per_cpu(process_counts, cpu);
146
147         return total;
148 }
149
150 void __weak arch_release_task_struct(struct task_struct *tsk)
151 {
152 }
153
154 #ifndef CONFIG_ARCH_TASK_STRUCT_ALLOCATOR
155 static struct kmem_cache *task_struct_cachep;
156
157 static inline struct task_struct *alloc_task_struct_node(int node)
158 {
159         return kmem_cache_alloc_node(task_struct_cachep, GFP_KERNEL, node);
160 }
161
162 static inline void free_task_struct(struct task_struct *tsk)
163 {
164         kmem_cache_free(task_struct_cachep, tsk);
165 }
166 #endif
167
168 #ifndef CONFIG_ARCH_THREAD_STACK_ALLOCATOR
169
170 /*
171  * Allocate pages if THREAD_SIZE is >= PAGE_SIZE, otherwise use a
172  * kmemcache based allocator.
173  */
174 # if THREAD_SIZE >= PAGE_SIZE || defined(CONFIG_VMAP_STACK)
175
176 #ifdef CONFIG_VMAP_STACK
177 /*
178  * vmalloc() is a bit slow, and calling vfree() enough times will force a TLB
179  * flush.  Try to minimize the number of calls by caching stacks.
180  */
181 #define NR_CACHED_STACKS 2
182 static DEFINE_PER_CPU(struct vm_struct *, cached_stacks[NR_CACHED_STACKS]);
183
184 static int free_vm_stack_cache(unsigned int cpu)
185 {
186         struct vm_struct **cached_vm_stacks = per_cpu_ptr(cached_stacks, cpu);
187         int i;
188
189         for (i = 0; i < NR_CACHED_STACKS; i++) {
190                 struct vm_struct *vm_stack = cached_vm_stacks[i];
191
192                 if (!vm_stack)
193                         continue;
194
195                 vfree(vm_stack->addr);
196                 cached_vm_stacks[i] = NULL;
197         }
198
199         return 0;
200 }
201 #endif
202
203 static unsigned long *alloc_thread_stack_node(struct task_struct *tsk, int node)
204 {
205 #ifdef CONFIG_VMAP_STACK
206         void *stack;
207         int i;
208
209         for (i = 0; i < NR_CACHED_STACKS; i++) {
210                 struct vm_struct *s;
211
212                 s = this_cpu_xchg(cached_stacks[i], NULL);
213
214                 if (!s)
215                         continue;
216
217                 /* Clear stale pointers from reused stack. */
218                 memset(s->addr, 0, THREAD_SIZE);
219
220                 tsk->stack_vm_area = s;
221                 tsk->stack = s->addr;
222                 return s->addr;
223         }
224
225         /*
226          * Allocated stacks are cached and later reused by new threads,
227          * so memcg accounting is performed manually on assigning/releasing
228          * stacks to tasks. Drop __GFP_ACCOUNT.
229          */
230         stack = __vmalloc_node_range(THREAD_SIZE, THREAD_ALIGN,
231                                      VMALLOC_START, VMALLOC_END,
232                                      THREADINFO_GFP & ~__GFP_ACCOUNT,
233                                      PAGE_KERNEL,
234                                      0, node, __builtin_return_address(0));
235
236         /*
237          * We can't call find_vm_area() in interrupt context, and
238          * free_thread_stack() can be called in interrupt context,
239          * so cache the vm_struct.
240          */
241         if (stack) {
242                 tsk->stack_vm_area = find_vm_area(stack);
243                 tsk->stack = stack;
244         }
245         return stack;
246 #else
247         struct page *page = alloc_pages_node(node, THREADINFO_GFP,
248                                              THREAD_SIZE_ORDER);
249
250         return page ? page_address(page) : NULL;
251 #endif
252 }
253
254 static inline void free_thread_stack(struct task_struct *tsk)
255 {
256 #ifdef CONFIG_VMAP_STACK
257         struct vm_struct *vm = task_stack_vm_area(tsk);
258
259         if (vm) {
260                 int i;
261
262                 for (i = 0; i < THREAD_SIZE / PAGE_SIZE; i++) {
263                         mod_memcg_page_state(vm->pages[i],
264                                              MEMCG_KERNEL_STACK_KB,
265                                              -(int)(PAGE_SIZE / 1024));
266
267                         memcg_kmem_uncharge(vm->pages[i], 0);
268                 }
269
270                 for (i = 0; i < NR_CACHED_STACKS; i++) {
271                         if (this_cpu_cmpxchg(cached_stacks[i],
272                                         NULL, tsk->stack_vm_area) != NULL)
273                                 continue;
274
275                         return;
276                 }
277
278                 vfree_atomic(tsk->stack);
279                 return;
280         }
281 #endif
282
283         __free_pages(virt_to_page(tsk->stack), THREAD_SIZE_ORDER);
284 }
285 # else
286 static struct kmem_cache *thread_stack_cache;
287
288 static unsigned long *alloc_thread_stack_node(struct task_struct *tsk,
289                                                   int node)
290 {
291         unsigned long *stack;
292         stack = kmem_cache_alloc_node(thread_stack_cache, THREADINFO_GFP, node);
293         tsk->stack = stack;
294         return stack;
295 }
296
297 static void free_thread_stack(struct task_struct *tsk)
298 {
299         kmem_cache_free(thread_stack_cache, tsk->stack);
300 }
301
302 void thread_stack_cache_init(void)
303 {
304         thread_stack_cache = kmem_cache_create_usercopy("thread_stack",
305                                         THREAD_SIZE, THREAD_SIZE, 0, 0,
306                                         THREAD_SIZE, NULL);
307         BUG_ON(thread_stack_cache == NULL);
308 }
309 # endif
310 #endif
311
312 /* SLAB cache for signal_struct structures (tsk->signal) */
313 static struct kmem_cache *signal_cachep;
314
315 /* SLAB cache for sighand_struct structures (tsk->sighand) */
316 struct kmem_cache *sighand_cachep;
317
318 /* SLAB cache for files_struct structures (tsk->files) */
319 struct kmem_cache *files_cachep;
320
321 /* SLAB cache for fs_struct structures (tsk->fs) */
322 struct kmem_cache *fs_cachep;
323
324 /* SLAB cache for vm_area_struct structures */
325 static struct kmem_cache *vm_area_cachep;
326
327 /* SLAB cache for mm_struct structures (tsk->mm) */
328 static struct kmem_cache *mm_cachep;
329
330 struct vm_area_struct *vm_area_alloc(struct mm_struct *mm)
331 {
332         struct vm_area_struct *vma;
333
334         vma = kmem_cache_alloc(vm_area_cachep, GFP_KERNEL);
335         if (vma)
336                 vma_init(vma, mm);
337         return vma;
338 }
339
340 struct vm_area_struct *vm_area_dup(struct vm_area_struct *orig)
341 {
342         struct vm_area_struct *new = kmem_cache_alloc(vm_area_cachep, GFP_KERNEL);
343
344         if (new) {
345                 *new = *orig;
346                 INIT_LIST_HEAD(&new->anon_vma_chain);
347         }
348         return new;
349 }
350
351 void vm_area_free(struct vm_area_struct *vma)
352 {
353         kmem_cache_free(vm_area_cachep, vma);
354 }
355
356 static void account_kernel_stack(struct task_struct *tsk, int account)
357 {
358         void *stack = task_stack_page(tsk);
359         struct vm_struct *vm = task_stack_vm_area(tsk);
360
361         BUILD_BUG_ON(IS_ENABLED(CONFIG_VMAP_STACK) && PAGE_SIZE % 1024 != 0);
362
363         if (vm) {
364                 int i;
365
366                 BUG_ON(vm->nr_pages != THREAD_SIZE / PAGE_SIZE);
367
368                 for (i = 0; i < THREAD_SIZE / PAGE_SIZE; i++) {
369                         mod_zone_page_state(page_zone(vm->pages[i]),
370                                             NR_KERNEL_STACK_KB,
371                                             PAGE_SIZE / 1024 * account);
372                 }
373         } else {
374                 /*
375                  * All stack pages are in the same zone and belong to the
376                  * same memcg.
377                  */
378                 struct page *first_page = virt_to_page(stack);
379
380                 mod_zone_page_state(page_zone(first_page), NR_KERNEL_STACK_KB,
381                                     THREAD_SIZE / 1024 * account);
382
383                 mod_memcg_page_state(first_page, MEMCG_KERNEL_STACK_KB,
384                                      account * (THREAD_SIZE / 1024));
385         }
386 }
387
388 static int memcg_charge_kernel_stack(struct task_struct *tsk)
389 {
390 #ifdef CONFIG_VMAP_STACK
391         struct vm_struct *vm = task_stack_vm_area(tsk);
392         int ret;
393
394         if (vm) {
395                 int i;
396
397                 for (i = 0; i < THREAD_SIZE / PAGE_SIZE; i++) {
398                         /*
399                          * If memcg_kmem_charge() fails, page->mem_cgroup
400                          * pointer is NULL, and both memcg_kmem_uncharge()
401                          * and mod_memcg_page_state() in free_thread_stack()
402                          * will ignore this page. So it's safe.
403                          */
404                         ret = memcg_kmem_charge(vm->pages[i], GFP_KERNEL, 0);
405                         if (ret)
406                                 return ret;
407
408                         mod_memcg_page_state(vm->pages[i],
409                                              MEMCG_KERNEL_STACK_KB,
410                                              PAGE_SIZE / 1024);
411                 }
412         }
413 #endif
414         return 0;
415 }
416
417 static void release_task_stack(struct task_struct *tsk)
418 {
419         if (WARN_ON(tsk->state != TASK_DEAD))
420                 return;  /* Better to leak the stack than to free prematurely */
421
422         account_kernel_stack(tsk, -1);
423         free_thread_stack(tsk);
424         tsk->stack = NULL;
425 #ifdef CONFIG_VMAP_STACK
426         tsk->stack_vm_area = NULL;
427 #endif
428 }
429
430 #ifdef CONFIG_THREAD_INFO_IN_TASK
431 void put_task_stack(struct task_struct *tsk)
432 {
433         if (refcount_dec_and_test(&tsk->stack_refcount))
434                 release_task_stack(tsk);
435 }
436 #endif
437
438 void free_task(struct task_struct *tsk)
439 {
440 #ifndef CONFIG_THREAD_INFO_IN_TASK
441         /*
442          * The task is finally done with both the stack and thread_info,
443          * so free both.
444          */
445         release_task_stack(tsk);
446 #else
447         /*
448          * If the task had a separate stack allocation, it should be gone
449          * by now.
450          */
451         WARN_ON_ONCE(refcount_read(&tsk->stack_refcount) != 0);
452 #endif
453         rt_mutex_debug_task_free(tsk);
454         ftrace_graph_exit_task(tsk);
455         put_seccomp_filter(tsk);
456         arch_release_task_struct(tsk);
457         if (tsk->flags & PF_KTHREAD)
458                 free_kthread_struct(tsk);
459         free_task_struct(tsk);
460 }
461 EXPORT_SYMBOL(free_task);
462
463 #ifdef CONFIG_MMU
464 static __latent_entropy int dup_mmap(struct mm_struct *mm,
465                                         struct mm_struct *oldmm)
466 {
467         struct vm_area_struct *mpnt, *tmp, *prev, **pprev;
468         struct rb_node **rb_link, *rb_parent;
469         int retval;
470         unsigned long charge;
471         LIST_HEAD(uf);
472
473         uprobe_start_dup_mmap();
474         if (down_write_killable(&oldmm->mmap_sem)) {
475                 retval = -EINTR;
476                 goto fail_uprobe_end;
477         }
478         flush_cache_dup_mm(oldmm);
479         uprobe_dup_mmap(oldmm, mm);
480         /*
481          * Not linked in yet - no deadlock potential:
482          */
483         down_write_nested(&mm->mmap_sem, SINGLE_DEPTH_NESTING);
484
485         /* No ordering required: file already has been exposed. */
486         RCU_INIT_POINTER(mm->exe_file, get_mm_exe_file(oldmm));
487
488         mm->total_vm = oldmm->total_vm;
489         mm->data_vm = oldmm->data_vm;
490         mm->exec_vm = oldmm->exec_vm;
491         mm->stack_vm = oldmm->stack_vm;
492
493         rb_link = &mm->mm_rb.rb_node;
494         rb_parent = NULL;
495         pprev = &mm->mmap;
496         retval = ksm_fork(mm, oldmm);
497         if (retval)
498                 goto out;
499         retval = khugepaged_fork(mm, oldmm);
500         if (retval)
501                 goto out;
502
503         prev = NULL;
504         for (mpnt = oldmm->mmap; mpnt; mpnt = mpnt->vm_next) {
505                 struct file *file;
506
507                 if (mpnt->vm_flags & VM_DONTCOPY) {
508                         vm_stat_account(mm, mpnt->vm_flags, -vma_pages(mpnt));
509                         continue;
510                 }
511                 charge = 0;
512                 /*
513                  * Don't duplicate many vmas if we've been oom-killed (for
514                  * example)
515                  */
516                 if (fatal_signal_pending(current)) {
517                         retval = -EINTR;
518                         goto out;
519                 }
520                 if (mpnt->vm_flags & VM_ACCOUNT) {
521                         unsigned long len = vma_pages(mpnt);
522
523                         if (security_vm_enough_memory_mm(oldmm, len)) /* sic */
524                                 goto fail_nomem;
525                         charge = len;
526                 }
527                 tmp = vm_area_dup(mpnt);
528                 if (!tmp)
529                         goto fail_nomem;
530                 retval = vma_dup_policy(mpnt, tmp);
531                 if (retval)
532                         goto fail_nomem_policy;
533                 tmp->vm_mm = mm;
534                 retval = dup_userfaultfd(tmp, &uf);
535                 if (retval)
536                         goto fail_nomem_anon_vma_fork;
537                 if (tmp->vm_flags & VM_WIPEONFORK) {
538                         /* VM_WIPEONFORK gets a clean slate in the child. */
539                         tmp->anon_vma = NULL;
540                         if (anon_vma_prepare(tmp))
541                                 goto fail_nomem_anon_vma_fork;
542                 } else if (anon_vma_fork(tmp, mpnt))
543                         goto fail_nomem_anon_vma_fork;
544                 tmp->vm_flags &= ~(VM_LOCKED | VM_LOCKONFAULT);
545                 tmp->vm_next = tmp->vm_prev = NULL;
546                 file = tmp->vm_file;
547                 if (file) {
548                         struct inode *inode = file_inode(file);
549                         struct address_space *mapping = file->f_mapping;
550
551                         get_file(file);
552                         if (tmp->vm_flags & VM_DENYWRITE)
553                                 atomic_dec(&inode->i_writecount);
554                         i_mmap_lock_write(mapping);
555                         if (tmp->vm_flags & VM_SHARED)
556                                 atomic_inc(&mapping->i_mmap_writable);
557                         flush_dcache_mmap_lock(mapping);
558                         /* insert tmp into the share list, just after mpnt */
559                         vma_interval_tree_insert_after(tmp, mpnt,
560                                         &mapping->i_mmap);
561                         flush_dcache_mmap_unlock(mapping);
562                         i_mmap_unlock_write(mapping);
563                 }
564
565                 /*
566                  * Clear hugetlb-related page reserves for children. This only
567                  * affects MAP_PRIVATE mappings. Faults generated by the child
568                  * are not guaranteed to succeed, even if read-only
569                  */
570                 if (is_vm_hugetlb_page(tmp))
571                         reset_vma_resv_huge_pages(tmp);
572
573                 /*
574                  * Link in the new vma and copy the page table entries.
575                  */
576                 *pprev = tmp;
577                 pprev = &tmp->vm_next;
578                 tmp->vm_prev = prev;
579                 prev = tmp;
580
581                 __vma_link_rb(mm, tmp, rb_link, rb_parent);
582                 rb_link = &tmp->vm_rb.rb_right;
583                 rb_parent = &tmp->vm_rb;
584
585                 mm->map_count++;
586                 if (!(tmp->vm_flags & VM_WIPEONFORK))
587                         retval = copy_page_range(mm, oldmm, mpnt);
588
589                 if (tmp->vm_ops && tmp->vm_ops->open)
590                         tmp->vm_ops->open(tmp);
591
592                 if (retval)
593                         goto out;
594         }
595         /* a new mm has just been created */
596         retval = arch_dup_mmap(oldmm, mm);
597 out:
598         up_write(&mm->mmap_sem);
599         flush_tlb_mm(oldmm);
600         up_write(&oldmm->mmap_sem);
601         dup_userfaultfd_complete(&uf);
602 fail_uprobe_end:
603         uprobe_end_dup_mmap();
604         return retval;
605 fail_nomem_anon_vma_fork:
606         mpol_put(vma_policy(tmp));
607 fail_nomem_policy:
608         vm_area_free(tmp);
609 fail_nomem:
610         retval = -ENOMEM;
611         vm_unacct_memory(charge);
612         goto out;
613 }
614
615 static inline int mm_alloc_pgd(struct mm_struct *mm)
616 {
617         mm->pgd = pgd_alloc(mm);
618         if (unlikely(!mm->pgd))
619                 return -ENOMEM;
620         return 0;
621 }
622
623 static inline void mm_free_pgd(struct mm_struct *mm)
624 {
625         pgd_free(mm, mm->pgd);
626 }
627 #else
628 static int dup_mmap(struct mm_struct *mm, struct mm_struct *oldmm)
629 {
630         down_write(&oldmm->mmap_sem);
631         RCU_INIT_POINTER(mm->exe_file, get_mm_exe_file(oldmm));
632         up_write(&oldmm->mmap_sem);
633         return 0;
634 }
635 #define mm_alloc_pgd(mm)        (0)
636 #define mm_free_pgd(mm)
637 #endif /* CONFIG_MMU */
638
639 static void check_mm(struct mm_struct *mm)
640 {
641         int i;
642
643         for (i = 0; i < NR_MM_COUNTERS; i++) {
644                 long x = atomic_long_read(&mm->rss_stat.count[i]);
645
646                 if (unlikely(x))
647                         printk(KERN_ALERT "BUG: Bad rss-counter state "
648                                           "mm:%p idx:%d val:%ld\n", mm, i, x);
649         }
650
651         if (mm_pgtables_bytes(mm))
652                 pr_alert("BUG: non-zero pgtables_bytes on freeing mm: %ld\n",
653                                 mm_pgtables_bytes(mm));
654
655 #if defined(CONFIG_TRANSPARENT_HUGEPAGE) && !USE_SPLIT_PMD_PTLOCKS
656         VM_BUG_ON_MM(mm->pmd_huge_pte, mm);
657 #endif
658 }
659
660 #define allocate_mm()   (kmem_cache_alloc(mm_cachep, GFP_KERNEL))
661 #define free_mm(mm)     (kmem_cache_free(mm_cachep, (mm)))
662
663 /*
664  * Called when the last reference to the mm
665  * is dropped: either by a lazy thread or by
666  * mmput. Free the page directory and the mm.
667  */
668 void __mmdrop(struct mm_struct *mm)
669 {
670         BUG_ON(mm == &init_mm);
671         WARN_ON_ONCE(mm == current->mm);
672         WARN_ON_ONCE(mm == current->active_mm);
673         mm_free_pgd(mm);
674         destroy_context(mm);
675         hmm_mm_destroy(mm);
676         mmu_notifier_mm_destroy(mm);
677         check_mm(mm);
678         put_user_ns(mm->user_ns);
679         free_mm(mm);
680 }
681 EXPORT_SYMBOL_GPL(__mmdrop);
682
683 static void mmdrop_async_fn(struct work_struct *work)
684 {
685         struct mm_struct *mm;
686
687         mm = container_of(work, struct mm_struct, async_put_work);
688         __mmdrop(mm);
689 }
690
691 static void mmdrop_async(struct mm_struct *mm)
692 {
693         if (unlikely(atomic_dec_and_test(&mm->mm_count))) {
694                 INIT_WORK(&mm->async_put_work, mmdrop_async_fn);
695                 schedule_work(&mm->async_put_work);
696         }
697 }
698
699 static inline void free_signal_struct(struct signal_struct *sig)
700 {
701         taskstats_tgid_free(sig);
702         sched_autogroup_exit(sig);
703         /*
704          * __mmdrop is not safe to call from softirq context on x86 due to
705          * pgd_dtor so postpone it to the async context
706          */
707         if (sig->oom_mm)
708                 mmdrop_async(sig->oom_mm);
709         kmem_cache_free(signal_cachep, sig);
710 }
711
712 static inline void put_signal_struct(struct signal_struct *sig)
713 {
714         if (refcount_dec_and_test(&sig->sigcnt))
715                 free_signal_struct(sig);
716 }
717
718 void __put_task_struct(struct task_struct *tsk)
719 {
720         WARN_ON(!tsk->exit_state);
721         WARN_ON(refcount_read(&tsk->usage));
722         WARN_ON(tsk == current);
723
724         cgroup_free(tsk);
725         task_numa_free(tsk);
726         security_task_free(tsk);
727         exit_creds(tsk);
728         delayacct_tsk_free(tsk);
729         put_signal_struct(tsk->signal);
730
731         if (!profile_handoff_task(tsk))
732                 free_task(tsk);
733 }
734 EXPORT_SYMBOL_GPL(__put_task_struct);
735
736 void __init __weak arch_task_cache_init(void) { }
737
738 /*
739  * set_max_threads
740  */
741 static void set_max_threads(unsigned int max_threads_suggested)
742 {
743         u64 threads;
744         unsigned long nr_pages = totalram_pages();
745
746         /*
747          * The number of threads shall be limited such that the thread
748          * structures may only consume a small part of the available memory.
749          */
750         if (fls64(nr_pages) + fls64(PAGE_SIZE) > 64)
751                 threads = MAX_THREADS;
752         else
753                 threads = div64_u64((u64) nr_pages * (u64) PAGE_SIZE,
754                                     (u64) THREAD_SIZE * 8UL);
755
756         if (threads > max_threads_suggested)
757                 threads = max_threads_suggested;
758
759         max_threads = clamp_t(u64, threads, MIN_THREADS, MAX_THREADS);
760 }
761
762 #ifdef CONFIG_ARCH_WANTS_DYNAMIC_TASK_STRUCT
763 /* Initialized by the architecture: */
764 int arch_task_struct_size __read_mostly;
765 #endif
766
767 static void task_struct_whitelist(unsigned long *offset, unsigned long *size)
768 {
769         /* Fetch thread_struct whitelist for the architecture. */
770         arch_thread_struct_whitelist(offset, size);
771
772         /*
773          * Handle zero-sized whitelist or empty thread_struct, otherwise
774          * adjust offset to position of thread_struct in task_struct.
775          */
776         if (unlikely(*size == 0))
777                 *offset = 0;
778         else
779                 *offset += offsetof(struct task_struct, thread);
780 }
781
782 void __init fork_init(void)
783 {
784         int i;
785 #ifndef CONFIG_ARCH_TASK_STRUCT_ALLOCATOR
786 #ifndef ARCH_MIN_TASKALIGN
787 #define ARCH_MIN_TASKALIGN      0
788 #endif
789         int align = max_t(int, L1_CACHE_BYTES, ARCH_MIN_TASKALIGN);
790         unsigned long useroffset, usersize;
791
792         /* create a slab on which task_structs can be allocated */
793         task_struct_whitelist(&useroffset, &usersize);
794         task_struct_cachep = kmem_cache_create_usercopy("task_struct",
795                         arch_task_struct_size, align,
796                         SLAB_PANIC|SLAB_ACCOUNT,
797                         useroffset, usersize, NULL);
798 #endif
799
800         /* do the arch specific task caches init */
801         arch_task_cache_init();
802
803         set_max_threads(MAX_THREADS);
804
805         init_task.signal->rlim[RLIMIT_NPROC].rlim_cur = max_threads/2;
806         init_task.signal->rlim[RLIMIT_NPROC].rlim_max = max_threads/2;
807         init_task.signal->rlim[RLIMIT_SIGPENDING] =
808                 init_task.signal->rlim[RLIMIT_NPROC];
809
810         for (i = 0; i < UCOUNT_COUNTS; i++) {
811                 init_user_ns.ucount_max[i] = max_threads/2;
812         }
813
814 #ifdef CONFIG_VMAP_STACK
815         cpuhp_setup_state(CPUHP_BP_PREPARE_DYN, "fork:vm_stack_cache",
816                           NULL, free_vm_stack_cache);
817 #endif
818
819         lockdep_init_task(&init_task);
820         uprobes_init();
821 }
822
823 int __weak arch_dup_task_struct(struct task_struct *dst,
824                                                struct task_struct *src)
825 {
826         *dst = *src;
827         return 0;
828 }
829
830 void set_task_stack_end_magic(struct task_struct *tsk)
831 {
832         unsigned long *stackend;
833
834         stackend = end_of_stack(tsk);
835         *stackend = STACK_END_MAGIC;    /* for overflow detection */
836 }
837
838 static struct task_struct *dup_task_struct(struct task_struct *orig, int node)
839 {
840         struct task_struct *tsk;
841         unsigned long *stack;
842         struct vm_struct *stack_vm_area __maybe_unused;
843         int err;
844
845         if (node == NUMA_NO_NODE)
846                 node = tsk_fork_get_node(orig);
847         tsk = alloc_task_struct_node(node);
848         if (!tsk)
849                 return NULL;
850
851         stack = alloc_thread_stack_node(tsk, node);
852         if (!stack)
853                 goto free_tsk;
854
855         if (memcg_charge_kernel_stack(tsk))
856                 goto free_stack;
857
858         stack_vm_area = task_stack_vm_area(tsk);
859
860         err = arch_dup_task_struct(tsk, orig);
861
862         /*
863          * arch_dup_task_struct() clobbers the stack-related fields.  Make
864          * sure they're properly initialized before using any stack-related
865          * functions again.
866          */
867         tsk->stack = stack;
868 #ifdef CONFIG_VMAP_STACK
869         tsk->stack_vm_area = stack_vm_area;
870 #endif
871 #ifdef CONFIG_THREAD_INFO_IN_TASK
872         refcount_set(&tsk->stack_refcount, 1);
873 #endif
874
875         if (err)
876                 goto free_stack;
877
878 #ifdef CONFIG_SECCOMP
879         /*
880          * We must handle setting up seccomp filters once we're under
881          * the sighand lock in case orig has changed between now and
882          * then. Until then, filter must be NULL to avoid messing up
883          * the usage counts on the error path calling free_task.
884          */
885         tsk->seccomp.filter = NULL;
886 #endif
887
888         setup_thread_stack(tsk, orig);
889         clear_user_return_notifier(tsk);
890         clear_tsk_need_resched(tsk);
891         set_task_stack_end_magic(tsk);
892
893 #ifdef CONFIG_STACKPROTECTOR
894         tsk->stack_canary = get_random_canary();
895 #endif
896
897         /*
898          * One for us, one for whoever does the "release_task()" (usually
899          * parent)
900          */
901         refcount_set(&tsk->usage, 2);
902 #ifdef CONFIG_BLK_DEV_IO_TRACE
903         tsk->btrace_seq = 0;
904 #endif
905         tsk->splice_pipe = NULL;
906         tsk->task_frag.page = NULL;
907         tsk->wake_q.next = NULL;
908
909         account_kernel_stack(tsk, 1);
910
911         kcov_task_init(tsk);
912
913 #ifdef CONFIG_FAULT_INJECTION
914         tsk->fail_nth = 0;
915 #endif
916
917 #ifdef CONFIG_BLK_CGROUP
918         tsk->throttle_queue = NULL;
919         tsk->use_memdelay = 0;
920 #endif
921
922 #ifdef CONFIG_MEMCG
923         tsk->active_memcg = NULL;
924 #endif
925         return tsk;
926
927 free_stack:
928         free_thread_stack(tsk);
929 free_tsk:
930         free_task_struct(tsk);
931         return NULL;
932 }
933
934 __cacheline_aligned_in_smp DEFINE_SPINLOCK(mmlist_lock);
935
936 static unsigned long default_dump_filter = MMF_DUMP_FILTER_DEFAULT;
937
938 static int __init coredump_filter_setup(char *s)
939 {
940         default_dump_filter =
941                 (simple_strtoul(s, NULL, 0) << MMF_DUMP_FILTER_SHIFT) &
942                 MMF_DUMP_FILTER_MASK;
943         return 1;
944 }
945
946 __setup("coredump_filter=", coredump_filter_setup);
947
948 #include <linux/init_task.h>
949
950 static void mm_init_aio(struct mm_struct *mm)
951 {
952 #ifdef CONFIG_AIO
953         spin_lock_init(&mm->ioctx_lock);
954         mm->ioctx_table = NULL;
955 #endif
956 }
957
958 static void mm_init_owner(struct mm_struct *mm, struct task_struct *p)
959 {
960 #ifdef CONFIG_MEMCG
961         mm->owner = p;
962 #endif
963 }
964
965 static void mm_init_uprobes_state(struct mm_struct *mm)
966 {
967 #ifdef CONFIG_UPROBES
968         mm->uprobes_state.xol_area = NULL;
969 #endif
970 }
971
972 static struct mm_struct *mm_init(struct mm_struct *mm, struct task_struct *p,
973         struct user_namespace *user_ns)
974 {
975         mm->mmap = NULL;
976         mm->mm_rb = RB_ROOT;
977         mm->vmacache_seqnum = 0;
978         atomic_set(&mm->mm_users, 1);
979         atomic_set(&mm->mm_count, 1);
980         init_rwsem(&mm->mmap_sem);
981         INIT_LIST_HEAD(&mm->mmlist);
982         mm->core_state = NULL;
983         mm_pgtables_bytes_init(mm);
984         mm->map_count = 0;
985         mm->locked_vm = 0;
986         atomic64_set(&mm->pinned_vm, 0);
987         memset(&mm->rss_stat, 0, sizeof(mm->rss_stat));
988         spin_lock_init(&mm->page_table_lock);
989         spin_lock_init(&mm->arg_lock);
990         mm_init_cpumask(mm);
991         mm_init_aio(mm);
992         mm_init_owner(mm, p);
993         RCU_INIT_POINTER(mm->exe_file, NULL);
994         mmu_notifier_mm_init(mm);
995         hmm_mm_init(mm);
996         init_tlb_flush_pending(mm);
997 #if defined(CONFIG_TRANSPARENT_HUGEPAGE) && !USE_SPLIT_PMD_PTLOCKS
998         mm->pmd_huge_pte = NULL;
999 #endif
1000         mm_init_uprobes_state(mm);
1001
1002         if (current->mm) {
1003                 mm->flags = current->mm->flags & MMF_INIT_MASK;
1004                 mm->def_flags = current->mm->def_flags & VM_INIT_DEF_MASK;
1005         } else {
1006                 mm->flags = default_dump_filter;
1007                 mm->def_flags = 0;
1008         }
1009
1010         if (mm_alloc_pgd(mm))
1011                 goto fail_nopgd;
1012
1013         if (init_new_context(p, mm))
1014                 goto fail_nocontext;
1015
1016         mm->user_ns = get_user_ns(user_ns);
1017         return mm;
1018
1019 fail_nocontext:
1020         mm_free_pgd(mm);
1021 fail_nopgd:
1022         free_mm(mm);
1023         return NULL;
1024 }
1025
1026 /*
1027  * Allocate and initialize an mm_struct.
1028  */
1029 struct mm_struct *mm_alloc(void)
1030 {
1031         struct mm_struct *mm;
1032
1033         mm = allocate_mm();
1034         if (!mm)
1035                 return NULL;
1036
1037         memset(mm, 0, sizeof(*mm));
1038         return mm_init(mm, current, current_user_ns());
1039 }
1040
1041 static inline void __mmput(struct mm_struct *mm)
1042 {
1043         VM_BUG_ON(atomic_read(&mm->mm_users));
1044
1045         uprobe_clear_state(mm);
1046         exit_aio(mm);
1047         ksm_exit(mm);
1048         khugepaged_exit(mm); /* must run before exit_mmap */
1049         exit_mmap(mm);
1050         mm_put_huge_zero_page(mm);
1051         set_mm_exe_file(mm, NULL);
1052         if (!list_empty(&mm->mmlist)) {
1053                 spin_lock(&mmlist_lock);
1054                 list_del(&mm->mmlist);
1055                 spin_unlock(&mmlist_lock);
1056         }
1057         if (mm->binfmt)
1058                 module_put(mm->binfmt->module);
1059         mmdrop(mm);
1060 }
1061
1062 /*
1063  * Decrement the use count and release all resources for an mm.
1064  */
1065 void mmput(struct mm_struct *mm)
1066 {
1067         might_sleep();
1068
1069         if (atomic_dec_and_test(&mm->mm_users))
1070                 __mmput(mm);
1071 }
1072 EXPORT_SYMBOL_GPL(mmput);
1073
1074 #ifdef CONFIG_MMU
1075 static void mmput_async_fn(struct work_struct *work)
1076 {
1077         struct mm_struct *mm = container_of(work, struct mm_struct,
1078                                             async_put_work);
1079
1080         __mmput(mm);
1081 }
1082
1083 void mmput_async(struct mm_struct *mm)
1084 {
1085         if (atomic_dec_and_test(&mm->mm_users)) {
1086                 INIT_WORK(&mm->async_put_work, mmput_async_fn);
1087                 schedule_work(&mm->async_put_work);
1088         }
1089 }
1090 #endif
1091
1092 /**
1093  * set_mm_exe_file - change a reference to the mm's executable file
1094  *
1095  * This changes mm's executable file (shown as symlink /proc/[pid]/exe).
1096  *
1097  * Main users are mmput() and sys_execve(). Callers prevent concurrent
1098  * invocations: in mmput() nobody alive left, in execve task is single
1099  * threaded. sys_prctl(PR_SET_MM_MAP/EXE_FILE) also needs to set the
1100  * mm->exe_file, but does so without using set_mm_exe_file() in order
1101  * to do avoid the need for any locks.
1102  */
1103 void set_mm_exe_file(struct mm_struct *mm, struct file *new_exe_file)
1104 {
1105         struct file *old_exe_file;
1106
1107         /*
1108          * It is safe to dereference the exe_file without RCU as
1109          * this function is only called if nobody else can access
1110          * this mm -- see comment above for justification.
1111          */
1112         old_exe_file = rcu_dereference_raw(mm->exe_file);
1113
1114         if (new_exe_file)
1115                 get_file(new_exe_file);
1116         rcu_assign_pointer(mm->exe_file, new_exe_file);
1117         if (old_exe_file)
1118                 fput(old_exe_file);
1119 }
1120
1121 /**
1122  * get_mm_exe_file - acquire a reference to the mm's executable file
1123  *
1124  * Returns %NULL if mm has no associated executable file.
1125  * User must release file via fput().
1126  */
1127 struct file *get_mm_exe_file(struct mm_struct *mm)
1128 {
1129         struct file *exe_file;
1130
1131         rcu_read_lock();
1132         exe_file = rcu_dereference(mm->exe_file);
1133         if (exe_file && !get_file_rcu(exe_file))
1134                 exe_file = NULL;
1135         rcu_read_unlock();
1136         return exe_file;
1137 }
1138 EXPORT_SYMBOL(get_mm_exe_file);
1139
1140 /**
1141  * get_task_exe_file - acquire a reference to the task's executable file
1142  *
1143  * Returns %NULL if task's mm (if any) has no associated executable file or
1144  * this is a kernel thread with borrowed mm (see the comment above get_task_mm).
1145  * User must release file via fput().
1146  */
1147 struct file *get_task_exe_file(struct task_struct *task)
1148 {
1149         struct file *exe_file = NULL;
1150         struct mm_struct *mm;
1151
1152         task_lock(task);
1153         mm = task->mm;
1154         if (mm) {
1155                 if (!(task->flags & PF_KTHREAD))
1156                         exe_file = get_mm_exe_file(mm);
1157         }
1158         task_unlock(task);
1159         return exe_file;
1160 }
1161 EXPORT_SYMBOL(get_task_exe_file);
1162
1163 /**
1164  * get_task_mm - acquire a reference to the task's mm
1165  *
1166  * Returns %NULL if the task has no mm.  Checks PF_KTHREAD (meaning
1167  * this kernel workthread has transiently adopted a user mm with use_mm,
1168  * to do its AIO) is not set and if so returns a reference to it, after
1169  * bumping up the use count.  User must release the mm via mmput()
1170  * after use.  Typically used by /proc and ptrace.
1171  */
1172 struct mm_struct *get_task_mm(struct task_struct *task)
1173 {
1174         struct mm_struct *mm;
1175
1176         task_lock(task);
1177         mm = task->mm;
1178         if (mm) {
1179                 if (task->flags & PF_KTHREAD)
1180                         mm = NULL;
1181                 else
1182                         mmget(mm);
1183         }
1184         task_unlock(task);
1185         return mm;
1186 }
1187 EXPORT_SYMBOL_GPL(get_task_mm);
1188
1189 struct mm_struct *mm_access(struct task_struct *task, unsigned int mode)
1190 {
1191         struct mm_struct *mm;
1192         int err;
1193
1194         err =  mutex_lock_killable(&task->signal->cred_guard_mutex);
1195         if (err)
1196                 return ERR_PTR(err);
1197
1198         mm = get_task_mm(task);
1199         if (mm && mm != current->mm &&
1200                         !ptrace_may_access(task, mode)) {
1201                 mmput(mm);
1202                 mm = ERR_PTR(-EACCES);
1203         }
1204         mutex_unlock(&task->signal->cred_guard_mutex);
1205
1206         return mm;
1207 }
1208
1209 static void complete_vfork_done(struct task_struct *tsk)
1210 {
1211         struct completion *vfork;
1212
1213         task_lock(tsk);
1214         vfork = tsk->vfork_done;
1215         if (likely(vfork)) {
1216                 tsk->vfork_done = NULL;
1217                 complete(vfork);
1218         }
1219         task_unlock(tsk);
1220 }
1221
1222 static int wait_for_vfork_done(struct task_struct *child,
1223                                 struct completion *vfork)
1224 {
1225         int killed;
1226
1227         freezer_do_not_count();
1228         cgroup_enter_frozen();
1229         killed = wait_for_completion_killable(vfork);
1230         cgroup_leave_frozen(false);
1231         freezer_count();
1232
1233         if (killed) {
1234                 task_lock(child);
1235                 child->vfork_done = NULL;
1236                 task_unlock(child);
1237         }
1238
1239         put_task_struct(child);
1240         return killed;
1241 }
1242
1243 /* Please note the differences between mmput and mm_release.
1244  * mmput is called whenever we stop holding onto a mm_struct,
1245  * error success whatever.
1246  *
1247  * mm_release is called after a mm_struct has been removed
1248  * from the current process.
1249  *
1250  * This difference is important for error handling, when we
1251  * only half set up a mm_struct for a new process and need to restore
1252  * the old one.  Because we mmput the new mm_struct before
1253  * restoring the old one. . .
1254  * Eric Biederman 10 January 1998
1255  */
1256 void mm_release(struct task_struct *tsk, struct mm_struct *mm)
1257 {
1258         /* Get rid of any futexes when releasing the mm */
1259 #ifdef CONFIG_FUTEX
1260         if (unlikely(tsk->robust_list)) {
1261                 exit_robust_list(tsk);
1262                 tsk->robust_list = NULL;
1263         }
1264 #ifdef CONFIG_COMPAT
1265         if (unlikely(tsk->compat_robust_list)) {
1266                 compat_exit_robust_list(tsk);
1267                 tsk->compat_robust_list = NULL;
1268         }
1269 #endif
1270         if (unlikely(!list_empty(&tsk->pi_state_list)))
1271                 exit_pi_state_list(tsk);
1272 #endif
1273
1274         uprobe_free_utask(tsk);
1275
1276         /* Get rid of any cached register state */
1277         deactivate_mm(tsk, mm);
1278
1279         /*
1280          * Signal userspace if we're not exiting with a core dump
1281          * because we want to leave the value intact for debugging
1282          * purposes.
1283          */
1284         if (tsk->clear_child_tid) {
1285                 if (!(tsk->signal->flags & SIGNAL_GROUP_COREDUMP) &&
1286                     atomic_read(&mm->mm_users) > 1) {
1287                         /*
1288                          * We don't check the error code - if userspace has
1289                          * not set up a proper pointer then tough luck.
1290                          */
1291                         put_user(0, tsk->clear_child_tid);
1292                         do_futex(tsk->clear_child_tid, FUTEX_WAKE,
1293                                         1, NULL, NULL, 0, 0);
1294                 }
1295                 tsk->clear_child_tid = NULL;
1296         }
1297
1298         /*
1299          * All done, finally we can wake up parent and return this mm to him.
1300          * Also kthread_stop() uses this completion for synchronization.
1301          */
1302         if (tsk->vfork_done)
1303                 complete_vfork_done(tsk);
1304 }
1305
1306 /**
1307  * dup_mm() - duplicates an existing mm structure
1308  * @tsk: the task_struct with which the new mm will be associated.
1309  * @oldmm: the mm to duplicate.
1310  *
1311  * Allocates a new mm structure and duplicates the provided @oldmm structure
1312  * content into it.
1313  *
1314  * Return: the duplicated mm or NULL on failure.
1315  */
1316 static struct mm_struct *dup_mm(struct task_struct *tsk,
1317                                 struct mm_struct *oldmm)
1318 {
1319         struct mm_struct *mm;
1320         int err;
1321
1322         mm = allocate_mm();
1323         if (!mm)
1324                 goto fail_nomem;
1325
1326         memcpy(mm, oldmm, sizeof(*mm));
1327
1328         if (!mm_init(mm, tsk, mm->user_ns))
1329                 goto fail_nomem;
1330
1331         err = dup_mmap(mm, oldmm);
1332         if (err)
1333                 goto free_pt;
1334
1335         mm->hiwater_rss = get_mm_rss(mm);
1336         mm->hiwater_vm = mm->total_vm;
1337
1338         if (mm->binfmt && !try_module_get(mm->binfmt->module))
1339                 goto free_pt;
1340
1341         return mm;
1342
1343 free_pt:
1344         /* don't put binfmt in mmput, we haven't got module yet */
1345         mm->binfmt = NULL;
1346         mmput(mm);
1347
1348 fail_nomem:
1349         return NULL;
1350 }
1351
1352 static int copy_mm(unsigned long clone_flags, struct task_struct *tsk)
1353 {
1354         struct mm_struct *mm, *oldmm;
1355         int retval;
1356
1357         tsk->min_flt = tsk->maj_flt = 0;
1358         tsk->nvcsw = tsk->nivcsw = 0;
1359 #ifdef CONFIG_DETECT_HUNG_TASK
1360         tsk->last_switch_count = tsk->nvcsw + tsk->nivcsw;
1361         tsk->last_switch_time = 0;
1362 #endif
1363
1364         tsk->mm = NULL;
1365         tsk->active_mm = NULL;
1366
1367         /*
1368          * Are we cloning a kernel thread?
1369          *
1370          * We need to steal a active VM for that..
1371          */
1372         oldmm = current->mm;
1373         if (!oldmm)
1374                 return 0;
1375
1376         /* initialize the new vmacache entries */
1377         vmacache_flush(tsk);
1378
1379         if (clone_flags & CLONE_VM) {
1380                 mmget(oldmm);
1381                 mm = oldmm;
1382                 goto good_mm;
1383         }
1384
1385         retval = -ENOMEM;
1386         mm = dup_mm(tsk, current->mm);
1387         if (!mm)
1388                 goto fail_nomem;
1389
1390 good_mm:
1391         tsk->mm = mm;
1392         tsk->active_mm = mm;
1393         return 0;
1394
1395 fail_nomem:
1396         return retval;
1397 }
1398
1399 static int copy_fs(unsigned long clone_flags, struct task_struct *tsk)
1400 {
1401         struct fs_struct *fs = current->fs;
1402         if (clone_flags & CLONE_FS) {
1403                 /* tsk->fs is already what we want */
1404                 spin_lock(&fs->lock);
1405                 if (fs->in_exec) {
1406                         spin_unlock(&fs->lock);
1407                         return -EAGAIN;
1408                 }
1409                 fs->users++;
1410                 spin_unlock(&fs->lock);
1411                 return 0;
1412         }
1413         tsk->fs = copy_fs_struct(fs);
1414         if (!tsk->fs)
1415                 return -ENOMEM;
1416         return 0;
1417 }
1418
1419 static int copy_files(unsigned long clone_flags, struct task_struct *tsk)
1420 {
1421         struct files_struct *oldf, *newf;
1422         int error = 0;
1423
1424         /*
1425          * A background process may not have any files ...
1426          */
1427         oldf = current->files;
1428         if (!oldf)
1429                 goto out;
1430
1431         if (clone_flags & CLONE_FILES) {
1432                 atomic_inc(&oldf->count);
1433                 goto out;
1434         }
1435
1436         newf = dup_fd(oldf, &error);
1437         if (!newf)
1438                 goto out;
1439
1440         tsk->files = newf;
1441         error = 0;
1442 out:
1443         return error;
1444 }
1445
1446 static int copy_io(unsigned long clone_flags, struct task_struct *tsk)
1447 {
1448 #ifdef CONFIG_BLOCK
1449         struct io_context *ioc = current->io_context;
1450         struct io_context *new_ioc;
1451
1452         if (!ioc)
1453                 return 0;
1454         /*
1455          * Share io context with parent, if CLONE_IO is set
1456          */
1457         if (clone_flags & CLONE_IO) {
1458                 ioc_task_link(ioc);
1459                 tsk->io_context = ioc;
1460         } else if (ioprio_valid(ioc->ioprio)) {
1461                 new_ioc = get_task_io_context(tsk, GFP_KERNEL, NUMA_NO_NODE);
1462                 if (unlikely(!new_ioc))
1463                         return -ENOMEM;
1464
1465                 new_ioc->ioprio = ioc->ioprio;
1466                 put_io_context(new_ioc);
1467         }
1468 #endif
1469         return 0;
1470 }
1471
1472 static int copy_sighand(unsigned long clone_flags, struct task_struct *tsk)
1473 {
1474         struct sighand_struct *sig;
1475
1476         if (clone_flags & CLONE_SIGHAND) {
1477                 refcount_inc(&current->sighand->count);
1478                 return 0;
1479         }
1480         sig = kmem_cache_alloc(sighand_cachep, GFP_KERNEL);
1481         rcu_assign_pointer(tsk->sighand, sig);
1482         if (!sig)
1483                 return -ENOMEM;
1484
1485         refcount_set(&sig->count, 1);
1486         spin_lock_irq(&current->sighand->siglock);
1487         memcpy(sig->action, current->sighand->action, sizeof(sig->action));
1488         spin_unlock_irq(&current->sighand->siglock);
1489         return 0;
1490 }
1491
1492 void __cleanup_sighand(struct sighand_struct *sighand)
1493 {
1494         if (refcount_dec_and_test(&sighand->count)) {
1495                 signalfd_cleanup(sighand);
1496                 /*
1497                  * sighand_cachep is SLAB_TYPESAFE_BY_RCU so we can free it
1498                  * without an RCU grace period, see __lock_task_sighand().
1499                  */
1500                 kmem_cache_free(sighand_cachep, sighand);
1501         }
1502 }
1503
1504 #ifdef CONFIG_POSIX_TIMERS
1505 /*
1506  * Initialize POSIX timer handling for a thread group.
1507  */
1508 static void posix_cpu_timers_init_group(struct signal_struct *sig)
1509 {
1510         unsigned long cpu_limit;
1511
1512         cpu_limit = READ_ONCE(sig->rlim[RLIMIT_CPU].rlim_cur);
1513         if (cpu_limit != RLIM_INFINITY) {
1514                 sig->cputime_expires.prof_exp = cpu_limit * NSEC_PER_SEC;
1515                 sig->cputimer.running = true;
1516         }
1517
1518         /* The timer lists. */
1519         INIT_LIST_HEAD(&sig->cpu_timers[0]);
1520         INIT_LIST_HEAD(&sig->cpu_timers[1]);
1521         INIT_LIST_HEAD(&sig->cpu_timers[2]);
1522 }
1523 #else
1524 static inline void posix_cpu_timers_init_group(struct signal_struct *sig) { }
1525 #endif
1526
1527 static int copy_signal(unsigned long clone_flags, struct task_struct *tsk)
1528 {
1529         struct signal_struct *sig;
1530
1531         if (clone_flags & CLONE_THREAD)
1532                 return 0;
1533
1534         sig = kmem_cache_zalloc(signal_cachep, GFP_KERNEL);
1535         tsk->signal = sig;
1536         if (!sig)
1537                 return -ENOMEM;
1538
1539         sig->nr_threads = 1;
1540         atomic_set(&sig->live, 1);
1541         refcount_set(&sig->sigcnt, 1);
1542
1543         /* list_add(thread_node, thread_head) without INIT_LIST_HEAD() */
1544         sig->thread_head = (struct list_head)LIST_HEAD_INIT(tsk->thread_node);
1545         tsk->thread_node = (struct list_head)LIST_HEAD_INIT(sig->thread_head);
1546
1547         init_waitqueue_head(&sig->wait_chldexit);
1548         sig->curr_target = tsk;
1549         init_sigpending(&sig->shared_pending);
1550         INIT_HLIST_HEAD(&sig->multiprocess);
1551         seqlock_init(&sig->stats_lock);
1552         prev_cputime_init(&sig->prev_cputime);
1553
1554 #ifdef CONFIG_POSIX_TIMERS
1555         INIT_LIST_HEAD(&sig->posix_timers);
1556         hrtimer_init(&sig->real_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
1557         sig->real_timer.function = it_real_fn;
1558 #endif
1559
1560         task_lock(current->group_leader);
1561         memcpy(sig->rlim, current->signal->rlim, sizeof sig->rlim);
1562         task_unlock(current->group_leader);
1563
1564         posix_cpu_timers_init_group(sig);
1565
1566         tty_audit_fork(sig);
1567         sched_autogroup_fork(sig);
1568
1569         sig->oom_score_adj = current->signal->oom_score_adj;
1570         sig->oom_score_adj_min = current->signal->oom_score_adj_min;
1571
1572         mutex_init(&sig->cred_guard_mutex);
1573
1574         return 0;
1575 }
1576
1577 static void copy_seccomp(struct task_struct *p)
1578 {
1579 #ifdef CONFIG_SECCOMP
1580         /*
1581          * Must be called with sighand->lock held, which is common to
1582          * all threads in the group. Holding cred_guard_mutex is not
1583          * needed because this new task is not yet running and cannot
1584          * be racing exec.
1585          */
1586         assert_spin_locked(&current->sighand->siglock);
1587
1588         /* Ref-count the new filter user, and assign it. */
1589         get_seccomp_filter(current);
1590         p->seccomp = current->seccomp;
1591
1592         /*
1593          * Explicitly enable no_new_privs here in case it got set
1594          * between the task_struct being duplicated and holding the
1595          * sighand lock. The seccomp state and nnp must be in sync.
1596          */
1597         if (task_no_new_privs(current))
1598                 task_set_no_new_privs(p);
1599
1600         /*
1601          * If the parent gained a seccomp mode after copying thread
1602          * flags and between before we held the sighand lock, we have
1603          * to manually enable the seccomp thread flag here.
1604          */
1605         if (p->seccomp.mode != SECCOMP_MODE_DISABLED)
1606                 set_tsk_thread_flag(p, TIF_SECCOMP);
1607 #endif
1608 }
1609
1610 SYSCALL_DEFINE1(set_tid_address, int __user *, tidptr)
1611 {
1612         current->clear_child_tid = tidptr;
1613
1614         return task_pid_vnr(current);
1615 }
1616
1617 static void rt_mutex_init_task(struct task_struct *p)
1618 {
1619         raw_spin_lock_init(&p->pi_lock);
1620 #ifdef CONFIG_RT_MUTEXES
1621         p->pi_waiters = RB_ROOT_CACHED;
1622         p->pi_top_task = NULL;
1623         p->pi_blocked_on = NULL;
1624 #endif
1625 }
1626
1627 #ifdef CONFIG_POSIX_TIMERS
1628 /*
1629  * Initialize POSIX timer handling for a single task.
1630  */
1631 static void posix_cpu_timers_init(struct task_struct *tsk)
1632 {
1633         tsk->cputime_expires.prof_exp = 0;
1634         tsk->cputime_expires.virt_exp = 0;
1635         tsk->cputime_expires.sched_exp = 0;
1636         INIT_LIST_HEAD(&tsk->cpu_timers[0]);
1637         INIT_LIST_HEAD(&tsk->cpu_timers[1]);
1638         INIT_LIST_HEAD(&tsk->cpu_timers[2]);
1639 }
1640 #else
1641 static inline void posix_cpu_timers_init(struct task_struct *tsk) { }
1642 #endif
1643
1644 static inline void init_task_pid_links(struct task_struct *task)
1645 {
1646         enum pid_type type;
1647
1648         for (type = PIDTYPE_PID; type < PIDTYPE_MAX; ++type) {
1649                 INIT_HLIST_NODE(&task->pid_links[type]);
1650         }
1651 }
1652
1653 static inline void
1654 init_task_pid(struct task_struct *task, enum pid_type type, struct pid *pid)
1655 {
1656         if (type == PIDTYPE_PID)
1657                 task->thread_pid = pid;
1658         else
1659                 task->signal->pids[type] = pid;
1660 }
1661
1662 static inline void rcu_copy_process(struct task_struct *p)
1663 {
1664 #ifdef CONFIG_PREEMPT_RCU
1665         p->rcu_read_lock_nesting = 0;
1666         p->rcu_read_unlock_special.s = 0;
1667         p->rcu_blocked_node = NULL;
1668         INIT_LIST_HEAD(&p->rcu_node_entry);
1669 #endif /* #ifdef CONFIG_PREEMPT_RCU */
1670 #ifdef CONFIG_TASKS_RCU
1671         p->rcu_tasks_holdout = false;
1672         INIT_LIST_HEAD(&p->rcu_tasks_holdout_list);
1673         p->rcu_tasks_idle_cpu = -1;
1674 #endif /* #ifdef CONFIG_TASKS_RCU */
1675 }
1676
1677 static int pidfd_release(struct inode *inode, struct file *file)
1678 {
1679         struct pid *pid = file->private_data;
1680
1681         file->private_data = NULL;
1682         put_pid(pid);
1683         return 0;
1684 }
1685
1686 #ifdef CONFIG_PROC_FS
1687 static void pidfd_show_fdinfo(struct seq_file *m, struct file *f)
1688 {
1689         struct pid_namespace *ns = proc_pid_ns(file_inode(m->file));
1690         struct pid *pid = f->private_data;
1691
1692         seq_put_decimal_ull(m, "Pid:\t", pid_nr_ns(pid, ns));
1693         seq_putc(m, '\n');
1694 }
1695 #endif
1696
1697 const struct file_operations pidfd_fops = {
1698         .release = pidfd_release,
1699 #ifdef CONFIG_PROC_FS
1700         .show_fdinfo = pidfd_show_fdinfo,
1701 #endif
1702 };
1703
1704 /**
1705  * pidfd_create() - Create a new pid file descriptor.
1706  *
1707  * @pid:  struct pid that the pidfd will reference
1708  *
1709  * This creates a new pid file descriptor with the O_CLOEXEC flag set.
1710  *
1711  * Note, that this function can only be called after the fd table has
1712  * been unshared to avoid leaking the pidfd to the new process.
1713  *
1714  * Return: On success, a cloexec pidfd is returned.
1715  *         On error, a negative errno number will be returned.
1716  */
1717 static int pidfd_create(struct pid *pid)
1718 {
1719         int fd;
1720
1721         fd = anon_inode_getfd("[pidfd]", &pidfd_fops, get_pid(pid),
1722                               O_RDWR | O_CLOEXEC);
1723         if (fd < 0)
1724                 put_pid(pid);
1725
1726         return fd;
1727 }
1728
1729 /*
1730  * This creates a new process as a copy of the old one,
1731  * but does not actually start it yet.
1732  *
1733  * It copies the registers, and all the appropriate
1734  * parts of the process environment (as per the clone
1735  * flags). The actual kick-off is left to the caller.
1736  */
1737 static __latent_entropy struct task_struct *copy_process(
1738                                         unsigned long clone_flags,
1739                                         unsigned long stack_start,
1740                                         unsigned long stack_size,
1741                                         int __user *parent_tidptr,
1742                                         int __user *child_tidptr,
1743                                         struct pid *pid,
1744                                         int trace,
1745                                         unsigned long tls,
1746                                         int node)
1747 {
1748         int pidfd = -1, retval;
1749         struct task_struct *p;
1750         struct multiprocess_signals delayed;
1751
1752         /*
1753          * Don't allow sharing the root directory with processes in a different
1754          * namespace
1755          */
1756         if ((clone_flags & (CLONE_NEWNS|CLONE_FS)) == (CLONE_NEWNS|CLONE_FS))
1757                 return ERR_PTR(-EINVAL);
1758
1759         if ((clone_flags & (CLONE_NEWUSER|CLONE_FS)) == (CLONE_NEWUSER|CLONE_FS))
1760                 return ERR_PTR(-EINVAL);
1761
1762         /*
1763          * Thread groups must share signals as well, and detached threads
1764          * can only be started up within the thread group.
1765          */
1766         if ((clone_flags & CLONE_THREAD) && !(clone_flags & CLONE_SIGHAND))
1767                 return ERR_PTR(-EINVAL);
1768
1769         /*
1770          * Shared signal handlers imply shared VM. By way of the above,
1771          * thread groups also imply shared VM. Blocking this case allows
1772          * for various simplifications in other code.
1773          */
1774         if ((clone_flags & CLONE_SIGHAND) && !(clone_flags & CLONE_VM))
1775                 return ERR_PTR(-EINVAL);
1776
1777         /*
1778          * Siblings of global init remain as zombies on exit since they are
1779          * not reaped by their parent (swapper). To solve this and to avoid
1780          * multi-rooted process trees, prevent global and container-inits
1781          * from creating siblings.
1782          */
1783         if ((clone_flags & CLONE_PARENT) &&
1784                                 current->signal->flags & SIGNAL_UNKILLABLE)
1785                 return ERR_PTR(-EINVAL);
1786
1787         /*
1788          * If the new process will be in a different pid or user namespace
1789          * do not allow it to share a thread group with the forking task.
1790          */
1791         if (clone_flags & CLONE_THREAD) {
1792                 if ((clone_flags & (CLONE_NEWUSER | CLONE_NEWPID)) ||
1793                     (task_active_pid_ns(current) !=
1794                                 current->nsproxy->pid_ns_for_children))
1795                         return ERR_PTR(-EINVAL);
1796         }
1797
1798         if (clone_flags & CLONE_PIDFD) {
1799                 int reserved;
1800
1801                 /*
1802                  * - CLONE_PARENT_SETTID is useless for pidfds and also
1803                  *   parent_tidptr is used to return pidfds.
1804                  * - CLONE_DETACHED is blocked so that we can potentially
1805                  *   reuse it later for CLONE_PIDFD.
1806                  * - CLONE_THREAD is blocked until someone really needs it.
1807                  */
1808                 if (clone_flags &
1809                     (CLONE_DETACHED | CLONE_PARENT_SETTID | CLONE_THREAD))
1810                         return ERR_PTR(-EINVAL);
1811
1812                 /*
1813                  * Verify that parent_tidptr is sane so we can potentially
1814                  * reuse it later.
1815                  */
1816                 if (get_user(reserved, parent_tidptr))
1817                         return ERR_PTR(-EFAULT);
1818
1819                 if (reserved != 0)
1820                         return ERR_PTR(-EINVAL);
1821         }
1822
1823         /*
1824          * Force any signals received before this point to be delivered
1825          * before the fork happens.  Collect up signals sent to multiple
1826          * processes that happen during the fork and delay them so that
1827          * they appear to happen after the fork.
1828          */
1829         sigemptyset(&delayed.signal);
1830         INIT_HLIST_NODE(&delayed.node);
1831
1832         spin_lock_irq(&current->sighand->siglock);
1833         if (!(clone_flags & CLONE_THREAD))
1834                 hlist_add_head(&delayed.node, &current->signal->multiprocess);
1835         recalc_sigpending();
1836         spin_unlock_irq(&current->sighand->siglock);
1837         retval = -ERESTARTNOINTR;
1838         if (signal_pending(current))
1839                 goto fork_out;
1840
1841         retval = -ENOMEM;
1842         p = dup_task_struct(current, node);
1843         if (!p)
1844                 goto fork_out;
1845
1846         /*
1847          * This _must_ happen before we call free_task(), i.e. before we jump
1848          * to any of the bad_fork_* labels. This is to avoid freeing
1849          * p->set_child_tid which is (ab)used as a kthread's data pointer for
1850          * kernel threads (PF_KTHREAD).
1851          */
1852         p->set_child_tid = (clone_flags & CLONE_CHILD_SETTID) ? child_tidptr : NULL;
1853         /*
1854          * Clear TID on mm_release()?
1855          */
1856         p->clear_child_tid = (clone_flags & CLONE_CHILD_CLEARTID) ? child_tidptr : NULL;
1857
1858         ftrace_graph_init_task(p);
1859
1860         rt_mutex_init_task(p);
1861
1862 #ifdef CONFIG_PROVE_LOCKING
1863         DEBUG_LOCKS_WARN_ON(!p->hardirqs_enabled);
1864         DEBUG_LOCKS_WARN_ON(!p->softirqs_enabled);
1865 #endif
1866         retval = -EAGAIN;
1867         if (atomic_read(&p->real_cred->user->processes) >=
1868                         task_rlimit(p, RLIMIT_NPROC)) {
1869                 if (p->real_cred->user != INIT_USER &&
1870                     !capable(CAP_SYS_RESOURCE) && !capable(CAP_SYS_ADMIN))
1871                         goto bad_fork_free;
1872         }
1873         current->flags &= ~PF_NPROC_EXCEEDED;
1874
1875         retval = copy_creds(p, clone_flags);
1876         if (retval < 0)
1877                 goto bad_fork_free;
1878
1879         /*
1880          * If multiple threads are within copy_process(), then this check
1881          * triggers too late. This doesn't hurt, the check is only there
1882          * to stop root fork bombs.
1883          */
1884         retval = -EAGAIN;
1885         if (nr_threads >= max_threads)
1886                 goto bad_fork_cleanup_count;
1887
1888         delayacct_tsk_init(p);  /* Must remain after dup_task_struct() */
1889         p->flags &= ~(PF_SUPERPRIV | PF_WQ_WORKER | PF_IDLE);
1890         p->flags |= PF_FORKNOEXEC;
1891         INIT_LIST_HEAD(&p->children);
1892         INIT_LIST_HEAD(&p->sibling);
1893         rcu_copy_process(p);
1894         p->vfork_done = NULL;
1895         spin_lock_init(&p->alloc_lock);
1896
1897         init_sigpending(&p->pending);
1898
1899         p->utime = p->stime = p->gtime = 0;
1900 #ifdef CONFIG_ARCH_HAS_SCALED_CPUTIME
1901         p->utimescaled = p->stimescaled = 0;
1902 #endif
1903         prev_cputime_init(&p->prev_cputime);
1904
1905 #ifdef CONFIG_VIRT_CPU_ACCOUNTING_GEN
1906         seqcount_init(&p->vtime.seqcount);
1907         p->vtime.starttime = 0;
1908         p->vtime.state = VTIME_INACTIVE;
1909 #endif
1910
1911 #if defined(SPLIT_RSS_COUNTING)
1912         memset(&p->rss_stat, 0, sizeof(p->rss_stat));
1913 #endif
1914
1915         p->default_timer_slack_ns = current->timer_slack_ns;
1916
1917 #ifdef CONFIG_PSI
1918         p->psi_flags = 0;
1919 #endif
1920
1921         task_io_accounting_init(&p->ioac);
1922         acct_clear_integrals(p);
1923
1924         posix_cpu_timers_init(p);
1925
1926         p->io_context = NULL;
1927         audit_set_context(p, NULL);
1928         cgroup_fork(p);
1929 #ifdef CONFIG_NUMA
1930         p->mempolicy = mpol_dup(p->mempolicy);
1931         if (IS_ERR(p->mempolicy)) {
1932                 retval = PTR_ERR(p->mempolicy);
1933                 p->mempolicy = NULL;
1934                 goto bad_fork_cleanup_threadgroup_lock;
1935         }
1936 #endif
1937 #ifdef CONFIG_CPUSETS
1938         p->cpuset_mem_spread_rotor = NUMA_NO_NODE;
1939         p->cpuset_slab_spread_rotor = NUMA_NO_NODE;
1940         seqcount_init(&p->mems_allowed_seq);
1941 #endif
1942 #ifdef CONFIG_TRACE_IRQFLAGS
1943         p->irq_events = 0;
1944         p->hardirqs_enabled = 0;
1945         p->hardirq_enable_ip = 0;
1946         p->hardirq_enable_event = 0;
1947         p->hardirq_disable_ip = _THIS_IP_;
1948         p->hardirq_disable_event = 0;
1949         p->softirqs_enabled = 1;
1950         p->softirq_enable_ip = _THIS_IP_;
1951         p->softirq_enable_event = 0;
1952         p->softirq_disable_ip = 0;
1953         p->softirq_disable_event = 0;
1954         p->hardirq_context = 0;
1955         p->softirq_context = 0;
1956 #endif
1957
1958         p->pagefault_disabled = 0;
1959
1960 #ifdef CONFIG_LOCKDEP
1961         p->lockdep_depth = 0; /* no locks held yet */
1962         p->curr_chain_key = 0;
1963         p->lockdep_recursion = 0;
1964         lockdep_init_task(p);
1965 #endif
1966
1967 #ifdef CONFIG_DEBUG_MUTEXES
1968         p->blocked_on = NULL; /* not blocked yet */
1969 #endif
1970 #ifdef CONFIG_BCACHE
1971         p->sequential_io        = 0;
1972         p->sequential_io_avg    = 0;
1973 #endif
1974
1975         /* Perform scheduler related setup. Assign this task to a CPU. */
1976         retval = sched_fork(clone_flags, p);
1977         if (retval)
1978                 goto bad_fork_cleanup_policy;
1979
1980         retval = perf_event_init_task(p);
1981         if (retval)
1982                 goto bad_fork_cleanup_policy;
1983         retval = audit_alloc(p);
1984         if (retval)
1985                 goto bad_fork_cleanup_perf;
1986         /* copy all the process information */
1987         shm_init_task(p);
1988         retval = security_task_alloc(p, clone_flags);
1989         if (retval)
1990                 goto bad_fork_cleanup_audit;
1991         retval = copy_semundo(clone_flags, p);
1992         if (retval)
1993                 goto bad_fork_cleanup_security;
1994         retval = copy_files(clone_flags, p);
1995         if (retval)
1996                 goto bad_fork_cleanup_semundo;
1997         retval = copy_fs(clone_flags, p);
1998         if (retval)
1999                 goto bad_fork_cleanup_files;
2000         retval = copy_sighand(clone_flags, p);
2001         if (retval)
2002                 goto bad_fork_cleanup_fs;
2003         retval = copy_signal(clone_flags, p);
2004         if (retval)
2005                 goto bad_fork_cleanup_sighand;
2006         retval = copy_mm(clone_flags, p);
2007         if (retval)
2008                 goto bad_fork_cleanup_signal;
2009         retval = copy_namespaces(clone_flags, p);
2010         if (retval)
2011                 goto bad_fork_cleanup_mm;
2012         retval = copy_io(clone_flags, p);
2013         if (retval)
2014                 goto bad_fork_cleanup_namespaces;
2015         retval = copy_thread_tls(clone_flags, stack_start, stack_size, p, tls);
2016         if (retval)
2017                 goto bad_fork_cleanup_io;
2018
2019         stackleak_task_init(p);
2020
2021         if (pid != &init_struct_pid) {
2022                 pid = alloc_pid(p->nsproxy->pid_ns_for_children);
2023                 if (IS_ERR(pid)) {
2024                         retval = PTR_ERR(pid);
2025                         goto bad_fork_cleanup_thread;
2026                 }
2027         }
2028
2029         /*
2030          * This has to happen after we've potentially unshared the file
2031          * descriptor table (so that the pidfd doesn't leak into the child
2032          * if the fd table isn't shared).
2033          */
2034         if (clone_flags & CLONE_PIDFD) {
2035                 retval = pidfd_create(pid);
2036                 if (retval < 0)
2037                         goto bad_fork_free_pid;
2038
2039                 pidfd = retval;
2040                 retval = put_user(pidfd, parent_tidptr);
2041                 if (retval)
2042                         goto bad_fork_put_pidfd;
2043         }
2044
2045 #ifdef CONFIG_BLOCK
2046         p->plug = NULL;
2047 #endif
2048 #ifdef CONFIG_FUTEX
2049         p->robust_list = NULL;
2050 #ifdef CONFIG_COMPAT
2051         p->compat_robust_list = NULL;
2052 #endif
2053         INIT_LIST_HEAD(&p->pi_state_list);
2054         p->pi_state_cache = NULL;
2055 #endif
2056         /*
2057          * sigaltstack should be cleared when sharing the same VM
2058          */
2059         if ((clone_flags & (CLONE_VM|CLONE_VFORK)) == CLONE_VM)
2060                 sas_ss_reset(p);
2061
2062         /*
2063          * Syscall tracing and stepping should be turned off in the
2064          * child regardless of CLONE_PTRACE.
2065          */
2066         user_disable_single_step(p);
2067         clear_tsk_thread_flag(p, TIF_SYSCALL_TRACE);
2068 #ifdef TIF_SYSCALL_EMU
2069         clear_tsk_thread_flag(p, TIF_SYSCALL_EMU);
2070 #endif
2071         clear_all_latency_tracing(p);
2072
2073         /* ok, now we should be set up.. */
2074         p->pid = pid_nr(pid);
2075         if (clone_flags & CLONE_THREAD) {
2076                 p->exit_signal = -1;
2077                 p->group_leader = current->group_leader;
2078                 p->tgid = current->tgid;
2079         } else {
2080                 if (clone_flags & CLONE_PARENT)
2081                         p->exit_signal = current->group_leader->exit_signal;
2082                 else
2083                         p->exit_signal = (clone_flags & CSIGNAL);
2084                 p->group_leader = p;
2085                 p->tgid = p->pid;
2086         }
2087
2088         p->nr_dirtied = 0;
2089         p->nr_dirtied_pause = 128 >> (PAGE_SHIFT - 10);
2090         p->dirty_paused_when = 0;
2091
2092         p->pdeath_signal = 0;
2093         INIT_LIST_HEAD(&p->thread_group);
2094         p->task_works = NULL;
2095
2096         cgroup_threadgroup_change_begin(current);
2097         /*
2098          * Ensure that the cgroup subsystem policies allow the new process to be
2099          * forked. It should be noted the the new process's css_set can be changed
2100          * between here and cgroup_post_fork() if an organisation operation is in
2101          * progress.
2102          */
2103         retval = cgroup_can_fork(p);
2104         if (retval)
2105                 goto bad_fork_cgroup_threadgroup_change_end;
2106
2107         /*
2108          * From this point on we must avoid any synchronous user-space
2109          * communication until we take the tasklist-lock. In particular, we do
2110          * not want user-space to be able to predict the process start-time by
2111          * stalling fork(2) after we recorded the start_time but before it is
2112          * visible to the system.
2113          */
2114
2115         p->start_time = ktime_get_ns();
2116         p->real_start_time = ktime_get_boot_ns();
2117
2118         /*
2119          * Make it visible to the rest of the system, but dont wake it up yet.
2120          * Need tasklist lock for parent etc handling!
2121          */
2122         write_lock_irq(&tasklist_lock);
2123
2124         /* CLONE_PARENT re-uses the old parent */
2125         if (clone_flags & (CLONE_PARENT|CLONE_THREAD)) {
2126                 p->real_parent = current->real_parent;
2127                 p->parent_exec_id = current->parent_exec_id;
2128         } else {
2129                 p->real_parent = current;
2130                 p->parent_exec_id = current->self_exec_id;
2131         }
2132
2133         klp_copy_process(p);
2134
2135         spin_lock(&current->sighand->siglock);
2136
2137         /*
2138          * Copy seccomp details explicitly here, in case they were changed
2139          * before holding sighand lock.
2140          */
2141         copy_seccomp(p);
2142
2143         rseq_fork(p, clone_flags);
2144
2145         /* Don't start children in a dying pid namespace */
2146         if (unlikely(!(ns_of_pid(pid)->pid_allocated & PIDNS_ADDING))) {
2147                 retval = -ENOMEM;
2148                 goto bad_fork_cancel_cgroup;
2149         }
2150
2151         /* Let kill terminate clone/fork in the middle */
2152         if (fatal_signal_pending(current)) {
2153                 retval = -EINTR;
2154                 goto bad_fork_cancel_cgroup;
2155         }
2156
2157
2158         init_task_pid_links(p);
2159         if (likely(p->pid)) {
2160                 ptrace_init_task(p, (clone_flags & CLONE_PTRACE) || trace);
2161
2162                 init_task_pid(p, PIDTYPE_PID, pid);
2163                 if (thread_group_leader(p)) {
2164                         init_task_pid(p, PIDTYPE_TGID, pid);
2165                         init_task_pid(p, PIDTYPE_PGID, task_pgrp(current));
2166                         init_task_pid(p, PIDTYPE_SID, task_session(current));
2167
2168                         if (is_child_reaper(pid)) {
2169                                 ns_of_pid(pid)->child_reaper = p;
2170                                 p->signal->flags |= SIGNAL_UNKILLABLE;
2171                         }
2172                         p->signal->shared_pending.signal = delayed.signal;
2173                         p->signal->tty = tty_kref_get(current->signal->tty);
2174                         /*
2175                          * Inherit has_child_subreaper flag under the same
2176                          * tasklist_lock with adding child to the process tree
2177                          * for propagate_has_child_subreaper optimization.
2178                          */
2179                         p->signal->has_child_subreaper = p->real_parent->signal->has_child_subreaper ||
2180                                                          p->real_parent->signal->is_child_subreaper;
2181                         list_add_tail(&p->sibling, &p->real_parent->children);
2182                         list_add_tail_rcu(&p->tasks, &init_task.tasks);
2183                         attach_pid(p, PIDTYPE_TGID);
2184                         attach_pid(p, PIDTYPE_PGID);
2185                         attach_pid(p, PIDTYPE_SID);
2186                         __this_cpu_inc(process_counts);
2187                 } else {
2188                         current->signal->nr_threads++;
2189                         atomic_inc(&current->signal->live);
2190                         refcount_inc(&current->signal->sigcnt);
2191                         task_join_group_stop(p);
2192                         list_add_tail_rcu(&p->thread_group,
2193                                           &p->group_leader->thread_group);
2194                         list_add_tail_rcu(&p->thread_node,
2195                                           &p->signal->thread_head);
2196                 }
2197                 attach_pid(p, PIDTYPE_PID);
2198                 nr_threads++;
2199         }
2200         total_forks++;
2201         hlist_del_init(&delayed.node);
2202         spin_unlock(&current->sighand->siglock);
2203         syscall_tracepoint_update(p);
2204         write_unlock_irq(&tasklist_lock);
2205
2206         proc_fork_connector(p);
2207         cgroup_post_fork(p);
2208         cgroup_threadgroup_change_end(current);
2209         perf_event_fork(p);
2210
2211         trace_task_newtask(p, clone_flags);
2212         uprobe_copy_process(p, clone_flags);
2213
2214         return p;
2215
2216 bad_fork_cancel_cgroup:
2217         spin_unlock(&current->sighand->siglock);
2218         write_unlock_irq(&tasklist_lock);
2219         cgroup_cancel_fork(p);
2220 bad_fork_cgroup_threadgroup_change_end:
2221         cgroup_threadgroup_change_end(current);
2222 bad_fork_put_pidfd:
2223         if (clone_flags & CLONE_PIDFD)
2224                 ksys_close(pidfd);
2225 bad_fork_free_pid:
2226         if (pid != &init_struct_pid)
2227                 free_pid(pid);
2228 bad_fork_cleanup_thread:
2229         exit_thread(p);
2230 bad_fork_cleanup_io:
2231         if (p->io_context)
2232                 exit_io_context(p);
2233 bad_fork_cleanup_namespaces:
2234         exit_task_namespaces(p);
2235 bad_fork_cleanup_mm:
2236         if (p->mm)
2237                 mmput(p->mm);
2238 bad_fork_cleanup_signal:
2239         if (!(clone_flags & CLONE_THREAD))
2240                 free_signal_struct(p->signal);
2241 bad_fork_cleanup_sighand:
2242         __cleanup_sighand(p->sighand);
2243 bad_fork_cleanup_fs:
2244         exit_fs(p); /* blocking */
2245 bad_fork_cleanup_files:
2246         exit_files(p); /* blocking */
2247 bad_fork_cleanup_semundo:
2248         exit_sem(p);
2249 bad_fork_cleanup_security:
2250         security_task_free(p);
2251 bad_fork_cleanup_audit:
2252         audit_free(p);
2253 bad_fork_cleanup_perf:
2254         perf_event_free_task(p);
2255 bad_fork_cleanup_policy:
2256         lockdep_free_task(p);
2257 #ifdef CONFIG_NUMA
2258         mpol_put(p->mempolicy);
2259 bad_fork_cleanup_threadgroup_lock:
2260 #endif
2261         delayacct_tsk_free(p);
2262 bad_fork_cleanup_count:
2263         atomic_dec(&p->cred->user->processes);
2264         exit_creds(p);
2265 bad_fork_free:
2266         p->state = TASK_DEAD;
2267         put_task_stack(p);
2268         free_task(p);
2269 fork_out:
2270         spin_lock_irq(&current->sighand->siglock);
2271         hlist_del_init(&delayed.node);
2272         spin_unlock_irq(&current->sighand->siglock);
2273         return ERR_PTR(retval);
2274 }
2275
2276 static inline void init_idle_pids(struct task_struct *idle)
2277 {
2278         enum pid_type type;
2279
2280         for (type = PIDTYPE_PID; type < PIDTYPE_MAX; ++type) {
2281                 INIT_HLIST_NODE(&idle->pid_links[type]); /* not really needed */
2282                 init_task_pid(idle, type, &init_struct_pid);
2283         }
2284 }
2285
2286 struct task_struct *fork_idle(int cpu)
2287 {
2288         struct task_struct *task;
2289         task = copy_process(CLONE_VM, 0, 0, NULL, NULL, &init_struct_pid, 0, 0,
2290                             cpu_to_node(cpu));
2291         if (!IS_ERR(task)) {
2292                 init_idle_pids(task);
2293                 init_idle(task, cpu);
2294         }
2295
2296         return task;
2297 }
2298
2299 struct mm_struct *copy_init_mm(void)
2300 {
2301         return dup_mm(NULL, &init_mm);
2302 }
2303
2304 /*
2305  *  Ok, this is the main fork-routine.
2306  *
2307  * It copies the process, and if successful kick-starts
2308  * it and waits for it to finish using the VM if required.
2309  */
2310 long _do_fork(unsigned long clone_flags,
2311               unsigned long stack_start,
2312               unsigned long stack_size,
2313               int __user *parent_tidptr,
2314               int __user *child_tidptr,
2315               unsigned long tls)
2316 {
2317         struct completion vfork;
2318         struct pid *pid;
2319         struct task_struct *p;
2320         int trace = 0;
2321         long nr;
2322
2323         /*
2324          * Determine whether and which event to report to ptracer.  When
2325          * called from kernel_thread or CLONE_UNTRACED is explicitly
2326          * requested, no event is reported; otherwise, report if the event
2327          * for the type of forking is enabled.
2328          */
2329         if (!(clone_flags & CLONE_UNTRACED)) {
2330                 if (clone_flags & CLONE_VFORK)
2331                         trace = PTRACE_EVENT_VFORK;
2332                 else if ((clone_flags & CSIGNAL) != SIGCHLD)
2333                         trace = PTRACE_EVENT_CLONE;
2334                 else
2335                         trace = PTRACE_EVENT_FORK;
2336
2337                 if (likely(!ptrace_event_enabled(current, trace)))
2338                         trace = 0;
2339         }
2340
2341         p = copy_process(clone_flags, stack_start, stack_size, parent_tidptr,
2342                          child_tidptr, NULL, trace, tls, NUMA_NO_NODE);
2343         add_latent_entropy();
2344
2345         if (IS_ERR(p))
2346                 return PTR_ERR(p);
2347
2348         /*
2349          * Do this prior waking up the new thread - the thread pointer
2350          * might get invalid after that point, if the thread exits quickly.
2351          */
2352         trace_sched_process_fork(current, p);
2353
2354         pid = get_task_pid(p, PIDTYPE_PID);
2355         nr = pid_vnr(pid);
2356
2357         if (clone_flags & CLONE_PARENT_SETTID)
2358                 put_user(nr, parent_tidptr);
2359
2360         if (clone_flags & CLONE_VFORK) {
2361                 p->vfork_done = &vfork;
2362                 init_completion(&vfork);
2363                 get_task_struct(p);
2364         }
2365
2366         wake_up_new_task(p);
2367
2368         /* forking complete and child started to run, tell ptracer */
2369         if (unlikely(trace))
2370                 ptrace_event_pid(trace, pid);
2371
2372         if (clone_flags & CLONE_VFORK) {
2373                 if (!wait_for_vfork_done(p, &vfork))
2374                         ptrace_event_pid(PTRACE_EVENT_VFORK_DONE, pid);
2375         }
2376
2377         put_pid(pid);
2378         return nr;
2379 }
2380
2381 #ifndef CONFIG_HAVE_COPY_THREAD_TLS
2382 /* For compatibility with architectures that call do_fork directly rather than
2383  * using the syscall entry points below. */
2384 long do_fork(unsigned long clone_flags,
2385               unsigned long stack_start,
2386               unsigned long stack_size,
2387               int __user *parent_tidptr,
2388               int __user *child_tidptr)
2389 {
2390         return _do_fork(clone_flags, stack_start, stack_size,
2391                         parent_tidptr, child_tidptr, 0);
2392 }
2393 #endif
2394
2395 /*
2396  * Create a kernel thread.
2397  */
2398 pid_t kernel_thread(int (*fn)(void *), void *arg, unsigned long flags)
2399 {
2400         return _do_fork(flags|CLONE_VM|CLONE_UNTRACED, (unsigned long)fn,
2401                 (unsigned long)arg, NULL, NULL, 0);
2402 }
2403
2404 #ifdef __ARCH_WANT_SYS_FORK
2405 SYSCALL_DEFINE0(fork)
2406 {
2407 #ifdef CONFIG_MMU
2408         return _do_fork(SIGCHLD, 0, 0, NULL, NULL, 0);
2409 #else
2410         /* can not support in nommu mode */
2411         return -EINVAL;
2412 #endif
2413 }
2414 #endif
2415
2416 #ifdef __ARCH_WANT_SYS_VFORK
2417 SYSCALL_DEFINE0(vfork)
2418 {
2419         return _do_fork(CLONE_VFORK | CLONE_VM | SIGCHLD, 0,
2420                         0, NULL, NULL, 0);
2421 }
2422 #endif
2423
2424 #ifdef __ARCH_WANT_SYS_CLONE
2425 #ifdef CONFIG_CLONE_BACKWARDS
2426 SYSCALL_DEFINE5(clone, unsigned long, clone_flags, unsigned long, newsp,
2427                  int __user *, parent_tidptr,
2428                  unsigned long, tls,
2429                  int __user *, child_tidptr)
2430 #elif defined(CONFIG_CLONE_BACKWARDS2)
2431 SYSCALL_DEFINE5(clone, unsigned long, newsp, unsigned long, clone_flags,
2432                  int __user *, parent_tidptr,
2433                  int __user *, child_tidptr,
2434                  unsigned long, tls)
2435 #elif defined(CONFIG_CLONE_BACKWARDS3)
2436 SYSCALL_DEFINE6(clone, unsigned long, clone_flags, unsigned long, newsp,
2437                 int, stack_size,
2438                 int __user *, parent_tidptr,
2439                 int __user *, child_tidptr,
2440                 unsigned long, tls)
2441 #else
2442 SYSCALL_DEFINE5(clone, unsigned long, clone_flags, unsigned long, newsp,
2443                  int __user *, parent_tidptr,
2444                  int __user *, child_tidptr,
2445                  unsigned long, tls)
2446 #endif
2447 {
2448         return _do_fork(clone_flags, newsp, 0, parent_tidptr, child_tidptr, tls);
2449 }
2450 #endif
2451
2452 void walk_process_tree(struct task_struct *top, proc_visitor visitor, void *data)
2453 {
2454         struct task_struct *leader, *parent, *child;
2455         int res;
2456
2457         read_lock(&tasklist_lock);
2458         leader = top = top->group_leader;
2459 down:
2460         for_each_thread(leader, parent) {
2461                 list_for_each_entry(child, &parent->children, sibling) {
2462                         res = visitor(child, data);
2463                         if (res) {
2464                                 if (res < 0)
2465                                         goto out;
2466                                 leader = child;
2467                                 goto down;
2468                         }
2469 up:
2470                         ;
2471                 }
2472         }
2473
2474         if (leader != top) {
2475                 child = leader;
2476                 parent = child->real_parent;
2477                 leader = parent->group_leader;
2478                 goto up;
2479         }
2480 out:
2481         read_unlock(&tasklist_lock);
2482 }
2483
2484 #ifndef ARCH_MIN_MMSTRUCT_ALIGN
2485 #define ARCH_MIN_MMSTRUCT_ALIGN 0
2486 #endif
2487
2488 static void sighand_ctor(void *data)
2489 {
2490         struct sighand_struct *sighand = data;
2491
2492         spin_lock_init(&sighand->siglock);
2493         init_waitqueue_head(&sighand->signalfd_wqh);
2494 }
2495
2496 void __init proc_caches_init(void)
2497 {
2498         unsigned int mm_size;
2499
2500         sighand_cachep = kmem_cache_create("sighand_cache",
2501                         sizeof(struct sighand_struct), 0,
2502                         SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_TYPESAFE_BY_RCU|
2503                         SLAB_ACCOUNT, sighand_ctor);
2504         signal_cachep = kmem_cache_create("signal_cache",
2505                         sizeof(struct signal_struct), 0,
2506                         SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_ACCOUNT,
2507                         NULL);
2508         files_cachep = kmem_cache_create("files_cache",
2509                         sizeof(struct files_struct), 0,
2510                         SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_ACCOUNT,
2511                         NULL);
2512         fs_cachep = kmem_cache_create("fs_cache",
2513                         sizeof(struct fs_struct), 0,
2514                         SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_ACCOUNT,
2515                         NULL);
2516
2517         /*
2518          * The mm_cpumask is located at the end of mm_struct, and is
2519          * dynamically sized based on the maximum CPU number this system
2520          * can have, taking hotplug into account (nr_cpu_ids).
2521          */
2522         mm_size = sizeof(struct mm_struct) + cpumask_size();
2523
2524         mm_cachep = kmem_cache_create_usercopy("mm_struct",
2525                         mm_size, ARCH_MIN_MMSTRUCT_ALIGN,
2526                         SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_ACCOUNT,
2527                         offsetof(struct mm_struct, saved_auxv),
2528                         sizeof_field(struct mm_struct, saved_auxv),
2529                         NULL);
2530         vm_area_cachep = KMEM_CACHE(vm_area_struct, SLAB_PANIC|SLAB_ACCOUNT);
2531         mmap_init();
2532         nsproxy_cache_init();
2533 }
2534
2535 /*
2536  * Check constraints on flags passed to the unshare system call.
2537  */
2538 static int check_unshare_flags(unsigned long unshare_flags)
2539 {
2540         if (unshare_flags & ~(CLONE_THREAD|CLONE_FS|CLONE_NEWNS|CLONE_SIGHAND|
2541                                 CLONE_VM|CLONE_FILES|CLONE_SYSVSEM|
2542                                 CLONE_NEWUTS|CLONE_NEWIPC|CLONE_NEWNET|
2543                                 CLONE_NEWUSER|CLONE_NEWPID|CLONE_NEWCGROUP))
2544                 return -EINVAL;
2545         /*
2546          * Not implemented, but pretend it works if there is nothing
2547          * to unshare.  Note that unsharing the address space or the
2548          * signal handlers also need to unshare the signal queues (aka
2549          * CLONE_THREAD).
2550          */
2551         if (unshare_flags & (CLONE_THREAD | CLONE_SIGHAND | CLONE_VM)) {
2552                 if (!thread_group_empty(current))
2553                         return -EINVAL;
2554         }
2555         if (unshare_flags & (CLONE_SIGHAND | CLONE_VM)) {
2556                 if (refcount_read(&current->sighand->count) > 1)
2557                         return -EINVAL;
2558         }
2559         if (unshare_flags & CLONE_VM) {
2560                 if (!current_is_single_threaded())
2561                         return -EINVAL;
2562         }
2563
2564         return 0;
2565 }
2566
2567 /*
2568  * Unshare the filesystem structure if it is being shared
2569  */
2570 static int unshare_fs(unsigned long unshare_flags, struct fs_struct **new_fsp)
2571 {
2572         struct fs_struct *fs = current->fs;
2573
2574         if (!(unshare_flags & CLONE_FS) || !fs)
2575                 return 0;
2576
2577         /* don't need lock here; in the worst case we'll do useless copy */
2578         if (fs->users == 1)
2579                 return 0;
2580
2581         *new_fsp = copy_fs_struct(fs);
2582         if (!*new_fsp)
2583                 return -ENOMEM;
2584
2585         return 0;
2586 }
2587
2588 /*
2589  * Unshare file descriptor table if it is being shared
2590  */
2591 static int unshare_fd(unsigned long unshare_flags, struct files_struct **new_fdp)
2592 {
2593         struct files_struct *fd = current->files;
2594         int error = 0;
2595
2596         if ((unshare_flags & CLONE_FILES) &&
2597             (fd && atomic_read(&fd->count) > 1)) {
2598                 *new_fdp = dup_fd(fd, &error);
2599                 if (!*new_fdp)
2600                         return error;
2601         }
2602
2603         return 0;
2604 }
2605
2606 /*
2607  * unshare allows a process to 'unshare' part of the process
2608  * context which was originally shared using clone.  copy_*
2609  * functions used by do_fork() cannot be used here directly
2610  * because they modify an inactive task_struct that is being
2611  * constructed. Here we are modifying the current, active,
2612  * task_struct.
2613  */
2614 int ksys_unshare(unsigned long unshare_flags)
2615 {
2616         struct fs_struct *fs, *new_fs = NULL;
2617         struct files_struct *fd, *new_fd = NULL;
2618         struct cred *new_cred = NULL;
2619         struct nsproxy *new_nsproxy = NULL;
2620         int do_sysvsem = 0;
2621         int err;
2622
2623         /*
2624          * If unsharing a user namespace must also unshare the thread group
2625          * and unshare the filesystem root and working directories.
2626          */
2627         if (unshare_flags & CLONE_NEWUSER)
2628                 unshare_flags |= CLONE_THREAD | CLONE_FS;
2629         /*
2630          * If unsharing vm, must also unshare signal handlers.
2631          */
2632         if (unshare_flags & CLONE_VM)
2633                 unshare_flags |= CLONE_SIGHAND;
2634         /*
2635          * If unsharing a signal handlers, must also unshare the signal queues.
2636          */
2637         if (unshare_flags & CLONE_SIGHAND)
2638                 unshare_flags |= CLONE_THREAD;
2639         /*
2640          * If unsharing namespace, must also unshare filesystem information.
2641          */
2642         if (unshare_flags & CLONE_NEWNS)
2643                 unshare_flags |= CLONE_FS;
2644
2645         err = check_unshare_flags(unshare_flags);
2646         if (err)
2647                 goto bad_unshare_out;
2648         /*
2649          * CLONE_NEWIPC must also detach from the undolist: after switching
2650          * to a new ipc namespace, the semaphore arrays from the old
2651          * namespace are unreachable.
2652          */
2653         if (unshare_flags & (CLONE_NEWIPC|CLONE_SYSVSEM))
2654                 do_sysvsem = 1;
2655         err = unshare_fs(unshare_flags, &new_fs);
2656         if (err)
2657                 goto bad_unshare_out;
2658         err = unshare_fd(unshare_flags, &new_fd);
2659         if (err)
2660                 goto bad_unshare_cleanup_fs;
2661         err = unshare_userns(unshare_flags, &new_cred);
2662         if (err)
2663                 goto bad_unshare_cleanup_fd;
2664         err = unshare_nsproxy_namespaces(unshare_flags, &new_nsproxy,
2665                                          new_cred, new_fs);
2666         if (err)
2667                 goto bad_unshare_cleanup_cred;
2668
2669         if (new_fs || new_fd || do_sysvsem || new_cred || new_nsproxy) {
2670                 if (do_sysvsem) {
2671                         /*
2672                          * CLONE_SYSVSEM is equivalent to sys_exit().
2673                          */
2674                         exit_sem(current);
2675                 }
2676                 if (unshare_flags & CLONE_NEWIPC) {
2677                         /* Orphan segments in old ns (see sem above). */
2678                         exit_shm(current);
2679                         shm_init_task(current);
2680                 }
2681
2682                 if (new_nsproxy)
2683                         switch_task_namespaces(current, new_nsproxy);
2684
2685                 task_lock(current);
2686
2687                 if (new_fs) {
2688                         fs = current->fs;
2689                         spin_lock(&fs->lock);
2690                         current->fs = new_fs;
2691                         if (--fs->users)
2692                                 new_fs = NULL;
2693                         else
2694                                 new_fs = fs;
2695                         spin_unlock(&fs->lock);
2696                 }
2697
2698                 if (new_fd) {
2699                         fd = current->files;
2700                         current->files = new_fd;
2701                         new_fd = fd;
2702                 }
2703
2704                 task_unlock(current);
2705
2706                 if (new_cred) {
2707                         /* Install the new user namespace */
2708                         commit_creds(new_cred);
2709                         new_cred = NULL;
2710                 }
2711         }
2712
2713         perf_event_namespaces(current);
2714
2715 bad_unshare_cleanup_cred:
2716         if (new_cred)
2717                 put_cred(new_cred);
2718 bad_unshare_cleanup_fd:
2719         if (new_fd)
2720                 put_files_struct(new_fd);
2721
2722 bad_unshare_cleanup_fs:
2723         if (new_fs)
2724                 free_fs_struct(new_fs);
2725
2726 bad_unshare_out:
2727         return err;
2728 }
2729
2730 SYSCALL_DEFINE1(unshare, unsigned long, unshare_flags)
2731 {
2732         return ksys_unshare(unshare_flags);
2733 }
2734
2735 /*
2736  *      Helper to unshare the files of the current task.
2737  *      We don't want to expose copy_files internals to
2738  *      the exec layer of the kernel.
2739  */
2740
2741 int unshare_files(struct files_struct **displaced)
2742 {
2743         struct task_struct *task = current;
2744         struct files_struct *copy = NULL;
2745         int error;
2746
2747         error = unshare_fd(CLONE_FILES, &copy);
2748         if (error || !copy) {
2749                 *displaced = NULL;
2750                 return error;
2751         }
2752         *displaced = task->files;
2753         task_lock(task);
2754         task->files = copy;
2755         task_unlock(task);
2756         return 0;
2757 }
2758
2759 int sysctl_max_threads(struct ctl_table *table, int write,
2760                        void __user *buffer, size_t *lenp, loff_t *ppos)
2761 {
2762         struct ctl_table t;
2763         int ret;
2764         int threads = max_threads;
2765         int min = MIN_THREADS;
2766         int max = MAX_THREADS;
2767
2768         t = *table;
2769         t.data = &threads;
2770         t.extra1 = &min;
2771         t.extra2 = &max;
2772
2773         ret = proc_dointvec_minmax(&t, write, buffer, lenp, ppos);
2774         if (ret || !write)
2775                 return ret;
2776
2777         set_max_threads(threads);
2778
2779         return 0;
2780 }