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