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