1 // SPDX-License-Identifier: GPL-2.0-only 2 #include <linux/mm.h> 3 #include <linux/slab.h> 4 #include <linux/string.h> 5 #include <linux/compiler.h> 6 #include <linux/export.h> 7 #include <linux/err.h> 8 #include <linux/sched.h> 9 #include <linux/sched/mm.h> 10 #include <linux/sched/signal.h> 11 #include <linux/sched/task_stack.h> 12 #include <linux/security.h> 13 #include <linux/swap.h> 14 #include <linux/swapops.h> 15 #include <linux/mman.h> 16 #include <linux/hugetlb.h> 17 #include <linux/vmalloc.h> 18 #include <linux/userfaultfd_k.h> 19 #include <linux/elf.h> 20 #include <linux/elf-randomize.h> 21 #include <linux/personality.h> 22 #include <linux/random.h> 23 #include <linux/processor.h> 24 #include <linux/sizes.h> 25 #include <linux/compat.h> 26 27 #include <linux/uaccess.h> 28 29 #include <kunit/visibility.h> 30 31 #include "internal.h" 32 #include "swap.h" 33 34 /** 35 * kfree_const - conditionally free memory 36 * @x: pointer to the memory 37 * 38 * Function calls kfree only if @x is not in .rodata section. 39 */ 40 void kfree_const(const void *x) 41 { 42 if (!is_kernel_rodata((unsigned long)x)) 43 kfree(x); 44 } 45 EXPORT_SYMBOL(kfree_const); 46 47 /** 48 * kstrdup - allocate space for and copy an existing string 49 * @s: the string to duplicate 50 * @gfp: the GFP mask used in the kmalloc() call when allocating memory 51 * 52 * Return: newly allocated copy of @s or %NULL in case of error 53 */ 54 noinline 55 char *kstrdup(const char *s, gfp_t gfp) 56 { 57 size_t len; 58 char *buf; 59 60 if (!s) 61 return NULL; 62 63 len = strlen(s) + 1; 64 buf = kmalloc_track_caller(len, gfp); 65 if (buf) 66 memcpy(buf, s, len); 67 return buf; 68 } 69 EXPORT_SYMBOL(kstrdup); 70 71 /** 72 * kstrdup_const - conditionally duplicate an existing const string 73 * @s: the string to duplicate 74 * @gfp: the GFP mask used in the kmalloc() call when allocating memory 75 * 76 * Note: Strings allocated by kstrdup_const should be freed by kfree_const and 77 * must not be passed to krealloc(). 78 * 79 * Return: source string if it is in .rodata section otherwise 80 * fallback to kstrdup. 81 */ 82 const char *kstrdup_const(const char *s, gfp_t gfp) 83 { 84 if (is_kernel_rodata((unsigned long)s)) 85 return s; 86 87 return kstrdup(s, gfp); 88 } 89 EXPORT_SYMBOL(kstrdup_const); 90 91 /** 92 * kstrndup - allocate space for and copy an existing string 93 * @s: the string to duplicate 94 * @max: read at most @max chars from @s 95 * @gfp: the GFP mask used in the kmalloc() call when allocating memory 96 * 97 * Note: Use kmemdup_nul() instead if the size is known exactly. 98 * 99 * Return: newly allocated copy of @s or %NULL in case of error 100 */ 101 char *kstrndup(const char *s, size_t max, gfp_t gfp) 102 { 103 size_t len; 104 char *buf; 105 106 if (!s) 107 return NULL; 108 109 len = strnlen(s, max); 110 buf = kmalloc_track_caller(len+1, gfp); 111 if (buf) { 112 memcpy(buf, s, len); 113 buf[len] = '\0'; 114 } 115 return buf; 116 } 117 EXPORT_SYMBOL(kstrndup); 118 119 /** 120 * kmemdup - duplicate region of memory 121 * 122 * @src: memory region to duplicate 123 * @len: memory region length 124 * @gfp: GFP mask to use 125 * 126 * Return: newly allocated copy of @src or %NULL in case of error, 127 * result is physically contiguous. Use kfree() to free. 128 */ 129 void *kmemdup_noprof(const void *src, size_t len, gfp_t gfp) 130 { 131 void *p; 132 133 p = kmalloc_node_track_caller_noprof(len, gfp, NUMA_NO_NODE, _RET_IP_); 134 if (p) 135 memcpy(p, src, len); 136 return p; 137 } 138 EXPORT_SYMBOL(kmemdup_noprof); 139 140 /** 141 * kmemdup_array - duplicate a given array. 142 * 143 * @src: array to duplicate. 144 * @element_size: size of each element of array. 145 * @count: number of elements to duplicate from array. 146 * @gfp: GFP mask to use. 147 * 148 * Return: duplicated array of @src or %NULL in case of error, 149 * result is physically contiguous. Use kfree() to free. 150 */ 151 void *kmemdup_array(const void *src, size_t element_size, size_t count, gfp_t gfp) 152 { 153 return kmemdup(src, size_mul(element_size, count), gfp); 154 } 155 EXPORT_SYMBOL(kmemdup_array); 156 157 /** 158 * kvmemdup - duplicate region of memory 159 * 160 * @src: memory region to duplicate 161 * @len: memory region length 162 * @gfp: GFP mask to use 163 * 164 * Return: newly allocated copy of @src or %NULL in case of error, 165 * result may be not physically contiguous. Use kvfree() to free. 166 */ 167 void *kvmemdup(const void *src, size_t len, gfp_t gfp) 168 { 169 void *p; 170 171 p = kvmalloc(len, gfp); 172 if (p) 173 memcpy(p, src, len); 174 return p; 175 } 176 EXPORT_SYMBOL(kvmemdup); 177 178 /** 179 * kmemdup_nul - Create a NUL-terminated string from unterminated data 180 * @s: The data to stringify 181 * @len: The size of the data 182 * @gfp: the GFP mask used in the kmalloc() call when allocating memory 183 * 184 * Return: newly allocated copy of @s with NUL-termination or %NULL in 185 * case of error 186 */ 187 char *kmemdup_nul(const char *s, size_t len, gfp_t gfp) 188 { 189 char *buf; 190 191 if (!s) 192 return NULL; 193 194 buf = kmalloc_track_caller(len + 1, gfp); 195 if (buf) { 196 memcpy(buf, s, len); 197 buf[len] = '\0'; 198 } 199 return buf; 200 } 201 EXPORT_SYMBOL(kmemdup_nul); 202 203 /** 204 * memdup_user - duplicate memory region from user space 205 * 206 * @src: source address in user space 207 * @len: number of bytes to copy 208 * 209 * Return: an ERR_PTR() on failure. Result is physically 210 * contiguous, to be freed by kfree(). 211 */ 212 void *memdup_user(const void __user *src, size_t len) 213 { 214 void *p; 215 216 p = kmalloc_track_caller(len, GFP_USER | __GFP_NOWARN); 217 if (!p) 218 return ERR_PTR(-ENOMEM); 219 220 if (copy_from_user(p, src, len)) { 221 kfree(p); 222 return ERR_PTR(-EFAULT); 223 } 224 225 return p; 226 } 227 EXPORT_SYMBOL(memdup_user); 228 229 /** 230 * vmemdup_user - duplicate memory region from user space 231 * 232 * @src: source address in user space 233 * @len: number of bytes to copy 234 * 235 * Return: an ERR_PTR() on failure. Result may be not 236 * physically contiguous. Use kvfree() to free. 237 */ 238 void *vmemdup_user(const void __user *src, size_t len) 239 { 240 void *p; 241 242 p = kvmalloc(len, GFP_USER); 243 if (!p) 244 return ERR_PTR(-ENOMEM); 245 246 if (copy_from_user(p, src, len)) { 247 kvfree(p); 248 return ERR_PTR(-EFAULT); 249 } 250 251 return p; 252 } 253 EXPORT_SYMBOL(vmemdup_user); 254 255 /** 256 * strndup_user - duplicate an existing string from user space 257 * @s: The string to duplicate 258 * @n: Maximum number of bytes to copy, including the trailing NUL. 259 * 260 * Return: newly allocated copy of @s or an ERR_PTR() in case of error 261 */ 262 char *strndup_user(const char __user *s, long n) 263 { 264 char *p; 265 long length; 266 267 length = strnlen_user(s, n); 268 269 if (!length) 270 return ERR_PTR(-EFAULT); 271 272 if (length > n) 273 return ERR_PTR(-EINVAL); 274 275 p = memdup_user(s, length); 276 277 if (IS_ERR(p)) 278 return p; 279 280 p[length - 1] = '\0'; 281 282 return p; 283 } 284 EXPORT_SYMBOL(strndup_user); 285 286 /** 287 * memdup_user_nul - duplicate memory region from user space and NUL-terminate 288 * 289 * @src: source address in user space 290 * @len: number of bytes to copy 291 * 292 * Return: an ERR_PTR() on failure. 293 */ 294 void *memdup_user_nul(const void __user *src, size_t len) 295 { 296 char *p; 297 298 /* 299 * Always use GFP_KERNEL, since copy_from_user() can sleep and 300 * cause pagefault, which makes it pointless to use GFP_NOFS 301 * or GFP_ATOMIC. 302 */ 303 p = kmalloc_track_caller(len + 1, GFP_KERNEL); 304 if (!p) 305 return ERR_PTR(-ENOMEM); 306 307 if (copy_from_user(p, src, len)) { 308 kfree(p); 309 return ERR_PTR(-EFAULT); 310 } 311 p[len] = '\0'; 312 313 return p; 314 } 315 EXPORT_SYMBOL(memdup_user_nul); 316 317 /* Check if the vma is being used as a stack by this task */ 318 int vma_is_stack_for_current(struct vm_area_struct *vma) 319 { 320 struct task_struct * __maybe_unused t = current; 321 322 return (vma->vm_start <= KSTK_ESP(t) && vma->vm_end >= KSTK_ESP(t)); 323 } 324 325 /* 326 * Change backing file, only valid to use during initial VMA setup. 327 */ 328 void vma_set_file(struct vm_area_struct *vma, struct file *file) 329 { 330 /* Changing an anonymous vma with this is illegal */ 331 get_file(file); 332 swap(vma->vm_file, file); 333 fput(file); 334 } 335 EXPORT_SYMBOL(vma_set_file); 336 337 #ifndef STACK_RND_MASK 338 #define STACK_RND_MASK (0x7ff >> (PAGE_SHIFT - 12)) /* 8MB of VA */ 339 #endif 340 341 unsigned long randomize_stack_top(unsigned long stack_top) 342 { 343 unsigned long random_variable = 0; 344 345 if (current->flags & PF_RANDOMIZE) { 346 random_variable = get_random_long(); 347 random_variable &= STACK_RND_MASK; 348 random_variable <<= PAGE_SHIFT; 349 } 350 #ifdef CONFIG_STACK_GROWSUP 351 return PAGE_ALIGN(stack_top) + random_variable; 352 #else 353 return PAGE_ALIGN(stack_top) - random_variable; 354 #endif 355 } 356 357 /** 358 * randomize_page - Generate a random, page aligned address 359 * @start: The smallest acceptable address the caller will take. 360 * @range: The size of the area, starting at @start, within which the 361 * random address must fall. 362 * 363 * If @start + @range would overflow, @range is capped. 364 * 365 * NOTE: Historical use of randomize_range, which this replaces, presumed that 366 * @start was already page aligned. We now align it regardless. 367 * 368 * Return: A page aligned address within [start, start + range). On error, 369 * @start is returned. 370 */ 371 unsigned long randomize_page(unsigned long start, unsigned long range) 372 { 373 if (!PAGE_ALIGNED(start)) { 374 range -= PAGE_ALIGN(start) - start; 375 start = PAGE_ALIGN(start); 376 } 377 378 if (start > ULONG_MAX - range) 379 range = ULONG_MAX - start; 380 381 range >>= PAGE_SHIFT; 382 383 if (range == 0) 384 return start; 385 386 return start + (get_random_long() % range << PAGE_SHIFT); 387 } 388 389 #ifdef CONFIG_ARCH_WANT_DEFAULT_TOPDOWN_MMAP_LAYOUT 390 unsigned long __weak arch_randomize_brk(struct mm_struct *mm) 391 { 392 /* Is the current task 32bit ? */ 393 if (!IS_ENABLED(CONFIG_64BIT) || is_compat_task()) 394 return randomize_page(mm->brk, SZ_32M); 395 396 return randomize_page(mm->brk, SZ_1G); 397 } 398 399 unsigned long arch_mmap_rnd(void) 400 { 401 unsigned long rnd; 402 403 #ifdef CONFIG_HAVE_ARCH_MMAP_RND_COMPAT_BITS 404 if (is_compat_task()) 405 rnd = get_random_long() & ((1UL << mmap_rnd_compat_bits) - 1); 406 else 407 #endif /* CONFIG_HAVE_ARCH_MMAP_RND_COMPAT_BITS */ 408 rnd = get_random_long() & ((1UL << mmap_rnd_bits) - 1); 409 410 return rnd << PAGE_SHIFT; 411 } 412 413 static int mmap_is_legacy(struct rlimit *rlim_stack) 414 { 415 if (current->personality & ADDR_COMPAT_LAYOUT) 416 return 1; 417 418 /* On parisc the stack always grows up - so a unlimited stack should 419 * not be an indicator to use the legacy memory layout. */ 420 if (rlim_stack->rlim_cur == RLIM_INFINITY && 421 !IS_ENABLED(CONFIG_STACK_GROWSUP)) 422 return 1; 423 424 return sysctl_legacy_va_layout; 425 } 426 427 /* 428 * Leave enough space between the mmap area and the stack to honour ulimit in 429 * the face of randomisation. 430 */ 431 #define MIN_GAP (SZ_128M) 432 #define MAX_GAP (STACK_TOP / 6 * 5) 433 434 static unsigned long mmap_base(unsigned long rnd, struct rlimit *rlim_stack) 435 { 436 #ifdef CONFIG_STACK_GROWSUP 437 /* 438 * For an upwards growing stack the calculation is much simpler. 439 * Memory for the maximum stack size is reserved at the top of the 440 * task. mmap_base starts directly below the stack and grows 441 * downwards. 442 */ 443 return PAGE_ALIGN_DOWN(mmap_upper_limit(rlim_stack) - rnd); 444 #else 445 unsigned long gap = rlim_stack->rlim_cur; 446 unsigned long pad = stack_guard_gap; 447 448 /* Account for stack randomization if necessary */ 449 if (current->flags & PF_RANDOMIZE) 450 pad += (STACK_RND_MASK << PAGE_SHIFT); 451 452 /* Values close to RLIM_INFINITY can overflow. */ 453 if (gap + pad > gap) 454 gap += pad; 455 456 if (gap < MIN_GAP) 457 gap = MIN_GAP; 458 else if (gap > MAX_GAP) 459 gap = MAX_GAP; 460 461 return PAGE_ALIGN(STACK_TOP - gap - rnd); 462 #endif 463 } 464 465 void arch_pick_mmap_layout(struct mm_struct *mm, struct rlimit *rlim_stack) 466 { 467 unsigned long random_factor = 0UL; 468 469 if (current->flags & PF_RANDOMIZE) 470 random_factor = arch_mmap_rnd(); 471 472 if (mmap_is_legacy(rlim_stack)) { 473 mm->mmap_base = TASK_UNMAPPED_BASE + random_factor; 474 clear_bit(MMF_TOPDOWN, &mm->flags); 475 } else { 476 mm->mmap_base = mmap_base(random_factor, rlim_stack); 477 set_bit(MMF_TOPDOWN, &mm->flags); 478 } 479 } 480 #elif defined(CONFIG_MMU) && !defined(HAVE_ARCH_PICK_MMAP_LAYOUT) 481 void arch_pick_mmap_layout(struct mm_struct *mm, struct rlimit *rlim_stack) 482 { 483 mm->mmap_base = TASK_UNMAPPED_BASE; 484 clear_bit(MMF_TOPDOWN, &mm->flags); 485 } 486 #endif 487 #ifdef CONFIG_MMU 488 EXPORT_SYMBOL_IF_KUNIT(arch_pick_mmap_layout); 489 #endif 490 491 /** 492 * __account_locked_vm - account locked pages to an mm's locked_vm 493 * @mm: mm to account against 494 * @pages: number of pages to account 495 * @inc: %true if @pages should be considered positive, %false if not 496 * @task: task used to check RLIMIT_MEMLOCK 497 * @bypass_rlim: %true if checking RLIMIT_MEMLOCK should be skipped 498 * 499 * Assumes @task and @mm are valid (i.e. at least one reference on each), and 500 * that mmap_lock is held as writer. 501 * 502 * Return: 503 * * 0 on success 504 * * -ENOMEM if RLIMIT_MEMLOCK would be exceeded. 505 */ 506 int __account_locked_vm(struct mm_struct *mm, unsigned long pages, bool inc, 507 struct task_struct *task, bool bypass_rlim) 508 { 509 unsigned long locked_vm, limit; 510 int ret = 0; 511 512 mmap_assert_write_locked(mm); 513 514 locked_vm = mm->locked_vm; 515 if (inc) { 516 if (!bypass_rlim) { 517 limit = task_rlimit(task, RLIMIT_MEMLOCK) >> PAGE_SHIFT; 518 if (locked_vm + pages > limit) 519 ret = -ENOMEM; 520 } 521 if (!ret) 522 mm->locked_vm = locked_vm + pages; 523 } else { 524 WARN_ON_ONCE(pages > locked_vm); 525 mm->locked_vm = locked_vm - pages; 526 } 527 528 pr_debug("%s: [%d] caller %ps %c%lu %lu/%lu%s\n", __func__, task->pid, 529 (void *)_RET_IP_, (inc) ? '+' : '-', pages << PAGE_SHIFT, 530 locked_vm << PAGE_SHIFT, task_rlimit(task, RLIMIT_MEMLOCK), 531 ret ? " - exceeded" : ""); 532 533 return ret; 534 } 535 EXPORT_SYMBOL_GPL(__account_locked_vm); 536 537 /** 538 * account_locked_vm - account locked pages to an mm's locked_vm 539 * @mm: mm to account against, may be NULL 540 * @pages: number of pages to account 541 * @inc: %true if @pages should be considered positive, %false if not 542 * 543 * Assumes a non-NULL @mm is valid (i.e. at least one reference on it). 544 * 545 * Return: 546 * * 0 on success, or if mm is NULL 547 * * -ENOMEM if RLIMIT_MEMLOCK would be exceeded. 548 */ 549 int account_locked_vm(struct mm_struct *mm, unsigned long pages, bool inc) 550 { 551 int ret; 552 553 if (pages == 0 || !mm) 554 return 0; 555 556 mmap_write_lock(mm); 557 ret = __account_locked_vm(mm, pages, inc, current, 558 capable(CAP_IPC_LOCK)); 559 mmap_write_unlock(mm); 560 561 return ret; 562 } 563 EXPORT_SYMBOL_GPL(account_locked_vm); 564 565 unsigned long vm_mmap_pgoff(struct file *file, unsigned long addr, 566 unsigned long len, unsigned long prot, 567 unsigned long flag, unsigned long pgoff) 568 { 569 unsigned long ret; 570 struct mm_struct *mm = current->mm; 571 unsigned long populate; 572 LIST_HEAD(uf); 573 574 ret = security_mmap_file(file, prot, flag); 575 if (!ret) { 576 if (mmap_write_lock_killable(mm)) 577 return -EINTR; 578 ret = do_mmap(file, addr, len, prot, flag, 0, pgoff, &populate, 579 &uf); 580 mmap_write_unlock(mm); 581 userfaultfd_unmap_complete(mm, &uf); 582 if (populate) 583 mm_populate(ret, populate); 584 } 585 return ret; 586 } 587 588 unsigned long vm_mmap(struct file *file, unsigned long addr, 589 unsigned long len, unsigned long prot, 590 unsigned long flag, unsigned long offset) 591 { 592 if (unlikely(offset + PAGE_ALIGN(len) < offset)) 593 return -EINVAL; 594 if (unlikely(offset_in_page(offset))) 595 return -EINVAL; 596 597 return vm_mmap_pgoff(file, addr, len, prot, flag, offset >> PAGE_SHIFT); 598 } 599 EXPORT_SYMBOL(vm_mmap); 600 601 /** 602 * kvmalloc_node - attempt to allocate physically contiguous memory, but upon 603 * failure, fall back to non-contiguous (vmalloc) allocation. 604 * @size: size of the request. 605 * @flags: gfp mask for the allocation - must be compatible (superset) with GFP_KERNEL. 606 * @node: numa node to allocate from 607 * 608 * Uses kmalloc to get the memory but if the allocation fails then falls back 609 * to the vmalloc allocator. Use kvfree for freeing the memory. 610 * 611 * GFP_NOWAIT and GFP_ATOMIC are not supported, neither is the __GFP_NORETRY modifier. 612 * __GFP_RETRY_MAYFAIL is supported, and it should be used only if kmalloc is 613 * preferable to the vmalloc fallback, due to visible performance drawbacks. 614 * 615 * Return: pointer to the allocated memory of %NULL in case of failure 616 */ 617 void *kvmalloc_node_noprof(size_t size, gfp_t flags, int node) 618 { 619 gfp_t kmalloc_flags = flags; 620 void *ret; 621 622 /* 623 * We want to attempt a large physically contiguous block first because 624 * it is less likely to fragment multiple larger blocks and therefore 625 * contribute to a long term fragmentation less than vmalloc fallback. 626 * However make sure that larger requests are not too disruptive - no 627 * OOM killer and no allocation failure warnings as we have a fallback. 628 */ 629 if (size > PAGE_SIZE) { 630 kmalloc_flags |= __GFP_NOWARN; 631 632 if (!(kmalloc_flags & __GFP_RETRY_MAYFAIL)) 633 kmalloc_flags |= __GFP_NORETRY; 634 635 /* nofail semantic is implemented by the vmalloc fallback */ 636 kmalloc_flags &= ~__GFP_NOFAIL; 637 } 638 639 ret = kmalloc_node_noprof(size, kmalloc_flags, node); 640 641 /* 642 * It doesn't really make sense to fallback to vmalloc for sub page 643 * requests 644 */ 645 if (ret || size <= PAGE_SIZE) 646 return ret; 647 648 /* non-sleeping allocations are not supported by vmalloc */ 649 if (!gfpflags_allow_blocking(flags)) 650 return NULL; 651 652 /* Don't even allow crazy sizes */ 653 if (unlikely(size > INT_MAX)) { 654 WARN_ON_ONCE(!(flags & __GFP_NOWARN)); 655 return NULL; 656 } 657 658 /* 659 * kvmalloc() can always use VM_ALLOW_HUGE_VMAP, 660 * since the callers already cannot assume anything 661 * about the resulting pointer, and cannot play 662 * protection games. 663 */ 664 return __vmalloc_node_range_noprof(size, 1, VMALLOC_START, VMALLOC_END, 665 flags, PAGE_KERNEL, VM_ALLOW_HUGE_VMAP, 666 node, __builtin_return_address(0)); 667 } 668 EXPORT_SYMBOL(kvmalloc_node_noprof); 669 670 /** 671 * kvfree() - Free memory. 672 * @addr: Pointer to allocated memory. 673 * 674 * kvfree frees memory allocated by any of vmalloc(), kmalloc() or kvmalloc(). 675 * It is slightly more efficient to use kfree() or vfree() if you are certain 676 * that you know which one to use. 677 * 678 * Context: Either preemptible task context or not-NMI interrupt. 679 */ 680 void kvfree(const void *addr) 681 { 682 if (is_vmalloc_addr(addr)) 683 vfree(addr); 684 else 685 kfree(addr); 686 } 687 EXPORT_SYMBOL(kvfree); 688 689 /** 690 * kvfree_sensitive - Free a data object containing sensitive information. 691 * @addr: address of the data object to be freed. 692 * @len: length of the data object. 693 * 694 * Use the special memzero_explicit() function to clear the content of a 695 * kvmalloc'ed object containing sensitive data to make sure that the 696 * compiler won't optimize out the data clearing. 697 */ 698 void kvfree_sensitive(const void *addr, size_t len) 699 { 700 if (likely(!ZERO_OR_NULL_PTR(addr))) { 701 memzero_explicit((void *)addr, len); 702 kvfree(addr); 703 } 704 } 705 EXPORT_SYMBOL(kvfree_sensitive); 706 707 void *kvrealloc_noprof(const void *p, size_t oldsize, size_t newsize, gfp_t flags) 708 { 709 void *newp; 710 711 if (oldsize >= newsize) 712 return (void *)p; 713 newp = kvmalloc(newsize, flags); 714 if (!newp) 715 return NULL; 716 memcpy(newp, p, oldsize); 717 kvfree(p); 718 return newp; 719 } 720 EXPORT_SYMBOL(kvrealloc_noprof); 721 722 /** 723 * __vmalloc_array - allocate memory for a virtually contiguous array. 724 * @n: number of elements. 725 * @size: element size. 726 * @flags: the type of memory to allocate (see kmalloc). 727 */ 728 void *__vmalloc_array_noprof(size_t n, size_t size, gfp_t flags) 729 { 730 size_t bytes; 731 732 if (unlikely(check_mul_overflow(n, size, &bytes))) 733 return NULL; 734 return __vmalloc(bytes, flags); 735 } 736 EXPORT_SYMBOL(__vmalloc_array_noprof); 737 738 /** 739 * vmalloc_array - allocate memory for a virtually contiguous array. 740 * @n: number of elements. 741 * @size: element size. 742 */ 743 void *vmalloc_array_noprof(size_t n, size_t size) 744 { 745 return __vmalloc_array(n, size, GFP_KERNEL); 746 } 747 EXPORT_SYMBOL(vmalloc_array_noprof); 748 749 /** 750 * __vcalloc - allocate and zero memory for a virtually contiguous array. 751 * @n: number of elements. 752 * @size: element size. 753 * @flags: the type of memory to allocate (see kmalloc). 754 */ 755 void *__vcalloc_noprof(size_t n, size_t size, gfp_t flags) 756 { 757 return __vmalloc_array(n, size, flags | __GFP_ZERO); 758 } 759 EXPORT_SYMBOL(__vcalloc_noprof); 760 761 /** 762 * vcalloc - allocate and zero memory for a virtually contiguous array. 763 * @n: number of elements. 764 * @size: element size. 765 */ 766 void *vcalloc_noprof(size_t n, size_t size) 767 { 768 return __vmalloc_array(n, size, GFP_KERNEL | __GFP_ZERO); 769 } 770 EXPORT_SYMBOL(vcalloc_noprof); 771 772 struct anon_vma *folio_anon_vma(struct folio *folio) 773 { 774 unsigned long mapping = (unsigned long)folio->mapping; 775 776 if ((mapping & PAGE_MAPPING_FLAGS) != PAGE_MAPPING_ANON) 777 return NULL; 778 return (void *)(mapping - PAGE_MAPPING_ANON); 779 } 780 781 /** 782 * folio_mapping - Find the mapping where this folio is stored. 783 * @folio: The folio. 784 * 785 * For folios which are in the page cache, return the mapping that this 786 * page belongs to. Folios in the swap cache return the swap mapping 787 * this page is stored in (which is different from the mapping for the 788 * swap file or swap device where the data is stored). 789 * 790 * You can call this for folios which aren't in the swap cache or page 791 * cache and it will return NULL. 792 */ 793 struct address_space *folio_mapping(struct folio *folio) 794 { 795 struct address_space *mapping; 796 797 /* This happens if someone calls flush_dcache_page on slab page */ 798 if (unlikely(folio_test_slab(folio))) 799 return NULL; 800 801 if (unlikely(folio_test_swapcache(folio))) 802 return swap_address_space(folio->swap); 803 804 mapping = folio->mapping; 805 if ((unsigned long)mapping & PAGE_MAPPING_FLAGS) 806 return NULL; 807 808 return mapping; 809 } 810 EXPORT_SYMBOL(folio_mapping); 811 812 /** 813 * folio_copy - Copy the contents of one folio to another. 814 * @dst: Folio to copy to. 815 * @src: Folio to copy from. 816 * 817 * The bytes in the folio represented by @src are copied to @dst. 818 * Assumes the caller has validated that @dst is at least as large as @src. 819 * Can be called in atomic context for order-0 folios, but if the folio is 820 * larger, it may sleep. 821 */ 822 void folio_copy(struct folio *dst, struct folio *src) 823 { 824 long i = 0; 825 long nr = folio_nr_pages(src); 826 827 for (;;) { 828 copy_highpage(folio_page(dst, i), folio_page(src, i)); 829 if (++i == nr) 830 break; 831 cond_resched(); 832 } 833 } 834 EXPORT_SYMBOL(folio_copy); 835 836 int sysctl_overcommit_memory __read_mostly = OVERCOMMIT_GUESS; 837 int sysctl_overcommit_ratio __read_mostly = 50; 838 unsigned long sysctl_overcommit_kbytes __read_mostly; 839 int sysctl_max_map_count __read_mostly = DEFAULT_MAX_MAP_COUNT; 840 unsigned long sysctl_user_reserve_kbytes __read_mostly = 1UL << 17; /* 128MB */ 841 unsigned long sysctl_admin_reserve_kbytes __read_mostly = 1UL << 13; /* 8MB */ 842 843 int overcommit_ratio_handler(struct ctl_table *table, int write, void *buffer, 844 size_t *lenp, loff_t *ppos) 845 { 846 int ret; 847 848 ret = proc_dointvec(table, write, buffer, lenp, ppos); 849 if (ret == 0 && write) 850 sysctl_overcommit_kbytes = 0; 851 return ret; 852 } 853 854 static void sync_overcommit_as(struct work_struct *dummy) 855 { 856 percpu_counter_sync(&vm_committed_as); 857 } 858 859 int overcommit_policy_handler(struct ctl_table *table, int write, void *buffer, 860 size_t *lenp, loff_t *ppos) 861 { 862 struct ctl_table t; 863 int new_policy = -1; 864 int ret; 865 866 /* 867 * The deviation of sync_overcommit_as could be big with loose policy 868 * like OVERCOMMIT_ALWAYS/OVERCOMMIT_GUESS. When changing policy to 869 * strict OVERCOMMIT_NEVER, we need to reduce the deviation to comply 870 * with the strict "NEVER", and to avoid possible race condition (even 871 * though user usually won't too frequently do the switching to policy 872 * OVERCOMMIT_NEVER), the switch is done in the following order: 873 * 1. changing the batch 874 * 2. sync percpu count on each CPU 875 * 3. switch the policy 876 */ 877 if (write) { 878 t = *table; 879 t.data = &new_policy; 880 ret = proc_dointvec_minmax(&t, write, buffer, lenp, ppos); 881 if (ret || new_policy == -1) 882 return ret; 883 884 mm_compute_batch(new_policy); 885 if (new_policy == OVERCOMMIT_NEVER) 886 schedule_on_each_cpu(sync_overcommit_as); 887 sysctl_overcommit_memory = new_policy; 888 } else { 889 ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos); 890 } 891 892 return ret; 893 } 894 895 int overcommit_kbytes_handler(struct ctl_table *table, int write, void *buffer, 896 size_t *lenp, loff_t *ppos) 897 { 898 int ret; 899 900 ret = proc_doulongvec_minmax(table, write, buffer, lenp, ppos); 901 if (ret == 0 && write) 902 sysctl_overcommit_ratio = 0; 903 return ret; 904 } 905 906 /* 907 * Committed memory limit enforced when OVERCOMMIT_NEVER policy is used 908 */ 909 unsigned long vm_commit_limit(void) 910 { 911 unsigned long allowed; 912 913 if (sysctl_overcommit_kbytes) 914 allowed = sysctl_overcommit_kbytes >> (PAGE_SHIFT - 10); 915 else 916 allowed = ((totalram_pages() - hugetlb_total_pages()) 917 * sysctl_overcommit_ratio / 100); 918 allowed += total_swap_pages; 919 920 return allowed; 921 } 922 923 /* 924 * Make sure vm_committed_as in one cacheline and not cacheline shared with 925 * other variables. It can be updated by several CPUs frequently. 926 */ 927 struct percpu_counter vm_committed_as ____cacheline_aligned_in_smp; 928 929 /* 930 * The global memory commitment made in the system can be a metric 931 * that can be used to drive ballooning decisions when Linux is hosted 932 * as a guest. On Hyper-V, the host implements a policy engine for dynamically 933 * balancing memory across competing virtual machines that are hosted. 934 * Several metrics drive this policy engine including the guest reported 935 * memory commitment. 936 * 937 * The time cost of this is very low for small platforms, and for big 938 * platform like a 2S/36C/72T Skylake server, in worst case where 939 * vm_committed_as's spinlock is under severe contention, the time cost 940 * could be about 30~40 microseconds. 941 */ 942 unsigned long vm_memory_committed(void) 943 { 944 return percpu_counter_sum_positive(&vm_committed_as); 945 } 946 EXPORT_SYMBOL_GPL(vm_memory_committed); 947 948 /* 949 * Check that a process has enough memory to allocate a new virtual 950 * mapping. 0 means there is enough memory for the allocation to 951 * succeed and -ENOMEM implies there is not. 952 * 953 * We currently support three overcommit policies, which are set via the 954 * vm.overcommit_memory sysctl. See Documentation/mm/overcommit-accounting.rst 955 * 956 * Strict overcommit modes added 2002 Feb 26 by Alan Cox. 957 * Additional code 2002 Jul 20 by Robert Love. 958 * 959 * cap_sys_admin is 1 if the process has admin privileges, 0 otherwise. 960 * 961 * Note this is a helper function intended to be used by LSMs which 962 * wish to use this logic. 963 */ 964 int __vm_enough_memory(struct mm_struct *mm, long pages, int cap_sys_admin) 965 { 966 long allowed; 967 unsigned long bytes_failed; 968 969 vm_acct_memory(pages); 970 971 /* 972 * Sometimes we want to use more memory than we have 973 */ 974 if (sysctl_overcommit_memory == OVERCOMMIT_ALWAYS) 975 return 0; 976 977 if (sysctl_overcommit_memory == OVERCOMMIT_GUESS) { 978 if (pages > totalram_pages() + total_swap_pages) 979 goto error; 980 return 0; 981 } 982 983 allowed = vm_commit_limit(); 984 /* 985 * Reserve some for root 986 */ 987 if (!cap_sys_admin) 988 allowed -= sysctl_admin_reserve_kbytes >> (PAGE_SHIFT - 10); 989 990 /* 991 * Don't let a single process grow so big a user can't recover 992 */ 993 if (mm) { 994 long reserve = sysctl_user_reserve_kbytes >> (PAGE_SHIFT - 10); 995 996 allowed -= min_t(long, mm->total_vm / 32, reserve); 997 } 998 999 if (percpu_counter_read_positive(&vm_committed_as) < allowed) 1000 return 0; 1001 error: 1002 bytes_failed = pages << PAGE_SHIFT; 1003 pr_warn_ratelimited("%s: pid: %d, comm: %s, bytes: %lu not enough memory for the allocation\n", 1004 __func__, current->pid, current->comm, bytes_failed); 1005 vm_unacct_memory(pages); 1006 1007 return -ENOMEM; 1008 } 1009 1010 /** 1011 * get_cmdline() - copy the cmdline value to a buffer. 1012 * @task: the task whose cmdline value to copy. 1013 * @buffer: the buffer to copy to. 1014 * @buflen: the length of the buffer. Larger cmdline values are truncated 1015 * to this length. 1016 * 1017 * Return: the size of the cmdline field copied. Note that the copy does 1018 * not guarantee an ending NULL byte. 1019 */ 1020 int get_cmdline(struct task_struct *task, char *buffer, int buflen) 1021 { 1022 int res = 0; 1023 unsigned int len; 1024 struct mm_struct *mm = get_task_mm(task); 1025 unsigned long arg_start, arg_end, env_start, env_end; 1026 if (!mm) 1027 goto out; 1028 if (!mm->arg_end) 1029 goto out_mm; /* Shh! No looking before we're done */ 1030 1031 spin_lock(&mm->arg_lock); 1032 arg_start = mm->arg_start; 1033 arg_end = mm->arg_end; 1034 env_start = mm->env_start; 1035 env_end = mm->env_end; 1036 spin_unlock(&mm->arg_lock); 1037 1038 len = arg_end - arg_start; 1039 1040 if (len > buflen) 1041 len = buflen; 1042 1043 res = access_process_vm(task, arg_start, buffer, len, FOLL_FORCE); 1044 1045 /* 1046 * If the nul at the end of args has been overwritten, then 1047 * assume application is using setproctitle(3). 1048 */ 1049 if (res > 0 && buffer[res-1] != '\0' && len < buflen) { 1050 len = strnlen(buffer, res); 1051 if (len < res) { 1052 res = len; 1053 } else { 1054 len = env_end - env_start; 1055 if (len > buflen - res) 1056 len = buflen - res; 1057 res += access_process_vm(task, env_start, 1058 buffer+res, len, 1059 FOLL_FORCE); 1060 res = strnlen(buffer, res); 1061 } 1062 } 1063 out_mm: 1064 mmput(mm); 1065 out: 1066 return res; 1067 } 1068 1069 int __weak memcmp_pages(struct page *page1, struct page *page2) 1070 { 1071 char *addr1, *addr2; 1072 int ret; 1073 1074 addr1 = kmap_local_page(page1); 1075 addr2 = kmap_local_page(page2); 1076 ret = memcmp(addr1, addr2, PAGE_SIZE); 1077 kunmap_local(addr2); 1078 kunmap_local(addr1); 1079 return ret; 1080 } 1081 1082 #ifdef CONFIG_PRINTK 1083 /** 1084 * mem_dump_obj - Print available provenance information 1085 * @object: object for which to find provenance information. 1086 * 1087 * This function uses pr_cont(), so that the caller is expected to have 1088 * printed out whatever preamble is appropriate. The provenance information 1089 * depends on the type of object and on how much debugging is enabled. 1090 * For example, for a slab-cache object, the slab name is printed, and, 1091 * if available, the return address and stack trace from the allocation 1092 * and last free path of that object. 1093 */ 1094 void mem_dump_obj(void *object) 1095 { 1096 const char *type; 1097 1098 if (kmem_dump_obj(object)) 1099 return; 1100 1101 if (vmalloc_dump_obj(object)) 1102 return; 1103 1104 if (is_vmalloc_addr(object)) 1105 type = "vmalloc memory"; 1106 else if (virt_addr_valid(object)) 1107 type = "non-slab/vmalloc memory"; 1108 else if (object == NULL) 1109 type = "NULL pointer"; 1110 else if (object == ZERO_SIZE_PTR) 1111 type = "zero-size pointer"; 1112 else 1113 type = "non-paged memory"; 1114 1115 pr_cont(" %s\n", type); 1116 } 1117 EXPORT_SYMBOL_GPL(mem_dump_obj); 1118 #endif 1119 1120 /* 1121 * A driver might set a page logically offline -- PageOffline() -- and 1122 * turn the page inaccessible in the hypervisor; after that, access to page 1123 * content can be fatal. 1124 * 1125 * Some special PFN walkers -- i.e., /proc/kcore -- read content of random 1126 * pages after checking PageOffline(); however, these PFN walkers can race 1127 * with drivers that set PageOffline(). 1128 * 1129 * page_offline_freeze()/page_offline_thaw() allows for a subsystem to 1130 * synchronize with such drivers, achieving that a page cannot be set 1131 * PageOffline() while frozen. 1132 * 1133 * page_offline_begin()/page_offline_end() is used by drivers that care about 1134 * such races when setting a page PageOffline(). 1135 */ 1136 static DECLARE_RWSEM(page_offline_rwsem); 1137 1138 void page_offline_freeze(void) 1139 { 1140 down_read(&page_offline_rwsem); 1141 } 1142 1143 void page_offline_thaw(void) 1144 { 1145 up_read(&page_offline_rwsem); 1146 } 1147 1148 void page_offline_begin(void) 1149 { 1150 down_write(&page_offline_rwsem); 1151 } 1152 EXPORT_SYMBOL(page_offline_begin); 1153 1154 void page_offline_end(void) 1155 { 1156 up_write(&page_offline_rwsem); 1157 } 1158 EXPORT_SYMBOL(page_offline_end); 1159 1160 #ifndef flush_dcache_folio 1161 void flush_dcache_folio(struct folio *folio) 1162 { 1163 long i, nr = folio_nr_pages(folio); 1164 1165 for (i = 0; i < nr; i++) 1166 flush_dcache_page(folio_page(folio, i)); 1167 } 1168 EXPORT_SYMBOL(flush_dcache_folio); 1169 #endif 1170