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