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