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/io_uring_types.h> 101 #include <linux/bpf.h> 102 #include <linux/stackprotector.h> 103 #include <linux/user_events.h> 104 #include <linux/iommu.h> 105 #include <linux/rseq.h> 106 #include <uapi/linux/pidfd.h> 107 #include <linux/pidfs.h> 108 #include <linux/tick.h> 109 #include <linux/unwind_deferred.h> 110 #include <linux/pgalloc.h> 111 #include <linux/uaccess.h> 112 113 #include <asm/mmu_context.h> 114 #include <asm/cacheflush.h> 115 #include <asm/tlbflush.h> 116 117 /* For dup_mmap(). */ 118 #include "../mm/internal.h" 119 120 #include <trace/events/sched.h> 121 122 #define CREATE_TRACE_POINTS 123 #include <trace/events/task.h> 124 125 #include <kunit/visibility.h> 126 127 /* 128 * Minimum number of threads to boot the kernel 129 */ 130 #define MIN_THREADS 20 131 132 /* 133 * Maximum number of threads 134 */ 135 #define MAX_THREADS FUTEX_TID_MASK 136 137 /* 138 * Protected counters by write_lock_irq(&tasklist_lock) 139 */ 140 unsigned long total_forks; /* Handle normal Linux uptimes. */ 141 int nr_threads; /* The idle threads do not count.. */ 142 143 static int max_threads; /* tunable limit on nr_threads */ 144 145 #define NAMED_ARRAY_INDEX(x) [x] = __stringify(x) 146 147 static const char * const resident_page_types[] = { 148 NAMED_ARRAY_INDEX(MM_FILEPAGES), 149 NAMED_ARRAY_INDEX(MM_ANONPAGES), 150 NAMED_ARRAY_INDEX(MM_SWAPENTS), 151 NAMED_ARRAY_INDEX(MM_SHMEMPAGES), 152 }; 153 154 DEFINE_PER_CPU(unsigned long, process_counts) = 0; 155 156 __cacheline_aligned DEFINE_RWLOCK(tasklist_lock); /* outer */ 157 158 #ifdef CONFIG_PROVE_RCU 159 int lockdep_tasklist_lock_is_held(void) 160 { 161 return lockdep_is_held(&tasklist_lock); 162 } 163 EXPORT_SYMBOL_GPL(lockdep_tasklist_lock_is_held); 164 #endif /* #ifdef CONFIG_PROVE_RCU */ 165 166 int nr_processes(void) 167 { 168 int cpu; 169 int total = 0; 170 171 for_each_possible_cpu(cpu) 172 total += per_cpu(process_counts, cpu); 173 174 return total; 175 } 176 177 void __weak arch_release_task_struct(struct task_struct *tsk) 178 { 179 } 180 181 static struct kmem_cache *task_struct_cachep; 182 183 static inline struct task_struct *alloc_task_struct_node(int node) 184 { 185 return kmem_cache_alloc_node(task_struct_cachep, GFP_KERNEL, node); 186 } 187 188 static inline void free_task_struct(struct task_struct *tsk) 189 { 190 kmem_cache_free(task_struct_cachep, tsk); 191 } 192 193 #ifdef CONFIG_VMAP_STACK 194 /* 195 * vmalloc() is a bit slow, and calling vfree() enough times will force a TLB 196 * flush. Try to minimize the number of calls by caching stacks. 197 */ 198 #define NR_CACHED_STACKS 2 199 static DEFINE_PER_CPU(struct vm_struct *, cached_stacks[NR_CACHED_STACKS]); 200 /* 201 * Allocated stacks are cached and later reused by new threads, so memcg 202 * accounting is performed by the code assigning/releasing stacks to tasks. 203 * We need a zeroed memory without __GFP_ACCOUNT. 204 */ 205 #define GFP_VMAP_STACK (GFP_KERNEL | __GFP_ZERO) 206 207 struct vm_stack { 208 struct rcu_head rcu; 209 struct vm_struct *stack_vm_area; 210 }; 211 212 static struct vm_struct *alloc_thread_stack_node_from_cache(struct task_struct *tsk, int node) 213 { 214 struct vm_struct *vm_area; 215 unsigned int i; 216 217 /* 218 * If the node has memory, we are guaranteed the stacks are backed by local pages. 219 * Otherwise the pages are arbitrary. 220 * 221 * Note that depending on cpuset it is possible we will get migrated to a different 222 * node immediately after allocating here, so this does *not* guarantee locality for 223 * arbitrary callers. 224 */ 225 scoped_guard(preempt) { 226 if (node != NUMA_NO_NODE && numa_node_id() != node) 227 return NULL; 228 229 for (i = 0; i < NR_CACHED_STACKS; i++) { 230 vm_area = this_cpu_xchg(cached_stacks[i], NULL); 231 if (vm_area) 232 return vm_area; 233 } 234 } 235 236 return NULL; 237 } 238 239 static bool try_release_thread_stack_to_cache(struct vm_struct *vm_area) 240 { 241 unsigned int i; 242 int nid; 243 244 /* 245 * Don't cache stacks if any of the pages don't match the local domain, unless 246 * there is no local memory to begin with. 247 * 248 * Note that lack of local memory does not automatically mean it makes no difference 249 * performance-wise which other domain backs the stack. In this case we are merely 250 * trying to avoid constantly going to vmalloc. 251 */ 252 scoped_guard(preempt) { 253 nid = numa_node_id(); 254 if (node_state(nid, N_MEMORY)) { 255 for (i = 0; i < vm_area->nr_pages; i++) { 256 struct page *page = vm_area->pages[i]; 257 if (page_to_nid(page) != nid) 258 return false; 259 } 260 } 261 262 for (i = 0; i < NR_CACHED_STACKS; i++) { 263 struct vm_struct *tmp = NULL; 264 265 if (this_cpu_try_cmpxchg(cached_stacks[i], &tmp, vm_area)) 266 return true; 267 } 268 } 269 return false; 270 } 271 272 static void thread_stack_free_rcu(struct rcu_head *rh) 273 { 274 struct vm_stack *vm_stack = container_of(rh, struct vm_stack, rcu); 275 struct vm_struct *vm_area = vm_stack->stack_vm_area; 276 277 if (try_release_thread_stack_to_cache(vm_stack->stack_vm_area)) 278 return; 279 280 vfree(vm_area->addr); 281 } 282 283 static void thread_stack_delayed_free(struct task_struct *tsk) 284 { 285 struct vm_stack *vm_stack = tsk->stack; 286 287 vm_stack->stack_vm_area = tsk->stack_vm_area; 288 call_rcu(&vm_stack->rcu, thread_stack_free_rcu); 289 } 290 291 static int free_vm_stack_cache(unsigned int cpu) 292 { 293 struct vm_struct **cached_vm_stack_areas = per_cpu_ptr(cached_stacks, cpu); 294 int i; 295 296 for (i = 0; i < NR_CACHED_STACKS; i++) { 297 struct vm_struct *vm_area = cached_vm_stack_areas[i]; 298 299 if (!vm_area) 300 continue; 301 302 vfree(vm_area->addr); 303 cached_vm_stack_areas[i] = NULL; 304 } 305 306 return 0; 307 } 308 309 static int memcg_charge_kernel_stack(struct vm_struct *vm_area) 310 { 311 int i; 312 int ret; 313 int nr_charged = 0; 314 315 BUG_ON(vm_area->nr_pages != THREAD_SIZE / PAGE_SIZE); 316 317 for (i = 0; i < THREAD_SIZE / PAGE_SIZE; i++) { 318 ret = memcg_kmem_charge_page(vm_area->pages[i], GFP_KERNEL, 0); 319 if (ret) 320 goto err; 321 nr_charged++; 322 } 323 return 0; 324 err: 325 for (i = 0; i < nr_charged; i++) 326 memcg_kmem_uncharge_page(vm_area->pages[i], 0); 327 return ret; 328 } 329 330 static int alloc_thread_stack_node(struct task_struct *tsk, int node) 331 { 332 struct vm_struct *vm_area; 333 void *stack; 334 335 vm_area = alloc_thread_stack_node_from_cache(tsk, node); 336 if (vm_area) { 337 if (memcg_charge_kernel_stack(vm_area)) { 338 vfree(vm_area->addr); 339 return -ENOMEM; 340 } 341 342 /* Reset stack metadata. */ 343 kasan_unpoison_range(vm_area->addr, THREAD_SIZE); 344 345 stack = kasan_reset_tag(vm_area->addr); 346 347 /* Clear stale pointers from reused stack. */ 348 clear_pages(vm_area->addr, vm_area->nr_pages); 349 350 tsk->stack_vm_area = vm_area; 351 tsk->stack = stack; 352 return 0; 353 } 354 355 stack = __vmalloc_node(THREAD_SIZE, THREAD_ALIGN, 356 GFP_VMAP_STACK, 357 node, __builtin_return_address(0)); 358 if (!stack) 359 return -ENOMEM; 360 361 vm_area = find_vm_area(stack); 362 if (memcg_charge_kernel_stack(vm_area)) { 363 vfree(stack); 364 return -ENOMEM; 365 } 366 /* 367 * We can't call find_vm_area() in interrupt context, and 368 * free_thread_stack() can be called in interrupt context, 369 * so cache the vm_struct. 370 */ 371 tsk->stack_vm_area = vm_area; 372 stack = kasan_reset_tag(stack); 373 tsk->stack = stack; 374 return 0; 375 } 376 377 static void free_thread_stack(struct task_struct *tsk) 378 { 379 if (!try_release_thread_stack_to_cache(tsk->stack_vm_area)) 380 thread_stack_delayed_free(tsk); 381 382 tsk->stack = NULL; 383 tsk->stack_vm_area = NULL; 384 } 385 386 #else /* !CONFIG_VMAP_STACK */ 387 388 /* 389 * Allocate pages if THREAD_SIZE is >= PAGE_SIZE, otherwise use a 390 * kmemcache based allocator. 391 */ 392 #if THREAD_SIZE >= PAGE_SIZE 393 394 static void thread_stack_free_rcu(struct rcu_head *rh) 395 { 396 __free_pages(virt_to_page(rh), THREAD_SIZE_ORDER); 397 } 398 399 static void thread_stack_delayed_free(struct task_struct *tsk) 400 { 401 struct rcu_head *rh = tsk->stack; 402 403 call_rcu(rh, thread_stack_free_rcu); 404 } 405 406 static int alloc_thread_stack_node(struct task_struct *tsk, int node) 407 { 408 struct page *page = alloc_pages_node(node, THREADINFO_GFP, 409 THREAD_SIZE_ORDER); 410 411 if (likely(page)) { 412 tsk->stack = kasan_reset_tag(page_address(page)); 413 return 0; 414 } 415 return -ENOMEM; 416 } 417 418 static void free_thread_stack(struct task_struct *tsk) 419 { 420 thread_stack_delayed_free(tsk); 421 tsk->stack = NULL; 422 } 423 424 #else /* !(THREAD_SIZE >= PAGE_SIZE) */ 425 426 static struct kmem_cache *thread_stack_cache; 427 428 static void thread_stack_free_rcu(struct rcu_head *rh) 429 { 430 kmem_cache_free(thread_stack_cache, rh); 431 } 432 433 static void thread_stack_delayed_free(struct task_struct *tsk) 434 { 435 struct rcu_head *rh = tsk->stack; 436 437 call_rcu(rh, thread_stack_free_rcu); 438 } 439 440 static int alloc_thread_stack_node(struct task_struct *tsk, int node) 441 { 442 unsigned long *stack; 443 stack = kmem_cache_alloc_node(thread_stack_cache, THREADINFO_GFP, node); 444 stack = kasan_reset_tag(stack); 445 tsk->stack = stack; 446 return stack ? 0 : -ENOMEM; 447 } 448 449 static void free_thread_stack(struct task_struct *tsk) 450 { 451 thread_stack_delayed_free(tsk); 452 tsk->stack = NULL; 453 } 454 455 void thread_stack_cache_init(void) 456 { 457 thread_stack_cache = kmem_cache_create_usercopy("thread_stack", 458 THREAD_SIZE, THREAD_SIZE, 0, 0, 459 THREAD_SIZE, NULL); 460 BUG_ON(thread_stack_cache == NULL); 461 } 462 463 #endif /* THREAD_SIZE >= PAGE_SIZE */ 464 #endif /* CONFIG_VMAP_STACK */ 465 466 /* SLAB cache for signal_struct structures (tsk->signal) */ 467 static struct kmem_cache *signal_cachep; 468 469 /* SLAB cache for sighand_struct structures (tsk->sighand) */ 470 struct kmem_cache *sighand_cachep; 471 472 /* SLAB cache for files_struct structures (tsk->files) */ 473 struct kmem_cache *files_cachep; 474 475 /* SLAB cache for fs_struct structures (tsk->fs) */ 476 struct kmem_cache *fs_cachep; 477 478 /* SLAB cache for mm_struct structures (tsk->mm) */ 479 static struct kmem_cache *mm_cachep; 480 481 static void account_kernel_stack(struct task_struct *tsk, int account) 482 { 483 if (IS_ENABLED(CONFIG_VMAP_STACK)) { 484 struct vm_struct *vm_area = task_stack_vm_area(tsk); 485 int i; 486 487 for (i = 0; i < THREAD_SIZE / PAGE_SIZE; i++) 488 mod_lruvec_page_state(vm_area->pages[i], NR_KERNEL_STACK_KB, 489 account * (PAGE_SIZE / 1024)); 490 } else { 491 void *stack = task_stack_page(tsk); 492 493 /* All stack pages are in the same node. */ 494 mod_lruvec_kmem_state(stack, NR_KERNEL_STACK_KB, 495 account * (THREAD_SIZE / 1024)); 496 } 497 } 498 499 void exit_task_stack_account(struct task_struct *tsk) 500 { 501 account_kernel_stack(tsk, -1); 502 503 if (IS_ENABLED(CONFIG_VMAP_STACK)) { 504 struct vm_struct *vm_area; 505 int i; 506 507 vm_area = task_stack_vm_area(tsk); 508 for (i = 0; i < THREAD_SIZE / PAGE_SIZE; i++) 509 memcg_kmem_uncharge_page(vm_area->pages[i], 0); 510 } 511 } 512 513 static void release_task_stack(struct task_struct *tsk) 514 { 515 if (WARN_ON(READ_ONCE(tsk->__state) != TASK_DEAD)) 516 return; /* Better to leak the stack than to free prematurely */ 517 518 free_thread_stack(tsk); 519 } 520 521 #ifdef CONFIG_THREAD_INFO_IN_TASK 522 void put_task_stack(struct task_struct *tsk) 523 { 524 if (refcount_dec_and_test(&tsk->stack_refcount)) 525 release_task_stack(tsk); 526 } 527 #endif 528 529 void free_task(struct task_struct *tsk) 530 { 531 #ifdef CONFIG_SECCOMP 532 WARN_ON_ONCE(tsk->seccomp.filter); 533 #endif 534 release_user_cpus_ptr(tsk); 535 scs_release(tsk); 536 537 #ifndef CONFIG_THREAD_INFO_IN_TASK 538 /* 539 * The task is finally done with both the stack and thread_info, 540 * so free both. 541 */ 542 release_task_stack(tsk); 543 #else 544 /* 545 * If the task had a separate stack allocation, it should be gone 546 * by now. 547 */ 548 WARN_ON_ONCE(refcount_read(&tsk->stack_refcount) != 0); 549 #endif 550 rt_mutex_debug_task_free(tsk); 551 ftrace_graph_exit_task(tsk); 552 arch_release_task_struct(tsk); 553 if (tsk->flags & PF_KTHREAD) 554 free_kthread_struct(tsk); 555 bpf_task_storage_free(tsk); 556 free_task_struct(tsk); 557 } 558 EXPORT_SYMBOL(free_task); 559 560 void dup_mm_exe_file(struct mm_struct *mm, struct mm_struct *oldmm) 561 { 562 struct file *exe_file; 563 564 exe_file = get_mm_exe_file(oldmm); 565 RCU_INIT_POINTER(mm->exe_file, exe_file); 566 /* 567 * We depend on the oldmm having properly denied write access to the 568 * exe_file already. 569 */ 570 if (exe_file && exe_file_deny_write_access(exe_file)) 571 pr_warn_once("exe_file_deny_write_access() failed in %s\n", __func__); 572 } 573 574 #ifdef CONFIG_MMU 575 static inline int mm_alloc_pgd(struct mm_struct *mm) 576 { 577 mm->pgd = pgd_alloc(mm); 578 if (unlikely(!mm->pgd)) 579 return -ENOMEM; 580 return 0; 581 } 582 583 static inline void mm_free_pgd(struct mm_struct *mm) 584 { 585 pgd_free(mm, mm->pgd); 586 } 587 #else 588 #define mm_alloc_pgd(mm) (0) 589 #define mm_free_pgd(mm) 590 #endif /* CONFIG_MMU */ 591 592 #ifdef CONFIG_MM_ID 593 static DEFINE_IDA(mm_ida); 594 595 static inline int mm_alloc_id(struct mm_struct *mm) 596 { 597 int ret; 598 599 ret = ida_alloc_range(&mm_ida, MM_ID_MIN, MM_ID_MAX, GFP_KERNEL); 600 if (ret < 0) 601 return ret; 602 mm->mm_id = ret; 603 return 0; 604 } 605 606 static inline void mm_free_id(struct mm_struct *mm) 607 { 608 const mm_id_t id = mm->mm_id; 609 610 mm->mm_id = MM_ID_DUMMY; 611 if (id == MM_ID_DUMMY) 612 return; 613 if (WARN_ON_ONCE(id < MM_ID_MIN || id > MM_ID_MAX)) 614 return; 615 ida_free(&mm_ida, id); 616 } 617 #else /* !CONFIG_MM_ID */ 618 static inline int mm_alloc_id(struct mm_struct *mm) { return 0; } 619 static inline void mm_free_id(struct mm_struct *mm) {} 620 #endif /* CONFIG_MM_ID */ 621 622 static void check_mm(struct mm_struct *mm) 623 { 624 int i; 625 626 BUILD_BUG_ON_MSG(ARRAY_SIZE(resident_page_types) != NR_MM_COUNTERS, 627 "Please make sure 'struct resident_page_types[]' is updated as well"); 628 629 for (i = 0; i < NR_MM_COUNTERS; i++) { 630 long x = percpu_counter_sum(&mm->rss_stat[i]); 631 632 if (unlikely(x)) { 633 pr_alert("BUG: Bad rss-counter state mm:%p type:%s val:%ld Comm:%s Pid:%d\n", 634 mm, resident_page_types[i], x, 635 current->comm, 636 task_pid_nr(current)); 637 } 638 } 639 640 if (mm_pgtables_bytes(mm)) 641 pr_alert("BUG: non-zero pgtables_bytes on freeing mm: %ld\n", 642 mm_pgtables_bytes(mm)); 643 644 #if defined(CONFIG_TRANSPARENT_HUGEPAGE) && !defined(CONFIG_SPLIT_PMD_PTLOCKS) 645 VM_BUG_ON_MM(mm->pmd_huge_pte, mm); 646 #endif 647 } 648 649 #define allocate_mm() (kmem_cache_alloc(mm_cachep, GFP_KERNEL)) 650 #define free_mm(mm) (kmem_cache_free(mm_cachep, (mm))) 651 652 static void do_check_lazy_tlb(void *arg) 653 { 654 struct mm_struct *mm = arg; 655 656 WARN_ON_ONCE(current->active_mm == mm); 657 } 658 659 static void do_shoot_lazy_tlb(void *arg) 660 { 661 struct mm_struct *mm = arg; 662 663 if (current->active_mm == mm) { 664 WARN_ON_ONCE(current->mm); 665 current->active_mm = &init_mm; 666 switch_mm(mm, &init_mm, current); 667 } 668 } 669 670 static void cleanup_lazy_tlbs(struct mm_struct *mm) 671 { 672 if (!IS_ENABLED(CONFIG_MMU_LAZY_TLB_SHOOTDOWN)) { 673 /* 674 * In this case, lazy tlb mms are refounted and would not reach 675 * __mmdrop until all CPUs have switched away and mmdrop()ed. 676 */ 677 return; 678 } 679 680 /* 681 * Lazy mm shootdown does not refcount "lazy tlb mm" usage, rather it 682 * requires lazy mm users to switch to another mm when the refcount 683 * drops to zero, before the mm is freed. This requires IPIs here to 684 * switch kernel threads to init_mm. 685 * 686 * archs that use IPIs to flush TLBs can piggy-back that lazy tlb mm 687 * switch with the final userspace teardown TLB flush which leaves the 688 * mm lazy on this CPU but no others, reducing the need for additional 689 * IPIs here. There are cases where a final IPI is still required here, 690 * such as the final mmdrop being performed on a different CPU than the 691 * one exiting, or kernel threads using the mm when userspace exits. 692 * 693 * IPI overheads have not found to be expensive, but they could be 694 * reduced in a number of possible ways, for example (roughly 695 * increasing order of complexity): 696 * - The last lazy reference created by exit_mm() could instead switch 697 * to init_mm, however it's probable this will run on the same CPU 698 * immediately afterwards, so this may not reduce IPIs much. 699 * - A batch of mms requiring IPIs could be gathered and freed at once. 700 * - CPUs store active_mm where it can be remotely checked without a 701 * lock, to filter out false-positives in the cpumask. 702 * - After mm_users or mm_count reaches zero, switching away from the 703 * mm could clear mm_cpumask to reduce some IPIs, perhaps together 704 * with some batching or delaying of the final IPIs. 705 * - A delayed freeing and RCU-like quiescing sequence based on mm 706 * switching to avoid IPIs completely. 707 */ 708 on_each_cpu_mask(mm_cpumask(mm), do_shoot_lazy_tlb, (void *)mm, 1); 709 if (IS_ENABLED(CONFIG_DEBUG_VM_SHOOT_LAZIES)) 710 on_each_cpu(do_check_lazy_tlb, (void *)mm, 1); 711 } 712 713 /* 714 * Called when the last reference to the mm 715 * is dropped: either by a lazy thread or by 716 * mmput. Free the page directory and the mm. 717 */ 718 void __mmdrop(struct mm_struct *mm) 719 { 720 BUG_ON(mm == &init_mm); 721 WARN_ON_ONCE(mm == current->mm); 722 723 /* Ensure no CPUs are using this as their lazy tlb mm */ 724 cleanup_lazy_tlbs(mm); 725 726 WARN_ON_ONCE(mm == current->active_mm); 727 mm_free_pgd(mm); 728 mm_free_id(mm); 729 destroy_context(mm); 730 mmu_notifier_subscriptions_destroy(mm); 731 check_mm(mm); 732 put_user_ns(mm->user_ns); 733 mm_pasid_drop(mm); 734 mm_destroy_cid(mm); 735 percpu_counter_destroy_many(mm->rss_stat, NR_MM_COUNTERS); 736 737 free_mm(mm); 738 } 739 EXPORT_SYMBOL_GPL(__mmdrop); 740 741 static void mmdrop_async_fn(struct work_struct *work) 742 { 743 struct mm_struct *mm; 744 745 mm = container_of(work, struct mm_struct, async_put_work); 746 __mmdrop(mm); 747 } 748 749 static void mmdrop_async(struct mm_struct *mm) 750 { 751 if (unlikely(atomic_dec_and_test(&mm->mm_count))) { 752 INIT_WORK(&mm->async_put_work, mmdrop_async_fn); 753 schedule_work(&mm->async_put_work); 754 } 755 } 756 757 static inline void free_signal_struct(struct signal_struct *sig) 758 { 759 taskstats_tgid_free(sig); 760 sched_autogroup_exit(sig); 761 /* 762 * __mmdrop is not safe to call from softirq context on x86 due to 763 * pgd_dtor so postpone it to the async context 764 */ 765 if (sig->oom_mm) 766 mmdrop_async(sig->oom_mm); 767 kmem_cache_free(signal_cachep, sig); 768 } 769 770 static inline void put_signal_struct(struct signal_struct *sig) 771 { 772 if (refcount_dec_and_test(&sig->sigcnt)) 773 free_signal_struct(sig); 774 } 775 776 void __put_task_struct(struct task_struct *tsk) 777 { 778 WARN_ON(!tsk->exit_state); 779 WARN_ON(refcount_read(&tsk->usage)); 780 WARN_ON(tsk == current); 781 782 unwind_task_free(tsk); 783 io_uring_free(tsk); 784 cgroup_task_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.cid = MM_CID_UNSET; 1002 tsk->mm_cid.active = 0; 1003 INIT_HLIST_NODE(&tsk->mm_cid.node); 1004 #endif 1005 return tsk; 1006 1007 free_stack: 1008 exit_task_stack_account(tsk); 1009 free_thread_stack(tsk); 1010 free_tsk: 1011 free_task_struct(tsk); 1012 return NULL; 1013 } 1014 1015 __cacheline_aligned_in_smp DEFINE_SPINLOCK(mmlist_lock); 1016 1017 static unsigned long coredump_filter = MMF_DUMP_FILTER_DEFAULT; 1018 1019 static int __init coredump_filter_setup(char *s) 1020 { 1021 if (kstrtoul(s, 0, &coredump_filter)) 1022 return 0; 1023 coredump_filter <<= MMF_DUMP_FILTER_SHIFT; 1024 coredump_filter &= 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_overwrite_word(mm, mmf_init_legacy_flags(flags)); 1108 mm->def_flags = current->mm->def_flags & VM_INIT_DEF_MASK; 1109 } else { 1110 __mm_flags_overwrite_word(mm, coredump_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 kthread_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 return 0; 1592 } 1593 1594 static int copy_fs(u64 clone_flags, struct task_struct *tsk) 1595 { 1596 struct fs_struct *fs = current->fs; 1597 if (clone_flags & CLONE_FS) { 1598 /* tsk->fs is already what we want */ 1599 read_seqlock_excl(&fs->seq); 1600 /* "users" and "in_exec" locked for check_unsafe_exec() */ 1601 if (fs->in_exec) { 1602 read_sequnlock_excl(&fs->seq); 1603 return -EAGAIN; 1604 } 1605 fs->users++; 1606 read_sequnlock_excl(&fs->seq); 1607 return 0; 1608 } 1609 tsk->fs = copy_fs_struct(fs); 1610 if (!tsk->fs) 1611 return -ENOMEM; 1612 return 0; 1613 } 1614 1615 static int copy_files(u64 clone_flags, struct task_struct *tsk, 1616 int no_files) 1617 { 1618 struct files_struct *oldf, *newf; 1619 1620 /* 1621 * A background process may not have any files ... 1622 */ 1623 oldf = current->files; 1624 if (!oldf) 1625 return 0; 1626 1627 if (no_files) { 1628 tsk->files = NULL; 1629 return 0; 1630 } 1631 1632 if (clone_flags & CLONE_FILES) { 1633 atomic_inc(&oldf->count); 1634 return 0; 1635 } 1636 1637 newf = dup_fd(oldf, NULL); 1638 if (IS_ERR(newf)) 1639 return PTR_ERR(newf); 1640 1641 tsk->files = newf; 1642 return 0; 1643 } 1644 1645 static int copy_sighand(u64 clone_flags, struct task_struct *tsk) 1646 { 1647 struct sighand_struct *sig; 1648 1649 if (clone_flags & CLONE_SIGHAND) { 1650 refcount_inc(¤t->sighand->count); 1651 return 0; 1652 } 1653 sig = kmem_cache_alloc(sighand_cachep, GFP_KERNEL); 1654 RCU_INIT_POINTER(tsk->sighand, sig); 1655 if (!sig) 1656 return -ENOMEM; 1657 1658 refcount_set(&sig->count, 1); 1659 spin_lock_irq(¤t->sighand->siglock); 1660 memcpy(sig->action, current->sighand->action, sizeof(sig->action)); 1661 spin_unlock_irq(¤t->sighand->siglock); 1662 1663 /* Reset all signal handler not set to SIG_IGN to SIG_DFL. */ 1664 if (clone_flags & CLONE_CLEAR_SIGHAND) 1665 flush_signal_handlers(tsk, 0); 1666 1667 return 0; 1668 } 1669 1670 void __cleanup_sighand(struct sighand_struct *sighand) 1671 { 1672 if (refcount_dec_and_test(&sighand->count)) { 1673 signalfd_cleanup(sighand); 1674 /* 1675 * sighand_cachep is SLAB_TYPESAFE_BY_RCU so we can free it 1676 * without an RCU grace period, see __lock_task_sighand(). 1677 */ 1678 kmem_cache_free(sighand_cachep, sighand); 1679 } 1680 } 1681 1682 /* 1683 * Initialize POSIX timer handling for a thread group. 1684 */ 1685 static void posix_cpu_timers_init_group(struct signal_struct *sig) 1686 { 1687 struct posix_cputimers *pct = &sig->posix_cputimers; 1688 unsigned long cpu_limit; 1689 1690 cpu_limit = READ_ONCE(sig->rlim[RLIMIT_CPU].rlim_cur); 1691 posix_cputimers_group_init(pct, cpu_limit); 1692 } 1693 1694 static int copy_signal(u64 clone_flags, struct task_struct *tsk) 1695 { 1696 struct signal_struct *sig; 1697 1698 if (clone_flags & CLONE_THREAD) 1699 return 0; 1700 1701 sig = kmem_cache_zalloc(signal_cachep, GFP_KERNEL); 1702 tsk->signal = sig; 1703 if (!sig) 1704 return -ENOMEM; 1705 1706 sig->nr_threads = 1; 1707 sig->quick_threads = 1; 1708 atomic_set(&sig->live, 1); 1709 refcount_set(&sig->sigcnt, 1); 1710 1711 /* list_add(thread_node, thread_head) without INIT_LIST_HEAD() */ 1712 sig->thread_head = (struct list_head)LIST_HEAD_INIT(tsk->thread_node); 1713 tsk->thread_node = (struct list_head)LIST_HEAD_INIT(sig->thread_head); 1714 1715 init_waitqueue_head(&sig->wait_chldexit); 1716 sig->curr_target = tsk; 1717 init_sigpending(&sig->shared_pending); 1718 INIT_HLIST_HEAD(&sig->multiprocess); 1719 seqlock_init(&sig->stats_lock); 1720 prev_cputime_init(&sig->prev_cputime); 1721 1722 #ifdef CONFIG_POSIX_TIMERS 1723 INIT_HLIST_HEAD(&sig->posix_timers); 1724 INIT_HLIST_HEAD(&sig->ignored_posix_timers); 1725 hrtimer_setup(&sig->real_timer, it_real_fn, CLOCK_MONOTONIC, HRTIMER_MODE_REL); 1726 #endif 1727 1728 task_lock(current->group_leader); 1729 memcpy(sig->rlim, current->signal->rlim, sizeof sig->rlim); 1730 task_unlock(current->group_leader); 1731 1732 posix_cpu_timers_init_group(sig); 1733 1734 tty_audit_fork(sig); 1735 sched_autogroup_fork(sig); 1736 1737 #ifdef CONFIG_CGROUPS 1738 init_rwsem(&sig->cgroup_threadgroup_rwsem); 1739 #endif 1740 1741 sig->oom_score_adj = current->signal->oom_score_adj; 1742 sig->oom_score_adj_min = current->signal->oom_score_adj_min; 1743 1744 mutex_init(&sig->cred_guard_mutex); 1745 init_rwsem(&sig->exec_update_lock); 1746 1747 return 0; 1748 } 1749 1750 static void copy_seccomp(struct task_struct *p) 1751 { 1752 #ifdef CONFIG_SECCOMP 1753 /* 1754 * Must be called with sighand->lock held, which is common to 1755 * all threads in the group. Holding cred_guard_mutex is not 1756 * needed because this new task is not yet running and cannot 1757 * be racing exec. 1758 */ 1759 assert_spin_locked(¤t->sighand->siglock); 1760 1761 /* Ref-count the new filter user, and assign it. */ 1762 get_seccomp_filter(current); 1763 p->seccomp = current->seccomp; 1764 1765 /* 1766 * Explicitly enable no_new_privs here in case it got set 1767 * between the task_struct being duplicated and holding the 1768 * sighand lock. The seccomp state and nnp must be in sync. 1769 */ 1770 if (task_no_new_privs(current)) 1771 task_set_no_new_privs(p); 1772 1773 /* 1774 * If the parent gained a seccomp mode after copying thread 1775 * flags and between before we held the sighand lock, we have 1776 * to manually enable the seccomp thread flag here. 1777 */ 1778 if (p->seccomp.mode != SECCOMP_MODE_DISABLED) 1779 set_task_syscall_work(p, SECCOMP); 1780 #endif 1781 } 1782 1783 SYSCALL_DEFINE1(set_tid_address, int __user *, tidptr) 1784 { 1785 current->clear_child_tid = tidptr; 1786 1787 return task_pid_vnr(current); 1788 } 1789 1790 static void rt_mutex_init_task(struct task_struct *p) 1791 { 1792 raw_spin_lock_init(&p->pi_lock); 1793 #ifdef CONFIG_RT_MUTEXES 1794 p->pi_waiters = RB_ROOT_CACHED; 1795 p->pi_top_task = NULL; 1796 p->pi_blocked_on = NULL; 1797 #endif 1798 } 1799 1800 static inline void init_task_pid_links(struct task_struct *task) 1801 { 1802 enum pid_type type; 1803 1804 for (type = PIDTYPE_PID; type < PIDTYPE_MAX; ++type) 1805 INIT_HLIST_NODE(&task->pid_links[type]); 1806 } 1807 1808 static inline void 1809 init_task_pid(struct task_struct *task, enum pid_type type, struct pid *pid) 1810 { 1811 if (type == PIDTYPE_PID) 1812 task->thread_pid = pid; 1813 else 1814 task->signal->pids[type] = pid; 1815 } 1816 1817 static inline void rcu_copy_process(struct task_struct *p) 1818 { 1819 #ifdef CONFIG_PREEMPT_RCU 1820 p->rcu_read_lock_nesting = 0; 1821 p->rcu_read_unlock_special.s = 0; 1822 p->rcu_blocked_node = NULL; 1823 INIT_LIST_HEAD(&p->rcu_node_entry); 1824 #endif /* #ifdef CONFIG_PREEMPT_RCU */ 1825 #ifdef CONFIG_TASKS_RCU 1826 p->rcu_tasks_holdout = false; 1827 INIT_LIST_HEAD(&p->rcu_tasks_holdout_list); 1828 p->rcu_tasks_idle_cpu = -1; 1829 INIT_LIST_HEAD(&p->rcu_tasks_exit_list); 1830 #endif /* #ifdef CONFIG_TASKS_RCU */ 1831 #ifdef CONFIG_TASKS_TRACE_RCU 1832 p->trc_reader_nesting = 0; 1833 #endif /* #ifdef CONFIG_TASKS_TRACE_RCU */ 1834 } 1835 1836 /** 1837 * pidfd_prepare - allocate a new pidfd_file and reserve a pidfd 1838 * @pid: the struct pid for which to create a pidfd 1839 * @flags: flags of the new @pidfd 1840 * @ret_file: return the new pidfs file 1841 * 1842 * Allocate a new file that stashes @pid and reserve a new pidfd number in the 1843 * caller's file descriptor table. The pidfd is reserved but not installed yet. 1844 * 1845 * The helper verifies that @pid is still in use, without PIDFD_THREAD the 1846 * task identified by @pid must be a thread-group leader. 1847 * 1848 * If this function returns successfully the caller is responsible to either 1849 * call fd_install() passing the returned pidfd and pidfd file as arguments in 1850 * order to install the pidfd into its file descriptor table or they must use 1851 * put_unused_fd() and fput() on the returned pidfd and pidfd file 1852 * respectively. 1853 * 1854 * This function is useful when a pidfd must already be reserved but there 1855 * might still be points of failure afterwards and the caller wants to ensure 1856 * that no pidfd is leaked into its file descriptor table. 1857 * 1858 * Return: On success, a reserved pidfd is returned from the function and a new 1859 * pidfd file is returned in the last argument to the function. On 1860 * error, a negative error code is returned from the function and the 1861 * last argument remains unchanged. 1862 */ 1863 int pidfd_prepare(struct pid *pid, unsigned int flags, struct file **ret_file) 1864 { 1865 struct file *pidfs_file; 1866 1867 /* 1868 * PIDFD_STALE is only allowed to be passed if the caller knows 1869 * that @pid is already registered in pidfs and thus 1870 * PIDFD_INFO_EXIT information is guaranteed to be available. 1871 */ 1872 if (!(flags & PIDFD_STALE)) { 1873 /* 1874 * While holding the pidfd waitqueue lock removing the 1875 * task linkage for the thread-group leader pid 1876 * (PIDTYPE_TGID) isn't possible. Thus, if there's still 1877 * task linkage for PIDTYPE_PID not having thread-group 1878 * leader linkage for the pid means it wasn't a 1879 * thread-group leader in the first place. 1880 */ 1881 guard(spinlock_irq)(&pid->wait_pidfd.lock); 1882 1883 /* Task has already been reaped. */ 1884 if (!pid_has_task(pid, PIDTYPE_PID)) 1885 return -ESRCH; 1886 /* 1887 * If this struct pid isn't used as a thread-group 1888 * leader but the caller requested to create a 1889 * thread-group leader pidfd then report ENOENT. 1890 */ 1891 if (!(flags & PIDFD_THREAD) && !pid_has_task(pid, PIDTYPE_TGID)) 1892 return -ENOENT; 1893 } 1894 1895 CLASS(get_unused_fd, pidfd)(O_CLOEXEC); 1896 if (pidfd < 0) 1897 return pidfd; 1898 1899 pidfs_file = pidfs_alloc_file(pid, flags | O_RDWR); 1900 if (IS_ERR(pidfs_file)) 1901 return PTR_ERR(pidfs_file); 1902 1903 *ret_file = pidfs_file; 1904 return take_fd(pidfd); 1905 } 1906 1907 static void __delayed_free_task(struct rcu_head *rhp) 1908 { 1909 struct task_struct *tsk = container_of(rhp, struct task_struct, rcu); 1910 1911 free_task(tsk); 1912 } 1913 1914 static __always_inline void delayed_free_task(struct task_struct *tsk) 1915 { 1916 if (IS_ENABLED(CONFIG_MEMCG)) 1917 call_rcu(&tsk->rcu, __delayed_free_task); 1918 else 1919 free_task(tsk); 1920 } 1921 1922 static void copy_oom_score_adj(u64 clone_flags, struct task_struct *tsk) 1923 { 1924 /* Skip if kernel thread */ 1925 if (!tsk->mm) 1926 return; 1927 1928 /* Skip if spawning a thread or using vfork */ 1929 if ((clone_flags & (CLONE_VM | CLONE_THREAD | CLONE_VFORK)) != CLONE_VM) 1930 return; 1931 1932 /* We need to synchronize with __set_oom_adj */ 1933 mutex_lock(&oom_adj_mutex); 1934 mm_flags_set(MMF_MULTIPROCESS, tsk->mm); 1935 /* Update the values in case they were changed after copy_signal */ 1936 tsk->signal->oom_score_adj = current->signal->oom_score_adj; 1937 tsk->signal->oom_score_adj_min = current->signal->oom_score_adj_min; 1938 mutex_unlock(&oom_adj_mutex); 1939 } 1940 1941 #ifdef CONFIG_RV 1942 static void rv_task_fork(struct task_struct *p) 1943 { 1944 memset(&p->rv, 0, sizeof(p->rv)); 1945 } 1946 #else 1947 #define rv_task_fork(p) do {} while (0) 1948 #endif 1949 1950 static bool need_futex_hash_allocate_default(u64 clone_flags) 1951 { 1952 if ((clone_flags & (CLONE_THREAD | CLONE_VM)) != (CLONE_THREAD | CLONE_VM)) 1953 return false; 1954 return true; 1955 } 1956 1957 /* 1958 * This creates a new process as a copy of the old one, 1959 * but does not actually start it yet. 1960 * 1961 * It copies the registers, and all the appropriate 1962 * parts of the process environment (as per the clone 1963 * flags). The actual kick-off is left to the caller. 1964 */ 1965 __latent_entropy struct task_struct *copy_process( 1966 struct pid *pid, 1967 int trace, 1968 int node, 1969 struct kernel_clone_args *args) 1970 { 1971 int pidfd = -1, retval; 1972 struct task_struct *p; 1973 struct multiprocess_signals delayed; 1974 struct file *pidfile = NULL; 1975 const u64 clone_flags = args->flags; 1976 struct nsproxy *nsp = current->nsproxy; 1977 1978 /* 1979 * Don't allow sharing the root directory with processes in a different 1980 * namespace 1981 */ 1982 if ((clone_flags & (CLONE_NEWNS|CLONE_FS)) == (CLONE_NEWNS|CLONE_FS)) 1983 return ERR_PTR(-EINVAL); 1984 1985 if ((clone_flags & (CLONE_NEWUSER|CLONE_FS)) == (CLONE_NEWUSER|CLONE_FS)) 1986 return ERR_PTR(-EINVAL); 1987 1988 /* 1989 * Thread groups must share signals as well, and detached threads 1990 * can only be started up within the thread group. 1991 */ 1992 if ((clone_flags & CLONE_THREAD) && !(clone_flags & CLONE_SIGHAND)) 1993 return ERR_PTR(-EINVAL); 1994 1995 /* 1996 * Shared signal handlers imply shared VM. By way of the above, 1997 * thread groups also imply shared VM. Blocking this case allows 1998 * for various simplifications in other code. 1999 */ 2000 if ((clone_flags & CLONE_SIGHAND) && !(clone_flags & CLONE_VM)) 2001 return ERR_PTR(-EINVAL); 2002 2003 /* 2004 * Siblings of global init remain as zombies on exit since they are 2005 * not reaped by their parent (swapper). To solve this and to avoid 2006 * multi-rooted process trees, prevent global and container-inits 2007 * from creating siblings. 2008 */ 2009 if ((clone_flags & CLONE_PARENT) && 2010 current->signal->flags & SIGNAL_UNKILLABLE) 2011 return ERR_PTR(-EINVAL); 2012 2013 /* 2014 * If the new process will be in a different pid or user namespace 2015 * do not allow it to share a thread group with the forking task. 2016 */ 2017 if (clone_flags & CLONE_THREAD) { 2018 if ((clone_flags & (CLONE_NEWUSER | CLONE_NEWPID)) || 2019 (task_active_pid_ns(current) != nsp->pid_ns_for_children)) 2020 return ERR_PTR(-EINVAL); 2021 } 2022 2023 if (clone_flags & CLONE_PIDFD) { 2024 /* 2025 * - CLONE_DETACHED is blocked so that we can potentially 2026 * reuse it later for CLONE_PIDFD. 2027 */ 2028 if (clone_flags & CLONE_DETACHED) 2029 return ERR_PTR(-EINVAL); 2030 } 2031 2032 /* 2033 * Force any signals received before this point to be delivered 2034 * before the fork happens. Collect up signals sent to multiple 2035 * processes that happen during the fork and delay them so that 2036 * they appear to happen after the fork. 2037 */ 2038 sigemptyset(&delayed.signal); 2039 INIT_HLIST_NODE(&delayed.node); 2040 2041 spin_lock_irq(¤t->sighand->siglock); 2042 if (!(clone_flags & CLONE_THREAD)) 2043 hlist_add_head(&delayed.node, ¤t->signal->multiprocess); 2044 recalc_sigpending(); 2045 spin_unlock_irq(¤t->sighand->siglock); 2046 retval = -ERESTARTNOINTR; 2047 if (task_sigpending(current)) 2048 goto fork_out; 2049 2050 retval = -ENOMEM; 2051 p = dup_task_struct(current, node); 2052 if (!p) 2053 goto fork_out; 2054 p->flags &= ~PF_KTHREAD; 2055 if (args->kthread) 2056 p->flags |= PF_KTHREAD; 2057 if (args->user_worker) { 2058 /* 2059 * Mark us a user worker, and block any signal that isn't 2060 * fatal or STOP 2061 */ 2062 p->flags |= PF_USER_WORKER; 2063 siginitsetinv(&p->blocked, sigmask(SIGKILL)|sigmask(SIGSTOP)); 2064 } 2065 if (args->io_thread) 2066 p->flags |= PF_IO_WORKER; 2067 2068 if (args->name) 2069 strscpy_pad(p->comm, args->name, sizeof(p->comm)); 2070 2071 p->set_child_tid = (clone_flags & CLONE_CHILD_SETTID) ? args->child_tid : NULL; 2072 /* 2073 * TID is cleared in mm_release() when the task exits 2074 */ 2075 p->clear_child_tid = (clone_flags & CLONE_CHILD_CLEARTID) ? args->child_tid : NULL; 2076 2077 ftrace_graph_init_task(p); 2078 2079 rt_mutex_init_task(p); 2080 2081 lockdep_assert_irqs_enabled(); 2082 #ifdef CONFIG_PROVE_LOCKING 2083 DEBUG_LOCKS_WARN_ON(!p->softirqs_enabled); 2084 #endif 2085 retval = copy_creds(p, clone_flags); 2086 if (retval < 0) 2087 goto bad_fork_free; 2088 2089 retval = -EAGAIN; 2090 if (is_rlimit_overlimit(task_ucounts(p), UCOUNT_RLIMIT_NPROC, rlimit(RLIMIT_NPROC))) { 2091 if (p->real_cred->user != INIT_USER && 2092 !capable(CAP_SYS_RESOURCE) && !capable(CAP_SYS_ADMIN)) 2093 goto bad_fork_cleanup_count; 2094 } 2095 current->flags &= ~PF_NPROC_EXCEEDED; 2096 2097 /* 2098 * If multiple threads are within copy_process(), then this check 2099 * triggers too late. This doesn't hurt, the check is only there 2100 * to stop root fork bombs. 2101 */ 2102 retval = -EAGAIN; 2103 if (data_race(nr_threads >= max_threads)) 2104 goto bad_fork_cleanup_count; 2105 2106 delayacct_tsk_init(p); /* Must remain after dup_task_struct() */ 2107 p->flags &= ~(PF_SUPERPRIV | PF_WQ_WORKER | PF_IDLE | PF_NO_SETAFFINITY); 2108 p->flags |= PF_FORKNOEXEC; 2109 INIT_LIST_HEAD(&p->children); 2110 INIT_LIST_HEAD(&p->sibling); 2111 rcu_copy_process(p); 2112 p->vfork_done = NULL; 2113 spin_lock_init(&p->alloc_lock); 2114 2115 init_sigpending(&p->pending); 2116 2117 p->utime = p->stime = p->gtime = 0; 2118 #ifdef CONFIG_ARCH_HAS_SCALED_CPUTIME 2119 p->utimescaled = p->stimescaled = 0; 2120 #endif 2121 prev_cputime_init(&p->prev_cputime); 2122 2123 #ifdef CONFIG_VIRT_CPU_ACCOUNTING_GEN 2124 seqcount_init(&p->vtime.seqcount); 2125 p->vtime.starttime = 0; 2126 p->vtime.state = VTIME_INACTIVE; 2127 #endif 2128 2129 #ifdef CONFIG_IO_URING 2130 p->io_uring = NULL; 2131 retval = io_uring_fork(p); 2132 if (unlikely(retval)) 2133 goto bad_fork_cleanup_delayacct; 2134 retval = -EAGAIN; 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 /* 2397 * If zap_pid_ns_processes() was called after alloc_pid(), the new 2398 * child missed SIGKILL. If current is not in the same namespace, 2399 * we can't rely on fatal_signal_pending() below. 2400 */ 2401 if (unlikely(!(ns_of_pid(pid)->pid_allocated & PIDNS_ADDING))) { 2402 retval = -ENOMEM; 2403 goto bad_fork_core_free; 2404 } 2405 2406 /* Let kill terminate clone/fork in the middle */ 2407 if (fatal_signal_pending(current)) { 2408 retval = -EINTR; 2409 goto bad_fork_core_free; 2410 } 2411 2412 /* No more failure paths after this point. */ 2413 2414 /* 2415 * Copy seccomp details explicitly here, in case they were changed 2416 * before holding sighand lock. 2417 */ 2418 copy_seccomp(p); 2419 2420 init_task_pid_links(p); 2421 if (likely(p->pid)) { 2422 ptrace_init_task(p, (clone_flags & CLONE_PTRACE) || trace); 2423 2424 init_task_pid(p, PIDTYPE_PID, pid); 2425 if (thread_group_leader(p)) { 2426 init_task_pid(p, PIDTYPE_TGID, pid); 2427 init_task_pid(p, PIDTYPE_PGID, task_pgrp(current)); 2428 init_task_pid(p, PIDTYPE_SID, task_session(current)); 2429 2430 if (is_child_reaper(pid)) { 2431 ns_of_pid(pid)->child_reaper = p; 2432 p->signal->flags |= SIGNAL_UNKILLABLE; 2433 } 2434 p->signal->shared_pending.signal = delayed.signal; 2435 p->signal->tty = tty_kref_get(current->signal->tty); 2436 /* 2437 * Inherit has_child_subreaper flag under the same 2438 * tasklist_lock with adding child to the process tree 2439 * for propagate_has_child_subreaper optimization. 2440 */ 2441 p->signal->has_child_subreaper = p->real_parent->signal->has_child_subreaper || 2442 p->real_parent->signal->is_child_subreaper; 2443 list_add_tail(&p->sibling, &p->real_parent->children); 2444 list_add_tail_rcu(&p->tasks, &init_task.tasks); 2445 attach_pid(p, PIDTYPE_TGID); 2446 attach_pid(p, PIDTYPE_PGID); 2447 attach_pid(p, PIDTYPE_SID); 2448 __this_cpu_inc(process_counts); 2449 } else { 2450 current->signal->nr_threads++; 2451 current->signal->quick_threads++; 2452 atomic_inc(¤t->signal->live); 2453 refcount_inc(¤t->signal->sigcnt); 2454 task_join_group_stop(p); 2455 list_add_tail_rcu(&p->thread_node, 2456 &p->signal->thread_head); 2457 } 2458 attach_pid(p, PIDTYPE_PID); 2459 nr_threads++; 2460 } 2461 total_forks++; 2462 hlist_del_init(&delayed.node); 2463 spin_unlock(¤t->sighand->siglock); 2464 syscall_tracepoint_update(p); 2465 write_unlock_irq(&tasklist_lock); 2466 2467 if (pidfile) 2468 fd_install(pidfd, pidfile); 2469 2470 proc_fork_connector(p); 2471 sched_post_fork(p); 2472 cgroup_post_fork(p, args); 2473 perf_event_fork(p); 2474 2475 trace_task_newtask(p, clone_flags); 2476 uprobe_copy_process(p, clone_flags); 2477 user_events_fork(p, clone_flags); 2478 2479 copy_oom_score_adj(clone_flags, p); 2480 2481 return p; 2482 2483 bad_fork_core_free: 2484 sched_core_free(p); 2485 spin_unlock(¤t->sighand->siglock); 2486 write_unlock_irq(&tasklist_lock); 2487 bad_fork_cancel_cgroup: 2488 cgroup_cancel_fork(p, args); 2489 bad_fork_put_pidfd: 2490 if (clone_flags & CLONE_PIDFD) { 2491 fput(pidfile); 2492 put_unused_fd(pidfd); 2493 } 2494 bad_fork_free_pid: 2495 if (pid != &init_struct_pid) 2496 free_pid(pid); 2497 bad_fork_cleanup_thread: 2498 exit_thread(p); 2499 bad_fork_cleanup_io: 2500 if (p->io_context) 2501 exit_io_context(p); 2502 bad_fork_cleanup_namespaces: 2503 exit_nsproxy_namespaces(p); 2504 bad_fork_cleanup_mm: 2505 if (p->mm) { 2506 mm_clear_owner(p->mm, p); 2507 mmput(p->mm); 2508 } 2509 bad_fork_cleanup_signal: 2510 if (!(clone_flags & CLONE_THREAD)) 2511 free_signal_struct(p->signal); 2512 bad_fork_cleanup_sighand: 2513 __cleanup_sighand(p->sighand); 2514 bad_fork_cleanup_fs: 2515 exit_fs(p); /* blocking */ 2516 bad_fork_cleanup_files: 2517 exit_files(p); /* blocking */ 2518 bad_fork_cleanup_semundo: 2519 exit_sem(p); 2520 bad_fork_cleanup_security: 2521 security_task_free(p); 2522 bad_fork_cleanup_audit: 2523 audit_free(p); 2524 bad_fork_cleanup_perf: 2525 perf_event_free_task(p); 2526 bad_fork_sched_cancel_fork: 2527 sched_cancel_fork(p); 2528 bad_fork_cleanup_policy: 2529 lockdep_free_task(p); 2530 #ifdef CONFIG_NUMA 2531 mpol_put(p->mempolicy); 2532 #endif 2533 bad_fork_cleanup_delayacct: 2534 io_uring_free(p); 2535 delayacct_tsk_free(p); 2536 bad_fork_cleanup_count: 2537 dec_rlimit_ucounts(task_ucounts(p), UCOUNT_RLIMIT_NPROC, 1); 2538 exit_cred_namespaces(p); 2539 exit_creds(p); 2540 bad_fork_free: 2541 WRITE_ONCE(p->__state, TASK_DEAD); 2542 exit_task_stack_account(p); 2543 put_task_stack(p); 2544 delayed_free_task(p); 2545 fork_out: 2546 spin_lock_irq(¤t->sighand->siglock); 2547 hlist_del_init(&delayed.node); 2548 spin_unlock_irq(¤t->sighand->siglock); 2549 return ERR_PTR(retval); 2550 } 2551 2552 static inline void init_idle_pids(struct task_struct *idle) 2553 { 2554 enum pid_type type; 2555 2556 for (type = PIDTYPE_PID; type < PIDTYPE_MAX; ++type) { 2557 INIT_HLIST_NODE(&idle->pid_links[type]); /* not really needed */ 2558 init_task_pid(idle, type, &init_struct_pid); 2559 } 2560 } 2561 2562 static int idle_dummy(void *dummy) 2563 { 2564 /* This function is never called */ 2565 return 0; 2566 } 2567 2568 struct task_struct * __init fork_idle(int cpu) 2569 { 2570 struct task_struct *task; 2571 struct kernel_clone_args args = { 2572 .flags = CLONE_VM, 2573 .fn = &idle_dummy, 2574 .fn_arg = NULL, 2575 .kthread = 1, 2576 .idle = 1, 2577 }; 2578 2579 task = copy_process(&init_struct_pid, 0, cpu_to_node(cpu), &args); 2580 if (!IS_ERR(task)) { 2581 init_idle_pids(task); 2582 init_idle(task, cpu); 2583 } 2584 2585 return task; 2586 } 2587 2588 /* 2589 * This is like kernel_clone(), but shaved down and tailored to just 2590 * creating io_uring workers. It returns a created task, or an error pointer. 2591 * The returned task is inactive, and the caller must fire it up through 2592 * wake_up_new_task(p). All signals are blocked in the created task. 2593 */ 2594 struct task_struct *create_io_thread(int (*fn)(void *), void *arg, int node) 2595 { 2596 unsigned long flags = CLONE_FS|CLONE_FILES|CLONE_SIGHAND|CLONE_THREAD| 2597 CLONE_IO|CLONE_VM|CLONE_UNTRACED; 2598 struct kernel_clone_args args = { 2599 .flags = flags, 2600 .fn = fn, 2601 .fn_arg = arg, 2602 .io_thread = 1, 2603 .user_worker = 1, 2604 }; 2605 2606 return copy_process(NULL, 0, node, &args); 2607 } 2608 2609 /* 2610 * Ok, this is the main fork-routine. 2611 * 2612 * It copies the process, and if successful kick-starts 2613 * it and waits for it to finish using the VM if required. 2614 * 2615 * args->exit_signal is expected to be checked for sanity by the caller. 2616 */ 2617 pid_t kernel_clone(struct kernel_clone_args *args) 2618 { 2619 u64 clone_flags = args->flags; 2620 struct completion vfork; 2621 struct pid *pid; 2622 struct task_struct *p; 2623 int trace = 0; 2624 pid_t nr; 2625 2626 /* 2627 * For legacy clone() calls, CLONE_PIDFD uses the parent_tid argument 2628 * to return the pidfd. Hence, CLONE_PIDFD and CLONE_PARENT_SETTID are 2629 * mutually exclusive. With clone3() CLONE_PIDFD has grown a separate 2630 * field in struct clone_args and it still doesn't make sense to have 2631 * them both point at the same memory location. Performing this check 2632 * here has the advantage that we don't need to have a separate helper 2633 * to check for legacy clone(). 2634 */ 2635 if ((clone_flags & CLONE_PIDFD) && 2636 (clone_flags & CLONE_PARENT_SETTID) && 2637 (args->pidfd == args->parent_tid)) 2638 return -EINVAL; 2639 2640 /* 2641 * Determine whether and which event to report to ptracer. When 2642 * called from kernel_thread or CLONE_UNTRACED is explicitly 2643 * requested, no event is reported; otherwise, report if the event 2644 * for the type of forking is enabled. 2645 */ 2646 if (!(clone_flags & CLONE_UNTRACED)) { 2647 if (clone_flags & CLONE_VFORK) 2648 trace = PTRACE_EVENT_VFORK; 2649 else if (args->exit_signal != SIGCHLD) 2650 trace = PTRACE_EVENT_CLONE; 2651 else 2652 trace = PTRACE_EVENT_FORK; 2653 2654 if (likely(!ptrace_event_enabled(current, trace))) 2655 trace = 0; 2656 } 2657 2658 p = copy_process(NULL, trace, NUMA_NO_NODE, args); 2659 add_latent_entropy(); 2660 2661 if (IS_ERR(p)) 2662 return PTR_ERR(p); 2663 2664 /* 2665 * Do this prior waking up the new thread - the thread pointer 2666 * might get invalid after that point, if the thread exits quickly. 2667 */ 2668 trace_sched_process_fork(current, p); 2669 2670 pid = get_task_pid(p, PIDTYPE_PID); 2671 nr = pid_vnr(pid); 2672 2673 if (clone_flags & CLONE_PARENT_SETTID) 2674 put_user(nr, args->parent_tid); 2675 2676 if (clone_flags & CLONE_VFORK) { 2677 p->vfork_done = &vfork; 2678 init_completion(&vfork); 2679 get_task_struct(p); 2680 } 2681 2682 if (IS_ENABLED(CONFIG_LRU_GEN_WALKS_MMU) && !(clone_flags & CLONE_VM)) { 2683 /* lock the task to synchronize with memcg migration */ 2684 task_lock(p); 2685 lru_gen_add_mm(p->mm); 2686 task_unlock(p); 2687 } 2688 2689 wake_up_new_task(p); 2690 2691 /* forking complete and child started to run, tell ptracer */ 2692 if (unlikely(trace)) 2693 ptrace_event_pid(trace, pid); 2694 2695 if (clone_flags & CLONE_VFORK) { 2696 if (!wait_for_vfork_done(p, &vfork)) 2697 ptrace_event_pid(PTRACE_EVENT_VFORK_DONE, pid); 2698 } 2699 2700 put_pid(pid); 2701 return nr; 2702 } 2703 2704 /* 2705 * Create a kernel thread. 2706 */ 2707 pid_t kernel_thread(int (*fn)(void *), void *arg, const char *name, 2708 unsigned long flags) 2709 { 2710 struct kernel_clone_args args = { 2711 .flags = ((flags | CLONE_VM | CLONE_UNTRACED) & ~CSIGNAL), 2712 .exit_signal = (flags & CSIGNAL), 2713 .fn = fn, 2714 .fn_arg = arg, 2715 .name = name, 2716 .kthread = 1, 2717 }; 2718 2719 return kernel_clone(&args); 2720 } 2721 2722 /* 2723 * Create a user mode thread. 2724 */ 2725 pid_t user_mode_thread(int (*fn)(void *), void *arg, unsigned long flags) 2726 { 2727 struct kernel_clone_args args = { 2728 .flags = ((flags | CLONE_VM | CLONE_UNTRACED) & ~CSIGNAL), 2729 .exit_signal = (flags & CSIGNAL), 2730 .fn = fn, 2731 .fn_arg = arg, 2732 }; 2733 2734 return kernel_clone(&args); 2735 } 2736 2737 #ifdef __ARCH_WANT_SYS_FORK 2738 SYSCALL_DEFINE0(fork) 2739 { 2740 #ifdef CONFIG_MMU 2741 struct kernel_clone_args args = { 2742 .exit_signal = SIGCHLD, 2743 }; 2744 2745 return kernel_clone(&args); 2746 #else 2747 /* can not support in nommu mode */ 2748 return -EINVAL; 2749 #endif 2750 } 2751 #endif 2752 2753 #ifdef __ARCH_WANT_SYS_VFORK 2754 SYSCALL_DEFINE0(vfork) 2755 { 2756 struct kernel_clone_args args = { 2757 .flags = CLONE_VFORK | CLONE_VM, 2758 .exit_signal = SIGCHLD, 2759 }; 2760 2761 return kernel_clone(&args); 2762 } 2763 #endif 2764 2765 #ifdef __ARCH_WANT_SYS_CLONE 2766 #ifdef CONFIG_CLONE_BACKWARDS 2767 SYSCALL_DEFINE5(clone, unsigned long, clone_flags, unsigned long, newsp, 2768 int __user *, parent_tidptr, 2769 unsigned long, tls, 2770 int __user *, child_tidptr) 2771 #elif defined(CONFIG_CLONE_BACKWARDS2) 2772 SYSCALL_DEFINE5(clone, unsigned long, newsp, unsigned long, clone_flags, 2773 int __user *, parent_tidptr, 2774 int __user *, child_tidptr, 2775 unsigned long, tls) 2776 #elif defined(CONFIG_CLONE_BACKWARDS3) 2777 SYSCALL_DEFINE6(clone, unsigned long, clone_flags, unsigned long, newsp, 2778 int, stack_size, 2779 int __user *, parent_tidptr, 2780 int __user *, child_tidptr, 2781 unsigned long, tls) 2782 #else 2783 SYSCALL_DEFINE5(clone, unsigned long, clone_flags, unsigned long, newsp, 2784 int __user *, parent_tidptr, 2785 int __user *, child_tidptr, 2786 unsigned long, tls) 2787 #endif 2788 { 2789 struct kernel_clone_args args = { 2790 .flags = (lower_32_bits(clone_flags) & ~CSIGNAL), 2791 .pidfd = parent_tidptr, 2792 .child_tid = child_tidptr, 2793 .parent_tid = parent_tidptr, 2794 .exit_signal = (lower_32_bits(clone_flags) & CSIGNAL), 2795 .stack = newsp, 2796 .tls = tls, 2797 }; 2798 2799 return kernel_clone(&args); 2800 } 2801 #endif 2802 2803 static noinline int copy_clone_args_from_user(struct kernel_clone_args *kargs, 2804 struct clone_args __user *uargs, 2805 size_t usize) 2806 { 2807 int err; 2808 struct clone_args args; 2809 pid_t *kset_tid = kargs->set_tid; 2810 2811 BUILD_BUG_ON(offsetofend(struct clone_args, tls) != 2812 CLONE_ARGS_SIZE_VER0); 2813 BUILD_BUG_ON(offsetofend(struct clone_args, set_tid_size) != 2814 CLONE_ARGS_SIZE_VER1); 2815 BUILD_BUG_ON(offsetofend(struct clone_args, cgroup) != 2816 CLONE_ARGS_SIZE_VER2); 2817 BUILD_BUG_ON(sizeof(struct clone_args) != CLONE_ARGS_SIZE_VER2); 2818 2819 if (unlikely(usize > PAGE_SIZE)) 2820 return -E2BIG; 2821 if (unlikely(usize < CLONE_ARGS_SIZE_VER0)) 2822 return -EINVAL; 2823 2824 err = copy_struct_from_user(&args, sizeof(args), uargs, usize); 2825 if (err) 2826 return err; 2827 2828 if (unlikely(args.set_tid_size > MAX_PID_NS_LEVEL)) 2829 return -EINVAL; 2830 2831 if (unlikely(!args.set_tid && args.set_tid_size > 0)) 2832 return -EINVAL; 2833 2834 if (unlikely(args.set_tid && args.set_tid_size == 0)) 2835 return -EINVAL; 2836 2837 /* 2838 * Verify that higher 32bits of exit_signal are unset and that 2839 * it is a valid signal 2840 */ 2841 if (unlikely((args.exit_signal & ~((u64)CSIGNAL)) || 2842 !valid_signal(args.exit_signal))) 2843 return -EINVAL; 2844 2845 if ((args.flags & CLONE_INTO_CGROUP) && 2846 (args.cgroup > INT_MAX || usize < CLONE_ARGS_SIZE_VER2)) 2847 return -EINVAL; 2848 2849 *kargs = (struct kernel_clone_args){ 2850 .flags = args.flags, 2851 .pidfd = u64_to_user_ptr(args.pidfd), 2852 .child_tid = u64_to_user_ptr(args.child_tid), 2853 .parent_tid = u64_to_user_ptr(args.parent_tid), 2854 .exit_signal = args.exit_signal, 2855 .stack = args.stack, 2856 .stack_size = args.stack_size, 2857 .tls = args.tls, 2858 .set_tid_size = args.set_tid_size, 2859 .cgroup = args.cgroup, 2860 }; 2861 2862 if (args.set_tid && 2863 copy_from_user(kset_tid, u64_to_user_ptr(args.set_tid), 2864 (kargs->set_tid_size * sizeof(pid_t)))) 2865 return -EFAULT; 2866 2867 kargs->set_tid = kset_tid; 2868 2869 return 0; 2870 } 2871 2872 /** 2873 * clone3_stack_valid - check and prepare stack 2874 * @kargs: kernel clone args 2875 * 2876 * Verify that the stack arguments userspace gave us are sane. 2877 * In addition, set the stack direction for userspace since it's easy for us to 2878 * determine. 2879 */ 2880 static inline bool clone3_stack_valid(struct kernel_clone_args *kargs) 2881 { 2882 if (kargs->stack == 0) { 2883 if (kargs->stack_size > 0) 2884 return false; 2885 } else { 2886 if (kargs->stack_size == 0) 2887 return false; 2888 2889 if (!access_ok((void __user *)kargs->stack, kargs->stack_size)) 2890 return false; 2891 2892 #if !defined(CONFIG_STACK_GROWSUP) 2893 kargs->stack += kargs->stack_size; 2894 #endif 2895 } 2896 2897 return true; 2898 } 2899 2900 static bool clone3_args_valid(struct kernel_clone_args *kargs) 2901 { 2902 /* Verify that no unknown flags are passed along. */ 2903 if (kargs->flags & 2904 ~(CLONE_LEGACY_FLAGS | CLONE_CLEAR_SIGHAND | CLONE_INTO_CGROUP)) 2905 return false; 2906 2907 /* 2908 * - make the CLONE_DETACHED bit reusable for clone3 2909 * - make the CSIGNAL bits reusable for clone3 2910 */ 2911 if (kargs->flags & (CLONE_DETACHED | (CSIGNAL & (~CLONE_NEWTIME)))) 2912 return false; 2913 2914 if ((kargs->flags & (CLONE_SIGHAND | CLONE_CLEAR_SIGHAND)) == 2915 (CLONE_SIGHAND | CLONE_CLEAR_SIGHAND)) 2916 return false; 2917 2918 if ((kargs->flags & (CLONE_THREAD | CLONE_PARENT)) && 2919 kargs->exit_signal) 2920 return false; 2921 2922 if (!clone3_stack_valid(kargs)) 2923 return false; 2924 2925 return true; 2926 } 2927 2928 /** 2929 * sys_clone3 - create a new process with specific properties 2930 * @uargs: argument structure 2931 * @size: size of @uargs 2932 * 2933 * clone3() is the extensible successor to clone()/clone2(). 2934 * It takes a struct as argument that is versioned by its size. 2935 * 2936 * Return: On success, a positive PID for the child process. 2937 * On error, a negative errno number. 2938 */ 2939 SYSCALL_DEFINE2(clone3, struct clone_args __user *, uargs, size_t, size) 2940 { 2941 int err; 2942 2943 struct kernel_clone_args kargs; 2944 pid_t set_tid[MAX_PID_NS_LEVEL]; 2945 2946 #ifdef __ARCH_BROKEN_SYS_CLONE3 2947 #warning clone3() entry point is missing, please fix 2948 return -ENOSYS; 2949 #endif 2950 2951 kargs.set_tid = set_tid; 2952 2953 err = copy_clone_args_from_user(&kargs, uargs, size); 2954 if (err) 2955 return err; 2956 2957 if (!clone3_args_valid(&kargs)) 2958 return -EINVAL; 2959 2960 return kernel_clone(&kargs); 2961 } 2962 2963 void walk_process_tree(struct task_struct *top, proc_visitor visitor, void *data) 2964 { 2965 struct task_struct *leader, *parent, *child; 2966 int res; 2967 2968 read_lock(&tasklist_lock); 2969 leader = top = top->group_leader; 2970 down: 2971 for_each_thread(leader, parent) { 2972 list_for_each_entry(child, &parent->children, sibling) { 2973 res = visitor(child, data); 2974 if (res) { 2975 if (res < 0) 2976 goto out; 2977 leader = child; 2978 goto down; 2979 } 2980 up: 2981 ; 2982 } 2983 } 2984 2985 if (leader != top) { 2986 child = leader; 2987 parent = child->real_parent; 2988 leader = parent->group_leader; 2989 goto up; 2990 } 2991 out: 2992 read_unlock(&tasklist_lock); 2993 } 2994 2995 #ifndef ARCH_MIN_MMSTRUCT_ALIGN 2996 #define ARCH_MIN_MMSTRUCT_ALIGN 0 2997 #endif 2998 2999 static void sighand_ctor(void *data) 3000 { 3001 struct sighand_struct *sighand = data; 3002 3003 spin_lock_init(&sighand->siglock); 3004 init_waitqueue_head(&sighand->signalfd_wqh); 3005 } 3006 3007 void __init mm_cache_init(void) 3008 { 3009 unsigned int mm_size; 3010 3011 /* 3012 * The mm_cpumask is located at the end of mm_struct, and is 3013 * dynamically sized based on the maximum CPU number this system 3014 * can have, taking hotplug into account (nr_cpu_ids). 3015 */ 3016 mm_size = sizeof(struct mm_struct) + cpumask_size() + mm_cid_size(); 3017 3018 mm_cachep = kmem_cache_create_usercopy("mm_struct", 3019 mm_size, ARCH_MIN_MMSTRUCT_ALIGN, 3020 SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_ACCOUNT, 3021 offsetof(struct mm_struct, saved_auxv), 3022 sizeof_field(struct mm_struct, saved_auxv), 3023 NULL); 3024 } 3025 3026 void __init proc_caches_init(void) 3027 { 3028 sighand_cachep = kmem_cache_create("sighand_cache", 3029 sizeof(struct sighand_struct), 0, 3030 SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_TYPESAFE_BY_RCU| 3031 SLAB_ACCOUNT, sighand_ctor); 3032 signal_cachep = kmem_cache_create("signal_cache", 3033 sizeof(struct signal_struct), 0, 3034 SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_ACCOUNT, 3035 NULL); 3036 files_cachep = kmem_cache_create("files_cache", 3037 sizeof(struct files_struct), 0, 3038 SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_ACCOUNT, 3039 NULL); 3040 fs_cachep = kmem_cache_create("fs_cache", 3041 sizeof(struct fs_struct), 0, 3042 SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_ACCOUNT, 3043 NULL); 3044 mmap_init(); 3045 nsproxy_cache_init(); 3046 } 3047 3048 /* 3049 * Check constraints on flags passed to the unshare system call. 3050 */ 3051 static int check_unshare_flags(unsigned long unshare_flags) 3052 { 3053 if (unshare_flags & ~(CLONE_THREAD|CLONE_FS|CLONE_NEWNS|CLONE_SIGHAND| 3054 CLONE_VM|CLONE_FILES|CLONE_SYSVSEM| 3055 CLONE_NEWUTS|CLONE_NEWIPC|CLONE_NEWNET| 3056 CLONE_NEWUSER|CLONE_NEWPID|CLONE_NEWCGROUP| 3057 CLONE_NEWTIME)) 3058 return -EINVAL; 3059 /* 3060 * Not implemented, but pretend it works if there is nothing 3061 * to unshare. Note that unsharing the address space or the 3062 * signal handlers also need to unshare the signal queues (aka 3063 * CLONE_THREAD). 3064 */ 3065 if (unshare_flags & (CLONE_THREAD | CLONE_SIGHAND | CLONE_VM)) { 3066 if (!thread_group_empty(current)) 3067 return -EINVAL; 3068 } 3069 if (unshare_flags & (CLONE_SIGHAND | CLONE_VM)) { 3070 if (refcount_read(¤t->sighand->count) > 1) 3071 return -EINVAL; 3072 } 3073 if (unshare_flags & CLONE_VM) { 3074 if (!current_is_single_threaded()) 3075 return -EINVAL; 3076 } 3077 3078 return 0; 3079 } 3080 3081 /* 3082 * Unshare the filesystem structure if it is being shared 3083 */ 3084 static int unshare_fs(unsigned long unshare_flags, struct fs_struct **new_fsp) 3085 { 3086 struct fs_struct *fs = current->fs; 3087 3088 if (!(unshare_flags & CLONE_FS) || !fs) 3089 return 0; 3090 3091 /* don't need lock here; in the worst case we'll do useless copy */ 3092 if (!(unshare_flags & CLONE_NEWNS) && fs->users == 1) 3093 return 0; 3094 3095 *new_fsp = copy_fs_struct(fs); 3096 if (!*new_fsp) 3097 return -ENOMEM; 3098 3099 return 0; 3100 } 3101 3102 /* 3103 * Unshare file descriptor table if it is being shared 3104 */ 3105 static int unshare_fd(unsigned long unshare_flags, struct files_struct **new_fdp) 3106 { 3107 struct files_struct *fd = current->files; 3108 3109 if ((unshare_flags & CLONE_FILES) && 3110 (fd && atomic_read(&fd->count) > 1)) { 3111 fd = dup_fd(fd, NULL); 3112 if (IS_ERR(fd)) 3113 return PTR_ERR(fd); 3114 *new_fdp = fd; 3115 } 3116 3117 return 0; 3118 } 3119 3120 /* 3121 * unshare allows a process to 'unshare' part of the process 3122 * context which was originally shared using clone. copy_* 3123 * functions used by kernel_clone() cannot be used here directly 3124 * because they modify an inactive task_struct that is being 3125 * constructed. Here we are modifying the current, active, 3126 * task_struct. 3127 */ 3128 int ksys_unshare(unsigned long unshare_flags) 3129 { 3130 struct fs_struct *fs, *new_fs = NULL; 3131 struct files_struct *new_fd = NULL; 3132 struct cred *new_cred = NULL; 3133 struct nsproxy *new_nsproxy = NULL; 3134 int do_sysvsem = 0; 3135 int err; 3136 3137 /* 3138 * If unsharing a user namespace must also unshare the thread group 3139 * and unshare the filesystem root and working directories. 3140 */ 3141 if (unshare_flags & CLONE_NEWUSER) 3142 unshare_flags |= CLONE_THREAD | CLONE_FS; 3143 /* 3144 * If unsharing vm, must also unshare signal handlers. 3145 */ 3146 if (unshare_flags & CLONE_VM) 3147 unshare_flags |= CLONE_SIGHAND; 3148 /* 3149 * If unsharing a signal handlers, must also unshare the signal queues. 3150 */ 3151 if (unshare_flags & CLONE_SIGHAND) 3152 unshare_flags |= CLONE_THREAD; 3153 /* 3154 * If unsharing namespace, must also unshare filesystem information. 3155 */ 3156 if (unshare_flags & CLONE_NEWNS) 3157 unshare_flags |= CLONE_FS; 3158 3159 err = check_unshare_flags(unshare_flags); 3160 if (err) 3161 goto bad_unshare_out; 3162 /* 3163 * CLONE_NEWIPC must also detach from the undolist: after switching 3164 * to a new ipc namespace, the semaphore arrays from the old 3165 * namespace are unreachable. 3166 */ 3167 if (unshare_flags & (CLONE_NEWIPC|CLONE_SYSVSEM)) 3168 do_sysvsem = 1; 3169 err = unshare_fs(unshare_flags, &new_fs); 3170 if (err) 3171 goto bad_unshare_out; 3172 err = unshare_fd(unshare_flags, &new_fd); 3173 if (err) 3174 goto bad_unshare_cleanup_fs; 3175 err = unshare_userns(unshare_flags, &new_cred); 3176 if (err) 3177 goto bad_unshare_cleanup_fd; 3178 err = unshare_nsproxy_namespaces(unshare_flags, &new_nsproxy, 3179 new_cred, new_fs); 3180 if (err) 3181 goto bad_unshare_cleanup_cred; 3182 if (new_cred) { 3183 err = set_cred_ucounts(new_cred); 3184 if (err) 3185 goto bad_unshare_cleanup_nsproxy; 3186 } 3187 3188 if (new_fs || new_fd || do_sysvsem || new_cred || new_nsproxy) { 3189 if (do_sysvsem) { 3190 /* 3191 * CLONE_SYSVSEM is equivalent to sys_exit(). 3192 */ 3193 exit_sem(current); 3194 } 3195 if (unshare_flags & CLONE_NEWIPC) { 3196 /* Orphan segments in old ns (see sem above). */ 3197 exit_shm(current); 3198 shm_init_task(current); 3199 } 3200 3201 if (new_nsproxy) { 3202 switch_task_namespaces(current, new_nsproxy); 3203 new_nsproxy = NULL; 3204 } 3205 3206 task_lock(current); 3207 3208 if (new_fs) { 3209 fs = current->fs; 3210 read_seqlock_excl(&fs->seq); 3211 current->fs = new_fs; 3212 if (--fs->users) 3213 new_fs = NULL; 3214 else 3215 new_fs = fs; 3216 read_sequnlock_excl(&fs->seq); 3217 } 3218 3219 if (new_fd) 3220 swap(current->files, new_fd); 3221 3222 task_unlock(current); 3223 3224 if (new_cred) { 3225 /* Install the new user namespace */ 3226 commit_creds(new_cred); 3227 new_cred = NULL; 3228 } 3229 } 3230 3231 perf_event_namespaces(current); 3232 3233 bad_unshare_cleanup_nsproxy: 3234 if (new_nsproxy) 3235 put_nsproxy(new_nsproxy); 3236 bad_unshare_cleanup_cred: 3237 if (new_cred) 3238 put_cred(new_cred); 3239 bad_unshare_cleanup_fd: 3240 if (new_fd) 3241 put_files_struct(new_fd); 3242 bad_unshare_cleanup_fs: 3243 if (new_fs) 3244 free_fs_struct(new_fs); 3245 3246 bad_unshare_out: 3247 return err; 3248 } 3249 3250 SYSCALL_DEFINE1(unshare, unsigned long, unshare_flags) 3251 { 3252 return ksys_unshare(unshare_flags); 3253 } 3254 3255 /* 3256 * Helper to unshare the files of the current task. 3257 * We don't want to expose copy_files internals to 3258 * the exec layer of the kernel. 3259 */ 3260 3261 int unshare_files(void) 3262 { 3263 struct task_struct *task = current; 3264 struct files_struct *old, *copy = NULL; 3265 int error; 3266 3267 error = unshare_fd(CLONE_FILES, ©); 3268 if (error || !copy) 3269 return error; 3270 3271 old = task->files; 3272 task_lock(task); 3273 task->files = copy; 3274 task_unlock(task); 3275 put_files_struct(old); 3276 return 0; 3277 } 3278 3279 static int sysctl_max_threads(const struct ctl_table *table, int write, 3280 void *buffer, size_t *lenp, loff_t *ppos) 3281 { 3282 struct ctl_table t; 3283 int ret; 3284 int threads = max_threads; 3285 int min = 1; 3286 int max = MAX_THREADS; 3287 3288 t = *table; 3289 t.data = &threads; 3290 t.extra1 = &min; 3291 t.extra2 = &max; 3292 3293 ret = proc_dointvec_minmax(&t, write, buffer, lenp, ppos); 3294 if (ret || !write) 3295 return ret; 3296 3297 max_threads = threads; 3298 3299 return 0; 3300 } 3301 3302 static const struct ctl_table fork_sysctl_table[] = { 3303 { 3304 .procname = "threads-max", 3305 .data = NULL, 3306 .maxlen = sizeof(int), 3307 .mode = 0644, 3308 .proc_handler = sysctl_max_threads, 3309 }, 3310 }; 3311 3312 static int __init init_fork_sysctl(void) 3313 { 3314 register_sysctl_init("kernel", fork_sysctl_table); 3315 return 0; 3316 } 3317 3318 subsys_initcall(init_fork_sysctl); 3319