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