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