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