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