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