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