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