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