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