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 #if defined(CONFIG_TRANSPARENT_HUGEPAGE) && !defined(CONFIG_SPLIT_PMD_PTLOCKS) 1310 mm->pmd_huge_pte = NULL; 1311 #endif 1312 mm_init_uprobes_state(mm); 1313 hugetlb_count_init(mm); 1314 1315 if (current->mm) { 1316 mm->flags = mmf_init_flags(current->mm->flags); 1317 mm->def_flags = current->mm->def_flags & VM_INIT_DEF_MASK; 1318 } else { 1319 mm->flags = default_dump_filter; 1320 mm->def_flags = 0; 1321 } 1322 1323 if (mm_alloc_pgd(mm)) 1324 goto fail_nopgd; 1325 1326 if (mm_alloc_id(mm)) 1327 goto fail_noid; 1328 1329 if (init_new_context(p, mm)) 1330 goto fail_nocontext; 1331 1332 if (mm_alloc_cid(mm, p)) 1333 goto fail_cid; 1334 1335 if (percpu_counter_init_many(mm->rss_stat, 0, GFP_KERNEL_ACCOUNT, 1336 NR_MM_COUNTERS)) 1337 goto fail_pcpu; 1338 1339 mm->user_ns = get_user_ns(user_ns); 1340 lru_gen_init_mm(mm); 1341 return mm; 1342 1343 fail_pcpu: 1344 mm_destroy_cid(mm); 1345 fail_cid: 1346 destroy_context(mm); 1347 fail_nocontext: 1348 mm_free_id(mm); 1349 fail_noid: 1350 mm_free_pgd(mm); 1351 fail_nopgd: 1352 free_mm(mm); 1353 return NULL; 1354 } 1355 1356 /* 1357 * Allocate and initialize an mm_struct. 1358 */ 1359 struct mm_struct *mm_alloc(void) 1360 { 1361 struct mm_struct *mm; 1362 1363 mm = allocate_mm(); 1364 if (!mm) 1365 return NULL; 1366 1367 memset(mm, 0, sizeof(*mm)); 1368 return mm_init(mm, current, current_user_ns()); 1369 } 1370 EXPORT_SYMBOL_IF_KUNIT(mm_alloc); 1371 1372 static inline void __mmput(struct mm_struct *mm) 1373 { 1374 VM_BUG_ON(atomic_read(&mm->mm_users)); 1375 1376 uprobe_clear_state(mm); 1377 exit_aio(mm); 1378 ksm_exit(mm); 1379 khugepaged_exit(mm); /* must run before exit_mmap */ 1380 exit_mmap(mm); 1381 mm_put_huge_zero_folio(mm); 1382 set_mm_exe_file(mm, NULL); 1383 if (!list_empty(&mm->mmlist)) { 1384 spin_lock(&mmlist_lock); 1385 list_del(&mm->mmlist); 1386 spin_unlock(&mmlist_lock); 1387 } 1388 if (mm->binfmt) 1389 module_put(mm->binfmt->module); 1390 lru_gen_del_mm(mm); 1391 mmdrop(mm); 1392 } 1393 1394 /* 1395 * Decrement the use count and release all resources for an mm. 1396 */ 1397 void mmput(struct mm_struct *mm) 1398 { 1399 might_sleep(); 1400 1401 if (atomic_dec_and_test(&mm->mm_users)) 1402 __mmput(mm); 1403 } 1404 EXPORT_SYMBOL_GPL(mmput); 1405 1406 #ifdef CONFIG_MMU 1407 static void mmput_async_fn(struct work_struct *work) 1408 { 1409 struct mm_struct *mm = container_of(work, struct mm_struct, 1410 async_put_work); 1411 1412 __mmput(mm); 1413 } 1414 1415 void mmput_async(struct mm_struct *mm) 1416 { 1417 if (atomic_dec_and_test(&mm->mm_users)) { 1418 INIT_WORK(&mm->async_put_work, mmput_async_fn); 1419 schedule_work(&mm->async_put_work); 1420 } 1421 } 1422 EXPORT_SYMBOL_GPL(mmput_async); 1423 #endif 1424 1425 /** 1426 * set_mm_exe_file - change a reference to the mm's executable file 1427 * @mm: The mm to change. 1428 * @new_exe_file: The new file to use. 1429 * 1430 * This changes mm's executable file (shown as symlink /proc/[pid]/exe). 1431 * 1432 * Main users are mmput() and sys_execve(). Callers prevent concurrent 1433 * invocations: in mmput() nobody alive left, in execve it happens before 1434 * the new mm is made visible to anyone. 1435 * 1436 * Can only fail if new_exe_file != NULL. 1437 */ 1438 int set_mm_exe_file(struct mm_struct *mm, struct file *new_exe_file) 1439 { 1440 struct file *old_exe_file; 1441 1442 /* 1443 * It is safe to dereference the exe_file without RCU as 1444 * this function is only called if nobody else can access 1445 * this mm -- see comment above for justification. 1446 */ 1447 old_exe_file = rcu_dereference_raw(mm->exe_file); 1448 1449 if (new_exe_file) { 1450 /* 1451 * We expect the caller (i.e., sys_execve) to already denied 1452 * write access, so this is unlikely to fail. 1453 */ 1454 if (unlikely(exe_file_deny_write_access(new_exe_file))) 1455 return -EACCES; 1456 get_file(new_exe_file); 1457 } 1458 rcu_assign_pointer(mm->exe_file, new_exe_file); 1459 if (old_exe_file) { 1460 exe_file_allow_write_access(old_exe_file); 1461 fput(old_exe_file); 1462 } 1463 return 0; 1464 } 1465 1466 /** 1467 * replace_mm_exe_file - replace a reference to the mm's executable file 1468 * @mm: The mm to change. 1469 * @new_exe_file: The new file to use. 1470 * 1471 * This changes mm's executable file (shown as symlink /proc/[pid]/exe). 1472 * 1473 * Main user is sys_prctl(PR_SET_MM_MAP/EXE_FILE). 1474 */ 1475 int replace_mm_exe_file(struct mm_struct *mm, struct file *new_exe_file) 1476 { 1477 struct vm_area_struct *vma; 1478 struct file *old_exe_file; 1479 int ret = 0; 1480 1481 /* Forbid mm->exe_file change if old file still mapped. */ 1482 old_exe_file = get_mm_exe_file(mm); 1483 if (old_exe_file) { 1484 VMA_ITERATOR(vmi, mm, 0); 1485 mmap_read_lock(mm); 1486 for_each_vma(vmi, vma) { 1487 if (!vma->vm_file) 1488 continue; 1489 if (path_equal(&vma->vm_file->f_path, 1490 &old_exe_file->f_path)) { 1491 ret = -EBUSY; 1492 break; 1493 } 1494 } 1495 mmap_read_unlock(mm); 1496 fput(old_exe_file); 1497 if (ret) 1498 return ret; 1499 } 1500 1501 ret = exe_file_deny_write_access(new_exe_file); 1502 if (ret) 1503 return -EACCES; 1504 get_file(new_exe_file); 1505 1506 /* set the new file */ 1507 mmap_write_lock(mm); 1508 old_exe_file = rcu_dereference_raw(mm->exe_file); 1509 rcu_assign_pointer(mm->exe_file, new_exe_file); 1510 mmap_write_unlock(mm); 1511 1512 if (old_exe_file) { 1513 exe_file_allow_write_access(old_exe_file); 1514 fput(old_exe_file); 1515 } 1516 return 0; 1517 } 1518 1519 /** 1520 * get_mm_exe_file - acquire a reference to the mm's executable file 1521 * @mm: The mm of interest. 1522 * 1523 * Returns %NULL if mm has no associated executable file. 1524 * User must release file via fput(). 1525 */ 1526 struct file *get_mm_exe_file(struct mm_struct *mm) 1527 { 1528 struct file *exe_file; 1529 1530 rcu_read_lock(); 1531 exe_file = get_file_rcu(&mm->exe_file); 1532 rcu_read_unlock(); 1533 return exe_file; 1534 } 1535 1536 /** 1537 * get_task_exe_file - acquire a reference to the task's executable file 1538 * @task: The task. 1539 * 1540 * Returns %NULL if task's mm (if any) has no associated executable file or 1541 * this is a kernel thread with borrowed mm (see the comment above get_task_mm). 1542 * User must release file via fput(). 1543 */ 1544 struct file *get_task_exe_file(struct task_struct *task) 1545 { 1546 struct file *exe_file = NULL; 1547 struct mm_struct *mm; 1548 1549 if (task->flags & PF_KTHREAD) 1550 return NULL; 1551 1552 task_lock(task); 1553 mm = task->mm; 1554 if (mm) 1555 exe_file = get_mm_exe_file(mm); 1556 task_unlock(task); 1557 return exe_file; 1558 } 1559 1560 /** 1561 * get_task_mm - acquire a reference to the task's mm 1562 * @task: The task. 1563 * 1564 * Returns %NULL if the task has no mm. Checks PF_KTHREAD (meaning 1565 * this kernel workthread has transiently adopted a user mm with use_mm, 1566 * to do its AIO) is not set and if so returns a reference to it, after 1567 * bumping up the use count. User must release the mm via mmput() 1568 * after use. Typically used by /proc and ptrace. 1569 */ 1570 struct mm_struct *get_task_mm(struct task_struct *task) 1571 { 1572 struct mm_struct *mm; 1573 1574 if (task->flags & PF_KTHREAD) 1575 return NULL; 1576 1577 task_lock(task); 1578 mm = task->mm; 1579 if (mm) 1580 mmget(mm); 1581 task_unlock(task); 1582 return mm; 1583 } 1584 EXPORT_SYMBOL_GPL(get_task_mm); 1585 1586 static bool may_access_mm(struct mm_struct *mm, struct task_struct *task, unsigned int mode) 1587 { 1588 if (mm == current->mm) 1589 return true; 1590 if (ptrace_may_access(task, mode)) 1591 return true; 1592 if ((mode & PTRACE_MODE_READ) && perfmon_capable()) 1593 return true; 1594 return false; 1595 } 1596 1597 struct mm_struct *mm_access(struct task_struct *task, unsigned int mode) 1598 { 1599 struct mm_struct *mm; 1600 int err; 1601 1602 err = down_read_killable(&task->signal->exec_update_lock); 1603 if (err) 1604 return ERR_PTR(err); 1605 1606 mm = get_task_mm(task); 1607 if (!mm) { 1608 mm = ERR_PTR(-ESRCH); 1609 } else if (!may_access_mm(mm, task, mode)) { 1610 mmput(mm); 1611 mm = ERR_PTR(-EACCES); 1612 } 1613 up_read(&task->signal->exec_update_lock); 1614 1615 return mm; 1616 } 1617 1618 static void complete_vfork_done(struct task_struct *tsk) 1619 { 1620 struct completion *vfork; 1621 1622 task_lock(tsk); 1623 vfork = tsk->vfork_done; 1624 if (likely(vfork)) { 1625 tsk->vfork_done = NULL; 1626 complete(vfork); 1627 } 1628 task_unlock(tsk); 1629 } 1630 1631 static int wait_for_vfork_done(struct task_struct *child, 1632 struct completion *vfork) 1633 { 1634 unsigned int state = TASK_KILLABLE|TASK_FREEZABLE; 1635 int killed; 1636 1637 cgroup_enter_frozen(); 1638 killed = wait_for_completion_state(vfork, state); 1639 cgroup_leave_frozen(false); 1640 1641 if (killed) { 1642 task_lock(child); 1643 child->vfork_done = NULL; 1644 task_unlock(child); 1645 } 1646 1647 put_task_struct(child); 1648 return killed; 1649 } 1650 1651 /* Please note the differences between mmput and mm_release. 1652 * mmput is called whenever we stop holding onto a mm_struct, 1653 * error success whatever. 1654 * 1655 * mm_release is called after a mm_struct has been removed 1656 * from the current process. 1657 * 1658 * This difference is important for error handling, when we 1659 * only half set up a mm_struct for a new process and need to restore 1660 * the old one. Because we mmput the new mm_struct before 1661 * restoring the old one. . . 1662 * Eric Biederman 10 January 1998 1663 */ 1664 static void mm_release(struct task_struct *tsk, struct mm_struct *mm) 1665 { 1666 uprobe_free_utask(tsk); 1667 1668 /* Get rid of any cached register state */ 1669 deactivate_mm(tsk, mm); 1670 1671 /* 1672 * Signal userspace if we're not exiting with a core dump 1673 * because we want to leave the value intact for debugging 1674 * purposes. 1675 */ 1676 if (tsk->clear_child_tid) { 1677 if (atomic_read(&mm->mm_users) > 1) { 1678 /* 1679 * We don't check the error code - if userspace has 1680 * not set up a proper pointer then tough luck. 1681 */ 1682 put_user(0, tsk->clear_child_tid); 1683 do_futex(tsk->clear_child_tid, FUTEX_WAKE, 1684 1, NULL, NULL, 0, 0); 1685 } 1686 tsk->clear_child_tid = NULL; 1687 } 1688 1689 /* 1690 * All done, finally we can wake up parent and return this mm to him. 1691 * Also kthread_stop() uses this completion for synchronization. 1692 */ 1693 if (tsk->vfork_done) 1694 complete_vfork_done(tsk); 1695 } 1696 1697 void exit_mm_release(struct task_struct *tsk, struct mm_struct *mm) 1698 { 1699 futex_exit_release(tsk); 1700 mm_release(tsk, mm); 1701 } 1702 1703 void exec_mm_release(struct task_struct *tsk, struct mm_struct *mm) 1704 { 1705 futex_exec_release(tsk); 1706 mm_release(tsk, mm); 1707 } 1708 1709 /** 1710 * dup_mm() - duplicates an existing mm structure 1711 * @tsk: the task_struct with which the new mm will be associated. 1712 * @oldmm: the mm to duplicate. 1713 * 1714 * Allocates a new mm structure and duplicates the provided @oldmm structure 1715 * content into it. 1716 * 1717 * Return: the duplicated mm or NULL on failure. 1718 */ 1719 static struct mm_struct *dup_mm(struct task_struct *tsk, 1720 struct mm_struct *oldmm) 1721 { 1722 struct mm_struct *mm; 1723 int err; 1724 1725 mm = allocate_mm(); 1726 if (!mm) 1727 goto fail_nomem; 1728 1729 memcpy(mm, oldmm, sizeof(*mm)); 1730 1731 if (!mm_init(mm, tsk, mm->user_ns)) 1732 goto fail_nomem; 1733 1734 uprobe_start_dup_mmap(); 1735 err = dup_mmap(mm, oldmm); 1736 if (err) 1737 goto free_pt; 1738 uprobe_end_dup_mmap(); 1739 1740 mm->hiwater_rss = get_mm_rss(mm); 1741 mm->hiwater_vm = mm->total_vm; 1742 1743 if (mm->binfmt && !try_module_get(mm->binfmt->module)) 1744 goto free_pt; 1745 1746 return mm; 1747 1748 free_pt: 1749 /* don't put binfmt in mmput, we haven't got module yet */ 1750 mm->binfmt = NULL; 1751 mm_init_owner(mm, NULL); 1752 mmput(mm); 1753 if (err) 1754 uprobe_end_dup_mmap(); 1755 1756 fail_nomem: 1757 return NULL; 1758 } 1759 1760 static int copy_mm(unsigned long clone_flags, struct task_struct *tsk) 1761 { 1762 struct mm_struct *mm, *oldmm; 1763 1764 tsk->min_flt = tsk->maj_flt = 0; 1765 tsk->nvcsw = tsk->nivcsw = 0; 1766 #ifdef CONFIG_DETECT_HUNG_TASK 1767 tsk->last_switch_count = tsk->nvcsw + tsk->nivcsw; 1768 tsk->last_switch_time = 0; 1769 #endif 1770 1771 tsk->mm = NULL; 1772 tsk->active_mm = NULL; 1773 1774 /* 1775 * Are we cloning a kernel thread? 1776 * 1777 * We need to steal a active VM for that.. 1778 */ 1779 oldmm = current->mm; 1780 if (!oldmm) 1781 return 0; 1782 1783 if (clone_flags & CLONE_VM) { 1784 mmget(oldmm); 1785 mm = oldmm; 1786 } else { 1787 mm = dup_mm(tsk, current->mm); 1788 if (!mm) 1789 return -ENOMEM; 1790 } 1791 1792 tsk->mm = mm; 1793 tsk->active_mm = mm; 1794 sched_mm_cid_fork(tsk); 1795 return 0; 1796 } 1797 1798 static int copy_fs(unsigned long clone_flags, struct task_struct *tsk) 1799 { 1800 struct fs_struct *fs = current->fs; 1801 if (clone_flags & CLONE_FS) { 1802 /* tsk->fs is already what we want */ 1803 spin_lock(&fs->lock); 1804 /* "users" and "in_exec" locked for check_unsafe_exec() */ 1805 if (fs->in_exec) { 1806 spin_unlock(&fs->lock); 1807 return -EAGAIN; 1808 } 1809 fs->users++; 1810 spin_unlock(&fs->lock); 1811 return 0; 1812 } 1813 tsk->fs = copy_fs_struct(fs); 1814 if (!tsk->fs) 1815 return -ENOMEM; 1816 return 0; 1817 } 1818 1819 static int copy_files(unsigned long clone_flags, struct task_struct *tsk, 1820 int no_files) 1821 { 1822 struct files_struct *oldf, *newf; 1823 1824 /* 1825 * A background process may not have any files ... 1826 */ 1827 oldf = current->files; 1828 if (!oldf) 1829 return 0; 1830 1831 if (no_files) { 1832 tsk->files = NULL; 1833 return 0; 1834 } 1835 1836 if (clone_flags & CLONE_FILES) { 1837 atomic_inc(&oldf->count); 1838 return 0; 1839 } 1840 1841 newf = dup_fd(oldf, NULL); 1842 if (IS_ERR(newf)) 1843 return PTR_ERR(newf); 1844 1845 tsk->files = newf; 1846 return 0; 1847 } 1848 1849 static int copy_sighand(unsigned long clone_flags, struct task_struct *tsk) 1850 { 1851 struct sighand_struct *sig; 1852 1853 if (clone_flags & CLONE_SIGHAND) { 1854 refcount_inc(¤t->sighand->count); 1855 return 0; 1856 } 1857 sig = kmem_cache_alloc(sighand_cachep, GFP_KERNEL); 1858 RCU_INIT_POINTER(tsk->sighand, sig); 1859 if (!sig) 1860 return -ENOMEM; 1861 1862 refcount_set(&sig->count, 1); 1863 spin_lock_irq(¤t->sighand->siglock); 1864 memcpy(sig->action, current->sighand->action, sizeof(sig->action)); 1865 spin_unlock_irq(¤t->sighand->siglock); 1866 1867 /* Reset all signal handler not set to SIG_IGN to SIG_DFL. */ 1868 if (clone_flags & CLONE_CLEAR_SIGHAND) 1869 flush_signal_handlers(tsk, 0); 1870 1871 return 0; 1872 } 1873 1874 void __cleanup_sighand(struct sighand_struct *sighand) 1875 { 1876 if (refcount_dec_and_test(&sighand->count)) { 1877 signalfd_cleanup(sighand); 1878 /* 1879 * sighand_cachep is SLAB_TYPESAFE_BY_RCU so we can free it 1880 * without an RCU grace period, see __lock_task_sighand(). 1881 */ 1882 kmem_cache_free(sighand_cachep, sighand); 1883 } 1884 } 1885 1886 /* 1887 * Initialize POSIX timer handling for a thread group. 1888 */ 1889 static void posix_cpu_timers_init_group(struct signal_struct *sig) 1890 { 1891 struct posix_cputimers *pct = &sig->posix_cputimers; 1892 unsigned long cpu_limit; 1893 1894 cpu_limit = READ_ONCE(sig->rlim[RLIMIT_CPU].rlim_cur); 1895 posix_cputimers_group_init(pct, cpu_limit); 1896 } 1897 1898 static int copy_signal(unsigned long clone_flags, struct task_struct *tsk) 1899 { 1900 struct signal_struct *sig; 1901 1902 if (clone_flags & CLONE_THREAD) 1903 return 0; 1904 1905 sig = kmem_cache_zalloc(signal_cachep, GFP_KERNEL); 1906 tsk->signal = sig; 1907 if (!sig) 1908 return -ENOMEM; 1909 1910 sig->nr_threads = 1; 1911 sig->quick_threads = 1; 1912 atomic_set(&sig->live, 1); 1913 refcount_set(&sig->sigcnt, 1); 1914 1915 /* list_add(thread_node, thread_head) without INIT_LIST_HEAD() */ 1916 sig->thread_head = (struct list_head)LIST_HEAD_INIT(tsk->thread_node); 1917 tsk->thread_node = (struct list_head)LIST_HEAD_INIT(sig->thread_head); 1918 1919 init_waitqueue_head(&sig->wait_chldexit); 1920 sig->curr_target = tsk; 1921 init_sigpending(&sig->shared_pending); 1922 INIT_HLIST_HEAD(&sig->multiprocess); 1923 seqlock_init(&sig->stats_lock); 1924 prev_cputime_init(&sig->prev_cputime); 1925 1926 #ifdef CONFIG_POSIX_TIMERS 1927 INIT_HLIST_HEAD(&sig->posix_timers); 1928 INIT_HLIST_HEAD(&sig->ignored_posix_timers); 1929 hrtimer_setup(&sig->real_timer, it_real_fn, CLOCK_MONOTONIC, HRTIMER_MODE_REL); 1930 #endif 1931 1932 task_lock(current->group_leader); 1933 memcpy(sig->rlim, current->signal->rlim, sizeof sig->rlim); 1934 task_unlock(current->group_leader); 1935 1936 posix_cpu_timers_init_group(sig); 1937 1938 tty_audit_fork(sig); 1939 sched_autogroup_fork(sig); 1940 1941 sig->oom_score_adj = current->signal->oom_score_adj; 1942 sig->oom_score_adj_min = current->signal->oom_score_adj_min; 1943 1944 mutex_init(&sig->cred_guard_mutex); 1945 init_rwsem(&sig->exec_update_lock); 1946 1947 return 0; 1948 } 1949 1950 static void copy_seccomp(struct task_struct *p) 1951 { 1952 #ifdef CONFIG_SECCOMP 1953 /* 1954 * Must be called with sighand->lock held, which is common to 1955 * all threads in the group. Holding cred_guard_mutex is not 1956 * needed because this new task is not yet running and cannot 1957 * be racing exec. 1958 */ 1959 assert_spin_locked(¤t->sighand->siglock); 1960 1961 /* Ref-count the new filter user, and assign it. */ 1962 get_seccomp_filter(current); 1963 p->seccomp = current->seccomp; 1964 1965 /* 1966 * Explicitly enable no_new_privs here in case it got set 1967 * between the task_struct being duplicated and holding the 1968 * sighand lock. The seccomp state and nnp must be in sync. 1969 */ 1970 if (task_no_new_privs(current)) 1971 task_set_no_new_privs(p); 1972 1973 /* 1974 * If the parent gained a seccomp mode after copying thread 1975 * flags and between before we held the sighand lock, we have 1976 * to manually enable the seccomp thread flag here. 1977 */ 1978 if (p->seccomp.mode != SECCOMP_MODE_DISABLED) 1979 set_task_syscall_work(p, SECCOMP); 1980 #endif 1981 } 1982 1983 SYSCALL_DEFINE1(set_tid_address, int __user *, tidptr) 1984 { 1985 current->clear_child_tid = tidptr; 1986 1987 return task_pid_vnr(current); 1988 } 1989 1990 static void rt_mutex_init_task(struct task_struct *p) 1991 { 1992 raw_spin_lock_init(&p->pi_lock); 1993 #ifdef CONFIG_RT_MUTEXES 1994 p->pi_waiters = RB_ROOT_CACHED; 1995 p->pi_top_task = NULL; 1996 p->pi_blocked_on = NULL; 1997 #endif 1998 } 1999 2000 static inline void init_task_pid_links(struct task_struct *task) 2001 { 2002 enum pid_type type; 2003 2004 for (type = PIDTYPE_PID; type < PIDTYPE_MAX; ++type) 2005 INIT_HLIST_NODE(&task->pid_links[type]); 2006 } 2007 2008 static inline void 2009 init_task_pid(struct task_struct *task, enum pid_type type, struct pid *pid) 2010 { 2011 if (type == PIDTYPE_PID) 2012 task->thread_pid = pid; 2013 else 2014 task->signal->pids[type] = pid; 2015 } 2016 2017 static inline void rcu_copy_process(struct task_struct *p) 2018 { 2019 #ifdef CONFIG_PREEMPT_RCU 2020 p->rcu_read_lock_nesting = 0; 2021 p->rcu_read_unlock_special.s = 0; 2022 p->rcu_blocked_node = NULL; 2023 INIT_LIST_HEAD(&p->rcu_node_entry); 2024 #endif /* #ifdef CONFIG_PREEMPT_RCU */ 2025 #ifdef CONFIG_TASKS_RCU 2026 p->rcu_tasks_holdout = false; 2027 INIT_LIST_HEAD(&p->rcu_tasks_holdout_list); 2028 p->rcu_tasks_idle_cpu = -1; 2029 INIT_LIST_HEAD(&p->rcu_tasks_exit_list); 2030 #endif /* #ifdef CONFIG_TASKS_RCU */ 2031 #ifdef CONFIG_TASKS_TRACE_RCU 2032 p->trc_reader_nesting = 0; 2033 p->trc_reader_special.s = 0; 2034 INIT_LIST_HEAD(&p->trc_holdout_list); 2035 INIT_LIST_HEAD(&p->trc_blkd_node); 2036 #endif /* #ifdef CONFIG_TASKS_TRACE_RCU */ 2037 } 2038 2039 /** 2040 * pidfd_prepare - allocate a new pidfd_file and reserve a pidfd 2041 * @pid: the struct pid for which to create a pidfd 2042 * @flags: flags of the new @pidfd 2043 * @ret_file: return the new pidfs file 2044 * 2045 * Allocate a new file that stashes @pid and reserve a new pidfd number in the 2046 * caller's file descriptor table. The pidfd is reserved but not installed yet. 2047 * 2048 * The helper verifies that @pid is still in use, without PIDFD_THREAD the 2049 * task identified by @pid must be a thread-group leader. 2050 * 2051 * If this function returns successfully the caller is responsible to either 2052 * call fd_install() passing the returned pidfd and pidfd file as arguments in 2053 * order to install the pidfd into its file descriptor table or they must use 2054 * put_unused_fd() and fput() on the returned pidfd and pidfd file 2055 * respectively. 2056 * 2057 * This function is useful when a pidfd must already be reserved but there 2058 * might still be points of failure afterwards and the caller wants to ensure 2059 * that no pidfd is leaked into its file descriptor table. 2060 * 2061 * Return: On success, a reserved pidfd is returned from the function and a new 2062 * pidfd file is returned in the last argument to the function. On 2063 * error, a negative error code is returned from the function and the 2064 * last argument remains unchanged. 2065 */ 2066 int pidfd_prepare(struct pid *pid, unsigned int flags, struct file **ret_file) 2067 { 2068 struct file *pidfs_file; 2069 2070 /* 2071 * PIDFD_STALE is only allowed to be passed if the caller knows 2072 * that @pid is already registered in pidfs and thus 2073 * PIDFD_INFO_EXIT information is guaranteed to be available. 2074 */ 2075 if (!(flags & PIDFD_STALE)) { 2076 /* 2077 * While holding the pidfd waitqueue lock removing the 2078 * task linkage for the thread-group leader pid 2079 * (PIDTYPE_TGID) isn't possible. Thus, if there's still 2080 * task linkage for PIDTYPE_PID not having thread-group 2081 * leader linkage for the pid means it wasn't a 2082 * thread-group leader in the first place. 2083 */ 2084 guard(spinlock_irq)(&pid->wait_pidfd.lock); 2085 2086 /* Task has already been reaped. */ 2087 if (!pid_has_task(pid, PIDTYPE_PID)) 2088 return -ESRCH; 2089 /* 2090 * If this struct pid isn't used as a thread-group 2091 * leader but the caller requested to create a 2092 * thread-group leader pidfd then report ENOENT. 2093 */ 2094 if (!(flags & PIDFD_THREAD) && !pid_has_task(pid, PIDTYPE_TGID)) 2095 return -ENOENT; 2096 } 2097 2098 CLASS(get_unused_fd, pidfd)(O_CLOEXEC); 2099 if (pidfd < 0) 2100 return pidfd; 2101 2102 pidfs_file = pidfs_alloc_file(pid, flags | O_RDWR); 2103 if (IS_ERR(pidfs_file)) 2104 return PTR_ERR(pidfs_file); 2105 2106 *ret_file = pidfs_file; 2107 return take_fd(pidfd); 2108 } 2109 2110 static void __delayed_free_task(struct rcu_head *rhp) 2111 { 2112 struct task_struct *tsk = container_of(rhp, struct task_struct, rcu); 2113 2114 free_task(tsk); 2115 } 2116 2117 static __always_inline void delayed_free_task(struct task_struct *tsk) 2118 { 2119 if (IS_ENABLED(CONFIG_MEMCG)) 2120 call_rcu(&tsk->rcu, __delayed_free_task); 2121 else 2122 free_task(tsk); 2123 } 2124 2125 static void copy_oom_score_adj(u64 clone_flags, struct task_struct *tsk) 2126 { 2127 /* Skip if kernel thread */ 2128 if (!tsk->mm) 2129 return; 2130 2131 /* Skip if spawning a thread or using vfork */ 2132 if ((clone_flags & (CLONE_VM | CLONE_THREAD | CLONE_VFORK)) != CLONE_VM) 2133 return; 2134 2135 /* We need to synchronize with __set_oom_adj */ 2136 mutex_lock(&oom_adj_mutex); 2137 set_bit(MMF_MULTIPROCESS, &tsk->mm->flags); 2138 /* Update the values in case they were changed after copy_signal */ 2139 tsk->signal->oom_score_adj = current->signal->oom_score_adj; 2140 tsk->signal->oom_score_adj_min = current->signal->oom_score_adj_min; 2141 mutex_unlock(&oom_adj_mutex); 2142 } 2143 2144 #ifdef CONFIG_RV 2145 static void rv_task_fork(struct task_struct *p) 2146 { 2147 int i; 2148 2149 for (i = 0; i < RV_PER_TASK_MONITORS; i++) 2150 p->rv[i].da_mon.monitoring = false; 2151 } 2152 #else 2153 #define rv_task_fork(p) do {} while (0) 2154 #endif 2155 2156 /* 2157 * This creates a new process as a copy of the old one, 2158 * but does not actually start it yet. 2159 * 2160 * It copies the registers, and all the appropriate 2161 * parts of the process environment (as per the clone 2162 * flags). The actual kick-off is left to the caller. 2163 */ 2164 __latent_entropy struct task_struct *copy_process( 2165 struct pid *pid, 2166 int trace, 2167 int node, 2168 struct kernel_clone_args *args) 2169 { 2170 int pidfd = -1, retval; 2171 struct task_struct *p; 2172 struct multiprocess_signals delayed; 2173 struct file *pidfile = NULL; 2174 const u64 clone_flags = args->flags; 2175 struct nsproxy *nsp = current->nsproxy; 2176 2177 /* 2178 * Don't allow sharing the root directory with processes in a different 2179 * namespace 2180 */ 2181 if ((clone_flags & (CLONE_NEWNS|CLONE_FS)) == (CLONE_NEWNS|CLONE_FS)) 2182 return ERR_PTR(-EINVAL); 2183 2184 if ((clone_flags & (CLONE_NEWUSER|CLONE_FS)) == (CLONE_NEWUSER|CLONE_FS)) 2185 return ERR_PTR(-EINVAL); 2186 2187 /* 2188 * Thread groups must share signals as well, and detached threads 2189 * can only be started up within the thread group. 2190 */ 2191 if ((clone_flags & CLONE_THREAD) && !(clone_flags & CLONE_SIGHAND)) 2192 return ERR_PTR(-EINVAL); 2193 2194 /* 2195 * Shared signal handlers imply shared VM. By way of the above, 2196 * thread groups also imply shared VM. Blocking this case allows 2197 * for various simplifications in other code. 2198 */ 2199 if ((clone_flags & CLONE_SIGHAND) && !(clone_flags & CLONE_VM)) 2200 return ERR_PTR(-EINVAL); 2201 2202 /* 2203 * Siblings of global init remain as zombies on exit since they are 2204 * not reaped by their parent (swapper). To solve this and to avoid 2205 * multi-rooted process trees, prevent global and container-inits 2206 * from creating siblings. 2207 */ 2208 if ((clone_flags & CLONE_PARENT) && 2209 current->signal->flags & SIGNAL_UNKILLABLE) 2210 return ERR_PTR(-EINVAL); 2211 2212 /* 2213 * If the new process will be in a different pid or user namespace 2214 * do not allow it to share a thread group with the forking task. 2215 */ 2216 if (clone_flags & CLONE_THREAD) { 2217 if ((clone_flags & (CLONE_NEWUSER | CLONE_NEWPID)) || 2218 (task_active_pid_ns(current) != nsp->pid_ns_for_children)) 2219 return ERR_PTR(-EINVAL); 2220 } 2221 2222 if (clone_flags & CLONE_PIDFD) { 2223 /* 2224 * - CLONE_DETACHED is blocked so that we can potentially 2225 * reuse it later for CLONE_PIDFD. 2226 */ 2227 if (clone_flags & CLONE_DETACHED) 2228 return ERR_PTR(-EINVAL); 2229 } 2230 2231 /* 2232 * Force any signals received before this point to be delivered 2233 * before the fork happens. Collect up signals sent to multiple 2234 * processes that happen during the fork and delay them so that 2235 * they appear to happen after the fork. 2236 */ 2237 sigemptyset(&delayed.signal); 2238 INIT_HLIST_NODE(&delayed.node); 2239 2240 spin_lock_irq(¤t->sighand->siglock); 2241 if (!(clone_flags & CLONE_THREAD)) 2242 hlist_add_head(&delayed.node, ¤t->signal->multiprocess); 2243 recalc_sigpending(); 2244 spin_unlock_irq(¤t->sighand->siglock); 2245 retval = -ERESTARTNOINTR; 2246 if (task_sigpending(current)) 2247 goto fork_out; 2248 2249 retval = -ENOMEM; 2250 p = dup_task_struct(current, node); 2251 if (!p) 2252 goto fork_out; 2253 p->flags &= ~PF_KTHREAD; 2254 if (args->kthread) 2255 p->flags |= PF_KTHREAD; 2256 if (args->user_worker) { 2257 /* 2258 * Mark us a user worker, and block any signal that isn't 2259 * fatal or STOP 2260 */ 2261 p->flags |= PF_USER_WORKER; 2262 siginitsetinv(&p->blocked, sigmask(SIGKILL)|sigmask(SIGSTOP)); 2263 } 2264 if (args->io_thread) 2265 p->flags |= PF_IO_WORKER; 2266 2267 if (args->name) 2268 strscpy_pad(p->comm, args->name, sizeof(p->comm)); 2269 2270 p->set_child_tid = (clone_flags & CLONE_CHILD_SETTID) ? args->child_tid : NULL; 2271 /* 2272 * Clear TID on mm_release()? 2273 */ 2274 p->clear_child_tid = (clone_flags & CLONE_CHILD_CLEARTID) ? args->child_tid : NULL; 2275 2276 ftrace_graph_init_task(p); 2277 2278 rt_mutex_init_task(p); 2279 2280 lockdep_assert_irqs_enabled(); 2281 #ifdef CONFIG_PROVE_LOCKING 2282 DEBUG_LOCKS_WARN_ON(!p->softirqs_enabled); 2283 #endif 2284 retval = copy_creds(p, clone_flags); 2285 if (retval < 0) 2286 goto bad_fork_free; 2287 2288 retval = -EAGAIN; 2289 if (is_rlimit_overlimit(task_ucounts(p), UCOUNT_RLIMIT_NPROC, rlimit(RLIMIT_NPROC))) { 2290 if (p->real_cred->user != INIT_USER && 2291 !capable(CAP_SYS_RESOURCE) && !capable(CAP_SYS_ADMIN)) 2292 goto bad_fork_cleanup_count; 2293 } 2294 current->flags &= ~PF_NPROC_EXCEEDED; 2295 2296 /* 2297 * If multiple threads are within copy_process(), then this check 2298 * triggers too late. This doesn't hurt, the check is only there 2299 * to stop root fork bombs. 2300 */ 2301 retval = -EAGAIN; 2302 if (data_race(nr_threads >= max_threads)) 2303 goto bad_fork_cleanup_count; 2304 2305 delayacct_tsk_init(p); /* Must remain after dup_task_struct() */ 2306 p->flags &= ~(PF_SUPERPRIV | PF_WQ_WORKER | PF_IDLE | PF_NO_SETAFFINITY); 2307 p->flags |= PF_FORKNOEXEC; 2308 INIT_LIST_HEAD(&p->children); 2309 INIT_LIST_HEAD(&p->sibling); 2310 rcu_copy_process(p); 2311 p->vfork_done = NULL; 2312 spin_lock_init(&p->alloc_lock); 2313 2314 init_sigpending(&p->pending); 2315 2316 p->utime = p->stime = p->gtime = 0; 2317 #ifdef CONFIG_ARCH_HAS_SCALED_CPUTIME 2318 p->utimescaled = p->stimescaled = 0; 2319 #endif 2320 prev_cputime_init(&p->prev_cputime); 2321 2322 #ifdef CONFIG_VIRT_CPU_ACCOUNTING_GEN 2323 seqcount_init(&p->vtime.seqcount); 2324 p->vtime.starttime = 0; 2325 p->vtime.state = VTIME_INACTIVE; 2326 #endif 2327 2328 #ifdef CONFIG_IO_URING 2329 p->io_uring = NULL; 2330 #endif 2331 2332 p->default_timer_slack_ns = current->timer_slack_ns; 2333 2334 #ifdef CONFIG_PSI 2335 p->psi_flags = 0; 2336 #endif 2337 2338 task_io_accounting_init(&p->ioac); 2339 acct_clear_integrals(p); 2340 2341 posix_cputimers_init(&p->posix_cputimers); 2342 tick_dep_init_task(p); 2343 2344 p->io_context = NULL; 2345 audit_set_context(p, NULL); 2346 cgroup_fork(p); 2347 if (args->kthread) { 2348 if (!set_kthread_struct(p)) 2349 goto bad_fork_cleanup_delayacct; 2350 } 2351 #ifdef CONFIG_NUMA 2352 p->mempolicy = mpol_dup(p->mempolicy); 2353 if (IS_ERR(p->mempolicy)) { 2354 retval = PTR_ERR(p->mempolicy); 2355 p->mempolicy = NULL; 2356 goto bad_fork_cleanup_delayacct; 2357 } 2358 #endif 2359 #ifdef CONFIG_CPUSETS 2360 p->cpuset_mem_spread_rotor = NUMA_NO_NODE; 2361 seqcount_spinlock_init(&p->mems_allowed_seq, &p->alloc_lock); 2362 #endif 2363 #ifdef CONFIG_TRACE_IRQFLAGS 2364 memset(&p->irqtrace, 0, sizeof(p->irqtrace)); 2365 p->irqtrace.hardirq_disable_ip = _THIS_IP_; 2366 p->irqtrace.softirq_enable_ip = _THIS_IP_; 2367 p->softirqs_enabled = 1; 2368 p->softirq_context = 0; 2369 #endif 2370 2371 p->pagefault_disabled = 0; 2372 2373 #ifdef CONFIG_LOCKDEP 2374 lockdep_init_task(p); 2375 #endif 2376 2377 #ifdef CONFIG_DEBUG_MUTEXES 2378 p->blocked_on = NULL; /* not blocked yet */ 2379 #endif 2380 #ifdef CONFIG_BCACHE 2381 p->sequential_io = 0; 2382 p->sequential_io_avg = 0; 2383 #endif 2384 #ifdef CONFIG_BPF_SYSCALL 2385 RCU_INIT_POINTER(p->bpf_storage, NULL); 2386 p->bpf_ctx = NULL; 2387 #endif 2388 2389 /* Perform scheduler related setup. Assign this task to a CPU. */ 2390 retval = sched_fork(clone_flags, p); 2391 if (retval) 2392 goto bad_fork_cleanup_policy; 2393 2394 retval = perf_event_init_task(p, clone_flags); 2395 if (retval) 2396 goto bad_fork_sched_cancel_fork; 2397 retval = audit_alloc(p); 2398 if (retval) 2399 goto bad_fork_cleanup_perf; 2400 /* copy all the process information */ 2401 shm_init_task(p); 2402 retval = security_task_alloc(p, clone_flags); 2403 if (retval) 2404 goto bad_fork_cleanup_audit; 2405 retval = copy_semundo(clone_flags, p); 2406 if (retval) 2407 goto bad_fork_cleanup_security; 2408 retval = copy_files(clone_flags, p, args->no_files); 2409 if (retval) 2410 goto bad_fork_cleanup_semundo; 2411 retval = copy_fs(clone_flags, p); 2412 if (retval) 2413 goto bad_fork_cleanup_files; 2414 retval = copy_sighand(clone_flags, p); 2415 if (retval) 2416 goto bad_fork_cleanup_fs; 2417 retval = copy_signal(clone_flags, p); 2418 if (retval) 2419 goto bad_fork_cleanup_sighand; 2420 retval = copy_mm(clone_flags, p); 2421 if (retval) 2422 goto bad_fork_cleanup_signal; 2423 retval = copy_namespaces(clone_flags, p); 2424 if (retval) 2425 goto bad_fork_cleanup_mm; 2426 retval = copy_io(clone_flags, p); 2427 if (retval) 2428 goto bad_fork_cleanup_namespaces; 2429 retval = copy_thread(p, args); 2430 if (retval) 2431 goto bad_fork_cleanup_io; 2432 2433 stackleak_task_init(p); 2434 2435 if (pid != &init_struct_pid) { 2436 pid = alloc_pid(p->nsproxy->pid_ns_for_children, args->set_tid, 2437 args->set_tid_size); 2438 if (IS_ERR(pid)) { 2439 retval = PTR_ERR(pid); 2440 goto bad_fork_cleanup_thread; 2441 } 2442 } 2443 2444 /* 2445 * This has to happen after we've potentially unshared the file 2446 * descriptor table (so that the pidfd doesn't leak into the child 2447 * if the fd table isn't shared). 2448 */ 2449 if (clone_flags & CLONE_PIDFD) { 2450 int flags = (clone_flags & CLONE_THREAD) ? PIDFD_THREAD : 0; 2451 2452 /* 2453 * Note that no task has been attached to @pid yet indicate 2454 * that via CLONE_PIDFD. 2455 */ 2456 retval = pidfd_prepare(pid, flags | PIDFD_STALE, &pidfile); 2457 if (retval < 0) 2458 goto bad_fork_free_pid; 2459 pidfd = retval; 2460 2461 retval = put_user(pidfd, args->pidfd); 2462 if (retval) 2463 goto bad_fork_put_pidfd; 2464 } 2465 2466 #ifdef CONFIG_BLOCK 2467 p->plug = NULL; 2468 #endif 2469 futex_init_task(p); 2470 2471 /* 2472 * sigaltstack should be cleared when sharing the same VM 2473 */ 2474 if ((clone_flags & (CLONE_VM|CLONE_VFORK)) == CLONE_VM) 2475 sas_ss_reset(p); 2476 2477 /* 2478 * Syscall tracing and stepping should be turned off in the 2479 * child regardless of CLONE_PTRACE. 2480 */ 2481 user_disable_single_step(p); 2482 clear_task_syscall_work(p, SYSCALL_TRACE); 2483 #if defined(CONFIG_GENERIC_ENTRY) || defined(TIF_SYSCALL_EMU) 2484 clear_task_syscall_work(p, SYSCALL_EMU); 2485 #endif 2486 clear_tsk_latency_tracing(p); 2487 2488 /* ok, now we should be set up.. */ 2489 p->pid = pid_nr(pid); 2490 if (clone_flags & CLONE_THREAD) { 2491 p->group_leader = current->group_leader; 2492 p->tgid = current->tgid; 2493 } else { 2494 p->group_leader = p; 2495 p->tgid = p->pid; 2496 } 2497 2498 p->nr_dirtied = 0; 2499 p->nr_dirtied_pause = 128 >> (PAGE_SHIFT - 10); 2500 p->dirty_paused_when = 0; 2501 2502 p->pdeath_signal = 0; 2503 p->task_works = NULL; 2504 clear_posix_cputimers_work(p); 2505 2506 #ifdef CONFIG_KRETPROBES 2507 p->kretprobe_instances.first = NULL; 2508 #endif 2509 #ifdef CONFIG_RETHOOK 2510 p->rethooks.first = NULL; 2511 #endif 2512 2513 /* 2514 * Ensure that the cgroup subsystem policies allow the new process to be 2515 * forked. It should be noted that the new process's css_set can be changed 2516 * between here and cgroup_post_fork() if an organisation operation is in 2517 * progress. 2518 */ 2519 retval = cgroup_can_fork(p, args); 2520 if (retval) 2521 goto bad_fork_put_pidfd; 2522 2523 /* 2524 * Now that the cgroups are pinned, re-clone the parent cgroup and put 2525 * the new task on the correct runqueue. All this *before* the task 2526 * becomes visible. 2527 * 2528 * This isn't part of ->can_fork() because while the re-cloning is 2529 * cgroup specific, it unconditionally needs to place the task on a 2530 * runqueue. 2531 */ 2532 retval = sched_cgroup_fork(p, args); 2533 if (retval) 2534 goto bad_fork_cancel_cgroup; 2535 2536 /* 2537 * From this point on we must avoid any synchronous user-space 2538 * communication until we take the tasklist-lock. In particular, we do 2539 * not want user-space to be able to predict the process start-time by 2540 * stalling fork(2) after we recorded the start_time but before it is 2541 * visible to the system. 2542 */ 2543 2544 p->start_time = ktime_get_ns(); 2545 p->start_boottime = ktime_get_boottime_ns(); 2546 2547 /* 2548 * Make it visible to the rest of the system, but dont wake it up yet. 2549 * Need tasklist lock for parent etc handling! 2550 */ 2551 write_lock_irq(&tasklist_lock); 2552 2553 /* CLONE_PARENT re-uses the old parent */ 2554 if (clone_flags & (CLONE_PARENT|CLONE_THREAD)) { 2555 p->real_parent = current->real_parent; 2556 p->parent_exec_id = current->parent_exec_id; 2557 if (clone_flags & CLONE_THREAD) 2558 p->exit_signal = -1; 2559 else 2560 p->exit_signal = current->group_leader->exit_signal; 2561 } else { 2562 p->real_parent = current; 2563 p->parent_exec_id = current->self_exec_id; 2564 p->exit_signal = args->exit_signal; 2565 } 2566 2567 klp_copy_process(p); 2568 2569 sched_core_fork(p); 2570 2571 spin_lock(¤t->sighand->siglock); 2572 2573 rv_task_fork(p); 2574 2575 rseq_fork(p, clone_flags); 2576 2577 /* Don't start children in a dying pid namespace */ 2578 if (unlikely(!(ns_of_pid(pid)->pid_allocated & PIDNS_ADDING))) { 2579 retval = -ENOMEM; 2580 goto bad_fork_core_free; 2581 } 2582 2583 /* Let kill terminate clone/fork in the middle */ 2584 if (fatal_signal_pending(current)) { 2585 retval = -EINTR; 2586 goto bad_fork_core_free; 2587 } 2588 2589 /* No more failure paths after this point. */ 2590 2591 /* 2592 * Copy seccomp details explicitly here, in case they were changed 2593 * before holding sighand lock. 2594 */ 2595 copy_seccomp(p); 2596 2597 init_task_pid_links(p); 2598 if (likely(p->pid)) { 2599 ptrace_init_task(p, (clone_flags & CLONE_PTRACE) || trace); 2600 2601 init_task_pid(p, PIDTYPE_PID, pid); 2602 if (thread_group_leader(p)) { 2603 init_task_pid(p, PIDTYPE_TGID, pid); 2604 init_task_pid(p, PIDTYPE_PGID, task_pgrp(current)); 2605 init_task_pid(p, PIDTYPE_SID, task_session(current)); 2606 2607 if (is_child_reaper(pid)) { 2608 ns_of_pid(pid)->child_reaper = p; 2609 p->signal->flags |= SIGNAL_UNKILLABLE; 2610 } 2611 p->signal->shared_pending.signal = delayed.signal; 2612 p->signal->tty = tty_kref_get(current->signal->tty); 2613 /* 2614 * Inherit has_child_subreaper flag under the same 2615 * tasklist_lock with adding child to the process tree 2616 * for propagate_has_child_subreaper optimization. 2617 */ 2618 p->signal->has_child_subreaper = p->real_parent->signal->has_child_subreaper || 2619 p->real_parent->signal->is_child_subreaper; 2620 list_add_tail(&p->sibling, &p->real_parent->children); 2621 list_add_tail_rcu(&p->tasks, &init_task.tasks); 2622 attach_pid(p, PIDTYPE_TGID); 2623 attach_pid(p, PIDTYPE_PGID); 2624 attach_pid(p, PIDTYPE_SID); 2625 __this_cpu_inc(process_counts); 2626 } else { 2627 current->signal->nr_threads++; 2628 current->signal->quick_threads++; 2629 atomic_inc(¤t->signal->live); 2630 refcount_inc(¤t->signal->sigcnt); 2631 task_join_group_stop(p); 2632 list_add_tail_rcu(&p->thread_node, 2633 &p->signal->thread_head); 2634 } 2635 attach_pid(p, PIDTYPE_PID); 2636 nr_threads++; 2637 } 2638 total_forks++; 2639 hlist_del_init(&delayed.node); 2640 spin_unlock(¤t->sighand->siglock); 2641 syscall_tracepoint_update(p); 2642 write_unlock_irq(&tasklist_lock); 2643 2644 if (pidfile) 2645 fd_install(pidfd, pidfile); 2646 2647 proc_fork_connector(p); 2648 sched_post_fork(p); 2649 cgroup_post_fork(p, args); 2650 perf_event_fork(p); 2651 2652 trace_task_newtask(p, clone_flags); 2653 uprobe_copy_process(p, clone_flags); 2654 user_events_fork(p, clone_flags); 2655 2656 copy_oom_score_adj(clone_flags, p); 2657 2658 return p; 2659 2660 bad_fork_core_free: 2661 sched_core_free(p); 2662 spin_unlock(¤t->sighand->siglock); 2663 write_unlock_irq(&tasklist_lock); 2664 bad_fork_cancel_cgroup: 2665 cgroup_cancel_fork(p, args); 2666 bad_fork_put_pidfd: 2667 if (clone_flags & CLONE_PIDFD) { 2668 fput(pidfile); 2669 put_unused_fd(pidfd); 2670 } 2671 bad_fork_free_pid: 2672 if (pid != &init_struct_pid) 2673 free_pid(pid); 2674 bad_fork_cleanup_thread: 2675 exit_thread(p); 2676 bad_fork_cleanup_io: 2677 if (p->io_context) 2678 exit_io_context(p); 2679 bad_fork_cleanup_namespaces: 2680 exit_task_namespaces(p); 2681 bad_fork_cleanup_mm: 2682 if (p->mm) { 2683 mm_clear_owner(p->mm, p); 2684 mmput(p->mm); 2685 } 2686 bad_fork_cleanup_signal: 2687 if (!(clone_flags & CLONE_THREAD)) 2688 free_signal_struct(p->signal); 2689 bad_fork_cleanup_sighand: 2690 __cleanup_sighand(p->sighand); 2691 bad_fork_cleanup_fs: 2692 exit_fs(p); /* blocking */ 2693 bad_fork_cleanup_files: 2694 exit_files(p); /* blocking */ 2695 bad_fork_cleanup_semundo: 2696 exit_sem(p); 2697 bad_fork_cleanup_security: 2698 security_task_free(p); 2699 bad_fork_cleanup_audit: 2700 audit_free(p); 2701 bad_fork_cleanup_perf: 2702 perf_event_free_task(p); 2703 bad_fork_sched_cancel_fork: 2704 sched_cancel_fork(p); 2705 bad_fork_cleanup_policy: 2706 lockdep_free_task(p); 2707 #ifdef CONFIG_NUMA 2708 mpol_put(p->mempolicy); 2709 #endif 2710 bad_fork_cleanup_delayacct: 2711 delayacct_tsk_free(p); 2712 bad_fork_cleanup_count: 2713 dec_rlimit_ucounts(task_ucounts(p), UCOUNT_RLIMIT_NPROC, 1); 2714 exit_creds(p); 2715 bad_fork_free: 2716 WRITE_ONCE(p->__state, TASK_DEAD); 2717 exit_task_stack_account(p); 2718 put_task_stack(p); 2719 delayed_free_task(p); 2720 fork_out: 2721 spin_lock_irq(¤t->sighand->siglock); 2722 hlist_del_init(&delayed.node); 2723 spin_unlock_irq(¤t->sighand->siglock); 2724 return ERR_PTR(retval); 2725 } 2726 2727 static inline void init_idle_pids(struct task_struct *idle) 2728 { 2729 enum pid_type type; 2730 2731 for (type = PIDTYPE_PID; type < PIDTYPE_MAX; ++type) { 2732 INIT_HLIST_NODE(&idle->pid_links[type]); /* not really needed */ 2733 init_task_pid(idle, type, &init_struct_pid); 2734 } 2735 } 2736 2737 static int idle_dummy(void *dummy) 2738 { 2739 /* This function is never called */ 2740 return 0; 2741 } 2742 2743 struct task_struct * __init fork_idle(int cpu) 2744 { 2745 struct task_struct *task; 2746 struct kernel_clone_args args = { 2747 .flags = CLONE_VM, 2748 .fn = &idle_dummy, 2749 .fn_arg = NULL, 2750 .kthread = 1, 2751 .idle = 1, 2752 }; 2753 2754 task = copy_process(&init_struct_pid, 0, cpu_to_node(cpu), &args); 2755 if (!IS_ERR(task)) { 2756 init_idle_pids(task); 2757 init_idle(task, cpu); 2758 } 2759 2760 return task; 2761 } 2762 2763 /* 2764 * This is like kernel_clone(), but shaved down and tailored to just 2765 * creating io_uring workers. It returns a created task, or an error pointer. 2766 * The returned task is inactive, and the caller must fire it up through 2767 * wake_up_new_task(p). All signals are blocked in the created task. 2768 */ 2769 struct task_struct *create_io_thread(int (*fn)(void *), void *arg, int node) 2770 { 2771 unsigned long flags = CLONE_FS|CLONE_FILES|CLONE_SIGHAND|CLONE_THREAD| 2772 CLONE_IO; 2773 struct kernel_clone_args args = { 2774 .flags = ((lower_32_bits(flags) | CLONE_VM | 2775 CLONE_UNTRACED) & ~CSIGNAL), 2776 .exit_signal = (lower_32_bits(flags) & CSIGNAL), 2777 .fn = fn, 2778 .fn_arg = arg, 2779 .io_thread = 1, 2780 .user_worker = 1, 2781 }; 2782 2783 return copy_process(NULL, 0, node, &args); 2784 } 2785 2786 /* 2787 * Ok, this is the main fork-routine. 2788 * 2789 * It copies the process, and if successful kick-starts 2790 * it and waits for it to finish using the VM if required. 2791 * 2792 * args->exit_signal is expected to be checked for sanity by the caller. 2793 */ 2794 pid_t kernel_clone(struct kernel_clone_args *args) 2795 { 2796 u64 clone_flags = args->flags; 2797 struct completion vfork; 2798 struct pid *pid; 2799 struct task_struct *p; 2800 int trace = 0; 2801 pid_t nr; 2802 2803 /* 2804 * For legacy clone() calls, CLONE_PIDFD uses the parent_tid argument 2805 * to return the pidfd. Hence, CLONE_PIDFD and CLONE_PARENT_SETTID are 2806 * mutually exclusive. With clone3() CLONE_PIDFD has grown a separate 2807 * field in struct clone_args and it still doesn't make sense to have 2808 * them both point at the same memory location. Performing this check 2809 * here has the advantage that we don't need to have a separate helper 2810 * to check for legacy clone(). 2811 */ 2812 if ((clone_flags & CLONE_PIDFD) && 2813 (clone_flags & CLONE_PARENT_SETTID) && 2814 (args->pidfd == args->parent_tid)) 2815 return -EINVAL; 2816 2817 /* 2818 * Determine whether and which event to report to ptracer. When 2819 * called from kernel_thread or CLONE_UNTRACED is explicitly 2820 * requested, no event is reported; otherwise, report if the event 2821 * for the type of forking is enabled. 2822 */ 2823 if (!(clone_flags & CLONE_UNTRACED)) { 2824 if (clone_flags & CLONE_VFORK) 2825 trace = PTRACE_EVENT_VFORK; 2826 else if (args->exit_signal != SIGCHLD) 2827 trace = PTRACE_EVENT_CLONE; 2828 else 2829 trace = PTRACE_EVENT_FORK; 2830 2831 if (likely(!ptrace_event_enabled(current, trace))) 2832 trace = 0; 2833 } 2834 2835 p = copy_process(NULL, trace, NUMA_NO_NODE, args); 2836 add_latent_entropy(); 2837 2838 if (IS_ERR(p)) 2839 return PTR_ERR(p); 2840 2841 /* 2842 * Do this prior waking up the new thread - the thread pointer 2843 * might get invalid after that point, if the thread exits quickly. 2844 */ 2845 trace_sched_process_fork(current, p); 2846 2847 pid = get_task_pid(p, PIDTYPE_PID); 2848 nr = pid_vnr(pid); 2849 2850 if (clone_flags & CLONE_PARENT_SETTID) 2851 put_user(nr, args->parent_tid); 2852 2853 if (clone_flags & CLONE_VFORK) { 2854 p->vfork_done = &vfork; 2855 init_completion(&vfork); 2856 get_task_struct(p); 2857 } 2858 2859 if (IS_ENABLED(CONFIG_LRU_GEN_WALKS_MMU) && !(clone_flags & CLONE_VM)) { 2860 /* lock the task to synchronize with memcg migration */ 2861 task_lock(p); 2862 lru_gen_add_mm(p->mm); 2863 task_unlock(p); 2864 } 2865 2866 wake_up_new_task(p); 2867 2868 /* forking complete and child started to run, tell ptracer */ 2869 if (unlikely(trace)) 2870 ptrace_event_pid(trace, pid); 2871 2872 if (clone_flags & CLONE_VFORK) { 2873 if (!wait_for_vfork_done(p, &vfork)) 2874 ptrace_event_pid(PTRACE_EVENT_VFORK_DONE, pid); 2875 } 2876 2877 put_pid(pid); 2878 return nr; 2879 } 2880 2881 /* 2882 * Create a kernel thread. 2883 */ 2884 pid_t kernel_thread(int (*fn)(void *), void *arg, const char *name, 2885 unsigned long flags) 2886 { 2887 struct kernel_clone_args args = { 2888 .flags = ((lower_32_bits(flags) | CLONE_VM | 2889 CLONE_UNTRACED) & ~CSIGNAL), 2890 .exit_signal = (lower_32_bits(flags) & CSIGNAL), 2891 .fn = fn, 2892 .fn_arg = arg, 2893 .name = name, 2894 .kthread = 1, 2895 }; 2896 2897 return kernel_clone(&args); 2898 } 2899 2900 /* 2901 * Create a user mode thread. 2902 */ 2903 pid_t user_mode_thread(int (*fn)(void *), void *arg, unsigned long flags) 2904 { 2905 struct kernel_clone_args args = { 2906 .flags = ((lower_32_bits(flags) | CLONE_VM | 2907 CLONE_UNTRACED) & ~CSIGNAL), 2908 .exit_signal = (lower_32_bits(flags) & CSIGNAL), 2909 .fn = fn, 2910 .fn_arg = arg, 2911 }; 2912 2913 return kernel_clone(&args); 2914 } 2915 2916 #ifdef __ARCH_WANT_SYS_FORK 2917 SYSCALL_DEFINE0(fork) 2918 { 2919 #ifdef CONFIG_MMU 2920 struct kernel_clone_args args = { 2921 .exit_signal = SIGCHLD, 2922 }; 2923 2924 return kernel_clone(&args); 2925 #else 2926 /* can not support in nommu mode */ 2927 return -EINVAL; 2928 #endif 2929 } 2930 #endif 2931 2932 #ifdef __ARCH_WANT_SYS_VFORK 2933 SYSCALL_DEFINE0(vfork) 2934 { 2935 struct kernel_clone_args args = { 2936 .flags = CLONE_VFORK | CLONE_VM, 2937 .exit_signal = SIGCHLD, 2938 }; 2939 2940 return kernel_clone(&args); 2941 } 2942 #endif 2943 2944 #ifdef __ARCH_WANT_SYS_CLONE 2945 #ifdef CONFIG_CLONE_BACKWARDS 2946 SYSCALL_DEFINE5(clone, unsigned long, clone_flags, unsigned long, newsp, 2947 int __user *, parent_tidptr, 2948 unsigned long, tls, 2949 int __user *, child_tidptr) 2950 #elif defined(CONFIG_CLONE_BACKWARDS2) 2951 SYSCALL_DEFINE5(clone, unsigned long, newsp, unsigned long, clone_flags, 2952 int __user *, parent_tidptr, 2953 int __user *, child_tidptr, 2954 unsigned long, tls) 2955 #elif defined(CONFIG_CLONE_BACKWARDS3) 2956 SYSCALL_DEFINE6(clone, unsigned long, clone_flags, unsigned long, newsp, 2957 int, stack_size, 2958 int __user *, parent_tidptr, 2959 int __user *, child_tidptr, 2960 unsigned long, tls) 2961 #else 2962 SYSCALL_DEFINE5(clone, unsigned long, clone_flags, unsigned long, newsp, 2963 int __user *, parent_tidptr, 2964 int __user *, child_tidptr, 2965 unsigned long, tls) 2966 #endif 2967 { 2968 struct kernel_clone_args args = { 2969 .flags = (lower_32_bits(clone_flags) & ~CSIGNAL), 2970 .pidfd = parent_tidptr, 2971 .child_tid = child_tidptr, 2972 .parent_tid = parent_tidptr, 2973 .exit_signal = (lower_32_bits(clone_flags) & CSIGNAL), 2974 .stack = newsp, 2975 .tls = tls, 2976 }; 2977 2978 return kernel_clone(&args); 2979 } 2980 #endif 2981 2982 noinline static int copy_clone_args_from_user(struct kernel_clone_args *kargs, 2983 struct clone_args __user *uargs, 2984 size_t usize) 2985 { 2986 int err; 2987 struct clone_args args; 2988 pid_t *kset_tid = kargs->set_tid; 2989 2990 BUILD_BUG_ON(offsetofend(struct clone_args, tls) != 2991 CLONE_ARGS_SIZE_VER0); 2992 BUILD_BUG_ON(offsetofend(struct clone_args, set_tid_size) != 2993 CLONE_ARGS_SIZE_VER1); 2994 BUILD_BUG_ON(offsetofend(struct clone_args, cgroup) != 2995 CLONE_ARGS_SIZE_VER2); 2996 BUILD_BUG_ON(sizeof(struct clone_args) != CLONE_ARGS_SIZE_VER2); 2997 2998 if (unlikely(usize > PAGE_SIZE)) 2999 return -E2BIG; 3000 if (unlikely(usize < CLONE_ARGS_SIZE_VER0)) 3001 return -EINVAL; 3002 3003 err = copy_struct_from_user(&args, sizeof(args), uargs, usize); 3004 if (err) 3005 return err; 3006 3007 if (unlikely(args.set_tid_size > MAX_PID_NS_LEVEL)) 3008 return -EINVAL; 3009 3010 if (unlikely(!args.set_tid && args.set_tid_size > 0)) 3011 return -EINVAL; 3012 3013 if (unlikely(args.set_tid && args.set_tid_size == 0)) 3014 return -EINVAL; 3015 3016 /* 3017 * Verify that higher 32bits of exit_signal are unset and that 3018 * it is a valid signal 3019 */ 3020 if (unlikely((args.exit_signal & ~((u64)CSIGNAL)) || 3021 !valid_signal(args.exit_signal))) 3022 return -EINVAL; 3023 3024 if ((args.flags & CLONE_INTO_CGROUP) && 3025 (args.cgroup > INT_MAX || usize < CLONE_ARGS_SIZE_VER2)) 3026 return -EINVAL; 3027 3028 *kargs = (struct kernel_clone_args){ 3029 .flags = args.flags, 3030 .pidfd = u64_to_user_ptr(args.pidfd), 3031 .child_tid = u64_to_user_ptr(args.child_tid), 3032 .parent_tid = u64_to_user_ptr(args.parent_tid), 3033 .exit_signal = args.exit_signal, 3034 .stack = args.stack, 3035 .stack_size = args.stack_size, 3036 .tls = args.tls, 3037 .set_tid_size = args.set_tid_size, 3038 .cgroup = args.cgroup, 3039 }; 3040 3041 if (args.set_tid && 3042 copy_from_user(kset_tid, u64_to_user_ptr(args.set_tid), 3043 (kargs->set_tid_size * sizeof(pid_t)))) 3044 return -EFAULT; 3045 3046 kargs->set_tid = kset_tid; 3047 3048 return 0; 3049 } 3050 3051 /** 3052 * clone3_stack_valid - check and prepare stack 3053 * @kargs: kernel clone args 3054 * 3055 * Verify that the stack arguments userspace gave us are sane. 3056 * In addition, set the stack direction for userspace since it's easy for us to 3057 * determine. 3058 */ 3059 static inline bool clone3_stack_valid(struct kernel_clone_args *kargs) 3060 { 3061 if (kargs->stack == 0) { 3062 if (kargs->stack_size > 0) 3063 return false; 3064 } else { 3065 if (kargs->stack_size == 0) 3066 return false; 3067 3068 if (!access_ok((void __user *)kargs->stack, kargs->stack_size)) 3069 return false; 3070 3071 #if !defined(CONFIG_STACK_GROWSUP) 3072 kargs->stack += kargs->stack_size; 3073 #endif 3074 } 3075 3076 return true; 3077 } 3078 3079 static bool clone3_args_valid(struct kernel_clone_args *kargs) 3080 { 3081 /* Verify that no unknown flags are passed along. */ 3082 if (kargs->flags & 3083 ~(CLONE_LEGACY_FLAGS | CLONE_CLEAR_SIGHAND | CLONE_INTO_CGROUP)) 3084 return false; 3085 3086 /* 3087 * - make the CLONE_DETACHED bit reusable for clone3 3088 * - make the CSIGNAL bits reusable for clone3 3089 */ 3090 if (kargs->flags & (CLONE_DETACHED | (CSIGNAL & (~CLONE_NEWTIME)))) 3091 return false; 3092 3093 if ((kargs->flags & (CLONE_SIGHAND | CLONE_CLEAR_SIGHAND)) == 3094 (CLONE_SIGHAND | CLONE_CLEAR_SIGHAND)) 3095 return false; 3096 3097 if ((kargs->flags & (CLONE_THREAD | CLONE_PARENT)) && 3098 kargs->exit_signal) 3099 return false; 3100 3101 if (!clone3_stack_valid(kargs)) 3102 return false; 3103 3104 return true; 3105 } 3106 3107 /** 3108 * sys_clone3 - create a new process with specific properties 3109 * @uargs: argument structure 3110 * @size: size of @uargs 3111 * 3112 * clone3() is the extensible successor to clone()/clone2(). 3113 * It takes a struct as argument that is versioned by its size. 3114 * 3115 * Return: On success, a positive PID for the child process. 3116 * On error, a negative errno number. 3117 */ 3118 SYSCALL_DEFINE2(clone3, struct clone_args __user *, uargs, size_t, size) 3119 { 3120 int err; 3121 3122 struct kernel_clone_args kargs; 3123 pid_t set_tid[MAX_PID_NS_LEVEL]; 3124 3125 #ifdef __ARCH_BROKEN_SYS_CLONE3 3126 #warning clone3() entry point is missing, please fix 3127 return -ENOSYS; 3128 #endif 3129 3130 kargs.set_tid = set_tid; 3131 3132 err = copy_clone_args_from_user(&kargs, uargs, size); 3133 if (err) 3134 return err; 3135 3136 if (!clone3_args_valid(&kargs)) 3137 return -EINVAL; 3138 3139 return kernel_clone(&kargs); 3140 } 3141 3142 void walk_process_tree(struct task_struct *top, proc_visitor visitor, void *data) 3143 { 3144 struct task_struct *leader, *parent, *child; 3145 int res; 3146 3147 read_lock(&tasklist_lock); 3148 leader = top = top->group_leader; 3149 down: 3150 for_each_thread(leader, parent) { 3151 list_for_each_entry(child, &parent->children, sibling) { 3152 res = visitor(child, data); 3153 if (res) { 3154 if (res < 0) 3155 goto out; 3156 leader = child; 3157 goto down; 3158 } 3159 up: 3160 ; 3161 } 3162 } 3163 3164 if (leader != top) { 3165 child = leader; 3166 parent = child->real_parent; 3167 leader = parent->group_leader; 3168 goto up; 3169 } 3170 out: 3171 read_unlock(&tasklist_lock); 3172 } 3173 3174 #ifndef ARCH_MIN_MMSTRUCT_ALIGN 3175 #define ARCH_MIN_MMSTRUCT_ALIGN 0 3176 #endif 3177 3178 static void sighand_ctor(void *data) 3179 { 3180 struct sighand_struct *sighand = data; 3181 3182 spin_lock_init(&sighand->siglock); 3183 init_waitqueue_head(&sighand->signalfd_wqh); 3184 } 3185 3186 void __init mm_cache_init(void) 3187 { 3188 unsigned int mm_size; 3189 3190 /* 3191 * The mm_cpumask is located at the end of mm_struct, and is 3192 * dynamically sized based on the maximum CPU number this system 3193 * can have, taking hotplug into account (nr_cpu_ids). 3194 */ 3195 mm_size = sizeof(struct mm_struct) + cpumask_size() + mm_cid_size(); 3196 3197 mm_cachep = kmem_cache_create_usercopy("mm_struct", 3198 mm_size, ARCH_MIN_MMSTRUCT_ALIGN, 3199 SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_ACCOUNT, 3200 offsetof(struct mm_struct, saved_auxv), 3201 sizeof_field(struct mm_struct, saved_auxv), 3202 NULL); 3203 } 3204 3205 void __init proc_caches_init(void) 3206 { 3207 struct kmem_cache_args args = { 3208 .use_freeptr_offset = true, 3209 .freeptr_offset = offsetof(struct vm_area_struct, vm_freeptr), 3210 }; 3211 3212 sighand_cachep = kmem_cache_create("sighand_cache", 3213 sizeof(struct sighand_struct), 0, 3214 SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_TYPESAFE_BY_RCU| 3215 SLAB_ACCOUNT, sighand_ctor); 3216 signal_cachep = kmem_cache_create("signal_cache", 3217 sizeof(struct signal_struct), 0, 3218 SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_ACCOUNT, 3219 NULL); 3220 files_cachep = kmem_cache_create("files_cache", 3221 sizeof(struct files_struct), 0, 3222 SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_ACCOUNT, 3223 NULL); 3224 fs_cachep = kmem_cache_create("fs_cache", 3225 sizeof(struct fs_struct), 0, 3226 SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_ACCOUNT, 3227 NULL); 3228 vm_area_cachep = kmem_cache_create("vm_area_struct", 3229 sizeof(struct vm_area_struct), &args, 3230 SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_TYPESAFE_BY_RCU| 3231 SLAB_ACCOUNT); 3232 mmap_init(); 3233 nsproxy_cache_init(); 3234 } 3235 3236 /* 3237 * Check constraints on flags passed to the unshare system call. 3238 */ 3239 static int check_unshare_flags(unsigned long unshare_flags) 3240 { 3241 if (unshare_flags & ~(CLONE_THREAD|CLONE_FS|CLONE_NEWNS|CLONE_SIGHAND| 3242 CLONE_VM|CLONE_FILES|CLONE_SYSVSEM| 3243 CLONE_NEWUTS|CLONE_NEWIPC|CLONE_NEWNET| 3244 CLONE_NEWUSER|CLONE_NEWPID|CLONE_NEWCGROUP| 3245 CLONE_NEWTIME)) 3246 return -EINVAL; 3247 /* 3248 * Not implemented, but pretend it works if there is nothing 3249 * to unshare. Note that unsharing the address space or the 3250 * signal handlers also need to unshare the signal queues (aka 3251 * CLONE_THREAD). 3252 */ 3253 if (unshare_flags & (CLONE_THREAD | CLONE_SIGHAND | CLONE_VM)) { 3254 if (!thread_group_empty(current)) 3255 return -EINVAL; 3256 } 3257 if (unshare_flags & (CLONE_SIGHAND | CLONE_VM)) { 3258 if (refcount_read(¤t->sighand->count) > 1) 3259 return -EINVAL; 3260 } 3261 if (unshare_flags & CLONE_VM) { 3262 if (!current_is_single_threaded()) 3263 return -EINVAL; 3264 } 3265 3266 return 0; 3267 } 3268 3269 /* 3270 * Unshare the filesystem structure if it is being shared 3271 */ 3272 static int unshare_fs(unsigned long unshare_flags, struct fs_struct **new_fsp) 3273 { 3274 struct fs_struct *fs = current->fs; 3275 3276 if (!(unshare_flags & CLONE_FS) || !fs) 3277 return 0; 3278 3279 /* don't need lock here; in the worst case we'll do useless copy */ 3280 if (fs->users == 1) 3281 return 0; 3282 3283 *new_fsp = copy_fs_struct(fs); 3284 if (!*new_fsp) 3285 return -ENOMEM; 3286 3287 return 0; 3288 } 3289 3290 /* 3291 * Unshare file descriptor table if it is being shared 3292 */ 3293 static int unshare_fd(unsigned long unshare_flags, struct files_struct **new_fdp) 3294 { 3295 struct files_struct *fd = current->files; 3296 3297 if ((unshare_flags & CLONE_FILES) && 3298 (fd && atomic_read(&fd->count) > 1)) { 3299 fd = dup_fd(fd, NULL); 3300 if (IS_ERR(fd)) 3301 return PTR_ERR(fd); 3302 *new_fdp = fd; 3303 } 3304 3305 return 0; 3306 } 3307 3308 /* 3309 * unshare allows a process to 'unshare' part of the process 3310 * context which was originally shared using clone. copy_* 3311 * functions used by kernel_clone() cannot be used here directly 3312 * because they modify an inactive task_struct that is being 3313 * constructed. Here we are modifying the current, active, 3314 * task_struct. 3315 */ 3316 int ksys_unshare(unsigned long unshare_flags) 3317 { 3318 struct fs_struct *fs, *new_fs = NULL; 3319 struct files_struct *new_fd = NULL; 3320 struct cred *new_cred = NULL; 3321 struct nsproxy *new_nsproxy = NULL; 3322 int do_sysvsem = 0; 3323 int err; 3324 3325 /* 3326 * If unsharing a user namespace must also unshare the thread group 3327 * and unshare the filesystem root and working directories. 3328 */ 3329 if (unshare_flags & CLONE_NEWUSER) 3330 unshare_flags |= CLONE_THREAD | CLONE_FS; 3331 /* 3332 * If unsharing vm, must also unshare signal handlers. 3333 */ 3334 if (unshare_flags & CLONE_VM) 3335 unshare_flags |= CLONE_SIGHAND; 3336 /* 3337 * If unsharing a signal handlers, must also unshare the signal queues. 3338 */ 3339 if (unshare_flags & CLONE_SIGHAND) 3340 unshare_flags |= CLONE_THREAD; 3341 /* 3342 * If unsharing namespace, must also unshare filesystem information. 3343 */ 3344 if (unshare_flags & CLONE_NEWNS) 3345 unshare_flags |= CLONE_FS; 3346 3347 err = check_unshare_flags(unshare_flags); 3348 if (err) 3349 goto bad_unshare_out; 3350 /* 3351 * CLONE_NEWIPC must also detach from the undolist: after switching 3352 * to a new ipc namespace, the semaphore arrays from the old 3353 * namespace are unreachable. 3354 */ 3355 if (unshare_flags & (CLONE_NEWIPC|CLONE_SYSVSEM)) 3356 do_sysvsem = 1; 3357 err = unshare_fs(unshare_flags, &new_fs); 3358 if (err) 3359 goto bad_unshare_out; 3360 err = unshare_fd(unshare_flags, &new_fd); 3361 if (err) 3362 goto bad_unshare_cleanup_fs; 3363 err = unshare_userns(unshare_flags, &new_cred); 3364 if (err) 3365 goto bad_unshare_cleanup_fd; 3366 err = unshare_nsproxy_namespaces(unshare_flags, &new_nsproxy, 3367 new_cred, new_fs); 3368 if (err) 3369 goto bad_unshare_cleanup_cred; 3370 3371 if (new_cred) { 3372 err = set_cred_ucounts(new_cred); 3373 if (err) 3374 goto bad_unshare_cleanup_cred; 3375 } 3376 3377 if (new_fs || new_fd || do_sysvsem || new_cred || new_nsproxy) { 3378 if (do_sysvsem) { 3379 /* 3380 * CLONE_SYSVSEM is equivalent to sys_exit(). 3381 */ 3382 exit_sem(current); 3383 } 3384 if (unshare_flags & CLONE_NEWIPC) { 3385 /* Orphan segments in old ns (see sem above). */ 3386 exit_shm(current); 3387 shm_init_task(current); 3388 } 3389 3390 if (new_nsproxy) 3391 switch_task_namespaces(current, new_nsproxy); 3392 3393 task_lock(current); 3394 3395 if (new_fs) { 3396 fs = current->fs; 3397 spin_lock(&fs->lock); 3398 current->fs = new_fs; 3399 if (--fs->users) 3400 new_fs = NULL; 3401 else 3402 new_fs = fs; 3403 spin_unlock(&fs->lock); 3404 } 3405 3406 if (new_fd) 3407 swap(current->files, new_fd); 3408 3409 task_unlock(current); 3410 3411 if (new_cred) { 3412 /* Install the new user namespace */ 3413 commit_creds(new_cred); 3414 new_cred = NULL; 3415 } 3416 } 3417 3418 perf_event_namespaces(current); 3419 3420 bad_unshare_cleanup_cred: 3421 if (new_cred) 3422 put_cred(new_cred); 3423 bad_unshare_cleanup_fd: 3424 if (new_fd) 3425 put_files_struct(new_fd); 3426 3427 bad_unshare_cleanup_fs: 3428 if (new_fs) 3429 free_fs_struct(new_fs); 3430 3431 bad_unshare_out: 3432 return err; 3433 } 3434 3435 SYSCALL_DEFINE1(unshare, unsigned long, unshare_flags) 3436 { 3437 return ksys_unshare(unshare_flags); 3438 } 3439 3440 /* 3441 * Helper to unshare the files of the current task. 3442 * We don't want to expose copy_files internals to 3443 * the exec layer of the kernel. 3444 */ 3445 3446 int unshare_files(void) 3447 { 3448 struct task_struct *task = current; 3449 struct files_struct *old, *copy = NULL; 3450 int error; 3451 3452 error = unshare_fd(CLONE_FILES, ©); 3453 if (error || !copy) 3454 return error; 3455 3456 old = task->files; 3457 task_lock(task); 3458 task->files = copy; 3459 task_unlock(task); 3460 put_files_struct(old); 3461 return 0; 3462 } 3463 3464 int sysctl_max_threads(const struct ctl_table *table, int write, 3465 void *buffer, size_t *lenp, loff_t *ppos) 3466 { 3467 struct ctl_table t; 3468 int ret; 3469 int threads = max_threads; 3470 int min = 1; 3471 int max = MAX_THREADS; 3472 3473 t = *table; 3474 t.data = &threads; 3475 t.extra1 = &min; 3476 t.extra2 = &max; 3477 3478 ret = proc_dointvec_minmax(&t, write, buffer, lenp, ppos); 3479 if (ret || !write) 3480 return ret; 3481 3482 max_threads = threads; 3483 3484 return 0; 3485 } 3486